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