memcg: execute the whole memcg freeing in free_worker()
[linux-2.6/cjktty.git] / mm / memcontrol.c
blobe16694d5e1181b90c51cfc9901d3e9456bd980df
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>
9 * Memory thresholds
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>
31 #include <linux/mm.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>
49 #include <linux/fs.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>
56 #include "internal.h"
57 #include <net/sock.h>
58 #include <net/ip.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;
78 #else
79 static int really_do_swap_account __initdata = 0;
80 #endif
82 #else
83 #define do_swap_account 0
84 #endif
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[] = {
102 "cache",
103 "rss",
104 "mapped_file",
105 "swap",
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[] = {
117 "pgpgin",
118 "pgpgout",
119 "pgfault",
120 "pgmajfault",
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,
133 MEM_CGROUP_NTARGETS,
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 */
148 int position;
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*/
165 bool on_tree;
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;
185 spinlock_t lock;
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;
200 u64 threshold;
203 /* For threshold */
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[] */
208 unsigned int size;
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;
224 /* for OOM */
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.
244 struct mem_cgroup {
245 struct cgroup_subsys_state css;
247 * the counter to account for memory usage
249 struct res_counter res;
251 union {
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;
284 #if MAX_NUMNODES > 1
285 nodemask_t scan_nodes;
286 atomic_t numainfo_events;
287 atomic_t numainfo_updating;
288 #endif
290 * Should the accounting and control be hierarchical, per subtree?
292 bool use_hierarchy;
293 unsigned long kmem_account_flags; /* See KMEM_ACCOUNTED_*, below */
295 bool oom_lock;
296 atomic_t under_oom;
298 atomic_t refcnt;
300 int swappiness;
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;
331 * percpu counter.
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;
343 #endif
346 /* internal only representation about the status of kmem accounting. */
347 enum {
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);
384 #endif
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.
391 enum move_type {
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 */
394 NR_MOVE_TYPE,
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 */
407 } mc = {
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
431 enum charge_type {
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 */
436 NR_CHARGE_TYPE,
439 /* for encoding cft->private value on file */
440 enum res_type {
441 _MEM,
442 _MEMSWAP,
443 _OOM_TYPE,
444 _KMEM,
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);
464 static inline
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.
494 if (sk->sk_cgrp) {
495 BUG_ON(mem_cgroup_is_root(sk->sk_cgrp->memcg));
496 mem_cgroup_get(sk->sk_cgrp->memcg);
497 return;
500 rcu_read_lock();
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;
507 rcu_read_unlock();
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))
525 return NULL;
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))
534 return;
535 static_key_slow_dec(&memcg_socket_limit_enabled);
537 #else
538 static void disarm_sock_keys(struct mem_cgroup *memcg)
541 #endif
543 #ifdef CONFIG_MEMCG_KMEM
544 struct static_key memcg_kmem_enabled_key;
546 static void disarm_kmem_keys(struct mem_cgroup *memcg)
548 if (memcg_kmem_is_active(memcg))
549 static_key_slow_dec(&memcg_kmem_enabled_key);
551 * This check can't live in kmem destruction function,
552 * since the charges will outlive the cgroup
554 WARN_ON(res_counter_read_u64(&memcg->kmem, RES_USAGE) != 0);
556 #else
557 static void disarm_kmem_keys(struct mem_cgroup *memcg)
560 #endif /* CONFIG_MEMCG_KMEM */
562 static void disarm_static_keys(struct mem_cgroup *memcg)
564 disarm_sock_keys(memcg);
565 disarm_kmem_keys(memcg);
568 static void drain_all_stock_async(struct mem_cgroup *memcg);
570 static struct mem_cgroup_per_zone *
571 mem_cgroup_zoneinfo(struct mem_cgroup *memcg, int nid, int zid)
573 return &memcg->info.nodeinfo[nid]->zoneinfo[zid];
576 struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *memcg)
578 return &memcg->css;
581 static struct mem_cgroup_per_zone *
582 page_cgroup_zoneinfo(struct mem_cgroup *memcg, struct page *page)
584 int nid = page_to_nid(page);
585 int zid = page_zonenum(page);
587 return mem_cgroup_zoneinfo(memcg, nid, zid);
590 static struct mem_cgroup_tree_per_zone *
591 soft_limit_tree_node_zone(int nid, int zid)
593 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
596 static struct mem_cgroup_tree_per_zone *
597 soft_limit_tree_from_page(struct page *page)
599 int nid = page_to_nid(page);
600 int zid = page_zonenum(page);
602 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
605 static void
606 __mem_cgroup_insert_exceeded(struct mem_cgroup *memcg,
607 struct mem_cgroup_per_zone *mz,
608 struct mem_cgroup_tree_per_zone *mctz,
609 unsigned long long new_usage_in_excess)
611 struct rb_node **p = &mctz->rb_root.rb_node;
612 struct rb_node *parent = NULL;
613 struct mem_cgroup_per_zone *mz_node;
615 if (mz->on_tree)
616 return;
618 mz->usage_in_excess = new_usage_in_excess;
619 if (!mz->usage_in_excess)
620 return;
621 while (*p) {
622 parent = *p;
623 mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
624 tree_node);
625 if (mz->usage_in_excess < mz_node->usage_in_excess)
626 p = &(*p)->rb_left;
628 * We can't avoid mem cgroups that are over their soft
629 * limit by the same amount
631 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
632 p = &(*p)->rb_right;
634 rb_link_node(&mz->tree_node, parent, p);
635 rb_insert_color(&mz->tree_node, &mctz->rb_root);
636 mz->on_tree = true;
639 static void
640 __mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
641 struct mem_cgroup_per_zone *mz,
642 struct mem_cgroup_tree_per_zone *mctz)
644 if (!mz->on_tree)
645 return;
646 rb_erase(&mz->tree_node, &mctz->rb_root);
647 mz->on_tree = false;
650 static void
651 mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
652 struct mem_cgroup_per_zone *mz,
653 struct mem_cgroup_tree_per_zone *mctz)
655 spin_lock(&mctz->lock);
656 __mem_cgroup_remove_exceeded(memcg, mz, mctz);
657 spin_unlock(&mctz->lock);
661 static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
663 unsigned long long excess;
664 struct mem_cgroup_per_zone *mz;
665 struct mem_cgroup_tree_per_zone *mctz;
666 int nid = page_to_nid(page);
667 int zid = page_zonenum(page);
668 mctz = soft_limit_tree_from_page(page);
671 * Necessary to update all ancestors when hierarchy is used.
672 * because their event counter is not touched.
674 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
675 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
676 excess = res_counter_soft_limit_excess(&memcg->res);
678 * We have to update the tree if mz is on RB-tree or
679 * mem is over its softlimit.
681 if (excess || mz->on_tree) {
682 spin_lock(&mctz->lock);
683 /* if on-tree, remove it */
684 if (mz->on_tree)
685 __mem_cgroup_remove_exceeded(memcg, mz, mctz);
687 * Insert again. mz->usage_in_excess will be updated.
688 * If excess is 0, no tree ops.
690 __mem_cgroup_insert_exceeded(memcg, mz, mctz, excess);
691 spin_unlock(&mctz->lock);
696 static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
698 int node, zone;
699 struct mem_cgroup_per_zone *mz;
700 struct mem_cgroup_tree_per_zone *mctz;
702 for_each_node(node) {
703 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
704 mz = mem_cgroup_zoneinfo(memcg, node, zone);
705 mctz = soft_limit_tree_node_zone(node, zone);
706 mem_cgroup_remove_exceeded(memcg, mz, mctz);
711 static struct mem_cgroup_per_zone *
712 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
714 struct rb_node *rightmost = NULL;
715 struct mem_cgroup_per_zone *mz;
717 retry:
718 mz = NULL;
719 rightmost = rb_last(&mctz->rb_root);
720 if (!rightmost)
721 goto done; /* Nothing to reclaim from */
723 mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
725 * Remove the node now but someone else can add it back,
726 * we will to add it back at the end of reclaim to its correct
727 * position in the tree.
729 __mem_cgroup_remove_exceeded(mz->memcg, mz, mctz);
730 if (!res_counter_soft_limit_excess(&mz->memcg->res) ||
731 !css_tryget(&mz->memcg->css))
732 goto retry;
733 done:
734 return mz;
737 static struct mem_cgroup_per_zone *
738 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
740 struct mem_cgroup_per_zone *mz;
742 spin_lock(&mctz->lock);
743 mz = __mem_cgroup_largest_soft_limit_node(mctz);
744 spin_unlock(&mctz->lock);
745 return mz;
749 * Implementation Note: reading percpu statistics for memcg.
751 * Both of vmstat[] and percpu_counter has threshold and do periodic
752 * synchronization to implement "quick" read. There are trade-off between
753 * reading cost and precision of value. Then, we may have a chance to implement
754 * a periodic synchronizion of counter in memcg's counter.
756 * But this _read() function is used for user interface now. The user accounts
757 * memory usage by memory cgroup and he _always_ requires exact value because
758 * he accounts memory. Even if we provide quick-and-fuzzy read, we always
759 * have to visit all online cpus and make sum. So, for now, unnecessary
760 * synchronization is not implemented. (just implemented for cpu hotplug)
762 * If there are kernel internal actions which can make use of some not-exact
763 * value, and reading all cpu value can be performance bottleneck in some
764 * common workload, threashold and synchonization as vmstat[] should be
765 * implemented.
767 static long mem_cgroup_read_stat(struct mem_cgroup *memcg,
768 enum mem_cgroup_stat_index idx)
770 long val = 0;
771 int cpu;
773 get_online_cpus();
774 for_each_online_cpu(cpu)
775 val += per_cpu(memcg->stat->count[idx], cpu);
776 #ifdef CONFIG_HOTPLUG_CPU
777 spin_lock(&memcg->pcp_counter_lock);
778 val += memcg->nocpu_base.count[idx];
779 spin_unlock(&memcg->pcp_counter_lock);
780 #endif
781 put_online_cpus();
782 return val;
785 static void mem_cgroup_swap_statistics(struct mem_cgroup *memcg,
786 bool charge)
788 int val = (charge) ? 1 : -1;
789 this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_SWAP], val);
792 static unsigned long mem_cgroup_read_events(struct mem_cgroup *memcg,
793 enum mem_cgroup_events_index idx)
795 unsigned long val = 0;
796 int cpu;
798 for_each_online_cpu(cpu)
799 val += per_cpu(memcg->stat->events[idx], cpu);
800 #ifdef CONFIG_HOTPLUG_CPU
801 spin_lock(&memcg->pcp_counter_lock);
802 val += memcg->nocpu_base.events[idx];
803 spin_unlock(&memcg->pcp_counter_lock);
804 #endif
805 return val;
808 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
809 bool anon, int nr_pages)
811 preempt_disable();
814 * Here, RSS means 'mapped anon' and anon's SwapCache. Shmem/tmpfs is
815 * counted as CACHE even if it's on ANON LRU.
817 if (anon)
818 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS],
819 nr_pages);
820 else
821 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_CACHE],
822 nr_pages);
824 /* pagein of a big page is an event. So, ignore page size */
825 if (nr_pages > 0)
826 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGIN]);
827 else {
828 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGOUT]);
829 nr_pages = -nr_pages; /* for event */
832 __this_cpu_add(memcg->stat->nr_page_events, nr_pages);
834 preempt_enable();
837 unsigned long
838 mem_cgroup_get_lru_size(struct lruvec *lruvec, enum lru_list lru)
840 struct mem_cgroup_per_zone *mz;
842 mz = container_of(lruvec, struct mem_cgroup_per_zone, lruvec);
843 return mz->lru_size[lru];
846 static unsigned long
847 mem_cgroup_zone_nr_lru_pages(struct mem_cgroup *memcg, int nid, int zid,
848 unsigned int lru_mask)
850 struct mem_cgroup_per_zone *mz;
851 enum lru_list lru;
852 unsigned long ret = 0;
854 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
856 for_each_lru(lru) {
857 if (BIT(lru) & lru_mask)
858 ret += mz->lru_size[lru];
860 return ret;
863 static unsigned long
864 mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
865 int nid, unsigned int lru_mask)
867 u64 total = 0;
868 int zid;
870 for (zid = 0; zid < MAX_NR_ZONES; zid++)
871 total += mem_cgroup_zone_nr_lru_pages(memcg,
872 nid, zid, lru_mask);
874 return total;
877 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
878 unsigned int lru_mask)
880 int nid;
881 u64 total = 0;
883 for_each_node_state(nid, N_MEMORY)
884 total += mem_cgroup_node_nr_lru_pages(memcg, nid, lru_mask);
885 return total;
888 static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
889 enum mem_cgroup_events_target target)
891 unsigned long val, next;
893 val = __this_cpu_read(memcg->stat->nr_page_events);
894 next = __this_cpu_read(memcg->stat->targets[target]);
895 /* from time_after() in jiffies.h */
896 if ((long)next - (long)val < 0) {
897 switch (target) {
898 case MEM_CGROUP_TARGET_THRESH:
899 next = val + THRESHOLDS_EVENTS_TARGET;
900 break;
901 case MEM_CGROUP_TARGET_SOFTLIMIT:
902 next = val + SOFTLIMIT_EVENTS_TARGET;
903 break;
904 case MEM_CGROUP_TARGET_NUMAINFO:
905 next = val + NUMAINFO_EVENTS_TARGET;
906 break;
907 default:
908 break;
910 __this_cpu_write(memcg->stat->targets[target], next);
911 return true;
913 return false;
917 * Check events in order.
920 static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
922 preempt_disable();
923 /* threshold event is triggered in finer grain than soft limit */
924 if (unlikely(mem_cgroup_event_ratelimit(memcg,
925 MEM_CGROUP_TARGET_THRESH))) {
926 bool do_softlimit;
927 bool do_numainfo __maybe_unused;
929 do_softlimit = mem_cgroup_event_ratelimit(memcg,
930 MEM_CGROUP_TARGET_SOFTLIMIT);
931 #if MAX_NUMNODES > 1
932 do_numainfo = mem_cgroup_event_ratelimit(memcg,
933 MEM_CGROUP_TARGET_NUMAINFO);
934 #endif
935 preempt_enable();
937 mem_cgroup_threshold(memcg);
938 if (unlikely(do_softlimit))
939 mem_cgroup_update_tree(memcg, page);
940 #if MAX_NUMNODES > 1
941 if (unlikely(do_numainfo))
942 atomic_inc(&memcg->numainfo_events);
943 #endif
944 } else
945 preempt_enable();
948 struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
950 return mem_cgroup_from_css(
951 cgroup_subsys_state(cont, mem_cgroup_subsys_id));
954 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
957 * mm_update_next_owner() may clear mm->owner to NULL
958 * if it races with swapoff, page migration, etc.
959 * So this can be called with p == NULL.
961 if (unlikely(!p))
962 return NULL;
964 return mem_cgroup_from_css(task_subsys_state(p, mem_cgroup_subsys_id));
967 struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
969 struct mem_cgroup *memcg = NULL;
971 if (!mm)
972 return NULL;
974 * Because we have no locks, mm->owner's may be being moved to other
975 * cgroup. We use css_tryget() here even if this looks
976 * pessimistic (rather than adding locks here).
978 rcu_read_lock();
979 do {
980 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
981 if (unlikely(!memcg))
982 break;
983 } while (!css_tryget(&memcg->css));
984 rcu_read_unlock();
985 return memcg;
989 * mem_cgroup_iter - iterate over memory cgroup hierarchy
990 * @root: hierarchy root
991 * @prev: previously returned memcg, NULL on first invocation
992 * @reclaim: cookie for shared reclaim walks, NULL for full walks
994 * Returns references to children of the hierarchy below @root, or
995 * @root itself, or %NULL after a full round-trip.
997 * Caller must pass the return value in @prev on subsequent
998 * invocations for reference counting, or use mem_cgroup_iter_break()
999 * to cancel a hierarchy walk before the round-trip is complete.
1001 * Reclaimers can specify a zone and a priority level in @reclaim to
1002 * divide up the memcgs in the hierarchy among all concurrent
1003 * reclaimers operating on the same zone and priority.
1005 struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
1006 struct mem_cgroup *prev,
1007 struct mem_cgroup_reclaim_cookie *reclaim)
1009 struct mem_cgroup *memcg = NULL;
1010 int id = 0;
1012 if (mem_cgroup_disabled())
1013 return NULL;
1015 if (!root)
1016 root = root_mem_cgroup;
1018 if (prev && !reclaim)
1019 id = css_id(&prev->css);
1021 if (prev && prev != root)
1022 css_put(&prev->css);
1024 if (!root->use_hierarchy && root != root_mem_cgroup) {
1025 if (prev)
1026 return NULL;
1027 return root;
1030 while (!memcg) {
1031 struct mem_cgroup_reclaim_iter *uninitialized_var(iter);
1032 struct cgroup_subsys_state *css;
1034 if (reclaim) {
1035 int nid = zone_to_nid(reclaim->zone);
1036 int zid = zone_idx(reclaim->zone);
1037 struct mem_cgroup_per_zone *mz;
1039 mz = mem_cgroup_zoneinfo(root, nid, zid);
1040 iter = &mz->reclaim_iter[reclaim->priority];
1041 if (prev && reclaim->generation != iter->generation)
1042 return NULL;
1043 id = iter->position;
1046 rcu_read_lock();
1047 css = css_get_next(&mem_cgroup_subsys, id + 1, &root->css, &id);
1048 if (css) {
1049 if (css == &root->css || css_tryget(css))
1050 memcg = mem_cgroup_from_css(css);
1051 } else
1052 id = 0;
1053 rcu_read_unlock();
1055 if (reclaim) {
1056 iter->position = id;
1057 if (!css)
1058 iter->generation++;
1059 else if (!prev && memcg)
1060 reclaim->generation = iter->generation;
1063 if (prev && !css)
1064 return NULL;
1066 return memcg;
1070 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1071 * @root: hierarchy root
1072 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1074 void mem_cgroup_iter_break(struct mem_cgroup *root,
1075 struct mem_cgroup *prev)
1077 if (!root)
1078 root = root_mem_cgroup;
1079 if (prev && prev != root)
1080 css_put(&prev->css);
1084 * Iteration constructs for visiting all cgroups (under a tree). If
1085 * loops are exited prematurely (break), mem_cgroup_iter_break() must
1086 * be used for reference counting.
1088 #define for_each_mem_cgroup_tree(iter, root) \
1089 for (iter = mem_cgroup_iter(root, NULL, NULL); \
1090 iter != NULL; \
1091 iter = mem_cgroup_iter(root, iter, NULL))
1093 #define for_each_mem_cgroup(iter) \
1094 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
1095 iter != NULL; \
1096 iter = mem_cgroup_iter(NULL, iter, NULL))
1098 void __mem_cgroup_count_vm_event(struct mm_struct *mm, enum vm_event_item idx)
1100 struct mem_cgroup *memcg;
1102 rcu_read_lock();
1103 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
1104 if (unlikely(!memcg))
1105 goto out;
1107 switch (idx) {
1108 case PGFAULT:
1109 this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGFAULT]);
1110 break;
1111 case PGMAJFAULT:
1112 this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGMAJFAULT]);
1113 break;
1114 default:
1115 BUG();
1117 out:
1118 rcu_read_unlock();
1120 EXPORT_SYMBOL(__mem_cgroup_count_vm_event);
1123 * mem_cgroup_zone_lruvec - get the lru list vector for a zone and memcg
1124 * @zone: zone of the wanted lruvec
1125 * @memcg: memcg of the wanted lruvec
1127 * Returns the lru list vector holding pages for the given @zone and
1128 * @mem. This can be the global zone lruvec, if the memory controller
1129 * is disabled.
1131 struct lruvec *mem_cgroup_zone_lruvec(struct zone *zone,
1132 struct mem_cgroup *memcg)
1134 struct mem_cgroup_per_zone *mz;
1135 struct lruvec *lruvec;
1137 if (mem_cgroup_disabled()) {
1138 lruvec = &zone->lruvec;
1139 goto out;
1142 mz = mem_cgroup_zoneinfo(memcg, zone_to_nid(zone), zone_idx(zone));
1143 lruvec = &mz->lruvec;
1144 out:
1146 * Since a node can be onlined after the mem_cgroup was created,
1147 * we have to be prepared to initialize lruvec->zone here;
1148 * and if offlined then reonlined, we need to reinitialize it.
1150 if (unlikely(lruvec->zone != zone))
1151 lruvec->zone = zone;
1152 return lruvec;
1156 * Following LRU functions are allowed to be used without PCG_LOCK.
1157 * Operations are called by routine of global LRU independently from memcg.
1158 * What we have to take care of here is validness of pc->mem_cgroup.
1160 * Changes to pc->mem_cgroup happens when
1161 * 1. charge
1162 * 2. moving account
1163 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
1164 * It is added to LRU before charge.
1165 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
1166 * When moving account, the page is not on LRU. It's isolated.
1170 * mem_cgroup_page_lruvec - return lruvec for adding an lru page
1171 * @page: the page
1172 * @zone: zone of the page
1174 struct lruvec *mem_cgroup_page_lruvec(struct page *page, struct zone *zone)
1176 struct mem_cgroup_per_zone *mz;
1177 struct mem_cgroup *memcg;
1178 struct page_cgroup *pc;
1179 struct lruvec *lruvec;
1181 if (mem_cgroup_disabled()) {
1182 lruvec = &zone->lruvec;
1183 goto out;
1186 pc = lookup_page_cgroup(page);
1187 memcg = pc->mem_cgroup;
1190 * Surreptitiously switch any uncharged offlist page to root:
1191 * an uncharged page off lru does nothing to secure
1192 * its former mem_cgroup from sudden removal.
1194 * Our caller holds lru_lock, and PageCgroupUsed is updated
1195 * under page_cgroup lock: between them, they make all uses
1196 * of pc->mem_cgroup safe.
1198 if (!PageLRU(page) && !PageCgroupUsed(pc) && memcg != root_mem_cgroup)
1199 pc->mem_cgroup = memcg = root_mem_cgroup;
1201 mz = page_cgroup_zoneinfo(memcg, page);
1202 lruvec = &mz->lruvec;
1203 out:
1205 * Since a node can be onlined after the mem_cgroup was created,
1206 * we have to be prepared to initialize lruvec->zone here;
1207 * and if offlined then reonlined, we need to reinitialize it.
1209 if (unlikely(lruvec->zone != zone))
1210 lruvec->zone = zone;
1211 return lruvec;
1215 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1216 * @lruvec: mem_cgroup per zone lru vector
1217 * @lru: index of lru list the page is sitting on
1218 * @nr_pages: positive when adding or negative when removing
1220 * This function must be called when a page is added to or removed from an
1221 * lru list.
1223 void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
1224 int nr_pages)
1226 struct mem_cgroup_per_zone *mz;
1227 unsigned long *lru_size;
1229 if (mem_cgroup_disabled())
1230 return;
1232 mz = container_of(lruvec, struct mem_cgroup_per_zone, lruvec);
1233 lru_size = mz->lru_size + lru;
1234 *lru_size += nr_pages;
1235 VM_BUG_ON((long)(*lru_size) < 0);
1239 * Checks whether given mem is same or in the root_mem_cgroup's
1240 * hierarchy subtree
1242 bool __mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
1243 struct mem_cgroup *memcg)
1245 if (root_memcg == memcg)
1246 return true;
1247 if (!root_memcg->use_hierarchy || !memcg)
1248 return false;
1249 return css_is_ancestor(&memcg->css, &root_memcg->css);
1252 static bool mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
1253 struct mem_cgroup *memcg)
1255 bool ret;
1257 rcu_read_lock();
1258 ret = __mem_cgroup_same_or_subtree(root_memcg, memcg);
1259 rcu_read_unlock();
1260 return ret;
1263 int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *memcg)
1265 int ret;
1266 struct mem_cgroup *curr = NULL;
1267 struct task_struct *p;
1269 p = find_lock_task_mm(task);
1270 if (p) {
1271 curr = try_get_mem_cgroup_from_mm(p->mm);
1272 task_unlock(p);
1273 } else {
1275 * All threads may have already detached their mm's, but the oom
1276 * killer still needs to detect if they have already been oom
1277 * killed to prevent needlessly killing additional tasks.
1279 task_lock(task);
1280 curr = mem_cgroup_from_task(task);
1281 if (curr)
1282 css_get(&curr->css);
1283 task_unlock(task);
1285 if (!curr)
1286 return 0;
1288 * We should check use_hierarchy of "memcg" not "curr". Because checking
1289 * use_hierarchy of "curr" here make this function true if hierarchy is
1290 * enabled in "curr" and "curr" is a child of "memcg" in *cgroup*
1291 * hierarchy(even if use_hierarchy is disabled in "memcg").
1293 ret = mem_cgroup_same_or_subtree(memcg, curr);
1294 css_put(&curr->css);
1295 return ret;
1298 int mem_cgroup_inactive_anon_is_low(struct lruvec *lruvec)
1300 unsigned long inactive_ratio;
1301 unsigned long inactive;
1302 unsigned long active;
1303 unsigned long gb;
1305 inactive = mem_cgroup_get_lru_size(lruvec, LRU_INACTIVE_ANON);
1306 active = mem_cgroup_get_lru_size(lruvec, LRU_ACTIVE_ANON);
1308 gb = (inactive + active) >> (30 - PAGE_SHIFT);
1309 if (gb)
1310 inactive_ratio = int_sqrt(10 * gb);
1311 else
1312 inactive_ratio = 1;
1314 return inactive * inactive_ratio < active;
1317 int mem_cgroup_inactive_file_is_low(struct lruvec *lruvec)
1319 unsigned long active;
1320 unsigned long inactive;
1322 inactive = mem_cgroup_get_lru_size(lruvec, LRU_INACTIVE_FILE);
1323 active = mem_cgroup_get_lru_size(lruvec, LRU_ACTIVE_FILE);
1325 return (active > inactive);
1328 #define mem_cgroup_from_res_counter(counter, member) \
1329 container_of(counter, struct mem_cgroup, member)
1332 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1333 * @memcg: the memory cgroup
1335 * Returns the maximum amount of memory @mem can be charged with, in
1336 * pages.
1338 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1340 unsigned long long margin;
1342 margin = res_counter_margin(&memcg->res);
1343 if (do_swap_account)
1344 margin = min(margin, res_counter_margin(&memcg->memsw));
1345 return margin >> PAGE_SHIFT;
1348 int mem_cgroup_swappiness(struct mem_cgroup *memcg)
1350 struct cgroup *cgrp = memcg->css.cgroup;
1352 /* root ? */
1353 if (cgrp->parent == NULL)
1354 return vm_swappiness;
1356 return memcg->swappiness;
1360 * memcg->moving_account is used for checking possibility that some thread is
1361 * calling move_account(). When a thread on CPU-A starts moving pages under
1362 * a memcg, other threads should check memcg->moving_account under
1363 * rcu_read_lock(), like this:
1365 * CPU-A CPU-B
1366 * rcu_read_lock()
1367 * memcg->moving_account+1 if (memcg->mocing_account)
1368 * take heavy locks.
1369 * synchronize_rcu() update something.
1370 * rcu_read_unlock()
1371 * start move here.
1374 /* for quick checking without looking up memcg */
1375 atomic_t memcg_moving __read_mostly;
1377 static void mem_cgroup_start_move(struct mem_cgroup *memcg)
1379 atomic_inc(&memcg_moving);
1380 atomic_inc(&memcg->moving_account);
1381 synchronize_rcu();
1384 static void mem_cgroup_end_move(struct mem_cgroup *memcg)
1387 * Now, mem_cgroup_clear_mc() may call this function with NULL.
1388 * We check NULL in callee rather than caller.
1390 if (memcg) {
1391 atomic_dec(&memcg_moving);
1392 atomic_dec(&memcg->moving_account);
1397 * 2 routines for checking "mem" is under move_account() or not.
1399 * mem_cgroup_stolen() - checking whether a cgroup is mc.from or not. This
1400 * is used for avoiding races in accounting. If true,
1401 * pc->mem_cgroup may be overwritten.
1403 * mem_cgroup_under_move() - checking a cgroup is mc.from or mc.to or
1404 * under hierarchy of moving cgroups. This is for
1405 * waiting at hith-memory prressure caused by "move".
1408 static bool mem_cgroup_stolen(struct mem_cgroup *memcg)
1410 VM_BUG_ON(!rcu_read_lock_held());
1411 return atomic_read(&memcg->moving_account) > 0;
1414 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1416 struct mem_cgroup *from;
1417 struct mem_cgroup *to;
1418 bool ret = false;
1420 * Unlike task_move routines, we access mc.to, mc.from not under
1421 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1423 spin_lock(&mc.lock);
1424 from = mc.from;
1425 to = mc.to;
1426 if (!from)
1427 goto unlock;
1429 ret = mem_cgroup_same_or_subtree(memcg, from)
1430 || mem_cgroup_same_or_subtree(memcg, to);
1431 unlock:
1432 spin_unlock(&mc.lock);
1433 return ret;
1436 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1438 if (mc.moving_task && current != mc.moving_task) {
1439 if (mem_cgroup_under_move(memcg)) {
1440 DEFINE_WAIT(wait);
1441 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1442 /* moving charge context might have finished. */
1443 if (mc.moving_task)
1444 schedule();
1445 finish_wait(&mc.waitq, &wait);
1446 return true;
1449 return false;
1453 * Take this lock when
1454 * - a code tries to modify page's memcg while it's USED.
1455 * - a code tries to modify page state accounting in a memcg.
1456 * see mem_cgroup_stolen(), too.
1458 static void move_lock_mem_cgroup(struct mem_cgroup *memcg,
1459 unsigned long *flags)
1461 spin_lock_irqsave(&memcg->move_lock, *flags);
1464 static void move_unlock_mem_cgroup(struct mem_cgroup *memcg,
1465 unsigned long *flags)
1467 spin_unlock_irqrestore(&memcg->move_lock, *flags);
1471 * mem_cgroup_print_oom_info: Called from OOM with tasklist_lock held in read mode.
1472 * @memcg: The memory cgroup that went over limit
1473 * @p: Task that is going to be killed
1475 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1476 * enabled
1478 void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1480 struct cgroup *task_cgrp;
1481 struct cgroup *mem_cgrp;
1483 * Need a buffer in BSS, can't rely on allocations. The code relies
1484 * on the assumption that OOM is serialized for memory controller.
1485 * If this assumption is broken, revisit this code.
1487 static char memcg_name[PATH_MAX];
1488 int ret;
1490 if (!memcg || !p)
1491 return;
1493 rcu_read_lock();
1495 mem_cgrp = memcg->css.cgroup;
1496 task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
1498 ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
1499 if (ret < 0) {
1501 * Unfortunately, we are unable to convert to a useful name
1502 * But we'll still print out the usage information
1504 rcu_read_unlock();
1505 goto done;
1507 rcu_read_unlock();
1509 printk(KERN_INFO "Task in %s killed", memcg_name);
1511 rcu_read_lock();
1512 ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
1513 if (ret < 0) {
1514 rcu_read_unlock();
1515 goto done;
1517 rcu_read_unlock();
1520 * Continues from above, so we don't need an KERN_ level
1522 printk(KERN_CONT " as a result of limit of %s\n", memcg_name);
1523 done:
1525 printk(KERN_INFO "memory: usage %llukB, limit %llukB, failcnt %llu\n",
1526 res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
1527 res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
1528 res_counter_read_u64(&memcg->res, RES_FAILCNT));
1529 printk(KERN_INFO "memory+swap: usage %llukB, limit %llukB, "
1530 "failcnt %llu\n",
1531 res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
1532 res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
1533 res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
1534 printk(KERN_INFO "kmem: usage %llukB, limit %llukB, failcnt %llu\n",
1535 res_counter_read_u64(&memcg->kmem, RES_USAGE) >> 10,
1536 res_counter_read_u64(&memcg->kmem, RES_LIMIT) >> 10,
1537 res_counter_read_u64(&memcg->kmem, RES_FAILCNT));
1541 * This function returns the number of memcg under hierarchy tree. Returns
1542 * 1(self count) if no children.
1544 static int mem_cgroup_count_children(struct mem_cgroup *memcg)
1546 int num = 0;
1547 struct mem_cgroup *iter;
1549 for_each_mem_cgroup_tree(iter, memcg)
1550 num++;
1551 return num;
1555 * Return the memory (and swap, if configured) limit for a memcg.
1557 static u64 mem_cgroup_get_limit(struct mem_cgroup *memcg)
1559 u64 limit;
1561 limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
1564 * Do not consider swap space if we cannot swap due to swappiness
1566 if (mem_cgroup_swappiness(memcg)) {
1567 u64 memsw;
1569 limit += total_swap_pages << PAGE_SHIFT;
1570 memsw = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
1573 * If memsw is finite and limits the amount of swap space
1574 * available to this memcg, return that limit.
1576 limit = min(limit, memsw);
1579 return limit;
1582 static void mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
1583 int order)
1585 struct mem_cgroup *iter;
1586 unsigned long chosen_points = 0;
1587 unsigned long totalpages;
1588 unsigned int points = 0;
1589 struct task_struct *chosen = NULL;
1592 * If current has a pending SIGKILL, then automatically select it. The
1593 * goal is to allow it to allocate so that it may quickly exit and free
1594 * its memory.
1596 if (fatal_signal_pending(current)) {
1597 set_thread_flag(TIF_MEMDIE);
1598 return;
1601 check_panic_on_oom(CONSTRAINT_MEMCG, gfp_mask, order, NULL);
1602 totalpages = mem_cgroup_get_limit(memcg) >> PAGE_SHIFT ? : 1;
1603 for_each_mem_cgroup_tree(iter, memcg) {
1604 struct cgroup *cgroup = iter->css.cgroup;
1605 struct cgroup_iter it;
1606 struct task_struct *task;
1608 cgroup_iter_start(cgroup, &it);
1609 while ((task = cgroup_iter_next(cgroup, &it))) {
1610 switch (oom_scan_process_thread(task, totalpages, NULL,
1611 false)) {
1612 case OOM_SCAN_SELECT:
1613 if (chosen)
1614 put_task_struct(chosen);
1615 chosen = task;
1616 chosen_points = ULONG_MAX;
1617 get_task_struct(chosen);
1618 /* fall through */
1619 case OOM_SCAN_CONTINUE:
1620 continue;
1621 case OOM_SCAN_ABORT:
1622 cgroup_iter_end(cgroup, &it);
1623 mem_cgroup_iter_break(memcg, iter);
1624 if (chosen)
1625 put_task_struct(chosen);
1626 return;
1627 case OOM_SCAN_OK:
1628 break;
1630 points = oom_badness(task, memcg, NULL, totalpages);
1631 if (points > chosen_points) {
1632 if (chosen)
1633 put_task_struct(chosen);
1634 chosen = task;
1635 chosen_points = points;
1636 get_task_struct(chosen);
1639 cgroup_iter_end(cgroup, &it);
1642 if (!chosen)
1643 return;
1644 points = chosen_points * 1000 / totalpages;
1645 oom_kill_process(chosen, gfp_mask, order, points, totalpages, memcg,
1646 NULL, "Memory cgroup out of memory");
1649 static unsigned long mem_cgroup_reclaim(struct mem_cgroup *memcg,
1650 gfp_t gfp_mask,
1651 unsigned long flags)
1653 unsigned long total = 0;
1654 bool noswap = false;
1655 int loop;
1657 if (flags & MEM_CGROUP_RECLAIM_NOSWAP)
1658 noswap = true;
1659 if (!(flags & MEM_CGROUP_RECLAIM_SHRINK) && memcg->memsw_is_minimum)
1660 noswap = true;
1662 for (loop = 0; loop < MEM_CGROUP_MAX_RECLAIM_LOOPS; loop++) {
1663 if (loop)
1664 drain_all_stock_async(memcg);
1665 total += try_to_free_mem_cgroup_pages(memcg, gfp_mask, noswap);
1667 * Allow limit shrinkers, which are triggered directly
1668 * by userspace, to catch signals and stop reclaim
1669 * after minimal progress, regardless of the margin.
1671 if (total && (flags & MEM_CGROUP_RECLAIM_SHRINK))
1672 break;
1673 if (mem_cgroup_margin(memcg))
1674 break;
1676 * If nothing was reclaimed after two attempts, there
1677 * may be no reclaimable pages in this hierarchy.
1679 if (loop && !total)
1680 break;
1682 return total;
1686 * test_mem_cgroup_node_reclaimable
1687 * @memcg: the target memcg
1688 * @nid: the node ID to be checked.
1689 * @noswap : specify true here if the user wants flle only information.
1691 * This function returns whether the specified memcg contains any
1692 * reclaimable pages on a node. Returns true if there are any reclaimable
1693 * pages in the node.
1695 static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *memcg,
1696 int nid, bool noswap)
1698 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_FILE))
1699 return true;
1700 if (noswap || !total_swap_pages)
1701 return false;
1702 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_ANON))
1703 return true;
1704 return false;
1707 #if MAX_NUMNODES > 1
1710 * Always updating the nodemask is not very good - even if we have an empty
1711 * list or the wrong list here, we can start from some node and traverse all
1712 * nodes based on the zonelist. So update the list loosely once per 10 secs.
1715 static void mem_cgroup_may_update_nodemask(struct mem_cgroup *memcg)
1717 int nid;
1719 * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
1720 * pagein/pageout changes since the last update.
1722 if (!atomic_read(&memcg->numainfo_events))
1723 return;
1724 if (atomic_inc_return(&memcg->numainfo_updating) > 1)
1725 return;
1727 /* make a nodemask where this memcg uses memory from */
1728 memcg->scan_nodes = node_states[N_MEMORY];
1730 for_each_node_mask(nid, node_states[N_MEMORY]) {
1732 if (!test_mem_cgroup_node_reclaimable(memcg, nid, false))
1733 node_clear(nid, memcg->scan_nodes);
1736 atomic_set(&memcg->numainfo_events, 0);
1737 atomic_set(&memcg->numainfo_updating, 0);
1741 * Selecting a node where we start reclaim from. Because what we need is just
1742 * reducing usage counter, start from anywhere is O,K. Considering
1743 * memory reclaim from current node, there are pros. and cons.
1745 * Freeing memory from current node means freeing memory from a node which
1746 * we'll use or we've used. So, it may make LRU bad. And if several threads
1747 * hit limits, it will see a contention on a node. But freeing from remote
1748 * node means more costs for memory reclaim because of memory latency.
1750 * Now, we use round-robin. Better algorithm is welcomed.
1752 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1754 int node;
1756 mem_cgroup_may_update_nodemask(memcg);
1757 node = memcg->last_scanned_node;
1759 node = next_node(node, memcg->scan_nodes);
1760 if (node == MAX_NUMNODES)
1761 node = first_node(memcg->scan_nodes);
1763 * We call this when we hit limit, not when pages are added to LRU.
1764 * No LRU may hold pages because all pages are UNEVICTABLE or
1765 * memcg is too small and all pages are not on LRU. In that case,
1766 * we use curret node.
1768 if (unlikely(node == MAX_NUMNODES))
1769 node = numa_node_id();
1771 memcg->last_scanned_node = node;
1772 return node;
1776 * Check all nodes whether it contains reclaimable pages or not.
1777 * For quick scan, we make use of scan_nodes. This will allow us to skip
1778 * unused nodes. But scan_nodes is lazily updated and may not cotain
1779 * enough new information. We need to do double check.
1781 static bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
1783 int nid;
1786 * quick check...making use of scan_node.
1787 * We can skip unused nodes.
1789 if (!nodes_empty(memcg->scan_nodes)) {
1790 for (nid = first_node(memcg->scan_nodes);
1791 nid < MAX_NUMNODES;
1792 nid = next_node(nid, memcg->scan_nodes)) {
1794 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
1795 return true;
1799 * Check rest of nodes.
1801 for_each_node_state(nid, N_MEMORY) {
1802 if (node_isset(nid, memcg->scan_nodes))
1803 continue;
1804 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
1805 return true;
1807 return false;
1810 #else
1811 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1813 return 0;
1816 static bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
1818 return test_mem_cgroup_node_reclaimable(memcg, 0, noswap);
1820 #endif
1822 static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
1823 struct zone *zone,
1824 gfp_t gfp_mask,
1825 unsigned long *total_scanned)
1827 struct mem_cgroup *victim = NULL;
1828 int total = 0;
1829 int loop = 0;
1830 unsigned long excess;
1831 unsigned long nr_scanned;
1832 struct mem_cgroup_reclaim_cookie reclaim = {
1833 .zone = zone,
1834 .priority = 0,
1837 excess = res_counter_soft_limit_excess(&root_memcg->res) >> PAGE_SHIFT;
1839 while (1) {
1840 victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
1841 if (!victim) {
1842 loop++;
1843 if (loop >= 2) {
1845 * If we have not been able to reclaim
1846 * anything, it might because there are
1847 * no reclaimable pages under this hierarchy
1849 if (!total)
1850 break;
1852 * We want to do more targeted reclaim.
1853 * excess >> 2 is not to excessive so as to
1854 * reclaim too much, nor too less that we keep
1855 * coming back to reclaim from this cgroup
1857 if (total >= (excess >> 2) ||
1858 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
1859 break;
1861 continue;
1863 if (!mem_cgroup_reclaimable(victim, false))
1864 continue;
1865 total += mem_cgroup_shrink_node_zone(victim, gfp_mask, false,
1866 zone, &nr_scanned);
1867 *total_scanned += nr_scanned;
1868 if (!res_counter_soft_limit_excess(&root_memcg->res))
1869 break;
1871 mem_cgroup_iter_break(root_memcg, victim);
1872 return total;
1876 * Check OOM-Killer is already running under our hierarchy.
1877 * If someone is running, return false.
1878 * Has to be called with memcg_oom_lock
1880 static bool mem_cgroup_oom_lock(struct mem_cgroup *memcg)
1882 struct mem_cgroup *iter, *failed = NULL;
1884 for_each_mem_cgroup_tree(iter, memcg) {
1885 if (iter->oom_lock) {
1887 * this subtree of our hierarchy is already locked
1888 * so we cannot give a lock.
1890 failed = iter;
1891 mem_cgroup_iter_break(memcg, iter);
1892 break;
1893 } else
1894 iter->oom_lock = true;
1897 if (!failed)
1898 return true;
1901 * OK, we failed to lock the whole subtree so we have to clean up
1902 * what we set up to the failing subtree
1904 for_each_mem_cgroup_tree(iter, memcg) {
1905 if (iter == failed) {
1906 mem_cgroup_iter_break(memcg, iter);
1907 break;
1909 iter->oom_lock = false;
1911 return false;
1915 * Has to be called with memcg_oom_lock
1917 static int mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
1919 struct mem_cgroup *iter;
1921 for_each_mem_cgroup_tree(iter, memcg)
1922 iter->oom_lock = false;
1923 return 0;
1926 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
1928 struct mem_cgroup *iter;
1930 for_each_mem_cgroup_tree(iter, memcg)
1931 atomic_inc(&iter->under_oom);
1934 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
1936 struct mem_cgroup *iter;
1939 * When a new child is created while the hierarchy is under oom,
1940 * mem_cgroup_oom_lock() may not be called. We have to use
1941 * atomic_add_unless() here.
1943 for_each_mem_cgroup_tree(iter, memcg)
1944 atomic_add_unless(&iter->under_oom, -1, 0);
1947 static DEFINE_SPINLOCK(memcg_oom_lock);
1948 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1950 struct oom_wait_info {
1951 struct mem_cgroup *memcg;
1952 wait_queue_t wait;
1955 static int memcg_oom_wake_function(wait_queue_t *wait,
1956 unsigned mode, int sync, void *arg)
1958 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
1959 struct mem_cgroup *oom_wait_memcg;
1960 struct oom_wait_info *oom_wait_info;
1962 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1963 oom_wait_memcg = oom_wait_info->memcg;
1966 * Both of oom_wait_info->memcg and wake_memcg are stable under us.
1967 * Then we can use css_is_ancestor without taking care of RCU.
1969 if (!mem_cgroup_same_or_subtree(oom_wait_memcg, wake_memcg)
1970 && !mem_cgroup_same_or_subtree(wake_memcg, oom_wait_memcg))
1971 return 0;
1972 return autoremove_wake_function(wait, mode, sync, arg);
1975 static void memcg_wakeup_oom(struct mem_cgroup *memcg)
1977 /* for filtering, pass "memcg" as argument. */
1978 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
1981 static void memcg_oom_recover(struct mem_cgroup *memcg)
1983 if (memcg && atomic_read(&memcg->under_oom))
1984 memcg_wakeup_oom(memcg);
1988 * try to call OOM killer. returns false if we should exit memory-reclaim loop.
1990 static bool mem_cgroup_handle_oom(struct mem_cgroup *memcg, gfp_t mask,
1991 int order)
1993 struct oom_wait_info owait;
1994 bool locked, need_to_kill;
1996 owait.memcg = memcg;
1997 owait.wait.flags = 0;
1998 owait.wait.func = memcg_oom_wake_function;
1999 owait.wait.private = current;
2000 INIT_LIST_HEAD(&owait.wait.task_list);
2001 need_to_kill = true;
2002 mem_cgroup_mark_under_oom(memcg);
2004 /* At first, try to OOM lock hierarchy under memcg.*/
2005 spin_lock(&memcg_oom_lock);
2006 locked = mem_cgroup_oom_lock(memcg);
2008 * Even if signal_pending(), we can't quit charge() loop without
2009 * accounting. So, UNINTERRUPTIBLE is appropriate. But SIGKILL
2010 * under OOM is always welcomed, use TASK_KILLABLE here.
2012 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
2013 if (!locked || memcg->oom_kill_disable)
2014 need_to_kill = false;
2015 if (locked)
2016 mem_cgroup_oom_notify(memcg);
2017 spin_unlock(&memcg_oom_lock);
2019 if (need_to_kill) {
2020 finish_wait(&memcg_oom_waitq, &owait.wait);
2021 mem_cgroup_out_of_memory(memcg, mask, order);
2022 } else {
2023 schedule();
2024 finish_wait(&memcg_oom_waitq, &owait.wait);
2026 spin_lock(&memcg_oom_lock);
2027 if (locked)
2028 mem_cgroup_oom_unlock(memcg);
2029 memcg_wakeup_oom(memcg);
2030 spin_unlock(&memcg_oom_lock);
2032 mem_cgroup_unmark_under_oom(memcg);
2034 if (test_thread_flag(TIF_MEMDIE) || fatal_signal_pending(current))
2035 return false;
2036 /* Give chance to dying process */
2037 schedule_timeout_uninterruptible(1);
2038 return true;
2042 * Currently used to update mapped file statistics, but the routine can be
2043 * generalized to update other statistics as well.
2045 * Notes: Race condition
2047 * We usually use page_cgroup_lock() for accessing page_cgroup member but
2048 * it tends to be costly. But considering some conditions, we doesn't need
2049 * to do so _always_.
2051 * Considering "charge", lock_page_cgroup() is not required because all
2052 * file-stat operations happen after a page is attached to radix-tree. There
2053 * are no race with "charge".
2055 * Considering "uncharge", we know that memcg doesn't clear pc->mem_cgroup
2056 * at "uncharge" intentionally. So, we always see valid pc->mem_cgroup even
2057 * if there are race with "uncharge". Statistics itself is properly handled
2058 * by flags.
2060 * Considering "move", this is an only case we see a race. To make the race
2061 * small, we check mm->moving_account and detect there are possibility of race
2062 * If there is, we take a lock.
2065 void __mem_cgroup_begin_update_page_stat(struct page *page,
2066 bool *locked, unsigned long *flags)
2068 struct mem_cgroup *memcg;
2069 struct page_cgroup *pc;
2071 pc = lookup_page_cgroup(page);
2072 again:
2073 memcg = pc->mem_cgroup;
2074 if (unlikely(!memcg || !PageCgroupUsed(pc)))
2075 return;
2077 * If this memory cgroup is not under account moving, we don't
2078 * need to take move_lock_mem_cgroup(). Because we already hold
2079 * rcu_read_lock(), any calls to move_account will be delayed until
2080 * rcu_read_unlock() if mem_cgroup_stolen() == true.
2082 if (!mem_cgroup_stolen(memcg))
2083 return;
2085 move_lock_mem_cgroup(memcg, flags);
2086 if (memcg != pc->mem_cgroup || !PageCgroupUsed(pc)) {
2087 move_unlock_mem_cgroup(memcg, flags);
2088 goto again;
2090 *locked = true;
2093 void __mem_cgroup_end_update_page_stat(struct page *page, unsigned long *flags)
2095 struct page_cgroup *pc = lookup_page_cgroup(page);
2098 * It's guaranteed that pc->mem_cgroup never changes while
2099 * lock is held because a routine modifies pc->mem_cgroup
2100 * should take move_lock_mem_cgroup().
2102 move_unlock_mem_cgroup(pc->mem_cgroup, flags);
2105 void mem_cgroup_update_page_stat(struct page *page,
2106 enum mem_cgroup_page_stat_item idx, int val)
2108 struct mem_cgroup *memcg;
2109 struct page_cgroup *pc = lookup_page_cgroup(page);
2110 unsigned long uninitialized_var(flags);
2112 if (mem_cgroup_disabled())
2113 return;
2115 memcg = pc->mem_cgroup;
2116 if (unlikely(!memcg || !PageCgroupUsed(pc)))
2117 return;
2119 switch (idx) {
2120 case MEMCG_NR_FILE_MAPPED:
2121 idx = MEM_CGROUP_STAT_FILE_MAPPED;
2122 break;
2123 default:
2124 BUG();
2127 this_cpu_add(memcg->stat->count[idx], val);
2131 * size of first charge trial. "32" comes from vmscan.c's magic value.
2132 * TODO: maybe necessary to use big numbers in big irons.
2134 #define CHARGE_BATCH 32U
2135 struct memcg_stock_pcp {
2136 struct mem_cgroup *cached; /* this never be root cgroup */
2137 unsigned int nr_pages;
2138 struct work_struct work;
2139 unsigned long flags;
2140 #define FLUSHING_CACHED_CHARGE 0
2142 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
2143 static DEFINE_MUTEX(percpu_charge_mutex);
2146 * consume_stock: Try to consume stocked charge on this cpu.
2147 * @memcg: memcg to consume from.
2148 * @nr_pages: how many pages to charge.
2150 * The charges will only happen if @memcg matches the current cpu's memcg
2151 * stock, and at least @nr_pages are available in that stock. Failure to
2152 * service an allocation will refill the stock.
2154 * returns true if successful, false otherwise.
2156 static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2158 struct memcg_stock_pcp *stock;
2159 bool ret = true;
2161 if (nr_pages > CHARGE_BATCH)
2162 return false;
2164 stock = &get_cpu_var(memcg_stock);
2165 if (memcg == stock->cached && stock->nr_pages >= nr_pages)
2166 stock->nr_pages -= nr_pages;
2167 else /* need to call res_counter_charge */
2168 ret = false;
2169 put_cpu_var(memcg_stock);
2170 return ret;
2174 * Returns stocks cached in percpu to res_counter and reset cached information.
2176 static void drain_stock(struct memcg_stock_pcp *stock)
2178 struct mem_cgroup *old = stock->cached;
2180 if (stock->nr_pages) {
2181 unsigned long bytes = stock->nr_pages * PAGE_SIZE;
2183 res_counter_uncharge(&old->res, bytes);
2184 if (do_swap_account)
2185 res_counter_uncharge(&old->memsw, bytes);
2186 stock->nr_pages = 0;
2188 stock->cached = NULL;
2192 * This must be called under preempt disabled or must be called by
2193 * a thread which is pinned to local cpu.
2195 static void drain_local_stock(struct work_struct *dummy)
2197 struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
2198 drain_stock(stock);
2199 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2203 * Cache charges(val) which is from res_counter, to local per_cpu area.
2204 * This will be consumed by consume_stock() function, later.
2206 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2208 struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
2210 if (stock->cached != memcg) { /* reset if necessary */
2211 drain_stock(stock);
2212 stock->cached = memcg;
2214 stock->nr_pages += nr_pages;
2215 put_cpu_var(memcg_stock);
2219 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2220 * of the hierarchy under it. sync flag says whether we should block
2221 * until the work is done.
2223 static void drain_all_stock(struct mem_cgroup *root_memcg, bool sync)
2225 int cpu, curcpu;
2227 /* Notify other cpus that system-wide "drain" is running */
2228 get_online_cpus();
2229 curcpu = get_cpu();
2230 for_each_online_cpu(cpu) {
2231 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2232 struct mem_cgroup *memcg;
2234 memcg = stock->cached;
2235 if (!memcg || !stock->nr_pages)
2236 continue;
2237 if (!mem_cgroup_same_or_subtree(root_memcg, memcg))
2238 continue;
2239 if (!test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2240 if (cpu == curcpu)
2241 drain_local_stock(&stock->work);
2242 else
2243 schedule_work_on(cpu, &stock->work);
2246 put_cpu();
2248 if (!sync)
2249 goto out;
2251 for_each_online_cpu(cpu) {
2252 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2253 if (test_bit(FLUSHING_CACHED_CHARGE, &stock->flags))
2254 flush_work(&stock->work);
2256 out:
2257 put_online_cpus();
2261 * Tries to drain stocked charges in other cpus. This function is asynchronous
2262 * and just put a work per cpu for draining localy on each cpu. Caller can
2263 * expects some charges will be back to res_counter later but cannot wait for
2264 * it.
2266 static void drain_all_stock_async(struct mem_cgroup *root_memcg)
2269 * If someone calls draining, avoid adding more kworker runs.
2271 if (!mutex_trylock(&percpu_charge_mutex))
2272 return;
2273 drain_all_stock(root_memcg, false);
2274 mutex_unlock(&percpu_charge_mutex);
2277 /* This is a synchronous drain interface. */
2278 static void drain_all_stock_sync(struct mem_cgroup *root_memcg)
2280 /* called when force_empty is called */
2281 mutex_lock(&percpu_charge_mutex);
2282 drain_all_stock(root_memcg, true);
2283 mutex_unlock(&percpu_charge_mutex);
2287 * This function drains percpu counter value from DEAD cpu and
2288 * move it to local cpu. Note that this function can be preempted.
2290 static void mem_cgroup_drain_pcp_counter(struct mem_cgroup *memcg, int cpu)
2292 int i;
2294 spin_lock(&memcg->pcp_counter_lock);
2295 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
2296 long x = per_cpu(memcg->stat->count[i], cpu);
2298 per_cpu(memcg->stat->count[i], cpu) = 0;
2299 memcg->nocpu_base.count[i] += x;
2301 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
2302 unsigned long x = per_cpu(memcg->stat->events[i], cpu);
2304 per_cpu(memcg->stat->events[i], cpu) = 0;
2305 memcg->nocpu_base.events[i] += x;
2307 spin_unlock(&memcg->pcp_counter_lock);
2310 static int __cpuinit memcg_cpu_hotplug_callback(struct notifier_block *nb,
2311 unsigned long action,
2312 void *hcpu)
2314 int cpu = (unsigned long)hcpu;
2315 struct memcg_stock_pcp *stock;
2316 struct mem_cgroup *iter;
2318 if (action == CPU_ONLINE)
2319 return NOTIFY_OK;
2321 if (action != CPU_DEAD && action != CPU_DEAD_FROZEN)
2322 return NOTIFY_OK;
2324 for_each_mem_cgroup(iter)
2325 mem_cgroup_drain_pcp_counter(iter, cpu);
2327 stock = &per_cpu(memcg_stock, cpu);
2328 drain_stock(stock);
2329 return NOTIFY_OK;
2333 /* See __mem_cgroup_try_charge() for details */
2334 enum {
2335 CHARGE_OK, /* success */
2336 CHARGE_RETRY, /* need to retry but retry is not bad */
2337 CHARGE_NOMEM, /* we can't do more. return -ENOMEM */
2338 CHARGE_WOULDBLOCK, /* GFP_WAIT wasn't set and no enough res. */
2339 CHARGE_OOM_DIE, /* the current is killed because of OOM */
2342 static int mem_cgroup_do_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2343 unsigned int nr_pages, unsigned int min_pages,
2344 bool oom_check)
2346 unsigned long csize = nr_pages * PAGE_SIZE;
2347 struct mem_cgroup *mem_over_limit;
2348 struct res_counter *fail_res;
2349 unsigned long flags = 0;
2350 int ret;
2352 ret = res_counter_charge(&memcg->res, csize, &fail_res);
2354 if (likely(!ret)) {
2355 if (!do_swap_account)
2356 return CHARGE_OK;
2357 ret = res_counter_charge(&memcg->memsw, csize, &fail_res);
2358 if (likely(!ret))
2359 return CHARGE_OK;
2361 res_counter_uncharge(&memcg->res, csize);
2362 mem_over_limit = mem_cgroup_from_res_counter(fail_res, memsw);
2363 flags |= MEM_CGROUP_RECLAIM_NOSWAP;
2364 } else
2365 mem_over_limit = mem_cgroup_from_res_counter(fail_res, res);
2367 * Never reclaim on behalf of optional batching, retry with a
2368 * single page instead.
2370 if (nr_pages > min_pages)
2371 return CHARGE_RETRY;
2373 if (!(gfp_mask & __GFP_WAIT))
2374 return CHARGE_WOULDBLOCK;
2376 if (gfp_mask & __GFP_NORETRY)
2377 return CHARGE_NOMEM;
2379 ret = mem_cgroup_reclaim(mem_over_limit, gfp_mask, flags);
2380 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2381 return CHARGE_RETRY;
2383 * Even though the limit is exceeded at this point, reclaim
2384 * may have been able to free some pages. Retry the charge
2385 * before killing the task.
2387 * Only for regular pages, though: huge pages are rather
2388 * unlikely to succeed so close to the limit, and we fall back
2389 * to regular pages anyway in case of failure.
2391 if (nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER) && ret)
2392 return CHARGE_RETRY;
2395 * At task move, charge accounts can be doubly counted. So, it's
2396 * better to wait until the end of task_move if something is going on.
2398 if (mem_cgroup_wait_acct_move(mem_over_limit))
2399 return CHARGE_RETRY;
2401 /* If we don't need to call oom-killer at el, return immediately */
2402 if (!oom_check)
2403 return CHARGE_NOMEM;
2404 /* check OOM */
2405 if (!mem_cgroup_handle_oom(mem_over_limit, gfp_mask, get_order(csize)))
2406 return CHARGE_OOM_DIE;
2408 return CHARGE_RETRY;
2412 * __mem_cgroup_try_charge() does
2413 * 1. detect memcg to be charged against from passed *mm and *ptr,
2414 * 2. update res_counter
2415 * 3. call memory reclaim if necessary.
2417 * In some special case, if the task is fatal, fatal_signal_pending() or
2418 * has TIF_MEMDIE, this function returns -EINTR while writing root_mem_cgroup
2419 * to *ptr. There are two reasons for this. 1: fatal threads should quit as soon
2420 * as possible without any hazards. 2: all pages should have a valid
2421 * pc->mem_cgroup. If mm is NULL and the caller doesn't pass a valid memcg
2422 * pointer, that is treated as a charge to root_mem_cgroup.
2424 * So __mem_cgroup_try_charge() will return
2425 * 0 ... on success, filling *ptr with a valid memcg pointer.
2426 * -ENOMEM ... charge failure because of resource limits.
2427 * -EINTR ... if thread is fatal. *ptr is filled with root_mem_cgroup.
2429 * Unlike the exported interface, an "oom" parameter is added. if oom==true,
2430 * the oom-killer can be invoked.
2432 static int __mem_cgroup_try_charge(struct mm_struct *mm,
2433 gfp_t gfp_mask,
2434 unsigned int nr_pages,
2435 struct mem_cgroup **ptr,
2436 bool oom)
2438 unsigned int batch = max(CHARGE_BATCH, nr_pages);
2439 int nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2440 struct mem_cgroup *memcg = NULL;
2441 int ret;
2444 * Unlike gloval-vm's OOM-kill, we're not in memory shortage
2445 * in system level. So, allow to go ahead dying process in addition to
2446 * MEMDIE process.
2448 if (unlikely(test_thread_flag(TIF_MEMDIE)
2449 || fatal_signal_pending(current)))
2450 goto bypass;
2453 * We always charge the cgroup the mm_struct belongs to.
2454 * The mm_struct's mem_cgroup changes on task migration if the
2455 * thread group leader migrates. It's possible that mm is not
2456 * set, if so charge the root memcg (happens for pagecache usage).
2458 if (!*ptr && !mm)
2459 *ptr = root_mem_cgroup;
2460 again:
2461 if (*ptr) { /* css should be a valid one */
2462 memcg = *ptr;
2463 if (mem_cgroup_is_root(memcg))
2464 goto done;
2465 if (consume_stock(memcg, nr_pages))
2466 goto done;
2467 css_get(&memcg->css);
2468 } else {
2469 struct task_struct *p;
2471 rcu_read_lock();
2472 p = rcu_dereference(mm->owner);
2474 * Because we don't have task_lock(), "p" can exit.
2475 * In that case, "memcg" can point to root or p can be NULL with
2476 * race with swapoff. Then, we have small risk of mis-accouning.
2477 * But such kind of mis-account by race always happens because
2478 * we don't have cgroup_mutex(). It's overkill and we allo that
2479 * small race, here.
2480 * (*) swapoff at el will charge against mm-struct not against
2481 * task-struct. So, mm->owner can be NULL.
2483 memcg = mem_cgroup_from_task(p);
2484 if (!memcg)
2485 memcg = root_mem_cgroup;
2486 if (mem_cgroup_is_root(memcg)) {
2487 rcu_read_unlock();
2488 goto done;
2490 if (consume_stock(memcg, nr_pages)) {
2492 * It seems dagerous to access memcg without css_get().
2493 * But considering how consume_stok works, it's not
2494 * necessary. If consume_stock success, some charges
2495 * from this memcg are cached on this cpu. So, we
2496 * don't need to call css_get()/css_tryget() before
2497 * calling consume_stock().
2499 rcu_read_unlock();
2500 goto done;
2502 /* after here, we may be blocked. we need to get refcnt */
2503 if (!css_tryget(&memcg->css)) {
2504 rcu_read_unlock();
2505 goto again;
2507 rcu_read_unlock();
2510 do {
2511 bool oom_check;
2513 /* If killed, bypass charge */
2514 if (fatal_signal_pending(current)) {
2515 css_put(&memcg->css);
2516 goto bypass;
2519 oom_check = false;
2520 if (oom && !nr_oom_retries) {
2521 oom_check = true;
2522 nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2525 ret = mem_cgroup_do_charge(memcg, gfp_mask, batch, nr_pages,
2526 oom_check);
2527 switch (ret) {
2528 case CHARGE_OK:
2529 break;
2530 case CHARGE_RETRY: /* not in OOM situation but retry */
2531 batch = nr_pages;
2532 css_put(&memcg->css);
2533 memcg = NULL;
2534 goto again;
2535 case CHARGE_WOULDBLOCK: /* !__GFP_WAIT */
2536 css_put(&memcg->css);
2537 goto nomem;
2538 case CHARGE_NOMEM: /* OOM routine works */
2539 if (!oom) {
2540 css_put(&memcg->css);
2541 goto nomem;
2543 /* If oom, we never return -ENOMEM */
2544 nr_oom_retries--;
2545 break;
2546 case CHARGE_OOM_DIE: /* Killed by OOM Killer */
2547 css_put(&memcg->css);
2548 goto bypass;
2550 } while (ret != CHARGE_OK);
2552 if (batch > nr_pages)
2553 refill_stock(memcg, batch - nr_pages);
2554 css_put(&memcg->css);
2555 done:
2556 *ptr = memcg;
2557 return 0;
2558 nomem:
2559 *ptr = NULL;
2560 return -ENOMEM;
2561 bypass:
2562 *ptr = root_mem_cgroup;
2563 return -EINTR;
2567 * Somemtimes we have to undo a charge we got by try_charge().
2568 * This function is for that and do uncharge, put css's refcnt.
2569 * gotten by try_charge().
2571 static void __mem_cgroup_cancel_charge(struct mem_cgroup *memcg,
2572 unsigned int nr_pages)
2574 if (!mem_cgroup_is_root(memcg)) {
2575 unsigned long bytes = nr_pages * PAGE_SIZE;
2577 res_counter_uncharge(&memcg->res, bytes);
2578 if (do_swap_account)
2579 res_counter_uncharge(&memcg->memsw, bytes);
2584 * Cancel chrages in this cgroup....doesn't propagate to parent cgroup.
2585 * This is useful when moving usage to parent cgroup.
2587 static void __mem_cgroup_cancel_local_charge(struct mem_cgroup *memcg,
2588 unsigned int nr_pages)
2590 unsigned long bytes = nr_pages * PAGE_SIZE;
2592 if (mem_cgroup_is_root(memcg))
2593 return;
2595 res_counter_uncharge_until(&memcg->res, memcg->res.parent, bytes);
2596 if (do_swap_account)
2597 res_counter_uncharge_until(&memcg->memsw,
2598 memcg->memsw.parent, bytes);
2602 * A helper function to get mem_cgroup from ID. must be called under
2603 * rcu_read_lock(). The caller is responsible for calling css_tryget if
2604 * the mem_cgroup is used for charging. (dropping refcnt from swap can be
2605 * called against removed memcg.)
2607 static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
2609 struct cgroup_subsys_state *css;
2611 /* ID 0 is unused ID */
2612 if (!id)
2613 return NULL;
2614 css = css_lookup(&mem_cgroup_subsys, id);
2615 if (!css)
2616 return NULL;
2617 return mem_cgroup_from_css(css);
2620 struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
2622 struct mem_cgroup *memcg = NULL;
2623 struct page_cgroup *pc;
2624 unsigned short id;
2625 swp_entry_t ent;
2627 VM_BUG_ON(!PageLocked(page));
2629 pc = lookup_page_cgroup(page);
2630 lock_page_cgroup(pc);
2631 if (PageCgroupUsed(pc)) {
2632 memcg = pc->mem_cgroup;
2633 if (memcg && !css_tryget(&memcg->css))
2634 memcg = NULL;
2635 } else if (PageSwapCache(page)) {
2636 ent.val = page_private(page);
2637 id = lookup_swap_cgroup_id(ent);
2638 rcu_read_lock();
2639 memcg = mem_cgroup_lookup(id);
2640 if (memcg && !css_tryget(&memcg->css))
2641 memcg = NULL;
2642 rcu_read_unlock();
2644 unlock_page_cgroup(pc);
2645 return memcg;
2648 static void __mem_cgroup_commit_charge(struct mem_cgroup *memcg,
2649 struct page *page,
2650 unsigned int nr_pages,
2651 enum charge_type ctype,
2652 bool lrucare)
2654 struct page_cgroup *pc = lookup_page_cgroup(page);
2655 struct zone *uninitialized_var(zone);
2656 struct lruvec *lruvec;
2657 bool was_on_lru = false;
2658 bool anon;
2660 lock_page_cgroup(pc);
2661 VM_BUG_ON(PageCgroupUsed(pc));
2663 * we don't need page_cgroup_lock about tail pages, becase they are not
2664 * accessed by any other context at this point.
2668 * In some cases, SwapCache and FUSE(splice_buf->radixtree), the page
2669 * may already be on some other mem_cgroup's LRU. Take care of it.
2671 if (lrucare) {
2672 zone = page_zone(page);
2673 spin_lock_irq(&zone->lru_lock);
2674 if (PageLRU(page)) {
2675 lruvec = mem_cgroup_zone_lruvec(zone, pc->mem_cgroup);
2676 ClearPageLRU(page);
2677 del_page_from_lru_list(page, lruvec, page_lru(page));
2678 was_on_lru = true;
2682 pc->mem_cgroup = memcg;
2684 * We access a page_cgroup asynchronously without lock_page_cgroup().
2685 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
2686 * is accessed after testing USED bit. To make pc->mem_cgroup visible
2687 * before USED bit, we need memory barrier here.
2688 * See mem_cgroup_add_lru_list(), etc.
2690 smp_wmb();
2691 SetPageCgroupUsed(pc);
2693 if (lrucare) {
2694 if (was_on_lru) {
2695 lruvec = mem_cgroup_zone_lruvec(zone, pc->mem_cgroup);
2696 VM_BUG_ON(PageLRU(page));
2697 SetPageLRU(page);
2698 add_page_to_lru_list(page, lruvec, page_lru(page));
2700 spin_unlock_irq(&zone->lru_lock);
2703 if (ctype == MEM_CGROUP_CHARGE_TYPE_ANON)
2704 anon = true;
2705 else
2706 anon = false;
2708 mem_cgroup_charge_statistics(memcg, anon, nr_pages);
2709 unlock_page_cgroup(pc);
2712 * "charge_statistics" updated event counter. Then, check it.
2713 * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
2714 * if they exceeds softlimit.
2716 memcg_check_events(memcg, page);
2719 #ifdef CONFIG_MEMCG_KMEM
2720 static inline bool memcg_can_account_kmem(struct mem_cgroup *memcg)
2722 return !mem_cgroup_disabled() && !mem_cgroup_is_root(memcg) &&
2723 (memcg->kmem_account_flags & KMEM_ACCOUNTED_MASK);
2726 static int memcg_charge_kmem(struct mem_cgroup *memcg, gfp_t gfp, u64 size)
2728 struct res_counter *fail_res;
2729 struct mem_cgroup *_memcg;
2730 int ret = 0;
2731 bool may_oom;
2733 ret = res_counter_charge(&memcg->kmem, size, &fail_res);
2734 if (ret)
2735 return ret;
2738 * Conditions under which we can wait for the oom_killer. Those are
2739 * the same conditions tested by the core page allocator
2741 may_oom = (gfp & __GFP_FS) && !(gfp & __GFP_NORETRY);
2743 _memcg = memcg;
2744 ret = __mem_cgroup_try_charge(NULL, gfp, size >> PAGE_SHIFT,
2745 &_memcg, may_oom);
2747 if (ret == -EINTR) {
2749 * __mem_cgroup_try_charge() chosed to bypass to root due to
2750 * OOM kill or fatal signal. Since our only options are to
2751 * either fail the allocation or charge it to this cgroup, do
2752 * it as a temporary condition. But we can't fail. From a
2753 * kmem/slab perspective, the cache has already been selected,
2754 * by mem_cgroup_kmem_get_cache(), so it is too late to change
2755 * our minds.
2757 * This condition will only trigger if the task entered
2758 * memcg_charge_kmem in a sane state, but was OOM-killed during
2759 * __mem_cgroup_try_charge() above. Tasks that were already
2760 * dying when the allocation triggers should have been already
2761 * directed to the root cgroup in memcontrol.h
2763 res_counter_charge_nofail(&memcg->res, size, &fail_res);
2764 if (do_swap_account)
2765 res_counter_charge_nofail(&memcg->memsw, size,
2766 &fail_res);
2767 ret = 0;
2768 } else if (ret)
2769 res_counter_uncharge(&memcg->kmem, size);
2771 return ret;
2774 static void memcg_uncharge_kmem(struct mem_cgroup *memcg, u64 size)
2776 res_counter_uncharge(&memcg->res, size);
2777 if (do_swap_account)
2778 res_counter_uncharge(&memcg->memsw, size);
2780 /* Not down to 0 */
2781 if (res_counter_uncharge(&memcg->kmem, size))
2782 return;
2784 if (memcg_kmem_test_and_clear_dead(memcg))
2785 mem_cgroup_put(memcg);
2789 * We need to verify if the allocation against current->mm->owner's memcg is
2790 * possible for the given order. But the page is not allocated yet, so we'll
2791 * need a further commit step to do the final arrangements.
2793 * It is possible for the task to switch cgroups in this mean time, so at
2794 * commit time, we can't rely on task conversion any longer. We'll then use
2795 * the handle argument to return to the caller which cgroup we should commit
2796 * against. We could also return the memcg directly and avoid the pointer
2797 * passing, but a boolean return value gives better semantics considering
2798 * the compiled-out case as well.
2800 * Returning true means the allocation is possible.
2802 bool
2803 __memcg_kmem_newpage_charge(gfp_t gfp, struct mem_cgroup **_memcg, int order)
2805 struct mem_cgroup *memcg;
2806 int ret;
2808 *_memcg = NULL;
2809 memcg = try_get_mem_cgroup_from_mm(current->mm);
2812 * very rare case described in mem_cgroup_from_task. Unfortunately there
2813 * isn't much we can do without complicating this too much, and it would
2814 * be gfp-dependent anyway. Just let it go
2816 if (unlikely(!memcg))
2817 return true;
2819 if (!memcg_can_account_kmem(memcg)) {
2820 css_put(&memcg->css);
2821 return true;
2824 ret = memcg_charge_kmem(memcg, gfp, PAGE_SIZE << order);
2825 if (!ret)
2826 *_memcg = memcg;
2828 css_put(&memcg->css);
2829 return (ret == 0);
2832 void __memcg_kmem_commit_charge(struct page *page, struct mem_cgroup *memcg,
2833 int order)
2835 struct page_cgroup *pc;
2837 VM_BUG_ON(mem_cgroup_is_root(memcg));
2839 /* The page allocation failed. Revert */
2840 if (!page) {
2841 memcg_uncharge_kmem(memcg, PAGE_SIZE << order);
2842 return;
2845 pc = lookup_page_cgroup(page);
2846 lock_page_cgroup(pc);
2847 pc->mem_cgroup = memcg;
2848 SetPageCgroupUsed(pc);
2849 unlock_page_cgroup(pc);
2852 void __memcg_kmem_uncharge_pages(struct page *page, int order)
2854 struct mem_cgroup *memcg = NULL;
2855 struct page_cgroup *pc;
2858 pc = lookup_page_cgroup(page);
2860 * Fast unlocked return. Theoretically might have changed, have to
2861 * check again after locking.
2863 if (!PageCgroupUsed(pc))
2864 return;
2866 lock_page_cgroup(pc);
2867 if (PageCgroupUsed(pc)) {
2868 memcg = pc->mem_cgroup;
2869 ClearPageCgroupUsed(pc);
2871 unlock_page_cgroup(pc);
2874 * We trust that only if there is a memcg associated with the page, it
2875 * is a valid allocation
2877 if (!memcg)
2878 return;
2880 VM_BUG_ON(mem_cgroup_is_root(memcg));
2881 memcg_uncharge_kmem(memcg, PAGE_SIZE << order);
2883 #endif /* CONFIG_MEMCG_KMEM */
2885 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
2887 #define PCGF_NOCOPY_AT_SPLIT (1 << PCG_LOCK | 1 << PCG_MIGRATION)
2889 * Because tail pages are not marked as "used", set it. We're under
2890 * zone->lru_lock, 'splitting on pmd' and compound_lock.
2891 * charge/uncharge will be never happen and move_account() is done under
2892 * compound_lock(), so we don't have to take care of races.
2894 void mem_cgroup_split_huge_fixup(struct page *head)
2896 struct page_cgroup *head_pc = lookup_page_cgroup(head);
2897 struct page_cgroup *pc;
2898 int i;
2900 if (mem_cgroup_disabled())
2901 return;
2902 for (i = 1; i < HPAGE_PMD_NR; i++) {
2903 pc = head_pc + i;
2904 pc->mem_cgroup = head_pc->mem_cgroup;
2905 smp_wmb();/* see __commit_charge() */
2906 pc->flags = head_pc->flags & ~PCGF_NOCOPY_AT_SPLIT;
2909 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
2912 * mem_cgroup_move_account - move account of the page
2913 * @page: the page
2914 * @nr_pages: number of regular pages (>1 for huge pages)
2915 * @pc: page_cgroup of the page.
2916 * @from: mem_cgroup which the page is moved from.
2917 * @to: mem_cgroup which the page is moved to. @from != @to.
2919 * The caller must confirm following.
2920 * - page is not on LRU (isolate_page() is useful.)
2921 * - compound_lock is held when nr_pages > 1
2923 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
2924 * from old cgroup.
2926 static int mem_cgroup_move_account(struct page *page,
2927 unsigned int nr_pages,
2928 struct page_cgroup *pc,
2929 struct mem_cgroup *from,
2930 struct mem_cgroup *to)
2932 unsigned long flags;
2933 int ret;
2934 bool anon = PageAnon(page);
2936 VM_BUG_ON(from == to);
2937 VM_BUG_ON(PageLRU(page));
2939 * The page is isolated from LRU. So, collapse function
2940 * will not handle this page. But page splitting can happen.
2941 * Do this check under compound_page_lock(). The caller should
2942 * hold it.
2944 ret = -EBUSY;
2945 if (nr_pages > 1 && !PageTransHuge(page))
2946 goto out;
2948 lock_page_cgroup(pc);
2950 ret = -EINVAL;
2951 if (!PageCgroupUsed(pc) || pc->mem_cgroup != from)
2952 goto unlock;
2954 move_lock_mem_cgroup(from, &flags);
2956 if (!anon && page_mapped(page)) {
2957 /* Update mapped_file data for mem_cgroup */
2958 preempt_disable();
2959 __this_cpu_dec(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
2960 __this_cpu_inc(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
2961 preempt_enable();
2963 mem_cgroup_charge_statistics(from, anon, -nr_pages);
2965 /* caller should have done css_get */
2966 pc->mem_cgroup = to;
2967 mem_cgroup_charge_statistics(to, anon, nr_pages);
2968 move_unlock_mem_cgroup(from, &flags);
2969 ret = 0;
2970 unlock:
2971 unlock_page_cgroup(pc);
2973 * check events
2975 memcg_check_events(to, page);
2976 memcg_check_events(from, page);
2977 out:
2978 return ret;
2982 * mem_cgroup_move_parent - moves page to the parent group
2983 * @page: the page to move
2984 * @pc: page_cgroup of the page
2985 * @child: page's cgroup
2987 * move charges to its parent or the root cgroup if the group has no
2988 * parent (aka use_hierarchy==0).
2989 * Although this might fail (get_page_unless_zero, isolate_lru_page or
2990 * mem_cgroup_move_account fails) the failure is always temporary and
2991 * it signals a race with a page removal/uncharge or migration. In the
2992 * first case the page is on the way out and it will vanish from the LRU
2993 * on the next attempt and the call should be retried later.
2994 * Isolation from the LRU fails only if page has been isolated from
2995 * the LRU since we looked at it and that usually means either global
2996 * reclaim or migration going on. The page will either get back to the
2997 * LRU or vanish.
2998 * Finaly mem_cgroup_move_account fails only if the page got uncharged
2999 * (!PageCgroupUsed) or moved to a different group. The page will
3000 * disappear in the next attempt.
3002 static int mem_cgroup_move_parent(struct page *page,
3003 struct page_cgroup *pc,
3004 struct mem_cgroup *child)
3006 struct mem_cgroup *parent;
3007 unsigned int nr_pages;
3008 unsigned long uninitialized_var(flags);
3009 int ret;
3011 VM_BUG_ON(mem_cgroup_is_root(child));
3013 ret = -EBUSY;
3014 if (!get_page_unless_zero(page))
3015 goto out;
3016 if (isolate_lru_page(page))
3017 goto put;
3019 nr_pages = hpage_nr_pages(page);
3021 parent = parent_mem_cgroup(child);
3023 * If no parent, move charges to root cgroup.
3025 if (!parent)
3026 parent = root_mem_cgroup;
3028 if (nr_pages > 1) {
3029 VM_BUG_ON(!PageTransHuge(page));
3030 flags = compound_lock_irqsave(page);
3033 ret = mem_cgroup_move_account(page, nr_pages,
3034 pc, child, parent);
3035 if (!ret)
3036 __mem_cgroup_cancel_local_charge(child, nr_pages);
3038 if (nr_pages > 1)
3039 compound_unlock_irqrestore(page, flags);
3040 putback_lru_page(page);
3041 put:
3042 put_page(page);
3043 out:
3044 return ret;
3048 * Charge the memory controller for page usage.
3049 * Return
3050 * 0 if the charge was successful
3051 * < 0 if the cgroup is over its limit
3053 static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
3054 gfp_t gfp_mask, enum charge_type ctype)
3056 struct mem_cgroup *memcg = NULL;
3057 unsigned int nr_pages = 1;
3058 bool oom = true;
3059 int ret;
3061 if (PageTransHuge(page)) {
3062 nr_pages <<= compound_order(page);
3063 VM_BUG_ON(!PageTransHuge(page));
3065 * Never OOM-kill a process for a huge page. The
3066 * fault handler will fall back to regular pages.
3068 oom = false;
3071 ret = __mem_cgroup_try_charge(mm, gfp_mask, nr_pages, &memcg, oom);
3072 if (ret == -ENOMEM)
3073 return ret;
3074 __mem_cgroup_commit_charge(memcg, page, nr_pages, ctype, false);
3075 return 0;
3078 int mem_cgroup_newpage_charge(struct page *page,
3079 struct mm_struct *mm, gfp_t gfp_mask)
3081 if (mem_cgroup_disabled())
3082 return 0;
3083 VM_BUG_ON(page_mapped(page));
3084 VM_BUG_ON(page->mapping && !PageAnon(page));
3085 VM_BUG_ON(!mm);
3086 return mem_cgroup_charge_common(page, mm, gfp_mask,
3087 MEM_CGROUP_CHARGE_TYPE_ANON);
3091 * While swap-in, try_charge -> commit or cancel, the page is locked.
3092 * And when try_charge() successfully returns, one refcnt to memcg without
3093 * struct page_cgroup is acquired. This refcnt will be consumed by
3094 * "commit()" or removed by "cancel()"
3096 static int __mem_cgroup_try_charge_swapin(struct mm_struct *mm,
3097 struct page *page,
3098 gfp_t mask,
3099 struct mem_cgroup **memcgp)
3101 struct mem_cgroup *memcg;
3102 struct page_cgroup *pc;
3103 int ret;
3105 pc = lookup_page_cgroup(page);
3107 * Every swap fault against a single page tries to charge the
3108 * page, bail as early as possible. shmem_unuse() encounters
3109 * already charged pages, too. The USED bit is protected by
3110 * the page lock, which serializes swap cache removal, which
3111 * in turn serializes uncharging.
3113 if (PageCgroupUsed(pc))
3114 return 0;
3115 if (!do_swap_account)
3116 goto charge_cur_mm;
3117 memcg = try_get_mem_cgroup_from_page(page);
3118 if (!memcg)
3119 goto charge_cur_mm;
3120 *memcgp = memcg;
3121 ret = __mem_cgroup_try_charge(NULL, mask, 1, memcgp, true);
3122 css_put(&memcg->css);
3123 if (ret == -EINTR)
3124 ret = 0;
3125 return ret;
3126 charge_cur_mm:
3127 ret = __mem_cgroup_try_charge(mm, mask, 1, memcgp, true);
3128 if (ret == -EINTR)
3129 ret = 0;
3130 return ret;
3133 int mem_cgroup_try_charge_swapin(struct mm_struct *mm, struct page *page,
3134 gfp_t gfp_mask, struct mem_cgroup **memcgp)
3136 *memcgp = NULL;
3137 if (mem_cgroup_disabled())
3138 return 0;
3140 * A racing thread's fault, or swapoff, may have already
3141 * updated the pte, and even removed page from swap cache: in
3142 * those cases unuse_pte()'s pte_same() test will fail; but
3143 * there's also a KSM case which does need to charge the page.
3145 if (!PageSwapCache(page)) {
3146 int ret;
3148 ret = __mem_cgroup_try_charge(mm, gfp_mask, 1, memcgp, true);
3149 if (ret == -EINTR)
3150 ret = 0;
3151 return ret;
3153 return __mem_cgroup_try_charge_swapin(mm, page, gfp_mask, memcgp);
3156 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *memcg)
3158 if (mem_cgroup_disabled())
3159 return;
3160 if (!memcg)
3161 return;
3162 __mem_cgroup_cancel_charge(memcg, 1);
3165 static void
3166 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *memcg,
3167 enum charge_type ctype)
3169 if (mem_cgroup_disabled())
3170 return;
3171 if (!memcg)
3172 return;
3174 __mem_cgroup_commit_charge(memcg, page, 1, ctype, true);
3176 * Now swap is on-memory. This means this page may be
3177 * counted both as mem and swap....double count.
3178 * Fix it by uncharging from memsw. Basically, this SwapCache is stable
3179 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
3180 * may call delete_from_swap_cache() before reach here.
3182 if (do_swap_account && PageSwapCache(page)) {
3183 swp_entry_t ent = {.val = page_private(page)};
3184 mem_cgroup_uncharge_swap(ent);
3188 void mem_cgroup_commit_charge_swapin(struct page *page,
3189 struct mem_cgroup *memcg)
3191 __mem_cgroup_commit_charge_swapin(page, memcg,
3192 MEM_CGROUP_CHARGE_TYPE_ANON);
3195 int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
3196 gfp_t gfp_mask)
3198 struct mem_cgroup *memcg = NULL;
3199 enum charge_type type = MEM_CGROUP_CHARGE_TYPE_CACHE;
3200 int ret;
3202 if (mem_cgroup_disabled())
3203 return 0;
3204 if (PageCompound(page))
3205 return 0;
3207 if (!PageSwapCache(page))
3208 ret = mem_cgroup_charge_common(page, mm, gfp_mask, type);
3209 else { /* page is swapcache/shmem */
3210 ret = __mem_cgroup_try_charge_swapin(mm, page,
3211 gfp_mask, &memcg);
3212 if (!ret)
3213 __mem_cgroup_commit_charge_swapin(page, memcg, type);
3215 return ret;
3218 static void mem_cgroup_do_uncharge(struct mem_cgroup *memcg,
3219 unsigned int nr_pages,
3220 const enum charge_type ctype)
3222 struct memcg_batch_info *batch = NULL;
3223 bool uncharge_memsw = true;
3225 /* If swapout, usage of swap doesn't decrease */
3226 if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
3227 uncharge_memsw = false;
3229 batch = &current->memcg_batch;
3231 * In usual, we do css_get() when we remember memcg pointer.
3232 * But in this case, we keep res->usage until end of a series of
3233 * uncharges. Then, it's ok to ignore memcg's refcnt.
3235 if (!batch->memcg)
3236 batch->memcg = memcg;
3238 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
3239 * In those cases, all pages freed continuously can be expected to be in
3240 * the same cgroup and we have chance to coalesce uncharges.
3241 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
3242 * because we want to do uncharge as soon as possible.
3245 if (!batch->do_batch || test_thread_flag(TIF_MEMDIE))
3246 goto direct_uncharge;
3248 if (nr_pages > 1)
3249 goto direct_uncharge;
3252 * In typical case, batch->memcg == mem. This means we can
3253 * merge a series of uncharges to an uncharge of res_counter.
3254 * If not, we uncharge res_counter ony by one.
3256 if (batch->memcg != memcg)
3257 goto direct_uncharge;
3258 /* remember freed charge and uncharge it later */
3259 batch->nr_pages++;
3260 if (uncharge_memsw)
3261 batch->memsw_nr_pages++;
3262 return;
3263 direct_uncharge:
3264 res_counter_uncharge(&memcg->res, nr_pages * PAGE_SIZE);
3265 if (uncharge_memsw)
3266 res_counter_uncharge(&memcg->memsw, nr_pages * PAGE_SIZE);
3267 if (unlikely(batch->memcg != memcg))
3268 memcg_oom_recover(memcg);
3272 * uncharge if !page_mapped(page)
3274 static struct mem_cgroup *
3275 __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype,
3276 bool end_migration)
3278 struct mem_cgroup *memcg = NULL;
3279 unsigned int nr_pages = 1;
3280 struct page_cgroup *pc;
3281 bool anon;
3283 if (mem_cgroup_disabled())
3284 return NULL;
3286 VM_BUG_ON(PageSwapCache(page));
3288 if (PageTransHuge(page)) {
3289 nr_pages <<= compound_order(page);
3290 VM_BUG_ON(!PageTransHuge(page));
3293 * Check if our page_cgroup is valid
3295 pc = lookup_page_cgroup(page);
3296 if (unlikely(!PageCgroupUsed(pc)))
3297 return NULL;
3299 lock_page_cgroup(pc);
3301 memcg = pc->mem_cgroup;
3303 if (!PageCgroupUsed(pc))
3304 goto unlock_out;
3306 anon = PageAnon(page);
3308 switch (ctype) {
3309 case MEM_CGROUP_CHARGE_TYPE_ANON:
3311 * Generally PageAnon tells if it's the anon statistics to be
3312 * updated; but sometimes e.g. mem_cgroup_uncharge_page() is
3313 * used before page reached the stage of being marked PageAnon.
3315 anon = true;
3316 /* fallthrough */
3317 case MEM_CGROUP_CHARGE_TYPE_DROP:
3318 /* See mem_cgroup_prepare_migration() */
3319 if (page_mapped(page))
3320 goto unlock_out;
3322 * Pages under migration may not be uncharged. But
3323 * end_migration() /must/ be the one uncharging the
3324 * unused post-migration page and so it has to call
3325 * here with the migration bit still set. See the
3326 * res_counter handling below.
3328 if (!end_migration && PageCgroupMigration(pc))
3329 goto unlock_out;
3330 break;
3331 case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
3332 if (!PageAnon(page)) { /* Shared memory */
3333 if (page->mapping && !page_is_file_cache(page))
3334 goto unlock_out;
3335 } else if (page_mapped(page)) /* Anon */
3336 goto unlock_out;
3337 break;
3338 default:
3339 break;
3342 mem_cgroup_charge_statistics(memcg, anon, -nr_pages);
3344 ClearPageCgroupUsed(pc);
3346 * pc->mem_cgroup is not cleared here. It will be accessed when it's
3347 * freed from LRU. This is safe because uncharged page is expected not
3348 * to be reused (freed soon). Exception is SwapCache, it's handled by
3349 * special functions.
3352 unlock_page_cgroup(pc);
3354 * even after unlock, we have memcg->res.usage here and this memcg
3355 * will never be freed.
3357 memcg_check_events(memcg, page);
3358 if (do_swap_account && ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT) {
3359 mem_cgroup_swap_statistics(memcg, true);
3360 mem_cgroup_get(memcg);
3363 * Migration does not charge the res_counter for the
3364 * replacement page, so leave it alone when phasing out the
3365 * page that is unused after the migration.
3367 if (!end_migration && !mem_cgroup_is_root(memcg))
3368 mem_cgroup_do_uncharge(memcg, nr_pages, ctype);
3370 return memcg;
3372 unlock_out:
3373 unlock_page_cgroup(pc);
3374 return NULL;
3377 void mem_cgroup_uncharge_page(struct page *page)
3379 /* early check. */
3380 if (page_mapped(page))
3381 return;
3382 VM_BUG_ON(page->mapping && !PageAnon(page));
3383 if (PageSwapCache(page))
3384 return;
3385 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_ANON, false);
3388 void mem_cgroup_uncharge_cache_page(struct page *page)
3390 VM_BUG_ON(page_mapped(page));
3391 VM_BUG_ON(page->mapping);
3392 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE, false);
3396 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
3397 * In that cases, pages are freed continuously and we can expect pages
3398 * are in the same memcg. All these calls itself limits the number of
3399 * pages freed at once, then uncharge_start/end() is called properly.
3400 * This may be called prural(2) times in a context,
3403 void mem_cgroup_uncharge_start(void)
3405 current->memcg_batch.do_batch++;
3406 /* We can do nest. */
3407 if (current->memcg_batch.do_batch == 1) {
3408 current->memcg_batch.memcg = NULL;
3409 current->memcg_batch.nr_pages = 0;
3410 current->memcg_batch.memsw_nr_pages = 0;
3414 void mem_cgroup_uncharge_end(void)
3416 struct memcg_batch_info *batch = &current->memcg_batch;
3418 if (!batch->do_batch)
3419 return;
3421 batch->do_batch--;
3422 if (batch->do_batch) /* If stacked, do nothing. */
3423 return;
3425 if (!batch->memcg)
3426 return;
3428 * This "batch->memcg" is valid without any css_get/put etc...
3429 * bacause we hide charges behind us.
3431 if (batch->nr_pages)
3432 res_counter_uncharge(&batch->memcg->res,
3433 batch->nr_pages * PAGE_SIZE);
3434 if (batch->memsw_nr_pages)
3435 res_counter_uncharge(&batch->memcg->memsw,
3436 batch->memsw_nr_pages * PAGE_SIZE);
3437 memcg_oom_recover(batch->memcg);
3438 /* forget this pointer (for sanity check) */
3439 batch->memcg = NULL;
3442 #ifdef CONFIG_SWAP
3444 * called after __delete_from_swap_cache() and drop "page" account.
3445 * memcg information is recorded to swap_cgroup of "ent"
3447 void
3448 mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
3450 struct mem_cgroup *memcg;
3451 int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
3453 if (!swapout) /* this was a swap cache but the swap is unused ! */
3454 ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
3456 memcg = __mem_cgroup_uncharge_common(page, ctype, false);
3459 * record memcg information, if swapout && memcg != NULL,
3460 * mem_cgroup_get() was called in uncharge().
3462 if (do_swap_account && swapout && memcg)
3463 swap_cgroup_record(ent, css_id(&memcg->css));
3465 #endif
3467 #ifdef CONFIG_MEMCG_SWAP
3469 * called from swap_entry_free(). remove record in swap_cgroup and
3470 * uncharge "memsw" account.
3472 void mem_cgroup_uncharge_swap(swp_entry_t ent)
3474 struct mem_cgroup *memcg;
3475 unsigned short id;
3477 if (!do_swap_account)
3478 return;
3480 id = swap_cgroup_record(ent, 0);
3481 rcu_read_lock();
3482 memcg = mem_cgroup_lookup(id);
3483 if (memcg) {
3485 * We uncharge this because swap is freed.
3486 * This memcg can be obsolete one. We avoid calling css_tryget
3488 if (!mem_cgroup_is_root(memcg))
3489 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
3490 mem_cgroup_swap_statistics(memcg, false);
3491 mem_cgroup_put(memcg);
3493 rcu_read_unlock();
3497 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3498 * @entry: swap entry to be moved
3499 * @from: mem_cgroup which the entry is moved from
3500 * @to: mem_cgroup which the entry is moved to
3502 * It succeeds only when the swap_cgroup's record for this entry is the same
3503 * as the mem_cgroup's id of @from.
3505 * Returns 0 on success, -EINVAL on failure.
3507 * The caller must have charged to @to, IOW, called res_counter_charge() about
3508 * both res and memsw, and called css_get().
3510 static int mem_cgroup_move_swap_account(swp_entry_t entry,
3511 struct mem_cgroup *from, struct mem_cgroup *to)
3513 unsigned short old_id, new_id;
3515 old_id = css_id(&from->css);
3516 new_id = css_id(&to->css);
3518 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
3519 mem_cgroup_swap_statistics(from, false);
3520 mem_cgroup_swap_statistics(to, true);
3522 * This function is only called from task migration context now.
3523 * It postpones res_counter and refcount handling till the end
3524 * of task migration(mem_cgroup_clear_mc()) for performance
3525 * improvement. But we cannot postpone mem_cgroup_get(to)
3526 * because if the process that has been moved to @to does
3527 * swap-in, the refcount of @to might be decreased to 0.
3529 mem_cgroup_get(to);
3530 return 0;
3532 return -EINVAL;
3534 #else
3535 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
3536 struct mem_cgroup *from, struct mem_cgroup *to)
3538 return -EINVAL;
3540 #endif
3543 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
3544 * page belongs to.
3546 void mem_cgroup_prepare_migration(struct page *page, struct page *newpage,
3547 struct mem_cgroup **memcgp)
3549 struct mem_cgroup *memcg = NULL;
3550 unsigned int nr_pages = 1;
3551 struct page_cgroup *pc;
3552 enum charge_type ctype;
3554 *memcgp = NULL;
3556 if (mem_cgroup_disabled())
3557 return;
3559 if (PageTransHuge(page))
3560 nr_pages <<= compound_order(page);
3562 pc = lookup_page_cgroup(page);
3563 lock_page_cgroup(pc);
3564 if (PageCgroupUsed(pc)) {
3565 memcg = pc->mem_cgroup;
3566 css_get(&memcg->css);
3568 * At migrating an anonymous page, its mapcount goes down
3569 * to 0 and uncharge() will be called. But, even if it's fully
3570 * unmapped, migration may fail and this page has to be
3571 * charged again. We set MIGRATION flag here and delay uncharge
3572 * until end_migration() is called
3574 * Corner Case Thinking
3575 * A)
3576 * When the old page was mapped as Anon and it's unmap-and-freed
3577 * while migration was ongoing.
3578 * If unmap finds the old page, uncharge() of it will be delayed
3579 * until end_migration(). If unmap finds a new page, it's
3580 * uncharged when it make mapcount to be 1->0. If unmap code
3581 * finds swap_migration_entry, the new page will not be mapped
3582 * and end_migration() will find it(mapcount==0).
3584 * B)
3585 * When the old page was mapped but migraion fails, the kernel
3586 * remaps it. A charge for it is kept by MIGRATION flag even
3587 * if mapcount goes down to 0. We can do remap successfully
3588 * without charging it again.
3590 * C)
3591 * The "old" page is under lock_page() until the end of
3592 * migration, so, the old page itself will not be swapped-out.
3593 * If the new page is swapped out before end_migraton, our
3594 * hook to usual swap-out path will catch the event.
3596 if (PageAnon(page))
3597 SetPageCgroupMigration(pc);
3599 unlock_page_cgroup(pc);
3601 * If the page is not charged at this point,
3602 * we return here.
3604 if (!memcg)
3605 return;
3607 *memcgp = memcg;
3609 * We charge new page before it's used/mapped. So, even if unlock_page()
3610 * is called before end_migration, we can catch all events on this new
3611 * page. In the case new page is migrated but not remapped, new page's
3612 * mapcount will be finally 0 and we call uncharge in end_migration().
3614 if (PageAnon(page))
3615 ctype = MEM_CGROUP_CHARGE_TYPE_ANON;
3616 else
3617 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
3619 * The page is committed to the memcg, but it's not actually
3620 * charged to the res_counter since we plan on replacing the
3621 * old one and only one page is going to be left afterwards.
3623 __mem_cgroup_commit_charge(memcg, newpage, nr_pages, ctype, false);
3626 /* remove redundant charge if migration failed*/
3627 void mem_cgroup_end_migration(struct mem_cgroup *memcg,
3628 struct page *oldpage, struct page *newpage, bool migration_ok)
3630 struct page *used, *unused;
3631 struct page_cgroup *pc;
3632 bool anon;
3634 if (!memcg)
3635 return;
3637 if (!migration_ok) {
3638 used = oldpage;
3639 unused = newpage;
3640 } else {
3641 used = newpage;
3642 unused = oldpage;
3644 anon = PageAnon(used);
3645 __mem_cgroup_uncharge_common(unused,
3646 anon ? MEM_CGROUP_CHARGE_TYPE_ANON
3647 : MEM_CGROUP_CHARGE_TYPE_CACHE,
3648 true);
3649 css_put(&memcg->css);
3651 * We disallowed uncharge of pages under migration because mapcount
3652 * of the page goes down to zero, temporarly.
3653 * Clear the flag and check the page should be charged.
3655 pc = lookup_page_cgroup(oldpage);
3656 lock_page_cgroup(pc);
3657 ClearPageCgroupMigration(pc);
3658 unlock_page_cgroup(pc);
3661 * If a page is a file cache, radix-tree replacement is very atomic
3662 * and we can skip this check. When it was an Anon page, its mapcount
3663 * goes down to 0. But because we added MIGRATION flage, it's not
3664 * uncharged yet. There are several case but page->mapcount check
3665 * and USED bit check in mem_cgroup_uncharge_page() will do enough
3666 * check. (see prepare_charge() also)
3668 if (anon)
3669 mem_cgroup_uncharge_page(used);
3673 * At replace page cache, newpage is not under any memcg but it's on
3674 * LRU. So, this function doesn't touch res_counter but handles LRU
3675 * in correct way. Both pages are locked so we cannot race with uncharge.
3677 void mem_cgroup_replace_page_cache(struct page *oldpage,
3678 struct page *newpage)
3680 struct mem_cgroup *memcg = NULL;
3681 struct page_cgroup *pc;
3682 enum charge_type type = MEM_CGROUP_CHARGE_TYPE_CACHE;
3684 if (mem_cgroup_disabled())
3685 return;
3687 pc = lookup_page_cgroup(oldpage);
3688 /* fix accounting on old pages */
3689 lock_page_cgroup(pc);
3690 if (PageCgroupUsed(pc)) {
3691 memcg = pc->mem_cgroup;
3692 mem_cgroup_charge_statistics(memcg, false, -1);
3693 ClearPageCgroupUsed(pc);
3695 unlock_page_cgroup(pc);
3698 * When called from shmem_replace_page(), in some cases the
3699 * oldpage has already been charged, and in some cases not.
3701 if (!memcg)
3702 return;
3704 * Even if newpage->mapping was NULL before starting replacement,
3705 * the newpage may be on LRU(or pagevec for LRU) already. We lock
3706 * LRU while we overwrite pc->mem_cgroup.
3708 __mem_cgroup_commit_charge(memcg, newpage, 1, type, true);
3711 #ifdef CONFIG_DEBUG_VM
3712 static struct page_cgroup *lookup_page_cgroup_used(struct page *page)
3714 struct page_cgroup *pc;
3716 pc = lookup_page_cgroup(page);
3718 * Can be NULL while feeding pages into the page allocator for
3719 * the first time, i.e. during boot or memory hotplug;
3720 * or when mem_cgroup_disabled().
3722 if (likely(pc) && PageCgroupUsed(pc))
3723 return pc;
3724 return NULL;
3727 bool mem_cgroup_bad_page_check(struct page *page)
3729 if (mem_cgroup_disabled())
3730 return false;
3732 return lookup_page_cgroup_used(page) != NULL;
3735 void mem_cgroup_print_bad_page(struct page *page)
3737 struct page_cgroup *pc;
3739 pc = lookup_page_cgroup_used(page);
3740 if (pc) {
3741 printk(KERN_ALERT "pc:%p pc->flags:%lx pc->mem_cgroup:%p\n",
3742 pc, pc->flags, pc->mem_cgroup);
3745 #endif
3747 static DEFINE_MUTEX(set_limit_mutex);
3749 static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
3750 unsigned long long val)
3752 int retry_count;
3753 u64 memswlimit, memlimit;
3754 int ret = 0;
3755 int children = mem_cgroup_count_children(memcg);
3756 u64 curusage, oldusage;
3757 int enlarge;
3760 * For keeping hierarchical_reclaim simple, how long we should retry
3761 * is depends on callers. We set our retry-count to be function
3762 * of # of children which we should visit in this loop.
3764 retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
3766 oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
3768 enlarge = 0;
3769 while (retry_count) {
3770 if (signal_pending(current)) {
3771 ret = -EINTR;
3772 break;
3775 * Rather than hide all in some function, I do this in
3776 * open coded manner. You see what this really does.
3777 * We have to guarantee memcg->res.limit <= memcg->memsw.limit.
3779 mutex_lock(&set_limit_mutex);
3780 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3781 if (memswlimit < val) {
3782 ret = -EINVAL;
3783 mutex_unlock(&set_limit_mutex);
3784 break;
3787 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3788 if (memlimit < val)
3789 enlarge = 1;
3791 ret = res_counter_set_limit(&memcg->res, val);
3792 if (!ret) {
3793 if (memswlimit == val)
3794 memcg->memsw_is_minimum = true;
3795 else
3796 memcg->memsw_is_minimum = false;
3798 mutex_unlock(&set_limit_mutex);
3800 if (!ret)
3801 break;
3803 mem_cgroup_reclaim(memcg, GFP_KERNEL,
3804 MEM_CGROUP_RECLAIM_SHRINK);
3805 curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
3806 /* Usage is reduced ? */
3807 if (curusage >= oldusage)
3808 retry_count--;
3809 else
3810 oldusage = curusage;
3812 if (!ret && enlarge)
3813 memcg_oom_recover(memcg);
3815 return ret;
3818 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
3819 unsigned long long val)
3821 int retry_count;
3822 u64 memlimit, memswlimit, oldusage, curusage;
3823 int children = mem_cgroup_count_children(memcg);
3824 int ret = -EBUSY;
3825 int enlarge = 0;
3827 /* see mem_cgroup_resize_res_limit */
3828 retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
3829 oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
3830 while (retry_count) {
3831 if (signal_pending(current)) {
3832 ret = -EINTR;
3833 break;
3836 * Rather than hide all in some function, I do this in
3837 * open coded manner. You see what this really does.
3838 * We have to guarantee memcg->res.limit <= memcg->memsw.limit.
3840 mutex_lock(&set_limit_mutex);
3841 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3842 if (memlimit > val) {
3843 ret = -EINVAL;
3844 mutex_unlock(&set_limit_mutex);
3845 break;
3847 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3848 if (memswlimit < val)
3849 enlarge = 1;
3850 ret = res_counter_set_limit(&memcg->memsw, val);
3851 if (!ret) {
3852 if (memlimit == val)
3853 memcg->memsw_is_minimum = true;
3854 else
3855 memcg->memsw_is_minimum = false;
3857 mutex_unlock(&set_limit_mutex);
3859 if (!ret)
3860 break;
3862 mem_cgroup_reclaim(memcg, GFP_KERNEL,
3863 MEM_CGROUP_RECLAIM_NOSWAP |
3864 MEM_CGROUP_RECLAIM_SHRINK);
3865 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
3866 /* Usage is reduced ? */
3867 if (curusage >= oldusage)
3868 retry_count--;
3869 else
3870 oldusage = curusage;
3872 if (!ret && enlarge)
3873 memcg_oom_recover(memcg);
3874 return ret;
3877 unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
3878 gfp_t gfp_mask,
3879 unsigned long *total_scanned)
3881 unsigned long nr_reclaimed = 0;
3882 struct mem_cgroup_per_zone *mz, *next_mz = NULL;
3883 unsigned long reclaimed;
3884 int loop = 0;
3885 struct mem_cgroup_tree_per_zone *mctz;
3886 unsigned long long excess;
3887 unsigned long nr_scanned;
3889 if (order > 0)
3890 return 0;
3892 mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone));
3894 * This loop can run a while, specially if mem_cgroup's continuously
3895 * keep exceeding their soft limit and putting the system under
3896 * pressure
3898 do {
3899 if (next_mz)
3900 mz = next_mz;
3901 else
3902 mz = mem_cgroup_largest_soft_limit_node(mctz);
3903 if (!mz)
3904 break;
3906 nr_scanned = 0;
3907 reclaimed = mem_cgroup_soft_reclaim(mz->memcg, zone,
3908 gfp_mask, &nr_scanned);
3909 nr_reclaimed += reclaimed;
3910 *total_scanned += nr_scanned;
3911 spin_lock(&mctz->lock);
3914 * If we failed to reclaim anything from this memory cgroup
3915 * it is time to move on to the next cgroup
3917 next_mz = NULL;
3918 if (!reclaimed) {
3919 do {
3921 * Loop until we find yet another one.
3923 * By the time we get the soft_limit lock
3924 * again, someone might have aded the
3925 * group back on the RB tree. Iterate to
3926 * make sure we get a different mem.
3927 * mem_cgroup_largest_soft_limit_node returns
3928 * NULL if no other cgroup is present on
3929 * the tree
3931 next_mz =
3932 __mem_cgroup_largest_soft_limit_node(mctz);
3933 if (next_mz == mz)
3934 css_put(&next_mz->memcg->css);
3935 else /* next_mz == NULL or other memcg */
3936 break;
3937 } while (1);
3939 __mem_cgroup_remove_exceeded(mz->memcg, mz, mctz);
3940 excess = res_counter_soft_limit_excess(&mz->memcg->res);
3942 * One school of thought says that we should not add
3943 * back the node to the tree if reclaim returns 0.
3944 * But our reclaim could return 0, simply because due
3945 * to priority we are exposing a smaller subset of
3946 * memory to reclaim from. Consider this as a longer
3947 * term TODO.
3949 /* If excess == 0, no tree ops */
3950 __mem_cgroup_insert_exceeded(mz->memcg, mz, mctz, excess);
3951 spin_unlock(&mctz->lock);
3952 css_put(&mz->memcg->css);
3953 loop++;
3955 * Could not reclaim anything and there are no more
3956 * mem cgroups to try or we seem to be looping without
3957 * reclaiming anything.
3959 if (!nr_reclaimed &&
3960 (next_mz == NULL ||
3961 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3962 break;
3963 } while (!nr_reclaimed);
3964 if (next_mz)
3965 css_put(&next_mz->memcg->css);
3966 return nr_reclaimed;
3970 * mem_cgroup_force_empty_list - clears LRU of a group
3971 * @memcg: group to clear
3972 * @node: NUMA node
3973 * @zid: zone id
3974 * @lru: lru to to clear
3976 * Traverse a specified page_cgroup list and try to drop them all. This doesn't
3977 * reclaim the pages page themselves - pages are moved to the parent (or root)
3978 * group.
3980 static void mem_cgroup_force_empty_list(struct mem_cgroup *memcg,
3981 int node, int zid, enum lru_list lru)
3983 struct lruvec *lruvec;
3984 unsigned long flags;
3985 struct list_head *list;
3986 struct page *busy;
3987 struct zone *zone;
3989 zone = &NODE_DATA(node)->node_zones[zid];
3990 lruvec = mem_cgroup_zone_lruvec(zone, memcg);
3991 list = &lruvec->lists[lru];
3993 busy = NULL;
3994 do {
3995 struct page_cgroup *pc;
3996 struct page *page;
3998 spin_lock_irqsave(&zone->lru_lock, flags);
3999 if (list_empty(list)) {
4000 spin_unlock_irqrestore(&zone->lru_lock, flags);
4001 break;
4003 page = list_entry(list->prev, struct page, lru);
4004 if (busy == page) {
4005 list_move(&page->lru, list);
4006 busy = NULL;
4007 spin_unlock_irqrestore(&zone->lru_lock, flags);
4008 continue;
4010 spin_unlock_irqrestore(&zone->lru_lock, flags);
4012 pc = lookup_page_cgroup(page);
4014 if (mem_cgroup_move_parent(page, pc, memcg)) {
4015 /* found lock contention or "pc" is obsolete. */
4016 busy = page;
4017 cond_resched();
4018 } else
4019 busy = NULL;
4020 } while (!list_empty(list));
4024 * make mem_cgroup's charge to be 0 if there is no task by moving
4025 * all the charges and pages to the parent.
4026 * This enables deleting this mem_cgroup.
4028 * Caller is responsible for holding css reference on the memcg.
4030 static void mem_cgroup_reparent_charges(struct mem_cgroup *memcg)
4032 int node, zid;
4033 u64 usage;
4035 do {
4036 /* This is for making all *used* pages to be on LRU. */
4037 lru_add_drain_all();
4038 drain_all_stock_sync(memcg);
4039 mem_cgroup_start_move(memcg);
4040 for_each_node_state(node, N_MEMORY) {
4041 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
4042 enum lru_list lru;
4043 for_each_lru(lru) {
4044 mem_cgroup_force_empty_list(memcg,
4045 node, zid, lru);
4049 mem_cgroup_end_move(memcg);
4050 memcg_oom_recover(memcg);
4051 cond_resched();
4054 * Kernel memory may not necessarily be trackable to a specific
4055 * process. So they are not migrated, and therefore we can't
4056 * expect their value to drop to 0 here.
4057 * Having res filled up with kmem only is enough.
4059 * This is a safety check because mem_cgroup_force_empty_list
4060 * could have raced with mem_cgroup_replace_page_cache callers
4061 * so the lru seemed empty but the page could have been added
4062 * right after the check. RES_USAGE should be safe as we always
4063 * charge before adding to the LRU.
4065 usage = res_counter_read_u64(&memcg->res, RES_USAGE) -
4066 res_counter_read_u64(&memcg->kmem, RES_USAGE);
4067 } while (usage > 0);
4071 * Reclaims as many pages from the given memcg as possible and moves
4072 * the rest to the parent.
4074 * Caller is responsible for holding css reference for memcg.
4076 static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
4078 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
4079 struct cgroup *cgrp = memcg->css.cgroup;
4081 /* returns EBUSY if there is a task or if we come here twice. */
4082 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
4083 return -EBUSY;
4085 /* we call try-to-free pages for make this cgroup empty */
4086 lru_add_drain_all();
4087 /* try to free all pages in this cgroup */
4088 while (nr_retries && res_counter_read_u64(&memcg->res, RES_USAGE) > 0) {
4089 int progress;
4091 if (signal_pending(current))
4092 return -EINTR;
4094 progress = try_to_free_mem_cgroup_pages(memcg, GFP_KERNEL,
4095 false);
4096 if (!progress) {
4097 nr_retries--;
4098 /* maybe some writeback is necessary */
4099 congestion_wait(BLK_RW_ASYNC, HZ/10);
4103 lru_add_drain();
4104 mem_cgroup_reparent_charges(memcg);
4106 return 0;
4109 static int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
4111 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
4112 int ret;
4114 if (mem_cgroup_is_root(memcg))
4115 return -EINVAL;
4116 css_get(&memcg->css);
4117 ret = mem_cgroup_force_empty(memcg);
4118 css_put(&memcg->css);
4120 return ret;
4124 static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
4126 return mem_cgroup_from_cont(cont)->use_hierarchy;
4129 static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
4130 u64 val)
4132 int retval = 0;
4133 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
4134 struct cgroup *parent = cont->parent;
4135 struct mem_cgroup *parent_memcg = NULL;
4137 if (parent)
4138 parent_memcg = mem_cgroup_from_cont(parent);
4140 cgroup_lock();
4142 if (memcg->use_hierarchy == val)
4143 goto out;
4146 * If parent's use_hierarchy is set, we can't make any modifications
4147 * in the child subtrees. If it is unset, then the change can
4148 * occur, provided the current cgroup has no children.
4150 * For the root cgroup, parent_mem is NULL, we allow value to be
4151 * set if there are no children.
4153 if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
4154 (val == 1 || val == 0)) {
4155 if (list_empty(&cont->children))
4156 memcg->use_hierarchy = val;
4157 else
4158 retval = -EBUSY;
4159 } else
4160 retval = -EINVAL;
4162 out:
4163 cgroup_unlock();
4165 return retval;
4169 static unsigned long mem_cgroup_recursive_stat(struct mem_cgroup *memcg,
4170 enum mem_cgroup_stat_index idx)
4172 struct mem_cgroup *iter;
4173 long val = 0;
4175 /* Per-cpu values can be negative, use a signed accumulator */
4176 for_each_mem_cgroup_tree(iter, memcg)
4177 val += mem_cgroup_read_stat(iter, idx);
4179 if (val < 0) /* race ? */
4180 val = 0;
4181 return val;
4184 static inline u64 mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
4186 u64 val;
4188 if (!mem_cgroup_is_root(memcg)) {
4189 if (!swap)
4190 return res_counter_read_u64(&memcg->res, RES_USAGE);
4191 else
4192 return res_counter_read_u64(&memcg->memsw, RES_USAGE);
4195 val = mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_CACHE);
4196 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_RSS);
4198 if (swap)
4199 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_SWAP);
4201 return val << PAGE_SHIFT;
4204 static ssize_t mem_cgroup_read(struct cgroup *cont, struct cftype *cft,
4205 struct file *file, char __user *buf,
4206 size_t nbytes, loff_t *ppos)
4208 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
4209 char str[64];
4210 u64 val;
4211 int name, len;
4212 enum res_type type;
4214 type = MEMFILE_TYPE(cft->private);
4215 name = MEMFILE_ATTR(cft->private);
4217 if (!do_swap_account && type == _MEMSWAP)
4218 return -EOPNOTSUPP;
4220 switch (type) {
4221 case _MEM:
4222 if (name == RES_USAGE)
4223 val = mem_cgroup_usage(memcg, false);
4224 else
4225 val = res_counter_read_u64(&memcg->res, name);
4226 break;
4227 case _MEMSWAP:
4228 if (name == RES_USAGE)
4229 val = mem_cgroup_usage(memcg, true);
4230 else
4231 val = res_counter_read_u64(&memcg->memsw, name);
4232 break;
4233 case _KMEM:
4234 val = res_counter_read_u64(&memcg->kmem, name);
4235 break;
4236 default:
4237 BUG();
4240 len = scnprintf(str, sizeof(str), "%llu\n", (unsigned long long)val);
4241 return simple_read_from_buffer(buf, nbytes, ppos, str, len);
4244 static int memcg_update_kmem_limit(struct cgroup *cont, u64 val)
4246 int ret = -EINVAL;
4247 #ifdef CONFIG_MEMCG_KMEM
4248 bool must_inc_static_branch = false;
4250 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
4252 * For simplicity, we won't allow this to be disabled. It also can't
4253 * be changed if the cgroup has children already, or if tasks had
4254 * already joined.
4256 * If tasks join before we set the limit, a person looking at
4257 * kmem.usage_in_bytes will have no way to determine when it took
4258 * place, which makes the value quite meaningless.
4260 * After it first became limited, changes in the value of the limit are
4261 * of course permitted.
4263 * Taking the cgroup_lock is really offensive, but it is so far the only
4264 * way to guarantee that no children will appear. There are plenty of
4265 * other offenders, and they should all go away. Fine grained locking
4266 * is probably the way to go here. When we are fully hierarchical, we
4267 * can also get rid of the use_hierarchy check.
4269 cgroup_lock();
4270 mutex_lock(&set_limit_mutex);
4271 if (!memcg->kmem_account_flags && val != RESOURCE_MAX) {
4272 if (cgroup_task_count(cont) || (memcg->use_hierarchy &&
4273 !list_empty(&cont->children))) {
4274 ret = -EBUSY;
4275 goto out;
4277 ret = res_counter_set_limit(&memcg->kmem, val);
4278 VM_BUG_ON(ret);
4281 * After this point, kmem_accounted (that we test atomically in
4282 * the beginning of this conditional), is no longer 0. This
4283 * guarantees only one process will set the following boolean
4284 * to true. We don't need test_and_set because we're protected
4285 * by the set_limit_mutex anyway.
4287 memcg_kmem_set_activated(memcg);
4288 must_inc_static_branch = true;
4290 * kmem charges can outlive the cgroup. In the case of slab
4291 * pages, for instance, a page contain objects from various
4292 * processes, so it is unfeasible to migrate them away. We
4293 * need to reference count the memcg because of that.
4295 mem_cgroup_get(memcg);
4296 } else
4297 ret = res_counter_set_limit(&memcg->kmem, val);
4298 out:
4299 mutex_unlock(&set_limit_mutex);
4300 cgroup_unlock();
4303 * We are by now familiar with the fact that we can't inc the static
4304 * branch inside cgroup_lock. See disarm functions for details. A
4305 * worker here is overkill, but also wrong: After the limit is set, we
4306 * must start accounting right away. Since this operation can't fail,
4307 * we can safely defer it to here - no rollback will be needed.
4309 * The boolean used to control this is also safe, because
4310 * KMEM_ACCOUNTED_ACTIVATED guarantees that only one process will be
4311 * able to set it to true;
4313 if (must_inc_static_branch) {
4314 static_key_slow_inc(&memcg_kmem_enabled_key);
4316 * setting the active bit after the inc will guarantee no one
4317 * starts accounting before all call sites are patched
4319 memcg_kmem_set_active(memcg);
4322 #endif
4323 return ret;
4326 static void memcg_propagate_kmem(struct mem_cgroup *memcg)
4328 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
4329 if (!parent)
4330 return;
4331 memcg->kmem_account_flags = parent->kmem_account_flags;
4332 #ifdef CONFIG_MEMCG_KMEM
4334 * When that happen, we need to disable the static branch only on those
4335 * memcgs that enabled it. To achieve this, we would be forced to
4336 * complicate the code by keeping track of which memcgs were the ones
4337 * that actually enabled limits, and which ones got it from its
4338 * parents.
4340 * It is a lot simpler just to do static_key_slow_inc() on every child
4341 * that is accounted.
4343 if (memcg_kmem_is_active(memcg)) {
4344 mem_cgroup_get(memcg);
4345 static_key_slow_inc(&memcg_kmem_enabled_key);
4347 #endif
4351 * The user of this function is...
4352 * RES_LIMIT.
4354 static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
4355 const char *buffer)
4357 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
4358 enum res_type type;
4359 int name;
4360 unsigned long long val;
4361 int ret;
4363 type = MEMFILE_TYPE(cft->private);
4364 name = MEMFILE_ATTR(cft->private);
4366 if (!do_swap_account && type == _MEMSWAP)
4367 return -EOPNOTSUPP;
4369 switch (name) {
4370 case RES_LIMIT:
4371 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
4372 ret = -EINVAL;
4373 break;
4375 /* This function does all necessary parse...reuse it */
4376 ret = res_counter_memparse_write_strategy(buffer, &val);
4377 if (ret)
4378 break;
4379 if (type == _MEM)
4380 ret = mem_cgroup_resize_limit(memcg, val);
4381 else if (type == _MEMSWAP)
4382 ret = mem_cgroup_resize_memsw_limit(memcg, val);
4383 else if (type == _KMEM)
4384 ret = memcg_update_kmem_limit(cont, val);
4385 else
4386 return -EINVAL;
4387 break;
4388 case RES_SOFT_LIMIT:
4389 ret = res_counter_memparse_write_strategy(buffer, &val);
4390 if (ret)
4391 break;
4393 * For memsw, soft limits are hard to implement in terms
4394 * of semantics, for now, we support soft limits for
4395 * control without swap
4397 if (type == _MEM)
4398 ret = res_counter_set_soft_limit(&memcg->res, val);
4399 else
4400 ret = -EINVAL;
4401 break;
4402 default:
4403 ret = -EINVAL; /* should be BUG() ? */
4404 break;
4406 return ret;
4409 static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
4410 unsigned long long *mem_limit, unsigned long long *memsw_limit)
4412 struct cgroup *cgroup;
4413 unsigned long long min_limit, min_memsw_limit, tmp;
4415 min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
4416 min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
4417 cgroup = memcg->css.cgroup;
4418 if (!memcg->use_hierarchy)
4419 goto out;
4421 while (cgroup->parent) {
4422 cgroup = cgroup->parent;
4423 memcg = mem_cgroup_from_cont(cgroup);
4424 if (!memcg->use_hierarchy)
4425 break;
4426 tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
4427 min_limit = min(min_limit, tmp);
4428 tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
4429 min_memsw_limit = min(min_memsw_limit, tmp);
4431 out:
4432 *mem_limit = min_limit;
4433 *memsw_limit = min_memsw_limit;
4436 static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
4438 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
4439 int name;
4440 enum res_type type;
4442 type = MEMFILE_TYPE(event);
4443 name = MEMFILE_ATTR(event);
4445 if (!do_swap_account && type == _MEMSWAP)
4446 return -EOPNOTSUPP;
4448 switch (name) {
4449 case RES_MAX_USAGE:
4450 if (type == _MEM)
4451 res_counter_reset_max(&memcg->res);
4452 else if (type == _MEMSWAP)
4453 res_counter_reset_max(&memcg->memsw);
4454 else if (type == _KMEM)
4455 res_counter_reset_max(&memcg->kmem);
4456 else
4457 return -EINVAL;
4458 break;
4459 case RES_FAILCNT:
4460 if (type == _MEM)
4461 res_counter_reset_failcnt(&memcg->res);
4462 else if (type == _MEMSWAP)
4463 res_counter_reset_failcnt(&memcg->memsw);
4464 else if (type == _KMEM)
4465 res_counter_reset_failcnt(&memcg->kmem);
4466 else
4467 return -EINVAL;
4468 break;
4471 return 0;
4474 static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp,
4475 struct cftype *cft)
4477 return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate;
4480 #ifdef CONFIG_MMU
4481 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
4482 struct cftype *cft, u64 val)
4484 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4486 if (val >= (1 << NR_MOVE_TYPE))
4487 return -EINVAL;
4489 * We check this value several times in both in can_attach() and
4490 * attach(), so we need cgroup lock to prevent this value from being
4491 * inconsistent.
4493 cgroup_lock();
4494 memcg->move_charge_at_immigrate = val;
4495 cgroup_unlock();
4497 return 0;
4499 #else
4500 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
4501 struct cftype *cft, u64 val)
4503 return -ENOSYS;
4505 #endif
4507 #ifdef CONFIG_NUMA
4508 static int memcg_numa_stat_show(struct cgroup *cont, struct cftype *cft,
4509 struct seq_file *m)
4511 int nid;
4512 unsigned long total_nr, file_nr, anon_nr, unevictable_nr;
4513 unsigned long node_nr;
4514 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
4516 total_nr = mem_cgroup_nr_lru_pages(memcg, LRU_ALL);
4517 seq_printf(m, "total=%lu", total_nr);
4518 for_each_node_state(nid, N_MEMORY) {
4519 node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL);
4520 seq_printf(m, " N%d=%lu", nid, node_nr);
4522 seq_putc(m, '\n');
4524 file_nr = mem_cgroup_nr_lru_pages(memcg, LRU_ALL_FILE);
4525 seq_printf(m, "file=%lu", file_nr);
4526 for_each_node_state(nid, N_MEMORY) {
4527 node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
4528 LRU_ALL_FILE);
4529 seq_printf(m, " N%d=%lu", nid, node_nr);
4531 seq_putc(m, '\n');
4533 anon_nr = mem_cgroup_nr_lru_pages(memcg, LRU_ALL_ANON);
4534 seq_printf(m, "anon=%lu", anon_nr);
4535 for_each_node_state(nid, N_MEMORY) {
4536 node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
4537 LRU_ALL_ANON);
4538 seq_printf(m, " N%d=%lu", nid, node_nr);
4540 seq_putc(m, '\n');
4542 unevictable_nr = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_UNEVICTABLE));
4543 seq_printf(m, "unevictable=%lu", unevictable_nr);
4544 for_each_node_state(nid, N_MEMORY) {
4545 node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
4546 BIT(LRU_UNEVICTABLE));
4547 seq_printf(m, " N%d=%lu", nid, node_nr);
4549 seq_putc(m, '\n');
4550 return 0;
4552 #endif /* CONFIG_NUMA */
4554 static const char * const mem_cgroup_lru_names[] = {
4555 "inactive_anon",
4556 "active_anon",
4557 "inactive_file",
4558 "active_file",
4559 "unevictable",
4562 static inline void mem_cgroup_lru_names_not_uptodate(void)
4564 BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_lru_names) != NR_LRU_LISTS);
4567 static int memcg_stat_show(struct cgroup *cont, struct cftype *cft,
4568 struct seq_file *m)
4570 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
4571 struct mem_cgroup *mi;
4572 unsigned int i;
4574 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
4575 if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
4576 continue;
4577 seq_printf(m, "%s %ld\n", mem_cgroup_stat_names[i],
4578 mem_cgroup_read_stat(memcg, i) * PAGE_SIZE);
4581 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++)
4582 seq_printf(m, "%s %lu\n", mem_cgroup_events_names[i],
4583 mem_cgroup_read_events(memcg, i));
4585 for (i = 0; i < NR_LRU_LISTS; i++)
4586 seq_printf(m, "%s %lu\n", mem_cgroup_lru_names[i],
4587 mem_cgroup_nr_lru_pages(memcg, BIT(i)) * PAGE_SIZE);
4589 /* Hierarchical information */
4591 unsigned long long limit, memsw_limit;
4592 memcg_get_hierarchical_limit(memcg, &limit, &memsw_limit);
4593 seq_printf(m, "hierarchical_memory_limit %llu\n", limit);
4594 if (do_swap_account)
4595 seq_printf(m, "hierarchical_memsw_limit %llu\n",
4596 memsw_limit);
4599 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
4600 long long val = 0;
4602 if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
4603 continue;
4604 for_each_mem_cgroup_tree(mi, memcg)
4605 val += mem_cgroup_read_stat(mi, i) * PAGE_SIZE;
4606 seq_printf(m, "total_%s %lld\n", mem_cgroup_stat_names[i], val);
4609 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
4610 unsigned long long val = 0;
4612 for_each_mem_cgroup_tree(mi, memcg)
4613 val += mem_cgroup_read_events(mi, i);
4614 seq_printf(m, "total_%s %llu\n",
4615 mem_cgroup_events_names[i], val);
4618 for (i = 0; i < NR_LRU_LISTS; i++) {
4619 unsigned long long val = 0;
4621 for_each_mem_cgroup_tree(mi, memcg)
4622 val += mem_cgroup_nr_lru_pages(mi, BIT(i)) * PAGE_SIZE;
4623 seq_printf(m, "total_%s %llu\n", mem_cgroup_lru_names[i], val);
4626 #ifdef CONFIG_DEBUG_VM
4628 int nid, zid;
4629 struct mem_cgroup_per_zone *mz;
4630 struct zone_reclaim_stat *rstat;
4631 unsigned long recent_rotated[2] = {0, 0};
4632 unsigned long recent_scanned[2] = {0, 0};
4634 for_each_online_node(nid)
4635 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
4636 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
4637 rstat = &mz->lruvec.reclaim_stat;
4639 recent_rotated[0] += rstat->recent_rotated[0];
4640 recent_rotated[1] += rstat->recent_rotated[1];
4641 recent_scanned[0] += rstat->recent_scanned[0];
4642 recent_scanned[1] += rstat->recent_scanned[1];
4644 seq_printf(m, "recent_rotated_anon %lu\n", recent_rotated[0]);
4645 seq_printf(m, "recent_rotated_file %lu\n", recent_rotated[1]);
4646 seq_printf(m, "recent_scanned_anon %lu\n", recent_scanned[0]);
4647 seq_printf(m, "recent_scanned_file %lu\n", recent_scanned[1]);
4649 #endif
4651 return 0;
4654 static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
4656 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4658 return mem_cgroup_swappiness(memcg);
4661 static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
4662 u64 val)
4664 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4665 struct mem_cgroup *parent;
4667 if (val > 100)
4668 return -EINVAL;
4670 if (cgrp->parent == NULL)
4671 return -EINVAL;
4673 parent = mem_cgroup_from_cont(cgrp->parent);
4675 cgroup_lock();
4677 /* If under hierarchy, only empty-root can set this value */
4678 if ((parent->use_hierarchy) ||
4679 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
4680 cgroup_unlock();
4681 return -EINVAL;
4684 memcg->swappiness = val;
4686 cgroup_unlock();
4688 return 0;
4691 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4693 struct mem_cgroup_threshold_ary *t;
4694 u64 usage;
4695 int i;
4697 rcu_read_lock();
4698 if (!swap)
4699 t = rcu_dereference(memcg->thresholds.primary);
4700 else
4701 t = rcu_dereference(memcg->memsw_thresholds.primary);
4703 if (!t)
4704 goto unlock;
4706 usage = mem_cgroup_usage(memcg, swap);
4709 * current_threshold points to threshold just below or equal to usage.
4710 * If it's not true, a threshold was crossed after last
4711 * call of __mem_cgroup_threshold().
4713 i = t->current_threshold;
4716 * Iterate backward over array of thresholds starting from
4717 * current_threshold and check if a threshold is crossed.
4718 * If none of thresholds below usage is crossed, we read
4719 * only one element of the array here.
4721 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4722 eventfd_signal(t->entries[i].eventfd, 1);
4724 /* i = current_threshold + 1 */
4725 i++;
4728 * Iterate forward over array of thresholds starting from
4729 * current_threshold+1 and check if a threshold is crossed.
4730 * If none of thresholds above usage is crossed, we read
4731 * only one element of the array here.
4733 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4734 eventfd_signal(t->entries[i].eventfd, 1);
4736 /* Update current_threshold */
4737 t->current_threshold = i - 1;
4738 unlock:
4739 rcu_read_unlock();
4742 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4744 while (memcg) {
4745 __mem_cgroup_threshold(memcg, false);
4746 if (do_swap_account)
4747 __mem_cgroup_threshold(memcg, true);
4749 memcg = parent_mem_cgroup(memcg);
4753 static int compare_thresholds(const void *a, const void *b)
4755 const struct mem_cgroup_threshold *_a = a;
4756 const struct mem_cgroup_threshold *_b = b;
4758 return _a->threshold - _b->threshold;
4761 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
4763 struct mem_cgroup_eventfd_list *ev;
4765 list_for_each_entry(ev, &memcg->oom_notify, list)
4766 eventfd_signal(ev->eventfd, 1);
4767 return 0;
4770 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
4772 struct mem_cgroup *iter;
4774 for_each_mem_cgroup_tree(iter, memcg)
4775 mem_cgroup_oom_notify_cb(iter);
4778 static int mem_cgroup_usage_register_event(struct cgroup *cgrp,
4779 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
4781 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4782 struct mem_cgroup_thresholds *thresholds;
4783 struct mem_cgroup_threshold_ary *new;
4784 enum res_type type = MEMFILE_TYPE(cft->private);
4785 u64 threshold, usage;
4786 int i, size, ret;
4788 ret = res_counter_memparse_write_strategy(args, &threshold);
4789 if (ret)
4790 return ret;
4792 mutex_lock(&memcg->thresholds_lock);
4794 if (type == _MEM)
4795 thresholds = &memcg->thresholds;
4796 else if (type == _MEMSWAP)
4797 thresholds = &memcg->memsw_thresholds;
4798 else
4799 BUG();
4801 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
4803 /* Check if a threshold crossed before adding a new one */
4804 if (thresholds->primary)
4805 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4807 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
4809 /* Allocate memory for new array of thresholds */
4810 new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
4811 GFP_KERNEL);
4812 if (!new) {
4813 ret = -ENOMEM;
4814 goto unlock;
4816 new->size = size;
4818 /* Copy thresholds (if any) to new array */
4819 if (thresholds->primary) {
4820 memcpy(new->entries, thresholds->primary->entries, (size - 1) *
4821 sizeof(struct mem_cgroup_threshold));
4824 /* Add new threshold */
4825 new->entries[size - 1].eventfd = eventfd;
4826 new->entries[size - 1].threshold = threshold;
4828 /* Sort thresholds. Registering of new threshold isn't time-critical */
4829 sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
4830 compare_thresholds, NULL);
4832 /* Find current threshold */
4833 new->current_threshold = -1;
4834 for (i = 0; i < size; i++) {
4835 if (new->entries[i].threshold <= usage) {
4837 * new->current_threshold will not be used until
4838 * rcu_assign_pointer(), so it's safe to increment
4839 * it here.
4841 ++new->current_threshold;
4842 } else
4843 break;
4846 /* Free old spare buffer and save old primary buffer as spare */
4847 kfree(thresholds->spare);
4848 thresholds->spare = thresholds->primary;
4850 rcu_assign_pointer(thresholds->primary, new);
4852 /* To be sure that nobody uses thresholds */
4853 synchronize_rcu();
4855 unlock:
4856 mutex_unlock(&memcg->thresholds_lock);
4858 return ret;
4861 static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,
4862 struct cftype *cft, struct eventfd_ctx *eventfd)
4864 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4865 struct mem_cgroup_thresholds *thresholds;
4866 struct mem_cgroup_threshold_ary *new;
4867 enum res_type type = MEMFILE_TYPE(cft->private);
4868 u64 usage;
4869 int i, j, size;
4871 mutex_lock(&memcg->thresholds_lock);
4872 if (type == _MEM)
4873 thresholds = &memcg->thresholds;
4874 else if (type == _MEMSWAP)
4875 thresholds = &memcg->memsw_thresholds;
4876 else
4877 BUG();
4879 if (!thresholds->primary)
4880 goto unlock;
4882 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
4884 /* Check if a threshold crossed before removing */
4885 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4887 /* Calculate new number of threshold */
4888 size = 0;
4889 for (i = 0; i < thresholds->primary->size; i++) {
4890 if (thresholds->primary->entries[i].eventfd != eventfd)
4891 size++;
4894 new = thresholds->spare;
4896 /* Set thresholds array to NULL if we don't have thresholds */
4897 if (!size) {
4898 kfree(new);
4899 new = NULL;
4900 goto swap_buffers;
4903 new->size = size;
4905 /* Copy thresholds and find current threshold */
4906 new->current_threshold = -1;
4907 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4908 if (thresholds->primary->entries[i].eventfd == eventfd)
4909 continue;
4911 new->entries[j] = thresholds->primary->entries[i];
4912 if (new->entries[j].threshold <= usage) {
4914 * new->current_threshold will not be used
4915 * until rcu_assign_pointer(), so it's safe to increment
4916 * it here.
4918 ++new->current_threshold;
4920 j++;
4923 swap_buffers:
4924 /* Swap primary and spare array */
4925 thresholds->spare = thresholds->primary;
4926 /* If all events are unregistered, free the spare array */
4927 if (!new) {
4928 kfree(thresholds->spare);
4929 thresholds->spare = NULL;
4932 rcu_assign_pointer(thresholds->primary, new);
4934 /* To be sure that nobody uses thresholds */
4935 synchronize_rcu();
4936 unlock:
4937 mutex_unlock(&memcg->thresholds_lock);
4940 static int mem_cgroup_oom_register_event(struct cgroup *cgrp,
4941 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
4943 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4944 struct mem_cgroup_eventfd_list *event;
4945 enum res_type type = MEMFILE_TYPE(cft->private);
4947 BUG_ON(type != _OOM_TYPE);
4948 event = kmalloc(sizeof(*event), GFP_KERNEL);
4949 if (!event)
4950 return -ENOMEM;
4952 spin_lock(&memcg_oom_lock);
4954 event->eventfd = eventfd;
4955 list_add(&event->list, &memcg->oom_notify);
4957 /* already in OOM ? */
4958 if (atomic_read(&memcg->under_oom))
4959 eventfd_signal(eventfd, 1);
4960 spin_unlock(&memcg_oom_lock);
4962 return 0;
4965 static void mem_cgroup_oom_unregister_event(struct cgroup *cgrp,
4966 struct cftype *cft, struct eventfd_ctx *eventfd)
4968 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4969 struct mem_cgroup_eventfd_list *ev, *tmp;
4970 enum res_type type = MEMFILE_TYPE(cft->private);
4972 BUG_ON(type != _OOM_TYPE);
4974 spin_lock(&memcg_oom_lock);
4976 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
4977 if (ev->eventfd == eventfd) {
4978 list_del(&ev->list);
4979 kfree(ev);
4983 spin_unlock(&memcg_oom_lock);
4986 static int mem_cgroup_oom_control_read(struct cgroup *cgrp,
4987 struct cftype *cft, struct cgroup_map_cb *cb)
4989 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4991 cb->fill(cb, "oom_kill_disable", memcg->oom_kill_disable);
4993 if (atomic_read(&memcg->under_oom))
4994 cb->fill(cb, "under_oom", 1);
4995 else
4996 cb->fill(cb, "under_oom", 0);
4997 return 0;
5000 static int mem_cgroup_oom_control_write(struct cgroup *cgrp,
5001 struct cftype *cft, u64 val)
5003 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5004 struct mem_cgroup *parent;
5006 /* cannot set to root cgroup and only 0 and 1 are allowed */
5007 if (!cgrp->parent || !((val == 0) || (val == 1)))
5008 return -EINVAL;
5010 parent = mem_cgroup_from_cont(cgrp->parent);
5012 cgroup_lock();
5013 /* oom-kill-disable is a flag for subhierarchy. */
5014 if ((parent->use_hierarchy) ||
5015 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
5016 cgroup_unlock();
5017 return -EINVAL;
5019 memcg->oom_kill_disable = val;
5020 if (!val)
5021 memcg_oom_recover(memcg);
5022 cgroup_unlock();
5023 return 0;
5026 #ifdef CONFIG_MEMCG_KMEM
5027 static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
5029 memcg_propagate_kmem(memcg);
5030 return mem_cgroup_sockets_init(memcg, ss);
5033 static void kmem_cgroup_destroy(struct mem_cgroup *memcg)
5035 mem_cgroup_sockets_destroy(memcg);
5037 memcg_kmem_mark_dead(memcg);
5039 if (res_counter_read_u64(&memcg->kmem, RES_USAGE) != 0)
5040 return;
5043 * Charges already down to 0, undo mem_cgroup_get() done in the charge
5044 * path here, being careful not to race with memcg_uncharge_kmem: it is
5045 * possible that the charges went down to 0 between mark_dead and the
5046 * res_counter read, so in that case, we don't need the put
5048 if (memcg_kmem_test_and_clear_dead(memcg))
5049 mem_cgroup_put(memcg);
5051 #else
5052 static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
5054 return 0;
5057 static void kmem_cgroup_destroy(struct mem_cgroup *memcg)
5060 #endif
5062 static struct cftype mem_cgroup_files[] = {
5064 .name = "usage_in_bytes",
5065 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
5066 .read = mem_cgroup_read,
5067 .register_event = mem_cgroup_usage_register_event,
5068 .unregister_event = mem_cgroup_usage_unregister_event,
5071 .name = "max_usage_in_bytes",
5072 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
5073 .trigger = mem_cgroup_reset,
5074 .read = mem_cgroup_read,
5077 .name = "limit_in_bytes",
5078 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
5079 .write_string = mem_cgroup_write,
5080 .read = mem_cgroup_read,
5083 .name = "soft_limit_in_bytes",
5084 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
5085 .write_string = mem_cgroup_write,
5086 .read = mem_cgroup_read,
5089 .name = "failcnt",
5090 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
5091 .trigger = mem_cgroup_reset,
5092 .read = mem_cgroup_read,
5095 .name = "stat",
5096 .read_seq_string = memcg_stat_show,
5099 .name = "force_empty",
5100 .trigger = mem_cgroup_force_empty_write,
5103 .name = "use_hierarchy",
5104 .write_u64 = mem_cgroup_hierarchy_write,
5105 .read_u64 = mem_cgroup_hierarchy_read,
5108 .name = "swappiness",
5109 .read_u64 = mem_cgroup_swappiness_read,
5110 .write_u64 = mem_cgroup_swappiness_write,
5113 .name = "move_charge_at_immigrate",
5114 .read_u64 = mem_cgroup_move_charge_read,
5115 .write_u64 = mem_cgroup_move_charge_write,
5118 .name = "oom_control",
5119 .read_map = mem_cgroup_oom_control_read,
5120 .write_u64 = mem_cgroup_oom_control_write,
5121 .register_event = mem_cgroup_oom_register_event,
5122 .unregister_event = mem_cgroup_oom_unregister_event,
5123 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
5125 #ifdef CONFIG_NUMA
5127 .name = "numa_stat",
5128 .read_seq_string = memcg_numa_stat_show,
5130 #endif
5131 #ifdef CONFIG_MEMCG_SWAP
5133 .name = "memsw.usage_in_bytes",
5134 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
5135 .read = mem_cgroup_read,
5136 .register_event = mem_cgroup_usage_register_event,
5137 .unregister_event = mem_cgroup_usage_unregister_event,
5140 .name = "memsw.max_usage_in_bytes",
5141 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
5142 .trigger = mem_cgroup_reset,
5143 .read = mem_cgroup_read,
5146 .name = "memsw.limit_in_bytes",
5147 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
5148 .write_string = mem_cgroup_write,
5149 .read = mem_cgroup_read,
5152 .name = "memsw.failcnt",
5153 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
5154 .trigger = mem_cgroup_reset,
5155 .read = mem_cgroup_read,
5157 #endif
5158 #ifdef CONFIG_MEMCG_KMEM
5160 .name = "kmem.limit_in_bytes",
5161 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
5162 .write_string = mem_cgroup_write,
5163 .read = mem_cgroup_read,
5166 .name = "kmem.usage_in_bytes",
5167 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
5168 .read = mem_cgroup_read,
5171 .name = "kmem.failcnt",
5172 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
5173 .trigger = mem_cgroup_reset,
5174 .read = mem_cgroup_read,
5177 .name = "kmem.max_usage_in_bytes",
5178 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
5179 .trigger = mem_cgroup_reset,
5180 .read = mem_cgroup_read,
5182 #endif
5183 { }, /* terminate */
5186 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
5188 struct mem_cgroup_per_node *pn;
5189 struct mem_cgroup_per_zone *mz;
5190 int zone, tmp = node;
5192 * This routine is called against possible nodes.
5193 * But it's BUG to call kmalloc() against offline node.
5195 * TODO: this routine can waste much memory for nodes which will
5196 * never be onlined. It's better to use memory hotplug callback
5197 * function.
5199 if (!node_state(node, N_NORMAL_MEMORY))
5200 tmp = -1;
5201 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
5202 if (!pn)
5203 return 1;
5205 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
5206 mz = &pn->zoneinfo[zone];
5207 lruvec_init(&mz->lruvec);
5208 mz->usage_in_excess = 0;
5209 mz->on_tree = false;
5210 mz->memcg = memcg;
5212 memcg->info.nodeinfo[node] = pn;
5213 return 0;
5216 static void free_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
5218 kfree(memcg->info.nodeinfo[node]);
5221 static struct mem_cgroup *mem_cgroup_alloc(void)
5223 struct mem_cgroup *memcg;
5224 int size = sizeof(struct mem_cgroup);
5226 /* Can be very big if MAX_NUMNODES is very big */
5227 if (size < PAGE_SIZE)
5228 memcg = kzalloc(size, GFP_KERNEL);
5229 else
5230 memcg = vzalloc(size);
5232 if (!memcg)
5233 return NULL;
5235 memcg->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
5236 if (!memcg->stat)
5237 goto out_free;
5238 spin_lock_init(&memcg->pcp_counter_lock);
5239 return memcg;
5241 out_free:
5242 if (size < PAGE_SIZE)
5243 kfree(memcg);
5244 else
5245 vfree(memcg);
5246 return NULL;
5250 * At destroying mem_cgroup, references from swap_cgroup can remain.
5251 * (scanning all at force_empty is too costly...)
5253 * Instead of clearing all references at force_empty, we remember
5254 * the number of reference from swap_cgroup and free mem_cgroup when
5255 * it goes down to 0.
5257 * Removal of cgroup itself succeeds regardless of refs from swap.
5260 static void __mem_cgroup_free(struct mem_cgroup *memcg)
5262 int node;
5263 int size = sizeof(struct mem_cgroup);
5265 mem_cgroup_remove_from_trees(memcg);
5266 free_css_id(&mem_cgroup_subsys, &memcg->css);
5268 for_each_node(node)
5269 free_mem_cgroup_per_zone_info(memcg, node);
5271 free_percpu(memcg->stat);
5274 * We need to make sure that (at least for now), the jump label
5275 * destruction code runs outside of the cgroup lock. This is because
5276 * get_online_cpus(), which is called from the static_branch update,
5277 * can't be called inside the cgroup_lock. cpusets are the ones
5278 * enforcing this dependency, so if they ever change, we might as well.
5280 * schedule_work() will guarantee this happens. Be careful if you need
5281 * to move this code around, and make sure it is outside
5282 * the cgroup_lock.
5284 disarm_static_keys(memcg);
5285 if (size < PAGE_SIZE)
5286 kfree(memcg);
5287 else
5288 vfree(memcg);
5293 * Helpers for freeing a kmalloc()ed/vzalloc()ed mem_cgroup by RCU,
5294 * but in process context. The work_freeing structure is overlaid
5295 * on the rcu_freeing structure, which itself is overlaid on memsw.
5297 static void free_work(struct work_struct *work)
5299 struct mem_cgroup *memcg;
5301 memcg = container_of(work, struct mem_cgroup, work_freeing);
5302 __mem_cgroup_free(memcg);
5305 static void free_rcu(struct rcu_head *rcu_head)
5307 struct mem_cgroup *memcg;
5309 memcg = container_of(rcu_head, struct mem_cgroup, rcu_freeing);
5310 INIT_WORK(&memcg->work_freeing, free_work);
5311 schedule_work(&memcg->work_freeing);
5314 static void mem_cgroup_get(struct mem_cgroup *memcg)
5316 atomic_inc(&memcg->refcnt);
5319 static void __mem_cgroup_put(struct mem_cgroup *memcg, int count)
5321 if (atomic_sub_and_test(count, &memcg->refcnt)) {
5322 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
5323 call_rcu(&memcg->rcu_freeing, free_rcu);
5324 if (parent)
5325 mem_cgroup_put(parent);
5329 static void mem_cgroup_put(struct mem_cgroup *memcg)
5331 __mem_cgroup_put(memcg, 1);
5335 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
5337 struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg)
5339 if (!memcg->res.parent)
5340 return NULL;
5341 return mem_cgroup_from_res_counter(memcg->res.parent, res);
5343 EXPORT_SYMBOL(parent_mem_cgroup);
5345 #ifdef CONFIG_MEMCG_SWAP
5346 static void __init enable_swap_cgroup(void)
5348 if (!mem_cgroup_disabled() && really_do_swap_account)
5349 do_swap_account = 1;
5351 #else
5352 static void __init enable_swap_cgroup(void)
5355 #endif
5357 static int mem_cgroup_soft_limit_tree_init(void)
5359 struct mem_cgroup_tree_per_node *rtpn;
5360 struct mem_cgroup_tree_per_zone *rtpz;
5361 int tmp, node, zone;
5363 for_each_node(node) {
5364 tmp = node;
5365 if (!node_state(node, N_NORMAL_MEMORY))
5366 tmp = -1;
5367 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
5368 if (!rtpn)
5369 goto err_cleanup;
5371 soft_limit_tree.rb_tree_per_node[node] = rtpn;
5373 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
5374 rtpz = &rtpn->rb_tree_per_zone[zone];
5375 rtpz->rb_root = RB_ROOT;
5376 spin_lock_init(&rtpz->lock);
5379 return 0;
5381 err_cleanup:
5382 for_each_node(node) {
5383 if (!soft_limit_tree.rb_tree_per_node[node])
5384 break;
5385 kfree(soft_limit_tree.rb_tree_per_node[node]);
5386 soft_limit_tree.rb_tree_per_node[node] = NULL;
5388 return 1;
5392 static struct cgroup_subsys_state * __ref
5393 mem_cgroup_css_alloc(struct cgroup *cont)
5395 struct mem_cgroup *memcg, *parent;
5396 long error = -ENOMEM;
5397 int node;
5399 memcg = mem_cgroup_alloc();
5400 if (!memcg)
5401 return ERR_PTR(error);
5403 for_each_node(node)
5404 if (alloc_mem_cgroup_per_zone_info(memcg, node))
5405 goto free_out;
5407 /* root ? */
5408 if (cont->parent == NULL) {
5409 int cpu;
5410 enable_swap_cgroup();
5411 parent = NULL;
5412 if (mem_cgroup_soft_limit_tree_init())
5413 goto free_out;
5414 root_mem_cgroup = memcg;
5415 for_each_possible_cpu(cpu) {
5416 struct memcg_stock_pcp *stock =
5417 &per_cpu(memcg_stock, cpu);
5418 INIT_WORK(&stock->work, drain_local_stock);
5420 hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
5421 } else {
5422 parent = mem_cgroup_from_cont(cont->parent);
5423 memcg->use_hierarchy = parent->use_hierarchy;
5424 memcg->oom_kill_disable = parent->oom_kill_disable;
5427 if (parent && parent->use_hierarchy) {
5428 res_counter_init(&memcg->res, &parent->res);
5429 res_counter_init(&memcg->memsw, &parent->memsw);
5430 res_counter_init(&memcg->kmem, &parent->kmem);
5432 * We increment refcnt of the parent to ensure that we can
5433 * safely access it on res_counter_charge/uncharge.
5434 * This refcnt will be decremented when freeing this
5435 * mem_cgroup(see mem_cgroup_put).
5437 mem_cgroup_get(parent);
5438 } else {
5439 res_counter_init(&memcg->res, NULL);
5440 res_counter_init(&memcg->memsw, NULL);
5441 res_counter_init(&memcg->kmem, NULL);
5443 * Deeper hierachy with use_hierarchy == false doesn't make
5444 * much sense so let cgroup subsystem know about this
5445 * unfortunate state in our controller.
5447 if (parent && parent != root_mem_cgroup)
5448 mem_cgroup_subsys.broken_hierarchy = true;
5450 memcg->last_scanned_node = MAX_NUMNODES;
5451 INIT_LIST_HEAD(&memcg->oom_notify);
5453 if (parent)
5454 memcg->swappiness = mem_cgroup_swappiness(parent);
5455 atomic_set(&memcg->refcnt, 1);
5456 memcg->move_charge_at_immigrate = 0;
5457 mutex_init(&memcg->thresholds_lock);
5458 spin_lock_init(&memcg->move_lock);
5460 error = memcg_init_kmem(memcg, &mem_cgroup_subsys);
5461 if (error) {
5463 * We call put now because our (and parent's) refcnts
5464 * are already in place. mem_cgroup_put() will internally
5465 * call __mem_cgroup_free, so return directly
5467 mem_cgroup_put(memcg);
5468 return ERR_PTR(error);
5470 return &memcg->css;
5471 free_out:
5472 __mem_cgroup_free(memcg);
5473 return ERR_PTR(error);
5476 static void mem_cgroup_css_offline(struct cgroup *cont)
5478 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5480 mem_cgroup_reparent_charges(memcg);
5483 static void mem_cgroup_css_free(struct cgroup *cont)
5485 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5487 kmem_cgroup_destroy(memcg);
5489 mem_cgroup_put(memcg);
5492 #ifdef CONFIG_MMU
5493 /* Handlers for move charge at task migration. */
5494 #define PRECHARGE_COUNT_AT_ONCE 256
5495 static int mem_cgroup_do_precharge(unsigned long count)
5497 int ret = 0;
5498 int batch_count = PRECHARGE_COUNT_AT_ONCE;
5499 struct mem_cgroup *memcg = mc.to;
5501 if (mem_cgroup_is_root(memcg)) {
5502 mc.precharge += count;
5503 /* we don't need css_get for root */
5504 return ret;
5506 /* try to charge at once */
5507 if (count > 1) {
5508 struct res_counter *dummy;
5510 * "memcg" cannot be under rmdir() because we've already checked
5511 * by cgroup_lock_live_cgroup() that it is not removed and we
5512 * are still under the same cgroup_mutex. So we can postpone
5513 * css_get().
5515 if (res_counter_charge(&memcg->res, PAGE_SIZE * count, &dummy))
5516 goto one_by_one;
5517 if (do_swap_account && res_counter_charge(&memcg->memsw,
5518 PAGE_SIZE * count, &dummy)) {
5519 res_counter_uncharge(&memcg->res, PAGE_SIZE * count);
5520 goto one_by_one;
5522 mc.precharge += count;
5523 return ret;
5525 one_by_one:
5526 /* fall back to one by one charge */
5527 while (count--) {
5528 if (signal_pending(current)) {
5529 ret = -EINTR;
5530 break;
5532 if (!batch_count--) {
5533 batch_count = PRECHARGE_COUNT_AT_ONCE;
5534 cond_resched();
5536 ret = __mem_cgroup_try_charge(NULL,
5537 GFP_KERNEL, 1, &memcg, false);
5538 if (ret)
5539 /* mem_cgroup_clear_mc() will do uncharge later */
5540 return ret;
5541 mc.precharge++;
5543 return ret;
5547 * get_mctgt_type - get target type of moving charge
5548 * @vma: the vma the pte to be checked belongs
5549 * @addr: the address corresponding to the pte to be checked
5550 * @ptent: the pte to be checked
5551 * @target: the pointer the target page or swap ent will be stored(can be NULL)
5553 * Returns
5554 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
5555 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5556 * move charge. if @target is not NULL, the page is stored in target->page
5557 * with extra refcnt got(Callers should handle it).
5558 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5559 * target for charge migration. if @target is not NULL, the entry is stored
5560 * in target->ent.
5562 * Called with pte lock held.
5564 union mc_target {
5565 struct page *page;
5566 swp_entry_t ent;
5569 enum mc_target_type {
5570 MC_TARGET_NONE = 0,
5571 MC_TARGET_PAGE,
5572 MC_TARGET_SWAP,
5575 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5576 unsigned long addr, pte_t ptent)
5578 struct page *page = vm_normal_page(vma, addr, ptent);
5580 if (!page || !page_mapped(page))
5581 return NULL;
5582 if (PageAnon(page)) {
5583 /* we don't move shared anon */
5584 if (!move_anon())
5585 return NULL;
5586 } else if (!move_file())
5587 /* we ignore mapcount for file pages */
5588 return NULL;
5589 if (!get_page_unless_zero(page))
5590 return NULL;
5592 return page;
5595 #ifdef CONFIG_SWAP
5596 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5597 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5599 struct page *page = NULL;
5600 swp_entry_t ent = pte_to_swp_entry(ptent);
5602 if (!move_anon() || non_swap_entry(ent))
5603 return NULL;
5605 * Because lookup_swap_cache() updates some statistics counter,
5606 * we call find_get_page() with swapper_space directly.
5608 page = find_get_page(&swapper_space, ent.val);
5609 if (do_swap_account)
5610 entry->val = ent.val;
5612 return page;
5614 #else
5615 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5616 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5618 return NULL;
5620 #endif
5622 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5623 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5625 struct page *page = NULL;
5626 struct address_space *mapping;
5627 pgoff_t pgoff;
5629 if (!vma->vm_file) /* anonymous vma */
5630 return NULL;
5631 if (!move_file())
5632 return NULL;
5634 mapping = vma->vm_file->f_mapping;
5635 if (pte_none(ptent))
5636 pgoff = linear_page_index(vma, addr);
5637 else /* pte_file(ptent) is true */
5638 pgoff = pte_to_pgoff(ptent);
5640 /* page is moved even if it's not RSS of this task(page-faulted). */
5641 page = find_get_page(mapping, pgoff);
5643 #ifdef CONFIG_SWAP
5644 /* shmem/tmpfs may report page out on swap: account for that too. */
5645 if (radix_tree_exceptional_entry(page)) {
5646 swp_entry_t swap = radix_to_swp_entry(page);
5647 if (do_swap_account)
5648 *entry = swap;
5649 page = find_get_page(&swapper_space, swap.val);
5651 #endif
5652 return page;
5655 static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
5656 unsigned long addr, pte_t ptent, union mc_target *target)
5658 struct page *page = NULL;
5659 struct page_cgroup *pc;
5660 enum mc_target_type ret = MC_TARGET_NONE;
5661 swp_entry_t ent = { .val = 0 };
5663 if (pte_present(ptent))
5664 page = mc_handle_present_pte(vma, addr, ptent);
5665 else if (is_swap_pte(ptent))
5666 page = mc_handle_swap_pte(vma, addr, ptent, &ent);
5667 else if (pte_none(ptent) || pte_file(ptent))
5668 page = mc_handle_file_pte(vma, addr, ptent, &ent);
5670 if (!page && !ent.val)
5671 return ret;
5672 if (page) {
5673 pc = lookup_page_cgroup(page);
5675 * Do only loose check w/o page_cgroup lock.
5676 * mem_cgroup_move_account() checks the pc is valid or not under
5677 * the lock.
5679 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
5680 ret = MC_TARGET_PAGE;
5681 if (target)
5682 target->page = page;
5684 if (!ret || !target)
5685 put_page(page);
5687 /* There is a swap entry and a page doesn't exist or isn't charged */
5688 if (ent.val && !ret &&
5689 css_id(&mc.from->css) == lookup_swap_cgroup_id(ent)) {
5690 ret = MC_TARGET_SWAP;
5691 if (target)
5692 target->ent = ent;
5694 return ret;
5697 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5699 * We don't consider swapping or file mapped pages because THP does not
5700 * support them for now.
5701 * Caller should make sure that pmd_trans_huge(pmd) is true.
5703 static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5704 unsigned long addr, pmd_t pmd, union mc_target *target)
5706 struct page *page = NULL;
5707 struct page_cgroup *pc;
5708 enum mc_target_type ret = MC_TARGET_NONE;
5710 page = pmd_page(pmd);
5711 VM_BUG_ON(!page || !PageHead(page));
5712 if (!move_anon())
5713 return ret;
5714 pc = lookup_page_cgroup(page);
5715 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
5716 ret = MC_TARGET_PAGE;
5717 if (target) {
5718 get_page(page);
5719 target->page = page;
5722 return ret;
5724 #else
5725 static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5726 unsigned long addr, pmd_t pmd, union mc_target *target)
5728 return MC_TARGET_NONE;
5730 #endif
5732 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
5733 unsigned long addr, unsigned long end,
5734 struct mm_walk *walk)
5736 struct vm_area_struct *vma = walk->private;
5737 pte_t *pte;
5738 spinlock_t *ptl;
5740 if (pmd_trans_huge_lock(pmd, vma) == 1) {
5741 if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
5742 mc.precharge += HPAGE_PMD_NR;
5743 spin_unlock(&vma->vm_mm->page_table_lock);
5744 return 0;
5747 if (pmd_trans_unstable(pmd))
5748 return 0;
5749 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5750 for (; addr != end; pte++, addr += PAGE_SIZE)
5751 if (get_mctgt_type(vma, addr, *pte, NULL))
5752 mc.precharge++; /* increment precharge temporarily */
5753 pte_unmap_unlock(pte - 1, ptl);
5754 cond_resched();
5756 return 0;
5759 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
5761 unsigned long precharge;
5762 struct vm_area_struct *vma;
5764 down_read(&mm->mmap_sem);
5765 for (vma = mm->mmap; vma; vma = vma->vm_next) {
5766 struct mm_walk mem_cgroup_count_precharge_walk = {
5767 .pmd_entry = mem_cgroup_count_precharge_pte_range,
5768 .mm = mm,
5769 .private = vma,
5771 if (is_vm_hugetlb_page(vma))
5772 continue;
5773 walk_page_range(vma->vm_start, vma->vm_end,
5774 &mem_cgroup_count_precharge_walk);
5776 up_read(&mm->mmap_sem);
5778 precharge = mc.precharge;
5779 mc.precharge = 0;
5781 return precharge;
5784 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
5786 unsigned long precharge = mem_cgroup_count_precharge(mm);
5788 VM_BUG_ON(mc.moving_task);
5789 mc.moving_task = current;
5790 return mem_cgroup_do_precharge(precharge);
5793 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5794 static void __mem_cgroup_clear_mc(void)
5796 struct mem_cgroup *from = mc.from;
5797 struct mem_cgroup *to = mc.to;
5799 /* we must uncharge all the leftover precharges from mc.to */
5800 if (mc.precharge) {
5801 __mem_cgroup_cancel_charge(mc.to, mc.precharge);
5802 mc.precharge = 0;
5805 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5806 * we must uncharge here.
5808 if (mc.moved_charge) {
5809 __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
5810 mc.moved_charge = 0;
5812 /* we must fixup refcnts and charges */
5813 if (mc.moved_swap) {
5814 /* uncharge swap account from the old cgroup */
5815 if (!mem_cgroup_is_root(mc.from))
5816 res_counter_uncharge(&mc.from->memsw,
5817 PAGE_SIZE * mc.moved_swap);
5818 __mem_cgroup_put(mc.from, mc.moved_swap);
5820 if (!mem_cgroup_is_root(mc.to)) {
5822 * we charged both to->res and to->memsw, so we should
5823 * uncharge to->res.
5825 res_counter_uncharge(&mc.to->res,
5826 PAGE_SIZE * mc.moved_swap);
5828 /* we've already done mem_cgroup_get(mc.to) */
5829 mc.moved_swap = 0;
5831 memcg_oom_recover(from);
5832 memcg_oom_recover(to);
5833 wake_up_all(&mc.waitq);
5836 static void mem_cgroup_clear_mc(void)
5838 struct mem_cgroup *from = mc.from;
5841 * we must clear moving_task before waking up waiters at the end of
5842 * task migration.
5844 mc.moving_task = NULL;
5845 __mem_cgroup_clear_mc();
5846 spin_lock(&mc.lock);
5847 mc.from = NULL;
5848 mc.to = NULL;
5849 spin_unlock(&mc.lock);
5850 mem_cgroup_end_move(from);
5853 static int mem_cgroup_can_attach(struct cgroup *cgroup,
5854 struct cgroup_taskset *tset)
5856 struct task_struct *p = cgroup_taskset_first(tset);
5857 int ret = 0;
5858 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgroup);
5860 if (memcg->move_charge_at_immigrate) {
5861 struct mm_struct *mm;
5862 struct mem_cgroup *from = mem_cgroup_from_task(p);
5864 VM_BUG_ON(from == memcg);
5866 mm = get_task_mm(p);
5867 if (!mm)
5868 return 0;
5869 /* We move charges only when we move a owner of the mm */
5870 if (mm->owner == p) {
5871 VM_BUG_ON(mc.from);
5872 VM_BUG_ON(mc.to);
5873 VM_BUG_ON(mc.precharge);
5874 VM_BUG_ON(mc.moved_charge);
5875 VM_BUG_ON(mc.moved_swap);
5876 mem_cgroup_start_move(from);
5877 spin_lock(&mc.lock);
5878 mc.from = from;
5879 mc.to = memcg;
5880 spin_unlock(&mc.lock);
5881 /* We set mc.moving_task later */
5883 ret = mem_cgroup_precharge_mc(mm);
5884 if (ret)
5885 mem_cgroup_clear_mc();
5887 mmput(mm);
5889 return ret;
5892 static void mem_cgroup_cancel_attach(struct cgroup *cgroup,
5893 struct cgroup_taskset *tset)
5895 mem_cgroup_clear_mc();
5898 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
5899 unsigned long addr, unsigned long end,
5900 struct mm_walk *walk)
5902 int ret = 0;
5903 struct vm_area_struct *vma = walk->private;
5904 pte_t *pte;
5905 spinlock_t *ptl;
5906 enum mc_target_type target_type;
5907 union mc_target target;
5908 struct page *page;
5909 struct page_cgroup *pc;
5912 * We don't take compound_lock() here but no race with splitting thp
5913 * happens because:
5914 * - if pmd_trans_huge_lock() returns 1, the relevant thp is not
5915 * under splitting, which means there's no concurrent thp split,
5916 * - if another thread runs into split_huge_page() just after we
5917 * entered this if-block, the thread must wait for page table lock
5918 * to be unlocked in __split_huge_page_splitting(), where the main
5919 * part of thp split is not executed yet.
5921 if (pmd_trans_huge_lock(pmd, vma) == 1) {
5922 if (mc.precharge < HPAGE_PMD_NR) {
5923 spin_unlock(&vma->vm_mm->page_table_lock);
5924 return 0;
5926 target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
5927 if (target_type == MC_TARGET_PAGE) {
5928 page = target.page;
5929 if (!isolate_lru_page(page)) {
5930 pc = lookup_page_cgroup(page);
5931 if (!mem_cgroup_move_account(page, HPAGE_PMD_NR,
5932 pc, mc.from, mc.to)) {
5933 mc.precharge -= HPAGE_PMD_NR;
5934 mc.moved_charge += HPAGE_PMD_NR;
5936 putback_lru_page(page);
5938 put_page(page);
5940 spin_unlock(&vma->vm_mm->page_table_lock);
5941 return 0;
5944 if (pmd_trans_unstable(pmd))
5945 return 0;
5946 retry:
5947 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5948 for (; addr != end; addr += PAGE_SIZE) {
5949 pte_t ptent = *(pte++);
5950 swp_entry_t ent;
5952 if (!mc.precharge)
5953 break;
5955 switch (get_mctgt_type(vma, addr, ptent, &target)) {
5956 case MC_TARGET_PAGE:
5957 page = target.page;
5958 if (isolate_lru_page(page))
5959 goto put;
5960 pc = lookup_page_cgroup(page);
5961 if (!mem_cgroup_move_account(page, 1, pc,
5962 mc.from, mc.to)) {
5963 mc.precharge--;
5964 /* we uncharge from mc.from later. */
5965 mc.moved_charge++;
5967 putback_lru_page(page);
5968 put: /* get_mctgt_type() gets the page */
5969 put_page(page);
5970 break;
5971 case MC_TARGET_SWAP:
5972 ent = target.ent;
5973 if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
5974 mc.precharge--;
5975 /* we fixup refcnts and charges later. */
5976 mc.moved_swap++;
5978 break;
5979 default:
5980 break;
5983 pte_unmap_unlock(pte - 1, ptl);
5984 cond_resched();
5986 if (addr != end) {
5988 * We have consumed all precharges we got in can_attach().
5989 * We try charge one by one, but don't do any additional
5990 * charges to mc.to if we have failed in charge once in attach()
5991 * phase.
5993 ret = mem_cgroup_do_precharge(1);
5994 if (!ret)
5995 goto retry;
5998 return ret;
6001 static void mem_cgroup_move_charge(struct mm_struct *mm)
6003 struct vm_area_struct *vma;
6005 lru_add_drain_all();
6006 retry:
6007 if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
6009 * Someone who are holding the mmap_sem might be waiting in
6010 * waitq. So we cancel all extra charges, wake up all waiters,
6011 * and retry. Because we cancel precharges, we might not be able
6012 * to move enough charges, but moving charge is a best-effort
6013 * feature anyway, so it wouldn't be a big problem.
6015 __mem_cgroup_clear_mc();
6016 cond_resched();
6017 goto retry;
6019 for (vma = mm->mmap; vma; vma = vma->vm_next) {
6020 int ret;
6021 struct mm_walk mem_cgroup_move_charge_walk = {
6022 .pmd_entry = mem_cgroup_move_charge_pte_range,
6023 .mm = mm,
6024 .private = vma,
6026 if (is_vm_hugetlb_page(vma))
6027 continue;
6028 ret = walk_page_range(vma->vm_start, vma->vm_end,
6029 &mem_cgroup_move_charge_walk);
6030 if (ret)
6032 * means we have consumed all precharges and failed in
6033 * doing additional charge. Just abandon here.
6035 break;
6037 up_read(&mm->mmap_sem);
6040 static void mem_cgroup_move_task(struct cgroup *cont,
6041 struct cgroup_taskset *tset)
6043 struct task_struct *p = cgroup_taskset_first(tset);
6044 struct mm_struct *mm = get_task_mm(p);
6046 if (mm) {
6047 if (mc.to)
6048 mem_cgroup_move_charge(mm);
6049 mmput(mm);
6051 if (mc.to)
6052 mem_cgroup_clear_mc();
6054 #else /* !CONFIG_MMU */
6055 static int mem_cgroup_can_attach(struct cgroup *cgroup,
6056 struct cgroup_taskset *tset)
6058 return 0;
6060 static void mem_cgroup_cancel_attach(struct cgroup *cgroup,
6061 struct cgroup_taskset *tset)
6064 static void mem_cgroup_move_task(struct cgroup *cont,
6065 struct cgroup_taskset *tset)
6068 #endif
6070 struct cgroup_subsys mem_cgroup_subsys = {
6071 .name = "memory",
6072 .subsys_id = mem_cgroup_subsys_id,
6073 .css_alloc = mem_cgroup_css_alloc,
6074 .css_offline = mem_cgroup_css_offline,
6075 .css_free = mem_cgroup_css_free,
6076 .can_attach = mem_cgroup_can_attach,
6077 .cancel_attach = mem_cgroup_cancel_attach,
6078 .attach = mem_cgroup_move_task,
6079 .base_cftypes = mem_cgroup_files,
6080 .early_init = 0,
6081 .use_id = 1,
6084 #ifdef CONFIG_MEMCG_SWAP
6085 static int __init enable_swap_account(char *s)
6087 /* consider enabled if no parameter or 1 is given */
6088 if (!strcmp(s, "1"))
6089 really_do_swap_account = 1;
6090 else if (!strcmp(s, "0"))
6091 really_do_swap_account = 0;
6092 return 1;
6094 __setup("swapaccount=", enable_swap_account);
6096 #endif