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