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