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