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