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