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