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>
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 * This program is free software; you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation; either version 2 of the License, or
20 * (at your option) any later version.
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
28 #include <linux/res_counter.h>
29 #include <linux/memcontrol.h>
30 #include <linux/cgroup.h>
32 #include <linux/hugetlb.h>
33 #include <linux/pagemap.h>
34 #include <linux/smp.h>
35 #include <linux/page-flags.h>
36 #include <linux/backing-dev.h>
37 #include <linux/bit_spinlock.h>
38 #include <linux/rcupdate.h>
39 #include <linux/limits.h>
40 #include <linux/export.h>
41 #include <linux/mutex.h>
42 #include <linux/rbtree.h>
43 #include <linux/slab.h>
44 #include <linux/swap.h>
45 #include <linux/swapops.h>
46 #include <linux/spinlock.h>
47 #include <linux/eventfd.h>
48 #include <linux/poll.h>
49 #include <linux/sort.h>
51 #include <linux/seq_file.h>
52 #include <linux/vmalloc.h>
53 #include <linux/vmpressure.h>
54 #include <linux/mm_inline.h>
55 #include <linux/page_cgroup.h>
56 #include <linux/cpu.h>
57 #include <linux/oom.h>
58 #include <linux/lockdep.h>
59 #include <linux/file.h>
63 #include <net/tcp_memcontrol.h>
65 #include <asm/uaccess.h>
67 #include <trace/events/vmscan.h>
69 struct cgroup_subsys mem_cgroup_subsys __read_mostly;
70 EXPORT_SYMBOL(mem_cgroup_subsys);
72 #define MEM_CGROUP_RECLAIM_RETRIES 5
73 static struct mem_cgroup *root_mem_cgroup __read_mostly;
75 #ifdef CONFIG_MEMCG_SWAP
76 /* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
77 int do_swap_account __read_mostly;
79 /* for remember boot option*/
80 #ifdef CONFIG_MEMCG_SWAP_ENABLED
81 static int really_do_swap_account __initdata = 1;
83 static int really_do_swap_account __initdata = 0;
87 #define do_swap_account 0
91 static const char * const mem_cgroup_stat_names[] = {
100 enum mem_cgroup_events_index {
101 MEM_CGROUP_EVENTS_PGPGIN, /* # of pages paged in */
102 MEM_CGROUP_EVENTS_PGPGOUT, /* # of pages paged out */
103 MEM_CGROUP_EVENTS_PGFAULT, /* # of page-faults */
104 MEM_CGROUP_EVENTS_PGMAJFAULT, /* # of major page-faults */
105 MEM_CGROUP_EVENTS_NSTATS,
108 static const char * const mem_cgroup_events_names[] = {
115 static const char * const mem_cgroup_lru_names[] = {
124 * Per memcg event counter is incremented at every pagein/pageout. With THP,
125 * it will be incremated by the number of pages. This counter is used for
126 * for trigger some periodic events. This is straightforward and better
127 * than using jiffies etc. to handle periodic memcg event.
129 enum mem_cgroup_events_target {
130 MEM_CGROUP_TARGET_THRESH,
131 MEM_CGROUP_TARGET_SOFTLIMIT,
132 MEM_CGROUP_TARGET_NUMAINFO,
135 #define THRESHOLDS_EVENTS_TARGET 128
136 #define SOFTLIMIT_EVENTS_TARGET 1024
137 #define NUMAINFO_EVENTS_TARGET 1024
139 struct mem_cgroup_stat_cpu {
140 long count[MEM_CGROUP_STAT_NSTATS];
141 unsigned long events[MEM_CGROUP_EVENTS_NSTATS];
142 unsigned long nr_page_events;
143 unsigned long targets[MEM_CGROUP_NTARGETS];
146 struct mem_cgroup_reclaim_iter {
148 * last scanned hierarchy member. Valid only if last_dead_count
149 * matches memcg->dead_count of the hierarchy root group.
151 struct mem_cgroup *last_visited;
152 unsigned long last_dead_count;
154 /* scan generation, increased every round-trip */
155 unsigned int generation;
159 * per-zone information in memory controller.
161 struct mem_cgroup_per_zone {
162 struct lruvec lruvec;
163 unsigned long lru_size[NR_LRU_LISTS];
165 struct mem_cgroup_reclaim_iter reclaim_iter[DEF_PRIORITY + 1];
167 struct rb_node tree_node; /* RB tree node */
168 unsigned long long usage_in_excess;/* Set to the value by which */
169 /* the soft limit is exceeded*/
171 struct mem_cgroup *memcg; /* Back pointer, we cannot */
172 /* use container_of */
175 struct mem_cgroup_per_node {
176 struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
180 * Cgroups above their limits are maintained in a RB-Tree, independent of
181 * their hierarchy representation
184 struct mem_cgroup_tree_per_zone {
185 struct rb_root rb_root;
189 struct mem_cgroup_tree_per_node {
190 struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
193 struct mem_cgroup_tree {
194 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
197 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
199 struct mem_cgroup_threshold {
200 struct eventfd_ctx *eventfd;
205 struct mem_cgroup_threshold_ary {
206 /* An array index points to threshold just below or equal to usage. */
207 int current_threshold;
208 /* Size of entries[] */
210 /* Array of thresholds */
211 struct mem_cgroup_threshold entries[0];
214 struct mem_cgroup_thresholds {
215 /* Primary thresholds array */
216 struct mem_cgroup_threshold_ary *primary;
218 * Spare threshold array.
219 * This is needed to make mem_cgroup_unregister_event() "never fail".
220 * It must be able to store at least primary->size - 1 entries.
222 struct mem_cgroup_threshold_ary *spare;
226 struct mem_cgroup_eventfd_list {
227 struct list_head list;
228 struct eventfd_ctx *eventfd;
232 * cgroup_event represents events which userspace want to receive.
234 struct mem_cgroup_event {
236 * memcg which the event belongs to.
238 struct mem_cgroup *memcg;
240 * eventfd to signal userspace about the event.
242 struct eventfd_ctx *eventfd;
244 * Each of these stored in a list by the cgroup.
246 struct list_head list;
248 * register_event() callback will be used to add new userspace
249 * waiter for changes related to this event. Use eventfd_signal()
250 * on eventfd to send notification to userspace.
252 int (*register_event)(struct mem_cgroup *memcg,
253 struct eventfd_ctx *eventfd, const char *args);
255 * unregister_event() callback will be called when userspace closes
256 * the eventfd or on cgroup removing. This callback must be set,
257 * if you want provide notification functionality.
259 void (*unregister_event)(struct mem_cgroup *memcg,
260 struct eventfd_ctx *eventfd);
262 * All fields below needed to unregister event when
263 * userspace closes eventfd.
266 wait_queue_head_t *wqh;
268 struct work_struct remove;
271 static void mem_cgroup_threshold(struct mem_cgroup *memcg);
272 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
275 * The memory controller data structure. The memory controller controls both
276 * page cache and RSS per cgroup. We would eventually like to provide
277 * statistics based on the statistics developed by Rik Van Riel for clock-pro,
278 * to help the administrator determine what knobs to tune.
280 * TODO: Add a water mark for the memory controller. Reclaim will begin when
281 * we hit the water mark. May be even add a low water mark, such that
282 * no reclaim occurs from a cgroup at it's low water mark, this is
283 * a feature that will be implemented much later in the future.
286 struct cgroup_subsys_state css;
288 * the counter to account for memory usage
290 struct res_counter res;
292 /* vmpressure notifications */
293 struct vmpressure vmpressure;
296 * the counter to account for mem+swap usage.
298 struct res_counter memsw;
301 * the counter to account for kernel memory usage.
303 struct res_counter kmem;
305 * Should the accounting and control be hierarchical, per subtree?
308 unsigned long kmem_account_flags; /* See KMEM_ACCOUNTED_*, below */
312 atomic_t oom_wakeups;
315 /* OOM-Killer disable */
316 int oom_kill_disable;
318 /* set when res.limit == memsw.limit */
319 bool memsw_is_minimum;
321 /* protect arrays of thresholds */
322 struct mutex thresholds_lock;
324 /* thresholds for memory usage. RCU-protected */
325 struct mem_cgroup_thresholds thresholds;
327 /* thresholds for mem+swap usage. RCU-protected */
328 struct mem_cgroup_thresholds memsw_thresholds;
330 /* For oom notifier event fd */
331 struct list_head oom_notify;
334 * Should we move charges of a task when a task is moved into this
335 * mem_cgroup ? And what type of charges should we move ?
337 unsigned long move_charge_at_immigrate;
339 * set > 0 if pages under this cgroup are moving to other cgroup.
341 atomic_t moving_account;
342 /* taken only while moving_account > 0 */
343 spinlock_t move_lock;
347 struct mem_cgroup_stat_cpu __percpu *stat;
349 * used when a cpu is offlined or other synchronizations
350 * See mem_cgroup_read_stat().
352 struct mem_cgroup_stat_cpu nocpu_base;
353 spinlock_t pcp_counter_lock;
356 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_INET)
357 struct tcp_memcontrol tcp_mem;
359 #if defined(CONFIG_MEMCG_KMEM)
360 /* analogous to slab_common's slab_caches list. per-memcg */
361 struct list_head memcg_slab_caches;
362 /* Not a spinlock, we can take a lot of time walking the list */
363 struct mutex slab_caches_mutex;
364 /* Index in the kmem_cache->memcg_params->memcg_caches array */
368 int last_scanned_node;
370 nodemask_t scan_nodes;
371 atomic_t numainfo_events;
372 atomic_t numainfo_updating;
375 /* List of events which userspace want to receive */
376 struct list_head event_list;
377 spinlock_t event_list_lock;
379 struct mem_cgroup_per_node *nodeinfo[0];
380 /* WARNING: nodeinfo must be the last member here */
383 static size_t memcg_size(void)
385 return sizeof(struct mem_cgroup) +
386 nr_node_ids * sizeof(struct mem_cgroup_per_node);
389 /* internal only representation about the status of kmem accounting. */
391 KMEM_ACCOUNTED_ACTIVE = 0, /* accounted by this cgroup itself */
392 KMEM_ACCOUNTED_ACTIVATED, /* static key enabled. */
393 KMEM_ACCOUNTED_DEAD, /* dead memcg with pending kmem charges */
396 /* We account when limit is on, but only after call sites are patched */
397 #define KMEM_ACCOUNTED_MASK \
398 ((1 << KMEM_ACCOUNTED_ACTIVE) | (1 << KMEM_ACCOUNTED_ACTIVATED))
400 #ifdef CONFIG_MEMCG_KMEM
401 static inline void memcg_kmem_set_active(struct mem_cgroup *memcg)
403 set_bit(KMEM_ACCOUNTED_ACTIVE, &memcg->kmem_account_flags);
406 static bool memcg_kmem_is_active(struct mem_cgroup *memcg)
408 return test_bit(KMEM_ACCOUNTED_ACTIVE, &memcg->kmem_account_flags);
411 static void memcg_kmem_set_activated(struct mem_cgroup *memcg)
413 set_bit(KMEM_ACCOUNTED_ACTIVATED, &memcg->kmem_account_flags);
416 static void memcg_kmem_clear_activated(struct mem_cgroup *memcg)
418 clear_bit(KMEM_ACCOUNTED_ACTIVATED, &memcg->kmem_account_flags);
421 static void memcg_kmem_mark_dead(struct mem_cgroup *memcg)
424 * Our caller must use css_get() first, because memcg_uncharge_kmem()
425 * will call css_put() if it sees the memcg is dead.
428 if (test_bit(KMEM_ACCOUNTED_ACTIVE, &memcg->kmem_account_flags))
429 set_bit(KMEM_ACCOUNTED_DEAD, &memcg->kmem_account_flags);
432 static bool memcg_kmem_test_and_clear_dead(struct mem_cgroup *memcg)
434 return test_and_clear_bit(KMEM_ACCOUNTED_DEAD,
435 &memcg->kmem_account_flags);
439 /* Stuffs for move charges at task migration. */
441 * Types of charges to be moved. "move_charge_at_immitgrate" and
442 * "immigrate_flags" are treated as a left-shifted bitmap of these types.
445 MOVE_CHARGE_TYPE_ANON, /* private anonymous page and swap of it */
446 MOVE_CHARGE_TYPE_FILE, /* file page(including tmpfs) and swap of it */
450 /* "mc" and its members are protected by cgroup_mutex */
451 static struct move_charge_struct {
452 spinlock_t lock; /* for from, to */
453 struct mem_cgroup *from;
454 struct mem_cgroup *to;
455 unsigned long immigrate_flags;
456 unsigned long precharge;
457 unsigned long moved_charge;
458 unsigned long moved_swap;
459 struct task_struct *moving_task; /* a task moving charges */
460 wait_queue_head_t waitq; /* a waitq for other context */
462 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
463 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
466 static bool move_anon(void)
468 return test_bit(MOVE_CHARGE_TYPE_ANON, &mc.immigrate_flags);
471 static bool move_file(void)
473 return test_bit(MOVE_CHARGE_TYPE_FILE, &mc.immigrate_flags);
477 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
478 * limit reclaim to prevent infinite loops, if they ever occur.
480 #define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
481 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
484 MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
485 MEM_CGROUP_CHARGE_TYPE_ANON,
486 MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
487 MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
491 /* for encoding cft->private value on file */
499 #define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
500 #define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
501 #define MEMFILE_ATTR(val) ((val) & 0xffff)
502 /* Used for OOM nofiier */
503 #define OOM_CONTROL (0)
506 * Reclaim flags for mem_cgroup_hierarchical_reclaim
508 #define MEM_CGROUP_RECLAIM_NOSWAP_BIT 0x0
509 #define MEM_CGROUP_RECLAIM_NOSWAP (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
510 #define MEM_CGROUP_RECLAIM_SHRINK_BIT 0x1
511 #define MEM_CGROUP_RECLAIM_SHRINK (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
514 * The memcg_create_mutex will be held whenever a new cgroup is created.
515 * As a consequence, any change that needs to protect against new child cgroups
516 * appearing has to hold it as well.
518 static DEFINE_MUTEX(memcg_create_mutex);
520 struct mem_cgroup *mem_cgroup_from_css(struct cgroup_subsys_state *s)
522 return s ? container_of(s, struct mem_cgroup, css) : NULL;
525 /* Some nice accessors for the vmpressure. */
526 struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
529 memcg = root_mem_cgroup;
530 return &memcg->vmpressure;
533 struct cgroup_subsys_state *vmpressure_to_css(struct vmpressure *vmpr)
535 return &container_of(vmpr, struct mem_cgroup, vmpressure)->css;
538 static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg)
540 return (memcg == root_mem_cgroup);
543 /* Writing them here to avoid exposing memcg's inner layout */
544 #if defined(CONFIG_INET) && defined(CONFIG_MEMCG_KMEM)
546 void sock_update_memcg(struct sock *sk)
548 if (mem_cgroup_sockets_enabled) {
549 struct mem_cgroup *memcg;
550 struct cg_proto *cg_proto;
552 BUG_ON(!sk->sk_prot->proto_cgroup);
554 /* Socket cloning can throw us here with sk_cgrp already
555 * filled. It won't however, necessarily happen from
556 * process context. So the test for root memcg given
557 * the current task's memcg won't help us in this case.
559 * Respecting the original socket's memcg is a better
560 * decision in this case.
563 BUG_ON(mem_cgroup_is_root(sk->sk_cgrp->memcg));
564 css_get(&sk->sk_cgrp->memcg->css);
569 memcg = mem_cgroup_from_task(current);
570 cg_proto = sk->sk_prot->proto_cgroup(memcg);
571 if (!mem_cgroup_is_root(memcg) &&
572 memcg_proto_active(cg_proto) && css_tryget(&memcg->css)) {
573 sk->sk_cgrp = cg_proto;
578 EXPORT_SYMBOL(sock_update_memcg);
580 void sock_release_memcg(struct sock *sk)
582 if (mem_cgroup_sockets_enabled && sk->sk_cgrp) {
583 struct mem_cgroup *memcg;
584 WARN_ON(!sk->sk_cgrp->memcg);
585 memcg = sk->sk_cgrp->memcg;
586 css_put(&sk->sk_cgrp->memcg->css);
590 struct cg_proto *tcp_proto_cgroup(struct mem_cgroup *memcg)
592 if (!memcg || mem_cgroup_is_root(memcg))
595 return &memcg->tcp_mem.cg_proto;
597 EXPORT_SYMBOL(tcp_proto_cgroup);
599 static void disarm_sock_keys(struct mem_cgroup *memcg)
601 if (!memcg_proto_activated(&memcg->tcp_mem.cg_proto))
603 static_key_slow_dec(&memcg_socket_limit_enabled);
606 static void disarm_sock_keys(struct mem_cgroup *memcg)
611 #ifdef CONFIG_MEMCG_KMEM
613 * This will be the memcg's index in each cache's ->memcg_params->memcg_caches.
614 * There are two main reasons for not using the css_id for this:
615 * 1) this works better in sparse environments, where we have a lot of memcgs,
616 * but only a few kmem-limited. Or also, if we have, for instance, 200
617 * memcgs, and none but the 200th is kmem-limited, we'd have to have a
618 * 200 entry array for that.
620 * 2) In order not to violate the cgroup API, we would like to do all memory
621 * allocation in ->create(). At that point, we haven't yet allocated the
622 * css_id. Having a separate index prevents us from messing with the cgroup
625 * The current size of the caches array is stored in
626 * memcg_limited_groups_array_size. It will double each time we have to
629 static DEFINE_IDA(kmem_limited_groups);
630 int memcg_limited_groups_array_size;
633 * MIN_SIZE is different than 1, because we would like to avoid going through
634 * the alloc/free process all the time. In a small machine, 4 kmem-limited
635 * cgroups is a reasonable guess. In the future, it could be a parameter or
636 * tunable, but that is strictly not necessary.
638 * MAX_SIZE should be as large as the number of css_ids. Ideally, we could get
639 * this constant directly from cgroup, but it is understandable that this is
640 * better kept as an internal representation in cgroup.c. In any case, the
641 * css_id space is not getting any smaller, and we don't have to necessarily
642 * increase ours as well if it increases.
644 #define MEMCG_CACHES_MIN_SIZE 4
645 #define MEMCG_CACHES_MAX_SIZE 65535
648 * A lot of the calls to the cache allocation functions are expected to be
649 * inlined by the compiler. Since the calls to memcg_kmem_get_cache are
650 * conditional to this static branch, we'll have to allow modules that does
651 * kmem_cache_alloc and the such to see this symbol as well
653 struct static_key memcg_kmem_enabled_key;
654 EXPORT_SYMBOL(memcg_kmem_enabled_key);
656 static void disarm_kmem_keys(struct mem_cgroup *memcg)
658 if (memcg_kmem_is_active(memcg)) {
659 static_key_slow_dec(&memcg_kmem_enabled_key);
660 ida_simple_remove(&kmem_limited_groups, memcg->kmemcg_id);
663 * This check can't live in kmem destruction function,
664 * since the charges will outlive the cgroup
666 WARN_ON(res_counter_read_u64(&memcg->kmem, RES_USAGE) != 0);
669 static void disarm_kmem_keys(struct mem_cgroup *memcg)
672 #endif /* CONFIG_MEMCG_KMEM */
674 static void disarm_static_keys(struct mem_cgroup *memcg)
676 disarm_sock_keys(memcg);
677 disarm_kmem_keys(memcg);
680 static void drain_all_stock_async(struct mem_cgroup *memcg);
682 static struct mem_cgroup_per_zone *
683 mem_cgroup_zoneinfo(struct mem_cgroup *memcg, int nid, int zid)
685 VM_BUG_ON((unsigned)nid >= nr_node_ids);
686 return &memcg->nodeinfo[nid]->zoneinfo[zid];
689 struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *memcg)
694 static struct mem_cgroup_per_zone *
695 page_cgroup_zoneinfo(struct mem_cgroup *memcg, struct page *page)
697 int nid = page_to_nid(page);
698 int zid = page_zonenum(page);
700 return mem_cgroup_zoneinfo(memcg, nid, zid);
703 static struct mem_cgroup_tree_per_zone *
704 soft_limit_tree_node_zone(int nid, int zid)
706 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
709 static struct mem_cgroup_tree_per_zone *
710 soft_limit_tree_from_page(struct page *page)
712 int nid = page_to_nid(page);
713 int zid = page_zonenum(page);
715 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
719 __mem_cgroup_insert_exceeded(struct mem_cgroup *memcg,
720 struct mem_cgroup_per_zone *mz,
721 struct mem_cgroup_tree_per_zone *mctz,
722 unsigned long long new_usage_in_excess)
724 struct rb_node **p = &mctz->rb_root.rb_node;
725 struct rb_node *parent = NULL;
726 struct mem_cgroup_per_zone *mz_node;
731 mz->usage_in_excess = new_usage_in_excess;
732 if (!mz->usage_in_excess)
736 mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
738 if (mz->usage_in_excess < mz_node->usage_in_excess)
741 * We can't avoid mem cgroups that are over their soft
742 * limit by the same amount
744 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
747 rb_link_node(&mz->tree_node, parent, p);
748 rb_insert_color(&mz->tree_node, &mctz->rb_root);
753 __mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
754 struct mem_cgroup_per_zone *mz,
755 struct mem_cgroup_tree_per_zone *mctz)
759 rb_erase(&mz->tree_node, &mctz->rb_root);
764 mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
765 struct mem_cgroup_per_zone *mz,
766 struct mem_cgroup_tree_per_zone *mctz)
768 spin_lock(&mctz->lock);
769 __mem_cgroup_remove_exceeded(memcg, mz, mctz);
770 spin_unlock(&mctz->lock);
774 static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
776 unsigned long long excess;
777 struct mem_cgroup_per_zone *mz;
778 struct mem_cgroup_tree_per_zone *mctz;
779 int nid = page_to_nid(page);
780 int zid = page_zonenum(page);
781 mctz = soft_limit_tree_from_page(page);
784 * Necessary to update all ancestors when hierarchy is used.
785 * because their event counter is not touched.
787 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
788 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
789 excess = res_counter_soft_limit_excess(&memcg->res);
791 * We have to update the tree if mz is on RB-tree or
792 * mem is over its softlimit.
794 if (excess || mz->on_tree) {
795 spin_lock(&mctz->lock);
796 /* if on-tree, remove it */
798 __mem_cgroup_remove_exceeded(memcg, mz, mctz);
800 * Insert again. mz->usage_in_excess will be updated.
801 * If excess is 0, no tree ops.
803 __mem_cgroup_insert_exceeded(memcg, mz, mctz, excess);
804 spin_unlock(&mctz->lock);
809 static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
812 struct mem_cgroup_per_zone *mz;
813 struct mem_cgroup_tree_per_zone *mctz;
815 for_each_node(node) {
816 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
817 mz = mem_cgroup_zoneinfo(memcg, node, zone);
818 mctz = soft_limit_tree_node_zone(node, zone);
819 mem_cgroup_remove_exceeded(memcg, mz, mctz);
824 static struct mem_cgroup_per_zone *
825 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
827 struct rb_node *rightmost = NULL;
828 struct mem_cgroup_per_zone *mz;
832 rightmost = rb_last(&mctz->rb_root);
834 goto done; /* Nothing to reclaim from */
836 mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
838 * Remove the node now but someone else can add it back,
839 * we will to add it back at the end of reclaim to its correct
840 * position in the tree.
842 __mem_cgroup_remove_exceeded(mz->memcg, mz, mctz);
843 if (!res_counter_soft_limit_excess(&mz->memcg->res) ||
844 !css_tryget(&mz->memcg->css))
850 static struct mem_cgroup_per_zone *
851 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
853 struct mem_cgroup_per_zone *mz;
855 spin_lock(&mctz->lock);
856 mz = __mem_cgroup_largest_soft_limit_node(mctz);
857 spin_unlock(&mctz->lock);
862 * Implementation Note: reading percpu statistics for memcg.
864 * Both of vmstat[] and percpu_counter has threshold and do periodic
865 * synchronization to implement "quick" read. There are trade-off between
866 * reading cost and precision of value. Then, we may have a chance to implement
867 * a periodic synchronizion of counter in memcg's counter.
869 * But this _read() function is used for user interface now. The user accounts
870 * memory usage by memory cgroup and he _always_ requires exact value because
871 * he accounts memory. Even if we provide quick-and-fuzzy read, we always
872 * have to visit all online cpus and make sum. So, for now, unnecessary
873 * synchronization is not implemented. (just implemented for cpu hotplug)
875 * If there are kernel internal actions which can make use of some not-exact
876 * value, and reading all cpu value can be performance bottleneck in some
877 * common workload, threashold and synchonization as vmstat[] should be
880 static long mem_cgroup_read_stat(struct mem_cgroup *memcg,
881 enum mem_cgroup_stat_index idx)
887 for_each_online_cpu(cpu)
888 val += per_cpu(memcg->stat->count[idx], cpu);
889 #ifdef CONFIG_HOTPLUG_CPU
890 spin_lock(&memcg->pcp_counter_lock);
891 val += memcg->nocpu_base.count[idx];
892 spin_unlock(&memcg->pcp_counter_lock);
898 static void mem_cgroup_swap_statistics(struct mem_cgroup *memcg,
901 int val = (charge) ? 1 : -1;
902 this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_SWAP], val);
905 static unsigned long mem_cgroup_read_events(struct mem_cgroup *memcg,
906 enum mem_cgroup_events_index idx)
908 unsigned long val = 0;
912 for_each_online_cpu(cpu)
913 val += per_cpu(memcg->stat->events[idx], cpu);
914 #ifdef CONFIG_HOTPLUG_CPU
915 spin_lock(&memcg->pcp_counter_lock);
916 val += memcg->nocpu_base.events[idx];
917 spin_unlock(&memcg->pcp_counter_lock);
923 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
925 bool anon, int nr_pages)
930 * Here, RSS means 'mapped anon' and anon's SwapCache. Shmem/tmpfs is
931 * counted as CACHE even if it's on ANON LRU.
934 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS],
937 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_CACHE],
940 if (PageTransHuge(page))
941 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS_HUGE],
944 /* pagein of a big page is an event. So, ignore page size */
946 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGIN]);
948 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGOUT]);
949 nr_pages = -nr_pages; /* for event */
952 __this_cpu_add(memcg->stat->nr_page_events, nr_pages);
958 mem_cgroup_get_lru_size(struct lruvec *lruvec, enum lru_list lru)
960 struct mem_cgroup_per_zone *mz;
962 mz = container_of(lruvec, struct mem_cgroup_per_zone, lruvec);
963 return mz->lru_size[lru];
967 mem_cgroup_zone_nr_lru_pages(struct mem_cgroup *memcg, int nid, int zid,
968 unsigned int lru_mask)
970 struct mem_cgroup_per_zone *mz;
972 unsigned long ret = 0;
974 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
977 if (BIT(lru) & lru_mask)
978 ret += mz->lru_size[lru];
984 mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
985 int nid, unsigned int lru_mask)
990 for (zid = 0; zid < MAX_NR_ZONES; zid++)
991 total += mem_cgroup_zone_nr_lru_pages(memcg,
997 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
998 unsigned int lru_mask)
1003 for_each_node_state(nid, N_MEMORY)
1004 total += mem_cgroup_node_nr_lru_pages(memcg, nid, lru_mask);
1008 static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
1009 enum mem_cgroup_events_target target)
1011 unsigned long val, next;
1013 val = __this_cpu_read(memcg->stat->nr_page_events);
1014 next = __this_cpu_read(memcg->stat->targets[target]);
1015 /* from time_after() in jiffies.h */
1016 if ((long)next - (long)val < 0) {
1018 case MEM_CGROUP_TARGET_THRESH:
1019 next = val + THRESHOLDS_EVENTS_TARGET;
1021 case MEM_CGROUP_TARGET_SOFTLIMIT:
1022 next = val + SOFTLIMIT_EVENTS_TARGET;
1024 case MEM_CGROUP_TARGET_NUMAINFO:
1025 next = val + NUMAINFO_EVENTS_TARGET;
1030 __this_cpu_write(memcg->stat->targets[target], next);
1037 * Check events in order.
1040 static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
1043 /* threshold event is triggered in finer grain than soft limit */
1044 if (unlikely(mem_cgroup_event_ratelimit(memcg,
1045 MEM_CGROUP_TARGET_THRESH))) {
1047 bool do_numainfo __maybe_unused;
1049 do_softlimit = mem_cgroup_event_ratelimit(memcg,
1050 MEM_CGROUP_TARGET_SOFTLIMIT);
1051 #if MAX_NUMNODES > 1
1052 do_numainfo = mem_cgroup_event_ratelimit(memcg,
1053 MEM_CGROUP_TARGET_NUMAINFO);
1057 mem_cgroup_threshold(memcg);
1058 if (unlikely(do_softlimit))
1059 mem_cgroup_update_tree(memcg, page);
1060 #if MAX_NUMNODES > 1
1061 if (unlikely(do_numainfo))
1062 atomic_inc(&memcg->numainfo_events);
1068 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
1071 * mm_update_next_owner() may clear mm->owner to NULL
1072 * if it races with swapoff, page migration, etc.
1073 * So this can be called with p == NULL.
1078 return mem_cgroup_from_css(task_css(p, mem_cgroup_subsys_id));
1081 struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
1083 struct mem_cgroup *memcg = NULL;
1088 * Because we have no locks, mm->owner's may be being moved to other
1089 * cgroup. We use css_tryget() here even if this looks
1090 * pessimistic (rather than adding locks here).
1094 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
1095 if (unlikely(!memcg))
1097 } while (!css_tryget(&memcg->css));
1103 * Returns a next (in a pre-order walk) alive memcg (with elevated css
1104 * ref. count) or NULL if the whole root's subtree has been visited.
1106 * helper function to be used by mem_cgroup_iter
1108 static struct mem_cgroup *__mem_cgroup_iter_next(struct mem_cgroup *root,
1109 struct mem_cgroup *last_visited)
1111 struct cgroup_subsys_state *prev_css, *next_css;
1113 prev_css = last_visited ? &last_visited->css : NULL;
1115 next_css = css_next_descendant_pre(prev_css, &root->css);
1118 * Even if we found a group we have to make sure it is
1119 * alive. css && !memcg means that the groups should be
1120 * skipped and we should continue the tree walk.
1121 * last_visited css is safe to use because it is
1122 * protected by css_get and the tree walk is rcu safe.
1125 struct mem_cgroup *mem = mem_cgroup_from_css(next_css);
1127 if (css_tryget(&mem->css))
1130 prev_css = next_css;
1138 static void mem_cgroup_iter_invalidate(struct mem_cgroup *root)
1141 * When a group in the hierarchy below root is destroyed, the
1142 * hierarchy iterator can no longer be trusted since it might
1143 * have pointed to the destroyed group. Invalidate it.
1145 atomic_inc(&root->dead_count);
1148 static struct mem_cgroup *
1149 mem_cgroup_iter_load(struct mem_cgroup_reclaim_iter *iter,
1150 struct mem_cgroup *root,
1153 struct mem_cgroup *position = NULL;
1155 * A cgroup destruction happens in two stages: offlining and
1156 * release. They are separated by a RCU grace period.
1158 * If the iterator is valid, we may still race with an
1159 * offlining. The RCU lock ensures the object won't be
1160 * released, tryget will fail if we lost the race.
1162 *sequence = atomic_read(&root->dead_count);
1163 if (iter->last_dead_count == *sequence) {
1165 position = iter->last_visited;
1166 if (position && !css_tryget(&position->css))
1172 static void mem_cgroup_iter_update(struct mem_cgroup_reclaim_iter *iter,
1173 struct mem_cgroup *last_visited,
1174 struct mem_cgroup *new_position,
1178 css_put(&last_visited->css);
1180 * We store the sequence count from the time @last_visited was
1181 * loaded successfully instead of rereading it here so that we
1182 * don't lose destruction events in between. We could have
1183 * raced with the destruction of @new_position after all.
1185 iter->last_visited = new_position;
1187 iter->last_dead_count = sequence;
1191 * mem_cgroup_iter - iterate over memory cgroup hierarchy
1192 * @root: hierarchy root
1193 * @prev: previously returned memcg, NULL on first invocation
1194 * @reclaim: cookie for shared reclaim walks, NULL for full walks
1196 * Returns references to children of the hierarchy below @root, or
1197 * @root itself, or %NULL after a full round-trip.
1199 * Caller must pass the return value in @prev on subsequent
1200 * invocations for reference counting, or use mem_cgroup_iter_break()
1201 * to cancel a hierarchy walk before the round-trip is complete.
1203 * Reclaimers can specify a zone and a priority level in @reclaim to
1204 * divide up the memcgs in the hierarchy among all concurrent
1205 * reclaimers operating on the same zone and priority.
1207 struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
1208 struct mem_cgroup *prev,
1209 struct mem_cgroup_reclaim_cookie *reclaim)
1211 struct mem_cgroup *memcg = NULL;
1212 struct mem_cgroup *last_visited = NULL;
1214 if (mem_cgroup_disabled())
1218 root = root_mem_cgroup;
1220 if (prev && !reclaim)
1221 last_visited = prev;
1223 if (!root->use_hierarchy && root != root_mem_cgroup) {
1231 struct mem_cgroup_reclaim_iter *uninitialized_var(iter);
1232 int uninitialized_var(seq);
1235 int nid = zone_to_nid(reclaim->zone);
1236 int zid = zone_idx(reclaim->zone);
1237 struct mem_cgroup_per_zone *mz;
1239 mz = mem_cgroup_zoneinfo(root, nid, zid);
1240 iter = &mz->reclaim_iter[reclaim->priority];
1241 if (prev && reclaim->generation != iter->generation) {
1242 iter->last_visited = NULL;
1246 last_visited = mem_cgroup_iter_load(iter, root, &seq);
1249 memcg = __mem_cgroup_iter_next(root, last_visited);
1252 mem_cgroup_iter_update(iter, last_visited, memcg, seq);
1256 else if (!prev && memcg)
1257 reclaim->generation = iter->generation;
1266 if (prev && prev != root)
1267 css_put(&prev->css);
1273 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1274 * @root: hierarchy root
1275 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1277 void mem_cgroup_iter_break(struct mem_cgroup *root,
1278 struct mem_cgroup *prev)
1281 root = root_mem_cgroup;
1282 if (prev && prev != root)
1283 css_put(&prev->css);
1287 * Iteration constructs for visiting all cgroups (under a tree). If
1288 * loops are exited prematurely (break), mem_cgroup_iter_break() must
1289 * be used for reference counting.
1291 #define for_each_mem_cgroup_tree(iter, root) \
1292 for (iter = mem_cgroup_iter(root, NULL, NULL); \
1294 iter = mem_cgroup_iter(root, iter, NULL))
1296 #define for_each_mem_cgroup(iter) \
1297 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
1299 iter = mem_cgroup_iter(NULL, iter, NULL))
1301 void __mem_cgroup_count_vm_event(struct mm_struct *mm, enum vm_event_item idx)
1303 struct mem_cgroup *memcg;
1306 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
1307 if (unlikely(!memcg))
1312 this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGFAULT]);
1315 this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGMAJFAULT]);
1323 EXPORT_SYMBOL(__mem_cgroup_count_vm_event);
1326 * mem_cgroup_zone_lruvec - get the lru list vector for a zone and memcg
1327 * @zone: zone of the wanted lruvec
1328 * @memcg: memcg of the wanted lruvec
1330 * Returns the lru list vector holding pages for the given @zone and
1331 * @mem. This can be the global zone lruvec, if the memory controller
1334 struct lruvec *mem_cgroup_zone_lruvec(struct zone *zone,
1335 struct mem_cgroup *memcg)
1337 struct mem_cgroup_per_zone *mz;
1338 struct lruvec *lruvec;
1340 if (mem_cgroup_disabled()) {
1341 lruvec = &zone->lruvec;
1345 mz = mem_cgroup_zoneinfo(memcg, zone_to_nid(zone), zone_idx(zone));
1346 lruvec = &mz->lruvec;
1349 * Since a node can be onlined after the mem_cgroup was created,
1350 * we have to be prepared to initialize lruvec->zone here;
1351 * and if offlined then reonlined, we need to reinitialize it.
1353 if (unlikely(lruvec->zone != zone))
1354 lruvec->zone = zone;
1359 * Following LRU functions are allowed to be used without PCG_LOCK.
1360 * Operations are called by routine of global LRU independently from memcg.
1361 * What we have to take care of here is validness of pc->mem_cgroup.
1363 * Changes to pc->mem_cgroup happens when
1366 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
1367 * It is added to LRU before charge.
1368 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
1369 * When moving account, the page is not on LRU. It's isolated.
1373 * mem_cgroup_page_lruvec - return lruvec for adding an lru page
1375 * @zone: zone of the page
1377 struct lruvec *mem_cgroup_page_lruvec(struct page *page, struct zone *zone)
1379 struct mem_cgroup_per_zone *mz;
1380 struct mem_cgroup *memcg;
1381 struct page_cgroup *pc;
1382 struct lruvec *lruvec;
1384 if (mem_cgroup_disabled()) {
1385 lruvec = &zone->lruvec;
1389 pc = lookup_page_cgroup(page);
1390 memcg = pc->mem_cgroup;
1393 * Surreptitiously switch any uncharged offlist page to root:
1394 * an uncharged page off lru does nothing to secure
1395 * its former mem_cgroup from sudden removal.
1397 * Our caller holds lru_lock, and PageCgroupUsed is updated
1398 * under page_cgroup lock: between them, they make all uses
1399 * of pc->mem_cgroup safe.
1401 if (!PageLRU(page) && !PageCgroupUsed(pc) && memcg != root_mem_cgroup)
1402 pc->mem_cgroup = memcg = root_mem_cgroup;
1404 mz = page_cgroup_zoneinfo(memcg, page);
1405 lruvec = &mz->lruvec;
1408 * Since a node can be onlined after the mem_cgroup was created,
1409 * we have to be prepared to initialize lruvec->zone here;
1410 * and if offlined then reonlined, we need to reinitialize it.
1412 if (unlikely(lruvec->zone != zone))
1413 lruvec->zone = zone;
1418 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1419 * @lruvec: mem_cgroup per zone lru vector
1420 * @lru: index of lru list the page is sitting on
1421 * @nr_pages: positive when adding or negative when removing
1423 * This function must be called when a page is added to or removed from an
1426 void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
1429 struct mem_cgroup_per_zone *mz;
1430 unsigned long *lru_size;
1432 if (mem_cgroup_disabled())
1435 mz = container_of(lruvec, struct mem_cgroup_per_zone, lruvec);
1436 lru_size = mz->lru_size + lru;
1437 *lru_size += nr_pages;
1438 VM_BUG_ON((long)(*lru_size) < 0);
1442 * Checks whether given mem is same or in the root_mem_cgroup's
1445 bool __mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
1446 struct mem_cgroup *memcg)
1448 if (root_memcg == memcg)
1450 if (!root_memcg->use_hierarchy || !memcg)
1452 return css_is_ancestor(&memcg->css, &root_memcg->css);
1455 static bool mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
1456 struct mem_cgroup *memcg)
1461 ret = __mem_cgroup_same_or_subtree(root_memcg, memcg);
1466 bool task_in_mem_cgroup(struct task_struct *task,
1467 const struct mem_cgroup *memcg)
1469 struct mem_cgroup *curr = NULL;
1470 struct task_struct *p;
1473 p = find_lock_task_mm(task);
1475 curr = try_get_mem_cgroup_from_mm(p->mm);
1479 * All threads may have already detached their mm's, but the oom
1480 * killer still needs to detect if they have already been oom
1481 * killed to prevent needlessly killing additional tasks.
1484 curr = mem_cgroup_from_task(task);
1486 css_get(&curr->css);
1492 * We should check use_hierarchy of "memcg" not "curr". Because checking
1493 * use_hierarchy of "curr" here make this function true if hierarchy is
1494 * enabled in "curr" and "curr" is a child of "memcg" in *cgroup*
1495 * hierarchy(even if use_hierarchy is disabled in "memcg").
1497 ret = mem_cgroup_same_or_subtree(memcg, curr);
1498 css_put(&curr->css);
1502 int mem_cgroup_inactive_anon_is_low(struct lruvec *lruvec)
1504 unsigned long inactive_ratio;
1505 unsigned long inactive;
1506 unsigned long active;
1509 inactive = mem_cgroup_get_lru_size(lruvec, LRU_INACTIVE_ANON);
1510 active = mem_cgroup_get_lru_size(lruvec, LRU_ACTIVE_ANON);
1512 gb = (inactive + active) >> (30 - PAGE_SHIFT);
1514 inactive_ratio = int_sqrt(10 * gb);
1518 return inactive * inactive_ratio < active;
1521 #define mem_cgroup_from_res_counter(counter, member) \
1522 container_of(counter, struct mem_cgroup, member)
1525 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1526 * @memcg: the memory cgroup
1528 * Returns the maximum amount of memory @mem can be charged with, in
1531 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1533 unsigned long long margin;
1535 margin = res_counter_margin(&memcg->res);
1536 if (do_swap_account)
1537 margin = min(margin, res_counter_margin(&memcg->memsw));
1538 return margin >> PAGE_SHIFT;
1541 int mem_cgroup_swappiness(struct mem_cgroup *memcg)
1544 if (!css_parent(&memcg->css))
1545 return vm_swappiness;
1547 return memcg->swappiness;
1551 * memcg->moving_account is used for checking possibility that some thread is
1552 * calling move_account(). When a thread on CPU-A starts moving pages under
1553 * a memcg, other threads should check memcg->moving_account under
1554 * rcu_read_lock(), like this:
1558 * memcg->moving_account+1 if (memcg->mocing_account)
1560 * synchronize_rcu() update something.
1565 /* for quick checking without looking up memcg */
1566 atomic_t memcg_moving __read_mostly;
1568 static void mem_cgroup_start_move(struct mem_cgroup *memcg)
1570 atomic_inc(&memcg_moving);
1571 atomic_inc(&memcg->moving_account);
1575 static void mem_cgroup_end_move(struct mem_cgroup *memcg)
1578 * Now, mem_cgroup_clear_mc() may call this function with NULL.
1579 * We check NULL in callee rather than caller.
1582 atomic_dec(&memcg_moving);
1583 atomic_dec(&memcg->moving_account);
1588 * 2 routines for checking "mem" is under move_account() or not.
1590 * mem_cgroup_stolen() - checking whether a cgroup is mc.from or not. This
1591 * is used for avoiding races in accounting. If true,
1592 * pc->mem_cgroup may be overwritten.
1594 * mem_cgroup_under_move() - checking a cgroup is mc.from or mc.to or
1595 * under hierarchy of moving cgroups. This is for
1596 * waiting at hith-memory prressure caused by "move".
1599 static bool mem_cgroup_stolen(struct mem_cgroup *memcg)
1601 VM_BUG_ON(!rcu_read_lock_held());
1602 return atomic_read(&memcg->moving_account) > 0;
1605 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1607 struct mem_cgroup *from;
1608 struct mem_cgroup *to;
1611 * Unlike task_move routines, we access mc.to, mc.from not under
1612 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1614 spin_lock(&mc.lock);
1620 ret = mem_cgroup_same_or_subtree(memcg, from)
1621 || mem_cgroup_same_or_subtree(memcg, to);
1623 spin_unlock(&mc.lock);
1627 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1629 if (mc.moving_task && current != mc.moving_task) {
1630 if (mem_cgroup_under_move(memcg)) {
1632 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1633 /* moving charge context might have finished. */
1636 finish_wait(&mc.waitq, &wait);
1644 * Take this lock when
1645 * - a code tries to modify page's memcg while it's USED.
1646 * - a code tries to modify page state accounting in a memcg.
1647 * see mem_cgroup_stolen(), too.
1649 static void move_lock_mem_cgroup(struct mem_cgroup *memcg,
1650 unsigned long *flags)
1652 spin_lock_irqsave(&memcg->move_lock, *flags);
1655 static void move_unlock_mem_cgroup(struct mem_cgroup *memcg,
1656 unsigned long *flags)
1658 spin_unlock_irqrestore(&memcg->move_lock, *flags);
1661 #define K(x) ((x) << (PAGE_SHIFT-10))
1663 * mem_cgroup_print_oom_info: Print OOM information relevant to memory controller.
1664 * @memcg: The memory cgroup that went over limit
1665 * @p: Task that is going to be killed
1667 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1670 void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1672 struct cgroup *task_cgrp;
1673 struct cgroup *mem_cgrp;
1675 * Need a buffer in BSS, can't rely on allocations. The code relies
1676 * on the assumption that OOM is serialized for memory controller.
1677 * If this assumption is broken, revisit this code.
1679 static char memcg_name[PATH_MAX];
1681 struct mem_cgroup *iter;
1689 mem_cgrp = memcg->css.cgroup;
1690 task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
1692 ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
1695 * Unfortunately, we are unable to convert to a useful name
1696 * But we'll still print out the usage information
1703 pr_info("Task in %s killed", memcg_name);
1706 ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
1714 * Continues from above, so we don't need an KERN_ level
1716 pr_cont(" as a result of limit of %s\n", memcg_name);
1719 pr_info("memory: usage %llukB, limit %llukB, failcnt %llu\n",
1720 res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
1721 res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
1722 res_counter_read_u64(&memcg->res, RES_FAILCNT));
1723 pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %llu\n",
1724 res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
1725 res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
1726 res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
1727 pr_info("kmem: usage %llukB, limit %llukB, failcnt %llu\n",
1728 res_counter_read_u64(&memcg->kmem, RES_USAGE) >> 10,
1729 res_counter_read_u64(&memcg->kmem, RES_LIMIT) >> 10,
1730 res_counter_read_u64(&memcg->kmem, RES_FAILCNT));
1732 for_each_mem_cgroup_tree(iter, memcg) {
1733 pr_info("Memory cgroup stats");
1736 ret = cgroup_path(iter->css.cgroup, memcg_name, PATH_MAX);
1738 pr_cont(" for %s", memcg_name);
1742 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
1743 if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
1745 pr_cont(" %s:%ldKB", mem_cgroup_stat_names[i],
1746 K(mem_cgroup_read_stat(iter, i)));
1749 for (i = 0; i < NR_LRU_LISTS; i++)
1750 pr_cont(" %s:%luKB", mem_cgroup_lru_names[i],
1751 K(mem_cgroup_nr_lru_pages(iter, BIT(i))));
1758 * This function returns the number of memcg under hierarchy tree. Returns
1759 * 1(self count) if no children.
1761 static int mem_cgroup_count_children(struct mem_cgroup *memcg)
1764 struct mem_cgroup *iter;
1766 for_each_mem_cgroup_tree(iter, memcg)
1772 * Return the memory (and swap, if configured) limit for a memcg.
1774 static u64 mem_cgroup_get_limit(struct mem_cgroup *memcg)
1778 limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
1781 * Do not consider swap space if we cannot swap due to swappiness
1783 if (mem_cgroup_swappiness(memcg)) {
1786 limit += total_swap_pages << PAGE_SHIFT;
1787 memsw = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
1790 * If memsw is finite and limits the amount of swap space
1791 * available to this memcg, return that limit.
1793 limit = min(limit, memsw);
1799 static void mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
1802 struct mem_cgroup *iter;
1803 unsigned long chosen_points = 0;
1804 unsigned long totalpages;
1805 unsigned int points = 0;
1806 struct task_struct *chosen = NULL;
1809 * If current has a pending SIGKILL or is exiting, then automatically
1810 * select it. The goal is to allow it to allocate so that it may
1811 * quickly exit and free its memory.
1813 if (fatal_signal_pending(current) || current->flags & PF_EXITING) {
1814 set_thread_flag(TIF_MEMDIE);
1818 check_panic_on_oom(CONSTRAINT_MEMCG, gfp_mask, order, NULL);
1819 totalpages = mem_cgroup_get_limit(memcg) >> PAGE_SHIFT ? : 1;
1820 for_each_mem_cgroup_tree(iter, memcg) {
1821 struct css_task_iter it;
1822 struct task_struct *task;
1824 css_task_iter_start(&iter->css, &it);
1825 while ((task = css_task_iter_next(&it))) {
1826 switch (oom_scan_process_thread(task, totalpages, NULL,
1828 case OOM_SCAN_SELECT:
1830 put_task_struct(chosen);
1832 chosen_points = ULONG_MAX;
1833 get_task_struct(chosen);
1835 case OOM_SCAN_CONTINUE:
1837 case OOM_SCAN_ABORT:
1838 css_task_iter_end(&it);
1839 mem_cgroup_iter_break(memcg, iter);
1841 put_task_struct(chosen);
1846 points = oom_badness(task, memcg, NULL, totalpages);
1847 if (points > chosen_points) {
1849 put_task_struct(chosen);
1851 chosen_points = points;
1852 get_task_struct(chosen);
1855 css_task_iter_end(&it);
1860 points = chosen_points * 1000 / totalpages;
1861 oom_kill_process(chosen, gfp_mask, order, points, totalpages, memcg,
1862 NULL, "Memory cgroup out of memory");
1865 static unsigned long mem_cgroup_reclaim(struct mem_cgroup *memcg,
1867 unsigned long flags)
1869 unsigned long total = 0;
1870 bool noswap = false;
1873 if (flags & MEM_CGROUP_RECLAIM_NOSWAP)
1875 if (!(flags & MEM_CGROUP_RECLAIM_SHRINK) && memcg->memsw_is_minimum)
1878 for (loop = 0; loop < MEM_CGROUP_MAX_RECLAIM_LOOPS; loop++) {
1880 drain_all_stock_async(memcg);
1881 total += try_to_free_mem_cgroup_pages(memcg, gfp_mask, noswap);
1883 * Allow limit shrinkers, which are triggered directly
1884 * by userspace, to catch signals and stop reclaim
1885 * after minimal progress, regardless of the margin.
1887 if (total && (flags & MEM_CGROUP_RECLAIM_SHRINK))
1889 if (mem_cgroup_margin(memcg))
1892 * If nothing was reclaimed after two attempts, there
1893 * may be no reclaimable pages in this hierarchy.
1902 * test_mem_cgroup_node_reclaimable
1903 * @memcg: the target memcg
1904 * @nid: the node ID to be checked.
1905 * @noswap : specify true here if the user wants flle only information.
1907 * This function returns whether the specified memcg contains any
1908 * reclaimable pages on a node. Returns true if there are any reclaimable
1909 * pages in the node.
1911 static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *memcg,
1912 int nid, bool noswap)
1914 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_FILE))
1916 if (noswap || !total_swap_pages)
1918 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_ANON))
1923 #if MAX_NUMNODES > 1
1926 * Always updating the nodemask is not very good - even if we have an empty
1927 * list or the wrong list here, we can start from some node and traverse all
1928 * nodes based on the zonelist. So update the list loosely once per 10 secs.
1931 static void mem_cgroup_may_update_nodemask(struct mem_cgroup *memcg)
1935 * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
1936 * pagein/pageout changes since the last update.
1938 if (!atomic_read(&memcg->numainfo_events))
1940 if (atomic_inc_return(&memcg->numainfo_updating) > 1)
1943 /* make a nodemask where this memcg uses memory from */
1944 memcg->scan_nodes = node_states[N_MEMORY];
1946 for_each_node_mask(nid, node_states[N_MEMORY]) {
1948 if (!test_mem_cgroup_node_reclaimable(memcg, nid, false))
1949 node_clear(nid, memcg->scan_nodes);
1952 atomic_set(&memcg->numainfo_events, 0);
1953 atomic_set(&memcg->numainfo_updating, 0);
1957 * Selecting a node where we start reclaim from. Because what we need is just
1958 * reducing usage counter, start from anywhere is O,K. Considering
1959 * memory reclaim from current node, there are pros. and cons.
1961 * Freeing memory from current node means freeing memory from a node which
1962 * we'll use or we've used. So, it may make LRU bad. And if several threads
1963 * hit limits, it will see a contention on a node. But freeing from remote
1964 * node means more costs for memory reclaim because of memory latency.
1966 * Now, we use round-robin. Better algorithm is welcomed.
1968 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1972 mem_cgroup_may_update_nodemask(memcg);
1973 node = memcg->last_scanned_node;
1975 node = next_node(node, memcg->scan_nodes);
1976 if (node == MAX_NUMNODES)
1977 node = first_node(memcg->scan_nodes);
1979 * We call this when we hit limit, not when pages are added to LRU.
1980 * No LRU may hold pages because all pages are UNEVICTABLE or
1981 * memcg is too small and all pages are not on LRU. In that case,
1982 * we use curret node.
1984 if (unlikely(node == MAX_NUMNODES))
1985 node = numa_node_id();
1987 memcg->last_scanned_node = node;
1992 * Check all nodes whether it contains reclaimable pages or not.
1993 * For quick scan, we make use of scan_nodes. This will allow us to skip
1994 * unused nodes. But scan_nodes is lazily updated and may not cotain
1995 * enough new information. We need to do double check.
1997 static bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
2002 * quick check...making use of scan_node.
2003 * We can skip unused nodes.
2005 if (!nodes_empty(memcg->scan_nodes)) {
2006 for (nid = first_node(memcg->scan_nodes);
2008 nid = next_node(nid, memcg->scan_nodes)) {
2010 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
2015 * Check rest of nodes.
2017 for_each_node_state(nid, N_MEMORY) {
2018 if (node_isset(nid, memcg->scan_nodes))
2020 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
2027 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
2032 static bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
2034 return test_mem_cgroup_node_reclaimable(memcg, 0, noswap);
2038 static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
2041 unsigned long *total_scanned)
2043 struct mem_cgroup *victim = NULL;
2046 unsigned long excess;
2047 unsigned long nr_scanned;
2048 struct mem_cgroup_reclaim_cookie reclaim = {
2053 excess = res_counter_soft_limit_excess(&root_memcg->res) >> PAGE_SHIFT;
2056 victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
2061 * If we have not been able to reclaim
2062 * anything, it might because there are
2063 * no reclaimable pages under this hierarchy
2068 * We want to do more targeted reclaim.
2069 * excess >> 2 is not to excessive so as to
2070 * reclaim too much, nor too less that we keep
2071 * coming back to reclaim from this cgroup
2073 if (total >= (excess >> 2) ||
2074 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
2079 if (!mem_cgroup_reclaimable(victim, false))
2081 total += mem_cgroup_shrink_node_zone(victim, gfp_mask, false,
2083 *total_scanned += nr_scanned;
2084 if (!res_counter_soft_limit_excess(&root_memcg->res))
2087 mem_cgroup_iter_break(root_memcg, victim);
2091 #ifdef CONFIG_LOCKDEP
2092 static struct lockdep_map memcg_oom_lock_dep_map = {
2093 .name = "memcg_oom_lock",
2097 static DEFINE_SPINLOCK(memcg_oom_lock);
2100 * Check OOM-Killer is already running under our hierarchy.
2101 * If someone is running, return false.
2103 static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
2105 struct mem_cgroup *iter, *failed = NULL;
2107 spin_lock(&memcg_oom_lock);
2109 for_each_mem_cgroup_tree(iter, memcg) {
2110 if (iter->oom_lock) {
2112 * this subtree of our hierarchy is already locked
2113 * so we cannot give a lock.
2116 mem_cgroup_iter_break(memcg, iter);
2119 iter->oom_lock = true;
2124 * OK, we failed to lock the whole subtree so we have
2125 * to clean up what we set up to the failing subtree
2127 for_each_mem_cgroup_tree(iter, memcg) {
2128 if (iter == failed) {
2129 mem_cgroup_iter_break(memcg, iter);
2132 iter->oom_lock = false;
2135 mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_);
2137 spin_unlock(&memcg_oom_lock);
2142 static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
2144 struct mem_cgroup *iter;
2146 spin_lock(&memcg_oom_lock);
2147 mutex_release(&memcg_oom_lock_dep_map, 1, _RET_IP_);
2148 for_each_mem_cgroup_tree(iter, memcg)
2149 iter->oom_lock = false;
2150 spin_unlock(&memcg_oom_lock);
2153 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
2155 struct mem_cgroup *iter;
2157 for_each_mem_cgroup_tree(iter, memcg)
2158 atomic_inc(&iter->under_oom);
2161 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
2163 struct mem_cgroup *iter;
2166 * When a new child is created while the hierarchy is under oom,
2167 * mem_cgroup_oom_lock() may not be called. We have to use
2168 * atomic_add_unless() here.
2170 for_each_mem_cgroup_tree(iter, memcg)
2171 atomic_add_unless(&iter->under_oom, -1, 0);
2174 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
2176 struct oom_wait_info {
2177 struct mem_cgroup *memcg;
2181 static int memcg_oom_wake_function(wait_queue_t *wait,
2182 unsigned mode, int sync, void *arg)
2184 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
2185 struct mem_cgroup *oom_wait_memcg;
2186 struct oom_wait_info *oom_wait_info;
2188 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
2189 oom_wait_memcg = oom_wait_info->memcg;
2192 * Both of oom_wait_info->memcg and wake_memcg are stable under us.
2193 * Then we can use css_is_ancestor without taking care of RCU.
2195 if (!mem_cgroup_same_or_subtree(oom_wait_memcg, wake_memcg)
2196 && !mem_cgroup_same_or_subtree(wake_memcg, oom_wait_memcg))
2198 return autoremove_wake_function(wait, mode, sync, arg);
2201 static void memcg_wakeup_oom(struct mem_cgroup *memcg)
2203 atomic_inc(&memcg->oom_wakeups);
2204 /* for filtering, pass "memcg" as argument. */
2205 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
2208 static void memcg_oom_recover(struct mem_cgroup *memcg)
2210 if (memcg && atomic_read(&memcg->under_oom))
2211 memcg_wakeup_oom(memcg);
2214 static void mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
2216 if (!current->memcg_oom.may_oom)
2219 * We are in the middle of the charge context here, so we
2220 * don't want to block when potentially sitting on a callstack
2221 * that holds all kinds of filesystem and mm locks.
2223 * Also, the caller may handle a failed allocation gracefully
2224 * (like optional page cache readahead) and so an OOM killer
2225 * invocation might not even be necessary.
2227 * That's why we don't do anything here except remember the
2228 * OOM context and then deal with it at the end of the page
2229 * fault when the stack is unwound, the locks are released,
2230 * and when we know whether the fault was overall successful.
2232 css_get(&memcg->css);
2233 current->memcg_oom.memcg = memcg;
2234 current->memcg_oom.gfp_mask = mask;
2235 current->memcg_oom.order = order;
2239 * mem_cgroup_oom_synchronize - complete memcg OOM handling
2240 * @handle: actually kill/wait or just clean up the OOM state
2242 * This has to be called at the end of a page fault if the memcg OOM
2243 * handler was enabled.
2245 * Memcg supports userspace OOM handling where failed allocations must
2246 * sleep on a waitqueue until the userspace task resolves the
2247 * situation. Sleeping directly in the charge context with all kinds
2248 * of locks held is not a good idea, instead we remember an OOM state
2249 * in the task and mem_cgroup_oom_synchronize() has to be called at
2250 * the end of the page fault to complete the OOM handling.
2252 * Returns %true if an ongoing memcg OOM situation was detected and
2253 * completed, %false otherwise.
2255 bool mem_cgroup_oom_synchronize(bool handle)
2257 struct mem_cgroup *memcg = current->memcg_oom.memcg;
2258 struct oom_wait_info owait;
2261 /* OOM is global, do not handle */
2268 owait.memcg = memcg;
2269 owait.wait.flags = 0;
2270 owait.wait.func = memcg_oom_wake_function;
2271 owait.wait.private = current;
2272 INIT_LIST_HEAD(&owait.wait.task_list);
2274 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
2275 mem_cgroup_mark_under_oom(memcg);
2277 locked = mem_cgroup_oom_trylock(memcg);
2280 mem_cgroup_oom_notify(memcg);
2282 if (locked && !memcg->oom_kill_disable) {
2283 mem_cgroup_unmark_under_oom(memcg);
2284 finish_wait(&memcg_oom_waitq, &owait.wait);
2285 mem_cgroup_out_of_memory(memcg, current->memcg_oom.gfp_mask,
2286 current->memcg_oom.order);
2289 mem_cgroup_unmark_under_oom(memcg);
2290 finish_wait(&memcg_oom_waitq, &owait.wait);
2294 mem_cgroup_oom_unlock(memcg);
2296 * There is no guarantee that an OOM-lock contender
2297 * sees the wakeups triggered by the OOM kill
2298 * uncharges. Wake any sleepers explicitely.
2300 memcg_oom_recover(memcg);
2303 current->memcg_oom.memcg = NULL;
2304 css_put(&memcg->css);
2309 * Currently used to update mapped file statistics, but the routine can be
2310 * generalized to update other statistics as well.
2312 * Notes: Race condition
2314 * We usually use page_cgroup_lock() for accessing page_cgroup member but
2315 * it tends to be costly. But considering some conditions, we doesn't need
2316 * to do so _always_.
2318 * Considering "charge", lock_page_cgroup() is not required because all
2319 * file-stat operations happen after a page is attached to radix-tree. There
2320 * are no race with "charge".
2322 * Considering "uncharge", we know that memcg doesn't clear pc->mem_cgroup
2323 * at "uncharge" intentionally. So, we always see valid pc->mem_cgroup even
2324 * if there are race with "uncharge". Statistics itself is properly handled
2327 * Considering "move", this is an only case we see a race. To make the race
2328 * small, we check mm->moving_account and detect there are possibility of race
2329 * If there is, we take a lock.
2332 void __mem_cgroup_begin_update_page_stat(struct page *page,
2333 bool *locked, unsigned long *flags)
2335 struct mem_cgroup *memcg;
2336 struct page_cgroup *pc;
2338 pc = lookup_page_cgroup(page);
2340 memcg = pc->mem_cgroup;
2341 if (unlikely(!memcg || !PageCgroupUsed(pc)))
2344 * If this memory cgroup is not under account moving, we don't
2345 * need to take move_lock_mem_cgroup(). Because we already hold
2346 * rcu_read_lock(), any calls to move_account will be delayed until
2347 * rcu_read_unlock() if mem_cgroup_stolen() == true.
2349 if (!mem_cgroup_stolen(memcg))
2352 move_lock_mem_cgroup(memcg, flags);
2353 if (memcg != pc->mem_cgroup || !PageCgroupUsed(pc)) {
2354 move_unlock_mem_cgroup(memcg, flags);
2360 void __mem_cgroup_end_update_page_stat(struct page *page, unsigned long *flags)
2362 struct page_cgroup *pc = lookup_page_cgroup(page);
2365 * It's guaranteed that pc->mem_cgroup never changes while
2366 * lock is held because a routine modifies pc->mem_cgroup
2367 * should take move_lock_mem_cgroup().
2369 move_unlock_mem_cgroup(pc->mem_cgroup, flags);
2372 void mem_cgroup_update_page_stat(struct page *page,
2373 enum mem_cgroup_stat_index idx, int val)
2375 struct mem_cgroup *memcg;
2376 struct page_cgroup *pc = lookup_page_cgroup(page);
2377 unsigned long uninitialized_var(flags);
2379 if (mem_cgroup_disabled())
2382 VM_BUG_ON(!rcu_read_lock_held());
2383 memcg = pc->mem_cgroup;
2384 if (unlikely(!memcg || !PageCgroupUsed(pc)))
2387 this_cpu_add(memcg->stat->count[idx], val);
2391 * size of first charge trial. "32" comes from vmscan.c's magic value.
2392 * TODO: maybe necessary to use big numbers in big irons.
2394 #define CHARGE_BATCH 32U
2395 struct memcg_stock_pcp {
2396 struct mem_cgroup *cached; /* this never be root cgroup */
2397 unsigned int nr_pages;
2398 struct work_struct work;
2399 unsigned long flags;
2400 #define FLUSHING_CACHED_CHARGE 0
2402 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
2403 static DEFINE_MUTEX(percpu_charge_mutex);
2406 * consume_stock: Try to consume stocked charge on this cpu.
2407 * @memcg: memcg to consume from.
2408 * @nr_pages: how many pages to charge.
2410 * The charges will only happen if @memcg matches the current cpu's memcg
2411 * stock, and at least @nr_pages are available in that stock. Failure to
2412 * service an allocation will refill the stock.
2414 * returns true if successful, false otherwise.
2416 static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2418 struct memcg_stock_pcp *stock;
2421 if (nr_pages > CHARGE_BATCH)
2424 stock = &get_cpu_var(memcg_stock);
2425 if (memcg == stock->cached && stock->nr_pages >= nr_pages)
2426 stock->nr_pages -= nr_pages;
2427 else /* need to call res_counter_charge */
2429 put_cpu_var(memcg_stock);
2434 * Returns stocks cached in percpu to res_counter and reset cached information.
2436 static void drain_stock(struct memcg_stock_pcp *stock)
2438 struct mem_cgroup *old = stock->cached;
2440 if (stock->nr_pages) {
2441 unsigned long bytes = stock->nr_pages * PAGE_SIZE;
2443 res_counter_uncharge(&old->res, bytes);
2444 if (do_swap_account)
2445 res_counter_uncharge(&old->memsw, bytes);
2446 stock->nr_pages = 0;
2448 stock->cached = NULL;
2452 * This must be called under preempt disabled or must be called by
2453 * a thread which is pinned to local cpu.
2455 static void drain_local_stock(struct work_struct *dummy)
2457 struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
2459 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2462 static void __init memcg_stock_init(void)
2466 for_each_possible_cpu(cpu) {
2467 struct memcg_stock_pcp *stock =
2468 &per_cpu(memcg_stock, cpu);
2469 INIT_WORK(&stock->work, drain_local_stock);
2474 * Cache charges(val) which is from res_counter, to local per_cpu area.
2475 * This will be consumed by consume_stock() function, later.
2477 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2479 struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
2481 if (stock->cached != memcg) { /* reset if necessary */
2483 stock->cached = memcg;
2485 stock->nr_pages += nr_pages;
2486 put_cpu_var(memcg_stock);
2490 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2491 * of the hierarchy under it. sync flag says whether we should block
2492 * until the work is done.
2494 static void drain_all_stock(struct mem_cgroup *root_memcg, bool sync)
2498 /* Notify other cpus that system-wide "drain" is running */
2501 for_each_online_cpu(cpu) {
2502 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2503 struct mem_cgroup *memcg;
2505 memcg = stock->cached;
2506 if (!memcg || !stock->nr_pages)
2508 if (!mem_cgroup_same_or_subtree(root_memcg, memcg))
2510 if (!test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2512 drain_local_stock(&stock->work);
2514 schedule_work_on(cpu, &stock->work);
2522 for_each_online_cpu(cpu) {
2523 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2524 if (test_bit(FLUSHING_CACHED_CHARGE, &stock->flags))
2525 flush_work(&stock->work);
2532 * Tries to drain stocked charges in other cpus. This function is asynchronous
2533 * and just put a work per cpu for draining localy on each cpu. Caller can
2534 * expects some charges will be back to res_counter later but cannot wait for
2537 static void drain_all_stock_async(struct mem_cgroup *root_memcg)
2540 * If someone calls draining, avoid adding more kworker runs.
2542 if (!mutex_trylock(&percpu_charge_mutex))
2544 drain_all_stock(root_memcg, false);
2545 mutex_unlock(&percpu_charge_mutex);
2548 /* This is a synchronous drain interface. */
2549 static void drain_all_stock_sync(struct mem_cgroup *root_memcg)
2551 /* called when force_empty is called */
2552 mutex_lock(&percpu_charge_mutex);
2553 drain_all_stock(root_memcg, true);
2554 mutex_unlock(&percpu_charge_mutex);
2558 * This function drains percpu counter value from DEAD cpu and
2559 * move it to local cpu. Note that this function can be preempted.
2561 static void mem_cgroup_drain_pcp_counter(struct mem_cgroup *memcg, int cpu)
2565 spin_lock(&memcg->pcp_counter_lock);
2566 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
2567 long x = per_cpu(memcg->stat->count[i], cpu);
2569 per_cpu(memcg->stat->count[i], cpu) = 0;
2570 memcg->nocpu_base.count[i] += x;
2572 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
2573 unsigned long x = per_cpu(memcg->stat->events[i], cpu);
2575 per_cpu(memcg->stat->events[i], cpu) = 0;
2576 memcg->nocpu_base.events[i] += x;
2578 spin_unlock(&memcg->pcp_counter_lock);
2581 static int memcg_cpu_hotplug_callback(struct notifier_block *nb,
2582 unsigned long action,
2585 int cpu = (unsigned long)hcpu;
2586 struct memcg_stock_pcp *stock;
2587 struct mem_cgroup *iter;
2589 if (action == CPU_ONLINE)
2592 if (action != CPU_DEAD && action != CPU_DEAD_FROZEN)
2595 for_each_mem_cgroup(iter)
2596 mem_cgroup_drain_pcp_counter(iter, cpu);
2598 stock = &per_cpu(memcg_stock, cpu);
2604 /* See __mem_cgroup_try_charge() for details */
2606 CHARGE_OK, /* success */
2607 CHARGE_RETRY, /* need to retry but retry is not bad */
2608 CHARGE_NOMEM, /* we can't do more. return -ENOMEM */
2609 CHARGE_WOULDBLOCK, /* GFP_WAIT wasn't set and no enough res. */
2612 static int mem_cgroup_do_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2613 unsigned int nr_pages, unsigned int min_pages,
2616 unsigned long csize = nr_pages * PAGE_SIZE;
2617 struct mem_cgroup *mem_over_limit;
2618 struct res_counter *fail_res;
2619 unsigned long flags = 0;
2622 ret = res_counter_charge(&memcg->res, csize, &fail_res);
2625 if (!do_swap_account)
2627 ret = res_counter_charge(&memcg->memsw, csize, &fail_res);
2631 res_counter_uncharge(&memcg->res, csize);
2632 mem_over_limit = mem_cgroup_from_res_counter(fail_res, memsw);
2633 flags |= MEM_CGROUP_RECLAIM_NOSWAP;
2635 mem_over_limit = mem_cgroup_from_res_counter(fail_res, res);
2637 * Never reclaim on behalf of optional batching, retry with a
2638 * single page instead.
2640 if (nr_pages > min_pages)
2641 return CHARGE_RETRY;
2643 if (!(gfp_mask & __GFP_WAIT))
2644 return CHARGE_WOULDBLOCK;
2646 if (gfp_mask & __GFP_NORETRY)
2647 return CHARGE_NOMEM;
2649 ret = mem_cgroup_reclaim(mem_over_limit, gfp_mask, flags);
2650 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2651 return CHARGE_RETRY;
2653 * Even though the limit is exceeded at this point, reclaim
2654 * may have been able to free some pages. Retry the charge
2655 * before killing the task.
2657 * Only for regular pages, though: huge pages are rather
2658 * unlikely to succeed so close to the limit, and we fall back
2659 * to regular pages anyway in case of failure.
2661 if (nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER) && ret)
2662 return CHARGE_RETRY;
2665 * At task move, charge accounts can be doubly counted. So, it's
2666 * better to wait until the end of task_move if something is going on.
2668 if (mem_cgroup_wait_acct_move(mem_over_limit))
2669 return CHARGE_RETRY;
2672 mem_cgroup_oom(mem_over_limit, gfp_mask, get_order(csize));
2674 return CHARGE_NOMEM;
2678 * __mem_cgroup_try_charge() does
2679 * 1. detect memcg to be charged against from passed *mm and *ptr,
2680 * 2. update res_counter
2681 * 3. call memory reclaim if necessary.
2683 * In some special case, if the task is fatal, fatal_signal_pending() or
2684 * has TIF_MEMDIE, this function returns -EINTR while writing root_mem_cgroup
2685 * to *ptr. There are two reasons for this. 1: fatal threads should quit as soon
2686 * as possible without any hazards. 2: all pages should have a valid
2687 * pc->mem_cgroup. If mm is NULL and the caller doesn't pass a valid memcg
2688 * pointer, that is treated as a charge to root_mem_cgroup.
2690 * So __mem_cgroup_try_charge() will return
2691 * 0 ... on success, filling *ptr with a valid memcg pointer.
2692 * -ENOMEM ... charge failure because of resource limits.
2693 * -EINTR ... if thread is fatal. *ptr is filled with root_mem_cgroup.
2695 * Unlike the exported interface, an "oom" parameter is added. if oom==true,
2696 * the oom-killer can be invoked.
2698 static int __mem_cgroup_try_charge(struct mm_struct *mm,
2700 unsigned int nr_pages,
2701 struct mem_cgroup **ptr,
2704 unsigned int batch = max(CHARGE_BATCH, nr_pages);
2705 int nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2706 struct mem_cgroup *memcg = NULL;
2710 * Unlike gloval-vm's OOM-kill, we're not in memory shortage
2711 * in system level. So, allow to go ahead dying process in addition to
2714 if (unlikely(test_thread_flag(TIF_MEMDIE)
2715 || fatal_signal_pending(current)))
2718 if (unlikely(task_in_memcg_oom(current)))
2722 * We always charge the cgroup the mm_struct belongs to.
2723 * The mm_struct's mem_cgroup changes on task migration if the
2724 * thread group leader migrates. It's possible that mm is not
2725 * set, if so charge the root memcg (happens for pagecache usage).
2728 *ptr = root_mem_cgroup;
2730 if (*ptr) { /* css should be a valid one */
2732 if (mem_cgroup_is_root(memcg))
2734 if (consume_stock(memcg, nr_pages))
2736 css_get(&memcg->css);
2738 struct task_struct *p;
2741 p = rcu_dereference(mm->owner);
2743 * Because we don't have task_lock(), "p" can exit.
2744 * In that case, "memcg" can point to root or p can be NULL with
2745 * race with swapoff. Then, we have small risk of mis-accouning.
2746 * But such kind of mis-account by race always happens because
2747 * we don't have cgroup_mutex(). It's overkill and we allo that
2749 * (*) swapoff at el will charge against mm-struct not against
2750 * task-struct. So, mm->owner can be NULL.
2752 memcg = mem_cgroup_from_task(p);
2754 memcg = root_mem_cgroup;
2755 if (mem_cgroup_is_root(memcg)) {
2759 if (consume_stock(memcg, nr_pages)) {
2761 * It seems dagerous to access memcg without css_get().
2762 * But considering how consume_stok works, it's not
2763 * necessary. If consume_stock success, some charges
2764 * from this memcg are cached on this cpu. So, we
2765 * don't need to call css_get()/css_tryget() before
2766 * calling consume_stock().
2771 /* after here, we may be blocked. we need to get refcnt */
2772 if (!css_tryget(&memcg->css)) {
2780 bool invoke_oom = oom && !nr_oom_retries;
2782 /* If killed, bypass charge */
2783 if (fatal_signal_pending(current)) {
2784 css_put(&memcg->css);
2788 ret = mem_cgroup_do_charge(memcg, gfp_mask, batch,
2789 nr_pages, invoke_oom);
2793 case CHARGE_RETRY: /* not in OOM situation but retry */
2795 css_put(&memcg->css);
2798 case CHARGE_WOULDBLOCK: /* !__GFP_WAIT */
2799 css_put(&memcg->css);
2801 case CHARGE_NOMEM: /* OOM routine works */
2802 if (!oom || invoke_oom) {
2803 css_put(&memcg->css);
2809 } while (ret != CHARGE_OK);
2811 if (batch > nr_pages)
2812 refill_stock(memcg, batch - nr_pages);
2813 css_put(&memcg->css);
2818 if (!(gfp_mask & __GFP_NOFAIL)) {
2823 *ptr = root_mem_cgroup;
2828 * Somemtimes we have to undo a charge we got by try_charge().
2829 * This function is for that and do uncharge, put css's refcnt.
2830 * gotten by try_charge().
2832 static void __mem_cgroup_cancel_charge(struct mem_cgroup *memcg,
2833 unsigned int nr_pages)
2835 if (!mem_cgroup_is_root(memcg)) {
2836 unsigned long bytes = nr_pages * PAGE_SIZE;
2838 res_counter_uncharge(&memcg->res, bytes);
2839 if (do_swap_account)
2840 res_counter_uncharge(&memcg->memsw, bytes);
2845 * Cancel chrages in this cgroup....doesn't propagate to parent cgroup.
2846 * This is useful when moving usage to parent cgroup.
2848 static void __mem_cgroup_cancel_local_charge(struct mem_cgroup *memcg,
2849 unsigned int nr_pages)
2851 unsigned long bytes = nr_pages * PAGE_SIZE;
2853 if (mem_cgroup_is_root(memcg))
2856 res_counter_uncharge_until(&memcg->res, memcg->res.parent, bytes);
2857 if (do_swap_account)
2858 res_counter_uncharge_until(&memcg->memsw,
2859 memcg->memsw.parent, bytes);
2863 * A helper function to get mem_cgroup from ID. must be called under
2864 * rcu_read_lock(). The caller is responsible for calling css_tryget if
2865 * the mem_cgroup is used for charging. (dropping refcnt from swap can be
2866 * called against removed memcg.)
2868 static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
2870 struct cgroup_subsys_state *css;
2872 /* ID 0 is unused ID */
2875 css = css_lookup(&mem_cgroup_subsys, id);
2878 return mem_cgroup_from_css(css);
2881 struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
2883 struct mem_cgroup *memcg = NULL;
2884 struct page_cgroup *pc;
2888 VM_BUG_ON(!PageLocked(page));
2890 pc = lookup_page_cgroup(page);
2891 lock_page_cgroup(pc);
2892 if (PageCgroupUsed(pc)) {
2893 memcg = pc->mem_cgroup;
2894 if (memcg && !css_tryget(&memcg->css))
2896 } else if (PageSwapCache(page)) {
2897 ent.val = page_private(page);
2898 id = lookup_swap_cgroup_id(ent);
2900 memcg = mem_cgroup_lookup(id);
2901 if (memcg && !css_tryget(&memcg->css))
2905 unlock_page_cgroup(pc);
2909 static void __mem_cgroup_commit_charge(struct mem_cgroup *memcg,
2911 unsigned int nr_pages,
2912 enum charge_type ctype,
2915 struct page_cgroup *pc = lookup_page_cgroup(page);
2916 struct zone *uninitialized_var(zone);
2917 struct lruvec *lruvec;
2918 bool was_on_lru = false;
2921 lock_page_cgroup(pc);
2922 VM_BUG_ON(PageCgroupUsed(pc));
2924 * we don't need page_cgroup_lock about tail pages, becase they are not
2925 * accessed by any other context at this point.
2929 * In some cases, SwapCache and FUSE(splice_buf->radixtree), the page
2930 * may already be on some other mem_cgroup's LRU. Take care of it.
2933 zone = page_zone(page);
2934 spin_lock_irq(&zone->lru_lock);
2935 if (PageLRU(page)) {
2936 lruvec = mem_cgroup_zone_lruvec(zone, pc->mem_cgroup);
2938 del_page_from_lru_list(page, lruvec, page_lru(page));
2943 pc->mem_cgroup = memcg;
2945 * We access a page_cgroup asynchronously without lock_page_cgroup().
2946 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
2947 * is accessed after testing USED bit. To make pc->mem_cgroup visible
2948 * before USED bit, we need memory barrier here.
2949 * See mem_cgroup_add_lru_list(), etc.
2952 SetPageCgroupUsed(pc);
2956 lruvec = mem_cgroup_zone_lruvec(zone, pc->mem_cgroup);
2957 VM_BUG_ON(PageLRU(page));
2959 add_page_to_lru_list(page, lruvec, page_lru(page));
2961 spin_unlock_irq(&zone->lru_lock);
2964 if (ctype == MEM_CGROUP_CHARGE_TYPE_ANON)
2969 mem_cgroup_charge_statistics(memcg, page, anon, nr_pages);
2970 unlock_page_cgroup(pc);
2973 * "charge_statistics" updated event counter. Then, check it.
2974 * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
2975 * if they exceeds softlimit.
2977 memcg_check_events(memcg, page);
2980 static DEFINE_MUTEX(set_limit_mutex);
2982 #ifdef CONFIG_MEMCG_KMEM
2983 static inline bool memcg_can_account_kmem(struct mem_cgroup *memcg)
2985 return !mem_cgroup_disabled() && !mem_cgroup_is_root(memcg) &&
2986 (memcg->kmem_account_flags & KMEM_ACCOUNTED_MASK);
2990 * This is a bit cumbersome, but it is rarely used and avoids a backpointer
2991 * in the memcg_cache_params struct.
2993 static struct kmem_cache *memcg_params_to_cache(struct memcg_cache_params *p)
2995 struct kmem_cache *cachep;
2997 VM_BUG_ON(p->is_root_cache);
2998 cachep = p->root_cache;
2999 return cachep->memcg_params->memcg_caches[memcg_cache_id(p->memcg)];
3002 #ifdef CONFIG_SLABINFO
3003 static int mem_cgroup_slabinfo_read(struct cgroup_subsys_state *css,
3004 struct cftype *cft, struct seq_file *m)
3006 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3007 struct memcg_cache_params *params;
3009 if (!memcg_can_account_kmem(memcg))
3012 print_slabinfo_header(m);
3014 mutex_lock(&memcg->slab_caches_mutex);
3015 list_for_each_entry(params, &memcg->memcg_slab_caches, list)
3016 cache_show(memcg_params_to_cache(params), m);
3017 mutex_unlock(&memcg->slab_caches_mutex);
3023 static int memcg_charge_kmem(struct mem_cgroup *memcg, gfp_t gfp, u64 size)
3025 struct res_counter *fail_res;
3026 struct mem_cgroup *_memcg;
3030 ret = res_counter_charge(&memcg->kmem, size, &fail_res);
3035 * Conditions under which we can wait for the oom_killer. Those are
3036 * the same conditions tested by the core page allocator
3038 may_oom = (gfp & __GFP_FS) && !(gfp & __GFP_NORETRY);
3041 ret = __mem_cgroup_try_charge(NULL, gfp, size >> PAGE_SHIFT,
3044 if (ret == -EINTR) {
3046 * __mem_cgroup_try_charge() chosed to bypass to root due to
3047 * OOM kill or fatal signal. Since our only options are to
3048 * either fail the allocation or charge it to this cgroup, do
3049 * it as a temporary condition. But we can't fail. From a
3050 * kmem/slab perspective, the cache has already been selected,
3051 * by mem_cgroup_kmem_get_cache(), so it is too late to change
3054 * This condition will only trigger if the task entered
3055 * memcg_charge_kmem in a sane state, but was OOM-killed during
3056 * __mem_cgroup_try_charge() above. Tasks that were already
3057 * dying when the allocation triggers should have been already
3058 * directed to the root cgroup in memcontrol.h
3060 res_counter_charge_nofail(&memcg->res, size, &fail_res);
3061 if (do_swap_account)
3062 res_counter_charge_nofail(&memcg->memsw, size,
3066 res_counter_uncharge(&memcg->kmem, size);
3071 static void memcg_uncharge_kmem(struct mem_cgroup *memcg, u64 size)
3073 res_counter_uncharge(&memcg->res, size);
3074 if (do_swap_account)
3075 res_counter_uncharge(&memcg->memsw, size);
3078 if (res_counter_uncharge(&memcg->kmem, size))
3082 * Releases a reference taken in kmem_cgroup_css_offline in case
3083 * this last uncharge is racing with the offlining code or it is
3084 * outliving the memcg existence.
3086 * The memory barrier imposed by test&clear is paired with the
3087 * explicit one in memcg_kmem_mark_dead().
3089 if (memcg_kmem_test_and_clear_dead(memcg))
3090 css_put(&memcg->css);
3093 void memcg_cache_list_add(struct mem_cgroup *memcg, struct kmem_cache *cachep)
3098 mutex_lock(&memcg->slab_caches_mutex);
3099 list_add(&cachep->memcg_params->list, &memcg->memcg_slab_caches);
3100 mutex_unlock(&memcg->slab_caches_mutex);
3104 * helper for acessing a memcg's index. It will be used as an index in the
3105 * child cache array in kmem_cache, and also to derive its name. This function
3106 * will return -1 when this is not a kmem-limited memcg.
3108 int memcg_cache_id(struct mem_cgroup *memcg)
3110 return memcg ? memcg->kmemcg_id : -1;
3114 * This ends up being protected by the set_limit mutex, during normal
3115 * operation, because that is its main call site.
3117 * But when we create a new cache, we can call this as well if its parent
3118 * is kmem-limited. That will have to hold set_limit_mutex as well.
3120 int memcg_update_cache_sizes(struct mem_cgroup *memcg)
3124 num = ida_simple_get(&kmem_limited_groups,
3125 0, MEMCG_CACHES_MAX_SIZE, GFP_KERNEL);
3129 * After this point, kmem_accounted (that we test atomically in
3130 * the beginning of this conditional), is no longer 0. This
3131 * guarantees only one process will set the following boolean
3132 * to true. We don't need test_and_set because we're protected
3133 * by the set_limit_mutex anyway.
3135 memcg_kmem_set_activated(memcg);
3137 ret = memcg_update_all_caches(num+1);
3139 ida_simple_remove(&kmem_limited_groups, num);
3140 memcg_kmem_clear_activated(memcg);
3144 memcg->kmemcg_id = num;
3145 INIT_LIST_HEAD(&memcg->memcg_slab_caches);
3146 mutex_init(&memcg->slab_caches_mutex);
3150 static size_t memcg_caches_array_size(int num_groups)
3153 if (num_groups <= 0)
3156 size = 2 * num_groups;
3157 if (size < MEMCG_CACHES_MIN_SIZE)
3158 size = MEMCG_CACHES_MIN_SIZE;
3159 else if (size > MEMCG_CACHES_MAX_SIZE)
3160 size = MEMCG_CACHES_MAX_SIZE;
3166 * We should update the current array size iff all caches updates succeed. This
3167 * can only be done from the slab side. The slab mutex needs to be held when
3170 void memcg_update_array_size(int num)
3172 if (num > memcg_limited_groups_array_size)
3173 memcg_limited_groups_array_size = memcg_caches_array_size(num);
3176 static void kmem_cache_destroy_work_func(struct work_struct *w);
3178 int memcg_update_cache_size(struct kmem_cache *s, int num_groups)
3180 struct memcg_cache_params *cur_params = s->memcg_params;
3182 VM_BUG_ON(s->memcg_params && !s->memcg_params->is_root_cache);
3184 if (num_groups > memcg_limited_groups_array_size) {
3186 ssize_t size = memcg_caches_array_size(num_groups);
3188 size *= sizeof(void *);
3189 size += offsetof(struct memcg_cache_params, memcg_caches);
3191 s->memcg_params = kzalloc(size, GFP_KERNEL);
3192 if (!s->memcg_params) {
3193 s->memcg_params = cur_params;
3197 s->memcg_params->is_root_cache = true;
3200 * There is the chance it will be bigger than
3201 * memcg_limited_groups_array_size, if we failed an allocation
3202 * in a cache, in which case all caches updated before it, will
3203 * have a bigger array.
3205 * But if that is the case, the data after
3206 * memcg_limited_groups_array_size is certainly unused
3208 for (i = 0; i < memcg_limited_groups_array_size; i++) {
3209 if (!cur_params->memcg_caches[i])
3211 s->memcg_params->memcg_caches[i] =
3212 cur_params->memcg_caches[i];
3216 * Ideally, we would wait until all caches succeed, and only
3217 * then free the old one. But this is not worth the extra
3218 * pointer per-cache we'd have to have for this.
3220 * It is not a big deal if some caches are left with a size
3221 * bigger than the others. And all updates will reset this
3229 int memcg_register_cache(struct mem_cgroup *memcg, struct kmem_cache *s,
3230 struct kmem_cache *root_cache)
3234 if (!memcg_kmem_enabled())
3238 size = offsetof(struct memcg_cache_params, memcg_caches);
3239 size += memcg_limited_groups_array_size * sizeof(void *);
3241 size = sizeof(struct memcg_cache_params);
3243 s->memcg_params = kzalloc(size, GFP_KERNEL);
3244 if (!s->memcg_params)
3248 s->memcg_params->memcg = memcg;
3249 s->memcg_params->root_cache = root_cache;
3250 INIT_WORK(&s->memcg_params->destroy,
3251 kmem_cache_destroy_work_func);
3253 s->memcg_params->is_root_cache = true;
3258 void memcg_release_cache(struct kmem_cache *s)
3260 struct kmem_cache *root;
3261 struct mem_cgroup *memcg;
3265 * This happens, for instance, when a root cache goes away before we
3268 if (!s->memcg_params)
3271 if (s->memcg_params->is_root_cache)
3274 memcg = s->memcg_params->memcg;
3275 id = memcg_cache_id(memcg);
3277 root = s->memcg_params->root_cache;
3278 root->memcg_params->memcg_caches[id] = NULL;
3280 mutex_lock(&memcg->slab_caches_mutex);
3281 list_del(&s->memcg_params->list);
3282 mutex_unlock(&memcg->slab_caches_mutex);
3284 css_put(&memcg->css);
3286 kfree(s->memcg_params);
3290 * During the creation a new cache, we need to disable our accounting mechanism
3291 * altogether. This is true even if we are not creating, but rather just
3292 * enqueing new caches to be created.
3294 * This is because that process will trigger allocations; some visible, like
3295 * explicit kmallocs to auxiliary data structures, name strings and internal
3296 * cache structures; some well concealed, like INIT_WORK() that can allocate
3297 * objects during debug.
3299 * If any allocation happens during memcg_kmem_get_cache, we will recurse back
3300 * to it. This may not be a bounded recursion: since the first cache creation
3301 * failed to complete (waiting on the allocation), we'll just try to create the
3302 * cache again, failing at the same point.
3304 * memcg_kmem_get_cache is prepared to abort after seeing a positive count of
3305 * memcg_kmem_skip_account. So we enclose anything that might allocate memory
3306 * inside the following two functions.
3308 static inline void memcg_stop_kmem_account(void)
3310 VM_BUG_ON(!current->mm);
3311 current->memcg_kmem_skip_account++;
3314 static inline void memcg_resume_kmem_account(void)
3316 VM_BUG_ON(!current->mm);
3317 current->memcg_kmem_skip_account--;
3320 static void kmem_cache_destroy_work_func(struct work_struct *w)
3322 struct kmem_cache *cachep;
3323 struct memcg_cache_params *p;
3325 p = container_of(w, struct memcg_cache_params, destroy);
3327 cachep = memcg_params_to_cache(p);
3330 * If we get down to 0 after shrink, we could delete right away.
3331 * However, memcg_release_pages() already puts us back in the workqueue
3332 * in that case. If we proceed deleting, we'll get a dangling
3333 * reference, and removing the object from the workqueue in that case
3334 * is unnecessary complication. We are not a fast path.
3336 * Note that this case is fundamentally different from racing with
3337 * shrink_slab(): if memcg_cgroup_destroy_cache() is called in
3338 * kmem_cache_shrink, not only we would be reinserting a dead cache
3339 * into the queue, but doing so from inside the worker racing to
3342 * So if we aren't down to zero, we'll just schedule a worker and try
3345 if (atomic_read(&cachep->memcg_params->nr_pages) != 0) {
3346 kmem_cache_shrink(cachep);
3347 if (atomic_read(&cachep->memcg_params->nr_pages) == 0)
3350 kmem_cache_destroy(cachep);
3353 void mem_cgroup_destroy_cache(struct kmem_cache *cachep)
3355 if (!cachep->memcg_params->dead)
3359 * There are many ways in which we can get here.
3361 * We can get to a memory-pressure situation while the delayed work is
3362 * still pending to run. The vmscan shrinkers can then release all
3363 * cache memory and get us to destruction. If this is the case, we'll
3364 * be executed twice, which is a bug (the second time will execute over
3365 * bogus data). In this case, cancelling the work should be fine.
3367 * But we can also get here from the worker itself, if
3368 * kmem_cache_shrink is enough to shake all the remaining objects and
3369 * get the page count to 0. In this case, we'll deadlock if we try to
3370 * cancel the work (the worker runs with an internal lock held, which
3371 * is the same lock we would hold for cancel_work_sync().)
3373 * Since we can't possibly know who got us here, just refrain from
3374 * running if there is already work pending
3376 if (work_pending(&cachep->memcg_params->destroy))
3379 * We have to defer the actual destroying to a workqueue, because
3380 * we might currently be in a context that cannot sleep.
3382 schedule_work(&cachep->memcg_params->destroy);
3386 * This lock protects updaters, not readers. We want readers to be as fast as
3387 * they can, and they will either see NULL or a valid cache value. Our model
3388 * allow them to see NULL, in which case the root memcg will be selected.
3390 * We need this lock because multiple allocations to the same cache from a non
3391 * will span more than one worker. Only one of them can create the cache.
3393 static DEFINE_MUTEX(memcg_cache_mutex);
3396 * Called with memcg_cache_mutex held
3398 static struct kmem_cache *kmem_cache_dup(struct mem_cgroup *memcg,
3399 struct kmem_cache *s)
3401 struct kmem_cache *new;
3402 static char *tmp_name = NULL;
3404 lockdep_assert_held(&memcg_cache_mutex);
3407 * kmem_cache_create_memcg duplicates the given name and
3408 * cgroup_name for this name requires RCU context.
3409 * This static temporary buffer is used to prevent from
3410 * pointless shortliving allocation.
3413 tmp_name = kmalloc(PATH_MAX, GFP_KERNEL);
3419 snprintf(tmp_name, PATH_MAX, "%s(%d:%s)", s->name,
3420 memcg_cache_id(memcg), cgroup_name(memcg->css.cgroup));
3423 new = kmem_cache_create_memcg(memcg, tmp_name, s->object_size, s->align,
3424 (s->flags & ~SLAB_PANIC), s->ctor, s);
3427 new->allocflags |= __GFP_KMEMCG;
3432 static struct kmem_cache *memcg_create_kmem_cache(struct mem_cgroup *memcg,
3433 struct kmem_cache *cachep)
3435 struct kmem_cache *new_cachep;
3438 BUG_ON(!memcg_can_account_kmem(memcg));
3440 idx = memcg_cache_id(memcg);
3442 mutex_lock(&memcg_cache_mutex);
3443 new_cachep = cachep->memcg_params->memcg_caches[idx];
3445 css_put(&memcg->css);
3449 new_cachep = kmem_cache_dup(memcg, cachep);
3450 if (new_cachep == NULL) {
3451 new_cachep = cachep;
3452 css_put(&memcg->css);
3456 atomic_set(&new_cachep->memcg_params->nr_pages , 0);
3458 cachep->memcg_params->memcg_caches[idx] = new_cachep;
3460 * the readers won't lock, make sure everybody sees the updated value,
3461 * so they won't put stuff in the queue again for no reason
3465 mutex_unlock(&memcg_cache_mutex);
3469 void kmem_cache_destroy_memcg_children(struct kmem_cache *s)
3471 struct kmem_cache *c;
3474 if (!s->memcg_params)
3476 if (!s->memcg_params->is_root_cache)
3480 * If the cache is being destroyed, we trust that there is no one else
3481 * requesting objects from it. Even if there are, the sanity checks in
3482 * kmem_cache_destroy should caught this ill-case.
3484 * Still, we don't want anyone else freeing memcg_caches under our
3485 * noses, which can happen if a new memcg comes to life. As usual,
3486 * we'll take the set_limit_mutex to protect ourselves against this.
3488 mutex_lock(&set_limit_mutex);
3489 for (i = 0; i < memcg_limited_groups_array_size; i++) {
3490 c = s->memcg_params->memcg_caches[i];
3495 * We will now manually delete the caches, so to avoid races
3496 * we need to cancel all pending destruction workers and
3497 * proceed with destruction ourselves.
3499 * kmem_cache_destroy() will call kmem_cache_shrink internally,
3500 * and that could spawn the workers again: it is likely that
3501 * the cache still have active pages until this very moment.
3502 * This would lead us back to mem_cgroup_destroy_cache.
3504 * But that will not execute at all if the "dead" flag is not
3505 * set, so flip it down to guarantee we are in control.
3507 c->memcg_params->dead = false;
3508 cancel_work_sync(&c->memcg_params->destroy);
3509 kmem_cache_destroy(c);
3511 mutex_unlock(&set_limit_mutex);
3514 struct create_work {
3515 struct mem_cgroup *memcg;
3516 struct kmem_cache *cachep;
3517 struct work_struct work;
3520 static void mem_cgroup_destroy_all_caches(struct mem_cgroup *memcg)
3522 struct kmem_cache *cachep;
3523 struct memcg_cache_params *params;
3525 if (!memcg_kmem_is_active(memcg))
3528 mutex_lock(&memcg->slab_caches_mutex);
3529 list_for_each_entry(params, &memcg->memcg_slab_caches, list) {
3530 cachep = memcg_params_to_cache(params);
3531 cachep->memcg_params->dead = true;
3532 schedule_work(&cachep->memcg_params->destroy);
3534 mutex_unlock(&memcg->slab_caches_mutex);
3537 static void memcg_create_cache_work_func(struct work_struct *w)
3539 struct create_work *cw;
3541 cw = container_of(w, struct create_work, work);
3542 memcg_create_kmem_cache(cw->memcg, cw->cachep);
3547 * Enqueue the creation of a per-memcg kmem_cache.
3549 static void __memcg_create_cache_enqueue(struct mem_cgroup *memcg,
3550 struct kmem_cache *cachep)
3552 struct create_work *cw;
3554 cw = kmalloc(sizeof(struct create_work), GFP_NOWAIT);
3556 css_put(&memcg->css);
3561 cw->cachep = cachep;
3563 INIT_WORK(&cw->work, memcg_create_cache_work_func);
3564 schedule_work(&cw->work);
3567 static void memcg_create_cache_enqueue(struct mem_cgroup *memcg,
3568 struct kmem_cache *cachep)
3571 * We need to stop accounting when we kmalloc, because if the
3572 * corresponding kmalloc cache is not yet created, the first allocation
3573 * in __memcg_create_cache_enqueue will recurse.
3575 * However, it is better to enclose the whole function. Depending on
3576 * the debugging options enabled, INIT_WORK(), for instance, can
3577 * trigger an allocation. This too, will make us recurse. Because at
3578 * this point we can't allow ourselves back into memcg_kmem_get_cache,
3579 * the safest choice is to do it like this, wrapping the whole function.
3581 memcg_stop_kmem_account();
3582 __memcg_create_cache_enqueue(memcg, cachep);
3583 memcg_resume_kmem_account();
3586 * Return the kmem_cache we're supposed to use for a slab allocation.
3587 * We try to use the current memcg's version of the cache.
3589 * If the cache does not exist yet, if we are the first user of it,
3590 * we either create it immediately, if possible, or create it asynchronously
3592 * In the latter case, we will let the current allocation go through with
3593 * the original cache.
3595 * Can't be called in interrupt context or from kernel threads.
3596 * This function needs to be called with rcu_read_lock() held.
3598 struct kmem_cache *__memcg_kmem_get_cache(struct kmem_cache *cachep,
3601 struct mem_cgroup *memcg;
3604 VM_BUG_ON(!cachep->memcg_params);
3605 VM_BUG_ON(!cachep->memcg_params->is_root_cache);
3607 if (!current->mm || current->memcg_kmem_skip_account)
3611 memcg = mem_cgroup_from_task(rcu_dereference(current->mm->owner));
3613 if (!memcg_can_account_kmem(memcg))
3616 idx = memcg_cache_id(memcg);
3619 * barrier to mare sure we're always seeing the up to date value. The
3620 * code updating memcg_caches will issue a write barrier to match this.
3622 read_barrier_depends();
3623 if (likely(cachep->memcg_params->memcg_caches[idx])) {
3624 cachep = cachep->memcg_params->memcg_caches[idx];
3628 /* The corresponding put will be done in the workqueue. */
3629 if (!css_tryget(&memcg->css))
3634 * If we are in a safe context (can wait, and not in interrupt
3635 * context), we could be be predictable and return right away.
3636 * This would guarantee that the allocation being performed
3637 * already belongs in the new cache.
3639 * However, there are some clashes that can arrive from locking.
3640 * For instance, because we acquire the slab_mutex while doing
3641 * kmem_cache_dup, this means no further allocation could happen
3642 * with the slab_mutex held.
3644 * Also, because cache creation issue get_online_cpus(), this
3645 * creates a lock chain: memcg_slab_mutex -> cpu_hotplug_mutex,
3646 * that ends up reversed during cpu hotplug. (cpuset allocates
3647 * a bunch of GFP_KERNEL memory during cpuup). Due to all that,
3648 * better to defer everything.
3650 memcg_create_cache_enqueue(memcg, cachep);
3656 EXPORT_SYMBOL(__memcg_kmem_get_cache);
3659 * We need to verify if the allocation against current->mm->owner's memcg is
3660 * possible for the given order. But the page is not allocated yet, so we'll
3661 * need a further commit step to do the final arrangements.
3663 * It is possible for the task to switch cgroups in this mean time, so at
3664 * commit time, we can't rely on task conversion any longer. We'll then use
3665 * the handle argument to return to the caller which cgroup we should commit
3666 * against. We could also return the memcg directly and avoid the pointer
3667 * passing, but a boolean return value gives better semantics considering
3668 * the compiled-out case as well.
3670 * Returning true means the allocation is possible.
3673 __memcg_kmem_newpage_charge(gfp_t gfp, struct mem_cgroup **_memcg, int order)
3675 struct mem_cgroup *memcg;
3681 * Disabling accounting is only relevant for some specific memcg
3682 * internal allocations. Therefore we would initially not have such
3683 * check here, since direct calls to the page allocator that are marked
3684 * with GFP_KMEMCG only happen outside memcg core. We are mostly
3685 * concerned with cache allocations, and by having this test at
3686 * memcg_kmem_get_cache, we are already able to relay the allocation to
3687 * the root cache and bypass the memcg cache altogether.
3689 * There is one exception, though: the SLUB allocator does not create
3690 * large order caches, but rather service large kmallocs directly from
3691 * the page allocator. Therefore, the following sequence when backed by
3692 * the SLUB allocator:
3694 * memcg_stop_kmem_account();
3695 * kmalloc(<large_number>)
3696 * memcg_resume_kmem_account();
3698 * would effectively ignore the fact that we should skip accounting,
3699 * since it will drive us directly to this function without passing
3700 * through the cache selector memcg_kmem_get_cache. Such large
3701 * allocations are extremely rare but can happen, for instance, for the
3702 * cache arrays. We bring this test here.
3704 if (!current->mm || current->memcg_kmem_skip_account)
3707 memcg = try_get_mem_cgroup_from_mm(current->mm);
3710 * very rare case described in mem_cgroup_from_task. Unfortunately there
3711 * isn't much we can do without complicating this too much, and it would
3712 * be gfp-dependent anyway. Just let it go
3714 if (unlikely(!memcg))
3717 if (!memcg_can_account_kmem(memcg)) {
3718 css_put(&memcg->css);
3722 ret = memcg_charge_kmem(memcg, gfp, PAGE_SIZE << order);
3726 css_put(&memcg->css);
3730 void __memcg_kmem_commit_charge(struct page *page, struct mem_cgroup *memcg,
3733 struct page_cgroup *pc;
3735 VM_BUG_ON(mem_cgroup_is_root(memcg));
3737 /* The page allocation failed. Revert */
3739 memcg_uncharge_kmem(memcg, PAGE_SIZE << order);
3743 pc = lookup_page_cgroup(page);
3744 lock_page_cgroup(pc);
3745 pc->mem_cgroup = memcg;
3746 SetPageCgroupUsed(pc);
3747 unlock_page_cgroup(pc);
3750 void __memcg_kmem_uncharge_pages(struct page *page, int order)
3752 struct mem_cgroup *memcg = NULL;
3753 struct page_cgroup *pc;
3756 pc = lookup_page_cgroup(page);
3758 * Fast unlocked return. Theoretically might have changed, have to
3759 * check again after locking.
3761 if (!PageCgroupUsed(pc))
3764 lock_page_cgroup(pc);
3765 if (PageCgroupUsed(pc)) {
3766 memcg = pc->mem_cgroup;
3767 ClearPageCgroupUsed(pc);
3769 unlock_page_cgroup(pc);
3772 * We trust that only if there is a memcg associated with the page, it
3773 * is a valid allocation
3778 VM_BUG_ON(mem_cgroup_is_root(memcg));
3779 memcg_uncharge_kmem(memcg, PAGE_SIZE << order);
3782 static inline void mem_cgroup_destroy_all_caches(struct mem_cgroup *memcg)
3785 #endif /* CONFIG_MEMCG_KMEM */
3787 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3789 #define PCGF_NOCOPY_AT_SPLIT (1 << PCG_LOCK | 1 << PCG_MIGRATION)
3791 * Because tail pages are not marked as "used", set it. We're under
3792 * zone->lru_lock, 'splitting on pmd' and compound_lock.
3793 * charge/uncharge will be never happen and move_account() is done under
3794 * compound_lock(), so we don't have to take care of races.
3796 void mem_cgroup_split_huge_fixup(struct page *head)
3798 struct page_cgroup *head_pc = lookup_page_cgroup(head);
3799 struct page_cgroup *pc;
3800 struct mem_cgroup *memcg;
3803 if (mem_cgroup_disabled())
3806 memcg = head_pc->mem_cgroup;
3807 for (i = 1; i < HPAGE_PMD_NR; i++) {
3809 pc->mem_cgroup = memcg;
3810 smp_wmb();/* see __commit_charge() */
3811 pc->flags = head_pc->flags & ~PCGF_NOCOPY_AT_SPLIT;
3813 __this_cpu_sub(memcg->stat->count[MEM_CGROUP_STAT_RSS_HUGE],
3816 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
3819 void mem_cgroup_move_account_page_stat(struct mem_cgroup *from,
3820 struct mem_cgroup *to,
3821 unsigned int nr_pages,
3822 enum mem_cgroup_stat_index idx)
3824 /* Update stat data for mem_cgroup */
3826 __this_cpu_sub(from->stat->count[idx], nr_pages);
3827 __this_cpu_add(to->stat->count[idx], nr_pages);
3832 * mem_cgroup_move_account - move account of the page
3834 * @nr_pages: number of regular pages (>1 for huge pages)
3835 * @pc: page_cgroup of the page.
3836 * @from: mem_cgroup which the page is moved from.
3837 * @to: mem_cgroup which the page is moved to. @from != @to.
3839 * The caller must confirm following.
3840 * - page is not on LRU (isolate_page() is useful.)
3841 * - compound_lock is held when nr_pages > 1
3843 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
3846 static int mem_cgroup_move_account(struct page *page,
3847 unsigned int nr_pages,
3848 struct page_cgroup *pc,
3849 struct mem_cgroup *from,
3850 struct mem_cgroup *to)
3852 unsigned long flags;
3854 bool anon = PageAnon(page);
3856 VM_BUG_ON(from == to);
3857 VM_BUG_ON(PageLRU(page));
3859 * The page is isolated from LRU. So, collapse function
3860 * will not handle this page. But page splitting can happen.
3861 * Do this check under compound_page_lock(). The caller should
3865 if (nr_pages > 1 && !PageTransHuge(page))
3868 lock_page_cgroup(pc);
3871 if (!PageCgroupUsed(pc) || pc->mem_cgroup != from)
3874 move_lock_mem_cgroup(from, &flags);
3876 if (!anon && page_mapped(page))
3877 mem_cgroup_move_account_page_stat(from, to, nr_pages,
3878 MEM_CGROUP_STAT_FILE_MAPPED);
3880 if (PageWriteback(page))
3881 mem_cgroup_move_account_page_stat(from, to, nr_pages,
3882 MEM_CGROUP_STAT_WRITEBACK);
3884 mem_cgroup_charge_statistics(from, page, anon, -nr_pages);
3886 /* caller should have done css_get */
3887 pc->mem_cgroup = to;
3888 mem_cgroup_charge_statistics(to, page, anon, nr_pages);
3889 move_unlock_mem_cgroup(from, &flags);
3892 unlock_page_cgroup(pc);
3896 memcg_check_events(to, page);
3897 memcg_check_events(from, page);
3903 * mem_cgroup_move_parent - moves page to the parent group
3904 * @page: the page to move
3905 * @pc: page_cgroup of the page
3906 * @child: page's cgroup
3908 * move charges to its parent or the root cgroup if the group has no
3909 * parent (aka use_hierarchy==0).
3910 * Although this might fail (get_page_unless_zero, isolate_lru_page or
3911 * mem_cgroup_move_account fails) the failure is always temporary and
3912 * it signals a race with a page removal/uncharge or migration. In the
3913 * first case the page is on the way out and it will vanish from the LRU
3914 * on the next attempt and the call should be retried later.
3915 * Isolation from the LRU fails only if page has been isolated from
3916 * the LRU since we looked at it and that usually means either global
3917 * reclaim or migration going on. The page will either get back to the
3919 * Finaly mem_cgroup_move_account fails only if the page got uncharged
3920 * (!PageCgroupUsed) or moved to a different group. The page will
3921 * disappear in the next attempt.
3923 static int mem_cgroup_move_parent(struct page *page,
3924 struct page_cgroup *pc,
3925 struct mem_cgroup *child)
3927 struct mem_cgroup *parent;
3928 unsigned int nr_pages;
3929 unsigned long uninitialized_var(flags);
3932 VM_BUG_ON(mem_cgroup_is_root(child));
3935 if (!get_page_unless_zero(page))
3937 if (isolate_lru_page(page))
3940 nr_pages = hpage_nr_pages(page);
3942 parent = parent_mem_cgroup(child);
3944 * If no parent, move charges to root cgroup.
3947 parent = root_mem_cgroup;
3950 VM_BUG_ON(!PageTransHuge(page));
3951 flags = compound_lock_irqsave(page);
3954 ret = mem_cgroup_move_account(page, nr_pages,
3957 __mem_cgroup_cancel_local_charge(child, nr_pages);
3960 compound_unlock_irqrestore(page, flags);
3961 putback_lru_page(page);
3969 * Charge the memory controller for page usage.
3971 * 0 if the charge was successful
3972 * < 0 if the cgroup is over its limit
3974 static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
3975 gfp_t gfp_mask, enum charge_type ctype)
3977 struct mem_cgroup *memcg = NULL;
3978 unsigned int nr_pages = 1;
3982 if (PageTransHuge(page)) {
3983 nr_pages <<= compound_order(page);
3984 VM_BUG_ON(!PageTransHuge(page));
3986 * Never OOM-kill a process for a huge page. The
3987 * fault handler will fall back to regular pages.
3992 ret = __mem_cgroup_try_charge(mm, gfp_mask, nr_pages, &memcg, oom);
3995 __mem_cgroup_commit_charge(memcg, page, nr_pages, ctype, false);
3999 int mem_cgroup_newpage_charge(struct page *page,
4000 struct mm_struct *mm, gfp_t gfp_mask)
4002 if (mem_cgroup_disabled())
4004 VM_BUG_ON(page_mapped(page));
4005 VM_BUG_ON(page->mapping && !PageAnon(page));
4007 return mem_cgroup_charge_common(page, mm, gfp_mask,
4008 MEM_CGROUP_CHARGE_TYPE_ANON);
4012 * While swap-in, try_charge -> commit or cancel, the page is locked.
4013 * And when try_charge() successfully returns, one refcnt to memcg without
4014 * struct page_cgroup is acquired. This refcnt will be consumed by
4015 * "commit()" or removed by "cancel()"
4017 static int __mem_cgroup_try_charge_swapin(struct mm_struct *mm,
4020 struct mem_cgroup **memcgp)
4022 struct mem_cgroup *memcg;
4023 struct page_cgroup *pc;
4026 pc = lookup_page_cgroup(page);
4028 * Every swap fault against a single page tries to charge the
4029 * page, bail as early as possible. shmem_unuse() encounters
4030 * already charged pages, too. The USED bit is protected by
4031 * the page lock, which serializes swap cache removal, which
4032 * in turn serializes uncharging.
4034 if (PageCgroupUsed(pc))
4036 if (!do_swap_account)
4038 memcg = try_get_mem_cgroup_from_page(page);
4042 ret = __mem_cgroup_try_charge(NULL, mask, 1, memcgp, true);
4043 css_put(&memcg->css);
4048 ret = __mem_cgroup_try_charge(mm, mask, 1, memcgp, true);
4054 int mem_cgroup_try_charge_swapin(struct mm_struct *mm, struct page *page,
4055 gfp_t gfp_mask, struct mem_cgroup **memcgp)
4058 if (mem_cgroup_disabled())
4061 * A racing thread's fault, or swapoff, may have already
4062 * updated the pte, and even removed page from swap cache: in
4063 * those cases unuse_pte()'s pte_same() test will fail; but
4064 * there's also a KSM case which does need to charge the page.
4066 if (!PageSwapCache(page)) {
4069 ret = __mem_cgroup_try_charge(mm, gfp_mask, 1, memcgp, true);
4074 return __mem_cgroup_try_charge_swapin(mm, page, gfp_mask, memcgp);
4077 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *memcg)
4079 if (mem_cgroup_disabled())
4083 __mem_cgroup_cancel_charge(memcg, 1);
4087 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *memcg,
4088 enum charge_type ctype)
4090 if (mem_cgroup_disabled())
4095 __mem_cgroup_commit_charge(memcg, page, 1, ctype, true);
4097 * Now swap is on-memory. This means this page may be
4098 * counted both as mem and swap....double count.
4099 * Fix it by uncharging from memsw. Basically, this SwapCache is stable
4100 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
4101 * may call delete_from_swap_cache() before reach here.
4103 if (do_swap_account && PageSwapCache(page)) {
4104 swp_entry_t ent = {.val = page_private(page)};
4105 mem_cgroup_uncharge_swap(ent);
4109 void mem_cgroup_commit_charge_swapin(struct page *page,
4110 struct mem_cgroup *memcg)
4112 __mem_cgroup_commit_charge_swapin(page, memcg,
4113 MEM_CGROUP_CHARGE_TYPE_ANON);
4116 int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
4119 struct mem_cgroup *memcg = NULL;
4120 enum charge_type type = MEM_CGROUP_CHARGE_TYPE_CACHE;
4123 if (mem_cgroup_disabled())
4125 if (PageCompound(page))
4128 if (!PageSwapCache(page))
4129 ret = mem_cgroup_charge_common(page, mm, gfp_mask, type);
4130 else { /* page is swapcache/shmem */
4131 ret = __mem_cgroup_try_charge_swapin(mm, page,
4134 __mem_cgroup_commit_charge_swapin(page, memcg, type);
4139 static void mem_cgroup_do_uncharge(struct mem_cgroup *memcg,
4140 unsigned int nr_pages,
4141 const enum charge_type ctype)
4143 struct memcg_batch_info *batch = NULL;
4144 bool uncharge_memsw = true;
4146 /* If swapout, usage of swap doesn't decrease */
4147 if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
4148 uncharge_memsw = false;
4150 batch = ¤t->memcg_batch;
4152 * In usual, we do css_get() when we remember memcg pointer.
4153 * But in this case, we keep res->usage until end of a series of
4154 * uncharges. Then, it's ok to ignore memcg's refcnt.
4157 batch->memcg = memcg;
4159 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
4160 * In those cases, all pages freed continuously can be expected to be in
4161 * the same cgroup and we have chance to coalesce uncharges.
4162 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
4163 * because we want to do uncharge as soon as possible.
4166 if (!batch->do_batch || test_thread_flag(TIF_MEMDIE))
4167 goto direct_uncharge;
4170 goto direct_uncharge;
4173 * In typical case, batch->memcg == mem. This means we can
4174 * merge a series of uncharges to an uncharge of res_counter.
4175 * If not, we uncharge res_counter ony by one.
4177 if (batch->memcg != memcg)
4178 goto direct_uncharge;
4179 /* remember freed charge and uncharge it later */
4182 batch->memsw_nr_pages++;
4185 res_counter_uncharge(&memcg->res, nr_pages * PAGE_SIZE);
4187 res_counter_uncharge(&memcg->memsw, nr_pages * PAGE_SIZE);
4188 if (unlikely(batch->memcg != memcg))
4189 memcg_oom_recover(memcg);
4193 * uncharge if !page_mapped(page)
4195 static struct mem_cgroup *
4196 __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype,
4199 struct mem_cgroup *memcg = NULL;
4200 unsigned int nr_pages = 1;
4201 struct page_cgroup *pc;
4204 if (mem_cgroup_disabled())
4207 if (PageTransHuge(page)) {
4208 nr_pages <<= compound_order(page);
4209 VM_BUG_ON(!PageTransHuge(page));
4212 * Check if our page_cgroup is valid
4214 pc = lookup_page_cgroup(page);
4215 if (unlikely(!PageCgroupUsed(pc)))
4218 lock_page_cgroup(pc);
4220 memcg = pc->mem_cgroup;
4222 if (!PageCgroupUsed(pc))
4225 anon = PageAnon(page);
4228 case MEM_CGROUP_CHARGE_TYPE_ANON:
4230 * Generally PageAnon tells if it's the anon statistics to be
4231 * updated; but sometimes e.g. mem_cgroup_uncharge_page() is
4232 * used before page reached the stage of being marked PageAnon.
4236 case MEM_CGROUP_CHARGE_TYPE_DROP:
4237 /* See mem_cgroup_prepare_migration() */
4238 if (page_mapped(page))
4241 * Pages under migration may not be uncharged. But
4242 * end_migration() /must/ be the one uncharging the
4243 * unused post-migration page and so it has to call
4244 * here with the migration bit still set. See the
4245 * res_counter handling below.
4247 if (!end_migration && PageCgroupMigration(pc))
4250 case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
4251 if (!PageAnon(page)) { /* Shared memory */
4252 if (page->mapping && !page_is_file_cache(page))
4254 } else if (page_mapped(page)) /* Anon */
4261 mem_cgroup_charge_statistics(memcg, page, anon, -nr_pages);
4263 ClearPageCgroupUsed(pc);
4265 * pc->mem_cgroup is not cleared here. It will be accessed when it's
4266 * freed from LRU. This is safe because uncharged page is expected not
4267 * to be reused (freed soon). Exception is SwapCache, it's handled by
4268 * special functions.
4271 unlock_page_cgroup(pc);
4273 * even after unlock, we have memcg->res.usage here and this memcg
4274 * will never be freed, so it's safe to call css_get().
4276 memcg_check_events(memcg, page);
4277 if (do_swap_account && ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT) {
4278 mem_cgroup_swap_statistics(memcg, true);
4279 css_get(&memcg->css);
4282 * Migration does not charge the res_counter for the
4283 * replacement page, so leave it alone when phasing out the
4284 * page that is unused after the migration.
4286 if (!end_migration && !mem_cgroup_is_root(memcg))
4287 mem_cgroup_do_uncharge(memcg, nr_pages, ctype);
4292 unlock_page_cgroup(pc);
4296 void mem_cgroup_uncharge_page(struct page *page)
4299 if (page_mapped(page))
4301 VM_BUG_ON(page->mapping && !PageAnon(page));
4303 * If the page is in swap cache, uncharge should be deferred
4304 * to the swap path, which also properly accounts swap usage
4305 * and handles memcg lifetime.
4307 * Note that this check is not stable and reclaim may add the
4308 * page to swap cache at any time after this. However, if the
4309 * page is not in swap cache by the time page->mapcount hits
4310 * 0, there won't be any page table references to the swap
4311 * slot, and reclaim will free it and not actually write the
4314 if (PageSwapCache(page))
4316 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_ANON, false);
4319 void mem_cgroup_uncharge_cache_page(struct page *page)
4321 VM_BUG_ON(page_mapped(page));
4322 VM_BUG_ON(page->mapping);
4323 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE, false);
4327 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
4328 * In that cases, pages are freed continuously and we can expect pages
4329 * are in the same memcg. All these calls itself limits the number of
4330 * pages freed at once, then uncharge_start/end() is called properly.
4331 * This may be called prural(2) times in a context,
4334 void mem_cgroup_uncharge_start(void)
4336 current->memcg_batch.do_batch++;
4337 /* We can do nest. */
4338 if (current->memcg_batch.do_batch == 1) {
4339 current->memcg_batch.memcg = NULL;
4340 current->memcg_batch.nr_pages = 0;
4341 current->memcg_batch.memsw_nr_pages = 0;
4345 void mem_cgroup_uncharge_end(void)
4347 struct memcg_batch_info *batch = ¤t->memcg_batch;
4349 if (!batch->do_batch)
4353 if (batch->do_batch) /* If stacked, do nothing. */
4359 * This "batch->memcg" is valid without any css_get/put etc...
4360 * bacause we hide charges behind us.
4362 if (batch->nr_pages)
4363 res_counter_uncharge(&batch->memcg->res,
4364 batch->nr_pages * PAGE_SIZE);
4365 if (batch->memsw_nr_pages)
4366 res_counter_uncharge(&batch->memcg->memsw,
4367 batch->memsw_nr_pages * PAGE_SIZE);
4368 memcg_oom_recover(batch->memcg);
4369 /* forget this pointer (for sanity check) */
4370 batch->memcg = NULL;
4375 * called after __delete_from_swap_cache() and drop "page" account.
4376 * memcg information is recorded to swap_cgroup of "ent"
4379 mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
4381 struct mem_cgroup *memcg;
4382 int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
4384 if (!swapout) /* this was a swap cache but the swap is unused ! */
4385 ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
4387 memcg = __mem_cgroup_uncharge_common(page, ctype, false);
4390 * record memcg information, if swapout && memcg != NULL,
4391 * css_get() was called in uncharge().
4393 if (do_swap_account && swapout && memcg)
4394 swap_cgroup_record(ent, css_id(&memcg->css));
4398 #ifdef CONFIG_MEMCG_SWAP
4400 * called from swap_entry_free(). remove record in swap_cgroup and
4401 * uncharge "memsw" account.
4403 void mem_cgroup_uncharge_swap(swp_entry_t ent)
4405 struct mem_cgroup *memcg;
4408 if (!do_swap_account)
4411 id = swap_cgroup_record(ent, 0);
4413 memcg = mem_cgroup_lookup(id);
4416 * We uncharge this because swap is freed.
4417 * This memcg can be obsolete one. We avoid calling css_tryget
4419 if (!mem_cgroup_is_root(memcg))
4420 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
4421 mem_cgroup_swap_statistics(memcg, false);
4422 css_put(&memcg->css);
4428 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
4429 * @entry: swap entry to be moved
4430 * @from: mem_cgroup which the entry is moved from
4431 * @to: mem_cgroup which the entry is moved to
4433 * It succeeds only when the swap_cgroup's record for this entry is the same
4434 * as the mem_cgroup's id of @from.
4436 * Returns 0 on success, -EINVAL on failure.
4438 * The caller must have charged to @to, IOW, called res_counter_charge() about
4439 * both res and memsw, and called css_get().
4441 static int mem_cgroup_move_swap_account(swp_entry_t entry,
4442 struct mem_cgroup *from, struct mem_cgroup *to)
4444 unsigned short old_id, new_id;
4446 old_id = css_id(&from->css);
4447 new_id = css_id(&to->css);
4449 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
4450 mem_cgroup_swap_statistics(from, false);
4451 mem_cgroup_swap_statistics(to, true);
4453 * This function is only called from task migration context now.
4454 * It postpones res_counter and refcount handling till the end
4455 * of task migration(mem_cgroup_clear_mc()) for performance
4456 * improvement. But we cannot postpone css_get(to) because if
4457 * the process that has been moved to @to does swap-in, the
4458 * refcount of @to might be decreased to 0.
4460 * We are in attach() phase, so the cgroup is guaranteed to be
4461 * alive, so we can just call css_get().
4469 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
4470 struct mem_cgroup *from, struct mem_cgroup *to)
4477 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
4480 void mem_cgroup_prepare_migration(struct page *page, struct page *newpage,
4481 struct mem_cgroup **memcgp)
4483 struct mem_cgroup *memcg = NULL;
4484 unsigned int nr_pages = 1;
4485 struct page_cgroup *pc;
4486 enum charge_type ctype;
4490 if (mem_cgroup_disabled())
4493 if (PageTransHuge(page))
4494 nr_pages <<= compound_order(page);
4496 pc = lookup_page_cgroup(page);
4497 lock_page_cgroup(pc);
4498 if (PageCgroupUsed(pc)) {
4499 memcg = pc->mem_cgroup;
4500 css_get(&memcg->css);
4502 * At migrating an anonymous page, its mapcount goes down
4503 * to 0 and uncharge() will be called. But, even if it's fully
4504 * unmapped, migration may fail and this page has to be
4505 * charged again. We set MIGRATION flag here and delay uncharge
4506 * until end_migration() is called
4508 * Corner Case Thinking
4510 * When the old page was mapped as Anon and it's unmap-and-freed
4511 * while migration was ongoing.
4512 * If unmap finds the old page, uncharge() of it will be delayed
4513 * until end_migration(). If unmap finds a new page, it's
4514 * uncharged when it make mapcount to be 1->0. If unmap code
4515 * finds swap_migration_entry, the new page will not be mapped
4516 * and end_migration() will find it(mapcount==0).
4519 * When the old page was mapped but migraion fails, the kernel
4520 * remaps it. A charge for it is kept by MIGRATION flag even
4521 * if mapcount goes down to 0. We can do remap successfully
4522 * without charging it again.
4525 * The "old" page is under lock_page() until the end of
4526 * migration, so, the old page itself will not be swapped-out.
4527 * If the new page is swapped out before end_migraton, our
4528 * hook to usual swap-out path will catch the event.
4531 SetPageCgroupMigration(pc);
4533 unlock_page_cgroup(pc);
4535 * If the page is not charged at this point,
4543 * We charge new page before it's used/mapped. So, even if unlock_page()
4544 * is called before end_migration, we can catch all events on this new
4545 * page. In the case new page is migrated but not remapped, new page's
4546 * mapcount will be finally 0 and we call uncharge in end_migration().
4549 ctype = MEM_CGROUP_CHARGE_TYPE_ANON;
4551 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
4553 * The page is committed to the memcg, but it's not actually
4554 * charged to the res_counter since we plan on replacing the
4555 * old one and only one page is going to be left afterwards.
4557 __mem_cgroup_commit_charge(memcg, newpage, nr_pages, ctype, false);
4560 /* remove redundant charge if migration failed*/
4561 void mem_cgroup_end_migration(struct mem_cgroup *memcg,
4562 struct page *oldpage, struct page *newpage, bool migration_ok)
4564 struct page *used, *unused;
4565 struct page_cgroup *pc;
4571 if (!migration_ok) {
4578 anon = PageAnon(used);
4579 __mem_cgroup_uncharge_common(unused,
4580 anon ? MEM_CGROUP_CHARGE_TYPE_ANON
4581 : MEM_CGROUP_CHARGE_TYPE_CACHE,
4583 css_put(&memcg->css);
4585 * We disallowed uncharge of pages under migration because mapcount
4586 * of the page goes down to zero, temporarly.
4587 * Clear the flag and check the page should be charged.
4589 pc = lookup_page_cgroup(oldpage);
4590 lock_page_cgroup(pc);
4591 ClearPageCgroupMigration(pc);
4592 unlock_page_cgroup(pc);
4595 * If a page is a file cache, radix-tree replacement is very atomic
4596 * and we can skip this check. When it was an Anon page, its mapcount
4597 * goes down to 0. But because we added MIGRATION flage, it's not
4598 * uncharged yet. There are several case but page->mapcount check
4599 * and USED bit check in mem_cgroup_uncharge_page() will do enough
4600 * check. (see prepare_charge() also)
4603 mem_cgroup_uncharge_page(used);
4607 * At replace page cache, newpage is not under any memcg but it's on
4608 * LRU. So, this function doesn't touch res_counter but handles LRU
4609 * in correct way. Both pages are locked so we cannot race with uncharge.
4611 void mem_cgroup_replace_page_cache(struct page *oldpage,
4612 struct page *newpage)
4614 struct mem_cgroup *memcg = NULL;
4615 struct page_cgroup *pc;
4616 enum charge_type type = MEM_CGROUP_CHARGE_TYPE_CACHE;
4618 if (mem_cgroup_disabled())
4621 pc = lookup_page_cgroup(oldpage);
4622 /* fix accounting on old pages */
4623 lock_page_cgroup(pc);
4624 if (PageCgroupUsed(pc)) {
4625 memcg = pc->mem_cgroup;
4626 mem_cgroup_charge_statistics(memcg, oldpage, false, -1);
4627 ClearPageCgroupUsed(pc);
4629 unlock_page_cgroup(pc);
4632 * When called from shmem_replace_page(), in some cases the
4633 * oldpage has already been charged, and in some cases not.
4638 * Even if newpage->mapping was NULL before starting replacement,
4639 * the newpage may be on LRU(or pagevec for LRU) already. We lock
4640 * LRU while we overwrite pc->mem_cgroup.
4642 __mem_cgroup_commit_charge(memcg, newpage, 1, type, true);
4645 #ifdef CONFIG_DEBUG_VM
4646 static struct page_cgroup *lookup_page_cgroup_used(struct page *page)
4648 struct page_cgroup *pc;
4650 pc = lookup_page_cgroup(page);
4652 * Can be NULL while feeding pages into the page allocator for
4653 * the first time, i.e. during boot or memory hotplug;
4654 * or when mem_cgroup_disabled().
4656 if (likely(pc) && PageCgroupUsed(pc))
4661 bool mem_cgroup_bad_page_check(struct page *page)
4663 if (mem_cgroup_disabled())
4666 return lookup_page_cgroup_used(page) != NULL;
4669 void mem_cgroup_print_bad_page(struct page *page)
4671 struct page_cgroup *pc;
4673 pc = lookup_page_cgroup_used(page);
4675 pr_alert("pc:%p pc->flags:%lx pc->mem_cgroup:%p\n",
4676 pc, pc->flags, pc->mem_cgroup);
4681 static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
4682 unsigned long long val)
4685 u64 memswlimit, memlimit;
4687 int children = mem_cgroup_count_children(memcg);
4688 u64 curusage, oldusage;
4692 * For keeping hierarchical_reclaim simple, how long we should retry
4693 * is depends on callers. We set our retry-count to be function
4694 * of # of children which we should visit in this loop.
4696 retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
4698 oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
4701 while (retry_count) {
4702 if (signal_pending(current)) {
4707 * Rather than hide all in some function, I do this in
4708 * open coded manner. You see what this really does.
4709 * We have to guarantee memcg->res.limit <= memcg->memsw.limit.
4711 mutex_lock(&set_limit_mutex);
4712 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
4713 if (memswlimit < val) {
4715 mutex_unlock(&set_limit_mutex);
4719 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
4723 ret = res_counter_set_limit(&memcg->res, val);
4725 if (memswlimit == val)
4726 memcg->memsw_is_minimum = true;
4728 memcg->memsw_is_minimum = false;
4730 mutex_unlock(&set_limit_mutex);
4735 mem_cgroup_reclaim(memcg, GFP_KERNEL,
4736 MEM_CGROUP_RECLAIM_SHRINK);
4737 curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
4738 /* Usage is reduced ? */
4739 if (curusage >= oldusage)
4742 oldusage = curusage;
4744 if (!ret && enlarge)
4745 memcg_oom_recover(memcg);
4750 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
4751 unsigned long long val)
4754 u64 memlimit, memswlimit, oldusage, curusage;
4755 int children = mem_cgroup_count_children(memcg);
4759 /* see mem_cgroup_resize_res_limit */
4760 retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
4761 oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
4762 while (retry_count) {
4763 if (signal_pending(current)) {
4768 * Rather than hide all in some function, I do this in
4769 * open coded manner. You see what this really does.
4770 * We have to guarantee memcg->res.limit <= memcg->memsw.limit.
4772 mutex_lock(&set_limit_mutex);
4773 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
4774 if (memlimit > val) {
4776 mutex_unlock(&set_limit_mutex);
4779 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
4780 if (memswlimit < val)
4782 ret = res_counter_set_limit(&memcg->memsw, val);
4784 if (memlimit == val)
4785 memcg->memsw_is_minimum = true;
4787 memcg->memsw_is_minimum = false;
4789 mutex_unlock(&set_limit_mutex);
4794 mem_cgroup_reclaim(memcg, GFP_KERNEL,
4795 MEM_CGROUP_RECLAIM_NOSWAP |
4796 MEM_CGROUP_RECLAIM_SHRINK);
4797 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
4798 /* Usage is reduced ? */
4799 if (curusage >= oldusage)
4802 oldusage = curusage;
4804 if (!ret && enlarge)
4805 memcg_oom_recover(memcg);
4809 unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
4811 unsigned long *total_scanned)
4813 unsigned long nr_reclaimed = 0;
4814 struct mem_cgroup_per_zone *mz, *next_mz = NULL;
4815 unsigned long reclaimed;
4817 struct mem_cgroup_tree_per_zone *mctz;
4818 unsigned long long excess;
4819 unsigned long nr_scanned;
4824 mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone));
4826 * This loop can run a while, specially if mem_cgroup's continuously
4827 * keep exceeding their soft limit and putting the system under
4834 mz = mem_cgroup_largest_soft_limit_node(mctz);
4839 reclaimed = mem_cgroup_soft_reclaim(mz->memcg, zone,
4840 gfp_mask, &nr_scanned);
4841 nr_reclaimed += reclaimed;
4842 *total_scanned += nr_scanned;
4843 spin_lock(&mctz->lock);
4846 * If we failed to reclaim anything from this memory cgroup
4847 * it is time to move on to the next cgroup
4853 * Loop until we find yet another one.
4855 * By the time we get the soft_limit lock
4856 * again, someone might have aded the
4857 * group back on the RB tree. Iterate to
4858 * make sure we get a different mem.
4859 * mem_cgroup_largest_soft_limit_node returns
4860 * NULL if no other cgroup is present on
4864 __mem_cgroup_largest_soft_limit_node(mctz);
4866 css_put(&next_mz->memcg->css);
4867 else /* next_mz == NULL or other memcg */
4871 __mem_cgroup_remove_exceeded(mz->memcg, mz, mctz);
4872 excess = res_counter_soft_limit_excess(&mz->memcg->res);
4874 * One school of thought says that we should not add
4875 * back the node to the tree if reclaim returns 0.
4876 * But our reclaim could return 0, simply because due
4877 * to priority we are exposing a smaller subset of
4878 * memory to reclaim from. Consider this as a longer
4881 /* If excess == 0, no tree ops */
4882 __mem_cgroup_insert_exceeded(mz->memcg, mz, mctz, excess);
4883 spin_unlock(&mctz->lock);
4884 css_put(&mz->memcg->css);
4887 * Could not reclaim anything and there are no more
4888 * mem cgroups to try or we seem to be looping without
4889 * reclaiming anything.
4891 if (!nr_reclaimed &&
4893 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
4895 } while (!nr_reclaimed);
4897 css_put(&next_mz->memcg->css);
4898 return nr_reclaimed;
4902 * mem_cgroup_force_empty_list - clears LRU of a group
4903 * @memcg: group to clear
4906 * @lru: lru to to clear
4908 * Traverse a specified page_cgroup list and try to drop them all. This doesn't
4909 * reclaim the pages page themselves - pages are moved to the parent (or root)
4912 static void mem_cgroup_force_empty_list(struct mem_cgroup *memcg,
4913 int node, int zid, enum lru_list lru)
4915 struct lruvec *lruvec;
4916 unsigned long flags;
4917 struct list_head *list;
4921 zone = &NODE_DATA(node)->node_zones[zid];
4922 lruvec = mem_cgroup_zone_lruvec(zone, memcg);
4923 list = &lruvec->lists[lru];
4927 struct page_cgroup *pc;
4930 spin_lock_irqsave(&zone->lru_lock, flags);
4931 if (list_empty(list)) {
4932 spin_unlock_irqrestore(&zone->lru_lock, flags);
4935 page = list_entry(list->prev, struct page, lru);
4937 list_move(&page->lru, list);
4939 spin_unlock_irqrestore(&zone->lru_lock, flags);
4942 spin_unlock_irqrestore(&zone->lru_lock, flags);
4944 pc = lookup_page_cgroup(page);
4946 if (mem_cgroup_move_parent(page, pc, memcg)) {
4947 /* found lock contention or "pc" is obsolete. */
4952 } while (!list_empty(list));
4956 * make mem_cgroup's charge to be 0 if there is no task by moving
4957 * all the charges and pages to the parent.
4958 * This enables deleting this mem_cgroup.
4960 * Caller is responsible for holding css reference on the memcg.
4962 static void mem_cgroup_reparent_charges(struct mem_cgroup *memcg)
4968 /* This is for making all *used* pages to be on LRU. */
4969 lru_add_drain_all();
4970 drain_all_stock_sync(memcg);
4971 mem_cgroup_start_move(memcg);
4972 for_each_node_state(node, N_MEMORY) {
4973 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
4976 mem_cgroup_force_empty_list(memcg,
4981 mem_cgroup_end_move(memcg);
4982 memcg_oom_recover(memcg);
4986 * Kernel memory may not necessarily be trackable to a specific
4987 * process. So they are not migrated, and therefore we can't
4988 * expect their value to drop to 0 here.
4989 * Having res filled up with kmem only is enough.
4991 * This is a safety check because mem_cgroup_force_empty_list
4992 * could have raced with mem_cgroup_replace_page_cache callers
4993 * so the lru seemed empty but the page could have been added
4994 * right after the check. RES_USAGE should be safe as we always
4995 * charge before adding to the LRU.
4997 usage = res_counter_read_u64(&memcg->res, RES_USAGE) -
4998 res_counter_read_u64(&memcg->kmem, RES_USAGE);
4999 } while (usage > 0);
5002 static inline bool memcg_has_children(struct mem_cgroup *memcg)
5004 lockdep_assert_held(&memcg_create_mutex);
5006 * The lock does not prevent addition or deletion to the list
5007 * of children, but it prevents a new child from being
5008 * initialized based on this parent in css_online(), so it's
5009 * enough to decide whether hierarchically inherited
5010 * attributes can still be changed or not.
5012 return memcg->use_hierarchy &&
5013 !list_empty(&memcg->css.cgroup->children);
5017 * Reclaims as many pages from the given memcg as possible and moves
5018 * the rest to the parent.
5020 * Caller is responsible for holding css reference for memcg.
5022 static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
5024 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
5025 struct cgroup *cgrp = memcg->css.cgroup;
5027 /* returns EBUSY if there is a task or if we come here twice. */
5028 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
5031 /* we call try-to-free pages for make this cgroup empty */
5032 lru_add_drain_all();
5033 /* try to free all pages in this cgroup */
5034 while (nr_retries && res_counter_read_u64(&memcg->res, RES_USAGE) > 0) {
5037 if (signal_pending(current))
5040 progress = try_to_free_mem_cgroup_pages(memcg, GFP_KERNEL,
5044 /* maybe some writeback is necessary */
5045 congestion_wait(BLK_RW_ASYNC, HZ/10);
5050 mem_cgroup_reparent_charges(memcg);
5055 static int mem_cgroup_force_empty_write(struct cgroup_subsys_state *css,
5058 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5060 if (mem_cgroup_is_root(memcg))
5062 return mem_cgroup_force_empty(memcg);
5065 static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
5068 return mem_cgroup_from_css(css)->use_hierarchy;
5071 static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
5072 struct cftype *cft, u64 val)
5075 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5076 struct mem_cgroup *parent_memcg = mem_cgroup_from_css(css_parent(&memcg->css));
5078 mutex_lock(&memcg_create_mutex);
5080 if (memcg->use_hierarchy == val)
5084 * If parent's use_hierarchy is set, we can't make any modifications
5085 * in the child subtrees. If it is unset, then the change can
5086 * occur, provided the current cgroup has no children.
5088 * For the root cgroup, parent_mem is NULL, we allow value to be
5089 * set if there are no children.
5091 if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
5092 (val == 1 || val == 0)) {
5093 if (list_empty(&memcg->css.cgroup->children))
5094 memcg->use_hierarchy = val;
5101 mutex_unlock(&memcg_create_mutex);
5107 static unsigned long mem_cgroup_recursive_stat(struct mem_cgroup *memcg,
5108 enum mem_cgroup_stat_index idx)
5110 struct mem_cgroup *iter;
5113 /* Per-cpu values can be negative, use a signed accumulator */
5114 for_each_mem_cgroup_tree(iter, memcg)
5115 val += mem_cgroup_read_stat(iter, idx);
5117 if (val < 0) /* race ? */
5122 static inline u64 mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
5126 if (!mem_cgroup_is_root(memcg)) {
5128 return res_counter_read_u64(&memcg->res, RES_USAGE);
5130 return res_counter_read_u64(&memcg->memsw, RES_USAGE);
5134 * Transparent hugepages are still accounted for in MEM_CGROUP_STAT_RSS
5135 * as well as in MEM_CGROUP_STAT_RSS_HUGE.
5137 val = mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_CACHE);
5138 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_RSS);
5141 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_SWAP);
5143 return val << PAGE_SHIFT;
5146 static ssize_t mem_cgroup_read(struct cgroup_subsys_state *css,
5147 struct cftype *cft, struct file *file,
5148 char __user *buf, size_t nbytes, loff_t *ppos)
5150 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5156 type = MEMFILE_TYPE(cft->private);
5157 name = MEMFILE_ATTR(cft->private);
5161 if (name == RES_USAGE)
5162 val = mem_cgroup_usage(memcg, false);
5164 val = res_counter_read_u64(&memcg->res, name);
5167 if (name == RES_USAGE)
5168 val = mem_cgroup_usage(memcg, true);
5170 val = res_counter_read_u64(&memcg->memsw, name);
5173 val = res_counter_read_u64(&memcg->kmem, name);
5179 len = scnprintf(str, sizeof(str), "%llu\n", (unsigned long long)val);
5180 return simple_read_from_buffer(buf, nbytes, ppos, str, len);
5183 static int memcg_update_kmem_limit(struct cgroup_subsys_state *css, u64 val)
5186 #ifdef CONFIG_MEMCG_KMEM
5187 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5189 * For simplicity, we won't allow this to be disabled. It also can't
5190 * be changed if the cgroup has children already, or if tasks had
5193 * If tasks join before we set the limit, a person looking at
5194 * kmem.usage_in_bytes will have no way to determine when it took
5195 * place, which makes the value quite meaningless.
5197 * After it first became limited, changes in the value of the limit are
5198 * of course permitted.
5200 mutex_lock(&memcg_create_mutex);
5201 mutex_lock(&set_limit_mutex);
5202 if (!memcg->kmem_account_flags && val != RES_COUNTER_MAX) {
5203 if (cgroup_task_count(css->cgroup) || memcg_has_children(memcg)) {
5207 ret = res_counter_set_limit(&memcg->kmem, val);
5210 ret = memcg_update_cache_sizes(memcg);
5212 res_counter_set_limit(&memcg->kmem, RES_COUNTER_MAX);
5215 static_key_slow_inc(&memcg_kmem_enabled_key);
5217 * setting the active bit after the inc will guarantee no one
5218 * starts accounting before all call sites are patched
5220 memcg_kmem_set_active(memcg);
5222 ret = res_counter_set_limit(&memcg->kmem, val);
5224 mutex_unlock(&set_limit_mutex);
5225 mutex_unlock(&memcg_create_mutex);
5230 #ifdef CONFIG_MEMCG_KMEM
5231 static int memcg_propagate_kmem(struct mem_cgroup *memcg)
5234 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
5238 memcg->kmem_account_flags = parent->kmem_account_flags;
5240 * When that happen, we need to disable the static branch only on those
5241 * memcgs that enabled it. To achieve this, we would be forced to
5242 * complicate the code by keeping track of which memcgs were the ones
5243 * that actually enabled limits, and which ones got it from its
5246 * It is a lot simpler just to do static_key_slow_inc() on every child
5247 * that is accounted.
5249 if (!memcg_kmem_is_active(memcg))
5253 * __mem_cgroup_free() will issue static_key_slow_dec() because this
5254 * memcg is active already. If the later initialization fails then the
5255 * cgroup core triggers the cleanup so we do not have to do it here.
5257 static_key_slow_inc(&memcg_kmem_enabled_key);
5259 mutex_lock(&set_limit_mutex);
5260 memcg_stop_kmem_account();
5261 ret = memcg_update_cache_sizes(memcg);
5262 memcg_resume_kmem_account();
5263 mutex_unlock(&set_limit_mutex);
5267 #endif /* CONFIG_MEMCG_KMEM */
5270 * The user of this function is...
5273 static int mem_cgroup_write(struct cgroup_subsys_state *css, struct cftype *cft,
5276 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5279 unsigned long long val;
5282 type = MEMFILE_TYPE(cft->private);
5283 name = MEMFILE_ATTR(cft->private);
5287 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
5291 /* This function does all necessary parse...reuse it */
5292 ret = res_counter_memparse_write_strategy(buffer, &val);
5296 ret = mem_cgroup_resize_limit(memcg, val);
5297 else if (type == _MEMSWAP)
5298 ret = mem_cgroup_resize_memsw_limit(memcg, val);
5299 else if (type == _KMEM)
5300 ret = memcg_update_kmem_limit(css, val);
5304 case RES_SOFT_LIMIT:
5305 ret = res_counter_memparse_write_strategy(buffer, &val);
5309 * For memsw, soft limits are hard to implement in terms
5310 * of semantics, for now, we support soft limits for
5311 * control without swap
5314 ret = res_counter_set_soft_limit(&memcg->res, val);
5319 ret = -EINVAL; /* should be BUG() ? */
5325 static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
5326 unsigned long long *mem_limit, unsigned long long *memsw_limit)
5328 unsigned long long min_limit, min_memsw_limit, tmp;
5330 min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
5331 min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
5332 if (!memcg->use_hierarchy)
5335 while (css_parent(&memcg->css)) {
5336 memcg = mem_cgroup_from_css(css_parent(&memcg->css));
5337 if (!memcg->use_hierarchy)
5339 tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
5340 min_limit = min(min_limit, tmp);
5341 tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
5342 min_memsw_limit = min(min_memsw_limit, tmp);
5345 *mem_limit = min_limit;
5346 *memsw_limit = min_memsw_limit;
5349 static int mem_cgroup_reset(struct cgroup_subsys_state *css, unsigned int event)
5351 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5355 type = MEMFILE_TYPE(event);
5356 name = MEMFILE_ATTR(event);
5361 res_counter_reset_max(&memcg->res);
5362 else if (type == _MEMSWAP)
5363 res_counter_reset_max(&memcg->memsw);
5364 else if (type == _KMEM)
5365 res_counter_reset_max(&memcg->kmem);
5371 res_counter_reset_failcnt(&memcg->res);
5372 else if (type == _MEMSWAP)
5373 res_counter_reset_failcnt(&memcg->memsw);
5374 else if (type == _KMEM)
5375 res_counter_reset_failcnt(&memcg->kmem);
5384 static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
5387 return mem_cgroup_from_css(css)->move_charge_at_immigrate;
5391 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
5392 struct cftype *cft, u64 val)
5394 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5396 if (val >= (1 << NR_MOVE_TYPE))
5400 * No kind of locking is needed in here, because ->can_attach() will
5401 * check this value once in the beginning of the process, and then carry
5402 * on with stale data. This means that changes to this value will only
5403 * affect task migrations starting after the change.
5405 memcg->move_charge_at_immigrate = val;
5409 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
5410 struct cftype *cft, u64 val)
5417 static int memcg_numa_stat_show(struct cgroup_subsys_state *css,
5418 struct cftype *cft, struct seq_file *m)
5421 unsigned long total_nr, file_nr, anon_nr, unevictable_nr;
5422 unsigned long node_nr;
5423 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5425 total_nr = mem_cgroup_nr_lru_pages(memcg, LRU_ALL);
5426 seq_printf(m, "total=%lu", total_nr);
5427 for_each_node_state(nid, N_MEMORY) {
5428 node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL);
5429 seq_printf(m, " N%d=%lu", nid, node_nr);
5433 file_nr = mem_cgroup_nr_lru_pages(memcg, LRU_ALL_FILE);
5434 seq_printf(m, "file=%lu", file_nr);
5435 for_each_node_state(nid, N_MEMORY) {
5436 node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
5438 seq_printf(m, " N%d=%lu", nid, node_nr);
5442 anon_nr = mem_cgroup_nr_lru_pages(memcg, LRU_ALL_ANON);
5443 seq_printf(m, "anon=%lu", anon_nr);
5444 for_each_node_state(nid, N_MEMORY) {
5445 node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
5447 seq_printf(m, " N%d=%lu", nid, node_nr);
5451 unevictable_nr = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_UNEVICTABLE));
5452 seq_printf(m, "unevictable=%lu", unevictable_nr);
5453 for_each_node_state(nid, N_MEMORY) {
5454 node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
5455 BIT(LRU_UNEVICTABLE));
5456 seq_printf(m, " N%d=%lu", nid, node_nr);
5461 #endif /* CONFIG_NUMA */
5463 static inline void mem_cgroup_lru_names_not_uptodate(void)
5465 BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_lru_names) != NR_LRU_LISTS);
5468 static int memcg_stat_show(struct cgroup_subsys_state *css, struct cftype *cft,
5471 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5472 struct mem_cgroup *mi;
5475 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
5476 if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
5478 seq_printf(m, "%s %ld\n", mem_cgroup_stat_names[i],
5479 mem_cgroup_read_stat(memcg, i) * PAGE_SIZE);
5482 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++)
5483 seq_printf(m, "%s %lu\n", mem_cgroup_events_names[i],
5484 mem_cgroup_read_events(memcg, i));
5486 for (i = 0; i < NR_LRU_LISTS; i++)
5487 seq_printf(m, "%s %lu\n", mem_cgroup_lru_names[i],
5488 mem_cgroup_nr_lru_pages(memcg, BIT(i)) * PAGE_SIZE);
5490 /* Hierarchical information */
5492 unsigned long long limit, memsw_limit;
5493 memcg_get_hierarchical_limit(memcg, &limit, &memsw_limit);
5494 seq_printf(m, "hierarchical_memory_limit %llu\n", limit);
5495 if (do_swap_account)
5496 seq_printf(m, "hierarchical_memsw_limit %llu\n",
5500 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
5503 if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
5505 for_each_mem_cgroup_tree(mi, memcg)
5506 val += mem_cgroup_read_stat(mi, i) * PAGE_SIZE;
5507 seq_printf(m, "total_%s %lld\n", mem_cgroup_stat_names[i], val);
5510 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
5511 unsigned long long val = 0;
5513 for_each_mem_cgroup_tree(mi, memcg)
5514 val += mem_cgroup_read_events(mi, i);
5515 seq_printf(m, "total_%s %llu\n",
5516 mem_cgroup_events_names[i], val);
5519 for (i = 0; i < NR_LRU_LISTS; i++) {
5520 unsigned long long val = 0;
5522 for_each_mem_cgroup_tree(mi, memcg)
5523 val += mem_cgroup_nr_lru_pages(mi, BIT(i)) * PAGE_SIZE;
5524 seq_printf(m, "total_%s %llu\n", mem_cgroup_lru_names[i], val);
5527 #ifdef CONFIG_DEBUG_VM
5530 struct mem_cgroup_per_zone *mz;
5531 struct zone_reclaim_stat *rstat;
5532 unsigned long recent_rotated[2] = {0, 0};
5533 unsigned long recent_scanned[2] = {0, 0};
5535 for_each_online_node(nid)
5536 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
5537 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
5538 rstat = &mz->lruvec.reclaim_stat;
5540 recent_rotated[0] += rstat->recent_rotated[0];
5541 recent_rotated[1] += rstat->recent_rotated[1];
5542 recent_scanned[0] += rstat->recent_scanned[0];
5543 recent_scanned[1] += rstat->recent_scanned[1];
5545 seq_printf(m, "recent_rotated_anon %lu\n", recent_rotated[0]);
5546 seq_printf(m, "recent_rotated_file %lu\n", recent_rotated[1]);
5547 seq_printf(m, "recent_scanned_anon %lu\n", recent_scanned[0]);
5548 seq_printf(m, "recent_scanned_file %lu\n", recent_scanned[1]);
5555 static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
5558 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5560 return mem_cgroup_swappiness(memcg);
5563 static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
5564 struct cftype *cft, u64 val)
5566 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5567 struct mem_cgroup *parent = mem_cgroup_from_css(css_parent(&memcg->css));
5569 if (val > 100 || !parent)
5572 mutex_lock(&memcg_create_mutex);
5574 /* If under hierarchy, only empty-root can set this value */
5575 if ((parent->use_hierarchy) || memcg_has_children(memcg)) {
5576 mutex_unlock(&memcg_create_mutex);
5580 memcg->swappiness = val;
5582 mutex_unlock(&memcg_create_mutex);
5587 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
5589 struct mem_cgroup_threshold_ary *t;
5595 t = rcu_dereference(memcg->thresholds.primary);
5597 t = rcu_dereference(memcg->memsw_thresholds.primary);
5602 usage = mem_cgroup_usage(memcg, swap);
5605 * current_threshold points to threshold just below or equal to usage.
5606 * If it's not true, a threshold was crossed after last
5607 * call of __mem_cgroup_threshold().
5609 i = t->current_threshold;
5612 * Iterate backward over array of thresholds starting from
5613 * current_threshold and check if a threshold is crossed.
5614 * If none of thresholds below usage is crossed, we read
5615 * only one element of the array here.
5617 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
5618 eventfd_signal(t->entries[i].eventfd, 1);
5620 /* i = current_threshold + 1 */
5624 * Iterate forward over array of thresholds starting from
5625 * current_threshold+1 and check if a threshold is crossed.
5626 * If none of thresholds above usage is crossed, we read
5627 * only one element of the array here.
5629 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
5630 eventfd_signal(t->entries[i].eventfd, 1);
5632 /* Update current_threshold */
5633 t->current_threshold = i - 1;
5638 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
5641 __mem_cgroup_threshold(memcg, false);
5642 if (do_swap_account)
5643 __mem_cgroup_threshold(memcg, true);
5645 memcg = parent_mem_cgroup(memcg);
5649 static int compare_thresholds(const void *a, const void *b)
5651 const struct mem_cgroup_threshold *_a = a;
5652 const struct mem_cgroup_threshold *_b = b;
5654 if (_a->threshold > _b->threshold)
5657 if (_a->threshold < _b->threshold)
5663 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
5665 struct mem_cgroup_eventfd_list *ev;
5667 list_for_each_entry(ev, &memcg->oom_notify, list)
5668 eventfd_signal(ev->eventfd, 1);
5672 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
5674 struct mem_cgroup *iter;
5676 for_each_mem_cgroup_tree(iter, memcg)
5677 mem_cgroup_oom_notify_cb(iter);
5680 static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
5681 struct eventfd_ctx *eventfd, const char *args, enum res_type type)
5683 struct mem_cgroup_thresholds *thresholds;
5684 struct mem_cgroup_threshold_ary *new;
5685 u64 threshold, usage;
5688 ret = res_counter_memparse_write_strategy(args, &threshold);
5692 mutex_lock(&memcg->thresholds_lock);
5695 thresholds = &memcg->thresholds;
5696 else if (type == _MEMSWAP)
5697 thresholds = &memcg->memsw_thresholds;
5701 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
5703 /* Check if a threshold crossed before adding a new one */
5704 if (thresholds->primary)
5705 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
5707 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
5709 /* Allocate memory for new array of thresholds */
5710 new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
5718 /* Copy thresholds (if any) to new array */
5719 if (thresholds->primary) {
5720 memcpy(new->entries, thresholds->primary->entries, (size - 1) *
5721 sizeof(struct mem_cgroup_threshold));
5724 /* Add new threshold */
5725 new->entries[size - 1].eventfd = eventfd;
5726 new->entries[size - 1].threshold = threshold;
5728 /* Sort thresholds. Registering of new threshold isn't time-critical */
5729 sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
5730 compare_thresholds, NULL);
5732 /* Find current threshold */
5733 new->current_threshold = -1;
5734 for (i = 0; i < size; i++) {
5735 if (new->entries[i].threshold <= usage) {
5737 * new->current_threshold will not be used until
5738 * rcu_assign_pointer(), so it's safe to increment
5741 ++new->current_threshold;
5746 /* Free old spare buffer and save old primary buffer as spare */
5747 kfree(thresholds->spare);
5748 thresholds->spare = thresholds->primary;
5750 rcu_assign_pointer(thresholds->primary, new);
5752 /* To be sure that nobody uses thresholds */
5756 mutex_unlock(&memcg->thresholds_lock);
5761 static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
5762 struct eventfd_ctx *eventfd, const char *args)
5764 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
5767 static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
5768 struct eventfd_ctx *eventfd, const char *args)
5770 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
5773 static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
5774 struct eventfd_ctx *eventfd, enum res_type type)
5776 struct mem_cgroup_thresholds *thresholds;
5777 struct mem_cgroup_threshold_ary *new;
5781 mutex_lock(&memcg->thresholds_lock);
5783 thresholds = &memcg->thresholds;
5784 else if (type == _MEMSWAP)
5785 thresholds = &memcg->memsw_thresholds;
5789 if (!thresholds->primary)
5792 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
5794 /* Check if a threshold crossed before removing */
5795 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
5797 /* Calculate new number of threshold */
5799 for (i = 0; i < thresholds->primary->size; i++) {
5800 if (thresholds->primary->entries[i].eventfd != eventfd)
5804 new = thresholds->spare;
5806 /* Set thresholds array to NULL if we don't have thresholds */
5815 /* Copy thresholds and find current threshold */
5816 new->current_threshold = -1;
5817 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
5818 if (thresholds->primary->entries[i].eventfd == eventfd)
5821 new->entries[j] = thresholds->primary->entries[i];
5822 if (new->entries[j].threshold <= usage) {
5824 * new->current_threshold will not be used
5825 * until rcu_assign_pointer(), so it's safe to increment
5828 ++new->current_threshold;
5834 /* Swap primary and spare array */
5835 thresholds->spare = thresholds->primary;
5836 /* If all events are unregistered, free the spare array */
5838 kfree(thresholds->spare);
5839 thresholds->spare = NULL;
5842 rcu_assign_pointer(thresholds->primary, new);
5844 /* To be sure that nobody uses thresholds */
5847 mutex_unlock(&memcg->thresholds_lock);
5850 static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
5851 struct eventfd_ctx *eventfd)
5853 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
5856 static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
5857 struct eventfd_ctx *eventfd)
5859 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
5862 static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
5863 struct eventfd_ctx *eventfd, const char *args)
5865 struct mem_cgroup_eventfd_list *event;
5867 event = kmalloc(sizeof(*event), GFP_KERNEL);
5871 spin_lock(&memcg_oom_lock);
5873 event->eventfd = eventfd;
5874 list_add(&event->list, &memcg->oom_notify);
5876 /* already in OOM ? */
5877 if (atomic_read(&memcg->under_oom))
5878 eventfd_signal(eventfd, 1);
5879 spin_unlock(&memcg_oom_lock);
5884 static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
5885 struct eventfd_ctx *eventfd)
5887 struct mem_cgroup_eventfd_list *ev, *tmp;
5889 spin_lock(&memcg_oom_lock);
5891 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
5892 if (ev->eventfd == eventfd) {
5893 list_del(&ev->list);
5898 spin_unlock(&memcg_oom_lock);
5901 static int mem_cgroup_oom_control_read(struct cgroup_subsys_state *css,
5902 struct cftype *cft, struct cgroup_map_cb *cb)
5904 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5906 cb->fill(cb, "oom_kill_disable", memcg->oom_kill_disable);
5908 if (atomic_read(&memcg->under_oom))
5909 cb->fill(cb, "under_oom", 1);
5911 cb->fill(cb, "under_oom", 0);
5915 static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
5916 struct cftype *cft, u64 val)
5918 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5919 struct mem_cgroup *parent = mem_cgroup_from_css(css_parent(&memcg->css));
5921 /* cannot set to root cgroup and only 0 and 1 are allowed */
5922 if (!parent || !((val == 0) || (val == 1)))
5925 mutex_lock(&memcg_create_mutex);
5926 /* oom-kill-disable is a flag for subhierarchy. */
5927 if ((parent->use_hierarchy) || memcg_has_children(memcg)) {
5928 mutex_unlock(&memcg_create_mutex);
5931 memcg->oom_kill_disable = val;
5933 memcg_oom_recover(memcg);
5934 mutex_unlock(&memcg_create_mutex);
5938 #ifdef CONFIG_MEMCG_KMEM
5939 static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
5943 memcg->kmemcg_id = -1;
5944 ret = memcg_propagate_kmem(memcg);
5948 return mem_cgroup_sockets_init(memcg, ss);
5951 static void memcg_destroy_kmem(struct mem_cgroup *memcg)
5953 mem_cgroup_sockets_destroy(memcg);
5956 static void kmem_cgroup_css_offline(struct mem_cgroup *memcg)
5958 if (!memcg_kmem_is_active(memcg))
5962 * kmem charges can outlive the cgroup. In the case of slab
5963 * pages, for instance, a page contain objects from various
5964 * processes. As we prevent from taking a reference for every
5965 * such allocation we have to be careful when doing uncharge
5966 * (see memcg_uncharge_kmem) and here during offlining.
5968 * The idea is that that only the _last_ uncharge which sees
5969 * the dead memcg will drop the last reference. An additional
5970 * reference is taken here before the group is marked dead
5971 * which is then paired with css_put during uncharge resp. here.
5973 * Although this might sound strange as this path is called from
5974 * css_offline() when the referencemight have dropped down to 0
5975 * and shouldn't be incremented anymore (css_tryget would fail)
5976 * we do not have other options because of the kmem allocations
5979 css_get(&memcg->css);
5981 memcg_kmem_mark_dead(memcg);
5983 if (res_counter_read_u64(&memcg->kmem, RES_USAGE) != 0)
5986 if (memcg_kmem_test_and_clear_dead(memcg))
5987 css_put(&memcg->css);
5990 static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
5995 static void memcg_destroy_kmem(struct mem_cgroup *memcg)
5999 static void kmem_cgroup_css_offline(struct mem_cgroup *memcg)
6005 * DO NOT USE IN NEW FILES.
6007 * "cgroup.event_control" implementation.
6009 * This is way over-engineered. It tries to support fully configurable
6010 * events for each user. Such level of flexibility is completely
6011 * unnecessary especially in the light of the planned unified hierarchy.
6013 * Please deprecate this and replace with something simpler if at all
6018 * Unregister event and free resources.
6020 * Gets called from workqueue.
6022 static void memcg_event_remove(struct work_struct *work)
6024 struct mem_cgroup_event *event =
6025 container_of(work, struct mem_cgroup_event, remove);
6026 struct mem_cgroup *memcg = event->memcg;
6028 remove_wait_queue(event->wqh, &event->wait);
6030 event->unregister_event(memcg, event->eventfd);
6032 /* Notify userspace the event is going away. */
6033 eventfd_signal(event->eventfd, 1);
6035 eventfd_ctx_put(event->eventfd);
6037 css_put(&memcg->css);
6041 * Gets called on POLLHUP on eventfd when user closes it.
6043 * Called with wqh->lock held and interrupts disabled.
6045 static int memcg_event_wake(wait_queue_t *wait, unsigned mode,
6046 int sync, void *key)
6048 struct mem_cgroup_event *event =
6049 container_of(wait, struct mem_cgroup_event, wait);
6050 struct mem_cgroup *memcg = event->memcg;
6051 unsigned long flags = (unsigned long)key;
6053 if (flags & POLLHUP) {
6055 * If the event has been detached at cgroup removal, we
6056 * can simply return knowing the other side will cleanup
6059 * We can't race against event freeing since the other
6060 * side will require wqh->lock via remove_wait_queue(),
6063 spin_lock(&memcg->event_list_lock);
6064 if (!list_empty(&event->list)) {
6065 list_del_init(&event->list);
6067 * We are in atomic context, but cgroup_event_remove()
6068 * may sleep, so we have to call it in workqueue.
6070 schedule_work(&event->remove);
6072 spin_unlock(&memcg->event_list_lock);
6078 static void memcg_event_ptable_queue_proc(struct file *file,
6079 wait_queue_head_t *wqh, poll_table *pt)
6081 struct mem_cgroup_event *event =
6082 container_of(pt, struct mem_cgroup_event, pt);
6085 add_wait_queue(wqh, &event->wait);
6089 * DO NOT USE IN NEW FILES.
6091 * Parse input and register new cgroup event handler.
6093 * Input must be in format '<event_fd> <control_fd> <args>'.
6094 * Interpretation of args is defined by control file implementation.
6096 static int memcg_write_event_control(struct cgroup_subsys_state *css,
6097 struct cftype *cft, const char *buffer)
6099 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6100 struct mem_cgroup_event *event;
6101 struct cgroup_subsys_state *cfile_css;
6102 unsigned int efd, cfd;
6109 efd = simple_strtoul(buffer, &endp, 10);
6114 cfd = simple_strtoul(buffer, &endp, 10);
6115 if ((*endp != ' ') && (*endp != '\0'))
6119 event = kzalloc(sizeof(*event), GFP_KERNEL);
6123 event->memcg = memcg;
6124 INIT_LIST_HEAD(&event->list);
6125 init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
6126 init_waitqueue_func_entry(&event->wait, memcg_event_wake);
6127 INIT_WORK(&event->remove, memcg_event_remove);
6135 event->eventfd = eventfd_ctx_fileget(efile.file);
6136 if (IS_ERR(event->eventfd)) {
6137 ret = PTR_ERR(event->eventfd);
6144 goto out_put_eventfd;
6147 /* the process need read permission on control file */
6148 /* AV: shouldn't we check that it's been opened for read instead? */
6149 ret = inode_permission(file_inode(cfile.file), MAY_READ);
6154 * Determine the event callbacks and set them in @event. This used
6155 * to be done via struct cftype but cgroup core no longer knows
6156 * about these events. The following is crude but the whole thing
6157 * is for compatibility anyway.
6159 * DO NOT ADD NEW FILES.
6161 name = cfile.file->f_dentry->d_name.name;
6163 if (!strcmp(name, "memory.usage_in_bytes")) {
6164 event->register_event = mem_cgroup_usage_register_event;
6165 event->unregister_event = mem_cgroup_usage_unregister_event;
6166 } else if (!strcmp(name, "memory.oom_control")) {
6167 event->register_event = mem_cgroup_oom_register_event;
6168 event->unregister_event = mem_cgroup_oom_unregister_event;
6169 } else if (!strcmp(name, "memory.pressure_level")) {
6170 event->register_event = vmpressure_register_event;
6171 event->unregister_event = vmpressure_unregister_event;
6172 } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
6173 event->register_event = memsw_cgroup_usage_register_event;
6174 event->unregister_event = memsw_cgroup_usage_unregister_event;
6181 * Verify @cfile should belong to @css. Also, remaining events are
6182 * automatically removed on cgroup destruction but the removal is
6183 * asynchronous, so take an extra ref on @css.
6188 cfile_css = css_from_dir(cfile.file->f_dentry->d_parent,
6189 &mem_cgroup_subsys);
6190 if (cfile_css == css && css_tryget(css))
6197 ret = event->register_event(memcg, event->eventfd, buffer);
6201 efile.file->f_op->poll(efile.file, &event->pt);
6203 spin_lock(&memcg->event_list_lock);
6204 list_add(&event->list, &memcg->event_list);
6205 spin_unlock(&memcg->event_list_lock);
6217 eventfd_ctx_put(event->eventfd);
6226 static struct cftype mem_cgroup_files[] = {
6228 .name = "usage_in_bytes",
6229 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
6230 .read = mem_cgroup_read,
6233 .name = "max_usage_in_bytes",
6234 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
6235 .trigger = mem_cgroup_reset,
6236 .read = mem_cgroup_read,
6239 .name = "limit_in_bytes",
6240 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
6241 .write_string = mem_cgroup_write,
6242 .read = mem_cgroup_read,
6245 .name = "soft_limit_in_bytes",
6246 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
6247 .write_string = mem_cgroup_write,
6248 .read = mem_cgroup_read,
6252 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
6253 .trigger = mem_cgroup_reset,
6254 .read = mem_cgroup_read,
6258 .read_seq_string = memcg_stat_show,
6261 .name = "force_empty",
6262 .trigger = mem_cgroup_force_empty_write,
6265 .name = "use_hierarchy",
6266 .flags = CFTYPE_INSANE,
6267 .write_u64 = mem_cgroup_hierarchy_write,
6268 .read_u64 = mem_cgroup_hierarchy_read,
6271 .name = "cgroup.event_control", /* XXX: for compat */
6272 .write_string = memcg_write_event_control,
6273 .flags = CFTYPE_NO_PREFIX,
6277 .name = "swappiness",
6278 .read_u64 = mem_cgroup_swappiness_read,
6279 .write_u64 = mem_cgroup_swappiness_write,
6282 .name = "move_charge_at_immigrate",
6283 .read_u64 = mem_cgroup_move_charge_read,
6284 .write_u64 = mem_cgroup_move_charge_write,
6287 .name = "oom_control",
6288 .read_map = mem_cgroup_oom_control_read,
6289 .write_u64 = mem_cgroup_oom_control_write,
6290 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
6293 .name = "pressure_level",
6297 .name = "numa_stat",
6298 .read_seq_string = memcg_numa_stat_show,
6301 #ifdef CONFIG_MEMCG_KMEM
6303 .name = "kmem.limit_in_bytes",
6304 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
6305 .write_string = mem_cgroup_write,
6306 .read = mem_cgroup_read,
6309 .name = "kmem.usage_in_bytes",
6310 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
6311 .read = mem_cgroup_read,
6314 .name = "kmem.failcnt",
6315 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
6316 .trigger = mem_cgroup_reset,
6317 .read = mem_cgroup_read,
6320 .name = "kmem.max_usage_in_bytes",
6321 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
6322 .trigger = mem_cgroup_reset,
6323 .read = mem_cgroup_read,
6325 #ifdef CONFIG_SLABINFO
6327 .name = "kmem.slabinfo",
6328 .read_seq_string = mem_cgroup_slabinfo_read,
6332 { }, /* terminate */
6335 #ifdef CONFIG_MEMCG_SWAP
6336 static struct cftype memsw_cgroup_files[] = {
6338 .name = "memsw.usage_in_bytes",
6339 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
6340 .read = mem_cgroup_read,
6343 .name = "memsw.max_usage_in_bytes",
6344 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
6345 .trigger = mem_cgroup_reset,
6346 .read = mem_cgroup_read,
6349 .name = "memsw.limit_in_bytes",
6350 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
6351 .write_string = mem_cgroup_write,
6352 .read = mem_cgroup_read,
6355 .name = "memsw.failcnt",
6356 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
6357 .trigger = mem_cgroup_reset,
6358 .read = mem_cgroup_read,
6360 { }, /* terminate */
6363 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
6365 struct mem_cgroup_per_node *pn;
6366 struct mem_cgroup_per_zone *mz;
6367 int zone, tmp = node;
6369 * This routine is called against possible nodes.
6370 * But it's BUG to call kmalloc() against offline node.
6372 * TODO: this routine can waste much memory for nodes which will
6373 * never be onlined. It's better to use memory hotplug callback
6376 if (!node_state(node, N_NORMAL_MEMORY))
6378 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
6382 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
6383 mz = &pn->zoneinfo[zone];
6384 lruvec_init(&mz->lruvec);
6385 mz->usage_in_excess = 0;
6386 mz->on_tree = false;
6389 memcg->nodeinfo[node] = pn;
6393 static void free_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
6395 kfree(memcg->nodeinfo[node]);
6398 static struct mem_cgroup *mem_cgroup_alloc(void)
6400 struct mem_cgroup *memcg;
6401 size_t size = memcg_size();
6403 /* Can be very big if nr_node_ids is very big */
6404 if (size < PAGE_SIZE)
6405 memcg = kzalloc(size, GFP_KERNEL);
6407 memcg = vzalloc(size);
6412 memcg->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
6415 spin_lock_init(&memcg->pcp_counter_lock);
6419 if (size < PAGE_SIZE)
6427 * At destroying mem_cgroup, references from swap_cgroup can remain.
6428 * (scanning all at force_empty is too costly...)
6430 * Instead of clearing all references at force_empty, we remember
6431 * the number of reference from swap_cgroup and free mem_cgroup when
6432 * it goes down to 0.
6434 * Removal of cgroup itself succeeds regardless of refs from swap.
6437 static void __mem_cgroup_free(struct mem_cgroup *memcg)
6440 size_t size = memcg_size();
6442 mem_cgroup_remove_from_trees(memcg);
6443 free_css_id(&mem_cgroup_subsys, &memcg->css);
6446 free_mem_cgroup_per_zone_info(memcg, node);
6448 free_percpu(memcg->stat);
6451 * We need to make sure that (at least for now), the jump label
6452 * destruction code runs outside of the cgroup lock. This is because
6453 * get_online_cpus(), which is called from the static_branch update,
6454 * can't be called inside the cgroup_lock. cpusets are the ones
6455 * enforcing this dependency, so if they ever change, we might as well.
6457 * schedule_work() will guarantee this happens. Be careful if you need
6458 * to move this code around, and make sure it is outside
6461 disarm_static_keys(memcg);
6462 if (size < PAGE_SIZE)
6469 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
6471 struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg)
6473 if (!memcg->res.parent)
6475 return mem_cgroup_from_res_counter(memcg->res.parent, res);
6477 EXPORT_SYMBOL(parent_mem_cgroup);
6479 static void __init mem_cgroup_soft_limit_tree_init(void)
6481 struct mem_cgroup_tree_per_node *rtpn;
6482 struct mem_cgroup_tree_per_zone *rtpz;
6483 int tmp, node, zone;
6485 for_each_node(node) {
6487 if (!node_state(node, N_NORMAL_MEMORY))
6489 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
6492 soft_limit_tree.rb_tree_per_node[node] = rtpn;
6494 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
6495 rtpz = &rtpn->rb_tree_per_zone[zone];
6496 rtpz->rb_root = RB_ROOT;
6497 spin_lock_init(&rtpz->lock);
6502 static struct cgroup_subsys_state * __ref
6503 mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
6505 struct mem_cgroup *memcg;
6506 long error = -ENOMEM;
6509 memcg = mem_cgroup_alloc();
6511 return ERR_PTR(error);
6514 if (alloc_mem_cgroup_per_zone_info(memcg, node))
6518 if (parent_css == NULL) {
6519 root_mem_cgroup = memcg;
6520 res_counter_init(&memcg->res, NULL);
6521 res_counter_init(&memcg->memsw, NULL);
6522 res_counter_init(&memcg->kmem, NULL);
6525 memcg->last_scanned_node = MAX_NUMNODES;
6526 INIT_LIST_HEAD(&memcg->oom_notify);
6527 memcg->move_charge_at_immigrate = 0;
6528 mutex_init(&memcg->thresholds_lock);
6529 spin_lock_init(&memcg->move_lock);
6530 vmpressure_init(&memcg->vmpressure);
6531 INIT_LIST_HEAD(&memcg->event_list);
6532 spin_lock_init(&memcg->event_list_lock);
6537 __mem_cgroup_free(memcg);
6538 return ERR_PTR(error);
6542 mem_cgroup_css_online(struct cgroup_subsys_state *css)
6544 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6545 struct mem_cgroup *parent = mem_cgroup_from_css(css_parent(css));
6551 mutex_lock(&memcg_create_mutex);
6553 memcg->use_hierarchy = parent->use_hierarchy;
6554 memcg->oom_kill_disable = parent->oom_kill_disable;
6555 memcg->swappiness = mem_cgroup_swappiness(parent);
6557 if (parent->use_hierarchy) {
6558 res_counter_init(&memcg->res, &parent->res);
6559 res_counter_init(&memcg->memsw, &parent->memsw);
6560 res_counter_init(&memcg->kmem, &parent->kmem);
6563 * No need to take a reference to the parent because cgroup
6564 * core guarantees its existence.
6567 res_counter_init(&memcg->res, NULL);
6568 res_counter_init(&memcg->memsw, NULL);
6569 res_counter_init(&memcg->kmem, NULL);
6571 * Deeper hierachy with use_hierarchy == false doesn't make
6572 * much sense so let cgroup subsystem know about this
6573 * unfortunate state in our controller.
6575 if (parent != root_mem_cgroup)
6576 mem_cgroup_subsys.broken_hierarchy = true;
6579 error = memcg_init_kmem(memcg, &mem_cgroup_subsys);
6580 mutex_unlock(&memcg_create_mutex);
6585 * Announce all parents that a group from their hierarchy is gone.
6587 static void mem_cgroup_invalidate_reclaim_iterators(struct mem_cgroup *memcg)
6589 struct mem_cgroup *parent = memcg;
6591 while ((parent = parent_mem_cgroup(parent)))
6592 mem_cgroup_iter_invalidate(parent);
6595 * if the root memcg is not hierarchical we have to check it
6598 if (!root_mem_cgroup->use_hierarchy)
6599 mem_cgroup_iter_invalidate(root_mem_cgroup);
6602 static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
6604 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6605 struct mem_cgroup_event *event, *tmp;
6608 * Unregister events and notify userspace.
6609 * Notify userspace about cgroup removing only after rmdir of cgroup
6610 * directory to avoid race between userspace and kernelspace.
6612 spin_lock(&memcg->event_list_lock);
6613 list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
6614 list_del_init(&event->list);
6615 schedule_work(&event->remove);
6617 spin_unlock(&memcg->event_list_lock);
6619 kmem_cgroup_css_offline(memcg);
6621 mem_cgroup_invalidate_reclaim_iterators(memcg);
6622 mem_cgroup_reparent_charges(memcg);
6623 mem_cgroup_destroy_all_caches(memcg);
6624 vmpressure_cleanup(&memcg->vmpressure);
6627 static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
6629 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6631 memcg_destroy_kmem(memcg);
6632 __mem_cgroup_free(memcg);
6636 /* Handlers for move charge at task migration. */
6637 #define PRECHARGE_COUNT_AT_ONCE 256
6638 static int mem_cgroup_do_precharge(unsigned long count)
6641 int batch_count = PRECHARGE_COUNT_AT_ONCE;
6642 struct mem_cgroup *memcg = mc.to;
6644 if (mem_cgroup_is_root(memcg)) {
6645 mc.precharge += count;
6646 /* we don't need css_get for root */
6649 /* try to charge at once */
6651 struct res_counter *dummy;
6653 * "memcg" cannot be under rmdir() because we've already checked
6654 * by cgroup_lock_live_cgroup() that it is not removed and we
6655 * are still under the same cgroup_mutex. So we can postpone
6658 if (res_counter_charge(&memcg->res, PAGE_SIZE * count, &dummy))
6660 if (do_swap_account && res_counter_charge(&memcg->memsw,
6661 PAGE_SIZE * count, &dummy)) {
6662 res_counter_uncharge(&memcg->res, PAGE_SIZE * count);
6665 mc.precharge += count;
6669 /* fall back to one by one charge */
6671 if (signal_pending(current)) {
6675 if (!batch_count--) {
6676 batch_count = PRECHARGE_COUNT_AT_ONCE;
6679 ret = __mem_cgroup_try_charge(NULL,
6680 GFP_KERNEL, 1, &memcg, false);
6682 /* mem_cgroup_clear_mc() will do uncharge later */
6690 * get_mctgt_type - get target type of moving charge
6691 * @vma: the vma the pte to be checked belongs
6692 * @addr: the address corresponding to the pte to be checked
6693 * @ptent: the pte to be checked
6694 * @target: the pointer the target page or swap ent will be stored(can be NULL)
6697 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
6698 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
6699 * move charge. if @target is not NULL, the page is stored in target->page
6700 * with extra refcnt got(Callers should handle it).
6701 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
6702 * target for charge migration. if @target is not NULL, the entry is stored
6705 * Called with pte lock held.
6712 enum mc_target_type {
6718 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
6719 unsigned long addr, pte_t ptent)
6721 struct page *page = vm_normal_page(vma, addr, ptent);
6723 if (!page || !page_mapped(page))
6725 if (PageAnon(page)) {
6726 /* we don't move shared anon */
6729 } else if (!move_file())
6730 /* we ignore mapcount for file pages */
6732 if (!get_page_unless_zero(page))
6739 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
6740 unsigned long addr, pte_t ptent, swp_entry_t *entry)
6742 struct page *page = NULL;
6743 swp_entry_t ent = pte_to_swp_entry(ptent);
6745 if (!move_anon() || non_swap_entry(ent))
6748 * Because lookup_swap_cache() updates some statistics counter,
6749 * we call find_get_page() with swapper_space directly.
6751 page = find_get_page(swap_address_space(ent), ent.val);
6752 if (do_swap_account)
6753 entry->val = ent.val;
6758 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
6759 unsigned long addr, pte_t ptent, swp_entry_t *entry)
6765 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
6766 unsigned long addr, pte_t ptent, swp_entry_t *entry)
6768 struct page *page = NULL;
6769 struct address_space *mapping;
6772 if (!vma->vm_file) /* anonymous vma */
6777 mapping = vma->vm_file->f_mapping;
6778 if (pte_none(ptent))
6779 pgoff = linear_page_index(vma, addr);
6780 else /* pte_file(ptent) is true */
6781 pgoff = pte_to_pgoff(ptent);
6783 /* page is moved even if it's not RSS of this task(page-faulted). */
6784 page = find_get_page(mapping, pgoff);
6787 /* shmem/tmpfs may report page out on swap: account for that too. */
6788 if (radix_tree_exceptional_entry(page)) {
6789 swp_entry_t swap = radix_to_swp_entry(page);
6790 if (do_swap_account)
6792 page = find_get_page(swap_address_space(swap), swap.val);
6798 static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
6799 unsigned long addr, pte_t ptent, union mc_target *target)
6801 struct page *page = NULL;
6802 struct page_cgroup *pc;
6803 enum mc_target_type ret = MC_TARGET_NONE;
6804 swp_entry_t ent = { .val = 0 };
6806 if (pte_present(ptent))
6807 page = mc_handle_present_pte(vma, addr, ptent);
6808 else if (is_swap_pte(ptent))
6809 page = mc_handle_swap_pte(vma, addr, ptent, &ent);
6810 else if (pte_none(ptent) || pte_file(ptent))
6811 page = mc_handle_file_pte(vma, addr, ptent, &ent);
6813 if (!page && !ent.val)
6816 pc = lookup_page_cgroup(page);
6818 * Do only loose check w/o page_cgroup lock.
6819 * mem_cgroup_move_account() checks the pc is valid or not under
6822 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
6823 ret = MC_TARGET_PAGE;
6825 target->page = page;
6827 if (!ret || !target)
6830 /* There is a swap entry and a page doesn't exist or isn't charged */
6831 if (ent.val && !ret &&
6832 css_id(&mc.from->css) == lookup_swap_cgroup_id(ent)) {
6833 ret = MC_TARGET_SWAP;
6840 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
6842 * We don't consider swapping or file mapped pages because THP does not
6843 * support them for now.
6844 * Caller should make sure that pmd_trans_huge(pmd) is true.
6846 static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
6847 unsigned long addr, pmd_t pmd, union mc_target *target)
6849 struct page *page = NULL;
6850 struct page_cgroup *pc;
6851 enum mc_target_type ret = MC_TARGET_NONE;
6853 page = pmd_page(pmd);
6854 VM_BUG_ON(!page || !PageHead(page));
6857 pc = lookup_page_cgroup(page);
6858 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
6859 ret = MC_TARGET_PAGE;
6862 target->page = page;
6868 static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
6869 unsigned long addr, pmd_t pmd, union mc_target *target)
6871 return MC_TARGET_NONE;
6875 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
6876 unsigned long addr, unsigned long end,
6877 struct mm_walk *walk)
6879 struct vm_area_struct *vma = walk->private;
6883 if (pmd_trans_huge_lock(pmd, vma) == 1) {
6884 if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
6885 mc.precharge += HPAGE_PMD_NR;
6886 spin_unlock(&vma->vm_mm->page_table_lock);
6890 if (pmd_trans_unstable(pmd))
6892 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6893 for (; addr != end; pte++, addr += PAGE_SIZE)
6894 if (get_mctgt_type(vma, addr, *pte, NULL))
6895 mc.precharge++; /* increment precharge temporarily */
6896 pte_unmap_unlock(pte - 1, ptl);
6902 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
6904 unsigned long precharge;
6905 struct vm_area_struct *vma;
6907 down_read(&mm->mmap_sem);
6908 for (vma = mm->mmap; vma; vma = vma->vm_next) {
6909 struct mm_walk mem_cgroup_count_precharge_walk = {
6910 .pmd_entry = mem_cgroup_count_precharge_pte_range,
6914 if (is_vm_hugetlb_page(vma))
6916 walk_page_range(vma->vm_start, vma->vm_end,
6917 &mem_cgroup_count_precharge_walk);
6919 up_read(&mm->mmap_sem);
6921 precharge = mc.precharge;
6927 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
6929 unsigned long precharge = mem_cgroup_count_precharge(mm);
6931 VM_BUG_ON(mc.moving_task);
6932 mc.moving_task = current;
6933 return mem_cgroup_do_precharge(precharge);
6936 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
6937 static void __mem_cgroup_clear_mc(void)
6939 struct mem_cgroup *from = mc.from;
6940 struct mem_cgroup *to = mc.to;
6943 /* we must uncharge all the leftover precharges from mc.to */
6945 __mem_cgroup_cancel_charge(mc.to, mc.precharge);
6949 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
6950 * we must uncharge here.
6952 if (mc.moved_charge) {
6953 __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
6954 mc.moved_charge = 0;
6956 /* we must fixup refcnts and charges */
6957 if (mc.moved_swap) {
6958 /* uncharge swap account from the old cgroup */
6959 if (!mem_cgroup_is_root(mc.from))
6960 res_counter_uncharge(&mc.from->memsw,
6961 PAGE_SIZE * mc.moved_swap);
6963 for (i = 0; i < mc.moved_swap; i++)
6964 css_put(&mc.from->css);
6966 if (!mem_cgroup_is_root(mc.to)) {
6968 * we charged both to->res and to->memsw, so we should
6971 res_counter_uncharge(&mc.to->res,
6972 PAGE_SIZE * mc.moved_swap);
6974 /* we've already done css_get(mc.to) */
6977 memcg_oom_recover(from);
6978 memcg_oom_recover(to);
6979 wake_up_all(&mc.waitq);
6982 static void mem_cgroup_clear_mc(void)
6984 struct mem_cgroup *from = mc.from;
6987 * we must clear moving_task before waking up waiters at the end of
6990 mc.moving_task = NULL;
6991 __mem_cgroup_clear_mc();
6992 spin_lock(&mc.lock);
6995 spin_unlock(&mc.lock);
6996 mem_cgroup_end_move(from);
6999 static int mem_cgroup_can_attach(struct cgroup_subsys_state *css,
7000 struct cgroup_taskset *tset)
7002 struct task_struct *p = cgroup_taskset_first(tset);
7004 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
7005 unsigned long move_charge_at_immigrate;
7008 * We are now commited to this value whatever it is. Changes in this
7009 * tunable will only affect upcoming migrations, not the current one.
7010 * So we need to save it, and keep it going.
7012 move_charge_at_immigrate = memcg->move_charge_at_immigrate;
7013 if (move_charge_at_immigrate) {
7014 struct mm_struct *mm;
7015 struct mem_cgroup *from = mem_cgroup_from_task(p);
7017 VM_BUG_ON(from == memcg);
7019 mm = get_task_mm(p);
7022 /* We move charges only when we move a owner of the mm */
7023 if (mm->owner == p) {
7026 VM_BUG_ON(mc.precharge);
7027 VM_BUG_ON(mc.moved_charge);
7028 VM_BUG_ON(mc.moved_swap);
7029 mem_cgroup_start_move(from);
7030 spin_lock(&mc.lock);
7033 mc.immigrate_flags = move_charge_at_immigrate;
7034 spin_unlock(&mc.lock);
7035 /* We set mc.moving_task later */
7037 ret = mem_cgroup_precharge_mc(mm);
7039 mem_cgroup_clear_mc();
7046 static void mem_cgroup_cancel_attach(struct cgroup_subsys_state *css,
7047 struct cgroup_taskset *tset)
7049 mem_cgroup_clear_mc();
7052 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
7053 unsigned long addr, unsigned long end,
7054 struct mm_walk *walk)
7057 struct vm_area_struct *vma = walk->private;
7060 enum mc_target_type target_type;
7061 union mc_target target;
7063 struct page_cgroup *pc;
7066 * We don't take compound_lock() here but no race with splitting thp
7068 * - if pmd_trans_huge_lock() returns 1, the relevant thp is not
7069 * under splitting, which means there's no concurrent thp split,
7070 * - if another thread runs into split_huge_page() just after we
7071 * entered this if-block, the thread must wait for page table lock
7072 * to be unlocked in __split_huge_page_splitting(), where the main
7073 * part of thp split is not executed yet.
7075 if (pmd_trans_huge_lock(pmd, vma) == 1) {
7076 if (mc.precharge < HPAGE_PMD_NR) {
7077 spin_unlock(&vma->vm_mm->page_table_lock);
7080 target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
7081 if (target_type == MC_TARGET_PAGE) {
7083 if (!isolate_lru_page(page)) {
7084 pc = lookup_page_cgroup(page);
7085 if (!mem_cgroup_move_account(page, HPAGE_PMD_NR,
7086 pc, mc.from, mc.to)) {
7087 mc.precharge -= HPAGE_PMD_NR;
7088 mc.moved_charge += HPAGE_PMD_NR;
7090 putback_lru_page(page);
7094 spin_unlock(&vma->vm_mm->page_table_lock);
7098 if (pmd_trans_unstable(pmd))
7101 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
7102 for (; addr != end; addr += PAGE_SIZE) {
7103 pte_t ptent = *(pte++);
7109 switch (get_mctgt_type(vma, addr, ptent, &target)) {
7110 case MC_TARGET_PAGE:
7112 if (isolate_lru_page(page))
7114 pc = lookup_page_cgroup(page);
7115 if (!mem_cgroup_move_account(page, 1, pc,
7118 /* we uncharge from mc.from later. */
7121 putback_lru_page(page);
7122 put: /* get_mctgt_type() gets the page */
7125 case MC_TARGET_SWAP:
7127 if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
7129 /* we fixup refcnts and charges later. */
7137 pte_unmap_unlock(pte - 1, ptl);
7142 * We have consumed all precharges we got in can_attach().
7143 * We try charge one by one, but don't do any additional
7144 * charges to mc.to if we have failed in charge once in attach()
7147 ret = mem_cgroup_do_precharge(1);
7155 static void mem_cgroup_move_charge(struct mm_struct *mm)
7157 struct vm_area_struct *vma;
7159 lru_add_drain_all();
7161 if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
7163 * Someone who are holding the mmap_sem might be waiting in
7164 * waitq. So we cancel all extra charges, wake up all waiters,
7165 * and retry. Because we cancel precharges, we might not be able
7166 * to move enough charges, but moving charge is a best-effort
7167 * feature anyway, so it wouldn't be a big problem.
7169 __mem_cgroup_clear_mc();
7173 for (vma = mm->mmap; vma; vma = vma->vm_next) {
7175 struct mm_walk mem_cgroup_move_charge_walk = {
7176 .pmd_entry = mem_cgroup_move_charge_pte_range,
7180 if (is_vm_hugetlb_page(vma))
7182 ret = walk_page_range(vma->vm_start, vma->vm_end,
7183 &mem_cgroup_move_charge_walk);
7186 * means we have consumed all precharges and failed in
7187 * doing additional charge. Just abandon here.
7191 up_read(&mm->mmap_sem);
7194 static void mem_cgroup_move_task(struct cgroup_subsys_state *css,
7195 struct cgroup_taskset *tset)
7197 struct task_struct *p = cgroup_taskset_first(tset);
7198 struct mm_struct *mm = get_task_mm(p);
7202 mem_cgroup_move_charge(mm);
7206 mem_cgroup_clear_mc();
7208 #else /* !CONFIG_MMU */
7209 static int mem_cgroup_can_attach(struct cgroup_subsys_state *css,
7210 struct cgroup_taskset *tset)
7214 static void mem_cgroup_cancel_attach(struct cgroup_subsys_state *css,
7215 struct cgroup_taskset *tset)
7218 static void mem_cgroup_move_task(struct cgroup_subsys_state *css,
7219 struct cgroup_taskset *tset)
7225 * Cgroup retains root cgroups across [un]mount cycles making it necessary
7226 * to verify sane_behavior flag on each mount attempt.
7228 static void mem_cgroup_bind(struct cgroup_subsys_state *root_css)
7231 * use_hierarchy is forced with sane_behavior. cgroup core
7232 * guarantees that @root doesn't have any children, so turning it
7233 * on for the root memcg is enough.
7235 if (cgroup_sane_behavior(root_css->cgroup))
7236 mem_cgroup_from_css(root_css)->use_hierarchy = true;
7239 struct cgroup_subsys mem_cgroup_subsys = {
7241 .subsys_id = mem_cgroup_subsys_id,
7242 .css_alloc = mem_cgroup_css_alloc,
7243 .css_online = mem_cgroup_css_online,
7244 .css_offline = mem_cgroup_css_offline,
7245 .css_free = mem_cgroup_css_free,
7246 .can_attach = mem_cgroup_can_attach,
7247 .cancel_attach = mem_cgroup_cancel_attach,
7248 .attach = mem_cgroup_move_task,
7249 .bind = mem_cgroup_bind,
7250 .base_cftypes = mem_cgroup_files,
7255 #ifdef CONFIG_MEMCG_SWAP
7256 static int __init enable_swap_account(char *s)
7258 if (!strcmp(s, "1"))
7259 really_do_swap_account = 1;
7260 else if (!strcmp(s, "0"))
7261 really_do_swap_account = 0;
7264 __setup("swapaccount=", enable_swap_account);
7266 static void __init memsw_file_init(void)
7268 WARN_ON(cgroup_add_cftypes(&mem_cgroup_subsys, memsw_cgroup_files));
7271 static void __init enable_swap_cgroup(void)
7273 if (!mem_cgroup_disabled() && really_do_swap_account) {
7274 do_swap_account = 1;
7280 static void __init enable_swap_cgroup(void)
7286 * subsys_initcall() for memory controller.
7288 * Some parts like hotcpu_notifier() have to be initialized from this context
7289 * because of lock dependencies (cgroup_lock -> cpu hotplug) but basically
7290 * everything that doesn't depend on a specific mem_cgroup structure should
7291 * be initialized from here.
7293 static int __init mem_cgroup_init(void)
7295 hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
7296 enable_swap_cgroup();
7297 mem_cgroup_soft_limit_tree_init();
7301 subsys_initcall(mem_cgroup_init);