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