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