1 /* memcontrol.c - Memory Controller
3 * Copyright IBM Corporation, 2007
4 * Author Balbir Singh <balbir@linux.vnet.ibm.com>
6 * Copyright 2007 OpenVZ SWsoft Inc
7 * Author: Pavel Emelianov <xemul@openvz.org>
10 * Copyright (C) 2009 Nokia Corporation
11 * Author: Kirill A. Shutemov
13 * Kernel Memory Controller
14 * Copyright (C) 2012 Parallels Inc. and Google Inc.
15 * Authors: Glauber Costa and Suleiman Souhlal
17 * This program is free software; you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation; either version 2 of the License, or
20 * (at your option) any later version.
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
28 #include <linux/res_counter.h>
29 #include <linux/memcontrol.h>
30 #include <linux/cgroup.h>
32 #include <linux/hugetlb.h>
33 #include <linux/pagemap.h>
34 #include <linux/smp.h>
35 #include <linux/page-flags.h>
36 #include <linux/backing-dev.h>
37 #include <linux/bit_spinlock.h>
38 #include <linux/rcupdate.h>
39 #include <linux/limits.h>
40 #include <linux/export.h>
41 #include <linux/mutex.h>
42 #include <linux/rbtree.h>
43 #include <linux/slab.h>
44 #include <linux/swap.h>
45 #include <linux/swapops.h>
46 #include <linux/spinlock.h>
47 #include <linux/eventfd.h>
48 #include <linux/sort.h>
50 #include <linux/seq_file.h>
51 #include <linux/vmalloc.h>
52 #include <linux/mm_inline.h>
53 #include <linux/page_cgroup.h>
54 #include <linux/cpu.h>
55 #include <linux/oom.h>
59 #include <net/tcp_memcontrol.h>
61 #include <asm/uaccess.h>
63 #include <trace/events/vmscan.h>
65 struct cgroup_subsys mem_cgroup_subsys __read_mostly;
66 EXPORT_SYMBOL(mem_cgroup_subsys);
68 #define MEM_CGROUP_RECLAIM_RETRIES 5
69 static struct mem_cgroup *root_mem_cgroup __read_mostly;
71 #ifdef CONFIG_MEMCG_SWAP
72 /* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
73 int do_swap_account __read_mostly;
75 /* for remember boot option*/
76 #ifdef CONFIG_MEMCG_SWAP_ENABLED
77 static int really_do_swap_account __initdata = 1;
79 static int really_do_swap_account __initdata = 0;
83 #define do_swap_account 0
88 * Statistics for memory cgroup.
90 enum mem_cgroup_stat_index {
92 * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
94 MEM_CGROUP_STAT_CACHE, /* # of pages charged as cache */
95 MEM_CGROUP_STAT_RSS, /* # of pages charged as anon rss */
96 MEM_CGROUP_STAT_FILE_MAPPED, /* # of pages charged as file rss */
97 MEM_CGROUP_STAT_SWAP, /* # of pages, swapped out */
98 MEM_CGROUP_STAT_NSTATS,
101 static const char * const mem_cgroup_stat_names[] = {
108 enum mem_cgroup_events_index {
109 MEM_CGROUP_EVENTS_PGPGIN, /* # of pages paged in */
110 MEM_CGROUP_EVENTS_PGPGOUT, /* # of pages paged out */
111 MEM_CGROUP_EVENTS_PGFAULT, /* # of page-faults */
112 MEM_CGROUP_EVENTS_PGMAJFAULT, /* # of major page-faults */
113 MEM_CGROUP_EVENTS_NSTATS,
116 static const char * const mem_cgroup_events_names[] = {
124 * Per memcg event counter is incremented at every pagein/pageout. With THP,
125 * it will be incremated by the number of pages. This counter is used for
126 * for trigger some periodic events. This is straightforward and better
127 * than using jiffies etc. to handle periodic memcg event.
129 enum mem_cgroup_events_target {
130 MEM_CGROUP_TARGET_THRESH,
131 MEM_CGROUP_TARGET_SOFTLIMIT,
132 MEM_CGROUP_TARGET_NUMAINFO,
135 #define THRESHOLDS_EVENTS_TARGET 128
136 #define SOFTLIMIT_EVENTS_TARGET 1024
137 #define NUMAINFO_EVENTS_TARGET 1024
139 struct mem_cgroup_stat_cpu {
140 long count[MEM_CGROUP_STAT_NSTATS];
141 unsigned long events[MEM_CGROUP_EVENTS_NSTATS];
142 unsigned long nr_page_events;
143 unsigned long targets[MEM_CGROUP_NTARGETS];
146 struct mem_cgroup_reclaim_iter {
147 /* css_id of the last scanned hierarchy member */
149 /* scan generation, increased every round-trip */
150 unsigned int generation;
154 * per-zone information in memory controller.
156 struct mem_cgroup_per_zone {
157 struct lruvec lruvec;
158 unsigned long lru_size[NR_LRU_LISTS];
160 struct mem_cgroup_reclaim_iter reclaim_iter[DEF_PRIORITY + 1];
162 struct rb_node tree_node; /* RB tree node */
163 unsigned long long usage_in_excess;/* Set to the value by which */
164 /* the soft limit is exceeded*/
166 struct mem_cgroup *memcg; /* Back pointer, we cannot */
167 /* use container_of */
170 struct mem_cgroup_per_node {
171 struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
174 struct mem_cgroup_lru_info {
175 struct mem_cgroup_per_node *nodeinfo[MAX_NUMNODES];
179 * Cgroups above their limits are maintained in a RB-Tree, independent of
180 * their hierarchy representation
183 struct mem_cgroup_tree_per_zone {
184 struct rb_root rb_root;
188 struct mem_cgroup_tree_per_node {
189 struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
192 struct mem_cgroup_tree {
193 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
196 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
198 struct mem_cgroup_threshold {
199 struct eventfd_ctx *eventfd;
204 struct mem_cgroup_threshold_ary {
205 /* An array index points to threshold just below or equal to usage. */
206 int current_threshold;
207 /* Size of entries[] */
209 /* Array of thresholds */
210 struct mem_cgroup_threshold entries[0];
213 struct mem_cgroup_thresholds {
214 /* Primary thresholds array */
215 struct mem_cgroup_threshold_ary *primary;
217 * Spare threshold array.
218 * This is needed to make mem_cgroup_unregister_event() "never fail".
219 * It must be able to store at least primary->size - 1 entries.
221 struct mem_cgroup_threshold_ary *spare;
225 struct mem_cgroup_eventfd_list {
226 struct list_head list;
227 struct eventfd_ctx *eventfd;
230 static void mem_cgroup_threshold(struct mem_cgroup *memcg);
231 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
234 * The memory controller data structure. The memory controller controls both
235 * page cache and RSS per cgroup. We would eventually like to provide
236 * statistics based on the statistics developed by Rik Van Riel for clock-pro,
237 * to help the administrator determine what knobs to tune.
239 * TODO: Add a water mark for the memory controller. Reclaim will begin when
240 * we hit the water mark. May be even add a low water mark, such that
241 * no reclaim occurs from a cgroup at it's low water mark, this is
242 * a feature that will be implemented much later in the future.
245 struct cgroup_subsys_state css;
247 * the counter to account for memory usage
249 struct res_counter res;
253 * the counter to account for mem+swap usage.
255 struct res_counter memsw;
258 * rcu_freeing is used only when freeing struct mem_cgroup,
259 * so put it into a union to avoid wasting more memory.
260 * It must be disjoint from the css field. It could be
261 * in a union with the res field, but res plays a much
262 * larger part in mem_cgroup life than memsw, and might
263 * be of interest, even at time of free, when debugging.
264 * So share rcu_head with the less interesting memsw.
266 struct rcu_head rcu_freeing;
268 * We also need some space for a worker in deferred freeing.
269 * By the time we call it, rcu_freeing is no longer in use.
271 struct work_struct work_freeing;
275 * the counter to account for kernel memory usage.
277 struct res_counter kmem;
279 * Per cgroup active and inactive list, similar to the
280 * per zone LRU lists.
282 struct mem_cgroup_lru_info info;
283 int last_scanned_node;
285 nodemask_t scan_nodes;
286 atomic_t numainfo_events;
287 atomic_t numainfo_updating;
290 * Should the accounting and control be hierarchical, per subtree?
293 unsigned long kmem_account_flags; /* See KMEM_ACCOUNTED_*, below */
301 /* OOM-Killer disable */
302 int oom_kill_disable;
304 /* set when res.limit == memsw.limit */
305 bool memsw_is_minimum;
307 /* protect arrays of thresholds */
308 struct mutex thresholds_lock;
310 /* thresholds for memory usage. RCU-protected */
311 struct mem_cgroup_thresholds thresholds;
313 /* thresholds for mem+swap usage. RCU-protected */
314 struct mem_cgroup_thresholds memsw_thresholds;
316 /* For oom notifier event fd */
317 struct list_head oom_notify;
320 * Should we move charges of a task when a task is moved into this
321 * mem_cgroup ? And what type of charges should we move ?
323 unsigned long move_charge_at_immigrate;
325 * set > 0 if pages under this cgroup are moving to other cgroup.
327 atomic_t moving_account;
328 /* taken only while moving_account > 0 */
329 spinlock_t move_lock;
333 struct mem_cgroup_stat_cpu __percpu *stat;
335 * used when a cpu is offlined or other synchronizations
336 * See mem_cgroup_read_stat().
338 struct mem_cgroup_stat_cpu nocpu_base;
339 spinlock_t pcp_counter_lock;
341 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_INET)
342 struct tcp_memcontrol tcp_mem;
346 /* internal only representation about the status of kmem accounting. */
348 KMEM_ACCOUNTED_ACTIVE = 0, /* accounted by this cgroup itself */
349 KMEM_ACCOUNTED_ACTIVATED, /* static key enabled. */
350 KMEM_ACCOUNTED_DEAD, /* dead memcg with pending kmem charges */
353 /* We account when limit is on, but only after call sites are patched */
354 #define KMEM_ACCOUNTED_MASK \
355 ((1 << KMEM_ACCOUNTED_ACTIVE) | (1 << KMEM_ACCOUNTED_ACTIVATED))
357 #ifdef CONFIG_MEMCG_KMEM
358 static inline void memcg_kmem_set_active(struct mem_cgroup *memcg)
360 set_bit(KMEM_ACCOUNTED_ACTIVE, &memcg->kmem_account_flags);
363 static bool memcg_kmem_is_active(struct mem_cgroup *memcg)
365 return test_bit(KMEM_ACCOUNTED_ACTIVE, &memcg->kmem_account_flags);
368 static void memcg_kmem_set_activated(struct mem_cgroup *memcg)
370 set_bit(KMEM_ACCOUNTED_ACTIVATED, &memcg->kmem_account_flags);
373 static void memcg_kmem_mark_dead(struct mem_cgroup *memcg)
375 if (test_bit(KMEM_ACCOUNTED_ACTIVE, &memcg->kmem_account_flags))
376 set_bit(KMEM_ACCOUNTED_DEAD, &memcg->kmem_account_flags);
379 static bool memcg_kmem_test_and_clear_dead(struct mem_cgroup *memcg)
381 return test_and_clear_bit(KMEM_ACCOUNTED_DEAD,
382 &memcg->kmem_account_flags);
386 /* Stuffs for move charges at task migration. */
388 * Types of charges to be moved. "move_charge_at_immitgrate" is treated as a
389 * left-shifted bitmap of these types.
392 MOVE_CHARGE_TYPE_ANON, /* private anonymous page and swap of it */
393 MOVE_CHARGE_TYPE_FILE, /* file page(including tmpfs) and swap of it */
397 /* "mc" and its members are protected by cgroup_mutex */
398 static struct move_charge_struct {
399 spinlock_t lock; /* for from, to */
400 struct mem_cgroup *from;
401 struct mem_cgroup *to;
402 unsigned long precharge;
403 unsigned long moved_charge;
404 unsigned long moved_swap;
405 struct task_struct *moving_task; /* a task moving charges */
406 wait_queue_head_t waitq; /* a waitq for other context */
408 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
409 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
412 static bool move_anon(void)
414 return test_bit(MOVE_CHARGE_TYPE_ANON,
415 &mc.to->move_charge_at_immigrate);
418 static bool move_file(void)
420 return test_bit(MOVE_CHARGE_TYPE_FILE,
421 &mc.to->move_charge_at_immigrate);
425 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
426 * limit reclaim to prevent infinite loops, if they ever occur.
428 #define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
429 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
432 MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
433 MEM_CGROUP_CHARGE_TYPE_ANON,
434 MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
435 MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
439 /* for encoding cft->private value on file */
447 #define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
448 #define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
449 #define MEMFILE_ATTR(val) ((val) & 0xffff)
450 /* Used for OOM nofiier */
451 #define OOM_CONTROL (0)
454 * Reclaim flags for mem_cgroup_hierarchical_reclaim
456 #define MEM_CGROUP_RECLAIM_NOSWAP_BIT 0x0
457 #define MEM_CGROUP_RECLAIM_NOSWAP (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
458 #define MEM_CGROUP_RECLAIM_SHRINK_BIT 0x1
459 #define MEM_CGROUP_RECLAIM_SHRINK (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
461 static void mem_cgroup_get(struct mem_cgroup *memcg);
462 static void mem_cgroup_put(struct mem_cgroup *memcg);
465 struct mem_cgroup *mem_cgroup_from_css(struct cgroup_subsys_state *s)
467 return container_of(s, struct mem_cgroup, css);
470 static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg)
472 return (memcg == root_mem_cgroup);
475 /* Writing them here to avoid exposing memcg's inner layout */
476 #if defined(CONFIG_INET) && defined(CONFIG_MEMCG_KMEM)
478 void sock_update_memcg(struct sock *sk)
480 if (mem_cgroup_sockets_enabled) {
481 struct mem_cgroup *memcg;
482 struct cg_proto *cg_proto;
484 BUG_ON(!sk->sk_prot->proto_cgroup);
486 /* Socket cloning can throw us here with sk_cgrp already
487 * filled. It won't however, necessarily happen from
488 * process context. So the test for root memcg given
489 * the current task's memcg won't help us in this case.
491 * Respecting the original socket's memcg is a better
492 * decision in this case.
495 BUG_ON(mem_cgroup_is_root(sk->sk_cgrp->memcg));
496 mem_cgroup_get(sk->sk_cgrp->memcg);
501 memcg = mem_cgroup_from_task(current);
502 cg_proto = sk->sk_prot->proto_cgroup(memcg);
503 if (!mem_cgroup_is_root(memcg) && memcg_proto_active(cg_proto)) {
504 mem_cgroup_get(memcg);
505 sk->sk_cgrp = cg_proto;
510 EXPORT_SYMBOL(sock_update_memcg);
512 void sock_release_memcg(struct sock *sk)
514 if (mem_cgroup_sockets_enabled && sk->sk_cgrp) {
515 struct mem_cgroup *memcg;
516 WARN_ON(!sk->sk_cgrp->memcg);
517 memcg = sk->sk_cgrp->memcg;
518 mem_cgroup_put(memcg);
522 struct cg_proto *tcp_proto_cgroup(struct mem_cgroup *memcg)
524 if (!memcg || mem_cgroup_is_root(memcg))
527 return &memcg->tcp_mem.cg_proto;
529 EXPORT_SYMBOL(tcp_proto_cgroup);
531 static void disarm_sock_keys(struct mem_cgroup *memcg)
533 if (!memcg_proto_activated(&memcg->tcp_mem.cg_proto))
535 static_key_slow_dec(&memcg_socket_limit_enabled);
538 static void disarm_sock_keys(struct mem_cgroup *memcg)
543 #ifdef CONFIG_MEMCG_KMEM
544 struct static_key memcg_kmem_enabled_key;
546 static void disarm_kmem_keys(struct mem_cgroup *memcg)
548 if (memcg_kmem_is_active(memcg))
549 static_key_slow_dec(&memcg_kmem_enabled_key);
552 static void disarm_kmem_keys(struct mem_cgroup *memcg)
555 #endif /* CONFIG_MEMCG_KMEM */
557 static void disarm_static_keys(struct mem_cgroup *memcg)
559 disarm_sock_keys(memcg);
560 disarm_kmem_keys(memcg);
563 static void drain_all_stock_async(struct mem_cgroup *memcg);
565 static struct mem_cgroup_per_zone *
566 mem_cgroup_zoneinfo(struct mem_cgroup *memcg, int nid, int zid)
568 return &memcg->info.nodeinfo[nid]->zoneinfo[zid];
571 struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *memcg)
576 static struct mem_cgroup_per_zone *
577 page_cgroup_zoneinfo(struct mem_cgroup *memcg, struct page *page)
579 int nid = page_to_nid(page);
580 int zid = page_zonenum(page);
582 return mem_cgroup_zoneinfo(memcg, nid, zid);
585 static struct mem_cgroup_tree_per_zone *
586 soft_limit_tree_node_zone(int nid, int zid)
588 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
591 static struct mem_cgroup_tree_per_zone *
592 soft_limit_tree_from_page(struct page *page)
594 int nid = page_to_nid(page);
595 int zid = page_zonenum(page);
597 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
601 __mem_cgroup_insert_exceeded(struct mem_cgroup *memcg,
602 struct mem_cgroup_per_zone *mz,
603 struct mem_cgroup_tree_per_zone *mctz,
604 unsigned long long new_usage_in_excess)
606 struct rb_node **p = &mctz->rb_root.rb_node;
607 struct rb_node *parent = NULL;
608 struct mem_cgroup_per_zone *mz_node;
613 mz->usage_in_excess = new_usage_in_excess;
614 if (!mz->usage_in_excess)
618 mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
620 if (mz->usage_in_excess < mz_node->usage_in_excess)
623 * We can't avoid mem cgroups that are over their soft
624 * limit by the same amount
626 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
629 rb_link_node(&mz->tree_node, parent, p);
630 rb_insert_color(&mz->tree_node, &mctz->rb_root);
635 __mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
636 struct mem_cgroup_per_zone *mz,
637 struct mem_cgroup_tree_per_zone *mctz)
641 rb_erase(&mz->tree_node, &mctz->rb_root);
646 mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
647 struct mem_cgroup_per_zone *mz,
648 struct mem_cgroup_tree_per_zone *mctz)
650 spin_lock(&mctz->lock);
651 __mem_cgroup_remove_exceeded(memcg, mz, mctz);
652 spin_unlock(&mctz->lock);
656 static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
658 unsigned long long excess;
659 struct mem_cgroup_per_zone *mz;
660 struct mem_cgroup_tree_per_zone *mctz;
661 int nid = page_to_nid(page);
662 int zid = page_zonenum(page);
663 mctz = soft_limit_tree_from_page(page);
666 * Necessary to update all ancestors when hierarchy is used.
667 * because their event counter is not touched.
669 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
670 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
671 excess = res_counter_soft_limit_excess(&memcg->res);
673 * We have to update the tree if mz is on RB-tree or
674 * mem is over its softlimit.
676 if (excess || mz->on_tree) {
677 spin_lock(&mctz->lock);
678 /* if on-tree, remove it */
680 __mem_cgroup_remove_exceeded(memcg, mz, mctz);
682 * Insert again. mz->usage_in_excess will be updated.
683 * If excess is 0, no tree ops.
685 __mem_cgroup_insert_exceeded(memcg, mz, mctz, excess);
686 spin_unlock(&mctz->lock);
691 static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
694 struct mem_cgroup_per_zone *mz;
695 struct mem_cgroup_tree_per_zone *mctz;
697 for_each_node(node) {
698 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
699 mz = mem_cgroup_zoneinfo(memcg, node, zone);
700 mctz = soft_limit_tree_node_zone(node, zone);
701 mem_cgroup_remove_exceeded(memcg, mz, mctz);
706 static struct mem_cgroup_per_zone *
707 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
709 struct rb_node *rightmost = NULL;
710 struct mem_cgroup_per_zone *mz;
714 rightmost = rb_last(&mctz->rb_root);
716 goto done; /* Nothing to reclaim from */
718 mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
720 * Remove the node now but someone else can add it back,
721 * we will to add it back at the end of reclaim to its correct
722 * position in the tree.
724 __mem_cgroup_remove_exceeded(mz->memcg, mz, mctz);
725 if (!res_counter_soft_limit_excess(&mz->memcg->res) ||
726 !css_tryget(&mz->memcg->css))
732 static struct mem_cgroup_per_zone *
733 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
735 struct mem_cgroup_per_zone *mz;
737 spin_lock(&mctz->lock);
738 mz = __mem_cgroup_largest_soft_limit_node(mctz);
739 spin_unlock(&mctz->lock);
744 * Implementation Note: reading percpu statistics for memcg.
746 * Both of vmstat[] and percpu_counter has threshold and do periodic
747 * synchronization to implement "quick" read. There are trade-off between
748 * reading cost and precision of value. Then, we may have a chance to implement
749 * a periodic synchronizion of counter in memcg's counter.
751 * But this _read() function is used for user interface now. The user accounts
752 * memory usage by memory cgroup and he _always_ requires exact value because
753 * he accounts memory. Even if we provide quick-and-fuzzy read, we always
754 * have to visit all online cpus and make sum. So, for now, unnecessary
755 * synchronization is not implemented. (just implemented for cpu hotplug)
757 * If there are kernel internal actions which can make use of some not-exact
758 * value, and reading all cpu value can be performance bottleneck in some
759 * common workload, threashold and synchonization as vmstat[] should be
762 static long mem_cgroup_read_stat(struct mem_cgroup *memcg,
763 enum mem_cgroup_stat_index idx)
769 for_each_online_cpu(cpu)
770 val += per_cpu(memcg->stat->count[idx], cpu);
771 #ifdef CONFIG_HOTPLUG_CPU
772 spin_lock(&memcg->pcp_counter_lock);
773 val += memcg->nocpu_base.count[idx];
774 spin_unlock(&memcg->pcp_counter_lock);
780 static void mem_cgroup_swap_statistics(struct mem_cgroup *memcg,
783 int val = (charge) ? 1 : -1;
784 this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_SWAP], val);
787 static unsigned long mem_cgroup_read_events(struct mem_cgroup *memcg,
788 enum mem_cgroup_events_index idx)
790 unsigned long val = 0;
793 for_each_online_cpu(cpu)
794 val += per_cpu(memcg->stat->events[idx], cpu);
795 #ifdef CONFIG_HOTPLUG_CPU
796 spin_lock(&memcg->pcp_counter_lock);
797 val += memcg->nocpu_base.events[idx];
798 spin_unlock(&memcg->pcp_counter_lock);
803 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
804 bool anon, int nr_pages)
809 * Here, RSS means 'mapped anon' and anon's SwapCache. Shmem/tmpfs is
810 * counted as CACHE even if it's on ANON LRU.
813 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS],
816 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_CACHE],
819 /* pagein of a big page is an event. So, ignore page size */
821 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGIN]);
823 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGOUT]);
824 nr_pages = -nr_pages; /* for event */
827 __this_cpu_add(memcg->stat->nr_page_events, nr_pages);
833 mem_cgroup_get_lru_size(struct lruvec *lruvec, enum lru_list lru)
835 struct mem_cgroup_per_zone *mz;
837 mz = container_of(lruvec, struct mem_cgroup_per_zone, lruvec);
838 return mz->lru_size[lru];
842 mem_cgroup_zone_nr_lru_pages(struct mem_cgroup *memcg, int nid, int zid,
843 unsigned int lru_mask)
845 struct mem_cgroup_per_zone *mz;
847 unsigned long ret = 0;
849 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
852 if (BIT(lru) & lru_mask)
853 ret += mz->lru_size[lru];
859 mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
860 int nid, unsigned int lru_mask)
865 for (zid = 0; zid < MAX_NR_ZONES; zid++)
866 total += mem_cgroup_zone_nr_lru_pages(memcg,
872 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
873 unsigned int lru_mask)
878 for_each_node_state(nid, N_MEMORY)
879 total += mem_cgroup_node_nr_lru_pages(memcg, nid, lru_mask);
883 static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
884 enum mem_cgroup_events_target target)
886 unsigned long val, next;
888 val = __this_cpu_read(memcg->stat->nr_page_events);
889 next = __this_cpu_read(memcg->stat->targets[target]);
890 /* from time_after() in jiffies.h */
891 if ((long)next - (long)val < 0) {
893 case MEM_CGROUP_TARGET_THRESH:
894 next = val + THRESHOLDS_EVENTS_TARGET;
896 case MEM_CGROUP_TARGET_SOFTLIMIT:
897 next = val + SOFTLIMIT_EVENTS_TARGET;
899 case MEM_CGROUP_TARGET_NUMAINFO:
900 next = val + NUMAINFO_EVENTS_TARGET;
905 __this_cpu_write(memcg->stat->targets[target], next);
912 * Check events in order.
915 static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
918 /* threshold event is triggered in finer grain than soft limit */
919 if (unlikely(mem_cgroup_event_ratelimit(memcg,
920 MEM_CGROUP_TARGET_THRESH))) {
922 bool do_numainfo __maybe_unused;
924 do_softlimit = mem_cgroup_event_ratelimit(memcg,
925 MEM_CGROUP_TARGET_SOFTLIMIT);
927 do_numainfo = mem_cgroup_event_ratelimit(memcg,
928 MEM_CGROUP_TARGET_NUMAINFO);
932 mem_cgroup_threshold(memcg);
933 if (unlikely(do_softlimit))
934 mem_cgroup_update_tree(memcg, page);
936 if (unlikely(do_numainfo))
937 atomic_inc(&memcg->numainfo_events);
943 struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
945 return mem_cgroup_from_css(
946 cgroup_subsys_state(cont, mem_cgroup_subsys_id));
949 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
952 * mm_update_next_owner() may clear mm->owner to NULL
953 * if it races with swapoff, page migration, etc.
954 * So this can be called with p == NULL.
959 return mem_cgroup_from_css(task_subsys_state(p, mem_cgroup_subsys_id));
962 struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
964 struct mem_cgroup *memcg = NULL;
969 * Because we have no locks, mm->owner's may be being moved to other
970 * cgroup. We use css_tryget() here even if this looks
971 * pessimistic (rather than adding locks here).
975 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
976 if (unlikely(!memcg))
978 } while (!css_tryget(&memcg->css));
984 * mem_cgroup_iter - iterate over memory cgroup hierarchy
985 * @root: hierarchy root
986 * @prev: previously returned memcg, NULL on first invocation
987 * @reclaim: cookie for shared reclaim walks, NULL for full walks
989 * Returns references to children of the hierarchy below @root, or
990 * @root itself, or %NULL after a full round-trip.
992 * Caller must pass the return value in @prev on subsequent
993 * invocations for reference counting, or use mem_cgroup_iter_break()
994 * to cancel a hierarchy walk before the round-trip is complete.
996 * Reclaimers can specify a zone and a priority level in @reclaim to
997 * divide up the memcgs in the hierarchy among all concurrent
998 * reclaimers operating on the same zone and priority.
1000 struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
1001 struct mem_cgroup *prev,
1002 struct mem_cgroup_reclaim_cookie *reclaim)
1004 struct mem_cgroup *memcg = NULL;
1007 if (mem_cgroup_disabled())
1011 root = root_mem_cgroup;
1013 if (prev && !reclaim)
1014 id = css_id(&prev->css);
1016 if (prev && prev != root)
1017 css_put(&prev->css);
1019 if (!root->use_hierarchy && root != root_mem_cgroup) {
1026 struct mem_cgroup_reclaim_iter *uninitialized_var(iter);
1027 struct cgroup_subsys_state *css;
1030 int nid = zone_to_nid(reclaim->zone);
1031 int zid = zone_idx(reclaim->zone);
1032 struct mem_cgroup_per_zone *mz;
1034 mz = mem_cgroup_zoneinfo(root, nid, zid);
1035 iter = &mz->reclaim_iter[reclaim->priority];
1036 if (prev && reclaim->generation != iter->generation)
1038 id = iter->position;
1042 css = css_get_next(&mem_cgroup_subsys, id + 1, &root->css, &id);
1044 if (css == &root->css || css_tryget(css))
1045 memcg = mem_cgroup_from_css(css);
1051 iter->position = id;
1054 else if (!prev && memcg)
1055 reclaim->generation = iter->generation;
1065 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1066 * @root: hierarchy root
1067 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1069 void mem_cgroup_iter_break(struct mem_cgroup *root,
1070 struct mem_cgroup *prev)
1073 root = root_mem_cgroup;
1074 if (prev && prev != root)
1075 css_put(&prev->css);
1079 * Iteration constructs for visiting all cgroups (under a tree). If
1080 * loops are exited prematurely (break), mem_cgroup_iter_break() must
1081 * be used for reference counting.
1083 #define for_each_mem_cgroup_tree(iter, root) \
1084 for (iter = mem_cgroup_iter(root, NULL, NULL); \
1086 iter = mem_cgroup_iter(root, iter, NULL))
1088 #define for_each_mem_cgroup(iter) \
1089 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
1091 iter = mem_cgroup_iter(NULL, iter, NULL))
1093 void __mem_cgroup_count_vm_event(struct mm_struct *mm, enum vm_event_item idx)
1095 struct mem_cgroup *memcg;
1098 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
1099 if (unlikely(!memcg))
1104 this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGFAULT]);
1107 this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGMAJFAULT]);
1115 EXPORT_SYMBOL(__mem_cgroup_count_vm_event);
1118 * mem_cgroup_zone_lruvec - get the lru list vector for a zone and memcg
1119 * @zone: zone of the wanted lruvec
1120 * @memcg: memcg of the wanted lruvec
1122 * Returns the lru list vector holding pages for the given @zone and
1123 * @mem. This can be the global zone lruvec, if the memory controller
1126 struct lruvec *mem_cgroup_zone_lruvec(struct zone *zone,
1127 struct mem_cgroup *memcg)
1129 struct mem_cgroup_per_zone *mz;
1130 struct lruvec *lruvec;
1132 if (mem_cgroup_disabled()) {
1133 lruvec = &zone->lruvec;
1137 mz = mem_cgroup_zoneinfo(memcg, zone_to_nid(zone), zone_idx(zone));
1138 lruvec = &mz->lruvec;
1141 * Since a node can be onlined after the mem_cgroup was created,
1142 * we have to be prepared to initialize lruvec->zone here;
1143 * and if offlined then reonlined, we need to reinitialize it.
1145 if (unlikely(lruvec->zone != zone))
1146 lruvec->zone = zone;
1151 * Following LRU functions are allowed to be used without PCG_LOCK.
1152 * Operations are called by routine of global LRU independently from memcg.
1153 * What we have to take care of here is validness of pc->mem_cgroup.
1155 * Changes to pc->mem_cgroup happens when
1158 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
1159 * It is added to LRU before charge.
1160 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
1161 * When moving account, the page is not on LRU. It's isolated.
1165 * mem_cgroup_page_lruvec - return lruvec for adding an lru page
1167 * @zone: zone of the page
1169 struct lruvec *mem_cgroup_page_lruvec(struct page *page, struct zone *zone)
1171 struct mem_cgroup_per_zone *mz;
1172 struct mem_cgroup *memcg;
1173 struct page_cgroup *pc;
1174 struct lruvec *lruvec;
1176 if (mem_cgroup_disabled()) {
1177 lruvec = &zone->lruvec;
1181 pc = lookup_page_cgroup(page);
1182 memcg = pc->mem_cgroup;
1185 * Surreptitiously switch any uncharged offlist page to root:
1186 * an uncharged page off lru does nothing to secure
1187 * its former mem_cgroup from sudden removal.
1189 * Our caller holds lru_lock, and PageCgroupUsed is updated
1190 * under page_cgroup lock: between them, they make all uses
1191 * of pc->mem_cgroup safe.
1193 if (!PageLRU(page) && !PageCgroupUsed(pc) && memcg != root_mem_cgroup)
1194 pc->mem_cgroup = memcg = root_mem_cgroup;
1196 mz = page_cgroup_zoneinfo(memcg, page);
1197 lruvec = &mz->lruvec;
1200 * Since a node can be onlined after the mem_cgroup was created,
1201 * we have to be prepared to initialize lruvec->zone here;
1202 * and if offlined then reonlined, we need to reinitialize it.
1204 if (unlikely(lruvec->zone != zone))
1205 lruvec->zone = zone;
1210 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1211 * @lruvec: mem_cgroup per zone lru vector
1212 * @lru: index of lru list the page is sitting on
1213 * @nr_pages: positive when adding or negative when removing
1215 * This function must be called when a page is added to or removed from an
1218 void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
1221 struct mem_cgroup_per_zone *mz;
1222 unsigned long *lru_size;
1224 if (mem_cgroup_disabled())
1227 mz = container_of(lruvec, struct mem_cgroup_per_zone, lruvec);
1228 lru_size = mz->lru_size + lru;
1229 *lru_size += nr_pages;
1230 VM_BUG_ON((long)(*lru_size) < 0);
1234 * Checks whether given mem is same or in the root_mem_cgroup's
1237 bool __mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
1238 struct mem_cgroup *memcg)
1240 if (root_memcg == memcg)
1242 if (!root_memcg->use_hierarchy || !memcg)
1244 return css_is_ancestor(&memcg->css, &root_memcg->css);
1247 static bool mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
1248 struct mem_cgroup *memcg)
1253 ret = __mem_cgroup_same_or_subtree(root_memcg, memcg);
1258 int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *memcg)
1261 struct mem_cgroup *curr = NULL;
1262 struct task_struct *p;
1264 p = find_lock_task_mm(task);
1266 curr = try_get_mem_cgroup_from_mm(p->mm);
1270 * All threads may have already detached their mm's, but the oom
1271 * killer still needs to detect if they have already been oom
1272 * killed to prevent needlessly killing additional tasks.
1275 curr = mem_cgroup_from_task(task);
1277 css_get(&curr->css);
1283 * We should check use_hierarchy of "memcg" not "curr". Because checking
1284 * use_hierarchy of "curr" here make this function true if hierarchy is
1285 * enabled in "curr" and "curr" is a child of "memcg" in *cgroup*
1286 * hierarchy(even if use_hierarchy is disabled in "memcg").
1288 ret = mem_cgroup_same_or_subtree(memcg, curr);
1289 css_put(&curr->css);
1293 int mem_cgroup_inactive_anon_is_low(struct lruvec *lruvec)
1295 unsigned long inactive_ratio;
1296 unsigned long inactive;
1297 unsigned long active;
1300 inactive = mem_cgroup_get_lru_size(lruvec, LRU_INACTIVE_ANON);
1301 active = mem_cgroup_get_lru_size(lruvec, LRU_ACTIVE_ANON);
1303 gb = (inactive + active) >> (30 - PAGE_SHIFT);
1305 inactive_ratio = int_sqrt(10 * gb);
1309 return inactive * inactive_ratio < active;
1312 int mem_cgroup_inactive_file_is_low(struct lruvec *lruvec)
1314 unsigned long active;
1315 unsigned long inactive;
1317 inactive = mem_cgroup_get_lru_size(lruvec, LRU_INACTIVE_FILE);
1318 active = mem_cgroup_get_lru_size(lruvec, LRU_ACTIVE_FILE);
1320 return (active > inactive);
1323 #define mem_cgroup_from_res_counter(counter, member) \
1324 container_of(counter, struct mem_cgroup, member)
1327 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1328 * @memcg: the memory cgroup
1330 * Returns the maximum amount of memory @mem can be charged with, in
1333 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1335 unsigned long long margin;
1337 margin = res_counter_margin(&memcg->res);
1338 if (do_swap_account)
1339 margin = min(margin, res_counter_margin(&memcg->memsw));
1340 return margin >> PAGE_SHIFT;
1343 int mem_cgroup_swappiness(struct mem_cgroup *memcg)
1345 struct cgroup *cgrp = memcg->css.cgroup;
1348 if (cgrp->parent == NULL)
1349 return vm_swappiness;
1351 return memcg->swappiness;
1355 * memcg->moving_account is used for checking possibility that some thread is
1356 * calling move_account(). When a thread on CPU-A starts moving pages under
1357 * a memcg, other threads should check memcg->moving_account under
1358 * rcu_read_lock(), like this:
1362 * memcg->moving_account+1 if (memcg->mocing_account)
1364 * synchronize_rcu() update something.
1369 /* for quick checking without looking up memcg */
1370 atomic_t memcg_moving __read_mostly;
1372 static void mem_cgroup_start_move(struct mem_cgroup *memcg)
1374 atomic_inc(&memcg_moving);
1375 atomic_inc(&memcg->moving_account);
1379 static void mem_cgroup_end_move(struct mem_cgroup *memcg)
1382 * Now, mem_cgroup_clear_mc() may call this function with NULL.
1383 * We check NULL in callee rather than caller.
1386 atomic_dec(&memcg_moving);
1387 atomic_dec(&memcg->moving_account);
1392 * 2 routines for checking "mem" is under move_account() or not.
1394 * mem_cgroup_stolen() - checking whether a cgroup is mc.from or not. This
1395 * is used for avoiding races in accounting. If true,
1396 * pc->mem_cgroup may be overwritten.
1398 * mem_cgroup_under_move() - checking a cgroup is mc.from or mc.to or
1399 * under hierarchy of moving cgroups. This is for
1400 * waiting at hith-memory prressure caused by "move".
1403 static bool mem_cgroup_stolen(struct mem_cgroup *memcg)
1405 VM_BUG_ON(!rcu_read_lock_held());
1406 return atomic_read(&memcg->moving_account) > 0;
1409 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1411 struct mem_cgroup *from;
1412 struct mem_cgroup *to;
1415 * Unlike task_move routines, we access mc.to, mc.from not under
1416 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1418 spin_lock(&mc.lock);
1424 ret = mem_cgroup_same_or_subtree(memcg, from)
1425 || mem_cgroup_same_or_subtree(memcg, to);
1427 spin_unlock(&mc.lock);
1431 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1433 if (mc.moving_task && current != mc.moving_task) {
1434 if (mem_cgroup_under_move(memcg)) {
1436 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1437 /* moving charge context might have finished. */
1440 finish_wait(&mc.waitq, &wait);
1448 * Take this lock when
1449 * - a code tries to modify page's memcg while it's USED.
1450 * - a code tries to modify page state accounting in a memcg.
1451 * see mem_cgroup_stolen(), too.
1453 static void move_lock_mem_cgroup(struct mem_cgroup *memcg,
1454 unsigned long *flags)
1456 spin_lock_irqsave(&memcg->move_lock, *flags);
1459 static void move_unlock_mem_cgroup(struct mem_cgroup *memcg,
1460 unsigned long *flags)
1462 spin_unlock_irqrestore(&memcg->move_lock, *flags);
1466 * mem_cgroup_print_oom_info: Called from OOM with tasklist_lock held in read mode.
1467 * @memcg: The memory cgroup that went over limit
1468 * @p: Task that is going to be killed
1470 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1473 void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1475 struct cgroup *task_cgrp;
1476 struct cgroup *mem_cgrp;
1478 * Need a buffer in BSS, can't rely on allocations. The code relies
1479 * on the assumption that OOM is serialized for memory controller.
1480 * If this assumption is broken, revisit this code.
1482 static char memcg_name[PATH_MAX];
1490 mem_cgrp = memcg->css.cgroup;
1491 task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
1493 ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
1496 * Unfortunately, we are unable to convert to a useful name
1497 * But we'll still print out the usage information
1504 printk(KERN_INFO "Task in %s killed", memcg_name);
1507 ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
1515 * Continues from above, so we don't need an KERN_ level
1517 printk(KERN_CONT " as a result of limit of %s\n", memcg_name);
1520 printk(KERN_INFO "memory: usage %llukB, limit %llukB, failcnt %llu\n",
1521 res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
1522 res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
1523 res_counter_read_u64(&memcg->res, RES_FAILCNT));
1524 printk(KERN_INFO "memory+swap: usage %llukB, limit %llukB, "
1526 res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
1527 res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
1528 res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
1529 printk(KERN_INFO "kmem: usage %llukB, limit %llukB, failcnt %llu\n",
1530 res_counter_read_u64(&memcg->kmem, RES_USAGE) >> 10,
1531 res_counter_read_u64(&memcg->kmem, RES_LIMIT) >> 10,
1532 res_counter_read_u64(&memcg->kmem, RES_FAILCNT));
1536 * This function returns the number of memcg under hierarchy tree. Returns
1537 * 1(self count) if no children.
1539 static int mem_cgroup_count_children(struct mem_cgroup *memcg)
1542 struct mem_cgroup *iter;
1544 for_each_mem_cgroup_tree(iter, memcg)
1550 * Return the memory (and swap, if configured) limit for a memcg.
1552 static u64 mem_cgroup_get_limit(struct mem_cgroup *memcg)
1556 limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
1559 * Do not consider swap space if we cannot swap due to swappiness
1561 if (mem_cgroup_swappiness(memcg)) {
1564 limit += total_swap_pages << PAGE_SHIFT;
1565 memsw = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
1568 * If memsw is finite and limits the amount of swap space
1569 * available to this memcg, return that limit.
1571 limit = min(limit, memsw);
1577 static void mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
1580 struct mem_cgroup *iter;
1581 unsigned long chosen_points = 0;
1582 unsigned long totalpages;
1583 unsigned int points = 0;
1584 struct task_struct *chosen = NULL;
1587 * If current has a pending SIGKILL, then automatically select it. The
1588 * goal is to allow it to allocate so that it may quickly exit and free
1591 if (fatal_signal_pending(current)) {
1592 set_thread_flag(TIF_MEMDIE);
1596 check_panic_on_oom(CONSTRAINT_MEMCG, gfp_mask, order, NULL);
1597 totalpages = mem_cgroup_get_limit(memcg) >> PAGE_SHIFT ? : 1;
1598 for_each_mem_cgroup_tree(iter, memcg) {
1599 struct cgroup *cgroup = iter->css.cgroup;
1600 struct cgroup_iter it;
1601 struct task_struct *task;
1603 cgroup_iter_start(cgroup, &it);
1604 while ((task = cgroup_iter_next(cgroup, &it))) {
1605 switch (oom_scan_process_thread(task, totalpages, NULL,
1607 case OOM_SCAN_SELECT:
1609 put_task_struct(chosen);
1611 chosen_points = ULONG_MAX;
1612 get_task_struct(chosen);
1614 case OOM_SCAN_CONTINUE:
1616 case OOM_SCAN_ABORT:
1617 cgroup_iter_end(cgroup, &it);
1618 mem_cgroup_iter_break(memcg, iter);
1620 put_task_struct(chosen);
1625 points = oom_badness(task, memcg, NULL, totalpages);
1626 if (points > chosen_points) {
1628 put_task_struct(chosen);
1630 chosen_points = points;
1631 get_task_struct(chosen);
1634 cgroup_iter_end(cgroup, &it);
1639 points = chosen_points * 1000 / totalpages;
1640 oom_kill_process(chosen, gfp_mask, order, points, totalpages, memcg,
1641 NULL, "Memory cgroup out of memory");
1644 static unsigned long mem_cgroup_reclaim(struct mem_cgroup *memcg,
1646 unsigned long flags)
1648 unsigned long total = 0;
1649 bool noswap = false;
1652 if (flags & MEM_CGROUP_RECLAIM_NOSWAP)
1654 if (!(flags & MEM_CGROUP_RECLAIM_SHRINK) && memcg->memsw_is_minimum)
1657 for (loop = 0; loop < MEM_CGROUP_MAX_RECLAIM_LOOPS; loop++) {
1659 drain_all_stock_async(memcg);
1660 total += try_to_free_mem_cgroup_pages(memcg, gfp_mask, noswap);
1662 * Allow limit shrinkers, which are triggered directly
1663 * by userspace, to catch signals and stop reclaim
1664 * after minimal progress, regardless of the margin.
1666 if (total && (flags & MEM_CGROUP_RECLAIM_SHRINK))
1668 if (mem_cgroup_margin(memcg))
1671 * If nothing was reclaimed after two attempts, there
1672 * may be no reclaimable pages in this hierarchy.
1681 * test_mem_cgroup_node_reclaimable
1682 * @memcg: the target memcg
1683 * @nid: the node ID to be checked.
1684 * @noswap : specify true here if the user wants flle only information.
1686 * This function returns whether the specified memcg contains any
1687 * reclaimable pages on a node. Returns true if there are any reclaimable
1688 * pages in the node.
1690 static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *memcg,
1691 int nid, bool noswap)
1693 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_FILE))
1695 if (noswap || !total_swap_pages)
1697 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_ANON))
1702 #if MAX_NUMNODES > 1
1705 * Always updating the nodemask is not very good - even if we have an empty
1706 * list or the wrong list here, we can start from some node and traverse all
1707 * nodes based on the zonelist. So update the list loosely once per 10 secs.
1710 static void mem_cgroup_may_update_nodemask(struct mem_cgroup *memcg)
1714 * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
1715 * pagein/pageout changes since the last update.
1717 if (!atomic_read(&memcg->numainfo_events))
1719 if (atomic_inc_return(&memcg->numainfo_updating) > 1)
1722 /* make a nodemask where this memcg uses memory from */
1723 memcg->scan_nodes = node_states[N_MEMORY];
1725 for_each_node_mask(nid, node_states[N_MEMORY]) {
1727 if (!test_mem_cgroup_node_reclaimable(memcg, nid, false))
1728 node_clear(nid, memcg->scan_nodes);
1731 atomic_set(&memcg->numainfo_events, 0);
1732 atomic_set(&memcg->numainfo_updating, 0);
1736 * Selecting a node where we start reclaim from. Because what we need is just
1737 * reducing usage counter, start from anywhere is O,K. Considering
1738 * memory reclaim from current node, there are pros. and cons.
1740 * Freeing memory from current node means freeing memory from a node which
1741 * we'll use or we've used. So, it may make LRU bad. And if several threads
1742 * hit limits, it will see a contention on a node. But freeing from remote
1743 * node means more costs for memory reclaim because of memory latency.
1745 * Now, we use round-robin. Better algorithm is welcomed.
1747 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1751 mem_cgroup_may_update_nodemask(memcg);
1752 node = memcg->last_scanned_node;
1754 node = next_node(node, memcg->scan_nodes);
1755 if (node == MAX_NUMNODES)
1756 node = first_node(memcg->scan_nodes);
1758 * We call this when we hit limit, not when pages are added to LRU.
1759 * No LRU may hold pages because all pages are UNEVICTABLE or
1760 * memcg is too small and all pages are not on LRU. In that case,
1761 * we use curret node.
1763 if (unlikely(node == MAX_NUMNODES))
1764 node = numa_node_id();
1766 memcg->last_scanned_node = node;
1771 * Check all nodes whether it contains reclaimable pages or not.
1772 * For quick scan, we make use of scan_nodes. This will allow us to skip
1773 * unused nodes. But scan_nodes is lazily updated and may not cotain
1774 * enough new information. We need to do double check.
1776 static bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
1781 * quick check...making use of scan_node.
1782 * We can skip unused nodes.
1784 if (!nodes_empty(memcg->scan_nodes)) {
1785 for (nid = first_node(memcg->scan_nodes);
1787 nid = next_node(nid, memcg->scan_nodes)) {
1789 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
1794 * Check rest of nodes.
1796 for_each_node_state(nid, N_MEMORY) {
1797 if (node_isset(nid, memcg->scan_nodes))
1799 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
1806 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1811 static bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
1813 return test_mem_cgroup_node_reclaimable(memcg, 0, noswap);
1817 static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
1820 unsigned long *total_scanned)
1822 struct mem_cgroup *victim = NULL;
1825 unsigned long excess;
1826 unsigned long nr_scanned;
1827 struct mem_cgroup_reclaim_cookie reclaim = {
1832 excess = res_counter_soft_limit_excess(&root_memcg->res) >> PAGE_SHIFT;
1835 victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
1840 * If we have not been able to reclaim
1841 * anything, it might because there are
1842 * no reclaimable pages under this hierarchy
1847 * We want to do more targeted reclaim.
1848 * excess >> 2 is not to excessive so as to
1849 * reclaim too much, nor too less that we keep
1850 * coming back to reclaim from this cgroup
1852 if (total >= (excess >> 2) ||
1853 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
1858 if (!mem_cgroup_reclaimable(victim, false))
1860 total += mem_cgroup_shrink_node_zone(victim, gfp_mask, false,
1862 *total_scanned += nr_scanned;
1863 if (!res_counter_soft_limit_excess(&root_memcg->res))
1866 mem_cgroup_iter_break(root_memcg, victim);
1871 * Check OOM-Killer is already running under our hierarchy.
1872 * If someone is running, return false.
1873 * Has to be called with memcg_oom_lock
1875 static bool mem_cgroup_oom_lock(struct mem_cgroup *memcg)
1877 struct mem_cgroup *iter, *failed = NULL;
1879 for_each_mem_cgroup_tree(iter, memcg) {
1880 if (iter->oom_lock) {
1882 * this subtree of our hierarchy is already locked
1883 * so we cannot give a lock.
1886 mem_cgroup_iter_break(memcg, iter);
1889 iter->oom_lock = true;
1896 * OK, we failed to lock the whole subtree so we have to clean up
1897 * what we set up to the failing subtree
1899 for_each_mem_cgroup_tree(iter, memcg) {
1900 if (iter == failed) {
1901 mem_cgroup_iter_break(memcg, iter);
1904 iter->oom_lock = false;
1910 * Has to be called with memcg_oom_lock
1912 static int mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
1914 struct mem_cgroup *iter;
1916 for_each_mem_cgroup_tree(iter, memcg)
1917 iter->oom_lock = false;
1921 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
1923 struct mem_cgroup *iter;
1925 for_each_mem_cgroup_tree(iter, memcg)
1926 atomic_inc(&iter->under_oom);
1929 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
1931 struct mem_cgroup *iter;
1934 * When a new child is created while the hierarchy is under oom,
1935 * mem_cgroup_oom_lock() may not be called. We have to use
1936 * atomic_add_unless() here.
1938 for_each_mem_cgroup_tree(iter, memcg)
1939 atomic_add_unless(&iter->under_oom, -1, 0);
1942 static DEFINE_SPINLOCK(memcg_oom_lock);
1943 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1945 struct oom_wait_info {
1946 struct mem_cgroup *memcg;
1950 static int memcg_oom_wake_function(wait_queue_t *wait,
1951 unsigned mode, int sync, void *arg)
1953 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
1954 struct mem_cgroup *oom_wait_memcg;
1955 struct oom_wait_info *oom_wait_info;
1957 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1958 oom_wait_memcg = oom_wait_info->memcg;
1961 * Both of oom_wait_info->memcg and wake_memcg are stable under us.
1962 * Then we can use css_is_ancestor without taking care of RCU.
1964 if (!mem_cgroup_same_or_subtree(oom_wait_memcg, wake_memcg)
1965 && !mem_cgroup_same_or_subtree(wake_memcg, oom_wait_memcg))
1967 return autoremove_wake_function(wait, mode, sync, arg);
1970 static void memcg_wakeup_oom(struct mem_cgroup *memcg)
1972 /* for filtering, pass "memcg" as argument. */
1973 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
1976 static void memcg_oom_recover(struct mem_cgroup *memcg)
1978 if (memcg && atomic_read(&memcg->under_oom))
1979 memcg_wakeup_oom(memcg);
1983 * try to call OOM killer. returns false if we should exit memory-reclaim loop.
1985 static bool mem_cgroup_handle_oom(struct mem_cgroup *memcg, gfp_t mask,
1988 struct oom_wait_info owait;
1989 bool locked, need_to_kill;
1991 owait.memcg = memcg;
1992 owait.wait.flags = 0;
1993 owait.wait.func = memcg_oom_wake_function;
1994 owait.wait.private = current;
1995 INIT_LIST_HEAD(&owait.wait.task_list);
1996 need_to_kill = true;
1997 mem_cgroup_mark_under_oom(memcg);
1999 /* At first, try to OOM lock hierarchy under memcg.*/
2000 spin_lock(&memcg_oom_lock);
2001 locked = mem_cgroup_oom_lock(memcg);
2003 * Even if signal_pending(), we can't quit charge() loop without
2004 * accounting. So, UNINTERRUPTIBLE is appropriate. But SIGKILL
2005 * under OOM is always welcomed, use TASK_KILLABLE here.
2007 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
2008 if (!locked || memcg->oom_kill_disable)
2009 need_to_kill = false;
2011 mem_cgroup_oom_notify(memcg);
2012 spin_unlock(&memcg_oom_lock);
2015 finish_wait(&memcg_oom_waitq, &owait.wait);
2016 mem_cgroup_out_of_memory(memcg, mask, order);
2019 finish_wait(&memcg_oom_waitq, &owait.wait);
2021 spin_lock(&memcg_oom_lock);
2023 mem_cgroup_oom_unlock(memcg);
2024 memcg_wakeup_oom(memcg);
2025 spin_unlock(&memcg_oom_lock);
2027 mem_cgroup_unmark_under_oom(memcg);
2029 if (test_thread_flag(TIF_MEMDIE) || fatal_signal_pending(current))
2031 /* Give chance to dying process */
2032 schedule_timeout_uninterruptible(1);
2037 * Currently used to update mapped file statistics, but the routine can be
2038 * generalized to update other statistics as well.
2040 * Notes: Race condition
2042 * We usually use page_cgroup_lock() for accessing page_cgroup member but
2043 * it tends to be costly. But considering some conditions, we doesn't need
2044 * to do so _always_.
2046 * Considering "charge", lock_page_cgroup() is not required because all
2047 * file-stat operations happen after a page is attached to radix-tree. There
2048 * are no race with "charge".
2050 * Considering "uncharge", we know that memcg doesn't clear pc->mem_cgroup
2051 * at "uncharge" intentionally. So, we always see valid pc->mem_cgroup even
2052 * if there are race with "uncharge". Statistics itself is properly handled
2055 * Considering "move", this is an only case we see a race. To make the race
2056 * small, we check mm->moving_account and detect there are possibility of race
2057 * If there is, we take a lock.
2060 void __mem_cgroup_begin_update_page_stat(struct page *page,
2061 bool *locked, unsigned long *flags)
2063 struct mem_cgroup *memcg;
2064 struct page_cgroup *pc;
2066 pc = lookup_page_cgroup(page);
2068 memcg = pc->mem_cgroup;
2069 if (unlikely(!memcg || !PageCgroupUsed(pc)))
2072 * If this memory cgroup is not under account moving, we don't
2073 * need to take move_lock_mem_cgroup(). Because we already hold
2074 * rcu_read_lock(), any calls to move_account will be delayed until
2075 * rcu_read_unlock() if mem_cgroup_stolen() == true.
2077 if (!mem_cgroup_stolen(memcg))
2080 move_lock_mem_cgroup(memcg, flags);
2081 if (memcg != pc->mem_cgroup || !PageCgroupUsed(pc)) {
2082 move_unlock_mem_cgroup(memcg, flags);
2088 void __mem_cgroup_end_update_page_stat(struct page *page, unsigned long *flags)
2090 struct page_cgroup *pc = lookup_page_cgroup(page);
2093 * It's guaranteed that pc->mem_cgroup never changes while
2094 * lock is held because a routine modifies pc->mem_cgroup
2095 * should take move_lock_mem_cgroup().
2097 move_unlock_mem_cgroup(pc->mem_cgroup, flags);
2100 void mem_cgroup_update_page_stat(struct page *page,
2101 enum mem_cgroup_page_stat_item idx, int val)
2103 struct mem_cgroup *memcg;
2104 struct page_cgroup *pc = lookup_page_cgroup(page);
2105 unsigned long uninitialized_var(flags);
2107 if (mem_cgroup_disabled())
2110 memcg = pc->mem_cgroup;
2111 if (unlikely(!memcg || !PageCgroupUsed(pc)))
2115 case MEMCG_NR_FILE_MAPPED:
2116 idx = MEM_CGROUP_STAT_FILE_MAPPED;
2122 this_cpu_add(memcg->stat->count[idx], val);
2126 * size of first charge trial. "32" comes from vmscan.c's magic value.
2127 * TODO: maybe necessary to use big numbers in big irons.
2129 #define CHARGE_BATCH 32U
2130 struct memcg_stock_pcp {
2131 struct mem_cgroup *cached; /* this never be root cgroup */
2132 unsigned int nr_pages;
2133 struct work_struct work;
2134 unsigned long flags;
2135 #define FLUSHING_CACHED_CHARGE 0
2137 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
2138 static DEFINE_MUTEX(percpu_charge_mutex);
2141 * consume_stock: Try to consume stocked charge on this cpu.
2142 * @memcg: memcg to consume from.
2143 * @nr_pages: how many pages to charge.
2145 * The charges will only happen if @memcg matches the current cpu's memcg
2146 * stock, and at least @nr_pages are available in that stock. Failure to
2147 * service an allocation will refill the stock.
2149 * returns true if successful, false otherwise.
2151 static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2153 struct memcg_stock_pcp *stock;
2156 if (nr_pages > CHARGE_BATCH)
2159 stock = &get_cpu_var(memcg_stock);
2160 if (memcg == stock->cached && stock->nr_pages >= nr_pages)
2161 stock->nr_pages -= nr_pages;
2162 else /* need to call res_counter_charge */
2164 put_cpu_var(memcg_stock);
2169 * Returns stocks cached in percpu to res_counter and reset cached information.
2171 static void drain_stock(struct memcg_stock_pcp *stock)
2173 struct mem_cgroup *old = stock->cached;
2175 if (stock->nr_pages) {
2176 unsigned long bytes = stock->nr_pages * PAGE_SIZE;
2178 res_counter_uncharge(&old->res, bytes);
2179 if (do_swap_account)
2180 res_counter_uncharge(&old->memsw, bytes);
2181 stock->nr_pages = 0;
2183 stock->cached = NULL;
2187 * This must be called under preempt disabled or must be called by
2188 * a thread which is pinned to local cpu.
2190 static void drain_local_stock(struct work_struct *dummy)
2192 struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
2194 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2198 * Cache charges(val) which is from res_counter, to local per_cpu area.
2199 * This will be consumed by consume_stock() function, later.
2201 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2203 struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
2205 if (stock->cached != memcg) { /* reset if necessary */
2207 stock->cached = memcg;
2209 stock->nr_pages += nr_pages;
2210 put_cpu_var(memcg_stock);
2214 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2215 * of the hierarchy under it. sync flag says whether we should block
2216 * until the work is done.
2218 static void drain_all_stock(struct mem_cgroup *root_memcg, bool sync)
2222 /* Notify other cpus that system-wide "drain" is running */
2225 for_each_online_cpu(cpu) {
2226 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2227 struct mem_cgroup *memcg;
2229 memcg = stock->cached;
2230 if (!memcg || !stock->nr_pages)
2232 if (!mem_cgroup_same_or_subtree(root_memcg, memcg))
2234 if (!test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2236 drain_local_stock(&stock->work);
2238 schedule_work_on(cpu, &stock->work);
2246 for_each_online_cpu(cpu) {
2247 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2248 if (test_bit(FLUSHING_CACHED_CHARGE, &stock->flags))
2249 flush_work(&stock->work);
2256 * Tries to drain stocked charges in other cpus. This function is asynchronous
2257 * and just put a work per cpu for draining localy on each cpu. Caller can
2258 * expects some charges will be back to res_counter later but cannot wait for
2261 static void drain_all_stock_async(struct mem_cgroup *root_memcg)
2264 * If someone calls draining, avoid adding more kworker runs.
2266 if (!mutex_trylock(&percpu_charge_mutex))
2268 drain_all_stock(root_memcg, false);
2269 mutex_unlock(&percpu_charge_mutex);
2272 /* This is a synchronous drain interface. */
2273 static void drain_all_stock_sync(struct mem_cgroup *root_memcg)
2275 /* called when force_empty is called */
2276 mutex_lock(&percpu_charge_mutex);
2277 drain_all_stock(root_memcg, true);
2278 mutex_unlock(&percpu_charge_mutex);
2282 * This function drains percpu counter value from DEAD cpu and
2283 * move it to local cpu. Note that this function can be preempted.
2285 static void mem_cgroup_drain_pcp_counter(struct mem_cgroup *memcg, int cpu)
2289 spin_lock(&memcg->pcp_counter_lock);
2290 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
2291 long x = per_cpu(memcg->stat->count[i], cpu);
2293 per_cpu(memcg->stat->count[i], cpu) = 0;
2294 memcg->nocpu_base.count[i] += x;
2296 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
2297 unsigned long x = per_cpu(memcg->stat->events[i], cpu);
2299 per_cpu(memcg->stat->events[i], cpu) = 0;
2300 memcg->nocpu_base.events[i] += x;
2302 spin_unlock(&memcg->pcp_counter_lock);
2305 static int __cpuinit memcg_cpu_hotplug_callback(struct notifier_block *nb,
2306 unsigned long action,
2309 int cpu = (unsigned long)hcpu;
2310 struct memcg_stock_pcp *stock;
2311 struct mem_cgroup *iter;
2313 if (action == CPU_ONLINE)
2316 if (action != CPU_DEAD && action != CPU_DEAD_FROZEN)
2319 for_each_mem_cgroup(iter)
2320 mem_cgroup_drain_pcp_counter(iter, cpu);
2322 stock = &per_cpu(memcg_stock, cpu);
2328 /* See __mem_cgroup_try_charge() for details */
2330 CHARGE_OK, /* success */
2331 CHARGE_RETRY, /* need to retry but retry is not bad */
2332 CHARGE_NOMEM, /* we can't do more. return -ENOMEM */
2333 CHARGE_WOULDBLOCK, /* GFP_WAIT wasn't set and no enough res. */
2334 CHARGE_OOM_DIE, /* the current is killed because of OOM */
2337 static int mem_cgroup_do_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2338 unsigned int nr_pages, unsigned int min_pages,
2341 unsigned long csize = nr_pages * PAGE_SIZE;
2342 struct mem_cgroup *mem_over_limit;
2343 struct res_counter *fail_res;
2344 unsigned long flags = 0;
2347 ret = res_counter_charge(&memcg->res, csize, &fail_res);
2350 if (!do_swap_account)
2352 ret = res_counter_charge(&memcg->memsw, csize, &fail_res);
2356 res_counter_uncharge(&memcg->res, csize);
2357 mem_over_limit = mem_cgroup_from_res_counter(fail_res, memsw);
2358 flags |= MEM_CGROUP_RECLAIM_NOSWAP;
2360 mem_over_limit = mem_cgroup_from_res_counter(fail_res, res);
2362 * Never reclaim on behalf of optional batching, retry with a
2363 * single page instead.
2365 if (nr_pages > min_pages)
2366 return CHARGE_RETRY;
2368 if (!(gfp_mask & __GFP_WAIT))
2369 return CHARGE_WOULDBLOCK;
2371 if (gfp_mask & __GFP_NORETRY)
2372 return CHARGE_NOMEM;
2374 ret = mem_cgroup_reclaim(mem_over_limit, gfp_mask, flags);
2375 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2376 return CHARGE_RETRY;
2378 * Even though the limit is exceeded at this point, reclaim
2379 * may have been able to free some pages. Retry the charge
2380 * before killing the task.
2382 * Only for regular pages, though: huge pages are rather
2383 * unlikely to succeed so close to the limit, and we fall back
2384 * to regular pages anyway in case of failure.
2386 if (nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER) && ret)
2387 return CHARGE_RETRY;
2390 * At task move, charge accounts can be doubly counted. So, it's
2391 * better to wait until the end of task_move if something is going on.
2393 if (mem_cgroup_wait_acct_move(mem_over_limit))
2394 return CHARGE_RETRY;
2396 /* If we don't need to call oom-killer at el, return immediately */
2398 return CHARGE_NOMEM;
2400 if (!mem_cgroup_handle_oom(mem_over_limit, gfp_mask, get_order(csize)))
2401 return CHARGE_OOM_DIE;
2403 return CHARGE_RETRY;
2407 * __mem_cgroup_try_charge() does
2408 * 1. detect memcg to be charged against from passed *mm and *ptr,
2409 * 2. update res_counter
2410 * 3. call memory reclaim if necessary.
2412 * In some special case, if the task is fatal, fatal_signal_pending() or
2413 * has TIF_MEMDIE, this function returns -EINTR while writing root_mem_cgroup
2414 * to *ptr. There are two reasons for this. 1: fatal threads should quit as soon
2415 * as possible without any hazards. 2: all pages should have a valid
2416 * pc->mem_cgroup. If mm is NULL and the caller doesn't pass a valid memcg
2417 * pointer, that is treated as a charge to root_mem_cgroup.
2419 * So __mem_cgroup_try_charge() will return
2420 * 0 ... on success, filling *ptr with a valid memcg pointer.
2421 * -ENOMEM ... charge failure because of resource limits.
2422 * -EINTR ... if thread is fatal. *ptr is filled with root_mem_cgroup.
2424 * Unlike the exported interface, an "oom" parameter is added. if oom==true,
2425 * the oom-killer can be invoked.
2427 static int __mem_cgroup_try_charge(struct mm_struct *mm,
2429 unsigned int nr_pages,
2430 struct mem_cgroup **ptr,
2433 unsigned int batch = max(CHARGE_BATCH, nr_pages);
2434 int nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2435 struct mem_cgroup *memcg = NULL;
2439 * Unlike gloval-vm's OOM-kill, we're not in memory shortage
2440 * in system level. So, allow to go ahead dying process in addition to
2443 if (unlikely(test_thread_flag(TIF_MEMDIE)
2444 || fatal_signal_pending(current)))
2448 * We always charge the cgroup the mm_struct belongs to.
2449 * The mm_struct's mem_cgroup changes on task migration if the
2450 * thread group leader migrates. It's possible that mm is not
2451 * set, if so charge the root memcg (happens for pagecache usage).
2454 *ptr = root_mem_cgroup;
2456 if (*ptr) { /* css should be a valid one */
2458 if (mem_cgroup_is_root(memcg))
2460 if (consume_stock(memcg, nr_pages))
2462 css_get(&memcg->css);
2464 struct task_struct *p;
2467 p = rcu_dereference(mm->owner);
2469 * Because we don't have task_lock(), "p" can exit.
2470 * In that case, "memcg" can point to root or p can be NULL with
2471 * race with swapoff. Then, we have small risk of mis-accouning.
2472 * But such kind of mis-account by race always happens because
2473 * we don't have cgroup_mutex(). It's overkill and we allo that
2475 * (*) swapoff at el will charge against mm-struct not against
2476 * task-struct. So, mm->owner can be NULL.
2478 memcg = mem_cgroup_from_task(p);
2480 memcg = root_mem_cgroup;
2481 if (mem_cgroup_is_root(memcg)) {
2485 if (consume_stock(memcg, nr_pages)) {
2487 * It seems dagerous to access memcg without css_get().
2488 * But considering how consume_stok works, it's not
2489 * necessary. If consume_stock success, some charges
2490 * from this memcg are cached on this cpu. So, we
2491 * don't need to call css_get()/css_tryget() before
2492 * calling consume_stock().
2497 /* after here, we may be blocked. we need to get refcnt */
2498 if (!css_tryget(&memcg->css)) {
2508 /* If killed, bypass charge */
2509 if (fatal_signal_pending(current)) {
2510 css_put(&memcg->css);
2515 if (oom && !nr_oom_retries) {
2517 nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2520 ret = mem_cgroup_do_charge(memcg, gfp_mask, batch, nr_pages,
2525 case CHARGE_RETRY: /* not in OOM situation but retry */
2527 css_put(&memcg->css);
2530 case CHARGE_WOULDBLOCK: /* !__GFP_WAIT */
2531 css_put(&memcg->css);
2533 case CHARGE_NOMEM: /* OOM routine works */
2535 css_put(&memcg->css);
2538 /* If oom, we never return -ENOMEM */
2541 case CHARGE_OOM_DIE: /* Killed by OOM Killer */
2542 css_put(&memcg->css);
2545 } while (ret != CHARGE_OK);
2547 if (batch > nr_pages)
2548 refill_stock(memcg, batch - nr_pages);
2549 css_put(&memcg->css);
2557 *ptr = root_mem_cgroup;
2562 * Somemtimes we have to undo a charge we got by try_charge().
2563 * This function is for that and do uncharge, put css's refcnt.
2564 * gotten by try_charge().
2566 static void __mem_cgroup_cancel_charge(struct mem_cgroup *memcg,
2567 unsigned int nr_pages)
2569 if (!mem_cgroup_is_root(memcg)) {
2570 unsigned long bytes = nr_pages * PAGE_SIZE;
2572 res_counter_uncharge(&memcg->res, bytes);
2573 if (do_swap_account)
2574 res_counter_uncharge(&memcg->memsw, bytes);
2579 * Cancel chrages in this cgroup....doesn't propagate to parent cgroup.
2580 * This is useful when moving usage to parent cgroup.
2582 static void __mem_cgroup_cancel_local_charge(struct mem_cgroup *memcg,
2583 unsigned int nr_pages)
2585 unsigned long bytes = nr_pages * PAGE_SIZE;
2587 if (mem_cgroup_is_root(memcg))
2590 res_counter_uncharge_until(&memcg->res, memcg->res.parent, bytes);
2591 if (do_swap_account)
2592 res_counter_uncharge_until(&memcg->memsw,
2593 memcg->memsw.parent, bytes);
2597 * A helper function to get mem_cgroup from ID. must be called under
2598 * rcu_read_lock(). The caller is responsible for calling css_tryget if
2599 * the mem_cgroup is used for charging. (dropping refcnt from swap can be
2600 * called against removed memcg.)
2602 static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
2604 struct cgroup_subsys_state *css;
2606 /* ID 0 is unused ID */
2609 css = css_lookup(&mem_cgroup_subsys, id);
2612 return mem_cgroup_from_css(css);
2615 struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
2617 struct mem_cgroup *memcg = NULL;
2618 struct page_cgroup *pc;
2622 VM_BUG_ON(!PageLocked(page));
2624 pc = lookup_page_cgroup(page);
2625 lock_page_cgroup(pc);
2626 if (PageCgroupUsed(pc)) {
2627 memcg = pc->mem_cgroup;
2628 if (memcg && !css_tryget(&memcg->css))
2630 } else if (PageSwapCache(page)) {
2631 ent.val = page_private(page);
2632 id = lookup_swap_cgroup_id(ent);
2634 memcg = mem_cgroup_lookup(id);
2635 if (memcg && !css_tryget(&memcg->css))
2639 unlock_page_cgroup(pc);
2643 static void __mem_cgroup_commit_charge(struct mem_cgroup *memcg,
2645 unsigned int nr_pages,
2646 enum charge_type ctype,
2649 struct page_cgroup *pc = lookup_page_cgroup(page);
2650 struct zone *uninitialized_var(zone);
2651 struct lruvec *lruvec;
2652 bool was_on_lru = false;
2655 lock_page_cgroup(pc);
2656 VM_BUG_ON(PageCgroupUsed(pc));
2658 * we don't need page_cgroup_lock about tail pages, becase they are not
2659 * accessed by any other context at this point.
2663 * In some cases, SwapCache and FUSE(splice_buf->radixtree), the page
2664 * may already be on some other mem_cgroup's LRU. Take care of it.
2667 zone = page_zone(page);
2668 spin_lock_irq(&zone->lru_lock);
2669 if (PageLRU(page)) {
2670 lruvec = mem_cgroup_zone_lruvec(zone, pc->mem_cgroup);
2672 del_page_from_lru_list(page, lruvec, page_lru(page));
2677 pc->mem_cgroup = memcg;
2679 * We access a page_cgroup asynchronously without lock_page_cgroup().
2680 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
2681 * is accessed after testing USED bit. To make pc->mem_cgroup visible
2682 * before USED bit, we need memory barrier here.
2683 * See mem_cgroup_add_lru_list(), etc.
2686 SetPageCgroupUsed(pc);
2690 lruvec = mem_cgroup_zone_lruvec(zone, pc->mem_cgroup);
2691 VM_BUG_ON(PageLRU(page));
2693 add_page_to_lru_list(page, lruvec, page_lru(page));
2695 spin_unlock_irq(&zone->lru_lock);
2698 if (ctype == MEM_CGROUP_CHARGE_TYPE_ANON)
2703 mem_cgroup_charge_statistics(memcg, anon, nr_pages);
2704 unlock_page_cgroup(pc);
2707 * "charge_statistics" updated event counter. Then, check it.
2708 * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
2709 * if they exceeds softlimit.
2711 memcg_check_events(memcg, page);
2714 #ifdef CONFIG_MEMCG_KMEM
2715 static inline bool memcg_can_account_kmem(struct mem_cgroup *memcg)
2717 return !mem_cgroup_disabled() && !mem_cgroup_is_root(memcg) &&
2718 (memcg->kmem_account_flags & KMEM_ACCOUNTED_MASK);
2721 static int memcg_charge_kmem(struct mem_cgroup *memcg, gfp_t gfp, u64 size)
2723 struct res_counter *fail_res;
2724 struct mem_cgroup *_memcg;
2728 ret = res_counter_charge(&memcg->kmem, size, &fail_res);
2733 * Conditions under which we can wait for the oom_killer. Those are
2734 * the same conditions tested by the core page allocator
2736 may_oom = (gfp & __GFP_FS) && !(gfp & __GFP_NORETRY);
2739 ret = __mem_cgroup_try_charge(NULL, gfp, size >> PAGE_SHIFT,
2742 if (ret == -EINTR) {
2744 * __mem_cgroup_try_charge() chosed to bypass to root due to
2745 * OOM kill or fatal signal. Since our only options are to
2746 * either fail the allocation or charge it to this cgroup, do
2747 * it as a temporary condition. But we can't fail. From a
2748 * kmem/slab perspective, the cache has already been selected,
2749 * by mem_cgroup_kmem_get_cache(), so it is too late to change
2752 * This condition will only trigger if the task entered
2753 * memcg_charge_kmem in a sane state, but was OOM-killed during
2754 * __mem_cgroup_try_charge() above. Tasks that were already
2755 * dying when the allocation triggers should have been already
2756 * directed to the root cgroup in memcontrol.h
2758 res_counter_charge_nofail(&memcg->res, size, &fail_res);
2759 if (do_swap_account)
2760 res_counter_charge_nofail(&memcg->memsw, size,
2764 res_counter_uncharge(&memcg->kmem, size);
2769 static void memcg_uncharge_kmem(struct mem_cgroup *memcg, u64 size)
2771 res_counter_uncharge(&memcg->res, size);
2772 if (do_swap_account)
2773 res_counter_uncharge(&memcg->memsw, size);
2776 if (res_counter_uncharge(&memcg->kmem, size))
2779 if (memcg_kmem_test_and_clear_dead(memcg))
2780 mem_cgroup_put(memcg);
2784 * We need to verify if the allocation against current->mm->owner's memcg is
2785 * possible for the given order. But the page is not allocated yet, so we'll
2786 * need a further commit step to do the final arrangements.
2788 * It is possible for the task to switch cgroups in this mean time, so at
2789 * commit time, we can't rely on task conversion any longer. We'll then use
2790 * the handle argument to return to the caller which cgroup we should commit
2791 * against. We could also return the memcg directly and avoid the pointer
2792 * passing, but a boolean return value gives better semantics considering
2793 * the compiled-out case as well.
2795 * Returning true means the allocation is possible.
2798 __memcg_kmem_newpage_charge(gfp_t gfp, struct mem_cgroup **_memcg, int order)
2800 struct mem_cgroup *memcg;
2804 memcg = try_get_mem_cgroup_from_mm(current->mm);
2807 * very rare case described in mem_cgroup_from_task. Unfortunately there
2808 * isn't much we can do without complicating this too much, and it would
2809 * be gfp-dependent anyway. Just let it go
2811 if (unlikely(!memcg))
2814 if (!memcg_can_account_kmem(memcg)) {
2815 css_put(&memcg->css);
2819 ret = memcg_charge_kmem(memcg, gfp, PAGE_SIZE << order);
2823 css_put(&memcg->css);
2827 void __memcg_kmem_commit_charge(struct page *page, struct mem_cgroup *memcg,
2830 struct page_cgroup *pc;
2832 VM_BUG_ON(mem_cgroup_is_root(memcg));
2834 /* The page allocation failed. Revert */
2836 memcg_uncharge_kmem(memcg, PAGE_SIZE << order);
2840 pc = lookup_page_cgroup(page);
2841 lock_page_cgroup(pc);
2842 pc->mem_cgroup = memcg;
2843 SetPageCgroupUsed(pc);
2844 unlock_page_cgroup(pc);
2847 void __memcg_kmem_uncharge_pages(struct page *page, int order)
2849 struct mem_cgroup *memcg = NULL;
2850 struct page_cgroup *pc;
2853 pc = lookup_page_cgroup(page);
2855 * Fast unlocked return. Theoretically might have changed, have to
2856 * check again after locking.
2858 if (!PageCgroupUsed(pc))
2861 lock_page_cgroup(pc);
2862 if (PageCgroupUsed(pc)) {
2863 memcg = pc->mem_cgroup;
2864 ClearPageCgroupUsed(pc);
2866 unlock_page_cgroup(pc);
2869 * We trust that only if there is a memcg associated with the page, it
2870 * is a valid allocation
2875 VM_BUG_ON(mem_cgroup_is_root(memcg));
2876 memcg_uncharge_kmem(memcg, PAGE_SIZE << order);
2878 #endif /* CONFIG_MEMCG_KMEM */
2880 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
2882 #define PCGF_NOCOPY_AT_SPLIT (1 << PCG_LOCK | 1 << PCG_MIGRATION)
2884 * Because tail pages are not marked as "used", set it. We're under
2885 * zone->lru_lock, 'splitting on pmd' and compound_lock.
2886 * charge/uncharge will be never happen and move_account() is done under
2887 * compound_lock(), so we don't have to take care of races.
2889 void mem_cgroup_split_huge_fixup(struct page *head)
2891 struct page_cgroup *head_pc = lookup_page_cgroup(head);
2892 struct page_cgroup *pc;
2895 if (mem_cgroup_disabled())
2897 for (i = 1; i < HPAGE_PMD_NR; i++) {
2899 pc->mem_cgroup = head_pc->mem_cgroup;
2900 smp_wmb();/* see __commit_charge() */
2901 pc->flags = head_pc->flags & ~PCGF_NOCOPY_AT_SPLIT;
2904 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
2907 * mem_cgroup_move_account - move account of the page
2909 * @nr_pages: number of regular pages (>1 for huge pages)
2910 * @pc: page_cgroup of the page.
2911 * @from: mem_cgroup which the page is moved from.
2912 * @to: mem_cgroup which the page is moved to. @from != @to.
2914 * The caller must confirm following.
2915 * - page is not on LRU (isolate_page() is useful.)
2916 * - compound_lock is held when nr_pages > 1
2918 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
2921 static int mem_cgroup_move_account(struct page *page,
2922 unsigned int nr_pages,
2923 struct page_cgroup *pc,
2924 struct mem_cgroup *from,
2925 struct mem_cgroup *to)
2927 unsigned long flags;
2929 bool anon = PageAnon(page);
2931 VM_BUG_ON(from == to);
2932 VM_BUG_ON(PageLRU(page));
2934 * The page is isolated from LRU. So, collapse function
2935 * will not handle this page. But page splitting can happen.
2936 * Do this check under compound_page_lock(). The caller should
2940 if (nr_pages > 1 && !PageTransHuge(page))
2943 lock_page_cgroup(pc);
2946 if (!PageCgroupUsed(pc) || pc->mem_cgroup != from)
2949 move_lock_mem_cgroup(from, &flags);
2951 if (!anon && page_mapped(page)) {
2952 /* Update mapped_file data for mem_cgroup */
2954 __this_cpu_dec(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
2955 __this_cpu_inc(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
2958 mem_cgroup_charge_statistics(from, anon, -nr_pages);
2960 /* caller should have done css_get */
2961 pc->mem_cgroup = to;
2962 mem_cgroup_charge_statistics(to, anon, nr_pages);
2963 move_unlock_mem_cgroup(from, &flags);
2966 unlock_page_cgroup(pc);
2970 memcg_check_events(to, page);
2971 memcg_check_events(from, page);
2977 * mem_cgroup_move_parent - moves page to the parent group
2978 * @page: the page to move
2979 * @pc: page_cgroup of the page
2980 * @child: page's cgroup
2982 * move charges to its parent or the root cgroup if the group has no
2983 * parent (aka use_hierarchy==0).
2984 * Although this might fail (get_page_unless_zero, isolate_lru_page or
2985 * mem_cgroup_move_account fails) the failure is always temporary and
2986 * it signals a race with a page removal/uncharge or migration. In the
2987 * first case the page is on the way out and it will vanish from the LRU
2988 * on the next attempt and the call should be retried later.
2989 * Isolation from the LRU fails only if page has been isolated from
2990 * the LRU since we looked at it and that usually means either global
2991 * reclaim or migration going on. The page will either get back to the
2993 * Finaly mem_cgroup_move_account fails only if the page got uncharged
2994 * (!PageCgroupUsed) or moved to a different group. The page will
2995 * disappear in the next attempt.
2997 static int mem_cgroup_move_parent(struct page *page,
2998 struct page_cgroup *pc,
2999 struct mem_cgroup *child)
3001 struct mem_cgroup *parent;
3002 unsigned int nr_pages;
3003 unsigned long uninitialized_var(flags);
3006 VM_BUG_ON(mem_cgroup_is_root(child));
3009 if (!get_page_unless_zero(page))
3011 if (isolate_lru_page(page))
3014 nr_pages = hpage_nr_pages(page);
3016 parent = parent_mem_cgroup(child);
3018 * If no parent, move charges to root cgroup.
3021 parent = root_mem_cgroup;
3024 VM_BUG_ON(!PageTransHuge(page));
3025 flags = compound_lock_irqsave(page);
3028 ret = mem_cgroup_move_account(page, nr_pages,
3031 __mem_cgroup_cancel_local_charge(child, nr_pages);
3034 compound_unlock_irqrestore(page, flags);
3035 putback_lru_page(page);
3043 * Charge the memory controller for page usage.
3045 * 0 if the charge was successful
3046 * < 0 if the cgroup is over its limit
3048 static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
3049 gfp_t gfp_mask, enum charge_type ctype)
3051 struct mem_cgroup *memcg = NULL;
3052 unsigned int nr_pages = 1;
3056 if (PageTransHuge(page)) {
3057 nr_pages <<= compound_order(page);
3058 VM_BUG_ON(!PageTransHuge(page));
3060 * Never OOM-kill a process for a huge page. The
3061 * fault handler will fall back to regular pages.
3066 ret = __mem_cgroup_try_charge(mm, gfp_mask, nr_pages, &memcg, oom);
3069 __mem_cgroup_commit_charge(memcg, page, nr_pages, ctype, false);
3073 int mem_cgroup_newpage_charge(struct page *page,
3074 struct mm_struct *mm, gfp_t gfp_mask)
3076 if (mem_cgroup_disabled())
3078 VM_BUG_ON(page_mapped(page));
3079 VM_BUG_ON(page->mapping && !PageAnon(page));
3081 return mem_cgroup_charge_common(page, mm, gfp_mask,
3082 MEM_CGROUP_CHARGE_TYPE_ANON);
3086 * While swap-in, try_charge -> commit or cancel, the page is locked.
3087 * And when try_charge() successfully returns, one refcnt to memcg without
3088 * struct page_cgroup is acquired. This refcnt will be consumed by
3089 * "commit()" or removed by "cancel()"
3091 static int __mem_cgroup_try_charge_swapin(struct mm_struct *mm,
3094 struct mem_cgroup **memcgp)
3096 struct mem_cgroup *memcg;
3097 struct page_cgroup *pc;
3100 pc = lookup_page_cgroup(page);
3102 * Every swap fault against a single page tries to charge the
3103 * page, bail as early as possible. shmem_unuse() encounters
3104 * already charged pages, too. The USED bit is protected by
3105 * the page lock, which serializes swap cache removal, which
3106 * in turn serializes uncharging.
3108 if (PageCgroupUsed(pc))
3110 if (!do_swap_account)
3112 memcg = try_get_mem_cgroup_from_page(page);
3116 ret = __mem_cgroup_try_charge(NULL, mask, 1, memcgp, true);
3117 css_put(&memcg->css);
3122 ret = __mem_cgroup_try_charge(mm, mask, 1, memcgp, true);
3128 int mem_cgroup_try_charge_swapin(struct mm_struct *mm, struct page *page,
3129 gfp_t gfp_mask, struct mem_cgroup **memcgp)
3132 if (mem_cgroup_disabled())
3135 * A racing thread's fault, or swapoff, may have already
3136 * updated the pte, and even removed page from swap cache: in
3137 * those cases unuse_pte()'s pte_same() test will fail; but
3138 * there's also a KSM case which does need to charge the page.
3140 if (!PageSwapCache(page)) {
3143 ret = __mem_cgroup_try_charge(mm, gfp_mask, 1, memcgp, true);
3148 return __mem_cgroup_try_charge_swapin(mm, page, gfp_mask, memcgp);
3151 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *memcg)
3153 if (mem_cgroup_disabled())
3157 __mem_cgroup_cancel_charge(memcg, 1);
3161 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *memcg,
3162 enum charge_type ctype)
3164 if (mem_cgroup_disabled())
3169 __mem_cgroup_commit_charge(memcg, page, 1, ctype, true);
3171 * Now swap is on-memory. This means this page may be
3172 * counted both as mem and swap....double count.
3173 * Fix it by uncharging from memsw. Basically, this SwapCache is stable
3174 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
3175 * may call delete_from_swap_cache() before reach here.
3177 if (do_swap_account && PageSwapCache(page)) {
3178 swp_entry_t ent = {.val = page_private(page)};
3179 mem_cgroup_uncharge_swap(ent);
3183 void mem_cgroup_commit_charge_swapin(struct page *page,
3184 struct mem_cgroup *memcg)
3186 __mem_cgroup_commit_charge_swapin(page, memcg,
3187 MEM_CGROUP_CHARGE_TYPE_ANON);
3190 int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
3193 struct mem_cgroup *memcg = NULL;
3194 enum charge_type type = MEM_CGROUP_CHARGE_TYPE_CACHE;
3197 if (mem_cgroup_disabled())
3199 if (PageCompound(page))
3202 if (!PageSwapCache(page))
3203 ret = mem_cgroup_charge_common(page, mm, gfp_mask, type);
3204 else { /* page is swapcache/shmem */
3205 ret = __mem_cgroup_try_charge_swapin(mm, page,
3208 __mem_cgroup_commit_charge_swapin(page, memcg, type);
3213 static void mem_cgroup_do_uncharge(struct mem_cgroup *memcg,
3214 unsigned int nr_pages,
3215 const enum charge_type ctype)
3217 struct memcg_batch_info *batch = NULL;
3218 bool uncharge_memsw = true;
3220 /* If swapout, usage of swap doesn't decrease */
3221 if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
3222 uncharge_memsw = false;
3224 batch = ¤t->memcg_batch;
3226 * In usual, we do css_get() when we remember memcg pointer.
3227 * But in this case, we keep res->usage until end of a series of
3228 * uncharges. Then, it's ok to ignore memcg's refcnt.
3231 batch->memcg = memcg;
3233 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
3234 * In those cases, all pages freed continuously can be expected to be in
3235 * the same cgroup and we have chance to coalesce uncharges.
3236 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
3237 * because we want to do uncharge as soon as possible.
3240 if (!batch->do_batch || test_thread_flag(TIF_MEMDIE))
3241 goto direct_uncharge;
3244 goto direct_uncharge;
3247 * In typical case, batch->memcg == mem. This means we can
3248 * merge a series of uncharges to an uncharge of res_counter.
3249 * If not, we uncharge res_counter ony by one.
3251 if (batch->memcg != memcg)
3252 goto direct_uncharge;
3253 /* remember freed charge and uncharge it later */
3256 batch->memsw_nr_pages++;
3259 res_counter_uncharge(&memcg->res, nr_pages * PAGE_SIZE);
3261 res_counter_uncharge(&memcg->memsw, nr_pages * PAGE_SIZE);
3262 if (unlikely(batch->memcg != memcg))
3263 memcg_oom_recover(memcg);
3267 * uncharge if !page_mapped(page)
3269 static struct mem_cgroup *
3270 __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype,
3273 struct mem_cgroup *memcg = NULL;
3274 unsigned int nr_pages = 1;
3275 struct page_cgroup *pc;
3278 if (mem_cgroup_disabled())
3281 VM_BUG_ON(PageSwapCache(page));
3283 if (PageTransHuge(page)) {
3284 nr_pages <<= compound_order(page);
3285 VM_BUG_ON(!PageTransHuge(page));
3288 * Check if our page_cgroup is valid
3290 pc = lookup_page_cgroup(page);
3291 if (unlikely(!PageCgroupUsed(pc)))
3294 lock_page_cgroup(pc);
3296 memcg = pc->mem_cgroup;
3298 if (!PageCgroupUsed(pc))
3301 anon = PageAnon(page);
3304 case MEM_CGROUP_CHARGE_TYPE_ANON:
3306 * Generally PageAnon tells if it's the anon statistics to be
3307 * updated; but sometimes e.g. mem_cgroup_uncharge_page() is
3308 * used before page reached the stage of being marked PageAnon.
3312 case MEM_CGROUP_CHARGE_TYPE_DROP:
3313 /* See mem_cgroup_prepare_migration() */
3314 if (page_mapped(page))
3317 * Pages under migration may not be uncharged. But
3318 * end_migration() /must/ be the one uncharging the
3319 * unused post-migration page and so it has to call
3320 * here with the migration bit still set. See the
3321 * res_counter handling below.
3323 if (!end_migration && PageCgroupMigration(pc))
3326 case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
3327 if (!PageAnon(page)) { /* Shared memory */
3328 if (page->mapping && !page_is_file_cache(page))
3330 } else if (page_mapped(page)) /* Anon */
3337 mem_cgroup_charge_statistics(memcg, anon, -nr_pages);
3339 ClearPageCgroupUsed(pc);
3341 * pc->mem_cgroup is not cleared here. It will be accessed when it's
3342 * freed from LRU. This is safe because uncharged page is expected not
3343 * to be reused (freed soon). Exception is SwapCache, it's handled by
3344 * special functions.
3347 unlock_page_cgroup(pc);
3349 * even after unlock, we have memcg->res.usage here and this memcg
3350 * will never be freed.
3352 memcg_check_events(memcg, page);
3353 if (do_swap_account && ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT) {
3354 mem_cgroup_swap_statistics(memcg, true);
3355 mem_cgroup_get(memcg);
3358 * Migration does not charge the res_counter for the
3359 * replacement page, so leave it alone when phasing out the
3360 * page that is unused after the migration.
3362 if (!end_migration && !mem_cgroup_is_root(memcg))
3363 mem_cgroup_do_uncharge(memcg, nr_pages, ctype);
3368 unlock_page_cgroup(pc);
3372 void mem_cgroup_uncharge_page(struct page *page)
3375 if (page_mapped(page))
3377 VM_BUG_ON(page->mapping && !PageAnon(page));
3378 if (PageSwapCache(page))
3380 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_ANON, false);
3383 void mem_cgroup_uncharge_cache_page(struct page *page)
3385 VM_BUG_ON(page_mapped(page));
3386 VM_BUG_ON(page->mapping);
3387 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE, false);
3391 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
3392 * In that cases, pages are freed continuously and we can expect pages
3393 * are in the same memcg. All these calls itself limits the number of
3394 * pages freed at once, then uncharge_start/end() is called properly.
3395 * This may be called prural(2) times in a context,
3398 void mem_cgroup_uncharge_start(void)
3400 current->memcg_batch.do_batch++;
3401 /* We can do nest. */
3402 if (current->memcg_batch.do_batch == 1) {
3403 current->memcg_batch.memcg = NULL;
3404 current->memcg_batch.nr_pages = 0;
3405 current->memcg_batch.memsw_nr_pages = 0;
3409 void mem_cgroup_uncharge_end(void)
3411 struct memcg_batch_info *batch = ¤t->memcg_batch;
3413 if (!batch->do_batch)
3417 if (batch->do_batch) /* If stacked, do nothing. */
3423 * This "batch->memcg" is valid without any css_get/put etc...
3424 * bacause we hide charges behind us.
3426 if (batch->nr_pages)
3427 res_counter_uncharge(&batch->memcg->res,
3428 batch->nr_pages * PAGE_SIZE);
3429 if (batch->memsw_nr_pages)
3430 res_counter_uncharge(&batch->memcg->memsw,
3431 batch->memsw_nr_pages * PAGE_SIZE);
3432 memcg_oom_recover(batch->memcg);
3433 /* forget this pointer (for sanity check) */
3434 batch->memcg = NULL;
3439 * called after __delete_from_swap_cache() and drop "page" account.
3440 * memcg information is recorded to swap_cgroup of "ent"
3443 mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
3445 struct mem_cgroup *memcg;
3446 int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
3448 if (!swapout) /* this was a swap cache but the swap is unused ! */
3449 ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
3451 memcg = __mem_cgroup_uncharge_common(page, ctype, false);
3454 * record memcg information, if swapout && memcg != NULL,
3455 * mem_cgroup_get() was called in uncharge().
3457 if (do_swap_account && swapout && memcg)
3458 swap_cgroup_record(ent, css_id(&memcg->css));
3462 #ifdef CONFIG_MEMCG_SWAP
3464 * called from swap_entry_free(). remove record in swap_cgroup and
3465 * uncharge "memsw" account.
3467 void mem_cgroup_uncharge_swap(swp_entry_t ent)
3469 struct mem_cgroup *memcg;
3472 if (!do_swap_account)
3475 id = swap_cgroup_record(ent, 0);
3477 memcg = mem_cgroup_lookup(id);
3480 * We uncharge this because swap is freed.
3481 * This memcg can be obsolete one. We avoid calling css_tryget
3483 if (!mem_cgroup_is_root(memcg))
3484 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
3485 mem_cgroup_swap_statistics(memcg, false);
3486 mem_cgroup_put(memcg);
3492 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3493 * @entry: swap entry to be moved
3494 * @from: mem_cgroup which the entry is moved from
3495 * @to: mem_cgroup which the entry is moved to
3497 * It succeeds only when the swap_cgroup's record for this entry is the same
3498 * as the mem_cgroup's id of @from.
3500 * Returns 0 on success, -EINVAL on failure.
3502 * The caller must have charged to @to, IOW, called res_counter_charge() about
3503 * both res and memsw, and called css_get().
3505 static int mem_cgroup_move_swap_account(swp_entry_t entry,
3506 struct mem_cgroup *from, struct mem_cgroup *to)
3508 unsigned short old_id, new_id;
3510 old_id = css_id(&from->css);
3511 new_id = css_id(&to->css);
3513 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {