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
;
65 /* for remember boot option*/
66 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP_ENABLED
67 static int really_do_swap_account __initdata
= 1;
69 static int really_do_swap_account __initdata
= 0;
73 #define do_swap_account (0)
78 * Statistics for memory cgroup.
80 enum mem_cgroup_stat_index
{
82 * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
84 MEM_CGROUP_STAT_CACHE
, /* # of pages charged as cache */
85 MEM_CGROUP_STAT_RSS
, /* # of pages charged as anon rss */
86 MEM_CGROUP_STAT_FILE_MAPPED
, /* # of pages charged as file rss */
87 MEM_CGROUP_STAT_SWAPOUT
, /* # of pages, swapped out */
88 MEM_CGROUP_STAT_DATA
, /* end of data requires synchronization */
89 MEM_CGROUP_ON_MOVE
, /* someone is moving account between groups */
90 MEM_CGROUP_STAT_NSTATS
,
93 enum mem_cgroup_events_index
{
94 MEM_CGROUP_EVENTS_PGPGIN
, /* # of pages paged in */
95 MEM_CGROUP_EVENTS_PGPGOUT
, /* # of pages paged out */
96 MEM_CGROUP_EVENTS_COUNT
, /* # of pages paged in/out */
97 MEM_CGROUP_EVENTS_NSTATS
,
100 * Per memcg event counter is incremented at every pagein/pageout. With THP,
101 * it will be incremated by the number of pages. This counter is used for
102 * for trigger some periodic events. This is straightforward and better
103 * than using jiffies etc. to handle periodic memcg event.
105 enum mem_cgroup_events_target
{
106 MEM_CGROUP_TARGET_THRESH
,
107 MEM_CGROUP_TARGET_SOFTLIMIT
,
110 #define THRESHOLDS_EVENTS_TARGET (128)
111 #define SOFTLIMIT_EVENTS_TARGET (1024)
113 struct mem_cgroup_stat_cpu
{
114 long count
[MEM_CGROUP_STAT_NSTATS
];
115 unsigned long events
[MEM_CGROUP_EVENTS_NSTATS
];
116 unsigned long targets
[MEM_CGROUP_NTARGETS
];
120 * per-zone information in memory controller.
122 struct mem_cgroup_per_zone
{
124 * spin_lock to protect the per cgroup LRU
126 struct list_head lists
[NR_LRU_LISTS
];
127 unsigned long count
[NR_LRU_LISTS
];
129 struct zone_reclaim_stat reclaim_stat
;
130 struct rb_node tree_node
; /* RB tree node */
131 unsigned long long usage_in_excess
;/* Set to the value by which */
132 /* the soft limit is exceeded*/
134 struct mem_cgroup
*mem
; /* Back pointer, we cannot */
135 /* use container_of */
137 /* Macro for accessing counter */
138 #define MEM_CGROUP_ZSTAT(mz, idx) ((mz)->count[(idx)])
140 struct mem_cgroup_per_node
{
141 struct mem_cgroup_per_zone zoneinfo
[MAX_NR_ZONES
];
144 struct mem_cgroup_lru_info
{
145 struct mem_cgroup_per_node
*nodeinfo
[MAX_NUMNODES
];
149 * Cgroups above their limits are maintained in a RB-Tree, independent of
150 * their hierarchy representation
153 struct mem_cgroup_tree_per_zone
{
154 struct rb_root rb_root
;
158 struct mem_cgroup_tree_per_node
{
159 struct mem_cgroup_tree_per_zone rb_tree_per_zone
[MAX_NR_ZONES
];
162 struct mem_cgroup_tree
{
163 struct mem_cgroup_tree_per_node
*rb_tree_per_node
[MAX_NUMNODES
];
166 static struct mem_cgroup_tree soft_limit_tree __read_mostly
;
168 struct mem_cgroup_threshold
{
169 struct eventfd_ctx
*eventfd
;
174 struct mem_cgroup_threshold_ary
{
175 /* An array index points to threshold just below usage. */
176 int current_threshold
;
177 /* Size of entries[] */
179 /* Array of thresholds */
180 struct mem_cgroup_threshold entries
[0];
183 struct mem_cgroup_thresholds
{
184 /* Primary thresholds array */
185 struct mem_cgroup_threshold_ary
*primary
;
187 * Spare threshold array.
188 * This is needed to make mem_cgroup_unregister_event() "never fail".
189 * It must be able to store at least primary->size - 1 entries.
191 struct mem_cgroup_threshold_ary
*spare
;
195 struct mem_cgroup_eventfd_list
{
196 struct list_head list
;
197 struct eventfd_ctx
*eventfd
;
200 static void mem_cgroup_threshold(struct mem_cgroup
*mem
);
201 static void mem_cgroup_oom_notify(struct mem_cgroup
*mem
);
204 * The memory controller data structure. The memory controller controls both
205 * page cache and RSS per cgroup. We would eventually like to provide
206 * statistics based on the statistics developed by Rik Van Riel for clock-pro,
207 * to help the administrator determine what knobs to tune.
209 * TODO: Add a water mark for the memory controller. Reclaim will begin when
210 * we hit the water mark. May be even add a low water mark, such that
211 * no reclaim occurs from a cgroup at it's low water mark, this is
212 * a feature that will be implemented much later in the future.
215 struct cgroup_subsys_state css
;
217 * the counter to account for memory usage
219 struct res_counter res
;
221 * the counter to account for mem+swap usage.
223 struct res_counter memsw
;
225 * Per cgroup active and inactive list, similar to the
226 * per zone LRU lists.
228 struct mem_cgroup_lru_info info
;
230 * While reclaiming in a hierarchy, we cache the last child we
233 int last_scanned_child
;
234 int last_scanned_node
;
236 nodemask_t scan_nodes
;
237 unsigned long next_scan_node_update
;
240 * Should the accounting and control be hierarchical, per subtree?
246 unsigned int swappiness
;
247 /* OOM-Killer disable */
248 int oom_kill_disable
;
250 /* set when res.limit == memsw.limit */
251 bool memsw_is_minimum
;
253 /* protect arrays of thresholds */
254 struct mutex thresholds_lock
;
256 /* thresholds for memory usage. RCU-protected */
257 struct mem_cgroup_thresholds thresholds
;
259 /* thresholds for mem+swap usage. RCU-protected */
260 struct mem_cgroup_thresholds memsw_thresholds
;
262 /* For oom notifier event fd */
263 struct list_head oom_notify
;
266 * Should we move charges of a task when a task is moved into this
267 * mem_cgroup ? And what type of charges should we move ?
269 unsigned long move_charge_at_immigrate
;
273 struct mem_cgroup_stat_cpu
*stat
;
275 * used when a cpu is offlined or other synchronizations
276 * See mem_cgroup_read_stat().
278 struct mem_cgroup_stat_cpu nocpu_base
;
279 spinlock_t pcp_counter_lock
;
282 /* Stuffs for move charges at task migration. */
284 * Types of charges to be moved. "move_charge_at_immitgrate" is treated as a
285 * left-shifted bitmap of these types.
288 MOVE_CHARGE_TYPE_ANON
, /* private anonymous page and swap of it */
289 MOVE_CHARGE_TYPE_FILE
, /* file page(including tmpfs) and swap of it */
293 /* "mc" and its members are protected by cgroup_mutex */
294 static struct move_charge_struct
{
295 spinlock_t lock
; /* for from, to */
296 struct mem_cgroup
*from
;
297 struct mem_cgroup
*to
;
298 unsigned long precharge
;
299 unsigned long moved_charge
;
300 unsigned long moved_swap
;
301 struct task_struct
*moving_task
; /* a task moving charges */
302 wait_queue_head_t waitq
; /* a waitq for other context */
304 .lock
= __SPIN_LOCK_UNLOCKED(mc
.lock
),
305 .waitq
= __WAIT_QUEUE_HEAD_INITIALIZER(mc
.waitq
),
308 static bool move_anon(void)
310 return test_bit(MOVE_CHARGE_TYPE_ANON
,
311 &mc
.to
->move_charge_at_immigrate
);
314 static bool move_file(void)
316 return test_bit(MOVE_CHARGE_TYPE_FILE
,
317 &mc
.to
->move_charge_at_immigrate
);
321 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
322 * limit reclaim to prevent infinite loops, if they ever occur.
324 #define MEM_CGROUP_MAX_RECLAIM_LOOPS (100)
325 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS (2)
328 MEM_CGROUP_CHARGE_TYPE_CACHE
= 0,
329 MEM_CGROUP_CHARGE_TYPE_MAPPED
,
330 MEM_CGROUP_CHARGE_TYPE_SHMEM
, /* used by page migration of shmem */
331 MEM_CGROUP_CHARGE_TYPE_FORCE
, /* used by force_empty */
332 MEM_CGROUP_CHARGE_TYPE_SWAPOUT
, /* for accounting swapcache */
333 MEM_CGROUP_CHARGE_TYPE_DROP
, /* a page was unused swap cache */
337 /* for encoding cft->private value on file */
340 #define _OOM_TYPE (2)
341 #define MEMFILE_PRIVATE(x, val) (((x) << 16) | (val))
342 #define MEMFILE_TYPE(val) (((val) >> 16) & 0xffff)
343 #define MEMFILE_ATTR(val) ((val) & 0xffff)
344 /* Used for OOM nofiier */
345 #define OOM_CONTROL (0)
348 * Reclaim flags for mem_cgroup_hierarchical_reclaim
350 #define MEM_CGROUP_RECLAIM_NOSWAP_BIT 0x0
351 #define MEM_CGROUP_RECLAIM_NOSWAP (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
352 #define MEM_CGROUP_RECLAIM_SHRINK_BIT 0x1
353 #define MEM_CGROUP_RECLAIM_SHRINK (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
354 #define MEM_CGROUP_RECLAIM_SOFT_BIT 0x2
355 #define MEM_CGROUP_RECLAIM_SOFT (1 << MEM_CGROUP_RECLAIM_SOFT_BIT)
357 static void mem_cgroup_get(struct mem_cgroup
*mem
);
358 static void mem_cgroup_put(struct mem_cgroup
*mem
);
359 static struct mem_cgroup
*parent_mem_cgroup(struct mem_cgroup
*mem
);
360 static void drain_all_stock_async(void);
362 static struct mem_cgroup_per_zone
*
363 mem_cgroup_zoneinfo(struct mem_cgroup
*mem
, int nid
, int zid
)
365 return &mem
->info
.nodeinfo
[nid
]->zoneinfo
[zid
];
368 struct cgroup_subsys_state
*mem_cgroup_css(struct mem_cgroup
*mem
)
373 static struct mem_cgroup_per_zone
*
374 page_cgroup_zoneinfo(struct mem_cgroup
*mem
, struct page
*page
)
376 int nid
= page_to_nid(page
);
377 int zid
= page_zonenum(page
);
379 return mem_cgroup_zoneinfo(mem
, nid
, zid
);
382 static struct mem_cgroup_tree_per_zone
*
383 soft_limit_tree_node_zone(int nid
, int zid
)
385 return &soft_limit_tree
.rb_tree_per_node
[nid
]->rb_tree_per_zone
[zid
];
388 static struct mem_cgroup_tree_per_zone
*
389 soft_limit_tree_from_page(struct page
*page
)
391 int nid
= page_to_nid(page
);
392 int zid
= page_zonenum(page
);
394 return &soft_limit_tree
.rb_tree_per_node
[nid
]->rb_tree_per_zone
[zid
];
398 __mem_cgroup_insert_exceeded(struct mem_cgroup
*mem
,
399 struct mem_cgroup_per_zone
*mz
,
400 struct mem_cgroup_tree_per_zone
*mctz
,
401 unsigned long long new_usage_in_excess
)
403 struct rb_node
**p
= &mctz
->rb_root
.rb_node
;
404 struct rb_node
*parent
= NULL
;
405 struct mem_cgroup_per_zone
*mz_node
;
410 mz
->usage_in_excess
= new_usage_in_excess
;
411 if (!mz
->usage_in_excess
)
415 mz_node
= rb_entry(parent
, struct mem_cgroup_per_zone
,
417 if (mz
->usage_in_excess
< mz_node
->usage_in_excess
)
420 * We can't avoid mem cgroups that are over their soft
421 * limit by the same amount
423 else if (mz
->usage_in_excess
>= mz_node
->usage_in_excess
)
426 rb_link_node(&mz
->tree_node
, parent
, p
);
427 rb_insert_color(&mz
->tree_node
, &mctz
->rb_root
);
432 __mem_cgroup_remove_exceeded(struct mem_cgroup
*mem
,
433 struct mem_cgroup_per_zone
*mz
,
434 struct mem_cgroup_tree_per_zone
*mctz
)
438 rb_erase(&mz
->tree_node
, &mctz
->rb_root
);
443 mem_cgroup_remove_exceeded(struct mem_cgroup
*mem
,
444 struct mem_cgroup_per_zone
*mz
,
445 struct mem_cgroup_tree_per_zone
*mctz
)
447 spin_lock(&mctz
->lock
);
448 __mem_cgroup_remove_exceeded(mem
, mz
, mctz
);
449 spin_unlock(&mctz
->lock
);
453 static void mem_cgroup_update_tree(struct mem_cgroup
*mem
, struct page
*page
)
455 unsigned long long excess
;
456 struct mem_cgroup_per_zone
*mz
;
457 struct mem_cgroup_tree_per_zone
*mctz
;
458 int nid
= page_to_nid(page
);
459 int zid
= page_zonenum(page
);
460 mctz
= soft_limit_tree_from_page(page
);
463 * Necessary to update all ancestors when hierarchy is used.
464 * because their event counter is not touched.
466 for (; mem
; mem
= parent_mem_cgroup(mem
)) {
467 mz
= mem_cgroup_zoneinfo(mem
, nid
, zid
);
468 excess
= res_counter_soft_limit_excess(&mem
->res
);
470 * We have to update the tree if mz is on RB-tree or
471 * mem is over its softlimit.
473 if (excess
|| mz
->on_tree
) {
474 spin_lock(&mctz
->lock
);
475 /* if on-tree, remove it */
477 __mem_cgroup_remove_exceeded(mem
, mz
, mctz
);
479 * Insert again. mz->usage_in_excess will be updated.
480 * If excess is 0, no tree ops.
482 __mem_cgroup_insert_exceeded(mem
, mz
, mctz
, excess
);
483 spin_unlock(&mctz
->lock
);
488 static void mem_cgroup_remove_from_trees(struct mem_cgroup
*mem
)
491 struct mem_cgroup_per_zone
*mz
;
492 struct mem_cgroup_tree_per_zone
*mctz
;
494 for_each_node_state(node
, N_POSSIBLE
) {
495 for (zone
= 0; zone
< MAX_NR_ZONES
; zone
++) {
496 mz
= mem_cgroup_zoneinfo(mem
, node
, zone
);
497 mctz
= soft_limit_tree_node_zone(node
, zone
);
498 mem_cgroup_remove_exceeded(mem
, mz
, mctz
);
503 static struct mem_cgroup_per_zone
*
504 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone
*mctz
)
506 struct rb_node
*rightmost
= NULL
;
507 struct mem_cgroup_per_zone
*mz
;
511 rightmost
= rb_last(&mctz
->rb_root
);
513 goto done
; /* Nothing to reclaim from */
515 mz
= rb_entry(rightmost
, struct mem_cgroup_per_zone
, tree_node
);
517 * Remove the node now but someone else can add it back,
518 * we will to add it back at the end of reclaim to its correct
519 * position in the tree.
521 __mem_cgroup_remove_exceeded(mz
->mem
, mz
, mctz
);
522 if (!res_counter_soft_limit_excess(&mz
->mem
->res
) ||
523 !css_tryget(&mz
->mem
->css
))
529 static struct mem_cgroup_per_zone
*
530 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone
*mctz
)
532 struct mem_cgroup_per_zone
*mz
;
534 spin_lock(&mctz
->lock
);
535 mz
= __mem_cgroup_largest_soft_limit_node(mctz
);
536 spin_unlock(&mctz
->lock
);
541 * Implementation Note: reading percpu statistics for memcg.
543 * Both of vmstat[] and percpu_counter has threshold and do periodic
544 * synchronization to implement "quick" read. There are trade-off between
545 * reading cost and precision of value. Then, we may have a chance to implement
546 * a periodic synchronizion of counter in memcg's counter.
548 * But this _read() function is used for user interface now. The user accounts
549 * memory usage by memory cgroup and he _always_ requires exact value because
550 * he accounts memory. Even if we provide quick-and-fuzzy read, we always
551 * have to visit all online cpus and make sum. So, for now, unnecessary
552 * synchronization is not implemented. (just implemented for cpu hotplug)
554 * If there are kernel internal actions which can make use of some not-exact
555 * value, and reading all cpu value can be performance bottleneck in some
556 * common workload, threashold and synchonization as vmstat[] should be
559 static long mem_cgroup_read_stat(struct mem_cgroup
*mem
,
560 enum mem_cgroup_stat_index idx
)
566 for_each_online_cpu(cpu
)
567 val
+= per_cpu(mem
->stat
->count
[idx
], cpu
);
568 #ifdef CONFIG_HOTPLUG_CPU
569 spin_lock(&mem
->pcp_counter_lock
);
570 val
+= mem
->nocpu_base
.count
[idx
];
571 spin_unlock(&mem
->pcp_counter_lock
);
577 static long mem_cgroup_local_usage(struct mem_cgroup
*mem
)
581 ret
= mem_cgroup_read_stat(mem
, MEM_CGROUP_STAT_RSS
);
582 ret
+= mem_cgroup_read_stat(mem
, MEM_CGROUP_STAT_CACHE
);
586 static void mem_cgroup_swap_statistics(struct mem_cgroup
*mem
,
589 int val
= (charge
) ? 1 : -1;
590 this_cpu_add(mem
->stat
->count
[MEM_CGROUP_STAT_SWAPOUT
], val
);
593 static unsigned long mem_cgroup_read_events(struct mem_cgroup
*mem
,
594 enum mem_cgroup_events_index idx
)
596 unsigned long val
= 0;
599 for_each_online_cpu(cpu
)
600 val
+= per_cpu(mem
->stat
->events
[idx
], cpu
);
601 #ifdef CONFIG_HOTPLUG_CPU
602 spin_lock(&mem
->pcp_counter_lock
);
603 val
+= mem
->nocpu_base
.events
[idx
];
604 spin_unlock(&mem
->pcp_counter_lock
);
609 static void mem_cgroup_charge_statistics(struct mem_cgroup
*mem
,
610 bool file
, int nr_pages
)
615 __this_cpu_add(mem
->stat
->count
[MEM_CGROUP_STAT_CACHE
], nr_pages
);
617 __this_cpu_add(mem
->stat
->count
[MEM_CGROUP_STAT_RSS
], nr_pages
);
619 /* pagein of a big page is an event. So, ignore page size */
621 __this_cpu_inc(mem
->stat
->events
[MEM_CGROUP_EVENTS_PGPGIN
]);
623 __this_cpu_inc(mem
->stat
->events
[MEM_CGROUP_EVENTS_PGPGOUT
]);
624 nr_pages
= -nr_pages
; /* for event */
627 __this_cpu_add(mem
->stat
->events
[MEM_CGROUP_EVENTS_COUNT
], nr_pages
);
633 mem_cgroup_get_zonestat_node(struct mem_cgroup
*mem
, int nid
, enum lru_list idx
)
635 struct mem_cgroup_per_zone
*mz
;
639 for (zid
= 0; zid
< MAX_NR_ZONES
; zid
++) {
640 mz
= mem_cgroup_zoneinfo(mem
, nid
, zid
);
641 total
+= MEM_CGROUP_ZSTAT(mz
, idx
);
645 static unsigned long mem_cgroup_get_local_zonestat(struct mem_cgroup
*mem
,
651 for_each_online_node(nid
)
652 total
+= mem_cgroup_get_zonestat_node(mem
, nid
, idx
);
656 static bool __memcg_event_check(struct mem_cgroup
*mem
, int target
)
658 unsigned long val
, next
;
660 val
= this_cpu_read(mem
->stat
->events
[MEM_CGROUP_EVENTS_COUNT
]);
661 next
= this_cpu_read(mem
->stat
->targets
[target
]);
662 /* from time_after() in jiffies.h */
663 return ((long)next
- (long)val
< 0);
666 static void __mem_cgroup_target_update(struct mem_cgroup
*mem
, int target
)
668 unsigned long val
, next
;
670 val
= this_cpu_read(mem
->stat
->events
[MEM_CGROUP_EVENTS_COUNT
]);
673 case MEM_CGROUP_TARGET_THRESH
:
674 next
= val
+ THRESHOLDS_EVENTS_TARGET
;
676 case MEM_CGROUP_TARGET_SOFTLIMIT
:
677 next
= val
+ SOFTLIMIT_EVENTS_TARGET
;
683 this_cpu_write(mem
->stat
->targets
[target
], next
);
687 * Check events in order.
690 static void memcg_check_events(struct mem_cgroup
*mem
, struct page
*page
)
692 /* threshold event is triggered in finer grain than soft limit */
693 if (unlikely(__memcg_event_check(mem
, MEM_CGROUP_TARGET_THRESH
))) {
694 mem_cgroup_threshold(mem
);
695 __mem_cgroup_target_update(mem
, MEM_CGROUP_TARGET_THRESH
);
696 if (unlikely(__memcg_event_check(mem
,
697 MEM_CGROUP_TARGET_SOFTLIMIT
))){
698 mem_cgroup_update_tree(mem
, page
);
699 __mem_cgroup_target_update(mem
,
700 MEM_CGROUP_TARGET_SOFTLIMIT
);
705 static struct mem_cgroup
*mem_cgroup_from_cont(struct cgroup
*cont
)
707 return container_of(cgroup_subsys_state(cont
,
708 mem_cgroup_subsys_id
), struct mem_cgroup
,
712 struct mem_cgroup
*mem_cgroup_from_task(struct task_struct
*p
)
715 * mm_update_next_owner() may clear mm->owner to NULL
716 * if it races with swapoff, page migration, etc.
717 * So this can be called with p == NULL.
722 return container_of(task_subsys_state(p
, mem_cgroup_subsys_id
),
723 struct mem_cgroup
, css
);
726 static struct mem_cgroup
*try_get_mem_cgroup_from_mm(struct mm_struct
*mm
)
728 struct mem_cgroup
*mem
= NULL
;
733 * Because we have no locks, mm->owner's may be being moved to other
734 * cgroup. We use css_tryget() here even if this looks
735 * pessimistic (rather than adding locks here).
739 mem
= mem_cgroup_from_task(rcu_dereference(mm
->owner
));
742 } while (!css_tryget(&mem
->css
));
747 /* The caller has to guarantee "mem" exists before calling this */
748 static struct mem_cgroup
*mem_cgroup_start_loop(struct mem_cgroup
*mem
)
750 struct cgroup_subsys_state
*css
;
753 if (!mem
) /* ROOT cgroup has the smallest ID */
754 return root_mem_cgroup
; /*css_put/get against root is ignored*/
755 if (!mem
->use_hierarchy
) {
756 if (css_tryget(&mem
->css
))
762 * searching a memory cgroup which has the smallest ID under given
763 * ROOT cgroup. (ID >= 1)
765 css
= css_get_next(&mem_cgroup_subsys
, 1, &mem
->css
, &found
);
766 if (css
&& css_tryget(css
))
767 mem
= container_of(css
, struct mem_cgroup
, css
);
774 static struct mem_cgroup
*mem_cgroup_get_next(struct mem_cgroup
*iter
,
775 struct mem_cgroup
*root
,
778 int nextid
= css_id(&iter
->css
) + 1;
781 struct cgroup_subsys_state
*css
;
783 hierarchy_used
= iter
->use_hierarchy
;
786 /* If no ROOT, walk all, ignore hierarchy */
787 if (!cond
|| (root
&& !hierarchy_used
))
791 root
= root_mem_cgroup
;
797 css
= css_get_next(&mem_cgroup_subsys
, nextid
,
799 if (css
&& css_tryget(css
))
800 iter
= container_of(css
, struct mem_cgroup
, css
);
802 /* If css is NULL, no more cgroups will be found */
804 } while (css
&& !iter
);
809 * for_eacn_mem_cgroup_tree() for visiting all cgroup under tree. Please
810 * be careful that "break" loop is not allowed. We have reference count.
811 * Instead of that modify "cond" to be false and "continue" to exit the loop.
813 #define for_each_mem_cgroup_tree_cond(iter, root, cond) \
814 for (iter = mem_cgroup_start_loop(root);\
816 iter = mem_cgroup_get_next(iter, root, cond))
818 #define for_each_mem_cgroup_tree(iter, root) \
819 for_each_mem_cgroup_tree_cond(iter, root, true)
821 #define for_each_mem_cgroup_all(iter) \
822 for_each_mem_cgroup_tree_cond(iter, NULL, true)
825 static inline bool mem_cgroup_is_root(struct mem_cgroup
*mem
)
827 return (mem
== root_mem_cgroup
);
831 * Following LRU functions are allowed to be used without PCG_LOCK.
832 * Operations are called by routine of global LRU independently from memcg.
833 * What we have to take care of here is validness of pc->mem_cgroup.
835 * Changes to pc->mem_cgroup happens when
838 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
839 * It is added to LRU before charge.
840 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
841 * When moving account, the page is not on LRU. It's isolated.
844 void mem_cgroup_del_lru_list(struct page
*page
, enum lru_list lru
)
846 struct page_cgroup
*pc
;
847 struct mem_cgroup_per_zone
*mz
;
849 if (mem_cgroup_disabled())
851 pc
= lookup_page_cgroup(page
);
852 /* can happen while we handle swapcache. */
853 if (!TestClearPageCgroupAcctLRU(pc
))
855 VM_BUG_ON(!pc
->mem_cgroup
);
857 * We don't check PCG_USED bit. It's cleared when the "page" is finally
858 * removed from global LRU.
860 mz
= page_cgroup_zoneinfo(pc
->mem_cgroup
, page
);
861 /* huge page split is done under lru_lock. so, we have no races. */
862 MEM_CGROUP_ZSTAT(mz
, lru
) -= 1 << compound_order(page
);
863 if (mem_cgroup_is_root(pc
->mem_cgroup
))
865 VM_BUG_ON(list_empty(&pc
->lru
));
866 list_del_init(&pc
->lru
);
869 void mem_cgroup_del_lru(struct page
*page
)
871 mem_cgroup_del_lru_list(page
, page_lru(page
));
875 * Writeback is about to end against a page which has been marked for immediate
876 * reclaim. If it still appears to be reclaimable, move it to the tail of the
879 void mem_cgroup_rotate_reclaimable_page(struct page
*page
)
881 struct mem_cgroup_per_zone
*mz
;
882 struct page_cgroup
*pc
;
883 enum lru_list lru
= page_lru(page
);
885 if (mem_cgroup_disabled())
888 pc
= lookup_page_cgroup(page
);
889 /* unused or root page is not rotated. */
890 if (!PageCgroupUsed(pc
))
892 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
894 if (mem_cgroup_is_root(pc
->mem_cgroup
))
896 mz
= page_cgroup_zoneinfo(pc
->mem_cgroup
, page
);
897 list_move_tail(&pc
->lru
, &mz
->lists
[lru
]);
900 void mem_cgroup_rotate_lru_list(struct page
*page
, enum lru_list lru
)
902 struct mem_cgroup_per_zone
*mz
;
903 struct page_cgroup
*pc
;
905 if (mem_cgroup_disabled())
908 pc
= lookup_page_cgroup(page
);
909 /* unused or root page is not rotated. */
910 if (!PageCgroupUsed(pc
))
912 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
914 if (mem_cgroup_is_root(pc
->mem_cgroup
))
916 mz
= page_cgroup_zoneinfo(pc
->mem_cgroup
, page
);
917 list_move(&pc
->lru
, &mz
->lists
[lru
]);
920 void mem_cgroup_add_lru_list(struct page
*page
, enum lru_list lru
)
922 struct page_cgroup
*pc
;
923 struct mem_cgroup_per_zone
*mz
;
925 if (mem_cgroup_disabled())
927 pc
= lookup_page_cgroup(page
);
928 VM_BUG_ON(PageCgroupAcctLRU(pc
));
929 if (!PageCgroupUsed(pc
))
931 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
933 mz
= page_cgroup_zoneinfo(pc
->mem_cgroup
, page
);
934 /* huge page split is done under lru_lock. so, we have no races. */
935 MEM_CGROUP_ZSTAT(mz
, lru
) += 1 << compound_order(page
);
936 SetPageCgroupAcctLRU(pc
);
937 if (mem_cgroup_is_root(pc
->mem_cgroup
))
939 list_add(&pc
->lru
, &mz
->lists
[lru
]);
943 * At handling SwapCache and other FUSE stuff, pc->mem_cgroup may be changed
944 * while it's linked to lru because the page may be reused after it's fully
945 * uncharged. To handle that, unlink page_cgroup from LRU when charge it again.
946 * It's done under lock_page and expected that zone->lru_lock isnever held.
948 static void mem_cgroup_lru_del_before_commit(struct page
*page
)
951 struct zone
*zone
= page_zone(page
);
952 struct page_cgroup
*pc
= lookup_page_cgroup(page
);
955 * Doing this check without taking ->lru_lock seems wrong but this
956 * is safe. Because if page_cgroup's USED bit is unset, the page
957 * will not be added to any memcg's LRU. If page_cgroup's USED bit is
958 * set, the commit after this will fail, anyway.
959 * This all charge/uncharge is done under some mutual execustion.
960 * So, we don't need to taking care of changes in USED bit.
962 if (likely(!PageLRU(page
)))
965 spin_lock_irqsave(&zone
->lru_lock
, flags
);
967 * Forget old LRU when this page_cgroup is *not* used. This Used bit
968 * is guarded by lock_page() because the page is SwapCache.
970 if (!PageCgroupUsed(pc
))
971 mem_cgroup_del_lru_list(page
, page_lru(page
));
972 spin_unlock_irqrestore(&zone
->lru_lock
, flags
);
975 static void mem_cgroup_lru_add_after_commit(struct page
*page
)
978 struct zone
*zone
= page_zone(page
);
979 struct page_cgroup
*pc
= lookup_page_cgroup(page
);
981 /* taking care of that the page is added to LRU while we commit it */
982 if (likely(!PageLRU(page
)))
984 spin_lock_irqsave(&zone
->lru_lock
, flags
);
985 /* link when the page is linked to LRU but page_cgroup isn't */
986 if (PageLRU(page
) && !PageCgroupAcctLRU(pc
))
987 mem_cgroup_add_lru_list(page
, page_lru(page
));
988 spin_unlock_irqrestore(&zone
->lru_lock
, flags
);
992 void mem_cgroup_move_lists(struct page
*page
,
993 enum lru_list from
, enum lru_list to
)
995 if (mem_cgroup_disabled())
997 mem_cgroup_del_lru_list(page
, from
);
998 mem_cgroup_add_lru_list(page
, to
);
1001 int task_in_mem_cgroup(struct task_struct
*task
, const struct mem_cgroup
*mem
)
1004 struct mem_cgroup
*curr
= NULL
;
1005 struct task_struct
*p
;
1007 p
= find_lock_task_mm(task
);
1010 curr
= try_get_mem_cgroup_from_mm(p
->mm
);
1015 * We should check use_hierarchy of "mem" not "curr". Because checking
1016 * use_hierarchy of "curr" here make this function true if hierarchy is
1017 * enabled in "curr" and "curr" is a child of "mem" in *cgroup*
1018 * hierarchy(even if use_hierarchy is disabled in "mem").
1020 if (mem
->use_hierarchy
)
1021 ret
= css_is_ancestor(&curr
->css
, &mem
->css
);
1023 ret
= (curr
== mem
);
1024 css_put(&curr
->css
);
1028 static int calc_inactive_ratio(struct mem_cgroup
*memcg
, unsigned long *present_pages
)
1030 unsigned long active
;
1031 unsigned long inactive
;
1033 unsigned long inactive_ratio
;
1035 inactive
= mem_cgroup_get_local_zonestat(memcg
, LRU_INACTIVE_ANON
);
1036 active
= mem_cgroup_get_local_zonestat(memcg
, LRU_ACTIVE_ANON
);
1038 gb
= (inactive
+ active
) >> (30 - PAGE_SHIFT
);
1040 inactive_ratio
= int_sqrt(10 * gb
);
1044 if (present_pages
) {
1045 present_pages
[0] = inactive
;
1046 present_pages
[1] = active
;
1049 return inactive_ratio
;
1052 int mem_cgroup_inactive_anon_is_low(struct mem_cgroup
*memcg
)
1054 unsigned long active
;
1055 unsigned long inactive
;
1056 unsigned long present_pages
[2];
1057 unsigned long inactive_ratio
;
1059 inactive_ratio
= calc_inactive_ratio(memcg
, present_pages
);
1061 inactive
= present_pages
[0];
1062 active
= present_pages
[1];
1064 if (inactive
* inactive_ratio
< active
)
1070 int mem_cgroup_inactive_file_is_low(struct mem_cgroup
*memcg
)
1072 unsigned long active
;
1073 unsigned long inactive
;
1075 inactive
= mem_cgroup_get_local_zonestat(memcg
, LRU_INACTIVE_FILE
);
1076 active
= mem_cgroup_get_local_zonestat(memcg
, LRU_ACTIVE_FILE
);
1078 return (active
> inactive
);
1081 unsigned long mem_cgroup_zone_nr_lru_pages(struct mem_cgroup
*memcg
,
1085 int nid
= zone_to_nid(zone
);
1086 int zid
= zone_idx(zone
);
1087 struct mem_cgroup_per_zone
*mz
= mem_cgroup_zoneinfo(memcg
, nid
, zid
);
1089 return MEM_CGROUP_ZSTAT(mz
, lru
);
1092 struct zone_reclaim_stat
*mem_cgroup_get_reclaim_stat(struct mem_cgroup
*memcg
,
1095 int nid
= zone_to_nid(zone
);
1096 int zid
= zone_idx(zone
);
1097 struct mem_cgroup_per_zone
*mz
= mem_cgroup_zoneinfo(memcg
, nid
, zid
);
1099 return &mz
->reclaim_stat
;
1102 struct zone_reclaim_stat
*
1103 mem_cgroup_get_reclaim_stat_from_page(struct page
*page
)
1105 struct page_cgroup
*pc
;
1106 struct mem_cgroup_per_zone
*mz
;
1108 if (mem_cgroup_disabled())
1111 pc
= lookup_page_cgroup(page
);
1112 if (!PageCgroupUsed(pc
))
1114 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1116 mz
= page_cgroup_zoneinfo(pc
->mem_cgroup
, page
);
1117 return &mz
->reclaim_stat
;
1120 unsigned long mem_cgroup_isolate_pages(unsigned long nr_to_scan
,
1121 struct list_head
*dst
,
1122 unsigned long *scanned
, int order
,
1123 int mode
, struct zone
*z
,
1124 struct mem_cgroup
*mem_cont
,
1125 int active
, int file
)
1127 unsigned long nr_taken
= 0;
1131 struct list_head
*src
;
1132 struct page_cgroup
*pc
, *tmp
;
1133 int nid
= zone_to_nid(z
);
1134 int zid
= zone_idx(z
);
1135 struct mem_cgroup_per_zone
*mz
;
1136 int lru
= LRU_FILE
* file
+ active
;
1140 mz
= mem_cgroup_zoneinfo(mem_cont
, nid
, zid
);
1141 src
= &mz
->lists
[lru
];
1144 list_for_each_entry_safe_reverse(pc
, tmp
, src
, lru
) {
1145 if (scan
>= nr_to_scan
)
1148 if (unlikely(!PageCgroupUsed(pc
)))
1151 page
= lookup_cgroup_page(pc
);
1153 if (unlikely(!PageLRU(page
)))
1157 ret
= __isolate_lru_page(page
, mode
, file
);
1160 list_move(&page
->lru
, dst
);
1161 mem_cgroup_del_lru(page
);
1162 nr_taken
+= hpage_nr_pages(page
);
1165 /* we don't affect global LRU but rotate in our LRU */
1166 mem_cgroup_rotate_lru_list(page
, page_lru(page
));
1175 trace_mm_vmscan_memcg_isolate(0, nr_to_scan
, scan
, nr_taken
,
1181 #define mem_cgroup_from_res_counter(counter, member) \
1182 container_of(counter, struct mem_cgroup, member)
1185 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1186 * @mem: the memory cgroup
1188 * Returns the maximum amount of memory @mem can be charged with, in
1191 static unsigned long mem_cgroup_margin(struct mem_cgroup
*mem
)
1193 unsigned long long margin
;
1195 margin
= res_counter_margin(&mem
->res
);
1196 if (do_swap_account
)
1197 margin
= min(margin
, res_counter_margin(&mem
->memsw
));
1198 return margin
>> PAGE_SHIFT
;
1201 static unsigned int get_swappiness(struct mem_cgroup
*memcg
)
1203 struct cgroup
*cgrp
= memcg
->css
.cgroup
;
1206 if (cgrp
->parent
== NULL
)
1207 return vm_swappiness
;
1209 return memcg
->swappiness
;
1212 static void mem_cgroup_start_move(struct mem_cgroup
*mem
)
1217 spin_lock(&mem
->pcp_counter_lock
);
1218 for_each_online_cpu(cpu
)
1219 per_cpu(mem
->stat
->count
[MEM_CGROUP_ON_MOVE
], cpu
) += 1;
1220 mem
->nocpu_base
.count
[MEM_CGROUP_ON_MOVE
] += 1;
1221 spin_unlock(&mem
->pcp_counter_lock
);
1227 static void mem_cgroup_end_move(struct mem_cgroup
*mem
)
1234 spin_lock(&mem
->pcp_counter_lock
);
1235 for_each_online_cpu(cpu
)
1236 per_cpu(mem
->stat
->count
[MEM_CGROUP_ON_MOVE
], cpu
) -= 1;
1237 mem
->nocpu_base
.count
[MEM_CGROUP_ON_MOVE
] -= 1;
1238 spin_unlock(&mem
->pcp_counter_lock
);
1242 * 2 routines for checking "mem" is under move_account() or not.
1244 * mem_cgroup_stealed() - checking a cgroup is mc.from or not. This is used
1245 * for avoiding race in accounting. If true,
1246 * pc->mem_cgroup may be overwritten.
1248 * mem_cgroup_under_move() - checking a cgroup is mc.from or mc.to or
1249 * under hierarchy of moving cgroups. This is for
1250 * waiting at hith-memory prressure caused by "move".
1253 static bool mem_cgroup_stealed(struct mem_cgroup
*mem
)
1255 VM_BUG_ON(!rcu_read_lock_held());
1256 return this_cpu_read(mem
->stat
->count
[MEM_CGROUP_ON_MOVE
]) > 0;
1259 static bool mem_cgroup_under_move(struct mem_cgroup
*mem
)
1261 struct mem_cgroup
*from
;
1262 struct mem_cgroup
*to
;
1265 * Unlike task_move routines, we access mc.to, mc.from not under
1266 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1268 spin_lock(&mc
.lock
);
1273 if (from
== mem
|| to
== mem
1274 || (mem
->use_hierarchy
&& css_is_ancestor(&from
->css
, &mem
->css
))
1275 || (mem
->use_hierarchy
&& css_is_ancestor(&to
->css
, &mem
->css
)))
1278 spin_unlock(&mc
.lock
);
1282 static bool mem_cgroup_wait_acct_move(struct mem_cgroup
*mem
)
1284 if (mc
.moving_task
&& current
!= mc
.moving_task
) {
1285 if (mem_cgroup_under_move(mem
)) {
1287 prepare_to_wait(&mc
.waitq
, &wait
, TASK_INTERRUPTIBLE
);
1288 /* moving charge context might have finished. */
1291 finish_wait(&mc
.waitq
, &wait
);
1299 * mem_cgroup_print_oom_info: Called from OOM with tasklist_lock held in read mode.
1300 * @memcg: The memory cgroup that went over limit
1301 * @p: Task that is going to be killed
1303 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1306 void mem_cgroup_print_oom_info(struct mem_cgroup
*memcg
, struct task_struct
*p
)
1308 struct cgroup
*task_cgrp
;
1309 struct cgroup
*mem_cgrp
;
1311 * Need a buffer in BSS, can't rely on allocations. The code relies
1312 * on the assumption that OOM is serialized for memory controller.
1313 * If this assumption is broken, revisit this code.
1315 static char memcg_name
[PATH_MAX
];
1324 mem_cgrp
= memcg
->css
.cgroup
;
1325 task_cgrp
= task_cgroup(p
, mem_cgroup_subsys_id
);
1327 ret
= cgroup_path(task_cgrp
, memcg_name
, PATH_MAX
);
1330 * Unfortunately, we are unable to convert to a useful name
1331 * But we'll still print out the usage information
1338 printk(KERN_INFO
"Task in %s killed", memcg_name
);
1341 ret
= cgroup_path(mem_cgrp
, memcg_name
, PATH_MAX
);
1349 * Continues from above, so we don't need an KERN_ level
1351 printk(KERN_CONT
" as a result of limit of %s\n", memcg_name
);
1354 printk(KERN_INFO
"memory: usage %llukB, limit %llukB, failcnt %llu\n",
1355 res_counter_read_u64(&memcg
->res
, RES_USAGE
) >> 10,
1356 res_counter_read_u64(&memcg
->res
, RES_LIMIT
) >> 10,
1357 res_counter_read_u64(&memcg
->res
, RES_FAILCNT
));
1358 printk(KERN_INFO
"memory+swap: usage %llukB, limit %llukB, "
1360 res_counter_read_u64(&memcg
->memsw
, RES_USAGE
) >> 10,
1361 res_counter_read_u64(&memcg
->memsw
, RES_LIMIT
) >> 10,
1362 res_counter_read_u64(&memcg
->memsw
, RES_FAILCNT
));
1366 * This function returns the number of memcg under hierarchy tree. Returns
1367 * 1(self count) if no children.
1369 static int mem_cgroup_count_children(struct mem_cgroup
*mem
)
1372 struct mem_cgroup
*iter
;
1374 for_each_mem_cgroup_tree(iter
, mem
)
1380 * Return the memory (and swap, if configured) limit for a memcg.
1382 u64
mem_cgroup_get_limit(struct mem_cgroup
*memcg
)
1387 limit
= res_counter_read_u64(&memcg
->res
, RES_LIMIT
);
1388 limit
+= total_swap_pages
<< PAGE_SHIFT
;
1390 memsw
= res_counter_read_u64(&memcg
->memsw
, RES_LIMIT
);
1392 * If memsw is finite and limits the amount of swap space available
1393 * to this memcg, return that limit.
1395 return min(limit
, memsw
);
1399 * Visit the first child (need not be the first child as per the ordering
1400 * of the cgroup list, since we track last_scanned_child) of @mem and use
1401 * that to reclaim free pages from.
1403 static struct mem_cgroup
*
1404 mem_cgroup_select_victim(struct mem_cgroup
*root_mem
)
1406 struct mem_cgroup
*ret
= NULL
;
1407 struct cgroup_subsys_state
*css
;
1410 if (!root_mem
->use_hierarchy
) {
1411 css_get(&root_mem
->css
);
1417 nextid
= root_mem
->last_scanned_child
+ 1;
1418 css
= css_get_next(&mem_cgroup_subsys
, nextid
, &root_mem
->css
,
1420 if (css
&& css_tryget(css
))
1421 ret
= container_of(css
, struct mem_cgroup
, css
);
1424 /* Updates scanning parameter */
1426 /* this means start scan from ID:1 */
1427 root_mem
->last_scanned_child
= 0;
1429 root_mem
->last_scanned_child
= found
;
1435 #if MAX_NUMNODES > 1
1438 * Always updating the nodemask is not very good - even if we have an empty
1439 * list or the wrong list here, we can start from some node and traverse all
1440 * nodes based on the zonelist. So update the list loosely once per 10 secs.
1443 static void mem_cgroup_may_update_nodemask(struct mem_cgroup
*mem
)
1447 if (time_after(mem
->next_scan_node_update
, jiffies
))
1450 mem
->next_scan_node_update
= jiffies
+ 10*HZ
;
1451 /* make a nodemask where this memcg uses memory from */
1452 mem
->scan_nodes
= node_states
[N_HIGH_MEMORY
];
1454 for_each_node_mask(nid
, node_states
[N_HIGH_MEMORY
]) {
1456 if (mem_cgroup_get_zonestat_node(mem
, nid
, LRU_INACTIVE_FILE
) ||
1457 mem_cgroup_get_zonestat_node(mem
, nid
, LRU_ACTIVE_FILE
))
1460 if (total_swap_pages
&&
1461 (mem_cgroup_get_zonestat_node(mem
, nid
, LRU_INACTIVE_ANON
) ||
1462 mem_cgroup_get_zonestat_node(mem
, nid
, LRU_ACTIVE_ANON
)))
1464 node_clear(nid
, mem
->scan_nodes
);
1469 * Selecting a node where we start reclaim from. Because what we need is just
1470 * reducing usage counter, start from anywhere is O,K. Considering
1471 * memory reclaim from current node, there are pros. and cons.
1473 * Freeing memory from current node means freeing memory from a node which
1474 * we'll use or we've used. So, it may make LRU bad. And if several threads
1475 * hit limits, it will see a contention on a node. But freeing from remote
1476 * node means more costs for memory reclaim because of memory latency.
1478 * Now, we use round-robin. Better algorithm is welcomed.
1480 int mem_cgroup_select_victim_node(struct mem_cgroup
*mem
)
1484 mem_cgroup_may_update_nodemask(mem
);
1485 node
= mem
->last_scanned_node
;
1487 node
= next_node(node
, mem
->scan_nodes
);
1488 if (node
== MAX_NUMNODES
)
1489 node
= first_node(mem
->scan_nodes
);
1491 * We call this when we hit limit, not when pages are added to LRU.
1492 * No LRU may hold pages because all pages are UNEVICTABLE or
1493 * memcg is too small and all pages are not on LRU. In that case,
1494 * we use curret node.
1496 if (unlikely(node
== MAX_NUMNODES
))
1497 node
= numa_node_id();
1499 mem
->last_scanned_node
= node
;
1504 int mem_cgroup_select_victim_node(struct mem_cgroup
*mem
)
1511 * Scan the hierarchy if needed to reclaim memory. We remember the last child
1512 * we reclaimed from, so that we don't end up penalizing one child extensively
1513 * based on its position in the children list.
1515 * root_mem is the original ancestor that we've been reclaim from.
1517 * We give up and return to the caller when we visit root_mem twice.
1518 * (other groups can be removed while we're walking....)
1520 * If shrink==true, for avoiding to free too much, this returns immedieately.
1522 static int mem_cgroup_hierarchical_reclaim(struct mem_cgroup
*root_mem
,
1525 unsigned long reclaim_options
,
1526 unsigned long *total_scanned
)
1528 struct mem_cgroup
*victim
;
1531 bool noswap
= reclaim_options
& MEM_CGROUP_RECLAIM_NOSWAP
;
1532 bool shrink
= reclaim_options
& MEM_CGROUP_RECLAIM_SHRINK
;
1533 bool check_soft
= reclaim_options
& MEM_CGROUP_RECLAIM_SOFT
;
1534 unsigned long excess
;
1535 unsigned long nr_scanned
;
1537 excess
= res_counter_soft_limit_excess(&root_mem
->res
) >> PAGE_SHIFT
;
1539 /* If memsw_is_minimum==1, swap-out is of-no-use. */
1540 if (root_mem
->memsw_is_minimum
)
1544 victim
= mem_cgroup_select_victim(root_mem
);
1545 if (victim
== root_mem
) {
1548 drain_all_stock_async();
1551 * If we have not been able to reclaim
1552 * anything, it might because there are
1553 * no reclaimable pages under this hierarchy
1555 if (!check_soft
|| !total
) {
1556 css_put(&victim
->css
);
1560 * We want to do more targeted reclaim.
1561 * excess >> 2 is not to excessive so as to
1562 * reclaim too much, nor too less that we keep
1563 * coming back to reclaim from this cgroup
1565 if (total
>= (excess
>> 2) ||
1566 (loop
> MEM_CGROUP_MAX_RECLAIM_LOOPS
)) {
1567 css_put(&victim
->css
);
1572 if (!mem_cgroup_local_usage(victim
)) {
1573 /* this cgroup's local usage == 0 */
1574 css_put(&victim
->css
);
1577 /* we use swappiness of local cgroup */
1579 ret
= mem_cgroup_shrink_node_zone(victim
, gfp_mask
,
1580 noswap
, get_swappiness(victim
), zone
,
1582 *total_scanned
+= nr_scanned
;
1584 ret
= try_to_free_mem_cgroup_pages(victim
, gfp_mask
,
1585 noswap
, get_swappiness(victim
));
1586 css_put(&victim
->css
);
1588 * At shrinking usage, we can't check we should stop here or
1589 * reclaim more. It's depends on callers. last_scanned_child
1590 * will work enough for keeping fairness under tree.
1596 if (!res_counter_soft_limit_excess(&root_mem
->res
))
1598 } else if (mem_cgroup_margin(root_mem
))
1605 * Check OOM-Killer is already running under our hierarchy.
1606 * If someone is running, return false.
1608 static bool mem_cgroup_oom_lock(struct mem_cgroup
*mem
)
1610 int x
, lock_count
= 0;
1611 struct mem_cgroup
*iter
;
1613 for_each_mem_cgroup_tree(iter
, mem
) {
1614 x
= atomic_inc_return(&iter
->oom_lock
);
1615 lock_count
= max(x
, lock_count
);
1618 if (lock_count
== 1)
1623 static int mem_cgroup_oom_unlock(struct mem_cgroup
*mem
)
1625 struct mem_cgroup
*iter
;
1628 * When a new child is created while the hierarchy is under oom,
1629 * mem_cgroup_oom_lock() may not be called. We have to use
1630 * atomic_add_unless() here.
1632 for_each_mem_cgroup_tree(iter
, mem
)
1633 atomic_add_unless(&iter
->oom_lock
, -1, 0);
1638 static DEFINE_MUTEX(memcg_oom_mutex
);
1639 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq
);
1641 struct oom_wait_info
{
1642 struct mem_cgroup
*mem
;
1646 static int memcg_oom_wake_function(wait_queue_t
*wait
,
1647 unsigned mode
, int sync
, void *arg
)
1649 struct mem_cgroup
*wake_mem
= (struct mem_cgroup
*)arg
;
1650 struct oom_wait_info
*oom_wait_info
;
1652 oom_wait_info
= container_of(wait
, struct oom_wait_info
, wait
);
1654 if (oom_wait_info
->mem
== wake_mem
)
1656 /* if no hierarchy, no match */
1657 if (!oom_wait_info
->mem
->use_hierarchy
|| !wake_mem
->use_hierarchy
)
1660 * Both of oom_wait_info->mem and wake_mem are stable under us.
1661 * Then we can use css_is_ancestor without taking care of RCU.
1663 if (!css_is_ancestor(&oom_wait_info
->mem
->css
, &wake_mem
->css
) &&
1664 !css_is_ancestor(&wake_mem
->css
, &oom_wait_info
->mem
->css
))
1668 return autoremove_wake_function(wait
, mode
, sync
, arg
);
1671 static void memcg_wakeup_oom(struct mem_cgroup
*mem
)
1673 /* for filtering, pass "mem" as argument. */
1674 __wake_up(&memcg_oom_waitq
, TASK_NORMAL
, 0, mem
);
1677 static void memcg_oom_recover(struct mem_cgroup
*mem
)
1679 if (mem
&& atomic_read(&mem
->oom_lock
))
1680 memcg_wakeup_oom(mem
);
1684 * try to call OOM killer. returns false if we should exit memory-reclaim loop.
1686 bool mem_cgroup_handle_oom(struct mem_cgroup
*mem
, gfp_t mask
)
1688 struct oom_wait_info owait
;
1689 bool locked
, need_to_kill
;
1692 owait
.wait
.flags
= 0;
1693 owait
.wait
.func
= memcg_oom_wake_function
;
1694 owait
.wait
.private = current
;
1695 INIT_LIST_HEAD(&owait
.wait
.task_list
);
1696 need_to_kill
= true;
1697 /* At first, try to OOM lock hierarchy under mem.*/
1698 mutex_lock(&memcg_oom_mutex
);
1699 locked
= mem_cgroup_oom_lock(mem
);
1701 * Even if signal_pending(), we can't quit charge() loop without
1702 * accounting. So, UNINTERRUPTIBLE is appropriate. But SIGKILL
1703 * under OOM is always welcomed, use TASK_KILLABLE here.
1705 prepare_to_wait(&memcg_oom_waitq
, &owait
.wait
, TASK_KILLABLE
);
1706 if (!locked
|| mem
->oom_kill_disable
)
1707 need_to_kill
= false;
1709 mem_cgroup_oom_notify(mem
);
1710 mutex_unlock(&memcg_oom_mutex
);
1713 finish_wait(&memcg_oom_waitq
, &owait
.wait
);
1714 mem_cgroup_out_of_memory(mem
, mask
);
1717 finish_wait(&memcg_oom_waitq
, &owait
.wait
);
1719 mutex_lock(&memcg_oom_mutex
);
1720 mem_cgroup_oom_unlock(mem
);
1721 memcg_wakeup_oom(mem
);
1722 mutex_unlock(&memcg_oom_mutex
);
1724 if (test_thread_flag(TIF_MEMDIE
) || fatal_signal_pending(current
))
1726 /* Give chance to dying process */
1727 schedule_timeout(1);
1732 * Currently used to update mapped file statistics, but the routine can be
1733 * generalized to update other statistics as well.
1735 * Notes: Race condition
1737 * We usually use page_cgroup_lock() for accessing page_cgroup member but
1738 * it tends to be costly. But considering some conditions, we doesn't need
1739 * to do so _always_.
1741 * Considering "charge", lock_page_cgroup() is not required because all
1742 * file-stat operations happen after a page is attached to radix-tree. There
1743 * are no race with "charge".
1745 * Considering "uncharge", we know that memcg doesn't clear pc->mem_cgroup
1746 * at "uncharge" intentionally. So, we always see valid pc->mem_cgroup even
1747 * if there are race with "uncharge". Statistics itself is properly handled
1750 * Considering "move", this is an only case we see a race. To make the race
1751 * small, we check MEM_CGROUP_ON_MOVE percpu value and detect there are
1752 * possibility of race condition. If there is, we take a lock.
1755 void mem_cgroup_update_page_stat(struct page
*page
,
1756 enum mem_cgroup_page_stat_item idx
, int val
)
1758 struct mem_cgroup
*mem
;
1759 struct page_cgroup
*pc
= lookup_page_cgroup(page
);
1760 bool need_unlock
= false;
1761 unsigned long uninitialized_var(flags
);
1767 mem
= pc
->mem_cgroup
;
1768 if (unlikely(!mem
|| !PageCgroupUsed(pc
)))
1770 /* pc->mem_cgroup is unstable ? */
1771 if (unlikely(mem_cgroup_stealed(mem
)) || PageTransHuge(page
)) {
1772 /* take a lock against to access pc->mem_cgroup */
1773 move_lock_page_cgroup(pc
, &flags
);
1775 mem
= pc
->mem_cgroup
;
1776 if (!mem
|| !PageCgroupUsed(pc
))
1781 case MEMCG_NR_FILE_MAPPED
:
1783 SetPageCgroupFileMapped(pc
);
1784 else if (!page_mapped(page
))
1785 ClearPageCgroupFileMapped(pc
);
1786 idx
= MEM_CGROUP_STAT_FILE_MAPPED
;
1792 this_cpu_add(mem
->stat
->count
[idx
], val
);
1795 if (unlikely(need_unlock
))
1796 move_unlock_page_cgroup(pc
, &flags
);
1800 EXPORT_SYMBOL(mem_cgroup_update_page_stat
);
1803 * size of first charge trial. "32" comes from vmscan.c's magic value.
1804 * TODO: maybe necessary to use big numbers in big irons.
1806 #define CHARGE_BATCH 32U
1807 struct memcg_stock_pcp
{
1808 struct mem_cgroup
*cached
; /* this never be root cgroup */
1809 unsigned int nr_pages
;
1810 struct work_struct work
;
1812 static DEFINE_PER_CPU(struct memcg_stock_pcp
, memcg_stock
);
1813 static atomic_t memcg_drain_count
;
1816 * Try to consume stocked charge on this cpu. If success, one page is consumed
1817 * from local stock and true is returned. If the stock is 0 or charges from a
1818 * cgroup which is not current target, returns false. This stock will be
1821 static bool consume_stock(struct mem_cgroup
*mem
)
1823 struct memcg_stock_pcp
*stock
;
1826 stock
= &get_cpu_var(memcg_stock
);
1827 if (mem
== stock
->cached
&& stock
->nr_pages
)
1829 else /* need to call res_counter_charge */
1831 put_cpu_var(memcg_stock
);
1836 * Returns stocks cached in percpu to res_counter and reset cached information.
1838 static void drain_stock(struct memcg_stock_pcp
*stock
)
1840 struct mem_cgroup
*old
= stock
->cached
;
1842 if (stock
->nr_pages
) {
1843 unsigned long bytes
= stock
->nr_pages
* PAGE_SIZE
;
1845 res_counter_uncharge(&old
->res
, bytes
);
1846 if (do_swap_account
)
1847 res_counter_uncharge(&old
->memsw
, bytes
);
1848 stock
->nr_pages
= 0;
1850 stock
->cached
= NULL
;
1854 * This must be called under preempt disabled or must be called by
1855 * a thread which is pinned to local cpu.
1857 static void drain_local_stock(struct work_struct
*dummy
)
1859 struct memcg_stock_pcp
*stock
= &__get_cpu_var(memcg_stock
);
1864 * Cache charges(val) which is from res_counter, to local per_cpu area.
1865 * This will be consumed by consume_stock() function, later.
1867 static void refill_stock(struct mem_cgroup
*mem
, unsigned int nr_pages
)
1869 struct memcg_stock_pcp
*stock
= &get_cpu_var(memcg_stock
);
1871 if (stock
->cached
!= mem
) { /* reset if necessary */
1873 stock
->cached
= mem
;
1875 stock
->nr_pages
+= nr_pages
;
1876 put_cpu_var(memcg_stock
);
1880 * Tries to drain stocked charges in other cpus. This function is asynchronous
1881 * and just put a work per cpu for draining localy on each cpu. Caller can
1882 * expects some charges will be back to res_counter later but cannot wait for
1885 static void drain_all_stock_async(void)
1888 /* This function is for scheduling "drain" in asynchronous way.
1889 * The result of "drain" is not directly handled by callers. Then,
1890 * if someone is calling drain, we don't have to call drain more.
1891 * Anyway, WORK_STRUCT_PENDING check in queue_work_on() will catch if
1892 * there is a race. We just do loose check here.
1894 if (atomic_read(&memcg_drain_count
))
1896 /* Notify other cpus that system-wide "drain" is running */
1897 atomic_inc(&memcg_drain_count
);
1899 for_each_online_cpu(cpu
) {
1900 struct memcg_stock_pcp
*stock
= &per_cpu(memcg_stock
, cpu
);
1901 schedule_work_on(cpu
, &stock
->work
);
1904 atomic_dec(&memcg_drain_count
);
1905 /* We don't wait for flush_work */
1908 /* This is a synchronous drain interface. */
1909 static void drain_all_stock_sync(void)
1911 /* called when force_empty is called */
1912 atomic_inc(&memcg_drain_count
);
1913 schedule_on_each_cpu(drain_local_stock
);
1914 atomic_dec(&memcg_drain_count
);
1918 * This function drains percpu counter value from DEAD cpu and
1919 * move it to local cpu. Note that this function can be preempted.
1921 static void mem_cgroup_drain_pcp_counter(struct mem_cgroup
*mem
, int cpu
)
1925 spin_lock(&mem
->pcp_counter_lock
);
1926 for (i
= 0; i
< MEM_CGROUP_STAT_DATA
; i
++) {
1927 long x
= per_cpu(mem
->stat
->count
[i
], cpu
);
1929 per_cpu(mem
->stat
->count
[i
], cpu
) = 0;
1930 mem
->nocpu_base
.count
[i
] += x
;
1932 for (i
= 0; i
< MEM_CGROUP_EVENTS_NSTATS
; i
++) {
1933 unsigned long x
= per_cpu(mem
->stat
->events
[i
], cpu
);
1935 per_cpu(mem
->stat
->events
[i
], cpu
) = 0;
1936 mem
->nocpu_base
.events
[i
] += x
;
1938 /* need to clear ON_MOVE value, works as a kind of lock. */
1939 per_cpu(mem
->stat
->count
[MEM_CGROUP_ON_MOVE
], cpu
) = 0;
1940 spin_unlock(&mem
->pcp_counter_lock
);
1943 static void synchronize_mem_cgroup_on_move(struct mem_cgroup
*mem
, int cpu
)
1945 int idx
= MEM_CGROUP_ON_MOVE
;
1947 spin_lock(&mem
->pcp_counter_lock
);
1948 per_cpu(mem
->stat
->count
[idx
], cpu
) = mem
->nocpu_base
.count
[idx
];
1949 spin_unlock(&mem
->pcp_counter_lock
);
1952 static int __cpuinit
memcg_cpu_hotplug_callback(struct notifier_block
*nb
,
1953 unsigned long action
,
1956 int cpu
= (unsigned long)hcpu
;
1957 struct memcg_stock_pcp
*stock
;
1958 struct mem_cgroup
*iter
;
1960 if ((action
== CPU_ONLINE
)) {
1961 for_each_mem_cgroup_all(iter
)
1962 synchronize_mem_cgroup_on_move(iter
, cpu
);
1966 if ((action
!= CPU_DEAD
) || action
!= CPU_DEAD_FROZEN
)
1969 for_each_mem_cgroup_all(iter
)
1970 mem_cgroup_drain_pcp_counter(iter
, cpu
);
1972 stock
= &per_cpu(memcg_stock
, cpu
);
1978 /* See __mem_cgroup_try_charge() for details */
1980 CHARGE_OK
, /* success */
1981 CHARGE_RETRY
, /* need to retry but retry is not bad */
1982 CHARGE_NOMEM
, /* we can't do more. return -ENOMEM */
1983 CHARGE_WOULDBLOCK
, /* GFP_WAIT wasn't set and no enough res. */
1984 CHARGE_OOM_DIE
, /* the current is killed because of OOM */
1987 static int mem_cgroup_do_charge(struct mem_cgroup
*mem
, gfp_t gfp_mask
,
1988 unsigned int nr_pages
, bool oom_check
)
1990 unsigned long csize
= nr_pages
* PAGE_SIZE
;
1991 struct mem_cgroup
*mem_over_limit
;
1992 struct res_counter
*fail_res
;
1993 unsigned long flags
= 0;
1996 ret
= res_counter_charge(&mem
->res
, csize
, &fail_res
);
1999 if (!do_swap_account
)
2001 ret
= res_counter_charge(&mem
->memsw
, csize
, &fail_res
);
2005 res_counter_uncharge(&mem
->res
, csize
);
2006 mem_over_limit
= mem_cgroup_from_res_counter(fail_res
, memsw
);
2007 flags
|= MEM_CGROUP_RECLAIM_NOSWAP
;
2009 mem_over_limit
= mem_cgroup_from_res_counter(fail_res
, res
);
2011 * nr_pages can be either a huge page (HPAGE_PMD_NR), a batch
2012 * of regular pages (CHARGE_BATCH), or a single regular page (1).
2014 * Never reclaim on behalf of optional batching, retry with a
2015 * single page instead.
2017 if (nr_pages
== CHARGE_BATCH
)
2018 return CHARGE_RETRY
;
2020 if (!(gfp_mask
& __GFP_WAIT
))
2021 return CHARGE_WOULDBLOCK
;
2023 ret
= mem_cgroup_hierarchical_reclaim(mem_over_limit
, NULL
,
2024 gfp_mask
, flags
, NULL
);
2025 if (mem_cgroup_margin(mem_over_limit
) >= nr_pages
)
2026 return CHARGE_RETRY
;
2028 * Even though the limit is exceeded at this point, reclaim
2029 * may have been able to free some pages. Retry the charge
2030 * before killing the task.
2032 * Only for regular pages, though: huge pages are rather
2033 * unlikely to succeed so close to the limit, and we fall back
2034 * to regular pages anyway in case of failure.
2036 if (nr_pages
== 1 && ret
)
2037 return CHARGE_RETRY
;
2040 * At task move, charge accounts can be doubly counted. So, it's
2041 * better to wait until the end of task_move if something is going on.
2043 if (mem_cgroup_wait_acct_move(mem_over_limit
))
2044 return CHARGE_RETRY
;
2046 /* If we don't need to call oom-killer at el, return immediately */
2048 return CHARGE_NOMEM
;
2050 if (!mem_cgroup_handle_oom(mem_over_limit
, gfp_mask
))
2051 return CHARGE_OOM_DIE
;
2053 return CHARGE_RETRY
;
2057 * Unlike exported interface, "oom" parameter is added. if oom==true,
2058 * oom-killer can be invoked.
2060 static int __mem_cgroup_try_charge(struct mm_struct
*mm
,
2062 unsigned int nr_pages
,
2063 struct mem_cgroup
**memcg
,
2066 unsigned int batch
= max(CHARGE_BATCH
, nr_pages
);
2067 int nr_oom_retries
= MEM_CGROUP_RECLAIM_RETRIES
;
2068 struct mem_cgroup
*mem
= NULL
;
2072 * Unlike gloval-vm's OOM-kill, we're not in memory shortage
2073 * in system level. So, allow to go ahead dying process in addition to
2076 if (unlikely(test_thread_flag(TIF_MEMDIE
)
2077 || fatal_signal_pending(current
)))
2081 * We always charge the cgroup the mm_struct belongs to.
2082 * The mm_struct's mem_cgroup changes on task migration if the
2083 * thread group leader migrates. It's possible that mm is not
2084 * set, if so charge the init_mm (happens for pagecache usage).
2089 if (*memcg
) { /* css should be a valid one */
2091 VM_BUG_ON(css_is_removed(&mem
->css
));
2092 if (mem_cgroup_is_root(mem
))
2094 if (nr_pages
== 1 && consume_stock(mem
))
2098 struct task_struct
*p
;
2101 p
= rcu_dereference(mm
->owner
);
2103 * Because we don't have task_lock(), "p" can exit.
2104 * In that case, "mem" can point to root or p can be NULL with
2105 * race with swapoff. Then, we have small risk of mis-accouning.
2106 * But such kind of mis-account by race always happens because
2107 * we don't have cgroup_mutex(). It's overkill and we allo that
2109 * (*) swapoff at el will charge against mm-struct not against
2110 * task-struct. So, mm->owner can be NULL.
2112 mem
= mem_cgroup_from_task(p
);
2113 if (!mem
|| mem_cgroup_is_root(mem
)) {
2117 if (nr_pages
== 1 && consume_stock(mem
)) {
2119 * It seems dagerous to access memcg without css_get().
2120 * But considering how consume_stok works, it's not
2121 * necessary. If consume_stock success, some charges
2122 * from this memcg are cached on this cpu. So, we
2123 * don't need to call css_get()/css_tryget() before
2124 * calling consume_stock().
2129 /* after here, we may be blocked. we need to get refcnt */
2130 if (!css_tryget(&mem
->css
)) {
2140 /* If killed, bypass charge */
2141 if (fatal_signal_pending(current
)) {
2147 if (oom
&& !nr_oom_retries
) {
2149 nr_oom_retries
= MEM_CGROUP_RECLAIM_RETRIES
;
2152 ret
= mem_cgroup_do_charge(mem
, gfp_mask
, batch
, oom_check
);
2156 case CHARGE_RETRY
: /* not in OOM situation but retry */
2161 case CHARGE_WOULDBLOCK
: /* !__GFP_WAIT */
2164 case CHARGE_NOMEM
: /* OOM routine works */
2169 /* If oom, we never return -ENOMEM */
2172 case CHARGE_OOM_DIE
: /* Killed by OOM Killer */
2176 } while (ret
!= CHARGE_OK
);
2178 if (batch
> nr_pages
)
2179 refill_stock(mem
, batch
- nr_pages
);
2193 * Somemtimes we have to undo a charge we got by try_charge().
2194 * This function is for that and do uncharge, put css's refcnt.
2195 * gotten by try_charge().
2197 static void __mem_cgroup_cancel_charge(struct mem_cgroup
*mem
,
2198 unsigned int nr_pages
)
2200 if (!mem_cgroup_is_root(mem
)) {
2201 unsigned long bytes
= nr_pages
* PAGE_SIZE
;
2203 res_counter_uncharge(&mem
->res
, bytes
);
2204 if (do_swap_account
)
2205 res_counter_uncharge(&mem
->memsw
, bytes
);
2210 * A helper function to get mem_cgroup from ID. must be called under
2211 * rcu_read_lock(). The caller must check css_is_removed() or some if
2212 * it's concern. (dropping refcnt from swap can be called against removed
2215 static struct mem_cgroup
*mem_cgroup_lookup(unsigned short id
)
2217 struct cgroup_subsys_state
*css
;
2219 /* ID 0 is unused ID */
2222 css
= css_lookup(&mem_cgroup_subsys
, id
);
2225 return container_of(css
, struct mem_cgroup
, css
);
2228 struct mem_cgroup
*try_get_mem_cgroup_from_page(struct page
*page
)
2230 struct mem_cgroup
*mem
= NULL
;
2231 struct page_cgroup
*pc
;
2235 VM_BUG_ON(!PageLocked(page
));
2237 pc
= lookup_page_cgroup(page
);
2238 lock_page_cgroup(pc
);
2239 if (PageCgroupUsed(pc
)) {
2240 mem
= pc
->mem_cgroup
;
2241 if (mem
&& !css_tryget(&mem
->css
))
2243 } else if (PageSwapCache(page
)) {
2244 ent
.val
= page_private(page
);
2245 id
= lookup_swap_cgroup(ent
);
2247 mem
= mem_cgroup_lookup(id
);
2248 if (mem
&& !css_tryget(&mem
->css
))
2252 unlock_page_cgroup(pc
);
2256 static void __mem_cgroup_commit_charge(struct mem_cgroup
*mem
,
2258 unsigned int nr_pages
,
2259 struct page_cgroup
*pc
,
2260 enum charge_type ctype
)
2262 lock_page_cgroup(pc
);
2263 if (unlikely(PageCgroupUsed(pc
))) {
2264 unlock_page_cgroup(pc
);
2265 __mem_cgroup_cancel_charge(mem
, nr_pages
);
2269 * we don't need page_cgroup_lock about tail pages, becase they are not
2270 * accessed by any other context at this point.
2272 pc
->mem_cgroup
= mem
;
2274 * We access a page_cgroup asynchronously without lock_page_cgroup().
2275 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
2276 * is accessed after testing USED bit. To make pc->mem_cgroup visible
2277 * before USED bit, we need memory barrier here.
2278 * See mem_cgroup_add_lru_list(), etc.
2282 case MEM_CGROUP_CHARGE_TYPE_CACHE
:
2283 case MEM_CGROUP_CHARGE_TYPE_SHMEM
:
2284 SetPageCgroupCache(pc
);
2285 SetPageCgroupUsed(pc
);
2287 case MEM_CGROUP_CHARGE_TYPE_MAPPED
:
2288 ClearPageCgroupCache(pc
);
2289 SetPageCgroupUsed(pc
);
2295 mem_cgroup_charge_statistics(mem
, PageCgroupCache(pc
), nr_pages
);
2296 unlock_page_cgroup(pc
);
2298 * "charge_statistics" updated event counter. Then, check it.
2299 * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
2300 * if they exceeds softlimit.
2302 memcg_check_events(mem
, page
);
2305 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
2307 #define PCGF_NOCOPY_AT_SPLIT ((1 << PCG_LOCK) | (1 << PCG_MOVE_LOCK) |\
2308 (1 << PCG_ACCT_LRU) | (1 << PCG_MIGRATION))
2310 * Because tail pages are not marked as "used", set it. We're under
2311 * zone->lru_lock, 'splitting on pmd' and compund_lock.
2313 void mem_cgroup_split_huge_fixup(struct page
*head
, struct page
*tail
)
2315 struct page_cgroup
*head_pc
= lookup_page_cgroup(head
);
2316 struct page_cgroup
*tail_pc
= lookup_page_cgroup(tail
);
2317 unsigned long flags
;
2319 if (mem_cgroup_disabled())
2322 * We have no races with charge/uncharge but will have races with
2323 * page state accounting.
2325 move_lock_page_cgroup(head_pc
, &flags
);
2327 tail_pc
->mem_cgroup
= head_pc
->mem_cgroup
;
2328 smp_wmb(); /* see __commit_charge() */
2329 if (PageCgroupAcctLRU(head_pc
)) {
2331 struct mem_cgroup_per_zone
*mz
;
2334 * LRU flags cannot be copied because we need to add tail
2335 *.page to LRU by generic call and our hook will be called.
2336 * We hold lru_lock, then, reduce counter directly.
2338 lru
= page_lru(head
);
2339 mz
= page_cgroup_zoneinfo(head_pc
->mem_cgroup
, head
);
2340 MEM_CGROUP_ZSTAT(mz
, lru
) -= 1;
2342 tail_pc
->flags
= head_pc
->flags
& ~PCGF_NOCOPY_AT_SPLIT
;
2343 move_unlock_page_cgroup(head_pc
, &flags
);
2348 * mem_cgroup_move_account - move account of the page
2350 * @nr_pages: number of regular pages (>1 for huge pages)
2351 * @pc: page_cgroup of the page.
2352 * @from: mem_cgroup which the page is moved from.
2353 * @to: mem_cgroup which the page is moved to. @from != @to.
2354 * @uncharge: whether we should call uncharge and css_put against @from.
2356 * The caller must confirm following.
2357 * - page is not on LRU (isolate_page() is useful.)
2358 * - compound_lock is held when nr_pages > 1
2360 * This function doesn't do "charge" nor css_get to new cgroup. It should be
2361 * done by a caller(__mem_cgroup_try_charge would be useful). If @uncharge is
2362 * true, this function does "uncharge" from old cgroup, but it doesn't if
2363 * @uncharge is false, so a caller should do "uncharge".
2365 static int mem_cgroup_move_account(struct page
*page
,
2366 unsigned int nr_pages
,
2367 struct page_cgroup
*pc
,
2368 struct mem_cgroup
*from
,
2369 struct mem_cgroup
*to
,
2372 unsigned long flags
;
2375 VM_BUG_ON(from
== to
);
2376 VM_BUG_ON(PageLRU(page
));
2378 * The page is isolated from LRU. So, collapse function
2379 * will not handle this page. But page splitting can happen.
2380 * Do this check under compound_page_lock(). The caller should
2384 if (nr_pages
> 1 && !PageTransHuge(page
))
2387 lock_page_cgroup(pc
);
2390 if (!PageCgroupUsed(pc
) || pc
->mem_cgroup
!= from
)
2393 move_lock_page_cgroup(pc
, &flags
);
2395 if (PageCgroupFileMapped(pc
)) {
2396 /* Update mapped_file data for mem_cgroup */
2398 __this_cpu_dec(from
->stat
->count
[MEM_CGROUP_STAT_FILE_MAPPED
]);
2399 __this_cpu_inc(to
->stat
->count
[MEM_CGROUP_STAT_FILE_MAPPED
]);
2402 mem_cgroup_charge_statistics(from
, PageCgroupCache(pc
), -nr_pages
);
2404 /* This is not "cancel", but cancel_charge does all we need. */
2405 __mem_cgroup_cancel_charge(from
, nr_pages
);
2407 /* caller should have done css_get */
2408 pc
->mem_cgroup
= to
;
2409 mem_cgroup_charge_statistics(to
, PageCgroupCache(pc
), nr_pages
);
2411 * We charges against "to" which may not have any tasks. Then, "to"
2412 * can be under rmdir(). But in current implementation, caller of
2413 * this function is just force_empty() and move charge, so it's
2414 * guaranteed that "to" is never removed. So, we don't check rmdir
2417 move_unlock_page_cgroup(pc
, &flags
);
2420 unlock_page_cgroup(pc
);
2424 memcg_check_events(to
, page
);
2425 memcg_check_events(from
, page
);
2431 * move charges to its parent.
2434 static int mem_cgroup_move_parent(struct page
*page
,
2435 struct page_cgroup
*pc
,
2436 struct mem_cgroup
*child
,
2439 struct cgroup
*cg
= child
->css
.cgroup
;
2440 struct cgroup
*pcg
= cg
->parent
;
2441 struct mem_cgroup
*parent
;
2442 unsigned int nr_pages
;
2443 unsigned long uninitialized_var(flags
);
2451 if (!get_page_unless_zero(page
))
2453 if (isolate_lru_page(page
))
2456 nr_pages
= hpage_nr_pages(page
);
2458 parent
= mem_cgroup_from_cont(pcg
);
2459 ret
= __mem_cgroup_try_charge(NULL
, gfp_mask
, nr_pages
, &parent
, false);
2464 flags
= compound_lock_irqsave(page
);
2466 ret
= mem_cgroup_move_account(page
, nr_pages
, pc
, child
, parent
, true);
2468 __mem_cgroup_cancel_charge(parent
, nr_pages
);
2471 compound_unlock_irqrestore(page
, flags
);
2473 putback_lru_page(page
);
2481 * Charge the memory controller for page usage.
2483 * 0 if the charge was successful
2484 * < 0 if the cgroup is over its limit
2486 static int mem_cgroup_charge_common(struct page
*page
, struct mm_struct
*mm
,
2487 gfp_t gfp_mask
, enum charge_type ctype
)
2489 struct mem_cgroup
*mem
= NULL
;
2490 unsigned int nr_pages
= 1;
2491 struct page_cgroup
*pc
;
2495 if (PageTransHuge(page
)) {
2496 nr_pages
<<= compound_order(page
);
2497 VM_BUG_ON(!PageTransHuge(page
));
2499 * Never OOM-kill a process for a huge page. The
2500 * fault handler will fall back to regular pages.
2505 pc
= lookup_page_cgroup(page
);
2506 BUG_ON(!pc
); /* XXX: remove this and move pc lookup into commit */
2508 ret
= __mem_cgroup_try_charge(mm
, gfp_mask
, nr_pages
, &mem
, oom
);
2512 __mem_cgroup_commit_charge(mem
, page
, nr_pages
, pc
, ctype
);
2516 int mem_cgroup_newpage_charge(struct page
*page
,
2517 struct mm_struct
*mm
, gfp_t gfp_mask
)
2519 if (mem_cgroup_disabled())
2522 * If already mapped, we don't have to account.
2523 * If page cache, page->mapping has address_space.
2524 * But page->mapping may have out-of-use anon_vma pointer,
2525 * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
2528 if (page_mapped(page
) || (page
->mapping
&& !PageAnon(page
)))
2532 return mem_cgroup_charge_common(page
, mm
, gfp_mask
,
2533 MEM_CGROUP_CHARGE_TYPE_MAPPED
);
2537 __mem_cgroup_commit_charge_swapin(struct page
*page
, struct mem_cgroup
*ptr
,
2538 enum charge_type ctype
);
2541 __mem_cgroup_commit_charge_lrucare(struct page
*page
, struct mem_cgroup
*mem
,
2542 enum charge_type ctype
)
2544 struct page_cgroup
*pc
= lookup_page_cgroup(page
);
2546 * In some case, SwapCache, FUSE(splice_buf->radixtree), the page
2547 * is already on LRU. It means the page may on some other page_cgroup's
2548 * LRU. Take care of it.
2550 mem_cgroup_lru_del_before_commit(page
);
2551 __mem_cgroup_commit_charge(mem
, page
, 1, pc
, ctype
);
2552 mem_cgroup_lru_add_after_commit(page
);
2556 int mem_cgroup_cache_charge(struct page
*page
, struct mm_struct
*mm
,
2559 struct mem_cgroup
*mem
= NULL
;
2562 if (mem_cgroup_disabled())
2564 if (PageCompound(page
))
2567 * Corner case handling. This is called from add_to_page_cache()
2568 * in usual. But some FS (shmem) precharges this page before calling it
2569 * and call add_to_page_cache() with GFP_NOWAIT.
2571 * For GFP_NOWAIT case, the page may be pre-charged before calling
2572 * add_to_page_cache(). (See shmem.c) check it here and avoid to call
2573 * charge twice. (It works but has to pay a bit larger cost.)
2574 * And when the page is SwapCache, it should take swap information
2575 * into account. This is under lock_page() now.
2577 if (!(gfp_mask
& __GFP_WAIT
)) {
2578 struct page_cgroup
*pc
;
2580 pc
= lookup_page_cgroup(page
);
2583 lock_page_cgroup(pc
);
2584 if (PageCgroupUsed(pc
)) {
2585 unlock_page_cgroup(pc
);
2588 unlock_page_cgroup(pc
);
2594 if (page_is_file_cache(page
)) {
2595 ret
= __mem_cgroup_try_charge(mm
, gfp_mask
, 1, &mem
, true);
2600 * FUSE reuses pages without going through the final
2601 * put that would remove them from the LRU list, make
2602 * sure that they get relinked properly.
2604 __mem_cgroup_commit_charge_lrucare(page
, mem
,
2605 MEM_CGROUP_CHARGE_TYPE_CACHE
);
2609 if (PageSwapCache(page
)) {
2610 ret
= mem_cgroup_try_charge_swapin(mm
, page
, gfp_mask
, &mem
);
2612 __mem_cgroup_commit_charge_swapin(page
, mem
,
2613 MEM_CGROUP_CHARGE_TYPE_SHMEM
);
2615 ret
= mem_cgroup_charge_common(page
, mm
, gfp_mask
,
2616 MEM_CGROUP_CHARGE_TYPE_SHMEM
);
2622 * While swap-in, try_charge -> commit or cancel, the page is locked.
2623 * And when try_charge() successfully returns, one refcnt to memcg without
2624 * struct page_cgroup is acquired. This refcnt will be consumed by
2625 * "commit()" or removed by "cancel()"
2627 int mem_cgroup_try_charge_swapin(struct mm_struct
*mm
,
2629 gfp_t mask
, struct mem_cgroup
**ptr
)
2631 struct mem_cgroup
*mem
;
2636 if (mem_cgroup_disabled())
2639 if (!do_swap_account
)
2642 * A racing thread's fault, or swapoff, may have already updated
2643 * the pte, and even removed page from swap cache: in those cases
2644 * do_swap_page()'s pte_same() test will fail; but there's also a
2645 * KSM case which does need to charge the page.
2647 if (!PageSwapCache(page
))
2649 mem
= try_get_mem_cgroup_from_page(page
);
2653 ret
= __mem_cgroup_try_charge(NULL
, mask
, 1, ptr
, true);
2659 return __mem_cgroup_try_charge(mm
, mask
, 1, ptr
, true);
2663 __mem_cgroup_commit_charge_swapin(struct page
*page
, struct mem_cgroup
*ptr
,
2664 enum charge_type ctype
)
2666 if (mem_cgroup_disabled())
2670 cgroup_exclude_rmdir(&ptr
->css
);
2672 __mem_cgroup_commit_charge_lrucare(page
, ptr
, ctype
);
2674 * Now swap is on-memory. This means this page may be
2675 * counted both as mem and swap....double count.
2676 * Fix it by uncharging from memsw. Basically, this SwapCache is stable
2677 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
2678 * may call delete_from_swap_cache() before reach here.
2680 if (do_swap_account
&& PageSwapCache(page
)) {
2681 swp_entry_t ent
= {.val
= page_private(page
)};
2683 struct mem_cgroup
*memcg
;
2685 id
= swap_cgroup_record(ent
, 0);
2687 memcg
= mem_cgroup_lookup(id
);
2690 * This recorded memcg can be obsolete one. So, avoid
2691 * calling css_tryget
2693 if (!mem_cgroup_is_root(memcg
))
2694 res_counter_uncharge(&memcg
->memsw
, PAGE_SIZE
);
2695 mem_cgroup_swap_statistics(memcg
, false);
2696 mem_cgroup_put(memcg
);
2701 * At swapin, we may charge account against cgroup which has no tasks.
2702 * So, rmdir()->pre_destroy() can be called while we do this charge.
2703 * In that case, we need to call pre_destroy() again. check it here.
2705 cgroup_release_and_wakeup_rmdir(&ptr
->css
);
2708 void mem_cgroup_commit_charge_swapin(struct page
*page
, struct mem_cgroup
*ptr
)
2710 __mem_cgroup_commit_charge_swapin(page
, ptr
,
2711 MEM_CGROUP_CHARGE_TYPE_MAPPED
);
2714 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup
*mem
)
2716 if (mem_cgroup_disabled())
2720 __mem_cgroup_cancel_charge(mem
, 1);
2723 static void mem_cgroup_do_uncharge(struct mem_cgroup
*mem
,
2724 unsigned int nr_pages
,
2725 const enum charge_type ctype
)
2727 struct memcg_batch_info
*batch
= NULL
;
2728 bool uncharge_memsw
= true;
2730 /* If swapout, usage of swap doesn't decrease */
2731 if (!do_swap_account
|| ctype
== MEM_CGROUP_CHARGE_TYPE_SWAPOUT
)
2732 uncharge_memsw
= false;
2734 batch
= ¤t
->memcg_batch
;
2736 * In usual, we do css_get() when we remember memcg pointer.
2737 * But in this case, we keep res->usage until end of a series of
2738 * uncharges. Then, it's ok to ignore memcg's refcnt.
2743 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
2744 * In those cases, all pages freed continuously can be expected to be in
2745 * the same cgroup and we have chance to coalesce uncharges.
2746 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
2747 * because we want to do uncharge as soon as possible.
2750 if (!batch
->do_batch
|| test_thread_flag(TIF_MEMDIE
))
2751 goto direct_uncharge
;
2754 goto direct_uncharge
;
2757 * In typical case, batch->memcg == mem. This means we can
2758 * merge a series of uncharges to an uncharge of res_counter.
2759 * If not, we uncharge res_counter ony by one.
2761 if (batch
->memcg
!= mem
)
2762 goto direct_uncharge
;
2763 /* remember freed charge and uncharge it later */
2766 batch
->memsw_nr_pages
++;
2769 res_counter_uncharge(&mem
->res
, nr_pages
* PAGE_SIZE
);
2771 res_counter_uncharge(&mem
->memsw
, nr_pages
* PAGE_SIZE
);
2772 if (unlikely(batch
->memcg
!= mem
))
2773 memcg_oom_recover(mem
);
2778 * uncharge if !page_mapped(page)
2780 static struct mem_cgroup
*
2781 __mem_cgroup_uncharge_common(struct page
*page
, enum charge_type ctype
)
2783 struct mem_cgroup
*mem
= NULL
;
2784 unsigned int nr_pages
= 1;
2785 struct page_cgroup
*pc
;
2787 if (mem_cgroup_disabled())
2790 if (PageSwapCache(page
))
2793 if (PageTransHuge(page
)) {
2794 nr_pages
<<= compound_order(page
);
2795 VM_BUG_ON(!PageTransHuge(page
));
2798 * Check if our page_cgroup is valid
2800 pc
= lookup_page_cgroup(page
);
2801 if (unlikely(!pc
|| !PageCgroupUsed(pc
)))
2804 lock_page_cgroup(pc
);
2806 mem
= pc
->mem_cgroup
;
2808 if (!PageCgroupUsed(pc
))
2812 case MEM_CGROUP_CHARGE_TYPE_MAPPED
:
2813 case MEM_CGROUP_CHARGE_TYPE_DROP
:
2814 /* See mem_cgroup_prepare_migration() */
2815 if (page_mapped(page
) || PageCgroupMigration(pc
))
2818 case MEM_CGROUP_CHARGE_TYPE_SWAPOUT
:
2819 if (!PageAnon(page
)) { /* Shared memory */
2820 if (page
->mapping
&& !page_is_file_cache(page
))
2822 } else if (page_mapped(page
)) /* Anon */
2829 mem_cgroup_charge_statistics(mem
, PageCgroupCache(pc
), -nr_pages
);
2831 ClearPageCgroupUsed(pc
);
2833 * pc->mem_cgroup is not cleared here. It will be accessed when it's
2834 * freed from LRU. This is safe because uncharged page is expected not
2835 * to be reused (freed soon). Exception is SwapCache, it's handled by
2836 * special functions.
2839 unlock_page_cgroup(pc
);
2841 * even after unlock, we have mem->res.usage here and this memcg
2842 * will never be freed.
2844 memcg_check_events(mem
, page
);
2845 if (do_swap_account
&& ctype
== MEM_CGROUP_CHARGE_TYPE_SWAPOUT
) {
2846 mem_cgroup_swap_statistics(mem
, true);
2847 mem_cgroup_get(mem
);
2849 if (!mem_cgroup_is_root(mem
))
2850 mem_cgroup_do_uncharge(mem
, nr_pages
, ctype
);
2855 unlock_page_cgroup(pc
);
2859 void mem_cgroup_uncharge_page(struct page
*page
)
2862 if (page_mapped(page
))
2864 if (page
->mapping
&& !PageAnon(page
))
2866 __mem_cgroup_uncharge_common(page
, MEM_CGROUP_CHARGE_TYPE_MAPPED
);
2869 void mem_cgroup_uncharge_cache_page(struct page
*page
)
2871 VM_BUG_ON(page_mapped(page
));
2872 VM_BUG_ON(page
->mapping
);
2873 __mem_cgroup_uncharge_common(page
, MEM_CGROUP_CHARGE_TYPE_CACHE
);
2877 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
2878 * In that cases, pages are freed continuously and we can expect pages
2879 * are in the same memcg. All these calls itself limits the number of
2880 * pages freed at once, then uncharge_start/end() is called properly.
2881 * This may be called prural(2) times in a context,
2884 void mem_cgroup_uncharge_start(void)
2886 current
->memcg_batch
.do_batch
++;
2887 /* We can do nest. */
2888 if (current
->memcg_batch
.do_batch
== 1) {
2889 current
->memcg_batch
.memcg
= NULL
;
2890 current
->memcg_batch
.nr_pages
= 0;
2891 current
->memcg_batch
.memsw_nr_pages
= 0;
2895 void mem_cgroup_uncharge_end(void)
2897 struct memcg_batch_info
*batch
= ¤t
->memcg_batch
;
2899 if (!batch
->do_batch
)
2903 if (batch
->do_batch
) /* If stacked, do nothing. */
2909 * This "batch->memcg" is valid without any css_get/put etc...
2910 * bacause we hide charges behind us.
2912 if (batch
->nr_pages
)
2913 res_counter_uncharge(&batch
->memcg
->res
,
2914 batch
->nr_pages
* PAGE_SIZE
);
2915 if (batch
->memsw_nr_pages
)
2916 res_counter_uncharge(&batch
->memcg
->memsw
,
2917 batch
->memsw_nr_pages
* PAGE_SIZE
);
2918 memcg_oom_recover(batch
->memcg
);
2919 /* forget this pointer (for sanity check) */
2920 batch
->memcg
= NULL
;
2925 * called after __delete_from_swap_cache() and drop "page" account.
2926 * memcg information is recorded to swap_cgroup of "ent"
2929 mem_cgroup_uncharge_swapcache(struct page
*page
, swp_entry_t ent
, bool swapout
)
2931 struct mem_cgroup
*memcg
;
2932 int ctype
= MEM_CGROUP_CHARGE_TYPE_SWAPOUT
;
2934 if (!swapout
) /* this was a swap cache but the swap is unused ! */
2935 ctype
= MEM_CGROUP_CHARGE_TYPE_DROP
;
2937 memcg
= __mem_cgroup_uncharge_common(page
, ctype
);
2940 * record memcg information, if swapout && memcg != NULL,
2941 * mem_cgroup_get() was called in uncharge().
2943 if (do_swap_account
&& swapout
&& memcg
)
2944 swap_cgroup_record(ent
, css_id(&memcg
->css
));
2948 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
2950 * called from swap_entry_free(). remove record in swap_cgroup and
2951 * uncharge "memsw" account.
2953 void mem_cgroup_uncharge_swap(swp_entry_t ent
)
2955 struct mem_cgroup
*memcg
;
2958 if (!do_swap_account
)
2961 id
= swap_cgroup_record(ent
, 0);
2963 memcg
= mem_cgroup_lookup(id
);
2966 * We uncharge this because swap is freed.
2967 * This memcg can be obsolete one. We avoid calling css_tryget
2969 if (!mem_cgroup_is_root(memcg
))
2970 res_counter_uncharge(&memcg
->memsw
, PAGE_SIZE
);
2971 mem_cgroup_swap_statistics(memcg
, false);
2972 mem_cgroup_put(memcg
);
2978 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
2979 * @entry: swap entry to be moved
2980 * @from: mem_cgroup which the entry is moved from
2981 * @to: mem_cgroup which the entry is moved to
2982 * @need_fixup: whether we should fixup res_counters and refcounts.
2984 * It succeeds only when the swap_cgroup's record for this entry is the same
2985 * as the mem_cgroup's id of @from.
2987 * Returns 0 on success, -EINVAL on failure.
2989 * The caller must have charged to @to, IOW, called res_counter_charge() about
2990 * both res and memsw, and called css_get().
2992 static int mem_cgroup_move_swap_account(swp_entry_t entry
,
2993 struct mem_cgroup
*from
, struct mem_cgroup
*to
, bool need_fixup
)
2995 unsigned short old_id
, new_id
;
2997 old_id
= css_id(&from
->css
);
2998 new_id
= css_id(&to
->css
);
3000 if (swap_cgroup_cmpxchg(entry
, old_id
, new_id
) == old_id
) {
3001 mem_cgroup_swap_statistics(from
, false);
3002 mem_cgroup_swap_statistics(to
, true);
3004 * This function is only called from task migration context now.
3005 * It postpones res_counter and refcount handling till the end
3006 * of task migration(mem_cgroup_clear_mc()) for performance
3007 * improvement. But we cannot postpone mem_cgroup_get(to)
3008 * because if the process that has been moved to @to does
3009 * swap-in, the refcount of @to might be decreased to 0.
3013 if (!mem_cgroup_is_root(from
))
3014 res_counter_uncharge(&from
->memsw
, PAGE_SIZE
);
3015 mem_cgroup_put(from
);
3017 * we charged both to->res and to->memsw, so we should
3020 if (!mem_cgroup_is_root(to
))
3021 res_counter_uncharge(&to
->res
, PAGE_SIZE
);
3028 static inline int mem_cgroup_move_swap_account(swp_entry_t entry
,
3029 struct mem_cgroup
*from
, struct mem_cgroup
*to
, bool need_fixup
)
3036 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
3039 int mem_cgroup_prepare_migration(struct page
*page
,
3040 struct page
*newpage
, struct mem_cgroup
**ptr
, gfp_t gfp_mask
)
3042 struct mem_cgroup
*mem
= NULL
;
3043 struct page_cgroup
*pc
;
3044 enum charge_type ctype
;
3049 VM_BUG_ON(PageTransHuge(page
));
3050 if (mem_cgroup_disabled())
3053 pc
= lookup_page_cgroup(page
);
3054 lock_page_cgroup(pc
);
3055 if (PageCgroupUsed(pc
)) {
3056 mem
= pc
->mem_cgroup
;
3059 * At migrating an anonymous page, its mapcount goes down
3060 * to 0 and uncharge() will be called. But, even if it's fully
3061 * unmapped, migration may fail and this page has to be
3062 * charged again. We set MIGRATION flag here and delay uncharge
3063 * until end_migration() is called
3065 * Corner Case Thinking
3067 * When the old page was mapped as Anon and it's unmap-and-freed
3068 * while migration was ongoing.
3069 * If unmap finds the old page, uncharge() of it will be delayed
3070 * until end_migration(). If unmap finds a new page, it's
3071 * uncharged when it make mapcount to be 1->0. If unmap code
3072 * finds swap_migration_entry, the new page will not be mapped
3073 * and end_migration() will find it(mapcount==0).
3076 * When the old page was mapped but migraion fails, the kernel
3077 * remaps it. A charge for it is kept by MIGRATION flag even
3078 * if mapcount goes down to 0. We can do remap successfully
3079 * without charging it again.
3082 * The "old" page is under lock_page() until the end of
3083 * migration, so, the old page itself will not be swapped-out.
3084 * If the new page is swapped out before end_migraton, our
3085 * hook to usual swap-out path will catch the event.
3088 SetPageCgroupMigration(pc
);
3090 unlock_page_cgroup(pc
);
3092 * If the page is not charged at this point,
3099 ret
= __mem_cgroup_try_charge(NULL
, gfp_mask
, 1, ptr
, false);
3100 css_put(&mem
->css
);/* drop extra refcnt */
3101 if (ret
|| *ptr
== NULL
) {
3102 if (PageAnon(page
)) {
3103 lock_page_cgroup(pc
);
3104 ClearPageCgroupMigration(pc
);
3105 unlock_page_cgroup(pc
);
3107 * The old page may be fully unmapped while we kept it.
3109 mem_cgroup_uncharge_page(page
);
3114 * We charge new page before it's used/mapped. So, even if unlock_page()
3115 * is called before end_migration, we can catch all events on this new
3116 * page. In the case new page is migrated but not remapped, new page's
3117 * mapcount will be finally 0 and we call uncharge in end_migration().
3119 pc
= lookup_page_cgroup(newpage
);
3121 ctype
= MEM_CGROUP_CHARGE_TYPE_MAPPED
;
3122 else if (page_is_file_cache(page
))
3123 ctype
= MEM_CGROUP_CHARGE_TYPE_CACHE
;
3125 ctype
= MEM_CGROUP_CHARGE_TYPE_SHMEM
;
3126 __mem_cgroup_commit_charge(mem
, page
, 1, pc
, ctype
);
3130 /* remove redundant charge if migration failed*/
3131 void mem_cgroup_end_migration(struct mem_cgroup
*mem
,
3132 struct page
*oldpage
, struct page
*newpage
, bool migration_ok
)
3134 struct page
*used
, *unused
;
3135 struct page_cgroup
*pc
;
3139 /* blocks rmdir() */
3140 cgroup_exclude_rmdir(&mem
->css
);
3141 if (!migration_ok
) {
3149 * We disallowed uncharge of pages under migration because mapcount
3150 * of the page goes down to zero, temporarly.
3151 * Clear the flag and check the page should be charged.
3153 pc
= lookup_page_cgroup(oldpage
);
3154 lock_page_cgroup(pc
);
3155 ClearPageCgroupMigration(pc
);
3156 unlock_page_cgroup(pc
);
3158 __mem_cgroup_uncharge_common(unused
, MEM_CGROUP_CHARGE_TYPE_FORCE
);
3161 * If a page is a file cache, radix-tree replacement is very atomic
3162 * and we can skip this check. When it was an Anon page, its mapcount
3163 * goes down to 0. But because we added MIGRATION flage, it's not
3164 * uncharged yet. There are several case but page->mapcount check
3165 * and USED bit check in mem_cgroup_uncharge_page() will do enough
3166 * check. (see prepare_charge() also)
3169 mem_cgroup_uncharge_page(used
);
3171 * At migration, we may charge account against cgroup which has no
3173 * So, rmdir()->pre_destroy() can be called while we do this charge.
3174 * In that case, we need to call pre_destroy() again. check it here.
3176 cgroup_release_and_wakeup_rmdir(&mem
->css
);
3180 * A call to try to shrink memory usage on charge failure at shmem's swapin.
3181 * Calling hierarchical_reclaim is not enough because we should update
3182 * last_oom_jiffies to prevent pagefault_out_of_memory from invoking global OOM.
3183 * Moreover considering hierarchy, we should reclaim from the mem_over_limit,
3184 * not from the memcg which this page would be charged to.
3185 * try_charge_swapin does all of these works properly.
3187 int mem_cgroup_shmem_charge_fallback(struct page
*page
,
3188 struct mm_struct
*mm
,
3191 struct mem_cgroup
*mem
;
3194 if (mem_cgroup_disabled())
3197 ret
= mem_cgroup_try_charge_swapin(mm
, page
, gfp_mask
, &mem
);
3199 mem_cgroup_cancel_charge_swapin(mem
); /* it does !mem check */
3204 #ifdef CONFIG_DEBUG_VM
3205 static struct page_cgroup
*lookup_page_cgroup_used(struct page
*page
)
3207 struct page_cgroup
*pc
;
3209 pc
= lookup_page_cgroup(page
);
3210 if (likely(pc
) && PageCgroupUsed(pc
))
3215 bool mem_cgroup_bad_page_check(struct page
*page
)
3217 if (mem_cgroup_disabled())
3220 return lookup_page_cgroup_used(page
) != NULL
;
3223 void mem_cgroup_print_bad_page(struct page
*page
)
3225 struct page_cgroup
*pc
;
3227 pc
= lookup_page_cgroup_used(page
);
3232 printk(KERN_ALERT
"pc:%p pc->flags:%lx pc->mem_cgroup:%p",
3233 pc
, pc
->flags
, pc
->mem_cgroup
);
3235 path
= kmalloc(PATH_MAX
, GFP_KERNEL
);
3238 ret
= cgroup_path(pc
->mem_cgroup
->css
.cgroup
,
3243 printk(KERN_CONT
"(%s)\n",
3244 (ret
< 0) ? "cannot get the path" : path
);
3250 static DEFINE_MUTEX(set_limit_mutex
);
3252 static int mem_cgroup_resize_limit(struct mem_cgroup
*memcg
,
3253 unsigned long long val
)
3256 u64 memswlimit
, memlimit
;
3258 int children
= mem_cgroup_count_children(memcg
);
3259 u64 curusage
, oldusage
;
3263 * For keeping hierarchical_reclaim simple, how long we should retry
3264 * is depends on callers. We set our retry-count to be function
3265 * of # of children which we should visit in this loop.
3267 retry_count
= MEM_CGROUP_RECLAIM_RETRIES
* children
;
3269 oldusage
= res_counter_read_u64(&memcg
->res
, RES_USAGE
);
3272 while (retry_count
) {
3273 if (signal_pending(current
)) {
3278 * Rather than hide all in some function, I do this in
3279 * open coded manner. You see what this really does.
3280 * We have to guarantee mem->res.limit < mem->memsw.limit.
3282 mutex_lock(&set_limit_mutex
);
3283 memswlimit
= res_counter_read_u64(&memcg
->memsw
, RES_LIMIT
);
3284 if (memswlimit
< val
) {
3286 mutex_unlock(&set_limit_mutex
);
3290 memlimit
= res_counter_read_u64(&memcg
->res
, RES_LIMIT
);
3294 ret
= res_counter_set_limit(&memcg
->res
, val
);
3296 if (memswlimit
== val
)
3297 memcg
->memsw_is_minimum
= true;
3299 memcg
->memsw_is_minimum
= false;
3301 mutex_unlock(&set_limit_mutex
);
3306 mem_cgroup_hierarchical_reclaim(memcg
, NULL
, GFP_KERNEL
,
3307 MEM_CGROUP_RECLAIM_SHRINK
,
3309 curusage
= res_counter_read_u64(&memcg
->res
, RES_USAGE
);
3310 /* Usage is reduced ? */
3311 if (curusage
>= oldusage
)
3314 oldusage
= curusage
;
3316 if (!ret
&& enlarge
)
3317 memcg_oom_recover(memcg
);
3322 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup
*memcg
,
3323 unsigned long long val
)
3326 u64 memlimit
, memswlimit
, oldusage
, curusage
;
3327 int children
= mem_cgroup_count_children(memcg
);
3331 /* see mem_cgroup_resize_res_limit */
3332 retry_count
= children
* MEM_CGROUP_RECLAIM_RETRIES
;
3333 oldusage
= res_counter_read_u64(&memcg
->memsw
, RES_USAGE
);
3334 while (retry_count
) {
3335 if (signal_pending(current
)) {
3340 * Rather than hide all in some function, I do this in
3341 * open coded manner. You see what this really does.
3342 * We have to guarantee mem->res.limit < mem->memsw.limit.
3344 mutex_lock(&set_limit_mutex
);
3345 memlimit
= res_counter_read_u64(&memcg
->res
, RES_LIMIT
);
3346 if (memlimit
> val
) {
3348 mutex_unlock(&set_limit_mutex
);
3351 memswlimit
= res_counter_read_u64(&memcg
->memsw
, RES_LIMIT
);
3352 if (memswlimit
< val
)
3354 ret
= res_counter_set_limit(&memcg
->memsw
, val
);
3356 if (memlimit
== val
)
3357 memcg
->memsw_is_minimum
= true;
3359 memcg
->memsw_is_minimum
= false;
3361 mutex_unlock(&set_limit_mutex
);
3366 mem_cgroup_hierarchical_reclaim(memcg
, NULL
, GFP_KERNEL
,
3367 MEM_CGROUP_RECLAIM_NOSWAP
|
3368 MEM_CGROUP_RECLAIM_SHRINK
,
3370 curusage
= res_counter_read_u64(&memcg
->memsw
, RES_USAGE
);
3371 /* Usage is reduced ? */
3372 if (curusage
>= oldusage
)
3375 oldusage
= curusage
;
3377 if (!ret
&& enlarge
)
3378 memcg_oom_recover(memcg
);
3382 unsigned long mem_cgroup_soft_limit_reclaim(struct zone
*zone
, int order
,
3384 unsigned long *total_scanned
)
3386 unsigned long nr_reclaimed
= 0;
3387 struct mem_cgroup_per_zone
*mz
, *next_mz
= NULL
;
3388 unsigned long reclaimed
;
3390 struct mem_cgroup_tree_per_zone
*mctz
;
3391 unsigned long long excess
;
3392 unsigned long nr_scanned
;
3397 mctz
= soft_limit_tree_node_zone(zone_to_nid(zone
), zone_idx(zone
));
3399 * This loop can run a while, specially if mem_cgroup's continuously
3400 * keep exceeding their soft limit and putting the system under
3407 mz
= mem_cgroup_largest_soft_limit_node(mctz
);
3412 reclaimed
= mem_cgroup_hierarchical_reclaim(mz
->mem
, zone
,
3414 MEM_CGROUP_RECLAIM_SOFT
,
3416 nr_reclaimed
+= reclaimed
;
3417 *total_scanned
+= nr_scanned
;
3418 spin_lock(&mctz
->lock
);
3421 * If we failed to reclaim anything from this memory cgroup
3422 * it is time to move on to the next cgroup
3428 * Loop until we find yet another one.
3430 * By the time we get the soft_limit lock
3431 * again, someone might have aded the
3432 * group back on the RB tree. Iterate to
3433 * make sure we get a different mem.
3434 * mem_cgroup_largest_soft_limit_node returns
3435 * NULL if no other cgroup is present on
3439 __mem_cgroup_largest_soft_limit_node(mctz
);
3441 css_put(&next_mz
->mem
->css
);
3442 else /* next_mz == NULL or other memcg */
3446 __mem_cgroup_remove_exceeded(mz
->mem
, mz
, mctz
);
3447 excess
= res_counter_soft_limit_excess(&mz
->mem
->res
);
3449 * One school of thought says that we should not add
3450 * back the node to the tree if reclaim returns 0.
3451 * But our reclaim could return 0, simply because due
3452 * to priority we are exposing a smaller subset of
3453 * memory to reclaim from. Consider this as a longer
3456 /* If excess == 0, no tree ops */
3457 __mem_cgroup_insert_exceeded(mz
->mem
, mz
, mctz
, excess
);
3458 spin_unlock(&mctz
->lock
);
3459 css_put(&mz
->mem
->css
);
3462 * Could not reclaim anything and there are no more
3463 * mem cgroups to try or we seem to be looping without
3464 * reclaiming anything.
3466 if (!nr_reclaimed
&&
3468 loop
> MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS
))
3470 } while (!nr_reclaimed
);
3472 css_put(&next_mz
->mem
->css
);
3473 return nr_reclaimed
;
3477 * This routine traverse page_cgroup in given list and drop them all.
3478 * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
3480 static int mem_cgroup_force_empty_list(struct mem_cgroup
*mem
,
3481 int node
, int zid
, enum lru_list lru
)
3484 struct mem_cgroup_per_zone
*mz
;
3485 struct page_cgroup
*pc
, *busy
;
3486 unsigned long flags
, loop
;
3487 struct list_head
*list
;
3490 zone
= &NODE_DATA(node
)->node_zones
[zid
];
3491 mz
= mem_cgroup_zoneinfo(mem
, node
, zid
);
3492 list
= &mz
->lists
[lru
];
3494 loop
= MEM_CGROUP_ZSTAT(mz
, lru
);
3495 /* give some margin against EBUSY etc...*/
3502 spin_lock_irqsave(&zone
->lru_lock
, flags
);
3503 if (list_empty(list
)) {
3504 spin_unlock_irqrestore(&zone
->lru_lock
, flags
);
3507 pc
= list_entry(list
->prev
, struct page_cgroup
, lru
);
3509 list_move(&pc
->lru
, list
);
3511 spin_unlock_irqrestore(&zone
->lru_lock
, flags
);
3514 spin_unlock_irqrestore(&zone
->lru_lock
, flags
);
3516 page
= lookup_cgroup_page(pc
);
3518 ret
= mem_cgroup_move_parent(page
, pc
, mem
, GFP_KERNEL
);
3522 if (ret
== -EBUSY
|| ret
== -EINVAL
) {
3523 /* found lock contention or "pc" is obsolete. */
3530 if (!ret
&& !list_empty(list
))
3536 * make mem_cgroup's charge to be 0 if there is no task.
3537 * This enables deleting this mem_cgroup.
3539 static int mem_cgroup_force_empty(struct mem_cgroup
*mem
, bool free_all
)
3542 int node
, zid
, shrink
;
3543 int nr_retries
= MEM_CGROUP_RECLAIM_RETRIES
;
3544 struct cgroup
*cgrp
= mem
->css
.cgroup
;
3549 /* should free all ? */
3555 if (cgroup_task_count(cgrp
) || !list_empty(&cgrp
->children
))
3558 if (signal_pending(current
))
3560 /* This is for making all *used* pages to be on LRU. */
3561 lru_add_drain_all();
3562 drain_all_stock_sync();
3564 mem_cgroup_start_move(mem
);
3565 for_each_node_state(node
, N_HIGH_MEMORY
) {
3566 for (zid
= 0; !ret
&& zid
< MAX_NR_ZONES
; zid
++) {
3569 ret
= mem_cgroup_force_empty_list(mem
,
3578 mem_cgroup_end_move(mem
);
3579 memcg_oom_recover(mem
);
3580 /* it seems parent cgroup doesn't have enough mem */
3584 /* "ret" should also be checked to ensure all lists are empty. */
3585 } while (mem
->res
.usage
> 0 || ret
);
3591 /* returns EBUSY if there is a task or if we come here twice. */
3592 if (cgroup_task_count(cgrp
) || !list_empty(&cgrp
->children
) || shrink
) {
3596 /* we call try-to-free pages for make this cgroup empty */
3597 lru_add_drain_all();
3598 /* try to free all pages in this cgroup */
3600 while (nr_retries
&& mem
->res
.usage
> 0) {
3603 if (signal_pending(current
)) {
3607 progress
= try_to_free_mem_cgroup_pages(mem
, GFP_KERNEL
,
3608 false, get_swappiness(mem
));
3611 /* maybe some writeback is necessary */
3612 congestion_wait(BLK_RW_ASYNC
, HZ
/10);
3617 /* try move_account...there may be some *locked* pages. */
3621 int mem_cgroup_force_empty_write(struct cgroup
*cont
, unsigned int event
)
3623 return mem_cgroup_force_empty(mem_cgroup_from_cont(cont
), true);
3627 static u64
mem_cgroup_hierarchy_read(struct cgroup
*cont
, struct cftype
*cft
)
3629 return mem_cgroup_from_cont(cont
)->use_hierarchy
;
3632 static int mem_cgroup_hierarchy_write(struct cgroup
*cont
, struct cftype
*cft
,
3636 struct mem_cgroup
*mem
= mem_cgroup_from_cont(cont
);
3637 struct cgroup
*parent
= cont
->parent
;
3638 struct mem_cgroup
*parent_mem
= NULL
;
3641 parent_mem
= mem_cgroup_from_cont(parent
);
3645 * If parent's use_hierarchy is set, we can't make any modifications
3646 * in the child subtrees. If it is unset, then the change can
3647 * occur, provided the current cgroup has no children.
3649 * For the root cgroup, parent_mem is NULL, we allow value to be
3650 * set if there are no children.
3652 if ((!parent_mem
|| !parent_mem
->use_hierarchy
) &&
3653 (val
== 1 || val
== 0)) {
3654 if (list_empty(&cont
->children
))
3655 mem
->use_hierarchy
= val
;
3666 static unsigned long mem_cgroup_recursive_stat(struct mem_cgroup
*mem
,
3667 enum mem_cgroup_stat_index idx
)
3669 struct mem_cgroup
*iter
;
3672 /* Per-cpu values can be negative, use a signed accumulator */
3673 for_each_mem_cgroup_tree(iter
, mem
)
3674 val
+= mem_cgroup_read_stat(iter
, idx
);
3676 if (val
< 0) /* race ? */
3681 static inline u64
mem_cgroup_usage(struct mem_cgroup
*mem
, bool swap
)
3685 if (!mem_cgroup_is_root(mem
)) {
3687 return res_counter_read_u64(&mem
->res
, RES_USAGE
);
3689 return res_counter_read_u64(&mem
->memsw
, RES_USAGE
);
3692 val
= mem_cgroup_recursive_stat(mem
, MEM_CGROUP_STAT_CACHE
);
3693 val
+= mem_cgroup_recursive_stat(mem
, MEM_CGROUP_STAT_RSS
);
3696 val
+= mem_cgroup_recursive_stat(mem
, MEM_CGROUP_STAT_SWAPOUT
);
3698 return val
<< PAGE_SHIFT
;
3701 static u64
mem_cgroup_read(struct cgroup
*cont
, struct cftype
*cft
)
3703 struct mem_cgroup
*mem
= mem_cgroup_from_cont(cont
);
3707 type
= MEMFILE_TYPE(cft
->private);
3708 name
= MEMFILE_ATTR(cft
->private);
3711 if (name
== RES_USAGE
)
3712 val
= mem_cgroup_usage(mem
, false);
3714 val
= res_counter_read_u64(&mem
->res
, name
);
3717 if (name
== RES_USAGE
)
3718 val
= mem_cgroup_usage(mem
, true);
3720 val
= res_counter_read_u64(&mem
->memsw
, name
);
3729 * The user of this function is...
3732 static int mem_cgroup_write(struct cgroup
*cont
, struct cftype
*cft
,
3735 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cont
);
3737 unsigned long long val
;
3740 type
= MEMFILE_TYPE(cft
->private);
3741 name
= MEMFILE_ATTR(cft
->private);
3744 if (mem_cgroup_is_root(memcg
)) { /* Can't set limit on root */
3748 /* This function does all necessary parse...reuse it */
3749 ret
= res_counter_memparse_write_strategy(buffer
, &val
);
3753 ret
= mem_cgroup_resize_limit(memcg
, val
);
3755 ret
= mem_cgroup_resize_memsw_limit(memcg
, val
);
3757 case RES_SOFT_LIMIT
:
3758 ret
= res_counter_memparse_write_strategy(buffer
, &val
);
3762 * For memsw, soft limits are hard to implement in terms
3763 * of semantics, for now, we support soft limits for
3764 * control without swap
3767 ret
= res_counter_set_soft_limit(&memcg
->res
, val
);
3772 ret
= -EINVAL
; /* should be BUG() ? */
3778 static void memcg_get_hierarchical_limit(struct mem_cgroup
*memcg
,
3779 unsigned long long *mem_limit
, unsigned long long *memsw_limit
)
3781 struct cgroup
*cgroup
;
3782 unsigned long long min_limit
, min_memsw_limit
, tmp
;
3784 min_limit
= res_counter_read_u64(&memcg
->res
, RES_LIMIT
);
3785 min_memsw_limit
= res_counter_read_u64(&memcg
->memsw
, RES_LIMIT
);
3786 cgroup
= memcg
->css
.cgroup
;
3787 if (!memcg
->use_hierarchy
)
3790 while (cgroup
->parent
) {
3791 cgroup
= cgroup
->parent
;
3792 memcg
= mem_cgroup_from_cont(cgroup
);
3793 if (!memcg
->use_hierarchy
)
3795 tmp
= res_counter_read_u64(&memcg
->res
, RES_LIMIT
);
3796 min_limit
= min(min_limit
, tmp
);
3797 tmp
= res_counter_read_u64(&memcg
->memsw
, RES_LIMIT
);
3798 min_memsw_limit
= min(min_memsw_limit
, tmp
);
3801 *mem_limit
= min_limit
;
3802 *memsw_limit
= min_memsw_limit
;
3806 static int mem_cgroup_reset(struct cgroup
*cont
, unsigned int event
)
3808 struct mem_cgroup
*mem
;
3811 mem
= mem_cgroup_from_cont(cont
);
3812 type
= MEMFILE_TYPE(event
);
3813 name
= MEMFILE_ATTR(event
);
3817 res_counter_reset_max(&mem
->res
);
3819 res_counter_reset_max(&mem
->memsw
);
3823 res_counter_reset_failcnt(&mem
->res
);
3825 res_counter_reset_failcnt(&mem
->memsw
);
3832 static u64
mem_cgroup_move_charge_read(struct cgroup
*cgrp
,
3835 return mem_cgroup_from_cont(cgrp
)->move_charge_at_immigrate
;
3839 static int mem_cgroup_move_charge_write(struct cgroup
*cgrp
,
3840 struct cftype
*cft
, u64 val
)
3842 struct mem_cgroup
*mem
= mem_cgroup_from_cont(cgrp
);
3844 if (val
>= (1 << NR_MOVE_TYPE
))
3847 * We check this value several times in both in can_attach() and
3848 * attach(), so we need cgroup lock to prevent this value from being
3852 mem
->move_charge_at_immigrate
= val
;
3858 static int mem_cgroup_move_charge_write(struct cgroup
*cgrp
,
3859 struct cftype
*cft
, u64 val
)
3866 /* For read statistics */
3882 struct mcs_total_stat
{
3883 s64 stat
[NR_MCS_STAT
];
3889 } memcg_stat_strings
[NR_MCS_STAT
] = {
3890 {"cache", "total_cache"},
3891 {"rss", "total_rss"},
3892 {"mapped_file", "total_mapped_file"},
3893 {"pgpgin", "total_pgpgin"},
3894 {"pgpgout", "total_pgpgout"},
3895 {"swap", "total_swap"},
3896 {"inactive_anon", "total_inactive_anon"},
3897 {"active_anon", "total_active_anon"},
3898 {"inactive_file", "total_inactive_file"},
3899 {"active_file", "total_active_file"},
3900 {"unevictable", "total_unevictable"}
3905 mem_cgroup_get_local_stat(struct mem_cgroup
*mem
, struct mcs_total_stat
*s
)
3910 val
= mem_cgroup_read_stat(mem
, MEM_CGROUP_STAT_CACHE
);
3911 s
->stat
[MCS_CACHE
] += val
* PAGE_SIZE
;
3912 val
= mem_cgroup_read_stat(mem
, MEM_CGROUP_STAT_RSS
);
3913 s
->stat
[MCS_RSS
] += val
* PAGE_SIZE
;
3914 val
= mem_cgroup_read_stat(mem
, MEM_CGROUP_STAT_FILE_MAPPED
);
3915 s
->stat
[MCS_FILE_MAPPED
] += val
* PAGE_SIZE
;
3916 val
= mem_cgroup_read_events(mem
, MEM_CGROUP_EVENTS_PGPGIN
);
3917 s
->stat
[MCS_PGPGIN
] += val
;
3918 val
= mem_cgroup_read_events(mem
, MEM_CGROUP_EVENTS_PGPGOUT
);
3919 s
->stat
[MCS_PGPGOUT
] += val
;
3920 if (do_swap_account
) {
3921 val
= mem_cgroup_read_stat(mem
, MEM_CGROUP_STAT_SWAPOUT
);
3922 s
->stat
[MCS_SWAP
] += val
* PAGE_SIZE
;
3926 val
= mem_cgroup_get_local_zonestat(mem
, LRU_INACTIVE_ANON
);
3927 s
->stat
[MCS_INACTIVE_ANON
] += val
* PAGE_SIZE
;
3928 val
= mem_cgroup_get_local_zonestat(mem
, LRU_ACTIVE_ANON
);
3929 s
->stat
[MCS_ACTIVE_ANON
] += val
* PAGE_SIZE
;
3930 val
= mem_cgroup_get_local_zonestat(mem
, LRU_INACTIVE_FILE
);
3931 s
->stat
[MCS_INACTIVE_FILE
] += val
* PAGE_SIZE
;
3932 val
= mem_cgroup_get_local_zonestat(mem
, LRU_ACTIVE_FILE
);
3933 s
->stat
[MCS_ACTIVE_FILE
] += val
* PAGE_SIZE
;
3934 val
= mem_cgroup_get_local_zonestat(mem
, LRU_UNEVICTABLE
);
3935 s
->stat
[MCS_UNEVICTABLE
] += val
* PAGE_SIZE
;
3939 mem_cgroup_get_total_stat(struct mem_cgroup
*mem
, struct mcs_total_stat
*s
)
3941 struct mem_cgroup
*iter
;
3943 for_each_mem_cgroup_tree(iter
, mem
)
3944 mem_cgroup_get_local_stat(iter
, s
);
3947 static int mem_control_stat_show(struct cgroup
*cont
, struct cftype
*cft
,
3948 struct cgroup_map_cb
*cb
)
3950 struct mem_cgroup
*mem_cont
= mem_cgroup_from_cont(cont
);
3951 struct mcs_total_stat mystat
;
3954 memset(&mystat
, 0, sizeof(mystat
));
3955 mem_cgroup_get_local_stat(mem_cont
, &mystat
);
3957 for (i
= 0; i
< NR_MCS_STAT
; i
++) {
3958 if (i
== MCS_SWAP
&& !do_swap_account
)
3960 cb
->fill(cb
, memcg_stat_strings
[i
].local_name
, mystat
.stat
[i
]);
3963 /* Hierarchical information */
3965 unsigned long long limit
, memsw_limit
;
3966 memcg_get_hierarchical_limit(mem_cont
, &limit
, &memsw_limit
);
3967 cb
->fill(cb
, "hierarchical_memory_limit", limit
);
3968 if (do_swap_account
)
3969 cb
->fill(cb
, "hierarchical_memsw_limit", memsw_limit
);
3972 memset(&mystat
, 0, sizeof(mystat
));
3973 mem_cgroup_get_total_stat(mem_cont
, &mystat
);
3974 for (i
= 0; i
< NR_MCS_STAT
; i
++) {
3975 if (i
== MCS_SWAP
&& !do_swap_account
)
3977 cb
->fill(cb
, memcg_stat_strings
[i
].total_name
, mystat
.stat
[i
]);
3980 #ifdef CONFIG_DEBUG_VM
3981 cb
->fill(cb
, "inactive_ratio", calc_inactive_ratio(mem_cont
, NULL
));
3985 struct mem_cgroup_per_zone
*mz
;
3986 unsigned long recent_rotated
[2] = {0, 0};
3987 unsigned long recent_scanned
[2] = {0, 0};
3989 for_each_online_node(nid
)
3990 for (zid
= 0; zid
< MAX_NR_ZONES
; zid
++) {
3991 mz
= mem_cgroup_zoneinfo(mem_cont
, nid
, zid
);
3993 recent_rotated
[0] +=
3994 mz
->reclaim_stat
.recent_rotated
[0];
3995 recent_rotated
[1] +=
3996 mz
->reclaim_stat
.recent_rotated
[1];
3997 recent_scanned
[0] +=
3998 mz
->reclaim_stat
.recent_scanned
[0];
3999 recent_scanned
[1] +=
4000 mz
->reclaim_stat
.recent_scanned
[1];
4002 cb
->fill(cb
, "recent_rotated_anon", recent_rotated
[0]);
4003 cb
->fill(cb
, "recent_rotated_file", recent_rotated
[1]);
4004 cb
->fill(cb
, "recent_scanned_anon", recent_scanned
[0]);
4005 cb
->fill(cb
, "recent_scanned_file", recent_scanned
[1]);
4012 static u64
mem_cgroup_swappiness_read(struct cgroup
*cgrp
, struct cftype
*cft
)
4014 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cgrp
);
4016 return get_swappiness(memcg
);
4019 static int mem_cgroup_swappiness_write(struct cgroup
*cgrp
, struct cftype
*cft
,
4022 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cgrp
);
4023 struct mem_cgroup
*parent
;
4028 if (cgrp
->parent
== NULL
)
4031 parent
= mem_cgroup_from_cont(cgrp
->parent
);
4035 /* If under hierarchy, only empty-root can set this value */
4036 if ((parent
->use_hierarchy
) ||
4037 (memcg
->use_hierarchy
&& !list_empty(&cgrp
->children
))) {
4042 memcg
->swappiness
= val
;
4049 static void __mem_cgroup_threshold(struct mem_cgroup
*memcg
, bool swap
)
4051 struct mem_cgroup_threshold_ary
*t
;
4057 t
= rcu_dereference(memcg
->thresholds
.primary
);
4059 t
= rcu_dereference(memcg
->memsw_thresholds
.primary
);
4064 usage
= mem_cgroup_usage(memcg
, swap
);
4067 * current_threshold points to threshold just below usage.
4068 * If it's not true, a threshold was crossed after last
4069 * call of __mem_cgroup_threshold().
4071 i
= t
->current_threshold
;
4074 * Iterate backward over array of thresholds starting from
4075 * current_threshold and check if a threshold is crossed.
4076 * If none of thresholds below usage is crossed, we read
4077 * only one element of the array here.
4079 for (; i
>= 0 && unlikely(t
->entries
[i
].threshold
> usage
); i
--)
4080 eventfd_signal(t
->entries
[i
].eventfd
, 1);
4082 /* i = current_threshold + 1 */
4086 * Iterate forward over array of thresholds starting from
4087 * current_threshold+1 and check if a threshold is crossed.
4088 * If none of thresholds above usage is crossed, we read
4089 * only one element of the array here.
4091 for (; i
< t
->size
&& unlikely(t
->entries
[i
].threshold
<= usage
); i
++)
4092 eventfd_signal(t
->entries
[i
].eventfd
, 1);
4094 /* Update current_threshold */
4095 t
->current_threshold
= i
- 1;
4100 static void mem_cgroup_threshold(struct mem_cgroup
*memcg
)
4103 __mem_cgroup_threshold(memcg
, false);
4104 if (do_swap_account
)
4105 __mem_cgroup_threshold(memcg
, true);
4107 memcg
= parent_mem_cgroup(memcg
);
4111 static int compare_thresholds(const void *a
, const void *b
)
4113 const struct mem_cgroup_threshold
*_a
= a
;
4114 const struct mem_cgroup_threshold
*_b
= b
;
4116 return _a
->threshold
- _b
->threshold
;
4119 static int mem_cgroup_oom_notify_cb(struct mem_cgroup
*mem
)
4121 struct mem_cgroup_eventfd_list
*ev
;
4123 list_for_each_entry(ev
, &mem
->oom_notify
, list
)
4124 eventfd_signal(ev
->eventfd
, 1);
4128 static void mem_cgroup_oom_notify(struct mem_cgroup
*mem
)
4130 struct mem_cgroup
*iter
;
4132 for_each_mem_cgroup_tree(iter
, mem
)
4133 mem_cgroup_oom_notify_cb(iter
);
4136 static int mem_cgroup_usage_register_event(struct cgroup
*cgrp
,
4137 struct cftype
*cft
, struct eventfd_ctx
*eventfd
, const char *args
)
4139 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cgrp
);
4140 struct mem_cgroup_thresholds
*thresholds
;
4141 struct mem_cgroup_threshold_ary
*new;
4142 int type
= MEMFILE_TYPE(cft
->private);
4143 u64 threshold
, usage
;
4146 ret
= res_counter_memparse_write_strategy(args
, &threshold
);
4150 mutex_lock(&memcg
->thresholds_lock
);
4153 thresholds
= &memcg
->thresholds
;
4154 else if (type
== _MEMSWAP
)
4155 thresholds
= &memcg
->memsw_thresholds
;
4159 usage
= mem_cgroup_usage(memcg
, type
== _MEMSWAP
);
4161 /* Check if a threshold crossed before adding a new one */
4162 if (thresholds
->primary
)
4163 __mem_cgroup_threshold(memcg
, type
== _MEMSWAP
);
4165 size
= thresholds
->primary
? thresholds
->primary
->size
+ 1 : 1;
4167 /* Allocate memory for new array of thresholds */
4168 new = kmalloc(sizeof(*new) + size
* sizeof(struct mem_cgroup_threshold
),
4176 /* Copy thresholds (if any) to new array */
4177 if (thresholds
->primary
) {
4178 memcpy(new->entries
, thresholds
->primary
->entries
, (size
- 1) *
4179 sizeof(struct mem_cgroup_threshold
));
4182 /* Add new threshold */
4183 new->entries
[size
- 1].eventfd
= eventfd
;
4184 new->entries
[size
- 1].threshold
= threshold
;
4186 /* Sort thresholds. Registering of new threshold isn't time-critical */
4187 sort(new->entries
, size
, sizeof(struct mem_cgroup_threshold
),
4188 compare_thresholds
, NULL
);
4190 /* Find current threshold */
4191 new->current_threshold
= -1;
4192 for (i
= 0; i
< size
; i
++) {
4193 if (new->entries
[i
].threshold
< usage
) {
4195 * new->current_threshold will not be used until
4196 * rcu_assign_pointer(), so it's safe to increment
4199 ++new->current_threshold
;
4203 /* Free old spare buffer and save old primary buffer as spare */
4204 kfree(thresholds
->spare
);
4205 thresholds
->spare
= thresholds
->primary
;
4207 rcu_assign_pointer(thresholds
->primary
, new);
4209 /* To be sure that nobody uses thresholds */
4213 mutex_unlock(&memcg
->thresholds_lock
);
4218 static void mem_cgroup_usage_unregister_event(struct cgroup
*cgrp
,
4219 struct cftype
*cft
, struct eventfd_ctx
*eventfd
)
4221 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cgrp
);
4222 struct mem_cgroup_thresholds
*thresholds
;
4223 struct mem_cgroup_threshold_ary
*new;
4224 int type
= MEMFILE_TYPE(cft
->private);
4228 mutex_lock(&memcg
->thresholds_lock
);
4230 thresholds
= &memcg
->thresholds
;
4231 else if (type
== _MEMSWAP
)
4232 thresholds
= &memcg
->memsw_thresholds
;
4237 * Something went wrong if we trying to unregister a threshold
4238 * if we don't have thresholds
4240 BUG_ON(!thresholds
);
4242 usage
= mem_cgroup_usage(memcg
, type
== _MEMSWAP
);
4244 /* Check if a threshold crossed before removing */
4245 __mem_cgroup_threshold(memcg
, type
== _MEMSWAP
);
4247 /* Calculate new number of threshold */
4249 for (i
= 0; i
< thresholds
->primary
->size
; i
++) {
4250 if (thresholds
->primary
->entries
[i
].eventfd
!= eventfd
)
4254 new = thresholds
->spare
;
4256 /* Set thresholds array to NULL if we don't have thresholds */
4265 /* Copy thresholds and find current threshold */
4266 new->current_threshold
= -1;
4267 for (i
= 0, j
= 0; i
< thresholds
->primary
->size
; i
++) {
4268 if (thresholds
->primary
->entries
[i
].eventfd
== eventfd
)
4271 new->entries
[j
] = thresholds
->primary
->entries
[i
];
4272 if (new->entries
[j
].threshold
< usage
) {
4274 * new->current_threshold will not be used
4275 * until rcu_assign_pointer(), so it's safe to increment
4278 ++new->current_threshold
;
4284 /* Swap primary and spare array */
4285 thresholds
->spare
= thresholds
->primary
;
4286 rcu_assign_pointer(thresholds
->primary
, new);
4288 /* To be sure that nobody uses thresholds */
4291 mutex_unlock(&memcg
->thresholds_lock
);
4294 static int mem_cgroup_oom_register_event(struct cgroup
*cgrp
,
4295 struct cftype
*cft
, struct eventfd_ctx
*eventfd
, const char *args
)
4297 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cgrp
);
4298 struct mem_cgroup_eventfd_list
*event
;
4299 int type
= MEMFILE_TYPE(cft
->private);
4301 BUG_ON(type
!= _OOM_TYPE
);
4302 event
= kmalloc(sizeof(*event
), GFP_KERNEL
);
4306 mutex_lock(&memcg_oom_mutex
);
4308 event
->eventfd
= eventfd
;
4309 list_add(&event
->list
, &memcg
->oom_notify
);
4311 /* already in OOM ? */
4312 if (atomic_read(&memcg
->oom_lock
))
4313 eventfd_signal(eventfd
, 1);
4314 mutex_unlock(&memcg_oom_mutex
);
4319 static void mem_cgroup_oom_unregister_event(struct cgroup
*cgrp
,
4320 struct cftype
*cft
, struct eventfd_ctx
*eventfd
)
4322 struct mem_cgroup
*mem
= mem_cgroup_from_cont(cgrp
);
4323 struct mem_cgroup_eventfd_list
*ev
, *tmp
;
4324 int type
= MEMFILE_TYPE(cft
->private);
4326 BUG_ON(type
!= _OOM_TYPE
);
4328 mutex_lock(&memcg_oom_mutex
);
4330 list_for_each_entry_safe(ev
, tmp
, &mem
->oom_notify
, list
) {
4331 if (ev
->eventfd
== eventfd
) {
4332 list_del(&ev
->list
);
4337 mutex_unlock(&memcg_oom_mutex
);
4340 static int mem_cgroup_oom_control_read(struct cgroup
*cgrp
,
4341 struct cftype
*cft
, struct cgroup_map_cb
*cb
)
4343 struct mem_cgroup
*mem
= mem_cgroup_from_cont(cgrp
);
4345 cb
->fill(cb
, "oom_kill_disable", mem
->oom_kill_disable
);
4347 if (atomic_read(&mem
->oom_lock
))
4348 cb
->fill(cb
, "under_oom", 1);
4350 cb
->fill(cb
, "under_oom", 0);
4354 static int mem_cgroup_oom_control_write(struct cgroup
*cgrp
,
4355 struct cftype
*cft
, u64 val
)
4357 struct mem_cgroup
*mem
= mem_cgroup_from_cont(cgrp
);
4358 struct mem_cgroup
*parent
;
4360 /* cannot set to root cgroup and only 0 and 1 are allowed */
4361 if (!cgrp
->parent
|| !((val
== 0) || (val
== 1)))
4364 parent
= mem_cgroup_from_cont(cgrp
->parent
);
4367 /* oom-kill-disable is a flag for subhierarchy. */
4368 if ((parent
->use_hierarchy
) ||
4369 (mem
->use_hierarchy
&& !list_empty(&cgrp
->children
))) {
4373 mem
->oom_kill_disable
= val
;
4375 memcg_oom_recover(mem
);
4380 static struct cftype mem_cgroup_files
[] = {
4382 .name
= "usage_in_bytes",
4383 .private = MEMFILE_PRIVATE(_MEM
, RES_USAGE
),
4384 .read_u64
= mem_cgroup_read
,
4385 .register_event
= mem_cgroup_usage_register_event
,
4386 .unregister_event
= mem_cgroup_usage_unregister_event
,
4389 .name
= "max_usage_in_bytes",
4390 .private = MEMFILE_PRIVATE(_MEM
, RES_MAX_USAGE
),
4391 .trigger
= mem_cgroup_reset
,
4392 .read_u64
= mem_cgroup_read
,
4395 .name
= "limit_in_bytes",
4396 .private = MEMFILE_PRIVATE(_MEM
, RES_LIMIT
),
4397 .write_string
= mem_cgroup_write
,
4398 .read_u64
= mem_cgroup_read
,
4401 .name
= "soft_limit_in_bytes",
4402 .private = MEMFILE_PRIVATE(_MEM
, RES_SOFT_LIMIT
),
4403 .write_string
= mem_cgroup_write
,
4404 .read_u64
= mem_cgroup_read
,
4408 .private = MEMFILE_PRIVATE(_MEM
, RES_FAILCNT
),
4409 .trigger
= mem_cgroup_reset
,
4410 .read_u64
= mem_cgroup_read
,
4414 .read_map
= mem_control_stat_show
,
4417 .name
= "force_empty",
4418 .trigger
= mem_cgroup_force_empty_write
,
4421 .name
= "use_hierarchy",
4422 .write_u64
= mem_cgroup_hierarchy_write
,
4423 .read_u64
= mem_cgroup_hierarchy_read
,
4426 .name
= "swappiness",
4427 .read_u64
= mem_cgroup_swappiness_read
,
4428 .write_u64
= mem_cgroup_swappiness_write
,
4431 .name
= "move_charge_at_immigrate",
4432 .read_u64
= mem_cgroup_move_charge_read
,
4433 .write_u64
= mem_cgroup_move_charge_write
,
4436 .name
= "oom_control",
4437 .read_map
= mem_cgroup_oom_control_read
,
4438 .write_u64
= mem_cgroup_oom_control_write
,
4439 .register_event
= mem_cgroup_oom_register_event
,
4440 .unregister_event
= mem_cgroup_oom_unregister_event
,
4441 .private = MEMFILE_PRIVATE(_OOM_TYPE
, OOM_CONTROL
),
4445 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4446 static struct cftype memsw_cgroup_files
[] = {
4448 .name
= "memsw.usage_in_bytes",
4449 .private = MEMFILE_PRIVATE(_MEMSWAP
, RES_USAGE
),
4450 .read_u64
= mem_cgroup_read
,
4451 .register_event
= mem_cgroup_usage_register_event
,
4452 .unregister_event
= mem_cgroup_usage_unregister_event
,
4455 .name
= "memsw.max_usage_in_bytes",
4456 .private = MEMFILE_PRIVATE(_MEMSWAP
, RES_MAX_USAGE
),
4457 .trigger
= mem_cgroup_reset
,
4458 .read_u64
= mem_cgroup_read
,
4461 .name
= "memsw.limit_in_bytes",
4462 .private = MEMFILE_PRIVATE(_MEMSWAP
, RES_LIMIT
),
4463 .write_string
= mem_cgroup_write
,
4464 .read_u64
= mem_cgroup_read
,
4467 .name
= "memsw.failcnt",
4468 .private = MEMFILE_PRIVATE(_MEMSWAP
, RES_FAILCNT
),
4469 .trigger
= mem_cgroup_reset
,
4470 .read_u64
= mem_cgroup_read
,
4474 static int register_memsw_files(struct cgroup
*cont
, struct cgroup_subsys
*ss
)
4476 if (!do_swap_account
)
4478 return cgroup_add_files(cont
, ss
, memsw_cgroup_files
,
4479 ARRAY_SIZE(memsw_cgroup_files
));
4482 static int register_memsw_files(struct cgroup
*cont
, struct cgroup_subsys
*ss
)
4488 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup
*mem
, int node
)
4490 struct mem_cgroup_per_node
*pn
;
4491 struct mem_cgroup_per_zone
*mz
;
4493 int zone
, tmp
= node
;
4495 * This routine is called against possible nodes.
4496 * But it's BUG to call kmalloc() against offline node.
4498 * TODO: this routine can waste much memory for nodes which will
4499 * never be onlined. It's better to use memory hotplug callback
4502 if (!node_state(node
, N_NORMAL_MEMORY
))
4504 pn
= kzalloc_node(sizeof(*pn
), GFP_KERNEL
, tmp
);
4508 mem
->info
.nodeinfo
[node
] = pn
;
4509 for (zone
= 0; zone
< MAX_NR_ZONES
; zone
++) {
4510 mz
= &pn
->zoneinfo
[zone
];
4512 INIT_LIST_HEAD(&mz
->lists
[l
]);
4513 mz
->usage_in_excess
= 0;
4514 mz
->on_tree
= false;
4520 static void free_mem_cgroup_per_zone_info(struct mem_cgroup
*mem
, int node
)
4522 kfree(mem
->info
.nodeinfo
[node
]);
4525 static struct mem_cgroup
*mem_cgroup_alloc(void)
4527 struct mem_cgroup
*mem
;
4528 int size
= sizeof(struct mem_cgroup
);
4530 /* Can be very big if MAX_NUMNODES is very big */
4531 if (size
< PAGE_SIZE
)
4532 mem
= kzalloc(size
, GFP_KERNEL
);
4534 mem
= vzalloc(size
);
4539 mem
->stat
= alloc_percpu(struct mem_cgroup_stat_cpu
);
4542 spin_lock_init(&mem
->pcp_counter_lock
);
4546 if (size
< PAGE_SIZE
)
4554 * At destroying mem_cgroup, references from swap_cgroup can remain.
4555 * (scanning all at force_empty is too costly...)
4557 * Instead of clearing all references at force_empty, we remember
4558 * the number of reference from swap_cgroup and free mem_cgroup when
4559 * it goes down to 0.
4561 * Removal of cgroup itself succeeds regardless of refs from swap.
4564 static void __mem_cgroup_free(struct mem_cgroup
*mem
)
4568 mem_cgroup_remove_from_trees(mem
);
4569 free_css_id(&mem_cgroup_subsys
, &mem
->css
);
4571 for_each_node_state(node
, N_POSSIBLE
)
4572 free_mem_cgroup_per_zone_info(mem
, node
);
4574 free_percpu(mem
->stat
);
4575 if (sizeof(struct mem_cgroup
) < PAGE_SIZE
)
4581 static void mem_cgroup_get(struct mem_cgroup
*mem
)
4583 atomic_inc(&mem
->refcnt
);
4586 static void __mem_cgroup_put(struct mem_cgroup
*mem
, int count
)
4588 if (atomic_sub_and_test(count
, &mem
->refcnt
)) {
4589 struct mem_cgroup
*parent
= parent_mem_cgroup(mem
);
4590 __mem_cgroup_free(mem
);
4592 mem_cgroup_put(parent
);
4596 static void mem_cgroup_put(struct mem_cgroup
*mem
)
4598 __mem_cgroup_put(mem
, 1);
4602 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
4604 static struct mem_cgroup
*parent_mem_cgroup(struct mem_cgroup
*mem
)
4606 if (!mem
->res
.parent
)
4608 return mem_cgroup_from_res_counter(mem
->res
.parent
, res
);
4611 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4612 static void __init
enable_swap_cgroup(void)
4614 if (!mem_cgroup_disabled() && really_do_swap_account
)
4615 do_swap_account
= 1;
4618 static void __init
enable_swap_cgroup(void)
4623 static int mem_cgroup_soft_limit_tree_init(void)
4625 struct mem_cgroup_tree_per_node
*rtpn
;
4626 struct mem_cgroup_tree_per_zone
*rtpz
;
4627 int tmp
, node
, zone
;
4629 for_each_node_state(node
, N_POSSIBLE
) {
4631 if (!node_state(node
, N_NORMAL_MEMORY
))
4633 rtpn
= kzalloc_node(sizeof(*rtpn
), GFP_KERNEL
, tmp
);
4637 soft_limit_tree
.rb_tree_per_node
[node
] = rtpn
;
4639 for (zone
= 0; zone
< MAX_NR_ZONES
; zone
++) {
4640 rtpz
= &rtpn
->rb_tree_per_zone
[zone
];
4641 rtpz
->rb_root
= RB_ROOT
;
4642 spin_lock_init(&rtpz
->lock
);
4648 static struct cgroup_subsys_state
* __ref
4649 mem_cgroup_create(struct cgroup_subsys
*ss
, struct cgroup
*cont
)
4651 struct mem_cgroup
*mem
, *parent
;
4652 long error
= -ENOMEM
;
4655 mem
= mem_cgroup_alloc();
4657 return ERR_PTR(error
);
4659 for_each_node_state(node
, N_POSSIBLE
)
4660 if (alloc_mem_cgroup_per_zone_info(mem
, node
))
4664 if (cont
->parent
== NULL
) {
4666 enable_swap_cgroup();
4668 root_mem_cgroup
= mem
;
4669 if (mem_cgroup_soft_limit_tree_init())
4671 for_each_possible_cpu(cpu
) {
4672 struct memcg_stock_pcp
*stock
=
4673 &per_cpu(memcg_stock
, cpu
);
4674 INIT_WORK(&stock
->work
, drain_local_stock
);
4676 hotcpu_notifier(memcg_cpu_hotplug_callback
, 0);
4678 parent
= mem_cgroup_from_cont(cont
->parent
);
4679 mem
->use_hierarchy
= parent
->use_hierarchy
;
4680 mem
->oom_kill_disable
= parent
->oom_kill_disable
;
4683 if (parent
&& parent
->use_hierarchy
) {
4684 res_counter_init(&mem
->res
, &parent
->res
);
4685 res_counter_init(&mem
->memsw
, &parent
->memsw
);
4687 * We increment refcnt of the parent to ensure that we can
4688 * safely access it on res_counter_charge/uncharge.
4689 * This refcnt will be decremented when freeing this
4690 * mem_cgroup(see mem_cgroup_put).
4692 mem_cgroup_get(parent
);
4694 res_counter_init(&mem
->res
, NULL
);
4695 res_counter_init(&mem
->memsw
, NULL
);
4697 mem
->last_scanned_child
= 0;
4698 mem
->last_scanned_node
= MAX_NUMNODES
;
4699 INIT_LIST_HEAD(&mem
->oom_notify
);
4702 mem
->swappiness
= get_swappiness(parent
);
4703 atomic_set(&mem
->refcnt
, 1);
4704 mem
->move_charge_at_immigrate
= 0;
4705 mutex_init(&mem
->thresholds_lock
);
4708 __mem_cgroup_free(mem
);
4709 root_mem_cgroup
= NULL
;
4710 return ERR_PTR(error
);
4713 static int mem_cgroup_pre_destroy(struct cgroup_subsys
*ss
,
4714 struct cgroup
*cont
)
4716 struct mem_cgroup
*mem
= mem_cgroup_from_cont(cont
);
4718 return mem_cgroup_force_empty(mem
, false);
4721 static void mem_cgroup_destroy(struct cgroup_subsys
*ss
,
4722 struct cgroup
*cont
)
4724 struct mem_cgroup
*mem
= mem_cgroup_from_cont(cont
);
4726 mem_cgroup_put(mem
);
4729 static int mem_cgroup_populate(struct cgroup_subsys
*ss
,
4730 struct cgroup
*cont
)
4734 ret
= cgroup_add_files(cont
, ss
, mem_cgroup_files
,
4735 ARRAY_SIZE(mem_cgroup_files
));
4738 ret
= register_memsw_files(cont
, ss
);
4743 /* Handlers for move charge at task migration. */
4744 #define PRECHARGE_COUNT_AT_ONCE 256
4745 static int mem_cgroup_do_precharge(unsigned long count
)
4748 int batch_count
= PRECHARGE_COUNT_AT_ONCE
;
4749 struct mem_cgroup
*mem
= mc
.to
;
4751 if (mem_cgroup_is_root(mem
)) {
4752 mc
.precharge
+= count
;
4753 /* we don't need css_get for root */
4756 /* try to charge at once */
4758 struct res_counter
*dummy
;
4760 * "mem" cannot be under rmdir() because we've already checked
4761 * by cgroup_lock_live_cgroup() that it is not removed and we
4762 * are still under the same cgroup_mutex. So we can postpone
4765 if (res_counter_charge(&mem
->res
, PAGE_SIZE
* count
, &dummy
))
4767 if (do_swap_account
&& res_counter_charge(&mem
->memsw
,
4768 PAGE_SIZE
* count
, &dummy
)) {
4769 res_counter_uncharge(&mem
->res
, PAGE_SIZE
* count
);
4772 mc
.precharge
+= count
;
4776 /* fall back to one by one charge */
4778 if (signal_pending(current
)) {
4782 if (!batch_count
--) {
4783 batch_count
= PRECHARGE_COUNT_AT_ONCE
;
4786 ret
= __mem_cgroup_try_charge(NULL
, GFP_KERNEL
, 1, &mem
, false);
4788 /* mem_cgroup_clear_mc() will do uncharge later */
4796 * is_target_pte_for_mc - check a pte whether it is valid for move charge
4797 * @vma: the vma the pte to be checked belongs
4798 * @addr: the address corresponding to the pte to be checked
4799 * @ptent: the pte to be checked
4800 * @target: the pointer the target page or swap ent will be stored(can be NULL)
4803 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
4804 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
4805 * move charge. if @target is not NULL, the page is stored in target->page
4806 * with extra refcnt got(Callers should handle it).
4807 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
4808 * target for charge migration. if @target is not NULL, the entry is stored
4811 * Called with pte lock held.
4818 enum mc_target_type
{
4819 MC_TARGET_NONE
, /* not used */
4824 static struct page
*mc_handle_present_pte(struct vm_area_struct
*vma
,
4825 unsigned long addr
, pte_t ptent
)
4827 struct page
*page
= vm_normal_page(vma
, addr
, ptent
);
4829 if (!page
|| !page_mapped(page
))
4831 if (PageAnon(page
)) {
4832 /* we don't move shared anon */
4833 if (!move_anon() || page_mapcount(page
) > 2)
4835 } else if (!move_file())
4836 /* we ignore mapcount for file pages */
4838 if (!get_page_unless_zero(page
))
4844 static struct page
*mc_handle_swap_pte(struct vm_area_struct
*vma
,
4845 unsigned long addr
, pte_t ptent
, swp_entry_t
*entry
)
4848 struct page
*page
= NULL
;
4849 swp_entry_t ent
= pte_to_swp_entry(ptent
);
4851 if (!move_anon() || non_swap_entry(ent
))
4853 usage_count
= mem_cgroup_count_swap_user(ent
, &page
);
4854 if (usage_count
> 1) { /* we don't move shared anon */
4859 if (do_swap_account
)
4860 entry
->val
= ent
.val
;
4865 static struct page
*mc_handle_file_pte(struct vm_area_struct
*vma
,
4866 unsigned long addr
, pte_t ptent
, swp_entry_t
*entry
)
4868 struct page
*page
= NULL
;
4869 struct inode
*inode
;
4870 struct address_space
*mapping
;
4873 if (!vma
->vm_file
) /* anonymous vma */
4878 inode
= vma
->vm_file
->f_path
.dentry
->d_inode
;
4879 mapping
= vma
->vm_file
->f_mapping
;
4880 if (pte_none(ptent
))
4881 pgoff
= linear_page_index(vma
, addr
);
4882 else /* pte_file(ptent) is true */
4883 pgoff
= pte_to_pgoff(ptent
);
4885 /* page is moved even if it's not RSS of this task(page-faulted). */
4886 if (!mapping_cap_swap_backed(mapping
)) { /* normal file */
4887 page
= find_get_page(mapping
, pgoff
);
4888 } else { /* shmem/tmpfs file. we should take account of swap too. */
4890 mem_cgroup_get_shmem_target(inode
, pgoff
, &page
, &ent
);
4891 if (do_swap_account
)
4892 entry
->val
= ent
.val
;
4898 static int is_target_pte_for_mc(struct vm_area_struct
*vma
,
4899 unsigned long addr
, pte_t ptent
, union mc_target
*target
)
4901 struct page
*page
= NULL
;
4902 struct page_cgroup
*pc
;
4904 swp_entry_t ent
= { .val
= 0 };
4906 if (pte_present(ptent
))
4907 page
= mc_handle_present_pte(vma
, addr
, ptent
);
4908 else if (is_swap_pte(ptent
))
4909 page
= mc_handle_swap_pte(vma
, addr
, ptent
, &ent
);
4910 else if (pte_none(ptent
) || pte_file(ptent
))
4911 page
= mc_handle_file_pte(vma
, addr
, ptent
, &ent
);
4913 if (!page
&& !ent
.val
)
4916 pc
= lookup_page_cgroup(page
);
4918 * Do only loose check w/o page_cgroup lock.
4919 * mem_cgroup_move_account() checks the pc is valid or not under
4922 if (PageCgroupUsed(pc
) && pc
->mem_cgroup
== mc
.from
) {
4923 ret
= MC_TARGET_PAGE
;
4925 target
->page
= page
;
4927 if (!ret
|| !target
)
4930 /* There is a swap entry and a page doesn't exist or isn't charged */
4931 if (ent
.val
&& !ret
&&
4932 css_id(&mc
.from
->css
) == lookup_swap_cgroup(ent
)) {
4933 ret
= MC_TARGET_SWAP
;
4940 static int mem_cgroup_count_precharge_pte_range(pmd_t
*pmd
,
4941 unsigned long addr
, unsigned long end
,
4942 struct mm_walk
*walk
)
4944 struct vm_area_struct
*vma
= walk
->private;
4948 split_huge_page_pmd(walk
->mm
, pmd
);
4950 pte
= pte_offset_map_lock(vma
->vm_mm
, pmd
, addr
, &ptl
);
4951 for (; addr
!= end
; pte
++, addr
+= PAGE_SIZE
)
4952 if (is_target_pte_for_mc(vma
, addr
, *pte
, NULL
))
4953 mc
.precharge
++; /* increment precharge temporarily */
4954 pte_unmap_unlock(pte
- 1, ptl
);
4960 static unsigned long mem_cgroup_count_precharge(struct mm_struct
*mm
)
4962 unsigned long precharge
;
4963 struct vm_area_struct
*vma
;
4965 down_read(&mm
->mmap_sem
);
4966 for (vma
= mm
->mmap
; vma
; vma
= vma
->vm_next
) {
4967 struct mm_walk mem_cgroup_count_precharge_walk
= {
4968 .pmd_entry
= mem_cgroup_count_precharge_pte_range
,
4972 if (is_vm_hugetlb_page(vma
))
4974 walk_page_range(vma
->vm_start
, vma
->vm_end
,
4975 &mem_cgroup_count_precharge_walk
);
4977 up_read(&mm
->mmap_sem
);
4979 precharge
= mc
.precharge
;
4985 static int mem_cgroup_precharge_mc(struct mm_struct
*mm
)
4987 unsigned long precharge
= mem_cgroup_count_precharge(mm
);
4989 VM_BUG_ON(mc
.moving_task
);
4990 mc
.moving_task
= current
;
4991 return mem_cgroup_do_precharge(precharge
);
4994 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
4995 static void __mem_cgroup_clear_mc(void)
4997 struct mem_cgroup
*from
= mc
.from
;
4998 struct mem_cgroup
*to
= mc
.to
;
5000 /* we must uncharge all the leftover precharges from mc.to */
5002 __mem_cgroup_cancel_charge(mc
.to
, mc
.precharge
);
5006 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5007 * we must uncharge here.
5009 if (mc
.moved_charge
) {
5010 __mem_cgroup_cancel_charge(mc
.from
, mc
.moved_charge
);
5011 mc
.moved_charge
= 0;
5013 /* we must fixup refcnts and charges */
5014 if (mc
.moved_swap
) {
5015 /* uncharge swap account from the old cgroup */
5016 if (!mem_cgroup_is_root(mc
.from
))
5017 res_counter_uncharge(&mc
.from
->memsw
,
5018 PAGE_SIZE
* mc
.moved_swap
);
5019 __mem_cgroup_put(mc
.from
, mc
.moved_swap
);
5021 if (!mem_cgroup_is_root(mc
.to
)) {
5023 * we charged both to->res and to->memsw, so we should
5026 res_counter_uncharge(&mc
.to
->res
,
5027 PAGE_SIZE
* mc
.moved_swap
);
5029 /* we've already done mem_cgroup_get(mc.to) */
5032 memcg_oom_recover(from
);
5033 memcg_oom_recover(to
);
5034 wake_up_all(&mc
.waitq
);
5037 static void mem_cgroup_clear_mc(void)
5039 struct mem_cgroup
*from
= mc
.from
;
5042 * we must clear moving_task before waking up waiters at the end of
5045 mc
.moving_task
= NULL
;
5046 __mem_cgroup_clear_mc();
5047 spin_lock(&mc
.lock
);
5050 spin_unlock(&mc
.lock
);
5051 mem_cgroup_end_move(from
);
5054 static int mem_cgroup_can_attach(struct cgroup_subsys
*ss
,
5055 struct cgroup
*cgroup
,
5056 struct task_struct
*p
)
5059 struct mem_cgroup
*mem
= mem_cgroup_from_cont(cgroup
);
5061 if (mem
->move_charge_at_immigrate
) {
5062 struct mm_struct
*mm
;
5063 struct mem_cgroup
*from
= mem_cgroup_from_task(p
);
5065 VM_BUG_ON(from
== mem
);
5067 mm
= get_task_mm(p
);
5070 /* We move charges only when we move a owner of the mm */
5071 if (mm
->owner
== p
) {
5074 VM_BUG_ON(mc
.precharge
);
5075 VM_BUG_ON(mc
.moved_charge
);
5076 VM_BUG_ON(mc
.moved_swap
);
5077 mem_cgroup_start_move(from
);
5078 spin_lock(&mc
.lock
);
5081 spin_unlock(&mc
.lock
);
5082 /* We set mc.moving_task later */
5084 ret
= mem_cgroup_precharge_mc(mm
);
5086 mem_cgroup_clear_mc();
5093 static void mem_cgroup_cancel_attach(struct cgroup_subsys
*ss
,
5094 struct cgroup
*cgroup
,
5095 struct task_struct
*p
)
5097 mem_cgroup_clear_mc();
5100 static int mem_cgroup_move_charge_pte_range(pmd_t
*pmd
,
5101 unsigned long addr
, unsigned long end
,
5102 struct mm_walk
*walk
)
5105 struct vm_area_struct
*vma
= walk
->private;
5109 split_huge_page_pmd(walk
->mm
, pmd
);
5111 pte
= pte_offset_map_lock(vma
->vm_mm
, pmd
, addr
, &ptl
);
5112 for (; addr
!= end
; addr
+= PAGE_SIZE
) {
5113 pte_t ptent
= *(pte
++);
5114 union mc_target target
;
5117 struct page_cgroup
*pc
;
5123 type
= is_target_pte_for_mc(vma
, addr
, ptent
, &target
);
5125 case MC_TARGET_PAGE
:
5127 if (isolate_lru_page(page
))
5129 pc
= lookup_page_cgroup(page
);
5130 if (!mem_cgroup_move_account(page
, 1, pc
,
5131 mc
.from
, mc
.to
, false)) {
5133 /* we uncharge from mc.from later. */
5136 putback_lru_page(page
);
5137 put
: /* is_target_pte_for_mc() gets the page */
5140 case MC_TARGET_SWAP
:
5142 if (!mem_cgroup_move_swap_account(ent
,
5143 mc
.from
, mc
.to
, false)) {
5145 /* we fixup refcnts and charges later. */
5153 pte_unmap_unlock(pte
- 1, ptl
);
5158 * We have consumed all precharges we got in can_attach().
5159 * We try charge one by one, but don't do any additional
5160 * charges to mc.to if we have failed in charge once in attach()
5163 ret
= mem_cgroup_do_precharge(1);
5171 static void mem_cgroup_move_charge(struct mm_struct
*mm
)
5173 struct vm_area_struct
*vma
;
5175 lru_add_drain_all();
5177 if (unlikely(!down_read_trylock(&mm
->mmap_sem
))) {
5179 * Someone who are holding the mmap_sem might be waiting in
5180 * waitq. So we cancel all extra charges, wake up all waiters,
5181 * and retry. Because we cancel precharges, we might not be able
5182 * to move enough charges, but moving charge is a best-effort
5183 * feature anyway, so it wouldn't be a big problem.
5185 __mem_cgroup_clear_mc();
5189 for (vma
= mm
->mmap
; vma
; vma
= vma
->vm_next
) {
5191 struct mm_walk mem_cgroup_move_charge_walk
= {
5192 .pmd_entry
= mem_cgroup_move_charge_pte_range
,
5196 if (is_vm_hugetlb_page(vma
))
5198 ret
= walk_page_range(vma
->vm_start
, vma
->vm_end
,
5199 &mem_cgroup_move_charge_walk
);
5202 * means we have consumed all precharges and failed in
5203 * doing additional charge. Just abandon here.
5207 up_read(&mm
->mmap_sem
);
5210 static void mem_cgroup_move_task(struct cgroup_subsys
*ss
,
5211 struct cgroup
*cont
,
5212 struct cgroup
*old_cont
,
5213 struct task_struct
*p
)
5215 struct mm_struct
*mm
;
5218 /* no need to move charge */
5221 mm
= get_task_mm(p
);
5223 mem_cgroup_move_charge(mm
);
5226 mem_cgroup_clear_mc();
5228 #else /* !CONFIG_MMU */
5229 static int mem_cgroup_can_attach(struct cgroup_subsys
*ss
,
5230 struct cgroup
*cgroup
,
5231 struct task_struct
*p
)
5235 static void mem_cgroup_cancel_attach(struct cgroup_subsys
*ss
,
5236 struct cgroup
*cgroup
,
5237 struct task_struct
*p
)
5240 static void mem_cgroup_move_task(struct cgroup_subsys
*ss
,
5241 struct cgroup
*cont
,
5242 struct cgroup
*old_cont
,
5243 struct task_struct
*p
)
5248 struct cgroup_subsys mem_cgroup_subsys
= {
5250 .subsys_id
= mem_cgroup_subsys_id
,
5251 .create
= mem_cgroup_create
,
5252 .pre_destroy
= mem_cgroup_pre_destroy
,
5253 .destroy
= mem_cgroup_destroy
,
5254 .populate
= mem_cgroup_populate
,
5255 .can_attach
= mem_cgroup_can_attach
,
5256 .cancel_attach
= mem_cgroup_cancel_attach
,
5257 .attach
= mem_cgroup_move_task
,
5262 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
5263 static int __init
enable_swap_account(char *s
)
5265 /* consider enabled if no parameter or 1 is given */
5266 if (!strcmp(s
, "1"))
5267 really_do_swap_account
= 1;
5268 else if (!strcmp(s
, "0"))
5269 really_do_swap_account
= 0;
5272 __setup("swapaccount=", enable_swap_account
);