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/vmpressure.h>
53 #include <linux/mm_inline.h>
54 #include <linux/page_cgroup.h>
55 #include <linux/cpu.h>
56 #include <linux/oom.h>
57 #include <linux/lockdep.h>
61 #include <net/tcp_memcontrol.h>
63 #include <asm/uaccess.h>
65 #include <trace/events/vmscan.h>
67 struct cgroup_subsys mem_cgroup_subsys __read_mostly
;
68 EXPORT_SYMBOL(mem_cgroup_subsys
);
70 #define MEM_CGROUP_RECLAIM_RETRIES 5
71 static struct mem_cgroup
*root_mem_cgroup __read_mostly
;
73 #ifdef CONFIG_MEMCG_SWAP
74 /* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
75 int do_swap_account __read_mostly
;
77 /* for remember boot option*/
78 #ifdef CONFIG_MEMCG_SWAP_ENABLED
79 static int really_do_swap_account __initdata
= 1;
81 static int really_do_swap_account __initdata
= 0;
85 #define do_swap_account 0
89 static const char * const mem_cgroup_stat_names
[] = {
98 enum mem_cgroup_events_index
{
99 MEM_CGROUP_EVENTS_PGPGIN
, /* # of pages paged in */
100 MEM_CGROUP_EVENTS_PGPGOUT
, /* # of pages paged out */
101 MEM_CGROUP_EVENTS_PGFAULT
, /* # of page-faults */
102 MEM_CGROUP_EVENTS_PGMAJFAULT
, /* # of major page-faults */
103 MEM_CGROUP_EVENTS_NSTATS
,
106 static const char * const mem_cgroup_events_names
[] = {
113 static const char * const mem_cgroup_lru_names
[] = {
122 * Per memcg event counter is incremented at every pagein/pageout. With THP,
123 * it will be incremated by the number of pages. This counter is used for
124 * for trigger some periodic events. This is straightforward and better
125 * than using jiffies etc. to handle periodic memcg event.
127 enum mem_cgroup_events_target
{
128 MEM_CGROUP_TARGET_THRESH
,
129 MEM_CGROUP_TARGET_SOFTLIMIT
,
130 MEM_CGROUP_TARGET_NUMAINFO
,
133 #define THRESHOLDS_EVENTS_TARGET 128
134 #define SOFTLIMIT_EVENTS_TARGET 1024
135 #define NUMAINFO_EVENTS_TARGET 1024
137 struct mem_cgroup_stat_cpu
{
138 long count
[MEM_CGROUP_STAT_NSTATS
];
139 unsigned long events
[MEM_CGROUP_EVENTS_NSTATS
];
140 unsigned long nr_page_events
;
141 unsigned long targets
[MEM_CGROUP_NTARGETS
];
144 struct mem_cgroup_reclaim_iter
{
146 * last scanned hierarchy member. Valid only if last_dead_count
147 * matches memcg->dead_count of the hierarchy root group.
149 struct mem_cgroup
*last_visited
;
150 unsigned long last_dead_count
;
152 /* scan generation, increased every round-trip */
153 unsigned int generation
;
157 * per-zone information in memory controller.
159 struct mem_cgroup_per_zone
{
160 struct lruvec lruvec
;
161 unsigned long lru_size
[NR_LRU_LISTS
];
163 struct mem_cgroup_reclaim_iter reclaim_iter
[DEF_PRIORITY
+ 1];
165 struct rb_node tree_node
; /* RB tree node */
166 unsigned long long usage_in_excess
;/* Set to the value by which */
167 /* the soft limit is exceeded*/
169 struct mem_cgroup
*memcg
; /* Back pointer, we cannot */
170 /* use container_of */
173 struct mem_cgroup_per_node
{
174 struct mem_cgroup_per_zone zoneinfo
[MAX_NR_ZONES
];
178 * Cgroups above their limits are maintained in a RB-Tree, independent of
179 * their hierarchy representation
182 struct mem_cgroup_tree_per_zone
{
183 struct rb_root rb_root
;
187 struct mem_cgroup_tree_per_node
{
188 struct mem_cgroup_tree_per_zone rb_tree_per_zone
[MAX_NR_ZONES
];
191 struct mem_cgroup_tree
{
192 struct mem_cgroup_tree_per_node
*rb_tree_per_node
[MAX_NUMNODES
];
195 static struct mem_cgroup_tree soft_limit_tree __read_mostly
;
197 struct mem_cgroup_threshold
{
198 struct eventfd_ctx
*eventfd
;
203 struct mem_cgroup_threshold_ary
{
204 /* An array index points to threshold just below or equal to usage. */
205 int current_threshold
;
206 /* Size of entries[] */
208 /* Array of thresholds */
209 struct mem_cgroup_threshold entries
[0];
212 struct mem_cgroup_thresholds
{
213 /* Primary thresholds array */
214 struct mem_cgroup_threshold_ary
*primary
;
216 * Spare threshold array.
217 * This is needed to make mem_cgroup_unregister_event() "never fail".
218 * It must be able to store at least primary->size - 1 entries.
220 struct mem_cgroup_threshold_ary
*spare
;
224 struct mem_cgroup_eventfd_list
{
225 struct list_head list
;
226 struct eventfd_ctx
*eventfd
;
229 static void mem_cgroup_threshold(struct mem_cgroup
*memcg
);
230 static void mem_cgroup_oom_notify(struct mem_cgroup
*memcg
);
233 * The memory controller data structure. The memory controller controls both
234 * page cache and RSS per cgroup. We would eventually like to provide
235 * statistics based on the statistics developed by Rik Van Riel for clock-pro,
236 * to help the administrator determine what knobs to tune.
238 * TODO: Add a water mark for the memory controller. Reclaim will begin when
239 * we hit the water mark. May be even add a low water mark, such that
240 * no reclaim occurs from a cgroup at it's low water mark, this is
241 * a feature that will be implemented much later in the future.
244 struct cgroup_subsys_state css
;
246 * the counter to account for memory usage
248 struct res_counter res
;
250 /* vmpressure notifications */
251 struct vmpressure vmpressure
;
253 /* css_online() has been completed */
257 * the counter to account for mem+swap usage.
259 struct res_counter memsw
;
262 * the counter to account for kernel memory usage.
264 struct res_counter kmem
;
266 * Should the accounting and control be hierarchical, per subtree?
269 unsigned long kmem_account_flags
; /* See KMEM_ACCOUNTED_*, below */
273 atomic_t oom_wakeups
;
276 /* OOM-Killer disable */
277 int oom_kill_disable
;
279 /* set when res.limit == memsw.limit */
280 bool memsw_is_minimum
;
282 /* protect arrays of thresholds */
283 struct mutex thresholds_lock
;
285 /* thresholds for memory usage. RCU-protected */
286 struct mem_cgroup_thresholds thresholds
;
288 /* thresholds for mem+swap usage. RCU-protected */
289 struct mem_cgroup_thresholds memsw_thresholds
;
291 /* For oom notifier event fd */
292 struct list_head oom_notify
;
295 * Should we move charges of a task when a task is moved into this
296 * mem_cgroup ? And what type of charges should we move ?
298 unsigned long move_charge_at_immigrate
;
300 * set > 0 if pages under this cgroup are moving to other cgroup.
302 atomic_t moving_account
;
303 /* taken only while moving_account > 0 */
304 spinlock_t move_lock
;
308 struct mem_cgroup_stat_cpu __percpu
*stat
;
310 * used when a cpu is offlined or other synchronizations
311 * See mem_cgroup_read_stat().
313 struct mem_cgroup_stat_cpu nocpu_base
;
314 spinlock_t pcp_counter_lock
;
317 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_INET)
318 struct tcp_memcontrol tcp_mem
;
320 #if defined(CONFIG_MEMCG_KMEM)
321 /* analogous to slab_common's slab_caches list. per-memcg */
322 struct list_head memcg_slab_caches
;
323 /* Not a spinlock, we can take a lot of time walking the list */
324 struct mutex slab_caches_mutex
;
325 /* Index in the kmem_cache->memcg_params->memcg_caches array */
329 int last_scanned_node
;
331 nodemask_t scan_nodes
;
332 atomic_t numainfo_events
;
333 atomic_t numainfo_updating
;
336 struct mem_cgroup_per_node
*nodeinfo
[0];
337 /* WARNING: nodeinfo must be the last member here */
340 static size_t memcg_size(void)
342 return sizeof(struct mem_cgroup
) +
343 nr_node_ids
* sizeof(struct mem_cgroup_per_node
*);
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_clear_activated(struct mem_cgroup
*memcg
)
375 clear_bit(KMEM_ACCOUNTED_ACTIVATED
, &memcg
->kmem_account_flags
);
378 static void memcg_kmem_mark_dead(struct mem_cgroup
*memcg
)
381 * Our caller must use css_get() first, because memcg_uncharge_kmem()
382 * will call css_put() if it sees the memcg is dead.
385 if (test_bit(KMEM_ACCOUNTED_ACTIVE
, &memcg
->kmem_account_flags
))
386 set_bit(KMEM_ACCOUNTED_DEAD
, &memcg
->kmem_account_flags
);
389 static bool memcg_kmem_test_and_clear_dead(struct mem_cgroup
*memcg
)
391 return test_and_clear_bit(KMEM_ACCOUNTED_DEAD
,
392 &memcg
->kmem_account_flags
);
396 /* Stuffs for move charges at task migration. */
398 * Types of charges to be moved. "move_charge_at_immitgrate" and
399 * "immigrate_flags" are treated as a left-shifted bitmap of these types.
402 MOVE_CHARGE_TYPE_ANON
, /* private anonymous page and swap of it */
403 MOVE_CHARGE_TYPE_FILE
, /* file page(including tmpfs) and swap of it */
407 /* "mc" and its members are protected by cgroup_mutex */
408 static struct move_charge_struct
{
409 spinlock_t lock
; /* for from, to */
410 struct mem_cgroup
*from
;
411 struct mem_cgroup
*to
;
412 unsigned long immigrate_flags
;
413 unsigned long precharge
;
414 unsigned long moved_charge
;
415 unsigned long moved_swap
;
416 struct task_struct
*moving_task
; /* a task moving charges */
417 wait_queue_head_t waitq
; /* a waitq for other context */
419 .lock
= __SPIN_LOCK_UNLOCKED(mc
.lock
),
420 .waitq
= __WAIT_QUEUE_HEAD_INITIALIZER(mc
.waitq
),
423 static bool move_anon(void)
425 return test_bit(MOVE_CHARGE_TYPE_ANON
, &mc
.immigrate_flags
);
428 static bool move_file(void)
430 return test_bit(MOVE_CHARGE_TYPE_FILE
, &mc
.immigrate_flags
);
434 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
435 * limit reclaim to prevent infinite loops, if they ever occur.
437 #define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
438 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
441 MEM_CGROUP_CHARGE_TYPE_CACHE
= 0,
442 MEM_CGROUP_CHARGE_TYPE_ANON
,
443 MEM_CGROUP_CHARGE_TYPE_SWAPOUT
, /* for accounting swapcache */
444 MEM_CGROUP_CHARGE_TYPE_DROP
, /* a page was unused swap cache */
448 /* for encoding cft->private value on file */
456 #define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
457 #define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
458 #define MEMFILE_ATTR(val) ((val) & 0xffff)
459 /* Used for OOM nofiier */
460 #define OOM_CONTROL (0)
463 * Reclaim flags for mem_cgroup_hierarchical_reclaim
465 #define MEM_CGROUP_RECLAIM_NOSWAP_BIT 0x0
466 #define MEM_CGROUP_RECLAIM_NOSWAP (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
467 #define MEM_CGROUP_RECLAIM_SHRINK_BIT 0x1
468 #define MEM_CGROUP_RECLAIM_SHRINK (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
471 * The memcg_create_mutex will be held whenever a new cgroup is created.
472 * As a consequence, any change that needs to protect against new child cgroups
473 * appearing has to hold it as well.
475 static DEFINE_MUTEX(memcg_create_mutex
);
477 struct mem_cgroup
*mem_cgroup_from_css(struct cgroup_subsys_state
*s
)
479 return s
? container_of(s
, struct mem_cgroup
, css
) : NULL
;
482 /* Some nice accessors for the vmpressure. */
483 struct vmpressure
*memcg_to_vmpressure(struct mem_cgroup
*memcg
)
486 memcg
= root_mem_cgroup
;
487 return &memcg
->vmpressure
;
490 struct cgroup_subsys_state
*vmpressure_to_css(struct vmpressure
*vmpr
)
492 return &container_of(vmpr
, struct mem_cgroup
, vmpressure
)->css
;
495 struct vmpressure
*css_to_vmpressure(struct cgroup_subsys_state
*css
)
497 return &mem_cgroup_from_css(css
)->vmpressure
;
500 static inline bool mem_cgroup_is_root(struct mem_cgroup
*memcg
)
502 return (memcg
== root_mem_cgroup
);
505 /* Writing them here to avoid exposing memcg's inner layout */
506 #if defined(CONFIG_INET) && defined(CONFIG_MEMCG_KMEM)
508 void sock_update_memcg(struct sock
*sk
)
510 if (mem_cgroup_sockets_enabled
) {
511 struct mem_cgroup
*memcg
;
512 struct cg_proto
*cg_proto
;
514 BUG_ON(!sk
->sk_prot
->proto_cgroup
);
516 /* Socket cloning can throw us here with sk_cgrp already
517 * filled. It won't however, necessarily happen from
518 * process context. So the test for root memcg given
519 * the current task's memcg won't help us in this case.
521 * Respecting the original socket's memcg is a better
522 * decision in this case.
525 BUG_ON(mem_cgroup_is_root(sk
->sk_cgrp
->memcg
));
526 css_get(&sk
->sk_cgrp
->memcg
->css
);
531 memcg
= mem_cgroup_from_task(current
);
532 cg_proto
= sk
->sk_prot
->proto_cgroup(memcg
);
533 if (!mem_cgroup_is_root(memcg
) &&
534 memcg_proto_active(cg_proto
) && css_tryget(&memcg
->css
)) {
535 sk
->sk_cgrp
= cg_proto
;
540 EXPORT_SYMBOL(sock_update_memcg
);
542 void sock_release_memcg(struct sock
*sk
)
544 if (mem_cgroup_sockets_enabled
&& sk
->sk_cgrp
) {
545 struct mem_cgroup
*memcg
;
546 WARN_ON(!sk
->sk_cgrp
->memcg
);
547 memcg
= sk
->sk_cgrp
->memcg
;
548 css_put(&sk
->sk_cgrp
->memcg
->css
);
552 struct cg_proto
*tcp_proto_cgroup(struct mem_cgroup
*memcg
)
554 if (!memcg
|| mem_cgroup_is_root(memcg
))
557 return &memcg
->tcp_mem
.cg_proto
;
559 EXPORT_SYMBOL(tcp_proto_cgroup
);
561 static void disarm_sock_keys(struct mem_cgroup
*memcg
)
563 if (!memcg_proto_activated(&memcg
->tcp_mem
.cg_proto
))
565 static_key_slow_dec(&memcg_socket_limit_enabled
);
568 static void disarm_sock_keys(struct mem_cgroup
*memcg
)
573 #ifdef CONFIG_MEMCG_KMEM
575 * This will be the memcg's index in each cache's ->memcg_params->memcg_caches.
576 * There are two main reasons for not using the css_id for this:
577 * 1) this works better in sparse environments, where we have a lot of memcgs,
578 * but only a few kmem-limited. Or also, if we have, for instance, 200
579 * memcgs, and none but the 200th is kmem-limited, we'd have to have a
580 * 200 entry array for that.
582 * 2) In order not to violate the cgroup API, we would like to do all memory
583 * allocation in ->create(). At that point, we haven't yet allocated the
584 * css_id. Having a separate index prevents us from messing with the cgroup
587 * The current size of the caches array is stored in
588 * memcg_limited_groups_array_size. It will double each time we have to
591 static DEFINE_IDA(kmem_limited_groups
);
592 int memcg_limited_groups_array_size
;
595 * MIN_SIZE is different than 1, because we would like to avoid going through
596 * the alloc/free process all the time. In a small machine, 4 kmem-limited
597 * cgroups is a reasonable guess. In the future, it could be a parameter or
598 * tunable, but that is strictly not necessary.
600 * MAX_SIZE should be as large as the number of css_ids. Ideally, we could get
601 * this constant directly from cgroup, but it is understandable that this is
602 * better kept as an internal representation in cgroup.c. In any case, the
603 * css_id space is not getting any smaller, and we don't have to necessarily
604 * increase ours as well if it increases.
606 #define MEMCG_CACHES_MIN_SIZE 4
607 #define MEMCG_CACHES_MAX_SIZE 65535
610 * A lot of the calls to the cache allocation functions are expected to be
611 * inlined by the compiler. Since the calls to memcg_kmem_get_cache are
612 * conditional to this static branch, we'll have to allow modules that does
613 * kmem_cache_alloc and the such to see this symbol as well
615 struct static_key memcg_kmem_enabled_key
;
616 EXPORT_SYMBOL(memcg_kmem_enabled_key
);
618 static void disarm_kmem_keys(struct mem_cgroup
*memcg
)
620 if (memcg_kmem_is_active(memcg
)) {
621 static_key_slow_dec(&memcg_kmem_enabled_key
);
622 ida_simple_remove(&kmem_limited_groups
, memcg
->kmemcg_id
);
625 * This check can't live in kmem destruction function,
626 * since the charges will outlive the cgroup
628 WARN_ON(res_counter_read_u64(&memcg
->kmem
, RES_USAGE
) != 0);
631 static void disarm_kmem_keys(struct mem_cgroup
*memcg
)
634 #endif /* CONFIG_MEMCG_KMEM */
636 static void disarm_static_keys(struct mem_cgroup
*memcg
)
638 disarm_sock_keys(memcg
);
639 disarm_kmem_keys(memcg
);
642 static void drain_all_stock_async(struct mem_cgroup
*memcg
);
644 static struct mem_cgroup_per_zone
*
645 mem_cgroup_zoneinfo(struct mem_cgroup
*memcg
, int nid
, int zid
)
647 VM_BUG_ON((unsigned)nid
>= nr_node_ids
);
648 return &memcg
->nodeinfo
[nid
]->zoneinfo
[zid
];
651 struct cgroup_subsys_state
*mem_cgroup_css(struct mem_cgroup
*memcg
)
656 static struct mem_cgroup_per_zone
*
657 page_cgroup_zoneinfo(struct mem_cgroup
*memcg
, struct page
*page
)
659 int nid
= page_to_nid(page
);
660 int zid
= page_zonenum(page
);
662 return mem_cgroup_zoneinfo(memcg
, nid
, zid
);
665 static struct mem_cgroup_tree_per_zone
*
666 soft_limit_tree_node_zone(int nid
, int zid
)
668 return &soft_limit_tree
.rb_tree_per_node
[nid
]->rb_tree_per_zone
[zid
];
671 static struct mem_cgroup_tree_per_zone
*
672 soft_limit_tree_from_page(struct page
*page
)
674 int nid
= page_to_nid(page
);
675 int zid
= page_zonenum(page
);
677 return &soft_limit_tree
.rb_tree_per_node
[nid
]->rb_tree_per_zone
[zid
];
681 __mem_cgroup_insert_exceeded(struct mem_cgroup
*memcg
,
682 struct mem_cgroup_per_zone
*mz
,
683 struct mem_cgroup_tree_per_zone
*mctz
,
684 unsigned long long new_usage_in_excess
)
686 struct rb_node
**p
= &mctz
->rb_root
.rb_node
;
687 struct rb_node
*parent
= NULL
;
688 struct mem_cgroup_per_zone
*mz_node
;
693 mz
->usage_in_excess
= new_usage_in_excess
;
694 if (!mz
->usage_in_excess
)
698 mz_node
= rb_entry(parent
, struct mem_cgroup_per_zone
,
700 if (mz
->usage_in_excess
< mz_node
->usage_in_excess
)
703 * We can't avoid mem cgroups that are over their soft
704 * limit by the same amount
706 else if (mz
->usage_in_excess
>= mz_node
->usage_in_excess
)
709 rb_link_node(&mz
->tree_node
, parent
, p
);
710 rb_insert_color(&mz
->tree_node
, &mctz
->rb_root
);
715 __mem_cgroup_remove_exceeded(struct mem_cgroup
*memcg
,
716 struct mem_cgroup_per_zone
*mz
,
717 struct mem_cgroup_tree_per_zone
*mctz
)
721 rb_erase(&mz
->tree_node
, &mctz
->rb_root
);
726 mem_cgroup_remove_exceeded(struct mem_cgroup
*memcg
,
727 struct mem_cgroup_per_zone
*mz
,
728 struct mem_cgroup_tree_per_zone
*mctz
)
730 spin_lock(&mctz
->lock
);
731 __mem_cgroup_remove_exceeded(memcg
, mz
, mctz
);
732 spin_unlock(&mctz
->lock
);
736 static void mem_cgroup_update_tree(struct mem_cgroup
*memcg
, struct page
*page
)
738 unsigned long long excess
;
739 struct mem_cgroup_per_zone
*mz
;
740 struct mem_cgroup_tree_per_zone
*mctz
;
741 int nid
= page_to_nid(page
);
742 int zid
= page_zonenum(page
);
743 mctz
= soft_limit_tree_from_page(page
);
746 * Necessary to update all ancestors when hierarchy is used.
747 * because their event counter is not touched.
749 for (; memcg
; memcg
= parent_mem_cgroup(memcg
)) {
750 mz
= mem_cgroup_zoneinfo(memcg
, nid
, zid
);
751 excess
= res_counter_soft_limit_excess(&memcg
->res
);
753 * We have to update the tree if mz is on RB-tree or
754 * mem is over its softlimit.
756 if (excess
|| mz
->on_tree
) {
757 spin_lock(&mctz
->lock
);
758 /* if on-tree, remove it */
760 __mem_cgroup_remove_exceeded(memcg
, mz
, mctz
);
762 * Insert again. mz->usage_in_excess will be updated.
763 * If excess is 0, no tree ops.
765 __mem_cgroup_insert_exceeded(memcg
, mz
, mctz
, excess
);
766 spin_unlock(&mctz
->lock
);
771 static void mem_cgroup_remove_from_trees(struct mem_cgroup
*memcg
)
774 struct mem_cgroup_per_zone
*mz
;
775 struct mem_cgroup_tree_per_zone
*mctz
;
777 for_each_node(node
) {
778 for (zone
= 0; zone
< MAX_NR_ZONES
; zone
++) {
779 mz
= mem_cgroup_zoneinfo(memcg
, node
, zone
);
780 mctz
= soft_limit_tree_node_zone(node
, zone
);
781 mem_cgroup_remove_exceeded(memcg
, mz
, mctz
);
786 static struct mem_cgroup_per_zone
*
787 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone
*mctz
)
789 struct rb_node
*rightmost
= NULL
;
790 struct mem_cgroup_per_zone
*mz
;
794 rightmost
= rb_last(&mctz
->rb_root
);
796 goto done
; /* Nothing to reclaim from */
798 mz
= rb_entry(rightmost
, struct mem_cgroup_per_zone
, tree_node
);
800 * Remove the node now but someone else can add it back,
801 * we will to add it back at the end of reclaim to its correct
802 * position in the tree.
804 __mem_cgroup_remove_exceeded(mz
->memcg
, mz
, mctz
);
805 if (!res_counter_soft_limit_excess(&mz
->memcg
->res
) ||
806 !css_tryget(&mz
->memcg
->css
))
812 static struct mem_cgroup_per_zone
*
813 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone
*mctz
)
815 struct mem_cgroup_per_zone
*mz
;
817 spin_lock(&mctz
->lock
);
818 mz
= __mem_cgroup_largest_soft_limit_node(mctz
);
819 spin_unlock(&mctz
->lock
);
824 * Implementation Note: reading percpu statistics for memcg.
826 * Both of vmstat[] and percpu_counter has threshold and do periodic
827 * synchronization to implement "quick" read. There are trade-off between
828 * reading cost and precision of value. Then, we may have a chance to implement
829 * a periodic synchronizion of counter in memcg's counter.
831 * But this _read() function is used for user interface now. The user accounts
832 * memory usage by memory cgroup and he _always_ requires exact value because
833 * he accounts memory. Even if we provide quick-and-fuzzy read, we always
834 * have to visit all online cpus and make sum. So, for now, unnecessary
835 * synchronization is not implemented. (just implemented for cpu hotplug)
837 * If there are kernel internal actions which can make use of some not-exact
838 * value, and reading all cpu value can be performance bottleneck in some
839 * common workload, threashold and synchonization as vmstat[] should be
842 static long mem_cgroup_read_stat(struct mem_cgroup
*memcg
,
843 enum mem_cgroup_stat_index idx
)
849 for_each_online_cpu(cpu
)
850 val
+= per_cpu(memcg
->stat
->count
[idx
], cpu
);
851 #ifdef CONFIG_HOTPLUG_CPU
852 spin_lock(&memcg
->pcp_counter_lock
);
853 val
+= memcg
->nocpu_base
.count
[idx
];
854 spin_unlock(&memcg
->pcp_counter_lock
);
860 static void mem_cgroup_swap_statistics(struct mem_cgroup
*memcg
,
863 int val
= (charge
) ? 1 : -1;
864 this_cpu_add(memcg
->stat
->count
[MEM_CGROUP_STAT_SWAP
], val
);
867 static unsigned long mem_cgroup_read_events(struct mem_cgroup
*memcg
,
868 enum mem_cgroup_events_index idx
)
870 unsigned long val
= 0;
874 for_each_online_cpu(cpu
)
875 val
+= per_cpu(memcg
->stat
->events
[idx
], cpu
);
876 #ifdef CONFIG_HOTPLUG_CPU
877 spin_lock(&memcg
->pcp_counter_lock
);
878 val
+= memcg
->nocpu_base
.events
[idx
];
879 spin_unlock(&memcg
->pcp_counter_lock
);
885 static void mem_cgroup_charge_statistics(struct mem_cgroup
*memcg
,
887 bool anon
, int nr_pages
)
892 * Here, RSS means 'mapped anon' and anon's SwapCache. Shmem/tmpfs is
893 * counted as CACHE even if it's on ANON LRU.
896 __this_cpu_add(memcg
->stat
->count
[MEM_CGROUP_STAT_RSS
],
899 __this_cpu_add(memcg
->stat
->count
[MEM_CGROUP_STAT_CACHE
],
902 if (PageTransHuge(page
))
903 __this_cpu_add(memcg
->stat
->count
[MEM_CGROUP_STAT_RSS_HUGE
],
906 /* pagein of a big page is an event. So, ignore page size */
908 __this_cpu_inc(memcg
->stat
->events
[MEM_CGROUP_EVENTS_PGPGIN
]);
910 __this_cpu_inc(memcg
->stat
->events
[MEM_CGROUP_EVENTS_PGPGOUT
]);
911 nr_pages
= -nr_pages
; /* for event */
914 __this_cpu_add(memcg
->stat
->nr_page_events
, nr_pages
);
920 mem_cgroup_get_lru_size(struct lruvec
*lruvec
, enum lru_list lru
)
922 struct mem_cgroup_per_zone
*mz
;
924 mz
= container_of(lruvec
, struct mem_cgroup_per_zone
, lruvec
);
925 return mz
->lru_size
[lru
];
929 mem_cgroup_zone_nr_lru_pages(struct mem_cgroup
*memcg
, int nid
, int zid
,
930 unsigned int lru_mask
)
932 struct mem_cgroup_per_zone
*mz
;
934 unsigned long ret
= 0;
936 mz
= mem_cgroup_zoneinfo(memcg
, nid
, zid
);
939 if (BIT(lru
) & lru_mask
)
940 ret
+= mz
->lru_size
[lru
];
946 mem_cgroup_node_nr_lru_pages(struct mem_cgroup
*memcg
,
947 int nid
, unsigned int lru_mask
)
952 for (zid
= 0; zid
< MAX_NR_ZONES
; zid
++)
953 total
+= mem_cgroup_zone_nr_lru_pages(memcg
,
959 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup
*memcg
,
960 unsigned int lru_mask
)
965 for_each_node_state(nid
, N_MEMORY
)
966 total
+= mem_cgroup_node_nr_lru_pages(memcg
, nid
, lru_mask
);
970 static bool mem_cgroup_event_ratelimit(struct mem_cgroup
*memcg
,
971 enum mem_cgroup_events_target target
)
973 unsigned long val
, next
;
975 val
= __this_cpu_read(memcg
->stat
->nr_page_events
);
976 next
= __this_cpu_read(memcg
->stat
->targets
[target
]);
977 /* from time_after() in jiffies.h */
978 if ((long)next
- (long)val
< 0) {
980 case MEM_CGROUP_TARGET_THRESH
:
981 next
= val
+ THRESHOLDS_EVENTS_TARGET
;
983 case MEM_CGROUP_TARGET_SOFTLIMIT
:
984 next
= val
+ SOFTLIMIT_EVENTS_TARGET
;
986 case MEM_CGROUP_TARGET_NUMAINFO
:
987 next
= val
+ NUMAINFO_EVENTS_TARGET
;
992 __this_cpu_write(memcg
->stat
->targets
[target
], next
);
999 * Check events in order.
1002 static void memcg_check_events(struct mem_cgroup
*memcg
, struct page
*page
)
1005 /* threshold event is triggered in finer grain than soft limit */
1006 if (unlikely(mem_cgroup_event_ratelimit(memcg
,
1007 MEM_CGROUP_TARGET_THRESH
))) {
1009 bool do_numainfo __maybe_unused
;
1011 do_softlimit
= mem_cgroup_event_ratelimit(memcg
,
1012 MEM_CGROUP_TARGET_SOFTLIMIT
);
1013 #if MAX_NUMNODES > 1
1014 do_numainfo
= mem_cgroup_event_ratelimit(memcg
,
1015 MEM_CGROUP_TARGET_NUMAINFO
);
1019 mem_cgroup_threshold(memcg
);
1020 if (unlikely(do_softlimit
))
1021 mem_cgroup_update_tree(memcg
, page
);
1022 #if MAX_NUMNODES > 1
1023 if (unlikely(do_numainfo
))
1024 atomic_inc(&memcg
->numainfo_events
);
1030 struct mem_cgroup
*mem_cgroup_from_task(struct task_struct
*p
)
1033 * mm_update_next_owner() may clear mm->owner to NULL
1034 * if it races with swapoff, page migration, etc.
1035 * So this can be called with p == NULL.
1040 return mem_cgroup_from_css(task_css(p
, mem_cgroup_subsys_id
));
1043 struct mem_cgroup
*try_get_mem_cgroup_from_mm(struct mm_struct
*mm
)
1045 struct mem_cgroup
*memcg
= NULL
;
1050 * Because we have no locks, mm->owner's may be being moved to other
1051 * cgroup. We use css_tryget() here even if this looks
1052 * pessimistic (rather than adding locks here).
1056 memcg
= mem_cgroup_from_task(rcu_dereference(mm
->owner
));
1057 if (unlikely(!memcg
))
1059 } while (!css_tryget(&memcg
->css
));
1065 * Returns a next (in a pre-order walk) alive memcg (with elevated css
1066 * ref. count) or NULL if the whole root's subtree has been visited.
1068 * helper function to be used by mem_cgroup_iter
1070 static struct mem_cgroup
*__mem_cgroup_iter_next(struct mem_cgroup
*root
,
1071 struct mem_cgroup
*last_visited
)
1073 struct cgroup_subsys_state
*prev_css
, *next_css
;
1075 prev_css
= last_visited
? &last_visited
->css
: NULL
;
1077 next_css
= css_next_descendant_pre(prev_css
, &root
->css
);
1080 * Even if we found a group we have to make sure it is
1081 * alive. css && !memcg means that the groups should be
1082 * skipped and we should continue the tree walk.
1083 * last_visited css is safe to use because it is
1084 * protected by css_get and the tree walk is rcu safe.
1086 * We do not take a reference on the root of the tree walk
1087 * because we might race with the root removal when it would
1088 * be the only node in the iterated hierarchy and mem_cgroup_iter
1089 * would end up in an endless loop because it expects that at
1090 * least one valid node will be returned. Root cannot disappear
1091 * because caller of the iterator should hold it already so
1092 * skipping css reference should be safe.
1095 struct mem_cgroup
*memcg
= mem_cgroup_from_css(next_css
);
1097 if (next_css
== &root
->css
)
1100 if (css_tryget(next_css
)) {
1101 if (memcg
->initialized
) {
1103 * Make sure the memcg is initialized:
1104 * mem_cgroup_css_online() orders the the
1105 * initialization against setting the flag.
1113 prev_css
= next_css
;
1120 static void mem_cgroup_iter_invalidate(struct mem_cgroup
*root
)
1123 * When a group in the hierarchy below root is destroyed, the
1124 * hierarchy iterator can no longer be trusted since it might
1125 * have pointed to the destroyed group. Invalidate it.
1127 atomic_inc(&root
->dead_count
);
1130 static struct mem_cgroup
*
1131 mem_cgroup_iter_load(struct mem_cgroup_reclaim_iter
*iter
,
1132 struct mem_cgroup
*root
,
1135 struct mem_cgroup
*position
= NULL
;
1137 * A cgroup destruction happens in two stages: offlining and
1138 * release. They are separated by a RCU grace period.
1140 * If the iterator is valid, we may still race with an
1141 * offlining. The RCU lock ensures the object won't be
1142 * released, tryget will fail if we lost the race.
1144 *sequence
= atomic_read(&root
->dead_count
);
1145 if (iter
->last_dead_count
== *sequence
) {
1147 position
= iter
->last_visited
;
1150 * We cannot take a reference to root because we might race
1151 * with root removal and returning NULL would end up in
1152 * an endless loop on the iterator user level when root
1153 * would be returned all the time.
1155 if (position
&& position
!= root
&&
1156 !css_tryget(&position
->css
))
1162 static void mem_cgroup_iter_update(struct mem_cgroup_reclaim_iter
*iter
,
1163 struct mem_cgroup
*last_visited
,
1164 struct mem_cgroup
*new_position
,
1165 struct mem_cgroup
*root
,
1168 /* root reference counting symmetric to mem_cgroup_iter_load */
1169 if (last_visited
&& last_visited
!= root
)
1170 css_put(&last_visited
->css
);
1172 * We store the sequence count from the time @last_visited was
1173 * loaded successfully instead of rereading it here so that we
1174 * don't lose destruction events in between. We could have
1175 * raced with the destruction of @new_position after all.
1177 iter
->last_visited
= new_position
;
1179 iter
->last_dead_count
= sequence
;
1183 * mem_cgroup_iter - iterate over memory cgroup hierarchy
1184 * @root: hierarchy root
1185 * @prev: previously returned memcg, NULL on first invocation
1186 * @reclaim: cookie for shared reclaim walks, NULL for full walks
1188 * Returns references to children of the hierarchy below @root, or
1189 * @root itself, or %NULL after a full round-trip.
1191 * Caller must pass the return value in @prev on subsequent
1192 * invocations for reference counting, or use mem_cgroup_iter_break()
1193 * to cancel a hierarchy walk before the round-trip is complete.
1195 * Reclaimers can specify a zone and a priority level in @reclaim to
1196 * divide up the memcgs in the hierarchy among all concurrent
1197 * reclaimers operating on the same zone and priority.
1199 struct mem_cgroup
*mem_cgroup_iter(struct mem_cgroup
*root
,
1200 struct mem_cgroup
*prev
,
1201 struct mem_cgroup_reclaim_cookie
*reclaim
)
1203 struct mem_cgroup
*memcg
= NULL
;
1204 struct mem_cgroup
*last_visited
= NULL
;
1206 if (mem_cgroup_disabled())
1210 root
= root_mem_cgroup
;
1212 if (prev
&& !reclaim
)
1213 last_visited
= prev
;
1215 if (!root
->use_hierarchy
&& root
!= root_mem_cgroup
) {
1223 struct mem_cgroup_reclaim_iter
*uninitialized_var(iter
);
1224 int uninitialized_var(seq
);
1227 int nid
= zone_to_nid(reclaim
->zone
);
1228 int zid
= zone_idx(reclaim
->zone
);
1229 struct mem_cgroup_per_zone
*mz
;
1231 mz
= mem_cgroup_zoneinfo(root
, nid
, zid
);
1232 iter
= &mz
->reclaim_iter
[reclaim
->priority
];
1233 if (prev
&& reclaim
->generation
!= iter
->generation
) {
1234 iter
->last_visited
= NULL
;
1238 last_visited
= mem_cgroup_iter_load(iter
, root
, &seq
);
1241 memcg
= __mem_cgroup_iter_next(root
, last_visited
);
1244 mem_cgroup_iter_update(iter
, last_visited
, memcg
, root
,
1249 else if (!prev
&& memcg
)
1250 reclaim
->generation
= iter
->generation
;
1259 if (prev
&& prev
!= root
)
1260 css_put(&prev
->css
);
1266 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1267 * @root: hierarchy root
1268 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1270 void mem_cgroup_iter_break(struct mem_cgroup
*root
,
1271 struct mem_cgroup
*prev
)
1274 root
= root_mem_cgroup
;
1275 if (prev
&& prev
!= root
)
1276 css_put(&prev
->css
);
1280 * Iteration constructs for visiting all cgroups (under a tree). If
1281 * loops are exited prematurely (break), mem_cgroup_iter_break() must
1282 * be used for reference counting.
1284 #define for_each_mem_cgroup_tree(iter, root) \
1285 for (iter = mem_cgroup_iter(root, NULL, NULL); \
1287 iter = mem_cgroup_iter(root, iter, NULL))
1289 #define for_each_mem_cgroup(iter) \
1290 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
1292 iter = mem_cgroup_iter(NULL, iter, NULL))
1294 void __mem_cgroup_count_vm_event(struct mm_struct
*mm
, enum vm_event_item idx
)
1296 struct mem_cgroup
*memcg
;
1299 memcg
= mem_cgroup_from_task(rcu_dereference(mm
->owner
));
1300 if (unlikely(!memcg
))
1305 this_cpu_inc(memcg
->stat
->events
[MEM_CGROUP_EVENTS_PGFAULT
]);
1308 this_cpu_inc(memcg
->stat
->events
[MEM_CGROUP_EVENTS_PGMAJFAULT
]);
1316 EXPORT_SYMBOL(__mem_cgroup_count_vm_event
);
1319 * mem_cgroup_zone_lruvec - get the lru list vector for a zone and memcg
1320 * @zone: zone of the wanted lruvec
1321 * @memcg: memcg of the wanted lruvec
1323 * Returns the lru list vector holding pages for the given @zone and
1324 * @mem. This can be the global zone lruvec, if the memory controller
1327 struct lruvec
*mem_cgroup_zone_lruvec(struct zone
*zone
,
1328 struct mem_cgroup
*memcg
)
1330 struct mem_cgroup_per_zone
*mz
;
1331 struct lruvec
*lruvec
;
1333 if (mem_cgroup_disabled()) {
1334 lruvec
= &zone
->lruvec
;
1338 mz
= mem_cgroup_zoneinfo(memcg
, zone_to_nid(zone
), zone_idx(zone
));
1339 lruvec
= &mz
->lruvec
;
1342 * Since a node can be onlined after the mem_cgroup was created,
1343 * we have to be prepared to initialize lruvec->zone here;
1344 * and if offlined then reonlined, we need to reinitialize it.
1346 if (unlikely(lruvec
->zone
!= zone
))
1347 lruvec
->zone
= zone
;
1352 * Following LRU functions are allowed to be used without PCG_LOCK.
1353 * Operations are called by routine of global LRU independently from memcg.
1354 * What we have to take care of here is validness of pc->mem_cgroup.
1356 * Changes to pc->mem_cgroup happens when
1359 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
1360 * It is added to LRU before charge.
1361 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
1362 * When moving account, the page is not on LRU. It's isolated.
1366 * mem_cgroup_page_lruvec - return lruvec for adding an lru page
1368 * @zone: zone of the page
1370 struct lruvec
*mem_cgroup_page_lruvec(struct page
*page
, struct zone
*zone
)
1372 struct mem_cgroup_per_zone
*mz
;
1373 struct mem_cgroup
*memcg
;
1374 struct page_cgroup
*pc
;
1375 struct lruvec
*lruvec
;
1377 if (mem_cgroup_disabled()) {
1378 lruvec
= &zone
->lruvec
;
1382 pc
= lookup_page_cgroup(page
);
1383 memcg
= pc
->mem_cgroup
;
1386 * Surreptitiously switch any uncharged offlist page to root:
1387 * an uncharged page off lru does nothing to secure
1388 * its former mem_cgroup from sudden removal.
1390 * Our caller holds lru_lock, and PageCgroupUsed is updated
1391 * under page_cgroup lock: between them, they make all uses
1392 * of pc->mem_cgroup safe.
1394 if (!PageLRU(page
) && !PageCgroupUsed(pc
) && memcg
!= root_mem_cgroup
)
1395 pc
->mem_cgroup
= memcg
= root_mem_cgroup
;
1397 mz
= page_cgroup_zoneinfo(memcg
, page
);
1398 lruvec
= &mz
->lruvec
;
1401 * Since a node can be onlined after the mem_cgroup was created,
1402 * we have to be prepared to initialize lruvec->zone here;
1403 * and if offlined then reonlined, we need to reinitialize it.
1405 if (unlikely(lruvec
->zone
!= zone
))
1406 lruvec
->zone
= zone
;
1411 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1412 * @lruvec: mem_cgroup per zone lru vector
1413 * @lru: index of lru list the page is sitting on
1414 * @nr_pages: positive when adding or negative when removing
1416 * This function must be called when a page is added to or removed from an
1419 void mem_cgroup_update_lru_size(struct lruvec
*lruvec
, enum lru_list lru
,
1422 struct mem_cgroup_per_zone
*mz
;
1423 unsigned long *lru_size
;
1425 if (mem_cgroup_disabled())
1428 mz
= container_of(lruvec
, struct mem_cgroup_per_zone
, lruvec
);
1429 lru_size
= mz
->lru_size
+ lru
;
1430 *lru_size
+= nr_pages
;
1431 VM_BUG_ON((long)(*lru_size
) < 0);
1435 * Checks whether given mem is same or in the root_mem_cgroup's
1438 bool __mem_cgroup_same_or_subtree(const struct mem_cgroup
*root_memcg
,
1439 struct mem_cgroup
*memcg
)
1441 if (root_memcg
== memcg
)
1443 if (!root_memcg
->use_hierarchy
|| !memcg
)
1445 return css_is_ancestor(&memcg
->css
, &root_memcg
->css
);
1448 static bool mem_cgroup_same_or_subtree(const struct mem_cgroup
*root_memcg
,
1449 struct mem_cgroup
*memcg
)
1454 ret
= __mem_cgroup_same_or_subtree(root_memcg
, memcg
);
1459 bool task_in_mem_cgroup(struct task_struct
*task
,
1460 const struct mem_cgroup
*memcg
)
1462 struct mem_cgroup
*curr
= NULL
;
1463 struct task_struct
*p
;
1466 p
= find_lock_task_mm(task
);
1468 curr
= try_get_mem_cgroup_from_mm(p
->mm
);
1472 * All threads may have already detached their mm's, but the oom
1473 * killer still needs to detect if they have already been oom
1474 * killed to prevent needlessly killing additional tasks.
1477 curr
= mem_cgroup_from_task(task
);
1479 css_get(&curr
->css
);
1485 * We should check use_hierarchy of "memcg" not "curr". Because checking
1486 * use_hierarchy of "curr" here make this function true if hierarchy is
1487 * enabled in "curr" and "curr" is a child of "memcg" in *cgroup*
1488 * hierarchy(even if use_hierarchy is disabled in "memcg").
1490 ret
= mem_cgroup_same_or_subtree(memcg
, curr
);
1491 css_put(&curr
->css
);
1495 int mem_cgroup_inactive_anon_is_low(struct lruvec
*lruvec
)
1497 unsigned long inactive_ratio
;
1498 unsigned long inactive
;
1499 unsigned long active
;
1502 inactive
= mem_cgroup_get_lru_size(lruvec
, LRU_INACTIVE_ANON
);
1503 active
= mem_cgroup_get_lru_size(lruvec
, LRU_ACTIVE_ANON
);
1505 gb
= (inactive
+ active
) >> (30 - PAGE_SHIFT
);
1507 inactive_ratio
= int_sqrt(10 * gb
);
1511 return inactive
* inactive_ratio
< active
;
1514 #define mem_cgroup_from_res_counter(counter, member) \
1515 container_of(counter, struct mem_cgroup, member)
1518 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1519 * @memcg: the memory cgroup
1521 * Returns the maximum amount of memory @mem can be charged with, in
1524 static unsigned long mem_cgroup_margin(struct mem_cgroup
*memcg
)
1526 unsigned long long margin
;
1528 margin
= res_counter_margin(&memcg
->res
);
1529 if (do_swap_account
)
1530 margin
= min(margin
, res_counter_margin(&memcg
->memsw
));
1531 return margin
>> PAGE_SHIFT
;
1534 int mem_cgroup_swappiness(struct mem_cgroup
*memcg
)
1537 if (!css_parent(&memcg
->css
))
1538 return vm_swappiness
;
1540 return memcg
->swappiness
;
1544 * memcg->moving_account is used for checking possibility that some thread is
1545 * calling move_account(). When a thread on CPU-A starts moving pages under
1546 * a memcg, other threads should check memcg->moving_account under
1547 * rcu_read_lock(), like this:
1551 * memcg->moving_account+1 if (memcg->mocing_account)
1553 * synchronize_rcu() update something.
1558 /* for quick checking without looking up memcg */
1559 atomic_t memcg_moving __read_mostly
;
1561 static void mem_cgroup_start_move(struct mem_cgroup
*memcg
)
1563 atomic_inc(&memcg_moving
);
1564 atomic_inc(&memcg
->moving_account
);
1568 static void mem_cgroup_end_move(struct mem_cgroup
*memcg
)
1571 * Now, mem_cgroup_clear_mc() may call this function with NULL.
1572 * We check NULL in callee rather than caller.
1575 atomic_dec(&memcg_moving
);
1576 atomic_dec(&memcg
->moving_account
);
1581 * 2 routines for checking "mem" is under move_account() or not.
1583 * mem_cgroup_stolen() - checking whether a cgroup is mc.from or not. This
1584 * is used for avoiding races in accounting. If true,
1585 * pc->mem_cgroup may be overwritten.
1587 * mem_cgroup_under_move() - checking a cgroup is mc.from or mc.to or
1588 * under hierarchy of moving cgroups. This is for
1589 * waiting at hith-memory prressure caused by "move".
1592 static bool mem_cgroup_stolen(struct mem_cgroup
*memcg
)
1594 VM_BUG_ON(!rcu_read_lock_held());
1595 return atomic_read(&memcg
->moving_account
) > 0;
1598 static bool mem_cgroup_under_move(struct mem_cgroup
*memcg
)
1600 struct mem_cgroup
*from
;
1601 struct mem_cgroup
*to
;
1604 * Unlike task_move routines, we access mc.to, mc.from not under
1605 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1607 spin_lock(&mc
.lock
);
1613 ret
= mem_cgroup_same_or_subtree(memcg
, from
)
1614 || mem_cgroup_same_or_subtree(memcg
, to
);
1616 spin_unlock(&mc
.lock
);
1620 static bool mem_cgroup_wait_acct_move(struct mem_cgroup
*memcg
)
1622 if (mc
.moving_task
&& current
!= mc
.moving_task
) {
1623 if (mem_cgroup_under_move(memcg
)) {
1625 prepare_to_wait(&mc
.waitq
, &wait
, TASK_INTERRUPTIBLE
);
1626 /* moving charge context might have finished. */
1629 finish_wait(&mc
.waitq
, &wait
);
1637 * Take this lock when
1638 * - a code tries to modify page's memcg while it's USED.
1639 * - a code tries to modify page state accounting in a memcg.
1640 * see mem_cgroup_stolen(), too.
1642 static void move_lock_mem_cgroup(struct mem_cgroup
*memcg
,
1643 unsigned long *flags
)
1645 spin_lock_irqsave(&memcg
->move_lock
, *flags
);
1648 static void move_unlock_mem_cgroup(struct mem_cgroup
*memcg
,
1649 unsigned long *flags
)
1651 spin_unlock_irqrestore(&memcg
->move_lock
, *flags
);
1654 #define K(x) ((x) << (PAGE_SHIFT-10))
1656 * mem_cgroup_print_oom_info: Print OOM information relevant to memory controller.
1657 * @memcg: The memory cgroup that went over limit
1658 * @p: Task that is going to be killed
1660 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1663 void mem_cgroup_print_oom_info(struct mem_cgroup
*memcg
, struct task_struct
*p
)
1665 struct cgroup
*task_cgrp
;
1666 struct cgroup
*mem_cgrp
;
1668 * Need a buffer in BSS, can't rely on allocations. The code relies
1669 * on the assumption that OOM is serialized for memory controller.
1670 * If this assumption is broken, revisit this code.
1672 static char memcg_name
[PATH_MAX
];
1674 struct mem_cgroup
*iter
;
1682 mem_cgrp
= memcg
->css
.cgroup
;
1683 task_cgrp
= task_cgroup(p
, mem_cgroup_subsys_id
);
1685 ret
= cgroup_path(task_cgrp
, memcg_name
, PATH_MAX
);
1688 * Unfortunately, we are unable to convert to a useful name
1689 * But we'll still print out the usage information
1696 pr_info("Task in %s killed", memcg_name
);
1699 ret
= cgroup_path(mem_cgrp
, memcg_name
, PATH_MAX
);
1707 * Continues from above, so we don't need an KERN_ level
1709 pr_cont(" as a result of limit of %s\n", memcg_name
);
1712 pr_info("memory: usage %llukB, limit %llukB, failcnt %llu\n",
1713 res_counter_read_u64(&memcg
->res
, RES_USAGE
) >> 10,
1714 res_counter_read_u64(&memcg
->res
, RES_LIMIT
) >> 10,
1715 res_counter_read_u64(&memcg
->res
, RES_FAILCNT
));
1716 pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %llu\n",
1717 res_counter_read_u64(&memcg
->memsw
, RES_USAGE
) >> 10,
1718 res_counter_read_u64(&memcg
->memsw
, RES_LIMIT
) >> 10,
1719 res_counter_read_u64(&memcg
->memsw
, RES_FAILCNT
));
1720 pr_info("kmem: usage %llukB, limit %llukB, failcnt %llu\n",
1721 res_counter_read_u64(&memcg
->kmem
, RES_USAGE
) >> 10,
1722 res_counter_read_u64(&memcg
->kmem
, RES_LIMIT
) >> 10,
1723 res_counter_read_u64(&memcg
->kmem
, RES_FAILCNT
));
1725 for_each_mem_cgroup_tree(iter
, memcg
) {
1726 pr_info("Memory cgroup stats");
1729 ret
= cgroup_path(iter
->css
.cgroup
, memcg_name
, PATH_MAX
);
1731 pr_cont(" for %s", memcg_name
);
1735 for (i
= 0; i
< MEM_CGROUP_STAT_NSTATS
; i
++) {
1736 if (i
== MEM_CGROUP_STAT_SWAP
&& !do_swap_account
)
1738 pr_cont(" %s:%ldKB", mem_cgroup_stat_names
[i
],
1739 K(mem_cgroup_read_stat(iter
, i
)));
1742 for (i
= 0; i
< NR_LRU_LISTS
; i
++)
1743 pr_cont(" %s:%luKB", mem_cgroup_lru_names
[i
],
1744 K(mem_cgroup_nr_lru_pages(iter
, BIT(i
))));
1751 * This function returns the number of memcg under hierarchy tree. Returns
1752 * 1(self count) if no children.
1754 static int mem_cgroup_count_children(struct mem_cgroup
*memcg
)
1757 struct mem_cgroup
*iter
;
1759 for_each_mem_cgroup_tree(iter
, memcg
)
1765 * Return the memory (and swap, if configured) limit for a memcg.
1767 static u64
mem_cgroup_get_limit(struct mem_cgroup
*memcg
)
1771 limit
= res_counter_read_u64(&memcg
->res
, RES_LIMIT
);
1774 * Do not consider swap space if we cannot swap due to swappiness
1776 if (mem_cgroup_swappiness(memcg
)) {
1779 limit
+= total_swap_pages
<< PAGE_SHIFT
;
1780 memsw
= res_counter_read_u64(&memcg
->memsw
, RES_LIMIT
);
1783 * If memsw is finite and limits the amount of swap space
1784 * available to this memcg, return that limit.
1786 limit
= min(limit
, memsw
);
1792 static void mem_cgroup_out_of_memory(struct mem_cgroup
*memcg
, gfp_t gfp_mask
,
1795 struct mem_cgroup
*iter
;
1796 unsigned long chosen_points
= 0;
1797 unsigned long totalpages
;
1798 unsigned int points
= 0;
1799 struct task_struct
*chosen
= NULL
;
1802 * If current has a pending SIGKILL or is exiting, then automatically
1803 * select it. The goal is to allow it to allocate so that it may
1804 * quickly exit and free its memory.
1806 if (fatal_signal_pending(current
) || current
->flags
& PF_EXITING
) {
1807 set_thread_flag(TIF_MEMDIE
);
1811 check_panic_on_oom(CONSTRAINT_MEMCG
, gfp_mask
, order
, NULL
);
1812 totalpages
= mem_cgroup_get_limit(memcg
) >> PAGE_SHIFT
? : 1;
1813 for_each_mem_cgroup_tree(iter
, memcg
) {
1814 struct css_task_iter it
;
1815 struct task_struct
*task
;
1817 css_task_iter_start(&iter
->css
, &it
);
1818 while ((task
= css_task_iter_next(&it
))) {
1819 switch (oom_scan_process_thread(task
, totalpages
, NULL
,
1821 case OOM_SCAN_SELECT
:
1823 put_task_struct(chosen
);
1825 chosen_points
= ULONG_MAX
;
1826 get_task_struct(chosen
);
1828 case OOM_SCAN_CONTINUE
:
1830 case OOM_SCAN_ABORT
:
1831 css_task_iter_end(&it
);
1832 mem_cgroup_iter_break(memcg
, iter
);
1834 put_task_struct(chosen
);
1839 points
= oom_badness(task
, memcg
, NULL
, totalpages
);
1840 if (!points
|| points
< chosen_points
)
1842 /* Prefer thread group leaders for display purposes */
1843 if (points
== chosen_points
&&
1844 thread_group_leader(chosen
))
1848 put_task_struct(chosen
);
1850 chosen_points
= points
;
1851 get_task_struct(chosen
);
1853 css_task_iter_end(&it
);
1858 points
= chosen_points
* 1000 / totalpages
;
1859 oom_kill_process(chosen
, gfp_mask
, order
, points
, totalpages
, memcg
,
1860 NULL
, "Memory cgroup out of memory");
1863 static unsigned long mem_cgroup_reclaim(struct mem_cgroup
*memcg
,
1865 unsigned long flags
)
1867 unsigned long total
= 0;
1868 bool noswap
= false;
1871 if (flags
& MEM_CGROUP_RECLAIM_NOSWAP
)
1873 if (!(flags
& MEM_CGROUP_RECLAIM_SHRINK
) && memcg
->memsw_is_minimum
)
1876 for (loop
= 0; loop
< MEM_CGROUP_MAX_RECLAIM_LOOPS
; loop
++) {
1878 drain_all_stock_async(memcg
);
1879 total
+= try_to_free_mem_cgroup_pages(memcg
, gfp_mask
, noswap
);
1881 * Allow limit shrinkers, which are triggered directly
1882 * by userspace, to catch signals and stop reclaim
1883 * after minimal progress, regardless of the margin.
1885 if (total
&& (flags
& MEM_CGROUP_RECLAIM_SHRINK
))
1887 if (mem_cgroup_margin(memcg
))
1890 * If nothing was reclaimed after two attempts, there
1891 * may be no reclaimable pages in this hierarchy.
1900 * test_mem_cgroup_node_reclaimable
1901 * @memcg: the target memcg
1902 * @nid: the node ID to be checked.
1903 * @noswap : specify true here if the user wants flle only information.
1905 * This function returns whether the specified memcg contains any
1906 * reclaimable pages on a node. Returns true if there are any reclaimable
1907 * pages in the node.
1909 static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup
*memcg
,
1910 int nid
, bool noswap
)
1912 if (mem_cgroup_node_nr_lru_pages(memcg
, nid
, LRU_ALL_FILE
))
1914 if (noswap
|| !total_swap_pages
)
1916 if (mem_cgroup_node_nr_lru_pages(memcg
, nid
, LRU_ALL_ANON
))
1921 #if MAX_NUMNODES > 1
1924 * Always updating the nodemask is not very good - even if we have an empty
1925 * list or the wrong list here, we can start from some node and traverse all
1926 * nodes based on the zonelist. So update the list loosely once per 10 secs.
1929 static void mem_cgroup_may_update_nodemask(struct mem_cgroup
*memcg
)
1933 * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
1934 * pagein/pageout changes since the last update.
1936 if (!atomic_read(&memcg
->numainfo_events
))
1938 if (atomic_inc_return(&memcg
->numainfo_updating
) > 1)
1941 /* make a nodemask where this memcg uses memory from */
1942 memcg
->scan_nodes
= node_states
[N_MEMORY
];
1944 for_each_node_mask(nid
, node_states
[N_MEMORY
]) {
1946 if (!test_mem_cgroup_node_reclaimable(memcg
, nid
, false))
1947 node_clear(nid
, memcg
->scan_nodes
);
1950 atomic_set(&memcg
->numainfo_events
, 0);
1951 atomic_set(&memcg
->numainfo_updating
, 0);
1955 * Selecting a node where we start reclaim from. Because what we need is just
1956 * reducing usage counter, start from anywhere is O,K. Considering
1957 * memory reclaim from current node, there are pros. and cons.
1959 * Freeing memory from current node means freeing memory from a node which
1960 * we'll use or we've used. So, it may make LRU bad. And if several threads
1961 * hit limits, it will see a contention on a node. But freeing from remote
1962 * node means more costs for memory reclaim because of memory latency.
1964 * Now, we use round-robin. Better algorithm is welcomed.
1966 int mem_cgroup_select_victim_node(struct mem_cgroup
*memcg
)
1970 mem_cgroup_may_update_nodemask(memcg
);
1971 node
= memcg
->last_scanned_node
;
1973 node
= next_node(node
, memcg
->scan_nodes
);
1974 if (node
== MAX_NUMNODES
)
1975 node
= first_node(memcg
->scan_nodes
);
1977 * We call this when we hit limit, not when pages are added to LRU.
1978 * No LRU may hold pages because all pages are UNEVICTABLE or
1979 * memcg is too small and all pages are not on LRU. In that case,
1980 * we use curret node.
1982 if (unlikely(node
== MAX_NUMNODES
))
1983 node
= numa_node_id();
1985 memcg
->last_scanned_node
= node
;
1990 * Check all nodes whether it contains reclaimable pages or not.
1991 * For quick scan, we make use of scan_nodes. This will allow us to skip
1992 * unused nodes. But scan_nodes is lazily updated and may not cotain
1993 * enough new information. We need to do double check.
1995 static bool mem_cgroup_reclaimable(struct mem_cgroup
*memcg
, bool noswap
)
2000 * quick check...making use of scan_node.
2001 * We can skip unused nodes.
2003 if (!nodes_empty(memcg
->scan_nodes
)) {
2004 for (nid
= first_node(memcg
->scan_nodes
);
2006 nid
= next_node(nid
, memcg
->scan_nodes
)) {
2008 if (test_mem_cgroup_node_reclaimable(memcg
, nid
, noswap
))
2013 * Check rest of nodes.
2015 for_each_node_state(nid
, N_MEMORY
) {
2016 if (node_isset(nid
, memcg
->scan_nodes
))
2018 if (test_mem_cgroup_node_reclaimable(memcg
, nid
, noswap
))
2025 int mem_cgroup_select_victim_node(struct mem_cgroup
*memcg
)
2030 static bool mem_cgroup_reclaimable(struct mem_cgroup
*memcg
, bool noswap
)
2032 return test_mem_cgroup_node_reclaimable(memcg
, 0, noswap
);
2036 static int mem_cgroup_soft_reclaim(struct mem_cgroup
*root_memcg
,
2039 unsigned long *total_scanned
)
2041 struct mem_cgroup
*victim
= NULL
;
2044 unsigned long excess
;
2045 unsigned long nr_scanned
;
2046 struct mem_cgroup_reclaim_cookie reclaim
= {
2051 excess
= res_counter_soft_limit_excess(&root_memcg
->res
) >> PAGE_SHIFT
;
2054 victim
= mem_cgroup_iter(root_memcg
, victim
, &reclaim
);
2059 * If we have not been able to reclaim
2060 * anything, it might because there are
2061 * no reclaimable pages under this hierarchy
2066 * We want to do more targeted reclaim.
2067 * excess >> 2 is not to excessive so as to
2068 * reclaim too much, nor too less that we keep
2069 * coming back to reclaim from this cgroup
2071 if (total
>= (excess
>> 2) ||
2072 (loop
> MEM_CGROUP_MAX_RECLAIM_LOOPS
))
2077 if (!mem_cgroup_reclaimable(victim
, false))
2079 total
+= mem_cgroup_shrink_node_zone(victim
, gfp_mask
, false,
2081 *total_scanned
+= nr_scanned
;
2082 if (!res_counter_soft_limit_excess(&root_memcg
->res
))
2085 mem_cgroup_iter_break(root_memcg
, victim
);
2089 #ifdef CONFIG_LOCKDEP
2090 static struct lockdep_map memcg_oom_lock_dep_map
= {
2091 .name
= "memcg_oom_lock",
2095 static DEFINE_SPINLOCK(memcg_oom_lock
);
2098 * Check OOM-Killer is already running under our hierarchy.
2099 * If someone is running, return false.
2101 static bool mem_cgroup_oom_trylock(struct mem_cgroup
*memcg
)
2103 struct mem_cgroup
*iter
, *failed
= NULL
;
2105 spin_lock(&memcg_oom_lock
);
2107 for_each_mem_cgroup_tree(iter
, memcg
) {
2108 if (iter
->oom_lock
) {
2110 * this subtree of our hierarchy is already locked
2111 * so we cannot give a lock.
2114 mem_cgroup_iter_break(memcg
, iter
);
2117 iter
->oom_lock
= true;
2122 * OK, we failed to lock the whole subtree so we have
2123 * to clean up what we set up to the failing subtree
2125 for_each_mem_cgroup_tree(iter
, memcg
) {
2126 if (iter
== failed
) {
2127 mem_cgroup_iter_break(memcg
, iter
);
2130 iter
->oom_lock
= false;
2133 mutex_acquire(&memcg_oom_lock_dep_map
, 0, 1, _RET_IP_
);
2135 spin_unlock(&memcg_oom_lock
);
2140 static void mem_cgroup_oom_unlock(struct mem_cgroup
*memcg
)
2142 struct mem_cgroup
*iter
;
2144 spin_lock(&memcg_oom_lock
);
2145 mutex_release(&memcg_oom_lock_dep_map
, 1, _RET_IP_
);
2146 for_each_mem_cgroup_tree(iter
, memcg
)
2147 iter
->oom_lock
= false;
2148 spin_unlock(&memcg_oom_lock
);
2151 static void mem_cgroup_mark_under_oom(struct mem_cgroup
*memcg
)
2153 struct mem_cgroup
*iter
;
2155 for_each_mem_cgroup_tree(iter
, memcg
)
2156 atomic_inc(&iter
->under_oom
);
2159 static void mem_cgroup_unmark_under_oom(struct mem_cgroup
*memcg
)
2161 struct mem_cgroup
*iter
;
2164 * When a new child is created while the hierarchy is under oom,
2165 * mem_cgroup_oom_lock() may not be called. We have to use
2166 * atomic_add_unless() here.
2168 for_each_mem_cgroup_tree(iter
, memcg
)
2169 atomic_add_unless(&iter
->under_oom
, -1, 0);
2172 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq
);
2174 struct oom_wait_info
{
2175 struct mem_cgroup
*memcg
;
2179 static int memcg_oom_wake_function(wait_queue_t
*wait
,
2180 unsigned mode
, int sync
, void *arg
)
2182 struct mem_cgroup
*wake_memcg
= (struct mem_cgroup
*)arg
;
2183 struct mem_cgroup
*oom_wait_memcg
;
2184 struct oom_wait_info
*oom_wait_info
;
2186 oom_wait_info
= container_of(wait
, struct oom_wait_info
, wait
);
2187 oom_wait_memcg
= oom_wait_info
->memcg
;
2190 * Both of oom_wait_info->memcg and wake_memcg are stable under us.
2191 * Then we can use css_is_ancestor without taking care of RCU.
2193 if (!mem_cgroup_same_or_subtree(oom_wait_memcg
, wake_memcg
)
2194 && !mem_cgroup_same_or_subtree(wake_memcg
, oom_wait_memcg
))
2196 return autoremove_wake_function(wait
, mode
, sync
, arg
);
2199 static void memcg_wakeup_oom(struct mem_cgroup
*memcg
)
2201 atomic_inc(&memcg
->oom_wakeups
);
2202 /* for filtering, pass "memcg" as argument. */
2203 __wake_up(&memcg_oom_waitq
, TASK_NORMAL
, 0, memcg
);
2206 static void memcg_oom_recover(struct mem_cgroup
*memcg
)
2208 if (memcg
&& atomic_read(&memcg
->under_oom
))
2209 memcg_wakeup_oom(memcg
);
2212 static void mem_cgroup_oom(struct mem_cgroup
*memcg
, gfp_t mask
, int order
)
2214 if (!current
->memcg_oom
.may_oom
)
2217 * We are in the middle of the charge context here, so we
2218 * don't want to block when potentially sitting on a callstack
2219 * that holds all kinds of filesystem and mm locks.
2221 * Also, the caller may handle a failed allocation gracefully
2222 * (like optional page cache readahead) and so an OOM killer
2223 * invocation might not even be necessary.
2225 * That's why we don't do anything here except remember the
2226 * OOM context and then deal with it at the end of the page
2227 * fault when the stack is unwound, the locks are released,
2228 * and when we know whether the fault was overall successful.
2230 css_get(&memcg
->css
);
2231 current
->memcg_oom
.memcg
= memcg
;
2232 current
->memcg_oom
.gfp_mask
= mask
;
2233 current
->memcg_oom
.order
= order
;
2237 * mem_cgroup_oom_synchronize - complete memcg OOM handling
2238 * @handle: actually kill/wait or just clean up the OOM state
2240 * This has to be called at the end of a page fault if the memcg OOM
2241 * handler was enabled.
2243 * Memcg supports userspace OOM handling where failed allocations must
2244 * sleep on a waitqueue until the userspace task resolves the
2245 * situation. Sleeping directly in the charge context with all kinds
2246 * of locks held is not a good idea, instead we remember an OOM state
2247 * in the task and mem_cgroup_oom_synchronize() has to be called at
2248 * the end of the page fault to complete the OOM handling.
2250 * Returns %true if an ongoing memcg OOM situation was detected and
2251 * completed, %false otherwise.
2253 bool mem_cgroup_oom_synchronize(bool handle
)
2255 struct mem_cgroup
*memcg
= current
->memcg_oom
.memcg
;
2256 struct oom_wait_info owait
;
2259 /* OOM is global, do not handle */
2266 owait
.memcg
= memcg
;
2267 owait
.wait
.flags
= 0;
2268 owait
.wait
.func
= memcg_oom_wake_function
;
2269 owait
.wait
.private = current
;
2270 INIT_LIST_HEAD(&owait
.wait
.task_list
);
2272 prepare_to_wait(&memcg_oom_waitq
, &owait
.wait
, TASK_KILLABLE
);
2273 mem_cgroup_mark_under_oom(memcg
);
2275 locked
= mem_cgroup_oom_trylock(memcg
);
2278 mem_cgroup_oom_notify(memcg
);
2280 if (locked
&& !memcg
->oom_kill_disable
) {
2281 mem_cgroup_unmark_under_oom(memcg
);
2282 finish_wait(&memcg_oom_waitq
, &owait
.wait
);
2283 mem_cgroup_out_of_memory(memcg
, current
->memcg_oom
.gfp_mask
,
2284 current
->memcg_oom
.order
);
2287 mem_cgroup_unmark_under_oom(memcg
);
2288 finish_wait(&memcg_oom_waitq
, &owait
.wait
);
2292 mem_cgroup_oom_unlock(memcg
);
2294 * There is no guarantee that an OOM-lock contender
2295 * sees the wakeups triggered by the OOM kill
2296 * uncharges. Wake any sleepers explicitely.
2298 memcg_oom_recover(memcg
);
2301 current
->memcg_oom
.memcg
= NULL
;
2302 css_put(&memcg
->css
);
2307 * Currently used to update mapped file statistics, but the routine can be
2308 * generalized to update other statistics as well.
2310 * Notes: Race condition
2312 * We usually use page_cgroup_lock() for accessing page_cgroup member but
2313 * it tends to be costly. But considering some conditions, we doesn't need
2314 * to do so _always_.
2316 * Considering "charge", lock_page_cgroup() is not required because all
2317 * file-stat operations happen after a page is attached to radix-tree. There
2318 * are no race with "charge".
2320 * Considering "uncharge", we know that memcg doesn't clear pc->mem_cgroup
2321 * at "uncharge" intentionally. So, we always see valid pc->mem_cgroup even
2322 * if there are race with "uncharge". Statistics itself is properly handled
2325 * Considering "move", this is an only case we see a race. To make the race
2326 * small, we check mm->moving_account and detect there are possibility of race
2327 * If there is, we take a lock.
2330 void __mem_cgroup_begin_update_page_stat(struct page
*page
,
2331 bool *locked
, unsigned long *flags
)
2333 struct mem_cgroup
*memcg
;
2334 struct page_cgroup
*pc
;
2336 pc
= lookup_page_cgroup(page
);
2338 memcg
= pc
->mem_cgroup
;
2339 if (unlikely(!memcg
|| !PageCgroupUsed(pc
)))
2342 * If this memory cgroup is not under account moving, we don't
2343 * need to take move_lock_mem_cgroup(). Because we already hold
2344 * rcu_read_lock(), any calls to move_account will be delayed until
2345 * rcu_read_unlock() if mem_cgroup_stolen() == true.
2347 if (!mem_cgroup_stolen(memcg
))
2350 move_lock_mem_cgroup(memcg
, flags
);
2351 if (memcg
!= pc
->mem_cgroup
|| !PageCgroupUsed(pc
)) {
2352 move_unlock_mem_cgroup(memcg
, flags
);
2358 void __mem_cgroup_end_update_page_stat(struct page
*page
, unsigned long *flags
)
2360 struct page_cgroup
*pc
= lookup_page_cgroup(page
);
2363 * It's guaranteed that pc->mem_cgroup never changes while
2364 * lock is held because a routine modifies pc->mem_cgroup
2365 * should take move_lock_mem_cgroup().
2367 move_unlock_mem_cgroup(pc
->mem_cgroup
, flags
);
2370 void mem_cgroup_update_page_stat(struct page
*page
,
2371 enum mem_cgroup_stat_index idx
, int val
)
2373 struct mem_cgroup
*memcg
;
2374 struct page_cgroup
*pc
= lookup_page_cgroup(page
);
2375 unsigned long uninitialized_var(flags
);
2377 if (mem_cgroup_disabled())
2380 VM_BUG_ON(!rcu_read_lock_held());
2381 memcg
= pc
->mem_cgroup
;
2382 if (unlikely(!memcg
|| !PageCgroupUsed(pc
)))
2385 this_cpu_add(memcg
->stat
->count
[idx
], val
);
2389 * size of first charge trial. "32" comes from vmscan.c's magic value.
2390 * TODO: maybe necessary to use big numbers in big irons.
2392 #define CHARGE_BATCH 32U
2393 struct memcg_stock_pcp
{
2394 struct mem_cgroup
*cached
; /* this never be root cgroup */
2395 unsigned int nr_pages
;
2396 struct work_struct work
;
2397 unsigned long flags
;
2398 #define FLUSHING_CACHED_CHARGE 0
2400 static DEFINE_PER_CPU(struct memcg_stock_pcp
, memcg_stock
);
2401 static DEFINE_MUTEX(percpu_charge_mutex
);
2404 * consume_stock: Try to consume stocked charge on this cpu.
2405 * @memcg: memcg to consume from.
2406 * @nr_pages: how many pages to charge.
2408 * The charges will only happen if @memcg matches the current cpu's memcg
2409 * stock, and at least @nr_pages are available in that stock. Failure to
2410 * service an allocation will refill the stock.
2412 * returns true if successful, false otherwise.
2414 static bool consume_stock(struct mem_cgroup
*memcg
, unsigned int nr_pages
)
2416 struct memcg_stock_pcp
*stock
;
2419 if (nr_pages
> CHARGE_BATCH
)
2422 stock
= &get_cpu_var(memcg_stock
);
2423 if (memcg
== stock
->cached
&& stock
->nr_pages
>= nr_pages
)
2424 stock
->nr_pages
-= nr_pages
;
2425 else /* need to call res_counter_charge */
2427 put_cpu_var(memcg_stock
);
2432 * Returns stocks cached in percpu to res_counter and reset cached information.
2434 static void drain_stock(struct memcg_stock_pcp
*stock
)
2436 struct mem_cgroup
*old
= stock
->cached
;
2438 if (stock
->nr_pages
) {
2439 unsigned long bytes
= stock
->nr_pages
* PAGE_SIZE
;
2441 res_counter_uncharge(&old
->res
, bytes
);
2442 if (do_swap_account
)
2443 res_counter_uncharge(&old
->memsw
, bytes
);
2444 stock
->nr_pages
= 0;
2446 stock
->cached
= NULL
;
2450 * This must be called under preempt disabled or must be called by
2451 * a thread which is pinned to local cpu.
2453 static void drain_local_stock(struct work_struct
*dummy
)
2455 struct memcg_stock_pcp
*stock
= &__get_cpu_var(memcg_stock
);
2457 clear_bit(FLUSHING_CACHED_CHARGE
, &stock
->flags
);
2460 static void __init
memcg_stock_init(void)
2464 for_each_possible_cpu(cpu
) {
2465 struct memcg_stock_pcp
*stock
=
2466 &per_cpu(memcg_stock
, cpu
);
2467 INIT_WORK(&stock
->work
, drain_local_stock
);
2472 * Cache charges(val) which is from res_counter, to local per_cpu area.
2473 * This will be consumed by consume_stock() function, later.
2475 static void refill_stock(struct mem_cgroup
*memcg
, unsigned int nr_pages
)
2477 struct memcg_stock_pcp
*stock
= &get_cpu_var(memcg_stock
);
2479 if (stock
->cached
!= memcg
) { /* reset if necessary */
2481 stock
->cached
= memcg
;
2483 stock
->nr_pages
+= nr_pages
;
2484 put_cpu_var(memcg_stock
);
2488 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2489 * of the hierarchy under it. sync flag says whether we should block
2490 * until the work is done.
2492 static void drain_all_stock(struct mem_cgroup
*root_memcg
, bool sync
)
2496 /* Notify other cpus that system-wide "drain" is running */
2499 for_each_online_cpu(cpu
) {
2500 struct memcg_stock_pcp
*stock
= &per_cpu(memcg_stock
, cpu
);
2501 struct mem_cgroup
*memcg
;
2503 memcg
= stock
->cached
;
2504 if (!memcg
|| !stock
->nr_pages
)
2506 if (!mem_cgroup_same_or_subtree(root_memcg
, memcg
))
2508 if (!test_and_set_bit(FLUSHING_CACHED_CHARGE
, &stock
->flags
)) {
2510 drain_local_stock(&stock
->work
);
2512 schedule_work_on(cpu
, &stock
->work
);
2520 for_each_online_cpu(cpu
) {
2521 struct memcg_stock_pcp
*stock
= &per_cpu(memcg_stock
, cpu
);
2522 if (test_bit(FLUSHING_CACHED_CHARGE
, &stock
->flags
))
2523 flush_work(&stock
->work
);
2530 * Tries to drain stocked charges in other cpus. This function is asynchronous
2531 * and just put a work per cpu for draining localy on each cpu. Caller can
2532 * expects some charges will be back to res_counter later but cannot wait for
2535 static void drain_all_stock_async(struct mem_cgroup
*root_memcg
)
2538 * If someone calls draining, avoid adding more kworker runs.
2540 if (!mutex_trylock(&percpu_charge_mutex
))
2542 drain_all_stock(root_memcg
, false);
2543 mutex_unlock(&percpu_charge_mutex
);
2546 /* This is a synchronous drain interface. */
2547 static void drain_all_stock_sync(struct mem_cgroup
*root_memcg
)
2549 /* called when force_empty is called */
2550 mutex_lock(&percpu_charge_mutex
);
2551 drain_all_stock(root_memcg
, true);
2552 mutex_unlock(&percpu_charge_mutex
);
2556 * This function drains percpu counter value from DEAD cpu and
2557 * move it to local cpu. Note that this function can be preempted.
2559 static void mem_cgroup_drain_pcp_counter(struct mem_cgroup
*memcg
, int cpu
)
2563 spin_lock(&memcg
->pcp_counter_lock
);
2564 for (i
= 0; i
< MEM_CGROUP_STAT_NSTATS
; i
++) {
2565 long x
= per_cpu(memcg
->stat
->count
[i
], cpu
);
2567 per_cpu(memcg
->stat
->count
[i
], cpu
) = 0;
2568 memcg
->nocpu_base
.count
[i
] += x
;
2570 for (i
= 0; i
< MEM_CGROUP_EVENTS_NSTATS
; i
++) {
2571 unsigned long x
= per_cpu(memcg
->stat
->events
[i
], cpu
);
2573 per_cpu(memcg
->stat
->events
[i
], cpu
) = 0;
2574 memcg
->nocpu_base
.events
[i
] += x
;
2576 spin_unlock(&memcg
->pcp_counter_lock
);
2579 static int memcg_cpu_hotplug_callback(struct notifier_block
*nb
,
2580 unsigned long action
,
2583 int cpu
= (unsigned long)hcpu
;
2584 struct memcg_stock_pcp
*stock
;
2585 struct mem_cgroup
*iter
;
2587 if (action
== CPU_ONLINE
)
2590 if (action
!= CPU_DEAD
&& action
!= CPU_DEAD_FROZEN
)
2593 for_each_mem_cgroup(iter
)
2594 mem_cgroup_drain_pcp_counter(iter
, cpu
);
2596 stock
= &per_cpu(memcg_stock
, cpu
);
2602 /* See __mem_cgroup_try_charge() for details */
2604 CHARGE_OK
, /* success */
2605 CHARGE_RETRY
, /* need to retry but retry is not bad */
2606 CHARGE_NOMEM
, /* we can't do more. return -ENOMEM */
2607 CHARGE_WOULDBLOCK
, /* GFP_WAIT wasn't set and no enough res. */
2610 static int mem_cgroup_do_charge(struct mem_cgroup
*memcg
, gfp_t gfp_mask
,
2611 unsigned int nr_pages
, unsigned int min_pages
,
2614 unsigned long csize
= nr_pages
* PAGE_SIZE
;
2615 struct mem_cgroup
*mem_over_limit
;
2616 struct res_counter
*fail_res
;
2617 unsigned long flags
= 0;
2620 ret
= res_counter_charge(&memcg
->res
, csize
, &fail_res
);
2623 if (!do_swap_account
)
2625 ret
= res_counter_charge(&memcg
->memsw
, csize
, &fail_res
);
2629 res_counter_uncharge(&memcg
->res
, csize
);
2630 mem_over_limit
= mem_cgroup_from_res_counter(fail_res
, memsw
);
2631 flags
|= MEM_CGROUP_RECLAIM_NOSWAP
;
2633 mem_over_limit
= mem_cgroup_from_res_counter(fail_res
, res
);
2635 * Never reclaim on behalf of optional batching, retry with a
2636 * single page instead.
2638 if (nr_pages
> min_pages
)
2639 return CHARGE_RETRY
;
2641 if (!(gfp_mask
& __GFP_WAIT
))
2642 return CHARGE_WOULDBLOCK
;
2644 if (gfp_mask
& __GFP_NORETRY
)
2645 return CHARGE_NOMEM
;
2647 ret
= mem_cgroup_reclaim(mem_over_limit
, gfp_mask
, flags
);
2648 if (mem_cgroup_margin(mem_over_limit
) >= nr_pages
)
2649 return CHARGE_RETRY
;
2651 * Even though the limit is exceeded at this point, reclaim
2652 * may have been able to free some pages. Retry the charge
2653 * before killing the task.
2655 * Only for regular pages, though: huge pages are rather
2656 * unlikely to succeed so close to the limit, and we fall back
2657 * to regular pages anyway in case of failure.
2659 if (nr_pages
<= (1 << PAGE_ALLOC_COSTLY_ORDER
) && ret
)
2660 return CHARGE_RETRY
;
2663 * At task move, charge accounts can be doubly counted. So, it's
2664 * better to wait until the end of task_move if something is going on.
2666 if (mem_cgroup_wait_acct_move(mem_over_limit
))
2667 return CHARGE_RETRY
;
2670 mem_cgroup_oom(mem_over_limit
, gfp_mask
, get_order(csize
));
2672 return CHARGE_NOMEM
;
2676 * __mem_cgroup_try_charge() does
2677 * 1. detect memcg to be charged against from passed *mm and *ptr,
2678 * 2. update res_counter
2679 * 3. call memory reclaim if necessary.
2681 * In some special case, if the task is fatal, fatal_signal_pending() or
2682 * has TIF_MEMDIE, this function returns -EINTR while writing root_mem_cgroup
2683 * to *ptr. There are two reasons for this. 1: fatal threads should quit as soon
2684 * as possible without any hazards. 2: all pages should have a valid
2685 * pc->mem_cgroup. If mm is NULL and the caller doesn't pass a valid memcg
2686 * pointer, that is treated as a charge to root_mem_cgroup.
2688 * So __mem_cgroup_try_charge() will return
2689 * 0 ... on success, filling *ptr with a valid memcg pointer.
2690 * -ENOMEM ... charge failure because of resource limits.
2691 * -EINTR ... if thread is fatal. *ptr is filled with root_mem_cgroup.
2693 * Unlike the exported interface, an "oom" parameter is added. if oom==true,
2694 * the oom-killer can be invoked.
2696 static int __mem_cgroup_try_charge(struct mm_struct
*mm
,
2698 unsigned int nr_pages
,
2699 struct mem_cgroup
**ptr
,
2702 unsigned int batch
= max(CHARGE_BATCH
, nr_pages
);
2703 int nr_oom_retries
= MEM_CGROUP_RECLAIM_RETRIES
;
2704 struct mem_cgroup
*memcg
= NULL
;
2708 * Unlike gloval-vm's OOM-kill, we're not in memory shortage
2709 * in system level. So, allow to go ahead dying process in addition to
2712 if (unlikely(test_thread_flag(TIF_MEMDIE
)
2713 || fatal_signal_pending(current
)))
2716 if (unlikely(task_in_memcg_oom(current
)))
2719 if (gfp_mask
& __GFP_NOFAIL
)
2723 * We always charge the cgroup the mm_struct belongs to.
2724 * The mm_struct's mem_cgroup changes on task migration if the
2725 * thread group leader migrates. It's possible that mm is not
2726 * set, if so charge the root memcg (happens for pagecache usage).
2729 *ptr
= root_mem_cgroup
;
2731 if (*ptr
) { /* css should be a valid one */
2733 if (mem_cgroup_is_root(memcg
))
2735 if (consume_stock(memcg
, nr_pages
))
2737 css_get(&memcg
->css
);
2739 struct task_struct
*p
;
2742 p
= rcu_dereference(mm
->owner
);
2744 * Because we don't have task_lock(), "p" can exit.
2745 * In that case, "memcg" can point to root or p can be NULL with
2746 * race with swapoff. Then, we have small risk of mis-accouning.
2747 * But such kind of mis-account by race always happens because
2748 * we don't have cgroup_mutex(). It's overkill and we allo that
2750 * (*) swapoff at el will charge against mm-struct not against
2751 * task-struct. So, mm->owner can be NULL.
2753 memcg
= mem_cgroup_from_task(p
);
2755 memcg
= root_mem_cgroup
;
2756 if (mem_cgroup_is_root(memcg
)) {
2760 if (consume_stock(memcg
, nr_pages
)) {
2762 * It seems dagerous to access memcg without css_get().
2763 * But considering how consume_stok works, it's not
2764 * necessary. If consume_stock success, some charges
2765 * from this memcg are cached on this cpu. So, we
2766 * don't need to call css_get()/css_tryget() before
2767 * calling consume_stock().
2772 /* after here, we may be blocked. we need to get refcnt */
2773 if (!css_tryget(&memcg
->css
)) {
2781 bool invoke_oom
= oom
&& !nr_oom_retries
;
2783 /* If killed, bypass charge */
2784 if (fatal_signal_pending(current
)) {
2785 css_put(&memcg
->css
);
2789 ret
= mem_cgroup_do_charge(memcg
, gfp_mask
, batch
,
2790 nr_pages
, invoke_oom
);
2794 case CHARGE_RETRY
: /* not in OOM situation but retry */
2796 css_put(&memcg
->css
);
2799 case CHARGE_WOULDBLOCK
: /* !__GFP_WAIT */
2800 css_put(&memcg
->css
);
2802 case CHARGE_NOMEM
: /* OOM routine works */
2803 if (!oom
|| invoke_oom
) {
2804 css_put(&memcg
->css
);
2810 } while (ret
!= CHARGE_OK
);
2812 if (batch
> nr_pages
)
2813 refill_stock(memcg
, batch
- nr_pages
);
2814 css_put(&memcg
->css
);
2819 if (!(gfp_mask
& __GFP_NOFAIL
)) {
2824 *ptr
= root_mem_cgroup
;
2829 * Somemtimes we have to undo a charge we got by try_charge().
2830 * This function is for that and do uncharge, put css's refcnt.
2831 * gotten by try_charge().
2833 static void __mem_cgroup_cancel_charge(struct mem_cgroup
*memcg
,
2834 unsigned int nr_pages
)
2836 if (!mem_cgroup_is_root(memcg
)) {
2837 unsigned long bytes
= nr_pages
* PAGE_SIZE
;
2839 res_counter_uncharge(&memcg
->res
, bytes
);
2840 if (do_swap_account
)
2841 res_counter_uncharge(&memcg
->memsw
, bytes
);
2846 * Cancel chrages in this cgroup....doesn't propagate to parent cgroup.
2847 * This is useful when moving usage to parent cgroup.
2849 static void __mem_cgroup_cancel_local_charge(struct mem_cgroup
*memcg
,
2850 unsigned int nr_pages
)
2852 unsigned long bytes
= nr_pages
* PAGE_SIZE
;
2854 if (mem_cgroup_is_root(memcg
))
2857 res_counter_uncharge_until(&memcg
->res
, memcg
->res
.parent
, bytes
);
2858 if (do_swap_account
)
2859 res_counter_uncharge_until(&memcg
->memsw
,
2860 memcg
->memsw
.parent
, bytes
);
2864 * A helper function to get mem_cgroup from ID. must be called under
2865 * rcu_read_lock(). The caller is responsible for calling css_tryget if
2866 * the mem_cgroup is used for charging. (dropping refcnt from swap can be
2867 * called against removed memcg.)
2869 static struct mem_cgroup
*mem_cgroup_lookup(unsigned short id
)
2871 struct cgroup_subsys_state
*css
;
2873 /* ID 0 is unused ID */
2876 css
= css_lookup(&mem_cgroup_subsys
, id
);
2879 return mem_cgroup_from_css(css
);
2882 struct mem_cgroup
*try_get_mem_cgroup_from_page(struct page
*page
)
2884 struct mem_cgroup
*memcg
= NULL
;
2885 struct page_cgroup
*pc
;
2889 VM_BUG_ON(!PageLocked(page
));
2891 pc
= lookup_page_cgroup(page
);
2892 lock_page_cgroup(pc
);
2893 if (PageCgroupUsed(pc
)) {
2894 memcg
= pc
->mem_cgroup
;
2895 if (memcg
&& !css_tryget(&memcg
->css
))
2897 } else if (PageSwapCache(page
)) {
2898 ent
.val
= page_private(page
);
2899 id
= lookup_swap_cgroup_id(ent
);
2901 memcg
= mem_cgroup_lookup(id
);
2902 if (memcg
&& !css_tryget(&memcg
->css
))
2906 unlock_page_cgroup(pc
);
2910 static void __mem_cgroup_commit_charge(struct mem_cgroup
*memcg
,
2912 unsigned int nr_pages
,
2913 enum charge_type ctype
,
2916 struct page_cgroup
*pc
= lookup_page_cgroup(page
);
2917 struct zone
*uninitialized_var(zone
);
2918 struct lruvec
*lruvec
;
2919 bool was_on_lru
= false;
2922 lock_page_cgroup(pc
);
2923 VM_BUG_ON(PageCgroupUsed(pc
));
2925 * we don't need page_cgroup_lock about tail pages, becase they are not
2926 * accessed by any other context at this point.
2930 * In some cases, SwapCache and FUSE(splice_buf->radixtree), the page
2931 * may already be on some other mem_cgroup's LRU. Take care of it.
2934 zone
= page_zone(page
);
2935 spin_lock_irq(&zone
->lru_lock
);
2936 if (PageLRU(page
)) {
2937 lruvec
= mem_cgroup_zone_lruvec(zone
, pc
->mem_cgroup
);
2939 del_page_from_lru_list(page
, lruvec
, page_lru(page
));
2944 pc
->mem_cgroup
= memcg
;
2946 * We access a page_cgroup asynchronously without lock_page_cgroup().
2947 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
2948 * is accessed after testing USED bit. To make pc->mem_cgroup visible
2949 * before USED bit, we need memory barrier here.
2950 * See mem_cgroup_add_lru_list(), etc.
2953 SetPageCgroupUsed(pc
);
2957 lruvec
= mem_cgroup_zone_lruvec(zone
, pc
->mem_cgroup
);
2958 VM_BUG_ON(PageLRU(page
));
2960 add_page_to_lru_list(page
, lruvec
, page_lru(page
));
2962 spin_unlock_irq(&zone
->lru_lock
);
2965 if (ctype
== MEM_CGROUP_CHARGE_TYPE_ANON
)
2970 mem_cgroup_charge_statistics(memcg
, page
, anon
, nr_pages
);
2971 unlock_page_cgroup(pc
);
2974 * "charge_statistics" updated event counter. Then, check it.
2975 * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
2976 * if they exceeds softlimit.
2978 memcg_check_events(memcg
, page
);
2981 static DEFINE_MUTEX(set_limit_mutex
);
2983 #ifdef CONFIG_MEMCG_KMEM
2984 static inline bool memcg_can_account_kmem(struct mem_cgroup
*memcg
)
2986 return !mem_cgroup_disabled() && !mem_cgroup_is_root(memcg
) &&
2987 (memcg
->kmem_account_flags
& KMEM_ACCOUNTED_MASK
);
2991 * This is a bit cumbersome, but it is rarely used and avoids a backpointer
2992 * in the memcg_cache_params struct.
2994 static struct kmem_cache
*memcg_params_to_cache(struct memcg_cache_params
*p
)
2996 struct kmem_cache
*cachep
;
2998 VM_BUG_ON(p
->is_root_cache
);
2999 cachep
= p
->root_cache
;
3000 return cachep
->memcg_params
->memcg_caches
[memcg_cache_id(p
->memcg
)];
3003 #ifdef CONFIG_SLABINFO
3004 static int mem_cgroup_slabinfo_read(struct cgroup_subsys_state
*css
,
3005 struct cftype
*cft
, struct seq_file
*m
)
3007 struct mem_cgroup
*memcg
= mem_cgroup_from_css(css
);
3008 struct memcg_cache_params
*params
;
3010 if (!memcg_can_account_kmem(memcg
))
3013 print_slabinfo_header(m
);
3015 mutex_lock(&memcg
->slab_caches_mutex
);
3016 list_for_each_entry(params
, &memcg
->memcg_slab_caches
, list
)
3017 cache_show(memcg_params_to_cache(params
), m
);
3018 mutex_unlock(&memcg
->slab_caches_mutex
);
3024 static int memcg_charge_kmem(struct mem_cgroup
*memcg
, gfp_t gfp
, u64 size
)
3026 struct res_counter
*fail_res
;
3027 struct mem_cgroup
*_memcg
;
3031 ret
= res_counter_charge(&memcg
->kmem
, size
, &fail_res
);
3036 * Conditions under which we can wait for the oom_killer. Those are
3037 * the same conditions tested by the core page allocator
3039 may_oom
= (gfp
& __GFP_FS
) && !(gfp
& __GFP_NORETRY
);
3042 ret
= __mem_cgroup_try_charge(NULL
, gfp
, size
>> PAGE_SHIFT
,
3045 if (ret
== -EINTR
) {
3047 * __mem_cgroup_try_charge() chosed to bypass to root due to
3048 * OOM kill or fatal signal. Since our only options are to
3049 * either fail the allocation or charge it to this cgroup, do
3050 * it as a temporary condition. But we can't fail. From a
3051 * kmem/slab perspective, the cache has already been selected,
3052 * by mem_cgroup_kmem_get_cache(), so it is too late to change
3055 * This condition will only trigger if the task entered
3056 * memcg_charge_kmem in a sane state, but was OOM-killed during
3057 * __mem_cgroup_try_charge() above. Tasks that were already
3058 * dying when the allocation triggers should have been already
3059 * directed to the root cgroup in memcontrol.h
3061 res_counter_charge_nofail(&memcg
->res
, size
, &fail_res
);
3062 if (do_swap_account
)
3063 res_counter_charge_nofail(&memcg
->memsw
, size
,
3067 res_counter_uncharge(&memcg
->kmem
, size
);
3072 static void memcg_uncharge_kmem(struct mem_cgroup
*memcg
, u64 size
)
3074 res_counter_uncharge(&memcg
->res
, size
);
3075 if (do_swap_account
)
3076 res_counter_uncharge(&memcg
->memsw
, size
);
3079 if (res_counter_uncharge(&memcg
->kmem
, size
))
3083 * Releases a reference taken in kmem_cgroup_css_offline in case
3084 * this last uncharge is racing with the offlining code or it is
3085 * outliving the memcg existence.
3087 * The memory barrier imposed by test&clear is paired with the
3088 * explicit one in memcg_kmem_mark_dead().
3090 if (memcg_kmem_test_and_clear_dead(memcg
))
3091 css_put(&memcg
->css
);
3094 void memcg_cache_list_add(struct mem_cgroup
*memcg
, struct kmem_cache
*cachep
)
3099 mutex_lock(&memcg
->slab_caches_mutex
);
3100 list_add(&cachep
->memcg_params
->list
, &memcg
->memcg_slab_caches
);
3101 mutex_unlock(&memcg
->slab_caches_mutex
);
3105 * helper for acessing a memcg's index. It will be used as an index in the
3106 * child cache array in kmem_cache, and also to derive its name. This function
3107 * will return -1 when this is not a kmem-limited memcg.
3109 int memcg_cache_id(struct mem_cgroup
*memcg
)
3111 return memcg
? memcg
->kmemcg_id
: -1;
3115 * This ends up being protected by the set_limit mutex, during normal
3116 * operation, because that is its main call site.
3118 * But when we create a new cache, we can call this as well if its parent
3119 * is kmem-limited. That will have to hold set_limit_mutex as well.
3121 int memcg_update_cache_sizes(struct mem_cgroup
*memcg
)
3125 num
= ida_simple_get(&kmem_limited_groups
,
3126 0, MEMCG_CACHES_MAX_SIZE
, GFP_KERNEL
);
3130 * After this point, kmem_accounted (that we test atomically in
3131 * the beginning of this conditional), is no longer 0. This
3132 * guarantees only one process will set the following boolean
3133 * to true. We don't need test_and_set because we're protected
3134 * by the set_limit_mutex anyway.
3136 memcg_kmem_set_activated(memcg
);
3138 ret
= memcg_update_all_caches(num
+1);
3140 ida_simple_remove(&kmem_limited_groups
, num
);
3141 memcg_kmem_clear_activated(memcg
);
3145 memcg
->kmemcg_id
= num
;
3146 INIT_LIST_HEAD(&memcg
->memcg_slab_caches
);
3147 mutex_init(&memcg
->slab_caches_mutex
);
3151 static size_t memcg_caches_array_size(int num_groups
)
3154 if (num_groups
<= 0)
3157 size
= 2 * num_groups
;
3158 if (size
< MEMCG_CACHES_MIN_SIZE
)
3159 size
= MEMCG_CACHES_MIN_SIZE
;
3160 else if (size
> MEMCG_CACHES_MAX_SIZE
)
3161 size
= MEMCG_CACHES_MAX_SIZE
;
3167 * We should update the current array size iff all caches updates succeed. This
3168 * can only be done from the slab side. The slab mutex needs to be held when
3171 void memcg_update_array_size(int num
)
3173 if (num
> memcg_limited_groups_array_size
)
3174 memcg_limited_groups_array_size
= memcg_caches_array_size(num
);
3177 static void kmem_cache_destroy_work_func(struct work_struct
*w
);
3179 int memcg_update_cache_size(struct kmem_cache
*s
, int num_groups
)
3181 struct memcg_cache_params
*cur_params
= s
->memcg_params
;
3183 VM_BUG_ON(s
->memcg_params
&& !s
->memcg_params
->is_root_cache
);
3185 if (num_groups
> memcg_limited_groups_array_size
) {
3187 ssize_t size
= memcg_caches_array_size(num_groups
);
3189 size
*= sizeof(void *);
3190 size
+= offsetof(struct memcg_cache_params
, memcg_caches
);
3192 s
->memcg_params
= kzalloc(size
, GFP_KERNEL
);
3193 if (!s
->memcg_params
) {
3194 s
->memcg_params
= cur_params
;
3198 s
->memcg_params
->is_root_cache
= true;
3201 * There is the chance it will be bigger than
3202 * memcg_limited_groups_array_size, if we failed an allocation
3203 * in a cache, in which case all caches updated before it, will
3204 * have a bigger array.
3206 * But if that is the case, the data after
3207 * memcg_limited_groups_array_size is certainly unused
3209 for (i
= 0; i
< memcg_limited_groups_array_size
; i
++) {
3210 if (!cur_params
->memcg_caches
[i
])
3212 s
->memcg_params
->memcg_caches
[i
] =
3213 cur_params
->memcg_caches
[i
];
3217 * Ideally, we would wait until all caches succeed, and only
3218 * then free the old one. But this is not worth the extra
3219 * pointer per-cache we'd have to have for this.
3221 * It is not a big deal if some caches are left with a size
3222 * bigger than the others. And all updates will reset this
3230 int memcg_register_cache(struct mem_cgroup
*memcg
, struct kmem_cache
*s
,
3231 struct kmem_cache
*root_cache
)
3235 if (!memcg_kmem_enabled())
3239 size
= offsetof(struct memcg_cache_params
, memcg_caches
);
3240 size
+= memcg_limited_groups_array_size
* sizeof(void *);
3242 size
= sizeof(struct memcg_cache_params
);
3244 s
->memcg_params
= kzalloc(size
, GFP_KERNEL
);
3245 if (!s
->memcg_params
)
3249 s
->memcg_params
->memcg
= memcg
;
3250 s
->memcg_params
->root_cache
= root_cache
;
3251 INIT_WORK(&s
->memcg_params
->destroy
,
3252 kmem_cache_destroy_work_func
);
3254 s
->memcg_params
->is_root_cache
= true;
3259 void memcg_release_cache(struct kmem_cache
*s
)
3261 struct kmem_cache
*root
;
3262 struct mem_cgroup
*memcg
;
3266 * This happens, for instance, when a root cache goes away before we
3269 if (!s
->memcg_params
)
3272 if (s
->memcg_params
->is_root_cache
)
3275 memcg
= s
->memcg_params
->memcg
;
3276 id
= memcg_cache_id(memcg
);
3278 root
= s
->memcg_params
->root_cache
;
3279 root
->memcg_params
->memcg_caches
[id
] = NULL
;
3281 mutex_lock(&memcg
->slab_caches_mutex
);
3282 list_del(&s
->memcg_params
->list
);
3283 mutex_unlock(&memcg
->slab_caches_mutex
);
3285 css_put(&memcg
->css
);
3287 kfree(s
->memcg_params
);
3291 * During the creation a new cache, we need to disable our accounting mechanism
3292 * altogether. This is true even if we are not creating, but rather just
3293 * enqueing new caches to be created.
3295 * This is because that process will trigger allocations; some visible, like
3296 * explicit kmallocs to auxiliary data structures, name strings and internal
3297 * cache structures; some well concealed, like INIT_WORK() that can allocate
3298 * objects during debug.
3300 * If any allocation happens during memcg_kmem_get_cache, we will recurse back
3301 * to it. This may not be a bounded recursion: since the first cache creation
3302 * failed to complete (waiting on the allocation), we'll just try to create the
3303 * cache again, failing at the same point.
3305 * memcg_kmem_get_cache is prepared to abort after seeing a positive count of
3306 * memcg_kmem_skip_account. So we enclose anything that might allocate memory
3307 * inside the following two functions.
3309 static inline void memcg_stop_kmem_account(void)
3311 VM_BUG_ON(!current
->mm
);
3312 current
->memcg_kmem_skip_account
++;
3315 static inline void memcg_resume_kmem_account(void)
3317 VM_BUG_ON(!current
->mm
);
3318 current
->memcg_kmem_skip_account
--;
3321 static void kmem_cache_destroy_work_func(struct work_struct
*w
)
3323 struct kmem_cache
*cachep
;
3324 struct memcg_cache_params
*p
;
3326 p
= container_of(w
, struct memcg_cache_params
, destroy
);
3328 cachep
= memcg_params_to_cache(p
);
3331 * If we get down to 0 after shrink, we could delete right away.
3332 * However, memcg_release_pages() already puts us back in the workqueue
3333 * in that case. If we proceed deleting, we'll get a dangling
3334 * reference, and removing the object from the workqueue in that case
3335 * is unnecessary complication. We are not a fast path.
3337 * Note that this case is fundamentally different from racing with
3338 * shrink_slab(): if memcg_cgroup_destroy_cache() is called in
3339 * kmem_cache_shrink, not only we would be reinserting a dead cache
3340 * into the queue, but doing so from inside the worker racing to
3343 * So if we aren't down to zero, we'll just schedule a worker and try
3346 if (atomic_read(&cachep
->memcg_params
->nr_pages
) != 0) {
3347 kmem_cache_shrink(cachep
);
3348 if (atomic_read(&cachep
->memcg_params
->nr_pages
) == 0)
3351 kmem_cache_destroy(cachep
);
3354 void mem_cgroup_destroy_cache(struct kmem_cache
*cachep
)
3356 if (!cachep
->memcg_params
->dead
)
3360 * There are many ways in which we can get here.
3362 * We can get to a memory-pressure situation while the delayed work is
3363 * still pending to run. The vmscan shrinkers can then release all
3364 * cache memory and get us to destruction. If this is the case, we'll
3365 * be executed twice, which is a bug (the second time will execute over
3366 * bogus data). In this case, cancelling the work should be fine.
3368 * But we can also get here from the worker itself, if
3369 * kmem_cache_shrink is enough to shake all the remaining objects and
3370 * get the page count to 0. In this case, we'll deadlock if we try to
3371 * cancel the work (the worker runs with an internal lock held, which
3372 * is the same lock we would hold for cancel_work_sync().)
3374 * Since we can't possibly know who got us here, just refrain from
3375 * running if there is already work pending
3377 if (work_pending(&cachep
->memcg_params
->destroy
))
3380 * We have to defer the actual destroying to a workqueue, because
3381 * we might currently be in a context that cannot sleep.
3383 schedule_work(&cachep
->memcg_params
->destroy
);
3387 * This lock protects updaters, not readers. We want readers to be as fast as
3388 * they can, and they will either see NULL or a valid cache value. Our model
3389 * allow them to see NULL, in which case the root memcg will be selected.
3391 * We need this lock because multiple allocations to the same cache from a non
3392 * will span more than one worker. Only one of them can create the cache.
3394 static DEFINE_MUTEX(memcg_cache_mutex
);
3397 * Called with memcg_cache_mutex held
3399 static struct kmem_cache
*kmem_cache_dup(struct mem_cgroup
*memcg
,
3400 struct kmem_cache
*s
)
3402 struct kmem_cache
*new;
3403 static char *tmp_name
= NULL
;
3405 lockdep_assert_held(&memcg_cache_mutex
);
3408 * kmem_cache_create_memcg duplicates the given name and
3409 * cgroup_name for this name requires RCU context.
3410 * This static temporary buffer is used to prevent from
3411 * pointless shortliving allocation.
3414 tmp_name
= kmalloc(PATH_MAX
, GFP_KERNEL
);
3420 snprintf(tmp_name
, PATH_MAX
, "%s(%d:%s)", s
->name
,
3421 memcg_cache_id(memcg
), cgroup_name(memcg
->css
.cgroup
));
3424 new = kmem_cache_create_memcg(memcg
, tmp_name
, s
->object_size
, s
->align
,
3425 (s
->flags
& ~SLAB_PANIC
), s
->ctor
, s
);
3428 new->allocflags
|= __GFP_KMEMCG
;
3433 static struct kmem_cache
*memcg_create_kmem_cache(struct mem_cgroup
*memcg
,
3434 struct kmem_cache
*cachep
)
3436 struct kmem_cache
*new_cachep
;
3439 BUG_ON(!memcg_can_account_kmem(memcg
));
3441 idx
= memcg_cache_id(memcg
);
3443 mutex_lock(&memcg_cache_mutex
);
3444 new_cachep
= cachep
->memcg_params
->memcg_caches
[idx
];
3446 css_put(&memcg
->css
);
3450 new_cachep
= kmem_cache_dup(memcg
, cachep
);
3451 if (new_cachep
== NULL
) {
3452 new_cachep
= cachep
;
3453 css_put(&memcg
->css
);
3457 atomic_set(&new_cachep
->memcg_params
->nr_pages
, 0);
3459 cachep
->memcg_params
->memcg_caches
[idx
] = new_cachep
;
3461 * the readers won't lock, make sure everybody sees the updated value,
3462 * so they won't put stuff in the queue again for no reason
3466 mutex_unlock(&memcg_cache_mutex
);
3470 void kmem_cache_destroy_memcg_children(struct kmem_cache
*s
)
3472 struct kmem_cache
*c
;
3475 if (!s
->memcg_params
)
3477 if (!s
->memcg_params
->is_root_cache
)
3481 * If the cache is being destroyed, we trust that there is no one else
3482 * requesting objects from it. Even if there are, the sanity checks in
3483 * kmem_cache_destroy should caught this ill-case.
3485 * Still, we don't want anyone else freeing memcg_caches under our
3486 * noses, which can happen if a new memcg comes to life. As usual,
3487 * we'll take the set_limit_mutex to protect ourselves against this.
3489 mutex_lock(&set_limit_mutex
);
3490 for (i
= 0; i
< memcg_limited_groups_array_size
; i
++) {
3491 c
= s
->memcg_params
->memcg_caches
[i
];
3496 * We will now manually delete the caches, so to avoid races
3497 * we need to cancel all pending destruction workers and
3498 * proceed with destruction ourselves.
3500 * kmem_cache_destroy() will call kmem_cache_shrink internally,
3501 * and that could spawn the workers again: it is likely that
3502 * the cache still have active pages until this very moment.
3503 * This would lead us back to mem_cgroup_destroy_cache.
3505 * But that will not execute at all if the "dead" flag is not
3506 * set, so flip it down to guarantee we are in control.
3508 c
->memcg_params
->dead
= false;
3509 cancel_work_sync(&c
->memcg_params
->destroy
);
3510 kmem_cache_destroy(c
);
3512 mutex_unlock(&set_limit_mutex
);
3515 struct create_work
{
3516 struct mem_cgroup
*memcg
;
3517 struct kmem_cache
*cachep
;
3518 struct work_struct work
;
3521 static void mem_cgroup_destroy_all_caches(struct mem_cgroup
*memcg
)
3523 struct kmem_cache
*cachep
;
3524 struct memcg_cache_params
*params
;
3526 if (!memcg_kmem_is_active(memcg
))
3529 mutex_lock(&memcg
->slab_caches_mutex
);
3530 list_for_each_entry(params
, &memcg
->memcg_slab_caches
, list
) {
3531 cachep
= memcg_params_to_cache(params
);
3532 cachep
->memcg_params
->dead
= true;
3533 schedule_work(&cachep
->memcg_params
->destroy
);
3535 mutex_unlock(&memcg
->slab_caches_mutex
);
3538 static void memcg_create_cache_work_func(struct work_struct
*w
)
3540 struct create_work
*cw
;
3542 cw
= container_of(w
, struct create_work
, work
);
3543 memcg_create_kmem_cache(cw
->memcg
, cw
->cachep
);
3548 * Enqueue the creation of a per-memcg kmem_cache.
3550 static void __memcg_create_cache_enqueue(struct mem_cgroup
*memcg
,
3551 struct kmem_cache
*cachep
)
3553 struct create_work
*cw
;
3555 cw
= kmalloc(sizeof(struct create_work
), GFP_NOWAIT
);
3557 css_put(&memcg
->css
);
3562 cw
->cachep
= cachep
;
3564 INIT_WORK(&cw
->work
, memcg_create_cache_work_func
);
3565 schedule_work(&cw
->work
);
3568 static void memcg_create_cache_enqueue(struct mem_cgroup
*memcg
,
3569 struct kmem_cache
*cachep
)
3572 * We need to stop accounting when we kmalloc, because if the
3573 * corresponding kmalloc cache is not yet created, the first allocation
3574 * in __memcg_create_cache_enqueue will recurse.
3576 * However, it is better to enclose the whole function. Depending on
3577 * the debugging options enabled, INIT_WORK(), for instance, can
3578 * trigger an allocation. This too, will make us recurse. Because at
3579 * this point we can't allow ourselves back into memcg_kmem_get_cache,
3580 * the safest choice is to do it like this, wrapping the whole function.
3582 memcg_stop_kmem_account();
3583 __memcg_create_cache_enqueue(memcg
, cachep
);
3584 memcg_resume_kmem_account();
3587 * Return the kmem_cache we're supposed to use for a slab allocation.
3588 * We try to use the current memcg's version of the cache.
3590 * If the cache does not exist yet, if we are the first user of it,
3591 * we either create it immediately, if possible, or create it asynchronously
3593 * In the latter case, we will let the current allocation go through with
3594 * the original cache.
3596 * Can't be called in interrupt context or from kernel threads.
3597 * This function needs to be called with rcu_read_lock() held.
3599 struct kmem_cache
*__memcg_kmem_get_cache(struct kmem_cache
*cachep
,
3602 struct mem_cgroup
*memcg
;
3605 VM_BUG_ON(!cachep
->memcg_params
);
3606 VM_BUG_ON(!cachep
->memcg_params
->is_root_cache
);
3608 if (!current
->mm
|| current
->memcg_kmem_skip_account
)
3612 memcg
= mem_cgroup_from_task(rcu_dereference(current
->mm
->owner
));
3614 if (!memcg_can_account_kmem(memcg
))
3617 idx
= memcg_cache_id(memcg
);
3620 * barrier to mare sure we're always seeing the up to date value. The
3621 * code updating memcg_caches will issue a write barrier to match this.
3623 read_barrier_depends();
3624 if (likely(cachep
->memcg_params
->memcg_caches
[idx
])) {
3625 cachep
= cachep
->memcg_params
->memcg_caches
[idx
];
3629 /* The corresponding put will be done in the workqueue. */
3630 if (!css_tryget(&memcg
->css
))
3635 * If we are in a safe context (can wait, and not in interrupt
3636 * context), we could be be predictable and return right away.
3637 * This would guarantee that the allocation being performed
3638 * already belongs in the new cache.
3640 * However, there are some clashes that can arrive from locking.
3641 * For instance, because we acquire the slab_mutex while doing
3642 * kmem_cache_dup, this means no further allocation could happen
3643 * with the slab_mutex held.
3645 * Also, because cache creation issue get_online_cpus(), this
3646 * creates a lock chain: memcg_slab_mutex -> cpu_hotplug_mutex,
3647 * that ends up reversed during cpu hotplug. (cpuset allocates
3648 * a bunch of GFP_KERNEL memory during cpuup). Due to all that,
3649 * better to defer everything.
3651 memcg_create_cache_enqueue(memcg
, cachep
);
3657 EXPORT_SYMBOL(__memcg_kmem_get_cache
);
3660 * We need to verify if the allocation against current->mm->owner's memcg is
3661 * possible for the given order. But the page is not allocated yet, so we'll
3662 * need a further commit step to do the final arrangements.
3664 * It is possible for the task to switch cgroups in this mean time, so at
3665 * commit time, we can't rely on task conversion any longer. We'll then use
3666 * the handle argument to return to the caller which cgroup we should commit
3667 * against. We could also return the memcg directly and avoid the pointer
3668 * passing, but a boolean return value gives better semantics considering
3669 * the compiled-out case as well.
3671 * Returning true means the allocation is possible.
3674 __memcg_kmem_newpage_charge(gfp_t gfp
, struct mem_cgroup
**_memcg
, int order
)
3676 struct mem_cgroup
*memcg
;
3682 * Disabling accounting is only relevant for some specific memcg
3683 * internal allocations. Therefore we would initially not have such
3684 * check here, since direct calls to the page allocator that are marked
3685 * with GFP_KMEMCG only happen outside memcg core. We are mostly
3686 * concerned with cache allocations, and by having this test at
3687 * memcg_kmem_get_cache, we are already able to relay the allocation to
3688 * the root cache and bypass the memcg cache altogether.
3690 * There is one exception, though: the SLUB allocator does not create
3691 * large order caches, but rather service large kmallocs directly from
3692 * the page allocator. Therefore, the following sequence when backed by
3693 * the SLUB allocator:
3695 * memcg_stop_kmem_account();
3696 * kmalloc(<large_number>)
3697 * memcg_resume_kmem_account();
3699 * would effectively ignore the fact that we should skip accounting,
3700 * since it will drive us directly to this function without passing
3701 * through the cache selector memcg_kmem_get_cache. Such large
3702 * allocations are extremely rare but can happen, for instance, for the
3703 * cache arrays. We bring this test here.
3705 if (!current
->mm
|| current
->memcg_kmem_skip_account
)
3708 memcg
= try_get_mem_cgroup_from_mm(current
->mm
);
3711 * very rare case described in mem_cgroup_from_task. Unfortunately there
3712 * isn't much we can do without complicating this too much, and it would
3713 * be gfp-dependent anyway. Just let it go
3715 if (unlikely(!memcg
))
3718 if (!memcg_can_account_kmem(memcg
)) {
3719 css_put(&memcg
->css
);
3723 ret
= memcg_charge_kmem(memcg
, gfp
, PAGE_SIZE
<< order
);
3727 css_put(&memcg
->css
);
3731 void __memcg_kmem_commit_charge(struct page
*page
, struct mem_cgroup
*memcg
,
3734 struct page_cgroup
*pc
;
3736 VM_BUG_ON(mem_cgroup_is_root(memcg
));
3738 /* The page allocation failed. Revert */
3740 memcg_uncharge_kmem(memcg
, PAGE_SIZE
<< order
);
3744 pc
= lookup_page_cgroup(page
);
3745 lock_page_cgroup(pc
);
3746 pc
->mem_cgroup
= memcg
;
3747 SetPageCgroupUsed(pc
);
3748 unlock_page_cgroup(pc
);
3751 void __memcg_kmem_uncharge_pages(struct page
*page
, int order
)
3753 struct mem_cgroup
*memcg
= NULL
;
3754 struct page_cgroup
*pc
;
3757 pc
= lookup_page_cgroup(page
);
3759 * Fast unlocked return. Theoretically might have changed, have to
3760 * check again after locking.
3762 if (!PageCgroupUsed(pc
))
3765 lock_page_cgroup(pc
);
3766 if (PageCgroupUsed(pc
)) {
3767 memcg
= pc
->mem_cgroup
;
3768 ClearPageCgroupUsed(pc
);
3770 unlock_page_cgroup(pc
);
3773 * We trust that only if there is a memcg associated with the page, it
3774 * is a valid allocation
3779 VM_BUG_ON(mem_cgroup_is_root(memcg
));
3780 memcg_uncharge_kmem(memcg
, PAGE_SIZE
<< order
);
3783 static inline void mem_cgroup_destroy_all_caches(struct mem_cgroup
*memcg
)
3786 #endif /* CONFIG_MEMCG_KMEM */
3788 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3790 #define PCGF_NOCOPY_AT_SPLIT (1 << PCG_LOCK | 1 << PCG_MIGRATION)
3792 * Because tail pages are not marked as "used", set it. We're under
3793 * zone->lru_lock, 'splitting on pmd' and compound_lock.
3794 * charge/uncharge will be never happen and move_account() is done under
3795 * compound_lock(), so we don't have to take care of races.
3797 void mem_cgroup_split_huge_fixup(struct page
*head
)
3799 struct page_cgroup
*head_pc
= lookup_page_cgroup(head
);
3800 struct page_cgroup
*pc
;
3801 struct mem_cgroup
*memcg
;
3804 if (mem_cgroup_disabled())
3807 memcg
= head_pc
->mem_cgroup
;
3808 for (i
= 1; i
< HPAGE_PMD_NR
; i
++) {
3810 pc
->mem_cgroup
= memcg
;
3811 smp_wmb();/* see __commit_charge() */
3812 pc
->flags
= head_pc
->flags
& ~PCGF_NOCOPY_AT_SPLIT
;
3814 __this_cpu_sub(memcg
->stat
->count
[MEM_CGROUP_STAT_RSS_HUGE
],
3817 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
3820 void mem_cgroup_move_account_page_stat(struct mem_cgroup
*from
,
3821 struct mem_cgroup
*to
,
3822 unsigned int nr_pages
,
3823 enum mem_cgroup_stat_index idx
)
3825 /* Update stat data for mem_cgroup */
3827 __this_cpu_sub(from
->stat
->count
[idx
], nr_pages
);
3828 __this_cpu_add(to
->stat
->count
[idx
], nr_pages
);
3833 * mem_cgroup_move_account - move account of the page
3835 * @nr_pages: number of regular pages (>1 for huge pages)
3836 * @pc: page_cgroup of the page.
3837 * @from: mem_cgroup which the page is moved from.
3838 * @to: mem_cgroup which the page is moved to. @from != @to.
3840 * The caller must confirm following.
3841 * - page is not on LRU (isolate_page() is useful.)
3842 * - compound_lock is held when nr_pages > 1
3844 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
3847 static int mem_cgroup_move_account(struct page
*page
,
3848 unsigned int nr_pages
,
3849 struct page_cgroup
*pc
,
3850 struct mem_cgroup
*from
,
3851 struct mem_cgroup
*to
)
3853 unsigned long flags
;
3855 bool anon
= PageAnon(page
);
3857 VM_BUG_ON(from
== to
);
3858 VM_BUG_ON(PageLRU(page
));
3860 * The page is isolated from LRU. So, collapse function
3861 * will not handle this page. But page splitting can happen.
3862 * Do this check under compound_page_lock(). The caller should
3866 if (nr_pages
> 1 && !PageTransHuge(page
))
3869 lock_page_cgroup(pc
);
3872 if (!PageCgroupUsed(pc
) || pc
->mem_cgroup
!= from
)
3875 move_lock_mem_cgroup(from
, &flags
);
3877 if (!anon
&& page_mapped(page
))
3878 mem_cgroup_move_account_page_stat(from
, to
, nr_pages
,
3879 MEM_CGROUP_STAT_FILE_MAPPED
);
3881 if (PageWriteback(page
))
3882 mem_cgroup_move_account_page_stat(from
, to
, nr_pages
,
3883 MEM_CGROUP_STAT_WRITEBACK
);
3885 mem_cgroup_charge_statistics(from
, page
, anon
, -nr_pages
);
3887 /* caller should have done css_get */
3888 pc
->mem_cgroup
= to
;
3889 mem_cgroup_charge_statistics(to
, page
, anon
, nr_pages
);
3890 move_unlock_mem_cgroup(from
, &flags
);
3893 unlock_page_cgroup(pc
);
3897 memcg_check_events(to
, page
);
3898 memcg_check_events(from
, page
);
3904 * mem_cgroup_move_parent - moves page to the parent group
3905 * @page: the page to move
3906 * @pc: page_cgroup of the page
3907 * @child: page's cgroup
3909 * move charges to its parent or the root cgroup if the group has no
3910 * parent (aka use_hierarchy==0).
3911 * Although this might fail (get_page_unless_zero, isolate_lru_page or
3912 * mem_cgroup_move_account fails) the failure is always temporary and
3913 * it signals a race with a page removal/uncharge or migration. In the
3914 * first case the page is on the way out and it will vanish from the LRU
3915 * on the next attempt and the call should be retried later.
3916 * Isolation from the LRU fails only if page has been isolated from
3917 * the LRU since we looked at it and that usually means either global
3918 * reclaim or migration going on. The page will either get back to the
3920 * Finaly mem_cgroup_move_account fails only if the page got uncharged
3921 * (!PageCgroupUsed) or moved to a different group. The page will
3922 * disappear in the next attempt.
3924 static int mem_cgroup_move_parent(struct page
*page
,
3925 struct page_cgroup
*pc
,
3926 struct mem_cgroup
*child
)
3928 struct mem_cgroup
*parent
;
3929 unsigned int nr_pages
;
3930 unsigned long uninitialized_var(flags
);
3933 VM_BUG_ON(mem_cgroup_is_root(child
));
3936 if (!get_page_unless_zero(page
))
3938 if (isolate_lru_page(page
))
3941 nr_pages
= hpage_nr_pages(page
);
3943 parent
= parent_mem_cgroup(child
);
3945 * If no parent, move charges to root cgroup.
3948 parent
= root_mem_cgroup
;
3951 VM_BUG_ON(!PageTransHuge(page
));
3952 flags
= compound_lock_irqsave(page
);
3955 ret
= mem_cgroup_move_account(page
, nr_pages
,
3958 __mem_cgroup_cancel_local_charge(child
, nr_pages
);
3961 compound_unlock_irqrestore(page
, flags
);
3962 putback_lru_page(page
);
3970 * Charge the memory controller for page usage.
3972 * 0 if the charge was successful
3973 * < 0 if the cgroup is over its limit
3975 static int mem_cgroup_charge_common(struct page
*page
, struct mm_struct
*mm
,
3976 gfp_t gfp_mask
, enum charge_type ctype
)
3978 struct mem_cgroup
*memcg
= NULL
;
3979 unsigned int nr_pages
= 1;
3983 if (PageTransHuge(page
)) {
3984 nr_pages
<<= compound_order(page
);
3985 VM_BUG_ON(!PageTransHuge(page
));
3987 * Never OOM-kill a process for a huge page. The
3988 * fault handler will fall back to regular pages.
3993 ret
= __mem_cgroup_try_charge(mm
, gfp_mask
, nr_pages
, &memcg
, oom
);
3996 __mem_cgroup_commit_charge(memcg
, page
, nr_pages
, ctype
, false);
4000 int mem_cgroup_newpage_charge(struct page
*page
,
4001 struct mm_struct
*mm
, gfp_t gfp_mask
)
4003 if (mem_cgroup_disabled())
4005 VM_BUG_ON(page_mapped(page
));
4006 VM_BUG_ON(page
->mapping
&& !PageAnon(page
));
4008 return mem_cgroup_charge_common(page
, mm
, gfp_mask
,
4009 MEM_CGROUP_CHARGE_TYPE_ANON
);
4013 * While swap-in, try_charge -> commit or cancel, the page is locked.
4014 * And when try_charge() successfully returns, one refcnt to memcg without
4015 * struct page_cgroup is acquired. This refcnt will be consumed by
4016 * "commit()" or removed by "cancel()"
4018 static int __mem_cgroup_try_charge_swapin(struct mm_struct
*mm
,
4021 struct mem_cgroup
**memcgp
)
4023 struct mem_cgroup
*memcg
;
4024 struct page_cgroup
*pc
;
4027 pc
= lookup_page_cgroup(page
);
4029 * Every swap fault against a single page tries to charge the
4030 * page, bail as early as possible. shmem_unuse() encounters
4031 * already charged pages, too. The USED bit is protected by
4032 * the page lock, which serializes swap cache removal, which
4033 * in turn serializes uncharging.
4035 if (PageCgroupUsed(pc
))
4037 if (!do_swap_account
)
4039 memcg
= try_get_mem_cgroup_from_page(page
);
4043 ret
= __mem_cgroup_try_charge(NULL
, mask
, 1, memcgp
, true);
4044 css_put(&memcg
->css
);
4049 ret
= __mem_cgroup_try_charge(mm
, mask
, 1, memcgp
, true);
4055 int mem_cgroup_try_charge_swapin(struct mm_struct
*mm
, struct page
*page
,
4056 gfp_t gfp_mask
, struct mem_cgroup
**memcgp
)
4059 if (mem_cgroup_disabled())
4062 * A racing thread's fault, or swapoff, may have already
4063 * updated the pte, and even removed page from swap cache: in
4064 * those cases unuse_pte()'s pte_same() test will fail; but
4065 * there's also a KSM case which does need to charge the page.
4067 if (!PageSwapCache(page
)) {
4070 ret
= __mem_cgroup_try_charge(mm
, gfp_mask
, 1, memcgp
, true);
4075 return __mem_cgroup_try_charge_swapin(mm
, page
, gfp_mask
, memcgp
);
4078 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup
*memcg
)
4080 if (mem_cgroup_disabled())
4084 __mem_cgroup_cancel_charge(memcg
, 1);
4088 __mem_cgroup_commit_charge_swapin(struct page
*page
, struct mem_cgroup
*memcg
,
4089 enum charge_type ctype
)
4091 if (mem_cgroup_disabled())
4096 __mem_cgroup_commit_charge(memcg
, page
, 1, ctype
, true);
4098 * Now swap is on-memory. This means this page may be
4099 * counted both as mem and swap....double count.
4100 * Fix it by uncharging from memsw. Basically, this SwapCache is stable
4101 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
4102 * may call delete_from_swap_cache() before reach here.
4104 if (do_swap_account
&& PageSwapCache(page
)) {
4105 swp_entry_t ent
= {.val
= page_private(page
)};
4106 mem_cgroup_uncharge_swap(ent
);
4110 void mem_cgroup_commit_charge_swapin(struct page
*page
,
4111 struct mem_cgroup
*memcg
)
4113 __mem_cgroup_commit_charge_swapin(page
, memcg
,
4114 MEM_CGROUP_CHARGE_TYPE_ANON
);
4117 int mem_cgroup_cache_charge(struct page
*page
, struct mm_struct
*mm
,
4120 struct mem_cgroup
*memcg
= NULL
;
4121 enum charge_type type
= MEM_CGROUP_CHARGE_TYPE_CACHE
;
4124 if (mem_cgroup_disabled())
4126 if (PageCompound(page
))
4129 if (!PageSwapCache(page
))
4130 ret
= mem_cgroup_charge_common(page
, mm
, gfp_mask
, type
);
4131 else { /* page is swapcache/shmem */
4132 ret
= __mem_cgroup_try_charge_swapin(mm
, page
,
4135 __mem_cgroup_commit_charge_swapin(page
, memcg
, type
);
4140 static void mem_cgroup_do_uncharge(struct mem_cgroup
*memcg
,
4141 unsigned int nr_pages
,
4142 const enum charge_type ctype
)
4144 struct memcg_batch_info
*batch
= NULL
;
4145 bool uncharge_memsw
= true;
4147 /* If swapout, usage of swap doesn't decrease */
4148 if (!do_swap_account
|| ctype
== MEM_CGROUP_CHARGE_TYPE_SWAPOUT
)
4149 uncharge_memsw
= false;
4151 batch
= ¤t
->memcg_batch
;
4153 * In usual, we do css_get() when we remember memcg pointer.
4154 * But in this case, we keep res->usage until end of a series of
4155 * uncharges. Then, it's ok to ignore memcg's refcnt.
4158 batch
->memcg
= memcg
;
4160 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
4161 * In those cases, all pages freed continuously can be expected to be in
4162 * the same cgroup and we have chance to coalesce uncharges.
4163 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
4164 * because we want to do uncharge as soon as possible.
4167 if (!batch
->do_batch
|| test_thread_flag(TIF_MEMDIE
))
4168 goto direct_uncharge
;
4171 goto direct_uncharge
;
4174 * In typical case, batch->memcg == mem. This means we can
4175 * merge a series of uncharges to an uncharge of res_counter.
4176 * If not, we uncharge res_counter ony by one.
4178 if (batch
->memcg
!= memcg
)
4179 goto direct_uncharge
;
4180 /* remember freed charge and uncharge it later */
4183 batch
->memsw_nr_pages
++;
4186 res_counter_uncharge(&memcg
->res
, nr_pages
* PAGE_SIZE
);
4188 res_counter_uncharge(&memcg
->memsw
, nr_pages
* PAGE_SIZE
);
4189 if (unlikely(batch
->memcg
!= memcg
))
4190 memcg_oom_recover(memcg
);
4194 * uncharge if !page_mapped(page)
4196 static struct mem_cgroup
*
4197 __mem_cgroup_uncharge_common(struct page
*page
, enum charge_type ctype
,
4200 struct mem_cgroup
*memcg
= NULL
;
4201 unsigned int nr_pages
= 1;
4202 struct page_cgroup
*pc
;
4205 if (mem_cgroup_disabled())
4208 if (PageTransHuge(page
)) {
4209 nr_pages
<<= compound_order(page
);
4210 VM_BUG_ON(!PageTransHuge(page
));
4213 * Check if our page_cgroup is valid
4215 pc
= lookup_page_cgroup(page
);
4216 if (unlikely(!PageCgroupUsed(pc
)))
4219 lock_page_cgroup(pc
);
4221 memcg
= pc
->mem_cgroup
;
4223 if (!PageCgroupUsed(pc
))
4226 anon
= PageAnon(page
);
4229 case MEM_CGROUP_CHARGE_TYPE_ANON
:
4231 * Generally PageAnon tells if it's the anon statistics to be
4232 * updated; but sometimes e.g. mem_cgroup_uncharge_page() is
4233 * used before page reached the stage of being marked PageAnon.
4237 case MEM_CGROUP_CHARGE_TYPE_DROP
:
4238 /* See mem_cgroup_prepare_migration() */
4239 if (page_mapped(page
))
4242 * Pages under migration may not be uncharged. But
4243 * end_migration() /must/ be the one uncharging the
4244 * unused post-migration page and so it has to call
4245 * here with the migration bit still set. See the
4246 * res_counter handling below.
4248 if (!end_migration
&& PageCgroupMigration(pc
))
4251 case MEM_CGROUP_CHARGE_TYPE_SWAPOUT
:
4252 if (!PageAnon(page
)) { /* Shared memory */
4253 if (page
->mapping
&& !page_is_file_cache(page
))
4255 } else if (page_mapped(page
)) /* Anon */
4262 mem_cgroup_charge_statistics(memcg
, page
, anon
, -nr_pages
);
4264 ClearPageCgroupUsed(pc
);
4266 * pc->mem_cgroup is not cleared here. It will be accessed when it's
4267 * freed from LRU. This is safe because uncharged page is expected not
4268 * to be reused (freed soon). Exception is SwapCache, it's handled by
4269 * special functions.
4272 unlock_page_cgroup(pc
);
4274 * even after unlock, we have memcg->res.usage here and this memcg
4275 * will never be freed, so it's safe to call css_get().
4277 memcg_check_events(memcg
, page
);
4278 if (do_swap_account
&& ctype
== MEM_CGROUP_CHARGE_TYPE_SWAPOUT
) {
4279 mem_cgroup_swap_statistics(memcg
, true);
4280 css_get(&memcg
->css
);
4283 * Migration does not charge the res_counter for the
4284 * replacement page, so leave it alone when phasing out the
4285 * page that is unused after the migration.
4287 if (!end_migration
&& !mem_cgroup_is_root(memcg
))
4288 mem_cgroup_do_uncharge(memcg
, nr_pages
, ctype
);
4293 unlock_page_cgroup(pc
);
4297 void mem_cgroup_uncharge_page(struct page
*page
)
4300 if (page_mapped(page
))
4302 VM_BUG_ON(page
->mapping
&& !PageAnon(page
));
4304 * If the page is in swap cache, uncharge should be deferred
4305 * to the swap path, which also properly accounts swap usage
4306 * and handles memcg lifetime.
4308 * Note that this check is not stable and reclaim may add the
4309 * page to swap cache at any time after this. However, if the
4310 * page is not in swap cache by the time page->mapcount hits
4311 * 0, there won't be any page table references to the swap
4312 * slot, and reclaim will free it and not actually write the
4315 if (PageSwapCache(page
))
4317 __mem_cgroup_uncharge_common(page
, MEM_CGROUP_CHARGE_TYPE_ANON
, false);
4320 void mem_cgroup_uncharge_cache_page(struct page
*page
)
4322 VM_BUG_ON(page_mapped(page
));
4323 VM_BUG_ON(page
->mapping
);
4324 __mem_cgroup_uncharge_common(page
, MEM_CGROUP_CHARGE_TYPE_CACHE
, false);
4328 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
4329 * In that cases, pages are freed continuously and we can expect pages
4330 * are in the same memcg. All these calls itself limits the number of
4331 * pages freed at once, then uncharge_start/end() is called properly.
4332 * This may be called prural(2) times in a context,
4335 void mem_cgroup_uncharge_start(void)
4337 current
->memcg_batch
.do_batch
++;
4338 /* We can do nest. */
4339 if (current
->memcg_batch
.do_batch
== 1) {
4340 current
->memcg_batch
.memcg
= NULL
;
4341 current
->memcg_batch
.nr_pages
= 0;
4342 current
->memcg_batch
.memsw_nr_pages
= 0;
4346 void mem_cgroup_uncharge_end(void)
4348 struct memcg_batch_info
*batch
= ¤t
->memcg_batch
;
4350 if (!batch
->do_batch
)
4354 if (batch
->do_batch
) /* If stacked, do nothing. */
4360 * This "batch->memcg" is valid without any css_get/put etc...
4361 * bacause we hide charges behind us.
4363 if (batch
->nr_pages
)
4364 res_counter_uncharge(&batch
->memcg
->res
,
4365 batch
->nr_pages
* PAGE_SIZE
);
4366 if (batch
->memsw_nr_pages
)
4367 res_counter_uncharge(&batch
->memcg
->memsw
,
4368 batch
->memsw_nr_pages
* PAGE_SIZE
);
4369 memcg_oom_recover(batch
->memcg
);
4370 /* forget this pointer (for sanity check) */
4371 batch
->memcg
= NULL
;
4376 * called after __delete_from_swap_cache() and drop "page" account.
4377 * memcg information is recorded to swap_cgroup of "ent"
4380 mem_cgroup_uncharge_swapcache(struct page
*page
, swp_entry_t ent
, bool swapout
)
4382 struct mem_cgroup
*memcg
;
4383 int ctype
= MEM_CGROUP_CHARGE_TYPE_SWAPOUT
;
4385 if (!swapout
) /* this was a swap cache but the swap is unused ! */
4386 ctype
= MEM_CGROUP_CHARGE_TYPE_DROP
;
4388 memcg
= __mem_cgroup_uncharge_common(page
, ctype
, false);
4391 * record memcg information, if swapout && memcg != NULL,
4392 * css_get() was called in uncharge().
4394 if (do_swap_account
&& swapout
&& memcg
)
4395 swap_cgroup_record(ent
, css_id(&memcg
->css
));
4399 #ifdef CONFIG_MEMCG_SWAP
4401 * called from swap_entry_free(). remove record in swap_cgroup and
4402 * uncharge "memsw" account.
4404 void mem_cgroup_uncharge_swap(swp_entry_t ent
)
4406 struct mem_cgroup
*memcg
;
4409 if (!do_swap_account
)
4412 id
= swap_cgroup_record(ent
, 0);
4414 memcg
= mem_cgroup_lookup(id
);
4417 * We uncharge this because swap is freed.
4418 * This memcg can be obsolete one. We avoid calling css_tryget
4420 if (!mem_cgroup_is_root(memcg
))
4421 res_counter_uncharge(&memcg
->memsw
, PAGE_SIZE
);
4422 mem_cgroup_swap_statistics(memcg
, false);
4423 css_put(&memcg
->css
);
4429 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
4430 * @entry: swap entry to be moved
4431 * @from: mem_cgroup which the entry is moved from
4432 * @to: mem_cgroup which the entry is moved to
4434 * It succeeds only when the swap_cgroup's record for this entry is the same
4435 * as the mem_cgroup's id of @from.
4437 * Returns 0 on success, -EINVAL on failure.
4439 * The caller must have charged to @to, IOW, called res_counter_charge() about
4440 * both res and memsw, and called css_get().
4442 static int mem_cgroup_move_swap_account(swp_entry_t entry
,
4443 struct mem_cgroup
*from
, struct mem_cgroup
*to
)
4445 unsigned short old_id
, new_id
;
4447 old_id
= css_id(&from
->css
);
4448 new_id
= css_id(&to
->css
);
4450 if (swap_cgroup_cmpxchg(entry
, old_id
, new_id
) == old_id
) {
4451 mem_cgroup_swap_statistics(from
, false);
4452 mem_cgroup_swap_statistics(to
, true);
4454 * This function is only called from task migration context now.
4455 * It postpones res_counter and refcount handling till the end
4456 * of task migration(mem_cgroup_clear_mc()) for performance
4457 * improvement. But we cannot postpone css_get(to) because if
4458 * the process that has been moved to @to does swap-in, the
4459 * refcount of @to might be decreased to 0.
4461 * We are in attach() phase, so the cgroup is guaranteed to be
4462 * alive, so we can just call css_get().
4470 static inline int mem_cgroup_move_swap_account(swp_entry_t entry
,
4471 struct mem_cgroup
*from
, struct mem_cgroup
*to
)
4478 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
4481 void mem_cgroup_prepare_migration(struct page
*page
, struct page
*newpage
,
4482 struct mem_cgroup
**memcgp
)
4484 struct mem_cgroup
*memcg
= NULL
;
4485 unsigned int nr_pages
= 1;
4486 struct page_cgroup
*pc
;
4487 enum charge_type ctype
;
4491 if (mem_cgroup_disabled())
4494 if (PageTransHuge(page
))
4495 nr_pages
<<= compound_order(page
);
4497 pc
= lookup_page_cgroup(page
);
4498 lock_page_cgroup(pc
);
4499 if (PageCgroupUsed(pc
)) {
4500 memcg
= pc
->mem_cgroup
;
4501 css_get(&memcg
->css
);
4503 * At migrating an anonymous page, its mapcount goes down
4504 * to 0 and uncharge() will be called. But, even if it's fully
4505 * unmapped, migration may fail and this page has to be
4506 * charged again. We set MIGRATION flag here and delay uncharge
4507 * until end_migration() is called
4509 * Corner Case Thinking
4511 * When the old page was mapped as Anon and it's unmap-and-freed
4512 * while migration was ongoing.
4513 * If unmap finds the old page, uncharge() of it will be delayed
4514 * until end_migration(). If unmap finds a new page, it's
4515 * uncharged when it make mapcount to be 1->0. If unmap code
4516 * finds swap_migration_entry, the new page will not be mapped
4517 * and end_migration() will find it(mapcount==0).
4520 * When the old page was mapped but migraion fails, the kernel
4521 * remaps it. A charge for it is kept by MIGRATION flag even
4522 * if mapcount goes down to 0. We can do remap successfully
4523 * without charging it again.
4526 * The "old" page is under lock_page() until the end of
4527 * migration, so, the old page itself will not be swapped-out.
4528 * If the new page is swapped out before end_migraton, our
4529 * hook to usual swap-out path will catch the event.
4532 SetPageCgroupMigration(pc
);
4534 unlock_page_cgroup(pc
);
4536 * If the page is not charged at this point,
4544 * We charge new page before it's used/mapped. So, even if unlock_page()
4545 * is called before end_migration, we can catch all events on this new
4546 * page. In the case new page is migrated but not remapped, new page's
4547 * mapcount will be finally 0 and we call uncharge in end_migration().
4550 ctype
= MEM_CGROUP_CHARGE_TYPE_ANON
;
4552 ctype
= MEM_CGROUP_CHARGE_TYPE_CACHE
;
4554 * The page is committed to the memcg, but it's not actually
4555 * charged to the res_counter since we plan on replacing the
4556 * old one and only one page is going to be left afterwards.
4558 __mem_cgroup_commit_charge(memcg
, newpage
, nr_pages
, ctype
, false);
4561 /* remove redundant charge if migration failed*/
4562 void mem_cgroup_end_migration(struct mem_cgroup
*memcg
,
4563 struct page
*oldpage
, struct page
*newpage
, bool migration_ok
)
4565 struct page
*used
, *unused
;
4566 struct page_cgroup
*pc
;
4572 if (!migration_ok
) {
4579 anon
= PageAnon(used
);
4580 __mem_cgroup_uncharge_common(unused
,
4581 anon
? MEM_CGROUP_CHARGE_TYPE_ANON
4582 : MEM_CGROUP_CHARGE_TYPE_CACHE
,
4584 css_put(&memcg
->css
);
4586 * We disallowed uncharge of pages under migration because mapcount
4587 * of the page goes down to zero, temporarly.
4588 * Clear the flag and check the page should be charged.
4590 pc
= lookup_page_cgroup(oldpage
);
4591 lock_page_cgroup(pc
);
4592 ClearPageCgroupMigration(pc
);
4593 unlock_page_cgroup(pc
);
4596 * If a page is a file cache, radix-tree replacement is very atomic
4597 * and we can skip this check. When it was an Anon page, its mapcount
4598 * goes down to 0. But because we added MIGRATION flage, it's not
4599 * uncharged yet. There are several case but page->mapcount check
4600 * and USED bit check in mem_cgroup_uncharge_page() will do enough
4601 * check. (see prepare_charge() also)
4604 mem_cgroup_uncharge_page(used
);
4608 * At replace page cache, newpage is not under any memcg but it's on
4609 * LRU. So, this function doesn't touch res_counter but handles LRU
4610 * in correct way. Both pages are locked so we cannot race with uncharge.
4612 void mem_cgroup_replace_page_cache(struct page
*oldpage
,
4613 struct page
*newpage
)
4615 struct mem_cgroup
*memcg
= NULL
;
4616 struct page_cgroup
*pc
;
4617 enum charge_type type
= MEM_CGROUP_CHARGE_TYPE_CACHE
;
4619 if (mem_cgroup_disabled())
4622 pc
= lookup_page_cgroup(oldpage
);
4623 /* fix accounting on old pages */
4624 lock_page_cgroup(pc
);
4625 if (PageCgroupUsed(pc
)) {
4626 memcg
= pc
->mem_cgroup
;
4627 mem_cgroup_charge_statistics(memcg
, oldpage
, false, -1);
4628 ClearPageCgroupUsed(pc
);
4630 unlock_page_cgroup(pc
);
4633 * When called from shmem_replace_page(), in some cases the
4634 * oldpage has already been charged, and in some cases not.
4639 * Even if newpage->mapping was NULL before starting replacement,
4640 * the newpage may be on LRU(or pagevec for LRU) already. We lock
4641 * LRU while we overwrite pc->mem_cgroup.
4643 __mem_cgroup_commit_charge(memcg
, newpage
, 1, type
, true);
4646 #ifdef CONFIG_DEBUG_VM
4647 static struct page_cgroup
*lookup_page_cgroup_used(struct page
*page
)
4649 struct page_cgroup
*pc
;
4651 pc
= lookup_page_cgroup(page
);
4653 * Can be NULL while feeding pages into the page allocator for
4654 * the first time, i.e. during boot or memory hotplug;
4655 * or when mem_cgroup_disabled().
4657 if (likely(pc
) && PageCgroupUsed(pc
))
4662 bool mem_cgroup_bad_page_check(struct page
*page
)
4664 if (mem_cgroup_disabled())
4667 return lookup_page_cgroup_used(page
) != NULL
;
4670 void mem_cgroup_print_bad_page(struct page
*page
)
4672 struct page_cgroup
*pc
;
4674 pc
= lookup_page_cgroup_used(page
);
4676 pr_alert("pc:%p pc->flags:%lx pc->mem_cgroup:%p\n",
4677 pc
, pc
->flags
, pc
->mem_cgroup
);
4682 static int mem_cgroup_resize_limit(struct mem_cgroup
*memcg
,
4683 unsigned long long val
)
4686 u64 memswlimit
, memlimit
;
4688 int children
= mem_cgroup_count_children(memcg
);
4689 u64 curusage
, oldusage
;
4693 * For keeping hierarchical_reclaim simple, how long we should retry
4694 * is depends on callers. We set our retry-count to be function
4695 * of # of children which we should visit in this loop.
4697 retry_count
= MEM_CGROUP_RECLAIM_RETRIES
* children
;
4699 oldusage
= res_counter_read_u64(&memcg
->res
, RES_USAGE
);
4702 while (retry_count
) {
4703 if (signal_pending(current
)) {
4708 * Rather than hide all in some function, I do this in
4709 * open coded manner. You see what this really does.
4710 * We have to guarantee memcg->res.limit <= memcg->memsw.limit.
4712 mutex_lock(&set_limit_mutex
);
4713 memswlimit
= res_counter_read_u64(&memcg
->memsw
, RES_LIMIT
);
4714 if (memswlimit
< val
) {
4716 mutex_unlock(&set_limit_mutex
);
4720 memlimit
= res_counter_read_u64(&memcg
->res
, RES_LIMIT
);
4724 ret
= res_counter_set_limit(&memcg
->res
, val
);
4726 if (memswlimit
== val
)
4727 memcg
->memsw_is_minimum
= true;
4729 memcg
->memsw_is_minimum
= false;
4731 mutex_unlock(&set_limit_mutex
);
4736 mem_cgroup_reclaim(memcg
, GFP_KERNEL
,
4737 MEM_CGROUP_RECLAIM_SHRINK
);
4738 curusage
= res_counter_read_u64(&memcg
->res
, RES_USAGE
);
4739 /* Usage is reduced ? */
4740 if (curusage
>= oldusage
)
4743 oldusage
= curusage
;
4745 if (!ret
&& enlarge
)
4746 memcg_oom_recover(memcg
);
4751 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup
*memcg
,
4752 unsigned long long val
)
4755 u64 memlimit
, memswlimit
, oldusage
, curusage
;
4756 int children
= mem_cgroup_count_children(memcg
);
4760 /* see mem_cgroup_resize_res_limit */
4761 retry_count
= children
* MEM_CGROUP_RECLAIM_RETRIES
;
4762 oldusage
= res_counter_read_u64(&memcg
->memsw
, RES_USAGE
);
4763 while (retry_count
) {
4764 if (signal_pending(current
)) {
4769 * Rather than hide all in some function, I do this in
4770 * open coded manner. You see what this really does.
4771 * We have to guarantee memcg->res.limit <= memcg->memsw.limit.
4773 mutex_lock(&set_limit_mutex
);
4774 memlimit
= res_counter_read_u64(&memcg
->res
, RES_LIMIT
);
4775 if (memlimit
> val
) {
4777 mutex_unlock(&set_limit_mutex
);
4780 memswlimit
= res_counter_read_u64(&memcg
->memsw
, RES_LIMIT
);
4781 if (memswlimit
< val
)
4783 ret
= res_counter_set_limit(&memcg
->memsw
, val
);
4785 if (memlimit
== val
)
4786 memcg
->memsw_is_minimum
= true;
4788 memcg
->memsw_is_minimum
= false;
4790 mutex_unlock(&set_limit_mutex
);
4795 mem_cgroup_reclaim(memcg
, GFP_KERNEL
,
4796 MEM_CGROUP_RECLAIM_NOSWAP
|
4797 MEM_CGROUP_RECLAIM_SHRINK
);
4798 curusage
= res_counter_read_u64(&memcg
->memsw
, RES_USAGE
);
4799 /* Usage is reduced ? */
4800 if (curusage
>= oldusage
)
4803 oldusage
= curusage
;
4805 if (!ret
&& enlarge
)
4806 memcg_oom_recover(memcg
);
4810 unsigned long mem_cgroup_soft_limit_reclaim(struct zone
*zone
, int order
,
4812 unsigned long *total_scanned
)
4814 unsigned long nr_reclaimed
= 0;
4815 struct mem_cgroup_per_zone
*mz
, *next_mz
= NULL
;
4816 unsigned long reclaimed
;
4818 struct mem_cgroup_tree_per_zone
*mctz
;
4819 unsigned long long excess
;
4820 unsigned long nr_scanned
;
4825 mctz
= soft_limit_tree_node_zone(zone_to_nid(zone
), zone_idx(zone
));
4827 * This loop can run a while, specially if mem_cgroup's continuously
4828 * keep exceeding their soft limit and putting the system under
4835 mz
= mem_cgroup_largest_soft_limit_node(mctz
);
4840 reclaimed
= mem_cgroup_soft_reclaim(mz
->memcg
, zone
,
4841 gfp_mask
, &nr_scanned
);
4842 nr_reclaimed
+= reclaimed
;
4843 *total_scanned
+= nr_scanned
;
4844 spin_lock(&mctz
->lock
);
4847 * If we failed to reclaim anything from this memory cgroup
4848 * it is time to move on to the next cgroup
4854 * Loop until we find yet another one.
4856 * By the time we get the soft_limit lock
4857 * again, someone might have aded the
4858 * group back on the RB tree. Iterate to
4859 * make sure we get a different mem.
4860 * mem_cgroup_largest_soft_limit_node returns
4861 * NULL if no other cgroup is present on
4865 __mem_cgroup_largest_soft_limit_node(mctz
);
4867 css_put(&next_mz
->memcg
->css
);
4868 else /* next_mz == NULL or other memcg */
4872 __mem_cgroup_remove_exceeded(mz
->memcg
, mz
, mctz
);
4873 excess
= res_counter_soft_limit_excess(&mz
->memcg
->res
);
4875 * One school of thought says that we should not add
4876 * back the node to the tree if reclaim returns 0.
4877 * But our reclaim could return 0, simply because due
4878 * to priority we are exposing a smaller subset of
4879 * memory to reclaim from. Consider this as a longer
4882 /* If excess == 0, no tree ops */
4883 __mem_cgroup_insert_exceeded(mz
->memcg
, mz
, mctz
, excess
);
4884 spin_unlock(&mctz
->lock
);
4885 css_put(&mz
->memcg
->css
);
4888 * Could not reclaim anything and there are no more
4889 * mem cgroups to try or we seem to be looping without
4890 * reclaiming anything.
4892 if (!nr_reclaimed
&&
4894 loop
> MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS
))
4896 } while (!nr_reclaimed
);
4898 css_put(&next_mz
->memcg
->css
);
4899 return nr_reclaimed
;
4903 * mem_cgroup_force_empty_list - clears LRU of a group
4904 * @memcg: group to clear
4907 * @lru: lru to to clear
4909 * Traverse a specified page_cgroup list and try to drop them all. This doesn't
4910 * reclaim the pages page themselves - pages are moved to the parent (or root)
4913 static void mem_cgroup_force_empty_list(struct mem_cgroup
*memcg
,
4914 int node
, int zid
, enum lru_list lru
)
4916 struct lruvec
*lruvec
;
4917 unsigned long flags
;
4918 struct list_head
*list
;
4922 zone
= &NODE_DATA(node
)->node_zones
[zid
];
4923 lruvec
= mem_cgroup_zone_lruvec(zone
, memcg
);
4924 list
= &lruvec
->lists
[lru
];
4928 struct page_cgroup
*pc
;
4931 spin_lock_irqsave(&zone
->lru_lock
, flags
);
4932 if (list_empty(list
)) {
4933 spin_unlock_irqrestore(&zone
->lru_lock
, flags
);
4936 page
= list_entry(list
->prev
, struct page
, lru
);
4938 list_move(&page
->lru
, list
);
4940 spin_unlock_irqrestore(&zone
->lru_lock
, flags
);
4943 spin_unlock_irqrestore(&zone
->lru_lock
, flags
);
4945 pc
= lookup_page_cgroup(page
);
4947 if (mem_cgroup_move_parent(page
, pc
, memcg
)) {
4948 /* found lock contention or "pc" is obsolete. */
4953 } while (!list_empty(list
));
4957 * make mem_cgroup's charge to be 0 if there is no task by moving
4958 * all the charges and pages to the parent.
4959 * This enables deleting this mem_cgroup.
4961 * Caller is responsible for holding css reference on the memcg.
4963 static void mem_cgroup_reparent_charges(struct mem_cgroup
*memcg
)
4969 /* This is for making all *used* pages to be on LRU. */
4970 lru_add_drain_all();
4971 drain_all_stock_sync(memcg
);
4972 mem_cgroup_start_move(memcg
);
4973 for_each_node_state(node
, N_MEMORY
) {
4974 for (zid
= 0; zid
< MAX_NR_ZONES
; zid
++) {
4977 mem_cgroup_force_empty_list(memcg
,
4982 mem_cgroup_end_move(memcg
);
4983 memcg_oom_recover(memcg
);
4987 * Kernel memory may not necessarily be trackable to a specific
4988 * process. So they are not migrated, and therefore we can't
4989 * expect their value to drop to 0 here.
4990 * Having res filled up with kmem only is enough.
4992 * This is a safety check because mem_cgroup_force_empty_list
4993 * could have raced with mem_cgroup_replace_page_cache callers
4994 * so the lru seemed empty but the page could have been added
4995 * right after the check. RES_USAGE should be safe as we always
4996 * charge before adding to the LRU.
4998 usage
= res_counter_read_u64(&memcg
->res
, RES_USAGE
) -
4999 res_counter_read_u64(&memcg
->kmem
, RES_USAGE
);
5000 } while (usage
> 0);
5003 static inline bool memcg_has_children(struct mem_cgroup
*memcg
)
5005 lockdep_assert_held(&memcg_create_mutex
);
5007 * The lock does not prevent addition or deletion to the list
5008 * of children, but it prevents a new child from being
5009 * initialized based on this parent in css_online(), so it's
5010 * enough to decide whether hierarchically inherited
5011 * attributes can still be changed or not.
5013 return memcg
->use_hierarchy
&&
5014 !list_empty(&memcg
->css
.cgroup
->children
);
5018 * Reclaims as many pages from the given memcg as possible and moves
5019 * the rest to the parent.
5021 * Caller is responsible for holding css reference for memcg.
5023 static int mem_cgroup_force_empty(struct mem_cgroup
*memcg
)
5025 int nr_retries
= MEM_CGROUP_RECLAIM_RETRIES
;
5026 struct cgroup
*cgrp
= memcg
->css
.cgroup
;
5028 /* returns EBUSY if there is a task or if we come here twice. */
5029 if (cgroup_task_count(cgrp
) || !list_empty(&cgrp
->children
))
5032 /* we call try-to-free pages for make this cgroup empty */
5033 lru_add_drain_all();
5034 /* try to free all pages in this cgroup */
5035 while (nr_retries
&& res_counter_read_u64(&memcg
->res
, RES_USAGE
) > 0) {
5038 if (signal_pending(current
))
5041 progress
= try_to_free_mem_cgroup_pages(memcg
, GFP_KERNEL
,
5045 /* maybe some writeback is necessary */
5046 congestion_wait(BLK_RW_ASYNC
, HZ
/10);
5051 mem_cgroup_reparent_charges(memcg
);
5056 static int mem_cgroup_force_empty_write(struct cgroup_subsys_state
*css
,
5059 struct mem_cgroup
*memcg
= mem_cgroup_from_css(css
);
5061 if (mem_cgroup_is_root(memcg
))
5063 return mem_cgroup_force_empty(memcg
);
5066 static u64
mem_cgroup_hierarchy_read(struct cgroup_subsys_state
*css
,
5069 return mem_cgroup_from_css(css
)->use_hierarchy
;
5072 static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state
*css
,
5073 struct cftype
*cft
, u64 val
)
5076 struct mem_cgroup
*memcg
= mem_cgroup_from_css(css
);
5077 struct mem_cgroup
*parent_memcg
= mem_cgroup_from_css(css_parent(&memcg
->css
));
5079 mutex_lock(&memcg_create_mutex
);
5081 if (memcg
->use_hierarchy
== val
)
5085 * If parent's use_hierarchy is set, we can't make any modifications
5086 * in the child subtrees. If it is unset, then the change can
5087 * occur, provided the current cgroup has no children.
5089 * For the root cgroup, parent_mem is NULL, we allow value to be
5090 * set if there are no children.
5092 if ((!parent_memcg
|| !parent_memcg
->use_hierarchy
) &&
5093 (val
== 1 || val
== 0)) {
5094 if (list_empty(&memcg
->css
.cgroup
->children
))
5095 memcg
->use_hierarchy
= val
;
5102 mutex_unlock(&memcg_create_mutex
);
5108 static unsigned long mem_cgroup_recursive_stat(struct mem_cgroup
*memcg
,
5109 enum mem_cgroup_stat_index idx
)
5111 struct mem_cgroup
*iter
;
5114 /* Per-cpu values can be negative, use a signed accumulator */
5115 for_each_mem_cgroup_tree(iter
, memcg
)
5116 val
+= mem_cgroup_read_stat(iter
, idx
);
5118 if (val
< 0) /* race ? */
5123 static inline u64
mem_cgroup_usage(struct mem_cgroup
*memcg
, bool swap
)
5127 if (!mem_cgroup_is_root(memcg
)) {
5129 return res_counter_read_u64(&memcg
->res
, RES_USAGE
);
5131 return res_counter_read_u64(&memcg
->memsw
, RES_USAGE
);
5135 * Transparent hugepages are still accounted for in MEM_CGROUP_STAT_RSS
5136 * as well as in MEM_CGROUP_STAT_RSS_HUGE.
5138 val
= mem_cgroup_recursive_stat(memcg
, MEM_CGROUP_STAT_CACHE
);
5139 val
+= mem_cgroup_recursive_stat(memcg
, MEM_CGROUP_STAT_RSS
);
5142 val
+= mem_cgroup_recursive_stat(memcg
, MEM_CGROUP_STAT_SWAP
);
5144 return val
<< PAGE_SHIFT
;
5147 static ssize_t
mem_cgroup_read(struct cgroup_subsys_state
*css
,
5148 struct cftype
*cft
, struct file
*file
,
5149 char __user
*buf
, size_t nbytes
, loff_t
*ppos
)
5151 struct mem_cgroup
*memcg
= mem_cgroup_from_css(css
);
5157 type
= MEMFILE_TYPE(cft
->private);
5158 name
= MEMFILE_ATTR(cft
->private);
5162 if (name
== RES_USAGE
)
5163 val
= mem_cgroup_usage(memcg
, false);
5165 val
= res_counter_read_u64(&memcg
->res
, name
);
5168 if (name
== RES_USAGE
)
5169 val
= mem_cgroup_usage(memcg
, true);
5171 val
= res_counter_read_u64(&memcg
->memsw
, name
);
5174 val
= res_counter_read_u64(&memcg
->kmem
, name
);
5180 len
= scnprintf(str
, sizeof(str
), "%llu\n", (unsigned long long)val
);
5181 return simple_read_from_buffer(buf
, nbytes
, ppos
, str
, len
);
5184 static int memcg_update_kmem_limit(struct cgroup_subsys_state
*css
, u64 val
)
5187 #ifdef CONFIG_MEMCG_KMEM
5188 struct mem_cgroup
*memcg
= mem_cgroup_from_css(css
);
5190 * For simplicity, we won't allow this to be disabled. It also can't
5191 * be changed if the cgroup has children already, or if tasks had
5194 * If tasks join before we set the limit, a person looking at
5195 * kmem.usage_in_bytes will have no way to determine when it took
5196 * place, which makes the value quite meaningless.
5198 * After it first became limited, changes in the value of the limit are
5199 * of course permitted.
5201 mutex_lock(&memcg_create_mutex
);
5202 mutex_lock(&set_limit_mutex
);
5203 if (!memcg
->kmem_account_flags
&& val
!= RES_COUNTER_MAX
) {
5204 if (cgroup_task_count(css
->cgroup
) || memcg_has_children(memcg
)) {
5208 ret
= res_counter_set_limit(&memcg
->kmem
, val
);
5211 ret
= memcg_update_cache_sizes(memcg
);
5213 res_counter_set_limit(&memcg
->kmem
, RES_COUNTER_MAX
);
5216 static_key_slow_inc(&memcg_kmem_enabled_key
);
5218 * setting the active bit after the inc will guarantee no one
5219 * starts accounting before all call sites are patched
5221 memcg_kmem_set_active(memcg
);
5223 ret
= res_counter_set_limit(&memcg
->kmem
, val
);
5225 mutex_unlock(&set_limit_mutex
);
5226 mutex_unlock(&memcg_create_mutex
);
5231 #ifdef CONFIG_MEMCG_KMEM
5232 static int memcg_propagate_kmem(struct mem_cgroup
*memcg
)
5235 struct mem_cgroup
*parent
= parent_mem_cgroup(memcg
);
5239 memcg
->kmem_account_flags
= parent
->kmem_account_flags
;
5241 * When that happen, we need to disable the static branch only on those
5242 * memcgs that enabled it. To achieve this, we would be forced to
5243 * complicate the code by keeping track of which memcgs were the ones
5244 * that actually enabled limits, and which ones got it from its
5247 * It is a lot simpler just to do static_key_slow_inc() on every child
5248 * that is accounted.
5250 if (!memcg_kmem_is_active(memcg
))
5254 * __mem_cgroup_free() will issue static_key_slow_dec() because this
5255 * memcg is active already. If the later initialization fails then the
5256 * cgroup core triggers the cleanup so we do not have to do it here.
5258 static_key_slow_inc(&memcg_kmem_enabled_key
);
5260 mutex_lock(&set_limit_mutex
);
5261 memcg_stop_kmem_account();
5262 ret
= memcg_update_cache_sizes(memcg
);
5263 memcg_resume_kmem_account();
5264 mutex_unlock(&set_limit_mutex
);
5268 #endif /* CONFIG_MEMCG_KMEM */
5271 * The user of this function is...
5274 static int mem_cgroup_write(struct cgroup_subsys_state
*css
, struct cftype
*cft
,
5277 struct mem_cgroup
*memcg
= mem_cgroup_from_css(css
);
5280 unsigned long long val
;
5283 type
= MEMFILE_TYPE(cft
->private);
5284 name
= MEMFILE_ATTR(cft
->private);
5288 if (mem_cgroup_is_root(memcg
)) { /* Can't set limit on root */
5292 /* This function does all necessary parse...reuse it */
5293 ret
= res_counter_memparse_write_strategy(buffer
, &val
);
5297 ret
= mem_cgroup_resize_limit(memcg
, val
);
5298 else if (type
== _MEMSWAP
)
5299 ret
= mem_cgroup_resize_memsw_limit(memcg
, val
);
5300 else if (type
== _KMEM
)
5301 ret
= memcg_update_kmem_limit(css
, val
);
5305 case RES_SOFT_LIMIT
:
5306 ret
= res_counter_memparse_write_strategy(buffer
, &val
);
5310 * For memsw, soft limits are hard to implement in terms
5311 * of semantics, for now, we support soft limits for
5312 * control without swap
5315 ret
= res_counter_set_soft_limit(&memcg
->res
, val
);
5320 ret
= -EINVAL
; /* should be BUG() ? */
5326 static void memcg_get_hierarchical_limit(struct mem_cgroup
*memcg
,
5327 unsigned long long *mem_limit
, unsigned long long *memsw_limit
)
5329 unsigned long long min_limit
, min_memsw_limit
, tmp
;
5331 min_limit
= res_counter_read_u64(&memcg
->res
, RES_LIMIT
);
5332 min_memsw_limit
= res_counter_read_u64(&memcg
->memsw
, RES_LIMIT
);
5333 if (!memcg
->use_hierarchy
)
5336 while (css_parent(&memcg
->css
)) {
5337 memcg
= mem_cgroup_from_css(css_parent(&memcg
->css
));
5338 if (!memcg
->use_hierarchy
)
5340 tmp
= res_counter_read_u64(&memcg
->res
, RES_LIMIT
);
5341 min_limit
= min(min_limit
, tmp
);
5342 tmp
= res_counter_read_u64(&memcg
->memsw
, RES_LIMIT
);
5343 min_memsw_limit
= min(min_memsw_limit
, tmp
);
5346 *mem_limit
= min_limit
;
5347 *memsw_limit
= min_memsw_limit
;
5350 static int mem_cgroup_reset(struct cgroup_subsys_state
*css
, unsigned int event
)
5352 struct mem_cgroup
*memcg
= mem_cgroup_from_css(css
);
5356 type
= MEMFILE_TYPE(event
);
5357 name
= MEMFILE_ATTR(event
);
5362 res_counter_reset_max(&memcg
->res
);
5363 else if (type
== _MEMSWAP
)
5364 res_counter_reset_max(&memcg
->memsw
);
5365 else if (type
== _KMEM
)
5366 res_counter_reset_max(&memcg
->kmem
);
5372 res_counter_reset_failcnt(&memcg
->res
);
5373 else if (type
== _MEMSWAP
)
5374 res_counter_reset_failcnt(&memcg
->memsw
);
5375 else if (type
== _KMEM
)
5376 res_counter_reset_failcnt(&memcg
->kmem
);
5385 static u64
mem_cgroup_move_charge_read(struct cgroup_subsys_state
*css
,
5388 return mem_cgroup_from_css(css
)->move_charge_at_immigrate
;
5392 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state
*css
,
5393 struct cftype
*cft
, u64 val
)
5395 struct mem_cgroup
*memcg
= mem_cgroup_from_css(css
);
5397 if (val
>= (1 << NR_MOVE_TYPE
))
5401 * No kind of locking is needed in here, because ->can_attach() will
5402 * check this value once in the beginning of the process, and then carry
5403 * on with stale data. This means that changes to this value will only
5404 * affect task migrations starting after the change.
5406 memcg
->move_charge_at_immigrate
= val
;
5410 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state
*css
,
5411 struct cftype
*cft
, u64 val
)
5418 static int memcg_numa_stat_show(struct cgroup_subsys_state
*css
,
5419 struct cftype
*cft
, struct seq_file
*m
)
5422 unsigned long total_nr
, file_nr
, anon_nr
, unevictable_nr
;
5423 unsigned long node_nr
;
5424 struct mem_cgroup
*memcg
= mem_cgroup_from_css(css
);
5426 total_nr
= mem_cgroup_nr_lru_pages(memcg
, LRU_ALL
);
5427 seq_printf(m
, "total=%lu", total_nr
);
5428 for_each_node_state(nid
, N_MEMORY
) {
5429 node_nr
= mem_cgroup_node_nr_lru_pages(memcg
, nid
, LRU_ALL
);
5430 seq_printf(m
, " N%d=%lu", nid
, node_nr
);
5434 file_nr
= mem_cgroup_nr_lru_pages(memcg
, LRU_ALL_FILE
);
5435 seq_printf(m
, "file=%lu", file_nr
);
5436 for_each_node_state(nid
, N_MEMORY
) {
5437 node_nr
= mem_cgroup_node_nr_lru_pages(memcg
, nid
,
5439 seq_printf(m
, " N%d=%lu", nid
, node_nr
);
5443 anon_nr
= mem_cgroup_nr_lru_pages(memcg
, LRU_ALL_ANON
);
5444 seq_printf(m
, "anon=%lu", anon_nr
);
5445 for_each_node_state(nid
, N_MEMORY
) {
5446 node_nr
= mem_cgroup_node_nr_lru_pages(memcg
, nid
,
5448 seq_printf(m
, " N%d=%lu", nid
, node_nr
);
5452 unevictable_nr
= mem_cgroup_nr_lru_pages(memcg
, BIT(LRU_UNEVICTABLE
));
5453 seq_printf(m
, "unevictable=%lu", unevictable_nr
);
5454 for_each_node_state(nid
, N_MEMORY
) {
5455 node_nr
= mem_cgroup_node_nr_lru_pages(memcg
, nid
,
5456 BIT(LRU_UNEVICTABLE
));
5457 seq_printf(m
, " N%d=%lu", nid
, node_nr
);
5462 #endif /* CONFIG_NUMA */
5464 static inline void mem_cgroup_lru_names_not_uptodate(void)
5466 BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_lru_names
) != NR_LRU_LISTS
);
5469 static int memcg_stat_show(struct cgroup_subsys_state
*css
, struct cftype
*cft
,
5472 struct mem_cgroup
*memcg
= mem_cgroup_from_css(css
);
5473 struct mem_cgroup
*mi
;
5476 for (i
= 0; i
< MEM_CGROUP_STAT_NSTATS
; i
++) {
5477 if (i
== MEM_CGROUP_STAT_SWAP
&& !do_swap_account
)
5479 seq_printf(m
, "%s %ld\n", mem_cgroup_stat_names
[i
],
5480 mem_cgroup_read_stat(memcg
, i
) * PAGE_SIZE
);
5483 for (i
= 0; i
< MEM_CGROUP_EVENTS_NSTATS
; i
++)
5484 seq_printf(m
, "%s %lu\n", mem_cgroup_events_names
[i
],
5485 mem_cgroup_read_events(memcg
, i
));
5487 for (i
= 0; i
< NR_LRU_LISTS
; i
++)
5488 seq_printf(m
, "%s %lu\n", mem_cgroup_lru_names
[i
],
5489 mem_cgroup_nr_lru_pages(memcg
, BIT(i
)) * PAGE_SIZE
);
5491 /* Hierarchical information */
5493 unsigned long long limit
, memsw_limit
;
5494 memcg_get_hierarchical_limit(memcg
, &limit
, &memsw_limit
);
5495 seq_printf(m
, "hierarchical_memory_limit %llu\n", limit
);
5496 if (do_swap_account
)
5497 seq_printf(m
, "hierarchical_memsw_limit %llu\n",
5501 for (i
= 0; i
< MEM_CGROUP_STAT_NSTATS
; i
++) {
5504 if (i
== MEM_CGROUP_STAT_SWAP
&& !do_swap_account
)
5506 for_each_mem_cgroup_tree(mi
, memcg
)
5507 val
+= mem_cgroup_read_stat(mi
, i
) * PAGE_SIZE
;
5508 seq_printf(m
, "total_%s %lld\n", mem_cgroup_stat_names
[i
], val
);
5511 for (i
= 0; i
< MEM_CGROUP_EVENTS_NSTATS
; i
++) {
5512 unsigned long long val
= 0;
5514 for_each_mem_cgroup_tree(mi
, memcg
)
5515 val
+= mem_cgroup_read_events(mi
, i
);
5516 seq_printf(m
, "total_%s %llu\n",
5517 mem_cgroup_events_names
[i
], val
);
5520 for (i
= 0; i
< NR_LRU_LISTS
; i
++) {
5521 unsigned long long val
= 0;
5523 for_each_mem_cgroup_tree(mi
, memcg
)
5524 val
+= mem_cgroup_nr_lru_pages(mi
, BIT(i
)) * PAGE_SIZE
;
5525 seq_printf(m
, "total_%s %llu\n", mem_cgroup_lru_names
[i
], val
);
5528 #ifdef CONFIG_DEBUG_VM
5531 struct mem_cgroup_per_zone
*mz
;
5532 struct zone_reclaim_stat
*rstat
;
5533 unsigned long recent_rotated
[2] = {0, 0};
5534 unsigned long recent_scanned
[2] = {0, 0};
5536 for_each_online_node(nid
)
5537 for (zid
= 0; zid
< MAX_NR_ZONES
; zid
++) {
5538 mz
= mem_cgroup_zoneinfo(memcg
, nid
, zid
);
5539 rstat
= &mz
->lruvec
.reclaim_stat
;
5541 recent_rotated
[0] += rstat
->recent_rotated
[0];
5542 recent_rotated
[1] += rstat
->recent_rotated
[1];
5543 recent_scanned
[0] += rstat
->recent_scanned
[0];
5544 recent_scanned
[1] += rstat
->recent_scanned
[1];
5546 seq_printf(m
, "recent_rotated_anon %lu\n", recent_rotated
[0]);
5547 seq_printf(m
, "recent_rotated_file %lu\n", recent_rotated
[1]);
5548 seq_printf(m
, "recent_scanned_anon %lu\n", recent_scanned
[0]);
5549 seq_printf(m
, "recent_scanned_file %lu\n", recent_scanned
[1]);
5556 static u64
mem_cgroup_swappiness_read(struct cgroup_subsys_state
*css
,
5559 struct mem_cgroup
*memcg
= mem_cgroup_from_css(css
);
5561 return mem_cgroup_swappiness(memcg
);
5564 static int mem_cgroup_swappiness_write(struct cgroup_subsys_state
*css
,
5565 struct cftype
*cft
, u64 val
)
5567 struct mem_cgroup
*memcg
= mem_cgroup_from_css(css
);
5568 struct mem_cgroup
*parent
= mem_cgroup_from_css(css_parent(&memcg
->css
));
5570 if (val
> 100 || !parent
)
5573 mutex_lock(&memcg_create_mutex
);
5575 /* If under hierarchy, only empty-root can set this value */
5576 if ((parent
->use_hierarchy
) || memcg_has_children(memcg
)) {
5577 mutex_unlock(&memcg_create_mutex
);
5581 memcg
->swappiness
= val
;
5583 mutex_unlock(&memcg_create_mutex
);
5588 static void __mem_cgroup_threshold(struct mem_cgroup
*memcg
, bool swap
)
5590 struct mem_cgroup_threshold_ary
*t
;
5596 t
= rcu_dereference(memcg
->thresholds
.primary
);
5598 t
= rcu_dereference(memcg
->memsw_thresholds
.primary
);
5603 usage
= mem_cgroup_usage(memcg
, swap
);
5606 * current_threshold points to threshold just below or equal to usage.
5607 * If it's not true, a threshold was crossed after last
5608 * call of __mem_cgroup_threshold().
5610 i
= t
->current_threshold
;
5613 * Iterate backward over array of thresholds starting from
5614 * current_threshold and check if a threshold is crossed.
5615 * If none of thresholds below usage is crossed, we read
5616 * only one element of the array here.
5618 for (; i
>= 0 && unlikely(t
->entries
[i
].threshold
> usage
); i
--)
5619 eventfd_signal(t
->entries
[i
].eventfd
, 1);
5621 /* i = current_threshold + 1 */
5625 * Iterate forward over array of thresholds starting from
5626 * current_threshold+1 and check if a threshold is crossed.
5627 * If none of thresholds above usage is crossed, we read
5628 * only one element of the array here.
5630 for (; i
< t
->size
&& unlikely(t
->entries
[i
].threshold
<= usage
); i
++)
5631 eventfd_signal(t
->entries
[i
].eventfd
, 1);
5633 /* Update current_threshold */
5634 t
->current_threshold
= i
- 1;
5639 static void mem_cgroup_threshold(struct mem_cgroup
*memcg
)
5642 __mem_cgroup_threshold(memcg
, false);
5643 if (do_swap_account
)
5644 __mem_cgroup_threshold(memcg
, true);
5646 memcg
= parent_mem_cgroup(memcg
);
5650 static int compare_thresholds(const void *a
, const void *b
)
5652 const struct mem_cgroup_threshold
*_a
= a
;
5653 const struct mem_cgroup_threshold
*_b
= b
;
5655 if (_a
->threshold
> _b
->threshold
)
5658 if (_a
->threshold
< _b
->threshold
)
5664 static int mem_cgroup_oom_notify_cb(struct mem_cgroup
*memcg
)
5666 struct mem_cgroup_eventfd_list
*ev
;
5668 spin_lock(&memcg_oom_lock
);
5670 list_for_each_entry(ev
, &memcg
->oom_notify
, list
)
5671 eventfd_signal(ev
->eventfd
, 1);
5673 spin_unlock(&memcg_oom_lock
);
5677 static void mem_cgroup_oom_notify(struct mem_cgroup
*memcg
)
5679 struct mem_cgroup
*iter
;
5681 for_each_mem_cgroup_tree(iter
, memcg
)
5682 mem_cgroup_oom_notify_cb(iter
);
5685 static int mem_cgroup_usage_register_event(struct cgroup_subsys_state
*css
,
5686 struct cftype
*cft
, struct eventfd_ctx
*eventfd
, const char *args
)
5688 struct mem_cgroup
*memcg
= mem_cgroup_from_css(css
);
5689 struct mem_cgroup_thresholds
*thresholds
;
5690 struct mem_cgroup_threshold_ary
*new;
5691 enum res_type type
= MEMFILE_TYPE(cft
->private);
5692 u64 threshold
, usage
;
5695 ret
= res_counter_memparse_write_strategy(args
, &threshold
);
5699 mutex_lock(&memcg
->thresholds_lock
);
5702 thresholds
= &memcg
->thresholds
;
5703 else if (type
== _MEMSWAP
)
5704 thresholds
= &memcg
->memsw_thresholds
;
5708 usage
= mem_cgroup_usage(memcg
, type
== _MEMSWAP
);
5710 /* Check if a threshold crossed before adding a new one */
5711 if (thresholds
->primary
)
5712 __mem_cgroup_threshold(memcg
, type
== _MEMSWAP
);
5714 size
= thresholds
->primary
? thresholds
->primary
->size
+ 1 : 1;
5716 /* Allocate memory for new array of thresholds */
5717 new = kmalloc(sizeof(*new) + size
* sizeof(struct mem_cgroup_threshold
),
5725 /* Copy thresholds (if any) to new array */
5726 if (thresholds
->primary
) {
5727 memcpy(new->entries
, thresholds
->primary
->entries
, (size
- 1) *
5728 sizeof(struct mem_cgroup_threshold
));
5731 /* Add new threshold */
5732 new->entries
[size
- 1].eventfd
= eventfd
;
5733 new->entries
[size
- 1].threshold
= threshold
;
5735 /* Sort thresholds. Registering of new threshold isn't time-critical */
5736 sort(new->entries
, size
, sizeof(struct mem_cgroup_threshold
),
5737 compare_thresholds
, NULL
);
5739 /* Find current threshold */
5740 new->current_threshold
= -1;
5741 for (i
= 0; i
< size
; i
++) {
5742 if (new->entries
[i
].threshold
<= usage
) {
5744 * new->current_threshold will not be used until
5745 * rcu_assign_pointer(), so it's safe to increment
5748 ++new->current_threshold
;
5753 /* Free old spare buffer and save old primary buffer as spare */
5754 kfree(thresholds
->spare
);
5755 thresholds
->spare
= thresholds
->primary
;
5757 rcu_assign_pointer(thresholds
->primary
, new);
5759 /* To be sure that nobody uses thresholds */
5763 mutex_unlock(&memcg
->thresholds_lock
);
5768 static void mem_cgroup_usage_unregister_event(struct cgroup_subsys_state
*css
,
5769 struct cftype
*cft
, struct eventfd_ctx
*eventfd
)
5771 struct mem_cgroup
*memcg
= mem_cgroup_from_css(css
);
5772 struct mem_cgroup_thresholds
*thresholds
;
5773 struct mem_cgroup_threshold_ary
*new;
5774 enum res_type type
= MEMFILE_TYPE(cft
->private);
5778 mutex_lock(&memcg
->thresholds_lock
);
5780 thresholds
= &memcg
->thresholds
;
5781 else if (type
== _MEMSWAP
)
5782 thresholds
= &memcg
->memsw_thresholds
;
5786 if (!thresholds
->primary
)
5789 usage
= mem_cgroup_usage(memcg
, type
== _MEMSWAP
);
5791 /* Check if a threshold crossed before removing */
5792 __mem_cgroup_threshold(memcg
, type
== _MEMSWAP
);
5794 /* Calculate new number of threshold */
5796 for (i
= 0; i
< thresholds
->primary
->size
; i
++) {
5797 if (thresholds
->primary
->entries
[i
].eventfd
!= eventfd
)
5801 new = thresholds
->spare
;
5803 /* Set thresholds array to NULL if we don't have thresholds */
5812 /* Copy thresholds and find current threshold */
5813 new->current_threshold
= -1;
5814 for (i
= 0, j
= 0; i
< thresholds
->primary
->size
; i
++) {
5815 if (thresholds
->primary
->entries
[i
].eventfd
== eventfd
)
5818 new->entries
[j
] = thresholds
->primary
->entries
[i
];
5819 if (new->entries
[j
].threshold
<= usage
) {
5821 * new->current_threshold will not be used
5822 * until rcu_assign_pointer(), so it's safe to increment
5825 ++new->current_threshold
;
5831 /* Swap primary and spare array */
5832 thresholds
->spare
= thresholds
->primary
;
5833 /* If all events are unregistered, free the spare array */
5835 kfree(thresholds
->spare
);
5836 thresholds
->spare
= NULL
;
5839 rcu_assign_pointer(thresholds
->primary
, new);
5841 /* To be sure that nobody uses thresholds */
5844 mutex_unlock(&memcg
->thresholds_lock
);
5847 static int mem_cgroup_oom_register_event(struct cgroup_subsys_state
*css
,
5848 struct cftype
*cft
, struct eventfd_ctx
*eventfd
, const char *args
)
5850 struct mem_cgroup
*memcg
= mem_cgroup_from_css(css
);
5851 struct mem_cgroup_eventfd_list
*event
;
5852 enum res_type type
= MEMFILE_TYPE(cft
->private);
5854 BUG_ON(type
!= _OOM_TYPE
);
5855 event
= kmalloc(sizeof(*event
), GFP_KERNEL
);
5859 spin_lock(&memcg_oom_lock
);
5861 event
->eventfd
= eventfd
;
5862 list_add(&event
->list
, &memcg
->oom_notify
);
5864 /* already in OOM ? */
5865 if (atomic_read(&memcg
->under_oom
))
5866 eventfd_signal(eventfd
, 1);
5867 spin_unlock(&memcg_oom_lock
);
5872 static void mem_cgroup_oom_unregister_event(struct cgroup_subsys_state
*css
,
5873 struct cftype
*cft
, struct eventfd_ctx
*eventfd
)
5875 struct mem_cgroup
*memcg
= mem_cgroup_from_css(css
);
5876 struct mem_cgroup_eventfd_list
*ev
, *tmp
;
5877 enum res_type type
= MEMFILE_TYPE(cft
->private);
5879 BUG_ON(type
!= _OOM_TYPE
);
5881 spin_lock(&memcg_oom_lock
);
5883 list_for_each_entry_safe(ev
, tmp
, &memcg
->oom_notify
, list
) {
5884 if (ev
->eventfd
== eventfd
) {
5885 list_del(&ev
->list
);
5890 spin_unlock(&memcg_oom_lock
);
5893 static int mem_cgroup_oom_control_read(struct cgroup_subsys_state
*css
,
5894 struct cftype
*cft
, struct cgroup_map_cb
*cb
)
5896 struct mem_cgroup
*memcg
= mem_cgroup_from_css(css
);
5898 cb
->fill(cb
, "oom_kill_disable", memcg
->oom_kill_disable
);
5900 if (atomic_read(&memcg
->under_oom
))
5901 cb
->fill(cb
, "under_oom", 1);
5903 cb
->fill(cb
, "under_oom", 0);
5907 static int mem_cgroup_oom_control_write(struct cgroup_subsys_state
*css
,
5908 struct cftype
*cft
, u64 val
)
5910 struct mem_cgroup
*memcg
= mem_cgroup_from_css(css
);
5911 struct mem_cgroup
*parent
= mem_cgroup_from_css(css_parent(&memcg
->css
));
5913 /* cannot set to root cgroup and only 0 and 1 are allowed */
5914 if (!parent
|| !((val
== 0) || (val
== 1)))
5917 mutex_lock(&memcg_create_mutex
);
5918 /* oom-kill-disable is a flag for subhierarchy. */
5919 if ((parent
->use_hierarchy
) || memcg_has_children(memcg
)) {
5920 mutex_unlock(&memcg_create_mutex
);
5923 memcg
->oom_kill_disable
= val
;
5925 memcg_oom_recover(memcg
);
5926 mutex_unlock(&memcg_create_mutex
);
5930 #ifdef CONFIG_MEMCG_KMEM
5931 static int memcg_init_kmem(struct mem_cgroup
*memcg
, struct cgroup_subsys
*ss
)
5935 memcg
->kmemcg_id
= -1;
5936 ret
= memcg_propagate_kmem(memcg
);
5940 return mem_cgroup_sockets_init(memcg
, ss
);
5943 static void memcg_destroy_kmem(struct mem_cgroup
*memcg
)
5945 mem_cgroup_sockets_destroy(memcg
);
5948 static void kmem_cgroup_css_offline(struct mem_cgroup
*memcg
)
5950 if (!memcg_kmem_is_active(memcg
))
5954 * kmem charges can outlive the cgroup. In the case of slab
5955 * pages, for instance, a page contain objects from various
5956 * processes. As we prevent from taking a reference for every
5957 * such allocation we have to be careful when doing uncharge
5958 * (see memcg_uncharge_kmem) and here during offlining.
5960 * The idea is that that only the _last_ uncharge which sees
5961 * the dead memcg will drop the last reference. An additional
5962 * reference is taken here before the group is marked dead
5963 * which is then paired with css_put during uncharge resp. here.
5965 * Although this might sound strange as this path is called from
5966 * css_offline() when the referencemight have dropped down to 0
5967 * and shouldn't be incremented anymore (css_tryget would fail)
5968 * we do not have other options because of the kmem allocations
5971 css_get(&memcg
->css
);
5973 memcg_kmem_mark_dead(memcg
);
5975 if (res_counter_read_u64(&memcg
->kmem
, RES_USAGE
) != 0)
5978 if (memcg_kmem_test_and_clear_dead(memcg
))
5979 css_put(&memcg
->css
);
5982 static int memcg_init_kmem(struct mem_cgroup
*memcg
, struct cgroup_subsys
*ss
)
5987 static void memcg_destroy_kmem(struct mem_cgroup
*memcg
)
5991 static void kmem_cgroup_css_offline(struct mem_cgroup
*memcg
)
5996 static struct cftype mem_cgroup_files
[] = {
5998 .name
= "usage_in_bytes",
5999 .private = MEMFILE_PRIVATE(_MEM
, RES_USAGE
),
6000 .read
= mem_cgroup_read
,
6001 .register_event
= mem_cgroup_usage_register_event
,
6002 .unregister_event
= mem_cgroup_usage_unregister_event
,
6005 .name
= "max_usage_in_bytes",
6006 .private = MEMFILE_PRIVATE(_MEM
, RES_MAX_USAGE
),
6007 .trigger
= mem_cgroup_reset
,
6008 .read
= mem_cgroup_read
,
6011 .name
= "limit_in_bytes",
6012 .private = MEMFILE_PRIVATE(_MEM
, RES_LIMIT
),
6013 .write_string
= mem_cgroup_write
,
6014 .read
= mem_cgroup_read
,
6017 .name
= "soft_limit_in_bytes",
6018 .private = MEMFILE_PRIVATE(_MEM
, RES_SOFT_LIMIT
),
6019 .write_string
= mem_cgroup_write
,
6020 .read
= mem_cgroup_read
,
6024 .private = MEMFILE_PRIVATE(_MEM
, RES_FAILCNT
),
6025 .trigger
= mem_cgroup_reset
,
6026 .read
= mem_cgroup_read
,
6030 .read_seq_string
= memcg_stat_show
,
6033 .name
= "force_empty",
6034 .trigger
= mem_cgroup_force_empty_write
,
6037 .name
= "use_hierarchy",
6038 .flags
= CFTYPE_INSANE
,
6039 .write_u64
= mem_cgroup_hierarchy_write
,
6040 .read_u64
= mem_cgroup_hierarchy_read
,
6043 .name
= "swappiness",
6044 .read_u64
= mem_cgroup_swappiness_read
,
6045 .write_u64
= mem_cgroup_swappiness_write
,
6048 .name
= "move_charge_at_immigrate",
6049 .read_u64
= mem_cgroup_move_charge_read
,
6050 .write_u64
= mem_cgroup_move_charge_write
,
6053 .name
= "oom_control",
6054 .read_map
= mem_cgroup_oom_control_read
,
6055 .write_u64
= mem_cgroup_oom_control_write
,
6056 .register_event
= mem_cgroup_oom_register_event
,
6057 .unregister_event
= mem_cgroup_oom_unregister_event
,
6058 .private = MEMFILE_PRIVATE(_OOM_TYPE
, OOM_CONTROL
),
6061 .name
= "pressure_level",
6062 .register_event
= vmpressure_register_event
,
6063 .unregister_event
= vmpressure_unregister_event
,
6067 .name
= "numa_stat",
6068 .read_seq_string
= memcg_numa_stat_show
,
6071 #ifdef CONFIG_MEMCG_KMEM
6073 .name
= "kmem.limit_in_bytes",
6074 .private = MEMFILE_PRIVATE(_KMEM
, RES_LIMIT
),
6075 .write_string
= mem_cgroup_write
,
6076 .read
= mem_cgroup_read
,
6079 .name
= "kmem.usage_in_bytes",
6080 .private = MEMFILE_PRIVATE(_KMEM
, RES_USAGE
),
6081 .read
= mem_cgroup_read
,
6084 .name
= "kmem.failcnt",
6085 .private = MEMFILE_PRIVATE(_KMEM
, RES_FAILCNT
),
6086 .trigger
= mem_cgroup_reset
,
6087 .read
= mem_cgroup_read
,
6090 .name
= "kmem.max_usage_in_bytes",
6091 .private = MEMFILE_PRIVATE(_KMEM
, RES_MAX_USAGE
),
6092 .trigger
= mem_cgroup_reset
,
6093 .read
= mem_cgroup_read
,
6095 #ifdef CONFIG_SLABINFO
6097 .name
= "kmem.slabinfo",
6098 .read_seq_string
= mem_cgroup_slabinfo_read
,
6102 { }, /* terminate */
6105 #ifdef CONFIG_MEMCG_SWAP
6106 static struct cftype memsw_cgroup_files
[] = {
6108 .name
= "memsw.usage_in_bytes",
6109 .private = MEMFILE_PRIVATE(_MEMSWAP
, RES_USAGE
),
6110 .read
= mem_cgroup_read
,
6111 .register_event
= mem_cgroup_usage_register_event
,
6112 .unregister_event
= mem_cgroup_usage_unregister_event
,
6115 .name
= "memsw.max_usage_in_bytes",
6116 .private = MEMFILE_PRIVATE(_MEMSWAP
, RES_MAX_USAGE
),
6117 .trigger
= mem_cgroup_reset
,
6118 .read
= mem_cgroup_read
,
6121 .name
= "memsw.limit_in_bytes",
6122 .private = MEMFILE_PRIVATE(_MEMSWAP
, RES_LIMIT
),
6123 .write_string
= mem_cgroup_write
,
6124 .read
= mem_cgroup_read
,
6127 .name
= "memsw.failcnt",
6128 .private = MEMFILE_PRIVATE(_MEMSWAP
, RES_FAILCNT
),
6129 .trigger
= mem_cgroup_reset
,
6130 .read
= mem_cgroup_read
,
6132 { }, /* terminate */
6135 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup
*memcg
, int node
)
6137 struct mem_cgroup_per_node
*pn
;
6138 struct mem_cgroup_per_zone
*mz
;
6139 int zone
, tmp
= node
;
6141 * This routine is called against possible nodes.
6142 * But it's BUG to call kmalloc() against offline node.
6144 * TODO: this routine can waste much memory for nodes which will
6145 * never be onlined. It's better to use memory hotplug callback
6148 if (!node_state(node
, N_NORMAL_MEMORY
))
6150 pn
= kzalloc_node(sizeof(*pn
), GFP_KERNEL
, tmp
);
6154 for (zone
= 0; zone
< MAX_NR_ZONES
; zone
++) {
6155 mz
= &pn
->zoneinfo
[zone
];
6156 lruvec_init(&mz
->lruvec
);
6157 mz
->usage_in_excess
= 0;
6158 mz
->on_tree
= false;
6161 memcg
->nodeinfo
[node
] = pn
;
6165 static void free_mem_cgroup_per_zone_info(struct mem_cgroup
*memcg
, int node
)
6167 kfree(memcg
->nodeinfo
[node
]);
6170 static struct mem_cgroup
*mem_cgroup_alloc(void)
6172 struct mem_cgroup
*memcg
;
6173 size_t size
= memcg_size();
6175 /* Can be very big if nr_node_ids is very big */
6176 if (size
< PAGE_SIZE
)
6177 memcg
= kzalloc(size
, GFP_KERNEL
);
6179 memcg
= vzalloc(size
);
6184 memcg
->stat
= alloc_percpu(struct mem_cgroup_stat_cpu
);
6187 spin_lock_init(&memcg
->pcp_counter_lock
);
6191 if (size
< PAGE_SIZE
)
6199 * At destroying mem_cgroup, references from swap_cgroup can remain.
6200 * (scanning all at force_empty is too costly...)
6202 * Instead of clearing all references at force_empty, we remember
6203 * the number of reference from swap_cgroup and free mem_cgroup when
6204 * it goes down to 0.
6206 * Removal of cgroup itself succeeds regardless of refs from swap.
6209 static void __mem_cgroup_free(struct mem_cgroup
*memcg
)
6212 size_t size
= memcg_size();
6214 mem_cgroup_remove_from_trees(memcg
);
6215 free_css_id(&mem_cgroup_subsys
, &memcg
->css
);
6218 free_mem_cgroup_per_zone_info(memcg
, node
);
6220 free_percpu(memcg
->stat
);
6223 * We need to make sure that (at least for now), the jump label
6224 * destruction code runs outside of the cgroup lock. This is because
6225 * get_online_cpus(), which is called from the static_branch update,
6226 * can't be called inside the cgroup_lock. cpusets are the ones
6227 * enforcing this dependency, so if they ever change, we might as well.
6229 * schedule_work() will guarantee this happens. Be careful if you need
6230 * to move this code around, and make sure it is outside
6233 disarm_static_keys(memcg
);
6234 if (size
< PAGE_SIZE
)
6241 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
6243 struct mem_cgroup
*parent_mem_cgroup(struct mem_cgroup
*memcg
)
6245 if (!memcg
->res
.parent
)
6247 return mem_cgroup_from_res_counter(memcg
->res
.parent
, res
);
6249 EXPORT_SYMBOL(parent_mem_cgroup
);
6251 static void __init
mem_cgroup_soft_limit_tree_init(void)
6253 struct mem_cgroup_tree_per_node
*rtpn
;
6254 struct mem_cgroup_tree_per_zone
*rtpz
;
6255 int tmp
, node
, zone
;
6257 for_each_node(node
) {
6259 if (!node_state(node
, N_NORMAL_MEMORY
))
6261 rtpn
= kzalloc_node(sizeof(*rtpn
), GFP_KERNEL
, tmp
);
6264 soft_limit_tree
.rb_tree_per_node
[node
] = rtpn
;
6266 for (zone
= 0; zone
< MAX_NR_ZONES
; zone
++) {
6267 rtpz
= &rtpn
->rb_tree_per_zone
[zone
];
6268 rtpz
->rb_root
= RB_ROOT
;
6269 spin_lock_init(&rtpz
->lock
);
6274 static struct cgroup_subsys_state
* __ref
6275 mem_cgroup_css_alloc(struct cgroup_subsys_state
*parent_css
)
6277 struct mem_cgroup
*memcg
;
6278 long error
= -ENOMEM
;
6281 memcg
= mem_cgroup_alloc();
6283 return ERR_PTR(error
);
6286 if (alloc_mem_cgroup_per_zone_info(memcg
, node
))
6290 if (parent_css
== NULL
) {
6291 root_mem_cgroup
= memcg
;
6292 res_counter_init(&memcg
->res
, NULL
);
6293 res_counter_init(&memcg
->memsw
, NULL
);
6294 res_counter_init(&memcg
->kmem
, NULL
);
6297 memcg
->last_scanned_node
= MAX_NUMNODES
;
6298 INIT_LIST_HEAD(&memcg
->oom_notify
);
6299 memcg
->move_charge_at_immigrate
= 0;
6300 mutex_init(&memcg
->thresholds_lock
);
6301 spin_lock_init(&memcg
->move_lock
);
6302 vmpressure_init(&memcg
->vmpressure
);
6307 __mem_cgroup_free(memcg
);
6308 return ERR_PTR(error
);
6312 mem_cgroup_css_online(struct cgroup_subsys_state
*css
)
6314 struct mem_cgroup
*memcg
= mem_cgroup_from_css(css
);
6315 struct mem_cgroup
*parent
= mem_cgroup_from_css(css_parent(css
));
6321 mutex_lock(&memcg_create_mutex
);
6323 memcg
->use_hierarchy
= parent
->use_hierarchy
;
6324 memcg
->oom_kill_disable
= parent
->oom_kill_disable
;
6325 memcg
->swappiness
= mem_cgroup_swappiness(parent
);
6327 if (parent
->use_hierarchy
) {
6328 res_counter_init(&memcg
->res
, &parent
->res
);
6329 res_counter_init(&memcg
->memsw
, &parent
->memsw
);
6330 res_counter_init(&memcg
->kmem
, &parent
->kmem
);
6333 * No need to take a reference to the parent because cgroup
6334 * core guarantees its existence.
6337 res_counter_init(&memcg
->res
, NULL
);
6338 res_counter_init(&memcg
->memsw
, NULL
);
6339 res_counter_init(&memcg
->kmem
, NULL
);
6341 * Deeper hierachy with use_hierarchy == false doesn't make
6342 * much sense so let cgroup subsystem know about this
6343 * unfortunate state in our controller.
6345 if (parent
!= root_mem_cgroup
)
6346 mem_cgroup_subsys
.broken_hierarchy
= true;
6349 error
= memcg_init_kmem(memcg
, &mem_cgroup_subsys
);
6350 mutex_unlock(&memcg_create_mutex
);
6354 * Make sure the memcg is initialized: mem_cgroup_iter()
6355 * orders reading memcg->initialized against its callers
6356 * reading the memcg members.
6359 memcg
->initialized
= 1;
6365 * Announce all parents that a group from their hierarchy is gone.
6367 static void mem_cgroup_invalidate_reclaim_iterators(struct mem_cgroup
*memcg
)
6369 struct mem_cgroup
*parent
= memcg
;
6371 while ((parent
= parent_mem_cgroup(parent
)))
6372 mem_cgroup_iter_invalidate(parent
);
6375 * if the root memcg is not hierarchical we have to check it
6378 if (!root_mem_cgroup
->use_hierarchy
)
6379 mem_cgroup_iter_invalidate(root_mem_cgroup
);
6382 static void mem_cgroup_css_offline(struct cgroup_subsys_state
*css
)
6384 struct mem_cgroup
*memcg
= mem_cgroup_from_css(css
);
6385 struct cgroup_subsys_state
*iter
;
6387 kmem_cgroup_css_offline(memcg
);
6389 mem_cgroup_invalidate_reclaim_iterators(memcg
);
6392 * This requires that offlining is serialized. Right now that is
6393 * guaranteed because css_killed_work_fn() holds the cgroup_mutex.
6396 css_for_each_descendant_post(iter
, css
) {
6398 mem_cgroup_reparent_charges(mem_cgroup_from_css(iter
));
6403 mem_cgroup_destroy_all_caches(memcg
);
6404 vmpressure_cleanup(&memcg
->vmpressure
);
6407 static void mem_cgroup_css_free(struct cgroup_subsys_state
*css
)
6409 struct mem_cgroup
*memcg
= mem_cgroup_from_css(css
);
6411 * XXX: css_offline() would be where we should reparent all
6412 * memory to prepare the cgroup for destruction. However,
6413 * memcg does not do css_tryget() and res_counter charging
6414 * under the same RCU lock region, which means that charging
6415 * could race with offlining. Offlining only happens to
6416 * cgroups with no tasks in them but charges can show up
6417 * without any tasks from the swapin path when the target
6418 * memcg is looked up from the swapout record and not from the
6419 * current task as it usually is. A race like this can leak
6420 * charges and put pages with stale cgroup pointers into
6424 * lookup_swap_cgroup_id()
6426 * mem_cgroup_lookup()
6429 * disable css_tryget()
6432 * reparent_charges()
6433 * res_counter_charge()
6436 * pc->mem_cgroup = dead memcg
6439 * The bulk of the charges are still moved in offline_css() to
6440 * avoid pinning a lot of pages in case a long-term reference
6441 * like a swapout record is deferring the css_free() to long
6442 * after offlining. But this makes sure we catch any charges
6443 * made after offlining:
6445 mem_cgroup_reparent_charges(memcg
);
6447 memcg_destroy_kmem(memcg
);
6448 __mem_cgroup_free(memcg
);
6452 /* Handlers for move charge at task migration. */
6453 #define PRECHARGE_COUNT_AT_ONCE 256
6454 static int mem_cgroup_do_precharge(unsigned long count
)
6457 int batch_count
= PRECHARGE_COUNT_AT_ONCE
;
6458 struct mem_cgroup
*memcg
= mc
.to
;
6460 if (mem_cgroup_is_root(memcg
)) {
6461 mc
.precharge
+= count
;
6462 /* we don't need css_get for root */
6465 /* try to charge at once */
6467 struct res_counter
*dummy
;
6469 * "memcg" cannot be under rmdir() because we've already checked
6470 * by cgroup_lock_live_cgroup() that it is not removed and we
6471 * are still under the same cgroup_mutex. So we can postpone
6474 if (res_counter_charge(&memcg
->res
, PAGE_SIZE
* count
, &dummy
))
6476 if (do_swap_account
&& res_counter_charge(&memcg
->memsw
,
6477 PAGE_SIZE
* count
, &dummy
)) {
6478 res_counter_uncharge(&memcg
->res
, PAGE_SIZE
* count
);
6481 mc
.precharge
+= count
;
6485 /* fall back to one by one charge */
6487 if (signal_pending(current
)) {
6491 if (!batch_count
--) {
6492 batch_count
= PRECHARGE_COUNT_AT_ONCE
;
6495 ret
= __mem_cgroup_try_charge(NULL
,
6496 GFP_KERNEL
, 1, &memcg
, false);
6498 /* mem_cgroup_clear_mc() will do uncharge later */
6506 * get_mctgt_type - get target type of moving charge
6507 * @vma: the vma the pte to be checked belongs
6508 * @addr: the address corresponding to the pte to be checked
6509 * @ptent: the pte to be checked
6510 * @target: the pointer the target page or swap ent will be stored(can be NULL)
6513 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
6514 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
6515 * move charge. if @target is not NULL, the page is stored in target->page
6516 * with extra refcnt got(Callers should handle it).
6517 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
6518 * target for charge migration. if @target is not NULL, the entry is stored
6521 * Called with pte lock held.
6528 enum mc_target_type
{
6534 static struct page
*mc_handle_present_pte(struct vm_area_struct
*vma
,
6535 unsigned long addr
, pte_t ptent
)
6537 struct page
*page
= vm_normal_page(vma
, addr
, ptent
);
6539 if (!page
|| !page_mapped(page
))
6541 if (PageAnon(page
)) {
6542 /* we don't move shared anon */
6545 } else if (!move_file())
6546 /* we ignore mapcount for file pages */
6548 if (!get_page_unless_zero(page
))
6555 static struct page
*mc_handle_swap_pte(struct vm_area_struct
*vma
,
6556 unsigned long addr
, pte_t ptent
, swp_entry_t
*entry
)
6558 struct page
*page
= NULL
;
6559 swp_entry_t ent
= pte_to_swp_entry(ptent
);
6561 if (!move_anon() || non_swap_entry(ent
))
6564 * Because lookup_swap_cache() updates some statistics counter,
6565 * we call find_get_page() with swapper_space directly.
6567 page
= find_get_page(swap_address_space(ent
), ent
.val
);
6568 if (do_swap_account
)
6569 entry
->val
= ent
.val
;
6574 static struct page
*mc_handle_swap_pte(struct vm_area_struct
*vma
,
6575 unsigned long addr
, pte_t ptent
, swp_entry_t
*entry
)
6581 static struct page
*mc_handle_file_pte(struct vm_area_struct
*vma
,
6582 unsigned long addr
, pte_t ptent
, swp_entry_t
*entry
)
6584 struct page
*page
= NULL
;
6585 struct address_space
*mapping
;
6588 if (!vma
->vm_file
) /* anonymous vma */
6593 mapping
= vma
->vm_file
->f_mapping
;
6594 if (pte_none(ptent
))
6595 pgoff
= linear_page_index(vma
, addr
);
6596 else /* pte_file(ptent) is true */
6597 pgoff
= pte_to_pgoff(ptent
);
6599 /* page is moved even if it's not RSS of this task(page-faulted). */
6600 page
= find_get_page(mapping
, pgoff
);
6603 /* shmem/tmpfs may report page out on swap: account for that too. */
6604 if (radix_tree_exceptional_entry(page
)) {
6605 swp_entry_t swap
= radix_to_swp_entry(page
);
6606 if (do_swap_account
)
6608 page
= find_get_page(swap_address_space(swap
), swap
.val
);
6614 static enum mc_target_type
get_mctgt_type(struct vm_area_struct
*vma
,
6615 unsigned long addr
, pte_t ptent
, union mc_target
*target
)
6617 struct page
*page
= NULL
;
6618 struct page_cgroup
*pc
;
6619 enum mc_target_type ret
= MC_TARGET_NONE
;
6620 swp_entry_t ent
= { .val
= 0 };
6622 if (pte_present(ptent
))
6623 page
= mc_handle_present_pte(vma
, addr
, ptent
);
6624 else if (is_swap_pte(ptent
))
6625 page
= mc_handle_swap_pte(vma
, addr
, ptent
, &ent
);
6626 else if (pte_none(ptent
) || pte_file(ptent
))
6627 page
= mc_handle_file_pte(vma
, addr
, ptent
, &ent
);
6629 if (!page
&& !ent
.val
)
6632 pc
= lookup_page_cgroup(page
);
6634 * Do only loose check w/o page_cgroup lock.
6635 * mem_cgroup_move_account() checks the pc is valid or not under
6638 if (PageCgroupUsed(pc
) && pc
->mem_cgroup
== mc
.from
) {
6639 ret
= MC_TARGET_PAGE
;
6641 target
->page
= page
;
6643 if (!ret
|| !target
)
6646 /* There is a swap entry and a page doesn't exist or isn't charged */
6647 if (ent
.val
&& !ret
&&
6648 css_id(&mc
.from
->css
) == lookup_swap_cgroup_id(ent
)) {
6649 ret
= MC_TARGET_SWAP
;
6656 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
6658 * We don't consider swapping or file mapped pages because THP does not
6659 * support them for now.
6660 * Caller should make sure that pmd_trans_huge(pmd) is true.
6662 static enum mc_target_type
get_mctgt_type_thp(struct vm_area_struct
*vma
,
6663 unsigned long addr
, pmd_t pmd
, union mc_target
*target
)
6665 struct page
*page
= NULL
;
6666 struct page_cgroup
*pc
;
6667 enum mc_target_type ret
= MC_TARGET_NONE
;
6669 page
= pmd_page(pmd
);
6670 VM_BUG_ON(!page
|| !PageHead(page
));
6673 pc
= lookup_page_cgroup(page
);
6674 if (PageCgroupUsed(pc
) && pc
->mem_cgroup
== mc
.from
) {
6675 ret
= MC_TARGET_PAGE
;
6678 target
->page
= page
;
6684 static inline enum mc_target_type
get_mctgt_type_thp(struct vm_area_struct
*vma
,
6685 unsigned long addr
, pmd_t pmd
, union mc_target
*target
)
6687 return MC_TARGET_NONE
;
6691 static int mem_cgroup_count_precharge_pte_range(pmd_t
*pmd
,
6692 unsigned long addr
, unsigned long end
,
6693 struct mm_walk
*walk
)
6695 struct vm_area_struct
*vma
= walk
->private;
6699 if (pmd_trans_huge_lock(pmd
, vma
) == 1) {
6700 if (get_mctgt_type_thp(vma
, addr
, *pmd
, NULL
) == MC_TARGET_PAGE
)
6701 mc
.precharge
+= HPAGE_PMD_NR
;
6702 spin_unlock(&vma
->vm_mm
->page_table_lock
);
6706 if (pmd_trans_unstable(pmd
))
6708 pte
= pte_offset_map_lock(vma
->vm_mm
, pmd
, addr
, &ptl
);
6709 for (; addr
!= end
; pte
++, addr
+= PAGE_SIZE
)
6710 if (get_mctgt_type(vma
, addr
, *pte
, NULL
))
6711 mc
.precharge
++; /* increment precharge temporarily */
6712 pte_unmap_unlock(pte
- 1, ptl
);
6718 static unsigned long mem_cgroup_count_precharge(struct mm_struct
*mm
)
6720 unsigned long precharge
;
6721 struct vm_area_struct
*vma
;
6723 down_read(&mm
->mmap_sem
);
6724 for (vma
= mm
->mmap
; vma
; vma
= vma
->vm_next
) {
6725 struct mm_walk mem_cgroup_count_precharge_walk
= {
6726 .pmd_entry
= mem_cgroup_count_precharge_pte_range
,
6730 if (is_vm_hugetlb_page(vma
))
6732 walk_page_range(vma
->vm_start
, vma
->vm_end
,
6733 &mem_cgroup_count_precharge_walk
);
6735 up_read(&mm
->mmap_sem
);
6737 precharge
= mc
.precharge
;
6743 static int mem_cgroup_precharge_mc(struct mm_struct
*mm
)
6745 unsigned long precharge
= mem_cgroup_count_precharge(mm
);
6747 VM_BUG_ON(mc
.moving_task
);
6748 mc
.moving_task
= current
;
6749 return mem_cgroup_do_precharge(precharge
);
6752 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
6753 static void __mem_cgroup_clear_mc(void)
6755 struct mem_cgroup
*from
= mc
.from
;
6756 struct mem_cgroup
*to
= mc
.to
;
6759 /* we must uncharge all the leftover precharges from mc.to */
6761 __mem_cgroup_cancel_charge(mc
.to
, mc
.precharge
);
6765 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
6766 * we must uncharge here.
6768 if (mc
.moved_charge
) {
6769 __mem_cgroup_cancel_charge(mc
.from
, mc
.moved_charge
);
6770 mc
.moved_charge
= 0;
6772 /* we must fixup refcnts and charges */
6773 if (mc
.moved_swap
) {
6774 /* uncharge swap account from the old cgroup */
6775 if (!mem_cgroup_is_root(mc
.from
))
6776 res_counter_uncharge(&mc
.from
->memsw
,
6777 PAGE_SIZE
* mc
.moved_swap
);
6779 for (i
= 0; i
< mc
.moved_swap
; i
++)
6780 css_put(&mc
.from
->css
);
6782 if (!mem_cgroup_is_root(mc
.to
)) {
6784 * we charged both to->res and to->memsw, so we should
6787 res_counter_uncharge(&mc
.to
->res
,
6788 PAGE_SIZE
* mc
.moved_swap
);
6790 /* we've already done css_get(mc.to) */
6793 memcg_oom_recover(from
);
6794 memcg_oom_recover(to
);
6795 wake_up_all(&mc
.waitq
);
6798 static void mem_cgroup_clear_mc(void)
6800 struct mem_cgroup
*from
= mc
.from
;
6803 * we must clear moving_task before waking up waiters at the end of
6806 mc
.moving_task
= NULL
;
6807 __mem_cgroup_clear_mc();
6808 spin_lock(&mc
.lock
);
6811 spin_unlock(&mc
.lock
);
6812 mem_cgroup_end_move(from
);
6815 static int mem_cgroup_can_attach(struct cgroup_subsys_state
*css
,
6816 struct cgroup_taskset
*tset
)
6818 struct task_struct
*p
= cgroup_taskset_first(tset
);
6820 struct mem_cgroup
*memcg
= mem_cgroup_from_css(css
);
6821 unsigned long move_charge_at_immigrate
;
6824 * We are now commited to this value whatever it is. Changes in this
6825 * tunable will only affect upcoming migrations, not the current one.
6826 * So we need to save it, and keep it going.
6828 move_charge_at_immigrate
= memcg
->move_charge_at_immigrate
;
6829 if (move_charge_at_immigrate
) {
6830 struct mm_struct
*mm
;
6831 struct mem_cgroup
*from
= mem_cgroup_from_task(p
);
6833 VM_BUG_ON(from
== memcg
);
6835 mm
= get_task_mm(p
);
6838 /* We move charges only when we move a owner of the mm */
6839 if (mm
->owner
== p
) {
6842 VM_BUG_ON(mc
.precharge
);
6843 VM_BUG_ON(mc
.moved_charge
);
6844 VM_BUG_ON(mc
.moved_swap
);
6845 mem_cgroup_start_move(from
);
6846 spin_lock(&mc
.lock
);
6849 mc
.immigrate_flags
= move_charge_at_immigrate
;
6850 spin_unlock(&mc
.lock
);
6851 /* We set mc.moving_task later */
6853 ret
= mem_cgroup_precharge_mc(mm
);
6855 mem_cgroup_clear_mc();
6862 static void mem_cgroup_cancel_attach(struct cgroup_subsys_state
*css
,
6863 struct cgroup_taskset
*tset
)
6865 mem_cgroup_clear_mc();
6868 static int mem_cgroup_move_charge_pte_range(pmd_t
*pmd
,
6869 unsigned long addr
, unsigned long end
,
6870 struct mm_walk
*walk
)
6873 struct vm_area_struct
*vma
= walk
->private;
6876 enum mc_target_type target_type
;
6877 union mc_target target
;
6879 struct page_cgroup
*pc
;
6882 * We don't take compound_lock() here but no race with splitting thp
6884 * - if pmd_trans_huge_lock() returns 1, the relevant thp is not
6885 * under splitting, which means there's no concurrent thp split,
6886 * - if another thread runs into split_huge_page() just after we
6887 * entered this if-block, the thread must wait for page table lock
6888 * to be unlocked in __split_huge_page_splitting(), where the main
6889 * part of thp split is not executed yet.
6891 if (pmd_trans_huge_lock(pmd
, vma
) == 1) {
6892 if (mc
.precharge
< HPAGE_PMD_NR
) {
6893 spin_unlock(&vma
->vm_mm
->page_table_lock
);
6896 target_type
= get_mctgt_type_thp(vma
, addr
, *pmd
, &target
);
6897 if (target_type
== MC_TARGET_PAGE
) {
6899 if (!isolate_lru_page(page
)) {
6900 pc
= lookup_page_cgroup(page
);
6901 if (!mem_cgroup_move_account(page
, HPAGE_PMD_NR
,
6902 pc
, mc
.from
, mc
.to
)) {
6903 mc
.precharge
-= HPAGE_PMD_NR
;
6904 mc
.moved_charge
+= HPAGE_PMD_NR
;
6906 putback_lru_page(page
);
6910 spin_unlock(&vma
->vm_mm
->page_table_lock
);
6914 if (pmd_trans_unstable(pmd
))
6917 pte
= pte_offset_map_lock(vma
->vm_mm
, pmd
, addr
, &ptl
);
6918 for (; addr
!= end
; addr
+= PAGE_SIZE
) {
6919 pte_t ptent
= *(pte
++);
6925 switch (get_mctgt_type(vma
, addr
, ptent
, &target
)) {
6926 case MC_TARGET_PAGE
:
6928 if (isolate_lru_page(page
))
6930 pc
= lookup_page_cgroup(page
);
6931 if (!mem_cgroup_move_account(page
, 1, pc
,
6934 /* we uncharge from mc.from later. */
6937 putback_lru_page(page
);
6938 put
: /* get_mctgt_type() gets the page */
6941 case MC_TARGET_SWAP
:
6943 if (!mem_cgroup_move_swap_account(ent
, mc
.from
, mc
.to
)) {
6945 /* we fixup refcnts and charges later. */
6953 pte_unmap_unlock(pte
- 1, ptl
);
6958 * We have consumed all precharges we got in can_attach().
6959 * We try charge one by one, but don't do any additional
6960 * charges to mc.to if we have failed in charge once in attach()
6963 ret
= mem_cgroup_do_precharge(1);
6971 static void mem_cgroup_move_charge(struct mm_struct
*mm
)
6973 struct vm_area_struct
*vma
;
6975 lru_add_drain_all();
6977 if (unlikely(!down_read_trylock(&mm
->mmap_sem
))) {
6979 * Someone who are holding the mmap_sem might be waiting in
6980 * waitq. So we cancel all extra charges, wake up all waiters,
6981 * and retry. Because we cancel precharges, we might not be able
6982 * to move enough charges, but moving charge is a best-effort
6983 * feature anyway, so it wouldn't be a big problem.
6985 __mem_cgroup_clear_mc();
6989 for (vma
= mm
->mmap
; vma
; vma
= vma
->vm_next
) {
6991 struct mm_walk mem_cgroup_move_charge_walk
= {
6992 .pmd_entry
= mem_cgroup_move_charge_pte_range
,
6996 if (is_vm_hugetlb_page(vma
))
6998 ret
= walk_page_range(vma
->vm_start
, vma
->vm_end
,
6999 &mem_cgroup_move_charge_walk
);
7002 * means we have consumed all precharges and failed in
7003 * doing additional charge. Just abandon here.
7007 up_read(&mm
->mmap_sem
);
7010 static void mem_cgroup_move_task(struct cgroup_subsys_state
*css
,
7011 struct cgroup_taskset
*tset
)
7013 struct task_struct
*p
= cgroup_taskset_first(tset
);
7014 struct mm_struct
*mm
= get_task_mm(p
);
7018 mem_cgroup_move_charge(mm
);
7022 mem_cgroup_clear_mc();
7024 #else /* !CONFIG_MMU */
7025 static int mem_cgroup_can_attach(struct cgroup_subsys_state
*css
,
7026 struct cgroup_taskset
*tset
)
7030 static void mem_cgroup_cancel_attach(struct cgroup_subsys_state
*css
,
7031 struct cgroup_taskset
*tset
)
7034 static void mem_cgroup_move_task(struct cgroup_subsys_state
*css
,
7035 struct cgroup_taskset
*tset
)
7041 * Cgroup retains root cgroups across [un]mount cycles making it necessary
7042 * to verify sane_behavior flag on each mount attempt.
7044 static void mem_cgroup_bind(struct cgroup_subsys_state
*root_css
)
7047 * use_hierarchy is forced with sane_behavior. cgroup core
7048 * guarantees that @root doesn't have any children, so turning it
7049 * on for the root memcg is enough.
7051 if (cgroup_sane_behavior(root_css
->cgroup
))
7052 mem_cgroup_from_css(root_css
)->use_hierarchy
= true;
7055 struct cgroup_subsys mem_cgroup_subsys
= {
7057 .subsys_id
= mem_cgroup_subsys_id
,
7058 .css_alloc
= mem_cgroup_css_alloc
,
7059 .css_online
= mem_cgroup_css_online
,
7060 .css_offline
= mem_cgroup_css_offline
,
7061 .css_free
= mem_cgroup_css_free
,
7062 .can_attach
= mem_cgroup_can_attach
,
7063 .cancel_attach
= mem_cgroup_cancel_attach
,
7064 .attach
= mem_cgroup_move_task
,
7065 .bind
= mem_cgroup_bind
,
7066 .base_cftypes
= mem_cgroup_files
,
7071 #ifdef CONFIG_MEMCG_SWAP
7072 static int __init
enable_swap_account(char *s
)
7074 if (!strcmp(s
, "1"))
7075 really_do_swap_account
= 1;
7076 else if (!strcmp(s
, "0"))
7077 really_do_swap_account
= 0;
7080 __setup("swapaccount=", enable_swap_account
);
7082 static void __init
memsw_file_init(void)
7084 WARN_ON(cgroup_add_cftypes(&mem_cgroup_subsys
, memsw_cgroup_files
));
7087 static void __init
enable_swap_cgroup(void)
7089 if (!mem_cgroup_disabled() && really_do_swap_account
) {
7090 do_swap_account
= 1;
7096 static void __init
enable_swap_cgroup(void)
7102 * subsys_initcall() for memory controller.
7104 * Some parts like hotcpu_notifier() have to be initialized from this context
7105 * because of lock dependencies (cgroup_lock -> cpu hotplug) but basically
7106 * everything that doesn't depend on a specific mem_cgroup structure should
7107 * be initialized from here.
7109 static int __init
mem_cgroup_init(void)
7111 hotcpu_notifier(memcg_cpu_hotplug_callback
, 0);
7112 enable_swap_cgroup();
7113 mem_cgroup_soft_limit_tree_init();
7117 subsys_initcall(mem_cgroup_init
);