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