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