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