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