]> bbs.cooldavid.org Git - net-next-2.6.git/blame - mm/memcontrol.c
memcg: mem_cgroup_shrink_node_zone() doesn't need sc.nodemask
[net-next-2.6.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>
8c7c6e34 36#include <linux/mutex.h>
f64c3f54 37#include <linux/rbtree.h>
b6ac57d5 38#include <linux/slab.h>
66e1707b 39#include <linux/swap.h>
02491447 40#include <linux/swapops.h>
66e1707b 41#include <linux/spinlock.h>
2e72b634
KS
42#include <linux/eventfd.h>
43#include <linux/sort.h>
66e1707b 44#include <linux/fs.h>
d2ceb9b7 45#include <linux/seq_file.h>
33327948 46#include <linux/vmalloc.h>
b69408e8 47#include <linux/mm_inline.h>
52d4b9ac 48#include <linux/page_cgroup.h>
cdec2e42 49#include <linux/cpu.h>
158e0a2d 50#include <linux/oom.h>
08e552c6 51#include "internal.h"
8cdea7c0 52
8697d331
BS
53#include <asm/uaccess.h>
54
cc8e970c
KM
55#include <trace/events/vmscan.h>
56
a181b0e8 57struct cgroup_subsys mem_cgroup_subsys __read_mostly;
a181b0e8 58#define MEM_CGROUP_RECLAIM_RETRIES 5
4b3bde4c 59struct mem_cgroup *root_mem_cgroup __read_mostly;
8cdea7c0 60
c077719b 61#ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
338c8431 62/* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
c077719b
KH
63int do_swap_account __read_mostly;
64static int really_do_swap_account __initdata = 1; /* for remember boot option*/
65#else
66#define do_swap_account (0)
67#endif
68
d2265e6f
KH
69/*
70 * Per memcg event counter is incremented at every pagein/pageout. This counter
71 * is used for trigger some periodic events. This is straightforward and better
72 * than using jiffies etc. to handle periodic memcg event.
73 *
74 * These values will be used as !((event) & ((1 <<(thresh)) - 1))
75 */
76#define THRESHOLDS_EVENTS_THRESH (7) /* once in 128 */
77#define SOFTLIMIT_EVENTS_THRESH (10) /* once in 1024 */
c077719b 78
d52aa412
KH
79/*
80 * Statistics for memory cgroup.
81 */
82enum mem_cgroup_stat_index {
83 /*
84 * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
85 */
86 MEM_CGROUP_STAT_CACHE, /* # of pages charged as cache */
d69b042f 87 MEM_CGROUP_STAT_RSS, /* # of pages charged as anon rss */
d8046582 88 MEM_CGROUP_STAT_FILE_MAPPED, /* # of pages charged as file rss */
55e462b0
BR
89 MEM_CGROUP_STAT_PGPGIN_COUNT, /* # of pages paged in */
90 MEM_CGROUP_STAT_PGPGOUT_COUNT, /* # of pages paged out */
0c3e73e8 91 MEM_CGROUP_STAT_SWAPOUT, /* # of pages, swapped out */
d2265e6f 92 MEM_CGROUP_EVENTS, /* incremented at every pagein/pageout */
d52aa412
KH
93
94 MEM_CGROUP_STAT_NSTATS,
95};
96
97struct mem_cgroup_stat_cpu {
98 s64 count[MEM_CGROUP_STAT_NSTATS];
d52aa412
KH
99};
100
6d12e2d8
KH
101/*
102 * per-zone information in memory controller.
103 */
6d12e2d8 104struct mem_cgroup_per_zone {
072c56c1
KH
105 /*
106 * spin_lock to protect the per cgroup LRU
107 */
b69408e8
CL
108 struct list_head lists[NR_LRU_LISTS];
109 unsigned long count[NR_LRU_LISTS];
3e2f41f1
KM
110
111 struct zone_reclaim_stat reclaim_stat;
f64c3f54
BS
112 struct rb_node tree_node; /* RB tree node */
113 unsigned long long usage_in_excess;/* Set to the value by which */
114 /* the soft limit is exceeded*/
115 bool on_tree;
4e416953
BS
116 struct mem_cgroup *mem; /* Back pointer, we cannot */
117 /* use container_of */
6d12e2d8
KH
118};
119/* Macro for accessing counter */
120#define MEM_CGROUP_ZSTAT(mz, idx) ((mz)->count[(idx)])
121
122struct mem_cgroup_per_node {
123 struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
124};
125
126struct mem_cgroup_lru_info {
127 struct mem_cgroup_per_node *nodeinfo[MAX_NUMNODES];
128};
129
f64c3f54
BS
130/*
131 * Cgroups above their limits are maintained in a RB-Tree, independent of
132 * their hierarchy representation
133 */
134
135struct mem_cgroup_tree_per_zone {
136 struct rb_root rb_root;
137 spinlock_t lock;
138};
139
140struct mem_cgroup_tree_per_node {
141 struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
142};
143
144struct mem_cgroup_tree {
145 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
146};
147
148static struct mem_cgroup_tree soft_limit_tree __read_mostly;
149
2e72b634
KS
150struct mem_cgroup_threshold {
151 struct eventfd_ctx *eventfd;
152 u64 threshold;
153};
154
9490ff27 155/* For threshold */
2e72b634
KS
156struct mem_cgroup_threshold_ary {
157 /* An array index points to threshold just below usage. */
5407a562 158 int current_threshold;
2e72b634
KS
159 /* Size of entries[] */
160 unsigned int size;
161 /* Array of thresholds */
162 struct mem_cgroup_threshold entries[0];
163};
2c488db2
KS
164
165struct mem_cgroup_thresholds {
166 /* Primary thresholds array */
167 struct mem_cgroup_threshold_ary *primary;
168 /*
169 * Spare threshold array.
170 * This is needed to make mem_cgroup_unregister_event() "never fail".
171 * It must be able to store at least primary->size - 1 entries.
172 */
173 struct mem_cgroup_threshold_ary *spare;
174};
175
9490ff27
KH
176/* for OOM */
177struct mem_cgroup_eventfd_list {
178 struct list_head list;
179 struct eventfd_ctx *eventfd;
180};
2e72b634 181
2e72b634 182static void mem_cgroup_threshold(struct mem_cgroup *mem);
9490ff27 183static void mem_cgroup_oom_notify(struct mem_cgroup *mem);
2e72b634 184
8cdea7c0
BS
185/*
186 * The memory controller data structure. The memory controller controls both
187 * page cache and RSS per cgroup. We would eventually like to provide
188 * statistics based on the statistics developed by Rik Van Riel for clock-pro,
189 * to help the administrator determine what knobs to tune.
190 *
191 * TODO: Add a water mark for the memory controller. Reclaim will begin when
8a9f3ccd
BS
192 * we hit the water mark. May be even add a low water mark, such that
193 * no reclaim occurs from a cgroup at it's low water mark, this is
194 * a feature that will be implemented much later in the future.
8cdea7c0
BS
195 */
196struct mem_cgroup {
197 struct cgroup_subsys_state css;
198 /*
199 * the counter to account for memory usage
200 */
201 struct res_counter res;
8c7c6e34
KH
202 /*
203 * the counter to account for mem+swap usage.
204 */
205 struct res_counter memsw;
78fb7466
PE
206 /*
207 * Per cgroup active and inactive list, similar to the
208 * per zone LRU lists.
78fb7466 209 */
6d12e2d8 210 struct mem_cgroup_lru_info info;
072c56c1 211
2733c06a
KM
212 /*
213 protect against reclaim related member.
214 */
215 spinlock_t reclaim_param_lock;
216
6d61ef40 217 /*
af901ca1 218 * While reclaiming in a hierarchy, we cache the last child we
04046e1a 219 * reclaimed from.
6d61ef40 220 */
04046e1a 221 int last_scanned_child;
18f59ea7
BS
222 /*
223 * Should the accounting and control be hierarchical, per subtree?
224 */
225 bool use_hierarchy;
867578cb 226 atomic_t oom_lock;
8c7c6e34 227 atomic_t refcnt;
14797e23 228
a7885eb8 229 unsigned int swappiness;
3c11ecf4
KH
230 /* OOM-Killer disable */
231 int oom_kill_disable;
a7885eb8 232
22a668d7
KH
233 /* set when res.limit == memsw.limit */
234 bool memsw_is_minimum;
235
2e72b634
KS
236 /* protect arrays of thresholds */
237 struct mutex thresholds_lock;
238
239 /* thresholds for memory usage. RCU-protected */
2c488db2 240 struct mem_cgroup_thresholds thresholds;
907860ed 241
2e72b634 242 /* thresholds for mem+swap usage. RCU-protected */
2c488db2 243 struct mem_cgroup_thresholds memsw_thresholds;
907860ed 244
9490ff27
KH
245 /* For oom notifier event fd */
246 struct list_head oom_notify;
247
7dc74be0
DN
248 /*
249 * Should we move charges of a task when a task is moved into this
250 * mem_cgroup ? And what type of charges should we move ?
251 */
252 unsigned long move_charge_at_immigrate;
d52aa412 253 /*
c62b1a3b 254 * percpu counter.
d52aa412 255 */
c62b1a3b 256 struct mem_cgroup_stat_cpu *stat;
8cdea7c0
BS
257};
258
7dc74be0
DN
259/* Stuffs for move charges at task migration. */
260/*
261 * Types of charges to be moved. "move_charge_at_immitgrate" is treated as a
262 * left-shifted bitmap of these types.
263 */
264enum move_type {
4ffef5fe 265 MOVE_CHARGE_TYPE_ANON, /* private anonymous page and swap of it */
87946a72 266 MOVE_CHARGE_TYPE_FILE, /* file page(including tmpfs) and swap of it */
7dc74be0
DN
267 NR_MOVE_TYPE,
268};
269
4ffef5fe
DN
270/* "mc" and its members are protected by cgroup_mutex */
271static struct move_charge_struct {
2bd9bb20 272 spinlock_t lock; /* for from, to, moving_task */
4ffef5fe
DN
273 struct mem_cgroup *from;
274 struct mem_cgroup *to;
275 unsigned long precharge;
854ffa8d 276 unsigned long moved_charge;
483c30b5 277 unsigned long moved_swap;
8033b97c
DN
278 struct task_struct *moving_task; /* a task moving charges */
279 wait_queue_head_t waitq; /* a waitq for other context */
280} mc = {
2bd9bb20 281 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
8033b97c
DN
282 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
283};
4ffef5fe 284
90254a65
DN
285static bool move_anon(void)
286{
287 return test_bit(MOVE_CHARGE_TYPE_ANON,
288 &mc.to->move_charge_at_immigrate);
289}
290
87946a72
DN
291static bool move_file(void)
292{
293 return test_bit(MOVE_CHARGE_TYPE_FILE,
294 &mc.to->move_charge_at_immigrate);
295}
296
4e416953
BS
297/*
298 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
299 * limit reclaim to prevent infinite loops, if they ever occur.
300 */
301#define MEM_CGROUP_MAX_RECLAIM_LOOPS (100)
302#define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS (2)
303
217bc319
KH
304enum charge_type {
305 MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
306 MEM_CGROUP_CHARGE_TYPE_MAPPED,
4f98a2fe 307 MEM_CGROUP_CHARGE_TYPE_SHMEM, /* used by page migration of shmem */
c05555b5 308 MEM_CGROUP_CHARGE_TYPE_FORCE, /* used by force_empty */
d13d1443 309 MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
8a9478ca 310 MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
c05555b5
KH
311 NR_CHARGE_TYPE,
312};
313
52d4b9ac
KH
314/* only for here (for easy reading.) */
315#define PCGF_CACHE (1UL << PCG_CACHE)
316#define PCGF_USED (1UL << PCG_USED)
52d4b9ac 317#define PCGF_LOCK (1UL << PCG_LOCK)
4b3bde4c
BS
318/* Not used, but added here for completeness */
319#define PCGF_ACCT (1UL << PCG_ACCT)
217bc319 320
8c7c6e34
KH
321/* for encoding cft->private value on file */
322#define _MEM (0)
323#define _MEMSWAP (1)
9490ff27 324#define _OOM_TYPE (2)
8c7c6e34
KH
325#define MEMFILE_PRIVATE(x, val) (((x) << 16) | (val))
326#define MEMFILE_TYPE(val) (((val) >> 16) & 0xffff)
327#define MEMFILE_ATTR(val) ((val) & 0xffff)
9490ff27
KH
328/* Used for OOM nofiier */
329#define OOM_CONTROL (0)
8c7c6e34 330
75822b44
BS
331/*
332 * Reclaim flags for mem_cgroup_hierarchical_reclaim
333 */
334#define MEM_CGROUP_RECLAIM_NOSWAP_BIT 0x0
335#define MEM_CGROUP_RECLAIM_NOSWAP (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
336#define MEM_CGROUP_RECLAIM_SHRINK_BIT 0x1
337#define MEM_CGROUP_RECLAIM_SHRINK (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
4e416953
BS
338#define MEM_CGROUP_RECLAIM_SOFT_BIT 0x2
339#define MEM_CGROUP_RECLAIM_SOFT (1 << MEM_CGROUP_RECLAIM_SOFT_BIT)
75822b44 340
8c7c6e34
KH
341static void mem_cgroup_get(struct mem_cgroup *mem);
342static void mem_cgroup_put(struct mem_cgroup *mem);
7bcc1bb1 343static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem);
cdec2e42 344static void drain_all_stock_async(void);
8c7c6e34 345
f64c3f54
BS
346static struct mem_cgroup_per_zone *
347mem_cgroup_zoneinfo(struct mem_cgroup *mem, int nid, int zid)
348{
349 return &mem->info.nodeinfo[nid]->zoneinfo[zid];
350}
351
d324236b
WF
352struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *mem)
353{
354 return &mem->css;
355}
356
f64c3f54
BS
357static struct mem_cgroup_per_zone *
358page_cgroup_zoneinfo(struct page_cgroup *pc)
359{
360 struct mem_cgroup *mem = pc->mem_cgroup;
361 int nid = page_cgroup_nid(pc);
362 int zid = page_cgroup_zid(pc);
363
364 if (!mem)
365 return NULL;
366
367 return mem_cgroup_zoneinfo(mem, nid, zid);
368}
369
370static struct mem_cgroup_tree_per_zone *
371soft_limit_tree_node_zone(int nid, int zid)
372{
373 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
374}
375
376static struct mem_cgroup_tree_per_zone *
377soft_limit_tree_from_page(struct page *page)
378{
379 int nid = page_to_nid(page);
380 int zid = page_zonenum(page);
381
382 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
383}
384
385static void
4e416953 386__mem_cgroup_insert_exceeded(struct mem_cgroup *mem,
f64c3f54 387 struct mem_cgroup_per_zone *mz,
ef8745c1
KH
388 struct mem_cgroup_tree_per_zone *mctz,
389 unsigned long long new_usage_in_excess)
f64c3f54
BS
390{
391 struct rb_node **p = &mctz->rb_root.rb_node;
392 struct rb_node *parent = NULL;
393 struct mem_cgroup_per_zone *mz_node;
394
395 if (mz->on_tree)
396 return;
397
ef8745c1
KH
398 mz->usage_in_excess = new_usage_in_excess;
399 if (!mz->usage_in_excess)
400 return;
f64c3f54
BS
401 while (*p) {
402 parent = *p;
403 mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
404 tree_node);
405 if (mz->usage_in_excess < mz_node->usage_in_excess)
406 p = &(*p)->rb_left;
407 /*
408 * We can't avoid mem cgroups that are over their soft
409 * limit by the same amount
410 */
411 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
412 p = &(*p)->rb_right;
413 }
414 rb_link_node(&mz->tree_node, parent, p);
415 rb_insert_color(&mz->tree_node, &mctz->rb_root);
416 mz->on_tree = true;
4e416953
BS
417}
418
419static void
420__mem_cgroup_remove_exceeded(struct mem_cgroup *mem,
421 struct mem_cgroup_per_zone *mz,
422 struct mem_cgroup_tree_per_zone *mctz)
423{
424 if (!mz->on_tree)
425 return;
426 rb_erase(&mz->tree_node, &mctz->rb_root);
427 mz->on_tree = false;
428}
429
f64c3f54
BS
430static void
431mem_cgroup_remove_exceeded(struct mem_cgroup *mem,
432 struct mem_cgroup_per_zone *mz,
433 struct mem_cgroup_tree_per_zone *mctz)
434{
435 spin_lock(&mctz->lock);
4e416953 436 __mem_cgroup_remove_exceeded(mem, mz, mctz);
f64c3f54
BS
437 spin_unlock(&mctz->lock);
438}
439
f64c3f54
BS
440
441static void mem_cgroup_update_tree(struct mem_cgroup *mem, struct page *page)
442{
ef8745c1 443 unsigned long long excess;
f64c3f54
BS
444 struct mem_cgroup_per_zone *mz;
445 struct mem_cgroup_tree_per_zone *mctz;
4e649152
KH
446 int nid = page_to_nid(page);
447 int zid = page_zonenum(page);
f64c3f54
BS
448 mctz = soft_limit_tree_from_page(page);
449
450 /*
4e649152
KH
451 * Necessary to update all ancestors when hierarchy is used.
452 * because their event counter is not touched.
f64c3f54 453 */
4e649152
KH
454 for (; mem; mem = parent_mem_cgroup(mem)) {
455 mz = mem_cgroup_zoneinfo(mem, nid, zid);
ef8745c1 456 excess = res_counter_soft_limit_excess(&mem->res);
4e649152
KH
457 /*
458 * We have to update the tree if mz is on RB-tree or
459 * mem is over its softlimit.
460 */
ef8745c1 461 if (excess || mz->on_tree) {
4e649152
KH
462 spin_lock(&mctz->lock);
463 /* if on-tree, remove it */
464 if (mz->on_tree)
465 __mem_cgroup_remove_exceeded(mem, mz, mctz);
466 /*
ef8745c1
KH
467 * Insert again. mz->usage_in_excess will be updated.
468 * If excess is 0, no tree ops.
4e649152 469 */
ef8745c1 470 __mem_cgroup_insert_exceeded(mem, mz, mctz, excess);
4e649152
KH
471 spin_unlock(&mctz->lock);
472 }
f64c3f54
BS
473 }
474}
475
476static void mem_cgroup_remove_from_trees(struct mem_cgroup *mem)
477{
478 int node, zone;
479 struct mem_cgroup_per_zone *mz;
480 struct mem_cgroup_tree_per_zone *mctz;
481
482 for_each_node_state(node, N_POSSIBLE) {
483 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
484 mz = mem_cgroup_zoneinfo(mem, node, zone);
485 mctz = soft_limit_tree_node_zone(node, zone);
486 mem_cgroup_remove_exceeded(mem, mz, mctz);
487 }
488 }
489}
490
4e416953
BS
491static inline unsigned long mem_cgroup_get_excess(struct mem_cgroup *mem)
492{
493 return res_counter_soft_limit_excess(&mem->res) >> PAGE_SHIFT;
494}
495
496static struct mem_cgroup_per_zone *
497__mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
498{
499 struct rb_node *rightmost = NULL;
26251eaf 500 struct mem_cgroup_per_zone *mz;
4e416953
BS
501
502retry:
26251eaf 503 mz = NULL;
4e416953
BS
504 rightmost = rb_last(&mctz->rb_root);
505 if (!rightmost)
506 goto done; /* Nothing to reclaim from */
507
508 mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
509 /*
510 * Remove the node now but someone else can add it back,
511 * we will to add it back at the end of reclaim to its correct
512 * position in the tree.
513 */
514 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
515 if (!res_counter_soft_limit_excess(&mz->mem->res) ||
516 !css_tryget(&mz->mem->css))
517 goto retry;
518done:
519 return mz;
520}
521
522static struct mem_cgroup_per_zone *
523mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
524{
525 struct mem_cgroup_per_zone *mz;
526
527 spin_lock(&mctz->lock);
528 mz = __mem_cgroup_largest_soft_limit_node(mctz);
529 spin_unlock(&mctz->lock);
530 return mz;
531}
532
c62b1a3b
KH
533static s64 mem_cgroup_read_stat(struct mem_cgroup *mem,
534 enum mem_cgroup_stat_index idx)
535{
536 int cpu;
537 s64 val = 0;
538
539 for_each_possible_cpu(cpu)
540 val += per_cpu(mem->stat->count[idx], cpu);
541 return val;
542}
543
544static s64 mem_cgroup_local_usage(struct mem_cgroup *mem)
545{
546 s64 ret;
547
548 ret = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_RSS);
549 ret += mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_CACHE);
550 return ret;
551}
552
0c3e73e8
BS
553static void mem_cgroup_swap_statistics(struct mem_cgroup *mem,
554 bool charge)
555{
556 int val = (charge) ? 1 : -1;
c62b1a3b 557 this_cpu_add(mem->stat->count[MEM_CGROUP_STAT_SWAPOUT], val);
0c3e73e8
BS
558}
559
c05555b5
KH
560static void mem_cgroup_charge_statistics(struct mem_cgroup *mem,
561 struct page_cgroup *pc,
562 bool charge)
d52aa412 563{
0c3e73e8 564 int val = (charge) ? 1 : -1;
d52aa412 565
c62b1a3b
KH
566 preempt_disable();
567
c05555b5 568 if (PageCgroupCache(pc))
c62b1a3b 569 __this_cpu_add(mem->stat->count[MEM_CGROUP_STAT_CACHE], val);
d52aa412 570 else
c62b1a3b 571 __this_cpu_add(mem->stat->count[MEM_CGROUP_STAT_RSS], val);
55e462b0
BR
572
573 if (charge)
c62b1a3b 574 __this_cpu_inc(mem->stat->count[MEM_CGROUP_STAT_PGPGIN_COUNT]);
55e462b0 575 else
c62b1a3b 576 __this_cpu_inc(mem->stat->count[MEM_CGROUP_STAT_PGPGOUT_COUNT]);
d2265e6f 577 __this_cpu_inc(mem->stat->count[MEM_CGROUP_EVENTS]);
2e72b634 578
c62b1a3b 579 preempt_enable();
6d12e2d8
KH
580}
581
14067bb3 582static unsigned long mem_cgroup_get_local_zonestat(struct mem_cgroup *mem,
b69408e8 583 enum lru_list idx)
6d12e2d8
KH
584{
585 int nid, zid;
586 struct mem_cgroup_per_zone *mz;
587 u64 total = 0;
588
589 for_each_online_node(nid)
590 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
591 mz = mem_cgroup_zoneinfo(mem, nid, zid);
592 total += MEM_CGROUP_ZSTAT(mz, idx);
593 }
594 return total;
d52aa412
KH
595}
596
d2265e6f
KH
597static bool __memcg_event_check(struct mem_cgroup *mem, int event_mask_shift)
598{
599 s64 val;
600
601 val = this_cpu_read(mem->stat->count[MEM_CGROUP_EVENTS]);
602
603 return !(val & ((1 << event_mask_shift) - 1));
604}
605
606/*
607 * Check events in order.
608 *
609 */
610static void memcg_check_events(struct mem_cgroup *mem, struct page *page)
611{
612 /* threshold event is triggered in finer grain than soft limit */
613 if (unlikely(__memcg_event_check(mem, THRESHOLDS_EVENTS_THRESH))) {
614 mem_cgroup_threshold(mem);
615 if (unlikely(__memcg_event_check(mem, SOFTLIMIT_EVENTS_THRESH)))
616 mem_cgroup_update_tree(mem, page);
617 }
618}
619
d5b69e38 620static struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
8cdea7c0
BS
621{
622 return container_of(cgroup_subsys_state(cont,
623 mem_cgroup_subsys_id), struct mem_cgroup,
624 css);
625}
626
cf475ad2 627struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
78fb7466 628{
31a78f23
BS
629 /*
630 * mm_update_next_owner() may clear mm->owner to NULL
631 * if it races with swapoff, page migration, etc.
632 * So this can be called with p == NULL.
633 */
634 if (unlikely(!p))
635 return NULL;
636
78fb7466
PE
637 return container_of(task_subsys_state(p, mem_cgroup_subsys_id),
638 struct mem_cgroup, css);
639}
640
54595fe2
KH
641static struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
642{
643 struct mem_cgroup *mem = NULL;
0b7f569e
KH
644
645 if (!mm)
646 return NULL;
54595fe2
KH
647 /*
648 * Because we have no locks, mm->owner's may be being moved to other
649 * cgroup. We use css_tryget() here even if this looks
650 * pessimistic (rather than adding locks here).
651 */
652 rcu_read_lock();
653 do {
654 mem = mem_cgroup_from_task(rcu_dereference(mm->owner));
655 if (unlikely(!mem))
656 break;
657 } while (!css_tryget(&mem->css));
658 rcu_read_unlock();
659 return mem;
660}
661
14067bb3
KH
662/*
663 * Call callback function against all cgroup under hierarchy tree.
664 */
665static int mem_cgroup_walk_tree(struct mem_cgroup *root, void *data,
666 int (*func)(struct mem_cgroup *, void *))
667{
668 int found, ret, nextid;
669 struct cgroup_subsys_state *css;
670 struct mem_cgroup *mem;
671
672 if (!root->use_hierarchy)
673 return (*func)(root, data);
674
675 nextid = 1;
676 do {
677 ret = 0;
678 mem = NULL;
679
680 rcu_read_lock();
681 css = css_get_next(&mem_cgroup_subsys, nextid, &root->css,
682 &found);
683 if (css && css_tryget(css))
684 mem = container_of(css, struct mem_cgroup, css);
685 rcu_read_unlock();
686
687 if (mem) {
688 ret = (*func)(mem, data);
689 css_put(&mem->css);
690 }
691 nextid = found + 1;
692 } while (!ret && css);
693
694 return ret;
695}
696
4b3bde4c
BS
697static inline bool mem_cgroup_is_root(struct mem_cgroup *mem)
698{
699 return (mem == root_mem_cgroup);
700}
701
08e552c6
KH
702/*
703 * Following LRU functions are allowed to be used without PCG_LOCK.
704 * Operations are called by routine of global LRU independently from memcg.
705 * What we have to take care of here is validness of pc->mem_cgroup.
706 *
707 * Changes to pc->mem_cgroup happens when
708 * 1. charge
709 * 2. moving account
710 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
711 * It is added to LRU before charge.
712 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
713 * When moving account, the page is not on LRU. It's isolated.
714 */
4f98a2fe 715
08e552c6
KH
716void mem_cgroup_del_lru_list(struct page *page, enum lru_list lru)
717{
718 struct page_cgroup *pc;
08e552c6 719 struct mem_cgroup_per_zone *mz;
6d12e2d8 720
f8d66542 721 if (mem_cgroup_disabled())
08e552c6
KH
722 return;
723 pc = lookup_page_cgroup(page);
724 /* can happen while we handle swapcache. */
4b3bde4c 725 if (!TestClearPageCgroupAcctLRU(pc))
08e552c6 726 return;
4b3bde4c 727 VM_BUG_ON(!pc->mem_cgroup);
544122e5
KH
728 /*
729 * We don't check PCG_USED bit. It's cleared when the "page" is finally
730 * removed from global LRU.
731 */
08e552c6 732 mz = page_cgroup_zoneinfo(pc);
b69408e8 733 MEM_CGROUP_ZSTAT(mz, lru) -= 1;
4b3bde4c
BS
734 if (mem_cgroup_is_root(pc->mem_cgroup))
735 return;
736 VM_BUG_ON(list_empty(&pc->lru));
08e552c6
KH
737 list_del_init(&pc->lru);
738 return;
6d12e2d8
KH
739}
740
08e552c6 741void mem_cgroup_del_lru(struct page *page)
6d12e2d8 742{
08e552c6
KH
743 mem_cgroup_del_lru_list(page, page_lru(page));
744}
b69408e8 745
08e552c6
KH
746void mem_cgroup_rotate_lru_list(struct page *page, enum lru_list lru)
747{
748 struct mem_cgroup_per_zone *mz;
749 struct page_cgroup *pc;
b69408e8 750
f8d66542 751 if (mem_cgroup_disabled())
08e552c6 752 return;
6d12e2d8 753
08e552c6 754 pc = lookup_page_cgroup(page);
bd112db8
DN
755 /*
756 * Used bit is set without atomic ops but after smp_wmb().
757 * For making pc->mem_cgroup visible, insert smp_rmb() here.
758 */
08e552c6 759 smp_rmb();
4b3bde4c
BS
760 /* unused or root page is not rotated. */
761 if (!PageCgroupUsed(pc) || mem_cgroup_is_root(pc->mem_cgroup))
08e552c6
KH
762 return;
763 mz = page_cgroup_zoneinfo(pc);
764 list_move(&pc->lru, &mz->lists[lru]);
6d12e2d8
KH
765}
766
08e552c6 767void mem_cgroup_add_lru_list(struct page *page, enum lru_list lru)
66e1707b 768{
08e552c6
KH
769 struct page_cgroup *pc;
770 struct mem_cgroup_per_zone *mz;
6d12e2d8 771
f8d66542 772 if (mem_cgroup_disabled())
08e552c6
KH
773 return;
774 pc = lookup_page_cgroup(page);
4b3bde4c 775 VM_BUG_ON(PageCgroupAcctLRU(pc));
bd112db8
DN
776 /*
777 * Used bit is set without atomic ops but after smp_wmb().
778 * For making pc->mem_cgroup visible, insert smp_rmb() here.
779 */
08e552c6
KH
780 smp_rmb();
781 if (!PageCgroupUsed(pc))
894bc310 782 return;
b69408e8 783
08e552c6 784 mz = page_cgroup_zoneinfo(pc);
b69408e8 785 MEM_CGROUP_ZSTAT(mz, lru) += 1;
4b3bde4c
BS
786 SetPageCgroupAcctLRU(pc);
787 if (mem_cgroup_is_root(pc->mem_cgroup))
788 return;
08e552c6
KH
789 list_add(&pc->lru, &mz->lists[lru]);
790}
544122e5 791
08e552c6 792/*
544122e5
KH
793 * At handling SwapCache, pc->mem_cgroup may be changed while it's linked to
794 * lru because the page may.be reused after it's fully uncharged (because of
795 * SwapCache behavior).To handle that, unlink page_cgroup from LRU when charge
796 * it again. This function is only used to charge SwapCache. It's done under
797 * lock_page and expected that zone->lru_lock is never held.
08e552c6 798 */
544122e5 799static void mem_cgroup_lru_del_before_commit_swapcache(struct page *page)
08e552c6 800{
544122e5
KH
801 unsigned long flags;
802 struct zone *zone = page_zone(page);
803 struct page_cgroup *pc = lookup_page_cgroup(page);
804
805 spin_lock_irqsave(&zone->lru_lock, flags);
806 /*
807 * Forget old LRU when this page_cgroup is *not* used. This Used bit
808 * is guarded by lock_page() because the page is SwapCache.
809 */
810 if (!PageCgroupUsed(pc))
811 mem_cgroup_del_lru_list(page, page_lru(page));
812 spin_unlock_irqrestore(&zone->lru_lock, flags);
08e552c6
KH
813}
814
544122e5
KH
815static void mem_cgroup_lru_add_after_commit_swapcache(struct page *page)
816{
817 unsigned long flags;
818 struct zone *zone = page_zone(page);
819 struct page_cgroup *pc = lookup_page_cgroup(page);
820
821 spin_lock_irqsave(&zone->lru_lock, flags);
822 /* link when the page is linked to LRU but page_cgroup isn't */
4b3bde4c 823 if (PageLRU(page) && !PageCgroupAcctLRU(pc))
544122e5
KH
824 mem_cgroup_add_lru_list(page, page_lru(page));
825 spin_unlock_irqrestore(&zone->lru_lock, flags);
826}
827
828
08e552c6
KH
829void mem_cgroup_move_lists(struct page *page,
830 enum lru_list from, enum lru_list to)
831{
f8d66542 832 if (mem_cgroup_disabled())
08e552c6
KH
833 return;
834 mem_cgroup_del_lru_list(page, from);
835 mem_cgroup_add_lru_list(page, to);
66e1707b
BS
836}
837
4c4a2214
DR
838int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *mem)
839{
840 int ret;
0b7f569e 841 struct mem_cgroup *curr = NULL;
158e0a2d 842 struct task_struct *p;
4c4a2214 843
158e0a2d
KH
844 p = find_lock_task_mm(task);
845 if (!p)
846 return 0;
847 curr = try_get_mem_cgroup_from_mm(p->mm);
848 task_unlock(p);
0b7f569e
KH
849 if (!curr)
850 return 0;
d31f56db
DN
851 /*
852 * We should check use_hierarchy of "mem" not "curr". Because checking
853 * use_hierarchy of "curr" here make this function true if hierarchy is
854 * enabled in "curr" and "curr" is a child of "mem" in *cgroup*
855 * hierarchy(even if use_hierarchy is disabled in "mem").
856 */
857 if (mem->use_hierarchy)
0b7f569e
KH
858 ret = css_is_ancestor(&curr->css, &mem->css);
859 else
860 ret = (curr == mem);
861 css_put(&curr->css);
4c4a2214
DR
862 return ret;
863}
864
c772be93 865static int calc_inactive_ratio(struct mem_cgroup *memcg, unsigned long *present_pages)
14797e23
KM
866{
867 unsigned long active;
868 unsigned long inactive;
c772be93
KM
869 unsigned long gb;
870 unsigned long inactive_ratio;
14797e23 871
14067bb3
KH
872 inactive = mem_cgroup_get_local_zonestat(memcg, LRU_INACTIVE_ANON);
873 active = mem_cgroup_get_local_zonestat(memcg, LRU_ACTIVE_ANON);
14797e23 874
c772be93
KM
875 gb = (inactive + active) >> (30 - PAGE_SHIFT);
876 if (gb)
877 inactive_ratio = int_sqrt(10 * gb);
878 else
879 inactive_ratio = 1;
880
881 if (present_pages) {
882 present_pages[0] = inactive;
883 present_pages[1] = active;
884 }
885
886 return inactive_ratio;
887}
888
889int mem_cgroup_inactive_anon_is_low(struct mem_cgroup *memcg)
890{
891 unsigned long active;
892 unsigned long inactive;
893 unsigned long present_pages[2];
894 unsigned long inactive_ratio;
895
896 inactive_ratio = calc_inactive_ratio(memcg, present_pages);
897
898 inactive = present_pages[0];
899 active = present_pages[1];
900
901 if (inactive * inactive_ratio < active)
14797e23
KM
902 return 1;
903
904 return 0;
905}
906
56e49d21
RR
907int mem_cgroup_inactive_file_is_low(struct mem_cgroup *memcg)
908{
909 unsigned long active;
910 unsigned long inactive;
911
912 inactive = mem_cgroup_get_local_zonestat(memcg, LRU_INACTIVE_FILE);
913 active = mem_cgroup_get_local_zonestat(memcg, LRU_ACTIVE_FILE);
914
915 return (active > inactive);
916}
917
a3d8e054
KM
918unsigned long mem_cgroup_zone_nr_pages(struct mem_cgroup *memcg,
919 struct zone *zone,
920 enum lru_list lru)
921{
922 int nid = zone->zone_pgdat->node_id;
923 int zid = zone_idx(zone);
924 struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
925
926 return MEM_CGROUP_ZSTAT(mz, lru);
927}
928
3e2f41f1
KM
929struct zone_reclaim_stat *mem_cgroup_get_reclaim_stat(struct mem_cgroup *memcg,
930 struct zone *zone)
931{
932 int nid = zone->zone_pgdat->node_id;
933 int zid = zone_idx(zone);
934 struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
935
936 return &mz->reclaim_stat;
937}
938
939struct zone_reclaim_stat *
940mem_cgroup_get_reclaim_stat_from_page(struct page *page)
941{
942 struct page_cgroup *pc;
943 struct mem_cgroup_per_zone *mz;
944
945 if (mem_cgroup_disabled())
946 return NULL;
947
948 pc = lookup_page_cgroup(page);
bd112db8
DN
949 /*
950 * Used bit is set without atomic ops but after smp_wmb().
951 * For making pc->mem_cgroup visible, insert smp_rmb() here.
952 */
953 smp_rmb();
954 if (!PageCgroupUsed(pc))
955 return NULL;
956
3e2f41f1
KM
957 mz = page_cgroup_zoneinfo(pc);
958 if (!mz)
959 return NULL;
960
961 return &mz->reclaim_stat;
962}
963
66e1707b
BS
964unsigned long mem_cgroup_isolate_pages(unsigned long nr_to_scan,
965 struct list_head *dst,
966 unsigned long *scanned, int order,
967 int mode, struct zone *z,
968 struct mem_cgroup *mem_cont,
4f98a2fe 969 int active, int file)
66e1707b
BS
970{
971 unsigned long nr_taken = 0;
972 struct page *page;
973 unsigned long scan;
974 LIST_HEAD(pc_list);
975 struct list_head *src;
ff7283fa 976 struct page_cgroup *pc, *tmp;
1ecaab2b
KH
977 int nid = z->zone_pgdat->node_id;
978 int zid = zone_idx(z);
979 struct mem_cgroup_per_zone *mz;
b7c46d15 980 int lru = LRU_FILE * file + active;
2ffebca6 981 int ret;
66e1707b 982
cf475ad2 983 BUG_ON(!mem_cont);
1ecaab2b 984 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
b69408e8 985 src = &mz->lists[lru];
66e1707b 986
ff7283fa
KH
987 scan = 0;
988 list_for_each_entry_safe_reverse(pc, tmp, src, lru) {
436c6541 989 if (scan >= nr_to_scan)
ff7283fa 990 break;
08e552c6
KH
991
992 page = pc->page;
52d4b9ac
KH
993 if (unlikely(!PageCgroupUsed(pc)))
994 continue;
436c6541 995 if (unlikely(!PageLRU(page)))
ff7283fa 996 continue;
ff7283fa 997
436c6541 998 scan++;
2ffebca6
KH
999 ret = __isolate_lru_page(page, mode, file);
1000 switch (ret) {
1001 case 0:
66e1707b 1002 list_move(&page->lru, dst);
2ffebca6 1003 mem_cgroup_del_lru(page);
66e1707b 1004 nr_taken++;
2ffebca6
KH
1005 break;
1006 case -EBUSY:
1007 /* we don't affect global LRU but rotate in our LRU */
1008 mem_cgroup_rotate_lru_list(page, page_lru(page));
1009 break;
1010 default:
1011 break;
66e1707b
BS
1012 }
1013 }
1014
66e1707b 1015 *scanned = scan;
cc8e970c
KM
1016
1017 trace_mm_vmscan_memcg_isolate(0, nr_to_scan, scan, nr_taken,
1018 0, 0, 0, mode);
1019
66e1707b
BS
1020 return nr_taken;
1021}
1022
6d61ef40
BS
1023#define mem_cgroup_from_res_counter(counter, member) \
1024 container_of(counter, struct mem_cgroup, member)
1025
b85a96c0
DN
1026static bool mem_cgroup_check_under_limit(struct mem_cgroup *mem)
1027{
1028 if (do_swap_account) {
1029 if (res_counter_check_under_limit(&mem->res) &&
1030 res_counter_check_under_limit(&mem->memsw))
1031 return true;
1032 } else
1033 if (res_counter_check_under_limit(&mem->res))
1034 return true;
1035 return false;
1036}
1037
a7885eb8
KM
1038static unsigned int get_swappiness(struct mem_cgroup *memcg)
1039{
1040 struct cgroup *cgrp = memcg->css.cgroup;
1041 unsigned int swappiness;
1042
1043 /* root ? */
1044 if (cgrp->parent == NULL)
1045 return vm_swappiness;
1046
1047 spin_lock(&memcg->reclaim_param_lock);
1048 swappiness = memcg->swappiness;
1049 spin_unlock(&memcg->reclaim_param_lock);
1050
1051 return swappiness;
1052}
1053
4b534334
KH
1054/* A routine for testing mem is not under move_account */
1055
1056static bool mem_cgroup_under_move(struct mem_cgroup *mem)
1057{
2bd9bb20
KH
1058 struct mem_cgroup *from;
1059 struct mem_cgroup *to;
4b534334 1060 bool ret = false;
2bd9bb20
KH
1061 /*
1062 * Unlike task_move routines, we access mc.to, mc.from not under
1063 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1064 */
1065 spin_lock(&mc.lock);
1066 from = mc.from;
1067 to = mc.to;
1068 if (!from)
1069 goto unlock;
1070 if (from == mem || to == mem
1071 || (mem->use_hierarchy && css_is_ancestor(&from->css, &mem->css))
1072 || (mem->use_hierarchy && css_is_ancestor(&to->css, &mem->css)))
1073 ret = true;
1074unlock:
1075 spin_unlock(&mc.lock);
4b534334
KH
1076 return ret;
1077}
1078
1079static bool mem_cgroup_wait_acct_move(struct mem_cgroup *mem)
1080{
1081 if (mc.moving_task && current != mc.moving_task) {
1082 if (mem_cgroup_under_move(mem)) {
1083 DEFINE_WAIT(wait);
1084 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1085 /* moving charge context might have finished. */
1086 if (mc.moving_task)
1087 schedule();
1088 finish_wait(&mc.waitq, &wait);
1089 return true;
1090 }
1091 }
1092 return false;
1093}
1094
81d39c20
KH
1095static int mem_cgroup_count_children_cb(struct mem_cgroup *mem, void *data)
1096{
1097 int *val = data;
1098 (*val)++;
1099 return 0;
1100}
e222432b
BS
1101
1102/**
6a6135b6 1103 * mem_cgroup_print_oom_info: Called from OOM with tasklist_lock held in read mode.
e222432b
BS
1104 * @memcg: The memory cgroup that went over limit
1105 * @p: Task that is going to be killed
1106 *
1107 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1108 * enabled
1109 */
1110void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1111{
1112 struct cgroup *task_cgrp;
1113 struct cgroup *mem_cgrp;
1114 /*
1115 * Need a buffer in BSS, can't rely on allocations. The code relies
1116 * on the assumption that OOM is serialized for memory controller.
1117 * If this assumption is broken, revisit this code.
1118 */
1119 static char memcg_name[PATH_MAX];
1120 int ret;
1121
d31f56db 1122 if (!memcg || !p)
e222432b
BS
1123 return;
1124
1125
1126 rcu_read_lock();
1127
1128 mem_cgrp = memcg->css.cgroup;
1129 task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
1130
1131 ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
1132 if (ret < 0) {
1133 /*
1134 * Unfortunately, we are unable to convert to a useful name
1135 * But we'll still print out the usage information
1136 */
1137 rcu_read_unlock();
1138 goto done;
1139 }
1140 rcu_read_unlock();
1141
1142 printk(KERN_INFO "Task in %s killed", memcg_name);
1143
1144 rcu_read_lock();
1145 ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
1146 if (ret < 0) {
1147 rcu_read_unlock();
1148 goto done;
1149 }
1150 rcu_read_unlock();
1151
1152 /*
1153 * Continues from above, so we don't need an KERN_ level
1154 */
1155 printk(KERN_CONT " as a result of limit of %s\n", memcg_name);
1156done:
1157
1158 printk(KERN_INFO "memory: usage %llukB, limit %llukB, failcnt %llu\n",
1159 res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
1160 res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
1161 res_counter_read_u64(&memcg->res, RES_FAILCNT));
1162 printk(KERN_INFO "memory+swap: usage %llukB, limit %llukB, "
1163 "failcnt %llu\n",
1164 res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
1165 res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
1166 res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
1167}
1168
81d39c20
KH
1169/*
1170 * This function returns the number of memcg under hierarchy tree. Returns
1171 * 1(self count) if no children.
1172 */
1173static int mem_cgroup_count_children(struct mem_cgroup *mem)
1174{
1175 int num = 0;
1176 mem_cgroup_walk_tree(mem, &num, mem_cgroup_count_children_cb);
1177 return num;
1178}
1179
a63d83f4
DR
1180/*
1181 * Return the memory (and swap, if configured) limit for a memcg.
1182 */
1183u64 mem_cgroup_get_limit(struct mem_cgroup *memcg)
1184{
1185 u64 limit;
1186 u64 memsw;
1187
1188 limit = res_counter_read_u64(&memcg->res, RES_LIMIT) +
1189 total_swap_pages;
1190 memsw = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
1191 /*
1192 * If memsw is finite and limits the amount of swap space available
1193 * to this memcg, return that limit.
1194 */
1195 return min(limit, memsw);
1196}
1197
6d61ef40 1198/*
04046e1a
KH
1199 * Visit the first child (need not be the first child as per the ordering
1200 * of the cgroup list, since we track last_scanned_child) of @mem and use
1201 * that to reclaim free pages from.
1202 */
1203static struct mem_cgroup *
1204mem_cgroup_select_victim(struct mem_cgroup *root_mem)
1205{
1206 struct mem_cgroup *ret = NULL;
1207 struct cgroup_subsys_state *css;
1208 int nextid, found;
1209
1210 if (!root_mem->use_hierarchy) {
1211 css_get(&root_mem->css);
1212 ret = root_mem;
1213 }
1214
1215 while (!ret) {
1216 rcu_read_lock();
1217 nextid = root_mem->last_scanned_child + 1;
1218 css = css_get_next(&mem_cgroup_subsys, nextid, &root_mem->css,
1219 &found);
1220 if (css && css_tryget(css))
1221 ret = container_of(css, struct mem_cgroup, css);
1222
1223 rcu_read_unlock();
1224 /* Updates scanning parameter */
1225 spin_lock(&root_mem->reclaim_param_lock);
1226 if (!css) {
1227 /* this means start scan from ID:1 */
1228 root_mem->last_scanned_child = 0;
1229 } else
1230 root_mem->last_scanned_child = found;
1231 spin_unlock(&root_mem->reclaim_param_lock);
1232 }
1233
1234 return ret;
1235}
1236
1237/*
1238 * Scan the hierarchy if needed to reclaim memory. We remember the last child
1239 * we reclaimed from, so that we don't end up penalizing one child extensively
1240 * based on its position in the children list.
6d61ef40
BS
1241 *
1242 * root_mem is the original ancestor that we've been reclaim from.
04046e1a
KH
1243 *
1244 * We give up and return to the caller when we visit root_mem twice.
1245 * (other groups can be removed while we're walking....)
81d39c20
KH
1246 *
1247 * If shrink==true, for avoiding to free too much, this returns immedieately.
6d61ef40
BS
1248 */
1249static int mem_cgroup_hierarchical_reclaim(struct mem_cgroup *root_mem,
4e416953 1250 struct zone *zone,
75822b44
BS
1251 gfp_t gfp_mask,
1252 unsigned long reclaim_options)
6d61ef40 1253{
04046e1a
KH
1254 struct mem_cgroup *victim;
1255 int ret, total = 0;
1256 int loop = 0;
75822b44
BS
1257 bool noswap = reclaim_options & MEM_CGROUP_RECLAIM_NOSWAP;
1258 bool shrink = reclaim_options & MEM_CGROUP_RECLAIM_SHRINK;
4e416953
BS
1259 bool check_soft = reclaim_options & MEM_CGROUP_RECLAIM_SOFT;
1260 unsigned long excess = mem_cgroup_get_excess(root_mem);
04046e1a 1261
22a668d7
KH
1262 /* If memsw_is_minimum==1, swap-out is of-no-use. */
1263 if (root_mem->memsw_is_minimum)
1264 noswap = true;
1265
4e416953 1266 while (1) {
04046e1a 1267 victim = mem_cgroup_select_victim(root_mem);
4e416953 1268 if (victim == root_mem) {
04046e1a 1269 loop++;
cdec2e42
KH
1270 if (loop >= 1)
1271 drain_all_stock_async();
4e416953
BS
1272 if (loop >= 2) {
1273 /*
1274 * If we have not been able to reclaim
1275 * anything, it might because there are
1276 * no reclaimable pages under this hierarchy
1277 */
1278 if (!check_soft || !total) {
1279 css_put(&victim->css);
1280 break;
1281 }
1282 /*
1283 * We want to do more targetted reclaim.
1284 * excess >> 2 is not to excessive so as to
1285 * reclaim too much, nor too less that we keep
1286 * coming back to reclaim from this cgroup
1287 */
1288 if (total >= (excess >> 2) ||
1289 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS)) {
1290 css_put(&victim->css);
1291 break;
1292 }
1293 }
1294 }
c62b1a3b 1295 if (!mem_cgroup_local_usage(victim)) {
04046e1a
KH
1296 /* this cgroup's local usage == 0 */
1297 css_put(&victim->css);
6d61ef40
BS
1298 continue;
1299 }
04046e1a 1300 /* we use swappiness of local cgroup */
4e416953
BS
1301 if (check_soft)
1302 ret = mem_cgroup_shrink_node_zone(victim, gfp_mask,
14fec796 1303 noswap, get_swappiness(victim), zone);
4e416953
BS
1304 else
1305 ret = try_to_free_mem_cgroup_pages(victim, gfp_mask,
1306 noswap, get_swappiness(victim));
04046e1a 1307 css_put(&victim->css);
81d39c20
KH
1308 /*
1309 * At shrinking usage, we can't check we should stop here or
1310 * reclaim more. It's depends on callers. last_scanned_child
1311 * will work enough for keeping fairness under tree.
1312 */
1313 if (shrink)
1314 return ret;
04046e1a 1315 total += ret;
4e416953
BS
1316 if (check_soft) {
1317 if (res_counter_check_under_soft_limit(&root_mem->res))
1318 return total;
1319 } else if (mem_cgroup_check_under_limit(root_mem))
04046e1a 1320 return 1 + total;
6d61ef40 1321 }
04046e1a 1322 return total;
6d61ef40
BS
1323}
1324
867578cb 1325static int mem_cgroup_oom_lock_cb(struct mem_cgroup *mem, void *data)
a636b327 1326{
867578cb
KH
1327 int *val = (int *)data;
1328 int x;
1329 /*
1330 * Logically, we can stop scanning immediately when we find
1331 * a memcg is already locked. But condidering unlock ops and
1332 * creation/removal of memcg, scan-all is simple operation.
1333 */
1334 x = atomic_inc_return(&mem->oom_lock);
1335 *val = max(x, *val);
1336 return 0;
1337}
1338/*
1339 * Check OOM-Killer is already running under our hierarchy.
1340 * If someone is running, return false.
1341 */
1342static bool mem_cgroup_oom_lock(struct mem_cgroup *mem)
1343{
1344 int lock_count = 0;
a636b327 1345
867578cb
KH
1346 mem_cgroup_walk_tree(mem, &lock_count, mem_cgroup_oom_lock_cb);
1347
1348 if (lock_count == 1)
1349 return true;
1350 return false;
a636b327 1351}
0b7f569e 1352
867578cb 1353static int mem_cgroup_oom_unlock_cb(struct mem_cgroup *mem, void *data)
0b7f569e 1354{
867578cb
KH
1355 /*
1356 * When a new child is created while the hierarchy is under oom,
1357 * mem_cgroup_oom_lock() may not be called. We have to use
1358 * atomic_add_unless() here.
1359 */
1360 atomic_add_unless(&mem->oom_lock, -1, 0);
0b7f569e
KH
1361 return 0;
1362}
1363
867578cb
KH
1364static void mem_cgroup_oom_unlock(struct mem_cgroup *mem)
1365{
1366 mem_cgroup_walk_tree(mem, NULL, mem_cgroup_oom_unlock_cb);
1367}
1368
1369static DEFINE_MUTEX(memcg_oom_mutex);
1370static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1371
dc98df5a
KH
1372struct oom_wait_info {
1373 struct mem_cgroup *mem;
1374 wait_queue_t wait;
1375};
1376
1377static int memcg_oom_wake_function(wait_queue_t *wait,
1378 unsigned mode, int sync, void *arg)
1379{
1380 struct mem_cgroup *wake_mem = (struct mem_cgroup *)arg;
1381 struct oom_wait_info *oom_wait_info;
1382
1383 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1384
1385 if (oom_wait_info->mem == wake_mem)
1386 goto wakeup;
1387 /* if no hierarchy, no match */
1388 if (!oom_wait_info->mem->use_hierarchy || !wake_mem->use_hierarchy)
1389 return 0;
1390 /*
1391 * Both of oom_wait_info->mem and wake_mem are stable under us.
1392 * Then we can use css_is_ancestor without taking care of RCU.
1393 */
1394 if (!css_is_ancestor(&oom_wait_info->mem->css, &wake_mem->css) &&
1395 !css_is_ancestor(&wake_mem->css, &oom_wait_info->mem->css))
1396 return 0;
1397
1398wakeup:
1399 return autoremove_wake_function(wait, mode, sync, arg);
1400}
1401
1402static void memcg_wakeup_oom(struct mem_cgroup *mem)
1403{
1404 /* for filtering, pass "mem" as argument. */
1405 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, mem);
1406}
1407
3c11ecf4
KH
1408static void memcg_oom_recover(struct mem_cgroup *mem)
1409{
2bd9bb20 1410 if (mem && atomic_read(&mem->oom_lock))
3c11ecf4
KH
1411 memcg_wakeup_oom(mem);
1412}
1413
867578cb
KH
1414/*
1415 * try to call OOM killer. returns false if we should exit memory-reclaim loop.
1416 */
1417bool mem_cgroup_handle_oom(struct mem_cgroup *mem, gfp_t mask)
0b7f569e 1418{
dc98df5a 1419 struct oom_wait_info owait;
3c11ecf4 1420 bool locked, need_to_kill;
867578cb 1421
dc98df5a
KH
1422 owait.mem = mem;
1423 owait.wait.flags = 0;
1424 owait.wait.func = memcg_oom_wake_function;
1425 owait.wait.private = current;
1426 INIT_LIST_HEAD(&owait.wait.task_list);
3c11ecf4 1427 need_to_kill = true;
867578cb
KH
1428 /* At first, try to OOM lock hierarchy under mem.*/
1429 mutex_lock(&memcg_oom_mutex);
1430 locked = mem_cgroup_oom_lock(mem);
1431 /*
1432 * Even if signal_pending(), we can't quit charge() loop without
1433 * accounting. So, UNINTERRUPTIBLE is appropriate. But SIGKILL
1434 * under OOM is always welcomed, use TASK_KILLABLE here.
1435 */
3c11ecf4
KH
1436 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
1437 if (!locked || mem->oom_kill_disable)
1438 need_to_kill = false;
1439 if (locked)
9490ff27 1440 mem_cgroup_oom_notify(mem);
867578cb
KH
1441 mutex_unlock(&memcg_oom_mutex);
1442
3c11ecf4
KH
1443 if (need_to_kill) {
1444 finish_wait(&memcg_oom_waitq, &owait.wait);
867578cb 1445 mem_cgroup_out_of_memory(mem, mask);
3c11ecf4 1446 } else {
867578cb 1447 schedule();
dc98df5a 1448 finish_wait(&memcg_oom_waitq, &owait.wait);
867578cb
KH
1449 }
1450 mutex_lock(&memcg_oom_mutex);
1451 mem_cgroup_oom_unlock(mem);
dc98df5a 1452 memcg_wakeup_oom(mem);
867578cb
KH
1453 mutex_unlock(&memcg_oom_mutex);
1454
1455 if (test_thread_flag(TIF_MEMDIE) || fatal_signal_pending(current))
1456 return false;
1457 /* Give chance to dying process */
1458 schedule_timeout(1);
1459 return true;
0b7f569e
KH
1460}
1461
d69b042f
BS
1462/*
1463 * Currently used to update mapped file statistics, but the routine can be
1464 * generalized to update other statistics as well.
1465 */
d8046582 1466void mem_cgroup_update_file_mapped(struct page *page, int val)
d69b042f
BS
1467{
1468 struct mem_cgroup *mem;
d69b042f
BS
1469 struct page_cgroup *pc;
1470
d69b042f
BS
1471 pc = lookup_page_cgroup(page);
1472 if (unlikely(!pc))
1473 return;
1474
1475 lock_page_cgroup(pc);
1476 mem = pc->mem_cgroup;
8725d541 1477 if (!mem || !PageCgroupUsed(pc))
d69b042f
BS
1478 goto done;
1479
1480 /*
c62b1a3b 1481 * Preemption is already disabled. We can use __this_cpu_xxx
d69b042f 1482 */
8725d541
KH
1483 if (val > 0) {
1484 __this_cpu_inc(mem->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
1485 SetPageCgroupFileMapped(pc);
1486 } else {
1487 __this_cpu_dec(mem->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
1488 ClearPageCgroupFileMapped(pc);
1489 }
d69b042f 1490
d69b042f
BS
1491done:
1492 unlock_page_cgroup(pc);
1493}
0b7f569e 1494
cdec2e42
KH
1495/*
1496 * size of first charge trial. "32" comes from vmscan.c's magic value.
1497 * TODO: maybe necessary to use big numbers in big irons.
1498 */
1499#define CHARGE_SIZE (32 * PAGE_SIZE)
1500struct memcg_stock_pcp {
1501 struct mem_cgroup *cached; /* this never be root cgroup */
1502 int charge;
1503 struct work_struct work;
1504};
1505static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
1506static atomic_t memcg_drain_count;
1507
1508/*
1509 * Try to consume stocked charge on this cpu. If success, PAGE_SIZE is consumed
1510 * from local stock and true is returned. If the stock is 0 or charges from a
1511 * cgroup which is not current target, returns false. This stock will be
1512 * refilled.
1513 */
1514static bool consume_stock(struct mem_cgroup *mem)
1515{
1516 struct memcg_stock_pcp *stock;
1517 bool ret = true;
1518
1519 stock = &get_cpu_var(memcg_stock);
1520 if (mem == stock->cached && stock->charge)
1521 stock->charge -= PAGE_SIZE;
1522 else /* need to call res_counter_charge */
1523 ret = false;
1524 put_cpu_var(memcg_stock);
1525 return ret;
1526}
1527
1528/*
1529 * Returns stocks cached in percpu to res_counter and reset cached information.
1530 */
1531static void drain_stock(struct memcg_stock_pcp *stock)
1532{
1533 struct mem_cgroup *old = stock->cached;
1534
1535 if (stock->charge) {
1536 res_counter_uncharge(&old->res, stock->charge);
1537 if (do_swap_account)
1538 res_counter_uncharge(&old->memsw, stock->charge);
1539 }
1540 stock->cached = NULL;
1541 stock->charge = 0;
1542}
1543
1544/*
1545 * This must be called under preempt disabled or must be called by
1546 * a thread which is pinned to local cpu.
1547 */
1548static void drain_local_stock(struct work_struct *dummy)
1549{
1550 struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
1551 drain_stock(stock);
1552}
1553
1554/*
1555 * Cache charges(val) which is from res_counter, to local per_cpu area.
320cc51d 1556 * This will be consumed by consume_stock() function, later.
cdec2e42
KH
1557 */
1558static void refill_stock(struct mem_cgroup *mem, int val)
1559{
1560 struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
1561
1562 if (stock->cached != mem) { /* reset if necessary */
1563 drain_stock(stock);
1564 stock->cached = mem;
1565 }
1566 stock->charge += val;
1567 put_cpu_var(memcg_stock);
1568}
1569
1570/*
1571 * Tries to drain stocked charges in other cpus. This function is asynchronous
1572 * and just put a work per cpu for draining localy on each cpu. Caller can
1573 * expects some charges will be back to res_counter later but cannot wait for
1574 * it.
1575 */
1576static void drain_all_stock_async(void)
1577{
1578 int cpu;
1579 /* This function is for scheduling "drain" in asynchronous way.
1580 * The result of "drain" is not directly handled by callers. Then,
1581 * if someone is calling drain, we don't have to call drain more.
1582 * Anyway, WORK_STRUCT_PENDING check in queue_work_on() will catch if
1583 * there is a race. We just do loose check here.
1584 */
1585 if (atomic_read(&memcg_drain_count))
1586 return;
1587 /* Notify other cpus that system-wide "drain" is running */
1588 atomic_inc(&memcg_drain_count);
1589 get_online_cpus();
1590 for_each_online_cpu(cpu) {
1591 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
1592 schedule_work_on(cpu, &stock->work);
1593 }
1594 put_online_cpus();
1595 atomic_dec(&memcg_drain_count);
1596 /* We don't wait for flush_work */
1597}
1598
1599/* This is a synchronous drain interface. */
1600static void drain_all_stock_sync(void)
1601{
1602 /* called when force_empty is called */
1603 atomic_inc(&memcg_drain_count);
1604 schedule_on_each_cpu(drain_local_stock);
1605 atomic_dec(&memcg_drain_count);
1606}
1607
1608static int __cpuinit memcg_stock_cpu_callback(struct notifier_block *nb,
1609 unsigned long action,
1610 void *hcpu)
1611{
1612 int cpu = (unsigned long)hcpu;
1613 struct memcg_stock_pcp *stock;
1614
1615 if (action != CPU_DEAD)
1616 return NOTIFY_OK;
1617 stock = &per_cpu(memcg_stock, cpu);
1618 drain_stock(stock);
1619 return NOTIFY_OK;
1620}
1621
4b534334
KH
1622
1623/* See __mem_cgroup_try_charge() for details */
1624enum {
1625 CHARGE_OK, /* success */
1626 CHARGE_RETRY, /* need to retry but retry is not bad */
1627 CHARGE_NOMEM, /* we can't do more. return -ENOMEM */
1628 CHARGE_WOULDBLOCK, /* GFP_WAIT wasn't set and no enough res. */
1629 CHARGE_OOM_DIE, /* the current is killed because of OOM */
1630};
1631
1632static int __mem_cgroup_do_charge(struct mem_cgroup *mem, gfp_t gfp_mask,
1633 int csize, bool oom_check)
1634{
1635 struct mem_cgroup *mem_over_limit;
1636 struct res_counter *fail_res;
1637 unsigned long flags = 0;
1638 int ret;
1639
1640 ret = res_counter_charge(&mem->res, csize, &fail_res);
1641
1642 if (likely(!ret)) {
1643 if (!do_swap_account)
1644 return CHARGE_OK;
1645 ret = res_counter_charge(&mem->memsw, csize, &fail_res);
1646 if (likely(!ret))
1647 return CHARGE_OK;
1648
1649 mem_over_limit = mem_cgroup_from_res_counter(fail_res, memsw);
1650 flags |= MEM_CGROUP_RECLAIM_NOSWAP;
1651 } else
1652 mem_over_limit = mem_cgroup_from_res_counter(fail_res, res);
1653
1654 if (csize > PAGE_SIZE) /* change csize and retry */
1655 return CHARGE_RETRY;
1656
1657 if (!(gfp_mask & __GFP_WAIT))
1658 return CHARGE_WOULDBLOCK;
1659
1660 ret = mem_cgroup_hierarchical_reclaim(mem_over_limit, NULL,
1661 gfp_mask, flags);
1662 /*
1663 * try_to_free_mem_cgroup_pages() might not give us a full
1664 * picture of reclaim. Some pages are reclaimed and might be
1665 * moved to swap cache or just unmapped from the cgroup.
1666 * Check the limit again to see if the reclaim reduced the
1667 * current usage of the cgroup before giving up
1668 */
1669 if (ret || mem_cgroup_check_under_limit(mem_over_limit))
1670 return CHARGE_RETRY;
1671
1672 /*
1673 * At task move, charge accounts can be doubly counted. So, it's
1674 * better to wait until the end of task_move if something is going on.
1675 */
1676 if (mem_cgroup_wait_acct_move(mem_over_limit))
1677 return CHARGE_RETRY;
1678
1679 /* If we don't need to call oom-killer at el, return immediately */
1680 if (!oom_check)
1681 return CHARGE_NOMEM;
1682 /* check OOM */
1683 if (!mem_cgroup_handle_oom(mem_over_limit, gfp_mask))
1684 return CHARGE_OOM_DIE;
1685
1686 return CHARGE_RETRY;
1687}
1688
f817ed48
KH
1689/*
1690 * Unlike exported interface, "oom" parameter is added. if oom==true,
1691 * oom-killer can be invoked.
8a9f3ccd 1692 */
f817ed48 1693static int __mem_cgroup_try_charge(struct mm_struct *mm,
4b534334 1694 gfp_t gfp_mask, struct mem_cgroup **memcg, bool oom)
8a9f3ccd 1695{
4b534334
KH
1696 int nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
1697 struct mem_cgroup *mem = NULL;
1698 int ret;
cdec2e42 1699 int csize = CHARGE_SIZE;
a636b327 1700
867578cb
KH
1701 /*
1702 * Unlike gloval-vm's OOM-kill, we're not in memory shortage
1703 * in system level. So, allow to go ahead dying process in addition to
1704 * MEMDIE process.
1705 */
1706 if (unlikely(test_thread_flag(TIF_MEMDIE)
1707 || fatal_signal_pending(current)))
1708 goto bypass;
a636b327 1709
8a9f3ccd 1710 /*
3be91277
HD
1711 * We always charge the cgroup the mm_struct belongs to.
1712 * The mm_struct's mem_cgroup changes on task migration if the
8a9f3ccd
BS
1713 * thread group leader migrates. It's possible that mm is not
1714 * set, if so charge the init_mm (happens for pagecache usage).
1715 */
f75ca962
KH
1716 if (!*memcg && !mm)
1717 goto bypass;
1718again:
1719 if (*memcg) { /* css should be a valid one */
4b534334 1720 mem = *memcg;
f75ca962
KH
1721 VM_BUG_ON(css_is_removed(&mem->css));
1722 if (mem_cgroup_is_root(mem))
1723 goto done;
1724 if (consume_stock(mem))
1725 goto done;
4b534334
KH
1726 css_get(&mem->css);
1727 } else {
f75ca962 1728 struct task_struct *p;
54595fe2 1729
f75ca962
KH
1730 rcu_read_lock();
1731 p = rcu_dereference(mm->owner);
1732 VM_BUG_ON(!p);
1733 /*
1734 * because we don't have task_lock(), "p" can exit while
1735 * we're here. In that case, "mem" can point to root
1736 * cgroup but never be NULL. (and task_struct itself is freed
1737 * by RCU, cgroup itself is RCU safe.) Then, we have small
1738 * risk here to get wrong cgroup. But such kind of mis-account
1739 * by race always happens because we don't have cgroup_mutex().
1740 * It's overkill and we allow that small race, here.
1741 */
1742 mem = mem_cgroup_from_task(p);
1743 VM_BUG_ON(!mem);
1744 if (mem_cgroup_is_root(mem)) {
1745 rcu_read_unlock();
1746 goto done;
1747 }
1748 if (consume_stock(mem)) {
1749 /*
1750 * It seems dagerous to access memcg without css_get().
1751 * But considering how consume_stok works, it's not
1752 * necessary. If consume_stock success, some charges
1753 * from this memcg are cached on this cpu. So, we
1754 * don't need to call css_get()/css_tryget() before
1755 * calling consume_stock().
1756 */
1757 rcu_read_unlock();
1758 goto done;
1759 }
1760 /* after here, we may be blocked. we need to get refcnt */
1761 if (!css_tryget(&mem->css)) {
1762 rcu_read_unlock();
1763 goto again;
1764 }
1765 rcu_read_unlock();
1766 }
8a9f3ccd 1767
4b534334
KH
1768 do {
1769 bool oom_check;
7a81b88c 1770
4b534334 1771 /* If killed, bypass charge */
f75ca962
KH
1772 if (fatal_signal_pending(current)) {
1773 css_put(&mem->css);
4b534334 1774 goto bypass;
f75ca962 1775 }
6d61ef40 1776
4b534334
KH
1777 oom_check = false;
1778 if (oom && !nr_oom_retries) {
1779 oom_check = true;
1780 nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
cdec2e42 1781 }
66e1707b 1782
4b534334 1783 ret = __mem_cgroup_do_charge(mem, gfp_mask, csize, oom_check);
8033b97c 1784
4b534334
KH
1785 switch (ret) {
1786 case CHARGE_OK:
1787 break;
1788 case CHARGE_RETRY: /* not in OOM situation but retry */
1789 csize = PAGE_SIZE;
f75ca962
KH
1790 css_put(&mem->css);
1791 mem = NULL;
1792 goto again;
4b534334 1793 case CHARGE_WOULDBLOCK: /* !__GFP_WAIT */
f75ca962 1794 css_put(&mem->css);
4b534334
KH
1795 goto nomem;
1796 case CHARGE_NOMEM: /* OOM routine works */
f75ca962
KH
1797 if (!oom) {
1798 css_put(&mem->css);
867578cb 1799 goto nomem;
f75ca962 1800 }
4b534334
KH
1801 /* If oom, we never return -ENOMEM */
1802 nr_oom_retries--;
1803 break;
1804 case CHARGE_OOM_DIE: /* Killed by OOM Killer */
f75ca962 1805 css_put(&mem->css);
867578cb 1806 goto bypass;
66e1707b 1807 }
4b534334
KH
1808 } while (ret != CHARGE_OK);
1809
cdec2e42
KH
1810 if (csize > PAGE_SIZE)
1811 refill_stock(mem, csize - PAGE_SIZE);
f75ca962 1812 css_put(&mem->css);
0c3e73e8 1813done:
f75ca962 1814 *memcg = mem;
7a81b88c
KH
1815 return 0;
1816nomem:
f75ca962 1817 *memcg = NULL;
7a81b88c 1818 return -ENOMEM;
867578cb
KH
1819bypass:
1820 *memcg = NULL;
1821 return 0;
7a81b88c 1822}
8a9f3ccd 1823
a3032a2c
DN
1824/*
1825 * Somemtimes we have to undo a charge we got by try_charge().
1826 * This function is for that and do uncharge, put css's refcnt.
1827 * gotten by try_charge().
1828 */
854ffa8d
DN
1829static void __mem_cgroup_cancel_charge(struct mem_cgroup *mem,
1830 unsigned long count)
a3032a2c
DN
1831{
1832 if (!mem_cgroup_is_root(mem)) {
854ffa8d 1833 res_counter_uncharge(&mem->res, PAGE_SIZE * count);
a3032a2c 1834 if (do_swap_account)
854ffa8d 1835 res_counter_uncharge(&mem->memsw, PAGE_SIZE * count);
a3032a2c 1836 }
854ffa8d
DN
1837}
1838
1839static void mem_cgroup_cancel_charge(struct mem_cgroup *mem)
1840{
1841 __mem_cgroup_cancel_charge(mem, 1);
a3032a2c
DN
1842}
1843
a3b2d692
KH
1844/*
1845 * A helper function to get mem_cgroup from ID. must be called under
1846 * rcu_read_lock(). The caller must check css_is_removed() or some if
1847 * it's concern. (dropping refcnt from swap can be called against removed
1848 * memcg.)
1849 */
1850static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
1851{
1852 struct cgroup_subsys_state *css;
1853
1854 /* ID 0 is unused ID */
1855 if (!id)
1856 return NULL;
1857 css = css_lookup(&mem_cgroup_subsys, id);
1858 if (!css)
1859 return NULL;
1860 return container_of(css, struct mem_cgroup, css);
1861}
1862
e42d9d5d 1863struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
b5a84319 1864{
e42d9d5d 1865 struct mem_cgroup *mem = NULL;
3c776e64 1866 struct page_cgroup *pc;
a3b2d692 1867 unsigned short id;
b5a84319
KH
1868 swp_entry_t ent;
1869
3c776e64
DN
1870 VM_BUG_ON(!PageLocked(page));
1871
3c776e64 1872 pc = lookup_page_cgroup(page);
c0bd3f63 1873 lock_page_cgroup(pc);
a3b2d692 1874 if (PageCgroupUsed(pc)) {
3c776e64 1875 mem = pc->mem_cgroup;
a3b2d692
KH
1876 if (mem && !css_tryget(&mem->css))
1877 mem = NULL;
e42d9d5d 1878 } else if (PageSwapCache(page)) {
3c776e64 1879 ent.val = page_private(page);
a3b2d692
KH
1880 id = lookup_swap_cgroup(ent);
1881 rcu_read_lock();
1882 mem = mem_cgroup_lookup(id);
1883 if (mem && !css_tryget(&mem->css))
1884 mem = NULL;
1885 rcu_read_unlock();
3c776e64 1886 }
c0bd3f63 1887 unlock_page_cgroup(pc);
b5a84319
KH
1888 return mem;
1889}
1890
7a81b88c 1891/*
a5e924f5 1892 * commit a charge got by __mem_cgroup_try_charge() and makes page_cgroup to be
7a81b88c
KH
1893 * USED state. If already USED, uncharge and return.
1894 */
1895
1896static void __mem_cgroup_commit_charge(struct mem_cgroup *mem,
1897 struct page_cgroup *pc,
1898 enum charge_type ctype)
1899{
7a81b88c
KH
1900 /* try_charge() can return NULL to *memcg, taking care of it. */
1901 if (!mem)
1902 return;
52d4b9ac
KH
1903
1904 lock_page_cgroup(pc);
1905 if (unlikely(PageCgroupUsed(pc))) {
1906 unlock_page_cgroup(pc);
a3032a2c 1907 mem_cgroup_cancel_charge(mem);
7a81b88c 1908 return;
52d4b9ac 1909 }
4b3bde4c 1910
8a9f3ccd 1911 pc->mem_cgroup = mem;
261fb61a
KH
1912 /*
1913 * We access a page_cgroup asynchronously without lock_page_cgroup().
1914 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
1915 * is accessed after testing USED bit. To make pc->mem_cgroup visible
1916 * before USED bit, we need memory barrier here.
1917 * See mem_cgroup_add_lru_list(), etc.
1918 */
08e552c6 1919 smp_wmb();
4b3bde4c
BS
1920 switch (ctype) {
1921 case MEM_CGROUP_CHARGE_TYPE_CACHE:
1922 case MEM_CGROUP_CHARGE_TYPE_SHMEM:
1923 SetPageCgroupCache(pc);
1924 SetPageCgroupUsed(pc);
1925 break;
1926 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
1927 ClearPageCgroupCache(pc);
1928 SetPageCgroupUsed(pc);
1929 break;
1930 default:
1931 break;
1932 }
3be91277 1933
08e552c6 1934 mem_cgroup_charge_statistics(mem, pc, true);
52d4b9ac 1935
52d4b9ac 1936 unlock_page_cgroup(pc);
430e4863
KH
1937 /*
1938 * "charge_statistics" updated event counter. Then, check it.
1939 * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
1940 * if they exceeds softlimit.
1941 */
d2265e6f 1942 memcg_check_events(mem, pc->page);
7a81b88c 1943}
66e1707b 1944
f817ed48 1945/**
57f9fd7d 1946 * __mem_cgroup_move_account - move account of the page
f817ed48
KH
1947 * @pc: page_cgroup of the page.
1948 * @from: mem_cgroup which the page is moved from.
1949 * @to: mem_cgroup which the page is moved to. @from != @to.
854ffa8d 1950 * @uncharge: whether we should call uncharge and css_put against @from.
f817ed48
KH
1951 *
1952 * The caller must confirm following.
08e552c6 1953 * - page is not on LRU (isolate_page() is useful.)
57f9fd7d 1954 * - the pc is locked, used, and ->mem_cgroup points to @from.
f817ed48 1955 *
854ffa8d
DN
1956 * This function doesn't do "charge" nor css_get to new cgroup. It should be
1957 * done by a caller(__mem_cgroup_try_charge would be usefull). If @uncharge is
1958 * true, this function does "uncharge" from old cgroup, but it doesn't if
1959 * @uncharge is false, so a caller should do "uncharge".
f817ed48
KH
1960 */
1961
57f9fd7d 1962static void __mem_cgroup_move_account(struct page_cgroup *pc,
854ffa8d 1963 struct mem_cgroup *from, struct mem_cgroup *to, bool uncharge)
f817ed48 1964{
f817ed48 1965 VM_BUG_ON(from == to);
08e552c6 1966 VM_BUG_ON(PageLRU(pc->page));
57f9fd7d
DN
1967 VM_BUG_ON(!PageCgroupLocked(pc));
1968 VM_BUG_ON(!PageCgroupUsed(pc));
1969 VM_BUG_ON(pc->mem_cgroup != from);
f817ed48 1970
8725d541 1971 if (PageCgroupFileMapped(pc)) {
c62b1a3b
KH
1972 /* Update mapped_file data for mem_cgroup */
1973 preempt_disable();
1974 __this_cpu_dec(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
1975 __this_cpu_inc(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
1976 preempt_enable();
d69b042f 1977 }
854ffa8d
DN
1978 mem_cgroup_charge_statistics(from, pc, false);
1979 if (uncharge)
1980 /* This is not "cancel", but cancel_charge does all we need. */
1981 mem_cgroup_cancel_charge(from);
d69b042f 1982
854ffa8d 1983 /* caller should have done css_get */
08e552c6
KH
1984 pc->mem_cgroup = to;
1985 mem_cgroup_charge_statistics(to, pc, true);
88703267
KH
1986 /*
1987 * We charges against "to" which may not have any tasks. Then, "to"
1988 * can be under rmdir(). But in current implementation, caller of
4ffef5fe
DN
1989 * this function is just force_empty() and move charge, so it's
1990 * garanteed that "to" is never removed. So, we don't check rmdir
1991 * status here.
88703267 1992 */
57f9fd7d
DN
1993}
1994
1995/*
1996 * check whether the @pc is valid for moving account and call
1997 * __mem_cgroup_move_account()
1998 */
1999static int mem_cgroup_move_account(struct page_cgroup *pc,
854ffa8d 2000 struct mem_cgroup *from, struct mem_cgroup *to, bool uncharge)
57f9fd7d
DN
2001{
2002 int ret = -EINVAL;
2003 lock_page_cgroup(pc);
2004 if (PageCgroupUsed(pc) && pc->mem_cgroup == from) {
854ffa8d 2005 __mem_cgroup_move_account(pc, from, to, uncharge);
57f9fd7d
DN
2006 ret = 0;
2007 }
2008 unlock_page_cgroup(pc);
d2265e6f
KH
2009 /*
2010 * check events
2011 */
2012 memcg_check_events(to, pc->page);
2013 memcg_check_events(from, pc->page);
f817ed48
KH
2014 return ret;
2015}
2016
2017/*
2018 * move charges to its parent.
2019 */
2020
2021static int mem_cgroup_move_parent(struct page_cgroup *pc,
2022 struct mem_cgroup *child,
2023 gfp_t gfp_mask)
2024{
08e552c6 2025 struct page *page = pc->page;
f817ed48
KH
2026 struct cgroup *cg = child->css.cgroup;
2027 struct cgroup *pcg = cg->parent;
2028 struct mem_cgroup *parent;
f817ed48
KH
2029 int ret;
2030
2031 /* Is ROOT ? */
2032 if (!pcg)
2033 return -EINVAL;
2034
57f9fd7d
DN
2035 ret = -EBUSY;
2036 if (!get_page_unless_zero(page))
2037 goto out;
2038 if (isolate_lru_page(page))
2039 goto put;
08e552c6 2040
f817ed48 2041 parent = mem_cgroup_from_cont(pcg);
430e4863 2042 ret = __mem_cgroup_try_charge(NULL, gfp_mask, &parent, false);
a636b327 2043 if (ret || !parent)
57f9fd7d 2044 goto put_back;
f817ed48 2045
854ffa8d
DN
2046 ret = mem_cgroup_move_account(pc, child, parent, true);
2047 if (ret)
2048 mem_cgroup_cancel_charge(parent);
57f9fd7d 2049put_back:
08e552c6 2050 putback_lru_page(page);
57f9fd7d 2051put:
40d58138 2052 put_page(page);
57f9fd7d 2053out:
f817ed48
KH
2054 return ret;
2055}
2056
7a81b88c
KH
2057/*
2058 * Charge the memory controller for page usage.
2059 * Return
2060 * 0 if the charge was successful
2061 * < 0 if the cgroup is over its limit
2062 */
2063static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
73045c47 2064 gfp_t gfp_mask, enum charge_type ctype)
7a81b88c 2065{
73045c47 2066 struct mem_cgroup *mem = NULL;
7a81b88c
KH
2067 struct page_cgroup *pc;
2068 int ret;
2069
2070 pc = lookup_page_cgroup(page);
2071 /* can happen at boot */
2072 if (unlikely(!pc))
2073 return 0;
2074 prefetchw(pc);
2075
430e4863 2076 ret = __mem_cgroup_try_charge(mm, gfp_mask, &mem, true);
a636b327 2077 if (ret || !mem)
7a81b88c
KH
2078 return ret;
2079
2080 __mem_cgroup_commit_charge(mem, pc, ctype);
8a9f3ccd 2081 return 0;
8a9f3ccd
BS
2082}
2083
7a81b88c
KH
2084int mem_cgroup_newpage_charge(struct page *page,
2085 struct mm_struct *mm, gfp_t gfp_mask)
217bc319 2086{
f8d66542 2087 if (mem_cgroup_disabled())
cede86ac 2088 return 0;
52d4b9ac
KH
2089 if (PageCompound(page))
2090 return 0;
69029cd5
KH
2091 /*
2092 * If already mapped, we don't have to account.
2093 * If page cache, page->mapping has address_space.
2094 * But page->mapping may have out-of-use anon_vma pointer,
2095 * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
2096 * is NULL.
2097 */
2098 if (page_mapped(page) || (page->mapping && !PageAnon(page)))
2099 return 0;
2100 if (unlikely(!mm))
2101 mm = &init_mm;
217bc319 2102 return mem_cgroup_charge_common(page, mm, gfp_mask,
73045c47 2103 MEM_CGROUP_CHARGE_TYPE_MAPPED);
217bc319
KH
2104}
2105
83aae4c7
DN
2106static void
2107__mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
2108 enum charge_type ctype);
2109
e1a1cd59
BS
2110int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
2111 gfp_t gfp_mask)
8697d331 2112{
b5a84319
KH
2113 int ret;
2114
f8d66542 2115 if (mem_cgroup_disabled())
cede86ac 2116 return 0;
52d4b9ac
KH
2117 if (PageCompound(page))
2118 return 0;
accf163e
KH
2119 /*
2120 * Corner case handling. This is called from add_to_page_cache()
2121 * in usual. But some FS (shmem) precharges this page before calling it
2122 * and call add_to_page_cache() with GFP_NOWAIT.
2123 *
2124 * For GFP_NOWAIT case, the page may be pre-charged before calling
2125 * add_to_page_cache(). (See shmem.c) check it here and avoid to call
2126 * charge twice. (It works but has to pay a bit larger cost.)
b5a84319
KH
2127 * And when the page is SwapCache, it should take swap information
2128 * into account. This is under lock_page() now.
accf163e
KH
2129 */
2130 if (!(gfp_mask & __GFP_WAIT)) {
2131 struct page_cgroup *pc;
2132
52d4b9ac
KH
2133 pc = lookup_page_cgroup(page);
2134 if (!pc)
2135 return 0;
2136 lock_page_cgroup(pc);
2137 if (PageCgroupUsed(pc)) {
2138 unlock_page_cgroup(pc);
accf163e
KH
2139 return 0;
2140 }
52d4b9ac 2141 unlock_page_cgroup(pc);
accf163e
KH
2142 }
2143
73045c47 2144 if (unlikely(!mm))
8697d331 2145 mm = &init_mm;
accf163e 2146
c05555b5
KH
2147 if (page_is_file_cache(page))
2148 return mem_cgroup_charge_common(page, mm, gfp_mask,
73045c47 2149 MEM_CGROUP_CHARGE_TYPE_CACHE);
b5a84319 2150
83aae4c7
DN
2151 /* shmem */
2152 if (PageSwapCache(page)) {
73045c47
DN
2153 struct mem_cgroup *mem = NULL;
2154
83aae4c7
DN
2155 ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
2156 if (!ret)
2157 __mem_cgroup_commit_charge_swapin(page, mem,
2158 MEM_CGROUP_CHARGE_TYPE_SHMEM);
2159 } else
2160 ret = mem_cgroup_charge_common(page, mm, gfp_mask,
73045c47 2161 MEM_CGROUP_CHARGE_TYPE_SHMEM);
b5a84319 2162
b5a84319 2163 return ret;
e8589cc1
KH
2164}
2165
54595fe2
KH
2166/*
2167 * While swap-in, try_charge -> commit or cancel, the page is locked.
2168 * And when try_charge() successfully returns, one refcnt to memcg without
21ae2956 2169 * struct page_cgroup is acquired. This refcnt will be consumed by
54595fe2
KH
2170 * "commit()" or removed by "cancel()"
2171 */
8c7c6e34
KH
2172int mem_cgroup_try_charge_swapin(struct mm_struct *mm,
2173 struct page *page,
2174 gfp_t mask, struct mem_cgroup **ptr)
2175{
2176 struct mem_cgroup *mem;
54595fe2 2177 int ret;
8c7c6e34 2178
f8d66542 2179 if (mem_cgroup_disabled())
8c7c6e34
KH
2180 return 0;
2181
2182 if (!do_swap_account)
2183 goto charge_cur_mm;
8c7c6e34
KH
2184 /*
2185 * A racing thread's fault, or swapoff, may have already updated
407f9c8b
HD
2186 * the pte, and even removed page from swap cache: in those cases
2187 * do_swap_page()'s pte_same() test will fail; but there's also a
2188 * KSM case which does need to charge the page.
8c7c6e34
KH
2189 */
2190 if (!PageSwapCache(page))
407f9c8b 2191 goto charge_cur_mm;
e42d9d5d 2192 mem = try_get_mem_cgroup_from_page(page);
54595fe2
KH
2193 if (!mem)
2194 goto charge_cur_mm;
8c7c6e34 2195 *ptr = mem;
430e4863 2196 ret = __mem_cgroup_try_charge(NULL, mask, ptr, true);
54595fe2
KH
2197 css_put(&mem->css);
2198 return ret;
8c7c6e34
KH
2199charge_cur_mm:
2200 if (unlikely(!mm))
2201 mm = &init_mm;
430e4863 2202 return __mem_cgroup_try_charge(mm, mask, ptr, true);
8c7c6e34
KH
2203}
2204
83aae4c7
DN
2205static void
2206__mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
2207 enum charge_type ctype)
7a81b88c
KH
2208{
2209 struct page_cgroup *pc;
2210
f8d66542 2211 if (mem_cgroup_disabled())
7a81b88c
KH
2212 return;
2213 if (!ptr)
2214 return;
88703267 2215 cgroup_exclude_rmdir(&ptr->css);
7a81b88c 2216 pc = lookup_page_cgroup(page);
544122e5 2217 mem_cgroup_lru_del_before_commit_swapcache(page);
83aae4c7 2218 __mem_cgroup_commit_charge(ptr, pc, ctype);
544122e5 2219 mem_cgroup_lru_add_after_commit_swapcache(page);
8c7c6e34
KH
2220 /*
2221 * Now swap is on-memory. This means this page may be
2222 * counted both as mem and swap....double count.
03f3c433
KH
2223 * Fix it by uncharging from memsw. Basically, this SwapCache is stable
2224 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
2225 * may call delete_from_swap_cache() before reach here.
8c7c6e34 2226 */
03f3c433 2227 if (do_swap_account && PageSwapCache(page)) {
8c7c6e34 2228 swp_entry_t ent = {.val = page_private(page)};
a3b2d692 2229 unsigned short id;
8c7c6e34 2230 struct mem_cgroup *memcg;
a3b2d692
KH
2231
2232 id = swap_cgroup_record(ent, 0);
2233 rcu_read_lock();
2234 memcg = mem_cgroup_lookup(id);
8c7c6e34 2235 if (memcg) {
a3b2d692
KH
2236 /*
2237 * This recorded memcg can be obsolete one. So, avoid
2238 * calling css_tryget
2239 */
0c3e73e8 2240 if (!mem_cgroup_is_root(memcg))
4e649152 2241 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
0c3e73e8 2242 mem_cgroup_swap_statistics(memcg, false);
8c7c6e34
KH
2243 mem_cgroup_put(memcg);
2244 }
a3b2d692 2245 rcu_read_unlock();
8c7c6e34 2246 }
88703267
KH
2247 /*
2248 * At swapin, we may charge account against cgroup which has no tasks.
2249 * So, rmdir()->pre_destroy() can be called while we do this charge.
2250 * In that case, we need to call pre_destroy() again. check it here.
2251 */
2252 cgroup_release_and_wakeup_rmdir(&ptr->css);
7a81b88c
KH
2253}
2254
83aae4c7
DN
2255void mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr)
2256{
2257 __mem_cgroup_commit_charge_swapin(page, ptr,
2258 MEM_CGROUP_CHARGE_TYPE_MAPPED);
2259}
2260
7a81b88c
KH
2261void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *mem)
2262{
f8d66542 2263 if (mem_cgroup_disabled())
7a81b88c
KH
2264 return;
2265 if (!mem)
2266 return;
a3032a2c 2267 mem_cgroup_cancel_charge(mem);
7a81b88c
KH
2268}
2269
569b846d
KH
2270static void
2271__do_uncharge(struct mem_cgroup *mem, const enum charge_type ctype)
2272{
2273 struct memcg_batch_info *batch = NULL;
2274 bool uncharge_memsw = true;
2275 /* If swapout, usage of swap doesn't decrease */
2276 if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2277 uncharge_memsw = false;
569b846d
KH
2278
2279 batch = &current->memcg_batch;
2280 /*
2281 * In usual, we do css_get() when we remember memcg pointer.
2282 * But in this case, we keep res->usage until end of a series of
2283 * uncharges. Then, it's ok to ignore memcg's refcnt.
2284 */
2285 if (!batch->memcg)
2286 batch->memcg = mem;
3c11ecf4
KH
2287 /*
2288 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
2289 * In those cases, all pages freed continously can be expected to be in
2290 * the same cgroup and we have chance to coalesce uncharges.
2291 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
2292 * because we want to do uncharge as soon as possible.
2293 */
2294
2295 if (!batch->do_batch || test_thread_flag(TIF_MEMDIE))
2296 goto direct_uncharge;
2297
569b846d
KH
2298 /*
2299 * In typical case, batch->memcg == mem. This means we can
2300 * merge a series of uncharges to an uncharge of res_counter.
2301 * If not, we uncharge res_counter ony by one.
2302 */
2303 if (batch->memcg != mem)
2304 goto direct_uncharge;
2305 /* remember freed charge and uncharge it later */
2306 batch->bytes += PAGE_SIZE;
2307 if (uncharge_memsw)
2308 batch->memsw_bytes += PAGE_SIZE;
2309 return;
2310direct_uncharge:
2311 res_counter_uncharge(&mem->res, PAGE_SIZE);
2312 if (uncharge_memsw)
2313 res_counter_uncharge(&mem->memsw, PAGE_SIZE);
3c11ecf4
KH
2314 if (unlikely(batch->memcg != mem))
2315 memcg_oom_recover(mem);
569b846d
KH
2316 return;
2317}
7a81b88c 2318
8a9f3ccd 2319/*
69029cd5 2320 * uncharge if !page_mapped(page)
8a9f3ccd 2321 */
8c7c6e34 2322static struct mem_cgroup *
69029cd5 2323__mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype)
8a9f3ccd 2324{
8289546e 2325 struct page_cgroup *pc;
8c7c6e34 2326 struct mem_cgroup *mem = NULL;
8a9f3ccd 2327
f8d66542 2328 if (mem_cgroup_disabled())
8c7c6e34 2329 return NULL;
4077960e 2330
d13d1443 2331 if (PageSwapCache(page))
8c7c6e34 2332 return NULL;
d13d1443 2333
8697d331 2334 /*
3c541e14 2335 * Check if our page_cgroup is valid
8697d331 2336 */
52d4b9ac
KH
2337 pc = lookup_page_cgroup(page);
2338 if (unlikely(!pc || !PageCgroupUsed(pc)))
8c7c6e34 2339 return NULL;
b9c565d5 2340
52d4b9ac 2341 lock_page_cgroup(pc);
d13d1443 2342
8c7c6e34
KH
2343 mem = pc->mem_cgroup;
2344
d13d1443
KH
2345 if (!PageCgroupUsed(pc))
2346 goto unlock_out;
2347
2348 switch (ctype) {
2349 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
8a9478ca 2350 case MEM_CGROUP_CHARGE_TYPE_DROP:
ac39cf8c 2351 /* See mem_cgroup_prepare_migration() */
2352 if (page_mapped(page) || PageCgroupMigration(pc))
d13d1443
KH
2353 goto unlock_out;
2354 break;
2355 case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
2356 if (!PageAnon(page)) { /* Shared memory */
2357 if (page->mapping && !page_is_file_cache(page))
2358 goto unlock_out;
2359 } else if (page_mapped(page)) /* Anon */
2360 goto unlock_out;
2361 break;
2362 default:
2363 break;
52d4b9ac 2364 }
d13d1443 2365
08e552c6 2366 mem_cgroup_charge_statistics(mem, pc, false);
04046e1a 2367
52d4b9ac 2368 ClearPageCgroupUsed(pc);
544122e5
KH
2369 /*
2370 * pc->mem_cgroup is not cleared here. It will be accessed when it's
2371 * freed from LRU. This is safe because uncharged page is expected not
2372 * to be reused (freed soon). Exception is SwapCache, it's handled by
2373 * special functions.
2374 */
b9c565d5 2375
52d4b9ac 2376 unlock_page_cgroup(pc);
f75ca962
KH
2377 /*
2378 * even after unlock, we have mem->res.usage here and this memcg
2379 * will never be freed.
2380 */
d2265e6f 2381 memcg_check_events(mem, page);
f75ca962
KH
2382 if (do_swap_account && ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT) {
2383 mem_cgroup_swap_statistics(mem, true);
2384 mem_cgroup_get(mem);
2385 }
2386 if (!mem_cgroup_is_root(mem))
2387 __do_uncharge(mem, ctype);
6d12e2d8 2388
8c7c6e34 2389 return mem;
d13d1443
KH
2390
2391unlock_out:
2392 unlock_page_cgroup(pc);
8c7c6e34 2393 return NULL;
3c541e14
BS
2394}
2395
69029cd5
KH
2396void mem_cgroup_uncharge_page(struct page *page)
2397{
52d4b9ac
KH
2398 /* early check. */
2399 if (page_mapped(page))
2400 return;
2401 if (page->mapping && !PageAnon(page))
2402 return;
69029cd5
KH
2403 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_MAPPED);
2404}
2405
2406void mem_cgroup_uncharge_cache_page(struct page *page)
2407{
2408 VM_BUG_ON(page_mapped(page));
b7abea96 2409 VM_BUG_ON(page->mapping);
69029cd5
KH
2410 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE);
2411}
2412
569b846d
KH
2413/*
2414 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
2415 * In that cases, pages are freed continuously and we can expect pages
2416 * are in the same memcg. All these calls itself limits the number of
2417 * pages freed at once, then uncharge_start/end() is called properly.
2418 * This may be called prural(2) times in a context,
2419 */
2420
2421void mem_cgroup_uncharge_start(void)
2422{
2423 current->memcg_batch.do_batch++;
2424 /* We can do nest. */
2425 if (current->memcg_batch.do_batch == 1) {
2426 current->memcg_batch.memcg = NULL;
2427 current->memcg_batch.bytes = 0;
2428 current->memcg_batch.memsw_bytes = 0;
2429 }
2430}
2431
2432void mem_cgroup_uncharge_end(void)
2433{
2434 struct memcg_batch_info *batch = &current->memcg_batch;
2435
2436 if (!batch->do_batch)
2437 return;
2438
2439 batch->do_batch--;
2440 if (batch->do_batch) /* If stacked, do nothing. */
2441 return;
2442
2443 if (!batch->memcg)
2444 return;
2445 /*
2446 * This "batch->memcg" is valid without any css_get/put etc...
2447 * bacause we hide charges behind us.
2448 */
2449 if (batch->bytes)
2450 res_counter_uncharge(&batch->memcg->res, batch->bytes);
2451 if (batch->memsw_bytes)
2452 res_counter_uncharge(&batch->memcg->memsw, batch->memsw_bytes);
3c11ecf4 2453 memcg_oom_recover(batch->memcg);
569b846d
KH
2454 /* forget this pointer (for sanity check) */
2455 batch->memcg = NULL;
2456}
2457
e767e056 2458#ifdef CONFIG_SWAP
8c7c6e34 2459/*
e767e056 2460 * called after __delete_from_swap_cache() and drop "page" account.
8c7c6e34
KH
2461 * memcg information is recorded to swap_cgroup of "ent"
2462 */
8a9478ca
KH
2463void
2464mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
8c7c6e34
KH
2465{
2466 struct mem_cgroup *memcg;
8a9478ca
KH
2467 int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
2468
2469 if (!swapout) /* this was a swap cache but the swap is unused ! */
2470 ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
2471
2472 memcg = __mem_cgroup_uncharge_common(page, ctype);
8c7c6e34 2473
f75ca962
KH
2474 /*
2475 * record memcg information, if swapout && memcg != NULL,
2476 * mem_cgroup_get() was called in uncharge().
2477 */
2478 if (do_swap_account && swapout && memcg)
a3b2d692 2479 swap_cgroup_record(ent, css_id(&memcg->css));
8c7c6e34 2480}
e767e056 2481#endif
8c7c6e34
KH
2482
2483#ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
2484/*
2485 * called from swap_entry_free(). remove record in swap_cgroup and
2486 * uncharge "memsw" account.
2487 */
2488void mem_cgroup_uncharge_swap(swp_entry_t ent)
d13d1443 2489{
8c7c6e34 2490 struct mem_cgroup *memcg;
a3b2d692 2491 unsigned short id;
8c7c6e34
KH
2492
2493 if (!do_swap_account)
2494 return;
2495
a3b2d692
KH
2496 id = swap_cgroup_record(ent, 0);
2497 rcu_read_lock();
2498 memcg = mem_cgroup_lookup(id);
8c7c6e34 2499 if (memcg) {
a3b2d692
KH
2500 /*
2501 * We uncharge this because swap is freed.
2502 * This memcg can be obsolete one. We avoid calling css_tryget
2503 */
0c3e73e8 2504 if (!mem_cgroup_is_root(memcg))
4e649152 2505 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
0c3e73e8 2506 mem_cgroup_swap_statistics(memcg, false);
8c7c6e34
KH
2507 mem_cgroup_put(memcg);
2508 }
a3b2d692 2509 rcu_read_unlock();
d13d1443 2510}
02491447
DN
2511
2512/**
2513 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
2514 * @entry: swap entry to be moved
2515 * @from: mem_cgroup which the entry is moved from
2516 * @to: mem_cgroup which the entry is moved to
483c30b5 2517 * @need_fixup: whether we should fixup res_counters and refcounts.
02491447
DN
2518 *
2519 * It succeeds only when the swap_cgroup's record for this entry is the same
2520 * as the mem_cgroup's id of @from.
2521 *
2522 * Returns 0 on success, -EINVAL on failure.
2523 *
2524 * The caller must have charged to @to, IOW, called res_counter_charge() about
2525 * both res and memsw, and called css_get().
2526 */
2527static int mem_cgroup_move_swap_account(swp_entry_t entry,
483c30b5 2528 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
02491447
DN
2529{
2530 unsigned short old_id, new_id;
2531
2532 old_id = css_id(&from->css);
2533 new_id = css_id(&to->css);
2534
2535 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
02491447 2536 mem_cgroup_swap_statistics(from, false);
483c30b5 2537 mem_cgroup_swap_statistics(to, true);
02491447 2538 /*
483c30b5
DN
2539 * This function is only called from task migration context now.
2540 * It postpones res_counter and refcount handling till the end
2541 * of task migration(mem_cgroup_clear_mc()) for performance
2542 * improvement. But we cannot postpone mem_cgroup_get(to)
2543 * because if the process that has been moved to @to does
2544 * swap-in, the refcount of @to might be decreased to 0.
02491447 2545 */
02491447 2546 mem_cgroup_get(to);
483c30b5
DN
2547 if (need_fixup) {
2548 if (!mem_cgroup_is_root(from))
2549 res_counter_uncharge(&from->memsw, PAGE_SIZE);
2550 mem_cgroup_put(from);
2551 /*
2552 * we charged both to->res and to->memsw, so we should
2553 * uncharge to->res.
2554 */
2555 if (!mem_cgroup_is_root(to))
2556 res_counter_uncharge(&to->res, PAGE_SIZE);
483c30b5 2557 }
02491447
DN
2558 return 0;
2559 }
2560 return -EINVAL;
2561}
2562#else
2563static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
483c30b5 2564 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
02491447
DN
2565{
2566 return -EINVAL;
2567}
8c7c6e34 2568#endif
d13d1443 2569
ae41be37 2570/*
01b1ae63
KH
2571 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
2572 * page belongs to.
ae41be37 2573 */
ac39cf8c 2574int mem_cgroup_prepare_migration(struct page *page,
2575 struct page *newpage, struct mem_cgroup **ptr)
ae41be37
KH
2576{
2577 struct page_cgroup *pc;
e8589cc1 2578 struct mem_cgroup *mem = NULL;
ac39cf8c 2579 enum charge_type ctype;
e8589cc1 2580 int ret = 0;
8869b8f6 2581
f8d66542 2582 if (mem_cgroup_disabled())
4077960e
BS
2583 return 0;
2584
52d4b9ac
KH
2585 pc = lookup_page_cgroup(page);
2586 lock_page_cgroup(pc);
2587 if (PageCgroupUsed(pc)) {
e8589cc1
KH
2588 mem = pc->mem_cgroup;
2589 css_get(&mem->css);
ac39cf8c 2590 /*
2591 * At migrating an anonymous page, its mapcount goes down
2592 * to 0 and uncharge() will be called. But, even if it's fully
2593 * unmapped, migration may fail and this page has to be
2594 * charged again. We set MIGRATION flag here and delay uncharge
2595 * until end_migration() is called
2596 *
2597 * Corner Case Thinking
2598 * A)
2599 * When the old page was mapped as Anon and it's unmap-and-freed
2600 * while migration was ongoing.
2601 * If unmap finds the old page, uncharge() of it will be delayed
2602 * until end_migration(). If unmap finds a new page, it's
2603 * uncharged when it make mapcount to be 1->0. If unmap code
2604 * finds swap_migration_entry, the new page will not be mapped
2605 * and end_migration() will find it(mapcount==0).
2606 *
2607 * B)
2608 * When the old page was mapped but migraion fails, the kernel
2609 * remaps it. A charge for it is kept by MIGRATION flag even
2610 * if mapcount goes down to 0. We can do remap successfully
2611 * without charging it again.
2612 *
2613 * C)
2614 * The "old" page is under lock_page() until the end of
2615 * migration, so, the old page itself will not be swapped-out.
2616 * If the new page is swapped out before end_migraton, our
2617 * hook to usual swap-out path will catch the event.
2618 */
2619 if (PageAnon(page))
2620 SetPageCgroupMigration(pc);
e8589cc1 2621 }
52d4b9ac 2622 unlock_page_cgroup(pc);
ac39cf8c 2623 /*
2624 * If the page is not charged at this point,
2625 * we return here.
2626 */
2627 if (!mem)
2628 return 0;
01b1ae63 2629
93d5c9be 2630 *ptr = mem;
ac39cf8c 2631 ret = __mem_cgroup_try_charge(NULL, GFP_KERNEL, ptr, false);
2632 css_put(&mem->css);/* drop extra refcnt */
2633 if (ret || *ptr == NULL) {
2634 if (PageAnon(page)) {
2635 lock_page_cgroup(pc);
2636 ClearPageCgroupMigration(pc);
2637 unlock_page_cgroup(pc);
2638 /*
2639 * The old page may be fully unmapped while we kept it.
2640 */
2641 mem_cgroup_uncharge_page(page);
2642 }
2643 return -ENOMEM;
e8589cc1 2644 }
ac39cf8c 2645 /*
2646 * We charge new page before it's used/mapped. So, even if unlock_page()
2647 * is called before end_migration, we can catch all events on this new
2648 * page. In the case new page is migrated but not remapped, new page's
2649 * mapcount will be finally 0 and we call uncharge in end_migration().
2650 */
2651 pc = lookup_page_cgroup(newpage);
2652 if (PageAnon(page))
2653 ctype = MEM_CGROUP_CHARGE_TYPE_MAPPED;
2654 else if (page_is_file_cache(page))
2655 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
2656 else
2657 ctype = MEM_CGROUP_CHARGE_TYPE_SHMEM;
2658 __mem_cgroup_commit_charge(mem, pc, ctype);
e8589cc1 2659 return ret;
ae41be37 2660}
8869b8f6 2661
69029cd5 2662/* remove redundant charge if migration failed*/
01b1ae63 2663void mem_cgroup_end_migration(struct mem_cgroup *mem,
ac39cf8c 2664 struct page *oldpage, struct page *newpage)
ae41be37 2665{
ac39cf8c 2666 struct page *used, *unused;
01b1ae63 2667 struct page_cgroup *pc;
01b1ae63
KH
2668
2669 if (!mem)
2670 return;
ac39cf8c 2671 /* blocks rmdir() */
88703267 2672 cgroup_exclude_rmdir(&mem->css);
01b1ae63
KH
2673 /* at migration success, oldpage->mapping is NULL. */
2674 if (oldpage->mapping) {
ac39cf8c 2675 used = oldpage;
2676 unused = newpage;
01b1ae63 2677 } else {
ac39cf8c 2678 used = newpage;
01b1ae63
KH
2679 unused = oldpage;
2680 }
69029cd5 2681 /*
ac39cf8c 2682 * We disallowed uncharge of pages under migration because mapcount
2683 * of the page goes down to zero, temporarly.
2684 * Clear the flag and check the page should be charged.
01b1ae63 2685 */
ac39cf8c 2686 pc = lookup_page_cgroup(oldpage);
2687 lock_page_cgroup(pc);
2688 ClearPageCgroupMigration(pc);
2689 unlock_page_cgroup(pc);
01b1ae63 2690
ac39cf8c 2691 __mem_cgroup_uncharge_common(unused, MEM_CGROUP_CHARGE_TYPE_FORCE);
2692
01b1ae63 2693 /*
ac39cf8c 2694 * If a page is a file cache, radix-tree replacement is very atomic
2695 * and we can skip this check. When it was an Anon page, its mapcount
2696 * goes down to 0. But because we added MIGRATION flage, it's not
2697 * uncharged yet. There are several case but page->mapcount check
2698 * and USED bit check in mem_cgroup_uncharge_page() will do enough
2699 * check. (see prepare_charge() also)
69029cd5 2700 */
ac39cf8c 2701 if (PageAnon(used))
2702 mem_cgroup_uncharge_page(used);
88703267 2703 /*
ac39cf8c 2704 * At migration, we may charge account against cgroup which has no
2705 * tasks.
88703267
KH
2706 * So, rmdir()->pre_destroy() can be called while we do this charge.
2707 * In that case, we need to call pre_destroy() again. check it here.
2708 */
2709 cgroup_release_and_wakeup_rmdir(&mem->css);
ae41be37 2710}
78fb7466 2711
c9b0ed51 2712/*
ae3abae6
DN
2713 * A call to try to shrink memory usage on charge failure at shmem's swapin.
2714 * Calling hierarchical_reclaim is not enough because we should update
2715 * last_oom_jiffies to prevent pagefault_out_of_memory from invoking global OOM.
2716 * Moreover considering hierarchy, we should reclaim from the mem_over_limit,
2717 * not from the memcg which this page would be charged to.
2718 * try_charge_swapin does all of these works properly.
c9b0ed51 2719 */
ae3abae6 2720int mem_cgroup_shmem_charge_fallback(struct page *page,
b5a84319
KH
2721 struct mm_struct *mm,
2722 gfp_t gfp_mask)
c9b0ed51 2723{
b5a84319 2724 struct mem_cgroup *mem = NULL;
ae3abae6 2725 int ret;
c9b0ed51 2726
f8d66542 2727 if (mem_cgroup_disabled())
cede86ac 2728 return 0;
c9b0ed51 2729
ae3abae6
DN
2730 ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
2731 if (!ret)
2732 mem_cgroup_cancel_charge_swapin(mem); /* it does !mem check */
c9b0ed51 2733
ae3abae6 2734 return ret;
c9b0ed51
KH
2735}
2736
8c7c6e34
KH
2737static DEFINE_MUTEX(set_limit_mutex);
2738
d38d2a75 2739static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
8c7c6e34 2740 unsigned long long val)
628f4235 2741{
81d39c20 2742 int retry_count;
3c11ecf4 2743 u64 memswlimit, memlimit;
628f4235 2744 int ret = 0;
81d39c20
KH
2745 int children = mem_cgroup_count_children(memcg);
2746 u64 curusage, oldusage;
3c11ecf4 2747 int enlarge;
81d39c20
KH
2748
2749 /*
2750 * For keeping hierarchical_reclaim simple, how long we should retry
2751 * is depends on callers. We set our retry-count to be function
2752 * of # of children which we should visit in this loop.
2753 */
2754 retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
2755
2756 oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
628f4235 2757
3c11ecf4 2758 enlarge = 0;
8c7c6e34 2759 while (retry_count) {
628f4235
KH
2760 if (signal_pending(current)) {
2761 ret = -EINTR;
2762 break;
2763 }
8c7c6e34
KH
2764 /*
2765 * Rather than hide all in some function, I do this in
2766 * open coded manner. You see what this really does.
2767 * We have to guarantee mem->res.limit < mem->memsw.limit.
2768 */
2769 mutex_lock(&set_limit_mutex);
2770 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
2771 if (memswlimit < val) {
2772 ret = -EINVAL;
2773 mutex_unlock(&set_limit_mutex);
628f4235
KH
2774 break;
2775 }
3c11ecf4
KH
2776
2777 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
2778 if (memlimit < val)
2779 enlarge = 1;
2780
8c7c6e34 2781 ret = res_counter_set_limit(&memcg->res, val);
22a668d7
KH
2782 if (!ret) {
2783 if (memswlimit == val)
2784 memcg->memsw_is_minimum = true;
2785 else
2786 memcg->memsw_is_minimum = false;
2787 }
8c7c6e34
KH
2788 mutex_unlock(&set_limit_mutex);
2789
2790 if (!ret)
2791 break;
2792
aa20d489 2793 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
4e416953 2794 MEM_CGROUP_RECLAIM_SHRINK);
81d39c20
KH
2795 curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
2796 /* Usage is reduced ? */
2797 if (curusage >= oldusage)
2798 retry_count--;
2799 else
2800 oldusage = curusage;
8c7c6e34 2801 }
3c11ecf4
KH
2802 if (!ret && enlarge)
2803 memcg_oom_recover(memcg);
14797e23 2804
8c7c6e34
KH
2805 return ret;
2806}
2807
338c8431
LZ
2808static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
2809 unsigned long long val)
8c7c6e34 2810{
81d39c20 2811 int retry_count;
3c11ecf4 2812 u64 memlimit, memswlimit, oldusage, curusage;
81d39c20
KH
2813 int children = mem_cgroup_count_children(memcg);
2814 int ret = -EBUSY;
3c11ecf4 2815 int enlarge = 0;
8c7c6e34 2816
81d39c20
KH
2817 /* see mem_cgroup_resize_res_limit */
2818 retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
2819 oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
8c7c6e34
KH
2820 while (retry_count) {
2821 if (signal_pending(current)) {
2822 ret = -EINTR;
2823 break;
2824 }
2825 /*
2826 * Rather than hide all in some function, I do this in
2827 * open coded manner. You see what this really does.
2828 * We have to guarantee mem->res.limit < mem->memsw.limit.
2829 */
2830 mutex_lock(&set_limit_mutex);
2831 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
2832 if (memlimit > val) {
2833 ret = -EINVAL;
2834 mutex_unlock(&set_limit_mutex);
2835 break;
2836 }
3c11ecf4
KH
2837 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
2838 if (memswlimit < val)
2839 enlarge = 1;
8c7c6e34 2840 ret = res_counter_set_limit(&memcg->memsw, val);
22a668d7
KH
2841 if (!ret) {
2842 if (memlimit == val)
2843 memcg->memsw_is_minimum = true;
2844 else
2845 memcg->memsw_is_minimum = false;
2846 }
8c7c6e34
KH
2847 mutex_unlock(&set_limit_mutex);
2848
2849 if (!ret)
2850 break;
2851
4e416953 2852 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
75822b44
BS
2853 MEM_CGROUP_RECLAIM_NOSWAP |
2854 MEM_CGROUP_RECLAIM_SHRINK);
8c7c6e34 2855 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
81d39c20 2856 /* Usage is reduced ? */
8c7c6e34 2857 if (curusage >= oldusage)
628f4235 2858 retry_count--;
81d39c20
KH
2859 else
2860 oldusage = curusage;
628f4235 2861 }
3c11ecf4
KH
2862 if (!ret && enlarge)
2863 memcg_oom_recover(memcg);
628f4235
KH
2864 return ret;
2865}
2866
4e416953
BS
2867unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
2868 gfp_t gfp_mask, int nid,
2869 int zid)
2870{
2871 unsigned long nr_reclaimed = 0;
2872 struct mem_cgroup_per_zone *mz, *next_mz = NULL;
2873 unsigned long reclaimed;
2874 int loop = 0;
2875 struct mem_cgroup_tree_per_zone *mctz;
ef8745c1 2876 unsigned long long excess;
4e416953
BS
2877
2878 if (order > 0)
2879 return 0;
2880
2881 mctz = soft_limit_tree_node_zone(nid, zid);
2882 /*
2883 * This loop can run a while, specially if mem_cgroup's continuously
2884 * keep exceeding their soft limit and putting the system under
2885 * pressure
2886 */
2887 do {
2888 if (next_mz)
2889 mz = next_mz;
2890 else
2891 mz = mem_cgroup_largest_soft_limit_node(mctz);
2892 if (!mz)
2893 break;
2894
2895 reclaimed = mem_cgroup_hierarchical_reclaim(mz->mem, zone,
2896 gfp_mask,
2897 MEM_CGROUP_RECLAIM_SOFT);
2898 nr_reclaimed += reclaimed;
2899 spin_lock(&mctz->lock);
2900
2901 /*
2902 * If we failed to reclaim anything from this memory cgroup
2903 * it is time to move on to the next cgroup
2904 */
2905 next_mz = NULL;
2906 if (!reclaimed) {
2907 do {
2908 /*
2909 * Loop until we find yet another one.
2910 *
2911 * By the time we get the soft_limit lock
2912 * again, someone might have aded the
2913 * group back on the RB tree. Iterate to
2914 * make sure we get a different mem.
2915 * mem_cgroup_largest_soft_limit_node returns
2916 * NULL if no other cgroup is present on
2917 * the tree
2918 */
2919 next_mz =
2920 __mem_cgroup_largest_soft_limit_node(mctz);
2921 if (next_mz == mz) {
2922 css_put(&next_mz->mem->css);
2923 next_mz = NULL;
2924 } else /* next_mz == NULL or other memcg */
2925 break;
2926 } while (1);
2927 }
4e416953 2928 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
ef8745c1 2929 excess = res_counter_soft_limit_excess(&mz->mem->res);
4e416953
BS
2930 /*
2931 * One school of thought says that we should not add
2932 * back the node to the tree if reclaim returns 0.
2933 * But our reclaim could return 0, simply because due
2934 * to priority we are exposing a smaller subset of
2935 * memory to reclaim from. Consider this as a longer
2936 * term TODO.
2937 */
ef8745c1
KH
2938 /* If excess == 0, no tree ops */
2939 __mem_cgroup_insert_exceeded(mz->mem, mz, mctz, excess);
4e416953
BS
2940 spin_unlock(&mctz->lock);
2941 css_put(&mz->mem->css);
2942 loop++;
2943 /*
2944 * Could not reclaim anything and there are no more
2945 * mem cgroups to try or we seem to be looping without
2946 * reclaiming anything.
2947 */
2948 if (!nr_reclaimed &&
2949 (next_mz == NULL ||
2950 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
2951 break;
2952 } while (!nr_reclaimed);
2953 if (next_mz)
2954 css_put(&next_mz->mem->css);
2955 return nr_reclaimed;
2956}
2957
cc847582
KH
2958/*
2959 * This routine traverse page_cgroup in given list and drop them all.
cc847582
KH
2960 * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
2961 */
f817ed48 2962static int mem_cgroup_force_empty_list(struct mem_cgroup *mem,
08e552c6 2963 int node, int zid, enum lru_list lru)
cc847582 2964{
08e552c6
KH
2965 struct zone *zone;
2966 struct mem_cgroup_per_zone *mz;
f817ed48 2967 struct page_cgroup *pc, *busy;
08e552c6 2968 unsigned long flags, loop;
072c56c1 2969 struct list_head *list;
f817ed48 2970 int ret = 0;
072c56c1 2971
08e552c6
KH
2972 zone = &NODE_DATA(node)->node_zones[zid];
2973 mz = mem_cgroup_zoneinfo(mem, node, zid);
b69408e8 2974 list = &mz->lists[lru];
cc847582 2975
f817ed48
KH
2976 loop = MEM_CGROUP_ZSTAT(mz, lru);
2977 /* give some margin against EBUSY etc...*/
2978 loop += 256;
2979 busy = NULL;
2980 while (loop--) {
2981 ret = 0;
08e552c6 2982 spin_lock_irqsave(&zone->lru_lock, flags);
f817ed48 2983 if (list_empty(list)) {
08e552c6 2984 spin_unlock_irqrestore(&zone->lru_lock, flags);
52d4b9ac 2985 break;
f817ed48
KH
2986 }
2987 pc = list_entry(list->prev, struct page_cgroup, lru);
2988 if (busy == pc) {
2989 list_move(&pc->lru, list);
648bcc77 2990 busy = NULL;
08e552c6 2991 spin_unlock_irqrestore(&zone->lru_lock, flags);
f817ed48
KH
2992 continue;
2993 }
08e552c6 2994 spin_unlock_irqrestore(&zone->lru_lock, flags);
f817ed48 2995
2c26fdd7 2996 ret = mem_cgroup_move_parent(pc, mem, GFP_KERNEL);
f817ed48 2997 if (ret == -ENOMEM)
52d4b9ac 2998 break;
f817ed48
KH
2999
3000 if (ret == -EBUSY || ret == -EINVAL) {
3001 /* found lock contention or "pc" is obsolete. */
3002 busy = pc;
3003 cond_resched();
3004 } else
3005 busy = NULL;
cc847582 3006 }
08e552c6 3007
f817ed48
KH
3008 if (!ret && !list_empty(list))
3009 return -EBUSY;
3010 return ret;
cc847582
KH
3011}
3012
3013/*
3014 * make mem_cgroup's charge to be 0 if there is no task.
3015 * This enables deleting this mem_cgroup.
3016 */
c1e862c1 3017static int mem_cgroup_force_empty(struct mem_cgroup *mem, bool free_all)
cc847582 3018{
f817ed48
KH
3019 int ret;
3020 int node, zid, shrink;
3021 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
c1e862c1 3022 struct cgroup *cgrp = mem->css.cgroup;
8869b8f6 3023
cc847582 3024 css_get(&mem->css);
f817ed48
KH
3025
3026 shrink = 0;
c1e862c1
KH
3027 /* should free all ? */
3028 if (free_all)
3029 goto try_to_free;
f817ed48 3030move_account:
fce66477 3031 do {
f817ed48 3032 ret = -EBUSY;
c1e862c1
KH
3033 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
3034 goto out;
3035 ret = -EINTR;
3036 if (signal_pending(current))
cc847582 3037 goto out;
52d4b9ac
KH
3038 /* This is for making all *used* pages to be on LRU. */
3039 lru_add_drain_all();
cdec2e42 3040 drain_all_stock_sync();
f817ed48 3041 ret = 0;
299b4eaa 3042 for_each_node_state(node, N_HIGH_MEMORY) {
f817ed48 3043 for (zid = 0; !ret && zid < MAX_NR_ZONES; zid++) {
b69408e8 3044 enum lru_list l;
f817ed48
KH
3045 for_each_lru(l) {
3046 ret = mem_cgroup_force_empty_list(mem,
08e552c6 3047 node, zid, l);
f817ed48
KH
3048 if (ret)
3049 break;
3050 }
1ecaab2b 3051 }
f817ed48
KH
3052 if (ret)
3053 break;
3054 }
3c11ecf4 3055 memcg_oom_recover(mem);
f817ed48
KH
3056 /* it seems parent cgroup doesn't have enough mem */
3057 if (ret == -ENOMEM)
3058 goto try_to_free;
52d4b9ac 3059 cond_resched();
fce66477
DN
3060 /* "ret" should also be checked to ensure all lists are empty. */
3061 } while (mem->res.usage > 0 || ret);
cc847582
KH
3062out:
3063 css_put(&mem->css);
3064 return ret;
f817ed48
KH
3065
3066try_to_free:
c1e862c1
KH
3067 /* returns EBUSY if there is a task or if we come here twice. */
3068 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children) || shrink) {
f817ed48
KH
3069 ret = -EBUSY;
3070 goto out;
3071 }
c1e862c1
KH
3072 /* we call try-to-free pages for make this cgroup empty */
3073 lru_add_drain_all();
f817ed48
KH
3074 /* try to free all pages in this cgroup */
3075 shrink = 1;
3076 while (nr_retries && mem->res.usage > 0) {
3077 int progress;
c1e862c1
KH
3078
3079 if (signal_pending(current)) {
3080 ret = -EINTR;
3081 goto out;
3082 }
a7885eb8
KM
3083 progress = try_to_free_mem_cgroup_pages(mem, GFP_KERNEL,
3084 false, get_swappiness(mem));
c1e862c1 3085 if (!progress) {
f817ed48 3086 nr_retries--;
c1e862c1 3087 /* maybe some writeback is necessary */
8aa7e847 3088 congestion_wait(BLK_RW_ASYNC, HZ/10);
c1e862c1 3089 }
f817ed48
KH
3090
3091 }
08e552c6 3092 lru_add_drain();
f817ed48 3093 /* try move_account...there may be some *locked* pages. */
fce66477 3094 goto move_account;
cc847582
KH
3095}
3096
c1e862c1
KH
3097int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
3098{
3099 return mem_cgroup_force_empty(mem_cgroup_from_cont(cont), true);
3100}
3101
3102
18f59ea7
BS
3103static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
3104{
3105 return mem_cgroup_from_cont(cont)->use_hierarchy;
3106}
3107
3108static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
3109 u64 val)
3110{
3111 int retval = 0;
3112 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
3113 struct cgroup *parent = cont->parent;
3114 struct mem_cgroup *parent_mem = NULL;
3115
3116 if (parent)
3117 parent_mem = mem_cgroup_from_cont(parent);
3118
3119 cgroup_lock();
3120 /*
af901ca1 3121 * If parent's use_hierarchy is set, we can't make any modifications
18f59ea7
BS
3122 * in the child subtrees. If it is unset, then the change can
3123 * occur, provided the current cgroup has no children.
3124 *
3125 * For the root cgroup, parent_mem is NULL, we allow value to be
3126 * set if there are no children.
3127 */
3128 if ((!parent_mem || !parent_mem->use_hierarchy) &&
3129 (val == 1 || val == 0)) {
3130 if (list_empty(&cont->children))
3131 mem->use_hierarchy = val;
3132 else
3133 retval = -EBUSY;
3134 } else
3135 retval = -EINVAL;
3136 cgroup_unlock();
3137
3138 return retval;
3139}
3140
0c3e73e8
BS
3141struct mem_cgroup_idx_data {
3142 s64 val;
3143 enum mem_cgroup_stat_index idx;
3144};
3145
3146static int
3147mem_cgroup_get_idx_stat(struct mem_cgroup *mem, void *data)
3148{
3149 struct mem_cgroup_idx_data *d = data;
c62b1a3b 3150 d->val += mem_cgroup_read_stat(mem, d->idx);
0c3e73e8
BS
3151 return 0;
3152}
3153
3154static void
3155mem_cgroup_get_recursive_idx_stat(struct mem_cgroup *mem,
3156 enum mem_cgroup_stat_index idx, s64 *val)
3157{
3158 struct mem_cgroup_idx_data d;
3159 d.idx = idx;
3160 d.val = 0;
3161 mem_cgroup_walk_tree(mem, &d, mem_cgroup_get_idx_stat);
3162 *val = d.val;
3163}
3164
104f3928
KS
3165static inline u64 mem_cgroup_usage(struct mem_cgroup *mem, bool swap)
3166{
3167 u64 idx_val, val;
3168
3169 if (!mem_cgroup_is_root(mem)) {
3170 if (!swap)
3171 return res_counter_read_u64(&mem->res, RES_USAGE);
3172 else
3173 return res_counter_read_u64(&mem->memsw, RES_USAGE);
3174 }
3175
3176 mem_cgroup_get_recursive_idx_stat(mem, MEM_CGROUP_STAT_CACHE, &idx_val);
3177 val = idx_val;
3178 mem_cgroup_get_recursive_idx_stat(mem, MEM_CGROUP_STAT_RSS, &idx_val);
3179 val += idx_val;
3180
3181 if (swap) {
3182 mem_cgroup_get_recursive_idx_stat(mem,
3183 MEM_CGROUP_STAT_SWAPOUT, &idx_val);
3184 val += idx_val;
3185 }
3186
3187 return val << PAGE_SHIFT;
3188}
3189
2c3daa72 3190static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft)
8cdea7c0 3191{
8c7c6e34 3192 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
104f3928 3193 u64 val;
8c7c6e34
KH
3194 int type, name;
3195
3196 type = MEMFILE_TYPE(cft->private);
3197 name = MEMFILE_ATTR(cft->private);
3198 switch (type) {
3199 case _MEM:
104f3928
KS
3200 if (name == RES_USAGE)
3201 val = mem_cgroup_usage(mem, false);
3202 else
0c3e73e8 3203 val = res_counter_read_u64(&mem->res, name);
8c7c6e34
KH
3204 break;
3205 case _MEMSWAP:
104f3928
KS
3206 if (name == RES_USAGE)
3207 val = mem_cgroup_usage(mem, true);
3208 else
0c3e73e8 3209 val = res_counter_read_u64(&mem->memsw, name);
8c7c6e34
KH
3210 break;
3211 default:
3212 BUG();
3213 break;
3214 }
3215 return val;
8cdea7c0 3216}
628f4235
KH
3217/*
3218 * The user of this function is...
3219 * RES_LIMIT.
3220 */
856c13aa
PM
3221static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
3222 const char *buffer)
8cdea7c0 3223{
628f4235 3224 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
8c7c6e34 3225 int type, name;
628f4235
KH
3226 unsigned long long val;
3227 int ret;
3228
8c7c6e34
KH
3229 type = MEMFILE_TYPE(cft->private);
3230 name = MEMFILE_ATTR(cft->private);
3231 switch (name) {
628f4235 3232 case RES_LIMIT:
4b3bde4c
BS
3233 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3234 ret = -EINVAL;
3235 break;
3236 }
628f4235
KH
3237 /* This function does all necessary parse...reuse it */
3238 ret = res_counter_memparse_write_strategy(buffer, &val);
8c7c6e34
KH
3239 if (ret)
3240 break;
3241 if (type == _MEM)
628f4235 3242 ret = mem_cgroup_resize_limit(memcg, val);
8c7c6e34
KH
3243 else
3244 ret = mem_cgroup_resize_memsw_limit(memcg, val);
628f4235 3245 break;
296c81d8
BS
3246 case RES_SOFT_LIMIT:
3247 ret = res_counter_memparse_write_strategy(buffer, &val);
3248 if (ret)
3249 break;
3250 /*
3251 * For memsw, soft limits are hard to implement in terms
3252 * of semantics, for now, we support soft limits for
3253 * control without swap
3254 */
3255 if (type == _MEM)
3256 ret = res_counter_set_soft_limit(&memcg->res, val);
3257 else
3258 ret = -EINVAL;
3259 break;
628f4235
KH
3260 default:
3261 ret = -EINVAL; /* should be BUG() ? */
3262 break;
3263 }
3264 return ret;
8cdea7c0
BS
3265}
3266
fee7b548
KH
3267static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
3268 unsigned long long *mem_limit, unsigned long long *memsw_limit)
3269{
3270 struct cgroup *cgroup;
3271 unsigned long long min_limit, min_memsw_limit, tmp;
3272
3273 min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3274 min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3275 cgroup = memcg->css.cgroup;
3276 if (!memcg->use_hierarchy)
3277 goto out;
3278
3279 while (cgroup->parent) {
3280 cgroup = cgroup->parent;
3281 memcg = mem_cgroup_from_cont(cgroup);
3282 if (!memcg->use_hierarchy)
3283 break;
3284 tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
3285 min_limit = min(min_limit, tmp);
3286 tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3287 min_memsw_limit = min(min_memsw_limit, tmp);
3288 }
3289out:
3290 *mem_limit = min_limit;
3291 *memsw_limit = min_memsw_limit;
3292 return;
3293}
3294
29f2a4da 3295static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
c84872e1
PE
3296{
3297 struct mem_cgroup *mem;
8c7c6e34 3298 int type, name;
c84872e1
PE
3299
3300 mem = mem_cgroup_from_cont(cont);
8c7c6e34
KH
3301 type = MEMFILE_TYPE(event);
3302 name = MEMFILE_ATTR(event);
3303 switch (name) {
29f2a4da 3304 case RES_MAX_USAGE:
8c7c6e34
KH
3305 if (type == _MEM)
3306 res_counter_reset_max(&mem->res);
3307 else
3308 res_counter_reset_max(&mem->memsw);
29f2a4da
PE
3309 break;
3310 case RES_FAILCNT:
8c7c6e34
KH
3311 if (type == _MEM)
3312 res_counter_reset_failcnt(&mem->res);
3313 else
3314 res_counter_reset_failcnt(&mem->memsw);
29f2a4da
PE
3315 break;
3316 }
f64c3f54 3317
85cc59db 3318 return 0;
c84872e1
PE
3319}
3320
7dc74be0
DN
3321static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp,
3322 struct cftype *cft)
3323{
3324 return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate;
3325}
3326
02491447 3327#ifdef CONFIG_MMU
7dc74be0
DN
3328static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
3329 struct cftype *cft, u64 val)
3330{
3331 struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
3332
3333 if (val >= (1 << NR_MOVE_TYPE))
3334 return -EINVAL;
3335 /*
3336 * We check this value several times in both in can_attach() and
3337 * attach(), so we need cgroup lock to prevent this value from being
3338 * inconsistent.
3339 */
3340 cgroup_lock();
3341 mem->move_charge_at_immigrate = val;
3342 cgroup_unlock();
3343
3344 return 0;
3345}
02491447
DN
3346#else
3347static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
3348 struct cftype *cft, u64 val)
3349{
3350 return -ENOSYS;
3351}
3352#endif
7dc74be0 3353
14067bb3
KH
3354
3355/* For read statistics */
3356enum {
3357 MCS_CACHE,
3358 MCS_RSS,
d8046582 3359 MCS_FILE_MAPPED,
14067bb3
KH
3360 MCS_PGPGIN,
3361 MCS_PGPGOUT,
1dd3a273 3362 MCS_SWAP,
14067bb3
KH
3363 MCS_INACTIVE_ANON,
3364 MCS_ACTIVE_ANON,
3365 MCS_INACTIVE_FILE,
3366 MCS_ACTIVE_FILE,
3367 MCS_UNEVICTABLE,
3368 NR_MCS_STAT,
3369};
3370
3371struct mcs_total_stat {
3372 s64 stat[NR_MCS_STAT];
d2ceb9b7
KH
3373};
3374
14067bb3
KH
3375struct {
3376 char *local_name;
3377 char *total_name;
3378} memcg_stat_strings[NR_MCS_STAT] = {
3379 {"cache", "total_cache"},
3380 {"rss", "total_rss"},
d69b042f 3381 {"mapped_file", "total_mapped_file"},
14067bb3
KH
3382 {"pgpgin", "total_pgpgin"},
3383 {"pgpgout", "total_pgpgout"},
1dd3a273 3384 {"swap", "total_swap"},
14067bb3
KH
3385 {"inactive_anon", "total_inactive_anon"},
3386 {"active_anon", "total_active_anon"},
3387 {"inactive_file", "total_inactive_file"},
3388 {"active_file", "total_active_file"},
3389 {"unevictable", "total_unevictable"}
3390};
3391
3392
3393static int mem_cgroup_get_local_stat(struct mem_cgroup *mem, void *data)
3394{
3395 struct mcs_total_stat *s = data;
3396 s64 val;
3397
3398 /* per cpu stat */
c62b1a3b 3399 val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_CACHE);
14067bb3 3400 s->stat[MCS_CACHE] += val * PAGE_SIZE;
c62b1a3b 3401 val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_RSS);
14067bb3 3402 s->stat[MCS_RSS] += val * PAGE_SIZE;
c62b1a3b 3403 val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_FILE_MAPPED);
d8046582 3404 s->stat[MCS_FILE_MAPPED] += val * PAGE_SIZE;
c62b1a3b 3405 val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_PGPGIN_COUNT);
14067bb3 3406 s->stat[MCS_PGPGIN] += val;
c62b1a3b 3407 val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_PGPGOUT_COUNT);
14067bb3 3408 s->stat[MCS_PGPGOUT] += val;
1dd3a273 3409 if (do_swap_account) {
c62b1a3b 3410 val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_SWAPOUT);
1dd3a273
DN
3411 s->stat[MCS_SWAP] += val * PAGE_SIZE;
3412 }
14067bb3
KH
3413
3414 /* per zone stat */
3415 val = mem_cgroup_get_local_zonestat(mem, LRU_INACTIVE_ANON);
3416 s->stat[MCS_INACTIVE_ANON] += val * PAGE_SIZE;
3417 val = mem_cgroup_get_local_zonestat(mem, LRU_ACTIVE_ANON);
3418 s->stat[MCS_ACTIVE_ANON] += val * PAGE_SIZE;
3419 val = mem_cgroup_get_local_zonestat(mem, LRU_INACTIVE_FILE);
3420 s->stat[MCS_INACTIVE_FILE] += val * PAGE_SIZE;
3421 val = mem_cgroup_get_local_zonestat(mem, LRU_ACTIVE_FILE);
3422 s->stat[MCS_ACTIVE_FILE] += val * PAGE_SIZE;
3423 val = mem_cgroup_get_local_zonestat(mem, LRU_UNEVICTABLE);
3424 s->stat[MCS_UNEVICTABLE] += val * PAGE_SIZE;
3425 return 0;
3426}
3427
3428static void
3429mem_cgroup_get_total_stat(struct mem_cgroup *mem, struct mcs_total_stat *s)
3430{
3431 mem_cgroup_walk_tree(mem, s, mem_cgroup_get_local_stat);
3432}
3433
c64745cf
PM
3434static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft,
3435 struct cgroup_map_cb *cb)
d2ceb9b7 3436{
d2ceb9b7 3437 struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
14067bb3 3438 struct mcs_total_stat mystat;
d2ceb9b7
KH
3439 int i;
3440
14067bb3
KH
3441 memset(&mystat, 0, sizeof(mystat));
3442 mem_cgroup_get_local_stat(mem_cont, &mystat);
d2ceb9b7 3443
1dd3a273
DN
3444 for (i = 0; i < NR_MCS_STAT; i++) {
3445 if (i == MCS_SWAP && !do_swap_account)
3446 continue;
14067bb3 3447 cb->fill(cb, memcg_stat_strings[i].local_name, mystat.stat[i]);
1dd3a273 3448 }
7b854121 3449
14067bb3 3450 /* Hierarchical information */
fee7b548
KH
3451 {
3452 unsigned long long limit, memsw_limit;
3453 memcg_get_hierarchical_limit(mem_cont, &limit, &memsw_limit);
3454 cb->fill(cb, "hierarchical_memory_limit", limit);
3455 if (do_swap_account)
3456 cb->fill(cb, "hierarchical_memsw_limit", memsw_limit);
3457 }
7f016ee8 3458
14067bb3
KH
3459 memset(&mystat, 0, sizeof(mystat));
3460 mem_cgroup_get_total_stat(mem_cont, &mystat);
1dd3a273
DN
3461 for (i = 0; i < NR_MCS_STAT; i++) {
3462 if (i == MCS_SWAP && !do_swap_account)
3463 continue;
14067bb3 3464 cb->fill(cb, memcg_stat_strings[i].total_name, mystat.stat[i]);
1dd3a273 3465 }
14067bb3 3466
7f016ee8 3467#ifdef CONFIG_DEBUG_VM
c772be93 3468 cb->fill(cb, "inactive_ratio", calc_inactive_ratio(mem_cont, NULL));
7f016ee8
KM
3469
3470 {
3471 int nid, zid;
3472 struct mem_cgroup_per_zone *mz;
3473 unsigned long recent_rotated[2] = {0, 0};
3474 unsigned long recent_scanned[2] = {0, 0};
3475
3476 for_each_online_node(nid)
3477 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
3478 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
3479
3480 recent_rotated[0] +=
3481 mz->reclaim_stat.recent_rotated[0];
3482 recent_rotated[1] +=
3483 mz->reclaim_stat.recent_rotated[1];
3484 recent_scanned[0] +=
3485 mz->reclaim_stat.recent_scanned[0];
3486 recent_scanned[1] +=
3487 mz->reclaim_stat.recent_scanned[1];
3488 }
3489 cb->fill(cb, "recent_rotated_anon", recent_rotated[0]);
3490 cb->fill(cb, "recent_rotated_file", recent_rotated[1]);
3491 cb->fill(cb, "recent_scanned_anon", recent_scanned[0]);
3492 cb->fill(cb, "recent_scanned_file", recent_scanned[1]);
3493 }
3494#endif
3495
d2ceb9b7
KH
3496 return 0;
3497}
3498
a7885eb8
KM
3499static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
3500{
3501 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3502
3503 return get_swappiness(memcg);
3504}
3505
3506static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
3507 u64 val)
3508{
3509 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3510 struct mem_cgroup *parent;
068b38c1 3511
a7885eb8
KM
3512 if (val > 100)
3513 return -EINVAL;
3514
3515 if (cgrp->parent == NULL)
3516 return -EINVAL;
3517
3518 parent = mem_cgroup_from_cont(cgrp->parent);
068b38c1
LZ
3519
3520 cgroup_lock();
3521
a7885eb8
KM
3522 /* If under hierarchy, only empty-root can set this value */
3523 if ((parent->use_hierarchy) ||
068b38c1
LZ
3524 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
3525 cgroup_unlock();
a7885eb8 3526 return -EINVAL;
068b38c1 3527 }
a7885eb8
KM
3528
3529 spin_lock(&memcg->reclaim_param_lock);
3530 memcg->swappiness = val;
3531 spin_unlock(&memcg->reclaim_param_lock);
3532
068b38c1
LZ
3533 cgroup_unlock();
3534
a7885eb8
KM
3535 return 0;
3536}
3537
2e72b634
KS
3538static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
3539{
3540 struct mem_cgroup_threshold_ary *t;
3541 u64 usage;
3542 int i;
3543
3544 rcu_read_lock();
3545 if (!swap)
2c488db2 3546 t = rcu_dereference(memcg->thresholds.primary);
2e72b634 3547 else
2c488db2 3548 t = rcu_dereference(memcg->memsw_thresholds.primary);
2e72b634
KS
3549
3550 if (!t)
3551 goto unlock;
3552
3553 usage = mem_cgroup_usage(memcg, swap);
3554
3555 /*
3556 * current_threshold points to threshold just below usage.
3557 * If it's not true, a threshold was crossed after last
3558 * call of __mem_cgroup_threshold().
3559 */
5407a562 3560 i = t->current_threshold;
2e72b634
KS
3561
3562 /*
3563 * Iterate backward over array of thresholds starting from
3564 * current_threshold and check if a threshold is crossed.
3565 * If none of thresholds below usage is crossed, we read
3566 * only one element of the array here.
3567 */
3568 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
3569 eventfd_signal(t->entries[i].eventfd, 1);
3570
3571 /* i = current_threshold + 1 */
3572 i++;
3573
3574 /*
3575 * Iterate forward over array of thresholds starting from
3576 * current_threshold+1 and check if a threshold is crossed.
3577 * If none of thresholds above usage is crossed, we read
3578 * only one element of the array here.
3579 */
3580 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
3581 eventfd_signal(t->entries[i].eventfd, 1);
3582
3583 /* Update current_threshold */
5407a562 3584 t->current_threshold = i - 1;
2e72b634
KS
3585unlock:
3586 rcu_read_unlock();
3587}
3588
3589static void mem_cgroup_threshold(struct mem_cgroup *memcg)
3590{
3591 __mem_cgroup_threshold(memcg, false);
3592 if (do_swap_account)
3593 __mem_cgroup_threshold(memcg, true);
3594}
3595
3596static int compare_thresholds(const void *a, const void *b)
3597{
3598 const struct mem_cgroup_threshold *_a = a;
3599 const struct mem_cgroup_threshold *_b = b;
3600
3601 return _a->threshold - _b->threshold;
3602}
3603
9490ff27
KH
3604static int mem_cgroup_oom_notify_cb(struct mem_cgroup *mem, void *data)
3605{
3606 struct mem_cgroup_eventfd_list *ev;
3607
3608 list_for_each_entry(ev, &mem->oom_notify, list)
3609 eventfd_signal(ev->eventfd, 1);
3610 return 0;
3611}
3612
3613static void mem_cgroup_oom_notify(struct mem_cgroup *mem)
3614{
3615 mem_cgroup_walk_tree(mem, NULL, mem_cgroup_oom_notify_cb);
3616}
3617
3618static int mem_cgroup_usage_register_event(struct cgroup *cgrp,
3619 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
2e72b634
KS
3620{
3621 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
2c488db2
KS
3622 struct mem_cgroup_thresholds *thresholds;
3623 struct mem_cgroup_threshold_ary *new;
2e72b634
KS
3624 int type = MEMFILE_TYPE(cft->private);
3625 u64 threshold, usage;
2c488db2 3626 int i, size, ret;
2e72b634
KS
3627
3628 ret = res_counter_memparse_write_strategy(args, &threshold);
3629 if (ret)
3630 return ret;
3631
3632 mutex_lock(&memcg->thresholds_lock);
2c488db2 3633
2e72b634 3634 if (type == _MEM)
2c488db2 3635 thresholds = &memcg->thresholds;
2e72b634 3636 else if (type == _MEMSWAP)
2c488db2 3637 thresholds = &memcg->memsw_thresholds;
2e72b634
KS
3638 else
3639 BUG();
3640
3641 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
3642
3643 /* Check if a threshold crossed before adding a new one */
2c488db2 3644 if (thresholds->primary)
2e72b634
KS
3645 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
3646
2c488db2 3647 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
2e72b634
KS
3648
3649 /* Allocate memory for new array of thresholds */
2c488db2 3650 new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
2e72b634 3651 GFP_KERNEL);
2c488db2 3652 if (!new) {
2e72b634
KS
3653 ret = -ENOMEM;
3654 goto unlock;
3655 }
2c488db2 3656 new->size = size;
2e72b634
KS
3657
3658 /* Copy thresholds (if any) to new array */
2c488db2
KS
3659 if (thresholds->primary) {
3660 memcpy(new->entries, thresholds->primary->entries, (size - 1) *
2e72b634 3661 sizeof(struct mem_cgroup_threshold));
2c488db2
KS
3662 }
3663
2e72b634 3664 /* Add new threshold */
2c488db2
KS
3665 new->entries[size - 1].eventfd = eventfd;
3666 new->entries[size - 1].threshold = threshold;
2e72b634
KS
3667
3668 /* Sort thresholds. Registering of new threshold isn't time-critical */
2c488db2 3669 sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
2e72b634
KS
3670 compare_thresholds, NULL);
3671
3672 /* Find current threshold */
2c488db2 3673 new->current_threshold = -1;
2e72b634 3674 for (i = 0; i < size; i++) {
2c488db2 3675 if (new->entries[i].threshold < usage) {
2e72b634 3676 /*
2c488db2
KS
3677 * new->current_threshold will not be used until
3678 * rcu_assign_pointer(), so it's safe to increment
2e72b634
KS
3679 * it here.
3680 */
2c488db2 3681 ++new->current_threshold;
2e72b634
KS
3682 }
3683 }
3684
2c488db2
KS
3685 /* Free old spare buffer and save old primary buffer as spare */
3686 kfree(thresholds->spare);
3687 thresholds->spare = thresholds->primary;
3688
3689 rcu_assign_pointer(thresholds->primary, new);
2e72b634 3690
907860ed 3691 /* To be sure that nobody uses thresholds */
2e72b634
KS
3692 synchronize_rcu();
3693
2e72b634
KS
3694unlock:
3695 mutex_unlock(&memcg->thresholds_lock);
3696
3697 return ret;
3698}
3699
907860ed 3700static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,
9490ff27 3701 struct cftype *cft, struct eventfd_ctx *eventfd)
2e72b634
KS
3702{
3703 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
2c488db2
KS
3704 struct mem_cgroup_thresholds *thresholds;
3705 struct mem_cgroup_threshold_ary *new;
2e72b634
KS
3706 int type = MEMFILE_TYPE(cft->private);
3707 u64 usage;
2c488db2 3708 int i, j, size;
2e72b634
KS
3709
3710 mutex_lock(&memcg->thresholds_lock);
3711 if (type == _MEM)
2c488db2 3712 thresholds = &memcg->thresholds;
2e72b634 3713 else if (type == _MEMSWAP)
2c488db2 3714 thresholds = &memcg->memsw_thresholds;
2e72b634
KS
3715 else
3716 BUG();
3717
3718 /*
3719 * Something went wrong if we trying to unregister a threshold
3720 * if we don't have thresholds
3721 */
3722 BUG_ON(!thresholds);
3723
3724 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
3725
3726 /* Check if a threshold crossed before removing */
3727 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
3728
3729 /* Calculate new number of threshold */
2c488db2
KS
3730 size = 0;
3731 for (i = 0; i < thresholds->primary->size; i++) {
3732 if (thresholds->primary->entries[i].eventfd != eventfd)
2e72b634
KS
3733 size++;
3734 }
3735
2c488db2 3736 new = thresholds->spare;
907860ed 3737
2e72b634
KS
3738 /* Set thresholds array to NULL if we don't have thresholds */
3739 if (!size) {
2c488db2
KS
3740 kfree(new);
3741 new = NULL;
907860ed 3742 goto swap_buffers;
2e72b634
KS
3743 }
3744
2c488db2 3745 new->size = size;
2e72b634
KS
3746
3747 /* Copy thresholds and find current threshold */
2c488db2
KS
3748 new->current_threshold = -1;
3749 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
3750 if (thresholds->primary->entries[i].eventfd == eventfd)
2e72b634
KS
3751 continue;
3752
2c488db2
KS
3753 new->entries[j] = thresholds->primary->entries[i];
3754 if (new->entries[j].threshold < usage) {
2e72b634 3755 /*
2c488db2 3756 * new->current_threshold will not be used
2e72b634
KS
3757 * until rcu_assign_pointer(), so it's safe to increment
3758 * it here.
3759 */
2c488db2 3760 ++new->current_threshold;
2e72b634
KS
3761 }
3762 j++;
3763 }
3764
907860ed 3765swap_buffers:
2c488db2
KS
3766 /* Swap primary and spare array */
3767 thresholds->spare = thresholds->primary;
3768 rcu_assign_pointer(thresholds->primary, new);
2e72b634 3769
907860ed 3770 /* To be sure that nobody uses thresholds */
2e72b634
KS
3771 synchronize_rcu();
3772
2e72b634 3773 mutex_unlock(&memcg->thresholds_lock);
2e72b634 3774}
c1e862c1 3775
9490ff27
KH
3776static int mem_cgroup_oom_register_event(struct cgroup *cgrp,
3777 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
3778{
3779 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3780 struct mem_cgroup_eventfd_list *event;
3781 int type = MEMFILE_TYPE(cft->private);
3782
3783 BUG_ON(type != _OOM_TYPE);
3784 event = kmalloc(sizeof(*event), GFP_KERNEL);
3785 if (!event)
3786 return -ENOMEM;
3787
3788 mutex_lock(&memcg_oom_mutex);
3789
3790 event->eventfd = eventfd;
3791 list_add(&event->list, &memcg->oom_notify);
3792
3793 /* already in OOM ? */
3794 if (atomic_read(&memcg->oom_lock))
3795 eventfd_signal(eventfd, 1);
3796 mutex_unlock(&memcg_oom_mutex);
3797
3798 return 0;
3799}
3800
907860ed 3801static void mem_cgroup_oom_unregister_event(struct cgroup *cgrp,
9490ff27
KH
3802 struct cftype *cft, struct eventfd_ctx *eventfd)
3803{
3804 struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
3805 struct mem_cgroup_eventfd_list *ev, *tmp;
3806 int type = MEMFILE_TYPE(cft->private);
3807
3808 BUG_ON(type != _OOM_TYPE);
3809
3810 mutex_lock(&memcg_oom_mutex);
3811
3812 list_for_each_entry_safe(ev, tmp, &mem->oom_notify, list) {
3813 if (ev->eventfd == eventfd) {
3814 list_del(&ev->list);
3815 kfree(ev);
3816 }
3817 }
3818
3819 mutex_unlock(&memcg_oom_mutex);
9490ff27
KH
3820}
3821
3c11ecf4
KH
3822static int mem_cgroup_oom_control_read(struct cgroup *cgrp,
3823 struct cftype *cft, struct cgroup_map_cb *cb)
3824{
3825 struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
3826
3827 cb->fill(cb, "oom_kill_disable", mem->oom_kill_disable);
3828
3829 if (atomic_read(&mem->oom_lock))
3830 cb->fill(cb, "under_oom", 1);
3831 else
3832 cb->fill(cb, "under_oom", 0);
3833 return 0;
3834}
3835
3c11ecf4
KH
3836static int mem_cgroup_oom_control_write(struct cgroup *cgrp,
3837 struct cftype *cft, u64 val)
3838{
3839 struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
3840 struct mem_cgroup *parent;
3841
3842 /* cannot set to root cgroup and only 0 and 1 are allowed */
3843 if (!cgrp->parent || !((val == 0) || (val == 1)))
3844 return -EINVAL;
3845
3846 parent = mem_cgroup_from_cont(cgrp->parent);
3847
3848 cgroup_lock();
3849 /* oom-kill-disable is a flag for subhierarchy. */
3850 if ((parent->use_hierarchy) ||
3851 (mem->use_hierarchy && !list_empty(&cgrp->children))) {
3852 cgroup_unlock();
3853 return -EINVAL;
3854 }
3855 mem->oom_kill_disable = val;
4d845ebf
KH
3856 if (!val)
3857 memcg_oom_recover(mem);
3c11ecf4
KH
3858 cgroup_unlock();
3859 return 0;
3860}
3861
8cdea7c0
BS
3862static struct cftype mem_cgroup_files[] = {
3863 {
0eea1030 3864 .name = "usage_in_bytes",
8c7c6e34 3865 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
2c3daa72 3866 .read_u64 = mem_cgroup_read,
9490ff27
KH
3867 .register_event = mem_cgroup_usage_register_event,
3868 .unregister_event = mem_cgroup_usage_unregister_event,
8cdea7c0 3869 },
c84872e1
PE
3870 {
3871 .name = "max_usage_in_bytes",
8c7c6e34 3872 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
29f2a4da 3873 .trigger = mem_cgroup_reset,
c84872e1
PE
3874 .read_u64 = mem_cgroup_read,
3875 },
8cdea7c0 3876 {
0eea1030 3877 .name = "limit_in_bytes",
8c7c6e34 3878 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
856c13aa 3879 .write_string = mem_cgroup_write,
2c3daa72 3880 .read_u64 = mem_cgroup_read,
8cdea7c0 3881 },
296c81d8
BS
3882 {
3883 .name = "soft_limit_in_bytes",
3884 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
3885 .write_string = mem_cgroup_write,
3886 .read_u64 = mem_cgroup_read,
3887 },
8cdea7c0
BS
3888 {
3889 .name = "failcnt",
8c7c6e34 3890 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
29f2a4da 3891 .trigger = mem_cgroup_reset,
2c3daa72 3892 .read_u64 = mem_cgroup_read,
8cdea7c0 3893 },
d2ceb9b7
KH
3894 {
3895 .name = "stat",
c64745cf 3896 .read_map = mem_control_stat_show,
d2ceb9b7 3897 },
c1e862c1
KH
3898 {
3899 .name = "force_empty",
3900 .trigger = mem_cgroup_force_empty_write,
3901 },
18f59ea7
BS
3902 {
3903 .name = "use_hierarchy",
3904 .write_u64 = mem_cgroup_hierarchy_write,
3905 .read_u64 = mem_cgroup_hierarchy_read,
3906 },
a7885eb8
KM
3907 {
3908 .name = "swappiness",
3909 .read_u64 = mem_cgroup_swappiness_read,
3910 .write_u64 = mem_cgroup_swappiness_write,
3911 },
7dc74be0
DN
3912 {
3913 .name = "move_charge_at_immigrate",
3914 .read_u64 = mem_cgroup_move_charge_read,
3915 .write_u64 = mem_cgroup_move_charge_write,
3916 },
9490ff27
KH
3917 {
3918 .name = "oom_control",
3c11ecf4
KH
3919 .read_map = mem_cgroup_oom_control_read,
3920 .write_u64 = mem_cgroup_oom_control_write,
9490ff27
KH
3921 .register_event = mem_cgroup_oom_register_event,
3922 .unregister_event = mem_cgroup_oom_unregister_event,
3923 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
3924 },
8cdea7c0
BS
3925};
3926
8c7c6e34
KH
3927#ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3928static struct cftype memsw_cgroup_files[] = {
3929 {
3930 .name = "memsw.usage_in_bytes",
3931 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
3932 .read_u64 = mem_cgroup_read,
9490ff27
KH
3933 .register_event = mem_cgroup_usage_register_event,
3934 .unregister_event = mem_cgroup_usage_unregister_event,
8c7c6e34
KH
3935 },
3936 {
3937 .name = "memsw.max_usage_in_bytes",
3938 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
3939 .trigger = mem_cgroup_reset,
3940 .read_u64 = mem_cgroup_read,
3941 },
3942 {
3943 .name = "memsw.limit_in_bytes",
3944 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
3945 .write_string = mem_cgroup_write,
3946 .read_u64 = mem_cgroup_read,
3947 },
3948 {
3949 .name = "memsw.failcnt",
3950 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
3951 .trigger = mem_cgroup_reset,
3952 .read_u64 = mem_cgroup_read,
3953 },
3954};
3955
3956static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
3957{
3958 if (!do_swap_account)
3959 return 0;
3960 return cgroup_add_files(cont, ss, memsw_cgroup_files,
3961 ARRAY_SIZE(memsw_cgroup_files));
3962};
3963#else
3964static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
3965{
3966 return 0;
3967}
3968#endif
3969
6d12e2d8
KH
3970static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
3971{
3972 struct mem_cgroup_per_node *pn;
1ecaab2b 3973 struct mem_cgroup_per_zone *mz;
b69408e8 3974 enum lru_list l;
41e3355d 3975 int zone, tmp = node;
1ecaab2b
KH
3976 /*
3977 * This routine is called against possible nodes.
3978 * But it's BUG to call kmalloc() against offline node.
3979 *
3980 * TODO: this routine can waste much memory for nodes which will
3981 * never be onlined. It's better to use memory hotplug callback
3982 * function.
3983 */
41e3355d
KH
3984 if (!node_state(node, N_NORMAL_MEMORY))
3985 tmp = -1;
3986 pn = kmalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
6d12e2d8
KH
3987 if (!pn)
3988 return 1;
1ecaab2b 3989
6d12e2d8
KH
3990 mem->info.nodeinfo[node] = pn;
3991 memset(pn, 0, sizeof(*pn));
1ecaab2b
KH
3992
3993 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3994 mz = &pn->zoneinfo[zone];
b69408e8
CL
3995 for_each_lru(l)
3996 INIT_LIST_HEAD(&mz->lists[l]);
f64c3f54 3997 mz->usage_in_excess = 0;
4e416953
BS
3998 mz->on_tree = false;
3999 mz->mem = mem;
1ecaab2b 4000 }
6d12e2d8
KH
4001 return 0;
4002}
4003
1ecaab2b
KH
4004static void free_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
4005{
4006 kfree(mem->info.nodeinfo[node]);
4007}
4008
33327948
KH
4009static struct mem_cgroup *mem_cgroup_alloc(void)
4010{
4011 struct mem_cgroup *mem;
c62b1a3b 4012 int size = sizeof(struct mem_cgroup);
33327948 4013
c62b1a3b 4014 /* Can be very big if MAX_NUMNODES is very big */
c8dad2bb
JB
4015 if (size < PAGE_SIZE)
4016 mem = kmalloc(size, GFP_KERNEL);
33327948 4017 else
c8dad2bb 4018 mem = vmalloc(size);
33327948 4019
e7bbcdf3
DC
4020 if (!mem)
4021 return NULL;
4022
4023 memset(mem, 0, size);
c62b1a3b
KH
4024 mem->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
4025 if (!mem->stat) {
4026 if (size < PAGE_SIZE)
4027 kfree(mem);
4028 else
4029 vfree(mem);
4030 mem = NULL;
4031 }
33327948
KH
4032 return mem;
4033}
4034
8c7c6e34
KH
4035/*
4036 * At destroying mem_cgroup, references from swap_cgroup can remain.
4037 * (scanning all at force_empty is too costly...)
4038 *
4039 * Instead of clearing all references at force_empty, we remember
4040 * the number of reference from swap_cgroup and free mem_cgroup when
4041 * it goes down to 0.
4042 *
8c7c6e34
KH
4043 * Removal of cgroup itself succeeds regardless of refs from swap.
4044 */
4045
a7ba0eef 4046static void __mem_cgroup_free(struct mem_cgroup *mem)
33327948 4047{
08e552c6
KH
4048 int node;
4049
f64c3f54 4050 mem_cgroup_remove_from_trees(mem);
04046e1a
KH
4051 free_css_id(&mem_cgroup_subsys, &mem->css);
4052
08e552c6
KH
4053 for_each_node_state(node, N_POSSIBLE)
4054 free_mem_cgroup_per_zone_info(mem, node);
4055
c62b1a3b
KH
4056 free_percpu(mem->stat);
4057 if (sizeof(struct mem_cgroup) < PAGE_SIZE)
33327948
KH
4058 kfree(mem);
4059 else
4060 vfree(mem);
4061}
4062
8c7c6e34
KH
4063static void mem_cgroup_get(struct mem_cgroup *mem)
4064{
4065 atomic_inc(&mem->refcnt);
4066}
4067
483c30b5 4068static void __mem_cgroup_put(struct mem_cgroup *mem, int count)
8c7c6e34 4069{
483c30b5 4070 if (atomic_sub_and_test(count, &mem->refcnt)) {
7bcc1bb1 4071 struct mem_cgroup *parent = parent_mem_cgroup(mem);
a7ba0eef 4072 __mem_cgroup_free(mem);
7bcc1bb1
DN
4073 if (parent)
4074 mem_cgroup_put(parent);
4075 }
8c7c6e34
KH
4076}
4077
483c30b5
DN
4078static void mem_cgroup_put(struct mem_cgroup *mem)
4079{
4080 __mem_cgroup_put(mem, 1);
4081}
4082
7bcc1bb1
DN
4083/*
4084 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
4085 */
4086static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem)
4087{
4088 if (!mem->res.parent)
4089 return NULL;
4090 return mem_cgroup_from_res_counter(mem->res.parent, res);
4091}
33327948 4092
c077719b
KH
4093#ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4094static void __init enable_swap_cgroup(void)
4095{
f8d66542 4096 if (!mem_cgroup_disabled() && really_do_swap_account)
c077719b
KH
4097 do_swap_account = 1;
4098}
4099#else
4100static void __init enable_swap_cgroup(void)
4101{
4102}
4103#endif
4104
f64c3f54
BS
4105static int mem_cgroup_soft_limit_tree_init(void)
4106{
4107 struct mem_cgroup_tree_per_node *rtpn;
4108 struct mem_cgroup_tree_per_zone *rtpz;
4109 int tmp, node, zone;
4110
4111 for_each_node_state(node, N_POSSIBLE) {
4112 tmp = node;
4113 if (!node_state(node, N_NORMAL_MEMORY))
4114 tmp = -1;
4115 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
4116 if (!rtpn)
4117 return 1;
4118
4119 soft_limit_tree.rb_tree_per_node[node] = rtpn;
4120
4121 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4122 rtpz = &rtpn->rb_tree_per_zone[zone];
4123 rtpz->rb_root = RB_ROOT;
4124 spin_lock_init(&rtpz->lock);
4125 }
4126 }
4127 return 0;
4128}
4129
0eb253e2 4130static struct cgroup_subsys_state * __ref
8cdea7c0
BS
4131mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
4132{
28dbc4b6 4133 struct mem_cgroup *mem, *parent;
04046e1a 4134 long error = -ENOMEM;
6d12e2d8 4135 int node;
8cdea7c0 4136
c8dad2bb
JB
4137 mem = mem_cgroup_alloc();
4138 if (!mem)
04046e1a 4139 return ERR_PTR(error);
78fb7466 4140
6d12e2d8
KH
4141 for_each_node_state(node, N_POSSIBLE)
4142 if (alloc_mem_cgroup_per_zone_info(mem, node))
4143 goto free_out;
f64c3f54 4144
c077719b 4145 /* root ? */
28dbc4b6 4146 if (cont->parent == NULL) {
cdec2e42 4147 int cpu;
c077719b 4148 enable_swap_cgroup();
28dbc4b6 4149 parent = NULL;
4b3bde4c 4150 root_mem_cgroup = mem;
f64c3f54
BS
4151 if (mem_cgroup_soft_limit_tree_init())
4152 goto free_out;
cdec2e42
KH
4153 for_each_possible_cpu(cpu) {
4154 struct memcg_stock_pcp *stock =
4155 &per_cpu(memcg_stock, cpu);
4156 INIT_WORK(&stock->work, drain_local_stock);
4157 }
4158 hotcpu_notifier(memcg_stock_cpu_callback, 0);
18f59ea7 4159 } else {
28dbc4b6 4160 parent = mem_cgroup_from_cont(cont->parent);
18f59ea7 4161 mem->use_hierarchy = parent->use_hierarchy;
3c11ecf4 4162 mem->oom_kill_disable = parent->oom_kill_disable;
18f59ea7 4163 }
28dbc4b6 4164
18f59ea7
BS
4165 if (parent && parent->use_hierarchy) {
4166 res_counter_init(&mem->res, &parent->res);
4167 res_counter_init(&mem->memsw, &parent->memsw);
7bcc1bb1
DN
4168 /*
4169 * We increment refcnt of the parent to ensure that we can
4170 * safely access it on res_counter_charge/uncharge.
4171 * This refcnt will be decremented when freeing this
4172 * mem_cgroup(see mem_cgroup_put).
4173 */
4174 mem_cgroup_get(parent);
18f59ea7
BS
4175 } else {
4176 res_counter_init(&mem->res, NULL);
4177 res_counter_init(&mem->memsw, NULL);
4178 }
04046e1a 4179 mem->last_scanned_child = 0;
2733c06a 4180 spin_lock_init(&mem->reclaim_param_lock);
9490ff27 4181 INIT_LIST_HEAD(&mem->oom_notify);
6d61ef40 4182
a7885eb8
KM
4183 if (parent)
4184 mem->swappiness = get_swappiness(parent);
a7ba0eef 4185 atomic_set(&mem->refcnt, 1);
7dc74be0 4186 mem->move_charge_at_immigrate = 0;
2e72b634 4187 mutex_init(&mem->thresholds_lock);
8cdea7c0 4188 return &mem->css;
6d12e2d8 4189free_out:
a7ba0eef 4190 __mem_cgroup_free(mem);
4b3bde4c 4191 root_mem_cgroup = NULL;
04046e1a 4192 return ERR_PTR(error);
8cdea7c0
BS
4193}
4194
ec64f515 4195static int mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
df878fb0
KH
4196 struct cgroup *cont)
4197{
4198 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
ec64f515
KH
4199
4200 return mem_cgroup_force_empty(mem, false);
df878fb0
KH
4201}
4202
8cdea7c0
BS
4203static void mem_cgroup_destroy(struct cgroup_subsys *ss,
4204 struct cgroup *cont)
4205{
c268e994 4206 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
c268e994 4207
c268e994 4208 mem_cgroup_put(mem);
8cdea7c0
BS
4209}
4210
4211static int mem_cgroup_populate(struct cgroup_subsys *ss,
4212 struct cgroup *cont)
4213{
8c7c6e34
KH
4214 int ret;
4215
4216 ret = cgroup_add_files(cont, ss, mem_cgroup_files,
4217 ARRAY_SIZE(mem_cgroup_files));
4218
4219 if (!ret)
4220 ret = register_memsw_files(cont, ss);
4221 return ret;
8cdea7c0
BS
4222}
4223
02491447 4224#ifdef CONFIG_MMU
7dc74be0 4225/* Handlers for move charge at task migration. */
854ffa8d
DN
4226#define PRECHARGE_COUNT_AT_ONCE 256
4227static int mem_cgroup_do_precharge(unsigned long count)
7dc74be0 4228{
854ffa8d
DN
4229 int ret = 0;
4230 int batch_count = PRECHARGE_COUNT_AT_ONCE;
4ffef5fe
DN
4231 struct mem_cgroup *mem = mc.to;
4232
854ffa8d
DN
4233 if (mem_cgroup_is_root(mem)) {
4234 mc.precharge += count;
4235 /* we don't need css_get for root */
4236 return ret;
4237 }
4238 /* try to charge at once */
4239 if (count > 1) {
4240 struct res_counter *dummy;
4241 /*
4242 * "mem" cannot be under rmdir() because we've already checked
4243 * by cgroup_lock_live_cgroup() that it is not removed and we
4244 * are still under the same cgroup_mutex. So we can postpone
4245 * css_get().
4246 */
4247 if (res_counter_charge(&mem->res, PAGE_SIZE * count, &dummy))
4248 goto one_by_one;
4249 if (do_swap_account && res_counter_charge(&mem->memsw,
4250 PAGE_SIZE * count, &dummy)) {
4251 res_counter_uncharge(&mem->res, PAGE_SIZE * count);
4252 goto one_by_one;
4253 }
4254 mc.precharge += count;
854ffa8d
DN
4255 return ret;
4256 }
4257one_by_one:
4258 /* fall back to one by one charge */
4259 while (count--) {
4260 if (signal_pending(current)) {
4261 ret = -EINTR;
4262 break;
4263 }
4264 if (!batch_count--) {
4265 batch_count = PRECHARGE_COUNT_AT_ONCE;
4266 cond_resched();
4267 }
430e4863 4268 ret = __mem_cgroup_try_charge(NULL, GFP_KERNEL, &mem, false);
854ffa8d
DN
4269 if (ret || !mem)
4270 /* mem_cgroup_clear_mc() will do uncharge later */
4271 return -ENOMEM;
4272 mc.precharge++;
4273 }
4ffef5fe
DN
4274 return ret;
4275}
4276
4277/**
4278 * is_target_pte_for_mc - check a pte whether it is valid for move charge
4279 * @vma: the vma the pte to be checked belongs
4280 * @addr: the address corresponding to the pte to be checked
4281 * @ptent: the pte to be checked
02491447 4282 * @target: the pointer the target page or swap ent will be stored(can be NULL)
4ffef5fe
DN
4283 *
4284 * Returns
4285 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
4286 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
4287 * move charge. if @target is not NULL, the page is stored in target->page
4288 * with extra refcnt got(Callers should handle it).
02491447
DN
4289 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
4290 * target for charge migration. if @target is not NULL, the entry is stored
4291 * in target->ent.
4ffef5fe
DN
4292 *
4293 * Called with pte lock held.
4294 */
4ffef5fe
DN
4295union mc_target {
4296 struct page *page;
02491447 4297 swp_entry_t ent;
4ffef5fe
DN
4298};
4299
4ffef5fe
DN
4300enum mc_target_type {
4301 MC_TARGET_NONE, /* not used */
4302 MC_TARGET_PAGE,
02491447 4303 MC_TARGET_SWAP,
4ffef5fe
DN
4304};
4305
90254a65
DN
4306static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
4307 unsigned long addr, pte_t ptent)
4ffef5fe 4308{
90254a65 4309 struct page *page = vm_normal_page(vma, addr, ptent);
4ffef5fe 4310
90254a65
DN
4311 if (!page || !page_mapped(page))
4312 return NULL;
4313 if (PageAnon(page)) {
4314 /* we don't move shared anon */
4315 if (!move_anon() || page_mapcount(page) > 2)
4316 return NULL;
87946a72
DN
4317 } else if (!move_file())
4318 /* we ignore mapcount for file pages */
90254a65
DN
4319 return NULL;
4320 if (!get_page_unless_zero(page))
4321 return NULL;
4322
4323 return page;
4324}
4325
4326static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
4327 unsigned long addr, pte_t ptent, swp_entry_t *entry)
4328{
4329 int usage_count;
4330 struct page *page = NULL;
4331 swp_entry_t ent = pte_to_swp_entry(ptent);
4332
4333 if (!move_anon() || non_swap_entry(ent))
4334 return NULL;
4335 usage_count = mem_cgroup_count_swap_user(ent, &page);
4336 if (usage_count > 1) { /* we don't move shared anon */
02491447
DN
4337 if (page)
4338 put_page(page);
90254a65 4339 return NULL;
02491447 4340 }
90254a65
DN
4341 if (do_swap_account)
4342 entry->val = ent.val;
4343
4344 return page;
4345}
4346
87946a72
DN
4347static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
4348 unsigned long addr, pte_t ptent, swp_entry_t *entry)
4349{
4350 struct page *page = NULL;
4351 struct inode *inode;
4352 struct address_space *mapping;
4353 pgoff_t pgoff;
4354
4355 if (!vma->vm_file) /* anonymous vma */
4356 return NULL;
4357 if (!move_file())
4358 return NULL;
4359
4360 inode = vma->vm_file->f_path.dentry->d_inode;
4361 mapping = vma->vm_file->f_mapping;
4362 if (pte_none(ptent))
4363 pgoff = linear_page_index(vma, addr);
4364 else /* pte_file(ptent) is true */
4365 pgoff = pte_to_pgoff(ptent);
4366
4367 /* page is moved even if it's not RSS of this task(page-faulted). */
4368 if (!mapping_cap_swap_backed(mapping)) { /* normal file */
4369 page = find_get_page(mapping, pgoff);
4370 } else { /* shmem/tmpfs file. we should take account of swap too. */
4371 swp_entry_t ent;
4372 mem_cgroup_get_shmem_target(inode, pgoff, &page, &ent);
4373 if (do_swap_account)
4374 entry->val = ent.val;
4375 }
4376
4377 return page;
4378}
4379
90254a65
DN
4380static int is_target_pte_for_mc(struct vm_area_struct *vma,
4381 unsigned long addr, pte_t ptent, union mc_target *target)
4382{
4383 struct page *page = NULL;
4384 struct page_cgroup *pc;
4385 int ret = 0;
4386 swp_entry_t ent = { .val = 0 };
4387
4388 if (pte_present(ptent))
4389 page = mc_handle_present_pte(vma, addr, ptent);
4390 else if (is_swap_pte(ptent))
4391 page = mc_handle_swap_pte(vma, addr, ptent, &ent);
87946a72
DN
4392 else if (pte_none(ptent) || pte_file(ptent))
4393 page = mc_handle_file_pte(vma, addr, ptent, &ent);
90254a65
DN
4394
4395 if (!page && !ent.val)
4396 return 0;
02491447
DN
4397 if (page) {
4398 pc = lookup_page_cgroup(page);
4399 /*
4400 * Do only loose check w/o page_cgroup lock.
4401 * mem_cgroup_move_account() checks the pc is valid or not under
4402 * the lock.
4403 */
4404 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
4405 ret = MC_TARGET_PAGE;
4406 if (target)
4407 target->page = page;
4408 }
4409 if (!ret || !target)
4410 put_page(page);
4411 }
90254a65
DN
4412 /* There is a swap entry and a page doesn't exist or isn't charged */
4413 if (ent.val && !ret &&
7f0f1546
KH
4414 css_id(&mc.from->css) == lookup_swap_cgroup(ent)) {
4415 ret = MC_TARGET_SWAP;
4416 if (target)
4417 target->ent = ent;
4ffef5fe 4418 }
4ffef5fe
DN
4419 return ret;
4420}
4421
4422static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
4423 unsigned long addr, unsigned long end,
4424 struct mm_walk *walk)
4425{
4426 struct vm_area_struct *vma = walk->private;
4427 pte_t *pte;
4428 spinlock_t *ptl;
4429
4430 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
4431 for (; addr != end; pte++, addr += PAGE_SIZE)
4432 if (is_target_pte_for_mc(vma, addr, *pte, NULL))
4433 mc.precharge++; /* increment precharge temporarily */
4434 pte_unmap_unlock(pte - 1, ptl);
4435 cond_resched();
4436
7dc74be0
DN
4437 return 0;
4438}
4439
4ffef5fe
DN
4440static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
4441{
4442 unsigned long precharge;
4443 struct vm_area_struct *vma;
4444
4445 down_read(&mm->mmap_sem);
4446 for (vma = mm->mmap; vma; vma = vma->vm_next) {
4447 struct mm_walk mem_cgroup_count_precharge_walk = {
4448 .pmd_entry = mem_cgroup_count_precharge_pte_range,
4449 .mm = mm,
4450 .private = vma,
4451 };
4452 if (is_vm_hugetlb_page(vma))
4453 continue;
4ffef5fe
DN
4454 walk_page_range(vma->vm_start, vma->vm_end,
4455 &mem_cgroup_count_precharge_walk);
4456 }
4457 up_read(&mm->mmap_sem);
4458
4459 precharge = mc.precharge;
4460 mc.precharge = 0;
4461
4462 return precharge;
4463}
4464
4ffef5fe
DN
4465static int mem_cgroup_precharge_mc(struct mm_struct *mm)
4466{
854ffa8d 4467 return mem_cgroup_do_precharge(mem_cgroup_count_precharge(mm));
4ffef5fe
DN
4468}
4469
4470static void mem_cgroup_clear_mc(void)
4471{
2bd9bb20
KH
4472 struct mem_cgroup *from = mc.from;
4473 struct mem_cgroup *to = mc.to;
4474
4ffef5fe 4475 /* we must uncharge all the leftover precharges from mc.to */
854ffa8d
DN
4476 if (mc.precharge) {
4477 __mem_cgroup_cancel_charge(mc.to, mc.precharge);
4478 mc.precharge = 0;
4479 }
4480 /*
4481 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
4482 * we must uncharge here.
4483 */
4484 if (mc.moved_charge) {
4485 __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
4486 mc.moved_charge = 0;
4ffef5fe 4487 }
483c30b5
DN
4488 /* we must fixup refcnts and charges */
4489 if (mc.moved_swap) {
483c30b5
DN
4490 /* uncharge swap account from the old cgroup */
4491 if (!mem_cgroup_is_root(mc.from))
4492 res_counter_uncharge(&mc.from->memsw,
4493 PAGE_SIZE * mc.moved_swap);
4494 __mem_cgroup_put(mc.from, mc.moved_swap);
4495
4496 if (!mem_cgroup_is_root(mc.to)) {
4497 /*
4498 * we charged both to->res and to->memsw, so we should
4499 * uncharge to->res.
4500 */
4501 res_counter_uncharge(&mc.to->res,
4502 PAGE_SIZE * mc.moved_swap);
483c30b5
DN
4503 }
4504 /* we've already done mem_cgroup_get(mc.to) */
4505
4506 mc.moved_swap = 0;
4507 }
2bd9bb20 4508 spin_lock(&mc.lock);
4ffef5fe
DN
4509 mc.from = NULL;
4510 mc.to = NULL;
8033b97c 4511 mc.moving_task = NULL;
2bd9bb20
KH
4512 spin_unlock(&mc.lock);
4513 memcg_oom_recover(from);
4514 memcg_oom_recover(to);
8033b97c 4515 wake_up_all(&mc.waitq);
4ffef5fe
DN
4516}
4517
7dc74be0
DN
4518static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
4519 struct cgroup *cgroup,
4520 struct task_struct *p,
4521 bool threadgroup)
4522{
4523 int ret = 0;
4524 struct mem_cgroup *mem = mem_cgroup_from_cont(cgroup);
4525
4526 if (mem->move_charge_at_immigrate) {
4527 struct mm_struct *mm;
4528 struct mem_cgroup *from = mem_cgroup_from_task(p);
4529
4530 VM_BUG_ON(from == mem);
4531
4532 mm = get_task_mm(p);
4533 if (!mm)
4534 return 0;
7dc74be0 4535 /* We move charges only when we move a owner of the mm */
4ffef5fe
DN
4536 if (mm->owner == p) {
4537 VM_BUG_ON(mc.from);
4538 VM_BUG_ON(mc.to);
4539 VM_BUG_ON(mc.precharge);
854ffa8d 4540 VM_BUG_ON(mc.moved_charge);
483c30b5 4541 VM_BUG_ON(mc.moved_swap);
8033b97c 4542 VM_BUG_ON(mc.moving_task);
2bd9bb20 4543 spin_lock(&mc.lock);
4ffef5fe
DN
4544 mc.from = from;
4545 mc.to = mem;
4546 mc.precharge = 0;
854ffa8d 4547 mc.moved_charge = 0;
483c30b5 4548 mc.moved_swap = 0;
8033b97c 4549 mc.moving_task = current;
2bd9bb20 4550 spin_unlock(&mc.lock);
4ffef5fe
DN
4551
4552 ret = mem_cgroup_precharge_mc(mm);
4553 if (ret)
4554 mem_cgroup_clear_mc();
4555 }
7dc74be0
DN
4556 mmput(mm);
4557 }
4558 return ret;
4559}
4560
4561static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
4562 struct cgroup *cgroup,
4563 struct task_struct *p,
4564 bool threadgroup)
4565{
4ffef5fe 4566 mem_cgroup_clear_mc();
7dc74be0
DN
4567}
4568
4ffef5fe
DN
4569static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
4570 unsigned long addr, unsigned long end,
4571 struct mm_walk *walk)
7dc74be0 4572{
4ffef5fe
DN
4573 int ret = 0;
4574 struct vm_area_struct *vma = walk->private;
4575 pte_t *pte;
4576 spinlock_t *ptl;
4577
4578retry:
4579 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
4580 for (; addr != end; addr += PAGE_SIZE) {
4581 pte_t ptent = *(pte++);
4582 union mc_target target;
4583 int type;
4584 struct page *page;
4585 struct page_cgroup *pc;
02491447 4586 swp_entry_t ent;
4ffef5fe
DN
4587
4588 if (!mc.precharge)
4589 break;
4590
4591 type = is_target_pte_for_mc(vma, addr, ptent, &target);
4592 switch (type) {
4593 case MC_TARGET_PAGE:
4594 page = target.page;
4595 if (isolate_lru_page(page))
4596 goto put;
4597 pc = lookup_page_cgroup(page);
854ffa8d
DN
4598 if (!mem_cgroup_move_account(pc,
4599 mc.from, mc.to, false)) {
4ffef5fe 4600 mc.precharge--;
854ffa8d
DN
4601 /* we uncharge from mc.from later. */
4602 mc.moved_charge++;
4ffef5fe
DN
4603 }
4604 putback_lru_page(page);
4605put: /* is_target_pte_for_mc() gets the page */
4606 put_page(page);
4607 break;
02491447
DN
4608 case MC_TARGET_SWAP:
4609 ent = target.ent;
483c30b5
DN
4610 if (!mem_cgroup_move_swap_account(ent,
4611 mc.from, mc.to, false)) {
02491447 4612 mc.precharge--;
483c30b5
DN
4613 /* we fixup refcnts and charges later. */
4614 mc.moved_swap++;
4615 }
02491447 4616 break;
4ffef5fe
DN
4617 default:
4618 break;
4619 }
4620 }
4621 pte_unmap_unlock(pte - 1, ptl);
4622 cond_resched();
4623
4624 if (addr != end) {
4625 /*
4626 * We have consumed all precharges we got in can_attach().
4627 * We try charge one by one, but don't do any additional
4628 * charges to mc.to if we have failed in charge once in attach()
4629 * phase.
4630 */
854ffa8d 4631 ret = mem_cgroup_do_precharge(1);
4ffef5fe
DN
4632 if (!ret)
4633 goto retry;
4634 }
4635
4636 return ret;
4637}
4638
4639static void mem_cgroup_move_charge(struct mm_struct *mm)
4640{
4641 struct vm_area_struct *vma;
4642
4643 lru_add_drain_all();
4644 down_read(&mm->mmap_sem);
4645 for (vma = mm->mmap; vma; vma = vma->vm_next) {
4646 int ret;
4647 struct mm_walk mem_cgroup_move_charge_walk = {
4648 .pmd_entry = mem_cgroup_move_charge_pte_range,
4649 .mm = mm,
4650 .private = vma,
4651 };
4652 if (is_vm_hugetlb_page(vma))
4653 continue;
4ffef5fe
DN
4654 ret = walk_page_range(vma->vm_start, vma->vm_end,
4655 &mem_cgroup_move_charge_walk);
4656 if (ret)
4657 /*
4658 * means we have consumed all precharges and failed in
4659 * doing additional charge. Just abandon here.
4660 */
4661 break;
4662 }
4663 up_read(&mm->mmap_sem);
7dc74be0
DN
4664}
4665
67e465a7
BS
4666static void mem_cgroup_move_task(struct cgroup_subsys *ss,
4667 struct cgroup *cont,
4668 struct cgroup *old_cont,
be367d09
BB
4669 struct task_struct *p,
4670 bool threadgroup)
67e465a7 4671{
4ffef5fe
DN
4672 struct mm_struct *mm;
4673
4674 if (!mc.to)
4675 /* no need to move charge */
4676 return;
4677
4678 mm = get_task_mm(p);
4679 if (mm) {
4680 mem_cgroup_move_charge(mm);
4681 mmput(mm);
4682 }
4683 mem_cgroup_clear_mc();
67e465a7 4684}
5cfb80a7
DN
4685#else /* !CONFIG_MMU */
4686static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
4687 struct cgroup *cgroup,
4688 struct task_struct *p,
4689 bool threadgroup)
4690{
4691 return 0;
4692}
4693static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
4694 struct cgroup *cgroup,
4695 struct task_struct *p,
4696 bool threadgroup)
4697{
4698}
4699static void mem_cgroup_move_task(struct cgroup_subsys *ss,
4700 struct cgroup *cont,
4701 struct cgroup *old_cont,
4702 struct task_struct *p,
4703 bool threadgroup)
4704{
4705}
4706#endif
67e465a7 4707
8cdea7c0
BS
4708struct cgroup_subsys mem_cgroup_subsys = {
4709 .name = "memory",
4710 .subsys_id = mem_cgroup_subsys_id,
4711 .create = mem_cgroup_create,
df878fb0 4712 .pre_destroy = mem_cgroup_pre_destroy,
8cdea7c0
BS
4713 .destroy = mem_cgroup_destroy,
4714 .populate = mem_cgroup_populate,
7dc74be0
DN
4715 .can_attach = mem_cgroup_can_attach,
4716 .cancel_attach = mem_cgroup_cancel_attach,
67e465a7 4717 .attach = mem_cgroup_move_task,
6d12e2d8 4718 .early_init = 0,
04046e1a 4719 .use_id = 1,
8cdea7c0 4720};
c077719b
KH
4721
4722#ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4723
4724static int __init disable_swap_account(char *s)
4725{
4726 really_do_swap_account = 0;
4727 return 1;
4728}
4729__setup("noswapaccount", disable_swap_account);
4730#endif