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