linux/mm/memcontrol.c
<<
>>
Prefs
   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 * This program is free software; you can redistribute it and/or modify
  10 * it under the terms of the GNU General Public License as published by
  11 * the Free Software Foundation; either version 2 of the License, or
  12 * (at your option) any later version.
  13 *
  14 * This program is distributed in the hope that it will be useful,
  15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  17 * GNU General Public License for more details.
  18 */
  19
  20#include <linux/res_counter.h>
  21#include <linux/memcontrol.h>
  22#include <linux/cgroup.h>
  23#include <linux/mm.h>
  24#include <linux/smp.h>
  25#include <linux/page-flags.h>
  26#include <linux/backing-dev.h>
  27#include <linux/bit_spinlock.h>
  28#include <linux/rcupdate.h>
  29#include <linux/slab.h>
  30#include <linux/swap.h>
  31#include <linux/spinlock.h>
  32#include <linux/fs.h>
  33#include <linux/seq_file.h>
  34#include <linux/vmalloc.h>
  35
  36#include <asm/uaccess.h>
  37
  38struct cgroup_subsys mem_cgroup_subsys;
  39static const int MEM_CGROUP_RECLAIM_RETRIES = 5;
  40static struct kmem_cache *page_cgroup_cache;
  41
  42/*
  43 * Statistics for memory cgroup.
  44 */
  45enum mem_cgroup_stat_index {
  46        /*
  47         * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
  48         */
  49        MEM_CGROUP_STAT_CACHE,     /* # of pages charged as cache */
  50        MEM_CGROUP_STAT_RSS,       /* # of pages charged as rss */
  51        MEM_CGROUP_STAT_PGPGIN_COUNT,   /* # of pages paged in */
  52        MEM_CGROUP_STAT_PGPGOUT_COUNT,  /* # of pages paged out */
  53
  54        MEM_CGROUP_STAT_NSTATS,
  55};
  56
  57struct mem_cgroup_stat_cpu {
  58        s64 count[MEM_CGROUP_STAT_NSTATS];
  59} ____cacheline_aligned_in_smp;
  60
  61struct mem_cgroup_stat {
  62        struct mem_cgroup_stat_cpu cpustat[NR_CPUS];
  63};
  64
  65/*
  66 * For accounting under irq disable, no need for increment preempt count.
  67 */
  68static void __mem_cgroup_stat_add_safe(struct mem_cgroup_stat *stat,
  69                enum mem_cgroup_stat_index idx, int val)
  70{
  71        int cpu = smp_processor_id();
  72        stat->cpustat[cpu].count[idx] += val;
  73}
  74
  75static s64 mem_cgroup_read_stat(struct mem_cgroup_stat *stat,
  76                enum mem_cgroup_stat_index idx)
  77{
  78        int cpu;
  79        s64 ret = 0;
  80        for_each_possible_cpu(cpu)
  81                ret += stat->cpustat[cpu].count[idx];
  82        return ret;
  83}
  84
  85/*
  86 * per-zone information in memory controller.
  87 */
  88
  89enum mem_cgroup_zstat_index {
  90        MEM_CGROUP_ZSTAT_ACTIVE,
  91        MEM_CGROUP_ZSTAT_INACTIVE,
  92
  93        NR_MEM_CGROUP_ZSTAT,
  94};
  95
  96struct mem_cgroup_per_zone {
  97        /*
  98         * spin_lock to protect the per cgroup LRU
  99         */
 100        spinlock_t              lru_lock;
 101        struct list_head        active_list;
 102        struct list_head        inactive_list;
 103        unsigned long count[NR_MEM_CGROUP_ZSTAT];
 104};
 105/* Macro for accessing counter */
 106#define MEM_CGROUP_ZSTAT(mz, idx)       ((mz)->count[(idx)])
 107
 108struct mem_cgroup_per_node {
 109        struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
 110};
 111
 112struct mem_cgroup_lru_info {
 113        struct mem_cgroup_per_node *nodeinfo[MAX_NUMNODES];
 114};
 115
 116/*
 117 * The memory controller data structure. The memory controller controls both
 118 * page cache and RSS per cgroup. We would eventually like to provide
 119 * statistics based on the statistics developed by Rik Van Riel for clock-pro,
 120 * to help the administrator determine what knobs to tune.
 121 *
 122 * TODO: Add a water mark for the memory controller. Reclaim will begin when
 123 * we hit the water mark. May be even add a low water mark, such that
 124 * no reclaim occurs from a cgroup at it's low water mark, this is
 125 * a feature that will be implemented much later in the future.
 126 */
 127struct mem_cgroup {
 128        struct cgroup_subsys_state css;
 129        /*
 130         * the counter to account for memory usage
 131         */
 132        struct res_counter res;
 133        /*
 134         * Per cgroup active and inactive list, similar to the
 135         * per zone LRU lists.
 136         */
 137        struct mem_cgroup_lru_info info;
 138
 139        int     prev_priority;  /* for recording reclaim priority */
 140        /*
 141         * statistics.
 142         */
 143        struct mem_cgroup_stat stat;
 144};
 145static struct mem_cgroup init_mem_cgroup;
 146
 147/*
 148 * We use the lower bit of the page->page_cgroup pointer as a bit spin
 149 * lock.  We need to ensure that page->page_cgroup is at least two
 150 * byte aligned (based on comments from Nick Piggin).  But since
 151 * bit_spin_lock doesn't actually set that lock bit in a non-debug
 152 * uniprocessor kernel, we should avoid setting it here too.
 153 */
 154#define PAGE_CGROUP_LOCK_BIT    0x0
 155#if defined(CONFIG_SMP) || defined(CONFIG_DEBUG_SPINLOCK)
 156#define PAGE_CGROUP_LOCK        (1 << PAGE_CGROUP_LOCK_BIT)
 157#else
 158#define PAGE_CGROUP_LOCK        0x0
 159#endif
 160
 161/*
 162 * A page_cgroup page is associated with every page descriptor. The
 163 * page_cgroup helps us identify information about the cgroup
 164 */
 165struct page_cgroup {
 166        struct list_head lru;           /* per cgroup LRU list */
 167        struct page *page;
 168        struct mem_cgroup *mem_cgroup;
 169        int ref_cnt;                    /* cached, mapped, migrating */
 170        int flags;
 171};
 172#define PAGE_CGROUP_FLAG_CACHE  (0x1)   /* charged as cache */
 173#define PAGE_CGROUP_FLAG_ACTIVE (0x2)   /* page is active in this cgroup */
 174
 175static int page_cgroup_nid(struct page_cgroup *pc)
 176{
 177        return page_to_nid(pc->page);
 178}
 179
 180static enum zone_type page_cgroup_zid(struct page_cgroup *pc)
 181{
 182        return page_zonenum(pc->page);
 183}
 184
 185enum charge_type {
 186        MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
 187        MEM_CGROUP_CHARGE_TYPE_MAPPED,
 188};
 189
 190/*
 191 * Always modified under lru lock. Then, not necessary to preempt_disable()
 192 */
 193static void mem_cgroup_charge_statistics(struct mem_cgroup *mem, int flags,
 194                                        bool charge)
 195{
 196        int val = (charge)? 1 : -1;
 197        struct mem_cgroup_stat *stat = &mem->stat;
 198
 199        VM_BUG_ON(!irqs_disabled());
 200        if (flags & PAGE_CGROUP_FLAG_CACHE)
 201                __mem_cgroup_stat_add_safe(stat, MEM_CGROUP_STAT_CACHE, val);
 202        else
 203                __mem_cgroup_stat_add_safe(stat, MEM_CGROUP_STAT_RSS, val);
 204
 205        if (charge)
 206                __mem_cgroup_stat_add_safe(stat,
 207                                MEM_CGROUP_STAT_PGPGIN_COUNT, 1);
 208        else
 209                __mem_cgroup_stat_add_safe(stat,
 210                                MEM_CGROUP_STAT_PGPGOUT_COUNT, 1);
 211}
 212
 213static struct mem_cgroup_per_zone *
 214mem_cgroup_zoneinfo(struct mem_cgroup *mem, int nid, int zid)
 215{
 216        return &mem->info.nodeinfo[nid]->zoneinfo[zid];
 217}
 218
 219static struct mem_cgroup_per_zone *
 220page_cgroup_zoneinfo(struct page_cgroup *pc)
 221{
 222        struct mem_cgroup *mem = pc->mem_cgroup;
 223        int nid = page_cgroup_nid(pc);
 224        int zid = page_cgroup_zid(pc);
 225
 226        return mem_cgroup_zoneinfo(mem, nid, zid);
 227}
 228
 229static unsigned long mem_cgroup_get_all_zonestat(struct mem_cgroup *mem,
 230                                        enum mem_cgroup_zstat_index idx)
 231{
 232        int nid, zid;
 233        struct mem_cgroup_per_zone *mz;
 234        u64 total = 0;
 235
 236        for_each_online_node(nid)
 237                for (zid = 0; zid < MAX_NR_ZONES; zid++) {
 238                        mz = mem_cgroup_zoneinfo(mem, nid, zid);
 239                        total += MEM_CGROUP_ZSTAT(mz, idx);
 240                }
 241        return total;
 242}
 243
 244static struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
 245{
 246        return container_of(cgroup_subsys_state(cont,
 247                                mem_cgroup_subsys_id), struct mem_cgroup,
 248                                css);
 249}
 250
 251struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
 252{
 253        /*
 254         * mm_update_next_owner() may clear mm->owner to NULL
 255         * if it races with swapoff, page migration, etc.
 256         * So this can be called with p == NULL.
 257         */
 258        if (unlikely(!p))
 259                return NULL;
 260
 261        return container_of(task_subsys_state(p, mem_cgroup_subsys_id),
 262                                struct mem_cgroup, css);
 263}
 264
 265static inline int page_cgroup_locked(struct page *page)
 266{
 267        return bit_spin_is_locked(PAGE_CGROUP_LOCK_BIT, &page->page_cgroup);
 268}
 269
 270static void page_assign_page_cgroup(struct page *page, struct page_cgroup *pc)
 271{
 272        VM_BUG_ON(!page_cgroup_locked(page));
 273        page->page_cgroup = ((unsigned long)pc | PAGE_CGROUP_LOCK);
 274}
 275
 276struct page_cgroup *page_get_page_cgroup(struct page *page)
 277{
 278        return (struct page_cgroup *) (page->page_cgroup & ~PAGE_CGROUP_LOCK);
 279}
 280
 281static void lock_page_cgroup(struct page *page)
 282{
 283        bit_spin_lock(PAGE_CGROUP_LOCK_BIT, &page->page_cgroup);
 284}
 285
 286static int try_lock_page_cgroup(struct page *page)
 287{
 288        return bit_spin_trylock(PAGE_CGROUP_LOCK_BIT, &page->page_cgroup);
 289}
 290
 291static void unlock_page_cgroup(struct page *page)
 292{
 293        bit_spin_unlock(PAGE_CGROUP_LOCK_BIT, &page->page_cgroup);
 294}
 295
 296static void __mem_cgroup_remove_list(struct mem_cgroup_per_zone *mz,
 297                        struct page_cgroup *pc)
 298{
 299        int from = pc->flags & PAGE_CGROUP_FLAG_ACTIVE;
 300
 301        if (from)
 302                MEM_CGROUP_ZSTAT(mz, MEM_CGROUP_ZSTAT_ACTIVE) -= 1;
 303        else
 304                MEM_CGROUP_ZSTAT(mz, MEM_CGROUP_ZSTAT_INACTIVE) -= 1;
 305
 306        mem_cgroup_charge_statistics(pc->mem_cgroup, pc->flags, false);
 307        list_del_init(&pc->lru);
 308}
 309
 310static void __mem_cgroup_add_list(struct mem_cgroup_per_zone *mz,
 311                                struct page_cgroup *pc)
 312{
 313        int to = pc->flags & PAGE_CGROUP_FLAG_ACTIVE;
 314
 315        if (!to) {
 316                MEM_CGROUP_ZSTAT(mz, MEM_CGROUP_ZSTAT_INACTIVE) += 1;
 317                list_add(&pc->lru, &mz->inactive_list);
 318        } else {
 319                MEM_CGROUP_ZSTAT(mz, MEM_CGROUP_ZSTAT_ACTIVE) += 1;
 320                list_add(&pc->lru, &mz->active_list);
 321        }
 322        mem_cgroup_charge_statistics(pc->mem_cgroup, pc->flags, true);
 323}
 324
 325static void __mem_cgroup_move_lists(struct page_cgroup *pc, bool active)
 326{
 327        int from = pc->flags & PAGE_CGROUP_FLAG_ACTIVE;
 328        struct mem_cgroup_per_zone *mz = page_cgroup_zoneinfo(pc);
 329
 330        if (from)
 331                MEM_CGROUP_ZSTAT(mz, MEM_CGROUP_ZSTAT_ACTIVE) -= 1;
 332        else
 333                MEM_CGROUP_ZSTAT(mz, MEM_CGROUP_ZSTAT_INACTIVE) -= 1;
 334
 335        if (active) {
 336                MEM_CGROUP_ZSTAT(mz, MEM_CGROUP_ZSTAT_ACTIVE) += 1;
 337                pc->flags |= PAGE_CGROUP_FLAG_ACTIVE;
 338                list_move(&pc->lru, &mz->active_list);
 339        } else {
 340                MEM_CGROUP_ZSTAT(mz, MEM_CGROUP_ZSTAT_INACTIVE) += 1;
 341                pc->flags &= ~PAGE_CGROUP_FLAG_ACTIVE;
 342                list_move(&pc->lru, &mz->inactive_list);
 343        }
 344}
 345
 346int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *mem)
 347{
 348        int ret;
 349
 350        task_lock(task);
 351        ret = task->mm && mm_match_cgroup(task->mm, mem);
 352        task_unlock(task);
 353        return ret;
 354}
 355
 356/*
 357 * This routine assumes that the appropriate zone's lru lock is already held
 358 */
 359void mem_cgroup_move_lists(struct page *page, bool active)
 360{
 361        struct page_cgroup *pc;
 362        struct mem_cgroup_per_zone *mz;
 363        unsigned long flags;
 364
 365        /*
 366         * We cannot lock_page_cgroup while holding zone's lru_lock,
 367         * because other holders of lock_page_cgroup can be interrupted
 368         * with an attempt to rotate_reclaimable_page.  But we cannot
 369         * safely get to page_cgroup without it, so just try_lock it:
 370         * mem_cgroup_isolate_pages allows for page left on wrong list.
 371         */
 372        if (!try_lock_page_cgroup(page))
 373                return;
 374
 375        pc = page_get_page_cgroup(page);
 376        if (pc) {
 377                mz = page_cgroup_zoneinfo(pc);
 378                spin_lock_irqsave(&mz->lru_lock, flags);
 379                __mem_cgroup_move_lists(pc, active);
 380                spin_unlock_irqrestore(&mz->lru_lock, flags);
 381        }
 382        unlock_page_cgroup(page);
 383}
 384
 385/*
 386 * Calculate mapped_ratio under memory controller. This will be used in
 387 * vmscan.c for deteremining we have to reclaim mapped pages.
 388 */
 389int mem_cgroup_calc_mapped_ratio(struct mem_cgroup *mem)
 390{
 391        long total, rss;
 392
 393        /*
 394         * usage is recorded in bytes. But, here, we assume the number of
 395         * physical pages can be represented by "long" on any arch.
 396         */
 397        total = (long) (mem->res.usage >> PAGE_SHIFT) + 1L;
 398        rss = (long)mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_RSS);
 399        return (int)((rss * 100L) / total);
 400}
 401
 402/*
 403 * This function is called from vmscan.c. In page reclaiming loop. balance
 404 * between active and inactive list is calculated. For memory controller
 405 * page reclaiming, we should use using mem_cgroup's imbalance rather than
 406 * zone's global lru imbalance.
 407 */
 408long mem_cgroup_reclaim_imbalance(struct mem_cgroup *mem)
 409{
 410        unsigned long active, inactive;
 411        /* active and inactive are the number of pages. 'long' is ok.*/
 412        active = mem_cgroup_get_all_zonestat(mem, MEM_CGROUP_ZSTAT_ACTIVE);
 413        inactive = mem_cgroup_get_all_zonestat(mem, MEM_CGROUP_ZSTAT_INACTIVE);
 414        return (long) (active / (inactive + 1));
 415}
 416
 417/*
 418 * prev_priority control...this will be used in memory reclaim path.
 419 */
 420int mem_cgroup_get_reclaim_priority(struct mem_cgroup *mem)
 421{
 422        return mem->prev_priority;
 423}
 424
 425void mem_cgroup_note_reclaim_priority(struct mem_cgroup *mem, int priority)
 426{
 427        if (priority < mem->prev_priority)
 428                mem->prev_priority = priority;
 429}
 430
 431void mem_cgroup_record_reclaim_priority(struct mem_cgroup *mem, int priority)
 432{
 433        mem->prev_priority = priority;
 434}
 435
 436/*
 437 * Calculate # of pages to be scanned in this priority/zone.
 438 * See also vmscan.c
 439 *
 440 * priority starts from "DEF_PRIORITY" and decremented in each loop.
 441 * (see include/linux/mmzone.h)
 442 */
 443
 444long mem_cgroup_calc_reclaim_active(struct mem_cgroup *mem,
 445                                   struct zone *zone, int priority)
 446{
 447        long nr_active;
 448        int nid = zone->zone_pgdat->node_id;
 449        int zid = zone_idx(zone);
 450        struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(mem, nid, zid);
 451
 452        nr_active = MEM_CGROUP_ZSTAT(mz, MEM_CGROUP_ZSTAT_ACTIVE);
 453        return (nr_active >> priority);
 454}
 455
 456long mem_cgroup_calc_reclaim_inactive(struct mem_cgroup *mem,
 457                                        struct zone *zone, int priority)
 458{
 459        long nr_inactive;
 460        int nid = zone->zone_pgdat->node_id;
 461        int zid = zone_idx(zone);
 462        struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(mem, nid, zid);
 463
 464        nr_inactive = MEM_CGROUP_ZSTAT(mz, MEM_CGROUP_ZSTAT_INACTIVE);
 465        return (nr_inactive >> priority);
 466}
 467
 468unsigned long mem_cgroup_isolate_pages(unsigned long nr_to_scan,
 469                                        struct list_head *dst,
 470                                        unsigned long *scanned, int order,
 471                                        int mode, struct zone *z,
 472                                        struct mem_cgroup *mem_cont,
 473                                        int active)
 474{
 475        unsigned long nr_taken = 0;
 476        struct page *page;
 477        unsigned long scan;
 478        LIST_HEAD(pc_list);
 479        struct list_head *src;
 480        struct page_cgroup *pc, *tmp;
 481        int nid = z->zone_pgdat->node_id;
 482        int zid = zone_idx(z);
 483        struct mem_cgroup_per_zone *mz;
 484
 485        BUG_ON(!mem_cont);
 486        mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
 487        if (active)
 488                src = &mz->active_list;
 489        else
 490                src = &mz->inactive_list;
 491
 492
 493        spin_lock(&mz->lru_lock);
 494        scan = 0;
 495        list_for_each_entry_safe_reverse(pc, tmp, src, lru) {
 496                if (scan >= nr_to_scan)
 497                        break;
 498                page = pc->page;
 499
 500                if (unlikely(!PageLRU(page)))
 501                        continue;
 502
 503                if (PageActive(page) && !active) {
 504                        __mem_cgroup_move_lists(pc, true);
 505                        continue;
 506                }
 507                if (!PageActive(page) && active) {
 508                        __mem_cgroup_move_lists(pc, false);
 509                        continue;
 510                }
 511
 512                scan++;
 513                list_move(&pc->lru, &pc_list);
 514
 515                if (__isolate_lru_page(page, mode) == 0) {
 516                        list_move(&page->lru, dst);
 517                        nr_taken++;
 518                }
 519        }
 520
 521        list_splice(&pc_list, src);
 522        spin_unlock(&mz->lru_lock);
 523
 524        *scanned = scan;
 525        return nr_taken;
 526}
 527
 528/*
 529 * Charge the memory controller for page usage.
 530 * Return
 531 * 0 if the charge was successful
 532 * < 0 if the cgroup is over its limit
 533 */
 534static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
 535                                gfp_t gfp_mask, enum charge_type ctype)
 536{
 537        struct mem_cgroup *mem;
 538        struct page_cgroup *pc;
 539        unsigned long flags;
 540        unsigned long nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
 541        struct mem_cgroup_per_zone *mz;
 542
 543        if (mem_cgroup_subsys.disabled)
 544                return 0;
 545
 546        /*
 547         * Should page_cgroup's go to their own slab?
 548         * One could optimize the performance of the charging routine
 549         * by saving a bit in the page_flags and using it as a lock
 550         * to see if the cgroup page already has a page_cgroup associated
 551         * with it
 552         */
 553retry:
 554        lock_page_cgroup(page);
 555        pc = page_get_page_cgroup(page);
 556        /*
 557         * The page_cgroup exists and
 558         * the page has already been accounted.
 559         */
 560        if (pc) {
 561                VM_BUG_ON(pc->page != page);
 562                VM_BUG_ON(pc->ref_cnt <= 0);
 563
 564                pc->ref_cnt++;
 565                unlock_page_cgroup(page);
 566                goto done;
 567        }
 568        unlock_page_cgroup(page);
 569
 570        pc = kmem_cache_zalloc(page_cgroup_cache, gfp_mask);
 571        if (pc == NULL)
 572                goto err;
 573
 574        /*
 575         * We always charge the cgroup the mm_struct belongs to.
 576         * The mm_struct's mem_cgroup changes on task migration if the
 577         * thread group leader migrates. It's possible that mm is not
 578         * set, if so charge the init_mm (happens for pagecache usage).
 579         */
 580        if (!mm)
 581                mm = &init_mm;
 582
 583        rcu_read_lock();
 584        mem = mem_cgroup_from_task(rcu_dereference(mm->owner));
 585        if (unlikely(!mem)) {
 586                rcu_read_unlock();
 587                kmem_cache_free(page_cgroup_cache, pc);
 588                return 0;
 589        }
 590        /*
 591         * For every charge from the cgroup, increment reference count
 592         */
 593        css_get(&mem->css);
 594        rcu_read_unlock();
 595
 596        while (res_counter_charge(&mem->res, PAGE_SIZE)) {
 597                if (!(gfp_mask & __GFP_WAIT))
 598                        goto out;
 599
 600                if (try_to_free_mem_cgroup_pages(mem, gfp_mask))
 601                        continue;
 602
 603                /*
 604                 * try_to_free_mem_cgroup_pages() might not give us a full
 605                 * picture of reclaim. Some pages are reclaimed and might be
 606                 * moved to swap cache or just unmapped from the cgroup.
 607                 * Check the limit again to see if the reclaim reduced the
 608                 * current usage of the cgroup before giving up
 609                 */
 610                if (res_counter_check_under_limit(&mem->res))
 611                        continue;
 612
 613                if (!nr_retries--) {
 614                        mem_cgroup_out_of_memory(mem, gfp_mask);
 615                        goto out;
 616                }
 617        }
 618
 619        pc->ref_cnt = 1;
 620        pc->mem_cgroup = mem;
 621        pc->page = page;
 622        pc->flags = PAGE_CGROUP_FLAG_ACTIVE;
 623        if (ctype == MEM_CGROUP_CHARGE_TYPE_CACHE)
 624                pc->flags = PAGE_CGROUP_FLAG_CACHE;
 625
 626        lock_page_cgroup(page);
 627        if (page_get_page_cgroup(page)) {
 628                unlock_page_cgroup(page);
 629                /*
 630                 * Another charge has been added to this page already.
 631                 * We take lock_page_cgroup(page) again and read
 632                 * page->cgroup, increment refcnt.... just retry is OK.
 633                 */
 634                res_counter_uncharge(&mem->res, PAGE_SIZE);
 635                css_put(&mem->css);
 636                kmem_cache_free(page_cgroup_cache, pc);
 637                goto retry;
 638        }
 639        page_assign_page_cgroup(page, pc);
 640
 641        mz = page_cgroup_zoneinfo(pc);
 642        spin_lock_irqsave(&mz->lru_lock, flags);
 643        __mem_cgroup_add_list(mz, pc);
 644        spin_unlock_irqrestore(&mz->lru_lock, flags);
 645
 646        unlock_page_cgroup(page);
 647done:
 648        return 0;
 649out:
 650        css_put(&mem->css);
 651        kmem_cache_free(page_cgroup_cache, pc);
 652err:
 653        return -ENOMEM;
 654}
 655
 656int mem_cgroup_charge(struct page *page, struct mm_struct *mm, gfp_t gfp_mask)
 657{
 658        return mem_cgroup_charge_common(page, mm, gfp_mask,
 659                                MEM_CGROUP_CHARGE_TYPE_MAPPED);
 660}
 661
 662int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
 663                                gfp_t gfp_mask)
 664{
 665        if (!mm)
 666                mm = &init_mm;
 667        return mem_cgroup_charge_common(page, mm, gfp_mask,
 668                                MEM_CGROUP_CHARGE_TYPE_CACHE);
 669}
 670
 671/*
 672 * Uncharging is always a welcome operation, we never complain, simply
 673 * uncharge.
 674 */
 675void mem_cgroup_uncharge_page(struct page *page)
 676{
 677        struct page_cgroup *pc;
 678        struct mem_cgroup *mem;
 679        struct mem_cgroup_per_zone *mz;
 680        unsigned long flags;
 681
 682        if (mem_cgroup_subsys.disabled)
 683                return;
 684
 685        /*
 686         * Check if our page_cgroup is valid
 687         */
 688        lock_page_cgroup(page);
 689        pc = page_get_page_cgroup(page);
 690        if (!pc)
 691                goto unlock;
 692
 693        VM_BUG_ON(pc->page != page);
 694        VM_BUG_ON(pc->ref_cnt <= 0);
 695
 696        if (--(pc->ref_cnt) == 0) {
 697                mz = page_cgroup_zoneinfo(pc);
 698                spin_lock_irqsave(&mz->lru_lock, flags);
 699                __mem_cgroup_remove_list(mz, pc);
 700                spin_unlock_irqrestore(&mz->lru_lock, flags);
 701
 702                page_assign_page_cgroup(page, NULL);
 703                unlock_page_cgroup(page);
 704
 705                mem = pc->mem_cgroup;
 706                res_counter_uncharge(&mem->res, PAGE_SIZE);
 707                css_put(&mem->css);
 708
 709                kmem_cache_free(page_cgroup_cache, pc);
 710                return;
 711        }
 712
 713unlock:
 714        unlock_page_cgroup(page);
 715}
 716
 717/*
 718 * Returns non-zero if a page (under migration) has valid page_cgroup member.
 719 * Refcnt of page_cgroup is incremented.
 720 */
 721int mem_cgroup_prepare_migration(struct page *page)
 722{
 723        struct page_cgroup *pc;
 724
 725        if (mem_cgroup_subsys.disabled)
 726                return 0;
 727
 728        lock_page_cgroup(page);
 729        pc = page_get_page_cgroup(page);
 730        if (pc)
 731                pc->ref_cnt++;
 732        unlock_page_cgroup(page);
 733        return pc != NULL;
 734}
 735
 736void mem_cgroup_end_migration(struct page *page)
 737{
 738        mem_cgroup_uncharge_page(page);
 739}
 740
 741/*
 742 * We know both *page* and *newpage* are now not-on-LRU and PG_locked.
 743 * And no race with uncharge() routines because page_cgroup for *page*
 744 * has extra one reference by mem_cgroup_prepare_migration.
 745 */
 746void mem_cgroup_page_migration(struct page *page, struct page *newpage)
 747{
 748        struct page_cgroup *pc;
 749        struct mem_cgroup_per_zone *mz;
 750        unsigned long flags;
 751
 752        lock_page_cgroup(page);
 753        pc = page_get_page_cgroup(page);
 754        if (!pc) {
 755                unlock_page_cgroup(page);
 756                return;
 757        }
 758
 759        mz = page_cgroup_zoneinfo(pc);
 760        spin_lock_irqsave(&mz->lru_lock, flags);
 761        __mem_cgroup_remove_list(mz, pc);
 762        spin_unlock_irqrestore(&mz->lru_lock, flags);
 763
 764        page_assign_page_cgroup(page, NULL);
 765        unlock_page_cgroup(page);
 766
 767        pc->page = newpage;
 768        lock_page_cgroup(newpage);
 769        page_assign_page_cgroup(newpage, pc);
 770
 771        mz = page_cgroup_zoneinfo(pc);
 772        spin_lock_irqsave(&mz->lru_lock, flags);
 773        __mem_cgroup_add_list(mz, pc);
 774        spin_unlock_irqrestore(&mz->lru_lock, flags);
 775
 776        unlock_page_cgroup(newpage);
 777}
 778
 779/*
 780 * This routine traverse page_cgroup in given list and drop them all.
 781 * This routine ignores page_cgroup->ref_cnt.
 782 * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
 783 */
 784#define FORCE_UNCHARGE_BATCH    (128)
 785static void mem_cgroup_force_empty_list(struct mem_cgroup *mem,
 786                            struct mem_cgroup_per_zone *mz,
 787                            int active)
 788{
 789        struct page_cgroup *pc;
 790        struct page *page;
 791        int count = FORCE_UNCHARGE_BATCH;
 792        unsigned long flags;
 793        struct list_head *list;
 794
 795        if (active)
 796                list = &mz->active_list;
 797        else
 798                list = &mz->inactive_list;
 799
 800        spin_lock_irqsave(&mz->lru_lock, flags);
 801        while (!list_empty(list)) {
 802                pc = list_entry(list->prev, struct page_cgroup, lru);
 803                page = pc->page;
 804                get_page(page);
 805                spin_unlock_irqrestore(&mz->lru_lock, flags);
 806                mem_cgroup_uncharge_page(page);
 807                put_page(page);
 808                if (--count <= 0) {
 809                        count = FORCE_UNCHARGE_BATCH;
 810                        cond_resched();
 811                }
 812                spin_lock_irqsave(&mz->lru_lock, flags);
 813        }
 814        spin_unlock_irqrestore(&mz->lru_lock, flags);
 815}
 816
 817/*
 818 * make mem_cgroup's charge to be 0 if there is no task.
 819 * This enables deleting this mem_cgroup.
 820 */
 821static int mem_cgroup_force_empty(struct mem_cgroup *mem)
 822{
 823        int ret = -EBUSY;
 824        int node, zid;
 825
 826        if (mem_cgroup_subsys.disabled)
 827                return 0;
 828
 829        css_get(&mem->css);
 830        /*
 831         * page reclaim code (kswapd etc..) will move pages between
 832         * active_list <-> inactive_list while we don't take a lock.
 833         * So, we have to do loop here until all lists are empty.
 834         */
 835        while (mem->res.usage > 0) {
 836                if (atomic_read(&mem->css.cgroup->count) > 0)
 837                        goto out;
 838                for_each_node_state(node, N_POSSIBLE)
 839                        for (zid = 0; zid < MAX_NR_ZONES; zid++) {
 840                                struct mem_cgroup_per_zone *mz;
 841                                mz = mem_cgroup_zoneinfo(mem, node, zid);
 842                                /* drop all page_cgroup in active_list */
 843                                mem_cgroup_force_empty_list(mem, mz, 1);
 844                                /* drop all page_cgroup in inactive_list */
 845                                mem_cgroup_force_empty_list(mem, mz, 0);
 846                        }
 847        }
 848        ret = 0;
 849out:
 850        css_put(&mem->css);
 851        return ret;
 852}
 853
 854static int mem_cgroup_write_strategy(char *buf, unsigned long long *tmp)
 855{
 856        *tmp = memparse(buf, &buf);
 857        if (*buf != '\0')
 858                return -EINVAL;
 859
 860        /*
 861         * Round up the value to the closest page size
 862         */
 863        *tmp = ((*tmp + PAGE_SIZE - 1) >> PAGE_SHIFT) << PAGE_SHIFT;
 864        return 0;
 865}
 866
 867static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft)
 868{
 869        return res_counter_read_u64(&mem_cgroup_from_cont(cont)->res,
 870                                    cft->private);
 871}
 872
 873static ssize_t mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
 874                                struct file *file, const char __user *userbuf,
 875                                size_t nbytes, loff_t *ppos)
 876{
 877        return res_counter_write(&mem_cgroup_from_cont(cont)->res,
 878                                cft->private, userbuf, nbytes, ppos,
 879                                mem_cgroup_write_strategy);
 880}
 881
 882static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
 883{
 884        struct mem_cgroup *mem;
 885
 886        mem = mem_cgroup_from_cont(cont);
 887        switch (event) {
 888        case RES_MAX_USAGE:
 889                res_counter_reset_max(&mem->res);
 890                break;
 891        case RES_FAILCNT:
 892                res_counter_reset_failcnt(&mem->res);
 893                break;
 894        }
 895        return 0;
 896}
 897
 898static int mem_force_empty_write(struct cgroup *cont, unsigned int event)
 899{
 900        return mem_cgroup_force_empty(mem_cgroup_from_cont(cont));
 901}
 902
 903static const struct mem_cgroup_stat_desc {
 904        const char *msg;
 905        u64 unit;
 906} mem_cgroup_stat_desc[] = {
 907        [MEM_CGROUP_STAT_CACHE] = { "cache", PAGE_SIZE, },
 908        [MEM_CGROUP_STAT_RSS] = { "rss", PAGE_SIZE, },
 909        [MEM_CGROUP_STAT_PGPGIN_COUNT] = {"pgpgin", 1, },
 910        [MEM_CGROUP_STAT_PGPGOUT_COUNT] = {"pgpgout", 1, },
 911};
 912
 913static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft,
 914                                 struct cgroup_map_cb *cb)
 915{
 916        struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
 917        struct mem_cgroup_stat *stat = &mem_cont->stat;
 918        int i;
 919
 920        for (i = 0; i < ARRAY_SIZE(stat->cpustat[0].count); i++) {
 921                s64 val;
 922
 923                val = mem_cgroup_read_stat(stat, i);
 924                val *= mem_cgroup_stat_desc[i].unit;
 925                cb->fill(cb, mem_cgroup_stat_desc[i].msg, val);
 926        }
 927        /* showing # of active pages */
 928        {
 929                unsigned long active, inactive;
 930
 931                inactive = mem_cgroup_get_all_zonestat(mem_cont,
 932                                                MEM_CGROUP_ZSTAT_INACTIVE);
 933                active = mem_cgroup_get_all_zonestat(mem_cont,
 934                                                MEM_CGROUP_ZSTAT_ACTIVE);
 935                cb->fill(cb, "active", (active) * PAGE_SIZE);
 936                cb->fill(cb, "inactive", (inactive) * PAGE_SIZE);
 937        }
 938        return 0;
 939}
 940
 941static struct cftype mem_cgroup_files[] = {
 942        {
 943                .name = "usage_in_bytes",
 944                .private = RES_USAGE,
 945                .read_u64 = mem_cgroup_read,
 946        },
 947        {
 948                .name = "max_usage_in_bytes",
 949                .private = RES_MAX_USAGE,
 950                .trigger = mem_cgroup_reset,
 951                .read_u64 = mem_cgroup_read,
 952        },
 953        {
 954                .name = "limit_in_bytes",
 955                .private = RES_LIMIT,
 956                .write = mem_cgroup_write,
 957                .read_u64 = mem_cgroup_read,
 958        },
 959        {
 960                .name = "failcnt",
 961                .private = RES_FAILCNT,
 962                .trigger = mem_cgroup_reset,
 963                .read_u64 = mem_cgroup_read,
 964        },
 965        {
 966                .name = "force_empty",
 967                .trigger = mem_force_empty_write,
 968        },
 969        {
 970                .name = "stat",
 971                .read_map = mem_control_stat_show,
 972        },
 973};
 974
 975static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
 976{
 977        struct mem_cgroup_per_node *pn;
 978        struct mem_cgroup_per_zone *mz;
 979        int zone, tmp = node;
 980        /*
 981         * This routine is called against possible nodes.
 982         * But it's BUG to call kmalloc() against offline node.
 983         *
 984         * TODO: this routine can waste much memory for nodes which will
 985         *       never be onlined. It's better to use memory hotplug callback
 986         *       function.
 987         */
 988        if (!node_state(node, N_NORMAL_MEMORY))
 989                tmp = -1;
 990        pn = kmalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
 991        if (!pn)
 992                return 1;
 993
 994        mem->info.nodeinfo[node] = pn;
 995        memset(pn, 0, sizeof(*pn));
 996
 997        for (zone = 0; zone < MAX_NR_ZONES; zone++) {
 998                mz = &pn->zoneinfo[zone];
 999                INIT_LIST_HEAD(&mz->active_list);
1000                INIT_LIST_HEAD(&mz->inactive_list);
1001                spin_lock_init(&mz->lru_lock);
1002        }
1003        return 0;
1004}
1005
1006static void free_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
1007{
1008        kfree(mem->info.nodeinfo[node]);
1009}
1010
1011static struct mem_cgroup *mem_cgroup_alloc(void)
1012{
1013        struct mem_cgroup *mem;
1014
1015        if (sizeof(*mem) < PAGE_SIZE)
1016                mem = kmalloc(sizeof(*mem), GFP_KERNEL);
1017        else
1018                mem = vmalloc(sizeof(*mem));
1019
1020        if (mem)
1021                memset(mem, 0, sizeof(*mem));
1022        return mem;
1023}
1024
1025static void mem_cgroup_free(struct mem_cgroup *mem)
1026{
1027        if (sizeof(*mem) < PAGE_SIZE)
1028                kfree(mem);
1029        else
1030                vfree(mem);
1031}
1032
1033
1034static struct cgroup_subsys_state *
1035mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
1036{
1037        struct mem_cgroup *mem;
1038        int node;
1039
1040        if (unlikely((cont->parent) == NULL)) {
1041                mem = &init_mem_cgroup;
1042                page_cgroup_cache = KMEM_CACHE(page_cgroup, SLAB_PANIC);
1043        } else {
1044                mem = mem_cgroup_alloc();
1045                if (!mem)
1046                        return ERR_PTR(-ENOMEM);
1047        }
1048
1049        res_counter_init(&mem->res);
1050
1051        for_each_node_state(node, N_POSSIBLE)
1052                if (alloc_mem_cgroup_per_zone_info(mem, node))
1053                        goto free_out;
1054
1055        return &mem->css;
1056free_out:
1057        for_each_node_state(node, N_POSSIBLE)
1058                free_mem_cgroup_per_zone_info(mem, node);
1059        if (cont->parent != NULL)
1060                mem_cgroup_free(mem);
1061        return ERR_PTR(-ENOMEM);
1062}
1063
1064static void mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
1065                                        struct cgroup *cont)
1066{
1067        struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
1068        mem_cgroup_force_empty(mem);
1069}
1070
1071static void mem_cgroup_destroy(struct cgroup_subsys *ss,
1072                                struct cgroup *cont)
1073{
1074        int node;
1075        struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
1076
1077        for_each_node_state(node, N_POSSIBLE)
1078                free_mem_cgroup_per_zone_info(mem, node);
1079
1080        mem_cgroup_free(mem_cgroup_from_cont(cont));
1081}
1082
1083static int mem_cgroup_populate(struct cgroup_subsys *ss,
1084                                struct cgroup *cont)
1085{
1086        if (mem_cgroup_subsys.disabled)
1087                return 0;
1088        return cgroup_add_files(cont, ss, mem_cgroup_files,
1089                                        ARRAY_SIZE(mem_cgroup_files));
1090}
1091
1092static void mem_cgroup_move_task(struct cgroup_subsys *ss,
1093                                struct cgroup *cont,
1094                                struct cgroup *old_cont,
1095                                struct task_struct *p)
1096{
1097        struct mm_struct *mm;
1098        struct mem_cgroup *mem, *old_mem;
1099
1100        if (mem_cgroup_subsys.disabled)
1101                return;
1102
1103        mm = get_task_mm(p);
1104        if (mm == NULL)
1105                return;
1106
1107        mem = mem_cgroup_from_cont(cont);
1108        old_mem = mem_cgroup_from_cont(old_cont);
1109
1110        if (mem == old_mem)
1111                goto out;
1112
1113        /*
1114         * Only thread group leaders are allowed to migrate, the mm_struct is
1115         * in effect owned by the leader
1116         */
1117        if (!thread_group_leader(p))
1118                goto out;
1119
1120out:
1121        mmput(mm);
1122}
1123
1124struct cgroup_subsys mem_cgroup_subsys = {
1125        .name = "memory",
1126        .subsys_id = mem_cgroup_subsys_id,
1127        .create = mem_cgroup_create,
1128        .pre_destroy = mem_cgroup_pre_destroy,
1129        .destroy = mem_cgroup_destroy,
1130        .populate = mem_cgroup_populate,
1131        .attach = mem_cgroup_move_task,
1132        .early_init = 0,
1133};
1134