]> git.karo-electronics.de Git - karo-tx-linux.git/blob - mm/memcontrol.c
mm: memcg: remove optimization of keeping the root_mem_cgroup LRU lists empty
[karo-tx-linux.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/export.h>
37 #include <linux/mutex.h>
38 #include <linux/rbtree.h>
39 #include <linux/slab.h>
40 #include <linux/swap.h>
41 #include <linux/swapops.h>
42 #include <linux/spinlock.h>
43 #include <linux/eventfd.h>
44 #include <linux/sort.h>
45 #include <linux/fs.h>
46 #include <linux/seq_file.h>
47 #include <linux/vmalloc.h>
48 #include <linux/mm_inline.h>
49 #include <linux/page_cgroup.h>
50 #include <linux/cpu.h>
51 #include <linux/oom.h>
52 #include "internal.h"
53
54 #include <asm/uaccess.h>
55
56 #include <trace/events/vmscan.h>
57
58 struct cgroup_subsys mem_cgroup_subsys __read_mostly;
59 #define MEM_CGROUP_RECLAIM_RETRIES      5
60 struct mem_cgroup *root_mem_cgroup __read_mostly;
61
62 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
63 /* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
64 int do_swap_account __read_mostly;
65
66 /* for remember boot option*/
67 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP_ENABLED
68 static int really_do_swap_account __initdata = 1;
69 #else
70 static int really_do_swap_account __initdata = 0;
71 #endif
72
73 #else
74 #define do_swap_account         (0)
75 #endif
76
77
78 /*
79  * Statistics for memory cgroup.
80  */
81 enum mem_cgroup_stat_index {
82         /*
83          * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
84          */
85         MEM_CGROUP_STAT_CACHE,     /* # of pages charged as cache */
86         MEM_CGROUP_STAT_RSS,       /* # of pages charged as anon rss */
87         MEM_CGROUP_STAT_FILE_MAPPED,  /* # of pages charged as file rss */
88         MEM_CGROUP_STAT_SWAPOUT, /* # of pages, swapped out */
89         MEM_CGROUP_STAT_DATA, /* end of data requires synchronization */
90         MEM_CGROUP_ON_MOVE,     /* someone is moving account between groups */
91         MEM_CGROUP_STAT_NSTATS,
92 };
93
94 enum mem_cgroup_events_index {
95         MEM_CGROUP_EVENTS_PGPGIN,       /* # of pages paged in */
96         MEM_CGROUP_EVENTS_PGPGOUT,      /* # of pages paged out */
97         MEM_CGROUP_EVENTS_COUNT,        /* # of pages paged in/out */
98         MEM_CGROUP_EVENTS_PGFAULT,      /* # of page-faults */
99         MEM_CGROUP_EVENTS_PGMAJFAULT,   /* # of major page-faults */
100         MEM_CGROUP_EVENTS_NSTATS,
101 };
102 /*
103  * Per memcg event counter is incremented at every pagein/pageout. With THP,
104  * it will be incremated by the number of pages. This counter is used for
105  * for trigger some periodic events. This is straightforward and better
106  * than using jiffies etc. to handle periodic memcg event.
107  */
108 enum mem_cgroup_events_target {
109         MEM_CGROUP_TARGET_THRESH,
110         MEM_CGROUP_TARGET_SOFTLIMIT,
111         MEM_CGROUP_TARGET_NUMAINFO,
112         MEM_CGROUP_NTARGETS,
113 };
114 #define THRESHOLDS_EVENTS_TARGET (128)
115 #define SOFTLIMIT_EVENTS_TARGET (1024)
116 #define NUMAINFO_EVENTS_TARGET  (1024)
117
118 struct mem_cgroup_stat_cpu {
119         long count[MEM_CGROUP_STAT_NSTATS];
120         unsigned long events[MEM_CGROUP_EVENTS_NSTATS];
121         unsigned long targets[MEM_CGROUP_NTARGETS];
122 };
123
124 struct mem_cgroup_reclaim_iter {
125         /* css_id of the last scanned hierarchy member */
126         int position;
127         /* scan generation, increased every round-trip */
128         unsigned int generation;
129 };
130
131 /*
132  * per-zone information in memory controller.
133  */
134 struct mem_cgroup_per_zone {
135         /*
136          * spin_lock to protect the per cgroup LRU
137          */
138         struct list_head        lists[NR_LRU_LISTS];
139         unsigned long           count[NR_LRU_LISTS];
140
141         struct mem_cgroup_reclaim_iter reclaim_iter[DEF_PRIORITY + 1];
142
143         struct zone_reclaim_stat reclaim_stat;
144         struct rb_node          tree_node;      /* RB tree node */
145         unsigned long long      usage_in_excess;/* Set to the value by which */
146                                                 /* the soft limit is exceeded*/
147         bool                    on_tree;
148         struct mem_cgroup       *mem;           /* Back pointer, we cannot */
149                                                 /* use container_of        */
150 };
151 /* Macro for accessing counter */
152 #define MEM_CGROUP_ZSTAT(mz, idx)       ((mz)->count[(idx)])
153
154 struct mem_cgroup_per_node {
155         struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
156 };
157
158 struct mem_cgroup_lru_info {
159         struct mem_cgroup_per_node *nodeinfo[MAX_NUMNODES];
160 };
161
162 /*
163  * Cgroups above their limits are maintained in a RB-Tree, independent of
164  * their hierarchy representation
165  */
166
167 struct mem_cgroup_tree_per_zone {
168         struct rb_root rb_root;
169         spinlock_t lock;
170 };
171
172 struct mem_cgroup_tree_per_node {
173         struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
174 };
175
176 struct mem_cgroup_tree {
177         struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
178 };
179
180 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
181
182 struct mem_cgroup_threshold {
183         struct eventfd_ctx *eventfd;
184         u64 threshold;
185 };
186
187 /* For threshold */
188 struct mem_cgroup_threshold_ary {
189         /* An array index points to threshold just below usage. */
190         int current_threshold;
191         /* Size of entries[] */
192         unsigned int size;
193         /* Array of thresholds */
194         struct mem_cgroup_threshold entries[0];
195 };
196
197 struct mem_cgroup_thresholds {
198         /* Primary thresholds array */
199         struct mem_cgroup_threshold_ary *primary;
200         /*
201          * Spare threshold array.
202          * This is needed to make mem_cgroup_unregister_event() "never fail".
203          * It must be able to store at least primary->size - 1 entries.
204          */
205         struct mem_cgroup_threshold_ary *spare;
206 };
207
208 /* for OOM */
209 struct mem_cgroup_eventfd_list {
210         struct list_head list;
211         struct eventfd_ctx *eventfd;
212 };
213
214 static void mem_cgroup_threshold(struct mem_cgroup *memcg);
215 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
216
217 /*
218  * The memory controller data structure. The memory controller controls both
219  * page cache and RSS per cgroup. We would eventually like to provide
220  * statistics based on the statistics developed by Rik Van Riel for clock-pro,
221  * to help the administrator determine what knobs to tune.
222  *
223  * TODO: Add a water mark for the memory controller. Reclaim will begin when
224  * we hit the water mark. May be even add a low water mark, such that
225  * no reclaim occurs from a cgroup at it's low water mark, this is
226  * a feature that will be implemented much later in the future.
227  */
228 struct mem_cgroup {
229         struct cgroup_subsys_state css;
230         /*
231          * the counter to account for memory usage
232          */
233         struct res_counter res;
234         /*
235          * the counter to account for mem+swap usage.
236          */
237         struct res_counter memsw;
238         /*
239          * Per cgroup active and inactive list, similar to the
240          * per zone LRU lists.
241          */
242         struct mem_cgroup_lru_info info;
243         int last_scanned_node;
244 #if MAX_NUMNODES > 1
245         nodemask_t      scan_nodes;
246         atomic_t        numainfo_events;
247         atomic_t        numainfo_updating;
248 #endif
249         /*
250          * Should the accounting and control be hierarchical, per subtree?
251          */
252         bool use_hierarchy;
253
254         bool            oom_lock;
255         atomic_t        under_oom;
256
257         atomic_t        refcnt;
258
259         int     swappiness;
260         /* OOM-Killer disable */
261         int             oom_kill_disable;
262
263         /* set when res.limit == memsw.limit */
264         bool            memsw_is_minimum;
265
266         /* protect arrays of thresholds */
267         struct mutex thresholds_lock;
268
269         /* thresholds for memory usage. RCU-protected */
270         struct mem_cgroup_thresholds thresholds;
271
272         /* thresholds for mem+swap usage. RCU-protected */
273         struct mem_cgroup_thresholds memsw_thresholds;
274
275         /* For oom notifier event fd */
276         struct list_head oom_notify;
277
278         /*
279          * Should we move charges of a task when a task is moved into this
280          * mem_cgroup ? And what type of charges should we move ?
281          */
282         unsigned long   move_charge_at_immigrate;
283         /*
284          * percpu counter.
285          */
286         struct mem_cgroup_stat_cpu *stat;
287         /*
288          * used when a cpu is offlined or other synchronizations
289          * See mem_cgroup_read_stat().
290          */
291         struct mem_cgroup_stat_cpu nocpu_base;
292         spinlock_t pcp_counter_lock;
293 };
294
295 /* Stuffs for move charges at task migration. */
296 /*
297  * Types of charges to be moved. "move_charge_at_immitgrate" is treated as a
298  * left-shifted bitmap of these types.
299  */
300 enum move_type {
301         MOVE_CHARGE_TYPE_ANON,  /* private anonymous page and swap of it */
302         MOVE_CHARGE_TYPE_FILE,  /* file page(including tmpfs) and swap of it */
303         NR_MOVE_TYPE,
304 };
305
306 /* "mc" and its members are protected by cgroup_mutex */
307 static struct move_charge_struct {
308         spinlock_t        lock; /* for from, to */
309         struct mem_cgroup *from;
310         struct mem_cgroup *to;
311         unsigned long precharge;
312         unsigned long moved_charge;
313         unsigned long moved_swap;
314         struct task_struct *moving_task;        /* a task moving charges */
315         wait_queue_head_t waitq;                /* a waitq for other context */
316 } mc = {
317         .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
318         .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
319 };
320
321 static bool move_anon(void)
322 {
323         return test_bit(MOVE_CHARGE_TYPE_ANON,
324                                         &mc.to->move_charge_at_immigrate);
325 }
326
327 static bool move_file(void)
328 {
329         return test_bit(MOVE_CHARGE_TYPE_FILE,
330                                         &mc.to->move_charge_at_immigrate);
331 }
332
333 /*
334  * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
335  * limit reclaim to prevent infinite loops, if they ever occur.
336  */
337 #define MEM_CGROUP_MAX_RECLAIM_LOOPS            (100)
338 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS (2)
339
340 enum charge_type {
341         MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
342         MEM_CGROUP_CHARGE_TYPE_MAPPED,
343         MEM_CGROUP_CHARGE_TYPE_SHMEM,   /* used by page migration of shmem */
344         MEM_CGROUP_CHARGE_TYPE_FORCE,   /* used by force_empty */
345         MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
346         MEM_CGROUP_CHARGE_TYPE_DROP,    /* a page was unused swap cache */
347         NR_CHARGE_TYPE,
348 };
349
350 /* for encoding cft->private value on file */
351 #define _MEM                    (0)
352 #define _MEMSWAP                (1)
353 #define _OOM_TYPE               (2)
354 #define MEMFILE_PRIVATE(x, val) (((x) << 16) | (val))
355 #define MEMFILE_TYPE(val)       (((val) >> 16) & 0xffff)
356 #define MEMFILE_ATTR(val)       ((val) & 0xffff)
357 /* Used for OOM nofiier */
358 #define OOM_CONTROL             (0)
359
360 /*
361  * Reclaim flags for mem_cgroup_hierarchical_reclaim
362  */
363 #define MEM_CGROUP_RECLAIM_NOSWAP_BIT   0x0
364 #define MEM_CGROUP_RECLAIM_NOSWAP       (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
365 #define MEM_CGROUP_RECLAIM_SHRINK_BIT   0x1
366 #define MEM_CGROUP_RECLAIM_SHRINK       (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
367
368 static void mem_cgroup_get(struct mem_cgroup *memcg);
369 static void mem_cgroup_put(struct mem_cgroup *memcg);
370 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg);
371 static void drain_all_stock_async(struct mem_cgroup *memcg);
372
373 static struct mem_cgroup_per_zone *
374 mem_cgroup_zoneinfo(struct mem_cgroup *memcg, int nid, int zid)
375 {
376         return &memcg->info.nodeinfo[nid]->zoneinfo[zid];
377 }
378
379 struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *memcg)
380 {
381         return &memcg->css;
382 }
383
384 static struct mem_cgroup_per_zone *
385 page_cgroup_zoneinfo(struct mem_cgroup *memcg, struct page *page)
386 {
387         int nid = page_to_nid(page);
388         int zid = page_zonenum(page);
389
390         return mem_cgroup_zoneinfo(memcg, nid, zid);
391 }
392
393 static struct mem_cgroup_tree_per_zone *
394 soft_limit_tree_node_zone(int nid, int zid)
395 {
396         return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
397 }
398
399 static struct mem_cgroup_tree_per_zone *
400 soft_limit_tree_from_page(struct page *page)
401 {
402         int nid = page_to_nid(page);
403         int zid = page_zonenum(page);
404
405         return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
406 }
407
408 static void
409 __mem_cgroup_insert_exceeded(struct mem_cgroup *memcg,
410                                 struct mem_cgroup_per_zone *mz,
411                                 struct mem_cgroup_tree_per_zone *mctz,
412                                 unsigned long long new_usage_in_excess)
413 {
414         struct rb_node **p = &mctz->rb_root.rb_node;
415         struct rb_node *parent = NULL;
416         struct mem_cgroup_per_zone *mz_node;
417
418         if (mz->on_tree)
419                 return;
420
421         mz->usage_in_excess = new_usage_in_excess;
422         if (!mz->usage_in_excess)
423                 return;
424         while (*p) {
425                 parent = *p;
426                 mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
427                                         tree_node);
428                 if (mz->usage_in_excess < mz_node->usage_in_excess)
429                         p = &(*p)->rb_left;
430                 /*
431                  * We can't avoid mem cgroups that are over their soft
432                  * limit by the same amount
433                  */
434                 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
435                         p = &(*p)->rb_right;
436         }
437         rb_link_node(&mz->tree_node, parent, p);
438         rb_insert_color(&mz->tree_node, &mctz->rb_root);
439         mz->on_tree = true;
440 }
441
442 static void
443 __mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
444                                 struct mem_cgroup_per_zone *mz,
445                                 struct mem_cgroup_tree_per_zone *mctz)
446 {
447         if (!mz->on_tree)
448                 return;
449         rb_erase(&mz->tree_node, &mctz->rb_root);
450         mz->on_tree = false;
451 }
452
453 static void
454 mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
455                                 struct mem_cgroup_per_zone *mz,
456                                 struct mem_cgroup_tree_per_zone *mctz)
457 {
458         spin_lock(&mctz->lock);
459         __mem_cgroup_remove_exceeded(memcg, mz, mctz);
460         spin_unlock(&mctz->lock);
461 }
462
463
464 static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
465 {
466         unsigned long long excess;
467         struct mem_cgroup_per_zone *mz;
468         struct mem_cgroup_tree_per_zone *mctz;
469         int nid = page_to_nid(page);
470         int zid = page_zonenum(page);
471         mctz = soft_limit_tree_from_page(page);
472
473         /*
474          * Necessary to update all ancestors when hierarchy is used.
475          * because their event counter is not touched.
476          */
477         for (; memcg; memcg = parent_mem_cgroup(memcg)) {
478                 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
479                 excess = res_counter_soft_limit_excess(&memcg->res);
480                 /*
481                  * We have to update the tree if mz is on RB-tree or
482                  * mem is over its softlimit.
483                  */
484                 if (excess || mz->on_tree) {
485                         spin_lock(&mctz->lock);
486                         /* if on-tree, remove it */
487                         if (mz->on_tree)
488                                 __mem_cgroup_remove_exceeded(memcg, mz, mctz);
489                         /*
490                          * Insert again. mz->usage_in_excess will be updated.
491                          * If excess is 0, no tree ops.
492                          */
493                         __mem_cgroup_insert_exceeded(memcg, mz, mctz, excess);
494                         spin_unlock(&mctz->lock);
495                 }
496         }
497 }
498
499 static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
500 {
501         int node, zone;
502         struct mem_cgroup_per_zone *mz;
503         struct mem_cgroup_tree_per_zone *mctz;
504
505         for_each_node_state(node, N_POSSIBLE) {
506                 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
507                         mz = mem_cgroup_zoneinfo(memcg, node, zone);
508                         mctz = soft_limit_tree_node_zone(node, zone);
509                         mem_cgroup_remove_exceeded(memcg, mz, mctz);
510                 }
511         }
512 }
513
514 static struct mem_cgroup_per_zone *
515 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
516 {
517         struct rb_node *rightmost = NULL;
518         struct mem_cgroup_per_zone *mz;
519
520 retry:
521         mz = NULL;
522         rightmost = rb_last(&mctz->rb_root);
523         if (!rightmost)
524                 goto done;              /* Nothing to reclaim from */
525
526         mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
527         /*
528          * Remove the node now but someone else can add it back,
529          * we will to add it back at the end of reclaim to its correct
530          * position in the tree.
531          */
532         __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
533         if (!res_counter_soft_limit_excess(&mz->mem->res) ||
534                 !css_tryget(&mz->mem->css))
535                 goto retry;
536 done:
537         return mz;
538 }
539
540 static struct mem_cgroup_per_zone *
541 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
542 {
543         struct mem_cgroup_per_zone *mz;
544
545         spin_lock(&mctz->lock);
546         mz = __mem_cgroup_largest_soft_limit_node(mctz);
547         spin_unlock(&mctz->lock);
548         return mz;
549 }
550
551 /*
552  * Implementation Note: reading percpu statistics for memcg.
553  *
554  * Both of vmstat[] and percpu_counter has threshold and do periodic
555  * synchronization to implement "quick" read. There are trade-off between
556  * reading cost and precision of value. Then, we may have a chance to implement
557  * a periodic synchronizion of counter in memcg's counter.
558  *
559  * But this _read() function is used for user interface now. The user accounts
560  * memory usage by memory cgroup and he _always_ requires exact value because
561  * he accounts memory. Even if we provide quick-and-fuzzy read, we always
562  * have to visit all online cpus and make sum. So, for now, unnecessary
563  * synchronization is not implemented. (just implemented for cpu hotplug)
564  *
565  * If there are kernel internal actions which can make use of some not-exact
566  * value, and reading all cpu value can be performance bottleneck in some
567  * common workload, threashold and synchonization as vmstat[] should be
568  * implemented.
569  */
570 static long mem_cgroup_read_stat(struct mem_cgroup *memcg,
571                                  enum mem_cgroup_stat_index idx)
572 {
573         long val = 0;
574         int cpu;
575
576         get_online_cpus();
577         for_each_online_cpu(cpu)
578                 val += per_cpu(memcg->stat->count[idx], cpu);
579 #ifdef CONFIG_HOTPLUG_CPU
580         spin_lock(&memcg->pcp_counter_lock);
581         val += memcg->nocpu_base.count[idx];
582         spin_unlock(&memcg->pcp_counter_lock);
583 #endif
584         put_online_cpus();
585         return val;
586 }
587
588 static void mem_cgroup_swap_statistics(struct mem_cgroup *memcg,
589                                          bool charge)
590 {
591         int val = (charge) ? 1 : -1;
592         this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_SWAPOUT], val);
593 }
594
595 void mem_cgroup_pgfault(struct mem_cgroup *memcg, int val)
596 {
597         this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_PGFAULT], val);
598 }
599
600 void mem_cgroup_pgmajfault(struct mem_cgroup *memcg, int val)
601 {
602         this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_PGMAJFAULT], val);
603 }
604
605 static unsigned long mem_cgroup_read_events(struct mem_cgroup *memcg,
606                                             enum mem_cgroup_events_index idx)
607 {
608         unsigned long val = 0;
609         int cpu;
610
611         for_each_online_cpu(cpu)
612                 val += per_cpu(memcg->stat->events[idx], cpu);
613 #ifdef CONFIG_HOTPLUG_CPU
614         spin_lock(&memcg->pcp_counter_lock);
615         val += memcg->nocpu_base.events[idx];
616         spin_unlock(&memcg->pcp_counter_lock);
617 #endif
618         return val;
619 }
620
621 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
622                                          bool file, int nr_pages)
623 {
624         preempt_disable();
625
626         if (file)
627                 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_CACHE],
628                                 nr_pages);
629         else
630                 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS],
631                                 nr_pages);
632
633         /* pagein of a big page is an event. So, ignore page size */
634         if (nr_pages > 0)
635                 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGIN]);
636         else {
637                 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGOUT]);
638                 nr_pages = -nr_pages; /* for event */
639         }
640
641         __this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_COUNT], nr_pages);
642
643         preempt_enable();
644 }
645
646 unsigned long
647 mem_cgroup_zone_nr_lru_pages(struct mem_cgroup *memcg, int nid, int zid,
648                         unsigned int lru_mask)
649 {
650         struct mem_cgroup_per_zone *mz;
651         enum lru_list l;
652         unsigned long ret = 0;
653
654         mz = mem_cgroup_zoneinfo(memcg, nid, zid);
655
656         for_each_lru(l) {
657                 if (BIT(l) & lru_mask)
658                         ret += MEM_CGROUP_ZSTAT(mz, l);
659         }
660         return ret;
661 }
662
663 static unsigned long
664 mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
665                         int nid, unsigned int lru_mask)
666 {
667         u64 total = 0;
668         int zid;
669
670         for (zid = 0; zid < MAX_NR_ZONES; zid++)
671                 total += mem_cgroup_zone_nr_lru_pages(memcg,
672                                                 nid, zid, lru_mask);
673
674         return total;
675 }
676
677 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
678                         unsigned int lru_mask)
679 {
680         int nid;
681         u64 total = 0;
682
683         for_each_node_state(nid, N_HIGH_MEMORY)
684                 total += mem_cgroup_node_nr_lru_pages(memcg, nid, lru_mask);
685         return total;
686 }
687
688 static bool __memcg_event_check(struct mem_cgroup *memcg, int target)
689 {
690         unsigned long val, next;
691
692         val = __this_cpu_read(memcg->stat->events[MEM_CGROUP_EVENTS_COUNT]);
693         next = __this_cpu_read(memcg->stat->targets[target]);
694         /* from time_after() in jiffies.h */
695         return ((long)next - (long)val < 0);
696 }
697
698 static void __mem_cgroup_target_update(struct mem_cgroup *memcg, int target)
699 {
700         unsigned long val, next;
701
702         val = __this_cpu_read(memcg->stat->events[MEM_CGROUP_EVENTS_COUNT]);
703
704         switch (target) {
705         case MEM_CGROUP_TARGET_THRESH:
706                 next = val + THRESHOLDS_EVENTS_TARGET;
707                 break;
708         case MEM_CGROUP_TARGET_SOFTLIMIT:
709                 next = val + SOFTLIMIT_EVENTS_TARGET;
710                 break;
711         case MEM_CGROUP_TARGET_NUMAINFO:
712                 next = val + NUMAINFO_EVENTS_TARGET;
713                 break;
714         default:
715                 return;
716         }
717
718         __this_cpu_write(memcg->stat->targets[target], next);
719 }
720
721 /*
722  * Check events in order.
723  *
724  */
725 static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
726 {
727         preempt_disable();
728         /* threshold event is triggered in finer grain than soft limit */
729         if (unlikely(__memcg_event_check(memcg, MEM_CGROUP_TARGET_THRESH))) {
730                 mem_cgroup_threshold(memcg);
731                 __mem_cgroup_target_update(memcg, MEM_CGROUP_TARGET_THRESH);
732                 if (unlikely(__memcg_event_check(memcg,
733                              MEM_CGROUP_TARGET_SOFTLIMIT))) {
734                         mem_cgroup_update_tree(memcg, page);
735                         __mem_cgroup_target_update(memcg,
736                                                    MEM_CGROUP_TARGET_SOFTLIMIT);
737                 }
738 #if MAX_NUMNODES > 1
739                 if (unlikely(__memcg_event_check(memcg,
740                         MEM_CGROUP_TARGET_NUMAINFO))) {
741                         atomic_inc(&memcg->numainfo_events);
742                         __mem_cgroup_target_update(memcg,
743                                 MEM_CGROUP_TARGET_NUMAINFO);
744                 }
745 #endif
746         }
747         preempt_enable();
748 }
749
750 static struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
751 {
752         return container_of(cgroup_subsys_state(cont,
753                                 mem_cgroup_subsys_id), struct mem_cgroup,
754                                 css);
755 }
756
757 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
758 {
759         /*
760          * mm_update_next_owner() may clear mm->owner to NULL
761          * if it races with swapoff, page migration, etc.
762          * So this can be called with p == NULL.
763          */
764         if (unlikely(!p))
765                 return NULL;
766
767         return container_of(task_subsys_state(p, mem_cgroup_subsys_id),
768                                 struct mem_cgroup, css);
769 }
770
771 struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
772 {
773         struct mem_cgroup *memcg = NULL;
774
775         if (!mm)
776                 return NULL;
777         /*
778          * Because we have no locks, mm->owner's may be being moved to other
779          * cgroup. We use css_tryget() here even if this looks
780          * pessimistic (rather than adding locks here).
781          */
782         rcu_read_lock();
783         do {
784                 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
785                 if (unlikely(!memcg))
786                         break;
787         } while (!css_tryget(&memcg->css));
788         rcu_read_unlock();
789         return memcg;
790 }
791
792 /**
793  * mem_cgroup_iter - iterate over memory cgroup hierarchy
794  * @root: hierarchy root
795  * @prev: previously returned memcg, NULL on first invocation
796  * @reclaim: cookie for shared reclaim walks, NULL for full walks
797  *
798  * Returns references to children of the hierarchy below @root, or
799  * @root itself, or %NULL after a full round-trip.
800  *
801  * Caller must pass the return value in @prev on subsequent
802  * invocations for reference counting, or use mem_cgroup_iter_break()
803  * to cancel a hierarchy walk before the round-trip is complete.
804  *
805  * Reclaimers can specify a zone and a priority level in @reclaim to
806  * divide up the memcgs in the hierarchy among all concurrent
807  * reclaimers operating on the same zone and priority.
808  */
809 struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
810                                    struct mem_cgroup *prev,
811                                    struct mem_cgroup_reclaim_cookie *reclaim)
812 {
813         struct mem_cgroup *memcg = NULL;
814         int id = 0;
815
816         if (mem_cgroup_disabled())
817                 return NULL;
818
819         if (!root)
820                 root = root_mem_cgroup;
821
822         if (prev && !reclaim)
823                 id = css_id(&prev->css);
824
825         if (prev && prev != root)
826                 css_put(&prev->css);
827
828         if (!root->use_hierarchy && root != root_mem_cgroup) {
829                 if (prev)
830                         return NULL;
831                 return root;
832         }
833
834         while (!memcg) {
835                 struct mem_cgroup_reclaim_iter *uninitialized_var(iter);
836                 struct cgroup_subsys_state *css;
837
838                 if (reclaim) {
839                         int nid = zone_to_nid(reclaim->zone);
840                         int zid = zone_idx(reclaim->zone);
841                         struct mem_cgroup_per_zone *mz;
842
843                         mz = mem_cgroup_zoneinfo(root, nid, zid);
844                         iter = &mz->reclaim_iter[reclaim->priority];
845                         if (prev && reclaim->generation != iter->generation)
846                                 return NULL;
847                         id = iter->position;
848                 }
849
850                 rcu_read_lock();
851                 css = css_get_next(&mem_cgroup_subsys, id + 1, &root->css, &id);
852                 if (css) {
853                         if (css == &root->css || css_tryget(css))
854                                 memcg = container_of(css,
855                                                      struct mem_cgroup, css);
856                 } else
857                         id = 0;
858                 rcu_read_unlock();
859
860                 if (reclaim) {
861                         iter->position = id;
862                         if (!css)
863                                 iter->generation++;
864                         else if (!prev && memcg)
865                                 reclaim->generation = iter->generation;
866                 }
867
868                 if (prev && !css)
869                         return NULL;
870         }
871         return memcg;
872 }
873
874 /**
875  * mem_cgroup_iter_break - abort a hierarchy walk prematurely
876  * @root: hierarchy root
877  * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
878  */
879 void mem_cgroup_iter_break(struct mem_cgroup *root,
880                            struct mem_cgroup *prev)
881 {
882         if (!root)
883                 root = root_mem_cgroup;
884         if (prev && prev != root)
885                 css_put(&prev->css);
886 }
887
888 /*
889  * Iteration constructs for visiting all cgroups (under a tree).  If
890  * loops are exited prematurely (break), mem_cgroup_iter_break() must
891  * be used for reference counting.
892  */
893 #define for_each_mem_cgroup_tree(iter, root)            \
894         for (iter = mem_cgroup_iter(root, NULL, NULL);  \
895              iter != NULL;                              \
896              iter = mem_cgroup_iter(root, iter, NULL))
897
898 #define for_each_mem_cgroup(iter)                       \
899         for (iter = mem_cgroup_iter(NULL, NULL, NULL);  \
900              iter != NULL;                              \
901              iter = mem_cgroup_iter(NULL, iter, NULL))
902
903 static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg)
904 {
905         return (memcg == root_mem_cgroup);
906 }
907
908 void mem_cgroup_count_vm_event(struct mm_struct *mm, enum vm_event_item idx)
909 {
910         struct mem_cgroup *memcg;
911
912         if (!mm)
913                 return;
914
915         rcu_read_lock();
916         memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
917         if (unlikely(!memcg))
918                 goto out;
919
920         switch (idx) {
921         case PGMAJFAULT:
922                 mem_cgroup_pgmajfault(memcg, 1);
923                 break;
924         case PGFAULT:
925                 mem_cgroup_pgfault(memcg, 1);
926                 break;
927         default:
928                 BUG();
929         }
930 out:
931         rcu_read_unlock();
932 }
933 EXPORT_SYMBOL(mem_cgroup_count_vm_event);
934
935 /*
936  * Following LRU functions are allowed to be used without PCG_LOCK.
937  * Operations are called by routine of global LRU independently from memcg.
938  * What we have to take care of here is validness of pc->mem_cgroup.
939  *
940  * Changes to pc->mem_cgroup happens when
941  * 1. charge
942  * 2. moving account
943  * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
944  * It is added to LRU before charge.
945  * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
946  * When moving account, the page is not on LRU. It's isolated.
947  */
948
949 void mem_cgroup_del_lru_list(struct page *page, enum lru_list lru)
950 {
951         struct page_cgroup *pc;
952         struct mem_cgroup_per_zone *mz;
953
954         if (mem_cgroup_disabled())
955                 return;
956         pc = lookup_page_cgroup(page);
957         /* can happen while we handle swapcache. */
958         if (!TestClearPageCgroupAcctLRU(pc))
959                 return;
960         VM_BUG_ON(!pc->mem_cgroup);
961         /*
962          * We don't check PCG_USED bit. It's cleared when the "page" is finally
963          * removed from global LRU.
964          */
965         mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
966         /* huge page split is done under lru_lock. so, we have no races. */
967         MEM_CGROUP_ZSTAT(mz, lru) -= 1 << compound_order(page);
968         VM_BUG_ON(list_empty(&pc->lru));
969         list_del_init(&pc->lru);
970 }
971
972 void mem_cgroup_del_lru(struct page *page)
973 {
974         mem_cgroup_del_lru_list(page, page_lru(page));
975 }
976
977 /*
978  * Writeback is about to end against a page which has been marked for immediate
979  * reclaim.  If it still appears to be reclaimable, move it to the tail of the
980  * inactive list.
981  */
982 void mem_cgroup_rotate_reclaimable_page(struct page *page)
983 {
984         struct mem_cgroup_per_zone *mz;
985         struct page_cgroup *pc;
986         enum lru_list lru = page_lru(page);
987
988         if (mem_cgroup_disabled())
989                 return;
990
991         pc = lookup_page_cgroup(page);
992         /* unused page is not rotated. */
993         if (!PageCgroupUsed(pc))
994                 return;
995         /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
996         smp_rmb();
997         mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
998         list_move_tail(&pc->lru, &mz->lists[lru]);
999 }
1000
1001 void mem_cgroup_rotate_lru_list(struct page *page, enum lru_list lru)
1002 {
1003         struct mem_cgroup_per_zone *mz;
1004         struct page_cgroup *pc;
1005
1006         if (mem_cgroup_disabled())
1007                 return;
1008
1009         pc = lookup_page_cgroup(page);
1010         /* unused page is not rotated. */
1011         if (!PageCgroupUsed(pc))
1012                 return;
1013         /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1014         smp_rmb();
1015         mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
1016         list_move(&pc->lru, &mz->lists[lru]);
1017 }
1018
1019 void mem_cgroup_add_lru_list(struct page *page, enum lru_list lru)
1020 {
1021         struct page_cgroup *pc;
1022         struct mem_cgroup_per_zone *mz;
1023
1024         if (mem_cgroup_disabled())
1025                 return;
1026         pc = lookup_page_cgroup(page);
1027         VM_BUG_ON(PageCgroupAcctLRU(pc));
1028         /*
1029          * putback:                             charge:
1030          * SetPageLRU                           SetPageCgroupUsed
1031          * smp_mb                               smp_mb
1032          * PageCgroupUsed && add to memcg LRU   PageLRU && add to memcg LRU
1033          *
1034          * Ensure that one of the two sides adds the page to the memcg
1035          * LRU during a race.
1036          */
1037         smp_mb();
1038         if (!PageCgroupUsed(pc))
1039                 return;
1040         /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1041         smp_rmb();
1042         mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
1043         /* huge page split is done under lru_lock. so, we have no races. */
1044         MEM_CGROUP_ZSTAT(mz, lru) += 1 << compound_order(page);
1045         SetPageCgroupAcctLRU(pc);
1046         list_add(&pc->lru, &mz->lists[lru]);
1047 }
1048
1049 /*
1050  * At handling SwapCache and other FUSE stuff, pc->mem_cgroup may be changed
1051  * while it's linked to lru because the page may be reused after it's fully
1052  * uncharged. To handle that, unlink page_cgroup from LRU when charge it again.
1053  * It's done under lock_page and expected that zone->lru_lock isnever held.
1054  */
1055 static void mem_cgroup_lru_del_before_commit(struct page *page)
1056 {
1057         unsigned long flags;
1058         struct zone *zone = page_zone(page);
1059         struct page_cgroup *pc = lookup_page_cgroup(page);
1060
1061         /*
1062          * Doing this check without taking ->lru_lock seems wrong but this
1063          * is safe. Because if page_cgroup's USED bit is unset, the page
1064          * will not be added to any memcg's LRU. If page_cgroup's USED bit is
1065          * set, the commit after this will fail, anyway.
1066          * This all charge/uncharge is done under some mutual execustion.
1067          * So, we don't need to taking care of changes in USED bit.
1068          */
1069         if (likely(!PageLRU(page)))
1070                 return;
1071
1072         spin_lock_irqsave(&zone->lru_lock, flags);
1073         /*
1074          * Forget old LRU when this page_cgroup is *not* used. This Used bit
1075          * is guarded by lock_page() because the page is SwapCache.
1076          */
1077         if (!PageCgroupUsed(pc))
1078                 mem_cgroup_del_lru_list(page, page_lru(page));
1079         spin_unlock_irqrestore(&zone->lru_lock, flags);
1080 }
1081
1082 static void mem_cgroup_lru_add_after_commit(struct page *page)
1083 {
1084         unsigned long flags;
1085         struct zone *zone = page_zone(page);
1086         struct page_cgroup *pc = lookup_page_cgroup(page);
1087         /*
1088          * putback:                             charge:
1089          * SetPageLRU                           SetPageCgroupUsed
1090          * smp_mb                               smp_mb
1091          * PageCgroupUsed && add to memcg LRU   PageLRU && add to memcg LRU
1092          *
1093          * Ensure that one of the two sides adds the page to the memcg
1094          * LRU during a race.
1095          */
1096         smp_mb();
1097         /* taking care of that the page is added to LRU while we commit it */
1098         if (likely(!PageLRU(page)))
1099                 return;
1100         spin_lock_irqsave(&zone->lru_lock, flags);
1101         /* link when the page is linked to LRU but page_cgroup isn't */
1102         if (PageLRU(page) && !PageCgroupAcctLRU(pc))
1103                 mem_cgroup_add_lru_list(page, page_lru(page));
1104         spin_unlock_irqrestore(&zone->lru_lock, flags);
1105 }
1106
1107
1108 void mem_cgroup_move_lists(struct page *page,
1109                            enum lru_list from, enum lru_list to)
1110 {
1111         if (mem_cgroup_disabled())
1112                 return;
1113         mem_cgroup_del_lru_list(page, from);
1114         mem_cgroup_add_lru_list(page, to);
1115 }
1116
1117 /*
1118  * Checks whether given mem is same or in the root_mem_cgroup's
1119  * hierarchy subtree
1120  */
1121 static bool mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
1122                 struct mem_cgroup *memcg)
1123 {
1124         if (root_memcg != memcg) {
1125                 return (root_memcg->use_hierarchy &&
1126                         css_is_ancestor(&memcg->css, &root_memcg->css));
1127         }
1128
1129         return true;
1130 }
1131
1132 int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *memcg)
1133 {
1134         int ret;
1135         struct mem_cgroup *curr = NULL;
1136         struct task_struct *p;
1137
1138         p = find_lock_task_mm(task);
1139         if (!p)
1140                 return 0;
1141         curr = try_get_mem_cgroup_from_mm(p->mm);
1142         task_unlock(p);
1143         if (!curr)
1144                 return 0;
1145         /*
1146          * We should check use_hierarchy of "memcg" not "curr". Because checking
1147          * use_hierarchy of "curr" here make this function true if hierarchy is
1148          * enabled in "curr" and "curr" is a child of "memcg" in *cgroup*
1149          * hierarchy(even if use_hierarchy is disabled in "memcg").
1150          */
1151         ret = mem_cgroup_same_or_subtree(memcg, curr);
1152         css_put(&curr->css);
1153         return ret;
1154 }
1155
1156 int mem_cgroup_inactive_anon_is_low(struct mem_cgroup *memcg, struct zone *zone)
1157 {
1158         unsigned long inactive_ratio;
1159         int nid = zone_to_nid(zone);
1160         int zid = zone_idx(zone);
1161         unsigned long inactive;
1162         unsigned long active;
1163         unsigned long gb;
1164
1165         inactive = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1166                                                 BIT(LRU_INACTIVE_ANON));
1167         active = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1168                                               BIT(LRU_ACTIVE_ANON));
1169
1170         gb = (inactive + active) >> (30 - PAGE_SHIFT);
1171         if (gb)
1172                 inactive_ratio = int_sqrt(10 * gb);
1173         else
1174                 inactive_ratio = 1;
1175
1176         return inactive * inactive_ratio < active;
1177 }
1178
1179 int mem_cgroup_inactive_file_is_low(struct mem_cgroup *memcg, struct zone *zone)
1180 {
1181         unsigned long active;
1182         unsigned long inactive;
1183         int zid = zone_idx(zone);
1184         int nid = zone_to_nid(zone);
1185
1186         inactive = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1187                                                 BIT(LRU_INACTIVE_FILE));
1188         active = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1189                                               BIT(LRU_ACTIVE_FILE));
1190
1191         return (active > inactive);
1192 }
1193
1194 struct zone_reclaim_stat *mem_cgroup_get_reclaim_stat(struct mem_cgroup *memcg,
1195                                                       struct zone *zone)
1196 {
1197         int nid = zone_to_nid(zone);
1198         int zid = zone_idx(zone);
1199         struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
1200
1201         return &mz->reclaim_stat;
1202 }
1203
1204 struct zone_reclaim_stat *
1205 mem_cgroup_get_reclaim_stat_from_page(struct page *page)
1206 {
1207         struct page_cgroup *pc;
1208         struct mem_cgroup_per_zone *mz;
1209
1210         if (mem_cgroup_disabled())
1211                 return NULL;
1212
1213         pc = lookup_page_cgroup(page);
1214         if (!PageCgroupUsed(pc))
1215                 return NULL;
1216         /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1217         smp_rmb();
1218         mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
1219         return &mz->reclaim_stat;
1220 }
1221
1222 unsigned long mem_cgroup_isolate_pages(unsigned long nr_to_scan,
1223                                         struct list_head *dst,
1224                                         unsigned long *scanned, int order,
1225                                         isolate_mode_t mode,
1226                                         struct zone *z,
1227                                         struct mem_cgroup *mem_cont,
1228                                         int active, int file)
1229 {
1230         unsigned long nr_taken = 0;
1231         struct page *page;
1232         unsigned long scan;
1233         LIST_HEAD(pc_list);
1234         struct list_head *src;
1235         struct page_cgroup *pc, *tmp;
1236         int nid = zone_to_nid(z);
1237         int zid = zone_idx(z);
1238         struct mem_cgroup_per_zone *mz;
1239         int lru = LRU_FILE * file + active;
1240         int ret;
1241
1242         BUG_ON(!mem_cont);
1243         mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
1244         src = &mz->lists[lru];
1245
1246         scan = 0;
1247         list_for_each_entry_safe_reverse(pc, tmp, src, lru) {
1248                 if (scan >= nr_to_scan)
1249                         break;
1250
1251                 if (unlikely(!PageCgroupUsed(pc)))
1252                         continue;
1253
1254                 page = lookup_cgroup_page(pc);
1255
1256                 if (unlikely(!PageLRU(page)))
1257                         continue;
1258
1259                 scan++;
1260                 ret = __isolate_lru_page(page, mode, file);
1261                 switch (ret) {
1262                 case 0:
1263                         list_move(&page->lru, dst);
1264                         mem_cgroup_del_lru(page);
1265                         nr_taken += hpage_nr_pages(page);
1266                         break;
1267                 case -EBUSY:
1268                         /* we don't affect global LRU but rotate in our LRU */
1269                         mem_cgroup_rotate_lru_list(page, page_lru(page));
1270                         break;
1271                 default:
1272                         break;
1273                 }
1274         }
1275
1276         *scanned = scan;
1277
1278         trace_mm_vmscan_memcg_isolate(0, nr_to_scan, scan, nr_taken,
1279                                       0, 0, 0, mode);
1280
1281         return nr_taken;
1282 }
1283
1284 #define mem_cgroup_from_res_counter(counter, member)    \
1285         container_of(counter, struct mem_cgroup, member)
1286
1287 /**
1288  * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1289  * @mem: the memory cgroup
1290  *
1291  * Returns the maximum amount of memory @mem can be charged with, in
1292  * pages.
1293  */
1294 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1295 {
1296         unsigned long long margin;
1297
1298         margin = res_counter_margin(&memcg->res);
1299         if (do_swap_account)
1300                 margin = min(margin, res_counter_margin(&memcg->memsw));
1301         return margin >> PAGE_SHIFT;
1302 }
1303
1304 int mem_cgroup_swappiness(struct mem_cgroup *memcg)
1305 {
1306         struct cgroup *cgrp = memcg->css.cgroup;
1307
1308         /* root ? */
1309         if (cgrp->parent == NULL)
1310                 return vm_swappiness;
1311
1312         return memcg->swappiness;
1313 }
1314
1315 static void mem_cgroup_start_move(struct mem_cgroup *memcg)
1316 {
1317         int cpu;
1318
1319         get_online_cpus();
1320         spin_lock(&memcg->pcp_counter_lock);
1321         for_each_online_cpu(cpu)
1322                 per_cpu(memcg->stat->count[MEM_CGROUP_ON_MOVE], cpu) += 1;
1323         memcg->nocpu_base.count[MEM_CGROUP_ON_MOVE] += 1;
1324         spin_unlock(&memcg->pcp_counter_lock);
1325         put_online_cpus();
1326
1327         synchronize_rcu();
1328 }
1329
1330 static void mem_cgroup_end_move(struct mem_cgroup *memcg)
1331 {
1332         int cpu;
1333
1334         if (!memcg)
1335                 return;
1336         get_online_cpus();
1337         spin_lock(&memcg->pcp_counter_lock);
1338         for_each_online_cpu(cpu)
1339                 per_cpu(memcg->stat->count[MEM_CGROUP_ON_MOVE], cpu) -= 1;
1340         memcg->nocpu_base.count[MEM_CGROUP_ON_MOVE] -= 1;
1341         spin_unlock(&memcg->pcp_counter_lock);
1342         put_online_cpus();
1343 }
1344 /*
1345  * 2 routines for checking "mem" is under move_account() or not.
1346  *
1347  * mem_cgroup_stealed() - checking a cgroup is mc.from or not. This is used
1348  *                        for avoiding race in accounting. If true,
1349  *                        pc->mem_cgroup may be overwritten.
1350  *
1351  * mem_cgroup_under_move() - checking a cgroup is mc.from or mc.to or
1352  *                        under hierarchy of moving cgroups. This is for
1353  *                        waiting at hith-memory prressure caused by "move".
1354  */
1355
1356 static bool mem_cgroup_stealed(struct mem_cgroup *memcg)
1357 {
1358         VM_BUG_ON(!rcu_read_lock_held());
1359         return this_cpu_read(memcg->stat->count[MEM_CGROUP_ON_MOVE]) > 0;
1360 }
1361
1362 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1363 {
1364         struct mem_cgroup *from;
1365         struct mem_cgroup *to;
1366         bool ret = false;
1367         /*
1368          * Unlike task_move routines, we access mc.to, mc.from not under
1369          * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1370          */
1371         spin_lock(&mc.lock);
1372         from = mc.from;
1373         to = mc.to;
1374         if (!from)
1375                 goto unlock;
1376
1377         ret = mem_cgroup_same_or_subtree(memcg, from)
1378                 || mem_cgroup_same_or_subtree(memcg, to);
1379 unlock:
1380         spin_unlock(&mc.lock);
1381         return ret;
1382 }
1383
1384 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1385 {
1386         if (mc.moving_task && current != mc.moving_task) {
1387                 if (mem_cgroup_under_move(memcg)) {
1388                         DEFINE_WAIT(wait);
1389                         prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1390                         /* moving charge context might have finished. */
1391                         if (mc.moving_task)
1392                                 schedule();
1393                         finish_wait(&mc.waitq, &wait);
1394                         return true;
1395                 }
1396         }
1397         return false;
1398 }
1399
1400 /**
1401  * mem_cgroup_print_oom_info: Called from OOM with tasklist_lock held in read mode.
1402  * @memcg: The memory cgroup that went over limit
1403  * @p: Task that is going to be killed
1404  *
1405  * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1406  * enabled
1407  */
1408 void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1409 {
1410         struct cgroup *task_cgrp;
1411         struct cgroup *mem_cgrp;
1412         /*
1413          * Need a buffer in BSS, can't rely on allocations. The code relies
1414          * on the assumption that OOM is serialized for memory controller.
1415          * If this assumption is broken, revisit this code.
1416          */
1417         static char memcg_name[PATH_MAX];
1418         int ret;
1419
1420         if (!memcg || !p)
1421                 return;
1422
1423
1424         rcu_read_lock();
1425
1426         mem_cgrp = memcg->css.cgroup;
1427         task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
1428
1429         ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
1430         if (ret < 0) {
1431                 /*
1432                  * Unfortunately, we are unable to convert to a useful name
1433                  * But we'll still print out the usage information
1434                  */
1435                 rcu_read_unlock();
1436                 goto done;
1437         }
1438         rcu_read_unlock();
1439
1440         printk(KERN_INFO "Task in %s killed", memcg_name);
1441
1442         rcu_read_lock();
1443         ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
1444         if (ret < 0) {
1445                 rcu_read_unlock();
1446                 goto done;
1447         }
1448         rcu_read_unlock();
1449
1450         /*
1451          * Continues from above, so we don't need an KERN_ level
1452          */
1453         printk(KERN_CONT " as a result of limit of %s\n", memcg_name);
1454 done:
1455
1456         printk(KERN_INFO "memory: usage %llukB, limit %llukB, failcnt %llu\n",
1457                 res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
1458                 res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
1459                 res_counter_read_u64(&memcg->res, RES_FAILCNT));
1460         printk(KERN_INFO "memory+swap: usage %llukB, limit %llukB, "
1461                 "failcnt %llu\n",
1462                 res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
1463                 res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
1464                 res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
1465 }
1466
1467 /*
1468  * This function returns the number of memcg under hierarchy tree. Returns
1469  * 1(self count) if no children.
1470  */
1471 static int mem_cgroup_count_children(struct mem_cgroup *memcg)
1472 {
1473         int num = 0;
1474         struct mem_cgroup *iter;
1475
1476         for_each_mem_cgroup_tree(iter, memcg)
1477                 num++;
1478         return num;
1479 }
1480
1481 /*
1482  * Return the memory (and swap, if configured) limit for a memcg.
1483  */
1484 u64 mem_cgroup_get_limit(struct mem_cgroup *memcg)
1485 {
1486         u64 limit;
1487         u64 memsw;
1488
1489         limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
1490         limit += total_swap_pages << PAGE_SHIFT;
1491
1492         memsw = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
1493         /*
1494          * If memsw is finite and limits the amount of swap space available
1495          * to this memcg, return that limit.
1496          */
1497         return min(limit, memsw);
1498 }
1499
1500 static unsigned long mem_cgroup_reclaim(struct mem_cgroup *memcg,
1501                                         gfp_t gfp_mask,
1502                                         unsigned long flags)
1503 {
1504         unsigned long total = 0;
1505         bool noswap = false;
1506         int loop;
1507
1508         if (flags & MEM_CGROUP_RECLAIM_NOSWAP)
1509                 noswap = true;
1510         if (!(flags & MEM_CGROUP_RECLAIM_SHRINK) && memcg->memsw_is_minimum)
1511                 noswap = true;
1512
1513         for (loop = 0; loop < MEM_CGROUP_MAX_RECLAIM_LOOPS; loop++) {
1514                 if (loop)
1515                         drain_all_stock_async(memcg);
1516                 total += try_to_free_mem_cgroup_pages(memcg, gfp_mask, noswap);
1517                 /*
1518                  * Allow limit shrinkers, which are triggered directly
1519                  * by userspace, to catch signals and stop reclaim
1520                  * after minimal progress, regardless of the margin.
1521                  */
1522                 if (total && (flags & MEM_CGROUP_RECLAIM_SHRINK))
1523                         break;
1524                 if (mem_cgroup_margin(memcg))
1525                         break;
1526                 /*
1527                  * If nothing was reclaimed after two attempts, there
1528                  * may be no reclaimable pages in this hierarchy.
1529                  */
1530                 if (loop && !total)
1531                         break;
1532         }
1533         return total;
1534 }
1535
1536 /**
1537  * test_mem_cgroup_node_reclaimable
1538  * @mem: the target memcg
1539  * @nid: the node ID to be checked.
1540  * @noswap : specify true here if the user wants flle only information.
1541  *
1542  * This function returns whether the specified memcg contains any
1543  * reclaimable pages on a node. Returns true if there are any reclaimable
1544  * pages in the node.
1545  */
1546 static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *memcg,
1547                 int nid, bool noswap)
1548 {
1549         if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_FILE))
1550                 return true;
1551         if (noswap || !total_swap_pages)
1552                 return false;
1553         if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_ANON))
1554                 return true;
1555         return false;
1556
1557 }
1558 #if MAX_NUMNODES > 1
1559
1560 /*
1561  * Always updating the nodemask is not very good - even if we have an empty
1562  * list or the wrong list here, we can start from some node and traverse all
1563  * nodes based on the zonelist. So update the list loosely once per 10 secs.
1564  *
1565  */
1566 static void mem_cgroup_may_update_nodemask(struct mem_cgroup *memcg)
1567 {
1568         int nid;
1569         /*
1570          * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
1571          * pagein/pageout changes since the last update.
1572          */
1573         if (!atomic_read(&memcg->numainfo_events))
1574                 return;
1575         if (atomic_inc_return(&memcg->numainfo_updating) > 1)
1576                 return;
1577
1578         /* make a nodemask where this memcg uses memory from */
1579         memcg->scan_nodes = node_states[N_HIGH_MEMORY];
1580
1581         for_each_node_mask(nid, node_states[N_HIGH_MEMORY]) {
1582
1583                 if (!test_mem_cgroup_node_reclaimable(memcg, nid, false))
1584                         node_clear(nid, memcg->scan_nodes);
1585         }
1586
1587         atomic_set(&memcg->numainfo_events, 0);
1588         atomic_set(&memcg->numainfo_updating, 0);
1589 }
1590
1591 /*
1592  * Selecting a node where we start reclaim from. Because what we need is just
1593  * reducing usage counter, start from anywhere is O,K. Considering
1594  * memory reclaim from current node, there are pros. and cons.
1595  *
1596  * Freeing memory from current node means freeing memory from a node which
1597  * we'll use or we've used. So, it may make LRU bad. And if several threads
1598  * hit limits, it will see a contention on a node. But freeing from remote
1599  * node means more costs for memory reclaim because of memory latency.
1600  *
1601  * Now, we use round-robin. Better algorithm is welcomed.
1602  */
1603 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1604 {
1605         int node;
1606
1607         mem_cgroup_may_update_nodemask(memcg);
1608         node = memcg->last_scanned_node;
1609
1610         node = next_node(node, memcg->scan_nodes);
1611         if (node == MAX_NUMNODES)
1612                 node = first_node(memcg->scan_nodes);
1613         /*
1614          * We call this when we hit limit, not when pages are added to LRU.
1615          * No LRU may hold pages because all pages are UNEVICTABLE or
1616          * memcg is too small and all pages are not on LRU. In that case,
1617          * we use curret node.
1618          */
1619         if (unlikely(node == MAX_NUMNODES))
1620                 node = numa_node_id();
1621
1622         memcg->last_scanned_node = node;
1623         return node;
1624 }
1625
1626 /*
1627  * Check all nodes whether it contains reclaimable pages or not.
1628  * For quick scan, we make use of scan_nodes. This will allow us to skip
1629  * unused nodes. But scan_nodes is lazily updated and may not cotain
1630  * enough new information. We need to do double check.
1631  */
1632 bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
1633 {
1634         int nid;
1635
1636         /*
1637          * quick check...making use of scan_node.
1638          * We can skip unused nodes.
1639          */
1640         if (!nodes_empty(memcg->scan_nodes)) {
1641                 for (nid = first_node(memcg->scan_nodes);
1642                      nid < MAX_NUMNODES;
1643                      nid = next_node(nid, memcg->scan_nodes)) {
1644
1645                         if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
1646                                 return true;
1647                 }
1648         }
1649         /*
1650          * Check rest of nodes.
1651          */
1652         for_each_node_state(nid, N_HIGH_MEMORY) {
1653                 if (node_isset(nid, memcg->scan_nodes))
1654                         continue;
1655                 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
1656                         return true;
1657         }
1658         return false;
1659 }
1660
1661 #else
1662 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1663 {
1664         return 0;
1665 }
1666
1667 bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
1668 {
1669         return test_mem_cgroup_node_reclaimable(memcg, 0, noswap);
1670 }
1671 #endif
1672
1673 static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
1674                                    struct zone *zone,
1675                                    gfp_t gfp_mask,
1676                                    unsigned long *total_scanned)
1677 {
1678         struct mem_cgroup *victim = NULL;
1679         int total = 0;
1680         int loop = 0;
1681         unsigned long excess;
1682         unsigned long nr_scanned;
1683         struct mem_cgroup_reclaim_cookie reclaim = {
1684                 .zone = zone,
1685                 .priority = 0,
1686         };
1687
1688         excess = res_counter_soft_limit_excess(&root_memcg->res) >> PAGE_SHIFT;
1689
1690         while (1) {
1691                 victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
1692                 if (!victim) {
1693                         loop++;
1694                         if (loop >= 2) {
1695                                 /*
1696                                  * If we have not been able to reclaim
1697                                  * anything, it might because there are
1698                                  * no reclaimable pages under this hierarchy
1699                                  */
1700                                 if (!total)
1701                                         break;
1702                                 /*
1703                                  * We want to do more targeted reclaim.
1704                                  * excess >> 2 is not to excessive so as to
1705                                  * reclaim too much, nor too less that we keep
1706                                  * coming back to reclaim from this cgroup
1707                                  */
1708                                 if (total >= (excess >> 2) ||
1709                                         (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
1710                                         break;
1711                         }
1712                         continue;
1713                 }
1714                 if (!mem_cgroup_reclaimable(victim, false))
1715                         continue;
1716                 total += mem_cgroup_shrink_node_zone(victim, gfp_mask, false,
1717                                                      zone, &nr_scanned);
1718                 *total_scanned += nr_scanned;
1719                 if (!res_counter_soft_limit_excess(&root_memcg->res))
1720                         break;
1721         }
1722         mem_cgroup_iter_break(root_memcg, victim);
1723         return total;
1724 }
1725
1726 /*
1727  * Check OOM-Killer is already running under our hierarchy.
1728  * If someone is running, return false.
1729  * Has to be called with memcg_oom_lock
1730  */
1731 static bool mem_cgroup_oom_lock(struct mem_cgroup *memcg)
1732 {
1733         struct mem_cgroup *iter, *failed = NULL;
1734
1735         for_each_mem_cgroup_tree(iter, memcg) {
1736                 if (iter->oom_lock) {
1737                         /*
1738                          * this subtree of our hierarchy is already locked
1739                          * so we cannot give a lock.
1740                          */
1741                         failed = iter;
1742                         mem_cgroup_iter_break(memcg, iter);
1743                         break;
1744                 } else
1745                         iter->oom_lock = true;
1746         }
1747
1748         if (!failed)
1749                 return true;
1750
1751         /*
1752          * OK, we failed to lock the whole subtree so we have to clean up
1753          * what we set up to the failing subtree
1754          */
1755         for_each_mem_cgroup_tree(iter, memcg) {
1756                 if (iter == failed) {
1757                         mem_cgroup_iter_break(memcg, iter);
1758                         break;
1759                 }
1760                 iter->oom_lock = false;
1761         }
1762         return false;
1763 }
1764
1765 /*
1766  * Has to be called with memcg_oom_lock
1767  */
1768 static int mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
1769 {
1770         struct mem_cgroup *iter;
1771
1772         for_each_mem_cgroup_tree(iter, memcg)
1773                 iter->oom_lock = false;
1774         return 0;
1775 }
1776
1777 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
1778 {
1779         struct mem_cgroup *iter;
1780
1781         for_each_mem_cgroup_tree(iter, memcg)
1782                 atomic_inc(&iter->under_oom);
1783 }
1784
1785 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
1786 {
1787         struct mem_cgroup *iter;
1788
1789         /*
1790          * When a new child is created while the hierarchy is under oom,
1791          * mem_cgroup_oom_lock() may not be called. We have to use
1792          * atomic_add_unless() here.
1793          */
1794         for_each_mem_cgroup_tree(iter, memcg)
1795                 atomic_add_unless(&iter->under_oom, -1, 0);
1796 }
1797
1798 static DEFINE_SPINLOCK(memcg_oom_lock);
1799 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1800
1801 struct oom_wait_info {
1802         struct mem_cgroup *mem;
1803         wait_queue_t    wait;
1804 };
1805
1806 static int memcg_oom_wake_function(wait_queue_t *wait,
1807         unsigned mode, int sync, void *arg)
1808 {
1809         struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg,
1810                           *oom_wait_memcg;
1811         struct oom_wait_info *oom_wait_info;
1812
1813         oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1814         oom_wait_memcg = oom_wait_info->mem;
1815
1816         /*
1817          * Both of oom_wait_info->mem and wake_mem are stable under us.
1818          * Then we can use css_is_ancestor without taking care of RCU.
1819          */
1820         if (!mem_cgroup_same_or_subtree(oom_wait_memcg, wake_memcg)
1821                 && !mem_cgroup_same_or_subtree(wake_memcg, oom_wait_memcg))
1822                 return 0;
1823         return autoremove_wake_function(wait, mode, sync, arg);
1824 }
1825
1826 static void memcg_wakeup_oom(struct mem_cgroup *memcg)
1827 {
1828         /* for filtering, pass "memcg" as argument. */
1829         __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
1830 }
1831
1832 static void memcg_oom_recover(struct mem_cgroup *memcg)
1833 {
1834         if (memcg && atomic_read(&memcg->under_oom))
1835                 memcg_wakeup_oom(memcg);
1836 }
1837
1838 /*
1839  * try to call OOM killer. returns false if we should exit memory-reclaim loop.
1840  */
1841 bool mem_cgroup_handle_oom(struct mem_cgroup *memcg, gfp_t mask)
1842 {
1843         struct oom_wait_info owait;
1844         bool locked, need_to_kill;
1845
1846         owait.mem = memcg;
1847         owait.wait.flags = 0;
1848         owait.wait.func = memcg_oom_wake_function;
1849         owait.wait.private = current;
1850         INIT_LIST_HEAD(&owait.wait.task_list);
1851         need_to_kill = true;
1852         mem_cgroup_mark_under_oom(memcg);
1853
1854         /* At first, try to OOM lock hierarchy under memcg.*/
1855         spin_lock(&memcg_oom_lock);
1856         locked = mem_cgroup_oom_lock(memcg);
1857         /*
1858          * Even if signal_pending(), we can't quit charge() loop without
1859          * accounting. So, UNINTERRUPTIBLE is appropriate. But SIGKILL
1860          * under OOM is always welcomed, use TASK_KILLABLE here.
1861          */
1862         prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
1863         if (!locked || memcg->oom_kill_disable)
1864                 need_to_kill = false;
1865         if (locked)
1866                 mem_cgroup_oom_notify(memcg);
1867         spin_unlock(&memcg_oom_lock);
1868
1869         if (need_to_kill) {
1870                 finish_wait(&memcg_oom_waitq, &owait.wait);
1871                 mem_cgroup_out_of_memory(memcg, mask);
1872         } else {
1873                 schedule();
1874                 finish_wait(&memcg_oom_waitq, &owait.wait);
1875         }
1876         spin_lock(&memcg_oom_lock);
1877         if (locked)
1878                 mem_cgroup_oom_unlock(memcg);
1879         memcg_wakeup_oom(memcg);
1880         spin_unlock(&memcg_oom_lock);
1881
1882         mem_cgroup_unmark_under_oom(memcg);
1883
1884         if (test_thread_flag(TIF_MEMDIE) || fatal_signal_pending(current))
1885                 return false;
1886         /* Give chance to dying process */
1887         schedule_timeout_uninterruptible(1);
1888         return true;
1889 }
1890
1891 /*
1892  * Currently used to update mapped file statistics, but the routine can be
1893  * generalized to update other statistics as well.
1894  *
1895  * Notes: Race condition
1896  *
1897  * We usually use page_cgroup_lock() for accessing page_cgroup member but
1898  * it tends to be costly. But considering some conditions, we doesn't need
1899  * to do so _always_.
1900  *
1901  * Considering "charge", lock_page_cgroup() is not required because all
1902  * file-stat operations happen after a page is attached to radix-tree. There
1903  * are no race with "charge".
1904  *
1905  * Considering "uncharge", we know that memcg doesn't clear pc->mem_cgroup
1906  * at "uncharge" intentionally. So, we always see valid pc->mem_cgroup even
1907  * if there are race with "uncharge". Statistics itself is properly handled
1908  * by flags.
1909  *
1910  * Considering "move", this is an only case we see a race. To make the race
1911  * small, we check MEM_CGROUP_ON_MOVE percpu value and detect there are
1912  * possibility of race condition. If there is, we take a lock.
1913  */
1914
1915 void mem_cgroup_update_page_stat(struct page *page,
1916                                  enum mem_cgroup_page_stat_item idx, int val)
1917 {
1918         struct mem_cgroup *memcg;
1919         struct page_cgroup *pc = lookup_page_cgroup(page);
1920         bool need_unlock = false;
1921         unsigned long uninitialized_var(flags);
1922
1923         if (unlikely(!pc))
1924                 return;
1925
1926         rcu_read_lock();
1927         memcg = pc->mem_cgroup;
1928         if (unlikely(!memcg || !PageCgroupUsed(pc)))
1929                 goto out;
1930         /* pc->mem_cgroup is unstable ? */
1931         if (unlikely(mem_cgroup_stealed(memcg)) || PageTransHuge(page)) {
1932                 /* take a lock against to access pc->mem_cgroup */
1933                 move_lock_page_cgroup(pc, &flags);
1934                 need_unlock = true;
1935                 memcg = pc->mem_cgroup;
1936                 if (!memcg || !PageCgroupUsed(pc))
1937                         goto out;
1938         }
1939
1940         switch (idx) {
1941         case MEMCG_NR_FILE_MAPPED:
1942                 if (val > 0)
1943                         SetPageCgroupFileMapped(pc);
1944                 else if (!page_mapped(page))
1945                         ClearPageCgroupFileMapped(pc);
1946                 idx = MEM_CGROUP_STAT_FILE_MAPPED;
1947                 break;
1948         default:
1949                 BUG();
1950         }
1951
1952         this_cpu_add(memcg->stat->count[idx], val);
1953
1954 out:
1955         if (unlikely(need_unlock))
1956                 move_unlock_page_cgroup(pc, &flags);
1957         rcu_read_unlock();
1958         return;
1959 }
1960 EXPORT_SYMBOL(mem_cgroup_update_page_stat);
1961
1962 /*
1963  * size of first charge trial. "32" comes from vmscan.c's magic value.
1964  * TODO: maybe necessary to use big numbers in big irons.
1965  */
1966 #define CHARGE_BATCH    32U
1967 struct memcg_stock_pcp {
1968         struct mem_cgroup *cached; /* this never be root cgroup */
1969         unsigned int nr_pages;
1970         struct work_struct work;
1971         unsigned long flags;
1972 #define FLUSHING_CACHED_CHARGE  (0)
1973 };
1974 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
1975 static DEFINE_MUTEX(percpu_charge_mutex);
1976
1977 /*
1978  * Try to consume stocked charge on this cpu. If success, one page is consumed
1979  * from local stock and true is returned. If the stock is 0 or charges from a
1980  * cgroup which is not current target, returns false. This stock will be
1981  * refilled.
1982  */
1983 static bool consume_stock(struct mem_cgroup *memcg)
1984 {
1985         struct memcg_stock_pcp *stock;
1986         bool ret = true;
1987
1988         stock = &get_cpu_var(memcg_stock);
1989         if (memcg == stock->cached && stock->nr_pages)
1990                 stock->nr_pages--;
1991         else /* need to call res_counter_charge */
1992                 ret = false;
1993         put_cpu_var(memcg_stock);
1994         return ret;
1995 }
1996
1997 /*
1998  * Returns stocks cached in percpu to res_counter and reset cached information.
1999  */
2000 static void drain_stock(struct memcg_stock_pcp *stock)
2001 {
2002         struct mem_cgroup *old = stock->cached;
2003
2004         if (stock->nr_pages) {
2005                 unsigned long bytes = stock->nr_pages * PAGE_SIZE;
2006
2007                 res_counter_uncharge(&old->res, bytes);
2008                 if (do_swap_account)
2009                         res_counter_uncharge(&old->memsw, bytes);
2010                 stock->nr_pages = 0;
2011         }
2012         stock->cached = NULL;
2013 }
2014
2015 /*
2016  * This must be called under preempt disabled or must be called by
2017  * a thread which is pinned to local cpu.
2018  */
2019 static void drain_local_stock(struct work_struct *dummy)
2020 {
2021         struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
2022         drain_stock(stock);
2023         clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2024 }
2025
2026 /*
2027  * Cache charges(val) which is from res_counter, to local per_cpu area.
2028  * This will be consumed by consume_stock() function, later.
2029  */
2030 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2031 {
2032         struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
2033
2034         if (stock->cached != memcg) { /* reset if necessary */
2035                 drain_stock(stock);
2036                 stock->cached = memcg;
2037         }
2038         stock->nr_pages += nr_pages;
2039         put_cpu_var(memcg_stock);
2040 }
2041
2042 /*
2043  * Drains all per-CPU charge caches for given root_memcg resp. subtree
2044  * of the hierarchy under it. sync flag says whether we should block
2045  * until the work is done.
2046  */
2047 static void drain_all_stock(struct mem_cgroup *root_memcg, bool sync)
2048 {
2049         int cpu, curcpu;
2050
2051         /* Notify other cpus that system-wide "drain" is running */
2052         get_online_cpus();
2053         curcpu = get_cpu();
2054         for_each_online_cpu(cpu) {
2055                 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2056                 struct mem_cgroup *memcg;
2057
2058                 memcg = stock->cached;
2059                 if (!memcg || !stock->nr_pages)
2060                         continue;
2061                 if (!mem_cgroup_same_or_subtree(root_memcg, memcg))
2062                         continue;
2063                 if (!test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2064                         if (cpu == curcpu)
2065                                 drain_local_stock(&stock->work);
2066                         else
2067                                 schedule_work_on(cpu, &stock->work);
2068                 }
2069         }
2070         put_cpu();
2071
2072         if (!sync)
2073                 goto out;
2074
2075         for_each_online_cpu(cpu) {
2076                 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2077                 if (test_bit(FLUSHING_CACHED_CHARGE, &stock->flags))
2078                         flush_work(&stock->work);
2079         }
2080 out:
2081         put_online_cpus();
2082 }
2083
2084 /*
2085  * Tries to drain stocked charges in other cpus. This function is asynchronous
2086  * and just put a work per cpu for draining localy on each cpu. Caller can
2087  * expects some charges will be back to res_counter later but cannot wait for
2088  * it.
2089  */
2090 static void drain_all_stock_async(struct mem_cgroup *root_memcg)
2091 {
2092         /*
2093          * If someone calls draining, avoid adding more kworker runs.
2094          */
2095         if (!mutex_trylock(&percpu_charge_mutex))
2096                 return;
2097         drain_all_stock(root_memcg, false);
2098         mutex_unlock(&percpu_charge_mutex);
2099 }
2100
2101 /* This is a synchronous drain interface. */
2102 static void drain_all_stock_sync(struct mem_cgroup *root_memcg)
2103 {
2104         /* called when force_empty is called */
2105         mutex_lock(&percpu_charge_mutex);
2106         drain_all_stock(root_memcg, true);
2107         mutex_unlock(&percpu_charge_mutex);
2108 }
2109
2110 /*
2111  * This function drains percpu counter value from DEAD cpu and
2112  * move it to local cpu. Note that this function can be preempted.
2113  */
2114 static void mem_cgroup_drain_pcp_counter(struct mem_cgroup *memcg, int cpu)
2115 {
2116         int i;
2117
2118         spin_lock(&memcg->pcp_counter_lock);
2119         for (i = 0; i < MEM_CGROUP_STAT_DATA; i++) {
2120                 long x = per_cpu(memcg->stat->count[i], cpu);
2121
2122                 per_cpu(memcg->stat->count[i], cpu) = 0;
2123                 memcg->nocpu_base.count[i] += x;
2124         }
2125         for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
2126                 unsigned long x = per_cpu(memcg->stat->events[i], cpu);
2127
2128                 per_cpu(memcg->stat->events[i], cpu) = 0;
2129                 memcg->nocpu_base.events[i] += x;
2130         }
2131         /* need to clear ON_MOVE value, works as a kind of lock. */
2132         per_cpu(memcg->stat->count[MEM_CGROUP_ON_MOVE], cpu) = 0;
2133         spin_unlock(&memcg->pcp_counter_lock);
2134 }
2135
2136 static void synchronize_mem_cgroup_on_move(struct mem_cgroup *memcg, int cpu)
2137 {
2138         int idx = MEM_CGROUP_ON_MOVE;
2139
2140         spin_lock(&memcg->pcp_counter_lock);
2141         per_cpu(memcg->stat->count[idx], cpu) = memcg->nocpu_base.count[idx];
2142         spin_unlock(&memcg->pcp_counter_lock);
2143 }
2144
2145 static int __cpuinit memcg_cpu_hotplug_callback(struct notifier_block *nb,
2146                                         unsigned long action,
2147                                         void *hcpu)
2148 {
2149         int cpu = (unsigned long)hcpu;
2150         struct memcg_stock_pcp *stock;
2151         struct mem_cgroup *iter;
2152
2153         if ((action == CPU_ONLINE)) {
2154                 for_each_mem_cgroup(iter)
2155                         synchronize_mem_cgroup_on_move(iter, cpu);
2156                 return NOTIFY_OK;
2157         }
2158
2159         if ((action != CPU_DEAD) || action != CPU_DEAD_FROZEN)
2160                 return NOTIFY_OK;
2161
2162         for_each_mem_cgroup(iter)
2163                 mem_cgroup_drain_pcp_counter(iter, cpu);
2164
2165         stock = &per_cpu(memcg_stock, cpu);
2166         drain_stock(stock);
2167         return NOTIFY_OK;
2168 }
2169
2170
2171 /* See __mem_cgroup_try_charge() for details */
2172 enum {
2173         CHARGE_OK,              /* success */
2174         CHARGE_RETRY,           /* need to retry but retry is not bad */
2175         CHARGE_NOMEM,           /* we can't do more. return -ENOMEM */
2176         CHARGE_WOULDBLOCK,      /* GFP_WAIT wasn't set and no enough res. */
2177         CHARGE_OOM_DIE,         /* the current is killed because of OOM */
2178 };
2179
2180 static int mem_cgroup_do_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2181                                 unsigned int nr_pages, bool oom_check)
2182 {
2183         unsigned long csize = nr_pages * PAGE_SIZE;
2184         struct mem_cgroup *mem_over_limit;
2185         struct res_counter *fail_res;
2186         unsigned long flags = 0;
2187         int ret;
2188
2189         ret = res_counter_charge(&memcg->res, csize, &fail_res);
2190
2191         if (likely(!ret)) {
2192                 if (!do_swap_account)
2193                         return CHARGE_OK;
2194                 ret = res_counter_charge(&memcg->memsw, csize, &fail_res);
2195                 if (likely(!ret))
2196                         return CHARGE_OK;
2197
2198                 res_counter_uncharge(&memcg->res, csize);
2199                 mem_over_limit = mem_cgroup_from_res_counter(fail_res, memsw);
2200                 flags |= MEM_CGROUP_RECLAIM_NOSWAP;
2201         } else
2202                 mem_over_limit = mem_cgroup_from_res_counter(fail_res, res);
2203         /*
2204          * nr_pages can be either a huge page (HPAGE_PMD_NR), a batch
2205          * of regular pages (CHARGE_BATCH), or a single regular page (1).
2206          *
2207          * Never reclaim on behalf of optional batching, retry with a
2208          * single page instead.
2209          */
2210         if (nr_pages == CHARGE_BATCH)
2211                 return CHARGE_RETRY;
2212
2213         if (!(gfp_mask & __GFP_WAIT))
2214                 return CHARGE_WOULDBLOCK;
2215
2216         ret = mem_cgroup_reclaim(mem_over_limit, gfp_mask, flags);
2217         if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2218                 return CHARGE_RETRY;
2219         /*
2220          * Even though the limit is exceeded at this point, reclaim
2221          * may have been able to free some pages.  Retry the charge
2222          * before killing the task.
2223          *
2224          * Only for regular pages, though: huge pages are rather
2225          * unlikely to succeed so close to the limit, and we fall back
2226          * to regular pages anyway in case of failure.
2227          */
2228         if (nr_pages == 1 && ret)
2229                 return CHARGE_RETRY;
2230
2231         /*
2232          * At task move, charge accounts can be doubly counted. So, it's
2233          * better to wait until the end of task_move if something is going on.
2234          */
2235         if (mem_cgroup_wait_acct_move(mem_over_limit))
2236                 return CHARGE_RETRY;
2237
2238         /* If we don't need to call oom-killer at el, return immediately */
2239         if (!oom_check)
2240                 return CHARGE_NOMEM;
2241         /* check OOM */
2242         if (!mem_cgroup_handle_oom(mem_over_limit, gfp_mask))
2243                 return CHARGE_OOM_DIE;
2244
2245         return CHARGE_RETRY;
2246 }
2247
2248 /*
2249  * Unlike exported interface, "oom" parameter is added. if oom==true,
2250  * oom-killer can be invoked.
2251  */
2252 static int __mem_cgroup_try_charge(struct mm_struct *mm,
2253                                    gfp_t gfp_mask,
2254                                    unsigned int nr_pages,
2255                                    struct mem_cgroup **ptr,
2256                                    bool oom)
2257 {
2258         unsigned int batch = max(CHARGE_BATCH, nr_pages);
2259         int nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2260         struct mem_cgroup *memcg = NULL;
2261         int ret;
2262
2263         /*
2264          * Unlike gloval-vm's OOM-kill, we're not in memory shortage
2265          * in system level. So, allow to go ahead dying process in addition to
2266          * MEMDIE process.
2267          */
2268         if (unlikely(test_thread_flag(TIF_MEMDIE)
2269                      || fatal_signal_pending(current)))
2270                 goto bypass;
2271
2272         /*
2273          * We always charge the cgroup the mm_struct belongs to.
2274          * The mm_struct's mem_cgroup changes on task migration if the
2275          * thread group leader migrates. It's possible that mm is not
2276          * set, if so charge the init_mm (happens for pagecache usage).
2277          */
2278         if (!*ptr && !mm)
2279                 goto bypass;
2280 again:
2281         if (*ptr) { /* css should be a valid one */
2282                 memcg = *ptr;
2283                 VM_BUG_ON(css_is_removed(&memcg->css));
2284                 if (mem_cgroup_is_root(memcg))
2285                         goto done;
2286                 if (nr_pages == 1 && consume_stock(memcg))
2287                         goto done;
2288                 css_get(&memcg->css);
2289         } else {
2290                 struct task_struct *p;
2291
2292                 rcu_read_lock();
2293                 p = rcu_dereference(mm->owner);
2294                 /*
2295                  * Because we don't have task_lock(), "p" can exit.
2296                  * In that case, "memcg" can point to root or p can be NULL with
2297                  * race with swapoff. Then, we have small risk of mis-accouning.
2298                  * But such kind of mis-account by race always happens because
2299                  * we don't have cgroup_mutex(). It's overkill and we allo that
2300                  * small race, here.
2301                  * (*) swapoff at el will charge against mm-struct not against
2302                  * task-struct. So, mm->owner can be NULL.
2303                  */
2304                 memcg = mem_cgroup_from_task(p);
2305                 if (!memcg || mem_cgroup_is_root(memcg)) {
2306                         rcu_read_unlock();
2307                         goto done;
2308                 }
2309                 if (nr_pages == 1 && consume_stock(memcg)) {
2310                         /*
2311                          * It seems dagerous to access memcg without css_get().
2312                          * But considering how consume_stok works, it's not
2313                          * necessary. If consume_stock success, some charges
2314                          * from this memcg are cached on this cpu. So, we
2315                          * don't need to call css_get()/css_tryget() before
2316                          * calling consume_stock().
2317                          */
2318                         rcu_read_unlock();
2319                         goto done;
2320                 }
2321                 /* after here, we may be blocked. we need to get refcnt */
2322                 if (!css_tryget(&memcg->css)) {
2323                         rcu_read_unlock();
2324                         goto again;
2325                 }
2326                 rcu_read_unlock();
2327         }
2328
2329         do {
2330                 bool oom_check;
2331
2332                 /* If killed, bypass charge */
2333                 if (fatal_signal_pending(current)) {
2334                         css_put(&memcg->css);
2335                         goto bypass;
2336                 }
2337
2338                 oom_check = false;
2339                 if (oom && !nr_oom_retries) {
2340                         oom_check = true;
2341                         nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2342                 }
2343
2344                 ret = mem_cgroup_do_charge(memcg, gfp_mask, batch, oom_check);
2345                 switch (ret) {
2346                 case CHARGE_OK:
2347                         break;
2348                 case CHARGE_RETRY: /* not in OOM situation but retry */
2349                         batch = nr_pages;
2350                         css_put(&memcg->css);
2351                         memcg = NULL;
2352                         goto again;
2353                 case CHARGE_WOULDBLOCK: /* !__GFP_WAIT */
2354                         css_put(&memcg->css);
2355                         goto nomem;
2356                 case CHARGE_NOMEM: /* OOM routine works */
2357                         if (!oom) {
2358                                 css_put(&memcg->css);
2359                                 goto nomem;
2360                         }
2361                         /* If oom, we never return -ENOMEM */
2362                         nr_oom_retries--;
2363                         break;
2364                 case CHARGE_OOM_DIE: /* Killed by OOM Killer */
2365                         css_put(&memcg->css);
2366                         goto bypass;
2367                 }
2368         } while (ret != CHARGE_OK);
2369
2370         if (batch > nr_pages)
2371                 refill_stock(memcg, batch - nr_pages);
2372         css_put(&memcg->css);
2373 done:
2374         *ptr = memcg;
2375         return 0;
2376 nomem:
2377         *ptr = NULL;
2378         return -ENOMEM;
2379 bypass:
2380         *ptr = NULL;
2381         return 0;
2382 }
2383
2384 /*
2385  * Somemtimes we have to undo a charge we got by try_charge().
2386  * This function is for that and do uncharge, put css's refcnt.
2387  * gotten by try_charge().
2388  */
2389 static void __mem_cgroup_cancel_charge(struct mem_cgroup *memcg,
2390                                        unsigned int nr_pages)
2391 {
2392         if (!mem_cgroup_is_root(memcg)) {
2393                 unsigned long bytes = nr_pages * PAGE_SIZE;
2394
2395                 res_counter_uncharge(&memcg->res, bytes);
2396                 if (do_swap_account)
2397                         res_counter_uncharge(&memcg->memsw, bytes);
2398         }
2399 }
2400
2401 /*
2402  * A helper function to get mem_cgroup from ID. must be called under
2403  * rcu_read_lock(). The caller must check css_is_removed() or some if
2404  * it's concern. (dropping refcnt from swap can be called against removed
2405  * memcg.)
2406  */
2407 static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
2408 {
2409         struct cgroup_subsys_state *css;
2410
2411         /* ID 0 is unused ID */
2412         if (!id)
2413                 return NULL;
2414         css = css_lookup(&mem_cgroup_subsys, id);
2415         if (!css)
2416                 return NULL;
2417         return container_of(css, struct mem_cgroup, css);
2418 }
2419
2420 struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
2421 {
2422         struct mem_cgroup *memcg = NULL;
2423         struct page_cgroup *pc;
2424         unsigned short id;
2425         swp_entry_t ent;
2426
2427         VM_BUG_ON(!PageLocked(page));
2428
2429         pc = lookup_page_cgroup(page);
2430         lock_page_cgroup(pc);
2431         if (PageCgroupUsed(pc)) {
2432                 memcg = pc->mem_cgroup;
2433                 if (memcg && !css_tryget(&memcg->css))
2434                         memcg = NULL;
2435         } else if (PageSwapCache(page)) {
2436                 ent.val = page_private(page);
2437                 id = lookup_swap_cgroup(ent);
2438                 rcu_read_lock();
2439                 memcg = mem_cgroup_lookup(id);
2440                 if (memcg && !css_tryget(&memcg->css))
2441                         memcg = NULL;
2442                 rcu_read_unlock();
2443         }
2444         unlock_page_cgroup(pc);
2445         return memcg;
2446 }
2447
2448 static void __mem_cgroup_commit_charge(struct mem_cgroup *memcg,
2449                                        struct page *page,
2450                                        unsigned int nr_pages,
2451                                        struct page_cgroup *pc,
2452                                        enum charge_type ctype)
2453 {
2454         lock_page_cgroup(pc);
2455         if (unlikely(PageCgroupUsed(pc))) {
2456                 unlock_page_cgroup(pc);
2457                 __mem_cgroup_cancel_charge(memcg, nr_pages);
2458                 return;
2459         }
2460         /*
2461          * we don't need page_cgroup_lock about tail pages, becase they are not
2462          * accessed by any other context at this point.
2463          */
2464         pc->mem_cgroup = memcg;
2465         /*
2466          * We access a page_cgroup asynchronously without lock_page_cgroup().
2467          * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
2468          * is accessed after testing USED bit. To make pc->mem_cgroup visible
2469          * before USED bit, we need memory barrier here.
2470          * See mem_cgroup_add_lru_list(), etc.
2471          */
2472         smp_wmb();
2473         switch (ctype) {
2474         case MEM_CGROUP_CHARGE_TYPE_CACHE:
2475         case MEM_CGROUP_CHARGE_TYPE_SHMEM:
2476                 SetPageCgroupCache(pc);
2477                 SetPageCgroupUsed(pc);
2478                 break;
2479         case MEM_CGROUP_CHARGE_TYPE_MAPPED:
2480                 ClearPageCgroupCache(pc);
2481                 SetPageCgroupUsed(pc);
2482                 break;
2483         default:
2484                 break;
2485         }
2486
2487         mem_cgroup_charge_statistics(memcg, PageCgroupCache(pc), nr_pages);
2488         unlock_page_cgroup(pc);
2489         /*
2490          * "charge_statistics" updated event counter. Then, check it.
2491          * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
2492          * if they exceeds softlimit.
2493          */
2494         memcg_check_events(memcg, page);
2495 }
2496
2497 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
2498
2499 #define PCGF_NOCOPY_AT_SPLIT ((1 << PCG_LOCK) | (1 << PCG_MOVE_LOCK) |\
2500                         (1 << PCG_ACCT_LRU) | (1 << PCG_MIGRATION))
2501 /*
2502  * Because tail pages are not marked as "used", set it. We're under
2503  * zone->lru_lock, 'splitting on pmd' and compund_lock.
2504  */
2505 void mem_cgroup_split_huge_fixup(struct page *head, struct page *tail)
2506 {
2507         struct page_cgroup *head_pc = lookup_page_cgroup(head);
2508         struct page_cgroup *tail_pc = lookup_page_cgroup(tail);
2509         unsigned long flags;
2510
2511         if (mem_cgroup_disabled())
2512                 return;
2513         /*
2514          * We have no races with charge/uncharge but will have races with
2515          * page state accounting.
2516          */
2517         move_lock_page_cgroup(head_pc, &flags);
2518
2519         tail_pc->mem_cgroup = head_pc->mem_cgroup;
2520         smp_wmb(); /* see __commit_charge() */
2521         if (PageCgroupAcctLRU(head_pc)) {
2522                 enum lru_list lru;
2523                 struct mem_cgroup_per_zone *mz;
2524
2525                 /*
2526                  * LRU flags cannot be copied because we need to add tail
2527                  *.page to LRU by generic call and our hook will be called.
2528                  * We hold lru_lock, then, reduce counter directly.
2529                  */
2530                 lru = page_lru(head);
2531                 mz = page_cgroup_zoneinfo(head_pc->mem_cgroup, head);
2532                 MEM_CGROUP_ZSTAT(mz, lru) -= 1;
2533         }
2534         tail_pc->flags = head_pc->flags & ~PCGF_NOCOPY_AT_SPLIT;
2535         move_unlock_page_cgroup(head_pc, &flags);
2536 }
2537 #endif
2538
2539 /**
2540  * mem_cgroup_move_account - move account of the page
2541  * @page: the page
2542  * @nr_pages: number of regular pages (>1 for huge pages)
2543  * @pc: page_cgroup of the page.
2544  * @from: mem_cgroup which the page is moved from.
2545  * @to: mem_cgroup which the page is moved to. @from != @to.
2546  * @uncharge: whether we should call uncharge and css_put against @from.
2547  *
2548  * The caller must confirm following.
2549  * - page is not on LRU (isolate_page() is useful.)
2550  * - compound_lock is held when nr_pages > 1
2551  *
2552  * This function doesn't do "charge" nor css_get to new cgroup. It should be
2553  * done by a caller(__mem_cgroup_try_charge would be useful). If @uncharge is
2554  * true, this function does "uncharge" from old cgroup, but it doesn't if
2555  * @uncharge is false, so a caller should do "uncharge".
2556  */
2557 static int mem_cgroup_move_account(struct page *page,
2558                                    unsigned int nr_pages,
2559                                    struct page_cgroup *pc,
2560                                    struct mem_cgroup *from,
2561                                    struct mem_cgroup *to,
2562                                    bool uncharge)
2563 {
2564         unsigned long flags;
2565         int ret;
2566
2567         VM_BUG_ON(from == to);
2568         VM_BUG_ON(PageLRU(page));
2569         /*
2570          * The page is isolated from LRU. So, collapse function
2571          * will not handle this page. But page splitting can happen.
2572          * Do this check under compound_page_lock(). The caller should
2573          * hold it.
2574          */
2575         ret = -EBUSY;
2576         if (nr_pages > 1 && !PageTransHuge(page))
2577                 goto out;
2578
2579         lock_page_cgroup(pc);
2580
2581         ret = -EINVAL;
2582         if (!PageCgroupUsed(pc) || pc->mem_cgroup != from)
2583                 goto unlock;
2584
2585         move_lock_page_cgroup(pc, &flags);
2586
2587         if (PageCgroupFileMapped(pc)) {
2588                 /* Update mapped_file data for mem_cgroup */
2589                 preempt_disable();
2590                 __this_cpu_dec(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
2591                 __this_cpu_inc(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
2592                 preempt_enable();
2593         }
2594         mem_cgroup_charge_statistics(from, PageCgroupCache(pc), -nr_pages);
2595         if (uncharge)
2596                 /* This is not "cancel", but cancel_charge does all we need. */
2597                 __mem_cgroup_cancel_charge(from, nr_pages);
2598
2599         /* caller should have done css_get */
2600         pc->mem_cgroup = to;
2601         mem_cgroup_charge_statistics(to, PageCgroupCache(pc), nr_pages);
2602         /*
2603          * We charges against "to" which may not have any tasks. Then, "to"
2604          * can be under rmdir(). But in current implementation, caller of
2605          * this function is just force_empty() and move charge, so it's
2606          * guaranteed that "to" is never removed. So, we don't check rmdir
2607          * status here.
2608          */
2609         move_unlock_page_cgroup(pc, &flags);
2610         ret = 0;
2611 unlock:
2612         unlock_page_cgroup(pc);
2613         /*
2614          * check events
2615          */
2616         memcg_check_events(to, page);
2617         memcg_check_events(from, page);
2618 out:
2619         return ret;
2620 }
2621
2622 /*
2623  * move charges to its parent.
2624  */
2625
2626 static int mem_cgroup_move_parent(struct page *page,
2627                                   struct page_cgroup *pc,
2628                                   struct mem_cgroup *child,
2629                                   gfp_t gfp_mask)
2630 {
2631         struct cgroup *cg = child->css.cgroup;
2632         struct cgroup *pcg = cg->parent;
2633         struct mem_cgroup *parent;
2634         unsigned int nr_pages;
2635         unsigned long uninitialized_var(flags);
2636         int ret;
2637
2638         /* Is ROOT ? */
2639         if (!pcg)
2640                 return -EINVAL;
2641
2642         ret = -EBUSY;
2643         if (!get_page_unless_zero(page))
2644                 goto out;
2645         if (isolate_lru_page(page))
2646                 goto put;
2647
2648         nr_pages = hpage_nr_pages(page);
2649
2650         parent = mem_cgroup_from_cont(pcg);
2651         ret = __mem_cgroup_try_charge(NULL, gfp_mask, nr_pages, &parent, false);
2652         if (ret || !parent)
2653                 goto put_back;
2654
2655         if (nr_pages > 1)
2656                 flags = compound_lock_irqsave(page);
2657
2658         ret = mem_cgroup_move_account(page, nr_pages, pc, child, parent, true);
2659         if (ret)
2660                 __mem_cgroup_cancel_charge(parent, nr_pages);
2661
2662         if (nr_pages > 1)
2663                 compound_unlock_irqrestore(page, flags);
2664 put_back:
2665         putback_lru_page(page);
2666 put:
2667         put_page(page);
2668 out:
2669         return ret;
2670 }
2671
2672 /*
2673  * Charge the memory controller for page usage.
2674  * Return
2675  * 0 if the charge was successful
2676  * < 0 if the cgroup is over its limit
2677  */
2678 static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
2679                                 gfp_t gfp_mask, enum charge_type ctype)
2680 {
2681         struct mem_cgroup *memcg = NULL;
2682         unsigned int nr_pages = 1;
2683         struct page_cgroup *pc;
2684         bool oom = true;
2685         int ret;
2686
2687         if (PageTransHuge(page)) {
2688                 nr_pages <<= compound_order(page);
2689                 VM_BUG_ON(!PageTransHuge(page));
2690                 /*
2691                  * Never OOM-kill a process for a huge page.  The
2692                  * fault handler will fall back to regular pages.
2693                  */
2694                 oom = false;
2695         }
2696
2697         pc = lookup_page_cgroup(page);
2698         BUG_ON(!pc); /* XXX: remove this and move pc lookup into commit */
2699
2700         ret = __mem_cgroup_try_charge(mm, gfp_mask, nr_pages, &memcg, oom);
2701         if (ret || !memcg)
2702                 return ret;
2703
2704         __mem_cgroup_commit_charge(memcg, page, nr_pages, pc, ctype);
2705         return 0;
2706 }
2707
2708 int mem_cgroup_newpage_charge(struct page *page,
2709                               struct mm_struct *mm, gfp_t gfp_mask)
2710 {
2711         if (mem_cgroup_disabled())
2712                 return 0;
2713         /*
2714          * If already mapped, we don't have to account.
2715          * If page cache, page->mapping has address_space.
2716          * But page->mapping may have out-of-use anon_vma pointer,
2717          * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
2718          * is NULL.
2719          */
2720         if (page_mapped(page) || (page->mapping && !PageAnon(page)))
2721                 return 0;
2722         if (unlikely(!mm))
2723                 mm = &init_mm;
2724         return mem_cgroup_charge_common(page, mm, gfp_mask,
2725                                 MEM_CGROUP_CHARGE_TYPE_MAPPED);
2726 }
2727
2728 static void
2729 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
2730                                         enum charge_type ctype);
2731
2732 static void
2733 __mem_cgroup_commit_charge_lrucare(struct page *page, struct mem_cgroup *memcg,
2734                                         enum charge_type ctype)
2735 {
2736         struct page_cgroup *pc = lookup_page_cgroup(page);
2737         /*
2738          * In some case, SwapCache, FUSE(splice_buf->radixtree), the page
2739          * is already on LRU. It means the page may on some other page_cgroup's
2740          * LRU. Take care of it.
2741          */
2742         mem_cgroup_lru_del_before_commit(page);
2743         __mem_cgroup_commit_charge(memcg, page, 1, pc, ctype);
2744         mem_cgroup_lru_add_after_commit(page);
2745         return;
2746 }
2747
2748 int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
2749                                 gfp_t gfp_mask)
2750 {
2751         struct mem_cgroup *memcg = NULL;
2752         int ret;
2753
2754         if (mem_cgroup_disabled())
2755                 return 0;
2756         if (PageCompound(page))
2757                 return 0;
2758
2759         if (unlikely(!mm))
2760                 mm = &init_mm;
2761
2762         if (page_is_file_cache(page)) {
2763                 ret = __mem_cgroup_try_charge(mm, gfp_mask, 1, &memcg, true);
2764                 if (ret || !memcg)
2765                         return ret;
2766
2767                 /*
2768                  * FUSE reuses pages without going through the final
2769                  * put that would remove them from the LRU list, make
2770                  * sure that they get relinked properly.
2771                  */
2772                 __mem_cgroup_commit_charge_lrucare(page, memcg,
2773                                         MEM_CGROUP_CHARGE_TYPE_CACHE);
2774                 return ret;
2775         }
2776         /* shmem */
2777         if (PageSwapCache(page)) {
2778                 ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &memcg);
2779                 if (!ret)
2780                         __mem_cgroup_commit_charge_swapin(page, memcg,
2781                                         MEM_CGROUP_CHARGE_TYPE_SHMEM);
2782         } else
2783                 ret = mem_cgroup_charge_common(page, mm, gfp_mask,
2784                                         MEM_CGROUP_CHARGE_TYPE_SHMEM);
2785
2786         return ret;
2787 }
2788
2789 /*
2790  * While swap-in, try_charge -> commit or cancel, the page is locked.
2791  * And when try_charge() successfully returns, one refcnt to memcg without
2792  * struct page_cgroup is acquired. This refcnt will be consumed by
2793  * "commit()" or removed by "cancel()"
2794  */
2795 int mem_cgroup_try_charge_swapin(struct mm_struct *mm,
2796                                  struct page *page,
2797                                  gfp_t mask, struct mem_cgroup **ptr)
2798 {
2799         struct mem_cgroup *memcg;
2800         int ret;
2801
2802         *ptr = NULL;
2803
2804         if (mem_cgroup_disabled())
2805                 return 0;
2806
2807         if (!do_swap_account)
2808                 goto charge_cur_mm;
2809         /*
2810          * A racing thread's fault, or swapoff, may have already updated
2811          * the pte, and even removed page from swap cache: in those cases
2812          * do_swap_page()'s pte_same() test will fail; but there's also a
2813          * KSM case which does need to charge the page.
2814          */
2815         if (!PageSwapCache(page))
2816                 goto charge_cur_mm;
2817         memcg = try_get_mem_cgroup_from_page(page);
2818         if (!memcg)
2819                 goto charge_cur_mm;
2820         *ptr = memcg;
2821         ret = __mem_cgroup_try_charge(NULL, mask, 1, ptr, true);
2822         css_put(&memcg->css);
2823         return ret;
2824 charge_cur_mm:
2825         if (unlikely(!mm))
2826                 mm = &init_mm;
2827         return __mem_cgroup_try_charge(mm, mask, 1, ptr, true);
2828 }
2829
2830 static void
2831 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
2832                                         enum charge_type ctype)
2833 {
2834         if (mem_cgroup_disabled())
2835                 return;
2836         if (!ptr)
2837                 return;
2838         cgroup_exclude_rmdir(&ptr->css);
2839
2840         __mem_cgroup_commit_charge_lrucare(page, ptr, ctype);
2841         /*
2842          * Now swap is on-memory. This means this page may be
2843          * counted both as mem and swap....double count.
2844          * Fix it by uncharging from memsw. Basically, this SwapCache is stable
2845          * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
2846          * may call delete_from_swap_cache() before reach here.
2847          */
2848         if (do_swap_account && PageSwapCache(page)) {
2849                 swp_entry_t ent = {.val = page_private(page)};
2850                 unsigned short id;
2851                 struct mem_cgroup *memcg;
2852
2853                 id = swap_cgroup_record(ent, 0);
2854                 rcu_read_lock();
2855                 memcg = mem_cgroup_lookup(id);
2856                 if (memcg) {
2857                         /*
2858                          * This recorded memcg can be obsolete one. So, avoid
2859                          * calling css_tryget
2860                          */
2861                         if (!mem_cgroup_is_root(memcg))
2862                                 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
2863                         mem_cgroup_swap_statistics(memcg, false);
2864                         mem_cgroup_put(memcg);
2865                 }
2866                 rcu_read_unlock();
2867         }
2868         /*
2869          * At swapin, we may charge account against cgroup which has no tasks.
2870          * So, rmdir()->pre_destroy() can be called while we do this charge.
2871          * In that case, we need to call pre_destroy() again. check it here.
2872          */
2873         cgroup_release_and_wakeup_rmdir(&ptr->css);
2874 }
2875
2876 void mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr)
2877 {
2878         __mem_cgroup_commit_charge_swapin(page, ptr,
2879                                         MEM_CGROUP_CHARGE_TYPE_MAPPED);
2880 }
2881
2882 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *memcg)
2883 {
2884         if (mem_cgroup_disabled())
2885                 return;
2886         if (!memcg)
2887                 return;
2888         __mem_cgroup_cancel_charge(memcg, 1);
2889 }
2890
2891 static void mem_cgroup_do_uncharge(struct mem_cgroup *memcg,
2892                                    unsigned int nr_pages,
2893                                    const enum charge_type ctype)
2894 {
2895         struct memcg_batch_info *batch = NULL;
2896         bool uncharge_memsw = true;
2897
2898         /* If swapout, usage of swap doesn't decrease */
2899         if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2900                 uncharge_memsw = false;
2901
2902         batch = &current->memcg_batch;
2903         /*
2904          * In usual, we do css_get() when we remember memcg pointer.
2905          * But in this case, we keep res->usage until end of a series of
2906          * uncharges. Then, it's ok to ignore memcg's refcnt.
2907          */
2908         if (!batch->memcg)
2909                 batch->memcg = memcg;
2910         /*
2911          * do_batch > 0 when unmapping pages or inode invalidate/truncate.
2912          * In those cases, all pages freed continuously can be expected to be in
2913          * the same cgroup and we have chance to coalesce uncharges.
2914          * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
2915          * because we want to do uncharge as soon as possible.
2916          */
2917
2918         if (!batch->do_batch || test_thread_flag(TIF_MEMDIE))
2919                 goto direct_uncharge;
2920
2921         if (nr_pages > 1)
2922                 goto direct_uncharge;
2923
2924         /*
2925          * In typical case, batch->memcg == mem. This means we can
2926          * merge a series of uncharges to an uncharge of res_counter.
2927          * If not, we uncharge res_counter ony by one.
2928          */
2929         if (batch->memcg != memcg)
2930                 goto direct_uncharge;
2931         /* remember freed charge and uncharge it later */
2932         batch->nr_pages++;
2933         if (uncharge_memsw)
2934                 batch->memsw_nr_pages++;
2935         return;
2936 direct_uncharge:
2937         res_counter_uncharge(&memcg->res, nr_pages * PAGE_SIZE);
2938         if (uncharge_memsw)
2939                 res_counter_uncharge(&memcg->memsw, nr_pages * PAGE_SIZE);
2940         if (unlikely(batch->memcg != memcg))
2941                 memcg_oom_recover(memcg);
2942         return;
2943 }
2944
2945 /*
2946  * uncharge if !page_mapped(page)
2947  */
2948 static struct mem_cgroup *
2949 __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype)
2950 {
2951         struct mem_cgroup *memcg = NULL;
2952         unsigned int nr_pages = 1;
2953         struct page_cgroup *pc;
2954
2955         if (mem_cgroup_disabled())
2956                 return NULL;
2957
2958         if (PageSwapCache(page))
2959                 return NULL;
2960
2961         if (PageTransHuge(page)) {
2962                 nr_pages <<= compound_order(page);
2963                 VM_BUG_ON(!PageTransHuge(page));
2964         }
2965         /*
2966          * Check if our page_cgroup is valid
2967          */
2968         pc = lookup_page_cgroup(page);
2969         if (unlikely(!pc || !PageCgroupUsed(pc)))
2970                 return NULL;
2971
2972         lock_page_cgroup(pc);
2973
2974         memcg = pc->mem_cgroup;
2975
2976         if (!PageCgroupUsed(pc))
2977                 goto unlock_out;
2978
2979         switch (ctype) {
2980         case MEM_CGROUP_CHARGE_TYPE_MAPPED:
2981         case MEM_CGROUP_CHARGE_TYPE_DROP:
2982                 /* See mem_cgroup_prepare_migration() */
2983                 if (page_mapped(page) || PageCgroupMigration(pc))
2984                         goto unlock_out;
2985                 break;
2986         case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
2987                 if (!PageAnon(page)) {  /* Shared memory */
2988                         if (page->mapping && !page_is_file_cache(page))
2989                                 goto unlock_out;
2990                 } else if (page_mapped(page)) /* Anon */
2991                                 goto unlock_out;
2992                 break;
2993         default:
2994                 break;
2995         }
2996
2997         mem_cgroup_charge_statistics(memcg, PageCgroupCache(pc), -nr_pages);
2998
2999         ClearPageCgroupUsed(pc);
3000         /*
3001          * pc->mem_cgroup is not cleared here. It will be accessed when it's
3002          * freed from LRU. This is safe because uncharged page is expected not
3003          * to be reused (freed soon). Exception is SwapCache, it's handled by
3004          * special functions.
3005          */
3006
3007         unlock_page_cgroup(pc);
3008         /*
3009          * even after unlock, we have memcg->res.usage here and this memcg
3010          * will never be freed.
3011          */
3012         memcg_check_events(memcg, page);
3013         if (do_swap_account && ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT) {
3014                 mem_cgroup_swap_statistics(memcg, true);
3015                 mem_cgroup_get(memcg);
3016         }
3017         if (!mem_cgroup_is_root(memcg))
3018                 mem_cgroup_do_uncharge(memcg, nr_pages, ctype);
3019
3020         return memcg;
3021
3022 unlock_out:
3023         unlock_page_cgroup(pc);
3024         return NULL;
3025 }
3026
3027 void mem_cgroup_uncharge_page(struct page *page)
3028 {
3029         /* early check. */
3030         if (page_mapped(page))
3031                 return;
3032         if (page->mapping && !PageAnon(page))
3033                 return;
3034         __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_MAPPED);
3035 }
3036
3037 void mem_cgroup_uncharge_cache_page(struct page *page)
3038 {
3039         VM_BUG_ON(page_mapped(page));
3040         VM_BUG_ON(page->mapping);
3041         __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE);
3042 }
3043
3044 /*
3045  * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
3046  * In that cases, pages are freed continuously and we can expect pages
3047  * are in the same memcg. All these calls itself limits the number of
3048  * pages freed at once, then uncharge_start/end() is called properly.
3049  * This may be called prural(2) times in a context,
3050  */
3051
3052 void mem_cgroup_uncharge_start(void)
3053 {
3054         current->memcg_batch.do_batch++;
3055         /* We can do nest. */
3056         if (current->memcg_batch.do_batch == 1) {
3057                 current->memcg_batch.memcg = NULL;
3058                 current->memcg_batch.nr_pages = 0;
3059                 current->memcg_batch.memsw_nr_pages = 0;
3060         }
3061 }
3062
3063 void mem_cgroup_uncharge_end(void)
3064 {
3065         struct memcg_batch_info *batch = &current->memcg_batch;
3066
3067         if (!batch->do_batch)
3068                 return;
3069
3070         batch->do_batch--;
3071         if (batch->do_batch) /* If stacked, do nothing. */
3072                 return;
3073
3074         if (!batch->memcg)
3075                 return;
3076         /*
3077          * This "batch->memcg" is valid without any css_get/put etc...
3078          * bacause we hide charges behind us.
3079          */
3080         if (batch->nr_pages)
3081                 res_counter_uncharge(&batch->memcg->res,
3082                                      batch->nr_pages * PAGE_SIZE);
3083         if (batch->memsw_nr_pages)
3084                 res_counter_uncharge(&batch->memcg->memsw,
3085                                      batch->memsw_nr_pages * PAGE_SIZE);
3086         memcg_oom_recover(batch->memcg);
3087         /* forget this pointer (for sanity check) */
3088         batch->memcg = NULL;
3089 }
3090
3091 #ifdef CONFIG_SWAP
3092 /*
3093  * called after __delete_from_swap_cache() and drop "page" account.
3094  * memcg information is recorded to swap_cgroup of "ent"
3095  */
3096 void
3097 mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
3098 {
3099         struct mem_cgroup *memcg;
3100         int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
3101
3102         if (!swapout) /* this was a swap cache but the swap is unused ! */
3103                 ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
3104
3105         memcg = __mem_cgroup_uncharge_common(page, ctype);
3106
3107         /*
3108          * record memcg information,  if swapout && memcg != NULL,
3109          * mem_cgroup_get() was called in uncharge().
3110          */
3111         if (do_swap_account && swapout && memcg)
3112                 swap_cgroup_record(ent, css_id(&memcg->css));
3113 }
3114 #endif
3115
3116 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3117 /*
3118  * called from swap_entry_free(). remove record in swap_cgroup and
3119  * uncharge "memsw" account.
3120  */
3121 void mem_cgroup_uncharge_swap(swp_entry_t ent)
3122 {
3123         struct mem_cgroup *memcg;
3124         unsigned short id;
3125
3126         if (!do_swap_account)
3127                 return;
3128
3129         id = swap_cgroup_record(ent, 0);
3130         rcu_read_lock();
3131         memcg = mem_cgroup_lookup(id);
3132         if (memcg) {
3133                 /*
3134                  * We uncharge this because swap is freed.
3135                  * This memcg can be obsolete one. We avoid calling css_tryget
3136                  */
3137                 if (!mem_cgroup_is_root(memcg))
3138                         res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
3139                 mem_cgroup_swap_statistics(memcg, false);
3140                 mem_cgroup_put(memcg);
3141         }
3142         rcu_read_unlock();
3143 }
3144
3145 /**
3146  * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3147  * @entry: swap entry to be moved
3148  * @from:  mem_cgroup which the entry is moved from
3149  * @to:  mem_cgroup which the entry is moved to
3150  * @need_fixup: whether we should fixup res_counters and refcounts.
3151  *
3152  * It succeeds only when the swap_cgroup's record for this entry is the same
3153  * as the mem_cgroup's id of @from.
3154  *
3155  * Returns 0 on success, -EINVAL on failure.
3156  *
3157  * The caller must have charged to @to, IOW, called res_counter_charge() about
3158  * both res and memsw, and called css_get().
3159  */
3160 static int mem_cgroup_move_swap_account(swp_entry_t entry,
3161                 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
3162 {
3163         unsigned short old_id, new_id;
3164
3165         old_id = css_id(&from->css);
3166         new_id = css_id(&to->css);
3167
3168         if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
3169                 mem_cgroup_swap_statistics(from, false);
3170                 mem_cgroup_swap_statistics(to, true);
3171                 /*
3172                  * This function is only called from task migration context now.
3173                  * It postpones res_counter and refcount handling till the end
3174                  * of task migration(mem_cgroup_clear_mc()) for performance
3175                  * improvement. But we cannot postpone mem_cgroup_get(to)
3176                  * because if the process that has been moved to @to does
3177                  * swap-in, the refcount of @to might be decreased to 0.
3178                  */
3179                 mem_cgroup_get(to);
3180                 if (need_fixup) {
3181                         if (!mem_cgroup_is_root(from))
3182                                 res_counter_uncharge(&from->memsw, PAGE_SIZE);
3183                         mem_cgroup_put(from);
3184                         /*
3185                          * we charged both to->res and to->memsw, so we should
3186                          * uncharge to->res.
3187                          */
3188                         if (!mem_cgroup_is_root(to))
3189                                 res_counter_uncharge(&to->res, PAGE_SIZE);
3190                 }
3191                 return 0;
3192         }
3193         return -EINVAL;
3194 }
3195 #else
3196 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
3197                 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
3198 {
3199         return -EINVAL;
3200 }
3201 #endif
3202
3203 /*
3204  * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
3205  * page belongs to.
3206  */
3207 int mem_cgroup_prepare_migration(struct page *page,
3208         struct page *newpage, struct mem_cgroup **ptr, gfp_t gfp_mask)
3209 {
3210         struct mem_cgroup *memcg = NULL;
3211         struct page_cgroup *pc;
3212         enum charge_type ctype;
3213         int ret = 0;
3214
3215         *ptr = NULL;
3216
3217         VM_BUG_ON(PageTransHuge(page));
3218         if (mem_cgroup_disabled())
3219                 return 0;
3220
3221         pc = lookup_page_cgroup(page);
3222         lock_page_cgroup(pc);
3223         if (PageCgroupUsed(pc)) {
3224                 memcg = pc->mem_cgroup;
3225                 css_get(&memcg->css);
3226                 /*
3227                  * At migrating an anonymous page, its mapcount goes down
3228                  * to 0 and uncharge() will be called. But, even if it's fully
3229                  * unmapped, migration may fail and this page has to be
3230                  * charged again. We set MIGRATION flag here and delay uncharge
3231                  * until end_migration() is called
3232                  *
3233                  * Corner Case Thinking
3234                  * A)
3235                  * When the old page was mapped as Anon and it's unmap-and-freed
3236                  * while migration was ongoing.
3237                  * If unmap finds the old page, uncharge() of it will be delayed
3238                  * until end_migration(). If unmap finds a new page, it's
3239                  * uncharged when it make mapcount to be 1->0. If unmap code
3240                  * finds swap_migration_entry, the new page will not be mapped
3241                  * and end_migration() will find it(mapcount==0).
3242                  *
3243                  * B)
3244                  * When the old page was mapped but migraion fails, the kernel
3245                  * remaps it. A charge for it is kept by MIGRATION flag even
3246                  * if mapcount goes down to 0. We can do remap successfully
3247                  * without charging it again.
3248                  *
3249                  * C)
3250                  * The "old" page is under lock_page() until the end of
3251                  * migration, so, the old page itself will not be swapped-out.
3252                  * If the new page is swapped out before end_migraton, our
3253                  * hook to usual swap-out path will catch the event.
3254                  */
3255                 if (PageAnon(page))
3256                         SetPageCgroupMigration(pc);
3257         }
3258         unlock_page_cgroup(pc);
3259         /*
3260          * If the page is not charged at this point,
3261          * we return here.
3262          */
3263         if (!memcg)
3264                 return 0;
3265
3266         *ptr = memcg;
3267         ret = __mem_cgroup_try_charge(NULL, gfp_mask, 1, ptr, false);
3268         css_put(&memcg->css);/* drop extra refcnt */
3269         if (ret || *ptr == NULL) {
3270                 if (PageAnon(page)) {
3271                         lock_page_cgroup(pc);
3272                         ClearPageCgroupMigration(pc);
3273                         unlock_page_cgroup(pc);
3274                         /*
3275                          * The old page may be fully unmapped while we kept it.
3276                          */
3277                         mem_cgroup_uncharge_page(page);
3278                 }
3279                 return -ENOMEM;
3280         }
3281         /*
3282          * We charge new page before it's used/mapped. So, even if unlock_page()
3283          * is called before end_migration, we can catch all events on this new
3284          * page. In the case new page is migrated but not remapped, new page's
3285          * mapcount will be finally 0 and we call uncharge in end_migration().
3286          */
3287         pc = lookup_page_cgroup(newpage);
3288         if (PageAnon(page))
3289                 ctype = MEM_CGROUP_CHARGE_TYPE_MAPPED;
3290         else if (page_is_file_cache(page))
3291                 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
3292         else
3293                 ctype = MEM_CGROUP_CHARGE_TYPE_SHMEM;
3294         __mem_cgroup_commit_charge(memcg, page, 1, pc, ctype);
3295         return ret;
3296 }
3297
3298 /* remove redundant charge if migration failed*/
3299 void mem_cgroup_end_migration(struct mem_cgroup *memcg,
3300         struct page *oldpage, struct page *newpage, bool migration_ok)
3301 {
3302         struct page *used, *unused;
3303         struct page_cgroup *pc;
3304
3305         if (!memcg)
3306                 return;
3307         /* blocks rmdir() */
3308         cgroup_exclude_rmdir(&memcg->css);
3309         if (!migration_ok) {
3310                 used = oldpage;
3311                 unused = newpage;
3312         } else {
3313                 used = newpage;
3314                 unused = oldpage;
3315         }
3316         /*
3317          * We disallowed uncharge of pages under migration because mapcount
3318          * of the page goes down to zero, temporarly.
3319          * Clear the flag and check the page should be charged.
3320          */
3321         pc = lookup_page_cgroup(oldpage);
3322         lock_page_cgroup(pc);
3323         ClearPageCgroupMigration(pc);
3324         unlock_page_cgroup(pc);
3325
3326         __mem_cgroup_uncharge_common(unused, MEM_CGROUP_CHARGE_TYPE_FORCE);
3327
3328         /*
3329          * If a page is a file cache, radix-tree replacement is very atomic
3330          * and we can skip this check. When it was an Anon page, its mapcount
3331          * goes down to 0. But because we added MIGRATION flage, it's not
3332          * uncharged yet. There are several case but page->mapcount check
3333          * and USED bit check in mem_cgroup_uncharge_page() will do enough
3334          * check. (see prepare_charge() also)
3335          */
3336         if (PageAnon(used))
3337                 mem_cgroup_uncharge_page(used);
3338         /*
3339          * At migration, we may charge account against cgroup which has no
3340          * tasks.
3341          * So, rmdir()->pre_destroy() can be called while we do this charge.
3342          * In that case, we need to call pre_destroy() again. check it here.
3343          */
3344         cgroup_release_and_wakeup_rmdir(&memcg->css);
3345 }
3346
3347 #ifdef CONFIG_DEBUG_VM
3348 static struct page_cgroup *lookup_page_cgroup_used(struct page *page)
3349 {
3350         struct page_cgroup *pc;
3351
3352         pc = lookup_page_cgroup(page);
3353         if (likely(pc) && PageCgroupUsed(pc))
3354                 return pc;
3355         return NULL;
3356 }
3357
3358 bool mem_cgroup_bad_page_check(struct page *page)
3359 {
3360         if (mem_cgroup_disabled())
3361                 return false;
3362
3363         return lookup_page_cgroup_used(page) != NULL;
3364 }
3365
3366 void mem_cgroup_print_bad_page(struct page *page)
3367 {
3368         struct page_cgroup *pc;
3369
3370         pc = lookup_page_cgroup_used(page);
3371         if (pc) {
3372                 int ret = -1;
3373                 char *path;
3374
3375                 printk(KERN_ALERT "pc:%p pc->flags:%lx pc->mem_cgroup:%p",
3376                        pc, pc->flags, pc->mem_cgroup);
3377
3378                 path = kmalloc(PATH_MAX, GFP_KERNEL);
3379                 if (path) {
3380                         rcu_read_lock();
3381                         ret = cgroup_path(pc->mem_cgroup->css.cgroup,
3382                                                         path, PATH_MAX);
3383                         rcu_read_unlock();
3384                 }
3385
3386                 printk(KERN_CONT "(%s)\n",
3387                                 (ret < 0) ? "cannot get the path" : path);
3388                 kfree(path);
3389         }
3390 }
3391 #endif
3392
3393 static DEFINE_MUTEX(set_limit_mutex);
3394
3395 static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
3396                                 unsigned long long val)
3397 {
3398         int retry_count;
3399         u64 memswlimit, memlimit;
3400         int ret = 0;
3401         int children = mem_cgroup_count_children(memcg);
3402         u64 curusage, oldusage;
3403         int enlarge;
3404
3405         /*
3406          * For keeping hierarchical_reclaim simple, how long we should retry
3407          * is depends on callers. We set our retry-count to be function
3408          * of # of children which we should visit in this loop.
3409          */
3410         retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
3411
3412         oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
3413
3414         enlarge = 0;
3415         while (retry_count) {
3416                 if (signal_pending(current)) {
3417                         ret = -EINTR;
3418                         break;
3419                 }
3420                 /*
3421                  * Rather than hide all in some function, I do this in
3422                  * open coded manner. You see what this really does.
3423                  * We have to guarantee memcg->res.limit < memcg->memsw.limit.
3424                  */
3425                 mutex_lock(&set_limit_mutex);
3426                 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3427                 if (memswlimit < val) {
3428                         ret = -EINVAL;
3429                         mutex_unlock(&set_limit_mutex);
3430                         break;
3431                 }
3432
3433                 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3434                 if (memlimit < val)
3435                         enlarge = 1;
3436
3437                 ret = res_counter_set_limit(&memcg->res, val);
3438                 if (!ret) {
3439                         if (memswlimit == val)
3440                                 memcg->memsw_is_minimum = true;
3441                         else
3442                                 memcg->memsw_is_minimum = false;
3443                 }
3444                 mutex_unlock(&set_limit_mutex);
3445
3446                 if (!ret)
3447                         break;
3448
3449                 mem_cgroup_reclaim(memcg, GFP_KERNEL,
3450                                    MEM_CGROUP_RECLAIM_SHRINK);
3451                 curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
3452                 /* Usage is reduced ? */
3453                 if (curusage >= oldusage)
3454                         retry_count--;
3455                 else
3456                         oldusage = curusage;
3457         }
3458         if (!ret && enlarge)
3459                 memcg_oom_recover(memcg);
3460
3461         return ret;
3462 }
3463
3464 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
3465                                         unsigned long long val)
3466 {
3467         int retry_count;
3468         u64 memlimit, memswlimit, oldusage, curusage;
3469         int children = mem_cgroup_count_children(memcg);
3470         int ret = -EBUSY;
3471         int enlarge = 0;
3472
3473         /* see mem_cgroup_resize_res_limit */
3474         retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
3475         oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
3476         while (retry_count) {
3477                 if (signal_pending(current)) {
3478                         ret = -EINTR;
3479                         break;
3480                 }
3481                 /*
3482                  * Rather than hide all in some function, I do this in
3483                  * open coded manner. You see what this really does.
3484                  * We have to guarantee memcg->res.limit < memcg->memsw.limit.
3485                  */
3486                 mutex_lock(&set_limit_mutex);
3487                 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3488                 if (memlimit > val) {
3489                         ret = -EINVAL;
3490                         mutex_unlock(&set_limit_mutex);
3491                         break;
3492                 }
3493                 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3494                 if (memswlimit < val)
3495                         enlarge = 1;
3496                 ret = res_counter_set_limit(&memcg->memsw, val);
3497                 if (!ret) {
3498                         if (memlimit == val)
3499                                 memcg->memsw_is_minimum = true;
3500                         else
3501                                 memcg->memsw_is_minimum = false;
3502                 }
3503                 mutex_unlock(&set_limit_mutex);
3504
3505                 if (!ret)
3506                         break;
3507
3508                 mem_cgroup_reclaim(memcg, GFP_KERNEL,
3509                                    MEM_CGROUP_RECLAIM_NOSWAP |
3510                                    MEM_CGROUP_RECLAIM_SHRINK);
3511                 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
3512                 /* Usage is reduced ? */
3513                 if (curusage >= oldusage)
3514                         retry_count--;
3515                 else
3516                         oldusage = curusage;
3517         }
3518         if (!ret && enlarge)
3519                 memcg_oom_recover(memcg);
3520         return ret;
3521 }
3522
3523 unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
3524                                             gfp_t gfp_mask,
3525                                             unsigned long *total_scanned)
3526 {
3527         unsigned long nr_reclaimed = 0;
3528         struct mem_cgroup_per_zone *mz, *next_mz = NULL;
3529         unsigned long reclaimed;
3530         int loop = 0;
3531         struct mem_cgroup_tree_per_zone *mctz;
3532         unsigned long long excess;
3533         unsigned long nr_scanned;
3534
3535         if (order > 0)
3536                 return 0;
3537
3538         mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone));
3539         /*
3540          * This loop can run a while, specially if mem_cgroup's continuously
3541          * keep exceeding their soft limit and putting the system under
3542          * pressure
3543          */
3544         do {
3545                 if (next_mz)
3546                         mz = next_mz;
3547                 else
3548                         mz = mem_cgroup_largest_soft_limit_node(mctz);
3549                 if (!mz)
3550                         break;
3551
3552                 nr_scanned = 0;
3553                 reclaimed = mem_cgroup_soft_reclaim(mz->mem, zone,
3554                                                     gfp_mask, &nr_scanned);
3555                 nr_reclaimed += reclaimed;
3556                 *total_scanned += nr_scanned;
3557                 spin_lock(&mctz->lock);
3558
3559                 /*
3560                  * If we failed to reclaim anything from this memory cgroup
3561                  * it is time to move on to the next cgroup
3562                  */
3563                 next_mz = NULL;
3564                 if (!reclaimed) {
3565                         do {
3566                                 /*
3567                                  * Loop until we find yet another one.
3568                                  *
3569                                  * By the time we get the soft_limit lock
3570                                  * again, someone might have aded the
3571                                  * group back on the RB tree. Iterate to
3572                                  * make sure we get a different mem.
3573                                  * mem_cgroup_largest_soft_limit_node returns
3574                                  * NULL if no other cgroup is present on
3575                                  * the tree
3576                                  */
3577                                 next_mz =
3578                                 __mem_cgroup_largest_soft_limit_node(mctz);
3579                                 if (next_mz == mz)
3580                                         css_put(&next_mz->mem->css);
3581                                 else /* next_mz == NULL or other memcg */
3582                                         break;
3583                         } while (1);
3584                 }
3585                 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
3586                 excess = res_counter_soft_limit_excess(&mz->mem->res);
3587                 /*
3588                  * One school of thought says that we should not add
3589                  * back the node to the tree if reclaim returns 0.
3590                  * But our reclaim could return 0, simply because due
3591                  * to priority we are exposing a smaller subset of
3592                  * memory to reclaim from. Consider this as a longer
3593                  * term TODO.
3594                  */
3595                 /* If excess == 0, no tree ops */
3596                 __mem_cgroup_insert_exceeded(mz->mem, mz, mctz, excess);
3597                 spin_unlock(&mctz->lock);
3598                 css_put(&mz->mem->css);
3599                 loop++;
3600                 /*
3601                  * Could not reclaim anything and there are no more
3602                  * mem cgroups to try or we seem to be looping without
3603                  * reclaiming anything.
3604                  */
3605                 if (!nr_reclaimed &&
3606                         (next_mz == NULL ||
3607                         loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3608                         break;
3609         } while (!nr_reclaimed);
3610         if (next_mz)
3611                 css_put(&next_mz->mem->css);
3612         return nr_reclaimed;
3613 }
3614
3615 /*
3616  * This routine traverse page_cgroup in given list and drop them all.
3617  * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
3618  */
3619 static int mem_cgroup_force_empty_list(struct mem_cgroup *memcg,
3620                                 int node, int zid, enum lru_list lru)
3621 {
3622         struct zone *zone;
3623         struct mem_cgroup_per_zone *mz;
3624         struct page_cgroup *pc, *busy;
3625         unsigned long flags, loop;
3626         struct list_head *list;
3627         int ret = 0;
3628
3629         zone = &NODE_DATA(node)->node_zones[zid];
3630         mz = mem_cgroup_zoneinfo(memcg, node, zid);
3631         list = &mz->lists[lru];
3632
3633         loop = MEM_CGROUP_ZSTAT(mz, lru);
3634         /* give some margin against EBUSY etc...*/
3635         loop += 256;
3636         busy = NULL;
3637         while (loop--) {
3638                 struct page *page;
3639
3640                 ret = 0;
3641                 spin_lock_irqsave(&zone->lru_lock, flags);
3642                 if (list_empty(list)) {
3643                         spin_unlock_irqrestore(&zone->lru_lock, flags);
3644                         break;
3645                 }
3646                 pc = list_entry(list->prev, struct page_cgroup, lru);
3647                 if (busy == pc) {
3648                         list_move(&pc->lru, list);
3649                         busy = NULL;
3650                         spin_unlock_irqrestore(&zone->lru_lock, flags);
3651                         continue;
3652                 }
3653                 spin_unlock_irqrestore(&zone->lru_lock, flags);
3654
3655                 page = lookup_cgroup_page(pc);
3656
3657                 ret = mem_cgroup_move_parent(page, pc, memcg, GFP_KERNEL);
3658                 if (ret == -ENOMEM)
3659                         break;
3660
3661                 if (ret == -EBUSY || ret == -EINVAL) {
3662                         /* found lock contention or "pc" is obsolete. */
3663                         busy = pc;
3664                         cond_resched();
3665                 } else
3666                         busy = NULL;
3667         }
3668
3669         if (!ret && !list_empty(list))
3670                 return -EBUSY;
3671         return ret;
3672 }
3673
3674 /*
3675  * make mem_cgroup's charge to be 0 if there is no task.
3676  * This enables deleting this mem_cgroup.
3677  */
3678 static int mem_cgroup_force_empty(struct mem_cgroup *memcg, bool free_all)
3679 {
3680         int ret;
3681         int node, zid, shrink;
3682         int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
3683         struct cgroup *cgrp = memcg->css.cgroup;
3684
3685         css_get(&memcg->css);
3686
3687         shrink = 0;
3688         /* should free all ? */
3689         if (free_all)
3690                 goto try_to_free;
3691 move_account:
3692         do {
3693                 ret = -EBUSY;
3694                 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
3695                         goto out;
3696                 ret = -EINTR;
3697                 if (signal_pending(current))
3698                         goto out;
3699                 /* This is for making all *used* pages to be on LRU. */
3700                 lru_add_drain_all();
3701                 drain_all_stock_sync(memcg);
3702                 ret = 0;
3703                 mem_cgroup_start_move(memcg);
3704                 for_each_node_state(node, N_HIGH_MEMORY) {
3705                         for (zid = 0; !ret && zid < MAX_NR_ZONES; zid++) {
3706                                 enum lru_list l;
3707                                 for_each_lru(l) {
3708                                         ret = mem_cgroup_force_empty_list(memcg,
3709                                                         node, zid, l);
3710                                         if (ret)
3711                                                 break;
3712                                 }
3713                         }
3714                         if (ret)
3715                                 break;
3716                 }
3717                 mem_cgroup_end_move(memcg);
3718                 memcg_oom_recover(memcg);
3719                 /* it seems parent cgroup doesn't have enough mem */
3720                 if (ret == -ENOMEM)
3721                         goto try_to_free;
3722                 cond_resched();
3723         /* "ret" should also be checked to ensure all lists are empty. */
3724         } while (memcg->res.usage > 0 || ret);
3725 out:
3726         css_put(&memcg->css);
3727         return ret;
3728
3729 try_to_free:
3730         /* returns EBUSY if there is a task or if we come here twice. */
3731         if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children) || shrink) {
3732                 ret = -EBUSY;
3733                 goto out;
3734         }
3735         /* we call try-to-free pages for make this cgroup empty */
3736         lru_add_drain_all();
3737         /* try to free all pages in this cgroup */
3738         shrink = 1;
3739         while (nr_retries && memcg->res.usage > 0) {
3740                 int progress;
3741
3742                 if (signal_pending(current)) {
3743                         ret = -EINTR;
3744                         goto out;
3745                 }
3746                 progress = try_to_free_mem_cgroup_pages(memcg, GFP_KERNEL,
3747                                                 false);
3748                 if (!progress) {
3749                         nr_retries--;
3750                         /* maybe some writeback is necessary */
3751                         congestion_wait(BLK_RW_ASYNC, HZ/10);
3752                 }
3753
3754         }
3755         lru_add_drain();
3756         /* try move_account...there may be some *locked* pages. */
3757         goto move_account;
3758 }
3759
3760 int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
3761 {
3762         return mem_cgroup_force_empty(mem_cgroup_from_cont(cont), true);
3763 }
3764
3765
3766 static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
3767 {
3768         return mem_cgroup_from_cont(cont)->use_hierarchy;
3769 }
3770
3771 static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
3772                                         u64 val)
3773 {
3774         int retval = 0;
3775         struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
3776         struct cgroup *parent = cont->parent;
3777         struct mem_cgroup *parent_memcg = NULL;
3778
3779         if (parent)
3780                 parent_memcg = mem_cgroup_from_cont(parent);
3781
3782         cgroup_lock();
3783         /*
3784          * If parent's use_hierarchy is set, we can't make any modifications
3785          * in the child subtrees. If it is unset, then the change can
3786          * occur, provided the current cgroup has no children.
3787          *
3788          * For the root cgroup, parent_mem is NULL, we allow value to be
3789          * set if there are no children.
3790          */
3791         if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
3792                                 (val == 1 || val == 0)) {
3793                 if (list_empty(&cont->children))
3794                         memcg->use_hierarchy = val;
3795                 else
3796                         retval = -EBUSY;
3797         } else
3798                 retval = -EINVAL;
3799         cgroup_unlock();
3800
3801         return retval;
3802 }
3803
3804
3805 static unsigned long mem_cgroup_recursive_stat(struct mem_cgroup *memcg,
3806                                                enum mem_cgroup_stat_index idx)
3807 {
3808         struct mem_cgroup *iter;
3809         long val = 0;
3810
3811         /* Per-cpu values can be negative, use a signed accumulator */
3812         for_each_mem_cgroup_tree(iter, memcg)
3813                 val += mem_cgroup_read_stat(iter, idx);
3814
3815         if (val < 0) /* race ? */
3816                 val = 0;
3817         return val;
3818 }
3819
3820 static inline u64 mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
3821 {
3822         u64 val;
3823
3824         if (!mem_cgroup_is_root(memcg)) {
3825                 if (!swap)
3826                         return res_counter_read_u64(&memcg->res, RES_USAGE);
3827                 else
3828                         return res_counter_read_u64(&memcg->memsw, RES_USAGE);
3829         }
3830
3831         val = mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_CACHE);
3832         val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_RSS);
3833
3834         if (swap)
3835                 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_SWAPOUT);
3836
3837         return val << PAGE_SHIFT;
3838 }
3839
3840 static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft)
3841 {
3842         struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
3843         u64 val;
3844         int type, name;
3845
3846         type = MEMFILE_TYPE(cft->private);
3847         name = MEMFILE_ATTR(cft->private);
3848         switch (type) {
3849         case _MEM:
3850                 if (name == RES_USAGE)
3851                         val = mem_cgroup_usage(memcg, false);
3852                 else
3853                         val = res_counter_read_u64(&memcg->res, name);
3854                 break;
3855         case _MEMSWAP:
3856                 if (name == RES_USAGE)
3857                         val = mem_cgroup_usage(memcg, true);
3858                 else
3859                         val = res_counter_read_u64(&memcg->memsw, name);
3860                 break;
3861         default:
3862                 BUG();
3863                 break;
3864         }
3865         return val;
3866 }
3867 /*
3868  * The user of this function is...
3869  * RES_LIMIT.
3870  */
3871 static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
3872                             const char *buffer)
3873 {
3874         struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
3875         int type, name;
3876         unsigned long long val;
3877         int ret;
3878
3879         type = MEMFILE_TYPE(cft->private);
3880         name = MEMFILE_ATTR(cft->private);
3881         switch (name) {
3882         case RES_LIMIT:
3883                 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3884                         ret = -EINVAL;
3885                         break;
3886                 }
3887                 /* This function does all necessary parse...reuse it */
3888                 ret = res_counter_memparse_write_strategy(buffer, &val);
3889                 if (ret)
3890                         break;
3891                 if (type == _MEM)
3892                         ret = mem_cgroup_resize_limit(memcg, val);
3893                 else
3894                         ret = mem_cgroup_resize_memsw_limit(memcg, val);
3895                 break;
3896         case RES_SOFT_LIMIT:
3897                 ret = res_counter_memparse_write_strategy(buffer, &val);
3898                 if (ret)
3899                         break;
3900                 /*
3901                  * For memsw, soft limits are hard to implement in terms
3902                  * of semantics, for now, we support soft limits for
3903                  * control without swap
3904                  */
3905                 if (type == _MEM)
3906                         ret = res_counter_set_soft_limit(&memcg->res, val);
3907                 else
3908                         ret = -EINVAL;
3909                 break;
3910         default:
3911                 ret = -EINVAL; /* should be BUG() ? */
3912                 break;
3913         }
3914         return ret;
3915 }
3916
3917 static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
3918                 unsigned long long *mem_limit, unsigned long long *memsw_limit)
3919 {
3920         struct cgroup *cgroup;
3921         unsigned long long min_limit, min_memsw_limit, tmp;
3922
3923         min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3924         min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3925         cgroup = memcg->css.cgroup;
3926         if (!memcg->use_hierarchy)
3927                 goto out;
3928
3929         while (cgroup->parent) {
3930                 cgroup = cgroup->parent;
3931                 memcg = mem_cgroup_from_cont(cgroup);
3932                 if (!memcg->use_hierarchy)
3933                         break;
3934                 tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
3935                 min_limit = min(min_limit, tmp);
3936                 tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3937                 min_memsw_limit = min(min_memsw_limit, tmp);
3938         }
3939 out:
3940         *mem_limit = min_limit;
3941         *memsw_limit = min_memsw_limit;
3942         return;
3943 }
3944
3945 static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
3946 {
3947         struct mem_cgroup *memcg;
3948         int type, name;
3949
3950         memcg = mem_cgroup_from_cont(cont);
3951         type = MEMFILE_TYPE(event);
3952         name = MEMFILE_ATTR(event);
3953         switch (name) {
3954         case RES_MAX_USAGE:
3955                 if (type == _MEM)
3956                         res_counter_reset_max(&memcg->res);
3957                 else
3958                         res_counter_reset_max(&memcg->memsw);
3959                 break;
3960         case RES_FAILCNT:
3961                 if (type == _MEM)
3962                         res_counter_reset_failcnt(&memcg->res);
3963                 else
3964                         res_counter_reset_failcnt(&memcg->memsw);
3965                 break;
3966         }
3967
3968         return 0;
3969 }
3970
3971 static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp,
3972                                         struct cftype *cft)
3973 {
3974         return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate;
3975 }
3976
3977 #ifdef CONFIG_MMU
3978 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
3979                                         struct cftype *cft, u64 val)
3980 {
3981         struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3982
3983         if (val >= (1 << NR_MOVE_TYPE))
3984                 return -EINVAL;
3985         /*
3986          * We check this value several times in both in can_attach() and
3987          * attach(), so we need cgroup lock to prevent this value from being
3988          * inconsistent.
3989          */
3990         cgroup_lock();
3991         memcg->move_charge_at_immigrate = val;
3992         cgroup_unlock();
3993
3994         return 0;
3995 }
3996 #else
3997 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
3998                                         struct cftype *cft, u64 val)
3999 {
4000         return -ENOSYS;
4001 }
4002 #endif
4003
4004
4005 /* For read statistics */
4006 enum {
4007         MCS_CACHE,
4008         MCS_RSS,
4009         MCS_FILE_MAPPED,
4010         MCS_PGPGIN,
4011         MCS_PGPGOUT,
4012         MCS_SWAP,
4013         MCS_PGFAULT,
4014         MCS_PGMAJFAULT,
4015         MCS_INACTIVE_ANON,
4016         MCS_ACTIVE_ANON,
4017         MCS_INACTIVE_FILE,
4018         MCS_ACTIVE_FILE,
4019         MCS_UNEVICTABLE,
4020         NR_MCS_STAT,
4021 };
4022
4023 struct mcs_total_stat {
4024         s64 stat[NR_MCS_STAT];
4025 };
4026
4027 struct {
4028         char *local_name;
4029         char *total_name;
4030 } memcg_stat_strings[NR_MCS_STAT] = {
4031         {"cache", "total_cache"},
4032         {"rss", "total_rss"},
4033         {"mapped_file", "total_mapped_file"},
4034         {"pgpgin", "total_pgpgin"},
4035         {"pgpgout", "total_pgpgout"},
4036         {"swap", "total_swap"},
4037         {"pgfault", "total_pgfault"},
4038         {"pgmajfault", "total_pgmajfault"},
4039         {"inactive_anon", "total_inactive_anon"},
4040         {"active_anon", "total_active_anon"},
4041         {"inactive_file", "total_inactive_file"},
4042         {"active_file", "total_active_file"},
4043         {"unevictable", "total_unevictable"}
4044 };
4045
4046
4047 static void
4048 mem_cgroup_get_local_stat(struct mem_cgroup *memcg, struct mcs_total_stat *s)
4049 {
4050         s64 val;
4051
4052         /* per cpu stat */
4053         val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_CACHE);
4054         s->stat[MCS_CACHE] += val * PAGE_SIZE;
4055         val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_RSS);
4056         s->stat[MCS_RSS] += val * PAGE_SIZE;
4057         val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_FILE_MAPPED);
4058         s->stat[MCS_FILE_MAPPED] += val * PAGE_SIZE;
4059         val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGPGIN);
4060         s->stat[MCS_PGPGIN] += val;
4061         val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGPGOUT);
4062         s->stat[MCS_PGPGOUT] += val;
4063         if (do_swap_account) {
4064                 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_SWAPOUT);
4065                 s->stat[MCS_SWAP] += val * PAGE_SIZE;
4066         }
4067         val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGFAULT);
4068         s->stat[MCS_PGFAULT] += val;
4069         val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGMAJFAULT);
4070         s->stat[MCS_PGMAJFAULT] += val;
4071
4072         /* per zone stat */
4073         val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_INACTIVE_ANON));
4074         s->stat[MCS_INACTIVE_ANON] += val * PAGE_SIZE;
4075         val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_ACTIVE_ANON));
4076         s->stat[MCS_ACTIVE_ANON] += val * PAGE_SIZE;
4077         val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_INACTIVE_FILE));
4078         s->stat[MCS_INACTIVE_FILE] += val * PAGE_SIZE;
4079         val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_ACTIVE_FILE));
4080         s->stat[MCS_ACTIVE_FILE] += val * PAGE_SIZE;
4081         val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_UNEVICTABLE));
4082         s->stat[MCS_UNEVICTABLE] += val * PAGE_SIZE;
4083 }
4084
4085 static void
4086 mem_cgroup_get_total_stat(struct mem_cgroup *memcg, struct mcs_total_stat *s)
4087 {
4088         struct mem_cgroup *iter;
4089
4090         for_each_mem_cgroup_tree(iter, memcg)
4091                 mem_cgroup_get_local_stat(iter, s);
4092 }
4093
4094 #ifdef CONFIG_NUMA
4095 static int mem_control_numa_stat_show(struct seq_file *m, void *arg)
4096 {
4097         int nid;
4098         unsigned long total_nr, file_nr, anon_nr, unevictable_nr;
4099         unsigned long node_nr;
4100         struct cgroup *cont = m->private;
4101         struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
4102
4103         total_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL);
4104         seq_printf(m, "total=%lu", total_nr);
4105         for_each_node_state(nid, N_HIGH_MEMORY) {
4106                 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid, LRU_ALL);
4107                 seq_printf(m, " N%d=%lu", nid, node_nr);
4108         }
4109         seq_putc(m, '\n');
4110
4111         file_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL_FILE);
4112         seq_printf(m, "file=%lu", file_nr);
4113         for_each_node_state(nid, N_HIGH_MEMORY) {
4114                 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4115                                 LRU_ALL_FILE);
4116                 seq_printf(m, " N%d=%lu", nid, node_nr);
4117         }
4118         seq_putc(m, '\n');
4119
4120         anon_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL_ANON);
4121         seq_printf(m, "anon=%lu", anon_nr);
4122         for_each_node_state(nid, N_HIGH_MEMORY) {
4123                 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4124                                 LRU_ALL_ANON);
4125                 seq_printf(m, " N%d=%lu", nid, node_nr);
4126         }
4127         seq_putc(m, '\n');
4128
4129         unevictable_nr = mem_cgroup_nr_lru_pages(mem_cont, BIT(LRU_UNEVICTABLE));
4130         seq_printf(m, "unevictable=%lu", unevictable_nr);
4131         for_each_node_state(nid, N_HIGH_MEMORY) {
4132                 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4133                                 BIT(LRU_UNEVICTABLE));
4134                 seq_printf(m, " N%d=%lu", nid, node_nr);
4135         }
4136         seq_putc(m, '\n');
4137         return 0;
4138 }
4139 #endif /* CONFIG_NUMA */
4140
4141 static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft,
4142                                  struct cgroup_map_cb *cb)
4143 {
4144         struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
4145         struct mcs_total_stat mystat;
4146         int i;
4147
4148         memset(&mystat, 0, sizeof(mystat));
4149         mem_cgroup_get_local_stat(mem_cont, &mystat);
4150
4151
4152         for (i = 0; i < NR_MCS_STAT; i++) {
4153                 if (i == MCS_SWAP && !do_swap_account)
4154                         continue;
4155                 cb->fill(cb, memcg_stat_strings[i].local_name, mystat.stat[i]);
4156         }
4157
4158         /* Hierarchical information */
4159         {
4160                 unsigned long long limit, memsw_limit;
4161                 memcg_get_hierarchical_limit(mem_cont, &limit, &memsw_limit);
4162                 cb->fill(cb, "hierarchical_memory_limit", limit);
4163                 if (do_swap_account)
4164                         cb->fill(cb, "hierarchical_memsw_limit", memsw_limit);
4165         }
4166
4167         memset(&mystat, 0, sizeof(mystat));
4168         mem_cgroup_get_total_stat(mem_cont, &mystat);
4169         for (i = 0; i < NR_MCS_STAT; i++) {
4170                 if (i == MCS_SWAP && !do_swap_account)
4171                         continue;
4172                 cb->fill(cb, memcg_stat_strings[i].total_name, mystat.stat[i]);
4173         }
4174
4175 #ifdef CONFIG_DEBUG_VM
4176         {
4177                 int nid, zid;
4178                 struct mem_cgroup_per_zone *mz;
4179                 unsigned long recent_rotated[2] = {0, 0};
4180                 unsigned long recent_scanned[2] = {0, 0};
4181
4182                 for_each_online_node(nid)
4183                         for (zid = 0; zid < MAX_NR_ZONES; zid++) {
4184                                 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
4185
4186                                 recent_rotated[0] +=
4187                                         mz->reclaim_stat.recent_rotated[0];
4188                                 recent_rotated[1] +=
4189                                         mz->reclaim_stat.recent_rotated[1];
4190                                 recent_scanned[0] +=
4191                                         mz->reclaim_stat.recent_scanned[0];
4192                                 recent_scanned[1] +=
4193                                         mz->reclaim_stat.recent_scanned[1];
4194                         }
4195                 cb->fill(cb, "recent_rotated_anon", recent_rotated[0]);
4196                 cb->fill(cb, "recent_rotated_file", recent_rotated[1]);
4197                 cb->fill(cb, "recent_scanned_anon", recent_scanned[0]);
4198                 cb->fill(cb, "recent_scanned_file", recent_scanned[1]);
4199         }
4200 #endif
4201
4202         return 0;
4203 }
4204
4205 static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
4206 {
4207         struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4208
4209         return mem_cgroup_swappiness(memcg);
4210 }
4211
4212 static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
4213                                        u64 val)
4214 {
4215         struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4216         struct mem_cgroup *parent;
4217
4218         if (val > 100)
4219                 return -EINVAL;
4220
4221         if (cgrp->parent == NULL)
4222                 return -EINVAL;
4223
4224         parent = mem_cgroup_from_cont(cgrp->parent);
4225
4226         cgroup_lock();
4227
4228         /* If under hierarchy, only empty-root can set this value */
4229         if ((parent->use_hierarchy) ||
4230             (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
4231                 cgroup_unlock();
4232                 return -EINVAL;
4233         }
4234
4235         memcg->swappiness = val;
4236
4237         cgroup_unlock();
4238
4239         return 0;
4240 }
4241
4242 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4243 {
4244         struct mem_cgroup_threshold_ary *t;
4245         u64 usage;
4246         int i;
4247
4248         rcu_read_lock();
4249         if (!swap)
4250                 t = rcu_dereference(memcg->thresholds.primary);
4251         else
4252                 t = rcu_dereference(memcg->memsw_thresholds.primary);
4253
4254         if (!t)
4255                 goto unlock;
4256
4257         usage = mem_cgroup_usage(memcg, swap);
4258
4259         /*
4260          * current_threshold points to threshold just below usage.
4261          * If it's not true, a threshold was crossed after last
4262          * call of __mem_cgroup_threshold().
4263          */
4264         i = t->current_threshold;
4265
4266         /*
4267          * Iterate backward over array of thresholds starting from
4268          * current_threshold and check if a threshold is crossed.
4269          * If none of thresholds below usage is crossed, we read
4270          * only one element of the array here.
4271          */
4272         for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4273                 eventfd_signal(t->entries[i].eventfd, 1);
4274
4275         /* i = current_threshold + 1 */
4276         i++;
4277
4278         /*
4279          * Iterate forward over array of thresholds starting from
4280          * current_threshold+1 and check if a threshold is crossed.
4281          * If none of thresholds above usage is crossed, we read
4282          * only one element of the array here.
4283          */
4284         for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4285                 eventfd_signal(t->entries[i].eventfd, 1);
4286
4287         /* Update current_threshold */
4288         t->current_threshold = i - 1;
4289 unlock:
4290         rcu_read_unlock();
4291 }
4292
4293 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4294 {
4295         while (memcg) {
4296                 __mem_cgroup_threshold(memcg, false);
4297                 if (do_swap_account)
4298                         __mem_cgroup_threshold(memcg, true);
4299
4300                 memcg = parent_mem_cgroup(memcg);
4301         }
4302 }
4303
4304 static int compare_thresholds(const void *a, const void *b)
4305 {
4306         const struct mem_cgroup_threshold *_a = a;
4307         const struct mem_cgroup_threshold *_b = b;
4308
4309         return _a->threshold - _b->threshold;
4310 }
4311
4312 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
4313 {
4314         struct mem_cgroup_eventfd_list *ev;
4315
4316         list_for_each_entry(ev, &memcg->oom_notify, list)
4317                 eventfd_signal(ev->eventfd, 1);
4318         return 0;
4319 }
4320
4321 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
4322 {
4323         struct mem_cgroup *iter;
4324
4325         for_each_mem_cgroup_tree(iter, memcg)
4326                 mem_cgroup_oom_notify_cb(iter);
4327 }
4328
4329 static int mem_cgroup_usage_register_event(struct cgroup *cgrp,
4330         struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
4331 {
4332         struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4333         struct mem_cgroup_thresholds *thresholds;
4334         struct mem_cgroup_threshold_ary *new;
4335         int type = MEMFILE_TYPE(cft->private);
4336         u64 threshold, usage;
4337         int i, size, ret;
4338
4339         ret = res_counter_memparse_write_strategy(args, &threshold);
4340         if (ret)
4341                 return ret;
4342
4343         mutex_lock(&memcg->thresholds_lock);
4344
4345         if (type == _MEM)
4346                 thresholds = &memcg->thresholds;
4347         else if (type == _MEMSWAP)
4348                 thresholds = &memcg->memsw_thresholds;
4349         else
4350                 BUG();
4351
4352         usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
4353
4354         /* Check if a threshold crossed before adding a new one */
4355         if (thresholds->primary)
4356                 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4357
4358         size = thresholds->primary ? thresholds->primary->size + 1 : 1;
4359
4360         /* Allocate memory for new array of thresholds */
4361         new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
4362                         GFP_KERNEL);
4363         if (!new) {
4364                 ret = -ENOMEM;
4365                 goto unlock;
4366         }
4367         new->size = size;
4368
4369         /* Copy thresholds (if any) to new array */
4370         if (thresholds->primary) {
4371                 memcpy(new->entries, thresholds->primary->entries, (size - 1) *
4372                                 sizeof(struct mem_cgroup_threshold));
4373         }
4374
4375         /* Add new threshold */
4376         new->entries[size - 1].eventfd = eventfd;
4377         new->entries[size - 1].threshold = threshold;
4378
4379         /* Sort thresholds. Registering of new threshold isn't time-critical */
4380         sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
4381                         compare_thresholds, NULL);
4382
4383         /* Find current threshold */
4384         new->current_threshold = -1;
4385         for (i = 0; i < size; i++) {
4386                 if (new->entries[i].threshold < usage) {
4387                         /*
4388                          * new->current_threshold will not be used until
4389                          * rcu_assign_pointer(), so it's safe to increment
4390                          * it here.
4391                          */
4392                         ++new->current_threshold;
4393                 }
4394         }
4395
4396         /* Free old spare buffer and save old primary buffer as spare */
4397         kfree(thresholds->spare);
4398         thresholds->spare = thresholds->primary;
4399
4400         rcu_assign_pointer(thresholds->primary, new);
4401
4402         /* To be sure that nobody uses thresholds */
4403         synchronize_rcu();
4404
4405 unlock:
4406         mutex_unlock(&memcg->thresholds_lock);
4407
4408         return ret;
4409 }
4410
4411 static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,
4412         struct cftype *cft, struct eventfd_ctx *eventfd)
4413 {
4414         struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4415         struct mem_cgroup_thresholds *thresholds;
4416         struct mem_cgroup_threshold_ary *new;
4417         int type = MEMFILE_TYPE(cft->private);
4418         u64 usage;
4419         int i, j, size;
4420
4421         mutex_lock(&memcg->thresholds_lock);
4422         if (type == _MEM)
4423                 thresholds = &memcg->thresholds;
4424         else if (type == _MEMSWAP)
4425                 thresholds = &memcg->memsw_thresholds;
4426         else
4427                 BUG();
4428
4429         /*
4430          * Something went wrong if we trying to unregister a threshold
4431          * if we don't have thresholds
4432          */
4433         BUG_ON(!thresholds);
4434
4435         usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
4436
4437         /* Check if a threshold crossed before removing */
4438         __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4439
4440         /* Calculate new number of threshold */
4441         size = 0;
4442         for (i = 0; i < thresholds->primary->size; i++) {
4443                 if (thresholds->primary->entries[i].eventfd != eventfd)
4444                         size++;
4445         }
4446
4447         new = thresholds->spare;
4448
4449         /* Set thresholds array to NULL if we don't have thresholds */
4450         if (!size) {
4451                 kfree(new);
4452                 new = NULL;
4453                 goto swap_buffers;
4454         }
4455
4456         new->size = size;
4457
4458         /* Copy thresholds and find current threshold */
4459         new->current_threshold = -1;
4460         for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4461                 if (thresholds->primary->entries[i].eventfd == eventfd)
4462                         continue;
4463
4464                 new->entries[j] = thresholds->primary->entries[i];
4465                 if (new->entries[j].threshold < usage) {
4466                         /*
4467                          * new->current_threshold will not be used
4468                          * until rcu_assign_pointer(), so it's safe to increment
4469                          * it here.
4470                          */
4471                         ++new->current_threshold;
4472                 }
4473                 j++;
4474         }
4475
4476 swap_buffers:
4477         /* Swap primary and spare array */
4478         thresholds->spare = thresholds->primary;
4479         rcu_assign_pointer(thresholds->primary, new);
4480
4481         /* To be sure that nobody uses thresholds */
4482         synchronize_rcu();
4483
4484         mutex_unlock(&memcg->thresholds_lock);
4485 }
4486
4487 static int mem_cgroup_oom_register_event(struct cgroup *cgrp,
4488         struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
4489 {
4490         struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4491         struct mem_cgroup_eventfd_list *event;
4492         int type = MEMFILE_TYPE(cft->private);
4493
4494         BUG_ON(type != _OOM_TYPE);
4495         event = kmalloc(sizeof(*event), GFP_KERNEL);
4496         if (!event)
4497                 return -ENOMEM;
4498
4499         spin_lock(&memcg_oom_lock);
4500
4501         event->eventfd = eventfd;
4502         list_add(&event->list, &memcg->oom_notify);
4503
4504         /* already in OOM ? */
4505         if (atomic_read(&memcg->under_oom))
4506                 eventfd_signal(eventfd, 1);
4507         spin_unlock(&memcg_oom_lock);
4508
4509         return 0;
4510 }
4511
4512 static void mem_cgroup_oom_unregister_event(struct cgroup *cgrp,
4513         struct cftype *cft, struct eventfd_ctx *eventfd)
4514 {
4515         struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4516         struct mem_cgroup_eventfd_list *ev, *tmp;
4517         int type = MEMFILE_TYPE(cft->private);
4518
4519         BUG_ON(type != _OOM_TYPE);
4520
4521         spin_lock(&memcg_oom_lock);
4522
4523         list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
4524                 if (ev->eventfd == eventfd) {
4525                         list_del(&ev->list);
4526                         kfree(ev);
4527                 }
4528         }
4529
4530         spin_unlock(&memcg_oom_lock);
4531 }
4532
4533 static int mem_cgroup_oom_control_read(struct cgroup *cgrp,
4534         struct cftype *cft,  struct cgroup_map_cb *cb)
4535 {
4536         struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4537
4538         cb->fill(cb, "oom_kill_disable", memcg->oom_kill_disable);
4539
4540         if (atomic_read(&memcg->under_oom))
4541                 cb->fill(cb, "under_oom", 1);
4542         else
4543                 cb->fill(cb, "under_oom", 0);
4544         return 0;
4545 }
4546
4547 static int mem_cgroup_oom_control_write(struct cgroup *cgrp,
4548         struct cftype *cft, u64 val)
4549 {
4550         struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4551         struct mem_cgroup *parent;
4552
4553         /* cannot set to root cgroup and only 0 and 1 are allowed */
4554         if (!cgrp->parent || !((val == 0) || (val == 1)))
4555                 return -EINVAL;
4556
4557         parent = mem_cgroup_from_cont(cgrp->parent);
4558
4559         cgroup_lock();
4560         /* oom-kill-disable is a flag for subhierarchy. */
4561         if ((parent->use_hierarchy) ||
4562             (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
4563                 cgroup_unlock();
4564                 return -EINVAL;
4565         }
4566         memcg->oom_kill_disable = val;
4567         if (!val)
4568                 memcg_oom_recover(memcg);
4569         cgroup_unlock();
4570         return 0;
4571 }
4572
4573 #ifdef CONFIG_NUMA
4574 static const struct file_operations mem_control_numa_stat_file_operations = {
4575         .read = seq_read,
4576         .llseek = seq_lseek,
4577         .release = single_release,
4578 };
4579
4580 static int mem_control_numa_stat_open(struct inode *unused, struct file *file)
4581 {
4582         struct cgroup *cont = file->f_dentry->d_parent->d_fsdata;
4583
4584         file->f_op = &mem_control_numa_stat_file_operations;
4585         return single_open(file, mem_control_numa_stat_show, cont);
4586 }
4587 #endif /* CONFIG_NUMA */
4588
4589 static struct cftype mem_cgroup_files[] = {
4590         {
4591                 .name = "usage_in_bytes",
4592                 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
4593                 .read_u64 = mem_cgroup_read,
4594                 .register_event = mem_cgroup_usage_register_event,
4595                 .unregister_event = mem_cgroup_usage_unregister_event,
4596         },
4597         {
4598                 .name = "max_usage_in_bytes",
4599                 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
4600                 .trigger = mem_cgroup_reset,
4601                 .read_u64 = mem_cgroup_read,
4602         },
4603         {
4604                 .name = "limit_in_bytes",
4605                 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
4606                 .write_string = mem_cgroup_write,
4607                 .read_u64 = mem_cgroup_read,
4608         },
4609         {
4610                 .name = "soft_limit_in_bytes",
4611                 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
4612                 .write_string = mem_cgroup_write,
4613                 .read_u64 = mem_cgroup_read,
4614         },
4615         {
4616                 .name = "failcnt",
4617                 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
4618                 .trigger = mem_cgroup_reset,
4619                 .read_u64 = mem_cgroup_read,
4620         },
4621         {
4622                 .name = "stat",
4623                 .read_map = mem_control_stat_show,
4624         },
4625         {
4626                 .name = "force_empty",
4627                 .trigger = mem_cgroup_force_empty_write,
4628         },
4629         {
4630                 .name = "use_hierarchy",
4631                 .write_u64 = mem_cgroup_hierarchy_write,
4632                 .read_u64 = mem_cgroup_hierarchy_read,
4633         },
4634         {
4635                 .name = "swappiness",
4636                 .read_u64 = mem_cgroup_swappiness_read,
4637                 .write_u64 = mem_cgroup_swappiness_write,
4638         },
4639         {
4640                 .name = "move_charge_at_immigrate",
4641                 .read_u64 = mem_cgroup_move_charge_read,
4642                 .write_u64 = mem_cgroup_move_charge_write,
4643         },
4644         {
4645                 .name = "oom_control",
4646                 .read_map = mem_cgroup_oom_control_read,
4647                 .write_u64 = mem_cgroup_oom_control_write,
4648                 .register_event = mem_cgroup_oom_register_event,
4649                 .unregister_event = mem_cgroup_oom_unregister_event,
4650                 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
4651         },
4652 #ifdef CONFIG_NUMA
4653         {
4654                 .name = "numa_stat",
4655                 .open = mem_control_numa_stat_open,
4656                 .mode = S_IRUGO,
4657         },
4658 #endif
4659 };
4660
4661 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4662 static struct cftype memsw_cgroup_files[] = {
4663         {
4664                 .name = "memsw.usage_in_bytes",
4665                 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
4666                 .read_u64 = mem_cgroup_read,
4667                 .register_event = mem_cgroup_usage_register_event,
4668                 .unregister_event = mem_cgroup_usage_unregister_event,
4669         },
4670         {
4671                 .name = "memsw.max_usage_in_bytes",
4672                 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
4673                 .trigger = mem_cgroup_reset,
4674                 .read_u64 = mem_cgroup_read,
4675         },
4676         {
4677                 .name = "memsw.limit_in_bytes",
4678                 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
4679                 .write_string = mem_cgroup_write,
4680                 .read_u64 = mem_cgroup_read,
4681         },
4682         {
4683                 .name = "memsw.failcnt",
4684                 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
4685                 .trigger = mem_cgroup_reset,
4686                 .read_u64 = mem_cgroup_read,
4687         },
4688 };
4689
4690 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
4691 {
4692         if (!do_swap_account)
4693                 return 0;
4694         return cgroup_add_files(cont, ss, memsw_cgroup_files,
4695                                 ARRAY_SIZE(memsw_cgroup_files));
4696 };
4697 #else
4698 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
4699 {
4700         return 0;
4701 }
4702 #endif
4703
4704 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
4705 {
4706         struct mem_cgroup_per_node *pn;
4707         struct mem_cgroup_per_zone *mz;
4708         enum lru_list l;
4709         int zone, tmp = node;
4710         /*
4711          * This routine is called against possible nodes.
4712          * But it's BUG to call kmalloc() against offline node.
4713          *
4714          * TODO: this routine can waste much memory for nodes which will
4715          *       never be onlined. It's better to use memory hotplug callback
4716          *       function.
4717          */
4718         if (!node_state(node, N_NORMAL_MEMORY))
4719                 tmp = -1;
4720         pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
4721         if (!pn)
4722                 return 1;
4723
4724         for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4725                 mz = &pn->zoneinfo[zone];
4726                 for_each_lru(l)
4727                         INIT_LIST_HEAD(&mz->lists[l]);
4728                 mz->usage_in_excess = 0;
4729                 mz->on_tree = false;
4730                 mz->mem = memcg;
4731         }
4732         memcg->info.nodeinfo[node] = pn;
4733         return 0;
4734 }
4735
4736 static void free_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
4737 {
4738         kfree(memcg->info.nodeinfo[node]);
4739 }
4740
4741 static struct mem_cgroup *mem_cgroup_alloc(void)
4742 {
4743         struct mem_cgroup *mem;
4744         int size = sizeof(struct mem_cgroup);
4745
4746         /* Can be very big if MAX_NUMNODES is very big */
4747         if (size < PAGE_SIZE)
4748                 mem = kzalloc(size, GFP_KERNEL);
4749         else
4750                 mem = vzalloc(size);
4751
4752         if (!mem)
4753                 return NULL;
4754
4755         mem->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
4756         if (!mem->stat)
4757                 goto out_free;
4758         spin_lock_init(&mem->pcp_counter_lock);
4759         return mem;
4760
4761 out_free:
4762         if (size < PAGE_SIZE)
4763                 kfree(mem);
4764         else
4765                 vfree(mem);
4766         return NULL;
4767 }
4768
4769 /*
4770  * At destroying mem_cgroup, references from swap_cgroup can remain.
4771  * (scanning all at force_empty is too costly...)
4772  *
4773  * Instead of clearing all references at force_empty, we remember
4774  * the number of reference from swap_cgroup and free mem_cgroup when
4775  * it goes down to 0.
4776  *
4777  * Removal of cgroup itself succeeds regardless of refs from swap.
4778  */
4779
4780 static void __mem_cgroup_free(struct mem_cgroup *memcg)
4781 {
4782         int node;
4783
4784         mem_cgroup_remove_from_trees(memcg);
4785         free_css_id(&mem_cgroup_subsys, &memcg->css);
4786
4787         for_each_node_state(node, N_POSSIBLE)
4788                 free_mem_cgroup_per_zone_info(memcg, node);
4789
4790         free_percpu(memcg->stat);
4791         if (sizeof(struct mem_cgroup) < PAGE_SIZE)
4792                 kfree(memcg);
4793         else
4794                 vfree(memcg);
4795 }
4796
4797 static void mem_cgroup_get(struct mem_cgroup *memcg)
4798 {
4799         atomic_inc(&memcg->refcnt);
4800 }
4801
4802 static void __mem_cgroup_put(struct mem_cgroup *memcg, int count)
4803 {
4804         if (atomic_sub_and_test(count, &memcg->refcnt)) {
4805                 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
4806                 __mem_cgroup_free(memcg);
4807                 if (parent)
4808                         mem_cgroup_put(parent);
4809         }
4810 }
4811
4812 static void mem_cgroup_put(struct mem_cgroup *memcg)
4813 {
4814         __mem_cgroup_put(memcg, 1);
4815 }
4816
4817 /*
4818  * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
4819  */
4820 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg)
4821 {
4822         if (!memcg->res.parent)
4823                 return NULL;
4824         return mem_cgroup_from_res_counter(memcg->res.parent, res);
4825 }
4826
4827 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4828 static void __init enable_swap_cgroup(void)
4829 {
4830         if (!mem_cgroup_disabled() && really_do_swap_account)
4831                 do_swap_account = 1;
4832 }
4833 #else
4834 static void __init enable_swap_cgroup(void)
4835 {
4836 }
4837 #endif
4838
4839 static int mem_cgroup_soft_limit_tree_init(void)
4840 {
4841         struct mem_cgroup_tree_per_node *rtpn;
4842         struct mem_cgroup_tree_per_zone *rtpz;
4843         int tmp, node, zone;
4844
4845         for_each_node_state(node, N_POSSIBLE) {
4846                 tmp = node;
4847                 if (!node_state(node, N_NORMAL_MEMORY))
4848                         tmp = -1;
4849                 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
4850                 if (!rtpn)
4851                         return 1;
4852
4853                 soft_limit_tree.rb_tree_per_node[node] = rtpn;
4854
4855                 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4856                         rtpz = &rtpn->rb_tree_per_zone[zone];
4857                         rtpz->rb_root = RB_ROOT;
4858                         spin_lock_init(&rtpz->lock);
4859                 }
4860         }
4861         return 0;
4862 }
4863
4864 static struct cgroup_subsys_state * __ref
4865 mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
4866 {
4867         struct mem_cgroup *memcg, *parent;
4868         long error = -ENOMEM;
4869         int node;
4870
4871         memcg = mem_cgroup_alloc();
4872         if (!memcg)
4873                 return ERR_PTR(error);
4874
4875         for_each_node_state(node, N_POSSIBLE)
4876                 if (alloc_mem_cgroup_per_zone_info(memcg, node))
4877                         goto free_out;
4878
4879         /* root ? */
4880         if (cont->parent == NULL) {
4881                 int cpu;
4882                 enable_swap_cgroup();
4883                 parent = NULL;
4884                 root_mem_cgroup = memcg;
4885                 if (mem_cgroup_soft_limit_tree_init())
4886                         goto free_out;
4887                 for_each_possible_cpu(cpu) {
4888                         struct memcg_stock_pcp *stock =
4889                                                 &per_cpu(memcg_stock, cpu);
4890                         INIT_WORK(&stock->work, drain_local_stock);
4891                 }
4892                 hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
4893         } else {
4894                 parent = mem_cgroup_from_cont(cont->parent);
4895                 memcg->use_hierarchy = parent->use_hierarchy;
4896                 memcg->oom_kill_disable = parent->oom_kill_disable;
4897         }
4898
4899         if (parent && parent->use_hierarchy) {
4900                 res_counter_init(&memcg->res, &parent->res);
4901                 res_counter_init(&memcg->memsw, &parent->memsw);
4902                 /*
4903                  * We increment refcnt of the parent to ensure that we can
4904                  * safely access it on res_counter_charge/uncharge.
4905                  * This refcnt will be decremented when freeing this
4906                  * mem_cgroup(see mem_cgroup_put).
4907                  */
4908                 mem_cgroup_get(parent);
4909         } else {
4910                 res_counter_init(&memcg->res, NULL);
4911                 res_counter_init(&memcg->memsw, NULL);
4912         }
4913         memcg->last_scanned_node = MAX_NUMNODES;
4914         INIT_LIST_HEAD(&memcg->oom_notify);
4915
4916         if (parent)
4917                 memcg->swappiness = mem_cgroup_swappiness(parent);
4918         atomic_set(&memcg->refcnt, 1);
4919         memcg->move_charge_at_immigrate = 0;
4920         mutex_init(&memcg->thresholds_lock);
4921         return &memcg->css;
4922 free_out:
4923         __mem_cgroup_free(memcg);
4924         root_mem_cgroup = NULL;
4925         return ERR_PTR(error);
4926 }
4927
4928 static int mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
4929                                         struct cgroup *cont)
4930 {
4931         struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
4932
4933         return mem_cgroup_force_empty(memcg, false);
4934 }
4935
4936 static void mem_cgroup_destroy(struct cgroup_subsys *ss,
4937                                 struct cgroup *cont)
4938 {
4939         struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
4940
4941         mem_cgroup_put(memcg);
4942 }
4943
4944 static int mem_cgroup_populate(struct cgroup_subsys *ss,
4945                                 struct cgroup *cont)
4946 {
4947         int ret;
4948
4949         ret = cgroup_add_files(cont, ss, mem_cgroup_files,
4950                                 ARRAY_SIZE(mem_cgroup_files));
4951
4952         if (!ret)
4953                 ret = register_memsw_files(cont, ss);
4954         return ret;
4955 }
4956
4957 #ifdef CONFIG_MMU
4958 /* Handlers for move charge at task migration. */
4959 #define PRECHARGE_COUNT_AT_ONCE 256
4960 static int mem_cgroup_do_precharge(unsigned long count)
4961 {
4962         int ret = 0;
4963         int batch_count = PRECHARGE_COUNT_AT_ONCE;
4964         struct mem_cgroup *memcg = mc.to;
4965
4966         if (mem_cgroup_is_root(memcg)) {
4967                 mc.precharge += count;
4968                 /* we don't need css_get for root */
4969                 return ret;
4970         }
4971         /* try to charge at once */
4972         if (count > 1) {
4973                 struct res_counter *dummy;
4974                 /*
4975                  * "memcg" cannot be under rmdir() because we've already checked
4976                  * by cgroup_lock_live_cgroup() that it is not removed and we
4977                  * are still under the same cgroup_mutex. So we can postpone
4978                  * css_get().
4979                  */
4980                 if (res_counter_charge(&memcg->res, PAGE_SIZE * count, &dummy))
4981                         goto one_by_one;
4982                 if (do_swap_account && res_counter_charge(&memcg->memsw,
4983                                                 PAGE_SIZE * count, &dummy)) {
4984                         res_counter_uncharge(&memcg->res, PAGE_SIZE * count);
4985                         goto one_by_one;
4986                 }
4987                 mc.precharge += count;
4988                 return ret;
4989         }
4990 one_by_one:
4991         /* fall back to one by one charge */
4992         while (count--) {
4993                 if (signal_pending(current)) {
4994                         ret = -EINTR;
4995                         break;
4996                 }
4997                 if (!batch_count--) {
4998                         batch_count = PRECHARGE_COUNT_AT_ONCE;
4999                         cond_resched();
5000                 }
5001                 ret = __mem_cgroup_try_charge(NULL,
5002                                         GFP_KERNEL, 1, &memcg, false);
5003                 if (ret || !memcg)
5004                         /* mem_cgroup_clear_mc() will do uncharge later */
5005                         return -ENOMEM;
5006                 mc.precharge++;
5007         }
5008         return ret;
5009 }
5010
5011 /**
5012  * is_target_pte_for_mc - check a pte whether it is valid for move charge
5013  * @vma: the vma the pte to be checked belongs
5014  * @addr: the address corresponding to the pte to be checked
5015  * @ptent: the pte to be checked
5016  * @target: the pointer the target page or swap ent will be stored(can be NULL)
5017  *
5018  * Returns
5019  *   0(MC_TARGET_NONE): if the pte is not a target for move charge.
5020  *   1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5021  *     move charge. if @target is not NULL, the page is stored in target->page
5022  *     with extra refcnt got(Callers should handle it).
5023  *   2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5024  *     target for charge migration. if @target is not NULL, the entry is stored
5025  *     in target->ent.
5026  *
5027  * Called with pte lock held.
5028  */
5029 union mc_target {
5030         struct page     *page;
5031         swp_entry_t     ent;
5032 };
5033
5034 enum mc_target_type {
5035         MC_TARGET_NONE, /* not used */
5036         MC_TARGET_PAGE,
5037         MC_TARGET_SWAP,
5038 };
5039
5040 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5041                                                 unsigned long addr, pte_t ptent)
5042 {
5043         struct page *page = vm_normal_page(vma, addr, ptent);
5044
5045         if (!page || !page_mapped(page))
5046                 return NULL;
5047         if (PageAnon(page)) {
5048                 /* we don't move shared anon */
5049                 if (!move_anon() || page_mapcount(page) > 2)
5050                         return NULL;
5051         } else if (!move_file())
5052                 /* we ignore mapcount for file pages */
5053                 return NULL;
5054         if (!get_page_unless_zero(page))
5055                 return NULL;
5056
5057         return page;
5058 }
5059
5060 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5061                         unsigned long addr, pte_t ptent, swp_entry_t *entry)
5062 {
5063         int usage_count;
5064         struct page *page = NULL;
5065         swp_entry_t ent = pte_to_swp_entry(ptent);
5066
5067         if (!move_anon() || non_swap_entry(ent))
5068                 return NULL;
5069         usage_count = mem_cgroup_count_swap_user(ent, &page);
5070         if (usage_count > 1) { /* we don't move shared anon */
5071                 if (page)
5072                         put_page(page);
5073                 return NULL;
5074         }
5075         if (do_swap_account)
5076                 entry->val = ent.val;
5077
5078         return page;
5079 }
5080
5081 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5082                         unsigned long addr, pte_t ptent, swp_entry_t *entry)
5083 {
5084         struct page *page = NULL;
5085         struct inode *inode;
5086         struct address_space *mapping;
5087         pgoff_t pgoff;
5088
5089         if (!vma->vm_file) /* anonymous vma */
5090                 return NULL;
5091         if (!move_file())
5092                 return NULL;
5093
5094         inode = vma->vm_file->f_path.dentry->d_inode;
5095         mapping = vma->vm_file->f_mapping;
5096         if (pte_none(ptent))
5097                 pgoff = linear_page_index(vma, addr);
5098         else /* pte_file(ptent) is true */
5099                 pgoff = pte_to_pgoff(ptent);
5100
5101         /* page is moved even if it's not RSS of this task(page-faulted). */
5102         page = find_get_page(mapping, pgoff);
5103
5104 #ifdef CONFIG_SWAP
5105         /* shmem/tmpfs may report page out on swap: account for that too. */
5106         if (radix_tree_exceptional_entry(page)) {
5107                 swp_entry_t swap = radix_to_swp_entry(page);
5108                 if (do_swap_account)
5109                         *entry = swap;
5110                 page = find_get_page(&swapper_space, swap.val);
5111         }
5112 #endif
5113         return page;
5114 }
5115
5116 static int is_target_pte_for_mc(struct vm_area_struct *vma,
5117                 unsigned long addr, pte_t ptent, union mc_target *target)
5118 {
5119         struct page *page = NULL;
5120         struct page_cgroup *pc;
5121         int ret = 0;
5122         swp_entry_t ent = { .val = 0 };
5123
5124         if (pte_present(ptent))
5125                 page = mc_handle_present_pte(vma, addr, ptent);
5126         else if (is_swap_pte(ptent))
5127                 page = mc_handle_swap_pte(vma, addr, ptent, &ent);
5128         else if (pte_none(ptent) || pte_file(ptent))
5129                 page = mc_handle_file_pte(vma, addr, ptent, &ent);
5130
5131         if (!page && !ent.val)
5132                 return 0;
5133         if (page) {
5134                 pc = lookup_page_cgroup(page);
5135                 /*
5136                  * Do only loose check w/o page_cgroup lock.
5137                  * mem_cgroup_move_account() checks the pc is valid or not under
5138                  * the lock.
5139                  */
5140                 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
5141                         ret = MC_TARGET_PAGE;
5142                         if (target)
5143                                 target->page = page;
5144                 }
5145                 if (!ret || !target)
5146                         put_page(page);
5147         }
5148         /* There is a swap entry and a page doesn't exist or isn't charged */
5149         if (ent.val && !ret &&
5150                         css_id(&mc.from->css) == lookup_swap_cgroup(ent)) {
5151                 ret = MC_TARGET_SWAP;
5152                 if (target)
5153                         target->ent = ent;
5154         }
5155         return ret;
5156 }
5157
5158 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
5159                                         unsigned long addr, unsigned long end,
5160                                         struct mm_walk *walk)
5161 {
5162         struct vm_area_struct *vma = walk->private;
5163         pte_t *pte;
5164         spinlock_t *ptl;
5165
5166         split_huge_page_pmd(walk->mm, pmd);
5167
5168         pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5169         for (; addr != end; pte++, addr += PAGE_SIZE)
5170                 if (is_target_pte_for_mc(vma, addr, *pte, NULL))
5171                         mc.precharge++; /* increment precharge temporarily */
5172         pte_unmap_unlock(pte - 1, ptl);
5173         cond_resched();
5174
5175         return 0;
5176 }
5177
5178 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
5179 {
5180         unsigned long precharge;
5181         struct vm_area_struct *vma;
5182
5183         down_read(&mm->mmap_sem);
5184         for (vma = mm->mmap; vma; vma = vma->vm_next) {
5185                 struct mm_walk mem_cgroup_count_precharge_walk = {
5186                         .pmd_entry = mem_cgroup_count_precharge_pte_range,
5187                         .mm = mm,
5188                         .private = vma,
5189                 };
5190                 if (is_vm_hugetlb_page(vma))
5191                         continue;
5192                 walk_page_range(vma->vm_start, vma->vm_end,
5193                                         &mem_cgroup_count_precharge_walk);
5194         }
5195         up_read(&mm->mmap_sem);
5196
5197         precharge = mc.precharge;
5198         mc.precharge = 0;
5199
5200         return precharge;
5201 }
5202
5203 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
5204 {
5205         unsigned long precharge = mem_cgroup_count_precharge(mm);
5206
5207         VM_BUG_ON(mc.moving_task);
5208         mc.moving_task = current;
5209         return mem_cgroup_do_precharge(precharge);
5210 }
5211
5212 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5213 static void __mem_cgroup_clear_mc(void)
5214 {
5215         struct mem_cgroup *from = mc.from;
5216         struct mem_cgroup *to = mc.to;
5217
5218         /* we must uncharge all the leftover precharges from mc.to */
5219         if (mc.precharge) {
5220                 __mem_cgroup_cancel_charge(mc.to, mc.precharge);
5221                 mc.precharge = 0;
5222         }
5223         /*
5224          * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5225          * we must uncharge here.
5226          */
5227         if (mc.moved_charge) {
5228                 __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
5229                 mc.moved_charge = 0;
5230         }
5231         /* we must fixup refcnts and charges */
5232         if (mc.moved_swap) {
5233                 /* uncharge swap account from the old cgroup */
5234                 if (!mem_cgroup_is_root(mc.from))
5235                         res_counter_uncharge(&mc.from->memsw,
5236                                                 PAGE_SIZE * mc.moved_swap);
5237                 __mem_cgroup_put(mc.from, mc.moved_swap);
5238
5239                 if (!mem_cgroup_is_root(mc.to)) {
5240                         /*
5241                          * we charged both to->res and to->memsw, so we should
5242                          * uncharge to->res.
5243                          */
5244                         res_counter_uncharge(&mc.to->res,
5245                                                 PAGE_SIZE * mc.moved_swap);
5246                 }
5247                 /* we've already done mem_cgroup_get(mc.to) */
5248                 mc.moved_swap = 0;
5249         }
5250         memcg_oom_recover(from);
5251         memcg_oom_recover(to);
5252         wake_up_all(&mc.waitq);
5253 }
5254
5255 static void mem_cgroup_clear_mc(void)
5256 {
5257         struct mem_cgroup *from = mc.from;
5258
5259         /*
5260          * we must clear moving_task before waking up waiters at the end of
5261          * task migration.
5262          */
5263         mc.moving_task = NULL;
5264         __mem_cgroup_clear_mc();
5265         spin_lock(&mc.lock);
5266         mc.from = NULL;
5267         mc.to = NULL;
5268         spin_unlock(&mc.lock);
5269         mem_cgroup_end_move(from);
5270 }
5271
5272 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
5273                                 struct cgroup *cgroup,
5274                                 struct task_struct *p)
5275 {
5276         int ret = 0;
5277         struct mem_cgroup *memcg = mem_cgroup_from_cont(cgroup);
5278
5279         if (memcg->move_charge_at_immigrate) {
5280                 struct mm_struct *mm;
5281                 struct mem_cgroup *from = mem_cgroup_from_task(p);
5282
5283                 VM_BUG_ON(from == memcg);
5284
5285                 mm = get_task_mm(p);
5286                 if (!mm)
5287                         return 0;
5288                 /* We move charges only when we move a owner of the mm */
5289                 if (mm->owner == p) {
5290                         VM_BUG_ON(mc.from);
5291                         VM_BUG_ON(mc.to);
5292                         VM_BUG_ON(mc.precharge);
5293                         VM_BUG_ON(mc.moved_charge);
5294                         VM_BUG_ON(mc.moved_swap);
5295                         mem_cgroup_start_move(from);
5296                         spin_lock(&mc.lock);
5297                         mc.from = from;
5298                         mc.to = memcg;
5299                         spin_unlock(&mc.lock);
5300                         /* We set mc.moving_task later */
5301
5302                         ret = mem_cgroup_precharge_mc(mm);
5303                         if (ret)
5304                                 mem_cgroup_clear_mc();
5305                 }
5306                 mmput(mm);
5307         }
5308         return ret;
5309 }
5310
5311 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
5312                                 struct cgroup *cgroup,
5313                                 struct task_struct *p)
5314 {
5315         mem_cgroup_clear_mc();
5316 }
5317
5318 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
5319                                 unsigned long addr, unsigned long end,
5320                                 struct mm_walk *walk)
5321 {
5322         int ret = 0;
5323         struct vm_area_struct *vma = walk->private;
5324         pte_t *pte;
5325         spinlock_t *ptl;
5326
5327         split_huge_page_pmd(walk->mm, pmd);
5328 retry:
5329         pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5330         for (; addr != end; addr += PAGE_SIZE) {
5331                 pte_t ptent = *(pte++);
5332                 union mc_target target;
5333                 int type;
5334                 struct page *page;
5335                 struct page_cgroup *pc;
5336                 swp_entry_t ent;
5337
5338                 if (!mc.precharge)
5339                         break;
5340
5341                 type = is_target_pte_for_mc(vma, addr, ptent, &target);
5342                 switch (type) {
5343                 case MC_TARGET_PAGE:
5344                         page = target.page;
5345                         if (isolate_lru_page(page))
5346                                 goto put;
5347                         pc = lookup_page_cgroup(page);
5348                         if (!mem_cgroup_move_account(page, 1, pc,
5349                                                      mc.from, mc.to, false)) {
5350                                 mc.precharge--;
5351                                 /* we uncharge from mc.from later. */
5352                                 mc.moved_charge++;
5353                         }
5354                         putback_lru_page(page);
5355 put:                    /* is_target_pte_for_mc() gets the page */
5356                         put_page(page);
5357                         break;
5358                 case MC_TARGET_SWAP:
5359                         ent = target.ent;
5360                         if (!mem_cgroup_move_swap_account(ent,
5361                                                 mc.from, mc.to, false)) {
5362                                 mc.precharge--;
5363                                 /* we fixup refcnts and charges later. */
5364                                 mc.moved_swap++;
5365                         }
5366                         break;
5367                 default:
5368                         break;
5369                 }
5370         }
5371         pte_unmap_unlock(pte - 1, ptl);
5372         cond_resched();
5373
5374         if (addr != end) {
5375                 /*
5376                  * We have consumed all precharges we got in can_attach().
5377                  * We try charge one by one, but don't do any additional
5378                  * charges to mc.to if we have failed in charge once in attach()
5379                  * phase.
5380                  */
5381                 ret = mem_cgroup_do_precharge(1);
5382                 if (!ret)
5383                         goto retry;
5384         }
5385
5386         return ret;
5387 }
5388
5389 static void mem_cgroup_move_charge(struct mm_struct *mm)
5390 {
5391         struct vm_area_struct *vma;
5392
5393         lru_add_drain_all();
5394 retry:
5395         if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
5396                 /*
5397                  * Someone who are holding the mmap_sem might be waiting in
5398                  * waitq. So we cancel all extra charges, wake up all waiters,
5399                  * and retry. Because we cancel precharges, we might not be able
5400                  * to move enough charges, but moving charge is a best-effort
5401                  * feature anyway, so it wouldn't be a big problem.
5402                  */
5403                 __mem_cgroup_clear_mc();
5404                 cond_resched();
5405                 goto retry;
5406         }
5407         for (vma = mm->mmap; vma; vma = vma->vm_next) {
5408                 int ret;
5409                 struct mm_walk mem_cgroup_move_charge_walk = {
5410                         .pmd_entry = mem_cgroup_move_charge_pte_range,
5411                         .mm = mm,
5412                         .private = vma,
5413                 };
5414                 if (is_vm_hugetlb_page(vma))
5415                         continue;
5416                 ret = walk_page_range(vma->vm_start, vma->vm_end,
5417                                                 &mem_cgroup_move_charge_walk);
5418                 if (ret)
5419                         /*
5420                          * means we have consumed all precharges and failed in
5421                          * doing additional charge. Just abandon here.
5422                          */
5423                         break;
5424         }
5425         up_read(&mm->mmap_sem);
5426 }
5427
5428 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
5429                                 struct cgroup *cont,
5430                                 struct cgroup *old_cont,
5431                                 struct task_struct *p)
5432 {
5433         struct mm_struct *mm = get_task_mm(p);
5434
5435         if (mm) {
5436                 if (mc.to)
5437                         mem_cgroup_move_charge(mm);
5438                 put_swap_token(mm);
5439                 mmput(mm);
5440         }
5441         if (mc.to)
5442                 mem_cgroup_clear_mc();
5443 }
5444 #else   /* !CONFIG_MMU */
5445 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
5446                                 struct cgroup *cgroup,
5447                                 struct task_struct *p)
5448 {
5449         return 0;
5450 }
5451 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
5452                                 struct cgroup *cgroup,
5453                                 struct task_struct *p)
5454 {
5455 }
5456 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
5457                                 struct cgroup *cont,
5458                                 struct cgroup *old_cont,
5459                                 struct task_struct *p)
5460 {
5461 }
5462 #endif
5463
5464 struct cgroup_subsys mem_cgroup_subsys = {
5465         .name = "memory",
5466         .subsys_id = mem_cgroup_subsys_id,
5467         .create = mem_cgroup_create,
5468         .pre_destroy = mem_cgroup_pre_destroy,
5469         .destroy = mem_cgroup_destroy,
5470         .populate = mem_cgroup_populate,
5471         .can_attach = mem_cgroup_can_attach,
5472         .cancel_attach = mem_cgroup_cancel_attach,
5473         .attach = mem_cgroup_move_task,
5474         .early_init = 0,
5475         .use_id = 1,
5476 };
5477
5478 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
5479 static int __init enable_swap_account(char *s)
5480 {
5481         /* consider enabled if no parameter or 1 is given */
5482         if (!strcmp(s, "1"))
5483                 really_do_swap_account = 1;
5484         else if (!strcmp(s, "0"))
5485                 really_do_swap_account = 0;
5486         return 1;
5487 }
5488 __setup("swapaccount=", enable_swap_account);
5489
5490 #endif