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