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