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