x86/speculation/mds: Add SMT warning message
[linux/fpc-iii.git] / mm / memcontrol.c
blob81a0d3914ec999efcb36fb590e75c29d059d2b24
1 /* memcontrol.c - Memory Controller
3 * Copyright IBM Corporation, 2007
4 * Author Balbir Singh <balbir@linux.vnet.ibm.com>
6 * Copyright 2007 OpenVZ SWsoft Inc
7 * Author: Pavel Emelianov <xemul@openvz.org>
9 * Memory thresholds
10 * Copyright (C) 2009 Nokia Corporation
11 * Author: Kirill A. Shutemov
13 * Kernel Memory Controller
14 * Copyright (C) 2012 Parallels Inc. and Google Inc.
15 * Authors: Glauber Costa and Suleiman Souhlal
17 * Native page reclaim
18 * Charge lifetime sanitation
19 * Lockless page tracking & accounting
20 * Unified hierarchy configuration model
21 * Copyright (C) 2015 Red Hat, Inc., Johannes Weiner
23 * This program is free software; you can redistribute it and/or modify
24 * it under the terms of the GNU General Public License as published by
25 * the Free Software Foundation; either version 2 of the License, or
26 * (at your option) any later version.
28 * This program is distributed in the hope that it will be useful,
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
31 * GNU General Public License for more details.
34 #include <linux/page_counter.h>
35 #include <linux/memcontrol.h>
36 #include <linux/cgroup.h>
37 #include <linux/mm.h>
38 #include <linux/sched/mm.h>
39 #include <linux/shmem_fs.h>
40 #include <linux/hugetlb.h>
41 #include <linux/pagemap.h>
42 #include <linux/vm_event_item.h>
43 #include <linux/smp.h>
44 #include <linux/page-flags.h>
45 #include <linux/backing-dev.h>
46 #include <linux/bit_spinlock.h>
47 #include <linux/rcupdate.h>
48 #include <linux/limits.h>
49 #include <linux/export.h>
50 #include <linux/mutex.h>
51 #include <linux/rbtree.h>
52 #include <linux/slab.h>
53 #include <linux/swap.h>
54 #include <linux/swapops.h>
55 #include <linux/spinlock.h>
56 #include <linux/eventfd.h>
57 #include <linux/poll.h>
58 #include <linux/sort.h>
59 #include <linux/fs.h>
60 #include <linux/seq_file.h>
61 #include <linux/vmpressure.h>
62 #include <linux/mm_inline.h>
63 #include <linux/swap_cgroup.h>
64 #include <linux/cpu.h>
65 #include <linux/oom.h>
66 #include <linux/lockdep.h>
67 #include <linux/file.h>
68 #include <linux/tracehook.h>
69 #include "internal.h"
70 #include <net/sock.h>
71 #include <net/ip.h>
72 #include "slab.h"
74 #include <linux/uaccess.h>
76 #include <trace/events/vmscan.h>
78 struct cgroup_subsys memory_cgrp_subsys __read_mostly;
79 EXPORT_SYMBOL(memory_cgrp_subsys);
81 struct mem_cgroup *root_mem_cgroup __read_mostly;
83 #define MEM_CGROUP_RECLAIM_RETRIES 5
85 /* Socket memory accounting disabled? */
86 static bool cgroup_memory_nosocket;
88 /* Kernel memory accounting disabled? */
89 static bool cgroup_memory_nokmem;
91 /* Whether the swap controller is active */
92 #ifdef CONFIG_MEMCG_SWAP
93 int do_swap_account __read_mostly;
94 #else
95 #define do_swap_account 0
96 #endif
98 /* Whether legacy memory+swap accounting is active */
99 static bool do_memsw_account(void)
101 return !cgroup_subsys_on_dfl(memory_cgrp_subsys) && do_swap_account;
104 static const char *const mem_cgroup_lru_names[] = {
105 "inactive_anon",
106 "active_anon",
107 "inactive_file",
108 "active_file",
109 "unevictable",
112 #define THRESHOLDS_EVENTS_TARGET 128
113 #define SOFTLIMIT_EVENTS_TARGET 1024
114 #define NUMAINFO_EVENTS_TARGET 1024
117 * Cgroups above their limits are maintained in a RB-Tree, independent of
118 * their hierarchy representation
121 struct mem_cgroup_tree_per_node {
122 struct rb_root rb_root;
123 struct rb_node *rb_rightmost;
124 spinlock_t lock;
127 struct mem_cgroup_tree {
128 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
131 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
133 /* for OOM */
134 struct mem_cgroup_eventfd_list {
135 struct list_head list;
136 struct eventfd_ctx *eventfd;
140 * cgroup_event represents events which userspace want to receive.
142 struct mem_cgroup_event {
144 * memcg which the event belongs to.
146 struct mem_cgroup *memcg;
148 * eventfd to signal userspace about the event.
150 struct eventfd_ctx *eventfd;
152 * Each of these stored in a list by the cgroup.
154 struct list_head list;
156 * register_event() callback will be used to add new userspace
157 * waiter for changes related to this event. Use eventfd_signal()
158 * on eventfd to send notification to userspace.
160 int (*register_event)(struct mem_cgroup *memcg,
161 struct eventfd_ctx *eventfd, const char *args);
163 * unregister_event() callback will be called when userspace closes
164 * the eventfd or on cgroup removing. This callback must be set,
165 * if you want provide notification functionality.
167 void (*unregister_event)(struct mem_cgroup *memcg,
168 struct eventfd_ctx *eventfd);
170 * All fields below needed to unregister event when
171 * userspace closes eventfd.
173 poll_table pt;
174 wait_queue_head_t *wqh;
175 wait_queue_entry_t wait;
176 struct work_struct remove;
179 static void mem_cgroup_threshold(struct mem_cgroup *memcg);
180 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
182 /* Stuffs for move charges at task migration. */
184 * Types of charges to be moved.
186 #define MOVE_ANON 0x1U
187 #define MOVE_FILE 0x2U
188 #define MOVE_MASK (MOVE_ANON | MOVE_FILE)
190 /* "mc" and its members are protected by cgroup_mutex */
191 static struct move_charge_struct {
192 spinlock_t lock; /* for from, to */
193 struct mm_struct *mm;
194 struct mem_cgroup *from;
195 struct mem_cgroup *to;
196 unsigned long flags;
197 unsigned long precharge;
198 unsigned long moved_charge;
199 unsigned long moved_swap;
200 struct task_struct *moving_task; /* a task moving charges */
201 wait_queue_head_t waitq; /* a waitq for other context */
202 } mc = {
203 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
204 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
208 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
209 * limit reclaim to prevent infinite loops, if they ever occur.
211 #define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
212 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
214 enum charge_type {
215 MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
216 MEM_CGROUP_CHARGE_TYPE_ANON,
217 MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
218 MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
219 NR_CHARGE_TYPE,
222 /* for encoding cft->private value on file */
223 enum res_type {
224 _MEM,
225 _MEMSWAP,
226 _OOM_TYPE,
227 _KMEM,
228 _TCP,
231 #define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
232 #define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
233 #define MEMFILE_ATTR(val) ((val) & 0xffff)
234 /* Used for OOM nofiier */
235 #define OOM_CONTROL (0)
238 * Iteration constructs for visiting all cgroups (under a tree). If
239 * loops are exited prematurely (break), mem_cgroup_iter_break() must
240 * be used for reference counting.
242 #define for_each_mem_cgroup_tree(iter, root) \
243 for (iter = mem_cgroup_iter(root, NULL, NULL); \
244 iter != NULL; \
245 iter = mem_cgroup_iter(root, iter, NULL))
247 #define for_each_mem_cgroup(iter) \
248 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
249 iter != NULL; \
250 iter = mem_cgroup_iter(NULL, iter, NULL))
252 static inline bool should_force_charge(void)
254 return tsk_is_oom_victim(current) || fatal_signal_pending(current) ||
255 (current->flags & PF_EXITING);
258 /* Some nice accessors for the vmpressure. */
259 struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
261 if (!memcg)
262 memcg = root_mem_cgroup;
263 return &memcg->vmpressure;
266 struct cgroup_subsys_state *vmpressure_to_css(struct vmpressure *vmpr)
268 return &container_of(vmpr, struct mem_cgroup, vmpressure)->css;
271 #ifdef CONFIG_MEMCG_KMEM
273 * This will be the memcg's index in each cache's ->memcg_params.memcg_caches.
274 * The main reason for not using cgroup id for this:
275 * this works better in sparse environments, where we have a lot of memcgs,
276 * but only a few kmem-limited. Or also, if we have, for instance, 200
277 * memcgs, and none but the 200th is kmem-limited, we'd have to have a
278 * 200 entry array for that.
280 * The current size of the caches array is stored in memcg_nr_cache_ids. It
281 * will double each time we have to increase it.
283 static DEFINE_IDA(memcg_cache_ida);
284 int memcg_nr_cache_ids;
286 /* Protects memcg_nr_cache_ids */
287 static DECLARE_RWSEM(memcg_cache_ids_sem);
289 void memcg_get_cache_ids(void)
291 down_read(&memcg_cache_ids_sem);
294 void memcg_put_cache_ids(void)
296 up_read(&memcg_cache_ids_sem);
300 * MIN_SIZE is different than 1, because we would like to avoid going through
301 * the alloc/free process all the time. In a small machine, 4 kmem-limited
302 * cgroups is a reasonable guess. In the future, it could be a parameter or
303 * tunable, but that is strictly not necessary.
305 * MAX_SIZE should be as large as the number of cgrp_ids. Ideally, we could get
306 * this constant directly from cgroup, but it is understandable that this is
307 * better kept as an internal representation in cgroup.c. In any case, the
308 * cgrp_id space is not getting any smaller, and we don't have to necessarily
309 * increase ours as well if it increases.
311 #define MEMCG_CACHES_MIN_SIZE 4
312 #define MEMCG_CACHES_MAX_SIZE MEM_CGROUP_ID_MAX
315 * A lot of the calls to the cache allocation functions are expected to be
316 * inlined by the compiler. Since the calls to memcg_kmem_get_cache are
317 * conditional to this static branch, we'll have to allow modules that does
318 * kmem_cache_alloc and the such to see this symbol as well
320 DEFINE_STATIC_KEY_FALSE(memcg_kmem_enabled_key);
321 EXPORT_SYMBOL(memcg_kmem_enabled_key);
323 struct workqueue_struct *memcg_kmem_cache_wq;
325 static int memcg_shrinker_map_size;
326 static DEFINE_MUTEX(memcg_shrinker_map_mutex);
328 static void memcg_free_shrinker_map_rcu(struct rcu_head *head)
330 kvfree(container_of(head, struct memcg_shrinker_map, rcu));
333 static int memcg_expand_one_shrinker_map(struct mem_cgroup *memcg,
334 int size, int old_size)
336 struct memcg_shrinker_map *new, *old;
337 int nid;
339 lockdep_assert_held(&memcg_shrinker_map_mutex);
341 for_each_node(nid) {
342 old = rcu_dereference_protected(
343 mem_cgroup_nodeinfo(memcg, nid)->shrinker_map, true);
344 /* Not yet online memcg */
345 if (!old)
346 return 0;
348 new = kvmalloc(sizeof(*new) + size, GFP_KERNEL);
349 if (!new)
350 return -ENOMEM;
352 /* Set all old bits, clear all new bits */
353 memset(new->map, (int)0xff, old_size);
354 memset((void *)new->map + old_size, 0, size - old_size);
356 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_map, new);
357 call_rcu(&old->rcu, memcg_free_shrinker_map_rcu);
360 return 0;
363 static void memcg_free_shrinker_maps(struct mem_cgroup *memcg)
365 struct mem_cgroup_per_node *pn;
366 struct memcg_shrinker_map *map;
367 int nid;
369 if (mem_cgroup_is_root(memcg))
370 return;
372 for_each_node(nid) {
373 pn = mem_cgroup_nodeinfo(memcg, nid);
374 map = rcu_dereference_protected(pn->shrinker_map, true);
375 if (map)
376 kvfree(map);
377 rcu_assign_pointer(pn->shrinker_map, NULL);
381 static int memcg_alloc_shrinker_maps(struct mem_cgroup *memcg)
383 struct memcg_shrinker_map *map;
384 int nid, size, ret = 0;
386 if (mem_cgroup_is_root(memcg))
387 return 0;
389 mutex_lock(&memcg_shrinker_map_mutex);
390 size = memcg_shrinker_map_size;
391 for_each_node(nid) {
392 map = kvzalloc(sizeof(*map) + size, GFP_KERNEL);
393 if (!map) {
394 memcg_free_shrinker_maps(memcg);
395 ret = -ENOMEM;
396 break;
398 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_map, map);
400 mutex_unlock(&memcg_shrinker_map_mutex);
402 return ret;
405 int memcg_expand_shrinker_maps(int new_id)
407 int size, old_size, ret = 0;
408 struct mem_cgroup *memcg;
410 size = DIV_ROUND_UP(new_id + 1, BITS_PER_LONG) * sizeof(unsigned long);
411 old_size = memcg_shrinker_map_size;
412 if (size <= old_size)
413 return 0;
415 mutex_lock(&memcg_shrinker_map_mutex);
416 if (!root_mem_cgroup)
417 goto unlock;
419 for_each_mem_cgroup(memcg) {
420 if (mem_cgroup_is_root(memcg))
421 continue;
422 ret = memcg_expand_one_shrinker_map(memcg, size, old_size);
423 if (ret)
424 goto unlock;
426 unlock:
427 if (!ret)
428 memcg_shrinker_map_size = size;
429 mutex_unlock(&memcg_shrinker_map_mutex);
430 return ret;
433 void memcg_set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
435 if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
436 struct memcg_shrinker_map *map;
438 rcu_read_lock();
439 map = rcu_dereference(memcg->nodeinfo[nid]->shrinker_map);
440 /* Pairs with smp mb in shrink_slab() */
441 smp_mb__before_atomic();
442 set_bit(shrinker_id, map->map);
443 rcu_read_unlock();
447 #else /* CONFIG_MEMCG_KMEM */
448 static int memcg_alloc_shrinker_maps(struct mem_cgroup *memcg)
450 return 0;
452 static void memcg_free_shrinker_maps(struct mem_cgroup *memcg) { }
453 #endif /* CONFIG_MEMCG_KMEM */
456 * mem_cgroup_css_from_page - css of the memcg associated with a page
457 * @page: page of interest
459 * If memcg is bound to the default hierarchy, css of the memcg associated
460 * with @page is returned. The returned css remains associated with @page
461 * until it is released.
463 * If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup
464 * is returned.
466 struct cgroup_subsys_state *mem_cgroup_css_from_page(struct page *page)
468 struct mem_cgroup *memcg;
470 memcg = page->mem_cgroup;
472 if (!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
473 memcg = root_mem_cgroup;
475 return &memcg->css;
479 * page_cgroup_ino - return inode number of the memcg a page is charged to
480 * @page: the page
482 * Look up the closest online ancestor of the memory cgroup @page is charged to
483 * and return its inode number or 0 if @page is not charged to any cgroup. It
484 * is safe to call this function without holding a reference to @page.
486 * Note, this function is inherently racy, because there is nothing to prevent
487 * the cgroup inode from getting torn down and potentially reallocated a moment
488 * after page_cgroup_ino() returns, so it only should be used by callers that
489 * do not care (such as procfs interfaces).
491 ino_t page_cgroup_ino(struct page *page)
493 struct mem_cgroup *memcg;
494 unsigned long ino = 0;
496 rcu_read_lock();
497 memcg = READ_ONCE(page->mem_cgroup);
498 while (memcg && !(memcg->css.flags & CSS_ONLINE))
499 memcg = parent_mem_cgroup(memcg);
500 if (memcg)
501 ino = cgroup_ino(memcg->css.cgroup);
502 rcu_read_unlock();
503 return ino;
506 static struct mem_cgroup_per_node *
507 mem_cgroup_page_nodeinfo(struct mem_cgroup *memcg, struct page *page)
509 int nid = page_to_nid(page);
511 return memcg->nodeinfo[nid];
514 static struct mem_cgroup_tree_per_node *
515 soft_limit_tree_node(int nid)
517 return soft_limit_tree.rb_tree_per_node[nid];
520 static struct mem_cgroup_tree_per_node *
521 soft_limit_tree_from_page(struct page *page)
523 int nid = page_to_nid(page);
525 return soft_limit_tree.rb_tree_per_node[nid];
528 static void __mem_cgroup_insert_exceeded(struct mem_cgroup_per_node *mz,
529 struct mem_cgroup_tree_per_node *mctz,
530 unsigned long new_usage_in_excess)
532 struct rb_node **p = &mctz->rb_root.rb_node;
533 struct rb_node *parent = NULL;
534 struct mem_cgroup_per_node *mz_node;
535 bool rightmost = true;
537 if (mz->on_tree)
538 return;
540 mz->usage_in_excess = new_usage_in_excess;
541 if (!mz->usage_in_excess)
542 return;
543 while (*p) {
544 parent = *p;
545 mz_node = rb_entry(parent, struct mem_cgroup_per_node,
546 tree_node);
547 if (mz->usage_in_excess < mz_node->usage_in_excess) {
548 p = &(*p)->rb_left;
549 rightmost = false;
553 * We can't avoid mem cgroups that are over their soft
554 * limit by the same amount
556 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
557 p = &(*p)->rb_right;
560 if (rightmost)
561 mctz->rb_rightmost = &mz->tree_node;
563 rb_link_node(&mz->tree_node, parent, p);
564 rb_insert_color(&mz->tree_node, &mctz->rb_root);
565 mz->on_tree = true;
568 static void __mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
569 struct mem_cgroup_tree_per_node *mctz)
571 if (!mz->on_tree)
572 return;
574 if (&mz->tree_node == mctz->rb_rightmost)
575 mctz->rb_rightmost = rb_prev(&mz->tree_node);
577 rb_erase(&mz->tree_node, &mctz->rb_root);
578 mz->on_tree = false;
581 static void mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
582 struct mem_cgroup_tree_per_node *mctz)
584 unsigned long flags;
586 spin_lock_irqsave(&mctz->lock, flags);
587 __mem_cgroup_remove_exceeded(mz, mctz);
588 spin_unlock_irqrestore(&mctz->lock, flags);
591 static unsigned long soft_limit_excess(struct mem_cgroup *memcg)
593 unsigned long nr_pages = page_counter_read(&memcg->memory);
594 unsigned long soft_limit = READ_ONCE(memcg->soft_limit);
595 unsigned long excess = 0;
597 if (nr_pages > soft_limit)
598 excess = nr_pages - soft_limit;
600 return excess;
603 static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
605 unsigned long excess;
606 struct mem_cgroup_per_node *mz;
607 struct mem_cgroup_tree_per_node *mctz;
609 mctz = soft_limit_tree_from_page(page);
610 if (!mctz)
611 return;
613 * Necessary to update all ancestors when hierarchy is used.
614 * because their event counter is not touched.
616 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
617 mz = mem_cgroup_page_nodeinfo(memcg, page);
618 excess = soft_limit_excess(memcg);
620 * We have to update the tree if mz is on RB-tree or
621 * mem is over its softlimit.
623 if (excess || mz->on_tree) {
624 unsigned long flags;
626 spin_lock_irqsave(&mctz->lock, flags);
627 /* if on-tree, remove it */
628 if (mz->on_tree)
629 __mem_cgroup_remove_exceeded(mz, mctz);
631 * Insert again. mz->usage_in_excess will be updated.
632 * If excess is 0, no tree ops.
634 __mem_cgroup_insert_exceeded(mz, mctz, excess);
635 spin_unlock_irqrestore(&mctz->lock, flags);
640 static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
642 struct mem_cgroup_tree_per_node *mctz;
643 struct mem_cgroup_per_node *mz;
644 int nid;
646 for_each_node(nid) {
647 mz = mem_cgroup_nodeinfo(memcg, nid);
648 mctz = soft_limit_tree_node(nid);
649 if (mctz)
650 mem_cgroup_remove_exceeded(mz, mctz);
654 static struct mem_cgroup_per_node *
655 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
657 struct mem_cgroup_per_node *mz;
659 retry:
660 mz = NULL;
661 if (!mctz->rb_rightmost)
662 goto done; /* Nothing to reclaim from */
664 mz = rb_entry(mctz->rb_rightmost,
665 struct mem_cgroup_per_node, tree_node);
667 * Remove the node now but someone else can add it back,
668 * we will to add it back at the end of reclaim to its correct
669 * position in the tree.
671 __mem_cgroup_remove_exceeded(mz, mctz);
672 if (!soft_limit_excess(mz->memcg) ||
673 !css_tryget_online(&mz->memcg->css))
674 goto retry;
675 done:
676 return mz;
679 static struct mem_cgroup_per_node *
680 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
682 struct mem_cgroup_per_node *mz;
684 spin_lock_irq(&mctz->lock);
685 mz = __mem_cgroup_largest_soft_limit_node(mctz);
686 spin_unlock_irq(&mctz->lock);
687 return mz;
690 static unsigned long memcg_sum_events(struct mem_cgroup *memcg,
691 int event)
693 return atomic_long_read(&memcg->events[event]);
696 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
697 struct page *page,
698 bool compound, int nr_pages)
701 * Here, RSS means 'mapped anon' and anon's SwapCache. Shmem/tmpfs is
702 * counted as CACHE even if it's on ANON LRU.
704 if (PageAnon(page))
705 __mod_memcg_state(memcg, MEMCG_RSS, nr_pages);
706 else {
707 __mod_memcg_state(memcg, MEMCG_CACHE, nr_pages);
708 if (PageSwapBacked(page))
709 __mod_memcg_state(memcg, NR_SHMEM, nr_pages);
712 if (compound) {
713 VM_BUG_ON_PAGE(!PageTransHuge(page), page);
714 __mod_memcg_state(memcg, MEMCG_RSS_HUGE, nr_pages);
717 /* pagein of a big page is an event. So, ignore page size */
718 if (nr_pages > 0)
719 __count_memcg_events(memcg, PGPGIN, 1);
720 else {
721 __count_memcg_events(memcg, PGPGOUT, 1);
722 nr_pages = -nr_pages; /* for event */
725 __this_cpu_add(memcg->stat_cpu->nr_page_events, nr_pages);
728 unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
729 int nid, unsigned int lru_mask)
731 struct lruvec *lruvec = mem_cgroup_lruvec(NODE_DATA(nid), memcg);
732 unsigned long nr = 0;
733 enum lru_list lru;
735 VM_BUG_ON((unsigned)nid >= nr_node_ids);
737 for_each_lru(lru) {
738 if (!(BIT(lru) & lru_mask))
739 continue;
740 nr += mem_cgroup_get_lru_size(lruvec, lru);
742 return nr;
745 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
746 unsigned int lru_mask)
748 unsigned long nr = 0;
749 int nid;
751 for_each_node_state(nid, N_MEMORY)
752 nr += mem_cgroup_node_nr_lru_pages(memcg, nid, lru_mask);
753 return nr;
756 static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
757 enum mem_cgroup_events_target target)
759 unsigned long val, next;
761 val = __this_cpu_read(memcg->stat_cpu->nr_page_events);
762 next = __this_cpu_read(memcg->stat_cpu->targets[target]);
763 /* from time_after() in jiffies.h */
764 if ((long)(next - val) < 0) {
765 switch (target) {
766 case MEM_CGROUP_TARGET_THRESH:
767 next = val + THRESHOLDS_EVENTS_TARGET;
768 break;
769 case MEM_CGROUP_TARGET_SOFTLIMIT:
770 next = val + SOFTLIMIT_EVENTS_TARGET;
771 break;
772 case MEM_CGROUP_TARGET_NUMAINFO:
773 next = val + NUMAINFO_EVENTS_TARGET;
774 break;
775 default:
776 break;
778 __this_cpu_write(memcg->stat_cpu->targets[target], next);
779 return true;
781 return false;
785 * Check events in order.
788 static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
790 /* threshold event is triggered in finer grain than soft limit */
791 if (unlikely(mem_cgroup_event_ratelimit(memcg,
792 MEM_CGROUP_TARGET_THRESH))) {
793 bool do_softlimit;
794 bool do_numainfo __maybe_unused;
796 do_softlimit = mem_cgroup_event_ratelimit(memcg,
797 MEM_CGROUP_TARGET_SOFTLIMIT);
798 #if MAX_NUMNODES > 1
799 do_numainfo = mem_cgroup_event_ratelimit(memcg,
800 MEM_CGROUP_TARGET_NUMAINFO);
801 #endif
802 mem_cgroup_threshold(memcg);
803 if (unlikely(do_softlimit))
804 mem_cgroup_update_tree(memcg, page);
805 #if MAX_NUMNODES > 1
806 if (unlikely(do_numainfo))
807 atomic_inc(&memcg->numainfo_events);
808 #endif
812 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
815 * mm_update_next_owner() may clear mm->owner to NULL
816 * if it races with swapoff, page migration, etc.
817 * So this can be called with p == NULL.
819 if (unlikely(!p))
820 return NULL;
822 return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
824 EXPORT_SYMBOL(mem_cgroup_from_task);
827 * get_mem_cgroup_from_mm: Obtain a reference on given mm_struct's memcg.
828 * @mm: mm from which memcg should be extracted. It can be NULL.
830 * Obtain a reference on mm->memcg and returns it if successful. Otherwise
831 * root_mem_cgroup is returned. However if mem_cgroup is disabled, NULL is
832 * returned.
834 struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
836 struct mem_cgroup *memcg;
838 if (mem_cgroup_disabled())
839 return NULL;
841 rcu_read_lock();
842 do {
844 * Page cache insertions can happen withou an
845 * actual mm context, e.g. during disk probing
846 * on boot, loopback IO, acct() writes etc.
848 if (unlikely(!mm))
849 memcg = root_mem_cgroup;
850 else {
851 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
852 if (unlikely(!memcg))
853 memcg = root_mem_cgroup;
855 } while (!css_tryget_online(&memcg->css));
856 rcu_read_unlock();
857 return memcg;
859 EXPORT_SYMBOL(get_mem_cgroup_from_mm);
862 * get_mem_cgroup_from_page: Obtain a reference on given page's memcg.
863 * @page: page from which memcg should be extracted.
865 * Obtain a reference on page->memcg and returns it if successful. Otherwise
866 * root_mem_cgroup is returned.
868 struct mem_cgroup *get_mem_cgroup_from_page(struct page *page)
870 struct mem_cgroup *memcg = page->mem_cgroup;
872 if (mem_cgroup_disabled())
873 return NULL;
875 rcu_read_lock();
876 if (!memcg || !css_tryget_online(&memcg->css))
877 memcg = root_mem_cgroup;
878 rcu_read_unlock();
879 return memcg;
881 EXPORT_SYMBOL(get_mem_cgroup_from_page);
884 * If current->active_memcg is non-NULL, do not fallback to current->mm->memcg.
886 static __always_inline struct mem_cgroup *get_mem_cgroup_from_current(void)
888 if (unlikely(current->active_memcg)) {
889 struct mem_cgroup *memcg = root_mem_cgroup;
891 rcu_read_lock();
892 if (css_tryget_online(&current->active_memcg->css))
893 memcg = current->active_memcg;
894 rcu_read_unlock();
895 return memcg;
897 return get_mem_cgroup_from_mm(current->mm);
901 * mem_cgroup_iter - iterate over memory cgroup hierarchy
902 * @root: hierarchy root
903 * @prev: previously returned memcg, NULL on first invocation
904 * @reclaim: cookie for shared reclaim walks, NULL for full walks
906 * Returns references to children of the hierarchy below @root, or
907 * @root itself, or %NULL after a full round-trip.
909 * Caller must pass the return value in @prev on subsequent
910 * invocations for reference counting, or use mem_cgroup_iter_break()
911 * to cancel a hierarchy walk before the round-trip is complete.
913 * Reclaimers can specify a node and a priority level in @reclaim to
914 * divide up the memcgs in the hierarchy among all concurrent
915 * reclaimers operating on the same node and priority.
917 struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
918 struct mem_cgroup *prev,
919 struct mem_cgroup_reclaim_cookie *reclaim)
921 struct mem_cgroup_reclaim_iter *uninitialized_var(iter);
922 struct cgroup_subsys_state *css = NULL;
923 struct mem_cgroup *memcg = NULL;
924 struct mem_cgroup *pos = NULL;
926 if (mem_cgroup_disabled())
927 return NULL;
929 if (!root)
930 root = root_mem_cgroup;
932 if (prev && !reclaim)
933 pos = prev;
935 if (!root->use_hierarchy && root != root_mem_cgroup) {
936 if (prev)
937 goto out;
938 return root;
941 rcu_read_lock();
943 if (reclaim) {
944 struct mem_cgroup_per_node *mz;
946 mz = mem_cgroup_nodeinfo(root, reclaim->pgdat->node_id);
947 iter = &mz->iter[reclaim->priority];
949 if (prev && reclaim->generation != iter->generation)
950 goto out_unlock;
952 while (1) {
953 pos = READ_ONCE(iter->position);
954 if (!pos || css_tryget(&pos->css))
955 break;
957 * css reference reached zero, so iter->position will
958 * be cleared by ->css_released. However, we should not
959 * rely on this happening soon, because ->css_released
960 * is called from a work queue, and by busy-waiting we
961 * might block it. So we clear iter->position right
962 * away.
964 (void)cmpxchg(&iter->position, pos, NULL);
968 if (pos)
969 css = &pos->css;
971 for (;;) {
972 css = css_next_descendant_pre(css, &root->css);
973 if (!css) {
975 * Reclaimers share the hierarchy walk, and a
976 * new one might jump in right at the end of
977 * the hierarchy - make sure they see at least
978 * one group and restart from the beginning.
980 if (!prev)
981 continue;
982 break;
986 * Verify the css and acquire a reference. The root
987 * is provided by the caller, so we know it's alive
988 * and kicking, and don't take an extra reference.
990 memcg = mem_cgroup_from_css(css);
992 if (css == &root->css)
993 break;
995 if (css_tryget(css))
996 break;
998 memcg = NULL;
1001 if (reclaim) {
1003 * The position could have already been updated by a competing
1004 * thread, so check that the value hasn't changed since we read
1005 * it to avoid reclaiming from the same cgroup twice.
1007 (void)cmpxchg(&iter->position, pos, memcg);
1009 if (pos)
1010 css_put(&pos->css);
1012 if (!memcg)
1013 iter->generation++;
1014 else if (!prev)
1015 reclaim->generation = iter->generation;
1018 out_unlock:
1019 rcu_read_unlock();
1020 out:
1021 if (prev && prev != root)
1022 css_put(&prev->css);
1024 return memcg;
1028 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1029 * @root: hierarchy root
1030 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1032 void mem_cgroup_iter_break(struct mem_cgroup *root,
1033 struct mem_cgroup *prev)
1035 if (!root)
1036 root = root_mem_cgroup;
1037 if (prev && prev != root)
1038 css_put(&prev->css);
1041 static void invalidate_reclaim_iterators(struct mem_cgroup *dead_memcg)
1043 struct mem_cgroup *memcg = dead_memcg;
1044 struct mem_cgroup_reclaim_iter *iter;
1045 struct mem_cgroup_per_node *mz;
1046 int nid;
1047 int i;
1049 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
1050 for_each_node(nid) {
1051 mz = mem_cgroup_nodeinfo(memcg, nid);
1052 for (i = 0; i <= DEF_PRIORITY; i++) {
1053 iter = &mz->iter[i];
1054 cmpxchg(&iter->position,
1055 dead_memcg, NULL);
1062 * mem_cgroup_scan_tasks - iterate over tasks of a memory cgroup hierarchy
1063 * @memcg: hierarchy root
1064 * @fn: function to call for each task
1065 * @arg: argument passed to @fn
1067 * This function iterates over tasks attached to @memcg or to any of its
1068 * descendants and calls @fn for each task. If @fn returns a non-zero
1069 * value, the function breaks the iteration loop and returns the value.
1070 * Otherwise, it will iterate over all tasks and return 0.
1072 * This function must not be called for the root memory cgroup.
1074 int mem_cgroup_scan_tasks(struct mem_cgroup *memcg,
1075 int (*fn)(struct task_struct *, void *), void *arg)
1077 struct mem_cgroup *iter;
1078 int ret = 0;
1080 BUG_ON(memcg == root_mem_cgroup);
1082 for_each_mem_cgroup_tree(iter, memcg) {
1083 struct css_task_iter it;
1084 struct task_struct *task;
1086 css_task_iter_start(&iter->css, 0, &it);
1087 while (!ret && (task = css_task_iter_next(&it)))
1088 ret = fn(task, arg);
1089 css_task_iter_end(&it);
1090 if (ret) {
1091 mem_cgroup_iter_break(memcg, iter);
1092 break;
1095 return ret;
1099 * mem_cgroup_page_lruvec - return lruvec for isolating/putting an LRU page
1100 * @page: the page
1101 * @pgdat: pgdat of the page
1103 * This function is only safe when following the LRU page isolation
1104 * and putback protocol: the LRU lock must be held, and the page must
1105 * either be PageLRU() or the caller must have isolated/allocated it.
1107 struct lruvec *mem_cgroup_page_lruvec(struct page *page, struct pglist_data *pgdat)
1109 struct mem_cgroup_per_node *mz;
1110 struct mem_cgroup *memcg;
1111 struct lruvec *lruvec;
1113 if (mem_cgroup_disabled()) {
1114 lruvec = &pgdat->lruvec;
1115 goto out;
1118 memcg = page->mem_cgroup;
1120 * Swapcache readahead pages are added to the LRU - and
1121 * possibly migrated - before they are charged.
1123 if (!memcg)
1124 memcg = root_mem_cgroup;
1126 mz = mem_cgroup_page_nodeinfo(memcg, page);
1127 lruvec = &mz->lruvec;
1128 out:
1130 * Since a node can be onlined after the mem_cgroup was created,
1131 * we have to be prepared to initialize lruvec->zone here;
1132 * and if offlined then reonlined, we need to reinitialize it.
1134 if (unlikely(lruvec->pgdat != pgdat))
1135 lruvec->pgdat = pgdat;
1136 return lruvec;
1140 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1141 * @lruvec: mem_cgroup per zone lru vector
1142 * @lru: index of lru list the page is sitting on
1143 * @zid: zone id of the accounted pages
1144 * @nr_pages: positive when adding or negative when removing
1146 * This function must be called under lru_lock, just before a page is added
1147 * to or just after a page is removed from an lru list (that ordering being
1148 * so as to allow it to check that lru_size 0 is consistent with list_empty).
1150 void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
1151 int zid, int nr_pages)
1153 struct mem_cgroup_per_node *mz;
1154 unsigned long *lru_size;
1155 long size;
1157 if (mem_cgroup_disabled())
1158 return;
1160 mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
1161 lru_size = &mz->lru_zone_size[zid][lru];
1163 if (nr_pages < 0)
1164 *lru_size += nr_pages;
1166 size = *lru_size;
1167 if (WARN_ONCE(size < 0,
1168 "%s(%p, %d, %d): lru_size %ld\n",
1169 __func__, lruvec, lru, nr_pages, size)) {
1170 VM_BUG_ON(1);
1171 *lru_size = 0;
1174 if (nr_pages > 0)
1175 *lru_size += nr_pages;
1178 bool task_in_mem_cgroup(struct task_struct *task, struct mem_cgroup *memcg)
1180 struct mem_cgroup *task_memcg;
1181 struct task_struct *p;
1182 bool ret;
1184 p = find_lock_task_mm(task);
1185 if (p) {
1186 task_memcg = get_mem_cgroup_from_mm(p->mm);
1187 task_unlock(p);
1188 } else {
1190 * All threads may have already detached their mm's, but the oom
1191 * killer still needs to detect if they have already been oom
1192 * killed to prevent needlessly killing additional tasks.
1194 rcu_read_lock();
1195 task_memcg = mem_cgroup_from_task(task);
1196 css_get(&task_memcg->css);
1197 rcu_read_unlock();
1199 ret = mem_cgroup_is_descendant(task_memcg, memcg);
1200 css_put(&task_memcg->css);
1201 return ret;
1205 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1206 * @memcg: the memory cgroup
1208 * Returns the maximum amount of memory @mem can be charged with, in
1209 * pages.
1211 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1213 unsigned long margin = 0;
1214 unsigned long count;
1215 unsigned long limit;
1217 count = page_counter_read(&memcg->memory);
1218 limit = READ_ONCE(memcg->memory.max);
1219 if (count < limit)
1220 margin = limit - count;
1222 if (do_memsw_account()) {
1223 count = page_counter_read(&memcg->memsw);
1224 limit = READ_ONCE(memcg->memsw.max);
1225 if (count <= limit)
1226 margin = min(margin, limit - count);
1227 else
1228 margin = 0;
1231 return margin;
1235 * A routine for checking "mem" is under move_account() or not.
1237 * Checking a cgroup is mc.from or mc.to or under hierarchy of
1238 * moving cgroups. This is for waiting at high-memory pressure
1239 * caused by "move".
1241 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1243 struct mem_cgroup *from;
1244 struct mem_cgroup *to;
1245 bool ret = false;
1247 * Unlike task_move routines, we access mc.to, mc.from not under
1248 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1250 spin_lock(&mc.lock);
1251 from = mc.from;
1252 to = mc.to;
1253 if (!from)
1254 goto unlock;
1256 ret = mem_cgroup_is_descendant(from, memcg) ||
1257 mem_cgroup_is_descendant(to, memcg);
1258 unlock:
1259 spin_unlock(&mc.lock);
1260 return ret;
1263 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1265 if (mc.moving_task && current != mc.moving_task) {
1266 if (mem_cgroup_under_move(memcg)) {
1267 DEFINE_WAIT(wait);
1268 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1269 /* moving charge context might have finished. */
1270 if (mc.moving_task)
1271 schedule();
1272 finish_wait(&mc.waitq, &wait);
1273 return true;
1276 return false;
1279 static const unsigned int memcg1_stats[] = {
1280 MEMCG_CACHE,
1281 MEMCG_RSS,
1282 MEMCG_RSS_HUGE,
1283 NR_SHMEM,
1284 NR_FILE_MAPPED,
1285 NR_FILE_DIRTY,
1286 NR_WRITEBACK,
1287 MEMCG_SWAP,
1290 static const char *const memcg1_stat_names[] = {
1291 "cache",
1292 "rss",
1293 "rss_huge",
1294 "shmem",
1295 "mapped_file",
1296 "dirty",
1297 "writeback",
1298 "swap",
1301 #define K(x) ((x) << (PAGE_SHIFT-10))
1303 * mem_cgroup_print_oom_context: Print OOM information relevant to
1304 * memory controller.
1305 * @memcg: The memory cgroup that went over limit
1306 * @p: Task that is going to be killed
1308 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1309 * enabled
1311 void mem_cgroup_print_oom_context(struct mem_cgroup *memcg, struct task_struct *p)
1313 rcu_read_lock();
1315 if (memcg) {
1316 pr_cont(",oom_memcg=");
1317 pr_cont_cgroup_path(memcg->css.cgroup);
1318 } else
1319 pr_cont(",global_oom");
1320 if (p) {
1321 pr_cont(",task_memcg=");
1322 pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
1324 rcu_read_unlock();
1328 * mem_cgroup_print_oom_meminfo: Print OOM memory information relevant to
1329 * memory controller.
1330 * @memcg: The memory cgroup that went over limit
1332 void mem_cgroup_print_oom_meminfo(struct mem_cgroup *memcg)
1334 struct mem_cgroup *iter;
1335 unsigned int i;
1337 pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
1338 K((u64)page_counter_read(&memcg->memory)),
1339 K((u64)memcg->memory.max), memcg->memory.failcnt);
1340 pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
1341 K((u64)page_counter_read(&memcg->memsw)),
1342 K((u64)memcg->memsw.max), memcg->memsw.failcnt);
1343 pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
1344 K((u64)page_counter_read(&memcg->kmem)),
1345 K((u64)memcg->kmem.max), memcg->kmem.failcnt);
1347 for_each_mem_cgroup_tree(iter, memcg) {
1348 pr_info("Memory cgroup stats for ");
1349 pr_cont_cgroup_path(iter->css.cgroup);
1350 pr_cont(":");
1352 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
1353 if (memcg1_stats[i] == MEMCG_SWAP && !do_swap_account)
1354 continue;
1355 pr_cont(" %s:%luKB", memcg1_stat_names[i],
1356 K(memcg_page_state(iter, memcg1_stats[i])));
1359 for (i = 0; i < NR_LRU_LISTS; i++)
1360 pr_cont(" %s:%luKB", mem_cgroup_lru_names[i],
1361 K(mem_cgroup_nr_lru_pages(iter, BIT(i))));
1363 pr_cont("\n");
1368 * Return the memory (and swap, if configured) limit for a memcg.
1370 unsigned long mem_cgroup_get_max(struct mem_cgroup *memcg)
1372 unsigned long max;
1374 max = memcg->memory.max;
1375 if (mem_cgroup_swappiness(memcg)) {
1376 unsigned long memsw_max;
1377 unsigned long swap_max;
1379 memsw_max = memcg->memsw.max;
1380 swap_max = memcg->swap.max;
1381 swap_max = min(swap_max, (unsigned long)total_swap_pages);
1382 max = min(max + swap_max, memsw_max);
1384 return max;
1387 static bool mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
1388 int order)
1390 struct oom_control oc = {
1391 .zonelist = NULL,
1392 .nodemask = NULL,
1393 .memcg = memcg,
1394 .gfp_mask = gfp_mask,
1395 .order = order,
1397 bool ret;
1399 if (mutex_lock_killable(&oom_lock))
1400 return true;
1402 * A few threads which were not waiting at mutex_lock_killable() can
1403 * fail to bail out. Therefore, check again after holding oom_lock.
1405 ret = should_force_charge() || out_of_memory(&oc);
1406 mutex_unlock(&oom_lock);
1407 return ret;
1410 #if MAX_NUMNODES > 1
1413 * test_mem_cgroup_node_reclaimable
1414 * @memcg: the target memcg
1415 * @nid: the node ID to be checked.
1416 * @noswap : specify true here if the user wants flle only information.
1418 * This function returns whether the specified memcg contains any
1419 * reclaimable pages on a node. Returns true if there are any reclaimable
1420 * pages in the node.
1422 static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *memcg,
1423 int nid, bool noswap)
1425 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_FILE))
1426 return true;
1427 if (noswap || !total_swap_pages)
1428 return false;
1429 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_ANON))
1430 return true;
1431 return false;
1436 * Always updating the nodemask is not very good - even if we have an empty
1437 * list or the wrong list here, we can start from some node and traverse all
1438 * nodes based on the zonelist. So update the list loosely once per 10 secs.
1441 static void mem_cgroup_may_update_nodemask(struct mem_cgroup *memcg)
1443 int nid;
1445 * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
1446 * pagein/pageout changes since the last update.
1448 if (!atomic_read(&memcg->numainfo_events))
1449 return;
1450 if (atomic_inc_return(&memcg->numainfo_updating) > 1)
1451 return;
1453 /* make a nodemask where this memcg uses memory from */
1454 memcg->scan_nodes = node_states[N_MEMORY];
1456 for_each_node_mask(nid, node_states[N_MEMORY]) {
1458 if (!test_mem_cgroup_node_reclaimable(memcg, nid, false))
1459 node_clear(nid, memcg->scan_nodes);
1462 atomic_set(&memcg->numainfo_events, 0);
1463 atomic_set(&memcg->numainfo_updating, 0);
1467 * Selecting a node where we start reclaim from. Because what we need is just
1468 * reducing usage counter, start from anywhere is O,K. Considering
1469 * memory reclaim from current node, there are pros. and cons.
1471 * Freeing memory from current node means freeing memory from a node which
1472 * we'll use or we've used. So, it may make LRU bad. And if several threads
1473 * hit limits, it will see a contention on a node. But freeing from remote
1474 * node means more costs for memory reclaim because of memory latency.
1476 * Now, we use round-robin. Better algorithm is welcomed.
1478 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1480 int node;
1482 mem_cgroup_may_update_nodemask(memcg);
1483 node = memcg->last_scanned_node;
1485 node = next_node_in(node, memcg->scan_nodes);
1487 * mem_cgroup_may_update_nodemask might have seen no reclaimmable pages
1488 * last time it really checked all the LRUs due to rate limiting.
1489 * Fallback to the current node in that case for simplicity.
1491 if (unlikely(node == MAX_NUMNODES))
1492 node = numa_node_id();
1494 memcg->last_scanned_node = node;
1495 return node;
1497 #else
1498 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1500 return 0;
1502 #endif
1504 static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
1505 pg_data_t *pgdat,
1506 gfp_t gfp_mask,
1507 unsigned long *total_scanned)
1509 struct mem_cgroup *victim = NULL;
1510 int total = 0;
1511 int loop = 0;
1512 unsigned long excess;
1513 unsigned long nr_scanned;
1514 struct mem_cgroup_reclaim_cookie reclaim = {
1515 .pgdat = pgdat,
1516 .priority = 0,
1519 excess = soft_limit_excess(root_memcg);
1521 while (1) {
1522 victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
1523 if (!victim) {
1524 loop++;
1525 if (loop >= 2) {
1527 * If we have not been able to reclaim
1528 * anything, it might because there are
1529 * no reclaimable pages under this hierarchy
1531 if (!total)
1532 break;
1534 * We want to do more targeted reclaim.
1535 * excess >> 2 is not to excessive so as to
1536 * reclaim too much, nor too less that we keep
1537 * coming back to reclaim from this cgroup
1539 if (total >= (excess >> 2) ||
1540 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
1541 break;
1543 continue;
1545 total += mem_cgroup_shrink_node(victim, gfp_mask, false,
1546 pgdat, &nr_scanned);
1547 *total_scanned += nr_scanned;
1548 if (!soft_limit_excess(root_memcg))
1549 break;
1551 mem_cgroup_iter_break(root_memcg, victim);
1552 return total;
1555 #ifdef CONFIG_LOCKDEP
1556 static struct lockdep_map memcg_oom_lock_dep_map = {
1557 .name = "memcg_oom_lock",
1559 #endif
1561 static DEFINE_SPINLOCK(memcg_oom_lock);
1564 * Check OOM-Killer is already running under our hierarchy.
1565 * If someone is running, return false.
1567 static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
1569 struct mem_cgroup *iter, *failed = NULL;
1571 spin_lock(&memcg_oom_lock);
1573 for_each_mem_cgroup_tree(iter, memcg) {
1574 if (iter->oom_lock) {
1576 * this subtree of our hierarchy is already locked
1577 * so we cannot give a lock.
1579 failed = iter;
1580 mem_cgroup_iter_break(memcg, iter);
1581 break;
1582 } else
1583 iter->oom_lock = true;
1586 if (failed) {
1588 * OK, we failed to lock the whole subtree so we have
1589 * to clean up what we set up to the failing subtree
1591 for_each_mem_cgroup_tree(iter, memcg) {
1592 if (iter == failed) {
1593 mem_cgroup_iter_break(memcg, iter);
1594 break;
1596 iter->oom_lock = false;
1598 } else
1599 mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_);
1601 spin_unlock(&memcg_oom_lock);
1603 return !failed;
1606 static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
1608 struct mem_cgroup *iter;
1610 spin_lock(&memcg_oom_lock);
1611 mutex_release(&memcg_oom_lock_dep_map, 1, _RET_IP_);
1612 for_each_mem_cgroup_tree(iter, memcg)
1613 iter->oom_lock = false;
1614 spin_unlock(&memcg_oom_lock);
1617 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
1619 struct mem_cgroup *iter;
1621 spin_lock(&memcg_oom_lock);
1622 for_each_mem_cgroup_tree(iter, memcg)
1623 iter->under_oom++;
1624 spin_unlock(&memcg_oom_lock);
1627 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
1629 struct mem_cgroup *iter;
1632 * When a new child is created while the hierarchy is under oom,
1633 * mem_cgroup_oom_lock() may not be called. Watch for underflow.
1635 spin_lock(&memcg_oom_lock);
1636 for_each_mem_cgroup_tree(iter, memcg)
1637 if (iter->under_oom > 0)
1638 iter->under_oom--;
1639 spin_unlock(&memcg_oom_lock);
1642 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1644 struct oom_wait_info {
1645 struct mem_cgroup *memcg;
1646 wait_queue_entry_t wait;
1649 static int memcg_oom_wake_function(wait_queue_entry_t *wait,
1650 unsigned mode, int sync, void *arg)
1652 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
1653 struct mem_cgroup *oom_wait_memcg;
1654 struct oom_wait_info *oom_wait_info;
1656 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1657 oom_wait_memcg = oom_wait_info->memcg;
1659 if (!mem_cgroup_is_descendant(wake_memcg, oom_wait_memcg) &&
1660 !mem_cgroup_is_descendant(oom_wait_memcg, wake_memcg))
1661 return 0;
1662 return autoremove_wake_function(wait, mode, sync, arg);
1665 static void memcg_oom_recover(struct mem_cgroup *memcg)
1668 * For the following lockless ->under_oom test, the only required
1669 * guarantee is that it must see the state asserted by an OOM when
1670 * this function is called as a result of userland actions
1671 * triggered by the notification of the OOM. This is trivially
1672 * achieved by invoking mem_cgroup_mark_under_oom() before
1673 * triggering notification.
1675 if (memcg && memcg->under_oom)
1676 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
1679 enum oom_status {
1680 OOM_SUCCESS,
1681 OOM_FAILED,
1682 OOM_ASYNC,
1683 OOM_SKIPPED
1686 static enum oom_status mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
1688 enum oom_status ret;
1689 bool locked;
1691 if (order > PAGE_ALLOC_COSTLY_ORDER)
1692 return OOM_SKIPPED;
1694 memcg_memory_event(memcg, MEMCG_OOM);
1697 * We are in the middle of the charge context here, so we
1698 * don't want to block when potentially sitting on a callstack
1699 * that holds all kinds of filesystem and mm locks.
1701 * cgroup1 allows disabling the OOM killer and waiting for outside
1702 * handling until the charge can succeed; remember the context and put
1703 * the task to sleep at the end of the page fault when all locks are
1704 * released.
1706 * On the other hand, in-kernel OOM killer allows for an async victim
1707 * memory reclaim (oom_reaper) and that means that we are not solely
1708 * relying on the oom victim to make a forward progress and we can
1709 * invoke the oom killer here.
1711 * Please note that mem_cgroup_out_of_memory might fail to find a
1712 * victim and then we have to bail out from the charge path.
1714 if (memcg->oom_kill_disable) {
1715 if (!current->in_user_fault)
1716 return OOM_SKIPPED;
1717 css_get(&memcg->css);
1718 current->memcg_in_oom = memcg;
1719 current->memcg_oom_gfp_mask = mask;
1720 current->memcg_oom_order = order;
1722 return OOM_ASYNC;
1725 mem_cgroup_mark_under_oom(memcg);
1727 locked = mem_cgroup_oom_trylock(memcg);
1729 if (locked)
1730 mem_cgroup_oom_notify(memcg);
1732 mem_cgroup_unmark_under_oom(memcg);
1733 if (mem_cgroup_out_of_memory(memcg, mask, order))
1734 ret = OOM_SUCCESS;
1735 else
1736 ret = OOM_FAILED;
1738 if (locked)
1739 mem_cgroup_oom_unlock(memcg);
1741 return ret;
1745 * mem_cgroup_oom_synchronize - complete memcg OOM handling
1746 * @handle: actually kill/wait or just clean up the OOM state
1748 * This has to be called at the end of a page fault if the memcg OOM
1749 * handler was enabled.
1751 * Memcg supports userspace OOM handling where failed allocations must
1752 * sleep on a waitqueue until the userspace task resolves the
1753 * situation. Sleeping directly in the charge context with all kinds
1754 * of locks held is not a good idea, instead we remember an OOM state
1755 * in the task and mem_cgroup_oom_synchronize() has to be called at
1756 * the end of the page fault to complete the OOM handling.
1758 * Returns %true if an ongoing memcg OOM situation was detected and
1759 * completed, %false otherwise.
1761 bool mem_cgroup_oom_synchronize(bool handle)
1763 struct mem_cgroup *memcg = current->memcg_in_oom;
1764 struct oom_wait_info owait;
1765 bool locked;
1767 /* OOM is global, do not handle */
1768 if (!memcg)
1769 return false;
1771 if (!handle)
1772 goto cleanup;
1774 owait.memcg = memcg;
1775 owait.wait.flags = 0;
1776 owait.wait.func = memcg_oom_wake_function;
1777 owait.wait.private = current;
1778 INIT_LIST_HEAD(&owait.wait.entry);
1780 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
1781 mem_cgroup_mark_under_oom(memcg);
1783 locked = mem_cgroup_oom_trylock(memcg);
1785 if (locked)
1786 mem_cgroup_oom_notify(memcg);
1788 if (locked && !memcg->oom_kill_disable) {
1789 mem_cgroup_unmark_under_oom(memcg);
1790 finish_wait(&memcg_oom_waitq, &owait.wait);
1791 mem_cgroup_out_of_memory(memcg, current->memcg_oom_gfp_mask,
1792 current->memcg_oom_order);
1793 } else {
1794 schedule();
1795 mem_cgroup_unmark_under_oom(memcg);
1796 finish_wait(&memcg_oom_waitq, &owait.wait);
1799 if (locked) {
1800 mem_cgroup_oom_unlock(memcg);
1802 * There is no guarantee that an OOM-lock contender
1803 * sees the wakeups triggered by the OOM kill
1804 * uncharges. Wake any sleepers explicitely.
1806 memcg_oom_recover(memcg);
1808 cleanup:
1809 current->memcg_in_oom = NULL;
1810 css_put(&memcg->css);
1811 return true;
1815 * mem_cgroup_get_oom_group - get a memory cgroup to clean up after OOM
1816 * @victim: task to be killed by the OOM killer
1817 * @oom_domain: memcg in case of memcg OOM, NULL in case of system-wide OOM
1819 * Returns a pointer to a memory cgroup, which has to be cleaned up
1820 * by killing all belonging OOM-killable tasks.
1822 * Caller has to call mem_cgroup_put() on the returned non-NULL memcg.
1824 struct mem_cgroup *mem_cgroup_get_oom_group(struct task_struct *victim,
1825 struct mem_cgroup *oom_domain)
1827 struct mem_cgroup *oom_group = NULL;
1828 struct mem_cgroup *memcg;
1830 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
1831 return NULL;
1833 if (!oom_domain)
1834 oom_domain = root_mem_cgroup;
1836 rcu_read_lock();
1838 memcg = mem_cgroup_from_task(victim);
1839 if (memcg == root_mem_cgroup)
1840 goto out;
1843 * Traverse the memory cgroup hierarchy from the victim task's
1844 * cgroup up to the OOMing cgroup (or root) to find the
1845 * highest-level memory cgroup with oom.group set.
1847 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
1848 if (memcg->oom_group)
1849 oom_group = memcg;
1851 if (memcg == oom_domain)
1852 break;
1855 if (oom_group)
1856 css_get(&oom_group->css);
1857 out:
1858 rcu_read_unlock();
1860 return oom_group;
1863 void mem_cgroup_print_oom_group(struct mem_cgroup *memcg)
1865 pr_info("Tasks in ");
1866 pr_cont_cgroup_path(memcg->css.cgroup);
1867 pr_cont(" are going to be killed due to memory.oom.group set\n");
1871 * lock_page_memcg - lock a page->mem_cgroup binding
1872 * @page: the page
1874 * This function protects unlocked LRU pages from being moved to
1875 * another cgroup.
1877 * It ensures lifetime of the returned memcg. Caller is responsible
1878 * for the lifetime of the page; __unlock_page_memcg() is available
1879 * when @page might get freed inside the locked section.
1881 struct mem_cgroup *lock_page_memcg(struct page *page)
1883 struct mem_cgroup *memcg;
1884 unsigned long flags;
1887 * The RCU lock is held throughout the transaction. The fast
1888 * path can get away without acquiring the memcg->move_lock
1889 * because page moving starts with an RCU grace period.
1891 * The RCU lock also protects the memcg from being freed when
1892 * the page state that is going to change is the only thing
1893 * preventing the page itself from being freed. E.g. writeback
1894 * doesn't hold a page reference and relies on PG_writeback to
1895 * keep off truncation, migration and so forth.
1897 rcu_read_lock();
1899 if (mem_cgroup_disabled())
1900 return NULL;
1901 again:
1902 memcg = page->mem_cgroup;
1903 if (unlikely(!memcg))
1904 return NULL;
1906 if (atomic_read(&memcg->moving_account) <= 0)
1907 return memcg;
1909 spin_lock_irqsave(&memcg->move_lock, flags);
1910 if (memcg != page->mem_cgroup) {
1911 spin_unlock_irqrestore(&memcg->move_lock, flags);
1912 goto again;
1916 * When charge migration first begins, we can have locked and
1917 * unlocked page stat updates happening concurrently. Track
1918 * the task who has the lock for unlock_page_memcg().
1920 memcg->move_lock_task = current;
1921 memcg->move_lock_flags = flags;
1923 return memcg;
1925 EXPORT_SYMBOL(lock_page_memcg);
1928 * __unlock_page_memcg - unlock and unpin a memcg
1929 * @memcg: the memcg
1931 * Unlock and unpin a memcg returned by lock_page_memcg().
1933 void __unlock_page_memcg(struct mem_cgroup *memcg)
1935 if (memcg && memcg->move_lock_task == current) {
1936 unsigned long flags = memcg->move_lock_flags;
1938 memcg->move_lock_task = NULL;
1939 memcg->move_lock_flags = 0;
1941 spin_unlock_irqrestore(&memcg->move_lock, flags);
1944 rcu_read_unlock();
1948 * unlock_page_memcg - unlock a page->mem_cgroup binding
1949 * @page: the page
1951 void unlock_page_memcg(struct page *page)
1953 __unlock_page_memcg(page->mem_cgroup);
1955 EXPORT_SYMBOL(unlock_page_memcg);
1957 struct memcg_stock_pcp {
1958 struct mem_cgroup *cached; /* this never be root cgroup */
1959 unsigned int nr_pages;
1960 struct work_struct work;
1961 unsigned long flags;
1962 #define FLUSHING_CACHED_CHARGE 0
1964 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
1965 static DEFINE_MUTEX(percpu_charge_mutex);
1968 * consume_stock: Try to consume stocked charge on this cpu.
1969 * @memcg: memcg to consume from.
1970 * @nr_pages: how many pages to charge.
1972 * The charges will only happen if @memcg matches the current cpu's memcg
1973 * stock, and at least @nr_pages are available in that stock. Failure to
1974 * service an allocation will refill the stock.
1976 * returns true if successful, false otherwise.
1978 static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
1980 struct memcg_stock_pcp *stock;
1981 unsigned long flags;
1982 bool ret = false;
1984 if (nr_pages > MEMCG_CHARGE_BATCH)
1985 return ret;
1987 local_irq_save(flags);
1989 stock = this_cpu_ptr(&memcg_stock);
1990 if (memcg == stock->cached && stock->nr_pages >= nr_pages) {
1991 stock->nr_pages -= nr_pages;
1992 ret = true;
1995 local_irq_restore(flags);
1997 return ret;
2001 * Returns stocks cached in percpu and reset cached information.
2003 static void drain_stock(struct memcg_stock_pcp *stock)
2005 struct mem_cgroup *old = stock->cached;
2007 if (stock->nr_pages) {
2008 page_counter_uncharge(&old->memory, stock->nr_pages);
2009 if (do_memsw_account())
2010 page_counter_uncharge(&old->memsw, stock->nr_pages);
2011 css_put_many(&old->css, stock->nr_pages);
2012 stock->nr_pages = 0;
2014 stock->cached = NULL;
2017 static void drain_local_stock(struct work_struct *dummy)
2019 struct memcg_stock_pcp *stock;
2020 unsigned long flags;
2023 * The only protection from memory hotplug vs. drain_stock races is
2024 * that we always operate on local CPU stock here with IRQ disabled
2026 local_irq_save(flags);
2028 stock = this_cpu_ptr(&memcg_stock);
2029 drain_stock(stock);
2030 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2032 local_irq_restore(flags);
2036 * Cache charges(val) to local per_cpu area.
2037 * This will be consumed by consume_stock() function, later.
2039 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2041 struct memcg_stock_pcp *stock;
2042 unsigned long flags;
2044 local_irq_save(flags);
2046 stock = this_cpu_ptr(&memcg_stock);
2047 if (stock->cached != memcg) { /* reset if necessary */
2048 drain_stock(stock);
2049 stock->cached = memcg;
2051 stock->nr_pages += nr_pages;
2053 if (stock->nr_pages > MEMCG_CHARGE_BATCH)
2054 drain_stock(stock);
2056 local_irq_restore(flags);
2060 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2061 * of the hierarchy under it.
2063 static void drain_all_stock(struct mem_cgroup *root_memcg)
2065 int cpu, curcpu;
2067 /* If someone's already draining, avoid adding running more workers. */
2068 if (!mutex_trylock(&percpu_charge_mutex))
2069 return;
2071 * Notify other cpus that system-wide "drain" is running
2072 * We do not care about races with the cpu hotplug because cpu down
2073 * as well as workers from this path always operate on the local
2074 * per-cpu data. CPU up doesn't touch memcg_stock at all.
2076 curcpu = get_cpu();
2077 for_each_online_cpu(cpu) {
2078 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2079 struct mem_cgroup *memcg;
2081 memcg = stock->cached;
2082 if (!memcg || !stock->nr_pages || !css_tryget(&memcg->css))
2083 continue;
2084 if (!mem_cgroup_is_descendant(memcg, root_memcg)) {
2085 css_put(&memcg->css);
2086 continue;
2088 if (!test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2089 if (cpu == curcpu)
2090 drain_local_stock(&stock->work);
2091 else
2092 schedule_work_on(cpu, &stock->work);
2094 css_put(&memcg->css);
2096 put_cpu();
2097 mutex_unlock(&percpu_charge_mutex);
2100 static int memcg_hotplug_cpu_dead(unsigned int cpu)
2102 struct memcg_stock_pcp *stock;
2103 struct mem_cgroup *memcg;
2105 stock = &per_cpu(memcg_stock, cpu);
2106 drain_stock(stock);
2108 for_each_mem_cgroup(memcg) {
2109 int i;
2111 for (i = 0; i < MEMCG_NR_STAT; i++) {
2112 int nid;
2113 long x;
2115 x = this_cpu_xchg(memcg->stat_cpu->count[i], 0);
2116 if (x)
2117 atomic_long_add(x, &memcg->stat[i]);
2119 if (i >= NR_VM_NODE_STAT_ITEMS)
2120 continue;
2122 for_each_node(nid) {
2123 struct mem_cgroup_per_node *pn;
2125 pn = mem_cgroup_nodeinfo(memcg, nid);
2126 x = this_cpu_xchg(pn->lruvec_stat_cpu->count[i], 0);
2127 if (x)
2128 atomic_long_add(x, &pn->lruvec_stat[i]);
2132 for (i = 0; i < NR_VM_EVENT_ITEMS; i++) {
2133 long x;
2135 x = this_cpu_xchg(memcg->stat_cpu->events[i], 0);
2136 if (x)
2137 atomic_long_add(x, &memcg->events[i]);
2141 return 0;
2144 static void reclaim_high(struct mem_cgroup *memcg,
2145 unsigned int nr_pages,
2146 gfp_t gfp_mask)
2148 do {
2149 if (page_counter_read(&memcg->memory) <= memcg->high)
2150 continue;
2151 memcg_memory_event(memcg, MEMCG_HIGH);
2152 try_to_free_mem_cgroup_pages(memcg, nr_pages, gfp_mask, true);
2153 } while ((memcg = parent_mem_cgroup(memcg)));
2156 static void high_work_func(struct work_struct *work)
2158 struct mem_cgroup *memcg;
2160 memcg = container_of(work, struct mem_cgroup, high_work);
2161 reclaim_high(memcg, MEMCG_CHARGE_BATCH, GFP_KERNEL);
2165 * Scheduled by try_charge() to be executed from the userland return path
2166 * and reclaims memory over the high limit.
2168 void mem_cgroup_handle_over_high(void)
2170 unsigned int nr_pages = current->memcg_nr_pages_over_high;
2171 struct mem_cgroup *memcg;
2173 if (likely(!nr_pages))
2174 return;
2176 memcg = get_mem_cgroup_from_mm(current->mm);
2177 reclaim_high(memcg, nr_pages, GFP_KERNEL);
2178 css_put(&memcg->css);
2179 current->memcg_nr_pages_over_high = 0;
2182 static int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2183 unsigned int nr_pages)
2185 unsigned int batch = max(MEMCG_CHARGE_BATCH, nr_pages);
2186 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
2187 struct mem_cgroup *mem_over_limit;
2188 struct page_counter *counter;
2189 unsigned long nr_reclaimed;
2190 bool may_swap = true;
2191 bool drained = false;
2192 bool oomed = false;
2193 enum oom_status oom_status;
2195 if (mem_cgroup_is_root(memcg))
2196 return 0;
2197 retry:
2198 if (consume_stock(memcg, nr_pages))
2199 return 0;
2201 if (!do_memsw_account() ||
2202 page_counter_try_charge(&memcg->memsw, batch, &counter)) {
2203 if (page_counter_try_charge(&memcg->memory, batch, &counter))
2204 goto done_restock;
2205 if (do_memsw_account())
2206 page_counter_uncharge(&memcg->memsw, batch);
2207 mem_over_limit = mem_cgroup_from_counter(counter, memory);
2208 } else {
2209 mem_over_limit = mem_cgroup_from_counter(counter, memsw);
2210 may_swap = false;
2213 if (batch > nr_pages) {
2214 batch = nr_pages;
2215 goto retry;
2219 * Unlike in global OOM situations, memcg is not in a physical
2220 * memory shortage. Allow dying and OOM-killed tasks to
2221 * bypass the last charges so that they can exit quickly and
2222 * free their memory.
2224 if (unlikely(should_force_charge()))
2225 goto force;
2228 * Prevent unbounded recursion when reclaim operations need to
2229 * allocate memory. This might exceed the limits temporarily,
2230 * but we prefer facilitating memory reclaim and getting back
2231 * under the limit over triggering OOM kills in these cases.
2233 if (unlikely(current->flags & PF_MEMALLOC))
2234 goto force;
2236 if (unlikely(task_in_memcg_oom(current)))
2237 goto nomem;
2239 if (!gfpflags_allow_blocking(gfp_mask))
2240 goto nomem;
2242 memcg_memory_event(mem_over_limit, MEMCG_MAX);
2244 nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
2245 gfp_mask, may_swap);
2247 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2248 goto retry;
2250 if (!drained) {
2251 drain_all_stock(mem_over_limit);
2252 drained = true;
2253 goto retry;
2256 if (gfp_mask & __GFP_NORETRY)
2257 goto nomem;
2259 * Even though the limit is exceeded at this point, reclaim
2260 * may have been able to free some pages. Retry the charge
2261 * before killing the task.
2263 * Only for regular pages, though: huge pages are rather
2264 * unlikely to succeed so close to the limit, and we fall back
2265 * to regular pages anyway in case of failure.
2267 if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
2268 goto retry;
2270 * At task move, charge accounts can be doubly counted. So, it's
2271 * better to wait until the end of task_move if something is going on.
2273 if (mem_cgroup_wait_acct_move(mem_over_limit))
2274 goto retry;
2276 if (nr_retries--)
2277 goto retry;
2279 if (gfp_mask & __GFP_RETRY_MAYFAIL && oomed)
2280 goto nomem;
2282 if (gfp_mask & __GFP_NOFAIL)
2283 goto force;
2285 if (fatal_signal_pending(current))
2286 goto force;
2289 * keep retrying as long as the memcg oom killer is able to make
2290 * a forward progress or bypass the charge if the oom killer
2291 * couldn't make any progress.
2293 oom_status = mem_cgroup_oom(mem_over_limit, gfp_mask,
2294 get_order(nr_pages * PAGE_SIZE));
2295 switch (oom_status) {
2296 case OOM_SUCCESS:
2297 nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
2298 oomed = true;
2299 goto retry;
2300 case OOM_FAILED:
2301 goto force;
2302 default:
2303 goto nomem;
2305 nomem:
2306 if (!(gfp_mask & __GFP_NOFAIL))
2307 return -ENOMEM;
2308 force:
2310 * The allocation either can't fail or will lead to more memory
2311 * being freed very soon. Allow memory usage go over the limit
2312 * temporarily by force charging it.
2314 page_counter_charge(&memcg->memory, nr_pages);
2315 if (do_memsw_account())
2316 page_counter_charge(&memcg->memsw, nr_pages);
2317 css_get_many(&memcg->css, nr_pages);
2319 return 0;
2321 done_restock:
2322 css_get_many(&memcg->css, batch);
2323 if (batch > nr_pages)
2324 refill_stock(memcg, batch - nr_pages);
2327 * If the hierarchy is above the normal consumption range, schedule
2328 * reclaim on returning to userland. We can perform reclaim here
2329 * if __GFP_RECLAIM but let's always punt for simplicity and so that
2330 * GFP_KERNEL can consistently be used during reclaim. @memcg is
2331 * not recorded as it most likely matches current's and won't
2332 * change in the meantime. As high limit is checked again before
2333 * reclaim, the cost of mismatch is negligible.
2335 do {
2336 if (page_counter_read(&memcg->memory) > memcg->high) {
2337 /* Don't bother a random interrupted task */
2338 if (in_interrupt()) {
2339 schedule_work(&memcg->high_work);
2340 break;
2342 current->memcg_nr_pages_over_high += batch;
2343 set_notify_resume(current);
2344 break;
2346 } while ((memcg = parent_mem_cgroup(memcg)));
2348 return 0;
2351 static void cancel_charge(struct mem_cgroup *memcg, unsigned int nr_pages)
2353 if (mem_cgroup_is_root(memcg))
2354 return;
2356 page_counter_uncharge(&memcg->memory, nr_pages);
2357 if (do_memsw_account())
2358 page_counter_uncharge(&memcg->memsw, nr_pages);
2360 css_put_many(&memcg->css, nr_pages);
2363 static void lock_page_lru(struct page *page, int *isolated)
2365 pg_data_t *pgdat = page_pgdat(page);
2367 spin_lock_irq(&pgdat->lru_lock);
2368 if (PageLRU(page)) {
2369 struct lruvec *lruvec;
2371 lruvec = mem_cgroup_page_lruvec(page, pgdat);
2372 ClearPageLRU(page);
2373 del_page_from_lru_list(page, lruvec, page_lru(page));
2374 *isolated = 1;
2375 } else
2376 *isolated = 0;
2379 static void unlock_page_lru(struct page *page, int isolated)
2381 pg_data_t *pgdat = page_pgdat(page);
2383 if (isolated) {
2384 struct lruvec *lruvec;
2386 lruvec = mem_cgroup_page_lruvec(page, pgdat);
2387 VM_BUG_ON_PAGE(PageLRU(page), page);
2388 SetPageLRU(page);
2389 add_page_to_lru_list(page, lruvec, page_lru(page));
2391 spin_unlock_irq(&pgdat->lru_lock);
2394 static void commit_charge(struct page *page, struct mem_cgroup *memcg,
2395 bool lrucare)
2397 int isolated;
2399 VM_BUG_ON_PAGE(page->mem_cgroup, page);
2402 * In some cases, SwapCache and FUSE(splice_buf->radixtree), the page
2403 * may already be on some other mem_cgroup's LRU. Take care of it.
2405 if (lrucare)
2406 lock_page_lru(page, &isolated);
2409 * Nobody should be changing or seriously looking at
2410 * page->mem_cgroup at this point:
2412 * - the page is uncharged
2414 * - the page is off-LRU
2416 * - an anonymous fault has exclusive page access, except for
2417 * a locked page table
2419 * - a page cache insertion, a swapin fault, or a migration
2420 * have the page locked
2422 page->mem_cgroup = memcg;
2424 if (lrucare)
2425 unlock_page_lru(page, isolated);
2428 #ifdef CONFIG_MEMCG_KMEM
2429 static int memcg_alloc_cache_id(void)
2431 int id, size;
2432 int err;
2434 id = ida_simple_get(&memcg_cache_ida,
2435 0, MEMCG_CACHES_MAX_SIZE, GFP_KERNEL);
2436 if (id < 0)
2437 return id;
2439 if (id < memcg_nr_cache_ids)
2440 return id;
2443 * There's no space for the new id in memcg_caches arrays,
2444 * so we have to grow them.
2446 down_write(&memcg_cache_ids_sem);
2448 size = 2 * (id + 1);
2449 if (size < MEMCG_CACHES_MIN_SIZE)
2450 size = MEMCG_CACHES_MIN_SIZE;
2451 else if (size > MEMCG_CACHES_MAX_SIZE)
2452 size = MEMCG_CACHES_MAX_SIZE;
2454 err = memcg_update_all_caches(size);
2455 if (!err)
2456 err = memcg_update_all_list_lrus(size);
2457 if (!err)
2458 memcg_nr_cache_ids = size;
2460 up_write(&memcg_cache_ids_sem);
2462 if (err) {
2463 ida_simple_remove(&memcg_cache_ida, id);
2464 return err;
2466 return id;
2469 static void memcg_free_cache_id(int id)
2471 ida_simple_remove(&memcg_cache_ida, id);
2474 struct memcg_kmem_cache_create_work {
2475 struct mem_cgroup *memcg;
2476 struct kmem_cache *cachep;
2477 struct work_struct work;
2480 static void memcg_kmem_cache_create_func(struct work_struct *w)
2482 struct memcg_kmem_cache_create_work *cw =
2483 container_of(w, struct memcg_kmem_cache_create_work, work);
2484 struct mem_cgroup *memcg = cw->memcg;
2485 struct kmem_cache *cachep = cw->cachep;
2487 memcg_create_kmem_cache(memcg, cachep);
2489 css_put(&memcg->css);
2490 kfree(cw);
2494 * Enqueue the creation of a per-memcg kmem_cache.
2496 static void memcg_schedule_kmem_cache_create(struct mem_cgroup *memcg,
2497 struct kmem_cache *cachep)
2499 struct memcg_kmem_cache_create_work *cw;
2501 cw = kmalloc(sizeof(*cw), GFP_NOWAIT | __GFP_NOWARN);
2502 if (!cw)
2503 return;
2505 css_get(&memcg->css);
2507 cw->memcg = memcg;
2508 cw->cachep = cachep;
2509 INIT_WORK(&cw->work, memcg_kmem_cache_create_func);
2511 queue_work(memcg_kmem_cache_wq, &cw->work);
2514 static inline bool memcg_kmem_bypass(void)
2516 if (in_interrupt() || !current->mm || (current->flags & PF_KTHREAD))
2517 return true;
2518 return false;
2522 * memcg_kmem_get_cache: select the correct per-memcg cache for allocation
2523 * @cachep: the original global kmem cache
2525 * Return the kmem_cache we're supposed to use for a slab allocation.
2526 * We try to use the current memcg's version of the cache.
2528 * If the cache does not exist yet, if we are the first user of it, we
2529 * create it asynchronously in a workqueue and let the current allocation
2530 * go through with the original cache.
2532 * This function takes a reference to the cache it returns to assure it
2533 * won't get destroyed while we are working with it. Once the caller is
2534 * done with it, memcg_kmem_put_cache() must be called to release the
2535 * reference.
2537 struct kmem_cache *memcg_kmem_get_cache(struct kmem_cache *cachep)
2539 struct mem_cgroup *memcg;
2540 struct kmem_cache *memcg_cachep;
2541 int kmemcg_id;
2543 VM_BUG_ON(!is_root_cache(cachep));
2545 if (memcg_kmem_bypass())
2546 return cachep;
2548 memcg = get_mem_cgroup_from_current();
2549 kmemcg_id = READ_ONCE(memcg->kmemcg_id);
2550 if (kmemcg_id < 0)
2551 goto out;
2553 memcg_cachep = cache_from_memcg_idx(cachep, kmemcg_id);
2554 if (likely(memcg_cachep))
2555 return memcg_cachep;
2558 * If we are in a safe context (can wait, and not in interrupt
2559 * context), we could be be predictable and return right away.
2560 * This would guarantee that the allocation being performed
2561 * already belongs in the new cache.
2563 * However, there are some clashes that can arrive from locking.
2564 * For instance, because we acquire the slab_mutex while doing
2565 * memcg_create_kmem_cache, this means no further allocation
2566 * could happen with the slab_mutex held. So it's better to
2567 * defer everything.
2569 memcg_schedule_kmem_cache_create(memcg, cachep);
2570 out:
2571 css_put(&memcg->css);
2572 return cachep;
2576 * memcg_kmem_put_cache: drop reference taken by memcg_kmem_get_cache
2577 * @cachep: the cache returned by memcg_kmem_get_cache
2579 void memcg_kmem_put_cache(struct kmem_cache *cachep)
2581 if (!is_root_cache(cachep))
2582 css_put(&cachep->memcg_params.memcg->css);
2586 * __memcg_kmem_charge_memcg: charge a kmem page
2587 * @page: page to charge
2588 * @gfp: reclaim mode
2589 * @order: allocation order
2590 * @memcg: memory cgroup to charge
2592 * Returns 0 on success, an error code on failure.
2594 int __memcg_kmem_charge_memcg(struct page *page, gfp_t gfp, int order,
2595 struct mem_cgroup *memcg)
2597 unsigned int nr_pages = 1 << order;
2598 struct page_counter *counter;
2599 int ret;
2601 ret = try_charge(memcg, gfp, nr_pages);
2602 if (ret)
2603 return ret;
2605 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) &&
2606 !page_counter_try_charge(&memcg->kmem, nr_pages, &counter)) {
2607 cancel_charge(memcg, nr_pages);
2608 return -ENOMEM;
2611 page->mem_cgroup = memcg;
2613 return 0;
2617 * __memcg_kmem_charge: charge a kmem page to the current memory cgroup
2618 * @page: page to charge
2619 * @gfp: reclaim mode
2620 * @order: allocation order
2622 * Returns 0 on success, an error code on failure.
2624 int __memcg_kmem_charge(struct page *page, gfp_t gfp, int order)
2626 struct mem_cgroup *memcg;
2627 int ret = 0;
2629 if (memcg_kmem_bypass())
2630 return 0;
2632 memcg = get_mem_cgroup_from_current();
2633 if (!mem_cgroup_is_root(memcg)) {
2634 ret = __memcg_kmem_charge_memcg(page, gfp, order, memcg);
2635 if (!ret)
2636 __SetPageKmemcg(page);
2638 css_put(&memcg->css);
2639 return ret;
2642 * __memcg_kmem_uncharge: uncharge a kmem page
2643 * @page: page to uncharge
2644 * @order: allocation order
2646 void __memcg_kmem_uncharge(struct page *page, int order)
2648 struct mem_cgroup *memcg = page->mem_cgroup;
2649 unsigned int nr_pages = 1 << order;
2651 if (!memcg)
2652 return;
2654 VM_BUG_ON_PAGE(mem_cgroup_is_root(memcg), page);
2656 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
2657 page_counter_uncharge(&memcg->kmem, nr_pages);
2659 page_counter_uncharge(&memcg->memory, nr_pages);
2660 if (do_memsw_account())
2661 page_counter_uncharge(&memcg->memsw, nr_pages);
2663 page->mem_cgroup = NULL;
2665 /* slab pages do not have PageKmemcg flag set */
2666 if (PageKmemcg(page))
2667 __ClearPageKmemcg(page);
2669 css_put_many(&memcg->css, nr_pages);
2671 #endif /* CONFIG_MEMCG_KMEM */
2673 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
2676 * Because tail pages are not marked as "used", set it. We're under
2677 * pgdat->lru_lock and migration entries setup in all page mappings.
2679 void mem_cgroup_split_huge_fixup(struct page *head)
2681 int i;
2683 if (mem_cgroup_disabled())
2684 return;
2686 for (i = 1; i < HPAGE_PMD_NR; i++)
2687 head[i].mem_cgroup = head->mem_cgroup;
2689 __mod_memcg_state(head->mem_cgroup, MEMCG_RSS_HUGE, -HPAGE_PMD_NR);
2691 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
2693 #ifdef CONFIG_MEMCG_SWAP
2695 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
2696 * @entry: swap entry to be moved
2697 * @from: mem_cgroup which the entry is moved from
2698 * @to: mem_cgroup which the entry is moved to
2700 * It succeeds only when the swap_cgroup's record for this entry is the same
2701 * as the mem_cgroup's id of @from.
2703 * Returns 0 on success, -EINVAL on failure.
2705 * The caller must have charged to @to, IOW, called page_counter_charge() about
2706 * both res and memsw, and called css_get().
2708 static int mem_cgroup_move_swap_account(swp_entry_t entry,
2709 struct mem_cgroup *from, struct mem_cgroup *to)
2711 unsigned short old_id, new_id;
2713 old_id = mem_cgroup_id(from);
2714 new_id = mem_cgroup_id(to);
2716 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
2717 mod_memcg_state(from, MEMCG_SWAP, -1);
2718 mod_memcg_state(to, MEMCG_SWAP, 1);
2719 return 0;
2721 return -EINVAL;
2723 #else
2724 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
2725 struct mem_cgroup *from, struct mem_cgroup *to)
2727 return -EINVAL;
2729 #endif
2731 static DEFINE_MUTEX(memcg_max_mutex);
2733 static int mem_cgroup_resize_max(struct mem_cgroup *memcg,
2734 unsigned long max, bool memsw)
2736 bool enlarge = false;
2737 bool drained = false;
2738 int ret;
2739 bool limits_invariant;
2740 struct page_counter *counter = memsw ? &memcg->memsw : &memcg->memory;
2742 do {
2743 if (signal_pending(current)) {
2744 ret = -EINTR;
2745 break;
2748 mutex_lock(&memcg_max_mutex);
2750 * Make sure that the new limit (memsw or memory limit) doesn't
2751 * break our basic invariant rule memory.max <= memsw.max.
2753 limits_invariant = memsw ? max >= memcg->memory.max :
2754 max <= memcg->memsw.max;
2755 if (!limits_invariant) {
2756 mutex_unlock(&memcg_max_mutex);
2757 ret = -EINVAL;
2758 break;
2760 if (max > counter->max)
2761 enlarge = true;
2762 ret = page_counter_set_max(counter, max);
2763 mutex_unlock(&memcg_max_mutex);
2765 if (!ret)
2766 break;
2768 if (!drained) {
2769 drain_all_stock(memcg);
2770 drained = true;
2771 continue;
2774 if (!try_to_free_mem_cgroup_pages(memcg, 1,
2775 GFP_KERNEL, !memsw)) {
2776 ret = -EBUSY;
2777 break;
2779 } while (true);
2781 if (!ret && enlarge)
2782 memcg_oom_recover(memcg);
2784 return ret;
2787 unsigned long mem_cgroup_soft_limit_reclaim(pg_data_t *pgdat, int order,
2788 gfp_t gfp_mask,
2789 unsigned long *total_scanned)
2791 unsigned long nr_reclaimed = 0;
2792 struct mem_cgroup_per_node *mz, *next_mz = NULL;
2793 unsigned long reclaimed;
2794 int loop = 0;
2795 struct mem_cgroup_tree_per_node *mctz;
2796 unsigned long excess;
2797 unsigned long nr_scanned;
2799 if (order > 0)
2800 return 0;
2802 mctz = soft_limit_tree_node(pgdat->node_id);
2805 * Do not even bother to check the largest node if the root
2806 * is empty. Do it lockless to prevent lock bouncing. Races
2807 * are acceptable as soft limit is best effort anyway.
2809 if (!mctz || RB_EMPTY_ROOT(&mctz->rb_root))
2810 return 0;
2813 * This loop can run a while, specially if mem_cgroup's continuously
2814 * keep exceeding their soft limit and putting the system under
2815 * pressure
2817 do {
2818 if (next_mz)
2819 mz = next_mz;
2820 else
2821 mz = mem_cgroup_largest_soft_limit_node(mctz);
2822 if (!mz)
2823 break;
2825 nr_scanned = 0;
2826 reclaimed = mem_cgroup_soft_reclaim(mz->memcg, pgdat,
2827 gfp_mask, &nr_scanned);
2828 nr_reclaimed += reclaimed;
2829 *total_scanned += nr_scanned;
2830 spin_lock_irq(&mctz->lock);
2831 __mem_cgroup_remove_exceeded(mz, mctz);
2834 * If we failed to reclaim anything from this memory cgroup
2835 * it is time to move on to the next cgroup
2837 next_mz = NULL;
2838 if (!reclaimed)
2839 next_mz = __mem_cgroup_largest_soft_limit_node(mctz);
2841 excess = soft_limit_excess(mz->memcg);
2843 * One school of thought says that we should not add
2844 * back the node to the tree if reclaim returns 0.
2845 * But our reclaim could return 0, simply because due
2846 * to priority we are exposing a smaller subset of
2847 * memory to reclaim from. Consider this as a longer
2848 * term TODO.
2850 /* If excess == 0, no tree ops */
2851 __mem_cgroup_insert_exceeded(mz, mctz, excess);
2852 spin_unlock_irq(&mctz->lock);
2853 css_put(&mz->memcg->css);
2854 loop++;
2856 * Could not reclaim anything and there are no more
2857 * mem cgroups to try or we seem to be looping without
2858 * reclaiming anything.
2860 if (!nr_reclaimed &&
2861 (next_mz == NULL ||
2862 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
2863 break;
2864 } while (!nr_reclaimed);
2865 if (next_mz)
2866 css_put(&next_mz->memcg->css);
2867 return nr_reclaimed;
2871 * Test whether @memcg has children, dead or alive. Note that this
2872 * function doesn't care whether @memcg has use_hierarchy enabled and
2873 * returns %true if there are child csses according to the cgroup
2874 * hierarchy. Testing use_hierarchy is the caller's responsiblity.
2876 static inline bool memcg_has_children(struct mem_cgroup *memcg)
2878 bool ret;
2880 rcu_read_lock();
2881 ret = css_next_child(NULL, &memcg->css);
2882 rcu_read_unlock();
2883 return ret;
2887 * Reclaims as many pages from the given memcg as possible.
2889 * Caller is responsible for holding css reference for memcg.
2891 static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
2893 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
2895 /* we call try-to-free pages for make this cgroup empty */
2896 lru_add_drain_all();
2898 drain_all_stock(memcg);
2900 /* try to free all pages in this cgroup */
2901 while (nr_retries && page_counter_read(&memcg->memory)) {
2902 int progress;
2904 if (signal_pending(current))
2905 return -EINTR;
2907 progress = try_to_free_mem_cgroup_pages(memcg, 1,
2908 GFP_KERNEL, true);
2909 if (!progress) {
2910 nr_retries--;
2911 /* maybe some writeback is necessary */
2912 congestion_wait(BLK_RW_ASYNC, HZ/10);
2917 return 0;
2920 static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
2921 char *buf, size_t nbytes,
2922 loff_t off)
2924 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
2926 if (mem_cgroup_is_root(memcg))
2927 return -EINVAL;
2928 return mem_cgroup_force_empty(memcg) ?: nbytes;
2931 static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
2932 struct cftype *cft)
2934 return mem_cgroup_from_css(css)->use_hierarchy;
2937 static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
2938 struct cftype *cft, u64 val)
2940 int retval = 0;
2941 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
2942 struct mem_cgroup *parent_memcg = mem_cgroup_from_css(memcg->css.parent);
2944 if (memcg->use_hierarchy == val)
2945 return 0;
2948 * If parent's use_hierarchy is set, we can't make any modifications
2949 * in the child subtrees. If it is unset, then the change can
2950 * occur, provided the current cgroup has no children.
2952 * For the root cgroup, parent_mem is NULL, we allow value to be
2953 * set if there are no children.
2955 if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
2956 (val == 1 || val == 0)) {
2957 if (!memcg_has_children(memcg))
2958 memcg->use_hierarchy = val;
2959 else
2960 retval = -EBUSY;
2961 } else
2962 retval = -EINVAL;
2964 return retval;
2967 struct accumulated_stats {
2968 unsigned long stat[MEMCG_NR_STAT];
2969 unsigned long events[NR_VM_EVENT_ITEMS];
2970 unsigned long lru_pages[NR_LRU_LISTS];
2971 const unsigned int *stats_array;
2972 const unsigned int *events_array;
2973 int stats_size;
2974 int events_size;
2977 static void accumulate_memcg_tree(struct mem_cgroup *memcg,
2978 struct accumulated_stats *acc)
2980 struct mem_cgroup *mi;
2981 int i;
2983 for_each_mem_cgroup_tree(mi, memcg) {
2984 for (i = 0; i < acc->stats_size; i++)
2985 acc->stat[i] += memcg_page_state(mi,
2986 acc->stats_array ? acc->stats_array[i] : i);
2988 for (i = 0; i < acc->events_size; i++)
2989 acc->events[i] += memcg_sum_events(mi,
2990 acc->events_array ? acc->events_array[i] : i);
2992 for (i = 0; i < NR_LRU_LISTS; i++)
2993 acc->lru_pages[i] +=
2994 mem_cgroup_nr_lru_pages(mi, BIT(i));
2998 static unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
3000 unsigned long val = 0;
3002 if (mem_cgroup_is_root(memcg)) {
3003 struct mem_cgroup *iter;
3005 for_each_mem_cgroup_tree(iter, memcg) {
3006 val += memcg_page_state(iter, MEMCG_CACHE);
3007 val += memcg_page_state(iter, MEMCG_RSS);
3008 if (swap)
3009 val += memcg_page_state(iter, MEMCG_SWAP);
3011 } else {
3012 if (!swap)
3013 val = page_counter_read(&memcg->memory);
3014 else
3015 val = page_counter_read(&memcg->memsw);
3017 return val;
3020 enum {
3021 RES_USAGE,
3022 RES_LIMIT,
3023 RES_MAX_USAGE,
3024 RES_FAILCNT,
3025 RES_SOFT_LIMIT,
3028 static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
3029 struct cftype *cft)
3031 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3032 struct page_counter *counter;
3034 switch (MEMFILE_TYPE(cft->private)) {
3035 case _MEM:
3036 counter = &memcg->memory;
3037 break;
3038 case _MEMSWAP:
3039 counter = &memcg->memsw;
3040 break;
3041 case _KMEM:
3042 counter = &memcg->kmem;
3043 break;
3044 case _TCP:
3045 counter = &memcg->tcpmem;
3046 break;
3047 default:
3048 BUG();
3051 switch (MEMFILE_ATTR(cft->private)) {
3052 case RES_USAGE:
3053 if (counter == &memcg->memory)
3054 return (u64)mem_cgroup_usage(memcg, false) * PAGE_SIZE;
3055 if (counter == &memcg->memsw)
3056 return (u64)mem_cgroup_usage(memcg, true) * PAGE_SIZE;
3057 return (u64)page_counter_read(counter) * PAGE_SIZE;
3058 case RES_LIMIT:
3059 return (u64)counter->max * PAGE_SIZE;
3060 case RES_MAX_USAGE:
3061 return (u64)counter->watermark * PAGE_SIZE;
3062 case RES_FAILCNT:
3063 return counter->failcnt;
3064 case RES_SOFT_LIMIT:
3065 return (u64)memcg->soft_limit * PAGE_SIZE;
3066 default:
3067 BUG();
3071 #ifdef CONFIG_MEMCG_KMEM
3072 static int memcg_online_kmem(struct mem_cgroup *memcg)
3074 int memcg_id;
3076 if (cgroup_memory_nokmem)
3077 return 0;
3079 BUG_ON(memcg->kmemcg_id >= 0);
3080 BUG_ON(memcg->kmem_state);
3082 memcg_id = memcg_alloc_cache_id();
3083 if (memcg_id < 0)
3084 return memcg_id;
3086 static_branch_inc(&memcg_kmem_enabled_key);
3088 * A memory cgroup is considered kmem-online as soon as it gets
3089 * kmemcg_id. Setting the id after enabling static branching will
3090 * guarantee no one starts accounting before all call sites are
3091 * patched.
3093 memcg->kmemcg_id = memcg_id;
3094 memcg->kmem_state = KMEM_ONLINE;
3095 INIT_LIST_HEAD(&memcg->kmem_caches);
3097 return 0;
3100 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3102 struct cgroup_subsys_state *css;
3103 struct mem_cgroup *parent, *child;
3104 int kmemcg_id;
3106 if (memcg->kmem_state != KMEM_ONLINE)
3107 return;
3109 * Clear the online state before clearing memcg_caches array
3110 * entries. The slab_mutex in memcg_deactivate_kmem_caches()
3111 * guarantees that no cache will be created for this cgroup
3112 * after we are done (see memcg_create_kmem_cache()).
3114 memcg->kmem_state = KMEM_ALLOCATED;
3116 memcg_deactivate_kmem_caches(memcg);
3118 kmemcg_id = memcg->kmemcg_id;
3119 BUG_ON(kmemcg_id < 0);
3121 parent = parent_mem_cgroup(memcg);
3122 if (!parent)
3123 parent = root_mem_cgroup;
3126 * Change kmemcg_id of this cgroup and all its descendants to the
3127 * parent's id, and then move all entries from this cgroup's list_lrus
3128 * to ones of the parent. After we have finished, all list_lrus
3129 * corresponding to this cgroup are guaranteed to remain empty. The
3130 * ordering is imposed by list_lru_node->lock taken by
3131 * memcg_drain_all_list_lrus().
3133 rcu_read_lock(); /* can be called from css_free w/o cgroup_mutex */
3134 css_for_each_descendant_pre(css, &memcg->css) {
3135 child = mem_cgroup_from_css(css);
3136 BUG_ON(child->kmemcg_id != kmemcg_id);
3137 child->kmemcg_id = parent->kmemcg_id;
3138 if (!memcg->use_hierarchy)
3139 break;
3141 rcu_read_unlock();
3143 memcg_drain_all_list_lrus(kmemcg_id, parent);
3145 memcg_free_cache_id(kmemcg_id);
3148 static void memcg_free_kmem(struct mem_cgroup *memcg)
3150 /* css_alloc() failed, offlining didn't happen */
3151 if (unlikely(memcg->kmem_state == KMEM_ONLINE))
3152 memcg_offline_kmem(memcg);
3154 if (memcg->kmem_state == KMEM_ALLOCATED) {
3155 memcg_destroy_kmem_caches(memcg);
3156 static_branch_dec(&memcg_kmem_enabled_key);
3157 WARN_ON(page_counter_read(&memcg->kmem));
3160 #else
3161 static int memcg_online_kmem(struct mem_cgroup *memcg)
3163 return 0;
3165 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3168 static void memcg_free_kmem(struct mem_cgroup *memcg)
3171 #endif /* CONFIG_MEMCG_KMEM */
3173 static int memcg_update_kmem_max(struct mem_cgroup *memcg,
3174 unsigned long max)
3176 int ret;
3178 mutex_lock(&memcg_max_mutex);
3179 ret = page_counter_set_max(&memcg->kmem, max);
3180 mutex_unlock(&memcg_max_mutex);
3181 return ret;
3184 static int memcg_update_tcp_max(struct mem_cgroup *memcg, unsigned long max)
3186 int ret;
3188 mutex_lock(&memcg_max_mutex);
3190 ret = page_counter_set_max(&memcg->tcpmem, max);
3191 if (ret)
3192 goto out;
3194 if (!memcg->tcpmem_active) {
3196 * The active flag needs to be written after the static_key
3197 * update. This is what guarantees that the socket activation
3198 * function is the last one to run. See mem_cgroup_sk_alloc()
3199 * for details, and note that we don't mark any socket as
3200 * belonging to this memcg until that flag is up.
3202 * We need to do this, because static_keys will span multiple
3203 * sites, but we can't control their order. If we mark a socket
3204 * as accounted, but the accounting functions are not patched in
3205 * yet, we'll lose accounting.
3207 * We never race with the readers in mem_cgroup_sk_alloc(),
3208 * because when this value change, the code to process it is not
3209 * patched in yet.
3211 static_branch_inc(&memcg_sockets_enabled_key);
3212 memcg->tcpmem_active = true;
3214 out:
3215 mutex_unlock(&memcg_max_mutex);
3216 return ret;
3220 * The user of this function is...
3221 * RES_LIMIT.
3223 static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
3224 char *buf, size_t nbytes, loff_t off)
3226 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3227 unsigned long nr_pages;
3228 int ret;
3230 buf = strstrip(buf);
3231 ret = page_counter_memparse(buf, "-1", &nr_pages);
3232 if (ret)
3233 return ret;
3235 switch (MEMFILE_ATTR(of_cft(of)->private)) {
3236 case RES_LIMIT:
3237 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3238 ret = -EINVAL;
3239 break;
3241 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3242 case _MEM:
3243 ret = mem_cgroup_resize_max(memcg, nr_pages, false);
3244 break;
3245 case _MEMSWAP:
3246 ret = mem_cgroup_resize_max(memcg, nr_pages, true);
3247 break;
3248 case _KMEM:
3249 ret = memcg_update_kmem_max(memcg, nr_pages);
3250 break;
3251 case _TCP:
3252 ret = memcg_update_tcp_max(memcg, nr_pages);
3253 break;
3255 break;
3256 case RES_SOFT_LIMIT:
3257 memcg->soft_limit = nr_pages;
3258 ret = 0;
3259 break;
3261 return ret ?: nbytes;
3264 static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
3265 size_t nbytes, loff_t off)
3267 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3268 struct page_counter *counter;
3270 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3271 case _MEM:
3272 counter = &memcg->memory;
3273 break;
3274 case _MEMSWAP:
3275 counter = &memcg->memsw;
3276 break;
3277 case _KMEM:
3278 counter = &memcg->kmem;
3279 break;
3280 case _TCP:
3281 counter = &memcg->tcpmem;
3282 break;
3283 default:
3284 BUG();
3287 switch (MEMFILE_ATTR(of_cft(of)->private)) {
3288 case RES_MAX_USAGE:
3289 page_counter_reset_watermark(counter);
3290 break;
3291 case RES_FAILCNT:
3292 counter->failcnt = 0;
3293 break;
3294 default:
3295 BUG();
3298 return nbytes;
3301 static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
3302 struct cftype *cft)
3304 return mem_cgroup_from_css(css)->move_charge_at_immigrate;
3307 #ifdef CONFIG_MMU
3308 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
3309 struct cftype *cft, u64 val)
3311 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3313 if (val & ~MOVE_MASK)
3314 return -EINVAL;
3317 * No kind of locking is needed in here, because ->can_attach() will
3318 * check this value once in the beginning of the process, and then carry
3319 * on with stale data. This means that changes to this value will only
3320 * affect task migrations starting after the change.
3322 memcg->move_charge_at_immigrate = val;
3323 return 0;
3325 #else
3326 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
3327 struct cftype *cft, u64 val)
3329 return -ENOSYS;
3331 #endif
3333 #ifdef CONFIG_NUMA
3334 static int memcg_numa_stat_show(struct seq_file *m, void *v)
3336 struct numa_stat {
3337 const char *name;
3338 unsigned int lru_mask;
3341 static const struct numa_stat stats[] = {
3342 { "total", LRU_ALL },
3343 { "file", LRU_ALL_FILE },
3344 { "anon", LRU_ALL_ANON },
3345 { "unevictable", BIT(LRU_UNEVICTABLE) },
3347 const struct numa_stat *stat;
3348 int nid;
3349 unsigned long nr;
3350 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
3352 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
3353 nr = mem_cgroup_nr_lru_pages(memcg, stat->lru_mask);
3354 seq_printf(m, "%s=%lu", stat->name, nr);
3355 for_each_node_state(nid, N_MEMORY) {
3356 nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
3357 stat->lru_mask);
3358 seq_printf(m, " N%d=%lu", nid, nr);
3360 seq_putc(m, '\n');
3363 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
3364 struct mem_cgroup *iter;
3366 nr = 0;
3367 for_each_mem_cgroup_tree(iter, memcg)
3368 nr += mem_cgroup_nr_lru_pages(iter, stat->lru_mask);
3369 seq_printf(m, "hierarchical_%s=%lu", stat->name, nr);
3370 for_each_node_state(nid, N_MEMORY) {
3371 nr = 0;
3372 for_each_mem_cgroup_tree(iter, memcg)
3373 nr += mem_cgroup_node_nr_lru_pages(
3374 iter, nid, stat->lru_mask);
3375 seq_printf(m, " N%d=%lu", nid, nr);
3377 seq_putc(m, '\n');
3380 return 0;
3382 #endif /* CONFIG_NUMA */
3384 /* Universal VM events cgroup1 shows, original sort order */
3385 static const unsigned int memcg1_events[] = {
3386 PGPGIN,
3387 PGPGOUT,
3388 PGFAULT,
3389 PGMAJFAULT,
3392 static const char *const memcg1_event_names[] = {
3393 "pgpgin",
3394 "pgpgout",
3395 "pgfault",
3396 "pgmajfault",
3399 static int memcg_stat_show(struct seq_file *m, void *v)
3401 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
3402 unsigned long memory, memsw;
3403 struct mem_cgroup *mi;
3404 unsigned int i;
3405 struct accumulated_stats acc;
3407 BUILD_BUG_ON(ARRAY_SIZE(memcg1_stat_names) != ARRAY_SIZE(memcg1_stats));
3408 BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_lru_names) != NR_LRU_LISTS);
3410 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
3411 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
3412 continue;
3413 seq_printf(m, "%s %lu\n", memcg1_stat_names[i],
3414 memcg_page_state(memcg, memcg1_stats[i]) *
3415 PAGE_SIZE);
3418 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
3419 seq_printf(m, "%s %lu\n", memcg1_event_names[i],
3420 memcg_sum_events(memcg, memcg1_events[i]));
3422 for (i = 0; i < NR_LRU_LISTS; i++)
3423 seq_printf(m, "%s %lu\n", mem_cgroup_lru_names[i],
3424 mem_cgroup_nr_lru_pages(memcg, BIT(i)) * PAGE_SIZE);
3426 /* Hierarchical information */
3427 memory = memsw = PAGE_COUNTER_MAX;
3428 for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
3429 memory = min(memory, mi->memory.max);
3430 memsw = min(memsw, mi->memsw.max);
3432 seq_printf(m, "hierarchical_memory_limit %llu\n",
3433 (u64)memory * PAGE_SIZE);
3434 if (do_memsw_account())
3435 seq_printf(m, "hierarchical_memsw_limit %llu\n",
3436 (u64)memsw * PAGE_SIZE);
3438 memset(&acc, 0, sizeof(acc));
3439 acc.stats_size = ARRAY_SIZE(memcg1_stats);
3440 acc.stats_array = memcg1_stats;
3441 acc.events_size = ARRAY_SIZE(memcg1_events);
3442 acc.events_array = memcg1_events;
3443 accumulate_memcg_tree(memcg, &acc);
3445 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
3446 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
3447 continue;
3448 seq_printf(m, "total_%s %llu\n", memcg1_stat_names[i],
3449 (u64)acc.stat[i] * PAGE_SIZE);
3452 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
3453 seq_printf(m, "total_%s %llu\n", memcg1_event_names[i],
3454 (u64)acc.events[i]);
3456 for (i = 0; i < NR_LRU_LISTS; i++)
3457 seq_printf(m, "total_%s %llu\n", mem_cgroup_lru_names[i],
3458 (u64)acc.lru_pages[i] * PAGE_SIZE);
3460 #ifdef CONFIG_DEBUG_VM
3462 pg_data_t *pgdat;
3463 struct mem_cgroup_per_node *mz;
3464 struct zone_reclaim_stat *rstat;
3465 unsigned long recent_rotated[2] = {0, 0};
3466 unsigned long recent_scanned[2] = {0, 0};
3468 for_each_online_pgdat(pgdat) {
3469 mz = mem_cgroup_nodeinfo(memcg, pgdat->node_id);
3470 rstat = &mz->lruvec.reclaim_stat;
3472 recent_rotated[0] += rstat->recent_rotated[0];
3473 recent_rotated[1] += rstat->recent_rotated[1];
3474 recent_scanned[0] += rstat->recent_scanned[0];
3475 recent_scanned[1] += rstat->recent_scanned[1];
3477 seq_printf(m, "recent_rotated_anon %lu\n", recent_rotated[0]);
3478 seq_printf(m, "recent_rotated_file %lu\n", recent_rotated[1]);
3479 seq_printf(m, "recent_scanned_anon %lu\n", recent_scanned[0]);
3480 seq_printf(m, "recent_scanned_file %lu\n", recent_scanned[1]);
3482 #endif
3484 return 0;
3487 static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
3488 struct cftype *cft)
3490 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3492 return mem_cgroup_swappiness(memcg);
3495 static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
3496 struct cftype *cft, u64 val)
3498 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3500 if (val > 100)
3501 return -EINVAL;
3503 if (css->parent)
3504 memcg->swappiness = val;
3505 else
3506 vm_swappiness = val;
3508 return 0;
3511 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
3513 struct mem_cgroup_threshold_ary *t;
3514 unsigned long usage;
3515 int i;
3517 rcu_read_lock();
3518 if (!swap)
3519 t = rcu_dereference(memcg->thresholds.primary);
3520 else
3521 t = rcu_dereference(memcg->memsw_thresholds.primary);
3523 if (!t)
3524 goto unlock;
3526 usage = mem_cgroup_usage(memcg, swap);
3529 * current_threshold points to threshold just below or equal to usage.
3530 * If it's not true, a threshold was crossed after last
3531 * call of __mem_cgroup_threshold().
3533 i = t->current_threshold;
3536 * Iterate backward over array of thresholds starting from
3537 * current_threshold and check if a threshold is crossed.
3538 * If none of thresholds below usage is crossed, we read
3539 * only one element of the array here.
3541 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
3542 eventfd_signal(t->entries[i].eventfd, 1);
3544 /* i = current_threshold + 1 */
3545 i++;
3548 * Iterate forward over array of thresholds starting from
3549 * current_threshold+1 and check if a threshold is crossed.
3550 * If none of thresholds above usage is crossed, we read
3551 * only one element of the array here.
3553 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
3554 eventfd_signal(t->entries[i].eventfd, 1);
3556 /* Update current_threshold */
3557 t->current_threshold = i - 1;
3558 unlock:
3559 rcu_read_unlock();
3562 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
3564 while (memcg) {
3565 __mem_cgroup_threshold(memcg, false);
3566 if (do_memsw_account())
3567 __mem_cgroup_threshold(memcg, true);
3569 memcg = parent_mem_cgroup(memcg);
3573 static int compare_thresholds(const void *a, const void *b)
3575 const struct mem_cgroup_threshold *_a = a;
3576 const struct mem_cgroup_threshold *_b = b;
3578 if (_a->threshold > _b->threshold)
3579 return 1;
3581 if (_a->threshold < _b->threshold)
3582 return -1;
3584 return 0;
3587 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
3589 struct mem_cgroup_eventfd_list *ev;
3591 spin_lock(&memcg_oom_lock);
3593 list_for_each_entry(ev, &memcg->oom_notify, list)
3594 eventfd_signal(ev->eventfd, 1);
3596 spin_unlock(&memcg_oom_lock);
3597 return 0;
3600 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
3602 struct mem_cgroup *iter;
3604 for_each_mem_cgroup_tree(iter, memcg)
3605 mem_cgroup_oom_notify_cb(iter);
3608 static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
3609 struct eventfd_ctx *eventfd, const char *args, enum res_type type)
3611 struct mem_cgroup_thresholds *thresholds;
3612 struct mem_cgroup_threshold_ary *new;
3613 unsigned long threshold;
3614 unsigned long usage;
3615 int i, size, ret;
3617 ret = page_counter_memparse(args, "-1", &threshold);
3618 if (ret)
3619 return ret;
3621 mutex_lock(&memcg->thresholds_lock);
3623 if (type == _MEM) {
3624 thresholds = &memcg->thresholds;
3625 usage = mem_cgroup_usage(memcg, false);
3626 } else if (type == _MEMSWAP) {
3627 thresholds = &memcg->memsw_thresholds;
3628 usage = mem_cgroup_usage(memcg, true);
3629 } else
3630 BUG();
3632 /* Check if a threshold crossed before adding a new one */
3633 if (thresholds->primary)
3634 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
3636 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
3638 /* Allocate memory for new array of thresholds */
3639 new = kmalloc(struct_size(new, entries, size), GFP_KERNEL);
3640 if (!new) {
3641 ret = -ENOMEM;
3642 goto unlock;
3644 new->size = size;
3646 /* Copy thresholds (if any) to new array */
3647 if (thresholds->primary) {
3648 memcpy(new->entries, thresholds->primary->entries, (size - 1) *
3649 sizeof(struct mem_cgroup_threshold));
3652 /* Add new threshold */
3653 new->entries[size - 1].eventfd = eventfd;
3654 new->entries[size - 1].threshold = threshold;
3656 /* Sort thresholds. Registering of new threshold isn't time-critical */
3657 sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
3658 compare_thresholds, NULL);
3660 /* Find current threshold */
3661 new->current_threshold = -1;
3662 for (i = 0; i < size; i++) {
3663 if (new->entries[i].threshold <= usage) {
3665 * new->current_threshold will not be used until
3666 * rcu_assign_pointer(), so it's safe to increment
3667 * it here.
3669 ++new->current_threshold;
3670 } else
3671 break;
3674 /* Free old spare buffer and save old primary buffer as spare */
3675 kfree(thresholds->spare);
3676 thresholds->spare = thresholds->primary;
3678 rcu_assign_pointer(thresholds->primary, new);
3680 /* To be sure that nobody uses thresholds */
3681 synchronize_rcu();
3683 unlock:
3684 mutex_unlock(&memcg->thresholds_lock);
3686 return ret;
3689 static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
3690 struct eventfd_ctx *eventfd, const char *args)
3692 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
3695 static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
3696 struct eventfd_ctx *eventfd, const char *args)
3698 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
3701 static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
3702 struct eventfd_ctx *eventfd, enum res_type type)
3704 struct mem_cgroup_thresholds *thresholds;
3705 struct mem_cgroup_threshold_ary *new;
3706 unsigned long usage;
3707 int i, j, size;
3709 mutex_lock(&memcg->thresholds_lock);
3711 if (type == _MEM) {
3712 thresholds = &memcg->thresholds;
3713 usage = mem_cgroup_usage(memcg, false);
3714 } else if (type == _MEMSWAP) {
3715 thresholds = &memcg->memsw_thresholds;
3716 usage = mem_cgroup_usage(memcg, true);
3717 } else
3718 BUG();
3720 if (!thresholds->primary)
3721 goto unlock;
3723 /* Check if a threshold crossed before removing */
3724 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
3726 /* Calculate new number of threshold */
3727 size = 0;
3728 for (i = 0; i < thresholds->primary->size; i++) {
3729 if (thresholds->primary->entries[i].eventfd != eventfd)
3730 size++;
3733 new = thresholds->spare;
3735 /* Set thresholds array to NULL if we don't have thresholds */
3736 if (!size) {
3737 kfree(new);
3738 new = NULL;
3739 goto swap_buffers;
3742 new->size = size;
3744 /* Copy thresholds and find current threshold */
3745 new->current_threshold = -1;
3746 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
3747 if (thresholds->primary->entries[i].eventfd == eventfd)
3748 continue;
3750 new->entries[j] = thresholds->primary->entries[i];
3751 if (new->entries[j].threshold <= usage) {
3753 * new->current_threshold will not be used
3754 * until rcu_assign_pointer(), so it's safe to increment
3755 * it here.
3757 ++new->current_threshold;
3759 j++;
3762 swap_buffers:
3763 /* Swap primary and spare array */
3764 thresholds->spare = thresholds->primary;
3766 rcu_assign_pointer(thresholds->primary, new);
3768 /* To be sure that nobody uses thresholds */
3769 synchronize_rcu();
3771 /* If all events are unregistered, free the spare array */
3772 if (!new) {
3773 kfree(thresholds->spare);
3774 thresholds->spare = NULL;
3776 unlock:
3777 mutex_unlock(&memcg->thresholds_lock);
3780 static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
3781 struct eventfd_ctx *eventfd)
3783 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
3786 static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
3787 struct eventfd_ctx *eventfd)
3789 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
3792 static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
3793 struct eventfd_ctx *eventfd, const char *args)
3795 struct mem_cgroup_eventfd_list *event;
3797 event = kmalloc(sizeof(*event), GFP_KERNEL);
3798 if (!event)
3799 return -ENOMEM;
3801 spin_lock(&memcg_oom_lock);
3803 event->eventfd = eventfd;
3804 list_add(&event->list, &memcg->oom_notify);
3806 /* already in OOM ? */
3807 if (memcg->under_oom)
3808 eventfd_signal(eventfd, 1);
3809 spin_unlock(&memcg_oom_lock);
3811 return 0;
3814 static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
3815 struct eventfd_ctx *eventfd)
3817 struct mem_cgroup_eventfd_list *ev, *tmp;
3819 spin_lock(&memcg_oom_lock);
3821 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
3822 if (ev->eventfd == eventfd) {
3823 list_del(&ev->list);
3824 kfree(ev);
3828 spin_unlock(&memcg_oom_lock);
3831 static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
3833 struct mem_cgroup *memcg = mem_cgroup_from_seq(sf);
3835 seq_printf(sf, "oom_kill_disable %d\n", memcg->oom_kill_disable);
3836 seq_printf(sf, "under_oom %d\n", (bool)memcg->under_oom);
3837 seq_printf(sf, "oom_kill %lu\n",
3838 atomic_long_read(&memcg->memory_events[MEMCG_OOM_KILL]));
3839 return 0;
3842 static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
3843 struct cftype *cft, u64 val)
3845 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3847 /* cannot set to root cgroup and only 0 and 1 are allowed */
3848 if (!css->parent || !((val == 0) || (val == 1)))
3849 return -EINVAL;
3851 memcg->oom_kill_disable = val;
3852 if (!val)
3853 memcg_oom_recover(memcg);
3855 return 0;
3858 #ifdef CONFIG_CGROUP_WRITEBACK
3860 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
3862 return wb_domain_init(&memcg->cgwb_domain, gfp);
3865 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
3867 wb_domain_exit(&memcg->cgwb_domain);
3870 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
3872 wb_domain_size_changed(&memcg->cgwb_domain);
3875 struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb)
3877 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
3879 if (!memcg->css.parent)
3880 return NULL;
3882 return &memcg->cgwb_domain;
3886 * idx can be of type enum memcg_stat_item or node_stat_item.
3887 * Keep in sync with memcg_exact_page().
3889 static unsigned long memcg_exact_page_state(struct mem_cgroup *memcg, int idx)
3891 long x = atomic_long_read(&memcg->stat[idx]);
3892 int cpu;
3894 for_each_online_cpu(cpu)
3895 x += per_cpu_ptr(memcg->stat_cpu, cpu)->count[idx];
3896 if (x < 0)
3897 x = 0;
3898 return x;
3902 * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
3903 * @wb: bdi_writeback in question
3904 * @pfilepages: out parameter for number of file pages
3905 * @pheadroom: out parameter for number of allocatable pages according to memcg
3906 * @pdirty: out parameter for number of dirty pages
3907 * @pwriteback: out parameter for number of pages under writeback
3909 * Determine the numbers of file, headroom, dirty, and writeback pages in
3910 * @wb's memcg. File, dirty and writeback are self-explanatory. Headroom
3911 * is a bit more involved.
3913 * A memcg's headroom is "min(max, high) - used". In the hierarchy, the
3914 * headroom is calculated as the lowest headroom of itself and the
3915 * ancestors. Note that this doesn't consider the actual amount of
3916 * available memory in the system. The caller should further cap
3917 * *@pheadroom accordingly.
3919 void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages,
3920 unsigned long *pheadroom, unsigned long *pdirty,
3921 unsigned long *pwriteback)
3923 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
3924 struct mem_cgroup *parent;
3926 *pdirty = memcg_exact_page_state(memcg, NR_FILE_DIRTY);
3928 /* this should eventually include NR_UNSTABLE_NFS */
3929 *pwriteback = memcg_exact_page_state(memcg, NR_WRITEBACK);
3930 *pfilepages = mem_cgroup_nr_lru_pages(memcg, (1 << LRU_INACTIVE_FILE) |
3931 (1 << LRU_ACTIVE_FILE));
3932 *pheadroom = PAGE_COUNTER_MAX;
3934 while ((parent = parent_mem_cgroup(memcg))) {
3935 unsigned long ceiling = min(memcg->memory.max, memcg->high);
3936 unsigned long used = page_counter_read(&memcg->memory);
3938 *pheadroom = min(*pheadroom, ceiling - min(ceiling, used));
3939 memcg = parent;
3943 #else /* CONFIG_CGROUP_WRITEBACK */
3945 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
3947 return 0;
3950 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
3954 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
3958 #endif /* CONFIG_CGROUP_WRITEBACK */
3961 * DO NOT USE IN NEW FILES.
3963 * "cgroup.event_control" implementation.
3965 * This is way over-engineered. It tries to support fully configurable
3966 * events for each user. Such level of flexibility is completely
3967 * unnecessary especially in the light of the planned unified hierarchy.
3969 * Please deprecate this and replace with something simpler if at all
3970 * possible.
3974 * Unregister event and free resources.
3976 * Gets called from workqueue.
3978 static void memcg_event_remove(struct work_struct *work)
3980 struct mem_cgroup_event *event =
3981 container_of(work, struct mem_cgroup_event, remove);
3982 struct mem_cgroup *memcg = event->memcg;
3984 remove_wait_queue(event->wqh, &event->wait);
3986 event->unregister_event(memcg, event->eventfd);
3988 /* Notify userspace the event is going away. */
3989 eventfd_signal(event->eventfd, 1);
3991 eventfd_ctx_put(event->eventfd);
3992 kfree(event);
3993 css_put(&memcg->css);
3997 * Gets called on EPOLLHUP on eventfd when user closes it.
3999 * Called with wqh->lock held and interrupts disabled.
4001 static int memcg_event_wake(wait_queue_entry_t *wait, unsigned mode,
4002 int sync, void *key)
4004 struct mem_cgroup_event *event =
4005 container_of(wait, struct mem_cgroup_event, wait);
4006 struct mem_cgroup *memcg = event->memcg;
4007 __poll_t flags = key_to_poll(key);
4009 if (flags & EPOLLHUP) {
4011 * If the event has been detached at cgroup removal, we
4012 * can simply return knowing the other side will cleanup
4013 * for us.
4015 * We can't race against event freeing since the other
4016 * side will require wqh->lock via remove_wait_queue(),
4017 * which we hold.
4019 spin_lock(&memcg->event_list_lock);
4020 if (!list_empty(&event->list)) {
4021 list_del_init(&event->list);
4023 * We are in atomic context, but cgroup_event_remove()
4024 * may sleep, so we have to call it in workqueue.
4026 schedule_work(&event->remove);
4028 spin_unlock(&memcg->event_list_lock);
4031 return 0;
4034 static void memcg_event_ptable_queue_proc(struct file *file,
4035 wait_queue_head_t *wqh, poll_table *pt)
4037 struct mem_cgroup_event *event =
4038 container_of(pt, struct mem_cgroup_event, pt);
4040 event->wqh = wqh;
4041 add_wait_queue(wqh, &event->wait);
4045 * DO NOT USE IN NEW FILES.
4047 * Parse input and register new cgroup event handler.
4049 * Input must be in format '<event_fd> <control_fd> <args>'.
4050 * Interpretation of args is defined by control file implementation.
4052 static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
4053 char *buf, size_t nbytes, loff_t off)
4055 struct cgroup_subsys_state *css = of_css(of);
4056 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4057 struct mem_cgroup_event *event;
4058 struct cgroup_subsys_state *cfile_css;
4059 unsigned int efd, cfd;
4060 struct fd efile;
4061 struct fd cfile;
4062 const char *name;
4063 char *endp;
4064 int ret;
4066 buf = strstrip(buf);
4068 efd = simple_strtoul(buf, &endp, 10);
4069 if (*endp != ' ')
4070 return -EINVAL;
4071 buf = endp + 1;
4073 cfd = simple_strtoul(buf, &endp, 10);
4074 if ((*endp != ' ') && (*endp != '\0'))
4075 return -EINVAL;
4076 buf = endp + 1;
4078 event = kzalloc(sizeof(*event), GFP_KERNEL);
4079 if (!event)
4080 return -ENOMEM;
4082 event->memcg = memcg;
4083 INIT_LIST_HEAD(&event->list);
4084 init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
4085 init_waitqueue_func_entry(&event->wait, memcg_event_wake);
4086 INIT_WORK(&event->remove, memcg_event_remove);
4088 efile = fdget(efd);
4089 if (!efile.file) {
4090 ret = -EBADF;
4091 goto out_kfree;
4094 event->eventfd = eventfd_ctx_fileget(efile.file);
4095 if (IS_ERR(event->eventfd)) {
4096 ret = PTR_ERR(event->eventfd);
4097 goto out_put_efile;
4100 cfile = fdget(cfd);
4101 if (!cfile.file) {
4102 ret = -EBADF;
4103 goto out_put_eventfd;
4106 /* the process need read permission on control file */
4107 /* AV: shouldn't we check that it's been opened for read instead? */
4108 ret = inode_permission(file_inode(cfile.file), MAY_READ);
4109 if (ret < 0)
4110 goto out_put_cfile;
4113 * Determine the event callbacks and set them in @event. This used
4114 * to be done via struct cftype but cgroup core no longer knows
4115 * about these events. The following is crude but the whole thing
4116 * is for compatibility anyway.
4118 * DO NOT ADD NEW FILES.
4120 name = cfile.file->f_path.dentry->d_name.name;
4122 if (!strcmp(name, "memory.usage_in_bytes")) {
4123 event->register_event = mem_cgroup_usage_register_event;
4124 event->unregister_event = mem_cgroup_usage_unregister_event;
4125 } else if (!strcmp(name, "memory.oom_control")) {
4126 event->register_event = mem_cgroup_oom_register_event;
4127 event->unregister_event = mem_cgroup_oom_unregister_event;
4128 } else if (!strcmp(name, "memory.pressure_level")) {
4129 event->register_event = vmpressure_register_event;
4130 event->unregister_event = vmpressure_unregister_event;
4131 } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
4132 event->register_event = memsw_cgroup_usage_register_event;
4133 event->unregister_event = memsw_cgroup_usage_unregister_event;
4134 } else {
4135 ret = -EINVAL;
4136 goto out_put_cfile;
4140 * Verify @cfile should belong to @css. Also, remaining events are
4141 * automatically removed on cgroup destruction but the removal is
4142 * asynchronous, so take an extra ref on @css.
4144 cfile_css = css_tryget_online_from_dir(cfile.file->f_path.dentry->d_parent,
4145 &memory_cgrp_subsys);
4146 ret = -EINVAL;
4147 if (IS_ERR(cfile_css))
4148 goto out_put_cfile;
4149 if (cfile_css != css) {
4150 css_put(cfile_css);
4151 goto out_put_cfile;
4154 ret = event->register_event(memcg, event->eventfd, buf);
4155 if (ret)
4156 goto out_put_css;
4158 vfs_poll(efile.file, &event->pt);
4160 spin_lock(&memcg->event_list_lock);
4161 list_add(&event->list, &memcg->event_list);
4162 spin_unlock(&memcg->event_list_lock);
4164 fdput(cfile);
4165 fdput(efile);
4167 return nbytes;
4169 out_put_css:
4170 css_put(css);
4171 out_put_cfile:
4172 fdput(cfile);
4173 out_put_eventfd:
4174 eventfd_ctx_put(event->eventfd);
4175 out_put_efile:
4176 fdput(efile);
4177 out_kfree:
4178 kfree(event);
4180 return ret;
4183 static struct cftype mem_cgroup_legacy_files[] = {
4185 .name = "usage_in_bytes",
4186 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
4187 .read_u64 = mem_cgroup_read_u64,
4190 .name = "max_usage_in_bytes",
4191 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
4192 .write = mem_cgroup_reset,
4193 .read_u64 = mem_cgroup_read_u64,
4196 .name = "limit_in_bytes",
4197 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
4198 .write = mem_cgroup_write,
4199 .read_u64 = mem_cgroup_read_u64,
4202 .name = "soft_limit_in_bytes",
4203 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
4204 .write = mem_cgroup_write,
4205 .read_u64 = mem_cgroup_read_u64,
4208 .name = "failcnt",
4209 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
4210 .write = mem_cgroup_reset,
4211 .read_u64 = mem_cgroup_read_u64,
4214 .name = "stat",
4215 .seq_show = memcg_stat_show,
4218 .name = "force_empty",
4219 .write = mem_cgroup_force_empty_write,
4222 .name = "use_hierarchy",
4223 .write_u64 = mem_cgroup_hierarchy_write,
4224 .read_u64 = mem_cgroup_hierarchy_read,
4227 .name = "cgroup.event_control", /* XXX: for compat */
4228 .write = memcg_write_event_control,
4229 .flags = CFTYPE_NO_PREFIX | CFTYPE_WORLD_WRITABLE,
4232 .name = "swappiness",
4233 .read_u64 = mem_cgroup_swappiness_read,
4234 .write_u64 = mem_cgroup_swappiness_write,
4237 .name = "move_charge_at_immigrate",
4238 .read_u64 = mem_cgroup_move_charge_read,
4239 .write_u64 = mem_cgroup_move_charge_write,
4242 .name = "oom_control",
4243 .seq_show = mem_cgroup_oom_control_read,
4244 .write_u64 = mem_cgroup_oom_control_write,
4245 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
4248 .name = "pressure_level",
4250 #ifdef CONFIG_NUMA
4252 .name = "numa_stat",
4253 .seq_show = memcg_numa_stat_show,
4255 #endif
4257 .name = "kmem.limit_in_bytes",
4258 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
4259 .write = mem_cgroup_write,
4260 .read_u64 = mem_cgroup_read_u64,
4263 .name = "kmem.usage_in_bytes",
4264 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
4265 .read_u64 = mem_cgroup_read_u64,
4268 .name = "kmem.failcnt",
4269 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
4270 .write = mem_cgroup_reset,
4271 .read_u64 = mem_cgroup_read_u64,
4274 .name = "kmem.max_usage_in_bytes",
4275 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
4276 .write = mem_cgroup_reset,
4277 .read_u64 = mem_cgroup_read_u64,
4279 #if defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG)
4281 .name = "kmem.slabinfo",
4282 .seq_start = memcg_slab_start,
4283 .seq_next = memcg_slab_next,
4284 .seq_stop = memcg_slab_stop,
4285 .seq_show = memcg_slab_show,
4287 #endif
4289 .name = "kmem.tcp.limit_in_bytes",
4290 .private = MEMFILE_PRIVATE(_TCP, RES_LIMIT),
4291 .write = mem_cgroup_write,
4292 .read_u64 = mem_cgroup_read_u64,
4295 .name = "kmem.tcp.usage_in_bytes",
4296 .private = MEMFILE_PRIVATE(_TCP, RES_USAGE),
4297 .read_u64 = mem_cgroup_read_u64,
4300 .name = "kmem.tcp.failcnt",
4301 .private = MEMFILE_PRIVATE(_TCP, RES_FAILCNT),
4302 .write = mem_cgroup_reset,
4303 .read_u64 = mem_cgroup_read_u64,
4306 .name = "kmem.tcp.max_usage_in_bytes",
4307 .private = MEMFILE_PRIVATE(_TCP, RES_MAX_USAGE),
4308 .write = mem_cgroup_reset,
4309 .read_u64 = mem_cgroup_read_u64,
4311 { }, /* terminate */
4315 * Private memory cgroup IDR
4317 * Swap-out records and page cache shadow entries need to store memcg
4318 * references in constrained space, so we maintain an ID space that is
4319 * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of
4320 * memory-controlled cgroups to 64k.
4322 * However, there usually are many references to the oflline CSS after
4323 * the cgroup has been destroyed, such as page cache or reclaimable
4324 * slab objects, that don't need to hang on to the ID. We want to keep
4325 * those dead CSS from occupying IDs, or we might quickly exhaust the
4326 * relatively small ID space and prevent the creation of new cgroups
4327 * even when there are much fewer than 64k cgroups - possibly none.
4329 * Maintain a private 16-bit ID space for memcg, and allow the ID to
4330 * be freed and recycled when it's no longer needed, which is usually
4331 * when the CSS is offlined.
4333 * The only exception to that are records of swapped out tmpfs/shmem
4334 * pages that need to be attributed to live ancestors on swapin. But
4335 * those references are manageable from userspace.
4338 static DEFINE_IDR(mem_cgroup_idr);
4340 static void mem_cgroup_id_remove(struct mem_cgroup *memcg)
4342 if (memcg->id.id > 0) {
4343 idr_remove(&mem_cgroup_idr, memcg->id.id);
4344 memcg->id.id = 0;
4348 static void mem_cgroup_id_get_many(struct mem_cgroup *memcg, unsigned int n)
4350 refcount_add(n, &memcg->id.ref);
4353 static void mem_cgroup_id_put_many(struct mem_cgroup *memcg, unsigned int n)
4355 if (refcount_sub_and_test(n, &memcg->id.ref)) {
4356 mem_cgroup_id_remove(memcg);
4358 /* Memcg ID pins CSS */
4359 css_put(&memcg->css);
4363 static inline void mem_cgroup_id_get(struct mem_cgroup *memcg)
4365 mem_cgroup_id_get_many(memcg, 1);
4368 static inline void mem_cgroup_id_put(struct mem_cgroup *memcg)
4370 mem_cgroup_id_put_many(memcg, 1);
4374 * mem_cgroup_from_id - look up a memcg from a memcg id
4375 * @id: the memcg id to look up
4377 * Caller must hold rcu_read_lock().
4379 struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
4381 WARN_ON_ONCE(!rcu_read_lock_held());
4382 return idr_find(&mem_cgroup_idr, id);
4385 static int alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
4387 struct mem_cgroup_per_node *pn;
4388 int tmp = node;
4390 * This routine is called against possible nodes.
4391 * But it's BUG to call kmalloc() against offline node.
4393 * TODO: this routine can waste much memory for nodes which will
4394 * never be onlined. It's better to use memory hotplug callback
4395 * function.
4397 if (!node_state(node, N_NORMAL_MEMORY))
4398 tmp = -1;
4399 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
4400 if (!pn)
4401 return 1;
4403 pn->lruvec_stat_cpu = alloc_percpu(struct lruvec_stat);
4404 if (!pn->lruvec_stat_cpu) {
4405 kfree(pn);
4406 return 1;
4409 lruvec_init(&pn->lruvec);
4410 pn->usage_in_excess = 0;
4411 pn->on_tree = false;
4412 pn->memcg = memcg;
4414 memcg->nodeinfo[node] = pn;
4415 return 0;
4418 static void free_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
4420 struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
4422 if (!pn)
4423 return;
4425 free_percpu(pn->lruvec_stat_cpu);
4426 kfree(pn);
4429 static void __mem_cgroup_free(struct mem_cgroup *memcg)
4431 int node;
4433 for_each_node(node)
4434 free_mem_cgroup_per_node_info(memcg, node);
4435 free_percpu(memcg->stat_cpu);
4436 kfree(memcg);
4439 static void mem_cgroup_free(struct mem_cgroup *memcg)
4441 memcg_wb_domain_exit(memcg);
4442 __mem_cgroup_free(memcg);
4445 static struct mem_cgroup *mem_cgroup_alloc(void)
4447 struct mem_cgroup *memcg;
4448 unsigned int size;
4449 int node;
4451 size = sizeof(struct mem_cgroup);
4452 size += nr_node_ids * sizeof(struct mem_cgroup_per_node *);
4454 memcg = kzalloc(size, GFP_KERNEL);
4455 if (!memcg)
4456 return NULL;
4458 memcg->id.id = idr_alloc(&mem_cgroup_idr, NULL,
4459 1, MEM_CGROUP_ID_MAX,
4460 GFP_KERNEL);
4461 if (memcg->id.id < 0)
4462 goto fail;
4464 memcg->stat_cpu = alloc_percpu(struct mem_cgroup_stat_cpu);
4465 if (!memcg->stat_cpu)
4466 goto fail;
4468 for_each_node(node)
4469 if (alloc_mem_cgroup_per_node_info(memcg, node))
4470 goto fail;
4472 if (memcg_wb_domain_init(memcg, GFP_KERNEL))
4473 goto fail;
4475 INIT_WORK(&memcg->high_work, high_work_func);
4476 memcg->last_scanned_node = MAX_NUMNODES;
4477 INIT_LIST_HEAD(&memcg->oom_notify);
4478 mutex_init(&memcg->thresholds_lock);
4479 spin_lock_init(&memcg->move_lock);
4480 vmpressure_init(&memcg->vmpressure);
4481 INIT_LIST_HEAD(&memcg->event_list);
4482 spin_lock_init(&memcg->event_list_lock);
4483 memcg->socket_pressure = jiffies;
4484 #ifdef CONFIG_MEMCG_KMEM
4485 memcg->kmemcg_id = -1;
4486 #endif
4487 #ifdef CONFIG_CGROUP_WRITEBACK
4488 INIT_LIST_HEAD(&memcg->cgwb_list);
4489 #endif
4490 idr_replace(&mem_cgroup_idr, memcg, memcg->id.id);
4491 return memcg;
4492 fail:
4493 mem_cgroup_id_remove(memcg);
4494 __mem_cgroup_free(memcg);
4495 return NULL;
4498 static struct cgroup_subsys_state * __ref
4499 mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
4501 struct mem_cgroup *parent = mem_cgroup_from_css(parent_css);
4502 struct mem_cgroup *memcg;
4503 long error = -ENOMEM;
4505 memcg = mem_cgroup_alloc();
4506 if (!memcg)
4507 return ERR_PTR(error);
4509 memcg->high = PAGE_COUNTER_MAX;
4510 memcg->soft_limit = PAGE_COUNTER_MAX;
4511 if (parent) {
4512 memcg->swappiness = mem_cgroup_swappiness(parent);
4513 memcg->oom_kill_disable = parent->oom_kill_disable;
4515 if (parent && parent->use_hierarchy) {
4516 memcg->use_hierarchy = true;
4517 page_counter_init(&memcg->memory, &parent->memory);
4518 page_counter_init(&memcg->swap, &parent->swap);
4519 page_counter_init(&memcg->memsw, &parent->memsw);
4520 page_counter_init(&memcg->kmem, &parent->kmem);
4521 page_counter_init(&memcg->tcpmem, &parent->tcpmem);
4522 } else {
4523 page_counter_init(&memcg->memory, NULL);
4524 page_counter_init(&memcg->swap, NULL);
4525 page_counter_init(&memcg->memsw, NULL);
4526 page_counter_init(&memcg->kmem, NULL);
4527 page_counter_init(&memcg->tcpmem, NULL);
4529 * Deeper hierachy with use_hierarchy == false doesn't make
4530 * much sense so let cgroup subsystem know about this
4531 * unfortunate state in our controller.
4533 if (parent != root_mem_cgroup)
4534 memory_cgrp_subsys.broken_hierarchy = true;
4537 /* The following stuff does not apply to the root */
4538 if (!parent) {
4539 root_mem_cgroup = memcg;
4540 return &memcg->css;
4543 error = memcg_online_kmem(memcg);
4544 if (error)
4545 goto fail;
4547 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
4548 static_branch_inc(&memcg_sockets_enabled_key);
4550 return &memcg->css;
4551 fail:
4552 mem_cgroup_id_remove(memcg);
4553 mem_cgroup_free(memcg);
4554 return ERR_PTR(-ENOMEM);
4557 static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
4559 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4562 * A memcg must be visible for memcg_expand_shrinker_maps()
4563 * by the time the maps are allocated. So, we allocate maps
4564 * here, when for_each_mem_cgroup() can't skip it.
4566 if (memcg_alloc_shrinker_maps(memcg)) {
4567 mem_cgroup_id_remove(memcg);
4568 return -ENOMEM;
4571 /* Online state pins memcg ID, memcg ID pins CSS */
4572 refcount_set(&memcg->id.ref, 1);
4573 css_get(css);
4574 return 0;
4577 static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
4579 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4580 struct mem_cgroup_event *event, *tmp;
4583 * Unregister events and notify userspace.
4584 * Notify userspace about cgroup removing only after rmdir of cgroup
4585 * directory to avoid race between userspace and kernelspace.
4587 spin_lock(&memcg->event_list_lock);
4588 list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
4589 list_del_init(&event->list);
4590 schedule_work(&event->remove);
4592 spin_unlock(&memcg->event_list_lock);
4594 page_counter_set_min(&memcg->memory, 0);
4595 page_counter_set_low(&memcg->memory, 0);
4597 memcg_offline_kmem(memcg);
4598 wb_memcg_offline(memcg);
4600 drain_all_stock(memcg);
4602 mem_cgroup_id_put(memcg);
4605 static void mem_cgroup_css_released(struct cgroup_subsys_state *css)
4607 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4609 invalidate_reclaim_iterators(memcg);
4612 static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
4614 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4616 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
4617 static_branch_dec(&memcg_sockets_enabled_key);
4619 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg->tcpmem_active)
4620 static_branch_dec(&memcg_sockets_enabled_key);
4622 vmpressure_cleanup(&memcg->vmpressure);
4623 cancel_work_sync(&memcg->high_work);
4624 mem_cgroup_remove_from_trees(memcg);
4625 memcg_free_shrinker_maps(memcg);
4626 memcg_free_kmem(memcg);
4627 mem_cgroup_free(memcg);
4631 * mem_cgroup_css_reset - reset the states of a mem_cgroup
4632 * @css: the target css
4634 * Reset the states of the mem_cgroup associated with @css. This is
4635 * invoked when the userland requests disabling on the default hierarchy
4636 * but the memcg is pinned through dependency. The memcg should stop
4637 * applying policies and should revert to the vanilla state as it may be
4638 * made visible again.
4640 * The current implementation only resets the essential configurations.
4641 * This needs to be expanded to cover all the visible parts.
4643 static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
4645 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4647 page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX);
4648 page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX);
4649 page_counter_set_max(&memcg->memsw, PAGE_COUNTER_MAX);
4650 page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX);
4651 page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX);
4652 page_counter_set_min(&memcg->memory, 0);
4653 page_counter_set_low(&memcg->memory, 0);
4654 memcg->high = PAGE_COUNTER_MAX;
4655 memcg->soft_limit = PAGE_COUNTER_MAX;
4656 memcg_wb_domain_size_changed(memcg);
4659 #ifdef CONFIG_MMU
4660 /* Handlers for move charge at task migration. */
4661 static int mem_cgroup_do_precharge(unsigned long count)
4663 int ret;
4665 /* Try a single bulk charge without reclaim first, kswapd may wake */
4666 ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_DIRECT_RECLAIM, count);
4667 if (!ret) {
4668 mc.precharge += count;
4669 return ret;
4672 /* Try charges one by one with reclaim, but do not retry */
4673 while (count--) {
4674 ret = try_charge(mc.to, GFP_KERNEL | __GFP_NORETRY, 1);
4675 if (ret)
4676 return ret;
4677 mc.precharge++;
4678 cond_resched();
4680 return 0;
4683 union mc_target {
4684 struct page *page;
4685 swp_entry_t ent;
4688 enum mc_target_type {
4689 MC_TARGET_NONE = 0,
4690 MC_TARGET_PAGE,
4691 MC_TARGET_SWAP,
4692 MC_TARGET_DEVICE,
4695 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
4696 unsigned long addr, pte_t ptent)
4698 struct page *page = _vm_normal_page(vma, addr, ptent, true);
4700 if (!page || !page_mapped(page))
4701 return NULL;
4702 if (PageAnon(page)) {
4703 if (!(mc.flags & MOVE_ANON))
4704 return NULL;
4705 } else {
4706 if (!(mc.flags & MOVE_FILE))
4707 return NULL;
4709 if (!get_page_unless_zero(page))
4710 return NULL;
4712 return page;
4715 #if defined(CONFIG_SWAP) || defined(CONFIG_DEVICE_PRIVATE)
4716 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
4717 pte_t ptent, swp_entry_t *entry)
4719 struct page *page = NULL;
4720 swp_entry_t ent = pte_to_swp_entry(ptent);
4722 if (!(mc.flags & MOVE_ANON) || non_swap_entry(ent))
4723 return NULL;
4726 * Handle MEMORY_DEVICE_PRIVATE which are ZONE_DEVICE page belonging to
4727 * a device and because they are not accessible by CPU they are store
4728 * as special swap entry in the CPU page table.
4730 if (is_device_private_entry(ent)) {
4731 page = device_private_entry_to_page(ent);
4733 * MEMORY_DEVICE_PRIVATE means ZONE_DEVICE page and which have
4734 * a refcount of 1 when free (unlike normal page)
4736 if (!page_ref_add_unless(page, 1, 1))
4737 return NULL;
4738 return page;
4742 * Because lookup_swap_cache() updates some statistics counter,
4743 * we call find_get_page() with swapper_space directly.
4745 page = find_get_page(swap_address_space(ent), swp_offset(ent));
4746 if (do_memsw_account())
4747 entry->val = ent.val;
4749 return page;
4751 #else
4752 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
4753 pte_t ptent, swp_entry_t *entry)
4755 return NULL;
4757 #endif
4759 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
4760 unsigned long addr, pte_t ptent, swp_entry_t *entry)
4762 struct page *page = NULL;
4763 struct address_space *mapping;
4764 pgoff_t pgoff;
4766 if (!vma->vm_file) /* anonymous vma */
4767 return NULL;
4768 if (!(mc.flags & MOVE_FILE))
4769 return NULL;
4771 mapping = vma->vm_file->f_mapping;
4772 pgoff = linear_page_index(vma, addr);
4774 /* page is moved even if it's not RSS of this task(page-faulted). */
4775 #ifdef CONFIG_SWAP
4776 /* shmem/tmpfs may report page out on swap: account for that too. */
4777 if (shmem_mapping(mapping)) {
4778 page = find_get_entry(mapping, pgoff);
4779 if (xa_is_value(page)) {
4780 swp_entry_t swp = radix_to_swp_entry(page);
4781 if (do_memsw_account())
4782 *entry = swp;
4783 page = find_get_page(swap_address_space(swp),
4784 swp_offset(swp));
4786 } else
4787 page = find_get_page(mapping, pgoff);
4788 #else
4789 page = find_get_page(mapping, pgoff);
4790 #endif
4791 return page;
4795 * mem_cgroup_move_account - move account of the page
4796 * @page: the page
4797 * @compound: charge the page as compound or small page
4798 * @from: mem_cgroup which the page is moved from.
4799 * @to: mem_cgroup which the page is moved to. @from != @to.
4801 * The caller must make sure the page is not on LRU (isolate_page() is useful.)
4803 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
4804 * from old cgroup.
4806 static int mem_cgroup_move_account(struct page *page,
4807 bool compound,
4808 struct mem_cgroup *from,
4809 struct mem_cgroup *to)
4811 unsigned long flags;
4812 unsigned int nr_pages = compound ? hpage_nr_pages(page) : 1;
4813 int ret;
4814 bool anon;
4816 VM_BUG_ON(from == to);
4817 VM_BUG_ON_PAGE(PageLRU(page), page);
4818 VM_BUG_ON(compound && !PageTransHuge(page));
4821 * Prevent mem_cgroup_migrate() from looking at
4822 * page->mem_cgroup of its source page while we change it.
4824 ret = -EBUSY;
4825 if (!trylock_page(page))
4826 goto out;
4828 ret = -EINVAL;
4829 if (page->mem_cgroup != from)
4830 goto out_unlock;
4832 anon = PageAnon(page);
4834 spin_lock_irqsave(&from->move_lock, flags);
4836 if (!anon && page_mapped(page)) {
4837 __mod_memcg_state(from, NR_FILE_MAPPED, -nr_pages);
4838 __mod_memcg_state(to, NR_FILE_MAPPED, nr_pages);
4842 * move_lock grabbed above and caller set from->moving_account, so
4843 * mod_memcg_page_state will serialize updates to PageDirty.
4844 * So mapping should be stable for dirty pages.
4846 if (!anon && PageDirty(page)) {
4847 struct address_space *mapping = page_mapping(page);
4849 if (mapping_cap_account_dirty(mapping)) {
4850 __mod_memcg_state(from, NR_FILE_DIRTY, -nr_pages);
4851 __mod_memcg_state(to, NR_FILE_DIRTY, nr_pages);
4855 if (PageWriteback(page)) {
4856 __mod_memcg_state(from, NR_WRITEBACK, -nr_pages);
4857 __mod_memcg_state(to, NR_WRITEBACK, nr_pages);
4861 * It is safe to change page->mem_cgroup here because the page
4862 * is referenced, charged, and isolated - we can't race with
4863 * uncharging, charging, migration, or LRU putback.
4866 /* caller should have done css_get */
4867 page->mem_cgroup = to;
4868 spin_unlock_irqrestore(&from->move_lock, flags);
4870 ret = 0;
4872 local_irq_disable();
4873 mem_cgroup_charge_statistics(to, page, compound, nr_pages);
4874 memcg_check_events(to, page);
4875 mem_cgroup_charge_statistics(from, page, compound, -nr_pages);
4876 memcg_check_events(from, page);
4877 local_irq_enable();
4878 out_unlock:
4879 unlock_page(page);
4880 out:
4881 return ret;
4885 * get_mctgt_type - get target type of moving charge
4886 * @vma: the vma the pte to be checked belongs
4887 * @addr: the address corresponding to the pte to be checked
4888 * @ptent: the pte to be checked
4889 * @target: the pointer the target page or swap ent will be stored(can be NULL)
4891 * Returns
4892 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
4893 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
4894 * move charge. if @target is not NULL, the page is stored in target->page
4895 * with extra refcnt got(Callers should handle it).
4896 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
4897 * target for charge migration. if @target is not NULL, the entry is stored
4898 * in target->ent.
4899 * 3(MC_TARGET_DEVICE): like MC_TARGET_PAGE but page is MEMORY_DEVICE_PUBLIC
4900 * or MEMORY_DEVICE_PRIVATE (so ZONE_DEVICE page and thus not on the lru).
4901 * For now we such page is charge like a regular page would be as for all
4902 * intent and purposes it is just special memory taking the place of a
4903 * regular page.
4905 * See Documentations/vm/hmm.txt and include/linux/hmm.h
4907 * Called with pte lock held.
4910 static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
4911 unsigned long addr, pte_t ptent, union mc_target *target)
4913 struct page *page = NULL;
4914 enum mc_target_type ret = MC_TARGET_NONE;
4915 swp_entry_t ent = { .val = 0 };
4917 if (pte_present(ptent))
4918 page = mc_handle_present_pte(vma, addr, ptent);
4919 else if (is_swap_pte(ptent))
4920 page = mc_handle_swap_pte(vma, ptent, &ent);
4921 else if (pte_none(ptent))
4922 page = mc_handle_file_pte(vma, addr, ptent, &ent);
4924 if (!page && !ent.val)
4925 return ret;
4926 if (page) {
4928 * Do only loose check w/o serialization.
4929 * mem_cgroup_move_account() checks the page is valid or
4930 * not under LRU exclusion.
4932 if (page->mem_cgroup == mc.from) {
4933 ret = MC_TARGET_PAGE;
4934 if (is_device_private_page(page) ||
4935 is_device_public_page(page))
4936 ret = MC_TARGET_DEVICE;
4937 if (target)
4938 target->page = page;
4940 if (!ret || !target)
4941 put_page(page);
4944 * There is a swap entry and a page doesn't exist or isn't charged.
4945 * But we cannot move a tail-page in a THP.
4947 if (ent.val && !ret && (!page || !PageTransCompound(page)) &&
4948 mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
4949 ret = MC_TARGET_SWAP;
4950 if (target)
4951 target->ent = ent;
4953 return ret;
4956 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4958 * We don't consider PMD mapped swapping or file mapped pages because THP does
4959 * not support them for now.
4960 * Caller should make sure that pmd_trans_huge(pmd) is true.
4962 static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
4963 unsigned long addr, pmd_t pmd, union mc_target *target)
4965 struct page *page = NULL;
4966 enum mc_target_type ret = MC_TARGET_NONE;
4968 if (unlikely(is_swap_pmd(pmd))) {
4969 VM_BUG_ON(thp_migration_supported() &&
4970 !is_pmd_migration_entry(pmd));
4971 return ret;
4973 page = pmd_page(pmd);
4974 VM_BUG_ON_PAGE(!page || !PageHead(page), page);
4975 if (!(mc.flags & MOVE_ANON))
4976 return ret;
4977 if (page->mem_cgroup == mc.from) {
4978 ret = MC_TARGET_PAGE;
4979 if (target) {
4980 get_page(page);
4981 target->page = page;
4984 return ret;
4986 #else
4987 static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
4988 unsigned long addr, pmd_t pmd, union mc_target *target)
4990 return MC_TARGET_NONE;
4992 #endif
4994 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
4995 unsigned long addr, unsigned long end,
4996 struct mm_walk *walk)
4998 struct vm_area_struct *vma = walk->vma;
4999 pte_t *pte;
5000 spinlock_t *ptl;
5002 ptl = pmd_trans_huge_lock(pmd, vma);
5003 if (ptl) {
5005 * Note their can not be MC_TARGET_DEVICE for now as we do not
5006 * support transparent huge page with MEMORY_DEVICE_PUBLIC or
5007 * MEMORY_DEVICE_PRIVATE but this might change.
5009 if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
5010 mc.precharge += HPAGE_PMD_NR;
5011 spin_unlock(ptl);
5012 return 0;
5015 if (pmd_trans_unstable(pmd))
5016 return 0;
5017 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5018 for (; addr != end; pte++, addr += PAGE_SIZE)
5019 if (get_mctgt_type(vma, addr, *pte, NULL))
5020 mc.precharge++; /* increment precharge temporarily */
5021 pte_unmap_unlock(pte - 1, ptl);
5022 cond_resched();
5024 return 0;
5027 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
5029 unsigned long precharge;
5031 struct mm_walk mem_cgroup_count_precharge_walk = {
5032 .pmd_entry = mem_cgroup_count_precharge_pte_range,
5033 .mm = mm,
5035 down_read(&mm->mmap_sem);
5036 walk_page_range(0, mm->highest_vm_end,
5037 &mem_cgroup_count_precharge_walk);
5038 up_read(&mm->mmap_sem);
5040 precharge = mc.precharge;
5041 mc.precharge = 0;
5043 return precharge;
5046 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
5048 unsigned long precharge = mem_cgroup_count_precharge(mm);
5050 VM_BUG_ON(mc.moving_task);
5051 mc.moving_task = current;
5052 return mem_cgroup_do_precharge(precharge);
5055 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5056 static void __mem_cgroup_clear_mc(void)
5058 struct mem_cgroup *from = mc.from;
5059 struct mem_cgroup *to = mc.to;
5061 /* we must uncharge all the leftover precharges from mc.to */
5062 if (mc.precharge) {
5063 cancel_charge(mc.to, mc.precharge);
5064 mc.precharge = 0;
5067 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5068 * we must uncharge here.
5070 if (mc.moved_charge) {
5071 cancel_charge(mc.from, mc.moved_charge);
5072 mc.moved_charge = 0;
5074 /* we must fixup refcnts and charges */
5075 if (mc.moved_swap) {
5076 /* uncharge swap account from the old cgroup */
5077 if (!mem_cgroup_is_root(mc.from))
5078 page_counter_uncharge(&mc.from->memsw, mc.moved_swap);
5080 mem_cgroup_id_put_many(mc.from, mc.moved_swap);
5083 * we charged both to->memory and to->memsw, so we
5084 * should uncharge to->memory.
5086 if (!mem_cgroup_is_root(mc.to))
5087 page_counter_uncharge(&mc.to->memory, mc.moved_swap);
5089 mem_cgroup_id_get_many(mc.to, mc.moved_swap);
5090 css_put_many(&mc.to->css, mc.moved_swap);
5092 mc.moved_swap = 0;
5094 memcg_oom_recover(from);
5095 memcg_oom_recover(to);
5096 wake_up_all(&mc.waitq);
5099 static void mem_cgroup_clear_mc(void)
5101 struct mm_struct *mm = mc.mm;
5104 * we must clear moving_task before waking up waiters at the end of
5105 * task migration.
5107 mc.moving_task = NULL;
5108 __mem_cgroup_clear_mc();
5109 spin_lock(&mc.lock);
5110 mc.from = NULL;
5111 mc.to = NULL;
5112 mc.mm = NULL;
5113 spin_unlock(&mc.lock);
5115 mmput(mm);
5118 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
5120 struct cgroup_subsys_state *css;
5121 struct mem_cgroup *memcg = NULL; /* unneeded init to make gcc happy */
5122 struct mem_cgroup *from;
5123 struct task_struct *leader, *p;
5124 struct mm_struct *mm;
5125 unsigned long move_flags;
5126 int ret = 0;
5128 /* charge immigration isn't supported on the default hierarchy */
5129 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
5130 return 0;
5133 * Multi-process migrations only happen on the default hierarchy
5134 * where charge immigration is not used. Perform charge
5135 * immigration if @tset contains a leader and whine if there are
5136 * multiple.
5138 p = NULL;
5139 cgroup_taskset_for_each_leader(leader, css, tset) {
5140 WARN_ON_ONCE(p);
5141 p = leader;
5142 memcg = mem_cgroup_from_css(css);
5144 if (!p)
5145 return 0;
5148 * We are now commited to this value whatever it is. Changes in this
5149 * tunable will only affect upcoming migrations, not the current one.
5150 * So we need to save it, and keep it going.
5152 move_flags = READ_ONCE(memcg->move_charge_at_immigrate);
5153 if (!move_flags)
5154 return 0;
5156 from = mem_cgroup_from_task(p);
5158 VM_BUG_ON(from == memcg);
5160 mm = get_task_mm(p);
5161 if (!mm)
5162 return 0;
5163 /* We move charges only when we move a owner of the mm */
5164 if (mm->owner == p) {
5165 VM_BUG_ON(mc.from);
5166 VM_BUG_ON(mc.to);
5167 VM_BUG_ON(mc.precharge);
5168 VM_BUG_ON(mc.moved_charge);
5169 VM_BUG_ON(mc.moved_swap);
5171 spin_lock(&mc.lock);
5172 mc.mm = mm;
5173 mc.from = from;
5174 mc.to = memcg;
5175 mc.flags = move_flags;
5176 spin_unlock(&mc.lock);
5177 /* We set mc.moving_task later */
5179 ret = mem_cgroup_precharge_mc(mm);
5180 if (ret)
5181 mem_cgroup_clear_mc();
5182 } else {
5183 mmput(mm);
5185 return ret;
5188 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
5190 if (mc.to)
5191 mem_cgroup_clear_mc();
5194 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
5195 unsigned long addr, unsigned long end,
5196 struct mm_walk *walk)
5198 int ret = 0;
5199 struct vm_area_struct *vma = walk->vma;
5200 pte_t *pte;
5201 spinlock_t *ptl;
5202 enum mc_target_type target_type;
5203 union mc_target target;
5204 struct page *page;
5206 ptl = pmd_trans_huge_lock(pmd, vma);
5207 if (ptl) {
5208 if (mc.precharge < HPAGE_PMD_NR) {
5209 spin_unlock(ptl);
5210 return 0;
5212 target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
5213 if (target_type == MC_TARGET_PAGE) {
5214 page = target.page;
5215 if (!isolate_lru_page(page)) {
5216 if (!mem_cgroup_move_account(page, true,
5217 mc.from, mc.to)) {
5218 mc.precharge -= HPAGE_PMD_NR;
5219 mc.moved_charge += HPAGE_PMD_NR;
5221 putback_lru_page(page);
5223 put_page(page);
5224 } else if (target_type == MC_TARGET_DEVICE) {
5225 page = target.page;
5226 if (!mem_cgroup_move_account(page, true,
5227 mc.from, mc.to)) {
5228 mc.precharge -= HPAGE_PMD_NR;
5229 mc.moved_charge += HPAGE_PMD_NR;
5231 put_page(page);
5233 spin_unlock(ptl);
5234 return 0;
5237 if (pmd_trans_unstable(pmd))
5238 return 0;
5239 retry:
5240 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5241 for (; addr != end; addr += PAGE_SIZE) {
5242 pte_t ptent = *(pte++);
5243 bool device = false;
5244 swp_entry_t ent;
5246 if (!mc.precharge)
5247 break;
5249 switch (get_mctgt_type(vma, addr, ptent, &target)) {
5250 case MC_TARGET_DEVICE:
5251 device = true;
5252 /* fall through */
5253 case MC_TARGET_PAGE:
5254 page = target.page;
5256 * We can have a part of the split pmd here. Moving it
5257 * can be done but it would be too convoluted so simply
5258 * ignore such a partial THP and keep it in original
5259 * memcg. There should be somebody mapping the head.
5261 if (PageTransCompound(page))
5262 goto put;
5263 if (!device && isolate_lru_page(page))
5264 goto put;
5265 if (!mem_cgroup_move_account(page, false,
5266 mc.from, mc.to)) {
5267 mc.precharge--;
5268 /* we uncharge from mc.from later. */
5269 mc.moved_charge++;
5271 if (!device)
5272 putback_lru_page(page);
5273 put: /* get_mctgt_type() gets the page */
5274 put_page(page);
5275 break;
5276 case MC_TARGET_SWAP:
5277 ent = target.ent;
5278 if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
5279 mc.precharge--;
5280 /* we fixup refcnts and charges later. */
5281 mc.moved_swap++;
5283 break;
5284 default:
5285 break;
5288 pte_unmap_unlock(pte - 1, ptl);
5289 cond_resched();
5291 if (addr != end) {
5293 * We have consumed all precharges we got in can_attach().
5294 * We try charge one by one, but don't do any additional
5295 * charges to mc.to if we have failed in charge once in attach()
5296 * phase.
5298 ret = mem_cgroup_do_precharge(1);
5299 if (!ret)
5300 goto retry;
5303 return ret;
5306 static void mem_cgroup_move_charge(void)
5308 struct mm_walk mem_cgroup_move_charge_walk = {
5309 .pmd_entry = mem_cgroup_move_charge_pte_range,
5310 .mm = mc.mm,
5313 lru_add_drain_all();
5315 * Signal lock_page_memcg() to take the memcg's move_lock
5316 * while we're moving its pages to another memcg. Then wait
5317 * for already started RCU-only updates to finish.
5319 atomic_inc(&mc.from->moving_account);
5320 synchronize_rcu();
5321 retry:
5322 if (unlikely(!down_read_trylock(&mc.mm->mmap_sem))) {
5324 * Someone who are holding the mmap_sem might be waiting in
5325 * waitq. So we cancel all extra charges, wake up all waiters,
5326 * and retry. Because we cancel precharges, we might not be able
5327 * to move enough charges, but moving charge is a best-effort
5328 * feature anyway, so it wouldn't be a big problem.
5330 __mem_cgroup_clear_mc();
5331 cond_resched();
5332 goto retry;
5335 * When we have consumed all precharges and failed in doing
5336 * additional charge, the page walk just aborts.
5338 walk_page_range(0, mc.mm->highest_vm_end, &mem_cgroup_move_charge_walk);
5340 up_read(&mc.mm->mmap_sem);
5341 atomic_dec(&mc.from->moving_account);
5344 static void mem_cgroup_move_task(void)
5346 if (mc.to) {
5347 mem_cgroup_move_charge();
5348 mem_cgroup_clear_mc();
5351 #else /* !CONFIG_MMU */
5352 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
5354 return 0;
5356 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
5359 static void mem_cgroup_move_task(void)
5362 #endif
5365 * Cgroup retains root cgroups across [un]mount cycles making it necessary
5366 * to verify whether we're attached to the default hierarchy on each mount
5367 * attempt.
5369 static void mem_cgroup_bind(struct cgroup_subsys_state *root_css)
5372 * use_hierarchy is forced on the default hierarchy. cgroup core
5373 * guarantees that @root doesn't have any children, so turning it
5374 * on for the root memcg is enough.
5376 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
5377 root_mem_cgroup->use_hierarchy = true;
5378 else
5379 root_mem_cgroup->use_hierarchy = false;
5382 static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value)
5384 if (value == PAGE_COUNTER_MAX)
5385 seq_puts(m, "max\n");
5386 else
5387 seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE);
5389 return 0;
5392 static u64 memory_current_read(struct cgroup_subsys_state *css,
5393 struct cftype *cft)
5395 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5397 return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
5400 static int memory_min_show(struct seq_file *m, void *v)
5402 return seq_puts_memcg_tunable(m,
5403 READ_ONCE(mem_cgroup_from_seq(m)->memory.min));
5406 static ssize_t memory_min_write(struct kernfs_open_file *of,
5407 char *buf, size_t nbytes, loff_t off)
5409 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
5410 unsigned long min;
5411 int err;
5413 buf = strstrip(buf);
5414 err = page_counter_memparse(buf, "max", &min);
5415 if (err)
5416 return err;
5418 page_counter_set_min(&memcg->memory, min);
5420 return nbytes;
5423 static int memory_low_show(struct seq_file *m, void *v)
5425 return seq_puts_memcg_tunable(m,
5426 READ_ONCE(mem_cgroup_from_seq(m)->memory.low));
5429 static ssize_t memory_low_write(struct kernfs_open_file *of,
5430 char *buf, size_t nbytes, loff_t off)
5432 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
5433 unsigned long low;
5434 int err;
5436 buf = strstrip(buf);
5437 err = page_counter_memparse(buf, "max", &low);
5438 if (err)
5439 return err;
5441 page_counter_set_low(&memcg->memory, low);
5443 return nbytes;
5446 static int memory_high_show(struct seq_file *m, void *v)
5448 return seq_puts_memcg_tunable(m, READ_ONCE(mem_cgroup_from_seq(m)->high));
5451 static ssize_t memory_high_write(struct kernfs_open_file *of,
5452 char *buf, size_t nbytes, loff_t off)
5454 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
5455 unsigned long nr_pages;
5456 unsigned long high;
5457 int err;
5459 buf = strstrip(buf);
5460 err = page_counter_memparse(buf, "max", &high);
5461 if (err)
5462 return err;
5464 memcg->high = high;
5466 nr_pages = page_counter_read(&memcg->memory);
5467 if (nr_pages > high)
5468 try_to_free_mem_cgroup_pages(memcg, nr_pages - high,
5469 GFP_KERNEL, true);
5471 memcg_wb_domain_size_changed(memcg);
5472 return nbytes;
5475 static int memory_max_show(struct seq_file *m, void *v)
5477 return seq_puts_memcg_tunable(m,
5478 READ_ONCE(mem_cgroup_from_seq(m)->memory.max));
5481 static ssize_t memory_max_write(struct kernfs_open_file *of,
5482 char *buf, size_t nbytes, loff_t off)
5484 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
5485 unsigned int nr_reclaims = MEM_CGROUP_RECLAIM_RETRIES;
5486 bool drained = false;
5487 unsigned long max;
5488 int err;
5490 buf = strstrip(buf);
5491 err = page_counter_memparse(buf, "max", &max);
5492 if (err)
5493 return err;
5495 xchg(&memcg->memory.max, max);
5497 for (;;) {
5498 unsigned long nr_pages = page_counter_read(&memcg->memory);
5500 if (nr_pages <= max)
5501 break;
5503 if (signal_pending(current)) {
5504 err = -EINTR;
5505 break;
5508 if (!drained) {
5509 drain_all_stock(memcg);
5510 drained = true;
5511 continue;
5514 if (nr_reclaims) {
5515 if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,
5516 GFP_KERNEL, true))
5517 nr_reclaims--;
5518 continue;
5521 memcg_memory_event(memcg, MEMCG_OOM);
5522 if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0))
5523 break;
5526 memcg_wb_domain_size_changed(memcg);
5527 return nbytes;
5530 static int memory_events_show(struct seq_file *m, void *v)
5532 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
5534 seq_printf(m, "low %lu\n",
5535 atomic_long_read(&memcg->memory_events[MEMCG_LOW]));
5536 seq_printf(m, "high %lu\n",
5537 atomic_long_read(&memcg->memory_events[MEMCG_HIGH]));
5538 seq_printf(m, "max %lu\n",
5539 atomic_long_read(&memcg->memory_events[MEMCG_MAX]));
5540 seq_printf(m, "oom %lu\n",
5541 atomic_long_read(&memcg->memory_events[MEMCG_OOM]));
5542 seq_printf(m, "oom_kill %lu\n",
5543 atomic_long_read(&memcg->memory_events[MEMCG_OOM_KILL]));
5545 return 0;
5548 static int memory_stat_show(struct seq_file *m, void *v)
5550 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
5551 struct accumulated_stats acc;
5552 int i;
5555 * Provide statistics on the state of the memory subsystem as
5556 * well as cumulative event counters that show past behavior.
5558 * This list is ordered following a combination of these gradients:
5559 * 1) generic big picture -> specifics and details
5560 * 2) reflecting userspace activity -> reflecting kernel heuristics
5562 * Current memory state:
5565 memset(&acc, 0, sizeof(acc));
5566 acc.stats_size = MEMCG_NR_STAT;
5567 acc.events_size = NR_VM_EVENT_ITEMS;
5568 accumulate_memcg_tree(memcg, &acc);
5570 seq_printf(m, "anon %llu\n",
5571 (u64)acc.stat[MEMCG_RSS] * PAGE_SIZE);
5572 seq_printf(m, "file %llu\n",
5573 (u64)acc.stat[MEMCG_CACHE] * PAGE_SIZE);
5574 seq_printf(m, "kernel_stack %llu\n",
5575 (u64)acc.stat[MEMCG_KERNEL_STACK_KB] * 1024);
5576 seq_printf(m, "slab %llu\n",
5577 (u64)(acc.stat[NR_SLAB_RECLAIMABLE] +
5578 acc.stat[NR_SLAB_UNRECLAIMABLE]) * PAGE_SIZE);
5579 seq_printf(m, "sock %llu\n",
5580 (u64)acc.stat[MEMCG_SOCK] * PAGE_SIZE);
5582 seq_printf(m, "shmem %llu\n",
5583 (u64)acc.stat[NR_SHMEM] * PAGE_SIZE);
5584 seq_printf(m, "file_mapped %llu\n",
5585 (u64)acc.stat[NR_FILE_MAPPED] * PAGE_SIZE);
5586 seq_printf(m, "file_dirty %llu\n",
5587 (u64)acc.stat[NR_FILE_DIRTY] * PAGE_SIZE);
5588 seq_printf(m, "file_writeback %llu\n",
5589 (u64)acc.stat[NR_WRITEBACK] * PAGE_SIZE);
5592 * TODO: We should eventually replace our own MEMCG_RSS_HUGE counter
5593 * with the NR_ANON_THP vm counter, but right now it's a pain in the
5594 * arse because it requires migrating the work out of rmap to a place
5595 * where the page->mem_cgroup is set up and stable.
5597 seq_printf(m, "anon_thp %llu\n",
5598 (u64)acc.stat[MEMCG_RSS_HUGE] * PAGE_SIZE);
5600 for (i = 0; i < NR_LRU_LISTS; i++)
5601 seq_printf(m, "%s %llu\n", mem_cgroup_lru_names[i],
5602 (u64)acc.lru_pages[i] * PAGE_SIZE);
5604 seq_printf(m, "slab_reclaimable %llu\n",
5605 (u64)acc.stat[NR_SLAB_RECLAIMABLE] * PAGE_SIZE);
5606 seq_printf(m, "slab_unreclaimable %llu\n",
5607 (u64)acc.stat[NR_SLAB_UNRECLAIMABLE] * PAGE_SIZE);
5609 /* Accumulated memory events */
5611 seq_printf(m, "pgfault %lu\n", acc.events[PGFAULT]);
5612 seq_printf(m, "pgmajfault %lu\n", acc.events[PGMAJFAULT]);
5614 seq_printf(m, "workingset_refault %lu\n",
5615 acc.stat[WORKINGSET_REFAULT]);
5616 seq_printf(m, "workingset_activate %lu\n",
5617 acc.stat[WORKINGSET_ACTIVATE]);
5618 seq_printf(m, "workingset_nodereclaim %lu\n",
5619 acc.stat[WORKINGSET_NODERECLAIM]);
5621 seq_printf(m, "pgrefill %lu\n", acc.events[PGREFILL]);
5622 seq_printf(m, "pgscan %lu\n", acc.events[PGSCAN_KSWAPD] +
5623 acc.events[PGSCAN_DIRECT]);
5624 seq_printf(m, "pgsteal %lu\n", acc.events[PGSTEAL_KSWAPD] +
5625 acc.events[PGSTEAL_DIRECT]);
5626 seq_printf(m, "pgactivate %lu\n", acc.events[PGACTIVATE]);
5627 seq_printf(m, "pgdeactivate %lu\n", acc.events[PGDEACTIVATE]);
5628 seq_printf(m, "pglazyfree %lu\n", acc.events[PGLAZYFREE]);
5629 seq_printf(m, "pglazyfreed %lu\n", acc.events[PGLAZYFREED]);
5631 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5632 seq_printf(m, "thp_fault_alloc %lu\n", acc.events[THP_FAULT_ALLOC]);
5633 seq_printf(m, "thp_collapse_alloc %lu\n",
5634 acc.events[THP_COLLAPSE_ALLOC]);
5635 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
5637 return 0;
5640 static int memory_oom_group_show(struct seq_file *m, void *v)
5642 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
5644 seq_printf(m, "%d\n", memcg->oom_group);
5646 return 0;
5649 static ssize_t memory_oom_group_write(struct kernfs_open_file *of,
5650 char *buf, size_t nbytes, loff_t off)
5652 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
5653 int ret, oom_group;
5655 buf = strstrip(buf);
5656 if (!buf)
5657 return -EINVAL;
5659 ret = kstrtoint(buf, 0, &oom_group);
5660 if (ret)
5661 return ret;
5663 if (oom_group != 0 && oom_group != 1)
5664 return -EINVAL;
5666 memcg->oom_group = oom_group;
5668 return nbytes;
5671 static struct cftype memory_files[] = {
5673 .name = "current",
5674 .flags = CFTYPE_NOT_ON_ROOT,
5675 .read_u64 = memory_current_read,
5678 .name = "min",
5679 .flags = CFTYPE_NOT_ON_ROOT,
5680 .seq_show = memory_min_show,
5681 .write = memory_min_write,
5684 .name = "low",
5685 .flags = CFTYPE_NOT_ON_ROOT,
5686 .seq_show = memory_low_show,
5687 .write = memory_low_write,
5690 .name = "high",
5691 .flags = CFTYPE_NOT_ON_ROOT,
5692 .seq_show = memory_high_show,
5693 .write = memory_high_write,
5696 .name = "max",
5697 .flags = CFTYPE_NOT_ON_ROOT,
5698 .seq_show = memory_max_show,
5699 .write = memory_max_write,
5702 .name = "events",
5703 .flags = CFTYPE_NOT_ON_ROOT,
5704 .file_offset = offsetof(struct mem_cgroup, events_file),
5705 .seq_show = memory_events_show,
5708 .name = "stat",
5709 .flags = CFTYPE_NOT_ON_ROOT,
5710 .seq_show = memory_stat_show,
5713 .name = "oom.group",
5714 .flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE,
5715 .seq_show = memory_oom_group_show,
5716 .write = memory_oom_group_write,
5718 { } /* terminate */
5721 struct cgroup_subsys memory_cgrp_subsys = {
5722 .css_alloc = mem_cgroup_css_alloc,
5723 .css_online = mem_cgroup_css_online,
5724 .css_offline = mem_cgroup_css_offline,
5725 .css_released = mem_cgroup_css_released,
5726 .css_free = mem_cgroup_css_free,
5727 .css_reset = mem_cgroup_css_reset,
5728 .can_attach = mem_cgroup_can_attach,
5729 .cancel_attach = mem_cgroup_cancel_attach,
5730 .post_attach = mem_cgroup_move_task,
5731 .bind = mem_cgroup_bind,
5732 .dfl_cftypes = memory_files,
5733 .legacy_cftypes = mem_cgroup_legacy_files,
5734 .early_init = 0,
5738 * mem_cgroup_protected - check if memory consumption is in the normal range
5739 * @root: the top ancestor of the sub-tree being checked
5740 * @memcg: the memory cgroup to check
5742 * WARNING: This function is not stateless! It can only be used as part
5743 * of a top-down tree iteration, not for isolated queries.
5745 * Returns one of the following:
5746 * MEMCG_PROT_NONE: cgroup memory is not protected
5747 * MEMCG_PROT_LOW: cgroup memory is protected as long there is
5748 * an unprotected supply of reclaimable memory from other cgroups.
5749 * MEMCG_PROT_MIN: cgroup memory is protected
5751 * @root is exclusive; it is never protected when looked at directly
5753 * To provide a proper hierarchical behavior, effective memory.min/low values
5754 * are used. Below is the description of how effective memory.low is calculated.
5755 * Effective memory.min values is calculated in the same way.
5757 * Effective memory.low is always equal or less than the original memory.low.
5758 * If there is no memory.low overcommittment (which is always true for
5759 * top-level memory cgroups), these two values are equal.
5760 * Otherwise, it's a part of parent's effective memory.low,
5761 * calculated as a cgroup's memory.low usage divided by sum of sibling's
5762 * memory.low usages, where memory.low usage is the size of actually
5763 * protected memory.
5765 * low_usage
5766 * elow = min( memory.low, parent->elow * ------------------ ),
5767 * siblings_low_usage
5769 * | memory.current, if memory.current < memory.low
5770 * low_usage = |
5771 * | 0, otherwise.
5774 * Such definition of the effective memory.low provides the expected
5775 * hierarchical behavior: parent's memory.low value is limiting
5776 * children, unprotected memory is reclaimed first and cgroups,
5777 * which are not using their guarantee do not affect actual memory
5778 * distribution.
5780 * For example, if there are memcgs A, A/B, A/C, A/D and A/E:
5782 * A A/memory.low = 2G, A/memory.current = 6G
5783 * //\\
5784 * BC DE B/memory.low = 3G B/memory.current = 2G
5785 * C/memory.low = 1G C/memory.current = 2G
5786 * D/memory.low = 0 D/memory.current = 2G
5787 * E/memory.low = 10G E/memory.current = 0
5789 * and the memory pressure is applied, the following memory distribution
5790 * is expected (approximately):
5792 * A/memory.current = 2G
5794 * B/memory.current = 1.3G
5795 * C/memory.current = 0.6G
5796 * D/memory.current = 0
5797 * E/memory.current = 0
5799 * These calculations require constant tracking of the actual low usages
5800 * (see propagate_protected_usage()), as well as recursive calculation of
5801 * effective memory.low values. But as we do call mem_cgroup_protected()
5802 * path for each memory cgroup top-down from the reclaim,
5803 * it's possible to optimize this part, and save calculated elow
5804 * for next usage. This part is intentionally racy, but it's ok,
5805 * as memory.low is a best-effort mechanism.
5807 enum mem_cgroup_protection mem_cgroup_protected(struct mem_cgroup *root,
5808 struct mem_cgroup *memcg)
5810 struct mem_cgroup *parent;
5811 unsigned long emin, parent_emin;
5812 unsigned long elow, parent_elow;
5813 unsigned long usage;
5815 if (mem_cgroup_disabled())
5816 return MEMCG_PROT_NONE;
5818 if (!root)
5819 root = root_mem_cgroup;
5820 if (memcg == root)
5821 return MEMCG_PROT_NONE;
5823 usage = page_counter_read(&memcg->memory);
5824 if (!usage)
5825 return MEMCG_PROT_NONE;
5827 emin = memcg->memory.min;
5828 elow = memcg->memory.low;
5830 parent = parent_mem_cgroup(memcg);
5831 /* No parent means a non-hierarchical mode on v1 memcg */
5832 if (!parent)
5833 return MEMCG_PROT_NONE;
5835 if (parent == root)
5836 goto exit;
5838 parent_emin = READ_ONCE(parent->memory.emin);
5839 emin = min(emin, parent_emin);
5840 if (emin && parent_emin) {
5841 unsigned long min_usage, siblings_min_usage;
5843 min_usage = min(usage, memcg->memory.min);
5844 siblings_min_usage = atomic_long_read(
5845 &parent->memory.children_min_usage);
5847 if (min_usage && siblings_min_usage)
5848 emin = min(emin, parent_emin * min_usage /
5849 siblings_min_usage);
5852 parent_elow = READ_ONCE(parent->memory.elow);
5853 elow = min(elow, parent_elow);
5854 if (elow && parent_elow) {
5855 unsigned long low_usage, siblings_low_usage;
5857 low_usage = min(usage, memcg->memory.low);
5858 siblings_low_usage = atomic_long_read(
5859 &parent->memory.children_low_usage);
5861 if (low_usage && siblings_low_usage)
5862 elow = min(elow, parent_elow * low_usage /
5863 siblings_low_usage);
5866 exit:
5867 memcg->memory.emin = emin;
5868 memcg->memory.elow = elow;
5870 if (usage <= emin)
5871 return MEMCG_PROT_MIN;
5872 else if (usage <= elow)
5873 return MEMCG_PROT_LOW;
5874 else
5875 return MEMCG_PROT_NONE;
5879 * mem_cgroup_try_charge - try charging a page
5880 * @page: page to charge
5881 * @mm: mm context of the victim
5882 * @gfp_mask: reclaim mode
5883 * @memcgp: charged memcg return
5884 * @compound: charge the page as compound or small page
5886 * Try to charge @page to the memcg that @mm belongs to, reclaiming
5887 * pages according to @gfp_mask if necessary.
5889 * Returns 0 on success, with *@memcgp pointing to the charged memcg.
5890 * Otherwise, an error code is returned.
5892 * After page->mapping has been set up, the caller must finalize the
5893 * charge with mem_cgroup_commit_charge(). Or abort the transaction
5894 * with mem_cgroup_cancel_charge() in case page instantiation fails.
5896 int mem_cgroup_try_charge(struct page *page, struct mm_struct *mm,
5897 gfp_t gfp_mask, struct mem_cgroup **memcgp,
5898 bool compound)
5900 struct mem_cgroup *memcg = NULL;
5901 unsigned int nr_pages = compound ? hpage_nr_pages(page) : 1;
5902 int ret = 0;
5904 if (mem_cgroup_disabled())
5905 goto out;
5907 if (PageSwapCache(page)) {
5909 * Every swap fault against a single page tries to charge the
5910 * page, bail as early as possible. shmem_unuse() encounters
5911 * already charged pages, too. The USED bit is protected by
5912 * the page lock, which serializes swap cache removal, which
5913 * in turn serializes uncharging.
5915 VM_BUG_ON_PAGE(!PageLocked(page), page);
5916 if (compound_head(page)->mem_cgroup)
5917 goto out;
5919 if (do_swap_account) {
5920 swp_entry_t ent = { .val = page_private(page), };
5921 unsigned short id = lookup_swap_cgroup_id(ent);
5923 rcu_read_lock();
5924 memcg = mem_cgroup_from_id(id);
5925 if (memcg && !css_tryget_online(&memcg->css))
5926 memcg = NULL;
5927 rcu_read_unlock();
5931 if (!memcg)
5932 memcg = get_mem_cgroup_from_mm(mm);
5934 ret = try_charge(memcg, gfp_mask, nr_pages);
5936 css_put(&memcg->css);
5937 out:
5938 *memcgp = memcg;
5939 return ret;
5942 int mem_cgroup_try_charge_delay(struct page *page, struct mm_struct *mm,
5943 gfp_t gfp_mask, struct mem_cgroup **memcgp,
5944 bool compound)
5946 struct mem_cgroup *memcg;
5947 int ret;
5949 ret = mem_cgroup_try_charge(page, mm, gfp_mask, memcgp, compound);
5950 memcg = *memcgp;
5951 mem_cgroup_throttle_swaprate(memcg, page_to_nid(page), gfp_mask);
5952 return ret;
5956 * mem_cgroup_commit_charge - commit a page charge
5957 * @page: page to charge
5958 * @memcg: memcg to charge the page to
5959 * @lrucare: page might be on LRU already
5960 * @compound: charge the page as compound or small page
5962 * Finalize a charge transaction started by mem_cgroup_try_charge(),
5963 * after page->mapping has been set up. This must happen atomically
5964 * as part of the page instantiation, i.e. under the page table lock
5965 * for anonymous pages, under the page lock for page and swap cache.
5967 * In addition, the page must not be on the LRU during the commit, to
5968 * prevent racing with task migration. If it might be, use @lrucare.
5970 * Use mem_cgroup_cancel_charge() to cancel the transaction instead.
5972 void mem_cgroup_commit_charge(struct page *page, struct mem_cgroup *memcg,
5973 bool lrucare, bool compound)
5975 unsigned int nr_pages = compound ? hpage_nr_pages(page) : 1;
5977 VM_BUG_ON_PAGE(!page->mapping, page);
5978 VM_BUG_ON_PAGE(PageLRU(page) && !lrucare, page);
5980 if (mem_cgroup_disabled())
5981 return;
5983 * Swap faults will attempt to charge the same page multiple
5984 * times. But reuse_swap_page() might have removed the page
5985 * from swapcache already, so we can't check PageSwapCache().
5987 if (!memcg)
5988 return;
5990 commit_charge(page, memcg, lrucare);
5992 local_irq_disable();
5993 mem_cgroup_charge_statistics(memcg, page, compound, nr_pages);
5994 memcg_check_events(memcg, page);
5995 local_irq_enable();
5997 if (do_memsw_account() && PageSwapCache(page)) {
5998 swp_entry_t entry = { .val = page_private(page) };
6000 * The swap entry might not get freed for a long time,
6001 * let's not wait for it. The page already received a
6002 * memory+swap charge, drop the swap entry duplicate.
6004 mem_cgroup_uncharge_swap(entry, nr_pages);
6009 * mem_cgroup_cancel_charge - cancel a page charge
6010 * @page: page to charge
6011 * @memcg: memcg to charge the page to
6012 * @compound: charge the page as compound or small page
6014 * Cancel a charge transaction started by mem_cgroup_try_charge().
6016 void mem_cgroup_cancel_charge(struct page *page, struct mem_cgroup *memcg,
6017 bool compound)
6019 unsigned int nr_pages = compound ? hpage_nr_pages(page) : 1;
6021 if (mem_cgroup_disabled())
6022 return;
6024 * Swap faults will attempt to charge the same page multiple
6025 * times. But reuse_swap_page() might have removed the page
6026 * from swapcache already, so we can't check PageSwapCache().
6028 if (!memcg)
6029 return;
6031 cancel_charge(memcg, nr_pages);
6034 struct uncharge_gather {
6035 struct mem_cgroup *memcg;
6036 unsigned long pgpgout;
6037 unsigned long nr_anon;
6038 unsigned long nr_file;
6039 unsigned long nr_kmem;
6040 unsigned long nr_huge;
6041 unsigned long nr_shmem;
6042 struct page *dummy_page;
6045 static inline void uncharge_gather_clear(struct uncharge_gather *ug)
6047 memset(ug, 0, sizeof(*ug));
6050 static void uncharge_batch(const struct uncharge_gather *ug)
6052 unsigned long nr_pages = ug->nr_anon + ug->nr_file + ug->nr_kmem;
6053 unsigned long flags;
6055 if (!mem_cgroup_is_root(ug->memcg)) {
6056 page_counter_uncharge(&ug->memcg->memory, nr_pages);
6057 if (do_memsw_account())
6058 page_counter_uncharge(&ug->memcg->memsw, nr_pages);
6059 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && ug->nr_kmem)
6060 page_counter_uncharge(&ug->memcg->kmem, ug->nr_kmem);
6061 memcg_oom_recover(ug->memcg);
6064 local_irq_save(flags);
6065 __mod_memcg_state(ug->memcg, MEMCG_RSS, -ug->nr_anon);
6066 __mod_memcg_state(ug->memcg, MEMCG_CACHE, -ug->nr_file);
6067 __mod_memcg_state(ug->memcg, MEMCG_RSS_HUGE, -ug->nr_huge);
6068 __mod_memcg_state(ug->memcg, NR_SHMEM, -ug->nr_shmem);
6069 __count_memcg_events(ug->memcg, PGPGOUT, ug->pgpgout);
6070 __this_cpu_add(ug->memcg->stat_cpu->nr_page_events, nr_pages);
6071 memcg_check_events(ug->memcg, ug->dummy_page);
6072 local_irq_restore(flags);
6074 if (!mem_cgroup_is_root(ug->memcg))
6075 css_put_many(&ug->memcg->css, nr_pages);
6078 static void uncharge_page(struct page *page, struct uncharge_gather *ug)
6080 VM_BUG_ON_PAGE(PageLRU(page), page);
6081 VM_BUG_ON_PAGE(page_count(page) && !is_zone_device_page(page) &&
6082 !PageHWPoison(page) , page);
6084 if (!page->mem_cgroup)
6085 return;
6088 * Nobody should be changing or seriously looking at
6089 * page->mem_cgroup at this point, we have fully
6090 * exclusive access to the page.
6093 if (ug->memcg != page->mem_cgroup) {
6094 if (ug->memcg) {
6095 uncharge_batch(ug);
6096 uncharge_gather_clear(ug);
6098 ug->memcg = page->mem_cgroup;
6101 if (!PageKmemcg(page)) {
6102 unsigned int nr_pages = 1;
6104 if (PageTransHuge(page)) {
6105 nr_pages <<= compound_order(page);
6106 ug->nr_huge += nr_pages;
6108 if (PageAnon(page))
6109 ug->nr_anon += nr_pages;
6110 else {
6111 ug->nr_file += nr_pages;
6112 if (PageSwapBacked(page))
6113 ug->nr_shmem += nr_pages;
6115 ug->pgpgout++;
6116 } else {
6117 ug->nr_kmem += 1 << compound_order(page);
6118 __ClearPageKmemcg(page);
6121 ug->dummy_page = page;
6122 page->mem_cgroup = NULL;
6125 static void uncharge_list(struct list_head *page_list)
6127 struct uncharge_gather ug;
6128 struct list_head *next;
6130 uncharge_gather_clear(&ug);
6133 * Note that the list can be a single page->lru; hence the
6134 * do-while loop instead of a simple list_for_each_entry().
6136 next = page_list->next;
6137 do {
6138 struct page *page;
6140 page = list_entry(next, struct page, lru);
6141 next = page->lru.next;
6143 uncharge_page(page, &ug);
6144 } while (next != page_list);
6146 if (ug.memcg)
6147 uncharge_batch(&ug);
6151 * mem_cgroup_uncharge - uncharge a page
6152 * @page: page to uncharge
6154 * Uncharge a page previously charged with mem_cgroup_try_charge() and
6155 * mem_cgroup_commit_charge().
6157 void mem_cgroup_uncharge(struct page *page)
6159 struct uncharge_gather ug;
6161 if (mem_cgroup_disabled())
6162 return;
6164 /* Don't touch page->lru of any random page, pre-check: */
6165 if (!page->mem_cgroup)
6166 return;
6168 uncharge_gather_clear(&ug);
6169 uncharge_page(page, &ug);
6170 uncharge_batch(&ug);
6174 * mem_cgroup_uncharge_list - uncharge a list of page
6175 * @page_list: list of pages to uncharge
6177 * Uncharge a list of pages previously charged with
6178 * mem_cgroup_try_charge() and mem_cgroup_commit_charge().
6180 void mem_cgroup_uncharge_list(struct list_head *page_list)
6182 if (mem_cgroup_disabled())
6183 return;
6185 if (!list_empty(page_list))
6186 uncharge_list(page_list);
6190 * mem_cgroup_migrate - charge a page's replacement
6191 * @oldpage: currently circulating page
6192 * @newpage: replacement page
6194 * Charge @newpage as a replacement page for @oldpage. @oldpage will
6195 * be uncharged upon free.
6197 * Both pages must be locked, @newpage->mapping must be set up.
6199 void mem_cgroup_migrate(struct page *oldpage, struct page *newpage)
6201 struct mem_cgroup *memcg;
6202 unsigned int nr_pages;
6203 bool compound;
6204 unsigned long flags;
6206 VM_BUG_ON_PAGE(!PageLocked(oldpage), oldpage);
6207 VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
6208 VM_BUG_ON_PAGE(PageAnon(oldpage) != PageAnon(newpage), newpage);
6209 VM_BUG_ON_PAGE(PageTransHuge(oldpage) != PageTransHuge(newpage),
6210 newpage);
6212 if (mem_cgroup_disabled())
6213 return;
6215 /* Page cache replacement: new page already charged? */
6216 if (newpage->mem_cgroup)
6217 return;
6219 /* Swapcache readahead pages can get replaced before being charged */
6220 memcg = oldpage->mem_cgroup;
6221 if (!memcg)
6222 return;
6224 /* Force-charge the new page. The old one will be freed soon */
6225 compound = PageTransHuge(newpage);
6226 nr_pages = compound ? hpage_nr_pages(newpage) : 1;
6228 page_counter_charge(&memcg->memory, nr_pages);
6229 if (do_memsw_account())
6230 page_counter_charge(&memcg->memsw, nr_pages);
6231 css_get_many(&memcg->css, nr_pages);
6233 commit_charge(newpage, memcg, false);
6235 local_irq_save(flags);
6236 mem_cgroup_charge_statistics(memcg, newpage, compound, nr_pages);
6237 memcg_check_events(memcg, newpage);
6238 local_irq_restore(flags);
6241 DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key);
6242 EXPORT_SYMBOL(memcg_sockets_enabled_key);
6244 void mem_cgroup_sk_alloc(struct sock *sk)
6246 struct mem_cgroup *memcg;
6248 if (!mem_cgroup_sockets_enabled)
6249 return;
6252 * Socket cloning can throw us here with sk_memcg already
6253 * filled. It won't however, necessarily happen from
6254 * process context. So the test for root memcg given
6255 * the current task's memcg won't help us in this case.
6257 * Respecting the original socket's memcg is a better
6258 * decision in this case.
6260 if (sk->sk_memcg) {
6261 css_get(&sk->sk_memcg->css);
6262 return;
6265 rcu_read_lock();
6266 memcg = mem_cgroup_from_task(current);
6267 if (memcg == root_mem_cgroup)
6268 goto out;
6269 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg->tcpmem_active)
6270 goto out;
6271 if (css_tryget_online(&memcg->css))
6272 sk->sk_memcg = memcg;
6273 out:
6274 rcu_read_unlock();
6277 void mem_cgroup_sk_free(struct sock *sk)
6279 if (sk->sk_memcg)
6280 css_put(&sk->sk_memcg->css);
6284 * mem_cgroup_charge_skmem - charge socket memory
6285 * @memcg: memcg to charge
6286 * @nr_pages: number of pages to charge
6288 * Charges @nr_pages to @memcg. Returns %true if the charge fit within
6289 * @memcg's configured limit, %false if the charge had to be forced.
6291 bool mem_cgroup_charge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
6293 gfp_t gfp_mask = GFP_KERNEL;
6295 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
6296 struct page_counter *fail;
6298 if (page_counter_try_charge(&memcg->tcpmem, nr_pages, &fail)) {
6299 memcg->tcpmem_pressure = 0;
6300 return true;
6302 page_counter_charge(&memcg->tcpmem, nr_pages);
6303 memcg->tcpmem_pressure = 1;
6304 return false;
6307 /* Don't block in the packet receive path */
6308 if (in_softirq())
6309 gfp_mask = GFP_NOWAIT;
6311 mod_memcg_state(memcg, MEMCG_SOCK, nr_pages);
6313 if (try_charge(memcg, gfp_mask, nr_pages) == 0)
6314 return true;
6316 try_charge(memcg, gfp_mask|__GFP_NOFAIL, nr_pages);
6317 return false;
6321 * mem_cgroup_uncharge_skmem - uncharge socket memory
6322 * @memcg: memcg to uncharge
6323 * @nr_pages: number of pages to uncharge
6325 void mem_cgroup_uncharge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
6327 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
6328 page_counter_uncharge(&memcg->tcpmem, nr_pages);
6329 return;
6332 mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages);
6334 refill_stock(memcg, nr_pages);
6337 static int __init cgroup_memory(char *s)
6339 char *token;
6341 while ((token = strsep(&s, ",")) != NULL) {
6342 if (!*token)
6343 continue;
6344 if (!strcmp(token, "nosocket"))
6345 cgroup_memory_nosocket = true;
6346 if (!strcmp(token, "nokmem"))
6347 cgroup_memory_nokmem = true;
6349 return 0;
6351 __setup("cgroup.memory=", cgroup_memory);
6354 * subsys_initcall() for memory controller.
6356 * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this
6357 * context because of lock dependencies (cgroup_lock -> cpu hotplug) but
6358 * basically everything that doesn't depend on a specific mem_cgroup structure
6359 * should be initialized from here.
6361 static int __init mem_cgroup_init(void)
6363 int cpu, node;
6365 #ifdef CONFIG_MEMCG_KMEM
6367 * Kmem cache creation is mostly done with the slab_mutex held,
6368 * so use a workqueue with limited concurrency to avoid stalling
6369 * all worker threads in case lots of cgroups are created and
6370 * destroyed simultaneously.
6372 memcg_kmem_cache_wq = alloc_workqueue("memcg_kmem_cache", 0, 1);
6373 BUG_ON(!memcg_kmem_cache_wq);
6374 #endif
6376 cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL,
6377 memcg_hotplug_cpu_dead);
6379 for_each_possible_cpu(cpu)
6380 INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
6381 drain_local_stock);
6383 for_each_node(node) {
6384 struct mem_cgroup_tree_per_node *rtpn;
6386 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL,
6387 node_online(node) ? node : NUMA_NO_NODE);
6389 rtpn->rb_root = RB_ROOT;
6390 rtpn->rb_rightmost = NULL;
6391 spin_lock_init(&rtpn->lock);
6392 soft_limit_tree.rb_tree_per_node[node] = rtpn;
6395 return 0;
6397 subsys_initcall(mem_cgroup_init);
6399 #ifdef CONFIG_MEMCG_SWAP
6400 static struct mem_cgroup *mem_cgroup_id_get_online(struct mem_cgroup *memcg)
6402 while (!refcount_inc_not_zero(&memcg->id.ref)) {
6404 * The root cgroup cannot be destroyed, so it's refcount must
6405 * always be >= 1.
6407 if (WARN_ON_ONCE(memcg == root_mem_cgroup)) {
6408 VM_BUG_ON(1);
6409 break;
6411 memcg = parent_mem_cgroup(memcg);
6412 if (!memcg)
6413 memcg = root_mem_cgroup;
6415 return memcg;
6419 * mem_cgroup_swapout - transfer a memsw charge to swap
6420 * @page: page whose memsw charge to transfer
6421 * @entry: swap entry to move the charge to
6423 * Transfer the memsw charge of @page to @entry.
6425 void mem_cgroup_swapout(struct page *page, swp_entry_t entry)
6427 struct mem_cgroup *memcg, *swap_memcg;
6428 unsigned int nr_entries;
6429 unsigned short oldid;
6431 VM_BUG_ON_PAGE(PageLRU(page), page);
6432 VM_BUG_ON_PAGE(page_count(page), page);
6434 if (!do_memsw_account())
6435 return;
6437 memcg = page->mem_cgroup;
6439 /* Readahead page, never charged */
6440 if (!memcg)
6441 return;
6444 * In case the memcg owning these pages has been offlined and doesn't
6445 * have an ID allocated to it anymore, charge the closest online
6446 * ancestor for the swap instead and transfer the memory+swap charge.
6448 swap_memcg = mem_cgroup_id_get_online(memcg);
6449 nr_entries = hpage_nr_pages(page);
6450 /* Get references for the tail pages, too */
6451 if (nr_entries > 1)
6452 mem_cgroup_id_get_many(swap_memcg, nr_entries - 1);
6453 oldid = swap_cgroup_record(entry, mem_cgroup_id(swap_memcg),
6454 nr_entries);
6455 VM_BUG_ON_PAGE(oldid, page);
6456 mod_memcg_state(swap_memcg, MEMCG_SWAP, nr_entries);
6458 page->mem_cgroup = NULL;
6460 if (!mem_cgroup_is_root(memcg))
6461 page_counter_uncharge(&memcg->memory, nr_entries);
6463 if (memcg != swap_memcg) {
6464 if (!mem_cgroup_is_root(swap_memcg))
6465 page_counter_charge(&swap_memcg->memsw, nr_entries);
6466 page_counter_uncharge(&memcg->memsw, nr_entries);
6470 * Interrupts should be disabled here because the caller holds the
6471 * i_pages lock which is taken with interrupts-off. It is
6472 * important here to have the interrupts disabled because it is the
6473 * only synchronisation we have for updating the per-CPU variables.
6475 VM_BUG_ON(!irqs_disabled());
6476 mem_cgroup_charge_statistics(memcg, page, PageTransHuge(page),
6477 -nr_entries);
6478 memcg_check_events(memcg, page);
6480 if (!mem_cgroup_is_root(memcg))
6481 css_put_many(&memcg->css, nr_entries);
6485 * mem_cgroup_try_charge_swap - try charging swap space for a page
6486 * @page: page being added to swap
6487 * @entry: swap entry to charge
6489 * Try to charge @page's memcg for the swap space at @entry.
6491 * Returns 0 on success, -ENOMEM on failure.
6493 int mem_cgroup_try_charge_swap(struct page *page, swp_entry_t entry)
6495 unsigned int nr_pages = hpage_nr_pages(page);
6496 struct page_counter *counter;
6497 struct mem_cgroup *memcg;
6498 unsigned short oldid;
6500 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) || !do_swap_account)
6501 return 0;
6503 memcg = page->mem_cgroup;
6505 /* Readahead page, never charged */
6506 if (!memcg)
6507 return 0;
6509 if (!entry.val) {
6510 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
6511 return 0;
6514 memcg = mem_cgroup_id_get_online(memcg);
6516 if (!mem_cgroup_is_root(memcg) &&
6517 !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
6518 memcg_memory_event(memcg, MEMCG_SWAP_MAX);
6519 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
6520 mem_cgroup_id_put(memcg);
6521 return -ENOMEM;
6524 /* Get references for the tail pages, too */
6525 if (nr_pages > 1)
6526 mem_cgroup_id_get_many(memcg, nr_pages - 1);
6527 oldid = swap_cgroup_record(entry, mem_cgroup_id(memcg), nr_pages);
6528 VM_BUG_ON_PAGE(oldid, page);
6529 mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
6531 return 0;
6535 * mem_cgroup_uncharge_swap - uncharge swap space
6536 * @entry: swap entry to uncharge
6537 * @nr_pages: the amount of swap space to uncharge
6539 void mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages)
6541 struct mem_cgroup *memcg;
6542 unsigned short id;
6544 if (!do_swap_account)
6545 return;
6547 id = swap_cgroup_record(entry, 0, nr_pages);
6548 rcu_read_lock();
6549 memcg = mem_cgroup_from_id(id);
6550 if (memcg) {
6551 if (!mem_cgroup_is_root(memcg)) {
6552 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
6553 page_counter_uncharge(&memcg->swap, nr_pages);
6554 else
6555 page_counter_uncharge(&memcg->memsw, nr_pages);
6557 mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
6558 mem_cgroup_id_put_many(memcg, nr_pages);
6560 rcu_read_unlock();
6563 long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg)
6565 long nr_swap_pages = get_nr_swap_pages();
6567 if (!do_swap_account || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
6568 return nr_swap_pages;
6569 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg))
6570 nr_swap_pages = min_t(long, nr_swap_pages,
6571 READ_ONCE(memcg->swap.max) -
6572 page_counter_read(&memcg->swap));
6573 return nr_swap_pages;
6576 bool mem_cgroup_swap_full(struct page *page)
6578 struct mem_cgroup *memcg;
6580 VM_BUG_ON_PAGE(!PageLocked(page), page);
6582 if (vm_swap_full())
6583 return true;
6584 if (!do_swap_account || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
6585 return false;
6587 memcg = page->mem_cgroup;
6588 if (!memcg)
6589 return false;
6591 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg))
6592 if (page_counter_read(&memcg->swap) * 2 >= memcg->swap.max)
6593 return true;
6595 return false;
6598 /* for remember boot option*/
6599 #ifdef CONFIG_MEMCG_SWAP_ENABLED
6600 static int really_do_swap_account __initdata = 1;
6601 #else
6602 static int really_do_swap_account __initdata;
6603 #endif
6605 static int __init enable_swap_account(char *s)
6607 if (!strcmp(s, "1"))
6608 really_do_swap_account = 1;
6609 else if (!strcmp(s, "0"))
6610 really_do_swap_account = 0;
6611 return 1;
6613 __setup("swapaccount=", enable_swap_account);
6615 static u64 swap_current_read(struct cgroup_subsys_state *css,
6616 struct cftype *cft)
6618 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6620 return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE;
6623 static int swap_max_show(struct seq_file *m, void *v)
6625 return seq_puts_memcg_tunable(m,
6626 READ_ONCE(mem_cgroup_from_seq(m)->swap.max));
6629 static ssize_t swap_max_write(struct kernfs_open_file *of,
6630 char *buf, size_t nbytes, loff_t off)
6632 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6633 unsigned long max;
6634 int err;
6636 buf = strstrip(buf);
6637 err = page_counter_memparse(buf, "max", &max);
6638 if (err)
6639 return err;
6641 xchg(&memcg->swap.max, max);
6643 return nbytes;
6646 static int swap_events_show(struct seq_file *m, void *v)
6648 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6650 seq_printf(m, "max %lu\n",
6651 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
6652 seq_printf(m, "fail %lu\n",
6653 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL]));
6655 return 0;
6658 static struct cftype swap_files[] = {
6660 .name = "swap.current",
6661 .flags = CFTYPE_NOT_ON_ROOT,
6662 .read_u64 = swap_current_read,
6665 .name = "swap.max",
6666 .flags = CFTYPE_NOT_ON_ROOT,
6667 .seq_show = swap_max_show,
6668 .write = swap_max_write,
6671 .name = "swap.events",
6672 .flags = CFTYPE_NOT_ON_ROOT,
6673 .file_offset = offsetof(struct mem_cgroup, swap_events_file),
6674 .seq_show = swap_events_show,
6676 { } /* terminate */
6679 static struct cftype memsw_cgroup_files[] = {
6681 .name = "memsw.usage_in_bytes",
6682 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
6683 .read_u64 = mem_cgroup_read_u64,
6686 .name = "memsw.max_usage_in_bytes",
6687 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
6688 .write = mem_cgroup_reset,
6689 .read_u64 = mem_cgroup_read_u64,
6692 .name = "memsw.limit_in_bytes",
6693 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
6694 .write = mem_cgroup_write,
6695 .read_u64 = mem_cgroup_read_u64,
6698 .name = "memsw.failcnt",
6699 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
6700 .write = mem_cgroup_reset,
6701 .read_u64 = mem_cgroup_read_u64,
6703 { }, /* terminate */
6706 static int __init mem_cgroup_swap_init(void)
6708 if (!mem_cgroup_disabled() && really_do_swap_account) {
6709 do_swap_account = 1;
6710 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys,
6711 swap_files));
6712 WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys,
6713 memsw_cgroup_files));
6715 return 0;
6717 subsys_initcall(mem_cgroup_swap_init);
6719 #endif /* CONFIG_MEMCG_SWAP */