OSDN Git Service

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