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