mm, memcg: decouple e{low,min} state mutations from protection checks
[platform/kernel/linux-rpi.git] / mm / memcontrol.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* memcontrol.c - Memory Controller
3  *
4  * Copyright IBM Corporation, 2007
5  * Author Balbir Singh <balbir@linux.vnet.ibm.com>
6  *
7  * Copyright 2007 OpenVZ SWsoft Inc
8  * Author: Pavel Emelianov <xemul@openvz.org>
9  *
10  * Memory thresholds
11  * Copyright (C) 2009 Nokia Corporation
12  * Author: Kirill A. Shutemov
13  *
14  * Kernel Memory Controller
15  * Copyright (C) 2012 Parallels Inc. and Google Inc.
16  * Authors: Glauber Costa and Suleiman Souhlal
17  *
18  * Native page reclaim
19  * Charge lifetime sanitation
20  * Lockless page tracking & accounting
21  * Unified hierarchy configuration model
22  * Copyright (C) 2015 Red Hat, Inc., Johannes Weiner
23  */
24
25 #include <linux/page_counter.h>
26 #include <linux/memcontrol.h>
27 #include <linux/cgroup.h>
28 #include <linux/pagewalk.h>
29 #include <linux/sched/mm.h>
30 #include <linux/shmem_fs.h>
31 #include <linux/hugetlb.h>
32 #include <linux/pagemap.h>
33 #include <linux/vm_event_item.h>
34 #include <linux/smp.h>
35 #include <linux/page-flags.h>
36 #include <linux/backing-dev.h>
37 #include <linux/bit_spinlock.h>
38 #include <linux/rcupdate.h>
39 #include <linux/limits.h>
40 #include <linux/export.h>
41 #include <linux/mutex.h>
42 #include <linux/rbtree.h>
43 #include <linux/slab.h>
44 #include <linux/swap.h>
45 #include <linux/swapops.h>
46 #include <linux/spinlock.h>
47 #include <linux/eventfd.h>
48 #include <linux/poll.h>
49 #include <linux/sort.h>
50 #include <linux/fs.h>
51 #include <linux/seq_file.h>
52 #include <linux/vmpressure.h>
53 #include <linux/mm_inline.h>
54 #include <linux/swap_cgroup.h>
55 #include <linux/cpu.h>
56 #include <linux/oom.h>
57 #include <linux/lockdep.h>
58 #include <linux/file.h>
59 #include <linux/tracehook.h>
60 #include <linux/psi.h>
61 #include <linux/seq_buf.h>
62 #include "internal.h"
63 #include <net/sock.h>
64 #include <net/ip.h>
65 #include "slab.h"
66
67 #include <linux/uaccess.h>
68
69 #include <trace/events/vmscan.h>
70
71 struct cgroup_subsys memory_cgrp_subsys __read_mostly;
72 EXPORT_SYMBOL(memory_cgrp_subsys);
73
74 struct mem_cgroup *root_mem_cgroup __read_mostly;
75
76 #define MEM_CGROUP_RECLAIM_RETRIES      5
77
78 /* Socket memory accounting disabled? */
79 static bool cgroup_memory_nosocket;
80
81 /* Kernel memory accounting disabled? */
82 static bool cgroup_memory_nokmem;
83
84 /* Whether the swap controller is active */
85 #ifdef CONFIG_MEMCG_SWAP
86 int do_swap_account __read_mostly;
87 #else
88 #define do_swap_account         0
89 #endif
90
91 #ifdef CONFIG_CGROUP_WRITEBACK
92 static DECLARE_WAIT_QUEUE_HEAD(memcg_cgwb_frn_waitq);
93 #endif
94
95 /* Whether legacy memory+swap accounting is active */
96 static bool do_memsw_account(void)
97 {
98         return !cgroup_subsys_on_dfl(memory_cgrp_subsys) && do_swap_account;
99 }
100
101 static const char *const mem_cgroup_lru_names[] = {
102         "inactive_anon",
103         "active_anon",
104         "inactive_file",
105         "active_file",
106         "unevictable",
107 };
108
109 #define THRESHOLDS_EVENTS_TARGET 128
110 #define SOFTLIMIT_EVENTS_TARGET 1024
111 #define NUMAINFO_EVENTS_TARGET  1024
112
113 /*
114  * Cgroups above their limits are maintained in a RB-Tree, independent of
115  * their hierarchy representation
116  */
117
118 struct mem_cgroup_tree_per_node {
119         struct rb_root rb_root;
120         struct rb_node *rb_rightmost;
121         spinlock_t lock;
122 };
123
124 struct mem_cgroup_tree {
125         struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
126 };
127
128 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
129
130 /* for OOM */
131 struct mem_cgroup_eventfd_list {
132         struct list_head list;
133         struct eventfd_ctx *eventfd;
134 };
135
136 /*
137  * cgroup_event represents events which userspace want to receive.
138  */
139 struct mem_cgroup_event {
140         /*
141          * memcg which the event belongs to.
142          */
143         struct mem_cgroup *memcg;
144         /*
145          * eventfd to signal userspace about the event.
146          */
147         struct eventfd_ctx *eventfd;
148         /*
149          * Each of these stored in a list by the cgroup.
150          */
151         struct list_head list;
152         /*
153          * register_event() callback will be used to add new userspace
154          * waiter for changes related to this event.  Use eventfd_signal()
155          * on eventfd to send notification to userspace.
156          */
157         int (*register_event)(struct mem_cgroup *memcg,
158                               struct eventfd_ctx *eventfd, const char *args);
159         /*
160          * unregister_event() callback will be called when userspace closes
161          * the eventfd or on cgroup removing.  This callback must be set,
162          * if you want provide notification functionality.
163          */
164         void (*unregister_event)(struct mem_cgroup *memcg,
165                                  struct eventfd_ctx *eventfd);
166         /*
167          * All fields below needed to unregister event when
168          * userspace closes eventfd.
169          */
170         poll_table pt;
171         wait_queue_head_t *wqh;
172         wait_queue_entry_t wait;
173         struct work_struct remove;
174 };
175
176 static void mem_cgroup_threshold(struct mem_cgroup *memcg);
177 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
178
179 /* Stuffs for move charges at task migration. */
180 /*
181  * Types of charges to be moved.
182  */
183 #define MOVE_ANON       0x1U
184 #define MOVE_FILE       0x2U
185 #define MOVE_MASK       (MOVE_ANON | MOVE_FILE)
186
187 /* "mc" and its members are protected by cgroup_mutex */
188 static struct move_charge_struct {
189         spinlock_t        lock; /* for from, to */
190         struct mm_struct  *mm;
191         struct mem_cgroup *from;
192         struct mem_cgroup *to;
193         unsigned long flags;
194         unsigned long precharge;
195         unsigned long moved_charge;
196         unsigned long moved_swap;
197         struct task_struct *moving_task;        /* a task moving charges */
198         wait_queue_head_t waitq;                /* a waitq for other context */
199 } mc = {
200         .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
201         .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
202 };
203
204 /*
205  * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
206  * limit reclaim to prevent infinite loops, if they ever occur.
207  */
208 #define MEM_CGROUP_MAX_RECLAIM_LOOPS            100
209 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
210
211 enum charge_type {
212         MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
213         MEM_CGROUP_CHARGE_TYPE_ANON,
214         MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
215         MEM_CGROUP_CHARGE_TYPE_DROP,    /* a page was unused swap cache */
216         NR_CHARGE_TYPE,
217 };
218
219 /* for encoding cft->private value on file */
220 enum res_type {
221         _MEM,
222         _MEMSWAP,
223         _OOM_TYPE,
224         _KMEM,
225         _TCP,
226 };
227
228 #define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
229 #define MEMFILE_TYPE(val)       ((val) >> 16 & 0xffff)
230 #define MEMFILE_ATTR(val)       ((val) & 0xffff)
231 /* Used for OOM nofiier */
232 #define OOM_CONTROL             (0)
233
234 /*
235  * Iteration constructs for visiting all cgroups (under a tree).  If
236  * loops are exited prematurely (break), mem_cgroup_iter_break() must
237  * be used for reference counting.
238  */
239 #define for_each_mem_cgroup_tree(iter, root)            \
240         for (iter = mem_cgroup_iter(root, NULL, NULL);  \
241              iter != NULL;                              \
242              iter = mem_cgroup_iter(root, iter, NULL))
243
244 #define for_each_mem_cgroup(iter)                       \
245         for (iter = mem_cgroup_iter(NULL, NULL, NULL);  \
246              iter != NULL;                              \
247              iter = mem_cgroup_iter(NULL, iter, NULL))
248
249 static inline bool should_force_charge(void)
250 {
251         return tsk_is_oom_victim(current) || fatal_signal_pending(current) ||
252                 (current->flags & PF_EXITING);
253 }
254
255 /* Some nice accessors for the vmpressure. */
256 struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
257 {
258         if (!memcg)
259                 memcg = root_mem_cgroup;
260         return &memcg->vmpressure;
261 }
262
263 struct cgroup_subsys_state *vmpressure_to_css(struct vmpressure *vmpr)
264 {
265         return &container_of(vmpr, struct mem_cgroup, vmpressure)->css;
266 }
267
268 #ifdef CONFIG_MEMCG_KMEM
269 /*
270  * This will be the memcg's index in each cache's ->memcg_params.memcg_caches.
271  * The main reason for not using cgroup id for this:
272  *  this works better in sparse environments, where we have a lot of memcgs,
273  *  but only a few kmem-limited. Or also, if we have, for instance, 200
274  *  memcgs, and none but the 200th is kmem-limited, we'd have to have a
275  *  200 entry array for that.
276  *
277  * The current size of the caches array is stored in memcg_nr_cache_ids. It
278  * will double each time we have to increase it.
279  */
280 static DEFINE_IDA(memcg_cache_ida);
281 int memcg_nr_cache_ids;
282
283 /* Protects memcg_nr_cache_ids */
284 static DECLARE_RWSEM(memcg_cache_ids_sem);
285
286 void memcg_get_cache_ids(void)
287 {
288         down_read(&memcg_cache_ids_sem);
289 }
290
291 void memcg_put_cache_ids(void)
292 {
293         up_read(&memcg_cache_ids_sem);
294 }
295
296 /*
297  * MIN_SIZE is different than 1, because we would like to avoid going through
298  * the alloc/free process all the time. In a small machine, 4 kmem-limited
299  * cgroups is a reasonable guess. In the future, it could be a parameter or
300  * tunable, but that is strictly not necessary.
301  *
302  * MAX_SIZE should be as large as the number of cgrp_ids. Ideally, we could get
303  * this constant directly from cgroup, but it is understandable that this is
304  * better kept as an internal representation in cgroup.c. In any case, the
305  * cgrp_id space is not getting any smaller, and we don't have to necessarily
306  * increase ours as well if it increases.
307  */
308 #define MEMCG_CACHES_MIN_SIZE 4
309 #define MEMCG_CACHES_MAX_SIZE MEM_CGROUP_ID_MAX
310
311 /*
312  * A lot of the calls to the cache allocation functions are expected to be
313  * inlined by the compiler. Since the calls to memcg_kmem_get_cache are
314  * conditional to this static branch, we'll have to allow modules that does
315  * kmem_cache_alloc and the such to see this symbol as well
316  */
317 DEFINE_STATIC_KEY_FALSE(memcg_kmem_enabled_key);
318 EXPORT_SYMBOL(memcg_kmem_enabled_key);
319
320 struct workqueue_struct *memcg_kmem_cache_wq;
321 #endif
322
323 static int memcg_shrinker_map_size;
324 static DEFINE_MUTEX(memcg_shrinker_map_mutex);
325
326 static void memcg_free_shrinker_map_rcu(struct rcu_head *head)
327 {
328         kvfree(container_of(head, struct memcg_shrinker_map, rcu));
329 }
330
331 static int memcg_expand_one_shrinker_map(struct mem_cgroup *memcg,
332                                          int size, int old_size)
333 {
334         struct memcg_shrinker_map *new, *old;
335         int nid;
336
337         lockdep_assert_held(&memcg_shrinker_map_mutex);
338
339         for_each_node(nid) {
340                 old = rcu_dereference_protected(
341                         mem_cgroup_nodeinfo(memcg, nid)->shrinker_map, true);
342                 /* Not yet online memcg */
343                 if (!old)
344                         return 0;
345
346                 new = kvmalloc(sizeof(*new) + size, GFP_KERNEL);
347                 if (!new)
348                         return -ENOMEM;
349
350                 /* Set all old bits, clear all new bits */
351                 memset(new->map, (int)0xff, old_size);
352                 memset((void *)new->map + old_size, 0, size - old_size);
353
354                 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_map, new);
355                 call_rcu(&old->rcu, memcg_free_shrinker_map_rcu);
356         }
357
358         return 0;
359 }
360
361 static void memcg_free_shrinker_maps(struct mem_cgroup *memcg)
362 {
363         struct mem_cgroup_per_node *pn;
364         struct memcg_shrinker_map *map;
365         int nid;
366
367         if (mem_cgroup_is_root(memcg))
368                 return;
369
370         for_each_node(nid) {
371                 pn = mem_cgroup_nodeinfo(memcg, nid);
372                 map = rcu_dereference_protected(pn->shrinker_map, true);
373                 if (map)
374                         kvfree(map);
375                 rcu_assign_pointer(pn->shrinker_map, NULL);
376         }
377 }
378
379 static int memcg_alloc_shrinker_maps(struct mem_cgroup *memcg)
380 {
381         struct memcg_shrinker_map *map;
382         int nid, size, ret = 0;
383
384         if (mem_cgroup_is_root(memcg))
385                 return 0;
386
387         mutex_lock(&memcg_shrinker_map_mutex);
388         size = memcg_shrinker_map_size;
389         for_each_node(nid) {
390                 map = kvzalloc(sizeof(*map) + size, GFP_KERNEL);
391                 if (!map) {
392                         memcg_free_shrinker_maps(memcg);
393                         ret = -ENOMEM;
394                         break;
395                 }
396                 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_map, map);
397         }
398         mutex_unlock(&memcg_shrinker_map_mutex);
399
400         return ret;
401 }
402
403 int memcg_expand_shrinker_maps(int new_id)
404 {
405         int size, old_size, ret = 0;
406         struct mem_cgroup *memcg;
407
408         size = DIV_ROUND_UP(new_id + 1, BITS_PER_LONG) * sizeof(unsigned long);
409         old_size = memcg_shrinker_map_size;
410         if (size <= old_size)
411                 return 0;
412
413         mutex_lock(&memcg_shrinker_map_mutex);
414         if (!root_mem_cgroup)
415                 goto unlock;
416
417         for_each_mem_cgroup(memcg) {
418                 if (mem_cgroup_is_root(memcg))
419                         continue;
420                 ret = memcg_expand_one_shrinker_map(memcg, size, old_size);
421                 if (ret) {
422                         mem_cgroup_iter_break(NULL, memcg);
423                         goto unlock;
424                 }
425         }
426 unlock:
427         if (!ret)
428                 memcg_shrinker_map_size = size;
429         mutex_unlock(&memcg_shrinker_map_mutex);
430         return ret;
431 }
432
433 void memcg_set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
434 {
435         if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
436                 struct memcg_shrinker_map *map;
437
438                 rcu_read_lock();
439                 map = rcu_dereference(memcg->nodeinfo[nid]->shrinker_map);
440                 /* Pairs with smp mb in shrink_slab() */
441                 smp_mb__before_atomic();
442                 set_bit(shrinker_id, map->map);
443                 rcu_read_unlock();
444         }
445 }
446
447 /**
448  * mem_cgroup_css_from_page - css of the memcg associated with a page
449  * @page: page of interest
450  *
451  * If memcg is bound to the default hierarchy, css of the memcg associated
452  * with @page is returned.  The returned css remains associated with @page
453  * until it is released.
454  *
455  * If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup
456  * is returned.
457  */
458 struct cgroup_subsys_state *mem_cgroup_css_from_page(struct page *page)
459 {
460         struct mem_cgroup *memcg;
461
462         memcg = page->mem_cgroup;
463
464         if (!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
465                 memcg = root_mem_cgroup;
466
467         return &memcg->css;
468 }
469
470 /**
471  * page_cgroup_ino - return inode number of the memcg a page is charged to
472  * @page: the page
473  *
474  * Look up the closest online ancestor of the memory cgroup @page is charged to
475  * and return its inode number or 0 if @page is not charged to any cgroup. It
476  * is safe to call this function without holding a reference to @page.
477  *
478  * Note, this function is inherently racy, because there is nothing to prevent
479  * the cgroup inode from getting torn down and potentially reallocated a moment
480  * after page_cgroup_ino() returns, so it only should be used by callers that
481  * do not care (such as procfs interfaces).
482  */
483 ino_t page_cgroup_ino(struct page *page)
484 {
485         struct mem_cgroup *memcg;
486         unsigned long ino = 0;
487
488         rcu_read_lock();
489         if (PageSlab(page) && !PageTail(page))
490                 memcg = memcg_from_slab_page(page);
491         else
492                 memcg = READ_ONCE(page->mem_cgroup);
493         while (memcg && !(memcg->css.flags & CSS_ONLINE))
494                 memcg = parent_mem_cgroup(memcg);
495         if (memcg)
496                 ino = cgroup_ino(memcg->css.cgroup);
497         rcu_read_unlock();
498         return ino;
499 }
500
501 static struct mem_cgroup_per_node *
502 mem_cgroup_page_nodeinfo(struct mem_cgroup *memcg, struct page *page)
503 {
504         int nid = page_to_nid(page);
505
506         return memcg->nodeinfo[nid];
507 }
508
509 static struct mem_cgroup_tree_per_node *
510 soft_limit_tree_node(int nid)
511 {
512         return soft_limit_tree.rb_tree_per_node[nid];
513 }
514
515 static struct mem_cgroup_tree_per_node *
516 soft_limit_tree_from_page(struct page *page)
517 {
518         int nid = page_to_nid(page);
519
520         return soft_limit_tree.rb_tree_per_node[nid];
521 }
522
523 static void __mem_cgroup_insert_exceeded(struct mem_cgroup_per_node *mz,
524                                          struct mem_cgroup_tree_per_node *mctz,
525                                          unsigned long new_usage_in_excess)
526 {
527         struct rb_node **p = &mctz->rb_root.rb_node;
528         struct rb_node *parent = NULL;
529         struct mem_cgroup_per_node *mz_node;
530         bool rightmost = true;
531
532         if (mz->on_tree)
533                 return;
534
535         mz->usage_in_excess = new_usage_in_excess;
536         if (!mz->usage_in_excess)
537                 return;
538         while (*p) {
539                 parent = *p;
540                 mz_node = rb_entry(parent, struct mem_cgroup_per_node,
541                                         tree_node);
542                 if (mz->usage_in_excess < mz_node->usage_in_excess) {
543                         p = &(*p)->rb_left;
544                         rightmost = false;
545                 }
546
547                 /*
548                  * We can't avoid mem cgroups that are over their soft
549                  * limit by the same amount
550                  */
551                 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
552                         p = &(*p)->rb_right;
553         }
554
555         if (rightmost)
556                 mctz->rb_rightmost = &mz->tree_node;
557
558         rb_link_node(&mz->tree_node, parent, p);
559         rb_insert_color(&mz->tree_node, &mctz->rb_root);
560         mz->on_tree = true;
561 }
562
563 static void __mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
564                                          struct mem_cgroup_tree_per_node *mctz)
565 {
566         if (!mz->on_tree)
567                 return;
568
569         if (&mz->tree_node == mctz->rb_rightmost)
570                 mctz->rb_rightmost = rb_prev(&mz->tree_node);
571
572         rb_erase(&mz->tree_node, &mctz->rb_root);
573         mz->on_tree = false;
574 }
575
576 static void mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
577                                        struct mem_cgroup_tree_per_node *mctz)
578 {
579         unsigned long flags;
580
581         spin_lock_irqsave(&mctz->lock, flags);
582         __mem_cgroup_remove_exceeded(mz, mctz);
583         spin_unlock_irqrestore(&mctz->lock, flags);
584 }
585
586 static unsigned long soft_limit_excess(struct mem_cgroup *memcg)
587 {
588         unsigned long nr_pages = page_counter_read(&memcg->memory);
589         unsigned long soft_limit = READ_ONCE(memcg->soft_limit);
590         unsigned long excess = 0;
591
592         if (nr_pages > soft_limit)
593                 excess = nr_pages - soft_limit;
594
595         return excess;
596 }
597
598 static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
599 {
600         unsigned long excess;
601         struct mem_cgroup_per_node *mz;
602         struct mem_cgroup_tree_per_node *mctz;
603
604         mctz = soft_limit_tree_from_page(page);
605         if (!mctz)
606                 return;
607         /*
608          * Necessary to update all ancestors when hierarchy is used.
609          * because their event counter is not touched.
610          */
611         for (; memcg; memcg = parent_mem_cgroup(memcg)) {
612                 mz = mem_cgroup_page_nodeinfo(memcg, page);
613                 excess = soft_limit_excess(memcg);
614                 /*
615                  * We have to update the tree if mz is on RB-tree or
616                  * mem is over its softlimit.
617                  */
618                 if (excess || mz->on_tree) {
619                         unsigned long flags;
620
621                         spin_lock_irqsave(&mctz->lock, flags);
622                         /* if on-tree, remove it */
623                         if (mz->on_tree)
624                                 __mem_cgroup_remove_exceeded(mz, mctz);
625                         /*
626                          * Insert again. mz->usage_in_excess will be updated.
627                          * If excess is 0, no tree ops.
628                          */
629                         __mem_cgroup_insert_exceeded(mz, mctz, excess);
630                         spin_unlock_irqrestore(&mctz->lock, flags);
631                 }
632         }
633 }
634
635 static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
636 {
637         struct mem_cgroup_tree_per_node *mctz;
638         struct mem_cgroup_per_node *mz;
639         int nid;
640
641         for_each_node(nid) {
642                 mz = mem_cgroup_nodeinfo(memcg, nid);
643                 mctz = soft_limit_tree_node(nid);
644                 if (mctz)
645                         mem_cgroup_remove_exceeded(mz, mctz);
646         }
647 }
648
649 static struct mem_cgroup_per_node *
650 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
651 {
652         struct mem_cgroup_per_node *mz;
653
654 retry:
655         mz = NULL;
656         if (!mctz->rb_rightmost)
657                 goto done;              /* Nothing to reclaim from */
658
659         mz = rb_entry(mctz->rb_rightmost,
660                       struct mem_cgroup_per_node, tree_node);
661         /*
662          * Remove the node now but someone else can add it back,
663          * we will to add it back at the end of reclaim to its correct
664          * position in the tree.
665          */
666         __mem_cgroup_remove_exceeded(mz, mctz);
667         if (!soft_limit_excess(mz->memcg) ||
668             !css_tryget_online(&mz->memcg->css))
669                 goto retry;
670 done:
671         return mz;
672 }
673
674 static struct mem_cgroup_per_node *
675 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
676 {
677         struct mem_cgroup_per_node *mz;
678
679         spin_lock_irq(&mctz->lock);
680         mz = __mem_cgroup_largest_soft_limit_node(mctz);
681         spin_unlock_irq(&mctz->lock);
682         return mz;
683 }
684
685 /**
686  * __mod_memcg_state - update cgroup memory statistics
687  * @memcg: the memory cgroup
688  * @idx: the stat item - can be enum memcg_stat_item or enum node_stat_item
689  * @val: delta to add to the counter, can be negative
690  */
691 void __mod_memcg_state(struct mem_cgroup *memcg, int idx, int val)
692 {
693         long x;
694
695         if (mem_cgroup_disabled())
696                 return;
697
698         x = val + __this_cpu_read(memcg->vmstats_percpu->stat[idx]);
699         if (unlikely(abs(x) > MEMCG_CHARGE_BATCH)) {
700                 struct mem_cgroup *mi;
701
702                 /*
703                  * Batch local counters to keep them in sync with
704                  * the hierarchical ones.
705                  */
706                 __this_cpu_add(memcg->vmstats_local->stat[idx], x);
707                 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
708                         atomic_long_add(x, &mi->vmstats[idx]);
709                 x = 0;
710         }
711         __this_cpu_write(memcg->vmstats_percpu->stat[idx], x);
712 }
713
714 static struct mem_cgroup_per_node *
715 parent_nodeinfo(struct mem_cgroup_per_node *pn, int nid)
716 {
717         struct mem_cgroup *parent;
718
719         parent = parent_mem_cgroup(pn->memcg);
720         if (!parent)
721                 return NULL;
722         return mem_cgroup_nodeinfo(parent, nid);
723 }
724
725 /**
726  * __mod_lruvec_state - update lruvec memory statistics
727  * @lruvec: the lruvec
728  * @idx: the stat item
729  * @val: delta to add to the counter, can be negative
730  *
731  * The lruvec is the intersection of the NUMA node and a cgroup. This
732  * function updates the all three counters that are affected by a
733  * change of state at this level: per-node, per-cgroup, per-lruvec.
734  */
735 void __mod_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
736                         int val)
737 {
738         pg_data_t *pgdat = lruvec_pgdat(lruvec);
739         struct mem_cgroup_per_node *pn;
740         struct mem_cgroup *memcg;
741         long x;
742
743         /* Update node */
744         __mod_node_page_state(pgdat, idx, val);
745
746         if (mem_cgroup_disabled())
747                 return;
748
749         pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
750         memcg = pn->memcg;
751
752         /* Update memcg */
753         __mod_memcg_state(memcg, idx, val);
754
755         /* Update lruvec */
756         __this_cpu_add(pn->lruvec_stat_local->count[idx], val);
757
758         x = val + __this_cpu_read(pn->lruvec_stat_cpu->count[idx]);
759         if (unlikely(abs(x) > MEMCG_CHARGE_BATCH)) {
760                 struct mem_cgroup_per_node *pi;
761
762                 for (pi = pn; pi; pi = parent_nodeinfo(pi, pgdat->node_id))
763                         atomic_long_add(x, &pi->lruvec_stat[idx]);
764                 x = 0;
765         }
766         __this_cpu_write(pn->lruvec_stat_cpu->count[idx], x);
767 }
768
769 void __mod_lruvec_slab_state(void *p, enum node_stat_item idx, int val)
770 {
771         struct page *page = virt_to_head_page(p);
772         pg_data_t *pgdat = page_pgdat(page);
773         struct mem_cgroup *memcg;
774         struct lruvec *lruvec;
775
776         rcu_read_lock();
777         memcg = memcg_from_slab_page(page);
778
779         /* Untracked pages have no memcg, no lruvec. Update only the node */
780         if (!memcg || memcg == root_mem_cgroup) {
781                 __mod_node_page_state(pgdat, idx, val);
782         } else {
783                 lruvec = mem_cgroup_lruvec(memcg, pgdat);
784                 __mod_lruvec_state(lruvec, idx, val);
785         }
786         rcu_read_unlock();
787 }
788
789 void mod_memcg_obj_state(void *p, int idx, int val)
790 {
791         struct mem_cgroup *memcg;
792
793         rcu_read_lock();
794         memcg = mem_cgroup_from_obj(p);
795         if (memcg)
796                 mod_memcg_state(memcg, idx, val);
797         rcu_read_unlock();
798 }
799
800 /**
801  * __count_memcg_events - account VM events in a cgroup
802  * @memcg: the memory cgroup
803  * @idx: the event item
804  * @count: the number of events that occured
805  */
806 void __count_memcg_events(struct mem_cgroup *memcg, enum vm_event_item idx,
807                           unsigned long count)
808 {
809         unsigned long x;
810
811         if (mem_cgroup_disabled())
812                 return;
813
814         x = count + __this_cpu_read(memcg->vmstats_percpu->events[idx]);
815         if (unlikely(x > MEMCG_CHARGE_BATCH)) {
816                 struct mem_cgroup *mi;
817
818                 /*
819                  * Batch local counters to keep them in sync with
820                  * the hierarchical ones.
821                  */
822                 __this_cpu_add(memcg->vmstats_local->events[idx], x);
823                 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
824                         atomic_long_add(x, &mi->vmevents[idx]);
825                 x = 0;
826         }
827         __this_cpu_write(memcg->vmstats_percpu->events[idx], x);
828 }
829
830 static unsigned long memcg_events(struct mem_cgroup *memcg, int event)
831 {
832         return atomic_long_read(&memcg->vmevents[event]);
833 }
834
835 static unsigned long memcg_events_local(struct mem_cgroup *memcg, int event)
836 {
837         long x = 0;
838         int cpu;
839
840         for_each_possible_cpu(cpu)
841                 x += per_cpu(memcg->vmstats_local->events[event], cpu);
842         return x;
843 }
844
845 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
846                                          struct page *page,
847                                          bool compound, int nr_pages)
848 {
849         /*
850          * Here, RSS means 'mapped anon' and anon's SwapCache. Shmem/tmpfs is
851          * counted as CACHE even if it's on ANON LRU.
852          */
853         if (PageAnon(page))
854                 __mod_memcg_state(memcg, MEMCG_RSS, nr_pages);
855         else {
856                 __mod_memcg_state(memcg, MEMCG_CACHE, nr_pages);
857                 if (PageSwapBacked(page))
858                         __mod_memcg_state(memcg, NR_SHMEM, nr_pages);
859         }
860
861         if (compound) {
862                 VM_BUG_ON_PAGE(!PageTransHuge(page), page);
863                 __mod_memcg_state(memcg, MEMCG_RSS_HUGE, nr_pages);
864         }
865
866         /* pagein of a big page is an event. So, ignore page size */
867         if (nr_pages > 0)
868                 __count_memcg_events(memcg, PGPGIN, 1);
869         else {
870                 __count_memcg_events(memcg, PGPGOUT, 1);
871                 nr_pages = -nr_pages; /* for event */
872         }
873
874         __this_cpu_add(memcg->vmstats_percpu->nr_page_events, nr_pages);
875 }
876
877 static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
878                                        enum mem_cgroup_events_target target)
879 {
880         unsigned long val, next;
881
882         val = __this_cpu_read(memcg->vmstats_percpu->nr_page_events);
883         next = __this_cpu_read(memcg->vmstats_percpu->targets[target]);
884         /* from time_after() in jiffies.h */
885         if ((long)(next - val) < 0) {
886                 switch (target) {
887                 case MEM_CGROUP_TARGET_THRESH:
888                         next = val + THRESHOLDS_EVENTS_TARGET;
889                         break;
890                 case MEM_CGROUP_TARGET_SOFTLIMIT:
891                         next = val + SOFTLIMIT_EVENTS_TARGET;
892                         break;
893                 case MEM_CGROUP_TARGET_NUMAINFO:
894                         next = val + NUMAINFO_EVENTS_TARGET;
895                         break;
896                 default:
897                         break;
898                 }
899                 __this_cpu_write(memcg->vmstats_percpu->targets[target], next);
900                 return true;
901         }
902         return false;
903 }
904
905 /*
906  * Check events in order.
907  *
908  */
909 static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
910 {
911         /* threshold event is triggered in finer grain than soft limit */
912         if (unlikely(mem_cgroup_event_ratelimit(memcg,
913                                                 MEM_CGROUP_TARGET_THRESH))) {
914                 bool do_softlimit;
915                 bool do_numainfo __maybe_unused;
916
917                 do_softlimit = mem_cgroup_event_ratelimit(memcg,
918                                                 MEM_CGROUP_TARGET_SOFTLIMIT);
919 #if MAX_NUMNODES > 1
920                 do_numainfo = mem_cgroup_event_ratelimit(memcg,
921                                                 MEM_CGROUP_TARGET_NUMAINFO);
922 #endif
923                 mem_cgroup_threshold(memcg);
924                 if (unlikely(do_softlimit))
925                         mem_cgroup_update_tree(memcg, page);
926 #if MAX_NUMNODES > 1
927                 if (unlikely(do_numainfo))
928                         atomic_inc(&memcg->numainfo_events);
929 #endif
930         }
931 }
932
933 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
934 {
935         /*
936          * mm_update_next_owner() may clear mm->owner to NULL
937          * if it races with swapoff, page migration, etc.
938          * So this can be called with p == NULL.
939          */
940         if (unlikely(!p))
941                 return NULL;
942
943         return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
944 }
945 EXPORT_SYMBOL(mem_cgroup_from_task);
946
947 /**
948  * get_mem_cgroup_from_mm: Obtain a reference on given mm_struct's memcg.
949  * @mm: mm from which memcg should be extracted. It can be NULL.
950  *
951  * Obtain a reference on mm->memcg and returns it if successful. Otherwise
952  * root_mem_cgroup is returned. However if mem_cgroup is disabled, NULL is
953  * returned.
954  */
955 struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
956 {
957         struct mem_cgroup *memcg;
958
959         if (mem_cgroup_disabled())
960                 return NULL;
961
962         rcu_read_lock();
963         do {
964                 /*
965                  * Page cache insertions can happen withou an
966                  * actual mm context, e.g. during disk probing
967                  * on boot, loopback IO, acct() writes etc.
968                  */
969                 if (unlikely(!mm))
970                         memcg = root_mem_cgroup;
971                 else {
972                         memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
973                         if (unlikely(!memcg))
974                                 memcg = root_mem_cgroup;
975                 }
976         } while (!css_tryget(&memcg->css));
977         rcu_read_unlock();
978         return memcg;
979 }
980 EXPORT_SYMBOL(get_mem_cgroup_from_mm);
981
982 /**
983  * get_mem_cgroup_from_page: Obtain a reference on given page's memcg.
984  * @page: page from which memcg should be extracted.
985  *
986  * Obtain a reference on page->memcg and returns it if successful. Otherwise
987  * root_mem_cgroup is returned.
988  */
989 struct mem_cgroup *get_mem_cgroup_from_page(struct page *page)
990 {
991         struct mem_cgroup *memcg = page->mem_cgroup;
992
993         if (mem_cgroup_disabled())
994                 return NULL;
995
996         rcu_read_lock();
997         if (!memcg || !css_tryget_online(&memcg->css))
998                 memcg = root_mem_cgroup;
999         rcu_read_unlock();
1000         return memcg;
1001 }
1002 EXPORT_SYMBOL(get_mem_cgroup_from_page);
1003
1004 /**
1005  * If current->active_memcg is non-NULL, do not fallback to current->mm->memcg.
1006  */
1007 static __always_inline struct mem_cgroup *get_mem_cgroup_from_current(void)
1008 {
1009         if (unlikely(current->active_memcg)) {
1010                 struct mem_cgroup *memcg = root_mem_cgroup;
1011
1012                 rcu_read_lock();
1013                 if (css_tryget_online(&current->active_memcg->css))
1014                         memcg = current->active_memcg;
1015                 rcu_read_unlock();
1016                 return memcg;
1017         }
1018         return get_mem_cgroup_from_mm(current->mm);
1019 }
1020
1021 /**
1022  * mem_cgroup_iter - iterate over memory cgroup hierarchy
1023  * @root: hierarchy root
1024  * @prev: previously returned memcg, NULL on first invocation
1025  * @reclaim: cookie for shared reclaim walks, NULL for full walks
1026  *
1027  * Returns references to children of the hierarchy below @root, or
1028  * @root itself, or %NULL after a full round-trip.
1029  *
1030  * Caller must pass the return value in @prev on subsequent
1031  * invocations for reference counting, or use mem_cgroup_iter_break()
1032  * to cancel a hierarchy walk before the round-trip is complete.
1033  *
1034  * Reclaimers can specify a node and a priority level in @reclaim to
1035  * divide up the memcgs in the hierarchy among all concurrent
1036  * reclaimers operating on the same node and priority.
1037  */
1038 struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
1039                                    struct mem_cgroup *prev,
1040                                    struct mem_cgroup_reclaim_cookie *reclaim)
1041 {
1042         struct mem_cgroup_reclaim_iter *uninitialized_var(iter);
1043         struct cgroup_subsys_state *css = NULL;
1044         struct mem_cgroup *memcg = NULL;
1045         struct mem_cgroup *pos = NULL;
1046
1047         if (mem_cgroup_disabled())
1048                 return NULL;
1049
1050         if (!root)
1051                 root = root_mem_cgroup;
1052
1053         if (prev && !reclaim)
1054                 pos = prev;
1055
1056         if (!root->use_hierarchy && root != root_mem_cgroup) {
1057                 if (prev)
1058                         goto out;
1059                 return root;
1060         }
1061
1062         rcu_read_lock();
1063
1064         if (reclaim) {
1065                 struct mem_cgroup_per_node *mz;
1066
1067                 mz = mem_cgroup_nodeinfo(root, reclaim->pgdat->node_id);
1068                 iter = &mz->iter[reclaim->priority];
1069
1070                 if (prev && reclaim->generation != iter->generation)
1071                         goto out_unlock;
1072
1073                 while (1) {
1074                         pos = READ_ONCE(iter->position);
1075                         if (!pos || css_tryget(&pos->css))
1076                                 break;
1077                         /*
1078                          * css reference reached zero, so iter->position will
1079                          * be cleared by ->css_released. However, we should not
1080                          * rely on this happening soon, because ->css_released
1081                          * is called from a work queue, and by busy-waiting we
1082                          * might block it. So we clear iter->position right
1083                          * away.
1084                          */
1085                         (void)cmpxchg(&iter->position, pos, NULL);
1086                 }
1087         }
1088
1089         if (pos)
1090                 css = &pos->css;
1091
1092         for (;;) {
1093                 css = css_next_descendant_pre(css, &root->css);
1094                 if (!css) {
1095                         /*
1096                          * Reclaimers share the hierarchy walk, and a
1097                          * new one might jump in right at the end of
1098                          * the hierarchy - make sure they see at least
1099                          * one group and restart from the beginning.
1100                          */
1101                         if (!prev)
1102                                 continue;
1103                         break;
1104                 }
1105
1106                 /*
1107                  * Verify the css and acquire a reference.  The root
1108                  * is provided by the caller, so we know it's alive
1109                  * and kicking, and don't take an extra reference.
1110                  */
1111                 memcg = mem_cgroup_from_css(css);
1112
1113                 if (css == &root->css)
1114                         break;
1115
1116                 if (css_tryget(css))
1117                         break;
1118
1119                 memcg = NULL;
1120         }
1121
1122         if (reclaim) {
1123                 /*
1124                  * The position could have already been updated by a competing
1125                  * thread, so check that the value hasn't changed since we read
1126                  * it to avoid reclaiming from the same cgroup twice.
1127                  */
1128                 (void)cmpxchg(&iter->position, pos, memcg);
1129
1130                 if (pos)
1131                         css_put(&pos->css);
1132
1133                 if (!memcg)
1134                         iter->generation++;
1135                 else if (!prev)
1136                         reclaim->generation = iter->generation;
1137         }
1138
1139 out_unlock:
1140         rcu_read_unlock();
1141 out:
1142         if (prev && prev != root)
1143                 css_put(&prev->css);
1144
1145         return memcg;
1146 }
1147
1148 /**
1149  * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1150  * @root: hierarchy root
1151  * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1152  */
1153 void mem_cgroup_iter_break(struct mem_cgroup *root,
1154                            struct mem_cgroup *prev)
1155 {
1156         if (!root)
1157                 root = root_mem_cgroup;
1158         if (prev && prev != root)
1159                 css_put(&prev->css);
1160 }
1161
1162 static void __invalidate_reclaim_iterators(struct mem_cgroup *from,
1163                                         struct mem_cgroup *dead_memcg)
1164 {
1165         struct mem_cgroup_reclaim_iter *iter;
1166         struct mem_cgroup_per_node *mz;
1167         int nid;
1168         int i;
1169
1170         for_each_node(nid) {
1171                 mz = mem_cgroup_nodeinfo(from, nid);
1172                 for (i = 0; i <= DEF_PRIORITY; i++) {
1173                         iter = &mz->iter[i];
1174                         cmpxchg(&iter->position,
1175                                 dead_memcg, NULL);
1176                 }
1177         }
1178 }
1179
1180 static void invalidate_reclaim_iterators(struct mem_cgroup *dead_memcg)
1181 {
1182         struct mem_cgroup *memcg = dead_memcg;
1183         struct mem_cgroup *last;
1184
1185         do {
1186                 __invalidate_reclaim_iterators(memcg, dead_memcg);
1187                 last = memcg;
1188         } while ((memcg = parent_mem_cgroup(memcg)));
1189
1190         /*
1191          * When cgruop1 non-hierarchy mode is used,
1192          * parent_mem_cgroup() does not walk all the way up to the
1193          * cgroup root (root_mem_cgroup). So we have to handle
1194          * dead_memcg from cgroup root separately.
1195          */
1196         if (last != root_mem_cgroup)
1197                 __invalidate_reclaim_iterators(root_mem_cgroup,
1198                                                 dead_memcg);
1199 }
1200
1201 /**
1202  * mem_cgroup_scan_tasks - iterate over tasks of a memory cgroup hierarchy
1203  * @memcg: hierarchy root
1204  * @fn: function to call for each task
1205  * @arg: argument passed to @fn
1206  *
1207  * This function iterates over tasks attached to @memcg or to any of its
1208  * descendants and calls @fn for each task. If @fn returns a non-zero
1209  * value, the function breaks the iteration loop and returns the value.
1210  * Otherwise, it will iterate over all tasks and return 0.
1211  *
1212  * This function must not be called for the root memory cgroup.
1213  */
1214 int mem_cgroup_scan_tasks(struct mem_cgroup *memcg,
1215                           int (*fn)(struct task_struct *, void *), void *arg)
1216 {
1217         struct mem_cgroup *iter;
1218         int ret = 0;
1219
1220         BUG_ON(memcg == root_mem_cgroup);
1221
1222         for_each_mem_cgroup_tree(iter, memcg) {
1223                 struct css_task_iter it;
1224                 struct task_struct *task;
1225
1226                 css_task_iter_start(&iter->css, CSS_TASK_ITER_PROCS, &it);
1227                 while (!ret && (task = css_task_iter_next(&it)))
1228                         ret = fn(task, arg);
1229                 css_task_iter_end(&it);
1230                 if (ret) {
1231                         mem_cgroup_iter_break(memcg, iter);
1232                         break;
1233                 }
1234         }
1235         return ret;
1236 }
1237
1238 /**
1239  * mem_cgroup_page_lruvec - return lruvec for isolating/putting an LRU page
1240  * @page: the page
1241  * @pgdat: pgdat of the page
1242  *
1243  * This function is only safe when following the LRU page isolation
1244  * and putback protocol: the LRU lock must be held, and the page must
1245  * either be PageLRU() or the caller must have isolated/allocated it.
1246  */
1247 struct lruvec *mem_cgroup_page_lruvec(struct page *page, struct pglist_data *pgdat)
1248 {
1249         struct mem_cgroup_per_node *mz;
1250         struct mem_cgroup *memcg;
1251         struct lruvec *lruvec;
1252
1253         if (mem_cgroup_disabled()) {
1254                 lruvec = &pgdat->__lruvec;
1255                 goto out;
1256         }
1257
1258         memcg = page->mem_cgroup;
1259         VM_WARN_ON_ONCE_PAGE(!memcg, page);
1260         if (!memcg)
1261                 memcg = root_mem_cgroup;
1262
1263         mz = mem_cgroup_page_nodeinfo(memcg, page);
1264         lruvec = &mz->lruvec;
1265 out:
1266         /*
1267          * Since a node can be onlined after the mem_cgroup was created,
1268          * we have to be prepared to initialize lruvec->zone here;
1269          * and if offlined then reonlined, we need to reinitialize it.
1270          */
1271         if (unlikely(lruvec->pgdat != pgdat))
1272                 lruvec->pgdat = pgdat;
1273         return lruvec;
1274 }
1275
1276 /**
1277  * mem_cgroup_update_lru_size - account for adding or removing an lru page
1278  * @lruvec: mem_cgroup per zone lru vector
1279  * @lru: index of lru list the page is sitting on
1280  * @zid: zone id of the accounted pages
1281  * @nr_pages: positive when adding or negative when removing
1282  *
1283  * This function must be called under lru_lock, just before a page is added
1284  * to or just after a page is removed from an lru list (that ordering being
1285  * so as to allow it to check that lru_size 0 is consistent with list_empty).
1286  */
1287 void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
1288                                 int zid, int nr_pages)
1289 {
1290         struct mem_cgroup_per_node *mz;
1291         unsigned long *lru_size;
1292         long size;
1293
1294         if (mem_cgroup_disabled())
1295                 return;
1296
1297         mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
1298         lru_size = &mz->lru_zone_size[zid][lru];
1299
1300         if (nr_pages < 0)
1301                 *lru_size += nr_pages;
1302
1303         size = *lru_size;
1304         if (WARN_ONCE(size < 0,
1305                 "%s(%p, %d, %d): lru_size %ld\n",
1306                 __func__, lruvec, lru, nr_pages, size)) {
1307                 VM_BUG_ON(1);
1308                 *lru_size = 0;
1309         }
1310
1311         if (nr_pages > 0)
1312                 *lru_size += nr_pages;
1313 }
1314
1315 /**
1316  * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1317  * @memcg: the memory cgroup
1318  *
1319  * Returns the maximum amount of memory @mem can be charged with, in
1320  * pages.
1321  */
1322 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1323 {
1324         unsigned long margin = 0;
1325         unsigned long count;
1326         unsigned long limit;
1327
1328         count = page_counter_read(&memcg->memory);
1329         limit = READ_ONCE(memcg->memory.max);
1330         if (count < limit)
1331                 margin = limit - count;
1332
1333         if (do_memsw_account()) {
1334                 count = page_counter_read(&memcg->memsw);
1335                 limit = READ_ONCE(memcg->memsw.max);
1336                 if (count <= limit)
1337                         margin = min(margin, limit - count);
1338                 else
1339                         margin = 0;
1340         }
1341
1342         return margin;
1343 }
1344
1345 /*
1346  * A routine for checking "mem" is under move_account() or not.
1347  *
1348  * Checking a cgroup is mc.from or mc.to or under hierarchy of
1349  * moving cgroups. This is for waiting at high-memory pressure
1350  * caused by "move".
1351  */
1352 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1353 {
1354         struct mem_cgroup *from;
1355         struct mem_cgroup *to;
1356         bool ret = false;
1357         /*
1358          * Unlike task_move routines, we access mc.to, mc.from not under
1359          * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1360          */
1361         spin_lock(&mc.lock);
1362         from = mc.from;
1363         to = mc.to;
1364         if (!from)
1365                 goto unlock;
1366
1367         ret = mem_cgroup_is_descendant(from, memcg) ||
1368                 mem_cgroup_is_descendant(to, memcg);
1369 unlock:
1370         spin_unlock(&mc.lock);
1371         return ret;
1372 }
1373
1374 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1375 {
1376         if (mc.moving_task && current != mc.moving_task) {
1377                 if (mem_cgroup_under_move(memcg)) {
1378                         DEFINE_WAIT(wait);
1379                         prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1380                         /* moving charge context might have finished. */
1381                         if (mc.moving_task)
1382                                 schedule();
1383                         finish_wait(&mc.waitq, &wait);
1384                         return true;
1385                 }
1386         }
1387         return false;
1388 }
1389
1390 static char *memory_stat_format(struct mem_cgroup *memcg)
1391 {
1392         struct seq_buf s;
1393         int i;
1394
1395         seq_buf_init(&s, kmalloc(PAGE_SIZE, GFP_KERNEL), PAGE_SIZE);
1396         if (!s.buffer)
1397                 return NULL;
1398
1399         /*
1400          * Provide statistics on the state of the memory subsystem as
1401          * well as cumulative event counters that show past behavior.
1402          *
1403          * This list is ordered following a combination of these gradients:
1404          * 1) generic big picture -> specifics and details
1405          * 2) reflecting userspace activity -> reflecting kernel heuristics
1406          *
1407          * Current memory state:
1408          */
1409
1410         seq_buf_printf(&s, "anon %llu\n",
1411                        (u64)memcg_page_state(memcg, MEMCG_RSS) *
1412                        PAGE_SIZE);
1413         seq_buf_printf(&s, "file %llu\n",
1414                        (u64)memcg_page_state(memcg, MEMCG_CACHE) *
1415                        PAGE_SIZE);
1416         seq_buf_printf(&s, "kernel_stack %llu\n",
1417                        (u64)memcg_page_state(memcg, MEMCG_KERNEL_STACK_KB) *
1418                        1024);
1419         seq_buf_printf(&s, "slab %llu\n",
1420                        (u64)(memcg_page_state(memcg, NR_SLAB_RECLAIMABLE) +
1421                              memcg_page_state(memcg, NR_SLAB_UNRECLAIMABLE)) *
1422                        PAGE_SIZE);
1423         seq_buf_printf(&s, "sock %llu\n",
1424                        (u64)memcg_page_state(memcg, MEMCG_SOCK) *
1425                        PAGE_SIZE);
1426
1427         seq_buf_printf(&s, "shmem %llu\n",
1428                        (u64)memcg_page_state(memcg, NR_SHMEM) *
1429                        PAGE_SIZE);
1430         seq_buf_printf(&s, "file_mapped %llu\n",
1431                        (u64)memcg_page_state(memcg, NR_FILE_MAPPED) *
1432                        PAGE_SIZE);
1433         seq_buf_printf(&s, "file_dirty %llu\n",
1434                        (u64)memcg_page_state(memcg, NR_FILE_DIRTY) *
1435                        PAGE_SIZE);
1436         seq_buf_printf(&s, "file_writeback %llu\n",
1437                        (u64)memcg_page_state(memcg, NR_WRITEBACK) *
1438                        PAGE_SIZE);
1439
1440         /*
1441          * TODO: We should eventually replace our own MEMCG_RSS_HUGE counter
1442          * with the NR_ANON_THP vm counter, but right now it's a pain in the
1443          * arse because it requires migrating the work out of rmap to a place
1444          * where the page->mem_cgroup is set up and stable.
1445          */
1446         seq_buf_printf(&s, "anon_thp %llu\n",
1447                        (u64)memcg_page_state(memcg, MEMCG_RSS_HUGE) *
1448                        PAGE_SIZE);
1449
1450         for (i = 0; i < NR_LRU_LISTS; i++)
1451                 seq_buf_printf(&s, "%s %llu\n", mem_cgroup_lru_names[i],
1452                                (u64)memcg_page_state(memcg, NR_LRU_BASE + i) *
1453                                PAGE_SIZE);
1454
1455         seq_buf_printf(&s, "slab_reclaimable %llu\n",
1456                        (u64)memcg_page_state(memcg, NR_SLAB_RECLAIMABLE) *
1457                        PAGE_SIZE);
1458         seq_buf_printf(&s, "slab_unreclaimable %llu\n",
1459                        (u64)memcg_page_state(memcg, NR_SLAB_UNRECLAIMABLE) *
1460                        PAGE_SIZE);
1461
1462         /* Accumulated memory events */
1463
1464         seq_buf_printf(&s, "pgfault %lu\n", memcg_events(memcg, PGFAULT));
1465         seq_buf_printf(&s, "pgmajfault %lu\n", memcg_events(memcg, PGMAJFAULT));
1466
1467         seq_buf_printf(&s, "workingset_refault %lu\n",
1468                        memcg_page_state(memcg, WORKINGSET_REFAULT));
1469         seq_buf_printf(&s, "workingset_activate %lu\n",
1470                        memcg_page_state(memcg, WORKINGSET_ACTIVATE));
1471         seq_buf_printf(&s, "workingset_nodereclaim %lu\n",
1472                        memcg_page_state(memcg, WORKINGSET_NODERECLAIM));
1473
1474         seq_buf_printf(&s, "pgrefill %lu\n", memcg_events(memcg, PGREFILL));
1475         seq_buf_printf(&s, "pgscan %lu\n",
1476                        memcg_events(memcg, PGSCAN_KSWAPD) +
1477                        memcg_events(memcg, PGSCAN_DIRECT));
1478         seq_buf_printf(&s, "pgsteal %lu\n",
1479                        memcg_events(memcg, PGSTEAL_KSWAPD) +
1480                        memcg_events(memcg, PGSTEAL_DIRECT));
1481         seq_buf_printf(&s, "pgactivate %lu\n", memcg_events(memcg, PGACTIVATE));
1482         seq_buf_printf(&s, "pgdeactivate %lu\n", memcg_events(memcg, PGDEACTIVATE));
1483         seq_buf_printf(&s, "pglazyfree %lu\n", memcg_events(memcg, PGLAZYFREE));
1484         seq_buf_printf(&s, "pglazyfreed %lu\n", memcg_events(memcg, PGLAZYFREED));
1485
1486 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1487         seq_buf_printf(&s, "thp_fault_alloc %lu\n",
1488                        memcg_events(memcg, THP_FAULT_ALLOC));
1489         seq_buf_printf(&s, "thp_collapse_alloc %lu\n",
1490                        memcg_events(memcg, THP_COLLAPSE_ALLOC));
1491 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
1492
1493         /* The above should easily fit into one page */
1494         WARN_ON_ONCE(seq_buf_has_overflowed(&s));
1495
1496         return s.buffer;
1497 }
1498
1499 #define K(x) ((x) << (PAGE_SHIFT-10))
1500 /**
1501  * mem_cgroup_print_oom_context: Print OOM information relevant to
1502  * memory controller.
1503  * @memcg: The memory cgroup that went over limit
1504  * @p: Task that is going to be killed
1505  *
1506  * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1507  * enabled
1508  */
1509 void mem_cgroup_print_oom_context(struct mem_cgroup *memcg, struct task_struct *p)
1510 {
1511         rcu_read_lock();
1512
1513         if (memcg) {
1514                 pr_cont(",oom_memcg=");
1515                 pr_cont_cgroup_path(memcg->css.cgroup);
1516         } else
1517                 pr_cont(",global_oom");
1518         if (p) {
1519                 pr_cont(",task_memcg=");
1520                 pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
1521         }
1522         rcu_read_unlock();
1523 }
1524
1525 /**
1526  * mem_cgroup_print_oom_meminfo: Print OOM memory information relevant to
1527  * memory controller.
1528  * @memcg: The memory cgroup that went over limit
1529  */
1530 void mem_cgroup_print_oom_meminfo(struct mem_cgroup *memcg)
1531 {
1532         char *buf;
1533
1534         pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
1535                 K((u64)page_counter_read(&memcg->memory)),
1536                 K((u64)memcg->memory.max), memcg->memory.failcnt);
1537         if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1538                 pr_info("swap: usage %llukB, limit %llukB, failcnt %lu\n",
1539                         K((u64)page_counter_read(&memcg->swap)),
1540                         K((u64)memcg->swap.max), memcg->swap.failcnt);
1541         else {
1542                 pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
1543                         K((u64)page_counter_read(&memcg->memsw)),
1544                         K((u64)memcg->memsw.max), memcg->memsw.failcnt);
1545                 pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
1546                         K((u64)page_counter_read(&memcg->kmem)),
1547                         K((u64)memcg->kmem.max), memcg->kmem.failcnt);
1548         }
1549
1550         pr_info("Memory cgroup stats for ");
1551         pr_cont_cgroup_path(memcg->css.cgroup);
1552         pr_cont(":");
1553         buf = memory_stat_format(memcg);
1554         if (!buf)
1555                 return;
1556         pr_info("%s", buf);
1557         kfree(buf);
1558 }
1559
1560 /*
1561  * Return the memory (and swap, if configured) limit for a memcg.
1562  */
1563 unsigned long mem_cgroup_get_max(struct mem_cgroup *memcg)
1564 {
1565         unsigned long max;
1566
1567         max = memcg->memory.max;
1568         if (mem_cgroup_swappiness(memcg)) {
1569                 unsigned long memsw_max;
1570                 unsigned long swap_max;
1571
1572                 memsw_max = memcg->memsw.max;
1573                 swap_max = memcg->swap.max;
1574                 swap_max = min(swap_max, (unsigned long)total_swap_pages);
1575                 max = min(max + swap_max, memsw_max);
1576         }
1577         return max;
1578 }
1579
1580 unsigned long mem_cgroup_size(struct mem_cgroup *memcg)
1581 {
1582         return page_counter_read(&memcg->memory);
1583 }
1584
1585 static bool mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
1586                                      int order)
1587 {
1588         struct oom_control oc = {
1589                 .zonelist = NULL,
1590                 .nodemask = NULL,
1591                 .memcg = memcg,
1592                 .gfp_mask = gfp_mask,
1593                 .order = order,
1594         };
1595         bool ret;
1596
1597         if (mutex_lock_killable(&oom_lock))
1598                 return true;
1599         /*
1600          * A few threads which were not waiting at mutex_lock_killable() can
1601          * fail to bail out. Therefore, check again after holding oom_lock.
1602          */
1603         ret = should_force_charge() || out_of_memory(&oc);
1604         mutex_unlock(&oom_lock);
1605         return ret;
1606 }
1607
1608 #if MAX_NUMNODES > 1
1609
1610 /**
1611  * test_mem_cgroup_node_reclaimable
1612  * @memcg: the target memcg
1613  * @nid: the node ID to be checked.
1614  * @noswap : specify true here if the user wants flle only information.
1615  *
1616  * This function returns whether the specified memcg contains any
1617  * reclaimable pages on a node. Returns true if there are any reclaimable
1618  * pages in the node.
1619  */
1620 static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *memcg,
1621                 int nid, bool noswap)
1622 {
1623         struct lruvec *lruvec = mem_cgroup_lruvec(NODE_DATA(nid), memcg);
1624
1625         if (lruvec_page_state(lruvec, NR_INACTIVE_FILE) ||
1626             lruvec_page_state(lruvec, NR_ACTIVE_FILE))
1627                 return true;
1628         if (noswap || !total_swap_pages)
1629                 return false;
1630         if (lruvec_page_state(lruvec, NR_INACTIVE_ANON) ||
1631             lruvec_page_state(lruvec, NR_ACTIVE_ANON))
1632                 return true;
1633         return false;
1634
1635 }
1636
1637 /*
1638  * Always updating the nodemask is not very good - even if we have an empty
1639  * list or the wrong list here, we can start from some node and traverse all
1640  * nodes based on the zonelist. So update the list loosely once per 10 secs.
1641  *
1642  */
1643 static void mem_cgroup_may_update_nodemask(struct mem_cgroup *memcg)
1644 {
1645         int nid;
1646         /*
1647          * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
1648          * pagein/pageout changes since the last update.
1649          */
1650         if (!atomic_read(&memcg->numainfo_events))
1651                 return;
1652         if (atomic_inc_return(&memcg->numainfo_updating) > 1)
1653                 return;
1654
1655         /* make a nodemask where this memcg uses memory from */
1656         memcg->scan_nodes = node_states[N_MEMORY];
1657
1658         for_each_node_mask(nid, node_states[N_MEMORY]) {
1659
1660                 if (!test_mem_cgroup_node_reclaimable(memcg, nid, false))
1661                         node_clear(nid, memcg->scan_nodes);
1662         }
1663
1664         atomic_set(&memcg->numainfo_events, 0);
1665         atomic_set(&memcg->numainfo_updating, 0);
1666 }
1667
1668 /*
1669  * Selecting a node where we start reclaim from. Because what we need is just
1670  * reducing usage counter, start from anywhere is O,K. Considering
1671  * memory reclaim from current node, there are pros. and cons.
1672  *
1673  * Freeing memory from current node means freeing memory from a node which
1674  * we'll use or we've used. So, it may make LRU bad. And if several threads
1675  * hit limits, it will see a contention on a node. But freeing from remote
1676  * node means more costs for memory reclaim because of memory latency.
1677  *
1678  * Now, we use round-robin. Better algorithm is welcomed.
1679  */
1680 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1681 {
1682         int node;
1683
1684         mem_cgroup_may_update_nodemask(memcg);
1685         node = memcg->last_scanned_node;
1686
1687         node = next_node_in(node, memcg->scan_nodes);
1688         /*
1689          * mem_cgroup_may_update_nodemask might have seen no reclaimmable pages
1690          * last time it really checked all the LRUs due to rate limiting.
1691          * Fallback to the current node in that case for simplicity.
1692          */
1693         if (unlikely(node == MAX_NUMNODES))
1694                 node = numa_node_id();
1695
1696         memcg->last_scanned_node = node;
1697         return node;
1698 }
1699 #else
1700 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1701 {
1702         return 0;
1703 }
1704 #endif
1705
1706 static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
1707                                    pg_data_t *pgdat,
1708                                    gfp_t gfp_mask,
1709                                    unsigned long *total_scanned)
1710 {
1711         struct mem_cgroup *victim = NULL;
1712         int total = 0;
1713         int loop = 0;
1714         unsigned long excess;
1715         unsigned long nr_scanned;
1716         struct mem_cgroup_reclaim_cookie reclaim = {
1717                 .pgdat = pgdat,
1718                 .priority = 0,
1719         };
1720
1721         excess = soft_limit_excess(root_memcg);
1722
1723         while (1) {
1724                 victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
1725                 if (!victim) {
1726                         loop++;
1727                         if (loop >= 2) {
1728                                 /*
1729                                  * If we have not been able to reclaim
1730                                  * anything, it might because there are
1731                                  * no reclaimable pages under this hierarchy
1732                                  */
1733                                 if (!total)
1734                                         break;
1735                                 /*
1736                                  * We want to do more targeted reclaim.
1737                                  * excess >> 2 is not to excessive so as to
1738                                  * reclaim too much, nor too less that we keep
1739                                  * coming back to reclaim from this cgroup
1740                                  */
1741                                 if (total >= (excess >> 2) ||
1742                                         (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
1743                                         break;
1744                         }
1745                         continue;
1746                 }
1747                 total += mem_cgroup_shrink_node(victim, gfp_mask, false,
1748                                         pgdat, &nr_scanned);
1749                 *total_scanned += nr_scanned;
1750                 if (!soft_limit_excess(root_memcg))
1751                         break;
1752         }
1753         mem_cgroup_iter_break(root_memcg, victim);
1754         return total;
1755 }
1756
1757 #ifdef CONFIG_LOCKDEP
1758 static struct lockdep_map memcg_oom_lock_dep_map = {
1759         .name = "memcg_oom_lock",
1760 };
1761 #endif
1762
1763 static DEFINE_SPINLOCK(memcg_oom_lock);
1764
1765 /*
1766  * Check OOM-Killer is already running under our hierarchy.
1767  * If someone is running, return false.
1768  */
1769 static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
1770 {
1771         struct mem_cgroup *iter, *failed = NULL;
1772
1773         spin_lock(&memcg_oom_lock);
1774
1775         for_each_mem_cgroup_tree(iter, memcg) {
1776                 if (iter->oom_lock) {
1777                         /*
1778                          * this subtree of our hierarchy is already locked
1779                          * so we cannot give a lock.
1780                          */
1781                         failed = iter;
1782                         mem_cgroup_iter_break(memcg, iter);
1783                         break;
1784                 } else
1785                         iter->oom_lock = true;
1786         }
1787
1788         if (failed) {
1789                 /*
1790                  * OK, we failed to lock the whole subtree so we have
1791                  * to clean up what we set up to the failing subtree
1792                  */
1793                 for_each_mem_cgroup_tree(iter, memcg) {
1794                         if (iter == failed) {
1795                                 mem_cgroup_iter_break(memcg, iter);
1796                                 break;
1797                         }
1798                         iter->oom_lock = false;
1799                 }
1800         } else
1801                 mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_);
1802
1803         spin_unlock(&memcg_oom_lock);
1804
1805         return !failed;
1806 }
1807
1808 static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
1809 {
1810         struct mem_cgroup *iter;
1811
1812         spin_lock(&memcg_oom_lock);
1813         mutex_release(&memcg_oom_lock_dep_map, 1, _RET_IP_);
1814         for_each_mem_cgroup_tree(iter, memcg)
1815                 iter->oom_lock = false;
1816         spin_unlock(&memcg_oom_lock);
1817 }
1818
1819 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
1820 {
1821         struct mem_cgroup *iter;
1822
1823         spin_lock(&memcg_oom_lock);
1824         for_each_mem_cgroup_tree(iter, memcg)
1825                 iter->under_oom++;
1826         spin_unlock(&memcg_oom_lock);
1827 }
1828
1829 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
1830 {
1831         struct mem_cgroup *iter;
1832
1833         /*
1834          * When a new child is created while the hierarchy is under oom,
1835          * mem_cgroup_oom_lock() may not be called. Watch for underflow.
1836          */
1837         spin_lock(&memcg_oom_lock);
1838         for_each_mem_cgroup_tree(iter, memcg)
1839                 if (iter->under_oom > 0)
1840                         iter->under_oom--;
1841         spin_unlock(&memcg_oom_lock);
1842 }
1843
1844 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1845
1846 struct oom_wait_info {
1847         struct mem_cgroup *memcg;
1848         wait_queue_entry_t      wait;
1849 };
1850
1851 static int memcg_oom_wake_function(wait_queue_entry_t *wait,
1852         unsigned mode, int sync, void *arg)
1853 {
1854         struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
1855         struct mem_cgroup *oom_wait_memcg;
1856         struct oom_wait_info *oom_wait_info;
1857
1858         oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1859         oom_wait_memcg = oom_wait_info->memcg;
1860
1861         if (!mem_cgroup_is_descendant(wake_memcg, oom_wait_memcg) &&
1862             !mem_cgroup_is_descendant(oom_wait_memcg, wake_memcg))
1863                 return 0;
1864         return autoremove_wake_function(wait, mode, sync, arg);
1865 }
1866
1867 static void memcg_oom_recover(struct mem_cgroup *memcg)
1868 {
1869         /*
1870          * For the following lockless ->under_oom test, the only required
1871          * guarantee is that it must see the state asserted by an OOM when
1872          * this function is called as a result of userland actions
1873          * triggered by the notification of the OOM.  This is trivially
1874          * achieved by invoking mem_cgroup_mark_under_oom() before
1875          * triggering notification.
1876          */
1877         if (memcg && memcg->under_oom)
1878                 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
1879 }
1880
1881 enum oom_status {
1882         OOM_SUCCESS,
1883         OOM_FAILED,
1884         OOM_ASYNC,
1885         OOM_SKIPPED
1886 };
1887
1888 static enum oom_status mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
1889 {
1890         enum oom_status ret;
1891         bool locked;
1892
1893         if (order > PAGE_ALLOC_COSTLY_ORDER)
1894                 return OOM_SKIPPED;
1895
1896         memcg_memory_event(memcg, MEMCG_OOM);
1897
1898         /*
1899          * We are in the middle of the charge context here, so we
1900          * don't want to block when potentially sitting on a callstack
1901          * that holds all kinds of filesystem and mm locks.
1902          *
1903          * cgroup1 allows disabling the OOM killer and waiting for outside
1904          * handling until the charge can succeed; remember the context and put
1905          * the task to sleep at the end of the page fault when all locks are
1906          * released.
1907          *
1908          * On the other hand, in-kernel OOM killer allows for an async victim
1909          * memory reclaim (oom_reaper) and that means that we are not solely
1910          * relying on the oom victim to make a forward progress and we can
1911          * invoke the oom killer here.
1912          *
1913          * Please note that mem_cgroup_out_of_memory might fail to find a
1914          * victim and then we have to bail out from the charge path.
1915          */
1916         if (memcg->oom_kill_disable) {
1917                 if (!current->in_user_fault)
1918                         return OOM_SKIPPED;
1919                 css_get(&memcg->css);
1920                 current->memcg_in_oom = memcg;
1921                 current->memcg_oom_gfp_mask = mask;
1922                 current->memcg_oom_order = order;
1923
1924                 return OOM_ASYNC;
1925         }
1926
1927         mem_cgroup_mark_under_oom(memcg);
1928
1929         locked = mem_cgroup_oom_trylock(memcg);
1930
1931         if (locked)
1932                 mem_cgroup_oom_notify(memcg);
1933
1934         mem_cgroup_unmark_under_oom(memcg);
1935         if (mem_cgroup_out_of_memory(memcg, mask, order))
1936                 ret = OOM_SUCCESS;
1937         else
1938                 ret = OOM_FAILED;
1939
1940         if (locked)
1941                 mem_cgroup_oom_unlock(memcg);
1942
1943         return ret;
1944 }
1945
1946 /**
1947  * mem_cgroup_oom_synchronize - complete memcg OOM handling
1948  * @handle: actually kill/wait or just clean up the OOM state
1949  *
1950  * This has to be called at the end of a page fault if the memcg OOM
1951  * handler was enabled.
1952  *
1953  * Memcg supports userspace OOM handling where failed allocations must
1954  * sleep on a waitqueue until the userspace task resolves the
1955  * situation.  Sleeping directly in the charge context with all kinds
1956  * of locks held is not a good idea, instead we remember an OOM state
1957  * in the task and mem_cgroup_oom_synchronize() has to be called at
1958  * the end of the page fault to complete the OOM handling.
1959  *
1960  * Returns %true if an ongoing memcg OOM situation was detected and
1961  * completed, %false otherwise.
1962  */
1963 bool mem_cgroup_oom_synchronize(bool handle)
1964 {
1965         struct mem_cgroup *memcg = current->memcg_in_oom;
1966         struct oom_wait_info owait;
1967         bool locked;
1968
1969         /* OOM is global, do not handle */
1970         if (!memcg)
1971                 return false;
1972
1973         if (!handle)
1974                 goto cleanup;
1975
1976         owait.memcg = memcg;
1977         owait.wait.flags = 0;
1978         owait.wait.func = memcg_oom_wake_function;
1979         owait.wait.private = current;
1980         INIT_LIST_HEAD(&owait.wait.entry);
1981
1982         prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
1983         mem_cgroup_mark_under_oom(memcg);
1984
1985         locked = mem_cgroup_oom_trylock(memcg);
1986
1987         if (locked)
1988                 mem_cgroup_oom_notify(memcg);
1989
1990         if (locked && !memcg->oom_kill_disable) {
1991                 mem_cgroup_unmark_under_oom(memcg);
1992                 finish_wait(&memcg_oom_waitq, &owait.wait);
1993                 mem_cgroup_out_of_memory(memcg, current->memcg_oom_gfp_mask,
1994                                          current->memcg_oom_order);
1995         } else {
1996                 schedule();
1997                 mem_cgroup_unmark_under_oom(memcg);
1998                 finish_wait(&memcg_oom_waitq, &owait.wait);
1999         }
2000
2001         if (locked) {
2002                 mem_cgroup_oom_unlock(memcg);
2003                 /*
2004                  * There is no guarantee that an OOM-lock contender
2005                  * sees the wakeups triggered by the OOM kill
2006                  * uncharges.  Wake any sleepers explicitely.
2007                  */
2008                 memcg_oom_recover(memcg);
2009         }
2010 cleanup:
2011         current->memcg_in_oom = NULL;
2012         css_put(&memcg->css);
2013         return true;
2014 }
2015
2016 /**
2017  * mem_cgroup_get_oom_group - get a memory cgroup to clean up after OOM
2018  * @victim: task to be killed by the OOM killer
2019  * @oom_domain: memcg in case of memcg OOM, NULL in case of system-wide OOM
2020  *
2021  * Returns a pointer to a memory cgroup, which has to be cleaned up
2022  * by killing all belonging OOM-killable tasks.
2023  *
2024  * Caller has to call mem_cgroup_put() on the returned non-NULL memcg.
2025  */
2026 struct mem_cgroup *mem_cgroup_get_oom_group(struct task_struct *victim,
2027                                             struct mem_cgroup *oom_domain)
2028 {
2029         struct mem_cgroup *oom_group = NULL;
2030         struct mem_cgroup *memcg;
2031
2032         if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
2033                 return NULL;
2034
2035         if (!oom_domain)
2036                 oom_domain = root_mem_cgroup;
2037
2038         rcu_read_lock();
2039
2040         memcg = mem_cgroup_from_task(victim);
2041         if (memcg == root_mem_cgroup)
2042                 goto out;
2043
2044         /*
2045          * Traverse the memory cgroup hierarchy from the victim task's
2046          * cgroup up to the OOMing cgroup (or root) to find the
2047          * highest-level memory cgroup with oom.group set.
2048          */
2049         for (; memcg; memcg = parent_mem_cgroup(memcg)) {
2050                 if (memcg->oom_group)
2051                         oom_group = memcg;
2052
2053                 if (memcg == oom_domain)
2054                         break;
2055         }
2056
2057         if (oom_group)
2058                 css_get(&oom_group->css);
2059 out:
2060         rcu_read_unlock();
2061
2062         return oom_group;
2063 }
2064
2065 void mem_cgroup_print_oom_group(struct mem_cgroup *memcg)
2066 {
2067         pr_info("Tasks in ");
2068         pr_cont_cgroup_path(memcg->css.cgroup);
2069         pr_cont(" are going to be killed due to memory.oom.group set\n");
2070 }
2071
2072 /**
2073  * lock_page_memcg - lock a page->mem_cgroup binding
2074  * @page: the page
2075  *
2076  * This function protects unlocked LRU pages from being moved to
2077  * another cgroup.
2078  *
2079  * It ensures lifetime of the returned memcg. Caller is responsible
2080  * for the lifetime of the page; __unlock_page_memcg() is available
2081  * when @page might get freed inside the locked section.
2082  */
2083 struct mem_cgroup *lock_page_memcg(struct page *page)
2084 {
2085         struct mem_cgroup *memcg;
2086         unsigned long flags;
2087
2088         /*
2089          * The RCU lock is held throughout the transaction.  The fast
2090          * path can get away without acquiring the memcg->move_lock
2091          * because page moving starts with an RCU grace period.
2092          *
2093          * The RCU lock also protects the memcg from being freed when
2094          * the page state that is going to change is the only thing
2095          * preventing the page itself from being freed. E.g. writeback
2096          * doesn't hold a page reference and relies on PG_writeback to
2097          * keep off truncation, migration and so forth.
2098          */
2099         rcu_read_lock();
2100
2101         if (mem_cgroup_disabled())
2102                 return NULL;
2103 again:
2104         memcg = page->mem_cgroup;
2105         if (unlikely(!memcg))
2106                 return NULL;
2107
2108         if (atomic_read(&memcg->moving_account) <= 0)
2109                 return memcg;
2110
2111         spin_lock_irqsave(&memcg->move_lock, flags);
2112         if (memcg != page->mem_cgroup) {
2113                 spin_unlock_irqrestore(&memcg->move_lock, flags);
2114                 goto again;
2115         }
2116
2117         /*
2118          * When charge migration first begins, we can have locked and
2119          * unlocked page stat updates happening concurrently.  Track
2120          * the task who has the lock for unlock_page_memcg().
2121          */
2122         memcg->move_lock_task = current;
2123         memcg->move_lock_flags = flags;
2124
2125         return memcg;
2126 }
2127 EXPORT_SYMBOL(lock_page_memcg);
2128
2129 /**
2130  * __unlock_page_memcg - unlock and unpin a memcg
2131  * @memcg: the memcg
2132  *
2133  * Unlock and unpin a memcg returned by lock_page_memcg().
2134  */
2135 void __unlock_page_memcg(struct mem_cgroup *memcg)
2136 {
2137         if (memcg && memcg->move_lock_task == current) {
2138                 unsigned long flags = memcg->move_lock_flags;
2139
2140                 memcg->move_lock_task = NULL;
2141                 memcg->move_lock_flags = 0;
2142
2143                 spin_unlock_irqrestore(&memcg->move_lock, flags);
2144         }
2145
2146         rcu_read_unlock();
2147 }
2148
2149 /**
2150  * unlock_page_memcg - unlock a page->mem_cgroup binding
2151  * @page: the page
2152  */
2153 void unlock_page_memcg(struct page *page)
2154 {
2155         __unlock_page_memcg(page->mem_cgroup);
2156 }
2157 EXPORT_SYMBOL(unlock_page_memcg);
2158
2159 struct memcg_stock_pcp {
2160         struct mem_cgroup *cached; /* this never be root cgroup */
2161         unsigned int nr_pages;
2162         struct work_struct work;
2163         unsigned long flags;
2164 #define FLUSHING_CACHED_CHARGE  0
2165 };
2166 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
2167 static DEFINE_MUTEX(percpu_charge_mutex);
2168
2169 /**
2170  * consume_stock: Try to consume stocked charge on this cpu.
2171  * @memcg: memcg to consume from.
2172  * @nr_pages: how many pages to charge.
2173  *
2174  * The charges will only happen if @memcg matches the current cpu's memcg
2175  * stock, and at least @nr_pages are available in that stock.  Failure to
2176  * service an allocation will refill the stock.
2177  *
2178  * returns true if successful, false otherwise.
2179  */
2180 static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2181 {
2182         struct memcg_stock_pcp *stock;
2183         unsigned long flags;
2184         bool ret = false;
2185
2186         if (nr_pages > MEMCG_CHARGE_BATCH)
2187                 return ret;
2188
2189         local_irq_save(flags);
2190
2191         stock = this_cpu_ptr(&memcg_stock);
2192         if (memcg == stock->cached && stock->nr_pages >= nr_pages) {
2193                 stock->nr_pages -= nr_pages;
2194                 ret = true;
2195         }
2196
2197         local_irq_restore(flags);
2198
2199         return ret;
2200 }
2201
2202 /*
2203  * Returns stocks cached in percpu and reset cached information.
2204  */
2205 static void drain_stock(struct memcg_stock_pcp *stock)
2206 {
2207         struct mem_cgroup *old = stock->cached;
2208
2209         if (stock->nr_pages) {
2210                 page_counter_uncharge(&old->memory, stock->nr_pages);
2211                 if (do_memsw_account())
2212                         page_counter_uncharge(&old->memsw, stock->nr_pages);
2213                 css_put_many(&old->css, stock->nr_pages);
2214                 stock->nr_pages = 0;
2215         }
2216         stock->cached = NULL;
2217 }
2218
2219 static void drain_local_stock(struct work_struct *dummy)
2220 {
2221         struct memcg_stock_pcp *stock;
2222         unsigned long flags;
2223
2224         /*
2225          * The only protection from memory hotplug vs. drain_stock races is
2226          * that we always operate on local CPU stock here with IRQ disabled
2227          */
2228         local_irq_save(flags);
2229
2230         stock = this_cpu_ptr(&memcg_stock);
2231         drain_stock(stock);
2232         clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2233
2234         local_irq_restore(flags);
2235 }
2236
2237 /*
2238  * Cache charges(val) to local per_cpu area.
2239  * This will be consumed by consume_stock() function, later.
2240  */
2241 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2242 {
2243         struct memcg_stock_pcp *stock;
2244         unsigned long flags;
2245
2246         local_irq_save(flags);
2247
2248         stock = this_cpu_ptr(&memcg_stock);
2249         if (stock->cached != memcg) { /* reset if necessary */
2250                 drain_stock(stock);
2251                 stock->cached = memcg;
2252         }
2253         stock->nr_pages += nr_pages;
2254
2255         if (stock->nr_pages > MEMCG_CHARGE_BATCH)
2256                 drain_stock(stock);
2257
2258         local_irq_restore(flags);
2259 }
2260
2261 /*
2262  * Drains all per-CPU charge caches for given root_memcg resp. subtree
2263  * of the hierarchy under it.
2264  */
2265 static void drain_all_stock(struct mem_cgroup *root_memcg)
2266 {
2267         int cpu, curcpu;
2268
2269         /* If someone's already draining, avoid adding running more workers. */
2270         if (!mutex_trylock(&percpu_charge_mutex))
2271                 return;
2272         /*
2273          * Notify other cpus that system-wide "drain" is running
2274          * We do not care about races with the cpu hotplug because cpu down
2275          * as well as workers from this path always operate on the local
2276          * per-cpu data. CPU up doesn't touch memcg_stock at all.
2277          */
2278         curcpu = get_cpu();
2279         for_each_online_cpu(cpu) {
2280                 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2281                 struct mem_cgroup *memcg;
2282                 bool flush = false;
2283
2284                 rcu_read_lock();
2285                 memcg = stock->cached;
2286                 if (memcg && stock->nr_pages &&
2287                     mem_cgroup_is_descendant(memcg, root_memcg))
2288                         flush = true;
2289                 rcu_read_unlock();
2290
2291                 if (flush &&
2292                     !test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2293                         if (cpu == curcpu)
2294                                 drain_local_stock(&stock->work);
2295                         else
2296                                 schedule_work_on(cpu, &stock->work);
2297                 }
2298         }
2299         put_cpu();
2300         mutex_unlock(&percpu_charge_mutex);
2301 }
2302
2303 static int memcg_hotplug_cpu_dead(unsigned int cpu)
2304 {
2305         struct memcg_stock_pcp *stock;
2306         struct mem_cgroup *memcg, *mi;
2307
2308         stock = &per_cpu(memcg_stock, cpu);
2309         drain_stock(stock);
2310
2311         for_each_mem_cgroup(memcg) {
2312                 int i;
2313
2314                 for (i = 0; i < MEMCG_NR_STAT; i++) {
2315                         int nid;
2316                         long x;
2317
2318                         x = this_cpu_xchg(memcg->vmstats_percpu->stat[i], 0);
2319                         if (x)
2320                                 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
2321                                         atomic_long_add(x, &memcg->vmstats[i]);
2322
2323                         if (i >= NR_VM_NODE_STAT_ITEMS)
2324                                 continue;
2325
2326                         for_each_node(nid) {
2327                                 struct mem_cgroup_per_node *pn;
2328
2329                                 pn = mem_cgroup_nodeinfo(memcg, nid);
2330                                 x = this_cpu_xchg(pn->lruvec_stat_cpu->count[i], 0);
2331                                 if (x)
2332                                         do {
2333                                                 atomic_long_add(x, &pn->lruvec_stat[i]);
2334                                         } while ((pn = parent_nodeinfo(pn, nid)));
2335                         }
2336                 }
2337
2338                 for (i = 0; i < NR_VM_EVENT_ITEMS; i++) {
2339                         long x;
2340
2341                         x = this_cpu_xchg(memcg->vmstats_percpu->events[i], 0);
2342                         if (x)
2343                                 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
2344                                         atomic_long_add(x, &memcg->vmevents[i]);
2345                 }
2346         }
2347
2348         return 0;
2349 }
2350
2351 static void reclaim_high(struct mem_cgroup *memcg,
2352                          unsigned int nr_pages,
2353                          gfp_t gfp_mask)
2354 {
2355         do {
2356                 if (page_counter_read(&memcg->memory) <= memcg->high)
2357                         continue;
2358                 memcg_memory_event(memcg, MEMCG_HIGH);
2359                 try_to_free_mem_cgroup_pages(memcg, nr_pages, gfp_mask, true);
2360         } while ((memcg = parent_mem_cgroup(memcg)));
2361 }
2362
2363 static void high_work_func(struct work_struct *work)
2364 {
2365         struct mem_cgroup *memcg;
2366
2367         memcg = container_of(work, struct mem_cgroup, high_work);
2368         reclaim_high(memcg, MEMCG_CHARGE_BATCH, GFP_KERNEL);
2369 }
2370
2371 /*
2372  * Clamp the maximum sleep time per allocation batch to 2 seconds. This is
2373  * enough to still cause a significant slowdown in most cases, while still
2374  * allowing diagnostics and tracing to proceed without becoming stuck.
2375  */
2376 #define MEMCG_MAX_HIGH_DELAY_JIFFIES (2UL*HZ)
2377
2378 /*
2379  * When calculating the delay, we use these either side of the exponentiation to
2380  * maintain precision and scale to a reasonable number of jiffies (see the table
2381  * below.
2382  *
2383  * - MEMCG_DELAY_PRECISION_SHIFT: Extra precision bits while translating the
2384  *   overage ratio to a delay.
2385  * - MEMCG_DELAY_SCALING_SHIFT: The number of bits to scale down down the
2386  *   proposed penalty in order to reduce to a reasonable number of jiffies, and
2387  *   to produce a reasonable delay curve.
2388  *
2389  * MEMCG_DELAY_SCALING_SHIFT just happens to be a number that produces a
2390  * reasonable delay curve compared to precision-adjusted overage, not
2391  * penalising heavily at first, but still making sure that growth beyond the
2392  * limit penalises misbehaviour cgroups by slowing them down exponentially. For
2393  * example, with a high of 100 megabytes:
2394  *
2395  *  +-------+------------------------+
2396  *  | usage | time to allocate in ms |
2397  *  +-------+------------------------+
2398  *  | 100M  |                      0 |
2399  *  | 101M  |                      6 |
2400  *  | 102M  |                     25 |
2401  *  | 103M  |                     57 |
2402  *  | 104M  |                    102 |
2403  *  | 105M  |                    159 |
2404  *  | 106M  |                    230 |
2405  *  | 107M  |                    313 |
2406  *  | 108M  |                    409 |
2407  *  | 109M  |                    518 |
2408  *  | 110M  |                    639 |
2409  *  | 111M  |                    774 |
2410  *  | 112M  |                    921 |
2411  *  | 113M  |                   1081 |
2412  *  | 114M  |                   1254 |
2413  *  | 115M  |                   1439 |
2414  *  | 116M  |                   1638 |
2415  *  | 117M  |                   1849 |
2416  *  | 118M  |                   2000 |
2417  *  | 119M  |                   2000 |
2418  *  | 120M  |                   2000 |
2419  *  +-------+------------------------+
2420  */
2421  #define MEMCG_DELAY_PRECISION_SHIFT 20
2422  #define MEMCG_DELAY_SCALING_SHIFT 14
2423
2424 /*
2425  * Get the number of jiffies that we should penalise a mischievous cgroup which
2426  * is exceeding its memory.high by checking both it and its ancestors.
2427  */
2428 static unsigned long calculate_high_delay(struct mem_cgroup *memcg,
2429                                           unsigned int nr_pages)
2430 {
2431         unsigned long penalty_jiffies;
2432         u64 max_overage = 0;
2433
2434         do {
2435                 unsigned long usage, high;
2436                 u64 overage;
2437
2438                 usage = page_counter_read(&memcg->memory);
2439                 high = READ_ONCE(memcg->high);
2440
2441                 if (usage <= high)
2442                         continue;
2443
2444                 /*
2445                  * Prevent division by 0 in overage calculation by acting as if
2446                  * it was a threshold of 1 page
2447                  */
2448                 high = max(high, 1UL);
2449
2450                 overage = usage - high;
2451                 overage <<= MEMCG_DELAY_PRECISION_SHIFT;
2452                 overage = div64_u64(overage, high);
2453
2454                 if (overage > max_overage)
2455                         max_overage = overage;
2456         } while ((memcg = parent_mem_cgroup(memcg)) &&
2457                  !mem_cgroup_is_root(memcg));
2458
2459         if (!max_overage)
2460                 return 0;
2461
2462         /*
2463          * We use overage compared to memory.high to calculate the number of
2464          * jiffies to sleep (penalty_jiffies). Ideally this value should be
2465          * fairly lenient on small overages, and increasingly harsh when the
2466          * memcg in question makes it clear that it has no intention of stopping
2467          * its crazy behaviour, so we exponentially increase the delay based on
2468          * overage amount.
2469          */
2470         penalty_jiffies = max_overage * max_overage * HZ;
2471         penalty_jiffies >>= MEMCG_DELAY_PRECISION_SHIFT;
2472         penalty_jiffies >>= MEMCG_DELAY_SCALING_SHIFT;
2473
2474         /*
2475          * Factor in the task's own contribution to the overage, such that four
2476          * N-sized allocations are throttled approximately the same as one
2477          * 4N-sized allocation.
2478          *
2479          * MEMCG_CHARGE_BATCH pages is nominal, so work out how much smaller or
2480          * larger the current charge patch is than that.
2481          */
2482         penalty_jiffies = penalty_jiffies * nr_pages / MEMCG_CHARGE_BATCH;
2483
2484         /*
2485          * Clamp the max delay per usermode return so as to still keep the
2486          * application moving forwards and also permit diagnostics, albeit
2487          * extremely slowly.
2488          */
2489         return min(penalty_jiffies, MEMCG_MAX_HIGH_DELAY_JIFFIES);
2490 }
2491
2492 /*
2493  * Scheduled by try_charge() to be executed from the userland return path
2494  * and reclaims memory over the high limit.
2495  */
2496 void mem_cgroup_handle_over_high(void)
2497 {
2498         unsigned long penalty_jiffies;
2499         unsigned long pflags;
2500         unsigned int nr_pages = current->memcg_nr_pages_over_high;
2501         struct mem_cgroup *memcg;
2502
2503         if (likely(!nr_pages))
2504                 return;
2505
2506         memcg = get_mem_cgroup_from_mm(current->mm);
2507         reclaim_high(memcg, nr_pages, GFP_KERNEL);
2508         current->memcg_nr_pages_over_high = 0;
2509
2510         /*
2511          * memory.high is breached and reclaim is unable to keep up. Throttle
2512          * allocators proactively to slow down excessive growth.
2513          */
2514         penalty_jiffies = calculate_high_delay(memcg, nr_pages);
2515
2516         /*
2517          * Don't sleep if the amount of jiffies this memcg owes us is so low
2518          * that it's not even worth doing, in an attempt to be nice to those who
2519          * go only a small amount over their memory.high value and maybe haven't
2520          * been aggressively reclaimed enough yet.
2521          */
2522         if (penalty_jiffies <= HZ / 100)
2523                 goto out;
2524
2525         /*
2526          * If we exit early, we're guaranteed to die (since
2527          * schedule_timeout_killable sets TASK_KILLABLE). This means we don't
2528          * need to account for any ill-begotten jiffies to pay them off later.
2529          */
2530         psi_memstall_enter(&pflags);
2531         schedule_timeout_killable(penalty_jiffies);
2532         psi_memstall_leave(&pflags);
2533
2534 out:
2535         css_put(&memcg->css);
2536 }
2537
2538 static int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2539                       unsigned int nr_pages)
2540 {
2541         unsigned int batch = max(MEMCG_CHARGE_BATCH, nr_pages);
2542         int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
2543         struct mem_cgroup *mem_over_limit;
2544         struct page_counter *counter;
2545         unsigned long nr_reclaimed;
2546         bool may_swap = true;
2547         bool drained = false;
2548         enum oom_status oom_status;
2549
2550         if (mem_cgroup_is_root(memcg))
2551                 return 0;
2552 retry:
2553         if (consume_stock(memcg, nr_pages))
2554                 return 0;
2555
2556         if (!do_memsw_account() ||
2557             page_counter_try_charge(&memcg->memsw, batch, &counter)) {
2558                 if (page_counter_try_charge(&memcg->memory, batch, &counter))
2559                         goto done_restock;
2560                 if (do_memsw_account())
2561                         page_counter_uncharge(&memcg->memsw, batch);
2562                 mem_over_limit = mem_cgroup_from_counter(counter, memory);
2563         } else {
2564                 mem_over_limit = mem_cgroup_from_counter(counter, memsw);
2565                 may_swap = false;
2566         }
2567
2568         if (batch > nr_pages) {
2569                 batch = nr_pages;
2570                 goto retry;
2571         }
2572
2573         /*
2574          * Memcg doesn't have a dedicated reserve for atomic
2575          * allocations. But like the global atomic pool, we need to
2576          * put the burden of reclaim on regular allocation requests
2577          * and let these go through as privileged allocations.
2578          */
2579         if (gfp_mask & __GFP_ATOMIC)
2580                 goto force;
2581
2582         /*
2583          * Unlike in global OOM situations, memcg is not in a physical
2584          * memory shortage.  Allow dying and OOM-killed tasks to
2585          * bypass the last charges so that they can exit quickly and
2586          * free their memory.
2587          */
2588         if (unlikely(should_force_charge()))
2589                 goto force;
2590
2591         /*
2592          * Prevent unbounded recursion when reclaim operations need to
2593          * allocate memory. This might exceed the limits temporarily,
2594          * but we prefer facilitating memory reclaim and getting back
2595          * under the limit over triggering OOM kills in these cases.
2596          */
2597         if (unlikely(current->flags & PF_MEMALLOC))
2598                 goto force;
2599
2600         if (unlikely(task_in_memcg_oom(current)))
2601                 goto nomem;
2602
2603         if (!gfpflags_allow_blocking(gfp_mask))
2604                 goto nomem;
2605
2606         memcg_memory_event(mem_over_limit, MEMCG_MAX);
2607
2608         nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
2609                                                     gfp_mask, may_swap);
2610
2611         if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2612                 goto retry;
2613
2614         if (!drained) {
2615                 drain_all_stock(mem_over_limit);
2616                 drained = true;
2617                 goto retry;
2618         }
2619
2620         if (gfp_mask & __GFP_NORETRY)
2621                 goto nomem;
2622         /*
2623          * Even though the limit is exceeded at this point, reclaim
2624          * may have been able to free some pages.  Retry the charge
2625          * before killing the task.
2626          *
2627          * Only for regular pages, though: huge pages are rather
2628          * unlikely to succeed so close to the limit, and we fall back
2629          * to regular pages anyway in case of failure.
2630          */
2631         if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
2632                 goto retry;
2633         /*
2634          * At task move, charge accounts can be doubly counted. So, it's
2635          * better to wait until the end of task_move if something is going on.
2636          */
2637         if (mem_cgroup_wait_acct_move(mem_over_limit))
2638                 goto retry;
2639
2640         if (nr_retries--)
2641                 goto retry;
2642
2643         if (gfp_mask & __GFP_RETRY_MAYFAIL)
2644                 goto nomem;
2645
2646         if (gfp_mask & __GFP_NOFAIL)
2647                 goto force;
2648
2649         if (fatal_signal_pending(current))
2650                 goto force;
2651
2652         /*
2653          * keep retrying as long as the memcg oom killer is able to make
2654          * a forward progress or bypass the charge if the oom killer
2655          * couldn't make any progress.
2656          */
2657         oom_status = mem_cgroup_oom(mem_over_limit, gfp_mask,
2658                        get_order(nr_pages * PAGE_SIZE));
2659         switch (oom_status) {
2660         case OOM_SUCCESS:
2661                 nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
2662                 goto retry;
2663         case OOM_FAILED:
2664                 goto force;
2665         default:
2666                 goto nomem;
2667         }
2668 nomem:
2669         if (!(gfp_mask & __GFP_NOFAIL))
2670                 return -ENOMEM;
2671 force:
2672         /*
2673          * The allocation either can't fail or will lead to more memory
2674          * being freed very soon.  Allow memory usage go over the limit
2675          * temporarily by force charging it.
2676          */
2677         page_counter_charge(&memcg->memory, nr_pages);
2678         if (do_memsw_account())
2679                 page_counter_charge(&memcg->memsw, nr_pages);
2680         css_get_many(&memcg->css, nr_pages);
2681
2682         return 0;
2683
2684 done_restock:
2685         css_get_many(&memcg->css, batch);
2686         if (batch > nr_pages)
2687                 refill_stock(memcg, batch - nr_pages);
2688
2689         /*
2690          * If the hierarchy is above the normal consumption range, schedule
2691          * reclaim on returning to userland.  We can perform reclaim here
2692          * if __GFP_RECLAIM but let's always punt for simplicity and so that
2693          * GFP_KERNEL can consistently be used during reclaim.  @memcg is
2694          * not recorded as it most likely matches current's and won't
2695          * change in the meantime.  As high limit is checked again before
2696          * reclaim, the cost of mismatch is negligible.
2697          */
2698         do {
2699                 if (page_counter_read(&memcg->memory) > memcg->high) {
2700                         /* Don't bother a random interrupted task */
2701                         if (in_interrupt()) {
2702                                 schedule_work(&memcg->high_work);
2703                                 break;
2704                         }
2705                         current->memcg_nr_pages_over_high += batch;
2706                         set_notify_resume(current);
2707                         break;
2708                 }
2709         } while ((memcg = parent_mem_cgroup(memcg)));
2710
2711         return 0;
2712 }
2713
2714 static void cancel_charge(struct mem_cgroup *memcg, unsigned int nr_pages)
2715 {
2716         if (mem_cgroup_is_root(memcg))
2717                 return;
2718
2719         page_counter_uncharge(&memcg->memory, nr_pages);
2720         if (do_memsw_account())
2721                 page_counter_uncharge(&memcg->memsw, nr_pages);
2722
2723         css_put_many(&memcg->css, nr_pages);
2724 }
2725
2726 static void lock_page_lru(struct page *page, int *isolated)
2727 {
2728         pg_data_t *pgdat = page_pgdat(page);
2729
2730         spin_lock_irq(&pgdat->lru_lock);
2731         if (PageLRU(page)) {
2732                 struct lruvec *lruvec;
2733
2734                 lruvec = mem_cgroup_page_lruvec(page, pgdat);
2735                 ClearPageLRU(page);
2736                 del_page_from_lru_list(page, lruvec, page_lru(page));
2737                 *isolated = 1;
2738         } else
2739                 *isolated = 0;
2740 }
2741
2742 static void unlock_page_lru(struct page *page, int isolated)
2743 {
2744         pg_data_t *pgdat = page_pgdat(page);
2745
2746         if (isolated) {
2747                 struct lruvec *lruvec;
2748
2749                 lruvec = mem_cgroup_page_lruvec(page, pgdat);
2750                 VM_BUG_ON_PAGE(PageLRU(page), page);
2751                 SetPageLRU(page);
2752                 add_page_to_lru_list(page, lruvec, page_lru(page));
2753         }
2754         spin_unlock_irq(&pgdat->lru_lock);
2755 }
2756
2757 static void commit_charge(struct page *page, struct mem_cgroup *memcg,
2758                           bool lrucare)
2759 {
2760         int isolated;
2761
2762         VM_BUG_ON_PAGE(page->mem_cgroup, page);
2763
2764         /*
2765          * In some cases, SwapCache and FUSE(splice_buf->radixtree), the page
2766          * may already be on some other mem_cgroup's LRU.  Take care of it.
2767          */
2768         if (lrucare)
2769                 lock_page_lru(page, &isolated);
2770
2771         /*
2772          * Nobody should be changing or seriously looking at
2773          * page->mem_cgroup at this point:
2774          *
2775          * - the page is uncharged
2776          *
2777          * - the page is off-LRU
2778          *
2779          * - an anonymous fault has exclusive page access, except for
2780          *   a locked page table
2781          *
2782          * - a page cache insertion, a swapin fault, or a migration
2783          *   have the page locked
2784          */
2785         page->mem_cgroup = memcg;
2786
2787         if (lrucare)
2788                 unlock_page_lru(page, isolated);
2789 }
2790
2791 #ifdef CONFIG_MEMCG_KMEM
2792 /*
2793  * Returns a pointer to the memory cgroup to which the kernel object is charged.
2794  *
2795  * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
2796  * cgroup_mutex, etc.
2797  */
2798 struct mem_cgroup *mem_cgroup_from_obj(void *p)
2799 {
2800         struct page *page;
2801
2802         if (mem_cgroup_disabled())
2803                 return NULL;
2804
2805         page = virt_to_head_page(p);
2806
2807         /*
2808          * Slab pages don't have page->mem_cgroup set because corresponding
2809          * kmem caches can be reparented during the lifetime. That's why
2810          * memcg_from_slab_page() should be used instead.
2811          */
2812         if (PageSlab(page))
2813                 return memcg_from_slab_page(page);
2814
2815         /* All other pages use page->mem_cgroup */
2816         return page->mem_cgroup;
2817 }
2818
2819 static int memcg_alloc_cache_id(void)
2820 {
2821         int id, size;
2822         int err;
2823
2824         id = ida_simple_get(&memcg_cache_ida,
2825                             0, MEMCG_CACHES_MAX_SIZE, GFP_KERNEL);
2826         if (id < 0)
2827                 return id;
2828
2829         if (id < memcg_nr_cache_ids)
2830                 return id;
2831
2832         /*
2833          * There's no space for the new id in memcg_caches arrays,
2834          * so we have to grow them.
2835          */
2836         down_write(&memcg_cache_ids_sem);
2837
2838         size = 2 * (id + 1);
2839         if (size < MEMCG_CACHES_MIN_SIZE)
2840                 size = MEMCG_CACHES_MIN_SIZE;
2841         else if (size > MEMCG_CACHES_MAX_SIZE)
2842                 size = MEMCG_CACHES_MAX_SIZE;
2843
2844         err = memcg_update_all_caches(size);
2845         if (!err)
2846                 err = memcg_update_all_list_lrus(size);
2847         if (!err)
2848                 memcg_nr_cache_ids = size;
2849
2850         up_write(&memcg_cache_ids_sem);
2851
2852         if (err) {
2853                 ida_simple_remove(&memcg_cache_ida, id);
2854                 return err;
2855         }
2856         return id;
2857 }
2858
2859 static void memcg_free_cache_id(int id)
2860 {
2861         ida_simple_remove(&memcg_cache_ida, id);
2862 }
2863
2864 struct memcg_kmem_cache_create_work {
2865         struct mem_cgroup *memcg;
2866         struct kmem_cache *cachep;
2867         struct work_struct work;
2868 };
2869
2870 static void memcg_kmem_cache_create_func(struct work_struct *w)
2871 {
2872         struct memcg_kmem_cache_create_work *cw =
2873                 container_of(w, struct memcg_kmem_cache_create_work, work);
2874         struct mem_cgroup *memcg = cw->memcg;
2875         struct kmem_cache *cachep = cw->cachep;
2876
2877         memcg_create_kmem_cache(memcg, cachep);
2878
2879         css_put(&memcg->css);
2880         kfree(cw);
2881 }
2882
2883 /*
2884  * Enqueue the creation of a per-memcg kmem_cache.
2885  */
2886 static void memcg_schedule_kmem_cache_create(struct mem_cgroup *memcg,
2887                                                struct kmem_cache *cachep)
2888 {
2889         struct memcg_kmem_cache_create_work *cw;
2890
2891         if (!css_tryget_online(&memcg->css))
2892                 return;
2893
2894         cw = kmalloc(sizeof(*cw), GFP_NOWAIT | __GFP_NOWARN);
2895         if (!cw) {
2896                 css_put(&memcg->css);
2897                 return;
2898         }
2899
2900         cw->memcg = memcg;
2901         cw->cachep = cachep;
2902         INIT_WORK(&cw->work, memcg_kmem_cache_create_func);
2903
2904         queue_work(memcg_kmem_cache_wq, &cw->work);
2905 }
2906
2907 static inline bool memcg_kmem_bypass(void)
2908 {
2909         if (in_interrupt() || !current->mm || (current->flags & PF_KTHREAD))
2910                 return true;
2911         return false;
2912 }
2913
2914 /**
2915  * memcg_kmem_get_cache: select the correct per-memcg cache for allocation
2916  * @cachep: the original global kmem cache
2917  *
2918  * Return the kmem_cache we're supposed to use for a slab allocation.
2919  * We try to use the current memcg's version of the cache.
2920  *
2921  * If the cache does not exist yet, if we are the first user of it, we
2922  * create it asynchronously in a workqueue and let the current allocation
2923  * go through with the original cache.
2924  *
2925  * This function takes a reference to the cache it returns to assure it
2926  * won't get destroyed while we are working with it. Once the caller is
2927  * done with it, memcg_kmem_put_cache() must be called to release the
2928  * reference.
2929  */
2930 struct kmem_cache *memcg_kmem_get_cache(struct kmem_cache *cachep)
2931 {
2932         struct mem_cgroup *memcg;
2933         struct kmem_cache *memcg_cachep;
2934         struct memcg_cache_array *arr;
2935         int kmemcg_id;
2936
2937         VM_BUG_ON(!is_root_cache(cachep));
2938
2939         if (memcg_kmem_bypass())
2940                 return cachep;
2941
2942         rcu_read_lock();
2943
2944         if (unlikely(current->active_memcg))
2945                 memcg = current->active_memcg;
2946         else
2947                 memcg = mem_cgroup_from_task(current);
2948
2949         if (!memcg || memcg == root_mem_cgroup)
2950                 goto out_unlock;
2951
2952         kmemcg_id = READ_ONCE(memcg->kmemcg_id);
2953         if (kmemcg_id < 0)
2954                 goto out_unlock;
2955
2956         arr = rcu_dereference(cachep->memcg_params.memcg_caches);
2957
2958         /*
2959          * Make sure we will access the up-to-date value. The code updating
2960          * memcg_caches issues a write barrier to match the data dependency
2961          * barrier inside READ_ONCE() (see memcg_create_kmem_cache()).
2962          */
2963         memcg_cachep = READ_ONCE(arr->entries[kmemcg_id]);
2964
2965         /*
2966          * If we are in a safe context (can wait, and not in interrupt
2967          * context), we could be be predictable and return right away.
2968          * This would guarantee that the allocation being performed
2969          * already belongs in the new cache.
2970          *
2971          * However, there are some clashes that can arrive from locking.
2972          * For instance, because we acquire the slab_mutex while doing
2973          * memcg_create_kmem_cache, this means no further allocation
2974          * could happen with the slab_mutex held. So it's better to
2975          * defer everything.
2976          *
2977          * If the memcg is dying or memcg_cache is about to be released,
2978          * don't bother creating new kmem_caches. Because memcg_cachep
2979          * is ZEROed as the fist step of kmem offlining, we don't need
2980          * percpu_ref_tryget_live() here. css_tryget_online() check in
2981          * memcg_schedule_kmem_cache_create() will prevent us from
2982          * creation of a new kmem_cache.
2983          */
2984         if (unlikely(!memcg_cachep))
2985                 memcg_schedule_kmem_cache_create(memcg, cachep);
2986         else if (percpu_ref_tryget(&memcg_cachep->memcg_params.refcnt))
2987                 cachep = memcg_cachep;
2988 out_unlock:
2989         rcu_read_unlock();
2990         return cachep;
2991 }
2992
2993 /**
2994  * memcg_kmem_put_cache: drop reference taken by memcg_kmem_get_cache
2995  * @cachep: the cache returned by memcg_kmem_get_cache
2996  */
2997 void memcg_kmem_put_cache(struct kmem_cache *cachep)
2998 {
2999         if (!is_root_cache(cachep))
3000                 percpu_ref_put(&cachep->memcg_params.refcnt);
3001 }
3002
3003 /**
3004  * __memcg_kmem_charge_memcg: charge a kmem page
3005  * @page: page to charge
3006  * @gfp: reclaim mode
3007  * @order: allocation order
3008  * @memcg: memory cgroup to charge
3009  *
3010  * Returns 0 on success, an error code on failure.
3011  */
3012 int __memcg_kmem_charge_memcg(struct page *page, gfp_t gfp, int order,
3013                             struct mem_cgroup *memcg)
3014 {
3015         unsigned int nr_pages = 1 << order;
3016         struct page_counter *counter;
3017         int ret;
3018
3019         ret = try_charge(memcg, gfp, nr_pages);
3020         if (ret)
3021                 return ret;
3022
3023         if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) &&
3024             !page_counter_try_charge(&memcg->kmem, nr_pages, &counter)) {
3025
3026                 /*
3027                  * Enforce __GFP_NOFAIL allocation because callers are not
3028                  * prepared to see failures and likely do not have any failure
3029                  * handling code.
3030                  */
3031                 if (gfp & __GFP_NOFAIL) {
3032                         page_counter_charge(&memcg->kmem, nr_pages);
3033                         return 0;
3034                 }
3035                 cancel_charge(memcg, nr_pages);
3036                 return -ENOMEM;
3037         }
3038         return 0;
3039 }
3040
3041 /**
3042  * __memcg_kmem_charge: charge a kmem page to the current memory cgroup
3043  * @page: page to charge
3044  * @gfp: reclaim mode
3045  * @order: allocation order
3046  *
3047  * Returns 0 on success, an error code on failure.
3048  */
3049 int __memcg_kmem_charge(struct page *page, gfp_t gfp, int order)
3050 {
3051         struct mem_cgroup *memcg;
3052         int ret = 0;
3053
3054         if (memcg_kmem_bypass())
3055                 return 0;
3056
3057         memcg = get_mem_cgroup_from_current();
3058         if (!mem_cgroup_is_root(memcg)) {
3059                 ret = __memcg_kmem_charge_memcg(page, gfp, order, memcg);
3060                 if (!ret) {
3061                         page->mem_cgroup = memcg;
3062                         __SetPageKmemcg(page);
3063                 }
3064         }
3065         css_put(&memcg->css);
3066         return ret;
3067 }
3068
3069 /**
3070  * __memcg_kmem_uncharge_memcg: uncharge a kmem page
3071  * @memcg: memcg to uncharge
3072  * @nr_pages: number of pages to uncharge
3073  */
3074 void __memcg_kmem_uncharge_memcg(struct mem_cgroup *memcg,
3075                                  unsigned int nr_pages)
3076 {
3077         if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
3078                 page_counter_uncharge(&memcg->kmem, nr_pages);
3079
3080         page_counter_uncharge(&memcg->memory, nr_pages);
3081         if (do_memsw_account())
3082                 page_counter_uncharge(&memcg->memsw, nr_pages);
3083 }
3084 /**
3085  * __memcg_kmem_uncharge: uncharge a kmem page
3086  * @page: page to uncharge
3087  * @order: allocation order
3088  */
3089 void __memcg_kmem_uncharge(struct page *page, int order)
3090 {
3091         struct mem_cgroup *memcg = page->mem_cgroup;
3092         unsigned int nr_pages = 1 << order;
3093
3094         if (!memcg)
3095                 return;
3096
3097         VM_BUG_ON_PAGE(mem_cgroup_is_root(memcg), page);
3098         __memcg_kmem_uncharge_memcg(memcg, nr_pages);
3099         page->mem_cgroup = NULL;
3100
3101         /* slab pages do not have PageKmemcg flag set */
3102         if (PageKmemcg(page))
3103                 __ClearPageKmemcg(page);
3104
3105         css_put_many(&memcg->css, nr_pages);
3106 }
3107 #endif /* CONFIG_MEMCG_KMEM */
3108
3109 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3110
3111 /*
3112  * Because tail pages are not marked as "used", set it. We're under
3113  * pgdat->lru_lock and migration entries setup in all page mappings.
3114  */
3115 void mem_cgroup_split_huge_fixup(struct page *head)
3116 {
3117         int i;
3118
3119         if (mem_cgroup_disabled())
3120                 return;
3121
3122         for (i = 1; i < HPAGE_PMD_NR; i++)
3123                 head[i].mem_cgroup = head->mem_cgroup;
3124
3125         __mod_memcg_state(head->mem_cgroup, MEMCG_RSS_HUGE, -HPAGE_PMD_NR);
3126 }
3127 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
3128
3129 #ifdef CONFIG_MEMCG_SWAP
3130 /**
3131  * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3132  * @entry: swap entry to be moved
3133  * @from:  mem_cgroup which the entry is moved from
3134  * @to:  mem_cgroup which the entry is moved to
3135  *
3136  * It succeeds only when the swap_cgroup's record for this entry is the same
3137  * as the mem_cgroup's id of @from.
3138  *
3139  * Returns 0 on success, -EINVAL on failure.
3140  *
3141  * The caller must have charged to @to, IOW, called page_counter_charge() about
3142  * both res and memsw, and called css_get().
3143  */
3144 static int mem_cgroup_move_swap_account(swp_entry_t entry,
3145                                 struct mem_cgroup *from, struct mem_cgroup *to)
3146 {
3147         unsigned short old_id, new_id;
3148
3149         old_id = mem_cgroup_id(from);
3150         new_id = mem_cgroup_id(to);
3151
3152         if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
3153                 mod_memcg_state(from, MEMCG_SWAP, -1);
3154                 mod_memcg_state(to, MEMCG_SWAP, 1);
3155                 return 0;
3156         }
3157         return -EINVAL;
3158 }
3159 #else
3160 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
3161                                 struct mem_cgroup *from, struct mem_cgroup *to)
3162 {
3163         return -EINVAL;
3164 }
3165 #endif
3166
3167 static DEFINE_MUTEX(memcg_max_mutex);
3168
3169 static int mem_cgroup_resize_max(struct mem_cgroup *memcg,
3170                                  unsigned long max, bool memsw)
3171 {
3172         bool enlarge = false;
3173         bool drained = false;
3174         int ret;
3175         bool limits_invariant;
3176         struct page_counter *counter = memsw ? &memcg->memsw : &memcg->memory;
3177
3178         do {
3179                 if (signal_pending(current)) {
3180                         ret = -EINTR;
3181                         break;
3182                 }
3183
3184                 mutex_lock(&memcg_max_mutex);
3185                 /*
3186                  * Make sure that the new limit (memsw or memory limit) doesn't
3187                  * break our basic invariant rule memory.max <= memsw.max.
3188                  */
3189                 limits_invariant = memsw ? max >= memcg->memory.max :
3190                                            max <= memcg->memsw.max;
3191                 if (!limits_invariant) {
3192                         mutex_unlock(&memcg_max_mutex);
3193                         ret = -EINVAL;
3194                         break;
3195                 }
3196                 if (max > counter->max)
3197                         enlarge = true;
3198                 ret = page_counter_set_max(counter, max);
3199                 mutex_unlock(&memcg_max_mutex);
3200
3201                 if (!ret)
3202                         break;
3203
3204                 if (!drained) {
3205                         drain_all_stock(memcg);
3206                         drained = true;
3207                         continue;
3208                 }
3209
3210                 if (!try_to_free_mem_cgroup_pages(memcg, 1,
3211                                         GFP_KERNEL, !memsw)) {
3212                         ret = -EBUSY;
3213                         break;
3214                 }
3215         } while (true);
3216
3217         if (!ret && enlarge)
3218                 memcg_oom_recover(memcg);
3219
3220         return ret;
3221 }
3222
3223 unsigned long mem_cgroup_soft_limit_reclaim(pg_data_t *pgdat, int order,
3224                                             gfp_t gfp_mask,
3225                                             unsigned long *total_scanned)
3226 {
3227         unsigned long nr_reclaimed = 0;
3228         struct mem_cgroup_per_node *mz, *next_mz = NULL;
3229         unsigned long reclaimed;
3230         int loop = 0;
3231         struct mem_cgroup_tree_per_node *mctz;
3232         unsigned long excess;
3233         unsigned long nr_scanned;
3234
3235         if (order > 0)
3236                 return 0;
3237
3238         mctz = soft_limit_tree_node(pgdat->node_id);
3239
3240         /*
3241          * Do not even bother to check the largest node if the root
3242          * is empty. Do it lockless to prevent lock bouncing. Races
3243          * are acceptable as soft limit is best effort anyway.
3244          */
3245         if (!mctz || RB_EMPTY_ROOT(&mctz->rb_root))
3246                 return 0;
3247
3248         /*
3249          * This loop can run a while, specially if mem_cgroup's continuously
3250          * keep exceeding their soft limit and putting the system under
3251          * pressure
3252          */
3253         do {
3254                 if (next_mz)
3255                         mz = next_mz;
3256                 else
3257                         mz = mem_cgroup_largest_soft_limit_node(mctz);
3258                 if (!mz)
3259                         break;
3260
3261                 nr_scanned = 0;
3262                 reclaimed = mem_cgroup_soft_reclaim(mz->memcg, pgdat,
3263                                                     gfp_mask, &nr_scanned);
3264                 nr_reclaimed += reclaimed;
3265                 *total_scanned += nr_scanned;
3266                 spin_lock_irq(&mctz->lock);
3267                 __mem_cgroup_remove_exceeded(mz, mctz);
3268
3269                 /*
3270                  * If we failed to reclaim anything from this memory cgroup
3271                  * it is time to move on to the next cgroup
3272                  */
3273                 next_mz = NULL;
3274                 if (!reclaimed)
3275                         next_mz = __mem_cgroup_largest_soft_limit_node(mctz);
3276
3277                 excess = soft_limit_excess(mz->memcg);
3278                 /*
3279                  * One school of thought says that we should not add
3280                  * back the node to the tree if reclaim returns 0.
3281                  * But our reclaim could return 0, simply because due
3282                  * to priority we are exposing a smaller subset of
3283                  * memory to reclaim from. Consider this as a longer
3284                  * term TODO.
3285                  */
3286                 /* If excess == 0, no tree ops */
3287                 __mem_cgroup_insert_exceeded(mz, mctz, excess);
3288                 spin_unlock_irq(&mctz->lock);
3289                 css_put(&mz->memcg->css);
3290                 loop++;
3291                 /*
3292                  * Could not reclaim anything and there are no more
3293                  * mem cgroups to try or we seem to be looping without
3294                  * reclaiming anything.
3295                  */
3296                 if (!nr_reclaimed &&
3297                         (next_mz == NULL ||
3298                         loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3299                         break;
3300         } while (!nr_reclaimed);
3301         if (next_mz)
3302                 css_put(&next_mz->memcg->css);
3303         return nr_reclaimed;
3304 }
3305
3306 /*
3307  * Test whether @memcg has children, dead or alive.  Note that this
3308  * function doesn't care whether @memcg has use_hierarchy enabled and
3309  * returns %true if there are child csses according to the cgroup
3310  * hierarchy.  Testing use_hierarchy is the caller's responsiblity.
3311  */
3312 static inline bool memcg_has_children(struct mem_cgroup *memcg)
3313 {
3314         bool ret;
3315
3316         rcu_read_lock();
3317         ret = css_next_child(NULL, &memcg->css);
3318         rcu_read_unlock();
3319         return ret;
3320 }
3321
3322 /*
3323  * Reclaims as many pages from the given memcg as possible.
3324  *
3325  * Caller is responsible for holding css reference for memcg.
3326  */
3327 static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
3328 {
3329         int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
3330
3331         /* we call try-to-free pages for make this cgroup empty */
3332         lru_add_drain_all();
3333
3334         drain_all_stock(memcg);
3335
3336         /* try to free all pages in this cgroup */
3337         while (nr_retries && page_counter_read(&memcg->memory)) {
3338                 int progress;
3339
3340                 if (signal_pending(current))
3341                         return -EINTR;
3342
3343                 progress = try_to_free_mem_cgroup_pages(memcg, 1,
3344                                                         GFP_KERNEL, true);
3345                 if (!progress) {
3346                         nr_retries--;
3347                         /* maybe some writeback is necessary */
3348                         congestion_wait(BLK_RW_ASYNC, HZ/10);
3349                 }
3350
3351         }
3352
3353         return 0;
3354 }
3355
3356 static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
3357                                             char *buf, size_t nbytes,
3358                                             loff_t off)
3359 {
3360         struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3361
3362         if (mem_cgroup_is_root(memcg))
3363                 return -EINVAL;
3364         return mem_cgroup_force_empty(memcg) ?: nbytes;
3365 }
3366
3367 #ifdef CONFIG_MEMCG_SWAP
3368 static int mem_cgroup_force_reclaim(struct cgroup_subsys_state *css,
3369                                struct cftype *cft, u64 val)
3370 {
3371         struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3372         unsigned long nr_to_reclaim = val;
3373         unsigned long total = 0;
3374         int loop;
3375
3376         for (loop = 0; loop < MEM_CGROUP_MAX_RECLAIM_LOOPS; loop++) {
3377                 total += try_to_free_mem_cgroup_pages(memcg, nr_to_reclaim,
3378                                                 GFP_KERNEL, true);
3379
3380                 /*
3381                  * If nothing was reclaimed after two attempts, there
3382                  * may be no reclaimable pages in this hierarchy.
3383                  * If more than nr_to_reclaim pages were already reclaimed,
3384                  * finish force reclaim.
3385                  */
3386                 if (loop && (!total || total > nr_to_reclaim))
3387                         break;
3388         }
3389
3390         pr_info("%s: [Mem_reclaim] Loop: %d - Total_reclaimed: %lu - nr_to_reclaim: %lu\n",
3391                 __func__, loop, total, nr_to_reclaim);
3392
3393         return total;
3394 }
3395 #endif
3396
3397 static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
3398                                      struct cftype *cft)
3399 {
3400         return mem_cgroup_from_css(css)->use_hierarchy;
3401 }
3402
3403 static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
3404                                       struct cftype *cft, u64 val)
3405 {
3406         int retval = 0;
3407         struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3408         struct mem_cgroup *parent_memcg = mem_cgroup_from_css(memcg->css.parent);
3409
3410         if (memcg->use_hierarchy == val)
3411                 return 0;
3412
3413         /*
3414          * If parent's use_hierarchy is set, we can't make any modifications
3415          * in the child subtrees. If it is unset, then the change can
3416          * occur, provided the current cgroup has no children.
3417          *
3418          * For the root cgroup, parent_mem is NULL, we allow value to be
3419          * set if there are no children.
3420          */
3421         if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
3422                                 (val == 1 || val == 0)) {
3423                 if (!memcg_has_children(memcg))
3424                         memcg->use_hierarchy = val;
3425                 else
3426                         retval = -EBUSY;
3427         } else
3428                 retval = -EINVAL;
3429
3430         return retval;
3431 }
3432
3433 static unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
3434 {
3435         unsigned long val;
3436
3437         if (mem_cgroup_is_root(memcg)) {
3438                 val = memcg_page_state(memcg, MEMCG_CACHE) +
3439                         memcg_page_state(memcg, MEMCG_RSS);
3440                 if (swap)
3441                         val += memcg_page_state(memcg, MEMCG_SWAP);
3442         } else {
3443                 if (!swap)
3444                         val = page_counter_read(&memcg->memory);
3445                 else
3446                         val = page_counter_read(&memcg->memsw);
3447         }
3448         return val;
3449 }
3450
3451 enum {
3452         RES_USAGE,
3453         RES_LIMIT,
3454         RES_MAX_USAGE,
3455         RES_FAILCNT,
3456         RES_SOFT_LIMIT,
3457 };
3458
3459 static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
3460                                struct cftype *cft)
3461 {
3462         struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3463         struct page_counter *counter;
3464
3465         switch (MEMFILE_TYPE(cft->private)) {
3466         case _MEM:
3467                 counter = &memcg->memory;
3468                 break;
3469         case _MEMSWAP:
3470                 counter = &memcg->memsw;
3471                 break;
3472         case _KMEM:
3473                 counter = &memcg->kmem;
3474                 break;
3475         case _TCP:
3476                 counter = &memcg->tcpmem;
3477                 break;
3478         default:
3479                 BUG();
3480         }
3481
3482         switch (MEMFILE_ATTR(cft->private)) {
3483         case RES_USAGE:
3484                 if (counter == &memcg->memory)
3485                         return (u64)mem_cgroup_usage(memcg, false) * PAGE_SIZE;
3486                 if (counter == &memcg->memsw)
3487                         return (u64)mem_cgroup_usage(memcg, true) * PAGE_SIZE;
3488                 return (u64)page_counter_read(counter) * PAGE_SIZE;
3489         case RES_LIMIT:
3490                 return (u64)counter->max * PAGE_SIZE;
3491         case RES_MAX_USAGE:
3492                 return (u64)counter->watermark * PAGE_SIZE;
3493         case RES_FAILCNT:
3494                 return counter->failcnt;
3495         case RES_SOFT_LIMIT:
3496                 return (u64)memcg->soft_limit * PAGE_SIZE;
3497         default:
3498                 BUG();
3499         }
3500 }
3501
3502 static void memcg_flush_percpu_vmstats(struct mem_cgroup *memcg)
3503 {
3504         unsigned long stat[MEMCG_NR_STAT] = {0};
3505         struct mem_cgroup *mi;
3506         int node, cpu, i;
3507
3508         for_each_online_cpu(cpu)
3509                 for (i = 0; i < MEMCG_NR_STAT; i++)
3510                         stat[i] += per_cpu(memcg->vmstats_percpu->stat[i], cpu);
3511
3512         for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
3513                 for (i = 0; i < MEMCG_NR_STAT; i++)
3514                         atomic_long_add(stat[i], &mi->vmstats[i]);
3515
3516         for_each_node(node) {
3517                 struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
3518                 struct mem_cgroup_per_node *pi;
3519
3520                 for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++)
3521                         stat[i] = 0;
3522
3523                 for_each_online_cpu(cpu)
3524                         for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++)
3525                                 stat[i] += per_cpu(
3526                                         pn->lruvec_stat_cpu->count[i], cpu);
3527
3528                 for (pi = pn; pi; pi = parent_nodeinfo(pi, node))
3529                         for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++)
3530                                 atomic_long_add(stat[i], &pi->lruvec_stat[i]);
3531         }
3532 }
3533
3534 static void memcg_flush_percpu_vmevents(struct mem_cgroup *memcg)
3535 {
3536         unsigned long events[NR_VM_EVENT_ITEMS];
3537         struct mem_cgroup *mi;
3538         int cpu, i;
3539
3540         for (i = 0; i < NR_VM_EVENT_ITEMS; i++)
3541                 events[i] = 0;
3542
3543         for_each_online_cpu(cpu)
3544                 for (i = 0; i < NR_VM_EVENT_ITEMS; i++)
3545                         events[i] += per_cpu(memcg->vmstats_percpu->events[i],
3546                                              cpu);
3547
3548         for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
3549                 for (i = 0; i < NR_VM_EVENT_ITEMS; i++)
3550                         atomic_long_add(events[i], &mi->vmevents[i]);
3551 }
3552
3553 #ifdef CONFIG_MEMCG_KMEM
3554 static int memcg_online_kmem(struct mem_cgroup *memcg)
3555 {
3556         int memcg_id;
3557
3558         if (cgroup_memory_nokmem)
3559                 return 0;
3560
3561         BUG_ON(memcg->kmemcg_id >= 0);
3562         BUG_ON(memcg->kmem_state);
3563
3564         memcg_id = memcg_alloc_cache_id();
3565         if (memcg_id < 0)
3566                 return memcg_id;
3567
3568         static_branch_inc(&memcg_kmem_enabled_key);
3569         /*
3570          * A memory cgroup is considered kmem-online as soon as it gets
3571          * kmemcg_id. Setting the id after enabling static branching will
3572          * guarantee no one starts accounting before all call sites are
3573          * patched.
3574          */
3575         memcg->kmemcg_id = memcg_id;
3576         memcg->kmem_state = KMEM_ONLINE;
3577         INIT_LIST_HEAD(&memcg->kmem_caches);
3578
3579         return 0;
3580 }
3581
3582 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3583 {
3584         struct cgroup_subsys_state *css;
3585         struct mem_cgroup *parent, *child;
3586         int kmemcg_id;
3587
3588         if (memcg->kmem_state != KMEM_ONLINE)
3589                 return;
3590         /*
3591          * Clear the online state before clearing memcg_caches array
3592          * entries. The slab_mutex in memcg_deactivate_kmem_caches()
3593          * guarantees that no cache will be created for this cgroup
3594          * after we are done (see memcg_create_kmem_cache()).
3595          */
3596         memcg->kmem_state = KMEM_ALLOCATED;
3597
3598         parent = parent_mem_cgroup(memcg);
3599         if (!parent)
3600                 parent = root_mem_cgroup;
3601
3602         /*
3603          * Deactivate and reparent kmem_caches.
3604          */
3605         memcg_deactivate_kmem_caches(memcg, parent);
3606
3607         kmemcg_id = memcg->kmemcg_id;
3608         BUG_ON(kmemcg_id < 0);
3609
3610         /*
3611          * Change kmemcg_id of this cgroup and all its descendants to the
3612          * parent's id, and then move all entries from this cgroup's list_lrus
3613          * to ones of the parent. After we have finished, all list_lrus
3614          * corresponding to this cgroup are guaranteed to remain empty. The
3615          * ordering is imposed by list_lru_node->lock taken by
3616          * memcg_drain_all_list_lrus().
3617          */
3618         rcu_read_lock(); /* can be called from css_free w/o cgroup_mutex */
3619         css_for_each_descendant_pre(css, &memcg->css) {
3620                 child = mem_cgroup_from_css(css);
3621                 BUG_ON(child->kmemcg_id != kmemcg_id);
3622                 child->kmemcg_id = parent->kmemcg_id;
3623                 if (!memcg->use_hierarchy)
3624                         break;
3625         }
3626         rcu_read_unlock();
3627
3628         memcg_drain_all_list_lrus(kmemcg_id, parent);
3629
3630         memcg_free_cache_id(kmemcg_id);
3631 }
3632
3633 static void memcg_free_kmem(struct mem_cgroup *memcg)
3634 {
3635         /* css_alloc() failed, offlining didn't happen */
3636         if (unlikely(memcg->kmem_state == KMEM_ONLINE))
3637                 memcg_offline_kmem(memcg);
3638
3639         if (memcg->kmem_state == KMEM_ALLOCATED) {
3640                 WARN_ON(!list_empty(&memcg->kmem_caches));
3641                 static_branch_dec(&memcg_kmem_enabled_key);
3642         }
3643 }
3644 #else
3645 static int memcg_online_kmem(struct mem_cgroup *memcg)
3646 {
3647         return 0;
3648 }
3649 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3650 {
3651 }
3652 static void memcg_free_kmem(struct mem_cgroup *memcg)
3653 {
3654 }
3655 #endif /* CONFIG_MEMCG_KMEM */
3656
3657 static int memcg_update_kmem_max(struct mem_cgroup *memcg,
3658                                  unsigned long max)
3659 {
3660         int ret;
3661
3662         mutex_lock(&memcg_max_mutex);
3663         ret = page_counter_set_max(&memcg->kmem, max);
3664         mutex_unlock(&memcg_max_mutex);
3665         return ret;
3666 }
3667
3668 static int memcg_update_tcp_max(struct mem_cgroup *memcg, unsigned long max)
3669 {
3670         int ret;
3671
3672         mutex_lock(&memcg_max_mutex);
3673
3674         ret = page_counter_set_max(&memcg->tcpmem, max);
3675         if (ret)
3676                 goto out;
3677
3678         if (!memcg->tcpmem_active) {
3679                 /*
3680                  * The active flag needs to be written after the static_key
3681                  * update. This is what guarantees that the socket activation
3682                  * function is the last one to run. See mem_cgroup_sk_alloc()
3683                  * for details, and note that we don't mark any socket as
3684                  * belonging to this memcg until that flag is up.
3685                  *
3686                  * We need to do this, because static_keys will span multiple
3687                  * sites, but we can't control their order. If we mark a socket
3688                  * as accounted, but the accounting functions are not patched in
3689                  * yet, we'll lose accounting.
3690                  *
3691                  * We never race with the readers in mem_cgroup_sk_alloc(),
3692                  * because when this value change, the code to process it is not
3693                  * patched in yet.
3694                  */
3695                 static_branch_inc(&memcg_sockets_enabled_key);
3696                 memcg->tcpmem_active = true;
3697         }
3698 out:
3699         mutex_unlock(&memcg_max_mutex);
3700         return ret;
3701 }
3702
3703 /*
3704  * The user of this function is...
3705  * RES_LIMIT.
3706  */
3707 static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
3708                                 char *buf, size_t nbytes, loff_t off)
3709 {
3710         struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3711         unsigned long nr_pages;
3712         int ret;
3713
3714         buf = strstrip(buf);
3715         ret = page_counter_memparse(buf, "-1", &nr_pages);
3716         if (ret)
3717                 return ret;
3718
3719         switch (MEMFILE_ATTR(of_cft(of)->private)) {
3720         case RES_LIMIT:
3721                 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3722                         ret = -EINVAL;
3723                         break;
3724                 }
3725                 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3726                 case _MEM:
3727                         ret = mem_cgroup_resize_max(memcg, nr_pages, false);
3728                         break;
3729                 case _MEMSWAP:
3730                         ret = mem_cgroup_resize_max(memcg, nr_pages, true);
3731                         break;
3732                 case _KMEM:
3733                         pr_warn_once("kmem.limit_in_bytes is deprecated and will be removed. "
3734                                      "Please report your usecase to linux-mm@kvack.org if you "
3735                                      "depend on this functionality.\n");
3736                         ret = memcg_update_kmem_max(memcg, nr_pages);
3737                         break;
3738                 case _TCP:
3739                         ret = memcg_update_tcp_max(memcg, nr_pages);
3740                         break;
3741                 }
3742                 break;
3743         case RES_SOFT_LIMIT:
3744                 memcg->soft_limit = nr_pages;
3745                 ret = 0;
3746                 break;
3747         }
3748         return ret ?: nbytes;
3749 }
3750
3751 static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
3752                                 size_t nbytes, loff_t off)
3753 {
3754         struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3755         struct page_counter *counter;
3756
3757         switch (MEMFILE_TYPE(of_cft(of)->private)) {
3758         case _MEM:
3759                 counter = &memcg->memory;
3760                 break;
3761         case _MEMSWAP:
3762                 counter = &memcg->memsw;
3763                 break;
3764         case _KMEM:
3765                 counter = &memcg->kmem;
3766                 break;
3767         case _TCP:
3768                 counter = &memcg->tcpmem;
3769                 break;
3770         default:
3771                 BUG();
3772         }
3773
3774         switch (MEMFILE_ATTR(of_cft(of)->private)) {
3775         case RES_MAX_USAGE:
3776                 page_counter_reset_watermark(counter);
3777                 break;
3778         case RES_FAILCNT:
3779                 counter->failcnt = 0;
3780                 break;
3781         default:
3782                 BUG();
3783         }
3784
3785         return nbytes;
3786 }
3787
3788 static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
3789                                         struct cftype *cft)
3790 {
3791         return mem_cgroup_from_css(css)->move_charge_at_immigrate;
3792 }
3793
3794 #ifdef CONFIG_MMU
3795 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
3796                                         struct cftype *cft, u64 val)
3797 {
3798         struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3799
3800         if (val & ~MOVE_MASK)
3801                 return -EINVAL;
3802
3803         /*
3804          * No kind of locking is needed in here, because ->can_attach() will
3805          * check this value once in the beginning of the process, and then carry
3806          * on with stale data. This means that changes to this value will only
3807          * affect task migrations starting after the change.
3808          */
3809         memcg->move_charge_at_immigrate = val;
3810         return 0;
3811 }
3812 #else
3813 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
3814                                         struct cftype *cft, u64 val)
3815 {
3816         return -ENOSYS;
3817 }
3818 #endif
3819
3820 #ifdef CONFIG_NUMA
3821
3822 #define LRU_ALL_FILE (BIT(LRU_INACTIVE_FILE) | BIT(LRU_ACTIVE_FILE))
3823 #define LRU_ALL_ANON (BIT(LRU_INACTIVE_ANON) | BIT(LRU_ACTIVE_ANON))
3824 #define LRU_ALL      ((1 << NR_LRU_LISTS) - 1)
3825
3826 static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
3827                                            int nid, unsigned int lru_mask)
3828 {
3829         struct lruvec *lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
3830         unsigned long nr = 0;
3831         enum lru_list lru;
3832
3833         VM_BUG_ON((unsigned)nid >= nr_node_ids);
3834
3835         for_each_lru(lru) {
3836                 if (!(BIT(lru) & lru_mask))
3837                         continue;
3838                 nr += lruvec_page_state_local(lruvec, NR_LRU_BASE + lru);
3839         }
3840         return nr;
3841 }
3842
3843 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
3844                                              unsigned int lru_mask)
3845 {
3846         unsigned long nr = 0;
3847         enum lru_list lru;
3848
3849         for_each_lru(lru) {
3850                 if (!(BIT(lru) & lru_mask))
3851                         continue;
3852                 nr += memcg_page_state_local(memcg, NR_LRU_BASE + lru);
3853         }
3854         return nr;
3855 }
3856
3857 static int memcg_numa_stat_show(struct seq_file *m, void *v)
3858 {
3859         struct numa_stat {
3860                 const char *name;
3861                 unsigned int lru_mask;
3862         };
3863
3864         static const struct numa_stat stats[] = {
3865                 { "total", LRU_ALL },
3866                 { "file", LRU_ALL_FILE },
3867                 { "anon", LRU_ALL_ANON },
3868                 { "unevictable", BIT(LRU_UNEVICTABLE) },
3869         };
3870         const struct numa_stat *stat;
3871         int nid;
3872         unsigned long nr;
3873         struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
3874
3875         for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
3876                 nr = mem_cgroup_nr_lru_pages(memcg, stat->lru_mask);
3877                 seq_printf(m, "%s=%lu", stat->name, nr);
3878                 for_each_node_state(nid, N_MEMORY) {
3879                         nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
3880                                                           stat->lru_mask);
3881                         seq_printf(m, " N%d=%lu", nid, nr);
3882                 }
3883                 seq_putc(m, '\n');
3884         }
3885
3886         for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
3887                 struct mem_cgroup *iter;
3888
3889                 nr = 0;
3890                 for_each_mem_cgroup_tree(iter, memcg)
3891                         nr += mem_cgroup_nr_lru_pages(iter, stat->lru_mask);
3892                 seq_printf(m, "hierarchical_%s=%lu", stat->name, nr);
3893                 for_each_node_state(nid, N_MEMORY) {
3894                         nr = 0;
3895                         for_each_mem_cgroup_tree(iter, memcg)
3896                                 nr += mem_cgroup_node_nr_lru_pages(
3897                                         iter, nid, stat->lru_mask);
3898                         seq_printf(m, " N%d=%lu", nid, nr);
3899                 }
3900                 seq_putc(m, '\n');
3901         }
3902
3903         return 0;
3904 }
3905 #endif /* CONFIG_NUMA */
3906
3907 static const unsigned int memcg1_stats[] = {
3908         MEMCG_CACHE,
3909         MEMCG_RSS,
3910         MEMCG_RSS_HUGE,
3911         NR_SHMEM,
3912         NR_FILE_MAPPED,
3913         NR_FILE_DIRTY,
3914         NR_WRITEBACK,
3915         MEMCG_SWAP,
3916 };
3917
3918 static const char *const memcg1_stat_names[] = {
3919         "cache",
3920         "rss",
3921         "rss_huge",
3922         "shmem",
3923         "mapped_file",
3924         "dirty",
3925         "writeback",
3926         "swap",
3927 };
3928
3929 /* Universal VM events cgroup1 shows, original sort order */
3930 static const unsigned int memcg1_events[] = {
3931         PGPGIN,
3932         PGPGOUT,
3933         PGFAULT,
3934         PGMAJFAULT,
3935 };
3936
3937 static const char *const memcg1_event_names[] = {
3938         "pgpgin",
3939         "pgpgout",
3940         "pgfault",
3941         "pgmajfault",
3942 };
3943
3944 static int memcg_stat_show(struct seq_file *m, void *v)
3945 {
3946         struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
3947         unsigned long memory, memsw;
3948         struct mem_cgroup *mi;
3949         unsigned int i;
3950
3951         BUILD_BUG_ON(ARRAY_SIZE(memcg1_stat_names) != ARRAY_SIZE(memcg1_stats));
3952         BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_lru_names) != NR_LRU_LISTS);
3953
3954         for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
3955                 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
3956                         continue;
3957                 seq_printf(m, "%s %lu\n", memcg1_stat_names[i],
3958                            memcg_page_state_local(memcg, memcg1_stats[i]) *
3959                            PAGE_SIZE);
3960         }
3961
3962         for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
3963                 seq_printf(m, "%s %lu\n", memcg1_event_names[i],
3964                            memcg_events_local(memcg, memcg1_events[i]));
3965
3966         for (i = 0; i < NR_LRU_LISTS; i++)
3967                 seq_printf(m, "%s %lu\n", mem_cgroup_lru_names[i],
3968                            memcg_page_state_local(memcg, NR_LRU_BASE + i) *
3969                            PAGE_SIZE);
3970
3971         /* Hierarchical information */
3972         memory = memsw = PAGE_COUNTER_MAX;
3973         for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
3974                 memory = min(memory, mi->memory.max);
3975                 memsw = min(memsw, mi->memsw.max);
3976         }
3977         seq_printf(m, "hierarchical_memory_limit %llu\n",
3978                    (u64)memory * PAGE_SIZE);
3979         if (do_memsw_account())
3980                 seq_printf(m, "hierarchical_memsw_limit %llu\n",
3981                            (u64)memsw * PAGE_SIZE);
3982
3983         for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
3984                 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
3985                         continue;
3986                 seq_printf(m, "total_%s %llu\n", memcg1_stat_names[i],
3987                            (u64)memcg_page_state(memcg, memcg1_stats[i]) *
3988                            PAGE_SIZE);
3989         }
3990
3991         for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
3992                 seq_printf(m, "total_%s %llu\n", memcg1_event_names[i],
3993                            (u64)memcg_events(memcg, memcg1_events[i]));
3994
3995         for (i = 0; i < NR_LRU_LISTS; i++)
3996                 seq_printf(m, "total_%s %llu\n", mem_cgroup_lru_names[i],
3997                            (u64)memcg_page_state(memcg, NR_LRU_BASE + i) *
3998                            PAGE_SIZE);
3999
4000 #ifdef CONFIG_DEBUG_VM
4001         {
4002                 pg_data_t *pgdat;
4003                 struct mem_cgroup_per_node *mz;
4004                 struct zone_reclaim_stat *rstat;
4005                 unsigned long recent_rotated[2] = {0, 0};
4006                 unsigned long recent_scanned[2] = {0, 0};
4007
4008                 for_each_online_pgdat(pgdat) {
4009                         mz = mem_cgroup_nodeinfo(memcg, pgdat->node_id);
4010                         rstat = &mz->lruvec.reclaim_stat;
4011
4012                         recent_rotated[0] += rstat->recent_rotated[0];
4013                         recent_rotated[1] += rstat->recent_rotated[1];
4014                         recent_scanned[0] += rstat->recent_scanned[0];
4015                         recent_scanned[1] += rstat->recent_scanned[1];
4016                 }
4017                 seq_printf(m, "recent_rotated_anon %lu\n", recent_rotated[0]);
4018                 seq_printf(m, "recent_rotated_file %lu\n", recent_rotated[1]);
4019                 seq_printf(m, "recent_scanned_anon %lu\n", recent_scanned[0]);
4020                 seq_printf(m, "recent_scanned_file %lu\n", recent_scanned[1]);
4021         }
4022 #endif
4023
4024         return 0;
4025 }
4026
4027 static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
4028                                       struct cftype *cft)
4029 {
4030         struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4031
4032         return mem_cgroup_swappiness(memcg);
4033 }
4034
4035 static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
4036                                        struct cftype *cft, u64 val)
4037 {
4038         struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4039
4040         if (val > 100)
4041                 return -EINVAL;
4042
4043         if (css->parent)
4044                 memcg->swappiness = val;
4045         else
4046                 vm_swappiness = val;
4047
4048         return 0;
4049 }
4050
4051 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4052 {
4053         struct mem_cgroup_threshold_ary *t;
4054         unsigned long usage;
4055         int i;
4056
4057         rcu_read_lock();
4058         if (!swap)
4059                 t = rcu_dereference(memcg->thresholds.primary);
4060         else
4061                 t = rcu_dereference(memcg->memsw_thresholds.primary);
4062
4063         if (!t)
4064                 goto unlock;
4065
4066         usage = mem_cgroup_usage(memcg, swap);
4067
4068         /*
4069          * current_threshold points to threshold just below or equal to usage.
4070          * If it's not true, a threshold was crossed after last
4071          * call of __mem_cgroup_threshold().
4072          */
4073         i = t->current_threshold;
4074
4075         /*
4076          * Iterate backward over array of thresholds starting from
4077          * current_threshold and check if a threshold is crossed.
4078          * If none of thresholds below usage is crossed, we read
4079          * only one element of the array here.
4080          */
4081         for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4082                 eventfd_signal(t->entries[i].eventfd, 1);
4083
4084         /* i = current_threshold + 1 */
4085         i++;
4086
4087         /*
4088          * Iterate forward over array of thresholds starting from
4089          * current_threshold+1 and check if a threshold is crossed.
4090          * If none of thresholds above usage is crossed, we read
4091          * only one element of the array here.
4092          */
4093         for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4094                 eventfd_signal(t->entries[i].eventfd, 1);
4095
4096         /* Update current_threshold */
4097         t->current_threshold = i - 1;
4098 unlock:
4099         rcu_read_unlock();
4100 }
4101
4102 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4103 {
4104         while (memcg) {
4105                 __mem_cgroup_threshold(memcg, false);
4106                 if (do_memsw_account())
4107                         __mem_cgroup_threshold(memcg, true);
4108
4109                 memcg = parent_mem_cgroup(memcg);
4110         }
4111 }
4112
4113 static int compare_thresholds(const void *a, const void *b)
4114 {
4115         const struct mem_cgroup_threshold *_a = a;
4116         const struct mem_cgroup_threshold *_b = b;
4117
4118         if (_a->threshold > _b->threshold)
4119                 return 1;
4120
4121         if (_a->threshold < _b->threshold)
4122                 return -1;
4123
4124         return 0;
4125 }
4126
4127 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
4128 {
4129         struct mem_cgroup_eventfd_list *ev;
4130
4131         spin_lock(&memcg_oom_lock);
4132
4133         list_for_each_entry(ev, &memcg->oom_notify, list)
4134                 eventfd_signal(ev->eventfd, 1);
4135
4136         spin_unlock(&memcg_oom_lock);
4137         return 0;
4138 }
4139
4140 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
4141 {
4142         struct mem_cgroup *iter;
4143
4144         for_each_mem_cgroup_tree(iter, memcg)
4145                 mem_cgroup_oom_notify_cb(iter);
4146 }
4147
4148 static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4149         struct eventfd_ctx *eventfd, const char *args, enum res_type type)
4150 {
4151         struct mem_cgroup_thresholds *thresholds;
4152         struct mem_cgroup_threshold_ary *new;
4153         unsigned long threshold;
4154         unsigned long usage;
4155         int i, size, ret;
4156
4157         ret = page_counter_memparse(args, "-1", &threshold);
4158         if (ret)
4159                 return ret;
4160
4161         mutex_lock(&memcg->thresholds_lock);
4162
4163         if (type == _MEM) {
4164                 thresholds = &memcg->thresholds;
4165                 usage = mem_cgroup_usage(memcg, false);
4166         } else if (type == _MEMSWAP) {
4167                 thresholds = &memcg->memsw_thresholds;
4168                 usage = mem_cgroup_usage(memcg, true);
4169         } else
4170                 BUG();
4171
4172         /* Check if a threshold crossed before adding a new one */
4173         if (thresholds->primary)
4174                 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4175
4176         size = thresholds->primary ? thresholds->primary->size + 1 : 1;
4177
4178         /* Allocate memory for new array of thresholds */
4179         new = kmalloc(struct_size(new, entries, size), GFP_KERNEL);
4180         if (!new) {
4181                 ret = -ENOMEM;
4182                 goto unlock;
4183         }
4184         new->size = size;
4185
4186         /* Copy thresholds (if any) to new array */
4187         if (thresholds->primary) {
4188                 memcpy(new->entries, thresholds->primary->entries, (size - 1) *
4189                                 sizeof(struct mem_cgroup_threshold));
4190         }
4191
4192         /* Add new threshold */
4193         new->entries[size - 1].eventfd = eventfd;
4194         new->entries[size - 1].threshold = threshold;
4195
4196         /* Sort thresholds. Registering of new threshold isn't time-critical */
4197         sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
4198                         compare_thresholds, NULL);
4199
4200         /* Find current threshold */
4201         new->current_threshold = -1;
4202         for (i = 0; i < size; i++) {
4203                 if (new->entries[i].threshold <= usage) {
4204                         /*
4205                          * new->current_threshold will not be used until
4206                          * rcu_assign_pointer(), so it's safe to increment
4207                          * it here.
4208                          */
4209                         ++new->current_threshold;
4210                 } else
4211                         break;
4212         }
4213
4214         /* Free old spare buffer and save old primary buffer as spare */
4215         kfree(thresholds->spare);
4216         thresholds->spare = thresholds->primary;
4217
4218         rcu_assign_pointer(thresholds->primary, new);
4219
4220         /* To be sure that nobody uses thresholds */
4221         synchronize_rcu();
4222
4223 unlock:
4224         mutex_unlock(&memcg->thresholds_lock);
4225
4226         return ret;
4227 }
4228
4229 static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4230         struct eventfd_ctx *eventfd, const char *args)
4231 {
4232         return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
4233 }
4234
4235 static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
4236         struct eventfd_ctx *eventfd, const char *args)
4237 {
4238         return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
4239 }
4240
4241 static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4242         struct eventfd_ctx *eventfd, enum res_type type)
4243 {
4244         struct mem_cgroup_thresholds *thresholds;
4245         struct mem_cgroup_threshold_ary *new;
4246         unsigned long usage;
4247         int i, j, size, entries;
4248
4249         mutex_lock(&memcg->thresholds_lock);
4250
4251         if (type == _MEM) {
4252                 thresholds = &memcg->thresholds;
4253                 usage = mem_cgroup_usage(memcg, false);
4254         } else if (type == _MEMSWAP) {
4255                 thresholds = &memcg->memsw_thresholds;
4256                 usage = mem_cgroup_usage(memcg, true);
4257         } else
4258                 BUG();
4259
4260         if (!thresholds->primary)
4261                 goto unlock;
4262
4263         /* Check if a threshold crossed before removing */
4264         __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4265
4266         /* Calculate new number of threshold */
4267         size = entries = 0;
4268         for (i = 0; i < thresholds->primary->size; i++) {
4269                 if (thresholds->primary->entries[i].eventfd != eventfd)
4270                         size++;
4271                 else
4272                         entries++;
4273         }
4274
4275         new = thresholds->spare;
4276
4277         /* If no items related to eventfd have been cleared, nothing to do */
4278         if (!entries)
4279                 goto unlock;
4280
4281         /* Set thresholds array to NULL if we don't have thresholds */
4282         if (!size) {
4283                 kfree(new);
4284                 new = NULL;
4285                 goto swap_buffers;
4286         }
4287
4288         new->size = size;
4289
4290         /* Copy thresholds and find current threshold */
4291         new->current_threshold = -1;
4292         for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4293                 if (thresholds->primary->entries[i].eventfd == eventfd)
4294                         continue;
4295
4296                 new->entries[j] = thresholds->primary->entries[i];
4297                 if (new->entries[j].threshold <= usage) {
4298                         /*
4299                          * new->current_threshold will not be used
4300                          * until rcu_assign_pointer(), so it's safe to increment
4301                          * it here.
4302                          */
4303                         ++new->current_threshold;
4304                 }
4305                 j++;
4306         }
4307
4308 swap_buffers:
4309         /* Swap primary and spare array */
4310         thresholds->spare = thresholds->primary;
4311
4312         rcu_assign_pointer(thresholds->primary, new);
4313
4314         /* To be sure that nobody uses thresholds */
4315         synchronize_rcu();
4316
4317         /* If all events are unregistered, free the spare array */
4318         if (!new) {
4319                 kfree(thresholds->spare);
4320                 thresholds->spare = NULL;
4321         }
4322 unlock:
4323         mutex_unlock(&memcg->thresholds_lock);
4324 }
4325
4326 static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4327         struct eventfd_ctx *eventfd)
4328 {
4329         return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
4330 }
4331
4332 static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4333         struct eventfd_ctx *eventfd)
4334 {
4335         return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
4336 }
4337
4338 static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
4339         struct eventfd_ctx *eventfd, const char *args)
4340 {
4341         struct mem_cgroup_eventfd_list *event;
4342
4343         event = kmalloc(sizeof(*event), GFP_KERNEL);
4344         if (!event)
4345                 return -ENOMEM;
4346
4347         spin_lock(&memcg_oom_lock);
4348
4349         event->eventfd = eventfd;
4350         list_add(&event->list, &memcg->oom_notify);
4351
4352         /* already in OOM ? */
4353         if (memcg->under_oom)
4354                 eventfd_signal(eventfd, 1);
4355         spin_unlock(&memcg_oom_lock);
4356
4357         return 0;
4358 }
4359
4360 static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
4361         struct eventfd_ctx *eventfd)
4362 {
4363         struct mem_cgroup_eventfd_list *ev, *tmp;
4364
4365         spin_lock(&memcg_oom_lock);
4366
4367         list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
4368                 if (ev->eventfd == eventfd) {
4369                         list_del(&ev->list);
4370                         kfree(ev);
4371                 }
4372         }
4373
4374         spin_unlock(&memcg_oom_lock);
4375 }
4376
4377 static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
4378 {
4379         struct mem_cgroup *memcg = mem_cgroup_from_seq(sf);
4380
4381         seq_printf(sf, "oom_kill_disable %d\n", memcg->oom_kill_disable);
4382         seq_printf(sf, "under_oom %d\n", (bool)memcg->under_oom);
4383         seq_printf(sf, "oom_kill %lu\n",
4384                    atomic_long_read(&memcg->memory_events[MEMCG_OOM_KILL]));
4385         return 0;
4386 }
4387
4388 static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
4389         struct cftype *cft, u64 val)
4390 {
4391         struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4392
4393         /* cannot set to root cgroup and only 0 and 1 are allowed */
4394         if (!css->parent || !((val == 0) || (val == 1)))
4395                 return -EINVAL;
4396
4397         memcg->oom_kill_disable = val;
4398         if (!val)
4399                 memcg_oom_recover(memcg);
4400
4401         return 0;
4402 }
4403
4404 #ifdef CONFIG_CGROUP_WRITEBACK
4405
4406 #include <trace/events/writeback.h>
4407
4408 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4409 {
4410         return wb_domain_init(&memcg->cgwb_domain, gfp);
4411 }
4412
4413 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4414 {
4415         wb_domain_exit(&memcg->cgwb_domain);
4416 }
4417
4418 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4419 {
4420         wb_domain_size_changed(&memcg->cgwb_domain);
4421 }
4422
4423 struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb)
4424 {
4425         struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4426
4427         if (!memcg->css.parent)
4428                 return NULL;
4429
4430         return &memcg->cgwb_domain;
4431 }
4432
4433 /*
4434  * idx can be of type enum memcg_stat_item or node_stat_item.
4435  * Keep in sync with memcg_exact_page().
4436  */
4437 static unsigned long memcg_exact_page_state(struct mem_cgroup *memcg, int idx)
4438 {
4439         long x = atomic_long_read(&memcg->vmstats[idx]);
4440         int cpu;
4441
4442         for_each_online_cpu(cpu)
4443                 x += per_cpu_ptr(memcg->vmstats_percpu, cpu)->stat[idx];
4444         if (x < 0)
4445                 x = 0;
4446         return x;
4447 }
4448
4449 /**
4450  * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
4451  * @wb: bdi_writeback in question
4452  * @pfilepages: out parameter for number of file pages
4453  * @pheadroom: out parameter for number of allocatable pages according to memcg
4454  * @pdirty: out parameter for number of dirty pages
4455  * @pwriteback: out parameter for number of pages under writeback
4456  *
4457  * Determine the numbers of file, headroom, dirty, and writeback pages in
4458  * @wb's memcg.  File, dirty and writeback are self-explanatory.  Headroom
4459  * is a bit more involved.
4460  *
4461  * A memcg's headroom is "min(max, high) - used".  In the hierarchy, the
4462  * headroom is calculated as the lowest headroom of itself and the
4463  * ancestors.  Note that this doesn't consider the actual amount of
4464  * available memory in the system.  The caller should further cap
4465  * *@pheadroom accordingly.
4466  */
4467 void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages,
4468                          unsigned long *pheadroom, unsigned long *pdirty,
4469                          unsigned long *pwriteback)
4470 {
4471         struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4472         struct mem_cgroup *parent;
4473
4474         *pdirty = memcg_exact_page_state(memcg, NR_FILE_DIRTY);
4475
4476         /* this should eventually include NR_UNSTABLE_NFS */
4477         *pwriteback = memcg_exact_page_state(memcg, NR_WRITEBACK);
4478         *pfilepages = memcg_exact_page_state(memcg, NR_INACTIVE_FILE) +
4479                         memcg_exact_page_state(memcg, NR_ACTIVE_FILE);
4480         *pheadroom = PAGE_COUNTER_MAX;
4481
4482         while ((parent = parent_mem_cgroup(memcg))) {
4483                 unsigned long ceiling = min(memcg->memory.max, memcg->high);
4484                 unsigned long used = page_counter_read(&memcg->memory);
4485
4486                 *pheadroom = min(*pheadroom, ceiling - min(ceiling, used));
4487                 memcg = parent;
4488         }
4489 }
4490
4491 /*
4492  * Foreign dirty flushing
4493  *
4494  * There's an inherent mismatch between memcg and writeback.  The former
4495  * trackes ownership per-page while the latter per-inode.  This was a
4496  * deliberate design decision because honoring per-page ownership in the
4497  * writeback path is complicated, may lead to higher CPU and IO overheads
4498  * and deemed unnecessary given that write-sharing an inode across
4499  * different cgroups isn't a common use-case.
4500  *
4501  * Combined with inode majority-writer ownership switching, this works well
4502  * enough in most cases but there are some pathological cases.  For
4503  * example, let's say there are two cgroups A and B which keep writing to
4504  * different but confined parts of the same inode.  B owns the inode and
4505  * A's memory is limited far below B's.  A's dirty ratio can rise enough to
4506  * trigger balance_dirty_pages() sleeps but B's can be low enough to avoid
4507  * triggering background writeback.  A will be slowed down without a way to
4508  * make writeback of the dirty pages happen.
4509  *
4510  * Conditions like the above can lead to a cgroup getting repatedly and
4511  * severely throttled after making some progress after each
4512  * dirty_expire_interval while the underyling IO device is almost
4513  * completely idle.
4514  *
4515  * Solving this problem completely requires matching the ownership tracking
4516  * granularities between memcg and writeback in either direction.  However,
4517  * the more egregious behaviors can be avoided by simply remembering the
4518  * most recent foreign dirtying events and initiating remote flushes on
4519  * them when local writeback isn't enough to keep the memory clean enough.
4520  *
4521  * The following two functions implement such mechanism.  When a foreign
4522  * page - a page whose memcg and writeback ownerships don't match - is
4523  * dirtied, mem_cgroup_track_foreign_dirty() records the inode owning
4524  * bdi_writeback on the page owning memcg.  When balance_dirty_pages()
4525  * decides that the memcg needs to sleep due to high dirty ratio, it calls
4526  * mem_cgroup_flush_foreign() which queues writeback on the recorded
4527  * foreign bdi_writebacks which haven't expired.  Both the numbers of
4528  * recorded bdi_writebacks and concurrent in-flight foreign writebacks are
4529  * limited to MEMCG_CGWB_FRN_CNT.
4530  *
4531  * The mechanism only remembers IDs and doesn't hold any object references.
4532  * As being wrong occasionally doesn't matter, updates and accesses to the
4533  * records are lockless and racy.
4534  */
4535 void mem_cgroup_track_foreign_dirty_slowpath(struct page *page,
4536                                              struct bdi_writeback *wb)
4537 {
4538         struct mem_cgroup *memcg = page->mem_cgroup;
4539         struct memcg_cgwb_frn *frn;
4540         u64 now = get_jiffies_64();
4541         u64 oldest_at = now;
4542         int oldest = -1;
4543         int i;
4544
4545         trace_track_foreign_dirty(page, wb);
4546
4547         /*
4548          * Pick the slot to use.  If there is already a slot for @wb, keep
4549          * using it.  If not replace the oldest one which isn't being
4550          * written out.
4551          */
4552         for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4553                 frn = &memcg->cgwb_frn[i];
4554                 if (frn->bdi_id == wb->bdi->id &&
4555                     frn->memcg_id == wb->memcg_css->id)
4556                         break;
4557                 if (time_before64(frn->at, oldest_at) &&
4558                     atomic_read(&frn->done.cnt) == 1) {
4559                         oldest = i;
4560                         oldest_at = frn->at;
4561                 }
4562         }
4563
4564         if (i < MEMCG_CGWB_FRN_CNT) {
4565                 /*
4566                  * Re-using an existing one.  Update timestamp lazily to
4567                  * avoid making the cacheline hot.  We want them to be
4568                  * reasonably up-to-date and significantly shorter than
4569                  * dirty_expire_interval as that's what expires the record.
4570                  * Use the shorter of 1s and dirty_expire_interval / 8.
4571                  */
4572                 unsigned long update_intv =
4573                         min_t(unsigned long, HZ,
4574                               msecs_to_jiffies(dirty_expire_interval * 10) / 8);
4575
4576                 if (time_before64(frn->at, now - update_intv))
4577                         frn->at = now;
4578         } else if (oldest >= 0) {
4579                 /* replace the oldest free one */
4580                 frn = &memcg->cgwb_frn[oldest];
4581                 frn->bdi_id = wb->bdi->id;
4582                 frn->memcg_id = wb->memcg_css->id;
4583                 frn->at = now;
4584         }
4585 }
4586
4587 /* issue foreign writeback flushes for recorded foreign dirtying events */
4588 void mem_cgroup_flush_foreign(struct bdi_writeback *wb)
4589 {
4590         struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4591         unsigned long intv = msecs_to_jiffies(dirty_expire_interval * 10);
4592         u64 now = jiffies_64;
4593         int i;
4594
4595         for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4596                 struct memcg_cgwb_frn *frn = &memcg->cgwb_frn[i];
4597
4598                 /*
4599                  * If the record is older than dirty_expire_interval,
4600                  * writeback on it has already started.  No need to kick it
4601                  * off again.  Also, don't start a new one if there's
4602                  * already one in flight.
4603                  */
4604                 if (time_after64(frn->at, now - intv) &&
4605                     atomic_read(&frn->done.cnt) == 1) {
4606                         frn->at = 0;
4607                         trace_flush_foreign(wb, frn->bdi_id, frn->memcg_id);
4608                         cgroup_writeback_by_id(frn->bdi_id, frn->memcg_id, 0,
4609                                                WB_REASON_FOREIGN_FLUSH,
4610                                                &frn->done);
4611                 }
4612         }
4613 }
4614
4615 #else   /* CONFIG_CGROUP_WRITEBACK */
4616
4617 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4618 {
4619         return 0;
4620 }
4621
4622 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4623 {
4624 }
4625
4626 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4627 {
4628 }
4629
4630 #endif  /* CONFIG_CGROUP_WRITEBACK */
4631
4632 /*
4633  * DO NOT USE IN NEW FILES.
4634  *
4635  * "cgroup.event_control" implementation.
4636  *
4637  * This is way over-engineered.  It tries to support fully configurable
4638  * events for each user.  Such level of flexibility is completely
4639  * unnecessary especially in the light of the planned unified hierarchy.
4640  *
4641  * Please deprecate this and replace with something simpler if at all
4642  * possible.
4643  */
4644
4645 /*
4646  * Unregister event and free resources.
4647  *
4648  * Gets called from workqueue.
4649  */
4650 static void memcg_event_remove(struct work_struct *work)
4651 {
4652         struct mem_cgroup_event *event =
4653                 container_of(work, struct mem_cgroup_event, remove);
4654         struct mem_cgroup *memcg = event->memcg;
4655
4656         remove_wait_queue(event->wqh, &event->wait);
4657
4658         event->unregister_event(memcg, event->eventfd);
4659
4660         /* Notify userspace the event is going away. */
4661         eventfd_signal(event->eventfd, 1);
4662
4663         eventfd_ctx_put(event->eventfd);
4664         kfree(event);
4665         css_put(&memcg->css);
4666 }
4667
4668 /*
4669  * Gets called on EPOLLHUP on eventfd when user closes it.
4670  *
4671  * Called with wqh->lock held and interrupts disabled.
4672  */
4673 static int memcg_event_wake(wait_queue_entry_t *wait, unsigned mode,
4674                             int sync, void *key)
4675 {
4676         struct mem_cgroup_event *event =
4677                 container_of(wait, struct mem_cgroup_event, wait);
4678         struct mem_cgroup *memcg = event->memcg;
4679         __poll_t flags = key_to_poll(key);
4680
4681         if (flags & EPOLLHUP) {
4682                 /*
4683                  * If the event has been detached at cgroup removal, we
4684                  * can simply return knowing the other side will cleanup
4685                  * for us.
4686                  *
4687                  * We can't race against event freeing since the other
4688                  * side will require wqh->lock via remove_wait_queue(),
4689                  * which we hold.
4690                  */
4691                 spin_lock(&memcg->event_list_lock);
4692                 if (!list_empty(&event->list)) {
4693                         list_del_init(&event->list);
4694                         /*
4695                          * We are in atomic context, but cgroup_event_remove()
4696                          * may sleep, so we have to call it in workqueue.
4697                          */
4698                         schedule_work(&event->remove);
4699                 }
4700                 spin_unlock(&memcg->event_list_lock);
4701         }
4702
4703         return 0;
4704 }
4705
4706 static void memcg_event_ptable_queue_proc(struct file *file,
4707                 wait_queue_head_t *wqh, poll_table *pt)
4708 {
4709         struct mem_cgroup_event *event =
4710                 container_of(pt, struct mem_cgroup_event, pt);
4711
4712         event->wqh = wqh;
4713         add_wait_queue(wqh, &event->wait);
4714 }
4715
4716 /*
4717  * DO NOT USE IN NEW FILES.
4718  *
4719  * Parse input and register new cgroup event handler.
4720  *
4721  * Input must be in format '<event_fd> <control_fd> <args>'.
4722  * Interpretation of args is defined by control file implementation.
4723  */
4724 static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
4725                                          char *buf, size_t nbytes, loff_t off)
4726 {
4727         struct cgroup_subsys_state *css = of_css(of);
4728         struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4729         struct mem_cgroup_event *event;
4730         struct cgroup_subsys_state *cfile_css;
4731         unsigned int efd, cfd;
4732         struct fd efile;
4733         struct fd cfile;
4734         const char *name;
4735         char *endp;
4736         int ret;
4737
4738         buf = strstrip(buf);
4739
4740         efd = simple_strtoul(buf, &endp, 10);
4741         if (*endp != ' ')
4742                 return -EINVAL;
4743         buf = endp + 1;
4744
4745         cfd = simple_strtoul(buf, &endp, 10);
4746         if ((*endp != ' ') && (*endp != '\0'))
4747                 return -EINVAL;
4748         buf = endp + 1;
4749
4750         event = kzalloc(sizeof(*event), GFP_KERNEL);
4751         if (!event)
4752                 return -ENOMEM;
4753
4754         event->memcg = memcg;
4755         INIT_LIST_HEAD(&event->list);
4756         init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
4757         init_waitqueue_func_entry(&event->wait, memcg_event_wake);
4758         INIT_WORK(&event->remove, memcg_event_remove);
4759
4760         efile = fdget(efd);
4761         if (!efile.file) {
4762                 ret = -EBADF;
4763                 goto out_kfree;
4764         }
4765
4766         event->eventfd = eventfd_ctx_fileget(efile.file);
4767         if (IS_ERR(event->eventfd)) {
4768                 ret = PTR_ERR(event->eventfd);
4769                 goto out_put_efile;
4770         }
4771
4772         cfile = fdget(cfd);
4773         if (!cfile.file) {
4774                 ret = -EBADF;
4775                 goto out_put_eventfd;
4776         }
4777
4778         /* the process need read permission on control file */
4779         /* AV: shouldn't we check that it's been opened for read instead? */
4780         ret = inode_permission(file_inode(cfile.file), MAY_READ);
4781         if (ret < 0)
4782                 goto out_put_cfile;
4783
4784         /*
4785          * Determine the event callbacks and set them in @event.  This used
4786          * to be done via struct cftype but cgroup core no longer knows
4787          * about these events.  The following is crude but the whole thing
4788          * is for compatibility anyway.
4789          *
4790          * DO NOT ADD NEW FILES.
4791          */
4792         name = cfile.file->f_path.dentry->d_name.name;
4793
4794         if (!strcmp(name, "memory.usage_in_bytes")) {
4795                 event->register_event = mem_cgroup_usage_register_event;
4796                 event->unregister_event = mem_cgroup_usage_unregister_event;
4797         } else if (!strcmp(name, "memory.oom_control")) {
4798                 event->register_event = mem_cgroup_oom_register_event;
4799                 event->unregister_event = mem_cgroup_oom_unregister_event;
4800         } else if (!strcmp(name, "memory.pressure_level")) {
4801                 event->register_event = vmpressure_register_event;
4802                 event->unregister_event = vmpressure_unregister_event;
4803         } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
4804                 event->register_event = memsw_cgroup_usage_register_event;
4805                 event->unregister_event = memsw_cgroup_usage_unregister_event;
4806         } else {
4807                 ret = -EINVAL;
4808                 goto out_put_cfile;
4809         }
4810
4811         /*
4812          * Verify @cfile should belong to @css.  Also, remaining events are
4813          * automatically removed on cgroup destruction but the removal is
4814          * asynchronous, so take an extra ref on @css.
4815          */
4816         cfile_css = css_tryget_online_from_dir(cfile.file->f_path.dentry->d_parent,
4817                                                &memory_cgrp_subsys);
4818         ret = -EINVAL;
4819         if (IS_ERR(cfile_css))
4820                 goto out_put_cfile;
4821         if (cfile_css != css) {
4822                 css_put(cfile_css);
4823                 goto out_put_cfile;
4824         }
4825
4826         ret = event->register_event(memcg, event->eventfd, buf);
4827         if (ret)
4828                 goto out_put_css;
4829
4830         vfs_poll(efile.file, &event->pt);
4831
4832         spin_lock(&memcg->event_list_lock);
4833         list_add(&event->list, &memcg->event_list);
4834         spin_unlock(&memcg->event_list_lock);
4835
4836         fdput(cfile);
4837         fdput(efile);
4838
4839         return nbytes;
4840
4841 out_put_css:
4842         css_put(css);
4843 out_put_cfile:
4844         fdput(cfile);
4845 out_put_eventfd:
4846         eventfd_ctx_put(event->eventfd);
4847 out_put_efile:
4848         fdput(efile);
4849 out_kfree:
4850         kfree(event);
4851
4852         return ret;
4853 }
4854
4855 static struct cftype mem_cgroup_legacy_files[] = {
4856         {
4857                 .name = "usage_in_bytes",
4858                 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
4859                 .read_u64 = mem_cgroup_read_u64,
4860         },
4861         {
4862                 .name = "max_usage_in_bytes",
4863                 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
4864                 .write = mem_cgroup_reset,
4865                 .read_u64 = mem_cgroup_read_u64,
4866         },
4867         {
4868                 .name = "limit_in_bytes",
4869                 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
4870                 .write = mem_cgroup_write,
4871                 .read_u64 = mem_cgroup_read_u64,
4872         },
4873         {
4874                 .name = "soft_limit_in_bytes",
4875                 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
4876                 .write = mem_cgroup_write,
4877                 .read_u64 = mem_cgroup_read_u64,
4878         },
4879         {
4880                 .name = "failcnt",
4881                 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
4882                 .write = mem_cgroup_reset,
4883                 .read_u64 = mem_cgroup_read_u64,
4884         },
4885         {
4886                 .name = "stat",
4887                 .seq_show = memcg_stat_show,
4888         },
4889         {
4890                 .name = "force_empty",
4891                 .write = mem_cgroup_force_empty_write,
4892         },
4893         {
4894                 .name = "use_hierarchy",
4895                 .write_u64 = mem_cgroup_hierarchy_write,
4896                 .read_u64 = mem_cgroup_hierarchy_read,
4897         },
4898         {
4899                 .name = "cgroup.event_control",         /* XXX: for compat */
4900                 .write = memcg_write_event_control,
4901                 .flags = CFTYPE_NO_PREFIX | CFTYPE_WORLD_WRITABLE,
4902         },
4903         {
4904                 .name = "swappiness",
4905                 .read_u64 = mem_cgroup_swappiness_read,
4906                 .write_u64 = mem_cgroup_swappiness_write,
4907         },
4908         {
4909                 .name = "move_charge_at_immigrate",
4910                 .read_u64 = mem_cgroup_move_charge_read,
4911                 .write_u64 = mem_cgroup_move_charge_write,
4912         },
4913         {
4914                 .name = "oom_control",
4915                 .seq_show = mem_cgroup_oom_control_read,
4916                 .write_u64 = mem_cgroup_oom_control_write,
4917                 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
4918         },
4919         {
4920                 .name = "pressure_level",
4921         },
4922 #ifdef CONFIG_NUMA
4923         {
4924                 .name = "numa_stat",
4925                 .seq_show = memcg_numa_stat_show,
4926         },
4927 #endif
4928         {
4929                 .name = "kmem.limit_in_bytes",
4930                 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
4931                 .write = mem_cgroup_write,
4932                 .read_u64 = mem_cgroup_read_u64,
4933         },
4934         {
4935                 .name = "kmem.usage_in_bytes",
4936                 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
4937                 .read_u64 = mem_cgroup_read_u64,
4938         },
4939         {
4940                 .name = "kmem.failcnt",
4941                 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
4942                 .write = mem_cgroup_reset,
4943                 .read_u64 = mem_cgroup_read_u64,
4944         },
4945         {
4946                 .name = "kmem.max_usage_in_bytes",
4947                 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
4948                 .write = mem_cgroup_reset,
4949                 .read_u64 = mem_cgroup_read_u64,
4950         },
4951 #if defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG)
4952         {
4953                 .name = "kmem.slabinfo",
4954                 .seq_start = memcg_slab_start,
4955                 .seq_next = memcg_slab_next,
4956                 .seq_stop = memcg_slab_stop,
4957                 .seq_show = memcg_slab_show,
4958         },
4959 #endif
4960         {
4961                 .name = "kmem.tcp.limit_in_bytes",
4962                 .private = MEMFILE_PRIVATE(_TCP, RES_LIMIT),
4963                 .write = mem_cgroup_write,
4964                 .read_u64 = mem_cgroup_read_u64,
4965         },
4966         {
4967                 .name = "kmem.tcp.usage_in_bytes",
4968                 .private = MEMFILE_PRIVATE(_TCP, RES_USAGE),
4969                 .read_u64 = mem_cgroup_read_u64,
4970         },
4971         {
4972                 .name = "kmem.tcp.failcnt",
4973                 .private = MEMFILE_PRIVATE(_TCP, RES_FAILCNT),
4974                 .write = mem_cgroup_reset,
4975                 .read_u64 = mem_cgroup_read_u64,
4976         },
4977         {
4978                 .name = "kmem.tcp.max_usage_in_bytes",
4979                 .private = MEMFILE_PRIVATE(_TCP, RES_MAX_USAGE),
4980                 .write = mem_cgroup_reset,
4981                 .read_u64 = mem_cgroup_read_u64,
4982         },
4983         { },    /* terminate */
4984 };
4985
4986 /*
4987  * Private memory cgroup IDR
4988  *
4989  * Swap-out records and page cache shadow entries need to store memcg
4990  * references in constrained space, so we maintain an ID space that is
4991  * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of
4992  * memory-controlled cgroups to 64k.
4993  *
4994  * However, there usually are many references to the oflline CSS after
4995  * the cgroup has been destroyed, such as page cache or reclaimable
4996  * slab objects, that don't need to hang on to the ID. We want to keep
4997  * those dead CSS from occupying IDs, or we might quickly exhaust the
4998  * relatively small ID space and prevent the creation of new cgroups
4999  * even when there are much fewer than 64k cgroups - possibly none.
5000  *
5001  * Maintain a private 16-bit ID space for memcg, and allow the ID to
5002  * be freed and recycled when it's no longer needed, which is usually
5003  * when the CSS is offlined.
5004  *
5005  * The only exception to that are records of swapped out tmpfs/shmem
5006  * pages that need to be attributed to live ancestors on swapin. But
5007  * those references are manageable from userspace.
5008  */
5009
5010 static DEFINE_IDR(mem_cgroup_idr);
5011
5012 static void mem_cgroup_id_remove(struct mem_cgroup *memcg)
5013 {
5014         if (memcg->id.id > 0) {
5015                 idr_remove(&mem_cgroup_idr, memcg->id.id);
5016                 memcg->id.id = 0;
5017         }
5018 }
5019
5020 static void mem_cgroup_id_get_many(struct mem_cgroup *memcg, unsigned int n)
5021 {
5022         refcount_add(n, &memcg->id.ref);
5023 }
5024
5025 static void mem_cgroup_id_put_many(struct mem_cgroup *memcg, unsigned int n)
5026 {
5027         if (refcount_sub_and_test(n, &memcg->id.ref)) {
5028                 mem_cgroup_id_remove(memcg);
5029
5030                 /* Memcg ID pins CSS */
5031                 css_put(&memcg->css);
5032         }
5033 }
5034
5035 static inline void mem_cgroup_id_put(struct mem_cgroup *memcg)
5036 {
5037         mem_cgroup_id_put_many(memcg, 1);
5038 }
5039
5040 /**
5041  * mem_cgroup_from_id - look up a memcg from a memcg id
5042  * @id: the memcg id to look up
5043  *
5044  * Caller must hold rcu_read_lock().
5045  */
5046 struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
5047 {
5048         WARN_ON_ONCE(!rcu_read_lock_held());
5049         return idr_find(&mem_cgroup_idr, id);
5050 }
5051
5052 static int alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5053 {
5054         struct mem_cgroup_per_node *pn;
5055         int tmp = node;
5056         /*
5057          * This routine is called against possible nodes.
5058          * But it's BUG to call kmalloc() against offline node.
5059          *
5060          * TODO: this routine can waste much memory for nodes which will
5061          *       never be onlined. It's better to use memory hotplug callback
5062          *       function.
5063          */
5064         if (!node_state(node, N_NORMAL_MEMORY))
5065                 tmp = -1;
5066         pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
5067         if (!pn)
5068                 return 1;
5069
5070         pn->lruvec_stat_local = alloc_percpu(struct lruvec_stat);
5071         if (!pn->lruvec_stat_local) {
5072                 kfree(pn);
5073                 return 1;
5074         }
5075
5076         pn->lruvec_stat_cpu = alloc_percpu(struct lruvec_stat);
5077         if (!pn->lruvec_stat_cpu) {
5078                 free_percpu(pn->lruvec_stat_local);
5079                 kfree(pn);
5080                 return 1;
5081         }
5082
5083         lruvec_init(&pn->lruvec);
5084         pn->usage_in_excess = 0;
5085         pn->on_tree = false;
5086         pn->memcg = memcg;
5087
5088         memcg->nodeinfo[node] = pn;
5089         return 0;
5090 }
5091
5092 static void free_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
5093 {
5094         struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
5095
5096         if (!pn)
5097                 return;
5098
5099         free_percpu(pn->lruvec_stat_cpu);
5100         free_percpu(pn->lruvec_stat_local);
5101         kfree(pn);
5102 }
5103
5104 static void __mem_cgroup_free(struct mem_cgroup *memcg)
5105 {
5106         int node;
5107
5108         for_each_node(node)
5109                 free_mem_cgroup_per_node_info(memcg, node);
5110         free_percpu(memcg->vmstats_percpu);
5111         free_percpu(memcg->vmstats_local);
5112         kfree(memcg);
5113 }
5114
5115 static void mem_cgroup_free(struct mem_cgroup *memcg)
5116 {
5117         memcg_wb_domain_exit(memcg);
5118         /*
5119          * Flush percpu vmstats and vmevents to guarantee the value correctness
5120          * on parent's and all ancestor levels.
5121          */
5122         memcg_flush_percpu_vmstats(memcg);
5123         memcg_flush_percpu_vmevents(memcg);
5124         __mem_cgroup_free(memcg);
5125 }
5126
5127 static struct mem_cgroup *mem_cgroup_alloc(void)
5128 {
5129         struct mem_cgroup *memcg;
5130         unsigned int size;
5131         int node;
5132         int __maybe_unused i;
5133         long error = -ENOMEM;
5134
5135         size = sizeof(struct mem_cgroup);
5136         size += nr_node_ids * sizeof(struct mem_cgroup_per_node *);
5137
5138         memcg = kzalloc(size, GFP_KERNEL);
5139         if (!memcg)
5140                 return ERR_PTR(error);
5141
5142         memcg->id.id = idr_alloc(&mem_cgroup_idr, NULL,
5143                                  1, MEM_CGROUP_ID_MAX,
5144                                  GFP_KERNEL);
5145         if (memcg->id.id < 0) {
5146                 error = memcg->id.id;
5147                 goto fail;
5148         }
5149
5150         memcg->vmstats_local = alloc_percpu(struct memcg_vmstats_percpu);
5151         if (!memcg->vmstats_local)
5152                 goto fail;
5153
5154         memcg->vmstats_percpu = alloc_percpu(struct memcg_vmstats_percpu);
5155         if (!memcg->vmstats_percpu)
5156                 goto fail;
5157
5158         for_each_node(node)
5159                 if (alloc_mem_cgroup_per_node_info(memcg, node))
5160                         goto fail;
5161
5162         if (memcg_wb_domain_init(memcg, GFP_KERNEL))
5163                 goto fail;
5164
5165         INIT_WORK(&memcg->high_work, high_work_func);
5166         memcg->last_scanned_node = MAX_NUMNODES;
5167         INIT_LIST_HEAD(&memcg->oom_notify);
5168         mutex_init(&memcg->thresholds_lock);
5169         spin_lock_init(&memcg->move_lock);
5170         vmpressure_init(&memcg->vmpressure);
5171         INIT_LIST_HEAD(&memcg->event_list);
5172         spin_lock_init(&memcg->event_list_lock);
5173         memcg->socket_pressure = jiffies;
5174 #ifdef CONFIG_MEMCG_KMEM
5175         memcg->kmemcg_id = -1;
5176 #endif
5177 #ifdef CONFIG_CGROUP_WRITEBACK
5178         INIT_LIST_HEAD(&memcg->cgwb_list);
5179         for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5180                 memcg->cgwb_frn[i].done =
5181                         __WB_COMPLETION_INIT(&memcg_cgwb_frn_waitq);
5182 #endif
5183 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5184         spin_lock_init(&memcg->deferred_split_queue.split_queue_lock);
5185         INIT_LIST_HEAD(&memcg->deferred_split_queue.split_queue);
5186         memcg->deferred_split_queue.split_queue_len = 0;
5187 #endif
5188         idr_replace(&mem_cgroup_idr, memcg, memcg->id.id);
5189         return memcg;
5190 fail:
5191         mem_cgroup_id_remove(memcg);
5192         __mem_cgroup_free(memcg);
5193         return ERR_PTR(error);
5194 }
5195
5196 static struct cgroup_subsys_state * __ref
5197 mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
5198 {
5199         struct mem_cgroup *parent = mem_cgroup_from_css(parent_css);
5200         struct mem_cgroup *memcg;
5201         long error = -ENOMEM;
5202
5203         memcg = mem_cgroup_alloc();
5204         if (IS_ERR(memcg))
5205                 return ERR_CAST(memcg);
5206
5207         memcg->high = PAGE_COUNTER_MAX;
5208         memcg->soft_limit = PAGE_COUNTER_MAX;
5209         if (parent) {
5210                 memcg->swappiness = mem_cgroup_swappiness(parent);
5211                 memcg->oom_kill_disable = parent->oom_kill_disable;
5212         }
5213         if (parent && parent->use_hierarchy) {
5214                 memcg->use_hierarchy = true;
5215                 page_counter_init(&memcg->memory, &parent->memory);
5216                 page_counter_init(&memcg->swap, &parent->swap);
5217                 page_counter_init(&memcg->memsw, &parent->memsw);
5218                 page_counter_init(&memcg->kmem, &parent->kmem);
5219                 page_counter_init(&memcg->tcpmem, &parent->tcpmem);
5220         } else {
5221                 page_counter_init(&memcg->memory, NULL);
5222                 page_counter_init(&memcg->swap, NULL);
5223                 page_counter_init(&memcg->memsw, NULL);
5224                 page_counter_init(&memcg->kmem, NULL);
5225                 page_counter_init(&memcg->tcpmem, NULL);
5226                 /*
5227                  * Deeper hierachy with use_hierarchy == false doesn't make
5228                  * much sense so let cgroup subsystem know about this
5229                  * unfortunate state in our controller.
5230                  */
5231                 if (parent != root_mem_cgroup)
5232                         memory_cgrp_subsys.broken_hierarchy = true;
5233         }
5234
5235         /* The following stuff does not apply to the root */
5236         if (!parent) {
5237 #ifdef CONFIG_MEMCG_KMEM
5238                 INIT_LIST_HEAD(&memcg->kmem_caches);
5239 #endif
5240                 root_mem_cgroup = memcg;
5241                 return &memcg->css;
5242         }
5243
5244         error = memcg_online_kmem(memcg);
5245         if (error)
5246                 goto fail;
5247
5248         if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5249                 static_branch_inc(&memcg_sockets_enabled_key);
5250
5251         return &memcg->css;
5252 fail:
5253         mem_cgroup_id_remove(memcg);
5254         mem_cgroup_free(memcg);
5255         return ERR_PTR(error);
5256 }
5257
5258 static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
5259 {
5260         struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5261
5262         /*
5263          * A memcg must be visible for memcg_expand_shrinker_maps()
5264          * by the time the maps are allocated. So, we allocate maps
5265          * here, when for_each_mem_cgroup() can't skip it.
5266          */
5267         if (memcg_alloc_shrinker_maps(memcg)) {
5268                 mem_cgroup_id_remove(memcg);
5269                 return -ENOMEM;
5270         }
5271
5272         /* Online state pins memcg ID, memcg ID pins CSS */
5273         refcount_set(&memcg->id.ref, 1);
5274         css_get(css);
5275         return 0;
5276 }
5277
5278 static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
5279 {
5280         struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5281         struct mem_cgroup_event *event, *tmp;
5282
5283         /*
5284          * Unregister events and notify userspace.
5285          * Notify userspace about cgroup removing only after rmdir of cgroup
5286          * directory to avoid race between userspace and kernelspace.
5287          */
5288         spin_lock(&memcg->event_list_lock);
5289         list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
5290                 list_del_init(&event->list);
5291                 schedule_work(&event->remove);
5292         }
5293         spin_unlock(&memcg->event_list_lock);
5294
5295         page_counter_set_min(&memcg->memory, 0);
5296         page_counter_set_low(&memcg->memory, 0);
5297
5298         memcg_offline_kmem(memcg);
5299         wb_memcg_offline(memcg);
5300
5301         drain_all_stock(memcg);
5302
5303         mem_cgroup_id_put(memcg);
5304 }
5305
5306 static void mem_cgroup_css_released(struct cgroup_subsys_state *css)
5307 {
5308         struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5309
5310         invalidate_reclaim_iterators(memcg);
5311 }
5312
5313 static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
5314 {
5315         struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5316         int __maybe_unused i;
5317
5318 #ifdef CONFIG_CGROUP_WRITEBACK
5319         for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5320                 wb_wait_for_completion(&memcg->cgwb_frn[i].done);
5321 #endif
5322         if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5323                 static_branch_dec(&memcg_sockets_enabled_key);
5324
5325         if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg->tcpmem_active)
5326                 static_branch_dec(&memcg_sockets_enabled_key);
5327
5328         vmpressure_cleanup(&memcg->vmpressure);
5329         cancel_work_sync(&memcg->high_work);
5330         mem_cgroup_remove_from_trees(memcg);
5331         memcg_free_shrinker_maps(memcg);
5332         memcg_free_kmem(memcg);
5333         mem_cgroup_free(memcg);
5334 }
5335
5336 /**
5337  * mem_cgroup_css_reset - reset the states of a mem_cgroup
5338  * @css: the target css
5339  *
5340  * Reset the states of the mem_cgroup associated with @css.  This is
5341  * invoked when the userland requests disabling on the default hierarchy
5342  * but the memcg is pinned through dependency.  The memcg should stop
5343  * applying policies and should revert to the vanilla state as it may be
5344  * made visible again.
5345  *
5346  * The current implementation only resets the essential configurations.
5347  * This needs to be expanded to cover all the visible parts.
5348  */
5349 static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
5350 {
5351         struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5352
5353         page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX);
5354         page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX);
5355         page_counter_set_max(&memcg->memsw, PAGE_COUNTER_MAX);
5356         page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX);
5357         page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX);
5358         page_counter_set_min(&memcg->memory, 0);
5359         page_counter_set_low(&memcg->memory, 0);
5360         memcg->high = PAGE_COUNTER_MAX;
5361         memcg->soft_limit = PAGE_COUNTER_MAX;
5362         memcg_wb_domain_size_changed(memcg);
5363 }
5364
5365 #ifdef CONFIG_MMU
5366 /* Handlers for move charge at task migration. */
5367 static int mem_cgroup_do_precharge(unsigned long count)
5368 {
5369         int ret;
5370
5371         /* Try a single bulk charge without reclaim first, kswapd may wake */
5372         ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_DIRECT_RECLAIM, count);
5373         if (!ret) {
5374                 mc.precharge += count;
5375                 return ret;
5376         }
5377
5378         /* Try charges one by one with reclaim, but do not retry */
5379         while (count--) {
5380                 ret = try_charge(mc.to, GFP_KERNEL | __GFP_NORETRY, 1);
5381                 if (ret)
5382                         return ret;
5383                 mc.precharge++;
5384                 cond_resched();
5385         }
5386         return 0;
5387 }
5388
5389 union mc_target {
5390         struct page     *page;
5391         swp_entry_t     ent;
5392 };
5393
5394 enum mc_target_type {
5395         MC_TARGET_NONE = 0,
5396         MC_TARGET_PAGE,
5397         MC_TARGET_SWAP,
5398         MC_TARGET_DEVICE,
5399 };
5400
5401 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5402                                                 unsigned long addr, pte_t ptent)
5403 {
5404         struct page *page = vm_normal_page(vma, addr, ptent);
5405
5406         if (!page || !page_mapped(page))
5407                 return NULL;
5408         if (PageAnon(page)) {
5409                 if (!(mc.flags & MOVE_ANON))
5410                         return NULL;
5411         } else {
5412                 if (!(mc.flags & MOVE_FILE))
5413                         return NULL;
5414         }
5415         if (!get_page_unless_zero(page))
5416                 return NULL;
5417
5418         return page;
5419 }
5420
5421 #if defined(CONFIG_SWAP) || defined(CONFIG_DEVICE_PRIVATE)
5422 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5423                         pte_t ptent, swp_entry_t *entry)
5424 {
5425         struct page *page = NULL;
5426         swp_entry_t ent = pte_to_swp_entry(ptent);
5427
5428         if (!(mc.flags & MOVE_ANON) || non_swap_entry(ent))
5429                 return NULL;
5430
5431         /*
5432          * Handle MEMORY_DEVICE_PRIVATE which are ZONE_DEVICE page belonging to
5433          * a device and because they are not accessible by CPU they are store
5434          * as special swap entry in the CPU page table.
5435          */
5436         if (is_device_private_entry(ent)) {
5437                 page = device_private_entry_to_page(ent);
5438                 /*
5439                  * MEMORY_DEVICE_PRIVATE means ZONE_DEVICE page and which have
5440                  * a refcount of 1 when free (unlike normal page)
5441                  */
5442                 if (!page_ref_add_unless(page, 1, 1))
5443                         return NULL;
5444                 return page;
5445         }
5446
5447         /*
5448          * Because lookup_swap_cache() updates some statistics counter,
5449          * we call find_get_page() with swapper_space directly.
5450          */
5451         page = find_get_page(swap_address_space(ent), swp_offset(ent));
5452         if (do_memsw_account())
5453                 entry->val = ent.val;
5454
5455         return page;
5456 }
5457 #else
5458 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5459                         pte_t ptent, swp_entry_t *entry)
5460 {
5461         return NULL;
5462 }
5463 #endif
5464
5465 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5466                         unsigned long addr, pte_t ptent, swp_entry_t *entry)
5467 {
5468         struct page *page = NULL;
5469         struct address_space *mapping;
5470         pgoff_t pgoff;
5471
5472         if (!vma->vm_file) /* anonymous vma */
5473                 return NULL;
5474         if (!(mc.flags & MOVE_FILE))
5475                 return NULL;
5476
5477         mapping = vma->vm_file->f_mapping;
5478         pgoff = linear_page_index(vma, addr);
5479
5480         /* page is moved even if it's not RSS of this task(page-faulted). */
5481 #ifdef CONFIG_SWAP
5482         /* shmem/tmpfs may report page out on swap: account for that too. */
5483         if (shmem_mapping(mapping)) {
5484                 page = find_get_entry(mapping, pgoff);
5485                 if (xa_is_value(page)) {
5486                         swp_entry_t swp = radix_to_swp_entry(page);
5487                         if (do_memsw_account())
5488                                 *entry = swp;
5489                         page = find_get_page(swap_address_space(swp),
5490                                              swp_offset(swp));
5491                 }
5492         } else
5493                 page = find_get_page(mapping, pgoff);
5494 #else
5495         page = find_get_page(mapping, pgoff);
5496 #endif
5497         return page;
5498 }
5499
5500 /**
5501  * mem_cgroup_move_account - move account of the page
5502  * @page: the page
5503  * @compound: charge the page as compound or small page
5504  * @from: mem_cgroup which the page is moved from.
5505  * @to: mem_cgroup which the page is moved to. @from != @to.
5506  *
5507  * The caller must make sure the page is not on LRU (isolate_page() is useful.)
5508  *
5509  * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
5510  * from old cgroup.
5511  */
5512 static int mem_cgroup_move_account(struct page *page,
5513                                    bool compound,
5514                                    struct mem_cgroup *from,
5515                                    struct mem_cgroup *to)
5516 {
5517         struct lruvec *from_vec, *to_vec;
5518         struct pglist_data *pgdat;
5519         unsigned long flags;
5520         unsigned int nr_pages = compound ? hpage_nr_pages(page) : 1;
5521         int ret;
5522         bool anon;
5523
5524         VM_BUG_ON(from == to);
5525         VM_BUG_ON_PAGE(PageLRU(page), page);
5526         VM_BUG_ON(compound && !PageTransHuge(page));
5527
5528         /*
5529          * Prevent mem_cgroup_migrate() from looking at
5530          * page->mem_cgroup of its source page while we change it.
5531          */
5532         ret = -EBUSY;
5533         if (!trylock_page(page))
5534                 goto out;
5535
5536         ret = -EINVAL;
5537         if (page->mem_cgroup != from)
5538                 goto out_unlock;
5539
5540         anon = PageAnon(page);
5541
5542         pgdat = page_pgdat(page);
5543         from_vec = mem_cgroup_lruvec(from, pgdat);
5544         to_vec = mem_cgroup_lruvec(to, pgdat);
5545
5546         spin_lock_irqsave(&from->move_lock, flags);
5547
5548         if (!anon && page_mapped(page)) {
5549                 __mod_lruvec_state(from_vec, NR_FILE_MAPPED, -nr_pages);
5550                 __mod_lruvec_state(to_vec, NR_FILE_MAPPED, nr_pages);
5551         }
5552
5553         /*
5554          * move_lock grabbed above and caller set from->moving_account, so
5555          * mod_memcg_page_state will serialize updates to PageDirty.
5556          * So mapping should be stable for dirty pages.
5557          */
5558         if (!anon && PageDirty(page)) {
5559                 struct address_space *mapping = page_mapping(page);
5560
5561                 if (mapping_cap_account_dirty(mapping)) {
5562                         __mod_lruvec_state(from_vec, NR_FILE_DIRTY, -nr_pages);
5563                         __mod_lruvec_state(to_vec, NR_FILE_DIRTY, nr_pages);
5564                 }
5565         }
5566
5567         if (PageWriteback(page)) {
5568                 __mod_lruvec_state(from_vec, NR_WRITEBACK, -nr_pages);
5569                 __mod_lruvec_state(to_vec, NR_WRITEBACK, nr_pages);
5570         }
5571
5572         /*
5573          * It is safe to change page->mem_cgroup here because the page
5574          * is referenced, charged, and isolated - we can't race with
5575          * uncharging, charging, migration, or LRU putback.
5576          */
5577
5578         /* caller should have done css_get */
5579         page->mem_cgroup = to;
5580
5581         spin_unlock_irqrestore(&from->move_lock, flags);
5582
5583         ret = 0;
5584
5585         local_irq_disable();
5586         mem_cgroup_charge_statistics(to, page, compound, nr_pages);
5587         memcg_check_events(to, page);
5588         mem_cgroup_charge_statistics(from, page, compound, -nr_pages);
5589         memcg_check_events(from, page);
5590         local_irq_enable();
5591 out_unlock:
5592         unlock_page(page);
5593 out:
5594         return ret;
5595 }
5596
5597 /**
5598  * get_mctgt_type - get target type of moving charge
5599  * @vma: the vma the pte to be checked belongs
5600  * @addr: the address corresponding to the pte to be checked
5601  * @ptent: the pte to be checked
5602  * @target: the pointer the target page or swap ent will be stored(can be NULL)
5603  *
5604  * Returns
5605  *   0(MC_TARGET_NONE): if the pte is not a target for move charge.
5606  *   1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5607  *     move charge. if @target is not NULL, the page is stored in target->page
5608  *     with extra refcnt got(Callers should handle it).
5609  *   2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5610  *     target for charge migration. if @target is not NULL, the entry is stored
5611  *     in target->ent.
5612  *   3(MC_TARGET_DEVICE): like MC_TARGET_PAGE  but page is MEMORY_DEVICE_PRIVATE
5613  *     (so ZONE_DEVICE page and thus not on the lru).
5614  *     For now we such page is charge like a regular page would be as for all
5615  *     intent and purposes it is just special memory taking the place of a
5616  *     regular page.
5617  *
5618  *     See Documentations/vm/hmm.txt and include/linux/hmm.h
5619  *
5620  * Called with pte lock held.
5621  */
5622
5623 static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
5624                 unsigned long addr, pte_t ptent, union mc_target *target)
5625 {
5626         struct page *page = NULL;
5627         enum mc_target_type ret = MC_TARGET_NONE;
5628         swp_entry_t ent = { .val = 0 };
5629
5630         if (pte_present(ptent))
5631                 page = mc_handle_present_pte(vma, addr, ptent);
5632         else if (is_swap_pte(ptent))
5633                 page = mc_handle_swap_pte(vma, ptent, &ent);
5634         else if (pte_none(ptent))
5635                 page = mc_handle_file_pte(vma, addr, ptent, &ent);
5636
5637         if (!page && !ent.val)
5638                 return ret;
5639         if (page) {
5640                 /*
5641                  * Do only loose check w/o serialization.
5642                  * mem_cgroup_move_account() checks the page is valid or
5643                  * not under LRU exclusion.
5644                  */
5645                 if (page->mem_cgroup == mc.from) {
5646                         ret = MC_TARGET_PAGE;
5647                         if (is_device_private_page(page))
5648                                 ret = MC_TARGET_DEVICE;
5649                         if (target)
5650                                 target->page = page;
5651                 }
5652                 if (!ret || !target)
5653                         put_page(page);
5654         }
5655         /*
5656          * There is a swap entry and a page doesn't exist or isn't charged.
5657          * But we cannot move a tail-page in a THP.
5658          */
5659         if (ent.val && !ret && (!page || !PageTransCompound(page)) &&
5660             mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
5661                 ret = MC_TARGET_SWAP;
5662                 if (target)
5663                         target->ent = ent;
5664         }
5665         return ret;
5666 }
5667
5668 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5669 /*
5670  * We don't consider PMD mapped swapping or file mapped pages because THP does
5671  * not support them for now.
5672  * Caller should make sure that pmd_trans_huge(pmd) is true.
5673  */
5674 static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5675                 unsigned long addr, pmd_t pmd, union mc_target *target)
5676 {
5677         struct page *page = NULL;
5678         enum mc_target_type ret = MC_TARGET_NONE;
5679
5680         if (unlikely(is_swap_pmd(pmd))) {
5681                 VM_BUG_ON(thp_migration_supported() &&
5682                                   !is_pmd_migration_entry(pmd));
5683                 return ret;
5684         }
5685         page = pmd_page(pmd);
5686         VM_BUG_ON_PAGE(!page || !PageHead(page), page);
5687         if (!(mc.flags & MOVE_ANON))
5688                 return ret;
5689         if (page->mem_cgroup == mc.from) {
5690                 ret = MC_TARGET_PAGE;
5691                 if (target) {
5692                         get_page(page);
5693                         target->page = page;
5694                 }
5695         }
5696         return ret;
5697 }
5698 #else
5699 static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5700                 unsigned long addr, pmd_t pmd, union mc_target *target)
5701 {
5702         return MC_TARGET_NONE;
5703 }
5704 #endif
5705
5706 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
5707                                         unsigned long addr, unsigned long end,
5708                                         struct mm_walk *walk)
5709 {
5710         struct vm_area_struct *vma = walk->vma;
5711         pte_t *pte;
5712         spinlock_t *ptl;
5713
5714         ptl = pmd_trans_huge_lock(pmd, vma);
5715         if (ptl) {
5716                 /*
5717                  * Note their can not be MC_TARGET_DEVICE for now as we do not
5718                  * support transparent huge page with MEMORY_DEVICE_PRIVATE but
5719                  * this might change.
5720                  */
5721                 if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
5722                         mc.precharge += HPAGE_PMD_NR;
5723                 spin_unlock(ptl);
5724                 return 0;
5725         }
5726
5727         if (pmd_trans_unstable(pmd))
5728                 return 0;
5729         pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5730         for (; addr != end; pte++, addr += PAGE_SIZE)
5731                 if (get_mctgt_type(vma, addr, *pte, NULL))
5732                         mc.precharge++; /* increment precharge temporarily */
5733         pte_unmap_unlock(pte - 1, ptl);
5734         cond_resched();
5735
5736         return 0;
5737 }
5738
5739 static const struct mm_walk_ops precharge_walk_ops = {
5740         .pmd_entry      = mem_cgroup_count_precharge_pte_range,
5741 };
5742
5743 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
5744 {
5745         unsigned long precharge;
5746
5747         down_read(&mm->mmap_sem);
5748         walk_page_range(mm, 0, mm->highest_vm_end, &precharge_walk_ops, NULL);
5749         up_read(&mm->mmap_sem);
5750
5751         precharge = mc.precharge;
5752         mc.precharge = 0;
5753
5754         return precharge;
5755 }
5756
5757 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
5758 {
5759         unsigned long precharge = mem_cgroup_count_precharge(mm);
5760
5761         VM_BUG_ON(mc.moving_task);
5762         mc.moving_task = current;
5763         return mem_cgroup_do_precharge(precharge);
5764 }
5765
5766 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5767 static void __mem_cgroup_clear_mc(void)
5768 {
5769         struct mem_cgroup *from = mc.from;
5770         struct mem_cgroup *to = mc.to;
5771
5772         /* we must uncharge all the leftover precharges from mc.to */
5773         if (mc.precharge) {
5774                 cancel_charge(mc.to, mc.precharge);
5775                 mc.precharge = 0;
5776         }
5777         /*
5778          * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5779          * we must uncharge here.
5780          */
5781         if (mc.moved_charge) {
5782                 cancel_charge(mc.from, mc.moved_charge);
5783                 mc.moved_charge = 0;
5784         }
5785         /* we must fixup refcnts and charges */
5786         if (mc.moved_swap) {
5787                 /* uncharge swap account from the old cgroup */
5788                 if (!mem_cgroup_is_root(mc.from))
5789                         page_counter_uncharge(&mc.from->memsw, mc.moved_swap);
5790
5791                 mem_cgroup_id_put_many(mc.from, mc.moved_swap);
5792
5793                 /*
5794                  * we charged both to->memory and to->memsw, so we
5795                  * should uncharge to->memory.
5796                  */
5797                 if (!mem_cgroup_is_root(mc.to))
5798                         page_counter_uncharge(&mc.to->memory, mc.moved_swap);
5799
5800                 mem_cgroup_id_get_many(mc.to, mc.moved_swap);
5801                 css_put_many(&mc.to->css, mc.moved_swap);
5802
5803                 mc.moved_swap = 0;
5804         }
5805         memcg_oom_recover(from);
5806         memcg_oom_recover(to);
5807         wake_up_all(&mc.waitq);
5808 }
5809
5810 static void mem_cgroup_clear_mc(void)
5811 {
5812         struct mm_struct *mm = mc.mm;
5813
5814         /*
5815          * we must clear moving_task before waking up waiters at the end of
5816          * task migration.
5817          */
5818         mc.moving_task = NULL;
5819         __mem_cgroup_clear_mc();
5820         spin_lock(&mc.lock);
5821         mc.from = NULL;
5822         mc.to = NULL;
5823         mc.mm = NULL;
5824         spin_unlock(&mc.lock);
5825
5826         mmput(mm);
5827 }
5828
5829 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
5830 {
5831         struct cgroup_subsys_state *css;
5832         struct mem_cgroup *memcg = NULL; /* unneeded init to make gcc happy */
5833         struct mem_cgroup *from;
5834         struct task_struct *leader, *p;
5835         struct mm_struct *mm;
5836         unsigned long move_flags;
5837         int ret = 0;
5838
5839         /* charge immigration isn't supported on the default hierarchy */
5840         if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
5841                 return 0;
5842
5843         /*
5844          * Multi-process migrations only happen on the default hierarchy
5845          * where charge immigration is not used.  Perform charge
5846          * immigration if @tset contains a leader and whine if there are
5847          * multiple.
5848          */
5849         p = NULL;
5850         cgroup_taskset_for_each_leader(leader, css, tset) {
5851                 WARN_ON_ONCE(p);
5852                 p = leader;
5853                 memcg = mem_cgroup_from_css(css);
5854         }
5855         if (!p)
5856                 return 0;
5857
5858         /*
5859          * We are now commited to this value whatever it is. Changes in this
5860          * tunable will only affect upcoming migrations, not the current one.
5861          * So we need to save it, and keep it going.
5862          */
5863         move_flags = READ_ONCE(memcg->move_charge_at_immigrate);
5864         if (!move_flags)
5865                 return 0;
5866
5867         from = mem_cgroup_from_task(p);
5868
5869         VM_BUG_ON(from == memcg);
5870
5871         mm = get_task_mm(p);
5872         if (!mm)
5873                 return 0;
5874         /* We move charges only when we move a owner of the mm */
5875         if (mm->owner == p) {
5876                 VM_BUG_ON(mc.from);
5877                 VM_BUG_ON(mc.to);
5878                 VM_BUG_ON(mc.precharge);
5879                 VM_BUG_ON(mc.moved_charge);
5880                 VM_BUG_ON(mc.moved_swap);
5881
5882                 spin_lock(&mc.lock);
5883                 mc.mm = mm;
5884                 mc.from = from;
5885                 mc.to = memcg;
5886                 mc.flags = move_flags;
5887                 spin_unlock(&mc.lock);
5888                 /* We set mc.moving_task later */
5889
5890                 ret = mem_cgroup_precharge_mc(mm);
5891                 if (ret)
5892                         mem_cgroup_clear_mc();
5893         } else {
5894                 mmput(mm);
5895         }
5896         return ret;
5897 }
5898
5899 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
5900 {
5901         if (mc.to)
5902                 mem_cgroup_clear_mc();
5903 }
5904
5905 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
5906                                 unsigned long addr, unsigned long end,
5907                                 struct mm_walk *walk)
5908 {
5909         int ret = 0;
5910         struct vm_area_struct *vma = walk->vma;
5911         pte_t *pte;
5912         spinlock_t *ptl;
5913         enum mc_target_type target_type;
5914         union mc_target target;
5915         struct page *page;
5916
5917         ptl = pmd_trans_huge_lock(pmd, vma);
5918         if (ptl) {
5919                 if (mc.precharge < HPAGE_PMD_NR) {
5920                         spin_unlock(ptl);
5921                         return 0;
5922                 }
5923                 target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
5924                 if (target_type == MC_TARGET_PAGE) {
5925                         page = target.page;
5926                         if (!isolate_lru_page(page)) {
5927                                 if (!mem_cgroup_move_account(page, true,
5928                                                              mc.from, mc.to)) {
5929                                         mc.precharge -= HPAGE_PMD_NR;
5930                                         mc.moved_charge += HPAGE_PMD_NR;
5931                                 }
5932                                 putback_lru_page(page);
5933                         }
5934                         put_page(page);
5935                 } else if (target_type == MC_TARGET_DEVICE) {
5936                         page = target.page;
5937                         if (!mem_cgroup_move_account(page, true,
5938                                                      mc.from, mc.to)) {
5939                                 mc.precharge -= HPAGE_PMD_NR;
5940                                 mc.moved_charge += HPAGE_PMD_NR;
5941                         }
5942                         put_page(page);
5943                 }
5944                 spin_unlock(ptl);
5945                 return 0;
5946         }
5947
5948         if (pmd_trans_unstable(pmd))
5949                 return 0;
5950 retry:
5951         pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5952         for (; addr != end; addr += PAGE_SIZE) {
5953                 pte_t ptent = *(pte++);
5954                 bool device = false;
5955                 swp_entry_t ent;
5956
5957                 if (!mc.precharge)
5958                         break;
5959
5960                 switch (get_mctgt_type(vma, addr, ptent, &target)) {
5961                 case MC_TARGET_DEVICE:
5962                         device = true;
5963                         /* fall through */
5964                 case MC_TARGET_PAGE:
5965                         page = target.page;
5966                         /*
5967                          * We can have a part of the split pmd here. Moving it
5968                          * can be done but it would be too convoluted so simply
5969                          * ignore such a partial THP and keep it in original
5970                          * memcg. There should be somebody mapping the head.
5971                          */
5972                         if (PageTransCompound(page))
5973                                 goto put;
5974                         if (!device && isolate_lru_page(page))
5975                                 goto put;
5976                         if (!mem_cgroup_move_account(page, false,
5977                                                 mc.from, mc.to)) {
5978                                 mc.precharge--;
5979                                 /* we uncharge from mc.from later. */
5980                                 mc.moved_charge++;
5981                         }
5982                         if (!device)
5983                                 putback_lru_page(page);
5984 put:                    /* get_mctgt_type() gets the page */
5985                         put_page(page);
5986                         break;
5987                 case MC_TARGET_SWAP:
5988                         ent = target.ent;
5989                         if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
5990                                 mc.precharge--;
5991                                 /* we fixup refcnts and charges later. */
5992                                 mc.moved_swap++;
5993                         }
5994                         break;
5995                 default:
5996                         break;
5997                 }
5998         }
5999         pte_unmap_unlock(pte - 1, ptl);
6000         cond_resched();
6001
6002         if (addr != end) {
6003                 /*
6004                  * We have consumed all precharges we got in can_attach().
6005                  * We try charge one by one, but don't do any additional
6006                  * charges to mc.to if we have failed in charge once in attach()
6007                  * phase.
6008                  */
6009                 ret = mem_cgroup_do_precharge(1);
6010                 if (!ret)
6011                         goto retry;
6012         }
6013
6014         return ret;
6015 }
6016
6017 static const struct mm_walk_ops charge_walk_ops = {
6018         .pmd_entry      = mem_cgroup_move_charge_pte_range,
6019 };
6020
6021 static void mem_cgroup_move_charge(void)
6022 {
6023         lru_add_drain_all();
6024         /*
6025          * Signal lock_page_memcg() to take the memcg's move_lock
6026          * while we're moving its pages to another memcg. Then wait
6027          * for already started RCU-only updates to finish.
6028          */
6029         atomic_inc(&mc.from->moving_account);
6030         synchronize_rcu();
6031 retry:
6032         if (unlikely(!down_read_trylock(&mc.mm->mmap_sem))) {
6033                 /*
6034                  * Someone who are holding the mmap_sem might be waiting in
6035                  * waitq. So we cancel all extra charges, wake up all waiters,
6036                  * and retry. Because we cancel precharges, we might not be able
6037                  * to move enough charges, but moving charge is a best-effort
6038                  * feature anyway, so it wouldn't be a big problem.
6039                  */
6040                 __mem_cgroup_clear_mc();
6041                 cond_resched();
6042                 goto retry;
6043         }
6044         /*
6045          * When we have consumed all precharges and failed in doing
6046          * additional charge, the page walk just aborts.
6047          */
6048         walk_page_range(mc.mm, 0, mc.mm->highest_vm_end, &charge_walk_ops,
6049                         NULL);
6050
6051         up_read(&mc.mm->mmap_sem);
6052         atomic_dec(&mc.from->moving_account);
6053 }
6054
6055 static void mem_cgroup_move_task(void)
6056 {
6057         if (mc.to) {
6058                 mem_cgroup_move_charge();
6059                 mem_cgroup_clear_mc();
6060         }
6061 }
6062 #else   /* !CONFIG_MMU */
6063 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
6064 {
6065         return 0;
6066 }
6067 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
6068 {
6069 }
6070 static void mem_cgroup_move_task(void)
6071 {
6072 }
6073 #endif
6074
6075 /*
6076  * Cgroup retains root cgroups across [un]mount cycles making it necessary
6077  * to verify whether we're attached to the default hierarchy on each mount
6078  * attempt.
6079  */
6080 static void mem_cgroup_bind(struct cgroup_subsys_state *root_css)
6081 {
6082         /*
6083          * use_hierarchy is forced on the default hierarchy.  cgroup core
6084          * guarantees that @root doesn't have any children, so turning it
6085          * on for the root memcg is enough.
6086          */
6087         if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
6088                 root_mem_cgroup->use_hierarchy = true;
6089         else
6090                 root_mem_cgroup->use_hierarchy = false;
6091 }
6092
6093 static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value)
6094 {
6095         if (value == PAGE_COUNTER_MAX)
6096                 seq_puts(m, "max\n");
6097         else
6098                 seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE);
6099
6100         return 0;
6101 }
6102
6103 static u64 memory_current_read(struct cgroup_subsys_state *css,
6104                                struct cftype *cft)
6105 {
6106         struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6107
6108         return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
6109 }
6110
6111 static int memory_min_show(struct seq_file *m, void *v)
6112 {
6113         return seq_puts_memcg_tunable(m,
6114                 READ_ONCE(mem_cgroup_from_seq(m)->memory.min));
6115 }
6116
6117 static ssize_t memory_min_write(struct kernfs_open_file *of,
6118                                 char *buf, size_t nbytes, loff_t off)
6119 {
6120         struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6121         unsigned long min;
6122         int err;
6123
6124         buf = strstrip(buf);
6125         err = page_counter_memparse(buf, "max", &min);
6126         if (err)
6127                 return err;
6128
6129         page_counter_set_min(&memcg->memory, min);
6130
6131         return nbytes;
6132 }
6133
6134 static int memory_low_show(struct seq_file *m, void *v)
6135 {
6136         return seq_puts_memcg_tunable(m,
6137                 READ_ONCE(mem_cgroup_from_seq(m)->memory.low));
6138 }
6139
6140 static ssize_t memory_low_write(struct kernfs_open_file *of,
6141                                 char *buf, size_t nbytes, loff_t off)
6142 {
6143         struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6144         unsigned long low;
6145         int err;
6146
6147         buf = strstrip(buf);
6148         err = page_counter_memparse(buf, "max", &low);
6149         if (err)
6150                 return err;
6151
6152         page_counter_set_low(&memcg->memory, low);
6153
6154         return nbytes;
6155 }
6156
6157 static int memory_high_show(struct seq_file *m, void *v)
6158 {
6159         return seq_puts_memcg_tunable(m, READ_ONCE(mem_cgroup_from_seq(m)->high));
6160 }
6161
6162 static ssize_t memory_high_write(struct kernfs_open_file *of,
6163                                  char *buf, size_t nbytes, loff_t off)
6164 {
6165         struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6166         unsigned long nr_pages;
6167         unsigned long high;
6168         int err;
6169
6170         buf = strstrip(buf);
6171         err = page_counter_memparse(buf, "max", &high);
6172         if (err)
6173                 return err;
6174
6175         memcg->high = high;
6176
6177         nr_pages = page_counter_read(&memcg->memory);
6178         if (nr_pages > high)
6179                 try_to_free_mem_cgroup_pages(memcg, nr_pages - high,
6180                                              GFP_KERNEL, true);
6181
6182         memcg_wb_domain_size_changed(memcg);
6183         return nbytes;
6184 }
6185
6186 static int memory_max_show(struct seq_file *m, void *v)
6187 {
6188         return seq_puts_memcg_tunable(m,
6189                 READ_ONCE(mem_cgroup_from_seq(m)->memory.max));
6190 }
6191
6192 static ssize_t memory_max_write(struct kernfs_open_file *of,
6193                                 char *buf, size_t nbytes, loff_t off)
6194 {
6195         struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6196         unsigned int nr_reclaims = MEM_CGROUP_RECLAIM_RETRIES;
6197         bool drained = false;
6198         unsigned long max;
6199         int err;
6200
6201         buf = strstrip(buf);
6202         err = page_counter_memparse(buf, "max", &max);
6203         if (err)
6204                 return err;
6205
6206         xchg(&memcg->memory.max, max);
6207
6208         for (;;) {
6209                 unsigned long nr_pages = page_counter_read(&memcg->memory);
6210
6211                 if (nr_pages <= max)
6212                         break;
6213
6214                 if (signal_pending(current)) {
6215                         err = -EINTR;
6216                         break;
6217                 }
6218
6219                 if (!drained) {
6220                         drain_all_stock(memcg);
6221                         drained = true;
6222                         continue;
6223                 }
6224
6225                 if (nr_reclaims) {
6226                         if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,
6227                                                           GFP_KERNEL, true))
6228                                 nr_reclaims--;
6229                         continue;
6230                 }
6231
6232                 memcg_memory_event(memcg, MEMCG_OOM);
6233                 if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0))
6234                         break;
6235         }
6236
6237         memcg_wb_domain_size_changed(memcg);
6238         return nbytes;
6239 }
6240
6241 static void __memory_events_show(struct seq_file *m, atomic_long_t *events)
6242 {
6243         seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW]));
6244         seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH]));
6245         seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX]));
6246         seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM]));
6247         seq_printf(m, "oom_kill %lu\n",
6248                    atomic_long_read(&events[MEMCG_OOM_KILL]));
6249 }
6250
6251 static int memory_events_show(struct seq_file *m, void *v)
6252 {
6253         struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6254
6255         __memory_events_show(m, memcg->memory_events);
6256         return 0;
6257 }
6258
6259 static int memory_events_local_show(struct seq_file *m, void *v)
6260 {
6261         struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6262
6263         __memory_events_show(m, memcg->memory_events_local);
6264         return 0;
6265 }
6266
6267 static int memory_stat_show(struct seq_file *m, void *v)
6268 {
6269         struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6270         char *buf;
6271
6272         buf = memory_stat_format(memcg);
6273         if (!buf)
6274                 return -ENOMEM;
6275         seq_puts(m, buf);
6276         kfree(buf);
6277         return 0;
6278 }
6279
6280 static int memory_oom_group_show(struct seq_file *m, void *v)
6281 {
6282         struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6283
6284         seq_printf(m, "%d\n", memcg->oom_group);
6285
6286         return 0;
6287 }
6288
6289 static ssize_t memory_oom_group_write(struct kernfs_open_file *of,
6290                                       char *buf, size_t nbytes, loff_t off)
6291 {
6292         struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6293         int ret, oom_group;
6294
6295         buf = strstrip(buf);
6296         if (!buf)
6297                 return -EINVAL;
6298
6299         ret = kstrtoint(buf, 0, &oom_group);
6300         if (ret)
6301                 return ret;
6302
6303         if (oom_group != 0 && oom_group != 1)
6304                 return -EINVAL;
6305
6306         memcg->oom_group = oom_group;
6307
6308         return nbytes;
6309 }
6310
6311 static struct cftype memory_files[] = {
6312         {
6313                 .name = "current",
6314                 .flags = CFTYPE_NOT_ON_ROOT,
6315                 .read_u64 = memory_current_read,
6316         },
6317         {
6318                 .name = "min",
6319                 .flags = CFTYPE_NOT_ON_ROOT,
6320                 .seq_show = memory_min_show,
6321                 .write = memory_min_write,
6322         },
6323         {
6324                 .name = "low",
6325                 .flags = CFTYPE_NOT_ON_ROOT,
6326                 .seq_show = memory_low_show,
6327                 .write = memory_low_write,
6328         },
6329         {
6330                 .name = "high",
6331                 .flags = CFTYPE_NOT_ON_ROOT,
6332                 .seq_show = memory_high_show,
6333                 .write = memory_high_write,
6334         },
6335         {
6336                 .name = "max",
6337                 .flags = CFTYPE_NOT_ON_ROOT,
6338                 .seq_show = memory_max_show,
6339                 .write = memory_max_write,
6340         },
6341         {
6342                 .name = "events",
6343                 .flags = CFTYPE_NOT_ON_ROOT,
6344                 .file_offset = offsetof(struct mem_cgroup, events_file),
6345                 .seq_show = memory_events_show,
6346         },
6347         {
6348                 .name = "events.local",
6349                 .flags = CFTYPE_NOT_ON_ROOT,
6350                 .file_offset = offsetof(struct mem_cgroup, events_local_file),
6351                 .seq_show = memory_events_local_show,
6352         },
6353         {
6354                 .name = "stat",
6355                 .flags = CFTYPE_NOT_ON_ROOT,
6356                 .seq_show = memory_stat_show,
6357         },
6358         {
6359                 .name = "oom.group",
6360                 .flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE,
6361                 .seq_show = memory_oom_group_show,
6362                 .write = memory_oom_group_write,
6363         },
6364         { }     /* terminate */
6365 };
6366
6367 struct cgroup_subsys memory_cgrp_subsys = {
6368         .css_alloc = mem_cgroup_css_alloc,
6369         .css_online = mem_cgroup_css_online,
6370         .css_offline = mem_cgroup_css_offline,
6371         .css_released = mem_cgroup_css_released,
6372         .css_free = mem_cgroup_css_free,
6373         .css_reset = mem_cgroup_css_reset,
6374         .can_attach = mem_cgroup_can_attach,
6375         .cancel_attach = mem_cgroup_cancel_attach,
6376         .post_attach = mem_cgroup_move_task,
6377         .bind = mem_cgroup_bind,
6378         .dfl_cftypes = memory_files,
6379         .legacy_cftypes = mem_cgroup_legacy_files,
6380         .early_init = 0,
6381 };
6382
6383 /**
6384  * mem_cgroup_protected - check if memory consumption is in the normal range
6385  * @root: the top ancestor of the sub-tree being checked
6386  * @memcg: the memory cgroup to check
6387  *
6388  * WARNING: This function is not stateless! It can only be used as part
6389  *          of a top-down tree iteration, not for isolated queries.
6390  *
6391  * Returns one of the following:
6392  *   MEMCG_PROT_NONE: cgroup memory is not protected
6393  *   MEMCG_PROT_LOW: cgroup memory is protected as long there is
6394  *     an unprotected supply of reclaimable memory from other cgroups.
6395  *   MEMCG_PROT_MIN: cgroup memory is protected
6396  *
6397  * @root is exclusive; it is never protected when looked at directly
6398  *
6399  * To provide a proper hierarchical behavior, effective memory.min/low values
6400  * are used. Below is the description of how effective memory.low is calculated.
6401  * Effective memory.min values is calculated in the same way.
6402  *
6403  * Effective memory.low is always equal or less than the original memory.low.
6404  * If there is no memory.low overcommittment (which is always true for
6405  * top-level memory cgroups), these two values are equal.
6406  * Otherwise, it's a part of parent's effective memory.low,
6407  * calculated as a cgroup's memory.low usage divided by sum of sibling's
6408  * memory.low usages, where memory.low usage is the size of actually
6409  * protected memory.
6410  *
6411  *                                             low_usage
6412  * elow = min( memory.low, parent->elow * ------------------ ),
6413  *                                        siblings_low_usage
6414  *
6415  *             | memory.current, if memory.current < memory.low
6416  * low_usage = |
6417  *             | 0, otherwise.
6418  *
6419  *
6420  * Such definition of the effective memory.low provides the expected
6421  * hierarchical behavior: parent's memory.low value is limiting
6422  * children, unprotected memory is reclaimed first and cgroups,
6423  * which are not using their guarantee do not affect actual memory
6424  * distribution.
6425  *
6426  * For example, if there are memcgs A, A/B, A/C, A/D and A/E:
6427  *
6428  *     A      A/memory.low = 2G, A/memory.current = 6G
6429  *    //\\
6430  *   BC  DE   B/memory.low = 3G  B/memory.current = 2G
6431  *            C/memory.low = 1G  C/memory.current = 2G
6432  *            D/memory.low = 0   D/memory.current = 2G
6433  *            E/memory.low = 10G E/memory.current = 0
6434  *
6435  * and the memory pressure is applied, the following memory distribution
6436  * is expected (approximately):
6437  *
6438  *     A/memory.current = 2G
6439  *
6440  *     B/memory.current = 1.3G
6441  *     C/memory.current = 0.6G
6442  *     D/memory.current = 0
6443  *     E/memory.current = 0
6444  *
6445  * These calculations require constant tracking of the actual low usages
6446  * (see propagate_protected_usage()), as well as recursive calculation of
6447  * effective memory.low values. But as we do call mem_cgroup_protected()
6448  * path for each memory cgroup top-down from the reclaim,
6449  * it's possible to optimize this part, and save calculated elow
6450  * for next usage. This part is intentionally racy, but it's ok,
6451  * as memory.low is a best-effort mechanism.
6452  */
6453 void mem_cgroup_calculate_protection(struct mem_cgroup *root,
6454                                      struct mem_cgroup *memcg)
6455 {
6456         struct mem_cgroup *parent;
6457         unsigned long emin, parent_emin;
6458         unsigned long elow, parent_elow;
6459         unsigned long usage;
6460
6461         if (mem_cgroup_disabled())
6462                 return;
6463
6464         if (!root)
6465                 root = root_mem_cgroup;
6466         if (memcg == root)
6467                 return;
6468
6469         usage = page_counter_read(&memcg->memory);
6470         if (!usage)
6471                 return;
6472
6473         emin = memcg->memory.min;
6474         elow = memcg->memory.low;
6475
6476         parent = parent_mem_cgroup(memcg);
6477         /* No parent means a non-hierarchical mode on v1 memcg */
6478         if (!parent)
6479                 return;
6480
6481         if (parent == root)
6482                 return;
6483
6484         parent_emin = READ_ONCE(parent->memory.emin);
6485         emin = min(emin, parent_emin);
6486         if (emin && parent_emin) {
6487                 unsigned long min_usage, siblings_min_usage;
6488
6489                 min_usage = min(usage, memcg->memory.min);
6490                 siblings_min_usage = atomic_long_read(
6491                         &parent->memory.children_min_usage);
6492
6493                 if (min_usage && siblings_min_usage)
6494                         emin = min(emin, parent_emin * min_usage /
6495                                    siblings_min_usage);
6496         }
6497
6498         parent_elow = READ_ONCE(parent->memory.elow);
6499         elow = min(elow, parent_elow);
6500         if (elow && parent_elow) {
6501                 unsigned long low_usage, siblings_low_usage;
6502
6503                 low_usage = min(usage, memcg->memory.low);
6504                 siblings_low_usage = atomic_long_read(
6505                         &parent->memory.children_low_usage);
6506
6507                 if (low_usage && siblings_low_usage)
6508                         elow = min(elow, parent_elow * low_usage /
6509                                    siblings_low_usage);
6510         }
6511
6512 }
6513
6514 /**
6515  * mem_cgroup_try_charge - try charging a page
6516  * @page: page to charge
6517  * @mm: mm context of the victim
6518  * @gfp_mask: reclaim mode
6519  * @memcgp: charged memcg return
6520  * @compound: charge the page as compound or small page
6521  *
6522  * Try to charge @page to the memcg that @mm belongs to, reclaiming
6523  * pages according to @gfp_mask if necessary.
6524  *
6525  * Returns 0 on success, with *@memcgp pointing to the charged memcg.
6526  * Otherwise, an error code is returned.
6527  *
6528  * After page->mapping has been set up, the caller must finalize the
6529  * charge with mem_cgroup_commit_charge().  Or abort the transaction
6530  * with mem_cgroup_cancel_charge() in case page instantiation fails.
6531  */
6532 int mem_cgroup_try_charge(struct page *page, struct mm_struct *mm,
6533                           gfp_t gfp_mask, struct mem_cgroup **memcgp,
6534                           bool compound)
6535 {
6536         struct mem_cgroup *memcg = NULL;
6537         unsigned int nr_pages = compound ? hpage_nr_pages(page) : 1;
6538         int ret = 0;
6539
6540         if (mem_cgroup_disabled())
6541                 goto out;
6542
6543         if (PageSwapCache(page)) {
6544                 /*
6545                  * Every swap fault against a single page tries to charge the
6546                  * page, bail as early as possible.  shmem_unuse() encounters
6547                  * already charged pages, too.  The USED bit is protected by
6548                  * the page lock, which serializes swap cache removal, which
6549                  * in turn serializes uncharging.
6550                  */
6551                 VM_BUG_ON_PAGE(!PageLocked(page), page);
6552                 if (compound_head(page)->mem_cgroup)
6553                         goto out;
6554
6555                 if (do_swap_account) {
6556                         swp_entry_t ent = { .val = page_private(page), };
6557                         unsigned short id = lookup_swap_cgroup_id(ent);
6558
6559                         rcu_read_lock();
6560                         memcg = mem_cgroup_from_id(id);
6561                         if (memcg && !css_tryget_online(&memcg->css))
6562                                 memcg = NULL;
6563                         rcu_read_unlock();
6564                 }
6565         }
6566
6567         if (!memcg)
6568                 memcg = get_mem_cgroup_from_mm(mm);
6569
6570         ret = try_charge(memcg, gfp_mask, nr_pages);
6571
6572         css_put(&memcg->css);
6573 out:
6574         *memcgp = memcg;
6575         return ret;
6576 }
6577
6578 int mem_cgroup_try_charge_delay(struct page *page, struct mm_struct *mm,
6579                           gfp_t gfp_mask, struct mem_cgroup **memcgp,
6580                           bool compound)
6581 {
6582         struct mem_cgroup *memcg;
6583         int ret;
6584
6585         ret = mem_cgroup_try_charge(page, mm, gfp_mask, memcgp, compound);
6586         memcg = *memcgp;
6587         mem_cgroup_throttle_swaprate(memcg, page_to_nid(page), gfp_mask);
6588         return ret;
6589 }
6590
6591 /**
6592  * mem_cgroup_commit_charge - commit a page charge
6593  * @page: page to charge
6594  * @memcg: memcg to charge the page to
6595  * @lrucare: page might be on LRU already
6596  * @compound: charge the page as compound or small page
6597  *
6598  * Finalize a charge transaction started by mem_cgroup_try_charge(),
6599  * after page->mapping has been set up.  This must happen atomically
6600  * as part of the page instantiation, i.e. under the page table lock
6601  * for anonymous pages, under the page lock for page and swap cache.
6602  *
6603  * In addition, the page must not be on the LRU during the commit, to
6604  * prevent racing with task migration.  If it might be, use @lrucare.
6605  *
6606  * Use mem_cgroup_cancel_charge() to cancel the transaction instead.
6607  */
6608 void mem_cgroup_commit_charge(struct page *page, struct mem_cgroup *memcg,
6609                               bool lrucare, bool compound)
6610 {
6611         unsigned int nr_pages = compound ? hpage_nr_pages(page) : 1;
6612
6613         VM_BUG_ON_PAGE(!page->mapping, page);
6614         VM_BUG_ON_PAGE(PageLRU(page) && !lrucare, page);
6615
6616         if (mem_cgroup_disabled())
6617                 return;
6618         /*
6619          * Swap faults will attempt to charge the same page multiple
6620          * times.  But reuse_swap_page() might have removed the page
6621          * from swapcache already, so we can't check PageSwapCache().
6622          */
6623         if (!memcg)
6624                 return;
6625
6626         commit_charge(page, memcg, lrucare);
6627
6628         local_irq_disable();
6629         mem_cgroup_charge_statistics(memcg, page, compound, nr_pages);
6630         memcg_check_events(memcg, page);
6631         local_irq_enable();
6632
6633         if (do_memsw_account() && PageSwapCache(page)) {
6634                 swp_entry_t entry = { .val = page_private(page) };
6635                 /*
6636                  * The swap entry might not get freed for a long time,
6637                  * let's not wait for it.  The page already received a
6638                  * memory+swap charge, drop the swap entry duplicate.
6639                  */
6640                 mem_cgroup_uncharge_swap(entry, nr_pages);
6641         }
6642 }
6643
6644 /**
6645  * mem_cgroup_cancel_charge - cancel a page charge
6646  * @page: page to charge
6647  * @memcg: memcg to charge the page to
6648  * @compound: charge the page as compound or small page
6649  *
6650  * Cancel a charge transaction started by mem_cgroup_try_charge().
6651  */
6652 void mem_cgroup_cancel_charge(struct page *page, struct mem_cgroup *memcg,
6653                 bool compound)
6654 {
6655         unsigned int nr_pages = compound ? hpage_nr_pages(page) : 1;
6656
6657         if (mem_cgroup_disabled())
6658                 return;
6659         /*
6660          * Swap faults will attempt to charge the same page multiple
6661          * times.  But reuse_swap_page() might have removed the page
6662          * from swapcache already, so we can't check PageSwapCache().
6663          */
6664         if (!memcg)
6665                 return;
6666
6667         cancel_charge(memcg, nr_pages);
6668 }
6669
6670 struct uncharge_gather {
6671         struct mem_cgroup *memcg;
6672         unsigned long pgpgout;
6673         unsigned long nr_anon;
6674         unsigned long nr_file;
6675         unsigned long nr_kmem;
6676         unsigned long nr_huge;
6677         unsigned long nr_shmem;
6678         struct page *dummy_page;
6679 };
6680
6681 static inline void uncharge_gather_clear(struct uncharge_gather *ug)
6682 {
6683         memset(ug, 0, sizeof(*ug));
6684 }
6685
6686 static void uncharge_batch(const struct uncharge_gather *ug)
6687 {
6688         unsigned long nr_pages = ug->nr_anon + ug->nr_file + ug->nr_kmem;
6689         unsigned long flags;
6690
6691         if (!mem_cgroup_is_root(ug->memcg)) {
6692                 page_counter_uncharge(&ug->memcg->memory, nr_pages);
6693                 if (do_memsw_account())
6694                         page_counter_uncharge(&ug->memcg->memsw, nr_pages);
6695                 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && ug->nr_kmem)
6696                         page_counter_uncharge(&ug->memcg->kmem, ug->nr_kmem);
6697                 memcg_oom_recover(ug->memcg);
6698         }
6699
6700         local_irq_save(flags);
6701         __mod_memcg_state(ug->memcg, MEMCG_RSS, -ug->nr_anon);
6702         __mod_memcg_state(ug->memcg, MEMCG_CACHE, -ug->nr_file);
6703         __mod_memcg_state(ug->memcg, MEMCG_RSS_HUGE, -ug->nr_huge);
6704         __mod_memcg_state(ug->memcg, NR_SHMEM, -ug->nr_shmem);
6705         __count_memcg_events(ug->memcg, PGPGOUT, ug->pgpgout);
6706         __this_cpu_add(ug->memcg->vmstats_percpu->nr_page_events, nr_pages);
6707         memcg_check_events(ug->memcg, ug->dummy_page);
6708         local_irq_restore(flags);
6709
6710         if (!mem_cgroup_is_root(ug->memcg))
6711                 css_put_many(&ug->memcg->css, nr_pages);
6712 }
6713
6714 static void uncharge_page(struct page *page, struct uncharge_gather *ug)
6715 {
6716         VM_BUG_ON_PAGE(PageLRU(page), page);
6717         VM_BUG_ON_PAGE(page_count(page) && !is_zone_device_page(page) &&
6718                         !PageHWPoison(page) , page);
6719
6720         if (!page->mem_cgroup)
6721                 return;
6722
6723         /*
6724          * Nobody should be changing or seriously looking at
6725          * page->mem_cgroup at this point, we have fully
6726          * exclusive access to the page.
6727          */
6728
6729         if (ug->memcg != page->mem_cgroup) {
6730                 if (ug->memcg) {
6731                         uncharge_batch(ug);
6732                         uncharge_gather_clear(ug);
6733                 }
6734                 ug->memcg = page->mem_cgroup;
6735         }
6736
6737         if (!PageKmemcg(page)) {
6738                 unsigned int nr_pages = 1;
6739
6740                 if (PageTransHuge(page)) {
6741                         nr_pages = compound_nr(page);
6742                         ug->nr_huge += nr_pages;
6743                 }
6744                 if (PageAnon(page))
6745                         ug->nr_anon += nr_pages;
6746                 else {
6747                         ug->nr_file += nr_pages;
6748                         if (PageSwapBacked(page))
6749                                 ug->nr_shmem += nr_pages;
6750                 }
6751                 ug->pgpgout++;
6752         } else {
6753                 ug->nr_kmem += compound_nr(page);
6754                 __ClearPageKmemcg(page);
6755         }
6756
6757         ug->dummy_page = page;
6758         page->mem_cgroup = NULL;
6759 }
6760
6761 static void uncharge_list(struct list_head *page_list)
6762 {
6763         struct uncharge_gather ug;
6764         struct list_head *next;
6765
6766         uncharge_gather_clear(&ug);
6767
6768         /*
6769          * Note that the list can be a single page->lru; hence the
6770          * do-while loop instead of a simple list_for_each_entry().
6771          */
6772         next = page_list->next;
6773         do {
6774                 struct page *page;
6775
6776                 page = list_entry(next, struct page, lru);
6777                 next = page->lru.next;
6778
6779                 uncharge_page(page, &ug);
6780         } while (next != page_list);
6781
6782         if (ug.memcg)
6783                 uncharge_batch(&ug);
6784 }
6785
6786 /**
6787  * mem_cgroup_uncharge - uncharge a page
6788  * @page: page to uncharge
6789  *
6790  * Uncharge a page previously charged with mem_cgroup_try_charge() and
6791  * mem_cgroup_commit_charge().
6792  */
6793 void mem_cgroup_uncharge(struct page *page)
6794 {
6795         struct uncharge_gather ug;
6796
6797         if (mem_cgroup_disabled())
6798                 return;
6799
6800         /* Don't touch page->lru of any random page, pre-check: */
6801         if (!page->mem_cgroup)
6802                 return;
6803
6804         uncharge_gather_clear(&ug);
6805         uncharge_page(page, &ug);
6806         uncharge_batch(&ug);
6807 }
6808
6809 /**
6810  * mem_cgroup_uncharge_list - uncharge a list of page
6811  * @page_list: list of pages to uncharge
6812  *
6813  * Uncharge a list of pages previously charged with
6814  * mem_cgroup_try_charge() and mem_cgroup_commit_charge().
6815  */
6816 void mem_cgroup_uncharge_list(struct list_head *page_list)
6817 {
6818         if (mem_cgroup_disabled())
6819                 return;
6820
6821         if (!list_empty(page_list))
6822                 uncharge_list(page_list);
6823 }
6824
6825 /**
6826  * mem_cgroup_migrate - charge a page's replacement
6827  * @oldpage: currently circulating page
6828  * @newpage: replacement page
6829  *
6830  * Charge @newpage as a replacement page for @oldpage. @oldpage will
6831  * be uncharged upon free.
6832  *
6833  * Both pages must be locked, @newpage->mapping must be set up.
6834  */
6835 void mem_cgroup_migrate(struct page *oldpage, struct page *newpage)
6836 {
6837         struct mem_cgroup *memcg;
6838         unsigned int nr_pages;
6839         bool compound;
6840         unsigned long flags;
6841
6842         VM_BUG_ON_PAGE(!PageLocked(oldpage), oldpage);
6843         VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
6844         VM_BUG_ON_PAGE(PageAnon(oldpage) != PageAnon(newpage), newpage);
6845         VM_BUG_ON_PAGE(PageTransHuge(oldpage) != PageTransHuge(newpage),
6846                        newpage);
6847
6848         if (mem_cgroup_disabled())
6849                 return;
6850
6851         /* Page cache replacement: new page already charged? */
6852         if (newpage->mem_cgroup)
6853                 return;
6854
6855         /* Swapcache readahead pages can get replaced before being charged */
6856         memcg = oldpage->mem_cgroup;
6857         if (!memcg)
6858                 return;
6859
6860         /* Force-charge the new page. The old one will be freed soon */
6861         compound = PageTransHuge(newpage);
6862         nr_pages = compound ? hpage_nr_pages(newpage) : 1;
6863
6864         page_counter_charge(&memcg->memory, nr_pages);
6865         if (do_memsw_account())
6866                 page_counter_charge(&memcg->memsw, nr_pages);
6867         css_get_many(&memcg->css, nr_pages);
6868
6869         commit_charge(newpage, memcg, false);
6870
6871         local_irq_save(flags);
6872         mem_cgroup_charge_statistics(memcg, newpage, compound, nr_pages);
6873         memcg_check_events(memcg, newpage);
6874         local_irq_restore(flags);
6875 }
6876
6877 DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key);
6878 EXPORT_SYMBOL(memcg_sockets_enabled_key);
6879
6880 void mem_cgroup_sk_alloc(struct sock *sk)
6881 {
6882         struct mem_cgroup *memcg;
6883
6884         if (!mem_cgroup_sockets_enabled)
6885                 return;
6886
6887         /* Do not associate the sock with unrelated interrupted task's memcg. */
6888         if (in_interrupt())
6889                 return;
6890
6891         rcu_read_lock();
6892         memcg = mem_cgroup_from_task(current);
6893         if (memcg == root_mem_cgroup)
6894                 goto out;
6895         if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg->tcpmem_active)
6896                 goto out;
6897         if (css_tryget_online(&memcg->css))
6898                 sk->sk_memcg = memcg;
6899 out:
6900         rcu_read_unlock();
6901 }
6902
6903 void mem_cgroup_sk_free(struct sock *sk)
6904 {
6905         if (sk->sk_memcg)
6906                 css_put(&sk->sk_memcg->css);
6907 }
6908
6909 /**
6910  * mem_cgroup_charge_skmem - charge socket memory
6911  * @memcg: memcg to charge
6912  * @nr_pages: number of pages to charge
6913  *
6914  * Charges @nr_pages to @memcg. Returns %true if the charge fit within
6915  * @memcg's configured limit, %false if the charge had to be forced.
6916  */
6917 bool mem_cgroup_charge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
6918 {
6919         gfp_t gfp_mask = GFP_KERNEL;
6920
6921         if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
6922                 struct page_counter *fail;
6923
6924                 if (page_counter_try_charge(&memcg->tcpmem, nr_pages, &fail)) {
6925                         memcg->tcpmem_pressure = 0;
6926                         return true;
6927                 }
6928                 page_counter_charge(&memcg->tcpmem, nr_pages);
6929                 memcg->tcpmem_pressure = 1;
6930                 return false;
6931         }
6932
6933         /* Don't block in the packet receive path */
6934         if (in_softirq())
6935                 gfp_mask = GFP_NOWAIT;
6936
6937         mod_memcg_state(memcg, MEMCG_SOCK, nr_pages);
6938
6939         if (try_charge(memcg, gfp_mask, nr_pages) == 0)
6940                 return true;
6941
6942         try_charge(memcg, gfp_mask|__GFP_NOFAIL, nr_pages);
6943         return false;
6944 }
6945
6946 /**
6947  * mem_cgroup_uncharge_skmem - uncharge socket memory
6948  * @memcg: memcg to uncharge
6949  * @nr_pages: number of pages to uncharge
6950  */
6951 void mem_cgroup_uncharge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
6952 {
6953         if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
6954                 page_counter_uncharge(&memcg->tcpmem, nr_pages);
6955                 return;
6956         }
6957
6958         mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages);
6959
6960         refill_stock(memcg, nr_pages);
6961 }
6962
6963 static int __init cgroup_memory(char *s)
6964 {
6965         char *token;
6966
6967         while ((token = strsep(&s, ",")) != NULL) {
6968                 if (!*token)
6969                         continue;
6970                 if (!strcmp(token, "nosocket"))
6971                         cgroup_memory_nosocket = true;
6972                 if (!strcmp(token, "nokmem"))
6973                         cgroup_memory_nokmem = true;
6974         }
6975         return 0;
6976 }
6977 __setup("cgroup.memory=", cgroup_memory);
6978
6979 /*
6980  * subsys_initcall() for memory controller.
6981  *
6982  * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this
6983  * context because of lock dependencies (cgroup_lock -> cpu hotplug) but
6984  * basically everything that doesn't depend on a specific mem_cgroup structure
6985  * should be initialized from here.
6986  */
6987 static int __init mem_cgroup_init(void)
6988 {
6989         int cpu, node;
6990
6991 #ifdef CONFIG_MEMCG_KMEM
6992         /*
6993          * Kmem cache creation is mostly done with the slab_mutex held,
6994          * so use a workqueue with limited concurrency to avoid stalling
6995          * all worker threads in case lots of cgroups are created and
6996          * destroyed simultaneously.
6997          */
6998         memcg_kmem_cache_wq = alloc_workqueue("memcg_kmem_cache", 0, 1);
6999         BUG_ON(!memcg_kmem_cache_wq);
7000 #endif
7001
7002         cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL,
7003                                   memcg_hotplug_cpu_dead);
7004
7005         for_each_possible_cpu(cpu)
7006                 INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
7007                           drain_local_stock);
7008
7009         for_each_node(node) {
7010                 struct mem_cgroup_tree_per_node *rtpn;
7011
7012                 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL,
7013                                     node_online(node) ? node : NUMA_NO_NODE);
7014
7015                 rtpn->rb_root = RB_ROOT;
7016                 rtpn->rb_rightmost = NULL;
7017                 spin_lock_init(&rtpn->lock);
7018                 soft_limit_tree.rb_tree_per_node[node] = rtpn;
7019         }
7020
7021         return 0;
7022 }
7023 subsys_initcall(mem_cgroup_init);
7024
7025 #ifdef CONFIG_MEMCG_SWAP
7026 static struct mem_cgroup *mem_cgroup_id_get_online(struct mem_cgroup *memcg)
7027 {
7028         while (!refcount_inc_not_zero(&memcg->id.ref)) {
7029                 /*
7030                  * The root cgroup cannot be destroyed, so it's refcount must
7031                  * always be >= 1.
7032                  */
7033                 if (WARN_ON_ONCE(memcg == root_mem_cgroup)) {
7034                         VM_BUG_ON(1);
7035                         break;
7036                 }
7037                 memcg = parent_mem_cgroup(memcg);
7038                 if (!memcg)
7039                         memcg = root_mem_cgroup;
7040         }
7041         return memcg;
7042 }
7043
7044 /**
7045  * mem_cgroup_swapout - transfer a memsw charge to swap
7046  * @page: page whose memsw charge to transfer
7047  * @entry: swap entry to move the charge to
7048  *
7049  * Transfer the memsw charge of @page to @entry.
7050  */
7051 void mem_cgroup_swapout(struct page *page, swp_entry_t entry)
7052 {
7053         struct mem_cgroup *memcg, *swap_memcg;
7054         unsigned int nr_entries;
7055         unsigned short oldid;
7056
7057         VM_BUG_ON_PAGE(PageLRU(page), page);
7058         VM_BUG_ON_PAGE(page_count(page), page);
7059
7060         if (!do_memsw_account())
7061                 return;
7062
7063         memcg = page->mem_cgroup;
7064
7065         VM_WARN_ON_ONCE_PAGE(!memcg, page);
7066         if (!memcg)
7067                 return;
7068
7069         /*
7070          * In case the memcg owning these pages has been offlined and doesn't
7071          * have an ID allocated to it anymore, charge the closest online
7072          * ancestor for the swap instead and transfer the memory+swap charge.
7073          */
7074         swap_memcg = mem_cgroup_id_get_online(memcg);
7075         nr_entries = hpage_nr_pages(page);
7076         /* Get references for the tail pages, too */
7077         if (nr_entries > 1)
7078                 mem_cgroup_id_get_many(swap_memcg, nr_entries - 1);
7079         oldid = swap_cgroup_record(entry, mem_cgroup_id(swap_memcg),
7080                                    nr_entries);
7081         VM_BUG_ON_PAGE(oldid, page);
7082         mod_memcg_state(swap_memcg, MEMCG_SWAP, nr_entries);
7083
7084         page->mem_cgroup = NULL;
7085
7086         if (!mem_cgroup_is_root(memcg))
7087                 page_counter_uncharge(&memcg->memory, nr_entries);
7088
7089         if (memcg != swap_memcg) {
7090                 if (!mem_cgroup_is_root(swap_memcg))
7091                         page_counter_charge(&swap_memcg->memsw, nr_entries);
7092                 page_counter_uncharge(&memcg->memsw, nr_entries);
7093         }
7094
7095         /*
7096          * Interrupts should be disabled here because the caller holds the
7097          * i_pages lock which is taken with interrupts-off. It is
7098          * important here to have the interrupts disabled because it is the
7099          * only synchronisation we have for updating the per-CPU variables.
7100          */
7101         VM_BUG_ON(!irqs_disabled());
7102         mem_cgroup_charge_statistics(memcg, page, PageTransHuge(page),
7103                                      -nr_entries);
7104         memcg_check_events(memcg, page);
7105
7106         if (!mem_cgroup_is_root(memcg))
7107                 css_put_many(&memcg->css, nr_entries);
7108 }
7109
7110 /**
7111  * mem_cgroup_try_charge_swap - try charging swap space for a page
7112  * @page: page being added to swap
7113  * @entry: swap entry to charge
7114  *
7115  * Try to charge @page's memcg for the swap space at @entry.
7116  *
7117  * Returns 0 on success, -ENOMEM on failure.
7118  */
7119 int mem_cgroup_try_charge_swap(struct page *page, swp_entry_t entry)
7120 {
7121         unsigned int nr_pages = hpage_nr_pages(page);
7122         struct page_counter *counter;
7123         struct mem_cgroup *memcg;
7124         unsigned short oldid;
7125
7126         if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) || !do_swap_account)
7127                 return 0;
7128
7129         memcg = page->mem_cgroup;
7130
7131         VM_WARN_ON_ONCE_PAGE(!memcg, page);
7132         if (!memcg)
7133                 return 0;
7134
7135         if (!entry.val) {
7136                 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
7137                 return 0;
7138         }
7139
7140         memcg = mem_cgroup_id_get_online(memcg);
7141
7142         if (!mem_cgroup_is_root(memcg) &&
7143             !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
7144                 memcg_memory_event(memcg, MEMCG_SWAP_MAX);
7145                 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
7146                 mem_cgroup_id_put(memcg);
7147                 return -ENOMEM;
7148         }
7149
7150         /* Get references for the tail pages, too */
7151         if (nr_pages > 1)
7152                 mem_cgroup_id_get_many(memcg, nr_pages - 1);
7153         oldid = swap_cgroup_record(entry, mem_cgroup_id(memcg), nr_pages);
7154         VM_BUG_ON_PAGE(oldid, page);
7155         mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
7156
7157         return 0;
7158 }
7159
7160 /**
7161  * mem_cgroup_uncharge_swap - uncharge swap space
7162  * @entry: swap entry to uncharge
7163  * @nr_pages: the amount of swap space to uncharge
7164  */
7165 void mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages)
7166 {
7167         struct mem_cgroup *memcg;
7168         unsigned short id;
7169
7170         if (!do_swap_account)
7171                 return;
7172
7173         id = swap_cgroup_record(entry, 0, nr_pages);
7174         rcu_read_lock();
7175         memcg = mem_cgroup_from_id(id);
7176         if (memcg) {
7177                 if (!mem_cgroup_is_root(memcg)) {
7178                         if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
7179                                 page_counter_uncharge(&memcg->swap, nr_pages);
7180                         else
7181                                 page_counter_uncharge(&memcg->memsw, nr_pages);
7182                 }
7183                 mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
7184                 mem_cgroup_id_put_many(memcg, nr_pages);
7185         }
7186         rcu_read_unlock();
7187 }
7188
7189 long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg)
7190 {
7191         long nr_swap_pages = get_nr_swap_pages();
7192
7193         if (!do_swap_account || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
7194                 return nr_swap_pages;
7195         for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg))
7196                 nr_swap_pages = min_t(long, nr_swap_pages,
7197                                       READ_ONCE(memcg->swap.max) -
7198                                       page_counter_read(&memcg->swap));
7199         return nr_swap_pages;
7200 }
7201
7202 bool mem_cgroup_swap_full(struct page *page)
7203 {
7204         struct mem_cgroup *memcg;
7205
7206         VM_BUG_ON_PAGE(!PageLocked(page), page);
7207
7208         if (vm_swap_full())
7209                 return true;
7210         if (!do_swap_account || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
7211                 return false;
7212
7213         memcg = page->mem_cgroup;
7214         if (!memcg)
7215                 return false;
7216
7217         for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg))
7218                 if (page_counter_read(&memcg->swap) * 2 >= memcg->swap.max)
7219                         return true;
7220
7221         return false;
7222 }
7223
7224 /* for remember boot option*/
7225 #ifdef CONFIG_MEMCG_SWAP_ENABLED
7226 static int really_do_swap_account __initdata = 1;
7227 #else
7228 static int really_do_swap_account __initdata;
7229 #endif
7230
7231 static int __init enable_swap_account(char *s)
7232 {
7233         if (!strcmp(s, "1"))
7234                 really_do_swap_account = 1;
7235         else if (!strcmp(s, "0"))
7236                 really_do_swap_account = 0;
7237         return 1;
7238 }
7239 __setup("swapaccount=", enable_swap_account);
7240
7241 static u64 swap_current_read(struct cgroup_subsys_state *css,
7242                              struct cftype *cft)
7243 {
7244         struct mem_cgroup *memcg = mem_cgroup_from_css(css);
7245
7246         return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE;
7247 }
7248
7249 static int swap_max_show(struct seq_file *m, void *v)
7250 {
7251         return seq_puts_memcg_tunable(m,
7252                 READ_ONCE(mem_cgroup_from_seq(m)->swap.max));
7253 }
7254
7255 static ssize_t swap_max_write(struct kernfs_open_file *of,
7256                               char *buf, size_t nbytes, loff_t off)
7257 {
7258         struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7259         unsigned long max;
7260         int err;
7261
7262         buf = strstrip(buf);
7263         err = page_counter_memparse(buf, "max", &max);
7264         if (err)
7265                 return err;
7266
7267         xchg(&memcg->swap.max, max);
7268
7269         return nbytes;
7270 }
7271
7272 static int swap_events_show(struct seq_file *m, void *v)
7273 {
7274         struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
7275
7276         seq_printf(m, "max %lu\n",
7277                    atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
7278         seq_printf(m, "fail %lu\n",
7279                    atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL]));
7280
7281         return 0;
7282 }
7283
7284 static struct cftype swap_files[] = {
7285         {
7286                 .name = "swap.current",
7287                 .flags = CFTYPE_NOT_ON_ROOT,
7288                 .read_u64 = swap_current_read,
7289         },
7290         {
7291                 .name = "swap.max",
7292                 .flags = CFTYPE_NOT_ON_ROOT,
7293                 .seq_show = swap_max_show,
7294                 .write = swap_max_write,
7295         },
7296         {
7297                 .name = "swap.events",
7298                 .flags = CFTYPE_NOT_ON_ROOT,
7299                 .file_offset = offsetof(struct mem_cgroup, swap_events_file),
7300                 .seq_show = swap_events_show,
7301         },
7302         { }     /* terminate */
7303 };
7304
7305 static struct cftype memsw_cgroup_files[] = {
7306         {
7307                 .name = "memsw.usage_in_bytes",
7308                 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
7309                 .read_u64 = mem_cgroup_read_u64,
7310         },
7311         {
7312                 .name = "memsw.max_usage_in_bytes",
7313                 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
7314                 .write = mem_cgroup_reset,
7315                 .read_u64 = mem_cgroup_read_u64,
7316         },
7317         {
7318                 .name = "memsw.limit_in_bytes",
7319                 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
7320                 .write = mem_cgroup_write,
7321                 .read_u64 = mem_cgroup_read_u64,
7322         },
7323         {
7324                 .name = "memsw.failcnt",
7325                 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
7326                 .write = mem_cgroup_reset,
7327                 .read_u64 = mem_cgroup_read_u64,
7328         },
7329         {
7330                 .name = "force_reclaim",
7331                 .write_u64 = mem_cgroup_force_reclaim,
7332         },
7333         { },    /* terminate */
7334 };
7335
7336 static int __init mem_cgroup_swap_init(void)
7337 {
7338         if (!mem_cgroup_disabled() && really_do_swap_account) {
7339                 do_swap_account = 1;
7340                 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys,
7341                                                swap_files));
7342                 WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys,
7343                                                   memsw_cgroup_files));
7344         }
7345         return 0;
7346 }
7347 subsys_initcall(mem_cgroup_swap_init);
7348
7349 #endif /* CONFIG_MEMCG_SWAP */