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