memcg: add mem_cgroup_cancel_charge()
[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         if (curr->use_hierarchy)
764                 ret = css_is_ancestor(&curr->css, &mem->css);
765         else
766                 ret = (curr == mem);
767         css_put(&curr->css);
768         return ret;
769 }
770
771 /*
772  * prev_priority control...this will be used in memory reclaim path.
773  */
774 int mem_cgroup_get_reclaim_priority(struct mem_cgroup *mem)
775 {
776         int prev_priority;
777
778         spin_lock(&mem->reclaim_param_lock);
779         prev_priority = mem->prev_priority;
780         spin_unlock(&mem->reclaim_param_lock);
781
782         return prev_priority;
783 }
784
785 void mem_cgroup_note_reclaim_priority(struct mem_cgroup *mem, int priority)
786 {
787         spin_lock(&mem->reclaim_param_lock);
788         if (priority < mem->prev_priority)
789                 mem->prev_priority = priority;
790         spin_unlock(&mem->reclaim_param_lock);
791 }
792
793 void mem_cgroup_record_reclaim_priority(struct mem_cgroup *mem, int priority)
794 {
795         spin_lock(&mem->reclaim_param_lock);
796         mem->prev_priority = priority;
797         spin_unlock(&mem->reclaim_param_lock);
798 }
799
800 static int calc_inactive_ratio(struct mem_cgroup *memcg, unsigned long *present_pages)
801 {
802         unsigned long active;
803         unsigned long inactive;
804         unsigned long gb;
805         unsigned long inactive_ratio;
806
807         inactive = mem_cgroup_get_local_zonestat(memcg, LRU_INACTIVE_ANON);
808         active = mem_cgroup_get_local_zonestat(memcg, LRU_ACTIVE_ANON);
809
810         gb = (inactive + active) >> (30 - PAGE_SHIFT);
811         if (gb)
812                 inactive_ratio = int_sqrt(10 * gb);
813         else
814                 inactive_ratio = 1;
815
816         if (present_pages) {
817                 present_pages[0] = inactive;
818                 present_pages[1] = active;
819         }
820
821         return inactive_ratio;
822 }
823
824 int mem_cgroup_inactive_anon_is_low(struct mem_cgroup *memcg)
825 {
826         unsigned long active;
827         unsigned long inactive;
828         unsigned long present_pages[2];
829         unsigned long inactive_ratio;
830
831         inactive_ratio = calc_inactive_ratio(memcg, present_pages);
832
833         inactive = present_pages[0];
834         active = present_pages[1];
835
836         if (inactive * inactive_ratio < active)
837                 return 1;
838
839         return 0;
840 }
841
842 int mem_cgroup_inactive_file_is_low(struct mem_cgroup *memcg)
843 {
844         unsigned long active;
845         unsigned long inactive;
846
847         inactive = mem_cgroup_get_local_zonestat(memcg, LRU_INACTIVE_FILE);
848         active = mem_cgroup_get_local_zonestat(memcg, LRU_ACTIVE_FILE);
849
850         return (active > inactive);
851 }
852
853 unsigned long mem_cgroup_zone_nr_pages(struct mem_cgroup *memcg,
854                                        struct zone *zone,
855                                        enum lru_list lru)
856 {
857         int nid = zone->zone_pgdat->node_id;
858         int zid = zone_idx(zone);
859         struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
860
861         return MEM_CGROUP_ZSTAT(mz, lru);
862 }
863
864 struct zone_reclaim_stat *mem_cgroup_get_reclaim_stat(struct mem_cgroup *memcg,
865                                                       struct zone *zone)
866 {
867         int nid = zone->zone_pgdat->node_id;
868         int zid = zone_idx(zone);
869         struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
870
871         return &mz->reclaim_stat;
872 }
873
874 struct zone_reclaim_stat *
875 mem_cgroup_get_reclaim_stat_from_page(struct page *page)
876 {
877         struct page_cgroup *pc;
878         struct mem_cgroup_per_zone *mz;
879
880         if (mem_cgroup_disabled())
881                 return NULL;
882
883         pc = lookup_page_cgroup(page);
884         /*
885          * Used bit is set without atomic ops but after smp_wmb().
886          * For making pc->mem_cgroup visible, insert smp_rmb() here.
887          */
888         smp_rmb();
889         if (!PageCgroupUsed(pc))
890                 return NULL;
891
892         mz = page_cgroup_zoneinfo(pc);
893         if (!mz)
894                 return NULL;
895
896         return &mz->reclaim_stat;
897 }
898
899 unsigned long mem_cgroup_isolate_pages(unsigned long nr_to_scan,
900                                         struct list_head *dst,
901                                         unsigned long *scanned, int order,
902                                         int mode, struct zone *z,
903                                         struct mem_cgroup *mem_cont,
904                                         int active, int file)
905 {
906         unsigned long nr_taken = 0;
907         struct page *page;
908         unsigned long scan;
909         LIST_HEAD(pc_list);
910         struct list_head *src;
911         struct page_cgroup *pc, *tmp;
912         int nid = z->zone_pgdat->node_id;
913         int zid = zone_idx(z);
914         struct mem_cgroup_per_zone *mz;
915         int lru = LRU_FILE * file + active;
916         int ret;
917
918         BUG_ON(!mem_cont);
919         mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
920         src = &mz->lists[lru];
921
922         scan = 0;
923         list_for_each_entry_safe_reverse(pc, tmp, src, lru) {
924                 if (scan >= nr_to_scan)
925                         break;
926
927                 page = pc->page;
928                 if (unlikely(!PageCgroupUsed(pc)))
929                         continue;
930                 if (unlikely(!PageLRU(page)))
931                         continue;
932
933                 scan++;
934                 ret = __isolate_lru_page(page, mode, file);
935                 switch (ret) {
936                 case 0:
937                         list_move(&page->lru, dst);
938                         mem_cgroup_del_lru(page);
939                         nr_taken++;
940                         break;
941                 case -EBUSY:
942                         /* we don't affect global LRU but rotate in our LRU */
943                         mem_cgroup_rotate_lru_list(page, page_lru(page));
944                         break;
945                 default:
946                         break;
947                 }
948         }
949
950         *scanned = scan;
951         return nr_taken;
952 }
953
954 #define mem_cgroup_from_res_counter(counter, member)    \
955         container_of(counter, struct mem_cgroup, member)
956
957 static bool mem_cgroup_check_under_limit(struct mem_cgroup *mem)
958 {
959         if (do_swap_account) {
960                 if (res_counter_check_under_limit(&mem->res) &&
961                         res_counter_check_under_limit(&mem->memsw))
962                         return true;
963         } else
964                 if (res_counter_check_under_limit(&mem->res))
965                         return true;
966         return false;
967 }
968
969 static unsigned int get_swappiness(struct mem_cgroup *memcg)
970 {
971         struct cgroup *cgrp = memcg->css.cgroup;
972         unsigned int swappiness;
973
974         /* root ? */
975         if (cgrp->parent == NULL)
976                 return vm_swappiness;
977
978         spin_lock(&memcg->reclaim_param_lock);
979         swappiness = memcg->swappiness;
980         spin_unlock(&memcg->reclaim_param_lock);
981
982         return swappiness;
983 }
984
985 static int mem_cgroup_count_children_cb(struct mem_cgroup *mem, void *data)
986 {
987         int *val = data;
988         (*val)++;
989         return 0;
990 }
991
992 /**
993  * mem_cgroup_print_mem_info: Called from OOM with tasklist_lock held in read mode.
994  * @memcg: The memory cgroup that went over limit
995  * @p: Task that is going to be killed
996  *
997  * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
998  * enabled
999  */
1000 void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1001 {
1002         struct cgroup *task_cgrp;
1003         struct cgroup *mem_cgrp;
1004         /*
1005          * Need a buffer in BSS, can't rely on allocations. The code relies
1006          * on the assumption that OOM is serialized for memory controller.
1007          * If this assumption is broken, revisit this code.
1008          */
1009         static char memcg_name[PATH_MAX];
1010         int ret;
1011
1012         if (!memcg)
1013                 return;
1014
1015
1016         rcu_read_lock();
1017
1018         mem_cgrp = memcg->css.cgroup;
1019         task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
1020
1021         ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
1022         if (ret < 0) {
1023                 /*
1024                  * Unfortunately, we are unable to convert to a useful name
1025                  * But we'll still print out the usage information
1026                  */
1027                 rcu_read_unlock();
1028                 goto done;
1029         }
1030         rcu_read_unlock();
1031
1032         printk(KERN_INFO "Task in %s killed", memcg_name);
1033
1034         rcu_read_lock();
1035         ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
1036         if (ret < 0) {
1037                 rcu_read_unlock();
1038                 goto done;
1039         }
1040         rcu_read_unlock();
1041
1042         /*
1043          * Continues from above, so we don't need an KERN_ level
1044          */
1045         printk(KERN_CONT " as a result of limit of %s\n", memcg_name);
1046 done:
1047
1048         printk(KERN_INFO "memory: usage %llukB, limit %llukB, failcnt %llu\n",
1049                 res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
1050                 res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
1051                 res_counter_read_u64(&memcg->res, RES_FAILCNT));
1052         printk(KERN_INFO "memory+swap: usage %llukB, limit %llukB, "
1053                 "failcnt %llu\n",
1054                 res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
1055                 res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
1056                 res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
1057 }
1058
1059 /*
1060  * This function returns the number of memcg under hierarchy tree. Returns
1061  * 1(self count) if no children.
1062  */
1063 static int mem_cgroup_count_children(struct mem_cgroup *mem)
1064 {
1065         int num = 0;
1066         mem_cgroup_walk_tree(mem, &num, mem_cgroup_count_children_cb);
1067         return num;
1068 }
1069
1070 /*
1071  * Visit the first child (need not be the first child as per the ordering
1072  * of the cgroup list, since we track last_scanned_child) of @mem and use
1073  * that to reclaim free pages from.
1074  */
1075 static struct mem_cgroup *
1076 mem_cgroup_select_victim(struct mem_cgroup *root_mem)
1077 {
1078         struct mem_cgroup *ret = NULL;
1079         struct cgroup_subsys_state *css;
1080         int nextid, found;
1081
1082         if (!root_mem->use_hierarchy) {
1083                 css_get(&root_mem->css);
1084                 ret = root_mem;
1085         }
1086
1087         while (!ret) {
1088                 rcu_read_lock();
1089                 nextid = root_mem->last_scanned_child + 1;
1090                 css = css_get_next(&mem_cgroup_subsys, nextid, &root_mem->css,
1091                                    &found);
1092                 if (css && css_tryget(css))
1093                         ret = container_of(css, struct mem_cgroup, css);
1094
1095                 rcu_read_unlock();
1096                 /* Updates scanning parameter */
1097                 spin_lock(&root_mem->reclaim_param_lock);
1098                 if (!css) {
1099                         /* this means start scan from ID:1 */
1100                         root_mem->last_scanned_child = 0;
1101                 } else
1102                         root_mem->last_scanned_child = found;
1103                 spin_unlock(&root_mem->reclaim_param_lock);
1104         }
1105
1106         return ret;
1107 }
1108
1109 /*
1110  * Scan the hierarchy if needed to reclaim memory. We remember the last child
1111  * we reclaimed from, so that we don't end up penalizing one child extensively
1112  * based on its position in the children list.
1113  *
1114  * root_mem is the original ancestor that we've been reclaim from.
1115  *
1116  * We give up and return to the caller when we visit root_mem twice.
1117  * (other groups can be removed while we're walking....)
1118  *
1119  * If shrink==true, for avoiding to free too much, this returns immedieately.
1120  */
1121 static int mem_cgroup_hierarchical_reclaim(struct mem_cgroup *root_mem,
1122                                                 struct zone *zone,
1123                                                 gfp_t gfp_mask,
1124                                                 unsigned long reclaim_options)
1125 {
1126         struct mem_cgroup *victim;
1127         int ret, total = 0;
1128         int loop = 0;
1129         bool noswap = reclaim_options & MEM_CGROUP_RECLAIM_NOSWAP;
1130         bool shrink = reclaim_options & MEM_CGROUP_RECLAIM_SHRINK;
1131         bool check_soft = reclaim_options & MEM_CGROUP_RECLAIM_SOFT;
1132         unsigned long excess = mem_cgroup_get_excess(root_mem);
1133
1134         /* If memsw_is_minimum==1, swap-out is of-no-use. */
1135         if (root_mem->memsw_is_minimum)
1136                 noswap = true;
1137
1138         while (1) {
1139                 victim = mem_cgroup_select_victim(root_mem);
1140                 if (victim == root_mem) {
1141                         loop++;
1142                         if (loop >= 1)
1143                                 drain_all_stock_async();
1144                         if (loop >= 2) {
1145                                 /*
1146                                  * If we have not been able to reclaim
1147                                  * anything, it might because there are
1148                                  * no reclaimable pages under this hierarchy
1149                                  */
1150                                 if (!check_soft || !total) {
1151                                         css_put(&victim->css);
1152                                         break;
1153                                 }
1154                                 /*
1155                                  * We want to do more targetted reclaim.
1156                                  * excess >> 2 is not to excessive so as to
1157                                  * reclaim too much, nor too less that we keep
1158                                  * coming back to reclaim from this cgroup
1159                                  */
1160                                 if (total >= (excess >> 2) ||
1161                                         (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS)) {
1162                                         css_put(&victim->css);
1163                                         break;
1164                                 }
1165                         }
1166                 }
1167                 if (!mem_cgroup_local_usage(&victim->stat)) {
1168                         /* this cgroup's local usage == 0 */
1169                         css_put(&victim->css);
1170                         continue;
1171                 }
1172                 /* we use swappiness of local cgroup */
1173                 if (check_soft)
1174                         ret = mem_cgroup_shrink_node_zone(victim, gfp_mask,
1175                                 noswap, get_swappiness(victim), zone,
1176                                 zone->zone_pgdat->node_id);
1177                 else
1178                         ret = try_to_free_mem_cgroup_pages(victim, gfp_mask,
1179                                                 noswap, get_swappiness(victim));
1180                 css_put(&victim->css);
1181                 /*
1182                  * At shrinking usage, we can't check we should stop here or
1183                  * reclaim more. It's depends on callers. last_scanned_child
1184                  * will work enough for keeping fairness under tree.
1185                  */
1186                 if (shrink)
1187                         return ret;
1188                 total += ret;
1189                 if (check_soft) {
1190                         if (res_counter_check_under_soft_limit(&root_mem->res))
1191                                 return total;
1192                 } else if (mem_cgroup_check_under_limit(root_mem))
1193                         return 1 + total;
1194         }
1195         return total;
1196 }
1197
1198 bool mem_cgroup_oom_called(struct task_struct *task)
1199 {
1200         bool ret = false;
1201         struct mem_cgroup *mem;
1202         struct mm_struct *mm;
1203
1204         rcu_read_lock();
1205         mm = task->mm;
1206         if (!mm)
1207                 mm = &init_mm;
1208         mem = mem_cgroup_from_task(rcu_dereference(mm->owner));
1209         if (mem && time_before(jiffies, mem->last_oom_jiffies + HZ/10))
1210                 ret = true;
1211         rcu_read_unlock();
1212         return ret;
1213 }
1214
1215 static int record_last_oom_cb(struct mem_cgroup *mem, void *data)
1216 {
1217         mem->last_oom_jiffies = jiffies;
1218         return 0;
1219 }
1220
1221 static void record_last_oom(struct mem_cgroup *mem)
1222 {
1223         mem_cgroup_walk_tree(mem, NULL, record_last_oom_cb);
1224 }
1225
1226 /*
1227  * Currently used to update mapped file statistics, but the routine can be
1228  * generalized to update other statistics as well.
1229  */
1230 void mem_cgroup_update_file_mapped(struct page *page, int val)
1231 {
1232         struct mem_cgroup *mem;
1233         struct mem_cgroup_stat *stat;
1234         struct mem_cgroup_stat_cpu *cpustat;
1235         int cpu;
1236         struct page_cgroup *pc;
1237
1238         pc = lookup_page_cgroup(page);
1239         if (unlikely(!pc))
1240                 return;
1241
1242         lock_page_cgroup(pc);
1243         mem = pc->mem_cgroup;
1244         if (!mem)
1245                 goto done;
1246
1247         if (!PageCgroupUsed(pc))
1248                 goto done;
1249
1250         /*
1251          * Preemption is already disabled, we don't need get_cpu()
1252          */
1253         cpu = smp_processor_id();
1254         stat = &mem->stat;
1255         cpustat = &stat->cpustat[cpu];
1256
1257         __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_FILE_MAPPED, val);
1258 done:
1259         unlock_page_cgroup(pc);
1260 }
1261
1262 /*
1263  * size of first charge trial. "32" comes from vmscan.c's magic value.
1264  * TODO: maybe necessary to use big numbers in big irons.
1265  */
1266 #define CHARGE_SIZE     (32 * PAGE_SIZE)
1267 struct memcg_stock_pcp {
1268         struct mem_cgroup *cached; /* this never be root cgroup */
1269         int charge;
1270         struct work_struct work;
1271 };
1272 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
1273 static atomic_t memcg_drain_count;
1274
1275 /*
1276  * Try to consume stocked charge on this cpu. If success, PAGE_SIZE is consumed
1277  * from local stock and true is returned. If the stock is 0 or charges from a
1278  * cgroup which is not current target, returns false. This stock will be
1279  * refilled.
1280  */
1281 static bool consume_stock(struct mem_cgroup *mem)
1282 {
1283         struct memcg_stock_pcp *stock;
1284         bool ret = true;
1285
1286         stock = &get_cpu_var(memcg_stock);
1287         if (mem == stock->cached && stock->charge)
1288                 stock->charge -= PAGE_SIZE;
1289         else /* need to call res_counter_charge */
1290                 ret = false;
1291         put_cpu_var(memcg_stock);
1292         return ret;
1293 }
1294
1295 /*
1296  * Returns stocks cached in percpu to res_counter and reset cached information.
1297  */
1298 static void drain_stock(struct memcg_stock_pcp *stock)
1299 {
1300         struct mem_cgroup *old = stock->cached;
1301
1302         if (stock->charge) {
1303                 res_counter_uncharge(&old->res, stock->charge);
1304                 if (do_swap_account)
1305                         res_counter_uncharge(&old->memsw, stock->charge);
1306         }
1307         stock->cached = NULL;
1308         stock->charge = 0;
1309 }
1310
1311 /*
1312  * This must be called under preempt disabled or must be called by
1313  * a thread which is pinned to local cpu.
1314  */
1315 static void drain_local_stock(struct work_struct *dummy)
1316 {
1317         struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
1318         drain_stock(stock);
1319 }
1320
1321 /*
1322  * Cache charges(val) which is from res_counter, to local per_cpu area.
1323  * This will be consumed by consumt_stock() function, later.
1324  */
1325 static void refill_stock(struct mem_cgroup *mem, int val)
1326 {
1327         struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
1328
1329         if (stock->cached != mem) { /* reset if necessary */
1330                 drain_stock(stock);
1331                 stock->cached = mem;
1332         }
1333         stock->charge += val;
1334         put_cpu_var(memcg_stock);
1335 }
1336
1337 /*
1338  * Tries to drain stocked charges in other cpus. This function is asynchronous
1339  * and just put a work per cpu for draining localy on each cpu. Caller can
1340  * expects some charges will be back to res_counter later but cannot wait for
1341  * it.
1342  */
1343 static void drain_all_stock_async(void)
1344 {
1345         int cpu;
1346         /* This function is for scheduling "drain" in asynchronous way.
1347          * The result of "drain" is not directly handled by callers. Then,
1348          * if someone is calling drain, we don't have to call drain more.
1349          * Anyway, WORK_STRUCT_PENDING check in queue_work_on() will catch if
1350          * there is a race. We just do loose check here.
1351          */
1352         if (atomic_read(&memcg_drain_count))
1353                 return;
1354         /* Notify other cpus that system-wide "drain" is running */
1355         atomic_inc(&memcg_drain_count);
1356         get_online_cpus();
1357         for_each_online_cpu(cpu) {
1358                 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
1359                 schedule_work_on(cpu, &stock->work);
1360         }
1361         put_online_cpus();
1362         atomic_dec(&memcg_drain_count);
1363         /* We don't wait for flush_work */
1364 }
1365
1366 /* This is a synchronous drain interface. */
1367 static void drain_all_stock_sync(void)
1368 {
1369         /* called when force_empty is called */
1370         atomic_inc(&memcg_drain_count);
1371         schedule_on_each_cpu(drain_local_stock);
1372         atomic_dec(&memcg_drain_count);
1373 }
1374
1375 static int __cpuinit memcg_stock_cpu_callback(struct notifier_block *nb,
1376                                         unsigned long action,
1377                                         void *hcpu)
1378 {
1379         int cpu = (unsigned long)hcpu;
1380         struct memcg_stock_pcp *stock;
1381
1382         if (action != CPU_DEAD)
1383                 return NOTIFY_OK;
1384         stock = &per_cpu(memcg_stock, cpu);
1385         drain_stock(stock);
1386         return NOTIFY_OK;
1387 }
1388
1389 /*
1390  * Unlike exported interface, "oom" parameter is added. if oom==true,
1391  * oom-killer can be invoked.
1392  */
1393 static int __mem_cgroup_try_charge(struct mm_struct *mm,
1394                         gfp_t gfp_mask, struct mem_cgroup **memcg,
1395                         bool oom, struct page *page)
1396 {
1397         struct mem_cgroup *mem, *mem_over_limit;
1398         int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
1399         struct res_counter *fail_res;
1400         int csize = CHARGE_SIZE;
1401
1402         if (unlikely(test_thread_flag(TIF_MEMDIE))) {
1403                 /* Don't account this! */
1404                 *memcg = NULL;
1405                 return 0;
1406         }
1407
1408         /*
1409          * We always charge the cgroup the mm_struct belongs to.
1410          * The mm_struct's mem_cgroup changes on task migration if the
1411          * thread group leader migrates. It's possible that mm is not
1412          * set, if so charge the init_mm (happens for pagecache usage).
1413          */
1414         mem = *memcg;
1415         if (likely(!mem)) {
1416                 mem = try_get_mem_cgroup_from_mm(mm);
1417                 *memcg = mem;
1418         } else {
1419                 css_get(&mem->css);
1420         }
1421         if (unlikely(!mem))
1422                 return 0;
1423
1424         VM_BUG_ON(css_is_removed(&mem->css));
1425         if (mem_cgroup_is_root(mem))
1426                 goto done;
1427
1428         while (1) {
1429                 int ret = 0;
1430                 unsigned long flags = 0;
1431
1432                 if (consume_stock(mem))
1433                         goto charged;
1434
1435                 ret = res_counter_charge(&mem->res, csize, &fail_res);
1436                 if (likely(!ret)) {
1437                         if (!do_swap_account)
1438                                 break;
1439                         ret = res_counter_charge(&mem->memsw, csize, &fail_res);
1440                         if (likely(!ret))
1441                                 break;
1442                         /* mem+swap counter fails */
1443                         res_counter_uncharge(&mem->res, csize);
1444                         flags |= MEM_CGROUP_RECLAIM_NOSWAP;
1445                         mem_over_limit = mem_cgroup_from_res_counter(fail_res,
1446                                                                         memsw);
1447                 } else
1448                         /* mem counter fails */
1449                         mem_over_limit = mem_cgroup_from_res_counter(fail_res,
1450                                                                         res);
1451
1452                 /* reduce request size and retry */
1453                 if (csize > PAGE_SIZE) {
1454                         csize = PAGE_SIZE;
1455                         continue;
1456                 }
1457                 if (!(gfp_mask & __GFP_WAIT))
1458                         goto nomem;
1459
1460                 ret = mem_cgroup_hierarchical_reclaim(mem_over_limit, NULL,
1461                                                 gfp_mask, flags);
1462                 if (ret)
1463                         continue;
1464
1465                 /*
1466                  * try_to_free_mem_cgroup_pages() might not give us a full
1467                  * picture of reclaim. Some pages are reclaimed and might be
1468                  * moved to swap cache or just unmapped from the cgroup.
1469                  * Check the limit again to see if the reclaim reduced the
1470                  * current usage of the cgroup before giving up
1471                  *
1472                  */
1473                 if (mem_cgroup_check_under_limit(mem_over_limit))
1474                         continue;
1475
1476                 if (!nr_retries--) {
1477                         if (oom) {
1478                                 mutex_lock(&memcg_tasklist);
1479                                 mem_cgroup_out_of_memory(mem_over_limit, gfp_mask);
1480                                 mutex_unlock(&memcg_tasklist);
1481                                 record_last_oom(mem_over_limit);
1482                         }
1483                         goto nomem;
1484                 }
1485         }
1486         if (csize > PAGE_SIZE)
1487                 refill_stock(mem, csize - PAGE_SIZE);
1488 charged:
1489         /*
1490          * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
1491          * if they exceeds softlimit.
1492          */
1493         if (mem_cgroup_soft_limit_check(mem))
1494                 mem_cgroup_update_tree(mem, page);
1495 done:
1496         return 0;
1497 nomem:
1498         css_put(&mem->css);
1499         return -ENOMEM;
1500 }
1501
1502 /*
1503  * Somemtimes we have to undo a charge we got by try_charge().
1504  * This function is for that and do uncharge, put css's refcnt.
1505  * gotten by try_charge().
1506  */
1507 static void mem_cgroup_cancel_charge(struct mem_cgroup *mem)
1508 {
1509         if (!mem_cgroup_is_root(mem)) {
1510                 res_counter_uncharge(&mem->res, PAGE_SIZE);
1511                 if (do_swap_account)
1512                         res_counter_uncharge(&mem->memsw, PAGE_SIZE);
1513         }
1514         css_put(&mem->css);
1515 }
1516
1517 /*
1518  * A helper function to get mem_cgroup from ID. must be called under
1519  * rcu_read_lock(). The caller must check css_is_removed() or some if
1520  * it's concern. (dropping refcnt from swap can be called against removed
1521  * memcg.)
1522  */
1523 static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
1524 {
1525         struct cgroup_subsys_state *css;
1526
1527         /* ID 0 is unused ID */
1528         if (!id)
1529                 return NULL;
1530         css = css_lookup(&mem_cgroup_subsys, id);
1531         if (!css)
1532                 return NULL;
1533         return container_of(css, struct mem_cgroup, css);
1534 }
1535
1536 static struct mem_cgroup *try_get_mem_cgroup_from_swapcache(struct page *page)
1537 {
1538         struct mem_cgroup *mem;
1539         struct page_cgroup *pc;
1540         unsigned short id;
1541         swp_entry_t ent;
1542
1543         VM_BUG_ON(!PageLocked(page));
1544
1545         if (!PageSwapCache(page))
1546                 return NULL;
1547
1548         pc = lookup_page_cgroup(page);
1549         lock_page_cgroup(pc);
1550         if (PageCgroupUsed(pc)) {
1551                 mem = pc->mem_cgroup;
1552                 if (mem && !css_tryget(&mem->css))
1553                         mem = NULL;
1554         } else {
1555                 ent.val = page_private(page);
1556                 id = lookup_swap_cgroup(ent);
1557                 rcu_read_lock();
1558                 mem = mem_cgroup_lookup(id);
1559                 if (mem && !css_tryget(&mem->css))
1560                         mem = NULL;
1561                 rcu_read_unlock();
1562         }
1563         unlock_page_cgroup(pc);
1564         return mem;
1565 }
1566
1567 /*
1568  * commit a charge got by __mem_cgroup_try_charge() and makes page_cgroup to be
1569  * USED state. If already USED, uncharge and return.
1570  */
1571
1572 static void __mem_cgroup_commit_charge(struct mem_cgroup *mem,
1573                                      struct page_cgroup *pc,
1574                                      enum charge_type ctype)
1575 {
1576         /* try_charge() can return NULL to *memcg, taking care of it. */
1577         if (!mem)
1578                 return;
1579
1580         lock_page_cgroup(pc);
1581         if (unlikely(PageCgroupUsed(pc))) {
1582                 unlock_page_cgroup(pc);
1583                 mem_cgroup_cancel_charge(mem);
1584                 return;
1585         }
1586
1587         pc->mem_cgroup = mem;
1588         /*
1589          * We access a page_cgroup asynchronously without lock_page_cgroup().
1590          * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
1591          * is accessed after testing USED bit. To make pc->mem_cgroup visible
1592          * before USED bit, we need memory barrier here.
1593          * See mem_cgroup_add_lru_list(), etc.
1594          */
1595         smp_wmb();
1596         switch (ctype) {
1597         case MEM_CGROUP_CHARGE_TYPE_CACHE:
1598         case MEM_CGROUP_CHARGE_TYPE_SHMEM:
1599                 SetPageCgroupCache(pc);
1600                 SetPageCgroupUsed(pc);
1601                 break;
1602         case MEM_CGROUP_CHARGE_TYPE_MAPPED:
1603                 ClearPageCgroupCache(pc);
1604                 SetPageCgroupUsed(pc);
1605                 break;
1606         default:
1607                 break;
1608         }
1609
1610         mem_cgroup_charge_statistics(mem, pc, true);
1611
1612         unlock_page_cgroup(pc);
1613 }
1614
1615 /**
1616  * mem_cgroup_move_account - move account of the page
1617  * @pc: page_cgroup of the page.
1618  * @from: mem_cgroup which the page is moved from.
1619  * @to: mem_cgroup which the page is moved to. @from != @to.
1620  *
1621  * The caller must confirm following.
1622  * - page is not on LRU (isolate_page() is useful.)
1623  *
1624  * returns 0 at success,
1625  * returns -EBUSY when lock is busy or "pc" is unstable.
1626  *
1627  * This function does "uncharge" from old cgroup but doesn't do "charge" to
1628  * new cgroup. It should be done by a caller.
1629  */
1630
1631 static int mem_cgroup_move_account(struct page_cgroup *pc,
1632         struct mem_cgroup *from, struct mem_cgroup *to)
1633 {
1634         struct mem_cgroup_per_zone *from_mz, *to_mz;
1635         int nid, zid;
1636         int ret = -EBUSY;
1637         struct page *page;
1638         int cpu;
1639         struct mem_cgroup_stat *stat;
1640         struct mem_cgroup_stat_cpu *cpustat;
1641
1642         VM_BUG_ON(from == to);
1643         VM_BUG_ON(PageLRU(pc->page));
1644
1645         nid = page_cgroup_nid(pc);
1646         zid = page_cgroup_zid(pc);
1647         from_mz =  mem_cgroup_zoneinfo(from, nid, zid);
1648         to_mz =  mem_cgroup_zoneinfo(to, nid, zid);
1649
1650         if (!trylock_page_cgroup(pc))
1651                 return ret;
1652
1653         if (!PageCgroupUsed(pc))
1654                 goto out;
1655
1656         if (pc->mem_cgroup != from)
1657                 goto out;
1658
1659         if (!mem_cgroup_is_root(from))
1660                 res_counter_uncharge(&from->res, PAGE_SIZE);
1661         mem_cgroup_charge_statistics(from, pc, false);
1662
1663         page = pc->page;
1664         if (page_mapped(page) && !PageAnon(page)) {
1665                 cpu = smp_processor_id();
1666                 /* Update mapped_file data for mem_cgroup "from" */
1667                 stat = &from->stat;
1668                 cpustat = &stat->cpustat[cpu];
1669                 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_FILE_MAPPED,
1670                                                 -1);
1671
1672                 /* Update mapped_file data for mem_cgroup "to" */
1673                 stat = &to->stat;
1674                 cpustat = &stat->cpustat[cpu];
1675                 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_FILE_MAPPED,
1676                                                 1);
1677         }
1678
1679         if (do_swap_account && !mem_cgroup_is_root(from))
1680                 res_counter_uncharge(&from->memsw, PAGE_SIZE);
1681         css_put(&from->css);
1682
1683         css_get(&to->css);
1684         pc->mem_cgroup = to;
1685         mem_cgroup_charge_statistics(to, pc, true);
1686         ret = 0;
1687 out:
1688         unlock_page_cgroup(pc);
1689         /*
1690          * We charges against "to" which may not have any tasks. Then, "to"
1691          * can be under rmdir(). But in current implementation, caller of
1692          * this function is just force_empty() and it's garanteed that
1693          * "to" is never removed. So, we don't check rmdir status here.
1694          */
1695         return ret;
1696 }
1697
1698 /*
1699  * move charges to its parent.
1700  */
1701
1702 static int mem_cgroup_move_parent(struct page_cgroup *pc,
1703                                   struct mem_cgroup *child,
1704                                   gfp_t gfp_mask)
1705 {
1706         struct page *page = pc->page;
1707         struct cgroup *cg = child->css.cgroup;
1708         struct cgroup *pcg = cg->parent;
1709         struct mem_cgroup *parent;
1710         int ret;
1711
1712         /* Is ROOT ? */
1713         if (!pcg)
1714                 return -EINVAL;
1715
1716
1717         parent = mem_cgroup_from_cont(pcg);
1718
1719
1720         ret = __mem_cgroup_try_charge(NULL, gfp_mask, &parent, false, page);
1721         if (ret || !parent)
1722                 return ret;
1723
1724         if (!get_page_unless_zero(page)) {
1725                 ret = -EBUSY;
1726                 goto uncharge;
1727         }
1728
1729         ret = isolate_lru_page(page);
1730
1731         if (ret)
1732                 goto cancel;
1733
1734         ret = mem_cgroup_move_account(pc, child, parent);
1735
1736         putback_lru_page(page);
1737         if (!ret) {
1738                 put_page(page);
1739                 /* drop extra refcnt by try_charge() */
1740                 css_put(&parent->css);
1741                 return 0;
1742         }
1743
1744 cancel:
1745         put_page(page);
1746 uncharge:
1747         mem_cgroup_cancel_charge(parent);
1748         return ret;
1749 }
1750
1751 /*
1752  * Charge the memory controller for page usage.
1753  * Return
1754  * 0 if the charge was successful
1755  * < 0 if the cgroup is over its limit
1756  */
1757 static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
1758                                 gfp_t gfp_mask, enum charge_type ctype,
1759                                 struct mem_cgroup *memcg)
1760 {
1761         struct mem_cgroup *mem;
1762         struct page_cgroup *pc;
1763         int ret;
1764
1765         pc = lookup_page_cgroup(page);
1766         /* can happen at boot */
1767         if (unlikely(!pc))
1768                 return 0;
1769         prefetchw(pc);
1770
1771         mem = memcg;
1772         ret = __mem_cgroup_try_charge(mm, gfp_mask, &mem, true, page);
1773         if (ret || !mem)
1774                 return ret;
1775
1776         __mem_cgroup_commit_charge(mem, pc, ctype);
1777         return 0;
1778 }
1779
1780 int mem_cgroup_newpage_charge(struct page *page,
1781                               struct mm_struct *mm, gfp_t gfp_mask)
1782 {
1783         if (mem_cgroup_disabled())
1784                 return 0;
1785         if (PageCompound(page))
1786                 return 0;
1787         /*
1788          * If already mapped, we don't have to account.
1789          * If page cache, page->mapping has address_space.
1790          * But page->mapping may have out-of-use anon_vma pointer,
1791          * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
1792          * is NULL.
1793          */
1794         if (page_mapped(page) || (page->mapping && !PageAnon(page)))
1795                 return 0;
1796         if (unlikely(!mm))
1797                 mm = &init_mm;
1798         return mem_cgroup_charge_common(page, mm, gfp_mask,
1799                                 MEM_CGROUP_CHARGE_TYPE_MAPPED, NULL);
1800 }
1801
1802 static void
1803 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
1804                                         enum charge_type ctype);
1805
1806 int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
1807                                 gfp_t gfp_mask)
1808 {
1809         struct mem_cgroup *mem = NULL;
1810         int ret;
1811
1812         if (mem_cgroup_disabled())
1813                 return 0;
1814         if (PageCompound(page))
1815                 return 0;
1816         /*
1817          * Corner case handling. This is called from add_to_page_cache()
1818          * in usual. But some FS (shmem) precharges this page before calling it
1819          * and call add_to_page_cache() with GFP_NOWAIT.
1820          *
1821          * For GFP_NOWAIT case, the page may be pre-charged before calling
1822          * add_to_page_cache(). (See shmem.c) check it here and avoid to call
1823          * charge twice. (It works but has to pay a bit larger cost.)
1824          * And when the page is SwapCache, it should take swap information
1825          * into account. This is under lock_page() now.
1826          */
1827         if (!(gfp_mask & __GFP_WAIT)) {
1828                 struct page_cgroup *pc;
1829
1830
1831                 pc = lookup_page_cgroup(page);
1832                 if (!pc)
1833                         return 0;
1834                 lock_page_cgroup(pc);
1835                 if (PageCgroupUsed(pc)) {
1836                         unlock_page_cgroup(pc);
1837                         return 0;
1838                 }
1839                 unlock_page_cgroup(pc);
1840         }
1841
1842         if (unlikely(!mm && !mem))
1843                 mm = &init_mm;
1844
1845         if (page_is_file_cache(page))
1846                 return mem_cgroup_charge_common(page, mm, gfp_mask,
1847                                 MEM_CGROUP_CHARGE_TYPE_CACHE, NULL);
1848
1849         /* shmem */
1850         if (PageSwapCache(page)) {
1851                 ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
1852                 if (!ret)
1853                         __mem_cgroup_commit_charge_swapin(page, mem,
1854                                         MEM_CGROUP_CHARGE_TYPE_SHMEM);
1855         } else
1856                 ret = mem_cgroup_charge_common(page, mm, gfp_mask,
1857                                         MEM_CGROUP_CHARGE_TYPE_SHMEM, mem);
1858
1859         return ret;
1860 }
1861
1862 /*
1863  * While swap-in, try_charge -> commit or cancel, the page is locked.
1864  * And when try_charge() successfully returns, one refcnt to memcg without
1865  * struct page_cgroup is acquired. This refcnt will be consumed by
1866  * "commit()" or removed by "cancel()"
1867  */
1868 int mem_cgroup_try_charge_swapin(struct mm_struct *mm,
1869                                  struct page *page,
1870                                  gfp_t mask, struct mem_cgroup **ptr)
1871 {
1872         struct mem_cgroup *mem;
1873         int ret;
1874
1875         if (mem_cgroup_disabled())
1876                 return 0;
1877
1878         if (!do_swap_account)
1879                 goto charge_cur_mm;
1880         /*
1881          * A racing thread's fault, or swapoff, may have already updated
1882          * the pte, and even removed page from swap cache: in those cases
1883          * do_swap_page()'s pte_same() test will fail; but there's also a
1884          * KSM case which does need to charge the page.
1885          */
1886         if (!PageSwapCache(page))
1887                 goto charge_cur_mm;
1888         mem = try_get_mem_cgroup_from_swapcache(page);
1889         if (!mem)
1890                 goto charge_cur_mm;
1891         *ptr = mem;
1892         ret = __mem_cgroup_try_charge(NULL, mask, ptr, true, page);
1893         /* drop extra refcnt from tryget */
1894         css_put(&mem->css);
1895         return ret;
1896 charge_cur_mm:
1897         if (unlikely(!mm))
1898                 mm = &init_mm;
1899         return __mem_cgroup_try_charge(mm, mask, ptr, true, page);
1900 }
1901
1902 static void
1903 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
1904                                         enum charge_type ctype)
1905 {
1906         struct page_cgroup *pc;
1907
1908         if (mem_cgroup_disabled())
1909                 return;
1910         if (!ptr)
1911                 return;
1912         cgroup_exclude_rmdir(&ptr->css);
1913         pc = lookup_page_cgroup(page);
1914         mem_cgroup_lru_del_before_commit_swapcache(page);
1915         __mem_cgroup_commit_charge(ptr, pc, ctype);
1916         mem_cgroup_lru_add_after_commit_swapcache(page);
1917         /*
1918          * Now swap is on-memory. This means this page may be
1919          * counted both as mem and swap....double count.
1920          * Fix it by uncharging from memsw. Basically, this SwapCache is stable
1921          * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
1922          * may call delete_from_swap_cache() before reach here.
1923          */
1924         if (do_swap_account && PageSwapCache(page)) {
1925                 swp_entry_t ent = {.val = page_private(page)};
1926                 unsigned short id;
1927                 struct mem_cgroup *memcg;
1928
1929                 id = swap_cgroup_record(ent, 0);
1930                 rcu_read_lock();
1931                 memcg = mem_cgroup_lookup(id);
1932                 if (memcg) {
1933                         /*
1934                          * This recorded memcg can be obsolete one. So, avoid
1935                          * calling css_tryget
1936                          */
1937                         if (!mem_cgroup_is_root(memcg))
1938                                 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
1939                         mem_cgroup_swap_statistics(memcg, false);
1940                         mem_cgroup_put(memcg);
1941                 }
1942                 rcu_read_unlock();
1943         }
1944         /*
1945          * At swapin, we may charge account against cgroup which has no tasks.
1946          * So, rmdir()->pre_destroy() can be called while we do this charge.
1947          * In that case, we need to call pre_destroy() again. check it here.
1948          */
1949         cgroup_release_and_wakeup_rmdir(&ptr->css);
1950 }
1951
1952 void mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr)
1953 {
1954         __mem_cgroup_commit_charge_swapin(page, ptr,
1955                                         MEM_CGROUP_CHARGE_TYPE_MAPPED);
1956 }
1957
1958 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *mem)
1959 {
1960         if (mem_cgroup_disabled())
1961                 return;
1962         if (!mem)
1963                 return;
1964         mem_cgroup_cancel_charge(mem);
1965 }
1966
1967 static void
1968 __do_uncharge(struct mem_cgroup *mem, const enum charge_type ctype)
1969 {
1970         struct memcg_batch_info *batch = NULL;
1971         bool uncharge_memsw = true;
1972         /* If swapout, usage of swap doesn't decrease */
1973         if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
1974                 uncharge_memsw = false;
1975         /*
1976          * do_batch > 0 when unmapping pages or inode invalidate/truncate.
1977          * In those cases, all pages freed continously can be expected to be in
1978          * the same cgroup and we have chance to coalesce uncharges.
1979          * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
1980          * because we want to do uncharge as soon as possible.
1981          */
1982         if (!current->memcg_batch.do_batch || test_thread_flag(TIF_MEMDIE))
1983                 goto direct_uncharge;
1984
1985         batch = &current->memcg_batch;
1986         /*
1987          * In usual, we do css_get() when we remember memcg pointer.
1988          * But in this case, we keep res->usage until end of a series of
1989          * uncharges. Then, it's ok to ignore memcg's refcnt.
1990          */
1991         if (!batch->memcg)
1992                 batch->memcg = mem;
1993         /*
1994          * In typical case, batch->memcg == mem. This means we can
1995          * merge a series of uncharges to an uncharge of res_counter.
1996          * If not, we uncharge res_counter ony by one.
1997          */
1998         if (batch->memcg != mem)
1999                 goto direct_uncharge;
2000         /* remember freed charge and uncharge it later */
2001         batch->bytes += PAGE_SIZE;
2002         if (uncharge_memsw)
2003                 batch->memsw_bytes += PAGE_SIZE;
2004         return;
2005 direct_uncharge:
2006         res_counter_uncharge(&mem->res, PAGE_SIZE);
2007         if (uncharge_memsw)
2008                 res_counter_uncharge(&mem->memsw, PAGE_SIZE);
2009         return;
2010 }
2011
2012 /*
2013  * uncharge if !page_mapped(page)
2014  */
2015 static struct mem_cgroup *
2016 __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype)
2017 {
2018         struct page_cgroup *pc;
2019         struct mem_cgroup *mem = NULL;
2020         struct mem_cgroup_per_zone *mz;
2021
2022         if (mem_cgroup_disabled())
2023                 return NULL;
2024
2025         if (PageSwapCache(page))
2026                 return NULL;
2027
2028         /*
2029          * Check if our page_cgroup is valid
2030          */
2031         pc = lookup_page_cgroup(page);
2032         if (unlikely(!pc || !PageCgroupUsed(pc)))
2033                 return NULL;
2034
2035         lock_page_cgroup(pc);
2036
2037         mem = pc->mem_cgroup;
2038
2039         if (!PageCgroupUsed(pc))
2040                 goto unlock_out;
2041
2042         switch (ctype) {
2043         case MEM_CGROUP_CHARGE_TYPE_MAPPED:
2044         case MEM_CGROUP_CHARGE_TYPE_DROP:
2045                 if (page_mapped(page))
2046                         goto unlock_out;
2047                 break;
2048         case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
2049                 if (!PageAnon(page)) {  /* Shared memory */
2050                         if (page->mapping && !page_is_file_cache(page))
2051                                 goto unlock_out;
2052                 } else if (page_mapped(page)) /* Anon */
2053                                 goto unlock_out;
2054                 break;
2055         default:
2056                 break;
2057         }
2058
2059         if (!mem_cgroup_is_root(mem))
2060                 __do_uncharge(mem, ctype);
2061         if (ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2062                 mem_cgroup_swap_statistics(mem, true);
2063         mem_cgroup_charge_statistics(mem, pc, false);
2064
2065         ClearPageCgroupUsed(pc);
2066         /*
2067          * pc->mem_cgroup is not cleared here. It will be accessed when it's
2068          * freed from LRU. This is safe because uncharged page is expected not
2069          * to be reused (freed soon). Exception is SwapCache, it's handled by
2070          * special functions.
2071          */
2072
2073         mz = page_cgroup_zoneinfo(pc);
2074         unlock_page_cgroup(pc);
2075
2076         if (mem_cgroup_soft_limit_check(mem))
2077                 mem_cgroup_update_tree(mem, page);
2078         /* at swapout, this memcg will be accessed to record to swap */
2079         if (ctype != MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2080                 css_put(&mem->css);
2081
2082         return mem;
2083
2084 unlock_out:
2085         unlock_page_cgroup(pc);
2086         return NULL;
2087 }
2088
2089 void mem_cgroup_uncharge_page(struct page *page)
2090 {
2091         /* early check. */
2092         if (page_mapped(page))
2093                 return;
2094         if (page->mapping && !PageAnon(page))
2095                 return;
2096         __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_MAPPED);
2097 }
2098
2099 void mem_cgroup_uncharge_cache_page(struct page *page)
2100 {
2101         VM_BUG_ON(page_mapped(page));
2102         VM_BUG_ON(page->mapping);
2103         __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE);
2104 }
2105
2106 /*
2107  * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
2108  * In that cases, pages are freed continuously and we can expect pages
2109  * are in the same memcg. All these calls itself limits the number of
2110  * pages freed at once, then uncharge_start/end() is called properly.
2111  * This may be called prural(2) times in a context,
2112  */
2113
2114 void mem_cgroup_uncharge_start(void)
2115 {
2116         current->memcg_batch.do_batch++;
2117         /* We can do nest. */
2118         if (current->memcg_batch.do_batch == 1) {
2119                 current->memcg_batch.memcg = NULL;
2120                 current->memcg_batch.bytes = 0;
2121                 current->memcg_batch.memsw_bytes = 0;
2122         }
2123 }
2124
2125 void mem_cgroup_uncharge_end(void)
2126 {
2127         struct memcg_batch_info *batch = &current->memcg_batch;
2128
2129         if (!batch->do_batch)
2130                 return;
2131
2132         batch->do_batch--;
2133         if (batch->do_batch) /* If stacked, do nothing. */
2134                 return;
2135
2136         if (!batch->memcg)
2137                 return;
2138         /*
2139          * This "batch->memcg" is valid without any css_get/put etc...
2140          * bacause we hide charges behind us.
2141          */
2142         if (batch->bytes)
2143                 res_counter_uncharge(&batch->memcg->res, batch->bytes);
2144         if (batch->memsw_bytes)
2145                 res_counter_uncharge(&batch->memcg->memsw, batch->memsw_bytes);
2146         /* forget this pointer (for sanity check) */
2147         batch->memcg = NULL;
2148 }
2149
2150 #ifdef CONFIG_SWAP
2151 /*
2152  * called after __delete_from_swap_cache() and drop "page" account.
2153  * memcg information is recorded to swap_cgroup of "ent"
2154  */
2155 void
2156 mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
2157 {
2158         struct mem_cgroup *memcg;
2159         int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
2160
2161         if (!swapout) /* this was a swap cache but the swap is unused ! */
2162                 ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
2163
2164         memcg = __mem_cgroup_uncharge_common(page, ctype);
2165
2166         /* record memcg information */
2167         if (do_swap_account && swapout && memcg) {
2168                 swap_cgroup_record(ent, css_id(&memcg->css));
2169                 mem_cgroup_get(memcg);
2170         }
2171         if (swapout && memcg)
2172                 css_put(&memcg->css);
2173 }
2174 #endif
2175
2176 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
2177 /*
2178  * called from swap_entry_free(). remove record in swap_cgroup and
2179  * uncharge "memsw" account.
2180  */
2181 void mem_cgroup_uncharge_swap(swp_entry_t ent)
2182 {
2183         struct mem_cgroup *memcg;
2184         unsigned short id;
2185
2186         if (!do_swap_account)
2187                 return;
2188
2189         id = swap_cgroup_record(ent, 0);
2190         rcu_read_lock();
2191         memcg = mem_cgroup_lookup(id);
2192         if (memcg) {
2193                 /*
2194                  * We uncharge this because swap is freed.
2195                  * This memcg can be obsolete one. We avoid calling css_tryget
2196                  */
2197                 if (!mem_cgroup_is_root(memcg))
2198                         res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
2199                 mem_cgroup_swap_statistics(memcg, false);
2200                 mem_cgroup_put(memcg);
2201         }
2202         rcu_read_unlock();
2203 }
2204 #endif
2205
2206 /*
2207  * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
2208  * page belongs to.
2209  */
2210 int mem_cgroup_prepare_migration(struct page *page, struct mem_cgroup **ptr)
2211 {
2212         struct page_cgroup *pc;
2213         struct mem_cgroup *mem = NULL;
2214         int ret = 0;
2215
2216         if (mem_cgroup_disabled())
2217                 return 0;
2218
2219         pc = lookup_page_cgroup(page);
2220         lock_page_cgroup(pc);
2221         if (PageCgroupUsed(pc)) {
2222                 mem = pc->mem_cgroup;
2223                 css_get(&mem->css);
2224         }
2225         unlock_page_cgroup(pc);
2226
2227         if (mem) {
2228                 ret = __mem_cgroup_try_charge(NULL, GFP_KERNEL, &mem, false,
2229                                                 page);
2230                 css_put(&mem->css);
2231         }
2232         *ptr = mem;
2233         return ret;
2234 }
2235
2236 /* remove redundant charge if migration failed*/
2237 void mem_cgroup_end_migration(struct mem_cgroup *mem,
2238                 struct page *oldpage, struct page *newpage)
2239 {
2240         struct page *target, *unused;
2241         struct page_cgroup *pc;
2242         enum charge_type ctype;
2243
2244         if (!mem)
2245                 return;
2246         cgroup_exclude_rmdir(&mem->css);
2247         /* at migration success, oldpage->mapping is NULL. */
2248         if (oldpage->mapping) {
2249                 target = oldpage;
2250                 unused = NULL;
2251         } else {
2252                 target = newpage;
2253                 unused = oldpage;
2254         }
2255
2256         if (PageAnon(target))
2257                 ctype = MEM_CGROUP_CHARGE_TYPE_MAPPED;
2258         else if (page_is_file_cache(target))
2259                 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
2260         else
2261                 ctype = MEM_CGROUP_CHARGE_TYPE_SHMEM;
2262
2263         /* unused page is not on radix-tree now. */
2264         if (unused)
2265                 __mem_cgroup_uncharge_common(unused, ctype);
2266
2267         pc = lookup_page_cgroup(target);
2268         /*
2269          * __mem_cgroup_commit_charge() check PCG_USED bit of page_cgroup.
2270          * So, double-counting is effectively avoided.
2271          */
2272         __mem_cgroup_commit_charge(mem, pc, ctype);
2273
2274         /*
2275          * Both of oldpage and newpage are still under lock_page().
2276          * Then, we don't have to care about race in radix-tree.
2277          * But we have to be careful that this page is unmapped or not.
2278          *
2279          * There is a case for !page_mapped(). At the start of
2280          * migration, oldpage was mapped. But now, it's zapped.
2281          * But we know *target* page is not freed/reused under us.
2282          * mem_cgroup_uncharge_page() does all necessary checks.
2283          */
2284         if (ctype == MEM_CGROUP_CHARGE_TYPE_MAPPED)
2285                 mem_cgroup_uncharge_page(target);
2286         /*
2287          * At migration, we may charge account against cgroup which has no tasks
2288          * So, rmdir()->pre_destroy() can be called while we do this charge.
2289          * In that case, we need to call pre_destroy() again. check it here.
2290          */
2291         cgroup_release_and_wakeup_rmdir(&mem->css);
2292 }
2293
2294 /*
2295  * A call to try to shrink memory usage on charge failure at shmem's swapin.
2296  * Calling hierarchical_reclaim is not enough because we should update
2297  * last_oom_jiffies to prevent pagefault_out_of_memory from invoking global OOM.
2298  * Moreover considering hierarchy, we should reclaim from the mem_over_limit,
2299  * not from the memcg which this page would be charged to.
2300  * try_charge_swapin does all of these works properly.
2301  */
2302 int mem_cgroup_shmem_charge_fallback(struct page *page,
2303                             struct mm_struct *mm,
2304                             gfp_t gfp_mask)
2305 {
2306         struct mem_cgroup *mem = NULL;
2307         int ret;
2308
2309         if (mem_cgroup_disabled())
2310                 return 0;
2311
2312         ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
2313         if (!ret)
2314                 mem_cgroup_cancel_charge_swapin(mem); /* it does !mem check */
2315
2316         return ret;
2317 }
2318
2319 static DEFINE_MUTEX(set_limit_mutex);
2320
2321 static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
2322                                 unsigned long long val)
2323 {
2324         int retry_count;
2325         int progress;
2326         u64 memswlimit;
2327         int ret = 0;
2328         int children = mem_cgroup_count_children(memcg);
2329         u64 curusage, oldusage;
2330
2331         /*
2332          * For keeping hierarchical_reclaim simple, how long we should retry
2333          * is depends on callers. We set our retry-count to be function
2334          * of # of children which we should visit in this loop.
2335          */
2336         retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
2337
2338         oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
2339
2340         while (retry_count) {
2341                 if (signal_pending(current)) {
2342                         ret = -EINTR;
2343                         break;
2344                 }
2345                 /*
2346                  * Rather than hide all in some function, I do this in
2347                  * open coded manner. You see what this really does.
2348                  * We have to guarantee mem->res.limit < mem->memsw.limit.
2349                  */
2350                 mutex_lock(&set_limit_mutex);
2351                 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
2352                 if (memswlimit < val) {
2353                         ret = -EINVAL;
2354                         mutex_unlock(&set_limit_mutex);
2355                         break;
2356                 }
2357                 ret = res_counter_set_limit(&memcg->res, val);
2358                 if (!ret) {
2359                         if (memswlimit == val)
2360                                 memcg->memsw_is_minimum = true;
2361                         else
2362                                 memcg->memsw_is_minimum = false;
2363                 }
2364                 mutex_unlock(&set_limit_mutex);
2365
2366                 if (!ret)
2367                         break;
2368
2369                 progress = mem_cgroup_hierarchical_reclaim(memcg, NULL,
2370                                                 GFP_KERNEL,
2371                                                 MEM_CGROUP_RECLAIM_SHRINK);
2372                 curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
2373                 /* Usage is reduced ? */
2374                 if (curusage >= oldusage)
2375                         retry_count--;
2376                 else
2377                         oldusage = curusage;
2378         }
2379
2380         return ret;
2381 }
2382
2383 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
2384                                         unsigned long long val)
2385 {
2386         int retry_count;
2387         u64 memlimit, oldusage, curusage;
2388         int children = mem_cgroup_count_children(memcg);
2389         int ret = -EBUSY;
2390
2391         /* see mem_cgroup_resize_res_limit */
2392         retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
2393         oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
2394         while (retry_count) {
2395                 if (signal_pending(current)) {
2396                         ret = -EINTR;
2397                         break;
2398                 }
2399                 /*
2400                  * Rather than hide all in some function, I do this in
2401                  * open coded manner. You see what this really does.
2402                  * We have to guarantee mem->res.limit < mem->memsw.limit.
2403                  */
2404                 mutex_lock(&set_limit_mutex);
2405                 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
2406                 if (memlimit > val) {
2407                         ret = -EINVAL;
2408                         mutex_unlock(&set_limit_mutex);
2409                         break;
2410                 }
2411                 ret = res_counter_set_limit(&memcg->memsw, val);
2412                 if (!ret) {
2413                         if (memlimit == val)
2414                                 memcg->memsw_is_minimum = true;
2415                         else
2416                                 memcg->memsw_is_minimum = false;
2417                 }
2418                 mutex_unlock(&set_limit_mutex);
2419
2420                 if (!ret)
2421                         break;
2422
2423                 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
2424                                                 MEM_CGROUP_RECLAIM_NOSWAP |
2425                                                 MEM_CGROUP_RECLAIM_SHRINK);
2426                 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
2427                 /* Usage is reduced ? */
2428                 if (curusage >= oldusage)
2429                         retry_count--;
2430                 else
2431                         oldusage = curusage;
2432         }
2433         return ret;
2434 }
2435
2436 unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
2437                                                 gfp_t gfp_mask, int nid,
2438                                                 int zid)
2439 {
2440         unsigned long nr_reclaimed = 0;
2441         struct mem_cgroup_per_zone *mz, *next_mz = NULL;
2442         unsigned long reclaimed;
2443         int loop = 0;
2444         struct mem_cgroup_tree_per_zone *mctz;
2445         unsigned long long excess;
2446
2447         if (order > 0)
2448                 return 0;
2449
2450         mctz = soft_limit_tree_node_zone(nid, zid);
2451         /*
2452          * This loop can run a while, specially if mem_cgroup's continuously
2453          * keep exceeding their soft limit and putting the system under
2454          * pressure
2455          */
2456         do {
2457                 if (next_mz)
2458                         mz = next_mz;
2459                 else
2460                         mz = mem_cgroup_largest_soft_limit_node(mctz);
2461                 if (!mz)
2462                         break;
2463
2464                 reclaimed = mem_cgroup_hierarchical_reclaim(mz->mem, zone,
2465                                                 gfp_mask,
2466                                                 MEM_CGROUP_RECLAIM_SOFT);
2467                 nr_reclaimed += reclaimed;
2468                 spin_lock(&mctz->lock);
2469
2470                 /*
2471                  * If we failed to reclaim anything from this memory cgroup
2472                  * it is time to move on to the next cgroup
2473                  */
2474                 next_mz = NULL;
2475                 if (!reclaimed) {
2476                         do {
2477                                 /*
2478                                  * Loop until we find yet another one.
2479                                  *
2480                                  * By the time we get the soft_limit lock
2481                                  * again, someone might have aded the
2482                                  * group back on the RB tree. Iterate to
2483                                  * make sure we get a different mem.
2484                                  * mem_cgroup_largest_soft_limit_node returns
2485                                  * NULL if no other cgroup is present on
2486                                  * the tree
2487                                  */
2488                                 next_mz =
2489                                 __mem_cgroup_largest_soft_limit_node(mctz);
2490                                 if (next_mz == mz) {
2491                                         css_put(&next_mz->mem->css);
2492                                         next_mz = NULL;
2493                                 } else /* next_mz == NULL or other memcg */
2494                                         break;
2495                         } while (1);
2496                 }
2497                 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
2498                 excess = res_counter_soft_limit_excess(&mz->mem->res);
2499                 /*
2500                  * One school of thought says that we should not add
2501                  * back the node to the tree if reclaim returns 0.
2502                  * But our reclaim could return 0, simply because due
2503                  * to priority we are exposing a smaller subset of
2504                  * memory to reclaim from. Consider this as a longer
2505                  * term TODO.
2506                  */
2507                 /* If excess == 0, no tree ops */
2508                 __mem_cgroup_insert_exceeded(mz->mem, mz, mctz, excess);
2509                 spin_unlock(&mctz->lock);
2510                 css_put(&mz->mem->css);
2511                 loop++;
2512                 /*
2513                  * Could not reclaim anything and there are no more
2514                  * mem cgroups to try or we seem to be looping without
2515                  * reclaiming anything.
2516                  */
2517                 if (!nr_reclaimed &&
2518                         (next_mz == NULL ||
2519                         loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
2520                         break;
2521         } while (!nr_reclaimed);
2522         if (next_mz)
2523                 css_put(&next_mz->mem->css);
2524         return nr_reclaimed;
2525 }
2526
2527 /*
2528  * This routine traverse page_cgroup in given list and drop them all.
2529  * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
2530  */
2531 static int mem_cgroup_force_empty_list(struct mem_cgroup *mem,
2532                                 int node, int zid, enum lru_list lru)
2533 {
2534         struct zone *zone;
2535         struct mem_cgroup_per_zone *mz;
2536         struct page_cgroup *pc, *busy;
2537         unsigned long flags, loop;
2538         struct list_head *list;
2539         int ret = 0;
2540
2541         zone = &NODE_DATA(node)->node_zones[zid];
2542         mz = mem_cgroup_zoneinfo(mem, node, zid);
2543         list = &mz->lists[lru];
2544
2545         loop = MEM_CGROUP_ZSTAT(mz, lru);
2546         /* give some margin against EBUSY etc...*/
2547         loop += 256;
2548         busy = NULL;
2549         while (loop--) {
2550                 ret = 0;
2551                 spin_lock_irqsave(&zone->lru_lock, flags);
2552                 if (list_empty(list)) {
2553                         spin_unlock_irqrestore(&zone->lru_lock, flags);
2554                         break;
2555                 }
2556                 pc = list_entry(list->prev, struct page_cgroup, lru);
2557                 if (busy == pc) {
2558                         list_move(&pc->lru, list);
2559                         busy = 0;
2560                         spin_unlock_irqrestore(&zone->lru_lock, flags);
2561                         continue;
2562                 }
2563                 spin_unlock_irqrestore(&zone->lru_lock, flags);
2564
2565                 ret = mem_cgroup_move_parent(pc, mem, GFP_KERNEL);
2566                 if (ret == -ENOMEM)
2567                         break;
2568
2569                 if (ret == -EBUSY || ret == -EINVAL) {
2570                         /* found lock contention or "pc" is obsolete. */
2571                         busy = pc;
2572                         cond_resched();
2573                 } else
2574                         busy = NULL;
2575         }
2576
2577         if (!ret && !list_empty(list))
2578                 return -EBUSY;
2579         return ret;
2580 }
2581
2582 /*
2583  * make mem_cgroup's charge to be 0 if there is no task.
2584  * This enables deleting this mem_cgroup.
2585  */
2586 static int mem_cgroup_force_empty(struct mem_cgroup *mem, bool free_all)
2587 {
2588         int ret;
2589         int node, zid, shrink;
2590         int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
2591         struct cgroup *cgrp = mem->css.cgroup;
2592
2593         css_get(&mem->css);
2594
2595         shrink = 0;
2596         /* should free all ? */
2597         if (free_all)
2598                 goto try_to_free;
2599 move_account:
2600         while (mem->res.usage > 0) {
2601                 ret = -EBUSY;
2602                 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
2603                         goto out;
2604                 ret = -EINTR;
2605                 if (signal_pending(current))
2606                         goto out;
2607                 /* This is for making all *used* pages to be on LRU. */
2608                 lru_add_drain_all();
2609                 drain_all_stock_sync();
2610                 ret = 0;
2611                 for_each_node_state(node, N_HIGH_MEMORY) {
2612                         for (zid = 0; !ret && zid < MAX_NR_ZONES; zid++) {
2613                                 enum lru_list l;
2614                                 for_each_lru(l) {
2615                                         ret = mem_cgroup_force_empty_list(mem,
2616                                                         node, zid, l);
2617                                         if (ret)
2618                                                 break;
2619                                 }
2620                         }
2621                         if (ret)
2622                                 break;
2623                 }
2624                 /* it seems parent cgroup doesn't have enough mem */
2625                 if (ret == -ENOMEM)
2626                         goto try_to_free;
2627                 cond_resched();
2628         }
2629         ret = 0;
2630 out:
2631         css_put(&mem->css);
2632         return ret;
2633
2634 try_to_free:
2635         /* returns EBUSY if there is a task or if we come here twice. */
2636         if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children) || shrink) {
2637                 ret = -EBUSY;
2638                 goto out;
2639         }
2640         /* we call try-to-free pages for make this cgroup empty */
2641         lru_add_drain_all();
2642         /* try to free all pages in this cgroup */
2643         shrink = 1;
2644         while (nr_retries && mem->res.usage > 0) {
2645                 int progress;
2646
2647                 if (signal_pending(current)) {
2648                         ret = -EINTR;
2649                         goto out;
2650                 }
2651                 progress = try_to_free_mem_cgroup_pages(mem, GFP_KERNEL,
2652                                                 false, get_swappiness(mem));
2653                 if (!progress) {
2654                         nr_retries--;
2655                         /* maybe some writeback is necessary */
2656                         congestion_wait(BLK_RW_ASYNC, HZ/10);
2657                 }
2658
2659         }
2660         lru_add_drain();
2661         /* try move_account...there may be some *locked* pages. */
2662         if (mem->res.usage)
2663                 goto move_account;
2664         ret = 0;
2665         goto out;
2666 }
2667
2668 int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
2669 {
2670         return mem_cgroup_force_empty(mem_cgroup_from_cont(cont), true);
2671 }
2672
2673
2674 static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
2675 {
2676         return mem_cgroup_from_cont(cont)->use_hierarchy;
2677 }
2678
2679 static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
2680                                         u64 val)
2681 {
2682         int retval = 0;
2683         struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
2684         struct cgroup *parent = cont->parent;
2685         struct mem_cgroup *parent_mem = NULL;
2686
2687         if (parent)
2688                 parent_mem = mem_cgroup_from_cont(parent);
2689
2690         cgroup_lock();
2691         /*
2692          * If parent's use_hierarchy is set, we can't make any modifications
2693          * in the child subtrees. If it is unset, then the change can
2694          * occur, provided the current cgroup has no children.
2695          *
2696          * For the root cgroup, parent_mem is NULL, we allow value to be
2697          * set if there are no children.
2698          */
2699         if ((!parent_mem || !parent_mem->use_hierarchy) &&
2700                                 (val == 1 || val == 0)) {
2701                 if (list_empty(&cont->children))
2702                         mem->use_hierarchy = val;
2703                 else
2704                         retval = -EBUSY;
2705         } else
2706                 retval = -EINVAL;
2707         cgroup_unlock();
2708
2709         return retval;
2710 }
2711
2712 struct mem_cgroup_idx_data {
2713         s64 val;
2714         enum mem_cgroup_stat_index idx;
2715 };
2716
2717 static int
2718 mem_cgroup_get_idx_stat(struct mem_cgroup *mem, void *data)
2719 {
2720         struct mem_cgroup_idx_data *d = data;
2721         d->val += mem_cgroup_read_stat(&mem->stat, d->idx);
2722         return 0;
2723 }
2724
2725 static void
2726 mem_cgroup_get_recursive_idx_stat(struct mem_cgroup *mem,
2727                                 enum mem_cgroup_stat_index idx, s64 *val)
2728 {
2729         struct mem_cgroup_idx_data d;
2730         d.idx = idx;
2731         d.val = 0;
2732         mem_cgroup_walk_tree(mem, &d, mem_cgroup_get_idx_stat);
2733         *val = d.val;
2734 }
2735
2736 static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft)
2737 {
2738         struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
2739         u64 idx_val, val;
2740         int type, name;
2741
2742         type = MEMFILE_TYPE(cft->private);
2743         name = MEMFILE_ATTR(cft->private);
2744         switch (type) {
2745         case _MEM:
2746                 if (name == RES_USAGE && mem_cgroup_is_root(mem)) {
2747                         mem_cgroup_get_recursive_idx_stat(mem,
2748                                 MEM_CGROUP_STAT_CACHE, &idx_val);
2749                         val = idx_val;
2750                         mem_cgroup_get_recursive_idx_stat(mem,
2751                                 MEM_CGROUP_STAT_RSS, &idx_val);
2752                         val += idx_val;
2753                         val <<= PAGE_SHIFT;
2754                 } else
2755                         val = res_counter_read_u64(&mem->res, name);
2756                 break;
2757         case _MEMSWAP:
2758                 if (name == RES_USAGE && mem_cgroup_is_root(mem)) {
2759                         mem_cgroup_get_recursive_idx_stat(mem,
2760                                 MEM_CGROUP_STAT_CACHE, &idx_val);
2761                         val = idx_val;
2762                         mem_cgroup_get_recursive_idx_stat(mem,
2763                                 MEM_CGROUP_STAT_RSS, &idx_val);
2764                         val += idx_val;
2765                         mem_cgroup_get_recursive_idx_stat(mem,
2766                                 MEM_CGROUP_STAT_SWAPOUT, &idx_val);
2767                         val += idx_val;
2768                         val <<= PAGE_SHIFT;
2769                 } else
2770                         val = res_counter_read_u64(&mem->memsw, name);
2771                 break;
2772         default:
2773                 BUG();
2774                 break;
2775         }
2776         return val;
2777 }
2778 /*
2779  * The user of this function is...
2780  * RES_LIMIT.
2781  */
2782 static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
2783                             const char *buffer)
2784 {
2785         struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
2786         int type, name;
2787         unsigned long long val;
2788         int ret;
2789
2790         type = MEMFILE_TYPE(cft->private);
2791         name = MEMFILE_ATTR(cft->private);
2792         switch (name) {
2793         case RES_LIMIT:
2794                 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
2795                         ret = -EINVAL;
2796                         break;
2797                 }
2798                 /* This function does all necessary parse...reuse it */
2799                 ret = res_counter_memparse_write_strategy(buffer, &val);
2800                 if (ret)
2801                         break;
2802                 if (type == _MEM)
2803                         ret = mem_cgroup_resize_limit(memcg, val);
2804                 else
2805                         ret = mem_cgroup_resize_memsw_limit(memcg, val);
2806                 break;
2807         case RES_SOFT_LIMIT:
2808                 ret = res_counter_memparse_write_strategy(buffer, &val);
2809                 if (ret)
2810                         break;
2811                 /*
2812                  * For memsw, soft limits are hard to implement in terms
2813                  * of semantics, for now, we support soft limits for
2814                  * control without swap
2815                  */
2816                 if (type == _MEM)
2817                         ret = res_counter_set_soft_limit(&memcg->res, val);
2818                 else
2819                         ret = -EINVAL;
2820                 break;
2821         default:
2822                 ret = -EINVAL; /* should be BUG() ? */
2823                 break;
2824         }
2825         return ret;
2826 }
2827
2828 static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
2829                 unsigned long long *mem_limit, unsigned long long *memsw_limit)
2830 {
2831         struct cgroup *cgroup;
2832         unsigned long long min_limit, min_memsw_limit, tmp;
2833
2834         min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
2835         min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
2836         cgroup = memcg->css.cgroup;
2837         if (!memcg->use_hierarchy)
2838                 goto out;
2839
2840         while (cgroup->parent) {
2841                 cgroup = cgroup->parent;
2842                 memcg = mem_cgroup_from_cont(cgroup);
2843                 if (!memcg->use_hierarchy)
2844                         break;
2845                 tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
2846                 min_limit = min(min_limit, tmp);
2847                 tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
2848                 min_memsw_limit = min(min_memsw_limit, tmp);
2849         }
2850 out:
2851         *mem_limit = min_limit;
2852         *memsw_limit = min_memsw_limit;
2853         return;
2854 }
2855
2856 static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
2857 {
2858         struct mem_cgroup *mem;
2859         int type, name;
2860
2861         mem = mem_cgroup_from_cont(cont);
2862         type = MEMFILE_TYPE(event);
2863         name = MEMFILE_ATTR(event);
2864         switch (name) {
2865         case RES_MAX_USAGE:
2866                 if (type == _MEM)
2867                         res_counter_reset_max(&mem->res);
2868                 else
2869                         res_counter_reset_max(&mem->memsw);
2870                 break;
2871         case RES_FAILCNT:
2872                 if (type == _MEM)
2873                         res_counter_reset_failcnt(&mem->res);
2874                 else
2875                         res_counter_reset_failcnt(&mem->memsw);
2876                 break;
2877         }
2878
2879         return 0;
2880 }
2881
2882
2883 /* For read statistics */
2884 enum {
2885         MCS_CACHE,
2886         MCS_RSS,
2887         MCS_FILE_MAPPED,
2888         MCS_PGPGIN,
2889         MCS_PGPGOUT,
2890         MCS_SWAP,
2891         MCS_INACTIVE_ANON,
2892         MCS_ACTIVE_ANON,
2893         MCS_INACTIVE_FILE,
2894         MCS_ACTIVE_FILE,
2895         MCS_UNEVICTABLE,
2896         NR_MCS_STAT,
2897 };
2898
2899 struct mcs_total_stat {
2900         s64 stat[NR_MCS_STAT];
2901 };
2902
2903 struct {
2904         char *local_name;
2905         char *total_name;
2906 } memcg_stat_strings[NR_MCS_STAT] = {
2907         {"cache", "total_cache"},
2908         {"rss", "total_rss"},
2909         {"mapped_file", "total_mapped_file"},
2910         {"pgpgin", "total_pgpgin"},
2911         {"pgpgout", "total_pgpgout"},
2912         {"swap", "total_swap"},
2913         {"inactive_anon", "total_inactive_anon"},
2914         {"active_anon", "total_active_anon"},
2915         {"inactive_file", "total_inactive_file"},
2916         {"active_file", "total_active_file"},
2917         {"unevictable", "total_unevictable"}
2918 };
2919
2920
2921 static int mem_cgroup_get_local_stat(struct mem_cgroup *mem, void *data)
2922 {
2923         struct mcs_total_stat *s = data;
2924         s64 val;
2925
2926         /* per cpu stat */
2927         val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_CACHE);
2928         s->stat[MCS_CACHE] += val * PAGE_SIZE;
2929         val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_RSS);
2930         s->stat[MCS_RSS] += val * PAGE_SIZE;
2931         val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_FILE_MAPPED);
2932         s->stat[MCS_FILE_MAPPED] += val * PAGE_SIZE;
2933         val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_PGPGIN_COUNT);
2934         s->stat[MCS_PGPGIN] += val;
2935         val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_PGPGOUT_COUNT);
2936         s->stat[MCS_PGPGOUT] += val;
2937         if (do_swap_account) {
2938                 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_SWAPOUT);
2939                 s->stat[MCS_SWAP] += val * PAGE_SIZE;
2940         }
2941
2942         /* per zone stat */
2943         val = mem_cgroup_get_local_zonestat(mem, LRU_INACTIVE_ANON);
2944         s->stat[MCS_INACTIVE_ANON] += val * PAGE_SIZE;
2945         val = mem_cgroup_get_local_zonestat(mem, LRU_ACTIVE_ANON);
2946         s->stat[MCS_ACTIVE_ANON] += val * PAGE_SIZE;
2947         val = mem_cgroup_get_local_zonestat(mem, LRU_INACTIVE_FILE);
2948         s->stat[MCS_INACTIVE_FILE] += val * PAGE_SIZE;
2949         val = mem_cgroup_get_local_zonestat(mem, LRU_ACTIVE_FILE);
2950         s->stat[MCS_ACTIVE_FILE] += val * PAGE_SIZE;
2951         val = mem_cgroup_get_local_zonestat(mem, LRU_UNEVICTABLE);
2952         s->stat[MCS_UNEVICTABLE] += val * PAGE_SIZE;
2953         return 0;
2954 }
2955
2956 static void
2957 mem_cgroup_get_total_stat(struct mem_cgroup *mem, struct mcs_total_stat *s)
2958 {
2959         mem_cgroup_walk_tree(mem, s, mem_cgroup_get_local_stat);
2960 }
2961
2962 static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft,
2963                                  struct cgroup_map_cb *cb)
2964 {
2965         struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
2966         struct mcs_total_stat mystat;
2967         int i;
2968
2969         memset(&mystat, 0, sizeof(mystat));
2970         mem_cgroup_get_local_stat(mem_cont, &mystat);
2971
2972         for (i = 0; i < NR_MCS_STAT; i++) {
2973                 if (i == MCS_SWAP && !do_swap_account)
2974                         continue;
2975                 cb->fill(cb, memcg_stat_strings[i].local_name, mystat.stat[i]);
2976         }
2977
2978         /* Hierarchical information */
2979         {
2980                 unsigned long long limit, memsw_limit;
2981                 memcg_get_hierarchical_limit(mem_cont, &limit, &memsw_limit);
2982                 cb->fill(cb, "hierarchical_memory_limit", limit);
2983                 if (do_swap_account)
2984                         cb->fill(cb, "hierarchical_memsw_limit", memsw_limit);
2985         }
2986
2987         memset(&mystat, 0, sizeof(mystat));
2988         mem_cgroup_get_total_stat(mem_cont, &mystat);
2989         for (i = 0; i < NR_MCS_STAT; i++) {
2990                 if (i == MCS_SWAP && !do_swap_account)
2991                         continue;
2992                 cb->fill(cb, memcg_stat_strings[i].total_name, mystat.stat[i]);
2993         }
2994
2995 #ifdef CONFIG_DEBUG_VM
2996         cb->fill(cb, "inactive_ratio", calc_inactive_ratio(mem_cont, NULL));
2997
2998         {
2999                 int nid, zid;
3000                 struct mem_cgroup_per_zone *mz;
3001                 unsigned long recent_rotated[2] = {0, 0};
3002                 unsigned long recent_scanned[2] = {0, 0};
3003
3004                 for_each_online_node(nid)
3005                         for (zid = 0; zid < MAX_NR_ZONES; zid++) {
3006                                 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
3007
3008                                 recent_rotated[0] +=
3009                                         mz->reclaim_stat.recent_rotated[0];
3010                                 recent_rotated[1] +=
3011                                         mz->reclaim_stat.recent_rotated[1];
3012                                 recent_scanned[0] +=
3013                                         mz->reclaim_stat.recent_scanned[0];
3014                                 recent_scanned[1] +=
3015                                         mz->reclaim_stat.recent_scanned[1];
3016                         }
3017                 cb->fill(cb, "recent_rotated_anon", recent_rotated[0]);
3018                 cb->fill(cb, "recent_rotated_file", recent_rotated[1]);
3019                 cb->fill(cb, "recent_scanned_anon", recent_scanned[0]);
3020                 cb->fill(cb, "recent_scanned_file", recent_scanned[1]);
3021         }
3022 #endif
3023
3024         return 0;
3025 }
3026
3027 static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
3028 {
3029         struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3030
3031         return get_swappiness(memcg);
3032 }
3033
3034 static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
3035                                        u64 val)
3036 {
3037         struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3038         struct mem_cgroup *parent;
3039
3040         if (val > 100)
3041                 return -EINVAL;
3042
3043         if (cgrp->parent == NULL)
3044                 return -EINVAL;
3045
3046         parent = mem_cgroup_from_cont(cgrp->parent);
3047
3048         cgroup_lock();
3049
3050         /* If under hierarchy, only empty-root can set this value */
3051         if ((parent->use_hierarchy) ||
3052             (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
3053                 cgroup_unlock();
3054                 return -EINVAL;
3055         }
3056
3057         spin_lock(&memcg->reclaim_param_lock);
3058         memcg->swappiness = val;
3059         spin_unlock(&memcg->reclaim_param_lock);
3060
3061         cgroup_unlock();
3062
3063         return 0;
3064 }
3065
3066
3067 static struct cftype mem_cgroup_files[] = {
3068         {
3069                 .name = "usage_in_bytes",
3070                 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
3071                 .read_u64 = mem_cgroup_read,
3072         },
3073         {
3074                 .name = "max_usage_in_bytes",
3075                 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
3076                 .trigger = mem_cgroup_reset,
3077                 .read_u64 = mem_cgroup_read,
3078         },
3079         {
3080                 .name = "limit_in_bytes",
3081                 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
3082                 .write_string = mem_cgroup_write,
3083                 .read_u64 = mem_cgroup_read,
3084         },
3085         {
3086                 .name = "soft_limit_in_bytes",
3087                 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
3088                 .write_string = mem_cgroup_write,
3089                 .read_u64 = mem_cgroup_read,
3090         },
3091         {
3092                 .name = "failcnt",
3093                 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
3094                 .trigger = mem_cgroup_reset,
3095                 .read_u64 = mem_cgroup_read,
3096         },
3097         {
3098                 .name = "stat",
3099                 .read_map = mem_control_stat_show,
3100         },
3101         {
3102                 .name = "force_empty",
3103                 .trigger = mem_cgroup_force_empty_write,
3104         },
3105         {
3106                 .name = "use_hierarchy",
3107                 .write_u64 = mem_cgroup_hierarchy_write,
3108                 .read_u64 = mem_cgroup_hierarchy_read,
3109         },
3110         {
3111                 .name = "swappiness",
3112                 .read_u64 = mem_cgroup_swappiness_read,
3113                 .write_u64 = mem_cgroup_swappiness_write,
3114         },
3115 };
3116
3117 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3118 static struct cftype memsw_cgroup_files[] = {
3119         {
3120                 .name = "memsw.usage_in_bytes",
3121                 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
3122                 .read_u64 = mem_cgroup_read,
3123         },
3124         {
3125                 .name = "memsw.max_usage_in_bytes",
3126                 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
3127                 .trigger = mem_cgroup_reset,
3128                 .read_u64 = mem_cgroup_read,
3129         },
3130         {
3131                 .name = "memsw.limit_in_bytes",
3132                 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
3133                 .write_string = mem_cgroup_write,
3134                 .read_u64 = mem_cgroup_read,
3135         },
3136         {
3137                 .name = "memsw.failcnt",
3138                 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
3139                 .trigger = mem_cgroup_reset,
3140                 .read_u64 = mem_cgroup_read,
3141         },
3142 };
3143
3144 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
3145 {
3146         if (!do_swap_account)
3147                 return 0;
3148         return cgroup_add_files(cont, ss, memsw_cgroup_files,
3149                                 ARRAY_SIZE(memsw_cgroup_files));
3150 };
3151 #else
3152 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
3153 {
3154         return 0;
3155 }
3156 #endif
3157
3158 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
3159 {
3160         struct mem_cgroup_per_node *pn;
3161         struct mem_cgroup_per_zone *mz;
3162         enum lru_list l;
3163         int zone, tmp = node;
3164         /*
3165          * This routine is called against possible nodes.
3166          * But it's BUG to call kmalloc() against offline node.
3167          *
3168          * TODO: this routine can waste much memory for nodes which will
3169          *       never be onlined. It's better to use memory hotplug callback
3170          *       function.
3171          */
3172         if (!node_state(node, N_NORMAL_MEMORY))
3173                 tmp = -1;
3174         pn = kmalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
3175         if (!pn)
3176                 return 1;
3177
3178         mem->info.nodeinfo[node] = pn;
3179         memset(pn, 0, sizeof(*pn));
3180
3181         for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3182                 mz = &pn->zoneinfo[zone];
3183                 for_each_lru(l)
3184                         INIT_LIST_HEAD(&mz->lists[l]);
3185                 mz->usage_in_excess = 0;
3186                 mz->on_tree = false;
3187                 mz->mem = mem;
3188         }
3189         return 0;
3190 }
3191
3192 static void free_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
3193 {
3194         kfree(mem->info.nodeinfo[node]);
3195 }
3196
3197 static int mem_cgroup_size(void)
3198 {
3199         int cpustat_size = nr_cpu_ids * sizeof(struct mem_cgroup_stat_cpu);
3200         return sizeof(struct mem_cgroup) + cpustat_size;
3201 }
3202
3203 static struct mem_cgroup *mem_cgroup_alloc(void)
3204 {
3205         struct mem_cgroup *mem;
3206         int size = mem_cgroup_size();
3207
3208         if (size < PAGE_SIZE)
3209                 mem = kmalloc(size, GFP_KERNEL);
3210         else
3211                 mem = vmalloc(size);
3212
3213         if (mem)
3214                 memset(mem, 0, size);
3215         return mem;
3216 }
3217
3218 /*
3219  * At destroying mem_cgroup, references from swap_cgroup can remain.
3220  * (scanning all at force_empty is too costly...)
3221  *
3222  * Instead of clearing all references at force_empty, we remember
3223  * the number of reference from swap_cgroup and free mem_cgroup when
3224  * it goes down to 0.
3225  *
3226  * Removal of cgroup itself succeeds regardless of refs from swap.
3227  */
3228
3229 static void __mem_cgroup_free(struct mem_cgroup *mem)
3230 {
3231         int node;
3232
3233         mem_cgroup_remove_from_trees(mem);
3234         free_css_id(&mem_cgroup_subsys, &mem->css);
3235
3236         for_each_node_state(node, N_POSSIBLE)
3237                 free_mem_cgroup_per_zone_info(mem, node);
3238
3239         if (mem_cgroup_size() < PAGE_SIZE)
3240                 kfree(mem);
3241         else
3242                 vfree(mem);
3243 }
3244
3245 static void mem_cgroup_get(struct mem_cgroup *mem)
3246 {
3247         atomic_inc(&mem->refcnt);
3248 }
3249
3250 static void mem_cgroup_put(struct mem_cgroup *mem)
3251 {
3252         if (atomic_dec_and_test(&mem->refcnt)) {
3253                 struct mem_cgroup *parent = parent_mem_cgroup(mem);
3254                 __mem_cgroup_free(mem);
3255                 if (parent)
3256                         mem_cgroup_put(parent);
3257         }
3258 }
3259
3260 /*
3261  * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
3262  */
3263 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem)
3264 {
3265         if (!mem->res.parent)
3266                 return NULL;
3267         return mem_cgroup_from_res_counter(mem->res.parent, res);
3268 }
3269
3270 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3271 static void __init enable_swap_cgroup(void)
3272 {
3273         if (!mem_cgroup_disabled() && really_do_swap_account)
3274                 do_swap_account = 1;
3275 }
3276 #else
3277 static void __init enable_swap_cgroup(void)
3278 {
3279 }
3280 #endif
3281
3282 static int mem_cgroup_soft_limit_tree_init(void)
3283 {
3284         struct mem_cgroup_tree_per_node *rtpn;
3285         struct mem_cgroup_tree_per_zone *rtpz;
3286         int tmp, node, zone;
3287
3288         for_each_node_state(node, N_POSSIBLE) {
3289                 tmp = node;
3290                 if (!node_state(node, N_NORMAL_MEMORY))
3291                         tmp = -1;
3292                 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
3293                 if (!rtpn)
3294                         return 1;
3295
3296                 soft_limit_tree.rb_tree_per_node[node] = rtpn;
3297
3298                 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3299                         rtpz = &rtpn->rb_tree_per_zone[zone];
3300                         rtpz->rb_root = RB_ROOT;
3301                         spin_lock_init(&rtpz->lock);
3302                 }
3303         }
3304         return 0;
3305 }
3306
3307 static struct cgroup_subsys_state * __ref
3308 mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
3309 {
3310         struct mem_cgroup *mem, *parent;
3311         long error = -ENOMEM;
3312         int node;
3313
3314         mem = mem_cgroup_alloc();
3315         if (!mem)
3316                 return ERR_PTR(error);
3317
3318         for_each_node_state(node, N_POSSIBLE)
3319                 if (alloc_mem_cgroup_per_zone_info(mem, node))
3320                         goto free_out;
3321
3322         /* root ? */
3323         if (cont->parent == NULL) {
3324                 int cpu;
3325                 enable_swap_cgroup();
3326                 parent = NULL;
3327                 root_mem_cgroup = mem;
3328                 if (mem_cgroup_soft_limit_tree_init())
3329                         goto free_out;
3330                 for_each_possible_cpu(cpu) {
3331                         struct memcg_stock_pcp *stock =
3332                                                 &per_cpu(memcg_stock, cpu);
3333                         INIT_WORK(&stock->work, drain_local_stock);
3334                 }
3335                 hotcpu_notifier(memcg_stock_cpu_callback, 0);
3336
3337         } else {
3338                 parent = mem_cgroup_from_cont(cont->parent);
3339                 mem->use_hierarchy = parent->use_hierarchy;
3340         }
3341
3342         if (parent && parent->use_hierarchy) {
3343                 res_counter_init(&mem->res, &parent->res);
3344                 res_counter_init(&mem->memsw, &parent->memsw);
3345                 /*
3346                  * We increment refcnt of the parent to ensure that we can
3347                  * safely access it on res_counter_charge/uncharge.
3348                  * This refcnt will be decremented when freeing this
3349                  * mem_cgroup(see mem_cgroup_put).
3350                  */
3351                 mem_cgroup_get(parent);
3352         } else {
3353                 res_counter_init(&mem->res, NULL);
3354                 res_counter_init(&mem->memsw, NULL);
3355         }
3356         mem->last_scanned_child = 0;
3357         spin_lock_init(&mem->reclaim_param_lock);
3358
3359         if (parent)
3360                 mem->swappiness = get_swappiness(parent);
3361         atomic_set(&mem->refcnt, 1);
3362         return &mem->css;
3363 free_out:
3364         __mem_cgroup_free(mem);
3365         root_mem_cgroup = NULL;
3366         return ERR_PTR(error);
3367 }
3368
3369 static int mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
3370                                         struct cgroup *cont)
3371 {
3372         struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
3373
3374         return mem_cgroup_force_empty(mem, false);
3375 }
3376
3377 static void mem_cgroup_destroy(struct cgroup_subsys *ss,
3378                                 struct cgroup *cont)
3379 {
3380         struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
3381
3382         mem_cgroup_put(mem);
3383 }
3384
3385 static int mem_cgroup_populate(struct cgroup_subsys *ss,
3386                                 struct cgroup *cont)
3387 {
3388         int ret;
3389
3390         ret = cgroup_add_files(cont, ss, mem_cgroup_files,
3391                                 ARRAY_SIZE(mem_cgroup_files));
3392
3393         if (!ret)
3394                 ret = register_memsw_files(cont, ss);
3395         return ret;
3396 }
3397
3398 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
3399                                 struct cgroup *cont,
3400                                 struct cgroup *old_cont,
3401                                 struct task_struct *p,
3402                                 bool threadgroup)
3403 {
3404         mutex_lock(&memcg_tasklist);
3405         /*
3406          * FIXME: It's better to move charges of this process from old
3407          * memcg to new memcg. But it's just on TODO-List now.
3408          */
3409         mutex_unlock(&memcg_tasklist);
3410 }
3411
3412 struct cgroup_subsys mem_cgroup_subsys = {
3413         .name = "memory",
3414         .subsys_id = mem_cgroup_subsys_id,
3415         .create = mem_cgroup_create,
3416         .pre_destroy = mem_cgroup_pre_destroy,
3417         .destroy = mem_cgroup_destroy,
3418         .populate = mem_cgroup_populate,
3419         .attach = mem_cgroup_move_task,
3420         .early_init = 0,
3421         .use_id = 1,
3422 };
3423
3424 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3425
3426 static int __init disable_swap_account(char *s)
3427 {
3428         really_do_swap_account = 0;
3429         return 1;
3430 }
3431 __setup("noswapaccount", disable_swap_account);
3432 #endif