memcg: cpu hotplug aware percpu count updates
[deliverable/linux.git] / mm / memcontrol.c
1 /* memcontrol.c - Memory Controller
2 *
3 * Copyright IBM Corporation, 2007
4 * Author Balbir Singh <balbir@linux.vnet.ibm.com>
5 *
6 * Copyright 2007 OpenVZ SWsoft Inc
7 * Author: Pavel Emelianov <xemul@openvz.org>
8 *
9 * Memory thresholds
10 * Copyright (C) 2009 Nokia Corporation
11 * Author: Kirill A. Shutemov
12 *
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
17 *
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
22 */
23
24 #include <linux/res_counter.h>
25 #include <linux/memcontrol.h>
26 #include <linux/cgroup.h>
27 #include <linux/mm.h>
28 #include <linux/hugetlb.h>
29 #include <linux/pagemap.h>
30 #include <linux/smp.h>
31 #include <linux/page-flags.h>
32 #include <linux/backing-dev.h>
33 #include <linux/bit_spinlock.h>
34 #include <linux/rcupdate.h>
35 #include <linux/limits.h>
36 #include <linux/mutex.h>
37 #include <linux/rbtree.h>
38 #include <linux/slab.h>
39 #include <linux/swap.h>
40 #include <linux/swapops.h>
41 #include <linux/spinlock.h>
42 #include <linux/eventfd.h>
43 #include <linux/sort.h>
44 #include <linux/fs.h>
45 #include <linux/seq_file.h>
46 #include <linux/vmalloc.h>
47 #include <linux/mm_inline.h>
48 #include <linux/page_cgroup.h>
49 #include <linux/cpu.h>
50 #include <linux/oom.h>
51 #include "internal.h"
52
53 #include <asm/uaccess.h>
54
55 #include <trace/events/vmscan.h>
56
57 struct cgroup_subsys mem_cgroup_subsys __read_mostly;
58 #define MEM_CGROUP_RECLAIM_RETRIES 5
59 struct mem_cgroup *root_mem_cgroup __read_mostly;
60
61 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
62 /* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
63 int do_swap_account __read_mostly;
64 static int really_do_swap_account __initdata = 1; /* for remember boot option*/
65 #else
66 #define do_swap_account (0)
67 #endif
68
69 /*
70 * Per memcg event counter is incremented at every pagein/pageout. This counter
71 * is used for trigger some periodic events. This is straightforward and better
72 * than using jiffies etc. to handle periodic memcg event.
73 *
74 * These values will be used as !((event) & ((1 <<(thresh)) - 1))
75 */
76 #define THRESHOLDS_EVENTS_THRESH (7) /* once in 128 */
77 #define SOFTLIMIT_EVENTS_THRESH (10) /* once in 1024 */
78
79 /*
80 * Statistics for memory cgroup.
81 */
82 enum mem_cgroup_stat_index {
83 /*
84 * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
85 */
86 MEM_CGROUP_STAT_CACHE, /* # of pages charged as cache */
87 MEM_CGROUP_STAT_RSS, /* # of pages charged as anon rss */
88 MEM_CGROUP_STAT_FILE_MAPPED, /* # of pages charged as file rss */
89 MEM_CGROUP_STAT_PGPGIN_COUNT, /* # of pages paged in */
90 MEM_CGROUP_STAT_PGPGOUT_COUNT, /* # of pages paged out */
91 MEM_CGROUP_STAT_SWAPOUT, /* # of pages, swapped out */
92 MEM_CGROUP_STAT_DATA, /* end of data requires synchronization */
93 /* incremented at every pagein/pageout */
94 MEM_CGROUP_EVENTS = MEM_CGROUP_STAT_DATA,
95 MEM_CGROUP_ON_MOVE, /* someone is moving account between groups */
96
97 MEM_CGROUP_STAT_NSTATS,
98 };
99
100 struct mem_cgroup_stat_cpu {
101 s64 count[MEM_CGROUP_STAT_NSTATS];
102 };
103
104 /*
105 * per-zone information in memory controller.
106 */
107 struct mem_cgroup_per_zone {
108 /*
109 * spin_lock to protect the per cgroup LRU
110 */
111 struct list_head lists[NR_LRU_LISTS];
112 unsigned long count[NR_LRU_LISTS];
113
114 struct zone_reclaim_stat reclaim_stat;
115 struct rb_node tree_node; /* RB tree node */
116 unsigned long long usage_in_excess;/* Set to the value by which */
117 /* the soft limit is exceeded*/
118 bool on_tree;
119 struct mem_cgroup *mem; /* Back pointer, we cannot */
120 /* use container_of */
121 };
122 /* Macro for accessing counter */
123 #define MEM_CGROUP_ZSTAT(mz, idx) ((mz)->count[(idx)])
124
125 struct mem_cgroup_per_node {
126 struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
127 };
128
129 struct mem_cgroup_lru_info {
130 struct mem_cgroup_per_node *nodeinfo[MAX_NUMNODES];
131 };
132
133 /*
134 * Cgroups above their limits are maintained in a RB-Tree, independent of
135 * their hierarchy representation
136 */
137
138 struct mem_cgroup_tree_per_zone {
139 struct rb_root rb_root;
140 spinlock_t lock;
141 };
142
143 struct mem_cgroup_tree_per_node {
144 struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
145 };
146
147 struct mem_cgroup_tree {
148 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
149 };
150
151 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
152
153 struct mem_cgroup_threshold {
154 struct eventfd_ctx *eventfd;
155 u64 threshold;
156 };
157
158 /* For threshold */
159 struct mem_cgroup_threshold_ary {
160 /* An array index points to threshold just below usage. */
161 int current_threshold;
162 /* Size of entries[] */
163 unsigned int size;
164 /* Array of thresholds */
165 struct mem_cgroup_threshold entries[0];
166 };
167
168 struct mem_cgroup_thresholds {
169 /* Primary thresholds array */
170 struct mem_cgroup_threshold_ary *primary;
171 /*
172 * Spare threshold array.
173 * This is needed to make mem_cgroup_unregister_event() "never fail".
174 * It must be able to store at least primary->size - 1 entries.
175 */
176 struct mem_cgroup_threshold_ary *spare;
177 };
178
179 /* for OOM */
180 struct mem_cgroup_eventfd_list {
181 struct list_head list;
182 struct eventfd_ctx *eventfd;
183 };
184
185 static void mem_cgroup_threshold(struct mem_cgroup *mem);
186 static void mem_cgroup_oom_notify(struct mem_cgroup *mem);
187
188 /*
189 * The memory controller data structure. The memory controller controls both
190 * page cache and RSS per cgroup. We would eventually like to provide
191 * statistics based on the statistics developed by Rik Van Riel for clock-pro,
192 * to help the administrator determine what knobs to tune.
193 *
194 * TODO: Add a water mark for the memory controller. Reclaim will begin when
195 * we hit the water mark. May be even add a low water mark, such that
196 * no reclaim occurs from a cgroup at it's low water mark, this is
197 * a feature that will be implemented much later in the future.
198 */
199 struct mem_cgroup {
200 struct cgroup_subsys_state css;
201 /*
202 * the counter to account for memory usage
203 */
204 struct res_counter res;
205 /*
206 * the counter to account for mem+swap usage.
207 */
208 struct res_counter memsw;
209 /*
210 * Per cgroup active and inactive list, similar to the
211 * per zone LRU lists.
212 */
213 struct mem_cgroup_lru_info info;
214
215 /*
216 protect against reclaim related member.
217 */
218 spinlock_t reclaim_param_lock;
219
220 /*
221 * While reclaiming in a hierarchy, we cache the last child we
222 * reclaimed from.
223 */
224 int last_scanned_child;
225 /*
226 * Should the accounting and control be hierarchical, per subtree?
227 */
228 bool use_hierarchy;
229 atomic_t oom_lock;
230 atomic_t refcnt;
231
232 unsigned int swappiness;
233 /* OOM-Killer disable */
234 int oom_kill_disable;
235
236 /* set when res.limit == memsw.limit */
237 bool memsw_is_minimum;
238
239 /* protect arrays of thresholds */
240 struct mutex thresholds_lock;
241
242 /* thresholds for memory usage. RCU-protected */
243 struct mem_cgroup_thresholds thresholds;
244
245 /* thresholds for mem+swap usage. RCU-protected */
246 struct mem_cgroup_thresholds memsw_thresholds;
247
248 /* For oom notifier event fd */
249 struct list_head oom_notify;
250
251 /*
252 * Should we move charges of a task when a task is moved into this
253 * mem_cgroup ? And what type of charges should we move ?
254 */
255 unsigned long move_charge_at_immigrate;
256 /*
257 * percpu counter.
258 */
259 struct mem_cgroup_stat_cpu *stat;
260 /*
261 * used when a cpu is offlined or other synchronizations
262 * See mem_cgroup_read_stat().
263 */
264 struct mem_cgroup_stat_cpu nocpu_base;
265 spinlock_t pcp_counter_lock;
266 };
267
268 /* Stuffs for move charges at task migration. */
269 /*
270 * Types of charges to be moved. "move_charge_at_immitgrate" is treated as a
271 * left-shifted bitmap of these types.
272 */
273 enum move_type {
274 MOVE_CHARGE_TYPE_ANON, /* private anonymous page and swap of it */
275 MOVE_CHARGE_TYPE_FILE, /* file page(including tmpfs) and swap of it */
276 NR_MOVE_TYPE,
277 };
278
279 /* "mc" and its members are protected by cgroup_mutex */
280 static struct move_charge_struct {
281 spinlock_t lock; /* for from, to, moving_task */
282 struct mem_cgroup *from;
283 struct mem_cgroup *to;
284 unsigned long precharge;
285 unsigned long moved_charge;
286 unsigned long moved_swap;
287 struct task_struct *moving_task; /* a task moving charges */
288 wait_queue_head_t waitq; /* a waitq for other context */
289 } mc = {
290 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
291 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
292 };
293
294 static bool move_anon(void)
295 {
296 return test_bit(MOVE_CHARGE_TYPE_ANON,
297 &mc.to->move_charge_at_immigrate);
298 }
299
300 static bool move_file(void)
301 {
302 return test_bit(MOVE_CHARGE_TYPE_FILE,
303 &mc.to->move_charge_at_immigrate);
304 }
305
306 /*
307 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
308 * limit reclaim to prevent infinite loops, if they ever occur.
309 */
310 #define MEM_CGROUP_MAX_RECLAIM_LOOPS (100)
311 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS (2)
312
313 enum charge_type {
314 MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
315 MEM_CGROUP_CHARGE_TYPE_MAPPED,
316 MEM_CGROUP_CHARGE_TYPE_SHMEM, /* used by page migration of shmem */
317 MEM_CGROUP_CHARGE_TYPE_FORCE, /* used by force_empty */
318 MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
319 MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
320 NR_CHARGE_TYPE,
321 };
322
323 /* only for here (for easy reading.) */
324 #define PCGF_CACHE (1UL << PCG_CACHE)
325 #define PCGF_USED (1UL << PCG_USED)
326 #define PCGF_LOCK (1UL << PCG_LOCK)
327 /* Not used, but added here for completeness */
328 #define PCGF_ACCT (1UL << PCG_ACCT)
329
330 /* for encoding cft->private value on file */
331 #define _MEM (0)
332 #define _MEMSWAP (1)
333 #define _OOM_TYPE (2)
334 #define MEMFILE_PRIVATE(x, val) (((x) << 16) | (val))
335 #define MEMFILE_TYPE(val) (((val) >> 16) & 0xffff)
336 #define MEMFILE_ATTR(val) ((val) & 0xffff)
337 /* Used for OOM nofiier */
338 #define OOM_CONTROL (0)
339
340 /*
341 * Reclaim flags for mem_cgroup_hierarchical_reclaim
342 */
343 #define MEM_CGROUP_RECLAIM_NOSWAP_BIT 0x0
344 #define MEM_CGROUP_RECLAIM_NOSWAP (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
345 #define MEM_CGROUP_RECLAIM_SHRINK_BIT 0x1
346 #define MEM_CGROUP_RECLAIM_SHRINK (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
347 #define MEM_CGROUP_RECLAIM_SOFT_BIT 0x2
348 #define MEM_CGROUP_RECLAIM_SOFT (1 << MEM_CGROUP_RECLAIM_SOFT_BIT)
349
350 static void mem_cgroup_get(struct mem_cgroup *mem);
351 static void mem_cgroup_put(struct mem_cgroup *mem);
352 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem);
353 static void drain_all_stock_async(void);
354
355 static struct mem_cgroup_per_zone *
356 mem_cgroup_zoneinfo(struct mem_cgroup *mem, int nid, int zid)
357 {
358 return &mem->info.nodeinfo[nid]->zoneinfo[zid];
359 }
360
361 struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *mem)
362 {
363 return &mem->css;
364 }
365
366 static struct mem_cgroup_per_zone *
367 page_cgroup_zoneinfo(struct page_cgroup *pc)
368 {
369 struct mem_cgroup *mem = pc->mem_cgroup;
370 int nid = page_cgroup_nid(pc);
371 int zid = page_cgroup_zid(pc);
372
373 if (!mem)
374 return NULL;
375
376 return mem_cgroup_zoneinfo(mem, nid, zid);
377 }
378
379 static struct mem_cgroup_tree_per_zone *
380 soft_limit_tree_node_zone(int nid, int zid)
381 {
382 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
383 }
384
385 static struct mem_cgroup_tree_per_zone *
386 soft_limit_tree_from_page(struct page *page)
387 {
388 int nid = page_to_nid(page);
389 int zid = page_zonenum(page);
390
391 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
392 }
393
394 static void
395 __mem_cgroup_insert_exceeded(struct mem_cgroup *mem,
396 struct mem_cgroup_per_zone *mz,
397 struct mem_cgroup_tree_per_zone *mctz,
398 unsigned long long new_usage_in_excess)
399 {
400 struct rb_node **p = &mctz->rb_root.rb_node;
401 struct rb_node *parent = NULL;
402 struct mem_cgroup_per_zone *mz_node;
403
404 if (mz->on_tree)
405 return;
406
407 mz->usage_in_excess = new_usage_in_excess;
408 if (!mz->usage_in_excess)
409 return;
410 while (*p) {
411 parent = *p;
412 mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
413 tree_node);
414 if (mz->usage_in_excess < mz_node->usage_in_excess)
415 p = &(*p)->rb_left;
416 /*
417 * We can't avoid mem cgroups that are over their soft
418 * limit by the same amount
419 */
420 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
421 p = &(*p)->rb_right;
422 }
423 rb_link_node(&mz->tree_node, parent, p);
424 rb_insert_color(&mz->tree_node, &mctz->rb_root);
425 mz->on_tree = true;
426 }
427
428 static void
429 __mem_cgroup_remove_exceeded(struct mem_cgroup *mem,
430 struct mem_cgroup_per_zone *mz,
431 struct mem_cgroup_tree_per_zone *mctz)
432 {
433 if (!mz->on_tree)
434 return;
435 rb_erase(&mz->tree_node, &mctz->rb_root);
436 mz->on_tree = false;
437 }
438
439 static void
440 mem_cgroup_remove_exceeded(struct mem_cgroup *mem,
441 struct mem_cgroup_per_zone *mz,
442 struct mem_cgroup_tree_per_zone *mctz)
443 {
444 spin_lock(&mctz->lock);
445 __mem_cgroup_remove_exceeded(mem, mz, mctz);
446 spin_unlock(&mctz->lock);
447 }
448
449
450 static void mem_cgroup_update_tree(struct mem_cgroup *mem, struct page *page)
451 {
452 unsigned long long excess;
453 struct mem_cgroup_per_zone *mz;
454 struct mem_cgroup_tree_per_zone *mctz;
455 int nid = page_to_nid(page);
456 int zid = page_zonenum(page);
457 mctz = soft_limit_tree_from_page(page);
458
459 /*
460 * Necessary to update all ancestors when hierarchy is used.
461 * because their event counter is not touched.
462 */
463 for (; mem; mem = parent_mem_cgroup(mem)) {
464 mz = mem_cgroup_zoneinfo(mem, nid, zid);
465 excess = res_counter_soft_limit_excess(&mem->res);
466 /*
467 * We have to update the tree if mz is on RB-tree or
468 * mem is over its softlimit.
469 */
470 if (excess || mz->on_tree) {
471 spin_lock(&mctz->lock);
472 /* if on-tree, remove it */
473 if (mz->on_tree)
474 __mem_cgroup_remove_exceeded(mem, mz, mctz);
475 /*
476 * Insert again. mz->usage_in_excess will be updated.
477 * If excess is 0, no tree ops.
478 */
479 __mem_cgroup_insert_exceeded(mem, mz, mctz, excess);
480 spin_unlock(&mctz->lock);
481 }
482 }
483 }
484
485 static void mem_cgroup_remove_from_trees(struct mem_cgroup *mem)
486 {
487 int node, zone;
488 struct mem_cgroup_per_zone *mz;
489 struct mem_cgroup_tree_per_zone *mctz;
490
491 for_each_node_state(node, N_POSSIBLE) {
492 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
493 mz = mem_cgroup_zoneinfo(mem, node, zone);
494 mctz = soft_limit_tree_node_zone(node, zone);
495 mem_cgroup_remove_exceeded(mem, mz, mctz);
496 }
497 }
498 }
499
500 static inline unsigned long mem_cgroup_get_excess(struct mem_cgroup *mem)
501 {
502 return res_counter_soft_limit_excess(&mem->res) >> PAGE_SHIFT;
503 }
504
505 static struct mem_cgroup_per_zone *
506 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
507 {
508 struct rb_node *rightmost = NULL;
509 struct mem_cgroup_per_zone *mz;
510
511 retry:
512 mz = NULL;
513 rightmost = rb_last(&mctz->rb_root);
514 if (!rightmost)
515 goto done; /* Nothing to reclaim from */
516
517 mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
518 /*
519 * Remove the node now but someone else can add it back,
520 * we will to add it back at the end of reclaim to its correct
521 * position in the tree.
522 */
523 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
524 if (!res_counter_soft_limit_excess(&mz->mem->res) ||
525 !css_tryget(&mz->mem->css))
526 goto retry;
527 done:
528 return mz;
529 }
530
531 static struct mem_cgroup_per_zone *
532 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
533 {
534 struct mem_cgroup_per_zone *mz;
535
536 spin_lock(&mctz->lock);
537 mz = __mem_cgroup_largest_soft_limit_node(mctz);
538 spin_unlock(&mctz->lock);
539 return mz;
540 }
541
542 /*
543 * Implementation Note: reading percpu statistics for memcg.
544 *
545 * Both of vmstat[] and percpu_counter has threshold and do periodic
546 * synchronization to implement "quick" read. There are trade-off between
547 * reading cost and precision of value. Then, we may have a chance to implement
548 * a periodic synchronizion of counter in memcg's counter.
549 *
550 * But this _read() function is used for user interface now. The user accounts
551 * memory usage by memory cgroup and he _always_ requires exact value because
552 * he accounts memory. Even if we provide quick-and-fuzzy read, we always
553 * have to visit all online cpus and make sum. So, for now, unnecessary
554 * synchronization is not implemented. (just implemented for cpu hotplug)
555 *
556 * If there are kernel internal actions which can make use of some not-exact
557 * value, and reading all cpu value can be performance bottleneck in some
558 * common workload, threashold and synchonization as vmstat[] should be
559 * implemented.
560 */
561 static s64 mem_cgroup_read_stat(struct mem_cgroup *mem,
562 enum mem_cgroup_stat_index idx)
563 {
564 int cpu;
565 s64 val = 0;
566
567 get_online_cpus();
568 for_each_online_cpu(cpu)
569 val += per_cpu(mem->stat->count[idx], cpu);
570 #ifdef CONFIG_HOTPLUG_CPU
571 spin_lock(&mem->pcp_counter_lock);
572 val += mem->nocpu_base.count[idx];
573 spin_unlock(&mem->pcp_counter_lock);
574 #endif
575 put_online_cpus();
576 return val;
577 }
578
579 static s64 mem_cgroup_local_usage(struct mem_cgroup *mem)
580 {
581 s64 ret;
582
583 ret = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_RSS);
584 ret += mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_CACHE);
585 return ret;
586 }
587
588 static void mem_cgroup_swap_statistics(struct mem_cgroup *mem,
589 bool charge)
590 {
591 int val = (charge) ? 1 : -1;
592 this_cpu_add(mem->stat->count[MEM_CGROUP_STAT_SWAPOUT], val);
593 }
594
595 static void mem_cgroup_charge_statistics(struct mem_cgroup *mem,
596 struct page_cgroup *pc,
597 bool charge)
598 {
599 int val = (charge) ? 1 : -1;
600
601 preempt_disable();
602
603 if (PageCgroupCache(pc))
604 __this_cpu_add(mem->stat->count[MEM_CGROUP_STAT_CACHE], val);
605 else
606 __this_cpu_add(mem->stat->count[MEM_CGROUP_STAT_RSS], val);
607
608 if (charge)
609 __this_cpu_inc(mem->stat->count[MEM_CGROUP_STAT_PGPGIN_COUNT]);
610 else
611 __this_cpu_inc(mem->stat->count[MEM_CGROUP_STAT_PGPGOUT_COUNT]);
612 __this_cpu_inc(mem->stat->count[MEM_CGROUP_EVENTS]);
613
614 preempt_enable();
615 }
616
617 static unsigned long mem_cgroup_get_local_zonestat(struct mem_cgroup *mem,
618 enum lru_list idx)
619 {
620 int nid, zid;
621 struct mem_cgroup_per_zone *mz;
622 u64 total = 0;
623
624 for_each_online_node(nid)
625 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
626 mz = mem_cgroup_zoneinfo(mem, nid, zid);
627 total += MEM_CGROUP_ZSTAT(mz, idx);
628 }
629 return total;
630 }
631
632 static bool __memcg_event_check(struct mem_cgroup *mem, int event_mask_shift)
633 {
634 s64 val;
635
636 val = this_cpu_read(mem->stat->count[MEM_CGROUP_EVENTS]);
637
638 return !(val & ((1 << event_mask_shift) - 1));
639 }
640
641 /*
642 * Check events in order.
643 *
644 */
645 static void memcg_check_events(struct mem_cgroup *mem, struct page *page)
646 {
647 /* threshold event is triggered in finer grain than soft limit */
648 if (unlikely(__memcg_event_check(mem, THRESHOLDS_EVENTS_THRESH))) {
649 mem_cgroup_threshold(mem);
650 if (unlikely(__memcg_event_check(mem, SOFTLIMIT_EVENTS_THRESH)))
651 mem_cgroup_update_tree(mem, page);
652 }
653 }
654
655 static struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
656 {
657 return container_of(cgroup_subsys_state(cont,
658 mem_cgroup_subsys_id), struct mem_cgroup,
659 css);
660 }
661
662 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
663 {
664 /*
665 * mm_update_next_owner() may clear mm->owner to NULL
666 * if it races with swapoff, page migration, etc.
667 * So this can be called with p == NULL.
668 */
669 if (unlikely(!p))
670 return NULL;
671
672 return container_of(task_subsys_state(p, mem_cgroup_subsys_id),
673 struct mem_cgroup, css);
674 }
675
676 static struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
677 {
678 struct mem_cgroup *mem = NULL;
679
680 if (!mm)
681 return NULL;
682 /*
683 * Because we have no locks, mm->owner's may be being moved to other
684 * cgroup. We use css_tryget() here even if this looks
685 * pessimistic (rather than adding locks here).
686 */
687 rcu_read_lock();
688 do {
689 mem = mem_cgroup_from_task(rcu_dereference(mm->owner));
690 if (unlikely(!mem))
691 break;
692 } while (!css_tryget(&mem->css));
693 rcu_read_unlock();
694 return mem;
695 }
696
697 /* The caller has to guarantee "mem" exists before calling this */
698 static struct mem_cgroup *mem_cgroup_start_loop(struct mem_cgroup *mem)
699 {
700 struct cgroup_subsys_state *css;
701 int found;
702
703 if (!mem) /* ROOT cgroup has the smallest ID */
704 return root_mem_cgroup; /*css_put/get against root is ignored*/
705 if (!mem->use_hierarchy) {
706 if (css_tryget(&mem->css))
707 return mem;
708 return NULL;
709 }
710 rcu_read_lock();
711 /*
712 * searching a memory cgroup which has the smallest ID under given
713 * ROOT cgroup. (ID >= 1)
714 */
715 css = css_get_next(&mem_cgroup_subsys, 1, &mem->css, &found);
716 if (css && css_tryget(css))
717 mem = container_of(css, struct mem_cgroup, css);
718 else
719 mem = NULL;
720 rcu_read_unlock();
721 return mem;
722 }
723
724 static struct mem_cgroup *mem_cgroup_get_next(struct mem_cgroup *iter,
725 struct mem_cgroup *root,
726 bool cond)
727 {
728 int nextid = css_id(&iter->css) + 1;
729 int found;
730 int hierarchy_used;
731 struct cgroup_subsys_state *css;
732
733 hierarchy_used = iter->use_hierarchy;
734
735 css_put(&iter->css);
736 /* If no ROOT, walk all, ignore hierarchy */
737 if (!cond || (root && !hierarchy_used))
738 return NULL;
739
740 if (!root)
741 root = root_mem_cgroup;
742
743 do {
744 iter = NULL;
745 rcu_read_lock();
746
747 css = css_get_next(&mem_cgroup_subsys, nextid,
748 &root->css, &found);
749 if (css && css_tryget(css))
750 iter = container_of(css, struct mem_cgroup, css);
751 rcu_read_unlock();
752 /* If css is NULL, no more cgroups will be found */
753 nextid = found + 1;
754 } while (css && !iter);
755
756 return iter;
757 }
758 /*
759 * for_eacn_mem_cgroup_tree() for visiting all cgroup under tree. Please
760 * be careful that "break" loop is not allowed. We have reference count.
761 * Instead of that modify "cond" to be false and "continue" to exit the loop.
762 */
763 #define for_each_mem_cgroup_tree_cond(iter, root, cond) \
764 for (iter = mem_cgroup_start_loop(root);\
765 iter != NULL;\
766 iter = mem_cgroup_get_next(iter, root, cond))
767
768 #define for_each_mem_cgroup_tree(iter, root) \
769 for_each_mem_cgroup_tree_cond(iter, root, true)
770
771 #define for_each_mem_cgroup_all(iter) \
772 for_each_mem_cgroup_tree_cond(iter, NULL, true)
773
774
775 static inline bool mem_cgroup_is_root(struct mem_cgroup *mem)
776 {
777 return (mem == root_mem_cgroup);
778 }
779
780 /*
781 * Following LRU functions are allowed to be used without PCG_LOCK.
782 * Operations are called by routine of global LRU independently from memcg.
783 * What we have to take care of here is validness of pc->mem_cgroup.
784 *
785 * Changes to pc->mem_cgroup happens when
786 * 1. charge
787 * 2. moving account
788 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
789 * It is added to LRU before charge.
790 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
791 * When moving account, the page is not on LRU. It's isolated.
792 */
793
794 void mem_cgroup_del_lru_list(struct page *page, enum lru_list lru)
795 {
796 struct page_cgroup *pc;
797 struct mem_cgroup_per_zone *mz;
798
799 if (mem_cgroup_disabled())
800 return;
801 pc = lookup_page_cgroup(page);
802 /* can happen while we handle swapcache. */
803 if (!TestClearPageCgroupAcctLRU(pc))
804 return;
805 VM_BUG_ON(!pc->mem_cgroup);
806 /*
807 * We don't check PCG_USED bit. It's cleared when the "page" is finally
808 * removed from global LRU.
809 */
810 mz = page_cgroup_zoneinfo(pc);
811 MEM_CGROUP_ZSTAT(mz, lru) -= 1;
812 if (mem_cgroup_is_root(pc->mem_cgroup))
813 return;
814 VM_BUG_ON(list_empty(&pc->lru));
815 list_del_init(&pc->lru);
816 return;
817 }
818
819 void mem_cgroup_del_lru(struct page *page)
820 {
821 mem_cgroup_del_lru_list(page, page_lru(page));
822 }
823
824 void mem_cgroup_rotate_lru_list(struct page *page, enum lru_list lru)
825 {
826 struct mem_cgroup_per_zone *mz;
827 struct page_cgroup *pc;
828
829 if (mem_cgroup_disabled())
830 return;
831
832 pc = lookup_page_cgroup(page);
833 /*
834 * Used bit is set without atomic ops but after smp_wmb().
835 * For making pc->mem_cgroup visible, insert smp_rmb() here.
836 */
837 smp_rmb();
838 /* unused or root page is not rotated. */
839 if (!PageCgroupUsed(pc) || mem_cgroup_is_root(pc->mem_cgroup))
840 return;
841 mz = page_cgroup_zoneinfo(pc);
842 list_move(&pc->lru, &mz->lists[lru]);
843 }
844
845 void mem_cgroup_add_lru_list(struct page *page, enum lru_list lru)
846 {
847 struct page_cgroup *pc;
848 struct mem_cgroup_per_zone *mz;
849
850 if (mem_cgroup_disabled())
851 return;
852 pc = lookup_page_cgroup(page);
853 VM_BUG_ON(PageCgroupAcctLRU(pc));
854 /*
855 * Used bit is set without atomic ops but after smp_wmb().
856 * For making pc->mem_cgroup visible, insert smp_rmb() here.
857 */
858 smp_rmb();
859 if (!PageCgroupUsed(pc))
860 return;
861
862 mz = page_cgroup_zoneinfo(pc);
863 MEM_CGROUP_ZSTAT(mz, lru) += 1;
864 SetPageCgroupAcctLRU(pc);
865 if (mem_cgroup_is_root(pc->mem_cgroup))
866 return;
867 list_add(&pc->lru, &mz->lists[lru]);
868 }
869
870 /*
871 * At handling SwapCache, pc->mem_cgroup may be changed while it's linked to
872 * lru because the page may.be reused after it's fully uncharged (because of
873 * SwapCache behavior).To handle that, unlink page_cgroup from LRU when charge
874 * it again. This function is only used to charge SwapCache. It's done under
875 * lock_page and expected that zone->lru_lock is never held.
876 */
877 static void mem_cgroup_lru_del_before_commit_swapcache(struct page *page)
878 {
879 unsigned long flags;
880 struct zone *zone = page_zone(page);
881 struct page_cgroup *pc = lookup_page_cgroup(page);
882
883 spin_lock_irqsave(&zone->lru_lock, flags);
884 /*
885 * Forget old LRU when this page_cgroup is *not* used. This Used bit
886 * is guarded by lock_page() because the page is SwapCache.
887 */
888 if (!PageCgroupUsed(pc))
889 mem_cgroup_del_lru_list(page, page_lru(page));
890 spin_unlock_irqrestore(&zone->lru_lock, flags);
891 }
892
893 static void mem_cgroup_lru_add_after_commit_swapcache(struct page *page)
894 {
895 unsigned long flags;
896 struct zone *zone = page_zone(page);
897 struct page_cgroup *pc = lookup_page_cgroup(page);
898
899 spin_lock_irqsave(&zone->lru_lock, flags);
900 /* link when the page is linked to LRU but page_cgroup isn't */
901 if (PageLRU(page) && !PageCgroupAcctLRU(pc))
902 mem_cgroup_add_lru_list(page, page_lru(page));
903 spin_unlock_irqrestore(&zone->lru_lock, flags);
904 }
905
906
907 void mem_cgroup_move_lists(struct page *page,
908 enum lru_list from, enum lru_list to)
909 {
910 if (mem_cgroup_disabled())
911 return;
912 mem_cgroup_del_lru_list(page, from);
913 mem_cgroup_add_lru_list(page, to);
914 }
915
916 int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *mem)
917 {
918 int ret;
919 struct mem_cgroup *curr = NULL;
920 struct task_struct *p;
921
922 p = find_lock_task_mm(task);
923 if (!p)
924 return 0;
925 curr = try_get_mem_cgroup_from_mm(p->mm);
926 task_unlock(p);
927 if (!curr)
928 return 0;
929 /*
930 * We should check use_hierarchy of "mem" not "curr". Because checking
931 * use_hierarchy of "curr" here make this function true if hierarchy is
932 * enabled in "curr" and "curr" is a child of "mem" in *cgroup*
933 * hierarchy(even if use_hierarchy is disabled in "mem").
934 */
935 if (mem->use_hierarchy)
936 ret = css_is_ancestor(&curr->css, &mem->css);
937 else
938 ret = (curr == mem);
939 css_put(&curr->css);
940 return ret;
941 }
942
943 static int calc_inactive_ratio(struct mem_cgroup *memcg, unsigned long *present_pages)
944 {
945 unsigned long active;
946 unsigned long inactive;
947 unsigned long gb;
948 unsigned long inactive_ratio;
949
950 inactive = mem_cgroup_get_local_zonestat(memcg, LRU_INACTIVE_ANON);
951 active = mem_cgroup_get_local_zonestat(memcg, LRU_ACTIVE_ANON);
952
953 gb = (inactive + active) >> (30 - PAGE_SHIFT);
954 if (gb)
955 inactive_ratio = int_sqrt(10 * gb);
956 else
957 inactive_ratio = 1;
958
959 if (present_pages) {
960 present_pages[0] = inactive;
961 present_pages[1] = active;
962 }
963
964 return inactive_ratio;
965 }
966
967 int mem_cgroup_inactive_anon_is_low(struct mem_cgroup *memcg)
968 {
969 unsigned long active;
970 unsigned long inactive;
971 unsigned long present_pages[2];
972 unsigned long inactive_ratio;
973
974 inactive_ratio = calc_inactive_ratio(memcg, present_pages);
975
976 inactive = present_pages[0];
977 active = present_pages[1];
978
979 if (inactive * inactive_ratio < active)
980 return 1;
981
982 return 0;
983 }
984
985 int mem_cgroup_inactive_file_is_low(struct mem_cgroup *memcg)
986 {
987 unsigned long active;
988 unsigned long inactive;
989
990 inactive = mem_cgroup_get_local_zonestat(memcg, LRU_INACTIVE_FILE);
991 active = mem_cgroup_get_local_zonestat(memcg, LRU_ACTIVE_FILE);
992
993 return (active > inactive);
994 }
995
996 unsigned long mem_cgroup_zone_nr_pages(struct mem_cgroup *memcg,
997 struct zone *zone,
998 enum lru_list lru)
999 {
1000 int nid = zone_to_nid(zone);
1001 int zid = zone_idx(zone);
1002 struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
1003
1004 return MEM_CGROUP_ZSTAT(mz, lru);
1005 }
1006
1007 struct zone_reclaim_stat *mem_cgroup_get_reclaim_stat(struct mem_cgroup *memcg,
1008 struct zone *zone)
1009 {
1010 int nid = zone_to_nid(zone);
1011 int zid = zone_idx(zone);
1012 struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
1013
1014 return &mz->reclaim_stat;
1015 }
1016
1017 struct zone_reclaim_stat *
1018 mem_cgroup_get_reclaim_stat_from_page(struct page *page)
1019 {
1020 struct page_cgroup *pc;
1021 struct mem_cgroup_per_zone *mz;
1022
1023 if (mem_cgroup_disabled())
1024 return NULL;
1025
1026 pc = lookup_page_cgroup(page);
1027 /*
1028 * Used bit is set without atomic ops but after smp_wmb().
1029 * For making pc->mem_cgroup visible, insert smp_rmb() here.
1030 */
1031 smp_rmb();
1032 if (!PageCgroupUsed(pc))
1033 return NULL;
1034
1035 mz = page_cgroup_zoneinfo(pc);
1036 if (!mz)
1037 return NULL;
1038
1039 return &mz->reclaim_stat;
1040 }
1041
1042 unsigned long mem_cgroup_isolate_pages(unsigned long nr_to_scan,
1043 struct list_head *dst,
1044 unsigned long *scanned, int order,
1045 int mode, struct zone *z,
1046 struct mem_cgroup *mem_cont,
1047 int active, int file)
1048 {
1049 unsigned long nr_taken = 0;
1050 struct page *page;
1051 unsigned long scan;
1052 LIST_HEAD(pc_list);
1053 struct list_head *src;
1054 struct page_cgroup *pc, *tmp;
1055 int nid = zone_to_nid(z);
1056 int zid = zone_idx(z);
1057 struct mem_cgroup_per_zone *mz;
1058 int lru = LRU_FILE * file + active;
1059 int ret;
1060
1061 BUG_ON(!mem_cont);
1062 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
1063 src = &mz->lists[lru];
1064
1065 scan = 0;
1066 list_for_each_entry_safe_reverse(pc, tmp, src, lru) {
1067 if (scan >= nr_to_scan)
1068 break;
1069
1070 page = pc->page;
1071 if (unlikely(!PageCgroupUsed(pc)))
1072 continue;
1073 if (unlikely(!PageLRU(page)))
1074 continue;
1075
1076 scan++;
1077 ret = __isolate_lru_page(page, mode, file);
1078 switch (ret) {
1079 case 0:
1080 list_move(&page->lru, dst);
1081 mem_cgroup_del_lru(page);
1082 nr_taken++;
1083 break;
1084 case -EBUSY:
1085 /* we don't affect global LRU but rotate in our LRU */
1086 mem_cgroup_rotate_lru_list(page, page_lru(page));
1087 break;
1088 default:
1089 break;
1090 }
1091 }
1092
1093 *scanned = scan;
1094
1095 trace_mm_vmscan_memcg_isolate(0, nr_to_scan, scan, nr_taken,
1096 0, 0, 0, mode);
1097
1098 return nr_taken;
1099 }
1100
1101 #define mem_cgroup_from_res_counter(counter, member) \
1102 container_of(counter, struct mem_cgroup, member)
1103
1104 static bool mem_cgroup_check_under_limit(struct mem_cgroup *mem)
1105 {
1106 if (do_swap_account) {
1107 if (res_counter_check_under_limit(&mem->res) &&
1108 res_counter_check_under_limit(&mem->memsw))
1109 return true;
1110 } else
1111 if (res_counter_check_under_limit(&mem->res))
1112 return true;
1113 return false;
1114 }
1115
1116 static unsigned int get_swappiness(struct mem_cgroup *memcg)
1117 {
1118 struct cgroup *cgrp = memcg->css.cgroup;
1119 unsigned int swappiness;
1120
1121 /* root ? */
1122 if (cgrp->parent == NULL)
1123 return vm_swappiness;
1124
1125 spin_lock(&memcg->reclaim_param_lock);
1126 swappiness = memcg->swappiness;
1127 spin_unlock(&memcg->reclaim_param_lock);
1128
1129 return swappiness;
1130 }
1131
1132 static void mem_cgroup_start_move(struct mem_cgroup *mem)
1133 {
1134 int cpu;
1135 /* Because this is for moving account, reuse mc.lock */
1136 spin_lock(&mc.lock);
1137 for_each_possible_cpu(cpu)
1138 per_cpu(mem->stat->count[MEM_CGROUP_ON_MOVE], cpu) += 1;
1139 spin_unlock(&mc.lock);
1140
1141 synchronize_rcu();
1142 }
1143
1144 static void mem_cgroup_end_move(struct mem_cgroup *mem)
1145 {
1146 int cpu;
1147
1148 if (!mem)
1149 return;
1150 spin_lock(&mc.lock);
1151 for_each_possible_cpu(cpu)
1152 per_cpu(mem->stat->count[MEM_CGROUP_ON_MOVE], cpu) -= 1;
1153 spin_unlock(&mc.lock);
1154 }
1155 /*
1156 * 2 routines for checking "mem" is under move_account() or not.
1157 *
1158 * mem_cgroup_stealed() - checking a cgroup is mc.from or not. This is used
1159 * for avoiding race in accounting. If true,
1160 * pc->mem_cgroup may be overwritten.
1161 *
1162 * mem_cgroup_under_move() - checking a cgroup is mc.from or mc.to or
1163 * under hierarchy of moving cgroups. This is for
1164 * waiting at hith-memory prressure caused by "move".
1165 */
1166
1167 static bool mem_cgroup_stealed(struct mem_cgroup *mem)
1168 {
1169 VM_BUG_ON(!rcu_read_lock_held());
1170 return this_cpu_read(mem->stat->count[MEM_CGROUP_ON_MOVE]) > 0;
1171 }
1172
1173 static bool mem_cgroup_under_move(struct mem_cgroup *mem)
1174 {
1175 struct mem_cgroup *from;
1176 struct mem_cgroup *to;
1177 bool ret = false;
1178 /*
1179 * Unlike task_move routines, we access mc.to, mc.from not under
1180 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1181 */
1182 spin_lock(&mc.lock);
1183 from = mc.from;
1184 to = mc.to;
1185 if (!from)
1186 goto unlock;
1187 if (from == mem || to == mem
1188 || (mem->use_hierarchy && css_is_ancestor(&from->css, &mem->css))
1189 || (mem->use_hierarchy && css_is_ancestor(&to->css, &mem->css)))
1190 ret = true;
1191 unlock:
1192 spin_unlock(&mc.lock);
1193 return ret;
1194 }
1195
1196 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *mem)
1197 {
1198 if (mc.moving_task && current != mc.moving_task) {
1199 if (mem_cgroup_under_move(mem)) {
1200 DEFINE_WAIT(wait);
1201 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1202 /* moving charge context might have finished. */
1203 if (mc.moving_task)
1204 schedule();
1205 finish_wait(&mc.waitq, &wait);
1206 return true;
1207 }
1208 }
1209 return false;
1210 }
1211
1212 /**
1213 * mem_cgroup_print_oom_info: Called from OOM with tasklist_lock held in read mode.
1214 * @memcg: The memory cgroup that went over limit
1215 * @p: Task that is going to be killed
1216 *
1217 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1218 * enabled
1219 */
1220 void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1221 {
1222 struct cgroup *task_cgrp;
1223 struct cgroup *mem_cgrp;
1224 /*
1225 * Need a buffer in BSS, can't rely on allocations. The code relies
1226 * on the assumption that OOM is serialized for memory controller.
1227 * If this assumption is broken, revisit this code.
1228 */
1229 static char memcg_name[PATH_MAX];
1230 int ret;
1231
1232 if (!memcg || !p)
1233 return;
1234
1235
1236 rcu_read_lock();
1237
1238 mem_cgrp = memcg->css.cgroup;
1239 task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
1240
1241 ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
1242 if (ret < 0) {
1243 /*
1244 * Unfortunately, we are unable to convert to a useful name
1245 * But we'll still print out the usage information
1246 */
1247 rcu_read_unlock();
1248 goto done;
1249 }
1250 rcu_read_unlock();
1251
1252 printk(KERN_INFO "Task in %s killed", memcg_name);
1253
1254 rcu_read_lock();
1255 ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
1256 if (ret < 0) {
1257 rcu_read_unlock();
1258 goto done;
1259 }
1260 rcu_read_unlock();
1261
1262 /*
1263 * Continues from above, so we don't need an KERN_ level
1264 */
1265 printk(KERN_CONT " as a result of limit of %s\n", memcg_name);
1266 done:
1267
1268 printk(KERN_INFO "memory: usage %llukB, limit %llukB, failcnt %llu\n",
1269 res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
1270 res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
1271 res_counter_read_u64(&memcg->res, RES_FAILCNT));
1272 printk(KERN_INFO "memory+swap: usage %llukB, limit %llukB, "
1273 "failcnt %llu\n",
1274 res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
1275 res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
1276 res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
1277 }
1278
1279 /*
1280 * This function returns the number of memcg under hierarchy tree. Returns
1281 * 1(self count) if no children.
1282 */
1283 static int mem_cgroup_count_children(struct mem_cgroup *mem)
1284 {
1285 int num = 0;
1286 struct mem_cgroup *iter;
1287
1288 for_each_mem_cgroup_tree(iter, mem)
1289 num++;
1290 return num;
1291 }
1292
1293 /*
1294 * Return the memory (and swap, if configured) limit for a memcg.
1295 */
1296 u64 mem_cgroup_get_limit(struct mem_cgroup *memcg)
1297 {
1298 u64 limit;
1299 u64 memsw;
1300
1301 limit = res_counter_read_u64(&memcg->res, RES_LIMIT) +
1302 total_swap_pages;
1303 memsw = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
1304 /*
1305 * If memsw is finite and limits the amount of swap space available
1306 * to this memcg, return that limit.
1307 */
1308 return min(limit, memsw);
1309 }
1310
1311 /*
1312 * Visit the first child (need not be the first child as per the ordering
1313 * of the cgroup list, since we track last_scanned_child) of @mem and use
1314 * that to reclaim free pages from.
1315 */
1316 static struct mem_cgroup *
1317 mem_cgroup_select_victim(struct mem_cgroup *root_mem)
1318 {
1319 struct mem_cgroup *ret = NULL;
1320 struct cgroup_subsys_state *css;
1321 int nextid, found;
1322
1323 if (!root_mem->use_hierarchy) {
1324 css_get(&root_mem->css);
1325 ret = root_mem;
1326 }
1327
1328 while (!ret) {
1329 rcu_read_lock();
1330 nextid = root_mem->last_scanned_child + 1;
1331 css = css_get_next(&mem_cgroup_subsys, nextid, &root_mem->css,
1332 &found);
1333 if (css && css_tryget(css))
1334 ret = container_of(css, struct mem_cgroup, css);
1335
1336 rcu_read_unlock();
1337 /* Updates scanning parameter */
1338 spin_lock(&root_mem->reclaim_param_lock);
1339 if (!css) {
1340 /* this means start scan from ID:1 */
1341 root_mem->last_scanned_child = 0;
1342 } else
1343 root_mem->last_scanned_child = found;
1344 spin_unlock(&root_mem->reclaim_param_lock);
1345 }
1346
1347 return ret;
1348 }
1349
1350 /*
1351 * Scan the hierarchy if needed to reclaim memory. We remember the last child
1352 * we reclaimed from, so that we don't end up penalizing one child extensively
1353 * based on its position in the children list.
1354 *
1355 * root_mem is the original ancestor that we've been reclaim from.
1356 *
1357 * We give up and return to the caller when we visit root_mem twice.
1358 * (other groups can be removed while we're walking....)
1359 *
1360 * If shrink==true, for avoiding to free too much, this returns immedieately.
1361 */
1362 static int mem_cgroup_hierarchical_reclaim(struct mem_cgroup *root_mem,
1363 struct zone *zone,
1364 gfp_t gfp_mask,
1365 unsigned long reclaim_options)
1366 {
1367 struct mem_cgroup *victim;
1368 int ret, total = 0;
1369 int loop = 0;
1370 bool noswap = reclaim_options & MEM_CGROUP_RECLAIM_NOSWAP;
1371 bool shrink = reclaim_options & MEM_CGROUP_RECLAIM_SHRINK;
1372 bool check_soft = reclaim_options & MEM_CGROUP_RECLAIM_SOFT;
1373 unsigned long excess = mem_cgroup_get_excess(root_mem);
1374
1375 /* If memsw_is_minimum==1, swap-out is of-no-use. */
1376 if (root_mem->memsw_is_minimum)
1377 noswap = true;
1378
1379 while (1) {
1380 victim = mem_cgroup_select_victim(root_mem);
1381 if (victim == root_mem) {
1382 loop++;
1383 if (loop >= 1)
1384 drain_all_stock_async();
1385 if (loop >= 2) {
1386 /*
1387 * If we have not been able to reclaim
1388 * anything, it might because there are
1389 * no reclaimable pages under this hierarchy
1390 */
1391 if (!check_soft || !total) {
1392 css_put(&victim->css);
1393 break;
1394 }
1395 /*
1396 * We want to do more targetted reclaim.
1397 * excess >> 2 is not to excessive so as to
1398 * reclaim too much, nor too less that we keep
1399 * coming back to reclaim from this cgroup
1400 */
1401 if (total >= (excess >> 2) ||
1402 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS)) {
1403 css_put(&victim->css);
1404 break;
1405 }
1406 }
1407 }
1408 if (!mem_cgroup_local_usage(victim)) {
1409 /* this cgroup's local usage == 0 */
1410 css_put(&victim->css);
1411 continue;
1412 }
1413 /* we use swappiness of local cgroup */
1414 if (check_soft)
1415 ret = mem_cgroup_shrink_node_zone(victim, gfp_mask,
1416 noswap, get_swappiness(victim), zone);
1417 else
1418 ret = try_to_free_mem_cgroup_pages(victim, gfp_mask,
1419 noswap, get_swappiness(victim));
1420 css_put(&victim->css);
1421 /*
1422 * At shrinking usage, we can't check we should stop here or
1423 * reclaim more. It's depends on callers. last_scanned_child
1424 * will work enough for keeping fairness under tree.
1425 */
1426 if (shrink)
1427 return ret;
1428 total += ret;
1429 if (check_soft) {
1430 if (res_counter_check_under_soft_limit(&root_mem->res))
1431 return total;
1432 } else if (mem_cgroup_check_under_limit(root_mem))
1433 return 1 + total;
1434 }
1435 return total;
1436 }
1437
1438 /*
1439 * Check OOM-Killer is already running under our hierarchy.
1440 * If someone is running, return false.
1441 */
1442 static bool mem_cgroup_oom_lock(struct mem_cgroup *mem)
1443 {
1444 int x, lock_count = 0;
1445 struct mem_cgroup *iter;
1446
1447 for_each_mem_cgroup_tree(iter, mem) {
1448 x = atomic_inc_return(&iter->oom_lock);
1449 lock_count = max(x, lock_count);
1450 }
1451
1452 if (lock_count == 1)
1453 return true;
1454 return false;
1455 }
1456
1457 static int mem_cgroup_oom_unlock(struct mem_cgroup *mem)
1458 {
1459 struct mem_cgroup *iter;
1460
1461 /*
1462 * When a new child is created while the hierarchy is under oom,
1463 * mem_cgroup_oom_lock() may not be called. We have to use
1464 * atomic_add_unless() here.
1465 */
1466 for_each_mem_cgroup_tree(iter, mem)
1467 atomic_add_unless(&iter->oom_lock, -1, 0);
1468 return 0;
1469 }
1470
1471
1472 static DEFINE_MUTEX(memcg_oom_mutex);
1473 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1474
1475 struct oom_wait_info {
1476 struct mem_cgroup *mem;
1477 wait_queue_t wait;
1478 };
1479
1480 static int memcg_oom_wake_function(wait_queue_t *wait,
1481 unsigned mode, int sync, void *arg)
1482 {
1483 struct mem_cgroup *wake_mem = (struct mem_cgroup *)arg;
1484 struct oom_wait_info *oom_wait_info;
1485
1486 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1487
1488 if (oom_wait_info->mem == wake_mem)
1489 goto wakeup;
1490 /* if no hierarchy, no match */
1491 if (!oom_wait_info->mem->use_hierarchy || !wake_mem->use_hierarchy)
1492 return 0;
1493 /*
1494 * Both of oom_wait_info->mem and wake_mem are stable under us.
1495 * Then we can use css_is_ancestor without taking care of RCU.
1496 */
1497 if (!css_is_ancestor(&oom_wait_info->mem->css, &wake_mem->css) &&
1498 !css_is_ancestor(&wake_mem->css, &oom_wait_info->mem->css))
1499 return 0;
1500
1501 wakeup:
1502 return autoremove_wake_function(wait, mode, sync, arg);
1503 }
1504
1505 static void memcg_wakeup_oom(struct mem_cgroup *mem)
1506 {
1507 /* for filtering, pass "mem" as argument. */
1508 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, mem);
1509 }
1510
1511 static void memcg_oom_recover(struct mem_cgroup *mem)
1512 {
1513 if (mem && atomic_read(&mem->oom_lock))
1514 memcg_wakeup_oom(mem);
1515 }
1516
1517 /*
1518 * try to call OOM killer. returns false if we should exit memory-reclaim loop.
1519 */
1520 bool mem_cgroup_handle_oom(struct mem_cgroup *mem, gfp_t mask)
1521 {
1522 struct oom_wait_info owait;
1523 bool locked, need_to_kill;
1524
1525 owait.mem = mem;
1526 owait.wait.flags = 0;
1527 owait.wait.func = memcg_oom_wake_function;
1528 owait.wait.private = current;
1529 INIT_LIST_HEAD(&owait.wait.task_list);
1530 need_to_kill = true;
1531 /* At first, try to OOM lock hierarchy under mem.*/
1532 mutex_lock(&memcg_oom_mutex);
1533 locked = mem_cgroup_oom_lock(mem);
1534 /*
1535 * Even if signal_pending(), we can't quit charge() loop without
1536 * accounting. So, UNINTERRUPTIBLE is appropriate. But SIGKILL
1537 * under OOM is always welcomed, use TASK_KILLABLE here.
1538 */
1539 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
1540 if (!locked || mem->oom_kill_disable)
1541 need_to_kill = false;
1542 if (locked)
1543 mem_cgroup_oom_notify(mem);
1544 mutex_unlock(&memcg_oom_mutex);
1545
1546 if (need_to_kill) {
1547 finish_wait(&memcg_oom_waitq, &owait.wait);
1548 mem_cgroup_out_of_memory(mem, mask);
1549 } else {
1550 schedule();
1551 finish_wait(&memcg_oom_waitq, &owait.wait);
1552 }
1553 mutex_lock(&memcg_oom_mutex);
1554 mem_cgroup_oom_unlock(mem);
1555 memcg_wakeup_oom(mem);
1556 mutex_unlock(&memcg_oom_mutex);
1557
1558 if (test_thread_flag(TIF_MEMDIE) || fatal_signal_pending(current))
1559 return false;
1560 /* Give chance to dying process */
1561 schedule_timeout(1);
1562 return true;
1563 }
1564
1565 /*
1566 * Currently used to update mapped file statistics, but the routine can be
1567 * generalized to update other statistics as well.
1568 *
1569 * Notes: Race condition
1570 *
1571 * We usually use page_cgroup_lock() for accessing page_cgroup member but
1572 * it tends to be costly. But considering some conditions, we doesn't need
1573 * to do so _always_.
1574 *
1575 * Considering "charge", lock_page_cgroup() is not required because all
1576 * file-stat operations happen after a page is attached to radix-tree. There
1577 * are no race with "charge".
1578 *
1579 * Considering "uncharge", we know that memcg doesn't clear pc->mem_cgroup
1580 * at "uncharge" intentionally. So, we always see valid pc->mem_cgroup even
1581 * if there are race with "uncharge". Statistics itself is properly handled
1582 * by flags.
1583 *
1584 * Considering "move", this is an only case we see a race. To make the race
1585 * small, we check MEM_CGROUP_ON_MOVE percpu value and detect there are
1586 * possibility of race condition. If there is, we take a lock.
1587 */
1588 void mem_cgroup_update_file_mapped(struct page *page, int val)
1589 {
1590 struct mem_cgroup *mem;
1591 struct page_cgroup *pc = lookup_page_cgroup(page);
1592 bool need_unlock = false;
1593
1594 if (unlikely(!pc))
1595 return;
1596
1597 rcu_read_lock();
1598 mem = pc->mem_cgroup;
1599 if (unlikely(!mem || !PageCgroupUsed(pc)))
1600 goto out;
1601 /* pc->mem_cgroup is unstable ? */
1602 if (unlikely(mem_cgroup_stealed(mem))) {
1603 /* take a lock against to access pc->mem_cgroup */
1604 lock_page_cgroup(pc);
1605 need_unlock = true;
1606 mem = pc->mem_cgroup;
1607 if (!mem || !PageCgroupUsed(pc))
1608 goto out;
1609 }
1610 if (val > 0) {
1611 this_cpu_inc(mem->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
1612 SetPageCgroupFileMapped(pc);
1613 } else {
1614 this_cpu_dec(mem->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
1615 if (!page_mapped(page)) /* for race between dec->inc counter */
1616 ClearPageCgroupFileMapped(pc);
1617 }
1618
1619 out:
1620 if (unlikely(need_unlock))
1621 unlock_page_cgroup(pc);
1622 rcu_read_unlock();
1623 return;
1624 }
1625
1626 /*
1627 * size of first charge trial. "32" comes from vmscan.c's magic value.
1628 * TODO: maybe necessary to use big numbers in big irons.
1629 */
1630 #define CHARGE_SIZE (32 * PAGE_SIZE)
1631 struct memcg_stock_pcp {
1632 struct mem_cgroup *cached; /* this never be root cgroup */
1633 int charge;
1634 struct work_struct work;
1635 };
1636 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
1637 static atomic_t memcg_drain_count;
1638
1639 /*
1640 * Try to consume stocked charge on this cpu. If success, PAGE_SIZE is consumed
1641 * from local stock and true is returned. If the stock is 0 or charges from a
1642 * cgroup which is not current target, returns false. This stock will be
1643 * refilled.
1644 */
1645 static bool consume_stock(struct mem_cgroup *mem)
1646 {
1647 struct memcg_stock_pcp *stock;
1648 bool ret = true;
1649
1650 stock = &get_cpu_var(memcg_stock);
1651 if (mem == stock->cached && stock->charge)
1652 stock->charge -= PAGE_SIZE;
1653 else /* need to call res_counter_charge */
1654 ret = false;
1655 put_cpu_var(memcg_stock);
1656 return ret;
1657 }
1658
1659 /*
1660 * Returns stocks cached in percpu to res_counter and reset cached information.
1661 */
1662 static void drain_stock(struct memcg_stock_pcp *stock)
1663 {
1664 struct mem_cgroup *old = stock->cached;
1665
1666 if (stock->charge) {
1667 res_counter_uncharge(&old->res, stock->charge);
1668 if (do_swap_account)
1669 res_counter_uncharge(&old->memsw, stock->charge);
1670 }
1671 stock->cached = NULL;
1672 stock->charge = 0;
1673 }
1674
1675 /*
1676 * This must be called under preempt disabled or must be called by
1677 * a thread which is pinned to local cpu.
1678 */
1679 static void drain_local_stock(struct work_struct *dummy)
1680 {
1681 struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
1682 drain_stock(stock);
1683 }
1684
1685 /*
1686 * Cache charges(val) which is from res_counter, to local per_cpu area.
1687 * This will be consumed by consume_stock() function, later.
1688 */
1689 static void refill_stock(struct mem_cgroup *mem, int val)
1690 {
1691 struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
1692
1693 if (stock->cached != mem) { /* reset if necessary */
1694 drain_stock(stock);
1695 stock->cached = mem;
1696 }
1697 stock->charge += val;
1698 put_cpu_var(memcg_stock);
1699 }
1700
1701 /*
1702 * Tries to drain stocked charges in other cpus. This function is asynchronous
1703 * and just put a work per cpu for draining localy on each cpu. Caller can
1704 * expects some charges will be back to res_counter later but cannot wait for
1705 * it.
1706 */
1707 static void drain_all_stock_async(void)
1708 {
1709 int cpu;
1710 /* This function is for scheduling "drain" in asynchronous way.
1711 * The result of "drain" is not directly handled by callers. Then,
1712 * if someone is calling drain, we don't have to call drain more.
1713 * Anyway, WORK_STRUCT_PENDING check in queue_work_on() will catch if
1714 * there is a race. We just do loose check here.
1715 */
1716 if (atomic_read(&memcg_drain_count))
1717 return;
1718 /* Notify other cpus that system-wide "drain" is running */
1719 atomic_inc(&memcg_drain_count);
1720 get_online_cpus();
1721 for_each_online_cpu(cpu) {
1722 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
1723 schedule_work_on(cpu, &stock->work);
1724 }
1725 put_online_cpus();
1726 atomic_dec(&memcg_drain_count);
1727 /* We don't wait for flush_work */
1728 }
1729
1730 /* This is a synchronous drain interface. */
1731 static void drain_all_stock_sync(void)
1732 {
1733 /* called when force_empty is called */
1734 atomic_inc(&memcg_drain_count);
1735 schedule_on_each_cpu(drain_local_stock);
1736 atomic_dec(&memcg_drain_count);
1737 }
1738
1739 /*
1740 * This function drains percpu counter value from DEAD cpu and
1741 * move it to local cpu. Note that this function can be preempted.
1742 */
1743 static void mem_cgroup_drain_pcp_counter(struct mem_cgroup *mem, int cpu)
1744 {
1745 int i;
1746
1747 spin_lock(&mem->pcp_counter_lock);
1748 for (i = 0; i < MEM_CGROUP_STAT_DATA; i++) {
1749 s64 x = per_cpu(mem->stat->count[i], cpu);
1750
1751 per_cpu(mem->stat->count[i], cpu) = 0;
1752 mem->nocpu_base.count[i] += x;
1753 }
1754 spin_unlock(&mem->pcp_counter_lock);
1755 }
1756
1757 static int __cpuinit memcg_cpu_hotplug_callback(struct notifier_block *nb,
1758 unsigned long action,
1759 void *hcpu)
1760 {
1761 int cpu = (unsigned long)hcpu;
1762 struct memcg_stock_pcp *stock;
1763 struct mem_cgroup *iter;
1764
1765 if ((action != CPU_DEAD) || action != CPU_DEAD_FROZEN)
1766 return NOTIFY_OK;
1767
1768 for_each_mem_cgroup_all(iter)
1769 mem_cgroup_drain_pcp_counter(iter, cpu);
1770
1771 stock = &per_cpu(memcg_stock, cpu);
1772 drain_stock(stock);
1773 return NOTIFY_OK;
1774 }
1775
1776
1777 /* See __mem_cgroup_try_charge() for details */
1778 enum {
1779 CHARGE_OK, /* success */
1780 CHARGE_RETRY, /* need to retry but retry is not bad */
1781 CHARGE_NOMEM, /* we can't do more. return -ENOMEM */
1782 CHARGE_WOULDBLOCK, /* GFP_WAIT wasn't set and no enough res. */
1783 CHARGE_OOM_DIE, /* the current is killed because of OOM */
1784 };
1785
1786 static int __mem_cgroup_do_charge(struct mem_cgroup *mem, gfp_t gfp_mask,
1787 int csize, bool oom_check)
1788 {
1789 struct mem_cgroup *mem_over_limit;
1790 struct res_counter *fail_res;
1791 unsigned long flags = 0;
1792 int ret;
1793
1794 ret = res_counter_charge(&mem->res, csize, &fail_res);
1795
1796 if (likely(!ret)) {
1797 if (!do_swap_account)
1798 return CHARGE_OK;
1799 ret = res_counter_charge(&mem->memsw, csize, &fail_res);
1800 if (likely(!ret))
1801 return CHARGE_OK;
1802
1803 mem_over_limit = mem_cgroup_from_res_counter(fail_res, memsw);
1804 flags |= MEM_CGROUP_RECLAIM_NOSWAP;
1805 } else
1806 mem_over_limit = mem_cgroup_from_res_counter(fail_res, res);
1807
1808 if (csize > PAGE_SIZE) /* change csize and retry */
1809 return CHARGE_RETRY;
1810
1811 if (!(gfp_mask & __GFP_WAIT))
1812 return CHARGE_WOULDBLOCK;
1813
1814 ret = mem_cgroup_hierarchical_reclaim(mem_over_limit, NULL,
1815 gfp_mask, flags);
1816 /*
1817 * try_to_free_mem_cgroup_pages() might not give us a full
1818 * picture of reclaim. Some pages are reclaimed and might be
1819 * moved to swap cache or just unmapped from the cgroup.
1820 * Check the limit again to see if the reclaim reduced the
1821 * current usage of the cgroup before giving up
1822 */
1823 if (ret || mem_cgroup_check_under_limit(mem_over_limit))
1824 return CHARGE_RETRY;
1825
1826 /*
1827 * At task move, charge accounts can be doubly counted. So, it's
1828 * better to wait until the end of task_move if something is going on.
1829 */
1830 if (mem_cgroup_wait_acct_move(mem_over_limit))
1831 return CHARGE_RETRY;
1832
1833 /* If we don't need to call oom-killer at el, return immediately */
1834 if (!oom_check)
1835 return CHARGE_NOMEM;
1836 /* check OOM */
1837 if (!mem_cgroup_handle_oom(mem_over_limit, gfp_mask))
1838 return CHARGE_OOM_DIE;
1839
1840 return CHARGE_RETRY;
1841 }
1842
1843 /*
1844 * Unlike exported interface, "oom" parameter is added. if oom==true,
1845 * oom-killer can be invoked.
1846 */
1847 static int __mem_cgroup_try_charge(struct mm_struct *mm,
1848 gfp_t gfp_mask, struct mem_cgroup **memcg, bool oom)
1849 {
1850 int nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
1851 struct mem_cgroup *mem = NULL;
1852 int ret;
1853 int csize = CHARGE_SIZE;
1854
1855 /*
1856 * Unlike gloval-vm's OOM-kill, we're not in memory shortage
1857 * in system level. So, allow to go ahead dying process in addition to
1858 * MEMDIE process.
1859 */
1860 if (unlikely(test_thread_flag(TIF_MEMDIE)
1861 || fatal_signal_pending(current)))
1862 goto bypass;
1863
1864 /*
1865 * We always charge the cgroup the mm_struct belongs to.
1866 * The mm_struct's mem_cgroup changes on task migration if the
1867 * thread group leader migrates. It's possible that mm is not
1868 * set, if so charge the init_mm (happens for pagecache usage).
1869 */
1870 if (!*memcg && !mm)
1871 goto bypass;
1872 again:
1873 if (*memcg) { /* css should be a valid one */
1874 mem = *memcg;
1875 VM_BUG_ON(css_is_removed(&mem->css));
1876 if (mem_cgroup_is_root(mem))
1877 goto done;
1878 if (consume_stock(mem))
1879 goto done;
1880 css_get(&mem->css);
1881 } else {
1882 struct task_struct *p;
1883
1884 rcu_read_lock();
1885 p = rcu_dereference(mm->owner);
1886 VM_BUG_ON(!p);
1887 /*
1888 * because we don't have task_lock(), "p" can exit while
1889 * we're here. In that case, "mem" can point to root
1890 * cgroup but never be NULL. (and task_struct itself is freed
1891 * by RCU, cgroup itself is RCU safe.) Then, we have small
1892 * risk here to get wrong cgroup. But such kind of mis-account
1893 * by race always happens because we don't have cgroup_mutex().
1894 * It's overkill and we allow that small race, here.
1895 */
1896 mem = mem_cgroup_from_task(p);
1897 VM_BUG_ON(!mem);
1898 if (mem_cgroup_is_root(mem)) {
1899 rcu_read_unlock();
1900 goto done;
1901 }
1902 if (consume_stock(mem)) {
1903 /*
1904 * It seems dagerous to access memcg without css_get().
1905 * But considering how consume_stok works, it's not
1906 * necessary. If consume_stock success, some charges
1907 * from this memcg are cached on this cpu. So, we
1908 * don't need to call css_get()/css_tryget() before
1909 * calling consume_stock().
1910 */
1911 rcu_read_unlock();
1912 goto done;
1913 }
1914 /* after here, we may be blocked. we need to get refcnt */
1915 if (!css_tryget(&mem->css)) {
1916 rcu_read_unlock();
1917 goto again;
1918 }
1919 rcu_read_unlock();
1920 }
1921
1922 do {
1923 bool oom_check;
1924
1925 /* If killed, bypass charge */
1926 if (fatal_signal_pending(current)) {
1927 css_put(&mem->css);
1928 goto bypass;
1929 }
1930
1931 oom_check = false;
1932 if (oom && !nr_oom_retries) {
1933 oom_check = true;
1934 nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
1935 }
1936
1937 ret = __mem_cgroup_do_charge(mem, gfp_mask, csize, oom_check);
1938
1939 switch (ret) {
1940 case CHARGE_OK:
1941 break;
1942 case CHARGE_RETRY: /* not in OOM situation but retry */
1943 csize = PAGE_SIZE;
1944 css_put(&mem->css);
1945 mem = NULL;
1946 goto again;
1947 case CHARGE_WOULDBLOCK: /* !__GFP_WAIT */
1948 css_put(&mem->css);
1949 goto nomem;
1950 case CHARGE_NOMEM: /* OOM routine works */
1951 if (!oom) {
1952 css_put(&mem->css);
1953 goto nomem;
1954 }
1955 /* If oom, we never return -ENOMEM */
1956 nr_oom_retries--;
1957 break;
1958 case CHARGE_OOM_DIE: /* Killed by OOM Killer */
1959 css_put(&mem->css);
1960 goto bypass;
1961 }
1962 } while (ret != CHARGE_OK);
1963
1964 if (csize > PAGE_SIZE)
1965 refill_stock(mem, csize - PAGE_SIZE);
1966 css_put(&mem->css);
1967 done:
1968 *memcg = mem;
1969 return 0;
1970 nomem:
1971 *memcg = NULL;
1972 return -ENOMEM;
1973 bypass:
1974 *memcg = NULL;
1975 return 0;
1976 }
1977
1978 /*
1979 * Somemtimes we have to undo a charge we got by try_charge().
1980 * This function is for that and do uncharge, put css's refcnt.
1981 * gotten by try_charge().
1982 */
1983 static void __mem_cgroup_cancel_charge(struct mem_cgroup *mem,
1984 unsigned long count)
1985 {
1986 if (!mem_cgroup_is_root(mem)) {
1987 res_counter_uncharge(&mem->res, PAGE_SIZE * count);
1988 if (do_swap_account)
1989 res_counter_uncharge(&mem->memsw, PAGE_SIZE * count);
1990 }
1991 }
1992
1993 static void mem_cgroup_cancel_charge(struct mem_cgroup *mem)
1994 {
1995 __mem_cgroup_cancel_charge(mem, 1);
1996 }
1997
1998 /*
1999 * A helper function to get mem_cgroup from ID. must be called under
2000 * rcu_read_lock(). The caller must check css_is_removed() or some if
2001 * it's concern. (dropping refcnt from swap can be called against removed
2002 * memcg.)
2003 */
2004 static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
2005 {
2006 struct cgroup_subsys_state *css;
2007
2008 /* ID 0 is unused ID */
2009 if (!id)
2010 return NULL;
2011 css = css_lookup(&mem_cgroup_subsys, id);
2012 if (!css)
2013 return NULL;
2014 return container_of(css, struct mem_cgroup, css);
2015 }
2016
2017 struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
2018 {
2019 struct mem_cgroup *mem = NULL;
2020 struct page_cgroup *pc;
2021 unsigned short id;
2022 swp_entry_t ent;
2023
2024 VM_BUG_ON(!PageLocked(page));
2025
2026 pc = lookup_page_cgroup(page);
2027 lock_page_cgroup(pc);
2028 if (PageCgroupUsed(pc)) {
2029 mem = pc->mem_cgroup;
2030 if (mem && !css_tryget(&mem->css))
2031 mem = NULL;
2032 } else if (PageSwapCache(page)) {
2033 ent.val = page_private(page);
2034 id = lookup_swap_cgroup(ent);
2035 rcu_read_lock();
2036 mem = mem_cgroup_lookup(id);
2037 if (mem && !css_tryget(&mem->css))
2038 mem = NULL;
2039 rcu_read_unlock();
2040 }
2041 unlock_page_cgroup(pc);
2042 return mem;
2043 }
2044
2045 /*
2046 * commit a charge got by __mem_cgroup_try_charge() and makes page_cgroup to be
2047 * USED state. If already USED, uncharge and return.
2048 */
2049
2050 static void __mem_cgroup_commit_charge(struct mem_cgroup *mem,
2051 struct page_cgroup *pc,
2052 enum charge_type ctype)
2053 {
2054 /* try_charge() can return NULL to *memcg, taking care of it. */
2055 if (!mem)
2056 return;
2057
2058 lock_page_cgroup(pc);
2059 if (unlikely(PageCgroupUsed(pc))) {
2060 unlock_page_cgroup(pc);
2061 mem_cgroup_cancel_charge(mem);
2062 return;
2063 }
2064
2065 pc->mem_cgroup = mem;
2066 /*
2067 * We access a page_cgroup asynchronously without lock_page_cgroup().
2068 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
2069 * is accessed after testing USED bit. To make pc->mem_cgroup visible
2070 * before USED bit, we need memory barrier here.
2071 * See mem_cgroup_add_lru_list(), etc.
2072 */
2073 smp_wmb();
2074 switch (ctype) {
2075 case MEM_CGROUP_CHARGE_TYPE_CACHE:
2076 case MEM_CGROUP_CHARGE_TYPE_SHMEM:
2077 SetPageCgroupCache(pc);
2078 SetPageCgroupUsed(pc);
2079 break;
2080 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
2081 ClearPageCgroupCache(pc);
2082 SetPageCgroupUsed(pc);
2083 break;
2084 default:
2085 break;
2086 }
2087
2088 mem_cgroup_charge_statistics(mem, pc, true);
2089
2090 unlock_page_cgroup(pc);
2091 /*
2092 * "charge_statistics" updated event counter. Then, check it.
2093 * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
2094 * if they exceeds softlimit.
2095 */
2096 memcg_check_events(mem, pc->page);
2097 }
2098
2099 /**
2100 * __mem_cgroup_move_account - move account of the page
2101 * @pc: page_cgroup of the page.
2102 * @from: mem_cgroup which the page is moved from.
2103 * @to: mem_cgroup which the page is moved to. @from != @to.
2104 * @uncharge: whether we should call uncharge and css_put against @from.
2105 *
2106 * The caller must confirm following.
2107 * - page is not on LRU (isolate_page() is useful.)
2108 * - the pc is locked, used, and ->mem_cgroup points to @from.
2109 *
2110 * This function doesn't do "charge" nor css_get to new cgroup. It should be
2111 * done by a caller(__mem_cgroup_try_charge would be usefull). If @uncharge is
2112 * true, this function does "uncharge" from old cgroup, but it doesn't if
2113 * @uncharge is false, so a caller should do "uncharge".
2114 */
2115
2116 static void __mem_cgroup_move_account(struct page_cgroup *pc,
2117 struct mem_cgroup *from, struct mem_cgroup *to, bool uncharge)
2118 {
2119 VM_BUG_ON(from == to);
2120 VM_BUG_ON(PageLRU(pc->page));
2121 VM_BUG_ON(!PageCgroupLocked(pc));
2122 VM_BUG_ON(!PageCgroupUsed(pc));
2123 VM_BUG_ON(pc->mem_cgroup != from);
2124
2125 if (PageCgroupFileMapped(pc)) {
2126 /* Update mapped_file data for mem_cgroup */
2127 preempt_disable();
2128 __this_cpu_dec(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
2129 __this_cpu_inc(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
2130 preempt_enable();
2131 }
2132 mem_cgroup_charge_statistics(from, pc, false);
2133 if (uncharge)
2134 /* This is not "cancel", but cancel_charge does all we need. */
2135 mem_cgroup_cancel_charge(from);
2136
2137 /* caller should have done css_get */
2138 pc->mem_cgroup = to;
2139 mem_cgroup_charge_statistics(to, pc, true);
2140 /*
2141 * We charges against "to" which may not have any tasks. Then, "to"
2142 * can be under rmdir(). But in current implementation, caller of
2143 * this function is just force_empty() and move charge, so it's
2144 * garanteed that "to" is never removed. So, we don't check rmdir
2145 * status here.
2146 */
2147 }
2148
2149 /*
2150 * check whether the @pc is valid for moving account and call
2151 * __mem_cgroup_move_account()
2152 */
2153 static int mem_cgroup_move_account(struct page_cgroup *pc,
2154 struct mem_cgroup *from, struct mem_cgroup *to, bool uncharge)
2155 {
2156 int ret = -EINVAL;
2157 lock_page_cgroup(pc);
2158 if (PageCgroupUsed(pc) && pc->mem_cgroup == from) {
2159 __mem_cgroup_move_account(pc, from, to, uncharge);
2160 ret = 0;
2161 }
2162 unlock_page_cgroup(pc);
2163 /*
2164 * check events
2165 */
2166 memcg_check_events(to, pc->page);
2167 memcg_check_events(from, pc->page);
2168 return ret;
2169 }
2170
2171 /*
2172 * move charges to its parent.
2173 */
2174
2175 static int mem_cgroup_move_parent(struct page_cgroup *pc,
2176 struct mem_cgroup *child,
2177 gfp_t gfp_mask)
2178 {
2179 struct page *page = pc->page;
2180 struct cgroup *cg = child->css.cgroup;
2181 struct cgroup *pcg = cg->parent;
2182 struct mem_cgroup *parent;
2183 int ret;
2184
2185 /* Is ROOT ? */
2186 if (!pcg)
2187 return -EINVAL;
2188
2189 ret = -EBUSY;
2190 if (!get_page_unless_zero(page))
2191 goto out;
2192 if (isolate_lru_page(page))
2193 goto put;
2194
2195 parent = mem_cgroup_from_cont(pcg);
2196 ret = __mem_cgroup_try_charge(NULL, gfp_mask, &parent, false);
2197 if (ret || !parent)
2198 goto put_back;
2199
2200 ret = mem_cgroup_move_account(pc, child, parent, true);
2201 if (ret)
2202 mem_cgroup_cancel_charge(parent);
2203 put_back:
2204 putback_lru_page(page);
2205 put:
2206 put_page(page);
2207 out:
2208 return ret;
2209 }
2210
2211 /*
2212 * Charge the memory controller for page usage.
2213 * Return
2214 * 0 if the charge was successful
2215 * < 0 if the cgroup is over its limit
2216 */
2217 static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
2218 gfp_t gfp_mask, enum charge_type ctype)
2219 {
2220 struct mem_cgroup *mem = NULL;
2221 struct page_cgroup *pc;
2222 int ret;
2223
2224 pc = lookup_page_cgroup(page);
2225 /* can happen at boot */
2226 if (unlikely(!pc))
2227 return 0;
2228 prefetchw(pc);
2229
2230 ret = __mem_cgroup_try_charge(mm, gfp_mask, &mem, true);
2231 if (ret || !mem)
2232 return ret;
2233
2234 __mem_cgroup_commit_charge(mem, pc, ctype);
2235 return 0;
2236 }
2237
2238 int mem_cgroup_newpage_charge(struct page *page,
2239 struct mm_struct *mm, gfp_t gfp_mask)
2240 {
2241 if (mem_cgroup_disabled())
2242 return 0;
2243 if (PageCompound(page))
2244 return 0;
2245 /*
2246 * If already mapped, we don't have to account.
2247 * If page cache, page->mapping has address_space.
2248 * But page->mapping may have out-of-use anon_vma pointer,
2249 * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
2250 * is NULL.
2251 */
2252 if (page_mapped(page) || (page->mapping && !PageAnon(page)))
2253 return 0;
2254 if (unlikely(!mm))
2255 mm = &init_mm;
2256 return mem_cgroup_charge_common(page, mm, gfp_mask,
2257 MEM_CGROUP_CHARGE_TYPE_MAPPED);
2258 }
2259
2260 static void
2261 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
2262 enum charge_type ctype);
2263
2264 int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
2265 gfp_t gfp_mask)
2266 {
2267 int ret;
2268
2269 if (mem_cgroup_disabled())
2270 return 0;
2271 if (PageCompound(page))
2272 return 0;
2273 /*
2274 * Corner case handling. This is called from add_to_page_cache()
2275 * in usual. But some FS (shmem) precharges this page before calling it
2276 * and call add_to_page_cache() with GFP_NOWAIT.
2277 *
2278 * For GFP_NOWAIT case, the page may be pre-charged before calling
2279 * add_to_page_cache(). (See shmem.c) check it here and avoid to call
2280 * charge twice. (It works but has to pay a bit larger cost.)
2281 * And when the page is SwapCache, it should take swap information
2282 * into account. This is under lock_page() now.
2283 */
2284 if (!(gfp_mask & __GFP_WAIT)) {
2285 struct page_cgroup *pc;
2286
2287 pc = lookup_page_cgroup(page);
2288 if (!pc)
2289 return 0;
2290 lock_page_cgroup(pc);
2291 if (PageCgroupUsed(pc)) {
2292 unlock_page_cgroup(pc);
2293 return 0;
2294 }
2295 unlock_page_cgroup(pc);
2296 }
2297
2298 if (unlikely(!mm))
2299 mm = &init_mm;
2300
2301 if (page_is_file_cache(page))
2302 return mem_cgroup_charge_common(page, mm, gfp_mask,
2303 MEM_CGROUP_CHARGE_TYPE_CACHE);
2304
2305 /* shmem */
2306 if (PageSwapCache(page)) {
2307 struct mem_cgroup *mem = NULL;
2308
2309 ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
2310 if (!ret)
2311 __mem_cgroup_commit_charge_swapin(page, mem,
2312 MEM_CGROUP_CHARGE_TYPE_SHMEM);
2313 } else
2314 ret = mem_cgroup_charge_common(page, mm, gfp_mask,
2315 MEM_CGROUP_CHARGE_TYPE_SHMEM);
2316
2317 return ret;
2318 }
2319
2320 /*
2321 * While swap-in, try_charge -> commit or cancel, the page is locked.
2322 * And when try_charge() successfully returns, one refcnt to memcg without
2323 * struct page_cgroup is acquired. This refcnt will be consumed by
2324 * "commit()" or removed by "cancel()"
2325 */
2326 int mem_cgroup_try_charge_swapin(struct mm_struct *mm,
2327 struct page *page,
2328 gfp_t mask, struct mem_cgroup **ptr)
2329 {
2330 struct mem_cgroup *mem;
2331 int ret;
2332
2333 if (mem_cgroup_disabled())
2334 return 0;
2335
2336 if (!do_swap_account)
2337 goto charge_cur_mm;
2338 /*
2339 * A racing thread's fault, or swapoff, may have already updated
2340 * the pte, and even removed page from swap cache: in those cases
2341 * do_swap_page()'s pte_same() test will fail; but there's also a
2342 * KSM case which does need to charge the page.
2343 */
2344 if (!PageSwapCache(page))
2345 goto charge_cur_mm;
2346 mem = try_get_mem_cgroup_from_page(page);
2347 if (!mem)
2348 goto charge_cur_mm;
2349 *ptr = mem;
2350 ret = __mem_cgroup_try_charge(NULL, mask, ptr, true);
2351 css_put(&mem->css);
2352 return ret;
2353 charge_cur_mm:
2354 if (unlikely(!mm))
2355 mm = &init_mm;
2356 return __mem_cgroup_try_charge(mm, mask, ptr, true);
2357 }
2358
2359 static void
2360 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
2361 enum charge_type ctype)
2362 {
2363 struct page_cgroup *pc;
2364
2365 if (mem_cgroup_disabled())
2366 return;
2367 if (!ptr)
2368 return;
2369 cgroup_exclude_rmdir(&ptr->css);
2370 pc = lookup_page_cgroup(page);
2371 mem_cgroup_lru_del_before_commit_swapcache(page);
2372 __mem_cgroup_commit_charge(ptr, pc, ctype);
2373 mem_cgroup_lru_add_after_commit_swapcache(page);
2374 /*
2375 * Now swap is on-memory. This means this page may be
2376 * counted both as mem and swap....double count.
2377 * Fix it by uncharging from memsw. Basically, this SwapCache is stable
2378 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
2379 * may call delete_from_swap_cache() before reach here.
2380 */
2381 if (do_swap_account && PageSwapCache(page)) {
2382 swp_entry_t ent = {.val = page_private(page)};
2383 unsigned short id;
2384 struct mem_cgroup *memcg;
2385
2386 id = swap_cgroup_record(ent, 0);
2387 rcu_read_lock();
2388 memcg = mem_cgroup_lookup(id);
2389 if (memcg) {
2390 /*
2391 * This recorded memcg can be obsolete one. So, avoid
2392 * calling css_tryget
2393 */
2394 if (!mem_cgroup_is_root(memcg))
2395 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
2396 mem_cgroup_swap_statistics(memcg, false);
2397 mem_cgroup_put(memcg);
2398 }
2399 rcu_read_unlock();
2400 }
2401 /*
2402 * At swapin, we may charge account against cgroup which has no tasks.
2403 * So, rmdir()->pre_destroy() can be called while we do this charge.
2404 * In that case, we need to call pre_destroy() again. check it here.
2405 */
2406 cgroup_release_and_wakeup_rmdir(&ptr->css);
2407 }
2408
2409 void mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr)
2410 {
2411 __mem_cgroup_commit_charge_swapin(page, ptr,
2412 MEM_CGROUP_CHARGE_TYPE_MAPPED);
2413 }
2414
2415 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *mem)
2416 {
2417 if (mem_cgroup_disabled())
2418 return;
2419 if (!mem)
2420 return;
2421 mem_cgroup_cancel_charge(mem);
2422 }
2423
2424 static void
2425 __do_uncharge(struct mem_cgroup *mem, const enum charge_type ctype)
2426 {
2427 struct memcg_batch_info *batch = NULL;
2428 bool uncharge_memsw = true;
2429 /* If swapout, usage of swap doesn't decrease */
2430 if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2431 uncharge_memsw = false;
2432
2433 batch = &current->memcg_batch;
2434 /*
2435 * In usual, we do css_get() when we remember memcg pointer.
2436 * But in this case, we keep res->usage until end of a series of
2437 * uncharges. Then, it's ok to ignore memcg's refcnt.
2438 */
2439 if (!batch->memcg)
2440 batch->memcg = mem;
2441 /*
2442 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
2443 * In those cases, all pages freed continously can be expected to be in
2444 * the same cgroup and we have chance to coalesce uncharges.
2445 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
2446 * because we want to do uncharge as soon as possible.
2447 */
2448
2449 if (!batch->do_batch || test_thread_flag(TIF_MEMDIE))
2450 goto direct_uncharge;
2451
2452 /*
2453 * In typical case, batch->memcg == mem. This means we can
2454 * merge a series of uncharges to an uncharge of res_counter.
2455 * If not, we uncharge res_counter ony by one.
2456 */
2457 if (batch->memcg != mem)
2458 goto direct_uncharge;
2459 /* remember freed charge and uncharge it later */
2460 batch->bytes += PAGE_SIZE;
2461 if (uncharge_memsw)
2462 batch->memsw_bytes += PAGE_SIZE;
2463 return;
2464 direct_uncharge:
2465 res_counter_uncharge(&mem->res, PAGE_SIZE);
2466 if (uncharge_memsw)
2467 res_counter_uncharge(&mem->memsw, PAGE_SIZE);
2468 if (unlikely(batch->memcg != mem))
2469 memcg_oom_recover(mem);
2470 return;
2471 }
2472
2473 /*
2474 * uncharge if !page_mapped(page)
2475 */
2476 static struct mem_cgroup *
2477 __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype)
2478 {
2479 struct page_cgroup *pc;
2480 struct mem_cgroup *mem = NULL;
2481
2482 if (mem_cgroup_disabled())
2483 return NULL;
2484
2485 if (PageSwapCache(page))
2486 return NULL;
2487
2488 /*
2489 * Check if our page_cgroup is valid
2490 */
2491 pc = lookup_page_cgroup(page);
2492 if (unlikely(!pc || !PageCgroupUsed(pc)))
2493 return NULL;
2494
2495 lock_page_cgroup(pc);
2496
2497 mem = pc->mem_cgroup;
2498
2499 if (!PageCgroupUsed(pc))
2500 goto unlock_out;
2501
2502 switch (ctype) {
2503 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
2504 case MEM_CGROUP_CHARGE_TYPE_DROP:
2505 /* See mem_cgroup_prepare_migration() */
2506 if (page_mapped(page) || PageCgroupMigration(pc))
2507 goto unlock_out;
2508 break;
2509 case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
2510 if (!PageAnon(page)) { /* Shared memory */
2511 if (page->mapping && !page_is_file_cache(page))
2512 goto unlock_out;
2513 } else if (page_mapped(page)) /* Anon */
2514 goto unlock_out;
2515 break;
2516 default:
2517 break;
2518 }
2519
2520 mem_cgroup_charge_statistics(mem, pc, false);
2521
2522 ClearPageCgroupUsed(pc);
2523 /*
2524 * pc->mem_cgroup is not cleared here. It will be accessed when it's
2525 * freed from LRU. This is safe because uncharged page is expected not
2526 * to be reused (freed soon). Exception is SwapCache, it's handled by
2527 * special functions.
2528 */
2529
2530 unlock_page_cgroup(pc);
2531 /*
2532 * even after unlock, we have mem->res.usage here and this memcg
2533 * will never be freed.
2534 */
2535 memcg_check_events(mem, page);
2536 if (do_swap_account && ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT) {
2537 mem_cgroup_swap_statistics(mem, true);
2538 mem_cgroup_get(mem);
2539 }
2540 if (!mem_cgroup_is_root(mem))
2541 __do_uncharge(mem, ctype);
2542
2543 return mem;
2544
2545 unlock_out:
2546 unlock_page_cgroup(pc);
2547 return NULL;
2548 }
2549
2550 void mem_cgroup_uncharge_page(struct page *page)
2551 {
2552 /* early check. */
2553 if (page_mapped(page))
2554 return;
2555 if (page->mapping && !PageAnon(page))
2556 return;
2557 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_MAPPED);
2558 }
2559
2560 void mem_cgroup_uncharge_cache_page(struct page *page)
2561 {
2562 VM_BUG_ON(page_mapped(page));
2563 VM_BUG_ON(page->mapping);
2564 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE);
2565 }
2566
2567 /*
2568 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
2569 * In that cases, pages are freed continuously and we can expect pages
2570 * are in the same memcg. All these calls itself limits the number of
2571 * pages freed at once, then uncharge_start/end() is called properly.
2572 * This may be called prural(2) times in a context,
2573 */
2574
2575 void mem_cgroup_uncharge_start(void)
2576 {
2577 current->memcg_batch.do_batch++;
2578 /* We can do nest. */
2579 if (current->memcg_batch.do_batch == 1) {
2580 current->memcg_batch.memcg = NULL;
2581 current->memcg_batch.bytes = 0;
2582 current->memcg_batch.memsw_bytes = 0;
2583 }
2584 }
2585
2586 void mem_cgroup_uncharge_end(void)
2587 {
2588 struct memcg_batch_info *batch = &current->memcg_batch;
2589
2590 if (!batch->do_batch)
2591 return;
2592
2593 batch->do_batch--;
2594 if (batch->do_batch) /* If stacked, do nothing. */
2595 return;
2596
2597 if (!batch->memcg)
2598 return;
2599 /*
2600 * This "batch->memcg" is valid without any css_get/put etc...
2601 * bacause we hide charges behind us.
2602 */
2603 if (batch->bytes)
2604 res_counter_uncharge(&batch->memcg->res, batch->bytes);
2605 if (batch->memsw_bytes)
2606 res_counter_uncharge(&batch->memcg->memsw, batch->memsw_bytes);
2607 memcg_oom_recover(batch->memcg);
2608 /* forget this pointer (for sanity check) */
2609 batch->memcg = NULL;
2610 }
2611
2612 #ifdef CONFIG_SWAP
2613 /*
2614 * called after __delete_from_swap_cache() and drop "page" account.
2615 * memcg information is recorded to swap_cgroup of "ent"
2616 */
2617 void
2618 mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
2619 {
2620 struct mem_cgroup *memcg;
2621 int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
2622
2623 if (!swapout) /* this was a swap cache but the swap is unused ! */
2624 ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
2625
2626 memcg = __mem_cgroup_uncharge_common(page, ctype);
2627
2628 /*
2629 * record memcg information, if swapout && memcg != NULL,
2630 * mem_cgroup_get() was called in uncharge().
2631 */
2632 if (do_swap_account && swapout && memcg)
2633 swap_cgroup_record(ent, css_id(&memcg->css));
2634 }
2635 #endif
2636
2637 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
2638 /*
2639 * called from swap_entry_free(). remove record in swap_cgroup and
2640 * uncharge "memsw" account.
2641 */
2642 void mem_cgroup_uncharge_swap(swp_entry_t ent)
2643 {
2644 struct mem_cgroup *memcg;
2645 unsigned short id;
2646
2647 if (!do_swap_account)
2648 return;
2649
2650 id = swap_cgroup_record(ent, 0);
2651 rcu_read_lock();
2652 memcg = mem_cgroup_lookup(id);
2653 if (memcg) {
2654 /*
2655 * We uncharge this because swap is freed.
2656 * This memcg can be obsolete one. We avoid calling css_tryget
2657 */
2658 if (!mem_cgroup_is_root(memcg))
2659 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
2660 mem_cgroup_swap_statistics(memcg, false);
2661 mem_cgroup_put(memcg);
2662 }
2663 rcu_read_unlock();
2664 }
2665
2666 /**
2667 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
2668 * @entry: swap entry to be moved
2669 * @from: mem_cgroup which the entry is moved from
2670 * @to: mem_cgroup which the entry is moved to
2671 * @need_fixup: whether we should fixup res_counters and refcounts.
2672 *
2673 * It succeeds only when the swap_cgroup's record for this entry is the same
2674 * as the mem_cgroup's id of @from.
2675 *
2676 * Returns 0 on success, -EINVAL on failure.
2677 *
2678 * The caller must have charged to @to, IOW, called res_counter_charge() about
2679 * both res and memsw, and called css_get().
2680 */
2681 static int mem_cgroup_move_swap_account(swp_entry_t entry,
2682 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
2683 {
2684 unsigned short old_id, new_id;
2685
2686 old_id = css_id(&from->css);
2687 new_id = css_id(&to->css);
2688
2689 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
2690 mem_cgroup_swap_statistics(from, false);
2691 mem_cgroup_swap_statistics(to, true);
2692 /*
2693 * This function is only called from task migration context now.
2694 * It postpones res_counter and refcount handling till the end
2695 * of task migration(mem_cgroup_clear_mc()) for performance
2696 * improvement. But we cannot postpone mem_cgroup_get(to)
2697 * because if the process that has been moved to @to does
2698 * swap-in, the refcount of @to might be decreased to 0.
2699 */
2700 mem_cgroup_get(to);
2701 if (need_fixup) {
2702 if (!mem_cgroup_is_root(from))
2703 res_counter_uncharge(&from->memsw, PAGE_SIZE);
2704 mem_cgroup_put(from);
2705 /*
2706 * we charged both to->res and to->memsw, so we should
2707 * uncharge to->res.
2708 */
2709 if (!mem_cgroup_is_root(to))
2710 res_counter_uncharge(&to->res, PAGE_SIZE);
2711 }
2712 return 0;
2713 }
2714 return -EINVAL;
2715 }
2716 #else
2717 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
2718 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
2719 {
2720 return -EINVAL;
2721 }
2722 #endif
2723
2724 /*
2725 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
2726 * page belongs to.
2727 */
2728 int mem_cgroup_prepare_migration(struct page *page,
2729 struct page *newpage, struct mem_cgroup **ptr)
2730 {
2731 struct page_cgroup *pc;
2732 struct mem_cgroup *mem = NULL;
2733 enum charge_type ctype;
2734 int ret = 0;
2735
2736 if (mem_cgroup_disabled())
2737 return 0;
2738
2739 pc = lookup_page_cgroup(page);
2740 lock_page_cgroup(pc);
2741 if (PageCgroupUsed(pc)) {
2742 mem = pc->mem_cgroup;
2743 css_get(&mem->css);
2744 /*
2745 * At migrating an anonymous page, its mapcount goes down
2746 * to 0 and uncharge() will be called. But, even if it's fully
2747 * unmapped, migration may fail and this page has to be
2748 * charged again. We set MIGRATION flag here and delay uncharge
2749 * until end_migration() is called
2750 *
2751 * Corner Case Thinking
2752 * A)
2753 * When the old page was mapped as Anon and it's unmap-and-freed
2754 * while migration was ongoing.
2755 * If unmap finds the old page, uncharge() of it will be delayed
2756 * until end_migration(). If unmap finds a new page, it's
2757 * uncharged when it make mapcount to be 1->0. If unmap code
2758 * finds swap_migration_entry, the new page will not be mapped
2759 * and end_migration() will find it(mapcount==0).
2760 *
2761 * B)
2762 * When the old page was mapped but migraion fails, the kernel
2763 * remaps it. A charge for it is kept by MIGRATION flag even
2764 * if mapcount goes down to 0. We can do remap successfully
2765 * without charging it again.
2766 *
2767 * C)
2768 * The "old" page is under lock_page() until the end of
2769 * migration, so, the old page itself will not be swapped-out.
2770 * If the new page is swapped out before end_migraton, our
2771 * hook to usual swap-out path will catch the event.
2772 */
2773 if (PageAnon(page))
2774 SetPageCgroupMigration(pc);
2775 }
2776 unlock_page_cgroup(pc);
2777 /*
2778 * If the page is not charged at this point,
2779 * we return here.
2780 */
2781 if (!mem)
2782 return 0;
2783
2784 *ptr = mem;
2785 ret = __mem_cgroup_try_charge(NULL, GFP_KERNEL, ptr, false);
2786 css_put(&mem->css);/* drop extra refcnt */
2787 if (ret || *ptr == NULL) {
2788 if (PageAnon(page)) {
2789 lock_page_cgroup(pc);
2790 ClearPageCgroupMigration(pc);
2791 unlock_page_cgroup(pc);
2792 /*
2793 * The old page may be fully unmapped while we kept it.
2794 */
2795 mem_cgroup_uncharge_page(page);
2796 }
2797 return -ENOMEM;
2798 }
2799 /*
2800 * We charge new page before it's used/mapped. So, even if unlock_page()
2801 * is called before end_migration, we can catch all events on this new
2802 * page. In the case new page is migrated but not remapped, new page's
2803 * mapcount will be finally 0 and we call uncharge in end_migration().
2804 */
2805 pc = lookup_page_cgroup(newpage);
2806 if (PageAnon(page))
2807 ctype = MEM_CGROUP_CHARGE_TYPE_MAPPED;
2808 else if (page_is_file_cache(page))
2809 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
2810 else
2811 ctype = MEM_CGROUP_CHARGE_TYPE_SHMEM;
2812 __mem_cgroup_commit_charge(mem, pc, ctype);
2813 return ret;
2814 }
2815
2816 /* remove redundant charge if migration failed*/
2817 void mem_cgroup_end_migration(struct mem_cgroup *mem,
2818 struct page *oldpage, struct page *newpage)
2819 {
2820 struct page *used, *unused;
2821 struct page_cgroup *pc;
2822
2823 if (!mem)
2824 return;
2825 /* blocks rmdir() */
2826 cgroup_exclude_rmdir(&mem->css);
2827 /* at migration success, oldpage->mapping is NULL. */
2828 if (oldpage->mapping) {
2829 used = oldpage;
2830 unused = newpage;
2831 } else {
2832 used = newpage;
2833 unused = oldpage;
2834 }
2835 /*
2836 * We disallowed uncharge of pages under migration because mapcount
2837 * of the page goes down to zero, temporarly.
2838 * Clear the flag and check the page should be charged.
2839 */
2840 pc = lookup_page_cgroup(oldpage);
2841 lock_page_cgroup(pc);
2842 ClearPageCgroupMigration(pc);
2843 unlock_page_cgroup(pc);
2844
2845 __mem_cgroup_uncharge_common(unused, MEM_CGROUP_CHARGE_TYPE_FORCE);
2846
2847 /*
2848 * If a page is a file cache, radix-tree replacement is very atomic
2849 * and we can skip this check. When it was an Anon page, its mapcount
2850 * goes down to 0. But because we added MIGRATION flage, it's not
2851 * uncharged yet. There are several case but page->mapcount check
2852 * and USED bit check in mem_cgroup_uncharge_page() will do enough
2853 * check. (see prepare_charge() also)
2854 */
2855 if (PageAnon(used))
2856 mem_cgroup_uncharge_page(used);
2857 /*
2858 * At migration, we may charge account against cgroup which has no
2859 * tasks.
2860 * So, rmdir()->pre_destroy() can be called while we do this charge.
2861 * In that case, we need to call pre_destroy() again. check it here.
2862 */
2863 cgroup_release_and_wakeup_rmdir(&mem->css);
2864 }
2865
2866 /*
2867 * A call to try to shrink memory usage on charge failure at shmem's swapin.
2868 * Calling hierarchical_reclaim is not enough because we should update
2869 * last_oom_jiffies to prevent pagefault_out_of_memory from invoking global OOM.
2870 * Moreover considering hierarchy, we should reclaim from the mem_over_limit,
2871 * not from the memcg which this page would be charged to.
2872 * try_charge_swapin does all of these works properly.
2873 */
2874 int mem_cgroup_shmem_charge_fallback(struct page *page,
2875 struct mm_struct *mm,
2876 gfp_t gfp_mask)
2877 {
2878 struct mem_cgroup *mem = NULL;
2879 int ret;
2880
2881 if (mem_cgroup_disabled())
2882 return 0;
2883
2884 ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
2885 if (!ret)
2886 mem_cgroup_cancel_charge_swapin(mem); /* it does !mem check */
2887
2888 return ret;
2889 }
2890
2891 static DEFINE_MUTEX(set_limit_mutex);
2892
2893 static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
2894 unsigned long long val)
2895 {
2896 int retry_count;
2897 u64 memswlimit, memlimit;
2898 int ret = 0;
2899 int children = mem_cgroup_count_children(memcg);
2900 u64 curusage, oldusage;
2901 int enlarge;
2902
2903 /*
2904 * For keeping hierarchical_reclaim simple, how long we should retry
2905 * is depends on callers. We set our retry-count to be function
2906 * of # of children which we should visit in this loop.
2907 */
2908 retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
2909
2910 oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
2911
2912 enlarge = 0;
2913 while (retry_count) {
2914 if (signal_pending(current)) {
2915 ret = -EINTR;
2916 break;
2917 }
2918 /*
2919 * Rather than hide all in some function, I do this in
2920 * open coded manner. You see what this really does.
2921 * We have to guarantee mem->res.limit < mem->memsw.limit.
2922 */
2923 mutex_lock(&set_limit_mutex);
2924 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
2925 if (memswlimit < val) {
2926 ret = -EINVAL;
2927 mutex_unlock(&set_limit_mutex);
2928 break;
2929 }
2930
2931 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
2932 if (memlimit < val)
2933 enlarge = 1;
2934
2935 ret = res_counter_set_limit(&memcg->res, val);
2936 if (!ret) {
2937 if (memswlimit == val)
2938 memcg->memsw_is_minimum = true;
2939 else
2940 memcg->memsw_is_minimum = false;
2941 }
2942 mutex_unlock(&set_limit_mutex);
2943
2944 if (!ret)
2945 break;
2946
2947 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
2948 MEM_CGROUP_RECLAIM_SHRINK);
2949 curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
2950 /* Usage is reduced ? */
2951 if (curusage >= oldusage)
2952 retry_count--;
2953 else
2954 oldusage = curusage;
2955 }
2956 if (!ret && enlarge)
2957 memcg_oom_recover(memcg);
2958
2959 return ret;
2960 }
2961
2962 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
2963 unsigned long long val)
2964 {
2965 int retry_count;
2966 u64 memlimit, memswlimit, oldusage, curusage;
2967 int children = mem_cgroup_count_children(memcg);
2968 int ret = -EBUSY;
2969 int enlarge = 0;
2970
2971 /* see mem_cgroup_resize_res_limit */
2972 retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
2973 oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
2974 while (retry_count) {
2975 if (signal_pending(current)) {
2976 ret = -EINTR;
2977 break;
2978 }
2979 /*
2980 * Rather than hide all in some function, I do this in
2981 * open coded manner. You see what this really does.
2982 * We have to guarantee mem->res.limit < mem->memsw.limit.
2983 */
2984 mutex_lock(&set_limit_mutex);
2985 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
2986 if (memlimit > val) {
2987 ret = -EINVAL;
2988 mutex_unlock(&set_limit_mutex);
2989 break;
2990 }
2991 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
2992 if (memswlimit < val)
2993 enlarge = 1;
2994 ret = res_counter_set_limit(&memcg->memsw, val);
2995 if (!ret) {
2996 if (memlimit == val)
2997 memcg->memsw_is_minimum = true;
2998 else
2999 memcg->memsw_is_minimum = false;
3000 }
3001 mutex_unlock(&set_limit_mutex);
3002
3003 if (!ret)
3004 break;
3005
3006 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
3007 MEM_CGROUP_RECLAIM_NOSWAP |
3008 MEM_CGROUP_RECLAIM_SHRINK);
3009 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
3010 /* Usage is reduced ? */
3011 if (curusage >= oldusage)
3012 retry_count--;
3013 else
3014 oldusage = curusage;
3015 }
3016 if (!ret && enlarge)
3017 memcg_oom_recover(memcg);
3018 return ret;
3019 }
3020
3021 unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
3022 gfp_t gfp_mask)
3023 {
3024 unsigned long nr_reclaimed = 0;
3025 struct mem_cgroup_per_zone *mz, *next_mz = NULL;
3026 unsigned long reclaimed;
3027 int loop = 0;
3028 struct mem_cgroup_tree_per_zone *mctz;
3029 unsigned long long excess;
3030
3031 if (order > 0)
3032 return 0;
3033
3034 mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone));
3035 /*
3036 * This loop can run a while, specially if mem_cgroup's continuously
3037 * keep exceeding their soft limit and putting the system under
3038 * pressure
3039 */
3040 do {
3041 if (next_mz)
3042 mz = next_mz;
3043 else
3044 mz = mem_cgroup_largest_soft_limit_node(mctz);
3045 if (!mz)
3046 break;
3047
3048 reclaimed = mem_cgroup_hierarchical_reclaim(mz->mem, zone,
3049 gfp_mask,
3050 MEM_CGROUP_RECLAIM_SOFT);
3051 nr_reclaimed += reclaimed;
3052 spin_lock(&mctz->lock);
3053
3054 /*
3055 * If we failed to reclaim anything from this memory cgroup
3056 * it is time to move on to the next cgroup
3057 */
3058 next_mz = NULL;
3059 if (!reclaimed) {
3060 do {
3061 /*
3062 * Loop until we find yet another one.
3063 *
3064 * By the time we get the soft_limit lock
3065 * again, someone might have aded the
3066 * group back on the RB tree. Iterate to
3067 * make sure we get a different mem.
3068 * mem_cgroup_largest_soft_limit_node returns
3069 * NULL if no other cgroup is present on
3070 * the tree
3071 */
3072 next_mz =
3073 __mem_cgroup_largest_soft_limit_node(mctz);
3074 if (next_mz == mz) {
3075 css_put(&next_mz->mem->css);
3076 next_mz = NULL;
3077 } else /* next_mz == NULL or other memcg */
3078 break;
3079 } while (1);
3080 }
3081 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
3082 excess = res_counter_soft_limit_excess(&mz->mem->res);
3083 /*
3084 * One school of thought says that we should not add
3085 * back the node to the tree if reclaim returns 0.
3086 * But our reclaim could return 0, simply because due
3087 * to priority we are exposing a smaller subset of
3088 * memory to reclaim from. Consider this as a longer
3089 * term TODO.
3090 */
3091 /* If excess == 0, no tree ops */
3092 __mem_cgroup_insert_exceeded(mz->mem, mz, mctz, excess);
3093 spin_unlock(&mctz->lock);
3094 css_put(&mz->mem->css);
3095 loop++;
3096 /*
3097 * Could not reclaim anything and there are no more
3098 * mem cgroups to try or we seem to be looping without
3099 * reclaiming anything.
3100 */
3101 if (!nr_reclaimed &&
3102 (next_mz == NULL ||
3103 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3104 break;
3105 } while (!nr_reclaimed);
3106 if (next_mz)
3107 css_put(&next_mz->mem->css);
3108 return nr_reclaimed;
3109 }
3110
3111 /*
3112 * This routine traverse page_cgroup in given list and drop them all.
3113 * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
3114 */
3115 static int mem_cgroup_force_empty_list(struct mem_cgroup *mem,
3116 int node, int zid, enum lru_list lru)
3117 {
3118 struct zone *zone;
3119 struct mem_cgroup_per_zone *mz;
3120 struct page_cgroup *pc, *busy;
3121 unsigned long flags, loop;
3122 struct list_head *list;
3123 int ret = 0;
3124
3125 zone = &NODE_DATA(node)->node_zones[zid];
3126 mz = mem_cgroup_zoneinfo(mem, node, zid);
3127 list = &mz->lists[lru];
3128
3129 loop = MEM_CGROUP_ZSTAT(mz, lru);
3130 /* give some margin against EBUSY etc...*/
3131 loop += 256;
3132 busy = NULL;
3133 while (loop--) {
3134 ret = 0;
3135 spin_lock_irqsave(&zone->lru_lock, flags);
3136 if (list_empty(list)) {
3137 spin_unlock_irqrestore(&zone->lru_lock, flags);
3138 break;
3139 }
3140 pc = list_entry(list->prev, struct page_cgroup, lru);
3141 if (busy == pc) {
3142 list_move(&pc->lru, list);
3143 busy = NULL;
3144 spin_unlock_irqrestore(&zone->lru_lock, flags);
3145 continue;
3146 }
3147 spin_unlock_irqrestore(&zone->lru_lock, flags);
3148
3149 ret = mem_cgroup_move_parent(pc, mem, GFP_KERNEL);
3150 if (ret == -ENOMEM)
3151 break;
3152
3153 if (ret == -EBUSY || ret == -EINVAL) {
3154 /* found lock contention or "pc" is obsolete. */
3155 busy = pc;
3156 cond_resched();
3157 } else
3158 busy = NULL;
3159 }
3160
3161 if (!ret && !list_empty(list))
3162 return -EBUSY;
3163 return ret;
3164 }
3165
3166 /*
3167 * make mem_cgroup's charge to be 0 if there is no task.
3168 * This enables deleting this mem_cgroup.
3169 */
3170 static int mem_cgroup_force_empty(struct mem_cgroup *mem, bool free_all)
3171 {
3172 int ret;
3173 int node, zid, shrink;
3174 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
3175 struct cgroup *cgrp = mem->css.cgroup;
3176
3177 css_get(&mem->css);
3178
3179 shrink = 0;
3180 /* should free all ? */
3181 if (free_all)
3182 goto try_to_free;
3183 move_account:
3184 do {
3185 ret = -EBUSY;
3186 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
3187 goto out;
3188 ret = -EINTR;
3189 if (signal_pending(current))
3190 goto out;
3191 /* This is for making all *used* pages to be on LRU. */
3192 lru_add_drain_all();
3193 drain_all_stock_sync();
3194 ret = 0;
3195 mem_cgroup_start_move(mem);
3196 for_each_node_state(node, N_HIGH_MEMORY) {
3197 for (zid = 0; !ret && zid < MAX_NR_ZONES; zid++) {
3198 enum lru_list l;
3199 for_each_lru(l) {
3200 ret = mem_cgroup_force_empty_list(mem,
3201 node, zid, l);
3202 if (ret)
3203 break;
3204 }
3205 }
3206 if (ret)
3207 break;
3208 }
3209 mem_cgroup_end_move(mem);
3210 memcg_oom_recover(mem);
3211 /* it seems parent cgroup doesn't have enough mem */
3212 if (ret == -ENOMEM)
3213 goto try_to_free;
3214 cond_resched();
3215 /* "ret" should also be checked to ensure all lists are empty. */
3216 } while (mem->res.usage > 0 || ret);
3217 out:
3218 css_put(&mem->css);
3219 return ret;
3220
3221 try_to_free:
3222 /* returns EBUSY if there is a task or if we come here twice. */
3223 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children) || shrink) {
3224 ret = -EBUSY;
3225 goto out;
3226 }
3227 /* we call try-to-free pages for make this cgroup empty */
3228 lru_add_drain_all();
3229 /* try to free all pages in this cgroup */
3230 shrink = 1;
3231 while (nr_retries && mem->res.usage > 0) {
3232 int progress;
3233
3234 if (signal_pending(current)) {
3235 ret = -EINTR;
3236 goto out;
3237 }
3238 progress = try_to_free_mem_cgroup_pages(mem, GFP_KERNEL,
3239 false, get_swappiness(mem));
3240 if (!progress) {
3241 nr_retries--;
3242 /* maybe some writeback is necessary */
3243 congestion_wait(BLK_RW_ASYNC, HZ/10);
3244 }
3245
3246 }
3247 lru_add_drain();
3248 /* try move_account...there may be some *locked* pages. */
3249 goto move_account;
3250 }
3251
3252 int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
3253 {
3254 return mem_cgroup_force_empty(mem_cgroup_from_cont(cont), true);
3255 }
3256
3257
3258 static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
3259 {
3260 return mem_cgroup_from_cont(cont)->use_hierarchy;
3261 }
3262
3263 static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
3264 u64 val)
3265 {
3266 int retval = 0;
3267 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
3268 struct cgroup *parent = cont->parent;
3269 struct mem_cgroup *parent_mem = NULL;
3270
3271 if (parent)
3272 parent_mem = mem_cgroup_from_cont(parent);
3273
3274 cgroup_lock();
3275 /*
3276 * If parent's use_hierarchy is set, we can't make any modifications
3277 * in the child subtrees. If it is unset, then the change can
3278 * occur, provided the current cgroup has no children.
3279 *
3280 * For the root cgroup, parent_mem is NULL, we allow value to be
3281 * set if there are no children.
3282 */
3283 if ((!parent_mem || !parent_mem->use_hierarchy) &&
3284 (val == 1 || val == 0)) {
3285 if (list_empty(&cont->children))
3286 mem->use_hierarchy = val;
3287 else
3288 retval = -EBUSY;
3289 } else
3290 retval = -EINVAL;
3291 cgroup_unlock();
3292
3293 return retval;
3294 }
3295
3296
3297 static u64 mem_cgroup_get_recursive_idx_stat(struct mem_cgroup *mem,
3298 enum mem_cgroup_stat_index idx)
3299 {
3300 struct mem_cgroup *iter;
3301 s64 val = 0;
3302
3303 /* each per cpu's value can be minus.Then, use s64 */
3304 for_each_mem_cgroup_tree(iter, mem)
3305 val += mem_cgroup_read_stat(iter, idx);
3306
3307 if (val < 0) /* race ? */
3308 val = 0;
3309 return val;
3310 }
3311
3312 static inline u64 mem_cgroup_usage(struct mem_cgroup *mem, bool swap)
3313 {
3314 u64 val;
3315
3316 if (!mem_cgroup_is_root(mem)) {
3317 if (!swap)
3318 return res_counter_read_u64(&mem->res, RES_USAGE);
3319 else
3320 return res_counter_read_u64(&mem->memsw, RES_USAGE);
3321 }
3322
3323 val = mem_cgroup_get_recursive_idx_stat(mem, MEM_CGROUP_STAT_CACHE);
3324 val += mem_cgroup_get_recursive_idx_stat(mem, MEM_CGROUP_STAT_RSS);
3325
3326 if (swap)
3327 val += mem_cgroup_get_recursive_idx_stat(mem,
3328 MEM_CGROUP_STAT_SWAPOUT);
3329
3330 return val << PAGE_SHIFT;
3331 }
3332
3333 static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft)
3334 {
3335 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
3336 u64 val;
3337 int type, name;
3338
3339 type = MEMFILE_TYPE(cft->private);
3340 name = MEMFILE_ATTR(cft->private);
3341 switch (type) {
3342 case _MEM:
3343 if (name == RES_USAGE)
3344 val = mem_cgroup_usage(mem, false);
3345 else
3346 val = res_counter_read_u64(&mem->res, name);
3347 break;
3348 case _MEMSWAP:
3349 if (name == RES_USAGE)
3350 val = mem_cgroup_usage(mem, true);
3351 else
3352 val = res_counter_read_u64(&mem->memsw, name);
3353 break;
3354 default:
3355 BUG();
3356 break;
3357 }
3358 return val;
3359 }
3360 /*
3361 * The user of this function is...
3362 * RES_LIMIT.
3363 */
3364 static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
3365 const char *buffer)
3366 {
3367 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
3368 int type, name;
3369 unsigned long long val;
3370 int ret;
3371
3372 type = MEMFILE_TYPE(cft->private);
3373 name = MEMFILE_ATTR(cft->private);
3374 switch (name) {
3375 case RES_LIMIT:
3376 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3377 ret = -EINVAL;
3378 break;
3379 }
3380 /* This function does all necessary parse...reuse it */
3381 ret = res_counter_memparse_write_strategy(buffer, &val);
3382 if (ret)
3383 break;
3384 if (type == _MEM)
3385 ret = mem_cgroup_resize_limit(memcg, val);
3386 else
3387 ret = mem_cgroup_resize_memsw_limit(memcg, val);
3388 break;
3389 case RES_SOFT_LIMIT:
3390 ret = res_counter_memparse_write_strategy(buffer, &val);
3391 if (ret)
3392 break;
3393 /*
3394 * For memsw, soft limits are hard to implement in terms
3395 * of semantics, for now, we support soft limits for
3396 * control without swap
3397 */
3398 if (type == _MEM)
3399 ret = res_counter_set_soft_limit(&memcg->res, val);
3400 else
3401 ret = -EINVAL;
3402 break;
3403 default:
3404 ret = -EINVAL; /* should be BUG() ? */
3405 break;
3406 }
3407 return ret;
3408 }
3409
3410 static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
3411 unsigned long long *mem_limit, unsigned long long *memsw_limit)
3412 {
3413 struct cgroup *cgroup;
3414 unsigned long long min_limit, min_memsw_limit, tmp;
3415
3416 min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3417 min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3418 cgroup = memcg->css.cgroup;
3419 if (!memcg->use_hierarchy)
3420 goto out;
3421
3422 while (cgroup->parent) {
3423 cgroup = cgroup->parent;
3424 memcg = mem_cgroup_from_cont(cgroup);
3425 if (!memcg->use_hierarchy)
3426 break;
3427 tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
3428 min_limit = min(min_limit, tmp);
3429 tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3430 min_memsw_limit = min(min_memsw_limit, tmp);
3431 }
3432 out:
3433 *mem_limit = min_limit;
3434 *memsw_limit = min_memsw_limit;
3435 return;
3436 }
3437
3438 static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
3439 {
3440 struct mem_cgroup *mem;
3441 int type, name;
3442
3443 mem = mem_cgroup_from_cont(cont);
3444 type = MEMFILE_TYPE(event);
3445 name = MEMFILE_ATTR(event);
3446 switch (name) {
3447 case RES_MAX_USAGE:
3448 if (type == _MEM)
3449 res_counter_reset_max(&mem->res);
3450 else
3451 res_counter_reset_max(&mem->memsw);
3452 break;
3453 case RES_FAILCNT:
3454 if (type == _MEM)
3455 res_counter_reset_failcnt(&mem->res);
3456 else
3457 res_counter_reset_failcnt(&mem->memsw);
3458 break;
3459 }
3460
3461 return 0;
3462 }
3463
3464 static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp,
3465 struct cftype *cft)
3466 {
3467 return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate;
3468 }
3469
3470 #ifdef CONFIG_MMU
3471 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
3472 struct cftype *cft, u64 val)
3473 {
3474 struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
3475
3476 if (val >= (1 << NR_MOVE_TYPE))
3477 return -EINVAL;
3478 /*
3479 * We check this value several times in both in can_attach() and
3480 * attach(), so we need cgroup lock to prevent this value from being
3481 * inconsistent.
3482 */
3483 cgroup_lock();
3484 mem->move_charge_at_immigrate = val;
3485 cgroup_unlock();
3486
3487 return 0;
3488 }
3489 #else
3490 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
3491 struct cftype *cft, u64 val)
3492 {
3493 return -ENOSYS;
3494 }
3495 #endif
3496
3497
3498 /* For read statistics */
3499 enum {
3500 MCS_CACHE,
3501 MCS_RSS,
3502 MCS_FILE_MAPPED,
3503 MCS_PGPGIN,
3504 MCS_PGPGOUT,
3505 MCS_SWAP,
3506 MCS_INACTIVE_ANON,
3507 MCS_ACTIVE_ANON,
3508 MCS_INACTIVE_FILE,
3509 MCS_ACTIVE_FILE,
3510 MCS_UNEVICTABLE,
3511 NR_MCS_STAT,
3512 };
3513
3514 struct mcs_total_stat {
3515 s64 stat[NR_MCS_STAT];
3516 };
3517
3518 struct {
3519 char *local_name;
3520 char *total_name;
3521 } memcg_stat_strings[NR_MCS_STAT] = {
3522 {"cache", "total_cache"},
3523 {"rss", "total_rss"},
3524 {"mapped_file", "total_mapped_file"},
3525 {"pgpgin", "total_pgpgin"},
3526 {"pgpgout", "total_pgpgout"},
3527 {"swap", "total_swap"},
3528 {"inactive_anon", "total_inactive_anon"},
3529 {"active_anon", "total_active_anon"},
3530 {"inactive_file", "total_inactive_file"},
3531 {"active_file", "total_active_file"},
3532 {"unevictable", "total_unevictable"}
3533 };
3534
3535
3536 static void
3537 mem_cgroup_get_local_stat(struct mem_cgroup *mem, struct mcs_total_stat *s)
3538 {
3539 s64 val;
3540
3541 /* per cpu stat */
3542 val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_CACHE);
3543 s->stat[MCS_CACHE] += val * PAGE_SIZE;
3544 val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_RSS);
3545 s->stat[MCS_RSS] += val * PAGE_SIZE;
3546 val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_FILE_MAPPED);
3547 s->stat[MCS_FILE_MAPPED] += val * PAGE_SIZE;
3548 val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_PGPGIN_COUNT);
3549 s->stat[MCS_PGPGIN] += val;
3550 val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_PGPGOUT_COUNT);
3551 s->stat[MCS_PGPGOUT] += val;
3552 if (do_swap_account) {
3553 val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_SWAPOUT);
3554 s->stat[MCS_SWAP] += val * PAGE_SIZE;
3555 }
3556
3557 /* per zone stat */
3558 val = mem_cgroup_get_local_zonestat(mem, LRU_INACTIVE_ANON);
3559 s->stat[MCS_INACTIVE_ANON] += val * PAGE_SIZE;
3560 val = mem_cgroup_get_local_zonestat(mem, LRU_ACTIVE_ANON);
3561 s->stat[MCS_ACTIVE_ANON] += val * PAGE_SIZE;
3562 val = mem_cgroup_get_local_zonestat(mem, LRU_INACTIVE_FILE);
3563 s->stat[MCS_INACTIVE_FILE] += val * PAGE_SIZE;
3564 val = mem_cgroup_get_local_zonestat(mem, LRU_ACTIVE_FILE);
3565 s->stat[MCS_ACTIVE_FILE] += val * PAGE_SIZE;
3566 val = mem_cgroup_get_local_zonestat(mem, LRU_UNEVICTABLE);
3567 s->stat[MCS_UNEVICTABLE] += val * PAGE_SIZE;
3568 }
3569
3570 static void
3571 mem_cgroup_get_total_stat(struct mem_cgroup *mem, struct mcs_total_stat *s)
3572 {
3573 struct mem_cgroup *iter;
3574
3575 for_each_mem_cgroup_tree(iter, mem)
3576 mem_cgroup_get_local_stat(iter, s);
3577 }
3578
3579 static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft,
3580 struct cgroup_map_cb *cb)
3581 {
3582 struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
3583 struct mcs_total_stat mystat;
3584 int i;
3585
3586 memset(&mystat, 0, sizeof(mystat));
3587 mem_cgroup_get_local_stat(mem_cont, &mystat);
3588
3589 for (i = 0; i < NR_MCS_STAT; i++) {
3590 if (i == MCS_SWAP && !do_swap_account)
3591 continue;
3592 cb->fill(cb, memcg_stat_strings[i].local_name, mystat.stat[i]);
3593 }
3594
3595 /* Hierarchical information */
3596 {
3597 unsigned long long limit, memsw_limit;
3598 memcg_get_hierarchical_limit(mem_cont, &limit, &memsw_limit);
3599 cb->fill(cb, "hierarchical_memory_limit", limit);
3600 if (do_swap_account)
3601 cb->fill(cb, "hierarchical_memsw_limit", memsw_limit);
3602 }
3603
3604 memset(&mystat, 0, sizeof(mystat));
3605 mem_cgroup_get_total_stat(mem_cont, &mystat);
3606 for (i = 0; i < NR_MCS_STAT; i++) {
3607 if (i == MCS_SWAP && !do_swap_account)
3608 continue;
3609 cb->fill(cb, memcg_stat_strings[i].total_name, mystat.stat[i]);
3610 }
3611
3612 #ifdef CONFIG_DEBUG_VM
3613 cb->fill(cb, "inactive_ratio", calc_inactive_ratio(mem_cont, NULL));
3614
3615 {
3616 int nid, zid;
3617 struct mem_cgroup_per_zone *mz;
3618 unsigned long recent_rotated[2] = {0, 0};
3619 unsigned long recent_scanned[2] = {0, 0};
3620
3621 for_each_online_node(nid)
3622 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
3623 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
3624
3625 recent_rotated[0] +=
3626 mz->reclaim_stat.recent_rotated[0];
3627 recent_rotated[1] +=
3628 mz->reclaim_stat.recent_rotated[1];
3629 recent_scanned[0] +=
3630 mz->reclaim_stat.recent_scanned[0];
3631 recent_scanned[1] +=
3632 mz->reclaim_stat.recent_scanned[1];
3633 }
3634 cb->fill(cb, "recent_rotated_anon", recent_rotated[0]);
3635 cb->fill(cb, "recent_rotated_file", recent_rotated[1]);
3636 cb->fill(cb, "recent_scanned_anon", recent_scanned[0]);
3637 cb->fill(cb, "recent_scanned_file", recent_scanned[1]);
3638 }
3639 #endif
3640
3641 return 0;
3642 }
3643
3644 static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
3645 {
3646 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3647
3648 return get_swappiness(memcg);
3649 }
3650
3651 static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
3652 u64 val)
3653 {
3654 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3655 struct mem_cgroup *parent;
3656
3657 if (val > 100)
3658 return -EINVAL;
3659
3660 if (cgrp->parent == NULL)
3661 return -EINVAL;
3662
3663 parent = mem_cgroup_from_cont(cgrp->parent);
3664
3665 cgroup_lock();
3666
3667 /* If under hierarchy, only empty-root can set this value */
3668 if ((parent->use_hierarchy) ||
3669 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
3670 cgroup_unlock();
3671 return -EINVAL;
3672 }
3673
3674 spin_lock(&memcg->reclaim_param_lock);
3675 memcg->swappiness = val;
3676 spin_unlock(&memcg->reclaim_param_lock);
3677
3678 cgroup_unlock();
3679
3680 return 0;
3681 }
3682
3683 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
3684 {
3685 struct mem_cgroup_threshold_ary *t;
3686 u64 usage;
3687 int i;
3688
3689 rcu_read_lock();
3690 if (!swap)
3691 t = rcu_dereference(memcg->thresholds.primary);
3692 else
3693 t = rcu_dereference(memcg->memsw_thresholds.primary);
3694
3695 if (!t)
3696 goto unlock;
3697
3698 usage = mem_cgroup_usage(memcg, swap);
3699
3700 /*
3701 * current_threshold points to threshold just below usage.
3702 * If it's not true, a threshold was crossed after last
3703 * call of __mem_cgroup_threshold().
3704 */
3705 i = t->current_threshold;
3706
3707 /*
3708 * Iterate backward over array of thresholds starting from
3709 * current_threshold and check if a threshold is crossed.
3710 * If none of thresholds below usage is crossed, we read
3711 * only one element of the array here.
3712 */
3713 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
3714 eventfd_signal(t->entries[i].eventfd, 1);
3715
3716 /* i = current_threshold + 1 */
3717 i++;
3718
3719 /*
3720 * Iterate forward over array of thresholds starting from
3721 * current_threshold+1 and check if a threshold is crossed.
3722 * If none of thresholds above usage is crossed, we read
3723 * only one element of the array here.
3724 */
3725 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
3726 eventfd_signal(t->entries[i].eventfd, 1);
3727
3728 /* Update current_threshold */
3729 t->current_threshold = i - 1;
3730 unlock:
3731 rcu_read_unlock();
3732 }
3733
3734 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
3735 {
3736 while (memcg) {
3737 __mem_cgroup_threshold(memcg, false);
3738 if (do_swap_account)
3739 __mem_cgroup_threshold(memcg, true);
3740
3741 memcg = parent_mem_cgroup(memcg);
3742 }
3743 }
3744
3745 static int compare_thresholds(const void *a, const void *b)
3746 {
3747 const struct mem_cgroup_threshold *_a = a;
3748 const struct mem_cgroup_threshold *_b = b;
3749
3750 return _a->threshold - _b->threshold;
3751 }
3752
3753 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *mem)
3754 {
3755 struct mem_cgroup_eventfd_list *ev;
3756
3757 list_for_each_entry(ev, &mem->oom_notify, list)
3758 eventfd_signal(ev->eventfd, 1);
3759 return 0;
3760 }
3761
3762 static void mem_cgroup_oom_notify(struct mem_cgroup *mem)
3763 {
3764 struct mem_cgroup *iter;
3765
3766 for_each_mem_cgroup_tree(iter, mem)
3767 mem_cgroup_oom_notify_cb(iter);
3768 }
3769
3770 static int mem_cgroup_usage_register_event(struct cgroup *cgrp,
3771 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
3772 {
3773 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3774 struct mem_cgroup_thresholds *thresholds;
3775 struct mem_cgroup_threshold_ary *new;
3776 int type = MEMFILE_TYPE(cft->private);
3777 u64 threshold, usage;
3778 int i, size, ret;
3779
3780 ret = res_counter_memparse_write_strategy(args, &threshold);
3781 if (ret)
3782 return ret;
3783
3784 mutex_lock(&memcg->thresholds_lock);
3785
3786 if (type == _MEM)
3787 thresholds = &memcg->thresholds;
3788 else if (type == _MEMSWAP)
3789 thresholds = &memcg->memsw_thresholds;
3790 else
3791 BUG();
3792
3793 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
3794
3795 /* Check if a threshold crossed before adding a new one */
3796 if (thresholds->primary)
3797 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
3798
3799 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
3800
3801 /* Allocate memory for new array of thresholds */
3802 new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
3803 GFP_KERNEL);
3804 if (!new) {
3805 ret = -ENOMEM;
3806 goto unlock;
3807 }
3808 new->size = size;
3809
3810 /* Copy thresholds (if any) to new array */
3811 if (thresholds->primary) {
3812 memcpy(new->entries, thresholds->primary->entries, (size - 1) *
3813 sizeof(struct mem_cgroup_threshold));
3814 }
3815
3816 /* Add new threshold */
3817 new->entries[size - 1].eventfd = eventfd;
3818 new->entries[size - 1].threshold = threshold;
3819
3820 /* Sort thresholds. Registering of new threshold isn't time-critical */
3821 sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
3822 compare_thresholds, NULL);
3823
3824 /* Find current threshold */
3825 new->current_threshold = -1;
3826 for (i = 0; i < size; i++) {
3827 if (new->entries[i].threshold < usage) {
3828 /*
3829 * new->current_threshold will not be used until
3830 * rcu_assign_pointer(), so it's safe to increment
3831 * it here.
3832 */
3833 ++new->current_threshold;
3834 }
3835 }
3836
3837 /* Free old spare buffer and save old primary buffer as spare */
3838 kfree(thresholds->spare);
3839 thresholds->spare = thresholds->primary;
3840
3841 rcu_assign_pointer(thresholds->primary, new);
3842
3843 /* To be sure that nobody uses thresholds */
3844 synchronize_rcu();
3845
3846 unlock:
3847 mutex_unlock(&memcg->thresholds_lock);
3848
3849 return ret;
3850 }
3851
3852 static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,
3853 struct cftype *cft, struct eventfd_ctx *eventfd)
3854 {
3855 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3856 struct mem_cgroup_thresholds *thresholds;
3857 struct mem_cgroup_threshold_ary *new;
3858 int type = MEMFILE_TYPE(cft->private);
3859 u64 usage;
3860 int i, j, size;
3861
3862 mutex_lock(&memcg->thresholds_lock);
3863 if (type == _MEM)
3864 thresholds = &memcg->thresholds;
3865 else if (type == _MEMSWAP)
3866 thresholds = &memcg->memsw_thresholds;
3867 else
3868 BUG();
3869
3870 /*
3871 * Something went wrong if we trying to unregister a threshold
3872 * if we don't have thresholds
3873 */
3874 BUG_ON(!thresholds);
3875
3876 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
3877
3878 /* Check if a threshold crossed before removing */
3879 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
3880
3881 /* Calculate new number of threshold */
3882 size = 0;
3883 for (i = 0; i < thresholds->primary->size; i++) {
3884 if (thresholds->primary->entries[i].eventfd != eventfd)
3885 size++;
3886 }
3887
3888 new = thresholds->spare;
3889
3890 /* Set thresholds array to NULL if we don't have thresholds */
3891 if (!size) {
3892 kfree(new);
3893 new = NULL;
3894 goto swap_buffers;
3895 }
3896
3897 new->size = size;
3898
3899 /* Copy thresholds and find current threshold */
3900 new->current_threshold = -1;
3901 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
3902 if (thresholds->primary->entries[i].eventfd == eventfd)
3903 continue;
3904
3905 new->entries[j] = thresholds->primary->entries[i];
3906 if (new->entries[j].threshold < usage) {
3907 /*
3908 * new->current_threshold will not be used
3909 * until rcu_assign_pointer(), so it's safe to increment
3910 * it here.
3911 */
3912 ++new->current_threshold;
3913 }
3914 j++;
3915 }
3916
3917 swap_buffers:
3918 /* Swap primary and spare array */
3919 thresholds->spare = thresholds->primary;
3920 rcu_assign_pointer(thresholds->primary, new);
3921
3922 /* To be sure that nobody uses thresholds */
3923 synchronize_rcu();
3924
3925 mutex_unlock(&memcg->thresholds_lock);
3926 }
3927
3928 static int mem_cgroup_oom_register_event(struct cgroup *cgrp,
3929 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
3930 {
3931 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3932 struct mem_cgroup_eventfd_list *event;
3933 int type = MEMFILE_TYPE(cft->private);
3934
3935 BUG_ON(type != _OOM_TYPE);
3936 event = kmalloc(sizeof(*event), GFP_KERNEL);
3937 if (!event)
3938 return -ENOMEM;
3939
3940 mutex_lock(&memcg_oom_mutex);
3941
3942 event->eventfd = eventfd;
3943 list_add(&event->list, &memcg->oom_notify);
3944
3945 /* already in OOM ? */
3946 if (atomic_read(&memcg->oom_lock))
3947 eventfd_signal(eventfd, 1);
3948 mutex_unlock(&memcg_oom_mutex);
3949
3950 return 0;
3951 }
3952
3953 static void mem_cgroup_oom_unregister_event(struct cgroup *cgrp,
3954 struct cftype *cft, struct eventfd_ctx *eventfd)
3955 {
3956 struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
3957 struct mem_cgroup_eventfd_list *ev, *tmp;
3958 int type = MEMFILE_TYPE(cft->private);
3959
3960 BUG_ON(type != _OOM_TYPE);
3961
3962 mutex_lock(&memcg_oom_mutex);
3963
3964 list_for_each_entry_safe(ev, tmp, &mem->oom_notify, list) {
3965 if (ev->eventfd == eventfd) {
3966 list_del(&ev->list);
3967 kfree(ev);
3968 }
3969 }
3970
3971 mutex_unlock(&memcg_oom_mutex);
3972 }
3973
3974 static int mem_cgroup_oom_control_read(struct cgroup *cgrp,
3975 struct cftype *cft, struct cgroup_map_cb *cb)
3976 {
3977 struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
3978
3979 cb->fill(cb, "oom_kill_disable", mem->oom_kill_disable);
3980
3981 if (atomic_read(&mem->oom_lock))
3982 cb->fill(cb, "under_oom", 1);
3983 else
3984 cb->fill(cb, "under_oom", 0);
3985 return 0;
3986 }
3987
3988 static int mem_cgroup_oom_control_write(struct cgroup *cgrp,
3989 struct cftype *cft, u64 val)
3990 {
3991 struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
3992 struct mem_cgroup *parent;
3993
3994 /* cannot set to root cgroup and only 0 and 1 are allowed */
3995 if (!cgrp->parent || !((val == 0) || (val == 1)))
3996 return -EINVAL;
3997
3998 parent = mem_cgroup_from_cont(cgrp->parent);
3999
4000 cgroup_lock();
4001 /* oom-kill-disable is a flag for subhierarchy. */
4002 if ((parent->use_hierarchy) ||
4003 (mem->use_hierarchy && !list_empty(&cgrp->children))) {
4004 cgroup_unlock();
4005 return -EINVAL;
4006 }
4007 mem->oom_kill_disable = val;
4008 if (!val)
4009 memcg_oom_recover(mem);
4010 cgroup_unlock();
4011 return 0;
4012 }
4013
4014 static struct cftype mem_cgroup_files[] = {
4015 {
4016 .name = "usage_in_bytes",
4017 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
4018 .read_u64 = mem_cgroup_read,
4019 .register_event = mem_cgroup_usage_register_event,
4020 .unregister_event = mem_cgroup_usage_unregister_event,
4021 },
4022 {
4023 .name = "max_usage_in_bytes",
4024 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
4025 .trigger = mem_cgroup_reset,
4026 .read_u64 = mem_cgroup_read,
4027 },
4028 {
4029 .name = "limit_in_bytes",
4030 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
4031 .write_string = mem_cgroup_write,
4032 .read_u64 = mem_cgroup_read,
4033 },
4034 {
4035 .name = "soft_limit_in_bytes",
4036 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
4037 .write_string = mem_cgroup_write,
4038 .read_u64 = mem_cgroup_read,
4039 },
4040 {
4041 .name = "failcnt",
4042 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
4043 .trigger = mem_cgroup_reset,
4044 .read_u64 = mem_cgroup_read,
4045 },
4046 {
4047 .name = "stat",
4048 .read_map = mem_control_stat_show,
4049 },
4050 {
4051 .name = "force_empty",
4052 .trigger = mem_cgroup_force_empty_write,
4053 },
4054 {
4055 .name = "use_hierarchy",
4056 .write_u64 = mem_cgroup_hierarchy_write,
4057 .read_u64 = mem_cgroup_hierarchy_read,
4058 },
4059 {
4060 .name = "swappiness",
4061 .read_u64 = mem_cgroup_swappiness_read,
4062 .write_u64 = mem_cgroup_swappiness_write,
4063 },
4064 {
4065 .name = "move_charge_at_immigrate",
4066 .read_u64 = mem_cgroup_move_charge_read,
4067 .write_u64 = mem_cgroup_move_charge_write,
4068 },
4069 {
4070 .name = "oom_control",
4071 .read_map = mem_cgroup_oom_control_read,
4072 .write_u64 = mem_cgroup_oom_control_write,
4073 .register_event = mem_cgroup_oom_register_event,
4074 .unregister_event = mem_cgroup_oom_unregister_event,
4075 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
4076 },
4077 };
4078
4079 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4080 static struct cftype memsw_cgroup_files[] = {
4081 {
4082 .name = "memsw.usage_in_bytes",
4083 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
4084 .read_u64 = mem_cgroup_read,
4085 .register_event = mem_cgroup_usage_register_event,
4086 .unregister_event = mem_cgroup_usage_unregister_event,
4087 },
4088 {
4089 .name = "memsw.max_usage_in_bytes",
4090 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
4091 .trigger = mem_cgroup_reset,
4092 .read_u64 = mem_cgroup_read,
4093 },
4094 {
4095 .name = "memsw.limit_in_bytes",
4096 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
4097 .write_string = mem_cgroup_write,
4098 .read_u64 = mem_cgroup_read,
4099 },
4100 {
4101 .name = "memsw.failcnt",
4102 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
4103 .trigger = mem_cgroup_reset,
4104 .read_u64 = mem_cgroup_read,
4105 },
4106 };
4107
4108 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
4109 {
4110 if (!do_swap_account)
4111 return 0;
4112 return cgroup_add_files(cont, ss, memsw_cgroup_files,
4113 ARRAY_SIZE(memsw_cgroup_files));
4114 };
4115 #else
4116 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
4117 {
4118 return 0;
4119 }
4120 #endif
4121
4122 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
4123 {
4124 struct mem_cgroup_per_node *pn;
4125 struct mem_cgroup_per_zone *mz;
4126 enum lru_list l;
4127 int zone, tmp = node;
4128 /*
4129 * This routine is called against possible nodes.
4130 * But it's BUG to call kmalloc() against offline node.
4131 *
4132 * TODO: this routine can waste much memory for nodes which will
4133 * never be onlined. It's better to use memory hotplug callback
4134 * function.
4135 */
4136 if (!node_state(node, N_NORMAL_MEMORY))
4137 tmp = -1;
4138 pn = kmalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
4139 if (!pn)
4140 return 1;
4141
4142 mem->info.nodeinfo[node] = pn;
4143 memset(pn, 0, sizeof(*pn));
4144
4145 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4146 mz = &pn->zoneinfo[zone];
4147 for_each_lru(l)
4148 INIT_LIST_HEAD(&mz->lists[l]);
4149 mz->usage_in_excess = 0;
4150 mz->on_tree = false;
4151 mz->mem = mem;
4152 }
4153 return 0;
4154 }
4155
4156 static void free_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
4157 {
4158 kfree(mem->info.nodeinfo[node]);
4159 }
4160
4161 static struct mem_cgroup *mem_cgroup_alloc(void)
4162 {
4163 struct mem_cgroup *mem;
4164 int size = sizeof(struct mem_cgroup);
4165
4166 /* Can be very big if MAX_NUMNODES is very big */
4167 if (size < PAGE_SIZE)
4168 mem = kmalloc(size, GFP_KERNEL);
4169 else
4170 mem = vmalloc(size);
4171
4172 if (!mem)
4173 return NULL;
4174
4175 memset(mem, 0, size);
4176 mem->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
4177 if (!mem->stat) {
4178 if (size < PAGE_SIZE)
4179 kfree(mem);
4180 else
4181 vfree(mem);
4182 mem = NULL;
4183 }
4184 spin_lock_init(&mem->pcp_counter_lock);
4185 return mem;
4186 }
4187
4188 /*
4189 * At destroying mem_cgroup, references from swap_cgroup can remain.
4190 * (scanning all at force_empty is too costly...)
4191 *
4192 * Instead of clearing all references at force_empty, we remember
4193 * the number of reference from swap_cgroup and free mem_cgroup when
4194 * it goes down to 0.
4195 *
4196 * Removal of cgroup itself succeeds regardless of refs from swap.
4197 */
4198
4199 static void __mem_cgroup_free(struct mem_cgroup *mem)
4200 {
4201 int node;
4202
4203 mem_cgroup_remove_from_trees(mem);
4204 free_css_id(&mem_cgroup_subsys, &mem->css);
4205
4206 for_each_node_state(node, N_POSSIBLE)
4207 free_mem_cgroup_per_zone_info(mem, node);
4208
4209 free_percpu(mem->stat);
4210 if (sizeof(struct mem_cgroup) < PAGE_SIZE)
4211 kfree(mem);
4212 else
4213 vfree(mem);
4214 }
4215
4216 static void mem_cgroup_get(struct mem_cgroup *mem)
4217 {
4218 atomic_inc(&mem->refcnt);
4219 }
4220
4221 static void __mem_cgroup_put(struct mem_cgroup *mem, int count)
4222 {
4223 if (atomic_sub_and_test(count, &mem->refcnt)) {
4224 struct mem_cgroup *parent = parent_mem_cgroup(mem);
4225 __mem_cgroup_free(mem);
4226 if (parent)
4227 mem_cgroup_put(parent);
4228 }
4229 }
4230
4231 static void mem_cgroup_put(struct mem_cgroup *mem)
4232 {
4233 __mem_cgroup_put(mem, 1);
4234 }
4235
4236 /*
4237 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
4238 */
4239 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem)
4240 {
4241 if (!mem->res.parent)
4242 return NULL;
4243 return mem_cgroup_from_res_counter(mem->res.parent, res);
4244 }
4245
4246 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4247 static void __init enable_swap_cgroup(void)
4248 {
4249 if (!mem_cgroup_disabled() && really_do_swap_account)
4250 do_swap_account = 1;
4251 }
4252 #else
4253 static void __init enable_swap_cgroup(void)
4254 {
4255 }
4256 #endif
4257
4258 static int mem_cgroup_soft_limit_tree_init(void)
4259 {
4260 struct mem_cgroup_tree_per_node *rtpn;
4261 struct mem_cgroup_tree_per_zone *rtpz;
4262 int tmp, node, zone;
4263
4264 for_each_node_state(node, N_POSSIBLE) {
4265 tmp = node;
4266 if (!node_state(node, N_NORMAL_MEMORY))
4267 tmp = -1;
4268 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
4269 if (!rtpn)
4270 return 1;
4271
4272 soft_limit_tree.rb_tree_per_node[node] = rtpn;
4273
4274 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4275 rtpz = &rtpn->rb_tree_per_zone[zone];
4276 rtpz->rb_root = RB_ROOT;
4277 spin_lock_init(&rtpz->lock);
4278 }
4279 }
4280 return 0;
4281 }
4282
4283 static struct cgroup_subsys_state * __ref
4284 mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
4285 {
4286 struct mem_cgroup *mem, *parent;
4287 long error = -ENOMEM;
4288 int node;
4289
4290 mem = mem_cgroup_alloc();
4291 if (!mem)
4292 return ERR_PTR(error);
4293
4294 for_each_node_state(node, N_POSSIBLE)
4295 if (alloc_mem_cgroup_per_zone_info(mem, node))
4296 goto free_out;
4297
4298 /* root ? */
4299 if (cont->parent == NULL) {
4300 int cpu;
4301 enable_swap_cgroup();
4302 parent = NULL;
4303 root_mem_cgroup = mem;
4304 if (mem_cgroup_soft_limit_tree_init())
4305 goto free_out;
4306 for_each_possible_cpu(cpu) {
4307 struct memcg_stock_pcp *stock =
4308 &per_cpu(memcg_stock, cpu);
4309 INIT_WORK(&stock->work, drain_local_stock);
4310 }
4311 hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
4312 } else {
4313 parent = mem_cgroup_from_cont(cont->parent);
4314 mem->use_hierarchy = parent->use_hierarchy;
4315 mem->oom_kill_disable = parent->oom_kill_disable;
4316 }
4317
4318 if (parent && parent->use_hierarchy) {
4319 res_counter_init(&mem->res, &parent->res);
4320 res_counter_init(&mem->memsw, &parent->memsw);
4321 /*
4322 * We increment refcnt of the parent to ensure that we can
4323 * safely access it on res_counter_charge/uncharge.
4324 * This refcnt will be decremented when freeing this
4325 * mem_cgroup(see mem_cgroup_put).
4326 */
4327 mem_cgroup_get(parent);
4328 } else {
4329 res_counter_init(&mem->res, NULL);
4330 res_counter_init(&mem->memsw, NULL);
4331 }
4332 mem->last_scanned_child = 0;
4333 spin_lock_init(&mem->reclaim_param_lock);
4334 INIT_LIST_HEAD(&mem->oom_notify);
4335
4336 if (parent)
4337 mem->swappiness = get_swappiness(parent);
4338 atomic_set(&mem->refcnt, 1);
4339 mem->move_charge_at_immigrate = 0;
4340 mutex_init(&mem->thresholds_lock);
4341 return &mem->css;
4342 free_out:
4343 __mem_cgroup_free(mem);
4344 root_mem_cgroup = NULL;
4345 return ERR_PTR(error);
4346 }
4347
4348 static int mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
4349 struct cgroup *cont)
4350 {
4351 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
4352
4353 return mem_cgroup_force_empty(mem, false);
4354 }
4355
4356 static void mem_cgroup_destroy(struct cgroup_subsys *ss,
4357 struct cgroup *cont)
4358 {
4359 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
4360
4361 mem_cgroup_put(mem);
4362 }
4363
4364 static int mem_cgroup_populate(struct cgroup_subsys *ss,
4365 struct cgroup *cont)
4366 {
4367 int ret;
4368
4369 ret = cgroup_add_files(cont, ss, mem_cgroup_files,
4370 ARRAY_SIZE(mem_cgroup_files));
4371
4372 if (!ret)
4373 ret = register_memsw_files(cont, ss);
4374 return ret;
4375 }
4376
4377 #ifdef CONFIG_MMU
4378 /* Handlers for move charge at task migration. */
4379 #define PRECHARGE_COUNT_AT_ONCE 256
4380 static int mem_cgroup_do_precharge(unsigned long count)
4381 {
4382 int ret = 0;
4383 int batch_count = PRECHARGE_COUNT_AT_ONCE;
4384 struct mem_cgroup *mem = mc.to;
4385
4386 if (mem_cgroup_is_root(mem)) {
4387 mc.precharge += count;
4388 /* we don't need css_get for root */
4389 return ret;
4390 }
4391 /* try to charge at once */
4392 if (count > 1) {
4393 struct res_counter *dummy;
4394 /*
4395 * "mem" cannot be under rmdir() because we've already checked
4396 * by cgroup_lock_live_cgroup() that it is not removed and we
4397 * are still under the same cgroup_mutex. So we can postpone
4398 * css_get().
4399 */
4400 if (res_counter_charge(&mem->res, PAGE_SIZE * count, &dummy))
4401 goto one_by_one;
4402 if (do_swap_account && res_counter_charge(&mem->memsw,
4403 PAGE_SIZE * count, &dummy)) {
4404 res_counter_uncharge(&mem->res, PAGE_SIZE * count);
4405 goto one_by_one;
4406 }
4407 mc.precharge += count;
4408 return ret;
4409 }
4410 one_by_one:
4411 /* fall back to one by one charge */
4412 while (count--) {
4413 if (signal_pending(current)) {
4414 ret = -EINTR;
4415 break;
4416 }
4417 if (!batch_count--) {
4418 batch_count = PRECHARGE_COUNT_AT_ONCE;
4419 cond_resched();
4420 }
4421 ret = __mem_cgroup_try_charge(NULL, GFP_KERNEL, &mem, false);
4422 if (ret || !mem)
4423 /* mem_cgroup_clear_mc() will do uncharge later */
4424 return -ENOMEM;
4425 mc.precharge++;
4426 }
4427 return ret;
4428 }
4429
4430 /**
4431 * is_target_pte_for_mc - check a pte whether it is valid for move charge
4432 * @vma: the vma the pte to be checked belongs
4433 * @addr: the address corresponding to the pte to be checked
4434 * @ptent: the pte to be checked
4435 * @target: the pointer the target page or swap ent will be stored(can be NULL)
4436 *
4437 * Returns
4438 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
4439 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
4440 * move charge. if @target is not NULL, the page is stored in target->page
4441 * with extra refcnt got(Callers should handle it).
4442 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
4443 * target for charge migration. if @target is not NULL, the entry is stored
4444 * in target->ent.
4445 *
4446 * Called with pte lock held.
4447 */
4448 union mc_target {
4449 struct page *page;
4450 swp_entry_t ent;
4451 };
4452
4453 enum mc_target_type {
4454 MC_TARGET_NONE, /* not used */
4455 MC_TARGET_PAGE,
4456 MC_TARGET_SWAP,
4457 };
4458
4459 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
4460 unsigned long addr, pte_t ptent)
4461 {
4462 struct page *page = vm_normal_page(vma, addr, ptent);
4463
4464 if (!page || !page_mapped(page))
4465 return NULL;
4466 if (PageAnon(page)) {
4467 /* we don't move shared anon */
4468 if (!move_anon() || page_mapcount(page) > 2)
4469 return NULL;
4470 } else if (!move_file())
4471 /* we ignore mapcount for file pages */
4472 return NULL;
4473 if (!get_page_unless_zero(page))
4474 return NULL;
4475
4476 return page;
4477 }
4478
4479 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
4480 unsigned long addr, pte_t ptent, swp_entry_t *entry)
4481 {
4482 int usage_count;
4483 struct page *page = NULL;
4484 swp_entry_t ent = pte_to_swp_entry(ptent);
4485
4486 if (!move_anon() || non_swap_entry(ent))
4487 return NULL;
4488 usage_count = mem_cgroup_count_swap_user(ent, &page);
4489 if (usage_count > 1) { /* we don't move shared anon */
4490 if (page)
4491 put_page(page);
4492 return NULL;
4493 }
4494 if (do_swap_account)
4495 entry->val = ent.val;
4496
4497 return page;
4498 }
4499
4500 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
4501 unsigned long addr, pte_t ptent, swp_entry_t *entry)
4502 {
4503 struct page *page = NULL;
4504 struct inode *inode;
4505 struct address_space *mapping;
4506 pgoff_t pgoff;
4507
4508 if (!vma->vm_file) /* anonymous vma */
4509 return NULL;
4510 if (!move_file())
4511 return NULL;
4512
4513 inode = vma->vm_file->f_path.dentry->d_inode;
4514 mapping = vma->vm_file->f_mapping;
4515 if (pte_none(ptent))
4516 pgoff = linear_page_index(vma, addr);
4517 else /* pte_file(ptent) is true */
4518 pgoff = pte_to_pgoff(ptent);
4519
4520 /* page is moved even if it's not RSS of this task(page-faulted). */
4521 if (!mapping_cap_swap_backed(mapping)) { /* normal file */
4522 page = find_get_page(mapping, pgoff);
4523 } else { /* shmem/tmpfs file. we should take account of swap too. */
4524 swp_entry_t ent;
4525 mem_cgroup_get_shmem_target(inode, pgoff, &page, &ent);
4526 if (do_swap_account)
4527 entry->val = ent.val;
4528 }
4529
4530 return page;
4531 }
4532
4533 static int is_target_pte_for_mc(struct vm_area_struct *vma,
4534 unsigned long addr, pte_t ptent, union mc_target *target)
4535 {
4536 struct page *page = NULL;
4537 struct page_cgroup *pc;
4538 int ret = 0;
4539 swp_entry_t ent = { .val = 0 };
4540
4541 if (pte_present(ptent))
4542 page = mc_handle_present_pte(vma, addr, ptent);
4543 else if (is_swap_pte(ptent))
4544 page = mc_handle_swap_pte(vma, addr, ptent, &ent);
4545 else if (pte_none(ptent) || pte_file(ptent))
4546 page = mc_handle_file_pte(vma, addr, ptent, &ent);
4547
4548 if (!page && !ent.val)
4549 return 0;
4550 if (page) {
4551 pc = lookup_page_cgroup(page);
4552 /*
4553 * Do only loose check w/o page_cgroup lock.
4554 * mem_cgroup_move_account() checks the pc is valid or not under
4555 * the lock.
4556 */
4557 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
4558 ret = MC_TARGET_PAGE;
4559 if (target)
4560 target->page = page;
4561 }
4562 if (!ret || !target)
4563 put_page(page);
4564 }
4565 /* There is a swap entry and a page doesn't exist or isn't charged */
4566 if (ent.val && !ret &&
4567 css_id(&mc.from->css) == lookup_swap_cgroup(ent)) {
4568 ret = MC_TARGET_SWAP;
4569 if (target)
4570 target->ent = ent;
4571 }
4572 return ret;
4573 }
4574
4575 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
4576 unsigned long addr, unsigned long end,
4577 struct mm_walk *walk)
4578 {
4579 struct vm_area_struct *vma = walk->private;
4580 pte_t *pte;
4581 spinlock_t *ptl;
4582
4583 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
4584 for (; addr != end; pte++, addr += PAGE_SIZE)
4585 if (is_target_pte_for_mc(vma, addr, *pte, NULL))
4586 mc.precharge++; /* increment precharge temporarily */
4587 pte_unmap_unlock(pte - 1, ptl);
4588 cond_resched();
4589
4590 return 0;
4591 }
4592
4593 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
4594 {
4595 unsigned long precharge;
4596 struct vm_area_struct *vma;
4597
4598 down_read(&mm->mmap_sem);
4599 for (vma = mm->mmap; vma; vma = vma->vm_next) {
4600 struct mm_walk mem_cgroup_count_precharge_walk = {
4601 .pmd_entry = mem_cgroup_count_precharge_pte_range,
4602 .mm = mm,
4603 .private = vma,
4604 };
4605 if (is_vm_hugetlb_page(vma))
4606 continue;
4607 walk_page_range(vma->vm_start, vma->vm_end,
4608 &mem_cgroup_count_precharge_walk);
4609 }
4610 up_read(&mm->mmap_sem);
4611
4612 precharge = mc.precharge;
4613 mc.precharge = 0;
4614
4615 return precharge;
4616 }
4617
4618 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
4619 {
4620 return mem_cgroup_do_precharge(mem_cgroup_count_precharge(mm));
4621 }
4622
4623 static void mem_cgroup_clear_mc(void)
4624 {
4625 struct mem_cgroup *from = mc.from;
4626 struct mem_cgroup *to = mc.to;
4627
4628 /* we must uncharge all the leftover precharges from mc.to */
4629 if (mc.precharge) {
4630 __mem_cgroup_cancel_charge(mc.to, mc.precharge);
4631 mc.precharge = 0;
4632 }
4633 /*
4634 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
4635 * we must uncharge here.
4636 */
4637 if (mc.moved_charge) {
4638 __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
4639 mc.moved_charge = 0;
4640 }
4641 /* we must fixup refcnts and charges */
4642 if (mc.moved_swap) {
4643 /* uncharge swap account from the old cgroup */
4644 if (!mem_cgroup_is_root(mc.from))
4645 res_counter_uncharge(&mc.from->memsw,
4646 PAGE_SIZE * mc.moved_swap);
4647 __mem_cgroup_put(mc.from, mc.moved_swap);
4648
4649 if (!mem_cgroup_is_root(mc.to)) {
4650 /*
4651 * we charged both to->res and to->memsw, so we should
4652 * uncharge to->res.
4653 */
4654 res_counter_uncharge(&mc.to->res,
4655 PAGE_SIZE * mc.moved_swap);
4656 }
4657 /* we've already done mem_cgroup_get(mc.to) */
4658
4659 mc.moved_swap = 0;
4660 }
4661 spin_lock(&mc.lock);
4662 mc.from = NULL;
4663 mc.to = NULL;
4664 mc.moving_task = NULL;
4665 spin_unlock(&mc.lock);
4666 mem_cgroup_end_move(from);
4667 memcg_oom_recover(from);
4668 memcg_oom_recover(to);
4669 wake_up_all(&mc.waitq);
4670 }
4671
4672 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
4673 struct cgroup *cgroup,
4674 struct task_struct *p,
4675 bool threadgroup)
4676 {
4677 int ret = 0;
4678 struct mem_cgroup *mem = mem_cgroup_from_cont(cgroup);
4679
4680 if (mem->move_charge_at_immigrate) {
4681 struct mm_struct *mm;
4682 struct mem_cgroup *from = mem_cgroup_from_task(p);
4683
4684 VM_BUG_ON(from == mem);
4685
4686 mm = get_task_mm(p);
4687 if (!mm)
4688 return 0;
4689 /* We move charges only when we move a owner of the mm */
4690 if (mm->owner == p) {
4691 VM_BUG_ON(mc.from);
4692 VM_BUG_ON(mc.to);
4693 VM_BUG_ON(mc.precharge);
4694 VM_BUG_ON(mc.moved_charge);
4695 VM_BUG_ON(mc.moved_swap);
4696 VM_BUG_ON(mc.moving_task);
4697 mem_cgroup_start_move(from);
4698 spin_lock(&mc.lock);
4699 mc.from = from;
4700 mc.to = mem;
4701 mc.precharge = 0;
4702 mc.moved_charge = 0;
4703 mc.moved_swap = 0;
4704 mc.moving_task = current;
4705 spin_unlock(&mc.lock);
4706
4707 ret = mem_cgroup_precharge_mc(mm);
4708 if (ret)
4709 mem_cgroup_clear_mc();
4710 }
4711 mmput(mm);
4712 }
4713 return ret;
4714 }
4715
4716 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
4717 struct cgroup *cgroup,
4718 struct task_struct *p,
4719 bool threadgroup)
4720 {
4721 mem_cgroup_clear_mc();
4722 }
4723
4724 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
4725 unsigned long addr, unsigned long end,
4726 struct mm_walk *walk)
4727 {
4728 int ret = 0;
4729 struct vm_area_struct *vma = walk->private;
4730 pte_t *pte;
4731 spinlock_t *ptl;
4732
4733 retry:
4734 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
4735 for (; addr != end; addr += PAGE_SIZE) {
4736 pte_t ptent = *(pte++);
4737 union mc_target target;
4738 int type;
4739 struct page *page;
4740 struct page_cgroup *pc;
4741 swp_entry_t ent;
4742
4743 if (!mc.precharge)
4744 break;
4745
4746 type = is_target_pte_for_mc(vma, addr, ptent, &target);
4747 switch (type) {
4748 case MC_TARGET_PAGE:
4749 page = target.page;
4750 if (isolate_lru_page(page))
4751 goto put;
4752 pc = lookup_page_cgroup(page);
4753 if (!mem_cgroup_move_account(pc,
4754 mc.from, mc.to, false)) {
4755 mc.precharge--;
4756 /* we uncharge from mc.from later. */
4757 mc.moved_charge++;
4758 }
4759 putback_lru_page(page);
4760 put: /* is_target_pte_for_mc() gets the page */
4761 put_page(page);
4762 break;
4763 case MC_TARGET_SWAP:
4764 ent = target.ent;
4765 if (!mem_cgroup_move_swap_account(ent,
4766 mc.from, mc.to, false)) {
4767 mc.precharge--;
4768 /* we fixup refcnts and charges later. */
4769 mc.moved_swap++;
4770 }
4771 break;
4772 default:
4773 break;
4774 }
4775 }
4776 pte_unmap_unlock(pte - 1, ptl);
4777 cond_resched();
4778
4779 if (addr != end) {
4780 /*
4781 * We have consumed all precharges we got in can_attach().
4782 * We try charge one by one, but don't do any additional
4783 * charges to mc.to if we have failed in charge once in attach()
4784 * phase.
4785 */
4786 ret = mem_cgroup_do_precharge(1);
4787 if (!ret)
4788 goto retry;
4789 }
4790
4791 return ret;
4792 }
4793
4794 static void mem_cgroup_move_charge(struct mm_struct *mm)
4795 {
4796 struct vm_area_struct *vma;
4797
4798 lru_add_drain_all();
4799 down_read(&mm->mmap_sem);
4800 for (vma = mm->mmap; vma; vma = vma->vm_next) {
4801 int ret;
4802 struct mm_walk mem_cgroup_move_charge_walk = {
4803 .pmd_entry = mem_cgroup_move_charge_pte_range,
4804 .mm = mm,
4805 .private = vma,
4806 };
4807 if (is_vm_hugetlb_page(vma))
4808 continue;
4809 ret = walk_page_range(vma->vm_start, vma->vm_end,
4810 &mem_cgroup_move_charge_walk);
4811 if (ret)
4812 /*
4813 * means we have consumed all precharges and failed in
4814 * doing additional charge. Just abandon here.
4815 */
4816 break;
4817 }
4818 up_read(&mm->mmap_sem);
4819 }
4820
4821 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
4822 struct cgroup *cont,
4823 struct cgroup *old_cont,
4824 struct task_struct *p,
4825 bool threadgroup)
4826 {
4827 struct mm_struct *mm;
4828
4829 if (!mc.to)
4830 /* no need to move charge */
4831 return;
4832
4833 mm = get_task_mm(p);
4834 if (mm) {
4835 mem_cgroup_move_charge(mm);
4836 mmput(mm);
4837 }
4838 mem_cgroup_clear_mc();
4839 }
4840 #else /* !CONFIG_MMU */
4841 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
4842 struct cgroup *cgroup,
4843 struct task_struct *p,
4844 bool threadgroup)
4845 {
4846 return 0;
4847 }
4848 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
4849 struct cgroup *cgroup,
4850 struct task_struct *p,
4851 bool threadgroup)
4852 {
4853 }
4854 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
4855 struct cgroup *cont,
4856 struct cgroup *old_cont,
4857 struct task_struct *p,
4858 bool threadgroup)
4859 {
4860 }
4861 #endif
4862
4863 struct cgroup_subsys mem_cgroup_subsys = {
4864 .name = "memory",
4865 .subsys_id = mem_cgroup_subsys_id,
4866 .create = mem_cgroup_create,
4867 .pre_destroy = mem_cgroup_pre_destroy,
4868 .destroy = mem_cgroup_destroy,
4869 .populate = mem_cgroup_populate,
4870 .can_attach = mem_cgroup_can_attach,
4871 .cancel_attach = mem_cgroup_cancel_attach,
4872 .attach = mem_cgroup_move_task,
4873 .early_init = 0,
4874 .use_id = 1,
4875 };
4876
4877 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4878
4879 static int __init disable_swap_account(char *s)
4880 {
4881 really_do_swap_account = 0;
4882 return 1;
4883 }
4884 __setup("noswapaccount", disable_swap_account);
4885 #endif
This page took 0.124479 seconds and 6 git commands to generate.