~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/mm/memcontrol.c

Version: ~ [ linux-5.12-rc5 ] ~ [ linux-5.11.11 ] ~ [ linux-5.10.27 ] ~ [ linux-5.9.16 ] ~ [ linux-5.8.18 ] ~ [ linux-5.7.19 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.109 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.184 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.228 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.264 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.264 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.18.140 ] ~ [ linux-3.16.85 ] ~ [ linux-3.14.79 ] ~ [ linux-3.12.74 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

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