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