parisc: Fix pagefault crash in unaligned __get_user() call
[GitHub/exynos8895/android_kernel_samsung_universal8895.git] / mm / memcontrol.c
CommitLineData
8cdea7c0
BS
1/* memcontrol.c - Memory Controller
2 *
3 * Copyright IBM Corporation, 2007
4 * Author Balbir Singh <balbir@linux.vnet.ibm.com>
5 *
78fb7466
PE
6 * Copyright 2007 OpenVZ SWsoft Inc
7 * Author: Pavel Emelianov <xemul@openvz.org>
8 *
2e72b634
KS
9 * Memory thresholds
10 * Copyright (C) 2009 Nokia Corporation
11 * Author: Kirill A. Shutemov
12 *
7ae1e1d0
GC
13 * Kernel Memory Controller
14 * Copyright (C) 2012 Parallels Inc. and Google Inc.
15 * Authors: Glauber Costa and Suleiman Souhlal
16 *
1575e68b
JW
17 * Native page reclaim
18 * Charge lifetime sanitation
19 * Lockless page tracking & accounting
20 * Unified hierarchy configuration model
21 * Copyright (C) 2015 Red Hat, Inc., Johannes Weiner
22 *
8cdea7c0
BS
23 * This program is free software; you can redistribute it and/or modify
24 * it under the terms of the GNU General Public License as published by
25 * the Free Software Foundation; either version 2 of the License, or
26 * (at your option) any later version.
27 *
28 * This program is distributed in the hope that it will be useful,
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
31 * GNU General Public License for more details.
32 */
33
3e32cb2e 34#include <linux/page_counter.h>
8cdea7c0
BS
35#include <linux/memcontrol.h>
36#include <linux/cgroup.h>
78fb7466 37#include <linux/mm.h>
4ffef5fe 38#include <linux/hugetlb.h>
d13d1443 39#include <linux/pagemap.h>
d52aa412 40#include <linux/smp.h>
8a9f3ccd 41#include <linux/page-flags.h>
66e1707b 42#include <linux/backing-dev.h>
8a9f3ccd
BS
43#include <linux/bit_spinlock.h>
44#include <linux/rcupdate.h>
e222432b 45#include <linux/limits.h>
b9e15baf 46#include <linux/export.h>
8c7c6e34 47#include <linux/mutex.h>
bb4cc1a8 48#include <linux/rbtree.h>
b6ac57d5 49#include <linux/slab.h>
66e1707b 50#include <linux/swap.h>
02491447 51#include <linux/swapops.h>
66e1707b 52#include <linux/spinlock.h>
2e72b634 53#include <linux/eventfd.h>
79bd9814 54#include <linux/poll.h>
2e72b634 55#include <linux/sort.h>
66e1707b 56#include <linux/fs.h>
d2ceb9b7 57#include <linux/seq_file.h>
70ddf637 58#include <linux/vmpressure.h>
b69408e8 59#include <linux/mm_inline.h>
5d1ea48b 60#include <linux/swap_cgroup.h>
cdec2e42 61#include <linux/cpu.h>
158e0a2d 62#include <linux/oom.h>
0056f4e6 63#include <linux/lockdep.h>
79bd9814 64#include <linux/file.h>
b23afb93 65#include <linux/tracehook.h>
08e552c6 66#include "internal.h"
d1a4c0b3 67#include <net/sock.h>
4bd2c1ee 68#include <net/ip.h>
d1a4c0b3 69#include <net/tcp_memcontrol.h>
f35c3a8e 70#include "slab.h"
8cdea7c0 71
8697d331
BS
72#include <asm/uaccess.h>
73
cc8e970c
KM
74#include <trace/events/vmscan.h>
75
073219e9
TH
76struct cgroup_subsys memory_cgrp_subsys __read_mostly;
77EXPORT_SYMBOL(memory_cgrp_subsys);
68ae564b 78
a181b0e8 79#define MEM_CGROUP_RECLAIM_RETRIES 5
6bbda35c 80static struct mem_cgroup *root_mem_cgroup __read_mostly;
56161634 81struct cgroup_subsys_state *mem_cgroup_root_css __read_mostly;
8cdea7c0 82
21afa38e 83/* Whether the swap controller is active */
c255a458 84#ifdef CONFIG_MEMCG_SWAP
c077719b 85int do_swap_account __read_mostly;
c077719b 86#else
a0db00fc 87#define do_swap_account 0
c077719b
KH
88#endif
89
af7c4b0e
JW
90static const char * const mem_cgroup_stat_names[] = {
91 "cache",
92 "rss",
b070e65c 93 "rss_huge",
af7c4b0e 94 "mapped_file",
c4843a75 95 "dirty",
3ea67d06 96 "writeback",
af7c4b0e
JW
97 "swap",
98};
99
af7c4b0e
JW
100static const char * const mem_cgroup_events_names[] = {
101 "pgpgin",
102 "pgpgout",
103 "pgfault",
104 "pgmajfault",
105};
106
58cf188e
SZ
107static const char * const mem_cgroup_lru_names[] = {
108 "inactive_anon",
109 "active_anon",
110 "inactive_file",
111 "active_file",
112 "unevictable",
113};
114
a0db00fc
KS
115#define THRESHOLDS_EVENTS_TARGET 128
116#define SOFTLIMIT_EVENTS_TARGET 1024
117#define NUMAINFO_EVENTS_TARGET 1024
e9f8974f 118
bb4cc1a8
AM
119/*
120 * Cgroups above their limits are maintained in a RB-Tree, independent of
121 * their hierarchy representation
122 */
123
124struct mem_cgroup_tree_per_zone {
125 struct rb_root rb_root;
126 spinlock_t lock;
127};
128
129struct mem_cgroup_tree_per_node {
130 struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
131};
132
133struct mem_cgroup_tree {
134 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
135};
136
137static struct mem_cgroup_tree soft_limit_tree __read_mostly;
138
9490ff27
KH
139/* for OOM */
140struct mem_cgroup_eventfd_list {
141 struct list_head list;
142 struct eventfd_ctx *eventfd;
143};
2e72b634 144
79bd9814
TH
145/*
146 * cgroup_event represents events which userspace want to receive.
147 */
3bc942f3 148struct mem_cgroup_event {
79bd9814 149 /*
59b6f873 150 * memcg which the event belongs to.
79bd9814 151 */
59b6f873 152 struct mem_cgroup *memcg;
79bd9814
TH
153 /*
154 * eventfd to signal userspace about the event.
155 */
156 struct eventfd_ctx *eventfd;
157 /*
158 * Each of these stored in a list by the cgroup.
159 */
160 struct list_head list;
fba94807
TH
161 /*
162 * register_event() callback will be used to add new userspace
163 * waiter for changes related to this event. Use eventfd_signal()
164 * on eventfd to send notification to userspace.
165 */
59b6f873 166 int (*register_event)(struct mem_cgroup *memcg,
347c4a87 167 struct eventfd_ctx *eventfd, const char *args);
fba94807
TH
168 /*
169 * unregister_event() callback will be called when userspace closes
170 * the eventfd or on cgroup removing. This callback must be set,
171 * if you want provide notification functionality.
172 */
59b6f873 173 void (*unregister_event)(struct mem_cgroup *memcg,
fba94807 174 struct eventfd_ctx *eventfd);
79bd9814
TH
175 /*
176 * All fields below needed to unregister event when
177 * userspace closes eventfd.
178 */
179 poll_table pt;
180 wait_queue_head_t *wqh;
181 wait_queue_t wait;
182 struct work_struct remove;
183};
184
c0ff4b85
R
185static void mem_cgroup_threshold(struct mem_cgroup *memcg);
186static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
2e72b634 187
7dc74be0
DN
188/* Stuffs for move charges at task migration. */
189/*
1dfab5ab 190 * Types of charges to be moved.
7dc74be0 191 */
1dfab5ab
JW
192#define MOVE_ANON 0x1U
193#define MOVE_FILE 0x2U
194#define MOVE_MASK (MOVE_ANON | MOVE_FILE)
7dc74be0 195
4ffef5fe
DN
196/* "mc" and its members are protected by cgroup_mutex */
197static struct move_charge_struct {
b1dd693e 198 spinlock_t lock; /* for from, to */
52526076 199 struct mm_struct *mm;
4ffef5fe
DN
200 struct mem_cgroup *from;
201 struct mem_cgroup *to;
1dfab5ab 202 unsigned long flags;
4ffef5fe 203 unsigned long precharge;
854ffa8d 204 unsigned long moved_charge;
483c30b5 205 unsigned long moved_swap;
8033b97c
DN
206 struct task_struct *moving_task; /* a task moving charges */
207 wait_queue_head_t waitq; /* a waitq for other context */
208} mc = {
2bd9bb20 209 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
8033b97c
DN
210 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
211};
4ffef5fe 212
4e416953
BS
213/*
214 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
215 * limit reclaim to prevent infinite loops, if they ever occur.
216 */
a0db00fc 217#define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
bb4cc1a8 218#define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
4e416953 219
217bc319
KH
220enum charge_type {
221 MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
41326c17 222 MEM_CGROUP_CHARGE_TYPE_ANON,
d13d1443 223 MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
8a9478ca 224 MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
c05555b5
KH
225 NR_CHARGE_TYPE,
226};
227
8c7c6e34 228/* for encoding cft->private value on file */
86ae53e1
GC
229enum res_type {
230 _MEM,
231 _MEMSWAP,
232 _OOM_TYPE,
510fc4e1 233 _KMEM,
86ae53e1
GC
234};
235
a0db00fc
KS
236#define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
237#define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
8c7c6e34 238#define MEMFILE_ATTR(val) ((val) & 0xffff)
9490ff27
KH
239/* Used for OOM nofiier */
240#define OOM_CONTROL (0)
8c7c6e34 241
0999821b
GC
242/*
243 * The memcg_create_mutex will be held whenever a new cgroup is created.
244 * As a consequence, any change that needs to protect against new child cgroups
245 * appearing has to hold it as well.
246 */
247static DEFINE_MUTEX(memcg_create_mutex);
248
70ddf637
AV
249/* Some nice accessors for the vmpressure. */
250struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
251{
252 if (!memcg)
253 memcg = root_mem_cgroup;
254 return &memcg->vmpressure;
255}
256
257struct cgroup_subsys_state *vmpressure_to_css(struct vmpressure *vmpr)
258{
259 return &container_of(vmpr, struct mem_cgroup, vmpressure)->css;
260}
261
7ffc0edc
MH
262static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg)
263{
264 return (memcg == root_mem_cgroup);
265}
266
4219b2da
LZ
267/*
268 * We restrict the id in the range of [1, 65535], so it can fit into
269 * an unsigned short.
270 */
271#define MEM_CGROUP_ID_MAX USHRT_MAX
272
34c00c31
LZ
273static inline unsigned short mem_cgroup_id(struct mem_cgroup *memcg)
274{
15a4c835 275 return memcg->css.id;
34c00c31
LZ
276}
277
adbe427b
VD
278/*
279 * A helper function to get mem_cgroup from ID. must be called under
280 * rcu_read_lock(). The caller is responsible for calling
281 * css_tryget_online() if the mem_cgroup is used for charging. (dropping
282 * refcnt from swap can be called against removed memcg.)
283 */
34c00c31
LZ
284static inline struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
285{
286 struct cgroup_subsys_state *css;
287
7d699ddb 288 css = css_from_id(id, &memory_cgrp_subsys);
34c00c31
LZ
289 return mem_cgroup_from_css(css);
290}
291
e1aab161 292/* Writing them here to avoid exposing memcg's inner layout */
4bd2c1ee 293#if defined(CONFIG_INET) && defined(CONFIG_MEMCG_KMEM)
e1aab161 294
e1aab161
GC
295void sock_update_memcg(struct sock *sk)
296{
376be5ff 297 if (mem_cgroup_sockets_enabled) {
e1aab161 298 struct mem_cgroup *memcg;
3f134619 299 struct cg_proto *cg_proto;
e1aab161
GC
300
301 BUG_ON(!sk->sk_prot->proto_cgroup);
302
f3f511e1
GC
303 /* Socket cloning can throw us here with sk_cgrp already
304 * filled. It won't however, necessarily happen from
305 * process context. So the test for root memcg given
306 * the current task's memcg won't help us in this case.
307 *
308 * Respecting the original socket's memcg is a better
309 * decision in this case.
310 */
311 if (sk->sk_cgrp) {
312 BUG_ON(mem_cgroup_is_root(sk->sk_cgrp->memcg));
5347e5ae 313 css_get(&sk->sk_cgrp->memcg->css);
f3f511e1
GC
314 return;
315 }
316
e1aab161
GC
317 rcu_read_lock();
318 memcg = mem_cgroup_from_task(current);
3f134619 319 cg_proto = sk->sk_prot->proto_cgroup(memcg);
e752eb68 320 if (cg_proto && test_bit(MEMCG_SOCK_ACTIVE, &cg_proto->flags) &&
ec903c0c 321 css_tryget_online(&memcg->css)) {
3f134619 322 sk->sk_cgrp = cg_proto;
e1aab161
GC
323 }
324 rcu_read_unlock();
325 }
326}
327EXPORT_SYMBOL(sock_update_memcg);
328
329void sock_release_memcg(struct sock *sk)
330{
376be5ff 331 if (mem_cgroup_sockets_enabled && sk->sk_cgrp) {
e1aab161
GC
332 struct mem_cgroup *memcg;
333 WARN_ON(!sk->sk_cgrp->memcg);
334 memcg = sk->sk_cgrp->memcg;
5347e5ae 335 css_put(&sk->sk_cgrp->memcg->css);
e1aab161
GC
336 }
337}
d1a4c0b3
GC
338
339struct cg_proto *tcp_proto_cgroup(struct mem_cgroup *memcg)
340{
341 if (!memcg || mem_cgroup_is_root(memcg))
342 return NULL;
343
2e685cad 344 return &memcg->tcp_mem;
d1a4c0b3
GC
345}
346EXPORT_SYMBOL(tcp_proto_cgroup);
e1aab161 347
3f134619
GC
348#endif
349
a8964b9b 350#ifdef CONFIG_MEMCG_KMEM
55007d84 351/*
f7ce3190 352 * This will be the memcg's index in each cache's ->memcg_params.memcg_caches.
b8627835
LZ
353 * The main reason for not using cgroup id for this:
354 * this works better in sparse environments, where we have a lot of memcgs,
355 * but only a few kmem-limited. Or also, if we have, for instance, 200
356 * memcgs, and none but the 200th is kmem-limited, we'd have to have a
357 * 200 entry array for that.
55007d84 358 *
dbcf73e2
VD
359 * The current size of the caches array is stored in memcg_nr_cache_ids. It
360 * will double each time we have to increase it.
55007d84 361 */
dbcf73e2
VD
362static DEFINE_IDA(memcg_cache_ida);
363int memcg_nr_cache_ids;
749c5415 364
05257a1a
VD
365/* Protects memcg_nr_cache_ids */
366static DECLARE_RWSEM(memcg_cache_ids_sem);
367
368void memcg_get_cache_ids(void)
369{
370 down_read(&memcg_cache_ids_sem);
371}
372
373void memcg_put_cache_ids(void)
374{
375 up_read(&memcg_cache_ids_sem);
376}
377
55007d84
GC
378/*
379 * MIN_SIZE is different than 1, because we would like to avoid going through
380 * the alloc/free process all the time. In a small machine, 4 kmem-limited
381 * cgroups is a reasonable guess. In the future, it could be a parameter or
382 * tunable, but that is strictly not necessary.
383 *
b8627835 384 * MAX_SIZE should be as large as the number of cgrp_ids. Ideally, we could get
55007d84
GC
385 * this constant directly from cgroup, but it is understandable that this is
386 * better kept as an internal representation in cgroup.c. In any case, the
b8627835 387 * cgrp_id space is not getting any smaller, and we don't have to necessarily
55007d84
GC
388 * increase ours as well if it increases.
389 */
390#define MEMCG_CACHES_MIN_SIZE 4
b8627835 391#define MEMCG_CACHES_MAX_SIZE MEM_CGROUP_ID_MAX
55007d84 392
d7f25f8a
GC
393/*
394 * A lot of the calls to the cache allocation functions are expected to be
395 * inlined by the compiler. Since the calls to memcg_kmem_get_cache are
396 * conditional to this static branch, we'll have to allow modules that does
397 * kmem_cache_alloc and the such to see this symbol as well
398 */
a8964b9b 399struct static_key memcg_kmem_enabled_key;
d7f25f8a 400EXPORT_SYMBOL(memcg_kmem_enabled_key);
a8964b9b 401
a8964b9b
GC
402#endif /* CONFIG_MEMCG_KMEM */
403
f64c3f54 404static struct mem_cgroup_per_zone *
e231875b 405mem_cgroup_zone_zoneinfo(struct mem_cgroup *memcg, struct zone *zone)
f64c3f54 406{
e231875b
JZ
407 int nid = zone_to_nid(zone);
408 int zid = zone_idx(zone);
409
54f72fe0 410 return &memcg->nodeinfo[nid]->zoneinfo[zid];
f64c3f54
BS
411}
412
ad7fa852
TH
413/**
414 * mem_cgroup_css_from_page - css of the memcg associated with a page
415 * @page: page of interest
416 *
417 * If memcg is bound to the default hierarchy, css of the memcg associated
418 * with @page is returned. The returned css remains associated with @page
419 * until it is released.
420 *
421 * If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup
422 * is returned.
423 *
424 * XXX: The above description of behavior on the default hierarchy isn't
425 * strictly true yet as replace_page_cache_page() can modify the
426 * association before @page is released even on the default hierarchy;
427 * however, the current and planned usages don't mix the the two functions
428 * and replace_page_cache_page() will soon be updated to make the invariant
429 * actually true.
430 */
431struct cgroup_subsys_state *mem_cgroup_css_from_page(struct page *page)
432{
433 struct mem_cgroup *memcg;
434
435 rcu_read_lock();
436
437 memcg = page->mem_cgroup;
438
9e10a130 439 if (!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
ad7fa852
TH
440 memcg = root_mem_cgroup;
441
442 rcu_read_unlock();
443 return &memcg->css;
444}
445
2fc04524
VD
446/**
447 * page_cgroup_ino - return inode number of the memcg a page is charged to
448 * @page: the page
449 *
450 * Look up the closest online ancestor of the memory cgroup @page is charged to
451 * and return its inode number or 0 if @page is not charged to any cgroup. It
452 * is safe to call this function without holding a reference to @page.
453 *
454 * Note, this function is inherently racy, because there is nothing to prevent
455 * the cgroup inode from getting torn down and potentially reallocated a moment
456 * after page_cgroup_ino() returns, so it only should be used by callers that
457 * do not care (such as procfs interfaces).
458 */
459ino_t page_cgroup_ino(struct page *page)
460{
461 struct mem_cgroup *memcg;
462 unsigned long ino = 0;
463
464 rcu_read_lock();
465 memcg = READ_ONCE(page->mem_cgroup);
466 while (memcg && !(memcg->css.flags & CSS_ONLINE))
467 memcg = parent_mem_cgroup(memcg);
468 if (memcg)
469 ino = cgroup_ino(memcg->css.cgroup);
470 rcu_read_unlock();
471 return ino;
472}
473
f64c3f54 474static struct mem_cgroup_per_zone *
e231875b 475mem_cgroup_page_zoneinfo(struct mem_cgroup *memcg, struct page *page)
f64c3f54 476{
97a6c37b
JW
477 int nid = page_to_nid(page);
478 int zid = page_zonenum(page);
f64c3f54 479
e231875b 480 return &memcg->nodeinfo[nid]->zoneinfo[zid];
f64c3f54
BS
481}
482
bb4cc1a8
AM
483static struct mem_cgroup_tree_per_zone *
484soft_limit_tree_node_zone(int nid, int zid)
485{
486 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
487}
488
489static struct mem_cgroup_tree_per_zone *
490soft_limit_tree_from_page(struct page *page)
491{
492 int nid = page_to_nid(page);
493 int zid = page_zonenum(page);
494
495 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
496}
497
cf2c8127
JW
498static void __mem_cgroup_insert_exceeded(struct mem_cgroup_per_zone *mz,
499 struct mem_cgroup_tree_per_zone *mctz,
3e32cb2e 500 unsigned long new_usage_in_excess)
bb4cc1a8
AM
501{
502 struct rb_node **p = &mctz->rb_root.rb_node;
503 struct rb_node *parent = NULL;
504 struct mem_cgroup_per_zone *mz_node;
505
506 if (mz->on_tree)
507 return;
508
509 mz->usage_in_excess = new_usage_in_excess;
510 if (!mz->usage_in_excess)
511 return;
512 while (*p) {
513 parent = *p;
514 mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
515 tree_node);
516 if (mz->usage_in_excess < mz_node->usage_in_excess)
517 p = &(*p)->rb_left;
518 /*
519 * We can't avoid mem cgroups that are over their soft
520 * limit by the same amount
521 */
522 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
523 p = &(*p)->rb_right;
524 }
525 rb_link_node(&mz->tree_node, parent, p);
526 rb_insert_color(&mz->tree_node, &mctz->rb_root);
527 mz->on_tree = true;
528}
529
cf2c8127
JW
530static void __mem_cgroup_remove_exceeded(struct mem_cgroup_per_zone *mz,
531 struct mem_cgroup_tree_per_zone *mctz)
bb4cc1a8
AM
532{
533 if (!mz->on_tree)
534 return;
535 rb_erase(&mz->tree_node, &mctz->rb_root);
536 mz->on_tree = false;
537}
538
cf2c8127
JW
539static void mem_cgroup_remove_exceeded(struct mem_cgroup_per_zone *mz,
540 struct mem_cgroup_tree_per_zone *mctz)
bb4cc1a8 541{
0a31bc97
JW
542 unsigned long flags;
543
544 spin_lock_irqsave(&mctz->lock, flags);
cf2c8127 545 __mem_cgroup_remove_exceeded(mz, mctz);
0a31bc97 546 spin_unlock_irqrestore(&mctz->lock, flags);
bb4cc1a8
AM
547}
548
3e32cb2e
JW
549static unsigned long soft_limit_excess(struct mem_cgroup *memcg)
550{
551 unsigned long nr_pages = page_counter_read(&memcg->memory);
4db0c3c2 552 unsigned long soft_limit = READ_ONCE(memcg->soft_limit);
3e32cb2e
JW
553 unsigned long excess = 0;
554
555 if (nr_pages > soft_limit)
556 excess = nr_pages - soft_limit;
557
558 return excess;
559}
bb4cc1a8
AM
560
561static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
562{
3e32cb2e 563 unsigned long excess;
bb4cc1a8
AM
564 struct mem_cgroup_per_zone *mz;
565 struct mem_cgroup_tree_per_zone *mctz;
bb4cc1a8 566
e231875b 567 mctz = soft_limit_tree_from_page(page);
bb4cc1a8
AM
568 /*
569 * Necessary to update all ancestors when hierarchy is used.
570 * because their event counter is not touched.
571 */
572 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
e231875b 573 mz = mem_cgroup_page_zoneinfo(memcg, page);
3e32cb2e 574 excess = soft_limit_excess(memcg);
bb4cc1a8
AM
575 /*
576 * We have to update the tree if mz is on RB-tree or
577 * mem is over its softlimit.
578 */
579 if (excess || mz->on_tree) {
0a31bc97
JW
580 unsigned long flags;
581
582 spin_lock_irqsave(&mctz->lock, flags);
bb4cc1a8
AM
583 /* if on-tree, remove it */
584 if (mz->on_tree)
cf2c8127 585 __mem_cgroup_remove_exceeded(mz, mctz);
bb4cc1a8
AM
586 /*
587 * Insert again. mz->usage_in_excess will be updated.
588 * If excess is 0, no tree ops.
589 */
cf2c8127 590 __mem_cgroup_insert_exceeded(mz, mctz, excess);
0a31bc97 591 spin_unlock_irqrestore(&mctz->lock, flags);
bb4cc1a8
AM
592 }
593 }
594}
595
596static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
597{
bb4cc1a8 598 struct mem_cgroup_tree_per_zone *mctz;
e231875b
JZ
599 struct mem_cgroup_per_zone *mz;
600 int nid, zid;
bb4cc1a8 601
e231875b
JZ
602 for_each_node(nid) {
603 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
604 mz = &memcg->nodeinfo[nid]->zoneinfo[zid];
605 mctz = soft_limit_tree_node_zone(nid, zid);
cf2c8127 606 mem_cgroup_remove_exceeded(mz, mctz);
bb4cc1a8
AM
607 }
608 }
609}
610
611static struct mem_cgroup_per_zone *
612__mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
613{
614 struct rb_node *rightmost = NULL;
615 struct mem_cgroup_per_zone *mz;
616
617retry:
618 mz = NULL;
619 rightmost = rb_last(&mctz->rb_root);
620 if (!rightmost)
621 goto done; /* Nothing to reclaim from */
622
623 mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
624 /*
625 * Remove the node now but someone else can add it back,
626 * we will to add it back at the end of reclaim to its correct
627 * position in the tree.
628 */
cf2c8127 629 __mem_cgroup_remove_exceeded(mz, mctz);
3e32cb2e 630 if (!soft_limit_excess(mz->memcg) ||
ec903c0c 631 !css_tryget_online(&mz->memcg->css))
bb4cc1a8
AM
632 goto retry;
633done:
634 return mz;
635}
636
637static struct mem_cgroup_per_zone *
638mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
639{
640 struct mem_cgroup_per_zone *mz;
641
0a31bc97 642 spin_lock_irq(&mctz->lock);
bb4cc1a8 643 mz = __mem_cgroup_largest_soft_limit_node(mctz);
0a31bc97 644 spin_unlock_irq(&mctz->lock);
bb4cc1a8
AM
645 return mz;
646}
647
711d3d2c 648/*
484ebb3b
GT
649 * Return page count for single (non recursive) @memcg.
650 *
711d3d2c
KH
651 * Implementation Note: reading percpu statistics for memcg.
652 *
653 * Both of vmstat[] and percpu_counter has threshold and do periodic
654 * synchronization to implement "quick" read. There are trade-off between
655 * reading cost and precision of value. Then, we may have a chance to implement
484ebb3b 656 * a periodic synchronization of counter in memcg's counter.
711d3d2c
KH
657 *
658 * But this _read() function is used for user interface now. The user accounts
659 * memory usage by memory cgroup and he _always_ requires exact value because
660 * he accounts memory. Even if we provide quick-and-fuzzy read, we always
661 * have to visit all online cpus and make sum. So, for now, unnecessary
662 * synchronization is not implemented. (just implemented for cpu hotplug)
663 *
664 * If there are kernel internal actions which can make use of some not-exact
665 * value, and reading all cpu value can be performance bottleneck in some
484ebb3b 666 * common workload, threshold and synchronization as vmstat[] should be
711d3d2c
KH
667 * implemented.
668 */
484ebb3b
GT
669static unsigned long
670mem_cgroup_read_stat(struct mem_cgroup *memcg, enum mem_cgroup_stat_index idx)
c62b1a3b 671{
7a159cc9 672 long val = 0;
c62b1a3b 673 int cpu;
c62b1a3b 674
484ebb3b 675 /* Per-cpu values can be negative, use a signed accumulator */
733a572e 676 for_each_possible_cpu(cpu)
c0ff4b85 677 val += per_cpu(memcg->stat->count[idx], cpu);
484ebb3b
GT
678 /*
679 * Summing races with updates, so val may be negative. Avoid exposing
680 * transient negative values.
681 */
682 if (val < 0)
683 val = 0;
c62b1a3b
KH
684 return val;
685}
686
c0ff4b85 687static unsigned long mem_cgroup_read_events(struct mem_cgroup *memcg,
e9f8974f
JW
688 enum mem_cgroup_events_index idx)
689{
690 unsigned long val = 0;
691 int cpu;
692
733a572e 693 for_each_possible_cpu(cpu)
c0ff4b85 694 val += per_cpu(memcg->stat->events[idx], cpu);
e9f8974f
JW
695 return val;
696}
697
c0ff4b85 698static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
b070e65c 699 struct page *page,
0a31bc97 700 int nr_pages)
d52aa412 701{
b2402857
KH
702 /*
703 * Here, RSS means 'mapped anon' and anon's SwapCache. Shmem/tmpfs is
704 * counted as CACHE even if it's on ANON LRU.
705 */
0a31bc97 706 if (PageAnon(page))
b2402857 707 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS],
c0ff4b85 708 nr_pages);
d52aa412 709 else
b2402857 710 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_CACHE],
c0ff4b85 711 nr_pages);
55e462b0 712
b070e65c
DR
713 if (PageTransHuge(page))
714 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS_HUGE],
715 nr_pages);
716
e401f176
KH
717 /* pagein of a big page is an event. So, ignore page size */
718 if (nr_pages > 0)
c0ff4b85 719 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGIN]);
3751d604 720 else {
c0ff4b85 721 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGOUT]);
3751d604
KH
722 nr_pages = -nr_pages; /* for event */
723 }
e401f176 724
13114716 725 __this_cpu_add(memcg->stat->nr_page_events, nr_pages);
6d12e2d8
KH
726}
727
e231875b
JZ
728static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
729 int nid,
730 unsigned int lru_mask)
bb2a0de9 731{
e231875b 732 unsigned long nr = 0;
889976db
YH
733 int zid;
734
e231875b 735 VM_BUG_ON((unsigned)nid >= nr_node_ids);
bb2a0de9 736
e231875b
JZ
737 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
738 struct mem_cgroup_per_zone *mz;
739 enum lru_list lru;
740
741 for_each_lru(lru) {
742 if (!(BIT(lru) & lru_mask))
743 continue;
744 mz = &memcg->nodeinfo[nid]->zoneinfo[zid];
745 nr += mz->lru_size[lru];
746 }
747 }
748 return nr;
889976db 749}
bb2a0de9 750
c0ff4b85 751static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
bb2a0de9 752 unsigned int lru_mask)
6d12e2d8 753{
e231875b 754 unsigned long nr = 0;
889976db 755 int nid;
6d12e2d8 756
31aaea4a 757 for_each_node_state(nid, N_MEMORY)
e231875b
JZ
758 nr += mem_cgroup_node_nr_lru_pages(memcg, nid, lru_mask);
759 return nr;
d52aa412
KH
760}
761
f53d7ce3
JW
762static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
763 enum mem_cgroup_events_target target)
7a159cc9
JW
764{
765 unsigned long val, next;
766
13114716 767 val = __this_cpu_read(memcg->stat->nr_page_events);
4799401f 768 next = __this_cpu_read(memcg->stat->targets[target]);
7a159cc9 769 /* from time_after() in jiffies.h */
f53d7ce3
JW
770 if ((long)next - (long)val < 0) {
771 switch (target) {
772 case MEM_CGROUP_TARGET_THRESH:
773 next = val + THRESHOLDS_EVENTS_TARGET;
774 break;
bb4cc1a8
AM
775 case MEM_CGROUP_TARGET_SOFTLIMIT:
776 next = val + SOFTLIMIT_EVENTS_TARGET;
777 break;
f53d7ce3
JW
778 case MEM_CGROUP_TARGET_NUMAINFO:
779 next = val + NUMAINFO_EVENTS_TARGET;
780 break;
781 default:
782 break;
783 }
784 __this_cpu_write(memcg->stat->targets[target], next);
785 return true;
7a159cc9 786 }
f53d7ce3 787 return false;
d2265e6f
KH
788}
789
790/*
791 * Check events in order.
792 *
793 */
c0ff4b85 794static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
d2265e6f
KH
795{
796 /* threshold event is triggered in finer grain than soft limit */
f53d7ce3
JW
797 if (unlikely(mem_cgroup_event_ratelimit(memcg,
798 MEM_CGROUP_TARGET_THRESH))) {
bb4cc1a8 799 bool do_softlimit;
82b3f2a7 800 bool do_numainfo __maybe_unused;
f53d7ce3 801
bb4cc1a8
AM
802 do_softlimit = mem_cgroup_event_ratelimit(memcg,
803 MEM_CGROUP_TARGET_SOFTLIMIT);
f53d7ce3
JW
804#if MAX_NUMNODES > 1
805 do_numainfo = mem_cgroup_event_ratelimit(memcg,
806 MEM_CGROUP_TARGET_NUMAINFO);
807#endif
c0ff4b85 808 mem_cgroup_threshold(memcg);
bb4cc1a8
AM
809 if (unlikely(do_softlimit))
810 mem_cgroup_update_tree(memcg, page);
453a9bf3 811#if MAX_NUMNODES > 1
f53d7ce3 812 if (unlikely(do_numainfo))
c0ff4b85 813 atomic_inc(&memcg->numainfo_events);
453a9bf3 814#endif
0a31bc97 815 }
d2265e6f
KH
816}
817
cf475ad2 818struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
78fb7466 819{
31a78f23
BS
820 /*
821 * mm_update_next_owner() may clear mm->owner to NULL
822 * if it races with swapoff, page migration, etc.
823 * So this can be called with p == NULL.
824 */
825 if (unlikely(!p))
826 return NULL;
827
073219e9 828 return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
78fb7466 829}
33398cf2 830EXPORT_SYMBOL(mem_cgroup_from_task);
78fb7466 831
df381975 832static struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
54595fe2 833{
c0ff4b85 834 struct mem_cgroup *memcg = NULL;
0b7f569e 835
54595fe2
KH
836 rcu_read_lock();
837 do {
6f6acb00
MH
838 /*
839 * Page cache insertions can happen withou an
840 * actual mm context, e.g. during disk probing
841 * on boot, loopback IO, acct() writes etc.
842 */
843 if (unlikely(!mm))
df381975 844 memcg = root_mem_cgroup;
6f6acb00
MH
845 else {
846 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
847 if (unlikely(!memcg))
848 memcg = root_mem_cgroup;
849 }
ec903c0c 850 } while (!css_tryget_online(&memcg->css));
54595fe2 851 rcu_read_unlock();
c0ff4b85 852 return memcg;
54595fe2
KH
853}
854
5660048c
JW
855/**
856 * mem_cgroup_iter - iterate over memory cgroup hierarchy
857 * @root: hierarchy root
858 * @prev: previously returned memcg, NULL on first invocation
859 * @reclaim: cookie for shared reclaim walks, NULL for full walks
860 *
861 * Returns references to children of the hierarchy below @root, or
862 * @root itself, or %NULL after a full round-trip.
863 *
864 * Caller must pass the return value in @prev on subsequent
865 * invocations for reference counting, or use mem_cgroup_iter_break()
866 * to cancel a hierarchy walk before the round-trip is complete.
867 *
868 * Reclaimers can specify a zone and a priority level in @reclaim to
869 * divide up the memcgs in the hierarchy among all concurrent
870 * reclaimers operating on the same zone and priority.
871 */
694fbc0f 872struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
5660048c 873 struct mem_cgroup *prev,
694fbc0f 874 struct mem_cgroup_reclaim_cookie *reclaim)
14067bb3 875{
33398cf2 876 struct mem_cgroup_reclaim_iter *uninitialized_var(iter);
5ac8fb31 877 struct cgroup_subsys_state *css = NULL;
9f3a0d09 878 struct mem_cgroup *memcg = NULL;
5ac8fb31 879 struct mem_cgroup *pos = NULL;
711d3d2c 880
694fbc0f
AM
881 if (mem_cgroup_disabled())
882 return NULL;
5660048c 883
9f3a0d09
JW
884 if (!root)
885 root = root_mem_cgroup;
7d74b06f 886
9f3a0d09 887 if (prev && !reclaim)
5ac8fb31 888 pos = prev;
14067bb3 889
9f3a0d09
JW
890 if (!root->use_hierarchy && root != root_mem_cgroup) {
891 if (prev)
5ac8fb31 892 goto out;
694fbc0f 893 return root;
9f3a0d09 894 }
14067bb3 895
542f85f9 896 rcu_read_lock();
5f578161 897
5ac8fb31
JW
898 if (reclaim) {
899 struct mem_cgroup_per_zone *mz;
900
901 mz = mem_cgroup_zone_zoneinfo(root, reclaim->zone);
902 iter = &mz->iter[reclaim->priority];
903
904 if (prev && reclaim->generation != iter->generation)
905 goto out_unlock;
906
6df38689 907 while (1) {
4db0c3c2 908 pos = READ_ONCE(iter->position);
6df38689
VD
909 if (!pos || css_tryget(&pos->css))
910 break;
5ac8fb31 911 /*
6df38689
VD
912 * css reference reached zero, so iter->position will
913 * be cleared by ->css_released. However, we should not
914 * rely on this happening soon, because ->css_released
915 * is called from a work queue, and by busy-waiting we
916 * might block it. So we clear iter->position right
917 * away.
5ac8fb31 918 */
6df38689
VD
919 (void)cmpxchg(&iter->position, pos, NULL);
920 }
5ac8fb31
JW
921 }
922
923 if (pos)
924 css = &pos->css;
925
926 for (;;) {
927 css = css_next_descendant_pre(css, &root->css);
928 if (!css) {
929 /*
930 * Reclaimers share the hierarchy walk, and a
931 * new one might jump in right at the end of
932 * the hierarchy - make sure they see at least
933 * one group and restart from the beginning.
934 */
935 if (!prev)
936 continue;
937 break;
527a5ec9 938 }
7d74b06f 939
5ac8fb31
JW
940 /*
941 * Verify the css and acquire a reference. The root
942 * is provided by the caller, so we know it's alive
943 * and kicking, and don't take an extra reference.
944 */
945 memcg = mem_cgroup_from_css(css);
14067bb3 946
5ac8fb31
JW
947 if (css == &root->css)
948 break;
14067bb3 949
b2052564 950 if (css_tryget(css)) {
5ac8fb31
JW
951 /*
952 * Make sure the memcg is initialized:
953 * mem_cgroup_css_online() orders the the
954 * initialization against setting the flag.
955 */
956 if (smp_load_acquire(&memcg->initialized))
957 break;
542f85f9 958
5ac8fb31 959 css_put(css);
527a5ec9 960 }
9f3a0d09 961
5ac8fb31 962 memcg = NULL;
9f3a0d09 963 }
5ac8fb31
JW
964
965 if (reclaim) {
5ac8fb31 966 /*
6df38689
VD
967 * The position could have already been updated by a competing
968 * thread, so check that the value hasn't changed since we read
969 * it to avoid reclaiming from the same cgroup twice.
5ac8fb31 970 */
6df38689
VD
971 (void)cmpxchg(&iter->position, pos, memcg);
972
5ac8fb31
JW
973 if (pos)
974 css_put(&pos->css);
975
976 if (!memcg)
977 iter->generation++;
978 else if (!prev)
979 reclaim->generation = iter->generation;
9f3a0d09 980 }
5ac8fb31 981
542f85f9
MH
982out_unlock:
983 rcu_read_unlock();
5ac8fb31 984out:
c40046f3
MH
985 if (prev && prev != root)
986 css_put(&prev->css);
987
9f3a0d09 988 return memcg;
14067bb3 989}
7d74b06f 990
5660048c
JW
991/**
992 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
993 * @root: hierarchy root
994 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
995 */
996void mem_cgroup_iter_break(struct mem_cgroup *root,
997 struct mem_cgroup *prev)
9f3a0d09
JW
998{
999 if (!root)
1000 root = root_mem_cgroup;
1001 if (prev && prev != root)
1002 css_put(&prev->css);
1003}
7d74b06f 1004
6df38689
VD
1005static void invalidate_reclaim_iterators(struct mem_cgroup *dead_memcg)
1006{
1007 struct mem_cgroup *memcg = dead_memcg;
1008 struct mem_cgroup_reclaim_iter *iter;
1009 struct mem_cgroup_per_zone *mz;
1010 int nid, zid;
1011 int i;
1012
1013 while ((memcg = parent_mem_cgroup(memcg))) {
1014 for_each_node(nid) {
1015 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1016 mz = &memcg->nodeinfo[nid]->zoneinfo[zid];
1017 for (i = 0; i <= DEF_PRIORITY; i++) {
1018 iter = &mz->iter[i];
1019 cmpxchg(&iter->position,
1020 dead_memcg, NULL);
1021 }
1022 }
1023 }
1024 }
1025}
1026
9f3a0d09
JW
1027/*
1028 * Iteration constructs for visiting all cgroups (under a tree). If
1029 * loops are exited prematurely (break), mem_cgroup_iter_break() must
1030 * be used for reference counting.
1031 */
1032#define for_each_mem_cgroup_tree(iter, root) \
527a5ec9 1033 for (iter = mem_cgroup_iter(root, NULL, NULL); \
9f3a0d09 1034 iter != NULL; \
527a5ec9 1035 iter = mem_cgroup_iter(root, iter, NULL))
711d3d2c 1036
9f3a0d09 1037#define for_each_mem_cgroup(iter) \
527a5ec9 1038 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
9f3a0d09 1039 iter != NULL; \
527a5ec9 1040 iter = mem_cgroup_iter(NULL, iter, NULL))
14067bb3 1041
925b7673
JW
1042/**
1043 * mem_cgroup_zone_lruvec - get the lru list vector for a zone and memcg
1044 * @zone: zone of the wanted lruvec
fa9add64 1045 * @memcg: memcg of the wanted lruvec
925b7673
JW
1046 *
1047 * Returns the lru list vector holding pages for the given @zone and
1048 * @mem. This can be the global zone lruvec, if the memory controller
1049 * is disabled.
1050 */
1051struct lruvec *mem_cgroup_zone_lruvec(struct zone *zone,
1052 struct mem_cgroup *memcg)
1053{
1054 struct mem_cgroup_per_zone *mz;
bea8c150 1055 struct lruvec *lruvec;
925b7673 1056
bea8c150
HD
1057 if (mem_cgroup_disabled()) {
1058 lruvec = &zone->lruvec;
1059 goto out;
1060 }
925b7673 1061
e231875b 1062 mz = mem_cgroup_zone_zoneinfo(memcg, zone);
bea8c150
HD
1063 lruvec = &mz->lruvec;
1064out:
1065 /*
1066 * Since a node can be onlined after the mem_cgroup was created,
1067 * we have to be prepared to initialize lruvec->zone here;
1068 * and if offlined then reonlined, we need to reinitialize it.
1069 */
1070 if (unlikely(lruvec->zone != zone))
1071 lruvec->zone = zone;
1072 return lruvec;
925b7673
JW
1073}
1074
925b7673 1075/**
dfe0e773 1076 * mem_cgroup_page_lruvec - return lruvec for isolating/putting an LRU page
925b7673 1077 * @page: the page
fa9add64 1078 * @zone: zone of the page
dfe0e773
JW
1079 *
1080 * This function is only safe when following the LRU page isolation
1081 * and putback protocol: the LRU lock must be held, and the page must
1082 * either be PageLRU() or the caller must have isolated/allocated it.
925b7673 1083 */
fa9add64 1084struct lruvec *mem_cgroup_page_lruvec(struct page *page, struct zone *zone)
08e552c6 1085{
08e552c6 1086 struct mem_cgroup_per_zone *mz;
925b7673 1087 struct mem_cgroup *memcg;
bea8c150 1088 struct lruvec *lruvec;
6d12e2d8 1089
bea8c150
HD
1090 if (mem_cgroup_disabled()) {
1091 lruvec = &zone->lruvec;
1092 goto out;
1093 }
925b7673 1094
1306a85a 1095 memcg = page->mem_cgroup;
7512102c 1096 /*
dfe0e773 1097 * Swapcache readahead pages are added to the LRU - and
29833315 1098 * possibly migrated - before they are charged.
7512102c 1099 */
29833315
JW
1100 if (!memcg)
1101 memcg = root_mem_cgroup;
7512102c 1102
e231875b 1103 mz = mem_cgroup_page_zoneinfo(memcg, page);
bea8c150
HD
1104 lruvec = &mz->lruvec;
1105out:
1106 /*
1107 * Since a node can be onlined after the mem_cgroup was created,
1108 * we have to be prepared to initialize lruvec->zone here;
1109 * and if offlined then reonlined, we need to reinitialize it.
1110 */
1111 if (unlikely(lruvec->zone != zone))
1112 lruvec->zone = zone;
1113 return lruvec;
08e552c6 1114}
b69408e8 1115
925b7673 1116/**
fa9add64
HD
1117 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1118 * @lruvec: mem_cgroup per zone lru vector
1119 * @lru: index of lru list the page is sitting on
1120 * @nr_pages: positive when adding or negative when removing
925b7673 1121 *
fa9add64
HD
1122 * This function must be called when a page is added to or removed from an
1123 * lru list.
3f58a829 1124 */
fa9add64
HD
1125void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
1126 int nr_pages)
3f58a829
MK
1127{
1128 struct mem_cgroup_per_zone *mz;
fa9add64 1129 unsigned long *lru_size;
3f58a829
MK
1130
1131 if (mem_cgroup_disabled())
1132 return;
1133
fa9add64
HD
1134 mz = container_of(lruvec, struct mem_cgroup_per_zone, lruvec);
1135 lru_size = mz->lru_size + lru;
1136 *lru_size += nr_pages;
1137 VM_BUG_ON((long)(*lru_size) < 0);
08e552c6 1138}
544122e5 1139
2314b42d 1140bool task_in_mem_cgroup(struct task_struct *task, struct mem_cgroup *memcg)
c3ac9a8a 1141{
2314b42d 1142 struct mem_cgroup *task_memcg;
158e0a2d 1143 struct task_struct *p;
ffbdccf5 1144 bool ret;
4c4a2214 1145
158e0a2d 1146 p = find_lock_task_mm(task);
de077d22 1147 if (p) {
2314b42d 1148 task_memcg = get_mem_cgroup_from_mm(p->mm);
de077d22
DR
1149 task_unlock(p);
1150 } else {
1151 /*
1152 * All threads may have already detached their mm's, but the oom
1153 * killer still needs to detect if they have already been oom
1154 * killed to prevent needlessly killing additional tasks.
1155 */
ffbdccf5 1156 rcu_read_lock();
2314b42d
JW
1157 task_memcg = mem_cgroup_from_task(task);
1158 css_get(&task_memcg->css);
ffbdccf5 1159 rcu_read_unlock();
de077d22 1160 }
2314b42d
JW
1161 ret = mem_cgroup_is_descendant(task_memcg, memcg);
1162 css_put(&task_memcg->css);
4c4a2214
DR
1163 return ret;
1164}
1165
3e32cb2e 1166#define mem_cgroup_from_counter(counter, member) \
6d61ef40
BS
1167 container_of(counter, struct mem_cgroup, member)
1168
19942822 1169/**
9d11ea9f 1170 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
dad7557e 1171 * @memcg: the memory cgroup
19942822 1172 *
9d11ea9f 1173 * Returns the maximum amount of memory @mem can be charged with, in
7ec99d62 1174 * pages.
19942822 1175 */
c0ff4b85 1176static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
19942822 1177{
3e32cb2e
JW
1178 unsigned long margin = 0;
1179 unsigned long count;
1180 unsigned long limit;
9d11ea9f 1181
3e32cb2e 1182 count = page_counter_read(&memcg->memory);
4db0c3c2 1183 limit = READ_ONCE(memcg->memory.limit);
3e32cb2e
JW
1184 if (count < limit)
1185 margin = limit - count;
1186
1187 if (do_swap_account) {
1188 count = page_counter_read(&memcg->memsw);
4db0c3c2 1189 limit = READ_ONCE(memcg->memsw.limit);
3e32cb2e
JW
1190 if (count <= limit)
1191 margin = min(margin, limit - count);
1192 }
1193
1194 return margin;
19942822
JW
1195}
1196
32047e2a 1197/*
bdcbb659 1198 * A routine for checking "mem" is under move_account() or not.
32047e2a 1199 *
bdcbb659
QH
1200 * Checking a cgroup is mc.from or mc.to or under hierarchy of
1201 * moving cgroups. This is for waiting at high-memory pressure
1202 * caused by "move".
32047e2a 1203 */
c0ff4b85 1204static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
4b534334 1205{
2bd9bb20
KH
1206 struct mem_cgroup *from;
1207 struct mem_cgroup *to;
4b534334 1208 bool ret = false;
2bd9bb20
KH
1209 /*
1210 * Unlike task_move routines, we access mc.to, mc.from not under
1211 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1212 */
1213 spin_lock(&mc.lock);
1214 from = mc.from;
1215 to = mc.to;
1216 if (!from)
1217 goto unlock;
3e92041d 1218
2314b42d
JW
1219 ret = mem_cgroup_is_descendant(from, memcg) ||
1220 mem_cgroup_is_descendant(to, memcg);
2bd9bb20
KH
1221unlock:
1222 spin_unlock(&mc.lock);
4b534334
KH
1223 return ret;
1224}
1225
c0ff4b85 1226static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
4b534334
KH
1227{
1228 if (mc.moving_task && current != mc.moving_task) {
c0ff4b85 1229 if (mem_cgroup_under_move(memcg)) {
4b534334
KH
1230 DEFINE_WAIT(wait);
1231 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1232 /* moving charge context might have finished. */
1233 if (mc.moving_task)
1234 schedule();
1235 finish_wait(&mc.waitq, &wait);
1236 return true;
1237 }
1238 }
1239 return false;
1240}
1241
58cf188e 1242#define K(x) ((x) << (PAGE_SHIFT-10))
e222432b 1243/**
58cf188e 1244 * mem_cgroup_print_oom_info: Print OOM information relevant to memory controller.
e222432b
BS
1245 * @memcg: The memory cgroup that went over limit
1246 * @p: Task that is going to be killed
1247 *
1248 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1249 * enabled
1250 */
1251void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1252{
e61734c5 1253 /* oom_info_lock ensures that parallel ooms do not interleave */
08088cb9 1254 static DEFINE_MUTEX(oom_info_lock);
58cf188e
SZ
1255 struct mem_cgroup *iter;
1256 unsigned int i;
e222432b 1257
08088cb9 1258 mutex_lock(&oom_info_lock);
e222432b
BS
1259 rcu_read_lock();
1260
2415b9f5
BV
1261 if (p) {
1262 pr_info("Task in ");
1263 pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
1264 pr_cont(" killed as a result of limit of ");
1265 } else {
1266 pr_info("Memory limit reached of cgroup ");
1267 }
1268
e61734c5 1269 pr_cont_cgroup_path(memcg->css.cgroup);
0346dadb 1270 pr_cont("\n");
e222432b 1271
e222432b
BS
1272 rcu_read_unlock();
1273
3e32cb2e
JW
1274 pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
1275 K((u64)page_counter_read(&memcg->memory)),
1276 K((u64)memcg->memory.limit), memcg->memory.failcnt);
1277 pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
1278 K((u64)page_counter_read(&memcg->memsw)),
1279 K((u64)memcg->memsw.limit), memcg->memsw.failcnt);
1280 pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
1281 K((u64)page_counter_read(&memcg->kmem)),
1282 K((u64)memcg->kmem.limit), memcg->kmem.failcnt);
58cf188e
SZ
1283
1284 for_each_mem_cgroup_tree(iter, memcg) {
e61734c5
TH
1285 pr_info("Memory cgroup stats for ");
1286 pr_cont_cgroup_path(iter->css.cgroup);
58cf188e
SZ
1287 pr_cont(":");
1288
1289 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
1290 if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
1291 continue;
484ebb3b 1292 pr_cont(" %s:%luKB", mem_cgroup_stat_names[i],
58cf188e
SZ
1293 K(mem_cgroup_read_stat(iter, i)));
1294 }
1295
1296 for (i = 0; i < NR_LRU_LISTS; i++)
1297 pr_cont(" %s:%luKB", mem_cgroup_lru_names[i],
1298 K(mem_cgroup_nr_lru_pages(iter, BIT(i))));
1299
1300 pr_cont("\n");
1301 }
08088cb9 1302 mutex_unlock(&oom_info_lock);
e222432b
BS
1303}
1304
81d39c20
KH
1305/*
1306 * This function returns the number of memcg under hierarchy tree. Returns
1307 * 1(self count) if no children.
1308 */
c0ff4b85 1309static int mem_cgroup_count_children(struct mem_cgroup *memcg)
81d39c20
KH
1310{
1311 int num = 0;
7d74b06f
KH
1312 struct mem_cgroup *iter;
1313
c0ff4b85 1314 for_each_mem_cgroup_tree(iter, memcg)
7d74b06f 1315 num++;
81d39c20
KH
1316 return num;
1317}
1318
a63d83f4
DR
1319/*
1320 * Return the memory (and swap, if configured) limit for a memcg.
1321 */
3e32cb2e 1322static unsigned long mem_cgroup_get_limit(struct mem_cgroup *memcg)
a63d83f4 1323{
3e32cb2e 1324 unsigned long limit;
f3e8eb70 1325
3e32cb2e 1326 limit = memcg->memory.limit;
9a5a8f19 1327 if (mem_cgroup_swappiness(memcg)) {
3e32cb2e 1328 unsigned long memsw_limit;
9a5a8f19 1329
3e32cb2e
JW
1330 memsw_limit = memcg->memsw.limit;
1331 limit = min(limit + total_swap_pages, memsw_limit);
9a5a8f19 1332 }
9a5a8f19 1333 return limit;
a63d83f4
DR
1334}
1335
0ccab5b1 1336static bool mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
19965460 1337 int order)
9cbb78bb 1338{
6e0fc46d
DR
1339 struct oom_control oc = {
1340 .zonelist = NULL,
1341 .nodemask = NULL,
1342 .gfp_mask = gfp_mask,
1343 .order = order,
6e0fc46d 1344 };
9cbb78bb
DR
1345 struct mem_cgroup *iter;
1346 unsigned long chosen_points = 0;
1347 unsigned long totalpages;
1348 unsigned int points = 0;
1349 struct task_struct *chosen = NULL;
1350
dc56401f
JW
1351 mutex_lock(&oom_lock);
1352
876aafbf 1353 /*
465adcf1
DR
1354 * If current has a pending SIGKILL or is exiting, then automatically
1355 * select it. The goal is to allow it to allocate so that it may
1356 * quickly exit and free its memory.
876aafbf 1357 */
d003f371 1358 if (fatal_signal_pending(current) || task_will_free_mem(current)) {
16e95196 1359 mark_oom_victim(current);
dc56401f 1360 goto unlock;
876aafbf
DR
1361 }
1362
6e0fc46d 1363 check_panic_on_oom(&oc, CONSTRAINT_MEMCG, memcg);
3e32cb2e 1364 totalpages = mem_cgroup_get_limit(memcg) ? : 1;
9cbb78bb 1365 for_each_mem_cgroup_tree(iter, memcg) {
72ec7029 1366 struct css_task_iter it;
9cbb78bb
DR
1367 struct task_struct *task;
1368
72ec7029
TH
1369 css_task_iter_start(&iter->css, &it);
1370 while ((task = css_task_iter_next(&it))) {
6e0fc46d 1371 switch (oom_scan_process_thread(&oc, task, totalpages)) {
9cbb78bb
DR
1372 case OOM_SCAN_SELECT:
1373 if (chosen)
1374 put_task_struct(chosen);
1375 chosen = task;
1376 chosen_points = ULONG_MAX;
1377 get_task_struct(chosen);
1378 /* fall through */
1379 case OOM_SCAN_CONTINUE:
1380 continue;
1381 case OOM_SCAN_ABORT:
72ec7029 1382 css_task_iter_end(&it);
9cbb78bb
DR
1383 mem_cgroup_iter_break(memcg, iter);
1384 if (chosen)
1385 put_task_struct(chosen);
dc56401f 1386 goto unlock;
9cbb78bb
DR
1387 case OOM_SCAN_OK:
1388 break;
1389 };
1390 points = oom_badness(task, memcg, NULL, totalpages);
d49ad935
DR
1391 if (!points || points < chosen_points)
1392 continue;
1393 /* Prefer thread group leaders for display purposes */
1394 if (points == chosen_points &&
1395 thread_group_leader(chosen))
1396 continue;
1397
1398 if (chosen)
1399 put_task_struct(chosen);
1400 chosen = task;
1401 chosen_points = points;
1402 get_task_struct(chosen);
9cbb78bb 1403 }
72ec7029 1404 css_task_iter_end(&it);
9cbb78bb
DR
1405 }
1406
dc56401f
JW
1407 if (chosen) {
1408 points = chosen_points * 1000 / totalpages;
6e0fc46d
DR
1409 oom_kill_process(&oc, chosen, points, totalpages, memcg,
1410 "Memory cgroup out of memory");
dc56401f
JW
1411 }
1412unlock:
1413 mutex_unlock(&oom_lock);
0ccab5b1 1414 return chosen;
9cbb78bb
DR
1415}
1416
ae6e71d3
MC
1417#if MAX_NUMNODES > 1
1418
4d0c066d
KH
1419/**
1420 * test_mem_cgroup_node_reclaimable
dad7557e 1421 * @memcg: the target memcg
4d0c066d
KH
1422 * @nid: the node ID to be checked.
1423 * @noswap : specify true here if the user wants flle only information.
1424 *
1425 * This function returns whether the specified memcg contains any
1426 * reclaimable pages on a node. Returns true if there are any reclaimable
1427 * pages in the node.
1428 */
c0ff4b85 1429static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *memcg,
4d0c066d
KH
1430 int nid, bool noswap)
1431{
c0ff4b85 1432 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_FILE))
4d0c066d
KH
1433 return true;
1434 if (noswap || !total_swap_pages)
1435 return false;
c0ff4b85 1436 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_ANON))
4d0c066d
KH
1437 return true;
1438 return false;
1439
1440}
889976db
YH
1441
1442/*
1443 * Always updating the nodemask is not very good - even if we have an empty
1444 * list or the wrong list here, we can start from some node and traverse all
1445 * nodes based on the zonelist. So update the list loosely once per 10 secs.
1446 *
1447 */
c0ff4b85 1448static void mem_cgroup_may_update_nodemask(struct mem_cgroup *memcg)
889976db
YH
1449{
1450 int nid;
453a9bf3
KH
1451 /*
1452 * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
1453 * pagein/pageout changes since the last update.
1454 */
c0ff4b85 1455 if (!atomic_read(&memcg->numainfo_events))
453a9bf3 1456 return;
c0ff4b85 1457 if (atomic_inc_return(&memcg->numainfo_updating) > 1)
889976db
YH
1458 return;
1459
889976db 1460 /* make a nodemask where this memcg uses memory from */
31aaea4a 1461 memcg->scan_nodes = node_states[N_MEMORY];
889976db 1462
31aaea4a 1463 for_each_node_mask(nid, node_states[N_MEMORY]) {
889976db 1464
c0ff4b85
R
1465 if (!test_mem_cgroup_node_reclaimable(memcg, nid, false))
1466 node_clear(nid, memcg->scan_nodes);
889976db 1467 }
453a9bf3 1468
c0ff4b85
R
1469 atomic_set(&memcg->numainfo_events, 0);
1470 atomic_set(&memcg->numainfo_updating, 0);
889976db
YH
1471}
1472
1473/*
1474 * Selecting a node where we start reclaim from. Because what we need is just
1475 * reducing usage counter, start from anywhere is O,K. Considering
1476 * memory reclaim from current node, there are pros. and cons.
1477 *
1478 * Freeing memory from current node means freeing memory from a node which
1479 * we'll use or we've used. So, it may make LRU bad. And if several threads
1480 * hit limits, it will see a contention on a node. But freeing from remote
1481 * node means more costs for memory reclaim because of memory latency.
1482 *
1483 * Now, we use round-robin. Better algorithm is welcomed.
1484 */
c0ff4b85 1485int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
889976db
YH
1486{
1487 int node;
1488
c0ff4b85
R
1489 mem_cgroup_may_update_nodemask(memcg);
1490 node = memcg->last_scanned_node;
889976db 1491
c0ff4b85 1492 node = next_node(node, memcg->scan_nodes);
889976db 1493 if (node == MAX_NUMNODES)
c0ff4b85 1494 node = first_node(memcg->scan_nodes);
889976db
YH
1495 /*
1496 * We call this when we hit limit, not when pages are added to LRU.
1497 * No LRU may hold pages because all pages are UNEVICTABLE or
1498 * memcg is too small and all pages are not on LRU. In that case,
1499 * we use curret node.
1500 */
1501 if (unlikely(node == MAX_NUMNODES))
1502 node = numa_node_id();
1503
c0ff4b85 1504 memcg->last_scanned_node = node;
889976db
YH
1505 return node;
1506}
889976db 1507#else
c0ff4b85 1508int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
889976db
YH
1509{
1510 return 0;
1511}
1512#endif
1513
0608f43d
AM
1514static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
1515 struct zone *zone,
1516 gfp_t gfp_mask,
1517 unsigned long *total_scanned)
1518{
1519 struct mem_cgroup *victim = NULL;
1520 int total = 0;
1521 int loop = 0;
1522 unsigned long excess;
1523 unsigned long nr_scanned;
1524 struct mem_cgroup_reclaim_cookie reclaim = {
1525 .zone = zone,
1526 .priority = 0,
1527 };
1528
3e32cb2e 1529 excess = soft_limit_excess(root_memcg);
0608f43d
AM
1530
1531 while (1) {
1532 victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
1533 if (!victim) {
1534 loop++;
1535 if (loop >= 2) {
1536 /*
1537 * If we have not been able to reclaim
1538 * anything, it might because there are
1539 * no reclaimable pages under this hierarchy
1540 */
1541 if (!total)
1542 break;
1543 /*
1544 * We want to do more targeted reclaim.
1545 * excess >> 2 is not to excessive so as to
1546 * reclaim too much, nor too less that we keep
1547 * coming back to reclaim from this cgroup
1548 */
1549 if (total >= (excess >> 2) ||
1550 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
1551 break;
1552 }
1553 continue;
1554 }
0608f43d
AM
1555 total += mem_cgroup_shrink_node_zone(victim, gfp_mask, false,
1556 zone, &nr_scanned);
1557 *total_scanned += nr_scanned;
3e32cb2e 1558 if (!soft_limit_excess(root_memcg))
0608f43d 1559 break;
6d61ef40 1560 }
0608f43d
AM
1561 mem_cgroup_iter_break(root_memcg, victim);
1562 return total;
6d61ef40
BS
1563}
1564
0056f4e6
JW
1565#ifdef CONFIG_LOCKDEP
1566static struct lockdep_map memcg_oom_lock_dep_map = {
1567 .name = "memcg_oom_lock",
1568};
1569#endif
1570
fb2a6fc5
JW
1571static DEFINE_SPINLOCK(memcg_oom_lock);
1572
867578cb
KH
1573/*
1574 * Check OOM-Killer is already running under our hierarchy.
1575 * If someone is running, return false.
1576 */
fb2a6fc5 1577static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
867578cb 1578{
79dfdacc 1579 struct mem_cgroup *iter, *failed = NULL;
a636b327 1580
fb2a6fc5
JW
1581 spin_lock(&memcg_oom_lock);
1582
9f3a0d09 1583 for_each_mem_cgroup_tree(iter, memcg) {
23751be0 1584 if (iter->oom_lock) {
79dfdacc
MH
1585 /*
1586 * this subtree of our hierarchy is already locked
1587 * so we cannot give a lock.
1588 */
79dfdacc 1589 failed = iter;
9f3a0d09
JW
1590 mem_cgroup_iter_break(memcg, iter);
1591 break;
23751be0
JW
1592 } else
1593 iter->oom_lock = true;
7d74b06f 1594 }
867578cb 1595
fb2a6fc5
JW
1596 if (failed) {
1597 /*
1598 * OK, we failed to lock the whole subtree so we have
1599 * to clean up what we set up to the failing subtree
1600 */
1601 for_each_mem_cgroup_tree(iter, memcg) {
1602 if (iter == failed) {
1603 mem_cgroup_iter_break(memcg, iter);
1604 break;
1605 }
1606 iter->oom_lock = false;
79dfdacc 1607 }
0056f4e6
JW
1608 } else
1609 mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_);
fb2a6fc5
JW
1610
1611 spin_unlock(&memcg_oom_lock);
1612
1613 return !failed;
a636b327 1614}
0b7f569e 1615
fb2a6fc5 1616static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
0b7f569e 1617{
7d74b06f
KH
1618 struct mem_cgroup *iter;
1619
fb2a6fc5 1620 spin_lock(&memcg_oom_lock);
0056f4e6 1621 mutex_release(&memcg_oom_lock_dep_map, 1, _RET_IP_);
c0ff4b85 1622 for_each_mem_cgroup_tree(iter, memcg)
79dfdacc 1623 iter->oom_lock = false;
fb2a6fc5 1624 spin_unlock(&memcg_oom_lock);
79dfdacc
MH
1625}
1626
c0ff4b85 1627static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
79dfdacc
MH
1628{
1629 struct mem_cgroup *iter;
1630
c2b42d3c 1631 spin_lock(&memcg_oom_lock);
c0ff4b85 1632 for_each_mem_cgroup_tree(iter, memcg)
c2b42d3c
TH
1633 iter->under_oom++;
1634 spin_unlock(&memcg_oom_lock);
79dfdacc
MH
1635}
1636
c0ff4b85 1637static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
79dfdacc
MH
1638{
1639 struct mem_cgroup *iter;
1640
867578cb
KH
1641 /*
1642 * When a new child is created while the hierarchy is under oom,
c2b42d3c 1643 * mem_cgroup_oom_lock() may not be called. Watch for underflow.
867578cb 1644 */
c2b42d3c 1645 spin_lock(&memcg_oom_lock);
c0ff4b85 1646 for_each_mem_cgroup_tree(iter, memcg)
c2b42d3c
TH
1647 if (iter->under_oom > 0)
1648 iter->under_oom--;
1649 spin_unlock(&memcg_oom_lock);
0b7f569e
KH
1650}
1651
867578cb
KH
1652static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1653
dc98df5a 1654struct oom_wait_info {
d79154bb 1655 struct mem_cgroup *memcg;
dc98df5a
KH
1656 wait_queue_t wait;
1657};
1658
1659static int memcg_oom_wake_function(wait_queue_t *wait,
1660 unsigned mode, int sync, void *arg)
1661{
d79154bb
HD
1662 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
1663 struct mem_cgroup *oom_wait_memcg;
dc98df5a
KH
1664 struct oom_wait_info *oom_wait_info;
1665
1666 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
d79154bb 1667 oom_wait_memcg = oom_wait_info->memcg;
dc98df5a 1668
2314b42d
JW
1669 if (!mem_cgroup_is_descendant(wake_memcg, oom_wait_memcg) &&
1670 !mem_cgroup_is_descendant(oom_wait_memcg, wake_memcg))
dc98df5a 1671 return 0;
dc98df5a
KH
1672 return autoremove_wake_function(wait, mode, sync, arg);
1673}
1674
c0ff4b85 1675static void memcg_oom_recover(struct mem_cgroup *memcg)
3c11ecf4 1676{
c2b42d3c
TH
1677 /*
1678 * For the following lockless ->under_oom test, the only required
1679 * guarantee is that it must see the state asserted by an OOM when
1680 * this function is called as a result of userland actions
1681 * triggered by the notification of the OOM. This is trivially
1682 * achieved by invoking mem_cgroup_mark_under_oom() before
1683 * triggering notification.
1684 */
1685 if (memcg && memcg->under_oom)
f4b90b70 1686 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
3c11ecf4
KH
1687}
1688
3812c8c8 1689static void mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
0b7f569e 1690{
626ebc41 1691 if (!current->memcg_may_oom)
3812c8c8 1692 return;
867578cb 1693 /*
49426420
JW
1694 * We are in the middle of the charge context here, so we
1695 * don't want to block when potentially sitting on a callstack
1696 * that holds all kinds of filesystem and mm locks.
1697 *
1698 * Also, the caller may handle a failed allocation gracefully
1699 * (like optional page cache readahead) and so an OOM killer
1700 * invocation might not even be necessary.
1701 *
1702 * That's why we don't do anything here except remember the
1703 * OOM context and then deal with it at the end of the page
1704 * fault when the stack is unwound, the locks are released,
1705 * and when we know whether the fault was overall successful.
867578cb 1706 */
49426420 1707 css_get(&memcg->css);
626ebc41
TH
1708 current->memcg_in_oom = memcg;
1709 current->memcg_oom_gfp_mask = mask;
1710 current->memcg_oom_order = order;
3812c8c8
JW
1711}
1712
1713/**
1714 * mem_cgroup_oom_synchronize - complete memcg OOM handling
49426420 1715 * @handle: actually kill/wait or just clean up the OOM state
3812c8c8 1716 *
49426420
JW
1717 * This has to be called at the end of a page fault if the memcg OOM
1718 * handler was enabled.
3812c8c8 1719 *
49426420 1720 * Memcg supports userspace OOM handling where failed allocations must
3812c8c8
JW
1721 * sleep on a waitqueue until the userspace task resolves the
1722 * situation. Sleeping directly in the charge context with all kinds
1723 * of locks held is not a good idea, instead we remember an OOM state
1724 * in the task and mem_cgroup_oom_synchronize() has to be called at
49426420 1725 * the end of the page fault to complete the OOM handling.
3812c8c8
JW
1726 *
1727 * Returns %true if an ongoing memcg OOM situation was detected and
49426420 1728 * completed, %false otherwise.
3812c8c8 1729 */
49426420 1730bool mem_cgroup_oom_synchronize(bool handle)
3812c8c8 1731{
626ebc41 1732 struct mem_cgroup *memcg = current->memcg_in_oom;
3812c8c8 1733 struct oom_wait_info owait;
49426420 1734 bool locked;
3812c8c8
JW
1735
1736 /* OOM is global, do not handle */
3812c8c8 1737 if (!memcg)
49426420 1738 return false;
3812c8c8 1739
c32b3cbe 1740 if (!handle || oom_killer_disabled)
49426420 1741 goto cleanup;
3812c8c8
JW
1742
1743 owait.memcg = memcg;
1744 owait.wait.flags = 0;
1745 owait.wait.func = memcg_oom_wake_function;
1746 owait.wait.private = current;
1747 INIT_LIST_HEAD(&owait.wait.task_list);
867578cb 1748
3812c8c8 1749 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
49426420
JW
1750 mem_cgroup_mark_under_oom(memcg);
1751
1752 locked = mem_cgroup_oom_trylock(memcg);
1753
1754 if (locked)
1755 mem_cgroup_oom_notify(memcg);
1756
1757 if (locked && !memcg->oom_kill_disable) {
1758 mem_cgroup_unmark_under_oom(memcg);
1759 finish_wait(&memcg_oom_waitq, &owait.wait);
626ebc41
TH
1760 mem_cgroup_out_of_memory(memcg, current->memcg_oom_gfp_mask,
1761 current->memcg_oom_order);
49426420 1762 } else {
3812c8c8 1763 schedule();
49426420
JW
1764 mem_cgroup_unmark_under_oom(memcg);
1765 finish_wait(&memcg_oom_waitq, &owait.wait);
1766 }
1767
1768 if (locked) {
fb2a6fc5
JW
1769 mem_cgroup_oom_unlock(memcg);
1770 /*
1771 * There is no guarantee that an OOM-lock contender
1772 * sees the wakeups triggered by the OOM kill
1773 * uncharges. Wake any sleepers explicitely.
1774 */
1775 memcg_oom_recover(memcg);
1776 }
49426420 1777cleanup:
626ebc41 1778 current->memcg_in_oom = NULL;
3812c8c8 1779 css_put(&memcg->css);
867578cb 1780 return true;
0b7f569e
KH
1781}
1782
d7365e78
JW
1783/**
1784 * mem_cgroup_begin_page_stat - begin a page state statistics transaction
1785 * @page: page that is going to change accounted state
32047e2a 1786 *
d7365e78
JW
1787 * This function must mark the beginning of an accounted page state
1788 * change to prevent double accounting when the page is concurrently
1789 * being moved to another memcg:
32047e2a 1790 *
6de22619 1791 * memcg = mem_cgroup_begin_page_stat(page);
d7365e78
JW
1792 * if (TestClearPageState(page))
1793 * mem_cgroup_update_page_stat(memcg, state, -1);
6de22619 1794 * mem_cgroup_end_page_stat(memcg);
d69b042f 1795 */
6de22619 1796struct mem_cgroup *mem_cgroup_begin_page_stat(struct page *page)
89c06bd5
KH
1797{
1798 struct mem_cgroup *memcg;
6de22619 1799 unsigned long flags;
89c06bd5 1800
6de22619
JW
1801 /*
1802 * The RCU lock is held throughout the transaction. The fast
1803 * path can get away without acquiring the memcg->move_lock
1804 * because page moving starts with an RCU grace period.
1805 *
1806 * The RCU lock also protects the memcg from being freed when
1807 * the page state that is going to change is the only thing
1808 * preventing the page from being uncharged.
1809 * E.g. end-writeback clearing PageWriteback(), which allows
1810 * migration to go ahead and uncharge the page before the
1811 * account transaction might be complete.
1812 */
d7365e78
JW
1813 rcu_read_lock();
1814
1815 if (mem_cgroup_disabled())
1816 return NULL;
89c06bd5 1817again:
1306a85a 1818 memcg = page->mem_cgroup;
29833315 1819 if (unlikely(!memcg))
d7365e78
JW
1820 return NULL;
1821
bdcbb659 1822 if (atomic_read(&memcg->moving_account) <= 0)
d7365e78 1823 return memcg;
89c06bd5 1824
6de22619 1825 spin_lock_irqsave(&memcg->move_lock, flags);
1306a85a 1826 if (memcg != page->mem_cgroup) {
6de22619 1827 spin_unlock_irqrestore(&memcg->move_lock, flags);
89c06bd5
KH
1828 goto again;
1829 }
6de22619
JW
1830
1831 /*
1832 * When charge migration first begins, we can have locked and
1833 * unlocked page stat updates happening concurrently. Track
1834 * the task who has the lock for mem_cgroup_end_page_stat().
1835 */
1836 memcg->move_lock_task = current;
1837 memcg->move_lock_flags = flags;
d7365e78
JW
1838
1839 return memcg;
89c06bd5 1840}
c4843a75 1841EXPORT_SYMBOL(mem_cgroup_begin_page_stat);
89c06bd5 1842
d7365e78
JW
1843/**
1844 * mem_cgroup_end_page_stat - finish a page state statistics transaction
1845 * @memcg: the memcg that was accounted against
d7365e78 1846 */
6de22619 1847void mem_cgroup_end_page_stat(struct mem_cgroup *memcg)
89c06bd5 1848{
6de22619
JW
1849 if (memcg && memcg->move_lock_task == current) {
1850 unsigned long flags = memcg->move_lock_flags;
1851
1852 memcg->move_lock_task = NULL;
1853 memcg->move_lock_flags = 0;
1854
1855 spin_unlock_irqrestore(&memcg->move_lock, flags);
1856 }
89c06bd5 1857
d7365e78 1858 rcu_read_unlock();
89c06bd5 1859}
c4843a75 1860EXPORT_SYMBOL(mem_cgroup_end_page_stat);
89c06bd5 1861
cdec2e42
KH
1862/*
1863 * size of first charge trial. "32" comes from vmscan.c's magic value.
1864 * TODO: maybe necessary to use big numbers in big irons.
1865 */
7ec99d62 1866#define CHARGE_BATCH 32U
cdec2e42
KH
1867struct memcg_stock_pcp {
1868 struct mem_cgroup *cached; /* this never be root cgroup */
11c9ea4e 1869 unsigned int nr_pages;
cdec2e42 1870 struct work_struct work;
26fe6168 1871 unsigned long flags;
a0db00fc 1872#define FLUSHING_CACHED_CHARGE 0
cdec2e42
KH
1873};
1874static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
9f50fad6 1875static DEFINE_MUTEX(percpu_charge_mutex);
cdec2e42 1876
a0956d54
SS
1877/**
1878 * consume_stock: Try to consume stocked charge on this cpu.
1879 * @memcg: memcg to consume from.
1880 * @nr_pages: how many pages to charge.
1881 *
1882 * The charges will only happen if @memcg matches the current cpu's memcg
1883 * stock, and at least @nr_pages are available in that stock. Failure to
1884 * service an allocation will refill the stock.
1885 *
1886 * returns true if successful, false otherwise.
cdec2e42 1887 */
a0956d54 1888static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
cdec2e42
KH
1889{
1890 struct memcg_stock_pcp *stock;
3e32cb2e 1891 bool ret = false;
cdec2e42 1892
a0956d54 1893 if (nr_pages > CHARGE_BATCH)
3e32cb2e 1894 return ret;
a0956d54 1895
cdec2e42 1896 stock = &get_cpu_var(memcg_stock);
3e32cb2e 1897 if (memcg == stock->cached && stock->nr_pages >= nr_pages) {
a0956d54 1898 stock->nr_pages -= nr_pages;
3e32cb2e
JW
1899 ret = true;
1900 }
cdec2e42
KH
1901 put_cpu_var(memcg_stock);
1902 return ret;
1903}
1904
1905/*
3e32cb2e 1906 * Returns stocks cached in percpu and reset cached information.
cdec2e42
KH
1907 */
1908static void drain_stock(struct memcg_stock_pcp *stock)
1909{
1910 struct mem_cgroup *old = stock->cached;
1911
11c9ea4e 1912 if (stock->nr_pages) {
3e32cb2e 1913 page_counter_uncharge(&old->memory, stock->nr_pages);
cdec2e42 1914 if (do_swap_account)
3e32cb2e 1915 page_counter_uncharge(&old->memsw, stock->nr_pages);
e8ea14cc 1916 css_put_many(&old->css, stock->nr_pages);
11c9ea4e 1917 stock->nr_pages = 0;
cdec2e42
KH
1918 }
1919 stock->cached = NULL;
cdec2e42
KH
1920}
1921
1922/*
1923 * This must be called under preempt disabled or must be called by
1924 * a thread which is pinned to local cpu.
1925 */
1926static void drain_local_stock(struct work_struct *dummy)
1927{
7c8e0181 1928 struct memcg_stock_pcp *stock = this_cpu_ptr(&memcg_stock);
cdec2e42 1929 drain_stock(stock);
26fe6168 1930 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
cdec2e42
KH
1931}
1932
1933/*
3e32cb2e 1934 * Cache charges(val) to local per_cpu area.
320cc51d 1935 * This will be consumed by consume_stock() function, later.
cdec2e42 1936 */
c0ff4b85 1937static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
cdec2e42
KH
1938{
1939 struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
1940
c0ff4b85 1941 if (stock->cached != memcg) { /* reset if necessary */
cdec2e42 1942 drain_stock(stock);
c0ff4b85 1943 stock->cached = memcg;
cdec2e42 1944 }
11c9ea4e 1945 stock->nr_pages += nr_pages;
cdec2e42
KH
1946 put_cpu_var(memcg_stock);
1947}
1948
1949/*
c0ff4b85 1950 * Drains all per-CPU charge caches for given root_memcg resp. subtree
6d3d6aa2 1951 * of the hierarchy under it.
cdec2e42 1952 */
6d3d6aa2 1953static void drain_all_stock(struct mem_cgroup *root_memcg)
cdec2e42 1954{
26fe6168 1955 int cpu, curcpu;
d38144b7 1956
6d3d6aa2
JW
1957 /* If someone's already draining, avoid adding running more workers. */
1958 if (!mutex_trylock(&percpu_charge_mutex))
1959 return;
cdec2e42 1960 /* Notify other cpus that system-wide "drain" is running */
cdec2e42 1961 get_online_cpus();
5af12d0e 1962 curcpu = get_cpu();
cdec2e42
KH
1963 for_each_online_cpu(cpu) {
1964 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
c0ff4b85 1965 struct mem_cgroup *memcg;
26fe6168 1966
c0ff4b85
R
1967 memcg = stock->cached;
1968 if (!memcg || !stock->nr_pages)
26fe6168 1969 continue;
2314b42d 1970 if (!mem_cgroup_is_descendant(memcg, root_memcg))
3e92041d 1971 continue;
d1a05b69
MH
1972 if (!test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
1973 if (cpu == curcpu)
1974 drain_local_stock(&stock->work);
1975 else
1976 schedule_work_on(cpu, &stock->work);
1977 }
cdec2e42 1978 }
5af12d0e 1979 put_cpu();
f894ffa8 1980 put_online_cpus();
9f50fad6 1981 mutex_unlock(&percpu_charge_mutex);
cdec2e42
KH
1982}
1983
0db0628d 1984static int memcg_cpu_hotplug_callback(struct notifier_block *nb,
cdec2e42
KH
1985 unsigned long action,
1986 void *hcpu)
1987{
1988 int cpu = (unsigned long)hcpu;
1989 struct memcg_stock_pcp *stock;
1990
619d094b 1991 if (action == CPU_ONLINE)
1489ebad 1992 return NOTIFY_OK;
1489ebad 1993
d833049b 1994 if (action != CPU_DEAD && action != CPU_DEAD_FROZEN)
cdec2e42 1995 return NOTIFY_OK;
711d3d2c 1996
cdec2e42
KH
1997 stock = &per_cpu(memcg_stock, cpu);
1998 drain_stock(stock);
1999 return NOTIFY_OK;
2000}
2001
b23afb93
TH
2002/*
2003 * Scheduled by try_charge() to be executed from the userland return path
2004 * and reclaims memory over the high limit.
2005 */
2006void mem_cgroup_handle_over_high(void)
2007{
2008 unsigned int nr_pages = current->memcg_nr_pages_over_high;
2009 struct mem_cgroup *memcg, *pos;
2010
2011 if (likely(!nr_pages))
2012 return;
2013
2014 pos = memcg = get_mem_cgroup_from_mm(current->mm);
2015
2016 do {
2017 if (page_counter_read(&pos->memory) <= pos->high)
2018 continue;
2019 mem_cgroup_events(pos, MEMCG_HIGH, 1);
2020 try_to_free_mem_cgroup_pages(pos, nr_pages, GFP_KERNEL, true);
2021 } while ((pos = parent_mem_cgroup(pos)));
2022
2023 css_put(&memcg->css);
2024 current->memcg_nr_pages_over_high = 0;
2025}
2026
00501b53
JW
2027static int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2028 unsigned int nr_pages)
8a9f3ccd 2029{
7ec99d62 2030 unsigned int batch = max(CHARGE_BATCH, nr_pages);
9b130619 2031 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
6539cc05 2032 struct mem_cgroup *mem_over_limit;
3e32cb2e 2033 struct page_counter *counter;
6539cc05 2034 unsigned long nr_reclaimed;
b70a2a21
JW
2035 bool may_swap = true;
2036 bool drained = false;
a636b327 2037
ce00a967 2038 if (mem_cgroup_is_root(memcg))
10d53c74 2039 return 0;
6539cc05 2040retry:
b6b6cc72 2041 if (consume_stock(memcg, nr_pages))
10d53c74 2042 return 0;
8a9f3ccd 2043
3fbe7244 2044 if (!do_swap_account ||
6071ca52
JW
2045 page_counter_try_charge(&memcg->memsw, batch, &counter)) {
2046 if (page_counter_try_charge(&memcg->memory, batch, &counter))
6539cc05 2047 goto done_restock;
3fbe7244 2048 if (do_swap_account)
3e32cb2e
JW
2049 page_counter_uncharge(&memcg->memsw, batch);
2050 mem_over_limit = mem_cgroup_from_counter(counter, memory);
3fbe7244 2051 } else {
3e32cb2e 2052 mem_over_limit = mem_cgroup_from_counter(counter, memsw);
b70a2a21 2053 may_swap = false;
3fbe7244 2054 }
7a81b88c 2055
6539cc05
JW
2056 if (batch > nr_pages) {
2057 batch = nr_pages;
2058 goto retry;
2059 }
6d61ef40 2060
06b078fc
JW
2061 /*
2062 * Unlike in global OOM situations, memcg is not in a physical
2063 * memory shortage. Allow dying and OOM-killed tasks to
2064 * bypass the last charges so that they can exit quickly and
2065 * free their memory.
2066 */
2067 if (unlikely(test_thread_flag(TIF_MEMDIE) ||
2068 fatal_signal_pending(current) ||
2069 current->flags & PF_EXITING))
10d53c74 2070 goto force;
06b078fc
JW
2071
2072 if (unlikely(task_in_memcg_oom(current)))
2073 goto nomem;
2074
d0164adc 2075 if (!gfpflags_allow_blocking(gfp_mask))
6539cc05 2076 goto nomem;
4b534334 2077
241994ed
JW
2078 mem_cgroup_events(mem_over_limit, MEMCG_MAX, 1);
2079
b70a2a21
JW
2080 nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
2081 gfp_mask, may_swap);
6539cc05 2082
61e02c74 2083 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
6539cc05 2084 goto retry;
28c34c29 2085
b70a2a21 2086 if (!drained) {
6d3d6aa2 2087 drain_all_stock(mem_over_limit);
b70a2a21
JW
2088 drained = true;
2089 goto retry;
2090 }
2091
28c34c29
JW
2092 if (gfp_mask & __GFP_NORETRY)
2093 goto nomem;
6539cc05
JW
2094 /*
2095 * Even though the limit is exceeded at this point, reclaim
2096 * may have been able to free some pages. Retry the charge
2097 * before killing the task.
2098 *
2099 * Only for regular pages, though: huge pages are rather
2100 * unlikely to succeed so close to the limit, and we fall back
2101 * to regular pages anyway in case of failure.
2102 */
61e02c74 2103 if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
6539cc05
JW
2104 goto retry;
2105 /*
2106 * At task move, charge accounts can be doubly counted. So, it's
2107 * better to wait until the end of task_move if something is going on.
2108 */
2109 if (mem_cgroup_wait_acct_move(mem_over_limit))
2110 goto retry;
2111
9b130619
JW
2112 if (nr_retries--)
2113 goto retry;
2114
06b078fc 2115 if (gfp_mask & __GFP_NOFAIL)
10d53c74 2116 goto force;
06b078fc 2117
6539cc05 2118 if (fatal_signal_pending(current))
10d53c74 2119 goto force;
6539cc05 2120
241994ed
JW
2121 mem_cgroup_events(mem_over_limit, MEMCG_OOM, 1);
2122
3608de07
JM
2123 mem_cgroup_oom(mem_over_limit, gfp_mask,
2124 get_order(nr_pages * PAGE_SIZE));
7a81b88c 2125nomem:
6d1fdc48 2126 if (!(gfp_mask & __GFP_NOFAIL))
3168ecbe 2127 return -ENOMEM;
10d53c74
TH
2128force:
2129 /*
2130 * The allocation either can't fail or will lead to more memory
2131 * being freed very soon. Allow memory usage go over the limit
2132 * temporarily by force charging it.
2133 */
2134 page_counter_charge(&memcg->memory, nr_pages);
2135 if (do_swap_account)
2136 page_counter_charge(&memcg->memsw, nr_pages);
2137 css_get_many(&memcg->css, nr_pages);
2138
2139 return 0;
6539cc05
JW
2140
2141done_restock:
e8ea14cc 2142 css_get_many(&memcg->css, batch);
6539cc05
JW
2143 if (batch > nr_pages)
2144 refill_stock(memcg, batch - nr_pages);
b23afb93 2145
241994ed 2146 /*
b23afb93
TH
2147 * If the hierarchy is above the normal consumption range, schedule
2148 * reclaim on returning to userland. We can perform reclaim here
71baba4b 2149 * if __GFP_RECLAIM but let's always punt for simplicity and so that
b23afb93
TH
2150 * GFP_KERNEL can consistently be used during reclaim. @memcg is
2151 * not recorded as it most likely matches current's and won't
2152 * change in the meantime. As high limit is checked again before
2153 * reclaim, the cost of mismatch is negligible.
241994ed
JW
2154 */
2155 do {
b23afb93 2156 if (page_counter_read(&memcg->memory) > memcg->high) {
9516a18a 2157 current->memcg_nr_pages_over_high += batch;
b23afb93
TH
2158 set_notify_resume(current);
2159 break;
2160 }
241994ed 2161 } while ((memcg = parent_mem_cgroup(memcg)));
10d53c74
TH
2162
2163 return 0;
7a81b88c 2164}
8a9f3ccd 2165
00501b53 2166static void cancel_charge(struct mem_cgroup *memcg, unsigned int nr_pages)
a3032a2c 2167{
ce00a967
JW
2168 if (mem_cgroup_is_root(memcg))
2169 return;
2170
3e32cb2e 2171 page_counter_uncharge(&memcg->memory, nr_pages);
05b84301 2172 if (do_swap_account)
3e32cb2e 2173 page_counter_uncharge(&memcg->memsw, nr_pages);
ce00a967 2174
e8ea14cc 2175 css_put_many(&memcg->css, nr_pages);
d01dd17f
KH
2176}
2177
0a31bc97
JW
2178static void lock_page_lru(struct page *page, int *isolated)
2179{
2180 struct zone *zone = page_zone(page);
2181
2182 spin_lock_irq(&zone->lru_lock);
2183 if (PageLRU(page)) {
2184 struct lruvec *lruvec;
2185
2186 lruvec = mem_cgroup_page_lruvec(page, zone);
2187 ClearPageLRU(page);
2188 del_page_from_lru_list(page, lruvec, page_lru(page));
2189 *isolated = 1;
2190 } else
2191 *isolated = 0;
2192}
2193
2194static void unlock_page_lru(struct page *page, int isolated)
2195{
2196 struct zone *zone = page_zone(page);
2197
2198 if (isolated) {
2199 struct lruvec *lruvec;
2200
2201 lruvec = mem_cgroup_page_lruvec(page, zone);
2202 VM_BUG_ON_PAGE(PageLRU(page), page);
2203 SetPageLRU(page);
2204 add_page_to_lru_list(page, lruvec, page_lru(page));
2205 }
2206 spin_unlock_irq(&zone->lru_lock);
2207}
2208
00501b53 2209static void commit_charge(struct page *page, struct mem_cgroup *memcg,
6abb5a86 2210 bool lrucare)
7a81b88c 2211{
0a31bc97 2212 int isolated;
9ce70c02 2213
1306a85a 2214 VM_BUG_ON_PAGE(page->mem_cgroup, page);
9ce70c02
HD
2215
2216 /*
2217 * In some cases, SwapCache and FUSE(splice_buf->radixtree), the page
2218 * may already be on some other mem_cgroup's LRU. Take care of it.
2219 */
0a31bc97
JW
2220 if (lrucare)
2221 lock_page_lru(page, &isolated);
9ce70c02 2222
0a31bc97
JW
2223 /*
2224 * Nobody should be changing or seriously looking at
1306a85a 2225 * page->mem_cgroup at this point:
0a31bc97
JW
2226 *
2227 * - the page is uncharged
2228 *
2229 * - the page is off-LRU
2230 *
2231 * - an anonymous fault has exclusive page access, except for
2232 * a locked page table
2233 *
2234 * - a page cache insertion, a swapin fault, or a migration
2235 * have the page locked
2236 */
1306a85a 2237 page->mem_cgroup = memcg;
9ce70c02 2238
0a31bc97
JW
2239 if (lrucare)
2240 unlock_page_lru(page, isolated);
7a81b88c 2241}
66e1707b 2242
7ae1e1d0 2243#ifdef CONFIG_MEMCG_KMEM
f3bb3043 2244static int memcg_alloc_cache_id(void)
55007d84 2245{
f3bb3043
VD
2246 int id, size;
2247 int err;
2248
dbcf73e2 2249 id = ida_simple_get(&memcg_cache_ida,
f3bb3043
VD
2250 0, MEMCG_CACHES_MAX_SIZE, GFP_KERNEL);
2251 if (id < 0)
2252 return id;
55007d84 2253
dbcf73e2 2254 if (id < memcg_nr_cache_ids)
f3bb3043
VD
2255 return id;
2256
2257 /*
2258 * There's no space for the new id in memcg_caches arrays,
2259 * so we have to grow them.
2260 */
05257a1a 2261 down_write(&memcg_cache_ids_sem);
f3bb3043
VD
2262
2263 size = 2 * (id + 1);
55007d84
GC
2264 if (size < MEMCG_CACHES_MIN_SIZE)
2265 size = MEMCG_CACHES_MIN_SIZE;
2266 else if (size > MEMCG_CACHES_MAX_SIZE)
2267 size = MEMCG_CACHES_MAX_SIZE;
2268
f3bb3043 2269 err = memcg_update_all_caches(size);
60d3fd32
VD
2270 if (!err)
2271 err = memcg_update_all_list_lrus(size);
05257a1a
VD
2272 if (!err)
2273 memcg_nr_cache_ids = size;
2274
2275 up_write(&memcg_cache_ids_sem);
2276
f3bb3043 2277 if (err) {
dbcf73e2 2278 ida_simple_remove(&memcg_cache_ida, id);
f3bb3043
VD
2279 return err;
2280 }
2281 return id;
2282}
2283
2284static void memcg_free_cache_id(int id)
2285{
dbcf73e2 2286 ida_simple_remove(&memcg_cache_ida, id);
55007d84
GC
2287}
2288
d5b3cf71 2289struct memcg_kmem_cache_create_work {
5722d094
VD
2290 struct mem_cgroup *memcg;
2291 struct kmem_cache *cachep;
2292 struct work_struct work;
2293};
2294
d5b3cf71 2295static void memcg_kmem_cache_create_func(struct work_struct *w)
d7f25f8a 2296{
d5b3cf71
VD
2297 struct memcg_kmem_cache_create_work *cw =
2298 container_of(w, struct memcg_kmem_cache_create_work, work);
5722d094
VD
2299 struct mem_cgroup *memcg = cw->memcg;
2300 struct kmem_cache *cachep = cw->cachep;
d7f25f8a 2301
d5b3cf71 2302 memcg_create_kmem_cache(memcg, cachep);
bd673145 2303
5722d094 2304 css_put(&memcg->css);
d7f25f8a
GC
2305 kfree(cw);
2306}
2307
2308/*
2309 * Enqueue the creation of a per-memcg kmem_cache.
d7f25f8a 2310 */
d5b3cf71
VD
2311static void __memcg_schedule_kmem_cache_create(struct mem_cgroup *memcg,
2312 struct kmem_cache *cachep)
d7f25f8a 2313{
d5b3cf71 2314 struct memcg_kmem_cache_create_work *cw;
d7f25f8a 2315
776ed0f0 2316 cw = kmalloc(sizeof(*cw), GFP_NOWAIT);
8135be5a 2317 if (!cw)
d7f25f8a 2318 return;
8135be5a
VD
2319
2320 css_get(&memcg->css);
d7f25f8a
GC
2321
2322 cw->memcg = memcg;
2323 cw->cachep = cachep;
d5b3cf71 2324 INIT_WORK(&cw->work, memcg_kmem_cache_create_func);
d7f25f8a 2325
d7f25f8a
GC
2326 schedule_work(&cw->work);
2327}
2328
d5b3cf71
VD
2329static void memcg_schedule_kmem_cache_create(struct mem_cgroup *memcg,
2330 struct kmem_cache *cachep)
0e9d92f2
GC
2331{
2332 /*
2333 * We need to stop accounting when we kmalloc, because if the
2334 * corresponding kmalloc cache is not yet created, the first allocation
d5b3cf71 2335 * in __memcg_schedule_kmem_cache_create will recurse.
0e9d92f2
GC
2336 *
2337 * However, it is better to enclose the whole function. Depending on
2338 * the debugging options enabled, INIT_WORK(), for instance, can
2339 * trigger an allocation. This too, will make us recurse. Because at
2340 * this point we can't allow ourselves back into memcg_kmem_get_cache,
2341 * the safest choice is to do it like this, wrapping the whole function.
2342 */
6f185c29 2343 current->memcg_kmem_skip_account = 1;
d5b3cf71 2344 __memcg_schedule_kmem_cache_create(memcg, cachep);
6f185c29 2345 current->memcg_kmem_skip_account = 0;
0e9d92f2 2346}
c67a8a68 2347
d7f25f8a
GC
2348/*
2349 * Return the kmem_cache we're supposed to use for a slab allocation.
2350 * We try to use the current memcg's version of the cache.
2351 *
2352 * If the cache does not exist yet, if we are the first user of it,
2353 * we either create it immediately, if possible, or create it asynchronously
2354 * in a workqueue.
2355 * In the latter case, we will let the current allocation go through with
2356 * the original cache.
2357 *
2358 * Can't be called in interrupt context or from kernel threads.
2359 * This function needs to be called with rcu_read_lock() held.
2360 */
056b7cce 2361struct kmem_cache *__memcg_kmem_get_cache(struct kmem_cache *cachep)
d7f25f8a
GC
2362{
2363 struct mem_cgroup *memcg;
959c8963 2364 struct kmem_cache *memcg_cachep;
2a4db7eb 2365 int kmemcg_id;
d7f25f8a 2366
f7ce3190 2367 VM_BUG_ON(!is_root_cache(cachep));
d7f25f8a 2368
9d100c5e 2369 if (current->memcg_kmem_skip_account)
0e9d92f2
GC
2370 return cachep;
2371
8135be5a 2372 memcg = get_mem_cgroup_from_mm(current->mm);
4db0c3c2 2373 kmemcg_id = READ_ONCE(memcg->kmemcg_id);
2a4db7eb 2374 if (kmemcg_id < 0)
ca0dde97 2375 goto out;
d7f25f8a 2376
2a4db7eb 2377 memcg_cachep = cache_from_memcg_idx(cachep, kmemcg_id);
8135be5a
VD
2378 if (likely(memcg_cachep))
2379 return memcg_cachep;
ca0dde97
LZ
2380
2381 /*
2382 * If we are in a safe context (can wait, and not in interrupt
2383 * context), we could be be predictable and return right away.
2384 * This would guarantee that the allocation being performed
2385 * already belongs in the new cache.
2386 *
2387 * However, there are some clashes that can arrive from locking.
2388 * For instance, because we acquire the slab_mutex while doing
776ed0f0
VD
2389 * memcg_create_kmem_cache, this means no further allocation
2390 * could happen with the slab_mutex held. So it's better to
2391 * defer everything.
ca0dde97 2392 */
d5b3cf71 2393 memcg_schedule_kmem_cache_create(memcg, cachep);
ca0dde97 2394out:
8135be5a 2395 css_put(&memcg->css);
ca0dde97 2396 return cachep;
d7f25f8a 2397}
d7f25f8a 2398
8135be5a
VD
2399void __memcg_kmem_put_cache(struct kmem_cache *cachep)
2400{
2401 if (!is_root_cache(cachep))
f7ce3190 2402 css_put(&cachep->memcg_params.memcg->css);
8135be5a
VD
2403}
2404
f3ccb2c4
VD
2405int __memcg_kmem_charge_memcg(struct page *page, gfp_t gfp, int order,
2406 struct mem_cgroup *memcg)
7ae1e1d0 2407{
f3ccb2c4
VD
2408 unsigned int nr_pages = 1 << order;
2409 struct page_counter *counter;
7ae1e1d0
GC
2410 int ret;
2411
f3ccb2c4 2412 if (!memcg_kmem_is_active(memcg))
d05e83a6 2413 return 0;
6d42c232 2414
6071ca52
JW
2415 if (!page_counter_try_charge(&memcg->kmem, nr_pages, &counter))
2416 return -ENOMEM;
7ae1e1d0 2417
f3ccb2c4
VD
2418 ret = try_charge(memcg, gfp, nr_pages);
2419 if (ret) {
2420 page_counter_uncharge(&memcg->kmem, nr_pages);
2421 return ret;
7ae1e1d0
GC
2422 }
2423
f3ccb2c4 2424 page->mem_cgroup = memcg;
7ae1e1d0 2425
f3ccb2c4 2426 return 0;
7ae1e1d0
GC
2427}
2428
f3ccb2c4 2429int __memcg_kmem_charge(struct page *page, gfp_t gfp, int order)
7ae1e1d0 2430{
f3ccb2c4
VD
2431 struct mem_cgroup *memcg;
2432 int ret;
7ae1e1d0 2433
f3ccb2c4
VD
2434 memcg = get_mem_cgroup_from_mm(current->mm);
2435 ret = __memcg_kmem_charge_memcg(page, gfp, order, memcg);
7ae1e1d0 2436 css_put(&memcg->css);
d05e83a6 2437 return ret;
7ae1e1d0
GC
2438}
2439
d05e83a6 2440void __memcg_kmem_uncharge(struct page *page, int order)
7ae1e1d0 2441{
1306a85a 2442 struct mem_cgroup *memcg = page->mem_cgroup;
f3ccb2c4 2443 unsigned int nr_pages = 1 << order;
7ae1e1d0 2444
7ae1e1d0
GC
2445 if (!memcg)
2446 return;
2447
309381fe 2448 VM_BUG_ON_PAGE(mem_cgroup_is_root(memcg), page);
29833315 2449
f3ccb2c4
VD
2450 page_counter_uncharge(&memcg->kmem, nr_pages);
2451 page_counter_uncharge(&memcg->memory, nr_pages);
2452 if (do_swap_account)
2453 page_counter_uncharge(&memcg->memsw, nr_pages);
60d3fd32 2454
1306a85a 2455 page->mem_cgroup = NULL;
f3ccb2c4 2456 css_put_many(&memcg->css, nr_pages);
60d3fd32 2457}
7ae1e1d0
GC
2458#endif /* CONFIG_MEMCG_KMEM */
2459
ca3e0214
KH
2460#ifdef CONFIG_TRANSPARENT_HUGEPAGE
2461
ca3e0214
KH
2462/*
2463 * Because tail pages are not marked as "used", set it. We're under
e94c8a9c
KH
2464 * zone->lru_lock, 'splitting on pmd' and compound_lock.
2465 * charge/uncharge will be never happen and move_account() is done under
2466 * compound_lock(), so we don't have to take care of races.
ca3e0214 2467 */
e94c8a9c 2468void mem_cgroup_split_huge_fixup(struct page *head)
ca3e0214 2469{
e94c8a9c 2470 int i;
ca3e0214 2471
3d37c4a9
KH
2472 if (mem_cgroup_disabled())
2473 return;
b070e65c 2474
29833315 2475 for (i = 1; i < HPAGE_PMD_NR; i++)
1306a85a 2476 head[i].mem_cgroup = head->mem_cgroup;
b9982f8d 2477
1306a85a 2478 __this_cpu_sub(head->mem_cgroup->stat->count[MEM_CGROUP_STAT_RSS_HUGE],
b070e65c 2479 HPAGE_PMD_NR);
ca3e0214 2480}
12d27107 2481#endif /* CONFIG_TRANSPARENT_HUGEPAGE */
ca3e0214 2482
c255a458 2483#ifdef CONFIG_MEMCG_SWAP
0a31bc97
JW
2484static void mem_cgroup_swap_statistics(struct mem_cgroup *memcg,
2485 bool charge)
d13d1443 2486{
0a31bc97
JW
2487 int val = (charge) ? 1 : -1;
2488 this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_SWAP], val);
d13d1443 2489}
02491447
DN
2490
2491/**
2492 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
2493 * @entry: swap entry to be moved
2494 * @from: mem_cgroup which the entry is moved from
2495 * @to: mem_cgroup which the entry is moved to
2496 *
2497 * It succeeds only when the swap_cgroup's record for this entry is the same
2498 * as the mem_cgroup's id of @from.
2499 *
2500 * Returns 0 on success, -EINVAL on failure.
2501 *
3e32cb2e 2502 * The caller must have charged to @to, IOW, called page_counter_charge() about
02491447
DN
2503 * both res and memsw, and called css_get().
2504 */
2505static int mem_cgroup_move_swap_account(swp_entry_t entry,
e91cbb42 2506 struct mem_cgroup *from, struct mem_cgroup *to)
02491447
DN
2507{
2508 unsigned short old_id, new_id;
2509
34c00c31
LZ
2510 old_id = mem_cgroup_id(from);
2511 new_id = mem_cgroup_id(to);
02491447
DN
2512
2513 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
02491447 2514 mem_cgroup_swap_statistics(from, false);
483c30b5 2515 mem_cgroup_swap_statistics(to, true);
02491447
DN
2516 return 0;
2517 }
2518 return -EINVAL;
2519}
2520#else
2521static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
e91cbb42 2522 struct mem_cgroup *from, struct mem_cgroup *to)
02491447
DN
2523{
2524 return -EINVAL;
2525}
8c7c6e34 2526#endif
d13d1443 2527
3e32cb2e 2528static DEFINE_MUTEX(memcg_limit_mutex);
f212ad7c 2529
d38d2a75 2530static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
3e32cb2e 2531 unsigned long limit)
628f4235 2532{
3e32cb2e
JW
2533 unsigned long curusage;
2534 unsigned long oldusage;
2535 bool enlarge = false;
81d39c20 2536 int retry_count;
3e32cb2e 2537 int ret;
81d39c20
KH
2538
2539 /*
2540 * For keeping hierarchical_reclaim simple, how long we should retry
2541 * is depends on callers. We set our retry-count to be function
2542 * of # of children which we should visit in this loop.
2543 */
3e32cb2e
JW
2544 retry_count = MEM_CGROUP_RECLAIM_RETRIES *
2545 mem_cgroup_count_children(memcg);
81d39c20 2546
3e32cb2e 2547 oldusage = page_counter_read(&memcg->memory);
628f4235 2548
3e32cb2e 2549 do {
628f4235
KH
2550 if (signal_pending(current)) {
2551 ret = -EINTR;
2552 break;
2553 }
3e32cb2e
JW
2554
2555 mutex_lock(&memcg_limit_mutex);
2556 if (limit > memcg->memsw.limit) {
2557 mutex_unlock(&memcg_limit_mutex);
8c7c6e34 2558 ret = -EINVAL;
628f4235
KH
2559 break;
2560 }
3e32cb2e
JW
2561 if (limit > memcg->memory.limit)
2562 enlarge = true;
2563 ret = page_counter_limit(&memcg->memory, limit);
2564 mutex_unlock(&memcg_limit_mutex);
8c7c6e34
KH
2565
2566 if (!ret)
2567 break;
2568
b70a2a21
JW
2569 try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL, true);
2570
3e32cb2e 2571 curusage = page_counter_read(&memcg->memory);
81d39c20 2572 /* Usage is reduced ? */
f894ffa8 2573 if (curusage >= oldusage)
81d39c20
KH
2574 retry_count--;
2575 else
2576 oldusage = curusage;
3e32cb2e
JW
2577 } while (retry_count);
2578
3c11ecf4
KH
2579 if (!ret && enlarge)
2580 memcg_oom_recover(memcg);
14797e23 2581
8c7c6e34
KH
2582 return ret;
2583}
2584
338c8431 2585static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
3e32cb2e 2586 unsigned long limit)
8c7c6e34 2587{
3e32cb2e
JW
2588 unsigned long curusage;
2589 unsigned long oldusage;
2590 bool enlarge = false;
81d39c20 2591 int retry_count;
3e32cb2e 2592 int ret;
8c7c6e34 2593
81d39c20 2594 /* see mem_cgroup_resize_res_limit */
3e32cb2e
JW
2595 retry_count = MEM_CGROUP_RECLAIM_RETRIES *
2596 mem_cgroup_count_children(memcg);
2597
2598 oldusage = page_counter_read(&memcg->memsw);
2599
2600 do {
8c7c6e34
KH
2601 if (signal_pending(current)) {
2602 ret = -EINTR;
2603 break;
2604 }
3e32cb2e
JW
2605
2606 mutex_lock(&memcg_limit_mutex);
2607 if (limit < memcg->memory.limit) {
2608 mutex_unlock(&memcg_limit_mutex);
8c7c6e34 2609 ret = -EINVAL;
8c7c6e34
KH
2610 break;
2611 }
3e32cb2e
JW
2612 if (limit > memcg->memsw.limit)
2613 enlarge = true;
2614 ret = page_counter_limit(&memcg->memsw, limit);
2615 mutex_unlock(&memcg_limit_mutex);
8c7c6e34
KH
2616
2617 if (!ret)
2618 break;
2619
b70a2a21
JW
2620 try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL, false);
2621
3e32cb2e 2622 curusage = page_counter_read(&memcg->memsw);
81d39c20 2623 /* Usage is reduced ? */
8c7c6e34 2624 if (curusage >= oldusage)
628f4235 2625 retry_count--;
81d39c20
KH
2626 else
2627 oldusage = curusage;
3e32cb2e
JW
2628 } while (retry_count);
2629
3c11ecf4
KH
2630 if (!ret && enlarge)
2631 memcg_oom_recover(memcg);
3e32cb2e 2632
628f4235
KH
2633 return ret;
2634}
2635
0608f43d
AM
2636unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
2637 gfp_t gfp_mask,
2638 unsigned long *total_scanned)
2639{
2640 unsigned long nr_reclaimed = 0;
2641 struct mem_cgroup_per_zone *mz, *next_mz = NULL;
2642 unsigned long reclaimed;
2643 int loop = 0;
2644 struct mem_cgroup_tree_per_zone *mctz;
3e32cb2e 2645 unsigned long excess;
0608f43d
AM
2646 unsigned long nr_scanned;
2647
2648 if (order > 0)
2649 return 0;
2650
2651 mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone));
2652 /*
2653 * This loop can run a while, specially if mem_cgroup's continuously
2654 * keep exceeding their soft limit and putting the system under
2655 * pressure
2656 */
2657 do {
2658 if (next_mz)
2659 mz = next_mz;
2660 else
2661 mz = mem_cgroup_largest_soft_limit_node(mctz);
2662 if (!mz)
2663 break;
2664
2665 nr_scanned = 0;
2666 reclaimed = mem_cgroup_soft_reclaim(mz->memcg, zone,
2667 gfp_mask, &nr_scanned);
2668 nr_reclaimed += reclaimed;
2669 *total_scanned += nr_scanned;
0a31bc97 2670 spin_lock_irq(&mctz->lock);
bc2f2e7f 2671 __mem_cgroup_remove_exceeded(mz, mctz);
0608f43d
AM
2672
2673 /*
2674 * If we failed to reclaim anything from this memory cgroup
2675 * it is time to move on to the next cgroup
2676 */
2677 next_mz = NULL;
bc2f2e7f
VD
2678 if (!reclaimed)
2679 next_mz = __mem_cgroup_largest_soft_limit_node(mctz);
2680
3e32cb2e 2681 excess = soft_limit_excess(mz->memcg);
0608f43d
AM
2682 /*
2683 * One school of thought says that we should not add
2684 * back the node to the tree if reclaim returns 0.
2685 * But our reclaim could return 0, simply because due
2686 * to priority we are exposing a smaller subset of
2687 * memory to reclaim from. Consider this as a longer
2688 * term TODO.
2689 */
2690 /* If excess == 0, no tree ops */
cf2c8127 2691 __mem_cgroup_insert_exceeded(mz, mctz, excess);
0a31bc97 2692 spin_unlock_irq(&mctz->lock);
0608f43d
AM
2693 css_put(&mz->memcg->css);
2694 loop++;
2695 /*
2696 * Could not reclaim anything and there are no more
2697 * mem cgroups to try or we seem to be looping without
2698 * reclaiming anything.
2699 */
2700 if (!nr_reclaimed &&
2701 (next_mz == NULL ||
2702 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
2703 break;
2704 } while (!nr_reclaimed);
2705 if (next_mz)
2706 css_put(&next_mz->memcg->css);
2707 return nr_reclaimed;
2708}
2709
ea280e7b
TH
2710/*
2711 * Test whether @memcg has children, dead or alive. Note that this
2712 * function doesn't care whether @memcg has use_hierarchy enabled and
2713 * returns %true if there are child csses according to the cgroup
2714 * hierarchy. Testing use_hierarchy is the caller's responsiblity.
2715 */
b5f99b53
GC
2716static inline bool memcg_has_children(struct mem_cgroup *memcg)
2717{
ea280e7b
TH
2718 bool ret;
2719
696ac172 2720 /*
ea280e7b
TH
2721 * The lock does not prevent addition or deletion of children, but
2722 * it prevents a new child from being initialized based on this
2723 * parent in css_online(), so it's enough to decide whether
2724 * hierarchically inherited attributes can still be changed or not.
696ac172 2725 */
ea280e7b
TH
2726 lockdep_assert_held(&memcg_create_mutex);
2727
2728 rcu_read_lock();
2729 ret = css_next_child(NULL, &memcg->css);
2730 rcu_read_unlock();
2731 return ret;
b5f99b53
GC
2732}
2733
c26251f9
MH
2734/*
2735 * Reclaims as many pages from the given memcg as possible and moves
2736 * the rest to the parent.
2737 *
2738 * Caller is responsible for holding css reference for memcg.
2739 */
2740static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
2741{
2742 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
c26251f9 2743
c1e862c1
KH
2744 /* we call try-to-free pages for make this cgroup empty */
2745 lru_add_drain_all();
f817ed48 2746 /* try to free all pages in this cgroup */
3e32cb2e 2747 while (nr_retries && page_counter_read(&memcg->memory)) {
f817ed48 2748 int progress;
c1e862c1 2749
c26251f9
MH
2750 if (signal_pending(current))
2751 return -EINTR;
2752
b70a2a21
JW
2753 progress = try_to_free_mem_cgroup_pages(memcg, 1,
2754 GFP_KERNEL, true);
c1e862c1 2755 if (!progress) {
f817ed48 2756 nr_retries--;
c1e862c1 2757 /* maybe some writeback is necessary */
8aa7e847 2758 congestion_wait(BLK_RW_ASYNC, HZ/10);
c1e862c1 2759 }
f817ed48
KH
2760
2761 }
ab5196c2
MH
2762
2763 return 0;
cc847582
KH
2764}
2765
6770c64e
TH
2766static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
2767 char *buf, size_t nbytes,
2768 loff_t off)
c1e862c1 2769{
6770c64e 2770 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
c26251f9 2771
d8423011
MH
2772 if (mem_cgroup_is_root(memcg))
2773 return -EINVAL;
6770c64e 2774 return mem_cgroup_force_empty(memcg) ?: nbytes;
c1e862c1
KH
2775}
2776
182446d0
TH
2777static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
2778 struct cftype *cft)
18f59ea7 2779{
182446d0 2780 return mem_cgroup_from_css(css)->use_hierarchy;
18f59ea7
BS
2781}
2782
182446d0
TH
2783static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
2784 struct cftype *cft, u64 val)
18f59ea7
BS
2785{
2786 int retval = 0;
182446d0 2787 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5c9d535b 2788 struct mem_cgroup *parent_memcg = mem_cgroup_from_css(memcg->css.parent);
18f59ea7 2789
0999821b 2790 mutex_lock(&memcg_create_mutex);
567fb435
GC
2791
2792 if (memcg->use_hierarchy == val)
2793 goto out;
2794
18f59ea7 2795 /*
af901ca1 2796 * If parent's use_hierarchy is set, we can't make any modifications
18f59ea7
BS
2797 * in the child subtrees. If it is unset, then the change can
2798 * occur, provided the current cgroup has no children.
2799 *
2800 * For the root cgroup, parent_mem is NULL, we allow value to be
2801 * set if there are no children.
2802 */
c0ff4b85 2803 if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
18f59ea7 2804 (val == 1 || val == 0)) {
ea280e7b 2805 if (!memcg_has_children(memcg))
c0ff4b85 2806 memcg->use_hierarchy = val;
18f59ea7
BS
2807 else
2808 retval = -EBUSY;
2809 } else
2810 retval = -EINVAL;
567fb435
GC
2811
2812out:
0999821b 2813 mutex_unlock(&memcg_create_mutex);
18f59ea7
BS
2814
2815 return retval;
2816}
2817
3e32cb2e
JW
2818static unsigned long tree_stat(struct mem_cgroup *memcg,
2819 enum mem_cgroup_stat_index idx)
ce00a967
JW
2820{
2821 struct mem_cgroup *iter;
484ebb3b 2822 unsigned long val = 0;
ce00a967 2823
ce00a967
JW
2824 for_each_mem_cgroup_tree(iter, memcg)
2825 val += mem_cgroup_read_stat(iter, idx);
2826
ce00a967
JW
2827 return val;
2828}
2829
6f646156 2830static unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
ce00a967 2831{
c12176d3 2832 unsigned long val;
ce00a967 2833
3e32cb2e
JW
2834 if (mem_cgroup_is_root(memcg)) {
2835 val = tree_stat(memcg, MEM_CGROUP_STAT_CACHE);
2836 val += tree_stat(memcg, MEM_CGROUP_STAT_RSS);
2837 if (swap)
2838 val += tree_stat(memcg, MEM_CGROUP_STAT_SWAP);
2839 } else {
ce00a967 2840 if (!swap)
3e32cb2e 2841 val = page_counter_read(&memcg->memory);
ce00a967 2842 else
3e32cb2e 2843 val = page_counter_read(&memcg->memsw);
ce00a967 2844 }
c12176d3 2845 return val;
ce00a967
JW
2846}
2847
3e32cb2e
JW
2848enum {
2849 RES_USAGE,
2850 RES_LIMIT,
2851 RES_MAX_USAGE,
2852 RES_FAILCNT,
2853 RES_SOFT_LIMIT,
2854};
ce00a967 2855
791badbd 2856static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
05b84301 2857 struct cftype *cft)
8cdea7c0 2858{
182446d0 2859 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3e32cb2e 2860 struct page_counter *counter;
af36f906 2861
3e32cb2e 2862 switch (MEMFILE_TYPE(cft->private)) {
8c7c6e34 2863 case _MEM:
3e32cb2e
JW
2864 counter = &memcg->memory;
2865 break;
8c7c6e34 2866 case _MEMSWAP:
3e32cb2e
JW
2867 counter = &memcg->memsw;
2868 break;
510fc4e1 2869 case _KMEM:
3e32cb2e 2870 counter = &memcg->kmem;
510fc4e1 2871 break;
8c7c6e34
KH
2872 default:
2873 BUG();
8c7c6e34 2874 }
3e32cb2e
JW
2875
2876 switch (MEMFILE_ATTR(cft->private)) {
2877 case RES_USAGE:
2878 if (counter == &memcg->memory)
c12176d3 2879 return (u64)mem_cgroup_usage(memcg, false) * PAGE_SIZE;
3e32cb2e 2880 if (counter == &memcg->memsw)
c12176d3 2881 return (u64)mem_cgroup_usage(memcg, true) * PAGE_SIZE;
3e32cb2e
JW
2882 return (u64)page_counter_read(counter) * PAGE_SIZE;
2883 case RES_LIMIT:
2884 return (u64)counter->limit * PAGE_SIZE;
2885 case RES_MAX_USAGE:
2886 return (u64)counter->watermark * PAGE_SIZE;
2887 case RES_FAILCNT:
2888 return counter->failcnt;
2889 case RES_SOFT_LIMIT:
2890 return (u64)memcg->soft_limit * PAGE_SIZE;
2891 default:
2892 BUG();
2893 }
8cdea7c0 2894}
510fc4e1 2895
510fc4e1 2896#ifdef CONFIG_MEMCG_KMEM
8c0145b6
VD
2897static int memcg_activate_kmem(struct mem_cgroup *memcg,
2898 unsigned long nr_pages)
d6441637
VD
2899{
2900 int err = 0;
2901 int memcg_id;
2902
2a4db7eb 2903 BUG_ON(memcg->kmemcg_id >= 0);
2788cf0c 2904 BUG_ON(memcg->kmem_acct_activated);
2a4db7eb 2905 BUG_ON(memcg->kmem_acct_active);
d6441637 2906
510fc4e1
GC
2907 /*
2908 * For simplicity, we won't allow this to be disabled. It also can't
2909 * be changed if the cgroup has children already, or if tasks had
2910 * already joined.
2911 *
2912 * If tasks join before we set the limit, a person looking at
2913 * kmem.usage_in_bytes will have no way to determine when it took
2914 * place, which makes the value quite meaningless.
2915 *
2916 * After it first became limited, changes in the value of the limit are
2917 * of course permitted.
510fc4e1 2918 */
0999821b 2919 mutex_lock(&memcg_create_mutex);
27bd4dbb 2920 if (cgroup_is_populated(memcg->css.cgroup) ||
ea280e7b 2921 (memcg->use_hierarchy && memcg_has_children(memcg)))
d6441637
VD
2922 err = -EBUSY;
2923 mutex_unlock(&memcg_create_mutex);
2924 if (err)
2925 goto out;
510fc4e1 2926
f3bb3043 2927 memcg_id = memcg_alloc_cache_id();
d6441637
VD
2928 if (memcg_id < 0) {
2929 err = memcg_id;
2930 goto out;
2931 }
2932
d6441637 2933 /*
900a38f0
VD
2934 * We couldn't have accounted to this cgroup, because it hasn't got
2935 * activated yet, so this should succeed.
d6441637 2936 */
3e32cb2e 2937 err = page_counter_limit(&memcg->kmem, nr_pages);
d6441637
VD
2938 VM_BUG_ON(err);
2939
2940 static_key_slow_inc(&memcg_kmem_enabled_key);
2941 /*
900a38f0
VD
2942 * A memory cgroup is considered kmem-active as soon as it gets
2943 * kmemcg_id. Setting the id after enabling static branching will
d6441637
VD
2944 * guarantee no one starts accounting before all call sites are
2945 * patched.
2946 */
900a38f0 2947 memcg->kmemcg_id = memcg_id;
2788cf0c 2948 memcg->kmem_acct_activated = true;
2a4db7eb 2949 memcg->kmem_acct_active = true;
510fc4e1 2950out:
d6441637 2951 return err;
d6441637
VD
2952}
2953
d6441637 2954static int memcg_update_kmem_limit(struct mem_cgroup *memcg,
3e32cb2e 2955 unsigned long limit)
d6441637
VD
2956{
2957 int ret;
2958
3e32cb2e 2959 mutex_lock(&memcg_limit_mutex);
d6441637 2960 if (!memcg_kmem_is_active(memcg))
3e32cb2e 2961 ret = memcg_activate_kmem(memcg, limit);
d6441637 2962 else
3e32cb2e
JW
2963 ret = page_counter_limit(&memcg->kmem, limit);
2964 mutex_unlock(&memcg_limit_mutex);
510fc4e1
GC
2965 return ret;
2966}
2967
55007d84 2968static int memcg_propagate_kmem(struct mem_cgroup *memcg)
510fc4e1 2969{
55007d84 2970 int ret = 0;
510fc4e1 2971 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
55007d84 2972
d6441637
VD
2973 if (!parent)
2974 return 0;
55007d84 2975
8c0145b6 2976 mutex_lock(&memcg_limit_mutex);
55007d84 2977 /*
d6441637
VD
2978 * If the parent cgroup is not kmem-active now, it cannot be activated
2979 * after this point, because it has at least one child already.
55007d84 2980 */
d6441637 2981 if (memcg_kmem_is_active(parent))
8c0145b6
VD
2982 ret = memcg_activate_kmem(memcg, PAGE_COUNTER_MAX);
2983 mutex_unlock(&memcg_limit_mutex);
55007d84 2984 return ret;
510fc4e1 2985}
d6441637
VD
2986#else
2987static int memcg_update_kmem_limit(struct mem_cgroup *memcg,
3e32cb2e 2988 unsigned long limit)
d6441637
VD
2989{
2990 return -EINVAL;
2991}
6d043990 2992#endif /* CONFIG_MEMCG_KMEM */
510fc4e1 2993
628f4235
KH
2994/*
2995 * The user of this function is...
2996 * RES_LIMIT.
2997 */
451af504
TH
2998static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
2999 char *buf, size_t nbytes, loff_t off)
8cdea7c0 3000{
451af504 3001 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3e32cb2e 3002 unsigned long nr_pages;
628f4235
KH
3003 int ret;
3004
451af504 3005 buf = strstrip(buf);
650c5e56 3006 ret = page_counter_memparse(buf, "-1", &nr_pages);
3e32cb2e
JW
3007 if (ret)
3008 return ret;
af36f906 3009
3e32cb2e 3010 switch (MEMFILE_ATTR(of_cft(of)->private)) {
628f4235 3011 case RES_LIMIT:
4b3bde4c
BS
3012 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3013 ret = -EINVAL;
3014 break;
3015 }
3e32cb2e
JW
3016 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3017 case _MEM:
3018 ret = mem_cgroup_resize_limit(memcg, nr_pages);
8c7c6e34 3019 break;
3e32cb2e
JW
3020 case _MEMSWAP:
3021 ret = mem_cgroup_resize_memsw_limit(memcg, nr_pages);
296c81d8 3022 break;
3e32cb2e
JW
3023 case _KMEM:
3024 ret = memcg_update_kmem_limit(memcg, nr_pages);
3025 break;
3026 }
296c81d8 3027 break;
3e32cb2e
JW
3028 case RES_SOFT_LIMIT:
3029 memcg->soft_limit = nr_pages;
3030 ret = 0;
628f4235
KH
3031 break;
3032 }
451af504 3033 return ret ?: nbytes;
8cdea7c0
BS
3034}
3035
6770c64e
TH
3036static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
3037 size_t nbytes, loff_t off)
c84872e1 3038{
6770c64e 3039 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3e32cb2e 3040 struct page_counter *counter;
c84872e1 3041
3e32cb2e
JW
3042 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3043 case _MEM:
3044 counter = &memcg->memory;
3045 break;
3046 case _MEMSWAP:
3047 counter = &memcg->memsw;
3048 break;
3049 case _KMEM:
3050 counter = &memcg->kmem;
3051 break;
3052 default:
3053 BUG();
3054 }
af36f906 3055
3e32cb2e 3056 switch (MEMFILE_ATTR(of_cft(of)->private)) {
29f2a4da 3057 case RES_MAX_USAGE:
3e32cb2e 3058 page_counter_reset_watermark(counter);
29f2a4da
PE
3059 break;
3060 case RES_FAILCNT:
3e32cb2e 3061 counter->failcnt = 0;
29f2a4da 3062 break;
3e32cb2e
JW
3063 default:
3064 BUG();
29f2a4da 3065 }
f64c3f54 3066
6770c64e 3067 return nbytes;
c84872e1
PE
3068}
3069
182446d0 3070static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
7dc74be0
DN
3071 struct cftype *cft)
3072{
182446d0 3073 return mem_cgroup_from_css(css)->move_charge_at_immigrate;
7dc74be0
DN
3074}
3075
02491447 3076#ifdef CONFIG_MMU
182446d0 3077static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
7dc74be0
DN
3078 struct cftype *cft, u64 val)
3079{
182446d0 3080 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
7dc74be0 3081
1dfab5ab 3082 if (val & ~MOVE_MASK)
7dc74be0 3083 return -EINVAL;
ee5e8472 3084
7dc74be0 3085 /*
ee5e8472
GC
3086 * No kind of locking is needed in here, because ->can_attach() will
3087 * check this value once in the beginning of the process, and then carry
3088 * on with stale data. This means that changes to this value will only
3089 * affect task migrations starting after the change.
7dc74be0 3090 */
c0ff4b85 3091 memcg->move_charge_at_immigrate = val;
7dc74be0
DN
3092 return 0;
3093}
02491447 3094#else
182446d0 3095static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
02491447
DN
3096 struct cftype *cft, u64 val)
3097{
3098 return -ENOSYS;
3099}
3100#endif
7dc74be0 3101
406eb0c9 3102#ifdef CONFIG_NUMA
2da8ca82 3103static int memcg_numa_stat_show(struct seq_file *m, void *v)
406eb0c9 3104{
25485de6
GT
3105 struct numa_stat {
3106 const char *name;
3107 unsigned int lru_mask;
3108 };
3109
3110 static const struct numa_stat stats[] = {
3111 { "total", LRU_ALL },
3112 { "file", LRU_ALL_FILE },
3113 { "anon", LRU_ALL_ANON },
3114 { "unevictable", BIT(LRU_UNEVICTABLE) },
3115 };
3116 const struct numa_stat *stat;
406eb0c9 3117 int nid;
25485de6 3118 unsigned long nr;
2da8ca82 3119 struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
406eb0c9 3120
25485de6
GT
3121 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
3122 nr = mem_cgroup_nr_lru_pages(memcg, stat->lru_mask);
3123 seq_printf(m, "%s=%lu", stat->name, nr);
3124 for_each_node_state(nid, N_MEMORY) {
3125 nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
3126 stat->lru_mask);
3127 seq_printf(m, " N%d=%lu", nid, nr);
3128 }
3129 seq_putc(m, '\n');
406eb0c9 3130 }
406eb0c9 3131
071aee13
YH
3132 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
3133 struct mem_cgroup *iter;
3134
3135 nr = 0;
3136 for_each_mem_cgroup_tree(iter, memcg)
3137 nr += mem_cgroup_nr_lru_pages(iter, stat->lru_mask);
3138 seq_printf(m, "hierarchical_%s=%lu", stat->name, nr);
3139 for_each_node_state(nid, N_MEMORY) {
3140 nr = 0;
3141 for_each_mem_cgroup_tree(iter, memcg)
3142 nr += mem_cgroup_node_nr_lru_pages(
3143 iter, nid, stat->lru_mask);
3144 seq_printf(m, " N%d=%lu", nid, nr);
3145 }
3146 seq_putc(m, '\n');
406eb0c9 3147 }
406eb0c9 3148
406eb0c9
YH
3149 return 0;
3150}
3151#endif /* CONFIG_NUMA */
3152
2da8ca82 3153static int memcg_stat_show(struct seq_file *m, void *v)
d2ceb9b7 3154{
2da8ca82 3155 struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
3e32cb2e 3156 unsigned long memory, memsw;
af7c4b0e
JW
3157 struct mem_cgroup *mi;
3158 unsigned int i;
406eb0c9 3159
0ca44b14
GT
3160 BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_stat_names) !=
3161 MEM_CGROUP_STAT_NSTATS);
3162 BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_events_names) !=
3163 MEM_CGROUP_EVENTS_NSTATS);
70bc068c
RS
3164 BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_lru_names) != NR_LRU_LISTS);
3165
af7c4b0e 3166 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
bff6bb83 3167 if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
1dd3a273 3168 continue;
484ebb3b 3169 seq_printf(m, "%s %lu\n", mem_cgroup_stat_names[i],
af7c4b0e 3170 mem_cgroup_read_stat(memcg, i) * PAGE_SIZE);
1dd3a273 3171 }
7b854121 3172
af7c4b0e
JW
3173 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++)
3174 seq_printf(m, "%s %lu\n", mem_cgroup_events_names[i],
3175 mem_cgroup_read_events(memcg, i));
3176
3177 for (i = 0; i < NR_LRU_LISTS; i++)
3178 seq_printf(m, "%s %lu\n", mem_cgroup_lru_names[i],
3179 mem_cgroup_nr_lru_pages(memcg, BIT(i)) * PAGE_SIZE);
3180
14067bb3 3181 /* Hierarchical information */
3e32cb2e
JW
3182 memory = memsw = PAGE_COUNTER_MAX;
3183 for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
3184 memory = min(memory, mi->memory.limit);
3185 memsw = min(memsw, mi->memsw.limit);
fee7b548 3186 }
3e32cb2e
JW
3187 seq_printf(m, "hierarchical_memory_limit %llu\n",
3188 (u64)memory * PAGE_SIZE);
3189 if (do_swap_account)
3190 seq_printf(m, "hierarchical_memsw_limit %llu\n",
3191 (u64)memsw * PAGE_SIZE);
7f016ee8 3192
af7c4b0e 3193 for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
484ebb3b 3194 unsigned long long val = 0;
af7c4b0e 3195
bff6bb83 3196 if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
1dd3a273 3197 continue;
af7c4b0e
JW
3198 for_each_mem_cgroup_tree(mi, memcg)
3199 val += mem_cgroup_read_stat(mi, i) * PAGE_SIZE;
484ebb3b 3200 seq_printf(m, "total_%s %llu\n", mem_cgroup_stat_names[i], val);
af7c4b0e
JW
3201 }
3202
3203 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
3204 unsigned long long val = 0;
3205
3206 for_each_mem_cgroup_tree(mi, memcg)
3207 val += mem_cgroup_read_events(mi, i);
3208 seq_printf(m, "total_%s %llu\n",
3209 mem_cgroup_events_names[i], val);
3210 }
3211
3212 for (i = 0; i < NR_LRU_LISTS; i++) {
3213 unsigned long long val = 0;
3214
3215 for_each_mem_cgroup_tree(mi, memcg)
3216 val += mem_cgroup_nr_lru_pages(mi, BIT(i)) * PAGE_SIZE;
3217 seq_printf(m, "total_%s %llu\n", mem_cgroup_lru_names[i], val);
1dd3a273 3218 }
14067bb3 3219
7f016ee8 3220#ifdef CONFIG_DEBUG_VM
7f016ee8
KM
3221 {
3222 int nid, zid;
3223 struct mem_cgroup_per_zone *mz;
89abfab1 3224 struct zone_reclaim_stat *rstat;
7f016ee8
KM
3225 unsigned long recent_rotated[2] = {0, 0};
3226 unsigned long recent_scanned[2] = {0, 0};
3227
3228 for_each_online_node(nid)
3229 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
e231875b 3230 mz = &memcg->nodeinfo[nid]->zoneinfo[zid];
89abfab1 3231 rstat = &mz->lruvec.reclaim_stat;
7f016ee8 3232
89abfab1
HD
3233 recent_rotated[0] += rstat->recent_rotated[0];
3234 recent_rotated[1] += rstat->recent_rotated[1];
3235 recent_scanned[0] += rstat->recent_scanned[0];
3236 recent_scanned[1] += rstat->recent_scanned[1];
7f016ee8 3237 }
78ccf5b5
JW
3238 seq_printf(m, "recent_rotated_anon %lu\n", recent_rotated[0]);
3239 seq_printf(m, "recent_rotated_file %lu\n", recent_rotated[1]);
3240 seq_printf(m, "recent_scanned_anon %lu\n", recent_scanned[0]);
3241 seq_printf(m, "recent_scanned_file %lu\n", recent_scanned[1]);
7f016ee8
KM
3242 }
3243#endif
3244
d2ceb9b7
KH
3245 return 0;
3246}
3247
182446d0
TH
3248static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
3249 struct cftype *cft)
a7885eb8 3250{
182446d0 3251 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
a7885eb8 3252
1f4c025b 3253 return mem_cgroup_swappiness(memcg);
a7885eb8
KM
3254}
3255
182446d0
TH
3256static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
3257 struct cftype *cft, u64 val)
a7885eb8 3258{
182446d0 3259 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
a7885eb8 3260
3dae7fec 3261 if (val > 100)
a7885eb8
KM
3262 return -EINVAL;
3263
14208b0e 3264 if (css->parent)
3dae7fec
JW
3265 memcg->swappiness = val;
3266 else
3267 vm_swappiness = val;
068b38c1 3268
a7885eb8
KM
3269 return 0;
3270}
3271
2e72b634
KS
3272static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
3273{
3274 struct mem_cgroup_threshold_ary *t;
3e32cb2e 3275 unsigned long usage;
2e72b634
KS
3276 int i;
3277
3278 rcu_read_lock();
3279 if (!swap)
2c488db2 3280 t = rcu_dereference(memcg->thresholds.primary);
2e72b634 3281 else
2c488db2 3282 t = rcu_dereference(memcg->memsw_thresholds.primary);
2e72b634
KS
3283
3284 if (!t)
3285 goto unlock;
3286
ce00a967 3287 usage = mem_cgroup_usage(memcg, swap);
2e72b634
KS
3288
3289 /*
748dad36 3290 * current_threshold points to threshold just below or equal to usage.
2e72b634
KS
3291 * If it's not true, a threshold was crossed after last
3292 * call of __mem_cgroup_threshold().
3293 */
5407a562 3294 i = t->current_threshold;
2e72b634
KS
3295
3296 /*
3297 * Iterate backward over array of thresholds starting from
3298 * current_threshold and check if a threshold is crossed.
3299 * If none of thresholds below usage is crossed, we read
3300 * only one element of the array here.
3301 */
3302 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
3303 eventfd_signal(t->entries[i].eventfd, 1);
3304
3305 /* i = current_threshold + 1 */
3306 i++;
3307
3308 /*
3309 * Iterate forward over array of thresholds starting from
3310 * current_threshold+1 and check if a threshold is crossed.
3311 * If none of thresholds above usage is crossed, we read
3312 * only one element of the array here.
3313 */
3314 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
3315 eventfd_signal(t->entries[i].eventfd, 1);
3316
3317 /* Update current_threshold */
5407a562 3318 t->current_threshold = i - 1;
2e72b634
KS
3319unlock:
3320 rcu_read_unlock();
3321}
3322
3323static void mem_cgroup_threshold(struct mem_cgroup *memcg)
3324{
ad4ca5f4
KS
3325 while (memcg) {
3326 __mem_cgroup_threshold(memcg, false);
3327 if (do_swap_account)
3328 __mem_cgroup_threshold(memcg, true);
3329
3330 memcg = parent_mem_cgroup(memcg);
3331 }
2e72b634
KS
3332}
3333
3334static int compare_thresholds(const void *a, const void *b)
3335{
3336 const struct mem_cgroup_threshold *_a = a;
3337 const struct mem_cgroup_threshold *_b = b;
3338
2bff24a3
GT
3339 if (_a->threshold > _b->threshold)
3340 return 1;
3341
3342 if (_a->threshold < _b->threshold)
3343 return -1;
3344
3345 return 0;
2e72b634
KS
3346}
3347
c0ff4b85 3348static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
9490ff27
KH
3349{
3350 struct mem_cgroup_eventfd_list *ev;
3351
2bcf2e92
MH
3352 spin_lock(&memcg_oom_lock);
3353
c0ff4b85 3354 list_for_each_entry(ev, &memcg->oom_notify, list)
9490ff27 3355 eventfd_signal(ev->eventfd, 1);
2bcf2e92
MH
3356
3357 spin_unlock(&memcg_oom_lock);
9490ff27
KH
3358 return 0;
3359}
3360
c0ff4b85 3361static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
9490ff27 3362{
7d74b06f
KH
3363 struct mem_cgroup *iter;
3364
c0ff4b85 3365 for_each_mem_cgroup_tree(iter, memcg)
7d74b06f 3366 mem_cgroup_oom_notify_cb(iter);
9490ff27
KH
3367}
3368
59b6f873 3369static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
347c4a87 3370 struct eventfd_ctx *eventfd, const char *args, enum res_type type)
2e72b634 3371{
2c488db2
KS
3372 struct mem_cgroup_thresholds *thresholds;
3373 struct mem_cgroup_threshold_ary *new;
3e32cb2e
JW
3374 unsigned long threshold;
3375 unsigned long usage;
2c488db2 3376 int i, size, ret;
2e72b634 3377
650c5e56 3378 ret = page_counter_memparse(args, "-1", &threshold);
2e72b634
KS
3379 if (ret)
3380 return ret;
3381
3382 mutex_lock(&memcg->thresholds_lock);
2c488db2 3383
05b84301 3384 if (type == _MEM) {
2c488db2 3385 thresholds = &memcg->thresholds;
ce00a967 3386 usage = mem_cgroup_usage(memcg, false);
05b84301 3387 } else if (type == _MEMSWAP) {
2c488db2 3388 thresholds = &memcg->memsw_thresholds;
ce00a967 3389 usage = mem_cgroup_usage(memcg, true);
05b84301 3390 } else
2e72b634
KS
3391 BUG();
3392
2e72b634 3393 /* Check if a threshold crossed before adding a new one */
2c488db2 3394 if (thresholds->primary)
2e72b634
KS
3395 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
3396
2c488db2 3397 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
2e72b634
KS
3398
3399 /* Allocate memory for new array of thresholds */
2c488db2 3400 new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
2e72b634 3401 GFP_KERNEL);
2c488db2 3402 if (!new) {
2e72b634
KS
3403 ret = -ENOMEM;
3404 goto unlock;
3405 }
2c488db2 3406 new->size = size;
2e72b634
KS
3407
3408 /* Copy thresholds (if any) to new array */
2c488db2
KS
3409 if (thresholds->primary) {
3410 memcpy(new->entries, thresholds->primary->entries, (size - 1) *
2e72b634 3411 sizeof(struct mem_cgroup_threshold));
2c488db2
KS
3412 }
3413
2e72b634 3414 /* Add new threshold */
2c488db2
KS
3415 new->entries[size - 1].eventfd = eventfd;
3416 new->entries[size - 1].threshold = threshold;
2e72b634
KS
3417
3418 /* Sort thresholds. Registering of new threshold isn't time-critical */
2c488db2 3419 sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
2e72b634
KS
3420 compare_thresholds, NULL);
3421
3422 /* Find current threshold */
2c488db2 3423 new->current_threshold = -1;
2e72b634 3424 for (i = 0; i < size; i++) {
748dad36 3425 if (new->entries[i].threshold <= usage) {
2e72b634 3426 /*
2c488db2
KS
3427 * new->current_threshold will not be used until
3428 * rcu_assign_pointer(), so it's safe to increment
2e72b634
KS
3429 * it here.
3430 */
2c488db2 3431 ++new->current_threshold;
748dad36
SZ
3432 } else
3433 break;
2e72b634
KS
3434 }
3435
2c488db2
KS
3436 /* Free old spare buffer and save old primary buffer as spare */
3437 kfree(thresholds->spare);
3438 thresholds->spare = thresholds->primary;
3439
3440 rcu_assign_pointer(thresholds->primary, new);
2e72b634 3441
907860ed 3442 /* To be sure that nobody uses thresholds */
2e72b634
KS
3443 synchronize_rcu();
3444
2e72b634
KS
3445unlock:
3446 mutex_unlock(&memcg->thresholds_lock);
3447
3448 return ret;
3449}
3450
59b6f873 3451static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
347c4a87
TH
3452 struct eventfd_ctx *eventfd, const char *args)
3453{
59b6f873 3454 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
347c4a87
TH
3455}
3456
59b6f873 3457static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
347c4a87
TH
3458 struct eventfd_ctx *eventfd, const char *args)
3459{
59b6f873 3460 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
347c4a87
TH
3461}
3462
59b6f873 3463static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
347c4a87 3464 struct eventfd_ctx *eventfd, enum res_type type)
2e72b634 3465{
2c488db2
KS
3466 struct mem_cgroup_thresholds *thresholds;
3467 struct mem_cgroup_threshold_ary *new;
3e32cb2e 3468 unsigned long usage;
2c488db2 3469 int i, j, size;
2e72b634
KS
3470
3471 mutex_lock(&memcg->thresholds_lock);
05b84301
JW
3472
3473 if (type == _MEM) {
2c488db2 3474 thresholds = &memcg->thresholds;
ce00a967 3475 usage = mem_cgroup_usage(memcg, false);
05b84301 3476 } else if (type == _MEMSWAP) {
2c488db2 3477 thresholds = &memcg->memsw_thresholds;
ce00a967 3478 usage = mem_cgroup_usage(memcg, true);
05b84301 3479 } else
2e72b634
KS
3480 BUG();
3481
371528ca
AV
3482 if (!thresholds->primary)
3483 goto unlock;
3484
2e72b634
KS
3485 /* Check if a threshold crossed before removing */
3486 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
3487
3488 /* Calculate new number of threshold */
2c488db2
KS
3489 size = 0;
3490 for (i = 0; i < thresholds->primary->size; i++) {
3491 if (thresholds->primary->entries[i].eventfd != eventfd)
2e72b634
KS
3492 size++;
3493 }
3494
2c488db2 3495 new = thresholds->spare;
907860ed 3496
2e72b634
KS
3497 /* Set thresholds array to NULL if we don't have thresholds */
3498 if (!size) {
2c488db2
KS
3499 kfree(new);
3500 new = NULL;
907860ed 3501 goto swap_buffers;
2e72b634
KS
3502 }
3503
2c488db2 3504 new->size = size;
2e72b634
KS
3505
3506 /* Copy thresholds and find current threshold */
2c488db2
KS
3507 new->current_threshold = -1;
3508 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
3509 if (thresholds->primary->entries[i].eventfd == eventfd)
2e72b634
KS
3510 continue;
3511
2c488db2 3512 new->entries[j] = thresholds->primary->entries[i];
748dad36 3513 if (new->entries[j].threshold <= usage) {
2e72b634 3514 /*
2c488db2 3515 * new->current_threshold will not be used
2e72b634
KS
3516 * until rcu_assign_pointer(), so it's safe to increment
3517 * it here.
3518 */
2c488db2 3519 ++new->current_threshold;
2e72b634
KS
3520 }
3521 j++;
3522 }
3523
907860ed 3524swap_buffers:
2c488db2
KS
3525 /* Swap primary and spare array */
3526 thresholds->spare = thresholds->primary;
8c757763 3527
2c488db2 3528 rcu_assign_pointer(thresholds->primary, new);
2e72b634 3529
907860ed 3530 /* To be sure that nobody uses thresholds */
2e72b634 3531 synchronize_rcu();
ececa3eb
MC
3532
3533 /* If all events are unregistered, free the spare array */
3534 if (!new) {
3535 kfree(thresholds->spare);
3536 thresholds->spare = NULL;
3537 }
371528ca 3538unlock:
2e72b634 3539 mutex_unlock(&memcg->thresholds_lock);
2e72b634 3540}
c1e862c1 3541
59b6f873 3542static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
347c4a87
TH
3543 struct eventfd_ctx *eventfd)
3544{
59b6f873 3545 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
347c4a87
TH
3546}
3547
59b6f873 3548static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
347c4a87
TH
3549 struct eventfd_ctx *eventfd)
3550{
59b6f873 3551 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
347c4a87
TH
3552}
3553
59b6f873 3554static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
347c4a87 3555 struct eventfd_ctx *eventfd, const char *args)
9490ff27 3556{
9490ff27 3557 struct mem_cgroup_eventfd_list *event;
9490ff27 3558
9490ff27
KH
3559 event = kmalloc(sizeof(*event), GFP_KERNEL);
3560 if (!event)
3561 return -ENOMEM;
3562
1af8efe9 3563 spin_lock(&memcg_oom_lock);
9490ff27
KH
3564
3565 event->eventfd = eventfd;
3566 list_add(&event->list, &memcg->oom_notify);
3567
3568 /* already in OOM ? */
c2b42d3c 3569 if (memcg->under_oom)
9490ff27 3570 eventfd_signal(eventfd, 1);
1af8efe9 3571 spin_unlock(&memcg_oom_lock);
9490ff27
KH
3572
3573 return 0;
3574}
3575
59b6f873 3576static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
347c4a87 3577 struct eventfd_ctx *eventfd)
9490ff27 3578{
9490ff27 3579 struct mem_cgroup_eventfd_list *ev, *tmp;
9490ff27 3580
1af8efe9 3581 spin_lock(&memcg_oom_lock);
9490ff27 3582
c0ff4b85 3583 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
9490ff27
KH
3584 if (ev->eventfd == eventfd) {
3585 list_del(&ev->list);
3586 kfree(ev);
3587 }
3588 }
3589
1af8efe9 3590 spin_unlock(&memcg_oom_lock);
9490ff27
KH
3591}
3592
2da8ca82 3593static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
3c11ecf4 3594{
2da8ca82 3595 struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(sf));
3c11ecf4 3596
791badbd 3597 seq_printf(sf, "oom_kill_disable %d\n", memcg->oom_kill_disable);
c2b42d3c 3598 seq_printf(sf, "under_oom %d\n", (bool)memcg->under_oom);
3c11ecf4
KH
3599 return 0;
3600}
3601
182446d0 3602static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
3c11ecf4
KH
3603 struct cftype *cft, u64 val)
3604{
182446d0 3605 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3c11ecf4
KH
3606
3607 /* cannot set to root cgroup and only 0 and 1 are allowed */
14208b0e 3608 if (!css->parent || !((val == 0) || (val == 1)))
3c11ecf4
KH
3609 return -EINVAL;
3610
c0ff4b85 3611 memcg->oom_kill_disable = val;
4d845ebf 3612 if (!val)
c0ff4b85 3613 memcg_oom_recover(memcg);
3dae7fec 3614
3c11ecf4
KH
3615 return 0;
3616}
3617
c255a458 3618#ifdef CONFIG_MEMCG_KMEM
cbe128e3 3619static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
e5671dfa 3620{
55007d84
GC
3621 int ret;
3622
55007d84
GC
3623 ret = memcg_propagate_kmem(memcg);
3624 if (ret)
3625 return ret;
2633d7a0 3626
1d62e436 3627 return mem_cgroup_sockets_init(memcg, ss);
573b400d 3628}
e5671dfa 3629
2a4db7eb
VD
3630static void memcg_deactivate_kmem(struct mem_cgroup *memcg)
3631{
2788cf0c
VD
3632 struct cgroup_subsys_state *css;
3633 struct mem_cgroup *parent, *child;
3634 int kmemcg_id;
3635
2a4db7eb
VD
3636 if (!memcg->kmem_acct_active)
3637 return;
3638
3639 /*
3640 * Clear the 'active' flag before clearing memcg_caches arrays entries.
3641 * Since we take the slab_mutex in memcg_deactivate_kmem_caches(), it
3642 * guarantees no cache will be created for this cgroup after we are
3643 * done (see memcg_create_kmem_cache()).
3644 */
3645 memcg->kmem_acct_active = false;
3646
3647 memcg_deactivate_kmem_caches(memcg);
2788cf0c
VD
3648
3649 kmemcg_id = memcg->kmemcg_id;
3650 BUG_ON(kmemcg_id < 0);
3651
3652 parent = parent_mem_cgroup(memcg);
3653 if (!parent)
3654 parent = root_mem_cgroup;
3655
3656 /*
3657 * Change kmemcg_id of this cgroup and all its descendants to the
3658 * parent's id, and then move all entries from this cgroup's list_lrus
3659 * to ones of the parent. After we have finished, all list_lrus
3660 * corresponding to this cgroup are guaranteed to remain empty. The
3661 * ordering is imposed by list_lru_node->lock taken by
3662 * memcg_drain_all_list_lrus().
3663 */
3664 css_for_each_descendant_pre(css, &memcg->css) {
3665 child = mem_cgroup_from_css(css);
3666 BUG_ON(child->kmemcg_id != kmemcg_id);
3667 child->kmemcg_id = parent->kmemcg_id;
3668 if (!memcg->use_hierarchy)
3669 break;
3670 }
3671 memcg_drain_all_list_lrus(kmemcg_id, parent->kmemcg_id);
3672
3673 memcg_free_cache_id(kmemcg_id);
2a4db7eb
VD
3674}
3675
10d5ebf4 3676static void memcg_destroy_kmem(struct mem_cgroup *memcg)
d1a4c0b3 3677{
f48b80a5
VD
3678 if (memcg->kmem_acct_activated) {
3679 memcg_destroy_kmem_caches(memcg);
3680 static_key_slow_dec(&memcg_kmem_enabled_key);
3681 WARN_ON(page_counter_read(&memcg->kmem));
3682 }
1d62e436 3683 mem_cgroup_sockets_destroy(memcg);
10d5ebf4 3684}
e5671dfa 3685#else
cbe128e3 3686static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
e5671dfa
GC
3687{
3688 return 0;
3689}
d1a4c0b3 3690
2a4db7eb
VD
3691static void memcg_deactivate_kmem(struct mem_cgroup *memcg)
3692{
3693}
3694
10d5ebf4
LZ
3695static void memcg_destroy_kmem(struct mem_cgroup *memcg)
3696{
3697}
e5671dfa
GC
3698#endif
3699
52ebea74
TH
3700#ifdef CONFIG_CGROUP_WRITEBACK
3701
3702struct list_head *mem_cgroup_cgwb_list(struct mem_cgroup *memcg)
3703{
3704 return &memcg->cgwb_list;
3705}
3706
841710aa
TH
3707static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
3708{
3709 return wb_domain_init(&memcg->cgwb_domain, gfp);
3710}
3711
3712static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
3713{
3714 wb_domain_exit(&memcg->cgwb_domain);
3715}
3716
2529bb3a
TH
3717static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
3718{
3719 wb_domain_size_changed(&memcg->cgwb_domain);
3720}
3721
841710aa
TH
3722struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb)
3723{
3724 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
3725
3726 if (!memcg->css.parent)
3727 return NULL;
3728
3729 return &memcg->cgwb_domain;
3730}
3731
c2aa723a
TH
3732/**
3733 * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
3734 * @wb: bdi_writeback in question
c5edf9cd
TH
3735 * @pfilepages: out parameter for number of file pages
3736 * @pheadroom: out parameter for number of allocatable pages according to memcg
c2aa723a
TH
3737 * @pdirty: out parameter for number of dirty pages
3738 * @pwriteback: out parameter for number of pages under writeback
3739 *
c5edf9cd
TH
3740 * Determine the numbers of file, headroom, dirty, and writeback pages in
3741 * @wb's memcg. File, dirty and writeback are self-explanatory. Headroom
3742 * is a bit more involved.
c2aa723a 3743 *
c5edf9cd
TH
3744 * A memcg's headroom is "min(max, high) - used". In the hierarchy, the
3745 * headroom is calculated as the lowest headroom of itself and the
3746 * ancestors. Note that this doesn't consider the actual amount of
3747 * available memory in the system. The caller should further cap
3748 * *@pheadroom accordingly.
c2aa723a 3749 */
c5edf9cd
TH
3750void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages,
3751 unsigned long *pheadroom, unsigned long *pdirty,
3752 unsigned long *pwriteback)
c2aa723a
TH
3753{
3754 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
3755 struct mem_cgroup *parent;
c2aa723a
TH
3756
3757 *pdirty = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_DIRTY);
3758
3759 /* this should eventually include NR_UNSTABLE_NFS */
3760 *pwriteback = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_WRITEBACK);
c5edf9cd
TH
3761 *pfilepages = mem_cgroup_nr_lru_pages(memcg, (1 << LRU_INACTIVE_FILE) |
3762 (1 << LRU_ACTIVE_FILE));
3763 *pheadroom = PAGE_COUNTER_MAX;
c2aa723a 3764
c2aa723a
TH
3765 while ((parent = parent_mem_cgroup(memcg))) {
3766 unsigned long ceiling = min(memcg->memory.limit, memcg->high);
3767 unsigned long used = page_counter_read(&memcg->memory);
3768
c5edf9cd 3769 *pheadroom = min(*pheadroom, ceiling - min(ceiling, used));
c2aa723a
TH
3770 memcg = parent;
3771 }
c2aa723a
TH
3772}
3773
841710aa
TH
3774#else /* CONFIG_CGROUP_WRITEBACK */
3775
3776static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
3777{
3778 return 0;
3779}
3780
3781static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
3782{
3783}
3784
2529bb3a
TH
3785static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
3786{
3787}
3788
52ebea74
TH
3789#endif /* CONFIG_CGROUP_WRITEBACK */
3790
3bc942f3
TH
3791/*
3792 * DO NOT USE IN NEW FILES.
3793 *
3794 * "cgroup.event_control" implementation.
3795 *
3796 * This is way over-engineered. It tries to support fully configurable
3797 * events for each user. Such level of flexibility is completely
3798 * unnecessary especially in the light of the planned unified hierarchy.
3799 *
3800 * Please deprecate this and replace with something simpler if at all
3801 * possible.
3802 */
3803
79bd9814
TH
3804/*
3805 * Unregister event and free resources.
3806 *
3807 * Gets called from workqueue.
3808 */
3bc942f3 3809static void memcg_event_remove(struct work_struct *work)
79bd9814 3810{
3bc942f3
TH
3811 struct mem_cgroup_event *event =
3812 container_of(work, struct mem_cgroup_event, remove);
59b6f873 3813 struct mem_cgroup *memcg = event->memcg;
79bd9814
TH
3814
3815 remove_wait_queue(event->wqh, &event->wait);
3816
59b6f873 3817 event->unregister_event(memcg, event->eventfd);
79bd9814
TH
3818
3819 /* Notify userspace the event is going away. */
3820 eventfd_signal(event->eventfd, 1);
3821
3822 eventfd_ctx_put(event->eventfd);
3823 kfree(event);
59b6f873 3824 css_put(&memcg->css);
79bd9814
TH
3825}
3826
3827/*
3828 * Gets called on POLLHUP on eventfd when user closes it.
3829 *
3830 * Called with wqh->lock held and interrupts disabled.
3831 */
3bc942f3
TH
3832static int memcg_event_wake(wait_queue_t *wait, unsigned mode,
3833 int sync, void *key)
79bd9814 3834{
3bc942f3
TH
3835 struct mem_cgroup_event *event =
3836 container_of(wait, struct mem_cgroup_event, wait);
59b6f873 3837 struct mem_cgroup *memcg = event->memcg;
79bd9814
TH
3838 unsigned long flags = (unsigned long)key;
3839
3840 if (flags & POLLHUP) {
3841 /*
3842 * If the event has been detached at cgroup removal, we
3843 * can simply return knowing the other side will cleanup
3844 * for us.
3845 *
3846 * We can't race against event freeing since the other
3847 * side will require wqh->lock via remove_wait_queue(),
3848 * which we hold.
3849 */
fba94807 3850 spin_lock(&memcg->event_list_lock);
79bd9814
TH
3851 if (!list_empty(&event->list)) {
3852 list_del_init(&event->list);
3853 /*
3854 * We are in atomic context, but cgroup_event_remove()
3855 * may sleep, so we have to call it in workqueue.
3856 */
3857 schedule_work(&event->remove);
3858 }
fba94807 3859 spin_unlock(&memcg->event_list_lock);
79bd9814
TH
3860 }
3861
3862 return 0;
3863}
3864
3bc942f3 3865static void memcg_event_ptable_queue_proc(struct file *file,
79bd9814
TH
3866 wait_queue_head_t *wqh, poll_table *pt)
3867{
3bc942f3
TH
3868 struct mem_cgroup_event *event =
3869 container_of(pt, struct mem_cgroup_event, pt);
79bd9814
TH
3870
3871 event->wqh = wqh;
3872 add_wait_queue(wqh, &event->wait);
3873}
3874
3875/*
3bc942f3
TH
3876 * DO NOT USE IN NEW FILES.
3877 *
79bd9814
TH
3878 * Parse input and register new cgroup event handler.
3879 *
3880 * Input must be in format '<event_fd> <control_fd> <args>'.
3881 * Interpretation of args is defined by control file implementation.
3882 */
451af504
TH
3883static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
3884 char *buf, size_t nbytes, loff_t off)
79bd9814 3885{
451af504 3886 struct cgroup_subsys_state *css = of_css(of);
fba94807 3887 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3bc942f3 3888 struct mem_cgroup_event *event;
79bd9814
TH
3889 struct cgroup_subsys_state *cfile_css;
3890 unsigned int efd, cfd;
3891 struct fd efile;
3892 struct fd cfile;
fba94807 3893 const char *name;
79bd9814
TH
3894 char *endp;
3895 int ret;
3896
451af504
TH
3897 buf = strstrip(buf);
3898
3899 efd = simple_strtoul(buf, &endp, 10);
79bd9814
TH
3900 if (*endp != ' ')
3901 return -EINVAL;
451af504 3902 buf = endp + 1;
79bd9814 3903
451af504 3904 cfd = simple_strtoul(buf, &endp, 10);
79bd9814
TH
3905 if ((*endp != ' ') && (*endp != '\0'))
3906 return -EINVAL;
451af504 3907 buf = endp + 1;
79bd9814
TH
3908
3909 event = kzalloc(sizeof(*event), GFP_KERNEL);
3910 if (!event)
3911 return -ENOMEM;
3912
59b6f873 3913 event->memcg = memcg;
79bd9814 3914 INIT_LIST_HEAD(&event->list);
3bc942f3
TH
3915 init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
3916 init_waitqueue_func_entry(&event->wait, memcg_event_wake);
3917 INIT_WORK(&event->remove, memcg_event_remove);
79bd9814
TH
3918
3919 efile = fdget(efd);
3920 if (!efile.file) {
3921 ret = -EBADF;
3922 goto out_kfree;
3923 }
3924
3925 event->eventfd = eventfd_ctx_fileget(efile.file);
3926 if (IS_ERR(event->eventfd)) {
3927 ret = PTR_ERR(event->eventfd);
3928 goto out_put_efile;
3929 }
3930
3931 cfile = fdget(cfd);
3932 if (!cfile.file) {
3933 ret = -EBADF;
3934 goto out_put_eventfd;
3935 }
3936
3937 /* the process need read permission on control file */
3938 /* AV: shouldn't we check that it's been opened for read instead? */
3939 ret = inode_permission(file_inode(cfile.file), MAY_READ);
3940 if (ret < 0)
3941 goto out_put_cfile;
3942
fba94807
TH
3943 /*
3944 * Determine the event callbacks and set them in @event. This used
3945 * to be done via struct cftype but cgroup core no longer knows
3946 * about these events. The following is crude but the whole thing
3947 * is for compatibility anyway.
3bc942f3
TH
3948 *
3949 * DO NOT ADD NEW FILES.
fba94807 3950 */
b583043e 3951 name = cfile.file->f_path.dentry->d_name.name;
fba94807
TH
3952
3953 if (!strcmp(name, "memory.usage_in_bytes")) {
3954 event->register_event = mem_cgroup_usage_register_event;
3955 event->unregister_event = mem_cgroup_usage_unregister_event;
3956 } else if (!strcmp(name, "memory.oom_control")) {
3957 event->register_event = mem_cgroup_oom_register_event;
3958 event->unregister_event = mem_cgroup_oom_unregister_event;
3959 } else if (!strcmp(name, "memory.pressure_level")) {
3960 event->register_event = vmpressure_register_event;
3961 event->unregister_event = vmpressure_unregister_event;
3962 } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
347c4a87
TH
3963 event->register_event = memsw_cgroup_usage_register_event;
3964 event->unregister_event = memsw_cgroup_usage_unregister_event;
fba94807
TH
3965 } else {
3966 ret = -EINVAL;
3967 goto out_put_cfile;
3968 }
3969
79bd9814 3970 /*
b5557c4c
TH
3971 * Verify @cfile should belong to @css. Also, remaining events are
3972 * automatically removed on cgroup destruction but the removal is
3973 * asynchronous, so take an extra ref on @css.
79bd9814 3974 */
b583043e 3975 cfile_css = css_tryget_online_from_dir(cfile.file->f_path.dentry->d_parent,
ec903c0c 3976 &memory_cgrp_subsys);
79bd9814 3977 ret = -EINVAL;
5a17f543 3978 if (IS_ERR(cfile_css))
79bd9814 3979 goto out_put_cfile;
5a17f543
TH
3980 if (cfile_css != css) {
3981 css_put(cfile_css);
79bd9814 3982 goto out_put_cfile;
5a17f543 3983 }
79bd9814 3984
451af504 3985 ret = event->register_event(memcg, event->eventfd, buf);
79bd9814
TH
3986 if (ret)
3987 goto out_put_css;
3988
3989 efile.file->f_op->poll(efile.file, &event->pt);
3990
fba94807
TH
3991 spin_lock(&memcg->event_list_lock);
3992 list_add(&event->list, &memcg->event_list);
3993 spin_unlock(&memcg->event_list_lock);
79bd9814
TH
3994
3995 fdput(cfile);
3996 fdput(efile);
3997
451af504 3998 return nbytes;
79bd9814
TH
3999
4000out_put_css:
b5557c4c 4001 css_put(css);
79bd9814
TH
4002out_put_cfile:
4003 fdput(cfile);
4004out_put_eventfd:
4005 eventfd_ctx_put(event->eventfd);
4006out_put_efile:
4007 fdput(efile);
4008out_kfree:
4009 kfree(event);
4010
4011 return ret;
4012}
4013
241994ed 4014static struct cftype mem_cgroup_legacy_files[] = {
8cdea7c0 4015 {
0eea1030 4016 .name = "usage_in_bytes",
8c7c6e34 4017 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
791badbd 4018 .read_u64 = mem_cgroup_read_u64,
8cdea7c0 4019 },
c84872e1
PE
4020 {
4021 .name = "max_usage_in_bytes",
8c7c6e34 4022 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
6770c64e 4023 .write = mem_cgroup_reset,
791badbd 4024 .read_u64 = mem_cgroup_read_u64,
c84872e1 4025 },
8cdea7c0 4026 {
0eea1030 4027 .name = "limit_in_bytes",
8c7c6e34 4028 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
451af504 4029 .write = mem_cgroup_write,
791badbd 4030 .read_u64 = mem_cgroup_read_u64,
8cdea7c0 4031 },
296c81d8
BS
4032 {
4033 .name = "soft_limit_in_bytes",
4034 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
451af504 4035 .write = mem_cgroup_write,
791badbd 4036 .read_u64 = mem_cgroup_read_u64,
296c81d8 4037 },
8cdea7c0
BS
4038 {
4039 .name = "failcnt",
8c7c6e34 4040 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
6770c64e 4041 .write = mem_cgroup_reset,
791badbd 4042 .read_u64 = mem_cgroup_read_u64,
8cdea7c0 4043 },
d2ceb9b7
KH
4044 {
4045 .name = "stat",
2da8ca82 4046 .seq_show = memcg_stat_show,
d2ceb9b7 4047 },
c1e862c1
KH
4048 {
4049 .name = "force_empty",
6770c64e 4050 .write = mem_cgroup_force_empty_write,
c1e862c1 4051 },
18f59ea7
BS
4052 {
4053 .name = "use_hierarchy",
4054 .write_u64 = mem_cgroup_hierarchy_write,
4055 .read_u64 = mem_cgroup_hierarchy_read,
4056 },
79bd9814 4057 {
3bc942f3 4058 .name = "cgroup.event_control", /* XXX: for compat */
451af504 4059 .write = memcg_write_event_control,
7dbdb199 4060 .flags = CFTYPE_NO_PREFIX | CFTYPE_WORLD_WRITABLE,
79bd9814 4061 },
a7885eb8
KM
4062 {
4063 .name = "swappiness",
4064 .read_u64 = mem_cgroup_swappiness_read,
4065 .write_u64 = mem_cgroup_swappiness_write,
4066 },
7dc74be0
DN
4067 {
4068 .name = "move_charge_at_immigrate",
4069 .read_u64 = mem_cgroup_move_charge_read,
4070 .write_u64 = mem_cgroup_move_charge_write,
4071 },
9490ff27
KH
4072 {
4073 .name = "oom_control",
2da8ca82 4074 .seq_show = mem_cgroup_oom_control_read,
3c11ecf4 4075 .write_u64 = mem_cgroup_oom_control_write,
9490ff27
KH
4076 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
4077 },
70ddf637
AV
4078 {
4079 .name = "pressure_level",
70ddf637 4080 },
406eb0c9
YH
4081#ifdef CONFIG_NUMA
4082 {
4083 .name = "numa_stat",
2da8ca82 4084 .seq_show = memcg_numa_stat_show,
406eb0c9
YH
4085 },
4086#endif
510fc4e1
GC
4087#ifdef CONFIG_MEMCG_KMEM
4088 {
4089 .name = "kmem.limit_in_bytes",
4090 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
451af504 4091 .write = mem_cgroup_write,
791badbd 4092 .read_u64 = mem_cgroup_read_u64,
510fc4e1
GC
4093 },
4094 {
4095 .name = "kmem.usage_in_bytes",
4096 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
791badbd 4097 .read_u64 = mem_cgroup_read_u64,
510fc4e1
GC
4098 },
4099 {
4100 .name = "kmem.failcnt",
4101 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
6770c64e 4102 .write = mem_cgroup_reset,
791badbd 4103 .read_u64 = mem_cgroup_read_u64,
510fc4e1
GC
4104 },
4105 {
4106 .name = "kmem.max_usage_in_bytes",
4107 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
6770c64e 4108 .write = mem_cgroup_reset,
791badbd 4109 .read_u64 = mem_cgroup_read_u64,
510fc4e1 4110 },
749c5415
GC
4111#ifdef CONFIG_SLABINFO
4112 {
4113 .name = "kmem.slabinfo",
b047501c
VD
4114 .seq_start = slab_start,
4115 .seq_next = slab_next,
4116 .seq_stop = slab_stop,
4117 .seq_show = memcg_slab_show,
749c5415
GC
4118 },
4119#endif
8c7c6e34 4120#endif
6bc10349 4121 { }, /* terminate */
af36f906 4122};
8c7c6e34 4123
c0ff4b85 4124static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
6d12e2d8
KH
4125{
4126 struct mem_cgroup_per_node *pn;
1ecaab2b 4127 struct mem_cgroup_per_zone *mz;
41e3355d 4128 int zone, tmp = node;
1ecaab2b
KH
4129 /*
4130 * This routine is called against possible nodes.
4131 * But it's BUG to call kmalloc() against offline node.
4132 *
4133 * TODO: this routine can waste much memory for nodes which will
4134 * never be onlined. It's better to use memory hotplug callback
4135 * function.
4136 */
41e3355d
KH
4137 if (!node_state(node, N_NORMAL_MEMORY))
4138 tmp = -1;
17295c88 4139 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
6d12e2d8
KH
4140 if (!pn)
4141 return 1;
1ecaab2b 4142
1ecaab2b
KH
4143 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4144 mz = &pn->zoneinfo[zone];
bea8c150 4145 lruvec_init(&mz->lruvec);
bb4cc1a8
AM
4146 mz->usage_in_excess = 0;
4147 mz->on_tree = false;
d79154bb 4148 mz->memcg = memcg;
1ecaab2b 4149 }
54f72fe0 4150 memcg->nodeinfo[node] = pn;
6d12e2d8
KH
4151 return 0;
4152}
4153
c0ff4b85 4154static void free_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
1ecaab2b 4155{
54f72fe0 4156 kfree(memcg->nodeinfo[node]);
1ecaab2b
KH
4157}
4158
33327948
KH
4159static struct mem_cgroup *mem_cgroup_alloc(void)
4160{
d79154bb 4161 struct mem_cgroup *memcg;
8ff69e2c 4162 size_t size;
33327948 4163
8ff69e2c
VD
4164 size = sizeof(struct mem_cgroup);
4165 size += nr_node_ids * sizeof(struct mem_cgroup_per_node *);
33327948 4166
8ff69e2c 4167 memcg = kzalloc(size, GFP_KERNEL);
d79154bb 4168 if (!memcg)
e7bbcdf3
DC
4169 return NULL;
4170
d79154bb
HD
4171 memcg->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
4172 if (!memcg->stat)
d2e61b8d 4173 goto out_free;
841710aa
TH
4174
4175 if (memcg_wb_domain_init(memcg, GFP_KERNEL))
4176 goto out_free_stat;
4177
d79154bb 4178 return memcg;
d2e61b8d 4179
841710aa
TH
4180out_free_stat:
4181 free_percpu(memcg->stat);
d2e61b8d 4182out_free:
8ff69e2c 4183 kfree(memcg);
d2e61b8d 4184 return NULL;
33327948
KH
4185}
4186
59927fb9 4187/*
c8b2a36f
GC
4188 * At destroying mem_cgroup, references from swap_cgroup can remain.
4189 * (scanning all at force_empty is too costly...)
4190 *
4191 * Instead of clearing all references at force_empty, we remember
4192 * the number of reference from swap_cgroup and free mem_cgroup when
4193 * it goes down to 0.
4194 *
4195 * Removal of cgroup itself succeeds regardless of refs from swap.
59927fb9 4196 */
c8b2a36f
GC
4197
4198static void __mem_cgroup_free(struct mem_cgroup *memcg)
59927fb9 4199{
c8b2a36f 4200 int node;
59927fb9 4201
bb4cc1a8 4202 mem_cgroup_remove_from_trees(memcg);
c8b2a36f
GC
4203
4204 for_each_node(node)
4205 free_mem_cgroup_per_zone_info(memcg, node);
4206
4207 free_percpu(memcg->stat);
841710aa 4208 memcg_wb_domain_exit(memcg);
8ff69e2c 4209 kfree(memcg);
59927fb9 4210}
3afe36b1 4211
7bcc1bb1
DN
4212/*
4213 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
4214 */
e1aab161 4215struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg)
7bcc1bb1 4216{
3e32cb2e 4217 if (!memcg->memory.parent)
7bcc1bb1 4218 return NULL;
3e32cb2e 4219 return mem_cgroup_from_counter(memcg->memory.parent, memory);
7bcc1bb1 4220}
e1aab161 4221EXPORT_SYMBOL(parent_mem_cgroup);
33327948 4222
0eb253e2 4223static struct cgroup_subsys_state * __ref
eb95419b 4224mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
8cdea7c0 4225{
d142e3e6 4226 struct mem_cgroup *memcg;
04046e1a 4227 long error = -ENOMEM;
6d12e2d8 4228 int node;
8cdea7c0 4229
c0ff4b85
R
4230 memcg = mem_cgroup_alloc();
4231 if (!memcg)
04046e1a 4232 return ERR_PTR(error);
78fb7466 4233
3ed28fa1 4234 for_each_node(node)
c0ff4b85 4235 if (alloc_mem_cgroup_per_zone_info(memcg, node))
6d12e2d8 4236 goto free_out;
f64c3f54 4237
c077719b 4238 /* root ? */
eb95419b 4239 if (parent_css == NULL) {
a41c58a6 4240 root_mem_cgroup = memcg;
56161634 4241 mem_cgroup_root_css = &memcg->css;
3e32cb2e 4242 page_counter_init(&memcg->memory, NULL);
241994ed 4243 memcg->high = PAGE_COUNTER_MAX;
24d404dc 4244 memcg->soft_limit = PAGE_COUNTER_MAX;
3e32cb2e
JW
4245 page_counter_init(&memcg->memsw, NULL);
4246 page_counter_init(&memcg->kmem, NULL);
18f59ea7 4247 }
28dbc4b6 4248
d142e3e6
GC
4249 memcg->last_scanned_node = MAX_NUMNODES;
4250 INIT_LIST_HEAD(&memcg->oom_notify);
d142e3e6
GC
4251 memcg->move_charge_at_immigrate = 0;
4252 mutex_init(&memcg->thresholds_lock);
4253 spin_lock_init(&memcg->move_lock);
70ddf637 4254 vmpressure_init(&memcg->vmpressure);
fba94807
TH
4255 INIT_LIST_HEAD(&memcg->event_list);
4256 spin_lock_init(&memcg->event_list_lock);
900a38f0
VD
4257#ifdef CONFIG_MEMCG_KMEM
4258 memcg->kmemcg_id = -1;
900a38f0 4259#endif
52ebea74
TH
4260#ifdef CONFIG_CGROUP_WRITEBACK
4261 INIT_LIST_HEAD(&memcg->cgwb_list);
4262#endif
d142e3e6
GC
4263 return &memcg->css;
4264
4265free_out:
4266 __mem_cgroup_free(memcg);
4267 return ERR_PTR(error);
4268}
4269
4270static int
eb95419b 4271mem_cgroup_css_online(struct cgroup_subsys_state *css)
d142e3e6 4272{
eb95419b 4273 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5c9d535b 4274 struct mem_cgroup *parent = mem_cgroup_from_css(css->parent);
2f7dd7a4 4275 int ret;
d142e3e6 4276
15a4c835 4277 if (css->id > MEM_CGROUP_ID_MAX)
4219b2da
LZ
4278 return -ENOSPC;
4279
63876986 4280 if (!parent)
d142e3e6
GC
4281 return 0;
4282
0999821b 4283 mutex_lock(&memcg_create_mutex);
d142e3e6
GC
4284
4285 memcg->use_hierarchy = parent->use_hierarchy;
4286 memcg->oom_kill_disable = parent->oom_kill_disable;
4287 memcg->swappiness = mem_cgroup_swappiness(parent);
4288
4289 if (parent->use_hierarchy) {
3e32cb2e 4290 page_counter_init(&memcg->memory, &parent->memory);
241994ed 4291 memcg->high = PAGE_COUNTER_MAX;
24d404dc 4292 memcg->soft_limit = PAGE_COUNTER_MAX;
3e32cb2e
JW
4293 page_counter_init(&memcg->memsw, &parent->memsw);
4294 page_counter_init(&memcg->kmem, &parent->kmem);
55007d84 4295
7bcc1bb1 4296 /*
8d76a979
LZ
4297 * No need to take a reference to the parent because cgroup
4298 * core guarantees its existence.
7bcc1bb1 4299 */
18f59ea7 4300 } else {
3e32cb2e 4301 page_counter_init(&memcg->memory, NULL);
241994ed 4302 memcg->high = PAGE_COUNTER_MAX;
24d404dc 4303 memcg->soft_limit = PAGE_COUNTER_MAX;
3e32cb2e
JW
4304 page_counter_init(&memcg->memsw, NULL);
4305 page_counter_init(&memcg->kmem, NULL);
8c7f6edb
TH
4306 /*
4307 * Deeper hierachy with use_hierarchy == false doesn't make
4308 * much sense so let cgroup subsystem know about this
4309 * unfortunate state in our controller.
4310 */
d142e3e6 4311 if (parent != root_mem_cgroup)
073219e9 4312 memory_cgrp_subsys.broken_hierarchy = true;
18f59ea7 4313 }
0999821b 4314 mutex_unlock(&memcg_create_mutex);
d6441637 4315
2f7dd7a4
JW
4316 ret = memcg_init_kmem(memcg, &memory_cgrp_subsys);
4317 if (ret)
4318 return ret;
4319
4320 /*
4321 * Make sure the memcg is initialized: mem_cgroup_iter()
4322 * orders reading memcg->initialized against its callers
4323 * reading the memcg members.
4324 */
4325 smp_store_release(&memcg->initialized, 1);
4326
4327 return 0;
8cdea7c0
BS
4328}
4329
eb95419b 4330static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
df878fb0 4331{
eb95419b 4332 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3bc942f3 4333 struct mem_cgroup_event *event, *tmp;
79bd9814
TH
4334
4335 /*
4336 * Unregister events and notify userspace.
4337 * Notify userspace about cgroup removing only after rmdir of cgroup
4338 * directory to avoid race between userspace and kernelspace.
4339 */
fba94807
TH
4340 spin_lock(&memcg->event_list_lock);
4341 list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
79bd9814
TH
4342 list_del_init(&event->list);
4343 schedule_work(&event->remove);
4344 }
fba94807 4345 spin_unlock(&memcg->event_list_lock);
ec64f515 4346
33cb876e 4347 vmpressure_cleanup(&memcg->vmpressure);
2a4db7eb
VD
4348
4349 memcg_deactivate_kmem(memcg);
52ebea74
TH
4350
4351 wb_memcg_offline(memcg);
df878fb0
KH
4352}
4353
6df38689
VD
4354static void mem_cgroup_css_released(struct cgroup_subsys_state *css)
4355{
4356 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4357
4358 invalidate_reclaim_iterators(memcg);
4359}
4360
eb95419b 4361static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
8cdea7c0 4362{
eb95419b 4363 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
c268e994 4364
10d5ebf4 4365 memcg_destroy_kmem(memcg);
465939a1 4366 __mem_cgroup_free(memcg);
8cdea7c0
BS
4367}
4368
1ced953b
TH
4369/**
4370 * mem_cgroup_css_reset - reset the states of a mem_cgroup
4371 * @css: the target css
4372 *
4373 * Reset the states of the mem_cgroup associated with @css. This is
4374 * invoked when the userland requests disabling on the default hierarchy
4375 * but the memcg is pinned through dependency. The memcg should stop
4376 * applying policies and should revert to the vanilla state as it may be
4377 * made visible again.
4378 *
4379 * The current implementation only resets the essential configurations.
4380 * This needs to be expanded to cover all the visible parts.
4381 */
4382static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
4383{
4384 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4385
3e32cb2e
JW
4386 mem_cgroup_resize_limit(memcg, PAGE_COUNTER_MAX);
4387 mem_cgroup_resize_memsw_limit(memcg, PAGE_COUNTER_MAX);
4388 memcg_update_kmem_limit(memcg, PAGE_COUNTER_MAX);
241994ed
JW
4389 memcg->low = 0;
4390 memcg->high = PAGE_COUNTER_MAX;
24d404dc 4391 memcg->soft_limit = PAGE_COUNTER_MAX;
2529bb3a 4392 memcg_wb_domain_size_changed(memcg);
1ced953b
TH
4393}
4394
02491447 4395#ifdef CONFIG_MMU
7dc74be0 4396/* Handlers for move charge at task migration. */
854ffa8d 4397static int mem_cgroup_do_precharge(unsigned long count)
7dc74be0 4398{
05b84301 4399 int ret;
9476db97 4400
d0164adc
MG
4401 /* Try a single bulk charge without reclaim first, kswapd may wake */
4402 ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_DIRECT_RECLAIM, count);
9476db97 4403 if (!ret) {
854ffa8d 4404 mc.precharge += count;
854ffa8d
DN
4405 return ret;
4406 }
9476db97
JW
4407
4408 /* Try charges one by one with reclaim */
854ffa8d 4409 while (count--) {
00501b53 4410 ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_NORETRY, 1);
38c5d72f 4411 if (ret)
38c5d72f 4412 return ret;
854ffa8d 4413 mc.precharge++;
9476db97 4414 cond_resched();
854ffa8d 4415 }
9476db97 4416 return 0;
4ffef5fe
DN
4417}
4418
4419/**
8d32ff84 4420 * get_mctgt_type - get target type of moving charge
4ffef5fe
DN
4421 * @vma: the vma the pte to be checked belongs
4422 * @addr: the address corresponding to the pte to be checked
4423 * @ptent: the pte to be checked
02491447 4424 * @target: the pointer the target page or swap ent will be stored(can be NULL)
4ffef5fe
DN
4425 *
4426 * Returns
4427 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
4428 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
4429 * move charge. if @target is not NULL, the page is stored in target->page
4430 * with extra refcnt got(Callers should handle it).
02491447
DN
4431 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
4432 * target for charge migration. if @target is not NULL, the entry is stored
4433 * in target->ent.
4ffef5fe
DN
4434 *
4435 * Called with pte lock held.
4436 */
4ffef5fe
DN
4437union mc_target {
4438 struct page *page;
02491447 4439 swp_entry_t ent;
4ffef5fe
DN
4440};
4441
4ffef5fe 4442enum mc_target_type {
8d32ff84 4443 MC_TARGET_NONE = 0,
4ffef5fe 4444 MC_TARGET_PAGE,
02491447 4445 MC_TARGET_SWAP,
4ffef5fe
DN
4446};
4447
90254a65
DN
4448static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
4449 unsigned long addr, pte_t ptent)
4ffef5fe 4450{
90254a65 4451 struct page *page = vm_normal_page(vma, addr, ptent);
4ffef5fe 4452
90254a65
DN
4453 if (!page || !page_mapped(page))
4454 return NULL;
4455 if (PageAnon(page)) {
1dfab5ab 4456 if (!(mc.flags & MOVE_ANON))
90254a65 4457 return NULL;
1dfab5ab
JW
4458 } else {
4459 if (!(mc.flags & MOVE_FILE))
4460 return NULL;
4461 }
90254a65
DN
4462 if (!get_page_unless_zero(page))
4463 return NULL;
4464
4465 return page;
4466}
4467
4b91355e 4468#ifdef CONFIG_SWAP
90254a65
DN
4469static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
4470 unsigned long addr, pte_t ptent, swp_entry_t *entry)
4471{
90254a65
DN
4472 struct page *page = NULL;
4473 swp_entry_t ent = pte_to_swp_entry(ptent);
4474
1dfab5ab 4475 if (!(mc.flags & MOVE_ANON) || non_swap_entry(ent))
90254a65 4476 return NULL;
4b91355e
KH
4477 /*
4478 * Because lookup_swap_cache() updates some statistics counter,
4479 * we call find_get_page() with swapper_space directly.
4480 */
33806f06 4481 page = find_get_page(swap_address_space(ent), ent.val);
90254a65
DN
4482 if (do_swap_account)
4483 entry->val = ent.val;
4484
4485 return page;
4486}
4b91355e
KH
4487#else
4488static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
4489 unsigned long addr, pte_t ptent, swp_entry_t *entry)
4490{
4491 return NULL;
4492}
4493#endif
90254a65 4494
87946a72
DN
4495static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
4496 unsigned long addr, pte_t ptent, swp_entry_t *entry)
4497{
4498 struct page *page = NULL;
87946a72
DN
4499 struct address_space *mapping;
4500 pgoff_t pgoff;
4501
4502 if (!vma->vm_file) /* anonymous vma */
4503 return NULL;
1dfab5ab 4504 if (!(mc.flags & MOVE_FILE))
87946a72
DN
4505 return NULL;
4506
87946a72 4507 mapping = vma->vm_file->f_mapping;
0661a336 4508 pgoff = linear_page_index(vma, addr);
87946a72
DN
4509
4510 /* page is moved even if it's not RSS of this task(page-faulted). */
aa3b1895
HD
4511#ifdef CONFIG_SWAP
4512 /* shmem/tmpfs may report page out on swap: account for that too. */
139b6a6f
JW
4513 if (shmem_mapping(mapping)) {
4514 page = find_get_entry(mapping, pgoff);
4515 if (radix_tree_exceptional_entry(page)) {
4516 swp_entry_t swp = radix_to_swp_entry(page);
4517 if (do_swap_account)
4518 *entry = swp;
4519 page = find_get_page(swap_address_space(swp), swp.val);
4520 }
4521 } else
4522 page = find_get_page(mapping, pgoff);
4523#else
4524 page = find_get_page(mapping, pgoff);
aa3b1895 4525#endif
87946a72
DN
4526 return page;
4527}
4528
b1b0deab
CG
4529/**
4530 * mem_cgroup_move_account - move account of the page
4531 * @page: the page
4532 * @nr_pages: number of regular pages (>1 for huge pages)
4533 * @from: mem_cgroup which the page is moved from.
4534 * @to: mem_cgroup which the page is moved to. @from != @to.
4535 *
4536 * The caller must confirm following.
4537 * - page is not on LRU (isolate_page() is useful.)
4538 * - compound_lock is held when nr_pages > 1
4539 *
4540 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
4541 * from old cgroup.
4542 */
4543static int mem_cgroup_move_account(struct page *page,
4544 unsigned int nr_pages,
4545 struct mem_cgroup *from,
4546 struct mem_cgroup *to)
4547{
4548 unsigned long flags;
4549 int ret;
c4843a75 4550 bool anon;
b1b0deab
CG
4551
4552 VM_BUG_ON(from == to);
4553 VM_BUG_ON_PAGE(PageLRU(page), page);
4554 /*
4555 * The page is isolated from LRU. So, collapse function
4556 * will not handle this page. But page splitting can happen.
4557 * Do this check under compound_page_lock(). The caller should
4558 * hold it.
4559 */
4560 ret = -EBUSY;
4561 if (nr_pages > 1 && !PageTransHuge(page))
4562 goto out;
4563
4564 /*
45637bab
HD
4565 * Prevent mem_cgroup_replace_page() from looking at
4566 * page->mem_cgroup of its source page while we change it.
b1b0deab
CG
4567 */
4568 if (!trylock_page(page))
4569 goto out;
4570
4571 ret = -EINVAL;
4572 if (page->mem_cgroup != from)
4573 goto out_unlock;
4574
c4843a75
GT
4575 anon = PageAnon(page);
4576
b1b0deab
CG
4577 spin_lock_irqsave(&from->move_lock, flags);
4578
c4843a75 4579 if (!anon && page_mapped(page)) {
b1b0deab
CG
4580 __this_cpu_sub(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED],
4581 nr_pages);
4582 __this_cpu_add(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED],
4583 nr_pages);
4584 }
4585
c4843a75
GT
4586 /*
4587 * move_lock grabbed above and caller set from->moving_account, so
4588 * mem_cgroup_update_page_stat() will serialize updates to PageDirty.
4589 * So mapping should be stable for dirty pages.
4590 */
4591 if (!anon && PageDirty(page)) {
4592 struct address_space *mapping = page_mapping(page);
4593
4594 if (mapping_cap_account_dirty(mapping)) {
4595 __this_cpu_sub(from->stat->count[MEM_CGROUP_STAT_DIRTY],
4596 nr_pages);
4597 __this_cpu_add(to->stat->count[MEM_CGROUP_STAT_DIRTY],
4598 nr_pages);
4599 }
4600 }
4601
b1b0deab
CG
4602 if (PageWriteback(page)) {
4603 __this_cpu_sub(from->stat->count[MEM_CGROUP_STAT_WRITEBACK],
4604 nr_pages);
4605 __this_cpu_add(to->stat->count[MEM_CGROUP_STAT_WRITEBACK],
4606 nr_pages);
4607 }
4608
4609 /*
4610 * It is safe to change page->mem_cgroup here because the page
4611 * is referenced, charged, and isolated - we can't race with
4612 * uncharging, charging, migration, or LRU putback.
4613 */
4614
4615 /* caller should have done css_get */
4616 page->mem_cgroup = to;
4617 spin_unlock_irqrestore(&from->move_lock, flags);
4618
4619 ret = 0;
4620
4621 local_irq_disable();
4622 mem_cgroup_charge_statistics(to, page, nr_pages);
4623 memcg_check_events(to, page);
4624 mem_cgroup_charge_statistics(from, page, -nr_pages);
4625 memcg_check_events(from, page);
4626 local_irq_enable();
4627out_unlock:
4628 unlock_page(page);
4629out:
4630 return ret;
4631}
4632
8d32ff84 4633static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
90254a65
DN
4634 unsigned long addr, pte_t ptent, union mc_target *target)
4635{
4636 struct page *page = NULL;
8d32ff84 4637 enum mc_target_type ret = MC_TARGET_NONE;
90254a65
DN
4638 swp_entry_t ent = { .val = 0 };
4639
4640 if (pte_present(ptent))
4641 page = mc_handle_present_pte(vma, addr, ptent);
4642 else if (is_swap_pte(ptent))
4643 page = mc_handle_swap_pte(vma, addr, ptent, &ent);
0661a336 4644 else if (pte_none(ptent))
87946a72 4645 page = mc_handle_file_pte(vma, addr, ptent, &ent);
90254a65
DN
4646
4647 if (!page && !ent.val)
8d32ff84 4648 return ret;
02491447 4649 if (page) {
02491447 4650 /*
0a31bc97 4651 * Do only loose check w/o serialization.
1306a85a 4652 * mem_cgroup_move_account() checks the page is valid or
0a31bc97 4653 * not under LRU exclusion.
02491447 4654 */
1306a85a 4655 if (page->mem_cgroup == mc.from) {
02491447
DN
4656 ret = MC_TARGET_PAGE;
4657 if (target)
4658 target->page = page;
4659 }
4660 if (!ret || !target)
4661 put_page(page);
4662 }
90254a65
DN
4663 /* There is a swap entry and a page doesn't exist or isn't charged */
4664 if (ent.val && !ret &&
34c00c31 4665 mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
7f0f1546
KH
4666 ret = MC_TARGET_SWAP;
4667 if (target)
4668 target->ent = ent;
4ffef5fe 4669 }
4ffef5fe
DN
4670 return ret;
4671}
4672
12724850
NH
4673#ifdef CONFIG_TRANSPARENT_HUGEPAGE
4674/*
4675 * We don't consider swapping or file mapped pages because THP does not
4676 * support them for now.
4677 * Caller should make sure that pmd_trans_huge(pmd) is true.
4678 */
4679static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
4680 unsigned long addr, pmd_t pmd, union mc_target *target)
4681{
4682 struct page *page = NULL;
12724850
NH
4683 enum mc_target_type ret = MC_TARGET_NONE;
4684
4685 page = pmd_page(pmd);
309381fe 4686 VM_BUG_ON_PAGE(!page || !PageHead(page), page);
1dfab5ab 4687 if (!(mc.flags & MOVE_ANON))
12724850 4688 return ret;
1306a85a 4689 if (page->mem_cgroup == mc.from) {
12724850
NH
4690 ret = MC_TARGET_PAGE;
4691 if (target) {
4692 get_page(page);
4693 target->page = page;
4694 }
4695 }
4696 return ret;
4697}
4698#else
4699static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
4700 unsigned long addr, pmd_t pmd, union mc_target *target)
4701{
4702 return MC_TARGET_NONE;
4703}
4704#endif
4705
4ffef5fe
DN
4706static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
4707 unsigned long addr, unsigned long end,
4708 struct mm_walk *walk)
4709{
26bcd64a 4710 struct vm_area_struct *vma = walk->vma;
4ffef5fe
DN
4711 pte_t *pte;
4712 spinlock_t *ptl;
4713
bf929152 4714 if (pmd_trans_huge_lock(pmd, vma, &ptl) == 1) {
12724850
NH
4715 if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
4716 mc.precharge += HPAGE_PMD_NR;
bf929152 4717 spin_unlock(ptl);
1a5a9906 4718 return 0;
12724850 4719 }
03319327 4720
45f83cef
AA
4721 if (pmd_trans_unstable(pmd))
4722 return 0;
4ffef5fe
DN
4723 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
4724 for (; addr != end; pte++, addr += PAGE_SIZE)
8d32ff84 4725 if (get_mctgt_type(vma, addr, *pte, NULL))
4ffef5fe
DN
4726 mc.precharge++; /* increment precharge temporarily */
4727 pte_unmap_unlock(pte - 1, ptl);
4728 cond_resched();
4729
7dc74be0
DN
4730 return 0;
4731}
4732
4ffef5fe
DN
4733static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
4734{
4735 unsigned long precharge;
4ffef5fe 4736
26bcd64a
NH
4737 struct mm_walk mem_cgroup_count_precharge_walk = {
4738 .pmd_entry = mem_cgroup_count_precharge_pte_range,
4739 .mm = mm,
4740 };
dfe076b0 4741 down_read(&mm->mmap_sem);
26bcd64a 4742 walk_page_range(0, ~0UL, &mem_cgroup_count_precharge_walk);
dfe076b0 4743 up_read(&mm->mmap_sem);
4ffef5fe
DN
4744
4745 precharge = mc.precharge;
4746 mc.precharge = 0;
4747
4748 return precharge;
4749}
4750
4ffef5fe
DN
4751static int mem_cgroup_precharge_mc(struct mm_struct *mm)
4752{
dfe076b0
DN
4753 unsigned long precharge = mem_cgroup_count_precharge(mm);
4754
4755 VM_BUG_ON(mc.moving_task);
4756 mc.moving_task = current;
4757 return mem_cgroup_do_precharge(precharge);
4ffef5fe
DN
4758}
4759
dfe076b0
DN
4760/* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
4761static void __mem_cgroup_clear_mc(void)
4ffef5fe 4762{
2bd9bb20
KH
4763 struct mem_cgroup *from = mc.from;
4764 struct mem_cgroup *to = mc.to;
4765
4ffef5fe 4766 /* we must uncharge all the leftover precharges from mc.to */
854ffa8d 4767 if (mc.precharge) {
00501b53 4768 cancel_charge(mc.to, mc.precharge);
854ffa8d
DN
4769 mc.precharge = 0;
4770 }
4771 /*
4772 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
4773 * we must uncharge here.
4774 */
4775 if (mc.moved_charge) {
00501b53 4776 cancel_charge(mc.from, mc.moved_charge);
854ffa8d 4777 mc.moved_charge = 0;
4ffef5fe 4778 }
483c30b5
DN
4779 /* we must fixup refcnts and charges */
4780 if (mc.moved_swap) {
483c30b5 4781 /* uncharge swap account from the old cgroup */
ce00a967 4782 if (!mem_cgroup_is_root(mc.from))
3e32cb2e 4783 page_counter_uncharge(&mc.from->memsw, mc.moved_swap);
483c30b5 4784
05b84301 4785 /*
3e32cb2e
JW
4786 * we charged both to->memory and to->memsw, so we
4787 * should uncharge to->memory.
05b84301 4788 */
ce00a967 4789 if (!mem_cgroup_is_root(mc.to))
3e32cb2e
JW
4790 page_counter_uncharge(&mc.to->memory, mc.moved_swap);
4791
e8ea14cc 4792 css_put_many(&mc.from->css, mc.moved_swap);
3e32cb2e 4793
4050377b 4794 /* we've already done css_get(mc.to) */
483c30b5
DN
4795 mc.moved_swap = 0;
4796 }
dfe076b0
DN
4797 memcg_oom_recover(from);
4798 memcg_oom_recover(to);
4799 wake_up_all(&mc.waitq);
4800}
4801
4802static void mem_cgroup_clear_mc(void)
4803{
52526076
TH
4804 struct mm_struct *mm = mc.mm;
4805
dfe076b0
DN
4806 /*
4807 * we must clear moving_task before waking up waiters at the end of
4808 * task migration.
4809 */
4810 mc.moving_task = NULL;
4811 __mem_cgroup_clear_mc();
2bd9bb20 4812 spin_lock(&mc.lock);
4ffef5fe
DN
4813 mc.from = NULL;
4814 mc.to = NULL;
52526076 4815 mc.mm = NULL;
2bd9bb20 4816 spin_unlock(&mc.lock);
52526076
TH
4817
4818 mmput(mm);
4ffef5fe
DN
4819}
4820
1f7dd3e5 4821static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
7dc74be0 4822{
1f7dd3e5
TH
4823 struct cgroup_subsys_state *css;
4824 struct mem_cgroup *memcg;
9f2115f9 4825 struct mem_cgroup *from;
4530eddb 4826 struct task_struct *leader, *p;
9f2115f9 4827 struct mm_struct *mm;
1dfab5ab 4828 unsigned long move_flags;
9f2115f9 4829 int ret = 0;
7dc74be0 4830
1f7dd3e5
TH
4831 /* charge immigration isn't supported on the default hierarchy */
4832 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
9f2115f9
TH
4833 return 0;
4834
4530eddb
TH
4835 /*
4836 * Multi-process migrations only happen on the default hierarchy
4837 * where charge immigration is not used. Perform charge
4838 * immigration if @tset contains a leader and whine if there are
4839 * multiple.
4840 */
4841 p = NULL;
1f7dd3e5 4842 cgroup_taskset_for_each_leader(leader, css, tset) {
4530eddb
TH
4843 WARN_ON_ONCE(p);
4844 p = leader;
1f7dd3e5 4845 memcg = mem_cgroup_from_css(css);
4530eddb
TH
4846 }
4847 if (!p)
4848 return 0;
4849
1f7dd3e5
TH
4850 /*
4851 * We are now commited to this value whatever it is. Changes in this
4852 * tunable will only affect upcoming migrations, not the current one.
4853 * So we need to save it, and keep it going.
4854 */
4855 move_flags = READ_ONCE(memcg->move_charge_at_immigrate);
4856 if (!move_flags)
4857 return 0;
4858
9f2115f9
TH
4859 from = mem_cgroup_from_task(p);
4860
4861 VM_BUG_ON(from == memcg);
4862
4863 mm = get_task_mm(p);
4864 if (!mm)
4865 return 0;
4866 /* We move charges only when we move a owner of the mm */
4867 if (mm->owner == p) {
4868 VM_BUG_ON(mc.from);
4869 VM_BUG_ON(mc.to);
4870 VM_BUG_ON(mc.precharge);
4871 VM_BUG_ON(mc.moved_charge);
4872 VM_BUG_ON(mc.moved_swap);
4873
4874 spin_lock(&mc.lock);
52526076 4875 mc.mm = mm;
9f2115f9
TH
4876 mc.from = from;
4877 mc.to = memcg;
4878 mc.flags = move_flags;
4879 spin_unlock(&mc.lock);
4880 /* We set mc.moving_task later */
4881
4882 ret = mem_cgroup_precharge_mc(mm);
4883 if (ret)
4884 mem_cgroup_clear_mc();
52526076
TH
4885 } else {
4886 mmput(mm);
7dc74be0
DN
4887 }
4888 return ret;
4889}
4890
1f7dd3e5 4891static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
7dc74be0 4892{
4e2f245d
JW
4893 if (mc.to)
4894 mem_cgroup_clear_mc();
7dc74be0
DN
4895}
4896
4ffef5fe
DN
4897static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
4898 unsigned long addr, unsigned long end,
4899 struct mm_walk *walk)
7dc74be0 4900{
4ffef5fe 4901 int ret = 0;
26bcd64a 4902 struct vm_area_struct *vma = walk->vma;
4ffef5fe
DN
4903 pte_t *pte;
4904 spinlock_t *ptl;
12724850
NH
4905 enum mc_target_type target_type;
4906 union mc_target target;
4907 struct page *page;
4ffef5fe 4908
12724850
NH
4909 /*
4910 * We don't take compound_lock() here but no race with splitting thp
4911 * happens because:
4912 * - if pmd_trans_huge_lock() returns 1, the relevant thp is not
4913 * under splitting, which means there's no concurrent thp split,
4914 * - if another thread runs into split_huge_page() just after we
4915 * entered this if-block, the thread must wait for page table lock
4916 * to be unlocked in __split_huge_page_splitting(), where the main
4917 * part of thp split is not executed yet.
4918 */
bf929152 4919 if (pmd_trans_huge_lock(pmd, vma, &ptl) == 1) {
62ade86a 4920 if (mc.precharge < HPAGE_PMD_NR) {
bf929152 4921 spin_unlock(ptl);
12724850
NH
4922 return 0;
4923 }
4924 target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
4925 if (target_type == MC_TARGET_PAGE) {
4926 page = target.page;
4927 if (!isolate_lru_page(page)) {
12724850 4928 if (!mem_cgroup_move_account(page, HPAGE_PMD_NR,
1306a85a 4929 mc.from, mc.to)) {
12724850
NH
4930 mc.precharge -= HPAGE_PMD_NR;
4931 mc.moved_charge += HPAGE_PMD_NR;
4932 }
4933 putback_lru_page(page);
4934 }
4935 put_page(page);
4936 }
bf929152 4937 spin_unlock(ptl);
1a5a9906 4938 return 0;
12724850
NH
4939 }
4940
45f83cef
AA
4941 if (pmd_trans_unstable(pmd))
4942 return 0;
4ffef5fe
DN
4943retry:
4944 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
4945 for (; addr != end; addr += PAGE_SIZE) {
4946 pte_t ptent = *(pte++);
02491447 4947 swp_entry_t ent;
4ffef5fe
DN
4948
4949 if (!mc.precharge)
4950 break;
4951
8d32ff84 4952 switch (get_mctgt_type(vma, addr, ptent, &target)) {
4ffef5fe
DN
4953 case MC_TARGET_PAGE:
4954 page = target.page;
4955 if (isolate_lru_page(page))
4956 goto put;
1306a85a 4957 if (!mem_cgroup_move_account(page, 1, mc.from, mc.to)) {
4ffef5fe 4958 mc.precharge--;
854ffa8d
DN
4959 /* we uncharge from mc.from later. */
4960 mc.moved_charge++;
4ffef5fe
DN
4961 }
4962 putback_lru_page(page);
8d32ff84 4963put: /* get_mctgt_type() gets the page */
4ffef5fe
DN
4964 put_page(page);
4965 break;
02491447
DN
4966 case MC_TARGET_SWAP:
4967 ent = target.ent;
e91cbb42 4968 if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
02491447 4969 mc.precharge--;
483c30b5
DN
4970 /* we fixup refcnts and charges later. */
4971 mc.moved_swap++;
4972 }
02491447 4973 break;
4ffef5fe
DN
4974 default:
4975 break;
4976 }
4977 }
4978 pte_unmap_unlock(pte - 1, ptl);
4979 cond_resched();
4980
4981 if (addr != end) {
4982 /*
4983 * We have consumed all precharges we got in can_attach().
4984 * We try charge one by one, but don't do any additional
4985 * charges to mc.to if we have failed in charge once in attach()
4986 * phase.
4987 */
854ffa8d 4988 ret = mem_cgroup_do_precharge(1);
4ffef5fe
DN
4989 if (!ret)
4990 goto retry;
4991 }
4992
4993 return ret;
4994}
4995
52526076 4996static void mem_cgroup_move_charge(void)
4ffef5fe 4997{
26bcd64a
NH
4998 struct mm_walk mem_cgroup_move_charge_walk = {
4999 .pmd_entry = mem_cgroup_move_charge_pte_range,
52526076 5000 .mm = mc.mm,
26bcd64a 5001 };
4ffef5fe
DN
5002
5003 lru_add_drain_all();
312722cb
JW
5004 /*
5005 * Signal mem_cgroup_begin_page_stat() to take the memcg's
5006 * move_lock while we're moving its pages to another memcg.
5007 * Then wait for already started RCU-only updates to finish.
5008 */
5009 atomic_inc(&mc.from->moving_account);
5010 synchronize_rcu();
dfe076b0 5011retry:
52526076 5012 if (unlikely(!down_read_trylock(&mc.mm->mmap_sem))) {
dfe076b0
DN
5013 /*
5014 * Someone who are holding the mmap_sem might be waiting in
5015 * waitq. So we cancel all extra charges, wake up all waiters,
5016 * and retry. Because we cancel precharges, we might not be able
5017 * to move enough charges, but moving charge is a best-effort
5018 * feature anyway, so it wouldn't be a big problem.
5019 */
5020 __mem_cgroup_clear_mc();
5021 cond_resched();
5022 goto retry;
5023 }
26bcd64a
NH
5024 /*
5025 * When we have consumed all precharges and failed in doing
5026 * additional charge, the page walk just aborts.
5027 */
5028 walk_page_range(0, ~0UL, &mem_cgroup_move_charge_walk);
52526076 5029 up_read(&mc.mm->mmap_sem);
312722cb 5030 atomic_dec(&mc.from->moving_account);
7dc74be0
DN
5031}
5032
52526076 5033static void mem_cgroup_move_task(void)
67e465a7 5034{
52526076
TH
5035 if (mc.to) {
5036 mem_cgroup_move_charge();
a433658c 5037 mem_cgroup_clear_mc();
52526076 5038 }
67e465a7 5039}
5cfb80a7 5040#else /* !CONFIG_MMU */
1f7dd3e5 5041static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
5cfb80a7
DN
5042{
5043 return 0;
5044}
1f7dd3e5 5045static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
5cfb80a7
DN
5046{
5047}
52526076 5048static void mem_cgroup_move_task(void)
5cfb80a7
DN
5049{
5050}
5051#endif
67e465a7 5052
f00baae7
TH
5053/*
5054 * Cgroup retains root cgroups across [un]mount cycles making it necessary
aa6ec29b
TH
5055 * to verify whether we're attached to the default hierarchy on each mount
5056 * attempt.
f00baae7 5057 */
eb95419b 5058static void mem_cgroup_bind(struct cgroup_subsys_state *root_css)
f00baae7
TH
5059{
5060 /*
aa6ec29b 5061 * use_hierarchy is forced on the default hierarchy. cgroup core
f00baae7
TH
5062 * guarantees that @root doesn't have any children, so turning it
5063 * on for the root memcg is enough.
5064 */
9e10a130 5065 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
7feee590
VD
5066 root_mem_cgroup->use_hierarchy = true;
5067 else
5068 root_mem_cgroup->use_hierarchy = false;
f00baae7
TH
5069}
5070
241994ed
JW
5071static u64 memory_current_read(struct cgroup_subsys_state *css,
5072 struct cftype *cft)
5073{
f5fc3c5d
JW
5074 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5075
5076 return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
241994ed
JW
5077}
5078
5079static int memory_low_show(struct seq_file *m, void *v)
5080{
5081 struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
4db0c3c2 5082 unsigned long low = READ_ONCE(memcg->low);
241994ed
JW
5083
5084 if (low == PAGE_COUNTER_MAX)
d2973697 5085 seq_puts(m, "max\n");
241994ed
JW
5086 else
5087 seq_printf(m, "%llu\n", (u64)low * PAGE_SIZE);
5088
5089 return 0;
5090}
5091
5092static ssize_t memory_low_write(struct kernfs_open_file *of,
5093 char *buf, size_t nbytes, loff_t off)
5094{
5095 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
5096 unsigned long low;
5097 int err;
5098
5099 buf = strstrip(buf);
d2973697 5100 err = page_counter_memparse(buf, "max", &low);
241994ed
JW
5101 if (err)
5102 return err;
5103
5104 memcg->low = low;
5105
5106 return nbytes;
5107}
5108
5109static int memory_high_show(struct seq_file *m, void *v)
5110{
5111 struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
4db0c3c2 5112 unsigned long high = READ_ONCE(memcg->high);
241994ed
JW
5113
5114 if (high == PAGE_COUNTER_MAX)
d2973697 5115 seq_puts(m, "max\n");
241994ed
JW
5116 else
5117 seq_printf(m, "%llu\n", (u64)high * PAGE_SIZE);
5118
5119 return 0;
5120}
5121
5122static ssize_t memory_high_write(struct kernfs_open_file *of,
5123 char *buf, size_t nbytes, loff_t off)
5124{
5125 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
8b42fc47 5126 unsigned long nr_pages;
241994ed
JW
5127 unsigned long high;
5128 int err;
5129
5130 buf = strstrip(buf);
d2973697 5131 err = page_counter_memparse(buf, "max", &high);
241994ed
JW
5132 if (err)
5133 return err;
5134
5135 memcg->high = high;
5136
8b42fc47
JW
5137 nr_pages = page_counter_read(&memcg->memory);
5138 if (nr_pages > high)
5139 try_to_free_mem_cgroup_pages(memcg, nr_pages - high,
5140 GFP_KERNEL, true);
5141
2529bb3a 5142 memcg_wb_domain_size_changed(memcg);
241994ed
JW
5143 return nbytes;
5144}
5145
5146static int memory_max_show(struct seq_file *m, void *v)
5147{
5148 struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
4db0c3c2 5149 unsigned long max = READ_ONCE(memcg->memory.limit);
241994ed
JW
5150
5151 if (max == PAGE_COUNTER_MAX)
d2973697 5152 seq_puts(m, "max\n");
241994ed
JW
5153 else
5154 seq_printf(m, "%llu\n", (u64)max * PAGE_SIZE);
5155
5156 return 0;
5157}
5158
5159static ssize_t memory_max_write(struct kernfs_open_file *of,
5160 char *buf, size_t nbytes, loff_t off)
5161{
5162 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
0ccab5b1
JW
5163 unsigned int nr_reclaims = MEM_CGROUP_RECLAIM_RETRIES;
5164 bool drained = false;
241994ed
JW
5165 unsigned long max;
5166 int err;
5167
5168 buf = strstrip(buf);
d2973697 5169 err = page_counter_memparse(buf, "max", &max);
241994ed
JW
5170 if (err)
5171 return err;
5172
0ccab5b1
JW
5173 xchg(&memcg->memory.limit, max);
5174
5175 for (;;) {
5176 unsigned long nr_pages = page_counter_read(&memcg->memory);
5177
5178 if (nr_pages <= max)
5179 break;
5180
5181 if (signal_pending(current)) {
5182 err = -EINTR;
5183 break;
5184 }
5185
5186 if (!drained) {
5187 drain_all_stock(memcg);
5188 drained = true;
5189 continue;
5190 }
5191
5192 if (nr_reclaims) {
5193 if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,
5194 GFP_KERNEL, true))
5195 nr_reclaims--;
5196 continue;
5197 }
5198
5199 mem_cgroup_events(memcg, MEMCG_OOM, 1);
5200 if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0))
5201 break;
5202 }
241994ed 5203
2529bb3a 5204 memcg_wb_domain_size_changed(memcg);
241994ed
JW
5205 return nbytes;
5206}
5207
5208static int memory_events_show(struct seq_file *m, void *v)
5209{
5210 struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
5211
5212 seq_printf(m, "low %lu\n", mem_cgroup_read_events(memcg, MEMCG_LOW));
5213 seq_printf(m, "high %lu\n", mem_cgroup_read_events(memcg, MEMCG_HIGH));
5214 seq_printf(m, "max %lu\n", mem_cgroup_read_events(memcg, MEMCG_MAX));
5215 seq_printf(m, "oom %lu\n", mem_cgroup_read_events(memcg, MEMCG_OOM));
5216
5217 return 0;
5218}
5219
5220static struct cftype memory_files[] = {
5221 {
5222 .name = "current",
f5fc3c5d 5223 .flags = CFTYPE_NOT_ON_ROOT,
241994ed
JW
5224 .read_u64 = memory_current_read,
5225 },
5226 {
5227 .name = "low",
5228 .flags = CFTYPE_NOT_ON_ROOT,
5229 .seq_show = memory_low_show,
5230 .write = memory_low_write,
5231 },
5232 {
5233 .name = "high",
5234 .flags = CFTYPE_NOT_ON_ROOT,
5235 .seq_show = memory_high_show,
5236 .write = memory_high_write,
5237 },
5238 {
5239 .name = "max",
5240 .flags = CFTYPE_NOT_ON_ROOT,
5241 .seq_show = memory_max_show,
5242 .write = memory_max_write,
5243 },
5244 {
5245 .name = "events",
5246 .flags = CFTYPE_NOT_ON_ROOT,
472912a2 5247 .file_offset = offsetof(struct mem_cgroup, events_file),
241994ed
JW
5248 .seq_show = memory_events_show,
5249 },
5250 { } /* terminate */
5251};
5252
073219e9 5253struct cgroup_subsys memory_cgrp_subsys = {
92fb9748 5254 .css_alloc = mem_cgroup_css_alloc,
d142e3e6 5255 .css_online = mem_cgroup_css_online,
92fb9748 5256 .css_offline = mem_cgroup_css_offline,
6df38689 5257 .css_released = mem_cgroup_css_released,
92fb9748 5258 .css_free = mem_cgroup_css_free,
1ced953b 5259 .css_reset = mem_cgroup_css_reset,
7dc74be0
DN
5260 .can_attach = mem_cgroup_can_attach,
5261 .cancel_attach = mem_cgroup_cancel_attach,
52526076 5262 .post_attach = mem_cgroup_move_task,
f00baae7 5263 .bind = mem_cgroup_bind,
241994ed
JW
5264 .dfl_cftypes = memory_files,
5265 .legacy_cftypes = mem_cgroup_legacy_files,
6d12e2d8 5266 .early_init = 0,
8cdea7c0 5267};
c077719b 5268
241994ed
JW
5269/**
5270 * mem_cgroup_low - check if memory consumption is below the normal range
5271 * @root: the highest ancestor to consider
5272 * @memcg: the memory cgroup to check
5273 *
5274 * Returns %true if memory consumption of @memcg, and that of all
5275 * configurable ancestors up to @root, is below the normal range.
5276 */
5277bool mem_cgroup_low(struct mem_cgroup *root, struct mem_cgroup *memcg)
5278{
5279 if (mem_cgroup_disabled())
5280 return false;
5281
5282 /*
5283 * The toplevel group doesn't have a configurable range, so
5284 * it's never low when looked at directly, and it is not
5285 * considered an ancestor when assessing the hierarchy.
5286 */
5287
5288 if (memcg == root_mem_cgroup)
5289 return false;
5290
4e54dede 5291 if (page_counter_read(&memcg->memory) >= memcg->low)
241994ed
JW
5292 return false;
5293
5294 while (memcg != root) {
5295 memcg = parent_mem_cgroup(memcg);
5296
5297 if (memcg == root_mem_cgroup)
5298 break;
5299
4e54dede 5300 if (page_counter_read(&memcg->memory) >= memcg->low)
241994ed
JW
5301 return false;
5302 }
5303 return true;
5304}
5305
00501b53
JW
5306/**
5307 * mem_cgroup_try_charge - try charging a page
5308 * @page: page to charge
5309 * @mm: mm context of the victim
5310 * @gfp_mask: reclaim mode
5311 * @memcgp: charged memcg return
5312 *
5313 * Try to charge @page to the memcg that @mm belongs to, reclaiming
5314 * pages according to @gfp_mask if necessary.
5315 *
5316 * Returns 0 on success, with *@memcgp pointing to the charged memcg.
5317 * Otherwise, an error code is returned.
5318 *
5319 * After page->mapping has been set up, the caller must finalize the
5320 * charge with mem_cgroup_commit_charge(). Or abort the transaction
5321 * with mem_cgroup_cancel_charge() in case page instantiation fails.
5322 */
5323int mem_cgroup_try_charge(struct page *page, struct mm_struct *mm,
5324 gfp_t gfp_mask, struct mem_cgroup **memcgp)
5325{
5326 struct mem_cgroup *memcg = NULL;
5327 unsigned int nr_pages = 1;
5328 int ret = 0;
5329
5330 if (mem_cgroup_disabled())
5331 goto out;
5332
5333 if (PageSwapCache(page)) {
00501b53
JW
5334 /*
5335 * Every swap fault against a single page tries to charge the
5336 * page, bail as early as possible. shmem_unuse() encounters
5337 * already charged pages, too. The USED bit is protected by
5338 * the page lock, which serializes swap cache removal, which
5339 * in turn serializes uncharging.
5340 */
e993d905 5341 VM_BUG_ON_PAGE(!PageLocked(page), page);
1306a85a 5342 if (page->mem_cgroup)
00501b53 5343 goto out;
e993d905
VD
5344
5345 if (do_swap_account) {
5346 swp_entry_t ent = { .val = page_private(page), };
5347 unsigned short id = lookup_swap_cgroup_id(ent);
5348
5349 rcu_read_lock();
5350 memcg = mem_cgroup_from_id(id);
5351 if (memcg && !css_tryget_online(&memcg->css))
5352 memcg = NULL;
5353 rcu_read_unlock();
5354 }
00501b53
JW
5355 }
5356
5357 if (PageTransHuge(page)) {
5358 nr_pages <<= compound_order(page);
5359 VM_BUG_ON_PAGE(!PageTransHuge(page), page);
5360 }
5361
00501b53
JW
5362 if (!memcg)
5363 memcg = get_mem_cgroup_from_mm(mm);
5364
5365 ret = try_charge(memcg, gfp_mask, nr_pages);
5366
5367 css_put(&memcg->css);
00501b53
JW
5368out:
5369 *memcgp = memcg;
5370 return ret;
5371}
5372
5373/**
5374 * mem_cgroup_commit_charge - commit a page charge
5375 * @page: page to charge
5376 * @memcg: memcg to charge the page to
5377 * @lrucare: page might be on LRU already
5378 *
5379 * Finalize a charge transaction started by mem_cgroup_try_charge(),
5380 * after page->mapping has been set up. This must happen atomically
5381 * as part of the page instantiation, i.e. under the page table lock
5382 * for anonymous pages, under the page lock for page and swap cache.
5383 *
5384 * In addition, the page must not be on the LRU during the commit, to
5385 * prevent racing with task migration. If it might be, use @lrucare.
5386 *
5387 * Use mem_cgroup_cancel_charge() to cancel the transaction instead.
5388 */
5389void mem_cgroup_commit_charge(struct page *page, struct mem_cgroup *memcg,
5390 bool lrucare)
5391{
5392 unsigned int nr_pages = 1;
5393
5394 VM_BUG_ON_PAGE(!page->mapping, page);
5395 VM_BUG_ON_PAGE(PageLRU(page) && !lrucare, page);
5396
5397 if (mem_cgroup_disabled())
5398 return;
5399 /*
5400 * Swap faults will attempt to charge the same page multiple
5401 * times. But reuse_swap_page() might have removed the page
5402 * from swapcache already, so we can't check PageSwapCache().
5403 */
5404 if (!memcg)
5405 return;
5406
6abb5a86
JW
5407 commit_charge(page, memcg, lrucare);
5408
00501b53
JW
5409 if (PageTransHuge(page)) {
5410 nr_pages <<= compound_order(page);
5411 VM_BUG_ON_PAGE(!PageTransHuge(page), page);
5412 }
5413
6abb5a86
JW
5414 local_irq_disable();
5415 mem_cgroup_charge_statistics(memcg, page, nr_pages);
5416 memcg_check_events(memcg, page);
5417 local_irq_enable();
00501b53
JW
5418
5419 if (do_swap_account && PageSwapCache(page)) {
5420 swp_entry_t entry = { .val = page_private(page) };
5421 /*
5422 * The swap entry might not get freed for a long time,
5423 * let's not wait for it. The page already received a
5424 * memory+swap charge, drop the swap entry duplicate.
5425 */
5426 mem_cgroup_uncharge_swap(entry);
5427 }
5428}
5429
5430/**
5431 * mem_cgroup_cancel_charge - cancel a page charge
5432 * @page: page to charge
5433 * @memcg: memcg to charge the page to
5434 *
5435 * Cancel a charge transaction started by mem_cgroup_try_charge().
5436 */
5437void mem_cgroup_cancel_charge(struct page *page, struct mem_cgroup *memcg)
5438{
5439 unsigned int nr_pages = 1;
5440
5441 if (mem_cgroup_disabled())
5442 return;
5443 /*
5444 * Swap faults will attempt to charge the same page multiple
5445 * times. But reuse_swap_page() might have removed the page
5446 * from swapcache already, so we can't check PageSwapCache().
5447 */
5448 if (!memcg)
5449 return;
5450
5451 if (PageTransHuge(page)) {
5452 nr_pages <<= compound_order(page);
5453 VM_BUG_ON_PAGE(!PageTransHuge(page), page);
5454 }
5455
5456 cancel_charge(memcg, nr_pages);
5457}
5458
747db954 5459static void uncharge_batch(struct mem_cgroup *memcg, unsigned long pgpgout,
747db954
JW
5460 unsigned long nr_anon, unsigned long nr_file,
5461 unsigned long nr_huge, struct page *dummy_page)
5462{
18eca2e6 5463 unsigned long nr_pages = nr_anon + nr_file;
747db954
JW
5464 unsigned long flags;
5465
ce00a967 5466 if (!mem_cgroup_is_root(memcg)) {
18eca2e6
JW
5467 page_counter_uncharge(&memcg->memory, nr_pages);
5468 if (do_swap_account)
5469 page_counter_uncharge(&memcg->memsw, nr_pages);
ce00a967
JW
5470 memcg_oom_recover(memcg);
5471 }
747db954
JW
5472
5473 local_irq_save(flags);
5474 __this_cpu_sub(memcg->stat->count[MEM_CGROUP_STAT_RSS], nr_anon);
5475 __this_cpu_sub(memcg->stat->count[MEM_CGROUP_STAT_CACHE], nr_file);
5476 __this_cpu_sub(memcg->stat->count[MEM_CGROUP_STAT_RSS_HUGE], nr_huge);
5477 __this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGOUT], pgpgout);
18eca2e6 5478 __this_cpu_add(memcg->stat->nr_page_events, nr_pages);
747db954
JW
5479 memcg_check_events(memcg, dummy_page);
5480 local_irq_restore(flags);
e8ea14cc
JW
5481
5482 if (!mem_cgroup_is_root(memcg))
18eca2e6 5483 css_put_many(&memcg->css, nr_pages);
747db954
JW
5484}
5485
5486static void uncharge_list(struct list_head *page_list)
5487{
5488 struct mem_cgroup *memcg = NULL;
747db954
JW
5489 unsigned long nr_anon = 0;
5490 unsigned long nr_file = 0;
5491 unsigned long nr_huge = 0;
5492 unsigned long pgpgout = 0;
747db954
JW
5493 struct list_head *next;
5494 struct page *page;
5495
5496 next = page_list->next;
5497 do {
5498 unsigned int nr_pages = 1;
747db954
JW
5499
5500 page = list_entry(next, struct page, lru);
5501 next = page->lru.next;
5502
5503 VM_BUG_ON_PAGE(PageLRU(page), page);
5504 VM_BUG_ON_PAGE(page_count(page), page);
5505
1306a85a 5506 if (!page->mem_cgroup)
747db954
JW
5507 continue;
5508
5509 /*
5510 * Nobody should be changing or seriously looking at
1306a85a 5511 * page->mem_cgroup at this point, we have fully
29833315 5512 * exclusive access to the page.
747db954
JW
5513 */
5514
1306a85a 5515 if (memcg != page->mem_cgroup) {
747db954 5516 if (memcg) {
18eca2e6
JW
5517 uncharge_batch(memcg, pgpgout, nr_anon, nr_file,
5518 nr_huge, page);
5519 pgpgout = nr_anon = nr_file = nr_huge = 0;
747db954 5520 }
1306a85a 5521 memcg = page->mem_cgroup;
747db954
JW
5522 }
5523
5524 if (PageTransHuge(page)) {
5525 nr_pages <<= compound_order(page);
5526 VM_BUG_ON_PAGE(!PageTransHuge(page), page);
5527 nr_huge += nr_pages;
5528 }
5529
5530 if (PageAnon(page))
5531 nr_anon += nr_pages;
5532 else
5533 nr_file += nr_pages;
5534
1306a85a 5535 page->mem_cgroup = NULL;
747db954
JW
5536
5537 pgpgout++;
5538 } while (next != page_list);
5539
5540 if (memcg)
18eca2e6
JW
5541 uncharge_batch(memcg, pgpgout, nr_anon, nr_file,
5542 nr_huge, page);
747db954
JW
5543}
5544
0a31bc97
JW
5545/**
5546 * mem_cgroup_uncharge - uncharge a page
5547 * @page: page to uncharge
5548 *
5549 * Uncharge a page previously charged with mem_cgroup_try_charge() and
5550 * mem_cgroup_commit_charge().
5551 */
5552void mem_cgroup_uncharge(struct page *page)
5553{
0a31bc97
JW
5554 if (mem_cgroup_disabled())
5555 return;
5556
747db954 5557 /* Don't touch page->lru of any random page, pre-check: */
1306a85a 5558 if (!page->mem_cgroup)
0a31bc97
JW
5559 return;
5560
747db954
JW
5561 INIT_LIST_HEAD(&page->lru);
5562 uncharge_list(&page->lru);
5563}
0a31bc97 5564
747db954
JW
5565/**
5566 * mem_cgroup_uncharge_list - uncharge a list of page
5567 * @page_list: list of pages to uncharge
5568 *
5569 * Uncharge a list of pages previously charged with
5570 * mem_cgroup_try_charge() and mem_cgroup_commit_charge().
5571 */
5572void mem_cgroup_uncharge_list(struct list_head *page_list)
5573{
5574 if (mem_cgroup_disabled())
5575 return;
0a31bc97 5576
747db954
JW
5577 if (!list_empty(page_list))
5578 uncharge_list(page_list);
0a31bc97
JW
5579}
5580
5581/**
45637bab 5582 * mem_cgroup_replace_page - migrate a charge to another page
0a31bc97
JW
5583 * @oldpage: currently charged page
5584 * @newpage: page to transfer the charge to
0a31bc97
JW
5585 *
5586 * Migrate the charge from @oldpage to @newpage.
5587 *
5588 * Both pages must be locked, @newpage->mapping must be set up.
25be6a65 5589 * Either or both pages might be on the LRU already.
0a31bc97 5590 */
45637bab 5591void mem_cgroup_replace_page(struct page *oldpage, struct page *newpage)
0a31bc97 5592{
29833315 5593 struct mem_cgroup *memcg;
0a31bc97
JW
5594 int isolated;
5595
5596 VM_BUG_ON_PAGE(!PageLocked(oldpage), oldpage);
5597 VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
0a31bc97 5598 VM_BUG_ON_PAGE(PageAnon(oldpage) != PageAnon(newpage), newpage);
6abb5a86
JW
5599 VM_BUG_ON_PAGE(PageTransHuge(oldpage) != PageTransHuge(newpage),
5600 newpage);
0a31bc97
JW
5601
5602 if (mem_cgroup_disabled())
5603 return;
5604
5605 /* Page cache replacement: new page already charged? */
1306a85a 5606 if (newpage->mem_cgroup)
0a31bc97
JW
5607 return;
5608
45637bab 5609 /* Swapcache readahead pages can get replaced before being charged */
1306a85a 5610 memcg = oldpage->mem_cgroup;
29833315 5611 if (!memcg)
0a31bc97
JW
5612 return;
5613
45637bab 5614 lock_page_lru(oldpage, &isolated);
1306a85a 5615 oldpage->mem_cgroup = NULL;
45637bab 5616 unlock_page_lru(oldpage, isolated);
0a31bc97 5617
45637bab 5618 commit_charge(newpage, memcg, true);
0a31bc97
JW
5619}
5620
2d11085e 5621/*
1081312f
MH
5622 * subsys_initcall() for memory controller.
5623 *
5624 * Some parts like hotcpu_notifier() have to be initialized from this context
5625 * because of lock dependencies (cgroup_lock -> cpu hotplug) but basically
5626 * everything that doesn't depend on a specific mem_cgroup structure should
5627 * be initialized from here.
2d11085e
MH
5628 */
5629static int __init mem_cgroup_init(void)
5630{
95a045f6
JW
5631 int cpu, node;
5632
2d11085e 5633 hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
95a045f6
JW
5634
5635 for_each_possible_cpu(cpu)
5636 INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
5637 drain_local_stock);
5638
5639 for_each_node(node) {
5640 struct mem_cgroup_tree_per_node *rtpn;
5641 int zone;
5642
5643 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL,
5644 node_online(node) ? node : NUMA_NO_NODE);
5645
5646 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
5647 struct mem_cgroup_tree_per_zone *rtpz;
5648
5649 rtpz = &rtpn->rb_tree_per_zone[zone];
5650 rtpz->rb_root = RB_ROOT;
5651 spin_lock_init(&rtpz->lock);
5652 }
5653 soft_limit_tree.rb_tree_per_node[node] = rtpn;
5654 }
5655
2d11085e
MH
5656 return 0;
5657}
5658subsys_initcall(mem_cgroup_init);
21afa38e
JW
5659
5660#ifdef CONFIG_MEMCG_SWAP
5661/**
5662 * mem_cgroup_swapout - transfer a memsw charge to swap
5663 * @page: page whose memsw charge to transfer
5664 * @entry: swap entry to move the charge to
5665 *
5666 * Transfer the memsw charge of @page to @entry.
5667 */
5668void mem_cgroup_swapout(struct page *page, swp_entry_t entry)
5669{
5670 struct mem_cgroup *memcg;
5671 unsigned short oldid;
5672
5673 VM_BUG_ON_PAGE(PageLRU(page), page);
5674 VM_BUG_ON_PAGE(page_count(page), page);
5675
5676 if (!do_swap_account)
5677 return;
5678
5679 memcg = page->mem_cgroup;
5680
5681 /* Readahead page, never charged */
5682 if (!memcg)
5683 return;
5684
5685 oldid = swap_cgroup_record(entry, mem_cgroup_id(memcg));
5686 VM_BUG_ON_PAGE(oldid, page);
5687 mem_cgroup_swap_statistics(memcg, true);
5688
5689 page->mem_cgroup = NULL;
5690
5691 if (!mem_cgroup_is_root(memcg))
5692 page_counter_uncharge(&memcg->memory, 1);
5693
ce9ce665
SAS
5694 /*
5695 * Interrupts should be disabled here because the caller holds the
5696 * mapping->tree_lock lock which is taken with interrupts-off. It is
5697 * important here to have the interrupts disabled because it is the
5698 * only synchronisation we have for udpating the per-CPU variables.
5699 */
5700 VM_BUG_ON(!irqs_disabled());
21afa38e
JW
5701 mem_cgroup_charge_statistics(memcg, page, -1);
5702 memcg_check_events(memcg, page);
5703}
5704
5705/**
5706 * mem_cgroup_uncharge_swap - uncharge a swap entry
5707 * @entry: swap entry to uncharge
5708 *
5709 * Drop the memsw charge associated with @entry.
5710 */
5711void mem_cgroup_uncharge_swap(swp_entry_t entry)
5712{
5713 struct mem_cgroup *memcg;
5714 unsigned short id;
5715
5716 if (!do_swap_account)
5717 return;
5718
5719 id = swap_cgroup_record(entry, 0);
5720 rcu_read_lock();
adbe427b 5721 memcg = mem_cgroup_from_id(id);
21afa38e
JW
5722 if (memcg) {
5723 if (!mem_cgroup_is_root(memcg))
5724 page_counter_uncharge(&memcg->memsw, 1);
5725 mem_cgroup_swap_statistics(memcg, false);
5726 css_put(&memcg->css);
5727 }
5728 rcu_read_unlock();
5729}
5730
5731/* for remember boot option*/
5732#ifdef CONFIG_MEMCG_SWAP_ENABLED
5733static int really_do_swap_account __initdata = 1;
5734#else
5735static int really_do_swap_account __initdata;
5736#endif
5737
5738static int __init enable_swap_account(char *s)
5739{
5740 if (!strcmp(s, "1"))
5741 really_do_swap_account = 1;
5742 else if (!strcmp(s, "0"))
5743 really_do_swap_account = 0;
5744 return 1;
5745}
5746__setup("swapaccount=", enable_swap_account);
5747
5748static struct cftype memsw_cgroup_files[] = {
5749 {
5750 .name = "memsw.usage_in_bytes",
5751 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
5752 .read_u64 = mem_cgroup_read_u64,
5753 },
5754 {
5755 .name = "memsw.max_usage_in_bytes",
5756 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
5757 .write = mem_cgroup_reset,
5758 .read_u64 = mem_cgroup_read_u64,
5759 },
5760 {
5761 .name = "memsw.limit_in_bytes",
5762 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
5763 .write = mem_cgroup_write,
5764 .read_u64 = mem_cgroup_read_u64,
5765 },
5766 {
5767 .name = "memsw.failcnt",
5768 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
5769 .write = mem_cgroup_reset,
5770 .read_u64 = mem_cgroup_read_u64,
5771 },
5772 { }, /* terminate */
5773};
5774
5775static int __init mem_cgroup_swap_init(void)
5776{
5777 if (!mem_cgroup_disabled() && really_do_swap_account) {
5778 do_swap_account = 1;
5779 WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys,
5780 memsw_cgroup_files));
5781 }
5782 return 0;
5783}
5784subsys_initcall(mem_cgroup_swap_init);
5785
5786#endif /* CONFIG_MEMCG_SWAP */