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 * Kernel Memory Controller
14 * Copyright (C) 2012 Parallels Inc. and Google Inc.
15 * Authors: Glauber Costa and Suleiman Souhlal
17 * This program is free software; you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation; either version 2 of the License, or
20 * (at your option) any later version.
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
28 #include <linux/res_counter.h>
29 #include <linux/memcontrol.h>
30 #include <linux/cgroup.h>
32 #include <linux/hugetlb.h>
33 #include <linux/pagemap.h>
34 #include <linux/smp.h>
35 #include <linux/page-flags.h>
36 #include <linux/backing-dev.h>
37 #include <linux/bit_spinlock.h>
38 #include <linux/rcupdate.h>
39 #include <linux/limits.h>
40 #include <linux/export.h>
41 #include <linux/mutex.h>
42 #include <linux/rbtree.h>
43 #include <linux/slab.h>
44 #include <linux/swap.h>
45 #include <linux/swapops.h>
46 #include <linux/spinlock.h>
47 #include <linux/eventfd.h>
48 #include <linux/sort.h>
50 #include <linux/seq_file.h>
51 #include <linux/vmalloc.h>
52 #include <linux/mm_inline.h>
53 #include <linux/page_cgroup.h>
54 #include <linux/cpu.h>
55 #include <linux/oom.h>
59 #include <net/tcp_memcontrol.h>
61 #include <asm/uaccess.h>
63 #include <trace/events/vmscan.h>
65 struct cgroup_subsys mem_cgroup_subsys __read_mostly
;
66 EXPORT_SYMBOL(mem_cgroup_subsys
);
68 #define MEM_CGROUP_RECLAIM_RETRIES 5
69 static struct mem_cgroup
*root_mem_cgroup __read_mostly
;
71 #ifdef CONFIG_MEMCG_SWAP
72 /* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
73 int do_swap_account __read_mostly
;
75 /* for remember boot option*/
76 #ifdef CONFIG_MEMCG_SWAP_ENABLED
77 static int really_do_swap_account __initdata
= 1;
79 static int really_do_swap_account __initdata
= 0;
83 #define do_swap_account 0
88 * Statistics for memory cgroup.
90 enum mem_cgroup_stat_index
{
92 * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
94 MEM_CGROUP_STAT_CACHE
, /* # of pages charged as cache */
95 MEM_CGROUP_STAT_RSS
, /* # of pages charged as anon rss */
96 MEM_CGROUP_STAT_FILE_MAPPED
, /* # of pages charged as file rss */
97 MEM_CGROUP_STAT_SWAP
, /* # of pages, swapped out */
98 MEM_CGROUP_STAT_NSTATS
,
101 static const char * const mem_cgroup_stat_names
[] = {
108 enum mem_cgroup_events_index
{
109 MEM_CGROUP_EVENTS_PGPGIN
, /* # of pages paged in */
110 MEM_CGROUP_EVENTS_PGPGOUT
, /* # of pages paged out */
111 MEM_CGROUP_EVENTS_PGFAULT
, /* # of page-faults */
112 MEM_CGROUP_EVENTS_PGMAJFAULT
, /* # of major page-faults */
113 MEM_CGROUP_EVENTS_NSTATS
,
116 static const char * const mem_cgroup_events_names
[] = {
124 * Per memcg event counter is incremented at every pagein/pageout. With THP,
125 * it will be incremated by the number of pages. This counter is used for
126 * for trigger some periodic events. This is straightforward and better
127 * than using jiffies etc. to handle periodic memcg event.
129 enum mem_cgroup_events_target
{
130 MEM_CGROUP_TARGET_THRESH
,
131 MEM_CGROUP_TARGET_SOFTLIMIT
,
132 MEM_CGROUP_TARGET_NUMAINFO
,
135 #define THRESHOLDS_EVENTS_TARGET 128
136 #define SOFTLIMIT_EVENTS_TARGET 1024
137 #define NUMAINFO_EVENTS_TARGET 1024
139 struct mem_cgroup_stat_cpu
{
140 long count
[MEM_CGROUP_STAT_NSTATS
];
141 unsigned long events
[MEM_CGROUP_EVENTS_NSTATS
];
142 unsigned long nr_page_events
;
143 unsigned long targets
[MEM_CGROUP_NTARGETS
];
146 struct mem_cgroup_reclaim_iter
{
147 /* css_id of the last scanned hierarchy member */
149 /* scan generation, increased every round-trip */
150 unsigned int generation
;
154 * per-zone information in memory controller.
156 struct mem_cgroup_per_zone
{
157 struct lruvec lruvec
;
158 unsigned long lru_size
[NR_LRU_LISTS
];
160 struct mem_cgroup_reclaim_iter reclaim_iter
[DEF_PRIORITY
+ 1];
162 struct rb_node tree_node
; /* RB tree node */
163 unsigned long long usage_in_excess
;/* Set to the value by which */
164 /* the soft limit is exceeded*/
166 struct mem_cgroup
*memcg
; /* Back pointer, we cannot */
167 /* use container_of */
170 struct mem_cgroup_per_node
{
171 struct mem_cgroup_per_zone zoneinfo
[MAX_NR_ZONES
];
174 struct mem_cgroup_lru_info
{
175 struct mem_cgroup_per_node
*nodeinfo
[MAX_NUMNODES
];
179 * Cgroups above their limits are maintained in a RB-Tree, independent of
180 * their hierarchy representation
183 struct mem_cgroup_tree_per_zone
{
184 struct rb_root rb_root
;
188 struct mem_cgroup_tree_per_node
{
189 struct mem_cgroup_tree_per_zone rb_tree_per_zone
[MAX_NR_ZONES
];
192 struct mem_cgroup_tree
{
193 struct mem_cgroup_tree_per_node
*rb_tree_per_node
[MAX_NUMNODES
];
196 static struct mem_cgroup_tree soft_limit_tree __read_mostly
;
198 struct mem_cgroup_threshold
{
199 struct eventfd_ctx
*eventfd
;
204 struct mem_cgroup_threshold_ary
{
205 /* An array index points to threshold just below or equal to usage. */
206 int current_threshold
;
207 /* Size of entries[] */
209 /* Array of thresholds */
210 struct mem_cgroup_threshold entries
[0];
213 struct mem_cgroup_thresholds
{
214 /* Primary thresholds array */
215 struct mem_cgroup_threshold_ary
*primary
;
217 * Spare threshold array.
218 * This is needed to make mem_cgroup_unregister_event() "never fail".
219 * It must be able to store at least primary->size - 1 entries.
221 struct mem_cgroup_threshold_ary
*spare
;
225 struct mem_cgroup_eventfd_list
{
226 struct list_head list
;
227 struct eventfd_ctx
*eventfd
;
230 static void mem_cgroup_threshold(struct mem_cgroup
*memcg
);
231 static void mem_cgroup_oom_notify(struct mem_cgroup
*memcg
);
234 * The memory controller data structure. The memory controller controls both
235 * page cache and RSS per cgroup. We would eventually like to provide
236 * statistics based on the statistics developed by Rik Van Riel for clock-pro,
237 * to help the administrator determine what knobs to tune.
239 * TODO: Add a water mark for the memory controller. Reclaim will begin when
240 * we hit the water mark. May be even add a low water mark, such that
241 * no reclaim occurs from a cgroup at it's low water mark, this is
242 * a feature that will be implemented much later in the future.
245 struct cgroup_subsys_state css
;
247 * the counter to account for memory usage
249 struct res_counter res
;
253 * the counter to account for mem+swap usage.
255 struct res_counter memsw
;
258 * rcu_freeing is used only when freeing struct mem_cgroup,
259 * so put it into a union to avoid wasting more memory.
260 * It must be disjoint from the css field. It could be
261 * in a union with the res field, but res plays a much
262 * larger part in mem_cgroup life than memsw, and might
263 * be of interest, even at time of free, when debugging.
264 * So share rcu_head with the less interesting memsw.
266 struct rcu_head rcu_freeing
;
268 * We also need some space for a worker in deferred freeing.
269 * By the time we call it, rcu_freeing is no longer in use.
271 struct work_struct work_freeing
;
275 * the counter to account for kernel memory usage.
277 struct res_counter kmem
;
279 * Per cgroup active and inactive list, similar to the
280 * per zone LRU lists.
282 struct mem_cgroup_lru_info info
;
283 int last_scanned_node
;
285 nodemask_t scan_nodes
;
286 atomic_t numainfo_events
;
287 atomic_t numainfo_updating
;
290 * Should the accounting and control be hierarchical, per subtree?
293 unsigned long kmem_account_flags
; /* See KMEM_ACCOUNTED_*, below */
301 /* OOM-Killer disable */
302 int oom_kill_disable
;
304 /* set when res.limit == memsw.limit */
305 bool memsw_is_minimum
;
307 /* protect arrays of thresholds */
308 struct mutex thresholds_lock
;
310 /* thresholds for memory usage. RCU-protected */
311 struct mem_cgroup_thresholds thresholds
;
313 /* thresholds for mem+swap usage. RCU-protected */
314 struct mem_cgroup_thresholds memsw_thresholds
;
316 /* For oom notifier event fd */
317 struct list_head oom_notify
;
320 * Should we move charges of a task when a task is moved into this
321 * mem_cgroup ? And what type of charges should we move ?
323 unsigned long move_charge_at_immigrate
;
325 * set > 0 if pages under this cgroup are moving to other cgroup.
327 atomic_t moving_account
;
328 /* taken only while moving_account > 0 */
329 spinlock_t move_lock
;
333 struct mem_cgroup_stat_cpu __percpu
*stat
;
335 * used when a cpu is offlined or other synchronizations
336 * See mem_cgroup_read_stat().
338 struct mem_cgroup_stat_cpu nocpu_base
;
339 spinlock_t pcp_counter_lock
;
341 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_INET)
342 struct tcp_memcontrol tcp_mem
;
346 /* internal only representation about the status of kmem accounting. */
348 KMEM_ACCOUNTED_ACTIVE
= 0, /* accounted by this cgroup itself */
349 KMEM_ACCOUNTED_ACTIVATED
, /* static key enabled. */
350 KMEM_ACCOUNTED_DEAD
, /* dead memcg with pending kmem charges */
353 /* We account when limit is on, but only after call sites are patched */
354 #define KMEM_ACCOUNTED_MASK \
355 ((1 << KMEM_ACCOUNTED_ACTIVE) | (1 << KMEM_ACCOUNTED_ACTIVATED))
357 #ifdef CONFIG_MEMCG_KMEM
358 static inline void memcg_kmem_set_active(struct mem_cgroup
*memcg
)
360 set_bit(KMEM_ACCOUNTED_ACTIVE
, &memcg
->kmem_account_flags
);
363 static bool memcg_kmem_is_active(struct mem_cgroup
*memcg
)
365 return test_bit(KMEM_ACCOUNTED_ACTIVE
, &memcg
->kmem_account_flags
);
368 static void memcg_kmem_set_activated(struct mem_cgroup
*memcg
)
370 set_bit(KMEM_ACCOUNTED_ACTIVATED
, &memcg
->kmem_account_flags
);
373 static void memcg_kmem_mark_dead(struct mem_cgroup
*memcg
)
375 if (test_bit(KMEM_ACCOUNTED_ACTIVE
, &memcg
->kmem_account_flags
))
376 set_bit(KMEM_ACCOUNTED_DEAD
, &memcg
->kmem_account_flags
);
379 static bool memcg_kmem_test_and_clear_dead(struct mem_cgroup
*memcg
)
381 return test_and_clear_bit(KMEM_ACCOUNTED_DEAD
,
382 &memcg
->kmem_account_flags
);
386 /* Stuffs for move charges at task migration. */
388 * Types of charges to be moved. "move_charge_at_immitgrate" is treated as a
389 * left-shifted bitmap of these types.
392 MOVE_CHARGE_TYPE_ANON
, /* private anonymous page and swap of it */
393 MOVE_CHARGE_TYPE_FILE
, /* file page(including tmpfs) and swap of it */
397 /* "mc" and its members are protected by cgroup_mutex */
398 static struct move_charge_struct
{
399 spinlock_t lock
; /* for from, to */
400 struct mem_cgroup
*from
;
401 struct mem_cgroup
*to
;
402 unsigned long precharge
;
403 unsigned long moved_charge
;
404 unsigned long moved_swap
;
405 struct task_struct
*moving_task
; /* a task moving charges */
406 wait_queue_head_t waitq
; /* a waitq for other context */
408 .lock
= __SPIN_LOCK_UNLOCKED(mc
.lock
),
409 .waitq
= __WAIT_QUEUE_HEAD_INITIALIZER(mc
.waitq
),
412 static bool move_anon(void)
414 return test_bit(MOVE_CHARGE_TYPE_ANON
,
415 &mc
.to
->move_charge_at_immigrate
);
418 static bool move_file(void)
420 return test_bit(MOVE_CHARGE_TYPE_FILE
,
421 &mc
.to
->move_charge_at_immigrate
);
425 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
426 * limit reclaim to prevent infinite loops, if they ever occur.
428 #define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
429 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
432 MEM_CGROUP_CHARGE_TYPE_CACHE
= 0,
433 MEM_CGROUP_CHARGE_TYPE_ANON
,
434 MEM_CGROUP_CHARGE_TYPE_SWAPOUT
, /* for accounting swapcache */
435 MEM_CGROUP_CHARGE_TYPE_DROP
, /* a page was unused swap cache */
439 /* for encoding cft->private value on file */
447 #define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
448 #define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
449 #define MEMFILE_ATTR(val) ((val) & 0xffff)
450 /* Used for OOM nofiier */
451 #define OOM_CONTROL (0)
454 * Reclaim flags for mem_cgroup_hierarchical_reclaim
456 #define MEM_CGROUP_RECLAIM_NOSWAP_BIT 0x0
457 #define MEM_CGROUP_RECLAIM_NOSWAP (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
458 #define MEM_CGROUP_RECLAIM_SHRINK_BIT 0x1
459 #define MEM_CGROUP_RECLAIM_SHRINK (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
461 static void mem_cgroup_get(struct mem_cgroup
*memcg
);
462 static void mem_cgroup_put(struct mem_cgroup
*memcg
);
465 struct mem_cgroup
*mem_cgroup_from_css(struct cgroup_subsys_state
*s
)
467 return container_of(s
, struct mem_cgroup
, css
);
470 static inline bool mem_cgroup_is_root(struct mem_cgroup
*memcg
)
472 return (memcg
== root_mem_cgroup
);
475 /* Writing them here to avoid exposing memcg's inner layout */
476 #if defined(CONFIG_INET) && defined(CONFIG_MEMCG_KMEM)
478 void sock_update_memcg(struct sock
*sk
)
480 if (mem_cgroup_sockets_enabled
) {
481 struct mem_cgroup
*memcg
;
482 struct cg_proto
*cg_proto
;
484 BUG_ON(!sk
->sk_prot
->proto_cgroup
);
486 /* Socket cloning can throw us here with sk_cgrp already
487 * filled. It won't however, necessarily happen from
488 * process context. So the test for root memcg given
489 * the current task's memcg won't help us in this case.
491 * Respecting the original socket's memcg is a better
492 * decision in this case.
495 BUG_ON(mem_cgroup_is_root(sk
->sk_cgrp
->memcg
));
496 mem_cgroup_get(sk
->sk_cgrp
->memcg
);
501 memcg
= mem_cgroup_from_task(current
);
502 cg_proto
= sk
->sk_prot
->proto_cgroup(memcg
);
503 if (!mem_cgroup_is_root(memcg
) && memcg_proto_active(cg_proto
)) {
504 mem_cgroup_get(memcg
);
505 sk
->sk_cgrp
= cg_proto
;
510 EXPORT_SYMBOL(sock_update_memcg
);
512 void sock_release_memcg(struct sock
*sk
)
514 if (mem_cgroup_sockets_enabled
&& sk
->sk_cgrp
) {
515 struct mem_cgroup
*memcg
;
516 WARN_ON(!sk
->sk_cgrp
->memcg
);
517 memcg
= sk
->sk_cgrp
->memcg
;
518 mem_cgroup_put(memcg
);
522 struct cg_proto
*tcp_proto_cgroup(struct mem_cgroup
*memcg
)
524 if (!memcg
|| mem_cgroup_is_root(memcg
))
527 return &memcg
->tcp_mem
.cg_proto
;
529 EXPORT_SYMBOL(tcp_proto_cgroup
);
531 static void disarm_sock_keys(struct mem_cgroup
*memcg
)
533 if (!memcg_proto_activated(&memcg
->tcp_mem
.cg_proto
))
535 static_key_slow_dec(&memcg_socket_limit_enabled
);
538 static void disarm_sock_keys(struct mem_cgroup
*memcg
)
543 #ifdef CONFIG_MEMCG_KMEM
544 struct static_key memcg_kmem_enabled_key
;
546 static void disarm_kmem_keys(struct mem_cgroup
*memcg
)
548 if (memcg_kmem_is_active(memcg
))
549 static_key_slow_dec(&memcg_kmem_enabled_key
);
551 * This check can't live in kmem destruction function,
552 * since the charges will outlive the cgroup
554 WARN_ON(res_counter_read_u64(&memcg
->kmem
, RES_USAGE
) != 0);
557 static void disarm_kmem_keys(struct mem_cgroup
*memcg
)
560 #endif /* CONFIG_MEMCG_KMEM */
562 static void disarm_static_keys(struct mem_cgroup
*memcg
)
564 disarm_sock_keys(memcg
);
565 disarm_kmem_keys(memcg
);
568 static void drain_all_stock_async(struct mem_cgroup
*memcg
);
570 static struct mem_cgroup_per_zone
*
571 mem_cgroup_zoneinfo(struct mem_cgroup
*memcg
, int nid
, int zid
)
573 return &memcg
->info
.nodeinfo
[nid
]->zoneinfo
[zid
];
576 struct cgroup_subsys_state
*mem_cgroup_css(struct mem_cgroup
*memcg
)
581 static struct mem_cgroup_per_zone
*
582 page_cgroup_zoneinfo(struct mem_cgroup
*memcg
, struct page
*page
)
584 int nid
= page_to_nid(page
);
585 int zid
= page_zonenum(page
);
587 return mem_cgroup_zoneinfo(memcg
, nid
, zid
);
590 static struct mem_cgroup_tree_per_zone
*
591 soft_limit_tree_node_zone(int nid
, int zid
)
593 return &soft_limit_tree
.rb_tree_per_node
[nid
]->rb_tree_per_zone
[zid
];
596 static struct mem_cgroup_tree_per_zone
*
597 soft_limit_tree_from_page(struct page
*page
)
599 int nid
= page_to_nid(page
);
600 int zid
= page_zonenum(page
);
602 return &soft_limit_tree
.rb_tree_per_node
[nid
]->rb_tree_per_zone
[zid
];
606 __mem_cgroup_insert_exceeded(struct mem_cgroup
*memcg
,
607 struct mem_cgroup_per_zone
*mz
,
608 struct mem_cgroup_tree_per_zone
*mctz
,
609 unsigned long long new_usage_in_excess
)
611 struct rb_node
**p
= &mctz
->rb_root
.rb_node
;
612 struct rb_node
*parent
= NULL
;
613 struct mem_cgroup_per_zone
*mz_node
;
618 mz
->usage_in_excess
= new_usage_in_excess
;
619 if (!mz
->usage_in_excess
)
623 mz_node
= rb_entry(parent
, struct mem_cgroup_per_zone
,
625 if (mz
->usage_in_excess
< mz_node
->usage_in_excess
)
628 * We can't avoid mem cgroups that are over their soft
629 * limit by the same amount
631 else if (mz
->usage_in_excess
>= mz_node
->usage_in_excess
)
634 rb_link_node(&mz
->tree_node
, parent
, p
);
635 rb_insert_color(&mz
->tree_node
, &mctz
->rb_root
);
640 __mem_cgroup_remove_exceeded(struct mem_cgroup
*memcg
,
641 struct mem_cgroup_per_zone
*mz
,
642 struct mem_cgroup_tree_per_zone
*mctz
)
646 rb_erase(&mz
->tree_node
, &mctz
->rb_root
);
651 mem_cgroup_remove_exceeded(struct mem_cgroup
*memcg
,
652 struct mem_cgroup_per_zone
*mz
,
653 struct mem_cgroup_tree_per_zone
*mctz
)
655 spin_lock(&mctz
->lock
);
656 __mem_cgroup_remove_exceeded(memcg
, mz
, mctz
);
657 spin_unlock(&mctz
->lock
);
661 static void mem_cgroup_update_tree(struct mem_cgroup
*memcg
, struct page
*page
)
663 unsigned long long excess
;
664 struct mem_cgroup_per_zone
*mz
;
665 struct mem_cgroup_tree_per_zone
*mctz
;
666 int nid
= page_to_nid(page
);
667 int zid
= page_zonenum(page
);
668 mctz
= soft_limit_tree_from_page(page
);
671 * Necessary to update all ancestors when hierarchy is used.
672 * because their event counter is not touched.
674 for (; memcg
; memcg
= parent_mem_cgroup(memcg
)) {
675 mz
= mem_cgroup_zoneinfo(memcg
, nid
, zid
);
676 excess
= res_counter_soft_limit_excess(&memcg
->res
);
678 * We have to update the tree if mz is on RB-tree or
679 * mem is over its softlimit.
681 if (excess
|| mz
->on_tree
) {
682 spin_lock(&mctz
->lock
);
683 /* if on-tree, remove it */
685 __mem_cgroup_remove_exceeded(memcg
, mz
, mctz
);
687 * Insert again. mz->usage_in_excess will be updated.
688 * If excess is 0, no tree ops.
690 __mem_cgroup_insert_exceeded(memcg
, mz
, mctz
, excess
);
691 spin_unlock(&mctz
->lock
);
696 static void mem_cgroup_remove_from_trees(struct mem_cgroup
*memcg
)
699 struct mem_cgroup_per_zone
*mz
;
700 struct mem_cgroup_tree_per_zone
*mctz
;
702 for_each_node(node
) {
703 for (zone
= 0; zone
< MAX_NR_ZONES
; zone
++) {
704 mz
= mem_cgroup_zoneinfo(memcg
, node
, zone
);
705 mctz
= soft_limit_tree_node_zone(node
, zone
);
706 mem_cgroup_remove_exceeded(memcg
, mz
, mctz
);
711 static struct mem_cgroup_per_zone
*
712 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone
*mctz
)
714 struct rb_node
*rightmost
= NULL
;
715 struct mem_cgroup_per_zone
*mz
;
719 rightmost
= rb_last(&mctz
->rb_root
);
721 goto done
; /* Nothing to reclaim from */
723 mz
= rb_entry(rightmost
, struct mem_cgroup_per_zone
, tree_node
);
725 * Remove the node now but someone else can add it back,
726 * we will to add it back at the end of reclaim to its correct
727 * position in the tree.
729 __mem_cgroup_remove_exceeded(mz
->memcg
, mz
, mctz
);
730 if (!res_counter_soft_limit_excess(&mz
->memcg
->res
) ||
731 !css_tryget(&mz
->memcg
->css
))
737 static struct mem_cgroup_per_zone
*
738 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone
*mctz
)
740 struct mem_cgroup_per_zone
*mz
;
742 spin_lock(&mctz
->lock
);
743 mz
= __mem_cgroup_largest_soft_limit_node(mctz
);
744 spin_unlock(&mctz
->lock
);
749 * Implementation Note: reading percpu statistics for memcg.
751 * Both of vmstat[] and percpu_counter has threshold and do periodic
752 * synchronization to implement "quick" read. There are trade-off between
753 * reading cost and precision of value. Then, we may have a chance to implement
754 * a periodic synchronizion of counter in memcg's counter.
756 * But this _read() function is used for user interface now. The user accounts
757 * memory usage by memory cgroup and he _always_ requires exact value because
758 * he accounts memory. Even if we provide quick-and-fuzzy read, we always
759 * have to visit all online cpus and make sum. So, for now, unnecessary
760 * synchronization is not implemented. (just implemented for cpu hotplug)
762 * If there are kernel internal actions which can make use of some not-exact
763 * value, and reading all cpu value can be performance bottleneck in some
764 * common workload, threashold and synchonization as vmstat[] should be
767 static long mem_cgroup_read_stat(struct mem_cgroup
*memcg
,
768 enum mem_cgroup_stat_index idx
)
774 for_each_online_cpu(cpu
)
775 val
+= per_cpu(memcg
->stat
->count
[idx
], cpu
);
776 #ifdef CONFIG_HOTPLUG_CPU
777 spin_lock(&memcg
->pcp_counter_lock
);
778 val
+= memcg
->nocpu_base
.count
[idx
];
779 spin_unlock(&memcg
->pcp_counter_lock
);
785 static void mem_cgroup_swap_statistics(struct mem_cgroup
*memcg
,
788 int val
= (charge
) ? 1 : -1;
789 this_cpu_add(memcg
->stat
->count
[MEM_CGROUP_STAT_SWAP
], val
);
792 static unsigned long mem_cgroup_read_events(struct mem_cgroup
*memcg
,
793 enum mem_cgroup_events_index idx
)
795 unsigned long val
= 0;
798 for_each_online_cpu(cpu
)
799 val
+= per_cpu(memcg
->stat
->events
[idx
], cpu
);
800 #ifdef CONFIG_HOTPLUG_CPU
801 spin_lock(&memcg
->pcp_counter_lock
);
802 val
+= memcg
->nocpu_base
.events
[idx
];
803 spin_unlock(&memcg
->pcp_counter_lock
);
808 static void mem_cgroup_charge_statistics(struct mem_cgroup
*memcg
,
809 bool anon
, int nr_pages
)
814 * Here, RSS means 'mapped anon' and anon's SwapCache. Shmem/tmpfs is
815 * counted as CACHE even if it's on ANON LRU.
818 __this_cpu_add(memcg
->stat
->count
[MEM_CGROUP_STAT_RSS
],
821 __this_cpu_add(memcg
->stat
->count
[MEM_CGROUP_STAT_CACHE
],
824 /* pagein of a big page is an event. So, ignore page size */
826 __this_cpu_inc(memcg
->stat
->events
[MEM_CGROUP_EVENTS_PGPGIN
]);
828 __this_cpu_inc(memcg
->stat
->events
[MEM_CGROUP_EVENTS_PGPGOUT
]);
829 nr_pages
= -nr_pages
; /* for event */
832 __this_cpu_add(memcg
->stat
->nr_page_events
, nr_pages
);
838 mem_cgroup_get_lru_size(struct lruvec
*lruvec
, enum lru_list lru
)
840 struct mem_cgroup_per_zone
*mz
;
842 mz
= container_of(lruvec
, struct mem_cgroup_per_zone
, lruvec
);
843 return mz
->lru_size
[lru
];
847 mem_cgroup_zone_nr_lru_pages(struct mem_cgroup
*memcg
, int nid
, int zid
,
848 unsigned int lru_mask
)
850 struct mem_cgroup_per_zone
*mz
;
852 unsigned long ret
= 0;
854 mz
= mem_cgroup_zoneinfo(memcg
, nid
, zid
);
857 if (BIT(lru
) & lru_mask
)
858 ret
+= mz
->lru_size
[lru
];
864 mem_cgroup_node_nr_lru_pages(struct mem_cgroup
*memcg
,
865 int nid
, unsigned int lru_mask
)
870 for (zid
= 0; zid
< MAX_NR_ZONES
; zid
++)
871 total
+= mem_cgroup_zone_nr_lru_pages(memcg
,
877 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup
*memcg
,
878 unsigned int lru_mask
)
883 for_each_node_state(nid
, N_MEMORY
)
884 total
+= mem_cgroup_node_nr_lru_pages(memcg
, nid
, lru_mask
);
888 static bool mem_cgroup_event_ratelimit(struct mem_cgroup
*memcg
,
889 enum mem_cgroup_events_target target
)
891 unsigned long val
, next
;
893 val
= __this_cpu_read(memcg
->stat
->nr_page_events
);
894 next
= __this_cpu_read(memcg
->stat
->targets
[target
]);
895 /* from time_after() in jiffies.h */
896 if ((long)next
- (long)val
< 0) {
898 case MEM_CGROUP_TARGET_THRESH
:
899 next
= val
+ THRESHOLDS_EVENTS_TARGET
;
901 case MEM_CGROUP_TARGET_SOFTLIMIT
:
902 next
= val
+ SOFTLIMIT_EVENTS_TARGET
;
904 case MEM_CGROUP_TARGET_NUMAINFO
:
905 next
= val
+ NUMAINFO_EVENTS_TARGET
;
910 __this_cpu_write(memcg
->stat
->targets
[target
], next
);
917 * Check events in order.
920 static void memcg_check_events(struct mem_cgroup
*memcg
, struct page
*page
)
923 /* threshold event is triggered in finer grain than soft limit */
924 if (unlikely(mem_cgroup_event_ratelimit(memcg
,
925 MEM_CGROUP_TARGET_THRESH
))) {
927 bool do_numainfo __maybe_unused
;
929 do_softlimit
= mem_cgroup_event_ratelimit(memcg
,
930 MEM_CGROUP_TARGET_SOFTLIMIT
);
932 do_numainfo
= mem_cgroup_event_ratelimit(memcg
,
933 MEM_CGROUP_TARGET_NUMAINFO
);
937 mem_cgroup_threshold(memcg
);
938 if (unlikely(do_softlimit
))
939 mem_cgroup_update_tree(memcg
, page
);
941 if (unlikely(do_numainfo
))
942 atomic_inc(&memcg
->numainfo_events
);
948 struct mem_cgroup
*mem_cgroup_from_cont(struct cgroup
*cont
)
950 return mem_cgroup_from_css(
951 cgroup_subsys_state(cont
, mem_cgroup_subsys_id
));
954 struct mem_cgroup
*mem_cgroup_from_task(struct task_struct
*p
)
957 * mm_update_next_owner() may clear mm->owner to NULL
958 * if it races with swapoff, page migration, etc.
959 * So this can be called with p == NULL.
964 return mem_cgroup_from_css(task_subsys_state(p
, mem_cgroup_subsys_id
));
967 struct mem_cgroup
*try_get_mem_cgroup_from_mm(struct mm_struct
*mm
)
969 struct mem_cgroup
*memcg
= NULL
;
974 * Because we have no locks, mm->owner's may be being moved to other
975 * cgroup. We use css_tryget() here even if this looks
976 * pessimistic (rather than adding locks here).
980 memcg
= mem_cgroup_from_task(rcu_dereference(mm
->owner
));
981 if (unlikely(!memcg
))
983 } while (!css_tryget(&memcg
->css
));
989 * mem_cgroup_iter - iterate over memory cgroup hierarchy
990 * @root: hierarchy root
991 * @prev: previously returned memcg, NULL on first invocation
992 * @reclaim: cookie for shared reclaim walks, NULL for full walks
994 * Returns references to children of the hierarchy below @root, or
995 * @root itself, or %NULL after a full round-trip.
997 * Caller must pass the return value in @prev on subsequent
998 * invocations for reference counting, or use mem_cgroup_iter_break()
999 * to cancel a hierarchy walk before the round-trip is complete.
1001 * Reclaimers can specify a zone and a priority level in @reclaim to
1002 * divide up the memcgs in the hierarchy among all concurrent
1003 * reclaimers operating on the same zone and priority.
1005 struct mem_cgroup
*mem_cgroup_iter(struct mem_cgroup
*root
,
1006 struct mem_cgroup
*prev
,
1007 struct mem_cgroup_reclaim_cookie
*reclaim
)
1009 struct mem_cgroup
*memcg
= NULL
;
1012 if (mem_cgroup_disabled())
1016 root
= root_mem_cgroup
;
1018 if (prev
&& !reclaim
)
1019 id
= css_id(&prev
->css
);
1021 if (prev
&& prev
!= root
)
1022 css_put(&prev
->css
);
1024 if (!root
->use_hierarchy
&& root
!= root_mem_cgroup
) {
1031 struct mem_cgroup_reclaim_iter
*uninitialized_var(iter
);
1032 struct cgroup_subsys_state
*css
;
1035 int nid
= zone_to_nid(reclaim
->zone
);
1036 int zid
= zone_idx(reclaim
->zone
);
1037 struct mem_cgroup_per_zone
*mz
;
1039 mz
= mem_cgroup_zoneinfo(root
, nid
, zid
);
1040 iter
= &mz
->reclaim_iter
[reclaim
->priority
];
1041 if (prev
&& reclaim
->generation
!= iter
->generation
)
1043 id
= iter
->position
;
1047 css
= css_get_next(&mem_cgroup_subsys
, id
+ 1, &root
->css
, &id
);
1049 if (css
== &root
->css
|| css_tryget(css
))
1050 memcg
= mem_cgroup_from_css(css
);
1056 iter
->position
= id
;
1059 else if (!prev
&& memcg
)
1060 reclaim
->generation
= iter
->generation
;
1070 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1071 * @root: hierarchy root
1072 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1074 void mem_cgroup_iter_break(struct mem_cgroup
*root
,
1075 struct mem_cgroup
*prev
)
1078 root
= root_mem_cgroup
;
1079 if (prev
&& prev
!= root
)
1080 css_put(&prev
->css
);
1084 * Iteration constructs for visiting all cgroups (under a tree). If
1085 * loops are exited prematurely (break), mem_cgroup_iter_break() must
1086 * be used for reference counting.
1088 #define for_each_mem_cgroup_tree(iter, root) \
1089 for (iter = mem_cgroup_iter(root, NULL, NULL); \
1091 iter = mem_cgroup_iter(root, iter, NULL))
1093 #define for_each_mem_cgroup(iter) \
1094 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
1096 iter = mem_cgroup_iter(NULL, iter, NULL))
1098 void __mem_cgroup_count_vm_event(struct mm_struct
*mm
, enum vm_event_item idx
)
1100 struct mem_cgroup
*memcg
;
1103 memcg
= mem_cgroup_from_task(rcu_dereference(mm
->owner
));
1104 if (unlikely(!memcg
))
1109 this_cpu_inc(memcg
->stat
->events
[MEM_CGROUP_EVENTS_PGFAULT
]);
1112 this_cpu_inc(memcg
->stat
->events
[MEM_CGROUP_EVENTS_PGMAJFAULT
]);
1120 EXPORT_SYMBOL(__mem_cgroup_count_vm_event
);
1123 * mem_cgroup_zone_lruvec - get the lru list vector for a zone and memcg
1124 * @zone: zone of the wanted lruvec
1125 * @memcg: memcg of the wanted lruvec
1127 * Returns the lru list vector holding pages for the given @zone and
1128 * @mem. This can be the global zone lruvec, if the memory controller
1131 struct lruvec
*mem_cgroup_zone_lruvec(struct zone
*zone
,
1132 struct mem_cgroup
*memcg
)
1134 struct mem_cgroup_per_zone
*mz
;
1135 struct lruvec
*lruvec
;
1137 if (mem_cgroup_disabled()) {
1138 lruvec
= &zone
->lruvec
;
1142 mz
= mem_cgroup_zoneinfo(memcg
, zone_to_nid(zone
), zone_idx(zone
));
1143 lruvec
= &mz
->lruvec
;
1146 * Since a node can be onlined after the mem_cgroup was created,
1147 * we have to be prepared to initialize lruvec->zone here;
1148 * and if offlined then reonlined, we need to reinitialize it.
1150 if (unlikely(lruvec
->zone
!= zone
))
1151 lruvec
->zone
= zone
;
1156 * Following LRU functions are allowed to be used without PCG_LOCK.
1157 * Operations are called by routine of global LRU independently from memcg.
1158 * What we have to take care of here is validness of pc->mem_cgroup.
1160 * Changes to pc->mem_cgroup happens when
1163 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
1164 * It is added to LRU before charge.
1165 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
1166 * When moving account, the page is not on LRU. It's isolated.
1170 * mem_cgroup_page_lruvec - return lruvec for adding an lru page
1172 * @zone: zone of the page
1174 struct lruvec
*mem_cgroup_page_lruvec(struct page
*page
, struct zone
*zone
)
1176 struct mem_cgroup_per_zone
*mz
;
1177 struct mem_cgroup
*memcg
;
1178 struct page_cgroup
*pc
;
1179 struct lruvec
*lruvec
;
1181 if (mem_cgroup_disabled()) {
1182 lruvec
= &zone
->lruvec
;
1186 pc
= lookup_page_cgroup(page
);
1187 memcg
= pc
->mem_cgroup
;
1190 * Surreptitiously switch any uncharged offlist page to root:
1191 * an uncharged page off lru does nothing to secure
1192 * its former mem_cgroup from sudden removal.
1194 * Our caller holds lru_lock, and PageCgroupUsed is updated
1195 * under page_cgroup lock: between them, they make all uses
1196 * of pc->mem_cgroup safe.
1198 if (!PageLRU(page
) && !PageCgroupUsed(pc
) && memcg
!= root_mem_cgroup
)
1199 pc
->mem_cgroup
= memcg
= root_mem_cgroup
;
1201 mz
= page_cgroup_zoneinfo(memcg
, page
);
1202 lruvec
= &mz
->lruvec
;
1205 * Since a node can be onlined after the mem_cgroup was created,
1206 * we have to be prepared to initialize lruvec->zone here;
1207 * and if offlined then reonlined, we need to reinitialize it.
1209 if (unlikely(lruvec
->zone
!= zone
))
1210 lruvec
->zone
= zone
;
1215 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1216 * @lruvec: mem_cgroup per zone lru vector
1217 * @lru: index of lru list the page is sitting on
1218 * @nr_pages: positive when adding or negative when removing
1220 * This function must be called when a page is added to or removed from an
1223 void mem_cgroup_update_lru_size(struct lruvec
*lruvec
, enum lru_list lru
,
1226 struct mem_cgroup_per_zone
*mz
;
1227 unsigned long *lru_size
;
1229 if (mem_cgroup_disabled())
1232 mz
= container_of(lruvec
, struct mem_cgroup_per_zone
, lruvec
);
1233 lru_size
= mz
->lru_size
+ lru
;
1234 *lru_size
+= nr_pages
;
1235 VM_BUG_ON((long)(*lru_size
) < 0);
1239 * Checks whether given mem is same or in the root_mem_cgroup's
1242 bool __mem_cgroup_same_or_subtree(const struct mem_cgroup
*root_memcg
,
1243 struct mem_cgroup
*memcg
)
1245 if (root_memcg
== memcg
)
1247 if (!root_memcg
->use_hierarchy
|| !memcg
)
1249 return css_is_ancestor(&memcg
->css
, &root_memcg
->css
);
1252 static bool mem_cgroup_same_or_subtree(const struct mem_cgroup
*root_memcg
,
1253 struct mem_cgroup
*memcg
)
1258 ret
= __mem_cgroup_same_or_subtree(root_memcg
, memcg
);
1263 int task_in_mem_cgroup(struct task_struct
*task
, const struct mem_cgroup
*memcg
)
1266 struct mem_cgroup
*curr
= NULL
;
1267 struct task_struct
*p
;
1269 p
= find_lock_task_mm(task
);
1271 curr
= try_get_mem_cgroup_from_mm(p
->mm
);
1275 * All threads may have already detached their mm's, but the oom
1276 * killer still needs to detect if they have already been oom
1277 * killed to prevent needlessly killing additional tasks.
1280 curr
= mem_cgroup_from_task(task
);
1282 css_get(&curr
->css
);
1288 * We should check use_hierarchy of "memcg" not "curr". Because checking
1289 * use_hierarchy of "curr" here make this function true if hierarchy is
1290 * enabled in "curr" and "curr" is a child of "memcg" in *cgroup*
1291 * hierarchy(even if use_hierarchy is disabled in "memcg").
1293 ret
= mem_cgroup_same_or_subtree(memcg
, curr
);
1294 css_put(&curr
->css
);
1298 int mem_cgroup_inactive_anon_is_low(struct lruvec
*lruvec
)
1300 unsigned long inactive_ratio
;
1301 unsigned long inactive
;
1302 unsigned long active
;
1305 inactive
= mem_cgroup_get_lru_size(lruvec
, LRU_INACTIVE_ANON
);
1306 active
= mem_cgroup_get_lru_size(lruvec
, LRU_ACTIVE_ANON
);
1308 gb
= (inactive
+ active
) >> (30 - PAGE_SHIFT
);
1310 inactive_ratio
= int_sqrt(10 * gb
);
1314 return inactive
* inactive_ratio
< active
;
1317 int mem_cgroup_inactive_file_is_low(struct lruvec
*lruvec
)
1319 unsigned long active
;
1320 unsigned long inactive
;
1322 inactive
= mem_cgroup_get_lru_size(lruvec
, LRU_INACTIVE_FILE
);
1323 active
= mem_cgroup_get_lru_size(lruvec
, LRU_ACTIVE_FILE
);
1325 return (active
> inactive
);
1328 #define mem_cgroup_from_res_counter(counter, member) \
1329 container_of(counter, struct mem_cgroup, member)
1332 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1333 * @memcg: the memory cgroup
1335 * Returns the maximum amount of memory @mem can be charged with, in
1338 static unsigned long mem_cgroup_margin(struct mem_cgroup
*memcg
)
1340 unsigned long long margin
;
1342 margin
= res_counter_margin(&memcg
->res
);
1343 if (do_swap_account
)
1344 margin
= min(margin
, res_counter_margin(&memcg
->memsw
));
1345 return margin
>> PAGE_SHIFT
;
1348 int mem_cgroup_swappiness(struct mem_cgroup
*memcg
)
1350 struct cgroup
*cgrp
= memcg
->css
.cgroup
;
1353 if (cgrp
->parent
== NULL
)
1354 return vm_swappiness
;
1356 return memcg
->swappiness
;
1360 * memcg->moving_account is used for checking possibility that some thread is
1361 * calling move_account(). When a thread on CPU-A starts moving pages under
1362 * a memcg, other threads should check memcg->moving_account under
1363 * rcu_read_lock(), like this:
1367 * memcg->moving_account+1 if (memcg->mocing_account)
1369 * synchronize_rcu() update something.
1374 /* for quick checking without looking up memcg */
1375 atomic_t memcg_moving __read_mostly
;
1377 static void mem_cgroup_start_move(struct mem_cgroup
*memcg
)
1379 atomic_inc(&memcg_moving
);
1380 atomic_inc(&memcg
->moving_account
);
1384 static void mem_cgroup_end_move(struct mem_cgroup
*memcg
)
1387 * Now, mem_cgroup_clear_mc() may call this function with NULL.
1388 * We check NULL in callee rather than caller.
1391 atomic_dec(&memcg_moving
);
1392 atomic_dec(&memcg
->moving_account
);
1397 * 2 routines for checking "mem" is under move_account() or not.
1399 * mem_cgroup_stolen() - checking whether a cgroup is mc.from or not. This
1400 * is used for avoiding races in accounting. If true,
1401 * pc->mem_cgroup may be overwritten.
1403 * mem_cgroup_under_move() - checking a cgroup is mc.from or mc.to or
1404 * under hierarchy of moving cgroups. This is for
1405 * waiting at hith-memory prressure caused by "move".
1408 static bool mem_cgroup_stolen(struct mem_cgroup
*memcg
)
1410 VM_BUG_ON(!rcu_read_lock_held());
1411 return atomic_read(&memcg
->moving_account
) > 0;
1414 static bool mem_cgroup_under_move(struct mem_cgroup
*memcg
)
1416 struct mem_cgroup
*from
;
1417 struct mem_cgroup
*to
;
1420 * Unlike task_move routines, we access mc.to, mc.from not under
1421 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1423 spin_lock(&mc
.lock
);
1429 ret
= mem_cgroup_same_or_subtree(memcg
, from
)
1430 || mem_cgroup_same_or_subtree(memcg
, to
);
1432 spin_unlock(&mc
.lock
);
1436 static bool mem_cgroup_wait_acct_move(struct mem_cgroup
*memcg
)
1438 if (mc
.moving_task
&& current
!= mc
.moving_task
) {
1439 if (mem_cgroup_under_move(memcg
)) {
1441 prepare_to_wait(&mc
.waitq
, &wait
, TASK_INTERRUPTIBLE
);
1442 /* moving charge context might have finished. */
1445 finish_wait(&mc
.waitq
, &wait
);
1453 * Take this lock when
1454 * - a code tries to modify page's memcg while it's USED.
1455 * - a code tries to modify page state accounting in a memcg.
1456 * see mem_cgroup_stolen(), too.
1458 static void move_lock_mem_cgroup(struct mem_cgroup
*memcg
,
1459 unsigned long *flags
)
1461 spin_lock_irqsave(&memcg
->move_lock
, *flags
);
1464 static void move_unlock_mem_cgroup(struct mem_cgroup
*memcg
,
1465 unsigned long *flags
)
1467 spin_unlock_irqrestore(&memcg
->move_lock
, *flags
);
1471 * mem_cgroup_print_oom_info: Called from OOM with tasklist_lock held in read mode.
1472 * @memcg: The memory cgroup that went over limit
1473 * @p: Task that is going to be killed
1475 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1478 void mem_cgroup_print_oom_info(struct mem_cgroup
*memcg
, struct task_struct
*p
)
1480 struct cgroup
*task_cgrp
;
1481 struct cgroup
*mem_cgrp
;
1483 * Need a buffer in BSS, can't rely on allocations. The code relies
1484 * on the assumption that OOM is serialized for memory controller.
1485 * If this assumption is broken, revisit this code.
1487 static char memcg_name
[PATH_MAX
];
1495 mem_cgrp
= memcg
->css
.cgroup
;
1496 task_cgrp
= task_cgroup(p
, mem_cgroup_subsys_id
);
1498 ret
= cgroup_path(task_cgrp
, memcg_name
, PATH_MAX
);
1501 * Unfortunately, we are unable to convert to a useful name
1502 * But we'll still print out the usage information
1509 printk(KERN_INFO
"Task in %s killed", memcg_name
);
1512 ret
= cgroup_path(mem_cgrp
, memcg_name
, PATH_MAX
);
1520 * Continues from above, so we don't need an KERN_ level
1522 printk(KERN_CONT
" as a result of limit of %s\n", memcg_name
);
1525 printk(KERN_INFO
"memory: usage %llukB, limit %llukB, failcnt %llu\n",
1526 res_counter_read_u64(&memcg
->res
, RES_USAGE
) >> 10,
1527 res_counter_read_u64(&memcg
->res
, RES_LIMIT
) >> 10,
1528 res_counter_read_u64(&memcg
->res
, RES_FAILCNT
));
1529 printk(KERN_INFO
"memory+swap: usage %llukB, limit %llukB, "
1531 res_counter_read_u64(&memcg
->memsw
, RES_USAGE
) >> 10,
1532 res_counter_read_u64(&memcg
->memsw
, RES_LIMIT
) >> 10,
1533 res_counter_read_u64(&memcg
->memsw
, RES_FAILCNT
));
1534 printk(KERN_INFO
"kmem: usage %llukB, limit %llukB, failcnt %llu\n",
1535 res_counter_read_u64(&memcg
->kmem
, RES_USAGE
) >> 10,
1536 res_counter_read_u64(&memcg
->kmem
, RES_LIMIT
) >> 10,
1537 res_counter_read_u64(&memcg
->kmem
, RES_FAILCNT
));
1541 * This function returns the number of memcg under hierarchy tree. Returns
1542 * 1(self count) if no children.
1544 static int mem_cgroup_count_children(struct mem_cgroup
*memcg
)
1547 struct mem_cgroup
*iter
;
1549 for_each_mem_cgroup_tree(iter
, memcg
)
1555 * Return the memory (and swap, if configured) limit for a memcg.
1557 static u64
mem_cgroup_get_limit(struct mem_cgroup
*memcg
)
1561 limit
= res_counter_read_u64(&memcg
->res
, RES_LIMIT
);
1564 * Do not consider swap space if we cannot swap due to swappiness
1566 if (mem_cgroup_swappiness(memcg
)) {
1569 limit
+= total_swap_pages
<< PAGE_SHIFT
;
1570 memsw
= res_counter_read_u64(&memcg
->memsw
, RES_LIMIT
);
1573 * If memsw is finite and limits the amount of swap space
1574 * available to this memcg, return that limit.
1576 limit
= min(limit
, memsw
);
1582 static void mem_cgroup_out_of_memory(struct mem_cgroup
*memcg
, gfp_t gfp_mask
,
1585 struct mem_cgroup
*iter
;
1586 unsigned long chosen_points
= 0;
1587 unsigned long totalpages
;
1588 unsigned int points
= 0;
1589 struct task_struct
*chosen
= NULL
;
1592 * If current has a pending SIGKILL, then automatically select it. The
1593 * goal is to allow it to allocate so that it may quickly exit and free
1596 if (fatal_signal_pending(current
)) {
1597 set_thread_flag(TIF_MEMDIE
);
1601 check_panic_on_oom(CONSTRAINT_MEMCG
, gfp_mask
, order
, NULL
);
1602 totalpages
= mem_cgroup_get_limit(memcg
) >> PAGE_SHIFT
? : 1;
1603 for_each_mem_cgroup_tree(iter
, memcg
) {
1604 struct cgroup
*cgroup
= iter
->css
.cgroup
;
1605 struct cgroup_iter it
;
1606 struct task_struct
*task
;
1608 cgroup_iter_start(cgroup
, &it
);
1609 while ((task
= cgroup_iter_next(cgroup
, &it
))) {
1610 switch (oom_scan_process_thread(task
, totalpages
, NULL
,
1612 case OOM_SCAN_SELECT
:
1614 put_task_struct(chosen
);
1616 chosen_points
= ULONG_MAX
;
1617 get_task_struct(chosen
);
1619 case OOM_SCAN_CONTINUE
:
1621 case OOM_SCAN_ABORT
:
1622 cgroup_iter_end(cgroup
, &it
);
1623 mem_cgroup_iter_break(memcg
, iter
);
1625 put_task_struct(chosen
);
1630 points
= oom_badness(task
, memcg
, NULL
, totalpages
);
1631 if (points
> chosen_points
) {
1633 put_task_struct(chosen
);
1635 chosen_points
= points
;
1636 get_task_struct(chosen
);
1639 cgroup_iter_end(cgroup
, &it
);
1644 points
= chosen_points
* 1000 / totalpages
;
1645 oom_kill_process(chosen
, gfp_mask
, order
, points
, totalpages
, memcg
,
1646 NULL
, "Memory cgroup out of memory");
1649 static unsigned long mem_cgroup_reclaim(struct mem_cgroup
*memcg
,
1651 unsigned long flags
)
1653 unsigned long total
= 0;
1654 bool noswap
= false;
1657 if (flags
& MEM_CGROUP_RECLAIM_NOSWAP
)
1659 if (!(flags
& MEM_CGROUP_RECLAIM_SHRINK
) && memcg
->memsw_is_minimum
)
1662 for (loop
= 0; loop
< MEM_CGROUP_MAX_RECLAIM_LOOPS
; loop
++) {
1664 drain_all_stock_async(memcg
);
1665 total
+= try_to_free_mem_cgroup_pages(memcg
, gfp_mask
, noswap
);
1667 * Allow limit shrinkers, which are triggered directly
1668 * by userspace, to catch signals and stop reclaim
1669 * after minimal progress, regardless of the margin.
1671 if (total
&& (flags
& MEM_CGROUP_RECLAIM_SHRINK
))
1673 if (mem_cgroup_margin(memcg
))
1676 * If nothing was reclaimed after two attempts, there
1677 * may be no reclaimable pages in this hierarchy.
1686 * test_mem_cgroup_node_reclaimable
1687 * @memcg: the target memcg
1688 * @nid: the node ID to be checked.
1689 * @noswap : specify true here if the user wants flle only information.
1691 * This function returns whether the specified memcg contains any
1692 * reclaimable pages on a node. Returns true if there are any reclaimable
1693 * pages in the node.
1695 static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup
*memcg
,
1696 int nid
, bool noswap
)
1698 if (mem_cgroup_node_nr_lru_pages(memcg
, nid
, LRU_ALL_FILE
))
1700 if (noswap
|| !total_swap_pages
)
1702 if (mem_cgroup_node_nr_lru_pages(memcg
, nid
, LRU_ALL_ANON
))
1707 #if MAX_NUMNODES > 1
1710 * Always updating the nodemask is not very good - even if we have an empty
1711 * list or the wrong list here, we can start from some node and traverse all
1712 * nodes based on the zonelist. So update the list loosely once per 10 secs.
1715 static void mem_cgroup_may_update_nodemask(struct mem_cgroup
*memcg
)
1719 * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
1720 * pagein/pageout changes since the last update.
1722 if (!atomic_read(&memcg
->numainfo_events
))
1724 if (atomic_inc_return(&memcg
->numainfo_updating
) > 1)
1727 /* make a nodemask where this memcg uses memory from */
1728 memcg
->scan_nodes
= node_states
[N_MEMORY
];
1730 for_each_node_mask(nid
, node_states
[N_MEMORY
]) {
1732 if (!test_mem_cgroup_node_reclaimable(memcg
, nid
, false))
1733 node_clear(nid
, memcg
->scan_nodes
);
1736 atomic_set(&memcg
->numainfo_events
, 0);
1737 atomic_set(&memcg
->numainfo_updating
, 0);
1741 * Selecting a node where we start reclaim from. Because what we need is just
1742 * reducing usage counter, start from anywhere is O,K. Considering
1743 * memory reclaim from current node, there are pros. and cons.
1745 * Freeing memory from current node means freeing memory from a node which
1746 * we'll use or we've used. So, it may make LRU bad. And if several threads
1747 * hit limits, it will see a contention on a node. But freeing from remote
1748 * node means more costs for memory reclaim because of memory latency.
1750 * Now, we use round-robin. Better algorithm is welcomed.
1752 int mem_cgroup_select_victim_node(struct mem_cgroup
*memcg
)
1756 mem_cgroup_may_update_nodemask(memcg
);
1757 node
= memcg
->last_scanned_node
;
1759 node
= next_node(node
, memcg
->scan_nodes
);
1760 if (node
== MAX_NUMNODES
)
1761 node
= first_node(memcg
->scan_nodes
);
1763 * We call this when we hit limit, not when pages are added to LRU.
1764 * No LRU may hold pages because all pages are UNEVICTABLE or
1765 * memcg is too small and all pages are not on LRU. In that case,
1766 * we use curret node.
1768 if (unlikely(node
== MAX_NUMNODES
))
1769 node
= numa_node_id();
1771 memcg
->last_scanned_node
= node
;
1776 * Check all nodes whether it contains reclaimable pages or not.
1777 * For quick scan, we make use of scan_nodes. This will allow us to skip
1778 * unused nodes. But scan_nodes is lazily updated and may not cotain
1779 * enough new information. We need to do double check.
1781 static bool mem_cgroup_reclaimable(struct mem_cgroup
*memcg
, bool noswap
)
1786 * quick check...making use of scan_node.
1787 * We can skip unused nodes.
1789 if (!nodes_empty(memcg
->scan_nodes
)) {
1790 for (nid
= first_node(memcg
->scan_nodes
);
1792 nid
= next_node(nid
, memcg
->scan_nodes
)) {
1794 if (test_mem_cgroup_node_reclaimable(memcg
, nid
, noswap
))
1799 * Check rest of nodes.
1801 for_each_node_state(nid
, N_MEMORY
) {
1802 if (node_isset(nid
, memcg
->scan_nodes
))
1804 if (test_mem_cgroup_node_reclaimable(memcg
, nid
, noswap
))
1811 int mem_cgroup_select_victim_node(struct mem_cgroup
*memcg
)
1816 static bool mem_cgroup_reclaimable(struct mem_cgroup
*memcg
, bool noswap
)
1818 return test_mem_cgroup_node_reclaimable(memcg
, 0, noswap
);
1822 static int mem_cgroup_soft_reclaim(struct mem_cgroup
*root_memcg
,
1825 unsigned long *total_scanned
)
1827 struct mem_cgroup
*victim
= NULL
;
1830 unsigned long excess
;
1831 unsigned long nr_scanned
;
1832 struct mem_cgroup_reclaim_cookie reclaim
= {
1837 excess
= res_counter_soft_limit_excess(&root_memcg
->res
) >> PAGE_SHIFT
;
1840 victim
= mem_cgroup_iter(root_memcg
, victim
, &reclaim
);
1845 * If we have not been able to reclaim
1846 * anything, it might because there are
1847 * no reclaimable pages under this hierarchy
1852 * We want to do more targeted reclaim.
1853 * excess >> 2 is not to excessive so as to
1854 * reclaim too much, nor too less that we keep
1855 * coming back to reclaim from this cgroup
1857 if (total
>= (excess
>> 2) ||
1858 (loop
> MEM_CGROUP_MAX_RECLAIM_LOOPS
))
1863 if (!mem_cgroup_reclaimable(victim
, false))
1865 total
+= mem_cgroup_shrink_node_zone(victim
, gfp_mask
, false,
1867 *total_scanned
+= nr_scanned
;
1868 if (!res_counter_soft_limit_excess(&root_memcg
->res
))
1871 mem_cgroup_iter_break(root_memcg
, victim
);
1876 * Check OOM-Killer is already running under our hierarchy.
1877 * If someone is running, return false.
1878 * Has to be called with memcg_oom_lock
1880 static bool mem_cgroup_oom_lock(struct mem_cgroup
*memcg
)
1882 struct mem_cgroup
*iter
, *failed
= NULL
;
1884 for_each_mem_cgroup_tree(iter
, memcg
) {
1885 if (iter
->oom_lock
) {
1887 * this subtree of our hierarchy is already locked
1888 * so we cannot give a lock.
1891 mem_cgroup_iter_break(memcg
, iter
);
1894 iter
->oom_lock
= true;
1901 * OK, we failed to lock the whole subtree so we have to clean up
1902 * what we set up to the failing subtree
1904 for_each_mem_cgroup_tree(iter
, memcg
) {
1905 if (iter
== failed
) {
1906 mem_cgroup_iter_break(memcg
, iter
);
1909 iter
->oom_lock
= false;
1915 * Has to be called with memcg_oom_lock
1917 static int mem_cgroup_oom_unlock(struct mem_cgroup
*memcg
)
1919 struct mem_cgroup
*iter
;
1921 for_each_mem_cgroup_tree(iter
, memcg
)
1922 iter
->oom_lock
= false;
1926 static void mem_cgroup_mark_under_oom(struct mem_cgroup
*memcg
)
1928 struct mem_cgroup
*iter
;
1930 for_each_mem_cgroup_tree(iter
, memcg
)
1931 atomic_inc(&iter
->under_oom
);
1934 static void mem_cgroup_unmark_under_oom(struct mem_cgroup
*memcg
)
1936 struct mem_cgroup
*iter
;
1939 * When a new child is created while the hierarchy is under oom,
1940 * mem_cgroup_oom_lock() may not be called. We have to use
1941 * atomic_add_unless() here.
1943 for_each_mem_cgroup_tree(iter
, memcg
)
1944 atomic_add_unless(&iter
->under_oom
, -1, 0);
1947 static DEFINE_SPINLOCK(memcg_oom_lock
);
1948 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq
);
1950 struct oom_wait_info
{
1951 struct mem_cgroup
*memcg
;
1955 static int memcg_oom_wake_function(wait_queue_t
*wait
,
1956 unsigned mode
, int sync
, void *arg
)
1958 struct mem_cgroup
*wake_memcg
= (struct mem_cgroup
*)arg
;
1959 struct mem_cgroup
*oom_wait_memcg
;
1960 struct oom_wait_info
*oom_wait_info
;
1962 oom_wait_info
= container_of(wait
, struct oom_wait_info
, wait
);
1963 oom_wait_memcg
= oom_wait_info
->memcg
;
1966 * Both of oom_wait_info->memcg and wake_memcg are stable under us.
1967 * Then we can use css_is_ancestor without taking care of RCU.
1969 if (!mem_cgroup_same_or_subtree(oom_wait_memcg
, wake_memcg
)
1970 && !mem_cgroup_same_or_subtree(wake_memcg
, oom_wait_memcg
))
1972 return autoremove_wake_function(wait
, mode
, sync
, arg
);
1975 static void memcg_wakeup_oom(struct mem_cgroup
*memcg
)
1977 /* for filtering, pass "memcg" as argument. */
1978 __wake_up(&memcg_oom_waitq
, TASK_NORMAL
, 0, memcg
);
1981 static void memcg_oom_recover(struct mem_cgroup
*memcg
)
1983 if (memcg
&& atomic_read(&memcg
->under_oom
))
1984 memcg_wakeup_oom(memcg
);
1988 * try to call OOM killer. returns false if we should exit memory-reclaim loop.
1990 static bool mem_cgroup_handle_oom(struct mem_cgroup
*memcg
, gfp_t mask
,
1993 struct oom_wait_info owait
;
1994 bool locked
, need_to_kill
;
1996 owait
.memcg
= memcg
;
1997 owait
.wait
.flags
= 0;
1998 owait
.wait
.func
= memcg_oom_wake_function
;
1999 owait
.wait
.private = current
;
2000 INIT_LIST_HEAD(&owait
.wait
.task_list
);
2001 need_to_kill
= true;
2002 mem_cgroup_mark_under_oom(memcg
);
2004 /* At first, try to OOM lock hierarchy under memcg.*/
2005 spin_lock(&memcg_oom_lock
);
2006 locked
= mem_cgroup_oom_lock(memcg
);
2008 * Even if signal_pending(), we can't quit charge() loop without
2009 * accounting. So, UNINTERRUPTIBLE is appropriate. But SIGKILL
2010 * under OOM is always welcomed, use TASK_KILLABLE here.
2012 prepare_to_wait(&memcg_oom_waitq
, &owait
.wait
, TASK_KILLABLE
);
2013 if (!locked
|| memcg
->oom_kill_disable
)
2014 need_to_kill
= false;
2016 mem_cgroup_oom_notify(memcg
);
2017 spin_unlock(&memcg_oom_lock
);
2020 finish_wait(&memcg_oom_waitq
, &owait
.wait
);
2021 mem_cgroup_out_of_memory(memcg
, mask
, order
);
2024 finish_wait(&memcg_oom_waitq
, &owait
.wait
);
2026 spin_lock(&memcg_oom_lock
);
2028 mem_cgroup_oom_unlock(memcg
);
2029 memcg_wakeup_oom(memcg
);
2030 spin_unlock(&memcg_oom_lock
);
2032 mem_cgroup_unmark_under_oom(memcg
);
2034 if (test_thread_flag(TIF_MEMDIE
) || fatal_signal_pending(current
))
2036 /* Give chance to dying process */
2037 schedule_timeout_uninterruptible(1);
2042 * Currently used to update mapped file statistics, but the routine can be
2043 * generalized to update other statistics as well.
2045 * Notes: Race condition
2047 * We usually use page_cgroup_lock() for accessing page_cgroup member but
2048 * it tends to be costly. But considering some conditions, we doesn't need
2049 * to do so _always_.
2051 * Considering "charge", lock_page_cgroup() is not required because all
2052 * file-stat operations happen after a page is attached to radix-tree. There
2053 * are no race with "charge".
2055 * Considering "uncharge", we know that memcg doesn't clear pc->mem_cgroup
2056 * at "uncharge" intentionally. So, we always see valid pc->mem_cgroup even
2057 * if there are race with "uncharge". Statistics itself is properly handled
2060 * Considering "move", this is an only case we see a race. To make the race
2061 * small, we check mm->moving_account and detect there are possibility of race
2062 * If there is, we take a lock.
2065 void __mem_cgroup_begin_update_page_stat(struct page
*page
,
2066 bool *locked
, unsigned long *flags
)
2068 struct mem_cgroup
*memcg
;
2069 struct page_cgroup
*pc
;
2071 pc
= lookup_page_cgroup(page
);
2073 memcg
= pc
->mem_cgroup
;
2074 if (unlikely(!memcg
|| !PageCgroupUsed(pc
)))
2077 * If this memory cgroup is not under account moving, we don't
2078 * need to take move_lock_mem_cgroup(). Because we already hold
2079 * rcu_read_lock(), any calls to move_account will be delayed until
2080 * rcu_read_unlock() if mem_cgroup_stolen() == true.
2082 if (!mem_cgroup_stolen(memcg
))
2085 move_lock_mem_cgroup(memcg
, flags
);
2086 if (memcg
!= pc
->mem_cgroup
|| !PageCgroupUsed(pc
)) {
2087 move_unlock_mem_cgroup(memcg
, flags
);
2093 void __mem_cgroup_end_update_page_stat(struct page
*page
, unsigned long *flags
)
2095 struct page_cgroup
*pc
= lookup_page_cgroup(page
);
2098 * It's guaranteed that pc->mem_cgroup never changes while
2099 * lock is held because a routine modifies pc->mem_cgroup
2100 * should take move_lock_mem_cgroup().
2102 move_unlock_mem_cgroup(pc
->mem_cgroup
, flags
);
2105 void mem_cgroup_update_page_stat(struct page
*page
,
2106 enum mem_cgroup_page_stat_item idx
, int val
)
2108 struct mem_cgroup
*memcg
;
2109 struct page_cgroup
*pc
= lookup_page_cgroup(page
);
2110 unsigned long uninitialized_var(flags
);
2112 if (mem_cgroup_disabled())
2115 memcg
= pc
->mem_cgroup
;
2116 if (unlikely(!memcg
|| !PageCgroupUsed(pc
)))
2120 case MEMCG_NR_FILE_MAPPED
:
2121 idx
= MEM_CGROUP_STAT_FILE_MAPPED
;
2127 this_cpu_add(memcg
->stat
->count
[idx
], val
);
2131 * size of first charge trial. "32" comes from vmscan.c's magic value.
2132 * TODO: maybe necessary to use big numbers in big irons.
2134 #define CHARGE_BATCH 32U
2135 struct memcg_stock_pcp
{
2136 struct mem_cgroup
*cached
; /* this never be root cgroup */
2137 unsigned int nr_pages
;
2138 struct work_struct work
;
2139 unsigned long flags
;
2140 #define FLUSHING_CACHED_CHARGE 0
2142 static DEFINE_PER_CPU(struct memcg_stock_pcp
, memcg_stock
);
2143 static DEFINE_MUTEX(percpu_charge_mutex
);
2146 * consume_stock: Try to consume stocked charge on this cpu.
2147 * @memcg: memcg to consume from.
2148 * @nr_pages: how many pages to charge.
2150 * The charges will only happen if @memcg matches the current cpu's memcg
2151 * stock, and at least @nr_pages are available in that stock. Failure to
2152 * service an allocation will refill the stock.
2154 * returns true if successful, false otherwise.
2156 static bool consume_stock(struct mem_cgroup
*memcg
, unsigned int nr_pages
)
2158 struct memcg_stock_pcp
*stock
;
2161 if (nr_pages
> CHARGE_BATCH
)
2164 stock
= &get_cpu_var(memcg_stock
);
2165 if (memcg
== stock
->cached
&& stock
->nr_pages
>= nr_pages
)
2166 stock
->nr_pages
-= nr_pages
;
2167 else /* need to call res_counter_charge */
2169 put_cpu_var(memcg_stock
);
2174 * Returns stocks cached in percpu to res_counter and reset cached information.
2176 static void drain_stock(struct memcg_stock_pcp
*stock
)
2178 struct mem_cgroup
*old
= stock
->cached
;
2180 if (stock
->nr_pages
) {
2181 unsigned long bytes
= stock
->nr_pages
* PAGE_SIZE
;
2183 res_counter_uncharge(&old
->res
, bytes
);
2184 if (do_swap_account
)
2185 res_counter_uncharge(&old
->memsw
, bytes
);
2186 stock
->nr_pages
= 0;
2188 stock
->cached
= NULL
;
2192 * This must be called under preempt disabled or must be called by
2193 * a thread which is pinned to local cpu.
2195 static void drain_local_stock(struct work_struct
*dummy
)
2197 struct memcg_stock_pcp
*stock
= &__get_cpu_var(memcg_stock
);
2199 clear_bit(FLUSHING_CACHED_CHARGE
, &stock
->flags
);
2203 * Cache charges(val) which is from res_counter, to local per_cpu area.
2204 * This will be consumed by consume_stock() function, later.
2206 static void refill_stock(struct mem_cgroup
*memcg
, unsigned int nr_pages
)
2208 struct memcg_stock_pcp
*stock
= &get_cpu_var(memcg_stock
);
2210 if (stock
->cached
!= memcg
) { /* reset if necessary */
2212 stock
->cached
= memcg
;
2214 stock
->nr_pages
+= nr_pages
;
2215 put_cpu_var(memcg_stock
);
2219 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2220 * of the hierarchy under it. sync flag says whether we should block
2221 * until the work is done.
2223 static void drain_all_stock(struct mem_cgroup
*root_memcg
, bool sync
)
2227 /* Notify other cpus that system-wide "drain" is running */
2230 for_each_online_cpu(cpu
) {
2231 struct memcg_stock_pcp
*stock
= &per_cpu(memcg_stock
, cpu
);
2232 struct mem_cgroup
*memcg
;
2234 memcg
= stock
->cached
;
2235 if (!memcg
|| !stock
->nr_pages
)
2237 if (!mem_cgroup_same_or_subtree(root_memcg
, memcg
))
2239 if (!test_and_set_bit(FLUSHING_CACHED_CHARGE
, &stock
->flags
)) {
2241 drain_local_stock(&stock
->work
);
2243 schedule_work_on(cpu
, &stock
->work
);
2251 for_each_online_cpu(cpu
) {
2252 struct memcg_stock_pcp
*stock
= &per_cpu(memcg_stock
, cpu
);
2253 if (test_bit(FLUSHING_CACHED_CHARGE
, &stock
->flags
))
2254 flush_work(&stock
->work
);
2261 * Tries to drain stocked charges in other cpus. This function is asynchronous
2262 * and just put a work per cpu for draining localy on each cpu. Caller can
2263 * expects some charges will be back to res_counter later but cannot wait for
2266 static void drain_all_stock_async(struct mem_cgroup
*root_memcg
)
2269 * If someone calls draining, avoid adding more kworker runs.
2271 if (!mutex_trylock(&percpu_charge_mutex
))
2273 drain_all_stock(root_memcg
, false);
2274 mutex_unlock(&percpu_charge_mutex
);
2277 /* This is a synchronous drain interface. */
2278 static void drain_all_stock_sync(struct mem_cgroup
*root_memcg
)
2280 /* called when force_empty is called */
2281 mutex_lock(&percpu_charge_mutex
);
2282 drain_all_stock(root_memcg
, true);
2283 mutex_unlock(&percpu_charge_mutex
);
2287 * This function drains percpu counter value from DEAD cpu and
2288 * move it to local cpu. Note that this function can be preempted.
2290 static void mem_cgroup_drain_pcp_counter(struct mem_cgroup
*memcg
, int cpu
)
2294 spin_lock(&memcg
->pcp_counter_lock
);
2295 for (i
= 0; i
< MEM_CGROUP_STAT_NSTATS
; i
++) {
2296 long x
= per_cpu(memcg
->stat
->count
[i
], cpu
);
2298 per_cpu(memcg
->stat
->count
[i
], cpu
) = 0;
2299 memcg
->nocpu_base
.count
[i
] += x
;
2301 for (i
= 0; i
< MEM_CGROUP_EVENTS_NSTATS
; i
++) {
2302 unsigned long x
= per_cpu(memcg
->stat
->events
[i
], cpu
);
2304 per_cpu(memcg
->stat
->events
[i
], cpu
) = 0;
2305 memcg
->nocpu_base
.events
[i
] += x
;
2307 spin_unlock(&memcg
->pcp_counter_lock
);
2310 static int __cpuinit
memcg_cpu_hotplug_callback(struct notifier_block
*nb
,
2311 unsigned long action
,
2314 int cpu
= (unsigned long)hcpu
;
2315 struct memcg_stock_pcp
*stock
;
2316 struct mem_cgroup
*iter
;
2318 if (action
== CPU_ONLINE
)
2321 if (action
!= CPU_DEAD
&& action
!= CPU_DEAD_FROZEN
)
2324 for_each_mem_cgroup(iter
)
2325 mem_cgroup_drain_pcp_counter(iter
, cpu
);
2327 stock
= &per_cpu(memcg_stock
, cpu
);
2333 /* See __mem_cgroup_try_charge() for details */
2335 CHARGE_OK
, /* success */
2336 CHARGE_RETRY
, /* need to retry but retry is not bad */
2337 CHARGE_NOMEM
, /* we can't do more. return -ENOMEM */
2338 CHARGE_WOULDBLOCK
, /* GFP_WAIT wasn't set and no enough res. */
2339 CHARGE_OOM_DIE
, /* the current is killed because of OOM */
2342 static int mem_cgroup_do_charge(struct mem_cgroup
*memcg
, gfp_t gfp_mask
,
2343 unsigned int nr_pages
, unsigned int min_pages
,
2346 unsigned long csize
= nr_pages
* PAGE_SIZE
;
2347 struct mem_cgroup
*mem_over_limit
;
2348 struct res_counter
*fail_res
;
2349 unsigned long flags
= 0;
2352 ret
= res_counter_charge(&memcg
->res
, csize
, &fail_res
);
2355 if (!do_swap_account
)
2357 ret
= res_counter_charge(&memcg
->memsw
, csize
, &fail_res
);
2361 res_counter_uncharge(&memcg
->res
, csize
);
2362 mem_over_limit
= mem_cgroup_from_res_counter(fail_res
, memsw
);
2363 flags
|= MEM_CGROUP_RECLAIM_NOSWAP
;
2365 mem_over_limit
= mem_cgroup_from_res_counter(fail_res
, res
);
2367 * Never reclaim on behalf of optional batching, retry with a
2368 * single page instead.
2370 if (nr_pages
> min_pages
)
2371 return CHARGE_RETRY
;
2373 if (!(gfp_mask
& __GFP_WAIT
))
2374 return CHARGE_WOULDBLOCK
;
2376 if (gfp_mask
& __GFP_NORETRY
)
2377 return CHARGE_NOMEM
;
2379 ret
= mem_cgroup_reclaim(mem_over_limit
, gfp_mask
, flags
);
2380 if (mem_cgroup_margin(mem_over_limit
) >= nr_pages
)
2381 return CHARGE_RETRY
;
2383 * Even though the limit is exceeded at this point, reclaim
2384 * may have been able to free some pages. Retry the charge
2385 * before killing the task.
2387 * Only for regular pages, though: huge pages are rather
2388 * unlikely to succeed so close to the limit, and we fall back
2389 * to regular pages anyway in case of failure.
2391 if (nr_pages
<= (1 << PAGE_ALLOC_COSTLY_ORDER
) && ret
)
2392 return CHARGE_RETRY
;
2395 * At task move, charge accounts can be doubly counted. So, it's
2396 * better to wait until the end of task_move if something is going on.
2398 if (mem_cgroup_wait_acct_move(mem_over_limit
))
2399 return CHARGE_RETRY
;
2401 /* If we don't need to call oom-killer at el, return immediately */
2403 return CHARGE_NOMEM
;
2405 if (!mem_cgroup_handle_oom(mem_over_limit
, gfp_mask
, get_order(csize
)))
2406 return CHARGE_OOM_DIE
;
2408 return CHARGE_RETRY
;
2412 * __mem_cgroup_try_charge() does
2413 * 1. detect memcg to be charged against from passed *mm and *ptr,
2414 * 2. update res_counter
2415 * 3. call memory reclaim if necessary.
2417 * In some special case, if the task is fatal, fatal_signal_pending() or
2418 * has TIF_MEMDIE, this function returns -EINTR while writing root_mem_cgroup
2419 * to *ptr. There are two reasons for this. 1: fatal threads should quit as soon
2420 * as possible without any hazards. 2: all pages should have a valid
2421 * pc->mem_cgroup. If mm is NULL and the caller doesn't pass a valid memcg
2422 * pointer, that is treated as a charge to root_mem_cgroup.
2424 * So __mem_cgroup_try_charge() will return
2425 * 0 ... on success, filling *ptr with a valid memcg pointer.
2426 * -ENOMEM ... charge failure because of resource limits.
2427 * -EINTR ... if thread is fatal. *ptr is filled with root_mem_cgroup.
2429 * Unlike the exported interface, an "oom" parameter is added. if oom==true,
2430 * the oom-killer can be invoked.
2432 static int __mem_cgroup_try_charge(struct mm_struct
*mm
,
2434 unsigned int nr_pages
,
2435 struct mem_cgroup
**ptr
,
2438 unsigned int batch
= max(CHARGE_BATCH
, nr_pages
);
2439 int nr_oom_retries
= MEM_CGROUP_RECLAIM_RETRIES
;
2440 struct mem_cgroup
*memcg
= NULL
;
2444 * Unlike gloval-vm's OOM-kill, we're not in memory shortage
2445 * in system level. So, allow to go ahead dying process in addition to
2448 if (unlikely(test_thread_flag(TIF_MEMDIE
)
2449 || fatal_signal_pending(current
)))
2453 * We always charge the cgroup the mm_struct belongs to.
2454 * The mm_struct's mem_cgroup changes on task migration if the
2455 * thread group leader migrates. It's possible that mm is not
2456 * set, if so charge the root memcg (happens for pagecache usage).
2459 *ptr
= root_mem_cgroup
;
2461 if (*ptr
) { /* css should be a valid one */
2463 if (mem_cgroup_is_root(memcg
))
2465 if (consume_stock(memcg
, nr_pages
))
2467 css_get(&memcg
->css
);
2469 struct task_struct
*p
;
2472 p
= rcu_dereference(mm
->owner
);
2474 * Because we don't have task_lock(), "p" can exit.
2475 * In that case, "memcg" can point to root or p can be NULL with
2476 * race with swapoff. Then, we have small risk of mis-accouning.
2477 * But such kind of mis-account by race always happens because
2478 * we don't have cgroup_mutex(). It's overkill and we allo that
2480 * (*) swapoff at el will charge against mm-struct not against
2481 * task-struct. So, mm->owner can be NULL.
2483 memcg
= mem_cgroup_from_task(p
);
2485 memcg
= root_mem_cgroup
;
2486 if (mem_cgroup_is_root(memcg
)) {
2490 if (consume_stock(memcg
, nr_pages
)) {
2492 * It seems dagerous to access memcg without css_get().
2493 * But considering how consume_stok works, it's not
2494 * necessary. If consume_stock success, some charges
2495 * from this memcg are cached on this cpu. So, we
2496 * don't need to call css_get()/css_tryget() before
2497 * calling consume_stock().
2502 /* after here, we may be blocked. we need to get refcnt */
2503 if (!css_tryget(&memcg
->css
)) {
2513 /* If killed, bypass charge */
2514 if (fatal_signal_pending(current
)) {
2515 css_put(&memcg
->css
);
2520 if (oom
&& !nr_oom_retries
) {
2522 nr_oom_retries
= MEM_CGROUP_RECLAIM_RETRIES
;
2525 ret
= mem_cgroup_do_charge(memcg
, gfp_mask
, batch
, nr_pages
,
2530 case CHARGE_RETRY
: /* not in OOM situation but retry */
2532 css_put(&memcg
->css
);
2535 case CHARGE_WOULDBLOCK
: /* !__GFP_WAIT */
2536 css_put(&memcg
->css
);
2538 case CHARGE_NOMEM
: /* OOM routine works */
2540 css_put(&memcg
->css
);
2543 /* If oom, we never return -ENOMEM */
2546 case CHARGE_OOM_DIE
: /* Killed by OOM Killer */
2547 css_put(&memcg
->css
);
2550 } while (ret
!= CHARGE_OK
);
2552 if (batch
> nr_pages
)
2553 refill_stock(memcg
, batch
- nr_pages
);
2554 css_put(&memcg
->css
);
2562 *ptr
= root_mem_cgroup
;
2567 * Somemtimes we have to undo a charge we got by try_charge().
2568 * This function is for that and do uncharge, put css's refcnt.
2569 * gotten by try_charge().
2571 static void __mem_cgroup_cancel_charge(struct mem_cgroup
*memcg
,
2572 unsigned int nr_pages
)
2574 if (!mem_cgroup_is_root(memcg
)) {
2575 unsigned long bytes
= nr_pages
* PAGE_SIZE
;
2577 res_counter_uncharge(&memcg
->res
, bytes
);
2578 if (do_swap_account
)
2579 res_counter_uncharge(&memcg
->memsw
, bytes
);
2584 * Cancel chrages in this cgroup....doesn't propagate to parent cgroup.
2585 * This is useful when moving usage to parent cgroup.
2587 static void __mem_cgroup_cancel_local_charge(struct mem_cgroup
*memcg
,
2588 unsigned int nr_pages
)
2590 unsigned long bytes
= nr_pages
* PAGE_SIZE
;
2592 if (mem_cgroup_is_root(memcg
))
2595 res_counter_uncharge_until(&memcg
->res
, memcg
->res
.parent
, bytes
);
2596 if (do_swap_account
)
2597 res_counter_uncharge_until(&memcg
->memsw
,
2598 memcg
->memsw
.parent
, bytes
);
2602 * A helper function to get mem_cgroup from ID. must be called under
2603 * rcu_read_lock(). The caller is responsible for calling css_tryget if
2604 * the mem_cgroup is used for charging. (dropping refcnt from swap can be
2605 * called against removed memcg.)
2607 static struct mem_cgroup
*mem_cgroup_lookup(unsigned short id
)
2609 struct cgroup_subsys_state
*css
;
2611 /* ID 0 is unused ID */
2614 css
= css_lookup(&mem_cgroup_subsys
, id
);
2617 return mem_cgroup_from_css(css
);
2620 struct mem_cgroup
*try_get_mem_cgroup_from_page(struct page
*page
)
2622 struct mem_cgroup
*memcg
= NULL
;
2623 struct page_cgroup
*pc
;
2627 VM_BUG_ON(!PageLocked(page
));
2629 pc
= lookup_page_cgroup(page
);
2630 lock_page_cgroup(pc
);
2631 if (PageCgroupUsed(pc
)) {
2632 memcg
= pc
->mem_cgroup
;
2633 if (memcg
&& !css_tryget(&memcg
->css
))
2635 } else if (PageSwapCache(page
)) {
2636 ent
.val
= page_private(page
);
2637 id
= lookup_swap_cgroup_id(ent
);
2639 memcg
= mem_cgroup_lookup(id
);
2640 if (memcg
&& !css_tryget(&memcg
->css
))
2644 unlock_page_cgroup(pc
);
2648 static void __mem_cgroup_commit_charge(struct mem_cgroup
*memcg
,
2650 unsigned int nr_pages
,
2651 enum charge_type ctype
,
2654 struct page_cgroup
*pc
= lookup_page_cgroup(page
);
2655 struct zone
*uninitialized_var(zone
);
2656 struct lruvec
*lruvec
;
2657 bool was_on_lru
= false;
2660 lock_page_cgroup(pc
);
2661 VM_BUG_ON(PageCgroupUsed(pc
));
2663 * we don't need page_cgroup_lock about tail pages, becase they are not
2664 * accessed by any other context at this point.
2668 * In some cases, SwapCache and FUSE(splice_buf->radixtree), the page
2669 * may already be on some other mem_cgroup's LRU. Take care of it.
2672 zone
= page_zone(page
);
2673 spin_lock_irq(&zone
->lru_lock
);
2674 if (PageLRU(page
)) {
2675 lruvec
= mem_cgroup_zone_lruvec(zone
, pc
->mem_cgroup
);
2677 del_page_from_lru_list(page
, lruvec
, page_lru(page
));
2682 pc
->mem_cgroup
= memcg
;
2684 * We access a page_cgroup asynchronously without lock_page_cgroup().
2685 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
2686 * is accessed after testing USED bit. To make pc->mem_cgroup visible
2687 * before USED bit, we need memory barrier here.
2688 * See mem_cgroup_add_lru_list(), etc.
2691 SetPageCgroupUsed(pc
);
2695 lruvec
= mem_cgroup_zone_lruvec(zone
, pc
->mem_cgroup
);
2696 VM_BUG_ON(PageLRU(page
));
2698 add_page_to_lru_list(page
, lruvec
, page_lru(page
));
2700 spin_unlock_irq(&zone
->lru_lock
);
2703 if (ctype
== MEM_CGROUP_CHARGE_TYPE_ANON
)
2708 mem_cgroup_charge_statistics(memcg
, anon
, nr_pages
);
2709 unlock_page_cgroup(pc
);
2712 * "charge_statistics" updated event counter. Then, check it.
2713 * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
2714 * if they exceeds softlimit.
2716 memcg_check_events(memcg
, page
);
2719 #ifdef CONFIG_MEMCG_KMEM
2720 static inline bool memcg_can_account_kmem(struct mem_cgroup
*memcg
)
2722 return !mem_cgroup_disabled() && !mem_cgroup_is_root(memcg
) &&
2723 (memcg
->kmem_account_flags
& KMEM_ACCOUNTED_MASK
);
2726 static int memcg_charge_kmem(struct mem_cgroup
*memcg
, gfp_t gfp
, u64 size
)
2728 struct res_counter
*fail_res
;
2729 struct mem_cgroup
*_memcg
;
2733 ret
= res_counter_charge(&memcg
->kmem
, size
, &fail_res
);
2738 * Conditions under which we can wait for the oom_killer. Those are
2739 * the same conditions tested by the core page allocator
2741 may_oom
= (gfp
& __GFP_FS
) && !(gfp
& __GFP_NORETRY
);
2744 ret
= __mem_cgroup_try_charge(NULL
, gfp
, size
>> PAGE_SHIFT
,
2747 if (ret
== -EINTR
) {
2749 * __mem_cgroup_try_charge() chosed to bypass to root due to
2750 * OOM kill or fatal signal. Since our only options are to
2751 * either fail the allocation or charge it to this cgroup, do
2752 * it as a temporary condition. But we can't fail. From a
2753 * kmem/slab perspective, the cache has already been selected,
2754 * by mem_cgroup_kmem_get_cache(), so it is too late to change
2757 * This condition will only trigger if the task entered
2758 * memcg_charge_kmem in a sane state, but was OOM-killed during
2759 * __mem_cgroup_try_charge() above. Tasks that were already
2760 * dying when the allocation triggers should have been already
2761 * directed to the root cgroup in memcontrol.h
2763 res_counter_charge_nofail(&memcg
->res
, size
, &fail_res
);
2764 if (do_swap_account
)
2765 res_counter_charge_nofail(&memcg
->memsw
, size
,
2769 res_counter_uncharge(&memcg
->kmem
, size
);
2774 static void memcg_uncharge_kmem(struct mem_cgroup
*memcg
, u64 size
)
2776 res_counter_uncharge(&memcg
->res
, size
);
2777 if (do_swap_account
)
2778 res_counter_uncharge(&memcg
->memsw
, size
);
2781 if (res_counter_uncharge(&memcg
->kmem
, size
))
2784 if (memcg_kmem_test_and_clear_dead(memcg
))
2785 mem_cgroup_put(memcg
);
2789 * We need to verify if the allocation against current->mm->owner's memcg is
2790 * possible for the given order. But the page is not allocated yet, so we'll
2791 * need a further commit step to do the final arrangements.
2793 * It is possible for the task to switch cgroups in this mean time, so at
2794 * commit time, we can't rely on task conversion any longer. We'll then use
2795 * the handle argument to return to the caller which cgroup we should commit
2796 * against. We could also return the memcg directly and avoid the pointer
2797 * passing, but a boolean return value gives better semantics considering
2798 * the compiled-out case as well.
2800 * Returning true means the allocation is possible.
2803 __memcg_kmem_newpage_charge(gfp_t gfp
, struct mem_cgroup
**_memcg
, int order
)
2805 struct mem_cgroup
*memcg
;
2809 memcg
= try_get_mem_cgroup_from_mm(current
->mm
);
2812 * very rare case described in mem_cgroup_from_task. Unfortunately there
2813 * isn't much we can do without complicating this too much, and it would
2814 * be gfp-dependent anyway. Just let it go
2816 if (unlikely(!memcg
))
2819 if (!memcg_can_account_kmem(memcg
)) {
2820 css_put(&memcg
->css
);
2824 ret
= memcg_charge_kmem(memcg
, gfp
, PAGE_SIZE
<< order
);
2828 css_put(&memcg
->css
);
2832 void __memcg_kmem_commit_charge(struct page
*page
, struct mem_cgroup
*memcg
,
2835 struct page_cgroup
*pc
;
2837 VM_BUG_ON(mem_cgroup_is_root(memcg
));
2839 /* The page allocation failed. Revert */
2841 memcg_uncharge_kmem(memcg
, PAGE_SIZE
<< order
);
2845 pc
= lookup_page_cgroup(page
);
2846 lock_page_cgroup(pc
);
2847 pc
->mem_cgroup
= memcg
;
2848 SetPageCgroupUsed(pc
);
2849 unlock_page_cgroup(pc
);
2852 void __memcg_kmem_uncharge_pages(struct page
*page
, int order
)
2854 struct mem_cgroup
*memcg
= NULL
;
2855 struct page_cgroup
*pc
;
2858 pc
= lookup_page_cgroup(page
);
2860 * Fast unlocked return. Theoretically might have changed, have to
2861 * check again after locking.
2863 if (!PageCgroupUsed(pc
))
2866 lock_page_cgroup(pc
);
2867 if (PageCgroupUsed(pc
)) {
2868 memcg
= pc
->mem_cgroup
;
2869 ClearPageCgroupUsed(pc
);
2871 unlock_page_cgroup(pc
);
2874 * We trust that only if there is a memcg associated with the page, it
2875 * is a valid allocation
2880 VM_BUG_ON(mem_cgroup_is_root(memcg
));
2881 memcg_uncharge_kmem(memcg
, PAGE_SIZE
<< order
);
2883 #endif /* CONFIG_MEMCG_KMEM */
2885 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
2887 #define PCGF_NOCOPY_AT_SPLIT (1 << PCG_LOCK | 1 << PCG_MIGRATION)
2889 * Because tail pages are not marked as "used", set it. We're under
2890 * zone->lru_lock, 'splitting on pmd' and compound_lock.
2891 * charge/uncharge will be never happen and move_account() is done under
2892 * compound_lock(), so we don't have to take care of races.
2894 void mem_cgroup_split_huge_fixup(struct page
*head
)
2896 struct page_cgroup
*head_pc
= lookup_page_cgroup(head
);
2897 struct page_cgroup
*pc
;
2900 if (mem_cgroup_disabled())
2902 for (i
= 1; i
< HPAGE_PMD_NR
; i
++) {
2904 pc
->mem_cgroup
= head_pc
->mem_cgroup
;
2905 smp_wmb();/* see __commit_charge() */
2906 pc
->flags
= head_pc
->flags
& ~PCGF_NOCOPY_AT_SPLIT
;
2909 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
2912 * mem_cgroup_move_account - move account of the page
2914 * @nr_pages: number of regular pages (>1 for huge pages)
2915 * @pc: page_cgroup of the page.
2916 * @from: mem_cgroup which the page is moved from.
2917 * @to: mem_cgroup which the page is moved to. @from != @to.
2919 * The caller must confirm following.
2920 * - page is not on LRU (isolate_page() is useful.)
2921 * - compound_lock is held when nr_pages > 1
2923 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
2926 static int mem_cgroup_move_account(struct page
*page
,
2927 unsigned int nr_pages
,
2928 struct page_cgroup
*pc
,
2929 struct mem_cgroup
*from
,
2930 struct mem_cgroup
*to
)
2932 unsigned long flags
;
2934 bool anon
= PageAnon(page
);
2936 VM_BUG_ON(from
== to
);
2937 VM_BUG_ON(PageLRU(page
));
2939 * The page is isolated from LRU. So, collapse function
2940 * will not handle this page. But page splitting can happen.
2941 * Do this check under compound_page_lock(). The caller should
2945 if (nr_pages
> 1 && !PageTransHuge(page
))
2948 lock_page_cgroup(pc
);
2951 if (!PageCgroupUsed(pc
) || pc
->mem_cgroup
!= from
)
2954 move_lock_mem_cgroup(from
, &flags
);
2956 if (!anon
&& page_mapped(page
)) {
2957 /* Update mapped_file data for mem_cgroup */
2959 __this_cpu_dec(from
->stat
->count
[MEM_CGROUP_STAT_FILE_MAPPED
]);
2960 __this_cpu_inc(to
->stat
->count
[MEM_CGROUP_STAT_FILE_MAPPED
]);
2963 mem_cgroup_charge_statistics(from
, anon
, -nr_pages
);
2965 /* caller should have done css_get */
2966 pc
->mem_cgroup
= to
;
2967 mem_cgroup_charge_statistics(to
, anon
, nr_pages
);
2968 move_unlock_mem_cgroup(from
, &flags
);
2971 unlock_page_cgroup(pc
);
2975 memcg_check_events(to
, page
);
2976 memcg_check_events(from
, page
);
2982 * mem_cgroup_move_parent - moves page to the parent group
2983 * @page: the page to move
2984 * @pc: page_cgroup of the page
2985 * @child: page's cgroup
2987 * move charges to its parent or the root cgroup if the group has no
2988 * parent (aka use_hierarchy==0).
2989 * Although this might fail (get_page_unless_zero, isolate_lru_page or
2990 * mem_cgroup_move_account fails) the failure is always temporary and
2991 * it signals a race with a page removal/uncharge or migration. In the
2992 * first case the page is on the way out and it will vanish from the LRU
2993 * on the next attempt and the call should be retried later.
2994 * Isolation from the LRU fails only if page has been isolated from
2995 * the LRU since we looked at it and that usually means either global
2996 * reclaim or migration going on. The page will either get back to the
2998 * Finaly mem_cgroup_move_account fails only if the page got uncharged
2999 * (!PageCgroupUsed) or moved to a different group. The page will
3000 * disappear in the next attempt.
3002 static int mem_cgroup_move_parent(struct page
*page
,
3003 struct page_cgroup
*pc
,
3004 struct mem_cgroup
*child
)
3006 struct mem_cgroup
*parent
;
3007 unsigned int nr_pages
;
3008 unsigned long uninitialized_var(flags
);
3011 VM_BUG_ON(mem_cgroup_is_root(child
));
3014 if (!get_page_unless_zero(page
))
3016 if (isolate_lru_page(page
))
3019 nr_pages
= hpage_nr_pages(page
);
3021 parent
= parent_mem_cgroup(child
);
3023 * If no parent, move charges to root cgroup.
3026 parent
= root_mem_cgroup
;
3029 VM_BUG_ON(!PageTransHuge(page
));
3030 flags
= compound_lock_irqsave(page
);
3033 ret
= mem_cgroup_move_account(page
, nr_pages
,
3036 __mem_cgroup_cancel_local_charge(child
, nr_pages
);
3039 compound_unlock_irqrestore(page
, flags
);
3040 putback_lru_page(page
);
3048 * Charge the memory controller for page usage.
3050 * 0 if the charge was successful
3051 * < 0 if the cgroup is over its limit
3053 static int mem_cgroup_charge_common(struct page
*page
, struct mm_struct
*mm
,
3054 gfp_t gfp_mask
, enum charge_type ctype
)
3056 struct mem_cgroup
*memcg
= NULL
;
3057 unsigned int nr_pages
= 1;
3061 if (PageTransHuge(page
)) {
3062 nr_pages
<<= compound_order(page
);
3063 VM_BUG_ON(!PageTransHuge(page
));
3065 * Never OOM-kill a process for a huge page. The
3066 * fault handler will fall back to regular pages.
3071 ret
= __mem_cgroup_try_charge(mm
, gfp_mask
, nr_pages
, &memcg
, oom
);
3074 __mem_cgroup_commit_charge(memcg
, page
, nr_pages
, ctype
, false);
3078 int mem_cgroup_newpage_charge(struct page
*page
,
3079 struct mm_struct
*mm
, gfp_t gfp_mask
)
3081 if (mem_cgroup_disabled())
3083 VM_BUG_ON(page_mapped(page
));
3084 VM_BUG_ON(page
->mapping
&& !PageAnon(page
));
3086 return mem_cgroup_charge_common(page
, mm
, gfp_mask
,
3087 MEM_CGROUP_CHARGE_TYPE_ANON
);
3091 * While swap-in, try_charge -> commit or cancel, the page is locked.
3092 * And when try_charge() successfully returns, one refcnt to memcg without
3093 * struct page_cgroup is acquired. This refcnt will be consumed by
3094 * "commit()" or removed by "cancel()"
3096 static int __mem_cgroup_try_charge_swapin(struct mm_struct
*mm
,
3099 struct mem_cgroup
**memcgp
)
3101 struct mem_cgroup
*memcg
;
3102 struct page_cgroup
*pc
;
3105 pc
= lookup_page_cgroup(page
);
3107 * Every swap fault against a single page tries to charge the
3108 * page, bail as early as possible. shmem_unuse() encounters
3109 * already charged pages, too. The USED bit is protected by
3110 * the page lock, which serializes swap cache removal, which
3111 * in turn serializes uncharging.
3113 if (PageCgroupUsed(pc
))
3115 if (!do_swap_account
)
3117 memcg
= try_get_mem_cgroup_from_page(page
);
3121 ret
= __mem_cgroup_try_charge(NULL
, mask
, 1, memcgp
, true);
3122 css_put(&memcg
->css
);
3127 ret
= __mem_cgroup_try_charge(mm
, mask
, 1, memcgp
, true);
3133 int mem_cgroup_try_charge_swapin(struct mm_struct
*mm
, struct page
*page
,
3134 gfp_t gfp_mask
, struct mem_cgroup
**memcgp
)
3137 if (mem_cgroup_disabled())
3140 * A racing thread's fault, or swapoff, may have already
3141 * updated the pte, and even removed page from swap cache: in
3142 * those cases unuse_pte()'s pte_same() test will fail; but
3143 * there's also a KSM case which does need to charge the page.
3145 if (!PageSwapCache(page
)) {
3148 ret
= __mem_cgroup_try_charge(mm
, gfp_mask
, 1, memcgp
, true);
3153 return __mem_cgroup_try_charge_swapin(mm
, page
, gfp_mask
, memcgp
);
3156 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup
*memcg
)
3158 if (mem_cgroup_disabled())
3162 __mem_cgroup_cancel_charge(memcg
, 1);
3166 __mem_cgroup_commit_charge_swapin(struct page
*page
, struct mem_cgroup
*memcg
,
3167 enum charge_type ctype
)
3169 if (mem_cgroup_disabled())
3174 __mem_cgroup_commit_charge(memcg
, page
, 1, ctype
, true);
3176 * Now swap is on-memory. This means this page may be
3177 * counted both as mem and swap....double count.
3178 * Fix it by uncharging from memsw. Basically, this SwapCache is stable
3179 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
3180 * may call delete_from_swap_cache() before reach here.
3182 if (do_swap_account
&& PageSwapCache(page
)) {
3183 swp_entry_t ent
= {.val
= page_private(page
)};
3184 mem_cgroup_uncharge_swap(ent
);
3188 void mem_cgroup_commit_charge_swapin(struct page
*page
,
3189 struct mem_cgroup
*memcg
)
3191 __mem_cgroup_commit_charge_swapin(page
, memcg
,
3192 MEM_CGROUP_CHARGE_TYPE_ANON
);
3195 int mem_cgroup_cache_charge(struct page
*page
, struct mm_struct
*mm
,
3198 struct mem_cgroup
*memcg
= NULL
;
3199 enum charge_type type
= MEM_CGROUP_CHARGE_TYPE_CACHE
;
3202 if (mem_cgroup_disabled())
3204 if (PageCompound(page
))
3207 if (!PageSwapCache(page
))
3208 ret
= mem_cgroup_charge_common(page
, mm
, gfp_mask
, type
);
3209 else { /* page is swapcache/shmem */
3210 ret
= __mem_cgroup_try_charge_swapin(mm
, page
,
3213 __mem_cgroup_commit_charge_swapin(page
, memcg
, type
);
3218 static void mem_cgroup_do_uncharge(struct mem_cgroup
*memcg
,
3219 unsigned int nr_pages
,
3220 const enum charge_type ctype
)
3222 struct memcg_batch_info
*batch
= NULL
;
3223 bool uncharge_memsw
= true;
3225 /* If swapout, usage of swap doesn't decrease */
3226 if (!do_swap_account
|| ctype
== MEM_CGROUP_CHARGE_TYPE_SWAPOUT
)
3227 uncharge_memsw
= false;
3229 batch
= ¤t
->memcg_batch
;
3231 * In usual, we do css_get() when we remember memcg pointer.
3232 * But in this case, we keep res->usage until end of a series of
3233 * uncharges. Then, it's ok to ignore memcg's refcnt.
3236 batch
->memcg
= memcg
;
3238 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
3239 * In those cases, all pages freed continuously can be expected to be in
3240 * the same cgroup and we have chance to coalesce uncharges.
3241 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
3242 * because we want to do uncharge as soon as possible.
3245 if (!batch
->do_batch
|| test_thread_flag(TIF_MEMDIE
))
3246 goto direct_uncharge
;
3249 goto direct_uncharge
;
3252 * In typical case, batch->memcg == mem. This means we can
3253 * merge a series of uncharges to an uncharge of res_counter.
3254 * If not, we uncharge res_counter ony by one.
3256 if (batch
->memcg
!= memcg
)
3257 goto direct_uncharge
;
3258 /* remember freed charge and uncharge it later */
3261 batch
->memsw_nr_pages
++;
3264 res_counter_uncharge(&memcg
->res
, nr_pages
* PAGE_SIZE
);
3266 res_counter_uncharge(&memcg
->memsw
, nr_pages
* PAGE_SIZE
);
3267 if (unlikely(batch
->memcg
!= memcg
))
3268 memcg_oom_recover(memcg
);
3272 * uncharge if !page_mapped(page)
3274 static struct mem_cgroup
*
3275 __mem_cgroup_uncharge_common(struct page
*page
, enum charge_type ctype
,
3278 struct mem_cgroup
*memcg
= NULL
;
3279 unsigned int nr_pages
= 1;
3280 struct page_cgroup
*pc
;
3283 if (mem_cgroup_disabled())
3286 VM_BUG_ON(PageSwapCache(page
));
3288 if (PageTransHuge(page
)) {
3289 nr_pages
<<= compound_order(page
);
3290 VM_BUG_ON(!PageTransHuge(page
));
3293 * Check if our page_cgroup is valid
3295 pc
= lookup_page_cgroup(page
);
3296 if (unlikely(!PageCgroupUsed(pc
)))
3299 lock_page_cgroup(pc
);
3301 memcg
= pc
->mem_cgroup
;
3303 if (!PageCgroupUsed(pc
))
3306 anon
= PageAnon(page
);
3309 case MEM_CGROUP_CHARGE_TYPE_ANON
:
3311 * Generally PageAnon tells if it's the anon statistics to be
3312 * updated; but sometimes e.g. mem_cgroup_uncharge_page() is
3313 * used before page reached the stage of being marked PageAnon.
3317 case MEM_CGROUP_CHARGE_TYPE_DROP
:
3318 /* See mem_cgroup_prepare_migration() */
3319 if (page_mapped(page
))
3322 * Pages under migration may not be uncharged. But
3323 * end_migration() /must/ be the one uncharging the
3324 * unused post-migration page and so it has to call
3325 * here with the migration bit still set. See the
3326 * res_counter handling below.
3328 if (!end_migration
&& PageCgroupMigration(pc
))
3331 case MEM_CGROUP_CHARGE_TYPE_SWAPOUT
:
3332 if (!PageAnon(page
)) { /* Shared memory */
3333 if (page
->mapping
&& !page_is_file_cache(page
))
3335 } else if (page_mapped(page
)) /* Anon */
3342 mem_cgroup_charge_statistics(memcg
, anon
, -nr_pages
);
3344 ClearPageCgroupUsed(pc
);
3346 * pc->mem_cgroup is not cleared here. It will be accessed when it's
3347 * freed from LRU. This is safe because uncharged page is expected not
3348 * to be reused (freed soon). Exception is SwapCache, it's handled by
3349 * special functions.
3352 unlock_page_cgroup(pc
);
3354 * even after unlock, we have memcg->res.usage here and this memcg
3355 * will never be freed.
3357 memcg_check_events(memcg
, page
);
3358 if (do_swap_account
&& ctype
== MEM_CGROUP_CHARGE_TYPE_SWAPOUT
) {
3359 mem_cgroup_swap_statistics(memcg
, true);
3360 mem_cgroup_get(memcg
);
3363 * Migration does not charge the res_counter for the
3364 * replacement page, so leave it alone when phasing out the
3365 * page that is unused after the migration.
3367 if (!end_migration
&& !mem_cgroup_is_root(memcg
))
3368 mem_cgroup_do_uncharge(memcg
, nr_pages
, ctype
);
3373 unlock_page_cgroup(pc
);
3377 void mem_cgroup_uncharge_page(struct page
*page
)
3380 if (page_mapped(page
))
3382 VM_BUG_ON(page
->mapping
&& !PageAnon(page
));
3383 if (PageSwapCache(page
))
3385 __mem_cgroup_uncharge_common(page
, MEM_CGROUP_CHARGE_TYPE_ANON
, false);
3388 void mem_cgroup_uncharge_cache_page(struct page
*page
)
3390 VM_BUG_ON(page_mapped(page
));
3391 VM_BUG_ON(page
->mapping
);
3392 __mem_cgroup_uncharge_common(page
, MEM_CGROUP_CHARGE_TYPE_CACHE
, false);
3396 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
3397 * In that cases, pages are freed continuously and we can expect pages
3398 * are in the same memcg. All these calls itself limits the number of
3399 * pages freed at once, then uncharge_start/end() is called properly.
3400 * This may be called prural(2) times in a context,
3403 void mem_cgroup_uncharge_start(void)
3405 current
->memcg_batch
.do_batch
++;
3406 /* We can do nest. */
3407 if (current
->memcg_batch
.do_batch
== 1) {
3408 current
->memcg_batch
.memcg
= NULL
;
3409 current
->memcg_batch
.nr_pages
= 0;
3410 current
->memcg_batch
.memsw_nr_pages
= 0;
3414 void mem_cgroup_uncharge_end(void)
3416 struct memcg_batch_info
*batch
= ¤t
->memcg_batch
;
3418 if (!batch
->do_batch
)
3422 if (batch
->do_batch
) /* If stacked, do nothing. */
3428 * This "batch->memcg" is valid without any css_get/put etc...
3429 * bacause we hide charges behind us.
3431 if (batch
->nr_pages
)
3432 res_counter_uncharge(&batch
->memcg
->res
,
3433 batch
->nr_pages
* PAGE_SIZE
);
3434 if (batch
->memsw_nr_pages
)
3435 res_counter_uncharge(&batch
->memcg
->memsw
,
3436 batch
->memsw_nr_pages
* PAGE_SIZE
);
3437 memcg_oom_recover(batch
->memcg
);
3438 /* forget this pointer (for sanity check) */
3439 batch
->memcg
= NULL
;
3444 * called after __delete_from_swap_cache() and drop "page" account.
3445 * memcg information is recorded to swap_cgroup of "ent"
3448 mem_cgroup_uncharge_swapcache(struct page
*page
, swp_entry_t ent
, bool swapout
)
3450 struct mem_cgroup
*memcg
;
3451 int ctype
= MEM_CGROUP_CHARGE_TYPE_SWAPOUT
;
3453 if (!swapout
) /* this was a swap cache but the swap is unused ! */
3454 ctype
= MEM_CGROUP_CHARGE_TYPE_DROP
;
3456 memcg
= __mem_cgroup_uncharge_common(page
, ctype
, false);
3459 * record memcg information, if swapout && memcg != NULL,
3460 * mem_cgroup_get() was called in uncharge().
3462 if (do_swap_account
&& swapout
&& memcg
)
3463 swap_cgroup_record(ent
, css_id(&memcg
->css
));
3467 #ifdef CONFIG_MEMCG_SWAP
3469 * called from swap_entry_free(). remove record in swap_cgroup and
3470 * uncharge "memsw" account.
3472 void mem_cgroup_uncharge_swap(swp_entry_t ent
)
3474 struct mem_cgroup
*memcg
;
3477 if (!do_swap_account
)
3480 id
= swap_cgroup_record(ent
, 0);
3482 memcg
= mem_cgroup_lookup(id
);
3485 * We uncharge this because swap is freed.
3486 * This memcg can be obsolete one. We avoid calling css_tryget
3488 if (!mem_cgroup_is_root(memcg
))
3489 res_counter_uncharge(&memcg
->memsw
, PAGE_SIZE
);
3490 mem_cgroup_swap_statistics(memcg
, false);
3491 mem_cgroup_put(memcg
);
3497 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3498 * @entry: swap entry to be moved
3499 * @from: mem_cgroup which the entry is moved from
3500 * @to: mem_cgroup which the entry is moved to
3502 * It succeeds only when the swap_cgroup's record for this entry is the same
3503 * as the mem_cgroup's id of @from.
3505 * Returns 0 on success, -EINVAL on failure.
3507 * The caller must have charged to @to, IOW, called res_counter_charge() about
3508 * both res and memsw, and called css_get().
3510 static int mem_cgroup_move_swap_account(swp_entry_t entry
,
3511 struct mem_cgroup
*from
, struct mem_cgroup
*to
)
3513 unsigned short old_id
, new_id
;
3515 old_id
= css_id(&from
->css
);
3516 new_id
= css_id(&to
->css
);
3518 if (swap_cgroup_cmpxchg(entry
, old_id
, new_id
) == old_id
) {
3519 mem_cgroup_swap_statistics(from
, false);
3520 mem_cgroup_swap_statistics(to
, true);
3522 * This function is only called from task migration context now.
3523 * It postpones res_counter and refcount handling till the end
3524 * of task migration(mem_cgroup_clear_mc()) for performance
3525 * improvement. But we cannot postpone mem_cgroup_get(to)
3526 * because if the process that has been moved to @to does
3527 * swap-in, the refcount of @to might be decreased to 0.
3535 static inline int mem_cgroup_move_swap_account(swp_entry_t entry
,
3536 struct mem_cgroup
*from
, struct mem_cgroup
*to
)
3543 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
3546 void mem_cgroup_prepare_migration(struct page
*page
, struct page
*newpage
,
3547 struct mem_cgroup
**memcgp
)
3549 struct mem_cgroup
*memcg
= NULL
;
3550 unsigned int nr_pages
= 1;
3551 struct page_cgroup
*pc
;
3552 enum charge_type ctype
;
3556 if (mem_cgroup_disabled())
3559 if (PageTransHuge(page
))
3560 nr_pages
<<= compound_order(page
);
3562 pc
= lookup_page_cgroup(page
);
3563 lock_page_cgroup(pc
);
3564 if (PageCgroupUsed(pc
)) {
3565 memcg
= pc
->mem_cgroup
;
3566 css_get(&memcg
->css
);
3568 * At migrating an anonymous page, its mapcount goes down
3569 * to 0 and uncharge() will be called. But, even if it's fully
3570 * unmapped, migration may fail and this page has to be
3571 * charged again. We set MIGRATION flag here and delay uncharge
3572 * until end_migration() is called
3574 * Corner Case Thinking
3576 * When the old page was mapped as Anon and it's unmap-and-freed
3577 * while migration was ongoing.
3578 * If unmap finds the old page, uncharge() of it will be delayed
3579 * until end_migration(). If unmap finds a new page, it's
3580 * uncharged when it make mapcount to be 1->0. If unmap code
3581 * finds swap_migration_entry, the new page will not be mapped
3582 * and end_migration() will find it(mapcount==0).
3585 * When the old page was mapped but migraion fails, the kernel
3586 * remaps it. A charge for it is kept by MIGRATION flag even
3587 * if mapcount goes down to 0. We can do remap successfully
3588 * without charging it again.
3591 * The "old" page is under lock_page() until the end of
3592 * migration, so, the old page itself will not be swapped-out.
3593 * If the new page is swapped out before end_migraton, our
3594 * hook to usual swap-out path will catch the event.
3597 SetPageCgroupMigration(pc
);
3599 unlock_page_cgroup(pc
);
3601 * If the page is not charged at this point,
3609 * We charge new page before it's used/mapped. So, even if unlock_page()
3610 * is called before end_migration, we can catch all events on this new
3611 * page. In the case new page is migrated but not remapped, new page's
3612 * mapcount will be finally 0 and we call uncharge in end_migration().
3615 ctype
= MEM_CGROUP_CHARGE_TYPE_ANON
;
3617 ctype
= MEM_CGROUP_CHARGE_TYPE_CACHE
;
3619 * The page is committed to the memcg, but it's not actually
3620 * charged to the res_counter since we plan on replacing the
3621 * old one and only one page is going to be left afterwards.
3623 __mem_cgroup_commit_charge(memcg
, newpage
, nr_pages
, ctype
, false);
3626 /* remove redundant charge if migration failed*/
3627 void mem_cgroup_end_migration(struct mem_cgroup
*memcg
,
3628 struct page
*oldpage
, struct page
*newpage
, bool migration_ok
)
3630 struct page
*used
, *unused
;
3631 struct page_cgroup
*pc
;
3637 if (!migration_ok
) {
3644 anon
= PageAnon(used
);
3645 __mem_cgroup_uncharge_common(unused
,
3646 anon
? MEM_CGROUP_CHARGE_TYPE_ANON
3647 : MEM_CGROUP_CHARGE_TYPE_CACHE
,
3649 css_put(&memcg
->css
);
3651 * We disallowed uncharge of pages under migration because mapcount
3652 * of the page goes down to zero, temporarly.
3653 * Clear the flag and check the page should be charged.
3655 pc
= lookup_page_cgroup(oldpage
);
3656 lock_page_cgroup(pc
);
3657 ClearPageCgroupMigration(pc
);
3658 unlock_page_cgroup(pc
);
3661 * If a page is a file cache, radix-tree replacement is very atomic
3662 * and we can skip this check. When it was an Anon page, its mapcount
3663 * goes down to 0. But because we added MIGRATION flage, it's not
3664 * uncharged yet. There are several case but page->mapcount check
3665 * and USED bit check in mem_cgroup_uncharge_page() will do enough
3666 * check. (see prepare_charge() also)
3669 mem_cgroup_uncharge_page(used
);
3673 * At replace page cache, newpage is not under any memcg but it's on
3674 * LRU. So, this function doesn't touch res_counter but handles LRU
3675 * in correct way. Both pages are locked so we cannot race with uncharge.
3677 void mem_cgroup_replace_page_cache(struct page
*oldpage
,
3678 struct page
*newpage
)
3680 struct mem_cgroup
*memcg
= NULL
;
3681 struct page_cgroup
*pc
;
3682 enum charge_type type
= MEM_CGROUP_CHARGE_TYPE_CACHE
;
3684 if (mem_cgroup_disabled())
3687 pc
= lookup_page_cgroup(oldpage
);
3688 /* fix accounting on old pages */
3689 lock_page_cgroup(pc
);
3690 if (PageCgroupUsed(pc
)) {
3691 memcg
= pc
->mem_cgroup
;
3692 mem_cgroup_charge_statistics(memcg
, false, -1);
3693 ClearPageCgroupUsed(pc
);
3695 unlock_page_cgroup(pc
);
3698 * When called from shmem_replace_page(), in some cases the
3699 * oldpage has already been charged, and in some cases not.
3704 * Even if newpage->mapping was NULL before starting replacement,
3705 * the newpage may be on LRU(or pagevec for LRU) already. We lock
3706 * LRU while we overwrite pc->mem_cgroup.
3708 __mem_cgroup_commit_charge(memcg
, newpage
, 1, type
, true);
3711 #ifdef CONFIG_DEBUG_VM
3712 static struct page_cgroup
*lookup_page_cgroup_used(struct page
*page
)
3714 struct page_cgroup
*pc
;
3716 pc
= lookup_page_cgroup(page
);
3718 * Can be NULL while feeding pages into the page allocator for
3719 * the first time, i.e. during boot or memory hotplug;
3720 * or when mem_cgroup_disabled().
3722 if (likely(pc
) && PageCgroupUsed(pc
))
3727 bool mem_cgroup_bad_page_check(struct page
*page
)
3729 if (mem_cgroup_disabled())
3732 return lookup_page_cgroup_used(page
) != NULL
;
3735 void mem_cgroup_print_bad_page(struct page
*page
)
3737 struct page_cgroup
*pc
;
3739 pc
= lookup_page_cgroup_used(page
);
3741 printk(KERN_ALERT
"pc:%p pc->flags:%lx pc->mem_cgroup:%p\n",
3742 pc
, pc
->flags
, pc
->mem_cgroup
);
3747 static DEFINE_MUTEX(set_limit_mutex
);
3749 static int mem_cgroup_resize_limit(struct mem_cgroup
*memcg
,
3750 unsigned long long val
)
3753 u64 memswlimit
, memlimit
;
3755 int children
= mem_cgroup_count_children(memcg
);
3756 u64 curusage
, oldusage
;
3760 * For keeping hierarchical_reclaim simple, how long we should retry
3761 * is depends on callers. We set our retry-count to be function
3762 * of # of children which we should visit in this loop.
3764 retry_count
= MEM_CGROUP_RECLAIM_RETRIES
* children
;
3766 oldusage
= res_counter_read_u64(&memcg
->res
, RES_USAGE
);
3769 while (retry_count
) {
3770 if (signal_pending(current
)) {
3775 * Rather than hide all in some function, I do this in
3776 * open coded manner. You see what this really does.
3777 * We have to guarantee memcg->res.limit <= memcg->memsw.limit.
3779 mutex_lock(&set_limit_mutex
);
3780 memswlimit
= res_counter_read_u64(&memcg
->memsw
, RES_LIMIT
);
3781 if (memswlimit
< val
) {
3783 mutex_unlock(&set_limit_mutex
);
3787 memlimit
= res_counter_read_u64(&memcg
->res
, RES_LIMIT
);
3791 ret
= res_counter_set_limit(&memcg
->res
, val
);
3793 if (memswlimit
== val
)
3794 memcg
->memsw_is_minimum
= true;
3796 memcg
->memsw_is_minimum
= false;
3798 mutex_unlock(&set_limit_mutex
);
3803 mem_cgroup_reclaim(memcg
, GFP_KERNEL
,
3804 MEM_CGROUP_RECLAIM_SHRINK
);
3805 curusage
= res_counter_read_u64(&memcg
->res
, RES_USAGE
);
3806 /* Usage is reduced ? */
3807 if (curusage
>= oldusage
)
3810 oldusage
= curusage
;
3812 if (!ret
&& enlarge
)
3813 memcg_oom_recover(memcg
);
3818 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup
*memcg
,
3819 unsigned long long val
)
3822 u64 memlimit
, memswlimit
, oldusage
, curusage
;
3823 int children
= mem_cgroup_count_children(memcg
);
3827 /* see mem_cgroup_resize_res_limit */
3828 retry_count
= children
* MEM_CGROUP_RECLAIM_RETRIES
;
3829 oldusage
= res_counter_read_u64(&memcg
->memsw
, RES_USAGE
);
3830 while (retry_count
) {
3831 if (signal_pending(current
)) {
3836 * Rather than hide all in some function, I do this in
3837 * open coded manner. You see what this really does.
3838 * We have to guarantee memcg->res.limit <= memcg->memsw.limit.
3840 mutex_lock(&set_limit_mutex
);
3841 memlimit
= res_counter_read_u64(&memcg
->res
, RES_LIMIT
);
3842 if (memlimit
> val
) {
3844 mutex_unlock(&set_limit_mutex
);
3847 memswlimit
= res_counter_read_u64(&memcg
->memsw
, RES_LIMIT
);
3848 if (memswlimit
< val
)
3850 ret
= res_counter_set_limit(&memcg
->memsw
, val
);
3852 if (memlimit
== val
)
3853 memcg
->memsw_is_minimum
= true;
3855 memcg
->memsw_is_minimum
= false;
3857 mutex_unlock(&set_limit_mutex
);
3862 mem_cgroup_reclaim(memcg
, GFP_KERNEL
,
3863 MEM_CGROUP_RECLAIM_NOSWAP
|
3864 MEM_CGROUP_RECLAIM_SHRINK
);
3865 curusage
= res_counter_read_u64(&memcg
->memsw
, RES_USAGE
);
3866 /* Usage is reduced ? */
3867 if (curusage
>= oldusage
)
3870 oldusage
= curusage
;
3872 if (!ret
&& enlarge
)
3873 memcg_oom_recover(memcg
);
3877 unsigned long mem_cgroup_soft_limit_reclaim(struct zone
*zone
, int order
,
3879 unsigned long *total_scanned
)
3881 unsigned long nr_reclaimed
= 0;
3882 struct mem_cgroup_per_zone
*mz
, *next_mz
= NULL
;
3883 unsigned long reclaimed
;
3885 struct mem_cgroup_tree_per_zone
*mctz
;
3886 unsigned long long excess
;
3887 unsigned long nr_scanned
;
3892 mctz
= soft_limit_tree_node_zone(zone_to_nid(zone
), zone_idx(zone
));
3894 * This loop can run a while, specially if mem_cgroup's continuously
3895 * keep exceeding their soft limit and putting the system under
3902 mz
= mem_cgroup_largest_soft_limit_node(mctz
);
3907 reclaimed
= mem_cgroup_soft_reclaim(mz
->memcg
, zone
,
3908 gfp_mask
, &nr_scanned
);
3909 nr_reclaimed
+= reclaimed
;
3910 *total_scanned
+= nr_scanned
;
3911 spin_lock(&mctz
->lock
);
3914 * If we failed to reclaim anything from this memory cgroup
3915 * it is time to move on to the next cgroup
3921 * Loop until we find yet another one.
3923 * By the time we get the soft_limit lock
3924 * again, someone might have aded the
3925 * group back on the RB tree. Iterate to
3926 * make sure we get a different mem.
3927 * mem_cgroup_largest_soft_limit_node returns
3928 * NULL if no other cgroup is present on
3932 __mem_cgroup_largest_soft_limit_node(mctz
);
3934 css_put(&next_mz
->memcg
->css
);
3935 else /* next_mz == NULL or other memcg */
3939 __mem_cgroup_remove_exceeded(mz
->memcg
, mz
, mctz
);
3940 excess
= res_counter_soft_limit_excess(&mz
->memcg
->res
);
3942 * One school of thought says that we should not add
3943 * back the node to the tree if reclaim returns 0.
3944 * But our reclaim could return 0, simply because due
3945 * to priority we are exposing a smaller subset of
3946 * memory to reclaim from. Consider this as a longer
3949 /* If excess == 0, no tree ops */
3950 __mem_cgroup_insert_exceeded(mz
->memcg
, mz
, mctz
, excess
);
3951 spin_unlock(&mctz
->lock
);
3952 css_put(&mz
->memcg
->css
);
3955 * Could not reclaim anything and there are no more
3956 * mem cgroups to try or we seem to be looping without
3957 * reclaiming anything.
3959 if (!nr_reclaimed
&&
3961 loop
> MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS
))
3963 } while (!nr_reclaimed
);
3965 css_put(&next_mz
->memcg
->css
);
3966 return nr_reclaimed
;
3970 * mem_cgroup_force_empty_list - clears LRU of a group
3971 * @memcg: group to clear
3974 * @lru: lru to to clear
3976 * Traverse a specified page_cgroup list and try to drop them all. This doesn't
3977 * reclaim the pages page themselves - pages are moved to the parent (or root)
3980 static void mem_cgroup_force_empty_list(struct mem_cgroup
*memcg
,
3981 int node
, int zid
, enum lru_list lru
)
3983 struct lruvec
*lruvec
;
3984 unsigned long flags
;
3985 struct list_head
*list
;
3989 zone
= &NODE_DATA(node
)->node_zones
[zid
];
3990 lruvec
= mem_cgroup_zone_lruvec(zone
, memcg
);
3991 list
= &lruvec
->lists
[lru
];
3995 struct page_cgroup
*pc
;
3998 spin_lock_irqsave(&zone
->lru_lock
, flags
);
3999 if (list_empty(list
)) {
4000 spin_unlock_irqrestore(&zone
->lru_lock
, flags
);
4003 page
= list_entry(list
->prev
, struct page
, lru
);
4005 list_move(&page
->lru
, list
);
4007 spin_unlock_irqrestore(&zone
->lru_lock
, flags
);
4010 spin_unlock_irqrestore(&zone
->lru_lock
, flags
);
4012 pc
= lookup_page_cgroup(page
);
4014 if (mem_cgroup_move_parent(page
, pc
, memcg
)) {
4015 /* found lock contention or "pc" is obsolete. */
4020 } while (!list_empty(list
));
4024 * make mem_cgroup's charge to be 0 if there is no task by moving
4025 * all the charges and pages to the parent.
4026 * This enables deleting this mem_cgroup.
4028 * Caller is responsible for holding css reference on the memcg.
4030 static void mem_cgroup_reparent_charges(struct mem_cgroup
*memcg
)
4036 /* This is for making all *used* pages to be on LRU. */
4037 lru_add_drain_all();
4038 drain_all_stock_sync(memcg
);
4039 mem_cgroup_start_move(memcg
);
4040 for_each_node_state(node
, N_MEMORY
) {
4041 for (zid
= 0; zid
< MAX_NR_ZONES
; zid
++) {
4044 mem_cgroup_force_empty_list(memcg
,
4049 mem_cgroup_end_move(memcg
);
4050 memcg_oom_recover(memcg
);
4054 * Kernel memory may not necessarily be trackable to a specific
4055 * process. So they are not migrated, and therefore we can't
4056 * expect their value to drop to 0 here.
4057 * Having res filled up with kmem only is enough.
4059 * This is a safety check because mem_cgroup_force_empty_list
4060 * could have raced with mem_cgroup_replace_page_cache callers
4061 * so the lru seemed empty but the page could have been added
4062 * right after the check. RES_USAGE should be safe as we always
4063 * charge before adding to the LRU.
4065 usage
= res_counter_read_u64(&memcg
->res
, RES_USAGE
) -
4066 res_counter_read_u64(&memcg
->kmem
, RES_USAGE
);
4067 } while (usage
> 0);
4071 * Reclaims as many pages from the given memcg as possible and moves
4072 * the rest to the parent.
4074 * Caller is responsible for holding css reference for memcg.
4076 static int mem_cgroup_force_empty(struct mem_cgroup
*memcg
)
4078 int nr_retries
= MEM_CGROUP_RECLAIM_RETRIES
;
4079 struct cgroup
*cgrp
= memcg
->css
.cgroup
;
4081 /* returns EBUSY if there is a task or if we come here twice. */
4082 if (cgroup_task_count(cgrp
) || !list_empty(&cgrp
->children
))
4085 /* we call try-to-free pages for make this cgroup empty */
4086 lru_add_drain_all();
4087 /* try to free all pages in this cgroup */
4088 while (nr_retries
&& res_counter_read_u64(&memcg
->res
, RES_USAGE
) > 0) {
4091 if (signal_pending(current
))
4094 progress
= try_to_free_mem_cgroup_pages(memcg
, GFP_KERNEL
,
4098 /* maybe some writeback is necessary */
4099 congestion_wait(BLK_RW_ASYNC
, HZ
/10);
4104 mem_cgroup_reparent_charges(memcg
);
4109 static int mem_cgroup_force_empty_write(struct cgroup
*cont
, unsigned int event
)
4111 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cont
);
4114 if (mem_cgroup_is_root(memcg
))
4116 css_get(&memcg
->css
);
4117 ret
= mem_cgroup_force_empty(memcg
);
4118 css_put(&memcg
->css
);
4124 static u64
mem_cgroup_hierarchy_read(struct cgroup
*cont
, struct cftype
*cft
)
4126 return mem_cgroup_from_cont(cont
)->use_hierarchy
;
4129 static int mem_cgroup_hierarchy_write(struct cgroup
*cont
, struct cftype
*cft
,
4133 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cont
);
4134 struct cgroup
*parent
= cont
->parent
;
4135 struct mem_cgroup
*parent_memcg
= NULL
;
4138 parent_memcg
= mem_cgroup_from_cont(parent
);
4142 if (memcg
->use_hierarchy
== val
)
4146 * If parent's use_hierarchy is set, we can't make any modifications
4147 * in the child subtrees. If it is unset, then the change can
4148 * occur, provided the current cgroup has no children.
4150 * For the root cgroup, parent_mem is NULL, we allow value to be
4151 * set if there are no children.
4153 if ((!parent_memcg
|| !parent_memcg
->use_hierarchy
) &&
4154 (val
== 1 || val
== 0)) {
4155 if (list_empty(&cont
->children
))
4156 memcg
->use_hierarchy
= val
;
4169 static unsigned long mem_cgroup_recursive_stat(struct mem_cgroup
*memcg
,
4170 enum mem_cgroup_stat_index idx
)
4172 struct mem_cgroup
*iter
;
4175 /* Per-cpu values can be negative, use a signed accumulator */
4176 for_each_mem_cgroup_tree(iter
, memcg
)
4177 val
+= mem_cgroup_read_stat(iter
, idx
);
4179 if (val
< 0) /* race ? */
4184 static inline u64
mem_cgroup_usage(struct mem_cgroup
*memcg
, bool swap
)
4188 if (!mem_cgroup_is_root(memcg
)) {
4190 return res_counter_read_u64(&memcg
->res
, RES_USAGE
);
4192 return res_counter_read_u64(&memcg
->memsw
, RES_USAGE
);
4195 val
= mem_cgroup_recursive_stat(memcg
, MEM_CGROUP_STAT_CACHE
);
4196 val
+= mem_cgroup_recursive_stat(memcg
, MEM_CGROUP_STAT_RSS
);
4199 val
+= mem_cgroup_recursive_stat(memcg
, MEM_CGROUP_STAT_SWAP
);
4201 return val
<< PAGE_SHIFT
;
4204 static ssize_t
mem_cgroup_read(struct cgroup
*cont
, struct cftype
*cft
,
4205 struct file
*file
, char __user
*buf
,
4206 size_t nbytes
, loff_t
*ppos
)
4208 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cont
);
4214 type
= MEMFILE_TYPE(cft
->private);
4215 name
= MEMFILE_ATTR(cft
->private);
4217 if (!do_swap_account
&& type
== _MEMSWAP
)
4222 if (name
== RES_USAGE
)
4223 val
= mem_cgroup_usage(memcg
, false);
4225 val
= res_counter_read_u64(&memcg
->res
, name
);
4228 if (name
== RES_USAGE
)
4229 val
= mem_cgroup_usage(memcg
, true);
4231 val
= res_counter_read_u64(&memcg
->memsw
, name
);
4234 val
= res_counter_read_u64(&memcg
->kmem
, name
);
4240 len
= scnprintf(str
, sizeof(str
), "%llu\n", (unsigned long long)val
);
4241 return simple_read_from_buffer(buf
, nbytes
, ppos
, str
, len
);
4244 static int memcg_update_kmem_limit(struct cgroup
*cont
, u64 val
)
4247 #ifdef CONFIG_MEMCG_KMEM
4248 bool must_inc_static_branch
= false;
4250 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cont
);
4252 * For simplicity, we won't allow this to be disabled. It also can't
4253 * be changed if the cgroup has children already, or if tasks had
4256 * If tasks join before we set the limit, a person looking at
4257 * kmem.usage_in_bytes will have no way to determine when it took
4258 * place, which makes the value quite meaningless.
4260 * After it first became limited, changes in the value of the limit are
4261 * of course permitted.
4263 * Taking the cgroup_lock is really offensive, but it is so far the only
4264 * way to guarantee that no children will appear. There are plenty of
4265 * other offenders, and they should all go away. Fine grained locking
4266 * is probably the way to go here. When we are fully hierarchical, we
4267 * can also get rid of the use_hierarchy check.
4270 mutex_lock(&set_limit_mutex
);
4271 if (!memcg
->kmem_account_flags
&& val
!= RESOURCE_MAX
) {
4272 if (cgroup_task_count(cont
) || (memcg
->use_hierarchy
&&
4273 !list_empty(&cont
->children
))) {
4277 ret
= res_counter_set_limit(&memcg
->kmem
, val
);
4281 * After this point, kmem_accounted (that we test atomically in
4282 * the beginning of this conditional), is no longer 0. This
4283 * guarantees only one process will set the following boolean
4284 * to true. We don't need test_and_set because we're protected
4285 * by the set_limit_mutex anyway.
4287 memcg_kmem_set_activated(memcg
);
4288 must_inc_static_branch
= true;
4290 * kmem charges can outlive the cgroup. In the case of slab
4291 * pages, for instance, a page contain objects from various
4292 * processes, so it is unfeasible to migrate them away. We
4293 * need to reference count the memcg because of that.
4295 mem_cgroup_get(memcg
);
4297 ret
= res_counter_set_limit(&memcg
->kmem
, val
);
4299 mutex_unlock(&set_limit_mutex
);
4303 * We are by now familiar with the fact that we can't inc the static
4304 * branch inside cgroup_lock. See disarm functions for details. A
4305 * worker here is overkill, but also wrong: After the limit is set, we
4306 * must start accounting right away. Since this operation can't fail,
4307 * we can safely defer it to here - no rollback will be needed.
4309 * The boolean used to control this is also safe, because
4310 * KMEM_ACCOUNTED_ACTIVATED guarantees that only one process will be
4311 * able to set it to true;
4313 if (must_inc_static_branch
) {
4314 static_key_slow_inc(&memcg_kmem_enabled_key
);
4316 * setting the active bit after the inc will guarantee no one
4317 * starts accounting before all call sites are patched
4319 memcg_kmem_set_active(memcg
);
4326 static void memcg_propagate_kmem(struct mem_cgroup
*memcg
)
4328 struct mem_cgroup
*parent
= parent_mem_cgroup(memcg
);
4331 memcg
->kmem_account_flags
= parent
->kmem_account_flags
;
4332 #ifdef CONFIG_MEMCG_KMEM
4334 * When that happen, we need to disable the static branch only on those
4335 * memcgs that enabled it. To achieve this, we would be forced to
4336 * complicate the code by keeping track of which memcgs were the ones
4337 * that actually enabled limits, and which ones got it from its
4340 * It is a lot simpler just to do static_key_slow_inc() on every child
4341 * that is accounted.
4343 if (memcg_kmem_is_active(memcg
)) {
4344 mem_cgroup_get(memcg
);
4345 static_key_slow_inc(&memcg_kmem_enabled_key
);
4351 * The user of this function is...
4354 static int mem_cgroup_write(struct cgroup
*cont
, struct cftype
*cft
,
4357 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cont
);
4360 unsigned long long val
;
4363 type
= MEMFILE_TYPE(cft
->private);
4364 name
= MEMFILE_ATTR(cft
->private);
4366 if (!do_swap_account
&& type
== _MEMSWAP
)
4371 if (mem_cgroup_is_root(memcg
)) { /* Can't set limit on root */
4375 /* This function does all necessary parse...reuse it */
4376 ret
= res_counter_memparse_write_strategy(buffer
, &val
);
4380 ret
= mem_cgroup_resize_limit(memcg
, val
);
4381 else if (type
== _MEMSWAP
)
4382 ret
= mem_cgroup_resize_memsw_limit(memcg
, val
);
4383 else if (type
== _KMEM
)
4384 ret
= memcg_update_kmem_limit(cont
, val
);
4388 case RES_SOFT_LIMIT
:
4389 ret
= res_counter_memparse_write_strategy(buffer
, &val
);
4393 * For memsw, soft limits are hard to implement in terms
4394 * of semantics, for now, we support soft limits for
4395 * control without swap
4398 ret
= res_counter_set_soft_limit(&memcg
->res
, val
);
4403 ret
= -EINVAL
; /* should be BUG() ? */
4409 static void memcg_get_hierarchical_limit(struct mem_cgroup
*memcg
,
4410 unsigned long long *mem_limit
, unsigned long long *memsw_limit
)
4412 struct cgroup
*cgroup
;
4413 unsigned long long min_limit
, min_memsw_limit
, tmp
;
4415 min_limit
= res_counter_read_u64(&memcg
->res
, RES_LIMIT
);
4416 min_memsw_limit
= res_counter_read_u64(&memcg
->memsw
, RES_LIMIT
);
4417 cgroup
= memcg
->css
.cgroup
;
4418 if (!memcg
->use_hierarchy
)
4421 while (cgroup
->parent
) {
4422 cgroup
= cgroup
->parent
;
4423 memcg
= mem_cgroup_from_cont(cgroup
);
4424 if (!memcg
->use_hierarchy
)
4426 tmp
= res_counter_read_u64(&memcg
->res
, RES_LIMIT
);
4427 min_limit
= min(min_limit
, tmp
);
4428 tmp
= res_counter_read_u64(&memcg
->memsw
, RES_LIMIT
);
4429 min_memsw_limit
= min(min_memsw_limit
, tmp
);
4432 *mem_limit
= min_limit
;
4433 *memsw_limit
= min_memsw_limit
;
4436 static int mem_cgroup_reset(struct cgroup
*cont
, unsigned int event
)
4438 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cont
);
4442 type
= MEMFILE_TYPE(event
);
4443 name
= MEMFILE_ATTR(event
);
4445 if (!do_swap_account
&& type
== _MEMSWAP
)
4451 res_counter_reset_max(&memcg
->res
);
4452 else if (type
== _MEMSWAP
)
4453 res_counter_reset_max(&memcg
->memsw
);
4454 else if (type
== _KMEM
)
4455 res_counter_reset_max(&memcg
->kmem
);
4461 res_counter_reset_failcnt(&memcg
->res
);
4462 else if (type
== _MEMSWAP
)
4463 res_counter_reset_failcnt(&memcg
->memsw
);
4464 else if (type
== _KMEM
)
4465 res_counter_reset_failcnt(&memcg
->kmem
);
4474 static u64
mem_cgroup_move_charge_read(struct cgroup
*cgrp
,
4477 return mem_cgroup_from_cont(cgrp
)->move_charge_at_immigrate
;
4481 static int mem_cgroup_move_charge_write(struct cgroup
*cgrp
,
4482 struct cftype
*cft
, u64 val
)
4484 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cgrp
);
4486 if (val
>= (1 << NR_MOVE_TYPE
))
4489 * We check this value several times in both in can_attach() and
4490 * attach(), so we need cgroup lock to prevent this value from being
4494 memcg
->move_charge_at_immigrate
= val
;
4500 static int mem_cgroup_move_charge_write(struct cgroup
*cgrp
,
4501 struct cftype
*cft
, u64 val
)
4508 static int memcg_numa_stat_show(struct cgroup
*cont
, struct cftype
*cft
,
4512 unsigned long total_nr
, file_nr
, anon_nr
, unevictable_nr
;
4513 unsigned long node_nr
;
4514 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cont
);
4516 total_nr
= mem_cgroup_nr_lru_pages(memcg
, LRU_ALL
);
4517 seq_printf(m
, "total=%lu", total_nr
);
4518 for_each_node_state(nid
, N_MEMORY
) {
4519 node_nr
= mem_cgroup_node_nr_lru_pages(memcg
, nid
, LRU_ALL
);
4520 seq_printf(m
, " N%d=%lu", nid
, node_nr
);
4524 file_nr
= mem_cgroup_nr_lru_pages(memcg
, LRU_ALL_FILE
);
4525 seq_printf(m
, "file=%lu", file_nr
);
4526 for_each_node_state(nid
, N_MEMORY
) {
4527 node_nr
= mem_cgroup_node_nr_lru_pages(memcg
, nid
,
4529 seq_printf(m
, " N%d=%lu", nid
, node_nr
);
4533 anon_nr
= mem_cgroup_nr_lru_pages(memcg
, LRU_ALL_ANON
);
4534 seq_printf(m
, "anon=%lu", anon_nr
);
4535 for_each_node_state(nid
, N_MEMORY
) {
4536 node_nr
= mem_cgroup_node_nr_lru_pages(memcg
, nid
,
4538 seq_printf(m
, " N%d=%lu", nid
, node_nr
);
4542 unevictable_nr
= mem_cgroup_nr_lru_pages(memcg
, BIT(LRU_UNEVICTABLE
));
4543 seq_printf(m
, "unevictable=%lu", unevictable_nr
);
4544 for_each_node_state(nid
, N_MEMORY
) {
4545 node_nr
= mem_cgroup_node_nr_lru_pages(memcg
, nid
,
4546 BIT(LRU_UNEVICTABLE
));
4547 seq_printf(m
, " N%d=%lu", nid
, node_nr
);
4552 #endif /* CONFIG_NUMA */
4554 static const char * const mem_cgroup_lru_names
[] = {
4562 static inline void mem_cgroup_lru_names_not_uptodate(void)
4564 BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_lru_names
) != NR_LRU_LISTS
);
4567 static int memcg_stat_show(struct cgroup
*cont
, struct cftype
*cft
,
4570 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cont
);
4571 struct mem_cgroup
*mi
;
4574 for (i
= 0; i
< MEM_CGROUP_STAT_NSTATS
; i
++) {
4575 if (i
== MEM_CGROUP_STAT_SWAP
&& !do_swap_account
)
4577 seq_printf(m
, "%s %ld\n", mem_cgroup_stat_names
[i
],
4578 mem_cgroup_read_stat(memcg
, i
) * PAGE_SIZE
);
4581 for (i
= 0; i
< MEM_CGROUP_EVENTS_NSTATS
; i
++)
4582 seq_printf(m
, "%s %lu\n", mem_cgroup_events_names
[i
],
4583 mem_cgroup_read_events(memcg
, i
));
4585 for (i
= 0; i
< NR_LRU_LISTS
; i
++)
4586 seq_printf(m
, "%s %lu\n", mem_cgroup_lru_names
[i
],
4587 mem_cgroup_nr_lru_pages(memcg
, BIT(i
)) * PAGE_SIZE
);
4589 /* Hierarchical information */
4591 unsigned long long limit
, memsw_limit
;
4592 memcg_get_hierarchical_limit(memcg
, &limit
, &memsw_limit
);
4593 seq_printf(m
, "hierarchical_memory_limit %llu\n", limit
);
4594 if (do_swap_account
)
4595 seq_printf(m
, "hierarchical_memsw_limit %llu\n",
4599 for (i
= 0; i
< MEM_CGROUP_STAT_NSTATS
; i
++) {
4602 if (i
== MEM_CGROUP_STAT_SWAP
&& !do_swap_account
)
4604 for_each_mem_cgroup_tree(mi
, memcg
)
4605 val
+= mem_cgroup_read_stat(mi
, i
) * PAGE_SIZE
;
4606 seq_printf(m
, "total_%s %lld\n", mem_cgroup_stat_names
[i
], val
);
4609 for (i
= 0; i
< MEM_CGROUP_EVENTS_NSTATS
; i
++) {
4610 unsigned long long val
= 0;
4612 for_each_mem_cgroup_tree(mi
, memcg
)
4613 val
+= mem_cgroup_read_events(mi
, i
);
4614 seq_printf(m
, "total_%s %llu\n",
4615 mem_cgroup_events_names
[i
], val
);
4618 for (i
= 0; i
< NR_LRU_LISTS
; i
++) {
4619 unsigned long long val
= 0;
4621 for_each_mem_cgroup_tree(mi
, memcg
)
4622 val
+= mem_cgroup_nr_lru_pages(mi
, BIT(i
)) * PAGE_SIZE
;
4623 seq_printf(m
, "total_%s %llu\n", mem_cgroup_lru_names
[i
], val
);
4626 #ifdef CONFIG_DEBUG_VM
4629 struct mem_cgroup_per_zone
*mz
;
4630 struct zone_reclaim_stat
*rstat
;
4631 unsigned long recent_rotated
[2] = {0, 0};
4632 unsigned long recent_scanned
[2] = {0, 0};
4634 for_each_online_node(nid
)
4635 for (zid
= 0; zid
< MAX_NR_ZONES
; zid
++) {
4636 mz
= mem_cgroup_zoneinfo(memcg
, nid
, zid
);
4637 rstat
= &mz
->lruvec
.reclaim_stat
;
4639 recent_rotated
[0] += rstat
->recent_rotated
[0];
4640 recent_rotated
[1] += rstat
->recent_rotated
[1];
4641 recent_scanned
[0] += rstat
->recent_scanned
[0];
4642 recent_scanned
[1] += rstat
->recent_scanned
[1];
4644 seq_printf(m
, "recent_rotated_anon %lu\n", recent_rotated
[0]);
4645 seq_printf(m
, "recent_rotated_file %lu\n", recent_rotated
[1]);
4646 seq_printf(m
, "recent_scanned_anon %lu\n", recent_scanned
[0]);
4647 seq_printf(m
, "recent_scanned_file %lu\n", recent_scanned
[1]);
4654 static u64
mem_cgroup_swappiness_read(struct cgroup
*cgrp
, struct cftype
*cft
)
4656 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cgrp
);
4658 return mem_cgroup_swappiness(memcg
);
4661 static int mem_cgroup_swappiness_write(struct cgroup
*cgrp
, struct cftype
*cft
,
4664 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cgrp
);
4665 struct mem_cgroup
*parent
;
4670 if (cgrp
->parent
== NULL
)
4673 parent
= mem_cgroup_from_cont(cgrp
->parent
);
4677 /* If under hierarchy, only empty-root can set this value */
4678 if ((parent
->use_hierarchy
) ||
4679 (memcg
->use_hierarchy
&& !list_empty(&cgrp
->children
))) {
4684 memcg
->swappiness
= val
;
4691 static void __mem_cgroup_threshold(struct mem_cgroup
*memcg
, bool swap
)
4693 struct mem_cgroup_threshold_ary
*t
;
4699 t
= rcu_dereference(memcg
->thresholds
.primary
);
4701 t
= rcu_dereference(memcg
->memsw_thresholds
.primary
);
4706 usage
= mem_cgroup_usage(memcg
, swap
);
4709 * current_threshold points to threshold just below or equal to usage.
4710 * If it's not true, a threshold was crossed after last
4711 * call of __mem_cgroup_threshold().
4713 i
= t
->current_threshold
;
4716 * Iterate backward over array of thresholds starting from
4717 * current_threshold and check if a threshold is crossed.
4718 * If none of thresholds below usage is crossed, we read
4719 * only one element of the array here.
4721 for (; i
>= 0 && unlikely(t
->entries
[i
].threshold
> usage
); i
--)
4722 eventfd_signal(t
->entries
[i
].eventfd
, 1);
4724 /* i = current_threshold + 1 */
4728 * Iterate forward over array of thresholds starting from
4729 * current_threshold+1 and check if a threshold is crossed.
4730 * If none of thresholds above usage is crossed, we read
4731 * only one element of the array here.
4733 for (; i
< t
->size
&& unlikely(t
->entries
[i
].threshold
<= usage
); i
++)
4734 eventfd_signal(t
->entries
[i
].eventfd
, 1);
4736 /* Update current_threshold */
4737 t
->current_threshold
= i
- 1;
4742 static void mem_cgroup_threshold(struct mem_cgroup
*memcg
)
4745 __mem_cgroup_threshold(memcg
, false);
4746 if (do_swap_account
)
4747 __mem_cgroup_threshold(memcg
, true);
4749 memcg
= parent_mem_cgroup(memcg
);
4753 static int compare_thresholds(const void *a
, const void *b
)
4755 const struct mem_cgroup_threshold
*_a
= a
;
4756 const struct mem_cgroup_threshold
*_b
= b
;
4758 return _a
->threshold
- _b
->threshold
;
4761 static int mem_cgroup_oom_notify_cb(struct mem_cgroup
*memcg
)
4763 struct mem_cgroup_eventfd_list
*ev
;
4765 list_for_each_entry(ev
, &memcg
->oom_notify
, list
)
4766 eventfd_signal(ev
->eventfd
, 1);
4770 static void mem_cgroup_oom_notify(struct mem_cgroup
*memcg
)
4772 struct mem_cgroup
*iter
;
4774 for_each_mem_cgroup_tree(iter
, memcg
)
4775 mem_cgroup_oom_notify_cb(iter
);
4778 static int mem_cgroup_usage_register_event(struct cgroup
*cgrp
,
4779 struct cftype
*cft
, struct eventfd_ctx
*eventfd
, const char *args
)
4781 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cgrp
);
4782 struct mem_cgroup_thresholds
*thresholds
;
4783 struct mem_cgroup_threshold_ary
*new;
4784 enum res_type type
= MEMFILE_TYPE(cft
->private);
4785 u64 threshold
, usage
;
4788 ret
= res_counter_memparse_write_strategy(args
, &threshold
);
4792 mutex_lock(&memcg
->thresholds_lock
);
4795 thresholds
= &memcg
->thresholds
;
4796 else if (type
== _MEMSWAP
)
4797 thresholds
= &memcg
->memsw_thresholds
;
4801 usage
= mem_cgroup_usage(memcg
, type
== _MEMSWAP
);
4803 /* Check if a threshold crossed before adding a new one */
4804 if (thresholds
->primary
)
4805 __mem_cgroup_threshold(memcg
, type
== _MEMSWAP
);
4807 size
= thresholds
->primary
? thresholds
->primary
->size
+ 1 : 1;
4809 /* Allocate memory for new array of thresholds */
4810 new = kmalloc(sizeof(*new) + size
* sizeof(struct mem_cgroup_threshold
),
4818 /* Copy thresholds (if any) to new array */
4819 if (thresholds
->primary
) {
4820 memcpy(new->entries
, thresholds
->primary
->entries
, (size
- 1) *
4821 sizeof(struct mem_cgroup_threshold
));
4824 /* Add new threshold */
4825 new->entries
[size
- 1].eventfd
= eventfd
;
4826 new->entries
[size
- 1].threshold
= threshold
;
4828 /* Sort thresholds. Registering of new threshold isn't time-critical */
4829 sort(new->entries
, size
, sizeof(struct mem_cgroup_threshold
),
4830 compare_thresholds
, NULL
);
4832 /* Find current threshold */
4833 new->current_threshold
= -1;
4834 for (i
= 0; i
< size
; i
++) {
4835 if (new->entries
[i
].threshold
<= usage
) {
4837 * new->current_threshold will not be used until
4838 * rcu_assign_pointer(), so it's safe to increment
4841 ++new->current_threshold
;
4846 /* Free old spare buffer and save old primary buffer as spare */
4847 kfree(thresholds
->spare
);
4848 thresholds
->spare
= thresholds
->primary
;
4850 rcu_assign_pointer(thresholds
->primary
, new);
4852 /* To be sure that nobody uses thresholds */
4856 mutex_unlock(&memcg
->thresholds_lock
);
4861 static void mem_cgroup_usage_unregister_event(struct cgroup
*cgrp
,
4862 struct cftype
*cft
, struct eventfd_ctx
*eventfd
)
4864 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cgrp
);
4865 struct mem_cgroup_thresholds
*thresholds
;
4866 struct mem_cgroup_threshold_ary
*new;
4867 enum res_type type
= MEMFILE_TYPE(cft
->private);
4871 mutex_lock(&memcg
->thresholds_lock
);
4873 thresholds
= &memcg
->thresholds
;
4874 else if (type
== _MEMSWAP
)
4875 thresholds
= &memcg
->memsw_thresholds
;
4879 if (!thresholds
->primary
)
4882 usage
= mem_cgroup_usage(memcg
, type
== _MEMSWAP
);
4884 /* Check if a threshold crossed before removing */
4885 __mem_cgroup_threshold(memcg
, type
== _MEMSWAP
);
4887 /* Calculate new number of threshold */
4889 for (i
= 0; i
< thresholds
->primary
->size
; i
++) {
4890 if (thresholds
->primary
->entries
[i
].eventfd
!= eventfd
)
4894 new = thresholds
->spare
;
4896 /* Set thresholds array to NULL if we don't have thresholds */
4905 /* Copy thresholds and find current threshold */
4906 new->current_threshold
= -1;
4907 for (i
= 0, j
= 0; i
< thresholds
->primary
->size
; i
++) {
4908 if (thresholds
->primary
->entries
[i
].eventfd
== eventfd
)
4911 new->entries
[j
] = thresholds
->primary
->entries
[i
];
4912 if (new->entries
[j
].threshold
<= usage
) {
4914 * new->current_threshold will not be used
4915 * until rcu_assign_pointer(), so it's safe to increment
4918 ++new->current_threshold
;
4924 /* Swap primary and spare array */
4925 thresholds
->spare
= thresholds
->primary
;
4926 /* If all events are unregistered, free the spare array */
4928 kfree(thresholds
->spare
);
4929 thresholds
->spare
= NULL
;
4932 rcu_assign_pointer(thresholds
->primary
, new);
4934 /* To be sure that nobody uses thresholds */
4937 mutex_unlock(&memcg
->thresholds_lock
);
4940 static int mem_cgroup_oom_register_event(struct cgroup
*cgrp
,
4941 struct cftype
*cft
, struct eventfd_ctx
*eventfd
, const char *args
)
4943 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cgrp
);
4944 struct mem_cgroup_eventfd_list
*event
;
4945 enum res_type type
= MEMFILE_TYPE(cft
->private);
4947 BUG_ON(type
!= _OOM_TYPE
);
4948 event
= kmalloc(sizeof(*event
), GFP_KERNEL
);
4952 spin_lock(&memcg_oom_lock
);
4954 event
->eventfd
= eventfd
;
4955 list_add(&event
->list
, &memcg
->oom_notify
);
4957 /* already in OOM ? */
4958 if (atomic_read(&memcg
->under_oom
))
4959 eventfd_signal(eventfd
, 1);
4960 spin_unlock(&memcg_oom_lock
);
4965 static void mem_cgroup_oom_unregister_event(struct cgroup
*cgrp
,
4966 struct cftype
*cft
, struct eventfd_ctx
*eventfd
)
4968 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cgrp
);
4969 struct mem_cgroup_eventfd_list
*ev
, *tmp
;
4970 enum res_type type
= MEMFILE_TYPE(cft
->private);
4972 BUG_ON(type
!= _OOM_TYPE
);
4974 spin_lock(&memcg_oom_lock
);
4976 list_for_each_entry_safe(ev
, tmp
, &memcg
->oom_notify
, list
) {
4977 if (ev
->eventfd
== eventfd
) {
4978 list_del(&ev
->list
);
4983 spin_unlock(&memcg_oom_lock
);
4986 static int mem_cgroup_oom_control_read(struct cgroup
*cgrp
,
4987 struct cftype
*cft
, struct cgroup_map_cb
*cb
)
4989 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cgrp
);
4991 cb
->fill(cb
, "oom_kill_disable", memcg
->oom_kill_disable
);
4993 if (atomic_read(&memcg
->under_oom
))
4994 cb
->fill(cb
, "under_oom", 1);
4996 cb
->fill(cb
, "under_oom", 0);
5000 static int mem_cgroup_oom_control_write(struct cgroup
*cgrp
,
5001 struct cftype
*cft
, u64 val
)
5003 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cgrp
);
5004 struct mem_cgroup
*parent
;
5006 /* cannot set to root cgroup and only 0 and 1 are allowed */
5007 if (!cgrp
->parent
|| !((val
== 0) || (val
== 1)))
5010 parent
= mem_cgroup_from_cont(cgrp
->parent
);
5013 /* oom-kill-disable is a flag for subhierarchy. */
5014 if ((parent
->use_hierarchy
) ||
5015 (memcg
->use_hierarchy
&& !list_empty(&cgrp
->children
))) {
5019 memcg
->oom_kill_disable
= val
;
5021 memcg_oom_recover(memcg
);
5026 #ifdef CONFIG_MEMCG_KMEM
5027 static int memcg_init_kmem(struct mem_cgroup
*memcg
, struct cgroup_subsys
*ss
)
5029 memcg_propagate_kmem(memcg
);
5030 return mem_cgroup_sockets_init(memcg
, ss
);
5033 static void kmem_cgroup_destroy(struct mem_cgroup
*memcg
)
5035 mem_cgroup_sockets_destroy(memcg
);
5037 memcg_kmem_mark_dead(memcg
);
5039 if (res_counter_read_u64(&memcg
->kmem
, RES_USAGE
) != 0)
5043 * Charges already down to 0, undo mem_cgroup_get() done in the charge
5044 * path here, being careful not to race with memcg_uncharge_kmem: it is
5045 * possible that the charges went down to 0 between mark_dead and the
5046 * res_counter read, so in that case, we don't need the put
5048 if (memcg_kmem_test_and_clear_dead(memcg
))
5049 mem_cgroup_put(memcg
);
5052 static int memcg_init_kmem(struct mem_cgroup
*memcg
, struct cgroup_subsys
*ss
)
5057 static void kmem_cgroup_destroy(struct mem_cgroup
*memcg
)
5062 static struct cftype mem_cgroup_files
[] = {
5064 .name
= "usage_in_bytes",
5065 .private = MEMFILE_PRIVATE(_MEM
, RES_USAGE
),
5066 .read
= mem_cgroup_read
,
5067 .register_event
= mem_cgroup_usage_register_event
,
5068 .unregister_event
= mem_cgroup_usage_unregister_event
,
5071 .name
= "max_usage_in_bytes",
5072 .private = MEMFILE_PRIVATE(_MEM
, RES_MAX_USAGE
),
5073 .trigger
= mem_cgroup_reset
,
5074 .read
= mem_cgroup_read
,
5077 .name
= "limit_in_bytes",
5078 .private = MEMFILE_PRIVATE(_MEM
, RES_LIMIT
),
5079 .write_string
= mem_cgroup_write
,
5080 .read
= mem_cgroup_read
,
5083 .name
= "soft_limit_in_bytes",
5084 .private = MEMFILE_PRIVATE(_MEM
, RES_SOFT_LIMIT
),
5085 .write_string
= mem_cgroup_write
,
5086 .read
= mem_cgroup_read
,
5090 .private = MEMFILE_PRIVATE(_MEM
, RES_FAILCNT
),
5091 .trigger
= mem_cgroup_reset
,
5092 .read
= mem_cgroup_read
,
5096 .read_seq_string
= memcg_stat_show
,
5099 .name
= "force_empty",
5100 .trigger
= mem_cgroup_force_empty_write
,
5103 .name
= "use_hierarchy",
5104 .write_u64
= mem_cgroup_hierarchy_write
,
5105 .read_u64
= mem_cgroup_hierarchy_read
,
5108 .name
= "swappiness",
5109 .read_u64
= mem_cgroup_swappiness_read
,
5110 .write_u64
= mem_cgroup_swappiness_write
,
5113 .name
= "move_charge_at_immigrate",
5114 .read_u64
= mem_cgroup_move_charge_read
,
5115 .write_u64
= mem_cgroup_move_charge_write
,
5118 .name
= "oom_control",
5119 .read_map
= mem_cgroup_oom_control_read
,
5120 .write_u64
= mem_cgroup_oom_control_write
,
5121 .register_event
= mem_cgroup_oom_register_event
,
5122 .unregister_event
= mem_cgroup_oom_unregister_event
,
5123 .private = MEMFILE_PRIVATE(_OOM_TYPE
, OOM_CONTROL
),
5127 .name
= "numa_stat",
5128 .read_seq_string
= memcg_numa_stat_show
,
5131 #ifdef CONFIG_MEMCG_SWAP
5133 .name
= "memsw.usage_in_bytes",
5134 .private = MEMFILE_PRIVATE(_MEMSWAP
, RES_USAGE
),
5135 .read
= mem_cgroup_read
,
5136 .register_event
= mem_cgroup_usage_register_event
,
5137 .unregister_event
= mem_cgroup_usage_unregister_event
,
5140 .name
= "memsw.max_usage_in_bytes",
5141 .private = MEMFILE_PRIVATE(_MEMSWAP
, RES_MAX_USAGE
),
5142 .trigger
= mem_cgroup_reset
,
5143 .read
= mem_cgroup_read
,
5146 .name
= "memsw.limit_in_bytes",
5147 .private = MEMFILE_PRIVATE(_MEMSWAP
, RES_LIMIT
),
5148 .write_string
= mem_cgroup_write
,
5149 .read
= mem_cgroup_read
,
5152 .name
= "memsw.failcnt",
5153 .private = MEMFILE_PRIVATE(_MEMSWAP
, RES_FAILCNT
),
5154 .trigger
= mem_cgroup_reset
,
5155 .read
= mem_cgroup_read
,
5158 #ifdef CONFIG_MEMCG_KMEM
5160 .name
= "kmem.limit_in_bytes",
5161 .private = MEMFILE_PRIVATE(_KMEM
, RES_LIMIT
),
5162 .write_string
= mem_cgroup_write
,
5163 .read
= mem_cgroup_read
,
5166 .name
= "kmem.usage_in_bytes",
5167 .private = MEMFILE_PRIVATE(_KMEM
, RES_USAGE
),
5168 .read
= mem_cgroup_read
,
5171 .name
= "kmem.failcnt",
5172 .private = MEMFILE_PRIVATE(_KMEM
, RES_FAILCNT
),
5173 .trigger
= mem_cgroup_reset
,
5174 .read
= mem_cgroup_read
,
5177 .name
= "kmem.max_usage_in_bytes",
5178 .private = MEMFILE_PRIVATE(_KMEM
, RES_MAX_USAGE
),
5179 .trigger
= mem_cgroup_reset
,
5180 .read
= mem_cgroup_read
,
5183 { }, /* terminate */
5186 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup
*memcg
, int node
)
5188 struct mem_cgroup_per_node
*pn
;
5189 struct mem_cgroup_per_zone
*mz
;
5190 int zone
, tmp
= node
;
5192 * This routine is called against possible nodes.
5193 * But it's BUG to call kmalloc() against offline node.
5195 * TODO: this routine can waste much memory for nodes which will
5196 * never be onlined. It's better to use memory hotplug callback
5199 if (!node_state(node
, N_NORMAL_MEMORY
))
5201 pn
= kzalloc_node(sizeof(*pn
), GFP_KERNEL
, tmp
);
5205 for (zone
= 0; zone
< MAX_NR_ZONES
; zone
++) {
5206 mz
= &pn
->zoneinfo
[zone
];
5207 lruvec_init(&mz
->lruvec
);
5208 mz
->usage_in_excess
= 0;
5209 mz
->on_tree
= false;
5212 memcg
->info
.nodeinfo
[node
] = pn
;
5216 static void free_mem_cgroup_per_zone_info(struct mem_cgroup
*memcg
, int node
)
5218 kfree(memcg
->info
.nodeinfo
[node
]);
5221 static struct mem_cgroup
*mem_cgroup_alloc(void)
5223 struct mem_cgroup
*memcg
;
5224 int size
= sizeof(struct mem_cgroup
);
5226 /* Can be very big if MAX_NUMNODES is very big */
5227 if (size
< PAGE_SIZE
)
5228 memcg
= kzalloc(size
, GFP_KERNEL
);
5230 memcg
= vzalloc(size
);
5235 memcg
->stat
= alloc_percpu(struct mem_cgroup_stat_cpu
);
5238 spin_lock_init(&memcg
->pcp_counter_lock
);
5242 if (size
< PAGE_SIZE
)
5250 * At destroying mem_cgroup, references from swap_cgroup can remain.
5251 * (scanning all at force_empty is too costly...)
5253 * Instead of clearing all references at force_empty, we remember
5254 * the number of reference from swap_cgroup and free mem_cgroup when
5255 * it goes down to 0.
5257 * Removal of cgroup itself succeeds regardless of refs from swap.
5260 static void __mem_cgroup_free(struct mem_cgroup
*memcg
)
5263 int size
= sizeof(struct mem_cgroup
);
5265 mem_cgroup_remove_from_trees(memcg
);
5266 free_css_id(&mem_cgroup_subsys
, &memcg
->css
);
5269 free_mem_cgroup_per_zone_info(memcg
, node
);
5271 free_percpu(memcg
->stat
);
5274 * We need to make sure that (at least for now), the jump label
5275 * destruction code runs outside of the cgroup lock. This is because
5276 * get_online_cpus(), which is called from the static_branch update,
5277 * can't be called inside the cgroup_lock. cpusets are the ones
5278 * enforcing this dependency, so if they ever change, we might as well.
5280 * schedule_work() will guarantee this happens. Be careful if you need
5281 * to move this code around, and make sure it is outside
5284 disarm_static_keys(memcg
);
5285 if (size
< PAGE_SIZE
)
5293 * Helpers for freeing a kmalloc()ed/vzalloc()ed mem_cgroup by RCU,
5294 * but in process context. The work_freeing structure is overlaid
5295 * on the rcu_freeing structure, which itself is overlaid on memsw.
5297 static void free_work(struct work_struct
*work
)
5299 struct mem_cgroup
*memcg
;
5301 memcg
= container_of(work
, struct mem_cgroup
, work_freeing
);
5302 __mem_cgroup_free(memcg
);
5305 static void free_rcu(struct rcu_head
*rcu_head
)
5307 struct mem_cgroup
*memcg
;
5309 memcg
= container_of(rcu_head
, struct mem_cgroup
, rcu_freeing
);
5310 INIT_WORK(&memcg
->work_freeing
, free_work
);
5311 schedule_work(&memcg
->work_freeing
);
5314 static void mem_cgroup_get(struct mem_cgroup
*memcg
)
5316 atomic_inc(&memcg
->refcnt
);
5319 static void __mem_cgroup_put(struct mem_cgroup
*memcg
, int count
)
5321 if (atomic_sub_and_test(count
, &memcg
->refcnt
)) {
5322 struct mem_cgroup
*parent
= parent_mem_cgroup(memcg
);
5323 call_rcu(&memcg
->rcu_freeing
, free_rcu
);
5325 mem_cgroup_put(parent
);
5329 static void mem_cgroup_put(struct mem_cgroup
*memcg
)
5331 __mem_cgroup_put(memcg
, 1);
5335 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
5337 struct mem_cgroup
*parent_mem_cgroup(struct mem_cgroup
*memcg
)
5339 if (!memcg
->res
.parent
)
5341 return mem_cgroup_from_res_counter(memcg
->res
.parent
, res
);
5343 EXPORT_SYMBOL(parent_mem_cgroup
);
5345 #ifdef CONFIG_MEMCG_SWAP
5346 static void __init
enable_swap_cgroup(void)
5348 if (!mem_cgroup_disabled() && really_do_swap_account
)
5349 do_swap_account
= 1;
5352 static void __init
enable_swap_cgroup(void)
5357 static int mem_cgroup_soft_limit_tree_init(void)
5359 struct mem_cgroup_tree_per_node
*rtpn
;
5360 struct mem_cgroup_tree_per_zone
*rtpz
;
5361 int tmp
, node
, zone
;
5363 for_each_node(node
) {
5365 if (!node_state(node
, N_NORMAL_MEMORY
))
5367 rtpn
= kzalloc_node(sizeof(*rtpn
), GFP_KERNEL
, tmp
);
5371 soft_limit_tree
.rb_tree_per_node
[node
] = rtpn
;
5373 for (zone
= 0; zone
< MAX_NR_ZONES
; zone
++) {
5374 rtpz
= &rtpn
->rb_tree_per_zone
[zone
];
5375 rtpz
->rb_root
= RB_ROOT
;
5376 spin_lock_init(&rtpz
->lock
);
5382 for_each_node(node
) {
5383 if (!soft_limit_tree
.rb_tree_per_node
[node
])
5385 kfree(soft_limit_tree
.rb_tree_per_node
[node
]);
5386 soft_limit_tree
.rb_tree_per_node
[node
] = NULL
;
5392 static struct cgroup_subsys_state
* __ref
5393 mem_cgroup_css_alloc(struct cgroup
*cont
)
5395 struct mem_cgroup
*memcg
, *parent
;
5396 long error
= -ENOMEM
;
5399 memcg
= mem_cgroup_alloc();
5401 return ERR_PTR(error
);
5404 if (alloc_mem_cgroup_per_zone_info(memcg
, node
))
5408 if (cont
->parent
== NULL
) {
5410 enable_swap_cgroup();
5412 if (mem_cgroup_soft_limit_tree_init())
5414 root_mem_cgroup
= memcg
;
5415 for_each_possible_cpu(cpu
) {
5416 struct memcg_stock_pcp
*stock
=
5417 &per_cpu(memcg_stock
, cpu
);
5418 INIT_WORK(&stock
->work
, drain_local_stock
);
5420 hotcpu_notifier(memcg_cpu_hotplug_callback
, 0);
5422 parent
= mem_cgroup_from_cont(cont
->parent
);
5423 memcg
->use_hierarchy
= parent
->use_hierarchy
;
5424 memcg
->oom_kill_disable
= parent
->oom_kill_disable
;
5427 if (parent
&& parent
->use_hierarchy
) {
5428 res_counter_init(&memcg
->res
, &parent
->res
);
5429 res_counter_init(&memcg
->memsw
, &parent
->memsw
);
5430 res_counter_init(&memcg
->kmem
, &parent
->kmem
);
5432 * We increment refcnt of the parent to ensure that we can
5433 * safely access it on res_counter_charge/uncharge.
5434 * This refcnt will be decremented when freeing this
5435 * mem_cgroup(see mem_cgroup_put).
5437 mem_cgroup_get(parent
);
5439 res_counter_init(&memcg
->res
, NULL
);
5440 res_counter_init(&memcg
->memsw
, NULL
);
5441 res_counter_init(&memcg
->kmem
, NULL
);
5443 * Deeper hierachy with use_hierarchy == false doesn't make
5444 * much sense so let cgroup subsystem know about this
5445 * unfortunate state in our controller.
5447 if (parent
&& parent
!= root_mem_cgroup
)
5448 mem_cgroup_subsys
.broken_hierarchy
= true;
5450 memcg
->last_scanned_node
= MAX_NUMNODES
;
5451 INIT_LIST_HEAD(&memcg
->oom_notify
);
5454 memcg
->swappiness
= mem_cgroup_swappiness(parent
);
5455 atomic_set(&memcg
->refcnt
, 1);
5456 memcg
->move_charge_at_immigrate
= 0;
5457 mutex_init(&memcg
->thresholds_lock
);
5458 spin_lock_init(&memcg
->move_lock
);
5460 error
= memcg_init_kmem(memcg
, &mem_cgroup_subsys
);
5463 * We call put now because our (and parent's) refcnts
5464 * are already in place. mem_cgroup_put() will internally
5465 * call __mem_cgroup_free, so return directly
5467 mem_cgroup_put(memcg
);
5468 return ERR_PTR(error
);
5472 __mem_cgroup_free(memcg
);
5473 return ERR_PTR(error
);
5476 static void mem_cgroup_css_offline(struct cgroup
*cont
)
5478 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cont
);
5480 mem_cgroup_reparent_charges(memcg
);
5483 static void mem_cgroup_css_free(struct cgroup
*cont
)
5485 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cont
);
5487 kmem_cgroup_destroy(memcg
);
5489 mem_cgroup_put(memcg
);
5493 /* Handlers for move charge at task migration. */
5494 #define PRECHARGE_COUNT_AT_ONCE 256
5495 static int mem_cgroup_do_precharge(unsigned long count
)
5498 int batch_count
= PRECHARGE_COUNT_AT_ONCE
;
5499 struct mem_cgroup
*memcg
= mc
.to
;
5501 if (mem_cgroup_is_root(memcg
)) {
5502 mc
.precharge
+= count
;
5503 /* we don't need css_get for root */
5506 /* try to charge at once */
5508 struct res_counter
*dummy
;
5510 * "memcg" cannot be under rmdir() because we've already checked
5511 * by cgroup_lock_live_cgroup() that it is not removed and we
5512 * are still under the same cgroup_mutex. So we can postpone
5515 if (res_counter_charge(&memcg
->res
, PAGE_SIZE
* count
, &dummy
))
5517 if (do_swap_account
&& res_counter_charge(&memcg
->memsw
,
5518 PAGE_SIZE
* count
, &dummy
)) {
5519 res_counter_uncharge(&memcg
->res
, PAGE_SIZE
* count
);
5522 mc
.precharge
+= count
;
5526 /* fall back to one by one charge */
5528 if (signal_pending(current
)) {
5532 if (!batch_count
--) {
5533 batch_count
= PRECHARGE_COUNT_AT_ONCE
;
5536 ret
= __mem_cgroup_try_charge(NULL
,
5537 GFP_KERNEL
, 1, &memcg
, false);
5539 /* mem_cgroup_clear_mc() will do uncharge later */
5547 * get_mctgt_type - get target type of moving charge
5548 * @vma: the vma the pte to be checked belongs
5549 * @addr: the address corresponding to the pte to be checked
5550 * @ptent: the pte to be checked
5551 * @target: the pointer the target page or swap ent will be stored(can be NULL)
5554 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
5555 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5556 * move charge. if @target is not NULL, the page is stored in target->page
5557 * with extra refcnt got(Callers should handle it).
5558 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5559 * target for charge migration. if @target is not NULL, the entry is stored
5562 * Called with pte lock held.
5569 enum mc_target_type
{
5575 static struct page
*mc_handle_present_pte(struct vm_area_struct
*vma
,
5576 unsigned long addr
, pte_t ptent
)
5578 struct page
*page
= vm_normal_page(vma
, addr
, ptent
);
5580 if (!page
|| !page_mapped(page
))
5582 if (PageAnon(page
)) {
5583 /* we don't move shared anon */
5586 } else if (!move_file())
5587 /* we ignore mapcount for file pages */
5589 if (!get_page_unless_zero(page
))
5596 static struct page
*mc_handle_swap_pte(struct vm_area_struct
*vma
,
5597 unsigned long addr
, pte_t ptent
, swp_entry_t
*entry
)
5599 struct page
*page
= NULL
;
5600 swp_entry_t ent
= pte_to_swp_entry(ptent
);
5602 if (!move_anon() || non_swap_entry(ent
))
5605 * Because lookup_swap_cache() updates some statistics counter,
5606 * we call find_get_page() with swapper_space directly.
5608 page
= find_get_page(&swapper_space
, ent
.val
);
5609 if (do_swap_account
)
5610 entry
->val
= ent
.val
;
5615 static struct page
*mc_handle_swap_pte(struct vm_area_struct
*vma
,
5616 unsigned long addr
, pte_t ptent
, swp_entry_t
*entry
)
5622 static struct page
*mc_handle_file_pte(struct vm_area_struct
*vma
,
5623 unsigned long addr
, pte_t ptent
, swp_entry_t
*entry
)
5625 struct page
*page
= NULL
;
5626 struct address_space
*mapping
;
5629 if (!vma
->vm_file
) /* anonymous vma */
5634 mapping
= vma
->vm_file
->f_mapping
;
5635 if (pte_none(ptent
))
5636 pgoff
= linear_page_index(vma
, addr
);
5637 else /* pte_file(ptent) is true */
5638 pgoff
= pte_to_pgoff(ptent
);
5640 /* page is moved even if it's not RSS of this task(page-faulted). */
5641 page
= find_get_page(mapping
, pgoff
);
5644 /* shmem/tmpfs may report page out on swap: account for that too. */
5645 if (radix_tree_exceptional_entry(page
)) {
5646 swp_entry_t swap
= radix_to_swp_entry(page
);
5647 if (do_swap_account
)
5649 page
= find_get_page(&swapper_space
, swap
.val
);
5655 static enum mc_target_type
get_mctgt_type(struct vm_area_struct
*vma
,
5656 unsigned long addr
, pte_t ptent
, union mc_target
*target
)
5658 struct page
*page
= NULL
;
5659 struct page_cgroup
*pc
;
5660 enum mc_target_type ret
= MC_TARGET_NONE
;
5661 swp_entry_t ent
= { .val
= 0 };
5663 if (pte_present(ptent
))
5664 page
= mc_handle_present_pte(vma
, addr
, ptent
);
5665 else if (is_swap_pte(ptent
))
5666 page
= mc_handle_swap_pte(vma
, addr
, ptent
, &ent
);
5667 else if (pte_none(ptent
) || pte_file(ptent
))
5668 page
= mc_handle_file_pte(vma
, addr
, ptent
, &ent
);
5670 if (!page
&& !ent
.val
)
5673 pc
= lookup_page_cgroup(page
);
5675 * Do only loose check w/o page_cgroup lock.
5676 * mem_cgroup_move_account() checks the pc is valid or not under
5679 if (PageCgroupUsed(pc
) && pc
->mem_cgroup
== mc
.from
) {
5680 ret
= MC_TARGET_PAGE
;
5682 target
->page
= page
;
5684 if (!ret
|| !target
)
5687 /* There is a swap entry and a page doesn't exist or isn't charged */
5688 if (ent
.val
&& !ret
&&
5689 css_id(&mc
.from
->css
) == lookup_swap_cgroup_id(ent
)) {
5690 ret
= MC_TARGET_SWAP
;
5697 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5699 * We don't consider swapping or file mapped pages because THP does not
5700 * support them for now.
5701 * Caller should make sure that pmd_trans_huge(pmd) is true.
5703 static enum mc_target_type
get_mctgt_type_thp(struct vm_area_struct
*vma
,
5704 unsigned long addr
, pmd_t pmd
, union mc_target
*target
)
5706 struct page
*page
= NULL
;
5707 struct page_cgroup
*pc
;
5708 enum mc_target_type ret
= MC_TARGET_NONE
;
5710 page
= pmd_page(pmd
);
5711 VM_BUG_ON(!page
|| !PageHead(page
));
5714 pc
= lookup_page_cgroup(page
);
5715 if (PageCgroupUsed(pc
) && pc
->mem_cgroup
== mc
.from
) {
5716 ret
= MC_TARGET_PAGE
;
5719 target
->page
= page
;
5725 static inline enum mc_target_type
get_mctgt_type_thp(struct vm_area_struct
*vma
,
5726 unsigned long addr
, pmd_t pmd
, union mc_target
*target
)
5728 return MC_TARGET_NONE
;
5732 static int mem_cgroup_count_precharge_pte_range(pmd_t
*pmd
,
5733 unsigned long addr
, unsigned long end
,
5734 struct mm_walk
*walk
)
5736 struct vm_area_struct
*vma
= walk
->private;
5740 if (pmd_trans_huge_lock(pmd
, vma
) == 1) {
5741 if (get_mctgt_type_thp(vma
, addr
, *pmd
, NULL
) == MC_TARGET_PAGE
)
5742 mc
.precharge
+= HPAGE_PMD_NR
;
5743 spin_unlock(&vma
->vm_mm
->page_table_lock
);
5747 if (pmd_trans_unstable(pmd
))
5749 pte
= pte_offset_map_lock(vma
->vm_mm
, pmd
, addr
, &ptl
);
5750 for (; addr
!= end
; pte
++, addr
+= PAGE_SIZE
)
5751 if (get_mctgt_type(vma
, addr
, *pte
, NULL
))
5752 mc
.precharge
++; /* increment precharge temporarily */
5753 pte_unmap_unlock(pte
- 1, ptl
);
5759 static unsigned long mem_cgroup_count_precharge(struct mm_struct
*mm
)
5761 unsigned long precharge
;
5762 struct vm_area_struct
*vma
;
5764 down_read(&mm
->mmap_sem
);
5765 for (vma
= mm
->mmap
; vma
; vma
= vma
->vm_next
) {
5766 struct mm_walk mem_cgroup_count_precharge_walk
= {
5767 .pmd_entry
= mem_cgroup_count_precharge_pte_range
,
5771 if (is_vm_hugetlb_page(vma
))
5773 walk_page_range(vma
->vm_start
, vma
->vm_end
,
5774 &mem_cgroup_count_precharge_walk
);
5776 up_read(&mm
->mmap_sem
);
5778 precharge
= mc
.precharge
;
5784 static int mem_cgroup_precharge_mc(struct mm_struct
*mm
)
5786 unsigned long precharge
= mem_cgroup_count_precharge(mm
);
5788 VM_BUG_ON(mc
.moving_task
);
5789 mc
.moving_task
= current
;
5790 return mem_cgroup_do_precharge(precharge
);
5793 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5794 static void __mem_cgroup_clear_mc(void)
5796 struct mem_cgroup
*from
= mc
.from
;
5797 struct mem_cgroup
*to
= mc
.to
;
5799 /* we must uncharge all the leftover precharges from mc.to */
5801 __mem_cgroup_cancel_charge(mc
.to
, mc
.precharge
);
5805 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5806 * we must uncharge here.
5808 if (mc
.moved_charge
) {
5809 __mem_cgroup_cancel_charge(mc
.from
, mc
.moved_charge
);
5810 mc
.moved_charge
= 0;
5812 /* we must fixup refcnts and charges */
5813 if (mc
.moved_swap
) {
5814 /* uncharge swap account from the old cgroup */
5815 if (!mem_cgroup_is_root(mc
.from
))
5816 res_counter_uncharge(&mc
.from
->memsw
,
5817 PAGE_SIZE
* mc
.moved_swap
);
5818 __mem_cgroup_put(mc
.from
, mc
.moved_swap
);
5820 if (!mem_cgroup_is_root(mc
.to
)) {
5822 * we charged both to->res and to->memsw, so we should
5825 res_counter_uncharge(&mc
.to
->res
,
5826 PAGE_SIZE
* mc
.moved_swap
);
5828 /* we've already done mem_cgroup_get(mc.to) */
5831 memcg_oom_recover(from
);
5832 memcg_oom_recover(to
);
5833 wake_up_all(&mc
.waitq
);
5836 static void mem_cgroup_clear_mc(void)
5838 struct mem_cgroup
*from
= mc
.from
;
5841 * we must clear moving_task before waking up waiters at the end of
5844 mc
.moving_task
= NULL
;
5845 __mem_cgroup_clear_mc();
5846 spin_lock(&mc
.lock
);
5849 spin_unlock(&mc
.lock
);
5850 mem_cgroup_end_move(from
);
5853 static int mem_cgroup_can_attach(struct cgroup
*cgroup
,
5854 struct cgroup_taskset
*tset
)
5856 struct task_struct
*p
= cgroup_taskset_first(tset
);
5858 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cgroup
);
5860 if (memcg
->move_charge_at_immigrate
) {
5861 struct mm_struct
*mm
;
5862 struct mem_cgroup
*from
= mem_cgroup_from_task(p
);
5864 VM_BUG_ON(from
== memcg
);
5866 mm
= get_task_mm(p
);
5869 /* We move charges only when we move a owner of the mm */
5870 if (mm
->owner
== p
) {
5873 VM_BUG_ON(mc
.precharge
);
5874 VM_BUG_ON(mc
.moved_charge
);
5875 VM_BUG_ON(mc
.moved_swap
);
5876 mem_cgroup_start_move(from
);
5877 spin_lock(&mc
.lock
);
5880 spin_unlock(&mc
.lock
);
5881 /* We set mc.moving_task later */
5883 ret
= mem_cgroup_precharge_mc(mm
);
5885 mem_cgroup_clear_mc();
5892 static void mem_cgroup_cancel_attach(struct cgroup
*cgroup
,
5893 struct cgroup_taskset
*tset
)
5895 mem_cgroup_clear_mc();
5898 static int mem_cgroup_move_charge_pte_range(pmd_t
*pmd
,
5899 unsigned long addr
, unsigned long end
,
5900 struct mm_walk
*walk
)
5903 struct vm_area_struct
*vma
= walk
->private;
5906 enum mc_target_type target_type
;
5907 union mc_target target
;
5909 struct page_cgroup
*pc
;
5912 * We don't take compound_lock() here but no race with splitting thp
5914 * - if pmd_trans_huge_lock() returns 1, the relevant thp is not
5915 * under splitting, which means there's no concurrent thp split,
5916 * - if another thread runs into split_huge_page() just after we
5917 * entered this if-block, the thread must wait for page table lock
5918 * to be unlocked in __split_huge_page_splitting(), where the main
5919 * part of thp split is not executed yet.
5921 if (pmd_trans_huge_lock(pmd
, vma
) == 1) {
5922 if (mc
.precharge
< HPAGE_PMD_NR
) {
5923 spin_unlock(&vma
->vm_mm
->page_table_lock
);
5926 target_type
= get_mctgt_type_thp(vma
, addr
, *pmd
, &target
);
5927 if (target_type
== MC_TARGET_PAGE
) {
5929 if (!isolate_lru_page(page
)) {
5930 pc
= lookup_page_cgroup(page
);
5931 if (!mem_cgroup_move_account(page
, HPAGE_PMD_NR
,
5932 pc
, mc
.from
, mc
.to
)) {
5933 mc
.precharge
-= HPAGE_PMD_NR
;
5934 mc
.moved_charge
+= HPAGE_PMD_NR
;
5936 putback_lru_page(page
);
5940 spin_unlock(&vma
->vm_mm
->page_table_lock
);
5944 if (pmd_trans_unstable(pmd
))
5947 pte
= pte_offset_map_lock(vma
->vm_mm
, pmd
, addr
, &ptl
);
5948 for (; addr
!= end
; addr
+= PAGE_SIZE
) {
5949 pte_t ptent
= *(pte
++);
5955 switch (get_mctgt_type(vma
, addr
, ptent
, &target
)) {
5956 case MC_TARGET_PAGE
:
5958 if (isolate_lru_page(page
))
5960 pc
= lookup_page_cgroup(page
);
5961 if (!mem_cgroup_move_account(page
, 1, pc
,
5964 /* we uncharge from mc.from later. */
5967 putback_lru_page(page
);
5968 put
: /* get_mctgt_type() gets the page */
5971 case MC_TARGET_SWAP
:
5973 if (!mem_cgroup_move_swap_account(ent
, mc
.from
, mc
.to
)) {
5975 /* we fixup refcnts and charges later. */
5983 pte_unmap_unlock(pte
- 1, ptl
);
5988 * We have consumed all precharges we got in can_attach().
5989 * We try charge one by one, but don't do any additional
5990 * charges to mc.to if we have failed in charge once in attach()
5993 ret
= mem_cgroup_do_precharge(1);
6001 static void mem_cgroup_move_charge(struct mm_struct
*mm
)
6003 struct vm_area_struct
*vma
;
6005 lru_add_drain_all();
6007 if (unlikely(!down_read_trylock(&mm
->mmap_sem
))) {
6009 * Someone who are holding the mmap_sem might be waiting in
6010 * waitq. So we cancel all extra charges, wake up all waiters,
6011 * and retry. Because we cancel precharges, we might not be able
6012 * to move enough charges, but moving charge is a best-effort
6013 * feature anyway, so it wouldn't be a big problem.
6015 __mem_cgroup_clear_mc();
6019 for (vma
= mm
->mmap
; vma
; vma
= vma
->vm_next
) {
6021 struct mm_walk mem_cgroup_move_charge_walk
= {
6022 .pmd_entry
= mem_cgroup_move_charge_pte_range
,
6026 if (is_vm_hugetlb_page(vma
))
6028 ret
= walk_page_range(vma
->vm_start
, vma
->vm_end
,
6029 &mem_cgroup_move_charge_walk
);
6032 * means we have consumed all precharges and failed in
6033 * doing additional charge. Just abandon here.
6037 up_read(&mm
->mmap_sem
);
6040 static void mem_cgroup_move_task(struct cgroup
*cont
,
6041 struct cgroup_taskset
*tset
)
6043 struct task_struct
*p
= cgroup_taskset_first(tset
);
6044 struct mm_struct
*mm
= get_task_mm(p
);
6048 mem_cgroup_move_charge(mm
);
6052 mem_cgroup_clear_mc();
6054 #else /* !CONFIG_MMU */
6055 static int mem_cgroup_can_attach(struct cgroup
*cgroup
,
6056 struct cgroup_taskset
*tset
)
6060 static void mem_cgroup_cancel_attach(struct cgroup
*cgroup
,
6061 struct cgroup_taskset
*tset
)
6064 static void mem_cgroup_move_task(struct cgroup
*cont
,
6065 struct cgroup_taskset
*tset
)
6070 struct cgroup_subsys mem_cgroup_subsys
= {
6072 .subsys_id
= mem_cgroup_subsys_id
,
6073 .css_alloc
= mem_cgroup_css_alloc
,
6074 .css_offline
= mem_cgroup_css_offline
,
6075 .css_free
= mem_cgroup_css_free
,
6076 .can_attach
= mem_cgroup_can_attach
,
6077 .cancel_attach
= mem_cgroup_cancel_attach
,
6078 .attach
= mem_cgroup_move_task
,
6079 .base_cftypes
= mem_cgroup_files
,
6084 #ifdef CONFIG_MEMCG_SWAP
6085 static int __init
enable_swap_account(char *s
)
6087 /* consider enabled if no parameter or 1 is given */
6088 if (!strcmp(s
, "1"))
6089 really_do_swap_account
= 1;
6090 else if (!strcmp(s
, "0"))
6091 really_do_swap_account
= 0;
6094 __setup("swapaccount=", enable_swap_account
);