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