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);
491 static inline unsigned short mem_cgroup_id(struct mem_cgroup *memcg)
494 * The ID of the root cgroup is 0, but memcg treat 0 as an
495 * invalid ID, so we return (cgroup_id + 1).
497 return memcg->css.cgroup->id + 1;
500 static inline struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
502 struct cgroup_subsys_state *css;
504 css = css_from_id(id - 1, &mem_cgroup_subsys);
505 return mem_cgroup_from_css(css);
508 /* Writing them here to avoid exposing memcg's inner layout */
509 #if defined(CONFIG_INET) && defined(CONFIG_MEMCG_KMEM)
511 void sock_update_memcg(struct sock *sk)
513 if (mem_cgroup_sockets_enabled) {
514 struct mem_cgroup *memcg;
515 struct cg_proto *cg_proto;
517 BUG_ON(!sk->sk_prot->proto_cgroup);
519 /* Socket cloning can throw us here with sk_cgrp already
520 * filled. It won't however, necessarily happen from
521 * process context. So the test for root memcg given
522 * the current task's memcg won't help us in this case.
524 * Respecting the original socket's memcg is a better
525 * decision in this case.
528 BUG_ON(mem_cgroup_is_root(sk->sk_cgrp->memcg));
529 css_get(&sk->sk_cgrp->memcg->css);
534 memcg = mem_cgroup_from_task(current);
535 cg_proto = sk->sk_prot->proto_cgroup(memcg);
536 if (!mem_cgroup_is_root(memcg) &&
537 memcg_proto_active(cg_proto) && css_tryget(&memcg->css)) {
538 sk->sk_cgrp = cg_proto;
543 EXPORT_SYMBOL(sock_update_memcg);
545 void sock_release_memcg(struct sock *sk)
547 if (mem_cgroup_sockets_enabled && sk->sk_cgrp) {
548 struct mem_cgroup *memcg;
549 WARN_ON(!sk->sk_cgrp->memcg);
550 memcg = sk->sk_cgrp->memcg;
551 css_put(&sk->sk_cgrp->memcg->css);
555 struct cg_proto *tcp_proto_cgroup(struct mem_cgroup *memcg)
557 if (!memcg || mem_cgroup_is_root(memcg))
560 return &memcg->tcp_mem.cg_proto;
562 EXPORT_SYMBOL(tcp_proto_cgroup);
564 static void disarm_sock_keys(struct mem_cgroup *memcg)
566 if (!memcg_proto_activated(&memcg->tcp_mem.cg_proto))
568 static_key_slow_dec(&memcg_socket_limit_enabled);
571 static void disarm_sock_keys(struct mem_cgroup *memcg)
576 #ifdef CONFIG_MEMCG_KMEM
578 * This will be the memcg's index in each cache's ->memcg_params->memcg_caches.
579 * There are two main reasons for not using the css_id for this:
580 * 1) this works better in sparse environments, where we have a lot of memcgs,
581 * but only a few kmem-limited. Or also, if we have, for instance, 200
582 * memcgs, and none but the 200th is kmem-limited, we'd have to have a
583 * 200 entry array for that.
585 * 2) In order not to violate the cgroup API, we would like to do all memory
586 * allocation in ->create(). At that point, we haven't yet allocated the
587 * css_id. Having a separate index prevents us from messing with the cgroup
590 * The current size of the caches array is stored in
591 * memcg_limited_groups_array_size. It will double each time we have to
594 static DEFINE_IDA(kmem_limited_groups);
595 int memcg_limited_groups_array_size;
598 * MIN_SIZE is different than 1, because we would like to avoid going through
599 * the alloc/free process all the time. In a small machine, 4 kmem-limited
600 * cgroups is a reasonable guess. In the future, it could be a parameter or
601 * tunable, but that is strictly not necessary.
603 * MAX_SIZE should be as large as the number of css_ids. Ideally, we could get
604 * this constant directly from cgroup, but it is understandable that this is
605 * better kept as an internal representation in cgroup.c. In any case, the
606 * css_id space is not getting any smaller, and we don't have to necessarily
607 * increase ours as well if it increases.
609 #define MEMCG_CACHES_MIN_SIZE 4
610 #define MEMCG_CACHES_MAX_SIZE 65535
613 * A lot of the calls to the cache allocation functions are expected to be
614 * inlined by the compiler. Since the calls to memcg_kmem_get_cache are
615 * conditional to this static branch, we'll have to allow modules that does
616 * kmem_cache_alloc and the such to see this symbol as well
618 struct static_key memcg_kmem_enabled_key;
619 EXPORT_SYMBOL(memcg_kmem_enabled_key);
621 static void disarm_kmem_keys(struct mem_cgroup *memcg)
623 if (memcg_kmem_is_active(memcg)) {
624 static_key_slow_dec(&memcg_kmem_enabled_key);
625 ida_simple_remove(&kmem_limited_groups, memcg->kmemcg_id);
628 * This check can't live in kmem destruction function,
629 * since the charges will outlive the cgroup
631 WARN_ON(res_counter_read_u64(&memcg->kmem, RES_USAGE) != 0);
634 static void disarm_kmem_keys(struct mem_cgroup *memcg)
637 #endif /* CONFIG_MEMCG_KMEM */
639 static void disarm_static_keys(struct mem_cgroup *memcg)
641 disarm_sock_keys(memcg);
642 disarm_kmem_keys(memcg);
645 static void drain_all_stock_async(struct mem_cgroup *memcg);
647 static struct mem_cgroup_per_zone *
648 mem_cgroup_zoneinfo(struct mem_cgroup *memcg, int nid, int zid)
650 VM_BUG_ON((unsigned)nid >= nr_node_ids);
651 return &memcg->nodeinfo[nid]->zoneinfo[zid];
654 struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *memcg)
659 static struct mem_cgroup_per_zone *
660 page_cgroup_zoneinfo(struct mem_cgroup *memcg, struct page *page)
662 int nid = page_to_nid(page);
663 int zid = page_zonenum(page);
665 return mem_cgroup_zoneinfo(memcg, nid, zid);
669 * Implementation Note: reading percpu statistics for memcg.
671 * Both of vmstat[] and percpu_counter has threshold and do periodic
672 * synchronization to implement "quick" read. There are trade-off between
673 * reading cost and precision of value. Then, we may have a chance to implement
674 * a periodic synchronizion of counter in memcg's counter.
676 * But this _read() function is used for user interface now. The user accounts
677 * memory usage by memory cgroup and he _always_ requires exact value because
678 * he accounts memory. Even if we provide quick-and-fuzzy read, we always
679 * have to visit all online cpus and make sum. So, for now, unnecessary
680 * synchronization is not implemented. (just implemented for cpu hotplug)
682 * If there are kernel internal actions which can make use of some not-exact
683 * value, and reading all cpu value can be performance bottleneck in some
684 * common workload, threashold and synchonization as vmstat[] should be
687 static long mem_cgroup_read_stat(struct mem_cgroup *memcg,
688 enum mem_cgroup_stat_index idx)
694 for_each_online_cpu(cpu)
695 val += per_cpu(memcg->stat->count[idx], cpu);
696 #ifdef CONFIG_HOTPLUG_CPU
697 spin_lock(&memcg->pcp_counter_lock);
698 val += memcg->nocpu_base.count[idx];
699 spin_unlock(&memcg->pcp_counter_lock);
705 static void mem_cgroup_swap_statistics(struct mem_cgroup *memcg,
708 int val = (charge) ? 1 : -1;
709 this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_SWAP], val);
712 static unsigned long mem_cgroup_read_events(struct mem_cgroup *memcg,
713 enum mem_cgroup_events_index idx)
715 unsigned long val = 0;
718 for_each_online_cpu(cpu)
719 val += per_cpu(memcg->stat->events[idx], cpu);
720 #ifdef CONFIG_HOTPLUG_CPU
721 spin_lock(&memcg->pcp_counter_lock);
722 val += memcg->nocpu_base.events[idx];
723 spin_unlock(&memcg->pcp_counter_lock);
728 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
730 bool anon, int nr_pages)
735 * Here, RSS means 'mapped anon' and anon's SwapCache. Shmem/tmpfs is
736 * counted as CACHE even if it's on ANON LRU.
739 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS],
742 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_CACHE],
745 if (PageTransHuge(page))
746 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS_HUGE],
749 /* pagein of a big page is an event. So, ignore page size */
751 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGIN]);
753 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGOUT]);
754 nr_pages = -nr_pages; /* for event */
757 __this_cpu_add(memcg->stat->nr_page_events, nr_pages);
763 mem_cgroup_get_lru_size(struct lruvec *lruvec, enum lru_list lru)
765 struct mem_cgroup_per_zone *mz;
767 mz = container_of(lruvec, struct mem_cgroup_per_zone, lruvec);
768 return mz->lru_size[lru];
772 mem_cgroup_zone_nr_lru_pages(struct mem_cgroup *memcg, int nid, int zid,
773 unsigned int lru_mask)
775 struct mem_cgroup_per_zone *mz;
777 unsigned long ret = 0;
779 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
782 if (BIT(lru) & lru_mask)
783 ret += mz->lru_size[lru];
789 mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
790 int nid, unsigned int lru_mask)
795 for (zid = 0; zid < MAX_NR_ZONES; zid++)
796 total += mem_cgroup_zone_nr_lru_pages(memcg,
802 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
803 unsigned int lru_mask)
808 for_each_node_state(nid, N_MEMORY)
809 total += mem_cgroup_node_nr_lru_pages(memcg, nid, lru_mask);
813 static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
814 enum mem_cgroup_events_target target)
816 unsigned long val, next;
818 val = __this_cpu_read(memcg->stat->nr_page_events);
819 next = __this_cpu_read(memcg->stat->targets[target]);
820 /* from time_after() in jiffies.h */
821 if ((long)next - (long)val < 0) {
823 case MEM_CGROUP_TARGET_THRESH:
824 next = val + THRESHOLDS_EVENTS_TARGET;
826 case MEM_CGROUP_TARGET_SOFTLIMIT:
827 next = val + SOFTLIMIT_EVENTS_TARGET;
829 case MEM_CGROUP_TARGET_NUMAINFO:
830 next = val + NUMAINFO_EVENTS_TARGET;
835 __this_cpu_write(memcg->stat->targets[target], next);
842 * Called from rate-limited memcg_check_events when enough
843 * MEM_CGROUP_TARGET_SOFTLIMIT events are accumulated and it makes sure
844 * that all the parents up the hierarchy will be notified that this group
845 * is in excess or that it is not in excess anymore. mmecg->soft_contributed
846 * makes the transition a single action whenever the state flips from one to
849 static void mem_cgroup_update_soft_limit(struct mem_cgroup *memcg)
851 unsigned long long excess = res_counter_soft_limit_excess(&memcg->res);
852 struct mem_cgroup *parent = memcg;
855 spin_lock(&memcg->soft_lock);
857 if (!memcg->soft_contributed) {
859 memcg->soft_contributed = true;
862 if (memcg->soft_contributed) {
864 memcg->soft_contributed = false;
869 * Necessary to update all ancestors when hierarchy is used
870 * because their event counter is not touched.
871 * We track children even outside the hierarchy for the root
872 * cgroup because tree walk starting at root should visit
873 * all cgroups and we want to prevent from pointless tree
874 * walk if no children is below the limit.
876 while (delta && (parent = parent_mem_cgroup(parent)))
877 atomic_add(delta, &parent->children_in_excess);
878 if (memcg != root_mem_cgroup && !root_mem_cgroup->use_hierarchy)
879 atomic_add(delta, &root_mem_cgroup->children_in_excess);
880 spin_unlock(&memcg->soft_lock);
884 * Check events in order.
887 static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
890 /* threshold event is triggered in finer grain than soft limit */
891 if (unlikely(mem_cgroup_event_ratelimit(memcg,
892 MEM_CGROUP_TARGET_THRESH))) {
894 bool do_numainfo __maybe_unused;
896 do_softlimit = mem_cgroup_event_ratelimit(memcg,
897 MEM_CGROUP_TARGET_SOFTLIMIT);
899 do_numainfo = mem_cgroup_event_ratelimit(memcg,
900 MEM_CGROUP_TARGET_NUMAINFO);
904 mem_cgroup_threshold(memcg);
905 if (unlikely(do_softlimit))
906 mem_cgroup_update_soft_limit(memcg);
908 if (unlikely(do_numainfo))
909 atomic_inc(&memcg->numainfo_events);
915 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
918 * mm_update_next_owner() may clear mm->owner to NULL
919 * if it races with swapoff, page migration, etc.
920 * So this can be called with p == NULL.
925 return mem_cgroup_from_css(task_css(p, mem_cgroup_subsys_id));
928 struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
930 struct mem_cgroup *memcg = NULL;
935 * Because we have no locks, mm->owner's may be being moved to other
936 * cgroup. We use css_tryget() here even if this looks
937 * pessimistic (rather than adding locks here).
941 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
942 if (unlikely(!memcg))
944 } while (!css_tryget(&memcg->css));
949 static enum mem_cgroup_filter_t
950 mem_cgroup_filter(struct mem_cgroup *memcg, struct mem_cgroup *root,
951 mem_cgroup_iter_filter cond)
955 return cond(memcg, root);
959 * Returns a next (in a pre-order walk) alive memcg (with elevated css
960 * ref. count) or NULL if the whole root's subtree has been visited.
962 * helper function to be used by mem_cgroup_iter
964 static struct mem_cgroup *__mem_cgroup_iter_next(struct mem_cgroup *root,
965 struct mem_cgroup *last_visited, mem_cgroup_iter_filter cond)
967 struct cgroup_subsys_state *prev_css, *next_css;
969 prev_css = last_visited ? &last_visited->css : NULL;
971 next_css = css_next_descendant_pre(prev_css, &root->css);
974 * Even if we found a group we have to make sure it is
975 * alive. css && !memcg means that the groups should be
976 * skipped and we should continue the tree walk.
977 * last_visited css is safe to use because it is
978 * protected by css_get and the tree walk is rcu safe.
981 struct mem_cgroup *mem = mem_cgroup_from_css(next_css);
983 switch (mem_cgroup_filter(mem, root, cond)) {
991 * css_rightmost_descendant is not an optimal way to
992 * skip through a subtree (especially for imbalanced
993 * trees leaning to right) but that's what we have right
994 * now. More effective solution would be traversing
995 * right-up for first non-NULL without calling
996 * css_next_descendant_pre afterwards.
998 prev_css = css_rightmost_descendant(next_css);
1001 if (css_tryget(&mem->css))
1004 prev_css = next_css;
1014 static void mem_cgroup_iter_invalidate(struct mem_cgroup *root)
1017 * When a group in the hierarchy below root is destroyed, the
1018 * hierarchy iterator can no longer be trusted since it might
1019 * have pointed to the destroyed group. Invalidate it.
1021 atomic_inc(&root->dead_count);
1024 static struct mem_cgroup *
1025 mem_cgroup_iter_load(struct mem_cgroup_reclaim_iter *iter,
1026 struct mem_cgroup *root,
1029 struct mem_cgroup *position = NULL;
1031 * A cgroup destruction happens in two stages: offlining and
1032 * release. They are separated by a RCU grace period.
1034 * If the iterator is valid, we may still race with an
1035 * offlining. The RCU lock ensures the object won't be
1036 * released, tryget will fail if we lost the race.
1038 *sequence = atomic_read(&root->dead_count);
1039 if (iter->last_dead_count == *sequence) {
1041 position = iter->last_visited;
1042 if (position && !css_tryget(&position->css))
1048 static void mem_cgroup_iter_update(struct mem_cgroup_reclaim_iter *iter,
1049 struct mem_cgroup *last_visited,
1050 struct mem_cgroup *new_position,
1054 css_put(&last_visited->css);
1056 * We store the sequence count from the time @last_visited was
1057 * loaded successfully instead of rereading it here so that we
1058 * don't lose destruction events in between. We could have
1059 * raced with the destruction of @new_position after all.
1061 iter->last_visited = new_position;
1063 iter->last_dead_count = sequence;
1067 * mem_cgroup_iter - iterate over memory cgroup hierarchy
1068 * @root: hierarchy root
1069 * @prev: previously returned memcg, NULL on first invocation
1070 * @reclaim: cookie for shared reclaim walks, NULL for full walks
1071 * @cond: filter for visited nodes, NULL for no filter
1073 * Returns references to children of the hierarchy below @root, or
1074 * @root itself, or %NULL after a full round-trip.
1076 * Caller must pass the return value in @prev on subsequent
1077 * invocations for reference counting, or use mem_cgroup_iter_break()
1078 * to cancel a hierarchy walk before the round-trip is complete.
1080 * Reclaimers can specify a zone and a priority level in @reclaim to
1081 * divide up the memcgs in the hierarchy among all concurrent
1082 * reclaimers operating on the same zone and priority.
1084 struct mem_cgroup *mem_cgroup_iter_cond(struct mem_cgroup *root,
1085 struct mem_cgroup *prev,
1086 struct mem_cgroup_reclaim_cookie *reclaim,
1087 mem_cgroup_iter_filter cond)
1089 struct mem_cgroup *memcg = NULL;
1090 struct mem_cgroup *last_visited = NULL;
1092 if (mem_cgroup_disabled()) {
1093 /* first call must return non-NULL, second return NULL */
1094 return (struct mem_cgroup *)(unsigned long)!prev;
1098 root = root_mem_cgroup;
1100 if (prev && !reclaim)
1101 last_visited = prev;
1103 if (!root->use_hierarchy && root != root_mem_cgroup) {
1106 if (mem_cgroup_filter(root, root, cond) == VISIT)
1113 struct mem_cgroup_reclaim_iter *uninitialized_var(iter);
1114 int uninitialized_var(seq);
1117 int nid = zone_to_nid(reclaim->zone);
1118 int zid = zone_idx(reclaim->zone);
1119 struct mem_cgroup_per_zone *mz;
1121 mz = mem_cgroup_zoneinfo(root, nid, zid);
1122 iter = &mz->reclaim_iter[reclaim->priority];
1123 if (prev && reclaim->generation != iter->generation) {
1124 iter->last_visited = NULL;
1128 last_visited = mem_cgroup_iter_load(iter, root, &seq);
1131 memcg = __mem_cgroup_iter_next(root, last_visited, cond);
1134 mem_cgroup_iter_update(iter, last_visited, memcg, seq);
1138 else if (!prev && memcg)
1139 reclaim->generation = iter->generation;
1143 * We have finished the whole tree walk or no group has been
1144 * visited because filter told us to skip the root node.
1146 if (!memcg && (prev || (cond && !last_visited)))
1152 if (prev && prev != root)
1153 css_put(&prev->css);
1159 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1160 * @root: hierarchy root
1161 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1163 void mem_cgroup_iter_break(struct mem_cgroup *root,
1164 struct mem_cgroup *prev)
1167 root = root_mem_cgroup;
1168 if (prev && prev != root)
1169 css_put(&prev->css);
1173 * Iteration constructs for visiting all cgroups (under a tree). If
1174 * loops are exited prematurely (break), mem_cgroup_iter_break() must
1175 * be used for reference counting.
1177 #define for_each_mem_cgroup_tree(iter, root) \
1178 for (iter = mem_cgroup_iter(root, NULL, NULL); \
1180 iter = mem_cgroup_iter(root, iter, NULL))
1182 #define for_each_mem_cgroup(iter) \
1183 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
1185 iter = mem_cgroup_iter(NULL, iter, NULL))
1187 void __mem_cgroup_count_vm_event(struct mm_struct *mm, enum vm_event_item idx)
1189 struct mem_cgroup *memcg;
1192 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
1193 if (unlikely(!memcg))
1198 this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGFAULT]);
1201 this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGMAJFAULT]);
1209 EXPORT_SYMBOL(__mem_cgroup_count_vm_event);
1212 * mem_cgroup_zone_lruvec - get the lru list vector for a zone and memcg
1213 * @zone: zone of the wanted lruvec
1214 * @memcg: memcg of the wanted lruvec
1216 * Returns the lru list vector holding pages for the given @zone and
1217 * @mem. This can be the global zone lruvec, if the memory controller
1220 struct lruvec *mem_cgroup_zone_lruvec(struct zone *zone,
1221 struct mem_cgroup *memcg)
1223 struct mem_cgroup_per_zone *mz;
1224 struct lruvec *lruvec;
1226 if (mem_cgroup_disabled()) {
1227 lruvec = &zone->lruvec;
1231 mz = mem_cgroup_zoneinfo(memcg, zone_to_nid(zone), zone_idx(zone));
1232 lruvec = &mz->lruvec;
1235 * Since a node can be onlined after the mem_cgroup was created,
1236 * we have to be prepared to initialize lruvec->zone here;
1237 * and if offlined then reonlined, we need to reinitialize it.
1239 if (unlikely(lruvec->zone != zone))
1240 lruvec->zone = zone;
1245 * Following LRU functions are allowed to be used without PCG_LOCK.
1246 * Operations are called by routine of global LRU independently from memcg.
1247 * What we have to take care of here is validness of pc->mem_cgroup.
1249 * Changes to pc->mem_cgroup happens when
1252 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
1253 * It is added to LRU before charge.
1254 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
1255 * When moving account, the page is not on LRU. It's isolated.
1259 * mem_cgroup_page_lruvec - return lruvec for adding an lru page
1261 * @zone: zone of the page
1263 struct lruvec *mem_cgroup_page_lruvec(struct page *page, struct zone *zone)
1265 struct mem_cgroup_per_zone *mz;
1266 struct mem_cgroup *memcg;
1267 struct page_cgroup *pc;
1268 struct lruvec *lruvec;
1270 if (mem_cgroup_disabled()) {
1271 lruvec = &zone->lruvec;
1275 pc = lookup_page_cgroup(page);
1276 memcg = pc->mem_cgroup;
1279 * Surreptitiously switch any uncharged offlist page to root:
1280 * an uncharged page off lru does nothing to secure
1281 * its former mem_cgroup from sudden removal.
1283 * Our caller holds lru_lock, and PageCgroupUsed is updated
1284 * under page_cgroup lock: between them, they make all uses
1285 * of pc->mem_cgroup safe.
1287 if (!PageLRU(page) && !PageCgroupUsed(pc) && memcg != root_mem_cgroup)
1288 pc->mem_cgroup = memcg = root_mem_cgroup;
1290 mz = page_cgroup_zoneinfo(memcg, page);
1291 lruvec = &mz->lruvec;
1294 * Since a node can be onlined after the mem_cgroup was created,
1295 * we have to be prepared to initialize lruvec->zone here;
1296 * and if offlined then reonlined, we need to reinitialize it.
1298 if (unlikely(lruvec->zone != zone))
1299 lruvec->zone = zone;
1304 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1305 * @lruvec: mem_cgroup per zone lru vector
1306 * @lru: index of lru list the page is sitting on
1307 * @nr_pages: positive when adding or negative when removing
1309 * This function must be called when a page is added to or removed from an
1312 void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
1315 struct mem_cgroup_per_zone *mz;
1316 unsigned long *lru_size;
1318 if (mem_cgroup_disabled())
1321 mz = container_of(lruvec, struct mem_cgroup_per_zone, lruvec);
1322 lru_size = mz->lru_size + lru;
1323 *lru_size += nr_pages;
1324 VM_BUG_ON((long)(*lru_size) < 0);
1328 * Checks whether given mem is same or in the root_mem_cgroup's
1331 bool __mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
1332 struct mem_cgroup *memcg)
1334 if (root_memcg == memcg)
1336 if (!root_memcg->use_hierarchy || !memcg)
1338 return cgroup_is_descendant(memcg->css.cgroup, root_memcg->css.cgroup);
1341 static bool mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
1342 struct mem_cgroup *memcg)
1347 ret = __mem_cgroup_same_or_subtree(root_memcg, memcg);
1352 bool task_in_mem_cgroup(struct task_struct *task,
1353 const struct mem_cgroup *memcg)
1355 struct mem_cgroup *curr = NULL;
1356 struct task_struct *p;
1359 p = find_lock_task_mm(task);
1361 curr = try_get_mem_cgroup_from_mm(p->mm);
1365 * All threads may have already detached their mm's, but the oom
1366 * killer still needs to detect if they have already been oom
1367 * killed to prevent needlessly killing additional tasks.
1370 curr = mem_cgroup_from_task(task);
1372 css_get(&curr->css);
1378 * We should check use_hierarchy of "memcg" not "curr". Because checking
1379 * use_hierarchy of "curr" here make this function true if hierarchy is
1380 * enabled in "curr" and "curr" is a child of "memcg" in *cgroup*
1381 * hierarchy(even if use_hierarchy is disabled in "memcg").
1383 ret = mem_cgroup_same_or_subtree(memcg, curr);
1384 css_put(&curr->css);
1388 int mem_cgroup_inactive_anon_is_low(struct lruvec *lruvec)
1390 unsigned long inactive_ratio;
1391 unsigned long inactive;
1392 unsigned long active;
1395 inactive = mem_cgroup_get_lru_size(lruvec, LRU_INACTIVE_ANON);
1396 active = mem_cgroup_get_lru_size(lruvec, LRU_ACTIVE_ANON);
1398 gb = (inactive + active) >> (30 - PAGE_SHIFT);
1400 inactive_ratio = int_sqrt(10 * gb);
1404 return inactive * inactive_ratio < active;
1407 #define mem_cgroup_from_res_counter(counter, member) \
1408 container_of(counter, struct mem_cgroup, member)
1411 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1412 * @memcg: the memory cgroup
1414 * Returns the maximum amount of memory @mem can be charged with, in
1417 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1419 unsigned long long margin;
1421 margin = res_counter_margin(&memcg->res);
1422 if (do_swap_account)
1423 margin = min(margin, res_counter_margin(&memcg->memsw));
1424 return margin >> PAGE_SHIFT;
1427 int mem_cgroup_swappiness(struct mem_cgroup *memcg)
1430 if (!css_parent(&memcg->css))
1431 return vm_swappiness;
1433 return memcg->swappiness;
1437 * memcg->moving_account is used for checking possibility that some thread is
1438 * calling move_account(). When a thread on CPU-A starts moving pages under
1439 * a memcg, other threads should check memcg->moving_account under
1440 * rcu_read_lock(), like this:
1444 * memcg->moving_account+1 if (memcg->mocing_account)
1446 * synchronize_rcu() update something.
1451 /* for quick checking without looking up memcg */
1452 atomic_t memcg_moving __read_mostly;
1454 static void mem_cgroup_start_move(struct mem_cgroup *memcg)
1456 atomic_inc(&memcg_moving);
1457 atomic_inc(&memcg->moving_account);
1461 static void mem_cgroup_end_move(struct mem_cgroup *memcg)
1464 * Now, mem_cgroup_clear_mc() may call this function with NULL.
1465 * We check NULL in callee rather than caller.
1468 atomic_dec(&memcg_moving);
1469 atomic_dec(&memcg->moving_account);
1474 * 2 routines for checking "mem" is under move_account() or not.
1476 * mem_cgroup_stolen() - checking whether a cgroup is mc.from or not. This
1477 * is used for avoiding races in accounting. If true,
1478 * pc->mem_cgroup may be overwritten.
1480 * mem_cgroup_under_move() - checking a cgroup is mc.from or mc.to or
1481 * under hierarchy of moving cgroups. This is for
1482 * waiting at hith-memory prressure caused by "move".
1485 static bool mem_cgroup_stolen(struct mem_cgroup *memcg)
1487 VM_BUG_ON(!rcu_read_lock_held());
1488 return atomic_read(&memcg->moving_account) > 0;
1491 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1493 struct mem_cgroup *from;
1494 struct mem_cgroup *to;
1497 * Unlike task_move routines, we access mc.to, mc.from not under
1498 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1500 spin_lock(&mc.lock);
1506 ret = mem_cgroup_same_or_subtree(memcg, from)
1507 || mem_cgroup_same_or_subtree(memcg, to);
1509 spin_unlock(&mc.lock);
1513 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1515 if (mc.moving_task && current != mc.moving_task) {
1516 if (mem_cgroup_under_move(memcg)) {
1518 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1519 /* moving charge context might have finished. */
1522 finish_wait(&mc.waitq, &wait);
1530 * Take this lock when
1531 * - a code tries to modify page's memcg while it's USED.
1532 * - a code tries to modify page state accounting in a memcg.
1533 * see mem_cgroup_stolen(), too.
1535 static void move_lock_mem_cgroup(struct mem_cgroup *memcg,
1536 unsigned long *flags)
1538 spin_lock_irqsave(&memcg->move_lock, *flags);
1541 static void move_unlock_mem_cgroup(struct mem_cgroup *memcg,
1542 unsigned long *flags)
1544 spin_unlock_irqrestore(&memcg->move_lock, *flags);
1547 #define K(x) ((x) << (PAGE_SHIFT-10))
1549 * mem_cgroup_print_oom_info: Print OOM information relevant to memory controller.
1550 * @memcg: The memory cgroup that went over limit
1551 * @p: Task that is going to be killed
1553 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1556 void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1558 struct cgroup *task_cgrp;
1559 struct cgroup *mem_cgrp;
1561 * Need a buffer in BSS, can't rely on allocations. The code relies
1562 * on the assumption that OOM is serialized for memory controller.
1563 * If this assumption is broken, revisit this code.
1565 static char memcg_name[PATH_MAX];
1567 struct mem_cgroup *iter;
1575 mem_cgrp = memcg->css.cgroup;
1576 task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
1578 ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
1581 * Unfortunately, we are unable to convert to a useful name
1582 * But we'll still print out the usage information
1589 pr_info("Task in %s killed", memcg_name);
1592 ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
1600 * Continues from above, so we don't need an KERN_ level
1602 pr_cont(" as a result of limit of %s\n", memcg_name);
1605 pr_info("memory: usage %llukB, limit %llukB, failcnt %llu\n",
1606 res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
1607 res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
1608 res_counter_read_u64(&memcg->res, RES_FAILCNT));
1609 pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %llu\n",
1610 res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
1611 res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
1612 res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
1613 pr_info("kmem: usage %llukB, limit %llukB, failcnt %llu\n",
1614 res_counter_read_u64(&memcg->kmem, RES_USAGE) >> 10,
1615 res_counter_read_u64(&memcg->kmem, RES_LIMIT) >> 10,
1616 res_counter_read_u64(&memcg->kmem, RES_FAILCNT));
1618 for_each_mem_cgroup_tree(iter, memcg) {
1619 pr_info("Memory cgroup stats");
1622 ret = cgroup_path(iter->css.cgroup, memcg_name, PATH_MAX);
1624 pr_cont(" for %s", memcg_name);
1628 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
1629 if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
1631 pr_cont(" %s:%ldKB", mem_cgroup_stat_names[i],
1632 K(mem_cgroup_read_stat(iter, i)));
1635 for (i = 0; i < NR_LRU_LISTS; i++)
1636 pr_cont(" %s:%luKB", mem_cgroup_lru_names[i],
1637 K(mem_cgroup_nr_lru_pages(iter, BIT(i))));
1644 * This function returns the number of memcg under hierarchy tree. Returns
1645 * 1(self count) if no children.
1647 static int mem_cgroup_count_children(struct mem_cgroup *memcg)
1650 struct mem_cgroup *iter;
1652 for_each_mem_cgroup_tree(iter, memcg)
1658 * Return the memory (and swap, if configured) limit for a memcg.
1660 static u64 mem_cgroup_get_limit(struct mem_cgroup *memcg)
1664 limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
1667 * Do not consider swap space if we cannot swap due to swappiness
1669 if (mem_cgroup_swappiness(memcg)) {
1672 limit += total_swap_pages << PAGE_SHIFT;
1673 memsw = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
1676 * If memsw is finite and limits the amount of swap space
1677 * available to this memcg, return that limit.
1679 limit = min(limit, memsw);
1685 static void mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
1688 struct mem_cgroup *iter;
1689 unsigned long chosen_points = 0;
1690 unsigned long totalpages;
1691 unsigned int points = 0;
1692 struct task_struct *chosen = NULL;
1695 * If current has a pending SIGKILL or is exiting, then automatically
1696 * select it. The goal is to allow it to allocate so that it may
1697 * quickly exit and free its memory.
1699 if (fatal_signal_pending(current) || current->flags & PF_EXITING) {
1700 set_thread_flag(TIF_MEMDIE);
1704 check_panic_on_oom(CONSTRAINT_MEMCG, gfp_mask, order, NULL);
1705 totalpages = mem_cgroup_get_limit(memcg) >> PAGE_SHIFT ? : 1;
1706 for_each_mem_cgroup_tree(iter, memcg) {
1707 struct css_task_iter it;
1708 struct task_struct *task;
1710 css_task_iter_start(&iter->css, &it);
1711 while ((task = css_task_iter_next(&it))) {
1712 switch (oom_scan_process_thread(task, totalpages, NULL,
1714 case OOM_SCAN_SELECT:
1716 put_task_struct(chosen);
1718 chosen_points = ULONG_MAX;
1719 get_task_struct(chosen);
1721 case OOM_SCAN_CONTINUE:
1723 case OOM_SCAN_ABORT:
1724 css_task_iter_end(&it);
1725 mem_cgroup_iter_break(memcg, iter);
1727 put_task_struct(chosen);
1732 points = oom_badness(task, memcg, NULL, totalpages);
1733 if (points > chosen_points) {
1735 put_task_struct(chosen);
1737 chosen_points = points;
1738 get_task_struct(chosen);
1741 css_task_iter_end(&it);
1746 points = chosen_points * 1000 / totalpages;
1747 oom_kill_process(chosen, gfp_mask, order, points, totalpages, memcg,
1748 NULL, "Memory cgroup out of memory");
1751 static unsigned long mem_cgroup_reclaim(struct mem_cgroup *memcg,
1753 unsigned long flags)
1755 unsigned long total = 0;
1756 bool noswap = false;
1759 if (flags & MEM_CGROUP_RECLAIM_NOSWAP)
1761 if (!(flags & MEM_CGROUP_RECLAIM_SHRINK) && memcg->memsw_is_minimum)
1764 for (loop = 0; loop < MEM_CGROUP_MAX_RECLAIM_LOOPS; loop++) {
1766 drain_all_stock_async(memcg);
1767 total += try_to_free_mem_cgroup_pages(memcg, gfp_mask, noswap);
1769 * Allow limit shrinkers, which are triggered directly
1770 * by userspace, to catch signals and stop reclaim
1771 * after minimal progress, regardless of the margin.
1773 if (total && (flags & MEM_CGROUP_RECLAIM_SHRINK))
1775 if (mem_cgroup_margin(memcg))
1778 * If nothing was reclaimed after two attempts, there
1779 * may be no reclaimable pages in this hierarchy.
1787 #if MAX_NUMNODES > 1
1789 * test_mem_cgroup_node_reclaimable
1790 * @memcg: the target memcg
1791 * @nid: the node ID to be checked.
1792 * @noswap : specify true here if the user wants flle only information.
1794 * This function returns whether the specified memcg contains any
1795 * reclaimable pages on a node. Returns true if there are any reclaimable
1796 * pages in the node.
1798 static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *memcg,
1799 int nid, bool noswap)
1801 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_FILE))
1803 if (noswap || !total_swap_pages)
1805 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_ANON))
1812 * Always updating the nodemask is not very good - even if we have an empty
1813 * list or the wrong list here, we can start from some node and traverse all
1814 * nodes based on the zonelist. So update the list loosely once per 10 secs.
1817 static void mem_cgroup_may_update_nodemask(struct mem_cgroup *memcg)
1821 * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
1822 * pagein/pageout changes since the last update.
1824 if (!atomic_read(&memcg->numainfo_events))
1826 if (atomic_inc_return(&memcg->numainfo_updating) > 1)
1829 /* make a nodemask where this memcg uses memory from */
1830 memcg->scan_nodes = node_states[N_MEMORY];
1832 for_each_node_mask(nid, node_states[N_MEMORY]) {
1834 if (!test_mem_cgroup_node_reclaimable(memcg, nid, false))
1835 node_clear(nid, memcg->scan_nodes);
1838 atomic_set(&memcg->numainfo_events, 0);
1839 atomic_set(&memcg->numainfo_updating, 0);
1843 * Selecting a node where we start reclaim from. Because what we need is just
1844 * reducing usage counter, start from anywhere is O,K. Considering
1845 * memory reclaim from current node, there are pros. and cons.
1847 * Freeing memory from current node means freeing memory from a node which
1848 * we'll use or we've used. So, it may make LRU bad. And if several threads
1849 * hit limits, it will see a contention on a node. But freeing from remote
1850 * node means more costs for memory reclaim because of memory latency.
1852 * Now, we use round-robin. Better algorithm is welcomed.
1854 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1858 mem_cgroup_may_update_nodemask(memcg);
1859 node = memcg->last_scanned_node;
1861 node = next_node(node, memcg->scan_nodes);
1862 if (node == MAX_NUMNODES)
1863 node = first_node(memcg->scan_nodes);
1865 * We call this when we hit limit, not when pages are added to LRU.
1866 * No LRU may hold pages because all pages are UNEVICTABLE or
1867 * memcg is too small and all pages are not on LRU. In that case,
1868 * we use curret node.
1870 if (unlikely(node == MAX_NUMNODES))
1871 node = numa_node_id();
1873 memcg->last_scanned_node = node;
1878 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
1886 * A group is eligible for the soft limit reclaim under the given root
1888 * a) it is over its soft limit
1889 * b) any parent up the hierarchy is over its soft limit
1891 * If the given group doesn't have any children over the limit then it
1892 * doesn't make any sense to iterate its subtree.
1894 enum mem_cgroup_filter_t
1895 mem_cgroup_soft_reclaim_eligible(struct mem_cgroup *memcg,
1896 struct mem_cgroup *root)
1898 struct mem_cgroup *parent;
1901 memcg = root_mem_cgroup;
1904 if (res_counter_soft_limit_excess(&memcg->res))
1908 * If any parent up to the root in the hierarchy is over its soft limit
1909 * then we have to obey and reclaim from this group as well.
1911 while ((parent = parent_mem_cgroup(parent))) {
1912 if (res_counter_soft_limit_excess(&parent->res))
1918 if (!atomic_read(&memcg->children_in_excess))
1923 static DEFINE_SPINLOCK(memcg_oom_lock);
1926 * Check OOM-Killer is already running under our hierarchy.
1927 * If someone is running, return false.
1929 static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
1931 struct mem_cgroup *iter, *failed = NULL;
1933 spin_lock(&memcg_oom_lock);
1935 for_each_mem_cgroup_tree(iter, memcg) {
1936 if (iter->oom_lock) {
1938 * this subtree of our hierarchy is already locked
1939 * so we cannot give a lock.
1942 mem_cgroup_iter_break(memcg, iter);
1945 iter->oom_lock = true;
1950 * OK, we failed to lock the whole subtree so we have
1951 * to clean up what we set up to the failing subtree
1953 for_each_mem_cgroup_tree(iter, memcg) {
1954 if (iter == failed) {
1955 mem_cgroup_iter_break(memcg, iter);
1958 iter->oom_lock = false;
1962 spin_unlock(&memcg_oom_lock);
1967 static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
1969 struct mem_cgroup *iter;
1971 spin_lock(&memcg_oom_lock);
1972 for_each_mem_cgroup_tree(iter, memcg)
1973 iter->oom_lock = false;
1974 spin_unlock(&memcg_oom_lock);
1977 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
1979 struct mem_cgroup *iter;
1981 for_each_mem_cgroup_tree(iter, memcg)
1982 atomic_inc(&iter->under_oom);
1985 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
1987 struct mem_cgroup *iter;
1990 * When a new child is created while the hierarchy is under oom,
1991 * mem_cgroup_oom_lock() may not be called. We have to use
1992 * atomic_add_unless() here.
1994 for_each_mem_cgroup_tree(iter, memcg)
1995 atomic_add_unless(&iter->under_oom, -1, 0);
1998 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
2000 struct oom_wait_info {
2001 struct mem_cgroup *memcg;
2005 static int memcg_oom_wake_function(wait_queue_t *wait,
2006 unsigned mode, int sync, void *arg)
2008 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
2009 struct mem_cgroup *oom_wait_memcg;
2010 struct oom_wait_info *oom_wait_info;
2012 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
2013 oom_wait_memcg = oom_wait_info->memcg;
2016 * Both of oom_wait_info->memcg and wake_memcg are stable under us.
2017 * Then we can use css_is_ancestor without taking care of RCU.
2019 if (!mem_cgroup_same_or_subtree(oom_wait_memcg, wake_memcg)
2020 && !mem_cgroup_same_or_subtree(wake_memcg, oom_wait_memcg))
2022 return autoremove_wake_function(wait, mode, sync, arg);
2025 static void memcg_wakeup_oom(struct mem_cgroup *memcg)
2027 atomic_inc(&memcg->oom_wakeups);
2028 /* for filtering, pass "memcg" as argument. */
2029 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
2032 static void memcg_oom_recover(struct mem_cgroup *memcg)
2034 if (memcg && atomic_read(&memcg->under_oom))
2035 memcg_wakeup_oom(memcg);
2039 * try to call OOM killer
2041 static void mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
2046 if (!current->memcg_oom.may_oom)
2049 current->memcg_oom.in_memcg_oom = 1;
2052 * As with any blocking lock, a contender needs to start
2053 * listening for wakeups before attempting the trylock,
2054 * otherwise it can miss the wakeup from the unlock and sleep
2055 * indefinitely. This is just open-coded because our locking
2056 * is so particular to memcg hierarchies.
2058 wakeups = atomic_read(&memcg->oom_wakeups);
2059 mem_cgroup_mark_under_oom(memcg);
2061 locked = mem_cgroup_oom_trylock(memcg);
2064 mem_cgroup_oom_notify(memcg);
2066 if (locked && !memcg->oom_kill_disable) {
2067 mem_cgroup_unmark_under_oom(memcg);
2068 mem_cgroup_out_of_memory(memcg, mask, order);
2069 mem_cgroup_oom_unlock(memcg);
2071 * There is no guarantee that an OOM-lock contender
2072 * sees the wakeups triggered by the OOM kill
2073 * uncharges. Wake any sleepers explicitely.
2075 memcg_oom_recover(memcg);
2078 * A system call can just return -ENOMEM, but if this
2079 * is a page fault and somebody else is handling the
2080 * OOM already, we need to sleep on the OOM waitqueue
2081 * for this memcg until the situation is resolved.
2082 * Which can take some time because it might be
2083 * handled by a userspace task.
2085 * However, this is the charge context, which means
2086 * that we may sit on a large call stack and hold
2087 * various filesystem locks, the mmap_sem etc. and we
2088 * don't want the OOM handler to deadlock on them
2089 * while we sit here and wait. Store the current OOM
2090 * context in the task_struct, then return -ENOMEM.
2091 * At the end of the page fault handler, with the
2092 * stack unwound, pagefault_out_of_memory() will check
2093 * back with us by calling
2094 * mem_cgroup_oom_synchronize(), possibly putting the
2097 current->memcg_oom.oom_locked = locked;
2098 current->memcg_oom.wakeups = wakeups;
2099 css_get(&memcg->css);
2100 current->memcg_oom.wait_on_memcg = memcg;
2105 * mem_cgroup_oom_synchronize - complete memcg OOM handling
2107 * This has to be called at the end of a page fault if the the memcg
2108 * OOM handler was enabled and the fault is returning %VM_FAULT_OOM.
2110 * Memcg supports userspace OOM handling, so failed allocations must
2111 * sleep on a waitqueue until the userspace task resolves the
2112 * situation. Sleeping directly in the charge context with all kinds
2113 * of locks held is not a good idea, instead we remember an OOM state
2114 * in the task and mem_cgroup_oom_synchronize() has to be called at
2115 * the end of the page fault to put the task to sleep and clean up the
2118 * Returns %true if an ongoing memcg OOM situation was detected and
2119 * finalized, %false otherwise.
2121 bool mem_cgroup_oom_synchronize(void)
2123 struct oom_wait_info owait;
2124 struct mem_cgroup *memcg;
2126 /* OOM is global, do not handle */
2127 if (!current->memcg_oom.in_memcg_oom)
2131 * We invoked the OOM killer but there is a chance that a kill
2132 * did not free up any charges. Everybody else might already
2133 * be sleeping, so restart the fault and keep the rampage
2134 * going until some charges are released.
2136 memcg = current->memcg_oom.wait_on_memcg;
2140 if (test_thread_flag(TIF_MEMDIE) || fatal_signal_pending(current))
2143 owait.memcg = memcg;
2144 owait.wait.flags = 0;
2145 owait.wait.func = memcg_oom_wake_function;
2146 owait.wait.private = current;
2147 INIT_LIST_HEAD(&owait.wait.task_list);
2149 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
2150 /* Only sleep if we didn't miss any wakeups since OOM */
2151 if (atomic_read(&memcg->oom_wakeups) == current->memcg_oom.wakeups)
2153 finish_wait(&memcg_oom_waitq, &owait.wait);
2155 mem_cgroup_unmark_under_oom(memcg);
2156 if (current->memcg_oom.oom_locked) {
2157 mem_cgroup_oom_unlock(memcg);
2159 * There is no guarantee that an OOM-lock contender
2160 * sees the wakeups triggered by the OOM kill
2161 * uncharges. Wake any sleepers explicitely.
2163 memcg_oom_recover(memcg);
2165 css_put(&memcg->css);
2166 current->memcg_oom.wait_on_memcg = NULL;
2168 current->memcg_oom.in_memcg_oom = 0;
2173 * Currently used to update mapped file statistics, but the routine can be
2174 * generalized to update other statistics as well.
2176 * Notes: Race condition
2178 * We usually use page_cgroup_lock() for accessing page_cgroup member but
2179 * it tends to be costly. But considering some conditions, we doesn't need
2180 * to do so _always_.
2182 * Considering "charge", lock_page_cgroup() is not required because all
2183 * file-stat operations happen after a page is attached to radix-tree. There
2184 * are no race with "charge".
2186 * Considering "uncharge", we know that memcg doesn't clear pc->mem_cgroup
2187 * at "uncharge" intentionally. So, we always see valid pc->mem_cgroup even
2188 * if there are race with "uncharge". Statistics itself is properly handled
2191 * Considering "move", this is an only case we see a race. To make the race
2192 * small, we check mm->moving_account and detect there are possibility of race
2193 * If there is, we take a lock.
2196 void __mem_cgroup_begin_update_page_stat(struct page *page,
2197 bool *locked, unsigned long *flags)
2199 struct mem_cgroup *memcg;
2200 struct page_cgroup *pc;
2202 pc = lookup_page_cgroup(page);
2204 memcg = pc->mem_cgroup;
2205 if (unlikely(!memcg || !PageCgroupUsed(pc)))
2208 * If this memory cgroup is not under account moving, we don't
2209 * need to take move_lock_mem_cgroup(). Because we already hold
2210 * rcu_read_lock(), any calls to move_account will be delayed until
2211 * rcu_read_unlock() if mem_cgroup_stolen() == true.
2213 if (!mem_cgroup_stolen(memcg))
2216 move_lock_mem_cgroup(memcg, flags);
2217 if (memcg != pc->mem_cgroup || !PageCgroupUsed(pc)) {
2218 move_unlock_mem_cgroup(memcg, flags);
2224 void __mem_cgroup_end_update_page_stat(struct page *page, unsigned long *flags)
2226 struct page_cgroup *pc = lookup_page_cgroup(page);
2229 * It's guaranteed that pc->mem_cgroup never changes while
2230 * lock is held because a routine modifies pc->mem_cgroup
2231 * should take move_lock_mem_cgroup().
2233 move_unlock_mem_cgroup(pc->mem_cgroup, flags);
2236 void mem_cgroup_update_page_stat(struct page *page,
2237 enum mem_cgroup_stat_index idx, int val)
2239 struct mem_cgroup *memcg;
2240 struct page_cgroup *pc = lookup_page_cgroup(page);
2241 unsigned long uninitialized_var(flags);
2243 if (mem_cgroup_disabled())
2246 VM_BUG_ON(!rcu_read_lock_held());
2247 memcg = pc->mem_cgroup;
2248 if (unlikely(!memcg || !PageCgroupUsed(pc)))
2251 this_cpu_add(memcg->stat->count[idx], val);
2255 * size of first charge trial. "32" comes from vmscan.c's magic value.
2256 * TODO: maybe necessary to use big numbers in big irons.
2258 #define CHARGE_BATCH 32U
2259 struct memcg_stock_pcp {
2260 struct mem_cgroup *cached; /* this never be root cgroup */
2261 unsigned int nr_pages;
2262 struct work_struct work;
2263 unsigned long flags;
2264 #define FLUSHING_CACHED_CHARGE 0
2266 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
2267 static DEFINE_MUTEX(percpu_charge_mutex);
2270 * consume_stock: Try to consume stocked charge on this cpu.
2271 * @memcg: memcg to consume from.
2272 * @nr_pages: how many pages to charge.
2274 * The charges will only happen if @memcg matches the current cpu's memcg
2275 * stock, and at least @nr_pages are available in that stock. Failure to
2276 * service an allocation will refill the stock.
2278 * returns true if successful, false otherwise.
2280 static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2282 struct memcg_stock_pcp *stock;
2285 if (nr_pages > CHARGE_BATCH)
2288 stock = &get_cpu_var(memcg_stock);
2289 if (memcg == stock->cached && stock->nr_pages >= nr_pages)
2290 stock->nr_pages -= nr_pages;
2291 else /* need to call res_counter_charge */
2293 put_cpu_var(memcg_stock);
2298 * Returns stocks cached in percpu to res_counter and reset cached information.
2300 static void drain_stock(struct memcg_stock_pcp *stock)
2302 struct mem_cgroup *old = stock->cached;
2304 if (stock->nr_pages) {
2305 unsigned long bytes = stock->nr_pages * PAGE_SIZE;
2307 res_counter_uncharge(&old->res, bytes);
2308 if (do_swap_account)
2309 res_counter_uncharge(&old->memsw, bytes);
2310 stock->nr_pages = 0;
2312 stock->cached = NULL;
2316 * This must be called under preempt disabled or must be called by
2317 * a thread which is pinned to local cpu.
2319 static void drain_local_stock(struct work_struct *dummy)
2321 struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
2323 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2326 static void __init memcg_stock_init(void)
2330 for_each_possible_cpu(cpu) {
2331 struct memcg_stock_pcp *stock =
2332 &per_cpu(memcg_stock, cpu);
2333 INIT_WORK(&stock->work, drain_local_stock);
2338 * Cache charges(val) which is from res_counter, to local per_cpu area.
2339 * This will be consumed by consume_stock() function, later.
2341 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2343 struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
2345 if (stock->cached != memcg) { /* reset if necessary */
2347 stock->cached = memcg;
2349 stock->nr_pages += nr_pages;
2350 put_cpu_var(memcg_stock);
2354 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2355 * of the hierarchy under it. sync flag says whether we should block
2356 * until the work is done.
2358 static void drain_all_stock(struct mem_cgroup *root_memcg, bool sync)
2362 /* Notify other cpus that system-wide "drain" is running */
2365 for_each_online_cpu(cpu) {
2366 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2367 struct mem_cgroup *memcg;
2369 memcg = stock->cached;
2370 if (!memcg || !stock->nr_pages)
2372 if (!mem_cgroup_same_or_subtree(root_memcg, memcg))
2374 if (!test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2376 drain_local_stock(&stock->work);
2378 schedule_work_on(cpu, &stock->work);
2386 for_each_online_cpu(cpu) {
2387 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2388 if (test_bit(FLUSHING_CACHED_CHARGE, &stock->flags))
2389 flush_work(&stock->work);
2396 * Tries to drain stocked charges in other cpus. This function is asynchronous
2397 * and just put a work per cpu for draining localy on each cpu. Caller can
2398 * expects some charges will be back to res_counter later but cannot wait for
2401 static void drain_all_stock_async(struct mem_cgroup *root_memcg)
2404 * If someone calls draining, avoid adding more kworker runs.
2406 if (!mutex_trylock(&percpu_charge_mutex))
2408 drain_all_stock(root_memcg, false);
2409 mutex_unlock(&percpu_charge_mutex);
2412 /* This is a synchronous drain interface. */
2413 static void drain_all_stock_sync(struct mem_cgroup *root_memcg)
2415 /* called when force_empty is called */
2416 mutex_lock(&percpu_charge_mutex);
2417 drain_all_stock(root_memcg, true);
2418 mutex_unlock(&percpu_charge_mutex);
2422 * This function drains percpu counter value from DEAD cpu and
2423 * move it to local cpu. Note that this function can be preempted.
2425 static void mem_cgroup_drain_pcp_counter(struct mem_cgroup *memcg, int cpu)
2429 spin_lock(&memcg->pcp_counter_lock);
2430 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
2431 long x = per_cpu(memcg->stat->count[i], cpu);
2433 per_cpu(memcg->stat->count[i], cpu) = 0;
2434 memcg->nocpu_base.count[i] += x;
2436 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
2437 unsigned long x = per_cpu(memcg->stat->events[i], cpu);
2439 per_cpu(memcg->stat->events[i], cpu) = 0;
2440 memcg->nocpu_base.events[i] += x;
2442 spin_unlock(&memcg->pcp_counter_lock);
2445 static int memcg_cpu_hotplug_callback(struct notifier_block *nb,
2446 unsigned long action,
2449 int cpu = (unsigned long)hcpu;
2450 struct memcg_stock_pcp *stock;
2451 struct mem_cgroup *iter;
2453 if (action == CPU_ONLINE)
2456 if (action != CPU_DEAD && action != CPU_DEAD_FROZEN)
2459 for_each_mem_cgroup(iter)
2460 mem_cgroup_drain_pcp_counter(iter, cpu);
2462 stock = &per_cpu(memcg_stock, cpu);
2468 /* See __mem_cgroup_try_charge() for details */
2470 CHARGE_OK, /* success */
2471 CHARGE_RETRY, /* need to retry but retry is not bad */
2472 CHARGE_NOMEM, /* we can't do more. return -ENOMEM */
2473 CHARGE_WOULDBLOCK, /* GFP_WAIT wasn't set and no enough res. */
2476 static int mem_cgroup_do_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2477 unsigned int nr_pages, unsigned int min_pages,
2480 unsigned long csize = nr_pages * PAGE_SIZE;
2481 struct mem_cgroup *mem_over_limit;
2482 struct res_counter *fail_res;
2483 unsigned long flags = 0;
2486 ret = res_counter_charge(&memcg->res, csize, &fail_res);
2489 if (!do_swap_account)
2491 ret = res_counter_charge(&memcg->memsw, csize, &fail_res);
2495 res_counter_uncharge(&memcg->res, csize);
2496 mem_over_limit = mem_cgroup_from_res_counter(fail_res, memsw);
2497 flags |= MEM_CGROUP_RECLAIM_NOSWAP;
2499 mem_over_limit = mem_cgroup_from_res_counter(fail_res, res);
2501 * Never reclaim on behalf of optional batching, retry with a
2502 * single page instead.
2504 if (nr_pages > min_pages)
2505 return CHARGE_RETRY;
2507 if (!(gfp_mask & __GFP_WAIT))
2508 return CHARGE_WOULDBLOCK;
2510 if (gfp_mask & __GFP_NORETRY)
2511 return CHARGE_NOMEM;
2513 ret = mem_cgroup_reclaim(mem_over_limit, gfp_mask, flags);
2514 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2515 return CHARGE_RETRY;
2517 * Even though the limit is exceeded at this point, reclaim
2518 * may have been able to free some pages. Retry the charge
2519 * before killing the task.
2521 * Only for regular pages, though: huge pages are rather
2522 * unlikely to succeed so close to the limit, and we fall back
2523 * to regular pages anyway in case of failure.
2525 if (nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER) && ret)
2526 return CHARGE_RETRY;
2529 * At task move, charge accounts can be doubly counted. So, it's
2530 * better to wait until the end of task_move if something is going on.
2532 if (mem_cgroup_wait_acct_move(mem_over_limit))
2533 return CHARGE_RETRY;
2536 mem_cgroup_oom(mem_over_limit, gfp_mask, get_order(csize));
2538 return CHARGE_NOMEM;
2542 * __mem_cgroup_try_charge() does
2543 * 1. detect memcg to be charged against from passed *mm and *ptr,
2544 * 2. update res_counter
2545 * 3. call memory reclaim if necessary.
2547 * In some special case, if the task is fatal, fatal_signal_pending() or
2548 * has TIF_MEMDIE, this function returns -EINTR while writing root_mem_cgroup
2549 * to *ptr. There are two reasons for this. 1: fatal threads should quit as soon
2550 * as possible without any hazards. 2: all pages should have a valid
2551 * pc->mem_cgroup. If mm is NULL and the caller doesn't pass a valid memcg
2552 * pointer, that is treated as a charge to root_mem_cgroup.
2554 * So __mem_cgroup_try_charge() will return
2555 * 0 ... on success, filling *ptr with a valid memcg pointer.
2556 * -ENOMEM ... charge failure because of resource limits.
2557 * -EINTR ... if thread is fatal. *ptr is filled with root_mem_cgroup.
2559 * Unlike the exported interface, an "oom" parameter is added. if oom==true,
2560 * the oom-killer can be invoked.
2562 static int __mem_cgroup_try_charge(struct mm_struct *mm,
2564 unsigned int nr_pages,
2565 struct mem_cgroup **ptr,
2568 unsigned int batch = max(CHARGE_BATCH, nr_pages);
2569 int nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2570 struct mem_cgroup *memcg = NULL;
2574 * Unlike gloval-vm's OOM-kill, we're not in memory shortage
2575 * in system level. So, allow to go ahead dying process in addition to
2578 if (unlikely(test_thread_flag(TIF_MEMDIE)
2579 || fatal_signal_pending(current)))
2583 * We always charge the cgroup the mm_struct belongs to.
2584 * The mm_struct's mem_cgroup changes on task migration if the
2585 * thread group leader migrates. It's possible that mm is not
2586 * set, if so charge the root memcg (happens for pagecache usage).
2589 *ptr = root_mem_cgroup;
2591 if (*ptr) { /* css should be a valid one */
2593 if (mem_cgroup_is_root(memcg))
2595 if (consume_stock(memcg, nr_pages))
2597 css_get(&memcg->css);
2599 struct task_struct *p;
2602 p = rcu_dereference(mm->owner);
2604 * Because we don't have task_lock(), "p" can exit.
2605 * In that case, "memcg" can point to root or p can be NULL with
2606 * race with swapoff. Then, we have small risk of mis-accouning.
2607 * But such kind of mis-account by race always happens because
2608 * we don't have cgroup_mutex(). It's overkill and we allo that
2610 * (*) swapoff at el will charge against mm-struct not against
2611 * task-struct. So, mm->owner can be NULL.
2613 memcg = mem_cgroup_from_task(p);
2615 memcg = root_mem_cgroup;
2616 if (mem_cgroup_is_root(memcg)) {
2620 if (consume_stock(memcg, nr_pages)) {
2622 * It seems dagerous to access memcg without css_get().
2623 * But considering how consume_stok works, it's not
2624 * necessary. If consume_stock success, some charges
2625 * from this memcg are cached on this cpu. So, we
2626 * don't need to call css_get()/css_tryget() before
2627 * calling consume_stock().
2632 /* after here, we may be blocked. we need to get refcnt */
2633 if (!css_tryget(&memcg->css)) {
2641 bool invoke_oom = oom && !nr_oom_retries;
2643 /* If killed, bypass charge */
2644 if (fatal_signal_pending(current)) {
2645 css_put(&memcg->css);
2649 ret = mem_cgroup_do_charge(memcg, gfp_mask, batch,
2650 nr_pages, invoke_oom);
2654 case CHARGE_RETRY: /* not in OOM situation but retry */
2656 css_put(&memcg->css);
2659 case CHARGE_WOULDBLOCK: /* !__GFP_WAIT */
2660 css_put(&memcg->css);
2662 case CHARGE_NOMEM: /* OOM routine works */
2663 if (!oom || invoke_oom) {
2664 css_put(&memcg->css);
2670 } while (ret != CHARGE_OK);
2672 if (batch > nr_pages)
2673 refill_stock(memcg, batch - nr_pages);
2674 css_put(&memcg->css);
2682 *ptr = root_mem_cgroup;
2687 * Somemtimes we have to undo a charge we got by try_charge().
2688 * This function is for that and do uncharge, put css's refcnt.
2689 * gotten by try_charge().
2691 static void __mem_cgroup_cancel_charge(struct mem_cgroup *memcg,
2692 unsigned int nr_pages)
2694 if (!mem_cgroup_is_root(memcg)) {
2695 unsigned long bytes = nr_pages * PAGE_SIZE;
2697 res_counter_uncharge(&memcg->res, bytes);
2698 if (do_swap_account)
2699 res_counter_uncharge(&memcg->memsw, bytes);
2704 * Cancel chrages in this cgroup....doesn't propagate to parent cgroup.
2705 * This is useful when moving usage to parent cgroup.
2707 static void __mem_cgroup_cancel_local_charge(struct mem_cgroup *memcg,
2708 unsigned int nr_pages)
2710 unsigned long bytes = nr_pages * PAGE_SIZE;
2712 if (mem_cgroup_is_root(memcg))
2715 res_counter_uncharge_until(&memcg->res, memcg->res.parent, bytes);
2716 if (do_swap_account)
2717 res_counter_uncharge_until(&memcg->memsw,
2718 memcg->memsw.parent, bytes);
2722 * A helper function to get mem_cgroup from ID. must be called under
2723 * rcu_read_lock(). The caller is responsible for calling css_tryget if
2724 * the mem_cgroup is used for charging. (dropping refcnt from swap can be
2725 * called against removed memcg.)
2727 static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
2729 /* ID 0 is unused ID */
2732 return mem_cgroup_from_id(id);
2735 struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
2737 struct mem_cgroup *memcg = NULL;
2738 struct page_cgroup *pc;
2742 VM_BUG_ON(!PageLocked(page));
2744 pc = lookup_page_cgroup(page);
2745 lock_page_cgroup(pc);
2746 if (PageCgroupUsed(pc)) {
2747 memcg = pc->mem_cgroup;
2748 if (memcg && !css_tryget(&memcg->css))
2750 } else if (PageSwapCache(page)) {
2751 ent.val = page_private(page);
2752 id = lookup_swap_cgroup_id(ent);
2754 memcg = mem_cgroup_lookup(id);
2755 if (memcg && !css_tryget(&memcg->css))
2759 unlock_page_cgroup(pc);
2763 static void __mem_cgroup_commit_charge(struct mem_cgroup *memcg,
2765 unsigned int nr_pages,
2766 enum charge_type ctype,
2769 struct page_cgroup *pc = lookup_page_cgroup(page);
2770 struct zone *uninitialized_var(zone);
2771 struct lruvec *lruvec;
2772 bool was_on_lru = false;
2775 lock_page_cgroup(pc);
2776 VM_BUG_ON(PageCgroupUsed(pc));
2778 * we don't need page_cgroup_lock about tail pages, becase they are not
2779 * accessed by any other context at this point.
2783 * In some cases, SwapCache and FUSE(splice_buf->radixtree), the page
2784 * may already be on some other mem_cgroup's LRU. Take care of it.
2787 zone = page_zone(page);
2788 spin_lock_irq(&zone->lru_lock);
2789 if (PageLRU(page)) {
2790 lruvec = mem_cgroup_zone_lruvec(zone, pc->mem_cgroup);
2792 del_page_from_lru_list(page, lruvec, page_lru(page));
2797 pc->mem_cgroup = memcg;
2799 * We access a page_cgroup asynchronously without lock_page_cgroup().
2800 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
2801 * is accessed after testing USED bit. To make pc->mem_cgroup visible
2802 * before USED bit, we need memory barrier here.
2803 * See mem_cgroup_add_lru_list(), etc.
2806 SetPageCgroupUsed(pc);
2810 lruvec = mem_cgroup_zone_lruvec(zone, pc->mem_cgroup);
2811 VM_BUG_ON(PageLRU(page));
2813 add_page_to_lru_list(page, lruvec, page_lru(page));
2815 spin_unlock_irq(&zone->lru_lock);
2818 if (ctype == MEM_CGROUP_CHARGE_TYPE_ANON)
2823 mem_cgroup_charge_statistics(memcg, page, anon, nr_pages);
2824 unlock_page_cgroup(pc);
2827 * "charge_statistics" updated event counter.
2829 memcg_check_events(memcg, page);
2832 static DEFINE_MUTEX(set_limit_mutex);
2834 #ifdef CONFIG_MEMCG_KMEM
2835 static inline bool memcg_can_account_kmem(struct mem_cgroup *memcg)
2837 return !mem_cgroup_disabled() && !mem_cgroup_is_root(memcg) &&
2838 (memcg->kmem_account_flags & KMEM_ACCOUNTED_MASK);
2842 * This is a bit cumbersome, but it is rarely used and avoids a backpointer
2843 * in the memcg_cache_params struct.
2845 static struct kmem_cache *memcg_params_to_cache(struct memcg_cache_params *p)
2847 struct kmem_cache *cachep;
2849 VM_BUG_ON(p->is_root_cache);
2850 cachep = p->root_cache;
2851 return cachep->memcg_params->memcg_caches[memcg_cache_id(p->memcg)];
2854 #ifdef CONFIG_SLABINFO
2855 static int mem_cgroup_slabinfo_read(struct cgroup_subsys_state *css,
2856 struct cftype *cft, struct seq_file *m)
2858 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
2859 struct memcg_cache_params *params;
2861 if (!memcg_can_account_kmem(memcg))
2864 print_slabinfo_header(m);
2866 mutex_lock(&memcg->slab_caches_mutex);
2867 list_for_each_entry(params, &memcg->memcg_slab_caches, list)
2868 cache_show(memcg_params_to_cache(params), m);
2869 mutex_unlock(&memcg->slab_caches_mutex);
2875 static int memcg_charge_kmem(struct mem_cgroup *memcg, gfp_t gfp, u64 size)
2877 struct res_counter *fail_res;
2878 struct mem_cgroup *_memcg;
2882 ret = res_counter_charge(&memcg->kmem, size, &fail_res);
2887 * Conditions under which we can wait for the oom_killer. Those are
2888 * the same conditions tested by the core page allocator
2890 may_oom = (gfp & __GFP_FS) && !(gfp & __GFP_NORETRY);
2893 ret = __mem_cgroup_try_charge(NULL, gfp, size >> PAGE_SHIFT,
2896 if (ret == -EINTR) {
2898 * __mem_cgroup_try_charge() chosed to bypass to root due to
2899 * OOM kill or fatal signal. Since our only options are to
2900 * either fail the allocation or charge it to this cgroup, do
2901 * it as a temporary condition. But we can't fail. From a
2902 * kmem/slab perspective, the cache has already been selected,
2903 * by mem_cgroup_kmem_get_cache(), so it is too late to change
2906 * This condition will only trigger if the task entered
2907 * memcg_charge_kmem in a sane state, but was OOM-killed during
2908 * __mem_cgroup_try_charge() above. Tasks that were already
2909 * dying when the allocation triggers should have been already
2910 * directed to the root cgroup in memcontrol.h
2912 res_counter_charge_nofail(&memcg->res, size, &fail_res);
2913 if (do_swap_account)
2914 res_counter_charge_nofail(&memcg->memsw, size,
2918 res_counter_uncharge(&memcg->kmem, size);
2923 static void memcg_uncharge_kmem(struct mem_cgroup *memcg, u64 size)
2925 res_counter_uncharge(&memcg->res, size);
2926 if (do_swap_account)
2927 res_counter_uncharge(&memcg->memsw, size);
2930 if (res_counter_uncharge(&memcg->kmem, size))
2934 * Releases a reference taken in kmem_cgroup_css_offline in case
2935 * this last uncharge is racing with the offlining code or it is
2936 * outliving the memcg existence.
2938 * The memory barrier imposed by test&clear is paired with the
2939 * explicit one in memcg_kmem_mark_dead().
2941 if (memcg_kmem_test_and_clear_dead(memcg))
2942 css_put(&memcg->css);
2945 void memcg_cache_list_add(struct mem_cgroup *memcg, struct kmem_cache *cachep)
2950 mutex_lock(&memcg->slab_caches_mutex);
2951 list_add(&cachep->memcg_params->list, &memcg->memcg_slab_caches);
2952 mutex_unlock(&memcg->slab_caches_mutex);
2956 * helper for acessing a memcg's index. It will be used as an index in the
2957 * child cache array in kmem_cache, and also to derive its name. This function
2958 * will return -1 when this is not a kmem-limited memcg.
2960 int memcg_cache_id(struct mem_cgroup *memcg)
2962 return memcg ? memcg->kmemcg_id : -1;
2966 * This ends up being protected by the set_limit mutex, during normal
2967 * operation, because that is its main call site.
2969 * But when we create a new cache, we can call this as well if its parent
2970 * is kmem-limited. That will have to hold set_limit_mutex as well.
2972 int memcg_update_cache_sizes(struct mem_cgroup *memcg)
2976 num = ida_simple_get(&kmem_limited_groups,
2977 0, MEMCG_CACHES_MAX_SIZE, GFP_KERNEL);
2981 * After this point, kmem_accounted (that we test atomically in
2982 * the beginning of this conditional), is no longer 0. This
2983 * guarantees only one process will set the following boolean
2984 * to true. We don't need test_and_set because we're protected
2985 * by the set_limit_mutex anyway.
2987 memcg_kmem_set_activated(memcg);
2989 ret = memcg_update_all_caches(num+1);
2991 ida_simple_remove(&kmem_limited_groups, num);
2992 memcg_kmem_clear_activated(memcg);
2996 memcg->kmemcg_id = num;
2997 INIT_LIST_HEAD(&memcg->memcg_slab_caches);
2998 mutex_init(&memcg->slab_caches_mutex);
3002 static size_t memcg_caches_array_size(int num_groups)
3005 if (num_groups <= 0)
3008 size = 2 * num_groups;
3009 if (size < MEMCG_CACHES_MIN_SIZE)
3010 size = MEMCG_CACHES_MIN_SIZE;
3011 else if (size > MEMCG_CACHES_MAX_SIZE)
3012 size = MEMCG_CACHES_MAX_SIZE;
3018 * We should update the current array size iff all caches updates succeed. This
3019 * can only be done from the slab side. The slab mutex needs to be held when
3022 void memcg_update_array_size(int num)
3024 if (num > memcg_limited_groups_array_size)
3025 memcg_limited_groups_array_size = memcg_caches_array_size(num);
3028 static void kmem_cache_destroy_work_func(struct work_struct *w);
3030 int memcg_update_cache_size(struct kmem_cache *s, int num_groups)
3032 struct memcg_cache_params *cur_params = s->memcg_params;
3034 VM_BUG_ON(s->memcg_params && !s->memcg_params->is_root_cache);
3036 if (num_groups > memcg_limited_groups_array_size) {
3038 ssize_t size = memcg_caches_array_size(num_groups);
3040 size *= sizeof(void *);
3041 size += offsetof(struct memcg_cache_params, memcg_caches);
3043 s->memcg_params = kzalloc(size, GFP_KERNEL);
3044 if (!s->memcg_params) {
3045 s->memcg_params = cur_params;
3049 s->memcg_params->is_root_cache = true;
3052 * There is the chance it will be bigger than
3053 * memcg_limited_groups_array_size, if we failed an allocation
3054 * in a cache, in which case all caches updated before it, will
3055 * have a bigger array.
3057 * But if that is the case, the data after
3058 * memcg_limited_groups_array_size is certainly unused
3060 for (i = 0; i < memcg_limited_groups_array_size; i++) {
3061 if (!cur_params->memcg_caches[i])
3063 s->memcg_params->memcg_caches[i] =
3064 cur_params->memcg_caches[i];
3068 * Ideally, we would wait until all caches succeed, and only
3069 * then free the old one. But this is not worth the extra
3070 * pointer per-cache we'd have to have for this.
3072 * It is not a big deal if some caches are left with a size
3073 * bigger than the others. And all updates will reset this
3081 int memcg_register_cache(struct mem_cgroup *memcg, struct kmem_cache *s,
3082 struct kmem_cache *root_cache)
3086 if (!memcg_kmem_enabled())
3090 size = offsetof(struct memcg_cache_params, memcg_caches);
3091 size += memcg_limited_groups_array_size * sizeof(void *);
3093 size = sizeof(struct memcg_cache_params);
3095 s->memcg_params = kzalloc(size, GFP_KERNEL);
3096 if (!s->memcg_params)
3100 s->memcg_params->memcg = memcg;
3101 s->memcg_params->root_cache = root_cache;
3102 INIT_WORK(&s->memcg_params->destroy,
3103 kmem_cache_destroy_work_func);
3105 s->memcg_params->is_root_cache = true;
3110 void memcg_release_cache(struct kmem_cache *s)
3112 struct kmem_cache *root;
3113 struct mem_cgroup *memcg;
3117 * This happens, for instance, when a root cache goes away before we
3120 if (!s->memcg_params)
3123 if (s->memcg_params->is_root_cache)
3126 memcg = s->memcg_params->memcg;
3127 id = memcg_cache_id(memcg);
3129 root = s->memcg_params->root_cache;
3130 root->memcg_params->memcg_caches[id] = NULL;
3132 mutex_lock(&memcg->slab_caches_mutex);
3133 list_del(&s->memcg_params->list);
3134 mutex_unlock(&memcg->slab_caches_mutex);
3136 css_put(&memcg->css);
3138 kfree(s->memcg_params);
3142 * During the creation a new cache, we need to disable our accounting mechanism
3143 * altogether. This is true even if we are not creating, but rather just
3144 * enqueing new caches to be created.
3146 * This is because that process will trigger allocations; some visible, like
3147 * explicit kmallocs to auxiliary data structures, name strings and internal
3148 * cache structures; some well concealed, like INIT_WORK() that can allocate
3149 * objects during debug.
3151 * If any allocation happens during memcg_kmem_get_cache, we will recurse back
3152 * to it. This may not be a bounded recursion: since the first cache creation
3153 * failed to complete (waiting on the allocation), we'll just try to create the
3154 * cache again, failing at the same point.
3156 * memcg_kmem_get_cache is prepared to abort after seeing a positive count of
3157 * memcg_kmem_skip_account. So we enclose anything that might allocate memory
3158 * inside the following two functions.
3160 static inline void memcg_stop_kmem_account(void)
3162 VM_BUG_ON(!current->mm);
3163 current->memcg_kmem_skip_account++;
3166 static inline void memcg_resume_kmem_account(void)
3168 VM_BUG_ON(!current->mm);
3169 current->memcg_kmem_skip_account--;
3172 static void kmem_cache_destroy_work_func(struct work_struct *w)
3174 struct kmem_cache *cachep;
3175 struct memcg_cache_params *p;
3177 p = container_of(w, struct memcg_cache_params, destroy);
3179 cachep = memcg_params_to_cache(p);
3182 * If we get down to 0 after shrink, we could delete right away.
3183 * However, memcg_release_pages() already puts us back in the workqueue
3184 * in that case. If we proceed deleting, we'll get a dangling
3185 * reference, and removing the object from the workqueue in that case
3186 * is unnecessary complication. We are not a fast path.
3188 * Note that this case is fundamentally different from racing with
3189 * shrink_slab(): if memcg_cgroup_destroy_cache() is called in
3190 * kmem_cache_shrink, not only we would be reinserting a dead cache
3191 * into the queue, but doing so from inside the worker racing to
3194 * So if we aren't down to zero, we'll just schedule a worker and try
3197 if (atomic_read(&cachep->memcg_params->nr_pages) != 0) {
3198 kmem_cache_shrink(cachep);
3199 if (atomic_read(&cachep->memcg_params->nr_pages) == 0)
3202 kmem_cache_destroy(cachep);
3205 void mem_cgroup_destroy_cache(struct kmem_cache *cachep)
3207 if (!cachep->memcg_params->dead)
3211 * There are many ways in which we can get here.
3213 * We can get to a memory-pressure situation while the delayed work is
3214 * still pending to run. The vmscan shrinkers can then release all
3215 * cache memory and get us to destruction. If this is the case, we'll
3216 * be executed twice, which is a bug (the second time will execute over
3217 * bogus data). In this case, cancelling the work should be fine.
3219 * But we can also get here from the worker itself, if
3220 * kmem_cache_shrink is enough to shake all the remaining objects and
3221 * get the page count to 0. In this case, we'll deadlock if we try to
3222 * cancel the work (the worker runs with an internal lock held, which
3223 * is the same lock we would hold for cancel_work_sync().)
3225 * Since we can't possibly know who got us here, just refrain from
3226 * running if there is already work pending
3228 if (work_pending(&cachep->memcg_params->destroy))
3231 * We have to defer the actual destroying to a workqueue, because
3232 * we might currently be in a context that cannot sleep.
3234 schedule_work(&cachep->memcg_params->destroy);
3238 * This lock protects updaters, not readers. We want readers to be as fast as
3239 * they can, and they will either see NULL or a valid cache value. Our model
3240 * allow them to see NULL, in which case the root memcg will be selected.
3242 * We need this lock because multiple allocations to the same cache from a non
3243 * will span more than one worker. Only one of them can create the cache.
3245 static DEFINE_MUTEX(memcg_cache_mutex);
3248 * Called with memcg_cache_mutex held
3250 static struct kmem_cache *kmem_cache_dup(struct mem_cgroup *memcg,
3251 struct kmem_cache *s)
3253 struct kmem_cache *new;
3254 static char *tmp_name = NULL;
3256 lockdep_assert_held(&memcg_cache_mutex);
3259 * kmem_cache_create_memcg duplicates the given name and
3260 * cgroup_name for this name requires RCU context.
3261 * This static temporary buffer is used to prevent from
3262 * pointless shortliving allocation.
3265 tmp_name = kmalloc(PATH_MAX, GFP_KERNEL);
3271 snprintf(tmp_name, PATH_MAX, "%s(%d:%s)", s->name,
3272 memcg_cache_id(memcg), cgroup_name(memcg->css.cgroup));
3275 new = kmem_cache_create_memcg(memcg, tmp_name, s->object_size, s->align,
3276 (s->flags & ~SLAB_PANIC), s->ctor, s);
3279 new->allocflags |= __GFP_KMEMCG;
3284 static struct kmem_cache *memcg_create_kmem_cache(struct mem_cgroup *memcg,
3285 struct kmem_cache *cachep)
3287 struct kmem_cache *new_cachep;
3290 BUG_ON(!memcg_can_account_kmem(memcg));
3292 idx = memcg_cache_id(memcg);
3294 mutex_lock(&memcg_cache_mutex);
3295 new_cachep = cachep->memcg_params->memcg_caches[idx];
3297 css_put(&memcg->css);
3301 new_cachep = kmem_cache_dup(memcg, cachep);
3302 if (new_cachep == NULL) {
3303 new_cachep = cachep;
3304 css_put(&memcg->css);
3308 atomic_set(&new_cachep->memcg_params->nr_pages , 0);
3310 cachep->memcg_params->memcg_caches[idx] = new_cachep;
3312 * the readers won't lock, make sure everybody sees the updated value,
3313 * so they won't put stuff in the queue again for no reason
3317 mutex_unlock(&memcg_cache_mutex);
3321 void kmem_cache_destroy_memcg_children(struct kmem_cache *s)
3323 struct kmem_cache *c;
3326 if (!s->memcg_params)
3328 if (!s->memcg_params->is_root_cache)
3332 * If the cache is being destroyed, we trust that there is no one else
3333 * requesting objects from it. Even if there are, the sanity checks in
3334 * kmem_cache_destroy should caught this ill-case.
3336 * Still, we don't want anyone else freeing memcg_caches under our
3337 * noses, which can happen if a new memcg comes to life. As usual,
3338 * we'll take the set_limit_mutex to protect ourselves against this.
3340 mutex_lock(&set_limit_mutex);
3341 for (i = 0; i < memcg_limited_groups_array_size; i++) {
3342 c = s->memcg_params->memcg_caches[i];
3347 * We will now manually delete the caches, so to avoid races
3348 * we need to cancel all pending destruction workers and
3349 * proceed with destruction ourselves.
3351 * kmem_cache_destroy() will call kmem_cache_shrink internally,
3352 * and that could spawn the workers again: it is likely that
3353 * the cache still have active pages until this very moment.
3354 * This would lead us back to mem_cgroup_destroy_cache.
3356 * But that will not execute at all if the "dead" flag is not
3357 * set, so flip it down to guarantee we are in control.
3359 c->memcg_params->dead = false;
3360 cancel_work_sync(&c->memcg_params->destroy);
3361 kmem_cache_destroy(c);
3363 mutex_unlock(&set_limit_mutex);
3366 struct create_work {
3367 struct mem_cgroup *memcg;
3368 struct kmem_cache *cachep;
3369 struct work_struct work;
3372 static void mem_cgroup_destroy_all_caches(struct mem_cgroup *memcg)
3374 struct kmem_cache *cachep;
3375 struct memcg_cache_params *params;
3377 if (!memcg_kmem_is_active(memcg))
3380 mutex_lock(&memcg->slab_caches_mutex);
3381 list_for_each_entry(params, &memcg->memcg_slab_caches, list) {
3382 cachep = memcg_params_to_cache(params);
3383 cachep->memcg_params->dead = true;
3384 schedule_work(&cachep->memcg_params->destroy);
3386 mutex_unlock(&memcg->slab_caches_mutex);
3389 static void memcg_create_cache_work_func(struct work_struct *w)
3391 struct create_work *cw;
3393 cw = container_of(w, struct create_work, work);
3394 memcg_create_kmem_cache(cw->memcg, cw->cachep);
3399 * Enqueue the creation of a per-memcg kmem_cache.
3401 static void __memcg_create_cache_enqueue(struct mem_cgroup *memcg,
3402 struct kmem_cache *cachep)
3404 struct create_work *cw;
3406 cw = kmalloc(sizeof(struct create_work), GFP_NOWAIT);
3408 css_put(&memcg->css);
3413 cw->cachep = cachep;
3415 INIT_WORK(&cw->work, memcg_create_cache_work_func);
3416 schedule_work(&cw->work);
3419 static void memcg_create_cache_enqueue(struct mem_cgroup *memcg,
3420 struct kmem_cache *cachep)
3423 * We need to stop accounting when we kmalloc, because if the
3424 * corresponding kmalloc cache is not yet created, the first allocation
3425 * in __memcg_create_cache_enqueue will recurse.
3427 * However, it is better to enclose the whole function. Depending on
3428 * the debugging options enabled, INIT_WORK(), for instance, can
3429 * trigger an allocation. This too, will make us recurse. Because at
3430 * this point we can't allow ourselves back into memcg_kmem_get_cache,
3431 * the safest choice is to do it like this, wrapping the whole function.
3433 memcg_stop_kmem_account();
3434 __memcg_create_cache_enqueue(memcg, cachep);
3435 memcg_resume_kmem_account();
3438 * Return the kmem_cache we're supposed to use for a slab allocation.
3439 * We try to use the current memcg's version of the cache.
3441 * If the cache does not exist yet, if we are the first user of it,
3442 * we either create it immediately, if possible, or create it asynchronously
3444 * In the latter case, we will let the current allocation go through with
3445 * the original cache.
3447 * Can't be called in interrupt context or from kernel threads.
3448 * This function needs to be called with rcu_read_lock() held.
3450 struct kmem_cache *__memcg_kmem_get_cache(struct kmem_cache *cachep,
3453 struct mem_cgroup *memcg;
3456 VM_BUG_ON(!cachep->memcg_params);
3457 VM_BUG_ON(!cachep->memcg_params->is_root_cache);
3459 if (!current->mm || current->memcg_kmem_skip_account)
3463 memcg = mem_cgroup_from_task(rcu_dereference(current->mm->owner));
3465 if (!memcg_can_account_kmem(memcg))
3468 idx = memcg_cache_id(memcg);
3471 * barrier to mare sure we're always seeing the up to date value. The
3472 * code updating memcg_caches will issue a write barrier to match this.
3474 read_barrier_depends();
3475 if (likely(cachep->memcg_params->memcg_caches[idx])) {
3476 cachep = cachep->memcg_params->memcg_caches[idx];
3480 /* The corresponding put will be done in the workqueue. */
3481 if (!css_tryget(&memcg->css))
3486 * If we are in a safe context (can wait, and not in interrupt
3487 * context), we could be be predictable and return right away.
3488 * This would guarantee that the allocation being performed
3489 * already belongs in the new cache.
3491 * However, there are some clashes that can arrive from locking.
3492 * For instance, because we acquire the slab_mutex while doing
3493 * kmem_cache_dup, this means no further allocation could happen
3494 * with the slab_mutex held.
3496 * Also, because cache creation issue get_online_cpus(), this
3497 * creates a lock chain: memcg_slab_mutex -> cpu_hotplug_mutex,
3498 * that ends up reversed during cpu hotplug. (cpuset allocates
3499 * a bunch of GFP_KERNEL memory during cpuup). Due to all that,
3500 * better to defer everything.
3502 memcg_create_cache_enqueue(memcg, cachep);
3508 EXPORT_SYMBOL(__memcg_kmem_get_cache);
3511 * We need to verify if the allocation against current->mm->owner's memcg is
3512 * possible for the given order. But the page is not allocated yet, so we'll
3513 * need a further commit step to do the final arrangements.
3515 * It is possible for the task to switch cgroups in this mean time, so at
3516 * commit time, we can't rely on task conversion any longer. We'll then use
3517 * the handle argument to return to the caller which cgroup we should commit
3518 * against. We could also return the memcg directly and avoid the pointer
3519 * passing, but a boolean return value gives better semantics considering
3520 * the compiled-out case as well.
3522 * Returning true means the allocation is possible.
3525 __memcg_kmem_newpage_charge(gfp_t gfp, struct mem_cgroup **_memcg, int order)
3527 struct mem_cgroup *memcg;
3533 * Disabling accounting is only relevant for some specific memcg
3534 * internal allocations. Therefore we would initially not have such
3535 * check here, since direct calls to the page allocator that are marked
3536 * with GFP_KMEMCG only happen outside memcg core. We are mostly
3537 * concerned with cache allocations, and by having this test at
3538 * memcg_kmem_get_cache, we are already able to relay the allocation to
3539 * the root cache and bypass the memcg cache altogether.
3541 * There is one exception, though: the SLUB allocator does not create
3542 * large order caches, but rather service large kmallocs directly from
3543 * the page allocator. Therefore, the following sequence when backed by
3544 * the SLUB allocator:
3546 * memcg_stop_kmem_account();
3547 * kmalloc(<large_number>)
3548 * memcg_resume_kmem_account();
3550 * would effectively ignore the fact that we should skip accounting,
3551 * since it will drive us directly to this function without passing
3552 * through the cache selector memcg_kmem_get_cache. Such large
3553 * allocations are extremely rare but can happen, for instance, for the
3554 * cache arrays. We bring this test here.
3556 if (!current->mm || current->memcg_kmem_skip_account)
3559 memcg = try_get_mem_cgroup_from_mm(current->mm);
3562 * very rare case described in mem_cgroup_from_task. Unfortunately there
3563 * isn't much we can do without complicating this too much, and it would
3564 * be gfp-dependent anyway. Just let it go
3566 if (unlikely(!memcg))
3569 if (!memcg_can_account_kmem(memcg)) {
3570 css_put(&memcg->css);
3574 ret = memcg_charge_kmem(memcg, gfp, PAGE_SIZE << order);
3578 css_put(&memcg->css);
3582 void __memcg_kmem_commit_charge(struct page *page, struct mem_cgroup *memcg,
3585 struct page_cgroup *pc;
3587 VM_BUG_ON(mem_cgroup_is_root(memcg));
3589 /* The page allocation failed. Revert */
3591 memcg_uncharge_kmem(memcg, PAGE_SIZE << order);
3595 pc = lookup_page_cgroup(page);
3596 lock_page_cgroup(pc);
3597 pc->mem_cgroup = memcg;
3598 SetPageCgroupUsed(pc);
3599 unlock_page_cgroup(pc);
3602 void __memcg_kmem_uncharge_pages(struct page *page, int order)
3604 struct mem_cgroup *memcg = NULL;
3605 struct page_cgroup *pc;
3608 pc = lookup_page_cgroup(page);
3610 * Fast unlocked return. Theoretically might have changed, have to
3611 * check again after locking.
3613 if (!PageCgroupUsed(pc))
3616 lock_page_cgroup(pc);
3617 if (PageCgroupUsed(pc)) {
3618 memcg = pc->mem_cgroup;
3619 ClearPageCgroupUsed(pc);
3621 unlock_page_cgroup(pc);
3624 * We trust that only if there is a memcg associated with the page, it
3625 * is a valid allocation
3630 VM_BUG_ON(mem_cgroup_is_root(memcg));
3631 memcg_uncharge_kmem(memcg, PAGE_SIZE << order);
3634 static inline void mem_cgroup_destroy_all_caches(struct mem_cgroup *memcg)
3637 #endif /* CONFIG_MEMCG_KMEM */
3639 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3641 #define PCGF_NOCOPY_AT_SPLIT (1 << PCG_LOCK | 1 << PCG_MIGRATION)
3643 * Because tail pages are not marked as "used", set it. We're under
3644 * zone->lru_lock, 'splitting on pmd' and compound_lock.
3645 * charge/uncharge will be never happen and move_account() is done under
3646 * compound_lock(), so we don't have to take care of races.
3648 void mem_cgroup_split_huge_fixup(struct page *head)
3650 struct page_cgroup *head_pc = lookup_page_cgroup(head);
3651 struct page_cgroup *pc;
3652 struct mem_cgroup *memcg;
3655 if (mem_cgroup_disabled())
3658 memcg = head_pc->mem_cgroup;
3659 for (i = 1; i < HPAGE_PMD_NR; i++) {
3661 pc->mem_cgroup = memcg;
3662 smp_wmb();/* see __commit_charge() */
3663 pc->flags = head_pc->flags & ~PCGF_NOCOPY_AT_SPLIT;
3665 __this_cpu_sub(memcg->stat->count[MEM_CGROUP_STAT_RSS_HUGE],
3668 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
3671 void mem_cgroup_move_account_page_stat(struct mem_cgroup *from,
3672 struct mem_cgroup *to,
3673 unsigned int nr_pages,
3674 enum mem_cgroup_stat_index idx)
3676 /* Update stat data for mem_cgroup */
3678 WARN_ON_ONCE(from->stat->count[idx] < nr_pages);
3679 __this_cpu_add(from->stat->count[idx], -nr_pages);
3680 __this_cpu_add(to->stat->count[idx], nr_pages);
3685 * mem_cgroup_move_account - move account of the page
3687 * @nr_pages: number of regular pages (>1 for huge pages)
3688 * @pc: page_cgroup of the page.
3689 * @from: mem_cgroup which the page is moved from.
3690 * @to: mem_cgroup which the page is moved to. @from != @to.
3692 * The caller must confirm following.
3693 * - page is not on LRU (isolate_page() is useful.)
3694 * - compound_lock is held when nr_pages > 1
3696 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
3699 static int mem_cgroup_move_account(struct page *page,
3700 unsigned int nr_pages,
3701 struct page_cgroup *pc,
3702 struct mem_cgroup *from,
3703 struct mem_cgroup *to)
3705 unsigned long flags;
3707 bool anon = PageAnon(page);
3709 VM_BUG_ON(from == to);
3710 VM_BUG_ON(PageLRU(page));
3712 * The page is isolated from LRU. So, collapse function
3713 * will not handle this page. But page splitting can happen.
3714 * Do this check under compound_page_lock(). The caller should
3718 if (nr_pages > 1 && !PageTransHuge(page))
3721 lock_page_cgroup(pc);
3724 if (!PageCgroupUsed(pc) || pc->mem_cgroup != from)
3727 move_lock_mem_cgroup(from, &flags);
3729 if (!anon && page_mapped(page))
3730 mem_cgroup_move_account_page_stat(from, to, nr_pages,
3731 MEM_CGROUP_STAT_FILE_MAPPED);
3733 if (PageWriteback(page))
3734 mem_cgroup_move_account_page_stat(from, to, nr_pages,
3735 MEM_CGROUP_STAT_WRITEBACK);
3737 mem_cgroup_charge_statistics(from, page, anon, -nr_pages);
3739 /* caller should have done css_get */
3740 pc->mem_cgroup = to;
3741 mem_cgroup_charge_statistics(to, page, anon, nr_pages);
3742 move_unlock_mem_cgroup(from, &flags);
3745 unlock_page_cgroup(pc);
3749 memcg_check_events(to, page);
3750 memcg_check_events(from, page);
3756 * mem_cgroup_move_parent - moves page to the parent group
3757 * @page: the page to move
3758 * @pc: page_cgroup of the page
3759 * @child: page's cgroup
3761 * move charges to its parent or the root cgroup if the group has no
3762 * parent (aka use_hierarchy==0).
3763 * Although this might fail (get_page_unless_zero, isolate_lru_page or
3764 * mem_cgroup_move_account fails) the failure is always temporary and
3765 * it signals a race with a page removal/uncharge or migration. In the
3766 * first case the page is on the way out and it will vanish from the LRU
3767 * on the next attempt and the call should be retried later.
3768 * Isolation from the LRU fails only if page has been isolated from
3769 * the LRU since we looked at it and that usually means either global
3770 * reclaim or migration going on. The page will either get back to the
3772 * Finaly mem_cgroup_move_account fails only if the page got uncharged
3773 * (!PageCgroupUsed) or moved to a different group. The page will
3774 * disappear in the next attempt.
3776 static int mem_cgroup_move_parent(struct page *page,
3777 struct page_cgroup *pc,
3778 struct mem_cgroup *child)
3780 struct mem_cgroup *parent;
3781 unsigned int nr_pages;
3782 unsigned long uninitialized_var(flags);
3785 VM_BUG_ON(mem_cgroup_is_root(child));
3788 if (!get_page_unless_zero(page))
3790 if (isolate_lru_page(page))
3793 nr_pages = hpage_nr_pages(page);
3795 parent = parent_mem_cgroup(child);
3797 * If no parent, move charges to root cgroup.
3800 parent = root_mem_cgroup;
3803 VM_BUG_ON(!PageTransHuge(page));
3804 flags = compound_lock_irqsave(page);
3807 ret = mem_cgroup_move_account(page, nr_pages,
3810 __mem_cgroup_cancel_local_charge(child, nr_pages);
3813 compound_unlock_irqrestore(page, flags);
3814 putback_lru_page(page);
3822 * Charge the memory controller for page usage.
3824 * 0 if the charge was successful
3825 * < 0 if the cgroup is over its limit
3827 static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
3828 gfp_t gfp_mask, enum charge_type ctype)
3830 struct mem_cgroup *memcg = NULL;
3831 unsigned int nr_pages = 1;
3835 if (PageTransHuge(page)) {
3836 nr_pages <<= compound_order(page);
3837 VM_BUG_ON(!PageTransHuge(page));
3839 * Never OOM-kill a process for a huge page. The
3840 * fault handler will fall back to regular pages.
3845 ret = __mem_cgroup_try_charge(mm, gfp_mask, nr_pages, &memcg, oom);
3848 __mem_cgroup_commit_charge(memcg, page, nr_pages, ctype, false);
3852 int mem_cgroup_newpage_charge(struct page *page,
3853 struct mm_struct *mm, gfp_t gfp_mask)
3855 if (mem_cgroup_disabled())
3857 VM_BUG_ON(page_mapped(page));
3858 VM_BUG_ON(page->mapping && !PageAnon(page));
3860 return mem_cgroup_charge_common(page, mm, gfp_mask,
3861 MEM_CGROUP_CHARGE_TYPE_ANON);
3865 * While swap-in, try_charge -> commit or cancel, the page is locked.
3866 * And when try_charge() successfully returns, one refcnt to memcg without
3867 * struct page_cgroup is acquired. This refcnt will be consumed by
3868 * "commit()" or removed by "cancel()"
3870 static int __mem_cgroup_try_charge_swapin(struct mm_struct *mm,
3873 struct mem_cgroup **memcgp)
3875 struct mem_cgroup *memcg;
3876 struct page_cgroup *pc;
3879 pc = lookup_page_cgroup(page);
3881 * Every swap fault against a single page tries to charge the
3882 * page, bail as early as possible. shmem_unuse() encounters
3883 * already charged pages, too. The USED bit is protected by
3884 * the page lock, which serializes swap cache removal, which
3885 * in turn serializes uncharging.
3887 if (PageCgroupUsed(pc))
3889 if (!do_swap_account)
3891 memcg = try_get_mem_cgroup_from_page(page);
3895 ret = __mem_cgroup_try_charge(NULL, mask, 1, memcgp, true);
3896 css_put(&memcg->css);
3901 ret = __mem_cgroup_try_charge(mm, mask, 1, memcgp, true);
3907 int mem_cgroup_try_charge_swapin(struct mm_struct *mm, struct page *page,
3908 gfp_t gfp_mask, struct mem_cgroup **memcgp)
3911 if (mem_cgroup_disabled())
3914 * A racing thread's fault, or swapoff, may have already
3915 * updated the pte, and even removed page from swap cache: in
3916 * those cases unuse_pte()'s pte_same() test will fail; but
3917 * there's also a KSM case which does need to charge the page.
3919 if (!PageSwapCache(page)) {
3922 ret = __mem_cgroup_try_charge(mm, gfp_mask, 1, memcgp, true);
3927 return __mem_cgroup_try_charge_swapin(mm, page, gfp_mask, memcgp);
3930 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *memcg)
3932 if (mem_cgroup_disabled())
3936 __mem_cgroup_cancel_charge(memcg, 1);
3940 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *memcg,
3941 enum charge_type ctype)
3943 if (mem_cgroup_disabled())
3948 __mem_cgroup_commit_charge(memcg, page, 1, ctype, true);
3950 * Now swap is on-memory. This means this page may be
3951 * counted both as mem and swap....double count.
3952 * Fix it by uncharging from memsw. Basically, this SwapCache is stable
3953 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
3954 * may call delete_from_swap_cache() before reach here.
3956 if (do_swap_account && PageSwapCache(page)) {
3957 swp_entry_t ent = {.val = page_private(page)};
3958 mem_cgroup_uncharge_swap(ent);
3962 void mem_cgroup_commit_charge_swapin(struct page *page,
3963 struct mem_cgroup *memcg)
3965 __mem_cgroup_commit_charge_swapin(page, memcg,
3966 MEM_CGROUP_CHARGE_TYPE_ANON);
3969 int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
3972 struct mem_cgroup *memcg = NULL;
3973 enum charge_type type = MEM_CGROUP_CHARGE_TYPE_CACHE;
3976 if (mem_cgroup_disabled())
3978 if (PageCompound(page))
3981 if (!PageSwapCache(page))
3982 ret = mem_cgroup_charge_common(page, mm, gfp_mask, type);
3983 else { /* page is swapcache/shmem */
3984 ret = __mem_cgroup_try_charge_swapin(mm, page,
3987 __mem_cgroup_commit_charge_swapin(page, memcg, type);
3992 static void mem_cgroup_do_uncharge(struct mem_cgroup *memcg,
3993 unsigned int nr_pages,
3994 const enum charge_type ctype)
3996 struct memcg_batch_info *batch = NULL;
3997 bool uncharge_memsw = true;
3999 /* If swapout, usage of swap doesn't decrease */
4000 if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
4001 uncharge_memsw = false;
4003 batch = ¤t->memcg_batch;
4005 * In usual, we do css_get() when we remember memcg pointer.
4006 * But in this case, we keep res->usage until end of a series of
4007 * uncharges. Then, it's ok to ignore memcg's refcnt.
4010 batch->memcg = memcg;
4012 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
4013 * In those cases, all pages freed continuously can be expected to be in
4014 * the same cgroup and we have chance to coalesce uncharges.
4015 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
4016 * because we want to do uncharge as soon as possible.
4019 if (!batch->do_batch || test_thread_flag(TIF_MEMDIE))
4020 goto direct_uncharge;
4023 goto direct_uncharge;
4026 * In typical case, batch->memcg == mem. This means we can
4027 * merge a series of uncharges to an uncharge of res_counter.
4028 * If not, we uncharge res_counter ony by one.
4030 if (batch->memcg != memcg)
4031 goto direct_uncharge;
4032 /* remember freed charge and uncharge it later */
4035 batch->memsw_nr_pages++;
4038 res_counter_uncharge(&memcg->res, nr_pages * PAGE_SIZE);
4040 res_counter_uncharge(&memcg->memsw, nr_pages * PAGE_SIZE);
4041 if (unlikely(batch->memcg != memcg))
4042 memcg_oom_recover(memcg);
4046 * uncharge if !page_mapped(page)
4048 static struct mem_cgroup *
4049 __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype,
4052 struct mem_cgroup *memcg = NULL;
4053 unsigned int nr_pages = 1;
4054 struct page_cgroup *pc;
4057 if (mem_cgroup_disabled())
4060 if (PageTransHuge(page)) {
4061 nr_pages <<= compound_order(page);
4062 VM_BUG_ON(!PageTransHuge(page));
4065 * Check if our page_cgroup is valid
4067 pc = lookup_page_cgroup(page);
4068 if (unlikely(!PageCgroupUsed(pc)))
4071 lock_page_cgroup(pc);
4073 memcg = pc->mem_cgroup;
4075 if (!PageCgroupUsed(pc))
4078 anon = PageAnon(page);
4081 case MEM_CGROUP_CHARGE_TYPE_ANON:
4083 * Generally PageAnon tells if it's the anon statistics to be
4084 * updated; but sometimes e.g. mem_cgroup_uncharge_page() is
4085 * used before page reached the stage of being marked PageAnon.
4089 case MEM_CGROUP_CHARGE_TYPE_DROP:
4090 /* See mem_cgroup_prepare_migration() */
4091 if (page_mapped(page))
4094 * Pages under migration may not be uncharged. But
4095 * end_migration() /must/ be the one uncharging the
4096 * unused post-migration page and so it has to call
4097 * here with the migration bit still set. See the
4098 * res_counter handling below.
4100 if (!end_migration && PageCgroupMigration(pc))
4103 case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
4104 if (!PageAnon(page)) { /* Shared memory */
4105 if (page->mapping && !page_is_file_cache(page))
4107 } else if (page_mapped(page)) /* Anon */
4114 mem_cgroup_charge_statistics(memcg, page, anon, -nr_pages);
4116 ClearPageCgroupUsed(pc);
4118 * pc->mem_cgroup is not cleared here. It will be accessed when it's
4119 * freed from LRU. This is safe because uncharged page is expected not
4120 * to be reused (freed soon). Exception is SwapCache, it's handled by
4121 * special functions.
4124 unlock_page_cgroup(pc);
4126 * even after unlock, we have memcg->res.usage here and this memcg
4127 * will never be freed, so it's safe to call css_get().
4129 memcg_check_events(memcg, page);
4130 if (do_swap_account && ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT) {
4131 mem_cgroup_swap_statistics(memcg, true);
4132 css_get(&memcg->css);
4135 * Migration does not charge the res_counter for the
4136 * replacement page, so leave it alone when phasing out the
4137 * page that is unused after the migration.
4139 if (!end_migration && !mem_cgroup_is_root(memcg))
4140 mem_cgroup_do_uncharge(memcg, nr_pages, ctype);
4145 unlock_page_cgroup(pc);
4149 void mem_cgroup_uncharge_page(struct page *page)
4152 if (page_mapped(page))
4154 VM_BUG_ON(page->mapping && !PageAnon(page));
4156 * If the page is in swap cache, uncharge should be deferred
4157 * to the swap path, which also properly accounts swap usage
4158 * and handles memcg lifetime.
4160 * Note that this check is not stable and reclaim may add the
4161 * page to swap cache at any time after this. However, if the
4162 * page is not in swap cache by the time page->mapcount hits
4163 * 0, there won't be any page table references to the swap
4164 * slot, and reclaim will free it and not actually write the
4167 if (PageSwapCache(page))
4169 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_ANON, false);
4172 void mem_cgroup_uncharge_cache_page(struct page *page)
4174 VM_BUG_ON(page_mapped(page));
4175 VM_BUG_ON(page->mapping);
4176 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE, false);
4180 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
4181 * In that cases, pages are freed continuously and we can expect pages
4182 * are in the same memcg. All these calls itself limits the number of
4183 * pages freed at once, then uncharge_start/end() is called properly.
4184 * This may be called prural(2) times in a context,
4187 void mem_cgroup_uncharge_start(void)
4189 current->memcg_batch.do_batch++;
4190 /* We can do nest. */
4191 if (current->memcg_batch.do_batch == 1) {
4192 current->memcg_batch.memcg = NULL;
4193 current->memcg_batch.nr_pages = 0;
4194 current->memcg_batch.memsw_nr_pages = 0;
4198 void mem_cgroup_uncharge_end(void)
4200 struct memcg_batch_info *batch = ¤t->memcg_batch;
4202 if (!batch->do_batch)
4206 if (batch->do_batch) /* If stacked, do nothing. */
4212 * This "batch->memcg" is valid without any css_get/put etc...
4213 * bacause we hide charges behind us.
4215 if (batch->nr_pages)
4216 res_counter_uncharge(&batch->memcg->res,
4217 batch->nr_pages * PAGE_SIZE);
4218 if (batch->memsw_nr_pages)
4219 res_counter_uncharge(&batch->memcg->memsw,
4220 batch->memsw_nr_pages * PAGE_SIZE);
4221 memcg_oom_recover(batch->memcg);
4222 /* forget this pointer (for sanity check) */
4223 batch->memcg = NULL;
4228 * called after __delete_from_swap_cache() and drop "page" account.
4229 * memcg information is recorded to swap_cgroup of "ent"
4232 mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
4234 struct mem_cgroup *memcg;
4235 int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
4237 if (!swapout) /* this was a swap cache but the swap is unused ! */
4238 ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
4240 memcg = __mem_cgroup_uncharge_common(page, ctype, false);
4243 * record memcg information, if swapout && memcg != NULL,
4244 * css_get() was called in uncharge().
4246 if (do_swap_account && swapout && memcg)
4247 swap_cgroup_record(ent, mem_cgroup_id(memcg));
4251 #ifdef CONFIG_MEMCG_SWAP
4253 * called from swap_entry_free(). remove record in swap_cgroup and
4254 * uncharge "memsw" account.
4256 void mem_cgroup_uncharge_swap(swp_entry_t ent)
4258 struct mem_cgroup *memcg;
4261 if (!do_swap_account)
4264 id = swap_cgroup_record(ent, 0);
4266 memcg = mem_cgroup_lookup(id);
4269 * We uncharge this because swap is freed.
4270 * This memcg can be obsolete one. We avoid calling css_tryget
4272 if (!mem_cgroup_is_root(memcg))
4273 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
4274 mem_cgroup_swap_statistics(memcg, false);
4275 css_put(&memcg->css);
4281 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
4282 * @entry: swap entry to be moved
4283 * @from: mem_cgroup which the entry is moved from
4284 * @to: mem_cgroup which the entry is moved to
4286 * It succeeds only when the swap_cgroup's record for this entry is the same
4287 * as the mem_cgroup's id of @from.
4289 * Returns 0 on success, -EINVAL on failure.
4291 * The caller must have charged to @to, IOW, called res_counter_charge() about
4292 * both res and memsw, and called css_get().
4294 static int mem_cgroup_move_swap_account(swp_entry_t entry,
4295 struct mem_cgroup *from, struct mem_cgroup *to)
4297 unsigned short old_id, new_id;
4299 old_id = mem_cgroup_id(from);
4300 new_id = mem_cgroup_id(to);
4302 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
4303 mem_cgroup_swap_statistics(from, false);
4304 mem_cgroup_swap_statistics(to, true);
4306 * This function is only called from task migration context now.
4307 * It postpones res_counter and refcount handling till the end
4308 * of task migration(mem_cgroup_clear_mc()) for performance
4309 * improvement. But we cannot postpone css_get(to) because if
4310 * the process that has been moved to @to does swap-in, the
4311 * refcount of @to might be decreased to 0.
4313 * We are in attach() phase, so the cgroup is guaranteed to be
4314 * alive, so we can just call css_get().
4322 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
4323 struct mem_cgroup *from, struct mem_cgroup *to)
4330 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
4333 void mem_cgroup_prepare_migration(struct page *page, struct page *newpage,
4334 struct mem_cgroup **memcgp)
4336 struct mem_cgroup *memcg = NULL;
4337 unsigned int nr_pages = 1;
4338 struct page_cgroup *pc;
4339 enum charge_type ctype;
4343 if (mem_cgroup_disabled())
4346 if (PageTransHuge(page))
4347 nr_pages <<= compound_order(page);
4349 pc = lookup_page_cgroup(page);
4350 lock_page_cgroup(pc);
4351 if (PageCgroupUsed(pc)) {
4352 memcg = pc->mem_cgroup;
4353 css_get(&memcg->css);
4355 * At migrating an anonymous page, its mapcount goes down
4356 * to 0 and uncharge() will be called. But, even if it's fully
4357 * unmapped, migration may fail and this page has to be
4358 * charged again. We set MIGRATION flag here and delay uncharge
4359 * until end_migration() is called
4361 * Corner Case Thinking
4363 * When the old page was mapped as Anon and it's unmap-and-freed
4364 * while migration was ongoing.
4365 * If unmap finds the old page, uncharge() of it will be delayed
4366 * until end_migration(). If unmap finds a new page, it's
4367 * uncharged when it make mapcount to be 1->0. If unmap code
4368 * finds swap_migration_entry, the new page will not be mapped
4369 * and end_migration() will find it(mapcount==0).
4372 * When the old page was mapped but migraion fails, the kernel
4373 * remaps it. A charge for it is kept by MIGRATION flag even
4374 * if mapcount goes down to 0. We can do remap successfully
4375 * without charging it again.
4378 * The "old" page is under lock_page() until the end of
4379 * migration, so, the old page itself will not be swapped-out.
4380 * If the new page is swapped out before end_migraton, our
4381 * hook to usual swap-out path will catch the event.
4384 SetPageCgroupMigration(pc);
4386 unlock_page_cgroup(pc);
4388 * If the page is not charged at this point,
4396 * We charge new page before it's used/mapped. So, even if unlock_page()
4397 * is called before end_migration, we can catch all events on this new
4398 * page. In the case new page is migrated but not remapped, new page's
4399 * mapcount will be finally 0 and we call uncharge in end_migration().
4402 ctype = MEM_CGROUP_CHARGE_TYPE_ANON;
4404 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
4406 * The page is committed to the memcg, but it's not actually
4407 * charged to the res_counter since we plan on replacing the
4408 * old one and only one page is going to be left afterwards.
4410 __mem_cgroup_commit_charge(memcg, newpage, nr_pages, ctype, false);
4413 /* remove redundant charge if migration failed*/
4414 void mem_cgroup_end_migration(struct mem_cgroup *memcg,
4415 struct page *oldpage, struct page *newpage, bool migration_ok)
4417 struct page *used, *unused;
4418 struct page_cgroup *pc;
4424 if (!migration_ok) {
4431 anon = PageAnon(used);
4432 __mem_cgroup_uncharge_common(unused,
4433 anon ? MEM_CGROUP_CHARGE_TYPE_ANON
4434 : MEM_CGROUP_CHARGE_TYPE_CACHE,
4436 css_put(&memcg->css);
4438 * We disallowed uncharge of pages under migration because mapcount
4439 * of the page goes down to zero, temporarly.
4440 * Clear the flag and check the page should be charged.
4442 pc = lookup_page_cgroup(oldpage);
4443 lock_page_cgroup(pc);
4444 ClearPageCgroupMigration(pc);
4445 unlock_page_cgroup(pc);
4448 * If a page is a file cache, radix-tree replacement is very atomic
4449 * and we can skip this check. When it was an Anon page, its mapcount
4450 * goes down to 0. But because we added MIGRATION flage, it's not
4451 * uncharged yet. There are several case but page->mapcount check
4452 * and USED bit check in mem_cgroup_uncharge_page() will do enough
4453 * check. (see prepare_charge() also)
4456 mem_cgroup_uncharge_page(used);
4460 * At replace page cache, newpage is not under any memcg but it's on
4461 * LRU. So, this function doesn't touch res_counter but handles LRU
4462 * in correct way. Both pages are locked so we cannot race with uncharge.
4464 void mem_cgroup_replace_page_cache(struct page *oldpage,
4465 struct page *newpage)
4467 struct mem_cgroup *memcg = NULL;
4468 struct page_cgroup *pc;
4469 enum charge_type type = MEM_CGROUP_CHARGE_TYPE_CACHE;
4471 if (mem_cgroup_disabled())
4474 pc = lookup_page_cgroup(oldpage);
4475 /* fix accounting on old pages */
4476 lock_page_cgroup(pc);
4477 if (PageCgroupUsed(pc)) {
4478 memcg = pc->mem_cgroup;
4479 mem_cgroup_charge_statistics(memcg, oldpage, false, -1);
4480 ClearPageCgroupUsed(pc);
4482 unlock_page_cgroup(pc);
4485 * When called from shmem_replace_page(), in some cases the
4486 * oldpage has already been charged, and in some cases not.
4491 * Even if newpage->mapping was NULL before starting replacement,
4492 * the newpage may be on LRU(or pagevec for LRU) already. We lock
4493 * LRU while we overwrite pc->mem_cgroup.
4495 __mem_cgroup_commit_charge(memcg, newpage, 1, type, true);
4498 #ifdef CONFIG_DEBUG_VM
4499 static struct page_cgroup *lookup_page_cgroup_used(struct page *page)
4501 struct page_cgroup *pc;
4503 pc = lookup_page_cgroup(page);
4505 * Can be NULL while feeding pages into the page allocator for
4506 * the first time, i.e. during boot or memory hotplug;
4507 * or when mem_cgroup_disabled().
4509 if (likely(pc) && PageCgroupUsed(pc))
4514 bool mem_cgroup_bad_page_check(struct page *page)
4516 if (mem_cgroup_disabled())
4519 return lookup_page_cgroup_used(page) != NULL;
4522 void mem_cgroup_print_bad_page(struct page *page)
4524 struct page_cgroup *pc;
4526 pc = lookup_page_cgroup_used(page);
4528 pr_alert("pc:%p pc->flags:%lx pc->mem_cgroup:%p\n",
4529 pc, pc->flags, pc->mem_cgroup);
4534 static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
4535 unsigned long long val)
4538 u64 memswlimit, memlimit;
4540 int children = mem_cgroup_count_children(memcg);
4541 u64 curusage, oldusage;
4545 * For keeping hierarchical_reclaim simple, how long we should retry
4546 * is depends on callers. We set our retry-count to be function
4547 * of # of children which we should visit in this loop.
4549 retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
4551 oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
4554 while (retry_count) {
4555 if (signal_pending(current)) {
4560 * Rather than hide all in some function, I do this in
4561 * open coded manner. You see what this really does.
4562 * We have to guarantee memcg->res.limit <= memcg->memsw.limit.
4564 mutex_lock(&set_limit_mutex);
4565 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
4566 if (memswlimit < val) {
4568 mutex_unlock(&set_limit_mutex);
4572 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
4576 ret = res_counter_set_limit(&memcg->res, val);
4578 if (memswlimit == val)
4579 memcg->memsw_is_minimum = true;
4581 memcg->memsw_is_minimum = false;
4583 mutex_unlock(&set_limit_mutex);
4588 mem_cgroup_reclaim(memcg, GFP_KERNEL,
4589 MEM_CGROUP_RECLAIM_SHRINK);
4590 curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
4591 /* Usage is reduced ? */
4592 if (curusage >= oldusage)
4595 oldusage = curusage;
4597 if (!ret && enlarge)
4598 memcg_oom_recover(memcg);
4603 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
4604 unsigned long long val)
4607 u64 memlimit, memswlimit, oldusage, curusage;
4608 int children = mem_cgroup_count_children(memcg);
4612 /* see mem_cgroup_resize_res_limit */
4613 retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
4614 oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
4615 while (retry_count) {
4616 if (signal_pending(current)) {
4621 * Rather than hide all in some function, I do this in
4622 * open coded manner. You see what this really does.
4623 * We have to guarantee memcg->res.limit <= memcg->memsw.limit.
4625 mutex_lock(&set_limit_mutex);
4626 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
4627 if (memlimit > val) {
4629 mutex_unlock(&set_limit_mutex);
4632 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
4633 if (memswlimit < val)
4635 ret = res_counter_set_limit(&memcg->memsw, val);
4637 if (memlimit == val)
4638 memcg->memsw_is_minimum = true;
4640 memcg->memsw_is_minimum = false;
4642 mutex_unlock(&set_limit_mutex);
4647 mem_cgroup_reclaim(memcg, GFP_KERNEL,
4648 MEM_CGROUP_RECLAIM_NOSWAP |
4649 MEM_CGROUP_RECLAIM_SHRINK);
4650 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
4651 /* Usage is reduced ? */
4652 if (curusage >= oldusage)
4655 oldusage = curusage;
4657 if (!ret && enlarge)
4658 memcg_oom_recover(memcg);
4663 * mem_cgroup_force_empty_list - clears LRU of a group
4664 * @memcg: group to clear
4667 * @lru: lru to to clear
4669 * Traverse a specified page_cgroup list and try to drop them all. This doesn't
4670 * reclaim the pages page themselves - pages are moved to the parent (or root)
4673 static void mem_cgroup_force_empty_list(struct mem_cgroup *memcg,
4674 int node, int zid, enum lru_list lru)
4676 struct lruvec *lruvec;
4677 unsigned long flags;
4678 struct list_head *list;
4682 zone = &NODE_DATA(node)->node_zones[zid];
4683 lruvec = mem_cgroup_zone_lruvec(zone, memcg);
4684 list = &lruvec->lists[lru];
4688 struct page_cgroup *pc;
4691 spin_lock_irqsave(&zone->lru_lock, flags);
4692 if (list_empty(list)) {
4693 spin_unlock_irqrestore(&zone->lru_lock, flags);
4696 page = list_entry(list->prev, struct page, lru);
4698 list_move(&page->lru, list);
4700 spin_unlock_irqrestore(&zone->lru_lock, flags);
4703 spin_unlock_irqrestore(&zone->lru_lock, flags);
4705 pc = lookup_page_cgroup(page);
4707 if (mem_cgroup_move_parent(page, pc, memcg)) {
4708 /* found lock contention or "pc" is obsolete. */
4713 } while (!list_empty(list));
4717 * make mem_cgroup's charge to be 0 if there is no task by moving
4718 * all the charges and pages to the parent.
4719 * This enables deleting this mem_cgroup.
4721 * Caller is responsible for holding css reference on the memcg.
4723 static void mem_cgroup_reparent_charges(struct mem_cgroup *memcg)
4729 /* This is for making all *used* pages to be on LRU. */
4730 lru_add_drain_all();
4731 drain_all_stock_sync(memcg);
4732 mem_cgroup_start_move(memcg);
4733 for_each_node_state(node, N_MEMORY) {
4734 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
4737 mem_cgroup_force_empty_list(memcg,
4742 mem_cgroup_end_move(memcg);
4743 memcg_oom_recover(memcg);
4747 * Kernel memory may not necessarily be trackable to a specific
4748 * process. So they are not migrated, and therefore we can't
4749 * expect their value to drop to 0 here.
4750 * Having res filled up with kmem only is enough.
4752 * This is a safety check because mem_cgroup_force_empty_list
4753 * could have raced with mem_cgroup_replace_page_cache callers
4754 * so the lru seemed empty but the page could have been added
4755 * right after the check. RES_USAGE should be safe as we always
4756 * charge before adding to the LRU.
4758 usage = res_counter_read_u64(&memcg->res, RES_USAGE) -
4759 res_counter_read_u64(&memcg->kmem, RES_USAGE);
4760 } while (usage > 0);
4764 * This mainly exists for tests during the setting of set of use_hierarchy.
4765 * Since this is the very setting we are changing, the current hierarchy value
4768 static inline bool __memcg_has_children(struct mem_cgroup *memcg)
4770 struct cgroup_subsys_state *pos;
4772 /* bounce at first found */
4773 css_for_each_child(pos, &memcg->css)
4779 * Must be called with memcg_create_mutex held, unless the cgroup is guaranteed
4780 * to be already dead (as in mem_cgroup_force_empty, for instance). This is
4781 * from mem_cgroup_count_children(), in the sense that we don't really care how
4782 * many children we have; we only need to know if we have any. It also counts
4783 * any memcg without hierarchy as infertile.
4785 static inline bool memcg_has_children(struct mem_cgroup *memcg)
4787 return memcg->use_hierarchy && __memcg_has_children(memcg);
4791 * Reclaims as many pages from the given memcg as possible and moves
4792 * the rest to the parent.
4794 * Caller is responsible for holding css reference for memcg.
4796 static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
4798 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
4799 struct cgroup *cgrp = memcg->css.cgroup;
4801 /* returns EBUSY if there is a task or if we come here twice. */
4802 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
4805 /* we call try-to-free pages for make this cgroup empty */
4806 lru_add_drain_all();
4807 /* try to free all pages in this cgroup */
4808 while (nr_retries && res_counter_read_u64(&memcg->res, RES_USAGE) > 0) {
4811 if (signal_pending(current))
4814 progress = try_to_free_mem_cgroup_pages(memcg, GFP_KERNEL,
4818 /* maybe some writeback is necessary */
4819 congestion_wait(BLK_RW_ASYNC, HZ/10);
4824 mem_cgroup_reparent_charges(memcg);
4829 static int mem_cgroup_force_empty_write(struct cgroup_subsys_state *css,
4832 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4834 if (mem_cgroup_is_root(memcg))
4836 return mem_cgroup_force_empty(memcg);
4839 static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
4842 return mem_cgroup_from_css(css)->use_hierarchy;
4845 static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
4846 struct cftype *cft, u64 val)
4849 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4850 struct mem_cgroup *parent_memcg = mem_cgroup_from_css(css_parent(&memcg->css));
4852 mutex_lock(&memcg_create_mutex);
4854 if (memcg->use_hierarchy == val)
4858 * If parent's use_hierarchy is set, we can't make any modifications
4859 * in the child subtrees. If it is unset, then the change can
4860 * occur, provided the current cgroup has no children.
4862 * For the root cgroup, parent_mem is NULL, we allow value to be
4863 * set if there are no children.
4865 if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
4866 (val == 1 || val == 0)) {
4867 if (!__memcg_has_children(memcg))
4868 memcg->use_hierarchy = val;
4875 mutex_unlock(&memcg_create_mutex);
4881 static unsigned long mem_cgroup_recursive_stat(struct mem_cgroup *memcg,
4882 enum mem_cgroup_stat_index idx)
4884 struct mem_cgroup *iter;
4887 /* Per-cpu values can be negative, use a signed accumulator */
4888 for_each_mem_cgroup_tree(iter, memcg)
4889 val += mem_cgroup_read_stat(iter, idx);
4891 if (val < 0) /* race ? */
4896 static inline u64 mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
4900 if (!mem_cgroup_is_root(memcg)) {
4902 return res_counter_read_u64(&memcg->res, RES_USAGE);
4904 return res_counter_read_u64(&memcg->memsw, RES_USAGE);
4908 * Transparent hugepages are still accounted for in MEM_CGROUP_STAT_RSS
4909 * as well as in MEM_CGROUP_STAT_RSS_HUGE.
4911 val = mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_CACHE);
4912 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_RSS);
4915 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_SWAP);
4917 return val << PAGE_SHIFT;
4920 static ssize_t mem_cgroup_read(struct cgroup_subsys_state *css,
4921 struct cftype *cft, struct file *file,
4922 char __user *buf, size_t nbytes, loff_t *ppos)
4924 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4930 type = MEMFILE_TYPE(cft->private);
4931 name = MEMFILE_ATTR(cft->private);
4935 if (name == RES_USAGE)
4936 val = mem_cgroup_usage(memcg, false);
4938 val = res_counter_read_u64(&memcg->res, name);
4941 if (name == RES_USAGE)
4942 val = mem_cgroup_usage(memcg, true);
4944 val = res_counter_read_u64(&memcg->memsw, name);
4947 val = res_counter_read_u64(&memcg->kmem, name);
4953 len = scnprintf(str, sizeof(str), "%llu\n", (unsigned long long)val);
4954 return simple_read_from_buffer(buf, nbytes, ppos, str, len);
4957 static int memcg_update_kmem_limit(struct cgroup_subsys_state *css, u64 val)
4960 #ifdef CONFIG_MEMCG_KMEM
4961 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4963 * For simplicity, we won't allow this to be disabled. It also can't
4964 * be changed if the cgroup has children already, or if tasks had
4967 * If tasks join before we set the limit, a person looking at
4968 * kmem.usage_in_bytes will have no way to determine when it took
4969 * place, which makes the value quite meaningless.
4971 * After it first became limited, changes in the value of the limit are
4972 * of course permitted.
4974 mutex_lock(&memcg_create_mutex);
4975 mutex_lock(&set_limit_mutex);
4976 if (!memcg->kmem_account_flags && val != RES_COUNTER_MAX) {
4977 if (cgroup_task_count(css->cgroup) || memcg_has_children(memcg)) {
4981 ret = res_counter_set_limit(&memcg->kmem, val);
4984 ret = memcg_update_cache_sizes(memcg);
4986 res_counter_set_limit(&memcg->kmem, RES_COUNTER_MAX);
4989 static_key_slow_inc(&memcg_kmem_enabled_key);
4991 * setting the active bit after the inc will guarantee no one
4992 * starts accounting before all call sites are patched
4994 memcg_kmem_set_active(memcg);
4996 ret = res_counter_set_limit(&memcg->kmem, val);
4998 mutex_unlock(&set_limit_mutex);
4999 mutex_unlock(&memcg_create_mutex);
5004 #ifdef CONFIG_MEMCG_KMEM
5005 static int memcg_propagate_kmem(struct mem_cgroup *memcg)
5008 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
5012 memcg->kmem_account_flags = parent->kmem_account_flags;
5014 * When that happen, we need to disable the static branch only on those
5015 * memcgs that enabled it. To achieve this, we would be forced to
5016 * complicate the code by keeping track of which memcgs were the ones
5017 * that actually enabled limits, and which ones got it from its
5020 * It is a lot simpler just to do static_key_slow_inc() on every child
5021 * that is accounted.
5023 if (!memcg_kmem_is_active(memcg))
5027 * __mem_cgroup_free() will issue static_key_slow_dec() because this
5028 * memcg is active already. If the later initialization fails then the
5029 * cgroup core triggers the cleanup so we do not have to do it here.
5031 static_key_slow_inc(&memcg_kmem_enabled_key);
5033 mutex_lock(&set_limit_mutex);
5034 memcg_stop_kmem_account();
5035 ret = memcg_update_cache_sizes(memcg);
5036 memcg_resume_kmem_account();
5037 mutex_unlock(&set_limit_mutex);
5041 #endif /* CONFIG_MEMCG_KMEM */
5044 * The user of this function is...
5047 static int mem_cgroup_write(struct cgroup_subsys_state *css, struct cftype *cft,
5050 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5053 unsigned long long val;
5056 type = MEMFILE_TYPE(cft->private);
5057 name = MEMFILE_ATTR(cft->private);
5061 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
5065 /* This function does all necessary parse...reuse it */
5066 ret = res_counter_memparse_write_strategy(buffer, &val);
5070 ret = mem_cgroup_resize_limit(memcg, val);
5071 else if (type == _MEMSWAP)
5072 ret = mem_cgroup_resize_memsw_limit(memcg, val);
5073 else if (type == _KMEM)
5074 ret = memcg_update_kmem_limit(css, val);
5078 case RES_SOFT_LIMIT:
5079 ret = res_counter_memparse_write_strategy(buffer, &val);
5083 * For memsw, soft limits are hard to implement in terms
5084 * of semantics, for now, we support soft limits for
5085 * control without swap
5088 ret = res_counter_set_soft_limit(&memcg->res, val);
5093 ret = -EINVAL; /* should be BUG() ? */
5099 static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
5100 unsigned long long *mem_limit, unsigned long long *memsw_limit)
5102 unsigned long long min_limit, min_memsw_limit, tmp;
5104 min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
5105 min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
5106 if (!memcg->use_hierarchy)
5109 while (css_parent(&memcg->css)) {
5110 memcg = mem_cgroup_from_css(css_parent(&memcg->css));
5111 if (!memcg->use_hierarchy)
5113 tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
5114 min_limit = min(min_limit, tmp);
5115 tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
5116 min_memsw_limit = min(min_memsw_limit, tmp);
5119 *mem_limit = min_limit;
5120 *memsw_limit = min_memsw_limit;
5123 static int mem_cgroup_reset(struct cgroup_subsys_state *css, unsigned int event)
5125 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5129 type = MEMFILE_TYPE(event);
5130 name = MEMFILE_ATTR(event);
5135 res_counter_reset_max(&memcg->res);
5136 else if (type == _MEMSWAP)
5137 res_counter_reset_max(&memcg->memsw);
5138 else if (type == _KMEM)
5139 res_counter_reset_max(&memcg->kmem);
5145 res_counter_reset_failcnt(&memcg->res);
5146 else if (type == _MEMSWAP)
5147 res_counter_reset_failcnt(&memcg->memsw);
5148 else if (type == _KMEM)
5149 res_counter_reset_failcnt(&memcg->kmem);
5158 static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
5161 return mem_cgroup_from_css(css)->move_charge_at_immigrate;
5165 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
5166 struct cftype *cft, u64 val)
5168 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5170 if (val >= (1 << NR_MOVE_TYPE))
5174 * No kind of locking is needed in here, because ->can_attach() will
5175 * check this value once in the beginning of the process, and then carry
5176 * on with stale data. This means that changes to this value will only
5177 * affect task migrations starting after the change.
5179 memcg->move_charge_at_immigrate = val;
5183 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
5184 struct cftype *cft, u64 val)
5191 static int memcg_numa_stat_show(struct cgroup_subsys_state *css,
5192 struct cftype *cft, struct seq_file *m)
5195 unsigned long total_nr, file_nr, anon_nr, unevictable_nr;
5196 unsigned long node_nr;
5197 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5199 total_nr = mem_cgroup_nr_lru_pages(memcg, LRU_ALL);
5200 seq_printf(m, "total=%lu", total_nr);
5201 for_each_node_state(nid, N_MEMORY) {
5202 node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL);
5203 seq_printf(m, " N%d=%lu", nid, node_nr);
5207 file_nr = mem_cgroup_nr_lru_pages(memcg, LRU_ALL_FILE);
5208 seq_printf(m, "file=%lu", file_nr);
5209 for_each_node_state(nid, N_MEMORY) {
5210 node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
5212 seq_printf(m, " N%d=%lu", nid, node_nr);
5216 anon_nr = mem_cgroup_nr_lru_pages(memcg, LRU_ALL_ANON);
5217 seq_printf(m, "anon=%lu", anon_nr);
5218 for_each_node_state(nid, N_MEMORY) {
5219 node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
5221 seq_printf(m, " N%d=%lu", nid, node_nr);
5225 unevictable_nr = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_UNEVICTABLE));
5226 seq_printf(m, "unevictable=%lu", unevictable_nr);
5227 for_each_node_state(nid, N_MEMORY) {
5228 node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
5229 BIT(LRU_UNEVICTABLE));
5230 seq_printf(m, " N%d=%lu", nid, node_nr);
5235 #endif /* CONFIG_NUMA */
5237 static inline void mem_cgroup_lru_names_not_uptodate(void)
5239 BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_lru_names) != NR_LRU_LISTS);
5242 static int memcg_stat_show(struct cgroup_subsys_state *css, struct cftype *cft,
5245 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5246 struct mem_cgroup *mi;
5249 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
5250 if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
5252 seq_printf(m, "%s %ld\n", mem_cgroup_stat_names[i],
5253 mem_cgroup_read_stat(memcg, i) * PAGE_SIZE);
5256 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++)
5257 seq_printf(m, "%s %lu\n", mem_cgroup_events_names[i],
5258 mem_cgroup_read_events(memcg, i));
5260 for (i = 0; i < NR_LRU_LISTS; i++)
5261 seq_printf(m, "%s %lu\n", mem_cgroup_lru_names[i],
5262 mem_cgroup_nr_lru_pages(memcg, BIT(i)) * PAGE_SIZE);
5264 /* Hierarchical information */
5266 unsigned long long limit, memsw_limit;
5267 memcg_get_hierarchical_limit(memcg, &limit, &memsw_limit);
5268 seq_printf(m, "hierarchical_memory_limit %llu\n", limit);
5269 if (do_swap_account)
5270 seq_printf(m, "hierarchical_memsw_limit %llu\n",
5274 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
5277 if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
5279 for_each_mem_cgroup_tree(mi, memcg)
5280 val += mem_cgroup_read_stat(mi, i) * PAGE_SIZE;
5281 seq_printf(m, "total_%s %lld\n", mem_cgroup_stat_names[i], val);
5284 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
5285 unsigned long long val = 0;
5287 for_each_mem_cgroup_tree(mi, memcg)
5288 val += mem_cgroup_read_events(mi, i);
5289 seq_printf(m, "total_%s %llu\n",
5290 mem_cgroup_events_names[i], val);
5293 for (i = 0; i < NR_LRU_LISTS; i++) {
5294 unsigned long long val = 0;
5296 for_each_mem_cgroup_tree(mi, memcg)
5297 val += mem_cgroup_nr_lru_pages(mi, BIT(i)) * PAGE_SIZE;
5298 seq_printf(m, "total_%s %llu\n", mem_cgroup_lru_names[i], val);
5301 #ifdef CONFIG_DEBUG_VM
5304 struct mem_cgroup_per_zone *mz;
5305 struct zone_reclaim_stat *rstat;
5306 unsigned long recent_rotated[2] = {0, 0};
5307 unsigned long recent_scanned[2] = {0, 0};
5309 for_each_online_node(nid)
5310 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
5311 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
5312 rstat = &mz->lruvec.reclaim_stat;
5314 recent_rotated[0] += rstat->recent_rotated[0];
5315 recent_rotated[1] += rstat->recent_rotated[1];
5316 recent_scanned[0] += rstat->recent_scanned[0];
5317 recent_scanned[1] += rstat->recent_scanned[1];
5319 seq_printf(m, "recent_rotated_anon %lu\n", recent_rotated[0]);
5320 seq_printf(m, "recent_rotated_file %lu\n", recent_rotated[1]);
5321 seq_printf(m, "recent_scanned_anon %lu\n", recent_scanned[0]);
5322 seq_printf(m, "recent_scanned_file %lu\n", recent_scanned[1]);
5329 static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
5332 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5334 return mem_cgroup_swappiness(memcg);
5337 static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
5338 struct cftype *cft, u64 val)
5340 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5341 struct mem_cgroup *parent = mem_cgroup_from_css(css_parent(&memcg->css));
5343 if (val > 100 || !parent)
5346 mutex_lock(&memcg_create_mutex);
5348 /* If under hierarchy, only empty-root can set this value */
5349 if ((parent->use_hierarchy) || memcg_has_children(memcg)) {
5350 mutex_unlock(&memcg_create_mutex);
5354 memcg->swappiness = val;
5356 mutex_unlock(&memcg_create_mutex);
5361 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
5363 struct mem_cgroup_threshold_ary *t;
5369 t = rcu_dereference(memcg->thresholds.primary);
5371 t = rcu_dereference(memcg->memsw_thresholds.primary);
5376 usage = mem_cgroup_usage(memcg, swap);
5379 * current_threshold points to threshold just below or equal to usage.
5380 * If it's not true, a threshold was crossed after last
5381 * call of __mem_cgroup_threshold().
5383 i = t->current_threshold;
5386 * Iterate backward over array of thresholds starting from
5387 * current_threshold and check if a threshold is crossed.
5388 * If none of thresholds below usage is crossed, we read
5389 * only one element of the array here.
5391 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
5392 eventfd_signal(t->entries[i].eventfd, 1);
5394 /* i = current_threshold + 1 */
5398 * Iterate forward over array of thresholds starting from
5399 * current_threshold+1 and check if a threshold is crossed.
5400 * If none of thresholds above usage is crossed, we read
5401 * only one element of the array here.
5403 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
5404 eventfd_signal(t->entries[i].eventfd, 1);
5406 /* Update current_threshold */
5407 t->current_threshold = i - 1;
5412 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
5415 __mem_cgroup_threshold(memcg, false);
5416 if (do_swap_account)
5417 __mem_cgroup_threshold(memcg, true);
5419 memcg = parent_mem_cgroup(memcg);
5423 static int compare_thresholds(const void *a, const void *b)
5425 const struct mem_cgroup_threshold *_a = a;
5426 const struct mem_cgroup_threshold *_b = b;
5428 if (_a->threshold > _b->threshold)
5431 if (_a->threshold < _b->threshold)
5437 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
5439 struct mem_cgroup_eventfd_list *ev;
5441 list_for_each_entry(ev, &memcg->oom_notify, list)
5442 eventfd_signal(ev->eventfd, 1);
5446 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
5448 struct mem_cgroup *iter;
5450 for_each_mem_cgroup_tree(iter, memcg)
5451 mem_cgroup_oom_notify_cb(iter);
5454 static int mem_cgroup_usage_register_event(struct cgroup_subsys_state *css,
5455 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
5457 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5458 struct mem_cgroup_thresholds *thresholds;
5459 struct mem_cgroup_threshold_ary *new;
5460 enum res_type type = MEMFILE_TYPE(cft->private);
5461 u64 threshold, usage;
5464 ret = res_counter_memparse_write_strategy(args, &threshold);
5468 mutex_lock(&memcg->thresholds_lock);
5471 thresholds = &memcg->thresholds;
5472 else if (type == _MEMSWAP)
5473 thresholds = &memcg->memsw_thresholds;
5477 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
5479 /* Check if a threshold crossed before adding a new one */
5480 if (thresholds->primary)
5481 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
5483 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
5485 /* Allocate memory for new array of thresholds */
5486 new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
5494 /* Copy thresholds (if any) to new array */
5495 if (thresholds->primary) {
5496 memcpy(new->entries, thresholds->primary->entries, (size - 1) *
5497 sizeof(struct mem_cgroup_threshold));
5500 /* Add new threshold */
5501 new->entries[size - 1].eventfd = eventfd;
5502 new->entries[size - 1].threshold = threshold;
5504 /* Sort thresholds. Registering of new threshold isn't time-critical */
5505 sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
5506 compare_thresholds, NULL);
5508 /* Find current threshold */
5509 new->current_threshold = -1;
5510 for (i = 0; i < size; i++) {
5511 if (new->entries[i].threshold <= usage) {
5513 * new->current_threshold will not be used until
5514 * rcu_assign_pointer(), so it's safe to increment
5517 ++new->current_threshold;
5522 /* Free old spare buffer and save old primary buffer as spare */
5523 kfree(thresholds->spare);
5524 thresholds->spare = thresholds->primary;
5526 rcu_assign_pointer(thresholds->primary, new);
5528 /* To be sure that nobody uses thresholds */
5532 mutex_unlock(&memcg->thresholds_lock);
5537 static void mem_cgroup_usage_unregister_event(struct cgroup_subsys_state *css,
5538 struct cftype *cft, struct eventfd_ctx *eventfd)
5540 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5541 struct mem_cgroup_thresholds *thresholds;
5542 struct mem_cgroup_threshold_ary *new;
5543 enum res_type type = MEMFILE_TYPE(cft->private);
5547 mutex_lock(&memcg->thresholds_lock);
5549 thresholds = &memcg->thresholds;
5550 else if (type == _MEMSWAP)
5551 thresholds = &memcg->memsw_thresholds;
5555 if (!thresholds->primary)
5558 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
5560 /* Check if a threshold crossed before removing */
5561 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
5563 /* Calculate new number of threshold */
5565 for (i = 0; i < thresholds->primary->size; i++) {
5566 if (thresholds->primary->entries[i].eventfd != eventfd)
5570 new = thresholds->spare;
5572 /* Set thresholds array to NULL if we don't have thresholds */
5581 /* Copy thresholds and find current threshold */
5582 new->current_threshold = -1;
5583 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
5584 if (thresholds->primary->entries[i].eventfd == eventfd)
5587 new->entries[j] = thresholds->primary->entries[i];
5588 if (new->entries[j].threshold <= usage) {
5590 * new->current_threshold will not be used
5591 * until rcu_assign_pointer(), so it's safe to increment
5594 ++new->current_threshold;
5600 /* Swap primary and spare array */
5601 thresholds->spare = thresholds->primary;
5602 /* If all events are unregistered, free the spare array */
5604 kfree(thresholds->spare);
5605 thresholds->spare = NULL;
5608 rcu_assign_pointer(thresholds->primary, new);
5610 /* To be sure that nobody uses thresholds */
5613 mutex_unlock(&memcg->thresholds_lock);
5616 static int mem_cgroup_oom_register_event(struct cgroup_subsys_state *css,
5617 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
5619 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5620 struct mem_cgroup_eventfd_list *event;
5621 enum res_type type = MEMFILE_TYPE(cft->private);
5623 BUG_ON(type != _OOM_TYPE);
5624 event = kmalloc(sizeof(*event), GFP_KERNEL);
5628 spin_lock(&memcg_oom_lock);
5630 event->eventfd = eventfd;
5631 list_add(&event->list, &memcg->oom_notify);
5633 /* already in OOM ? */
5634 if (atomic_read(&memcg->under_oom))
5635 eventfd_signal(eventfd, 1);
5636 spin_unlock(&memcg_oom_lock);
5641 static void mem_cgroup_oom_unregister_event(struct cgroup_subsys_state *css,
5642 struct cftype *cft, struct eventfd_ctx *eventfd)
5644 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5645 struct mem_cgroup_eventfd_list *ev, *tmp;
5646 enum res_type type = MEMFILE_TYPE(cft->private);
5648 BUG_ON(type != _OOM_TYPE);
5650 spin_lock(&memcg_oom_lock);
5652 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
5653 if (ev->eventfd == eventfd) {
5654 list_del(&ev->list);
5659 spin_unlock(&memcg_oom_lock);
5662 static int mem_cgroup_oom_control_read(struct cgroup_subsys_state *css,
5663 struct cftype *cft, struct cgroup_map_cb *cb)
5665 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5667 cb->fill(cb, "oom_kill_disable", memcg->oom_kill_disable);
5669 if (atomic_read(&memcg->under_oom))
5670 cb->fill(cb, "under_oom", 1);
5672 cb->fill(cb, "under_oom", 0);
5676 static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
5677 struct cftype *cft, u64 val)
5679 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5680 struct mem_cgroup *parent = mem_cgroup_from_css(css_parent(&memcg->css));
5682 /* cannot set to root cgroup and only 0 and 1 are allowed */
5683 if (!parent || !((val == 0) || (val == 1)))
5686 mutex_lock(&memcg_create_mutex);
5687 /* oom-kill-disable is a flag for subhierarchy. */
5688 if ((parent->use_hierarchy) || memcg_has_children(memcg)) {
5689 mutex_unlock(&memcg_create_mutex);
5692 memcg->oom_kill_disable = val;
5694 memcg_oom_recover(memcg);
5695 mutex_unlock(&memcg_create_mutex);
5699 #ifdef CONFIG_MEMCG_KMEM
5700 static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
5704 memcg->kmemcg_id = -1;
5705 ret = memcg_propagate_kmem(memcg);
5709 return mem_cgroup_sockets_init(memcg, ss);
5712 static void memcg_destroy_kmem(struct mem_cgroup *memcg)
5714 mem_cgroup_sockets_destroy(memcg);
5717 static void kmem_cgroup_css_offline(struct mem_cgroup *memcg)
5719 if (!memcg_kmem_is_active(memcg))
5723 * kmem charges can outlive the cgroup. In the case of slab
5724 * pages, for instance, a page contain objects from various
5725 * processes. As we prevent from taking a reference for every
5726 * such allocation we have to be careful when doing uncharge
5727 * (see memcg_uncharge_kmem) and here during offlining.
5729 * The idea is that that only the _last_ uncharge which sees
5730 * the dead memcg will drop the last reference. An additional
5731 * reference is taken here before the group is marked dead
5732 * which is then paired with css_put during uncharge resp. here.
5734 * Although this might sound strange as this path is called from
5735 * css_offline() when the referencemight have dropped down to 0
5736 * and shouldn't be incremented anymore (css_tryget would fail)
5737 * we do not have other options because of the kmem allocations
5740 css_get(&memcg->css);
5742 memcg_kmem_mark_dead(memcg);
5744 if (res_counter_read_u64(&memcg->kmem, RES_USAGE) != 0)
5747 if (memcg_kmem_test_and_clear_dead(memcg))
5748 css_put(&memcg->css);
5751 static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
5756 static void memcg_destroy_kmem(struct mem_cgroup *memcg)
5760 static void kmem_cgroup_css_offline(struct mem_cgroup *memcg)
5765 static struct cftype mem_cgroup_files[] = {
5767 .name = "usage_in_bytes",
5768 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
5769 .read = mem_cgroup_read,
5770 .register_event = mem_cgroup_usage_register_event,
5771 .unregister_event = mem_cgroup_usage_unregister_event,
5774 .name = "max_usage_in_bytes",
5775 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
5776 .trigger = mem_cgroup_reset,
5777 .read = mem_cgroup_read,
5780 .name = "limit_in_bytes",
5781 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
5782 .write_string = mem_cgroup_write,
5783 .read = mem_cgroup_read,
5786 .name = "soft_limit_in_bytes",
5787 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
5788 .write_string = mem_cgroup_write,
5789 .read = mem_cgroup_read,
5793 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
5794 .trigger = mem_cgroup_reset,
5795 .read = mem_cgroup_read,
5799 .read_seq_string = memcg_stat_show,
5802 .name = "force_empty",
5803 .trigger = mem_cgroup_force_empty_write,
5806 .name = "use_hierarchy",
5807 .flags = CFTYPE_INSANE,
5808 .write_u64 = mem_cgroup_hierarchy_write,
5809 .read_u64 = mem_cgroup_hierarchy_read,
5812 .name = "swappiness",
5813 .read_u64 = mem_cgroup_swappiness_read,
5814 .write_u64 = mem_cgroup_swappiness_write,
5817 .name = "move_charge_at_immigrate",
5818 .read_u64 = mem_cgroup_move_charge_read,
5819 .write_u64 = mem_cgroup_move_charge_write,
5822 .name = "oom_control",
5823 .read_map = mem_cgroup_oom_control_read,
5824 .write_u64 = mem_cgroup_oom_control_write,
5825 .register_event = mem_cgroup_oom_register_event,
5826 .unregister_event = mem_cgroup_oom_unregister_event,
5827 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
5830 .name = "pressure_level",
5831 .register_event = vmpressure_register_event,
5832 .unregister_event = vmpressure_unregister_event,
5836 .name = "numa_stat",
5837 .read_seq_string = memcg_numa_stat_show,
5840 #ifdef CONFIG_MEMCG_KMEM
5842 .name = "kmem.limit_in_bytes",
5843 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
5844 .write_string = mem_cgroup_write,
5845 .read = mem_cgroup_read,
5848 .name = "kmem.usage_in_bytes",
5849 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
5850 .read = mem_cgroup_read,
5853 .name = "kmem.failcnt",
5854 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
5855 .trigger = mem_cgroup_reset,
5856 .read = mem_cgroup_read,
5859 .name = "kmem.max_usage_in_bytes",
5860 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
5861 .trigger = mem_cgroup_reset,
5862 .read = mem_cgroup_read,
5864 #ifdef CONFIG_SLABINFO
5866 .name = "kmem.slabinfo",
5867 .read_seq_string = mem_cgroup_slabinfo_read,
5871 { }, /* terminate */
5874 #ifdef CONFIG_MEMCG_SWAP
5875 static struct cftype memsw_cgroup_files[] = {
5877 .name = "memsw.usage_in_bytes",
5878 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
5879 .read = mem_cgroup_read,
5880 .register_event = mem_cgroup_usage_register_event,
5881 .unregister_event = mem_cgroup_usage_unregister_event,
5884 .name = "memsw.max_usage_in_bytes",
5885 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
5886 .trigger = mem_cgroup_reset,
5887 .read = mem_cgroup_read,
5890 .name = "memsw.limit_in_bytes",
5891 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
5892 .write_string = mem_cgroup_write,
5893 .read = mem_cgroup_read,
5896 .name = "memsw.failcnt",
5897 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
5898 .trigger = mem_cgroup_reset,
5899 .read = mem_cgroup_read,
5901 { }, /* terminate */
5904 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
5906 struct mem_cgroup_per_node *pn;
5907 struct mem_cgroup_per_zone *mz;
5908 int zone, tmp = node;
5910 * This routine is called against possible nodes.
5911 * But it's BUG to call kmalloc() against offline node.
5913 * TODO: this routine can waste much memory for nodes which will
5914 * never be onlined. It's better to use memory hotplug callback
5917 if (!node_state(node, N_NORMAL_MEMORY))
5919 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
5923 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
5924 mz = &pn->zoneinfo[zone];
5925 lruvec_init(&mz->lruvec);
5928 memcg->nodeinfo[node] = pn;
5932 static void free_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
5934 kfree(memcg->nodeinfo[node]);
5937 static struct mem_cgroup *mem_cgroup_alloc(void)
5939 struct mem_cgroup *memcg;
5940 size_t size = memcg_size();
5942 /* Can be very big if nr_node_ids is very big */
5943 if (size < PAGE_SIZE)
5944 memcg = kzalloc(size, GFP_KERNEL);
5946 memcg = vzalloc(size);
5951 memcg->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
5954 spin_lock_init(&memcg->pcp_counter_lock);
5958 if (size < PAGE_SIZE)
5966 * At destroying mem_cgroup, references from swap_cgroup can remain.
5967 * (scanning all at force_empty is too costly...)
5969 * Instead of clearing all references at force_empty, we remember
5970 * the number of reference from swap_cgroup and free mem_cgroup when
5971 * it goes down to 0.
5973 * Removal of cgroup itself succeeds regardless of refs from swap.
5976 static void __mem_cgroup_free(struct mem_cgroup *memcg)
5979 size_t size = memcg_size();
5981 free_css_id(&mem_cgroup_subsys, &memcg->css);
5984 free_mem_cgroup_per_zone_info(memcg, node);
5986 free_percpu(memcg->stat);
5989 * We need to make sure that (at least for now), the jump label
5990 * destruction code runs outside of the cgroup lock. This is because
5991 * get_online_cpus(), which is called from the static_branch update,
5992 * can't be called inside the cgroup_lock. cpusets are the ones
5993 * enforcing this dependency, so if they ever change, we might as well.
5995 * schedule_work() will guarantee this happens. Be careful if you need
5996 * to move this code around, and make sure it is outside
5999 disarm_static_keys(memcg);
6000 if (size < PAGE_SIZE)
6007 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
6009 struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg)
6011 if (!memcg->res.parent)
6013 return mem_cgroup_from_res_counter(memcg->res.parent, res);
6015 EXPORT_SYMBOL(parent_mem_cgroup);
6017 static struct cgroup_subsys_state * __ref
6018 mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
6020 struct mem_cgroup *memcg;
6021 long error = -ENOMEM;
6024 memcg = mem_cgroup_alloc();
6026 return ERR_PTR(error);
6029 if (alloc_mem_cgroup_per_zone_info(memcg, node))
6033 if (parent_css == NULL) {
6034 root_mem_cgroup = memcg;
6035 res_counter_init(&memcg->res, NULL);
6036 res_counter_init(&memcg->memsw, NULL);
6037 res_counter_init(&memcg->kmem, NULL);
6040 memcg->last_scanned_node = MAX_NUMNODES;
6041 INIT_LIST_HEAD(&memcg->oom_notify);
6042 memcg->move_charge_at_immigrate = 0;
6043 mutex_init(&memcg->thresholds_lock);
6044 spin_lock_init(&memcg->move_lock);
6045 vmpressure_init(&memcg->vmpressure);
6046 spin_lock_init(&memcg->soft_lock);
6051 __mem_cgroup_free(memcg);
6052 return ERR_PTR(error);
6056 mem_cgroup_css_online(struct cgroup_subsys_state *css)
6058 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6059 struct mem_cgroup *parent = mem_cgroup_from_css(css_parent(css));
6065 mutex_lock(&memcg_create_mutex);
6067 memcg->use_hierarchy = parent->use_hierarchy;
6068 memcg->oom_kill_disable = parent->oom_kill_disable;
6069 memcg->swappiness = mem_cgroup_swappiness(parent);
6071 if (parent->use_hierarchy) {
6072 res_counter_init(&memcg->res, &parent->res);
6073 res_counter_init(&memcg->memsw, &parent->memsw);
6074 res_counter_init(&memcg->kmem, &parent->kmem);
6077 * No need to take a reference to the parent because cgroup
6078 * core guarantees its existence.
6081 res_counter_init(&memcg->res, NULL);
6082 res_counter_init(&memcg->memsw, NULL);
6083 res_counter_init(&memcg->kmem, NULL);
6085 * Deeper hierachy with use_hierarchy == false doesn't make
6086 * much sense so let cgroup subsystem know about this
6087 * unfortunate state in our controller.
6089 if (parent != root_mem_cgroup)
6090 mem_cgroup_subsys.broken_hierarchy = true;
6093 error = memcg_init_kmem(memcg, &mem_cgroup_subsys);
6094 mutex_unlock(&memcg_create_mutex);
6099 * Announce all parents that a group from their hierarchy is gone.
6101 static void mem_cgroup_invalidate_reclaim_iterators(struct mem_cgroup *memcg)
6103 struct mem_cgroup *parent = memcg;
6105 while ((parent = parent_mem_cgroup(parent)))
6106 mem_cgroup_iter_invalidate(parent);
6109 * if the root memcg is not hierarchical we have to check it
6112 if (!root_mem_cgroup->use_hierarchy)
6113 mem_cgroup_iter_invalidate(root_mem_cgroup);
6116 static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
6118 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6120 kmem_cgroup_css_offline(memcg);
6122 mem_cgroup_invalidate_reclaim_iterators(memcg);
6123 mem_cgroup_reparent_charges(memcg);
6124 if (memcg->soft_contributed) {
6125 while ((memcg = parent_mem_cgroup(memcg)))
6126 atomic_dec(&memcg->children_in_excess);
6128 if (memcg != root_mem_cgroup && !root_mem_cgroup->use_hierarchy)
6129 atomic_dec(&root_mem_cgroup->children_in_excess);
6131 mem_cgroup_destroy_all_caches(memcg);
6132 vmpressure_cleanup(&memcg->vmpressure);
6135 static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
6137 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6139 memcg_destroy_kmem(memcg);
6140 __mem_cgroup_free(memcg);
6144 /* Handlers for move charge at task migration. */
6145 #define PRECHARGE_COUNT_AT_ONCE 256
6146 static int mem_cgroup_do_precharge(unsigned long count)
6149 int batch_count = PRECHARGE_COUNT_AT_ONCE;
6150 struct mem_cgroup *memcg = mc.to;
6152 if (mem_cgroup_is_root(memcg)) {
6153 mc.precharge += count;
6154 /* we don't need css_get for root */
6157 /* try to charge at once */
6159 struct res_counter *dummy;
6161 * "memcg" cannot be under rmdir() because we've already checked
6162 * by cgroup_lock_live_cgroup() that it is not removed and we
6163 * are still under the same cgroup_mutex. So we can postpone
6166 if (res_counter_charge(&memcg->res, PAGE_SIZE * count, &dummy))
6168 if (do_swap_account && res_counter_charge(&memcg->memsw,
6169 PAGE_SIZE * count, &dummy)) {
6170 res_counter_uncharge(&memcg->res, PAGE_SIZE * count);
6173 mc.precharge += count;
6177 /* fall back to one by one charge */
6179 if (signal_pending(current)) {
6183 if (!batch_count--) {
6184 batch_count = PRECHARGE_COUNT_AT_ONCE;
6187 ret = __mem_cgroup_try_charge(NULL,
6188 GFP_KERNEL, 1, &memcg, false);
6190 /* mem_cgroup_clear_mc() will do uncharge later */
6198 * get_mctgt_type - get target type of moving charge
6199 * @vma: the vma the pte to be checked belongs
6200 * @addr: the address corresponding to the pte to be checked
6201 * @ptent: the pte to be checked
6202 * @target: the pointer the target page or swap ent will be stored(can be NULL)
6205 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
6206 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
6207 * move charge. if @target is not NULL, the page is stored in target->page
6208 * with extra refcnt got(Callers should handle it).
6209 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
6210 * target for charge migration. if @target is not NULL, the entry is stored
6213 * Called with pte lock held.
6220 enum mc_target_type {
6226 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
6227 unsigned long addr, pte_t ptent)
6229 struct page *page = vm_normal_page(vma, addr, ptent);
6231 if (!page || !page_mapped(page))
6233 if (PageAnon(page)) {
6234 /* we don't move shared anon */
6237 } else if (!move_file())
6238 /* we ignore mapcount for file pages */
6240 if (!get_page_unless_zero(page))
6247 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
6248 unsigned long addr, pte_t ptent, swp_entry_t *entry)
6250 struct page *page = NULL;
6251 swp_entry_t ent = pte_to_swp_entry(ptent);
6253 if (!move_anon() || non_swap_entry(ent))
6256 * Because lookup_swap_cache() updates some statistics counter,
6257 * we call find_get_page() with swapper_space directly.
6259 page = find_get_page(swap_address_space(ent), ent.val);
6260 if (do_swap_account)
6261 entry->val = ent.val;
6266 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
6267 unsigned long addr, pte_t ptent, swp_entry_t *entry)
6273 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
6274 unsigned long addr, pte_t ptent, swp_entry_t *entry)
6276 struct page *page = NULL;
6277 struct address_space *mapping;
6280 if (!vma->vm_file) /* anonymous vma */
6285 mapping = vma->vm_file->f_mapping;
6286 if (pte_none(ptent))
6287 pgoff = linear_page_index(vma, addr);
6288 else /* pte_file(ptent) is true */
6289 pgoff = pte_to_pgoff(ptent);
6291 /* page is moved even if it's not RSS of this task(page-faulted). */
6292 page = find_get_page(mapping, pgoff);
6295 /* shmem/tmpfs may report page out on swap: account for that too. */
6296 if (radix_tree_exceptional_entry(page)) {
6297 swp_entry_t swap = radix_to_swp_entry(page);
6298 if (do_swap_account)
6300 page = find_get_page(swap_address_space(swap), swap.val);
6306 static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
6307 unsigned long addr, pte_t ptent, union mc_target *target)
6309 struct page *page = NULL;
6310 struct page_cgroup *pc;
6311 enum mc_target_type ret = MC_TARGET_NONE;
6312 swp_entry_t ent = { .val = 0 };
6314 if (pte_present(ptent))
6315 page = mc_handle_present_pte(vma, addr, ptent);
6316 else if (is_swap_pte(ptent))
6317 page = mc_handle_swap_pte(vma, addr, ptent, &ent);
6318 else if (pte_none(ptent) || pte_file(ptent))
6319 page = mc_handle_file_pte(vma, addr, ptent, &ent);
6321 if (!page && !ent.val)
6324 pc = lookup_page_cgroup(page);
6326 * Do only loose check w/o page_cgroup lock.
6327 * mem_cgroup_move_account() checks the pc is valid or not under
6330 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
6331 ret = MC_TARGET_PAGE;
6333 target->page = page;
6335 if (!ret || !target)
6338 /* There is a swap entry and a page doesn't exist or isn't charged */
6339 if (ent.val && !ret &&
6340 mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
6341 ret = MC_TARGET_SWAP;
6348 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
6350 * We don't consider swapping or file mapped pages because THP does not
6351 * support them for now.
6352 * Caller should make sure that pmd_trans_huge(pmd) is true.
6354 static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
6355 unsigned long addr, pmd_t pmd, union mc_target *target)
6357 struct page *page = NULL;
6358 struct page_cgroup *pc;
6359 enum mc_target_type ret = MC_TARGET_NONE;
6361 page = pmd_page(pmd);
6362 VM_BUG_ON(!page || !PageHead(page));
6365 pc = lookup_page_cgroup(page);
6366 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
6367 ret = MC_TARGET_PAGE;
6370 target->page = page;
6376 static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
6377 unsigned long addr, pmd_t pmd, union mc_target *target)
6379 return MC_TARGET_NONE;
6383 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
6384 unsigned long addr, unsigned long end,
6385 struct mm_walk *walk)
6387 struct vm_area_struct *vma = walk->private;
6391 if (pmd_trans_huge_lock(pmd, vma) == 1) {
6392 if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
6393 mc.precharge += HPAGE_PMD_NR;
6394 spin_unlock(&vma->vm_mm->page_table_lock);
6398 if (pmd_trans_unstable(pmd))
6400 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6401 for (; addr != end; pte++, addr += PAGE_SIZE)
6402 if (get_mctgt_type(vma, addr, *pte, NULL))
6403 mc.precharge++; /* increment precharge temporarily */
6404 pte_unmap_unlock(pte - 1, ptl);
6410 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
6412 unsigned long precharge;
6413 struct vm_area_struct *vma;
6415 down_read(&mm->mmap_sem);
6416 for (vma = mm->mmap; vma; vma = vma->vm_next) {
6417 struct mm_walk mem_cgroup_count_precharge_walk = {
6418 .pmd_entry = mem_cgroup_count_precharge_pte_range,
6422 if (is_vm_hugetlb_page(vma))
6424 walk_page_range(vma->vm_start, vma->vm_end,
6425 &mem_cgroup_count_precharge_walk);
6427 up_read(&mm->mmap_sem);
6429 precharge = mc.precharge;
6435 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
6437 unsigned long precharge = mem_cgroup_count_precharge(mm);
6439 VM_BUG_ON(mc.moving_task);
6440 mc.moving_task = current;
6441 return mem_cgroup_do_precharge(precharge);
6444 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
6445 static void __mem_cgroup_clear_mc(void)
6447 struct mem_cgroup *from = mc.from;
6448 struct mem_cgroup *to = mc.to;
6451 /* we must uncharge all the leftover precharges from mc.to */
6453 __mem_cgroup_cancel_charge(mc.to, mc.precharge);
6457 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
6458 * we must uncharge here.
6460 if (mc.moved_charge) {
6461 __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
6462 mc.moved_charge = 0;
6464 /* we must fixup refcnts and charges */
6465 if (mc.moved_swap) {
6466 /* uncharge swap account from the old cgroup */
6467 if (!mem_cgroup_is_root(mc.from))
6468 res_counter_uncharge(&mc.from->memsw,
6469 PAGE_SIZE * mc.moved_swap);
6471 for (i = 0; i < mc.moved_swap; i++)
6472 css_put(&mc.from->css);
6474 if (!mem_cgroup_is_root(mc.to)) {
6476 * we charged both to->res and to->memsw, so we should
6479 res_counter_uncharge(&mc.to->res,
6480 PAGE_SIZE * mc.moved_swap);
6482 /* we've already done css_get(mc.to) */
6485 memcg_oom_recover(from);
6486 memcg_oom_recover(to);
6487 wake_up_all(&mc.waitq);
6490 static void mem_cgroup_clear_mc(void)
6492 struct mem_cgroup *from = mc.from;
6495 * we must clear moving_task before waking up waiters at the end of
6498 mc.moving_task = NULL;
6499 __mem_cgroup_clear_mc();
6500 spin_lock(&mc.lock);
6503 spin_unlock(&mc.lock);
6504 mem_cgroup_end_move(from);
6507 static int mem_cgroup_can_attach(struct cgroup_subsys_state *css,
6508 struct cgroup_taskset *tset)
6510 struct task_struct *p = cgroup_taskset_first(tset);
6512 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6513 unsigned long move_charge_at_immigrate;
6516 * We are now commited to this value whatever it is. Changes in this
6517 * tunable will only affect upcoming migrations, not the current one.
6518 * So we need to save it, and keep it going.
6520 move_charge_at_immigrate = memcg->move_charge_at_immigrate;
6521 if (move_charge_at_immigrate) {
6522 struct mm_struct *mm;
6523 struct mem_cgroup *from = mem_cgroup_from_task(p);
6525 VM_BUG_ON(from == memcg);
6527 mm = get_task_mm(p);
6530 /* We move charges only when we move a owner of the mm */
6531 if (mm->owner == p) {
6534 VM_BUG_ON(mc.precharge);
6535 VM_BUG_ON(mc.moved_charge);
6536 VM_BUG_ON(mc.moved_swap);
6537 mem_cgroup_start_move(from);
6538 spin_lock(&mc.lock);
6541 mc.immigrate_flags = move_charge_at_immigrate;
6542 spin_unlock(&mc.lock);
6543 /* We set mc.moving_task later */
6545 ret = mem_cgroup_precharge_mc(mm);
6547 mem_cgroup_clear_mc();
6554 static void mem_cgroup_cancel_attach(struct cgroup_subsys_state *css,
6555 struct cgroup_taskset *tset)
6557 mem_cgroup_clear_mc();
6560 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
6561 unsigned long addr, unsigned long end,
6562 struct mm_walk *walk)
6565 struct vm_area_struct *vma = walk->private;
6568 enum mc_target_type target_type;
6569 union mc_target target;
6571 struct page_cgroup *pc;
6574 * We don't take compound_lock() here but no race with splitting thp
6576 * - if pmd_trans_huge_lock() returns 1, the relevant thp is not
6577 * under splitting, which means there's no concurrent thp split,
6578 * - if another thread runs into split_huge_page() just after we
6579 * entered this if-block, the thread must wait for page table lock
6580 * to be unlocked in __split_huge_page_splitting(), where the main
6581 * part of thp split is not executed yet.
6583 if (pmd_trans_huge_lock(pmd, vma) == 1) {
6584 if (mc.precharge < HPAGE_PMD_NR) {
6585 spin_unlock(&vma->vm_mm->page_table_lock);
6588 target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
6589 if (target_type == MC_TARGET_PAGE) {
6591 if (!isolate_lru_page(page)) {
6592 pc = lookup_page_cgroup(page);
6593 if (!mem_cgroup_move_account(page, HPAGE_PMD_NR,
6594 pc, mc.from, mc.to)) {
6595 mc.precharge -= HPAGE_PMD_NR;
6596 mc.moved_charge += HPAGE_PMD_NR;
6598 putback_lru_page(page);
6602 spin_unlock(&vma->vm_mm->page_table_lock);
6606 if (pmd_trans_unstable(pmd))
6609 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6610 for (; addr != end; addr += PAGE_SIZE) {
6611 pte_t ptent = *(pte++);
6617 switch (get_mctgt_type(vma, addr, ptent, &target)) {
6618 case MC_TARGET_PAGE:
6620 if (isolate_lru_page(page))
6622 pc = lookup_page_cgroup(page);
6623 if (!mem_cgroup_move_account(page, 1, pc,
6626 /* we uncharge from mc.from later. */
6629 putback_lru_page(page);
6630 put: /* get_mctgt_type() gets the page */
6633 case MC_TARGET_SWAP:
6635 if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
6637 /* we fixup refcnts and charges later. */
6645 pte_unmap_unlock(pte - 1, ptl);
6650 * We have consumed all precharges we got in can_attach().
6651 * We try charge one by one, but don't do any additional
6652 * charges to mc.to if we have failed in charge once in attach()
6655 ret = mem_cgroup_do_precharge(1);
6663 static void mem_cgroup_move_charge(struct mm_struct *mm)
6665 struct vm_area_struct *vma;
6667 lru_add_drain_all();
6669 if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
6671 * Someone who are holding the mmap_sem might be waiting in
6672 * waitq. So we cancel all extra charges, wake up all waiters,
6673 * and retry. Because we cancel precharges, we might not be able
6674 * to move enough charges, but moving charge is a best-effort
6675 * feature anyway, so it wouldn't be a big problem.
6677 __mem_cgroup_clear_mc();
6681 for (vma = mm->mmap; vma; vma = vma->vm_next) {
6683 struct mm_walk mem_cgroup_move_charge_walk = {
6684 .pmd_entry = mem_cgroup_move_charge_pte_range,
6688 if (is_vm_hugetlb_page(vma))
6690 ret = walk_page_range(vma->vm_start, vma->vm_end,
6691 &mem_cgroup_move_charge_walk);
6694 * means we have consumed all precharges and failed in
6695 * doing additional charge. Just abandon here.
6699 up_read(&mm->mmap_sem);
6702 static void mem_cgroup_move_task(struct cgroup_subsys_state *css,
6703 struct cgroup_taskset *tset)
6705 struct task_struct *p = cgroup_taskset_first(tset);
6706 struct mm_struct *mm = get_task_mm(p);
6710 mem_cgroup_move_charge(mm);
6714 mem_cgroup_clear_mc();
6716 #else /* !CONFIG_MMU */
6717 static int mem_cgroup_can_attach(struct cgroup_subsys_state *css,
6718 struct cgroup_taskset *tset)
6722 static void mem_cgroup_cancel_attach(struct cgroup_subsys_state *css,
6723 struct cgroup_taskset *tset)
6726 static void mem_cgroup_move_task(struct cgroup_subsys_state *css,
6727 struct cgroup_taskset *tset)
6733 * Cgroup retains root cgroups across [un]mount cycles making it necessary
6734 * to verify sane_behavior flag on each mount attempt.
6736 static void mem_cgroup_bind(struct cgroup_subsys_state *root_css)
6739 * use_hierarchy is forced with sane_behavior. cgroup core
6740 * guarantees that @root doesn't have any children, so turning it
6741 * on for the root memcg is enough.
6743 if (cgroup_sane_behavior(root_css->cgroup))
6744 mem_cgroup_from_css(root_css)->use_hierarchy = true;
6747 struct cgroup_subsys mem_cgroup_subsys = {
6749 .subsys_id = mem_cgroup_subsys_id,
6750 .css_alloc = mem_cgroup_css_alloc,
6751 .css_online = mem_cgroup_css_online,
6752 .css_offline = mem_cgroup_css_offline,
6753 .css_free = mem_cgroup_css_free,
6754 .can_attach = mem_cgroup_can_attach,
6755 .cancel_attach = mem_cgroup_cancel_attach,
6756 .attach = mem_cgroup_move_task,
6757 .bind = mem_cgroup_bind,
6758 .base_cftypes = mem_cgroup_files,
6763 #ifdef CONFIG_MEMCG_SWAP
6764 static int __init enable_swap_account(char *s)
6766 if (!strcmp(s, "1"))
6767 really_do_swap_account = 1;
6768 else if (!strcmp(s, "0"))
6769 really_do_swap_account = 0;
6772 __setup("swapaccount=", enable_swap_account);
6774 static void __init memsw_file_init(void)
6776 WARN_ON(cgroup_add_cftypes(&mem_cgroup_subsys, memsw_cgroup_files));
6779 static void __init enable_swap_cgroup(void)
6781 if (!mem_cgroup_disabled() && really_do_swap_account) {
6782 do_swap_account = 1;
6788 static void __init enable_swap_cgroup(void)
6794 * subsys_initcall() for memory controller.
6796 * Some parts like hotcpu_notifier() have to be initialized from this context
6797 * because of lock dependencies (cgroup_lock -> cpu hotplug) but basically
6798 * everything that doesn't depend on a specific mem_cgroup structure should
6799 * be initialized from here.
6801 static int __init mem_cgroup_init(void)
6803 hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
6804 enable_swap_cgroup();
6808 subsys_initcall(mem_cgroup_init);