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