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