1 /* memcontrol.c - Memory Controller
3 * Copyright IBM Corporation, 2007
4 * Author Balbir Singh <balbir@linux.vnet.ibm.com>
6 * Copyright 2007 OpenVZ SWsoft Inc
7 * Author: Pavel Emelianov <xemul@openvz.org>
10 * Copyright (C) 2009 Nokia Corporation
11 * Author: Kirill A. Shutemov
13 * Kernel Memory Controller
14 * Copyright (C) 2012 Parallels Inc. and Google Inc.
15 * Authors: Glauber Costa and Suleiman Souhlal
17 * This program is free software; you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation; either version 2 of the License, or
20 * (at your option) any later version.
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
28 #include <linux/res_counter.h>
29 #include <linux/memcontrol.h>
30 #include <linux/cgroup.h>
32 #include <linux/hugetlb.h>
33 #include <linux/pagemap.h>
34 #include <linux/smp.h>
35 #include <linux/page-flags.h>
36 #include <linux/backing-dev.h>
37 #include <linux/bit_spinlock.h>
38 #include <linux/rcupdate.h>
39 #include <linux/limits.h>
40 #include <linux/export.h>
41 #include <linux/mutex.h>
42 #include <linux/rbtree.h>
43 #include <linux/slab.h>
44 #include <linux/swap.h>
45 #include <linux/swapops.h>
46 #include <linux/spinlock.h>
47 #include <linux/eventfd.h>
48 #include <linux/sort.h>
50 #include <linux/seq_file.h>
51 #include <linux/vmalloc.h>
52 #include <linux/mm_inline.h>
53 #include <linux/page_cgroup.h>
54 #include <linux/cpu.h>
55 #include <linux/oom.h>
59 #include <net/tcp_memcontrol.h>
61 #include <asm/uaccess.h>
63 #include <trace/events/vmscan.h>
65 struct cgroup_subsys mem_cgroup_subsys __read_mostly
;
66 EXPORT_SYMBOL(mem_cgroup_subsys
);
68 #define MEM_CGROUP_RECLAIM_RETRIES 5
69 static struct mem_cgroup
*root_mem_cgroup __read_mostly
;
71 #ifdef CONFIG_MEMCG_SWAP
72 /* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
73 int do_swap_account __read_mostly
;
75 /* for remember boot option*/
76 #ifdef CONFIG_MEMCG_SWAP_ENABLED
77 static int really_do_swap_account __initdata
= 1;
79 static int really_do_swap_account __initdata
= 0;
83 #define do_swap_account 0
88 * Statistics for memory cgroup.
90 enum mem_cgroup_stat_index
{
92 * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
94 MEM_CGROUP_STAT_CACHE
, /* # of pages charged as cache */
95 MEM_CGROUP_STAT_RSS
, /* # of pages charged as anon rss */
96 MEM_CGROUP_STAT_FILE_MAPPED
, /* # of pages charged as file rss */
97 MEM_CGROUP_STAT_SWAP
, /* # of pages, swapped out */
98 MEM_CGROUP_STAT_NSTATS
,
101 static const char * const mem_cgroup_stat_names
[] = {
108 enum mem_cgroup_events_index
{
109 MEM_CGROUP_EVENTS_PGPGIN
, /* # of pages paged in */
110 MEM_CGROUP_EVENTS_PGPGOUT
, /* # of pages paged out */
111 MEM_CGROUP_EVENTS_PGFAULT
, /* # of page-faults */
112 MEM_CGROUP_EVENTS_PGMAJFAULT
, /* # of major page-faults */
113 MEM_CGROUP_EVENTS_NSTATS
,
116 static const char * const mem_cgroup_events_names
[] = {
124 * Per memcg event counter is incremented at every pagein/pageout. With THP,
125 * it will be incremated by the number of pages. This counter is used for
126 * for trigger some periodic events. This is straightforward and better
127 * than using jiffies etc. to handle periodic memcg event.
129 enum mem_cgroup_events_target
{
130 MEM_CGROUP_TARGET_THRESH
,
131 MEM_CGROUP_TARGET_SOFTLIMIT
,
132 MEM_CGROUP_TARGET_NUMAINFO
,
135 #define THRESHOLDS_EVENTS_TARGET 128
136 #define SOFTLIMIT_EVENTS_TARGET 1024
137 #define NUMAINFO_EVENTS_TARGET 1024
139 struct mem_cgroup_stat_cpu
{
140 long count
[MEM_CGROUP_STAT_NSTATS
];
141 unsigned long events
[MEM_CGROUP_EVENTS_NSTATS
];
142 unsigned long nr_page_events
;
143 unsigned long targets
[MEM_CGROUP_NTARGETS
];
146 struct mem_cgroup_reclaim_iter
{
147 /* css_id of the last scanned hierarchy member */
149 /* scan generation, increased every round-trip */
150 unsigned int generation
;
154 * per-zone information in memory controller.
156 struct mem_cgroup_per_zone
{
157 struct lruvec lruvec
;
158 unsigned long lru_size
[NR_LRU_LISTS
];
160 struct mem_cgroup_reclaim_iter reclaim_iter
[DEF_PRIORITY
+ 1];
162 struct rb_node tree_node
; /* RB tree node */
163 unsigned long long usage_in_excess
;/* Set to the value by which */
164 /* the soft limit is exceeded*/
166 struct mem_cgroup
*memcg
; /* Back pointer, we cannot */
167 /* use container_of */
170 struct mem_cgroup_per_node
{
171 struct mem_cgroup_per_zone zoneinfo
[MAX_NR_ZONES
];
174 struct mem_cgroup_lru_info
{
175 struct mem_cgroup_per_node
*nodeinfo
[MAX_NUMNODES
];
179 * Cgroups above their limits are maintained in a RB-Tree, independent of
180 * their hierarchy representation
183 struct mem_cgroup_tree_per_zone
{
184 struct rb_root rb_root
;
188 struct mem_cgroup_tree_per_node
{
189 struct mem_cgroup_tree_per_zone rb_tree_per_zone
[MAX_NR_ZONES
];
192 struct mem_cgroup_tree
{
193 struct mem_cgroup_tree_per_node
*rb_tree_per_node
[MAX_NUMNODES
];
196 static struct mem_cgroup_tree soft_limit_tree __read_mostly
;
198 struct mem_cgroup_threshold
{
199 struct eventfd_ctx
*eventfd
;
204 struct mem_cgroup_threshold_ary
{
205 /* An array index points to threshold just below or equal to usage. */
206 int current_threshold
;
207 /* Size of entries[] */
209 /* Array of thresholds */
210 struct mem_cgroup_threshold entries
[0];
213 struct mem_cgroup_thresholds
{
214 /* Primary thresholds array */
215 struct mem_cgroup_threshold_ary
*primary
;
217 * Spare threshold array.
218 * This is needed to make mem_cgroup_unregister_event() "never fail".
219 * It must be able to store at least primary->size - 1 entries.
221 struct mem_cgroup_threshold_ary
*spare
;
225 struct mem_cgroup_eventfd_list
{
226 struct list_head list
;
227 struct eventfd_ctx
*eventfd
;
230 static void mem_cgroup_threshold(struct mem_cgroup
*memcg
);
231 static void mem_cgroup_oom_notify(struct mem_cgroup
*memcg
);
234 * The memory controller data structure. The memory controller controls both
235 * page cache and RSS per cgroup. We would eventually like to provide
236 * statistics based on the statistics developed by Rik Van Riel for clock-pro,
237 * to help the administrator determine what knobs to tune.
239 * TODO: Add a water mark for the memory controller. Reclaim will begin when
240 * we hit the water mark. May be even add a low water mark, such that
241 * no reclaim occurs from a cgroup at it's low water mark, this is
242 * a feature that will be implemented much later in the future.
245 struct cgroup_subsys_state css
;
247 * the counter to account for memory usage
249 struct res_counter res
;
253 * the counter to account for mem+swap usage.
255 struct res_counter memsw
;
258 * rcu_freeing is used only when freeing struct mem_cgroup,
259 * so put it into a union to avoid wasting more memory.
260 * It must be disjoint from the css field. It could be
261 * in a union with the res field, but res plays a much
262 * larger part in mem_cgroup life than memsw, and might
263 * be of interest, even at time of free, when debugging.
264 * So share rcu_head with the less interesting memsw.
266 struct rcu_head rcu_freeing
;
268 * We also need some space for a worker in deferred freeing.
269 * By the time we call it, rcu_freeing is no longer in use.
271 struct work_struct work_freeing
;
275 * the counter to account for kernel memory usage.
277 struct res_counter kmem
;
279 * Per cgroup active and inactive list, similar to the
280 * per zone LRU lists.
282 struct mem_cgroup_lru_info info
;
283 int last_scanned_node
;
285 nodemask_t scan_nodes
;
286 atomic_t numainfo_events
;
287 atomic_t numainfo_updating
;
290 * Should the accounting and control be hierarchical, per subtree?
293 unsigned long kmem_account_flags
; /* See KMEM_ACCOUNTED_*, below */
301 /* OOM-Killer disable */
302 int oom_kill_disable
;
304 /* set when res.limit == memsw.limit */
305 bool memsw_is_minimum
;
307 /* protect arrays of thresholds */
308 struct mutex thresholds_lock
;
310 /* thresholds for memory usage. RCU-protected */
311 struct mem_cgroup_thresholds thresholds
;
313 /* thresholds for mem+swap usage. RCU-protected */
314 struct mem_cgroup_thresholds memsw_thresholds
;
316 /* For oom notifier event fd */
317 struct list_head oom_notify
;
320 * Should we move charges of a task when a task is moved into this
321 * mem_cgroup ? And what type of charges should we move ?
323 unsigned long move_charge_at_immigrate
;
325 * set > 0 if pages under this cgroup are moving to other cgroup.
327 atomic_t moving_account
;
328 /* taken only while moving_account > 0 */
329 spinlock_t move_lock
;
333 struct mem_cgroup_stat_cpu __percpu
*stat
;
335 * used when a cpu is offlined or other synchronizations
336 * See mem_cgroup_read_stat().
338 struct mem_cgroup_stat_cpu nocpu_base
;
339 spinlock_t pcp_counter_lock
;
341 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_INET)
342 struct tcp_memcontrol tcp_mem
;
346 /* internal only representation about the status of kmem accounting. */
348 KMEM_ACCOUNTED_ACTIVE
= 0, /* accounted by this cgroup itself */
349 KMEM_ACCOUNTED_DEAD
, /* dead memcg with pending kmem charges */
352 #define KMEM_ACCOUNTED_MASK (1 << KMEM_ACCOUNTED_ACTIVE)
354 #ifdef CONFIG_MEMCG_KMEM
355 static inline void memcg_kmem_set_active(struct mem_cgroup
*memcg
)
357 set_bit(KMEM_ACCOUNTED_ACTIVE
, &memcg
->kmem_account_flags
);
360 static bool memcg_kmem_is_active(struct mem_cgroup
*memcg
)
362 return test_bit(KMEM_ACCOUNTED_ACTIVE
, &memcg
->kmem_account_flags
);
365 static void memcg_kmem_mark_dead(struct mem_cgroup
*memcg
)
367 if (test_bit(KMEM_ACCOUNTED_ACTIVE
, &memcg
->kmem_account_flags
))
368 set_bit(KMEM_ACCOUNTED_DEAD
, &memcg
->kmem_account_flags
);
371 static bool memcg_kmem_test_and_clear_dead(struct mem_cgroup
*memcg
)
373 return test_and_clear_bit(KMEM_ACCOUNTED_DEAD
,
374 &memcg
->kmem_account_flags
);
378 /* Stuffs for move charges at task migration. */
380 * Types of charges to be moved. "move_charge_at_immitgrate" is treated as a
381 * left-shifted bitmap of these types.
384 MOVE_CHARGE_TYPE_ANON
, /* private anonymous page and swap of it */
385 MOVE_CHARGE_TYPE_FILE
, /* file page(including tmpfs) and swap of it */
389 /* "mc" and its members are protected by cgroup_mutex */
390 static struct move_charge_struct
{
391 spinlock_t lock
; /* for from, to */
392 struct mem_cgroup
*from
;
393 struct mem_cgroup
*to
;
394 unsigned long precharge
;
395 unsigned long moved_charge
;
396 unsigned long moved_swap
;
397 struct task_struct
*moving_task
; /* a task moving charges */
398 wait_queue_head_t waitq
; /* a waitq for other context */
400 .lock
= __SPIN_LOCK_UNLOCKED(mc
.lock
),
401 .waitq
= __WAIT_QUEUE_HEAD_INITIALIZER(mc
.waitq
),
404 static bool move_anon(void)
406 return test_bit(MOVE_CHARGE_TYPE_ANON
,
407 &mc
.to
->move_charge_at_immigrate
);
410 static bool move_file(void)
412 return test_bit(MOVE_CHARGE_TYPE_FILE
,
413 &mc
.to
->move_charge_at_immigrate
);
417 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
418 * limit reclaim to prevent infinite loops, if they ever occur.
420 #define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
421 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
424 MEM_CGROUP_CHARGE_TYPE_CACHE
= 0,
425 MEM_CGROUP_CHARGE_TYPE_ANON
,
426 MEM_CGROUP_CHARGE_TYPE_SWAPOUT
, /* for accounting swapcache */
427 MEM_CGROUP_CHARGE_TYPE_DROP
, /* a page was unused swap cache */
431 /* for encoding cft->private value on file */
439 #define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
440 #define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
441 #define MEMFILE_ATTR(val) ((val) & 0xffff)
442 /* Used for OOM nofiier */
443 #define OOM_CONTROL (0)
446 * Reclaim flags for mem_cgroup_hierarchical_reclaim
448 #define MEM_CGROUP_RECLAIM_NOSWAP_BIT 0x0
449 #define MEM_CGROUP_RECLAIM_NOSWAP (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
450 #define MEM_CGROUP_RECLAIM_SHRINK_BIT 0x1
451 #define MEM_CGROUP_RECLAIM_SHRINK (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
453 static void mem_cgroup_get(struct mem_cgroup
*memcg
);
454 static void mem_cgroup_put(struct mem_cgroup
*memcg
);
457 struct mem_cgroup
*mem_cgroup_from_css(struct cgroup_subsys_state
*s
)
459 return container_of(s
, struct mem_cgroup
, css
);
462 static inline bool mem_cgroup_is_root(struct mem_cgroup
*memcg
)
464 return (memcg
== root_mem_cgroup
);
467 /* Writing them here to avoid exposing memcg's inner layout */
468 #if defined(CONFIG_INET) && defined(CONFIG_MEMCG_KMEM)
470 void sock_update_memcg(struct sock
*sk
)
472 if (mem_cgroup_sockets_enabled
) {
473 struct mem_cgroup
*memcg
;
474 struct cg_proto
*cg_proto
;
476 BUG_ON(!sk
->sk_prot
->proto_cgroup
);
478 /* Socket cloning can throw us here with sk_cgrp already
479 * filled. It won't however, necessarily happen from
480 * process context. So the test for root memcg given
481 * the current task's memcg won't help us in this case.
483 * Respecting the original socket's memcg is a better
484 * decision in this case.
487 BUG_ON(mem_cgroup_is_root(sk
->sk_cgrp
->memcg
));
488 mem_cgroup_get(sk
->sk_cgrp
->memcg
);
493 memcg
= mem_cgroup_from_task(current
);
494 cg_proto
= sk
->sk_prot
->proto_cgroup(memcg
);
495 if (!mem_cgroup_is_root(memcg
) && memcg_proto_active(cg_proto
)) {
496 mem_cgroup_get(memcg
);
497 sk
->sk_cgrp
= cg_proto
;
502 EXPORT_SYMBOL(sock_update_memcg
);
504 void sock_release_memcg(struct sock
*sk
)
506 if (mem_cgroup_sockets_enabled
&& sk
->sk_cgrp
) {
507 struct mem_cgroup
*memcg
;
508 WARN_ON(!sk
->sk_cgrp
->memcg
);
509 memcg
= sk
->sk_cgrp
->memcg
;
510 mem_cgroup_put(memcg
);
514 struct cg_proto
*tcp_proto_cgroup(struct mem_cgroup
*memcg
)
516 if (!memcg
|| mem_cgroup_is_root(memcg
))
519 return &memcg
->tcp_mem
.cg_proto
;
521 EXPORT_SYMBOL(tcp_proto_cgroup
);
523 static void disarm_sock_keys(struct mem_cgroup
*memcg
)
525 if (!memcg_proto_activated(&memcg
->tcp_mem
.cg_proto
))
527 static_key_slow_dec(&memcg_socket_limit_enabled
);
530 static void disarm_sock_keys(struct mem_cgroup
*memcg
)
535 static void drain_all_stock_async(struct mem_cgroup
*memcg
);
537 static struct mem_cgroup_per_zone
*
538 mem_cgroup_zoneinfo(struct mem_cgroup
*memcg
, int nid
, int zid
)
540 return &memcg
->info
.nodeinfo
[nid
]->zoneinfo
[zid
];
543 struct cgroup_subsys_state
*mem_cgroup_css(struct mem_cgroup
*memcg
)
548 static struct mem_cgroup_per_zone
*
549 page_cgroup_zoneinfo(struct mem_cgroup
*memcg
, struct page
*page
)
551 int nid
= page_to_nid(page
);
552 int zid
= page_zonenum(page
);
554 return mem_cgroup_zoneinfo(memcg
, nid
, zid
);
557 static struct mem_cgroup_tree_per_zone
*
558 soft_limit_tree_node_zone(int nid
, int zid
)
560 return &soft_limit_tree
.rb_tree_per_node
[nid
]->rb_tree_per_zone
[zid
];
563 static struct mem_cgroup_tree_per_zone
*
564 soft_limit_tree_from_page(struct page
*page
)
566 int nid
= page_to_nid(page
);
567 int zid
= page_zonenum(page
);
569 return &soft_limit_tree
.rb_tree_per_node
[nid
]->rb_tree_per_zone
[zid
];
573 __mem_cgroup_insert_exceeded(struct mem_cgroup
*memcg
,
574 struct mem_cgroup_per_zone
*mz
,
575 struct mem_cgroup_tree_per_zone
*mctz
,
576 unsigned long long new_usage_in_excess
)
578 struct rb_node
**p
= &mctz
->rb_root
.rb_node
;
579 struct rb_node
*parent
= NULL
;
580 struct mem_cgroup_per_zone
*mz_node
;
585 mz
->usage_in_excess
= new_usage_in_excess
;
586 if (!mz
->usage_in_excess
)
590 mz_node
= rb_entry(parent
, struct mem_cgroup_per_zone
,
592 if (mz
->usage_in_excess
< mz_node
->usage_in_excess
)
595 * We can't avoid mem cgroups that are over their soft
596 * limit by the same amount
598 else if (mz
->usage_in_excess
>= mz_node
->usage_in_excess
)
601 rb_link_node(&mz
->tree_node
, parent
, p
);
602 rb_insert_color(&mz
->tree_node
, &mctz
->rb_root
);
607 __mem_cgroup_remove_exceeded(struct mem_cgroup
*memcg
,
608 struct mem_cgroup_per_zone
*mz
,
609 struct mem_cgroup_tree_per_zone
*mctz
)
613 rb_erase(&mz
->tree_node
, &mctz
->rb_root
);
618 mem_cgroup_remove_exceeded(struct mem_cgroup
*memcg
,
619 struct mem_cgroup_per_zone
*mz
,
620 struct mem_cgroup_tree_per_zone
*mctz
)
622 spin_lock(&mctz
->lock
);
623 __mem_cgroup_remove_exceeded(memcg
, mz
, mctz
);
624 spin_unlock(&mctz
->lock
);
628 static void mem_cgroup_update_tree(struct mem_cgroup
*memcg
, struct page
*page
)
630 unsigned long long excess
;
631 struct mem_cgroup_per_zone
*mz
;
632 struct mem_cgroup_tree_per_zone
*mctz
;
633 int nid
= page_to_nid(page
);
634 int zid
= page_zonenum(page
);
635 mctz
= soft_limit_tree_from_page(page
);
638 * Necessary to update all ancestors when hierarchy is used.
639 * because their event counter is not touched.
641 for (; memcg
; memcg
= parent_mem_cgroup(memcg
)) {
642 mz
= mem_cgroup_zoneinfo(memcg
, nid
, zid
);
643 excess
= res_counter_soft_limit_excess(&memcg
->res
);
645 * We have to update the tree if mz is on RB-tree or
646 * mem is over its softlimit.
648 if (excess
|| mz
->on_tree
) {
649 spin_lock(&mctz
->lock
);
650 /* if on-tree, remove it */
652 __mem_cgroup_remove_exceeded(memcg
, mz
, mctz
);
654 * Insert again. mz->usage_in_excess will be updated.
655 * If excess is 0, no tree ops.
657 __mem_cgroup_insert_exceeded(memcg
, mz
, mctz
, excess
);
658 spin_unlock(&mctz
->lock
);
663 static void mem_cgroup_remove_from_trees(struct mem_cgroup
*memcg
)
666 struct mem_cgroup_per_zone
*mz
;
667 struct mem_cgroup_tree_per_zone
*mctz
;
669 for_each_node(node
) {
670 for (zone
= 0; zone
< MAX_NR_ZONES
; zone
++) {
671 mz
= mem_cgroup_zoneinfo(memcg
, node
, zone
);
672 mctz
= soft_limit_tree_node_zone(node
, zone
);
673 mem_cgroup_remove_exceeded(memcg
, mz
, mctz
);
678 static struct mem_cgroup_per_zone
*
679 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone
*mctz
)
681 struct rb_node
*rightmost
= NULL
;
682 struct mem_cgroup_per_zone
*mz
;
686 rightmost
= rb_last(&mctz
->rb_root
);
688 goto done
; /* Nothing to reclaim from */
690 mz
= rb_entry(rightmost
, struct mem_cgroup_per_zone
, tree_node
);
692 * Remove the node now but someone else can add it back,
693 * we will to add it back at the end of reclaim to its correct
694 * position in the tree.
696 __mem_cgroup_remove_exceeded(mz
->memcg
, mz
, mctz
);
697 if (!res_counter_soft_limit_excess(&mz
->memcg
->res
) ||
698 !css_tryget(&mz
->memcg
->css
))
704 static struct mem_cgroup_per_zone
*
705 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone
*mctz
)
707 struct mem_cgroup_per_zone
*mz
;
709 spin_lock(&mctz
->lock
);
710 mz
= __mem_cgroup_largest_soft_limit_node(mctz
);
711 spin_unlock(&mctz
->lock
);
716 * Implementation Note: reading percpu statistics for memcg.
718 * Both of vmstat[] and percpu_counter has threshold and do periodic
719 * synchronization to implement "quick" read. There are trade-off between
720 * reading cost and precision of value. Then, we may have a chance to implement
721 * a periodic synchronizion of counter in memcg's counter.
723 * But this _read() function is used for user interface now. The user accounts
724 * memory usage by memory cgroup and he _always_ requires exact value because
725 * he accounts memory. Even if we provide quick-and-fuzzy read, we always
726 * have to visit all online cpus and make sum. So, for now, unnecessary
727 * synchronization is not implemented. (just implemented for cpu hotplug)
729 * If there are kernel internal actions which can make use of some not-exact
730 * value, and reading all cpu value can be performance bottleneck in some
731 * common workload, threashold and synchonization as vmstat[] should be
734 static long mem_cgroup_read_stat(struct mem_cgroup
*memcg
,
735 enum mem_cgroup_stat_index idx
)
741 for_each_online_cpu(cpu
)
742 val
+= per_cpu(memcg
->stat
->count
[idx
], cpu
);
743 #ifdef CONFIG_HOTPLUG_CPU
744 spin_lock(&memcg
->pcp_counter_lock
);
745 val
+= memcg
->nocpu_base
.count
[idx
];
746 spin_unlock(&memcg
->pcp_counter_lock
);
752 static void mem_cgroup_swap_statistics(struct mem_cgroup
*memcg
,
755 int val
= (charge
) ? 1 : -1;
756 this_cpu_add(memcg
->stat
->count
[MEM_CGROUP_STAT_SWAP
], val
);
759 static unsigned long mem_cgroup_read_events(struct mem_cgroup
*memcg
,
760 enum mem_cgroup_events_index idx
)
762 unsigned long val
= 0;
765 for_each_online_cpu(cpu
)
766 val
+= per_cpu(memcg
->stat
->events
[idx
], cpu
);
767 #ifdef CONFIG_HOTPLUG_CPU
768 spin_lock(&memcg
->pcp_counter_lock
);
769 val
+= memcg
->nocpu_base
.events
[idx
];
770 spin_unlock(&memcg
->pcp_counter_lock
);
775 static void mem_cgroup_charge_statistics(struct mem_cgroup
*memcg
,
776 bool anon
, int nr_pages
)
781 * Here, RSS means 'mapped anon' and anon's SwapCache. Shmem/tmpfs is
782 * counted as CACHE even if it's on ANON LRU.
785 __this_cpu_add(memcg
->stat
->count
[MEM_CGROUP_STAT_RSS
],
788 __this_cpu_add(memcg
->stat
->count
[MEM_CGROUP_STAT_CACHE
],
791 /* pagein of a big page is an event. So, ignore page size */
793 __this_cpu_inc(memcg
->stat
->events
[MEM_CGROUP_EVENTS_PGPGIN
]);
795 __this_cpu_inc(memcg
->stat
->events
[MEM_CGROUP_EVENTS_PGPGOUT
]);
796 nr_pages
= -nr_pages
; /* for event */
799 __this_cpu_add(memcg
->stat
->nr_page_events
, nr_pages
);
805 mem_cgroup_get_lru_size(struct lruvec
*lruvec
, enum lru_list lru
)
807 struct mem_cgroup_per_zone
*mz
;
809 mz
= container_of(lruvec
, struct mem_cgroup_per_zone
, lruvec
);
810 return mz
->lru_size
[lru
];
814 mem_cgroup_zone_nr_lru_pages(struct mem_cgroup
*memcg
, int nid
, int zid
,
815 unsigned int lru_mask
)
817 struct mem_cgroup_per_zone
*mz
;
819 unsigned long ret
= 0;
821 mz
= mem_cgroup_zoneinfo(memcg
, nid
, zid
);
824 if (BIT(lru
) & lru_mask
)
825 ret
+= mz
->lru_size
[lru
];
831 mem_cgroup_node_nr_lru_pages(struct mem_cgroup
*memcg
,
832 int nid
, unsigned int lru_mask
)
837 for (zid
= 0; zid
< MAX_NR_ZONES
; zid
++)
838 total
+= mem_cgroup_zone_nr_lru_pages(memcg
,
844 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup
*memcg
,
845 unsigned int lru_mask
)
850 for_each_node_state(nid
, N_MEMORY
)
851 total
+= mem_cgroup_node_nr_lru_pages(memcg
, nid
, lru_mask
);
855 static bool mem_cgroup_event_ratelimit(struct mem_cgroup
*memcg
,
856 enum mem_cgroup_events_target target
)
858 unsigned long val
, next
;
860 val
= __this_cpu_read(memcg
->stat
->nr_page_events
);
861 next
= __this_cpu_read(memcg
->stat
->targets
[target
]);
862 /* from time_after() in jiffies.h */
863 if ((long)next
- (long)val
< 0) {
865 case MEM_CGROUP_TARGET_THRESH
:
866 next
= val
+ THRESHOLDS_EVENTS_TARGET
;
868 case MEM_CGROUP_TARGET_SOFTLIMIT
:
869 next
= val
+ SOFTLIMIT_EVENTS_TARGET
;
871 case MEM_CGROUP_TARGET_NUMAINFO
:
872 next
= val
+ NUMAINFO_EVENTS_TARGET
;
877 __this_cpu_write(memcg
->stat
->targets
[target
], next
);
884 * Check events in order.
887 static void memcg_check_events(struct mem_cgroup
*memcg
, struct page
*page
)
890 /* threshold event is triggered in finer grain than soft limit */
891 if (unlikely(mem_cgroup_event_ratelimit(memcg
,
892 MEM_CGROUP_TARGET_THRESH
))) {
894 bool do_numainfo __maybe_unused
;
896 do_softlimit
= mem_cgroup_event_ratelimit(memcg
,
897 MEM_CGROUP_TARGET_SOFTLIMIT
);
899 do_numainfo
= mem_cgroup_event_ratelimit(memcg
,
900 MEM_CGROUP_TARGET_NUMAINFO
);
904 mem_cgroup_threshold(memcg
);
905 if (unlikely(do_softlimit
))
906 mem_cgroup_update_tree(memcg
, page
);
908 if (unlikely(do_numainfo
))
909 atomic_inc(&memcg
->numainfo_events
);
915 struct mem_cgroup
*mem_cgroup_from_cont(struct cgroup
*cont
)
917 return mem_cgroup_from_css(
918 cgroup_subsys_state(cont
, mem_cgroup_subsys_id
));
921 struct mem_cgroup
*mem_cgroup_from_task(struct task_struct
*p
)
924 * mm_update_next_owner() may clear mm->owner to NULL
925 * if it races with swapoff, page migration, etc.
926 * So this can be called with p == NULL.
931 return mem_cgroup_from_css(task_subsys_state(p
, mem_cgroup_subsys_id
));
934 struct mem_cgroup
*try_get_mem_cgroup_from_mm(struct mm_struct
*mm
)
936 struct mem_cgroup
*memcg
= NULL
;
941 * Because we have no locks, mm->owner's may be being moved to other
942 * cgroup. We use css_tryget() here even if this looks
943 * pessimistic (rather than adding locks here).
947 memcg
= mem_cgroup_from_task(rcu_dereference(mm
->owner
));
948 if (unlikely(!memcg
))
950 } while (!css_tryget(&memcg
->css
));
956 * mem_cgroup_iter - iterate over memory cgroup hierarchy
957 * @root: hierarchy root
958 * @prev: previously returned memcg, NULL on first invocation
959 * @reclaim: cookie for shared reclaim walks, NULL for full walks
961 * Returns references to children of the hierarchy below @root, or
962 * @root itself, or %NULL after a full round-trip.
964 * Caller must pass the return value in @prev on subsequent
965 * invocations for reference counting, or use mem_cgroup_iter_break()
966 * to cancel a hierarchy walk before the round-trip is complete.
968 * Reclaimers can specify a zone and a priority level in @reclaim to
969 * divide up the memcgs in the hierarchy among all concurrent
970 * reclaimers operating on the same zone and priority.
972 struct mem_cgroup
*mem_cgroup_iter(struct mem_cgroup
*root
,
973 struct mem_cgroup
*prev
,
974 struct mem_cgroup_reclaim_cookie
*reclaim
)
976 struct mem_cgroup
*memcg
= NULL
;
979 if (mem_cgroup_disabled())
983 root
= root_mem_cgroup
;
985 if (prev
&& !reclaim
)
986 id
= css_id(&prev
->css
);
988 if (prev
&& prev
!= root
)
991 if (!root
->use_hierarchy
&& root
!= root_mem_cgroup
) {
998 struct mem_cgroup_reclaim_iter
*uninitialized_var(iter
);
999 struct cgroup_subsys_state
*css
;
1002 int nid
= zone_to_nid(reclaim
->zone
);
1003 int zid
= zone_idx(reclaim
->zone
);
1004 struct mem_cgroup_per_zone
*mz
;
1006 mz
= mem_cgroup_zoneinfo(root
, nid
, zid
);
1007 iter
= &mz
->reclaim_iter
[reclaim
->priority
];
1008 if (prev
&& reclaim
->generation
!= iter
->generation
)
1010 id
= iter
->position
;
1014 css
= css_get_next(&mem_cgroup_subsys
, id
+ 1, &root
->css
, &id
);
1016 if (css
== &root
->css
|| css_tryget(css
))
1017 memcg
= mem_cgroup_from_css(css
);
1023 iter
->position
= id
;
1026 else if (!prev
&& memcg
)
1027 reclaim
->generation
= iter
->generation
;
1037 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1038 * @root: hierarchy root
1039 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1041 void mem_cgroup_iter_break(struct mem_cgroup
*root
,
1042 struct mem_cgroup
*prev
)
1045 root
= root_mem_cgroup
;
1046 if (prev
&& prev
!= root
)
1047 css_put(&prev
->css
);
1051 * Iteration constructs for visiting all cgroups (under a tree). If
1052 * loops are exited prematurely (break), mem_cgroup_iter_break() must
1053 * be used for reference counting.
1055 #define for_each_mem_cgroup_tree(iter, root) \
1056 for (iter = mem_cgroup_iter(root, NULL, NULL); \
1058 iter = mem_cgroup_iter(root, iter, NULL))
1060 #define for_each_mem_cgroup(iter) \
1061 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
1063 iter = mem_cgroup_iter(NULL, iter, NULL))
1065 void __mem_cgroup_count_vm_event(struct mm_struct
*mm
, enum vm_event_item idx
)
1067 struct mem_cgroup
*memcg
;
1070 memcg
= mem_cgroup_from_task(rcu_dereference(mm
->owner
));
1071 if (unlikely(!memcg
))
1076 this_cpu_inc(memcg
->stat
->events
[MEM_CGROUP_EVENTS_PGFAULT
]);
1079 this_cpu_inc(memcg
->stat
->events
[MEM_CGROUP_EVENTS_PGMAJFAULT
]);
1087 EXPORT_SYMBOL(__mem_cgroup_count_vm_event
);
1090 * mem_cgroup_zone_lruvec - get the lru list vector for a zone and memcg
1091 * @zone: zone of the wanted lruvec
1092 * @memcg: memcg of the wanted lruvec
1094 * Returns the lru list vector holding pages for the given @zone and
1095 * @mem. This can be the global zone lruvec, if the memory controller
1098 struct lruvec
*mem_cgroup_zone_lruvec(struct zone
*zone
,
1099 struct mem_cgroup
*memcg
)
1101 struct mem_cgroup_per_zone
*mz
;
1102 struct lruvec
*lruvec
;
1104 if (mem_cgroup_disabled()) {
1105 lruvec
= &zone
->lruvec
;
1109 mz
= mem_cgroup_zoneinfo(memcg
, zone_to_nid(zone
), zone_idx(zone
));
1110 lruvec
= &mz
->lruvec
;
1113 * Since a node can be onlined after the mem_cgroup was created,
1114 * we have to be prepared to initialize lruvec->zone here;
1115 * and if offlined then reonlined, we need to reinitialize it.
1117 if (unlikely(lruvec
->zone
!= zone
))
1118 lruvec
->zone
= zone
;
1123 * Following LRU functions are allowed to be used without PCG_LOCK.
1124 * Operations are called by routine of global LRU independently from memcg.
1125 * What we have to take care of here is validness of pc->mem_cgroup.
1127 * Changes to pc->mem_cgroup happens when
1130 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
1131 * It is added to LRU before charge.
1132 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
1133 * When moving account, the page is not on LRU. It's isolated.
1137 * mem_cgroup_page_lruvec - return lruvec for adding an lru page
1139 * @zone: zone of the page
1141 struct lruvec
*mem_cgroup_page_lruvec(struct page
*page
, struct zone
*zone
)
1143 struct mem_cgroup_per_zone
*mz
;
1144 struct mem_cgroup
*memcg
;
1145 struct page_cgroup
*pc
;
1146 struct lruvec
*lruvec
;
1148 if (mem_cgroup_disabled()) {
1149 lruvec
= &zone
->lruvec
;
1153 pc
= lookup_page_cgroup(page
);
1154 memcg
= pc
->mem_cgroup
;
1157 * Surreptitiously switch any uncharged offlist page to root:
1158 * an uncharged page off lru does nothing to secure
1159 * its former mem_cgroup from sudden removal.
1161 * Our caller holds lru_lock, and PageCgroupUsed is updated
1162 * under page_cgroup lock: between them, they make all uses
1163 * of pc->mem_cgroup safe.
1165 if (!PageLRU(page
) && !PageCgroupUsed(pc
) && memcg
!= root_mem_cgroup
)
1166 pc
->mem_cgroup
= memcg
= root_mem_cgroup
;
1168 mz
= page_cgroup_zoneinfo(memcg
, page
);
1169 lruvec
= &mz
->lruvec
;
1172 * Since a node can be onlined after the mem_cgroup was created,
1173 * we have to be prepared to initialize lruvec->zone here;
1174 * and if offlined then reonlined, we need to reinitialize it.
1176 if (unlikely(lruvec
->zone
!= zone
))
1177 lruvec
->zone
= zone
;
1182 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1183 * @lruvec: mem_cgroup per zone lru vector
1184 * @lru: index of lru list the page is sitting on
1185 * @nr_pages: positive when adding or negative when removing
1187 * This function must be called when a page is added to or removed from an
1190 void mem_cgroup_update_lru_size(struct lruvec
*lruvec
, enum lru_list lru
,
1193 struct mem_cgroup_per_zone
*mz
;
1194 unsigned long *lru_size
;
1196 if (mem_cgroup_disabled())
1199 mz
= container_of(lruvec
, struct mem_cgroup_per_zone
, lruvec
);
1200 lru_size
= mz
->lru_size
+ lru
;
1201 *lru_size
+= nr_pages
;
1202 VM_BUG_ON((long)(*lru_size
) < 0);
1206 * Checks whether given mem is same or in the root_mem_cgroup's
1209 bool __mem_cgroup_same_or_subtree(const struct mem_cgroup
*root_memcg
,
1210 struct mem_cgroup
*memcg
)
1212 if (root_memcg
== memcg
)
1214 if (!root_memcg
->use_hierarchy
|| !memcg
)
1216 return css_is_ancestor(&memcg
->css
, &root_memcg
->css
);
1219 static bool mem_cgroup_same_or_subtree(const struct mem_cgroup
*root_memcg
,
1220 struct mem_cgroup
*memcg
)
1225 ret
= __mem_cgroup_same_or_subtree(root_memcg
, memcg
);
1230 int task_in_mem_cgroup(struct task_struct
*task
, const struct mem_cgroup
*memcg
)
1233 struct mem_cgroup
*curr
= NULL
;
1234 struct task_struct
*p
;
1236 p
= find_lock_task_mm(task
);
1238 curr
= try_get_mem_cgroup_from_mm(p
->mm
);
1242 * All threads may have already detached their mm's, but the oom
1243 * killer still needs to detect if they have already been oom
1244 * killed to prevent needlessly killing additional tasks.
1247 curr
= mem_cgroup_from_task(task
);
1249 css_get(&curr
->css
);
1255 * We should check use_hierarchy of "memcg" not "curr". Because checking
1256 * use_hierarchy of "curr" here make this function true if hierarchy is
1257 * enabled in "curr" and "curr" is a child of "memcg" in *cgroup*
1258 * hierarchy(even if use_hierarchy is disabled in "memcg").
1260 ret
= mem_cgroup_same_or_subtree(memcg
, curr
);
1261 css_put(&curr
->css
);
1265 int mem_cgroup_inactive_anon_is_low(struct lruvec
*lruvec
)
1267 unsigned long inactive_ratio
;
1268 unsigned long inactive
;
1269 unsigned long active
;
1272 inactive
= mem_cgroup_get_lru_size(lruvec
, LRU_INACTIVE_ANON
);
1273 active
= mem_cgroup_get_lru_size(lruvec
, LRU_ACTIVE_ANON
);
1275 gb
= (inactive
+ active
) >> (30 - PAGE_SHIFT
);
1277 inactive_ratio
= int_sqrt(10 * gb
);
1281 return inactive
* inactive_ratio
< active
;
1284 int mem_cgroup_inactive_file_is_low(struct lruvec
*lruvec
)
1286 unsigned long active
;
1287 unsigned long inactive
;
1289 inactive
= mem_cgroup_get_lru_size(lruvec
, LRU_INACTIVE_FILE
);
1290 active
= mem_cgroup_get_lru_size(lruvec
, LRU_ACTIVE_FILE
);
1292 return (active
> inactive
);
1295 #define mem_cgroup_from_res_counter(counter, member) \
1296 container_of(counter, struct mem_cgroup, member)
1299 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1300 * @memcg: the memory cgroup
1302 * Returns the maximum amount of memory @mem can be charged with, in
1305 static unsigned long mem_cgroup_margin(struct mem_cgroup
*memcg
)
1307 unsigned long long margin
;
1309 margin
= res_counter_margin(&memcg
->res
);
1310 if (do_swap_account
)
1311 margin
= min(margin
, res_counter_margin(&memcg
->memsw
));
1312 return margin
>> PAGE_SHIFT
;
1315 int mem_cgroup_swappiness(struct mem_cgroup
*memcg
)
1317 struct cgroup
*cgrp
= memcg
->css
.cgroup
;
1320 if (cgrp
->parent
== NULL
)
1321 return vm_swappiness
;
1323 return memcg
->swappiness
;
1327 * memcg->moving_account is used for checking possibility that some thread is
1328 * calling move_account(). When a thread on CPU-A starts moving pages under
1329 * a memcg, other threads should check memcg->moving_account under
1330 * rcu_read_lock(), like this:
1334 * memcg->moving_account+1 if (memcg->mocing_account)
1336 * synchronize_rcu() update something.
1341 /* for quick checking without looking up memcg */
1342 atomic_t memcg_moving __read_mostly
;
1344 static void mem_cgroup_start_move(struct mem_cgroup
*memcg
)
1346 atomic_inc(&memcg_moving
);
1347 atomic_inc(&memcg
->moving_account
);
1351 static void mem_cgroup_end_move(struct mem_cgroup
*memcg
)
1354 * Now, mem_cgroup_clear_mc() may call this function with NULL.
1355 * We check NULL in callee rather than caller.
1358 atomic_dec(&memcg_moving
);
1359 atomic_dec(&memcg
->moving_account
);
1364 * 2 routines for checking "mem" is under move_account() or not.
1366 * mem_cgroup_stolen() - checking whether a cgroup is mc.from or not. This
1367 * is used for avoiding races in accounting. If true,
1368 * pc->mem_cgroup may be overwritten.
1370 * mem_cgroup_under_move() - checking a cgroup is mc.from or mc.to or
1371 * under hierarchy of moving cgroups. This is for
1372 * waiting at hith-memory prressure caused by "move".
1375 static bool mem_cgroup_stolen(struct mem_cgroup
*memcg
)
1377 VM_BUG_ON(!rcu_read_lock_held());
1378 return atomic_read(&memcg
->moving_account
) > 0;
1381 static bool mem_cgroup_under_move(struct mem_cgroup
*memcg
)
1383 struct mem_cgroup
*from
;
1384 struct mem_cgroup
*to
;
1387 * Unlike task_move routines, we access mc.to, mc.from not under
1388 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1390 spin_lock(&mc
.lock
);
1396 ret
= mem_cgroup_same_or_subtree(memcg
, from
)
1397 || mem_cgroup_same_or_subtree(memcg
, to
);
1399 spin_unlock(&mc
.lock
);
1403 static bool mem_cgroup_wait_acct_move(struct mem_cgroup
*memcg
)
1405 if (mc
.moving_task
&& current
!= mc
.moving_task
) {
1406 if (mem_cgroup_under_move(memcg
)) {
1408 prepare_to_wait(&mc
.waitq
, &wait
, TASK_INTERRUPTIBLE
);
1409 /* moving charge context might have finished. */
1412 finish_wait(&mc
.waitq
, &wait
);
1420 * Take this lock when
1421 * - a code tries to modify page's memcg while it's USED.
1422 * - a code tries to modify page state accounting in a memcg.
1423 * see mem_cgroup_stolen(), too.
1425 static void move_lock_mem_cgroup(struct mem_cgroup
*memcg
,
1426 unsigned long *flags
)
1428 spin_lock_irqsave(&memcg
->move_lock
, *flags
);
1431 static void move_unlock_mem_cgroup(struct mem_cgroup
*memcg
,
1432 unsigned long *flags
)
1434 spin_unlock_irqrestore(&memcg
->move_lock
, *flags
);
1438 * mem_cgroup_print_oom_info: Called from OOM with tasklist_lock held in read mode.
1439 * @memcg: The memory cgroup that went over limit
1440 * @p: Task that is going to be killed
1442 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1445 void mem_cgroup_print_oom_info(struct mem_cgroup
*memcg
, struct task_struct
*p
)
1447 struct cgroup
*task_cgrp
;
1448 struct cgroup
*mem_cgrp
;
1450 * Need a buffer in BSS, can't rely on allocations. The code relies
1451 * on the assumption that OOM is serialized for memory controller.
1452 * If this assumption is broken, revisit this code.
1454 static char memcg_name
[PATH_MAX
];
1462 mem_cgrp
= memcg
->css
.cgroup
;
1463 task_cgrp
= task_cgroup(p
, mem_cgroup_subsys_id
);
1465 ret
= cgroup_path(task_cgrp
, memcg_name
, PATH_MAX
);
1468 * Unfortunately, we are unable to convert to a useful name
1469 * But we'll still print out the usage information
1476 printk(KERN_INFO
"Task in %s killed", memcg_name
);
1479 ret
= cgroup_path(mem_cgrp
, memcg_name
, PATH_MAX
);
1487 * Continues from above, so we don't need an KERN_ level
1489 printk(KERN_CONT
" as a result of limit of %s\n", memcg_name
);
1492 printk(KERN_INFO
"memory: usage %llukB, limit %llukB, failcnt %llu\n",
1493 res_counter_read_u64(&memcg
->res
, RES_USAGE
) >> 10,
1494 res_counter_read_u64(&memcg
->res
, RES_LIMIT
) >> 10,
1495 res_counter_read_u64(&memcg
->res
, RES_FAILCNT
));
1496 printk(KERN_INFO
"memory+swap: usage %llukB, limit %llukB, "
1498 res_counter_read_u64(&memcg
->memsw
, RES_USAGE
) >> 10,
1499 res_counter_read_u64(&memcg
->memsw
, RES_LIMIT
) >> 10,
1500 res_counter_read_u64(&memcg
->memsw
, RES_FAILCNT
));
1501 printk(KERN_INFO
"kmem: usage %llukB, limit %llukB, failcnt %llu\n",
1502 res_counter_read_u64(&memcg
->kmem
, RES_USAGE
) >> 10,
1503 res_counter_read_u64(&memcg
->kmem
, RES_LIMIT
) >> 10,
1504 res_counter_read_u64(&memcg
->kmem
, RES_FAILCNT
));
1508 * This function returns the number of memcg under hierarchy tree. Returns
1509 * 1(self count) if no children.
1511 static int mem_cgroup_count_children(struct mem_cgroup
*memcg
)
1514 struct mem_cgroup
*iter
;
1516 for_each_mem_cgroup_tree(iter
, memcg
)
1522 * Return the memory (and swap, if configured) limit for a memcg.
1524 static u64
mem_cgroup_get_limit(struct mem_cgroup
*memcg
)
1528 limit
= res_counter_read_u64(&memcg
->res
, RES_LIMIT
);
1531 * Do not consider swap space if we cannot swap due to swappiness
1533 if (mem_cgroup_swappiness(memcg
)) {
1536 limit
+= total_swap_pages
<< PAGE_SHIFT
;
1537 memsw
= res_counter_read_u64(&memcg
->memsw
, RES_LIMIT
);
1540 * If memsw is finite and limits the amount of swap space
1541 * available to this memcg, return that limit.
1543 limit
= min(limit
, memsw
);
1549 static void mem_cgroup_out_of_memory(struct mem_cgroup
*memcg
, gfp_t gfp_mask
,
1552 struct mem_cgroup
*iter
;
1553 unsigned long chosen_points
= 0;
1554 unsigned long totalpages
;
1555 unsigned int points
= 0;
1556 struct task_struct
*chosen
= NULL
;
1559 * If current has a pending SIGKILL, then automatically select it. The
1560 * goal is to allow it to allocate so that it may quickly exit and free
1563 if (fatal_signal_pending(current
)) {
1564 set_thread_flag(TIF_MEMDIE
);
1568 check_panic_on_oom(CONSTRAINT_MEMCG
, gfp_mask
, order
, NULL
);
1569 totalpages
= mem_cgroup_get_limit(memcg
) >> PAGE_SHIFT
? : 1;
1570 for_each_mem_cgroup_tree(iter
, memcg
) {
1571 struct cgroup
*cgroup
= iter
->css
.cgroup
;
1572 struct cgroup_iter it
;
1573 struct task_struct
*task
;
1575 cgroup_iter_start(cgroup
, &it
);
1576 while ((task
= cgroup_iter_next(cgroup
, &it
))) {
1577 switch (oom_scan_process_thread(task
, totalpages
, NULL
,
1579 case OOM_SCAN_SELECT
:
1581 put_task_struct(chosen
);
1583 chosen_points
= ULONG_MAX
;
1584 get_task_struct(chosen
);
1586 case OOM_SCAN_CONTINUE
:
1588 case OOM_SCAN_ABORT
:
1589 cgroup_iter_end(cgroup
, &it
);
1590 mem_cgroup_iter_break(memcg
, iter
);
1592 put_task_struct(chosen
);
1597 points
= oom_badness(task
, memcg
, NULL
, totalpages
);
1598 if (points
> chosen_points
) {
1600 put_task_struct(chosen
);
1602 chosen_points
= points
;
1603 get_task_struct(chosen
);
1606 cgroup_iter_end(cgroup
, &it
);
1611 points
= chosen_points
* 1000 / totalpages
;
1612 oom_kill_process(chosen
, gfp_mask
, order
, points
, totalpages
, memcg
,
1613 NULL
, "Memory cgroup out of memory");
1616 static unsigned long mem_cgroup_reclaim(struct mem_cgroup
*memcg
,
1618 unsigned long flags
)
1620 unsigned long total
= 0;
1621 bool noswap
= false;
1624 if (flags
& MEM_CGROUP_RECLAIM_NOSWAP
)
1626 if (!(flags
& MEM_CGROUP_RECLAIM_SHRINK
) && memcg
->memsw_is_minimum
)
1629 for (loop
= 0; loop
< MEM_CGROUP_MAX_RECLAIM_LOOPS
; loop
++) {
1631 drain_all_stock_async(memcg
);
1632 total
+= try_to_free_mem_cgroup_pages(memcg
, gfp_mask
, noswap
);
1634 * Allow limit shrinkers, which are triggered directly
1635 * by userspace, to catch signals and stop reclaim
1636 * after minimal progress, regardless of the margin.
1638 if (total
&& (flags
& MEM_CGROUP_RECLAIM_SHRINK
))
1640 if (mem_cgroup_margin(memcg
))
1643 * If nothing was reclaimed after two attempts, there
1644 * may be no reclaimable pages in this hierarchy.
1653 * test_mem_cgroup_node_reclaimable
1654 * @memcg: the target memcg
1655 * @nid: the node ID to be checked.
1656 * @noswap : specify true here if the user wants flle only information.
1658 * This function returns whether the specified memcg contains any
1659 * reclaimable pages on a node. Returns true if there are any reclaimable
1660 * pages in the node.
1662 static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup
*memcg
,
1663 int nid
, bool noswap
)
1665 if (mem_cgroup_node_nr_lru_pages(memcg
, nid
, LRU_ALL_FILE
))
1667 if (noswap
|| !total_swap_pages
)
1669 if (mem_cgroup_node_nr_lru_pages(memcg
, nid
, LRU_ALL_ANON
))
1674 #if MAX_NUMNODES > 1
1677 * Always updating the nodemask is not very good - even if we have an empty
1678 * list or the wrong list here, we can start from some node and traverse all
1679 * nodes based on the zonelist. So update the list loosely once per 10 secs.
1682 static void mem_cgroup_may_update_nodemask(struct mem_cgroup
*memcg
)
1686 * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
1687 * pagein/pageout changes since the last update.
1689 if (!atomic_read(&memcg
->numainfo_events
))
1691 if (atomic_inc_return(&memcg
->numainfo_updating
) > 1)
1694 /* make a nodemask where this memcg uses memory from */
1695 memcg
->scan_nodes
= node_states
[N_MEMORY
];
1697 for_each_node_mask(nid
, node_states
[N_MEMORY
]) {
1699 if (!test_mem_cgroup_node_reclaimable(memcg
, nid
, false))
1700 node_clear(nid
, memcg
->scan_nodes
);
1703 atomic_set(&memcg
->numainfo_events
, 0);
1704 atomic_set(&memcg
->numainfo_updating
, 0);
1708 * Selecting a node where we start reclaim from. Because what we need is just
1709 * reducing usage counter, start from anywhere is O,K. Considering
1710 * memory reclaim from current node, there are pros. and cons.
1712 * Freeing memory from current node means freeing memory from a node which
1713 * we'll use or we've used. So, it may make LRU bad. And if several threads
1714 * hit limits, it will see a contention on a node. But freeing from remote
1715 * node means more costs for memory reclaim because of memory latency.
1717 * Now, we use round-robin. Better algorithm is welcomed.
1719 int mem_cgroup_select_victim_node(struct mem_cgroup
*memcg
)
1723 mem_cgroup_may_update_nodemask(memcg
);
1724 node
= memcg
->last_scanned_node
;
1726 node
= next_node(node
, memcg
->scan_nodes
);
1727 if (node
== MAX_NUMNODES
)
1728 node
= first_node(memcg
->scan_nodes
);
1730 * We call this when we hit limit, not when pages are added to LRU.
1731 * No LRU may hold pages because all pages are UNEVICTABLE or
1732 * memcg is too small and all pages are not on LRU. In that case,
1733 * we use curret node.
1735 if (unlikely(node
== MAX_NUMNODES
))
1736 node
= numa_node_id();
1738 memcg
->last_scanned_node
= node
;
1743 * Check all nodes whether it contains reclaimable pages or not.
1744 * For quick scan, we make use of scan_nodes. This will allow us to skip
1745 * unused nodes. But scan_nodes is lazily updated and may not cotain
1746 * enough new information. We need to do double check.
1748 static bool mem_cgroup_reclaimable(struct mem_cgroup
*memcg
, bool noswap
)
1753 * quick check...making use of scan_node.
1754 * We can skip unused nodes.
1756 if (!nodes_empty(memcg
->scan_nodes
)) {
1757 for (nid
= first_node(memcg
->scan_nodes
);
1759 nid
= next_node(nid
, memcg
->scan_nodes
)) {
1761 if (test_mem_cgroup_node_reclaimable(memcg
, nid
, noswap
))
1766 * Check rest of nodes.
1768 for_each_node_state(nid
, N_MEMORY
) {
1769 if (node_isset(nid
, memcg
->scan_nodes
))
1771 if (test_mem_cgroup_node_reclaimable(memcg
, nid
, noswap
))
1778 int mem_cgroup_select_victim_node(struct mem_cgroup
*memcg
)
1783 static bool mem_cgroup_reclaimable(struct mem_cgroup
*memcg
, bool noswap
)
1785 return test_mem_cgroup_node_reclaimable(memcg
, 0, noswap
);
1789 static int mem_cgroup_soft_reclaim(struct mem_cgroup
*root_memcg
,
1792 unsigned long *total_scanned
)
1794 struct mem_cgroup
*victim
= NULL
;
1797 unsigned long excess
;
1798 unsigned long nr_scanned
;
1799 struct mem_cgroup_reclaim_cookie reclaim
= {
1804 excess
= res_counter_soft_limit_excess(&root_memcg
->res
) >> PAGE_SHIFT
;
1807 victim
= mem_cgroup_iter(root_memcg
, victim
, &reclaim
);
1812 * If we have not been able to reclaim
1813 * anything, it might because there are
1814 * no reclaimable pages under this hierarchy
1819 * We want to do more targeted reclaim.
1820 * excess >> 2 is not to excessive so as to
1821 * reclaim too much, nor too less that we keep
1822 * coming back to reclaim from this cgroup
1824 if (total
>= (excess
>> 2) ||
1825 (loop
> MEM_CGROUP_MAX_RECLAIM_LOOPS
))
1830 if (!mem_cgroup_reclaimable(victim
, false))
1832 total
+= mem_cgroup_shrink_node_zone(victim
, gfp_mask
, false,
1834 *total_scanned
+= nr_scanned
;
1835 if (!res_counter_soft_limit_excess(&root_memcg
->res
))
1838 mem_cgroup_iter_break(root_memcg
, victim
);
1843 * Check OOM-Killer is already running under our hierarchy.
1844 * If someone is running, return false.
1845 * Has to be called with memcg_oom_lock
1847 static bool mem_cgroup_oom_lock(struct mem_cgroup
*memcg
)
1849 struct mem_cgroup
*iter
, *failed
= NULL
;
1851 for_each_mem_cgroup_tree(iter
, memcg
) {
1852 if (iter
->oom_lock
) {
1854 * this subtree of our hierarchy is already locked
1855 * so we cannot give a lock.
1858 mem_cgroup_iter_break(memcg
, iter
);
1861 iter
->oom_lock
= true;
1868 * OK, we failed to lock the whole subtree so we have to clean up
1869 * what we set up to the failing subtree
1871 for_each_mem_cgroup_tree(iter
, memcg
) {
1872 if (iter
== failed
) {
1873 mem_cgroup_iter_break(memcg
, iter
);
1876 iter
->oom_lock
= false;
1882 * Has to be called with memcg_oom_lock
1884 static int mem_cgroup_oom_unlock(struct mem_cgroup
*memcg
)
1886 struct mem_cgroup
*iter
;
1888 for_each_mem_cgroup_tree(iter
, memcg
)
1889 iter
->oom_lock
= false;
1893 static void mem_cgroup_mark_under_oom(struct mem_cgroup
*memcg
)
1895 struct mem_cgroup
*iter
;
1897 for_each_mem_cgroup_tree(iter
, memcg
)
1898 atomic_inc(&iter
->under_oom
);
1901 static void mem_cgroup_unmark_under_oom(struct mem_cgroup
*memcg
)
1903 struct mem_cgroup
*iter
;
1906 * When a new child is created while the hierarchy is under oom,
1907 * mem_cgroup_oom_lock() may not be called. We have to use
1908 * atomic_add_unless() here.
1910 for_each_mem_cgroup_tree(iter
, memcg
)
1911 atomic_add_unless(&iter
->under_oom
, -1, 0);
1914 static DEFINE_SPINLOCK(memcg_oom_lock
);
1915 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq
);
1917 struct oom_wait_info
{
1918 struct mem_cgroup
*memcg
;
1922 static int memcg_oom_wake_function(wait_queue_t
*wait
,
1923 unsigned mode
, int sync
, void *arg
)
1925 struct mem_cgroup
*wake_memcg
= (struct mem_cgroup
*)arg
;
1926 struct mem_cgroup
*oom_wait_memcg
;
1927 struct oom_wait_info
*oom_wait_info
;
1929 oom_wait_info
= container_of(wait
, struct oom_wait_info
, wait
);
1930 oom_wait_memcg
= oom_wait_info
->memcg
;
1933 * Both of oom_wait_info->memcg and wake_memcg are stable under us.
1934 * Then we can use css_is_ancestor without taking care of RCU.
1936 if (!mem_cgroup_same_or_subtree(oom_wait_memcg
, wake_memcg
)
1937 && !mem_cgroup_same_or_subtree(wake_memcg
, oom_wait_memcg
))
1939 return autoremove_wake_function(wait
, mode
, sync
, arg
);
1942 static void memcg_wakeup_oom(struct mem_cgroup
*memcg
)
1944 /* for filtering, pass "memcg" as argument. */
1945 __wake_up(&memcg_oom_waitq
, TASK_NORMAL
, 0, memcg
);
1948 static void memcg_oom_recover(struct mem_cgroup
*memcg
)
1950 if (memcg
&& atomic_read(&memcg
->under_oom
))
1951 memcg_wakeup_oom(memcg
);
1955 * try to call OOM killer. returns false if we should exit memory-reclaim loop.
1957 static bool mem_cgroup_handle_oom(struct mem_cgroup
*memcg
, gfp_t mask
,
1960 struct oom_wait_info owait
;
1961 bool locked
, need_to_kill
;
1963 owait
.memcg
= memcg
;
1964 owait
.wait
.flags
= 0;
1965 owait
.wait
.func
= memcg_oom_wake_function
;
1966 owait
.wait
.private = current
;
1967 INIT_LIST_HEAD(&owait
.wait
.task_list
);
1968 need_to_kill
= true;
1969 mem_cgroup_mark_under_oom(memcg
);
1971 /* At first, try to OOM lock hierarchy under memcg.*/
1972 spin_lock(&memcg_oom_lock
);
1973 locked
= mem_cgroup_oom_lock(memcg
);
1975 * Even if signal_pending(), we can't quit charge() loop without
1976 * accounting. So, UNINTERRUPTIBLE is appropriate. But SIGKILL
1977 * under OOM is always welcomed, use TASK_KILLABLE here.
1979 prepare_to_wait(&memcg_oom_waitq
, &owait
.wait
, TASK_KILLABLE
);
1980 if (!locked
|| memcg
->oom_kill_disable
)
1981 need_to_kill
= false;
1983 mem_cgroup_oom_notify(memcg
);
1984 spin_unlock(&memcg_oom_lock
);
1987 finish_wait(&memcg_oom_waitq
, &owait
.wait
);
1988 mem_cgroup_out_of_memory(memcg
, mask
, order
);
1991 finish_wait(&memcg_oom_waitq
, &owait
.wait
);
1993 spin_lock(&memcg_oom_lock
);
1995 mem_cgroup_oom_unlock(memcg
);
1996 memcg_wakeup_oom(memcg
);
1997 spin_unlock(&memcg_oom_lock
);
1999 mem_cgroup_unmark_under_oom(memcg
);
2001 if (test_thread_flag(TIF_MEMDIE
) || fatal_signal_pending(current
))
2003 /* Give chance to dying process */
2004 schedule_timeout_uninterruptible(1);
2009 * Currently used to update mapped file statistics, but the routine can be
2010 * generalized to update other statistics as well.
2012 * Notes: Race condition
2014 * We usually use page_cgroup_lock() for accessing page_cgroup member but
2015 * it tends to be costly. But considering some conditions, we doesn't need
2016 * to do so _always_.
2018 * Considering "charge", lock_page_cgroup() is not required because all
2019 * file-stat operations happen after a page is attached to radix-tree. There
2020 * are no race with "charge".
2022 * Considering "uncharge", we know that memcg doesn't clear pc->mem_cgroup
2023 * at "uncharge" intentionally. So, we always see valid pc->mem_cgroup even
2024 * if there are race with "uncharge". Statistics itself is properly handled
2027 * Considering "move", this is an only case we see a race. To make the race
2028 * small, we check mm->moving_account and detect there are possibility of race
2029 * If there is, we take a lock.
2032 void __mem_cgroup_begin_update_page_stat(struct page
*page
,
2033 bool *locked
, unsigned long *flags
)
2035 struct mem_cgroup
*memcg
;
2036 struct page_cgroup
*pc
;
2038 pc
= lookup_page_cgroup(page
);
2040 memcg
= pc
->mem_cgroup
;
2041 if (unlikely(!memcg
|| !PageCgroupUsed(pc
)))
2044 * If this memory cgroup is not under account moving, we don't
2045 * need to take move_lock_mem_cgroup(). Because we already hold
2046 * rcu_read_lock(), any calls to move_account will be delayed until
2047 * rcu_read_unlock() if mem_cgroup_stolen() == true.
2049 if (!mem_cgroup_stolen(memcg
))
2052 move_lock_mem_cgroup(memcg
, flags
);
2053 if (memcg
!= pc
->mem_cgroup
|| !PageCgroupUsed(pc
)) {
2054 move_unlock_mem_cgroup(memcg
, flags
);
2060 void __mem_cgroup_end_update_page_stat(struct page
*page
, unsigned long *flags
)
2062 struct page_cgroup
*pc
= lookup_page_cgroup(page
);
2065 * It's guaranteed that pc->mem_cgroup never changes while
2066 * lock is held because a routine modifies pc->mem_cgroup
2067 * should take move_lock_mem_cgroup().
2069 move_unlock_mem_cgroup(pc
->mem_cgroup
, flags
);
2072 void mem_cgroup_update_page_stat(struct page
*page
,
2073 enum mem_cgroup_page_stat_item idx
, int val
)
2075 struct mem_cgroup
*memcg
;
2076 struct page_cgroup
*pc
= lookup_page_cgroup(page
);
2077 unsigned long uninitialized_var(flags
);
2079 if (mem_cgroup_disabled())
2082 memcg
= pc
->mem_cgroup
;
2083 if (unlikely(!memcg
|| !PageCgroupUsed(pc
)))
2087 case MEMCG_NR_FILE_MAPPED
:
2088 idx
= MEM_CGROUP_STAT_FILE_MAPPED
;
2094 this_cpu_add(memcg
->stat
->count
[idx
], val
);
2098 * size of first charge trial. "32" comes from vmscan.c's magic value.
2099 * TODO: maybe necessary to use big numbers in big irons.
2101 #define CHARGE_BATCH 32U
2102 struct memcg_stock_pcp
{
2103 struct mem_cgroup
*cached
; /* this never be root cgroup */
2104 unsigned int nr_pages
;
2105 struct work_struct work
;
2106 unsigned long flags
;
2107 #define FLUSHING_CACHED_CHARGE 0
2109 static DEFINE_PER_CPU(struct memcg_stock_pcp
, memcg_stock
);
2110 static DEFINE_MUTEX(percpu_charge_mutex
);
2113 * consume_stock: Try to consume stocked charge on this cpu.
2114 * @memcg: memcg to consume from.
2115 * @nr_pages: how many pages to charge.
2117 * The charges will only happen if @memcg matches the current cpu's memcg
2118 * stock, and at least @nr_pages are available in that stock. Failure to
2119 * service an allocation will refill the stock.
2121 * returns true if successful, false otherwise.
2123 static bool consume_stock(struct mem_cgroup
*memcg
, unsigned int nr_pages
)
2125 struct memcg_stock_pcp
*stock
;
2128 if (nr_pages
> CHARGE_BATCH
)
2131 stock
= &get_cpu_var(memcg_stock
);
2132 if (memcg
== stock
->cached
&& stock
->nr_pages
>= nr_pages
)
2133 stock
->nr_pages
-= nr_pages
;
2134 else /* need to call res_counter_charge */
2136 put_cpu_var(memcg_stock
);
2141 * Returns stocks cached in percpu to res_counter and reset cached information.
2143 static void drain_stock(struct memcg_stock_pcp
*stock
)
2145 struct mem_cgroup
*old
= stock
->cached
;
2147 if (stock
->nr_pages
) {
2148 unsigned long bytes
= stock
->nr_pages
* PAGE_SIZE
;
2150 res_counter_uncharge(&old
->res
, bytes
);
2151 if (do_swap_account
)
2152 res_counter_uncharge(&old
->memsw
, bytes
);
2153 stock
->nr_pages
= 0;
2155 stock
->cached
= NULL
;
2159 * This must be called under preempt disabled or must be called by
2160 * a thread which is pinned to local cpu.
2162 static void drain_local_stock(struct work_struct
*dummy
)
2164 struct memcg_stock_pcp
*stock
= &__get_cpu_var(memcg_stock
);
2166 clear_bit(FLUSHING_CACHED_CHARGE
, &stock
->flags
);
2170 * Cache charges(val) which is from res_counter, to local per_cpu area.
2171 * This will be consumed by consume_stock() function, later.
2173 static void refill_stock(struct mem_cgroup
*memcg
, unsigned int nr_pages
)
2175 struct memcg_stock_pcp
*stock
= &get_cpu_var(memcg_stock
);
2177 if (stock
->cached
!= memcg
) { /* reset if necessary */
2179 stock
->cached
= memcg
;
2181 stock
->nr_pages
+= nr_pages
;
2182 put_cpu_var(memcg_stock
);
2186 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2187 * of the hierarchy under it. sync flag says whether we should block
2188 * until the work is done.
2190 static void drain_all_stock(struct mem_cgroup
*root_memcg
, bool sync
)
2194 /* Notify other cpus that system-wide "drain" is running */
2197 for_each_online_cpu(cpu
) {
2198 struct memcg_stock_pcp
*stock
= &per_cpu(memcg_stock
, cpu
);
2199 struct mem_cgroup
*memcg
;
2201 memcg
= stock
->cached
;
2202 if (!memcg
|| !stock
->nr_pages
)
2204 if (!mem_cgroup_same_or_subtree(root_memcg
, memcg
))
2206 if (!test_and_set_bit(FLUSHING_CACHED_CHARGE
, &stock
->flags
)) {
2208 drain_local_stock(&stock
->work
);
2210 schedule_work_on(cpu
, &stock
->work
);
2218 for_each_online_cpu(cpu
) {
2219 struct memcg_stock_pcp
*stock
= &per_cpu(memcg_stock
, cpu
);
2220 if (test_bit(FLUSHING_CACHED_CHARGE
, &stock
->flags
))
2221 flush_work(&stock
->work
);
2228 * Tries to drain stocked charges in other cpus. This function is asynchronous
2229 * and just put a work per cpu for draining localy on each cpu. Caller can
2230 * expects some charges will be back to res_counter later but cannot wait for
2233 static void drain_all_stock_async(struct mem_cgroup
*root_memcg
)
2236 * If someone calls draining, avoid adding more kworker runs.
2238 if (!mutex_trylock(&percpu_charge_mutex
))
2240 drain_all_stock(root_memcg
, false);
2241 mutex_unlock(&percpu_charge_mutex
);
2244 /* This is a synchronous drain interface. */
2245 static void drain_all_stock_sync(struct mem_cgroup
*root_memcg
)
2247 /* called when force_empty is called */
2248 mutex_lock(&percpu_charge_mutex
);
2249 drain_all_stock(root_memcg
, true);
2250 mutex_unlock(&percpu_charge_mutex
);
2254 * This function drains percpu counter value from DEAD cpu and
2255 * move it to local cpu. Note that this function can be preempted.
2257 static void mem_cgroup_drain_pcp_counter(struct mem_cgroup
*memcg
, int cpu
)
2261 spin_lock(&memcg
->pcp_counter_lock
);
2262 for (i
= 0; i
< MEM_CGROUP_STAT_NSTATS
; i
++) {
2263 long x
= per_cpu(memcg
->stat
->count
[i
], cpu
);
2265 per_cpu(memcg
->stat
->count
[i
], cpu
) = 0;
2266 memcg
->nocpu_base
.count
[i
] += x
;
2268 for (i
= 0; i
< MEM_CGROUP_EVENTS_NSTATS
; i
++) {
2269 unsigned long x
= per_cpu(memcg
->stat
->events
[i
], cpu
);
2271 per_cpu(memcg
->stat
->events
[i
], cpu
) = 0;
2272 memcg
->nocpu_base
.events
[i
] += x
;
2274 spin_unlock(&memcg
->pcp_counter_lock
);
2277 static int __cpuinit
memcg_cpu_hotplug_callback(struct notifier_block
*nb
,
2278 unsigned long action
,
2281 int cpu
= (unsigned long)hcpu
;
2282 struct memcg_stock_pcp
*stock
;
2283 struct mem_cgroup
*iter
;
2285 if (action
== CPU_ONLINE
)
2288 if (action
!= CPU_DEAD
&& action
!= CPU_DEAD_FROZEN
)
2291 for_each_mem_cgroup(iter
)
2292 mem_cgroup_drain_pcp_counter(iter
, cpu
);
2294 stock
= &per_cpu(memcg_stock
, cpu
);
2300 /* See __mem_cgroup_try_charge() for details */
2302 CHARGE_OK
, /* success */
2303 CHARGE_RETRY
, /* need to retry but retry is not bad */
2304 CHARGE_NOMEM
, /* we can't do more. return -ENOMEM */
2305 CHARGE_WOULDBLOCK
, /* GFP_WAIT wasn't set and no enough res. */
2306 CHARGE_OOM_DIE
, /* the current is killed because of OOM */
2309 static int mem_cgroup_do_charge(struct mem_cgroup
*memcg
, gfp_t gfp_mask
,
2310 unsigned int nr_pages
, unsigned int min_pages
,
2313 unsigned long csize
= nr_pages
* PAGE_SIZE
;
2314 struct mem_cgroup
*mem_over_limit
;
2315 struct res_counter
*fail_res
;
2316 unsigned long flags
= 0;
2319 ret
= res_counter_charge(&memcg
->res
, csize
, &fail_res
);
2322 if (!do_swap_account
)
2324 ret
= res_counter_charge(&memcg
->memsw
, csize
, &fail_res
);
2328 res_counter_uncharge(&memcg
->res
, csize
);
2329 mem_over_limit
= mem_cgroup_from_res_counter(fail_res
, memsw
);
2330 flags
|= MEM_CGROUP_RECLAIM_NOSWAP
;
2332 mem_over_limit
= mem_cgroup_from_res_counter(fail_res
, res
);
2334 * Never reclaim on behalf of optional batching, retry with a
2335 * single page instead.
2337 if (nr_pages
> min_pages
)
2338 return CHARGE_RETRY
;
2340 if (!(gfp_mask
& __GFP_WAIT
))
2341 return CHARGE_WOULDBLOCK
;
2343 if (gfp_mask
& __GFP_NORETRY
)
2344 return CHARGE_NOMEM
;
2346 ret
= mem_cgroup_reclaim(mem_over_limit
, gfp_mask
, flags
);
2347 if (mem_cgroup_margin(mem_over_limit
) >= nr_pages
)
2348 return CHARGE_RETRY
;
2350 * Even though the limit is exceeded at this point, reclaim
2351 * may have been able to free some pages. Retry the charge
2352 * before killing the task.
2354 * Only for regular pages, though: huge pages are rather
2355 * unlikely to succeed so close to the limit, and we fall back
2356 * to regular pages anyway in case of failure.
2358 if (nr_pages
<= (1 << PAGE_ALLOC_COSTLY_ORDER
) && ret
)
2359 return CHARGE_RETRY
;
2362 * At task move, charge accounts can be doubly counted. So, it's
2363 * better to wait until the end of task_move if something is going on.
2365 if (mem_cgroup_wait_acct_move(mem_over_limit
))
2366 return CHARGE_RETRY
;
2368 /* If we don't need to call oom-killer at el, return immediately */
2370 return CHARGE_NOMEM
;
2372 if (!mem_cgroup_handle_oom(mem_over_limit
, gfp_mask
, get_order(csize
)))
2373 return CHARGE_OOM_DIE
;
2375 return CHARGE_RETRY
;
2379 * __mem_cgroup_try_charge() does
2380 * 1. detect memcg to be charged against from passed *mm and *ptr,
2381 * 2. update res_counter
2382 * 3. call memory reclaim if necessary.
2384 * In some special case, if the task is fatal, fatal_signal_pending() or
2385 * has TIF_MEMDIE, this function returns -EINTR while writing root_mem_cgroup
2386 * to *ptr. There are two reasons for this. 1: fatal threads should quit as soon
2387 * as possible without any hazards. 2: all pages should have a valid
2388 * pc->mem_cgroup. If mm is NULL and the caller doesn't pass a valid memcg
2389 * pointer, that is treated as a charge to root_mem_cgroup.
2391 * So __mem_cgroup_try_charge() will return
2392 * 0 ... on success, filling *ptr with a valid memcg pointer.
2393 * -ENOMEM ... charge failure because of resource limits.
2394 * -EINTR ... if thread is fatal. *ptr is filled with root_mem_cgroup.
2396 * Unlike the exported interface, an "oom" parameter is added. if oom==true,
2397 * the oom-killer can be invoked.
2399 static int __mem_cgroup_try_charge(struct mm_struct
*mm
,
2401 unsigned int nr_pages
,
2402 struct mem_cgroup
**ptr
,
2405 unsigned int batch
= max(CHARGE_BATCH
, nr_pages
);
2406 int nr_oom_retries
= MEM_CGROUP_RECLAIM_RETRIES
;
2407 struct mem_cgroup
*memcg
= NULL
;
2411 * Unlike gloval-vm's OOM-kill, we're not in memory shortage
2412 * in system level. So, allow to go ahead dying process in addition to
2415 if (unlikely(test_thread_flag(TIF_MEMDIE
)
2416 || fatal_signal_pending(current
)))
2420 * We always charge the cgroup the mm_struct belongs to.
2421 * The mm_struct's mem_cgroup changes on task migration if the
2422 * thread group leader migrates. It's possible that mm is not
2423 * set, if so charge the root memcg (happens for pagecache usage).
2426 *ptr
= root_mem_cgroup
;
2428 if (*ptr
) { /* css should be a valid one */
2430 if (mem_cgroup_is_root(memcg
))
2432 if (consume_stock(memcg
, nr_pages
))
2434 css_get(&memcg
->css
);
2436 struct task_struct
*p
;
2439 p
= rcu_dereference(mm
->owner
);
2441 * Because we don't have task_lock(), "p" can exit.
2442 * In that case, "memcg" can point to root or p can be NULL with
2443 * race with swapoff. Then, we have small risk of mis-accouning.
2444 * But such kind of mis-account by race always happens because
2445 * we don't have cgroup_mutex(). It's overkill and we allo that
2447 * (*) swapoff at el will charge against mm-struct not against
2448 * task-struct. So, mm->owner can be NULL.
2450 memcg
= mem_cgroup_from_task(p
);
2452 memcg
= root_mem_cgroup
;
2453 if (mem_cgroup_is_root(memcg
)) {
2457 if (consume_stock(memcg
, nr_pages
)) {
2459 * It seems dagerous to access memcg without css_get().
2460 * But considering how consume_stok works, it's not
2461 * necessary. If consume_stock success, some charges
2462 * from this memcg are cached on this cpu. So, we
2463 * don't need to call css_get()/css_tryget() before
2464 * calling consume_stock().
2469 /* after here, we may be blocked. we need to get refcnt */
2470 if (!css_tryget(&memcg
->css
)) {
2480 /* If killed, bypass charge */
2481 if (fatal_signal_pending(current
)) {
2482 css_put(&memcg
->css
);
2487 if (oom
&& !nr_oom_retries
) {
2489 nr_oom_retries
= MEM_CGROUP_RECLAIM_RETRIES
;
2492 ret
= mem_cgroup_do_charge(memcg
, gfp_mask
, batch
, nr_pages
,
2497 case CHARGE_RETRY
: /* not in OOM situation but retry */
2499 css_put(&memcg
->css
);
2502 case CHARGE_WOULDBLOCK
: /* !__GFP_WAIT */
2503 css_put(&memcg
->css
);
2505 case CHARGE_NOMEM
: /* OOM routine works */
2507 css_put(&memcg
->css
);
2510 /* If oom, we never return -ENOMEM */
2513 case CHARGE_OOM_DIE
: /* Killed by OOM Killer */
2514 css_put(&memcg
->css
);
2517 } while (ret
!= CHARGE_OK
);
2519 if (batch
> nr_pages
)
2520 refill_stock(memcg
, batch
- nr_pages
);
2521 css_put(&memcg
->css
);
2529 *ptr
= root_mem_cgroup
;
2534 * Somemtimes we have to undo a charge we got by try_charge().
2535 * This function is for that and do uncharge, put css's refcnt.
2536 * gotten by try_charge().
2538 static void __mem_cgroup_cancel_charge(struct mem_cgroup
*memcg
,
2539 unsigned int nr_pages
)
2541 if (!mem_cgroup_is_root(memcg
)) {
2542 unsigned long bytes
= nr_pages
* PAGE_SIZE
;
2544 res_counter_uncharge(&memcg
->res
, bytes
);
2545 if (do_swap_account
)
2546 res_counter_uncharge(&memcg
->memsw
, bytes
);
2551 * Cancel chrages in this cgroup....doesn't propagate to parent cgroup.
2552 * This is useful when moving usage to parent cgroup.
2554 static void __mem_cgroup_cancel_local_charge(struct mem_cgroup
*memcg
,
2555 unsigned int nr_pages
)
2557 unsigned long bytes
= nr_pages
* PAGE_SIZE
;
2559 if (mem_cgroup_is_root(memcg
))
2562 res_counter_uncharge_until(&memcg
->res
, memcg
->res
.parent
, bytes
);
2563 if (do_swap_account
)
2564 res_counter_uncharge_until(&memcg
->memsw
,
2565 memcg
->memsw
.parent
, bytes
);
2569 * A helper function to get mem_cgroup from ID. must be called under
2570 * rcu_read_lock(). The caller is responsible for calling css_tryget if
2571 * the mem_cgroup is used for charging. (dropping refcnt from swap can be
2572 * called against removed memcg.)
2574 static struct mem_cgroup
*mem_cgroup_lookup(unsigned short id
)
2576 struct cgroup_subsys_state
*css
;
2578 /* ID 0 is unused ID */
2581 css
= css_lookup(&mem_cgroup_subsys
, id
);
2584 return mem_cgroup_from_css(css
);
2587 struct mem_cgroup
*try_get_mem_cgroup_from_page(struct page
*page
)
2589 struct mem_cgroup
*memcg
= NULL
;
2590 struct page_cgroup
*pc
;
2594 VM_BUG_ON(!PageLocked(page
));
2596 pc
= lookup_page_cgroup(page
);
2597 lock_page_cgroup(pc
);
2598 if (PageCgroupUsed(pc
)) {
2599 memcg
= pc
->mem_cgroup
;
2600 if (memcg
&& !css_tryget(&memcg
->css
))
2602 } else if (PageSwapCache(page
)) {
2603 ent
.val
= page_private(page
);
2604 id
= lookup_swap_cgroup_id(ent
);
2606 memcg
= mem_cgroup_lookup(id
);
2607 if (memcg
&& !css_tryget(&memcg
->css
))
2611 unlock_page_cgroup(pc
);
2615 static void __mem_cgroup_commit_charge(struct mem_cgroup
*memcg
,
2617 unsigned int nr_pages
,
2618 enum charge_type ctype
,
2621 struct page_cgroup
*pc
= lookup_page_cgroup(page
);
2622 struct zone
*uninitialized_var(zone
);
2623 struct lruvec
*lruvec
;
2624 bool was_on_lru
= false;
2627 lock_page_cgroup(pc
);
2628 VM_BUG_ON(PageCgroupUsed(pc
));
2630 * we don't need page_cgroup_lock about tail pages, becase they are not
2631 * accessed by any other context at this point.
2635 * In some cases, SwapCache and FUSE(splice_buf->radixtree), the page
2636 * may already be on some other mem_cgroup's LRU. Take care of it.
2639 zone
= page_zone(page
);
2640 spin_lock_irq(&zone
->lru_lock
);
2641 if (PageLRU(page
)) {
2642 lruvec
= mem_cgroup_zone_lruvec(zone
, pc
->mem_cgroup
);
2644 del_page_from_lru_list(page
, lruvec
, page_lru(page
));
2649 pc
->mem_cgroup
= memcg
;
2651 * We access a page_cgroup asynchronously without lock_page_cgroup().
2652 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
2653 * is accessed after testing USED bit. To make pc->mem_cgroup visible
2654 * before USED bit, we need memory barrier here.
2655 * See mem_cgroup_add_lru_list(), etc.
2658 SetPageCgroupUsed(pc
);
2662 lruvec
= mem_cgroup_zone_lruvec(zone
, pc
->mem_cgroup
);
2663 VM_BUG_ON(PageLRU(page
));
2665 add_page_to_lru_list(page
, lruvec
, page_lru(page
));
2667 spin_unlock_irq(&zone
->lru_lock
);
2670 if (ctype
== MEM_CGROUP_CHARGE_TYPE_ANON
)
2675 mem_cgroup_charge_statistics(memcg
, anon
, nr_pages
);
2676 unlock_page_cgroup(pc
);
2679 * "charge_statistics" updated event counter. Then, check it.
2680 * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
2681 * if they exceeds softlimit.
2683 memcg_check_events(memcg
, page
);
2686 #ifdef CONFIG_MEMCG_KMEM
2687 static inline bool memcg_can_account_kmem(struct mem_cgroup
*memcg
)
2689 return !mem_cgroup_disabled() && !mem_cgroup_is_root(memcg
) &&
2690 (memcg
->kmem_account_flags
& KMEM_ACCOUNTED_MASK
);
2693 static int memcg_charge_kmem(struct mem_cgroup
*memcg
, gfp_t gfp
, u64 size
)
2695 struct res_counter
*fail_res
;
2696 struct mem_cgroup
*_memcg
;
2700 ret
= res_counter_charge(&memcg
->kmem
, size
, &fail_res
);
2705 * Conditions under which we can wait for the oom_killer. Those are
2706 * the same conditions tested by the core page allocator
2708 may_oom
= (gfp
& __GFP_FS
) && !(gfp
& __GFP_NORETRY
);
2711 ret
= __mem_cgroup_try_charge(NULL
, gfp
, size
>> PAGE_SHIFT
,
2714 if (ret
== -EINTR
) {
2716 * __mem_cgroup_try_charge() chosed to bypass to root due to
2717 * OOM kill or fatal signal. Since our only options are to
2718 * either fail the allocation or charge it to this cgroup, do
2719 * it as a temporary condition. But we can't fail. From a
2720 * kmem/slab perspective, the cache has already been selected,
2721 * by mem_cgroup_kmem_get_cache(), so it is too late to change
2724 * This condition will only trigger if the task entered
2725 * memcg_charge_kmem in a sane state, but was OOM-killed during
2726 * __mem_cgroup_try_charge() above. Tasks that were already
2727 * dying when the allocation triggers should have been already
2728 * directed to the root cgroup in memcontrol.h
2730 res_counter_charge_nofail(&memcg
->res
, size
, &fail_res
);
2731 if (do_swap_account
)
2732 res_counter_charge_nofail(&memcg
->memsw
, size
,
2736 res_counter_uncharge(&memcg
->kmem
, size
);
2741 static void memcg_uncharge_kmem(struct mem_cgroup
*memcg
, u64 size
)
2743 res_counter_uncharge(&memcg
->res
, size
);
2744 if (do_swap_account
)
2745 res_counter_uncharge(&memcg
->memsw
, size
);
2748 if (res_counter_uncharge(&memcg
->kmem
, size
))
2751 if (memcg_kmem_test_and_clear_dead(memcg
))
2752 mem_cgroup_put(memcg
);
2756 * We need to verify if the allocation against current->mm->owner's memcg is
2757 * possible for the given order. But the page is not allocated yet, so we'll
2758 * need a further commit step to do the final arrangements.
2760 * It is possible for the task to switch cgroups in this mean time, so at
2761 * commit time, we can't rely on task conversion any longer. We'll then use
2762 * the handle argument to return to the caller which cgroup we should commit
2763 * against. We could also return the memcg directly and avoid the pointer
2764 * passing, but a boolean return value gives better semantics considering
2765 * the compiled-out case as well.
2767 * Returning true means the allocation is possible.
2770 __memcg_kmem_newpage_charge(gfp_t gfp
, struct mem_cgroup
**_memcg
, int order
)
2772 struct mem_cgroup
*memcg
;
2776 memcg
= try_get_mem_cgroup_from_mm(current
->mm
);
2779 * very rare case described in mem_cgroup_from_task. Unfortunately there
2780 * isn't much we can do without complicating this too much, and it would
2781 * be gfp-dependent anyway. Just let it go
2783 if (unlikely(!memcg
))
2786 if (!memcg_can_account_kmem(memcg
)) {
2787 css_put(&memcg
->css
);
2791 ret
= memcg_charge_kmem(memcg
, gfp
, PAGE_SIZE
<< order
);
2795 css_put(&memcg
->css
);
2799 void __memcg_kmem_commit_charge(struct page
*page
, struct mem_cgroup
*memcg
,
2802 struct page_cgroup
*pc
;
2804 VM_BUG_ON(mem_cgroup_is_root(memcg
));
2806 /* The page allocation failed. Revert */
2808 memcg_uncharge_kmem(memcg
, PAGE_SIZE
<< order
);
2812 pc
= lookup_page_cgroup(page
);
2813 lock_page_cgroup(pc
);
2814 pc
->mem_cgroup
= memcg
;
2815 SetPageCgroupUsed(pc
);
2816 unlock_page_cgroup(pc
);
2819 void __memcg_kmem_uncharge_pages(struct page
*page
, int order
)
2821 struct mem_cgroup
*memcg
= NULL
;
2822 struct page_cgroup
*pc
;
2825 pc
= lookup_page_cgroup(page
);
2827 * Fast unlocked return. Theoretically might have changed, have to
2828 * check again after locking.
2830 if (!PageCgroupUsed(pc
))
2833 lock_page_cgroup(pc
);
2834 if (PageCgroupUsed(pc
)) {
2835 memcg
= pc
->mem_cgroup
;
2836 ClearPageCgroupUsed(pc
);
2838 unlock_page_cgroup(pc
);
2841 * We trust that only if there is a memcg associated with the page, it
2842 * is a valid allocation
2847 VM_BUG_ON(mem_cgroup_is_root(memcg
));
2848 memcg_uncharge_kmem(memcg
, PAGE_SIZE
<< order
);
2850 #endif /* CONFIG_MEMCG_KMEM */
2852 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
2854 #define PCGF_NOCOPY_AT_SPLIT (1 << PCG_LOCK | 1 << PCG_MIGRATION)
2856 * Because tail pages are not marked as "used", set it. We're under
2857 * zone->lru_lock, 'splitting on pmd' and compound_lock.
2858 * charge/uncharge will be never happen and move_account() is done under
2859 * compound_lock(), so we don't have to take care of races.
2861 void mem_cgroup_split_huge_fixup(struct page
*head
)
2863 struct page_cgroup
*head_pc
= lookup_page_cgroup(head
);
2864 struct page_cgroup
*pc
;
2867 if (mem_cgroup_disabled())
2869 for (i
= 1; i
< HPAGE_PMD_NR
; i
++) {
2871 pc
->mem_cgroup
= head_pc
->mem_cgroup
;
2872 smp_wmb();/* see __commit_charge() */
2873 pc
->flags
= head_pc
->flags
& ~PCGF_NOCOPY_AT_SPLIT
;
2876 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
2879 * mem_cgroup_move_account - move account of the page
2881 * @nr_pages: number of regular pages (>1 for huge pages)
2882 * @pc: page_cgroup of the page.
2883 * @from: mem_cgroup which the page is moved from.
2884 * @to: mem_cgroup which the page is moved to. @from != @to.
2886 * The caller must confirm following.
2887 * - page is not on LRU (isolate_page() is useful.)
2888 * - compound_lock is held when nr_pages > 1
2890 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
2893 static int mem_cgroup_move_account(struct page
*page
,
2894 unsigned int nr_pages
,
2895 struct page_cgroup
*pc
,
2896 struct mem_cgroup
*from
,
2897 struct mem_cgroup
*to
)
2899 unsigned long flags
;
2901 bool anon
= PageAnon(page
);
2903 VM_BUG_ON(from
== to
);
2904 VM_BUG_ON(PageLRU(page
));
2906 * The page is isolated from LRU. So, collapse function
2907 * will not handle this page. But page splitting can happen.
2908 * Do this check under compound_page_lock(). The caller should
2912 if (nr_pages
> 1 && !PageTransHuge(page
))
2915 lock_page_cgroup(pc
);
2918 if (!PageCgroupUsed(pc
) || pc
->mem_cgroup
!= from
)
2921 move_lock_mem_cgroup(from
, &flags
);
2923 if (!anon
&& page_mapped(page
)) {
2924 /* Update mapped_file data for mem_cgroup */
2926 __this_cpu_dec(from
->stat
->count
[MEM_CGROUP_STAT_FILE_MAPPED
]);
2927 __this_cpu_inc(to
->stat
->count
[MEM_CGROUP_STAT_FILE_MAPPED
]);
2930 mem_cgroup_charge_statistics(from
, anon
, -nr_pages
);
2932 /* caller should have done css_get */
2933 pc
->mem_cgroup
= to
;
2934 mem_cgroup_charge_statistics(to
, anon
, nr_pages
);
2935 move_unlock_mem_cgroup(from
, &flags
);
2938 unlock_page_cgroup(pc
);
2942 memcg_check_events(to
, page
);
2943 memcg_check_events(from
, page
);
2949 * mem_cgroup_move_parent - moves page to the parent group
2950 * @page: the page to move
2951 * @pc: page_cgroup of the page
2952 * @child: page's cgroup
2954 * move charges to its parent or the root cgroup if the group has no
2955 * parent (aka use_hierarchy==0).
2956 * Although this might fail (get_page_unless_zero, isolate_lru_page or
2957 * mem_cgroup_move_account fails) the failure is always temporary and
2958 * it signals a race with a page removal/uncharge or migration. In the
2959 * first case the page is on the way out and it will vanish from the LRU
2960 * on the next attempt and the call should be retried later.
2961 * Isolation from the LRU fails only if page has been isolated from
2962 * the LRU since we looked at it and that usually means either global
2963 * reclaim or migration going on. The page will either get back to the
2965 * Finaly mem_cgroup_move_account fails only if the page got uncharged
2966 * (!PageCgroupUsed) or moved to a different group. The page will
2967 * disappear in the next attempt.
2969 static int mem_cgroup_move_parent(struct page
*page
,
2970 struct page_cgroup
*pc
,
2971 struct mem_cgroup
*child
)
2973 struct mem_cgroup
*parent
;
2974 unsigned int nr_pages
;
2975 unsigned long uninitialized_var(flags
);
2978 VM_BUG_ON(mem_cgroup_is_root(child
));
2981 if (!get_page_unless_zero(page
))
2983 if (isolate_lru_page(page
))
2986 nr_pages
= hpage_nr_pages(page
);
2988 parent
= parent_mem_cgroup(child
);
2990 * If no parent, move charges to root cgroup.
2993 parent
= root_mem_cgroup
;
2996 VM_BUG_ON(!PageTransHuge(page
));
2997 flags
= compound_lock_irqsave(page
);
3000 ret
= mem_cgroup_move_account(page
, nr_pages
,
3003 __mem_cgroup_cancel_local_charge(child
, nr_pages
);
3006 compound_unlock_irqrestore(page
, flags
);
3007 putback_lru_page(page
);
3015 * Charge the memory controller for page usage.
3017 * 0 if the charge was successful
3018 * < 0 if the cgroup is over its limit
3020 static int mem_cgroup_charge_common(struct page
*page
, struct mm_struct
*mm
,
3021 gfp_t gfp_mask
, enum charge_type ctype
)
3023 struct mem_cgroup
*memcg
= NULL
;
3024 unsigned int nr_pages
= 1;
3028 if (PageTransHuge(page
)) {
3029 nr_pages
<<= compound_order(page
);
3030 VM_BUG_ON(!PageTransHuge(page
));
3032 * Never OOM-kill a process for a huge page. The
3033 * fault handler will fall back to regular pages.
3038 ret
= __mem_cgroup_try_charge(mm
, gfp_mask
, nr_pages
, &memcg
, oom
);
3041 __mem_cgroup_commit_charge(memcg
, page
, nr_pages
, ctype
, false);
3045 int mem_cgroup_newpage_charge(struct page
*page
,
3046 struct mm_struct
*mm
, gfp_t gfp_mask
)
3048 if (mem_cgroup_disabled())
3050 VM_BUG_ON(page_mapped(page
));
3051 VM_BUG_ON(page
->mapping
&& !PageAnon(page
));
3053 return mem_cgroup_charge_common(page
, mm
, gfp_mask
,
3054 MEM_CGROUP_CHARGE_TYPE_ANON
);
3058 * While swap-in, try_charge -> commit or cancel, the page is locked.
3059 * And when try_charge() successfully returns, one refcnt to memcg without
3060 * struct page_cgroup is acquired. This refcnt will be consumed by
3061 * "commit()" or removed by "cancel()"
3063 static int __mem_cgroup_try_charge_swapin(struct mm_struct
*mm
,
3066 struct mem_cgroup
**memcgp
)
3068 struct mem_cgroup
*memcg
;
3069 struct page_cgroup
*pc
;
3072 pc
= lookup_page_cgroup(page
);
3074 * Every swap fault against a single page tries to charge the
3075 * page, bail as early as possible. shmem_unuse() encounters
3076 * already charged pages, too. The USED bit is protected by
3077 * the page lock, which serializes swap cache removal, which
3078 * in turn serializes uncharging.
3080 if (PageCgroupUsed(pc
))
3082 if (!do_swap_account
)
3084 memcg
= try_get_mem_cgroup_from_page(page
);
3088 ret
= __mem_cgroup_try_charge(NULL
, mask
, 1, memcgp
, true);
3089 css_put(&memcg
->css
);
3094 ret
= __mem_cgroup_try_charge(mm
, mask
, 1, memcgp
, true);
3100 int mem_cgroup_try_charge_swapin(struct mm_struct
*mm
, struct page
*page
,
3101 gfp_t gfp_mask
, struct mem_cgroup
**memcgp
)
3104 if (mem_cgroup_disabled())
3107 * A racing thread's fault, or swapoff, may have already
3108 * updated the pte, and even removed page from swap cache: in
3109 * those cases unuse_pte()'s pte_same() test will fail; but
3110 * there's also a KSM case which does need to charge the page.
3112 if (!PageSwapCache(page
)) {
3115 ret
= __mem_cgroup_try_charge(mm
, gfp_mask
, 1, memcgp
, true);
3120 return __mem_cgroup_try_charge_swapin(mm
, page
, gfp_mask
, memcgp
);
3123 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup
*memcg
)
3125 if (mem_cgroup_disabled())
3129 __mem_cgroup_cancel_charge(memcg
, 1);
3133 __mem_cgroup_commit_charge_swapin(struct page
*page
, struct mem_cgroup
*memcg
,
3134 enum charge_type ctype
)
3136 if (mem_cgroup_disabled())
3141 __mem_cgroup_commit_charge(memcg
, page
, 1, ctype
, true);
3143 * Now swap is on-memory. This means this page may be
3144 * counted both as mem and swap....double count.
3145 * Fix it by uncharging from memsw. Basically, this SwapCache is stable
3146 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
3147 * may call delete_from_swap_cache() before reach here.
3149 if (do_swap_account
&& PageSwapCache(page
)) {
3150 swp_entry_t ent
= {.val
= page_private(page
)};
3151 mem_cgroup_uncharge_swap(ent
);
3155 void mem_cgroup_commit_charge_swapin(struct page
*page
,
3156 struct mem_cgroup
*memcg
)
3158 __mem_cgroup_commit_charge_swapin(page
, memcg
,
3159 MEM_CGROUP_CHARGE_TYPE_ANON
);
3162 int mem_cgroup_cache_charge(struct page
*page
, struct mm_struct
*mm
,
3165 struct mem_cgroup
*memcg
= NULL
;
3166 enum charge_type type
= MEM_CGROUP_CHARGE_TYPE_CACHE
;
3169 if (mem_cgroup_disabled())
3171 if (PageCompound(page
))
3174 if (!PageSwapCache(page
))
3175 ret
= mem_cgroup_charge_common(page
, mm
, gfp_mask
, type
);
3176 else { /* page is swapcache/shmem */
3177 ret
= __mem_cgroup_try_charge_swapin(mm
, page
,
3180 __mem_cgroup_commit_charge_swapin(page
, memcg
, type
);
3185 static void mem_cgroup_do_uncharge(struct mem_cgroup
*memcg
,
3186 unsigned int nr_pages
,
3187 const enum charge_type ctype
)
3189 struct memcg_batch_info
*batch
= NULL
;
3190 bool uncharge_memsw
= true;
3192 /* If swapout, usage of swap doesn't decrease */
3193 if (!do_swap_account
|| ctype
== MEM_CGROUP_CHARGE_TYPE_SWAPOUT
)
3194 uncharge_memsw
= false;
3196 batch
= ¤t
->memcg_batch
;
3198 * In usual, we do css_get() when we remember memcg pointer.
3199 * But in this case, we keep res->usage until end of a series of
3200 * uncharges. Then, it's ok to ignore memcg's refcnt.
3203 batch
->memcg
= memcg
;
3205 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
3206 * In those cases, all pages freed continuously can be expected to be in
3207 * the same cgroup and we have chance to coalesce uncharges.
3208 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
3209 * because we want to do uncharge as soon as possible.
3212 if (!batch
->do_batch
|| test_thread_flag(TIF_MEMDIE
))
3213 goto direct_uncharge
;
3216 goto direct_uncharge
;
3219 * In typical case, batch->memcg == mem. This means we can
3220 * merge a series of uncharges to an uncharge of res_counter.
3221 * If not, we uncharge res_counter ony by one.
3223 if (batch
->memcg
!= memcg
)
3224 goto direct_uncharge
;
3225 /* remember freed charge and uncharge it later */
3228 batch
->memsw_nr_pages
++;
3231 res_counter_uncharge(&memcg
->res
, nr_pages
* PAGE_SIZE
);
3233 res_counter_uncharge(&memcg
->memsw
, nr_pages
* PAGE_SIZE
);
3234 if (unlikely(batch
->memcg
!= memcg
))
3235 memcg_oom_recover(memcg
);
3239 * uncharge if !page_mapped(page)
3241 static struct mem_cgroup
*
3242 __mem_cgroup_uncharge_common(struct page
*page
, enum charge_type ctype
,
3245 struct mem_cgroup
*memcg
= NULL
;
3246 unsigned int nr_pages
= 1;
3247 struct page_cgroup
*pc
;
3250 if (mem_cgroup_disabled())
3253 VM_BUG_ON(PageSwapCache(page
));
3255 if (PageTransHuge(page
)) {
3256 nr_pages
<<= compound_order(page
);
3257 VM_BUG_ON(!PageTransHuge(page
));
3260 * Check if our page_cgroup is valid
3262 pc
= lookup_page_cgroup(page
);
3263 if (unlikely(!PageCgroupUsed(pc
)))
3266 lock_page_cgroup(pc
);
3268 memcg
= pc
->mem_cgroup
;
3270 if (!PageCgroupUsed(pc
))
3273 anon
= PageAnon(page
);
3276 case MEM_CGROUP_CHARGE_TYPE_ANON
:
3278 * Generally PageAnon tells if it's the anon statistics to be
3279 * updated; but sometimes e.g. mem_cgroup_uncharge_page() is
3280 * used before page reached the stage of being marked PageAnon.
3284 case MEM_CGROUP_CHARGE_TYPE_DROP
:
3285 /* See mem_cgroup_prepare_migration() */
3286 if (page_mapped(page
))
3289 * Pages under migration may not be uncharged. But
3290 * end_migration() /must/ be the one uncharging the
3291 * unused post-migration page and so it has to call
3292 * here with the migration bit still set. See the
3293 * res_counter handling below.
3295 if (!end_migration
&& PageCgroupMigration(pc
))
3298 case MEM_CGROUP_CHARGE_TYPE_SWAPOUT
:
3299 if (!PageAnon(page
)) { /* Shared memory */
3300 if (page
->mapping
&& !page_is_file_cache(page
))
3302 } else if (page_mapped(page
)) /* Anon */
3309 mem_cgroup_charge_statistics(memcg
, anon
, -nr_pages
);
3311 ClearPageCgroupUsed(pc
);
3313 * pc->mem_cgroup is not cleared here. It will be accessed when it's
3314 * freed from LRU. This is safe because uncharged page is expected not
3315 * to be reused (freed soon). Exception is SwapCache, it's handled by
3316 * special functions.
3319 unlock_page_cgroup(pc
);
3321 * even after unlock, we have memcg->res.usage here and this memcg
3322 * will never be freed.
3324 memcg_check_events(memcg
, page
);
3325 if (do_swap_account
&& ctype
== MEM_CGROUP_CHARGE_TYPE_SWAPOUT
) {
3326 mem_cgroup_swap_statistics(memcg
, true);
3327 mem_cgroup_get(memcg
);
3330 * Migration does not charge the res_counter for the
3331 * replacement page, so leave it alone when phasing out the
3332 * page that is unused after the migration.
3334 if (!end_migration
&& !mem_cgroup_is_root(memcg
))
3335 mem_cgroup_do_uncharge(memcg
, nr_pages
, ctype
);
3340 unlock_page_cgroup(pc
);
3344 void mem_cgroup_uncharge_page(struct page
*page
)
3347 if (page_mapped(page
))
3349 VM_BUG_ON(page
->mapping
&& !PageAnon(page
));
3350 if (PageSwapCache(page
))
3352 __mem_cgroup_uncharge_common(page
, MEM_CGROUP_CHARGE_TYPE_ANON
, false);
3355 void mem_cgroup_uncharge_cache_page(struct page
*page
)
3357 VM_BUG_ON(page_mapped(page
));
3358 VM_BUG_ON(page
->mapping
);
3359 __mem_cgroup_uncharge_common(page
, MEM_CGROUP_CHARGE_TYPE_CACHE
, false);
3363 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
3364 * In that cases, pages are freed continuously and we can expect pages
3365 * are in the same memcg. All these calls itself limits the number of
3366 * pages freed at once, then uncharge_start/end() is called properly.
3367 * This may be called prural(2) times in a context,
3370 void mem_cgroup_uncharge_start(void)
3372 current
->memcg_batch
.do_batch
++;
3373 /* We can do nest. */
3374 if (current
->memcg_batch
.do_batch
== 1) {
3375 current
->memcg_batch
.memcg
= NULL
;
3376 current
->memcg_batch
.nr_pages
= 0;
3377 current
->memcg_batch
.memsw_nr_pages
= 0;
3381 void mem_cgroup_uncharge_end(void)
3383 struct memcg_batch_info
*batch
= ¤t
->memcg_batch
;
3385 if (!batch
->do_batch
)
3389 if (batch
->do_batch
) /* If stacked, do nothing. */
3395 * This "batch->memcg" is valid without any css_get/put etc...
3396 * bacause we hide charges behind us.
3398 if (batch
->nr_pages
)
3399 res_counter_uncharge(&batch
->memcg
->res
,
3400 batch
->nr_pages
* PAGE_SIZE
);
3401 if (batch
->memsw_nr_pages
)
3402 res_counter_uncharge(&batch
->memcg
->memsw
,
3403 batch
->memsw_nr_pages
* PAGE_SIZE
);
3404 memcg_oom_recover(batch
->memcg
);
3405 /* forget this pointer (for sanity check) */
3406 batch
->memcg
= NULL
;
3411 * called after __delete_from_swap_cache() and drop "page" account.
3412 * memcg information is recorded to swap_cgroup of "ent"
3415 mem_cgroup_uncharge_swapcache(struct page
*page
, swp_entry_t ent
, bool swapout
)
3417 struct mem_cgroup
*memcg
;
3418 int ctype
= MEM_CGROUP_CHARGE_TYPE_SWAPOUT
;
3420 if (!swapout
) /* this was a swap cache but the swap is unused ! */
3421 ctype
= MEM_CGROUP_CHARGE_TYPE_DROP
;
3423 memcg
= __mem_cgroup_uncharge_common(page
, ctype
, false);
3426 * record memcg information, if swapout && memcg != NULL,
3427 * mem_cgroup_get() was called in uncharge().
3429 if (do_swap_account
&& swapout
&& memcg
)
3430 swap_cgroup_record(ent
, css_id(&memcg
->css
));
3434 #ifdef CONFIG_MEMCG_SWAP
3436 * called from swap_entry_free(). remove record in swap_cgroup and
3437 * uncharge "memsw" account.
3439 void mem_cgroup_uncharge_swap(swp_entry_t ent
)
3441 struct mem_cgroup
*memcg
;
3444 if (!do_swap_account
)
3447 id
= swap_cgroup_record(ent
, 0);
3449 memcg
= mem_cgroup_lookup(id
);
3452 * We uncharge this because swap is freed.
3453 * This memcg can be obsolete one. We avoid calling css_tryget
3455 if (!mem_cgroup_is_root(memcg
))
3456 res_counter_uncharge(&memcg
->memsw
, PAGE_SIZE
);
3457 mem_cgroup_swap_statistics(memcg
, false);
3458 mem_cgroup_put(memcg
);
3464 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3465 * @entry: swap entry to be moved
3466 * @from: mem_cgroup which the entry is moved from
3467 * @to: mem_cgroup which the entry is moved to
3469 * It succeeds only when the swap_cgroup's record for this entry is the same
3470 * as the mem_cgroup's id of @from.
3472 * Returns 0 on success, -EINVAL on failure.
3474 * The caller must have charged to @to, IOW, called res_counter_charge() about
3475 * both res and memsw, and called css_get().
3477 static int mem_cgroup_move_swap_account(swp_entry_t entry
,
3478 struct mem_cgroup
*from
, struct mem_cgroup
*to
)
3480 unsigned short old_id
, new_id
;
3482 old_id
= css_id(&from
->css
);
3483 new_id
= css_id(&to
->css
);
3485 if (swap_cgroup_cmpxchg(entry
, old_id
, new_id
) == old_id
) {
3486 mem_cgroup_swap_statistics(from
, false);
3487 mem_cgroup_swap_statistics(to
, true);
3489 * This function is only called from task migration context now.
3490 * It postpones res_counter and refcount handling till the end
3491 * of task migration(mem_cgroup_clear_mc()) for performance
3492 * improvement. But we cannot postpone mem_cgroup_get(to)
3493 * because if the process that has been moved to @to does
3494 * swap-in, the refcount of @to might be decreased to 0.
3502 static inline int mem_cgroup_move_swap_account(swp_entry_t entry
,
3503 struct mem_cgroup
*from
, struct mem_cgroup
*to
)
3510 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
3513 void mem_cgroup_prepare_migration(struct page
*page
, struct page
*newpage
,
3514 struct mem_cgroup
**memcgp
)
3516 struct mem_cgroup
*memcg
= NULL
;
3517 unsigned int nr_pages
= 1;
3518 struct page_cgroup
*pc
;
3519 enum charge_type ctype
;
3523 if (mem_cgroup_disabled())
3526 if (PageTransHuge(page
))
3527 nr_pages
<<= compound_order(page
);
3529 pc
= lookup_page_cgroup(page
);
3530 lock_page_cgroup(pc
);
3531 if (PageCgroupUsed(pc
)) {
3532 memcg
= pc
->mem_cgroup
;
3533 css_get(&memcg
->css
);
3535 * At migrating an anonymous page, its mapcount goes down
3536 * to 0 and uncharge() will be called. But, even if it's fully
3537 * unmapped, migration may fail and this page has to be
3538 * charged again. We set MIGRATION flag here and delay uncharge
3539 * until end_migration() is called
3541 * Corner Case Thinking
3543 * When the old page was mapped as Anon and it's unmap-and-freed
3544 * while migration was ongoing.
3545 * If unmap finds the old page, uncharge() of it will be delayed
3546 * until end_migration(). If unmap finds a new page, it's
3547 * uncharged when it make mapcount to be 1->0. If unmap code
3548 * finds swap_migration_entry, the new page will not be mapped
3549 * and end_migration() will find it(mapcount==0).
3552 * When the old page was mapped but migraion fails, the kernel
3553 * remaps it. A charge for it is kept by MIGRATION flag even
3554 * if mapcount goes down to 0. We can do remap successfully
3555 * without charging it again.
3558 * The "old" page is under lock_page() until the end of
3559 * migration, so, the old page itself will not be swapped-out.
3560 * If the new page is swapped out before end_migraton, our
3561 * hook to usual swap-out path will catch the event.
3564 SetPageCgroupMigration(pc
);
3566 unlock_page_cgroup(pc
);
3568 * If the page is not charged at this point,
3576 * We charge new page before it's used/mapped. So, even if unlock_page()
3577 * is called before end_migration, we can catch all events on this new
3578 * page. In the case new page is migrated but not remapped, new page's
3579 * mapcount will be finally 0 and we call uncharge in end_migration().
3582 ctype
= MEM_CGROUP_CHARGE_TYPE_ANON
;
3584 ctype
= MEM_CGROUP_CHARGE_TYPE_CACHE
;
3586 * The page is committed to the memcg, but it's not actually
3587 * charged to the res_counter since we plan on replacing the
3588 * old one and only one page is going to be left afterwards.
3590 __mem_cgroup_commit_charge(memcg
, newpage
, nr_pages
, ctype
, false);
3593 /* remove redundant charge if migration failed*/
3594 void mem_cgroup_end_migration(struct mem_cgroup
*memcg
,
3595 struct page
*oldpage
, struct page
*newpage
, bool migration_ok
)
3597 struct page
*used
, *unused
;
3598 struct page_cgroup
*pc
;
3604 if (!migration_ok
) {
3611 anon
= PageAnon(used
);
3612 __mem_cgroup_uncharge_common(unused
,
3613 anon
? MEM_CGROUP_CHARGE_TYPE_ANON
3614 : MEM_CGROUP_CHARGE_TYPE_CACHE
,
3616 css_put(&memcg
->css
);
3618 * We disallowed uncharge of pages under migration because mapcount
3619 * of the page goes down to zero, temporarly.
3620 * Clear the flag and check the page should be charged.
3622 pc
= lookup_page_cgroup(oldpage
);
3623 lock_page_cgroup(pc
);
3624 ClearPageCgroupMigration(pc
);
3625 unlock_page_cgroup(pc
);
3628 * If a page is a file cache, radix-tree replacement is very atomic
3629 * and we can skip this check. When it was an Anon page, its mapcount
3630 * goes down to 0. But because we added MIGRATION flage, it's not
3631 * uncharged yet. There are several case but page->mapcount check
3632 * and USED bit check in mem_cgroup_uncharge_page() will do enough
3633 * check. (see prepare_charge() also)
3636 mem_cgroup_uncharge_page(used
);
3640 * At replace page cache, newpage is not under any memcg but it's on
3641 * LRU. So, this function doesn't touch res_counter but handles LRU
3642 * in correct way. Both pages are locked so we cannot race with uncharge.
3644 void mem_cgroup_replace_page_cache(struct page
*oldpage
,
3645 struct page
*newpage
)
3647 struct mem_cgroup
*memcg
= NULL
;
3648 struct page_cgroup
*pc
;
3649 enum charge_type type
= MEM_CGROUP_CHARGE_TYPE_CACHE
;
3651 if (mem_cgroup_disabled())
3654 pc
= lookup_page_cgroup(oldpage
);
3655 /* fix accounting on old pages */
3656 lock_page_cgroup(pc
);
3657 if (PageCgroupUsed(pc
)) {
3658 memcg
= pc
->mem_cgroup
;
3659 mem_cgroup_charge_statistics(memcg
, false, -1);
3660 ClearPageCgroupUsed(pc
);
3662 unlock_page_cgroup(pc
);
3665 * When called from shmem_replace_page(), in some cases the
3666 * oldpage has already been charged, and in some cases not.
3671 * Even if newpage->mapping was NULL before starting replacement,
3672 * the newpage may be on LRU(or pagevec for LRU) already. We lock
3673 * LRU while we overwrite pc->mem_cgroup.
3675 __mem_cgroup_commit_charge(memcg
, newpage
, 1, type
, true);
3678 #ifdef CONFIG_DEBUG_VM
3679 static struct page_cgroup
*lookup_page_cgroup_used(struct page
*page
)
3681 struct page_cgroup
*pc
;
3683 pc
= lookup_page_cgroup(page
);
3685 * Can be NULL while feeding pages into the page allocator for
3686 * the first time, i.e. during boot or memory hotplug;
3687 * or when mem_cgroup_disabled().
3689 if (likely(pc
) && PageCgroupUsed(pc
))
3694 bool mem_cgroup_bad_page_check(struct page
*page
)
3696 if (mem_cgroup_disabled())
3699 return lookup_page_cgroup_used(page
) != NULL
;
3702 void mem_cgroup_print_bad_page(struct page
*page
)
3704 struct page_cgroup
*pc
;
3706 pc
= lookup_page_cgroup_used(page
);
3708 printk(KERN_ALERT
"pc:%p pc->flags:%lx pc->mem_cgroup:%p\n",
3709 pc
, pc
->flags
, pc
->mem_cgroup
);
3714 static DEFINE_MUTEX(set_limit_mutex
);
3716 static int mem_cgroup_resize_limit(struct mem_cgroup
*memcg
,
3717 unsigned long long val
)
3720 u64 memswlimit
, memlimit
;
3722 int children
= mem_cgroup_count_children(memcg
);
3723 u64 curusage
, oldusage
;
3727 * For keeping hierarchical_reclaim simple, how long we should retry
3728 * is depends on callers. We set our retry-count to be function
3729 * of # of children which we should visit in this loop.
3731 retry_count
= MEM_CGROUP_RECLAIM_RETRIES
* children
;
3733 oldusage
= res_counter_read_u64(&memcg
->res
, RES_USAGE
);
3736 while (retry_count
) {
3737 if (signal_pending(current
)) {
3742 * Rather than hide all in some function, I do this in
3743 * open coded manner. You see what this really does.
3744 * We have to guarantee memcg->res.limit <= memcg->memsw.limit.
3746 mutex_lock(&set_limit_mutex
);
3747 memswlimit
= res_counter_read_u64(&memcg
->memsw
, RES_LIMIT
);
3748 if (memswlimit
< val
) {
3750 mutex_unlock(&set_limit_mutex
);
3754 memlimit
= res_counter_read_u64(&memcg
->res
, RES_LIMIT
);
3758 ret
= res_counter_set_limit(&memcg
->res
, val
);
3760 if (memswlimit
== val
)
3761 memcg
->memsw_is_minimum
= true;
3763 memcg
->memsw_is_minimum
= false;
3765 mutex_unlock(&set_limit_mutex
);
3770 mem_cgroup_reclaim(memcg
, GFP_KERNEL
,
3771 MEM_CGROUP_RECLAIM_SHRINK
);
3772 curusage
= res_counter_read_u64(&memcg
->res
, RES_USAGE
);
3773 /* Usage is reduced ? */
3774 if (curusage
>= oldusage
)
3777 oldusage
= curusage
;
3779 if (!ret
&& enlarge
)
3780 memcg_oom_recover(memcg
);
3785 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup
*memcg
,
3786 unsigned long long val
)
3789 u64 memlimit
, memswlimit
, oldusage
, curusage
;
3790 int children
= mem_cgroup_count_children(memcg
);
3794 /* see mem_cgroup_resize_res_limit */
3795 retry_count
= children
* MEM_CGROUP_RECLAIM_RETRIES
;
3796 oldusage
= res_counter_read_u64(&memcg
->memsw
, RES_USAGE
);
3797 while (retry_count
) {
3798 if (signal_pending(current
)) {
3803 * Rather than hide all in some function, I do this in
3804 * open coded manner. You see what this really does.
3805 * We have to guarantee memcg->res.limit <= memcg->memsw.limit.
3807 mutex_lock(&set_limit_mutex
);
3808 memlimit
= res_counter_read_u64(&memcg
->res
, RES_LIMIT
);
3809 if (memlimit
> val
) {
3811 mutex_unlock(&set_limit_mutex
);
3814 memswlimit
= res_counter_read_u64(&memcg
->memsw
, RES_LIMIT
);
3815 if (memswlimit
< val
)
3817 ret
= res_counter_set_limit(&memcg
->memsw
, val
);
3819 if (memlimit
== val
)
3820 memcg
->memsw_is_minimum
= true;
3822 memcg
->memsw_is_minimum
= false;
3824 mutex_unlock(&set_limit_mutex
);
3829 mem_cgroup_reclaim(memcg
, GFP_KERNEL
,
3830 MEM_CGROUP_RECLAIM_NOSWAP
|
3831 MEM_CGROUP_RECLAIM_SHRINK
);
3832 curusage
= res_counter_read_u64(&memcg
->memsw
, RES_USAGE
);
3833 /* Usage is reduced ? */
3834 if (curusage
>= oldusage
)
3837 oldusage
= curusage
;
3839 if (!ret
&& enlarge
)
3840 memcg_oom_recover(memcg
);
3844 unsigned long mem_cgroup_soft_limit_reclaim(struct zone
*zone
, int order
,
3846 unsigned long *total_scanned
)
3848 unsigned long nr_reclaimed
= 0;
3849 struct mem_cgroup_per_zone
*mz
, *next_mz
= NULL
;
3850 unsigned long reclaimed
;
3852 struct mem_cgroup_tree_per_zone
*mctz
;
3853 unsigned long long excess
;
3854 unsigned long nr_scanned
;
3859 mctz
= soft_limit_tree_node_zone(zone_to_nid(zone
), zone_idx(zone
));
3861 * This loop can run a while, specially if mem_cgroup's continuously
3862 * keep exceeding their soft limit and putting the system under
3869 mz
= mem_cgroup_largest_soft_limit_node(mctz
);
3874 reclaimed
= mem_cgroup_soft_reclaim(mz
->memcg
, zone
,
3875 gfp_mask
, &nr_scanned
);
3876 nr_reclaimed
+= reclaimed
;
3877 *total_scanned
+= nr_scanned
;
3878 spin_lock(&mctz
->lock
);
3881 * If we failed to reclaim anything from this memory cgroup
3882 * it is time to move on to the next cgroup
3888 * Loop until we find yet another one.
3890 * By the time we get the soft_limit lock
3891 * again, someone might have aded the
3892 * group back on the RB tree. Iterate to
3893 * make sure we get a different mem.
3894 * mem_cgroup_largest_soft_limit_node returns
3895 * NULL if no other cgroup is present on
3899 __mem_cgroup_largest_soft_limit_node(mctz
);
3901 css_put(&next_mz
->memcg
->css
);
3902 else /* next_mz == NULL or other memcg */
3906 __mem_cgroup_remove_exceeded(mz
->memcg
, mz
, mctz
);
3907 excess
= res_counter_soft_limit_excess(&mz
->memcg
->res
);
3909 * One school of thought says that we should not add
3910 * back the node to the tree if reclaim returns 0.
3911 * But our reclaim could return 0, simply because due
3912 * to priority we are exposing a smaller subset of
3913 * memory to reclaim from. Consider this as a longer
3916 /* If excess == 0, no tree ops */
3917 __mem_cgroup_insert_exceeded(mz
->memcg
, mz
, mctz
, excess
);
3918 spin_unlock(&mctz
->lock
);
3919 css_put(&mz
->memcg
->css
);
3922 * Could not reclaim anything and there are no more
3923 * mem cgroups to try or we seem to be looping without
3924 * reclaiming anything.
3926 if (!nr_reclaimed
&&
3928 loop
> MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS
))
3930 } while (!nr_reclaimed
);
3932 css_put(&next_mz
->memcg
->css
);
3933 return nr_reclaimed
;
3937 * mem_cgroup_force_empty_list - clears LRU of a group
3938 * @memcg: group to clear
3941 * @lru: lru to to clear
3943 * Traverse a specified page_cgroup list and try to drop them all. This doesn't
3944 * reclaim the pages page themselves - pages are moved to the parent (or root)
3947 static void mem_cgroup_force_empty_list(struct mem_cgroup
*memcg
,
3948 int node
, int zid
, enum lru_list lru
)
3950 struct lruvec
*lruvec
;
3951 unsigned long flags
;
3952 struct list_head
*list
;
3956 zone
= &NODE_DATA(node
)->node_zones
[zid
];
3957 lruvec
= mem_cgroup_zone_lruvec(zone
, memcg
);
3958 list
= &lruvec
->lists
[lru
];
3962 struct page_cgroup
*pc
;
3965 spin_lock_irqsave(&zone
->lru_lock
, flags
);
3966 if (list_empty(list
)) {
3967 spin_unlock_irqrestore(&zone
->lru_lock
, flags
);
3970 page
= list_entry(list
->prev
, struct page
, lru
);
3972 list_move(&page
->lru
, list
);
3974 spin_unlock_irqrestore(&zone
->lru_lock
, flags
);
3977 spin_unlock_irqrestore(&zone
->lru_lock
, flags
);
3979 pc
= lookup_page_cgroup(page
);
3981 if (mem_cgroup_move_parent(page
, pc
, memcg
)) {
3982 /* found lock contention or "pc" is obsolete. */
3987 } while (!list_empty(list
));
3991 * make mem_cgroup's charge to be 0 if there is no task by moving
3992 * all the charges and pages to the parent.
3993 * This enables deleting this mem_cgroup.
3995 * Caller is responsible for holding css reference on the memcg.
3997 static void mem_cgroup_reparent_charges(struct mem_cgroup
*memcg
)
4002 /* This is for making all *used* pages to be on LRU. */
4003 lru_add_drain_all();
4004 drain_all_stock_sync(memcg
);
4005 mem_cgroup_start_move(memcg
);
4006 for_each_node_state(node
, N_MEMORY
) {
4007 for (zid
= 0; zid
< MAX_NR_ZONES
; zid
++) {
4010 mem_cgroup_force_empty_list(memcg
,
4015 mem_cgroup_end_move(memcg
);
4016 memcg_oom_recover(memcg
);
4020 * This is a safety check because mem_cgroup_force_empty_list
4021 * could have raced with mem_cgroup_replace_page_cache callers
4022 * so the lru seemed empty but the page could have been added
4023 * right after the check. RES_USAGE should be safe as we always
4024 * charge before adding to the LRU.
4026 } while (res_counter_read_u64(&memcg
->res
, RES_USAGE
) > 0);
4030 * Reclaims as many pages from the given memcg as possible and moves
4031 * the rest to the parent.
4033 * Caller is responsible for holding css reference for memcg.
4035 static int mem_cgroup_force_empty(struct mem_cgroup
*memcg
)
4037 int nr_retries
= MEM_CGROUP_RECLAIM_RETRIES
;
4038 struct cgroup
*cgrp
= memcg
->css
.cgroup
;
4040 /* returns EBUSY if there is a task or if we come here twice. */
4041 if (cgroup_task_count(cgrp
) || !list_empty(&cgrp
->children
))
4044 /* we call try-to-free pages for make this cgroup empty */
4045 lru_add_drain_all();
4046 /* try to free all pages in this cgroup */
4047 while (nr_retries
&& res_counter_read_u64(&memcg
->res
, RES_USAGE
) > 0) {
4050 if (signal_pending(current
))
4053 progress
= try_to_free_mem_cgroup_pages(memcg
, GFP_KERNEL
,
4057 /* maybe some writeback is necessary */
4058 congestion_wait(BLK_RW_ASYNC
, HZ
/10);
4063 mem_cgroup_reparent_charges(memcg
);
4068 static int mem_cgroup_force_empty_write(struct cgroup
*cont
, unsigned int event
)
4070 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cont
);
4073 if (mem_cgroup_is_root(memcg
))
4075 css_get(&memcg
->css
);
4076 ret
= mem_cgroup_force_empty(memcg
);
4077 css_put(&memcg
->css
);
4083 static u64
mem_cgroup_hierarchy_read(struct cgroup
*cont
, struct cftype
*cft
)
4085 return mem_cgroup_from_cont(cont
)->use_hierarchy
;
4088 static int mem_cgroup_hierarchy_write(struct cgroup
*cont
, struct cftype
*cft
,
4092 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cont
);
4093 struct cgroup
*parent
= cont
->parent
;
4094 struct mem_cgroup
*parent_memcg
= NULL
;
4097 parent_memcg
= mem_cgroup_from_cont(parent
);
4101 if (memcg
->use_hierarchy
== val
)
4105 * If parent's use_hierarchy is set, we can't make any modifications
4106 * in the child subtrees. If it is unset, then the change can
4107 * occur, provided the current cgroup has no children.
4109 * For the root cgroup, parent_mem is NULL, we allow value to be
4110 * set if there are no children.
4112 if ((!parent_memcg
|| !parent_memcg
->use_hierarchy
) &&
4113 (val
== 1 || val
== 0)) {
4114 if (list_empty(&cont
->children
))
4115 memcg
->use_hierarchy
= val
;
4128 static unsigned long mem_cgroup_recursive_stat(struct mem_cgroup
*memcg
,
4129 enum mem_cgroup_stat_index idx
)
4131 struct mem_cgroup
*iter
;
4134 /* Per-cpu values can be negative, use a signed accumulator */
4135 for_each_mem_cgroup_tree(iter
, memcg
)
4136 val
+= mem_cgroup_read_stat(iter
, idx
);
4138 if (val
< 0) /* race ? */
4143 static inline u64
mem_cgroup_usage(struct mem_cgroup
*memcg
, bool swap
)
4147 if (!mem_cgroup_is_root(memcg
)) {
4149 return res_counter_read_u64(&memcg
->res
, RES_USAGE
);
4151 return res_counter_read_u64(&memcg
->memsw
, RES_USAGE
);
4154 val
= mem_cgroup_recursive_stat(memcg
, MEM_CGROUP_STAT_CACHE
);
4155 val
+= mem_cgroup_recursive_stat(memcg
, MEM_CGROUP_STAT_RSS
);
4158 val
+= mem_cgroup_recursive_stat(memcg
, MEM_CGROUP_STAT_SWAP
);
4160 return val
<< PAGE_SHIFT
;
4163 static ssize_t
mem_cgroup_read(struct cgroup
*cont
, struct cftype
*cft
,
4164 struct file
*file
, char __user
*buf
,
4165 size_t nbytes
, loff_t
*ppos
)
4167 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cont
);
4173 type
= MEMFILE_TYPE(cft
->private);
4174 name
= MEMFILE_ATTR(cft
->private);
4176 if (!do_swap_account
&& type
== _MEMSWAP
)
4181 if (name
== RES_USAGE
)
4182 val
= mem_cgroup_usage(memcg
, false);
4184 val
= res_counter_read_u64(&memcg
->res
, name
);
4187 if (name
== RES_USAGE
)
4188 val
= mem_cgroup_usage(memcg
, true);
4190 val
= res_counter_read_u64(&memcg
->memsw
, name
);
4193 val
= res_counter_read_u64(&memcg
->kmem
, name
);
4199 len
= scnprintf(str
, sizeof(str
), "%llu\n", (unsigned long long)val
);
4200 return simple_read_from_buffer(buf
, nbytes
, ppos
, str
, len
);
4203 static int memcg_update_kmem_limit(struct cgroup
*cont
, u64 val
)
4206 #ifdef CONFIG_MEMCG_KMEM
4207 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cont
);
4209 * For simplicity, we won't allow this to be disabled. It also can't
4210 * be changed if the cgroup has children already, or if tasks had
4213 * If tasks join before we set the limit, a person looking at
4214 * kmem.usage_in_bytes will have no way to determine when it took
4215 * place, which makes the value quite meaningless.
4217 * After it first became limited, changes in the value of the limit are
4218 * of course permitted.
4220 * Taking the cgroup_lock is really offensive, but it is so far the only
4221 * way to guarantee that no children will appear. There are plenty of
4222 * other offenders, and they should all go away. Fine grained locking
4223 * is probably the way to go here. When we are fully hierarchical, we
4224 * can also get rid of the use_hierarchy check.
4227 mutex_lock(&set_limit_mutex
);
4228 if (!memcg
->kmem_account_flags
&& val
!= RESOURCE_MAX
) {
4229 if (cgroup_task_count(cont
) || (memcg
->use_hierarchy
&&
4230 !list_empty(&cont
->children
))) {
4234 ret
= res_counter_set_limit(&memcg
->kmem
, val
);
4237 memcg_kmem_set_active(memcg
);
4239 * kmem charges can outlive the cgroup. In the case of slab
4240 * pages, for instance, a page contain objects from various
4241 * processes, so it is unfeasible to migrate them away. We
4242 * need to reference count the memcg because of that.
4244 mem_cgroup_get(memcg
);
4246 ret
= res_counter_set_limit(&memcg
->kmem
, val
);
4248 mutex_unlock(&set_limit_mutex
);
4254 static void memcg_propagate_kmem(struct mem_cgroup
*memcg
)
4256 struct mem_cgroup
*parent
= parent_mem_cgroup(memcg
);
4259 memcg
->kmem_account_flags
= parent
->kmem_account_flags
;
4260 #ifdef CONFIG_MEMCG_KMEM
4261 if (memcg_kmem_is_active(memcg
))
4262 mem_cgroup_get(memcg
);
4267 * The user of this function is...
4270 static int mem_cgroup_write(struct cgroup
*cont
, struct cftype
*cft
,
4273 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cont
);
4276 unsigned long long val
;
4279 type
= MEMFILE_TYPE(cft
->private);
4280 name
= MEMFILE_ATTR(cft
->private);
4282 if (!do_swap_account
&& type
== _MEMSWAP
)
4287 if (mem_cgroup_is_root(memcg
)) { /* Can't set limit on root */
4291 /* This function does all necessary parse...reuse it */
4292 ret
= res_counter_memparse_write_strategy(buffer
, &val
);
4296 ret
= mem_cgroup_resize_limit(memcg
, val
);
4297 else if (type
== _MEMSWAP
)
4298 ret
= mem_cgroup_resize_memsw_limit(memcg
, val
);
4299 else if (type
== _KMEM
)
4300 ret
= memcg_update_kmem_limit(cont
, val
);
4304 case RES_SOFT_LIMIT
:
4305 ret
= res_counter_memparse_write_strategy(buffer
, &val
);
4309 * For memsw, soft limits are hard to implement in terms
4310 * of semantics, for now, we support soft limits for
4311 * control without swap
4314 ret
= res_counter_set_soft_limit(&memcg
->res
, val
);
4319 ret
= -EINVAL
; /* should be BUG() ? */
4325 static void memcg_get_hierarchical_limit(struct mem_cgroup
*memcg
,
4326 unsigned long long *mem_limit
, unsigned long long *memsw_limit
)
4328 struct cgroup
*cgroup
;
4329 unsigned long long min_limit
, min_memsw_limit
, tmp
;
4331 min_limit
= res_counter_read_u64(&memcg
->res
, RES_LIMIT
);
4332 min_memsw_limit
= res_counter_read_u64(&memcg
->memsw
, RES_LIMIT
);
4333 cgroup
= memcg
->css
.cgroup
;
4334 if (!memcg
->use_hierarchy
)
4337 while (cgroup
->parent
) {
4338 cgroup
= cgroup
->parent
;
4339 memcg
= mem_cgroup_from_cont(cgroup
);
4340 if (!memcg
->use_hierarchy
)
4342 tmp
= res_counter_read_u64(&memcg
->res
, RES_LIMIT
);
4343 min_limit
= min(min_limit
, tmp
);
4344 tmp
= res_counter_read_u64(&memcg
->memsw
, RES_LIMIT
);
4345 min_memsw_limit
= min(min_memsw_limit
, tmp
);
4348 *mem_limit
= min_limit
;
4349 *memsw_limit
= min_memsw_limit
;
4352 static int mem_cgroup_reset(struct cgroup
*cont
, unsigned int event
)
4354 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cont
);
4358 type
= MEMFILE_TYPE(event
);
4359 name
= MEMFILE_ATTR(event
);
4361 if (!do_swap_account
&& type
== _MEMSWAP
)
4367 res_counter_reset_max(&memcg
->res
);
4368 else if (type
== _MEMSWAP
)
4369 res_counter_reset_max(&memcg
->memsw
);
4370 else if (type
== _KMEM
)
4371 res_counter_reset_max(&memcg
->kmem
);
4377 res_counter_reset_failcnt(&memcg
->res
);
4378 else if (type
== _MEMSWAP
)
4379 res_counter_reset_failcnt(&memcg
->memsw
);
4380 else if (type
== _KMEM
)
4381 res_counter_reset_failcnt(&memcg
->kmem
);
4390 static u64
mem_cgroup_move_charge_read(struct cgroup
*cgrp
,
4393 return mem_cgroup_from_cont(cgrp
)->move_charge_at_immigrate
;
4397 static int mem_cgroup_move_charge_write(struct cgroup
*cgrp
,
4398 struct cftype
*cft
, u64 val
)
4400 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cgrp
);
4402 if (val
>= (1 << NR_MOVE_TYPE
))
4405 * We check this value several times in both in can_attach() and
4406 * attach(), so we need cgroup lock to prevent this value from being
4410 memcg
->move_charge_at_immigrate
= val
;
4416 static int mem_cgroup_move_charge_write(struct cgroup
*cgrp
,
4417 struct cftype
*cft
, u64 val
)
4424 static int memcg_numa_stat_show(struct cgroup
*cont
, struct cftype
*cft
,
4428 unsigned long total_nr
, file_nr
, anon_nr
, unevictable_nr
;
4429 unsigned long node_nr
;
4430 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cont
);
4432 total_nr
= mem_cgroup_nr_lru_pages(memcg
, LRU_ALL
);
4433 seq_printf(m
, "total=%lu", total_nr
);
4434 for_each_node_state(nid
, N_MEMORY
) {
4435 node_nr
= mem_cgroup_node_nr_lru_pages(memcg
, nid
, LRU_ALL
);
4436 seq_printf(m
, " N%d=%lu", nid
, node_nr
);
4440 file_nr
= mem_cgroup_nr_lru_pages(memcg
, LRU_ALL_FILE
);
4441 seq_printf(m
, "file=%lu", file_nr
);
4442 for_each_node_state(nid
, N_MEMORY
) {
4443 node_nr
= mem_cgroup_node_nr_lru_pages(memcg
, nid
,
4445 seq_printf(m
, " N%d=%lu", nid
, node_nr
);
4449 anon_nr
= mem_cgroup_nr_lru_pages(memcg
, LRU_ALL_ANON
);
4450 seq_printf(m
, "anon=%lu", anon_nr
);
4451 for_each_node_state(nid
, N_MEMORY
) {
4452 node_nr
= mem_cgroup_node_nr_lru_pages(memcg
, nid
,
4454 seq_printf(m
, " N%d=%lu", nid
, node_nr
);
4458 unevictable_nr
= mem_cgroup_nr_lru_pages(memcg
, BIT(LRU_UNEVICTABLE
));
4459 seq_printf(m
, "unevictable=%lu", unevictable_nr
);
4460 for_each_node_state(nid
, N_MEMORY
) {
4461 node_nr
= mem_cgroup_node_nr_lru_pages(memcg
, nid
,
4462 BIT(LRU_UNEVICTABLE
));
4463 seq_printf(m
, " N%d=%lu", nid
, node_nr
);
4468 #endif /* CONFIG_NUMA */
4470 static const char * const mem_cgroup_lru_names
[] = {
4478 static inline void mem_cgroup_lru_names_not_uptodate(void)
4480 BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_lru_names
) != NR_LRU_LISTS
);
4483 static int memcg_stat_show(struct cgroup
*cont
, struct cftype
*cft
,
4486 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cont
);
4487 struct mem_cgroup
*mi
;
4490 for (i
= 0; i
< MEM_CGROUP_STAT_NSTATS
; i
++) {
4491 if (i
== MEM_CGROUP_STAT_SWAP
&& !do_swap_account
)
4493 seq_printf(m
, "%s %ld\n", mem_cgroup_stat_names
[i
],
4494 mem_cgroup_read_stat(memcg
, i
) * PAGE_SIZE
);
4497 for (i
= 0; i
< MEM_CGROUP_EVENTS_NSTATS
; i
++)
4498 seq_printf(m
, "%s %lu\n", mem_cgroup_events_names
[i
],
4499 mem_cgroup_read_events(memcg
, i
));
4501 for (i
= 0; i
< NR_LRU_LISTS
; i
++)
4502 seq_printf(m
, "%s %lu\n", mem_cgroup_lru_names
[i
],
4503 mem_cgroup_nr_lru_pages(memcg
, BIT(i
)) * PAGE_SIZE
);
4505 /* Hierarchical information */
4507 unsigned long long limit
, memsw_limit
;
4508 memcg_get_hierarchical_limit(memcg
, &limit
, &memsw_limit
);
4509 seq_printf(m
, "hierarchical_memory_limit %llu\n", limit
);
4510 if (do_swap_account
)
4511 seq_printf(m
, "hierarchical_memsw_limit %llu\n",
4515 for (i
= 0; i
< MEM_CGROUP_STAT_NSTATS
; i
++) {
4518 if (i
== MEM_CGROUP_STAT_SWAP
&& !do_swap_account
)
4520 for_each_mem_cgroup_tree(mi
, memcg
)
4521 val
+= mem_cgroup_read_stat(mi
, i
) * PAGE_SIZE
;
4522 seq_printf(m
, "total_%s %lld\n", mem_cgroup_stat_names
[i
], val
);
4525 for (i
= 0; i
< MEM_CGROUP_EVENTS_NSTATS
; i
++) {
4526 unsigned long long val
= 0;
4528 for_each_mem_cgroup_tree(mi
, memcg
)
4529 val
+= mem_cgroup_read_events(mi
, i
);
4530 seq_printf(m
, "total_%s %llu\n",
4531 mem_cgroup_events_names
[i
], val
);
4534 for (i
= 0; i
< NR_LRU_LISTS
; i
++) {
4535 unsigned long long val
= 0;
4537 for_each_mem_cgroup_tree(mi
, memcg
)
4538 val
+= mem_cgroup_nr_lru_pages(mi
, BIT(i
)) * PAGE_SIZE
;
4539 seq_printf(m
, "total_%s %llu\n", mem_cgroup_lru_names
[i
], val
);
4542 #ifdef CONFIG_DEBUG_VM
4545 struct mem_cgroup_per_zone
*mz
;
4546 struct zone_reclaim_stat
*rstat
;
4547 unsigned long recent_rotated
[2] = {0, 0};
4548 unsigned long recent_scanned
[2] = {0, 0};
4550 for_each_online_node(nid
)
4551 for (zid
= 0; zid
< MAX_NR_ZONES
; zid
++) {
4552 mz
= mem_cgroup_zoneinfo(memcg
, nid
, zid
);
4553 rstat
= &mz
->lruvec
.reclaim_stat
;
4555 recent_rotated
[0] += rstat
->recent_rotated
[0];
4556 recent_rotated
[1] += rstat
->recent_rotated
[1];
4557 recent_scanned
[0] += rstat
->recent_scanned
[0];
4558 recent_scanned
[1] += rstat
->recent_scanned
[1];
4560 seq_printf(m
, "recent_rotated_anon %lu\n", recent_rotated
[0]);
4561 seq_printf(m
, "recent_rotated_file %lu\n", recent_rotated
[1]);
4562 seq_printf(m
, "recent_scanned_anon %lu\n", recent_scanned
[0]);
4563 seq_printf(m
, "recent_scanned_file %lu\n", recent_scanned
[1]);
4570 static u64
mem_cgroup_swappiness_read(struct cgroup
*cgrp
, struct cftype
*cft
)
4572 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cgrp
);
4574 return mem_cgroup_swappiness(memcg
);
4577 static int mem_cgroup_swappiness_write(struct cgroup
*cgrp
, struct cftype
*cft
,
4580 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cgrp
);
4581 struct mem_cgroup
*parent
;
4586 if (cgrp
->parent
== NULL
)
4589 parent
= mem_cgroup_from_cont(cgrp
->parent
);
4593 /* If under hierarchy, only empty-root can set this value */
4594 if ((parent
->use_hierarchy
) ||
4595 (memcg
->use_hierarchy
&& !list_empty(&cgrp
->children
))) {
4600 memcg
->swappiness
= val
;
4607 static void __mem_cgroup_threshold(struct mem_cgroup
*memcg
, bool swap
)
4609 struct mem_cgroup_threshold_ary
*t
;
4615 t
= rcu_dereference(memcg
->thresholds
.primary
);
4617 t
= rcu_dereference(memcg
->memsw_thresholds
.primary
);
4622 usage
= mem_cgroup_usage(memcg
, swap
);
4625 * current_threshold points to threshold just below or equal to usage.
4626 * If it's not true, a threshold was crossed after last
4627 * call of __mem_cgroup_threshold().
4629 i
= t
->current_threshold
;
4632 * Iterate backward over array of thresholds starting from
4633 * current_threshold and check if a threshold is crossed.
4634 * If none of thresholds below usage is crossed, we read
4635 * only one element of the array here.
4637 for (; i
>= 0 && unlikely(t
->entries
[i
].threshold
> usage
); i
--)
4638 eventfd_signal(t
->entries
[i
].eventfd
, 1);
4640 /* i = current_threshold + 1 */
4644 * Iterate forward over array of thresholds starting from
4645 * current_threshold+1 and check if a threshold is crossed.
4646 * If none of thresholds above usage is crossed, we read
4647 * only one element of the array here.
4649 for (; i
< t
->size
&& unlikely(t
->entries
[i
].threshold
<= usage
); i
++)
4650 eventfd_signal(t
->entries
[i
].eventfd
, 1);
4652 /* Update current_threshold */
4653 t
->current_threshold
= i
- 1;
4658 static void mem_cgroup_threshold(struct mem_cgroup
*memcg
)
4661 __mem_cgroup_threshold(memcg
, false);
4662 if (do_swap_account
)
4663 __mem_cgroup_threshold(memcg
, true);
4665 memcg
= parent_mem_cgroup(memcg
);
4669 static int compare_thresholds(const void *a
, const void *b
)
4671 const struct mem_cgroup_threshold
*_a
= a
;
4672 const struct mem_cgroup_threshold
*_b
= b
;
4674 return _a
->threshold
- _b
->threshold
;
4677 static int mem_cgroup_oom_notify_cb(struct mem_cgroup
*memcg
)
4679 struct mem_cgroup_eventfd_list
*ev
;
4681 list_for_each_entry(ev
, &memcg
->oom_notify
, list
)
4682 eventfd_signal(ev
->eventfd
, 1);
4686 static void mem_cgroup_oom_notify(struct mem_cgroup
*memcg
)
4688 struct mem_cgroup
*iter
;
4690 for_each_mem_cgroup_tree(iter
, memcg
)
4691 mem_cgroup_oom_notify_cb(iter
);
4694 static int mem_cgroup_usage_register_event(struct cgroup
*cgrp
,
4695 struct cftype
*cft
, struct eventfd_ctx
*eventfd
, const char *args
)
4697 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cgrp
);
4698 struct mem_cgroup_thresholds
*thresholds
;
4699 struct mem_cgroup_threshold_ary
*new;
4700 enum res_type type
= MEMFILE_TYPE(cft
->private);
4701 u64 threshold
, usage
;
4704 ret
= res_counter_memparse_write_strategy(args
, &threshold
);
4708 mutex_lock(&memcg
->thresholds_lock
);
4711 thresholds
= &memcg
->thresholds
;
4712 else if (type
== _MEMSWAP
)
4713 thresholds
= &memcg
->memsw_thresholds
;
4717 usage
= mem_cgroup_usage(memcg
, type
== _MEMSWAP
);
4719 /* Check if a threshold crossed before adding a new one */
4720 if (thresholds
->primary
)
4721 __mem_cgroup_threshold(memcg
, type
== _MEMSWAP
);
4723 size
= thresholds
->primary
? thresholds
->primary
->size
+ 1 : 1;
4725 /* Allocate memory for new array of thresholds */
4726 new = kmalloc(sizeof(*new) + size
* sizeof(struct mem_cgroup_threshold
),
4734 /* Copy thresholds (if any) to new array */
4735 if (thresholds
->primary
) {
4736 memcpy(new->entries
, thresholds
->primary
->entries
, (size
- 1) *
4737 sizeof(struct mem_cgroup_threshold
));
4740 /* Add new threshold */
4741 new->entries
[size
- 1].eventfd
= eventfd
;
4742 new->entries
[size
- 1].threshold
= threshold
;
4744 /* Sort thresholds. Registering of new threshold isn't time-critical */
4745 sort(new->entries
, size
, sizeof(struct mem_cgroup_threshold
),
4746 compare_thresholds
, NULL
);
4748 /* Find current threshold */
4749 new->current_threshold
= -1;
4750 for (i
= 0; i
< size
; i
++) {
4751 if (new->entries
[i
].threshold
<= usage
) {
4753 * new->current_threshold will not be used until
4754 * rcu_assign_pointer(), so it's safe to increment
4757 ++new->current_threshold
;
4762 /* Free old spare buffer and save old primary buffer as spare */
4763 kfree(thresholds
->spare
);
4764 thresholds
->spare
= thresholds
->primary
;
4766 rcu_assign_pointer(thresholds
->primary
, new);
4768 /* To be sure that nobody uses thresholds */
4772 mutex_unlock(&memcg
->thresholds_lock
);
4777 static void mem_cgroup_usage_unregister_event(struct cgroup
*cgrp
,
4778 struct cftype
*cft
, struct eventfd_ctx
*eventfd
)
4780 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cgrp
);
4781 struct mem_cgroup_thresholds
*thresholds
;
4782 struct mem_cgroup_threshold_ary
*new;
4783 enum res_type type
= MEMFILE_TYPE(cft
->private);
4787 mutex_lock(&memcg
->thresholds_lock
);
4789 thresholds
= &memcg
->thresholds
;
4790 else if (type
== _MEMSWAP
)
4791 thresholds
= &memcg
->memsw_thresholds
;
4795 if (!thresholds
->primary
)
4798 usage
= mem_cgroup_usage(memcg
, type
== _MEMSWAP
);
4800 /* Check if a threshold crossed before removing */
4801 __mem_cgroup_threshold(memcg
, type
== _MEMSWAP
);
4803 /* Calculate new number of threshold */
4805 for (i
= 0; i
< thresholds
->primary
->size
; i
++) {
4806 if (thresholds
->primary
->entries
[i
].eventfd
!= eventfd
)
4810 new = thresholds
->spare
;
4812 /* Set thresholds array to NULL if we don't have thresholds */
4821 /* Copy thresholds and find current threshold */
4822 new->current_threshold
= -1;
4823 for (i
= 0, j
= 0; i
< thresholds
->primary
->size
; i
++) {
4824 if (thresholds
->primary
->entries
[i
].eventfd
== eventfd
)
4827 new->entries
[j
] = thresholds
->primary
->entries
[i
];
4828 if (new->entries
[j
].threshold
<= usage
) {
4830 * new->current_threshold will not be used
4831 * until rcu_assign_pointer(), so it's safe to increment
4834 ++new->current_threshold
;
4840 /* Swap primary and spare array */
4841 thresholds
->spare
= thresholds
->primary
;
4842 /* If all events are unregistered, free the spare array */
4844 kfree(thresholds
->spare
);
4845 thresholds
->spare
= NULL
;
4848 rcu_assign_pointer(thresholds
->primary
, new);
4850 /* To be sure that nobody uses thresholds */
4853 mutex_unlock(&memcg
->thresholds_lock
);
4856 static int mem_cgroup_oom_register_event(struct cgroup
*cgrp
,
4857 struct cftype
*cft
, struct eventfd_ctx
*eventfd
, const char *args
)
4859 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cgrp
);
4860 struct mem_cgroup_eventfd_list
*event
;
4861 enum res_type type
= MEMFILE_TYPE(cft
->private);
4863 BUG_ON(type
!= _OOM_TYPE
);
4864 event
= kmalloc(sizeof(*event
), GFP_KERNEL
);
4868 spin_lock(&memcg_oom_lock
);
4870 event
->eventfd
= eventfd
;
4871 list_add(&event
->list
, &memcg
->oom_notify
);
4873 /* already in OOM ? */
4874 if (atomic_read(&memcg
->under_oom
))
4875 eventfd_signal(eventfd
, 1);
4876 spin_unlock(&memcg_oom_lock
);
4881 static void mem_cgroup_oom_unregister_event(struct cgroup
*cgrp
,
4882 struct cftype
*cft
, struct eventfd_ctx
*eventfd
)
4884 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cgrp
);
4885 struct mem_cgroup_eventfd_list
*ev
, *tmp
;
4886 enum res_type type
= MEMFILE_TYPE(cft
->private);
4888 BUG_ON(type
!= _OOM_TYPE
);
4890 spin_lock(&memcg_oom_lock
);
4892 list_for_each_entry_safe(ev
, tmp
, &memcg
->oom_notify
, list
) {
4893 if (ev
->eventfd
== eventfd
) {
4894 list_del(&ev
->list
);
4899 spin_unlock(&memcg_oom_lock
);
4902 static int mem_cgroup_oom_control_read(struct cgroup
*cgrp
,
4903 struct cftype
*cft
, struct cgroup_map_cb
*cb
)
4905 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cgrp
);
4907 cb
->fill(cb
, "oom_kill_disable", memcg
->oom_kill_disable
);
4909 if (atomic_read(&memcg
->under_oom
))
4910 cb
->fill(cb
, "under_oom", 1);
4912 cb
->fill(cb
, "under_oom", 0);
4916 static int mem_cgroup_oom_control_write(struct cgroup
*cgrp
,
4917 struct cftype
*cft
, u64 val
)
4919 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cgrp
);
4920 struct mem_cgroup
*parent
;
4922 /* cannot set to root cgroup and only 0 and 1 are allowed */
4923 if (!cgrp
->parent
|| !((val
== 0) || (val
== 1)))
4926 parent
= mem_cgroup_from_cont(cgrp
->parent
);
4929 /* oom-kill-disable is a flag for subhierarchy. */
4930 if ((parent
->use_hierarchy
) ||
4931 (memcg
->use_hierarchy
&& !list_empty(&cgrp
->children
))) {
4935 memcg
->oom_kill_disable
= val
;
4937 memcg_oom_recover(memcg
);
4942 #ifdef CONFIG_MEMCG_KMEM
4943 static int memcg_init_kmem(struct mem_cgroup
*memcg
, struct cgroup_subsys
*ss
)
4945 memcg_propagate_kmem(memcg
);
4946 return mem_cgroup_sockets_init(memcg
, ss
);
4949 static void kmem_cgroup_destroy(struct mem_cgroup
*memcg
)
4951 mem_cgroup_sockets_destroy(memcg
);
4953 memcg_kmem_mark_dead(memcg
);
4955 if (res_counter_read_u64(&memcg
->kmem
, RES_USAGE
) != 0)
4959 * Charges already down to 0, undo mem_cgroup_get() done in the charge
4960 * path here, being careful not to race with memcg_uncharge_kmem: it is
4961 * possible that the charges went down to 0 between mark_dead and the
4962 * res_counter read, so in that case, we don't need the put
4964 if (memcg_kmem_test_and_clear_dead(memcg
))
4965 mem_cgroup_put(memcg
);
4968 static int memcg_init_kmem(struct mem_cgroup
*memcg
, struct cgroup_subsys
*ss
)
4973 static void kmem_cgroup_destroy(struct mem_cgroup
*memcg
)
4978 static struct cftype mem_cgroup_files
[] = {
4980 .name
= "usage_in_bytes",
4981 .private = MEMFILE_PRIVATE(_MEM
, RES_USAGE
),
4982 .read
= mem_cgroup_read
,
4983 .register_event
= mem_cgroup_usage_register_event
,
4984 .unregister_event
= mem_cgroup_usage_unregister_event
,
4987 .name
= "max_usage_in_bytes",
4988 .private = MEMFILE_PRIVATE(_MEM
, RES_MAX_USAGE
),
4989 .trigger
= mem_cgroup_reset
,
4990 .read
= mem_cgroup_read
,
4993 .name
= "limit_in_bytes",
4994 .private = MEMFILE_PRIVATE(_MEM
, RES_LIMIT
),
4995 .write_string
= mem_cgroup_write
,
4996 .read
= mem_cgroup_read
,
4999 .name
= "soft_limit_in_bytes",
5000 .private = MEMFILE_PRIVATE(_MEM
, RES_SOFT_LIMIT
),
5001 .write_string
= mem_cgroup_write
,
5002 .read
= mem_cgroup_read
,
5006 .private = MEMFILE_PRIVATE(_MEM
, RES_FAILCNT
),
5007 .trigger
= mem_cgroup_reset
,
5008 .read
= mem_cgroup_read
,
5012 .read_seq_string
= memcg_stat_show
,
5015 .name
= "force_empty",
5016 .trigger
= mem_cgroup_force_empty_write
,
5019 .name
= "use_hierarchy",
5020 .write_u64
= mem_cgroup_hierarchy_write
,
5021 .read_u64
= mem_cgroup_hierarchy_read
,
5024 .name
= "swappiness",
5025 .read_u64
= mem_cgroup_swappiness_read
,
5026 .write_u64
= mem_cgroup_swappiness_write
,
5029 .name
= "move_charge_at_immigrate",
5030 .read_u64
= mem_cgroup_move_charge_read
,
5031 .write_u64
= mem_cgroup_move_charge_write
,
5034 .name
= "oom_control",
5035 .read_map
= mem_cgroup_oom_control_read
,
5036 .write_u64
= mem_cgroup_oom_control_write
,
5037 .register_event
= mem_cgroup_oom_register_event
,
5038 .unregister_event
= mem_cgroup_oom_unregister_event
,
5039 .private = MEMFILE_PRIVATE(_OOM_TYPE
, OOM_CONTROL
),
5043 .name
= "numa_stat",
5044 .read_seq_string
= memcg_numa_stat_show
,
5047 #ifdef CONFIG_MEMCG_SWAP
5049 .name
= "memsw.usage_in_bytes",
5050 .private = MEMFILE_PRIVATE(_MEMSWAP
, RES_USAGE
),
5051 .read
= mem_cgroup_read
,
5052 .register_event
= mem_cgroup_usage_register_event
,
5053 .unregister_event
= mem_cgroup_usage_unregister_event
,
5056 .name
= "memsw.max_usage_in_bytes",
5057 .private = MEMFILE_PRIVATE(_MEMSWAP
, RES_MAX_USAGE
),
5058 .trigger
= mem_cgroup_reset
,
5059 .read
= mem_cgroup_read
,
5062 .name
= "memsw.limit_in_bytes",
5063 .private = MEMFILE_PRIVATE(_MEMSWAP
, RES_LIMIT
),
5064 .write_string
= mem_cgroup_write
,
5065 .read
= mem_cgroup_read
,
5068 .name
= "memsw.failcnt",
5069 .private = MEMFILE_PRIVATE(_MEMSWAP
, RES_FAILCNT
),
5070 .trigger
= mem_cgroup_reset
,
5071 .read
= mem_cgroup_read
,
5074 #ifdef CONFIG_MEMCG_KMEM
5076 .name
= "kmem.limit_in_bytes",
5077 .private = MEMFILE_PRIVATE(_KMEM
, RES_LIMIT
),
5078 .write_string
= mem_cgroup_write
,
5079 .read
= mem_cgroup_read
,
5082 .name
= "kmem.usage_in_bytes",
5083 .private = MEMFILE_PRIVATE(_KMEM
, RES_USAGE
),
5084 .read
= mem_cgroup_read
,
5087 .name
= "kmem.failcnt",
5088 .private = MEMFILE_PRIVATE(_KMEM
, RES_FAILCNT
),
5089 .trigger
= mem_cgroup_reset
,
5090 .read
= mem_cgroup_read
,
5093 .name
= "kmem.max_usage_in_bytes",
5094 .private = MEMFILE_PRIVATE(_KMEM
, RES_MAX_USAGE
),
5095 .trigger
= mem_cgroup_reset
,
5096 .read
= mem_cgroup_read
,
5099 { }, /* terminate */
5102 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup
*memcg
, int node
)
5104 struct mem_cgroup_per_node
*pn
;
5105 struct mem_cgroup_per_zone
*mz
;
5106 int zone
, tmp
= node
;
5108 * This routine is called against possible nodes.
5109 * But it's BUG to call kmalloc() against offline node.
5111 * TODO: this routine can waste much memory for nodes which will
5112 * never be onlined. It's better to use memory hotplug callback
5115 if (!node_state(node
, N_NORMAL_MEMORY
))
5117 pn
= kzalloc_node(sizeof(*pn
), GFP_KERNEL
, tmp
);
5121 for (zone
= 0; zone
< MAX_NR_ZONES
; zone
++) {
5122 mz
= &pn
->zoneinfo
[zone
];
5123 lruvec_init(&mz
->lruvec
);
5124 mz
->usage_in_excess
= 0;
5125 mz
->on_tree
= false;
5128 memcg
->info
.nodeinfo
[node
] = pn
;
5132 static void free_mem_cgroup_per_zone_info(struct mem_cgroup
*memcg
, int node
)
5134 kfree(memcg
->info
.nodeinfo
[node
]);
5137 static struct mem_cgroup
*mem_cgroup_alloc(void)
5139 struct mem_cgroup
*memcg
;
5140 int size
= sizeof(struct mem_cgroup
);
5142 /* Can be very big if MAX_NUMNODES is very big */
5143 if (size
< PAGE_SIZE
)
5144 memcg
= kzalloc(size
, GFP_KERNEL
);
5146 memcg
= vzalloc(size
);
5151 memcg
->stat
= alloc_percpu(struct mem_cgroup_stat_cpu
);
5154 spin_lock_init(&memcg
->pcp_counter_lock
);
5158 if (size
< PAGE_SIZE
)
5166 * Helpers for freeing a kmalloc()ed/vzalloc()ed mem_cgroup by RCU,
5167 * but in process context. The work_freeing structure is overlaid
5168 * on the rcu_freeing structure, which itself is overlaid on memsw.
5170 static void free_work(struct work_struct
*work
)
5172 struct mem_cgroup
*memcg
;
5173 int size
= sizeof(struct mem_cgroup
);
5175 memcg
= container_of(work
, struct mem_cgroup
, work_freeing
);
5177 * We need to make sure that (at least for now), the jump label
5178 * destruction code runs outside of the cgroup lock. This is because
5179 * get_online_cpus(), which is called from the static_branch update,
5180 * can't be called inside the cgroup_lock. cpusets are the ones
5181 * enforcing this dependency, so if they ever change, we might as well.
5183 * schedule_work() will guarantee this happens. Be careful if you need
5184 * to move this code around, and make sure it is outside
5187 disarm_sock_keys(memcg
);
5188 if (size
< PAGE_SIZE
)
5194 static void free_rcu(struct rcu_head
*rcu_head
)
5196 struct mem_cgroup
*memcg
;
5198 memcg
= container_of(rcu_head
, struct mem_cgroup
, rcu_freeing
);
5199 INIT_WORK(&memcg
->work_freeing
, free_work
);
5200 schedule_work(&memcg
->work_freeing
);
5204 * At destroying mem_cgroup, references from swap_cgroup can remain.
5205 * (scanning all at force_empty is too costly...)
5207 * Instead of clearing all references at force_empty, we remember
5208 * the number of reference from swap_cgroup and free mem_cgroup when
5209 * it goes down to 0.
5211 * Removal of cgroup itself succeeds regardless of refs from swap.
5214 static void __mem_cgroup_free(struct mem_cgroup
*memcg
)
5218 mem_cgroup_remove_from_trees(memcg
);
5219 free_css_id(&mem_cgroup_subsys
, &memcg
->css
);
5222 free_mem_cgroup_per_zone_info(memcg
, node
);
5224 free_percpu(memcg
->stat
);
5225 call_rcu(&memcg
->rcu_freeing
, free_rcu
);
5228 static void mem_cgroup_get(struct mem_cgroup
*memcg
)
5230 atomic_inc(&memcg
->refcnt
);
5233 static void __mem_cgroup_put(struct mem_cgroup
*memcg
, int count
)
5235 if (atomic_sub_and_test(count
, &memcg
->refcnt
)) {
5236 struct mem_cgroup
*parent
= parent_mem_cgroup(memcg
);
5237 __mem_cgroup_free(memcg
);
5239 mem_cgroup_put(parent
);
5243 static void mem_cgroup_put(struct mem_cgroup
*memcg
)
5245 __mem_cgroup_put(memcg
, 1);
5249 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
5251 struct mem_cgroup
*parent_mem_cgroup(struct mem_cgroup
*memcg
)
5253 if (!memcg
->res
.parent
)
5255 return mem_cgroup_from_res_counter(memcg
->res
.parent
, res
);
5257 EXPORT_SYMBOL(parent_mem_cgroup
);
5259 #ifdef CONFIG_MEMCG_SWAP
5260 static void __init
enable_swap_cgroup(void)
5262 if (!mem_cgroup_disabled() && really_do_swap_account
)
5263 do_swap_account
= 1;
5266 static void __init
enable_swap_cgroup(void)
5271 static int mem_cgroup_soft_limit_tree_init(void)
5273 struct mem_cgroup_tree_per_node
*rtpn
;
5274 struct mem_cgroup_tree_per_zone
*rtpz
;
5275 int tmp
, node
, zone
;
5277 for_each_node(node
) {
5279 if (!node_state(node
, N_NORMAL_MEMORY
))
5281 rtpn
= kzalloc_node(sizeof(*rtpn
), GFP_KERNEL
, tmp
);
5285 soft_limit_tree
.rb_tree_per_node
[node
] = rtpn
;
5287 for (zone
= 0; zone
< MAX_NR_ZONES
; zone
++) {
5288 rtpz
= &rtpn
->rb_tree_per_zone
[zone
];
5289 rtpz
->rb_root
= RB_ROOT
;
5290 spin_lock_init(&rtpz
->lock
);
5296 for_each_node(node
) {
5297 if (!soft_limit_tree
.rb_tree_per_node
[node
])
5299 kfree(soft_limit_tree
.rb_tree_per_node
[node
]);
5300 soft_limit_tree
.rb_tree_per_node
[node
] = NULL
;
5306 static struct cgroup_subsys_state
* __ref
5307 mem_cgroup_css_alloc(struct cgroup
*cont
)
5309 struct mem_cgroup
*memcg
, *parent
;
5310 long error
= -ENOMEM
;
5313 memcg
= mem_cgroup_alloc();
5315 return ERR_PTR(error
);
5318 if (alloc_mem_cgroup_per_zone_info(memcg
, node
))
5322 if (cont
->parent
== NULL
) {
5324 enable_swap_cgroup();
5326 if (mem_cgroup_soft_limit_tree_init())
5328 root_mem_cgroup
= memcg
;
5329 for_each_possible_cpu(cpu
) {
5330 struct memcg_stock_pcp
*stock
=
5331 &per_cpu(memcg_stock
, cpu
);
5332 INIT_WORK(&stock
->work
, drain_local_stock
);
5334 hotcpu_notifier(memcg_cpu_hotplug_callback
, 0);
5336 parent
= mem_cgroup_from_cont(cont
->parent
);
5337 memcg
->use_hierarchy
= parent
->use_hierarchy
;
5338 memcg
->oom_kill_disable
= parent
->oom_kill_disable
;
5341 if (parent
&& parent
->use_hierarchy
) {
5342 res_counter_init(&memcg
->res
, &parent
->res
);
5343 res_counter_init(&memcg
->memsw
, &parent
->memsw
);
5344 res_counter_init(&memcg
->kmem
, &parent
->kmem
);
5346 * We increment refcnt of the parent to ensure that we can
5347 * safely access it on res_counter_charge/uncharge.
5348 * This refcnt will be decremented when freeing this
5349 * mem_cgroup(see mem_cgroup_put).
5351 mem_cgroup_get(parent
);
5353 res_counter_init(&memcg
->res
, NULL
);
5354 res_counter_init(&memcg
->memsw
, NULL
);
5355 res_counter_init(&memcg
->kmem
, NULL
);
5357 * Deeper hierachy with use_hierarchy == false doesn't make
5358 * much sense so let cgroup subsystem know about this
5359 * unfortunate state in our controller.
5361 if (parent
&& parent
!= root_mem_cgroup
)
5362 mem_cgroup_subsys
.broken_hierarchy
= true;
5364 memcg
->last_scanned_node
= MAX_NUMNODES
;
5365 INIT_LIST_HEAD(&memcg
->oom_notify
);
5368 memcg
->swappiness
= mem_cgroup_swappiness(parent
);
5369 atomic_set(&memcg
->refcnt
, 1);
5370 memcg
->move_charge_at_immigrate
= 0;
5371 mutex_init(&memcg
->thresholds_lock
);
5372 spin_lock_init(&memcg
->move_lock
);
5374 error
= memcg_init_kmem(memcg
, &mem_cgroup_subsys
);
5377 * We call put now because our (and parent's) refcnts
5378 * are already in place. mem_cgroup_put() will internally
5379 * call __mem_cgroup_free, so return directly
5381 mem_cgroup_put(memcg
);
5382 return ERR_PTR(error
);
5386 __mem_cgroup_free(memcg
);
5387 return ERR_PTR(error
);
5390 static void mem_cgroup_css_offline(struct cgroup
*cont
)
5392 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cont
);
5394 mem_cgroup_reparent_charges(memcg
);
5397 static void mem_cgroup_css_free(struct cgroup
*cont
)
5399 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cont
);
5401 kmem_cgroup_destroy(memcg
);
5403 mem_cgroup_put(memcg
);
5407 /* Handlers for move charge at task migration. */
5408 #define PRECHARGE_COUNT_AT_ONCE 256
5409 static int mem_cgroup_do_precharge(unsigned long count
)
5412 int batch_count
= PRECHARGE_COUNT_AT_ONCE
;
5413 struct mem_cgroup
*memcg
= mc
.to
;
5415 if (mem_cgroup_is_root(memcg
)) {
5416 mc
.precharge
+= count
;
5417 /* we don't need css_get for root */
5420 /* try to charge at once */
5422 struct res_counter
*dummy
;
5424 * "memcg" cannot be under rmdir() because we've already checked
5425 * by cgroup_lock_live_cgroup() that it is not removed and we
5426 * are still under the same cgroup_mutex. So we can postpone
5429 if (res_counter_charge(&memcg
->res
, PAGE_SIZE
* count
, &dummy
))
5431 if (do_swap_account
&& res_counter_charge(&memcg
->memsw
,
5432 PAGE_SIZE
* count
, &dummy
)) {
5433 res_counter_uncharge(&memcg
->res
, PAGE_SIZE
* count
);
5436 mc
.precharge
+= count
;
5440 /* fall back to one by one charge */
5442 if (signal_pending(current
)) {
5446 if (!batch_count
--) {
5447 batch_count
= PRECHARGE_COUNT_AT_ONCE
;
5450 ret
= __mem_cgroup_try_charge(NULL
,
5451 GFP_KERNEL
, 1, &memcg
, false);
5453 /* mem_cgroup_clear_mc() will do uncharge later */
5461 * get_mctgt_type - get target type of moving charge
5462 * @vma: the vma the pte to be checked belongs
5463 * @addr: the address corresponding to the pte to be checked
5464 * @ptent: the pte to be checked
5465 * @target: the pointer the target page or swap ent will be stored(can be NULL)
5468 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
5469 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5470 * move charge. if @target is not NULL, the page is stored in target->page
5471 * with extra refcnt got(Callers should handle it).
5472 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5473 * target for charge migration. if @target is not NULL, the entry is stored
5476 * Called with pte lock held.
5483 enum mc_target_type
{
5489 static struct page
*mc_handle_present_pte(struct vm_area_struct
*vma
,
5490 unsigned long addr
, pte_t ptent
)
5492 struct page
*page
= vm_normal_page(vma
, addr
, ptent
);
5494 if (!page
|| !page_mapped(page
))
5496 if (PageAnon(page
)) {
5497 /* we don't move shared anon */
5500 } else if (!move_file())
5501 /* we ignore mapcount for file pages */
5503 if (!get_page_unless_zero(page
))
5510 static struct page
*mc_handle_swap_pte(struct vm_area_struct
*vma
,
5511 unsigned long addr
, pte_t ptent
, swp_entry_t
*entry
)
5513 struct page
*page
= NULL
;
5514 swp_entry_t ent
= pte_to_swp_entry(ptent
);
5516 if (!move_anon() || non_swap_entry(ent
))
5519 * Because lookup_swap_cache() updates some statistics counter,
5520 * we call find_get_page() with swapper_space directly.
5522 page
= find_get_page(&swapper_space
, ent
.val
);
5523 if (do_swap_account
)
5524 entry
->val
= ent
.val
;
5529 static struct page
*mc_handle_swap_pte(struct vm_area_struct
*vma
,
5530 unsigned long addr
, pte_t ptent
, swp_entry_t
*entry
)
5536 static struct page
*mc_handle_file_pte(struct vm_area_struct
*vma
,
5537 unsigned long addr
, pte_t ptent
, swp_entry_t
*entry
)
5539 struct page
*page
= NULL
;
5540 struct address_space
*mapping
;
5543 if (!vma
->vm_file
) /* anonymous vma */
5548 mapping
= vma
->vm_file
->f_mapping
;
5549 if (pte_none(ptent
))
5550 pgoff
= linear_page_index(vma
, addr
);
5551 else /* pte_file(ptent) is true */
5552 pgoff
= pte_to_pgoff(ptent
);
5554 /* page is moved even if it's not RSS of this task(page-faulted). */
5555 page
= find_get_page(mapping
, pgoff
);
5558 /* shmem/tmpfs may report page out on swap: account for that too. */
5559 if (radix_tree_exceptional_entry(page
)) {
5560 swp_entry_t swap
= radix_to_swp_entry(page
);
5561 if (do_swap_account
)
5563 page
= find_get_page(&swapper_space
, swap
.val
);
5569 static enum mc_target_type
get_mctgt_type(struct vm_area_struct
*vma
,
5570 unsigned long addr
, pte_t ptent
, union mc_target
*target
)
5572 struct page
*page
= NULL
;
5573 struct page_cgroup
*pc
;
5574 enum mc_target_type ret
= MC_TARGET_NONE
;
5575 swp_entry_t ent
= { .val
= 0 };
5577 if (pte_present(ptent
))
5578 page
= mc_handle_present_pte(vma
, addr
, ptent
);
5579 else if (is_swap_pte(ptent
))
5580 page
= mc_handle_swap_pte(vma
, addr
, ptent
, &ent
);
5581 else if (pte_none(ptent
) || pte_file(ptent
))
5582 page
= mc_handle_file_pte(vma
, addr
, ptent
, &ent
);
5584 if (!page
&& !ent
.val
)
5587 pc
= lookup_page_cgroup(page
);
5589 * Do only loose check w/o page_cgroup lock.
5590 * mem_cgroup_move_account() checks the pc is valid or not under
5593 if (PageCgroupUsed(pc
) && pc
->mem_cgroup
== mc
.from
) {
5594 ret
= MC_TARGET_PAGE
;
5596 target
->page
= page
;
5598 if (!ret
|| !target
)
5601 /* There is a swap entry and a page doesn't exist or isn't charged */
5602 if (ent
.val
&& !ret
&&
5603 css_id(&mc
.from
->css
) == lookup_swap_cgroup_id(ent
)) {
5604 ret
= MC_TARGET_SWAP
;
5611 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5613 * We don't consider swapping or file mapped pages because THP does not
5614 * support them for now.
5615 * Caller should make sure that pmd_trans_huge(pmd) is true.
5617 static enum mc_target_type
get_mctgt_type_thp(struct vm_area_struct
*vma
,
5618 unsigned long addr
, pmd_t pmd
, union mc_target
*target
)
5620 struct page
*page
= NULL
;
5621 struct page_cgroup
*pc
;
5622 enum mc_target_type ret
= MC_TARGET_NONE
;
5624 page
= pmd_page(pmd
);
5625 VM_BUG_ON(!page
|| !PageHead(page
));
5628 pc
= lookup_page_cgroup(page
);
5629 if (PageCgroupUsed(pc
) && pc
->mem_cgroup
== mc
.from
) {
5630 ret
= MC_TARGET_PAGE
;
5633 target
->page
= page
;
5639 static inline enum mc_target_type
get_mctgt_type_thp(struct vm_area_struct
*vma
,
5640 unsigned long addr
, pmd_t pmd
, union mc_target
*target
)
5642 return MC_TARGET_NONE
;
5646 static int mem_cgroup_count_precharge_pte_range(pmd_t
*pmd
,
5647 unsigned long addr
, unsigned long end
,
5648 struct mm_walk
*walk
)
5650 struct vm_area_struct
*vma
= walk
->private;
5654 if (pmd_trans_huge_lock(pmd
, vma
) == 1) {
5655 if (get_mctgt_type_thp(vma
, addr
, *pmd
, NULL
) == MC_TARGET_PAGE
)
5656 mc
.precharge
+= HPAGE_PMD_NR
;
5657 spin_unlock(&vma
->vm_mm
->page_table_lock
);
5661 if (pmd_trans_unstable(pmd
))
5663 pte
= pte_offset_map_lock(vma
->vm_mm
, pmd
, addr
, &ptl
);
5664 for (; addr
!= end
; pte
++, addr
+= PAGE_SIZE
)
5665 if (get_mctgt_type(vma
, addr
, *pte
, NULL
))
5666 mc
.precharge
++; /* increment precharge temporarily */
5667 pte_unmap_unlock(pte
- 1, ptl
);
5673 static unsigned long mem_cgroup_count_precharge(struct mm_struct
*mm
)
5675 unsigned long precharge
;
5676 struct vm_area_struct
*vma
;
5678 down_read(&mm
->mmap_sem
);
5679 for (vma
= mm
->mmap
; vma
; vma
= vma
->vm_next
) {
5680 struct mm_walk mem_cgroup_count_precharge_walk
= {
5681 .pmd_entry
= mem_cgroup_count_precharge_pte_range
,
5685 if (is_vm_hugetlb_page(vma
))
5687 walk_page_range(vma
->vm_start
, vma
->vm_end
,
5688 &mem_cgroup_count_precharge_walk
);
5690 up_read(&mm
->mmap_sem
);
5692 precharge
= mc
.precharge
;
5698 static int mem_cgroup_precharge_mc(struct mm_struct
*mm
)
5700 unsigned long precharge
= mem_cgroup_count_precharge(mm
);
5702 VM_BUG_ON(mc
.moving_task
);
5703 mc
.moving_task
= current
;
5704 return mem_cgroup_do_precharge(precharge
);
5707 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5708 static void __mem_cgroup_clear_mc(void)
5710 struct mem_cgroup
*from
= mc
.from
;
5711 struct mem_cgroup
*to
= mc
.to
;
5713 /* we must uncharge all the leftover precharges from mc.to */
5715 __mem_cgroup_cancel_charge(mc
.to
, mc
.precharge
);
5719 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5720 * we must uncharge here.
5722 if (mc
.moved_charge
) {
5723 __mem_cgroup_cancel_charge(mc
.from
, mc
.moved_charge
);
5724 mc
.moved_charge
= 0;
5726 /* we must fixup refcnts and charges */
5727 if (mc
.moved_swap
) {
5728 /* uncharge swap account from the old cgroup */
5729 if (!mem_cgroup_is_root(mc
.from
))
5730 res_counter_uncharge(&mc
.from
->memsw
,
5731 PAGE_SIZE
* mc
.moved_swap
);
5732 __mem_cgroup_put(mc
.from
, mc
.moved_swap
);
5734 if (!mem_cgroup_is_root(mc
.to
)) {
5736 * we charged both to->res and to->memsw, so we should
5739 res_counter_uncharge(&mc
.to
->res
,
5740 PAGE_SIZE
* mc
.moved_swap
);
5742 /* we've already done mem_cgroup_get(mc.to) */
5745 memcg_oom_recover(from
);
5746 memcg_oom_recover(to
);
5747 wake_up_all(&mc
.waitq
);
5750 static void mem_cgroup_clear_mc(void)
5752 struct mem_cgroup
*from
= mc
.from
;
5755 * we must clear moving_task before waking up waiters at the end of
5758 mc
.moving_task
= NULL
;
5759 __mem_cgroup_clear_mc();
5760 spin_lock(&mc
.lock
);
5763 spin_unlock(&mc
.lock
);
5764 mem_cgroup_end_move(from
);
5767 static int mem_cgroup_can_attach(struct cgroup
*cgroup
,
5768 struct cgroup_taskset
*tset
)
5770 struct task_struct
*p
= cgroup_taskset_first(tset
);
5772 struct mem_cgroup
*memcg
= mem_cgroup_from_cont(cgroup
);
5774 if (memcg
->move_charge_at_immigrate
) {
5775 struct mm_struct
*mm
;
5776 struct mem_cgroup
*from
= mem_cgroup_from_task(p
);
5778 VM_BUG_ON(from
== memcg
);
5780 mm
= get_task_mm(p
);
5783 /* We move charges only when we move a owner of the mm */
5784 if (mm
->owner
== p
) {
5787 VM_BUG_ON(mc
.precharge
);
5788 VM_BUG_ON(mc
.moved_charge
);
5789 VM_BUG_ON(mc
.moved_swap
);
5790 mem_cgroup_start_move(from
);
5791 spin_lock(&mc
.lock
);
5794 spin_unlock(&mc
.lock
);
5795 /* We set mc.moving_task later */
5797 ret
= mem_cgroup_precharge_mc(mm
);
5799 mem_cgroup_clear_mc();
5806 static void mem_cgroup_cancel_attach(struct cgroup
*cgroup
,
5807 struct cgroup_taskset
*tset
)
5809 mem_cgroup_clear_mc();
5812 static int mem_cgroup_move_charge_pte_range(pmd_t
*pmd
,
5813 unsigned long addr
, unsigned long end
,
5814 struct mm_walk
*walk
)
5817 struct vm_area_struct
*vma
= walk
->private;
5820 enum mc_target_type target_type
;
5821 union mc_target target
;
5823 struct page_cgroup
*pc
;
5826 * We don't take compound_lock() here but no race with splitting thp
5828 * - if pmd_trans_huge_lock() returns 1, the relevant thp is not
5829 * under splitting, which means there's no concurrent thp split,
5830 * - if another thread runs into split_huge_page() just after we
5831 * entered this if-block, the thread must wait for page table lock
5832 * to be unlocked in __split_huge_page_splitting(), where the main
5833 * part of thp split is not executed yet.
5835 if (pmd_trans_huge_lock(pmd
, vma
) == 1) {
5836 if (mc
.precharge
< HPAGE_PMD_NR
) {
5837 spin_unlock(&vma
->vm_mm
->page_table_lock
);
5840 target_type
= get_mctgt_type_thp(vma
, addr
, *pmd
, &target
);
5841 if (target_type
== MC_TARGET_PAGE
) {
5843 if (!isolate_lru_page(page
)) {
5844 pc
= lookup_page_cgroup(page
);
5845 if (!mem_cgroup_move_account(page
, HPAGE_PMD_NR
,
5846 pc
, mc
.from
, mc
.to
)) {
5847 mc
.precharge
-= HPAGE_PMD_NR
;
5848 mc
.moved_charge
+= HPAGE_PMD_NR
;
5850 putback_lru_page(page
);
5854 spin_unlock(&vma
->vm_mm
->page_table_lock
);
5858 if (pmd_trans_unstable(pmd
))
5861 pte
= pte_offset_map_lock(vma
->vm_mm
, pmd
, addr
, &ptl
);
5862 for (; addr
!= end
; addr
+= PAGE_SIZE
) {
5863 pte_t ptent
= *(pte
++);
5869 switch (get_mctgt_type(vma
, addr
, ptent
, &target
)) {
5870 case MC_TARGET_PAGE
:
5872 if (isolate_lru_page(page
))
5874 pc
= lookup_page_cgroup(page
);
5875 if (!mem_cgroup_move_account(page
, 1, pc
,
5878 /* we uncharge from mc.from later. */
5881 putback_lru_page(page
);
5882 put
: /* get_mctgt_type() gets the page */
5885 case MC_TARGET_SWAP
:
5887 if (!mem_cgroup_move_swap_account(ent
, mc
.from
, mc
.to
)) {
5889 /* we fixup refcnts and charges later. */
5897 pte_unmap_unlock(pte
- 1, ptl
);
5902 * We have consumed all precharges we got in can_attach().
5903 * We try charge one by one, but don't do any additional
5904 * charges to mc.to if we have failed in charge once in attach()
5907 ret
= mem_cgroup_do_precharge(1);
5915 static void mem_cgroup_move_charge(struct mm_struct
*mm
)
5917 struct vm_area_struct
*vma
;
5919 lru_add_drain_all();
5921 if (unlikely(!down_read_trylock(&mm
->mmap_sem
))) {
5923 * Someone who are holding the mmap_sem might be waiting in
5924 * waitq. So we cancel all extra charges, wake up all waiters,
5925 * and retry. Because we cancel precharges, we might not be able
5926 * to move enough charges, but moving charge is a best-effort
5927 * feature anyway, so it wouldn't be a big problem.
5929 __mem_cgroup_clear_mc();
5933 for (vma
= mm
->mmap
; vma
; vma
= vma
->vm_next
) {
5935 struct mm_walk mem_cgroup_move_charge_walk
= {
5936 .pmd_entry
= mem_cgroup_move_charge_pte_range
,
5940 if (is_vm_hugetlb_page(vma
))
5942 ret
= walk_page_range(vma
->vm_start
, vma
->vm_end
,
5943 &mem_cgroup_move_charge_walk
);
5946 * means we have consumed all precharges and failed in
5947 * doing additional charge. Just abandon here.
5951 up_read(&mm
->mmap_sem
);
5954 static void mem_cgroup_move_task(struct cgroup
*cont
,
5955 struct cgroup_taskset
*tset
)
5957 struct task_struct
*p
= cgroup_taskset_first(tset
);
5958 struct mm_struct
*mm
= get_task_mm(p
);
5962 mem_cgroup_move_charge(mm
);
5966 mem_cgroup_clear_mc();
5968 #else /* !CONFIG_MMU */
5969 static int mem_cgroup_can_attach(struct cgroup
*cgroup
,
5970 struct cgroup_taskset
*tset
)
5974 static void mem_cgroup_cancel_attach(struct cgroup
*cgroup
,
5975 struct cgroup_taskset
*tset
)
5978 static void mem_cgroup_move_task(struct cgroup
*cont
,
5979 struct cgroup_taskset
*tset
)
5984 struct cgroup_subsys mem_cgroup_subsys
= {
5986 .subsys_id
= mem_cgroup_subsys_id
,
5987 .css_alloc
= mem_cgroup_css_alloc
,
5988 .css_offline
= mem_cgroup_css_offline
,
5989 .css_free
= mem_cgroup_css_free
,
5990 .can_attach
= mem_cgroup_can_attach
,
5991 .cancel_attach
= mem_cgroup_cancel_attach
,
5992 .attach
= mem_cgroup_move_task
,
5993 .base_cftypes
= mem_cgroup_files
,
5998 #ifdef CONFIG_MEMCG_SWAP
5999 static int __init
enable_swap_account(char *s
)
6001 /* consider enabled if no parameter or 1 is given */
6002 if (!strcmp(s
, "1"))
6003 really_do_swap_account
= 1;
6004 else if (!strcmp(s
, "0"))
6005 really_do_swap_account
= 0;
6008 __setup("swapaccount=", enable_swap_account
);