]> git.proxmox.com Git - mirror_ubuntu-hirsute-kernel.git/blame - mm/memcontrol.c
mm: memcg/slab: obj_cgroup API
[mirror_ubuntu-hirsute-kernel.git] / mm / memcontrol.c
CommitLineData
c942fddf 1// SPDX-License-Identifier: GPL-2.0-or-later
8cdea7c0
BS
2/* memcontrol.c - Memory Controller
3 *
4 * Copyright IBM Corporation, 2007
5 * Author Balbir Singh <balbir@linux.vnet.ibm.com>
6 *
78fb7466
PE
7 * Copyright 2007 OpenVZ SWsoft Inc
8 * Author: Pavel Emelianov <xemul@openvz.org>
9 *
2e72b634
KS
10 * Memory thresholds
11 * Copyright (C) 2009 Nokia Corporation
12 * Author: Kirill A. Shutemov
13 *
7ae1e1d0
GC
14 * Kernel Memory Controller
15 * Copyright (C) 2012 Parallels Inc. and Google Inc.
16 * Authors: Glauber Costa and Suleiman Souhlal
17 *
1575e68b
JW
18 * Native page reclaim
19 * Charge lifetime sanitation
20 * Lockless page tracking & accounting
21 * Unified hierarchy configuration model
22 * Copyright (C) 2015 Red Hat, Inc., Johannes Weiner
8cdea7c0
BS
23 */
24
3e32cb2e 25#include <linux/page_counter.h>
8cdea7c0
BS
26#include <linux/memcontrol.h>
27#include <linux/cgroup.h>
a520110e 28#include <linux/pagewalk.h>
6e84f315 29#include <linux/sched/mm.h>
3a4f8a0b 30#include <linux/shmem_fs.h>
4ffef5fe 31#include <linux/hugetlb.h>
d13d1443 32#include <linux/pagemap.h>
1ff9e6e1 33#include <linux/vm_event_item.h>
d52aa412 34#include <linux/smp.h>
8a9f3ccd 35#include <linux/page-flags.h>
66e1707b 36#include <linux/backing-dev.h>
8a9f3ccd
BS
37#include <linux/bit_spinlock.h>
38#include <linux/rcupdate.h>
e222432b 39#include <linux/limits.h>
b9e15baf 40#include <linux/export.h>
8c7c6e34 41#include <linux/mutex.h>
bb4cc1a8 42#include <linux/rbtree.h>
b6ac57d5 43#include <linux/slab.h>
66e1707b 44#include <linux/swap.h>
02491447 45#include <linux/swapops.h>
66e1707b 46#include <linux/spinlock.h>
2e72b634 47#include <linux/eventfd.h>
79bd9814 48#include <linux/poll.h>
2e72b634 49#include <linux/sort.h>
66e1707b 50#include <linux/fs.h>
d2ceb9b7 51#include <linux/seq_file.h>
70ddf637 52#include <linux/vmpressure.h>
b69408e8 53#include <linux/mm_inline.h>
5d1ea48b 54#include <linux/swap_cgroup.h>
cdec2e42 55#include <linux/cpu.h>
158e0a2d 56#include <linux/oom.h>
0056f4e6 57#include <linux/lockdep.h>
79bd9814 58#include <linux/file.h>
b23afb93 59#include <linux/tracehook.h>
0e4b01df 60#include <linux/psi.h>
c8713d0b 61#include <linux/seq_buf.h>
08e552c6 62#include "internal.h"
d1a4c0b3 63#include <net/sock.h>
4bd2c1ee 64#include <net/ip.h>
f35c3a8e 65#include "slab.h"
8cdea7c0 66
7c0f6ba6 67#include <linux/uaccess.h>
8697d331 68
cc8e970c
KM
69#include <trace/events/vmscan.h>
70
073219e9
TH
71struct cgroup_subsys memory_cgrp_subsys __read_mostly;
72EXPORT_SYMBOL(memory_cgrp_subsys);
68ae564b 73
7d828602
JW
74struct mem_cgroup *root_mem_cgroup __read_mostly;
75
a181b0e8 76#define MEM_CGROUP_RECLAIM_RETRIES 5
8cdea7c0 77
f7e1cb6e
JW
78/* Socket memory accounting disabled? */
79static bool cgroup_memory_nosocket;
80
04823c83
VD
81/* Kernel memory accounting disabled? */
82static bool cgroup_memory_nokmem;
83
21afa38e 84/* Whether the swap controller is active */
c255a458 85#ifdef CONFIG_MEMCG_SWAP
eccb52e7 86bool cgroup_memory_noswap __read_mostly;
c077719b 87#else
eccb52e7 88#define cgroup_memory_noswap 1
2d1c4980 89#endif
c077719b 90
97b27821
TH
91#ifdef CONFIG_CGROUP_WRITEBACK
92static DECLARE_WAIT_QUEUE_HEAD(memcg_cgwb_frn_waitq);
93#endif
94
7941d214
JW
95/* Whether legacy memory+swap accounting is active */
96static bool do_memsw_account(void)
97{
eccb52e7 98 return !cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_noswap;
7941d214
JW
99}
100
a0db00fc
KS
101#define THRESHOLDS_EVENTS_TARGET 128
102#define SOFTLIMIT_EVENTS_TARGET 1024
e9f8974f 103
bb4cc1a8
AM
104/*
105 * Cgroups above their limits are maintained in a RB-Tree, independent of
106 * their hierarchy representation
107 */
108
ef8f2327 109struct mem_cgroup_tree_per_node {
bb4cc1a8 110 struct rb_root rb_root;
fa90b2fd 111 struct rb_node *rb_rightmost;
bb4cc1a8
AM
112 spinlock_t lock;
113};
114
bb4cc1a8
AM
115struct mem_cgroup_tree {
116 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
117};
118
119static struct mem_cgroup_tree soft_limit_tree __read_mostly;
120
9490ff27
KH
121/* for OOM */
122struct mem_cgroup_eventfd_list {
123 struct list_head list;
124 struct eventfd_ctx *eventfd;
125};
2e72b634 126
79bd9814
TH
127/*
128 * cgroup_event represents events which userspace want to receive.
129 */
3bc942f3 130struct mem_cgroup_event {
79bd9814 131 /*
59b6f873 132 * memcg which the event belongs to.
79bd9814 133 */
59b6f873 134 struct mem_cgroup *memcg;
79bd9814
TH
135 /*
136 * eventfd to signal userspace about the event.
137 */
138 struct eventfd_ctx *eventfd;
139 /*
140 * Each of these stored in a list by the cgroup.
141 */
142 struct list_head list;
fba94807
TH
143 /*
144 * register_event() callback will be used to add new userspace
145 * waiter for changes related to this event. Use eventfd_signal()
146 * on eventfd to send notification to userspace.
147 */
59b6f873 148 int (*register_event)(struct mem_cgroup *memcg,
347c4a87 149 struct eventfd_ctx *eventfd, const char *args);
fba94807
TH
150 /*
151 * unregister_event() callback will be called when userspace closes
152 * the eventfd or on cgroup removing. This callback must be set,
153 * if you want provide notification functionality.
154 */
59b6f873 155 void (*unregister_event)(struct mem_cgroup *memcg,
fba94807 156 struct eventfd_ctx *eventfd);
79bd9814
TH
157 /*
158 * All fields below needed to unregister event when
159 * userspace closes eventfd.
160 */
161 poll_table pt;
162 wait_queue_head_t *wqh;
ac6424b9 163 wait_queue_entry_t wait;
79bd9814
TH
164 struct work_struct remove;
165};
166
c0ff4b85
R
167static void mem_cgroup_threshold(struct mem_cgroup *memcg);
168static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
2e72b634 169
7dc74be0
DN
170/* Stuffs for move charges at task migration. */
171/*
1dfab5ab 172 * Types of charges to be moved.
7dc74be0 173 */
1dfab5ab
JW
174#define MOVE_ANON 0x1U
175#define MOVE_FILE 0x2U
176#define MOVE_MASK (MOVE_ANON | MOVE_FILE)
7dc74be0 177
4ffef5fe
DN
178/* "mc" and its members are protected by cgroup_mutex */
179static struct move_charge_struct {
b1dd693e 180 spinlock_t lock; /* for from, to */
264a0ae1 181 struct mm_struct *mm;
4ffef5fe
DN
182 struct mem_cgroup *from;
183 struct mem_cgroup *to;
1dfab5ab 184 unsigned long flags;
4ffef5fe 185 unsigned long precharge;
854ffa8d 186 unsigned long moved_charge;
483c30b5 187 unsigned long moved_swap;
8033b97c
DN
188 struct task_struct *moving_task; /* a task moving charges */
189 wait_queue_head_t waitq; /* a waitq for other context */
190} mc = {
2bd9bb20 191 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
8033b97c
DN
192 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
193};
4ffef5fe 194
4e416953
BS
195/*
196 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
197 * limit reclaim to prevent infinite loops, if they ever occur.
198 */
a0db00fc 199#define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
bb4cc1a8 200#define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
4e416953 201
217bc319
KH
202enum charge_type {
203 MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
41326c17 204 MEM_CGROUP_CHARGE_TYPE_ANON,
d13d1443 205 MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
8a9478ca 206 MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
c05555b5
KH
207 NR_CHARGE_TYPE,
208};
209
8c7c6e34 210/* for encoding cft->private value on file */
86ae53e1
GC
211enum res_type {
212 _MEM,
213 _MEMSWAP,
214 _OOM_TYPE,
510fc4e1 215 _KMEM,
d55f90bf 216 _TCP,
86ae53e1
GC
217};
218
a0db00fc
KS
219#define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
220#define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
8c7c6e34 221#define MEMFILE_ATTR(val) ((val) & 0xffff)
9490ff27
KH
222/* Used for OOM nofiier */
223#define OOM_CONTROL (0)
8c7c6e34 224
b05706f1
KT
225/*
226 * Iteration constructs for visiting all cgroups (under a tree). If
227 * loops are exited prematurely (break), mem_cgroup_iter_break() must
228 * be used for reference counting.
229 */
230#define for_each_mem_cgroup_tree(iter, root) \
231 for (iter = mem_cgroup_iter(root, NULL, NULL); \
232 iter != NULL; \
233 iter = mem_cgroup_iter(root, iter, NULL))
234
235#define for_each_mem_cgroup(iter) \
236 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
237 iter != NULL; \
238 iter = mem_cgroup_iter(NULL, iter, NULL))
239
7775face
TH
240static inline bool should_force_charge(void)
241{
242 return tsk_is_oom_victim(current) || fatal_signal_pending(current) ||
243 (current->flags & PF_EXITING);
244}
245
70ddf637
AV
246/* Some nice accessors for the vmpressure. */
247struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
248{
249 if (!memcg)
250 memcg = root_mem_cgroup;
251 return &memcg->vmpressure;
252}
253
254struct cgroup_subsys_state *vmpressure_to_css(struct vmpressure *vmpr)
255{
256 return &container_of(vmpr, struct mem_cgroup, vmpressure)->css;
257}
258
84c07d11 259#ifdef CONFIG_MEMCG_KMEM
bf4f0599
RG
260extern spinlock_t css_set_lock;
261
262static void obj_cgroup_release(struct percpu_ref *ref)
263{
264 struct obj_cgroup *objcg = container_of(ref, struct obj_cgroup, refcnt);
265 struct mem_cgroup *memcg;
266 unsigned int nr_bytes;
267 unsigned int nr_pages;
268 unsigned long flags;
269
270 /*
271 * At this point all allocated objects are freed, and
272 * objcg->nr_charged_bytes can't have an arbitrary byte value.
273 * However, it can be PAGE_SIZE or (x * PAGE_SIZE).
274 *
275 * The following sequence can lead to it:
276 * 1) CPU0: objcg == stock->cached_objcg
277 * 2) CPU1: we do a small allocation (e.g. 92 bytes),
278 * PAGE_SIZE bytes are charged
279 * 3) CPU1: a process from another memcg is allocating something,
280 * the stock if flushed,
281 * objcg->nr_charged_bytes = PAGE_SIZE - 92
282 * 5) CPU0: we do release this object,
283 * 92 bytes are added to stock->nr_bytes
284 * 6) CPU0: stock is flushed,
285 * 92 bytes are added to objcg->nr_charged_bytes
286 *
287 * In the result, nr_charged_bytes == PAGE_SIZE.
288 * This page will be uncharged in obj_cgroup_release().
289 */
290 nr_bytes = atomic_read(&objcg->nr_charged_bytes);
291 WARN_ON_ONCE(nr_bytes & (PAGE_SIZE - 1));
292 nr_pages = nr_bytes >> PAGE_SHIFT;
293
294 spin_lock_irqsave(&css_set_lock, flags);
295 memcg = obj_cgroup_memcg(objcg);
296 if (nr_pages)
297 __memcg_kmem_uncharge(memcg, nr_pages);
298 list_del(&objcg->list);
299 mem_cgroup_put(memcg);
300 spin_unlock_irqrestore(&css_set_lock, flags);
301
302 percpu_ref_exit(ref);
303 kfree_rcu(objcg, rcu);
304}
305
306static struct obj_cgroup *obj_cgroup_alloc(void)
307{
308 struct obj_cgroup *objcg;
309 int ret;
310
311 objcg = kzalloc(sizeof(struct obj_cgroup), GFP_KERNEL);
312 if (!objcg)
313 return NULL;
314
315 ret = percpu_ref_init(&objcg->refcnt, obj_cgroup_release, 0,
316 GFP_KERNEL);
317 if (ret) {
318 kfree(objcg);
319 return NULL;
320 }
321 INIT_LIST_HEAD(&objcg->list);
322 return objcg;
323}
324
325static void memcg_reparent_objcgs(struct mem_cgroup *memcg,
326 struct mem_cgroup *parent)
327{
328 struct obj_cgroup *objcg, *iter;
329
330 objcg = rcu_replace_pointer(memcg->objcg, NULL, true);
331
332 spin_lock_irq(&css_set_lock);
333
334 /* Move active objcg to the parent's list */
335 xchg(&objcg->memcg, parent);
336 css_get(&parent->css);
337 list_add(&objcg->list, &parent->objcg_list);
338
339 /* Move already reparented objcgs to the parent's list */
340 list_for_each_entry(iter, &memcg->objcg_list, list) {
341 css_get(&parent->css);
342 xchg(&iter->memcg, parent);
343 css_put(&memcg->css);
344 }
345 list_splice(&memcg->objcg_list, &parent->objcg_list);
346
347 spin_unlock_irq(&css_set_lock);
348
349 percpu_ref_kill(&objcg->refcnt);
350}
351
55007d84 352/*
f7ce3190 353 * This will be the memcg's index in each cache's ->memcg_params.memcg_caches.
b8627835
LZ
354 * The main reason for not using cgroup id for this:
355 * this works better in sparse environments, where we have a lot of memcgs,
356 * but only a few kmem-limited. Or also, if we have, for instance, 200
357 * memcgs, and none but the 200th is kmem-limited, we'd have to have a
358 * 200 entry array for that.
55007d84 359 *
dbcf73e2
VD
360 * The current size of the caches array is stored in memcg_nr_cache_ids. It
361 * will double each time we have to increase it.
55007d84 362 */
dbcf73e2
VD
363static DEFINE_IDA(memcg_cache_ida);
364int memcg_nr_cache_ids;
749c5415 365
05257a1a
VD
366/* Protects memcg_nr_cache_ids */
367static DECLARE_RWSEM(memcg_cache_ids_sem);
368
369void memcg_get_cache_ids(void)
370{
371 down_read(&memcg_cache_ids_sem);
372}
373
374void memcg_put_cache_ids(void)
375{
376 up_read(&memcg_cache_ids_sem);
377}
378
55007d84
GC
379/*
380 * MIN_SIZE is different than 1, because we would like to avoid going through
381 * the alloc/free process all the time. In a small machine, 4 kmem-limited
382 * cgroups is a reasonable guess. In the future, it could be a parameter or
383 * tunable, but that is strictly not necessary.
384 *
b8627835 385 * MAX_SIZE should be as large as the number of cgrp_ids. Ideally, we could get
55007d84
GC
386 * this constant directly from cgroup, but it is understandable that this is
387 * better kept as an internal representation in cgroup.c. In any case, the
b8627835 388 * cgrp_id space is not getting any smaller, and we don't have to necessarily
55007d84
GC
389 * increase ours as well if it increases.
390 */
391#define MEMCG_CACHES_MIN_SIZE 4
b8627835 392#define MEMCG_CACHES_MAX_SIZE MEM_CGROUP_ID_MAX
55007d84 393
d7f25f8a
GC
394/*
395 * A lot of the calls to the cache allocation functions are expected to be
396 * inlined by the compiler. Since the calls to memcg_kmem_get_cache are
397 * conditional to this static branch, we'll have to allow modules that does
398 * kmem_cache_alloc and the such to see this symbol as well
399 */
ef12947c 400DEFINE_STATIC_KEY_FALSE(memcg_kmem_enabled_key);
d7f25f8a 401EXPORT_SYMBOL(memcg_kmem_enabled_key);
a8964b9b 402
17cc4dfe 403struct workqueue_struct *memcg_kmem_cache_wq;
0a432dcb 404#endif
17cc4dfe 405
0a4465d3
KT
406static int memcg_shrinker_map_size;
407static DEFINE_MUTEX(memcg_shrinker_map_mutex);
408
409static void memcg_free_shrinker_map_rcu(struct rcu_head *head)
410{
411 kvfree(container_of(head, struct memcg_shrinker_map, rcu));
412}
413
414static int memcg_expand_one_shrinker_map(struct mem_cgroup *memcg,
415 int size, int old_size)
416{
417 struct memcg_shrinker_map *new, *old;
418 int nid;
419
420 lockdep_assert_held(&memcg_shrinker_map_mutex);
421
422 for_each_node(nid) {
423 old = rcu_dereference_protected(
424 mem_cgroup_nodeinfo(memcg, nid)->shrinker_map, true);
425 /* Not yet online memcg */
426 if (!old)
427 return 0;
428
86daf94e 429 new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
0a4465d3
KT
430 if (!new)
431 return -ENOMEM;
432
433 /* Set all old bits, clear all new bits */
434 memset(new->map, (int)0xff, old_size);
435 memset((void *)new->map + old_size, 0, size - old_size);
436
437 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_map, new);
438 call_rcu(&old->rcu, memcg_free_shrinker_map_rcu);
439 }
440
441 return 0;
442}
443
444static void memcg_free_shrinker_maps(struct mem_cgroup *memcg)
445{
446 struct mem_cgroup_per_node *pn;
447 struct memcg_shrinker_map *map;
448 int nid;
449
450 if (mem_cgroup_is_root(memcg))
451 return;
452
453 for_each_node(nid) {
454 pn = mem_cgroup_nodeinfo(memcg, nid);
455 map = rcu_dereference_protected(pn->shrinker_map, true);
456 if (map)
457 kvfree(map);
458 rcu_assign_pointer(pn->shrinker_map, NULL);
459 }
460}
461
462static int memcg_alloc_shrinker_maps(struct mem_cgroup *memcg)
463{
464 struct memcg_shrinker_map *map;
465 int nid, size, ret = 0;
466
467 if (mem_cgroup_is_root(memcg))
468 return 0;
469
470 mutex_lock(&memcg_shrinker_map_mutex);
471 size = memcg_shrinker_map_size;
472 for_each_node(nid) {
86daf94e 473 map = kvzalloc_node(sizeof(*map) + size, GFP_KERNEL, nid);
0a4465d3
KT
474 if (!map) {
475 memcg_free_shrinker_maps(memcg);
476 ret = -ENOMEM;
477 break;
478 }
479 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_map, map);
480 }
481 mutex_unlock(&memcg_shrinker_map_mutex);
482
483 return ret;
484}
485
486int memcg_expand_shrinker_maps(int new_id)
487{
488 int size, old_size, ret = 0;
489 struct mem_cgroup *memcg;
490
491 size = DIV_ROUND_UP(new_id + 1, BITS_PER_LONG) * sizeof(unsigned long);
492 old_size = memcg_shrinker_map_size;
493 if (size <= old_size)
494 return 0;
495
496 mutex_lock(&memcg_shrinker_map_mutex);
497 if (!root_mem_cgroup)
498 goto unlock;
499
500 for_each_mem_cgroup(memcg) {
501 if (mem_cgroup_is_root(memcg))
502 continue;
503 ret = memcg_expand_one_shrinker_map(memcg, size, old_size);
75866af6
VA
504 if (ret) {
505 mem_cgroup_iter_break(NULL, memcg);
0a4465d3 506 goto unlock;
75866af6 507 }
0a4465d3
KT
508 }
509unlock:
510 if (!ret)
511 memcg_shrinker_map_size = size;
512 mutex_unlock(&memcg_shrinker_map_mutex);
513 return ret;
514}
fae91d6d
KT
515
516void memcg_set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
517{
518 if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
519 struct memcg_shrinker_map *map;
520
521 rcu_read_lock();
522 map = rcu_dereference(memcg->nodeinfo[nid]->shrinker_map);
f90280d6
KT
523 /* Pairs with smp mb in shrink_slab() */
524 smp_mb__before_atomic();
fae91d6d
KT
525 set_bit(shrinker_id, map->map);
526 rcu_read_unlock();
527 }
528}
529
ad7fa852
TH
530/**
531 * mem_cgroup_css_from_page - css of the memcg associated with a page
532 * @page: page of interest
533 *
534 * If memcg is bound to the default hierarchy, css of the memcg associated
535 * with @page is returned. The returned css remains associated with @page
536 * until it is released.
537 *
538 * If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup
539 * is returned.
ad7fa852
TH
540 */
541struct cgroup_subsys_state *mem_cgroup_css_from_page(struct page *page)
542{
543 struct mem_cgroup *memcg;
544
ad7fa852
TH
545 memcg = page->mem_cgroup;
546
9e10a130 547 if (!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
ad7fa852
TH
548 memcg = root_mem_cgroup;
549
ad7fa852
TH
550 return &memcg->css;
551}
552
2fc04524
VD
553/**
554 * page_cgroup_ino - return inode number of the memcg a page is charged to
555 * @page: the page
556 *
557 * Look up the closest online ancestor of the memory cgroup @page is charged to
558 * and return its inode number or 0 if @page is not charged to any cgroup. It
559 * is safe to call this function without holding a reference to @page.
560 *
561 * Note, this function is inherently racy, because there is nothing to prevent
562 * the cgroup inode from getting torn down and potentially reallocated a moment
563 * after page_cgroup_ino() returns, so it only should be used by callers that
564 * do not care (such as procfs interfaces).
565 */
566ino_t page_cgroup_ino(struct page *page)
567{
568 struct mem_cgroup *memcg;
569 unsigned long ino = 0;
570
571 rcu_read_lock();
221ec5c0 572 if (PageSlab(page) && !PageTail(page))
4d96ba35
RG
573 memcg = memcg_from_slab_page(page);
574 else
575 memcg = READ_ONCE(page->mem_cgroup);
2fc04524
VD
576 while (memcg && !(memcg->css.flags & CSS_ONLINE))
577 memcg = parent_mem_cgroup(memcg);
578 if (memcg)
579 ino = cgroup_ino(memcg->css.cgroup);
580 rcu_read_unlock();
581 return ino;
582}
583
ef8f2327
MG
584static struct mem_cgroup_per_node *
585mem_cgroup_page_nodeinfo(struct mem_cgroup *memcg, struct page *page)
f64c3f54 586{
97a6c37b 587 int nid = page_to_nid(page);
f64c3f54 588
ef8f2327 589 return memcg->nodeinfo[nid];
f64c3f54
BS
590}
591
ef8f2327
MG
592static struct mem_cgroup_tree_per_node *
593soft_limit_tree_node(int nid)
bb4cc1a8 594{
ef8f2327 595 return soft_limit_tree.rb_tree_per_node[nid];
bb4cc1a8
AM
596}
597
ef8f2327 598static struct mem_cgroup_tree_per_node *
bb4cc1a8
AM
599soft_limit_tree_from_page(struct page *page)
600{
601 int nid = page_to_nid(page);
bb4cc1a8 602
ef8f2327 603 return soft_limit_tree.rb_tree_per_node[nid];
bb4cc1a8
AM
604}
605
ef8f2327
MG
606static void __mem_cgroup_insert_exceeded(struct mem_cgroup_per_node *mz,
607 struct mem_cgroup_tree_per_node *mctz,
3e32cb2e 608 unsigned long new_usage_in_excess)
bb4cc1a8
AM
609{
610 struct rb_node **p = &mctz->rb_root.rb_node;
611 struct rb_node *parent = NULL;
ef8f2327 612 struct mem_cgroup_per_node *mz_node;
fa90b2fd 613 bool rightmost = true;
bb4cc1a8
AM
614
615 if (mz->on_tree)
616 return;
617
618 mz->usage_in_excess = new_usage_in_excess;
619 if (!mz->usage_in_excess)
620 return;
621 while (*p) {
622 parent = *p;
ef8f2327 623 mz_node = rb_entry(parent, struct mem_cgroup_per_node,
bb4cc1a8 624 tree_node);
fa90b2fd 625 if (mz->usage_in_excess < mz_node->usage_in_excess) {
bb4cc1a8 626 p = &(*p)->rb_left;
fa90b2fd
DB
627 rightmost = false;
628 }
629
bb4cc1a8
AM
630 /*
631 * We can't avoid mem cgroups that are over their soft
632 * limit by the same amount
633 */
634 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
635 p = &(*p)->rb_right;
636 }
fa90b2fd
DB
637
638 if (rightmost)
639 mctz->rb_rightmost = &mz->tree_node;
640
bb4cc1a8
AM
641 rb_link_node(&mz->tree_node, parent, p);
642 rb_insert_color(&mz->tree_node, &mctz->rb_root);
643 mz->on_tree = true;
644}
645
ef8f2327
MG
646static void __mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
647 struct mem_cgroup_tree_per_node *mctz)
bb4cc1a8
AM
648{
649 if (!mz->on_tree)
650 return;
fa90b2fd
DB
651
652 if (&mz->tree_node == mctz->rb_rightmost)
653 mctz->rb_rightmost = rb_prev(&mz->tree_node);
654
bb4cc1a8
AM
655 rb_erase(&mz->tree_node, &mctz->rb_root);
656 mz->on_tree = false;
657}
658
ef8f2327
MG
659static void mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
660 struct mem_cgroup_tree_per_node *mctz)
bb4cc1a8 661{
0a31bc97
JW
662 unsigned long flags;
663
664 spin_lock_irqsave(&mctz->lock, flags);
cf2c8127 665 __mem_cgroup_remove_exceeded(mz, mctz);
0a31bc97 666 spin_unlock_irqrestore(&mctz->lock, flags);
bb4cc1a8
AM
667}
668
3e32cb2e
JW
669static unsigned long soft_limit_excess(struct mem_cgroup *memcg)
670{
671 unsigned long nr_pages = page_counter_read(&memcg->memory);
4db0c3c2 672 unsigned long soft_limit = READ_ONCE(memcg->soft_limit);
3e32cb2e
JW
673 unsigned long excess = 0;
674
675 if (nr_pages > soft_limit)
676 excess = nr_pages - soft_limit;
677
678 return excess;
679}
bb4cc1a8
AM
680
681static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
682{
3e32cb2e 683 unsigned long excess;
ef8f2327
MG
684 struct mem_cgroup_per_node *mz;
685 struct mem_cgroup_tree_per_node *mctz;
bb4cc1a8 686
e231875b 687 mctz = soft_limit_tree_from_page(page);
bfc7228b
LD
688 if (!mctz)
689 return;
bb4cc1a8
AM
690 /*
691 * Necessary to update all ancestors when hierarchy is used.
692 * because their event counter is not touched.
693 */
694 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
ef8f2327 695 mz = mem_cgroup_page_nodeinfo(memcg, page);
3e32cb2e 696 excess = soft_limit_excess(memcg);
bb4cc1a8
AM
697 /*
698 * We have to update the tree if mz is on RB-tree or
699 * mem is over its softlimit.
700 */
701 if (excess || mz->on_tree) {
0a31bc97
JW
702 unsigned long flags;
703
704 spin_lock_irqsave(&mctz->lock, flags);
bb4cc1a8
AM
705 /* if on-tree, remove it */
706 if (mz->on_tree)
cf2c8127 707 __mem_cgroup_remove_exceeded(mz, mctz);
bb4cc1a8
AM
708 /*
709 * Insert again. mz->usage_in_excess will be updated.
710 * If excess is 0, no tree ops.
711 */
cf2c8127 712 __mem_cgroup_insert_exceeded(mz, mctz, excess);
0a31bc97 713 spin_unlock_irqrestore(&mctz->lock, flags);
bb4cc1a8
AM
714 }
715 }
716}
717
718static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
719{
ef8f2327
MG
720 struct mem_cgroup_tree_per_node *mctz;
721 struct mem_cgroup_per_node *mz;
722 int nid;
bb4cc1a8 723
e231875b 724 for_each_node(nid) {
ef8f2327
MG
725 mz = mem_cgroup_nodeinfo(memcg, nid);
726 mctz = soft_limit_tree_node(nid);
bfc7228b
LD
727 if (mctz)
728 mem_cgroup_remove_exceeded(mz, mctz);
bb4cc1a8
AM
729 }
730}
731
ef8f2327
MG
732static struct mem_cgroup_per_node *
733__mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
bb4cc1a8 734{
ef8f2327 735 struct mem_cgroup_per_node *mz;
bb4cc1a8
AM
736
737retry:
738 mz = NULL;
fa90b2fd 739 if (!mctz->rb_rightmost)
bb4cc1a8
AM
740 goto done; /* Nothing to reclaim from */
741
fa90b2fd
DB
742 mz = rb_entry(mctz->rb_rightmost,
743 struct mem_cgroup_per_node, tree_node);
bb4cc1a8
AM
744 /*
745 * Remove the node now but someone else can add it back,
746 * we will to add it back at the end of reclaim to its correct
747 * position in the tree.
748 */
cf2c8127 749 __mem_cgroup_remove_exceeded(mz, mctz);
3e32cb2e 750 if (!soft_limit_excess(mz->memcg) ||
8965aa28 751 !css_tryget(&mz->memcg->css))
bb4cc1a8
AM
752 goto retry;
753done:
754 return mz;
755}
756
ef8f2327
MG
757static struct mem_cgroup_per_node *
758mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
bb4cc1a8 759{
ef8f2327 760 struct mem_cgroup_per_node *mz;
bb4cc1a8 761
0a31bc97 762 spin_lock_irq(&mctz->lock);
bb4cc1a8 763 mz = __mem_cgroup_largest_soft_limit_node(mctz);
0a31bc97 764 spin_unlock_irq(&mctz->lock);
bb4cc1a8
AM
765 return mz;
766}
767
db9adbcb
JW
768/**
769 * __mod_memcg_state - update cgroup memory statistics
770 * @memcg: the memory cgroup
771 * @idx: the stat item - can be enum memcg_stat_item or enum node_stat_item
772 * @val: delta to add to the counter, can be negative
773 */
774void __mod_memcg_state(struct mem_cgroup *memcg, int idx, int val)
775{
ea426c2a 776 long x, threshold = MEMCG_CHARGE_BATCH;
db9adbcb
JW
777
778 if (mem_cgroup_disabled())
779 return;
780
ea426c2a
RG
781 if (vmstat_item_in_bytes(idx))
782 threshold <<= PAGE_SHIFT;
783
db9adbcb 784 x = val + __this_cpu_read(memcg->vmstats_percpu->stat[idx]);
ea426c2a 785 if (unlikely(abs(x) > threshold)) {
42a30035
JW
786 struct mem_cgroup *mi;
787
766a4c19
YS
788 /*
789 * Batch local counters to keep them in sync with
790 * the hierarchical ones.
791 */
792 __this_cpu_add(memcg->vmstats_local->stat[idx], x);
42a30035
JW
793 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
794 atomic_long_add(x, &mi->vmstats[idx]);
db9adbcb
JW
795 x = 0;
796 }
797 __this_cpu_write(memcg->vmstats_percpu->stat[idx], x);
798}
799
42a30035
JW
800static struct mem_cgroup_per_node *
801parent_nodeinfo(struct mem_cgroup_per_node *pn, int nid)
802{
803 struct mem_cgroup *parent;
804
805 parent = parent_mem_cgroup(pn->memcg);
806 if (!parent)
807 return NULL;
808 return mem_cgroup_nodeinfo(parent, nid);
809}
810
eedc4e5a
RG
811void __mod_memcg_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
812 int val)
db9adbcb
JW
813{
814 struct mem_cgroup_per_node *pn;
42a30035 815 struct mem_cgroup *memcg;
ea426c2a 816 long x, threshold = MEMCG_CHARGE_BATCH;
db9adbcb 817
db9adbcb 818 pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
42a30035 819 memcg = pn->memcg;
db9adbcb
JW
820
821 /* Update memcg */
42a30035 822 __mod_memcg_state(memcg, idx, val);
db9adbcb 823
b4c46484
RG
824 /* Update lruvec */
825 __this_cpu_add(pn->lruvec_stat_local->count[idx], val);
826
ea426c2a
RG
827 if (vmstat_item_in_bytes(idx))
828 threshold <<= PAGE_SHIFT;
829
db9adbcb 830 x = val + __this_cpu_read(pn->lruvec_stat_cpu->count[idx]);
ea426c2a 831 if (unlikely(abs(x) > threshold)) {
eedc4e5a 832 pg_data_t *pgdat = lruvec_pgdat(lruvec);
42a30035
JW
833 struct mem_cgroup_per_node *pi;
834
42a30035
JW
835 for (pi = pn; pi; pi = parent_nodeinfo(pi, pgdat->node_id))
836 atomic_long_add(x, &pi->lruvec_stat[idx]);
db9adbcb
JW
837 x = 0;
838 }
839 __this_cpu_write(pn->lruvec_stat_cpu->count[idx], x);
840}
841
eedc4e5a
RG
842/**
843 * __mod_lruvec_state - update lruvec memory statistics
844 * @lruvec: the lruvec
845 * @idx: the stat item
846 * @val: delta to add to the counter, can be negative
847 *
848 * The lruvec is the intersection of the NUMA node and a cgroup. This
849 * function updates the all three counters that are affected by a
850 * change of state at this level: per-node, per-cgroup, per-lruvec.
851 */
852void __mod_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
853 int val)
854{
855 /* Update node */
856 __mod_node_page_state(lruvec_pgdat(lruvec), idx, val);
857
858 /* Update memcg and lruvec */
859 if (!mem_cgroup_disabled())
860 __mod_memcg_lruvec_state(lruvec, idx, val);
861}
862
ec9f0238
RG
863void __mod_lruvec_slab_state(void *p, enum node_stat_item idx, int val)
864{
4f103c63 865 pg_data_t *pgdat = page_pgdat(virt_to_page(p));
ec9f0238
RG
866 struct mem_cgroup *memcg;
867 struct lruvec *lruvec;
868
869 rcu_read_lock();
4f103c63 870 memcg = mem_cgroup_from_obj(p);
ec9f0238
RG
871
872 /* Untracked pages have no memcg, no lruvec. Update only the node */
873 if (!memcg || memcg == root_mem_cgroup) {
874 __mod_node_page_state(pgdat, idx, val);
875 } else {
867e5e1d 876 lruvec = mem_cgroup_lruvec(memcg, pgdat);
ec9f0238
RG
877 __mod_lruvec_state(lruvec, idx, val);
878 }
879 rcu_read_unlock();
880}
881
8380ce47
RG
882void mod_memcg_obj_state(void *p, int idx, int val)
883{
884 struct mem_cgroup *memcg;
885
886 rcu_read_lock();
887 memcg = mem_cgroup_from_obj(p);
888 if (memcg)
889 mod_memcg_state(memcg, idx, val);
890 rcu_read_unlock();
891}
892
db9adbcb
JW
893/**
894 * __count_memcg_events - account VM events in a cgroup
895 * @memcg: the memory cgroup
896 * @idx: the event item
897 * @count: the number of events that occured
898 */
899void __count_memcg_events(struct mem_cgroup *memcg, enum vm_event_item idx,
900 unsigned long count)
901{
902 unsigned long x;
903
904 if (mem_cgroup_disabled())
905 return;
906
907 x = count + __this_cpu_read(memcg->vmstats_percpu->events[idx]);
908 if (unlikely(x > MEMCG_CHARGE_BATCH)) {
42a30035
JW
909 struct mem_cgroup *mi;
910
766a4c19
YS
911 /*
912 * Batch local counters to keep them in sync with
913 * the hierarchical ones.
914 */
915 __this_cpu_add(memcg->vmstats_local->events[idx], x);
42a30035
JW
916 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
917 atomic_long_add(x, &mi->vmevents[idx]);
db9adbcb
JW
918 x = 0;
919 }
920 __this_cpu_write(memcg->vmstats_percpu->events[idx], x);
921}
922
42a30035 923static unsigned long memcg_events(struct mem_cgroup *memcg, int event)
e9f8974f 924{
871789d4 925 return atomic_long_read(&memcg->vmevents[event]);
e9f8974f
JW
926}
927
42a30035
JW
928static unsigned long memcg_events_local(struct mem_cgroup *memcg, int event)
929{
815744d7
JW
930 long x = 0;
931 int cpu;
932
933 for_each_possible_cpu(cpu)
934 x += per_cpu(memcg->vmstats_local->events[event], cpu);
935 return x;
42a30035
JW
936}
937
c0ff4b85 938static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
b070e65c 939 struct page *page,
3fba69a5 940 int nr_pages)
d52aa412 941{
e401f176
KH
942 /* pagein of a big page is an event. So, ignore page size */
943 if (nr_pages > 0)
c9019e9b 944 __count_memcg_events(memcg, PGPGIN, 1);
3751d604 945 else {
c9019e9b 946 __count_memcg_events(memcg, PGPGOUT, 1);
3751d604
KH
947 nr_pages = -nr_pages; /* for event */
948 }
e401f176 949
871789d4 950 __this_cpu_add(memcg->vmstats_percpu->nr_page_events, nr_pages);
6d12e2d8
KH
951}
952
f53d7ce3
JW
953static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
954 enum mem_cgroup_events_target target)
7a159cc9
JW
955{
956 unsigned long val, next;
957
871789d4
CD
958 val = __this_cpu_read(memcg->vmstats_percpu->nr_page_events);
959 next = __this_cpu_read(memcg->vmstats_percpu->targets[target]);
7a159cc9 960 /* from time_after() in jiffies.h */
6a1a8b80 961 if ((long)(next - val) < 0) {
f53d7ce3
JW
962 switch (target) {
963 case MEM_CGROUP_TARGET_THRESH:
964 next = val + THRESHOLDS_EVENTS_TARGET;
965 break;
bb4cc1a8
AM
966 case MEM_CGROUP_TARGET_SOFTLIMIT:
967 next = val + SOFTLIMIT_EVENTS_TARGET;
968 break;
f53d7ce3
JW
969 default:
970 break;
971 }
871789d4 972 __this_cpu_write(memcg->vmstats_percpu->targets[target], next);
f53d7ce3 973 return true;
7a159cc9 974 }
f53d7ce3 975 return false;
d2265e6f
KH
976}
977
978/*
979 * Check events in order.
980 *
981 */
c0ff4b85 982static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
d2265e6f
KH
983{
984 /* threshold event is triggered in finer grain than soft limit */
f53d7ce3
JW
985 if (unlikely(mem_cgroup_event_ratelimit(memcg,
986 MEM_CGROUP_TARGET_THRESH))) {
bb4cc1a8 987 bool do_softlimit;
f53d7ce3 988
bb4cc1a8
AM
989 do_softlimit = mem_cgroup_event_ratelimit(memcg,
990 MEM_CGROUP_TARGET_SOFTLIMIT);
c0ff4b85 991 mem_cgroup_threshold(memcg);
bb4cc1a8
AM
992 if (unlikely(do_softlimit))
993 mem_cgroup_update_tree(memcg, page);
0a31bc97 994 }
d2265e6f
KH
995}
996
cf475ad2 997struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
78fb7466 998{
31a78f23
BS
999 /*
1000 * mm_update_next_owner() may clear mm->owner to NULL
1001 * if it races with swapoff, page migration, etc.
1002 * So this can be called with p == NULL.
1003 */
1004 if (unlikely(!p))
1005 return NULL;
1006
073219e9 1007 return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
78fb7466 1008}
33398cf2 1009EXPORT_SYMBOL(mem_cgroup_from_task);
78fb7466 1010
d46eb14b
SB
1011/**
1012 * get_mem_cgroup_from_mm: Obtain a reference on given mm_struct's memcg.
1013 * @mm: mm from which memcg should be extracted. It can be NULL.
1014 *
1015 * Obtain a reference on mm->memcg and returns it if successful. Otherwise
1016 * root_mem_cgroup is returned. However if mem_cgroup is disabled, NULL is
1017 * returned.
1018 */
1019struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
54595fe2 1020{
d46eb14b
SB
1021 struct mem_cgroup *memcg;
1022
1023 if (mem_cgroup_disabled())
1024 return NULL;
0b7f569e 1025
54595fe2
KH
1026 rcu_read_lock();
1027 do {
6f6acb00
MH
1028 /*
1029 * Page cache insertions can happen withou an
1030 * actual mm context, e.g. during disk probing
1031 * on boot, loopback IO, acct() writes etc.
1032 */
1033 if (unlikely(!mm))
df381975 1034 memcg = root_mem_cgroup;
6f6acb00
MH
1035 else {
1036 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
1037 if (unlikely(!memcg))
1038 memcg = root_mem_cgroup;
1039 }
00d484f3 1040 } while (!css_tryget(&memcg->css));
54595fe2 1041 rcu_read_unlock();
c0ff4b85 1042 return memcg;
54595fe2 1043}
d46eb14b
SB
1044EXPORT_SYMBOL(get_mem_cgroup_from_mm);
1045
f745c6f5
SB
1046/**
1047 * get_mem_cgroup_from_page: Obtain a reference on given page's memcg.
1048 * @page: page from which memcg should be extracted.
1049 *
1050 * Obtain a reference on page->memcg and returns it if successful. Otherwise
1051 * root_mem_cgroup is returned.
1052 */
1053struct mem_cgroup *get_mem_cgroup_from_page(struct page *page)
1054{
1055 struct mem_cgroup *memcg = page->mem_cgroup;
1056
1057 if (mem_cgroup_disabled())
1058 return NULL;
1059
1060 rcu_read_lock();
8965aa28
SB
1061 /* Page should not get uncharged and freed memcg under us. */
1062 if (!memcg || WARN_ON_ONCE(!css_tryget(&memcg->css)))
f745c6f5
SB
1063 memcg = root_mem_cgroup;
1064 rcu_read_unlock();
1065 return memcg;
1066}
1067EXPORT_SYMBOL(get_mem_cgroup_from_page);
1068
d46eb14b
SB
1069/**
1070 * If current->active_memcg is non-NULL, do not fallback to current->mm->memcg.
1071 */
1072static __always_inline struct mem_cgroup *get_mem_cgroup_from_current(void)
1073{
1074 if (unlikely(current->active_memcg)) {
8965aa28 1075 struct mem_cgroup *memcg;
d46eb14b
SB
1076
1077 rcu_read_lock();
8965aa28
SB
1078 /* current->active_memcg must hold a ref. */
1079 if (WARN_ON_ONCE(!css_tryget(&current->active_memcg->css)))
1080 memcg = root_mem_cgroup;
1081 else
d46eb14b
SB
1082 memcg = current->active_memcg;
1083 rcu_read_unlock();
1084 return memcg;
1085 }
1086 return get_mem_cgroup_from_mm(current->mm);
1087}
54595fe2 1088
5660048c
JW
1089/**
1090 * mem_cgroup_iter - iterate over memory cgroup hierarchy
1091 * @root: hierarchy root
1092 * @prev: previously returned memcg, NULL on first invocation
1093 * @reclaim: cookie for shared reclaim walks, NULL for full walks
1094 *
1095 * Returns references to children of the hierarchy below @root, or
1096 * @root itself, or %NULL after a full round-trip.
1097 *
1098 * Caller must pass the return value in @prev on subsequent
1099 * invocations for reference counting, or use mem_cgroup_iter_break()
1100 * to cancel a hierarchy walk before the round-trip is complete.
1101 *
b213b54f 1102 * Reclaimers can specify a node and a priority level in @reclaim to
5660048c 1103 * divide up the memcgs in the hierarchy among all concurrent
b213b54f 1104 * reclaimers operating on the same node and priority.
5660048c 1105 */
694fbc0f 1106struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
5660048c 1107 struct mem_cgroup *prev,
694fbc0f 1108 struct mem_cgroup_reclaim_cookie *reclaim)
14067bb3 1109{
3f649ab7 1110 struct mem_cgroup_reclaim_iter *iter;
5ac8fb31 1111 struct cgroup_subsys_state *css = NULL;
9f3a0d09 1112 struct mem_cgroup *memcg = NULL;
5ac8fb31 1113 struct mem_cgroup *pos = NULL;
711d3d2c 1114
694fbc0f
AM
1115 if (mem_cgroup_disabled())
1116 return NULL;
5660048c 1117
9f3a0d09
JW
1118 if (!root)
1119 root = root_mem_cgroup;
7d74b06f 1120
9f3a0d09 1121 if (prev && !reclaim)
5ac8fb31 1122 pos = prev;
14067bb3 1123
9f3a0d09
JW
1124 if (!root->use_hierarchy && root != root_mem_cgroup) {
1125 if (prev)
5ac8fb31 1126 goto out;
694fbc0f 1127 return root;
9f3a0d09 1128 }
14067bb3 1129
542f85f9 1130 rcu_read_lock();
5f578161 1131
5ac8fb31 1132 if (reclaim) {
ef8f2327 1133 struct mem_cgroup_per_node *mz;
5ac8fb31 1134
ef8f2327 1135 mz = mem_cgroup_nodeinfo(root, reclaim->pgdat->node_id);
9da83f3f 1136 iter = &mz->iter;
5ac8fb31
JW
1137
1138 if (prev && reclaim->generation != iter->generation)
1139 goto out_unlock;
1140
6df38689 1141 while (1) {
4db0c3c2 1142 pos = READ_ONCE(iter->position);
6df38689
VD
1143 if (!pos || css_tryget(&pos->css))
1144 break;
5ac8fb31 1145 /*
6df38689
VD
1146 * css reference reached zero, so iter->position will
1147 * be cleared by ->css_released. However, we should not
1148 * rely on this happening soon, because ->css_released
1149 * is called from a work queue, and by busy-waiting we
1150 * might block it. So we clear iter->position right
1151 * away.
5ac8fb31 1152 */
6df38689
VD
1153 (void)cmpxchg(&iter->position, pos, NULL);
1154 }
5ac8fb31
JW
1155 }
1156
1157 if (pos)
1158 css = &pos->css;
1159
1160 for (;;) {
1161 css = css_next_descendant_pre(css, &root->css);
1162 if (!css) {
1163 /*
1164 * Reclaimers share the hierarchy walk, and a
1165 * new one might jump in right at the end of
1166 * the hierarchy - make sure they see at least
1167 * one group and restart from the beginning.
1168 */
1169 if (!prev)
1170 continue;
1171 break;
527a5ec9 1172 }
7d74b06f 1173
5ac8fb31
JW
1174 /*
1175 * Verify the css and acquire a reference. The root
1176 * is provided by the caller, so we know it's alive
1177 * and kicking, and don't take an extra reference.
1178 */
1179 memcg = mem_cgroup_from_css(css);
14067bb3 1180
5ac8fb31
JW
1181 if (css == &root->css)
1182 break;
14067bb3 1183
0b8f73e1
JW
1184 if (css_tryget(css))
1185 break;
9f3a0d09 1186
5ac8fb31 1187 memcg = NULL;
9f3a0d09 1188 }
5ac8fb31
JW
1189
1190 if (reclaim) {
5ac8fb31 1191 /*
6df38689
VD
1192 * The position could have already been updated by a competing
1193 * thread, so check that the value hasn't changed since we read
1194 * it to avoid reclaiming from the same cgroup twice.
5ac8fb31 1195 */
6df38689
VD
1196 (void)cmpxchg(&iter->position, pos, memcg);
1197
5ac8fb31
JW
1198 if (pos)
1199 css_put(&pos->css);
1200
1201 if (!memcg)
1202 iter->generation++;
1203 else if (!prev)
1204 reclaim->generation = iter->generation;
9f3a0d09 1205 }
5ac8fb31 1206
542f85f9
MH
1207out_unlock:
1208 rcu_read_unlock();
5ac8fb31 1209out:
c40046f3
MH
1210 if (prev && prev != root)
1211 css_put(&prev->css);
1212
9f3a0d09 1213 return memcg;
14067bb3 1214}
7d74b06f 1215
5660048c
JW
1216/**
1217 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1218 * @root: hierarchy root
1219 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1220 */
1221void mem_cgroup_iter_break(struct mem_cgroup *root,
1222 struct mem_cgroup *prev)
9f3a0d09
JW
1223{
1224 if (!root)
1225 root = root_mem_cgroup;
1226 if (prev && prev != root)
1227 css_put(&prev->css);
1228}
7d74b06f 1229
54a83d6b
MC
1230static void __invalidate_reclaim_iterators(struct mem_cgroup *from,
1231 struct mem_cgroup *dead_memcg)
6df38689 1232{
6df38689 1233 struct mem_cgroup_reclaim_iter *iter;
ef8f2327
MG
1234 struct mem_cgroup_per_node *mz;
1235 int nid;
6df38689 1236
54a83d6b
MC
1237 for_each_node(nid) {
1238 mz = mem_cgroup_nodeinfo(from, nid);
9da83f3f
YS
1239 iter = &mz->iter;
1240 cmpxchg(&iter->position, dead_memcg, NULL);
6df38689
VD
1241 }
1242}
1243
54a83d6b
MC
1244static void invalidate_reclaim_iterators(struct mem_cgroup *dead_memcg)
1245{
1246 struct mem_cgroup *memcg = dead_memcg;
1247 struct mem_cgroup *last;
1248
1249 do {
1250 __invalidate_reclaim_iterators(memcg, dead_memcg);
1251 last = memcg;
1252 } while ((memcg = parent_mem_cgroup(memcg)));
1253
1254 /*
1255 * When cgruop1 non-hierarchy mode is used,
1256 * parent_mem_cgroup() does not walk all the way up to the
1257 * cgroup root (root_mem_cgroup). So we have to handle
1258 * dead_memcg from cgroup root separately.
1259 */
1260 if (last != root_mem_cgroup)
1261 __invalidate_reclaim_iterators(root_mem_cgroup,
1262 dead_memcg);
1263}
1264
7c5f64f8
VD
1265/**
1266 * mem_cgroup_scan_tasks - iterate over tasks of a memory cgroup hierarchy
1267 * @memcg: hierarchy root
1268 * @fn: function to call for each task
1269 * @arg: argument passed to @fn
1270 *
1271 * This function iterates over tasks attached to @memcg or to any of its
1272 * descendants and calls @fn for each task. If @fn returns a non-zero
1273 * value, the function breaks the iteration loop and returns the value.
1274 * Otherwise, it will iterate over all tasks and return 0.
1275 *
1276 * This function must not be called for the root memory cgroup.
1277 */
1278int mem_cgroup_scan_tasks(struct mem_cgroup *memcg,
1279 int (*fn)(struct task_struct *, void *), void *arg)
1280{
1281 struct mem_cgroup *iter;
1282 int ret = 0;
1283
1284 BUG_ON(memcg == root_mem_cgroup);
1285
1286 for_each_mem_cgroup_tree(iter, memcg) {
1287 struct css_task_iter it;
1288 struct task_struct *task;
1289
f168a9a5 1290 css_task_iter_start(&iter->css, CSS_TASK_ITER_PROCS, &it);
7c5f64f8
VD
1291 while (!ret && (task = css_task_iter_next(&it)))
1292 ret = fn(task, arg);
1293 css_task_iter_end(&it);
1294 if (ret) {
1295 mem_cgroup_iter_break(memcg, iter);
1296 break;
1297 }
1298 }
1299 return ret;
1300}
1301
925b7673 1302/**
dfe0e773 1303 * mem_cgroup_page_lruvec - return lruvec for isolating/putting an LRU page
925b7673 1304 * @page: the page
f144c390 1305 * @pgdat: pgdat of the page
dfe0e773 1306 *
a0b5b414
JW
1307 * This function relies on page->mem_cgroup being stable - see the
1308 * access rules in commit_charge().
925b7673 1309 */
599d0c95 1310struct lruvec *mem_cgroup_page_lruvec(struct page *page, struct pglist_data *pgdat)
08e552c6 1311{
ef8f2327 1312 struct mem_cgroup_per_node *mz;
925b7673 1313 struct mem_cgroup *memcg;
bea8c150 1314 struct lruvec *lruvec;
6d12e2d8 1315
bea8c150 1316 if (mem_cgroup_disabled()) {
867e5e1d 1317 lruvec = &pgdat->__lruvec;
bea8c150
HD
1318 goto out;
1319 }
925b7673 1320
1306a85a 1321 memcg = page->mem_cgroup;
7512102c 1322 /*
dfe0e773 1323 * Swapcache readahead pages are added to the LRU - and
29833315 1324 * possibly migrated - before they are charged.
7512102c 1325 */
29833315
JW
1326 if (!memcg)
1327 memcg = root_mem_cgroup;
7512102c 1328
ef8f2327 1329 mz = mem_cgroup_page_nodeinfo(memcg, page);
bea8c150
HD
1330 lruvec = &mz->lruvec;
1331out:
1332 /*
1333 * Since a node can be onlined after the mem_cgroup was created,
1334 * we have to be prepared to initialize lruvec->zone here;
1335 * and if offlined then reonlined, we need to reinitialize it.
1336 */
599d0c95
MG
1337 if (unlikely(lruvec->pgdat != pgdat))
1338 lruvec->pgdat = pgdat;
bea8c150 1339 return lruvec;
08e552c6 1340}
b69408e8 1341
925b7673 1342/**
fa9add64
HD
1343 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1344 * @lruvec: mem_cgroup per zone lru vector
1345 * @lru: index of lru list the page is sitting on
b4536f0c 1346 * @zid: zone id of the accounted pages
fa9add64 1347 * @nr_pages: positive when adding or negative when removing
925b7673 1348 *
ca707239
HD
1349 * This function must be called under lru_lock, just before a page is added
1350 * to or just after a page is removed from an lru list (that ordering being
1351 * so as to allow it to check that lru_size 0 is consistent with list_empty).
3f58a829 1352 */
fa9add64 1353void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
b4536f0c 1354 int zid, int nr_pages)
3f58a829 1355{
ef8f2327 1356 struct mem_cgroup_per_node *mz;
fa9add64 1357 unsigned long *lru_size;
ca707239 1358 long size;
3f58a829
MK
1359
1360 if (mem_cgroup_disabled())
1361 return;
1362
ef8f2327 1363 mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
b4536f0c 1364 lru_size = &mz->lru_zone_size[zid][lru];
ca707239
HD
1365
1366 if (nr_pages < 0)
1367 *lru_size += nr_pages;
1368
1369 size = *lru_size;
b4536f0c
MH
1370 if (WARN_ONCE(size < 0,
1371 "%s(%p, %d, %d): lru_size %ld\n",
1372 __func__, lruvec, lru, nr_pages, size)) {
ca707239
HD
1373 VM_BUG_ON(1);
1374 *lru_size = 0;
1375 }
1376
1377 if (nr_pages > 0)
1378 *lru_size += nr_pages;
08e552c6 1379}
544122e5 1380
19942822 1381/**
9d11ea9f 1382 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
dad7557e 1383 * @memcg: the memory cgroup
19942822 1384 *
9d11ea9f 1385 * Returns the maximum amount of memory @mem can be charged with, in
7ec99d62 1386 * pages.
19942822 1387 */
c0ff4b85 1388static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
19942822 1389{
3e32cb2e
JW
1390 unsigned long margin = 0;
1391 unsigned long count;
1392 unsigned long limit;
9d11ea9f 1393
3e32cb2e 1394 count = page_counter_read(&memcg->memory);
bbec2e15 1395 limit = READ_ONCE(memcg->memory.max);
3e32cb2e
JW
1396 if (count < limit)
1397 margin = limit - count;
1398
7941d214 1399 if (do_memsw_account()) {
3e32cb2e 1400 count = page_counter_read(&memcg->memsw);
bbec2e15 1401 limit = READ_ONCE(memcg->memsw.max);
1c4448ed 1402 if (count < limit)
3e32cb2e 1403 margin = min(margin, limit - count);
cbedbac3
LR
1404 else
1405 margin = 0;
3e32cb2e
JW
1406 }
1407
1408 return margin;
19942822
JW
1409}
1410
32047e2a 1411/*
bdcbb659 1412 * A routine for checking "mem" is under move_account() or not.
32047e2a 1413 *
bdcbb659
QH
1414 * Checking a cgroup is mc.from or mc.to or under hierarchy of
1415 * moving cgroups. This is for waiting at high-memory pressure
1416 * caused by "move".
32047e2a 1417 */
c0ff4b85 1418static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
4b534334 1419{
2bd9bb20
KH
1420 struct mem_cgroup *from;
1421 struct mem_cgroup *to;
4b534334 1422 bool ret = false;
2bd9bb20
KH
1423 /*
1424 * Unlike task_move routines, we access mc.to, mc.from not under
1425 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1426 */
1427 spin_lock(&mc.lock);
1428 from = mc.from;
1429 to = mc.to;
1430 if (!from)
1431 goto unlock;
3e92041d 1432
2314b42d
JW
1433 ret = mem_cgroup_is_descendant(from, memcg) ||
1434 mem_cgroup_is_descendant(to, memcg);
2bd9bb20
KH
1435unlock:
1436 spin_unlock(&mc.lock);
4b534334
KH
1437 return ret;
1438}
1439
c0ff4b85 1440static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
4b534334
KH
1441{
1442 if (mc.moving_task && current != mc.moving_task) {
c0ff4b85 1443 if (mem_cgroup_under_move(memcg)) {
4b534334
KH
1444 DEFINE_WAIT(wait);
1445 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1446 /* moving charge context might have finished. */
1447 if (mc.moving_task)
1448 schedule();
1449 finish_wait(&mc.waitq, &wait);
1450 return true;
1451 }
1452 }
1453 return false;
1454}
1455
c8713d0b
JW
1456static char *memory_stat_format(struct mem_cgroup *memcg)
1457{
1458 struct seq_buf s;
1459 int i;
71cd3113 1460
c8713d0b
JW
1461 seq_buf_init(&s, kmalloc(PAGE_SIZE, GFP_KERNEL), PAGE_SIZE);
1462 if (!s.buffer)
1463 return NULL;
1464
1465 /*
1466 * Provide statistics on the state of the memory subsystem as
1467 * well as cumulative event counters that show past behavior.
1468 *
1469 * This list is ordered following a combination of these gradients:
1470 * 1) generic big picture -> specifics and details
1471 * 2) reflecting userspace activity -> reflecting kernel heuristics
1472 *
1473 * Current memory state:
1474 */
1475
1476 seq_buf_printf(&s, "anon %llu\n",
be5d0a74 1477 (u64)memcg_page_state(memcg, NR_ANON_MAPPED) *
c8713d0b
JW
1478 PAGE_SIZE);
1479 seq_buf_printf(&s, "file %llu\n",
0d1c2072 1480 (u64)memcg_page_state(memcg, NR_FILE_PAGES) *
c8713d0b
JW
1481 PAGE_SIZE);
1482 seq_buf_printf(&s, "kernel_stack %llu\n",
1483 (u64)memcg_page_state(memcg, MEMCG_KERNEL_STACK_KB) *
1484 1024);
1485 seq_buf_printf(&s, "slab %llu\n",
d42f3245
RG
1486 (u64)(memcg_page_state(memcg, NR_SLAB_RECLAIMABLE_B) +
1487 memcg_page_state(memcg, NR_SLAB_UNRECLAIMABLE_B)));
c8713d0b
JW
1488 seq_buf_printf(&s, "sock %llu\n",
1489 (u64)memcg_page_state(memcg, MEMCG_SOCK) *
1490 PAGE_SIZE);
1491
1492 seq_buf_printf(&s, "shmem %llu\n",
1493 (u64)memcg_page_state(memcg, NR_SHMEM) *
1494 PAGE_SIZE);
1495 seq_buf_printf(&s, "file_mapped %llu\n",
1496 (u64)memcg_page_state(memcg, NR_FILE_MAPPED) *
1497 PAGE_SIZE);
1498 seq_buf_printf(&s, "file_dirty %llu\n",
1499 (u64)memcg_page_state(memcg, NR_FILE_DIRTY) *
1500 PAGE_SIZE);
1501 seq_buf_printf(&s, "file_writeback %llu\n",
1502 (u64)memcg_page_state(memcg, NR_WRITEBACK) *
1503 PAGE_SIZE);
1504
468c3982 1505#ifdef CONFIG_TRANSPARENT_HUGEPAGE
c8713d0b 1506 seq_buf_printf(&s, "anon_thp %llu\n",
468c3982
JW
1507 (u64)memcg_page_state(memcg, NR_ANON_THPS) *
1508 HPAGE_PMD_SIZE);
1509#endif
c8713d0b
JW
1510
1511 for (i = 0; i < NR_LRU_LISTS; i++)
ebc5d83d 1512 seq_buf_printf(&s, "%s %llu\n", lru_list_name(i),
c8713d0b
JW
1513 (u64)memcg_page_state(memcg, NR_LRU_BASE + i) *
1514 PAGE_SIZE);
1515
1516 seq_buf_printf(&s, "slab_reclaimable %llu\n",
d42f3245 1517 (u64)memcg_page_state(memcg, NR_SLAB_RECLAIMABLE_B));
c8713d0b 1518 seq_buf_printf(&s, "slab_unreclaimable %llu\n",
d42f3245 1519 (u64)memcg_page_state(memcg, NR_SLAB_UNRECLAIMABLE_B));
c8713d0b
JW
1520
1521 /* Accumulated memory events */
1522
ebc5d83d
KK
1523 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGFAULT),
1524 memcg_events(memcg, PGFAULT));
1525 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGMAJFAULT),
1526 memcg_events(memcg, PGMAJFAULT));
c8713d0b
JW
1527
1528 seq_buf_printf(&s, "workingset_refault %lu\n",
1529 memcg_page_state(memcg, WORKINGSET_REFAULT));
1530 seq_buf_printf(&s, "workingset_activate %lu\n",
1531 memcg_page_state(memcg, WORKINGSET_ACTIVATE));
a6f5576b
YS
1532 seq_buf_printf(&s, "workingset_restore %lu\n",
1533 memcg_page_state(memcg, WORKINGSET_RESTORE));
c8713d0b
JW
1534 seq_buf_printf(&s, "workingset_nodereclaim %lu\n",
1535 memcg_page_state(memcg, WORKINGSET_NODERECLAIM));
1536
ebc5d83d
KK
1537 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGREFILL),
1538 memcg_events(memcg, PGREFILL));
c8713d0b
JW
1539 seq_buf_printf(&s, "pgscan %lu\n",
1540 memcg_events(memcg, PGSCAN_KSWAPD) +
1541 memcg_events(memcg, PGSCAN_DIRECT));
1542 seq_buf_printf(&s, "pgsteal %lu\n",
1543 memcg_events(memcg, PGSTEAL_KSWAPD) +
1544 memcg_events(memcg, PGSTEAL_DIRECT));
ebc5d83d
KK
1545 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGACTIVATE),
1546 memcg_events(memcg, PGACTIVATE));
1547 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGDEACTIVATE),
1548 memcg_events(memcg, PGDEACTIVATE));
1549 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGLAZYFREE),
1550 memcg_events(memcg, PGLAZYFREE));
1551 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGLAZYFREED),
1552 memcg_events(memcg, PGLAZYFREED));
c8713d0b
JW
1553
1554#ifdef CONFIG_TRANSPARENT_HUGEPAGE
ebc5d83d 1555 seq_buf_printf(&s, "%s %lu\n", vm_event_name(THP_FAULT_ALLOC),
c8713d0b 1556 memcg_events(memcg, THP_FAULT_ALLOC));
ebc5d83d 1557 seq_buf_printf(&s, "%s %lu\n", vm_event_name(THP_COLLAPSE_ALLOC),
c8713d0b
JW
1558 memcg_events(memcg, THP_COLLAPSE_ALLOC));
1559#endif /* CONFIG_TRANSPARENT_HUGEPAGE */
1560
1561 /* The above should easily fit into one page */
1562 WARN_ON_ONCE(seq_buf_has_overflowed(&s));
1563
1564 return s.buffer;
1565}
71cd3113 1566
58cf188e 1567#define K(x) ((x) << (PAGE_SHIFT-10))
e222432b 1568/**
f0c867d9 1569 * mem_cgroup_print_oom_context: Print OOM information relevant to
1570 * memory controller.
e222432b
BS
1571 * @memcg: The memory cgroup that went over limit
1572 * @p: Task that is going to be killed
1573 *
1574 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1575 * enabled
1576 */
f0c867d9 1577void mem_cgroup_print_oom_context(struct mem_cgroup *memcg, struct task_struct *p)
e222432b 1578{
e222432b
BS
1579 rcu_read_lock();
1580
f0c867d9 1581 if (memcg) {
1582 pr_cont(",oom_memcg=");
1583 pr_cont_cgroup_path(memcg->css.cgroup);
1584 } else
1585 pr_cont(",global_oom");
2415b9f5 1586 if (p) {
f0c867d9 1587 pr_cont(",task_memcg=");
2415b9f5 1588 pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
2415b9f5 1589 }
e222432b 1590 rcu_read_unlock();
f0c867d9 1591}
1592
1593/**
1594 * mem_cgroup_print_oom_meminfo: Print OOM memory information relevant to
1595 * memory controller.
1596 * @memcg: The memory cgroup that went over limit
1597 */
1598void mem_cgroup_print_oom_meminfo(struct mem_cgroup *memcg)
1599{
c8713d0b 1600 char *buf;
e222432b 1601
3e32cb2e
JW
1602 pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
1603 K((u64)page_counter_read(&memcg->memory)),
15b42562 1604 K((u64)READ_ONCE(memcg->memory.max)), memcg->memory.failcnt);
c8713d0b
JW
1605 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1606 pr_info("swap: usage %llukB, limit %llukB, failcnt %lu\n",
1607 K((u64)page_counter_read(&memcg->swap)),
32d087cd 1608 K((u64)READ_ONCE(memcg->swap.max)), memcg->swap.failcnt);
c8713d0b
JW
1609 else {
1610 pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
1611 K((u64)page_counter_read(&memcg->memsw)),
1612 K((u64)memcg->memsw.max), memcg->memsw.failcnt);
1613 pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
1614 K((u64)page_counter_read(&memcg->kmem)),
1615 K((u64)memcg->kmem.max), memcg->kmem.failcnt);
58cf188e 1616 }
c8713d0b
JW
1617
1618 pr_info("Memory cgroup stats for ");
1619 pr_cont_cgroup_path(memcg->css.cgroup);
1620 pr_cont(":");
1621 buf = memory_stat_format(memcg);
1622 if (!buf)
1623 return;
1624 pr_info("%s", buf);
1625 kfree(buf);
e222432b
BS
1626}
1627
a63d83f4
DR
1628/*
1629 * Return the memory (and swap, if configured) limit for a memcg.
1630 */
bbec2e15 1631unsigned long mem_cgroup_get_max(struct mem_cgroup *memcg)
a63d83f4 1632{
bbec2e15 1633 unsigned long max;
f3e8eb70 1634
15b42562 1635 max = READ_ONCE(memcg->memory.max);
9a5a8f19 1636 if (mem_cgroup_swappiness(memcg)) {
bbec2e15
RG
1637 unsigned long memsw_max;
1638 unsigned long swap_max;
9a5a8f19 1639
bbec2e15 1640 memsw_max = memcg->memsw.max;
32d087cd 1641 swap_max = READ_ONCE(memcg->swap.max);
bbec2e15
RG
1642 swap_max = min(swap_max, (unsigned long)total_swap_pages);
1643 max = min(max + swap_max, memsw_max);
9a5a8f19 1644 }
bbec2e15 1645 return max;
a63d83f4
DR
1646}
1647
9783aa99
CD
1648unsigned long mem_cgroup_size(struct mem_cgroup *memcg)
1649{
1650 return page_counter_read(&memcg->memory);
1651}
1652
b6e6edcf 1653static bool mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
19965460 1654 int order)
9cbb78bb 1655{
6e0fc46d
DR
1656 struct oom_control oc = {
1657 .zonelist = NULL,
1658 .nodemask = NULL,
2a966b77 1659 .memcg = memcg,
6e0fc46d
DR
1660 .gfp_mask = gfp_mask,
1661 .order = order,
6e0fc46d 1662 };
7c5f64f8 1663 bool ret;
9cbb78bb 1664
7775face
TH
1665 if (mutex_lock_killable(&oom_lock))
1666 return true;
1667 /*
1668 * A few threads which were not waiting at mutex_lock_killable() can
1669 * fail to bail out. Therefore, check again after holding oom_lock.
1670 */
1671 ret = should_force_charge() || out_of_memory(&oc);
dc56401f 1672 mutex_unlock(&oom_lock);
7c5f64f8 1673 return ret;
9cbb78bb
DR
1674}
1675
0608f43d 1676static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
ef8f2327 1677 pg_data_t *pgdat,
0608f43d
AM
1678 gfp_t gfp_mask,
1679 unsigned long *total_scanned)
1680{
1681 struct mem_cgroup *victim = NULL;
1682 int total = 0;
1683 int loop = 0;
1684 unsigned long excess;
1685 unsigned long nr_scanned;
1686 struct mem_cgroup_reclaim_cookie reclaim = {
ef8f2327 1687 .pgdat = pgdat,
0608f43d
AM
1688 };
1689
3e32cb2e 1690 excess = soft_limit_excess(root_memcg);
0608f43d
AM
1691
1692 while (1) {
1693 victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
1694 if (!victim) {
1695 loop++;
1696 if (loop >= 2) {
1697 /*
1698 * If we have not been able to reclaim
1699 * anything, it might because there are
1700 * no reclaimable pages under this hierarchy
1701 */
1702 if (!total)
1703 break;
1704 /*
1705 * We want to do more targeted reclaim.
1706 * excess >> 2 is not to excessive so as to
1707 * reclaim too much, nor too less that we keep
1708 * coming back to reclaim from this cgroup
1709 */
1710 if (total >= (excess >> 2) ||
1711 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
1712 break;
1713 }
1714 continue;
1715 }
a9dd0a83 1716 total += mem_cgroup_shrink_node(victim, gfp_mask, false,
ef8f2327 1717 pgdat, &nr_scanned);
0608f43d 1718 *total_scanned += nr_scanned;
3e32cb2e 1719 if (!soft_limit_excess(root_memcg))
0608f43d 1720 break;
6d61ef40 1721 }
0608f43d
AM
1722 mem_cgroup_iter_break(root_memcg, victim);
1723 return total;
6d61ef40
BS
1724}
1725
0056f4e6
JW
1726#ifdef CONFIG_LOCKDEP
1727static struct lockdep_map memcg_oom_lock_dep_map = {
1728 .name = "memcg_oom_lock",
1729};
1730#endif
1731
fb2a6fc5
JW
1732static DEFINE_SPINLOCK(memcg_oom_lock);
1733
867578cb
KH
1734/*
1735 * Check OOM-Killer is already running under our hierarchy.
1736 * If someone is running, return false.
1737 */
fb2a6fc5 1738static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
867578cb 1739{
79dfdacc 1740 struct mem_cgroup *iter, *failed = NULL;
a636b327 1741
fb2a6fc5
JW
1742 spin_lock(&memcg_oom_lock);
1743
9f3a0d09 1744 for_each_mem_cgroup_tree(iter, memcg) {
23751be0 1745 if (iter->oom_lock) {
79dfdacc
MH
1746 /*
1747 * this subtree of our hierarchy is already locked
1748 * so we cannot give a lock.
1749 */
79dfdacc 1750 failed = iter;
9f3a0d09
JW
1751 mem_cgroup_iter_break(memcg, iter);
1752 break;
23751be0
JW
1753 } else
1754 iter->oom_lock = true;
7d74b06f 1755 }
867578cb 1756
fb2a6fc5
JW
1757 if (failed) {
1758 /*
1759 * OK, we failed to lock the whole subtree so we have
1760 * to clean up what we set up to the failing subtree
1761 */
1762 for_each_mem_cgroup_tree(iter, memcg) {
1763 if (iter == failed) {
1764 mem_cgroup_iter_break(memcg, iter);
1765 break;
1766 }
1767 iter->oom_lock = false;
79dfdacc 1768 }
0056f4e6
JW
1769 } else
1770 mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_);
fb2a6fc5
JW
1771
1772 spin_unlock(&memcg_oom_lock);
1773
1774 return !failed;
a636b327 1775}
0b7f569e 1776
fb2a6fc5 1777static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
0b7f569e 1778{
7d74b06f
KH
1779 struct mem_cgroup *iter;
1780
fb2a6fc5 1781 spin_lock(&memcg_oom_lock);
5facae4f 1782 mutex_release(&memcg_oom_lock_dep_map, _RET_IP_);
c0ff4b85 1783 for_each_mem_cgroup_tree(iter, memcg)
79dfdacc 1784 iter->oom_lock = false;
fb2a6fc5 1785 spin_unlock(&memcg_oom_lock);
79dfdacc
MH
1786}
1787
c0ff4b85 1788static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
79dfdacc
MH
1789{
1790 struct mem_cgroup *iter;
1791
c2b42d3c 1792 spin_lock(&memcg_oom_lock);
c0ff4b85 1793 for_each_mem_cgroup_tree(iter, memcg)
c2b42d3c
TH
1794 iter->under_oom++;
1795 spin_unlock(&memcg_oom_lock);
79dfdacc
MH
1796}
1797
c0ff4b85 1798static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
79dfdacc
MH
1799{
1800 struct mem_cgroup *iter;
1801
867578cb
KH
1802 /*
1803 * When a new child is created while the hierarchy is under oom,
c2b42d3c 1804 * mem_cgroup_oom_lock() may not be called. Watch for underflow.
867578cb 1805 */
c2b42d3c 1806 spin_lock(&memcg_oom_lock);
c0ff4b85 1807 for_each_mem_cgroup_tree(iter, memcg)
c2b42d3c
TH
1808 if (iter->under_oom > 0)
1809 iter->under_oom--;
1810 spin_unlock(&memcg_oom_lock);
0b7f569e
KH
1811}
1812
867578cb
KH
1813static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1814
dc98df5a 1815struct oom_wait_info {
d79154bb 1816 struct mem_cgroup *memcg;
ac6424b9 1817 wait_queue_entry_t wait;
dc98df5a
KH
1818};
1819
ac6424b9 1820static int memcg_oom_wake_function(wait_queue_entry_t *wait,
dc98df5a
KH
1821 unsigned mode, int sync, void *arg)
1822{
d79154bb
HD
1823 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
1824 struct mem_cgroup *oom_wait_memcg;
dc98df5a
KH
1825 struct oom_wait_info *oom_wait_info;
1826
1827 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
d79154bb 1828 oom_wait_memcg = oom_wait_info->memcg;
dc98df5a 1829
2314b42d
JW
1830 if (!mem_cgroup_is_descendant(wake_memcg, oom_wait_memcg) &&
1831 !mem_cgroup_is_descendant(oom_wait_memcg, wake_memcg))
dc98df5a 1832 return 0;
dc98df5a
KH
1833 return autoremove_wake_function(wait, mode, sync, arg);
1834}
1835
c0ff4b85 1836static void memcg_oom_recover(struct mem_cgroup *memcg)
3c11ecf4 1837{
c2b42d3c
TH
1838 /*
1839 * For the following lockless ->under_oom test, the only required
1840 * guarantee is that it must see the state asserted by an OOM when
1841 * this function is called as a result of userland actions
1842 * triggered by the notification of the OOM. This is trivially
1843 * achieved by invoking mem_cgroup_mark_under_oom() before
1844 * triggering notification.
1845 */
1846 if (memcg && memcg->under_oom)
f4b90b70 1847 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
3c11ecf4
KH
1848}
1849
29ef680a
MH
1850enum oom_status {
1851 OOM_SUCCESS,
1852 OOM_FAILED,
1853 OOM_ASYNC,
1854 OOM_SKIPPED
1855};
1856
1857static enum oom_status mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
0b7f569e 1858{
7056d3a3
MH
1859 enum oom_status ret;
1860 bool locked;
1861
29ef680a
MH
1862 if (order > PAGE_ALLOC_COSTLY_ORDER)
1863 return OOM_SKIPPED;
1864
7a1adfdd
RG
1865 memcg_memory_event(memcg, MEMCG_OOM);
1866
867578cb 1867 /*
49426420
JW
1868 * We are in the middle of the charge context here, so we
1869 * don't want to block when potentially sitting on a callstack
1870 * that holds all kinds of filesystem and mm locks.
1871 *
29ef680a
MH
1872 * cgroup1 allows disabling the OOM killer and waiting for outside
1873 * handling until the charge can succeed; remember the context and put
1874 * the task to sleep at the end of the page fault when all locks are
1875 * released.
49426420 1876 *
29ef680a
MH
1877 * On the other hand, in-kernel OOM killer allows for an async victim
1878 * memory reclaim (oom_reaper) and that means that we are not solely
1879 * relying on the oom victim to make a forward progress and we can
1880 * invoke the oom killer here.
1881 *
1882 * Please note that mem_cgroup_out_of_memory might fail to find a
1883 * victim and then we have to bail out from the charge path.
867578cb 1884 */
29ef680a
MH
1885 if (memcg->oom_kill_disable) {
1886 if (!current->in_user_fault)
1887 return OOM_SKIPPED;
1888 css_get(&memcg->css);
1889 current->memcg_in_oom = memcg;
1890 current->memcg_oom_gfp_mask = mask;
1891 current->memcg_oom_order = order;
1892
1893 return OOM_ASYNC;
1894 }
1895
7056d3a3
MH
1896 mem_cgroup_mark_under_oom(memcg);
1897
1898 locked = mem_cgroup_oom_trylock(memcg);
1899
1900 if (locked)
1901 mem_cgroup_oom_notify(memcg);
1902
1903 mem_cgroup_unmark_under_oom(memcg);
29ef680a 1904 if (mem_cgroup_out_of_memory(memcg, mask, order))
7056d3a3
MH
1905 ret = OOM_SUCCESS;
1906 else
1907 ret = OOM_FAILED;
1908
1909 if (locked)
1910 mem_cgroup_oom_unlock(memcg);
29ef680a 1911
7056d3a3 1912 return ret;
3812c8c8
JW
1913}
1914
1915/**
1916 * mem_cgroup_oom_synchronize - complete memcg OOM handling
49426420 1917 * @handle: actually kill/wait or just clean up the OOM state
3812c8c8 1918 *
49426420
JW
1919 * This has to be called at the end of a page fault if the memcg OOM
1920 * handler was enabled.
3812c8c8 1921 *
49426420 1922 * Memcg supports userspace OOM handling where failed allocations must
3812c8c8
JW
1923 * sleep on a waitqueue until the userspace task resolves the
1924 * situation. Sleeping directly in the charge context with all kinds
1925 * of locks held is not a good idea, instead we remember an OOM state
1926 * in the task and mem_cgroup_oom_synchronize() has to be called at
49426420 1927 * the end of the page fault to complete the OOM handling.
3812c8c8
JW
1928 *
1929 * Returns %true if an ongoing memcg OOM situation was detected and
49426420 1930 * completed, %false otherwise.
3812c8c8 1931 */
49426420 1932bool mem_cgroup_oom_synchronize(bool handle)
3812c8c8 1933{
626ebc41 1934 struct mem_cgroup *memcg = current->memcg_in_oom;
3812c8c8 1935 struct oom_wait_info owait;
49426420 1936 bool locked;
3812c8c8
JW
1937
1938 /* OOM is global, do not handle */
3812c8c8 1939 if (!memcg)
49426420 1940 return false;
3812c8c8 1941
7c5f64f8 1942 if (!handle)
49426420 1943 goto cleanup;
3812c8c8
JW
1944
1945 owait.memcg = memcg;
1946 owait.wait.flags = 0;
1947 owait.wait.func = memcg_oom_wake_function;
1948 owait.wait.private = current;
2055da97 1949 INIT_LIST_HEAD(&owait.wait.entry);
867578cb 1950
3812c8c8 1951 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
49426420
JW
1952 mem_cgroup_mark_under_oom(memcg);
1953
1954 locked = mem_cgroup_oom_trylock(memcg);
1955
1956 if (locked)
1957 mem_cgroup_oom_notify(memcg);
1958
1959 if (locked && !memcg->oom_kill_disable) {
1960 mem_cgroup_unmark_under_oom(memcg);
1961 finish_wait(&memcg_oom_waitq, &owait.wait);
626ebc41
TH
1962 mem_cgroup_out_of_memory(memcg, current->memcg_oom_gfp_mask,
1963 current->memcg_oom_order);
49426420 1964 } else {
3812c8c8 1965 schedule();
49426420
JW
1966 mem_cgroup_unmark_under_oom(memcg);
1967 finish_wait(&memcg_oom_waitq, &owait.wait);
1968 }
1969
1970 if (locked) {
fb2a6fc5
JW
1971 mem_cgroup_oom_unlock(memcg);
1972 /*
1973 * There is no guarantee that an OOM-lock contender
1974 * sees the wakeups triggered by the OOM kill
1975 * uncharges. Wake any sleepers explicitely.
1976 */
1977 memcg_oom_recover(memcg);
1978 }
49426420 1979cleanup:
626ebc41 1980 current->memcg_in_oom = NULL;
3812c8c8 1981 css_put(&memcg->css);
867578cb 1982 return true;
0b7f569e
KH
1983}
1984
3d8b38eb
RG
1985/**
1986 * mem_cgroup_get_oom_group - get a memory cgroup to clean up after OOM
1987 * @victim: task to be killed by the OOM killer
1988 * @oom_domain: memcg in case of memcg OOM, NULL in case of system-wide OOM
1989 *
1990 * Returns a pointer to a memory cgroup, which has to be cleaned up
1991 * by killing all belonging OOM-killable tasks.
1992 *
1993 * Caller has to call mem_cgroup_put() on the returned non-NULL memcg.
1994 */
1995struct mem_cgroup *mem_cgroup_get_oom_group(struct task_struct *victim,
1996 struct mem_cgroup *oom_domain)
1997{
1998 struct mem_cgroup *oom_group = NULL;
1999 struct mem_cgroup *memcg;
2000
2001 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
2002 return NULL;
2003
2004 if (!oom_domain)
2005 oom_domain = root_mem_cgroup;
2006
2007 rcu_read_lock();
2008
2009 memcg = mem_cgroup_from_task(victim);
2010 if (memcg == root_mem_cgroup)
2011 goto out;
2012
48fe267c
RG
2013 /*
2014 * If the victim task has been asynchronously moved to a different
2015 * memory cgroup, we might end up killing tasks outside oom_domain.
2016 * In this case it's better to ignore memory.group.oom.
2017 */
2018 if (unlikely(!mem_cgroup_is_descendant(memcg, oom_domain)))
2019 goto out;
2020
3d8b38eb
RG
2021 /*
2022 * Traverse the memory cgroup hierarchy from the victim task's
2023 * cgroup up to the OOMing cgroup (or root) to find the
2024 * highest-level memory cgroup with oom.group set.
2025 */
2026 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
2027 if (memcg->oom_group)
2028 oom_group = memcg;
2029
2030 if (memcg == oom_domain)
2031 break;
2032 }
2033
2034 if (oom_group)
2035 css_get(&oom_group->css);
2036out:
2037 rcu_read_unlock();
2038
2039 return oom_group;
2040}
2041
2042void mem_cgroup_print_oom_group(struct mem_cgroup *memcg)
2043{
2044 pr_info("Tasks in ");
2045 pr_cont_cgroup_path(memcg->css.cgroup);
2046 pr_cont(" are going to be killed due to memory.oom.group set\n");
2047}
2048
d7365e78 2049/**
81f8c3a4
JW
2050 * lock_page_memcg - lock a page->mem_cgroup binding
2051 * @page: the page
32047e2a 2052 *
81f8c3a4 2053 * This function protects unlocked LRU pages from being moved to
739f79fc
JW
2054 * another cgroup.
2055 *
2056 * It ensures lifetime of the returned memcg. Caller is responsible
2057 * for the lifetime of the page; __unlock_page_memcg() is available
2058 * when @page might get freed inside the locked section.
d69b042f 2059 */
739f79fc 2060struct mem_cgroup *lock_page_memcg(struct page *page)
89c06bd5 2061{
9da7b521 2062 struct page *head = compound_head(page); /* rmap on tail pages */
89c06bd5 2063 struct mem_cgroup *memcg;
6de22619 2064 unsigned long flags;
89c06bd5 2065
6de22619
JW
2066 /*
2067 * The RCU lock is held throughout the transaction. The fast
2068 * path can get away without acquiring the memcg->move_lock
2069 * because page moving starts with an RCU grace period.
739f79fc
JW
2070 *
2071 * The RCU lock also protects the memcg from being freed when
2072 * the page state that is going to change is the only thing
2073 * preventing the page itself from being freed. E.g. writeback
2074 * doesn't hold a page reference and relies on PG_writeback to
2075 * keep off truncation, migration and so forth.
2076 */
d7365e78
JW
2077 rcu_read_lock();
2078
2079 if (mem_cgroup_disabled())
739f79fc 2080 return NULL;
89c06bd5 2081again:
9da7b521 2082 memcg = head->mem_cgroup;
29833315 2083 if (unlikely(!memcg))
739f79fc 2084 return NULL;
d7365e78 2085
bdcbb659 2086 if (atomic_read(&memcg->moving_account) <= 0)
739f79fc 2087 return memcg;
89c06bd5 2088
6de22619 2089 spin_lock_irqsave(&memcg->move_lock, flags);
9da7b521 2090 if (memcg != head->mem_cgroup) {
6de22619 2091 spin_unlock_irqrestore(&memcg->move_lock, flags);
89c06bd5
KH
2092 goto again;
2093 }
6de22619
JW
2094
2095 /*
2096 * When charge migration first begins, we can have locked and
2097 * unlocked page stat updates happening concurrently. Track
81f8c3a4 2098 * the task who has the lock for unlock_page_memcg().
6de22619
JW
2099 */
2100 memcg->move_lock_task = current;
2101 memcg->move_lock_flags = flags;
d7365e78 2102
739f79fc 2103 return memcg;
89c06bd5 2104}
81f8c3a4 2105EXPORT_SYMBOL(lock_page_memcg);
89c06bd5 2106
d7365e78 2107/**
739f79fc
JW
2108 * __unlock_page_memcg - unlock and unpin a memcg
2109 * @memcg: the memcg
2110 *
2111 * Unlock and unpin a memcg returned by lock_page_memcg().
d7365e78 2112 */
739f79fc 2113void __unlock_page_memcg(struct mem_cgroup *memcg)
89c06bd5 2114{
6de22619
JW
2115 if (memcg && memcg->move_lock_task == current) {
2116 unsigned long flags = memcg->move_lock_flags;
2117
2118 memcg->move_lock_task = NULL;
2119 memcg->move_lock_flags = 0;
2120
2121 spin_unlock_irqrestore(&memcg->move_lock, flags);
2122 }
89c06bd5 2123
d7365e78 2124 rcu_read_unlock();
89c06bd5 2125}
739f79fc
JW
2126
2127/**
2128 * unlock_page_memcg - unlock a page->mem_cgroup binding
2129 * @page: the page
2130 */
2131void unlock_page_memcg(struct page *page)
2132{
9da7b521
JW
2133 struct page *head = compound_head(page);
2134
2135 __unlock_page_memcg(head->mem_cgroup);
739f79fc 2136}
81f8c3a4 2137EXPORT_SYMBOL(unlock_page_memcg);
89c06bd5 2138
cdec2e42
KH
2139struct memcg_stock_pcp {
2140 struct mem_cgroup *cached; /* this never be root cgroup */
11c9ea4e 2141 unsigned int nr_pages;
bf4f0599
RG
2142
2143#ifdef CONFIG_MEMCG_KMEM
2144 struct obj_cgroup *cached_objcg;
2145 unsigned int nr_bytes;
2146#endif
2147
cdec2e42 2148 struct work_struct work;
26fe6168 2149 unsigned long flags;
a0db00fc 2150#define FLUSHING_CACHED_CHARGE 0
cdec2e42
KH
2151};
2152static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
9f50fad6 2153static DEFINE_MUTEX(percpu_charge_mutex);
cdec2e42 2154
bf4f0599
RG
2155#ifdef CONFIG_MEMCG_KMEM
2156static void drain_obj_stock(struct memcg_stock_pcp *stock);
2157static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2158 struct mem_cgroup *root_memcg);
2159
2160#else
2161static inline void drain_obj_stock(struct memcg_stock_pcp *stock)
2162{
2163}
2164static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2165 struct mem_cgroup *root_memcg)
2166{
2167 return false;
2168}
2169#endif
2170
a0956d54
SS
2171/**
2172 * consume_stock: Try to consume stocked charge on this cpu.
2173 * @memcg: memcg to consume from.
2174 * @nr_pages: how many pages to charge.
2175 *
2176 * The charges will only happen if @memcg matches the current cpu's memcg
2177 * stock, and at least @nr_pages are available in that stock. Failure to
2178 * service an allocation will refill the stock.
2179 *
2180 * returns true if successful, false otherwise.
cdec2e42 2181 */
a0956d54 2182static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
cdec2e42
KH
2183{
2184 struct memcg_stock_pcp *stock;
db2ba40c 2185 unsigned long flags;
3e32cb2e 2186 bool ret = false;
cdec2e42 2187
a983b5eb 2188 if (nr_pages > MEMCG_CHARGE_BATCH)
3e32cb2e 2189 return ret;
a0956d54 2190
db2ba40c
JW
2191 local_irq_save(flags);
2192
2193 stock = this_cpu_ptr(&memcg_stock);
3e32cb2e 2194 if (memcg == stock->cached && stock->nr_pages >= nr_pages) {
a0956d54 2195 stock->nr_pages -= nr_pages;
3e32cb2e
JW
2196 ret = true;
2197 }
db2ba40c
JW
2198
2199 local_irq_restore(flags);
2200
cdec2e42
KH
2201 return ret;
2202}
2203
2204/*
3e32cb2e 2205 * Returns stocks cached in percpu and reset cached information.
cdec2e42
KH
2206 */
2207static void drain_stock(struct memcg_stock_pcp *stock)
2208{
2209 struct mem_cgroup *old = stock->cached;
2210
1a3e1f40
JW
2211 if (!old)
2212 return;
2213
11c9ea4e 2214 if (stock->nr_pages) {
3e32cb2e 2215 page_counter_uncharge(&old->memory, stock->nr_pages);
7941d214 2216 if (do_memsw_account())
3e32cb2e 2217 page_counter_uncharge(&old->memsw, stock->nr_pages);
11c9ea4e 2218 stock->nr_pages = 0;
cdec2e42 2219 }
1a3e1f40
JW
2220
2221 css_put(&old->css);
cdec2e42 2222 stock->cached = NULL;
cdec2e42
KH
2223}
2224
cdec2e42
KH
2225static void drain_local_stock(struct work_struct *dummy)
2226{
db2ba40c
JW
2227 struct memcg_stock_pcp *stock;
2228 unsigned long flags;
2229
72f0184c
MH
2230 /*
2231 * The only protection from memory hotplug vs. drain_stock races is
2232 * that we always operate on local CPU stock here with IRQ disabled
2233 */
db2ba40c
JW
2234 local_irq_save(flags);
2235
2236 stock = this_cpu_ptr(&memcg_stock);
bf4f0599 2237 drain_obj_stock(stock);
cdec2e42 2238 drain_stock(stock);
26fe6168 2239 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
db2ba40c
JW
2240
2241 local_irq_restore(flags);
cdec2e42
KH
2242}
2243
2244/*
3e32cb2e 2245 * Cache charges(val) to local per_cpu area.
320cc51d 2246 * This will be consumed by consume_stock() function, later.
cdec2e42 2247 */
c0ff4b85 2248static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
cdec2e42 2249{
db2ba40c
JW
2250 struct memcg_stock_pcp *stock;
2251 unsigned long flags;
2252
2253 local_irq_save(flags);
cdec2e42 2254
db2ba40c 2255 stock = this_cpu_ptr(&memcg_stock);
c0ff4b85 2256 if (stock->cached != memcg) { /* reset if necessary */
cdec2e42 2257 drain_stock(stock);
1a3e1f40 2258 css_get(&memcg->css);
c0ff4b85 2259 stock->cached = memcg;
cdec2e42 2260 }
11c9ea4e 2261 stock->nr_pages += nr_pages;
db2ba40c 2262
a983b5eb 2263 if (stock->nr_pages > MEMCG_CHARGE_BATCH)
475d0487
RG
2264 drain_stock(stock);
2265
db2ba40c 2266 local_irq_restore(flags);
cdec2e42
KH
2267}
2268
2269/*
c0ff4b85 2270 * Drains all per-CPU charge caches for given root_memcg resp. subtree
6d3d6aa2 2271 * of the hierarchy under it.
cdec2e42 2272 */
6d3d6aa2 2273static void drain_all_stock(struct mem_cgroup *root_memcg)
cdec2e42 2274{
26fe6168 2275 int cpu, curcpu;
d38144b7 2276
6d3d6aa2
JW
2277 /* If someone's already draining, avoid adding running more workers. */
2278 if (!mutex_trylock(&percpu_charge_mutex))
2279 return;
72f0184c
MH
2280 /*
2281 * Notify other cpus that system-wide "drain" is running
2282 * We do not care about races with the cpu hotplug because cpu down
2283 * as well as workers from this path always operate on the local
2284 * per-cpu data. CPU up doesn't touch memcg_stock at all.
2285 */
5af12d0e 2286 curcpu = get_cpu();
cdec2e42
KH
2287 for_each_online_cpu(cpu) {
2288 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
c0ff4b85 2289 struct mem_cgroup *memcg;
e1a366be 2290 bool flush = false;
26fe6168 2291
e1a366be 2292 rcu_read_lock();
c0ff4b85 2293 memcg = stock->cached;
e1a366be
RG
2294 if (memcg && stock->nr_pages &&
2295 mem_cgroup_is_descendant(memcg, root_memcg))
2296 flush = true;
bf4f0599
RG
2297 if (obj_stock_flush_required(stock, root_memcg))
2298 flush = true;
e1a366be
RG
2299 rcu_read_unlock();
2300
2301 if (flush &&
2302 !test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
d1a05b69
MH
2303 if (cpu == curcpu)
2304 drain_local_stock(&stock->work);
2305 else
2306 schedule_work_on(cpu, &stock->work);
2307 }
cdec2e42 2308 }
5af12d0e 2309 put_cpu();
9f50fad6 2310 mutex_unlock(&percpu_charge_mutex);
cdec2e42
KH
2311}
2312
308167fc 2313static int memcg_hotplug_cpu_dead(unsigned int cpu)
cdec2e42 2314{
cdec2e42 2315 struct memcg_stock_pcp *stock;
42a30035 2316 struct mem_cgroup *memcg, *mi;
cdec2e42 2317
cdec2e42
KH
2318 stock = &per_cpu(memcg_stock, cpu);
2319 drain_stock(stock);
a983b5eb
JW
2320
2321 for_each_mem_cgroup(memcg) {
2322 int i;
2323
2324 for (i = 0; i < MEMCG_NR_STAT; i++) {
2325 int nid;
2326 long x;
2327
871789d4 2328 x = this_cpu_xchg(memcg->vmstats_percpu->stat[i], 0);
815744d7 2329 if (x)
42a30035
JW
2330 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
2331 atomic_long_add(x, &memcg->vmstats[i]);
a983b5eb
JW
2332
2333 if (i >= NR_VM_NODE_STAT_ITEMS)
2334 continue;
2335
2336 for_each_node(nid) {
2337 struct mem_cgroup_per_node *pn;
2338
2339 pn = mem_cgroup_nodeinfo(memcg, nid);
2340 x = this_cpu_xchg(pn->lruvec_stat_cpu->count[i], 0);
815744d7 2341 if (x)
42a30035
JW
2342 do {
2343 atomic_long_add(x, &pn->lruvec_stat[i]);
2344 } while ((pn = parent_nodeinfo(pn, nid)));
a983b5eb
JW
2345 }
2346 }
2347
e27be240 2348 for (i = 0; i < NR_VM_EVENT_ITEMS; i++) {
a983b5eb
JW
2349 long x;
2350
871789d4 2351 x = this_cpu_xchg(memcg->vmstats_percpu->events[i], 0);
815744d7 2352 if (x)
42a30035
JW
2353 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
2354 atomic_long_add(x, &memcg->vmevents[i]);
a983b5eb
JW
2355 }
2356 }
2357
308167fc 2358 return 0;
cdec2e42
KH
2359}
2360
f7e1cb6e
JW
2361static void reclaim_high(struct mem_cgroup *memcg,
2362 unsigned int nr_pages,
2363 gfp_t gfp_mask)
2364{
2365 do {
d1663a90
JK
2366 if (page_counter_read(&memcg->memory) <=
2367 READ_ONCE(memcg->memory.high))
f7e1cb6e 2368 continue;
e27be240 2369 memcg_memory_event(memcg, MEMCG_HIGH);
f7e1cb6e 2370 try_to_free_mem_cgroup_pages(memcg, nr_pages, gfp_mask, true);
4bf17307
CD
2371 } while ((memcg = parent_mem_cgroup(memcg)) &&
2372 !mem_cgroup_is_root(memcg));
f7e1cb6e
JW
2373}
2374
2375static void high_work_func(struct work_struct *work)
2376{
2377 struct mem_cgroup *memcg;
2378
2379 memcg = container_of(work, struct mem_cgroup, high_work);
a983b5eb 2380 reclaim_high(memcg, MEMCG_CHARGE_BATCH, GFP_KERNEL);
f7e1cb6e
JW
2381}
2382
0e4b01df
CD
2383/*
2384 * Clamp the maximum sleep time per allocation batch to 2 seconds. This is
2385 * enough to still cause a significant slowdown in most cases, while still
2386 * allowing diagnostics and tracing to proceed without becoming stuck.
2387 */
2388#define MEMCG_MAX_HIGH_DELAY_JIFFIES (2UL*HZ)
2389
2390/*
2391 * When calculating the delay, we use these either side of the exponentiation to
2392 * maintain precision and scale to a reasonable number of jiffies (see the table
2393 * below.
2394 *
2395 * - MEMCG_DELAY_PRECISION_SHIFT: Extra precision bits while translating the
2396 * overage ratio to a delay.
2397 * - MEMCG_DELAY_SCALING_SHIFT: The number of bits to scale down down the
2398 * proposed penalty in order to reduce to a reasonable number of jiffies, and
2399 * to produce a reasonable delay curve.
2400 *
2401 * MEMCG_DELAY_SCALING_SHIFT just happens to be a number that produces a
2402 * reasonable delay curve compared to precision-adjusted overage, not
2403 * penalising heavily at first, but still making sure that growth beyond the
2404 * limit penalises misbehaviour cgroups by slowing them down exponentially. For
2405 * example, with a high of 100 megabytes:
2406 *
2407 * +-------+------------------------+
2408 * | usage | time to allocate in ms |
2409 * +-------+------------------------+
2410 * | 100M | 0 |
2411 * | 101M | 6 |
2412 * | 102M | 25 |
2413 * | 103M | 57 |
2414 * | 104M | 102 |
2415 * | 105M | 159 |
2416 * | 106M | 230 |
2417 * | 107M | 313 |
2418 * | 108M | 409 |
2419 * | 109M | 518 |
2420 * | 110M | 639 |
2421 * | 111M | 774 |
2422 * | 112M | 921 |
2423 * | 113M | 1081 |
2424 * | 114M | 1254 |
2425 * | 115M | 1439 |
2426 * | 116M | 1638 |
2427 * | 117M | 1849 |
2428 * | 118M | 2000 |
2429 * | 119M | 2000 |
2430 * | 120M | 2000 |
2431 * +-------+------------------------+
2432 */
2433 #define MEMCG_DELAY_PRECISION_SHIFT 20
2434 #define MEMCG_DELAY_SCALING_SHIFT 14
2435
8a5dbc65 2436static u64 calculate_overage(unsigned long usage, unsigned long high)
b23afb93 2437{
8a5dbc65 2438 u64 overage;
b23afb93 2439
8a5dbc65
JK
2440 if (usage <= high)
2441 return 0;
e26733e0 2442
8a5dbc65
JK
2443 /*
2444 * Prevent division by 0 in overage calculation by acting as if
2445 * it was a threshold of 1 page
2446 */
2447 high = max(high, 1UL);
9b8b1754 2448
8a5dbc65
JK
2449 overage = usage - high;
2450 overage <<= MEMCG_DELAY_PRECISION_SHIFT;
2451 return div64_u64(overage, high);
2452}
e26733e0 2453
8a5dbc65
JK
2454static u64 mem_find_max_overage(struct mem_cgroup *memcg)
2455{
2456 u64 overage, max_overage = 0;
e26733e0 2457
8a5dbc65
JK
2458 do {
2459 overage = calculate_overage(page_counter_read(&memcg->memory),
d1663a90 2460 READ_ONCE(memcg->memory.high));
8a5dbc65 2461 max_overage = max(overage, max_overage);
e26733e0
CD
2462 } while ((memcg = parent_mem_cgroup(memcg)) &&
2463 !mem_cgroup_is_root(memcg));
2464
8a5dbc65
JK
2465 return max_overage;
2466}
2467
4b82ab4f
JK
2468static u64 swap_find_max_overage(struct mem_cgroup *memcg)
2469{
2470 u64 overage, max_overage = 0;
2471
2472 do {
2473 overage = calculate_overage(page_counter_read(&memcg->swap),
2474 READ_ONCE(memcg->swap.high));
2475 if (overage)
2476 memcg_memory_event(memcg, MEMCG_SWAP_HIGH);
2477 max_overage = max(overage, max_overage);
2478 } while ((memcg = parent_mem_cgroup(memcg)) &&
2479 !mem_cgroup_is_root(memcg));
2480
2481 return max_overage;
2482}
2483
8a5dbc65
JK
2484/*
2485 * Get the number of jiffies that we should penalise a mischievous cgroup which
2486 * is exceeding its memory.high by checking both it and its ancestors.
2487 */
2488static unsigned long calculate_high_delay(struct mem_cgroup *memcg,
2489 unsigned int nr_pages,
2490 u64 max_overage)
2491{
2492 unsigned long penalty_jiffies;
2493
e26733e0
CD
2494 if (!max_overage)
2495 return 0;
0e4b01df
CD
2496
2497 /*
0e4b01df
CD
2498 * We use overage compared to memory.high to calculate the number of
2499 * jiffies to sleep (penalty_jiffies). Ideally this value should be
2500 * fairly lenient on small overages, and increasingly harsh when the
2501 * memcg in question makes it clear that it has no intention of stopping
2502 * its crazy behaviour, so we exponentially increase the delay based on
2503 * overage amount.
2504 */
e26733e0
CD
2505 penalty_jiffies = max_overage * max_overage * HZ;
2506 penalty_jiffies >>= MEMCG_DELAY_PRECISION_SHIFT;
2507 penalty_jiffies >>= MEMCG_DELAY_SCALING_SHIFT;
0e4b01df
CD
2508
2509 /*
2510 * Factor in the task's own contribution to the overage, such that four
2511 * N-sized allocations are throttled approximately the same as one
2512 * 4N-sized allocation.
2513 *
2514 * MEMCG_CHARGE_BATCH pages is nominal, so work out how much smaller or
2515 * larger the current charge patch is than that.
2516 */
ff144e69 2517 return penalty_jiffies * nr_pages / MEMCG_CHARGE_BATCH;
e26733e0
CD
2518}
2519
2520/*
2521 * Scheduled by try_charge() to be executed from the userland return path
2522 * and reclaims memory over the high limit.
2523 */
2524void mem_cgroup_handle_over_high(void)
2525{
2526 unsigned long penalty_jiffies;
2527 unsigned long pflags;
2528 unsigned int nr_pages = current->memcg_nr_pages_over_high;
2529 struct mem_cgroup *memcg;
2530
2531 if (likely(!nr_pages))
2532 return;
2533
2534 memcg = get_mem_cgroup_from_mm(current->mm);
2535 reclaim_high(memcg, nr_pages, GFP_KERNEL);
2536 current->memcg_nr_pages_over_high = 0;
2537
2538 /*
2539 * memory.high is breached and reclaim is unable to keep up. Throttle
2540 * allocators proactively to slow down excessive growth.
2541 */
8a5dbc65
JK
2542 penalty_jiffies = calculate_high_delay(memcg, nr_pages,
2543 mem_find_max_overage(memcg));
0e4b01df 2544
4b82ab4f
JK
2545 penalty_jiffies += calculate_high_delay(memcg, nr_pages,
2546 swap_find_max_overage(memcg));
2547
ff144e69
JK
2548 /*
2549 * Clamp the max delay per usermode return so as to still keep the
2550 * application moving forwards and also permit diagnostics, albeit
2551 * extremely slowly.
2552 */
2553 penalty_jiffies = min(penalty_jiffies, MEMCG_MAX_HIGH_DELAY_JIFFIES);
2554
0e4b01df
CD
2555 /*
2556 * Don't sleep if the amount of jiffies this memcg owes us is so low
2557 * that it's not even worth doing, in an attempt to be nice to those who
2558 * go only a small amount over their memory.high value and maybe haven't
2559 * been aggressively reclaimed enough yet.
2560 */
2561 if (penalty_jiffies <= HZ / 100)
2562 goto out;
2563
2564 /*
2565 * If we exit early, we're guaranteed to die (since
2566 * schedule_timeout_killable sets TASK_KILLABLE). This means we don't
2567 * need to account for any ill-begotten jiffies to pay them off later.
2568 */
2569 psi_memstall_enter(&pflags);
2570 schedule_timeout_killable(penalty_jiffies);
2571 psi_memstall_leave(&pflags);
2572
2573out:
2574 css_put(&memcg->css);
b23afb93
TH
2575}
2576
00501b53
JW
2577static int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2578 unsigned int nr_pages)
8a9f3ccd 2579{
a983b5eb 2580 unsigned int batch = max(MEMCG_CHARGE_BATCH, nr_pages);
9b130619 2581 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
6539cc05 2582 struct mem_cgroup *mem_over_limit;
3e32cb2e 2583 struct page_counter *counter;
6539cc05 2584 unsigned long nr_reclaimed;
b70a2a21
JW
2585 bool may_swap = true;
2586 bool drained = false;
29ef680a 2587 enum oom_status oom_status;
a636b327 2588
ce00a967 2589 if (mem_cgroup_is_root(memcg))
10d53c74 2590 return 0;
6539cc05 2591retry:
b6b6cc72 2592 if (consume_stock(memcg, nr_pages))
10d53c74 2593 return 0;
8a9f3ccd 2594
7941d214 2595 if (!do_memsw_account() ||
6071ca52
JW
2596 page_counter_try_charge(&memcg->memsw, batch, &counter)) {
2597 if (page_counter_try_charge(&memcg->memory, batch, &counter))
6539cc05 2598 goto done_restock;
7941d214 2599 if (do_memsw_account())
3e32cb2e
JW
2600 page_counter_uncharge(&memcg->memsw, batch);
2601 mem_over_limit = mem_cgroup_from_counter(counter, memory);
3fbe7244 2602 } else {
3e32cb2e 2603 mem_over_limit = mem_cgroup_from_counter(counter, memsw);
b70a2a21 2604 may_swap = false;
3fbe7244 2605 }
7a81b88c 2606
6539cc05
JW
2607 if (batch > nr_pages) {
2608 batch = nr_pages;
2609 goto retry;
2610 }
6d61ef40 2611
869712fd
JW
2612 /*
2613 * Memcg doesn't have a dedicated reserve for atomic
2614 * allocations. But like the global atomic pool, we need to
2615 * put the burden of reclaim on regular allocation requests
2616 * and let these go through as privileged allocations.
2617 */
2618 if (gfp_mask & __GFP_ATOMIC)
2619 goto force;
2620
06b078fc
JW
2621 /*
2622 * Unlike in global OOM situations, memcg is not in a physical
2623 * memory shortage. Allow dying and OOM-killed tasks to
2624 * bypass the last charges so that they can exit quickly and
2625 * free their memory.
2626 */
7775face 2627 if (unlikely(should_force_charge()))
10d53c74 2628 goto force;
06b078fc 2629
89a28483
JW
2630 /*
2631 * Prevent unbounded recursion when reclaim operations need to
2632 * allocate memory. This might exceed the limits temporarily,
2633 * but we prefer facilitating memory reclaim and getting back
2634 * under the limit over triggering OOM kills in these cases.
2635 */
2636 if (unlikely(current->flags & PF_MEMALLOC))
2637 goto force;
2638
06b078fc
JW
2639 if (unlikely(task_in_memcg_oom(current)))
2640 goto nomem;
2641
d0164adc 2642 if (!gfpflags_allow_blocking(gfp_mask))
6539cc05 2643 goto nomem;
4b534334 2644
e27be240 2645 memcg_memory_event(mem_over_limit, MEMCG_MAX);
241994ed 2646
b70a2a21
JW
2647 nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
2648 gfp_mask, may_swap);
6539cc05 2649
61e02c74 2650 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
6539cc05 2651 goto retry;
28c34c29 2652
b70a2a21 2653 if (!drained) {
6d3d6aa2 2654 drain_all_stock(mem_over_limit);
b70a2a21
JW
2655 drained = true;
2656 goto retry;
2657 }
2658
28c34c29
JW
2659 if (gfp_mask & __GFP_NORETRY)
2660 goto nomem;
6539cc05
JW
2661 /*
2662 * Even though the limit is exceeded at this point, reclaim
2663 * may have been able to free some pages. Retry the charge
2664 * before killing the task.
2665 *
2666 * Only for regular pages, though: huge pages are rather
2667 * unlikely to succeed so close to the limit, and we fall back
2668 * to regular pages anyway in case of failure.
2669 */
61e02c74 2670 if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
6539cc05
JW
2671 goto retry;
2672 /*
2673 * At task move, charge accounts can be doubly counted. So, it's
2674 * better to wait until the end of task_move if something is going on.
2675 */
2676 if (mem_cgroup_wait_acct_move(mem_over_limit))
2677 goto retry;
2678
9b130619
JW
2679 if (nr_retries--)
2680 goto retry;
2681
38d38493 2682 if (gfp_mask & __GFP_RETRY_MAYFAIL)
29ef680a
MH
2683 goto nomem;
2684
06b078fc 2685 if (gfp_mask & __GFP_NOFAIL)
10d53c74 2686 goto force;
06b078fc 2687
6539cc05 2688 if (fatal_signal_pending(current))
10d53c74 2689 goto force;
6539cc05 2690
29ef680a
MH
2691 /*
2692 * keep retrying as long as the memcg oom killer is able to make
2693 * a forward progress or bypass the charge if the oom killer
2694 * couldn't make any progress.
2695 */
2696 oom_status = mem_cgroup_oom(mem_over_limit, gfp_mask,
3608de07 2697 get_order(nr_pages * PAGE_SIZE));
29ef680a
MH
2698 switch (oom_status) {
2699 case OOM_SUCCESS:
2700 nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
29ef680a
MH
2701 goto retry;
2702 case OOM_FAILED:
2703 goto force;
2704 default:
2705 goto nomem;
2706 }
7a81b88c 2707nomem:
6d1fdc48 2708 if (!(gfp_mask & __GFP_NOFAIL))
3168ecbe 2709 return -ENOMEM;
10d53c74
TH
2710force:
2711 /*
2712 * The allocation either can't fail or will lead to more memory
2713 * being freed very soon. Allow memory usage go over the limit
2714 * temporarily by force charging it.
2715 */
2716 page_counter_charge(&memcg->memory, nr_pages);
7941d214 2717 if (do_memsw_account())
10d53c74 2718 page_counter_charge(&memcg->memsw, nr_pages);
10d53c74
TH
2719
2720 return 0;
6539cc05
JW
2721
2722done_restock:
2723 if (batch > nr_pages)
2724 refill_stock(memcg, batch - nr_pages);
b23afb93 2725
241994ed 2726 /*
b23afb93
TH
2727 * If the hierarchy is above the normal consumption range, schedule
2728 * reclaim on returning to userland. We can perform reclaim here
71baba4b 2729 * if __GFP_RECLAIM but let's always punt for simplicity and so that
b23afb93
TH
2730 * GFP_KERNEL can consistently be used during reclaim. @memcg is
2731 * not recorded as it most likely matches current's and won't
2732 * change in the meantime. As high limit is checked again before
2733 * reclaim, the cost of mismatch is negligible.
241994ed
JW
2734 */
2735 do {
4b82ab4f
JK
2736 bool mem_high, swap_high;
2737
2738 mem_high = page_counter_read(&memcg->memory) >
2739 READ_ONCE(memcg->memory.high);
2740 swap_high = page_counter_read(&memcg->swap) >
2741 READ_ONCE(memcg->swap.high);
2742
2743 /* Don't bother a random interrupted task */
2744 if (in_interrupt()) {
2745 if (mem_high) {
f7e1cb6e
JW
2746 schedule_work(&memcg->high_work);
2747 break;
2748 }
4b82ab4f
JK
2749 continue;
2750 }
2751
2752 if (mem_high || swap_high) {
2753 /*
2754 * The allocating tasks in this cgroup will need to do
2755 * reclaim or be throttled to prevent further growth
2756 * of the memory or swap footprints.
2757 *
2758 * Target some best-effort fairness between the tasks,
2759 * and distribute reclaim work and delay penalties
2760 * based on how much each task is actually allocating.
2761 */
9516a18a 2762 current->memcg_nr_pages_over_high += batch;
b23afb93
TH
2763 set_notify_resume(current);
2764 break;
2765 }
241994ed 2766 } while ((memcg = parent_mem_cgroup(memcg)));
10d53c74
TH
2767
2768 return 0;
7a81b88c 2769}
8a9f3ccd 2770
f0e45fb4 2771#if defined(CONFIG_MEMCG_KMEM) || defined(CONFIG_MMU)
00501b53 2772static void cancel_charge(struct mem_cgroup *memcg, unsigned int nr_pages)
a3032a2c 2773{
ce00a967
JW
2774 if (mem_cgroup_is_root(memcg))
2775 return;
2776
3e32cb2e 2777 page_counter_uncharge(&memcg->memory, nr_pages);
7941d214 2778 if (do_memsw_account())
3e32cb2e 2779 page_counter_uncharge(&memcg->memsw, nr_pages);
d01dd17f 2780}
f0e45fb4 2781#endif
d01dd17f 2782
d9eb1ea2 2783static void commit_charge(struct page *page, struct mem_cgroup *memcg)
0a31bc97 2784{
1306a85a 2785 VM_BUG_ON_PAGE(page->mem_cgroup, page);
0a31bc97 2786 /*
a0b5b414 2787 * Any of the following ensures page->mem_cgroup stability:
0a31bc97 2788 *
a0b5b414
JW
2789 * - the page lock
2790 * - LRU isolation
2791 * - lock_page_memcg()
2792 * - exclusive reference
0a31bc97 2793 */
1306a85a 2794 page->mem_cgroup = memcg;
7a81b88c 2795}
66e1707b 2796
84c07d11 2797#ifdef CONFIG_MEMCG_KMEM
8380ce47
RG
2798/*
2799 * Returns a pointer to the memory cgroup to which the kernel object is charged.
2800 *
2801 * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
2802 * cgroup_mutex, etc.
2803 */
2804struct mem_cgroup *mem_cgroup_from_obj(void *p)
2805{
2806 struct page *page;
2807
2808 if (mem_cgroup_disabled())
2809 return NULL;
2810
2811 page = virt_to_head_page(p);
2812
2813 /*
2814 * Slab pages don't have page->mem_cgroup set because corresponding
2815 * kmem caches can be reparented during the lifetime. That's why
2816 * memcg_from_slab_page() should be used instead.
2817 */
2818 if (PageSlab(page))
2819 return memcg_from_slab_page(page);
2820
2821 /* All other pages use page->mem_cgroup */
2822 return page->mem_cgroup;
2823}
2824
bf4f0599
RG
2825__always_inline struct obj_cgroup *get_obj_cgroup_from_current(void)
2826{
2827 struct obj_cgroup *objcg = NULL;
2828 struct mem_cgroup *memcg;
2829
2830 if (unlikely(!current->mm && !current->active_memcg))
2831 return NULL;
2832
2833 rcu_read_lock();
2834 if (unlikely(current->active_memcg))
2835 memcg = rcu_dereference(current->active_memcg);
2836 else
2837 memcg = mem_cgroup_from_task(current);
2838
2839 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg)) {
2840 objcg = rcu_dereference(memcg->objcg);
2841 if (objcg && obj_cgroup_tryget(objcg))
2842 break;
2843 }
2844 rcu_read_unlock();
2845
2846 return objcg;
2847}
2848
f3bb3043 2849static int memcg_alloc_cache_id(void)
55007d84 2850{
f3bb3043
VD
2851 int id, size;
2852 int err;
2853
dbcf73e2 2854 id = ida_simple_get(&memcg_cache_ida,
f3bb3043
VD
2855 0, MEMCG_CACHES_MAX_SIZE, GFP_KERNEL);
2856 if (id < 0)
2857 return id;
55007d84 2858
dbcf73e2 2859 if (id < memcg_nr_cache_ids)
f3bb3043
VD
2860 return id;
2861
2862 /*
2863 * There's no space for the new id in memcg_caches arrays,
2864 * so we have to grow them.
2865 */
05257a1a 2866 down_write(&memcg_cache_ids_sem);
f3bb3043
VD
2867
2868 size = 2 * (id + 1);
55007d84
GC
2869 if (size < MEMCG_CACHES_MIN_SIZE)
2870 size = MEMCG_CACHES_MIN_SIZE;
2871 else if (size > MEMCG_CACHES_MAX_SIZE)
2872 size = MEMCG_CACHES_MAX_SIZE;
2873
f3bb3043 2874 err = memcg_update_all_caches(size);
60d3fd32
VD
2875 if (!err)
2876 err = memcg_update_all_list_lrus(size);
05257a1a
VD
2877 if (!err)
2878 memcg_nr_cache_ids = size;
2879
2880 up_write(&memcg_cache_ids_sem);
2881
f3bb3043 2882 if (err) {
dbcf73e2 2883 ida_simple_remove(&memcg_cache_ida, id);
f3bb3043
VD
2884 return err;
2885 }
2886 return id;
2887}
2888
2889static void memcg_free_cache_id(int id)
2890{
dbcf73e2 2891 ida_simple_remove(&memcg_cache_ida, id);
55007d84
GC
2892}
2893
d5b3cf71 2894struct memcg_kmem_cache_create_work {
5722d094
VD
2895 struct mem_cgroup *memcg;
2896 struct kmem_cache *cachep;
2897 struct work_struct work;
2898};
2899
d5b3cf71 2900static void memcg_kmem_cache_create_func(struct work_struct *w)
d7f25f8a 2901{
d5b3cf71
VD
2902 struct memcg_kmem_cache_create_work *cw =
2903 container_of(w, struct memcg_kmem_cache_create_work, work);
5722d094
VD
2904 struct mem_cgroup *memcg = cw->memcg;
2905 struct kmem_cache *cachep = cw->cachep;
d7f25f8a 2906
d5b3cf71 2907 memcg_create_kmem_cache(memcg, cachep);
bd673145 2908
5722d094 2909 css_put(&memcg->css);
d7f25f8a
GC
2910 kfree(cw);
2911}
2912
2913/*
2914 * Enqueue the creation of a per-memcg kmem_cache.
d7f25f8a 2915 */
85cfb245 2916static void memcg_schedule_kmem_cache_create(struct mem_cgroup *memcg,
d5b3cf71 2917 struct kmem_cache *cachep)
d7f25f8a 2918{
d5b3cf71 2919 struct memcg_kmem_cache_create_work *cw;
d7f25f8a 2920
f0a3a24b
RG
2921 if (!css_tryget_online(&memcg->css))
2922 return;
2923
c892fd82 2924 cw = kmalloc(sizeof(*cw), GFP_NOWAIT | __GFP_NOWARN);
3a98990a
MS
2925 if (!cw) {
2926 css_put(&memcg->css);
d7f25f8a 2927 return;
3a98990a 2928 }
8135be5a 2929
d7f25f8a
GC
2930 cw->memcg = memcg;
2931 cw->cachep = cachep;
d5b3cf71 2932 INIT_WORK(&cw->work, memcg_kmem_cache_create_func);
d7f25f8a 2933
17cc4dfe 2934 queue_work(memcg_kmem_cache_wq, &cw->work);
d7f25f8a
GC
2935}
2936
45264778
VD
2937static inline bool memcg_kmem_bypass(void)
2938{
50d53d7c
ZL
2939 if (in_interrupt())
2940 return true;
2941
2942 /* Allow remote memcg charging in kthread contexts. */
2943 if ((!current->mm || (current->flags & PF_KTHREAD)) &&
2944 !current->active_memcg)
45264778
VD
2945 return true;
2946 return false;
2947}
2948
2949/**
2950 * memcg_kmem_get_cache: select the correct per-memcg cache for allocation
2951 * @cachep: the original global kmem cache
2952 *
d7f25f8a
GC
2953 * Return the kmem_cache we're supposed to use for a slab allocation.
2954 * We try to use the current memcg's version of the cache.
2955 *
45264778
VD
2956 * If the cache does not exist yet, if we are the first user of it, we
2957 * create it asynchronously in a workqueue and let the current allocation
2958 * go through with the original cache.
d7f25f8a 2959 *
45264778
VD
2960 * This function takes a reference to the cache it returns to assure it
2961 * won't get destroyed while we are working with it. Once the caller is
2962 * done with it, memcg_kmem_put_cache() must be called to release the
2963 * reference.
d7f25f8a 2964 */
45264778 2965struct kmem_cache *memcg_kmem_get_cache(struct kmem_cache *cachep)
d7f25f8a
GC
2966{
2967 struct mem_cgroup *memcg;
959c8963 2968 struct kmem_cache *memcg_cachep;
f0a3a24b 2969 struct memcg_cache_array *arr;
2a4db7eb 2970 int kmemcg_id;
d7f25f8a 2971
f7ce3190 2972 VM_BUG_ON(!is_root_cache(cachep));
d7f25f8a 2973
45264778 2974 if (memcg_kmem_bypass())
230e9fc2
VD
2975 return cachep;
2976
f0a3a24b
RG
2977 rcu_read_lock();
2978
2979 if (unlikely(current->active_memcg))
2980 memcg = current->active_memcg;
2981 else
2982 memcg = mem_cgroup_from_task(current);
2983
2984 if (!memcg || memcg == root_mem_cgroup)
2985 goto out_unlock;
2986
4db0c3c2 2987 kmemcg_id = READ_ONCE(memcg->kmemcg_id);
2a4db7eb 2988 if (kmemcg_id < 0)
f0a3a24b 2989 goto out_unlock;
d7f25f8a 2990
f0a3a24b
RG
2991 arr = rcu_dereference(cachep->memcg_params.memcg_caches);
2992
2993 /*
2994 * Make sure we will access the up-to-date value. The code updating
2995 * memcg_caches issues a write barrier to match the data dependency
2996 * barrier inside READ_ONCE() (see memcg_create_kmem_cache()).
2997 */
2998 memcg_cachep = READ_ONCE(arr->entries[kmemcg_id]);
ca0dde97
LZ
2999
3000 /*
3001 * If we are in a safe context (can wait, and not in interrupt
3002 * context), we could be be predictable and return right away.
3003 * This would guarantee that the allocation being performed
3004 * already belongs in the new cache.
3005 *
3006 * However, there are some clashes that can arrive from locking.
3007 * For instance, because we acquire the slab_mutex while doing
776ed0f0
VD
3008 * memcg_create_kmem_cache, this means no further allocation
3009 * could happen with the slab_mutex held. So it's better to
3010 * defer everything.
f0a3a24b
RG
3011 *
3012 * If the memcg is dying or memcg_cache is about to be released,
3013 * don't bother creating new kmem_caches. Because memcg_cachep
3014 * is ZEROed as the fist step of kmem offlining, we don't need
3015 * percpu_ref_tryget_live() here. css_tryget_online() check in
3016 * memcg_schedule_kmem_cache_create() will prevent us from
3017 * creation of a new kmem_cache.
ca0dde97 3018 */
f0a3a24b
RG
3019 if (unlikely(!memcg_cachep))
3020 memcg_schedule_kmem_cache_create(memcg, cachep);
3021 else if (percpu_ref_tryget(&memcg_cachep->memcg_params.refcnt))
3022 cachep = memcg_cachep;
3023out_unlock:
3024 rcu_read_unlock();
ca0dde97 3025 return cachep;
d7f25f8a 3026}
d7f25f8a 3027
45264778
VD
3028/**
3029 * memcg_kmem_put_cache: drop reference taken by memcg_kmem_get_cache
3030 * @cachep: the cache returned by memcg_kmem_get_cache
3031 */
3032void memcg_kmem_put_cache(struct kmem_cache *cachep)
8135be5a
VD
3033{
3034 if (!is_root_cache(cachep))
f0a3a24b 3035 percpu_ref_put(&cachep->memcg_params.refcnt);
8135be5a
VD
3036}
3037
45264778 3038/**
4b13f64d 3039 * __memcg_kmem_charge: charge a number of kernel pages to a memcg
10eaec2f 3040 * @memcg: memory cgroup to charge
45264778 3041 * @gfp: reclaim mode
92d0510c 3042 * @nr_pages: number of pages to charge
45264778
VD
3043 *
3044 * Returns 0 on success, an error code on failure.
3045 */
4b13f64d
RG
3046int __memcg_kmem_charge(struct mem_cgroup *memcg, gfp_t gfp,
3047 unsigned int nr_pages)
7ae1e1d0 3048{
f3ccb2c4 3049 struct page_counter *counter;
7ae1e1d0
GC
3050 int ret;
3051
f3ccb2c4 3052 ret = try_charge(memcg, gfp, nr_pages);
52c29b04 3053 if (ret)
f3ccb2c4 3054 return ret;
52c29b04
JW
3055
3056 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) &&
3057 !page_counter_try_charge(&memcg->kmem, nr_pages, &counter)) {
e55d9d9b
MH
3058
3059 /*
3060 * Enforce __GFP_NOFAIL allocation because callers are not
3061 * prepared to see failures and likely do not have any failure
3062 * handling code.
3063 */
3064 if (gfp & __GFP_NOFAIL) {
3065 page_counter_charge(&memcg->kmem, nr_pages);
3066 return 0;
3067 }
52c29b04
JW
3068 cancel_charge(memcg, nr_pages);
3069 return -ENOMEM;
7ae1e1d0 3070 }
f3ccb2c4 3071 return 0;
7ae1e1d0
GC
3072}
3073
4b13f64d
RG
3074/**
3075 * __memcg_kmem_uncharge: uncharge a number of kernel pages from a memcg
3076 * @memcg: memcg to uncharge
3077 * @nr_pages: number of pages to uncharge
3078 */
3079void __memcg_kmem_uncharge(struct mem_cgroup *memcg, unsigned int nr_pages)
3080{
3081 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
3082 page_counter_uncharge(&memcg->kmem, nr_pages);
3083
3084 page_counter_uncharge(&memcg->memory, nr_pages);
3085 if (do_memsw_account())
3086 page_counter_uncharge(&memcg->memsw, nr_pages);
3087}
3088
45264778 3089/**
f4b00eab 3090 * __memcg_kmem_charge_page: charge a kmem page to the current memory cgroup
45264778
VD
3091 * @page: page to charge
3092 * @gfp: reclaim mode
3093 * @order: allocation order
3094 *
3095 * Returns 0 on success, an error code on failure.
3096 */
f4b00eab 3097int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order)
7ae1e1d0 3098{
f3ccb2c4 3099 struct mem_cgroup *memcg;
fcff7d7e 3100 int ret = 0;
7ae1e1d0 3101
60cd4bcd 3102 if (memcg_kmem_bypass())
45264778
VD
3103 return 0;
3104
d46eb14b 3105 memcg = get_mem_cgroup_from_current();
c4159a75 3106 if (!mem_cgroup_is_root(memcg)) {
4b13f64d 3107 ret = __memcg_kmem_charge(memcg, gfp, 1 << order);
4d96ba35
RG
3108 if (!ret) {
3109 page->mem_cgroup = memcg;
c4159a75 3110 __SetPageKmemcg(page);
1a3e1f40 3111 return 0;
4d96ba35 3112 }
c4159a75 3113 }
7ae1e1d0 3114 css_put(&memcg->css);
d05e83a6 3115 return ret;
7ae1e1d0 3116}
49a18eae 3117
45264778 3118/**
f4b00eab 3119 * __memcg_kmem_uncharge_page: uncharge a kmem page
45264778
VD
3120 * @page: page to uncharge
3121 * @order: allocation order
3122 */
f4b00eab 3123void __memcg_kmem_uncharge_page(struct page *page, int order)
7ae1e1d0 3124{
1306a85a 3125 struct mem_cgroup *memcg = page->mem_cgroup;
f3ccb2c4 3126 unsigned int nr_pages = 1 << order;
7ae1e1d0 3127
7ae1e1d0
GC
3128 if (!memcg)
3129 return;
3130
309381fe 3131 VM_BUG_ON_PAGE(mem_cgroup_is_root(memcg), page);
4b13f64d 3132 __memcg_kmem_uncharge(memcg, nr_pages);
1306a85a 3133 page->mem_cgroup = NULL;
1a3e1f40 3134 css_put(&memcg->css);
c4159a75
VD
3135
3136 /* slab pages do not have PageKmemcg flag set */
3137 if (PageKmemcg(page))
3138 __ClearPageKmemcg(page);
60d3fd32 3139}
bf4f0599
RG
3140
3141static bool consume_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes)
3142{
3143 struct memcg_stock_pcp *stock;
3144 unsigned long flags;
3145 bool ret = false;
3146
3147 local_irq_save(flags);
3148
3149 stock = this_cpu_ptr(&memcg_stock);
3150 if (objcg == stock->cached_objcg && stock->nr_bytes >= nr_bytes) {
3151 stock->nr_bytes -= nr_bytes;
3152 ret = true;
3153 }
3154
3155 local_irq_restore(flags);
3156
3157 return ret;
3158}
3159
3160static void drain_obj_stock(struct memcg_stock_pcp *stock)
3161{
3162 struct obj_cgroup *old = stock->cached_objcg;
3163
3164 if (!old)
3165 return;
3166
3167 if (stock->nr_bytes) {
3168 unsigned int nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3169 unsigned int nr_bytes = stock->nr_bytes & (PAGE_SIZE - 1);
3170
3171 if (nr_pages) {
3172 rcu_read_lock();
3173 __memcg_kmem_uncharge(obj_cgroup_memcg(old), nr_pages);
3174 rcu_read_unlock();
3175 }
3176
3177 /*
3178 * The leftover is flushed to the centralized per-memcg value.
3179 * On the next attempt to refill obj stock it will be moved
3180 * to a per-cpu stock (probably, on an other CPU), see
3181 * refill_obj_stock().
3182 *
3183 * How often it's flushed is a trade-off between the memory
3184 * limit enforcement accuracy and potential CPU contention,
3185 * so it might be changed in the future.
3186 */
3187 atomic_add(nr_bytes, &old->nr_charged_bytes);
3188 stock->nr_bytes = 0;
3189 }
3190
3191 obj_cgroup_put(old);
3192 stock->cached_objcg = NULL;
3193}
3194
3195static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
3196 struct mem_cgroup *root_memcg)
3197{
3198 struct mem_cgroup *memcg;
3199
3200 if (stock->cached_objcg) {
3201 memcg = obj_cgroup_memcg(stock->cached_objcg);
3202 if (memcg && mem_cgroup_is_descendant(memcg, root_memcg))
3203 return true;
3204 }
3205
3206 return false;
3207}
3208
3209static void refill_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes)
3210{
3211 struct memcg_stock_pcp *stock;
3212 unsigned long flags;
3213
3214 local_irq_save(flags);
3215
3216 stock = this_cpu_ptr(&memcg_stock);
3217 if (stock->cached_objcg != objcg) { /* reset if necessary */
3218 drain_obj_stock(stock);
3219 obj_cgroup_get(objcg);
3220 stock->cached_objcg = objcg;
3221 stock->nr_bytes = atomic_xchg(&objcg->nr_charged_bytes, 0);
3222 }
3223 stock->nr_bytes += nr_bytes;
3224
3225 if (stock->nr_bytes > PAGE_SIZE)
3226 drain_obj_stock(stock);
3227
3228 local_irq_restore(flags);
3229}
3230
3231int obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp, size_t size)
3232{
3233 struct mem_cgroup *memcg;
3234 unsigned int nr_pages, nr_bytes;
3235 int ret;
3236
3237 if (consume_obj_stock(objcg, size))
3238 return 0;
3239
3240 /*
3241 * In theory, memcg->nr_charged_bytes can have enough
3242 * pre-charged bytes to satisfy the allocation. However,
3243 * flushing memcg->nr_charged_bytes requires two atomic
3244 * operations, and memcg->nr_charged_bytes can't be big,
3245 * so it's better to ignore it and try grab some new pages.
3246 * memcg->nr_charged_bytes will be flushed in
3247 * refill_obj_stock(), called from this function or
3248 * independently later.
3249 */
3250 rcu_read_lock();
3251 memcg = obj_cgroup_memcg(objcg);
3252 css_get(&memcg->css);
3253 rcu_read_unlock();
3254
3255 nr_pages = size >> PAGE_SHIFT;
3256 nr_bytes = size & (PAGE_SIZE - 1);
3257
3258 if (nr_bytes)
3259 nr_pages += 1;
3260
3261 ret = __memcg_kmem_charge(memcg, gfp, nr_pages);
3262 if (!ret && nr_bytes)
3263 refill_obj_stock(objcg, PAGE_SIZE - nr_bytes);
3264
3265 css_put(&memcg->css);
3266 return ret;
3267}
3268
3269void obj_cgroup_uncharge(struct obj_cgroup *objcg, size_t size)
3270{
3271 refill_obj_stock(objcg, size);
3272}
3273
84c07d11 3274#endif /* CONFIG_MEMCG_KMEM */
7ae1e1d0 3275
ca3e0214
KH
3276#ifdef CONFIG_TRANSPARENT_HUGEPAGE
3277
ca3e0214
KH
3278/*
3279 * Because tail pages are not marked as "used", set it. We're under
f4b7e272 3280 * pgdat->lru_lock and migration entries setup in all page mappings.
ca3e0214 3281 */
e94c8a9c 3282void mem_cgroup_split_huge_fixup(struct page *head)
ca3e0214 3283{
1a3e1f40 3284 struct mem_cgroup *memcg = head->mem_cgroup;
e94c8a9c 3285 int i;
ca3e0214 3286
3d37c4a9
KH
3287 if (mem_cgroup_disabled())
3288 return;
b070e65c 3289
1a3e1f40
JW
3290 for (i = 1; i < HPAGE_PMD_NR; i++) {
3291 css_get(&memcg->css);
3292 head[i].mem_cgroup = memcg;
3293 }
ca3e0214 3294}
12d27107 3295#endif /* CONFIG_TRANSPARENT_HUGEPAGE */
ca3e0214 3296
c255a458 3297#ifdef CONFIG_MEMCG_SWAP
02491447
DN
3298/**
3299 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3300 * @entry: swap entry to be moved
3301 * @from: mem_cgroup which the entry is moved from
3302 * @to: mem_cgroup which the entry is moved to
3303 *
3304 * It succeeds only when the swap_cgroup's record for this entry is the same
3305 * as the mem_cgroup's id of @from.
3306 *
3307 * Returns 0 on success, -EINVAL on failure.
3308 *
3e32cb2e 3309 * The caller must have charged to @to, IOW, called page_counter_charge() about
02491447
DN
3310 * both res and memsw, and called css_get().
3311 */
3312static int mem_cgroup_move_swap_account(swp_entry_t entry,
e91cbb42 3313 struct mem_cgroup *from, struct mem_cgroup *to)
02491447
DN
3314{
3315 unsigned short old_id, new_id;
3316
34c00c31
LZ
3317 old_id = mem_cgroup_id(from);
3318 new_id = mem_cgroup_id(to);
02491447
DN
3319
3320 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
c9019e9b
JW
3321 mod_memcg_state(from, MEMCG_SWAP, -1);
3322 mod_memcg_state(to, MEMCG_SWAP, 1);
02491447
DN
3323 return 0;
3324 }
3325 return -EINVAL;
3326}
3327#else
3328static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
e91cbb42 3329 struct mem_cgroup *from, struct mem_cgroup *to)
02491447
DN
3330{
3331 return -EINVAL;
3332}
8c7c6e34 3333#endif
d13d1443 3334
bbec2e15 3335static DEFINE_MUTEX(memcg_max_mutex);
f212ad7c 3336
bbec2e15
RG
3337static int mem_cgroup_resize_max(struct mem_cgroup *memcg,
3338 unsigned long max, bool memsw)
628f4235 3339{
3e32cb2e 3340 bool enlarge = false;
bb4a7ea2 3341 bool drained = false;
3e32cb2e 3342 int ret;
c054a78c
YZ
3343 bool limits_invariant;
3344 struct page_counter *counter = memsw ? &memcg->memsw : &memcg->memory;
81d39c20 3345
3e32cb2e 3346 do {
628f4235
KH
3347 if (signal_pending(current)) {
3348 ret = -EINTR;
3349 break;
3350 }
3e32cb2e 3351
bbec2e15 3352 mutex_lock(&memcg_max_mutex);
c054a78c
YZ
3353 /*
3354 * Make sure that the new limit (memsw or memory limit) doesn't
bbec2e15 3355 * break our basic invariant rule memory.max <= memsw.max.
c054a78c 3356 */
15b42562 3357 limits_invariant = memsw ? max >= READ_ONCE(memcg->memory.max) :
bbec2e15 3358 max <= memcg->memsw.max;
c054a78c 3359 if (!limits_invariant) {
bbec2e15 3360 mutex_unlock(&memcg_max_mutex);
8c7c6e34 3361 ret = -EINVAL;
8c7c6e34
KH
3362 break;
3363 }
bbec2e15 3364 if (max > counter->max)
3e32cb2e 3365 enlarge = true;
bbec2e15
RG
3366 ret = page_counter_set_max(counter, max);
3367 mutex_unlock(&memcg_max_mutex);
8c7c6e34
KH
3368
3369 if (!ret)
3370 break;
3371
bb4a7ea2
SB
3372 if (!drained) {
3373 drain_all_stock(memcg);
3374 drained = true;
3375 continue;
3376 }
3377
1ab5c056
AR
3378 if (!try_to_free_mem_cgroup_pages(memcg, 1,
3379 GFP_KERNEL, !memsw)) {
3380 ret = -EBUSY;
3381 break;
3382 }
3383 } while (true);
3e32cb2e 3384
3c11ecf4
KH
3385 if (!ret && enlarge)
3386 memcg_oom_recover(memcg);
3e32cb2e 3387
628f4235
KH
3388 return ret;
3389}
3390
ef8f2327 3391unsigned long mem_cgroup_soft_limit_reclaim(pg_data_t *pgdat, int order,
0608f43d
AM
3392 gfp_t gfp_mask,
3393 unsigned long *total_scanned)
3394{
3395 unsigned long nr_reclaimed = 0;
ef8f2327 3396 struct mem_cgroup_per_node *mz, *next_mz = NULL;
0608f43d
AM
3397 unsigned long reclaimed;
3398 int loop = 0;
ef8f2327 3399 struct mem_cgroup_tree_per_node *mctz;
3e32cb2e 3400 unsigned long excess;
0608f43d
AM
3401 unsigned long nr_scanned;
3402
3403 if (order > 0)
3404 return 0;
3405
ef8f2327 3406 mctz = soft_limit_tree_node(pgdat->node_id);
d6507ff5
MH
3407
3408 /*
3409 * Do not even bother to check the largest node if the root
3410 * is empty. Do it lockless to prevent lock bouncing. Races
3411 * are acceptable as soft limit is best effort anyway.
3412 */
bfc7228b 3413 if (!mctz || RB_EMPTY_ROOT(&mctz->rb_root))
d6507ff5
MH
3414 return 0;
3415
0608f43d
AM
3416 /*
3417 * This loop can run a while, specially if mem_cgroup's continuously
3418 * keep exceeding their soft limit and putting the system under
3419 * pressure
3420 */
3421 do {
3422 if (next_mz)
3423 mz = next_mz;
3424 else
3425 mz = mem_cgroup_largest_soft_limit_node(mctz);
3426 if (!mz)
3427 break;
3428
3429 nr_scanned = 0;
ef8f2327 3430 reclaimed = mem_cgroup_soft_reclaim(mz->memcg, pgdat,
0608f43d
AM
3431 gfp_mask, &nr_scanned);
3432 nr_reclaimed += reclaimed;
3433 *total_scanned += nr_scanned;
0a31bc97 3434 spin_lock_irq(&mctz->lock);
bc2f2e7f 3435 __mem_cgroup_remove_exceeded(mz, mctz);
0608f43d
AM
3436
3437 /*
3438 * If we failed to reclaim anything from this memory cgroup
3439 * it is time to move on to the next cgroup
3440 */
3441 next_mz = NULL;
bc2f2e7f
VD
3442 if (!reclaimed)
3443 next_mz = __mem_cgroup_largest_soft_limit_node(mctz);
3444
3e32cb2e 3445 excess = soft_limit_excess(mz->memcg);
0608f43d
AM
3446 /*
3447 * One school of thought says that we should not add
3448 * back the node to the tree if reclaim returns 0.
3449 * But our reclaim could return 0, simply because due
3450 * to priority we are exposing a smaller subset of
3451 * memory to reclaim from. Consider this as a longer
3452 * term TODO.
3453 */
3454 /* If excess == 0, no tree ops */
cf2c8127 3455 __mem_cgroup_insert_exceeded(mz, mctz, excess);
0a31bc97 3456 spin_unlock_irq(&mctz->lock);
0608f43d
AM
3457 css_put(&mz->memcg->css);
3458 loop++;
3459 /*
3460 * Could not reclaim anything and there are no more
3461 * mem cgroups to try or we seem to be looping without
3462 * reclaiming anything.
3463 */
3464 if (!nr_reclaimed &&
3465 (next_mz == NULL ||
3466 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3467 break;
3468 } while (!nr_reclaimed);
3469 if (next_mz)
3470 css_put(&next_mz->memcg->css);
3471 return nr_reclaimed;
3472}
3473
ea280e7b
TH
3474/*
3475 * Test whether @memcg has children, dead or alive. Note that this
3476 * function doesn't care whether @memcg has use_hierarchy enabled and
3477 * returns %true if there are child csses according to the cgroup
b8f2935f 3478 * hierarchy. Testing use_hierarchy is the caller's responsibility.
ea280e7b 3479 */
b5f99b53
GC
3480static inline bool memcg_has_children(struct mem_cgroup *memcg)
3481{
ea280e7b
TH
3482 bool ret;
3483
ea280e7b
TH
3484 rcu_read_lock();
3485 ret = css_next_child(NULL, &memcg->css);
3486 rcu_read_unlock();
3487 return ret;
b5f99b53
GC
3488}
3489
c26251f9 3490/*
51038171 3491 * Reclaims as many pages from the given memcg as possible.
c26251f9
MH
3492 *
3493 * Caller is responsible for holding css reference for memcg.
3494 */
3495static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
3496{
3497 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
c26251f9 3498
c1e862c1
KH
3499 /* we call try-to-free pages for make this cgroup empty */
3500 lru_add_drain_all();
d12c60f6
JS
3501
3502 drain_all_stock(memcg);
3503
f817ed48 3504 /* try to free all pages in this cgroup */
3e32cb2e 3505 while (nr_retries && page_counter_read(&memcg->memory)) {
f817ed48 3506 int progress;
c1e862c1 3507
c26251f9
MH
3508 if (signal_pending(current))
3509 return -EINTR;
3510
b70a2a21
JW
3511 progress = try_to_free_mem_cgroup_pages(memcg, 1,
3512 GFP_KERNEL, true);
c1e862c1 3513 if (!progress) {
f817ed48 3514 nr_retries--;
c1e862c1 3515 /* maybe some writeback is necessary */
8aa7e847 3516 congestion_wait(BLK_RW_ASYNC, HZ/10);
c1e862c1 3517 }
f817ed48
KH
3518
3519 }
ab5196c2
MH
3520
3521 return 0;
cc847582
KH
3522}
3523
6770c64e
TH
3524static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
3525 char *buf, size_t nbytes,
3526 loff_t off)
c1e862c1 3527{
6770c64e 3528 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
c26251f9 3529
d8423011
MH
3530 if (mem_cgroup_is_root(memcg))
3531 return -EINVAL;
6770c64e 3532 return mem_cgroup_force_empty(memcg) ?: nbytes;
c1e862c1
KH
3533}
3534
182446d0
TH
3535static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
3536 struct cftype *cft)
18f59ea7 3537{
182446d0 3538 return mem_cgroup_from_css(css)->use_hierarchy;
18f59ea7
BS
3539}
3540
182446d0
TH
3541static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
3542 struct cftype *cft, u64 val)
18f59ea7
BS
3543{
3544 int retval = 0;
182446d0 3545 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5c9d535b 3546 struct mem_cgroup *parent_memcg = mem_cgroup_from_css(memcg->css.parent);
18f59ea7 3547
567fb435 3548 if (memcg->use_hierarchy == val)
0b8f73e1 3549 return 0;
567fb435 3550
18f59ea7 3551 /*
af901ca1 3552 * If parent's use_hierarchy is set, we can't make any modifications
18f59ea7
BS
3553 * in the child subtrees. If it is unset, then the change can
3554 * occur, provided the current cgroup has no children.
3555 *
3556 * For the root cgroup, parent_mem is NULL, we allow value to be
3557 * set if there are no children.
3558 */
c0ff4b85 3559 if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
18f59ea7 3560 (val == 1 || val == 0)) {
ea280e7b 3561 if (!memcg_has_children(memcg))
c0ff4b85 3562 memcg->use_hierarchy = val;
18f59ea7
BS
3563 else
3564 retval = -EBUSY;
3565 } else
3566 retval = -EINVAL;
567fb435 3567
18f59ea7
BS
3568 return retval;
3569}
3570
6f646156 3571static unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
ce00a967 3572{
42a30035 3573 unsigned long val;
ce00a967 3574
3e32cb2e 3575 if (mem_cgroup_is_root(memcg)) {
0d1c2072 3576 val = memcg_page_state(memcg, NR_FILE_PAGES) +
be5d0a74 3577 memcg_page_state(memcg, NR_ANON_MAPPED);
42a30035
JW
3578 if (swap)
3579 val += memcg_page_state(memcg, MEMCG_SWAP);
3e32cb2e 3580 } else {
ce00a967 3581 if (!swap)
3e32cb2e 3582 val = page_counter_read(&memcg->memory);
ce00a967 3583 else
3e32cb2e 3584 val = page_counter_read(&memcg->memsw);
ce00a967 3585 }
c12176d3 3586 return val;
ce00a967
JW
3587}
3588
3e32cb2e
JW
3589enum {
3590 RES_USAGE,
3591 RES_LIMIT,
3592 RES_MAX_USAGE,
3593 RES_FAILCNT,
3594 RES_SOFT_LIMIT,
3595};
ce00a967 3596
791badbd 3597static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
05b84301 3598 struct cftype *cft)
8cdea7c0 3599{
182446d0 3600 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3e32cb2e 3601 struct page_counter *counter;
af36f906 3602
3e32cb2e 3603 switch (MEMFILE_TYPE(cft->private)) {
8c7c6e34 3604 case _MEM:
3e32cb2e
JW
3605 counter = &memcg->memory;
3606 break;
8c7c6e34 3607 case _MEMSWAP:
3e32cb2e
JW
3608 counter = &memcg->memsw;
3609 break;
510fc4e1 3610 case _KMEM:
3e32cb2e 3611 counter = &memcg->kmem;
510fc4e1 3612 break;
d55f90bf 3613 case _TCP:
0db15298 3614 counter = &memcg->tcpmem;
d55f90bf 3615 break;
8c7c6e34
KH
3616 default:
3617 BUG();
8c7c6e34 3618 }
3e32cb2e
JW
3619
3620 switch (MEMFILE_ATTR(cft->private)) {
3621 case RES_USAGE:
3622 if (counter == &memcg->memory)
c12176d3 3623 return (u64)mem_cgroup_usage(memcg, false) * PAGE_SIZE;
3e32cb2e 3624 if (counter == &memcg->memsw)
c12176d3 3625 return (u64)mem_cgroup_usage(memcg, true) * PAGE_SIZE;
3e32cb2e
JW
3626 return (u64)page_counter_read(counter) * PAGE_SIZE;
3627 case RES_LIMIT:
bbec2e15 3628 return (u64)counter->max * PAGE_SIZE;
3e32cb2e
JW
3629 case RES_MAX_USAGE:
3630 return (u64)counter->watermark * PAGE_SIZE;
3631 case RES_FAILCNT:
3632 return counter->failcnt;
3633 case RES_SOFT_LIMIT:
3634 return (u64)memcg->soft_limit * PAGE_SIZE;
3635 default:
3636 BUG();
3637 }
8cdea7c0 3638}
510fc4e1 3639
4a87e2a2 3640static void memcg_flush_percpu_vmstats(struct mem_cgroup *memcg)
c350a99e 3641{
4a87e2a2 3642 unsigned long stat[MEMCG_NR_STAT] = {0};
c350a99e
RG
3643 struct mem_cgroup *mi;
3644 int node, cpu, i;
c350a99e
RG
3645
3646 for_each_online_cpu(cpu)
4a87e2a2 3647 for (i = 0; i < MEMCG_NR_STAT; i++)
6c1c2808 3648 stat[i] += per_cpu(memcg->vmstats_percpu->stat[i], cpu);
c350a99e
RG
3649
3650 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
4a87e2a2 3651 for (i = 0; i < MEMCG_NR_STAT; i++)
c350a99e
RG
3652 atomic_long_add(stat[i], &mi->vmstats[i]);
3653
3654 for_each_node(node) {
3655 struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
3656 struct mem_cgroup_per_node *pi;
3657
4a87e2a2 3658 for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++)
c350a99e
RG
3659 stat[i] = 0;
3660
3661 for_each_online_cpu(cpu)
4a87e2a2 3662 for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++)
6c1c2808
SB
3663 stat[i] += per_cpu(
3664 pn->lruvec_stat_cpu->count[i], cpu);
c350a99e
RG
3665
3666 for (pi = pn; pi; pi = parent_nodeinfo(pi, node))
4a87e2a2 3667 for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++)
c350a99e
RG
3668 atomic_long_add(stat[i], &pi->lruvec_stat[i]);
3669 }
3670}
3671
bb65f89b
RG
3672static void memcg_flush_percpu_vmevents(struct mem_cgroup *memcg)
3673{
3674 unsigned long events[NR_VM_EVENT_ITEMS];
3675 struct mem_cgroup *mi;
3676 int cpu, i;
3677
3678 for (i = 0; i < NR_VM_EVENT_ITEMS; i++)
3679 events[i] = 0;
3680
3681 for_each_online_cpu(cpu)
3682 for (i = 0; i < NR_VM_EVENT_ITEMS; i++)
6c1c2808
SB
3683 events[i] += per_cpu(memcg->vmstats_percpu->events[i],
3684 cpu);
bb65f89b
RG
3685
3686 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
3687 for (i = 0; i < NR_VM_EVENT_ITEMS; i++)
3688 atomic_long_add(events[i], &mi->vmevents[i]);
3689}
3690
84c07d11 3691#ifdef CONFIG_MEMCG_KMEM
567e9ab2 3692static int memcg_online_kmem(struct mem_cgroup *memcg)
d6441637 3693{
bf4f0599 3694 struct obj_cgroup *objcg;
d6441637
VD
3695 int memcg_id;
3696
b313aeee
VD
3697 if (cgroup_memory_nokmem)
3698 return 0;
3699
2a4db7eb 3700 BUG_ON(memcg->kmemcg_id >= 0);
567e9ab2 3701 BUG_ON(memcg->kmem_state);
d6441637 3702
f3bb3043 3703 memcg_id = memcg_alloc_cache_id();
0b8f73e1
JW
3704 if (memcg_id < 0)
3705 return memcg_id;
d6441637 3706
bf4f0599
RG
3707 objcg = obj_cgroup_alloc();
3708 if (!objcg) {
3709 memcg_free_cache_id(memcg_id);
3710 return -ENOMEM;
3711 }
3712 objcg->memcg = memcg;
3713 rcu_assign_pointer(memcg->objcg, objcg);
3714
d648bcc7
RG
3715 static_branch_enable(&memcg_kmem_enabled_key);
3716
d6441637 3717 /*
567e9ab2 3718 * A memory cgroup is considered kmem-online as soon as it gets
900a38f0 3719 * kmemcg_id. Setting the id after enabling static branching will
d6441637
VD
3720 * guarantee no one starts accounting before all call sites are
3721 * patched.
3722 */
900a38f0 3723 memcg->kmemcg_id = memcg_id;
567e9ab2 3724 memcg->kmem_state = KMEM_ONLINE;
bc2791f8 3725 INIT_LIST_HEAD(&memcg->kmem_caches);
0b8f73e1
JW
3726
3727 return 0;
d6441637
VD
3728}
3729
8e0a8912
JW
3730static void memcg_offline_kmem(struct mem_cgroup *memcg)
3731{
3732 struct cgroup_subsys_state *css;
3733 struct mem_cgroup *parent, *child;
3734 int kmemcg_id;
3735
3736 if (memcg->kmem_state != KMEM_ONLINE)
3737 return;
3738 /*
3739 * Clear the online state before clearing memcg_caches array
3740 * entries. The slab_mutex in memcg_deactivate_kmem_caches()
3741 * guarantees that no cache will be created for this cgroup
3742 * after we are done (see memcg_create_kmem_cache()).
3743 */
3744 memcg->kmem_state = KMEM_ALLOCATED;
3745
8e0a8912
JW
3746 parent = parent_mem_cgroup(memcg);
3747 if (!parent)
3748 parent = root_mem_cgroup;
3749
bee07b33 3750 /*
bf4f0599 3751 * Deactivate and reparent kmem_caches and objcgs.
bee07b33 3752 */
fb2f2b0a 3753 memcg_deactivate_kmem_caches(memcg, parent);
bf4f0599 3754 memcg_reparent_objcgs(memcg, parent);
fb2f2b0a
RG
3755
3756 kmemcg_id = memcg->kmemcg_id;
3757 BUG_ON(kmemcg_id < 0);
3758
8e0a8912
JW
3759 /*
3760 * Change kmemcg_id of this cgroup and all its descendants to the
3761 * parent's id, and then move all entries from this cgroup's list_lrus
3762 * to ones of the parent. After we have finished, all list_lrus
3763 * corresponding to this cgroup are guaranteed to remain empty. The
3764 * ordering is imposed by list_lru_node->lock taken by
3765 * memcg_drain_all_list_lrus().
3766 */
3a06bb78 3767 rcu_read_lock(); /* can be called from css_free w/o cgroup_mutex */
8e0a8912
JW
3768 css_for_each_descendant_pre(css, &memcg->css) {
3769 child = mem_cgroup_from_css(css);
3770 BUG_ON(child->kmemcg_id != kmemcg_id);
3771 child->kmemcg_id = parent->kmemcg_id;
3772 if (!memcg->use_hierarchy)
3773 break;
3774 }
3a06bb78
TH
3775 rcu_read_unlock();
3776
9bec5c35 3777 memcg_drain_all_list_lrus(kmemcg_id, parent);
8e0a8912
JW
3778
3779 memcg_free_cache_id(kmemcg_id);
3780}
3781
3782static void memcg_free_kmem(struct mem_cgroup *memcg)
3783{
0b8f73e1
JW
3784 /* css_alloc() failed, offlining didn't happen */
3785 if (unlikely(memcg->kmem_state == KMEM_ONLINE))
3786 memcg_offline_kmem(memcg);
8e0a8912 3787}
d6441637 3788#else
0b8f73e1 3789static int memcg_online_kmem(struct mem_cgroup *memcg)
127424c8
JW
3790{
3791 return 0;
3792}
3793static void memcg_offline_kmem(struct mem_cgroup *memcg)
3794{
3795}
3796static void memcg_free_kmem(struct mem_cgroup *memcg)
3797{
3798}
84c07d11 3799#endif /* CONFIG_MEMCG_KMEM */
127424c8 3800
bbec2e15
RG
3801static int memcg_update_kmem_max(struct mem_cgroup *memcg,
3802 unsigned long max)
d6441637 3803{
b313aeee 3804 int ret;
127424c8 3805
bbec2e15
RG
3806 mutex_lock(&memcg_max_mutex);
3807 ret = page_counter_set_max(&memcg->kmem, max);
3808 mutex_unlock(&memcg_max_mutex);
127424c8 3809 return ret;
d6441637 3810}
510fc4e1 3811
bbec2e15 3812static int memcg_update_tcp_max(struct mem_cgroup *memcg, unsigned long max)
d55f90bf
VD
3813{
3814 int ret;
3815
bbec2e15 3816 mutex_lock(&memcg_max_mutex);
d55f90bf 3817
bbec2e15 3818 ret = page_counter_set_max(&memcg->tcpmem, max);
d55f90bf
VD
3819 if (ret)
3820 goto out;
3821
0db15298 3822 if (!memcg->tcpmem_active) {
d55f90bf
VD
3823 /*
3824 * The active flag needs to be written after the static_key
3825 * update. This is what guarantees that the socket activation
2d758073
JW
3826 * function is the last one to run. See mem_cgroup_sk_alloc()
3827 * for details, and note that we don't mark any socket as
3828 * belonging to this memcg until that flag is up.
d55f90bf
VD
3829 *
3830 * We need to do this, because static_keys will span multiple
3831 * sites, but we can't control their order. If we mark a socket
3832 * as accounted, but the accounting functions are not patched in
3833 * yet, we'll lose accounting.
3834 *
2d758073 3835 * We never race with the readers in mem_cgroup_sk_alloc(),
d55f90bf
VD
3836 * because when this value change, the code to process it is not
3837 * patched in yet.
3838 */
3839 static_branch_inc(&memcg_sockets_enabled_key);
0db15298 3840 memcg->tcpmem_active = true;
d55f90bf
VD
3841 }
3842out:
bbec2e15 3843 mutex_unlock(&memcg_max_mutex);
d55f90bf
VD
3844 return ret;
3845}
d55f90bf 3846
628f4235
KH
3847/*
3848 * The user of this function is...
3849 * RES_LIMIT.
3850 */
451af504
TH
3851static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
3852 char *buf, size_t nbytes, loff_t off)
8cdea7c0 3853{
451af504 3854 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3e32cb2e 3855 unsigned long nr_pages;
628f4235
KH
3856 int ret;
3857
451af504 3858 buf = strstrip(buf);
650c5e56 3859 ret = page_counter_memparse(buf, "-1", &nr_pages);
3e32cb2e
JW
3860 if (ret)
3861 return ret;
af36f906 3862
3e32cb2e 3863 switch (MEMFILE_ATTR(of_cft(of)->private)) {
628f4235 3864 case RES_LIMIT:
4b3bde4c
BS
3865 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3866 ret = -EINVAL;
3867 break;
3868 }
3e32cb2e
JW
3869 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3870 case _MEM:
bbec2e15 3871 ret = mem_cgroup_resize_max(memcg, nr_pages, false);
8c7c6e34 3872 break;
3e32cb2e 3873 case _MEMSWAP:
bbec2e15 3874 ret = mem_cgroup_resize_max(memcg, nr_pages, true);
296c81d8 3875 break;
3e32cb2e 3876 case _KMEM:
0158115f
MH
3877 pr_warn_once("kmem.limit_in_bytes is deprecated and will be removed. "
3878 "Please report your usecase to linux-mm@kvack.org if you "
3879 "depend on this functionality.\n");
bbec2e15 3880 ret = memcg_update_kmem_max(memcg, nr_pages);
3e32cb2e 3881 break;
d55f90bf 3882 case _TCP:
bbec2e15 3883 ret = memcg_update_tcp_max(memcg, nr_pages);
d55f90bf 3884 break;
3e32cb2e 3885 }
296c81d8 3886 break;
3e32cb2e
JW
3887 case RES_SOFT_LIMIT:
3888 memcg->soft_limit = nr_pages;
3889 ret = 0;
628f4235
KH
3890 break;
3891 }
451af504 3892 return ret ?: nbytes;
8cdea7c0
BS
3893}
3894
6770c64e
TH
3895static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
3896 size_t nbytes, loff_t off)
c84872e1 3897{
6770c64e 3898 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3e32cb2e 3899 struct page_counter *counter;
c84872e1 3900
3e32cb2e
JW
3901 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3902 case _MEM:
3903 counter = &memcg->memory;
3904 break;
3905 case _MEMSWAP:
3906 counter = &memcg->memsw;
3907 break;
3908 case _KMEM:
3909 counter = &memcg->kmem;
3910 break;
d55f90bf 3911 case _TCP:
0db15298 3912 counter = &memcg->tcpmem;
d55f90bf 3913 break;
3e32cb2e
JW
3914 default:
3915 BUG();
3916 }
af36f906 3917
3e32cb2e 3918 switch (MEMFILE_ATTR(of_cft(of)->private)) {
29f2a4da 3919 case RES_MAX_USAGE:
3e32cb2e 3920 page_counter_reset_watermark(counter);
29f2a4da
PE
3921 break;
3922 case RES_FAILCNT:
3e32cb2e 3923 counter->failcnt = 0;
29f2a4da 3924 break;
3e32cb2e
JW
3925 default:
3926 BUG();
29f2a4da 3927 }
f64c3f54 3928
6770c64e 3929 return nbytes;
c84872e1
PE
3930}
3931
182446d0 3932static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
7dc74be0
DN
3933 struct cftype *cft)
3934{
182446d0 3935 return mem_cgroup_from_css(css)->move_charge_at_immigrate;
7dc74be0
DN
3936}
3937
02491447 3938#ifdef CONFIG_MMU
182446d0 3939static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
7dc74be0
DN
3940 struct cftype *cft, u64 val)
3941{
182446d0 3942 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
7dc74be0 3943
1dfab5ab 3944 if (val & ~MOVE_MASK)
7dc74be0 3945 return -EINVAL;
ee5e8472 3946
7dc74be0 3947 /*
ee5e8472
GC
3948 * No kind of locking is needed in here, because ->can_attach() will
3949 * check this value once in the beginning of the process, and then carry
3950 * on with stale data. This means that changes to this value will only
3951 * affect task migrations starting after the change.
7dc74be0 3952 */
c0ff4b85 3953 memcg->move_charge_at_immigrate = val;
7dc74be0
DN
3954 return 0;
3955}
02491447 3956#else
182446d0 3957static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
02491447
DN
3958 struct cftype *cft, u64 val)
3959{
3960 return -ENOSYS;
3961}
3962#endif
7dc74be0 3963
406eb0c9 3964#ifdef CONFIG_NUMA
113b7dfd
JW
3965
3966#define LRU_ALL_FILE (BIT(LRU_INACTIVE_FILE) | BIT(LRU_ACTIVE_FILE))
3967#define LRU_ALL_ANON (BIT(LRU_INACTIVE_ANON) | BIT(LRU_ACTIVE_ANON))
3968#define LRU_ALL ((1 << NR_LRU_LISTS) - 1)
3969
3970static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
dd8657b6 3971 int nid, unsigned int lru_mask, bool tree)
113b7dfd 3972{
867e5e1d 3973 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
113b7dfd
JW
3974 unsigned long nr = 0;
3975 enum lru_list lru;
3976
3977 VM_BUG_ON((unsigned)nid >= nr_node_ids);
3978
3979 for_each_lru(lru) {
3980 if (!(BIT(lru) & lru_mask))
3981 continue;
dd8657b6
SB
3982 if (tree)
3983 nr += lruvec_page_state(lruvec, NR_LRU_BASE + lru);
3984 else
3985 nr += lruvec_page_state_local(lruvec, NR_LRU_BASE + lru);
113b7dfd
JW
3986 }
3987 return nr;
3988}
3989
3990static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
dd8657b6
SB
3991 unsigned int lru_mask,
3992 bool tree)
113b7dfd
JW
3993{
3994 unsigned long nr = 0;
3995 enum lru_list lru;
3996
3997 for_each_lru(lru) {
3998 if (!(BIT(lru) & lru_mask))
3999 continue;
dd8657b6
SB
4000 if (tree)
4001 nr += memcg_page_state(memcg, NR_LRU_BASE + lru);
4002 else
4003 nr += memcg_page_state_local(memcg, NR_LRU_BASE + lru);
113b7dfd
JW
4004 }
4005 return nr;
4006}
4007
2da8ca82 4008static int memcg_numa_stat_show(struct seq_file *m, void *v)
406eb0c9 4009{
25485de6
GT
4010 struct numa_stat {
4011 const char *name;
4012 unsigned int lru_mask;
4013 };
4014
4015 static const struct numa_stat stats[] = {
4016 { "total", LRU_ALL },
4017 { "file", LRU_ALL_FILE },
4018 { "anon", LRU_ALL_ANON },
4019 { "unevictable", BIT(LRU_UNEVICTABLE) },
4020 };
4021 const struct numa_stat *stat;
406eb0c9 4022 int nid;
aa9694bb 4023 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
406eb0c9 4024
25485de6 4025 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
dd8657b6
SB
4026 seq_printf(m, "%s=%lu", stat->name,
4027 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
4028 false));
4029 for_each_node_state(nid, N_MEMORY)
4030 seq_printf(m, " N%d=%lu", nid,
4031 mem_cgroup_node_nr_lru_pages(memcg, nid,
4032 stat->lru_mask, false));
25485de6 4033 seq_putc(m, '\n');
406eb0c9 4034 }
406eb0c9 4035
071aee13 4036 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
dd8657b6
SB
4037
4038 seq_printf(m, "hierarchical_%s=%lu", stat->name,
4039 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
4040 true));
4041 for_each_node_state(nid, N_MEMORY)
4042 seq_printf(m, " N%d=%lu", nid,
4043 mem_cgroup_node_nr_lru_pages(memcg, nid,
4044 stat->lru_mask, true));
071aee13 4045 seq_putc(m, '\n');
406eb0c9 4046 }
406eb0c9 4047
406eb0c9
YH
4048 return 0;
4049}
4050#endif /* CONFIG_NUMA */
4051
c8713d0b 4052static const unsigned int memcg1_stats[] = {
0d1c2072 4053 NR_FILE_PAGES,
be5d0a74 4054 NR_ANON_MAPPED,
468c3982
JW
4055#ifdef CONFIG_TRANSPARENT_HUGEPAGE
4056 NR_ANON_THPS,
4057#endif
c8713d0b
JW
4058 NR_SHMEM,
4059 NR_FILE_MAPPED,
4060 NR_FILE_DIRTY,
4061 NR_WRITEBACK,
4062 MEMCG_SWAP,
4063};
4064
4065static const char *const memcg1_stat_names[] = {
4066 "cache",
4067 "rss",
468c3982 4068#ifdef CONFIG_TRANSPARENT_HUGEPAGE
c8713d0b 4069 "rss_huge",
468c3982 4070#endif
c8713d0b
JW
4071 "shmem",
4072 "mapped_file",
4073 "dirty",
4074 "writeback",
4075 "swap",
4076};
4077
df0e53d0 4078/* Universal VM events cgroup1 shows, original sort order */
8dd53fd3 4079static const unsigned int memcg1_events[] = {
df0e53d0
JW
4080 PGPGIN,
4081 PGPGOUT,
4082 PGFAULT,
4083 PGMAJFAULT,
4084};
4085
2da8ca82 4086static int memcg_stat_show(struct seq_file *m, void *v)
d2ceb9b7 4087{
aa9694bb 4088 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
3e32cb2e 4089 unsigned long memory, memsw;
af7c4b0e
JW
4090 struct mem_cgroup *mi;
4091 unsigned int i;
406eb0c9 4092
71cd3113 4093 BUILD_BUG_ON(ARRAY_SIZE(memcg1_stat_names) != ARRAY_SIZE(memcg1_stats));
70bc068c 4094
71cd3113 4095 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
468c3982
JW
4096 unsigned long nr;
4097
71cd3113 4098 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
1dd3a273 4099 continue;
468c3982
JW
4100 nr = memcg_page_state_local(memcg, memcg1_stats[i]);
4101#ifdef CONFIG_TRANSPARENT_HUGEPAGE
4102 if (memcg1_stats[i] == NR_ANON_THPS)
4103 nr *= HPAGE_PMD_NR;
4104#endif
4105 seq_printf(m, "%s %lu\n", memcg1_stat_names[i], nr * PAGE_SIZE);
1dd3a273 4106 }
7b854121 4107
df0e53d0 4108 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
ebc5d83d 4109 seq_printf(m, "%s %lu\n", vm_event_name(memcg1_events[i]),
205b20cc 4110 memcg_events_local(memcg, memcg1_events[i]));
af7c4b0e
JW
4111
4112 for (i = 0; i < NR_LRU_LISTS; i++)
ebc5d83d 4113 seq_printf(m, "%s %lu\n", lru_list_name(i),
205b20cc 4114 memcg_page_state_local(memcg, NR_LRU_BASE + i) *
21d89d15 4115 PAGE_SIZE);
af7c4b0e 4116
14067bb3 4117 /* Hierarchical information */
3e32cb2e
JW
4118 memory = memsw = PAGE_COUNTER_MAX;
4119 for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
15b42562
CD
4120 memory = min(memory, READ_ONCE(mi->memory.max));
4121 memsw = min(memsw, READ_ONCE(mi->memsw.max));
fee7b548 4122 }
3e32cb2e
JW
4123 seq_printf(m, "hierarchical_memory_limit %llu\n",
4124 (u64)memory * PAGE_SIZE);
7941d214 4125 if (do_memsw_account())
3e32cb2e
JW
4126 seq_printf(m, "hierarchical_memsw_limit %llu\n",
4127 (u64)memsw * PAGE_SIZE);
7f016ee8 4128
8de7ecc6 4129 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
71cd3113 4130 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
1dd3a273 4131 continue;
8de7ecc6 4132 seq_printf(m, "total_%s %llu\n", memcg1_stat_names[i],
dd923990
YS
4133 (u64)memcg_page_state(memcg, memcg1_stats[i]) *
4134 PAGE_SIZE);
af7c4b0e
JW
4135 }
4136
8de7ecc6 4137 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
ebc5d83d
KK
4138 seq_printf(m, "total_%s %llu\n",
4139 vm_event_name(memcg1_events[i]),
dd923990 4140 (u64)memcg_events(memcg, memcg1_events[i]));
af7c4b0e 4141
8de7ecc6 4142 for (i = 0; i < NR_LRU_LISTS; i++)
ebc5d83d 4143 seq_printf(m, "total_%s %llu\n", lru_list_name(i),
42a30035
JW
4144 (u64)memcg_page_state(memcg, NR_LRU_BASE + i) *
4145 PAGE_SIZE);
14067bb3 4146
7f016ee8 4147#ifdef CONFIG_DEBUG_VM
7f016ee8 4148 {
ef8f2327
MG
4149 pg_data_t *pgdat;
4150 struct mem_cgroup_per_node *mz;
1431d4d1
JW
4151 unsigned long anon_cost = 0;
4152 unsigned long file_cost = 0;
7f016ee8 4153
ef8f2327
MG
4154 for_each_online_pgdat(pgdat) {
4155 mz = mem_cgroup_nodeinfo(memcg, pgdat->node_id);
7f016ee8 4156
1431d4d1
JW
4157 anon_cost += mz->lruvec.anon_cost;
4158 file_cost += mz->lruvec.file_cost;
ef8f2327 4159 }
1431d4d1
JW
4160 seq_printf(m, "anon_cost %lu\n", anon_cost);
4161 seq_printf(m, "file_cost %lu\n", file_cost);
7f016ee8
KM
4162 }
4163#endif
4164
d2ceb9b7
KH
4165 return 0;
4166}
4167
182446d0
TH
4168static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
4169 struct cftype *cft)
a7885eb8 4170{
182446d0 4171 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
a7885eb8 4172
1f4c025b 4173 return mem_cgroup_swappiness(memcg);
a7885eb8
KM
4174}
4175
182446d0
TH
4176static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
4177 struct cftype *cft, u64 val)
a7885eb8 4178{
182446d0 4179 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
a7885eb8 4180
3dae7fec 4181 if (val > 100)
a7885eb8
KM
4182 return -EINVAL;
4183
14208b0e 4184 if (css->parent)
3dae7fec
JW
4185 memcg->swappiness = val;
4186 else
4187 vm_swappiness = val;
068b38c1 4188
a7885eb8
KM
4189 return 0;
4190}
4191
2e72b634
KS
4192static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4193{
4194 struct mem_cgroup_threshold_ary *t;
3e32cb2e 4195 unsigned long usage;
2e72b634
KS
4196 int i;
4197
4198 rcu_read_lock();
4199 if (!swap)
2c488db2 4200 t = rcu_dereference(memcg->thresholds.primary);
2e72b634 4201 else
2c488db2 4202 t = rcu_dereference(memcg->memsw_thresholds.primary);
2e72b634
KS
4203
4204 if (!t)
4205 goto unlock;
4206
ce00a967 4207 usage = mem_cgroup_usage(memcg, swap);
2e72b634
KS
4208
4209 /*
748dad36 4210 * current_threshold points to threshold just below or equal to usage.
2e72b634
KS
4211 * If it's not true, a threshold was crossed after last
4212 * call of __mem_cgroup_threshold().
4213 */
5407a562 4214 i = t->current_threshold;
2e72b634
KS
4215
4216 /*
4217 * Iterate backward over array of thresholds starting from
4218 * current_threshold and check if a threshold is crossed.
4219 * If none of thresholds below usage is crossed, we read
4220 * only one element of the array here.
4221 */
4222 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4223 eventfd_signal(t->entries[i].eventfd, 1);
4224
4225 /* i = current_threshold + 1 */
4226 i++;
4227
4228 /*
4229 * Iterate forward over array of thresholds starting from
4230 * current_threshold+1 and check if a threshold is crossed.
4231 * If none of thresholds above usage is crossed, we read
4232 * only one element of the array here.
4233 */
4234 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4235 eventfd_signal(t->entries[i].eventfd, 1);
4236
4237 /* Update current_threshold */
5407a562 4238 t->current_threshold = i - 1;
2e72b634
KS
4239unlock:
4240 rcu_read_unlock();
4241}
4242
4243static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4244{
ad4ca5f4
KS
4245 while (memcg) {
4246 __mem_cgroup_threshold(memcg, false);
7941d214 4247 if (do_memsw_account())
ad4ca5f4
KS
4248 __mem_cgroup_threshold(memcg, true);
4249
4250 memcg = parent_mem_cgroup(memcg);
4251 }
2e72b634
KS
4252}
4253
4254static int compare_thresholds(const void *a, const void *b)
4255{
4256 const struct mem_cgroup_threshold *_a = a;
4257 const struct mem_cgroup_threshold *_b = b;
4258
2bff24a3
GT
4259 if (_a->threshold > _b->threshold)
4260 return 1;
4261
4262 if (_a->threshold < _b->threshold)
4263 return -1;
4264
4265 return 0;
2e72b634
KS
4266}
4267
c0ff4b85 4268static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
9490ff27
KH
4269{
4270 struct mem_cgroup_eventfd_list *ev;
4271
2bcf2e92
MH
4272 spin_lock(&memcg_oom_lock);
4273
c0ff4b85 4274 list_for_each_entry(ev, &memcg->oom_notify, list)
9490ff27 4275 eventfd_signal(ev->eventfd, 1);
2bcf2e92
MH
4276
4277 spin_unlock(&memcg_oom_lock);
9490ff27
KH
4278 return 0;
4279}
4280
c0ff4b85 4281static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
9490ff27 4282{
7d74b06f
KH
4283 struct mem_cgroup *iter;
4284
c0ff4b85 4285 for_each_mem_cgroup_tree(iter, memcg)
7d74b06f 4286 mem_cgroup_oom_notify_cb(iter);
9490ff27
KH
4287}
4288
59b6f873 4289static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
347c4a87 4290 struct eventfd_ctx *eventfd, const char *args, enum res_type type)
2e72b634 4291{
2c488db2
KS
4292 struct mem_cgroup_thresholds *thresholds;
4293 struct mem_cgroup_threshold_ary *new;
3e32cb2e
JW
4294 unsigned long threshold;
4295 unsigned long usage;
2c488db2 4296 int i, size, ret;
2e72b634 4297
650c5e56 4298 ret = page_counter_memparse(args, "-1", &threshold);
2e72b634
KS
4299 if (ret)
4300 return ret;
4301
4302 mutex_lock(&memcg->thresholds_lock);
2c488db2 4303
05b84301 4304 if (type == _MEM) {
2c488db2 4305 thresholds = &memcg->thresholds;
ce00a967 4306 usage = mem_cgroup_usage(memcg, false);
05b84301 4307 } else if (type == _MEMSWAP) {
2c488db2 4308 thresholds = &memcg->memsw_thresholds;
ce00a967 4309 usage = mem_cgroup_usage(memcg, true);
05b84301 4310 } else
2e72b634
KS
4311 BUG();
4312
2e72b634 4313 /* Check if a threshold crossed before adding a new one */
2c488db2 4314 if (thresholds->primary)
2e72b634
KS
4315 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4316
2c488db2 4317 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
2e72b634
KS
4318
4319 /* Allocate memory for new array of thresholds */
67b8046f 4320 new = kmalloc(struct_size(new, entries, size), GFP_KERNEL);
2c488db2 4321 if (!new) {
2e72b634
KS
4322 ret = -ENOMEM;
4323 goto unlock;
4324 }
2c488db2 4325 new->size = size;
2e72b634
KS
4326
4327 /* Copy thresholds (if any) to new array */
2c488db2
KS
4328 if (thresholds->primary) {
4329 memcpy(new->entries, thresholds->primary->entries, (size - 1) *
2e72b634 4330 sizeof(struct mem_cgroup_threshold));
2c488db2
KS
4331 }
4332
2e72b634 4333 /* Add new threshold */
2c488db2
KS
4334 new->entries[size - 1].eventfd = eventfd;
4335 new->entries[size - 1].threshold = threshold;
2e72b634
KS
4336
4337 /* Sort thresholds. Registering of new threshold isn't time-critical */
2c488db2 4338 sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
2e72b634
KS
4339 compare_thresholds, NULL);
4340
4341 /* Find current threshold */
2c488db2 4342 new->current_threshold = -1;
2e72b634 4343 for (i = 0; i < size; i++) {
748dad36 4344 if (new->entries[i].threshold <= usage) {
2e72b634 4345 /*
2c488db2
KS
4346 * new->current_threshold will not be used until
4347 * rcu_assign_pointer(), so it's safe to increment
2e72b634
KS
4348 * it here.
4349 */
2c488db2 4350 ++new->current_threshold;
748dad36
SZ
4351 } else
4352 break;
2e72b634
KS
4353 }
4354
2c488db2
KS
4355 /* Free old spare buffer and save old primary buffer as spare */
4356 kfree(thresholds->spare);
4357 thresholds->spare = thresholds->primary;
4358
4359 rcu_assign_pointer(thresholds->primary, new);
2e72b634 4360
907860ed 4361 /* To be sure that nobody uses thresholds */
2e72b634
KS
4362 synchronize_rcu();
4363
2e72b634
KS
4364unlock:
4365 mutex_unlock(&memcg->thresholds_lock);
4366
4367 return ret;
4368}
4369
59b6f873 4370static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
347c4a87
TH
4371 struct eventfd_ctx *eventfd, const char *args)
4372{
59b6f873 4373 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
347c4a87
TH
4374}
4375
59b6f873 4376static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
347c4a87
TH
4377 struct eventfd_ctx *eventfd, const char *args)
4378{
59b6f873 4379 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
347c4a87
TH
4380}
4381
59b6f873 4382static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
347c4a87 4383 struct eventfd_ctx *eventfd, enum res_type type)
2e72b634 4384{
2c488db2
KS
4385 struct mem_cgroup_thresholds *thresholds;
4386 struct mem_cgroup_threshold_ary *new;
3e32cb2e 4387 unsigned long usage;
7d36665a 4388 int i, j, size, entries;
2e72b634
KS
4389
4390 mutex_lock(&memcg->thresholds_lock);
05b84301
JW
4391
4392 if (type == _MEM) {
2c488db2 4393 thresholds = &memcg->thresholds;
ce00a967 4394 usage = mem_cgroup_usage(memcg, false);
05b84301 4395 } else if (type == _MEMSWAP) {
2c488db2 4396 thresholds = &memcg->memsw_thresholds;
ce00a967 4397 usage = mem_cgroup_usage(memcg, true);
05b84301 4398 } else
2e72b634
KS
4399 BUG();
4400
371528ca
AV
4401 if (!thresholds->primary)
4402 goto unlock;
4403
2e72b634
KS
4404 /* Check if a threshold crossed before removing */
4405 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4406
4407 /* Calculate new number of threshold */
7d36665a 4408 size = entries = 0;
2c488db2
KS
4409 for (i = 0; i < thresholds->primary->size; i++) {
4410 if (thresholds->primary->entries[i].eventfd != eventfd)
2e72b634 4411 size++;
7d36665a
CX
4412 else
4413 entries++;
2e72b634
KS
4414 }
4415
2c488db2 4416 new = thresholds->spare;
907860ed 4417
7d36665a
CX
4418 /* If no items related to eventfd have been cleared, nothing to do */
4419 if (!entries)
4420 goto unlock;
4421
2e72b634
KS
4422 /* Set thresholds array to NULL if we don't have thresholds */
4423 if (!size) {
2c488db2
KS
4424 kfree(new);
4425 new = NULL;
907860ed 4426 goto swap_buffers;
2e72b634
KS
4427 }
4428
2c488db2 4429 new->size = size;
2e72b634
KS
4430
4431 /* Copy thresholds and find current threshold */
2c488db2
KS
4432 new->current_threshold = -1;
4433 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4434 if (thresholds->primary->entries[i].eventfd == eventfd)
2e72b634
KS
4435 continue;
4436
2c488db2 4437 new->entries[j] = thresholds->primary->entries[i];
748dad36 4438 if (new->entries[j].threshold <= usage) {
2e72b634 4439 /*
2c488db2 4440 * new->current_threshold will not be used
2e72b634
KS
4441 * until rcu_assign_pointer(), so it's safe to increment
4442 * it here.
4443 */
2c488db2 4444 ++new->current_threshold;
2e72b634
KS
4445 }
4446 j++;
4447 }
4448
907860ed 4449swap_buffers:
2c488db2
KS
4450 /* Swap primary and spare array */
4451 thresholds->spare = thresholds->primary;
8c757763 4452
2c488db2 4453 rcu_assign_pointer(thresholds->primary, new);
2e72b634 4454
907860ed 4455 /* To be sure that nobody uses thresholds */
2e72b634 4456 synchronize_rcu();
6611d8d7
MC
4457
4458 /* If all events are unregistered, free the spare array */
4459 if (!new) {
4460 kfree(thresholds->spare);
4461 thresholds->spare = NULL;
4462 }
371528ca 4463unlock:
2e72b634 4464 mutex_unlock(&memcg->thresholds_lock);
2e72b634 4465}
c1e862c1 4466
59b6f873 4467static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
347c4a87
TH
4468 struct eventfd_ctx *eventfd)
4469{
59b6f873 4470 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
347c4a87
TH
4471}
4472
59b6f873 4473static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
347c4a87
TH
4474 struct eventfd_ctx *eventfd)
4475{
59b6f873 4476 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
347c4a87
TH
4477}
4478
59b6f873 4479static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
347c4a87 4480 struct eventfd_ctx *eventfd, const char *args)
9490ff27 4481{
9490ff27 4482 struct mem_cgroup_eventfd_list *event;
9490ff27 4483
9490ff27
KH
4484 event = kmalloc(sizeof(*event), GFP_KERNEL);
4485 if (!event)
4486 return -ENOMEM;
4487
1af8efe9 4488 spin_lock(&memcg_oom_lock);
9490ff27
KH
4489
4490 event->eventfd = eventfd;
4491 list_add(&event->list, &memcg->oom_notify);
4492
4493 /* already in OOM ? */
c2b42d3c 4494 if (memcg->under_oom)
9490ff27 4495 eventfd_signal(eventfd, 1);
1af8efe9 4496 spin_unlock(&memcg_oom_lock);
9490ff27
KH
4497
4498 return 0;
4499}
4500
59b6f873 4501static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
347c4a87 4502 struct eventfd_ctx *eventfd)
9490ff27 4503{
9490ff27 4504 struct mem_cgroup_eventfd_list *ev, *tmp;
9490ff27 4505
1af8efe9 4506 spin_lock(&memcg_oom_lock);
9490ff27 4507
c0ff4b85 4508 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
9490ff27
KH
4509 if (ev->eventfd == eventfd) {
4510 list_del(&ev->list);
4511 kfree(ev);
4512 }
4513 }
4514
1af8efe9 4515 spin_unlock(&memcg_oom_lock);
9490ff27
KH
4516}
4517
2da8ca82 4518static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
3c11ecf4 4519{
aa9694bb 4520 struct mem_cgroup *memcg = mem_cgroup_from_seq(sf);
3c11ecf4 4521
791badbd 4522 seq_printf(sf, "oom_kill_disable %d\n", memcg->oom_kill_disable);
c2b42d3c 4523 seq_printf(sf, "under_oom %d\n", (bool)memcg->under_oom);
fe6bdfc8
RG
4524 seq_printf(sf, "oom_kill %lu\n",
4525 atomic_long_read(&memcg->memory_events[MEMCG_OOM_KILL]));
3c11ecf4
KH
4526 return 0;
4527}
4528
182446d0 4529static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
3c11ecf4
KH
4530 struct cftype *cft, u64 val)
4531{
182446d0 4532 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3c11ecf4
KH
4533
4534 /* cannot set to root cgroup and only 0 and 1 are allowed */
14208b0e 4535 if (!css->parent || !((val == 0) || (val == 1)))
3c11ecf4
KH
4536 return -EINVAL;
4537
c0ff4b85 4538 memcg->oom_kill_disable = val;
4d845ebf 4539 if (!val)
c0ff4b85 4540 memcg_oom_recover(memcg);
3dae7fec 4541
3c11ecf4
KH
4542 return 0;
4543}
4544
52ebea74
TH
4545#ifdef CONFIG_CGROUP_WRITEBACK
4546
3a8e9ac8
TH
4547#include <trace/events/writeback.h>
4548
841710aa
TH
4549static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4550{
4551 return wb_domain_init(&memcg->cgwb_domain, gfp);
4552}
4553
4554static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4555{
4556 wb_domain_exit(&memcg->cgwb_domain);
4557}
4558
2529bb3a
TH
4559static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4560{
4561 wb_domain_size_changed(&memcg->cgwb_domain);
4562}
4563
841710aa
TH
4564struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb)
4565{
4566 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4567
4568 if (!memcg->css.parent)
4569 return NULL;
4570
4571 return &memcg->cgwb_domain;
4572}
4573
0b3d6e6f
GT
4574/*
4575 * idx can be of type enum memcg_stat_item or node_stat_item.
4576 * Keep in sync with memcg_exact_page().
4577 */
4578static unsigned long memcg_exact_page_state(struct mem_cgroup *memcg, int idx)
4579{
871789d4 4580 long x = atomic_long_read(&memcg->vmstats[idx]);
0b3d6e6f
GT
4581 int cpu;
4582
4583 for_each_online_cpu(cpu)
871789d4 4584 x += per_cpu_ptr(memcg->vmstats_percpu, cpu)->stat[idx];
0b3d6e6f
GT
4585 if (x < 0)
4586 x = 0;
4587 return x;
4588}
4589
c2aa723a
TH
4590/**
4591 * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
4592 * @wb: bdi_writeback in question
c5edf9cd
TH
4593 * @pfilepages: out parameter for number of file pages
4594 * @pheadroom: out parameter for number of allocatable pages according to memcg
c2aa723a
TH
4595 * @pdirty: out parameter for number of dirty pages
4596 * @pwriteback: out parameter for number of pages under writeback
4597 *
c5edf9cd
TH
4598 * Determine the numbers of file, headroom, dirty, and writeback pages in
4599 * @wb's memcg. File, dirty and writeback are self-explanatory. Headroom
4600 * is a bit more involved.
c2aa723a 4601 *
c5edf9cd
TH
4602 * A memcg's headroom is "min(max, high) - used". In the hierarchy, the
4603 * headroom is calculated as the lowest headroom of itself and the
4604 * ancestors. Note that this doesn't consider the actual amount of
4605 * available memory in the system. The caller should further cap
4606 * *@pheadroom accordingly.
c2aa723a 4607 */
c5edf9cd
TH
4608void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages,
4609 unsigned long *pheadroom, unsigned long *pdirty,
4610 unsigned long *pwriteback)
c2aa723a
TH
4611{
4612 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4613 struct mem_cgroup *parent;
c2aa723a 4614
0b3d6e6f 4615 *pdirty = memcg_exact_page_state(memcg, NR_FILE_DIRTY);
c2aa723a 4616
0b3d6e6f 4617 *pwriteback = memcg_exact_page_state(memcg, NR_WRITEBACK);
21d89d15
JW
4618 *pfilepages = memcg_exact_page_state(memcg, NR_INACTIVE_FILE) +
4619 memcg_exact_page_state(memcg, NR_ACTIVE_FILE);
c5edf9cd 4620 *pheadroom = PAGE_COUNTER_MAX;
c2aa723a 4621
c2aa723a 4622 while ((parent = parent_mem_cgroup(memcg))) {
15b42562 4623 unsigned long ceiling = min(READ_ONCE(memcg->memory.max),
d1663a90 4624 READ_ONCE(memcg->memory.high));
c2aa723a
TH
4625 unsigned long used = page_counter_read(&memcg->memory);
4626
c5edf9cd 4627 *pheadroom = min(*pheadroom, ceiling - min(ceiling, used));
c2aa723a
TH
4628 memcg = parent;
4629 }
c2aa723a
TH
4630}
4631
97b27821
TH
4632/*
4633 * Foreign dirty flushing
4634 *
4635 * There's an inherent mismatch between memcg and writeback. The former
4636 * trackes ownership per-page while the latter per-inode. This was a
4637 * deliberate design decision because honoring per-page ownership in the
4638 * writeback path is complicated, may lead to higher CPU and IO overheads
4639 * and deemed unnecessary given that write-sharing an inode across
4640 * different cgroups isn't a common use-case.
4641 *
4642 * Combined with inode majority-writer ownership switching, this works well
4643 * enough in most cases but there are some pathological cases. For
4644 * example, let's say there are two cgroups A and B which keep writing to
4645 * different but confined parts of the same inode. B owns the inode and
4646 * A's memory is limited far below B's. A's dirty ratio can rise enough to
4647 * trigger balance_dirty_pages() sleeps but B's can be low enough to avoid
4648 * triggering background writeback. A will be slowed down without a way to
4649 * make writeback of the dirty pages happen.
4650 *
4651 * Conditions like the above can lead to a cgroup getting repatedly and
4652 * severely throttled after making some progress after each
4653 * dirty_expire_interval while the underyling IO device is almost
4654 * completely idle.
4655 *
4656 * Solving this problem completely requires matching the ownership tracking
4657 * granularities between memcg and writeback in either direction. However,
4658 * the more egregious behaviors can be avoided by simply remembering the
4659 * most recent foreign dirtying events and initiating remote flushes on
4660 * them when local writeback isn't enough to keep the memory clean enough.
4661 *
4662 * The following two functions implement such mechanism. When a foreign
4663 * page - a page whose memcg and writeback ownerships don't match - is
4664 * dirtied, mem_cgroup_track_foreign_dirty() records the inode owning
4665 * bdi_writeback on the page owning memcg. When balance_dirty_pages()
4666 * decides that the memcg needs to sleep due to high dirty ratio, it calls
4667 * mem_cgroup_flush_foreign() which queues writeback on the recorded
4668 * foreign bdi_writebacks which haven't expired. Both the numbers of
4669 * recorded bdi_writebacks and concurrent in-flight foreign writebacks are
4670 * limited to MEMCG_CGWB_FRN_CNT.
4671 *
4672 * The mechanism only remembers IDs and doesn't hold any object references.
4673 * As being wrong occasionally doesn't matter, updates and accesses to the
4674 * records are lockless and racy.
4675 */
4676void mem_cgroup_track_foreign_dirty_slowpath(struct page *page,
4677 struct bdi_writeback *wb)
4678{
4679 struct mem_cgroup *memcg = page->mem_cgroup;
4680 struct memcg_cgwb_frn *frn;
4681 u64 now = get_jiffies_64();
4682 u64 oldest_at = now;
4683 int oldest = -1;
4684 int i;
4685
3a8e9ac8
TH
4686 trace_track_foreign_dirty(page, wb);
4687
97b27821
TH
4688 /*
4689 * Pick the slot to use. If there is already a slot for @wb, keep
4690 * using it. If not replace the oldest one which isn't being
4691 * written out.
4692 */
4693 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4694 frn = &memcg->cgwb_frn[i];
4695 if (frn->bdi_id == wb->bdi->id &&
4696 frn->memcg_id == wb->memcg_css->id)
4697 break;
4698 if (time_before64(frn->at, oldest_at) &&
4699 atomic_read(&frn->done.cnt) == 1) {
4700 oldest = i;
4701 oldest_at = frn->at;
4702 }
4703 }
4704
4705 if (i < MEMCG_CGWB_FRN_CNT) {
4706 /*
4707 * Re-using an existing one. Update timestamp lazily to
4708 * avoid making the cacheline hot. We want them to be
4709 * reasonably up-to-date and significantly shorter than
4710 * dirty_expire_interval as that's what expires the record.
4711 * Use the shorter of 1s and dirty_expire_interval / 8.
4712 */
4713 unsigned long update_intv =
4714 min_t(unsigned long, HZ,
4715 msecs_to_jiffies(dirty_expire_interval * 10) / 8);
4716
4717 if (time_before64(frn->at, now - update_intv))
4718 frn->at = now;
4719 } else if (oldest >= 0) {
4720 /* replace the oldest free one */
4721 frn = &memcg->cgwb_frn[oldest];
4722 frn->bdi_id = wb->bdi->id;
4723 frn->memcg_id = wb->memcg_css->id;
4724 frn->at = now;
4725 }
4726}
4727
4728/* issue foreign writeback flushes for recorded foreign dirtying events */
4729void mem_cgroup_flush_foreign(struct bdi_writeback *wb)
4730{
4731 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4732 unsigned long intv = msecs_to_jiffies(dirty_expire_interval * 10);
4733 u64 now = jiffies_64;
4734 int i;
4735
4736 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4737 struct memcg_cgwb_frn *frn = &memcg->cgwb_frn[i];
4738
4739 /*
4740 * If the record is older than dirty_expire_interval,
4741 * writeback on it has already started. No need to kick it
4742 * off again. Also, don't start a new one if there's
4743 * already one in flight.
4744 */
4745 if (time_after64(frn->at, now - intv) &&
4746 atomic_read(&frn->done.cnt) == 1) {
4747 frn->at = 0;
3a8e9ac8 4748 trace_flush_foreign(wb, frn->bdi_id, frn->memcg_id);
97b27821
TH
4749 cgroup_writeback_by_id(frn->bdi_id, frn->memcg_id, 0,
4750 WB_REASON_FOREIGN_FLUSH,
4751 &frn->done);
4752 }
4753 }
4754}
4755
841710aa
TH
4756#else /* CONFIG_CGROUP_WRITEBACK */
4757
4758static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4759{
4760 return 0;
4761}
4762
4763static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4764{
4765}
4766
2529bb3a
TH
4767static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4768{
4769}
4770
52ebea74
TH
4771#endif /* CONFIG_CGROUP_WRITEBACK */
4772
3bc942f3
TH
4773/*
4774 * DO NOT USE IN NEW FILES.
4775 *
4776 * "cgroup.event_control" implementation.
4777 *
4778 * This is way over-engineered. It tries to support fully configurable
4779 * events for each user. Such level of flexibility is completely
4780 * unnecessary especially in the light of the planned unified hierarchy.
4781 *
4782 * Please deprecate this and replace with something simpler if at all
4783 * possible.
4784 */
4785
79bd9814
TH
4786/*
4787 * Unregister event and free resources.
4788 *
4789 * Gets called from workqueue.
4790 */
3bc942f3 4791static void memcg_event_remove(struct work_struct *work)
79bd9814 4792{
3bc942f3
TH
4793 struct mem_cgroup_event *event =
4794 container_of(work, struct mem_cgroup_event, remove);
59b6f873 4795 struct mem_cgroup *memcg = event->memcg;
79bd9814
TH
4796
4797 remove_wait_queue(event->wqh, &event->wait);
4798
59b6f873 4799 event->unregister_event(memcg, event->eventfd);
79bd9814
TH
4800
4801 /* Notify userspace the event is going away. */
4802 eventfd_signal(event->eventfd, 1);
4803
4804 eventfd_ctx_put(event->eventfd);
4805 kfree(event);
59b6f873 4806 css_put(&memcg->css);
79bd9814
TH
4807}
4808
4809/*
a9a08845 4810 * Gets called on EPOLLHUP on eventfd when user closes it.
79bd9814
TH
4811 *
4812 * Called with wqh->lock held and interrupts disabled.
4813 */
ac6424b9 4814static int memcg_event_wake(wait_queue_entry_t *wait, unsigned mode,
3bc942f3 4815 int sync, void *key)
79bd9814 4816{
3bc942f3
TH
4817 struct mem_cgroup_event *event =
4818 container_of(wait, struct mem_cgroup_event, wait);
59b6f873 4819 struct mem_cgroup *memcg = event->memcg;
3ad6f93e 4820 __poll_t flags = key_to_poll(key);
79bd9814 4821
a9a08845 4822 if (flags & EPOLLHUP) {
79bd9814
TH
4823 /*
4824 * If the event has been detached at cgroup removal, we
4825 * can simply return knowing the other side will cleanup
4826 * for us.
4827 *
4828 * We can't race against event freeing since the other
4829 * side will require wqh->lock via remove_wait_queue(),
4830 * which we hold.
4831 */
fba94807 4832 spin_lock(&memcg->event_list_lock);
79bd9814
TH
4833 if (!list_empty(&event->list)) {
4834 list_del_init(&event->list);
4835 /*
4836 * We are in atomic context, but cgroup_event_remove()
4837 * may sleep, so we have to call it in workqueue.
4838 */
4839 schedule_work(&event->remove);
4840 }
fba94807 4841 spin_unlock(&memcg->event_list_lock);
79bd9814
TH
4842 }
4843
4844 return 0;
4845}
4846
3bc942f3 4847static void memcg_event_ptable_queue_proc(struct file *file,
79bd9814
TH
4848 wait_queue_head_t *wqh, poll_table *pt)
4849{
3bc942f3
TH
4850 struct mem_cgroup_event *event =
4851 container_of(pt, struct mem_cgroup_event, pt);
79bd9814
TH
4852
4853 event->wqh = wqh;
4854 add_wait_queue(wqh, &event->wait);
4855}
4856
4857/*
3bc942f3
TH
4858 * DO NOT USE IN NEW FILES.
4859 *
79bd9814
TH
4860 * Parse input and register new cgroup event handler.
4861 *
4862 * Input must be in format '<event_fd> <control_fd> <args>'.
4863 * Interpretation of args is defined by control file implementation.
4864 */
451af504
TH
4865static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
4866 char *buf, size_t nbytes, loff_t off)
79bd9814 4867{
451af504 4868 struct cgroup_subsys_state *css = of_css(of);
fba94807 4869 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3bc942f3 4870 struct mem_cgroup_event *event;
79bd9814
TH
4871 struct cgroup_subsys_state *cfile_css;
4872 unsigned int efd, cfd;
4873 struct fd efile;
4874 struct fd cfile;
fba94807 4875 const char *name;
79bd9814
TH
4876 char *endp;
4877 int ret;
4878
451af504
TH
4879 buf = strstrip(buf);
4880
4881 efd = simple_strtoul(buf, &endp, 10);
79bd9814
TH
4882 if (*endp != ' ')
4883 return -EINVAL;
451af504 4884 buf = endp + 1;
79bd9814 4885
451af504 4886 cfd = simple_strtoul(buf, &endp, 10);
79bd9814
TH
4887 if ((*endp != ' ') && (*endp != '\0'))
4888 return -EINVAL;
451af504 4889 buf = endp + 1;
79bd9814
TH
4890
4891 event = kzalloc(sizeof(*event), GFP_KERNEL);
4892 if (!event)
4893 return -ENOMEM;
4894
59b6f873 4895 event->memcg = memcg;
79bd9814 4896 INIT_LIST_HEAD(&event->list);
3bc942f3
TH
4897 init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
4898 init_waitqueue_func_entry(&event->wait, memcg_event_wake);
4899 INIT_WORK(&event->remove, memcg_event_remove);
79bd9814
TH
4900
4901 efile = fdget(efd);
4902 if (!efile.file) {
4903 ret = -EBADF;
4904 goto out_kfree;
4905 }
4906
4907 event->eventfd = eventfd_ctx_fileget(efile.file);
4908 if (IS_ERR(event->eventfd)) {
4909 ret = PTR_ERR(event->eventfd);
4910 goto out_put_efile;
4911 }
4912
4913 cfile = fdget(cfd);
4914 if (!cfile.file) {
4915 ret = -EBADF;
4916 goto out_put_eventfd;
4917 }
4918
4919 /* the process need read permission on control file */
4920 /* AV: shouldn't we check that it's been opened for read instead? */
4921 ret = inode_permission(file_inode(cfile.file), MAY_READ);
4922 if (ret < 0)
4923 goto out_put_cfile;
4924
fba94807
TH
4925 /*
4926 * Determine the event callbacks and set them in @event. This used
4927 * to be done via struct cftype but cgroup core no longer knows
4928 * about these events. The following is crude but the whole thing
4929 * is for compatibility anyway.
3bc942f3
TH
4930 *
4931 * DO NOT ADD NEW FILES.
fba94807 4932 */
b583043e 4933 name = cfile.file->f_path.dentry->d_name.name;
fba94807
TH
4934
4935 if (!strcmp(name, "memory.usage_in_bytes")) {
4936 event->register_event = mem_cgroup_usage_register_event;
4937 event->unregister_event = mem_cgroup_usage_unregister_event;
4938 } else if (!strcmp(name, "memory.oom_control")) {
4939 event->register_event = mem_cgroup_oom_register_event;
4940 event->unregister_event = mem_cgroup_oom_unregister_event;
4941 } else if (!strcmp(name, "memory.pressure_level")) {
4942 event->register_event = vmpressure_register_event;
4943 event->unregister_event = vmpressure_unregister_event;
4944 } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
347c4a87
TH
4945 event->register_event = memsw_cgroup_usage_register_event;
4946 event->unregister_event = memsw_cgroup_usage_unregister_event;
fba94807
TH
4947 } else {
4948 ret = -EINVAL;
4949 goto out_put_cfile;
4950 }
4951
79bd9814 4952 /*
b5557c4c
TH
4953 * Verify @cfile should belong to @css. Also, remaining events are
4954 * automatically removed on cgroup destruction but the removal is
4955 * asynchronous, so take an extra ref on @css.
79bd9814 4956 */
b583043e 4957 cfile_css = css_tryget_online_from_dir(cfile.file->f_path.dentry->d_parent,
ec903c0c 4958 &memory_cgrp_subsys);
79bd9814 4959 ret = -EINVAL;
5a17f543 4960 if (IS_ERR(cfile_css))
79bd9814 4961 goto out_put_cfile;
5a17f543
TH
4962 if (cfile_css != css) {
4963 css_put(cfile_css);
79bd9814 4964 goto out_put_cfile;
5a17f543 4965 }
79bd9814 4966
451af504 4967 ret = event->register_event(memcg, event->eventfd, buf);
79bd9814
TH
4968 if (ret)
4969 goto out_put_css;
4970
9965ed17 4971 vfs_poll(efile.file, &event->pt);
79bd9814 4972
fba94807
TH
4973 spin_lock(&memcg->event_list_lock);
4974 list_add(&event->list, &memcg->event_list);
4975 spin_unlock(&memcg->event_list_lock);
79bd9814
TH
4976
4977 fdput(cfile);
4978 fdput(efile);
4979
451af504 4980 return nbytes;
79bd9814
TH
4981
4982out_put_css:
b5557c4c 4983 css_put(css);
79bd9814
TH
4984out_put_cfile:
4985 fdput(cfile);
4986out_put_eventfd:
4987 eventfd_ctx_put(event->eventfd);
4988out_put_efile:
4989 fdput(efile);
4990out_kfree:
4991 kfree(event);
4992
4993 return ret;
4994}
4995
241994ed 4996static struct cftype mem_cgroup_legacy_files[] = {
8cdea7c0 4997 {
0eea1030 4998 .name = "usage_in_bytes",
8c7c6e34 4999 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
791badbd 5000 .read_u64 = mem_cgroup_read_u64,
8cdea7c0 5001 },
c84872e1
PE
5002 {
5003 .name = "max_usage_in_bytes",
8c7c6e34 5004 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
6770c64e 5005 .write = mem_cgroup_reset,
791badbd 5006 .read_u64 = mem_cgroup_read_u64,
c84872e1 5007 },
8cdea7c0 5008 {
0eea1030 5009 .name = "limit_in_bytes",
8c7c6e34 5010 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
451af504 5011 .write = mem_cgroup_write,
791badbd 5012 .read_u64 = mem_cgroup_read_u64,
8cdea7c0 5013 },
296c81d8
BS
5014 {
5015 .name = "soft_limit_in_bytes",
5016 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
451af504 5017 .write = mem_cgroup_write,
791badbd 5018 .read_u64 = mem_cgroup_read_u64,
296c81d8 5019 },
8cdea7c0
BS
5020 {
5021 .name = "failcnt",
8c7c6e34 5022 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
6770c64e 5023 .write = mem_cgroup_reset,
791badbd 5024 .read_u64 = mem_cgroup_read_u64,
8cdea7c0 5025 },
d2ceb9b7
KH
5026 {
5027 .name = "stat",
2da8ca82 5028 .seq_show = memcg_stat_show,
d2ceb9b7 5029 },
c1e862c1
KH
5030 {
5031 .name = "force_empty",
6770c64e 5032 .write = mem_cgroup_force_empty_write,
c1e862c1 5033 },
18f59ea7
BS
5034 {
5035 .name = "use_hierarchy",
5036 .write_u64 = mem_cgroup_hierarchy_write,
5037 .read_u64 = mem_cgroup_hierarchy_read,
5038 },
79bd9814 5039 {
3bc942f3 5040 .name = "cgroup.event_control", /* XXX: for compat */
451af504 5041 .write = memcg_write_event_control,
7dbdb199 5042 .flags = CFTYPE_NO_PREFIX | CFTYPE_WORLD_WRITABLE,
79bd9814 5043 },
a7885eb8
KM
5044 {
5045 .name = "swappiness",
5046 .read_u64 = mem_cgroup_swappiness_read,
5047 .write_u64 = mem_cgroup_swappiness_write,
5048 },
7dc74be0
DN
5049 {
5050 .name = "move_charge_at_immigrate",
5051 .read_u64 = mem_cgroup_move_charge_read,
5052 .write_u64 = mem_cgroup_move_charge_write,
5053 },
9490ff27
KH
5054 {
5055 .name = "oom_control",
2da8ca82 5056 .seq_show = mem_cgroup_oom_control_read,
3c11ecf4 5057 .write_u64 = mem_cgroup_oom_control_write,
9490ff27
KH
5058 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
5059 },
70ddf637
AV
5060 {
5061 .name = "pressure_level",
70ddf637 5062 },
406eb0c9
YH
5063#ifdef CONFIG_NUMA
5064 {
5065 .name = "numa_stat",
2da8ca82 5066 .seq_show = memcg_numa_stat_show,
406eb0c9
YH
5067 },
5068#endif
510fc4e1
GC
5069 {
5070 .name = "kmem.limit_in_bytes",
5071 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
451af504 5072 .write = mem_cgroup_write,
791badbd 5073 .read_u64 = mem_cgroup_read_u64,
510fc4e1
GC
5074 },
5075 {
5076 .name = "kmem.usage_in_bytes",
5077 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
791badbd 5078 .read_u64 = mem_cgroup_read_u64,
510fc4e1
GC
5079 },
5080 {
5081 .name = "kmem.failcnt",
5082 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
6770c64e 5083 .write = mem_cgroup_reset,
791badbd 5084 .read_u64 = mem_cgroup_read_u64,
510fc4e1
GC
5085 },
5086 {
5087 .name = "kmem.max_usage_in_bytes",
5088 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
6770c64e 5089 .write = mem_cgroup_reset,
791badbd 5090 .read_u64 = mem_cgroup_read_u64,
510fc4e1 5091 },
a87425a3
YS
5092#if defined(CONFIG_MEMCG_KMEM) && \
5093 (defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG))
749c5415
GC
5094 {
5095 .name = "kmem.slabinfo",
bc2791f8
TH
5096 .seq_start = memcg_slab_start,
5097 .seq_next = memcg_slab_next,
5098 .seq_stop = memcg_slab_stop,
b047501c 5099 .seq_show = memcg_slab_show,
749c5415
GC
5100 },
5101#endif
d55f90bf
VD
5102 {
5103 .name = "kmem.tcp.limit_in_bytes",
5104 .private = MEMFILE_PRIVATE(_TCP, RES_LIMIT),
5105 .write = mem_cgroup_write,
5106 .read_u64 = mem_cgroup_read_u64,
5107 },
5108 {
5109 .name = "kmem.tcp.usage_in_bytes",
5110 .private = MEMFILE_PRIVATE(_TCP, RES_USAGE),
5111 .read_u64 = mem_cgroup_read_u64,
5112 },
5113 {
5114 .name = "kmem.tcp.failcnt",
5115 .private = MEMFILE_PRIVATE(_TCP, RES_FAILCNT),
5116 .write = mem_cgroup_reset,
5117 .read_u64 = mem_cgroup_read_u64,
5118 },
5119 {
5120 .name = "kmem.tcp.max_usage_in_bytes",
5121 .private = MEMFILE_PRIVATE(_TCP, RES_MAX_USAGE),
5122 .write = mem_cgroup_reset,
5123 .read_u64 = mem_cgroup_read_u64,
5124 },
6bc10349 5125 { }, /* terminate */
af36f906 5126};
8c7c6e34 5127
73f576c0
JW
5128/*
5129 * Private memory cgroup IDR
5130 *
5131 * Swap-out records and page cache shadow entries need to store memcg
5132 * references in constrained space, so we maintain an ID space that is
5133 * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of
5134 * memory-controlled cgroups to 64k.
5135 *
b8f2935f 5136 * However, there usually are many references to the offline CSS after
73f576c0
JW
5137 * the cgroup has been destroyed, such as page cache or reclaimable
5138 * slab objects, that don't need to hang on to the ID. We want to keep
5139 * those dead CSS from occupying IDs, or we might quickly exhaust the
5140 * relatively small ID space and prevent the creation of new cgroups
5141 * even when there are much fewer than 64k cgroups - possibly none.
5142 *
5143 * Maintain a private 16-bit ID space for memcg, and allow the ID to
5144 * be freed and recycled when it's no longer needed, which is usually
5145 * when the CSS is offlined.
5146 *
5147 * The only exception to that are records of swapped out tmpfs/shmem
5148 * pages that need to be attributed to live ancestors on swapin. But
5149 * those references are manageable from userspace.
5150 */
5151
5152static DEFINE_IDR(mem_cgroup_idr);
5153
7e97de0b
KT
5154static void mem_cgroup_id_remove(struct mem_cgroup *memcg)
5155{
5156 if (memcg->id.id > 0) {
5157 idr_remove(&mem_cgroup_idr, memcg->id.id);
5158 memcg->id.id = 0;
5159 }
5160}
5161
c1514c0a
VF
5162static void __maybe_unused mem_cgroup_id_get_many(struct mem_cgroup *memcg,
5163 unsigned int n)
73f576c0 5164{
1c2d479a 5165 refcount_add(n, &memcg->id.ref);
73f576c0
JW
5166}
5167
615d66c3 5168static void mem_cgroup_id_put_many(struct mem_cgroup *memcg, unsigned int n)
73f576c0 5169{
1c2d479a 5170 if (refcount_sub_and_test(n, &memcg->id.ref)) {
7e97de0b 5171 mem_cgroup_id_remove(memcg);
73f576c0
JW
5172
5173 /* Memcg ID pins CSS */
5174 css_put(&memcg->css);
5175 }
5176}
5177
615d66c3
VD
5178static inline void mem_cgroup_id_put(struct mem_cgroup *memcg)
5179{
5180 mem_cgroup_id_put_many(memcg, 1);
5181}
5182
73f576c0
JW
5183/**
5184 * mem_cgroup_from_id - look up a memcg from a memcg id
5185 * @id: the memcg id to look up
5186 *
5187 * Caller must hold rcu_read_lock().
5188 */
5189struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
5190{
5191 WARN_ON_ONCE(!rcu_read_lock_held());
5192 return idr_find(&mem_cgroup_idr, id);
5193}
5194
ef8f2327 5195static int alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
6d12e2d8
KH
5196{
5197 struct mem_cgroup_per_node *pn;
ef8f2327 5198 int tmp = node;
1ecaab2b
KH
5199 /*
5200 * This routine is called against possible nodes.
5201 * But it's BUG to call kmalloc() against offline node.
5202 *
5203 * TODO: this routine can waste much memory for nodes which will
5204 * never be onlined. It's better to use memory hotplug callback
5205 * function.
5206 */
41e3355d
KH
5207 if (!node_state(node, N_NORMAL_MEMORY))
5208 tmp = -1;
17295c88 5209 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
6d12e2d8
KH
5210 if (!pn)
5211 return 1;
1ecaab2b 5212
815744d7
JW
5213 pn->lruvec_stat_local = alloc_percpu(struct lruvec_stat);
5214 if (!pn->lruvec_stat_local) {
5215 kfree(pn);
5216 return 1;
5217 }
5218
a983b5eb
JW
5219 pn->lruvec_stat_cpu = alloc_percpu(struct lruvec_stat);
5220 if (!pn->lruvec_stat_cpu) {
815744d7 5221 free_percpu(pn->lruvec_stat_local);
00f3ca2c
JW
5222 kfree(pn);
5223 return 1;
5224 }
5225
ef8f2327
MG
5226 lruvec_init(&pn->lruvec);
5227 pn->usage_in_excess = 0;
5228 pn->on_tree = false;
5229 pn->memcg = memcg;
5230
54f72fe0 5231 memcg->nodeinfo[node] = pn;
6d12e2d8
KH
5232 return 0;
5233}
5234
ef8f2327 5235static void free_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
1ecaab2b 5236{
00f3ca2c
JW
5237 struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
5238
4eaf431f
MH
5239 if (!pn)
5240 return;
5241
a983b5eb 5242 free_percpu(pn->lruvec_stat_cpu);
815744d7 5243 free_percpu(pn->lruvec_stat_local);
00f3ca2c 5244 kfree(pn);
1ecaab2b
KH
5245}
5246
40e952f9 5247static void __mem_cgroup_free(struct mem_cgroup *memcg)
59927fb9 5248{
c8b2a36f 5249 int node;
59927fb9 5250
c8b2a36f 5251 for_each_node(node)
ef8f2327 5252 free_mem_cgroup_per_node_info(memcg, node);
871789d4 5253 free_percpu(memcg->vmstats_percpu);
815744d7 5254 free_percpu(memcg->vmstats_local);
8ff69e2c 5255 kfree(memcg);
59927fb9 5256}
3afe36b1 5257
40e952f9
TE
5258static void mem_cgroup_free(struct mem_cgroup *memcg)
5259{
5260 memcg_wb_domain_exit(memcg);
7961eee3
SB
5261 /*
5262 * Flush percpu vmstats and vmevents to guarantee the value correctness
5263 * on parent's and all ancestor levels.
5264 */
4a87e2a2 5265 memcg_flush_percpu_vmstats(memcg);
7961eee3 5266 memcg_flush_percpu_vmevents(memcg);
40e952f9
TE
5267 __mem_cgroup_free(memcg);
5268}
5269
0b8f73e1 5270static struct mem_cgroup *mem_cgroup_alloc(void)
8cdea7c0 5271{
d142e3e6 5272 struct mem_cgroup *memcg;
b9726c26 5273 unsigned int size;
6d12e2d8 5274 int node;
97b27821 5275 int __maybe_unused i;
11d67612 5276 long error = -ENOMEM;
8cdea7c0 5277
0b8f73e1
JW
5278 size = sizeof(struct mem_cgroup);
5279 size += nr_node_ids * sizeof(struct mem_cgroup_per_node *);
5280
5281 memcg = kzalloc(size, GFP_KERNEL);
c0ff4b85 5282 if (!memcg)
11d67612 5283 return ERR_PTR(error);
0b8f73e1 5284
73f576c0
JW
5285 memcg->id.id = idr_alloc(&mem_cgroup_idr, NULL,
5286 1, MEM_CGROUP_ID_MAX,
5287 GFP_KERNEL);
11d67612
YS
5288 if (memcg->id.id < 0) {
5289 error = memcg->id.id;
73f576c0 5290 goto fail;
11d67612 5291 }
73f576c0 5292
815744d7
JW
5293 memcg->vmstats_local = alloc_percpu(struct memcg_vmstats_percpu);
5294 if (!memcg->vmstats_local)
5295 goto fail;
5296
871789d4
CD
5297 memcg->vmstats_percpu = alloc_percpu(struct memcg_vmstats_percpu);
5298 if (!memcg->vmstats_percpu)
0b8f73e1 5299 goto fail;
78fb7466 5300
3ed28fa1 5301 for_each_node(node)
ef8f2327 5302 if (alloc_mem_cgroup_per_node_info(memcg, node))
0b8f73e1 5303 goto fail;
f64c3f54 5304
0b8f73e1
JW
5305 if (memcg_wb_domain_init(memcg, GFP_KERNEL))
5306 goto fail;
28dbc4b6 5307
f7e1cb6e 5308 INIT_WORK(&memcg->high_work, high_work_func);
d142e3e6 5309 INIT_LIST_HEAD(&memcg->oom_notify);
d142e3e6
GC
5310 mutex_init(&memcg->thresholds_lock);
5311 spin_lock_init(&memcg->move_lock);
70ddf637 5312 vmpressure_init(&memcg->vmpressure);
fba94807
TH
5313 INIT_LIST_HEAD(&memcg->event_list);
5314 spin_lock_init(&memcg->event_list_lock);
d886f4e4 5315 memcg->socket_pressure = jiffies;
84c07d11 5316#ifdef CONFIG_MEMCG_KMEM
900a38f0 5317 memcg->kmemcg_id = -1;
bf4f0599 5318 INIT_LIST_HEAD(&memcg->objcg_list);
900a38f0 5319#endif
52ebea74
TH
5320#ifdef CONFIG_CGROUP_WRITEBACK
5321 INIT_LIST_HEAD(&memcg->cgwb_list);
97b27821
TH
5322 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5323 memcg->cgwb_frn[i].done =
5324 __WB_COMPLETION_INIT(&memcg_cgwb_frn_waitq);
87eaceb3
YS
5325#endif
5326#ifdef CONFIG_TRANSPARENT_HUGEPAGE
5327 spin_lock_init(&memcg->deferred_split_queue.split_queue_lock);
5328 INIT_LIST_HEAD(&memcg->deferred_split_queue.split_queue);
5329 memcg->deferred_split_queue.split_queue_len = 0;
52ebea74 5330#endif
73f576c0 5331 idr_replace(&mem_cgroup_idr, memcg, memcg->id.id);
0b8f73e1
JW
5332 return memcg;
5333fail:
7e97de0b 5334 mem_cgroup_id_remove(memcg);
40e952f9 5335 __mem_cgroup_free(memcg);
11d67612 5336 return ERR_PTR(error);
d142e3e6
GC
5337}
5338
0b8f73e1
JW
5339static struct cgroup_subsys_state * __ref
5340mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
d142e3e6 5341{
0b8f73e1
JW
5342 struct mem_cgroup *parent = mem_cgroup_from_css(parent_css);
5343 struct mem_cgroup *memcg;
5344 long error = -ENOMEM;
d142e3e6 5345
0b8f73e1 5346 memcg = mem_cgroup_alloc();
11d67612
YS
5347 if (IS_ERR(memcg))
5348 return ERR_CAST(memcg);
d142e3e6 5349
d1663a90 5350 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
0b8f73e1 5351 memcg->soft_limit = PAGE_COUNTER_MAX;
4b82ab4f 5352 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
0b8f73e1
JW
5353 if (parent) {
5354 memcg->swappiness = mem_cgroup_swappiness(parent);
5355 memcg->oom_kill_disable = parent->oom_kill_disable;
5356 }
5357 if (parent && parent->use_hierarchy) {
5358 memcg->use_hierarchy = true;
3e32cb2e 5359 page_counter_init(&memcg->memory, &parent->memory);
37e84351 5360 page_counter_init(&memcg->swap, &parent->swap);
3e32cb2e
JW
5361 page_counter_init(&memcg->memsw, &parent->memsw);
5362 page_counter_init(&memcg->kmem, &parent->kmem);
0db15298 5363 page_counter_init(&memcg->tcpmem, &parent->tcpmem);
18f59ea7 5364 } else {
3e32cb2e 5365 page_counter_init(&memcg->memory, NULL);
37e84351 5366 page_counter_init(&memcg->swap, NULL);
3e32cb2e
JW
5367 page_counter_init(&memcg->memsw, NULL);
5368 page_counter_init(&memcg->kmem, NULL);
0db15298 5369 page_counter_init(&memcg->tcpmem, NULL);
8c7f6edb
TH
5370 /*
5371 * Deeper hierachy with use_hierarchy == false doesn't make
5372 * much sense so let cgroup subsystem know about this
5373 * unfortunate state in our controller.
5374 */
d142e3e6 5375 if (parent != root_mem_cgroup)
073219e9 5376 memory_cgrp_subsys.broken_hierarchy = true;
18f59ea7 5377 }
d6441637 5378
0b8f73e1
JW
5379 /* The following stuff does not apply to the root */
5380 if (!parent) {
fb2f2b0a
RG
5381#ifdef CONFIG_MEMCG_KMEM
5382 INIT_LIST_HEAD(&memcg->kmem_caches);
5383#endif
0b8f73e1
JW
5384 root_mem_cgroup = memcg;
5385 return &memcg->css;
5386 }
5387
b313aeee 5388 error = memcg_online_kmem(memcg);
0b8f73e1
JW
5389 if (error)
5390 goto fail;
127424c8 5391
f7e1cb6e 5392 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
ef12947c 5393 static_branch_inc(&memcg_sockets_enabled_key);
f7e1cb6e 5394
0b8f73e1
JW
5395 return &memcg->css;
5396fail:
7e97de0b 5397 mem_cgroup_id_remove(memcg);
0b8f73e1 5398 mem_cgroup_free(memcg);
11d67612 5399 return ERR_PTR(error);
0b8f73e1
JW
5400}
5401
73f576c0 5402static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
0b8f73e1 5403{
58fa2a55
VD
5404 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5405
0a4465d3
KT
5406 /*
5407 * A memcg must be visible for memcg_expand_shrinker_maps()
5408 * by the time the maps are allocated. So, we allocate maps
5409 * here, when for_each_mem_cgroup() can't skip it.
5410 */
5411 if (memcg_alloc_shrinker_maps(memcg)) {
5412 mem_cgroup_id_remove(memcg);
5413 return -ENOMEM;
5414 }
5415
73f576c0 5416 /* Online state pins memcg ID, memcg ID pins CSS */
1c2d479a 5417 refcount_set(&memcg->id.ref, 1);
73f576c0 5418 css_get(css);
2f7dd7a4 5419 return 0;
8cdea7c0
BS
5420}
5421
eb95419b 5422static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
df878fb0 5423{
eb95419b 5424 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3bc942f3 5425 struct mem_cgroup_event *event, *tmp;
79bd9814
TH
5426
5427 /*
5428 * Unregister events and notify userspace.
5429 * Notify userspace about cgroup removing only after rmdir of cgroup
5430 * directory to avoid race between userspace and kernelspace.
5431 */
fba94807
TH
5432 spin_lock(&memcg->event_list_lock);
5433 list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
79bd9814
TH
5434 list_del_init(&event->list);
5435 schedule_work(&event->remove);
5436 }
fba94807 5437 spin_unlock(&memcg->event_list_lock);
ec64f515 5438
bf8d5d52 5439 page_counter_set_min(&memcg->memory, 0);
23067153 5440 page_counter_set_low(&memcg->memory, 0);
63677c74 5441
567e9ab2 5442 memcg_offline_kmem(memcg);
52ebea74 5443 wb_memcg_offline(memcg);
73f576c0 5444
591edfb1
RG
5445 drain_all_stock(memcg);
5446
73f576c0 5447 mem_cgroup_id_put(memcg);
df878fb0
KH
5448}
5449
6df38689
VD
5450static void mem_cgroup_css_released(struct cgroup_subsys_state *css)
5451{
5452 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5453
5454 invalidate_reclaim_iterators(memcg);
5455}
5456
eb95419b 5457static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
8cdea7c0 5458{
eb95419b 5459 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
97b27821 5460 int __maybe_unused i;
c268e994 5461
97b27821
TH
5462#ifdef CONFIG_CGROUP_WRITEBACK
5463 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5464 wb_wait_for_completion(&memcg->cgwb_frn[i].done);
5465#endif
f7e1cb6e 5466 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
ef12947c 5467 static_branch_dec(&memcg_sockets_enabled_key);
127424c8 5468
0db15298 5469 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg->tcpmem_active)
d55f90bf 5470 static_branch_dec(&memcg_sockets_enabled_key);
3893e302 5471
0b8f73e1
JW
5472 vmpressure_cleanup(&memcg->vmpressure);
5473 cancel_work_sync(&memcg->high_work);
5474 mem_cgroup_remove_from_trees(memcg);
0a4465d3 5475 memcg_free_shrinker_maps(memcg);
d886f4e4 5476 memcg_free_kmem(memcg);
0b8f73e1 5477 mem_cgroup_free(memcg);
8cdea7c0
BS
5478}
5479
1ced953b
TH
5480/**
5481 * mem_cgroup_css_reset - reset the states of a mem_cgroup
5482 * @css: the target css
5483 *
5484 * Reset the states of the mem_cgroup associated with @css. This is
5485 * invoked when the userland requests disabling on the default hierarchy
5486 * but the memcg is pinned through dependency. The memcg should stop
5487 * applying policies and should revert to the vanilla state as it may be
5488 * made visible again.
5489 *
5490 * The current implementation only resets the essential configurations.
5491 * This needs to be expanded to cover all the visible parts.
5492 */
5493static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
5494{
5495 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5496
bbec2e15
RG
5497 page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX);
5498 page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX);
5499 page_counter_set_max(&memcg->memsw, PAGE_COUNTER_MAX);
5500 page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX);
5501 page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX);
bf8d5d52 5502 page_counter_set_min(&memcg->memory, 0);
23067153 5503 page_counter_set_low(&memcg->memory, 0);
d1663a90 5504 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
24d404dc 5505 memcg->soft_limit = PAGE_COUNTER_MAX;
4b82ab4f 5506 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
2529bb3a 5507 memcg_wb_domain_size_changed(memcg);
1ced953b
TH
5508}
5509
02491447 5510#ifdef CONFIG_MMU
7dc74be0 5511/* Handlers for move charge at task migration. */
854ffa8d 5512static int mem_cgroup_do_precharge(unsigned long count)
7dc74be0 5513{
05b84301 5514 int ret;
9476db97 5515
d0164adc
MG
5516 /* Try a single bulk charge without reclaim first, kswapd may wake */
5517 ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_DIRECT_RECLAIM, count);
9476db97 5518 if (!ret) {
854ffa8d 5519 mc.precharge += count;
854ffa8d
DN
5520 return ret;
5521 }
9476db97 5522
3674534b 5523 /* Try charges one by one with reclaim, but do not retry */
854ffa8d 5524 while (count--) {
3674534b 5525 ret = try_charge(mc.to, GFP_KERNEL | __GFP_NORETRY, 1);
38c5d72f 5526 if (ret)
38c5d72f 5527 return ret;
854ffa8d 5528 mc.precharge++;
9476db97 5529 cond_resched();
854ffa8d 5530 }
9476db97 5531 return 0;
4ffef5fe
DN
5532}
5533
4ffef5fe
DN
5534union mc_target {
5535 struct page *page;
02491447 5536 swp_entry_t ent;
4ffef5fe
DN
5537};
5538
4ffef5fe 5539enum mc_target_type {
8d32ff84 5540 MC_TARGET_NONE = 0,
4ffef5fe 5541 MC_TARGET_PAGE,
02491447 5542 MC_TARGET_SWAP,
c733a828 5543 MC_TARGET_DEVICE,
4ffef5fe
DN
5544};
5545
90254a65
DN
5546static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5547 unsigned long addr, pte_t ptent)
4ffef5fe 5548{
25b2995a 5549 struct page *page = vm_normal_page(vma, addr, ptent);
4ffef5fe 5550
90254a65
DN
5551 if (!page || !page_mapped(page))
5552 return NULL;
5553 if (PageAnon(page)) {
1dfab5ab 5554 if (!(mc.flags & MOVE_ANON))
90254a65 5555 return NULL;
1dfab5ab
JW
5556 } else {
5557 if (!(mc.flags & MOVE_FILE))
5558 return NULL;
5559 }
90254a65
DN
5560 if (!get_page_unless_zero(page))
5561 return NULL;
5562
5563 return page;
5564}
5565
c733a828 5566#if defined(CONFIG_SWAP) || defined(CONFIG_DEVICE_PRIVATE)
90254a65 5567static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
48406ef8 5568 pte_t ptent, swp_entry_t *entry)
90254a65 5569{
90254a65
DN
5570 struct page *page = NULL;
5571 swp_entry_t ent = pte_to_swp_entry(ptent);
5572
1dfab5ab 5573 if (!(mc.flags & MOVE_ANON) || non_swap_entry(ent))
90254a65 5574 return NULL;
c733a828
JG
5575
5576 /*
5577 * Handle MEMORY_DEVICE_PRIVATE which are ZONE_DEVICE page belonging to
5578 * a device and because they are not accessible by CPU they are store
5579 * as special swap entry in the CPU page table.
5580 */
5581 if (is_device_private_entry(ent)) {
5582 page = device_private_entry_to_page(ent);
5583 /*
5584 * MEMORY_DEVICE_PRIVATE means ZONE_DEVICE page and which have
5585 * a refcount of 1 when free (unlike normal page)
5586 */
5587 if (!page_ref_add_unless(page, 1, 1))
5588 return NULL;
5589 return page;
5590 }
5591
4b91355e
KH
5592 /*
5593 * Because lookup_swap_cache() updates some statistics counter,
5594 * we call find_get_page() with swapper_space directly.
5595 */
f6ab1f7f 5596 page = find_get_page(swap_address_space(ent), swp_offset(ent));
2d1c4980 5597 entry->val = ent.val;
90254a65
DN
5598
5599 return page;
5600}
4b91355e
KH
5601#else
5602static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
48406ef8 5603 pte_t ptent, swp_entry_t *entry)
4b91355e
KH
5604{
5605 return NULL;
5606}
5607#endif
90254a65 5608
87946a72
DN
5609static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5610 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5611{
5612 struct page *page = NULL;
87946a72
DN
5613 struct address_space *mapping;
5614 pgoff_t pgoff;
5615
5616 if (!vma->vm_file) /* anonymous vma */
5617 return NULL;
1dfab5ab 5618 if (!(mc.flags & MOVE_FILE))
87946a72
DN
5619 return NULL;
5620
87946a72 5621 mapping = vma->vm_file->f_mapping;
0661a336 5622 pgoff = linear_page_index(vma, addr);
87946a72
DN
5623
5624 /* page is moved even if it's not RSS of this task(page-faulted). */
aa3b1895
HD
5625#ifdef CONFIG_SWAP
5626 /* shmem/tmpfs may report page out on swap: account for that too. */
139b6a6f
JW
5627 if (shmem_mapping(mapping)) {
5628 page = find_get_entry(mapping, pgoff);
3159f943 5629 if (xa_is_value(page)) {
139b6a6f 5630 swp_entry_t swp = radix_to_swp_entry(page);
2d1c4980 5631 *entry = swp;
f6ab1f7f
HY
5632 page = find_get_page(swap_address_space(swp),
5633 swp_offset(swp));
139b6a6f
JW
5634 }
5635 } else
5636 page = find_get_page(mapping, pgoff);
5637#else
5638 page = find_get_page(mapping, pgoff);
aa3b1895 5639#endif
87946a72
DN
5640 return page;
5641}
5642
b1b0deab
CG
5643/**
5644 * mem_cgroup_move_account - move account of the page
5645 * @page: the page
25843c2b 5646 * @compound: charge the page as compound or small page
b1b0deab
CG
5647 * @from: mem_cgroup which the page is moved from.
5648 * @to: mem_cgroup which the page is moved to. @from != @to.
5649 *
3ac808fd 5650 * The caller must make sure the page is not on LRU (isolate_page() is useful.)
b1b0deab
CG
5651 *
5652 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
5653 * from old cgroup.
5654 */
5655static int mem_cgroup_move_account(struct page *page,
f627c2f5 5656 bool compound,
b1b0deab
CG
5657 struct mem_cgroup *from,
5658 struct mem_cgroup *to)
5659{
ae8af438
KK
5660 struct lruvec *from_vec, *to_vec;
5661 struct pglist_data *pgdat;
f627c2f5 5662 unsigned int nr_pages = compound ? hpage_nr_pages(page) : 1;
b1b0deab
CG
5663 int ret;
5664
5665 VM_BUG_ON(from == to);
5666 VM_BUG_ON_PAGE(PageLRU(page), page);
f627c2f5 5667 VM_BUG_ON(compound && !PageTransHuge(page));
b1b0deab
CG
5668
5669 /*
6a93ca8f 5670 * Prevent mem_cgroup_migrate() from looking at
45637bab 5671 * page->mem_cgroup of its source page while we change it.
b1b0deab 5672 */
f627c2f5 5673 ret = -EBUSY;
b1b0deab
CG
5674 if (!trylock_page(page))
5675 goto out;
5676
5677 ret = -EINVAL;
5678 if (page->mem_cgroup != from)
5679 goto out_unlock;
5680
ae8af438 5681 pgdat = page_pgdat(page);
867e5e1d
JW
5682 from_vec = mem_cgroup_lruvec(from, pgdat);
5683 to_vec = mem_cgroup_lruvec(to, pgdat);
ae8af438 5684
abb242f5 5685 lock_page_memcg(page);
b1b0deab 5686
be5d0a74
JW
5687 if (PageAnon(page)) {
5688 if (page_mapped(page)) {
5689 __mod_lruvec_state(from_vec, NR_ANON_MAPPED, -nr_pages);
5690 __mod_lruvec_state(to_vec, NR_ANON_MAPPED, nr_pages);
468c3982
JW
5691 if (PageTransHuge(page)) {
5692 __mod_lruvec_state(from_vec, NR_ANON_THPS,
5693 -nr_pages);
5694 __mod_lruvec_state(to_vec, NR_ANON_THPS,
5695 nr_pages);
5696 }
5697
be5d0a74
JW
5698 }
5699 } else {
0d1c2072
JW
5700 __mod_lruvec_state(from_vec, NR_FILE_PAGES, -nr_pages);
5701 __mod_lruvec_state(to_vec, NR_FILE_PAGES, nr_pages);
5702
5703 if (PageSwapBacked(page)) {
5704 __mod_lruvec_state(from_vec, NR_SHMEM, -nr_pages);
5705 __mod_lruvec_state(to_vec, NR_SHMEM, nr_pages);
5706 }
5707
49e50d27
JW
5708 if (page_mapped(page)) {
5709 __mod_lruvec_state(from_vec, NR_FILE_MAPPED, -nr_pages);
5710 __mod_lruvec_state(to_vec, NR_FILE_MAPPED, nr_pages);
5711 }
b1b0deab 5712
49e50d27
JW
5713 if (PageDirty(page)) {
5714 struct address_space *mapping = page_mapping(page);
c4843a75 5715
49e50d27
JW
5716 if (mapping_cap_account_dirty(mapping)) {
5717 __mod_lruvec_state(from_vec, NR_FILE_DIRTY,
5718 -nr_pages);
5719 __mod_lruvec_state(to_vec, NR_FILE_DIRTY,
5720 nr_pages);
5721 }
c4843a75
GT
5722 }
5723 }
5724
b1b0deab 5725 if (PageWriteback(page)) {
ae8af438
KK
5726 __mod_lruvec_state(from_vec, NR_WRITEBACK, -nr_pages);
5727 __mod_lruvec_state(to_vec, NR_WRITEBACK, nr_pages);
b1b0deab
CG
5728 }
5729
5730 /*
abb242f5
JW
5731 * All state has been migrated, let's switch to the new memcg.
5732 *
b1b0deab 5733 * It is safe to change page->mem_cgroup here because the page
abb242f5
JW
5734 * is referenced, charged, isolated, and locked: we can't race
5735 * with (un)charging, migration, LRU putback, or anything else
5736 * that would rely on a stable page->mem_cgroup.
5737 *
5738 * Note that lock_page_memcg is a memcg lock, not a page lock,
5739 * to save space. As soon as we switch page->mem_cgroup to a
5740 * new memcg that isn't locked, the above state can change
5741 * concurrently again. Make sure we're truly done with it.
b1b0deab 5742 */
abb242f5 5743 smp_mb();
b1b0deab 5744
1a3e1f40
JW
5745 css_get(&to->css);
5746 css_put(&from->css);
5747
5748 page->mem_cgroup = to;
87eaceb3 5749
abb242f5 5750 __unlock_page_memcg(from);
b1b0deab
CG
5751
5752 ret = 0;
5753
5754 local_irq_disable();
3fba69a5 5755 mem_cgroup_charge_statistics(to, page, nr_pages);
b1b0deab 5756 memcg_check_events(to, page);
3fba69a5 5757 mem_cgroup_charge_statistics(from, page, -nr_pages);
b1b0deab
CG
5758 memcg_check_events(from, page);
5759 local_irq_enable();
5760out_unlock:
5761 unlock_page(page);
5762out:
5763 return ret;
5764}
5765
7cf7806c
LR
5766/**
5767 * get_mctgt_type - get target type of moving charge
5768 * @vma: the vma the pte to be checked belongs
5769 * @addr: the address corresponding to the pte to be checked
5770 * @ptent: the pte to be checked
5771 * @target: the pointer the target page or swap ent will be stored(can be NULL)
5772 *
5773 * Returns
5774 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
5775 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5776 * move charge. if @target is not NULL, the page is stored in target->page
5777 * with extra refcnt got(Callers should handle it).
5778 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5779 * target for charge migration. if @target is not NULL, the entry is stored
5780 * in target->ent.
25b2995a
CH
5781 * 3(MC_TARGET_DEVICE): like MC_TARGET_PAGE but page is MEMORY_DEVICE_PRIVATE
5782 * (so ZONE_DEVICE page and thus not on the lru).
df6ad698
JG
5783 * For now we such page is charge like a regular page would be as for all
5784 * intent and purposes it is just special memory taking the place of a
5785 * regular page.
c733a828
JG
5786 *
5787 * See Documentations/vm/hmm.txt and include/linux/hmm.h
7cf7806c
LR
5788 *
5789 * Called with pte lock held.
5790 */
5791
8d32ff84 5792static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
90254a65
DN
5793 unsigned long addr, pte_t ptent, union mc_target *target)
5794{
5795 struct page *page = NULL;
8d32ff84 5796 enum mc_target_type ret = MC_TARGET_NONE;
90254a65
DN
5797 swp_entry_t ent = { .val = 0 };
5798
5799 if (pte_present(ptent))
5800 page = mc_handle_present_pte(vma, addr, ptent);
5801 else if (is_swap_pte(ptent))
48406ef8 5802 page = mc_handle_swap_pte(vma, ptent, &ent);
0661a336 5803 else if (pte_none(ptent))
87946a72 5804 page = mc_handle_file_pte(vma, addr, ptent, &ent);
90254a65
DN
5805
5806 if (!page && !ent.val)
8d32ff84 5807 return ret;
02491447 5808 if (page) {
02491447 5809 /*
0a31bc97 5810 * Do only loose check w/o serialization.
1306a85a 5811 * mem_cgroup_move_account() checks the page is valid or
0a31bc97 5812 * not under LRU exclusion.
02491447 5813 */
1306a85a 5814 if (page->mem_cgroup == mc.from) {
02491447 5815 ret = MC_TARGET_PAGE;
25b2995a 5816 if (is_device_private_page(page))
c733a828 5817 ret = MC_TARGET_DEVICE;
02491447
DN
5818 if (target)
5819 target->page = page;
5820 }
5821 if (!ret || !target)
5822 put_page(page);
5823 }
3e14a57b
HY
5824 /*
5825 * There is a swap entry and a page doesn't exist or isn't charged.
5826 * But we cannot move a tail-page in a THP.
5827 */
5828 if (ent.val && !ret && (!page || !PageTransCompound(page)) &&
34c00c31 5829 mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
7f0f1546
KH
5830 ret = MC_TARGET_SWAP;
5831 if (target)
5832 target->ent = ent;
4ffef5fe 5833 }
4ffef5fe
DN
5834 return ret;
5835}
5836
12724850
NH
5837#ifdef CONFIG_TRANSPARENT_HUGEPAGE
5838/*
d6810d73
HY
5839 * We don't consider PMD mapped swapping or file mapped pages because THP does
5840 * not support them for now.
12724850
NH
5841 * Caller should make sure that pmd_trans_huge(pmd) is true.
5842 */
5843static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5844 unsigned long addr, pmd_t pmd, union mc_target *target)
5845{
5846 struct page *page = NULL;
12724850
NH
5847 enum mc_target_type ret = MC_TARGET_NONE;
5848
84c3fc4e
ZY
5849 if (unlikely(is_swap_pmd(pmd))) {
5850 VM_BUG_ON(thp_migration_supported() &&
5851 !is_pmd_migration_entry(pmd));
5852 return ret;
5853 }
12724850 5854 page = pmd_page(pmd);
309381fe 5855 VM_BUG_ON_PAGE(!page || !PageHead(page), page);
1dfab5ab 5856 if (!(mc.flags & MOVE_ANON))
12724850 5857 return ret;
1306a85a 5858 if (page->mem_cgroup == mc.from) {
12724850
NH
5859 ret = MC_TARGET_PAGE;
5860 if (target) {
5861 get_page(page);
5862 target->page = page;
5863 }
5864 }
5865 return ret;
5866}
5867#else
5868static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5869 unsigned long addr, pmd_t pmd, union mc_target *target)
5870{
5871 return MC_TARGET_NONE;
5872}
5873#endif
5874
4ffef5fe
DN
5875static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
5876 unsigned long addr, unsigned long end,
5877 struct mm_walk *walk)
5878{
26bcd64a 5879 struct vm_area_struct *vma = walk->vma;
4ffef5fe
DN
5880 pte_t *pte;
5881 spinlock_t *ptl;
5882
b6ec57f4
KS
5883 ptl = pmd_trans_huge_lock(pmd, vma);
5884 if (ptl) {
c733a828
JG
5885 /*
5886 * Note their can not be MC_TARGET_DEVICE for now as we do not
25b2995a
CH
5887 * support transparent huge page with MEMORY_DEVICE_PRIVATE but
5888 * this might change.
c733a828 5889 */
12724850
NH
5890 if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
5891 mc.precharge += HPAGE_PMD_NR;
bf929152 5892 spin_unlock(ptl);
1a5a9906 5893 return 0;
12724850 5894 }
03319327 5895
45f83cef
AA
5896 if (pmd_trans_unstable(pmd))
5897 return 0;
4ffef5fe
DN
5898 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5899 for (; addr != end; pte++, addr += PAGE_SIZE)
8d32ff84 5900 if (get_mctgt_type(vma, addr, *pte, NULL))
4ffef5fe
DN
5901 mc.precharge++; /* increment precharge temporarily */
5902 pte_unmap_unlock(pte - 1, ptl);
5903 cond_resched();
5904
7dc74be0
DN
5905 return 0;
5906}
5907
7b86ac33
CH
5908static const struct mm_walk_ops precharge_walk_ops = {
5909 .pmd_entry = mem_cgroup_count_precharge_pte_range,
5910};
5911
4ffef5fe
DN
5912static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
5913{
5914 unsigned long precharge;
4ffef5fe 5915
d8ed45c5 5916 mmap_read_lock(mm);
7b86ac33 5917 walk_page_range(mm, 0, mm->highest_vm_end, &precharge_walk_ops, NULL);
d8ed45c5 5918 mmap_read_unlock(mm);
4ffef5fe
DN
5919
5920 precharge = mc.precharge;
5921 mc.precharge = 0;
5922
5923 return precharge;
5924}
5925
4ffef5fe
DN
5926static int mem_cgroup_precharge_mc(struct mm_struct *mm)
5927{
dfe076b0
DN
5928 unsigned long precharge = mem_cgroup_count_precharge(mm);
5929
5930 VM_BUG_ON(mc.moving_task);
5931 mc.moving_task = current;
5932 return mem_cgroup_do_precharge(precharge);
4ffef5fe
DN
5933}
5934
dfe076b0
DN
5935/* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5936static void __mem_cgroup_clear_mc(void)
4ffef5fe 5937{
2bd9bb20
KH
5938 struct mem_cgroup *from = mc.from;
5939 struct mem_cgroup *to = mc.to;
5940
4ffef5fe 5941 /* we must uncharge all the leftover precharges from mc.to */
854ffa8d 5942 if (mc.precharge) {
00501b53 5943 cancel_charge(mc.to, mc.precharge);
854ffa8d
DN
5944 mc.precharge = 0;
5945 }
5946 /*
5947 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5948 * we must uncharge here.
5949 */
5950 if (mc.moved_charge) {
00501b53 5951 cancel_charge(mc.from, mc.moved_charge);
854ffa8d 5952 mc.moved_charge = 0;
4ffef5fe 5953 }
483c30b5
DN
5954 /* we must fixup refcnts and charges */
5955 if (mc.moved_swap) {
483c30b5 5956 /* uncharge swap account from the old cgroup */
ce00a967 5957 if (!mem_cgroup_is_root(mc.from))
3e32cb2e 5958 page_counter_uncharge(&mc.from->memsw, mc.moved_swap);
483c30b5 5959
615d66c3
VD
5960 mem_cgroup_id_put_many(mc.from, mc.moved_swap);
5961
05b84301 5962 /*
3e32cb2e
JW
5963 * we charged both to->memory and to->memsw, so we
5964 * should uncharge to->memory.
05b84301 5965 */
ce00a967 5966 if (!mem_cgroup_is_root(mc.to))
3e32cb2e
JW
5967 page_counter_uncharge(&mc.to->memory, mc.moved_swap);
5968
483c30b5
DN
5969 mc.moved_swap = 0;
5970 }
dfe076b0
DN
5971 memcg_oom_recover(from);
5972 memcg_oom_recover(to);
5973 wake_up_all(&mc.waitq);
5974}
5975
5976static void mem_cgroup_clear_mc(void)
5977{
264a0ae1
TH
5978 struct mm_struct *mm = mc.mm;
5979
dfe076b0
DN
5980 /*
5981 * we must clear moving_task before waking up waiters at the end of
5982 * task migration.
5983 */
5984 mc.moving_task = NULL;
5985 __mem_cgroup_clear_mc();
2bd9bb20 5986 spin_lock(&mc.lock);
4ffef5fe
DN
5987 mc.from = NULL;
5988 mc.to = NULL;
264a0ae1 5989 mc.mm = NULL;
2bd9bb20 5990 spin_unlock(&mc.lock);
264a0ae1
TH
5991
5992 mmput(mm);
4ffef5fe
DN
5993}
5994
1f7dd3e5 5995static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
7dc74be0 5996{
1f7dd3e5 5997 struct cgroup_subsys_state *css;
eed67d75 5998 struct mem_cgroup *memcg = NULL; /* unneeded init to make gcc happy */
9f2115f9 5999 struct mem_cgroup *from;
4530eddb 6000 struct task_struct *leader, *p;
9f2115f9 6001 struct mm_struct *mm;
1dfab5ab 6002 unsigned long move_flags;
9f2115f9 6003 int ret = 0;
7dc74be0 6004
1f7dd3e5
TH
6005 /* charge immigration isn't supported on the default hierarchy */
6006 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
9f2115f9
TH
6007 return 0;
6008
4530eddb
TH
6009 /*
6010 * Multi-process migrations only happen on the default hierarchy
6011 * where charge immigration is not used. Perform charge
6012 * immigration if @tset contains a leader and whine if there are
6013 * multiple.
6014 */
6015 p = NULL;
1f7dd3e5 6016 cgroup_taskset_for_each_leader(leader, css, tset) {
4530eddb
TH
6017 WARN_ON_ONCE(p);
6018 p = leader;
1f7dd3e5 6019 memcg = mem_cgroup_from_css(css);
4530eddb
TH
6020 }
6021 if (!p)
6022 return 0;
6023
1f7dd3e5
TH
6024 /*
6025 * We are now commited to this value whatever it is. Changes in this
6026 * tunable will only affect upcoming migrations, not the current one.
6027 * So we need to save it, and keep it going.
6028 */
6029 move_flags = READ_ONCE(memcg->move_charge_at_immigrate);
6030 if (!move_flags)
6031 return 0;
6032
9f2115f9
TH
6033 from = mem_cgroup_from_task(p);
6034
6035 VM_BUG_ON(from == memcg);
6036
6037 mm = get_task_mm(p);
6038 if (!mm)
6039 return 0;
6040 /* We move charges only when we move a owner of the mm */
6041 if (mm->owner == p) {
6042 VM_BUG_ON(mc.from);
6043 VM_BUG_ON(mc.to);
6044 VM_BUG_ON(mc.precharge);
6045 VM_BUG_ON(mc.moved_charge);
6046 VM_BUG_ON(mc.moved_swap);
6047
6048 spin_lock(&mc.lock);
264a0ae1 6049 mc.mm = mm;
9f2115f9
TH
6050 mc.from = from;
6051 mc.to = memcg;
6052 mc.flags = move_flags;
6053 spin_unlock(&mc.lock);
6054 /* We set mc.moving_task later */
6055
6056 ret = mem_cgroup_precharge_mc(mm);
6057 if (ret)
6058 mem_cgroup_clear_mc();
264a0ae1
TH
6059 } else {
6060 mmput(mm);
7dc74be0
DN
6061 }
6062 return ret;
6063}
6064
1f7dd3e5 6065static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
7dc74be0 6066{
4e2f245d
JW
6067 if (mc.to)
6068 mem_cgroup_clear_mc();
7dc74be0
DN
6069}
6070
4ffef5fe
DN
6071static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
6072 unsigned long addr, unsigned long end,
6073 struct mm_walk *walk)
7dc74be0 6074{
4ffef5fe 6075 int ret = 0;
26bcd64a 6076 struct vm_area_struct *vma = walk->vma;
4ffef5fe
DN
6077 pte_t *pte;
6078 spinlock_t *ptl;
12724850
NH
6079 enum mc_target_type target_type;
6080 union mc_target target;
6081 struct page *page;
4ffef5fe 6082
b6ec57f4
KS
6083 ptl = pmd_trans_huge_lock(pmd, vma);
6084 if (ptl) {
62ade86a 6085 if (mc.precharge < HPAGE_PMD_NR) {
bf929152 6086 spin_unlock(ptl);
12724850
NH
6087 return 0;
6088 }
6089 target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
6090 if (target_type == MC_TARGET_PAGE) {
6091 page = target.page;
6092 if (!isolate_lru_page(page)) {
f627c2f5 6093 if (!mem_cgroup_move_account(page, true,
1306a85a 6094 mc.from, mc.to)) {
12724850
NH
6095 mc.precharge -= HPAGE_PMD_NR;
6096 mc.moved_charge += HPAGE_PMD_NR;
6097 }
6098 putback_lru_page(page);
6099 }
6100 put_page(page);
c733a828
JG
6101 } else if (target_type == MC_TARGET_DEVICE) {
6102 page = target.page;
6103 if (!mem_cgroup_move_account(page, true,
6104 mc.from, mc.to)) {
6105 mc.precharge -= HPAGE_PMD_NR;
6106 mc.moved_charge += HPAGE_PMD_NR;
6107 }
6108 put_page(page);
12724850 6109 }
bf929152 6110 spin_unlock(ptl);
1a5a9906 6111 return 0;
12724850
NH
6112 }
6113
45f83cef
AA
6114 if (pmd_trans_unstable(pmd))
6115 return 0;
4ffef5fe
DN
6116retry:
6117 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6118 for (; addr != end; addr += PAGE_SIZE) {
6119 pte_t ptent = *(pte++);
c733a828 6120 bool device = false;
02491447 6121 swp_entry_t ent;
4ffef5fe
DN
6122
6123 if (!mc.precharge)
6124 break;
6125
8d32ff84 6126 switch (get_mctgt_type(vma, addr, ptent, &target)) {
c733a828
JG
6127 case MC_TARGET_DEVICE:
6128 device = true;
e4a9bc58 6129 fallthrough;
4ffef5fe
DN
6130 case MC_TARGET_PAGE:
6131 page = target.page;
53f9263b
KS
6132 /*
6133 * We can have a part of the split pmd here. Moving it
6134 * can be done but it would be too convoluted so simply
6135 * ignore such a partial THP and keep it in original
6136 * memcg. There should be somebody mapping the head.
6137 */
6138 if (PageTransCompound(page))
6139 goto put;
c733a828 6140 if (!device && isolate_lru_page(page))
4ffef5fe 6141 goto put;
f627c2f5
KS
6142 if (!mem_cgroup_move_account(page, false,
6143 mc.from, mc.to)) {
4ffef5fe 6144 mc.precharge--;
854ffa8d
DN
6145 /* we uncharge from mc.from later. */
6146 mc.moved_charge++;
4ffef5fe 6147 }
c733a828
JG
6148 if (!device)
6149 putback_lru_page(page);
8d32ff84 6150put: /* get_mctgt_type() gets the page */
4ffef5fe
DN
6151 put_page(page);
6152 break;
02491447
DN
6153 case MC_TARGET_SWAP:
6154 ent = target.ent;
e91cbb42 6155 if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
02491447 6156 mc.precharge--;
8d22a935
HD
6157 mem_cgroup_id_get_many(mc.to, 1);
6158 /* we fixup other refcnts and charges later. */
483c30b5
DN
6159 mc.moved_swap++;
6160 }
02491447 6161 break;
4ffef5fe
DN
6162 default:
6163 break;
6164 }
6165 }
6166 pte_unmap_unlock(pte - 1, ptl);
6167 cond_resched();
6168
6169 if (addr != end) {
6170 /*
6171 * We have consumed all precharges we got in can_attach().
6172 * We try charge one by one, but don't do any additional
6173 * charges to mc.to if we have failed in charge once in attach()
6174 * phase.
6175 */
854ffa8d 6176 ret = mem_cgroup_do_precharge(1);
4ffef5fe
DN
6177 if (!ret)
6178 goto retry;
6179 }
6180
6181 return ret;
6182}
6183
7b86ac33
CH
6184static const struct mm_walk_ops charge_walk_ops = {
6185 .pmd_entry = mem_cgroup_move_charge_pte_range,
6186};
6187
264a0ae1 6188static void mem_cgroup_move_charge(void)
4ffef5fe 6189{
4ffef5fe 6190 lru_add_drain_all();
312722cb 6191 /*
81f8c3a4
JW
6192 * Signal lock_page_memcg() to take the memcg's move_lock
6193 * while we're moving its pages to another memcg. Then wait
6194 * for already started RCU-only updates to finish.
312722cb
JW
6195 */
6196 atomic_inc(&mc.from->moving_account);
6197 synchronize_rcu();
dfe076b0 6198retry:
d8ed45c5 6199 if (unlikely(!mmap_read_trylock(mc.mm))) {
dfe076b0 6200 /*
c1e8d7c6 6201 * Someone who are holding the mmap_lock might be waiting in
dfe076b0
DN
6202 * waitq. So we cancel all extra charges, wake up all waiters,
6203 * and retry. Because we cancel precharges, we might not be able
6204 * to move enough charges, but moving charge is a best-effort
6205 * feature anyway, so it wouldn't be a big problem.
6206 */
6207 __mem_cgroup_clear_mc();
6208 cond_resched();
6209 goto retry;
6210 }
26bcd64a
NH
6211 /*
6212 * When we have consumed all precharges and failed in doing
6213 * additional charge, the page walk just aborts.
6214 */
7b86ac33
CH
6215 walk_page_range(mc.mm, 0, mc.mm->highest_vm_end, &charge_walk_ops,
6216 NULL);
0247f3f4 6217
d8ed45c5 6218 mmap_read_unlock(mc.mm);
312722cb 6219 atomic_dec(&mc.from->moving_account);
7dc74be0
DN
6220}
6221
264a0ae1 6222static void mem_cgroup_move_task(void)
67e465a7 6223{
264a0ae1
TH
6224 if (mc.to) {
6225 mem_cgroup_move_charge();
a433658c 6226 mem_cgroup_clear_mc();
264a0ae1 6227 }
67e465a7 6228}
5cfb80a7 6229#else /* !CONFIG_MMU */
1f7dd3e5 6230static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
5cfb80a7
DN
6231{
6232 return 0;
6233}
1f7dd3e5 6234static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
5cfb80a7
DN
6235{
6236}
264a0ae1 6237static void mem_cgroup_move_task(void)
5cfb80a7
DN
6238{
6239}
6240#endif
67e465a7 6241
f00baae7
TH
6242/*
6243 * Cgroup retains root cgroups across [un]mount cycles making it necessary
aa6ec29b
TH
6244 * to verify whether we're attached to the default hierarchy on each mount
6245 * attempt.
f00baae7 6246 */
eb95419b 6247static void mem_cgroup_bind(struct cgroup_subsys_state *root_css)
f00baae7
TH
6248{
6249 /*
aa6ec29b 6250 * use_hierarchy is forced on the default hierarchy. cgroup core
f00baae7
TH
6251 * guarantees that @root doesn't have any children, so turning it
6252 * on for the root memcg is enough.
6253 */
9e10a130 6254 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
7feee590
VD
6255 root_mem_cgroup->use_hierarchy = true;
6256 else
6257 root_mem_cgroup->use_hierarchy = false;
f00baae7
TH
6258}
6259
677dc973
CD
6260static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value)
6261{
6262 if (value == PAGE_COUNTER_MAX)
6263 seq_puts(m, "max\n");
6264 else
6265 seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE);
6266
6267 return 0;
6268}
6269
241994ed
JW
6270static u64 memory_current_read(struct cgroup_subsys_state *css,
6271 struct cftype *cft)
6272{
f5fc3c5d
JW
6273 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6274
6275 return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
241994ed
JW
6276}
6277
bf8d5d52
RG
6278static int memory_min_show(struct seq_file *m, void *v)
6279{
677dc973
CD
6280 return seq_puts_memcg_tunable(m,
6281 READ_ONCE(mem_cgroup_from_seq(m)->memory.min));
bf8d5d52
RG
6282}
6283
6284static ssize_t memory_min_write(struct kernfs_open_file *of,
6285 char *buf, size_t nbytes, loff_t off)
6286{
6287 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6288 unsigned long min;
6289 int err;
6290
6291 buf = strstrip(buf);
6292 err = page_counter_memparse(buf, "max", &min);
6293 if (err)
6294 return err;
6295
6296 page_counter_set_min(&memcg->memory, min);
6297
6298 return nbytes;
6299}
6300
241994ed
JW
6301static int memory_low_show(struct seq_file *m, void *v)
6302{
677dc973
CD
6303 return seq_puts_memcg_tunable(m,
6304 READ_ONCE(mem_cgroup_from_seq(m)->memory.low));
241994ed
JW
6305}
6306
6307static ssize_t memory_low_write(struct kernfs_open_file *of,
6308 char *buf, size_t nbytes, loff_t off)
6309{
6310 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6311 unsigned long low;
6312 int err;
6313
6314 buf = strstrip(buf);
d2973697 6315 err = page_counter_memparse(buf, "max", &low);
241994ed
JW
6316 if (err)
6317 return err;
6318
23067153 6319 page_counter_set_low(&memcg->memory, low);
241994ed
JW
6320
6321 return nbytes;
6322}
6323
6324static int memory_high_show(struct seq_file *m, void *v)
6325{
d1663a90
JK
6326 return seq_puts_memcg_tunable(m,
6327 READ_ONCE(mem_cgroup_from_seq(m)->memory.high));
241994ed
JW
6328}
6329
6330static ssize_t memory_high_write(struct kernfs_open_file *of,
6331 char *buf, size_t nbytes, loff_t off)
6332{
6333 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
8c8c383c
JW
6334 unsigned int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
6335 bool drained = false;
241994ed
JW
6336 unsigned long high;
6337 int err;
6338
6339 buf = strstrip(buf);
d2973697 6340 err = page_counter_memparse(buf, "max", &high);
241994ed
JW
6341 if (err)
6342 return err;
6343
d1663a90 6344 page_counter_set_high(&memcg->memory, high);
241994ed 6345
8c8c383c
JW
6346 for (;;) {
6347 unsigned long nr_pages = page_counter_read(&memcg->memory);
6348 unsigned long reclaimed;
6349
6350 if (nr_pages <= high)
6351 break;
6352
6353 if (signal_pending(current))
6354 break;
6355
6356 if (!drained) {
6357 drain_all_stock(memcg);
6358 drained = true;
6359 continue;
6360 }
6361
6362 reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages - high,
6363 GFP_KERNEL, true);
6364
6365 if (!reclaimed && !nr_retries--)
6366 break;
6367 }
588083bb 6368
241994ed
JW
6369 return nbytes;
6370}
6371
6372static int memory_max_show(struct seq_file *m, void *v)
6373{
677dc973
CD
6374 return seq_puts_memcg_tunable(m,
6375 READ_ONCE(mem_cgroup_from_seq(m)->memory.max));
241994ed
JW
6376}
6377
6378static ssize_t memory_max_write(struct kernfs_open_file *of,
6379 char *buf, size_t nbytes, loff_t off)
6380{
6381 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
b6e6edcf
JW
6382 unsigned int nr_reclaims = MEM_CGROUP_RECLAIM_RETRIES;
6383 bool drained = false;
241994ed
JW
6384 unsigned long max;
6385 int err;
6386
6387 buf = strstrip(buf);
d2973697 6388 err = page_counter_memparse(buf, "max", &max);
241994ed
JW
6389 if (err)
6390 return err;
6391
bbec2e15 6392 xchg(&memcg->memory.max, max);
b6e6edcf
JW
6393
6394 for (;;) {
6395 unsigned long nr_pages = page_counter_read(&memcg->memory);
6396
6397 if (nr_pages <= max)
6398 break;
6399
7249c9f0 6400 if (signal_pending(current))
b6e6edcf 6401 break;
b6e6edcf
JW
6402
6403 if (!drained) {
6404 drain_all_stock(memcg);
6405 drained = true;
6406 continue;
6407 }
6408
6409 if (nr_reclaims) {
6410 if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,
6411 GFP_KERNEL, true))
6412 nr_reclaims--;
6413 continue;
6414 }
6415
e27be240 6416 memcg_memory_event(memcg, MEMCG_OOM);
b6e6edcf
JW
6417 if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0))
6418 break;
6419 }
241994ed 6420
2529bb3a 6421 memcg_wb_domain_size_changed(memcg);
241994ed
JW
6422 return nbytes;
6423}
6424
1e577f97
SB
6425static void __memory_events_show(struct seq_file *m, atomic_long_t *events)
6426{
6427 seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW]));
6428 seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH]));
6429 seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX]));
6430 seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM]));
6431 seq_printf(m, "oom_kill %lu\n",
6432 atomic_long_read(&events[MEMCG_OOM_KILL]));
6433}
6434
241994ed
JW
6435static int memory_events_show(struct seq_file *m, void *v)
6436{
aa9694bb 6437 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
241994ed 6438
1e577f97
SB
6439 __memory_events_show(m, memcg->memory_events);
6440 return 0;
6441}
6442
6443static int memory_events_local_show(struct seq_file *m, void *v)
6444{
6445 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
241994ed 6446
1e577f97 6447 __memory_events_show(m, memcg->memory_events_local);
241994ed
JW
6448 return 0;
6449}
6450
587d9f72
JW
6451static int memory_stat_show(struct seq_file *m, void *v)
6452{
aa9694bb 6453 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
c8713d0b 6454 char *buf;
1ff9e6e1 6455
c8713d0b
JW
6456 buf = memory_stat_format(memcg);
6457 if (!buf)
6458 return -ENOMEM;
6459 seq_puts(m, buf);
6460 kfree(buf);
587d9f72
JW
6461 return 0;
6462}
6463
3d8b38eb
RG
6464static int memory_oom_group_show(struct seq_file *m, void *v)
6465{
aa9694bb 6466 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
3d8b38eb
RG
6467
6468 seq_printf(m, "%d\n", memcg->oom_group);
6469
6470 return 0;
6471}
6472
6473static ssize_t memory_oom_group_write(struct kernfs_open_file *of,
6474 char *buf, size_t nbytes, loff_t off)
6475{
6476 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6477 int ret, oom_group;
6478
6479 buf = strstrip(buf);
6480 if (!buf)
6481 return -EINVAL;
6482
6483 ret = kstrtoint(buf, 0, &oom_group);
6484 if (ret)
6485 return ret;
6486
6487 if (oom_group != 0 && oom_group != 1)
6488 return -EINVAL;
6489
6490 memcg->oom_group = oom_group;
6491
6492 return nbytes;
6493}
6494
241994ed
JW
6495static struct cftype memory_files[] = {
6496 {
6497 .name = "current",
f5fc3c5d 6498 .flags = CFTYPE_NOT_ON_ROOT,
241994ed
JW
6499 .read_u64 = memory_current_read,
6500 },
bf8d5d52
RG
6501 {
6502 .name = "min",
6503 .flags = CFTYPE_NOT_ON_ROOT,
6504 .seq_show = memory_min_show,
6505 .write = memory_min_write,
6506 },
241994ed
JW
6507 {
6508 .name = "low",
6509 .flags = CFTYPE_NOT_ON_ROOT,
6510 .seq_show = memory_low_show,
6511 .write = memory_low_write,
6512 },
6513 {
6514 .name = "high",
6515 .flags = CFTYPE_NOT_ON_ROOT,
6516 .seq_show = memory_high_show,
6517 .write = memory_high_write,
6518 },
6519 {
6520 .name = "max",
6521 .flags = CFTYPE_NOT_ON_ROOT,
6522 .seq_show = memory_max_show,
6523 .write = memory_max_write,
6524 },
6525 {
6526 .name = "events",
6527 .flags = CFTYPE_NOT_ON_ROOT,
472912a2 6528 .file_offset = offsetof(struct mem_cgroup, events_file),
241994ed
JW
6529 .seq_show = memory_events_show,
6530 },
1e577f97
SB
6531 {
6532 .name = "events.local",
6533 .flags = CFTYPE_NOT_ON_ROOT,
6534 .file_offset = offsetof(struct mem_cgroup, events_local_file),
6535 .seq_show = memory_events_local_show,
6536 },
587d9f72
JW
6537 {
6538 .name = "stat",
587d9f72
JW
6539 .seq_show = memory_stat_show,
6540 },
3d8b38eb
RG
6541 {
6542 .name = "oom.group",
6543 .flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE,
6544 .seq_show = memory_oom_group_show,
6545 .write = memory_oom_group_write,
6546 },
241994ed
JW
6547 { } /* terminate */
6548};
6549
073219e9 6550struct cgroup_subsys memory_cgrp_subsys = {
92fb9748 6551 .css_alloc = mem_cgroup_css_alloc,
d142e3e6 6552 .css_online = mem_cgroup_css_online,
92fb9748 6553 .css_offline = mem_cgroup_css_offline,
6df38689 6554 .css_released = mem_cgroup_css_released,
92fb9748 6555 .css_free = mem_cgroup_css_free,
1ced953b 6556 .css_reset = mem_cgroup_css_reset,
7dc74be0
DN
6557 .can_attach = mem_cgroup_can_attach,
6558 .cancel_attach = mem_cgroup_cancel_attach,
264a0ae1 6559 .post_attach = mem_cgroup_move_task,
f00baae7 6560 .bind = mem_cgroup_bind,
241994ed
JW
6561 .dfl_cftypes = memory_files,
6562 .legacy_cftypes = mem_cgroup_legacy_files,
6d12e2d8 6563 .early_init = 0,
8cdea7c0 6564};
c077719b 6565
bc50bcc6
JW
6566/*
6567 * This function calculates an individual cgroup's effective
6568 * protection which is derived from its own memory.min/low, its
6569 * parent's and siblings' settings, as well as the actual memory
6570 * distribution in the tree.
6571 *
6572 * The following rules apply to the effective protection values:
6573 *
6574 * 1. At the first level of reclaim, effective protection is equal to
6575 * the declared protection in memory.min and memory.low.
6576 *
6577 * 2. To enable safe delegation of the protection configuration, at
6578 * subsequent levels the effective protection is capped to the
6579 * parent's effective protection.
6580 *
6581 * 3. To make complex and dynamic subtrees easier to configure, the
6582 * user is allowed to overcommit the declared protection at a given
6583 * level. If that is the case, the parent's effective protection is
6584 * distributed to the children in proportion to how much protection
6585 * they have declared and how much of it they are utilizing.
6586 *
6587 * This makes distribution proportional, but also work-conserving:
6588 * if one cgroup claims much more protection than it uses memory,
6589 * the unused remainder is available to its siblings.
6590 *
6591 * 4. Conversely, when the declared protection is undercommitted at a
6592 * given level, the distribution of the larger parental protection
6593 * budget is NOT proportional. A cgroup's protection from a sibling
6594 * is capped to its own memory.min/low setting.
6595 *
8a931f80
JW
6596 * 5. However, to allow protecting recursive subtrees from each other
6597 * without having to declare each individual cgroup's fixed share
6598 * of the ancestor's claim to protection, any unutilized -
6599 * "floating" - protection from up the tree is distributed in
6600 * proportion to each cgroup's *usage*. This makes the protection
6601 * neutral wrt sibling cgroups and lets them compete freely over
6602 * the shared parental protection budget, but it protects the
6603 * subtree as a whole from neighboring subtrees.
6604 *
6605 * Note that 4. and 5. are not in conflict: 4. is about protecting
6606 * against immediate siblings whereas 5. is about protecting against
6607 * neighboring subtrees.
bc50bcc6
JW
6608 */
6609static unsigned long effective_protection(unsigned long usage,
8a931f80 6610 unsigned long parent_usage,
bc50bcc6
JW
6611 unsigned long setting,
6612 unsigned long parent_effective,
6613 unsigned long siblings_protected)
6614{
6615 unsigned long protected;
8a931f80 6616 unsigned long ep;
bc50bcc6
JW
6617
6618 protected = min(usage, setting);
6619 /*
6620 * If all cgroups at this level combined claim and use more
6621 * protection then what the parent affords them, distribute
6622 * shares in proportion to utilization.
6623 *
6624 * We are using actual utilization rather than the statically
6625 * claimed protection in order to be work-conserving: claimed
6626 * but unused protection is available to siblings that would
6627 * otherwise get a smaller chunk than what they claimed.
6628 */
6629 if (siblings_protected > parent_effective)
6630 return protected * parent_effective / siblings_protected;
6631
6632 /*
6633 * Ok, utilized protection of all children is within what the
6634 * parent affords them, so we know whatever this child claims
6635 * and utilizes is effectively protected.
6636 *
6637 * If there is unprotected usage beyond this value, reclaim
6638 * will apply pressure in proportion to that amount.
6639 *
6640 * If there is unutilized protection, the cgroup will be fully
6641 * shielded from reclaim, but we do return a smaller value for
6642 * protection than what the group could enjoy in theory. This
6643 * is okay. With the overcommit distribution above, effective
6644 * protection is always dependent on how memory is actually
6645 * consumed among the siblings anyway.
6646 */
8a931f80
JW
6647 ep = protected;
6648
6649 /*
6650 * If the children aren't claiming (all of) the protection
6651 * afforded to them by the parent, distribute the remainder in
6652 * proportion to the (unprotected) memory of each cgroup. That
6653 * way, cgroups that aren't explicitly prioritized wrt each
6654 * other compete freely over the allowance, but they are
6655 * collectively protected from neighboring trees.
6656 *
6657 * We're using unprotected memory for the weight so that if
6658 * some cgroups DO claim explicit protection, we don't protect
6659 * the same bytes twice.
cd324edc
JW
6660 *
6661 * Check both usage and parent_usage against the respective
6662 * protected values. One should imply the other, but they
6663 * aren't read atomically - make sure the division is sane.
8a931f80
JW
6664 */
6665 if (!(cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT))
6666 return ep;
cd324edc
JW
6667 if (parent_effective > siblings_protected &&
6668 parent_usage > siblings_protected &&
6669 usage > protected) {
8a931f80
JW
6670 unsigned long unclaimed;
6671
6672 unclaimed = parent_effective - siblings_protected;
6673 unclaimed *= usage - protected;
6674 unclaimed /= parent_usage - siblings_protected;
6675
6676 ep += unclaimed;
6677 }
6678
6679 return ep;
bc50bcc6
JW
6680}
6681
241994ed 6682/**
bf8d5d52 6683 * mem_cgroup_protected - check if memory consumption is in the normal range
34c81057 6684 * @root: the top ancestor of the sub-tree being checked
241994ed
JW
6685 * @memcg: the memory cgroup to check
6686 *
23067153
RG
6687 * WARNING: This function is not stateless! It can only be used as part
6688 * of a top-down tree iteration, not for isolated queries.
34c81057 6689 *
bf8d5d52
RG
6690 * Returns one of the following:
6691 * MEMCG_PROT_NONE: cgroup memory is not protected
6692 * MEMCG_PROT_LOW: cgroup memory is protected as long there is
6693 * an unprotected supply of reclaimable memory from other cgroups.
6694 * MEMCG_PROT_MIN: cgroup memory is protected
241994ed 6695 */
bf8d5d52
RG
6696enum mem_cgroup_protection mem_cgroup_protected(struct mem_cgroup *root,
6697 struct mem_cgroup *memcg)
241994ed 6698{
8a931f80 6699 unsigned long usage, parent_usage;
23067153
RG
6700 struct mem_cgroup *parent;
6701
241994ed 6702 if (mem_cgroup_disabled())
bf8d5d52 6703 return MEMCG_PROT_NONE;
241994ed 6704
34c81057
SC
6705 if (!root)
6706 root = root_mem_cgroup;
6707 if (memcg == root)
bf8d5d52 6708 return MEMCG_PROT_NONE;
241994ed 6709
23067153 6710 usage = page_counter_read(&memcg->memory);
bf8d5d52
RG
6711 if (!usage)
6712 return MEMCG_PROT_NONE;
6713
bf8d5d52 6714 parent = parent_mem_cgroup(memcg);
df2a4196
RG
6715 /* No parent means a non-hierarchical mode on v1 memcg */
6716 if (!parent)
6717 return MEMCG_PROT_NONE;
6718
bc50bcc6 6719 if (parent == root) {
c3d53200 6720 memcg->memory.emin = READ_ONCE(memcg->memory.min);
03960e33 6721 memcg->memory.elow = READ_ONCE(memcg->memory.low);
bc50bcc6 6722 goto out;
bf8d5d52
RG
6723 }
6724
8a931f80
JW
6725 parent_usage = page_counter_read(&parent->memory);
6726
b3a7822e 6727 WRITE_ONCE(memcg->memory.emin, effective_protection(usage, parent_usage,
c3d53200
CD
6728 READ_ONCE(memcg->memory.min),
6729 READ_ONCE(parent->memory.emin),
b3a7822e 6730 atomic_long_read(&parent->memory.children_min_usage)));
23067153 6731
b3a7822e 6732 WRITE_ONCE(memcg->memory.elow, effective_protection(usage, parent_usage,
03960e33
CD
6733 READ_ONCE(memcg->memory.low),
6734 READ_ONCE(parent->memory.elow),
b3a7822e 6735 atomic_long_read(&parent->memory.children_low_usage)));
23067153 6736
bc50bcc6
JW
6737out:
6738 if (usage <= memcg->memory.emin)
bf8d5d52 6739 return MEMCG_PROT_MIN;
bc50bcc6 6740 else if (usage <= memcg->memory.elow)
bf8d5d52
RG
6741 return MEMCG_PROT_LOW;
6742 else
6743 return MEMCG_PROT_NONE;
241994ed
JW
6744}
6745
00501b53 6746/**
f0e45fb4 6747 * mem_cgroup_charge - charge a newly allocated page to a cgroup
00501b53
JW
6748 * @page: page to charge
6749 * @mm: mm context of the victim
6750 * @gfp_mask: reclaim mode
00501b53
JW
6751 *
6752 * Try to charge @page to the memcg that @mm belongs to, reclaiming
6753 * pages according to @gfp_mask if necessary.
6754 *
f0e45fb4 6755 * Returns 0 on success. Otherwise, an error code is returned.
00501b53 6756 */
d9eb1ea2 6757int mem_cgroup_charge(struct page *page, struct mm_struct *mm, gfp_t gfp_mask)
00501b53 6758{
3fba69a5 6759 unsigned int nr_pages = hpage_nr_pages(page);
00501b53 6760 struct mem_cgroup *memcg = NULL;
00501b53
JW
6761 int ret = 0;
6762
6763 if (mem_cgroup_disabled())
6764 goto out;
6765
6766 if (PageSwapCache(page)) {
2d1c4980
JW
6767 swp_entry_t ent = { .val = page_private(page), };
6768 unsigned short id;
6769
00501b53
JW
6770 /*
6771 * Every swap fault against a single page tries to charge the
6772 * page, bail as early as possible. shmem_unuse() encounters
eccb52e7
JW
6773 * already charged pages, too. page->mem_cgroup is protected
6774 * by the page lock, which serializes swap cache removal, which
00501b53
JW
6775 * in turn serializes uncharging.
6776 */
e993d905 6777 VM_BUG_ON_PAGE(!PageLocked(page), page);
abe2895b 6778 if (compound_head(page)->mem_cgroup)
00501b53 6779 goto out;
e993d905 6780
2d1c4980
JW
6781 id = lookup_swap_cgroup_id(ent);
6782 rcu_read_lock();
6783 memcg = mem_cgroup_from_id(id);
6784 if (memcg && !css_tryget_online(&memcg->css))
6785 memcg = NULL;
6786 rcu_read_unlock();
00501b53
JW
6787 }
6788
00501b53
JW
6789 if (!memcg)
6790 memcg = get_mem_cgroup_from_mm(mm);
6791
6792 ret = try_charge(memcg, gfp_mask, nr_pages);
f0e45fb4
JW
6793 if (ret)
6794 goto out_put;
00501b53 6795
1a3e1f40 6796 css_get(&memcg->css);
d9eb1ea2 6797 commit_charge(page, memcg);
6abb5a86 6798
6abb5a86 6799 local_irq_disable();
3fba69a5 6800 mem_cgroup_charge_statistics(memcg, page, nr_pages);
6abb5a86
JW
6801 memcg_check_events(memcg, page);
6802 local_irq_enable();
00501b53 6803
2d1c4980 6804 if (PageSwapCache(page)) {
00501b53
JW
6805 swp_entry_t entry = { .val = page_private(page) };
6806 /*
6807 * The swap entry might not get freed for a long time,
6808 * let's not wait for it. The page already received a
6809 * memory+swap charge, drop the swap entry duplicate.
6810 */
38d8b4e6 6811 mem_cgroup_uncharge_swap(entry, nr_pages);
00501b53 6812 }
00501b53 6813
f0e45fb4
JW
6814out_put:
6815 css_put(&memcg->css);
6816out:
6817 return ret;
3fea5a49
JW
6818}
6819
a9d5adee
JG
6820struct uncharge_gather {
6821 struct mem_cgroup *memcg;
9f762dbe 6822 unsigned long nr_pages;
a9d5adee 6823 unsigned long pgpgout;
a9d5adee 6824 unsigned long nr_kmem;
a9d5adee
JG
6825 struct page *dummy_page;
6826};
6827
6828static inline void uncharge_gather_clear(struct uncharge_gather *ug)
747db954 6829{
a9d5adee
JG
6830 memset(ug, 0, sizeof(*ug));
6831}
6832
6833static void uncharge_batch(const struct uncharge_gather *ug)
6834{
747db954
JW
6835 unsigned long flags;
6836
a9d5adee 6837 if (!mem_cgroup_is_root(ug->memcg)) {
9f762dbe 6838 page_counter_uncharge(&ug->memcg->memory, ug->nr_pages);
7941d214 6839 if (do_memsw_account())
9f762dbe 6840 page_counter_uncharge(&ug->memcg->memsw, ug->nr_pages);
a9d5adee
JG
6841 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && ug->nr_kmem)
6842 page_counter_uncharge(&ug->memcg->kmem, ug->nr_kmem);
6843 memcg_oom_recover(ug->memcg);
ce00a967 6844 }
747db954
JW
6845
6846 local_irq_save(flags);
c9019e9b 6847 __count_memcg_events(ug->memcg, PGPGOUT, ug->pgpgout);
9f762dbe 6848 __this_cpu_add(ug->memcg->vmstats_percpu->nr_page_events, ug->nr_pages);
a9d5adee 6849 memcg_check_events(ug->memcg, ug->dummy_page);
747db954 6850 local_irq_restore(flags);
a9d5adee
JG
6851}
6852
6853static void uncharge_page(struct page *page, struct uncharge_gather *ug)
6854{
9f762dbe
JW
6855 unsigned long nr_pages;
6856
a9d5adee 6857 VM_BUG_ON_PAGE(PageLRU(page), page);
a9d5adee
JG
6858
6859 if (!page->mem_cgroup)
6860 return;
6861
6862 /*
6863 * Nobody should be changing or seriously looking at
6864 * page->mem_cgroup at this point, we have fully
6865 * exclusive access to the page.
6866 */
6867
6868 if (ug->memcg != page->mem_cgroup) {
6869 if (ug->memcg) {
6870 uncharge_batch(ug);
6871 uncharge_gather_clear(ug);
6872 }
6873 ug->memcg = page->mem_cgroup;
6874 }
6875
9f762dbe
JW
6876 nr_pages = compound_nr(page);
6877 ug->nr_pages += nr_pages;
a9d5adee 6878
9f762dbe 6879 if (!PageKmemcg(page)) {
a9d5adee
JG
6880 ug->pgpgout++;
6881 } else {
9f762dbe 6882 ug->nr_kmem += nr_pages;
a9d5adee
JG
6883 __ClearPageKmemcg(page);
6884 }
6885
6886 ug->dummy_page = page;
6887 page->mem_cgroup = NULL;
1a3e1f40 6888 css_put(&ug->memcg->css);
747db954
JW
6889}
6890
6891static void uncharge_list(struct list_head *page_list)
6892{
a9d5adee 6893 struct uncharge_gather ug;
747db954 6894 struct list_head *next;
a9d5adee
JG
6895
6896 uncharge_gather_clear(&ug);
747db954 6897
8b592656
JW
6898 /*
6899 * Note that the list can be a single page->lru; hence the
6900 * do-while loop instead of a simple list_for_each_entry().
6901 */
747db954
JW
6902 next = page_list->next;
6903 do {
a9d5adee
JG
6904 struct page *page;
6905
747db954
JW
6906 page = list_entry(next, struct page, lru);
6907 next = page->lru.next;
6908
a9d5adee 6909 uncharge_page(page, &ug);
747db954
JW
6910 } while (next != page_list);
6911
a9d5adee
JG
6912 if (ug.memcg)
6913 uncharge_batch(&ug);
747db954
JW
6914}
6915
0a31bc97
JW
6916/**
6917 * mem_cgroup_uncharge - uncharge a page
6918 * @page: page to uncharge
6919 *
f0e45fb4 6920 * Uncharge a page previously charged with mem_cgroup_charge().
0a31bc97
JW
6921 */
6922void mem_cgroup_uncharge(struct page *page)
6923{
a9d5adee
JG
6924 struct uncharge_gather ug;
6925
0a31bc97
JW
6926 if (mem_cgroup_disabled())
6927 return;
6928
747db954 6929 /* Don't touch page->lru of any random page, pre-check: */
1306a85a 6930 if (!page->mem_cgroup)
0a31bc97
JW
6931 return;
6932
a9d5adee
JG
6933 uncharge_gather_clear(&ug);
6934 uncharge_page(page, &ug);
6935 uncharge_batch(&ug);
747db954 6936}
0a31bc97 6937
747db954
JW
6938/**
6939 * mem_cgroup_uncharge_list - uncharge a list of page
6940 * @page_list: list of pages to uncharge
6941 *
6942 * Uncharge a list of pages previously charged with
f0e45fb4 6943 * mem_cgroup_charge().
747db954
JW
6944 */
6945void mem_cgroup_uncharge_list(struct list_head *page_list)
6946{
6947 if (mem_cgroup_disabled())
6948 return;
0a31bc97 6949
747db954
JW
6950 if (!list_empty(page_list))
6951 uncharge_list(page_list);
0a31bc97
JW
6952}
6953
6954/**
6a93ca8f
JW
6955 * mem_cgroup_migrate - charge a page's replacement
6956 * @oldpage: currently circulating page
6957 * @newpage: replacement page
0a31bc97 6958 *
6a93ca8f
JW
6959 * Charge @newpage as a replacement page for @oldpage. @oldpage will
6960 * be uncharged upon free.
0a31bc97
JW
6961 *
6962 * Both pages must be locked, @newpage->mapping must be set up.
6963 */
6a93ca8f 6964void mem_cgroup_migrate(struct page *oldpage, struct page *newpage)
0a31bc97 6965{
29833315 6966 struct mem_cgroup *memcg;
44b7a8d3 6967 unsigned int nr_pages;
d93c4130 6968 unsigned long flags;
0a31bc97
JW
6969
6970 VM_BUG_ON_PAGE(!PageLocked(oldpage), oldpage);
6971 VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
0a31bc97 6972 VM_BUG_ON_PAGE(PageAnon(oldpage) != PageAnon(newpage), newpage);
6abb5a86
JW
6973 VM_BUG_ON_PAGE(PageTransHuge(oldpage) != PageTransHuge(newpage),
6974 newpage);
0a31bc97
JW
6975
6976 if (mem_cgroup_disabled())
6977 return;
6978
6979 /* Page cache replacement: new page already charged? */
1306a85a 6980 if (newpage->mem_cgroup)
0a31bc97
JW
6981 return;
6982
45637bab 6983 /* Swapcache readahead pages can get replaced before being charged */
1306a85a 6984 memcg = oldpage->mem_cgroup;
29833315 6985 if (!memcg)
0a31bc97
JW
6986 return;
6987
44b7a8d3 6988 /* Force-charge the new page. The old one will be freed soon */
92855270 6989 nr_pages = hpage_nr_pages(newpage);
44b7a8d3
JW
6990
6991 page_counter_charge(&memcg->memory, nr_pages);
6992 if (do_memsw_account())
6993 page_counter_charge(&memcg->memsw, nr_pages);
0a31bc97 6994
1a3e1f40 6995 css_get(&memcg->css);
d9eb1ea2 6996 commit_charge(newpage, memcg);
44b7a8d3 6997
d93c4130 6998 local_irq_save(flags);
3fba69a5 6999 mem_cgroup_charge_statistics(memcg, newpage, nr_pages);
44b7a8d3 7000 memcg_check_events(memcg, newpage);
d93c4130 7001 local_irq_restore(flags);
0a31bc97
JW
7002}
7003
ef12947c 7004DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key);
11092087
JW
7005EXPORT_SYMBOL(memcg_sockets_enabled_key);
7006
2d758073 7007void mem_cgroup_sk_alloc(struct sock *sk)
11092087
JW
7008{
7009 struct mem_cgroup *memcg;
7010
2d758073
JW
7011 if (!mem_cgroup_sockets_enabled)
7012 return;
7013
e876ecc6
SB
7014 /* Do not associate the sock with unrelated interrupted task's memcg. */
7015 if (in_interrupt())
7016 return;
7017
11092087
JW
7018 rcu_read_lock();
7019 memcg = mem_cgroup_from_task(current);
f7e1cb6e
JW
7020 if (memcg == root_mem_cgroup)
7021 goto out;
0db15298 7022 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg->tcpmem_active)
f7e1cb6e 7023 goto out;
8965aa28 7024 if (css_tryget(&memcg->css))
11092087 7025 sk->sk_memcg = memcg;
f7e1cb6e 7026out:
11092087
JW
7027 rcu_read_unlock();
7028}
11092087 7029
2d758073 7030void mem_cgroup_sk_free(struct sock *sk)
11092087 7031{
2d758073
JW
7032 if (sk->sk_memcg)
7033 css_put(&sk->sk_memcg->css);
11092087
JW
7034}
7035
7036/**
7037 * mem_cgroup_charge_skmem - charge socket memory
7038 * @memcg: memcg to charge
7039 * @nr_pages: number of pages to charge
7040 *
7041 * Charges @nr_pages to @memcg. Returns %true if the charge fit within
7042 * @memcg's configured limit, %false if the charge had to be forced.
7043 */
7044bool mem_cgroup_charge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
7045{
f7e1cb6e 7046 gfp_t gfp_mask = GFP_KERNEL;
11092087 7047
f7e1cb6e 7048 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
0db15298 7049 struct page_counter *fail;
f7e1cb6e 7050
0db15298
JW
7051 if (page_counter_try_charge(&memcg->tcpmem, nr_pages, &fail)) {
7052 memcg->tcpmem_pressure = 0;
f7e1cb6e
JW
7053 return true;
7054 }
0db15298
JW
7055 page_counter_charge(&memcg->tcpmem, nr_pages);
7056 memcg->tcpmem_pressure = 1;
f7e1cb6e 7057 return false;
11092087 7058 }
d886f4e4 7059
f7e1cb6e
JW
7060 /* Don't block in the packet receive path */
7061 if (in_softirq())
7062 gfp_mask = GFP_NOWAIT;
7063
c9019e9b 7064 mod_memcg_state(memcg, MEMCG_SOCK, nr_pages);
b2807f07 7065
f7e1cb6e
JW
7066 if (try_charge(memcg, gfp_mask, nr_pages) == 0)
7067 return true;
7068
7069 try_charge(memcg, gfp_mask|__GFP_NOFAIL, nr_pages);
11092087
JW
7070 return false;
7071}
7072
7073/**
7074 * mem_cgroup_uncharge_skmem - uncharge socket memory
b7701a5f
MR
7075 * @memcg: memcg to uncharge
7076 * @nr_pages: number of pages to uncharge
11092087
JW
7077 */
7078void mem_cgroup_uncharge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
7079{
f7e1cb6e 7080 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
0db15298 7081 page_counter_uncharge(&memcg->tcpmem, nr_pages);
f7e1cb6e
JW
7082 return;
7083 }
d886f4e4 7084
c9019e9b 7085 mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages);
b2807f07 7086
475d0487 7087 refill_stock(memcg, nr_pages);
11092087
JW
7088}
7089
f7e1cb6e
JW
7090static int __init cgroup_memory(char *s)
7091{
7092 char *token;
7093
7094 while ((token = strsep(&s, ",")) != NULL) {
7095 if (!*token)
7096 continue;
7097 if (!strcmp(token, "nosocket"))
7098 cgroup_memory_nosocket = true;
04823c83
VD
7099 if (!strcmp(token, "nokmem"))
7100 cgroup_memory_nokmem = true;
f7e1cb6e
JW
7101 }
7102 return 0;
7103}
7104__setup("cgroup.memory=", cgroup_memory);
11092087 7105
2d11085e 7106/*
1081312f
MH
7107 * subsys_initcall() for memory controller.
7108 *
308167fc
SAS
7109 * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this
7110 * context because of lock dependencies (cgroup_lock -> cpu hotplug) but
7111 * basically everything that doesn't depend on a specific mem_cgroup structure
7112 * should be initialized from here.
2d11085e
MH
7113 */
7114static int __init mem_cgroup_init(void)
7115{
95a045f6
JW
7116 int cpu, node;
7117
84c07d11 7118#ifdef CONFIG_MEMCG_KMEM
13583c3d
VD
7119 /*
7120 * Kmem cache creation is mostly done with the slab_mutex held,
17cc4dfe
TH
7121 * so use a workqueue with limited concurrency to avoid stalling
7122 * all worker threads in case lots of cgroups are created and
7123 * destroyed simultaneously.
13583c3d 7124 */
17cc4dfe
TH
7125 memcg_kmem_cache_wq = alloc_workqueue("memcg_kmem_cache", 0, 1);
7126 BUG_ON(!memcg_kmem_cache_wq);
13583c3d
VD
7127#endif
7128
308167fc
SAS
7129 cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL,
7130 memcg_hotplug_cpu_dead);
95a045f6
JW
7131
7132 for_each_possible_cpu(cpu)
7133 INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
7134 drain_local_stock);
7135
7136 for_each_node(node) {
7137 struct mem_cgroup_tree_per_node *rtpn;
95a045f6
JW
7138
7139 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL,
7140 node_online(node) ? node : NUMA_NO_NODE);
7141
ef8f2327 7142 rtpn->rb_root = RB_ROOT;
fa90b2fd 7143 rtpn->rb_rightmost = NULL;
ef8f2327 7144 spin_lock_init(&rtpn->lock);
95a045f6
JW
7145 soft_limit_tree.rb_tree_per_node[node] = rtpn;
7146 }
7147
2d11085e
MH
7148 return 0;
7149}
7150subsys_initcall(mem_cgroup_init);
21afa38e
JW
7151
7152#ifdef CONFIG_MEMCG_SWAP
358c07fc
AB
7153static struct mem_cgroup *mem_cgroup_id_get_online(struct mem_cgroup *memcg)
7154{
1c2d479a 7155 while (!refcount_inc_not_zero(&memcg->id.ref)) {
358c07fc
AB
7156 /*
7157 * The root cgroup cannot be destroyed, so it's refcount must
7158 * always be >= 1.
7159 */
7160 if (WARN_ON_ONCE(memcg == root_mem_cgroup)) {
7161 VM_BUG_ON(1);
7162 break;
7163 }
7164 memcg = parent_mem_cgroup(memcg);
7165 if (!memcg)
7166 memcg = root_mem_cgroup;
7167 }
7168 return memcg;
7169}
7170
21afa38e
JW
7171/**
7172 * mem_cgroup_swapout - transfer a memsw charge to swap
7173 * @page: page whose memsw charge to transfer
7174 * @entry: swap entry to move the charge to
7175 *
7176 * Transfer the memsw charge of @page to @entry.
7177 */
7178void mem_cgroup_swapout(struct page *page, swp_entry_t entry)
7179{
1f47b61f 7180 struct mem_cgroup *memcg, *swap_memcg;
d6810d73 7181 unsigned int nr_entries;
21afa38e
JW
7182 unsigned short oldid;
7183
7184 VM_BUG_ON_PAGE(PageLRU(page), page);
7185 VM_BUG_ON_PAGE(page_count(page), page);
7186
2d1c4980 7187 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
21afa38e
JW
7188 return;
7189
7190 memcg = page->mem_cgroup;
7191
7192 /* Readahead page, never charged */
7193 if (!memcg)
7194 return;
7195
1f47b61f
VD
7196 /*
7197 * In case the memcg owning these pages has been offlined and doesn't
7198 * have an ID allocated to it anymore, charge the closest online
7199 * ancestor for the swap instead and transfer the memory+swap charge.
7200 */
7201 swap_memcg = mem_cgroup_id_get_online(memcg);
d6810d73
HY
7202 nr_entries = hpage_nr_pages(page);
7203 /* Get references for the tail pages, too */
7204 if (nr_entries > 1)
7205 mem_cgroup_id_get_many(swap_memcg, nr_entries - 1);
7206 oldid = swap_cgroup_record(entry, mem_cgroup_id(swap_memcg),
7207 nr_entries);
21afa38e 7208 VM_BUG_ON_PAGE(oldid, page);
c9019e9b 7209 mod_memcg_state(swap_memcg, MEMCG_SWAP, nr_entries);
21afa38e
JW
7210
7211 page->mem_cgroup = NULL;
7212
7213 if (!mem_cgroup_is_root(memcg))
d6810d73 7214 page_counter_uncharge(&memcg->memory, nr_entries);
21afa38e 7215
2d1c4980 7216 if (!cgroup_memory_noswap && memcg != swap_memcg) {
1f47b61f 7217 if (!mem_cgroup_is_root(swap_memcg))
d6810d73
HY
7218 page_counter_charge(&swap_memcg->memsw, nr_entries);
7219 page_counter_uncharge(&memcg->memsw, nr_entries);
1f47b61f
VD
7220 }
7221
ce9ce665
SAS
7222 /*
7223 * Interrupts should be disabled here because the caller holds the
b93b0163 7224 * i_pages lock which is taken with interrupts-off. It is
ce9ce665 7225 * important here to have the interrupts disabled because it is the
b93b0163 7226 * only synchronisation we have for updating the per-CPU variables.
ce9ce665
SAS
7227 */
7228 VM_BUG_ON(!irqs_disabled());
3fba69a5 7229 mem_cgroup_charge_statistics(memcg, page, -nr_entries);
21afa38e 7230 memcg_check_events(memcg, page);
73f576c0 7231
1a3e1f40 7232 css_put(&memcg->css);
21afa38e
JW
7233}
7234
38d8b4e6
HY
7235/**
7236 * mem_cgroup_try_charge_swap - try charging swap space for a page
37e84351
VD
7237 * @page: page being added to swap
7238 * @entry: swap entry to charge
7239 *
38d8b4e6 7240 * Try to charge @page's memcg for the swap space at @entry.
37e84351
VD
7241 *
7242 * Returns 0 on success, -ENOMEM on failure.
7243 */
7244int mem_cgroup_try_charge_swap(struct page *page, swp_entry_t entry)
7245{
38d8b4e6 7246 unsigned int nr_pages = hpage_nr_pages(page);
37e84351 7247 struct page_counter *counter;
38d8b4e6 7248 struct mem_cgroup *memcg;
37e84351
VD
7249 unsigned short oldid;
7250
2d1c4980 7251 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
37e84351
VD
7252 return 0;
7253
7254 memcg = page->mem_cgroup;
7255
7256 /* Readahead page, never charged */
7257 if (!memcg)
7258 return 0;
7259
f3a53a3a
TH
7260 if (!entry.val) {
7261 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
bb98f2c5 7262 return 0;
f3a53a3a 7263 }
bb98f2c5 7264
1f47b61f
VD
7265 memcg = mem_cgroup_id_get_online(memcg);
7266
2d1c4980 7267 if (!cgroup_memory_noswap && !mem_cgroup_is_root(memcg) &&
38d8b4e6 7268 !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
f3a53a3a
TH
7269 memcg_memory_event(memcg, MEMCG_SWAP_MAX);
7270 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
1f47b61f 7271 mem_cgroup_id_put(memcg);
37e84351 7272 return -ENOMEM;
1f47b61f 7273 }
37e84351 7274
38d8b4e6
HY
7275 /* Get references for the tail pages, too */
7276 if (nr_pages > 1)
7277 mem_cgroup_id_get_many(memcg, nr_pages - 1);
7278 oldid = swap_cgroup_record(entry, mem_cgroup_id(memcg), nr_pages);
37e84351 7279 VM_BUG_ON_PAGE(oldid, page);
c9019e9b 7280 mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
37e84351 7281
37e84351
VD
7282 return 0;
7283}
7284
21afa38e 7285/**
38d8b4e6 7286 * mem_cgroup_uncharge_swap - uncharge swap space
21afa38e 7287 * @entry: swap entry to uncharge
38d8b4e6 7288 * @nr_pages: the amount of swap space to uncharge
21afa38e 7289 */
38d8b4e6 7290void mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages)
21afa38e
JW
7291{
7292 struct mem_cgroup *memcg;
7293 unsigned short id;
7294
38d8b4e6 7295 id = swap_cgroup_record(entry, 0, nr_pages);
21afa38e 7296 rcu_read_lock();
adbe427b 7297 memcg = mem_cgroup_from_id(id);
21afa38e 7298 if (memcg) {
2d1c4980 7299 if (!cgroup_memory_noswap && !mem_cgroup_is_root(memcg)) {
37e84351 7300 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
38d8b4e6 7301 page_counter_uncharge(&memcg->swap, nr_pages);
37e84351 7302 else
38d8b4e6 7303 page_counter_uncharge(&memcg->memsw, nr_pages);
37e84351 7304 }
c9019e9b 7305 mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
38d8b4e6 7306 mem_cgroup_id_put_many(memcg, nr_pages);
21afa38e
JW
7307 }
7308 rcu_read_unlock();
7309}
7310
d8b38438
VD
7311long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg)
7312{
7313 long nr_swap_pages = get_nr_swap_pages();
7314
eccb52e7 7315 if (cgroup_memory_noswap || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
d8b38438
VD
7316 return nr_swap_pages;
7317 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg))
7318 nr_swap_pages = min_t(long, nr_swap_pages,
bbec2e15 7319 READ_ONCE(memcg->swap.max) -
d8b38438
VD
7320 page_counter_read(&memcg->swap));
7321 return nr_swap_pages;
7322}
7323
5ccc5aba
VD
7324bool mem_cgroup_swap_full(struct page *page)
7325{
7326 struct mem_cgroup *memcg;
7327
7328 VM_BUG_ON_PAGE(!PageLocked(page), page);
7329
7330 if (vm_swap_full())
7331 return true;
eccb52e7 7332 if (cgroup_memory_noswap || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
5ccc5aba
VD
7333 return false;
7334
7335 memcg = page->mem_cgroup;
7336 if (!memcg)
7337 return false;
7338
4b82ab4f
JK
7339 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg)) {
7340 unsigned long usage = page_counter_read(&memcg->swap);
7341
7342 if (usage * 2 >= READ_ONCE(memcg->swap.high) ||
7343 usage * 2 >= READ_ONCE(memcg->swap.max))
5ccc5aba 7344 return true;
4b82ab4f 7345 }
5ccc5aba
VD
7346
7347 return false;
7348}
7349
eccb52e7 7350static int __init setup_swap_account(char *s)
21afa38e
JW
7351{
7352 if (!strcmp(s, "1"))
eccb52e7 7353 cgroup_memory_noswap = 0;
21afa38e 7354 else if (!strcmp(s, "0"))
eccb52e7 7355 cgroup_memory_noswap = 1;
21afa38e
JW
7356 return 1;
7357}
eccb52e7 7358__setup("swapaccount=", setup_swap_account);
21afa38e 7359
37e84351
VD
7360static u64 swap_current_read(struct cgroup_subsys_state *css,
7361 struct cftype *cft)
7362{
7363 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
7364
7365 return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE;
7366}
7367
4b82ab4f
JK
7368static int swap_high_show(struct seq_file *m, void *v)
7369{
7370 return seq_puts_memcg_tunable(m,
7371 READ_ONCE(mem_cgroup_from_seq(m)->swap.high));
7372}
7373
7374static ssize_t swap_high_write(struct kernfs_open_file *of,
7375 char *buf, size_t nbytes, loff_t off)
7376{
7377 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7378 unsigned long high;
7379 int err;
7380
7381 buf = strstrip(buf);
7382 err = page_counter_memparse(buf, "max", &high);
7383 if (err)
7384 return err;
7385
7386 page_counter_set_high(&memcg->swap, high);
7387
7388 return nbytes;
7389}
7390
37e84351
VD
7391static int swap_max_show(struct seq_file *m, void *v)
7392{
677dc973
CD
7393 return seq_puts_memcg_tunable(m,
7394 READ_ONCE(mem_cgroup_from_seq(m)->swap.max));
37e84351
VD
7395}
7396
7397static ssize_t swap_max_write(struct kernfs_open_file *of,
7398 char *buf, size_t nbytes, loff_t off)
7399{
7400 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7401 unsigned long max;
7402 int err;
7403
7404 buf = strstrip(buf);
7405 err = page_counter_memparse(buf, "max", &max);
7406 if (err)
7407 return err;
7408
be09102b 7409 xchg(&memcg->swap.max, max);
37e84351
VD
7410
7411 return nbytes;
7412}
7413
f3a53a3a
TH
7414static int swap_events_show(struct seq_file *m, void *v)
7415{
aa9694bb 7416 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
f3a53a3a 7417
4b82ab4f
JK
7418 seq_printf(m, "high %lu\n",
7419 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_HIGH]));
f3a53a3a
TH
7420 seq_printf(m, "max %lu\n",
7421 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
7422 seq_printf(m, "fail %lu\n",
7423 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL]));
7424
7425 return 0;
7426}
7427
37e84351
VD
7428static struct cftype swap_files[] = {
7429 {
7430 .name = "swap.current",
7431 .flags = CFTYPE_NOT_ON_ROOT,
7432 .read_u64 = swap_current_read,
7433 },
4b82ab4f
JK
7434 {
7435 .name = "swap.high",
7436 .flags = CFTYPE_NOT_ON_ROOT,
7437 .seq_show = swap_high_show,
7438 .write = swap_high_write,
7439 },
37e84351
VD
7440 {
7441 .name = "swap.max",
7442 .flags = CFTYPE_NOT_ON_ROOT,
7443 .seq_show = swap_max_show,
7444 .write = swap_max_write,
7445 },
f3a53a3a
TH
7446 {
7447 .name = "swap.events",
7448 .flags = CFTYPE_NOT_ON_ROOT,
7449 .file_offset = offsetof(struct mem_cgroup, swap_events_file),
7450 .seq_show = swap_events_show,
7451 },
37e84351
VD
7452 { } /* terminate */
7453};
7454
eccb52e7 7455static struct cftype memsw_files[] = {
21afa38e
JW
7456 {
7457 .name = "memsw.usage_in_bytes",
7458 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
7459 .read_u64 = mem_cgroup_read_u64,
7460 },
7461 {
7462 .name = "memsw.max_usage_in_bytes",
7463 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
7464 .write = mem_cgroup_reset,
7465 .read_u64 = mem_cgroup_read_u64,
7466 },
7467 {
7468 .name = "memsw.limit_in_bytes",
7469 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
7470 .write = mem_cgroup_write,
7471 .read_u64 = mem_cgroup_read_u64,
7472 },
7473 {
7474 .name = "memsw.failcnt",
7475 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
7476 .write = mem_cgroup_reset,
7477 .read_u64 = mem_cgroup_read_u64,
7478 },
7479 { }, /* terminate */
7480};
7481
82ff165c
BS
7482/*
7483 * If mem_cgroup_swap_init() is implemented as a subsys_initcall()
7484 * instead of a core_initcall(), this could mean cgroup_memory_noswap still
7485 * remains set to false even when memcg is disabled via "cgroup_disable=memory"
7486 * boot parameter. This may result in premature OOPS inside
7487 * mem_cgroup_get_nr_swap_pages() function in corner cases.
7488 */
21afa38e
JW
7489static int __init mem_cgroup_swap_init(void)
7490{
2d1c4980
JW
7491 /* No memory control -> no swap control */
7492 if (mem_cgroup_disabled())
7493 cgroup_memory_noswap = true;
7494
7495 if (cgroup_memory_noswap)
eccb52e7
JW
7496 return 0;
7497
7498 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, swap_files));
7499 WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys, memsw_files));
7500
21afa38e
JW
7501 return 0;
7502}
82ff165c 7503core_initcall(mem_cgroup_swap_init);
21afa38e
JW
7504
7505#endif /* CONFIG_MEMCG_SWAP */