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