• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 
3 #include <linux/memcontrol.h>
4 #include <linux/swap.h>
5 #include <linux/mm_inline.h>
6 #include <linux/pagewalk.h>
7 #include <linux/backing-dev.h>
8 #include <linux/swap_cgroup.h>
9 #include <linux/eventfd.h>
10 #include <linux/poll.h>
11 #include <linux/sort.h>
12 #include <linux/file.h>
13 #include <linux/seq_buf.h>
14 
15 #include "internal.h"
16 #include "swap.h"
17 #include "memcontrol-v1.h"
18 
19 /*
20  * Cgroups above their limits are maintained in a RB-Tree, independent of
21  * their hierarchy representation
22  */
23 
24 struct mem_cgroup_tree_per_node {
25 	struct rb_root rb_root;
26 	struct rb_node *rb_rightmost;
27 	spinlock_t lock;
28 };
29 
30 struct mem_cgroup_tree {
31 	struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
32 };
33 
34 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
35 
36 /*
37  * Maximum loops in mem_cgroup_soft_reclaim(), used for soft
38  * limit reclaim to prevent infinite loops, if they ever occur.
39  */
40 #define	MEM_CGROUP_MAX_RECLAIM_LOOPS		100
41 #define	MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS	2
42 
43 /* Stuffs for move charges at task migration. */
44 /*
45  * Types of charges to be moved.
46  */
47 #define MOVE_ANON	0x1ULL
48 #define MOVE_FILE	0x2ULL
49 #define MOVE_MASK	(MOVE_ANON | MOVE_FILE)
50 
51 /* "mc" and its members are protected by cgroup_mutex */
52 static struct move_charge_struct {
53 	spinlock_t	  lock; /* for from, to */
54 	struct mm_struct  *mm;
55 	struct mem_cgroup *from;
56 	struct mem_cgroup *to;
57 	unsigned long flags;
58 	unsigned long precharge;
59 	unsigned long moved_charge;
60 	unsigned long moved_swap;
61 	struct task_struct *moving_task;	/* a task moving charges */
62 	wait_queue_head_t waitq;		/* a waitq for other context */
63 } mc = {
64 	.lock = __SPIN_LOCK_UNLOCKED(mc.lock),
65 	.waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
66 };
67 
68 /* for OOM */
69 struct mem_cgroup_eventfd_list {
70 	struct list_head list;
71 	struct eventfd_ctx *eventfd;
72 };
73 
74 /*
75  * cgroup_event represents events which userspace want to receive.
76  */
77 struct mem_cgroup_event {
78 	/*
79 	 * memcg which the event belongs to.
80 	 */
81 	struct mem_cgroup *memcg;
82 	/*
83 	 * eventfd to signal userspace about the event.
84 	 */
85 	struct eventfd_ctx *eventfd;
86 	/*
87 	 * Each of these stored in a list by the cgroup.
88 	 */
89 	struct list_head list;
90 	/*
91 	 * register_event() callback will be used to add new userspace
92 	 * waiter for changes related to this event.  Use eventfd_signal()
93 	 * on eventfd to send notification to userspace.
94 	 */
95 	int (*register_event)(struct mem_cgroup *memcg,
96 			      struct eventfd_ctx *eventfd, const char *args);
97 	/*
98 	 * unregister_event() callback will be called when userspace closes
99 	 * the eventfd or on cgroup removing.  This callback must be set,
100 	 * if you want provide notification functionality.
101 	 */
102 	void (*unregister_event)(struct mem_cgroup *memcg,
103 				 struct eventfd_ctx *eventfd);
104 	/*
105 	 * All fields below needed to unregister event when
106 	 * userspace closes eventfd.
107 	 */
108 	poll_table pt;
109 	wait_queue_head_t *wqh;
110 	wait_queue_entry_t wait;
111 	struct work_struct remove;
112 };
113 
114 #define MEMFILE_PRIVATE(x, val)	((x) << 16 | (val))
115 #define MEMFILE_TYPE(val)	((val) >> 16 & 0xffff)
116 #define MEMFILE_ATTR(val)	((val) & 0xffff)
117 
118 enum {
119 	RES_USAGE,
120 	RES_LIMIT,
121 	RES_MAX_USAGE,
122 	RES_FAILCNT,
123 	RES_SOFT_LIMIT,
124 };
125 
126 #ifdef CONFIG_LOCKDEP
127 static struct lockdep_map memcg_oom_lock_dep_map = {
128 	.name = "memcg_oom_lock",
129 };
130 #endif
131 
132 DEFINE_SPINLOCK(memcg_oom_lock);
133 
__mem_cgroup_insert_exceeded(struct mem_cgroup_per_node * mz,struct mem_cgroup_tree_per_node * mctz,unsigned long new_usage_in_excess)134 static void __mem_cgroup_insert_exceeded(struct mem_cgroup_per_node *mz,
135 					 struct mem_cgroup_tree_per_node *mctz,
136 					 unsigned long new_usage_in_excess)
137 {
138 	struct rb_node **p = &mctz->rb_root.rb_node;
139 	struct rb_node *parent = NULL;
140 	struct mem_cgroup_per_node *mz_node;
141 	bool rightmost = true;
142 
143 	if (mz->on_tree)
144 		return;
145 
146 	mz->usage_in_excess = new_usage_in_excess;
147 	if (!mz->usage_in_excess)
148 		return;
149 	while (*p) {
150 		parent = *p;
151 		mz_node = rb_entry(parent, struct mem_cgroup_per_node,
152 					tree_node);
153 		if (mz->usage_in_excess < mz_node->usage_in_excess) {
154 			p = &(*p)->rb_left;
155 			rightmost = false;
156 		} else {
157 			p = &(*p)->rb_right;
158 		}
159 	}
160 
161 	if (rightmost)
162 		mctz->rb_rightmost = &mz->tree_node;
163 
164 	rb_link_node(&mz->tree_node, parent, p);
165 	rb_insert_color(&mz->tree_node, &mctz->rb_root);
166 	mz->on_tree = true;
167 }
168 
__mem_cgroup_remove_exceeded(struct mem_cgroup_per_node * mz,struct mem_cgroup_tree_per_node * mctz)169 static void __mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
170 					 struct mem_cgroup_tree_per_node *mctz)
171 {
172 	if (!mz->on_tree)
173 		return;
174 
175 	if (&mz->tree_node == mctz->rb_rightmost)
176 		mctz->rb_rightmost = rb_prev(&mz->tree_node);
177 
178 	rb_erase(&mz->tree_node, &mctz->rb_root);
179 	mz->on_tree = false;
180 }
181 
mem_cgroup_remove_exceeded(struct mem_cgroup_per_node * mz,struct mem_cgroup_tree_per_node * mctz)182 static void mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
183 				       struct mem_cgroup_tree_per_node *mctz)
184 {
185 	unsigned long flags;
186 
187 	spin_lock_irqsave(&mctz->lock, flags);
188 	__mem_cgroup_remove_exceeded(mz, mctz);
189 	spin_unlock_irqrestore(&mctz->lock, flags);
190 }
191 
soft_limit_excess(struct mem_cgroup * memcg)192 static unsigned long soft_limit_excess(struct mem_cgroup *memcg)
193 {
194 	unsigned long nr_pages = page_counter_read(&memcg->memory);
195 	unsigned long soft_limit = READ_ONCE(memcg->soft_limit);
196 	unsigned long excess = 0;
197 
198 	if (nr_pages > soft_limit)
199 		excess = nr_pages - soft_limit;
200 
201 	return excess;
202 }
203 
memcg1_update_tree(struct mem_cgroup * memcg,int nid)204 static void memcg1_update_tree(struct mem_cgroup *memcg, int nid)
205 {
206 	unsigned long excess;
207 	struct mem_cgroup_per_node *mz;
208 	struct mem_cgroup_tree_per_node *mctz;
209 
210 	if (lru_gen_enabled()) {
211 		if (soft_limit_excess(memcg))
212 			lru_gen_soft_reclaim(memcg, nid);
213 		return;
214 	}
215 
216 	mctz = soft_limit_tree.rb_tree_per_node[nid];
217 	if (!mctz)
218 		return;
219 	/*
220 	 * Necessary to update all ancestors when hierarchy is used.
221 	 * because their event counter is not touched.
222 	 */
223 	for (; memcg; memcg = parent_mem_cgroup(memcg)) {
224 		mz = memcg->nodeinfo[nid];
225 		excess = soft_limit_excess(memcg);
226 		/*
227 		 * We have to update the tree if mz is on RB-tree or
228 		 * mem is over its softlimit.
229 		 */
230 		if (excess || mz->on_tree) {
231 			unsigned long flags;
232 
233 			spin_lock_irqsave(&mctz->lock, flags);
234 			/* if on-tree, remove it */
235 			if (mz->on_tree)
236 				__mem_cgroup_remove_exceeded(mz, mctz);
237 			/*
238 			 * Insert again. mz->usage_in_excess will be updated.
239 			 * If excess is 0, no tree ops.
240 			 */
241 			__mem_cgroup_insert_exceeded(mz, mctz, excess);
242 			spin_unlock_irqrestore(&mctz->lock, flags);
243 		}
244 	}
245 }
246 
memcg1_remove_from_trees(struct mem_cgroup * memcg)247 void memcg1_remove_from_trees(struct mem_cgroup *memcg)
248 {
249 	struct mem_cgroup_tree_per_node *mctz;
250 	struct mem_cgroup_per_node *mz;
251 	int nid;
252 
253 	for_each_node(nid) {
254 		mz = memcg->nodeinfo[nid];
255 		mctz = soft_limit_tree.rb_tree_per_node[nid];
256 		if (mctz)
257 			mem_cgroup_remove_exceeded(mz, mctz);
258 	}
259 }
260 
261 static struct mem_cgroup_per_node *
__mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node * mctz)262 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
263 {
264 	struct mem_cgroup_per_node *mz;
265 
266 retry:
267 	mz = NULL;
268 	if (!mctz->rb_rightmost)
269 		goto done;		/* Nothing to reclaim from */
270 
271 	mz = rb_entry(mctz->rb_rightmost,
272 		      struct mem_cgroup_per_node, tree_node);
273 	/*
274 	 * Remove the node now but someone else can add it back,
275 	 * we will to add it back at the end of reclaim to its correct
276 	 * position in the tree.
277 	 */
278 	__mem_cgroup_remove_exceeded(mz, mctz);
279 	if (!soft_limit_excess(mz->memcg) ||
280 	    !css_tryget(&mz->memcg->css))
281 		goto retry;
282 done:
283 	return mz;
284 }
285 
286 static struct mem_cgroup_per_node *
mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node * mctz)287 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
288 {
289 	struct mem_cgroup_per_node *mz;
290 
291 	spin_lock_irq(&mctz->lock);
292 	mz = __mem_cgroup_largest_soft_limit_node(mctz);
293 	spin_unlock_irq(&mctz->lock);
294 	return mz;
295 }
296 
mem_cgroup_soft_reclaim(struct mem_cgroup * root_memcg,pg_data_t * pgdat,gfp_t gfp_mask,unsigned long * total_scanned)297 static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
298 				   pg_data_t *pgdat,
299 				   gfp_t gfp_mask,
300 				   unsigned long *total_scanned)
301 {
302 	struct mem_cgroup *victim = NULL;
303 	int total = 0;
304 	int loop = 0;
305 	unsigned long excess;
306 	unsigned long nr_scanned;
307 	struct mem_cgroup_reclaim_cookie reclaim = {
308 		.pgdat = pgdat,
309 	};
310 
311 	excess = soft_limit_excess(root_memcg);
312 
313 	while (1) {
314 		victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
315 		if (!victim) {
316 			loop++;
317 			if (loop >= 2) {
318 				/*
319 				 * If we have not been able to reclaim
320 				 * anything, it might because there are
321 				 * no reclaimable pages under this hierarchy
322 				 */
323 				if (!total)
324 					break;
325 				/*
326 				 * We want to do more targeted reclaim.
327 				 * excess >> 2 is not to excessive so as to
328 				 * reclaim too much, nor too less that we keep
329 				 * coming back to reclaim from this cgroup
330 				 */
331 				if (total >= (excess >> 2) ||
332 					(loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
333 					break;
334 			}
335 			continue;
336 		}
337 		total += mem_cgroup_shrink_node(victim, gfp_mask, false,
338 					pgdat, &nr_scanned);
339 		*total_scanned += nr_scanned;
340 		if (!soft_limit_excess(root_memcg))
341 			break;
342 	}
343 	mem_cgroup_iter_break(root_memcg, victim);
344 	return total;
345 }
346 
memcg1_soft_limit_reclaim(pg_data_t * pgdat,int order,gfp_t gfp_mask,unsigned long * total_scanned)347 unsigned long memcg1_soft_limit_reclaim(pg_data_t *pgdat, int order,
348 					    gfp_t gfp_mask,
349 					    unsigned long *total_scanned)
350 {
351 	unsigned long nr_reclaimed = 0;
352 	struct mem_cgroup_per_node *mz, *next_mz = NULL;
353 	unsigned long reclaimed;
354 	int loop = 0;
355 	struct mem_cgroup_tree_per_node *mctz;
356 	unsigned long excess;
357 
358 	if (lru_gen_enabled())
359 		return 0;
360 
361 	if (order > 0)
362 		return 0;
363 
364 	mctz = soft_limit_tree.rb_tree_per_node[pgdat->node_id];
365 
366 	/*
367 	 * Do not even bother to check the largest node if the root
368 	 * is empty. Do it lockless to prevent lock bouncing. Races
369 	 * are acceptable as soft limit is best effort anyway.
370 	 */
371 	if (!mctz || RB_EMPTY_ROOT(&mctz->rb_root))
372 		return 0;
373 
374 	/*
375 	 * This loop can run a while, specially if mem_cgroup's continuously
376 	 * keep exceeding their soft limit and putting the system under
377 	 * pressure
378 	 */
379 	do {
380 		if (next_mz)
381 			mz = next_mz;
382 		else
383 			mz = mem_cgroup_largest_soft_limit_node(mctz);
384 		if (!mz)
385 			break;
386 
387 		reclaimed = mem_cgroup_soft_reclaim(mz->memcg, pgdat,
388 						    gfp_mask, total_scanned);
389 		nr_reclaimed += reclaimed;
390 		spin_lock_irq(&mctz->lock);
391 
392 		/*
393 		 * If we failed to reclaim anything from this memory cgroup
394 		 * it is time to move on to the next cgroup
395 		 */
396 		next_mz = NULL;
397 		if (!reclaimed)
398 			next_mz = __mem_cgroup_largest_soft_limit_node(mctz);
399 
400 		excess = soft_limit_excess(mz->memcg);
401 		/*
402 		 * One school of thought says that we should not add
403 		 * back the node to the tree if reclaim returns 0.
404 		 * But our reclaim could return 0, simply because due
405 		 * to priority we are exposing a smaller subset of
406 		 * memory to reclaim from. Consider this as a longer
407 		 * term TODO.
408 		 */
409 		/* If excess == 0, no tree ops */
410 		__mem_cgroup_insert_exceeded(mz, mctz, excess);
411 		spin_unlock_irq(&mctz->lock);
412 		css_put(&mz->memcg->css);
413 		loop++;
414 		/*
415 		 * Could not reclaim anything and there are no more
416 		 * mem cgroups to try or we seem to be looping without
417 		 * reclaiming anything.
418 		 */
419 		if (!nr_reclaimed &&
420 			(next_mz == NULL ||
421 			loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
422 			break;
423 	} while (!nr_reclaimed);
424 	if (next_mz)
425 		css_put(&next_mz->memcg->css);
426 	return nr_reclaimed;
427 }
428 
429 /*
430  * A routine for checking "mem" is under move_account() or not.
431  *
432  * Checking a cgroup is mc.from or mc.to or under hierarchy of
433  * moving cgroups. This is for waiting at high-memory pressure
434  * caused by "move".
435  */
mem_cgroup_under_move(struct mem_cgroup * memcg)436 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
437 {
438 	struct mem_cgroup *from;
439 	struct mem_cgroup *to;
440 	bool ret = false;
441 	/*
442 	 * Unlike task_move routines, we access mc.to, mc.from not under
443 	 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
444 	 */
445 	spin_lock(&mc.lock);
446 	from = mc.from;
447 	to = mc.to;
448 	if (!from)
449 		goto unlock;
450 
451 	ret = mem_cgroup_is_descendant(from, memcg) ||
452 		mem_cgroup_is_descendant(to, memcg);
453 unlock:
454 	spin_unlock(&mc.lock);
455 	return ret;
456 }
457 
memcg1_wait_acct_move(struct mem_cgroup * memcg)458 bool memcg1_wait_acct_move(struct mem_cgroup *memcg)
459 {
460 	if (mc.moving_task && current != mc.moving_task) {
461 		if (mem_cgroup_under_move(memcg)) {
462 			DEFINE_WAIT(wait);
463 			prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
464 			/* moving charge context might have finished. */
465 			if (mc.moving_task)
466 				schedule();
467 			finish_wait(&mc.waitq, &wait);
468 			return true;
469 		}
470 	}
471 	return false;
472 }
473 
474 /**
475  * folio_memcg_lock - Bind a folio to its memcg.
476  * @folio: The folio.
477  *
478  * This function prevents unlocked LRU folios from being moved to
479  * another cgroup.
480  *
481  * It ensures lifetime of the bound memcg.  The caller is responsible
482  * for the lifetime of the folio.
483  */
folio_memcg_lock(struct folio * folio)484 void folio_memcg_lock(struct folio *folio)
485 {
486 	struct mem_cgroup *memcg;
487 	unsigned long flags;
488 
489 	/*
490 	 * The RCU lock is held throughout the transaction.  The fast
491 	 * path can get away without acquiring the memcg->move_lock
492 	 * because page moving starts with an RCU grace period.
493          */
494 	rcu_read_lock();
495 
496 	if (mem_cgroup_disabled())
497 		return;
498 again:
499 	memcg = folio_memcg(folio);
500 	if (unlikely(!memcg))
501 		return;
502 
503 #ifdef CONFIG_PROVE_LOCKING
504 	local_irq_save(flags);
505 	might_lock(&memcg->move_lock);
506 	local_irq_restore(flags);
507 #endif
508 
509 	if (atomic_read(&memcg->moving_account) <= 0)
510 		return;
511 
512 	spin_lock_irqsave(&memcg->move_lock, flags);
513 	if (memcg != folio_memcg(folio)) {
514 		spin_unlock_irqrestore(&memcg->move_lock, flags);
515 		goto again;
516 	}
517 
518 	/*
519 	 * When charge migration first begins, we can have multiple
520 	 * critical sections holding the fast-path RCU lock and one
521 	 * holding the slowpath move_lock. Track the task who has the
522 	 * move_lock for folio_memcg_unlock().
523 	 */
524 	memcg->move_lock_task = current;
525 	memcg->move_lock_flags = flags;
526 }
527 
__folio_memcg_unlock(struct mem_cgroup * memcg)528 static void __folio_memcg_unlock(struct mem_cgroup *memcg)
529 {
530 	if (memcg && memcg->move_lock_task == current) {
531 		unsigned long flags = memcg->move_lock_flags;
532 
533 		memcg->move_lock_task = NULL;
534 		memcg->move_lock_flags = 0;
535 
536 		spin_unlock_irqrestore(&memcg->move_lock, flags);
537 	}
538 
539 	rcu_read_unlock();
540 }
541 
542 /**
543  * folio_memcg_unlock - Release the binding between a folio and its memcg.
544  * @folio: The folio.
545  *
546  * This releases the binding created by folio_memcg_lock().  This does
547  * not change the accounting of this folio to its memcg, but it does
548  * permit others to change it.
549  */
folio_memcg_unlock(struct folio * folio)550 void folio_memcg_unlock(struct folio *folio)
551 {
552 	__folio_memcg_unlock(folio_memcg(folio));
553 }
554 
555 #ifdef CONFIG_SWAP
556 /**
557  * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
558  * @entry: swap entry to be moved
559  * @from:  mem_cgroup which the entry is moved from
560  * @to:  mem_cgroup which the entry is moved to
561  *
562  * It succeeds only when the swap_cgroup's record for this entry is the same
563  * as the mem_cgroup's id of @from.
564  *
565  * Returns 0 on success, -EINVAL on failure.
566  *
567  * The caller must have charged to @to, IOW, called page_counter_charge() about
568  * both res and memsw, and called css_get().
569  */
mem_cgroup_move_swap_account(swp_entry_t entry,struct mem_cgroup * from,struct mem_cgroup * to)570 static int mem_cgroup_move_swap_account(swp_entry_t entry,
571 				struct mem_cgroup *from, struct mem_cgroup *to)
572 {
573 	unsigned short old_id, new_id;
574 
575 	old_id = mem_cgroup_id(from);
576 	new_id = mem_cgroup_id(to);
577 
578 	if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
579 		mod_memcg_state(from, MEMCG_SWAP, -1);
580 		mod_memcg_state(to, MEMCG_SWAP, 1);
581 		return 0;
582 	}
583 	return -EINVAL;
584 }
585 #else
mem_cgroup_move_swap_account(swp_entry_t entry,struct mem_cgroup * from,struct mem_cgroup * to)586 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
587 				struct mem_cgroup *from, struct mem_cgroup *to)
588 {
589 	return -EINVAL;
590 }
591 #endif
592 
mem_cgroup_move_charge_read(struct cgroup_subsys_state * css,struct cftype * cft)593 static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
594 				struct cftype *cft)
595 {
596 	return mem_cgroup_from_css(css)->move_charge_at_immigrate;
597 }
598 
599 #ifdef CONFIG_MMU
mem_cgroup_move_charge_write(struct cgroup_subsys_state * css,struct cftype * cft,u64 val)600 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
601 				 struct cftype *cft, u64 val)
602 {
603 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
604 
605 	pr_warn_once("Cgroup memory moving (move_charge_at_immigrate) is deprecated. "
606 		     "Please report your usecase to linux-mm@kvack.org if you "
607 		     "depend on this functionality.\n");
608 
609 	if (val & ~MOVE_MASK)
610 		return -EINVAL;
611 
612 	/*
613 	 * No kind of locking is needed in here, because ->can_attach() will
614 	 * check this value once in the beginning of the process, and then carry
615 	 * on with stale data. This means that changes to this value will only
616 	 * affect task migrations starting after the change.
617 	 */
618 	memcg->move_charge_at_immigrate = val;
619 	return 0;
620 }
621 #else
mem_cgroup_move_charge_write(struct cgroup_subsys_state * css,struct cftype * cft,u64 val)622 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
623 				 struct cftype *cft, u64 val)
624 {
625 	return -ENOSYS;
626 }
627 #endif
628 
629 #ifdef CONFIG_MMU
630 /* Handlers for move charge at task migration. */
mem_cgroup_do_precharge(unsigned long count)631 static int mem_cgroup_do_precharge(unsigned long count)
632 {
633 	int ret;
634 
635 	/* Try a single bulk charge without reclaim first, kswapd may wake */
636 	ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_DIRECT_RECLAIM, count);
637 	if (!ret) {
638 		mc.precharge += count;
639 		return ret;
640 	}
641 
642 	/* Try charges one by one with reclaim, but do not retry */
643 	while (count--) {
644 		ret = try_charge(mc.to, GFP_KERNEL | __GFP_NORETRY, 1);
645 		if (ret)
646 			return ret;
647 		mc.precharge++;
648 		cond_resched();
649 	}
650 	return 0;
651 }
652 
653 union mc_target {
654 	struct folio	*folio;
655 	swp_entry_t	ent;
656 };
657 
658 enum mc_target_type {
659 	MC_TARGET_NONE = 0,
660 	MC_TARGET_PAGE,
661 	MC_TARGET_SWAP,
662 	MC_TARGET_DEVICE,
663 };
664 
mc_handle_present_pte(struct vm_area_struct * vma,unsigned long addr,pte_t ptent)665 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
666 						unsigned long addr, pte_t ptent)
667 {
668 	struct page *page = vm_normal_page(vma, addr, ptent);
669 
670 	if (!page)
671 		return NULL;
672 	if (PageAnon(page)) {
673 		if (!(mc.flags & MOVE_ANON))
674 			return NULL;
675 	} else {
676 		if (!(mc.flags & MOVE_FILE))
677 			return NULL;
678 	}
679 	get_page(page);
680 
681 	return page;
682 }
683 
684 #if defined(CONFIG_SWAP) || defined(CONFIG_DEVICE_PRIVATE)
mc_handle_swap_pte(struct vm_area_struct * vma,pte_t ptent,swp_entry_t * entry)685 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
686 			pte_t ptent, swp_entry_t *entry)
687 {
688 	struct page *page = NULL;
689 	swp_entry_t ent = pte_to_swp_entry(ptent);
690 
691 	if (!(mc.flags & MOVE_ANON))
692 		return NULL;
693 
694 	/*
695 	 * Handle device private pages that are not accessible by the CPU, but
696 	 * stored as special swap entries in the page table.
697 	 */
698 	if (is_device_private_entry(ent)) {
699 		page = pfn_swap_entry_to_page(ent);
700 		if (!get_page_unless_zero(page))
701 			return NULL;
702 		return page;
703 	}
704 
705 	if (non_swap_entry(ent))
706 		return NULL;
707 
708 	/*
709 	 * Because swap_cache_get_folio() updates some statistics counter,
710 	 * we call find_get_page() with swapper_space directly.
711 	 */
712 	page = find_get_page(swap_address_space(ent), swap_cache_index(ent));
713 	entry->val = ent.val;
714 
715 	return page;
716 }
717 #else
mc_handle_swap_pte(struct vm_area_struct * vma,pte_t ptent,swp_entry_t * entry)718 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
719 			pte_t ptent, swp_entry_t *entry)
720 {
721 	return NULL;
722 }
723 #endif
724 
mc_handle_file_pte(struct vm_area_struct * vma,unsigned long addr,pte_t ptent)725 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
726 			unsigned long addr, pte_t ptent)
727 {
728 	unsigned long index;
729 	struct folio *folio;
730 
731 	if (!vma->vm_file) /* anonymous vma */
732 		return NULL;
733 	if (!(mc.flags & MOVE_FILE))
734 		return NULL;
735 
736 	/* folio is moved even if it's not RSS of this task(page-faulted). */
737 	/* shmem/tmpfs may report page out on swap: account for that too. */
738 	index = linear_page_index(vma, addr);
739 	folio = filemap_get_incore_folio(vma->vm_file->f_mapping, index);
740 	if (IS_ERR(folio))
741 		return NULL;
742 	return folio_file_page(folio, index);
743 }
744 
745 static void memcg1_check_events(struct mem_cgroup *memcg, int nid);
746 static void memcg1_charge_statistics(struct mem_cgroup *memcg, int nr_pages);
747 
748 /**
749  * mem_cgroup_move_account - move account of the folio
750  * @folio: The folio.
751  * @compound: charge the page as compound or small page
752  * @from: mem_cgroup which the folio is moved from.
753  * @to:	mem_cgroup which the folio is moved to. @from != @to.
754  *
755  * The folio must be locked and not on the LRU.
756  *
757  * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
758  * from old cgroup.
759  */
mem_cgroup_move_account(struct folio * folio,bool compound,struct mem_cgroup * from,struct mem_cgroup * to)760 int mem_cgroup_move_account(struct folio *folio,
761 				   bool compound,
762 				   struct mem_cgroup *from,
763 				   struct mem_cgroup *to)
764 {
765 	struct lruvec *from_vec, *to_vec;
766 	struct pglist_data *pgdat;
767 	unsigned int nr_pages = compound ? folio_nr_pages(folio) : 1;
768 	int nid, ret;
769 
770 	VM_BUG_ON(from == to);
771 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
772 	VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
773 	VM_BUG_ON(compound && !folio_test_large(folio));
774 
775 	ret = -EINVAL;
776 	if (folio_memcg(folio) != from)
777 		goto out;
778 
779 	pgdat = folio_pgdat(folio);
780 	from_vec = mem_cgroup_lruvec(from, pgdat);
781 	to_vec = mem_cgroup_lruvec(to, pgdat);
782 
783 	folio_memcg_lock(folio);
784 
785 	if (folio_test_anon(folio)) {
786 		if (folio_mapped(folio)) {
787 			__mod_lruvec_state(from_vec, NR_ANON_MAPPED, -nr_pages);
788 			__mod_lruvec_state(to_vec, NR_ANON_MAPPED, nr_pages);
789 			if (folio_test_pmd_mappable(folio)) {
790 				__mod_lruvec_state(from_vec, NR_ANON_THPS,
791 						   -nr_pages);
792 				__mod_lruvec_state(to_vec, NR_ANON_THPS,
793 						   nr_pages);
794 			}
795 		}
796 	} else {
797 		__mod_lruvec_state(from_vec, NR_FILE_PAGES, -nr_pages);
798 		__mod_lruvec_state(to_vec, NR_FILE_PAGES, nr_pages);
799 
800 		if (folio_test_swapbacked(folio)) {
801 			__mod_lruvec_state(from_vec, NR_SHMEM, -nr_pages);
802 			__mod_lruvec_state(to_vec, NR_SHMEM, nr_pages);
803 		}
804 
805 		if (folio_mapped(folio)) {
806 			__mod_lruvec_state(from_vec, NR_FILE_MAPPED, -nr_pages);
807 			__mod_lruvec_state(to_vec, NR_FILE_MAPPED, nr_pages);
808 		}
809 
810 		if (folio_test_dirty(folio)) {
811 			struct address_space *mapping = folio_mapping(folio);
812 
813 			if (mapping_can_writeback(mapping)) {
814 				__mod_lruvec_state(from_vec, NR_FILE_DIRTY,
815 						   -nr_pages);
816 				__mod_lruvec_state(to_vec, NR_FILE_DIRTY,
817 						   nr_pages);
818 			}
819 		}
820 	}
821 
822 #ifdef CONFIG_SWAP
823 	if (folio_test_swapcache(folio)) {
824 		__mod_lruvec_state(from_vec, NR_SWAPCACHE, -nr_pages);
825 		__mod_lruvec_state(to_vec, NR_SWAPCACHE, nr_pages);
826 	}
827 #endif
828 	if (folio_test_writeback(folio)) {
829 		__mod_lruvec_state(from_vec, NR_WRITEBACK, -nr_pages);
830 		__mod_lruvec_state(to_vec, NR_WRITEBACK, nr_pages);
831 	}
832 
833 	/*
834 	 * All state has been migrated, let's switch to the new memcg.
835 	 *
836 	 * It is safe to change page's memcg here because the page
837 	 * is referenced, charged, isolated, and locked: we can't race
838 	 * with (un)charging, migration, LRU putback, or anything else
839 	 * that would rely on a stable page's memory cgroup.
840 	 *
841 	 * Note that folio_memcg_lock is a memcg lock, not a page lock,
842 	 * to save space. As soon as we switch page's memory cgroup to a
843 	 * new memcg that isn't locked, the above state can change
844 	 * concurrently again. Make sure we're truly done with it.
845 	 */
846 	smp_mb();
847 
848 	css_get(&to->css);
849 	css_put(&from->css);
850 
851 	/* Warning should never happen, so don't worry about refcount non-0 */
852 	WARN_ON_ONCE(folio_unqueue_deferred_split(folio));
853 	folio->memcg_data = (unsigned long)to;
854 
855 	__folio_memcg_unlock(from);
856 
857 	ret = 0;
858 	nid = folio_nid(folio);
859 
860 	local_irq_disable();
861 	memcg1_charge_statistics(to, nr_pages);
862 	memcg1_check_events(to, nid);
863 	memcg1_charge_statistics(from, -nr_pages);
864 	memcg1_check_events(from, nid);
865 	local_irq_enable();
866 out:
867 	return ret;
868 }
869 EXPORT_SYMBOL_GPL(mem_cgroup_move_account);
870 
871 /**
872  * get_mctgt_type - get target type of moving charge
873  * @vma: the vma the pte to be checked belongs
874  * @addr: the address corresponding to the pte to be checked
875  * @ptent: the pte to be checked
876  * @target: the pointer the target page or swap ent will be stored(can be NULL)
877  *
878  * Context: Called with pte lock held.
879  * Return:
880  * * MC_TARGET_NONE - If the pte is not a target for move charge.
881  * * MC_TARGET_PAGE - If the page corresponding to this pte is a target for
882  *   move charge. If @target is not NULL, the folio is stored in target->folio
883  *   with extra refcnt taken (Caller should release it).
884  * * MC_TARGET_SWAP - If the swap entry corresponding to this pte is a
885  *   target for charge migration.  If @target is not NULL, the entry is
886  *   stored in target->ent.
887  * * MC_TARGET_DEVICE - Like MC_TARGET_PAGE but page is device memory and
888  *   thus not on the lru.  For now such page is charged like a regular page
889  *   would be as it is just special memory taking the place of a regular page.
890  *   See Documentations/vm/hmm.txt and include/linux/hmm.h
891  */
get_mctgt_type(struct vm_area_struct * vma,unsigned long addr,pte_t ptent,union mc_target * target)892 static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
893 		unsigned long addr, pte_t ptent, union mc_target *target)
894 {
895 	struct page *page = NULL;
896 	struct folio *folio;
897 	enum mc_target_type ret = MC_TARGET_NONE;
898 	swp_entry_t ent = { .val = 0 };
899 
900 	if (pte_present(ptent))
901 		page = mc_handle_present_pte(vma, addr, ptent);
902 	else if (pte_none_mostly(ptent))
903 		/*
904 		 * PTE markers should be treated as a none pte here, separated
905 		 * from other swap handling below.
906 		 */
907 		page = mc_handle_file_pte(vma, addr, ptent);
908 	else if (is_swap_pte(ptent))
909 		page = mc_handle_swap_pte(vma, ptent, &ent);
910 
911 	if (page)
912 		folio = page_folio(page);
913 	if (target && page) {
914 		if (!folio_trylock(folio)) {
915 			folio_put(folio);
916 			return ret;
917 		}
918 		/*
919 		 * page_mapped() must be stable during the move. This
920 		 * pte is locked, so if it's present, the page cannot
921 		 * become unmapped. If it isn't, we have only partial
922 		 * control over the mapped state: the page lock will
923 		 * prevent new faults against pagecache and swapcache,
924 		 * so an unmapped page cannot become mapped. However,
925 		 * if the page is already mapped elsewhere, it can
926 		 * unmap, and there is nothing we can do about it.
927 		 * Alas, skip moving the page in this case.
928 		 */
929 		if (!pte_present(ptent) && page_mapped(page)) {
930 			folio_unlock(folio);
931 			folio_put(folio);
932 			return ret;
933 		}
934 	}
935 
936 	if (!page && !ent.val)
937 		return ret;
938 	if (page) {
939 		/*
940 		 * Do only loose check w/o serialization.
941 		 * mem_cgroup_move_account() checks the page is valid or
942 		 * not under LRU exclusion.
943 		 */
944 		if (folio_memcg(folio) == mc.from) {
945 			ret = MC_TARGET_PAGE;
946 			if (folio_is_device_private(folio) ||
947 			    folio_is_device_coherent(folio))
948 				ret = MC_TARGET_DEVICE;
949 			if (target)
950 				target->folio = folio;
951 		}
952 		if (!ret || !target) {
953 			if (target)
954 				folio_unlock(folio);
955 			folio_put(folio);
956 		}
957 	}
958 	/*
959 	 * There is a swap entry and a page doesn't exist or isn't charged.
960 	 * But we cannot move a tail-page in a THP.
961 	 */
962 	if (ent.val && !ret && (!page || !PageTransCompound(page)) &&
963 	    mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
964 		ret = MC_TARGET_SWAP;
965 		if (target)
966 			target->ent = ent;
967 	}
968 	return ret;
969 }
970 
971 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
972 /*
973  * We don't consider PMD mapped swapping or file mapped pages because THP does
974  * not support them for now.
975  * Caller should make sure that pmd_trans_huge(pmd) is true.
976  */
get_mctgt_type_thp(struct vm_area_struct * vma,unsigned long addr,pmd_t pmd,union mc_target * target)977 static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
978 		unsigned long addr, pmd_t pmd, union mc_target *target)
979 {
980 	struct page *page = NULL;
981 	struct folio *folio;
982 	enum mc_target_type ret = MC_TARGET_NONE;
983 
984 	if (unlikely(is_swap_pmd(pmd))) {
985 		VM_BUG_ON(thp_migration_supported() &&
986 				  !is_pmd_migration_entry(pmd));
987 		return ret;
988 	}
989 	page = pmd_page(pmd);
990 	VM_BUG_ON_PAGE(!page || !PageHead(page), page);
991 	folio = page_folio(page);
992 	if (!(mc.flags & MOVE_ANON))
993 		return ret;
994 	if (folio_memcg(folio) == mc.from) {
995 		ret = MC_TARGET_PAGE;
996 		if (target) {
997 			folio_get(folio);
998 			if (!folio_trylock(folio)) {
999 				folio_put(folio);
1000 				return MC_TARGET_NONE;
1001 			}
1002 			target->folio = folio;
1003 		}
1004 	}
1005 	return ret;
1006 }
1007 #else
get_mctgt_type_thp(struct vm_area_struct * vma,unsigned long addr,pmd_t pmd,union mc_target * target)1008 static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
1009 		unsigned long addr, pmd_t pmd, union mc_target *target)
1010 {
1011 	return MC_TARGET_NONE;
1012 }
1013 #endif
1014 
mem_cgroup_count_precharge_pte_range(pmd_t * pmd,unsigned long addr,unsigned long end,struct mm_walk * walk)1015 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
1016 					unsigned long addr, unsigned long end,
1017 					struct mm_walk *walk)
1018 {
1019 	struct vm_area_struct *vma = walk->vma;
1020 	pte_t *pte;
1021 	spinlock_t *ptl;
1022 
1023 	ptl = pmd_trans_huge_lock(pmd, vma);
1024 	if (ptl) {
1025 		/*
1026 		 * Note their can not be MC_TARGET_DEVICE for now as we do not
1027 		 * support transparent huge page with MEMORY_DEVICE_PRIVATE but
1028 		 * this might change.
1029 		 */
1030 		if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
1031 			mc.precharge += HPAGE_PMD_NR;
1032 		spin_unlock(ptl);
1033 		return 0;
1034 	}
1035 
1036 	pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
1037 	if (!pte)
1038 		return 0;
1039 	for (; addr != end; pte++, addr += PAGE_SIZE)
1040 		if (get_mctgt_type(vma, addr, ptep_get(pte), NULL))
1041 			mc.precharge++;	/* increment precharge temporarily */
1042 	pte_unmap_unlock(pte - 1, ptl);
1043 	cond_resched();
1044 
1045 	return 0;
1046 }
1047 
1048 static const struct mm_walk_ops precharge_walk_ops = {
1049 	.pmd_entry	= mem_cgroup_count_precharge_pte_range,
1050 	.walk_lock	= PGWALK_RDLOCK,
1051 };
1052 
mem_cgroup_count_precharge(struct mm_struct * mm)1053 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
1054 {
1055 	unsigned long precharge;
1056 
1057 	mmap_read_lock(mm);
1058 	walk_page_range(mm, 0, ULONG_MAX, &precharge_walk_ops, NULL);
1059 	mmap_read_unlock(mm);
1060 
1061 	precharge = mc.precharge;
1062 	mc.precharge = 0;
1063 
1064 	return precharge;
1065 }
1066 
mem_cgroup_precharge_mc(struct mm_struct * mm)1067 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
1068 {
1069 	unsigned long precharge = mem_cgroup_count_precharge(mm);
1070 
1071 	VM_BUG_ON(mc.moving_task);
1072 	mc.moving_task = current;
1073 	return mem_cgroup_do_precharge(precharge);
1074 }
1075 
1076 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
__mem_cgroup_clear_mc(void)1077 static void __mem_cgroup_clear_mc(void)
1078 {
1079 	struct mem_cgroup *from = mc.from;
1080 	struct mem_cgroup *to = mc.to;
1081 
1082 	/* we must uncharge all the leftover precharges from mc.to */
1083 	if (mc.precharge) {
1084 		mem_cgroup_cancel_charge(mc.to, mc.precharge);
1085 		mc.precharge = 0;
1086 	}
1087 	/*
1088 	 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
1089 	 * we must uncharge here.
1090 	 */
1091 	if (mc.moved_charge) {
1092 		mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
1093 		mc.moved_charge = 0;
1094 	}
1095 	/* we must fixup refcnts and charges */
1096 	if (mc.moved_swap) {
1097 		/* uncharge swap account from the old cgroup */
1098 		if (!mem_cgroup_is_root(mc.from))
1099 			page_counter_uncharge(&mc.from->memsw, mc.moved_swap);
1100 
1101 		mem_cgroup_id_put_many(mc.from, mc.moved_swap);
1102 
1103 		/*
1104 		 * we charged both to->memory and to->memsw, so we
1105 		 * should uncharge to->memory.
1106 		 */
1107 		if (!mem_cgroup_is_root(mc.to))
1108 			page_counter_uncharge(&mc.to->memory, mc.moved_swap);
1109 
1110 		mc.moved_swap = 0;
1111 	}
1112 	memcg1_oom_recover(from);
1113 	memcg1_oom_recover(to);
1114 	wake_up_all(&mc.waitq);
1115 }
1116 
mem_cgroup_clear_mc(void)1117 static void mem_cgroup_clear_mc(void)
1118 {
1119 	struct mm_struct *mm = mc.mm;
1120 
1121 	/*
1122 	 * we must clear moving_task before waking up waiters at the end of
1123 	 * task migration.
1124 	 */
1125 	mc.moving_task = NULL;
1126 	__mem_cgroup_clear_mc();
1127 	spin_lock(&mc.lock);
1128 	mc.from = NULL;
1129 	mc.to = NULL;
1130 	mc.mm = NULL;
1131 	spin_unlock(&mc.lock);
1132 
1133 	mmput(mm);
1134 }
1135 
memcg1_can_attach(struct cgroup_taskset * tset)1136 int memcg1_can_attach(struct cgroup_taskset *tset)
1137 {
1138 	struct cgroup_subsys_state *css;
1139 	struct mem_cgroup *memcg = NULL; /* unneeded init to make gcc happy */
1140 	struct mem_cgroup *from;
1141 	struct task_struct *leader, *p;
1142 	struct mm_struct *mm;
1143 	unsigned long move_flags;
1144 	int ret = 0;
1145 
1146 	/* charge immigration isn't supported on the default hierarchy */
1147 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1148 		return 0;
1149 
1150 	/*
1151 	 * Multi-process migrations only happen on the default hierarchy
1152 	 * where charge immigration is not used.  Perform charge
1153 	 * immigration if @tset contains a leader and whine if there are
1154 	 * multiple.
1155 	 */
1156 	p = NULL;
1157 	cgroup_taskset_for_each_leader(leader, css, tset) {
1158 		WARN_ON_ONCE(p);
1159 		p = leader;
1160 		memcg = mem_cgroup_from_css(css);
1161 	}
1162 	if (!p)
1163 		return 0;
1164 
1165 	/*
1166 	 * We are now committed to this value whatever it is. Changes in this
1167 	 * tunable will only affect upcoming migrations, not the current one.
1168 	 * So we need to save it, and keep it going.
1169 	 */
1170 	move_flags = READ_ONCE(memcg->move_charge_at_immigrate);
1171 	if (!move_flags)
1172 		return 0;
1173 
1174 	from = mem_cgroup_from_task(p);
1175 
1176 	VM_BUG_ON(from == memcg);
1177 
1178 	mm = get_task_mm(p);
1179 	if (!mm)
1180 		return 0;
1181 	/* We move charges only when we move a owner of the mm */
1182 	if (mm->owner == p) {
1183 		VM_BUG_ON(mc.from);
1184 		VM_BUG_ON(mc.to);
1185 		VM_BUG_ON(mc.precharge);
1186 		VM_BUG_ON(mc.moved_charge);
1187 		VM_BUG_ON(mc.moved_swap);
1188 
1189 		spin_lock(&mc.lock);
1190 		mc.mm = mm;
1191 		mc.from = from;
1192 		mc.to = memcg;
1193 		mc.flags = move_flags;
1194 		spin_unlock(&mc.lock);
1195 		/* We set mc.moving_task later */
1196 
1197 		ret = mem_cgroup_precharge_mc(mm);
1198 		if (ret)
1199 			mem_cgroup_clear_mc();
1200 	} else {
1201 		mmput(mm);
1202 	}
1203 	return ret;
1204 }
1205 
memcg1_cancel_attach(struct cgroup_taskset * tset)1206 void memcg1_cancel_attach(struct cgroup_taskset *tset)
1207 {
1208 	if (mc.to)
1209 		mem_cgroup_clear_mc();
1210 }
1211 
mem_cgroup_move_charge_pte_range(pmd_t * pmd,unsigned long addr,unsigned long end,struct mm_walk * walk)1212 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
1213 				unsigned long addr, unsigned long end,
1214 				struct mm_walk *walk)
1215 {
1216 	int ret = 0;
1217 	struct vm_area_struct *vma = walk->vma;
1218 	pte_t *pte;
1219 	spinlock_t *ptl;
1220 	enum mc_target_type target_type;
1221 	union mc_target target;
1222 	struct folio *folio;
1223 	bool tried_split_before = false;
1224 
1225 retry_pmd:
1226 	ptl = pmd_trans_huge_lock(pmd, vma);
1227 	if (ptl) {
1228 		if (mc.precharge < HPAGE_PMD_NR) {
1229 			spin_unlock(ptl);
1230 			return 0;
1231 		}
1232 		target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
1233 		if (target_type == MC_TARGET_PAGE) {
1234 			folio = target.folio;
1235 			/*
1236 			 * Deferred split queue locking depends on memcg,
1237 			 * and unqueue is unsafe unless folio refcount is 0:
1238 			 * split or skip if on the queue? first try to split.
1239 			 */
1240 			if (!list_empty(&folio->_deferred_list)) {
1241 				spin_unlock(ptl);
1242 				if (!tried_split_before)
1243 					split_folio(folio);
1244 				folio_unlock(folio);
1245 				folio_put(folio);
1246 				if (tried_split_before)
1247 					return 0;
1248 				tried_split_before = true;
1249 				goto retry_pmd;
1250 			}
1251 			/*
1252 			 * So long as that pmd lock is held, the folio cannot
1253 			 * be racily added to the _deferred_list, because
1254 			 * __folio_remove_rmap() will find !partially_mapped.
1255 			 */
1256 			if (folio_isolate_lru(folio)) {
1257 				if (!mem_cgroup_move_account(folio, true,
1258 							     mc.from, mc.to)) {
1259 					mc.precharge -= HPAGE_PMD_NR;
1260 					mc.moved_charge += HPAGE_PMD_NR;
1261 				}
1262 				folio_putback_lru(folio);
1263 			}
1264 			folio_unlock(folio);
1265 			folio_put(folio);
1266 		} else if (target_type == MC_TARGET_DEVICE) {
1267 			folio = target.folio;
1268 			if (!mem_cgroup_move_account(folio, true,
1269 						     mc.from, mc.to)) {
1270 				mc.precharge -= HPAGE_PMD_NR;
1271 				mc.moved_charge += HPAGE_PMD_NR;
1272 			}
1273 			folio_unlock(folio);
1274 			folio_put(folio);
1275 		}
1276 		spin_unlock(ptl);
1277 		return 0;
1278 	}
1279 
1280 retry:
1281 	pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
1282 	if (!pte)
1283 		return 0;
1284 	for (; addr != end; addr += PAGE_SIZE) {
1285 		pte_t ptent = ptep_get(pte++);
1286 		bool device = false;
1287 		swp_entry_t ent;
1288 
1289 		if (!mc.precharge)
1290 			break;
1291 
1292 		switch (get_mctgt_type(vma, addr, ptent, &target)) {
1293 		case MC_TARGET_DEVICE:
1294 			device = true;
1295 			fallthrough;
1296 		case MC_TARGET_PAGE:
1297 			folio = target.folio;
1298 			/*
1299 			 * We can have a part of the split pmd here. Moving it
1300 			 * can be done but it would be too convoluted so simply
1301 			 * ignore such a partial THP and keep it in original
1302 			 * memcg. There should be somebody mapping the head.
1303 			 */
1304 			if (folio_test_large(folio))
1305 				goto put;
1306 			if (!device && !folio_isolate_lru(folio))
1307 				goto put;
1308 			if (!mem_cgroup_move_account(folio, false,
1309 						mc.from, mc.to)) {
1310 				mc.precharge--;
1311 				/* we uncharge from mc.from later. */
1312 				mc.moved_charge++;
1313 			}
1314 			if (!device)
1315 				folio_putback_lru(folio);
1316 put:			/* get_mctgt_type() gets & locks the page */
1317 			folio_unlock(folio);
1318 			folio_put(folio);
1319 			break;
1320 		case MC_TARGET_SWAP:
1321 			ent = target.ent;
1322 			if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
1323 				mc.precharge--;
1324 				mem_cgroup_id_get_many(mc.to, 1);
1325 				/* we fixup other refcnts and charges later. */
1326 				mc.moved_swap++;
1327 			}
1328 			break;
1329 		default:
1330 			break;
1331 		}
1332 	}
1333 	pte_unmap_unlock(pte - 1, ptl);
1334 	cond_resched();
1335 
1336 	if (addr != end) {
1337 		/*
1338 		 * We have consumed all precharges we got in can_attach().
1339 		 * We try charge one by one, but don't do any additional
1340 		 * charges to mc.to if we have failed in charge once in attach()
1341 		 * phase.
1342 		 */
1343 		ret = mem_cgroup_do_precharge(1);
1344 		if (!ret)
1345 			goto retry;
1346 	}
1347 
1348 	return ret;
1349 }
1350 
1351 static const struct mm_walk_ops charge_walk_ops = {
1352 	.pmd_entry	= mem_cgroup_move_charge_pte_range,
1353 	.walk_lock	= PGWALK_RDLOCK,
1354 };
1355 
mem_cgroup_move_charge(void)1356 static void mem_cgroup_move_charge(void)
1357 {
1358 	lru_add_drain_all();
1359 	/*
1360 	 * Signal folio_memcg_lock() to take the memcg's move_lock
1361 	 * while we're moving its pages to another memcg. Then wait
1362 	 * for already started RCU-only updates to finish.
1363 	 */
1364 	atomic_inc(&mc.from->moving_account);
1365 	synchronize_rcu();
1366 retry:
1367 	if (unlikely(!mmap_read_trylock(mc.mm))) {
1368 		/*
1369 		 * Someone who are holding the mmap_lock might be waiting in
1370 		 * waitq. So we cancel all extra charges, wake up all waiters,
1371 		 * and retry. Because we cancel precharges, we might not be able
1372 		 * to move enough charges, but moving charge is a best-effort
1373 		 * feature anyway, so it wouldn't be a big problem.
1374 		 */
1375 		__mem_cgroup_clear_mc();
1376 		cond_resched();
1377 		goto retry;
1378 	}
1379 	/*
1380 	 * When we have consumed all precharges and failed in doing
1381 	 * additional charge, the page walk just aborts.
1382 	 */
1383 	walk_page_range(mc.mm, 0, ULONG_MAX, &charge_walk_ops, NULL);
1384 	mmap_read_unlock(mc.mm);
1385 	atomic_dec(&mc.from->moving_account);
1386 }
1387 
memcg1_move_task(void)1388 void memcg1_move_task(void)
1389 {
1390 	if (mc.to) {
1391 		mem_cgroup_move_charge();
1392 		mem_cgroup_clear_mc();
1393 	}
1394 }
1395 
1396 #else	/* !CONFIG_MMU */
memcg1_can_attach(struct cgroup_taskset * tset)1397 int memcg1_can_attach(struct cgroup_taskset *tset)
1398 {
1399 	return 0;
1400 }
memcg1_cancel_attach(struct cgroup_taskset * tset)1401 void memcg1_cancel_attach(struct cgroup_taskset *tset)
1402 {
1403 }
memcg1_move_task(void)1404 void memcg1_move_task(void)
1405 {
1406 }
1407 #endif
1408 
__mem_cgroup_threshold(struct mem_cgroup * memcg,bool swap)1409 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
1410 {
1411 	struct mem_cgroup_threshold_ary *t;
1412 	unsigned long usage;
1413 	int i;
1414 
1415 	rcu_read_lock();
1416 	if (!swap)
1417 		t = rcu_dereference(memcg->thresholds.primary);
1418 	else
1419 		t = rcu_dereference(memcg->memsw_thresholds.primary);
1420 
1421 	if (!t)
1422 		goto unlock;
1423 
1424 	usage = mem_cgroup_usage(memcg, swap);
1425 
1426 	/*
1427 	 * current_threshold points to threshold just below or equal to usage.
1428 	 * If it's not true, a threshold was crossed after last
1429 	 * call of __mem_cgroup_threshold().
1430 	 */
1431 	i = t->current_threshold;
1432 
1433 	/*
1434 	 * Iterate backward over array of thresholds starting from
1435 	 * current_threshold and check if a threshold is crossed.
1436 	 * If none of thresholds below usage is crossed, we read
1437 	 * only one element of the array here.
1438 	 */
1439 	for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
1440 		eventfd_signal(t->entries[i].eventfd);
1441 
1442 	/* i = current_threshold + 1 */
1443 	i++;
1444 
1445 	/*
1446 	 * Iterate forward over array of thresholds starting from
1447 	 * current_threshold+1 and check if a threshold is crossed.
1448 	 * If none of thresholds above usage is crossed, we read
1449 	 * only one element of the array here.
1450 	 */
1451 	for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
1452 		eventfd_signal(t->entries[i].eventfd);
1453 
1454 	/* Update current_threshold */
1455 	t->current_threshold = i - 1;
1456 unlock:
1457 	rcu_read_unlock();
1458 }
1459 
mem_cgroup_threshold(struct mem_cgroup * memcg)1460 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
1461 {
1462 	while (memcg) {
1463 		__mem_cgroup_threshold(memcg, false);
1464 		if (do_memsw_account())
1465 			__mem_cgroup_threshold(memcg, true);
1466 
1467 		memcg = parent_mem_cgroup(memcg);
1468 	}
1469 }
1470 
1471 /* Cgroup1: threshold notifications & softlimit tree updates */
1472 struct memcg1_events_percpu {
1473 	unsigned long nr_page_events;
1474 	unsigned long targets[MEM_CGROUP_NTARGETS];
1475 };
1476 
memcg1_charge_statistics(struct mem_cgroup * memcg,int nr_pages)1477 static void memcg1_charge_statistics(struct mem_cgroup *memcg, int nr_pages)
1478 {
1479 	/* pagein of a big page is an event. So, ignore page size */
1480 	if (nr_pages > 0)
1481 		__count_memcg_events(memcg, PGPGIN, 1);
1482 	else {
1483 		__count_memcg_events(memcg, PGPGOUT, 1);
1484 		nr_pages = -nr_pages; /* for event */
1485 	}
1486 
1487 	__this_cpu_add(memcg->events_percpu->nr_page_events, nr_pages);
1488 }
1489 
1490 #define THRESHOLDS_EVENTS_TARGET 128
1491 #define SOFTLIMIT_EVENTS_TARGET 1024
1492 
memcg1_event_ratelimit(struct mem_cgroup * memcg,enum mem_cgroup_events_target target)1493 static bool memcg1_event_ratelimit(struct mem_cgroup *memcg,
1494 				enum mem_cgroup_events_target target)
1495 {
1496 	unsigned long val, next;
1497 
1498 	val = __this_cpu_read(memcg->events_percpu->nr_page_events);
1499 	next = __this_cpu_read(memcg->events_percpu->targets[target]);
1500 	/* from time_after() in jiffies.h */
1501 	if ((long)(next - val) < 0) {
1502 		switch (target) {
1503 		case MEM_CGROUP_TARGET_THRESH:
1504 			next = val + THRESHOLDS_EVENTS_TARGET;
1505 			break;
1506 		case MEM_CGROUP_TARGET_SOFTLIMIT:
1507 			next = val + SOFTLIMIT_EVENTS_TARGET;
1508 			break;
1509 		default:
1510 			break;
1511 		}
1512 		__this_cpu_write(memcg->events_percpu->targets[target], next);
1513 		return true;
1514 	}
1515 	return false;
1516 }
1517 
1518 /*
1519  * Check events in order.
1520  *
1521  */
memcg1_check_events(struct mem_cgroup * memcg,int nid)1522 static void memcg1_check_events(struct mem_cgroup *memcg, int nid)
1523 {
1524 	if (IS_ENABLED(CONFIG_PREEMPT_RT))
1525 		return;
1526 
1527 	/* threshold event is triggered in finer grain than soft limit */
1528 	if (unlikely(memcg1_event_ratelimit(memcg,
1529 						MEM_CGROUP_TARGET_THRESH))) {
1530 		bool do_softlimit;
1531 
1532 		do_softlimit = memcg1_event_ratelimit(memcg,
1533 						MEM_CGROUP_TARGET_SOFTLIMIT);
1534 		mem_cgroup_threshold(memcg);
1535 		if (unlikely(do_softlimit))
1536 			memcg1_update_tree(memcg, nid);
1537 	}
1538 }
1539 
memcg1_commit_charge(struct folio * folio,struct mem_cgroup * memcg)1540 void memcg1_commit_charge(struct folio *folio, struct mem_cgroup *memcg)
1541 {
1542 	unsigned long flags;
1543 
1544 	local_irq_save(flags);
1545 	memcg1_charge_statistics(memcg, folio_nr_pages(folio));
1546 	memcg1_check_events(memcg, folio_nid(folio));
1547 	local_irq_restore(flags);
1548 }
1549 
memcg1_swapout(struct folio * folio,struct mem_cgroup * memcg)1550 void memcg1_swapout(struct folio *folio, struct mem_cgroup *memcg)
1551 {
1552 	/*
1553 	 * Interrupts should be disabled here because the caller holds the
1554 	 * i_pages lock which is taken with interrupts-off. It is
1555 	 * important here to have the interrupts disabled because it is the
1556 	 * only synchronisation we have for updating the per-CPU variables.
1557 	 */
1558 	preempt_disable_nested();
1559 	VM_WARN_ON_IRQS_ENABLED();
1560 	memcg1_charge_statistics(memcg, -folio_nr_pages(folio));
1561 	preempt_enable_nested();
1562 	memcg1_check_events(memcg, folio_nid(folio));
1563 }
1564 
memcg1_charge_batch(struct mem_cgroup * memcg,unsigned long nr_memory,int nid)1565 void memcg1_charge_batch(struct mem_cgroup *memcg, unsigned long nr_memory, int nid)
1566 {
1567 	unsigned long flags;
1568 
1569 	local_irq_save(flags);
1570 	memcg1_charge_statistics(memcg, nr_memory);
1571 	memcg1_check_events(memcg, nid);
1572 	local_irq_restore(flags);
1573 }
1574 EXPORT_SYMBOL_GPL(memcg1_charge_batch);
1575 
memcg1_uncharge_batch(struct mem_cgroup * memcg,unsigned long pgpgout,unsigned long nr_memory,int nid)1576 void memcg1_uncharge_batch(struct mem_cgroup *memcg, unsigned long pgpgout,
1577 			   unsigned long nr_memory, int nid)
1578 {
1579 	unsigned long flags;
1580 
1581 	local_irq_save(flags);
1582 	__count_memcg_events(memcg, PGPGOUT, pgpgout);
1583 	__this_cpu_add(memcg->events_percpu->nr_page_events, nr_memory);
1584 	memcg1_check_events(memcg, nid);
1585 	local_irq_restore(flags);
1586 }
1587 
compare_thresholds(const void * a,const void * b)1588 static int compare_thresholds(const void *a, const void *b)
1589 {
1590 	const struct mem_cgroup_threshold *_a = a;
1591 	const struct mem_cgroup_threshold *_b = b;
1592 
1593 	if (_a->threshold > _b->threshold)
1594 		return 1;
1595 
1596 	if (_a->threshold < _b->threshold)
1597 		return -1;
1598 
1599 	return 0;
1600 }
1601 
mem_cgroup_oom_notify_cb(struct mem_cgroup * memcg)1602 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
1603 {
1604 	struct mem_cgroup_eventfd_list *ev;
1605 
1606 	spin_lock(&memcg_oom_lock);
1607 
1608 	list_for_each_entry(ev, &memcg->oom_notify, list)
1609 		eventfd_signal(ev->eventfd);
1610 
1611 	spin_unlock(&memcg_oom_lock);
1612 	return 0;
1613 }
1614 
mem_cgroup_oom_notify(struct mem_cgroup * memcg)1615 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
1616 {
1617 	struct mem_cgroup *iter;
1618 
1619 	for_each_mem_cgroup_tree(iter, memcg)
1620 		mem_cgroup_oom_notify_cb(iter);
1621 }
1622 
__mem_cgroup_usage_register_event(struct mem_cgroup * memcg,struct eventfd_ctx * eventfd,const char * args,enum res_type type)1623 static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
1624 	struct eventfd_ctx *eventfd, const char *args, enum res_type type)
1625 {
1626 	struct mem_cgroup_thresholds *thresholds;
1627 	struct mem_cgroup_threshold_ary *new;
1628 	unsigned long threshold;
1629 	unsigned long usage;
1630 	int i, size, ret;
1631 
1632 	ret = page_counter_memparse(args, "-1", &threshold);
1633 	if (ret)
1634 		return ret;
1635 
1636 	mutex_lock(&memcg->thresholds_lock);
1637 
1638 	if (type == _MEM) {
1639 		thresholds = &memcg->thresholds;
1640 		usage = mem_cgroup_usage(memcg, false);
1641 	} else if (type == _MEMSWAP) {
1642 		thresholds = &memcg->memsw_thresholds;
1643 		usage = mem_cgroup_usage(memcg, true);
1644 	} else
1645 		BUG();
1646 
1647 	/* Check if a threshold crossed before adding a new one */
1648 	if (thresholds->primary)
1649 		__mem_cgroup_threshold(memcg, type == _MEMSWAP);
1650 
1651 	size = thresholds->primary ? thresholds->primary->size + 1 : 1;
1652 
1653 	/* Allocate memory for new array of thresholds */
1654 	new = kmalloc(struct_size(new, entries, size), GFP_KERNEL);
1655 	if (!new) {
1656 		ret = -ENOMEM;
1657 		goto unlock;
1658 	}
1659 	new->size = size;
1660 
1661 	/* Copy thresholds (if any) to new array */
1662 	if (thresholds->primary)
1663 		memcpy(new->entries, thresholds->primary->entries,
1664 		       flex_array_size(new, entries, size - 1));
1665 
1666 	/* Add new threshold */
1667 	new->entries[size - 1].eventfd = eventfd;
1668 	new->entries[size - 1].threshold = threshold;
1669 
1670 	/* Sort thresholds. Registering of new threshold isn't time-critical */
1671 	sort(new->entries, size, sizeof(*new->entries),
1672 			compare_thresholds, NULL);
1673 
1674 	/* Find current threshold */
1675 	new->current_threshold = -1;
1676 	for (i = 0; i < size; i++) {
1677 		if (new->entries[i].threshold <= usage) {
1678 			/*
1679 			 * new->current_threshold will not be used until
1680 			 * rcu_assign_pointer(), so it's safe to increment
1681 			 * it here.
1682 			 */
1683 			++new->current_threshold;
1684 		} else
1685 			break;
1686 	}
1687 
1688 	/* Free old spare buffer and save old primary buffer as spare */
1689 	kfree(thresholds->spare);
1690 	thresholds->spare = thresholds->primary;
1691 
1692 	rcu_assign_pointer(thresholds->primary, new);
1693 
1694 	/* To be sure that nobody uses thresholds */
1695 	synchronize_rcu();
1696 
1697 unlock:
1698 	mutex_unlock(&memcg->thresholds_lock);
1699 
1700 	return ret;
1701 }
1702 
mem_cgroup_usage_register_event(struct mem_cgroup * memcg,struct eventfd_ctx * eventfd,const char * args)1703 static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
1704 	struct eventfd_ctx *eventfd, const char *args)
1705 {
1706 	return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
1707 }
1708 
memsw_cgroup_usage_register_event(struct mem_cgroup * memcg,struct eventfd_ctx * eventfd,const char * args)1709 static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
1710 	struct eventfd_ctx *eventfd, const char *args)
1711 {
1712 	return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
1713 }
1714 
__mem_cgroup_usage_unregister_event(struct mem_cgroup * memcg,struct eventfd_ctx * eventfd,enum res_type type)1715 static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
1716 	struct eventfd_ctx *eventfd, enum res_type type)
1717 {
1718 	struct mem_cgroup_thresholds *thresholds;
1719 	struct mem_cgroup_threshold_ary *new;
1720 	unsigned long usage;
1721 	int i, j, size, entries;
1722 
1723 	mutex_lock(&memcg->thresholds_lock);
1724 
1725 	if (type == _MEM) {
1726 		thresholds = &memcg->thresholds;
1727 		usage = mem_cgroup_usage(memcg, false);
1728 	} else if (type == _MEMSWAP) {
1729 		thresholds = &memcg->memsw_thresholds;
1730 		usage = mem_cgroup_usage(memcg, true);
1731 	} else
1732 		BUG();
1733 
1734 	if (!thresholds->primary)
1735 		goto unlock;
1736 
1737 	/* Check if a threshold crossed before removing */
1738 	__mem_cgroup_threshold(memcg, type == _MEMSWAP);
1739 
1740 	/* Calculate new number of threshold */
1741 	size = entries = 0;
1742 	for (i = 0; i < thresholds->primary->size; i++) {
1743 		if (thresholds->primary->entries[i].eventfd != eventfd)
1744 			size++;
1745 		else
1746 			entries++;
1747 	}
1748 
1749 	new = thresholds->spare;
1750 
1751 	/* If no items related to eventfd have been cleared, nothing to do */
1752 	if (!entries)
1753 		goto unlock;
1754 
1755 	/* Set thresholds array to NULL if we don't have thresholds */
1756 	if (!size) {
1757 		kfree(new);
1758 		new = NULL;
1759 		goto swap_buffers;
1760 	}
1761 
1762 	new->size = size;
1763 
1764 	/* Copy thresholds and find current threshold */
1765 	new->current_threshold = -1;
1766 	for (i = 0, j = 0; i < thresholds->primary->size; i++) {
1767 		if (thresholds->primary->entries[i].eventfd == eventfd)
1768 			continue;
1769 
1770 		new->entries[j] = thresholds->primary->entries[i];
1771 		if (new->entries[j].threshold <= usage) {
1772 			/*
1773 			 * new->current_threshold will not be used
1774 			 * until rcu_assign_pointer(), so it's safe to increment
1775 			 * it here.
1776 			 */
1777 			++new->current_threshold;
1778 		}
1779 		j++;
1780 	}
1781 
1782 swap_buffers:
1783 	/* Swap primary and spare array */
1784 	thresholds->spare = thresholds->primary;
1785 
1786 	rcu_assign_pointer(thresholds->primary, new);
1787 
1788 	/* To be sure that nobody uses thresholds */
1789 	synchronize_rcu();
1790 
1791 	/* If all events are unregistered, free the spare array */
1792 	if (!new) {
1793 		kfree(thresholds->spare);
1794 		thresholds->spare = NULL;
1795 	}
1796 unlock:
1797 	mutex_unlock(&memcg->thresholds_lock);
1798 }
1799 
mem_cgroup_usage_unregister_event(struct mem_cgroup * memcg,struct eventfd_ctx * eventfd)1800 static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
1801 	struct eventfd_ctx *eventfd)
1802 {
1803 	return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
1804 }
1805 
memsw_cgroup_usage_unregister_event(struct mem_cgroup * memcg,struct eventfd_ctx * eventfd)1806 static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
1807 	struct eventfd_ctx *eventfd)
1808 {
1809 	return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
1810 }
1811 
mem_cgroup_oom_register_event(struct mem_cgroup * memcg,struct eventfd_ctx * eventfd,const char * args)1812 static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
1813 	struct eventfd_ctx *eventfd, const char *args)
1814 {
1815 	struct mem_cgroup_eventfd_list *event;
1816 
1817 	event = kmalloc(sizeof(*event),	GFP_KERNEL);
1818 	if (!event)
1819 		return -ENOMEM;
1820 
1821 	spin_lock(&memcg_oom_lock);
1822 
1823 	event->eventfd = eventfd;
1824 	list_add(&event->list, &memcg->oom_notify);
1825 
1826 	/* already in OOM ? */
1827 	if (memcg->under_oom)
1828 		eventfd_signal(eventfd);
1829 	spin_unlock(&memcg_oom_lock);
1830 
1831 	return 0;
1832 }
1833 
mem_cgroup_oom_unregister_event(struct mem_cgroup * memcg,struct eventfd_ctx * eventfd)1834 static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
1835 	struct eventfd_ctx *eventfd)
1836 {
1837 	struct mem_cgroup_eventfd_list *ev, *tmp;
1838 
1839 	spin_lock(&memcg_oom_lock);
1840 
1841 	list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
1842 		if (ev->eventfd == eventfd) {
1843 			list_del(&ev->list);
1844 			kfree(ev);
1845 		}
1846 	}
1847 
1848 	spin_unlock(&memcg_oom_lock);
1849 }
1850 
1851 /*
1852  * DO NOT USE IN NEW FILES.
1853  *
1854  * "cgroup.event_control" implementation.
1855  *
1856  * This is way over-engineered.  It tries to support fully configurable
1857  * events for each user.  Such level of flexibility is completely
1858  * unnecessary especially in the light of the planned unified hierarchy.
1859  *
1860  * Please deprecate this and replace with something simpler if at all
1861  * possible.
1862  */
1863 
1864 /*
1865  * Unregister event and free resources.
1866  *
1867  * Gets called from workqueue.
1868  */
memcg_event_remove(struct work_struct * work)1869 static void memcg_event_remove(struct work_struct *work)
1870 {
1871 	struct mem_cgroup_event *event =
1872 		container_of(work, struct mem_cgroup_event, remove);
1873 	struct mem_cgroup *memcg = event->memcg;
1874 
1875 	remove_wait_queue(event->wqh, &event->wait);
1876 
1877 	event->unregister_event(memcg, event->eventfd);
1878 
1879 	/* Notify userspace the event is going away. */
1880 	eventfd_signal(event->eventfd);
1881 
1882 	eventfd_ctx_put(event->eventfd);
1883 	kfree(event);
1884 	css_put(&memcg->css);
1885 }
1886 
1887 /*
1888  * Gets called on EPOLLHUP on eventfd when user closes it.
1889  *
1890  * Called with wqh->lock held and interrupts disabled.
1891  */
memcg_event_wake(wait_queue_entry_t * wait,unsigned mode,int sync,void * key)1892 static int memcg_event_wake(wait_queue_entry_t *wait, unsigned mode,
1893 			    int sync, void *key)
1894 {
1895 	struct mem_cgroup_event *event =
1896 		container_of(wait, struct mem_cgroup_event, wait);
1897 	struct mem_cgroup *memcg = event->memcg;
1898 	__poll_t flags = key_to_poll(key);
1899 
1900 	if (flags & EPOLLHUP) {
1901 		/*
1902 		 * If the event has been detached at cgroup removal, we
1903 		 * can simply return knowing the other side will cleanup
1904 		 * for us.
1905 		 *
1906 		 * We can't race against event freeing since the other
1907 		 * side will require wqh->lock via remove_wait_queue(),
1908 		 * which we hold.
1909 		 */
1910 		spin_lock(&memcg->event_list_lock);
1911 		if (!list_empty(&event->list)) {
1912 			list_del_init(&event->list);
1913 			/*
1914 			 * We are in atomic context, but cgroup_event_remove()
1915 			 * may sleep, so we have to call it in workqueue.
1916 			 */
1917 			schedule_work(&event->remove);
1918 		}
1919 		spin_unlock(&memcg->event_list_lock);
1920 	}
1921 
1922 	return 0;
1923 }
1924 
memcg_event_ptable_queue_proc(struct file * file,wait_queue_head_t * wqh,poll_table * pt)1925 static void memcg_event_ptable_queue_proc(struct file *file,
1926 		wait_queue_head_t *wqh, poll_table *pt)
1927 {
1928 	struct mem_cgroup_event *event =
1929 		container_of(pt, struct mem_cgroup_event, pt);
1930 
1931 	event->wqh = wqh;
1932 	add_wait_queue(wqh, &event->wait);
1933 }
1934 
1935 /*
1936  * DO NOT USE IN NEW FILES.
1937  *
1938  * Parse input and register new cgroup event handler.
1939  *
1940  * Input must be in format '<event_fd> <control_fd> <args>'.
1941  * Interpretation of args is defined by control file implementation.
1942  */
memcg_write_event_control(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)1943 static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
1944 					 char *buf, size_t nbytes, loff_t off)
1945 {
1946 	struct cgroup_subsys_state *css = of_css(of);
1947 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
1948 	struct mem_cgroup_event *event;
1949 	struct cgroup_subsys_state *cfile_css;
1950 	unsigned int efd, cfd;
1951 	struct fd efile;
1952 	struct fd cfile;
1953 	struct dentry *cdentry;
1954 	const char *name;
1955 	char *endp;
1956 	int ret;
1957 
1958 	if (IS_ENABLED(CONFIG_PREEMPT_RT))
1959 		return -EOPNOTSUPP;
1960 
1961 	buf = strstrip(buf);
1962 
1963 	efd = simple_strtoul(buf, &endp, 10);
1964 	if (*endp != ' ')
1965 		return -EINVAL;
1966 	buf = endp + 1;
1967 
1968 	cfd = simple_strtoul(buf, &endp, 10);
1969 	if (*endp == '\0')
1970 		buf = endp;
1971 	else if (*endp == ' ')
1972 		buf = endp + 1;
1973 	else
1974 		return -EINVAL;
1975 
1976 	event = kzalloc(sizeof(*event), GFP_KERNEL);
1977 	if (!event)
1978 		return -ENOMEM;
1979 
1980 	event->memcg = memcg;
1981 	INIT_LIST_HEAD(&event->list);
1982 	init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
1983 	init_waitqueue_func_entry(&event->wait, memcg_event_wake);
1984 	INIT_WORK(&event->remove, memcg_event_remove);
1985 
1986 	efile = fdget(efd);
1987 	if (!fd_file(efile)) {
1988 		ret = -EBADF;
1989 		goto out_kfree;
1990 	}
1991 
1992 	event->eventfd = eventfd_ctx_fileget(fd_file(efile));
1993 	if (IS_ERR(event->eventfd)) {
1994 		ret = PTR_ERR(event->eventfd);
1995 		goto out_put_efile;
1996 	}
1997 
1998 	cfile = fdget(cfd);
1999 	if (!fd_file(cfile)) {
2000 		ret = -EBADF;
2001 		goto out_put_eventfd;
2002 	}
2003 
2004 	/* the process need read permission on control file */
2005 	/* AV: shouldn't we check that it's been opened for read instead? */
2006 	ret = file_permission(fd_file(cfile), MAY_READ);
2007 	if (ret < 0)
2008 		goto out_put_cfile;
2009 
2010 	/*
2011 	 * The control file must be a regular cgroup1 file. As a regular cgroup
2012 	 * file can't be renamed, it's safe to access its name afterwards.
2013 	 */
2014 	cdentry = fd_file(cfile)->f_path.dentry;
2015 	if (cdentry->d_sb->s_type != &cgroup_fs_type || !d_is_reg(cdentry)) {
2016 		ret = -EINVAL;
2017 		goto out_put_cfile;
2018 	}
2019 
2020 	/*
2021 	 * Determine the event callbacks and set them in @event.  This used
2022 	 * to be done via struct cftype but cgroup core no longer knows
2023 	 * about these events.  The following is crude but the whole thing
2024 	 * is for compatibility anyway.
2025 	 *
2026 	 * DO NOT ADD NEW FILES.
2027 	 */
2028 	name = cdentry->d_name.name;
2029 
2030 	if (!strcmp(name, "memory.usage_in_bytes")) {
2031 		event->register_event = mem_cgroup_usage_register_event;
2032 		event->unregister_event = mem_cgroup_usage_unregister_event;
2033 	} else if (!strcmp(name, "memory.oom_control")) {
2034 		pr_warn_once("oom_control is deprecated and will be removed. "
2035 			     "Please report your usecase to linux-mm-@kvack.org"
2036 			     " if you depend on this functionality. \n");
2037 		event->register_event = mem_cgroup_oom_register_event;
2038 		event->unregister_event = mem_cgroup_oom_unregister_event;
2039 	} else if (!strcmp(name, "memory.pressure_level")) {
2040 		pr_warn_once("pressure_level is deprecated and will be removed. "
2041 			     "Please report your usecase to linux-mm-@kvack.org "
2042 			     "if you depend on this functionality. \n");
2043 		event->register_event = vmpressure_register_event;
2044 		event->unregister_event = vmpressure_unregister_event;
2045 	} else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
2046 		event->register_event = memsw_cgroup_usage_register_event;
2047 		event->unregister_event = memsw_cgroup_usage_unregister_event;
2048 	} else {
2049 		ret = -EINVAL;
2050 		goto out_put_cfile;
2051 	}
2052 
2053 	/*
2054 	 * Verify @cfile should belong to @css.  Also, remaining events are
2055 	 * automatically removed on cgroup destruction but the removal is
2056 	 * asynchronous, so take an extra ref on @css.
2057 	 */
2058 	cfile_css = css_tryget_online_from_dir(cdentry->d_parent,
2059 					       &memory_cgrp_subsys);
2060 	ret = -EINVAL;
2061 	if (IS_ERR(cfile_css))
2062 		goto out_put_cfile;
2063 	if (cfile_css != css) {
2064 		css_put(cfile_css);
2065 		goto out_put_cfile;
2066 	}
2067 
2068 	ret = event->register_event(memcg, event->eventfd, buf);
2069 	if (ret)
2070 		goto out_put_css;
2071 
2072 	vfs_poll(fd_file(efile), &event->pt);
2073 
2074 	spin_lock_irq(&memcg->event_list_lock);
2075 	list_add(&event->list, &memcg->event_list);
2076 	spin_unlock_irq(&memcg->event_list_lock);
2077 
2078 	fdput(cfile);
2079 	fdput(efile);
2080 
2081 	return nbytes;
2082 
2083 out_put_css:
2084 	css_put(css);
2085 out_put_cfile:
2086 	fdput(cfile);
2087 out_put_eventfd:
2088 	eventfd_ctx_put(event->eventfd);
2089 out_put_efile:
2090 	fdput(efile);
2091 out_kfree:
2092 	kfree(event);
2093 
2094 	return ret;
2095 }
2096 
memcg1_memcg_init(struct mem_cgroup * memcg)2097 void memcg1_memcg_init(struct mem_cgroup *memcg)
2098 {
2099 	INIT_LIST_HEAD(&memcg->oom_notify);
2100 	mutex_init(&memcg->thresholds_lock);
2101 	spin_lock_init(&memcg->move_lock);
2102 	INIT_LIST_HEAD(&memcg->event_list);
2103 	spin_lock_init(&memcg->event_list_lock);
2104 }
2105 
memcg1_css_offline(struct mem_cgroup * memcg)2106 void memcg1_css_offline(struct mem_cgroup *memcg)
2107 {
2108 	struct mem_cgroup_event *event, *tmp;
2109 
2110 	/*
2111 	 * Unregister events and notify userspace.
2112 	 * Notify userspace about cgroup removing only after rmdir of cgroup
2113 	 * directory to avoid race between userspace and kernelspace.
2114 	 */
2115 	spin_lock_irq(&memcg->event_list_lock);
2116 	list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
2117 		list_del_init(&event->list);
2118 		schedule_work(&event->remove);
2119 	}
2120 	spin_unlock_irq(&memcg->event_list_lock);
2121 }
2122 
2123 /*
2124  * Check OOM-Killer is already running under our hierarchy.
2125  * If someone is running, return false.
2126  */
mem_cgroup_oom_trylock(struct mem_cgroup * memcg)2127 static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
2128 {
2129 	struct mem_cgroup *iter, *failed = NULL;
2130 
2131 	spin_lock(&memcg_oom_lock);
2132 
2133 	for_each_mem_cgroup_tree(iter, memcg) {
2134 		if (iter->oom_lock) {
2135 			/*
2136 			 * this subtree of our hierarchy is already locked
2137 			 * so we cannot give a lock.
2138 			 */
2139 			failed = iter;
2140 			mem_cgroup_iter_break(memcg, iter);
2141 			break;
2142 		} else
2143 			iter->oom_lock = true;
2144 	}
2145 
2146 	if (failed) {
2147 		/*
2148 		 * OK, we failed to lock the whole subtree so we have
2149 		 * to clean up what we set up to the failing subtree
2150 		 */
2151 		for_each_mem_cgroup_tree(iter, memcg) {
2152 			if (iter == failed) {
2153 				mem_cgroup_iter_break(memcg, iter);
2154 				break;
2155 			}
2156 			iter->oom_lock = false;
2157 		}
2158 	} else
2159 		mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_);
2160 
2161 	spin_unlock(&memcg_oom_lock);
2162 
2163 	return !failed;
2164 }
2165 
mem_cgroup_oom_unlock(struct mem_cgroup * memcg)2166 static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
2167 {
2168 	struct mem_cgroup *iter;
2169 
2170 	spin_lock(&memcg_oom_lock);
2171 	mutex_release(&memcg_oom_lock_dep_map, _RET_IP_);
2172 	for_each_mem_cgroup_tree(iter, memcg)
2173 		iter->oom_lock = false;
2174 	spin_unlock(&memcg_oom_lock);
2175 }
2176 
mem_cgroup_mark_under_oom(struct mem_cgroup * memcg)2177 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
2178 {
2179 	struct mem_cgroup *iter;
2180 
2181 	spin_lock(&memcg_oom_lock);
2182 	for_each_mem_cgroup_tree(iter, memcg)
2183 		iter->under_oom++;
2184 	spin_unlock(&memcg_oom_lock);
2185 }
2186 
mem_cgroup_unmark_under_oom(struct mem_cgroup * memcg)2187 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
2188 {
2189 	struct mem_cgroup *iter;
2190 
2191 	/*
2192 	 * Be careful about under_oom underflows because a child memcg
2193 	 * could have been added after mem_cgroup_mark_under_oom.
2194 	 */
2195 	spin_lock(&memcg_oom_lock);
2196 	for_each_mem_cgroup_tree(iter, memcg)
2197 		if (iter->under_oom > 0)
2198 			iter->under_oom--;
2199 	spin_unlock(&memcg_oom_lock);
2200 }
2201 
2202 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
2203 
2204 struct oom_wait_info {
2205 	struct mem_cgroup *memcg;
2206 	wait_queue_entry_t	wait;
2207 };
2208 
memcg_oom_wake_function(wait_queue_entry_t * wait,unsigned mode,int sync,void * arg)2209 static int memcg_oom_wake_function(wait_queue_entry_t *wait,
2210 	unsigned mode, int sync, void *arg)
2211 {
2212 	struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
2213 	struct mem_cgroup *oom_wait_memcg;
2214 	struct oom_wait_info *oom_wait_info;
2215 
2216 	oom_wait_info = container_of(wait, struct oom_wait_info, wait);
2217 	oom_wait_memcg = oom_wait_info->memcg;
2218 
2219 	if (!mem_cgroup_is_descendant(wake_memcg, oom_wait_memcg) &&
2220 	    !mem_cgroup_is_descendant(oom_wait_memcg, wake_memcg))
2221 		return 0;
2222 	return autoremove_wake_function(wait, mode, sync, arg);
2223 }
2224 
memcg1_oom_recover(struct mem_cgroup * memcg)2225 void memcg1_oom_recover(struct mem_cgroup *memcg)
2226 {
2227 	/*
2228 	 * For the following lockless ->under_oom test, the only required
2229 	 * guarantee is that it must see the state asserted by an OOM when
2230 	 * this function is called as a result of userland actions
2231 	 * triggered by the notification of the OOM.  This is trivially
2232 	 * achieved by invoking mem_cgroup_mark_under_oom() before
2233 	 * triggering notification.
2234 	 */
2235 	if (memcg && memcg->under_oom)
2236 		__wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
2237 }
2238 
2239 /**
2240  * mem_cgroup_oom_synchronize - complete memcg OOM handling
2241  * @handle: actually kill/wait or just clean up the OOM state
2242  *
2243  * This has to be called at the end of a page fault if the memcg OOM
2244  * handler was enabled.
2245  *
2246  * Memcg supports userspace OOM handling where failed allocations must
2247  * sleep on a waitqueue until the userspace task resolves the
2248  * situation.  Sleeping directly in the charge context with all kinds
2249  * of locks held is not a good idea, instead we remember an OOM state
2250  * in the task and mem_cgroup_oom_synchronize() has to be called at
2251  * the end of the page fault to complete the OOM handling.
2252  *
2253  * Returns %true if an ongoing memcg OOM situation was detected and
2254  * completed, %false otherwise.
2255  */
mem_cgroup_oom_synchronize(bool handle)2256 bool mem_cgroup_oom_synchronize(bool handle)
2257 {
2258 	struct mem_cgroup *memcg = current->memcg_in_oom;
2259 	struct oom_wait_info owait;
2260 	bool locked;
2261 
2262 	/* OOM is global, do not handle */
2263 	if (!memcg)
2264 		return false;
2265 
2266 	if (!handle)
2267 		goto cleanup;
2268 
2269 	owait.memcg = memcg;
2270 	owait.wait.flags = 0;
2271 	owait.wait.func = memcg_oom_wake_function;
2272 	owait.wait.private = current;
2273 	INIT_LIST_HEAD(&owait.wait.entry);
2274 
2275 	prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
2276 	mem_cgroup_mark_under_oom(memcg);
2277 
2278 	locked = mem_cgroup_oom_trylock(memcg);
2279 
2280 	if (locked)
2281 		mem_cgroup_oom_notify(memcg);
2282 
2283 	schedule();
2284 	mem_cgroup_unmark_under_oom(memcg);
2285 	finish_wait(&memcg_oom_waitq, &owait.wait);
2286 
2287 	if (locked)
2288 		mem_cgroup_oom_unlock(memcg);
2289 cleanup:
2290 	current->memcg_in_oom = NULL;
2291 	css_put(&memcg->css);
2292 	return true;
2293 }
2294 
2295 
memcg1_oom_prepare(struct mem_cgroup * memcg,bool * locked)2296 bool memcg1_oom_prepare(struct mem_cgroup *memcg, bool *locked)
2297 {
2298 	/*
2299 	 * We are in the middle of the charge context here, so we
2300 	 * don't want to block when potentially sitting on a callstack
2301 	 * that holds all kinds of filesystem and mm locks.
2302 	 *
2303 	 * cgroup1 allows disabling the OOM killer and waiting for outside
2304 	 * handling until the charge can succeed; remember the context and put
2305 	 * the task to sleep at the end of the page fault when all locks are
2306 	 * released.
2307 	 *
2308 	 * On the other hand, in-kernel OOM killer allows for an async victim
2309 	 * memory reclaim (oom_reaper) and that means that we are not solely
2310 	 * relying on the oom victim to make a forward progress and we can
2311 	 * invoke the oom killer here.
2312 	 *
2313 	 * Please note that mem_cgroup_out_of_memory might fail to find a
2314 	 * victim and then we have to bail out from the charge path.
2315 	 */
2316 	if (READ_ONCE(memcg->oom_kill_disable)) {
2317 		if (current->in_user_fault) {
2318 			css_get(&memcg->css);
2319 			current->memcg_in_oom = memcg;
2320 		}
2321 		return false;
2322 	}
2323 
2324 	mem_cgroup_mark_under_oom(memcg);
2325 
2326 	*locked = mem_cgroup_oom_trylock(memcg);
2327 
2328 	if (*locked)
2329 		mem_cgroup_oom_notify(memcg);
2330 
2331 	mem_cgroup_unmark_under_oom(memcg);
2332 
2333 	return true;
2334 }
2335 
memcg1_oom_finish(struct mem_cgroup * memcg,bool locked)2336 void memcg1_oom_finish(struct mem_cgroup *memcg, bool locked)
2337 {
2338 	if (locked)
2339 		mem_cgroup_oom_unlock(memcg);
2340 }
2341 
2342 static DEFINE_MUTEX(memcg_max_mutex);
2343 
mem_cgroup_resize_max(struct mem_cgroup * memcg,unsigned long max,bool memsw)2344 static int mem_cgroup_resize_max(struct mem_cgroup *memcg,
2345 				 unsigned long max, bool memsw)
2346 {
2347 	bool enlarge = false;
2348 	bool drained = false;
2349 	int ret;
2350 	bool limits_invariant;
2351 	struct page_counter *counter = memsw ? &memcg->memsw : &memcg->memory;
2352 
2353 	do {
2354 		if (signal_pending(current)) {
2355 			ret = -EINTR;
2356 			break;
2357 		}
2358 
2359 		mutex_lock(&memcg_max_mutex);
2360 		/*
2361 		 * Make sure that the new limit (memsw or memory limit) doesn't
2362 		 * break our basic invariant rule memory.max <= memsw.max.
2363 		 */
2364 		limits_invariant = memsw ? max >= READ_ONCE(memcg->memory.max) :
2365 					   max <= memcg->memsw.max;
2366 		if (!limits_invariant) {
2367 			mutex_unlock(&memcg_max_mutex);
2368 			ret = -EINVAL;
2369 			break;
2370 		}
2371 		if (max > counter->max)
2372 			enlarge = true;
2373 		ret = page_counter_set_max(counter, max);
2374 		mutex_unlock(&memcg_max_mutex);
2375 
2376 		if (!ret)
2377 			break;
2378 
2379 		if (!drained) {
2380 			drain_all_stock(memcg);
2381 			drained = true;
2382 			continue;
2383 		}
2384 
2385 		if (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL,
2386 				memsw ? 0 : MEMCG_RECLAIM_MAY_SWAP, NULL)) {
2387 			ret = -EBUSY;
2388 			break;
2389 		}
2390 	} while (true);
2391 
2392 	if (!ret && enlarge)
2393 		memcg1_oom_recover(memcg);
2394 
2395 	return ret;
2396 }
2397 
2398 /*
2399  * Reclaims as many pages from the given memcg as possible.
2400  *
2401  * Caller is responsible for holding css reference for memcg.
2402  */
mem_cgroup_force_empty(struct mem_cgroup * memcg)2403 static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
2404 {
2405 	int nr_retries = MAX_RECLAIM_RETRIES;
2406 
2407 	/* we call try-to-free pages for make this cgroup empty */
2408 	lru_add_drain_all();
2409 
2410 	drain_all_stock(memcg);
2411 
2412 	/* try to free all pages in this cgroup */
2413 	while (nr_retries && page_counter_read(&memcg->memory)) {
2414 		if (signal_pending(current))
2415 			return -EINTR;
2416 
2417 		if (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL,
2418 						  MEMCG_RECLAIM_MAY_SWAP, NULL))
2419 			nr_retries--;
2420 	}
2421 
2422 	return 0;
2423 }
2424 
mem_cgroup_force_empty_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)2425 static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
2426 					    char *buf, size_t nbytes,
2427 					    loff_t off)
2428 {
2429 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
2430 
2431 	if (mem_cgroup_is_root(memcg))
2432 		return -EINVAL;
2433 	return mem_cgroup_force_empty(memcg) ?: nbytes;
2434 }
2435 
mem_cgroup_hierarchy_read(struct cgroup_subsys_state * css,struct cftype * cft)2436 static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
2437 				     struct cftype *cft)
2438 {
2439 	return 1;
2440 }
2441 
mem_cgroup_hierarchy_write(struct cgroup_subsys_state * css,struct cftype * cft,u64 val)2442 static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
2443 				      struct cftype *cft, u64 val)
2444 {
2445 	if (val == 1)
2446 		return 0;
2447 
2448 	pr_warn_once("Non-hierarchical mode is deprecated. "
2449 		     "Please report your usecase to linux-mm@kvack.org if you "
2450 		     "depend on this functionality.\n");
2451 
2452 	return -EINVAL;
2453 }
2454 
mem_cgroup_read_u64(struct cgroup_subsys_state * css,struct cftype * cft)2455 static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
2456 			       struct cftype *cft)
2457 {
2458 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
2459 	struct page_counter *counter;
2460 
2461 	switch (MEMFILE_TYPE(cft->private)) {
2462 	case _MEM:
2463 		counter = &memcg->memory;
2464 		break;
2465 	case _MEMSWAP:
2466 		counter = &memcg->memsw;
2467 		break;
2468 	case _KMEM:
2469 		counter = &memcg->kmem;
2470 		break;
2471 	case _TCP:
2472 		counter = &memcg->tcpmem;
2473 		break;
2474 	default:
2475 		BUG();
2476 	}
2477 
2478 	switch (MEMFILE_ATTR(cft->private)) {
2479 	case RES_USAGE:
2480 		if (counter == &memcg->memory)
2481 			return (u64)mem_cgroup_usage(memcg, false) * PAGE_SIZE;
2482 		if (counter == &memcg->memsw)
2483 			return (u64)mem_cgroup_usage(memcg, true) * PAGE_SIZE;
2484 		return (u64)page_counter_read(counter) * PAGE_SIZE;
2485 	case RES_LIMIT:
2486 		return (u64)counter->max * PAGE_SIZE;
2487 	case RES_MAX_USAGE:
2488 		return (u64)counter->watermark * PAGE_SIZE;
2489 	case RES_FAILCNT:
2490 		return counter->failcnt;
2491 	case RES_SOFT_LIMIT:
2492 		return (u64)READ_ONCE(memcg->soft_limit) * PAGE_SIZE;
2493 	default:
2494 		BUG();
2495 	}
2496 }
2497 
2498 /*
2499  * This function doesn't do anything useful. Its only job is to provide a read
2500  * handler for a file so that cgroup_file_mode() will add read permissions.
2501  */
mem_cgroup_dummy_seq_show(__always_unused struct seq_file * m,__always_unused void * v)2502 static int mem_cgroup_dummy_seq_show(__always_unused struct seq_file *m,
2503 				     __always_unused void *v)
2504 {
2505 	return -EINVAL;
2506 }
2507 
memcg_update_tcp_max(struct mem_cgroup * memcg,unsigned long max)2508 static int memcg_update_tcp_max(struct mem_cgroup *memcg, unsigned long max)
2509 {
2510 	int ret;
2511 
2512 	mutex_lock(&memcg_max_mutex);
2513 
2514 	ret = page_counter_set_max(&memcg->tcpmem, max);
2515 	if (ret)
2516 		goto out;
2517 
2518 	if (!memcg->tcpmem_active) {
2519 		/*
2520 		 * The active flag needs to be written after the static_key
2521 		 * update. This is what guarantees that the socket activation
2522 		 * function is the last one to run. See mem_cgroup_sk_alloc()
2523 		 * for details, and note that we don't mark any socket as
2524 		 * belonging to this memcg until that flag is up.
2525 		 *
2526 		 * We need to do this, because static_keys will span multiple
2527 		 * sites, but we can't control their order. If we mark a socket
2528 		 * as accounted, but the accounting functions are not patched in
2529 		 * yet, we'll lose accounting.
2530 		 *
2531 		 * We never race with the readers in mem_cgroup_sk_alloc(),
2532 		 * because when this value change, the code to process it is not
2533 		 * patched in yet.
2534 		 */
2535 		static_branch_inc(&memcg_sockets_enabled_key);
2536 		memcg->tcpmem_active = true;
2537 	}
2538 out:
2539 	mutex_unlock(&memcg_max_mutex);
2540 	return ret;
2541 }
2542 
2543 /*
2544  * The user of this function is...
2545  * RES_LIMIT.
2546  */
mem_cgroup_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)2547 static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
2548 				char *buf, size_t nbytes, loff_t off)
2549 {
2550 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
2551 	unsigned long nr_pages;
2552 	int ret;
2553 
2554 	buf = strstrip(buf);
2555 	ret = page_counter_memparse(buf, "-1", &nr_pages);
2556 	if (ret)
2557 		return ret;
2558 
2559 	switch (MEMFILE_ATTR(of_cft(of)->private)) {
2560 	case RES_LIMIT:
2561 		if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
2562 			ret = -EINVAL;
2563 			break;
2564 		}
2565 		switch (MEMFILE_TYPE(of_cft(of)->private)) {
2566 		case _MEM:
2567 			ret = mem_cgroup_resize_max(memcg, nr_pages, false);
2568 			break;
2569 		case _MEMSWAP:
2570 			ret = mem_cgroup_resize_max(memcg, nr_pages, true);
2571 			break;
2572 		case _KMEM:
2573 			pr_warn_once("kmem.limit_in_bytes is deprecated and will be removed. "
2574 				     "Writing any value to this file has no effect. "
2575 				     "Please report your usecase to linux-mm@kvack.org if you "
2576 				     "depend on this functionality.\n");
2577 			ret = 0;
2578 			break;
2579 		case _TCP:
2580 			pr_warn_once("kmem.tcp.limit_in_bytes is deprecated and will be removed. "
2581 				     "Please report your usecase to linux-mm@kvack.org if you "
2582 				     "depend on this functionality.\n");
2583 			ret = memcg_update_tcp_max(memcg, nr_pages);
2584 			break;
2585 		}
2586 		break;
2587 	case RES_SOFT_LIMIT:
2588 		if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
2589 			ret = -EOPNOTSUPP;
2590 		} else {
2591 			pr_warn_once("soft_limit_in_bytes is deprecated and will be removed. "
2592 				     "Please report your usecase to linux-mm@kvack.org if you "
2593 				     "depend on this functionality.\n");
2594 			WRITE_ONCE(memcg->soft_limit, nr_pages);
2595 			ret = 0;
2596 		}
2597 		break;
2598 	}
2599 	return ret ?: nbytes;
2600 }
2601 
mem_cgroup_reset(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)2602 static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
2603 				size_t nbytes, loff_t off)
2604 {
2605 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
2606 	struct page_counter *counter;
2607 
2608 	switch (MEMFILE_TYPE(of_cft(of)->private)) {
2609 	case _MEM:
2610 		counter = &memcg->memory;
2611 		break;
2612 	case _MEMSWAP:
2613 		counter = &memcg->memsw;
2614 		break;
2615 	case _KMEM:
2616 		counter = &memcg->kmem;
2617 		break;
2618 	case _TCP:
2619 		counter = &memcg->tcpmem;
2620 		break;
2621 	default:
2622 		BUG();
2623 	}
2624 
2625 	switch (MEMFILE_ATTR(of_cft(of)->private)) {
2626 	case RES_MAX_USAGE:
2627 		page_counter_reset_watermark(counter);
2628 		break;
2629 	case RES_FAILCNT:
2630 		counter->failcnt = 0;
2631 		break;
2632 	default:
2633 		BUG();
2634 	}
2635 
2636 	return nbytes;
2637 }
2638 
2639 #ifdef CONFIG_NUMA
2640 
2641 #define LRU_ALL_FILE (BIT(LRU_INACTIVE_FILE) | BIT(LRU_ACTIVE_FILE))
2642 #define LRU_ALL_ANON (BIT(LRU_INACTIVE_ANON) | BIT(LRU_ACTIVE_ANON))
2643 #define LRU_ALL	     ((1 << NR_LRU_LISTS) - 1)
2644 
mem_cgroup_node_nr_lru_pages(struct mem_cgroup * memcg,int nid,unsigned int lru_mask,bool tree)2645 static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
2646 				int nid, unsigned int lru_mask, bool tree)
2647 {
2648 	struct lruvec *lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
2649 	unsigned long nr = 0;
2650 	enum lru_list lru;
2651 
2652 	VM_BUG_ON((unsigned)nid >= nr_node_ids);
2653 
2654 	for_each_lru(lru) {
2655 		if (!(BIT(lru) & lru_mask))
2656 			continue;
2657 		if (tree)
2658 			nr += lruvec_page_state(lruvec, NR_LRU_BASE + lru);
2659 		else
2660 			nr += lruvec_page_state_local(lruvec, NR_LRU_BASE + lru);
2661 	}
2662 	return nr;
2663 }
2664 
mem_cgroup_nr_lru_pages(struct mem_cgroup * memcg,unsigned int lru_mask,bool tree)2665 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
2666 					     unsigned int lru_mask,
2667 					     bool tree)
2668 {
2669 	unsigned long nr = 0;
2670 	enum lru_list lru;
2671 
2672 	for_each_lru(lru) {
2673 		if (!(BIT(lru) & lru_mask))
2674 			continue;
2675 		if (tree)
2676 			nr += memcg_page_state(memcg, NR_LRU_BASE + lru);
2677 		else
2678 			nr += memcg_page_state_local(memcg, NR_LRU_BASE + lru);
2679 	}
2680 	return nr;
2681 }
2682 
memcg_numa_stat_show(struct seq_file * m,void * v)2683 static int memcg_numa_stat_show(struct seq_file *m, void *v)
2684 {
2685 	struct numa_stat {
2686 		const char *name;
2687 		unsigned int lru_mask;
2688 	};
2689 
2690 	static const struct numa_stat stats[] = {
2691 		{ "total", LRU_ALL },
2692 		{ "file", LRU_ALL_FILE },
2693 		{ "anon", LRU_ALL_ANON },
2694 		{ "unevictable", BIT(LRU_UNEVICTABLE) },
2695 	};
2696 	const struct numa_stat *stat;
2697 	int nid;
2698 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
2699 
2700 	mem_cgroup_flush_stats(memcg);
2701 
2702 	for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
2703 		seq_printf(m, "%s=%lu", stat->name,
2704 			   mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
2705 						   false));
2706 		for_each_node_state(nid, N_MEMORY)
2707 			seq_printf(m, " N%d=%lu", nid,
2708 				   mem_cgroup_node_nr_lru_pages(memcg, nid,
2709 							stat->lru_mask, false));
2710 		seq_putc(m, '\n');
2711 	}
2712 
2713 	for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
2714 
2715 		seq_printf(m, "hierarchical_%s=%lu", stat->name,
2716 			   mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
2717 						   true));
2718 		for_each_node_state(nid, N_MEMORY)
2719 			seq_printf(m, " N%d=%lu", nid,
2720 				   mem_cgroup_node_nr_lru_pages(memcg, nid,
2721 							stat->lru_mask, true));
2722 		seq_putc(m, '\n');
2723 	}
2724 
2725 	return 0;
2726 }
2727 #endif /* CONFIG_NUMA */
2728 
2729 static const unsigned int memcg1_stats[] = {
2730 	NR_FILE_PAGES,
2731 	NR_ANON_MAPPED,
2732 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
2733 	NR_ANON_THPS,
2734 #endif
2735 	NR_SHMEM,
2736 	NR_FILE_MAPPED,
2737 	NR_FILE_DIRTY,
2738 	NR_WRITEBACK,
2739 	WORKINGSET_REFAULT_ANON,
2740 	WORKINGSET_REFAULT_FILE,
2741 #ifdef CONFIG_SWAP
2742 	MEMCG_SWAP,
2743 	NR_SWAPCACHE,
2744 #endif
2745 };
2746 
2747 static const char *const memcg1_stat_names[] = {
2748 	"cache",
2749 	"rss",
2750 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
2751 	"rss_huge",
2752 #endif
2753 	"shmem",
2754 	"mapped_file",
2755 	"dirty",
2756 	"writeback",
2757 	"workingset_refault_anon",
2758 	"workingset_refault_file",
2759 #ifdef CONFIG_SWAP
2760 	"swap",
2761 	"swapcached",
2762 #endif
2763 };
2764 
2765 /* Universal VM events cgroup1 shows, original sort order */
2766 static const unsigned int memcg1_events[] = {
2767 	PGPGIN,
2768 	PGPGOUT,
2769 	PGFAULT,
2770 	PGMAJFAULT,
2771 };
2772 
memcg1_stat_format(struct mem_cgroup * memcg,struct seq_buf * s)2773 void memcg1_stat_format(struct mem_cgroup *memcg, struct seq_buf *s)
2774 {
2775 	unsigned long memory, memsw;
2776 	struct mem_cgroup *mi;
2777 	unsigned int i;
2778 
2779 	BUILD_BUG_ON(ARRAY_SIZE(memcg1_stat_names) != ARRAY_SIZE(memcg1_stats));
2780 
2781 	mem_cgroup_flush_stats(memcg);
2782 
2783 	for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
2784 		unsigned long nr;
2785 
2786 		nr = memcg_page_state_local_output(memcg, memcg1_stats[i]);
2787 		seq_buf_printf(s, "%s %lu\n", memcg1_stat_names[i], nr);
2788 	}
2789 
2790 	for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
2791 		seq_buf_printf(s, "%s %lu\n", vm_event_name(memcg1_events[i]),
2792 			       memcg_events_local(memcg, memcg1_events[i]));
2793 
2794 	for (i = 0; i < NR_LRU_LISTS; i++)
2795 		seq_buf_printf(s, "%s %lu\n", lru_list_name(i),
2796 			       memcg_page_state_local(memcg, NR_LRU_BASE + i) *
2797 			       PAGE_SIZE);
2798 
2799 	/* Hierarchical information */
2800 	memory = memsw = PAGE_COUNTER_MAX;
2801 	for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
2802 		memory = min(memory, READ_ONCE(mi->memory.max));
2803 		memsw = min(memsw, READ_ONCE(mi->memsw.max));
2804 	}
2805 	seq_buf_printf(s, "hierarchical_memory_limit %llu\n",
2806 		       (u64)memory * PAGE_SIZE);
2807 	seq_buf_printf(s, "hierarchical_memsw_limit %llu\n",
2808 		       (u64)memsw * PAGE_SIZE);
2809 
2810 	for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
2811 		unsigned long nr;
2812 
2813 		nr = memcg_page_state_output(memcg, memcg1_stats[i]);
2814 		seq_buf_printf(s, "total_%s %llu\n", memcg1_stat_names[i],
2815 			       (u64)nr);
2816 	}
2817 
2818 	for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
2819 		seq_buf_printf(s, "total_%s %llu\n",
2820 			       vm_event_name(memcg1_events[i]),
2821 			       (u64)memcg_events(memcg, memcg1_events[i]));
2822 
2823 	for (i = 0; i < NR_LRU_LISTS; i++)
2824 		seq_buf_printf(s, "total_%s %llu\n", lru_list_name(i),
2825 			       (u64)memcg_page_state(memcg, NR_LRU_BASE + i) *
2826 			       PAGE_SIZE);
2827 
2828 #ifdef CONFIG_DEBUG_VM
2829 	{
2830 		pg_data_t *pgdat;
2831 		struct mem_cgroup_per_node *mz;
2832 		unsigned long anon_cost = 0;
2833 		unsigned long file_cost = 0;
2834 
2835 		for_each_online_pgdat(pgdat) {
2836 			mz = memcg->nodeinfo[pgdat->node_id];
2837 
2838 			anon_cost += mz->lruvec.anon_cost;
2839 			file_cost += mz->lruvec.file_cost;
2840 		}
2841 		seq_buf_printf(s, "anon_cost %lu\n", anon_cost);
2842 		seq_buf_printf(s, "file_cost %lu\n", file_cost);
2843 	}
2844 #endif
2845 }
2846 
mem_cgroup_swappiness_read(struct cgroup_subsys_state * css,struct cftype * cft)2847 static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
2848 				      struct cftype *cft)
2849 {
2850 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
2851 
2852 	return mem_cgroup_swappiness(memcg);
2853 }
2854 
mem_cgroup_swappiness_write(struct cgroup_subsys_state * css,struct cftype * cft,u64 val)2855 static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
2856 				       struct cftype *cft, u64 val)
2857 {
2858 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
2859 
2860 	if (val > MAX_SWAPPINESS)
2861 		return -EINVAL;
2862 
2863 	if (!mem_cgroup_is_root(memcg))
2864 		WRITE_ONCE(memcg->swappiness, val);
2865 	else
2866 		WRITE_ONCE(vm_swappiness, val);
2867 
2868 	return 0;
2869 }
2870 
mem_cgroup_oom_control_read(struct seq_file * sf,void * v)2871 static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
2872 {
2873 	struct mem_cgroup *memcg = mem_cgroup_from_seq(sf);
2874 
2875 	seq_printf(sf, "oom_kill_disable %d\n", READ_ONCE(memcg->oom_kill_disable));
2876 	seq_printf(sf, "under_oom %d\n", (bool)memcg->under_oom);
2877 	seq_printf(sf, "oom_kill %lu\n",
2878 		   atomic_long_read(&memcg->memory_events[MEMCG_OOM_KILL]));
2879 	return 0;
2880 }
2881 
mem_cgroup_oom_control_write(struct cgroup_subsys_state * css,struct cftype * cft,u64 val)2882 static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
2883 	struct cftype *cft, u64 val)
2884 {
2885 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
2886 
2887 	pr_warn_once("oom_control is deprecated and will be removed. "
2888 		     "Please report your usecase to linux-mm-@kvack.org if you "
2889 		     "depend on this functionality. \n");
2890 
2891 	/* cannot set to root cgroup and only 0 and 1 are allowed */
2892 	if (mem_cgroup_is_root(memcg) || !((val == 0) || (val == 1)))
2893 		return -EINVAL;
2894 
2895 	WRITE_ONCE(memcg->oom_kill_disable, val);
2896 	if (!val)
2897 		memcg1_oom_recover(memcg);
2898 
2899 	return 0;
2900 }
2901 
2902 #ifdef CONFIG_SLUB_DEBUG
mem_cgroup_slab_show(struct seq_file * m,void * p)2903 static int mem_cgroup_slab_show(struct seq_file *m, void *p)
2904 {
2905 	/*
2906 	 * Deprecated.
2907 	 * Please, take a look at tools/cgroup/memcg_slabinfo.py .
2908 	 */
2909 	return 0;
2910 }
2911 #endif
2912 
2913 struct cftype mem_cgroup_legacy_files[] = {
2914 	{
2915 		.name = "usage_in_bytes",
2916 		.private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
2917 		.read_u64 = mem_cgroup_read_u64,
2918 	},
2919 	{
2920 		.name = "max_usage_in_bytes",
2921 		.private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
2922 		.write = mem_cgroup_reset,
2923 		.read_u64 = mem_cgroup_read_u64,
2924 	},
2925 	{
2926 		.name = "limit_in_bytes",
2927 		.private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
2928 		.write = mem_cgroup_write,
2929 		.read_u64 = mem_cgroup_read_u64,
2930 	},
2931 	{
2932 		.name = "soft_limit_in_bytes",
2933 		.private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
2934 		.write = mem_cgroup_write,
2935 		.read_u64 = mem_cgroup_read_u64,
2936 	},
2937 	{
2938 		.name = "failcnt",
2939 		.private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
2940 		.write = mem_cgroup_reset,
2941 		.read_u64 = mem_cgroup_read_u64,
2942 	},
2943 	{
2944 		.name = "stat",
2945 		.seq_show = memory_stat_show,
2946 	},
2947 	{
2948 		.name = "force_empty",
2949 		.write = mem_cgroup_force_empty_write,
2950 	},
2951 	{
2952 		.name = "use_hierarchy",
2953 		.write_u64 = mem_cgroup_hierarchy_write,
2954 		.read_u64 = mem_cgroup_hierarchy_read,
2955 	},
2956 	{
2957 		.name = "cgroup.event_control",		/* XXX: for compat */
2958 		.write = memcg_write_event_control,
2959 		.flags = CFTYPE_NO_PREFIX | CFTYPE_WORLD_WRITABLE,
2960 	},
2961 	{
2962 		.name = "swappiness",
2963 		.read_u64 = mem_cgroup_swappiness_read,
2964 		.write_u64 = mem_cgroup_swappiness_write,
2965 	},
2966 	{
2967 		.name = "move_charge_at_immigrate",
2968 		.read_u64 = mem_cgroup_move_charge_read,
2969 		.write_u64 = mem_cgroup_move_charge_write,
2970 	},
2971 	{
2972 		.name = "oom_control",
2973 		.seq_show = mem_cgroup_oom_control_read,
2974 		.write_u64 = mem_cgroup_oom_control_write,
2975 	},
2976 	{
2977 		.name = "pressure_level",
2978 		.seq_show = mem_cgroup_dummy_seq_show,
2979 	},
2980 #ifdef CONFIG_NUMA
2981 	{
2982 		.name = "numa_stat",
2983 		.seq_show = memcg_numa_stat_show,
2984 	},
2985 #endif
2986 	{
2987 		.name = "kmem.limit_in_bytes",
2988 		.private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
2989 		.write = mem_cgroup_write,
2990 		.read_u64 = mem_cgroup_read_u64,
2991 	},
2992 	{
2993 		.name = "kmem.usage_in_bytes",
2994 		.private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
2995 		.read_u64 = mem_cgroup_read_u64,
2996 	},
2997 	{
2998 		.name = "kmem.failcnt",
2999 		.private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
3000 		.write = mem_cgroup_reset,
3001 		.read_u64 = mem_cgroup_read_u64,
3002 	},
3003 	{
3004 		.name = "kmem.max_usage_in_bytes",
3005 		.private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
3006 		.write = mem_cgroup_reset,
3007 		.read_u64 = mem_cgroup_read_u64,
3008 	},
3009 #ifdef CONFIG_SLUB_DEBUG
3010 	{
3011 		.name = "kmem.slabinfo",
3012 		.seq_show = mem_cgroup_slab_show,
3013 	},
3014 #endif
3015 	{
3016 		.name = "kmem.tcp.limit_in_bytes",
3017 		.private = MEMFILE_PRIVATE(_TCP, RES_LIMIT),
3018 		.write = mem_cgroup_write,
3019 		.read_u64 = mem_cgroup_read_u64,
3020 	},
3021 	{
3022 		.name = "kmem.tcp.usage_in_bytes",
3023 		.private = MEMFILE_PRIVATE(_TCP, RES_USAGE),
3024 		.read_u64 = mem_cgroup_read_u64,
3025 	},
3026 	{
3027 		.name = "kmem.tcp.failcnt",
3028 		.private = MEMFILE_PRIVATE(_TCP, RES_FAILCNT),
3029 		.write = mem_cgroup_reset,
3030 		.read_u64 = mem_cgroup_read_u64,
3031 	},
3032 	{
3033 		.name = "kmem.tcp.max_usage_in_bytes",
3034 		.private = MEMFILE_PRIVATE(_TCP, RES_MAX_USAGE),
3035 		.write = mem_cgroup_reset,
3036 		.read_u64 = mem_cgroup_read_u64,
3037 	},
3038 	{ },	/* terminate */
3039 };
3040 
3041 struct cftype memsw_files[] = {
3042 	{
3043 		.name = "memsw.usage_in_bytes",
3044 		.private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
3045 		.read_u64 = mem_cgroup_read_u64,
3046 	},
3047 	{
3048 		.name = "memsw.max_usage_in_bytes",
3049 		.private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
3050 		.write = mem_cgroup_reset,
3051 		.read_u64 = mem_cgroup_read_u64,
3052 	},
3053 	{
3054 		.name = "memsw.limit_in_bytes",
3055 		.private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
3056 		.write = mem_cgroup_write,
3057 		.read_u64 = mem_cgroup_read_u64,
3058 	},
3059 	{
3060 		.name = "memsw.failcnt",
3061 		.private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
3062 		.write = mem_cgroup_reset,
3063 		.read_u64 = mem_cgroup_read_u64,
3064 	},
3065 	{ },	/* terminate */
3066 };
3067 
memcg1_account_kmem(struct mem_cgroup * memcg,int nr_pages)3068 void memcg1_account_kmem(struct mem_cgroup *memcg, int nr_pages)
3069 {
3070 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
3071 		if (nr_pages > 0)
3072 			page_counter_charge(&memcg->kmem, nr_pages);
3073 		else
3074 			page_counter_uncharge(&memcg->kmem, -nr_pages);
3075 	}
3076 }
3077 
memcg1_charge_skmem(struct mem_cgroup * memcg,unsigned int nr_pages,gfp_t gfp_mask)3078 bool memcg1_charge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages,
3079 			 gfp_t gfp_mask)
3080 {
3081 	struct page_counter *fail;
3082 
3083 	if (page_counter_try_charge(&memcg->tcpmem, nr_pages, &fail)) {
3084 		memcg->tcpmem_pressure = 0;
3085 		return true;
3086 	}
3087 	memcg->tcpmem_pressure = 1;
3088 	if (gfp_mask & __GFP_NOFAIL) {
3089 		page_counter_charge(&memcg->tcpmem, nr_pages);
3090 		return true;
3091 	}
3092 	return false;
3093 }
3094 
memcg1_alloc_events(struct mem_cgroup * memcg)3095 bool memcg1_alloc_events(struct mem_cgroup *memcg)
3096 {
3097 	memcg->events_percpu = alloc_percpu_gfp(struct memcg1_events_percpu,
3098 						GFP_KERNEL_ACCOUNT);
3099 	return !!memcg->events_percpu;
3100 }
3101 
memcg1_free_events(struct mem_cgroup * memcg)3102 void memcg1_free_events(struct mem_cgroup *memcg)
3103 {
3104 	if (memcg->events_percpu)
3105 		free_percpu(memcg->events_percpu);
3106 }
3107 
memcg1_init(void)3108 static int __init memcg1_init(void)
3109 {
3110 	int node;
3111 
3112 	for_each_node(node) {
3113 		struct mem_cgroup_tree_per_node *rtpn;
3114 
3115 		rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, node);
3116 
3117 		rtpn->rb_root = RB_ROOT;
3118 		rtpn->rb_rightmost = NULL;
3119 		spin_lock_init(&rtpn->lock);
3120 		soft_limit_tree.rb_tree_per_node[node] = rtpn;
3121 	}
3122 
3123 	return 0;
3124 }
3125 subsys_initcall(memcg1_init);
3126