slab/slub: consider a memcg parameter in kmem_create_cache
[linux-2.6-block.git] / mm / memcontrol.c
CommitLineData
8cdea7c0
BS
1/* memcontrol.c - Memory Controller
2 *
3 * Copyright IBM Corporation, 2007
4 * Author Balbir Singh <balbir@linux.vnet.ibm.com>
5 *
78fb7466
PE
6 * Copyright 2007 OpenVZ SWsoft Inc
7 * Author: Pavel Emelianov <xemul@openvz.org>
8 *
2e72b634
KS
9 * Memory thresholds
10 * Copyright (C) 2009 Nokia Corporation
11 * Author: Kirill A. Shutemov
12 *
7ae1e1d0
GC
13 * Kernel Memory Controller
14 * Copyright (C) 2012 Parallels Inc. and Google Inc.
15 * Authors: Glauber Costa and Suleiman Souhlal
16 *
8cdea7c0
BS
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.
21 *
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.
26 */
27
28#include <linux/res_counter.h>
29#include <linux/memcontrol.h>
30#include <linux/cgroup.h>
78fb7466 31#include <linux/mm.h>
4ffef5fe 32#include <linux/hugetlb.h>
d13d1443 33#include <linux/pagemap.h>
d52aa412 34#include <linux/smp.h>
8a9f3ccd 35#include <linux/page-flags.h>
66e1707b 36#include <linux/backing-dev.h>
8a9f3ccd
BS
37#include <linux/bit_spinlock.h>
38#include <linux/rcupdate.h>
e222432b 39#include <linux/limits.h>
b9e15baf 40#include <linux/export.h>
8c7c6e34 41#include <linux/mutex.h>
f64c3f54 42#include <linux/rbtree.h>
b6ac57d5 43#include <linux/slab.h>
66e1707b 44#include <linux/swap.h>
02491447 45#include <linux/swapops.h>
66e1707b 46#include <linux/spinlock.h>
2e72b634
KS
47#include <linux/eventfd.h>
48#include <linux/sort.h>
66e1707b 49#include <linux/fs.h>
d2ceb9b7 50#include <linux/seq_file.h>
33327948 51#include <linux/vmalloc.h>
b69408e8 52#include <linux/mm_inline.h>
52d4b9ac 53#include <linux/page_cgroup.h>
cdec2e42 54#include <linux/cpu.h>
158e0a2d 55#include <linux/oom.h>
08e552c6 56#include "internal.h"
d1a4c0b3 57#include <net/sock.h>
4bd2c1ee 58#include <net/ip.h>
d1a4c0b3 59#include <net/tcp_memcontrol.h>
8cdea7c0 60
8697d331
BS
61#include <asm/uaccess.h>
62
cc8e970c
KM
63#include <trace/events/vmscan.h>
64
a181b0e8 65struct cgroup_subsys mem_cgroup_subsys __read_mostly;
68ae564b
DR
66EXPORT_SYMBOL(mem_cgroup_subsys);
67
a181b0e8 68#define MEM_CGROUP_RECLAIM_RETRIES 5
6bbda35c 69static struct mem_cgroup *root_mem_cgroup __read_mostly;
8cdea7c0 70
c255a458 71#ifdef CONFIG_MEMCG_SWAP
338c8431 72/* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
c077719b 73int do_swap_account __read_mostly;
a42c390c
MH
74
75/* for remember boot option*/
c255a458 76#ifdef CONFIG_MEMCG_SWAP_ENABLED
a42c390c
MH
77static int really_do_swap_account __initdata = 1;
78#else
79static int really_do_swap_account __initdata = 0;
80#endif
81
c077719b 82#else
a0db00fc 83#define do_swap_account 0
c077719b
KH
84#endif
85
86
d52aa412
KH
87/*
88 * Statistics for memory cgroup.
89 */
90enum mem_cgroup_stat_index {
91 /*
92 * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
93 */
94 MEM_CGROUP_STAT_CACHE, /* # of pages charged as cache */
d69b042f 95 MEM_CGROUP_STAT_RSS, /* # of pages charged as anon rss */
d8046582 96 MEM_CGROUP_STAT_FILE_MAPPED, /* # of pages charged as file rss */
bff6bb83 97 MEM_CGROUP_STAT_SWAP, /* # of pages, swapped out */
d52aa412
KH
98 MEM_CGROUP_STAT_NSTATS,
99};
100
af7c4b0e
JW
101static const char * const mem_cgroup_stat_names[] = {
102 "cache",
103 "rss",
104 "mapped_file",
105 "swap",
106};
107
e9f8974f
JW
108enum mem_cgroup_events_index {
109 MEM_CGROUP_EVENTS_PGPGIN, /* # of pages paged in */
110 MEM_CGROUP_EVENTS_PGPGOUT, /* # of pages paged out */
456f998e
YH
111 MEM_CGROUP_EVENTS_PGFAULT, /* # of page-faults */
112 MEM_CGROUP_EVENTS_PGMAJFAULT, /* # of major page-faults */
e9f8974f
JW
113 MEM_CGROUP_EVENTS_NSTATS,
114};
af7c4b0e
JW
115
116static const char * const mem_cgroup_events_names[] = {
117 "pgpgin",
118 "pgpgout",
119 "pgfault",
120 "pgmajfault",
121};
122
7a159cc9
JW
123/*
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.
128 */
129enum mem_cgroup_events_target {
130 MEM_CGROUP_TARGET_THRESH,
131 MEM_CGROUP_TARGET_SOFTLIMIT,
453a9bf3 132 MEM_CGROUP_TARGET_NUMAINFO,
7a159cc9
JW
133 MEM_CGROUP_NTARGETS,
134};
a0db00fc
KS
135#define THRESHOLDS_EVENTS_TARGET 128
136#define SOFTLIMIT_EVENTS_TARGET 1024
137#define NUMAINFO_EVENTS_TARGET 1024
e9f8974f 138
d52aa412 139struct mem_cgroup_stat_cpu {
7a159cc9 140 long count[MEM_CGROUP_STAT_NSTATS];
e9f8974f 141 unsigned long events[MEM_CGROUP_EVENTS_NSTATS];
13114716 142 unsigned long nr_page_events;
7a159cc9 143 unsigned long targets[MEM_CGROUP_NTARGETS];
d52aa412
KH
144};
145
527a5ec9
JW
146struct 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;
151};
152
6d12e2d8
KH
153/*
154 * per-zone information in memory controller.
155 */
6d12e2d8 156struct mem_cgroup_per_zone {
6290df54 157 struct lruvec lruvec;
1eb49272 158 unsigned long lru_size[NR_LRU_LISTS];
3e2f41f1 159
527a5ec9
JW
160 struct mem_cgroup_reclaim_iter reclaim_iter[DEF_PRIORITY + 1];
161
f64c3f54
BS
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;
d79154bb 166 struct mem_cgroup *memcg; /* Back pointer, we cannot */
4e416953 167 /* use container_of */
6d12e2d8 168};
6d12e2d8
KH
169
170struct mem_cgroup_per_node {
171 struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
172};
173
174struct mem_cgroup_lru_info {
175 struct mem_cgroup_per_node *nodeinfo[MAX_NUMNODES];
176};
177
f64c3f54
BS
178/*
179 * Cgroups above their limits are maintained in a RB-Tree, independent of
180 * their hierarchy representation
181 */
182
183struct mem_cgroup_tree_per_zone {
184 struct rb_root rb_root;
185 spinlock_t lock;
186};
187
188struct mem_cgroup_tree_per_node {
189 struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
190};
191
192struct mem_cgroup_tree {
193 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
194};
195
196static struct mem_cgroup_tree soft_limit_tree __read_mostly;
197
2e72b634
KS
198struct mem_cgroup_threshold {
199 struct eventfd_ctx *eventfd;
200 u64 threshold;
201};
202
9490ff27 203/* For threshold */
2e72b634 204struct mem_cgroup_threshold_ary {
748dad36 205 /* An array index points to threshold just below or equal to usage. */
5407a562 206 int current_threshold;
2e72b634
KS
207 /* Size of entries[] */
208 unsigned int size;
209 /* Array of thresholds */
210 struct mem_cgroup_threshold entries[0];
211};
2c488db2
KS
212
213struct mem_cgroup_thresholds {
214 /* Primary thresholds array */
215 struct mem_cgroup_threshold_ary *primary;
216 /*
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.
220 */
221 struct mem_cgroup_threshold_ary *spare;
222};
223
9490ff27
KH
224/* for OOM */
225struct mem_cgroup_eventfd_list {
226 struct list_head list;
227 struct eventfd_ctx *eventfd;
228};
2e72b634 229
c0ff4b85
R
230static void mem_cgroup_threshold(struct mem_cgroup *memcg);
231static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
2e72b634 232
8cdea7c0
BS
233/*
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.
238 *
239 * TODO: Add a water mark for the memory controller. Reclaim will begin when
8a9f3ccd
BS
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.
8cdea7c0
BS
243 */
244struct mem_cgroup {
245 struct cgroup_subsys_state css;
246 /*
247 * the counter to account for memory usage
248 */
249 struct res_counter res;
59927fb9
HD
250
251 union {
252 /*
253 * the counter to account for mem+swap usage.
254 */
255 struct res_counter memsw;
256
257 /*
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.
265 */
266 struct rcu_head rcu_freeing;
267 /*
3afe36b1
GC
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.
59927fb9
HD
270 */
271 struct work_struct work_freeing;
272 };
273
510fc4e1
GC
274 /*
275 * the counter to account for kernel memory usage.
276 */
277 struct res_counter kmem;
78fb7466
PE
278 /*
279 * Per cgroup active and inactive list, similar to the
280 * per zone LRU lists.
78fb7466 281 */
6d12e2d8 282 struct mem_cgroup_lru_info info;
889976db
YH
283 int last_scanned_node;
284#if MAX_NUMNODES > 1
285 nodemask_t scan_nodes;
453a9bf3
KH
286 atomic_t numainfo_events;
287 atomic_t numainfo_updating;
889976db 288#endif
18f59ea7
BS
289 /*
290 * Should the accounting and control be hierarchical, per subtree?
291 */
292 bool use_hierarchy;
510fc4e1 293 unsigned long kmem_account_flags; /* See KMEM_ACCOUNTED_*, below */
79dfdacc
MH
294
295 bool oom_lock;
296 atomic_t under_oom;
297
8c7c6e34 298 atomic_t refcnt;
14797e23 299
1f4c025b 300 int swappiness;
3c11ecf4
KH
301 /* OOM-Killer disable */
302 int oom_kill_disable;
a7885eb8 303
22a668d7
KH
304 /* set when res.limit == memsw.limit */
305 bool memsw_is_minimum;
306
2e72b634
KS
307 /* protect arrays of thresholds */
308 struct mutex thresholds_lock;
309
310 /* thresholds for memory usage. RCU-protected */
2c488db2 311 struct mem_cgroup_thresholds thresholds;
907860ed 312
2e72b634 313 /* thresholds for mem+swap usage. RCU-protected */
2c488db2 314 struct mem_cgroup_thresholds memsw_thresholds;
907860ed 315
9490ff27
KH
316 /* For oom notifier event fd */
317 struct list_head oom_notify;
185efc0f 318
7dc74be0
DN
319 /*
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 ?
322 */
323 unsigned long move_charge_at_immigrate;
619d094b
KH
324 /*
325 * set > 0 if pages under this cgroup are moving to other cgroup.
326 */
327 atomic_t moving_account;
312734c0
KH
328 /* taken only while moving_account > 0 */
329 spinlock_t move_lock;
d52aa412 330 /*
c62b1a3b 331 * percpu counter.
d52aa412 332 */
3a7951b4 333 struct mem_cgroup_stat_cpu __percpu *stat;
711d3d2c
KH
334 /*
335 * used when a cpu is offlined or other synchronizations
336 * See mem_cgroup_read_stat().
337 */
338 struct mem_cgroup_stat_cpu nocpu_base;
339 spinlock_t pcp_counter_lock;
d1a4c0b3 340
4bd2c1ee 341#if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_INET)
d1a4c0b3
GC
342 struct tcp_memcontrol tcp_mem;
343#endif
2633d7a0
GC
344#if defined(CONFIG_MEMCG_KMEM)
345 /* analogous to slab_common's slab_caches list. per-memcg */
346 struct list_head memcg_slab_caches;
347 /* Not a spinlock, we can take a lot of time walking the list */
348 struct mutex slab_caches_mutex;
349 /* Index in the kmem_cache->memcg_params->memcg_caches array */
350 int kmemcg_id;
351#endif
8cdea7c0
BS
352};
353
510fc4e1
GC
354/* internal only representation about the status of kmem accounting. */
355enum {
356 KMEM_ACCOUNTED_ACTIVE = 0, /* accounted by this cgroup itself */
a8964b9b 357 KMEM_ACCOUNTED_ACTIVATED, /* static key enabled. */
7de37682 358 KMEM_ACCOUNTED_DEAD, /* dead memcg with pending kmem charges */
510fc4e1
GC
359};
360
a8964b9b
GC
361/* We account when limit is on, but only after call sites are patched */
362#define KMEM_ACCOUNTED_MASK \
363 ((1 << KMEM_ACCOUNTED_ACTIVE) | (1 << KMEM_ACCOUNTED_ACTIVATED))
510fc4e1
GC
364
365#ifdef CONFIG_MEMCG_KMEM
366static inline void memcg_kmem_set_active(struct mem_cgroup *memcg)
367{
368 set_bit(KMEM_ACCOUNTED_ACTIVE, &memcg->kmem_account_flags);
369}
7de37682
GC
370
371static bool memcg_kmem_is_active(struct mem_cgroup *memcg)
372{
373 return test_bit(KMEM_ACCOUNTED_ACTIVE, &memcg->kmem_account_flags);
374}
375
a8964b9b
GC
376static void memcg_kmem_set_activated(struct mem_cgroup *memcg)
377{
378 set_bit(KMEM_ACCOUNTED_ACTIVATED, &memcg->kmem_account_flags);
379}
380
7de37682
GC
381static void memcg_kmem_mark_dead(struct mem_cgroup *memcg)
382{
383 if (test_bit(KMEM_ACCOUNTED_ACTIVE, &memcg->kmem_account_flags))
384 set_bit(KMEM_ACCOUNTED_DEAD, &memcg->kmem_account_flags);
385}
386
387static bool memcg_kmem_test_and_clear_dead(struct mem_cgroup *memcg)
388{
389 return test_and_clear_bit(KMEM_ACCOUNTED_DEAD,
390 &memcg->kmem_account_flags);
391}
510fc4e1
GC
392#endif
393
7dc74be0
DN
394/* Stuffs for move charges at task migration. */
395/*
396 * Types of charges to be moved. "move_charge_at_immitgrate" is treated as a
397 * left-shifted bitmap of these types.
398 */
399enum move_type {
4ffef5fe 400 MOVE_CHARGE_TYPE_ANON, /* private anonymous page and swap of it */
87946a72 401 MOVE_CHARGE_TYPE_FILE, /* file page(including tmpfs) and swap of it */
7dc74be0
DN
402 NR_MOVE_TYPE,
403};
404
4ffef5fe
DN
405/* "mc" and its members are protected by cgroup_mutex */
406static struct move_charge_struct {
b1dd693e 407 spinlock_t lock; /* for from, to */
4ffef5fe
DN
408 struct mem_cgroup *from;
409 struct mem_cgroup *to;
410 unsigned long precharge;
854ffa8d 411 unsigned long moved_charge;
483c30b5 412 unsigned long moved_swap;
8033b97c
DN
413 struct task_struct *moving_task; /* a task moving charges */
414 wait_queue_head_t waitq; /* a waitq for other context */
415} mc = {
2bd9bb20 416 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
8033b97c
DN
417 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
418};
4ffef5fe 419
90254a65
DN
420static bool move_anon(void)
421{
422 return test_bit(MOVE_CHARGE_TYPE_ANON,
423 &mc.to->move_charge_at_immigrate);
424}
425
87946a72
DN
426static bool move_file(void)
427{
428 return test_bit(MOVE_CHARGE_TYPE_FILE,
429 &mc.to->move_charge_at_immigrate);
430}
431
4e416953
BS
432/*
433 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
434 * limit reclaim to prevent infinite loops, if they ever occur.
435 */
a0db00fc
KS
436#define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
437#define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
4e416953 438
217bc319
KH
439enum charge_type {
440 MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
41326c17 441 MEM_CGROUP_CHARGE_TYPE_ANON,
d13d1443 442 MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
8a9478ca 443 MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
c05555b5
KH
444 NR_CHARGE_TYPE,
445};
446
8c7c6e34 447/* for encoding cft->private value on file */
86ae53e1
GC
448enum res_type {
449 _MEM,
450 _MEMSWAP,
451 _OOM_TYPE,
510fc4e1 452 _KMEM,
86ae53e1
GC
453};
454
a0db00fc
KS
455#define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
456#define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
8c7c6e34 457#define MEMFILE_ATTR(val) ((val) & 0xffff)
9490ff27
KH
458/* Used for OOM nofiier */
459#define OOM_CONTROL (0)
8c7c6e34 460
75822b44
BS
461/*
462 * Reclaim flags for mem_cgroup_hierarchical_reclaim
463 */
464#define MEM_CGROUP_RECLAIM_NOSWAP_BIT 0x0
465#define MEM_CGROUP_RECLAIM_NOSWAP (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
466#define MEM_CGROUP_RECLAIM_SHRINK_BIT 0x1
467#define MEM_CGROUP_RECLAIM_SHRINK (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
468
c0ff4b85
R
469static void mem_cgroup_get(struct mem_cgroup *memcg);
470static void mem_cgroup_put(struct mem_cgroup *memcg);
e1aab161 471
b2145145
WL
472static inline
473struct mem_cgroup *mem_cgroup_from_css(struct cgroup_subsys_state *s)
474{
475 return container_of(s, struct mem_cgroup, css);
476}
477
7ffc0edc
MH
478static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg)
479{
480 return (memcg == root_mem_cgroup);
481}
482
e1aab161 483/* Writing them here to avoid exposing memcg's inner layout */
4bd2c1ee 484#if defined(CONFIG_INET) && defined(CONFIG_MEMCG_KMEM)
e1aab161 485
e1aab161
GC
486void sock_update_memcg(struct sock *sk)
487{
376be5ff 488 if (mem_cgroup_sockets_enabled) {
e1aab161 489 struct mem_cgroup *memcg;
3f134619 490 struct cg_proto *cg_proto;
e1aab161
GC
491
492 BUG_ON(!sk->sk_prot->proto_cgroup);
493
f3f511e1
GC
494 /* Socket cloning can throw us here with sk_cgrp already
495 * filled. It won't however, necessarily happen from
496 * process context. So the test for root memcg given
497 * the current task's memcg won't help us in this case.
498 *
499 * Respecting the original socket's memcg is a better
500 * decision in this case.
501 */
502 if (sk->sk_cgrp) {
503 BUG_ON(mem_cgroup_is_root(sk->sk_cgrp->memcg));
504 mem_cgroup_get(sk->sk_cgrp->memcg);
505 return;
506 }
507
e1aab161
GC
508 rcu_read_lock();
509 memcg = mem_cgroup_from_task(current);
3f134619
GC
510 cg_proto = sk->sk_prot->proto_cgroup(memcg);
511 if (!mem_cgroup_is_root(memcg) && memcg_proto_active(cg_proto)) {
e1aab161 512 mem_cgroup_get(memcg);
3f134619 513 sk->sk_cgrp = cg_proto;
e1aab161
GC
514 }
515 rcu_read_unlock();
516 }
517}
518EXPORT_SYMBOL(sock_update_memcg);
519
520void sock_release_memcg(struct sock *sk)
521{
376be5ff 522 if (mem_cgroup_sockets_enabled && sk->sk_cgrp) {
e1aab161
GC
523 struct mem_cgroup *memcg;
524 WARN_ON(!sk->sk_cgrp->memcg);
525 memcg = sk->sk_cgrp->memcg;
526 mem_cgroup_put(memcg);
527 }
528}
d1a4c0b3
GC
529
530struct cg_proto *tcp_proto_cgroup(struct mem_cgroup *memcg)
531{
532 if (!memcg || mem_cgroup_is_root(memcg))
533 return NULL;
534
535 return &memcg->tcp_mem.cg_proto;
536}
537EXPORT_SYMBOL(tcp_proto_cgroup);
e1aab161 538
3f134619
GC
539static void disarm_sock_keys(struct mem_cgroup *memcg)
540{
541 if (!memcg_proto_activated(&memcg->tcp_mem.cg_proto))
542 return;
543 static_key_slow_dec(&memcg_socket_limit_enabled);
544}
545#else
546static void disarm_sock_keys(struct mem_cgroup *memcg)
547{
548}
549#endif
550
a8964b9b
GC
551#ifdef CONFIG_MEMCG_KMEM
552struct static_key memcg_kmem_enabled_key;
553
554static void disarm_kmem_keys(struct mem_cgroup *memcg)
555{
556 if (memcg_kmem_is_active(memcg))
557 static_key_slow_dec(&memcg_kmem_enabled_key);
bea207c8
GC
558 /*
559 * This check can't live in kmem destruction function,
560 * since the charges will outlive the cgroup
561 */
562 WARN_ON(res_counter_read_u64(&memcg->kmem, RES_USAGE) != 0);
a8964b9b
GC
563}
564#else
565static void disarm_kmem_keys(struct mem_cgroup *memcg)
566{
567}
568#endif /* CONFIG_MEMCG_KMEM */
569
570static void disarm_static_keys(struct mem_cgroup *memcg)
571{
572 disarm_sock_keys(memcg);
573 disarm_kmem_keys(memcg);
574}
575
c0ff4b85 576static void drain_all_stock_async(struct mem_cgroup *memcg);
8c7c6e34 577
f64c3f54 578static struct mem_cgroup_per_zone *
c0ff4b85 579mem_cgroup_zoneinfo(struct mem_cgroup *memcg, int nid, int zid)
f64c3f54 580{
c0ff4b85 581 return &memcg->info.nodeinfo[nid]->zoneinfo[zid];
f64c3f54
BS
582}
583
c0ff4b85 584struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *memcg)
d324236b 585{
c0ff4b85 586 return &memcg->css;
d324236b
WF
587}
588
f64c3f54 589static struct mem_cgroup_per_zone *
c0ff4b85 590page_cgroup_zoneinfo(struct mem_cgroup *memcg, struct page *page)
f64c3f54 591{
97a6c37b
JW
592 int nid = page_to_nid(page);
593 int zid = page_zonenum(page);
f64c3f54 594
c0ff4b85 595 return mem_cgroup_zoneinfo(memcg, nid, zid);
f64c3f54
BS
596}
597
598static struct mem_cgroup_tree_per_zone *
599soft_limit_tree_node_zone(int nid, int zid)
600{
601 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
602}
603
604static struct mem_cgroup_tree_per_zone *
605soft_limit_tree_from_page(struct page *page)
606{
607 int nid = page_to_nid(page);
608 int zid = page_zonenum(page);
609
610 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
611}
612
613static void
c0ff4b85 614__mem_cgroup_insert_exceeded(struct mem_cgroup *memcg,
f64c3f54 615 struct mem_cgroup_per_zone *mz,
ef8745c1
KH
616 struct mem_cgroup_tree_per_zone *mctz,
617 unsigned long long new_usage_in_excess)
f64c3f54
BS
618{
619 struct rb_node **p = &mctz->rb_root.rb_node;
620 struct rb_node *parent = NULL;
621 struct mem_cgroup_per_zone *mz_node;
622
623 if (mz->on_tree)
624 return;
625
ef8745c1
KH
626 mz->usage_in_excess = new_usage_in_excess;
627 if (!mz->usage_in_excess)
628 return;
f64c3f54
BS
629 while (*p) {
630 parent = *p;
631 mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
632 tree_node);
633 if (mz->usage_in_excess < mz_node->usage_in_excess)
634 p = &(*p)->rb_left;
635 /*
636 * We can't avoid mem cgroups that are over their soft
637 * limit by the same amount
638 */
639 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
640 p = &(*p)->rb_right;
641 }
642 rb_link_node(&mz->tree_node, parent, p);
643 rb_insert_color(&mz->tree_node, &mctz->rb_root);
644 mz->on_tree = true;
4e416953
BS
645}
646
647static void
c0ff4b85 648__mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
4e416953
BS
649 struct mem_cgroup_per_zone *mz,
650 struct mem_cgroup_tree_per_zone *mctz)
651{
652 if (!mz->on_tree)
653 return;
654 rb_erase(&mz->tree_node, &mctz->rb_root);
655 mz->on_tree = false;
656}
657
f64c3f54 658static void
c0ff4b85 659mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
f64c3f54
BS
660 struct mem_cgroup_per_zone *mz,
661 struct mem_cgroup_tree_per_zone *mctz)
662{
663 spin_lock(&mctz->lock);
c0ff4b85 664 __mem_cgroup_remove_exceeded(memcg, mz, mctz);
f64c3f54
BS
665 spin_unlock(&mctz->lock);
666}
667
f64c3f54 668
c0ff4b85 669static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
f64c3f54 670{
ef8745c1 671 unsigned long long excess;
f64c3f54
BS
672 struct mem_cgroup_per_zone *mz;
673 struct mem_cgroup_tree_per_zone *mctz;
4e649152
KH
674 int nid = page_to_nid(page);
675 int zid = page_zonenum(page);
f64c3f54
BS
676 mctz = soft_limit_tree_from_page(page);
677
678 /*
4e649152
KH
679 * Necessary to update all ancestors when hierarchy is used.
680 * because their event counter is not touched.
f64c3f54 681 */
c0ff4b85
R
682 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
683 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
684 excess = res_counter_soft_limit_excess(&memcg->res);
4e649152
KH
685 /*
686 * We have to update the tree if mz is on RB-tree or
687 * mem is over its softlimit.
688 */
ef8745c1 689 if (excess || mz->on_tree) {
4e649152
KH
690 spin_lock(&mctz->lock);
691 /* if on-tree, remove it */
692 if (mz->on_tree)
c0ff4b85 693 __mem_cgroup_remove_exceeded(memcg, mz, mctz);
4e649152 694 /*
ef8745c1
KH
695 * Insert again. mz->usage_in_excess will be updated.
696 * If excess is 0, no tree ops.
4e649152 697 */
c0ff4b85 698 __mem_cgroup_insert_exceeded(memcg, mz, mctz, excess);
4e649152
KH
699 spin_unlock(&mctz->lock);
700 }
f64c3f54
BS
701 }
702}
703
c0ff4b85 704static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
f64c3f54
BS
705{
706 int node, zone;
707 struct mem_cgroup_per_zone *mz;
708 struct mem_cgroup_tree_per_zone *mctz;
709
3ed28fa1 710 for_each_node(node) {
f64c3f54 711 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
c0ff4b85 712 mz = mem_cgroup_zoneinfo(memcg, node, zone);
f64c3f54 713 mctz = soft_limit_tree_node_zone(node, zone);
c0ff4b85 714 mem_cgroup_remove_exceeded(memcg, mz, mctz);
f64c3f54
BS
715 }
716 }
717}
718
4e416953
BS
719static struct mem_cgroup_per_zone *
720__mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
721{
722 struct rb_node *rightmost = NULL;
26251eaf 723 struct mem_cgroup_per_zone *mz;
4e416953
BS
724
725retry:
26251eaf 726 mz = NULL;
4e416953
BS
727 rightmost = rb_last(&mctz->rb_root);
728 if (!rightmost)
729 goto done; /* Nothing to reclaim from */
730
731 mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
732 /*
733 * Remove the node now but someone else can add it back,
734 * we will to add it back at the end of reclaim to its correct
735 * position in the tree.
736 */
d79154bb
HD
737 __mem_cgroup_remove_exceeded(mz->memcg, mz, mctz);
738 if (!res_counter_soft_limit_excess(&mz->memcg->res) ||
739 !css_tryget(&mz->memcg->css))
4e416953
BS
740 goto retry;
741done:
742 return mz;
743}
744
745static struct mem_cgroup_per_zone *
746mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
747{
748 struct mem_cgroup_per_zone *mz;
749
750 spin_lock(&mctz->lock);
751 mz = __mem_cgroup_largest_soft_limit_node(mctz);
752 spin_unlock(&mctz->lock);
753 return mz;
754}
755
711d3d2c
KH
756/*
757 * Implementation Note: reading percpu statistics for memcg.
758 *
759 * Both of vmstat[] and percpu_counter has threshold and do periodic
760 * synchronization to implement "quick" read. There are trade-off between
761 * reading cost and precision of value. Then, we may have a chance to implement
762 * a periodic synchronizion of counter in memcg's counter.
763 *
764 * But this _read() function is used for user interface now. The user accounts
765 * memory usage by memory cgroup and he _always_ requires exact value because
766 * he accounts memory. Even if we provide quick-and-fuzzy read, we always
767 * have to visit all online cpus and make sum. So, for now, unnecessary
768 * synchronization is not implemented. (just implemented for cpu hotplug)
769 *
770 * If there are kernel internal actions which can make use of some not-exact
771 * value, and reading all cpu value can be performance bottleneck in some
772 * common workload, threashold and synchonization as vmstat[] should be
773 * implemented.
774 */
c0ff4b85 775static long mem_cgroup_read_stat(struct mem_cgroup *memcg,
7a159cc9 776 enum mem_cgroup_stat_index idx)
c62b1a3b 777{
7a159cc9 778 long val = 0;
c62b1a3b 779 int cpu;
c62b1a3b 780
711d3d2c
KH
781 get_online_cpus();
782 for_each_online_cpu(cpu)
c0ff4b85 783 val += per_cpu(memcg->stat->count[idx], cpu);
711d3d2c 784#ifdef CONFIG_HOTPLUG_CPU
c0ff4b85
R
785 spin_lock(&memcg->pcp_counter_lock);
786 val += memcg->nocpu_base.count[idx];
787 spin_unlock(&memcg->pcp_counter_lock);
711d3d2c
KH
788#endif
789 put_online_cpus();
c62b1a3b
KH
790 return val;
791}
792
c0ff4b85 793static void mem_cgroup_swap_statistics(struct mem_cgroup *memcg,
0c3e73e8
BS
794 bool charge)
795{
796 int val = (charge) ? 1 : -1;
bff6bb83 797 this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_SWAP], val);
0c3e73e8
BS
798}
799
c0ff4b85 800static unsigned long mem_cgroup_read_events(struct mem_cgroup *memcg,
e9f8974f
JW
801 enum mem_cgroup_events_index idx)
802{
803 unsigned long val = 0;
804 int cpu;
805
806 for_each_online_cpu(cpu)
c0ff4b85 807 val += per_cpu(memcg->stat->events[idx], cpu);
e9f8974f 808#ifdef CONFIG_HOTPLUG_CPU
c0ff4b85
R
809 spin_lock(&memcg->pcp_counter_lock);
810 val += memcg->nocpu_base.events[idx];
811 spin_unlock(&memcg->pcp_counter_lock);
e9f8974f
JW
812#endif
813 return val;
814}
815
c0ff4b85 816static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
b2402857 817 bool anon, int nr_pages)
d52aa412 818{
c62b1a3b
KH
819 preempt_disable();
820
b2402857
KH
821 /*
822 * Here, RSS means 'mapped anon' and anon's SwapCache. Shmem/tmpfs is
823 * counted as CACHE even if it's on ANON LRU.
824 */
825 if (anon)
826 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS],
c0ff4b85 827 nr_pages);
d52aa412 828 else
b2402857 829 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_CACHE],
c0ff4b85 830 nr_pages);
55e462b0 831
e401f176
KH
832 /* pagein of a big page is an event. So, ignore page size */
833 if (nr_pages > 0)
c0ff4b85 834 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGIN]);
3751d604 835 else {
c0ff4b85 836 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGOUT]);
3751d604
KH
837 nr_pages = -nr_pages; /* for event */
838 }
e401f176 839
13114716 840 __this_cpu_add(memcg->stat->nr_page_events, nr_pages);
2e72b634 841
c62b1a3b 842 preempt_enable();
6d12e2d8
KH
843}
844
bb2a0de9 845unsigned long
4d7dcca2 846mem_cgroup_get_lru_size(struct lruvec *lruvec, enum lru_list lru)
074291fe
KK
847{
848 struct mem_cgroup_per_zone *mz;
849
850 mz = container_of(lruvec, struct mem_cgroup_per_zone, lruvec);
851 return mz->lru_size[lru];
852}
853
854static unsigned long
c0ff4b85 855mem_cgroup_zone_nr_lru_pages(struct mem_cgroup *memcg, int nid, int zid,
bb2a0de9 856 unsigned int lru_mask)
889976db
YH
857{
858 struct mem_cgroup_per_zone *mz;
f156ab93 859 enum lru_list lru;
bb2a0de9
KH
860 unsigned long ret = 0;
861
c0ff4b85 862 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
bb2a0de9 863
f156ab93
HD
864 for_each_lru(lru) {
865 if (BIT(lru) & lru_mask)
866 ret += mz->lru_size[lru];
bb2a0de9
KH
867 }
868 return ret;
869}
870
871static unsigned long
c0ff4b85 872mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
bb2a0de9
KH
873 int nid, unsigned int lru_mask)
874{
889976db
YH
875 u64 total = 0;
876 int zid;
877
bb2a0de9 878 for (zid = 0; zid < MAX_NR_ZONES; zid++)
c0ff4b85
R
879 total += mem_cgroup_zone_nr_lru_pages(memcg,
880 nid, zid, lru_mask);
bb2a0de9 881
889976db
YH
882 return total;
883}
bb2a0de9 884
c0ff4b85 885static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
bb2a0de9 886 unsigned int lru_mask)
6d12e2d8 887{
889976db 888 int nid;
6d12e2d8
KH
889 u64 total = 0;
890
31aaea4a 891 for_each_node_state(nid, N_MEMORY)
c0ff4b85 892 total += mem_cgroup_node_nr_lru_pages(memcg, nid, lru_mask);
6d12e2d8 893 return total;
d52aa412
KH
894}
895
f53d7ce3
JW
896static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
897 enum mem_cgroup_events_target target)
7a159cc9
JW
898{
899 unsigned long val, next;
900
13114716 901 val = __this_cpu_read(memcg->stat->nr_page_events);
4799401f 902 next = __this_cpu_read(memcg->stat->targets[target]);
7a159cc9 903 /* from time_after() in jiffies.h */
f53d7ce3
JW
904 if ((long)next - (long)val < 0) {
905 switch (target) {
906 case MEM_CGROUP_TARGET_THRESH:
907 next = val + THRESHOLDS_EVENTS_TARGET;
908 break;
909 case MEM_CGROUP_TARGET_SOFTLIMIT:
910 next = val + SOFTLIMIT_EVENTS_TARGET;
911 break;
912 case MEM_CGROUP_TARGET_NUMAINFO:
913 next = val + NUMAINFO_EVENTS_TARGET;
914 break;
915 default:
916 break;
917 }
918 __this_cpu_write(memcg->stat->targets[target], next);
919 return true;
7a159cc9 920 }
f53d7ce3 921 return false;
d2265e6f
KH
922}
923
924/*
925 * Check events in order.
926 *
927 */
c0ff4b85 928static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
d2265e6f 929{
4799401f 930 preempt_disable();
d2265e6f 931 /* threshold event is triggered in finer grain than soft limit */
f53d7ce3
JW
932 if (unlikely(mem_cgroup_event_ratelimit(memcg,
933 MEM_CGROUP_TARGET_THRESH))) {
82b3f2a7
AM
934 bool do_softlimit;
935 bool do_numainfo __maybe_unused;
f53d7ce3
JW
936
937 do_softlimit = mem_cgroup_event_ratelimit(memcg,
938 MEM_CGROUP_TARGET_SOFTLIMIT);
939#if MAX_NUMNODES > 1
940 do_numainfo = mem_cgroup_event_ratelimit(memcg,
941 MEM_CGROUP_TARGET_NUMAINFO);
942#endif
943 preempt_enable();
944
c0ff4b85 945 mem_cgroup_threshold(memcg);
f53d7ce3 946 if (unlikely(do_softlimit))
c0ff4b85 947 mem_cgroup_update_tree(memcg, page);
453a9bf3 948#if MAX_NUMNODES > 1
f53d7ce3 949 if (unlikely(do_numainfo))
c0ff4b85 950 atomic_inc(&memcg->numainfo_events);
453a9bf3 951#endif
f53d7ce3
JW
952 } else
953 preempt_enable();
d2265e6f
KH
954}
955
d1a4c0b3 956struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
8cdea7c0 957{
b2145145
WL
958 return mem_cgroup_from_css(
959 cgroup_subsys_state(cont, mem_cgroup_subsys_id));
8cdea7c0
BS
960}
961
cf475ad2 962struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
78fb7466 963{
31a78f23
BS
964 /*
965 * mm_update_next_owner() may clear mm->owner to NULL
966 * if it races with swapoff, page migration, etc.
967 * So this can be called with p == NULL.
968 */
969 if (unlikely(!p))
970 return NULL;
971
b2145145 972 return mem_cgroup_from_css(task_subsys_state(p, mem_cgroup_subsys_id));
78fb7466
PE
973}
974
a433658c 975struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
54595fe2 976{
c0ff4b85 977 struct mem_cgroup *memcg = NULL;
0b7f569e
KH
978
979 if (!mm)
980 return NULL;
54595fe2
KH
981 /*
982 * Because we have no locks, mm->owner's may be being moved to other
983 * cgroup. We use css_tryget() here even if this looks
984 * pessimistic (rather than adding locks here).
985 */
986 rcu_read_lock();
987 do {
c0ff4b85
R
988 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
989 if (unlikely(!memcg))
54595fe2 990 break;
c0ff4b85 991 } while (!css_tryget(&memcg->css));
54595fe2 992 rcu_read_unlock();
c0ff4b85 993 return memcg;
54595fe2
KH
994}
995
5660048c
JW
996/**
997 * mem_cgroup_iter - iterate over memory cgroup hierarchy
998 * @root: hierarchy root
999 * @prev: previously returned memcg, NULL on first invocation
1000 * @reclaim: cookie for shared reclaim walks, NULL for full walks
1001 *
1002 * Returns references to children of the hierarchy below @root, or
1003 * @root itself, or %NULL after a full round-trip.
1004 *
1005 * Caller must pass the return value in @prev on subsequent
1006 * invocations for reference counting, or use mem_cgroup_iter_break()
1007 * to cancel a hierarchy walk before the round-trip is complete.
1008 *
1009 * Reclaimers can specify a zone and a priority level in @reclaim to
1010 * divide up the memcgs in the hierarchy among all concurrent
1011 * reclaimers operating on the same zone and priority.
1012 */
1013struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
1014 struct mem_cgroup *prev,
1015 struct mem_cgroup_reclaim_cookie *reclaim)
14067bb3 1016{
9f3a0d09
JW
1017 struct mem_cgroup *memcg = NULL;
1018 int id = 0;
711d3d2c 1019
5660048c
JW
1020 if (mem_cgroup_disabled())
1021 return NULL;
1022
9f3a0d09
JW
1023 if (!root)
1024 root = root_mem_cgroup;
7d74b06f 1025
9f3a0d09
JW
1026 if (prev && !reclaim)
1027 id = css_id(&prev->css);
14067bb3 1028
9f3a0d09
JW
1029 if (prev && prev != root)
1030 css_put(&prev->css);
14067bb3 1031
9f3a0d09
JW
1032 if (!root->use_hierarchy && root != root_mem_cgroup) {
1033 if (prev)
1034 return NULL;
1035 return root;
1036 }
14067bb3 1037
9f3a0d09 1038 while (!memcg) {
527a5ec9 1039 struct mem_cgroup_reclaim_iter *uninitialized_var(iter);
9f3a0d09 1040 struct cgroup_subsys_state *css;
711d3d2c 1041
527a5ec9
JW
1042 if (reclaim) {
1043 int nid = zone_to_nid(reclaim->zone);
1044 int zid = zone_idx(reclaim->zone);
1045 struct mem_cgroup_per_zone *mz;
1046
1047 mz = mem_cgroup_zoneinfo(root, nid, zid);
1048 iter = &mz->reclaim_iter[reclaim->priority];
1049 if (prev && reclaim->generation != iter->generation)
1050 return NULL;
1051 id = iter->position;
1052 }
7d74b06f 1053
9f3a0d09
JW
1054 rcu_read_lock();
1055 css = css_get_next(&mem_cgroup_subsys, id + 1, &root->css, &id);
1056 if (css) {
1057 if (css == &root->css || css_tryget(css))
b2145145 1058 memcg = mem_cgroup_from_css(css);
9f3a0d09
JW
1059 } else
1060 id = 0;
14067bb3 1061 rcu_read_unlock();
14067bb3 1062
527a5ec9
JW
1063 if (reclaim) {
1064 iter->position = id;
1065 if (!css)
1066 iter->generation++;
1067 else if (!prev && memcg)
1068 reclaim->generation = iter->generation;
1069 }
9f3a0d09
JW
1070
1071 if (prev && !css)
1072 return NULL;
1073 }
1074 return memcg;
14067bb3 1075}
7d74b06f 1076
5660048c
JW
1077/**
1078 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1079 * @root: hierarchy root
1080 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1081 */
1082void mem_cgroup_iter_break(struct mem_cgroup *root,
1083 struct mem_cgroup *prev)
9f3a0d09
JW
1084{
1085 if (!root)
1086 root = root_mem_cgroup;
1087 if (prev && prev != root)
1088 css_put(&prev->css);
1089}
7d74b06f 1090
9f3a0d09
JW
1091/*
1092 * Iteration constructs for visiting all cgroups (under a tree). If
1093 * loops are exited prematurely (break), mem_cgroup_iter_break() must
1094 * be used for reference counting.
1095 */
1096#define for_each_mem_cgroup_tree(iter, root) \
527a5ec9 1097 for (iter = mem_cgroup_iter(root, NULL, NULL); \
9f3a0d09 1098 iter != NULL; \
527a5ec9 1099 iter = mem_cgroup_iter(root, iter, NULL))
711d3d2c 1100
9f3a0d09 1101#define for_each_mem_cgroup(iter) \
527a5ec9 1102 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
9f3a0d09 1103 iter != NULL; \
527a5ec9 1104 iter = mem_cgroup_iter(NULL, iter, NULL))
14067bb3 1105
68ae564b 1106void __mem_cgroup_count_vm_event(struct mm_struct *mm, enum vm_event_item idx)
456f998e 1107{
c0ff4b85 1108 struct mem_cgroup *memcg;
456f998e 1109
456f998e 1110 rcu_read_lock();
c0ff4b85
R
1111 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
1112 if (unlikely(!memcg))
456f998e
YH
1113 goto out;
1114
1115 switch (idx) {
456f998e 1116 case PGFAULT:
0e574a93
JW
1117 this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGFAULT]);
1118 break;
1119 case PGMAJFAULT:
1120 this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGMAJFAULT]);
456f998e
YH
1121 break;
1122 default:
1123 BUG();
1124 }
1125out:
1126 rcu_read_unlock();
1127}
68ae564b 1128EXPORT_SYMBOL(__mem_cgroup_count_vm_event);
456f998e 1129
925b7673
JW
1130/**
1131 * mem_cgroup_zone_lruvec - get the lru list vector for a zone and memcg
1132 * @zone: zone of the wanted lruvec
fa9add64 1133 * @memcg: memcg of the wanted lruvec
925b7673
JW
1134 *
1135 * Returns the lru list vector holding pages for the given @zone and
1136 * @mem. This can be the global zone lruvec, if the memory controller
1137 * is disabled.
1138 */
1139struct lruvec *mem_cgroup_zone_lruvec(struct zone *zone,
1140 struct mem_cgroup *memcg)
1141{
1142 struct mem_cgroup_per_zone *mz;
bea8c150 1143 struct lruvec *lruvec;
925b7673 1144
bea8c150
HD
1145 if (mem_cgroup_disabled()) {
1146 lruvec = &zone->lruvec;
1147 goto out;
1148 }
925b7673
JW
1149
1150 mz = mem_cgroup_zoneinfo(memcg, zone_to_nid(zone), zone_idx(zone));
bea8c150
HD
1151 lruvec = &mz->lruvec;
1152out:
1153 /*
1154 * Since a node can be onlined after the mem_cgroup was created,
1155 * we have to be prepared to initialize lruvec->zone here;
1156 * and if offlined then reonlined, we need to reinitialize it.
1157 */
1158 if (unlikely(lruvec->zone != zone))
1159 lruvec->zone = zone;
1160 return lruvec;
925b7673
JW
1161}
1162
08e552c6
KH
1163/*
1164 * Following LRU functions are allowed to be used without PCG_LOCK.
1165 * Operations are called by routine of global LRU independently from memcg.
1166 * What we have to take care of here is validness of pc->mem_cgroup.
1167 *
1168 * Changes to pc->mem_cgroup happens when
1169 * 1. charge
1170 * 2. moving account
1171 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
1172 * It is added to LRU before charge.
1173 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
1174 * When moving account, the page is not on LRU. It's isolated.
1175 */
4f98a2fe 1176
925b7673 1177/**
fa9add64 1178 * mem_cgroup_page_lruvec - return lruvec for adding an lru page
925b7673 1179 * @page: the page
fa9add64 1180 * @zone: zone of the page
925b7673 1181 */
fa9add64 1182struct lruvec *mem_cgroup_page_lruvec(struct page *page, struct zone *zone)
08e552c6 1183{
08e552c6 1184 struct mem_cgroup_per_zone *mz;
925b7673
JW
1185 struct mem_cgroup *memcg;
1186 struct page_cgroup *pc;
bea8c150 1187 struct lruvec *lruvec;
6d12e2d8 1188
bea8c150
HD
1189 if (mem_cgroup_disabled()) {
1190 lruvec = &zone->lruvec;
1191 goto out;
1192 }
925b7673 1193
08e552c6 1194 pc = lookup_page_cgroup(page);
38c5d72f 1195 memcg = pc->mem_cgroup;
7512102c
HD
1196
1197 /*
fa9add64 1198 * Surreptitiously switch any uncharged offlist page to root:
7512102c
HD
1199 * an uncharged page off lru does nothing to secure
1200 * its former mem_cgroup from sudden removal.
1201 *
1202 * Our caller holds lru_lock, and PageCgroupUsed is updated
1203 * under page_cgroup lock: between them, they make all uses
1204 * of pc->mem_cgroup safe.
1205 */
fa9add64 1206 if (!PageLRU(page) && !PageCgroupUsed(pc) && memcg != root_mem_cgroup)
7512102c
HD
1207 pc->mem_cgroup = memcg = root_mem_cgroup;
1208
925b7673 1209 mz = page_cgroup_zoneinfo(memcg, page);
bea8c150
HD
1210 lruvec = &mz->lruvec;
1211out:
1212 /*
1213 * Since a node can be onlined after the mem_cgroup was created,
1214 * we have to be prepared to initialize lruvec->zone here;
1215 * and if offlined then reonlined, we need to reinitialize it.
1216 */
1217 if (unlikely(lruvec->zone != zone))
1218 lruvec->zone = zone;
1219 return lruvec;
08e552c6 1220}
b69408e8 1221
925b7673 1222/**
fa9add64
HD
1223 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1224 * @lruvec: mem_cgroup per zone lru vector
1225 * @lru: index of lru list the page is sitting on
1226 * @nr_pages: positive when adding or negative when removing
925b7673 1227 *
fa9add64
HD
1228 * This function must be called when a page is added to or removed from an
1229 * lru list.
3f58a829 1230 */
fa9add64
HD
1231void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
1232 int nr_pages)
3f58a829
MK
1233{
1234 struct mem_cgroup_per_zone *mz;
fa9add64 1235 unsigned long *lru_size;
3f58a829
MK
1236
1237 if (mem_cgroup_disabled())
1238 return;
1239
fa9add64
HD
1240 mz = container_of(lruvec, struct mem_cgroup_per_zone, lruvec);
1241 lru_size = mz->lru_size + lru;
1242 *lru_size += nr_pages;
1243 VM_BUG_ON((long)(*lru_size) < 0);
08e552c6 1244}
544122e5 1245
3e92041d 1246/*
c0ff4b85 1247 * Checks whether given mem is same or in the root_mem_cgroup's
3e92041d
MH
1248 * hierarchy subtree
1249 */
c3ac9a8a
JW
1250bool __mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
1251 struct mem_cgroup *memcg)
3e92041d 1252{
91c63734
JW
1253 if (root_memcg == memcg)
1254 return true;
3a981f48 1255 if (!root_memcg->use_hierarchy || !memcg)
91c63734 1256 return false;
c3ac9a8a
JW
1257 return css_is_ancestor(&memcg->css, &root_memcg->css);
1258}
1259
1260static bool mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
1261 struct mem_cgroup *memcg)
1262{
1263 bool ret;
1264
91c63734 1265 rcu_read_lock();
c3ac9a8a 1266 ret = __mem_cgroup_same_or_subtree(root_memcg, memcg);
91c63734
JW
1267 rcu_read_unlock();
1268 return ret;
3e92041d
MH
1269}
1270
c0ff4b85 1271int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *memcg)
4c4a2214
DR
1272{
1273 int ret;
0b7f569e 1274 struct mem_cgroup *curr = NULL;
158e0a2d 1275 struct task_struct *p;
4c4a2214 1276
158e0a2d 1277 p = find_lock_task_mm(task);
de077d22
DR
1278 if (p) {
1279 curr = try_get_mem_cgroup_from_mm(p->mm);
1280 task_unlock(p);
1281 } else {
1282 /*
1283 * All threads may have already detached their mm's, but the oom
1284 * killer still needs to detect if they have already been oom
1285 * killed to prevent needlessly killing additional tasks.
1286 */
1287 task_lock(task);
1288 curr = mem_cgroup_from_task(task);
1289 if (curr)
1290 css_get(&curr->css);
1291 task_unlock(task);
1292 }
0b7f569e
KH
1293 if (!curr)
1294 return 0;
d31f56db 1295 /*
c0ff4b85 1296 * We should check use_hierarchy of "memcg" not "curr". Because checking
d31f56db 1297 * use_hierarchy of "curr" here make this function true if hierarchy is
c0ff4b85
R
1298 * enabled in "curr" and "curr" is a child of "memcg" in *cgroup*
1299 * hierarchy(even if use_hierarchy is disabled in "memcg").
d31f56db 1300 */
c0ff4b85 1301 ret = mem_cgroup_same_or_subtree(memcg, curr);
0b7f569e 1302 css_put(&curr->css);
4c4a2214
DR
1303 return ret;
1304}
1305
c56d5c7d 1306int mem_cgroup_inactive_anon_is_low(struct lruvec *lruvec)
14797e23 1307{
9b272977 1308 unsigned long inactive_ratio;
14797e23 1309 unsigned long inactive;
9b272977 1310 unsigned long active;
c772be93 1311 unsigned long gb;
14797e23 1312
4d7dcca2
HD
1313 inactive = mem_cgroup_get_lru_size(lruvec, LRU_INACTIVE_ANON);
1314 active = mem_cgroup_get_lru_size(lruvec, LRU_ACTIVE_ANON);
14797e23 1315
c772be93
KM
1316 gb = (inactive + active) >> (30 - PAGE_SHIFT);
1317 if (gb)
1318 inactive_ratio = int_sqrt(10 * gb);
1319 else
1320 inactive_ratio = 1;
1321
9b272977 1322 return inactive * inactive_ratio < active;
14797e23
KM
1323}
1324
c56d5c7d 1325int mem_cgroup_inactive_file_is_low(struct lruvec *lruvec)
56e49d21
RR
1326{
1327 unsigned long active;
1328 unsigned long inactive;
1329
4d7dcca2
HD
1330 inactive = mem_cgroup_get_lru_size(lruvec, LRU_INACTIVE_FILE);
1331 active = mem_cgroup_get_lru_size(lruvec, LRU_ACTIVE_FILE);
56e49d21
RR
1332
1333 return (active > inactive);
1334}
1335
6d61ef40
BS
1336#define mem_cgroup_from_res_counter(counter, member) \
1337 container_of(counter, struct mem_cgroup, member)
1338
19942822 1339/**
9d11ea9f 1340 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
dad7557e 1341 * @memcg: the memory cgroup
19942822 1342 *
9d11ea9f 1343 * Returns the maximum amount of memory @mem can be charged with, in
7ec99d62 1344 * pages.
19942822 1345 */
c0ff4b85 1346static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
19942822 1347{
9d11ea9f
JW
1348 unsigned long long margin;
1349
c0ff4b85 1350 margin = res_counter_margin(&memcg->res);
9d11ea9f 1351 if (do_swap_account)
c0ff4b85 1352 margin = min(margin, res_counter_margin(&memcg->memsw));
7ec99d62 1353 return margin >> PAGE_SHIFT;
19942822
JW
1354}
1355
1f4c025b 1356int mem_cgroup_swappiness(struct mem_cgroup *memcg)
a7885eb8
KM
1357{
1358 struct cgroup *cgrp = memcg->css.cgroup;
a7885eb8
KM
1359
1360 /* root ? */
1361 if (cgrp->parent == NULL)
1362 return vm_swappiness;
1363
bf1ff263 1364 return memcg->swappiness;
a7885eb8
KM
1365}
1366
619d094b
KH
1367/*
1368 * memcg->moving_account is used for checking possibility that some thread is
1369 * calling move_account(). When a thread on CPU-A starts moving pages under
1370 * a memcg, other threads should check memcg->moving_account under
1371 * rcu_read_lock(), like this:
1372 *
1373 * CPU-A CPU-B
1374 * rcu_read_lock()
1375 * memcg->moving_account+1 if (memcg->mocing_account)
1376 * take heavy locks.
1377 * synchronize_rcu() update something.
1378 * rcu_read_unlock()
1379 * start move here.
1380 */
4331f7d3
KH
1381
1382/* for quick checking without looking up memcg */
1383atomic_t memcg_moving __read_mostly;
1384
c0ff4b85 1385static void mem_cgroup_start_move(struct mem_cgroup *memcg)
32047e2a 1386{
4331f7d3 1387 atomic_inc(&memcg_moving);
619d094b 1388 atomic_inc(&memcg->moving_account);
32047e2a
KH
1389 synchronize_rcu();
1390}
1391
c0ff4b85 1392static void mem_cgroup_end_move(struct mem_cgroup *memcg)
32047e2a 1393{
619d094b
KH
1394 /*
1395 * Now, mem_cgroup_clear_mc() may call this function with NULL.
1396 * We check NULL in callee rather than caller.
1397 */
4331f7d3
KH
1398 if (memcg) {
1399 atomic_dec(&memcg_moving);
619d094b 1400 atomic_dec(&memcg->moving_account);
4331f7d3 1401 }
32047e2a 1402}
619d094b 1403
32047e2a
KH
1404/*
1405 * 2 routines for checking "mem" is under move_account() or not.
1406 *
13fd1dd9
AM
1407 * mem_cgroup_stolen() - checking whether a cgroup is mc.from or not. This
1408 * is used for avoiding races in accounting. If true,
32047e2a
KH
1409 * pc->mem_cgroup may be overwritten.
1410 *
1411 * mem_cgroup_under_move() - checking a cgroup is mc.from or mc.to or
1412 * under hierarchy of moving cgroups. This is for
1413 * waiting at hith-memory prressure caused by "move".
1414 */
1415
13fd1dd9 1416static bool mem_cgroup_stolen(struct mem_cgroup *memcg)
32047e2a
KH
1417{
1418 VM_BUG_ON(!rcu_read_lock_held());
619d094b 1419 return atomic_read(&memcg->moving_account) > 0;
32047e2a 1420}
4b534334 1421
c0ff4b85 1422static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
4b534334 1423{
2bd9bb20
KH
1424 struct mem_cgroup *from;
1425 struct mem_cgroup *to;
4b534334 1426 bool ret = false;
2bd9bb20
KH
1427 /*
1428 * Unlike task_move routines, we access mc.to, mc.from not under
1429 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1430 */
1431 spin_lock(&mc.lock);
1432 from = mc.from;
1433 to = mc.to;
1434 if (!from)
1435 goto unlock;
3e92041d 1436
c0ff4b85
R
1437 ret = mem_cgroup_same_or_subtree(memcg, from)
1438 || mem_cgroup_same_or_subtree(memcg, to);
2bd9bb20
KH
1439unlock:
1440 spin_unlock(&mc.lock);
4b534334
KH
1441 return ret;
1442}
1443
c0ff4b85 1444static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
4b534334
KH
1445{
1446 if (mc.moving_task && current != mc.moving_task) {
c0ff4b85 1447 if (mem_cgroup_under_move(memcg)) {
4b534334
KH
1448 DEFINE_WAIT(wait);
1449 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1450 /* moving charge context might have finished. */
1451 if (mc.moving_task)
1452 schedule();
1453 finish_wait(&mc.waitq, &wait);
1454 return true;
1455 }
1456 }
1457 return false;
1458}
1459
312734c0
KH
1460/*
1461 * Take this lock when
1462 * - a code tries to modify page's memcg while it's USED.
1463 * - a code tries to modify page state accounting in a memcg.
13fd1dd9 1464 * see mem_cgroup_stolen(), too.
312734c0
KH
1465 */
1466static void move_lock_mem_cgroup(struct mem_cgroup *memcg,
1467 unsigned long *flags)
1468{
1469 spin_lock_irqsave(&memcg->move_lock, *flags);
1470}
1471
1472static void move_unlock_mem_cgroup(struct mem_cgroup *memcg,
1473 unsigned long *flags)
1474{
1475 spin_unlock_irqrestore(&memcg->move_lock, *flags);
1476}
1477
e222432b 1478/**
6a6135b6 1479 * mem_cgroup_print_oom_info: Called from OOM with tasklist_lock held in read mode.
e222432b
BS
1480 * @memcg: The memory cgroup that went over limit
1481 * @p: Task that is going to be killed
1482 *
1483 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1484 * enabled
1485 */
1486void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1487{
1488 struct cgroup *task_cgrp;
1489 struct cgroup *mem_cgrp;
1490 /*
1491 * Need a buffer in BSS, can't rely on allocations. The code relies
1492 * on the assumption that OOM is serialized for memory controller.
1493 * If this assumption is broken, revisit this code.
1494 */
1495 static char memcg_name[PATH_MAX];
1496 int ret;
1497
d31f56db 1498 if (!memcg || !p)
e222432b
BS
1499 return;
1500
e222432b
BS
1501 rcu_read_lock();
1502
1503 mem_cgrp = memcg->css.cgroup;
1504 task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
1505
1506 ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
1507 if (ret < 0) {
1508 /*
1509 * Unfortunately, we are unable to convert to a useful name
1510 * But we'll still print out the usage information
1511 */
1512 rcu_read_unlock();
1513 goto done;
1514 }
1515 rcu_read_unlock();
1516
1517 printk(KERN_INFO "Task in %s killed", memcg_name);
1518
1519 rcu_read_lock();
1520 ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
1521 if (ret < 0) {
1522 rcu_read_unlock();
1523 goto done;
1524 }
1525 rcu_read_unlock();
1526
1527 /*
1528 * Continues from above, so we don't need an KERN_ level
1529 */
1530 printk(KERN_CONT " as a result of limit of %s\n", memcg_name);
1531done:
1532
1533 printk(KERN_INFO "memory: usage %llukB, limit %llukB, failcnt %llu\n",
1534 res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
1535 res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
1536 res_counter_read_u64(&memcg->res, RES_FAILCNT));
1537 printk(KERN_INFO "memory+swap: usage %llukB, limit %llukB, "
1538 "failcnt %llu\n",
1539 res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
1540 res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
1541 res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
510fc4e1
GC
1542 printk(KERN_INFO "kmem: usage %llukB, limit %llukB, failcnt %llu\n",
1543 res_counter_read_u64(&memcg->kmem, RES_USAGE) >> 10,
1544 res_counter_read_u64(&memcg->kmem, RES_LIMIT) >> 10,
1545 res_counter_read_u64(&memcg->kmem, RES_FAILCNT));
e222432b
BS
1546}
1547
81d39c20
KH
1548/*
1549 * This function returns the number of memcg under hierarchy tree. Returns
1550 * 1(self count) if no children.
1551 */
c0ff4b85 1552static int mem_cgroup_count_children(struct mem_cgroup *memcg)
81d39c20
KH
1553{
1554 int num = 0;
7d74b06f
KH
1555 struct mem_cgroup *iter;
1556
c0ff4b85 1557 for_each_mem_cgroup_tree(iter, memcg)
7d74b06f 1558 num++;
81d39c20
KH
1559 return num;
1560}
1561
a63d83f4
DR
1562/*
1563 * Return the memory (and swap, if configured) limit for a memcg.
1564 */
9cbb78bb 1565static u64 mem_cgroup_get_limit(struct mem_cgroup *memcg)
a63d83f4
DR
1566{
1567 u64 limit;
a63d83f4 1568
f3e8eb70 1569 limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
f3e8eb70 1570
a63d83f4 1571 /*
9a5a8f19 1572 * Do not consider swap space if we cannot swap due to swappiness
a63d83f4 1573 */
9a5a8f19
MH
1574 if (mem_cgroup_swappiness(memcg)) {
1575 u64 memsw;
1576
1577 limit += total_swap_pages << PAGE_SHIFT;
1578 memsw = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
1579
1580 /*
1581 * If memsw is finite and limits the amount of swap space
1582 * available to this memcg, return that limit.
1583 */
1584 limit = min(limit, memsw);
1585 }
1586
1587 return limit;
a63d83f4
DR
1588}
1589
19965460
DR
1590static void mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
1591 int order)
9cbb78bb
DR
1592{
1593 struct mem_cgroup *iter;
1594 unsigned long chosen_points = 0;
1595 unsigned long totalpages;
1596 unsigned int points = 0;
1597 struct task_struct *chosen = NULL;
1598
876aafbf
DR
1599 /*
1600 * If current has a pending SIGKILL, then automatically select it. The
1601 * goal is to allow it to allocate so that it may quickly exit and free
1602 * its memory.
1603 */
1604 if (fatal_signal_pending(current)) {
1605 set_thread_flag(TIF_MEMDIE);
1606 return;
1607 }
1608
1609 check_panic_on_oom(CONSTRAINT_MEMCG, gfp_mask, order, NULL);
9cbb78bb
DR
1610 totalpages = mem_cgroup_get_limit(memcg) >> PAGE_SHIFT ? : 1;
1611 for_each_mem_cgroup_tree(iter, memcg) {
1612 struct cgroup *cgroup = iter->css.cgroup;
1613 struct cgroup_iter it;
1614 struct task_struct *task;
1615
1616 cgroup_iter_start(cgroup, &it);
1617 while ((task = cgroup_iter_next(cgroup, &it))) {
1618 switch (oom_scan_process_thread(task, totalpages, NULL,
1619 false)) {
1620 case OOM_SCAN_SELECT:
1621 if (chosen)
1622 put_task_struct(chosen);
1623 chosen = task;
1624 chosen_points = ULONG_MAX;
1625 get_task_struct(chosen);
1626 /* fall through */
1627 case OOM_SCAN_CONTINUE:
1628 continue;
1629 case OOM_SCAN_ABORT:
1630 cgroup_iter_end(cgroup, &it);
1631 mem_cgroup_iter_break(memcg, iter);
1632 if (chosen)
1633 put_task_struct(chosen);
1634 return;
1635 case OOM_SCAN_OK:
1636 break;
1637 };
1638 points = oom_badness(task, memcg, NULL, totalpages);
1639 if (points > chosen_points) {
1640 if (chosen)
1641 put_task_struct(chosen);
1642 chosen = task;
1643 chosen_points = points;
1644 get_task_struct(chosen);
1645 }
1646 }
1647 cgroup_iter_end(cgroup, &it);
1648 }
1649
1650 if (!chosen)
1651 return;
1652 points = chosen_points * 1000 / totalpages;
9cbb78bb
DR
1653 oom_kill_process(chosen, gfp_mask, order, points, totalpages, memcg,
1654 NULL, "Memory cgroup out of memory");
9cbb78bb
DR
1655}
1656
5660048c
JW
1657static unsigned long mem_cgroup_reclaim(struct mem_cgroup *memcg,
1658 gfp_t gfp_mask,
1659 unsigned long flags)
1660{
1661 unsigned long total = 0;
1662 bool noswap = false;
1663 int loop;
1664
1665 if (flags & MEM_CGROUP_RECLAIM_NOSWAP)
1666 noswap = true;
1667 if (!(flags & MEM_CGROUP_RECLAIM_SHRINK) && memcg->memsw_is_minimum)
1668 noswap = true;
1669
1670 for (loop = 0; loop < MEM_CGROUP_MAX_RECLAIM_LOOPS; loop++) {
1671 if (loop)
1672 drain_all_stock_async(memcg);
1673 total += try_to_free_mem_cgroup_pages(memcg, gfp_mask, noswap);
1674 /*
1675 * Allow limit shrinkers, which are triggered directly
1676 * by userspace, to catch signals and stop reclaim
1677 * after minimal progress, regardless of the margin.
1678 */
1679 if (total && (flags & MEM_CGROUP_RECLAIM_SHRINK))
1680 break;
1681 if (mem_cgroup_margin(memcg))
1682 break;
1683 /*
1684 * If nothing was reclaimed after two attempts, there
1685 * may be no reclaimable pages in this hierarchy.
1686 */
1687 if (loop && !total)
1688 break;
1689 }
1690 return total;
1691}
1692
4d0c066d
KH
1693/**
1694 * test_mem_cgroup_node_reclaimable
dad7557e 1695 * @memcg: the target memcg
4d0c066d
KH
1696 * @nid: the node ID to be checked.
1697 * @noswap : specify true here if the user wants flle only information.
1698 *
1699 * This function returns whether the specified memcg contains any
1700 * reclaimable pages on a node. Returns true if there are any reclaimable
1701 * pages in the node.
1702 */
c0ff4b85 1703static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *memcg,
4d0c066d
KH
1704 int nid, bool noswap)
1705{
c0ff4b85 1706 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_FILE))
4d0c066d
KH
1707 return true;
1708 if (noswap || !total_swap_pages)
1709 return false;
c0ff4b85 1710 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_ANON))
4d0c066d
KH
1711 return true;
1712 return false;
1713
1714}
889976db
YH
1715#if MAX_NUMNODES > 1
1716
1717/*
1718 * Always updating the nodemask is not very good - even if we have an empty
1719 * list or the wrong list here, we can start from some node and traverse all
1720 * nodes based on the zonelist. So update the list loosely once per 10 secs.
1721 *
1722 */
c0ff4b85 1723static void mem_cgroup_may_update_nodemask(struct mem_cgroup *memcg)
889976db
YH
1724{
1725 int nid;
453a9bf3
KH
1726 /*
1727 * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
1728 * pagein/pageout changes since the last update.
1729 */
c0ff4b85 1730 if (!atomic_read(&memcg->numainfo_events))
453a9bf3 1731 return;
c0ff4b85 1732 if (atomic_inc_return(&memcg->numainfo_updating) > 1)
889976db
YH
1733 return;
1734
889976db 1735 /* make a nodemask where this memcg uses memory from */
31aaea4a 1736 memcg->scan_nodes = node_states[N_MEMORY];
889976db 1737
31aaea4a 1738 for_each_node_mask(nid, node_states[N_MEMORY]) {
889976db 1739
c0ff4b85
R
1740 if (!test_mem_cgroup_node_reclaimable(memcg, nid, false))
1741 node_clear(nid, memcg->scan_nodes);
889976db 1742 }
453a9bf3 1743
c0ff4b85
R
1744 atomic_set(&memcg->numainfo_events, 0);
1745 atomic_set(&memcg->numainfo_updating, 0);
889976db
YH
1746}
1747
1748/*
1749 * Selecting a node where we start reclaim from. Because what we need is just
1750 * reducing usage counter, start from anywhere is O,K. Considering
1751 * memory reclaim from current node, there are pros. and cons.
1752 *
1753 * Freeing memory from current node means freeing memory from a node which
1754 * we'll use or we've used. So, it may make LRU bad. And if several threads
1755 * hit limits, it will see a contention on a node. But freeing from remote
1756 * node means more costs for memory reclaim because of memory latency.
1757 *
1758 * Now, we use round-robin. Better algorithm is welcomed.
1759 */
c0ff4b85 1760int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
889976db
YH
1761{
1762 int node;
1763
c0ff4b85
R
1764 mem_cgroup_may_update_nodemask(memcg);
1765 node = memcg->last_scanned_node;
889976db 1766
c0ff4b85 1767 node = next_node(node, memcg->scan_nodes);
889976db 1768 if (node == MAX_NUMNODES)
c0ff4b85 1769 node = first_node(memcg->scan_nodes);
889976db
YH
1770 /*
1771 * We call this when we hit limit, not when pages are added to LRU.
1772 * No LRU may hold pages because all pages are UNEVICTABLE or
1773 * memcg is too small and all pages are not on LRU. In that case,
1774 * we use curret node.
1775 */
1776 if (unlikely(node == MAX_NUMNODES))
1777 node = numa_node_id();
1778
c0ff4b85 1779 memcg->last_scanned_node = node;
889976db
YH
1780 return node;
1781}
1782
4d0c066d
KH
1783/*
1784 * Check all nodes whether it contains reclaimable pages or not.
1785 * For quick scan, we make use of scan_nodes. This will allow us to skip
1786 * unused nodes. But scan_nodes is lazily updated and may not cotain
1787 * enough new information. We need to do double check.
1788 */
6bbda35c 1789static bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
4d0c066d
KH
1790{
1791 int nid;
1792
1793 /*
1794 * quick check...making use of scan_node.
1795 * We can skip unused nodes.
1796 */
c0ff4b85
R
1797 if (!nodes_empty(memcg->scan_nodes)) {
1798 for (nid = first_node(memcg->scan_nodes);
4d0c066d 1799 nid < MAX_NUMNODES;
c0ff4b85 1800 nid = next_node(nid, memcg->scan_nodes)) {
4d0c066d 1801
c0ff4b85 1802 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
4d0c066d
KH
1803 return true;
1804 }
1805 }
1806 /*
1807 * Check rest of nodes.
1808 */
31aaea4a 1809 for_each_node_state(nid, N_MEMORY) {
c0ff4b85 1810 if (node_isset(nid, memcg->scan_nodes))
4d0c066d 1811 continue;
c0ff4b85 1812 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
4d0c066d
KH
1813 return true;
1814 }
1815 return false;
1816}
1817
889976db 1818#else
c0ff4b85 1819int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
889976db
YH
1820{
1821 return 0;
1822}
4d0c066d 1823
6bbda35c 1824static bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
4d0c066d 1825{
c0ff4b85 1826 return test_mem_cgroup_node_reclaimable(memcg, 0, noswap);
4d0c066d 1827}
889976db
YH
1828#endif
1829
5660048c
JW
1830static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
1831 struct zone *zone,
1832 gfp_t gfp_mask,
1833 unsigned long *total_scanned)
6d61ef40 1834{
9f3a0d09 1835 struct mem_cgroup *victim = NULL;
5660048c 1836 int total = 0;
04046e1a 1837 int loop = 0;
9d11ea9f 1838 unsigned long excess;
185efc0f 1839 unsigned long nr_scanned;
527a5ec9
JW
1840 struct mem_cgroup_reclaim_cookie reclaim = {
1841 .zone = zone,
1842 .priority = 0,
1843 };
9d11ea9f 1844
c0ff4b85 1845 excess = res_counter_soft_limit_excess(&root_memcg->res) >> PAGE_SHIFT;
04046e1a 1846
4e416953 1847 while (1) {
527a5ec9 1848 victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
9f3a0d09 1849 if (!victim) {
04046e1a 1850 loop++;
4e416953
BS
1851 if (loop >= 2) {
1852 /*
1853 * If we have not been able to reclaim
1854 * anything, it might because there are
1855 * no reclaimable pages under this hierarchy
1856 */
5660048c 1857 if (!total)
4e416953 1858 break;
4e416953 1859 /*
25985edc 1860 * We want to do more targeted reclaim.
4e416953
BS
1861 * excess >> 2 is not to excessive so as to
1862 * reclaim too much, nor too less that we keep
1863 * coming back to reclaim from this cgroup
1864 */
1865 if (total >= (excess >> 2) ||
9f3a0d09 1866 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
4e416953 1867 break;
4e416953 1868 }
9f3a0d09 1869 continue;
4e416953 1870 }
5660048c 1871 if (!mem_cgroup_reclaimable(victim, false))
6d61ef40 1872 continue;
5660048c
JW
1873 total += mem_cgroup_shrink_node_zone(victim, gfp_mask, false,
1874 zone, &nr_scanned);
1875 *total_scanned += nr_scanned;
1876 if (!res_counter_soft_limit_excess(&root_memcg->res))
9f3a0d09 1877 break;
6d61ef40 1878 }
9f3a0d09 1879 mem_cgroup_iter_break(root_memcg, victim);
04046e1a 1880 return total;
6d61ef40
BS
1881}
1882
867578cb
KH
1883/*
1884 * Check OOM-Killer is already running under our hierarchy.
1885 * If someone is running, return false.
1af8efe9 1886 * Has to be called with memcg_oom_lock
867578cb 1887 */
c0ff4b85 1888static bool mem_cgroup_oom_lock(struct mem_cgroup *memcg)
867578cb 1889{
79dfdacc 1890 struct mem_cgroup *iter, *failed = NULL;
a636b327 1891
9f3a0d09 1892 for_each_mem_cgroup_tree(iter, memcg) {
23751be0 1893 if (iter->oom_lock) {
79dfdacc
MH
1894 /*
1895 * this subtree of our hierarchy is already locked
1896 * so we cannot give a lock.
1897 */
79dfdacc 1898 failed = iter;
9f3a0d09
JW
1899 mem_cgroup_iter_break(memcg, iter);
1900 break;
23751be0
JW
1901 } else
1902 iter->oom_lock = true;
7d74b06f 1903 }
867578cb 1904
79dfdacc 1905 if (!failed)
23751be0 1906 return true;
79dfdacc
MH
1907
1908 /*
1909 * OK, we failed to lock the whole subtree so we have to clean up
1910 * what we set up to the failing subtree
1911 */
9f3a0d09 1912 for_each_mem_cgroup_tree(iter, memcg) {
79dfdacc 1913 if (iter == failed) {
9f3a0d09
JW
1914 mem_cgroup_iter_break(memcg, iter);
1915 break;
79dfdacc
MH
1916 }
1917 iter->oom_lock = false;
1918 }
23751be0 1919 return false;
a636b327 1920}
0b7f569e 1921
79dfdacc 1922/*
1af8efe9 1923 * Has to be called with memcg_oom_lock
79dfdacc 1924 */
c0ff4b85 1925static int mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
0b7f569e 1926{
7d74b06f
KH
1927 struct mem_cgroup *iter;
1928
c0ff4b85 1929 for_each_mem_cgroup_tree(iter, memcg)
79dfdacc
MH
1930 iter->oom_lock = false;
1931 return 0;
1932}
1933
c0ff4b85 1934static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
79dfdacc
MH
1935{
1936 struct mem_cgroup *iter;
1937
c0ff4b85 1938 for_each_mem_cgroup_tree(iter, memcg)
79dfdacc
MH
1939 atomic_inc(&iter->under_oom);
1940}
1941
c0ff4b85 1942static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
79dfdacc
MH
1943{
1944 struct mem_cgroup *iter;
1945
867578cb
KH
1946 /*
1947 * When a new child is created while the hierarchy is under oom,
1948 * mem_cgroup_oom_lock() may not be called. We have to use
1949 * atomic_add_unless() here.
1950 */
c0ff4b85 1951 for_each_mem_cgroup_tree(iter, memcg)
79dfdacc 1952 atomic_add_unless(&iter->under_oom, -1, 0);
0b7f569e
KH
1953}
1954
1af8efe9 1955static DEFINE_SPINLOCK(memcg_oom_lock);
867578cb
KH
1956static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1957
dc98df5a 1958struct oom_wait_info {
d79154bb 1959 struct mem_cgroup *memcg;
dc98df5a
KH
1960 wait_queue_t wait;
1961};
1962
1963static int memcg_oom_wake_function(wait_queue_t *wait,
1964 unsigned mode, int sync, void *arg)
1965{
d79154bb
HD
1966 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
1967 struct mem_cgroup *oom_wait_memcg;
dc98df5a
KH
1968 struct oom_wait_info *oom_wait_info;
1969
1970 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
d79154bb 1971 oom_wait_memcg = oom_wait_info->memcg;
dc98df5a 1972
dc98df5a 1973 /*
d79154bb 1974 * Both of oom_wait_info->memcg and wake_memcg are stable under us.
dc98df5a
KH
1975 * Then we can use css_is_ancestor without taking care of RCU.
1976 */
c0ff4b85
R
1977 if (!mem_cgroup_same_or_subtree(oom_wait_memcg, wake_memcg)
1978 && !mem_cgroup_same_or_subtree(wake_memcg, oom_wait_memcg))
dc98df5a 1979 return 0;
dc98df5a
KH
1980 return autoremove_wake_function(wait, mode, sync, arg);
1981}
1982
c0ff4b85 1983static void memcg_wakeup_oom(struct mem_cgroup *memcg)
dc98df5a 1984{
c0ff4b85
R
1985 /* for filtering, pass "memcg" as argument. */
1986 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
dc98df5a
KH
1987}
1988
c0ff4b85 1989static void memcg_oom_recover(struct mem_cgroup *memcg)
3c11ecf4 1990{
c0ff4b85
R
1991 if (memcg && atomic_read(&memcg->under_oom))
1992 memcg_wakeup_oom(memcg);
3c11ecf4
KH
1993}
1994
867578cb
KH
1995/*
1996 * try to call OOM killer. returns false if we should exit memory-reclaim loop.
1997 */
6bbda35c
KS
1998static bool mem_cgroup_handle_oom(struct mem_cgroup *memcg, gfp_t mask,
1999 int order)
0b7f569e 2000{
dc98df5a 2001 struct oom_wait_info owait;
3c11ecf4 2002 bool locked, need_to_kill;
867578cb 2003
d79154bb 2004 owait.memcg = memcg;
dc98df5a
KH
2005 owait.wait.flags = 0;
2006 owait.wait.func = memcg_oom_wake_function;
2007 owait.wait.private = current;
2008 INIT_LIST_HEAD(&owait.wait.task_list);
3c11ecf4 2009 need_to_kill = true;
c0ff4b85 2010 mem_cgroup_mark_under_oom(memcg);
79dfdacc 2011
c0ff4b85 2012 /* At first, try to OOM lock hierarchy under memcg.*/
1af8efe9 2013 spin_lock(&memcg_oom_lock);
c0ff4b85 2014 locked = mem_cgroup_oom_lock(memcg);
867578cb
KH
2015 /*
2016 * Even if signal_pending(), we can't quit charge() loop without
2017 * accounting. So, UNINTERRUPTIBLE is appropriate. But SIGKILL
2018 * under OOM is always welcomed, use TASK_KILLABLE here.
2019 */
3c11ecf4 2020 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
c0ff4b85 2021 if (!locked || memcg->oom_kill_disable)
3c11ecf4
KH
2022 need_to_kill = false;
2023 if (locked)
c0ff4b85 2024 mem_cgroup_oom_notify(memcg);
1af8efe9 2025 spin_unlock(&memcg_oom_lock);
867578cb 2026
3c11ecf4
KH
2027 if (need_to_kill) {
2028 finish_wait(&memcg_oom_waitq, &owait.wait);
e845e199 2029 mem_cgroup_out_of_memory(memcg, mask, order);
3c11ecf4 2030 } else {
867578cb 2031 schedule();
dc98df5a 2032 finish_wait(&memcg_oom_waitq, &owait.wait);
867578cb 2033 }
1af8efe9 2034 spin_lock(&memcg_oom_lock);
79dfdacc 2035 if (locked)
c0ff4b85
R
2036 mem_cgroup_oom_unlock(memcg);
2037 memcg_wakeup_oom(memcg);
1af8efe9 2038 spin_unlock(&memcg_oom_lock);
867578cb 2039
c0ff4b85 2040 mem_cgroup_unmark_under_oom(memcg);
79dfdacc 2041
867578cb
KH
2042 if (test_thread_flag(TIF_MEMDIE) || fatal_signal_pending(current))
2043 return false;
2044 /* Give chance to dying process */
715a5ee8 2045 schedule_timeout_uninterruptible(1);
867578cb 2046 return true;
0b7f569e
KH
2047}
2048
d69b042f
BS
2049/*
2050 * Currently used to update mapped file statistics, but the routine can be
2051 * generalized to update other statistics as well.
32047e2a
KH
2052 *
2053 * Notes: Race condition
2054 *
2055 * We usually use page_cgroup_lock() for accessing page_cgroup member but
2056 * it tends to be costly. But considering some conditions, we doesn't need
2057 * to do so _always_.
2058 *
2059 * Considering "charge", lock_page_cgroup() is not required because all
2060 * file-stat operations happen after a page is attached to radix-tree. There
2061 * are no race with "charge".
2062 *
2063 * Considering "uncharge", we know that memcg doesn't clear pc->mem_cgroup
2064 * at "uncharge" intentionally. So, we always see valid pc->mem_cgroup even
2065 * if there are race with "uncharge". Statistics itself is properly handled
2066 * by flags.
2067 *
2068 * Considering "move", this is an only case we see a race. To make the race
619d094b
KH
2069 * small, we check mm->moving_account and detect there are possibility of race
2070 * If there is, we take a lock.
d69b042f 2071 */
26174efd 2072
89c06bd5
KH
2073void __mem_cgroup_begin_update_page_stat(struct page *page,
2074 bool *locked, unsigned long *flags)
2075{
2076 struct mem_cgroup *memcg;
2077 struct page_cgroup *pc;
2078
2079 pc = lookup_page_cgroup(page);
2080again:
2081 memcg = pc->mem_cgroup;
2082 if (unlikely(!memcg || !PageCgroupUsed(pc)))
2083 return;
2084 /*
2085 * If this memory cgroup is not under account moving, we don't
da92c47d 2086 * need to take move_lock_mem_cgroup(). Because we already hold
89c06bd5 2087 * rcu_read_lock(), any calls to move_account will be delayed until
13fd1dd9 2088 * rcu_read_unlock() if mem_cgroup_stolen() == true.
89c06bd5 2089 */
13fd1dd9 2090 if (!mem_cgroup_stolen(memcg))
89c06bd5
KH
2091 return;
2092
2093 move_lock_mem_cgroup(memcg, flags);
2094 if (memcg != pc->mem_cgroup || !PageCgroupUsed(pc)) {
2095 move_unlock_mem_cgroup(memcg, flags);
2096 goto again;
2097 }
2098 *locked = true;
2099}
2100
2101void __mem_cgroup_end_update_page_stat(struct page *page, unsigned long *flags)
2102{
2103 struct page_cgroup *pc = lookup_page_cgroup(page);
2104
2105 /*
2106 * It's guaranteed that pc->mem_cgroup never changes while
2107 * lock is held because a routine modifies pc->mem_cgroup
da92c47d 2108 * should take move_lock_mem_cgroup().
89c06bd5
KH
2109 */
2110 move_unlock_mem_cgroup(pc->mem_cgroup, flags);
2111}
2112
2a7106f2
GT
2113void mem_cgroup_update_page_stat(struct page *page,
2114 enum mem_cgroup_page_stat_item idx, int val)
d69b042f 2115{
c0ff4b85 2116 struct mem_cgroup *memcg;
32047e2a 2117 struct page_cgroup *pc = lookup_page_cgroup(page);
dbd4ea78 2118 unsigned long uninitialized_var(flags);
d69b042f 2119
cfa44946 2120 if (mem_cgroup_disabled())
d69b042f 2121 return;
89c06bd5 2122
c0ff4b85
R
2123 memcg = pc->mem_cgroup;
2124 if (unlikely(!memcg || !PageCgroupUsed(pc)))
89c06bd5 2125 return;
26174efd 2126
26174efd 2127 switch (idx) {
2a7106f2 2128 case MEMCG_NR_FILE_MAPPED:
2a7106f2 2129 idx = MEM_CGROUP_STAT_FILE_MAPPED;
26174efd
KH
2130 break;
2131 default:
2132 BUG();
8725d541 2133 }
d69b042f 2134
c0ff4b85 2135 this_cpu_add(memcg->stat->count[idx], val);
d69b042f 2136}
26174efd 2137
cdec2e42
KH
2138/*
2139 * size of first charge trial. "32" comes from vmscan.c's magic value.
2140 * TODO: maybe necessary to use big numbers in big irons.
2141 */
7ec99d62 2142#define CHARGE_BATCH 32U
cdec2e42
KH
2143struct memcg_stock_pcp {
2144 struct mem_cgroup *cached; /* this never be root cgroup */
11c9ea4e 2145 unsigned int nr_pages;
cdec2e42 2146 struct work_struct work;
26fe6168 2147 unsigned long flags;
a0db00fc 2148#define FLUSHING_CACHED_CHARGE 0
cdec2e42
KH
2149};
2150static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
9f50fad6 2151static DEFINE_MUTEX(percpu_charge_mutex);
cdec2e42 2152
a0956d54
SS
2153/**
2154 * consume_stock: Try to consume stocked charge on this cpu.
2155 * @memcg: memcg to consume from.
2156 * @nr_pages: how many pages to charge.
2157 *
2158 * The charges will only happen if @memcg matches the current cpu's memcg
2159 * stock, and at least @nr_pages are available in that stock. Failure to
2160 * service an allocation will refill the stock.
2161 *
2162 * returns true if successful, false otherwise.
cdec2e42 2163 */
a0956d54 2164static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
cdec2e42
KH
2165{
2166 struct memcg_stock_pcp *stock;
2167 bool ret = true;
2168
a0956d54
SS
2169 if (nr_pages > CHARGE_BATCH)
2170 return false;
2171
cdec2e42 2172 stock = &get_cpu_var(memcg_stock);
a0956d54
SS
2173 if (memcg == stock->cached && stock->nr_pages >= nr_pages)
2174 stock->nr_pages -= nr_pages;
cdec2e42
KH
2175 else /* need to call res_counter_charge */
2176 ret = false;
2177 put_cpu_var(memcg_stock);
2178 return ret;
2179}
2180
2181/*
2182 * Returns stocks cached in percpu to res_counter and reset cached information.
2183 */
2184static void drain_stock(struct memcg_stock_pcp *stock)
2185{
2186 struct mem_cgroup *old = stock->cached;
2187
11c9ea4e
JW
2188 if (stock->nr_pages) {
2189 unsigned long bytes = stock->nr_pages * PAGE_SIZE;
2190
2191 res_counter_uncharge(&old->res, bytes);
cdec2e42 2192 if (do_swap_account)
11c9ea4e
JW
2193 res_counter_uncharge(&old->memsw, bytes);
2194 stock->nr_pages = 0;
cdec2e42
KH
2195 }
2196 stock->cached = NULL;
cdec2e42
KH
2197}
2198
2199/*
2200 * This must be called under preempt disabled or must be called by
2201 * a thread which is pinned to local cpu.
2202 */
2203static void drain_local_stock(struct work_struct *dummy)
2204{
2205 struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
2206 drain_stock(stock);
26fe6168 2207 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
cdec2e42
KH
2208}
2209
2210/*
2211 * Cache charges(val) which is from res_counter, to local per_cpu area.
320cc51d 2212 * This will be consumed by consume_stock() function, later.
cdec2e42 2213 */
c0ff4b85 2214static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
cdec2e42
KH
2215{
2216 struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
2217
c0ff4b85 2218 if (stock->cached != memcg) { /* reset if necessary */
cdec2e42 2219 drain_stock(stock);
c0ff4b85 2220 stock->cached = memcg;
cdec2e42 2221 }
11c9ea4e 2222 stock->nr_pages += nr_pages;
cdec2e42
KH
2223 put_cpu_var(memcg_stock);
2224}
2225
2226/*
c0ff4b85 2227 * Drains all per-CPU charge caches for given root_memcg resp. subtree
d38144b7
MH
2228 * of the hierarchy under it. sync flag says whether we should block
2229 * until the work is done.
cdec2e42 2230 */
c0ff4b85 2231static void drain_all_stock(struct mem_cgroup *root_memcg, bool sync)
cdec2e42 2232{
26fe6168 2233 int cpu, curcpu;
d38144b7 2234
cdec2e42 2235 /* Notify other cpus that system-wide "drain" is running */
cdec2e42 2236 get_online_cpus();
5af12d0e 2237 curcpu = get_cpu();
cdec2e42
KH
2238 for_each_online_cpu(cpu) {
2239 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
c0ff4b85 2240 struct mem_cgroup *memcg;
26fe6168 2241
c0ff4b85
R
2242 memcg = stock->cached;
2243 if (!memcg || !stock->nr_pages)
26fe6168 2244 continue;
c0ff4b85 2245 if (!mem_cgroup_same_or_subtree(root_memcg, memcg))
3e92041d 2246 continue;
d1a05b69
MH
2247 if (!test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2248 if (cpu == curcpu)
2249 drain_local_stock(&stock->work);
2250 else
2251 schedule_work_on(cpu, &stock->work);
2252 }
cdec2e42 2253 }
5af12d0e 2254 put_cpu();
d38144b7
MH
2255
2256 if (!sync)
2257 goto out;
2258
2259 for_each_online_cpu(cpu) {
2260 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
9f50fad6 2261 if (test_bit(FLUSHING_CACHED_CHARGE, &stock->flags))
d38144b7
MH
2262 flush_work(&stock->work);
2263 }
2264out:
cdec2e42 2265 put_online_cpus();
d38144b7
MH
2266}
2267
2268/*
2269 * Tries to drain stocked charges in other cpus. This function is asynchronous
2270 * and just put a work per cpu for draining localy on each cpu. Caller can
2271 * expects some charges will be back to res_counter later but cannot wait for
2272 * it.
2273 */
c0ff4b85 2274static void drain_all_stock_async(struct mem_cgroup *root_memcg)
d38144b7 2275{
9f50fad6
MH
2276 /*
2277 * If someone calls draining, avoid adding more kworker runs.
2278 */
2279 if (!mutex_trylock(&percpu_charge_mutex))
2280 return;
c0ff4b85 2281 drain_all_stock(root_memcg, false);
9f50fad6 2282 mutex_unlock(&percpu_charge_mutex);
cdec2e42
KH
2283}
2284
2285/* This is a synchronous drain interface. */
c0ff4b85 2286static void drain_all_stock_sync(struct mem_cgroup *root_memcg)
cdec2e42
KH
2287{
2288 /* called when force_empty is called */
9f50fad6 2289 mutex_lock(&percpu_charge_mutex);
c0ff4b85 2290 drain_all_stock(root_memcg, true);
9f50fad6 2291 mutex_unlock(&percpu_charge_mutex);
cdec2e42
KH
2292}
2293
711d3d2c
KH
2294/*
2295 * This function drains percpu counter value from DEAD cpu and
2296 * move it to local cpu. Note that this function can be preempted.
2297 */
c0ff4b85 2298static void mem_cgroup_drain_pcp_counter(struct mem_cgroup *memcg, int cpu)
711d3d2c
KH
2299{
2300 int i;
2301
c0ff4b85 2302 spin_lock(&memcg->pcp_counter_lock);
6104621d 2303 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
c0ff4b85 2304 long x = per_cpu(memcg->stat->count[i], cpu);
711d3d2c 2305
c0ff4b85
R
2306 per_cpu(memcg->stat->count[i], cpu) = 0;
2307 memcg->nocpu_base.count[i] += x;
711d3d2c 2308 }
e9f8974f 2309 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
c0ff4b85 2310 unsigned long x = per_cpu(memcg->stat->events[i], cpu);
e9f8974f 2311
c0ff4b85
R
2312 per_cpu(memcg->stat->events[i], cpu) = 0;
2313 memcg->nocpu_base.events[i] += x;
e9f8974f 2314 }
c0ff4b85 2315 spin_unlock(&memcg->pcp_counter_lock);
711d3d2c
KH
2316}
2317
2318static int __cpuinit memcg_cpu_hotplug_callback(struct notifier_block *nb,
cdec2e42
KH
2319 unsigned long action,
2320 void *hcpu)
2321{
2322 int cpu = (unsigned long)hcpu;
2323 struct memcg_stock_pcp *stock;
711d3d2c 2324 struct mem_cgroup *iter;
cdec2e42 2325
619d094b 2326 if (action == CPU_ONLINE)
1489ebad 2327 return NOTIFY_OK;
1489ebad 2328
d833049b 2329 if (action != CPU_DEAD && action != CPU_DEAD_FROZEN)
cdec2e42 2330 return NOTIFY_OK;
711d3d2c 2331
9f3a0d09 2332 for_each_mem_cgroup(iter)
711d3d2c
KH
2333 mem_cgroup_drain_pcp_counter(iter, cpu);
2334
cdec2e42
KH
2335 stock = &per_cpu(memcg_stock, cpu);
2336 drain_stock(stock);
2337 return NOTIFY_OK;
2338}
2339
4b534334
KH
2340
2341/* See __mem_cgroup_try_charge() for details */
2342enum {
2343 CHARGE_OK, /* success */
2344 CHARGE_RETRY, /* need to retry but retry is not bad */
2345 CHARGE_NOMEM, /* we can't do more. return -ENOMEM */
2346 CHARGE_WOULDBLOCK, /* GFP_WAIT wasn't set and no enough res. */
2347 CHARGE_OOM_DIE, /* the current is killed because of OOM */
2348};
2349
c0ff4b85 2350static int mem_cgroup_do_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
4c9c5359
SS
2351 unsigned int nr_pages, unsigned int min_pages,
2352 bool oom_check)
4b534334 2353{
7ec99d62 2354 unsigned long csize = nr_pages * PAGE_SIZE;
4b534334
KH
2355 struct mem_cgroup *mem_over_limit;
2356 struct res_counter *fail_res;
2357 unsigned long flags = 0;
2358 int ret;
2359
c0ff4b85 2360 ret = res_counter_charge(&memcg->res, csize, &fail_res);
4b534334
KH
2361
2362 if (likely(!ret)) {
2363 if (!do_swap_account)
2364 return CHARGE_OK;
c0ff4b85 2365 ret = res_counter_charge(&memcg->memsw, csize, &fail_res);
4b534334
KH
2366 if (likely(!ret))
2367 return CHARGE_OK;
2368
c0ff4b85 2369 res_counter_uncharge(&memcg->res, csize);
4b534334
KH
2370 mem_over_limit = mem_cgroup_from_res_counter(fail_res, memsw);
2371 flags |= MEM_CGROUP_RECLAIM_NOSWAP;
2372 } else
2373 mem_over_limit = mem_cgroup_from_res_counter(fail_res, res);
9221edb7 2374 /*
9221edb7
JW
2375 * Never reclaim on behalf of optional batching, retry with a
2376 * single page instead.
2377 */
4c9c5359 2378 if (nr_pages > min_pages)
4b534334
KH
2379 return CHARGE_RETRY;
2380
2381 if (!(gfp_mask & __GFP_WAIT))
2382 return CHARGE_WOULDBLOCK;
2383
4c9c5359
SS
2384 if (gfp_mask & __GFP_NORETRY)
2385 return CHARGE_NOMEM;
2386
5660048c 2387 ret = mem_cgroup_reclaim(mem_over_limit, gfp_mask, flags);
7ec99d62 2388 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
19942822 2389 return CHARGE_RETRY;
4b534334 2390 /*
19942822
JW
2391 * Even though the limit is exceeded at this point, reclaim
2392 * may have been able to free some pages. Retry the charge
2393 * before killing the task.
2394 *
2395 * Only for regular pages, though: huge pages are rather
2396 * unlikely to succeed so close to the limit, and we fall back
2397 * to regular pages anyway in case of failure.
4b534334 2398 */
4c9c5359 2399 if (nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER) && ret)
4b534334
KH
2400 return CHARGE_RETRY;
2401
2402 /*
2403 * At task move, charge accounts can be doubly counted. So, it's
2404 * better to wait until the end of task_move if something is going on.
2405 */
2406 if (mem_cgroup_wait_acct_move(mem_over_limit))
2407 return CHARGE_RETRY;
2408
2409 /* If we don't need to call oom-killer at el, return immediately */
2410 if (!oom_check)
2411 return CHARGE_NOMEM;
2412 /* check OOM */
e845e199 2413 if (!mem_cgroup_handle_oom(mem_over_limit, gfp_mask, get_order(csize)))
4b534334
KH
2414 return CHARGE_OOM_DIE;
2415
2416 return CHARGE_RETRY;
2417}
2418
f817ed48 2419/*
38c5d72f
KH
2420 * __mem_cgroup_try_charge() does
2421 * 1. detect memcg to be charged against from passed *mm and *ptr,
2422 * 2. update res_counter
2423 * 3. call memory reclaim if necessary.
2424 *
2425 * In some special case, if the task is fatal, fatal_signal_pending() or
2426 * has TIF_MEMDIE, this function returns -EINTR while writing root_mem_cgroup
2427 * to *ptr. There are two reasons for this. 1: fatal threads should quit as soon
2428 * as possible without any hazards. 2: all pages should have a valid
2429 * pc->mem_cgroup. If mm is NULL and the caller doesn't pass a valid memcg
2430 * pointer, that is treated as a charge to root_mem_cgroup.
2431 *
2432 * So __mem_cgroup_try_charge() will return
2433 * 0 ... on success, filling *ptr with a valid memcg pointer.
2434 * -ENOMEM ... charge failure because of resource limits.
2435 * -EINTR ... if thread is fatal. *ptr is filled with root_mem_cgroup.
2436 *
2437 * Unlike the exported interface, an "oom" parameter is added. if oom==true,
2438 * the oom-killer can be invoked.
8a9f3ccd 2439 */
f817ed48 2440static int __mem_cgroup_try_charge(struct mm_struct *mm,
ec168510 2441 gfp_t gfp_mask,
7ec99d62 2442 unsigned int nr_pages,
c0ff4b85 2443 struct mem_cgroup **ptr,
7ec99d62 2444 bool oom)
8a9f3ccd 2445{
7ec99d62 2446 unsigned int batch = max(CHARGE_BATCH, nr_pages);
4b534334 2447 int nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
c0ff4b85 2448 struct mem_cgroup *memcg = NULL;
4b534334 2449 int ret;
a636b327 2450
867578cb
KH
2451 /*
2452 * Unlike gloval-vm's OOM-kill, we're not in memory shortage
2453 * in system level. So, allow to go ahead dying process in addition to
2454 * MEMDIE process.
2455 */
2456 if (unlikely(test_thread_flag(TIF_MEMDIE)
2457 || fatal_signal_pending(current)))
2458 goto bypass;
a636b327 2459
8a9f3ccd 2460 /*
3be91277
HD
2461 * We always charge the cgroup the mm_struct belongs to.
2462 * The mm_struct's mem_cgroup changes on task migration if the
8a9f3ccd 2463 * thread group leader migrates. It's possible that mm is not
24467cac 2464 * set, if so charge the root memcg (happens for pagecache usage).
8a9f3ccd 2465 */
c0ff4b85 2466 if (!*ptr && !mm)
38c5d72f 2467 *ptr = root_mem_cgroup;
f75ca962 2468again:
c0ff4b85
R
2469 if (*ptr) { /* css should be a valid one */
2470 memcg = *ptr;
c0ff4b85 2471 if (mem_cgroup_is_root(memcg))
f75ca962 2472 goto done;
a0956d54 2473 if (consume_stock(memcg, nr_pages))
f75ca962 2474 goto done;
c0ff4b85 2475 css_get(&memcg->css);
4b534334 2476 } else {
f75ca962 2477 struct task_struct *p;
54595fe2 2478
f75ca962
KH
2479 rcu_read_lock();
2480 p = rcu_dereference(mm->owner);
f75ca962 2481 /*
ebb76ce1 2482 * Because we don't have task_lock(), "p" can exit.
c0ff4b85 2483 * In that case, "memcg" can point to root or p can be NULL with
ebb76ce1
KH
2484 * race with swapoff. Then, we have small risk of mis-accouning.
2485 * But such kind of mis-account by race always happens because
2486 * we don't have cgroup_mutex(). It's overkill and we allo that
2487 * small race, here.
2488 * (*) swapoff at el will charge against mm-struct not against
2489 * task-struct. So, mm->owner can be NULL.
f75ca962 2490 */
c0ff4b85 2491 memcg = mem_cgroup_from_task(p);
38c5d72f
KH
2492 if (!memcg)
2493 memcg = root_mem_cgroup;
2494 if (mem_cgroup_is_root(memcg)) {
f75ca962
KH
2495 rcu_read_unlock();
2496 goto done;
2497 }
a0956d54 2498 if (consume_stock(memcg, nr_pages)) {
f75ca962
KH
2499 /*
2500 * It seems dagerous to access memcg without css_get().
2501 * But considering how consume_stok works, it's not
2502 * necessary. If consume_stock success, some charges
2503 * from this memcg are cached on this cpu. So, we
2504 * don't need to call css_get()/css_tryget() before
2505 * calling consume_stock().
2506 */
2507 rcu_read_unlock();
2508 goto done;
2509 }
2510 /* after here, we may be blocked. we need to get refcnt */
c0ff4b85 2511 if (!css_tryget(&memcg->css)) {
f75ca962
KH
2512 rcu_read_unlock();
2513 goto again;
2514 }
2515 rcu_read_unlock();
2516 }
8a9f3ccd 2517
4b534334
KH
2518 do {
2519 bool oom_check;
7a81b88c 2520
4b534334 2521 /* If killed, bypass charge */
f75ca962 2522 if (fatal_signal_pending(current)) {
c0ff4b85 2523 css_put(&memcg->css);
4b534334 2524 goto bypass;
f75ca962 2525 }
6d61ef40 2526
4b534334
KH
2527 oom_check = false;
2528 if (oom && !nr_oom_retries) {
2529 oom_check = true;
2530 nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
cdec2e42 2531 }
66e1707b 2532
4c9c5359
SS
2533 ret = mem_cgroup_do_charge(memcg, gfp_mask, batch, nr_pages,
2534 oom_check);
4b534334
KH
2535 switch (ret) {
2536 case CHARGE_OK:
2537 break;
2538 case CHARGE_RETRY: /* not in OOM situation but retry */
7ec99d62 2539 batch = nr_pages;
c0ff4b85
R
2540 css_put(&memcg->css);
2541 memcg = NULL;
f75ca962 2542 goto again;
4b534334 2543 case CHARGE_WOULDBLOCK: /* !__GFP_WAIT */
c0ff4b85 2544 css_put(&memcg->css);
4b534334
KH
2545 goto nomem;
2546 case CHARGE_NOMEM: /* OOM routine works */
f75ca962 2547 if (!oom) {
c0ff4b85 2548 css_put(&memcg->css);
867578cb 2549 goto nomem;
f75ca962 2550 }
4b534334
KH
2551 /* If oom, we never return -ENOMEM */
2552 nr_oom_retries--;
2553 break;
2554 case CHARGE_OOM_DIE: /* Killed by OOM Killer */
c0ff4b85 2555 css_put(&memcg->css);
867578cb 2556 goto bypass;
66e1707b 2557 }
4b534334
KH
2558 } while (ret != CHARGE_OK);
2559
7ec99d62 2560 if (batch > nr_pages)
c0ff4b85
R
2561 refill_stock(memcg, batch - nr_pages);
2562 css_put(&memcg->css);
0c3e73e8 2563done:
c0ff4b85 2564 *ptr = memcg;
7a81b88c
KH
2565 return 0;
2566nomem:
c0ff4b85 2567 *ptr = NULL;
7a81b88c 2568 return -ENOMEM;
867578cb 2569bypass:
38c5d72f
KH
2570 *ptr = root_mem_cgroup;
2571 return -EINTR;
7a81b88c 2572}
8a9f3ccd 2573
a3032a2c
DN
2574/*
2575 * Somemtimes we have to undo a charge we got by try_charge().
2576 * This function is for that and do uncharge, put css's refcnt.
2577 * gotten by try_charge().
2578 */
c0ff4b85 2579static void __mem_cgroup_cancel_charge(struct mem_cgroup *memcg,
e7018b8d 2580 unsigned int nr_pages)
a3032a2c 2581{
c0ff4b85 2582 if (!mem_cgroup_is_root(memcg)) {
e7018b8d
JW
2583 unsigned long bytes = nr_pages * PAGE_SIZE;
2584
c0ff4b85 2585 res_counter_uncharge(&memcg->res, bytes);
a3032a2c 2586 if (do_swap_account)
c0ff4b85 2587 res_counter_uncharge(&memcg->memsw, bytes);
a3032a2c 2588 }
854ffa8d
DN
2589}
2590
d01dd17f
KH
2591/*
2592 * Cancel chrages in this cgroup....doesn't propagate to parent cgroup.
2593 * This is useful when moving usage to parent cgroup.
2594 */
2595static void __mem_cgroup_cancel_local_charge(struct mem_cgroup *memcg,
2596 unsigned int nr_pages)
2597{
2598 unsigned long bytes = nr_pages * PAGE_SIZE;
2599
2600 if (mem_cgroup_is_root(memcg))
2601 return;
2602
2603 res_counter_uncharge_until(&memcg->res, memcg->res.parent, bytes);
2604 if (do_swap_account)
2605 res_counter_uncharge_until(&memcg->memsw,
2606 memcg->memsw.parent, bytes);
2607}
2608
a3b2d692
KH
2609/*
2610 * A helper function to get mem_cgroup from ID. must be called under
e9316080
TH
2611 * rcu_read_lock(). The caller is responsible for calling css_tryget if
2612 * the mem_cgroup is used for charging. (dropping refcnt from swap can be
2613 * called against removed memcg.)
a3b2d692
KH
2614 */
2615static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
2616{
2617 struct cgroup_subsys_state *css;
2618
2619 /* ID 0 is unused ID */
2620 if (!id)
2621 return NULL;
2622 css = css_lookup(&mem_cgroup_subsys, id);
2623 if (!css)
2624 return NULL;
b2145145 2625 return mem_cgroup_from_css(css);
a3b2d692
KH
2626}
2627
e42d9d5d 2628struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
b5a84319 2629{
c0ff4b85 2630 struct mem_cgroup *memcg = NULL;
3c776e64 2631 struct page_cgroup *pc;
a3b2d692 2632 unsigned short id;
b5a84319
KH
2633 swp_entry_t ent;
2634
3c776e64
DN
2635 VM_BUG_ON(!PageLocked(page));
2636
3c776e64 2637 pc = lookup_page_cgroup(page);
c0bd3f63 2638 lock_page_cgroup(pc);
a3b2d692 2639 if (PageCgroupUsed(pc)) {
c0ff4b85
R
2640 memcg = pc->mem_cgroup;
2641 if (memcg && !css_tryget(&memcg->css))
2642 memcg = NULL;
e42d9d5d 2643 } else if (PageSwapCache(page)) {
3c776e64 2644 ent.val = page_private(page);
9fb4b7cc 2645 id = lookup_swap_cgroup_id(ent);
a3b2d692 2646 rcu_read_lock();
c0ff4b85
R
2647 memcg = mem_cgroup_lookup(id);
2648 if (memcg && !css_tryget(&memcg->css))
2649 memcg = NULL;
a3b2d692 2650 rcu_read_unlock();
3c776e64 2651 }
c0bd3f63 2652 unlock_page_cgroup(pc);
c0ff4b85 2653 return memcg;
b5a84319
KH
2654}
2655
c0ff4b85 2656static void __mem_cgroup_commit_charge(struct mem_cgroup *memcg,
5564e88b 2657 struct page *page,
7ec99d62 2658 unsigned int nr_pages,
9ce70c02
HD
2659 enum charge_type ctype,
2660 bool lrucare)
7a81b88c 2661{
ce587e65 2662 struct page_cgroup *pc = lookup_page_cgroup(page);
9ce70c02 2663 struct zone *uninitialized_var(zone);
fa9add64 2664 struct lruvec *lruvec;
9ce70c02 2665 bool was_on_lru = false;
b2402857 2666 bool anon;
9ce70c02 2667
ca3e0214 2668 lock_page_cgroup(pc);
90deb788 2669 VM_BUG_ON(PageCgroupUsed(pc));
ca3e0214
KH
2670 /*
2671 * we don't need page_cgroup_lock about tail pages, becase they are not
2672 * accessed by any other context at this point.
2673 */
9ce70c02
HD
2674
2675 /*
2676 * In some cases, SwapCache and FUSE(splice_buf->radixtree), the page
2677 * may already be on some other mem_cgroup's LRU. Take care of it.
2678 */
2679 if (lrucare) {
2680 zone = page_zone(page);
2681 spin_lock_irq(&zone->lru_lock);
2682 if (PageLRU(page)) {
fa9add64 2683 lruvec = mem_cgroup_zone_lruvec(zone, pc->mem_cgroup);
9ce70c02 2684 ClearPageLRU(page);
fa9add64 2685 del_page_from_lru_list(page, lruvec, page_lru(page));
9ce70c02
HD
2686 was_on_lru = true;
2687 }
2688 }
2689
c0ff4b85 2690 pc->mem_cgroup = memcg;
261fb61a
KH
2691 /*
2692 * We access a page_cgroup asynchronously without lock_page_cgroup().
2693 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
2694 * is accessed after testing USED bit. To make pc->mem_cgroup visible
2695 * before USED bit, we need memory barrier here.
2696 * See mem_cgroup_add_lru_list(), etc.
2697 */
08e552c6 2698 smp_wmb();
b2402857 2699 SetPageCgroupUsed(pc);
3be91277 2700
9ce70c02
HD
2701 if (lrucare) {
2702 if (was_on_lru) {
fa9add64 2703 lruvec = mem_cgroup_zone_lruvec(zone, pc->mem_cgroup);
9ce70c02
HD
2704 VM_BUG_ON(PageLRU(page));
2705 SetPageLRU(page);
fa9add64 2706 add_page_to_lru_list(page, lruvec, page_lru(page));
9ce70c02
HD
2707 }
2708 spin_unlock_irq(&zone->lru_lock);
2709 }
2710
41326c17 2711 if (ctype == MEM_CGROUP_CHARGE_TYPE_ANON)
b2402857
KH
2712 anon = true;
2713 else
2714 anon = false;
2715
2716 mem_cgroup_charge_statistics(memcg, anon, nr_pages);
52d4b9ac 2717 unlock_page_cgroup(pc);
9ce70c02 2718
430e4863
KH
2719 /*
2720 * "charge_statistics" updated event counter. Then, check it.
2721 * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
2722 * if they exceeds softlimit.
2723 */
c0ff4b85 2724 memcg_check_events(memcg, page);
7a81b88c 2725}
66e1707b 2726
7ae1e1d0
GC
2727#ifdef CONFIG_MEMCG_KMEM
2728static inline bool memcg_can_account_kmem(struct mem_cgroup *memcg)
2729{
2730 return !mem_cgroup_disabled() && !mem_cgroup_is_root(memcg) &&
2731 (memcg->kmem_account_flags & KMEM_ACCOUNTED_MASK);
2732}
2733
2734static int memcg_charge_kmem(struct mem_cgroup *memcg, gfp_t gfp, u64 size)
2735{
2736 struct res_counter *fail_res;
2737 struct mem_cgroup *_memcg;
2738 int ret = 0;
2739 bool may_oom;
2740
2741 ret = res_counter_charge(&memcg->kmem, size, &fail_res);
2742 if (ret)
2743 return ret;
2744
2745 /*
2746 * Conditions under which we can wait for the oom_killer. Those are
2747 * the same conditions tested by the core page allocator
2748 */
2749 may_oom = (gfp & __GFP_FS) && !(gfp & __GFP_NORETRY);
2750
2751 _memcg = memcg;
2752 ret = __mem_cgroup_try_charge(NULL, gfp, size >> PAGE_SHIFT,
2753 &_memcg, may_oom);
2754
2755 if (ret == -EINTR) {
2756 /*
2757 * __mem_cgroup_try_charge() chosed to bypass to root due to
2758 * OOM kill or fatal signal. Since our only options are to
2759 * either fail the allocation or charge it to this cgroup, do
2760 * it as a temporary condition. But we can't fail. From a
2761 * kmem/slab perspective, the cache has already been selected,
2762 * by mem_cgroup_kmem_get_cache(), so it is too late to change
2763 * our minds.
2764 *
2765 * This condition will only trigger if the task entered
2766 * memcg_charge_kmem in a sane state, but was OOM-killed during
2767 * __mem_cgroup_try_charge() above. Tasks that were already
2768 * dying when the allocation triggers should have been already
2769 * directed to the root cgroup in memcontrol.h
2770 */
2771 res_counter_charge_nofail(&memcg->res, size, &fail_res);
2772 if (do_swap_account)
2773 res_counter_charge_nofail(&memcg->memsw, size,
2774 &fail_res);
2775 ret = 0;
2776 } else if (ret)
2777 res_counter_uncharge(&memcg->kmem, size);
2778
2779 return ret;
2780}
2781
2782static void memcg_uncharge_kmem(struct mem_cgroup *memcg, u64 size)
2783{
7ae1e1d0
GC
2784 res_counter_uncharge(&memcg->res, size);
2785 if (do_swap_account)
2786 res_counter_uncharge(&memcg->memsw, size);
7de37682
GC
2787
2788 /* Not down to 0 */
2789 if (res_counter_uncharge(&memcg->kmem, size))
2790 return;
2791
2792 if (memcg_kmem_test_and_clear_dead(memcg))
2793 mem_cgroup_put(memcg);
7ae1e1d0
GC
2794}
2795
2633d7a0
GC
2796void memcg_cache_list_add(struct mem_cgroup *memcg, struct kmem_cache *cachep)
2797{
2798 if (!memcg)
2799 return;
2800
2801 mutex_lock(&memcg->slab_caches_mutex);
2802 list_add(&cachep->memcg_params->list, &memcg->memcg_slab_caches);
2803 mutex_unlock(&memcg->slab_caches_mutex);
2804}
2805
2806/*
2807 * helper for acessing a memcg's index. It will be used as an index in the
2808 * child cache array in kmem_cache, and also to derive its name. This function
2809 * will return -1 when this is not a kmem-limited memcg.
2810 */
2811int memcg_cache_id(struct mem_cgroup *memcg)
2812{
2813 return memcg ? memcg->kmemcg_id : -1;
2814}
2815
2816int memcg_register_cache(struct mem_cgroup *memcg, struct kmem_cache *s)
2817{
2818 size_t size = sizeof(struct memcg_cache_params);
2819
2820 if (!memcg_kmem_enabled())
2821 return 0;
2822
2823 s->memcg_params = kzalloc(size, GFP_KERNEL);
2824 if (!s->memcg_params)
2825 return -ENOMEM;
2826
2827 if (memcg)
2828 s->memcg_params->memcg = memcg;
2829 return 0;
2830}
2831
2832void memcg_release_cache(struct kmem_cache *s)
2833{
2834 kfree(s->memcg_params);
2835}
2836
7ae1e1d0
GC
2837/*
2838 * We need to verify if the allocation against current->mm->owner's memcg is
2839 * possible for the given order. But the page is not allocated yet, so we'll
2840 * need a further commit step to do the final arrangements.
2841 *
2842 * It is possible for the task to switch cgroups in this mean time, so at
2843 * commit time, we can't rely on task conversion any longer. We'll then use
2844 * the handle argument to return to the caller which cgroup we should commit
2845 * against. We could also return the memcg directly and avoid the pointer
2846 * passing, but a boolean return value gives better semantics considering
2847 * the compiled-out case as well.
2848 *
2849 * Returning true means the allocation is possible.
2850 */
2851bool
2852__memcg_kmem_newpage_charge(gfp_t gfp, struct mem_cgroup **_memcg, int order)
2853{
2854 struct mem_cgroup *memcg;
2855 int ret;
2856
2857 *_memcg = NULL;
2858 memcg = try_get_mem_cgroup_from_mm(current->mm);
2859
2860 /*
2861 * very rare case described in mem_cgroup_from_task. Unfortunately there
2862 * isn't much we can do without complicating this too much, and it would
2863 * be gfp-dependent anyway. Just let it go
2864 */
2865 if (unlikely(!memcg))
2866 return true;
2867
2868 if (!memcg_can_account_kmem(memcg)) {
2869 css_put(&memcg->css);
2870 return true;
2871 }
2872
7ae1e1d0
GC
2873 ret = memcg_charge_kmem(memcg, gfp, PAGE_SIZE << order);
2874 if (!ret)
2875 *_memcg = memcg;
7ae1e1d0
GC
2876
2877 css_put(&memcg->css);
2878 return (ret == 0);
2879}
2880
2881void __memcg_kmem_commit_charge(struct page *page, struct mem_cgroup *memcg,
2882 int order)
2883{
2884 struct page_cgroup *pc;
2885
2886 VM_BUG_ON(mem_cgroup_is_root(memcg));
2887
2888 /* The page allocation failed. Revert */
2889 if (!page) {
2890 memcg_uncharge_kmem(memcg, PAGE_SIZE << order);
7ae1e1d0
GC
2891 return;
2892 }
2893
2894 pc = lookup_page_cgroup(page);
2895 lock_page_cgroup(pc);
2896 pc->mem_cgroup = memcg;
2897 SetPageCgroupUsed(pc);
2898 unlock_page_cgroup(pc);
2899}
2900
2901void __memcg_kmem_uncharge_pages(struct page *page, int order)
2902{
2903 struct mem_cgroup *memcg = NULL;
2904 struct page_cgroup *pc;
2905
2906
2907 pc = lookup_page_cgroup(page);
2908 /*
2909 * Fast unlocked return. Theoretically might have changed, have to
2910 * check again after locking.
2911 */
2912 if (!PageCgroupUsed(pc))
2913 return;
2914
2915 lock_page_cgroup(pc);
2916 if (PageCgroupUsed(pc)) {
2917 memcg = pc->mem_cgroup;
2918 ClearPageCgroupUsed(pc);
2919 }
2920 unlock_page_cgroup(pc);
2921
2922 /*
2923 * We trust that only if there is a memcg associated with the page, it
2924 * is a valid allocation
2925 */
2926 if (!memcg)
2927 return;
2928
2929 VM_BUG_ON(mem_cgroup_is_root(memcg));
2930 memcg_uncharge_kmem(memcg, PAGE_SIZE << order);
7ae1e1d0
GC
2931}
2932#endif /* CONFIG_MEMCG_KMEM */
2933
ca3e0214
KH
2934#ifdef CONFIG_TRANSPARENT_HUGEPAGE
2935
a0db00fc 2936#define PCGF_NOCOPY_AT_SPLIT (1 << PCG_LOCK | 1 << PCG_MIGRATION)
ca3e0214
KH
2937/*
2938 * Because tail pages are not marked as "used", set it. We're under
e94c8a9c
KH
2939 * zone->lru_lock, 'splitting on pmd' and compound_lock.
2940 * charge/uncharge will be never happen and move_account() is done under
2941 * compound_lock(), so we don't have to take care of races.
ca3e0214 2942 */
e94c8a9c 2943void mem_cgroup_split_huge_fixup(struct page *head)
ca3e0214
KH
2944{
2945 struct page_cgroup *head_pc = lookup_page_cgroup(head);
e94c8a9c
KH
2946 struct page_cgroup *pc;
2947 int i;
ca3e0214 2948
3d37c4a9
KH
2949 if (mem_cgroup_disabled())
2950 return;
e94c8a9c
KH
2951 for (i = 1; i < HPAGE_PMD_NR; i++) {
2952 pc = head_pc + i;
2953 pc->mem_cgroup = head_pc->mem_cgroup;
2954 smp_wmb();/* see __commit_charge() */
e94c8a9c
KH
2955 pc->flags = head_pc->flags & ~PCGF_NOCOPY_AT_SPLIT;
2956 }
ca3e0214 2957}
12d27107 2958#endif /* CONFIG_TRANSPARENT_HUGEPAGE */
ca3e0214 2959
f817ed48 2960/**
de3638d9 2961 * mem_cgroup_move_account - move account of the page
5564e88b 2962 * @page: the page
7ec99d62 2963 * @nr_pages: number of regular pages (>1 for huge pages)
f817ed48
KH
2964 * @pc: page_cgroup of the page.
2965 * @from: mem_cgroup which the page is moved from.
2966 * @to: mem_cgroup which the page is moved to. @from != @to.
2967 *
2968 * The caller must confirm following.
08e552c6 2969 * - page is not on LRU (isolate_page() is useful.)
7ec99d62 2970 * - compound_lock is held when nr_pages > 1
f817ed48 2971 *
2f3479b1
KH
2972 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
2973 * from old cgroup.
f817ed48 2974 */
7ec99d62
JW
2975static int mem_cgroup_move_account(struct page *page,
2976 unsigned int nr_pages,
2977 struct page_cgroup *pc,
2978 struct mem_cgroup *from,
2f3479b1 2979 struct mem_cgroup *to)
f817ed48 2980{
de3638d9
JW
2981 unsigned long flags;
2982 int ret;
b2402857 2983 bool anon = PageAnon(page);
987eba66 2984
f817ed48 2985 VM_BUG_ON(from == to);
5564e88b 2986 VM_BUG_ON(PageLRU(page));
de3638d9
JW
2987 /*
2988 * The page is isolated from LRU. So, collapse function
2989 * will not handle this page. But page splitting can happen.
2990 * Do this check under compound_page_lock(). The caller should
2991 * hold it.
2992 */
2993 ret = -EBUSY;
7ec99d62 2994 if (nr_pages > 1 && !PageTransHuge(page))
de3638d9
JW
2995 goto out;
2996
2997 lock_page_cgroup(pc);
2998
2999 ret = -EINVAL;
3000 if (!PageCgroupUsed(pc) || pc->mem_cgroup != from)
3001 goto unlock;
3002
312734c0 3003 move_lock_mem_cgroup(from, &flags);
f817ed48 3004
2ff76f11 3005 if (!anon && page_mapped(page)) {
c62b1a3b
KH
3006 /* Update mapped_file data for mem_cgroup */
3007 preempt_disable();
3008 __this_cpu_dec(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
3009 __this_cpu_inc(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
3010 preempt_enable();
d69b042f 3011 }
b2402857 3012 mem_cgroup_charge_statistics(from, anon, -nr_pages);
d69b042f 3013
854ffa8d 3014 /* caller should have done css_get */
08e552c6 3015 pc->mem_cgroup = to;
b2402857 3016 mem_cgroup_charge_statistics(to, anon, nr_pages);
312734c0 3017 move_unlock_mem_cgroup(from, &flags);
de3638d9
JW
3018 ret = 0;
3019unlock:
57f9fd7d 3020 unlock_page_cgroup(pc);
d2265e6f
KH
3021 /*
3022 * check events
3023 */
5564e88b
JW
3024 memcg_check_events(to, page);
3025 memcg_check_events(from, page);
de3638d9 3026out:
f817ed48
KH
3027 return ret;
3028}
3029
2ef37d3f
MH
3030/**
3031 * mem_cgroup_move_parent - moves page to the parent group
3032 * @page: the page to move
3033 * @pc: page_cgroup of the page
3034 * @child: page's cgroup
3035 *
3036 * move charges to its parent or the root cgroup if the group has no
3037 * parent (aka use_hierarchy==0).
3038 * Although this might fail (get_page_unless_zero, isolate_lru_page or
3039 * mem_cgroup_move_account fails) the failure is always temporary and
3040 * it signals a race with a page removal/uncharge or migration. In the
3041 * first case the page is on the way out and it will vanish from the LRU
3042 * on the next attempt and the call should be retried later.
3043 * Isolation from the LRU fails only if page has been isolated from
3044 * the LRU since we looked at it and that usually means either global
3045 * reclaim or migration going on. The page will either get back to the
3046 * LRU or vanish.
3047 * Finaly mem_cgroup_move_account fails only if the page got uncharged
3048 * (!PageCgroupUsed) or moved to a different group. The page will
3049 * disappear in the next attempt.
f817ed48 3050 */
5564e88b
JW
3051static int mem_cgroup_move_parent(struct page *page,
3052 struct page_cgroup *pc,
6068bf01 3053 struct mem_cgroup *child)
f817ed48 3054{
f817ed48 3055 struct mem_cgroup *parent;
7ec99d62 3056 unsigned int nr_pages;
4be4489f 3057 unsigned long uninitialized_var(flags);
f817ed48
KH
3058 int ret;
3059
d8423011 3060 VM_BUG_ON(mem_cgroup_is_root(child));
f817ed48 3061
57f9fd7d
DN
3062 ret = -EBUSY;
3063 if (!get_page_unless_zero(page))
3064 goto out;
3065 if (isolate_lru_page(page))
3066 goto put;
52dbb905 3067
7ec99d62 3068 nr_pages = hpage_nr_pages(page);
08e552c6 3069
cc926f78
KH
3070 parent = parent_mem_cgroup(child);
3071 /*
3072 * If no parent, move charges to root cgroup.
3073 */
3074 if (!parent)
3075 parent = root_mem_cgroup;
f817ed48 3076
2ef37d3f
MH
3077 if (nr_pages > 1) {
3078 VM_BUG_ON(!PageTransHuge(page));
987eba66 3079 flags = compound_lock_irqsave(page);
2ef37d3f 3080 }
987eba66 3081
cc926f78 3082 ret = mem_cgroup_move_account(page, nr_pages,
2f3479b1 3083 pc, child, parent);
cc926f78
KH
3084 if (!ret)
3085 __mem_cgroup_cancel_local_charge(child, nr_pages);
8dba474f 3086
7ec99d62 3087 if (nr_pages > 1)
987eba66 3088 compound_unlock_irqrestore(page, flags);
08e552c6 3089 putback_lru_page(page);
57f9fd7d 3090put:
40d58138 3091 put_page(page);
57f9fd7d 3092out:
f817ed48
KH
3093 return ret;
3094}
3095
7a81b88c
KH
3096/*
3097 * Charge the memory controller for page usage.
3098 * Return
3099 * 0 if the charge was successful
3100 * < 0 if the cgroup is over its limit
3101 */
3102static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
73045c47 3103 gfp_t gfp_mask, enum charge_type ctype)
7a81b88c 3104{
c0ff4b85 3105 struct mem_cgroup *memcg = NULL;
7ec99d62 3106 unsigned int nr_pages = 1;
8493ae43 3107 bool oom = true;
7a81b88c 3108 int ret;
ec168510 3109
37c2ac78 3110 if (PageTransHuge(page)) {
7ec99d62 3111 nr_pages <<= compound_order(page);
37c2ac78 3112 VM_BUG_ON(!PageTransHuge(page));
8493ae43
JW
3113 /*
3114 * Never OOM-kill a process for a huge page. The
3115 * fault handler will fall back to regular pages.
3116 */
3117 oom = false;
37c2ac78 3118 }
7a81b88c 3119
c0ff4b85 3120 ret = __mem_cgroup_try_charge(mm, gfp_mask, nr_pages, &memcg, oom);
38c5d72f 3121 if (ret == -ENOMEM)
7a81b88c 3122 return ret;
ce587e65 3123 __mem_cgroup_commit_charge(memcg, page, nr_pages, ctype, false);
8a9f3ccd 3124 return 0;
8a9f3ccd
BS
3125}
3126
7a81b88c
KH
3127int mem_cgroup_newpage_charge(struct page *page,
3128 struct mm_struct *mm, gfp_t gfp_mask)
217bc319 3129{
f8d66542 3130 if (mem_cgroup_disabled())
cede86ac 3131 return 0;
7a0524cf
JW
3132 VM_BUG_ON(page_mapped(page));
3133 VM_BUG_ON(page->mapping && !PageAnon(page));
3134 VM_BUG_ON(!mm);
217bc319 3135 return mem_cgroup_charge_common(page, mm, gfp_mask,
41326c17 3136 MEM_CGROUP_CHARGE_TYPE_ANON);
217bc319
KH
3137}
3138
54595fe2
KH
3139/*
3140 * While swap-in, try_charge -> commit or cancel, the page is locked.
3141 * And when try_charge() successfully returns, one refcnt to memcg without
21ae2956 3142 * struct page_cgroup is acquired. This refcnt will be consumed by
54595fe2
KH
3143 * "commit()" or removed by "cancel()"
3144 */
0435a2fd
JW
3145static int __mem_cgroup_try_charge_swapin(struct mm_struct *mm,
3146 struct page *page,
3147 gfp_t mask,
3148 struct mem_cgroup **memcgp)
8c7c6e34 3149{
c0ff4b85 3150 struct mem_cgroup *memcg;
90deb788 3151 struct page_cgroup *pc;
54595fe2 3152 int ret;
8c7c6e34 3153
90deb788
JW
3154 pc = lookup_page_cgroup(page);
3155 /*
3156 * Every swap fault against a single page tries to charge the
3157 * page, bail as early as possible. shmem_unuse() encounters
3158 * already charged pages, too. The USED bit is protected by
3159 * the page lock, which serializes swap cache removal, which
3160 * in turn serializes uncharging.
3161 */
3162 if (PageCgroupUsed(pc))
3163 return 0;
8c7c6e34
KH
3164 if (!do_swap_account)
3165 goto charge_cur_mm;
c0ff4b85
R
3166 memcg = try_get_mem_cgroup_from_page(page);
3167 if (!memcg)
54595fe2 3168 goto charge_cur_mm;
72835c86
JW
3169 *memcgp = memcg;
3170 ret = __mem_cgroup_try_charge(NULL, mask, 1, memcgp, true);
c0ff4b85 3171 css_put(&memcg->css);
38c5d72f
KH
3172 if (ret == -EINTR)
3173 ret = 0;
54595fe2 3174 return ret;
8c7c6e34 3175charge_cur_mm:
38c5d72f
KH
3176 ret = __mem_cgroup_try_charge(mm, mask, 1, memcgp, true);
3177 if (ret == -EINTR)
3178 ret = 0;
3179 return ret;
8c7c6e34
KH
3180}
3181
0435a2fd
JW
3182int mem_cgroup_try_charge_swapin(struct mm_struct *mm, struct page *page,
3183 gfp_t gfp_mask, struct mem_cgroup **memcgp)
3184{
3185 *memcgp = NULL;
3186 if (mem_cgroup_disabled())
3187 return 0;
bdf4f4d2
JW
3188 /*
3189 * A racing thread's fault, or swapoff, may have already
3190 * updated the pte, and even removed page from swap cache: in
3191 * those cases unuse_pte()'s pte_same() test will fail; but
3192 * there's also a KSM case which does need to charge the page.
3193 */
3194 if (!PageSwapCache(page)) {
3195 int ret;
3196
3197 ret = __mem_cgroup_try_charge(mm, gfp_mask, 1, memcgp, true);
3198 if (ret == -EINTR)
3199 ret = 0;
3200 return ret;
3201 }
0435a2fd
JW
3202 return __mem_cgroup_try_charge_swapin(mm, page, gfp_mask, memcgp);
3203}
3204
827a03d2
JW
3205void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *memcg)
3206{
3207 if (mem_cgroup_disabled())
3208 return;
3209 if (!memcg)
3210 return;
3211 __mem_cgroup_cancel_charge(memcg, 1);
3212}
3213
83aae4c7 3214static void
72835c86 3215__mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *memcg,
83aae4c7 3216 enum charge_type ctype)
7a81b88c 3217{
f8d66542 3218 if (mem_cgroup_disabled())
7a81b88c 3219 return;
72835c86 3220 if (!memcg)
7a81b88c 3221 return;
5a6475a4 3222
ce587e65 3223 __mem_cgroup_commit_charge(memcg, page, 1, ctype, true);
8c7c6e34
KH
3224 /*
3225 * Now swap is on-memory. This means this page may be
3226 * counted both as mem and swap....double count.
03f3c433
KH
3227 * Fix it by uncharging from memsw. Basically, this SwapCache is stable
3228 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
3229 * may call delete_from_swap_cache() before reach here.
8c7c6e34 3230 */
03f3c433 3231 if (do_swap_account && PageSwapCache(page)) {
8c7c6e34 3232 swp_entry_t ent = {.val = page_private(page)};
86493009 3233 mem_cgroup_uncharge_swap(ent);
8c7c6e34 3234 }
7a81b88c
KH
3235}
3236
72835c86
JW
3237void mem_cgroup_commit_charge_swapin(struct page *page,
3238 struct mem_cgroup *memcg)
83aae4c7 3239{
72835c86 3240 __mem_cgroup_commit_charge_swapin(page, memcg,
41326c17 3241 MEM_CGROUP_CHARGE_TYPE_ANON);
83aae4c7
DN
3242}
3243
827a03d2
JW
3244int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
3245 gfp_t gfp_mask)
7a81b88c 3246{
827a03d2
JW
3247 struct mem_cgroup *memcg = NULL;
3248 enum charge_type type = MEM_CGROUP_CHARGE_TYPE_CACHE;
3249 int ret;
3250
f8d66542 3251 if (mem_cgroup_disabled())
827a03d2
JW
3252 return 0;
3253 if (PageCompound(page))
3254 return 0;
3255
827a03d2
JW
3256 if (!PageSwapCache(page))
3257 ret = mem_cgroup_charge_common(page, mm, gfp_mask, type);
3258 else { /* page is swapcache/shmem */
0435a2fd
JW
3259 ret = __mem_cgroup_try_charge_swapin(mm, page,
3260 gfp_mask, &memcg);
827a03d2
JW
3261 if (!ret)
3262 __mem_cgroup_commit_charge_swapin(page, memcg, type);
3263 }
3264 return ret;
7a81b88c
KH
3265}
3266
c0ff4b85 3267static void mem_cgroup_do_uncharge(struct mem_cgroup *memcg,
7ec99d62
JW
3268 unsigned int nr_pages,
3269 const enum charge_type ctype)
569b846d
KH
3270{
3271 struct memcg_batch_info *batch = NULL;
3272 bool uncharge_memsw = true;
7ec99d62 3273
569b846d
KH
3274 /* If swapout, usage of swap doesn't decrease */
3275 if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
3276 uncharge_memsw = false;
569b846d
KH
3277
3278 batch = &current->memcg_batch;
3279 /*
3280 * In usual, we do css_get() when we remember memcg pointer.
3281 * But in this case, we keep res->usage until end of a series of
3282 * uncharges. Then, it's ok to ignore memcg's refcnt.
3283 */
3284 if (!batch->memcg)
c0ff4b85 3285 batch->memcg = memcg;
3c11ecf4
KH
3286 /*
3287 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
25985edc 3288 * In those cases, all pages freed continuously can be expected to be in
3c11ecf4
KH
3289 * the same cgroup and we have chance to coalesce uncharges.
3290 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
3291 * because we want to do uncharge as soon as possible.
3292 */
3293
3294 if (!batch->do_batch || test_thread_flag(TIF_MEMDIE))
3295 goto direct_uncharge;
3296
7ec99d62 3297 if (nr_pages > 1)
ec168510
AA
3298 goto direct_uncharge;
3299
569b846d
KH
3300 /*
3301 * In typical case, batch->memcg == mem. This means we can
3302 * merge a series of uncharges to an uncharge of res_counter.
3303 * If not, we uncharge res_counter ony by one.
3304 */
c0ff4b85 3305 if (batch->memcg != memcg)
569b846d
KH
3306 goto direct_uncharge;
3307 /* remember freed charge and uncharge it later */
7ffd4ca7 3308 batch->nr_pages++;
569b846d 3309 if (uncharge_memsw)
7ffd4ca7 3310 batch->memsw_nr_pages++;
569b846d
KH
3311 return;
3312direct_uncharge:
c0ff4b85 3313 res_counter_uncharge(&memcg->res, nr_pages * PAGE_SIZE);
569b846d 3314 if (uncharge_memsw)
c0ff4b85
R
3315 res_counter_uncharge(&memcg->memsw, nr_pages * PAGE_SIZE);
3316 if (unlikely(batch->memcg != memcg))
3317 memcg_oom_recover(memcg);
569b846d 3318}
7a81b88c 3319
8a9f3ccd 3320/*
69029cd5 3321 * uncharge if !page_mapped(page)
8a9f3ccd 3322 */
8c7c6e34 3323static struct mem_cgroup *
0030f535
JW
3324__mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype,
3325 bool end_migration)
8a9f3ccd 3326{
c0ff4b85 3327 struct mem_cgroup *memcg = NULL;
7ec99d62
JW
3328 unsigned int nr_pages = 1;
3329 struct page_cgroup *pc;
b2402857 3330 bool anon;
8a9f3ccd 3331
f8d66542 3332 if (mem_cgroup_disabled())
8c7c6e34 3333 return NULL;
4077960e 3334
0c59b89c 3335 VM_BUG_ON(PageSwapCache(page));
d13d1443 3336
37c2ac78 3337 if (PageTransHuge(page)) {
7ec99d62 3338 nr_pages <<= compound_order(page);
37c2ac78
AA
3339 VM_BUG_ON(!PageTransHuge(page));
3340 }
8697d331 3341 /*
3c541e14 3342 * Check if our page_cgroup is valid
8697d331 3343 */
52d4b9ac 3344 pc = lookup_page_cgroup(page);
cfa44946 3345 if (unlikely(!PageCgroupUsed(pc)))
8c7c6e34 3346 return NULL;
b9c565d5 3347
52d4b9ac 3348 lock_page_cgroup(pc);
d13d1443 3349
c0ff4b85 3350 memcg = pc->mem_cgroup;
8c7c6e34 3351
d13d1443
KH
3352 if (!PageCgroupUsed(pc))
3353 goto unlock_out;
3354
b2402857
KH
3355 anon = PageAnon(page);
3356
d13d1443 3357 switch (ctype) {
41326c17 3358 case MEM_CGROUP_CHARGE_TYPE_ANON:
2ff76f11
KH
3359 /*
3360 * Generally PageAnon tells if it's the anon statistics to be
3361 * updated; but sometimes e.g. mem_cgroup_uncharge_page() is
3362 * used before page reached the stage of being marked PageAnon.
3363 */
b2402857
KH
3364 anon = true;
3365 /* fallthrough */
8a9478ca 3366 case MEM_CGROUP_CHARGE_TYPE_DROP:
ac39cf8c 3367 /* See mem_cgroup_prepare_migration() */
0030f535
JW
3368 if (page_mapped(page))
3369 goto unlock_out;
3370 /*
3371 * Pages under migration may not be uncharged. But
3372 * end_migration() /must/ be the one uncharging the
3373 * unused post-migration page and so it has to call
3374 * here with the migration bit still set. See the
3375 * res_counter handling below.
3376 */
3377 if (!end_migration && PageCgroupMigration(pc))
d13d1443
KH
3378 goto unlock_out;
3379 break;
3380 case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
3381 if (!PageAnon(page)) { /* Shared memory */
3382 if (page->mapping && !page_is_file_cache(page))
3383 goto unlock_out;
3384 } else if (page_mapped(page)) /* Anon */
3385 goto unlock_out;
3386 break;
3387 default:
3388 break;
52d4b9ac 3389 }
d13d1443 3390
b2402857 3391 mem_cgroup_charge_statistics(memcg, anon, -nr_pages);
04046e1a 3392
52d4b9ac 3393 ClearPageCgroupUsed(pc);
544122e5
KH
3394 /*
3395 * pc->mem_cgroup is not cleared here. It will be accessed when it's
3396 * freed from LRU. This is safe because uncharged page is expected not
3397 * to be reused (freed soon). Exception is SwapCache, it's handled by
3398 * special functions.
3399 */
b9c565d5 3400
52d4b9ac 3401 unlock_page_cgroup(pc);
f75ca962 3402 /*
c0ff4b85 3403 * even after unlock, we have memcg->res.usage here and this memcg
f75ca962
KH
3404 * will never be freed.
3405 */
c0ff4b85 3406 memcg_check_events(memcg, page);
f75ca962 3407 if (do_swap_account && ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT) {
c0ff4b85
R
3408 mem_cgroup_swap_statistics(memcg, true);
3409 mem_cgroup_get(memcg);
f75ca962 3410 }
0030f535
JW
3411 /*
3412 * Migration does not charge the res_counter for the
3413 * replacement page, so leave it alone when phasing out the
3414 * page that is unused after the migration.
3415 */
3416 if (!end_migration && !mem_cgroup_is_root(memcg))
c0ff4b85 3417 mem_cgroup_do_uncharge(memcg, nr_pages, ctype);
6d12e2d8 3418
c0ff4b85 3419 return memcg;
d13d1443
KH
3420
3421unlock_out:
3422 unlock_page_cgroup(pc);
8c7c6e34 3423 return NULL;
3c541e14
BS
3424}
3425
69029cd5
KH
3426void mem_cgroup_uncharge_page(struct page *page)
3427{
52d4b9ac
KH
3428 /* early check. */
3429 if (page_mapped(page))
3430 return;
40f23a21 3431 VM_BUG_ON(page->mapping && !PageAnon(page));
0c59b89c
JW
3432 if (PageSwapCache(page))
3433 return;
0030f535 3434 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_ANON, false);
69029cd5
KH
3435}
3436
3437void mem_cgroup_uncharge_cache_page(struct page *page)
3438{
3439 VM_BUG_ON(page_mapped(page));
b7abea96 3440 VM_BUG_ON(page->mapping);
0030f535 3441 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE, false);
69029cd5
KH
3442}
3443
569b846d
KH
3444/*
3445 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
3446 * In that cases, pages are freed continuously and we can expect pages
3447 * are in the same memcg. All these calls itself limits the number of
3448 * pages freed at once, then uncharge_start/end() is called properly.
3449 * This may be called prural(2) times in a context,
3450 */
3451
3452void mem_cgroup_uncharge_start(void)
3453{
3454 current->memcg_batch.do_batch++;
3455 /* We can do nest. */
3456 if (current->memcg_batch.do_batch == 1) {
3457 current->memcg_batch.memcg = NULL;
7ffd4ca7
JW
3458 current->memcg_batch.nr_pages = 0;
3459 current->memcg_batch.memsw_nr_pages = 0;
569b846d
KH
3460 }
3461}
3462
3463void mem_cgroup_uncharge_end(void)
3464{
3465 struct memcg_batch_info *batch = &current->memcg_batch;
3466
3467 if (!batch->do_batch)
3468 return;
3469
3470 batch->do_batch--;
3471 if (batch->do_batch) /* If stacked, do nothing. */
3472 return;
3473
3474 if (!batch->memcg)
3475 return;
3476 /*
3477 * This "batch->memcg" is valid without any css_get/put etc...
3478 * bacause we hide charges behind us.
3479 */
7ffd4ca7
JW
3480 if (batch->nr_pages)
3481 res_counter_uncharge(&batch->memcg->res,
3482 batch->nr_pages * PAGE_SIZE);
3483 if (batch->memsw_nr_pages)
3484 res_counter_uncharge(&batch->memcg->memsw,
3485 batch->memsw_nr_pages * PAGE_SIZE);
3c11ecf4 3486 memcg_oom_recover(batch->memcg);
569b846d
KH
3487 /* forget this pointer (for sanity check) */
3488 batch->memcg = NULL;
3489}
3490
e767e056 3491#ifdef CONFIG_SWAP
8c7c6e34 3492/*
e767e056 3493 * called after __delete_from_swap_cache() and drop "page" account.
8c7c6e34
KH
3494 * memcg information is recorded to swap_cgroup of "ent"
3495 */
8a9478ca
KH
3496void
3497mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
8c7c6e34
KH
3498{
3499 struct mem_cgroup *memcg;
8a9478ca
KH
3500 int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
3501
3502 if (!swapout) /* this was a swap cache but the swap is unused ! */
3503 ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
3504
0030f535 3505 memcg = __mem_cgroup_uncharge_common(page, ctype, false);
8c7c6e34 3506
f75ca962
KH
3507 /*
3508 * record memcg information, if swapout && memcg != NULL,
3509 * mem_cgroup_get() was called in uncharge().
3510 */
3511 if (do_swap_account && swapout && memcg)
a3b2d692 3512 swap_cgroup_record(ent, css_id(&memcg->css));
8c7c6e34 3513}
e767e056 3514#endif
8c7c6e34 3515
c255a458 3516#ifdef CONFIG_MEMCG_SWAP
8c7c6e34
KH
3517/*
3518 * called from swap_entry_free(). remove record in swap_cgroup and
3519 * uncharge "memsw" account.
3520 */
3521void mem_cgroup_uncharge_swap(swp_entry_t ent)
d13d1443 3522{
8c7c6e34 3523 struct mem_cgroup *memcg;
a3b2d692 3524 unsigned short id;
8c7c6e34
KH
3525
3526 if (!do_swap_account)
3527 return;
3528
a3b2d692
KH
3529 id = swap_cgroup_record(ent, 0);
3530 rcu_read_lock();
3531 memcg = mem_cgroup_lookup(id);
8c7c6e34 3532 if (memcg) {
a3b2d692
KH
3533 /*
3534 * We uncharge this because swap is freed.
3535 * This memcg can be obsolete one. We avoid calling css_tryget
3536 */
0c3e73e8 3537 if (!mem_cgroup_is_root(memcg))
4e649152 3538 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
0c3e73e8 3539 mem_cgroup_swap_statistics(memcg, false);
8c7c6e34
KH
3540 mem_cgroup_put(memcg);
3541 }
a3b2d692 3542 rcu_read_unlock();
d13d1443 3543}
02491447
DN
3544
3545/**
3546 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3547 * @entry: swap entry to be moved
3548 * @from: mem_cgroup which the entry is moved from
3549 * @to: mem_cgroup which the entry is moved to
3550 *
3551 * It succeeds only when the swap_cgroup's record for this entry is the same
3552 * as the mem_cgroup's id of @from.
3553 *
3554 * Returns 0 on success, -EINVAL on failure.
3555 *
3556 * The caller must have charged to @to, IOW, called res_counter_charge() about
3557 * both res and memsw, and called css_get().
3558 */
3559static int mem_cgroup_move_swap_account(swp_entry_t entry,
e91cbb42 3560 struct mem_cgroup *from, struct mem_cgroup *to)
02491447
DN
3561{
3562 unsigned short old_id, new_id;
3563
3564 old_id = css_id(&from->css);
3565 new_id = css_id(&to->css);
3566
3567 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
02491447 3568 mem_cgroup_swap_statistics(from, false);
483c30b5 3569 mem_cgroup_swap_statistics(to, true);
02491447 3570 /*
483c30b5
DN
3571 * This function is only called from task migration context now.
3572 * It postpones res_counter and refcount handling till the end
3573 * of task migration(mem_cgroup_clear_mc()) for performance
3574 * improvement. But we cannot postpone mem_cgroup_get(to)
3575 * because if the process that has been moved to @to does
3576 * swap-in, the refcount of @to might be decreased to 0.
02491447 3577 */
02491447 3578 mem_cgroup_get(to);
02491447
DN
3579 return 0;
3580 }
3581 return -EINVAL;
3582}
3583#else
3584static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
e91cbb42 3585 struct mem_cgroup *from, struct mem_cgroup *to)
02491447
DN
3586{
3587 return -EINVAL;
3588}
8c7c6e34 3589#endif
d13d1443 3590
ae41be37 3591/*
01b1ae63
KH
3592 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
3593 * page belongs to.
ae41be37 3594 */
0030f535
JW
3595void mem_cgroup_prepare_migration(struct page *page, struct page *newpage,
3596 struct mem_cgroup **memcgp)
ae41be37 3597{
c0ff4b85 3598 struct mem_cgroup *memcg = NULL;
b32967ff 3599 unsigned int nr_pages = 1;
7ec99d62 3600 struct page_cgroup *pc;
ac39cf8c 3601 enum charge_type ctype;
8869b8f6 3602
72835c86 3603 *memcgp = NULL;
56039efa 3604
f8d66542 3605 if (mem_cgroup_disabled())
0030f535 3606 return;
4077960e 3607
b32967ff
MG
3608 if (PageTransHuge(page))
3609 nr_pages <<= compound_order(page);
3610
52d4b9ac
KH
3611 pc = lookup_page_cgroup(page);
3612 lock_page_cgroup(pc);
3613 if (PageCgroupUsed(pc)) {
c0ff4b85
R
3614 memcg = pc->mem_cgroup;
3615 css_get(&memcg->css);
ac39cf8c 3616 /*
3617 * At migrating an anonymous page, its mapcount goes down
3618 * to 0 and uncharge() will be called. But, even if it's fully
3619 * unmapped, migration may fail and this page has to be
3620 * charged again. We set MIGRATION flag here and delay uncharge
3621 * until end_migration() is called
3622 *
3623 * Corner Case Thinking
3624 * A)
3625 * When the old page was mapped as Anon and it's unmap-and-freed
3626 * while migration was ongoing.
3627 * If unmap finds the old page, uncharge() of it will be delayed
3628 * until end_migration(). If unmap finds a new page, it's
3629 * uncharged when it make mapcount to be 1->0. If unmap code
3630 * finds swap_migration_entry, the new page will not be mapped
3631 * and end_migration() will find it(mapcount==0).
3632 *
3633 * B)
3634 * When the old page was mapped but migraion fails, the kernel
3635 * remaps it. A charge for it is kept by MIGRATION flag even
3636 * if mapcount goes down to 0. We can do remap successfully
3637 * without charging it again.
3638 *
3639 * C)
3640 * The "old" page is under lock_page() until the end of
3641 * migration, so, the old page itself will not be swapped-out.
3642 * If the new page is swapped out before end_migraton, our
3643 * hook to usual swap-out path will catch the event.
3644 */
3645 if (PageAnon(page))
3646 SetPageCgroupMigration(pc);
e8589cc1 3647 }
52d4b9ac 3648 unlock_page_cgroup(pc);
ac39cf8c 3649 /*
3650 * If the page is not charged at this point,
3651 * we return here.
3652 */
c0ff4b85 3653 if (!memcg)
0030f535 3654 return;
01b1ae63 3655
72835c86 3656 *memcgp = memcg;
ac39cf8c 3657 /*
3658 * We charge new page before it's used/mapped. So, even if unlock_page()
3659 * is called before end_migration, we can catch all events on this new
3660 * page. In the case new page is migrated but not remapped, new page's
3661 * mapcount will be finally 0 and we call uncharge in end_migration().
3662 */
ac39cf8c 3663 if (PageAnon(page))
41326c17 3664 ctype = MEM_CGROUP_CHARGE_TYPE_ANON;
ac39cf8c 3665 else
62ba7442 3666 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
0030f535
JW
3667 /*
3668 * The page is committed to the memcg, but it's not actually
3669 * charged to the res_counter since we plan on replacing the
3670 * old one and only one page is going to be left afterwards.
3671 */
b32967ff 3672 __mem_cgroup_commit_charge(memcg, newpage, nr_pages, ctype, false);
ae41be37 3673}
8869b8f6 3674
69029cd5 3675/* remove redundant charge if migration failed*/
c0ff4b85 3676void mem_cgroup_end_migration(struct mem_cgroup *memcg,
50de1dd9 3677 struct page *oldpage, struct page *newpage, bool migration_ok)
ae41be37 3678{
ac39cf8c 3679 struct page *used, *unused;
01b1ae63 3680 struct page_cgroup *pc;
b2402857 3681 bool anon;
01b1ae63 3682
c0ff4b85 3683 if (!memcg)
01b1ae63 3684 return;
b25ed609 3685
50de1dd9 3686 if (!migration_ok) {
ac39cf8c 3687 used = oldpage;
3688 unused = newpage;
01b1ae63 3689 } else {
ac39cf8c 3690 used = newpage;
01b1ae63
KH
3691 unused = oldpage;
3692 }
0030f535 3693 anon = PageAnon(used);
7d188958
JW
3694 __mem_cgroup_uncharge_common(unused,
3695 anon ? MEM_CGROUP_CHARGE_TYPE_ANON
3696 : MEM_CGROUP_CHARGE_TYPE_CACHE,
3697 true);
0030f535 3698 css_put(&memcg->css);
69029cd5 3699 /*
ac39cf8c 3700 * We disallowed uncharge of pages under migration because mapcount
3701 * of the page goes down to zero, temporarly.
3702 * Clear the flag and check the page should be charged.
01b1ae63 3703 */
ac39cf8c 3704 pc = lookup_page_cgroup(oldpage);
3705 lock_page_cgroup(pc);
3706 ClearPageCgroupMigration(pc);
3707 unlock_page_cgroup(pc);
ac39cf8c 3708
01b1ae63 3709 /*
ac39cf8c 3710 * If a page is a file cache, radix-tree replacement is very atomic
3711 * and we can skip this check. When it was an Anon page, its mapcount
3712 * goes down to 0. But because we added MIGRATION flage, it's not
3713 * uncharged yet. There are several case but page->mapcount check
3714 * and USED bit check in mem_cgroup_uncharge_page() will do enough
3715 * check. (see prepare_charge() also)
69029cd5 3716 */
b2402857 3717 if (anon)
ac39cf8c 3718 mem_cgroup_uncharge_page(used);
ae41be37 3719}
78fb7466 3720
ab936cbc
KH
3721/*
3722 * At replace page cache, newpage is not under any memcg but it's on
3723 * LRU. So, this function doesn't touch res_counter but handles LRU
3724 * in correct way. Both pages are locked so we cannot race with uncharge.
3725 */
3726void mem_cgroup_replace_page_cache(struct page *oldpage,
3727 struct page *newpage)
3728{
bde05d1c 3729 struct mem_cgroup *memcg = NULL;
ab936cbc 3730 struct page_cgroup *pc;
ab936cbc 3731 enum charge_type type = MEM_CGROUP_CHARGE_TYPE_CACHE;
ab936cbc
KH
3732
3733 if (mem_cgroup_disabled())
3734 return;
3735
3736 pc = lookup_page_cgroup(oldpage);
3737 /* fix accounting on old pages */
3738 lock_page_cgroup(pc);
bde05d1c
HD
3739 if (PageCgroupUsed(pc)) {
3740 memcg = pc->mem_cgroup;
3741 mem_cgroup_charge_statistics(memcg, false, -1);
3742 ClearPageCgroupUsed(pc);
3743 }
ab936cbc
KH
3744 unlock_page_cgroup(pc);
3745
bde05d1c
HD
3746 /*
3747 * When called from shmem_replace_page(), in some cases the
3748 * oldpage has already been charged, and in some cases not.
3749 */
3750 if (!memcg)
3751 return;
ab936cbc
KH
3752 /*
3753 * Even if newpage->mapping was NULL before starting replacement,
3754 * the newpage may be on LRU(or pagevec for LRU) already. We lock
3755 * LRU while we overwrite pc->mem_cgroup.
3756 */
ce587e65 3757 __mem_cgroup_commit_charge(memcg, newpage, 1, type, true);
ab936cbc
KH
3758}
3759
f212ad7c
DN
3760#ifdef CONFIG_DEBUG_VM
3761static struct page_cgroup *lookup_page_cgroup_used(struct page *page)
3762{
3763 struct page_cgroup *pc;
3764
3765 pc = lookup_page_cgroup(page);
cfa44946
JW
3766 /*
3767 * Can be NULL while feeding pages into the page allocator for
3768 * the first time, i.e. during boot or memory hotplug;
3769 * or when mem_cgroup_disabled().
3770 */
f212ad7c
DN
3771 if (likely(pc) && PageCgroupUsed(pc))
3772 return pc;
3773 return NULL;
3774}
3775
3776bool mem_cgroup_bad_page_check(struct page *page)
3777{
3778 if (mem_cgroup_disabled())
3779 return false;
3780
3781 return lookup_page_cgroup_used(page) != NULL;
3782}
3783
3784void mem_cgroup_print_bad_page(struct page *page)
3785{
3786 struct page_cgroup *pc;
3787
3788 pc = lookup_page_cgroup_used(page);
3789 if (pc) {
90b3feae 3790 printk(KERN_ALERT "pc:%p pc->flags:%lx pc->mem_cgroup:%p\n",
f212ad7c 3791 pc, pc->flags, pc->mem_cgroup);
f212ad7c
DN
3792 }
3793}
3794#endif
3795
8c7c6e34
KH
3796static DEFINE_MUTEX(set_limit_mutex);
3797
d38d2a75 3798static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
8c7c6e34 3799 unsigned long long val)
628f4235 3800{
81d39c20 3801 int retry_count;
3c11ecf4 3802 u64 memswlimit, memlimit;
628f4235 3803 int ret = 0;
81d39c20
KH
3804 int children = mem_cgroup_count_children(memcg);
3805 u64 curusage, oldusage;
3c11ecf4 3806 int enlarge;
81d39c20
KH
3807
3808 /*
3809 * For keeping hierarchical_reclaim simple, how long we should retry
3810 * is depends on callers. We set our retry-count to be function
3811 * of # of children which we should visit in this loop.
3812 */
3813 retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
3814
3815 oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
628f4235 3816
3c11ecf4 3817 enlarge = 0;
8c7c6e34 3818 while (retry_count) {
628f4235
KH
3819 if (signal_pending(current)) {
3820 ret = -EINTR;
3821 break;
3822 }
8c7c6e34
KH
3823 /*
3824 * Rather than hide all in some function, I do this in
3825 * open coded manner. You see what this really does.
aaad153e 3826 * We have to guarantee memcg->res.limit <= memcg->memsw.limit.
8c7c6e34
KH
3827 */
3828 mutex_lock(&set_limit_mutex);
3829 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3830 if (memswlimit < val) {
3831 ret = -EINVAL;
3832 mutex_unlock(&set_limit_mutex);
628f4235
KH
3833 break;
3834 }
3c11ecf4
KH
3835
3836 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3837 if (memlimit < val)
3838 enlarge = 1;
3839
8c7c6e34 3840 ret = res_counter_set_limit(&memcg->res, val);
22a668d7
KH
3841 if (!ret) {
3842 if (memswlimit == val)
3843 memcg->memsw_is_minimum = true;
3844 else
3845 memcg->memsw_is_minimum = false;
3846 }
8c7c6e34
KH
3847 mutex_unlock(&set_limit_mutex);
3848
3849 if (!ret)
3850 break;
3851
5660048c
JW
3852 mem_cgroup_reclaim(memcg, GFP_KERNEL,
3853 MEM_CGROUP_RECLAIM_SHRINK);
81d39c20
KH
3854 curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
3855 /* Usage is reduced ? */
3856 if (curusage >= oldusage)
3857 retry_count--;
3858 else
3859 oldusage = curusage;
8c7c6e34 3860 }
3c11ecf4
KH
3861 if (!ret && enlarge)
3862 memcg_oom_recover(memcg);
14797e23 3863
8c7c6e34
KH
3864 return ret;
3865}
3866
338c8431
LZ
3867static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
3868 unsigned long long val)
8c7c6e34 3869{
81d39c20 3870 int retry_count;
3c11ecf4 3871 u64 memlimit, memswlimit, oldusage, curusage;
81d39c20
KH
3872 int children = mem_cgroup_count_children(memcg);
3873 int ret = -EBUSY;
3c11ecf4 3874 int enlarge = 0;
8c7c6e34 3875
81d39c20
KH
3876 /* see mem_cgroup_resize_res_limit */
3877 retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
3878 oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
8c7c6e34
KH
3879 while (retry_count) {
3880 if (signal_pending(current)) {
3881 ret = -EINTR;
3882 break;
3883 }
3884 /*
3885 * Rather than hide all in some function, I do this in
3886 * open coded manner. You see what this really does.
aaad153e 3887 * We have to guarantee memcg->res.limit <= memcg->memsw.limit.
8c7c6e34
KH
3888 */
3889 mutex_lock(&set_limit_mutex);
3890 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3891 if (memlimit > val) {
3892 ret = -EINVAL;
3893 mutex_unlock(&set_limit_mutex);
3894 break;
3895 }
3c11ecf4
KH
3896 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3897 if (memswlimit < val)
3898 enlarge = 1;
8c7c6e34 3899 ret = res_counter_set_limit(&memcg->memsw, val);
22a668d7
KH
3900 if (!ret) {
3901 if (memlimit == val)
3902 memcg->memsw_is_minimum = true;
3903 else
3904 memcg->memsw_is_minimum = false;
3905 }
8c7c6e34
KH
3906 mutex_unlock(&set_limit_mutex);
3907
3908 if (!ret)
3909 break;
3910
5660048c
JW
3911 mem_cgroup_reclaim(memcg, GFP_KERNEL,
3912 MEM_CGROUP_RECLAIM_NOSWAP |
3913 MEM_CGROUP_RECLAIM_SHRINK);
8c7c6e34 3914 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
81d39c20 3915 /* Usage is reduced ? */
8c7c6e34 3916 if (curusage >= oldusage)
628f4235 3917 retry_count--;
81d39c20
KH
3918 else
3919 oldusage = curusage;
628f4235 3920 }
3c11ecf4
KH
3921 if (!ret && enlarge)
3922 memcg_oom_recover(memcg);
628f4235
KH
3923 return ret;
3924}
3925
4e416953 3926unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
0ae5e89c
YH
3927 gfp_t gfp_mask,
3928 unsigned long *total_scanned)
4e416953
BS
3929{
3930 unsigned long nr_reclaimed = 0;
3931 struct mem_cgroup_per_zone *mz, *next_mz = NULL;
3932 unsigned long reclaimed;
3933 int loop = 0;
3934 struct mem_cgroup_tree_per_zone *mctz;
ef8745c1 3935 unsigned long long excess;
0ae5e89c 3936 unsigned long nr_scanned;
4e416953
BS
3937
3938 if (order > 0)
3939 return 0;
3940
00918b6a 3941 mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone));
4e416953
BS
3942 /*
3943 * This loop can run a while, specially if mem_cgroup's continuously
3944 * keep exceeding their soft limit and putting the system under
3945 * pressure
3946 */
3947 do {
3948 if (next_mz)
3949 mz = next_mz;
3950 else
3951 mz = mem_cgroup_largest_soft_limit_node(mctz);
3952 if (!mz)
3953 break;
3954
0ae5e89c 3955 nr_scanned = 0;
d79154bb 3956 reclaimed = mem_cgroup_soft_reclaim(mz->memcg, zone,
5660048c 3957 gfp_mask, &nr_scanned);
4e416953 3958 nr_reclaimed += reclaimed;
0ae5e89c 3959 *total_scanned += nr_scanned;
4e416953
BS
3960 spin_lock(&mctz->lock);
3961
3962 /*
3963 * If we failed to reclaim anything from this memory cgroup
3964 * it is time to move on to the next cgroup
3965 */
3966 next_mz = NULL;
3967 if (!reclaimed) {
3968 do {
3969 /*
3970 * Loop until we find yet another one.
3971 *
3972 * By the time we get the soft_limit lock
3973 * again, someone might have aded the
3974 * group back on the RB tree. Iterate to
3975 * make sure we get a different mem.
3976 * mem_cgroup_largest_soft_limit_node returns
3977 * NULL if no other cgroup is present on
3978 * the tree
3979 */
3980 next_mz =
3981 __mem_cgroup_largest_soft_limit_node(mctz);
39cc98f1 3982 if (next_mz == mz)
d79154bb 3983 css_put(&next_mz->memcg->css);
39cc98f1 3984 else /* next_mz == NULL or other memcg */
4e416953
BS
3985 break;
3986 } while (1);
3987 }
d79154bb
HD
3988 __mem_cgroup_remove_exceeded(mz->memcg, mz, mctz);
3989 excess = res_counter_soft_limit_excess(&mz->memcg->res);
4e416953
BS
3990 /*
3991 * One school of thought says that we should not add
3992 * back the node to the tree if reclaim returns 0.
3993 * But our reclaim could return 0, simply because due
3994 * to priority we are exposing a smaller subset of
3995 * memory to reclaim from. Consider this as a longer
3996 * term TODO.
3997 */
ef8745c1 3998 /* If excess == 0, no tree ops */
d79154bb 3999 __mem_cgroup_insert_exceeded(mz->memcg, mz, mctz, excess);
4e416953 4000 spin_unlock(&mctz->lock);
d79154bb 4001 css_put(&mz->memcg->css);
4e416953
BS
4002 loop++;
4003 /*
4004 * Could not reclaim anything and there are no more
4005 * mem cgroups to try or we seem to be looping without
4006 * reclaiming anything.
4007 */
4008 if (!nr_reclaimed &&
4009 (next_mz == NULL ||
4010 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
4011 break;
4012 } while (!nr_reclaimed);
4013 if (next_mz)
d79154bb 4014 css_put(&next_mz->memcg->css);
4e416953
BS
4015 return nr_reclaimed;
4016}
4017
2ef37d3f
MH
4018/**
4019 * mem_cgroup_force_empty_list - clears LRU of a group
4020 * @memcg: group to clear
4021 * @node: NUMA node
4022 * @zid: zone id
4023 * @lru: lru to to clear
4024 *
3c935d18 4025 * Traverse a specified page_cgroup list and try to drop them all. This doesn't
2ef37d3f
MH
4026 * reclaim the pages page themselves - pages are moved to the parent (or root)
4027 * group.
cc847582 4028 */
2ef37d3f 4029static void mem_cgroup_force_empty_list(struct mem_cgroup *memcg,
08e552c6 4030 int node, int zid, enum lru_list lru)
cc847582 4031{
bea8c150 4032 struct lruvec *lruvec;
2ef37d3f 4033 unsigned long flags;
072c56c1 4034 struct list_head *list;
925b7673
JW
4035 struct page *busy;
4036 struct zone *zone;
072c56c1 4037
08e552c6 4038 zone = &NODE_DATA(node)->node_zones[zid];
bea8c150
HD
4039 lruvec = mem_cgroup_zone_lruvec(zone, memcg);
4040 list = &lruvec->lists[lru];
cc847582 4041
f817ed48 4042 busy = NULL;
2ef37d3f 4043 do {
925b7673 4044 struct page_cgroup *pc;
5564e88b
JW
4045 struct page *page;
4046
08e552c6 4047 spin_lock_irqsave(&zone->lru_lock, flags);
f817ed48 4048 if (list_empty(list)) {
08e552c6 4049 spin_unlock_irqrestore(&zone->lru_lock, flags);
52d4b9ac 4050 break;
f817ed48 4051 }
925b7673
JW
4052 page = list_entry(list->prev, struct page, lru);
4053 if (busy == page) {
4054 list_move(&page->lru, list);
648bcc77 4055 busy = NULL;
08e552c6 4056 spin_unlock_irqrestore(&zone->lru_lock, flags);
f817ed48
KH
4057 continue;
4058 }
08e552c6 4059 spin_unlock_irqrestore(&zone->lru_lock, flags);
f817ed48 4060
925b7673 4061 pc = lookup_page_cgroup(page);
5564e88b 4062
3c935d18 4063 if (mem_cgroup_move_parent(page, pc, memcg)) {
f817ed48 4064 /* found lock contention or "pc" is obsolete. */
925b7673 4065 busy = page;
f817ed48
KH
4066 cond_resched();
4067 } else
4068 busy = NULL;
2ef37d3f 4069 } while (!list_empty(list));
cc847582
KH
4070}
4071
4072/*
c26251f9
MH
4073 * make mem_cgroup's charge to be 0 if there is no task by moving
4074 * all the charges and pages to the parent.
cc847582 4075 * This enables deleting this mem_cgroup.
c26251f9
MH
4076 *
4077 * Caller is responsible for holding css reference on the memcg.
cc847582 4078 */
ab5196c2 4079static void mem_cgroup_reparent_charges(struct mem_cgroup *memcg)
cc847582 4080{
c26251f9 4081 int node, zid;
bea207c8 4082 u64 usage;
f817ed48 4083
fce66477 4084 do {
52d4b9ac
KH
4085 /* This is for making all *used* pages to be on LRU. */
4086 lru_add_drain_all();
c0ff4b85 4087 drain_all_stock_sync(memcg);
c0ff4b85 4088 mem_cgroup_start_move(memcg);
31aaea4a 4089 for_each_node_state(node, N_MEMORY) {
2ef37d3f 4090 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
f156ab93
HD
4091 enum lru_list lru;
4092 for_each_lru(lru) {
2ef37d3f 4093 mem_cgroup_force_empty_list(memcg,
f156ab93 4094 node, zid, lru);
f817ed48 4095 }
1ecaab2b 4096 }
f817ed48 4097 }
c0ff4b85
R
4098 mem_cgroup_end_move(memcg);
4099 memcg_oom_recover(memcg);
52d4b9ac 4100 cond_resched();
f817ed48 4101
2ef37d3f 4102 /*
bea207c8
GC
4103 * Kernel memory may not necessarily be trackable to a specific
4104 * process. So they are not migrated, and therefore we can't
4105 * expect their value to drop to 0 here.
4106 * Having res filled up with kmem only is enough.
4107 *
2ef37d3f
MH
4108 * This is a safety check because mem_cgroup_force_empty_list
4109 * could have raced with mem_cgroup_replace_page_cache callers
4110 * so the lru seemed empty but the page could have been added
4111 * right after the check. RES_USAGE should be safe as we always
4112 * charge before adding to the LRU.
4113 */
bea207c8
GC
4114 usage = res_counter_read_u64(&memcg->res, RES_USAGE) -
4115 res_counter_read_u64(&memcg->kmem, RES_USAGE);
4116 } while (usage > 0);
c26251f9
MH
4117}
4118
4119/*
4120 * Reclaims as many pages from the given memcg as possible and moves
4121 * the rest to the parent.
4122 *
4123 * Caller is responsible for holding css reference for memcg.
4124 */
4125static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
4126{
4127 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
4128 struct cgroup *cgrp = memcg->css.cgroup;
f817ed48 4129
c1e862c1 4130 /* returns EBUSY if there is a task or if we come here twice. */
c26251f9
MH
4131 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
4132 return -EBUSY;
4133
c1e862c1
KH
4134 /* we call try-to-free pages for make this cgroup empty */
4135 lru_add_drain_all();
f817ed48 4136 /* try to free all pages in this cgroup */
569530fb 4137 while (nr_retries && res_counter_read_u64(&memcg->res, RES_USAGE) > 0) {
f817ed48 4138 int progress;
c1e862c1 4139
c26251f9
MH
4140 if (signal_pending(current))
4141 return -EINTR;
4142
c0ff4b85 4143 progress = try_to_free_mem_cgroup_pages(memcg, GFP_KERNEL,
185efc0f 4144 false);
c1e862c1 4145 if (!progress) {
f817ed48 4146 nr_retries--;
c1e862c1 4147 /* maybe some writeback is necessary */
8aa7e847 4148 congestion_wait(BLK_RW_ASYNC, HZ/10);
c1e862c1 4149 }
f817ed48
KH
4150
4151 }
08e552c6 4152 lru_add_drain();
ab5196c2
MH
4153 mem_cgroup_reparent_charges(memcg);
4154
4155 return 0;
cc847582
KH
4156}
4157
6bbda35c 4158static int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
c1e862c1 4159{
c26251f9
MH
4160 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
4161 int ret;
4162
d8423011
MH
4163 if (mem_cgroup_is_root(memcg))
4164 return -EINVAL;
c26251f9
MH
4165 css_get(&memcg->css);
4166 ret = mem_cgroup_force_empty(memcg);
4167 css_put(&memcg->css);
4168
4169 return ret;
c1e862c1
KH
4170}
4171
4172
18f59ea7
BS
4173static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
4174{
4175 return mem_cgroup_from_cont(cont)->use_hierarchy;
4176}
4177
4178static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
4179 u64 val)
4180{
4181 int retval = 0;
c0ff4b85 4182 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
18f59ea7 4183 struct cgroup *parent = cont->parent;
c0ff4b85 4184 struct mem_cgroup *parent_memcg = NULL;
18f59ea7
BS
4185
4186 if (parent)
c0ff4b85 4187 parent_memcg = mem_cgroup_from_cont(parent);
18f59ea7
BS
4188
4189 cgroup_lock();
567fb435
GC
4190
4191 if (memcg->use_hierarchy == val)
4192 goto out;
4193
18f59ea7 4194 /*
af901ca1 4195 * If parent's use_hierarchy is set, we can't make any modifications
18f59ea7
BS
4196 * in the child subtrees. If it is unset, then the change can
4197 * occur, provided the current cgroup has no children.
4198 *
4199 * For the root cgroup, parent_mem is NULL, we allow value to be
4200 * set if there are no children.
4201 */
c0ff4b85 4202 if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
18f59ea7
BS
4203 (val == 1 || val == 0)) {
4204 if (list_empty(&cont->children))
c0ff4b85 4205 memcg->use_hierarchy = val;
18f59ea7
BS
4206 else
4207 retval = -EBUSY;
4208 } else
4209 retval = -EINVAL;
567fb435
GC
4210
4211out:
18f59ea7
BS
4212 cgroup_unlock();
4213
4214 return retval;
4215}
4216
0c3e73e8 4217
c0ff4b85 4218static unsigned long mem_cgroup_recursive_stat(struct mem_cgroup *memcg,
7a159cc9 4219 enum mem_cgroup_stat_index idx)
0c3e73e8 4220{
7d74b06f 4221 struct mem_cgroup *iter;
7a159cc9 4222 long val = 0;
0c3e73e8 4223
7a159cc9 4224 /* Per-cpu values can be negative, use a signed accumulator */
c0ff4b85 4225 for_each_mem_cgroup_tree(iter, memcg)
7d74b06f
KH
4226 val += mem_cgroup_read_stat(iter, idx);
4227
4228 if (val < 0) /* race ? */
4229 val = 0;
4230 return val;
0c3e73e8
BS
4231}
4232
c0ff4b85 4233static inline u64 mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
104f3928 4234{
7d74b06f 4235 u64 val;
104f3928 4236
c0ff4b85 4237 if (!mem_cgroup_is_root(memcg)) {
104f3928 4238 if (!swap)
65c64ce8 4239 return res_counter_read_u64(&memcg->res, RES_USAGE);
104f3928 4240 else
65c64ce8 4241 return res_counter_read_u64(&memcg->memsw, RES_USAGE);
104f3928
KS
4242 }
4243
c0ff4b85
R
4244 val = mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_CACHE);
4245 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_RSS);
104f3928 4246
7d74b06f 4247 if (swap)
bff6bb83 4248 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_SWAP);
104f3928
KS
4249
4250 return val << PAGE_SHIFT;
4251}
4252
af36f906
TH
4253static ssize_t mem_cgroup_read(struct cgroup *cont, struct cftype *cft,
4254 struct file *file, char __user *buf,
4255 size_t nbytes, loff_t *ppos)
8cdea7c0 4256{
c0ff4b85 4257 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
af36f906 4258 char str[64];
104f3928 4259 u64 val;
86ae53e1
GC
4260 int name, len;
4261 enum res_type type;
8c7c6e34
KH
4262
4263 type = MEMFILE_TYPE(cft->private);
4264 name = MEMFILE_ATTR(cft->private);
af36f906
TH
4265
4266 if (!do_swap_account && type == _MEMSWAP)
4267 return -EOPNOTSUPP;
4268
8c7c6e34
KH
4269 switch (type) {
4270 case _MEM:
104f3928 4271 if (name == RES_USAGE)
c0ff4b85 4272 val = mem_cgroup_usage(memcg, false);
104f3928 4273 else
c0ff4b85 4274 val = res_counter_read_u64(&memcg->res, name);
8c7c6e34
KH
4275 break;
4276 case _MEMSWAP:
104f3928 4277 if (name == RES_USAGE)
c0ff4b85 4278 val = mem_cgroup_usage(memcg, true);
104f3928 4279 else
c0ff4b85 4280 val = res_counter_read_u64(&memcg->memsw, name);
8c7c6e34 4281 break;
510fc4e1
GC
4282 case _KMEM:
4283 val = res_counter_read_u64(&memcg->kmem, name);
4284 break;
8c7c6e34
KH
4285 default:
4286 BUG();
8c7c6e34 4287 }
af36f906
TH
4288
4289 len = scnprintf(str, sizeof(str), "%llu\n", (unsigned long long)val);
4290 return simple_read_from_buffer(buf, nbytes, ppos, str, len);
8cdea7c0 4291}
510fc4e1
GC
4292
4293static int memcg_update_kmem_limit(struct cgroup *cont, u64 val)
4294{
4295 int ret = -EINVAL;
4296#ifdef CONFIG_MEMCG_KMEM
a8964b9b
GC
4297 bool must_inc_static_branch = false;
4298
510fc4e1
GC
4299 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
4300 /*
4301 * For simplicity, we won't allow this to be disabled. It also can't
4302 * be changed if the cgroup has children already, or if tasks had
4303 * already joined.
4304 *
4305 * If tasks join before we set the limit, a person looking at
4306 * kmem.usage_in_bytes will have no way to determine when it took
4307 * place, which makes the value quite meaningless.
4308 *
4309 * After it first became limited, changes in the value of the limit are
4310 * of course permitted.
4311 *
4312 * Taking the cgroup_lock is really offensive, but it is so far the only
4313 * way to guarantee that no children will appear. There are plenty of
4314 * other offenders, and they should all go away. Fine grained locking
4315 * is probably the way to go here. When we are fully hierarchical, we
4316 * can also get rid of the use_hierarchy check.
4317 */
4318 cgroup_lock();
4319 mutex_lock(&set_limit_mutex);
4320 if (!memcg->kmem_account_flags && val != RESOURCE_MAX) {
4321 if (cgroup_task_count(cont) || (memcg->use_hierarchy &&
4322 !list_empty(&cont->children))) {
4323 ret = -EBUSY;
4324 goto out;
4325 }
4326 ret = res_counter_set_limit(&memcg->kmem, val);
4327 VM_BUG_ON(ret);
4328
a8964b9b
GC
4329 /*
4330 * After this point, kmem_accounted (that we test atomically in
4331 * the beginning of this conditional), is no longer 0. This
4332 * guarantees only one process will set the following boolean
4333 * to true. We don't need test_and_set because we're protected
4334 * by the set_limit_mutex anyway.
4335 */
4336 memcg_kmem_set_activated(memcg);
4337 must_inc_static_branch = true;
7de37682
GC
4338 /*
4339 * kmem charges can outlive the cgroup. In the case of slab
4340 * pages, for instance, a page contain objects from various
4341 * processes, so it is unfeasible to migrate them away. We
4342 * need to reference count the memcg because of that.
4343 */
4344 mem_cgroup_get(memcg);
510fc4e1
GC
4345 } else
4346 ret = res_counter_set_limit(&memcg->kmem, val);
4347out:
4348 mutex_unlock(&set_limit_mutex);
4349 cgroup_unlock();
a8964b9b
GC
4350
4351 /*
4352 * We are by now familiar with the fact that we can't inc the static
4353 * branch inside cgroup_lock. See disarm functions for details. A
4354 * worker here is overkill, but also wrong: After the limit is set, we
4355 * must start accounting right away. Since this operation can't fail,
4356 * we can safely defer it to here - no rollback will be needed.
4357 *
4358 * The boolean used to control this is also safe, because
4359 * KMEM_ACCOUNTED_ACTIVATED guarantees that only one process will be
4360 * able to set it to true;
4361 */
4362 if (must_inc_static_branch) {
4363 static_key_slow_inc(&memcg_kmem_enabled_key);
4364 /*
4365 * setting the active bit after the inc will guarantee no one
4366 * starts accounting before all call sites are patched
4367 */
4368 memcg_kmem_set_active(memcg);
4369 }
4370
510fc4e1
GC
4371#endif
4372 return ret;
4373}
4374
4375static void memcg_propagate_kmem(struct mem_cgroup *memcg)
4376{
4377 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
4378 if (!parent)
4379 return;
4380 memcg->kmem_account_flags = parent->kmem_account_flags;
7de37682 4381#ifdef CONFIG_MEMCG_KMEM
a8964b9b
GC
4382 /*
4383 * When that happen, we need to disable the static branch only on those
4384 * memcgs that enabled it. To achieve this, we would be forced to
4385 * complicate the code by keeping track of which memcgs were the ones
4386 * that actually enabled limits, and which ones got it from its
4387 * parents.
4388 *
4389 * It is a lot simpler just to do static_key_slow_inc() on every child
4390 * that is accounted.
4391 */
4392 if (memcg_kmem_is_active(memcg)) {
7de37682 4393 mem_cgroup_get(memcg);
a8964b9b
GC
4394 static_key_slow_inc(&memcg_kmem_enabled_key);
4395 }
7de37682 4396#endif
510fc4e1
GC
4397}
4398
628f4235
KH
4399/*
4400 * The user of this function is...
4401 * RES_LIMIT.
4402 */
856c13aa
PM
4403static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
4404 const char *buffer)
8cdea7c0 4405{
628f4235 4406 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
86ae53e1
GC
4407 enum res_type type;
4408 int name;
628f4235
KH
4409 unsigned long long val;
4410 int ret;
4411
8c7c6e34
KH
4412 type = MEMFILE_TYPE(cft->private);
4413 name = MEMFILE_ATTR(cft->private);
af36f906
TH
4414
4415 if (!do_swap_account && type == _MEMSWAP)
4416 return -EOPNOTSUPP;
4417
8c7c6e34 4418 switch (name) {
628f4235 4419 case RES_LIMIT:
4b3bde4c
BS
4420 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
4421 ret = -EINVAL;
4422 break;
4423 }
628f4235
KH
4424 /* This function does all necessary parse...reuse it */
4425 ret = res_counter_memparse_write_strategy(buffer, &val);
8c7c6e34
KH
4426 if (ret)
4427 break;
4428 if (type == _MEM)
628f4235 4429 ret = mem_cgroup_resize_limit(memcg, val);
510fc4e1 4430 else if (type == _MEMSWAP)
8c7c6e34 4431 ret = mem_cgroup_resize_memsw_limit(memcg, val);
510fc4e1
GC
4432 else if (type == _KMEM)
4433 ret = memcg_update_kmem_limit(cont, val);
4434 else
4435 return -EINVAL;
628f4235 4436 break;
296c81d8
BS
4437 case RES_SOFT_LIMIT:
4438 ret = res_counter_memparse_write_strategy(buffer, &val);
4439 if (ret)
4440 break;
4441 /*
4442 * For memsw, soft limits are hard to implement in terms
4443 * of semantics, for now, we support soft limits for
4444 * control without swap
4445 */
4446 if (type == _MEM)
4447 ret = res_counter_set_soft_limit(&memcg->res, val);
4448 else
4449 ret = -EINVAL;
4450 break;
628f4235
KH
4451 default:
4452 ret = -EINVAL; /* should be BUG() ? */
4453 break;
4454 }
4455 return ret;
8cdea7c0
BS
4456}
4457
fee7b548
KH
4458static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
4459 unsigned long long *mem_limit, unsigned long long *memsw_limit)
4460{
4461 struct cgroup *cgroup;
4462 unsigned long long min_limit, min_memsw_limit, tmp;
4463
4464 min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
4465 min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
4466 cgroup = memcg->css.cgroup;
4467 if (!memcg->use_hierarchy)
4468 goto out;
4469
4470 while (cgroup->parent) {
4471 cgroup = cgroup->parent;
4472 memcg = mem_cgroup_from_cont(cgroup);
4473 if (!memcg->use_hierarchy)
4474 break;
4475 tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
4476 min_limit = min(min_limit, tmp);
4477 tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
4478 min_memsw_limit = min(min_memsw_limit, tmp);
4479 }
4480out:
4481 *mem_limit = min_limit;
4482 *memsw_limit = min_memsw_limit;
fee7b548
KH
4483}
4484
29f2a4da 4485static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
c84872e1 4486{
af36f906 4487 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
86ae53e1
GC
4488 int name;
4489 enum res_type type;
c84872e1 4490
8c7c6e34
KH
4491 type = MEMFILE_TYPE(event);
4492 name = MEMFILE_ATTR(event);
af36f906
TH
4493
4494 if (!do_swap_account && type == _MEMSWAP)
4495 return -EOPNOTSUPP;
4496
8c7c6e34 4497 switch (name) {
29f2a4da 4498 case RES_MAX_USAGE:
8c7c6e34 4499 if (type == _MEM)
c0ff4b85 4500 res_counter_reset_max(&memcg->res);
510fc4e1 4501 else if (type == _MEMSWAP)
c0ff4b85 4502 res_counter_reset_max(&memcg->memsw);
510fc4e1
GC
4503 else if (type == _KMEM)
4504 res_counter_reset_max(&memcg->kmem);
4505 else
4506 return -EINVAL;
29f2a4da
PE
4507 break;
4508 case RES_FAILCNT:
8c7c6e34 4509 if (type == _MEM)
c0ff4b85 4510 res_counter_reset_failcnt(&memcg->res);
510fc4e1 4511 else if (type == _MEMSWAP)
c0ff4b85 4512 res_counter_reset_failcnt(&memcg->memsw);
510fc4e1
GC
4513 else if (type == _KMEM)
4514 res_counter_reset_failcnt(&memcg->kmem);
4515 else
4516 return -EINVAL;
29f2a4da
PE
4517 break;
4518 }
f64c3f54 4519
85cc59db 4520 return 0;
c84872e1
PE
4521}
4522
7dc74be0
DN
4523static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp,
4524 struct cftype *cft)
4525{
4526 return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate;
4527}
4528
02491447 4529#ifdef CONFIG_MMU
7dc74be0
DN
4530static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
4531 struct cftype *cft, u64 val)
4532{
c0ff4b85 4533 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
7dc74be0
DN
4534
4535 if (val >= (1 << NR_MOVE_TYPE))
4536 return -EINVAL;
4537 /*
4538 * We check this value several times in both in can_attach() and
4539 * attach(), so we need cgroup lock to prevent this value from being
4540 * inconsistent.
4541 */
4542 cgroup_lock();
c0ff4b85 4543 memcg->move_charge_at_immigrate = val;
7dc74be0
DN
4544 cgroup_unlock();
4545
4546 return 0;
4547}
02491447
DN
4548#else
4549static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
4550 struct cftype *cft, u64 val)
4551{
4552 return -ENOSYS;
4553}
4554#endif
7dc74be0 4555
406eb0c9 4556#ifdef CONFIG_NUMA
ab215884 4557static int memcg_numa_stat_show(struct cgroup *cont, struct cftype *cft,
fada52ca 4558 struct seq_file *m)
406eb0c9
YH
4559{
4560 int nid;
4561 unsigned long total_nr, file_nr, anon_nr, unevictable_nr;
4562 unsigned long node_nr;
d79154bb 4563 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
406eb0c9 4564
d79154bb 4565 total_nr = mem_cgroup_nr_lru_pages(memcg, LRU_ALL);
406eb0c9 4566 seq_printf(m, "total=%lu", total_nr);
31aaea4a 4567 for_each_node_state(nid, N_MEMORY) {
d79154bb 4568 node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL);
406eb0c9
YH
4569 seq_printf(m, " N%d=%lu", nid, node_nr);
4570 }
4571 seq_putc(m, '\n');
4572
d79154bb 4573 file_nr = mem_cgroup_nr_lru_pages(memcg, LRU_ALL_FILE);
406eb0c9 4574 seq_printf(m, "file=%lu", file_nr);
31aaea4a 4575 for_each_node_state(nid, N_MEMORY) {
d79154bb 4576 node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
bb2a0de9 4577 LRU_ALL_FILE);
406eb0c9
YH
4578 seq_printf(m, " N%d=%lu", nid, node_nr);
4579 }
4580 seq_putc(m, '\n');
4581
d79154bb 4582 anon_nr = mem_cgroup_nr_lru_pages(memcg, LRU_ALL_ANON);
406eb0c9 4583 seq_printf(m, "anon=%lu", anon_nr);
31aaea4a 4584 for_each_node_state(nid, N_MEMORY) {
d79154bb 4585 node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
bb2a0de9 4586 LRU_ALL_ANON);
406eb0c9
YH
4587 seq_printf(m, " N%d=%lu", nid, node_nr);
4588 }
4589 seq_putc(m, '\n');
4590
d79154bb 4591 unevictable_nr = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_UNEVICTABLE));
406eb0c9 4592 seq_printf(m, "unevictable=%lu", unevictable_nr);
31aaea4a 4593 for_each_node_state(nid, N_MEMORY) {
d79154bb 4594 node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
bb2a0de9 4595 BIT(LRU_UNEVICTABLE));
406eb0c9
YH
4596 seq_printf(m, " N%d=%lu", nid, node_nr);
4597 }
4598 seq_putc(m, '\n');
4599 return 0;
4600}
4601#endif /* CONFIG_NUMA */
4602
af7c4b0e
JW
4603static const char * const mem_cgroup_lru_names[] = {
4604 "inactive_anon",
4605 "active_anon",
4606 "inactive_file",
4607 "active_file",
4608 "unevictable",
4609};
4610
4611static inline void mem_cgroup_lru_names_not_uptodate(void)
4612{
4613 BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_lru_names) != NR_LRU_LISTS);
4614}
4615
ab215884 4616static int memcg_stat_show(struct cgroup *cont, struct cftype *cft,
78ccf5b5 4617 struct seq_file *m)
d2ceb9b7 4618{
d79154bb 4619 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
af7c4b0e
JW
4620 struct mem_cgroup *mi;
4621 unsigned int i;
406eb0c9 4622
af7c4b0e 4623 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
bff6bb83 4624 if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
1dd3a273 4625 continue;
af7c4b0e
JW
4626 seq_printf(m, "%s %ld\n", mem_cgroup_stat_names[i],
4627 mem_cgroup_read_stat(memcg, i) * PAGE_SIZE);
1dd3a273 4628 }
7b854121 4629
af7c4b0e
JW
4630 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++)
4631 seq_printf(m, "%s %lu\n", mem_cgroup_events_names[i],
4632 mem_cgroup_read_events(memcg, i));
4633
4634 for (i = 0; i < NR_LRU_LISTS; i++)
4635 seq_printf(m, "%s %lu\n", mem_cgroup_lru_names[i],
4636 mem_cgroup_nr_lru_pages(memcg, BIT(i)) * PAGE_SIZE);
4637
14067bb3 4638 /* Hierarchical information */
fee7b548
KH
4639 {
4640 unsigned long long limit, memsw_limit;
d79154bb 4641 memcg_get_hierarchical_limit(memcg, &limit, &memsw_limit);
78ccf5b5 4642 seq_printf(m, "hierarchical_memory_limit %llu\n", limit);
fee7b548 4643 if (do_swap_account)
78ccf5b5
JW
4644 seq_printf(m, "hierarchical_memsw_limit %llu\n",
4645 memsw_limit);
fee7b548 4646 }
7f016ee8 4647
af7c4b0e
JW
4648 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
4649 long long val = 0;
4650
bff6bb83 4651 if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
1dd3a273 4652 continue;
af7c4b0e
JW
4653 for_each_mem_cgroup_tree(mi, memcg)
4654 val += mem_cgroup_read_stat(mi, i) * PAGE_SIZE;
4655 seq_printf(m, "total_%s %lld\n", mem_cgroup_stat_names[i], val);
4656 }
4657
4658 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
4659 unsigned long long val = 0;
4660
4661 for_each_mem_cgroup_tree(mi, memcg)
4662 val += mem_cgroup_read_events(mi, i);
4663 seq_printf(m, "total_%s %llu\n",
4664 mem_cgroup_events_names[i], val);
4665 }
4666
4667 for (i = 0; i < NR_LRU_LISTS; i++) {
4668 unsigned long long val = 0;
4669
4670 for_each_mem_cgroup_tree(mi, memcg)
4671 val += mem_cgroup_nr_lru_pages(mi, BIT(i)) * PAGE_SIZE;
4672 seq_printf(m, "total_%s %llu\n", mem_cgroup_lru_names[i], val);
1dd3a273 4673 }
14067bb3 4674
7f016ee8 4675#ifdef CONFIG_DEBUG_VM
7f016ee8
KM
4676 {
4677 int nid, zid;
4678 struct mem_cgroup_per_zone *mz;
89abfab1 4679 struct zone_reclaim_stat *rstat;
7f016ee8
KM
4680 unsigned long recent_rotated[2] = {0, 0};
4681 unsigned long recent_scanned[2] = {0, 0};
4682
4683 for_each_online_node(nid)
4684 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
d79154bb 4685 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
89abfab1 4686 rstat = &mz->lruvec.reclaim_stat;
7f016ee8 4687
89abfab1
HD
4688 recent_rotated[0] += rstat->recent_rotated[0];
4689 recent_rotated[1] += rstat->recent_rotated[1];
4690 recent_scanned[0] += rstat->recent_scanned[0];
4691 recent_scanned[1] += rstat->recent_scanned[1];
7f016ee8 4692 }
78ccf5b5
JW
4693 seq_printf(m, "recent_rotated_anon %lu\n", recent_rotated[0]);
4694 seq_printf(m, "recent_rotated_file %lu\n", recent_rotated[1]);
4695 seq_printf(m, "recent_scanned_anon %lu\n", recent_scanned[0]);
4696 seq_printf(m, "recent_scanned_file %lu\n", recent_scanned[1]);
7f016ee8
KM
4697 }
4698#endif
4699
d2ceb9b7
KH
4700 return 0;
4701}
4702
a7885eb8
KM
4703static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
4704{
4705 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4706
1f4c025b 4707 return mem_cgroup_swappiness(memcg);
a7885eb8
KM
4708}
4709
4710static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
4711 u64 val)
4712{
4713 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4714 struct mem_cgroup *parent;
068b38c1 4715
a7885eb8
KM
4716 if (val > 100)
4717 return -EINVAL;
4718
4719 if (cgrp->parent == NULL)
4720 return -EINVAL;
4721
4722 parent = mem_cgroup_from_cont(cgrp->parent);
068b38c1
LZ
4723
4724 cgroup_lock();
4725
a7885eb8
KM
4726 /* If under hierarchy, only empty-root can set this value */
4727 if ((parent->use_hierarchy) ||
068b38c1
LZ
4728 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
4729 cgroup_unlock();
a7885eb8 4730 return -EINVAL;
068b38c1 4731 }
a7885eb8 4732
a7885eb8 4733 memcg->swappiness = val;
a7885eb8 4734
068b38c1
LZ
4735 cgroup_unlock();
4736
a7885eb8
KM
4737 return 0;
4738}
4739
2e72b634
KS
4740static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4741{
4742 struct mem_cgroup_threshold_ary *t;
4743 u64 usage;
4744 int i;
4745
4746 rcu_read_lock();
4747 if (!swap)
2c488db2 4748 t = rcu_dereference(memcg->thresholds.primary);
2e72b634 4749 else
2c488db2 4750 t = rcu_dereference(memcg->memsw_thresholds.primary);
2e72b634
KS
4751
4752 if (!t)
4753 goto unlock;
4754
4755 usage = mem_cgroup_usage(memcg, swap);
4756
4757 /*
748dad36 4758 * current_threshold points to threshold just below or equal to usage.
2e72b634
KS
4759 * If it's not true, a threshold was crossed after last
4760 * call of __mem_cgroup_threshold().
4761 */
5407a562 4762 i = t->current_threshold;
2e72b634
KS
4763
4764 /*
4765 * Iterate backward over array of thresholds starting from
4766 * current_threshold and check if a threshold is crossed.
4767 * If none of thresholds below usage is crossed, we read
4768 * only one element of the array here.
4769 */
4770 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4771 eventfd_signal(t->entries[i].eventfd, 1);
4772
4773 /* i = current_threshold + 1 */
4774 i++;
4775
4776 /*
4777 * Iterate forward over array of thresholds starting from
4778 * current_threshold+1 and check if a threshold is crossed.
4779 * If none of thresholds above usage is crossed, we read
4780 * only one element of the array here.
4781 */
4782 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4783 eventfd_signal(t->entries[i].eventfd, 1);
4784
4785 /* Update current_threshold */
5407a562 4786 t->current_threshold = i - 1;
2e72b634
KS
4787unlock:
4788 rcu_read_unlock();
4789}
4790
4791static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4792{
ad4ca5f4
KS
4793 while (memcg) {
4794 __mem_cgroup_threshold(memcg, false);
4795 if (do_swap_account)
4796 __mem_cgroup_threshold(memcg, true);
4797
4798 memcg = parent_mem_cgroup(memcg);
4799 }
2e72b634
KS
4800}
4801
4802static int compare_thresholds(const void *a, const void *b)
4803{
4804 const struct mem_cgroup_threshold *_a = a;
4805 const struct mem_cgroup_threshold *_b = b;
4806
4807 return _a->threshold - _b->threshold;
4808}
4809
c0ff4b85 4810static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
9490ff27
KH
4811{
4812 struct mem_cgroup_eventfd_list *ev;
4813
c0ff4b85 4814 list_for_each_entry(ev, &memcg->oom_notify, list)
9490ff27
KH
4815 eventfd_signal(ev->eventfd, 1);
4816 return 0;
4817}
4818
c0ff4b85 4819static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
9490ff27 4820{
7d74b06f
KH
4821 struct mem_cgroup *iter;
4822
c0ff4b85 4823 for_each_mem_cgroup_tree(iter, memcg)
7d74b06f 4824 mem_cgroup_oom_notify_cb(iter);
9490ff27
KH
4825}
4826
4827static int mem_cgroup_usage_register_event(struct cgroup *cgrp,
4828 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
2e72b634
KS
4829{
4830 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
2c488db2
KS
4831 struct mem_cgroup_thresholds *thresholds;
4832 struct mem_cgroup_threshold_ary *new;
86ae53e1 4833 enum res_type type = MEMFILE_TYPE(cft->private);
2e72b634 4834 u64 threshold, usage;
2c488db2 4835 int i, size, ret;
2e72b634
KS
4836
4837 ret = res_counter_memparse_write_strategy(args, &threshold);
4838 if (ret)
4839 return ret;
4840
4841 mutex_lock(&memcg->thresholds_lock);
2c488db2 4842
2e72b634 4843 if (type == _MEM)
2c488db2 4844 thresholds = &memcg->thresholds;
2e72b634 4845 else if (type == _MEMSWAP)
2c488db2 4846 thresholds = &memcg->memsw_thresholds;
2e72b634
KS
4847 else
4848 BUG();
4849
4850 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
4851
4852 /* Check if a threshold crossed before adding a new one */
2c488db2 4853 if (thresholds->primary)
2e72b634
KS
4854 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4855
2c488db2 4856 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
2e72b634
KS
4857
4858 /* Allocate memory for new array of thresholds */
2c488db2 4859 new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
2e72b634 4860 GFP_KERNEL);
2c488db2 4861 if (!new) {
2e72b634
KS
4862 ret = -ENOMEM;
4863 goto unlock;
4864 }
2c488db2 4865 new->size = size;
2e72b634
KS
4866
4867 /* Copy thresholds (if any) to new array */
2c488db2
KS
4868 if (thresholds->primary) {
4869 memcpy(new->entries, thresholds->primary->entries, (size - 1) *
2e72b634 4870 sizeof(struct mem_cgroup_threshold));
2c488db2
KS
4871 }
4872
2e72b634 4873 /* Add new threshold */
2c488db2
KS
4874 new->entries[size - 1].eventfd = eventfd;
4875 new->entries[size - 1].threshold = threshold;
2e72b634
KS
4876
4877 /* Sort thresholds. Registering of new threshold isn't time-critical */
2c488db2 4878 sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
2e72b634
KS
4879 compare_thresholds, NULL);
4880
4881 /* Find current threshold */
2c488db2 4882 new->current_threshold = -1;
2e72b634 4883 for (i = 0; i < size; i++) {
748dad36 4884 if (new->entries[i].threshold <= usage) {
2e72b634 4885 /*
2c488db2
KS
4886 * new->current_threshold will not be used until
4887 * rcu_assign_pointer(), so it's safe to increment
2e72b634
KS
4888 * it here.
4889 */
2c488db2 4890 ++new->current_threshold;
748dad36
SZ
4891 } else
4892 break;
2e72b634
KS
4893 }
4894
2c488db2
KS
4895 /* Free old spare buffer and save old primary buffer as spare */
4896 kfree(thresholds->spare);
4897 thresholds->spare = thresholds->primary;
4898
4899 rcu_assign_pointer(thresholds->primary, new);
2e72b634 4900
907860ed 4901 /* To be sure that nobody uses thresholds */
2e72b634
KS
4902 synchronize_rcu();
4903
2e72b634
KS
4904unlock:
4905 mutex_unlock(&memcg->thresholds_lock);
4906
4907 return ret;
4908}
4909
907860ed 4910static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,
9490ff27 4911 struct cftype *cft, struct eventfd_ctx *eventfd)
2e72b634
KS
4912{
4913 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
2c488db2
KS
4914 struct mem_cgroup_thresholds *thresholds;
4915 struct mem_cgroup_threshold_ary *new;
86ae53e1 4916 enum res_type type = MEMFILE_TYPE(cft->private);
2e72b634 4917 u64 usage;
2c488db2 4918 int i, j, size;
2e72b634
KS
4919
4920 mutex_lock(&memcg->thresholds_lock);
4921 if (type == _MEM)
2c488db2 4922 thresholds = &memcg->thresholds;
2e72b634 4923 else if (type == _MEMSWAP)
2c488db2 4924 thresholds = &memcg->memsw_thresholds;
2e72b634
KS
4925 else
4926 BUG();
4927
371528ca
AV
4928 if (!thresholds->primary)
4929 goto unlock;
4930
2e72b634
KS
4931 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
4932
4933 /* Check if a threshold crossed before removing */
4934 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4935
4936 /* Calculate new number of threshold */
2c488db2
KS
4937 size = 0;
4938 for (i = 0; i < thresholds->primary->size; i++) {
4939 if (thresholds->primary->entries[i].eventfd != eventfd)
2e72b634
KS
4940 size++;
4941 }
4942
2c488db2 4943 new = thresholds->spare;
907860ed 4944
2e72b634
KS
4945 /* Set thresholds array to NULL if we don't have thresholds */
4946 if (!size) {
2c488db2
KS
4947 kfree(new);
4948 new = NULL;
907860ed 4949 goto swap_buffers;
2e72b634
KS
4950 }
4951
2c488db2 4952 new->size = size;
2e72b634
KS
4953
4954 /* Copy thresholds and find current threshold */
2c488db2
KS
4955 new->current_threshold = -1;
4956 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4957 if (thresholds->primary->entries[i].eventfd == eventfd)
2e72b634
KS
4958 continue;
4959
2c488db2 4960 new->entries[j] = thresholds->primary->entries[i];
748dad36 4961 if (new->entries[j].threshold <= usage) {
2e72b634 4962 /*
2c488db2 4963 * new->current_threshold will not be used
2e72b634
KS
4964 * until rcu_assign_pointer(), so it's safe to increment
4965 * it here.
4966 */
2c488db2 4967 ++new->current_threshold;
2e72b634
KS
4968 }
4969 j++;
4970 }
4971
907860ed 4972swap_buffers:
2c488db2
KS
4973 /* Swap primary and spare array */
4974 thresholds->spare = thresholds->primary;
8c757763
SZ
4975 /* If all events are unregistered, free the spare array */
4976 if (!new) {
4977 kfree(thresholds->spare);
4978 thresholds->spare = NULL;
4979 }
4980
2c488db2 4981 rcu_assign_pointer(thresholds->primary, new);
2e72b634 4982
907860ed 4983 /* To be sure that nobody uses thresholds */
2e72b634 4984 synchronize_rcu();
371528ca 4985unlock:
2e72b634 4986 mutex_unlock(&memcg->thresholds_lock);
2e72b634 4987}
c1e862c1 4988
9490ff27
KH
4989static int mem_cgroup_oom_register_event(struct cgroup *cgrp,
4990 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
4991{
4992 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4993 struct mem_cgroup_eventfd_list *event;
86ae53e1 4994 enum res_type type = MEMFILE_TYPE(cft->private);
9490ff27
KH
4995
4996 BUG_ON(type != _OOM_TYPE);
4997 event = kmalloc(sizeof(*event), GFP_KERNEL);
4998 if (!event)
4999 return -ENOMEM;
5000
1af8efe9 5001 spin_lock(&memcg_oom_lock);
9490ff27
KH
5002
5003 event->eventfd = eventfd;
5004 list_add(&event->list, &memcg->oom_notify);
5005
5006 /* already in OOM ? */
79dfdacc 5007 if (atomic_read(&memcg->under_oom))
9490ff27 5008 eventfd_signal(eventfd, 1);
1af8efe9 5009 spin_unlock(&memcg_oom_lock);
9490ff27
KH
5010
5011 return 0;
5012}
5013
907860ed 5014static void mem_cgroup_oom_unregister_event(struct cgroup *cgrp,
9490ff27
KH
5015 struct cftype *cft, struct eventfd_ctx *eventfd)
5016{
c0ff4b85 5017 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
9490ff27 5018 struct mem_cgroup_eventfd_list *ev, *tmp;
86ae53e1 5019 enum res_type type = MEMFILE_TYPE(cft->private);
9490ff27
KH
5020
5021 BUG_ON(type != _OOM_TYPE);
5022
1af8efe9 5023 spin_lock(&memcg_oom_lock);
9490ff27 5024
c0ff4b85 5025 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
9490ff27
KH
5026 if (ev->eventfd == eventfd) {
5027 list_del(&ev->list);
5028 kfree(ev);
5029 }
5030 }
5031
1af8efe9 5032 spin_unlock(&memcg_oom_lock);
9490ff27
KH
5033}
5034
3c11ecf4
KH
5035static int mem_cgroup_oom_control_read(struct cgroup *cgrp,
5036 struct cftype *cft, struct cgroup_map_cb *cb)
5037{
c0ff4b85 5038 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3c11ecf4 5039
c0ff4b85 5040 cb->fill(cb, "oom_kill_disable", memcg->oom_kill_disable);
3c11ecf4 5041
c0ff4b85 5042 if (atomic_read(&memcg->under_oom))
3c11ecf4
KH
5043 cb->fill(cb, "under_oom", 1);
5044 else
5045 cb->fill(cb, "under_oom", 0);
5046 return 0;
5047}
5048
3c11ecf4
KH
5049static int mem_cgroup_oom_control_write(struct cgroup *cgrp,
5050 struct cftype *cft, u64 val)
5051{
c0ff4b85 5052 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3c11ecf4
KH
5053 struct mem_cgroup *parent;
5054
5055 /* cannot set to root cgroup and only 0 and 1 are allowed */
5056 if (!cgrp->parent || !((val == 0) || (val == 1)))
5057 return -EINVAL;
5058
5059 parent = mem_cgroup_from_cont(cgrp->parent);
5060
5061 cgroup_lock();
5062 /* oom-kill-disable is a flag for subhierarchy. */
5063 if ((parent->use_hierarchy) ||
c0ff4b85 5064 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
3c11ecf4
KH
5065 cgroup_unlock();
5066 return -EINVAL;
5067 }
c0ff4b85 5068 memcg->oom_kill_disable = val;
4d845ebf 5069 if (!val)
c0ff4b85 5070 memcg_oom_recover(memcg);
3c11ecf4
KH
5071 cgroup_unlock();
5072 return 0;
5073}
5074
c255a458 5075#ifdef CONFIG_MEMCG_KMEM
cbe128e3 5076static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
e5671dfa 5077{
2633d7a0 5078 memcg->kmemcg_id = -1;
510fc4e1 5079 memcg_propagate_kmem(memcg);
2633d7a0 5080
1d62e436 5081 return mem_cgroup_sockets_init(memcg, ss);
e5671dfa
GC
5082};
5083
1d62e436 5084static void kmem_cgroup_destroy(struct mem_cgroup *memcg)
d1a4c0b3 5085{
1d62e436 5086 mem_cgroup_sockets_destroy(memcg);
7de37682
GC
5087
5088 memcg_kmem_mark_dead(memcg);
5089
5090 if (res_counter_read_u64(&memcg->kmem, RES_USAGE) != 0)
5091 return;
5092
5093 /*
5094 * Charges already down to 0, undo mem_cgroup_get() done in the charge
5095 * path here, being careful not to race with memcg_uncharge_kmem: it is
5096 * possible that the charges went down to 0 between mark_dead and the
5097 * res_counter read, so in that case, we don't need the put
5098 */
5099 if (memcg_kmem_test_and_clear_dead(memcg))
5100 mem_cgroup_put(memcg);
d1a4c0b3 5101}
e5671dfa 5102#else
cbe128e3 5103static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
e5671dfa
GC
5104{
5105 return 0;
5106}
d1a4c0b3 5107
1d62e436 5108static void kmem_cgroup_destroy(struct mem_cgroup *memcg)
d1a4c0b3
GC
5109{
5110}
e5671dfa
GC
5111#endif
5112
8cdea7c0
BS
5113static struct cftype mem_cgroup_files[] = {
5114 {
0eea1030 5115 .name = "usage_in_bytes",
8c7c6e34 5116 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
af36f906 5117 .read = mem_cgroup_read,
9490ff27
KH
5118 .register_event = mem_cgroup_usage_register_event,
5119 .unregister_event = mem_cgroup_usage_unregister_event,
8cdea7c0 5120 },
c84872e1
PE
5121 {
5122 .name = "max_usage_in_bytes",
8c7c6e34 5123 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
29f2a4da 5124 .trigger = mem_cgroup_reset,
af36f906 5125 .read = mem_cgroup_read,
c84872e1 5126 },
8cdea7c0 5127 {
0eea1030 5128 .name = "limit_in_bytes",
8c7c6e34 5129 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
856c13aa 5130 .write_string = mem_cgroup_write,
af36f906 5131 .read = mem_cgroup_read,
8cdea7c0 5132 },
296c81d8
BS
5133 {
5134 .name = "soft_limit_in_bytes",
5135 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
5136 .write_string = mem_cgroup_write,
af36f906 5137 .read = mem_cgroup_read,
296c81d8 5138 },
8cdea7c0
BS
5139 {
5140 .name = "failcnt",
8c7c6e34 5141 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
29f2a4da 5142 .trigger = mem_cgroup_reset,
af36f906 5143 .read = mem_cgroup_read,
8cdea7c0 5144 },
d2ceb9b7
KH
5145 {
5146 .name = "stat",
ab215884 5147 .read_seq_string = memcg_stat_show,
d2ceb9b7 5148 },
c1e862c1
KH
5149 {
5150 .name = "force_empty",
5151 .trigger = mem_cgroup_force_empty_write,
5152 },
18f59ea7
BS
5153 {
5154 .name = "use_hierarchy",
5155 .write_u64 = mem_cgroup_hierarchy_write,
5156 .read_u64 = mem_cgroup_hierarchy_read,
5157 },
a7885eb8
KM
5158 {
5159 .name = "swappiness",
5160 .read_u64 = mem_cgroup_swappiness_read,
5161 .write_u64 = mem_cgroup_swappiness_write,
5162 },
7dc74be0
DN
5163 {
5164 .name = "move_charge_at_immigrate",
5165 .read_u64 = mem_cgroup_move_charge_read,
5166 .write_u64 = mem_cgroup_move_charge_write,
5167 },
9490ff27
KH
5168 {
5169 .name = "oom_control",
3c11ecf4
KH
5170 .read_map = mem_cgroup_oom_control_read,
5171 .write_u64 = mem_cgroup_oom_control_write,
9490ff27
KH
5172 .register_event = mem_cgroup_oom_register_event,
5173 .unregister_event = mem_cgroup_oom_unregister_event,
5174 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
5175 },
406eb0c9
YH
5176#ifdef CONFIG_NUMA
5177 {
5178 .name = "numa_stat",
ab215884 5179 .read_seq_string = memcg_numa_stat_show,
406eb0c9
YH
5180 },
5181#endif
c255a458 5182#ifdef CONFIG_MEMCG_SWAP
8c7c6e34
KH
5183 {
5184 .name = "memsw.usage_in_bytes",
5185 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
af36f906 5186 .read = mem_cgroup_read,
9490ff27
KH
5187 .register_event = mem_cgroup_usage_register_event,
5188 .unregister_event = mem_cgroup_usage_unregister_event,
8c7c6e34
KH
5189 },
5190 {
5191 .name = "memsw.max_usage_in_bytes",
5192 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
5193 .trigger = mem_cgroup_reset,
af36f906 5194 .read = mem_cgroup_read,
8c7c6e34
KH
5195 },
5196 {
5197 .name = "memsw.limit_in_bytes",
5198 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
5199 .write_string = mem_cgroup_write,
af36f906 5200 .read = mem_cgroup_read,
8c7c6e34
KH
5201 },
5202 {
5203 .name = "memsw.failcnt",
5204 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
5205 .trigger = mem_cgroup_reset,
af36f906 5206 .read = mem_cgroup_read,
8c7c6e34 5207 },
510fc4e1
GC
5208#endif
5209#ifdef CONFIG_MEMCG_KMEM
5210 {
5211 .name = "kmem.limit_in_bytes",
5212 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
5213 .write_string = mem_cgroup_write,
5214 .read = mem_cgroup_read,
5215 },
5216 {
5217 .name = "kmem.usage_in_bytes",
5218 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
5219 .read = mem_cgroup_read,
5220 },
5221 {
5222 .name = "kmem.failcnt",
5223 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
5224 .trigger = mem_cgroup_reset,
5225 .read = mem_cgroup_read,
5226 },
5227 {
5228 .name = "kmem.max_usage_in_bytes",
5229 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
5230 .trigger = mem_cgroup_reset,
5231 .read = mem_cgroup_read,
5232 },
8c7c6e34 5233#endif
6bc10349 5234 { }, /* terminate */
af36f906 5235};
8c7c6e34 5236
c0ff4b85 5237static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
6d12e2d8
KH
5238{
5239 struct mem_cgroup_per_node *pn;
1ecaab2b 5240 struct mem_cgroup_per_zone *mz;
41e3355d 5241 int zone, tmp = node;
1ecaab2b
KH
5242 /*
5243 * This routine is called against possible nodes.
5244 * But it's BUG to call kmalloc() against offline node.
5245 *
5246 * TODO: this routine can waste much memory for nodes which will
5247 * never be onlined. It's better to use memory hotplug callback
5248 * function.
5249 */
41e3355d
KH
5250 if (!node_state(node, N_NORMAL_MEMORY))
5251 tmp = -1;
17295c88 5252 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
6d12e2d8
KH
5253 if (!pn)
5254 return 1;
1ecaab2b 5255
1ecaab2b
KH
5256 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
5257 mz = &pn->zoneinfo[zone];
bea8c150 5258 lruvec_init(&mz->lruvec);
f64c3f54 5259 mz->usage_in_excess = 0;
4e416953 5260 mz->on_tree = false;
d79154bb 5261 mz->memcg = memcg;
1ecaab2b 5262 }
0a619e58 5263 memcg->info.nodeinfo[node] = pn;
6d12e2d8
KH
5264 return 0;
5265}
5266
c0ff4b85 5267static void free_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
1ecaab2b 5268{
c0ff4b85 5269 kfree(memcg->info.nodeinfo[node]);
1ecaab2b
KH
5270}
5271
33327948
KH
5272static struct mem_cgroup *mem_cgroup_alloc(void)
5273{
d79154bb 5274 struct mem_cgroup *memcg;
c62b1a3b 5275 int size = sizeof(struct mem_cgroup);
33327948 5276
c62b1a3b 5277 /* Can be very big if MAX_NUMNODES is very big */
c8dad2bb 5278 if (size < PAGE_SIZE)
d79154bb 5279 memcg = kzalloc(size, GFP_KERNEL);
33327948 5280 else
d79154bb 5281 memcg = vzalloc(size);
33327948 5282
d79154bb 5283 if (!memcg)
e7bbcdf3
DC
5284 return NULL;
5285
d79154bb
HD
5286 memcg->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
5287 if (!memcg->stat)
d2e61b8d 5288 goto out_free;
d79154bb
HD
5289 spin_lock_init(&memcg->pcp_counter_lock);
5290 return memcg;
d2e61b8d
DC
5291
5292out_free:
5293 if (size < PAGE_SIZE)
d79154bb 5294 kfree(memcg);
d2e61b8d 5295 else
d79154bb 5296 vfree(memcg);
d2e61b8d 5297 return NULL;
33327948
KH
5298}
5299
59927fb9 5300/*
c8b2a36f
GC
5301 * At destroying mem_cgroup, references from swap_cgroup can remain.
5302 * (scanning all at force_empty is too costly...)
5303 *
5304 * Instead of clearing all references at force_empty, we remember
5305 * the number of reference from swap_cgroup and free mem_cgroup when
5306 * it goes down to 0.
5307 *
5308 * Removal of cgroup itself succeeds regardless of refs from swap.
59927fb9 5309 */
c8b2a36f
GC
5310
5311static void __mem_cgroup_free(struct mem_cgroup *memcg)
59927fb9 5312{
c8b2a36f 5313 int node;
3afe36b1 5314 int size = sizeof(struct mem_cgroup);
59927fb9 5315
c8b2a36f
GC
5316 mem_cgroup_remove_from_trees(memcg);
5317 free_css_id(&mem_cgroup_subsys, &memcg->css);
5318
5319 for_each_node(node)
5320 free_mem_cgroup_per_zone_info(memcg, node);
5321
5322 free_percpu(memcg->stat);
5323
3f134619
GC
5324 /*
5325 * We need to make sure that (at least for now), the jump label
5326 * destruction code runs outside of the cgroup lock. This is because
5327 * get_online_cpus(), which is called from the static_branch update,
5328 * can't be called inside the cgroup_lock. cpusets are the ones
5329 * enforcing this dependency, so if they ever change, we might as well.
5330 *
5331 * schedule_work() will guarantee this happens. Be careful if you need
5332 * to move this code around, and make sure it is outside
5333 * the cgroup_lock.
5334 */
a8964b9b 5335 disarm_static_keys(memcg);
3afe36b1
GC
5336 if (size < PAGE_SIZE)
5337 kfree(memcg);
5338 else
5339 vfree(memcg);
59927fb9 5340}
3afe36b1 5341
59927fb9 5342
8c7c6e34 5343/*
c8b2a36f
GC
5344 * Helpers for freeing a kmalloc()ed/vzalloc()ed mem_cgroup by RCU,
5345 * but in process context. The work_freeing structure is overlaid
5346 * on the rcu_freeing structure, which itself is overlaid on memsw.
8c7c6e34 5347 */
c8b2a36f 5348static void free_work(struct work_struct *work)
33327948 5349{
c8b2a36f 5350 struct mem_cgroup *memcg;
08e552c6 5351
c8b2a36f
GC
5352 memcg = container_of(work, struct mem_cgroup, work_freeing);
5353 __mem_cgroup_free(memcg);
5354}
04046e1a 5355
c8b2a36f
GC
5356static void free_rcu(struct rcu_head *rcu_head)
5357{
5358 struct mem_cgroup *memcg;
08e552c6 5359
c8b2a36f
GC
5360 memcg = container_of(rcu_head, struct mem_cgroup, rcu_freeing);
5361 INIT_WORK(&memcg->work_freeing, free_work);
5362 schedule_work(&memcg->work_freeing);
33327948
KH
5363}
5364
c0ff4b85 5365static void mem_cgroup_get(struct mem_cgroup *memcg)
8c7c6e34 5366{
c0ff4b85 5367 atomic_inc(&memcg->refcnt);
8c7c6e34
KH
5368}
5369
c0ff4b85 5370static void __mem_cgroup_put(struct mem_cgroup *memcg, int count)
8c7c6e34 5371{
c0ff4b85
R
5372 if (atomic_sub_and_test(count, &memcg->refcnt)) {
5373 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
c8b2a36f 5374 call_rcu(&memcg->rcu_freeing, free_rcu);
7bcc1bb1
DN
5375 if (parent)
5376 mem_cgroup_put(parent);
5377 }
8c7c6e34
KH
5378}
5379
c0ff4b85 5380static void mem_cgroup_put(struct mem_cgroup *memcg)
483c30b5 5381{
c0ff4b85 5382 __mem_cgroup_put(memcg, 1);
483c30b5
DN
5383}
5384
7bcc1bb1
DN
5385/*
5386 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
5387 */
e1aab161 5388struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg)
7bcc1bb1 5389{
c0ff4b85 5390 if (!memcg->res.parent)
7bcc1bb1 5391 return NULL;
c0ff4b85 5392 return mem_cgroup_from_res_counter(memcg->res.parent, res);
7bcc1bb1 5393}
e1aab161 5394EXPORT_SYMBOL(parent_mem_cgroup);
33327948 5395
c255a458 5396#ifdef CONFIG_MEMCG_SWAP
c077719b
KH
5397static void __init enable_swap_cgroup(void)
5398{
f8d66542 5399 if (!mem_cgroup_disabled() && really_do_swap_account)
c077719b
KH
5400 do_swap_account = 1;
5401}
5402#else
5403static void __init enable_swap_cgroup(void)
5404{
5405}
5406#endif
5407
f64c3f54
BS
5408static int mem_cgroup_soft_limit_tree_init(void)
5409{
5410 struct mem_cgroup_tree_per_node *rtpn;
5411 struct mem_cgroup_tree_per_zone *rtpz;
5412 int tmp, node, zone;
5413
3ed28fa1 5414 for_each_node(node) {
f64c3f54
BS
5415 tmp = node;
5416 if (!node_state(node, N_NORMAL_MEMORY))
5417 tmp = -1;
5418 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
5419 if (!rtpn)
c3cecc68 5420 goto err_cleanup;
f64c3f54
BS
5421
5422 soft_limit_tree.rb_tree_per_node[node] = rtpn;
5423
5424 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
5425 rtpz = &rtpn->rb_tree_per_zone[zone];
5426 rtpz->rb_root = RB_ROOT;
5427 spin_lock_init(&rtpz->lock);
5428 }
5429 }
5430 return 0;
c3cecc68
MH
5431
5432err_cleanup:
3ed28fa1 5433 for_each_node(node) {
c3cecc68
MH
5434 if (!soft_limit_tree.rb_tree_per_node[node])
5435 break;
5436 kfree(soft_limit_tree.rb_tree_per_node[node]);
5437 soft_limit_tree.rb_tree_per_node[node] = NULL;
5438 }
5439 return 1;
5440
f64c3f54
BS
5441}
5442
0eb253e2 5443static struct cgroup_subsys_state * __ref
92fb9748 5444mem_cgroup_css_alloc(struct cgroup *cont)
8cdea7c0 5445{
c0ff4b85 5446 struct mem_cgroup *memcg, *parent;
04046e1a 5447 long error = -ENOMEM;
6d12e2d8 5448 int node;
8cdea7c0 5449
c0ff4b85
R
5450 memcg = mem_cgroup_alloc();
5451 if (!memcg)
04046e1a 5452 return ERR_PTR(error);
78fb7466 5453
3ed28fa1 5454 for_each_node(node)
c0ff4b85 5455 if (alloc_mem_cgroup_per_zone_info(memcg, node))
6d12e2d8 5456 goto free_out;
f64c3f54 5457
c077719b 5458 /* root ? */
28dbc4b6 5459 if (cont->parent == NULL) {
cdec2e42 5460 int cpu;
c077719b 5461 enable_swap_cgroup();
28dbc4b6 5462 parent = NULL;
f64c3f54
BS
5463 if (mem_cgroup_soft_limit_tree_init())
5464 goto free_out;
a41c58a6 5465 root_mem_cgroup = memcg;
cdec2e42
KH
5466 for_each_possible_cpu(cpu) {
5467 struct memcg_stock_pcp *stock =
5468 &per_cpu(memcg_stock, cpu);
5469 INIT_WORK(&stock->work, drain_local_stock);
5470 }
711d3d2c 5471 hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
18f59ea7 5472 } else {
28dbc4b6 5473 parent = mem_cgroup_from_cont(cont->parent);
c0ff4b85
R
5474 memcg->use_hierarchy = parent->use_hierarchy;
5475 memcg->oom_kill_disable = parent->oom_kill_disable;
18f59ea7 5476 }
28dbc4b6 5477
18f59ea7 5478 if (parent && parent->use_hierarchy) {
c0ff4b85
R
5479 res_counter_init(&memcg->res, &parent->res);
5480 res_counter_init(&memcg->memsw, &parent->memsw);
510fc4e1 5481 res_counter_init(&memcg->kmem, &parent->kmem);
7bcc1bb1
DN
5482 /*
5483 * We increment refcnt of the parent to ensure that we can
5484 * safely access it on res_counter_charge/uncharge.
5485 * This refcnt will be decremented when freeing this
5486 * mem_cgroup(see mem_cgroup_put).
5487 */
5488 mem_cgroup_get(parent);
18f59ea7 5489 } else {
c0ff4b85
R
5490 res_counter_init(&memcg->res, NULL);
5491 res_counter_init(&memcg->memsw, NULL);
510fc4e1 5492 res_counter_init(&memcg->kmem, NULL);
8c7f6edb
TH
5493 /*
5494 * Deeper hierachy with use_hierarchy == false doesn't make
5495 * much sense so let cgroup subsystem know about this
5496 * unfortunate state in our controller.
5497 */
5498 if (parent && parent != root_mem_cgroup)
5499 mem_cgroup_subsys.broken_hierarchy = true;
18f59ea7 5500 }
c0ff4b85
R
5501 memcg->last_scanned_node = MAX_NUMNODES;
5502 INIT_LIST_HEAD(&memcg->oom_notify);
6d61ef40 5503
a7885eb8 5504 if (parent)
c0ff4b85
R
5505 memcg->swappiness = mem_cgroup_swappiness(parent);
5506 atomic_set(&memcg->refcnt, 1);
5507 memcg->move_charge_at_immigrate = 0;
5508 mutex_init(&memcg->thresholds_lock);
312734c0 5509 spin_lock_init(&memcg->move_lock);
cbe128e3
GC
5510
5511 error = memcg_init_kmem(memcg, &mem_cgroup_subsys);
5512 if (error) {
5513 /*
5514 * We call put now because our (and parent's) refcnts
5515 * are already in place. mem_cgroup_put() will internally
5516 * call __mem_cgroup_free, so return directly
5517 */
5518 mem_cgroup_put(memcg);
5519 return ERR_PTR(error);
5520 }
c0ff4b85 5521 return &memcg->css;
6d12e2d8 5522free_out:
c0ff4b85 5523 __mem_cgroup_free(memcg);
04046e1a 5524 return ERR_PTR(error);
8cdea7c0
BS
5525}
5526
92fb9748 5527static void mem_cgroup_css_offline(struct cgroup *cont)
df878fb0 5528{
c0ff4b85 5529 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
ec64f515 5530
ab5196c2 5531 mem_cgroup_reparent_charges(memcg);
df878fb0
KH
5532}
5533
92fb9748 5534static void mem_cgroup_css_free(struct cgroup *cont)
8cdea7c0 5535{
c0ff4b85 5536 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
c268e994 5537
1d62e436 5538 kmem_cgroup_destroy(memcg);
d1a4c0b3 5539
c0ff4b85 5540 mem_cgroup_put(memcg);
8cdea7c0
BS
5541}
5542
02491447 5543#ifdef CONFIG_MMU
7dc74be0 5544/* Handlers for move charge at task migration. */
854ffa8d
DN
5545#define PRECHARGE_COUNT_AT_ONCE 256
5546static int mem_cgroup_do_precharge(unsigned long count)
7dc74be0 5547{
854ffa8d
DN
5548 int ret = 0;
5549 int batch_count = PRECHARGE_COUNT_AT_ONCE;
c0ff4b85 5550 struct mem_cgroup *memcg = mc.to;
4ffef5fe 5551
c0ff4b85 5552 if (mem_cgroup_is_root(memcg)) {
854ffa8d
DN
5553 mc.precharge += count;
5554 /* we don't need css_get for root */
5555 return ret;
5556 }
5557 /* try to charge at once */
5558 if (count > 1) {
5559 struct res_counter *dummy;
5560 /*
c0ff4b85 5561 * "memcg" cannot be under rmdir() because we've already checked
854ffa8d
DN
5562 * by cgroup_lock_live_cgroup() that it is not removed and we
5563 * are still under the same cgroup_mutex. So we can postpone
5564 * css_get().
5565 */
c0ff4b85 5566 if (res_counter_charge(&memcg->res, PAGE_SIZE * count, &dummy))
854ffa8d 5567 goto one_by_one;
c0ff4b85 5568 if (do_swap_account && res_counter_charge(&memcg->memsw,
854ffa8d 5569 PAGE_SIZE * count, &dummy)) {
c0ff4b85 5570 res_counter_uncharge(&memcg->res, PAGE_SIZE * count);
854ffa8d
DN
5571 goto one_by_one;
5572 }
5573 mc.precharge += count;
854ffa8d
DN
5574 return ret;
5575 }
5576one_by_one:
5577 /* fall back to one by one charge */
5578 while (count--) {
5579 if (signal_pending(current)) {
5580 ret = -EINTR;
5581 break;
5582 }
5583 if (!batch_count--) {
5584 batch_count = PRECHARGE_COUNT_AT_ONCE;
5585 cond_resched();
5586 }
c0ff4b85
R
5587 ret = __mem_cgroup_try_charge(NULL,
5588 GFP_KERNEL, 1, &memcg, false);
38c5d72f 5589 if (ret)
854ffa8d 5590 /* mem_cgroup_clear_mc() will do uncharge later */
38c5d72f 5591 return ret;
854ffa8d
DN
5592 mc.precharge++;
5593 }
4ffef5fe
DN
5594 return ret;
5595}
5596
5597/**
8d32ff84 5598 * get_mctgt_type - get target type of moving charge
4ffef5fe
DN
5599 * @vma: the vma the pte to be checked belongs
5600 * @addr: the address corresponding to the pte to be checked
5601 * @ptent: the pte to be checked
02491447 5602 * @target: the pointer the target page or swap ent will be stored(can be NULL)
4ffef5fe
DN
5603 *
5604 * Returns
5605 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
5606 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5607 * move charge. if @target is not NULL, the page is stored in target->page
5608 * with extra refcnt got(Callers should handle it).
02491447
DN
5609 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5610 * target for charge migration. if @target is not NULL, the entry is stored
5611 * in target->ent.
4ffef5fe
DN
5612 *
5613 * Called with pte lock held.
5614 */
4ffef5fe
DN
5615union mc_target {
5616 struct page *page;
02491447 5617 swp_entry_t ent;
4ffef5fe
DN
5618};
5619
4ffef5fe 5620enum mc_target_type {
8d32ff84 5621 MC_TARGET_NONE = 0,
4ffef5fe 5622 MC_TARGET_PAGE,
02491447 5623 MC_TARGET_SWAP,
4ffef5fe
DN
5624};
5625
90254a65
DN
5626static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5627 unsigned long addr, pte_t ptent)
4ffef5fe 5628{
90254a65 5629 struct page *page = vm_normal_page(vma, addr, ptent);
4ffef5fe 5630
90254a65
DN
5631 if (!page || !page_mapped(page))
5632 return NULL;
5633 if (PageAnon(page)) {
5634 /* we don't move shared anon */
4b91355e 5635 if (!move_anon())
90254a65 5636 return NULL;
87946a72
DN
5637 } else if (!move_file())
5638 /* we ignore mapcount for file pages */
90254a65
DN
5639 return NULL;
5640 if (!get_page_unless_zero(page))
5641 return NULL;
5642
5643 return page;
5644}
5645
4b91355e 5646#ifdef CONFIG_SWAP
90254a65
DN
5647static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5648 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5649{
90254a65
DN
5650 struct page *page = NULL;
5651 swp_entry_t ent = pte_to_swp_entry(ptent);
5652
5653 if (!move_anon() || non_swap_entry(ent))
5654 return NULL;
4b91355e
KH
5655 /*
5656 * Because lookup_swap_cache() updates some statistics counter,
5657 * we call find_get_page() with swapper_space directly.
5658 */
5659 page = find_get_page(&swapper_space, ent.val);
90254a65
DN
5660 if (do_swap_account)
5661 entry->val = ent.val;
5662
5663 return page;
5664}
4b91355e
KH
5665#else
5666static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5667 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5668{
5669 return NULL;
5670}
5671#endif
90254a65 5672
87946a72
DN
5673static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5674 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5675{
5676 struct page *page = NULL;
87946a72
DN
5677 struct address_space *mapping;
5678 pgoff_t pgoff;
5679
5680 if (!vma->vm_file) /* anonymous vma */
5681 return NULL;
5682 if (!move_file())
5683 return NULL;
5684
87946a72
DN
5685 mapping = vma->vm_file->f_mapping;
5686 if (pte_none(ptent))
5687 pgoff = linear_page_index(vma, addr);
5688 else /* pte_file(ptent) is true */
5689 pgoff = pte_to_pgoff(ptent);
5690
5691 /* page is moved even if it's not RSS of this task(page-faulted). */
aa3b1895
HD
5692 page = find_get_page(mapping, pgoff);
5693
5694#ifdef CONFIG_SWAP
5695 /* shmem/tmpfs may report page out on swap: account for that too. */
5696 if (radix_tree_exceptional_entry(page)) {
5697 swp_entry_t swap = radix_to_swp_entry(page);
87946a72 5698 if (do_swap_account)
aa3b1895
HD
5699 *entry = swap;
5700 page = find_get_page(&swapper_space, swap.val);
87946a72 5701 }
aa3b1895 5702#endif
87946a72
DN
5703 return page;
5704}
5705
8d32ff84 5706static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
90254a65
DN
5707 unsigned long addr, pte_t ptent, union mc_target *target)
5708{
5709 struct page *page = NULL;
5710 struct page_cgroup *pc;
8d32ff84 5711 enum mc_target_type ret = MC_TARGET_NONE;
90254a65
DN
5712 swp_entry_t ent = { .val = 0 };
5713
5714 if (pte_present(ptent))
5715 page = mc_handle_present_pte(vma, addr, ptent);
5716 else if (is_swap_pte(ptent))
5717 page = mc_handle_swap_pte(vma, addr, ptent, &ent);
87946a72
DN
5718 else if (pte_none(ptent) || pte_file(ptent))
5719 page = mc_handle_file_pte(vma, addr, ptent, &ent);
90254a65
DN
5720
5721 if (!page && !ent.val)
8d32ff84 5722 return ret;
02491447
DN
5723 if (page) {
5724 pc = lookup_page_cgroup(page);
5725 /*
5726 * Do only loose check w/o page_cgroup lock.
5727 * mem_cgroup_move_account() checks the pc is valid or not under
5728 * the lock.
5729 */
5730 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
5731 ret = MC_TARGET_PAGE;
5732 if (target)
5733 target->page = page;
5734 }
5735 if (!ret || !target)
5736 put_page(page);
5737 }
90254a65
DN
5738 /* There is a swap entry and a page doesn't exist or isn't charged */
5739 if (ent.val && !ret &&
9fb4b7cc 5740 css_id(&mc.from->css) == lookup_swap_cgroup_id(ent)) {
7f0f1546
KH
5741 ret = MC_TARGET_SWAP;
5742 if (target)
5743 target->ent = ent;
4ffef5fe 5744 }
4ffef5fe
DN
5745 return ret;
5746}
5747
12724850
NH
5748#ifdef CONFIG_TRANSPARENT_HUGEPAGE
5749/*
5750 * We don't consider swapping or file mapped pages because THP does not
5751 * support them for now.
5752 * Caller should make sure that pmd_trans_huge(pmd) is true.
5753 */
5754static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5755 unsigned long addr, pmd_t pmd, union mc_target *target)
5756{
5757 struct page *page = NULL;
5758 struct page_cgroup *pc;
5759 enum mc_target_type ret = MC_TARGET_NONE;
5760
5761 page = pmd_page(pmd);
5762 VM_BUG_ON(!page || !PageHead(page));
5763 if (!move_anon())
5764 return ret;
5765 pc = lookup_page_cgroup(page);
5766 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
5767 ret = MC_TARGET_PAGE;
5768 if (target) {
5769 get_page(page);
5770 target->page = page;
5771 }
5772 }
5773 return ret;
5774}
5775#else
5776static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5777 unsigned long addr, pmd_t pmd, union mc_target *target)
5778{
5779 return MC_TARGET_NONE;
5780}
5781#endif
5782
4ffef5fe
DN
5783static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
5784 unsigned long addr, unsigned long end,
5785 struct mm_walk *walk)
5786{
5787 struct vm_area_struct *vma = walk->private;
5788 pte_t *pte;
5789 spinlock_t *ptl;
5790
12724850
NH
5791 if (pmd_trans_huge_lock(pmd, vma) == 1) {
5792 if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
5793 mc.precharge += HPAGE_PMD_NR;
5794 spin_unlock(&vma->vm_mm->page_table_lock);
1a5a9906 5795 return 0;
12724850 5796 }
03319327 5797
45f83cef
AA
5798 if (pmd_trans_unstable(pmd))
5799 return 0;
4ffef5fe
DN
5800 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5801 for (; addr != end; pte++, addr += PAGE_SIZE)
8d32ff84 5802 if (get_mctgt_type(vma, addr, *pte, NULL))
4ffef5fe
DN
5803 mc.precharge++; /* increment precharge temporarily */
5804 pte_unmap_unlock(pte - 1, ptl);
5805 cond_resched();
5806
7dc74be0
DN
5807 return 0;
5808}
5809
4ffef5fe
DN
5810static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
5811{
5812 unsigned long precharge;
5813 struct vm_area_struct *vma;
5814
dfe076b0 5815 down_read(&mm->mmap_sem);
4ffef5fe
DN
5816 for (vma = mm->mmap; vma; vma = vma->vm_next) {
5817 struct mm_walk mem_cgroup_count_precharge_walk = {
5818 .pmd_entry = mem_cgroup_count_precharge_pte_range,
5819 .mm = mm,
5820 .private = vma,
5821 };
5822 if (is_vm_hugetlb_page(vma))
5823 continue;
4ffef5fe
DN
5824 walk_page_range(vma->vm_start, vma->vm_end,
5825 &mem_cgroup_count_precharge_walk);
5826 }
dfe076b0 5827 up_read(&mm->mmap_sem);
4ffef5fe
DN
5828
5829 precharge = mc.precharge;
5830 mc.precharge = 0;
5831
5832 return precharge;
5833}
5834
4ffef5fe
DN
5835static int mem_cgroup_precharge_mc(struct mm_struct *mm)
5836{
dfe076b0
DN
5837 unsigned long precharge = mem_cgroup_count_precharge(mm);
5838
5839 VM_BUG_ON(mc.moving_task);
5840 mc.moving_task = current;
5841 return mem_cgroup_do_precharge(precharge);
4ffef5fe
DN
5842}
5843
dfe076b0
DN
5844/* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5845static void __mem_cgroup_clear_mc(void)
4ffef5fe 5846{
2bd9bb20
KH
5847 struct mem_cgroup *from = mc.from;
5848 struct mem_cgroup *to = mc.to;
5849
4ffef5fe 5850 /* we must uncharge all the leftover precharges from mc.to */
854ffa8d
DN
5851 if (mc.precharge) {
5852 __mem_cgroup_cancel_charge(mc.to, mc.precharge);
5853 mc.precharge = 0;
5854 }
5855 /*
5856 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5857 * we must uncharge here.
5858 */
5859 if (mc.moved_charge) {
5860 __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
5861 mc.moved_charge = 0;
4ffef5fe 5862 }
483c30b5
DN
5863 /* we must fixup refcnts and charges */
5864 if (mc.moved_swap) {
483c30b5
DN
5865 /* uncharge swap account from the old cgroup */
5866 if (!mem_cgroup_is_root(mc.from))
5867 res_counter_uncharge(&mc.from->memsw,
5868 PAGE_SIZE * mc.moved_swap);
5869 __mem_cgroup_put(mc.from, mc.moved_swap);
5870
5871 if (!mem_cgroup_is_root(mc.to)) {
5872 /*
5873 * we charged both to->res and to->memsw, so we should
5874 * uncharge to->res.
5875 */
5876 res_counter_uncharge(&mc.to->res,
5877 PAGE_SIZE * mc.moved_swap);
483c30b5
DN
5878 }
5879 /* we've already done mem_cgroup_get(mc.to) */
483c30b5
DN
5880 mc.moved_swap = 0;
5881 }
dfe076b0
DN
5882 memcg_oom_recover(from);
5883 memcg_oom_recover(to);
5884 wake_up_all(&mc.waitq);
5885}
5886
5887static void mem_cgroup_clear_mc(void)
5888{
5889 struct mem_cgroup *from = mc.from;
5890
5891 /*
5892 * we must clear moving_task before waking up waiters at the end of
5893 * task migration.
5894 */
5895 mc.moving_task = NULL;
5896 __mem_cgroup_clear_mc();
2bd9bb20 5897 spin_lock(&mc.lock);
4ffef5fe
DN
5898 mc.from = NULL;
5899 mc.to = NULL;
2bd9bb20 5900 spin_unlock(&mc.lock);
32047e2a 5901 mem_cgroup_end_move(from);
4ffef5fe
DN
5902}
5903
761b3ef5
LZ
5904static int mem_cgroup_can_attach(struct cgroup *cgroup,
5905 struct cgroup_taskset *tset)
7dc74be0 5906{
2f7ee569 5907 struct task_struct *p = cgroup_taskset_first(tset);
7dc74be0 5908 int ret = 0;
c0ff4b85 5909 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgroup);
7dc74be0 5910
c0ff4b85 5911 if (memcg->move_charge_at_immigrate) {
7dc74be0
DN
5912 struct mm_struct *mm;
5913 struct mem_cgroup *from = mem_cgroup_from_task(p);
5914
c0ff4b85 5915 VM_BUG_ON(from == memcg);
7dc74be0
DN
5916
5917 mm = get_task_mm(p);
5918 if (!mm)
5919 return 0;
7dc74be0 5920 /* We move charges only when we move a owner of the mm */
4ffef5fe
DN
5921 if (mm->owner == p) {
5922 VM_BUG_ON(mc.from);
5923 VM_BUG_ON(mc.to);
5924 VM_BUG_ON(mc.precharge);
854ffa8d 5925 VM_BUG_ON(mc.moved_charge);
483c30b5 5926 VM_BUG_ON(mc.moved_swap);
32047e2a 5927 mem_cgroup_start_move(from);
2bd9bb20 5928 spin_lock(&mc.lock);
4ffef5fe 5929 mc.from = from;
c0ff4b85 5930 mc.to = memcg;
2bd9bb20 5931 spin_unlock(&mc.lock);
dfe076b0 5932 /* We set mc.moving_task later */
4ffef5fe
DN
5933
5934 ret = mem_cgroup_precharge_mc(mm);
5935 if (ret)
5936 mem_cgroup_clear_mc();
dfe076b0
DN
5937 }
5938 mmput(mm);
7dc74be0
DN
5939 }
5940 return ret;
5941}
5942
761b3ef5
LZ
5943static void mem_cgroup_cancel_attach(struct cgroup *cgroup,
5944 struct cgroup_taskset *tset)
7dc74be0 5945{
4ffef5fe 5946 mem_cgroup_clear_mc();
7dc74be0
DN
5947}
5948
4ffef5fe
DN
5949static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
5950 unsigned long addr, unsigned long end,
5951 struct mm_walk *walk)
7dc74be0 5952{
4ffef5fe
DN
5953 int ret = 0;
5954 struct vm_area_struct *vma = walk->private;
5955 pte_t *pte;
5956 spinlock_t *ptl;
12724850
NH
5957 enum mc_target_type target_type;
5958 union mc_target target;
5959 struct page *page;
5960 struct page_cgroup *pc;
4ffef5fe 5961
12724850
NH
5962 /*
5963 * We don't take compound_lock() here but no race with splitting thp
5964 * happens because:
5965 * - if pmd_trans_huge_lock() returns 1, the relevant thp is not
5966 * under splitting, which means there's no concurrent thp split,
5967 * - if another thread runs into split_huge_page() just after we
5968 * entered this if-block, the thread must wait for page table lock
5969 * to be unlocked in __split_huge_page_splitting(), where the main
5970 * part of thp split is not executed yet.
5971 */
5972 if (pmd_trans_huge_lock(pmd, vma) == 1) {
62ade86a 5973 if (mc.precharge < HPAGE_PMD_NR) {
12724850
NH
5974 spin_unlock(&vma->vm_mm->page_table_lock);
5975 return 0;
5976 }
5977 target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
5978 if (target_type == MC_TARGET_PAGE) {
5979 page = target.page;
5980 if (!isolate_lru_page(page)) {
5981 pc = lookup_page_cgroup(page);
5982 if (!mem_cgroup_move_account(page, HPAGE_PMD_NR,
2f3479b1 5983 pc, mc.from, mc.to)) {
12724850
NH
5984 mc.precharge -= HPAGE_PMD_NR;
5985 mc.moved_charge += HPAGE_PMD_NR;
5986 }
5987 putback_lru_page(page);
5988 }
5989 put_page(page);
5990 }
5991 spin_unlock(&vma->vm_mm->page_table_lock);
1a5a9906 5992 return 0;
12724850
NH
5993 }
5994
45f83cef
AA
5995 if (pmd_trans_unstable(pmd))
5996 return 0;
4ffef5fe
DN
5997retry:
5998 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5999 for (; addr != end; addr += PAGE_SIZE) {
6000 pte_t ptent = *(pte++);
02491447 6001 swp_entry_t ent;
4ffef5fe
DN
6002
6003 if (!mc.precharge)
6004 break;
6005
8d32ff84 6006 switch (get_mctgt_type(vma, addr, ptent, &target)) {
4ffef5fe
DN
6007 case MC_TARGET_PAGE:
6008 page = target.page;
6009 if (isolate_lru_page(page))
6010 goto put;
6011 pc = lookup_page_cgroup(page);
7ec99d62 6012 if (!mem_cgroup_move_account(page, 1, pc,
2f3479b1 6013 mc.from, mc.to)) {
4ffef5fe 6014 mc.precharge--;
854ffa8d
DN
6015 /* we uncharge from mc.from later. */
6016 mc.moved_charge++;
4ffef5fe
DN
6017 }
6018 putback_lru_page(page);
8d32ff84 6019put: /* get_mctgt_type() gets the page */
4ffef5fe
DN
6020 put_page(page);
6021 break;
02491447
DN
6022 case MC_TARGET_SWAP:
6023 ent = target.ent;
e91cbb42 6024 if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
02491447 6025 mc.precharge--;
483c30b5
DN
6026 /* we fixup refcnts and charges later. */
6027 mc.moved_swap++;
6028 }
02491447 6029 break;
4ffef5fe
DN
6030 default:
6031 break;
6032 }
6033 }
6034 pte_unmap_unlock(pte - 1, ptl);
6035 cond_resched();
6036
6037 if (addr != end) {
6038 /*
6039 * We have consumed all precharges we got in can_attach().
6040 * We try charge one by one, but don't do any additional
6041 * charges to mc.to if we have failed in charge once in attach()
6042 * phase.
6043 */
854ffa8d 6044 ret = mem_cgroup_do_precharge(1);
4ffef5fe
DN
6045 if (!ret)
6046 goto retry;
6047 }
6048
6049 return ret;
6050}
6051
6052static void mem_cgroup_move_charge(struct mm_struct *mm)
6053{
6054 struct vm_area_struct *vma;
6055
6056 lru_add_drain_all();
dfe076b0
DN
6057retry:
6058 if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
6059 /*
6060 * Someone who are holding the mmap_sem might be waiting in
6061 * waitq. So we cancel all extra charges, wake up all waiters,
6062 * and retry. Because we cancel precharges, we might not be able
6063 * to move enough charges, but moving charge is a best-effort
6064 * feature anyway, so it wouldn't be a big problem.
6065 */
6066 __mem_cgroup_clear_mc();
6067 cond_resched();
6068 goto retry;
6069 }
4ffef5fe
DN
6070 for (vma = mm->mmap; vma; vma = vma->vm_next) {
6071 int ret;
6072 struct mm_walk mem_cgroup_move_charge_walk = {
6073 .pmd_entry = mem_cgroup_move_charge_pte_range,
6074 .mm = mm,
6075 .private = vma,
6076 };
6077 if (is_vm_hugetlb_page(vma))
6078 continue;
4ffef5fe
DN
6079 ret = walk_page_range(vma->vm_start, vma->vm_end,
6080 &mem_cgroup_move_charge_walk);
6081 if (ret)
6082 /*
6083 * means we have consumed all precharges and failed in
6084 * doing additional charge. Just abandon here.
6085 */
6086 break;
6087 }
dfe076b0 6088 up_read(&mm->mmap_sem);
7dc74be0
DN
6089}
6090
761b3ef5
LZ
6091static void mem_cgroup_move_task(struct cgroup *cont,
6092 struct cgroup_taskset *tset)
67e465a7 6093{
2f7ee569 6094 struct task_struct *p = cgroup_taskset_first(tset);
a433658c 6095 struct mm_struct *mm = get_task_mm(p);
dfe076b0 6096
dfe076b0 6097 if (mm) {
a433658c
KM
6098 if (mc.to)
6099 mem_cgroup_move_charge(mm);
dfe076b0
DN
6100 mmput(mm);
6101 }
a433658c
KM
6102 if (mc.to)
6103 mem_cgroup_clear_mc();
67e465a7 6104}
5cfb80a7 6105#else /* !CONFIG_MMU */
761b3ef5
LZ
6106static int mem_cgroup_can_attach(struct cgroup *cgroup,
6107 struct cgroup_taskset *tset)
5cfb80a7
DN
6108{
6109 return 0;
6110}
761b3ef5
LZ
6111static void mem_cgroup_cancel_attach(struct cgroup *cgroup,
6112 struct cgroup_taskset *tset)
5cfb80a7
DN
6113{
6114}
761b3ef5
LZ
6115static void mem_cgroup_move_task(struct cgroup *cont,
6116 struct cgroup_taskset *tset)
5cfb80a7
DN
6117{
6118}
6119#endif
67e465a7 6120
8cdea7c0
BS
6121struct cgroup_subsys mem_cgroup_subsys = {
6122 .name = "memory",
6123 .subsys_id = mem_cgroup_subsys_id,
92fb9748
TH
6124 .css_alloc = mem_cgroup_css_alloc,
6125 .css_offline = mem_cgroup_css_offline,
6126 .css_free = mem_cgroup_css_free,
7dc74be0
DN
6127 .can_attach = mem_cgroup_can_attach,
6128 .cancel_attach = mem_cgroup_cancel_attach,
67e465a7 6129 .attach = mem_cgroup_move_task,
6bc10349 6130 .base_cftypes = mem_cgroup_files,
6d12e2d8 6131 .early_init = 0,
04046e1a 6132 .use_id = 1,
8cdea7c0 6133};
c077719b 6134
c255a458 6135#ifdef CONFIG_MEMCG_SWAP
a42c390c
MH
6136static int __init enable_swap_account(char *s)
6137{
6138 /* consider enabled if no parameter or 1 is given */
a2c8990a 6139 if (!strcmp(s, "1"))
a42c390c 6140 really_do_swap_account = 1;
a2c8990a 6141 else if (!strcmp(s, "0"))
a42c390c
MH
6142 really_do_swap_account = 0;
6143 return 1;
6144}
a2c8990a 6145__setup("swapaccount=", enable_swap_account);
c077719b 6146
c077719b 6147#endif