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/slab.h>
43 #include <linux/swap.h>
44 #include <linux/swapops.h>
45 #include <linux/spinlock.h>
46 #include <linux/eventfd.h>
47 #include <linux/sort.h>
49 #include <linux/seq_file.h>
50 #include <linux/vmalloc.h>
51 #include <linux/vmpressure.h>
52 #include <linux/mm_inline.h>
53 #include <linux/page_cgroup.h>
54 #include <linux/cpu.h>
55 #include <linux/oom.h>
59 #include <net/tcp_memcontrol.h>
61 #include <asm/uaccess.h>
63 #include <trace/events/vmscan.h>
65 struct cgroup_subsys mem_cgroup_subsys __read_mostly;
66 EXPORT_SYMBOL(mem_cgroup_subsys);
68 #define MEM_CGROUP_RECLAIM_RETRIES 5
69 static struct mem_cgroup *root_mem_cgroup __read_mostly;
71 #ifdef CONFIG_MEMCG_SWAP
72 /* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
73 int do_swap_account __read_mostly;
75 /* for remember boot option*/
76 #ifdef CONFIG_MEMCG_SWAP_ENABLED
77 static int really_do_swap_account __initdata = 1;
79 static int really_do_swap_account __initdata = 0;
83 #define do_swap_account 0
87 static const char * const mem_cgroup_stat_names[] = {
96 enum mem_cgroup_events_index {
97 MEM_CGROUP_EVENTS_PGPGIN, /* # of pages paged in */
98 MEM_CGROUP_EVENTS_PGPGOUT, /* # of pages paged out */
99 MEM_CGROUP_EVENTS_PGFAULT, /* # of page-faults */
100 MEM_CGROUP_EVENTS_PGMAJFAULT, /* # of major page-faults */
101 MEM_CGROUP_EVENTS_NSTATS,
104 static const char * const mem_cgroup_events_names[] = {
111 static const char * const mem_cgroup_lru_names[] = {
120 * Per memcg event counter is incremented at every pagein/pageout. With THP,
121 * it will be incremated by the number of pages. This counter is used for
122 * for trigger some periodic events. This is straightforward and better
123 * than using jiffies etc. to handle periodic memcg event.
125 enum mem_cgroup_events_target {
126 MEM_CGROUP_TARGET_THRESH,
127 MEM_CGROUP_TARGET_SOFTLIMIT,
128 MEM_CGROUP_TARGET_NUMAINFO,
131 #define THRESHOLDS_EVENTS_TARGET 128
132 #define SOFTLIMIT_EVENTS_TARGET 1024
133 #define NUMAINFO_EVENTS_TARGET 1024
135 struct mem_cgroup_stat_cpu {
136 long count[MEM_CGROUP_STAT_NSTATS];
137 unsigned long events[MEM_CGROUP_EVENTS_NSTATS];
138 unsigned long nr_page_events;
139 unsigned long targets[MEM_CGROUP_NTARGETS];
142 struct mem_cgroup_reclaim_iter {
144 * last scanned hierarchy member. Valid only if last_dead_count
145 * matches memcg->dead_count of the hierarchy root group.
147 struct mem_cgroup *last_visited;
148 unsigned long last_dead_count;
150 /* scan generation, increased every round-trip */
151 unsigned int generation;
155 * per-zone information in memory controller.
157 struct mem_cgroup_per_zone {
158 struct lruvec lruvec;
159 unsigned long lru_size[NR_LRU_LISTS];
161 struct mem_cgroup_reclaim_iter reclaim_iter[DEF_PRIORITY + 1];
163 struct mem_cgroup *memcg; /* Back pointer, we cannot */
164 /* use container_of */
167 struct mem_cgroup_per_node {
168 struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
171 struct mem_cgroup_threshold {
172 struct eventfd_ctx *eventfd;
177 struct mem_cgroup_threshold_ary {
178 /* An array index points to threshold just below or equal to usage. */
179 int current_threshold;
180 /* Size of entries[] */
182 /* Array of thresholds */
183 struct mem_cgroup_threshold entries[0];
186 struct mem_cgroup_thresholds {
187 /* Primary thresholds array */
188 struct mem_cgroup_threshold_ary *primary;
190 * Spare threshold array.
191 * This is needed to make mem_cgroup_unregister_event() "never fail".
192 * It must be able to store at least primary->size - 1 entries.
194 struct mem_cgroup_threshold_ary *spare;
198 struct mem_cgroup_eventfd_list {
199 struct list_head list;
200 struct eventfd_ctx *eventfd;
203 static void mem_cgroup_threshold(struct mem_cgroup *memcg);
204 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
207 * The memory controller data structure. The memory controller controls both
208 * page cache and RSS per cgroup. We would eventually like to provide
209 * statistics based on the statistics developed by Rik Van Riel for clock-pro,
210 * to help the administrator determine what knobs to tune.
212 * TODO: Add a water mark for the memory controller. Reclaim will begin when
213 * we hit the water mark. May be even add a low water mark, such that
214 * no reclaim occurs from a cgroup at it's low water mark, this is
215 * a feature that will be implemented much later in the future.
218 struct cgroup_subsys_state css;
220 * the counter to account for memory usage
222 struct res_counter res;
224 /* vmpressure notifications */
225 struct vmpressure vmpressure;
228 * the counter to account for mem+swap usage.
230 struct res_counter memsw;
233 * the counter to account for kernel memory usage.
235 struct res_counter kmem;
237 * Should the accounting and control be hierarchical, per subtree?
240 unsigned long kmem_account_flags; /* See KMEM_ACCOUNTED_*, below */
244 atomic_t oom_wakeups;
247 /* OOM-Killer disable */
248 int oom_kill_disable;
250 /* set when res.limit == memsw.limit */
251 bool memsw_is_minimum;
253 /* protect arrays of thresholds */
254 struct mutex thresholds_lock;
256 /* thresholds for memory usage. RCU-protected */
257 struct mem_cgroup_thresholds thresholds;
259 /* thresholds for mem+swap usage. RCU-protected */
260 struct mem_cgroup_thresholds memsw_thresholds;
262 /* For oom notifier event fd */
263 struct list_head oom_notify;
266 * Should we move charges of a task when a task is moved into this
267 * mem_cgroup ? And what type of charges should we move ?
269 unsigned long move_charge_at_immigrate;
271 * set > 0 if pages under this cgroup are moving to other cgroup.
273 atomic_t moving_account;
274 /* taken only while moving_account > 0 */
275 spinlock_t move_lock;
279 struct mem_cgroup_stat_cpu __percpu *stat;
281 * used when a cpu is offlined or other synchronizations
282 * See mem_cgroup_read_stat().
284 struct mem_cgroup_stat_cpu nocpu_base;
285 spinlock_t pcp_counter_lock;
288 #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_INET)
289 struct tcp_memcontrol tcp_mem;
291 #if defined(CONFIG_MEMCG_KMEM)
292 /* analogous to slab_common's slab_caches list. per-memcg */
293 struct list_head memcg_slab_caches;
294 /* Not a spinlock, we can take a lot of time walking the list */
295 struct mutex slab_caches_mutex;
296 /* Index in the kmem_cache->memcg_params->memcg_caches array */
300 int last_scanned_node;
302 nodemask_t scan_nodes;
303 atomic_t numainfo_events;
304 atomic_t numainfo_updating;
307 * Protects soft_contributed transitions.
308 * See mem_cgroup_update_soft_limit
310 spinlock_t soft_lock;
313 * If true then this group has increased parents' children_in_excess
314 * when it got over the soft limit.
315 * When a group falls bellow the soft limit, parents' children_in_excess
316 * is decreased and soft_contributed changed to false.
318 bool soft_contributed;
320 /* Number of children that are in soft limit excess */
321 atomic_t children_in_excess;
323 struct mem_cgroup_per_node *nodeinfo[0];
324 /* WARNING: nodeinfo must be the last member here */
327 static size_t memcg_size(void)
329 return sizeof(struct mem_cgroup) +
330 nr_node_ids * sizeof(struct mem_cgroup_per_node);
333 /* internal only representation about the status of kmem accounting. */
335 KMEM_ACCOUNTED_ACTIVE = 0, /* accounted by this cgroup itself */
336 KMEM_ACCOUNTED_ACTIVATED, /* static key enabled. */
337 KMEM_ACCOUNTED_DEAD, /* dead memcg with pending kmem charges */
340 /* We account when limit is on, but only after call sites are patched */
341 #define KMEM_ACCOUNTED_MASK \
342 ((1 << KMEM_ACCOUNTED_ACTIVE) | (1 << KMEM_ACCOUNTED_ACTIVATED))
344 #ifdef CONFIG_MEMCG_KMEM
345 static inline void memcg_kmem_set_active(struct mem_cgroup *memcg)
347 set_bit(KMEM_ACCOUNTED_ACTIVE, &memcg->kmem_account_flags);
350 static bool memcg_kmem_is_active(struct mem_cgroup *memcg)
352 return test_bit(KMEM_ACCOUNTED_ACTIVE, &memcg->kmem_account_flags);
355 static void memcg_kmem_set_activated(struct mem_cgroup *memcg)
357 set_bit(KMEM_ACCOUNTED_ACTIVATED, &memcg->kmem_account_flags);
360 static void memcg_kmem_clear_activated(struct mem_cgroup *memcg)
362 clear_bit(KMEM_ACCOUNTED_ACTIVATED, &memcg->kmem_account_flags);
365 static void memcg_kmem_mark_dead(struct mem_cgroup *memcg)
368 * Our caller must use css_get() first, because memcg_uncharge_kmem()
369 * will call css_put() if it sees the memcg is dead.
372 if (test_bit(KMEM_ACCOUNTED_ACTIVE, &memcg->kmem_account_flags))
373 set_bit(KMEM_ACCOUNTED_DEAD, &memcg->kmem_account_flags);
376 static bool memcg_kmem_test_and_clear_dead(struct mem_cgroup *memcg)
378 return test_and_clear_bit(KMEM_ACCOUNTED_DEAD,
379 &memcg->kmem_account_flags);
383 /* Stuffs for move charges at task migration. */
385 * Types of charges to be moved. "move_charge_at_immitgrate" and
386 * "immigrate_flags" are treated as a left-shifted bitmap of these types.
389 MOVE_CHARGE_TYPE_ANON, /* private anonymous page and swap of it */
390 MOVE_CHARGE_TYPE_FILE, /* file page(including tmpfs) and swap of it */
394 /* "mc" and its members are protected by cgroup_mutex */
395 static struct move_charge_struct {
396 spinlock_t lock; /* for from, to */
397 struct mem_cgroup *from;
398 struct mem_cgroup *to;
399 unsigned long immigrate_flags;
400 unsigned long precharge;
401 unsigned long moved_charge;
402 unsigned long moved_swap;
403 struct task_struct *moving_task; /* a task moving charges */
404 wait_queue_head_t waitq; /* a waitq for other context */
406 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
407 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
410 static bool move_anon(void)
412 return test_bit(MOVE_CHARGE_TYPE_ANON, &mc.immigrate_flags);
415 static bool move_file(void)
417 return test_bit(MOVE_CHARGE_TYPE_FILE, &mc.immigrate_flags);
421 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
422 * limit reclaim to prevent infinite loops, if they ever occur.
424 #define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
427 MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
428 MEM_CGROUP_CHARGE_TYPE_ANON,
429 MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
430 MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
434 /* for encoding cft->private value on file */
442 #define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
443 #define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
444 #define MEMFILE_ATTR(val) ((val) & 0xffff)
445 /* Used for OOM nofiier */
446 #define OOM_CONTROL (0)
449 * Reclaim flags for mem_cgroup_hierarchical_reclaim
451 #define MEM_CGROUP_RECLAIM_NOSWAP_BIT 0x0
452 #define MEM_CGROUP_RECLAIM_NOSWAP (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
453 #define MEM_CGROUP_RECLAIM_SHRINK_BIT 0x1
454 #define MEM_CGROUP_RECLAIM_SHRINK (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
457 * The memcg_create_mutex will be held whenever a new cgroup is created.
458 * As a consequence, any change that needs to protect against new child cgroups
459 * appearing has to hold it as well.
461 static DEFINE_MUTEX(memcg_create_mutex);
463 struct mem_cgroup *mem_cgroup_from_css(struct cgroup_subsys_state *s)
465 return s ? container_of(s, struct mem_cgroup, css) : NULL;
468 /* Some nice accessors for the vmpressure. */
469 struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
472 memcg = root_mem_cgroup;
473 return &memcg->vmpressure;
476 struct cgroup_subsys_state *vmpressure_to_css(struct vmpressure *vmpr)
478 return &container_of(vmpr, struct mem_cgroup, vmpressure)->css;
481 struct vmpressure *css_to_vmpressure(struct cgroup_subsys_state *css)
483 return &mem_cgroup_from_css(css)->vmpressure;
486 static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg)
488 return (memcg == root_mem_cgroup);
492 * We restrict the id in the range of [1, 65535], so it can fit into
495 #define MEM_CGROUP_ID_MAX USHRT_MAX
497 static inline unsigned short mem_cgroup_id(struct mem_cgroup *memcg)
500 * The ID of the root cgroup is 0, but memcg treat 0 as an
501 * invalid ID, so we return (cgroup_id + 1).
503 return memcg->css.cgroup->id + 1;
506 static inline struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
508 struct cgroup_subsys_state *css;
510 css = css_from_id(id - 1, &mem_cgroup_subsys);
511 return mem_cgroup_from_css(css);
514 /* Writing them here to avoid exposing memcg's inner layout */
515 #if defined(CONFIG_INET) && defined(CONFIG_MEMCG_KMEM)
517 void sock_update_memcg(struct sock *sk)
519 if (mem_cgroup_sockets_enabled) {
520 struct mem_cgroup *memcg;
521 struct cg_proto *cg_proto;
523 BUG_ON(!sk->sk_prot->proto_cgroup);
525 /* Socket cloning can throw us here with sk_cgrp already
526 * filled. It won't however, necessarily happen from
527 * process context. So the test for root memcg given
528 * the current task's memcg won't help us in this case.
530 * Respecting the original socket's memcg is a better
531 * decision in this case.
534 BUG_ON(mem_cgroup_is_root(sk->sk_cgrp->memcg));
535 css_get(&sk->sk_cgrp->memcg->css);
540 memcg = mem_cgroup_from_task(current);
541 cg_proto = sk->sk_prot->proto_cgroup(memcg);
542 if (!mem_cgroup_is_root(memcg) &&
543 memcg_proto_active(cg_proto) && css_tryget(&memcg->css)) {
544 sk->sk_cgrp = cg_proto;
549 EXPORT_SYMBOL(sock_update_memcg);
551 void sock_release_memcg(struct sock *sk)
553 if (mem_cgroup_sockets_enabled && sk->sk_cgrp) {
554 struct mem_cgroup *memcg;
555 WARN_ON(!sk->sk_cgrp->memcg);
556 memcg = sk->sk_cgrp->memcg;
557 css_put(&sk->sk_cgrp->memcg->css);
561 struct cg_proto *tcp_proto_cgroup(struct mem_cgroup *memcg)
563 if (!memcg || mem_cgroup_is_root(memcg))
566 return &memcg->tcp_mem.cg_proto;
568 EXPORT_SYMBOL(tcp_proto_cgroup);
570 static void disarm_sock_keys(struct mem_cgroup *memcg)
572 if (!memcg_proto_activated(&memcg->tcp_mem.cg_proto))
574 static_key_slow_dec(&memcg_socket_limit_enabled);
577 static void disarm_sock_keys(struct mem_cgroup *memcg)
582 #ifdef CONFIG_MEMCG_KMEM
584 * This will be the memcg's index in each cache's ->memcg_params->memcg_caches.
585 * The main reason for not using cgroup id for this:
586 * this works better in sparse environments, where we have a lot of memcgs,
587 * but only a few kmem-limited. Or also, if we have, for instance, 200
588 * memcgs, and none but the 200th is kmem-limited, we'd have to have a
589 * 200 entry array for that.
591 * The current size of the caches array is stored in
592 * memcg_limited_groups_array_size. It will double each time we have to
595 static DEFINE_IDA(kmem_limited_groups);
596 int memcg_limited_groups_array_size;
599 * MIN_SIZE is different than 1, because we would like to avoid going through
600 * the alloc/free process all the time. In a small machine, 4 kmem-limited
601 * cgroups is a reasonable guess. In the future, it could be a parameter or
602 * tunable, but that is strictly not necessary.
604 * MAX_SIZE should be as large as the number of cgrp_ids. Ideally, we could get
605 * this constant directly from cgroup, but it is understandable that this is
606 * better kept as an internal representation in cgroup.c. In any case, the
607 * cgrp_id space is not getting any smaller, and we don't have to necessarily
608 * increase ours as well if it increases.
610 #define MEMCG_CACHES_MIN_SIZE 4
611 #define MEMCG_CACHES_MAX_SIZE MEM_CGROUP_ID_MAX
614 * A lot of the calls to the cache allocation functions are expected to be
615 * inlined by the compiler. Since the calls to memcg_kmem_get_cache are
616 * conditional to this static branch, we'll have to allow modules that does
617 * kmem_cache_alloc and the such to see this symbol as well
619 struct static_key memcg_kmem_enabled_key;
620 EXPORT_SYMBOL(memcg_kmem_enabled_key);
622 static void disarm_kmem_keys(struct mem_cgroup *memcg)
624 if (memcg_kmem_is_active(memcg)) {
625 static_key_slow_dec(&memcg_kmem_enabled_key);
626 ida_simple_remove(&kmem_limited_groups, memcg->kmemcg_id);
629 * This check can't live in kmem destruction function,
630 * since the charges will outlive the cgroup
632 WARN_ON(res_counter_read_u64(&memcg->kmem, RES_USAGE) != 0);
635 static void disarm_kmem_keys(struct mem_cgroup *memcg)
638 #endif /* CONFIG_MEMCG_KMEM */
640 static void disarm_static_keys(struct mem_cgroup *memcg)
642 disarm_sock_keys(memcg);
643 disarm_kmem_keys(memcg);
646 static void drain_all_stock_async(struct mem_cgroup *memcg);
648 static struct mem_cgroup_per_zone *
649 mem_cgroup_zoneinfo(struct mem_cgroup *memcg, int nid, int zid)
651 VM_BUG_ON((unsigned)nid >= nr_node_ids);
652 return &memcg->nodeinfo[nid]->zoneinfo[zid];
655 struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *memcg)
660 static struct mem_cgroup_per_zone *
661 page_cgroup_zoneinfo(struct mem_cgroup *memcg, struct page *page)
663 int nid = page_to_nid(page);
664 int zid = page_zonenum(page);
666 return mem_cgroup_zoneinfo(memcg, nid, zid);
670 * Implementation Note: reading percpu statistics for memcg.
672 * Both of vmstat[] and percpu_counter has threshold and do periodic
673 * synchronization to implement "quick" read. There are trade-off between
674 * reading cost and precision of value. Then, we may have a chance to implement
675 * a periodic synchronizion of counter in memcg's counter.
677 * But this _read() function is used for user interface now. The user accounts
678 * memory usage by memory cgroup and he _always_ requires exact value because
679 * he accounts memory. Even if we provide quick-and-fuzzy read, we always
680 * have to visit all online cpus and make sum. So, for now, unnecessary
681 * synchronization is not implemented. (just implemented for cpu hotplug)
683 * If there are kernel internal actions which can make use of some not-exact
684 * value, and reading all cpu value can be performance bottleneck in some
685 * common workload, threashold and synchonization as vmstat[] should be
688 static long mem_cgroup_read_stat(struct mem_cgroup *memcg,
689 enum mem_cgroup_stat_index idx)
695 for_each_online_cpu(cpu)
696 val += per_cpu(memcg->stat->count[idx], cpu);
697 #ifdef CONFIG_HOTPLUG_CPU
698 spin_lock(&memcg->pcp_counter_lock);
699 val += memcg->nocpu_base.count[idx];
700 spin_unlock(&memcg->pcp_counter_lock);
706 static void mem_cgroup_swap_statistics(struct mem_cgroup *memcg,
709 int val = (charge) ? 1 : -1;
710 this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_SWAP], val);
713 static unsigned long mem_cgroup_read_events(struct mem_cgroup *memcg,
714 enum mem_cgroup_events_index idx)
716 unsigned long val = 0;
719 for_each_online_cpu(cpu)
720 val += per_cpu(memcg->stat->events[idx], cpu);
721 #ifdef CONFIG_HOTPLUG_CPU
722 spin_lock(&memcg->pcp_counter_lock);
723 val += memcg->nocpu_base.events[idx];
724 spin_unlock(&memcg->pcp_counter_lock);
729 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
731 bool anon, int nr_pages)
736 * Here, RSS means 'mapped anon' and anon's SwapCache. Shmem/tmpfs is
737 * counted as CACHE even if it's on ANON LRU.
740 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS],
743 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_CACHE],
746 if (PageTransHuge(page))
747 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS_HUGE],
750 /* pagein of a big page is an event. So, ignore page size */
752 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGIN]);
754 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGOUT]);
755 nr_pages = -nr_pages; /* for event */
758 __this_cpu_add(memcg->stat->nr_page_events, nr_pages);
764 mem_cgroup_get_lru_size(struct lruvec *lruvec, enum lru_list lru)
766 struct mem_cgroup_per_zone *mz;
768 mz = container_of(lruvec, struct mem_cgroup_per_zone, lruvec);
769 return mz->lru_size[lru];
773 mem_cgroup_zone_nr_lru_pages(struct mem_cgroup *memcg, int nid, int zid,
774 unsigned int lru_mask)
776 struct mem_cgroup_per_zone *mz;
778 unsigned long ret = 0;
780 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
783 if (BIT(lru) & lru_mask)
784 ret += mz->lru_size[lru];
790 mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
791 int nid, unsigned int lru_mask)
796 for (zid = 0; zid < MAX_NR_ZONES; zid++)
797 total += mem_cgroup_zone_nr_lru_pages(memcg,
803 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
804 unsigned int lru_mask)
809 for_each_node_state(nid, N_MEMORY)
810 total += mem_cgroup_node_nr_lru_pages(memcg, nid, lru_mask);
814 static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
815 enum mem_cgroup_events_target target)
817 unsigned long val, next;
819 val = __this_cpu_read(memcg->stat->nr_page_events);
820 next = __this_cpu_read(memcg->stat->targets[target]);
821 /* from time_after() in jiffies.h */
822 if ((long)next - (long)val < 0) {
824 case MEM_CGROUP_TARGET_THRESH:
825 next = val + THRESHOLDS_EVENTS_TARGET;
827 case MEM_CGROUP_TARGET_SOFTLIMIT:
828 next = val + SOFTLIMIT_EVENTS_TARGET;
830 case MEM_CGROUP_TARGET_NUMAINFO:
831 next = val + NUMAINFO_EVENTS_TARGET;
836 __this_cpu_write(memcg->stat->targets[target], next);
843 * Called from rate-limited memcg_check_events when enough
844 * MEM_CGROUP_TARGET_SOFTLIMIT events are accumulated and it makes sure
845 * that all the parents up the hierarchy will be notified that this group
846 * is in excess or that it is not in excess anymore. mmecg->soft_contributed
847 * makes the transition a single action whenever the state flips from one to
850 static void mem_cgroup_update_soft_limit(struct mem_cgroup *memcg)
852 unsigned long long excess = res_counter_soft_limit_excess(&memcg->res);
853 struct mem_cgroup *parent = memcg;
856 spin_lock(&memcg->soft_lock);
858 if (!memcg->soft_contributed) {
860 memcg->soft_contributed = true;
863 if (memcg->soft_contributed) {
865 memcg->soft_contributed = false;
870 * Necessary to update all ancestors when hierarchy is used
871 * because their event counter is not touched.
872 * We track children even outside the hierarchy for the root
873 * cgroup because tree walk starting at root should visit
874 * all cgroups and we want to prevent from pointless tree
875 * walk if no children is below the limit.
877 while (delta && (parent = parent_mem_cgroup(parent)))
878 atomic_add(delta, &parent->children_in_excess);
879 if (memcg != root_mem_cgroup && !root_mem_cgroup->use_hierarchy)
880 atomic_add(delta, &root_mem_cgroup->children_in_excess);
881 spin_unlock(&memcg->soft_lock);
885 * Check events in order.
888 static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
891 /* threshold event is triggered in finer grain than soft limit */
892 if (unlikely(mem_cgroup_event_ratelimit(memcg,
893 MEM_CGROUP_TARGET_THRESH))) {
895 bool do_numainfo __maybe_unused;
897 do_softlimit = mem_cgroup_event_ratelimit(memcg,
898 MEM_CGROUP_TARGET_SOFTLIMIT);
900 do_numainfo = mem_cgroup_event_ratelimit(memcg,
901 MEM_CGROUP_TARGET_NUMAINFO);
905 mem_cgroup_threshold(memcg);
906 if (unlikely(do_softlimit))
907 mem_cgroup_update_soft_limit(memcg);
909 if (unlikely(do_numainfo))
910 atomic_inc(&memcg->numainfo_events);
916 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
919 * mm_update_next_owner() may clear mm->owner to NULL
920 * if it races with swapoff, page migration, etc.
921 * So this can be called with p == NULL.
926 return mem_cgroup_from_css(task_css(p, mem_cgroup_subsys_id));
929 struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
931 struct mem_cgroup *memcg = NULL;
936 * Because we have no locks, mm->owner's may be being moved to other
937 * cgroup. We use css_tryget() here even if this looks
938 * pessimistic (rather than adding locks here).
942 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
943 if (unlikely(!memcg))
945 } while (!css_tryget(&memcg->css));
950 static enum mem_cgroup_filter_t
951 mem_cgroup_filter(struct mem_cgroup *memcg, struct mem_cgroup *root,
952 mem_cgroup_iter_filter cond)
956 return cond(memcg, root);
960 * Returns a next (in a pre-order walk) alive memcg (with elevated css
961 * ref. count) or NULL if the whole root's subtree has been visited.
963 * helper function to be used by mem_cgroup_iter
965 static struct mem_cgroup *__mem_cgroup_iter_next(struct mem_cgroup *root,
966 struct mem_cgroup *last_visited, mem_cgroup_iter_filter cond)
968 struct cgroup_subsys_state *prev_css, *next_css;
970 prev_css = last_visited ? &last_visited->css : NULL;
972 next_css = css_next_descendant_pre(prev_css, &root->css);
975 * Even if we found a group we have to make sure it is
976 * alive. css && !memcg means that the groups should be
977 * skipped and we should continue the tree walk.
978 * last_visited css is safe to use because it is
979 * protected by css_get and the tree walk is rcu safe.
982 struct mem_cgroup *mem = mem_cgroup_from_css(next_css);
984 switch (mem_cgroup_filter(mem, root, cond)) {
992 * css_rightmost_descendant is not an optimal way to
993 * skip through a subtree (especially for imbalanced
994 * trees leaning to right) but that's what we have right
995 * now. More effective solution would be traversing
996 * right-up for first non-NULL without calling
997 * css_next_descendant_pre afterwards.
999 prev_css = css_rightmost_descendant(next_css);
1002 if (css_tryget(&mem->css))
1005 prev_css = next_css;
1015 static void mem_cgroup_iter_invalidate(struct mem_cgroup *root)
1018 * When a group in the hierarchy below root is destroyed, the
1019 * hierarchy iterator can no longer be trusted since it might
1020 * have pointed to the destroyed group. Invalidate it.
1022 atomic_inc(&root->dead_count);
1025 static struct mem_cgroup *
1026 mem_cgroup_iter_load(struct mem_cgroup_reclaim_iter *iter,
1027 struct mem_cgroup *root,
1030 struct mem_cgroup *position = NULL;
1032 * A cgroup destruction happens in two stages: offlining and
1033 * release. They are separated by a RCU grace period.
1035 * If the iterator is valid, we may still race with an
1036 * offlining. The RCU lock ensures the object won't be
1037 * released, tryget will fail if we lost the race.
1039 *sequence = atomic_read(&root->dead_count);
1040 if (iter->last_dead_count == *sequence) {
1042 position = iter->last_visited;
1043 if (position && !css_tryget(&position->css))
1049 static void mem_cgroup_iter_update(struct mem_cgroup_reclaim_iter *iter,
1050 struct mem_cgroup *last_visited,
1051 struct mem_cgroup *new_position,
1055 css_put(&last_visited->css);
1057 * We store the sequence count from the time @last_visited was
1058 * loaded successfully instead of rereading it here so that we
1059 * don't lose destruction events in between. We could have
1060 * raced with the destruction of @new_position after all.
1062 iter->last_visited = new_position;
1064 iter->last_dead_count = sequence;
1068 * mem_cgroup_iter - iterate over memory cgroup hierarchy
1069 * @root: hierarchy root
1070 * @prev: previously returned memcg, NULL on first invocation
1071 * @reclaim: cookie for shared reclaim walks, NULL for full walks
1072 * @cond: filter for visited nodes, NULL for no filter
1074 * Returns references to children of the hierarchy below @root, or
1075 * @root itself, or %NULL after a full round-trip.
1077 * Caller must pass the return value in @prev on subsequent
1078 * invocations for reference counting, or use mem_cgroup_iter_break()
1079 * to cancel a hierarchy walk before the round-trip is complete.
1081 * Reclaimers can specify a zone and a priority level in @reclaim to
1082 * divide up the memcgs in the hierarchy among all concurrent
1083 * reclaimers operating on the same zone and priority.
1085 struct mem_cgroup *mem_cgroup_iter_cond(struct mem_cgroup *root,
1086 struct mem_cgroup *prev,
1087 struct mem_cgroup_reclaim_cookie *reclaim,
1088 mem_cgroup_iter_filter cond)
1090 struct mem_cgroup *memcg = NULL;
1091 struct mem_cgroup *last_visited = NULL;
1093 if (mem_cgroup_disabled()) {
1094 /* first call must return non-NULL, second return NULL */
1095 return (struct mem_cgroup *)(unsigned long)!prev;
1099 root = root_mem_cgroup;
1101 if (prev && !reclaim)
1102 last_visited = prev;
1104 if (!root->use_hierarchy && root != root_mem_cgroup) {
1107 if (mem_cgroup_filter(root, root, cond) == VISIT)
1114 struct mem_cgroup_reclaim_iter *uninitialized_var(iter);
1115 int uninitialized_var(seq);
1118 int nid = zone_to_nid(reclaim->zone);
1119 int zid = zone_idx(reclaim->zone);
1120 struct mem_cgroup_per_zone *mz;
1122 mz = mem_cgroup_zoneinfo(root, nid, zid);
1123 iter = &mz->reclaim_iter[reclaim->priority];
1124 if (prev && reclaim->generation != iter->generation) {
1125 iter->last_visited = NULL;
1129 last_visited = mem_cgroup_iter_load(iter, root, &seq);
1132 memcg = __mem_cgroup_iter_next(root, last_visited, cond);
1135 mem_cgroup_iter_update(iter, last_visited, memcg, seq);
1139 else if (!prev && memcg)
1140 reclaim->generation = iter->generation;
1144 * We have finished the whole tree walk or no group has been
1145 * visited because filter told us to skip the root node.
1147 if (!memcg && (prev || (cond && !last_visited)))
1153 if (prev && prev != root)
1154 css_put(&prev->css);
1160 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1161 * @root: hierarchy root
1162 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1164 void mem_cgroup_iter_break(struct mem_cgroup *root,
1165 struct mem_cgroup *prev)
1168 root = root_mem_cgroup;
1169 if (prev && prev != root)
1170 css_put(&prev->css);
1174 * Iteration constructs for visiting all cgroups (under a tree). If
1175 * loops are exited prematurely (break), mem_cgroup_iter_break() must
1176 * be used for reference counting.
1178 #define for_each_mem_cgroup_tree(iter, root) \
1179 for (iter = mem_cgroup_iter(root, NULL, NULL); \
1181 iter = mem_cgroup_iter(root, iter, NULL))
1183 #define for_each_mem_cgroup(iter) \
1184 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
1186 iter = mem_cgroup_iter(NULL, iter, NULL))
1188 void __mem_cgroup_count_vm_event(struct mm_struct *mm, enum vm_event_item idx)
1190 struct mem_cgroup *memcg;
1193 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
1194 if (unlikely(!memcg))
1199 this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGFAULT]);
1202 this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGMAJFAULT]);
1210 EXPORT_SYMBOL(__mem_cgroup_count_vm_event);
1213 * mem_cgroup_zone_lruvec - get the lru list vector for a zone and memcg
1214 * @zone: zone of the wanted lruvec
1215 * @memcg: memcg of the wanted lruvec
1217 * Returns the lru list vector holding pages for the given @zone and
1218 * @mem. This can be the global zone lruvec, if the memory controller
1221 struct lruvec *mem_cgroup_zone_lruvec(struct zone *zone,
1222 struct mem_cgroup *memcg)
1224 struct mem_cgroup_per_zone *mz;
1225 struct lruvec *lruvec;
1227 if (mem_cgroup_disabled()) {
1228 lruvec = &zone->lruvec;
1232 mz = mem_cgroup_zoneinfo(memcg, zone_to_nid(zone), zone_idx(zone));
1233 lruvec = &mz->lruvec;
1236 * Since a node can be onlined after the mem_cgroup was created,
1237 * we have to be prepared to initialize lruvec->zone here;
1238 * and if offlined then reonlined, we need to reinitialize it.
1240 if (unlikely(lruvec->zone != zone))
1241 lruvec->zone = zone;
1246 * Following LRU functions are allowed to be used without PCG_LOCK.
1247 * Operations are called by routine of global LRU independently from memcg.
1248 * What we have to take care of here is validness of pc->mem_cgroup.
1250 * Changes to pc->mem_cgroup happens when
1253 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
1254 * It is added to LRU before charge.
1255 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
1256 * When moving account, the page is not on LRU. It's isolated.
1260 * mem_cgroup_page_lruvec - return lruvec for adding an lru page
1262 * @zone: zone of the page
1264 struct lruvec *mem_cgroup_page_lruvec(struct page *page, struct zone *zone)
1266 struct mem_cgroup_per_zone *mz;
1267 struct mem_cgroup *memcg;
1268 struct page_cgroup *pc;
1269 struct lruvec *lruvec;
1271 if (mem_cgroup_disabled()) {
1272 lruvec = &zone->lruvec;
1276 pc = lookup_page_cgroup(page);
1277 memcg = pc->mem_cgroup;
1280 * Surreptitiously switch any uncharged offlist page to root:
1281 * an uncharged page off lru does nothing to secure
1282 * its former mem_cgroup from sudden removal.
1284 * Our caller holds lru_lock, and PageCgroupUsed is updated
1285 * under page_cgroup lock: between them, they make all uses
1286 * of pc->mem_cgroup safe.
1288 if (!PageLRU(page) && !PageCgroupUsed(pc) && memcg != root_mem_cgroup)
1289 pc->mem_cgroup = memcg = root_mem_cgroup;
1291 mz = page_cgroup_zoneinfo(memcg, page);
1292 lruvec = &mz->lruvec;
1295 * Since a node can be onlined after the mem_cgroup was created,
1296 * we have to be prepared to initialize lruvec->zone here;
1297 * and if offlined then reonlined, we need to reinitialize it.
1299 if (unlikely(lruvec->zone != zone))
1300 lruvec->zone = zone;
1305 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1306 * @lruvec: mem_cgroup per zone lru vector
1307 * @lru: index of lru list the page is sitting on
1308 * @nr_pages: positive when adding or negative when removing
1310 * This function must be called when a page is added to or removed from an
1313 void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
1316 struct mem_cgroup_per_zone *mz;
1317 unsigned long *lru_size;
1319 if (mem_cgroup_disabled())
1322 mz = container_of(lruvec, struct mem_cgroup_per_zone, lruvec);
1323 lru_size = mz->lru_size + lru;
1324 *lru_size += nr_pages;
1325 VM_BUG_ON((long)(*lru_size) < 0);
1329 * Checks whether given mem is same or in the root_mem_cgroup's
1332 bool __mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
1333 struct mem_cgroup *memcg)
1335 if (root_memcg == memcg)
1337 if (!root_memcg->use_hierarchy || !memcg)
1339 return cgroup_is_descendant(memcg->css.cgroup, root_memcg->css.cgroup);
1342 static bool mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
1343 struct mem_cgroup *memcg)
1348 ret = __mem_cgroup_same_or_subtree(root_memcg, memcg);
1353 bool task_in_mem_cgroup(struct task_struct *task,
1354 const struct mem_cgroup *memcg)
1356 struct mem_cgroup *curr = NULL;
1357 struct task_struct *p;
1360 p = find_lock_task_mm(task);
1362 curr = try_get_mem_cgroup_from_mm(p->mm);
1366 * All threads may have already detached their mm's, but the oom
1367 * killer still needs to detect if they have already been oom
1368 * killed to prevent needlessly killing additional tasks.
1371 curr = mem_cgroup_from_task(task);
1373 css_get(&curr->css);
1379 * We should check use_hierarchy of "memcg" not "curr". Because checking
1380 * use_hierarchy of "curr" here make this function true if hierarchy is
1381 * enabled in "curr" and "curr" is a child of "memcg" in *cgroup*
1382 * hierarchy(even if use_hierarchy is disabled in "memcg").
1384 ret = mem_cgroup_same_or_subtree(memcg, curr);
1385 css_put(&curr->css);
1389 int mem_cgroup_inactive_anon_is_low(struct lruvec *lruvec)
1391 unsigned long inactive_ratio;
1392 unsigned long inactive;
1393 unsigned long active;
1396 inactive = mem_cgroup_get_lru_size(lruvec, LRU_INACTIVE_ANON);
1397 active = mem_cgroup_get_lru_size(lruvec, LRU_ACTIVE_ANON);
1399 gb = (inactive + active) >> (30 - PAGE_SHIFT);
1401 inactive_ratio = int_sqrt(10 * gb);
1405 return inactive * inactive_ratio < active;
1408 #define mem_cgroup_from_res_counter(counter, member) \
1409 container_of(counter, struct mem_cgroup, member)
1412 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1413 * @memcg: the memory cgroup
1415 * Returns the maximum amount of memory @mem can be charged with, in
1418 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1420 unsigned long long margin;
1422 margin = res_counter_margin(&memcg->res);
1423 if (do_swap_account)
1424 margin = min(margin, res_counter_margin(&memcg->memsw));
1425 return margin >> PAGE_SHIFT;
1428 int mem_cgroup_swappiness(struct mem_cgroup *memcg)
1431 if (!css_parent(&memcg->css))
1432 return vm_swappiness;
1434 return memcg->swappiness;
1438 * memcg->moving_account is used for checking possibility that some thread is
1439 * calling move_account(). When a thread on CPU-A starts moving pages under
1440 * a memcg, other threads should check memcg->moving_account under
1441 * rcu_read_lock(), like this:
1445 * memcg->moving_account+1 if (memcg->mocing_account)
1447 * synchronize_rcu() update something.
1452 /* for quick checking without looking up memcg */
1453 atomic_t memcg_moving __read_mostly;
1455 static void mem_cgroup_start_move(struct mem_cgroup *memcg)
1457 atomic_inc(&memcg_moving);
1458 atomic_inc(&memcg->moving_account);
1462 static void mem_cgroup_end_move(struct mem_cgroup *memcg)
1465 * Now, mem_cgroup_clear_mc() may call this function with NULL.
1466 * We check NULL in callee rather than caller.
1469 atomic_dec(&memcg_moving);
1470 atomic_dec(&memcg->moving_account);
1475 * 2 routines for checking "mem" is under move_account() or not.
1477 * mem_cgroup_stolen() - checking whether a cgroup is mc.from or not. This
1478 * is used for avoiding races in accounting. If true,
1479 * pc->mem_cgroup may be overwritten.
1481 * mem_cgroup_under_move() - checking a cgroup is mc.from or mc.to or
1482 * under hierarchy of moving cgroups. This is for
1483 * waiting at hith-memory prressure caused by "move".
1486 static bool mem_cgroup_stolen(struct mem_cgroup *memcg)
1488 VM_BUG_ON(!rcu_read_lock_held());
1489 return atomic_read(&memcg->moving_account) > 0;
1492 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1494 struct mem_cgroup *from;
1495 struct mem_cgroup *to;
1498 * Unlike task_move routines, we access mc.to, mc.from not under
1499 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1501 spin_lock(&mc.lock);
1507 ret = mem_cgroup_same_or_subtree(memcg, from)
1508 || mem_cgroup_same_or_subtree(memcg, to);
1510 spin_unlock(&mc.lock);
1514 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1516 if (mc.moving_task && current != mc.moving_task) {
1517 if (mem_cgroup_under_move(memcg)) {
1519 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1520 /* moving charge context might have finished. */
1523 finish_wait(&mc.waitq, &wait);
1531 * Take this lock when
1532 * - a code tries to modify page's memcg while it's USED.
1533 * - a code tries to modify page state accounting in a memcg.
1534 * see mem_cgroup_stolen(), too.
1536 static void move_lock_mem_cgroup(struct mem_cgroup *memcg,
1537 unsigned long *flags)
1539 spin_lock_irqsave(&memcg->move_lock, *flags);
1542 static void move_unlock_mem_cgroup(struct mem_cgroup *memcg,
1543 unsigned long *flags)
1545 spin_unlock_irqrestore(&memcg->move_lock, *flags);
1548 #define K(x) ((x) << (PAGE_SHIFT-10))
1550 * mem_cgroup_print_oom_info: Print OOM information relevant to memory controller.
1551 * @memcg: The memory cgroup that went over limit
1552 * @p: Task that is going to be killed
1554 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1557 void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1559 struct cgroup *task_cgrp;
1560 struct cgroup *mem_cgrp;
1562 * Need a buffer in BSS, can't rely on allocations. The code relies
1563 * on the assumption that OOM is serialized for memory controller.
1564 * If this assumption is broken, revisit this code.
1566 static char memcg_name[PATH_MAX];
1568 struct mem_cgroup *iter;
1576 mem_cgrp = memcg->css.cgroup;
1577 task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
1579 ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
1582 * Unfortunately, we are unable to convert to a useful name
1583 * But we'll still print out the usage information
1590 pr_info("Task in %s killed", memcg_name);
1593 ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
1601 * Continues from above, so we don't need an KERN_ level
1603 pr_cont(" as a result of limit of %s\n", memcg_name);
1606 pr_info("memory: usage %llukB, limit %llukB, failcnt %llu\n",
1607 res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
1608 res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
1609 res_counter_read_u64(&memcg->res, RES_FAILCNT));
1610 pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %llu\n",
1611 res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
1612 res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
1613 res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
1614 pr_info("kmem: usage %llukB, limit %llukB, failcnt %llu\n",
1615 res_counter_read_u64(&memcg->kmem, RES_USAGE) >> 10,
1616 res_counter_read_u64(&memcg->kmem, RES_LIMIT) >> 10,
1617 res_counter_read_u64(&memcg->kmem, RES_FAILCNT));
1619 for_each_mem_cgroup_tree(iter, memcg) {
1620 pr_info("Memory cgroup stats");
1623 ret = cgroup_path(iter->css.cgroup, memcg_name, PATH_MAX);
1625 pr_cont(" for %s", memcg_name);
1629 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
1630 if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
1632 pr_cont(" %s:%ldKB", mem_cgroup_stat_names[i],
1633 K(mem_cgroup_read_stat(iter, i)));
1636 for (i = 0; i < NR_LRU_LISTS; i++)
1637 pr_cont(" %s:%luKB", mem_cgroup_lru_names[i],
1638 K(mem_cgroup_nr_lru_pages(iter, BIT(i))));
1645 * This function returns the number of memcg under hierarchy tree. Returns
1646 * 1(self count) if no children.
1648 static int mem_cgroup_count_children(struct mem_cgroup *memcg)
1651 struct mem_cgroup *iter;
1653 for_each_mem_cgroup_tree(iter, memcg)
1659 * Return the memory (and swap, if configured) limit for a memcg.
1661 static u64 mem_cgroup_get_limit(struct mem_cgroup *memcg)
1665 limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
1668 * Do not consider swap space if we cannot swap due to swappiness
1670 if (mem_cgroup_swappiness(memcg)) {
1673 limit += total_swap_pages << PAGE_SHIFT;
1674 memsw = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
1677 * If memsw is finite and limits the amount of swap space
1678 * available to this memcg, return that limit.
1680 limit = min(limit, memsw);
1686 static void mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
1689 struct mem_cgroup *iter;
1690 unsigned long chosen_points = 0;
1691 unsigned long totalpages;
1692 unsigned int points = 0;
1693 struct task_struct *chosen = NULL;
1696 * If current has a pending SIGKILL or is exiting, then automatically
1697 * select it. The goal is to allow it to allocate so that it may
1698 * quickly exit and free its memory.
1700 if (fatal_signal_pending(current) || current->flags & PF_EXITING) {
1701 set_thread_flag(TIF_MEMDIE);
1705 check_panic_on_oom(CONSTRAINT_MEMCG, gfp_mask, order, NULL);
1706 totalpages = mem_cgroup_get_limit(memcg) >> PAGE_SHIFT ? : 1;
1707 for_each_mem_cgroup_tree(iter, memcg) {
1708 struct css_task_iter it;
1709 struct task_struct *task;
1711 css_task_iter_start(&iter->css, &it);
1712 while ((task = css_task_iter_next(&it))) {
1713 switch (oom_scan_process_thread(task, totalpages, NULL,
1715 case OOM_SCAN_SELECT:
1717 put_task_struct(chosen);
1719 chosen_points = ULONG_MAX;
1720 get_task_struct(chosen);
1722 case OOM_SCAN_CONTINUE:
1724 case OOM_SCAN_ABORT:
1725 css_task_iter_end(&it);
1726 mem_cgroup_iter_break(memcg, iter);
1728 put_task_struct(chosen);
1733 points = oom_badness(task, memcg, NULL, totalpages);
1734 if (points > chosen_points) {
1736 put_task_struct(chosen);
1738 chosen_points = points;
1739 get_task_struct(chosen);
1742 css_task_iter_end(&it);
1747 points = chosen_points * 1000 / totalpages;
1748 oom_kill_process(chosen, gfp_mask, order, points, totalpages, memcg,
1749 NULL, "Memory cgroup out of memory");
1752 static unsigned long mem_cgroup_reclaim(struct mem_cgroup *memcg,
1754 unsigned long flags)
1756 unsigned long total = 0;
1757 bool noswap = false;
1760 if (flags & MEM_CGROUP_RECLAIM_NOSWAP)
1762 if (!(flags & MEM_CGROUP_RECLAIM_SHRINK) && memcg->memsw_is_minimum)
1765 for (loop = 0; loop < MEM_CGROUP_MAX_RECLAIM_LOOPS; loop++) {
1767 drain_all_stock_async(memcg);
1768 total += try_to_free_mem_cgroup_pages(memcg, gfp_mask, noswap);
1770 * Allow limit shrinkers, which are triggered directly
1771 * by userspace, to catch signals and stop reclaim
1772 * after minimal progress, regardless of the margin.
1774 if (total && (flags & MEM_CGROUP_RECLAIM_SHRINK))
1776 if (mem_cgroup_margin(memcg))
1779 * If nothing was reclaimed after two attempts, there
1780 * may be no reclaimable pages in this hierarchy.
1788 #if MAX_NUMNODES > 1
1790 * test_mem_cgroup_node_reclaimable
1791 * @memcg: the target memcg
1792 * @nid: the node ID to be checked.
1793 * @noswap : specify true here if the user wants flle only information.
1795 * This function returns whether the specified memcg contains any
1796 * reclaimable pages on a node. Returns true if there are any reclaimable
1797 * pages in the node.
1799 static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *memcg,
1800 int nid, bool noswap)
1802 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_FILE))
1804 if (noswap || !total_swap_pages)
1806 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_ANON))
1813 * Always updating the nodemask is not very good - even if we have an empty
1814 * list or the wrong list here, we can start from some node and traverse all
1815 * nodes based on the zonelist. So update the list loosely once per 10 secs.
1818 static void mem_cgroup_may_update_nodemask(struct mem_cgroup *memcg)
1822 * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
1823 * pagein/pageout changes since the last update.
1825 if (!atomic_read(&memcg->numainfo_events))
1827 if (atomic_inc_return(&memcg->numainfo_updating) > 1)
1830 /* make a nodemask where this memcg uses memory from */
1831 memcg->scan_nodes = node_states[N_MEMORY];
1833 for_each_node_mask(nid, node_states[N_MEMORY]) {
1835 if (!test_mem_cgroup_node_reclaimable(memcg, nid, false))
1836 node_clear(nid, memcg->scan_nodes);
1839 atomic_set(&memcg->numainfo_events, 0);
1840 atomic_set(&memcg->numainfo_updating, 0);
1844 * Selecting a node where we start reclaim from. Because what we need is just
1845 * reducing usage counter, start from anywhere is O,K. Considering
1846 * memory reclaim from current node, there are pros. and cons.
1848 * Freeing memory from current node means freeing memory from a node which
1849 * we'll use or we've used. So, it may make LRU bad. And if several threads
1850 * hit limits, it will see a contention on a node. But freeing from remote
1851 * node means more costs for memory reclaim because of memory latency.
1853 * Now, we use round-robin. Better algorithm is welcomed.
1855 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1859 mem_cgroup_may_update_nodemask(memcg);
1860 node = memcg->last_scanned_node;
1862 node = next_node(node, memcg->scan_nodes);
1863 if (node == MAX_NUMNODES)
1864 node = first_node(memcg->scan_nodes);
1866 * We call this when we hit limit, not when pages are added to LRU.
1867 * No LRU may hold pages because all pages are UNEVICTABLE or
1868 * memcg is too small and all pages are not on LRU. In that case,
1869 * we use curret node.
1871 if (unlikely(node == MAX_NUMNODES))
1872 node = numa_node_id();
1874 memcg->last_scanned_node = node;
1879 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1887 * A group is eligible for the soft limit reclaim under the given root
1889 * a) it is over its soft limit
1890 * b) any parent up the hierarchy is over its soft limit
1892 * If the given group doesn't have any children over the limit then it
1893 * doesn't make any sense to iterate its subtree.
1895 enum mem_cgroup_filter_t
1896 mem_cgroup_soft_reclaim_eligible(struct mem_cgroup *memcg,
1897 struct mem_cgroup *root)
1899 struct mem_cgroup *parent;
1902 memcg = root_mem_cgroup;
1905 if (res_counter_soft_limit_excess(&memcg->res))
1909 * If any parent up to the root in the hierarchy is over its soft limit
1910 * then we have to obey and reclaim from this group as well.
1912 while ((parent = parent_mem_cgroup(parent))) {
1913 if (res_counter_soft_limit_excess(&parent->res))
1919 if (!atomic_read(&memcg->children_in_excess))
1924 static DEFINE_SPINLOCK(memcg_oom_lock);
1927 * Check OOM-Killer is already running under our hierarchy.
1928 * If someone is running, return false.
1930 static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
1932 struct mem_cgroup *iter, *failed = NULL;
1934 spin_lock(&memcg_oom_lock);
1936 for_each_mem_cgroup_tree(iter, memcg) {
1937 if (iter->oom_lock) {
1939 * this subtree of our hierarchy is already locked
1940 * so we cannot give a lock.
1943 mem_cgroup_iter_break(memcg, iter);
1946 iter->oom_lock = true;
1951 * OK, we failed to lock the whole subtree so we have
1952 * to clean up what we set up to the failing subtree
1954 for_each_mem_cgroup_tree(iter, memcg) {
1955 if (iter == failed) {
1956 mem_cgroup_iter_break(memcg, iter);
1959 iter->oom_lock = false;
1963 spin_unlock(&memcg_oom_lock);
1968 static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
1970 struct mem_cgroup *iter;
1972 spin_lock(&memcg_oom_lock);
1973 for_each_mem_cgroup_tree(iter, memcg)
1974 iter->oom_lock = false;
1975 spin_unlock(&memcg_oom_lock);
1978 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
1980 struct mem_cgroup *iter;
1982 for_each_mem_cgroup_tree(iter, memcg)
1983 atomic_inc(&iter->under_oom);
1986 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
1988 struct mem_cgroup *iter;
1991 * When a new child is created while the hierarchy is under oom,
1992 * mem_cgroup_oom_lock() may not be called. We have to use
1993 * atomic_add_unless() here.
1995 for_each_mem_cgroup_tree(iter, memcg)
1996 atomic_add_unless(&iter->under_oom, -1, 0);
1999 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
2001 struct oom_wait_info {
2002 struct mem_cgroup *memcg;
2006 static int memcg_oom_wake_function(wait_queue_t *wait,
2007 unsigned mode, int sync, void *arg)
2009 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
2010 struct mem_cgroup *oom_wait_memcg;
2011 struct oom_wait_info *oom_wait_info;
2013 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
2014 oom_wait_memcg = oom_wait_info->memcg;
2017 * Both of oom_wait_info->memcg and wake_memcg are stable under us.
2018 * Then we can use css_is_ancestor without taking care of RCU.
2020 if (!mem_cgroup_same_or_subtree(oom_wait_memcg, wake_memcg)
2021 && !mem_cgroup_same_or_subtree(wake_memcg, oom_wait_memcg))
2023 return autoremove_wake_function(wait, mode, sync, arg);
2026 static void memcg_wakeup_oom(struct mem_cgroup *memcg)
2028 atomic_inc(&memcg->oom_wakeups);
2029 /* for filtering, pass "memcg" as argument. */
2030 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
2033 static void memcg_oom_recover(struct mem_cgroup *memcg)
2035 if (memcg && atomic_read(&memcg->under_oom))
2036 memcg_wakeup_oom(memcg);
2040 * try to call OOM killer
2042 static void mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
2047 if (!current->memcg_oom.may_oom)
2050 current->memcg_oom.in_memcg_oom = 1;
2053 * As with any blocking lock, a contender needs to start
2054 * listening for wakeups before attempting the trylock,
2055 * otherwise it can miss the wakeup from the unlock and sleep
2056 * indefinitely. This is just open-coded because our locking
2057 * is so particular to memcg hierarchies.
2059 wakeups = atomic_read(&memcg->oom_wakeups);
2060 mem_cgroup_mark_under_oom(memcg);
2062 locked = mem_cgroup_oom_trylock(memcg);
2065 mem_cgroup_oom_notify(memcg);
2067 if (locked && !memcg->oom_kill_disable) {
2068 mem_cgroup_unmark_under_oom(memcg);
2069 mem_cgroup_out_of_memory(memcg, mask, order);
2070 mem_cgroup_oom_unlock(memcg);
2072 * There is no guarantee that an OOM-lock contender
2073 * sees the wakeups triggered by the OOM kill
2074 * uncharges. Wake any sleepers explicitely.
2076 memcg_oom_recover(memcg);
2079 * A system call can just return -ENOMEM, but if this
2080 * is a page fault and somebody else is handling the
2081 * OOM already, we need to sleep on the OOM waitqueue
2082 * for this memcg until the situation is resolved.
2083 * Which can take some time because it might be
2084 * handled by a userspace task.
2086 * However, this is the charge context, which means
2087 * that we may sit on a large call stack and hold
2088 * various filesystem locks, the mmap_sem etc. and we
2089 * don't want the OOM handler to deadlock on them
2090 * while we sit here and wait. Store the current OOM
2091 * context in the task_struct, then return -ENOMEM.
2092 * At the end of the page fault handler, with the
2093 * stack unwound, pagefault_out_of_memory() will check
2094 * back with us by calling
2095 * mem_cgroup_oom_synchronize(), possibly putting the
2098 current->memcg_oom.oom_locked = locked;
2099 current->memcg_oom.wakeups = wakeups;
2100 css_get(&memcg->css);
2101 current->memcg_oom.wait_on_memcg = memcg;
2106 * mem_cgroup_oom_synchronize - complete memcg OOM handling
2108 * This has to be called at the end of a page fault if the the memcg
2109 * OOM handler was enabled and the fault is returning %VM_FAULT_OOM.
2111 * Memcg supports userspace OOM handling, so failed allocations must
2112 * sleep on a waitqueue until the userspace task resolves the
2113 * situation. Sleeping directly in the charge context with all kinds
2114 * of locks held is not a good idea, instead we remember an OOM state
2115 * in the task and mem_cgroup_oom_synchronize() has to be called at
2116 * the end of the page fault to put the task to sleep and clean up the
2119 * Returns %true if an ongoing memcg OOM situation was detected and
2120 * finalized, %false otherwise.
2122 bool mem_cgroup_oom_synchronize(void)
2124 struct oom_wait_info owait;
2125 struct mem_cgroup *memcg;
2127 /* OOM is global, do not handle */
2128 if (!current->memcg_oom.in_memcg_oom)
2132 * We invoked the OOM killer but there is a chance that a kill
2133 * did not free up any charges. Everybody else might already
2134 * be sleeping, so restart the fault and keep the rampage
2135 * going until some charges are released.
2137 memcg = current->memcg_oom.wait_on_memcg;
2141 if (test_thread_flag(TIF_MEMDIE) || fatal_signal_pending(current))
2144 owait.memcg = memcg;
2145 owait.wait.flags = 0;
2146 owait.wait.func = memcg_oom_wake_function;
2147 owait.wait.private = current;
2148 INIT_LIST_HEAD(&owait.wait.task_list);
2150 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
2151 /* Only sleep if we didn't miss any wakeups since OOM */
2152 if (atomic_read(&memcg->oom_wakeups) == current->memcg_oom.wakeups)
2154 finish_wait(&memcg_oom_waitq, &owait.wait);
2156 mem_cgroup_unmark_under_oom(memcg);
2157 if (current->memcg_oom.oom_locked) {
2158 mem_cgroup_oom_unlock(memcg);
2160 * There is no guarantee that an OOM-lock contender
2161 * sees the wakeups triggered by the OOM kill
2162 * uncharges. Wake any sleepers explicitely.
2164 memcg_oom_recover(memcg);
2166 css_put(&memcg->css);
2167 current->memcg_oom.wait_on_memcg = NULL;
2169 current->memcg_oom.in_memcg_oom = 0;
2174 * Currently used to update mapped file statistics, but the routine can be
2175 * generalized to update other statistics as well.
2177 * Notes: Race condition
2179 * We usually use page_cgroup_lock() for accessing page_cgroup member but
2180 * it tends to be costly. But considering some conditions, we doesn't need
2181 * to do so _always_.
2183 * Considering "charge", lock_page_cgroup() is not required because all
2184 * file-stat operations happen after a page is attached to radix-tree. There
2185 * are no race with "charge".
2187 * Considering "uncharge", we know that memcg doesn't clear pc->mem_cgroup
2188 * at "uncharge" intentionally. So, we always see valid pc->mem_cgroup even
2189 * if there are race with "uncharge". Statistics itself is properly handled
2192 * Considering "move", this is an only case we see a race. To make the race
2193 * small, we check mm->moving_account and detect there are possibility of race
2194 * If there is, we take a lock.
2197 void __mem_cgroup_begin_update_page_stat(struct page *page,
2198 bool *locked, unsigned long *flags)
2200 struct mem_cgroup *memcg;
2201 struct page_cgroup *pc;
2203 pc = lookup_page_cgroup(page);
2205 memcg = pc->mem_cgroup;
2206 if (unlikely(!memcg || !PageCgroupUsed(pc)))
2209 * If this memory cgroup is not under account moving, we don't
2210 * need to take move_lock_mem_cgroup(). Because we already hold
2211 * rcu_read_lock(), any calls to move_account will be delayed until
2212 * rcu_read_unlock() if mem_cgroup_stolen() == true.
2214 if (!mem_cgroup_stolen(memcg))
2217 move_lock_mem_cgroup(memcg, flags);
2218 if (memcg != pc->mem_cgroup || !PageCgroupUsed(pc)) {
2219 move_unlock_mem_cgroup(memcg, flags);
2225 void __mem_cgroup_end_update_page_stat(struct page *page, unsigned long *flags)
2227 struct page_cgroup *pc = lookup_page_cgroup(page);
2230 * It's guaranteed that pc->mem_cgroup never changes while
2231 * lock is held because a routine modifies pc->mem_cgroup
2232 * should take move_lock_mem_cgroup().
2234 move_unlock_mem_cgroup(pc->mem_cgroup, flags);
2237 void mem_cgroup_update_page_stat(struct page *page,
2238 enum mem_cgroup_stat_index idx, int val)
2240 struct mem_cgroup *memcg;
2241 struct page_cgroup *pc = lookup_page_cgroup(page);
2242 unsigned long uninitialized_var(flags);
2244 if (mem_cgroup_disabled())
2247 VM_BUG_ON(!rcu_read_lock_held());
2248 memcg = pc->mem_cgroup;
2249 if (unlikely(!memcg || !PageCgroupUsed(pc)))
2252 this_cpu_add(memcg->stat->count[idx], val);
2256 * size of first charge trial. "32" comes from vmscan.c's magic value.
2257 * TODO: maybe necessary to use big numbers in big irons.
2259 #define CHARGE_BATCH 32U
2260 struct memcg_stock_pcp {
2261 struct mem_cgroup *cached; /* this never be root cgroup */
2262 unsigned int nr_pages;
2263 struct work_struct work;
2264 unsigned long flags;
2265 #define FLUSHING_CACHED_CHARGE 0
2267 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
2268 static DEFINE_MUTEX(percpu_charge_mutex);
2271 * consume_stock: Try to consume stocked charge on this cpu.
2272 * @memcg: memcg to consume from.
2273 * @nr_pages: how many pages to charge.
2275 * The charges will only happen if @memcg matches the current cpu's memcg
2276 * stock, and at least @nr_pages are available in that stock. Failure to
2277 * service an allocation will refill the stock.
2279 * returns true if successful, false otherwise.
2281 static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2283 struct memcg_stock_pcp *stock;
2286 if (nr_pages > CHARGE_BATCH)
2289 stock = &get_cpu_var(memcg_stock);
2290 if (memcg == stock->cached && stock->nr_pages >= nr_pages)
2291 stock->nr_pages -= nr_pages;
2292 else /* need to call res_counter_charge */
2294 put_cpu_var(memcg_stock);
2299 * Returns stocks cached in percpu to res_counter and reset cached information.
2301 static void drain_stock(struct memcg_stock_pcp *stock)
2303 struct mem_cgroup *old = stock->cached;
2305 if (stock->nr_pages) {
2306 unsigned long bytes = stock->nr_pages * PAGE_SIZE;
2308 res_counter_uncharge(&old->res, bytes);
2309 if (do_swap_account)
2310 res_counter_uncharge(&old->memsw, bytes);
2311 stock->nr_pages = 0;
2313 stock->cached = NULL;
2317 * This must be called under preempt disabled or must be called by
2318 * a thread which is pinned to local cpu.
2320 static void drain_local_stock(struct work_struct *dummy)
2322 struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
2324 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2327 static void __init memcg_stock_init(void)
2331 for_each_possible_cpu(cpu) {
2332 struct memcg_stock_pcp *stock =
2333 &per_cpu(memcg_stock, cpu);
2334 INIT_WORK(&stock->work, drain_local_stock);
2339 * Cache charges(val) which is from res_counter, to local per_cpu area.
2340 * This will be consumed by consume_stock() function, later.
2342 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2344 struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
2346 if (stock->cached != memcg) { /* reset if necessary */
2348 stock->cached = memcg;
2350 stock->nr_pages += nr_pages;
2351 put_cpu_var(memcg_stock);
2355 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2356 * of the hierarchy under it. sync flag says whether we should block
2357 * until the work is done.
2359 static void drain_all_stock(struct mem_cgroup *root_memcg, bool sync)
2363 /* Notify other cpus that system-wide "drain" is running */
2366 for_each_online_cpu(cpu) {
2367 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2368 struct mem_cgroup *memcg;
2370 memcg = stock->cached;
2371 if (!memcg || !stock->nr_pages)
2373 if (!mem_cgroup_same_or_subtree(root_memcg, memcg))
2375 if (!test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2377 drain_local_stock(&stock->work);
2379 schedule_work_on(cpu, &stock->work);
2387 for_each_online_cpu(cpu) {
2388 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2389 if (test_bit(FLUSHING_CACHED_CHARGE, &stock->flags))
2390 flush_work(&stock->work);
2397 * Tries to drain stocked charges in other cpus. This function is asynchronous
2398 * and just put a work per cpu for draining localy on each cpu. Caller can
2399 * expects some charges will be back to res_counter later but cannot wait for
2402 static void drain_all_stock_async(struct mem_cgroup *root_memcg)
2405 * If someone calls draining, avoid adding more kworker runs.
2407 if (!mutex_trylock(&percpu_charge_mutex))
2409 drain_all_stock(root_memcg, false);
2410 mutex_unlock(&percpu_charge_mutex);
2413 /* This is a synchronous drain interface. */
2414 static void drain_all_stock_sync(struct mem_cgroup *root_memcg)
2416 /* called when force_empty is called */
2417 mutex_lock(&percpu_charge_mutex);
2418 drain_all_stock(root_memcg, true);
2419 mutex_unlock(&percpu_charge_mutex);
2423 * This function drains percpu counter value from DEAD cpu and
2424 * move it to local cpu. Note that this function can be preempted.
2426 static void mem_cgroup_drain_pcp_counter(struct mem_cgroup *memcg, int cpu)
2430 spin_lock(&memcg->pcp_counter_lock);
2431 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
2432 long x = per_cpu(memcg->stat->count[i], cpu);
2434 per_cpu(memcg->stat->count[i], cpu) = 0;
2435 memcg->nocpu_base.count[i] += x;
2437 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
2438 unsigned long x = per_cpu(memcg->stat->events[i], cpu);
2440 per_cpu(memcg->stat->events[i], cpu) = 0;
2441 memcg->nocpu_base.events[i] += x;
2443 spin_unlock(&memcg->pcp_counter_lock);
2446 static int memcg_cpu_hotplug_callback(struct notifier_block *nb,
2447 unsigned long action,
2450 int cpu = (unsigned long)hcpu;
2451 struct memcg_stock_pcp *stock;
2452 struct mem_cgroup *iter;
2454 if (action == CPU_ONLINE)
2457 if (action != CPU_DEAD && action != CPU_DEAD_FROZEN)
2460 for_each_mem_cgroup(iter)
2461 mem_cgroup_drain_pcp_counter(iter, cpu);
2463 stock = &per_cpu(memcg_stock, cpu);
2469 /* See __mem_cgroup_try_charge() for details */
2471 CHARGE_OK, /* success */
2472 CHARGE_RETRY, /* need to retry but retry is not bad */
2473 CHARGE_NOMEM, /* we can't do more. return -ENOMEM */
2474 CHARGE_WOULDBLOCK, /* GFP_WAIT wasn't set and no enough res. */
2477 static int mem_cgroup_do_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2478 unsigned int nr_pages, unsigned int min_pages,
2481 unsigned long csize = nr_pages * PAGE_SIZE;
2482 struct mem_cgroup *mem_over_limit;
2483 struct res_counter *fail_res;
2484 unsigned long flags = 0;
2487 ret = res_counter_charge(&memcg->res, csize, &fail_res);
2490 if (!do_swap_account)
2492 ret = res_counter_charge(&memcg->memsw, csize, &fail_res);
2496 res_counter_uncharge(&memcg->res, csize);
2497 mem_over_limit = mem_cgroup_from_res_counter(fail_res, memsw);
2498 flags |= MEM_CGROUP_RECLAIM_NOSWAP;
2500 mem_over_limit = mem_cgroup_from_res_counter(fail_res, res);
2502 * Never reclaim on behalf of optional batching, retry with a
2503 * single page instead.
2505 if (nr_pages > min_pages)
2506 return CHARGE_RETRY;
2508 if (!(gfp_mask & __GFP_WAIT))
2509 return CHARGE_WOULDBLOCK;
2511 if (gfp_mask & __GFP_NORETRY)
2512 return CHARGE_NOMEM;
2514 ret = mem_cgroup_reclaim(mem_over_limit, gfp_mask, flags);
2515 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2516 return CHARGE_RETRY;
2518 * Even though the limit is exceeded at this point, reclaim
2519 * may have been able to free some pages. Retry the charge
2520 * before killing the task.
2522 * Only for regular pages, though: huge pages are rather
2523 * unlikely to succeed so close to the limit, and we fall back
2524 * to regular pages anyway in case of failure.
2526 if (nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER) && ret)
2527 return CHARGE_RETRY;
2530 * At task move, charge accounts can be doubly counted. So, it's
2531 * better to wait until the end of task_move if something is going on.
2533 if (mem_cgroup_wait_acct_move(mem_over_limit))
2534 return CHARGE_RETRY;
2537 mem_cgroup_oom(mem_over_limit, gfp_mask, get_order(csize));
2539 return CHARGE_NOMEM;
2543 * __mem_cgroup_try_charge() does
2544 * 1. detect memcg to be charged against from passed *mm and *ptr,
2545 * 2. update res_counter
2546 * 3. call memory reclaim if necessary.
2548 * In some special case, if the task is fatal, fatal_signal_pending() or
2549 * has TIF_MEMDIE, this function returns -EINTR while writing root_mem_cgroup
2550 * to *ptr. There are two reasons for this. 1: fatal threads should quit as soon
2551 * as possible without any hazards. 2: all pages should have a valid
2552 * pc->mem_cgroup. If mm is NULL and the caller doesn't pass a valid memcg
2553 * pointer, that is treated as a charge to root_mem_cgroup.
2555 * So __mem_cgroup_try_charge() will return
2556 * 0 ... on success, filling *ptr with a valid memcg pointer.
2557 * -ENOMEM ... charge failure because of resource limits.
2558 * -EINTR ... if thread is fatal. *ptr is filled with root_mem_cgroup.
2560 * Unlike the exported interface, an "oom" parameter is added. if oom==true,
2561 * the oom-killer can be invoked.
2563 static int __mem_cgroup_try_charge(struct mm_struct *mm,
2565 unsigned int nr_pages,
2566 struct mem_cgroup **ptr,
2569 unsigned int batch = max(CHARGE_BATCH, nr_pages);
2570 int nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2571 struct mem_cgroup *memcg = NULL;
2575 * Unlike gloval-vm's OOM-kill, we're not in memory shortage
2576 * in system level. So, allow to go ahead dying process in addition to
2579 if (unlikely(test_thread_flag(TIF_MEMDIE)
2580 || fatal_signal_pending(current)))
2584 * We always charge the cgroup the mm_struct belongs to.
2585 * The mm_struct's mem_cgroup changes on task migration if the
2586 * thread group leader migrates. It's possible that mm is not
2587 * set, if so charge the root memcg (happens for pagecache usage).
2590 *ptr = root_mem_cgroup;
2592 if (*ptr) { /* css should be a valid one */
2594 if (mem_cgroup_is_root(memcg))
2596 if (consume_stock(memcg, nr_pages))
2598 css_get(&memcg->css);
2600 struct task_struct *p;
2603 p = rcu_dereference(mm->owner);
2605 * Because we don't have task_lock(), "p" can exit.
2606 * In that case, "memcg" can point to root or p can be NULL with
2607 * race with swapoff. Then, we have small risk of mis-accouning.
2608 * But such kind of mis-account by race always happens because
2609 * we don't have cgroup_mutex(). It's overkill and we allo that
2611 * (*) swapoff at el will charge against mm-struct not against
2612 * task-struct. So, mm->owner can be NULL.
2614 memcg = mem_cgroup_from_task(p);
2616 memcg = root_mem_cgroup;
2617 if (mem_cgroup_is_root(memcg)) {
2621 if (consume_stock(memcg, nr_pages)) {
2623 * It seems dagerous to access memcg without css_get().
2624 * But considering how consume_stok works, it's not
2625 * necessary. If consume_stock success, some charges
2626 * from this memcg are cached on this cpu. So, we
2627 * don't need to call css_get()/css_tryget() before
2628 * calling consume_stock().
2633 /* after here, we may be blocked. we need to get refcnt */
2634 if (!css_tryget(&memcg->css)) {
2642 bool invoke_oom = oom && !nr_oom_retries;
2644 /* If killed, bypass charge */
2645 if (fatal_signal_pending(current)) {
2646 css_put(&memcg->css);
2650 ret = mem_cgroup_do_charge(memcg, gfp_mask, batch,
2651 nr_pages, invoke_oom);
2655 case CHARGE_RETRY: /* not in OOM situation but retry */
2657 css_put(&memcg->css);
2660 case CHARGE_WOULDBLOCK: /* !__GFP_WAIT */
2661 css_put(&memcg->css);
2663 case CHARGE_NOMEM: /* OOM routine works */
2664 if (!oom || invoke_oom) {
2665 css_put(&memcg->css);
2671 } while (ret != CHARGE_OK);
2673 if (batch > nr_pages)
2674 refill_stock(memcg, batch - nr_pages);
2675 css_put(&memcg->css);
2683 *ptr = root_mem_cgroup;
2688 * Somemtimes we have to undo a charge we got by try_charge().
2689 * This function is for that and do uncharge, put css's refcnt.
2690 * gotten by try_charge().
2692 static void __mem_cgroup_cancel_charge(struct mem_cgroup *memcg,
2693 unsigned int nr_pages)
2695 if (!mem_cgroup_is_root(memcg)) {
2696 unsigned long bytes = nr_pages * PAGE_SIZE;
2698 res_counter_uncharge(&memcg->res, bytes);
2699 if (do_swap_account)
2700 res_counter_uncharge(&memcg->memsw, bytes);
2705 * Cancel chrages in this cgroup....doesn't propagate to parent cgroup.
2706 * This is useful when moving usage to parent cgroup.
2708 static void __mem_cgroup_cancel_local_charge(struct mem_cgroup *memcg,
2709 unsigned int nr_pages)
2711 unsigned long bytes = nr_pages * PAGE_SIZE;
2713 if (mem_cgroup_is_root(memcg))
2716 res_counter_uncharge_until(&memcg->res, memcg->res.parent, bytes);
2717 if (do_swap_account)
2718 res_counter_uncharge_until(&memcg->memsw,
2719 memcg->memsw.parent, bytes);
2723 * A helper function to get mem_cgroup from ID. must be called under
2724 * rcu_read_lock(). The caller is responsible for calling css_tryget if
2725 * the mem_cgroup is used for charging. (dropping refcnt from swap can be
2726 * called against removed memcg.)
2728 static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
2730 /* ID 0 is unused ID */
2733 return mem_cgroup_from_id(id);
2736 struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
2738 struct mem_cgroup *memcg = NULL;
2739 struct page_cgroup *pc;
2743 VM_BUG_ON(!PageLocked(page));
2745 pc = lookup_page_cgroup(page);
2746 lock_page_cgroup(pc);
2747 if (PageCgroupUsed(pc)) {
2748 memcg = pc->mem_cgroup;
2749 if (memcg && !css_tryget(&memcg->css))
2751 } else if (PageSwapCache(page)) {
2752 ent.val = page_private(page);
2753 id = lookup_swap_cgroup_id(ent);
2755 memcg = mem_cgroup_lookup(id);
2756 if (memcg && !css_tryget(&memcg->css))
2760 unlock_page_cgroup(pc);
2764 static void __mem_cgroup_commit_charge(struct mem_cgroup *memcg,
2766 unsigned int nr_pages,
2767 enum charge_type ctype,
2770 struct page_cgroup *pc = lookup_page_cgroup(page);
2771 struct zone *uninitialized_var(zone);
2772 struct lruvec *lruvec;
2773 bool was_on_lru = false;
2776 lock_page_cgroup(pc);
2777 VM_BUG_ON(PageCgroupUsed(pc));
2779 * we don't need page_cgroup_lock about tail pages, becase they are not
2780 * accessed by any other context at this point.
2784 * In some cases, SwapCache and FUSE(splice_buf->radixtree), the page
2785 * may already be on some other mem_cgroup's LRU. Take care of it.
2788 zone = page_zone(page);
2789 spin_lock_irq(&zone->lru_lock);
2790 if (PageLRU(page)) {
2791 lruvec = mem_cgroup_zone_lruvec(zone, pc->mem_cgroup);
2793 del_page_from_lru_list(page, lruvec, page_lru(page));
2798 pc->mem_cgroup = memcg;
2800 * We access a page_cgroup asynchronously without lock_page_cgroup().
2801 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
2802 * is accessed after testing USED bit. To make pc->mem_cgroup visible
2803 * before USED bit, we need memory barrier here.
2804 * See mem_cgroup_add_lru_list(), etc.
2807 SetPageCgroupUsed(pc);
2811 lruvec = mem_cgroup_zone_lruvec(zone, pc->mem_cgroup);
2812 VM_BUG_ON(PageLRU(page));
2814 add_page_to_lru_list(page, lruvec, page_lru(page));
2816 spin_unlock_irq(&zone->lru_lock);
2819 if (ctype == MEM_CGROUP_CHARGE_TYPE_ANON)
2824 mem_cgroup_charge_statistics(memcg, page, anon, nr_pages);
2825 unlock_page_cgroup(pc);
2828 * "charge_statistics" updated event counter.
2830 memcg_check_events(memcg, page);
2833 static DEFINE_MUTEX(set_limit_mutex);
2835 #ifdef CONFIG_MEMCG_KMEM
2836 static inline bool memcg_can_account_kmem(struct mem_cgroup *memcg)
2838 return !mem_cgroup_disabled() && !mem_cgroup_is_root(memcg) &&
2839 (memcg->kmem_account_flags & KMEM_ACCOUNTED_MASK);
2843 * This is a bit cumbersome, but it is rarely used and avoids a backpointer
2844 * in the memcg_cache_params struct.
2846 static struct kmem_cache *memcg_params_to_cache(struct memcg_cache_params *p)
2848 struct kmem_cache *cachep;
2850 VM_BUG_ON(p->is_root_cache);
2851 cachep = p->root_cache;
2852 return cachep->memcg_params->memcg_caches[memcg_cache_id(p->memcg)];
2855 #ifdef CONFIG_SLABINFO
2856 static int mem_cgroup_slabinfo_read(struct cgroup_subsys_state *css,
2857 struct cftype *cft, struct seq_file *m)
2859 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
2860 struct memcg_cache_params *params;
2862 if (!memcg_can_account_kmem(memcg))
2865 print_slabinfo_header(m);
2867 mutex_lock(&memcg->slab_caches_mutex);
2868 list_for_each_entry(params, &memcg->memcg_slab_caches, list)
2869 cache_show(memcg_params_to_cache(params), m);
2870 mutex_unlock(&memcg->slab_caches_mutex);
2876 static int memcg_charge_kmem(struct mem_cgroup *memcg, gfp_t gfp, u64 size)
2878 struct res_counter *fail_res;
2879 struct mem_cgroup *_memcg;
2883 ret = res_counter_charge(&memcg->kmem, size, &fail_res);
2888 * Conditions under which we can wait for the oom_killer. Those are
2889 * the same conditions tested by the core page allocator
2891 may_oom = (gfp & __GFP_FS) && !(gfp & __GFP_NORETRY);
2894 ret = __mem_cgroup_try_charge(NULL, gfp, size >> PAGE_SHIFT,
2897 if (ret == -EINTR) {
2899 * __mem_cgroup_try_charge() chosed to bypass to root due to
2900 * OOM kill or fatal signal. Since our only options are to
2901 * either fail the allocation or charge it to this cgroup, do
2902 * it as a temporary condition. But we can't fail. From a
2903 * kmem/slab perspective, the cache has already been selected,
2904 * by mem_cgroup_kmem_get_cache(), so it is too late to change
2907 * This condition will only trigger if the task entered
2908 * memcg_charge_kmem in a sane state, but was OOM-killed during
2909 * __mem_cgroup_try_charge() above. Tasks that were already
2910 * dying when the allocation triggers should have been already
2911 * directed to the root cgroup in memcontrol.h
2913 res_counter_charge_nofail(&memcg->res, size, &fail_res);
2914 if (do_swap_account)
2915 res_counter_charge_nofail(&memcg->memsw, size,
2919 res_counter_uncharge(&memcg->kmem, size);
2924 static void memcg_uncharge_kmem(struct mem_cgroup *memcg, u64 size)
2926 res_counter_uncharge(&memcg->res, size);
2927 if (do_swap_account)
2928 res_counter_uncharge(&memcg->memsw, size);
2931 if (res_counter_uncharge(&memcg->kmem, size))
2935 * Releases a reference taken in kmem_cgroup_css_offline in case
2936 * this last uncharge is racing with the offlining code or it is
2937 * outliving the memcg existence.
2939 * The memory barrier imposed by test&clear is paired with the
2940 * explicit one in memcg_kmem_mark_dead().
2942 if (memcg_kmem_test_and_clear_dead(memcg))
2943 css_put(&memcg->css);
2946 void memcg_cache_list_add(struct mem_cgroup *memcg, struct kmem_cache *cachep)
2951 mutex_lock(&memcg->slab_caches_mutex);
2952 list_add(&cachep->memcg_params->list, &memcg->memcg_slab_caches);
2953 mutex_unlock(&memcg->slab_caches_mutex);
2957 * helper for acessing a memcg's index. It will be used as an index in the
2958 * child cache array in kmem_cache, and also to derive its name. This function
2959 * will return -1 when this is not a kmem-limited memcg.
2961 int memcg_cache_id(struct mem_cgroup *memcg)
2963 return memcg ? memcg->kmemcg_id : -1;
2967 * This ends up being protected by the set_limit mutex, during normal
2968 * operation, because that is its main call site.
2970 * But when we create a new cache, we can call this as well if its parent
2971 * is kmem-limited. That will have to hold set_limit_mutex as well.
2973 int memcg_update_cache_sizes(struct mem_cgroup *memcg)
2977 num = ida_simple_get(&kmem_limited_groups,
2978 0, MEMCG_CACHES_MAX_SIZE, GFP_KERNEL);
2982 * After this point, kmem_accounted (that we test atomically in
2983 * the beginning of this conditional), is no longer 0. This
2984 * guarantees only one process will set the following boolean
2985 * to true. We don't need test_and_set because we're protected
2986 * by the set_limit_mutex anyway.
2988 memcg_kmem_set_activated(memcg);
2990 ret = memcg_update_all_caches(num+1);
2992 ida_simple_remove(&kmem_limited_groups, num);
2993 memcg_kmem_clear_activated(memcg);
2997 memcg->kmemcg_id = num;
2998 INIT_LIST_HEAD(&memcg->memcg_slab_caches);
2999 mutex_init(&memcg->slab_caches_mutex);
3003 static size_t memcg_caches_array_size(int num_groups)
3006 if (num_groups <= 0)
3009 size = 2 * num_groups;
3010 if (size < MEMCG_CACHES_MIN_SIZE)
3011 size = MEMCG_CACHES_MIN_SIZE;
3012 else if (size > MEMCG_CACHES_MAX_SIZE)
3013 size = MEMCG_CACHES_MAX_SIZE;
3019 * We should update the current array size iff all caches updates succeed. This
3020 * can only be done from the slab side. The slab mutex needs to be held when
3023 void memcg_update_array_size(int num)
3025 if (num > memcg_limited_groups_array_size)
3026 memcg_limited_groups_array_size = memcg_caches_array_size(num);
3029 static void kmem_cache_destroy_work_func(struct work_struct *w);
3031 int memcg_update_cache_size(struct kmem_cache *s, int num_groups)
3033 struct memcg_cache_params *cur_params = s->memcg_params;
3035 VM_BUG_ON(s->memcg_params && !s->memcg_params->is_root_cache);
3037 if (num_groups > memcg_limited_groups_array_size) {
3039 ssize_t size = memcg_caches_array_size(num_groups);
3041 size *= sizeof(void *);
3042 size += offsetof(struct memcg_cache_params, memcg_caches);
3044 s->memcg_params = kzalloc(size, GFP_KERNEL);
3045 if (!s->memcg_params) {
3046 s->memcg_params = cur_params;
3050 s->memcg_params->is_root_cache = true;
3053 * There is the chance it will be bigger than
3054 * memcg_limited_groups_array_size, if we failed an allocation
3055 * in a cache, in which case all caches updated before it, will
3056 * have a bigger array.
3058 * But if that is the case, the data after
3059 * memcg_limited_groups_array_size is certainly unused
3061 for (i = 0; i < memcg_limited_groups_array_size; i++) {
3062 if (!cur_params->memcg_caches[i])
3064 s->memcg_params->memcg_caches[i] =
3065 cur_params->memcg_caches[i];
3069 * Ideally, we would wait until all caches succeed, and only
3070 * then free the old one. But this is not worth the extra
3071 * pointer per-cache we'd have to have for this.
3073 * It is not a big deal if some caches are left with a size
3074 * bigger than the others. And all updates will reset this
3082 int memcg_register_cache(struct mem_cgroup *memcg, struct kmem_cache *s,
3083 struct kmem_cache *root_cache)
3087 if (!memcg_kmem_enabled())
3091 size = offsetof(struct memcg_cache_params, memcg_caches);
3092 size += memcg_limited_groups_array_size * sizeof(void *);
3094 size = sizeof(struct memcg_cache_params);
3096 s->memcg_params = kzalloc(size, GFP_KERNEL);
3097 if (!s->memcg_params)
3101 s->memcg_params->memcg = memcg;
3102 s->memcg_params->root_cache = root_cache;
3103 INIT_WORK(&s->memcg_params->destroy,
3104 kmem_cache_destroy_work_func);
3106 s->memcg_params->is_root_cache = true;
3111 void memcg_release_cache(struct kmem_cache *s)
3113 struct kmem_cache *root;
3114 struct mem_cgroup *memcg;
3118 * This happens, for instance, when a root cache goes away before we
3121 if (!s->memcg_params)
3124 if (s->memcg_params->is_root_cache)
3127 memcg = s->memcg_params->memcg;
3128 id = memcg_cache_id(memcg);
3130 root = s->memcg_params->root_cache;
3131 root->memcg_params->memcg_caches[id] = NULL;
3133 mutex_lock(&memcg->slab_caches_mutex);
3134 list_del(&s->memcg_params->list);
3135 mutex_unlock(&memcg->slab_caches_mutex);
3137 css_put(&memcg->css);
3139 kfree(s->memcg_params);
3143 * During the creation a new cache, we need to disable our accounting mechanism
3144 * altogether. This is true even if we are not creating, but rather just
3145 * enqueing new caches to be created.
3147 * This is because that process will trigger allocations; some visible, like
3148 * explicit kmallocs to auxiliary data structures, name strings and internal
3149 * cache structures; some well concealed, like INIT_WORK() that can allocate
3150 * objects during debug.
3152 * If any allocation happens during memcg_kmem_get_cache, we will recurse back
3153 * to it. This may not be a bounded recursion: since the first cache creation
3154 * failed to complete (waiting on the allocation), we'll just try to create the
3155 * cache again, failing at the same point.
3157 * memcg_kmem_get_cache is prepared to abort after seeing a positive count of
3158 * memcg_kmem_skip_account. So we enclose anything that might allocate memory
3159 * inside the following two functions.
3161 static inline void memcg_stop_kmem_account(void)
3163 VM_BUG_ON(!current->mm);
3164 current->memcg_kmem_skip_account++;
3167 static inline void memcg_resume_kmem_account(void)
3169 VM_BUG_ON(!current->mm);
3170 current->memcg_kmem_skip_account--;
3173 static void kmem_cache_destroy_work_func(struct work_struct *w)
3175 struct kmem_cache *cachep;
3176 struct memcg_cache_params *p;
3178 p = container_of(w, struct memcg_cache_params, destroy);
3180 cachep = memcg_params_to_cache(p);
3183 * If we get down to 0 after shrink, we could delete right away.
3184 * However, memcg_release_pages() already puts us back in the workqueue
3185 * in that case. If we proceed deleting, we'll get a dangling
3186 * reference, and removing the object from the workqueue in that case
3187 * is unnecessary complication. We are not a fast path.
3189 * Note that this case is fundamentally different from racing with
3190 * shrink_slab(): if memcg_cgroup_destroy_cache() is called in
3191 * kmem_cache_shrink, not only we would be reinserting a dead cache
3192 * into the queue, but doing so from inside the worker racing to
3195 * So if we aren't down to zero, we'll just schedule a worker and try
3198 if (atomic_read(&cachep->memcg_params->nr_pages) != 0) {
3199 kmem_cache_shrink(cachep);
3200 if (atomic_read(&cachep->memcg_params->nr_pages) == 0)
3203 kmem_cache_destroy(cachep);
3206 void mem_cgroup_destroy_cache(struct kmem_cache *cachep)
3208 if (!cachep->memcg_params->dead)
3212 * There are many ways in which we can get here.
3214 * We can get to a memory-pressure situation while the delayed work is
3215 * still pending to run. The vmscan shrinkers can then release all
3216 * cache memory and get us to destruction. If this is the case, we'll
3217 * be executed twice, which is a bug (the second time will execute over
3218 * bogus data). In this case, cancelling the work should be fine.
3220 * But we can also get here from the worker itself, if
3221 * kmem_cache_shrink is enough to shake all the remaining objects and
3222 * get the page count to 0. In this case, we'll deadlock if we try to
3223 * cancel the work (the worker runs with an internal lock held, which
3224 * is the same lock we would hold for cancel_work_sync().)
3226 * Since we can't possibly know who got us here, just refrain from
3227 * running if there is already work pending
3229 if (work_pending(&cachep->memcg_params->destroy))
3232 * We have to defer the actual destroying to a workqueue, because
3233 * we might currently be in a context that cannot sleep.
3235 schedule_work(&cachep->memcg_params->destroy);
3239 * This lock protects updaters, not readers. We want readers to be as fast as
3240 * they can, and they will either see NULL or a valid cache value. Our model
3241 * allow them to see NULL, in which case the root memcg will be selected.
3243 * We need this lock because multiple allocations to the same cache from a non
3244 * will span more than one worker. Only one of them can create the cache.
3246 static DEFINE_MUTEX(memcg_cache_mutex);
3249 * Called with memcg_cache_mutex held
3251 static struct kmem_cache *kmem_cache_dup(struct mem_cgroup *memcg,
3252 struct kmem_cache *s)
3254 struct kmem_cache *new;
3255 static char *tmp_name = NULL;
3257 lockdep_assert_held(&memcg_cache_mutex);
3260 * kmem_cache_create_memcg duplicates the given name and
3261 * cgroup_name for this name requires RCU context.
3262 * This static temporary buffer is used to prevent from
3263 * pointless shortliving allocation.
3266 tmp_name = kmalloc(PATH_MAX, GFP_KERNEL);
3272 snprintf(tmp_name, PATH_MAX, "%s(%d:%s)", s->name,
3273 memcg_cache_id(memcg), cgroup_name(memcg->css.cgroup));
3276 new = kmem_cache_create_memcg(memcg, tmp_name, s->object_size, s->align,
3277 (s->flags & ~SLAB_PANIC), s->ctor, s);
3280 new->allocflags |= __GFP_KMEMCG;
3285 static struct kmem_cache *memcg_create_kmem_cache(struct mem_cgroup *memcg,
3286 struct kmem_cache *cachep)
3288 struct kmem_cache *new_cachep;
3291 BUG_ON(!memcg_can_account_kmem(memcg));
3293 idx = memcg_cache_id(memcg);
3295 mutex_lock(&memcg_cache_mutex);
3296 new_cachep = cachep->memcg_params->memcg_caches[idx];
3298 css_put(&memcg->css);
3302 new_cachep = kmem_cache_dup(memcg, cachep);
3303 if (new_cachep == NULL) {
3304 new_cachep = cachep;
3305 css_put(&memcg->css);
3309 atomic_set(&new_cachep->memcg_params->nr_pages , 0);
3311 cachep->memcg_params->memcg_caches[idx] = new_cachep;
3313 * the readers won't lock, make sure everybody sees the updated value,
3314 * so they won't put stuff in the queue again for no reason
3318 mutex_unlock(&memcg_cache_mutex);
3322 void kmem_cache_destroy_memcg_children(struct kmem_cache *s)
3324 struct kmem_cache *c;
3327 if (!s->memcg_params)
3329 if (!s->memcg_params->is_root_cache)
3333 * If the cache is being destroyed, we trust that there is no one else
3334 * requesting objects from it. Even if there are, the sanity checks in
3335 * kmem_cache_destroy should caught this ill-case.
3337 * Still, we don't want anyone else freeing memcg_caches under our
3338 * noses, which can happen if a new memcg comes to life. As usual,
3339 * we'll take the set_limit_mutex to protect ourselves against this.
3341 mutex_lock(&set_limit_mutex);
3342 for (i = 0; i < memcg_limited_groups_array_size; i++) {
3343 c = s->memcg_params->memcg_caches[i];
3348 * We will now manually delete the caches, so to avoid races
3349 * we need to cancel all pending destruction workers and
3350 * proceed with destruction ourselves.
3352 * kmem_cache_destroy() will call kmem_cache_shrink internally,
3353 * and that could spawn the workers again: it is likely that
3354 * the cache still have active pages until this very moment.
3355 * This would lead us back to mem_cgroup_destroy_cache.
3357 * But that will not execute at all if the "dead" flag is not
3358 * set, so flip it down to guarantee we are in control.
3360 c->memcg_params->dead = false;
3361 cancel_work_sync(&c->memcg_params->destroy);
3362 kmem_cache_destroy(c);
3364 mutex_unlock(&set_limit_mutex);
3367 struct create_work {
3368 struct mem_cgroup *memcg;
3369 struct kmem_cache *cachep;
3370 struct work_struct work;
3373 static void mem_cgroup_destroy_all_caches(struct mem_cgroup *memcg)
3375 struct kmem_cache *cachep;
3376 struct memcg_cache_params *params;
3378 if (!memcg_kmem_is_active(memcg))
3381 mutex_lock(&memcg->slab_caches_mutex);
3382 list_for_each_entry(params, &memcg->memcg_slab_caches, list) {
3383 cachep = memcg_params_to_cache(params);
3384 cachep->memcg_params->dead = true;
3385 schedule_work(&cachep->memcg_params->destroy);
3387 mutex_unlock(&memcg->slab_caches_mutex);
3390 static void memcg_create_cache_work_func(struct work_struct *w)
3392 struct create_work *cw;
3394 cw = container_of(w, struct create_work, work);
3395 memcg_create_kmem_cache(cw->memcg, cw->cachep);
3400 * Enqueue the creation of a per-memcg kmem_cache.
3402 static void __memcg_create_cache_enqueue(struct mem_cgroup *memcg,
3403 struct kmem_cache *cachep)
3405 struct create_work *cw;
3407 cw = kmalloc(sizeof(struct create_work), GFP_NOWAIT);
3409 css_put(&memcg->css);
3414 cw->cachep = cachep;
3416 INIT_WORK(&cw->work, memcg_create_cache_work_func);
3417 schedule_work(&cw->work);
3420 static void memcg_create_cache_enqueue(struct mem_cgroup *memcg,
3421 struct kmem_cache *cachep)
3424 * We need to stop accounting when we kmalloc, because if the
3425 * corresponding kmalloc cache is not yet created, the first allocation
3426 * in __memcg_create_cache_enqueue will recurse.
3428 * However, it is better to enclose the whole function. Depending on
3429 * the debugging options enabled, INIT_WORK(), for instance, can
3430 * trigger an allocation. This too, will make us recurse. Because at
3431 * this point we can't allow ourselves back into memcg_kmem_get_cache,
3432 * the safest choice is to do it like this, wrapping the whole function.
3434 memcg_stop_kmem_account();
3435 __memcg_create_cache_enqueue(memcg, cachep);
3436 memcg_resume_kmem_account();
3439 * Return the kmem_cache we're supposed to use for a slab allocation.
3440 * We try to use the current memcg's version of the cache.
3442 * If the cache does not exist yet, if we are the first user of it,
3443 * we either create it immediately, if possible, or create it asynchronously
3445 * In the latter case, we will let the current allocation go through with
3446 * the original cache.
3448 * Can't be called in interrupt context or from kernel threads.
3449 * This function needs to be called with rcu_read_lock() held.
3451 struct kmem_cache *__memcg_kmem_get_cache(struct kmem_cache *cachep,
3454 struct mem_cgroup *memcg;
3457 VM_BUG_ON(!cachep->memcg_params);
3458 VM_BUG_ON(!cachep->memcg_params->is_root_cache);
3460 if (!current->mm || current->memcg_kmem_skip_account)
3464 memcg = mem_cgroup_from_task(rcu_dereference(current->mm->owner));
3466 if (!memcg_can_account_kmem(memcg))
3469 idx = memcg_cache_id(memcg);
3472 * barrier to mare sure we're always seeing the up to date value. The
3473 * code updating memcg_caches will issue a write barrier to match this.
3475 read_barrier_depends();
3476 if (likely(cachep->memcg_params->memcg_caches[idx])) {
3477 cachep = cachep->memcg_params->memcg_caches[idx];
3481 /* The corresponding put will be done in the workqueue. */
3482 if (!css_tryget(&memcg->css))
3487 * If we are in a safe context (can wait, and not in interrupt
3488 * context), we could be be predictable and return right away.
3489 * This would guarantee that the allocation being performed
3490 * already belongs in the new cache.
3492 * However, there are some clashes that can arrive from locking.
3493 * For instance, because we acquire the slab_mutex while doing
3494 * kmem_cache_dup, this means no further allocation could happen
3495 * with the slab_mutex held.
3497 * Also, because cache creation issue get_online_cpus(), this
3498 * creates a lock chain: memcg_slab_mutex -> cpu_hotplug_mutex,
3499 * that ends up reversed during cpu hotplug. (cpuset allocates
3500 * a bunch of GFP_KERNEL memory during cpuup). Due to all that,
3501 * better to defer everything.
3503 memcg_create_cache_enqueue(memcg, cachep);
3509 EXPORT_SYMBOL(__memcg_kmem_get_cache);
3512 * We need to verify if the allocation against current->mm->owner's memcg is
3513 * possible for the given order. But the page is not allocated yet, so we'll
3514 * need a further commit step to do the final arrangements.
3516 * It is possible for the task to switch cgroups in this mean time, so at
3517 * commit time, we can't rely on task conversion any longer. We'll then use
3518 * the handle argument to return to the caller which cgroup we should commit
3519 * against. We could also return the memcg directly and avoid the pointer
3520 * passing, but a boolean return value gives better semantics considering
3521 * the compiled-out case as well.
3523 * Returning true means the allocation is possible.
3526 __memcg_kmem_newpage_charge(gfp_t gfp, struct mem_cgroup **_memcg, int order)
3528 struct mem_cgroup *memcg;
3534 * Disabling accounting is only relevant for some specific memcg
3535 * internal allocations. Therefore we would initially not have such
3536 * check here, since direct calls to the page allocator that are marked
3537 * with GFP_KMEMCG only happen outside memcg core. We are mostly
3538 * concerned with cache allocations, and by having this test at
3539 * memcg_kmem_get_cache, we are already able to relay the allocation to
3540 * the root cache and bypass the memcg cache altogether.
3542 * There is one exception, though: the SLUB allocator does not create
3543 * large order caches, but rather service large kmallocs directly from
3544 * the page allocator. Therefore, the following sequence when backed by
3545 * the SLUB allocator:
3547 * memcg_stop_kmem_account();
3548 * kmalloc(<large_number>)
3549 * memcg_resume_kmem_account();
3551 * would effectively ignore the fact that we should skip accounting,
3552 * since it will drive us directly to this function without passing
3553 * through the cache selector memcg_kmem_get_cache. Such large
3554 * allocations are extremely rare but can happen, for instance, for the
3555 * cache arrays. We bring this test here.
3557 if (!current->mm || current->memcg_kmem_skip_account)
3560 memcg = try_get_mem_cgroup_from_mm(current->mm);
3563 * very rare case described in mem_cgroup_from_task. Unfortunately there
3564 * isn't much we can do without complicating this too much, and it would
3565 * be gfp-dependent anyway. Just let it go
3567 if (unlikely(!memcg))
3570 if (!memcg_can_account_kmem(memcg)) {
3571 css_put(&memcg->css);
3575 ret = memcg_charge_kmem(memcg, gfp, PAGE_SIZE << order);
3579 css_put(&memcg->css);
3583 void __memcg_kmem_commit_charge(struct page *page, struct mem_cgroup *memcg,
3586 struct page_cgroup *pc;
3588 VM_BUG_ON(mem_cgroup_is_root(memcg));
3590 /* The page allocation failed. Revert */
3592 memcg_uncharge_kmem(memcg, PAGE_SIZE << order);
3596 pc = lookup_page_cgroup(page);
3597 lock_page_cgroup(pc);
3598 pc->mem_cgroup = memcg;
3599 SetPageCgroupUsed(pc);
3600 unlock_page_cgroup(pc);
3603 void __memcg_kmem_uncharge_pages(struct page *page, int order)
3605 struct mem_cgroup *memcg = NULL;
3606 struct page_cgroup *pc;
3609 pc = lookup_page_cgroup(page);
3611 * Fast unlocked return. Theoretically might have changed, have to
3612 * check again after locking.
3614 if (!PageCgroupUsed(pc))
3617 lock_page_cgroup(pc);
3618 if (PageCgroupUsed(pc)) {
3619 memcg = pc->mem_cgroup;
3620 ClearPageCgroupUsed(pc);
3622 unlock_page_cgroup(pc);
3625 * We trust that only if there is a memcg associated with the page, it
3626 * is a valid allocation
3631 VM_BUG_ON(mem_cgroup_is_root(memcg));
3632 memcg_uncharge_kmem(memcg, PAGE_SIZE << order);
3635 static inline void mem_cgroup_destroy_all_caches(struct mem_cgroup *memcg)
3638 #endif /* CONFIG_MEMCG_KMEM */
3640 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3642 #define PCGF_NOCOPY_AT_SPLIT (1 << PCG_LOCK | 1 << PCG_MIGRATION)
3644 * Because tail pages are not marked as "used", set it. We're under
3645 * zone->lru_lock, 'splitting on pmd' and compound_lock.
3646 * charge/uncharge will be never happen and move_account() is done under
3647 * compound_lock(), so we don't have to take care of races.
3649 void mem_cgroup_split_huge_fixup(struct page *head)
3651 struct page_cgroup *head_pc = lookup_page_cgroup(head);
3652 struct page_cgroup *pc;
3653 struct mem_cgroup *memcg;
3656 if (mem_cgroup_disabled())
3659 memcg = head_pc->mem_cgroup;
3660 for (i = 1; i < HPAGE_PMD_NR; i++) {
3662 pc->mem_cgroup = memcg;
3663 smp_wmb();/* see __commit_charge() */
3664 pc->flags = head_pc->flags & ~PCGF_NOCOPY_AT_SPLIT;
3666 __this_cpu_sub(memcg->stat->count[MEM_CGROUP_STAT_RSS_HUGE],
3669 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
3672 void mem_cgroup_move_account_page_stat(struct mem_cgroup *from,
3673 struct mem_cgroup *to,
3674 unsigned int nr_pages,
3675 enum mem_cgroup_stat_index idx)
3677 /* Update stat data for mem_cgroup */
3679 WARN_ON_ONCE(from->stat->count[idx] < nr_pages);
3680 __this_cpu_add(from->stat->count[idx], -nr_pages);
3681 __this_cpu_add(to->stat->count[idx], nr_pages);
3686 * mem_cgroup_move_account - move account of the page
3688 * @nr_pages: number of regular pages (>1 for huge pages)
3689 * @pc: page_cgroup of the page.
3690 * @from: mem_cgroup which the page is moved from.
3691 * @to: mem_cgroup which the page is moved to. @from != @to.
3693 * The caller must confirm following.
3694 * - page is not on LRU (isolate_page() is useful.)
3695 * - compound_lock is held when nr_pages > 1
3697 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
3700 static int mem_cgroup_move_account(struct page *page,
3701 unsigned int nr_pages,
3702 struct page_cgroup *pc,
3703 struct mem_cgroup *from,
3704 struct mem_cgroup *to)
3706 unsigned long flags;
3708 bool anon = PageAnon(page);
3710 VM_BUG_ON(from == to);
3711 VM_BUG_ON(PageLRU(page));
3713 * The page is isolated from LRU. So, collapse function
3714 * will not handle this page. But page splitting can happen.
3715 * Do this check under compound_page_lock(). The caller should
3719 if (nr_pages > 1 && !PageTransHuge(page))
3722 lock_page_cgroup(pc);
3725 if (!PageCgroupUsed(pc) || pc->mem_cgroup != from)
3728 move_lock_mem_cgroup(from, &flags);
3730 if (!anon && page_mapped(page))
3731 mem_cgroup_move_account_page_stat(from, to, nr_pages,
3732 MEM_CGROUP_STAT_FILE_MAPPED);
3734 if (PageWriteback(page))
3735 mem_cgroup_move_account_page_stat(from, to, nr_pages,
3736 MEM_CGROUP_STAT_WRITEBACK);
3738 mem_cgroup_charge_statistics(from, page, anon, -nr_pages);
3740 /* caller should have done css_get */
3741 pc->mem_cgroup = to;
3742 mem_cgroup_charge_statistics(to, page, anon, nr_pages);
3743 move_unlock_mem_cgroup(from, &flags);
3746 unlock_page_cgroup(pc);
3750 memcg_check_events(to, page);
3751 memcg_check_events(from, page);
3757 * mem_cgroup_move_parent - moves page to the parent group
3758 * @page: the page to move
3759 * @pc: page_cgroup of the page
3760 * @child: page's cgroup
3762 * move charges to its parent or the root cgroup if the group has no
3763 * parent (aka use_hierarchy==0).
3764 * Although this might fail (get_page_unless_zero, isolate_lru_page or
3765 * mem_cgroup_move_account fails) the failure is always temporary and
3766 * it signals a race with a page removal/uncharge or migration. In the
3767 * first case the page is on the way out and it will vanish from the LRU
3768 * on the next attempt and the call should be retried later.
3769 * Isolation from the LRU fails only if page has been isolated from
3770 * the LRU since we looked at it and that usually means either global
3771 * reclaim or migration going on. The page will either get back to the
3773 * Finaly mem_cgroup_move_account fails only if the page got uncharged
3774 * (!PageCgroupUsed) or moved to a different group. The page will
3775 * disappear in the next attempt.
3777 static int mem_cgroup_move_parent(struct page *page,
3778 struct page_cgroup *pc,
3779 struct mem_cgroup *child)
3781 struct mem_cgroup *parent;
3782 unsigned int nr_pages;
3783 unsigned long uninitialized_var(flags);
3786 VM_BUG_ON(mem_cgroup_is_root(child));
3789 if (!get_page_unless_zero(page))
3791 if (isolate_lru_page(page))
3794 nr_pages = hpage_nr_pages(page);
3796 parent = parent_mem_cgroup(child);
3798 * If no parent, move charges to root cgroup.
3801 parent = root_mem_cgroup;
3804 VM_BUG_ON(!PageTransHuge(page));
3805 flags = compound_lock_irqsave(page);
3808 ret = mem_cgroup_move_account(page, nr_pages,
3811 __mem_cgroup_cancel_local_charge(child, nr_pages);
3814 compound_unlock_irqrestore(page, flags);
3815 putback_lru_page(page);
3823 * Charge the memory controller for page usage.
3825 * 0 if the charge was successful
3826 * < 0 if the cgroup is over its limit
3828 static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
3829 gfp_t gfp_mask, enum charge_type ctype)
3831 struct mem_cgroup *memcg = NULL;
3832 unsigned int nr_pages = 1;
3836 if (PageTransHuge(page)) {
3837 nr_pages <<= compound_order(page);
3838 VM_BUG_ON(!PageTransHuge(page));
3840 * Never OOM-kill a process for a huge page. The
3841 * fault handler will fall back to regular pages.
3846 ret = __mem_cgroup_try_charge(mm, gfp_mask, nr_pages, &memcg, oom);
3849 __mem_cgroup_commit_charge(memcg, page, nr_pages, ctype, false);
3853 int mem_cgroup_newpage_charge(struct page *page,
3854 struct mm_struct *mm, gfp_t gfp_mask)
3856 if (mem_cgroup_disabled())
3858 VM_BUG_ON(page_mapped(page));
3859 VM_BUG_ON(page->mapping && !PageAnon(page));
3861 return mem_cgroup_charge_common(page, mm, gfp_mask,
3862 MEM_CGROUP_CHARGE_TYPE_ANON);
3866 * While swap-in, try_charge -> commit or cancel, the page is locked.
3867 * And when try_charge() successfully returns, one refcnt to memcg without
3868 * struct page_cgroup is acquired. This refcnt will be consumed by
3869 * "commit()" or removed by "cancel()"
3871 static int __mem_cgroup_try_charge_swapin(struct mm_struct *mm,
3874 struct mem_cgroup **memcgp)
3876 struct mem_cgroup *memcg;
3877 struct page_cgroup *pc;
3880 pc = lookup_page_cgroup(page);
3882 * Every swap fault against a single page tries to charge the
3883 * page, bail as early as possible. shmem_unuse() encounters
3884 * already charged pages, too. The USED bit is protected by
3885 * the page lock, which serializes swap cache removal, which
3886 * in turn serializes uncharging.
3888 if (PageCgroupUsed(pc))
3890 if (!do_swap_account)
3892 memcg = try_get_mem_cgroup_from_page(page);
3896 ret = __mem_cgroup_try_charge(NULL, mask, 1, memcgp, true);
3897 css_put(&memcg->css);
3902 ret = __mem_cgroup_try_charge(mm, mask, 1, memcgp, true);
3908 int mem_cgroup_try_charge_swapin(struct mm_struct *mm, struct page *page,
3909 gfp_t gfp_mask, struct mem_cgroup **memcgp)
3912 if (mem_cgroup_disabled())
3915 * A racing thread's fault, or swapoff, may have already
3916 * updated the pte, and even removed page from swap cache: in
3917 * those cases unuse_pte()'s pte_same() test will fail; but
3918 * there's also a KSM case which does need to charge the page.
3920 if (!PageSwapCache(page)) {
3923 ret = __mem_cgroup_try_charge(mm, gfp_mask, 1, memcgp, true);
3928 return __mem_cgroup_try_charge_swapin(mm, page, gfp_mask, memcgp);
3931 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *memcg)
3933 if (mem_cgroup_disabled())
3937 __mem_cgroup_cancel_charge(memcg, 1);
3941 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *memcg,
3942 enum charge_type ctype)
3944 if (mem_cgroup_disabled())
3949 __mem_cgroup_commit_charge(memcg, page, 1, ctype, true);
3951 * Now swap is on-memory. This means this page may be
3952 * counted both as mem and swap....double count.
3953 * Fix it by uncharging from memsw. Basically, this SwapCache is stable
3954 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
3955 * may call delete_from_swap_cache() before reach here.
3957 if (do_swap_account && PageSwapCache(page)) {
3958 swp_entry_t ent = {.val = page_private(page)};
3959 mem_cgroup_uncharge_swap(ent);
3963 void mem_cgroup_commit_charge_swapin(struct page *page,
3964 struct mem_cgroup *memcg)
3966 __mem_cgroup_commit_charge_swapin(page, memcg,
3967 MEM_CGROUP_CHARGE_TYPE_ANON);
3970 int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
3973 struct mem_cgroup *memcg = NULL;
3974 enum charge_type type = MEM_CGROUP_CHARGE_TYPE_CACHE;
3977 if (mem_cgroup_disabled())
3979 if (PageCompound(page))
3982 if (!PageSwapCache(page))
3983 ret = mem_cgroup_charge_common(page, mm, gfp_mask, type);
3984 else { /* page is swapcache/shmem */
3985 ret = __mem_cgroup_try_charge_swapin(mm, page,
3988 __mem_cgroup_commit_charge_swapin(page, memcg, type);
3993 static void mem_cgroup_do_uncharge(struct mem_cgroup *memcg,
3994 unsigned int nr_pages,
3995 const enum charge_type ctype)
3997 struct memcg_batch_info *batch = NULL;
3998 bool uncharge_memsw = true;
4000 /* If swapout, usage of swap doesn't decrease */
4001 if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
4002 uncharge_memsw = false;
4004 batch = ¤t->memcg_batch;
4006 * In usual, we do css_get() when we remember memcg pointer.
4007 * But in this case, we keep res->usage until end of a series of
4008 * uncharges. Then, it's ok to ignore memcg's refcnt.
4011 batch->memcg = memcg;
4013 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
4014 * In those cases, all pages freed continuously can be expected to be in
4015 * the same cgroup and we have chance to coalesce uncharges.
4016 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
4017 * because we want to do uncharge as soon as possible.
4020 if (!batch->do_batch || test_thread_flag(TIF_MEMDIE))
4021 goto direct_uncharge;
4024 goto direct_uncharge;
4027 * In typical case, batch->memcg == mem. This means we can
4028 * merge a series of uncharges to an uncharge of res_counter.
4029 * If not, we uncharge res_counter ony by one.
4031 if (batch->memcg != memcg)
4032 goto direct_uncharge;
4033 /* remember freed charge and uncharge it later */
4036 batch->memsw_nr_pages++;
4039 res_counter_uncharge(&memcg->res, nr_pages * PAGE_SIZE);
4041 res_counter_uncharge(&memcg->memsw, nr_pages * PAGE_SIZE);
4042 if (unlikely(batch->memcg != memcg))
4043 memcg_oom_recover(memcg);
4047 * uncharge if !page_mapped(page)
4049 static struct mem_cgroup *
4050 __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype,
4053 struct mem_cgroup *memcg = NULL;
4054 unsigned int nr_pages = 1;
4055 struct page_cgroup *pc;
4058 if (mem_cgroup_disabled())
4061 if (PageTransHuge(page)) {
4062 nr_pages <<= compound_order(page);
4063 VM_BUG_ON(!PageTransHuge(page));
4066 * Check if our page_cgroup is valid
4068 pc = lookup_page_cgroup(page);
4069 if (unlikely(!PageCgroupUsed(pc)))
4072 lock_page_cgroup(pc);
4074 memcg = pc->mem_cgroup;
4076 if (!PageCgroupUsed(pc))
4079 anon = PageAnon(page);
4082 case MEM_CGROUP_CHARGE_TYPE_ANON:
4084 * Generally PageAnon tells if it's the anon statistics to be
4085 * updated; but sometimes e.g. mem_cgroup_uncharge_page() is
4086 * used before page reached the stage of being marked PageAnon.
4090 case MEM_CGROUP_CHARGE_TYPE_DROP:
4091 /* See mem_cgroup_prepare_migration() */
4092 if (page_mapped(page))
4095 * Pages under migration may not be uncharged. But
4096 * end_migration() /must/ be the one uncharging the
4097 * unused post-migration page and so it has to call
4098 * here with the migration bit still set. See the
4099 * res_counter handling below.
4101 if (!end_migration && PageCgroupMigration(pc))
4104 case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
4105 if (!PageAnon(page)) { /* Shared memory */
4106 if (page->mapping && !page_is_file_cache(page))
4108 } else if (page_mapped(page)) /* Anon */
4115 mem_cgroup_charge_statistics(memcg, page, anon, -nr_pages);
4117 ClearPageCgroupUsed(pc);
4119 * pc->mem_cgroup is not cleared here. It will be accessed when it's
4120 * freed from LRU. This is safe because uncharged page is expected not
4121 * to be reused (freed soon). Exception is SwapCache, it's handled by
4122 * special functions.
4125 unlock_page_cgroup(pc);
4127 * even after unlock, we have memcg->res.usage here and this memcg
4128 * will never be freed, so it's safe to call css_get().
4130 memcg_check_events(memcg, page);
4131 if (do_swap_account && ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT) {
4132 mem_cgroup_swap_statistics(memcg, true);
4133 css_get(&memcg->css);
4136 * Migration does not charge the res_counter for the
4137 * replacement page, so leave it alone when phasing out the
4138 * page that is unused after the migration.
4140 if (!end_migration && !mem_cgroup_is_root(memcg))
4141 mem_cgroup_do_uncharge(memcg, nr_pages, ctype);
4146 unlock_page_cgroup(pc);
4150 void mem_cgroup_uncharge_page(struct page *page)
4153 if (page_mapped(page))
4155 VM_BUG_ON(page->mapping && !PageAnon(page));
4157 * If the page is in swap cache, uncharge should be deferred
4158 * to the swap path, which also properly accounts swap usage
4159 * and handles memcg lifetime.
4161 * Note that this check is not stable and reclaim may add the
4162 * page to swap cache at any time after this. However, if the
4163 * page is not in swap cache by the time page->mapcount hits
4164 * 0, there won't be any page table references to the swap
4165 * slot, and reclaim will free it and not actually write the
4168 if (PageSwapCache(page))
4170 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_ANON, false);
4173 void mem_cgroup_uncharge_cache_page(struct page *page)
4175 VM_BUG_ON(page_mapped(page));
4176 VM_BUG_ON(page->mapping);
4177 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE, false);
4181 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
4182 * In that cases, pages are freed continuously and we can expect pages
4183 * are in the same memcg. All these calls itself limits the number of
4184 * pages freed at once, then uncharge_start/end() is called properly.
4185 * This may be called prural(2) times in a context,
4188 void mem_cgroup_uncharge_start(void)
4190 current->memcg_batch.do_batch++;
4191 /* We can do nest. */
4192 if (current->memcg_batch.do_batch == 1) {
4193 current->memcg_batch.memcg = NULL;
4194 current->memcg_batch.nr_pages = 0;
4195 current->memcg_batch.memsw_nr_pages = 0;
4199 void mem_cgroup_uncharge_end(void)
4201 struct memcg_batch_info *batch = ¤t->memcg_batch;
4203 if (!batch->do_batch)
4207 if (batch->do_batch) /* If stacked, do nothing. */
4213 * This "batch->memcg" is valid without any css_get/put etc...
4214 * bacause we hide charges behind us.
4216 if (batch->nr_pages)
4217 res_counter_uncharge(&batch->memcg->res,
4218 batch->nr_pages * PAGE_SIZE);
4219 if (batch->memsw_nr_pages)
4220 res_counter_uncharge(&batch->memcg->memsw,
4221 batch->memsw_nr_pages * PAGE_SIZE);
4222 memcg_oom_recover(batch->memcg);
4223 /* forget this pointer (for sanity check) */
4224 batch->memcg = NULL;
4229 * called after __delete_from_swap_cache() and drop "page" account.
4230 * memcg information is recorded to swap_cgroup of "ent"
4233 mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
4235 struct mem_cgroup *memcg;
4236 int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
4238 if (!swapout) /* this was a swap cache but the swap is unused ! */
4239 ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
4241 memcg = __mem_cgroup_uncharge_common(page, ctype, false);
4244 * record memcg information, if swapout && memcg != NULL,
4245 * css_get() was called in uncharge().
4247 if (do_swap_account && swapout && memcg)
4248 swap_cgroup_record(ent, mem_cgroup_id(memcg));
4252 #ifdef CONFIG_MEMCG_SWAP
4254 * called from swap_entry_free(). remove record in swap_cgroup and
4255 * uncharge "memsw" account.
4257 void mem_cgroup_uncharge_swap(swp_entry_t ent)
4259 struct mem_cgroup *memcg;
4262 if (!do_swap_account)
4265 id = swap_cgroup_record(ent, 0);
4267 memcg = mem_cgroup_lookup(id);
4270 * We uncharge this because swap is freed.
4271 * This memcg can be obsolete one. We avoid calling css_tryget
4273 if (!mem_cgroup_is_root(memcg))
4274 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
4275 mem_cgroup_swap_statistics(memcg, false);
4276 css_put(&memcg->css);
4282 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
4283 * @entry: swap entry to be moved
4284 * @from: mem_cgroup which the entry is moved from
4285 * @to: mem_cgroup which the entry is moved to
4287 * It succeeds only when the swap_cgroup's record for this entry is the same
4288 * as the mem_cgroup's id of @from.
4290 * Returns 0 on success, -EINVAL on failure.
4292 * The caller must have charged to @to, IOW, called res_counter_charge() about
4293 * both res and memsw, and called css_get().
4295 static int mem_cgroup_move_swap_account(swp_entry_t entry,
4296 struct mem_cgroup *from, struct mem_cgroup *to)
4298 unsigned short old_id, new_id;
4300 old_id = mem_cgroup_id(from);
4301 new_id = mem_cgroup_id(to);
4303 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
4304 mem_cgroup_swap_statistics(from, false);
4305 mem_cgroup_swap_statistics(to, true);
4307 * This function is only called from task migration context now.
4308 * It postpones res_counter and refcount handling till the end
4309 * of task migration(mem_cgroup_clear_mc()) for performance
4310 * improvement. But we cannot postpone css_get(to) because if
4311 * the process that has been moved to @to does swap-in, the
4312 * refcount of @to might be decreased to 0.
4314 * We are in attach() phase, so the cgroup is guaranteed to be
4315 * alive, so we can just call css_get().
4323 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
4324 struct mem_cgroup *from, struct mem_cgroup *to)
4331 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
4334 void mem_cgroup_prepare_migration(struct page *page, struct page *newpage,
4335 struct mem_cgroup **memcgp)
4337 struct mem_cgroup *memcg = NULL;
4338 unsigned int nr_pages = 1;
4339 struct page_cgroup *pc;
4340 enum charge_type ctype;
4344 if (mem_cgroup_disabled())
4347 if (PageTransHuge(page))
4348 nr_pages <<= compound_order(page);
4350 pc = lookup_page_cgroup(page);
4351 lock_page_cgroup(pc);
4352 if (PageCgroupUsed(pc)) {
4353 memcg = pc->mem_cgroup;
4354 css_get(&memcg->css);
4356 * At migrating an anonymous page, its mapcount goes down
4357 * to 0 and uncharge() will be called. But, even if it's fully
4358 * unmapped, migration may fail and this page has to be
4359 * charged again. We set MIGRATION flag here and delay uncharge
4360 * until end_migration() is called
4362 * Corner Case Thinking
4364 * When the old page was mapped as Anon and it's unmap-and-freed
4365 * while migration was ongoing.
4366 * If unmap finds the old page, uncharge() of it will be delayed
4367 * until end_migration(). If unmap finds a new page, it's
4368 * uncharged when it make mapcount to be 1->0. If unmap code
4369 * finds swap_migration_entry, the new page will not be mapped
4370 * and end_migration() will find it(mapcount==0).
4373 * When the old page was mapped but migraion fails, the kernel
4374 * remaps it. A charge for it is kept by MIGRATION flag even
4375 * if mapcount goes down to 0. We can do remap successfully
4376 * without charging it again.
4379 * The "old" page is under lock_page() until the end of
4380 * migration, so, the old page itself will not be swapped-out.
4381 * If the new page is swapped out before end_migraton, our
4382 * hook to usual swap-out path will catch the event.
4385 SetPageCgroupMigration(pc);
4387 unlock_page_cgroup(pc);
4389 * If the page is not charged at this point,
4397 * We charge new page before it's used/mapped. So, even if unlock_page()
4398 * is called before end_migration, we can catch all events on this new
4399 * page. In the case new page is migrated but not remapped, new page's
4400 * mapcount will be finally 0 and we call uncharge in end_migration().
4403 ctype = MEM_CGROUP_CHARGE_TYPE_ANON;
4405 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
4407 * The page is committed to the memcg, but it's not actually
4408 * charged to the res_counter since we plan on replacing the
4409 * old one and only one page is going to be left afterwards.
4411 __mem_cgroup_commit_charge(memcg, newpage, nr_pages, ctype, false);
4414 /* remove redundant charge if migration failed*/
4415 void mem_cgroup_end_migration(struct mem_cgroup *memcg,
4416 struct page *oldpage, struct page *newpage, bool migration_ok)
4418 struct page *used, *unused;
4419 struct page_cgroup *pc;
4425 if (!migration_ok) {
4432 anon = PageAnon(used);
4433 __mem_cgroup_uncharge_common(unused,
4434 anon ? MEM_CGROUP_CHARGE_TYPE_ANON
4435 : MEM_CGROUP_CHARGE_TYPE_CACHE,
4437 css_put(&memcg->css);
4439 * We disallowed uncharge of pages under migration because mapcount
4440 * of the page goes down to zero, temporarly.
4441 * Clear the flag and check the page should be charged.
4443 pc = lookup_page_cgroup(oldpage);
4444 lock_page_cgroup(pc);
4445 ClearPageCgroupMigration(pc);
4446 unlock_page_cgroup(pc);
4449 * If a page is a file cache, radix-tree replacement is very atomic
4450 * and we can skip this check. When it was an Anon page, its mapcount
4451 * goes down to 0. But because we added MIGRATION flage, it's not
4452 * uncharged yet. There are several case but page->mapcount check
4453 * and USED bit check in mem_cgroup_uncharge_page() will do enough
4454 * check. (see prepare_charge() also)
4457 mem_cgroup_uncharge_page(used);
4461 * At replace page cache, newpage is not under any memcg but it's on
4462 * LRU. So, this function doesn't touch res_counter but handles LRU
4463 * in correct way. Both pages are locked so we cannot race with uncharge.
4465 void mem_cgroup_replace_page_cache(struct page *oldpage,
4466 struct page *newpage)
4468 struct mem_cgroup *memcg = NULL;
4469 struct page_cgroup *pc;
4470 enum charge_type type = MEM_CGROUP_CHARGE_TYPE_CACHE;
4472 if (mem_cgroup_disabled())
4475 pc = lookup_page_cgroup(oldpage);
4476 /* fix accounting on old pages */
4477 lock_page_cgroup(pc);
4478 if (PageCgroupUsed(pc)) {
4479 memcg = pc->mem_cgroup;
4480 mem_cgroup_charge_statistics(memcg, oldpage, false, -1);
4481 ClearPageCgroupUsed(pc);
4483 unlock_page_cgroup(pc);
4486 * When called from shmem_replace_page(), in some cases the
4487 * oldpage has already been charged, and in some cases not.
4492 * Even if newpage->mapping was NULL before starting replacement,
4493 * the newpage may be on LRU(or pagevec for LRU) already. We lock
4494 * LRU while we overwrite pc->mem_cgroup.
4496 __mem_cgroup_commit_charge(memcg, newpage, 1, type, true);
4499 #ifdef CONFIG_DEBUG_VM
4500 static struct page_cgroup *lookup_page_cgroup_used(struct page *page)
4502 struct page_cgroup *pc;
4504 pc = lookup_page_cgroup(page);
4506 * Can be NULL while feeding pages into the page allocator for
4507 * the first time, i.e. during boot or memory hotplug;
4508 * or when mem_cgroup_disabled().
4510 if (likely(pc) && PageCgroupUsed(pc))
4515 bool mem_cgroup_bad_page_check(struct page *page)
4517 if (mem_cgroup_disabled())
4520 return lookup_page_cgroup_used(page) != NULL;
4523 void mem_cgroup_print_bad_page(struct page *page)
4525 struct page_cgroup *pc;
4527 pc = lookup_page_cgroup_used(page);
4529 pr_alert("pc:%p pc->flags:%lx pc->mem_cgroup:%p\n",
4530 pc, pc->flags, pc->mem_cgroup);
4535 static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
4536 unsigned long long val)
4539 u64 memswlimit, memlimit;
4541 int children = mem_cgroup_count_children(memcg);
4542 u64 curusage, oldusage;
4546 * For keeping hierarchical_reclaim simple, how long we should retry
4547 * is depends on callers. We set our retry-count to be function
4548 * of # of children which we should visit in this loop.
4550 retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
4552 oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
4555 while (retry_count) {
4556 if (signal_pending(current)) {
4561 * Rather than hide all in some function, I do this in
4562 * open coded manner. You see what this really does.
4563 * We have to guarantee memcg->res.limit <= memcg->memsw.limit.
4565 mutex_lock(&set_limit_mutex);
4566 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
4567 if (memswlimit < val) {
4569 mutex_unlock(&set_limit_mutex);
4573 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
4577 ret = res_counter_set_limit(&memcg->res, val);
4579 if (memswlimit == val)
4580 memcg->memsw_is_minimum = true;
4582 memcg->memsw_is_minimum = false;
4584 mutex_unlock(&set_limit_mutex);
4589 mem_cgroup_reclaim(memcg, GFP_KERNEL,
4590 MEM_CGROUP_RECLAIM_SHRINK);
4591 curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
4592 /* Usage is reduced ? */
4593 if (curusage >= oldusage)
4596 oldusage = curusage;
4598 if (!ret && enlarge)
4599 memcg_oom_recover(memcg);
4604 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
4605 unsigned long long val)
4608 u64 memlimit, memswlimit, oldusage, curusage;
4609 int children = mem_cgroup_count_children(memcg);
4613 /* see mem_cgroup_resize_res_limit */
4614 retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
4615 oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
4616 while (retry_count) {
4617 if (signal_pending(current)) {
4622 * Rather than hide all in some function, I do this in
4623 * open coded manner. You see what this really does.
4624 * We have to guarantee memcg->res.limit <= memcg->memsw.limit.
4626 mutex_lock(&set_limit_mutex);
4627 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
4628 if (memlimit > val) {
4630 mutex_unlock(&set_limit_mutex);
4633 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
4634 if (memswlimit < val)
4636 ret = res_counter_set_limit(&memcg->memsw, val);
4638 if (memlimit == val)
4639 memcg->memsw_is_minimum = true;
4641 memcg->memsw_is_minimum = false;
4643 mutex_unlock(&set_limit_mutex);
4648 mem_cgroup_reclaim(memcg, GFP_KERNEL,
4649 MEM_CGROUP_RECLAIM_NOSWAP |
4650 MEM_CGROUP_RECLAIM_SHRINK);
4651 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
4652 /* Usage is reduced ? */
4653 if (curusage >= oldusage)
4656 oldusage = curusage;
4658 if (!ret && enlarge)
4659 memcg_oom_recover(memcg);
4664 * mem_cgroup_force_empty_list - clears LRU of a group
4665 * @memcg: group to clear
4668 * @lru: lru to to clear
4670 * Traverse a specified page_cgroup list and try to drop them all. This doesn't
4671 * reclaim the pages page themselves - pages are moved to the parent (or root)
4674 static void mem_cgroup_force_empty_list(struct mem_cgroup *memcg,
4675 int node, int zid, enum lru_list lru)
4677 struct lruvec *lruvec;
4678 unsigned long flags;
4679 struct list_head *list;
4683 zone = &NODE_DATA(node)->node_zones[zid];
4684 lruvec = mem_cgroup_zone_lruvec(zone, memcg);
4685 list = &lruvec->lists[lru];
4689 struct page_cgroup *pc;
4692 spin_lock_irqsave(&zone->lru_lock, flags);
4693 if (list_empty(list)) {
4694 spin_unlock_irqrestore(&zone->lru_lock, flags);
4697 page = list_entry(list->prev, struct page, lru);
4699 list_move(&page->lru, list);
4701 spin_unlock_irqrestore(&zone->lru_lock, flags);
4704 spin_unlock_irqrestore(&zone->lru_lock, flags);
4706 pc = lookup_page_cgroup(page);
4708 if (mem_cgroup_move_parent(page, pc, memcg)) {
4709 /* found lock contention or "pc" is obsolete. */
4714 } while (!list_empty(list));
4718 * make mem_cgroup's charge to be 0 if there is no task by moving
4719 * all the charges and pages to the parent.
4720 * This enables deleting this mem_cgroup.
4722 * Caller is responsible for holding css reference on the memcg.
4724 static void mem_cgroup_reparent_charges(struct mem_cgroup *memcg)
4730 /* This is for making all *used* pages to be on LRU. */
4731 lru_add_drain_all();
4732 drain_all_stock_sync(memcg);
4733 mem_cgroup_start_move(memcg);
4734 for_each_node_state(node, N_MEMORY) {
4735 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
4738 mem_cgroup_force_empty_list(memcg,
4743 mem_cgroup_end_move(memcg);
4744 memcg_oom_recover(memcg);
4748 * Kernel memory may not necessarily be trackable to a specific
4749 * process. So they are not migrated, and therefore we can't
4750 * expect their value to drop to 0 here.
4751 * Having res filled up with kmem only is enough.
4753 * This is a safety check because mem_cgroup_force_empty_list
4754 * could have raced with mem_cgroup_replace_page_cache callers
4755 * so the lru seemed empty but the page could have been added
4756 * right after the check. RES_USAGE should be safe as we always
4757 * charge before adding to the LRU.
4759 usage = res_counter_read_u64(&memcg->res, RES_USAGE) -
4760 res_counter_read_u64(&memcg->kmem, RES_USAGE);
4761 } while (usage > 0);
4765 * This mainly exists for tests during the setting of set of use_hierarchy.
4766 * Since this is the very setting we are changing, the current hierarchy value
4769 static inline bool __memcg_has_children(struct mem_cgroup *memcg)
4771 struct cgroup_subsys_state *pos;
4773 /* bounce at first found */
4774 css_for_each_child(pos, &memcg->css)
4780 * Must be called with memcg_create_mutex held, unless the cgroup is guaranteed
4781 * to be already dead (as in mem_cgroup_force_empty, for instance). This is
4782 * from mem_cgroup_count_children(), in the sense that we don't really care how
4783 * many children we have; we only need to know if we have any. It also counts
4784 * any memcg without hierarchy as infertile.
4786 static inline bool memcg_has_children(struct mem_cgroup *memcg)
4788 return memcg->use_hierarchy && __memcg_has_children(memcg);
4792 * Reclaims as many pages from the given memcg as possible and moves
4793 * the rest to the parent.
4795 * Caller is responsible for holding css reference for memcg.
4797 static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
4799 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
4800 struct cgroup *cgrp = memcg->css.cgroup;
4802 /* returns EBUSY if there is a task or if we come here twice. */
4803 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
4806 /* we call try-to-free pages for make this cgroup empty */
4807 lru_add_drain_all();
4808 /* try to free all pages in this cgroup */
4809 while (nr_retries && res_counter_read_u64(&memcg->res, RES_USAGE) > 0) {
4812 if (signal_pending(current))
4815 progress = try_to_free_mem_cgroup_pages(memcg, GFP_KERNEL,
4819 /* maybe some writeback is necessary */
4820 congestion_wait(BLK_RW_ASYNC, HZ/10);
4825 mem_cgroup_reparent_charges(memcg);
4830 static int mem_cgroup_force_empty_write(struct cgroup_subsys_state *css,
4833 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4835 if (mem_cgroup_is_root(memcg))
4837 return mem_cgroup_force_empty(memcg);
4840 static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
4843 return mem_cgroup_from_css(css)->use_hierarchy;
4846 static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
4847 struct cftype *cft, u64 val)
4850 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4851 struct mem_cgroup *parent_memcg = mem_cgroup_from_css(css_parent(&memcg->css));
4853 mutex_lock(&memcg_create_mutex);
4855 if (memcg->use_hierarchy == val)
4859 * If parent's use_hierarchy is set, we can't make any modifications
4860 * in the child subtrees. If it is unset, then the change can
4861 * occur, provided the current cgroup has no children.
4863 * For the root cgroup, parent_mem is NULL, we allow value to be
4864 * set if there are no children.
4866 if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
4867 (val == 1 || val == 0)) {
4868 if (!__memcg_has_children(memcg))
4869 memcg->use_hierarchy = val;
4876 mutex_unlock(&memcg_create_mutex);
4882 static unsigned long mem_cgroup_recursive_stat(struct mem_cgroup *memcg,
4883 enum mem_cgroup_stat_index idx)
4885 struct mem_cgroup *iter;
4888 /* Per-cpu values can be negative, use a signed accumulator */
4889 for_each_mem_cgroup_tree(iter, memcg)
4890 val += mem_cgroup_read_stat(iter, idx);
4892 if (val < 0) /* race ? */
4897 static inline u64 mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
4901 if (!mem_cgroup_is_root(memcg)) {
4903 return res_counter_read_u64(&memcg->res, RES_USAGE);
4905 return res_counter_read_u64(&memcg->memsw, RES_USAGE);
4909 * Transparent hugepages are still accounted for in MEM_CGROUP_STAT_RSS
4910 * as well as in MEM_CGROUP_STAT_RSS_HUGE.
4912 val = mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_CACHE);
4913 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_RSS);
4916 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_SWAP);
4918 return val << PAGE_SHIFT;
4921 static ssize_t mem_cgroup_read(struct cgroup_subsys_state *css,
4922 struct cftype *cft, struct file *file,
4923 char __user *buf, size_t nbytes, loff_t *ppos)
4925 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4931 type = MEMFILE_TYPE(cft->private);
4932 name = MEMFILE_ATTR(cft->private);
4936 if (name == RES_USAGE)
4937 val = mem_cgroup_usage(memcg, false);
4939 val = res_counter_read_u64(&memcg->res, name);
4942 if (name == RES_USAGE)
4943 val = mem_cgroup_usage(memcg, true);
4945 val = res_counter_read_u64(&memcg->memsw, name);
4948 val = res_counter_read_u64(&memcg->kmem, name);
4954 len = scnprintf(str, sizeof(str), "%llu\n", (unsigned long long)val);
4955 return simple_read_from_buffer(buf, nbytes, ppos, str, len);
4958 static int memcg_update_kmem_limit(struct cgroup_subsys_state *css, u64 val)
4961 #ifdef CONFIG_MEMCG_KMEM
4962 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4964 * For simplicity, we won't allow this to be disabled. It also can't
4965 * be changed if the cgroup has children already, or if tasks had
4968 * If tasks join before we set the limit, a person looking at
4969 * kmem.usage_in_bytes will have no way to determine when it took
4970 * place, which makes the value quite meaningless.
4972 * After it first became limited, changes in the value of the limit are
4973 * of course permitted.
4975 mutex_lock(&memcg_create_mutex);
4976 mutex_lock(&set_limit_mutex);
4977 if (!memcg->kmem_account_flags && val != RES_COUNTER_MAX) {
4978 if (cgroup_task_count(css->cgroup) || memcg_has_children(memcg)) {
4982 ret = res_counter_set_limit(&memcg->kmem, val);
4985 ret = memcg_update_cache_sizes(memcg);
4987 res_counter_set_limit(&memcg->kmem, RES_COUNTER_MAX);
4990 static_key_slow_inc(&memcg_kmem_enabled_key);
4992 * setting the active bit after the inc will guarantee no one
4993 * starts accounting before all call sites are patched
4995 memcg_kmem_set_active(memcg);
4997 ret = res_counter_set_limit(&memcg->kmem, val);
4999 mutex_unlock(&set_limit_mutex);
5000 mutex_unlock(&memcg_create_mutex);
5005 #ifdef CONFIG_MEMCG_KMEM
5006 static int memcg_propagate_kmem(struct mem_cgroup *memcg)
5009 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
5013 memcg->kmem_account_flags = parent->kmem_account_flags;
5015 * When that happen, we need to disable the static branch only on those
5016 * memcgs that enabled it. To achieve this, we would be forced to
5017 * complicate the code by keeping track of which memcgs were the ones
5018 * that actually enabled limits, and which ones got it from its
5021 * It is a lot simpler just to do static_key_slow_inc() on every child
5022 * that is accounted.
5024 if (!memcg_kmem_is_active(memcg))
5028 * __mem_cgroup_free() will issue static_key_slow_dec() because this
5029 * memcg is active already. If the later initialization fails then the
5030 * cgroup core triggers the cleanup so we do not have to do it here.
5032 static_key_slow_inc(&memcg_kmem_enabled_key);
5034 mutex_lock(&set_limit_mutex);
5035 memcg_stop_kmem_account();
5036 ret = memcg_update_cache_sizes(memcg);
5037 memcg_resume_kmem_account();
5038 mutex_unlock(&set_limit_mutex);
5042 #endif /* CONFIG_MEMCG_KMEM */
5045 * The user of this function is...
5048 static int mem_cgroup_write(struct cgroup_subsys_state *css, struct cftype *cft,
5051 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5054 unsigned long long val;
5057 type = MEMFILE_TYPE(cft->private);
5058 name = MEMFILE_ATTR(cft->private);
5062 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
5066 /* This function does all necessary parse...reuse it */
5067 ret = res_counter_memparse_write_strategy(buffer, &val);
5071 ret = mem_cgroup_resize_limit(memcg, val);
5072 else if (type == _MEMSWAP)
5073 ret = mem_cgroup_resize_memsw_limit(memcg, val);
5074 else if (type == _KMEM)
5075 ret = memcg_update_kmem_limit(css, val);
5079 case RES_SOFT_LIMIT:
5080 ret = res_counter_memparse_write_strategy(buffer, &val);
5084 * For memsw, soft limits are hard to implement in terms
5085 * of semantics, for now, we support soft limits for
5086 * control without swap
5089 ret = res_counter_set_soft_limit(&memcg->res, val);
5094 ret = -EINVAL; /* should be BUG() ? */
5100 static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
5101 unsigned long long *mem_limit, unsigned long long *memsw_limit)
5103 unsigned long long min_limit, min_memsw_limit, tmp;
5105 min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
5106 min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
5107 if (!memcg->use_hierarchy)
5110 while (css_parent(&memcg->css)) {
5111 memcg = mem_cgroup_from_css(css_parent(&memcg->css));
5112 if (!memcg->use_hierarchy)
5114 tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
5115 min_limit = min(min_limit, tmp);
5116 tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
5117 min_memsw_limit = min(min_memsw_limit, tmp);
5120 *mem_limit = min_limit;
5121 *memsw_limit = min_memsw_limit;
5124 static int mem_cgroup_reset(struct cgroup_subsys_state *css, unsigned int event)
5126 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5130 type = MEMFILE_TYPE(event);
5131 name = MEMFILE_ATTR(event);
5136 res_counter_reset_max(&memcg->res);
5137 else if (type == _MEMSWAP)
5138 res_counter_reset_max(&memcg->memsw);
5139 else if (type == _KMEM)
5140 res_counter_reset_max(&memcg->kmem);
5146 res_counter_reset_failcnt(&memcg->res);
5147 else if (type == _MEMSWAP)
5148 res_counter_reset_failcnt(&memcg->memsw);
5149 else if (type == _KMEM)
5150 res_counter_reset_failcnt(&memcg->kmem);
5159 static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
5162 return mem_cgroup_from_css(css)->move_charge_at_immigrate;
5166 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
5167 struct cftype *cft, u64 val)
5169 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5171 if (val >= (1 << NR_MOVE_TYPE))
5175 * No kind of locking is needed in here, because ->can_attach() will
5176 * check this value once in the beginning of the process, and then carry
5177 * on with stale data. This means that changes to this value will only
5178 * affect task migrations starting after the change.
5180 memcg->move_charge_at_immigrate = val;
5184 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
5185 struct cftype *cft, u64 val)
5192 static int memcg_numa_stat_show(struct cgroup_subsys_state *css,
5193 struct cftype *cft, struct seq_file *m)
5196 unsigned long total_nr, file_nr, anon_nr, unevictable_nr;
5197 unsigned long node_nr;
5198 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5200 total_nr = mem_cgroup_nr_lru_pages(memcg, LRU_ALL);
5201 seq_printf(m, "total=%lu", total_nr);
5202 for_each_node_state(nid, N_MEMORY) {
5203 node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL);
5204 seq_printf(m, " N%d=%lu", nid, node_nr);
5208 file_nr = mem_cgroup_nr_lru_pages(memcg, LRU_ALL_FILE);
5209 seq_printf(m, "file=%lu", file_nr);
5210 for_each_node_state(nid, N_MEMORY) {
5211 node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
5213 seq_printf(m, " N%d=%lu", nid, node_nr);
5217 anon_nr = mem_cgroup_nr_lru_pages(memcg, LRU_ALL_ANON);
5218 seq_printf(m, "anon=%lu", anon_nr);
5219 for_each_node_state(nid, N_MEMORY) {
5220 node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
5222 seq_printf(m, " N%d=%lu", nid, node_nr);
5226 unevictable_nr = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_UNEVICTABLE));
5227 seq_printf(m, "unevictable=%lu", unevictable_nr);
5228 for_each_node_state(nid, N_MEMORY) {
5229 node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
5230 BIT(LRU_UNEVICTABLE));
5231 seq_printf(m, " N%d=%lu", nid, node_nr);
5236 #endif /* CONFIG_NUMA */
5238 static inline void mem_cgroup_lru_names_not_uptodate(void)
5240 BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_lru_names) != NR_LRU_LISTS);
5243 static int memcg_stat_show(struct cgroup_subsys_state *css, struct cftype *cft,
5246 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5247 struct mem_cgroup *mi;
5250 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
5251 if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
5253 seq_printf(m, "%s %ld\n", mem_cgroup_stat_names[i],
5254 mem_cgroup_read_stat(memcg, i) * PAGE_SIZE);
5257 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++)
5258 seq_printf(m, "%s %lu\n", mem_cgroup_events_names[i],
5259 mem_cgroup_read_events(memcg, i));
5261 for (i = 0; i < NR_LRU_LISTS; i++)
5262 seq_printf(m, "%s %lu\n", mem_cgroup_lru_names[i],
5263 mem_cgroup_nr_lru_pages(memcg, BIT(i)) * PAGE_SIZE);
5265 /* Hierarchical information */
5267 unsigned long long limit, memsw_limit;
5268 memcg_get_hierarchical_limit(memcg, &limit, &memsw_limit);
5269 seq_printf(m, "hierarchical_memory_limit %llu\n", limit);
5270 if (do_swap_account)
5271 seq_printf(m, "hierarchical_memsw_limit %llu\n",
5275 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
5278 if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
5280 for_each_mem_cgroup_tree(mi, memcg)
5281 val += mem_cgroup_read_stat(mi, i) * PAGE_SIZE;
5282 seq_printf(m, "total_%s %lld\n", mem_cgroup_stat_names[i], val);
5285 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
5286 unsigned long long val = 0;
5288 for_each_mem_cgroup_tree(mi, memcg)
5289 val += mem_cgroup_read_events(mi, i);
5290 seq_printf(m, "total_%s %llu\n",
5291 mem_cgroup_events_names[i], val);
5294 for (i = 0; i < NR_LRU_LISTS; i++) {
5295 unsigned long long val = 0;
5297 for_each_mem_cgroup_tree(mi, memcg)
5298 val += mem_cgroup_nr_lru_pages(mi, BIT(i)) * PAGE_SIZE;
5299 seq_printf(m, "total_%s %llu\n", mem_cgroup_lru_names[i], val);
5302 #ifdef CONFIG_DEBUG_VM
5305 struct mem_cgroup_per_zone *mz;
5306 struct zone_reclaim_stat *rstat;
5307 unsigned long recent_rotated[2] = {0, 0};
5308 unsigned long recent_scanned[2] = {0, 0};
5310 for_each_online_node(nid)
5311 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
5312 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
5313 rstat = &mz->lruvec.reclaim_stat;
5315 recent_rotated[0] += rstat->recent_rotated[0];
5316 recent_rotated[1] += rstat->recent_rotated[1];
5317 recent_scanned[0] += rstat->recent_scanned[0];
5318 recent_scanned[1] += rstat->recent_scanned[1];
5320 seq_printf(m, "recent_rotated_anon %lu\n", recent_rotated[0]);
5321 seq_printf(m, "recent_rotated_file %lu\n", recent_rotated[1]);
5322 seq_printf(m, "recent_scanned_anon %lu\n", recent_scanned[0]);
5323 seq_printf(m, "recent_scanned_file %lu\n", recent_scanned[1]);
5330 static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
5333 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5335 return mem_cgroup_swappiness(memcg);
5338 static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
5339 struct cftype *cft, u64 val)
5341 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5342 struct mem_cgroup *parent = mem_cgroup_from_css(css_parent(&memcg->css));
5344 if (val > 100 || !parent)
5347 mutex_lock(&memcg_create_mutex);
5349 /* If under hierarchy, only empty-root can set this value */
5350 if ((parent->use_hierarchy) || memcg_has_children(memcg)) {
5351 mutex_unlock(&memcg_create_mutex);
5355 memcg->swappiness = val;
5357 mutex_unlock(&memcg_create_mutex);
5362 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
5364 struct mem_cgroup_threshold_ary *t;
5370 t = rcu_dereference(memcg->thresholds.primary);
5372 t = rcu_dereference(memcg->memsw_thresholds.primary);
5377 usage = mem_cgroup_usage(memcg, swap);
5380 * current_threshold points to threshold just below or equal to usage.
5381 * If it's not true, a threshold was crossed after last
5382 * call of __mem_cgroup_threshold().
5384 i = t->current_threshold;
5387 * Iterate backward over array of thresholds starting from
5388 * current_threshold and check if a threshold is crossed.
5389 * If none of thresholds below usage is crossed, we read
5390 * only one element of the array here.
5392 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
5393 eventfd_signal(t->entries[i].eventfd, 1);
5395 /* i = current_threshold + 1 */
5399 * Iterate forward over array of thresholds starting from
5400 * current_threshold+1 and check if a threshold is crossed.
5401 * If none of thresholds above usage is crossed, we read
5402 * only one element of the array here.
5404 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
5405 eventfd_signal(t->entries[i].eventfd, 1);
5407 /* Update current_threshold */
5408 t->current_threshold = i - 1;
5413 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
5416 __mem_cgroup_threshold(memcg, false);
5417 if (do_swap_account)
5418 __mem_cgroup_threshold(memcg, true);
5420 memcg = parent_mem_cgroup(memcg);
5424 static int compare_thresholds(const void *a, const void *b)
5426 const struct mem_cgroup_threshold *_a = a;
5427 const struct mem_cgroup_threshold *_b = b;
5429 if (_a->threshold > _b->threshold)
5432 if (_a->threshold < _b->threshold)
5438 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
5440 struct mem_cgroup_eventfd_list *ev;
5442 list_for_each_entry(ev, &memcg->oom_notify, list)
5443 eventfd_signal(ev->eventfd, 1);
5447 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
5449 struct mem_cgroup *iter;
5451 for_each_mem_cgroup_tree(iter, memcg)
5452 mem_cgroup_oom_notify_cb(iter);
5455 static int mem_cgroup_usage_register_event(struct cgroup_subsys_state *css,
5456 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
5458 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5459 struct mem_cgroup_thresholds *thresholds;
5460 struct mem_cgroup_threshold_ary *new;
5461 enum res_type type = MEMFILE_TYPE(cft->private);
5462 u64 threshold, usage;
5465 ret = res_counter_memparse_write_strategy(args, &threshold);
5469 mutex_lock(&memcg->thresholds_lock);
5472 thresholds = &memcg->thresholds;
5473 else if (type == _MEMSWAP)
5474 thresholds = &memcg->memsw_thresholds;
5478 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
5480 /* Check if a threshold crossed before adding a new one */
5481 if (thresholds->primary)
5482 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
5484 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
5486 /* Allocate memory for new array of thresholds */
5487 new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
5495 /* Copy thresholds (if any) to new array */
5496 if (thresholds->primary) {
5497 memcpy(new->entries, thresholds->primary->entries, (size - 1) *
5498 sizeof(struct mem_cgroup_threshold));
5501 /* Add new threshold */
5502 new->entries[size - 1].eventfd = eventfd;
5503 new->entries[size - 1].threshold = threshold;
5505 /* Sort thresholds. Registering of new threshold isn't time-critical */
5506 sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
5507 compare_thresholds, NULL);
5509 /* Find current threshold */
5510 new->current_threshold = -1;
5511 for (i = 0; i < size; i++) {
5512 if (new->entries[i].threshold <= usage) {
5514 * new->current_threshold will not be used until
5515 * rcu_assign_pointer(), so it's safe to increment
5518 ++new->current_threshold;
5523 /* Free old spare buffer and save old primary buffer as spare */
5524 kfree(thresholds->spare);
5525 thresholds->spare = thresholds->primary;
5527 rcu_assign_pointer(thresholds->primary, new);
5529 /* To be sure that nobody uses thresholds */
5533 mutex_unlock(&memcg->thresholds_lock);
5538 static void mem_cgroup_usage_unregister_event(struct cgroup_subsys_state *css,
5539 struct cftype *cft, struct eventfd_ctx *eventfd)
5541 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5542 struct mem_cgroup_thresholds *thresholds;
5543 struct mem_cgroup_threshold_ary *new;
5544 enum res_type type = MEMFILE_TYPE(cft->private);
5548 mutex_lock(&memcg->thresholds_lock);
5550 thresholds = &memcg->thresholds;
5551 else if (type == _MEMSWAP)
5552 thresholds = &memcg->memsw_thresholds;
5556 if (!thresholds->primary)
5559 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
5561 /* Check if a threshold crossed before removing */
5562 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
5564 /* Calculate new number of threshold */
5566 for (i = 0; i < thresholds->primary->size; i++) {
5567 if (thresholds->primary->entries[i].eventfd != eventfd)
5571 new = thresholds->spare;
5573 /* Set thresholds array to NULL if we don't have thresholds */
5582 /* Copy thresholds and find current threshold */
5583 new->current_threshold = -1;
5584 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
5585 if (thresholds->primary->entries[i].eventfd == eventfd)
5588 new->entries[j] = thresholds->primary->entries[i];
5589 if (new->entries[j].threshold <= usage) {
5591 * new->current_threshold will not be used
5592 * until rcu_assign_pointer(), so it's safe to increment
5595 ++new->current_threshold;
5601 /* Swap primary and spare array */
5602 thresholds->spare = thresholds->primary;
5603 /* If all events are unregistered, free the spare array */
5605 kfree(thresholds->spare);
5606 thresholds->spare = NULL;
5609 rcu_assign_pointer(thresholds->primary, new);
5611 /* To be sure that nobody uses thresholds */
5614 mutex_unlock(&memcg->thresholds_lock);
5617 static int mem_cgroup_oom_register_event(struct cgroup_subsys_state *css,
5618 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
5620 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5621 struct mem_cgroup_eventfd_list *event;
5622 enum res_type type = MEMFILE_TYPE(cft->private);
5624 BUG_ON(type != _OOM_TYPE);
5625 event = kmalloc(sizeof(*event), GFP_KERNEL);
5629 spin_lock(&memcg_oom_lock);
5631 event->eventfd = eventfd;
5632 list_add(&event->list, &memcg->oom_notify);
5634 /* already in OOM ? */
5635 if (atomic_read(&memcg->under_oom))
5636 eventfd_signal(eventfd, 1);
5637 spin_unlock(&memcg_oom_lock);
5642 static void mem_cgroup_oom_unregister_event(struct cgroup_subsys_state *css,
5643 struct cftype *cft, struct eventfd_ctx *eventfd)
5645 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5646 struct mem_cgroup_eventfd_list *ev, *tmp;
5647 enum res_type type = MEMFILE_TYPE(cft->private);
5649 BUG_ON(type != _OOM_TYPE);
5651 spin_lock(&memcg_oom_lock);
5653 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
5654 if (ev->eventfd == eventfd) {
5655 list_del(&ev->list);
5660 spin_unlock(&memcg_oom_lock);
5663 static int mem_cgroup_oom_control_read(struct cgroup_subsys_state *css,
5664 struct cftype *cft, struct cgroup_map_cb *cb)
5666 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5668 cb->fill(cb, "oom_kill_disable", memcg->oom_kill_disable);
5670 if (atomic_read(&memcg->under_oom))
5671 cb->fill(cb, "under_oom", 1);
5673 cb->fill(cb, "under_oom", 0);
5677 static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
5678 struct cftype *cft, u64 val)
5680 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5681 struct mem_cgroup *parent = mem_cgroup_from_css(css_parent(&memcg->css));
5683 /* cannot set to root cgroup and only 0 and 1 are allowed */
5684 if (!parent || !((val == 0) || (val == 1)))
5687 mutex_lock(&memcg_create_mutex);
5688 /* oom-kill-disable is a flag for subhierarchy. */
5689 if ((parent->use_hierarchy) || memcg_has_children(memcg)) {
5690 mutex_unlock(&memcg_create_mutex);
5693 memcg->oom_kill_disable = val;
5695 memcg_oom_recover(memcg);
5696 mutex_unlock(&memcg_create_mutex);
5700 #ifdef CONFIG_MEMCG_KMEM
5701 static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
5705 memcg->kmemcg_id = -1;
5706 ret = memcg_propagate_kmem(memcg);
5710 return mem_cgroup_sockets_init(memcg, ss);
5713 static void memcg_destroy_kmem(struct mem_cgroup *memcg)
5715 mem_cgroup_sockets_destroy(memcg);
5718 static void kmem_cgroup_css_offline(struct mem_cgroup *memcg)
5720 if (!memcg_kmem_is_active(memcg))
5724 * kmem charges can outlive the cgroup. In the case of slab
5725 * pages, for instance, a page contain objects from various
5726 * processes. As we prevent from taking a reference for every
5727 * such allocation we have to be careful when doing uncharge
5728 * (see memcg_uncharge_kmem) and here during offlining.
5730 * The idea is that that only the _last_ uncharge which sees
5731 * the dead memcg will drop the last reference. An additional
5732 * reference is taken here before the group is marked dead
5733 * which is then paired with css_put during uncharge resp. here.
5735 * Although this might sound strange as this path is called from
5736 * css_offline() when the referencemight have dropped down to 0
5737 * and shouldn't be incremented anymore (css_tryget would fail)
5738 * we do not have other options because of the kmem allocations
5741 css_get(&memcg->css);
5743 memcg_kmem_mark_dead(memcg);
5745 if (res_counter_read_u64(&memcg->kmem, RES_USAGE) != 0)
5748 if (memcg_kmem_test_and_clear_dead(memcg))
5749 css_put(&memcg->css);
5752 static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
5757 static void memcg_destroy_kmem(struct mem_cgroup *memcg)
5761 static void kmem_cgroup_css_offline(struct mem_cgroup *memcg)
5766 static struct cftype mem_cgroup_files[] = {
5768 .name = "usage_in_bytes",
5769 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
5770 .read = mem_cgroup_read,
5771 .register_event = mem_cgroup_usage_register_event,
5772 .unregister_event = mem_cgroup_usage_unregister_event,
5775 .name = "max_usage_in_bytes",
5776 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
5777 .trigger = mem_cgroup_reset,
5778 .read = mem_cgroup_read,
5781 .name = "limit_in_bytes",
5782 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
5783 .write_string = mem_cgroup_write,
5784 .read = mem_cgroup_read,
5787 .name = "soft_limit_in_bytes",
5788 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
5789 .write_string = mem_cgroup_write,
5790 .read = mem_cgroup_read,
5794 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
5795 .trigger = mem_cgroup_reset,
5796 .read = mem_cgroup_read,
5800 .read_seq_string = memcg_stat_show,
5803 .name = "force_empty",
5804 .trigger = mem_cgroup_force_empty_write,
5807 .name = "use_hierarchy",
5808 .flags = CFTYPE_INSANE,
5809 .write_u64 = mem_cgroup_hierarchy_write,
5810 .read_u64 = mem_cgroup_hierarchy_read,
5813 .name = "swappiness",
5814 .read_u64 = mem_cgroup_swappiness_read,
5815 .write_u64 = mem_cgroup_swappiness_write,
5818 .name = "move_charge_at_immigrate",
5819 .read_u64 = mem_cgroup_move_charge_read,
5820 .write_u64 = mem_cgroup_move_charge_write,
5823 .name = "oom_control",
5824 .read_map = mem_cgroup_oom_control_read,
5825 .write_u64 = mem_cgroup_oom_control_write,
5826 .register_event = mem_cgroup_oom_register_event,
5827 .unregister_event = mem_cgroup_oom_unregister_event,
5828 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
5831 .name = "pressure_level",
5832 .register_event = vmpressure_register_event,
5833 .unregister_event = vmpressure_unregister_event,
5837 .name = "numa_stat",
5838 .read_seq_string = memcg_numa_stat_show,
5841 #ifdef CONFIG_MEMCG_KMEM
5843 .name = "kmem.limit_in_bytes",
5844 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
5845 .write_string = mem_cgroup_write,
5846 .read = mem_cgroup_read,
5849 .name = "kmem.usage_in_bytes",
5850 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
5851 .read = mem_cgroup_read,
5854 .name = "kmem.failcnt",
5855 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
5856 .trigger = mem_cgroup_reset,
5857 .read = mem_cgroup_read,
5860 .name = "kmem.max_usage_in_bytes",
5861 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
5862 .trigger = mem_cgroup_reset,
5863 .read = mem_cgroup_read,
5865 #ifdef CONFIG_SLABINFO
5867 .name = "kmem.slabinfo",
5868 .read_seq_string = mem_cgroup_slabinfo_read,
5872 { }, /* terminate */
5875 #ifdef CONFIG_MEMCG_SWAP
5876 static struct cftype memsw_cgroup_files[] = {
5878 .name = "memsw.usage_in_bytes",
5879 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
5880 .read = mem_cgroup_read,
5881 .register_event = mem_cgroup_usage_register_event,
5882 .unregister_event = mem_cgroup_usage_unregister_event,
5885 .name = "memsw.max_usage_in_bytes",
5886 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
5887 .trigger = mem_cgroup_reset,
5888 .read = mem_cgroup_read,
5891 .name = "memsw.limit_in_bytes",
5892 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
5893 .write_string = mem_cgroup_write,
5894 .read = mem_cgroup_read,
5897 .name = "memsw.failcnt",
5898 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
5899 .trigger = mem_cgroup_reset,
5900 .read = mem_cgroup_read,
5902 { }, /* terminate */
5905 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
5907 struct mem_cgroup_per_node *pn;
5908 struct mem_cgroup_per_zone *mz;
5909 int zone, tmp = node;
5911 * This routine is called against possible nodes.
5912 * But it's BUG to call kmalloc() against offline node.
5914 * TODO: this routine can waste much memory for nodes which will
5915 * never be onlined. It's better to use memory hotplug callback
5918 if (!node_state(node, N_NORMAL_MEMORY))
5920 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
5924 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
5925 mz = &pn->zoneinfo[zone];
5926 lruvec_init(&mz->lruvec);
5929 memcg->nodeinfo[node] = pn;
5933 static void free_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
5935 kfree(memcg->nodeinfo[node]);
5938 static struct mem_cgroup *mem_cgroup_alloc(void)
5940 struct mem_cgroup *memcg;
5941 size_t size = memcg_size();
5943 /* Can be very big if nr_node_ids is very big */
5944 if (size < PAGE_SIZE)
5945 memcg = kzalloc(size, GFP_KERNEL);
5947 memcg = vzalloc(size);
5952 memcg->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
5955 spin_lock_init(&memcg->pcp_counter_lock);
5959 if (size < PAGE_SIZE)
5967 * At destroying mem_cgroup, references from swap_cgroup can remain.
5968 * (scanning all at force_empty is too costly...)
5970 * Instead of clearing all references at force_empty, we remember
5971 * the number of reference from swap_cgroup and free mem_cgroup when
5972 * it goes down to 0.
5974 * Removal of cgroup itself succeeds regardless of refs from swap.
5977 static void __mem_cgroup_free(struct mem_cgroup *memcg)
5980 size_t size = memcg_size();
5983 free_mem_cgroup_per_zone_info(memcg, node);
5985 free_percpu(memcg->stat);
5988 * We need to make sure that (at least for now), the jump label
5989 * destruction code runs outside of the cgroup lock. This is because
5990 * get_online_cpus(), which is called from the static_branch update,
5991 * can't be called inside the cgroup_lock. cpusets are the ones
5992 * enforcing this dependency, so if they ever change, we might as well.
5994 * schedule_work() will guarantee this happens. Be careful if you need
5995 * to move this code around, and make sure it is outside
5998 disarm_static_keys(memcg);
5999 if (size < PAGE_SIZE)
6006 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
6008 struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg)
6010 if (!memcg->res.parent)
6012 return mem_cgroup_from_res_counter(memcg->res.parent, res);
6014 EXPORT_SYMBOL(parent_mem_cgroup);
6016 static struct cgroup_subsys_state * __ref
6017 mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
6019 struct mem_cgroup *memcg;
6020 long error = -ENOMEM;
6023 memcg = mem_cgroup_alloc();
6025 return ERR_PTR(error);
6028 if (alloc_mem_cgroup_per_zone_info(memcg, node))
6032 if (parent_css == NULL) {
6033 root_mem_cgroup = memcg;
6034 res_counter_init(&memcg->res, NULL);
6035 res_counter_init(&memcg->memsw, NULL);
6036 res_counter_init(&memcg->kmem, NULL);
6039 memcg->last_scanned_node = MAX_NUMNODES;
6040 INIT_LIST_HEAD(&memcg->oom_notify);
6041 memcg->move_charge_at_immigrate = 0;
6042 mutex_init(&memcg->thresholds_lock);
6043 spin_lock_init(&memcg->move_lock);
6044 vmpressure_init(&memcg->vmpressure);
6045 spin_lock_init(&memcg->soft_lock);
6050 __mem_cgroup_free(memcg);
6051 return ERR_PTR(error);
6055 mem_cgroup_css_online(struct cgroup_subsys_state *css)
6057 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6058 struct mem_cgroup *parent = mem_cgroup_from_css(css_parent(css));
6061 if (css->cgroup->id > MEM_CGROUP_ID_MAX)
6067 mutex_lock(&memcg_create_mutex);
6069 memcg->use_hierarchy = parent->use_hierarchy;
6070 memcg->oom_kill_disable = parent->oom_kill_disable;
6071 memcg->swappiness = mem_cgroup_swappiness(parent);
6073 if (parent->use_hierarchy) {
6074 res_counter_init(&memcg->res, &parent->res);
6075 res_counter_init(&memcg->memsw, &parent->memsw);
6076 res_counter_init(&memcg->kmem, &parent->kmem);
6079 * No need to take a reference to the parent because cgroup
6080 * core guarantees its existence.
6083 res_counter_init(&memcg->res, NULL);
6084 res_counter_init(&memcg->memsw, NULL);
6085 res_counter_init(&memcg->kmem, NULL);
6087 * Deeper hierachy with use_hierarchy == false doesn't make
6088 * much sense so let cgroup subsystem know about this
6089 * unfortunate state in our controller.
6091 if (parent != root_mem_cgroup)
6092 mem_cgroup_subsys.broken_hierarchy = true;
6095 error = memcg_init_kmem(memcg, &mem_cgroup_subsys);
6096 mutex_unlock(&memcg_create_mutex);
6101 * Announce all parents that a group from their hierarchy is gone.
6103 static void mem_cgroup_invalidate_reclaim_iterators(struct mem_cgroup *memcg)
6105 struct mem_cgroup *parent = memcg;
6107 while ((parent = parent_mem_cgroup(parent)))
6108 mem_cgroup_iter_invalidate(parent);
6111 * if the root memcg is not hierarchical we have to check it
6114 if (!root_mem_cgroup->use_hierarchy)
6115 mem_cgroup_iter_invalidate(root_mem_cgroup);
6118 static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
6120 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6122 kmem_cgroup_css_offline(memcg);
6124 mem_cgroup_invalidate_reclaim_iterators(memcg);
6125 mem_cgroup_reparent_charges(memcg);
6126 if (memcg->soft_contributed) {
6127 while ((memcg = parent_mem_cgroup(memcg)))
6128 atomic_dec(&memcg->children_in_excess);
6130 if (memcg != root_mem_cgroup && !root_mem_cgroup->use_hierarchy)
6131 atomic_dec(&root_mem_cgroup->children_in_excess);
6133 mem_cgroup_destroy_all_caches(memcg);
6134 vmpressure_cleanup(&memcg->vmpressure);
6137 static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
6139 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6141 memcg_destroy_kmem(memcg);
6142 __mem_cgroup_free(memcg);
6146 /* Handlers for move charge at task migration. */
6147 #define PRECHARGE_COUNT_AT_ONCE 256
6148 static int mem_cgroup_do_precharge(unsigned long count)
6151 int batch_count = PRECHARGE_COUNT_AT_ONCE;
6152 struct mem_cgroup *memcg = mc.to;
6154 if (mem_cgroup_is_root(memcg)) {
6155 mc.precharge += count;
6156 /* we don't need css_get for root */
6159 /* try to charge at once */
6161 struct res_counter *dummy;
6163 * "memcg" cannot be under rmdir() because we've already checked
6164 * by cgroup_lock_live_cgroup() that it is not removed and we
6165 * are still under the same cgroup_mutex. So we can postpone
6168 if (res_counter_charge(&memcg->res, PAGE_SIZE * count, &dummy))
6170 if (do_swap_account && res_counter_charge(&memcg->memsw,
6171 PAGE_SIZE * count, &dummy)) {
6172 res_counter_uncharge(&memcg->res, PAGE_SIZE * count);
6175 mc.precharge += count;
6179 /* fall back to one by one charge */
6181 if (signal_pending(current)) {
6185 if (!batch_count--) {
6186 batch_count = PRECHARGE_COUNT_AT_ONCE;
6189 ret = __mem_cgroup_try_charge(NULL,
6190 GFP_KERNEL, 1, &memcg, false);
6192 /* mem_cgroup_clear_mc() will do uncharge later */
6200 * get_mctgt_type - get target type of moving charge
6201 * @vma: the vma the pte to be checked belongs
6202 * @addr: the address corresponding to the pte to be checked
6203 * @ptent: the pte to be checked
6204 * @target: the pointer the target page or swap ent will be stored(can be NULL)
6207 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
6208 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
6209 * move charge. if @target is not NULL, the page is stored in target->page
6210 * with extra refcnt got(Callers should handle it).
6211 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
6212 * target for charge migration. if @target is not NULL, the entry is stored
6215 * Called with pte lock held.
6222 enum mc_target_type {
6228 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
6229 unsigned long addr, pte_t ptent)
6231 struct page *page = vm_normal_page(vma, addr, ptent);
6233 if (!page || !page_mapped(page))
6235 if (PageAnon(page)) {
6236 /* we don't move shared anon */
6239 } else if (!move_file())
6240 /* we ignore mapcount for file pages */
6242 if (!get_page_unless_zero(page))
6249 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
6250 unsigned long addr, pte_t ptent, swp_entry_t *entry)
6252 struct page *page = NULL;
6253 swp_entry_t ent = pte_to_swp_entry(ptent);
6255 if (!move_anon() || non_swap_entry(ent))
6258 * Because lookup_swap_cache() updates some statistics counter,
6259 * we call find_get_page() with swapper_space directly.
6261 page = find_get_page(swap_address_space(ent), ent.val);
6262 if (do_swap_account)
6263 entry->val = ent.val;
6268 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
6269 unsigned long addr, pte_t ptent, swp_entry_t *entry)
6275 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
6276 unsigned long addr, pte_t ptent, swp_entry_t *entry)
6278 struct page *page = NULL;
6279 struct address_space *mapping;
6282 if (!vma->vm_file) /* anonymous vma */
6287 mapping = vma->vm_file->f_mapping;
6288 if (pte_none(ptent))
6289 pgoff = linear_page_index(vma, addr);
6290 else /* pte_file(ptent) is true */
6291 pgoff = pte_to_pgoff(ptent);
6293 /* page is moved even if it's not RSS of this task(page-faulted). */
6294 page = find_get_page(mapping, pgoff);
6297 /* shmem/tmpfs may report page out on swap: account for that too. */
6298 if (radix_tree_exceptional_entry(page)) {
6299 swp_entry_t swap = radix_to_swp_entry(page);
6300 if (do_swap_account)
6302 page = find_get_page(swap_address_space(swap), swap.val);
6308 static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
6309 unsigned long addr, pte_t ptent, union mc_target *target)
6311 struct page *page = NULL;
6312 struct page_cgroup *pc;
6313 enum mc_target_type ret = MC_TARGET_NONE;
6314 swp_entry_t ent = { .val = 0 };
6316 if (pte_present(ptent))
6317 page = mc_handle_present_pte(vma, addr, ptent);
6318 else if (is_swap_pte(ptent))
6319 page = mc_handle_swap_pte(vma, addr, ptent, &ent);
6320 else if (pte_none(ptent) || pte_file(ptent))
6321 page = mc_handle_file_pte(vma, addr, ptent, &ent);
6323 if (!page && !ent.val)
6326 pc = lookup_page_cgroup(page);
6328 * Do only loose check w/o page_cgroup lock.
6329 * mem_cgroup_move_account() checks the pc is valid or not under
6332 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
6333 ret = MC_TARGET_PAGE;
6335 target->page = page;
6337 if (!ret || !target)
6340 /* There is a swap entry and a page doesn't exist or isn't charged */
6341 if (ent.val && !ret &&
6342 mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
6343 ret = MC_TARGET_SWAP;
6350 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
6352 * We don't consider swapping or file mapped pages because THP does not
6353 * support them for now.
6354 * Caller should make sure that pmd_trans_huge(pmd) is true.
6356 static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
6357 unsigned long addr, pmd_t pmd, union mc_target *target)
6359 struct page *page = NULL;
6360 struct page_cgroup *pc;
6361 enum mc_target_type ret = MC_TARGET_NONE;
6363 page = pmd_page(pmd);
6364 VM_BUG_ON(!page || !PageHead(page));
6367 pc = lookup_page_cgroup(page);
6368 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
6369 ret = MC_TARGET_PAGE;
6372 target->page = page;
6378 static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
6379 unsigned long addr, pmd_t pmd, union mc_target *target)
6381 return MC_TARGET_NONE;
6385 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
6386 unsigned long addr, unsigned long end,
6387 struct mm_walk *walk)
6389 struct vm_area_struct *vma = walk->private;
6393 if (pmd_trans_huge_lock(pmd, vma) == 1) {
6394 if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
6395 mc.precharge += HPAGE_PMD_NR;
6396 spin_unlock(&vma->vm_mm->page_table_lock);
6400 if (pmd_trans_unstable(pmd))
6402 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6403 for (; addr != end; pte++, addr += PAGE_SIZE)
6404 if (get_mctgt_type(vma, addr, *pte, NULL))
6405 mc.precharge++; /* increment precharge temporarily */
6406 pte_unmap_unlock(pte - 1, ptl);
6412 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
6414 unsigned long precharge;
6415 struct vm_area_struct *vma;
6417 down_read(&mm->mmap_sem);
6418 for (vma = mm->mmap; vma; vma = vma->vm_next) {
6419 struct mm_walk mem_cgroup_count_precharge_walk = {
6420 .pmd_entry = mem_cgroup_count_precharge_pte_range,
6424 if (is_vm_hugetlb_page(vma))
6426 walk_page_range(vma->vm_start, vma->vm_end,
6427 &mem_cgroup_count_precharge_walk);
6429 up_read(&mm->mmap_sem);
6431 precharge = mc.precharge;
6437 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
6439 unsigned long precharge = mem_cgroup_count_precharge(mm);
6441 VM_BUG_ON(mc.moving_task);
6442 mc.moving_task = current;
6443 return mem_cgroup_do_precharge(precharge);
6446 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
6447 static void __mem_cgroup_clear_mc(void)
6449 struct mem_cgroup *from = mc.from;
6450 struct mem_cgroup *to = mc.to;
6453 /* we must uncharge all the leftover precharges from mc.to */
6455 __mem_cgroup_cancel_charge(mc.to, mc.precharge);
6459 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
6460 * we must uncharge here.
6462 if (mc.moved_charge) {
6463 __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
6464 mc.moved_charge = 0;
6466 /* we must fixup refcnts and charges */
6467 if (mc.moved_swap) {
6468 /* uncharge swap account from the old cgroup */
6469 if (!mem_cgroup_is_root(mc.from))
6470 res_counter_uncharge(&mc.from->memsw,
6471 PAGE_SIZE * mc.moved_swap);
6473 for (i = 0; i < mc.moved_swap; i++)
6474 css_put(&mc.from->css);
6476 if (!mem_cgroup_is_root(mc.to)) {
6478 * we charged both to->res and to->memsw, so we should
6481 res_counter_uncharge(&mc.to->res,
6482 PAGE_SIZE * mc.moved_swap);
6484 /* we've already done css_get(mc.to) */
6487 memcg_oom_recover(from);
6488 memcg_oom_recover(to);
6489 wake_up_all(&mc.waitq);
6492 static void mem_cgroup_clear_mc(void)
6494 struct mem_cgroup *from = mc.from;
6497 * we must clear moving_task before waking up waiters at the end of
6500 mc.moving_task = NULL;
6501 __mem_cgroup_clear_mc();
6502 spin_lock(&mc.lock);
6505 spin_unlock(&mc.lock);
6506 mem_cgroup_end_move(from);
6509 static int mem_cgroup_can_attach(struct cgroup_subsys_state *css,
6510 struct cgroup_taskset *tset)
6512 struct task_struct *p = cgroup_taskset_first(tset);
6514 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6515 unsigned long move_charge_at_immigrate;
6518 * We are now commited to this value whatever it is. Changes in this
6519 * tunable will only affect upcoming migrations, not the current one.
6520 * So we need to save it, and keep it going.
6522 move_charge_at_immigrate = memcg->move_charge_at_immigrate;
6523 if (move_charge_at_immigrate) {
6524 struct mm_struct *mm;
6525 struct mem_cgroup *from = mem_cgroup_from_task(p);
6527 VM_BUG_ON(from == memcg);
6529 mm = get_task_mm(p);
6532 /* We move charges only when we move a owner of the mm */
6533 if (mm->owner == p) {
6536 VM_BUG_ON(mc.precharge);
6537 VM_BUG_ON(mc.moved_charge);
6538 VM_BUG_ON(mc.moved_swap);
6539 mem_cgroup_start_move(from);
6540 spin_lock(&mc.lock);
6543 mc.immigrate_flags = move_charge_at_immigrate;
6544 spin_unlock(&mc.lock);
6545 /* We set mc.moving_task later */
6547 ret = mem_cgroup_precharge_mc(mm);
6549 mem_cgroup_clear_mc();
6556 static void mem_cgroup_cancel_attach(struct cgroup_subsys_state *css,
6557 struct cgroup_taskset *tset)
6559 mem_cgroup_clear_mc();
6562 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
6563 unsigned long addr, unsigned long end,
6564 struct mm_walk *walk)
6567 struct vm_area_struct *vma = walk->private;
6570 enum mc_target_type target_type;
6571 union mc_target target;
6573 struct page_cgroup *pc;
6576 * We don't take compound_lock() here but no race with splitting thp
6578 * - if pmd_trans_huge_lock() returns 1, the relevant thp is not
6579 * under splitting, which means there's no concurrent thp split,
6580 * - if another thread runs into split_huge_page() just after we
6581 * entered this if-block, the thread must wait for page table lock
6582 * to be unlocked in __split_huge_page_splitting(), where the main
6583 * part of thp split is not executed yet.
6585 if (pmd_trans_huge_lock(pmd, vma) == 1) {
6586 if (mc.precharge < HPAGE_PMD_NR) {
6587 spin_unlock(&vma->vm_mm->page_table_lock);
6590 target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
6591 if (target_type == MC_TARGET_PAGE) {
6593 if (!isolate_lru_page(page)) {
6594 pc = lookup_page_cgroup(page);
6595 if (!mem_cgroup_move_account(page, HPAGE_PMD_NR,
6596 pc, mc.from, mc.to)) {
6597 mc.precharge -= HPAGE_PMD_NR;
6598 mc.moved_charge += HPAGE_PMD_NR;
6600 putback_lru_page(page);
6604 spin_unlock(&vma->vm_mm->page_table_lock);
6608 if (pmd_trans_unstable(pmd))
6611 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6612 for (; addr != end; addr += PAGE_SIZE) {
6613 pte_t ptent = *(pte++);
6619 switch (get_mctgt_type(vma, addr, ptent, &target)) {
6620 case MC_TARGET_PAGE:
6622 if (isolate_lru_page(page))
6624 pc = lookup_page_cgroup(page);
6625 if (!mem_cgroup_move_account(page, 1, pc,
6628 /* we uncharge from mc.from later. */
6631 putback_lru_page(page);
6632 put: /* get_mctgt_type() gets the page */
6635 case MC_TARGET_SWAP:
6637 if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
6639 /* we fixup refcnts and charges later. */
6647 pte_unmap_unlock(pte - 1, ptl);
6652 * We have consumed all precharges we got in can_attach().
6653 * We try charge one by one, but don't do any additional
6654 * charges to mc.to if we have failed in charge once in attach()
6657 ret = mem_cgroup_do_precharge(1);
6665 static void mem_cgroup_move_charge(struct mm_struct *mm)
6667 struct vm_area_struct *vma;
6669 lru_add_drain_all();
6671 if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
6673 * Someone who are holding the mmap_sem might be waiting in
6674 * waitq. So we cancel all extra charges, wake up all waiters,
6675 * and retry. Because we cancel precharges, we might not be able
6676 * to move enough charges, but moving charge is a best-effort
6677 * feature anyway, so it wouldn't be a big problem.
6679 __mem_cgroup_clear_mc();
6683 for (vma = mm->mmap; vma; vma = vma->vm_next) {
6685 struct mm_walk mem_cgroup_move_charge_walk = {
6686 .pmd_entry = mem_cgroup_move_charge_pte_range,
6690 if (is_vm_hugetlb_page(vma))
6692 ret = walk_page_range(vma->vm_start, vma->vm_end,
6693 &mem_cgroup_move_charge_walk);
6696 * means we have consumed all precharges and failed in
6697 * doing additional charge. Just abandon here.
6701 up_read(&mm->mmap_sem);
6704 static void mem_cgroup_move_task(struct cgroup_subsys_state *css,
6705 struct cgroup_taskset *tset)
6707 struct task_struct *p = cgroup_taskset_first(tset);
6708 struct mm_struct *mm = get_task_mm(p);
6712 mem_cgroup_move_charge(mm);
6716 mem_cgroup_clear_mc();
6718 #else /* !CONFIG_MMU */
6719 static int mem_cgroup_can_attach(struct cgroup_subsys_state *css,
6720 struct cgroup_taskset *tset)
6724 static void mem_cgroup_cancel_attach(struct cgroup_subsys_state *css,
6725 struct cgroup_taskset *tset)
6728 static void mem_cgroup_move_task(struct cgroup_subsys_state *css,
6729 struct cgroup_taskset *tset)
6735 * Cgroup retains root cgroups across [un]mount cycles making it necessary
6736 * to verify sane_behavior flag on each mount attempt.
6738 static void mem_cgroup_bind(struct cgroup_subsys_state *root_css)
6741 * use_hierarchy is forced with sane_behavior. cgroup core
6742 * guarantees that @root doesn't have any children, so turning it
6743 * on for the root memcg is enough.
6745 if (cgroup_sane_behavior(root_css->cgroup))
6746 mem_cgroup_from_css(root_css)->use_hierarchy = true;
6749 struct cgroup_subsys mem_cgroup_subsys = {
6751 .subsys_id = mem_cgroup_subsys_id,
6752 .css_alloc = mem_cgroup_css_alloc,
6753 .css_online = mem_cgroup_css_online,
6754 .css_offline = mem_cgroup_css_offline,
6755 .css_free = mem_cgroup_css_free,
6756 .can_attach = mem_cgroup_can_attach,
6757 .cancel_attach = mem_cgroup_cancel_attach,
6758 .attach = mem_cgroup_move_task,
6759 .bind = mem_cgroup_bind,
6760 .base_cftypes = mem_cgroup_files,
6764 #ifdef CONFIG_MEMCG_SWAP
6765 static int __init enable_swap_account(char *s)
6767 if (!strcmp(s, "1"))
6768 really_do_swap_account = 1;
6769 else if (!strcmp(s, "0"))
6770 really_do_swap_account = 0;
6773 __setup("swapaccount=", enable_swap_account);
6775 static void __init memsw_file_init(void)
6777 WARN_ON(cgroup_add_cftypes(&mem_cgroup_subsys, memsw_cgroup_files));
6780 static void __init enable_swap_cgroup(void)
6782 if (!mem_cgroup_disabled() && really_do_swap_account) {
6783 do_swap_account = 1;
6789 static void __init enable_swap_cgroup(void)
6795 * subsys_initcall() for memory controller.
6797 * Some parts like hotcpu_notifier() have to be initialized from this context
6798 * because of lock dependencies (cgroup_lock -> cpu hotplug) but basically
6799 * everything that doesn't depend on a specific mem_cgroup structure should
6800 * be initialized from here.
6802 static int __init mem_cgroup_init(void)
6804 hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
6805 enable_swap_cgroup();
6809 subsys_initcall(mem_cgroup_init);