linux/fs/f2fs/node.c
<<
>>
Prefs
   1/*
   2 * fs/f2fs/node.c
   3 *
   4 * Copyright (c) 2012 Samsung Electronics Co., Ltd.
   5 *             http://www.samsung.com/
   6 *
   7 * This program is free software; you can redistribute it and/or modify
   8 * it under the terms of the GNU General Public License version 2 as
   9 * published by the Free Software Foundation.
  10 */
  11#include <linux/fs.h>
  12#include <linux/f2fs_fs.h>
  13#include <linux/mpage.h>
  14#include <linux/backing-dev.h>
  15#include <linux/blkdev.h>
  16#include <linux/pagevec.h>
  17#include <linux/swap.h>
  18
  19#include "f2fs.h"
  20#include "node.h"
  21#include "segment.h"
  22#include "xattr.h"
  23#include "trace.h"
  24#include <trace/events/f2fs.h>
  25
  26#define on_f2fs_build_free_nids(nmi) mutex_is_locked(&(nm_i)->build_lock)
  27
  28static struct kmem_cache *nat_entry_slab;
  29static struct kmem_cache *free_nid_slab;
  30static struct kmem_cache *nat_entry_set_slab;
  31
  32/*
  33 * Check whether the given nid is within node id range.
  34 */
  35int f2fs_check_nid_range(struct f2fs_sb_info *sbi, nid_t nid)
  36{
  37        if (unlikely(nid < F2FS_ROOT_INO(sbi) || nid >= NM_I(sbi)->max_nid)) {
  38                set_sbi_flag(sbi, SBI_NEED_FSCK);
  39                f2fs_msg(sbi->sb, KERN_WARNING,
  40                                "%s: out-of-range nid=%x, run fsck to fix.",
  41                                __func__, nid);
  42                return -EINVAL;
  43        }
  44        return 0;
  45}
  46
  47bool f2fs_available_free_memory(struct f2fs_sb_info *sbi, int type)
  48{
  49        struct f2fs_nm_info *nm_i = NM_I(sbi);
  50        struct sysinfo val;
  51        unsigned long avail_ram;
  52        unsigned long mem_size = 0;
  53        bool res = false;
  54
  55        si_meminfo(&val);
  56
  57        /* only uses low memory */
  58        avail_ram = val.totalram - val.totalhigh;
  59
  60        /*
  61         * give 25%, 25%, 50%, 50%, 50% memory for each components respectively
  62         */
  63        if (type == FREE_NIDS) {
  64                mem_size = (nm_i->nid_cnt[FREE_NID] *
  65                                sizeof(struct free_nid)) >> PAGE_SHIFT;
  66                res = mem_size < ((avail_ram * nm_i->ram_thresh / 100) >> 2);
  67        } else if (type == NAT_ENTRIES) {
  68                mem_size = (nm_i->nat_cnt * sizeof(struct nat_entry)) >>
  69                                                        PAGE_SHIFT;
  70                res = mem_size < ((avail_ram * nm_i->ram_thresh / 100) >> 2);
  71                if (excess_cached_nats(sbi))
  72                        res = false;
  73        } else if (type == DIRTY_DENTS) {
  74                if (sbi->sb->s_bdi->wb.dirty_exceeded)
  75                        return false;
  76                mem_size = get_pages(sbi, F2FS_DIRTY_DENTS);
  77                res = mem_size < ((avail_ram * nm_i->ram_thresh / 100) >> 1);
  78        } else if (type == INO_ENTRIES) {
  79                int i;
  80
  81                for (i = 0; i < MAX_INO_ENTRY; i++)
  82                        mem_size += sbi->im[i].ino_num *
  83                                                sizeof(struct ino_entry);
  84                mem_size >>= PAGE_SHIFT;
  85                res = mem_size < ((avail_ram * nm_i->ram_thresh / 100) >> 1);
  86        } else if (type == EXTENT_CACHE) {
  87                mem_size = (atomic_read(&sbi->total_ext_tree) *
  88                                sizeof(struct extent_tree) +
  89                                atomic_read(&sbi->total_ext_node) *
  90                                sizeof(struct extent_node)) >> PAGE_SHIFT;
  91                res = mem_size < ((avail_ram * nm_i->ram_thresh / 100) >> 1);
  92        } else if (type == INMEM_PAGES) {
  93                /* it allows 20% / total_ram for inmemory pages */
  94                mem_size = get_pages(sbi, F2FS_INMEM_PAGES);
  95                res = mem_size < (val.totalram / 5);
  96        } else {
  97                if (!sbi->sb->s_bdi->wb.dirty_exceeded)
  98                        return true;
  99        }
 100        return res;
 101}
 102
 103static void clear_node_page_dirty(struct page *page)
 104{
 105        if (PageDirty(page)) {
 106                f2fs_clear_radix_tree_dirty_tag(page);
 107                clear_page_dirty_for_io(page);
 108                dec_page_count(F2FS_P_SB(page), F2FS_DIRTY_NODES);
 109        }
 110        ClearPageUptodate(page);
 111}
 112
 113static struct page *get_current_nat_page(struct f2fs_sb_info *sbi, nid_t nid)
 114{
 115        pgoff_t index = current_nat_addr(sbi, nid);
 116        return f2fs_get_meta_page(sbi, index);
 117}
 118
 119static struct page *get_next_nat_page(struct f2fs_sb_info *sbi, nid_t nid)
 120{
 121        struct page *src_page;
 122        struct page *dst_page;
 123        pgoff_t src_off;
 124        pgoff_t dst_off;
 125        void *src_addr;
 126        void *dst_addr;
 127        struct f2fs_nm_info *nm_i = NM_I(sbi);
 128
 129        src_off = current_nat_addr(sbi, nid);
 130        dst_off = next_nat_addr(sbi, src_off);
 131
 132        /* get current nat block page with lock */
 133        src_page = f2fs_get_meta_page(sbi, src_off);
 134        dst_page = f2fs_grab_meta_page(sbi, dst_off);
 135        f2fs_bug_on(sbi, PageDirty(src_page));
 136
 137        src_addr = page_address(src_page);
 138        dst_addr = page_address(dst_page);
 139        memcpy(dst_addr, src_addr, PAGE_SIZE);
 140        set_page_dirty(dst_page);
 141        f2fs_put_page(src_page, 1);
 142
 143        set_to_next_nat(nm_i, nid);
 144
 145        return dst_page;
 146}
 147
 148static struct nat_entry *__alloc_nat_entry(nid_t nid, bool no_fail)
 149{
 150        struct nat_entry *new;
 151
 152        if (no_fail)
 153                new = f2fs_kmem_cache_alloc(nat_entry_slab, GFP_F2FS_ZERO);
 154        else
 155                new = kmem_cache_alloc(nat_entry_slab, GFP_F2FS_ZERO);
 156        if (new) {
 157                nat_set_nid(new, nid);
 158                nat_reset_flag(new);
 159        }
 160        return new;
 161}
 162
 163static void __free_nat_entry(struct nat_entry *e)
 164{
 165        kmem_cache_free(nat_entry_slab, e);
 166}
 167
 168/* must be locked by nat_tree_lock */
 169static struct nat_entry *__init_nat_entry(struct f2fs_nm_info *nm_i,
 170        struct nat_entry *ne, struct f2fs_nat_entry *raw_ne, bool no_fail)
 171{
 172        if (no_fail)
 173                f2fs_radix_tree_insert(&nm_i->nat_root, nat_get_nid(ne), ne);
 174        else if (radix_tree_insert(&nm_i->nat_root, nat_get_nid(ne), ne))
 175                return NULL;
 176
 177        if (raw_ne)
 178                node_info_from_raw_nat(&ne->ni, raw_ne);
 179        list_add_tail(&ne->list, &nm_i->nat_entries);
 180        nm_i->nat_cnt++;
 181        return ne;
 182}
 183
 184static struct nat_entry *__lookup_nat_cache(struct f2fs_nm_info *nm_i, nid_t n)
 185{
 186        return radix_tree_lookup(&nm_i->nat_root, n);
 187}
 188
 189static unsigned int __gang_lookup_nat_cache(struct f2fs_nm_info *nm_i,
 190                nid_t start, unsigned int nr, struct nat_entry **ep)
 191{
 192        return radix_tree_gang_lookup(&nm_i->nat_root, (void **)ep, start, nr);
 193}
 194
 195static void __del_from_nat_cache(struct f2fs_nm_info *nm_i, struct nat_entry *e)
 196{
 197        list_del(&e->list);
 198        radix_tree_delete(&nm_i->nat_root, nat_get_nid(e));
 199        nm_i->nat_cnt--;
 200        __free_nat_entry(e);
 201}
 202
 203static struct nat_entry_set *__grab_nat_entry_set(struct f2fs_nm_info *nm_i,
 204                                                        struct nat_entry *ne)
 205{
 206        nid_t set = NAT_BLOCK_OFFSET(ne->ni.nid);
 207        struct nat_entry_set *head;
 208
 209        head = radix_tree_lookup(&nm_i->nat_set_root, set);
 210        if (!head) {
 211                head = f2fs_kmem_cache_alloc(nat_entry_set_slab, GFP_NOFS);
 212
 213                INIT_LIST_HEAD(&head->entry_list);
 214                INIT_LIST_HEAD(&head->set_list);
 215                head->set = set;
 216                head->entry_cnt = 0;
 217                f2fs_radix_tree_insert(&nm_i->nat_set_root, set, head);
 218        }
 219        return head;
 220}
 221
 222static void __set_nat_cache_dirty(struct f2fs_nm_info *nm_i,
 223                                                struct nat_entry *ne)
 224{
 225        struct nat_entry_set *head;
 226        bool new_ne = nat_get_blkaddr(ne) == NEW_ADDR;
 227
 228        if (!new_ne)
 229                head = __grab_nat_entry_set(nm_i, ne);
 230
 231        /*
 232         * update entry_cnt in below condition:
 233         * 1. update NEW_ADDR to valid block address;
 234         * 2. update old block address to new one;
 235         */
 236        if (!new_ne && (get_nat_flag(ne, IS_PREALLOC) ||
 237                                !get_nat_flag(ne, IS_DIRTY)))
 238                head->entry_cnt++;
 239
 240        set_nat_flag(ne, IS_PREALLOC, new_ne);
 241
 242        if (get_nat_flag(ne, IS_DIRTY))
 243                goto refresh_list;
 244
 245        nm_i->dirty_nat_cnt++;
 246        set_nat_flag(ne, IS_DIRTY, true);
 247refresh_list:
 248        if (new_ne)
 249                list_del_init(&ne->list);
 250        else
 251                list_move_tail(&ne->list, &head->entry_list);
 252}
 253
 254static void __clear_nat_cache_dirty(struct f2fs_nm_info *nm_i,
 255                struct nat_entry_set *set, struct nat_entry *ne)
 256{
 257        list_move_tail(&ne->list, &nm_i->nat_entries);
 258        set_nat_flag(ne, IS_DIRTY, false);
 259        set->entry_cnt--;
 260        nm_i->dirty_nat_cnt--;
 261}
 262
 263static unsigned int __gang_lookup_nat_set(struct f2fs_nm_info *nm_i,
 264                nid_t start, unsigned int nr, struct nat_entry_set **ep)
 265{
 266        return radix_tree_gang_lookup(&nm_i->nat_set_root, (void **)ep,
 267                                                        start, nr);
 268}
 269
 270int f2fs_need_dentry_mark(struct f2fs_sb_info *sbi, nid_t nid)
 271{
 272        struct f2fs_nm_info *nm_i = NM_I(sbi);
 273        struct nat_entry *e;
 274        bool need = false;
 275
 276        down_read(&nm_i->nat_tree_lock);
 277        e = __lookup_nat_cache(nm_i, nid);
 278        if (e) {
 279                if (!get_nat_flag(e, IS_CHECKPOINTED) &&
 280                                !get_nat_flag(e, HAS_FSYNCED_INODE))
 281                        need = true;
 282        }
 283        up_read(&nm_i->nat_tree_lock);
 284        return need;
 285}
 286
 287bool f2fs_is_checkpointed_node(struct f2fs_sb_info *sbi, nid_t nid)
 288{
 289        struct f2fs_nm_info *nm_i = NM_I(sbi);
 290        struct nat_entry *e;
 291        bool is_cp = true;
 292
 293        down_read(&nm_i->nat_tree_lock);
 294        e = __lookup_nat_cache(nm_i, nid);
 295        if (e && !get_nat_flag(e, IS_CHECKPOINTED))
 296                is_cp = false;
 297        up_read(&nm_i->nat_tree_lock);
 298        return is_cp;
 299}
 300
 301bool f2fs_need_inode_block_update(struct f2fs_sb_info *sbi, nid_t ino)
 302{
 303        struct f2fs_nm_info *nm_i = NM_I(sbi);
 304        struct nat_entry *e;
 305        bool need_update = true;
 306
 307        down_read(&nm_i->nat_tree_lock);
 308        e = __lookup_nat_cache(nm_i, ino);
 309        if (e && get_nat_flag(e, HAS_LAST_FSYNC) &&
 310                        (get_nat_flag(e, IS_CHECKPOINTED) ||
 311                         get_nat_flag(e, HAS_FSYNCED_INODE)))
 312                need_update = false;
 313        up_read(&nm_i->nat_tree_lock);
 314        return need_update;
 315}
 316
 317/* must be locked by nat_tree_lock */
 318static void cache_nat_entry(struct f2fs_sb_info *sbi, nid_t nid,
 319                                                struct f2fs_nat_entry *ne)
 320{
 321        struct f2fs_nm_info *nm_i = NM_I(sbi);
 322        struct nat_entry *new, *e;
 323
 324        new = __alloc_nat_entry(nid, false);
 325        if (!new)
 326                return;
 327
 328        down_write(&nm_i->nat_tree_lock);
 329        e = __lookup_nat_cache(nm_i, nid);
 330        if (!e)
 331                e = __init_nat_entry(nm_i, new, ne, false);
 332        else
 333                f2fs_bug_on(sbi, nat_get_ino(e) != le32_to_cpu(ne->ino) ||
 334                                nat_get_blkaddr(e) !=
 335                                        le32_to_cpu(ne->block_addr) ||
 336                                nat_get_version(e) != ne->version);
 337        up_write(&nm_i->nat_tree_lock);
 338        if (e != new)
 339                __free_nat_entry(new);
 340}
 341
 342static void set_node_addr(struct f2fs_sb_info *sbi, struct node_info *ni,
 343                        block_t new_blkaddr, bool fsync_done)
 344{
 345        struct f2fs_nm_info *nm_i = NM_I(sbi);
 346        struct nat_entry *e;
 347        struct nat_entry *new = __alloc_nat_entry(ni->nid, true);
 348
 349        down_write(&nm_i->nat_tree_lock);
 350        e = __lookup_nat_cache(nm_i, ni->nid);
 351        if (!e) {
 352                e = __init_nat_entry(nm_i, new, NULL, true);
 353                copy_node_info(&e->ni, ni);
 354                f2fs_bug_on(sbi, ni->blk_addr == NEW_ADDR);
 355        } else if (new_blkaddr == NEW_ADDR) {
 356                /*
 357                 * when nid is reallocated,
 358                 * previous nat entry can be remained in nat cache.
 359                 * So, reinitialize it with new information.
 360                 */
 361                copy_node_info(&e->ni, ni);
 362                f2fs_bug_on(sbi, ni->blk_addr != NULL_ADDR);
 363        }
 364        /* let's free early to reduce memory consumption */
 365        if (e != new)
 366                __free_nat_entry(new);
 367
 368        /* sanity check */
 369        f2fs_bug_on(sbi, nat_get_blkaddr(e) != ni->blk_addr);
 370        f2fs_bug_on(sbi, nat_get_blkaddr(e) == NULL_ADDR &&
 371                        new_blkaddr == NULL_ADDR);
 372        f2fs_bug_on(sbi, nat_get_blkaddr(e) == NEW_ADDR &&
 373                        new_blkaddr == NEW_ADDR);
 374        f2fs_bug_on(sbi, is_valid_blkaddr(nat_get_blkaddr(e)) &&
 375                        new_blkaddr == NEW_ADDR);
 376
 377        /* increment version no as node is removed */
 378        if (nat_get_blkaddr(e) != NEW_ADDR && new_blkaddr == NULL_ADDR) {
 379                unsigned char version = nat_get_version(e);
 380                nat_set_version(e, inc_node_version(version));
 381        }
 382
 383        /* change address */
 384        nat_set_blkaddr(e, new_blkaddr);
 385        if (!is_valid_blkaddr(new_blkaddr))
 386                set_nat_flag(e, IS_CHECKPOINTED, false);
 387        __set_nat_cache_dirty(nm_i, e);
 388
 389        /* update fsync_mark if its inode nat entry is still alive */
 390        if (ni->nid != ni->ino)
 391                e = __lookup_nat_cache(nm_i, ni->ino);
 392        if (e) {
 393                if (fsync_done && ni->nid == ni->ino)
 394                        set_nat_flag(e, HAS_FSYNCED_INODE, true);
 395                set_nat_flag(e, HAS_LAST_FSYNC, fsync_done);
 396        }
 397        up_write(&nm_i->nat_tree_lock);
 398}
 399
 400int f2fs_try_to_free_nats(struct f2fs_sb_info *sbi, int nr_shrink)
 401{
 402        struct f2fs_nm_info *nm_i = NM_I(sbi);
 403        int nr = nr_shrink;
 404
 405        if (!down_write_trylock(&nm_i->nat_tree_lock))
 406                return 0;
 407
 408        while (nr_shrink && !list_empty(&nm_i->nat_entries)) {
 409                struct nat_entry *ne;
 410                ne = list_first_entry(&nm_i->nat_entries,
 411                                        struct nat_entry, list);
 412                __del_from_nat_cache(nm_i, ne);
 413                nr_shrink--;
 414        }
 415        up_write(&nm_i->nat_tree_lock);
 416        return nr - nr_shrink;
 417}
 418
 419/*
 420 * This function always returns success
 421 */
 422void f2fs_get_node_info(struct f2fs_sb_info *sbi, nid_t nid,
 423                                                struct node_info *ni)
 424{
 425        struct f2fs_nm_info *nm_i = NM_I(sbi);
 426        struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_HOT_DATA);
 427        struct f2fs_journal *journal = curseg->journal;
 428        nid_t start_nid = START_NID(nid);
 429        struct f2fs_nat_block *nat_blk;
 430        struct page *page = NULL;
 431        struct f2fs_nat_entry ne;
 432        struct nat_entry *e;
 433        pgoff_t index;
 434        int i;
 435
 436        ni->nid = nid;
 437
 438        /* Check nat cache */
 439        down_read(&nm_i->nat_tree_lock);
 440        e = __lookup_nat_cache(nm_i, nid);
 441        if (e) {
 442                ni->ino = nat_get_ino(e);
 443                ni->blk_addr = nat_get_blkaddr(e);
 444                ni->version = nat_get_version(e);
 445                up_read(&nm_i->nat_tree_lock);
 446                return;
 447        }
 448
 449        memset(&ne, 0, sizeof(struct f2fs_nat_entry));
 450
 451        /* Check current segment summary */
 452        down_read(&curseg->journal_rwsem);
 453        i = f2fs_lookup_journal_in_cursum(journal, NAT_JOURNAL, nid, 0);
 454        if (i >= 0) {
 455                ne = nat_in_journal(journal, i);
 456                node_info_from_raw_nat(ni, &ne);
 457        }
 458        up_read(&curseg->journal_rwsem);
 459        if (i >= 0) {
 460                up_read(&nm_i->nat_tree_lock);
 461                goto cache;
 462        }
 463
 464        /* Fill node_info from nat page */
 465        index = current_nat_addr(sbi, nid);
 466        up_read(&nm_i->nat_tree_lock);
 467
 468        page = f2fs_get_meta_page(sbi, index);
 469        nat_blk = (struct f2fs_nat_block *)page_address(page);
 470        ne = nat_blk->entries[nid - start_nid];
 471        node_info_from_raw_nat(ni, &ne);
 472        f2fs_put_page(page, 1);
 473cache:
 474        /* cache nat entry */
 475        cache_nat_entry(sbi, nid, &ne);
 476}
 477
 478/*
 479 * readahead MAX_RA_NODE number of node pages.
 480 */
 481static void f2fs_ra_node_pages(struct page *parent, int start, int n)
 482{
 483        struct f2fs_sb_info *sbi = F2FS_P_SB(parent);
 484        struct blk_plug plug;
 485        int i, end;
 486        nid_t nid;
 487
 488        blk_start_plug(&plug);
 489
 490        /* Then, try readahead for siblings of the desired node */
 491        end = start + n;
 492        end = min(end, NIDS_PER_BLOCK);
 493        for (i = start; i < end; i++) {
 494                nid = get_nid(parent, i, false);
 495                f2fs_ra_node_page(sbi, nid);
 496        }
 497
 498        blk_finish_plug(&plug);
 499}
 500
 501pgoff_t f2fs_get_next_page_offset(struct dnode_of_data *dn, pgoff_t pgofs)
 502{
 503        const long direct_index = ADDRS_PER_INODE(dn->inode);
 504        const long direct_blks = ADDRS_PER_BLOCK;
 505        const long indirect_blks = ADDRS_PER_BLOCK * NIDS_PER_BLOCK;
 506        unsigned int skipped_unit = ADDRS_PER_BLOCK;
 507        int cur_level = dn->cur_level;
 508        int max_level = dn->max_level;
 509        pgoff_t base = 0;
 510
 511        if (!dn->max_level)
 512                return pgofs + 1;
 513
 514        while (max_level-- > cur_level)
 515                skipped_unit *= NIDS_PER_BLOCK;
 516
 517        switch (dn->max_level) {
 518        case 3:
 519                base += 2 * indirect_blks;
 520                /* fall through */
 521        case 2:
 522                base += 2 * direct_blks;
 523                /* fall through */
 524        case 1:
 525                base += direct_index;
 526                break;
 527        default:
 528                f2fs_bug_on(F2FS_I_SB(dn->inode), 1);
 529        }
 530
 531        return ((pgofs - base) / skipped_unit + 1) * skipped_unit + base;
 532}
 533
 534/*
 535 * The maximum depth is four.
 536 * Offset[0] will have raw inode offset.
 537 */
 538static int get_node_path(struct inode *inode, long block,
 539                                int offset[4], unsigned int noffset[4])
 540{
 541        const long direct_index = ADDRS_PER_INODE(inode);
 542        const long direct_blks = ADDRS_PER_BLOCK;
 543        const long dptrs_per_blk = NIDS_PER_BLOCK;
 544        const long indirect_blks = ADDRS_PER_BLOCK * NIDS_PER_BLOCK;
 545        const long dindirect_blks = indirect_blks * NIDS_PER_BLOCK;
 546        int n = 0;
 547        int level = 0;
 548
 549        noffset[0] = 0;
 550
 551        if (block < direct_index) {
 552                offset[n] = block;
 553                goto got;
 554        }
 555        block -= direct_index;
 556        if (block < direct_blks) {
 557                offset[n++] = NODE_DIR1_BLOCK;
 558                noffset[n] = 1;
 559                offset[n] = block;
 560                level = 1;
 561                goto got;
 562        }
 563        block -= direct_blks;
 564        if (block < direct_blks) {
 565                offset[n++] = NODE_DIR2_BLOCK;
 566                noffset[n] = 2;
 567                offset[n] = block;
 568                level = 1;
 569                goto got;
 570        }
 571        block -= direct_blks;
 572        if (block < indirect_blks) {
 573                offset[n++] = NODE_IND1_BLOCK;
 574                noffset[n] = 3;
 575                offset[n++] = block / direct_blks;
 576                noffset[n] = 4 + offset[n - 1];
 577                offset[n] = block % direct_blks;
 578                level = 2;
 579                goto got;
 580        }
 581        block -= indirect_blks;
 582        if (block < indirect_blks) {
 583                offset[n++] = NODE_IND2_BLOCK;
 584                noffset[n] = 4 + dptrs_per_blk;
 585                offset[n++] = block / direct_blks;
 586                noffset[n] = 5 + dptrs_per_blk + offset[n - 1];
 587                offset[n] = block % direct_blks;
 588                level = 2;
 589                goto got;
 590        }
 591        block -= indirect_blks;
 592        if (block < dindirect_blks) {
 593                offset[n++] = NODE_DIND_BLOCK;
 594                noffset[n] = 5 + (dptrs_per_blk * 2);
 595                offset[n++] = block / indirect_blks;
 596                noffset[n] = 6 + (dptrs_per_blk * 2) +
 597                              offset[n - 1] * (dptrs_per_blk + 1);
 598                offset[n++] = (block / direct_blks) % dptrs_per_blk;
 599                noffset[n] = 7 + (dptrs_per_blk * 2) +
 600                              offset[n - 2] * (dptrs_per_blk + 1) +
 601                              offset[n - 1];
 602                offset[n] = block % direct_blks;
 603                level = 3;
 604                goto got;
 605        } else {
 606                return -E2BIG;
 607        }
 608got:
 609        return level;
 610}
 611
 612/*
 613 * Caller should call f2fs_put_dnode(dn).
 614 * Also, it should grab and release a rwsem by calling f2fs_lock_op() and
 615 * f2fs_unlock_op() only if ro is not set RDONLY_NODE.
 616 * In the case of RDONLY_NODE, we don't need to care about mutex.
 617 */
 618int f2fs_get_dnode_of_data(struct dnode_of_data *dn, pgoff_t index, int mode)
 619{
 620        struct f2fs_sb_info *sbi = F2FS_I_SB(dn->inode);
 621        struct page *npage[4];
 622        struct page *parent = NULL;
 623        int offset[4];
 624        unsigned int noffset[4];
 625        nid_t nids[4];
 626        int level, i = 0;
 627        int err = 0;
 628
 629        level = get_node_path(dn->inode, index, offset, noffset);
 630        if (level < 0)
 631                return level;
 632
 633        nids[0] = dn->inode->i_ino;
 634        npage[0] = dn->inode_page;
 635
 636        if (!npage[0]) {
 637                npage[0] = f2fs_get_node_page(sbi, nids[0]);
 638                if (IS_ERR(npage[0]))
 639                        return PTR_ERR(npage[0]);
 640        }
 641
 642        /* if inline_data is set, should not report any block indices */
 643        if (f2fs_has_inline_data(dn->inode) && index) {
 644                err = -ENOENT;
 645                f2fs_put_page(npage[0], 1);
 646                goto release_out;
 647        }
 648
 649        parent = npage[0];
 650        if (level != 0)
 651                nids[1] = get_nid(parent, offset[0], true);
 652        dn->inode_page = npage[0];
 653        dn->inode_page_locked = true;
 654
 655        /* get indirect or direct nodes */
 656        for (i = 1; i <= level; i++) {
 657                bool done = false;
 658
 659                if (!nids[i] && mode == ALLOC_NODE) {
 660                        /* alloc new node */
 661                        if (!f2fs_alloc_nid(sbi, &(nids[i]))) {
 662                                err = -ENOSPC;
 663                                goto release_pages;
 664                        }
 665
 666                        dn->nid = nids[i];
 667                        npage[i] = f2fs_new_node_page(dn, noffset[i]);
 668                        if (IS_ERR(npage[i])) {
 669                                f2fs_alloc_nid_failed(sbi, nids[i]);
 670                                err = PTR_ERR(npage[i]);
 671                                goto release_pages;
 672                        }
 673
 674                        set_nid(parent, offset[i - 1], nids[i], i == 1);
 675                        f2fs_alloc_nid_done(sbi, nids[i]);
 676                        done = true;
 677                } else if (mode == LOOKUP_NODE_RA && i == level && level > 1) {
 678                        npage[i] = f2fs_get_node_page_ra(parent, offset[i - 1]);
 679                        if (IS_ERR(npage[i])) {
 680                                err = PTR_ERR(npage[i]);
 681                                goto release_pages;
 682                        }
 683                        done = true;
 684                }
 685                if (i == 1) {
 686                        dn->inode_page_locked = false;
 687                        unlock_page(parent);
 688                } else {
 689                        f2fs_put_page(parent, 1);
 690                }
 691
 692                if (!done) {
 693                        npage[i] = f2fs_get_node_page(sbi, nids[i]);
 694                        if (IS_ERR(npage[i])) {
 695                                err = PTR_ERR(npage[i]);
 696                                f2fs_put_page(npage[0], 0);
 697                                goto release_out;
 698                        }
 699                }
 700                if (i < level) {
 701                        parent = npage[i];
 702                        nids[i + 1] = get_nid(parent, offset[i], false);
 703                }
 704        }
 705        dn->nid = nids[level];
 706        dn->ofs_in_node = offset[level];
 707        dn->node_page = npage[level];
 708        dn->data_blkaddr = datablock_addr(dn->inode,
 709                                dn->node_page, dn->ofs_in_node);
 710        return 0;
 711
 712release_pages:
 713        f2fs_put_page(parent, 1);
 714        if (i > 1)
 715                f2fs_put_page(npage[0], 0);
 716release_out:
 717        dn->inode_page = NULL;
 718        dn->node_page = NULL;
 719        if (err == -ENOENT) {
 720                dn->cur_level = i;
 721                dn->max_level = level;
 722                dn->ofs_in_node = offset[level];
 723        }
 724        return err;
 725}
 726
 727static void truncate_node(struct dnode_of_data *dn)
 728{
 729        struct f2fs_sb_info *sbi = F2FS_I_SB(dn->inode);
 730        struct node_info ni;
 731
 732        f2fs_get_node_info(sbi, dn->nid, &ni);
 733
 734        /* Deallocate node address */
 735        f2fs_invalidate_blocks(sbi, ni.blk_addr);
 736        dec_valid_node_count(sbi, dn->inode, dn->nid == dn->inode->i_ino);
 737        set_node_addr(sbi, &ni, NULL_ADDR, false);
 738
 739        if (dn->nid == dn->inode->i_ino) {
 740                f2fs_remove_orphan_inode(sbi, dn->nid);
 741                dec_valid_inode_count(sbi);
 742                f2fs_inode_synced(dn->inode);
 743        }
 744
 745        clear_node_page_dirty(dn->node_page);
 746        set_sbi_flag(sbi, SBI_IS_DIRTY);
 747
 748        f2fs_put_page(dn->node_page, 1);
 749
 750        invalidate_mapping_pages(NODE_MAPPING(sbi),
 751                        dn->node_page->index, dn->node_page->index);
 752
 753        dn->node_page = NULL;
 754        trace_f2fs_truncate_node(dn->inode, dn->nid, ni.blk_addr);
 755}
 756
 757static int truncate_dnode(struct dnode_of_data *dn)
 758{
 759        struct page *page;
 760
 761        if (dn->nid == 0)
 762                return 1;
 763
 764        /* get direct node */
 765        page = f2fs_get_node_page(F2FS_I_SB(dn->inode), dn->nid);
 766        if (IS_ERR(page) && PTR_ERR(page) == -ENOENT)
 767                return 1;
 768        else if (IS_ERR(page))
 769                return PTR_ERR(page);
 770
 771        /* Make dnode_of_data for parameter */
 772        dn->node_page = page;
 773        dn->ofs_in_node = 0;
 774        f2fs_truncate_data_blocks(dn);
 775        truncate_node(dn);
 776        return 1;
 777}
 778
 779static int truncate_nodes(struct dnode_of_data *dn, unsigned int nofs,
 780                                                int ofs, int depth)
 781{
 782        struct dnode_of_data rdn = *dn;
 783        struct page *page;
 784        struct f2fs_node *rn;
 785        nid_t child_nid;
 786        unsigned int child_nofs;
 787        int freed = 0;
 788        int i, ret;
 789
 790        if (dn->nid == 0)
 791                return NIDS_PER_BLOCK + 1;
 792
 793        trace_f2fs_truncate_nodes_enter(dn->inode, dn->nid, dn->data_blkaddr);
 794
 795        page = f2fs_get_node_page(F2FS_I_SB(dn->inode), dn->nid);
 796        if (IS_ERR(page)) {
 797                trace_f2fs_truncate_nodes_exit(dn->inode, PTR_ERR(page));
 798                return PTR_ERR(page);
 799        }
 800
 801        f2fs_ra_node_pages(page, ofs, NIDS_PER_BLOCK);
 802
 803        rn = F2FS_NODE(page);
 804        if (depth < 3) {
 805                for (i = ofs; i < NIDS_PER_BLOCK; i++, freed++) {
 806                        child_nid = le32_to_cpu(rn->in.nid[i]);
 807                        if (child_nid == 0)
 808                                continue;
 809                        rdn.nid = child_nid;
 810                        ret = truncate_dnode(&rdn);
 811                        if (ret < 0)
 812                                goto out_err;
 813                        if (set_nid(page, i, 0, false))
 814                                dn->node_changed = true;
 815                }
 816        } else {
 817                child_nofs = nofs + ofs * (NIDS_PER_BLOCK + 1) + 1;
 818                for (i = ofs; i < NIDS_PER_BLOCK; i++) {
 819                        child_nid = le32_to_cpu(rn->in.nid[i]);
 820                        if (child_nid == 0) {
 821                                child_nofs += NIDS_PER_BLOCK + 1;
 822                                continue;
 823                        }
 824                        rdn.nid = child_nid;
 825                        ret = truncate_nodes(&rdn, child_nofs, 0, depth - 1);
 826                        if (ret == (NIDS_PER_BLOCK + 1)) {
 827                                if (set_nid(page, i, 0, false))
 828                                        dn->node_changed = true;
 829                                child_nofs += ret;
 830                        } else if (ret < 0 && ret != -ENOENT) {
 831                                goto out_err;
 832                        }
 833                }
 834                freed = child_nofs;
 835        }
 836
 837        if (!ofs) {
 838                /* remove current indirect node */
 839                dn->node_page = page;
 840                truncate_node(dn);
 841                freed++;
 842        } else {
 843                f2fs_put_page(page, 1);
 844        }
 845        trace_f2fs_truncate_nodes_exit(dn->inode, freed);
 846        return freed;
 847
 848out_err:
 849        f2fs_put_page(page, 1);
 850        trace_f2fs_truncate_nodes_exit(dn->inode, ret);
 851        return ret;
 852}
 853
 854static int truncate_partial_nodes(struct dnode_of_data *dn,
 855                        struct f2fs_inode *ri, int *offset, int depth)
 856{
 857        struct page *pages[2];
 858        nid_t nid[3];
 859        nid_t child_nid;
 860        int err = 0;
 861        int i;
 862        int idx = depth - 2;
 863
 864        nid[0] = le32_to_cpu(ri->i_nid[offset[0] - NODE_DIR1_BLOCK]);
 865        if (!nid[0])
 866                return 0;
 867
 868        /* get indirect nodes in the path */
 869        for (i = 0; i < idx + 1; i++) {
 870                /* reference count'll be increased */
 871                pages[i] = f2fs_get_node_page(F2FS_I_SB(dn->inode), nid[i]);
 872                if (IS_ERR(pages[i])) {
 873                        err = PTR_ERR(pages[i]);
 874                        idx = i - 1;
 875                        goto fail;
 876                }
 877                nid[i + 1] = get_nid(pages[i], offset[i + 1], false);
 878        }
 879
 880        f2fs_ra_node_pages(pages[idx], offset[idx + 1], NIDS_PER_BLOCK);
 881
 882        /* free direct nodes linked to a partial indirect node */
 883        for (i = offset[idx + 1]; i < NIDS_PER_BLOCK; i++) {
 884                child_nid = get_nid(pages[idx], i, false);
 885                if (!child_nid)
 886                        continue;
 887                dn->nid = child_nid;
 888                err = truncate_dnode(dn);
 889                if (err < 0)
 890                        goto fail;
 891                if (set_nid(pages[idx], i, 0, false))
 892                        dn->node_changed = true;
 893        }
 894
 895        if (offset[idx + 1] == 0) {
 896                dn->node_page = pages[idx];
 897                dn->nid = nid[idx];
 898                truncate_node(dn);
 899        } else {
 900                f2fs_put_page(pages[idx], 1);
 901        }
 902        offset[idx]++;
 903        offset[idx + 1] = 0;
 904        idx--;
 905fail:
 906        for (i = idx; i >= 0; i--)
 907                f2fs_put_page(pages[i], 1);
 908
 909        trace_f2fs_truncate_partial_nodes(dn->inode, nid, depth, err);
 910
 911        return err;
 912}
 913
 914/*
 915 * All the block addresses of data and nodes should be nullified.
 916 */
 917int f2fs_truncate_inode_blocks(struct inode *inode, pgoff_t from)
 918{
 919        struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
 920        int err = 0, cont = 1;
 921        int level, offset[4], noffset[4];
 922        unsigned int nofs = 0;
 923        struct f2fs_inode *ri;
 924        struct dnode_of_data dn;
 925        struct page *page;
 926
 927        trace_f2fs_truncate_inode_blocks_enter(inode, from);
 928
 929        level = get_node_path(inode, from, offset, noffset);
 930        if (level < 0)
 931                return level;
 932
 933        page = f2fs_get_node_page(sbi, inode->i_ino);
 934        if (IS_ERR(page)) {
 935                trace_f2fs_truncate_inode_blocks_exit(inode, PTR_ERR(page));
 936                return PTR_ERR(page);
 937        }
 938
 939        set_new_dnode(&dn, inode, page, NULL, 0);
 940        unlock_page(page);
 941
 942        ri = F2FS_INODE(page);
 943        switch (level) {
 944        case 0:
 945        case 1:
 946                nofs = noffset[1];
 947                break;
 948        case 2:
 949                nofs = noffset[1];
 950                if (!offset[level - 1])
 951                        goto skip_partial;
 952                err = truncate_partial_nodes(&dn, ri, offset, level);
 953                if (err < 0 && err != -ENOENT)
 954                        goto fail;
 955                nofs += 1 + NIDS_PER_BLOCK;
 956                break;
 957        case 3:
 958                nofs = 5 + 2 * NIDS_PER_BLOCK;
 959                if (!offset[level - 1])
 960                        goto skip_partial;
 961                err = truncate_partial_nodes(&dn, ri, offset, level);
 962                if (err < 0 && err != -ENOENT)
 963                        goto fail;
 964                break;
 965        default:
 966                BUG();
 967        }
 968
 969skip_partial:
 970        while (cont) {
 971                dn.nid = le32_to_cpu(ri->i_nid[offset[0] - NODE_DIR1_BLOCK]);
 972                switch (offset[0]) {
 973                case NODE_DIR1_BLOCK:
 974                case NODE_DIR2_BLOCK:
 975                        err = truncate_dnode(&dn);
 976                        break;
 977
 978                case NODE_IND1_BLOCK:
 979                case NODE_IND2_BLOCK:
 980                        err = truncate_nodes(&dn, nofs, offset[1], 2);
 981                        break;
 982
 983                case NODE_DIND_BLOCK:
 984                        err = truncate_nodes(&dn, nofs, offset[1], 3);
 985                        cont = 0;
 986                        break;
 987
 988                default:
 989                        BUG();
 990                }
 991                if (err < 0 && err != -ENOENT)
 992                        goto fail;
 993                if (offset[1] == 0 &&
 994                                ri->i_nid[offset[0] - NODE_DIR1_BLOCK]) {
 995                        lock_page(page);
 996                        BUG_ON(page->mapping != NODE_MAPPING(sbi));
 997                        f2fs_wait_on_page_writeback(page, NODE, true);
 998                        ri->i_nid[offset[0] - NODE_DIR1_BLOCK] = 0;
 999                        set_page_dirty(page);
1000                        unlock_page(page);
1001                }
1002                offset[1] = 0;
1003                offset[0]++;
1004                nofs += err;
1005        }
1006fail:
1007        f2fs_put_page(page, 0);
1008        trace_f2fs_truncate_inode_blocks_exit(inode, err);
1009        return err > 0 ? 0 : err;
1010}
1011
1012/* caller must lock inode page */
1013int f2fs_truncate_xattr_node(struct inode *inode)
1014{
1015        struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1016        nid_t nid = F2FS_I(inode)->i_xattr_nid;
1017        struct dnode_of_data dn;
1018        struct page *npage;
1019
1020        if (!nid)
1021                return 0;
1022
1023        npage = f2fs_get_node_page(sbi, nid);
1024        if (IS_ERR(npage))
1025                return PTR_ERR(npage);
1026
1027        f2fs_i_xnid_write(inode, 0);
1028
1029        set_new_dnode(&dn, inode, NULL, npage, nid);
1030        truncate_node(&dn);
1031        return 0;
1032}
1033
1034/*
1035 * Caller should grab and release a rwsem by calling f2fs_lock_op() and
1036 * f2fs_unlock_op().
1037 */
1038int f2fs_remove_inode_page(struct inode *inode)
1039{
1040        struct dnode_of_data dn;
1041        int err;
1042
1043        set_new_dnode(&dn, inode, NULL, NULL, inode->i_ino);
1044        err = f2fs_get_dnode_of_data(&dn, 0, LOOKUP_NODE);
1045        if (err)
1046                return err;
1047
1048        err = f2fs_truncate_xattr_node(inode);
1049        if (err) {
1050                f2fs_put_dnode(&dn);
1051                return err;
1052        }
1053
1054        /* remove potential inline_data blocks */
1055        if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
1056                                S_ISLNK(inode->i_mode))
1057                f2fs_truncate_data_blocks_range(&dn, 1);
1058
1059        /* 0 is possible, after f2fs_new_inode() has failed */
1060        f2fs_bug_on(F2FS_I_SB(inode),
1061                        inode->i_blocks != 0 && inode->i_blocks != 8);
1062
1063        /* will put inode & node pages */
1064        truncate_node(&dn);
1065        return 0;
1066}
1067
1068struct page *f2fs_new_inode_page(struct inode *inode)
1069{
1070        struct dnode_of_data dn;
1071
1072        /* allocate inode page for new inode */
1073        set_new_dnode(&dn, inode, NULL, NULL, inode->i_ino);
1074
1075        /* caller should f2fs_put_page(page, 1); */
1076        return f2fs_new_node_page(&dn, 0);
1077}
1078
1079struct page *f2fs_new_node_page(struct dnode_of_data *dn, unsigned int ofs)
1080{
1081        struct f2fs_sb_info *sbi = F2FS_I_SB(dn->inode);
1082        struct node_info new_ni;
1083        struct page *page;
1084        int err;
1085
1086        if (unlikely(is_inode_flag_set(dn->inode, FI_NO_ALLOC)))
1087                return ERR_PTR(-EPERM);
1088
1089        page = f2fs_grab_cache_page(NODE_MAPPING(sbi), dn->nid, false);
1090        if (!page)
1091                return ERR_PTR(-ENOMEM);
1092
1093        if (unlikely((err = inc_valid_node_count(sbi, dn->inode, !ofs))))
1094                goto fail;
1095
1096#ifdef CONFIG_F2FS_CHECK_FS
1097        f2fs_get_node_info(sbi, dn->nid, &new_ni);
1098        f2fs_bug_on(sbi, new_ni.blk_addr != NULL_ADDR);
1099#endif
1100        new_ni.nid = dn->nid;
1101        new_ni.ino = dn->inode->i_ino;
1102        new_ni.blk_addr = NULL_ADDR;
1103        new_ni.flag = 0;
1104        new_ni.version = 0;
1105        set_node_addr(sbi, &new_ni, NEW_ADDR, false);
1106
1107        f2fs_wait_on_page_writeback(page, NODE, true);
1108        fill_node_footer(page, dn->nid, dn->inode->i_ino, ofs, true);
1109        set_cold_node(page, S_ISDIR(dn->inode->i_mode));
1110        if (!PageUptodate(page))
1111                SetPageUptodate(page);
1112        if (set_page_dirty(page))
1113                dn->node_changed = true;
1114
1115        if (f2fs_has_xattr_block(ofs))
1116                f2fs_i_xnid_write(dn->inode, dn->nid);
1117
1118        if (ofs == 0)
1119                inc_valid_inode_count(sbi);
1120        return page;
1121
1122fail:
1123        clear_node_page_dirty(page);
1124        f2fs_put_page(page, 1);
1125        return ERR_PTR(err);
1126}
1127
1128/*
1129 * Caller should do after getting the following values.
1130 * 0: f2fs_put_page(page, 0)
1131 * LOCKED_PAGE or error: f2fs_put_page(page, 1)
1132 */
1133static int read_node_page(struct page *page, int op_flags)
1134{
1135        struct f2fs_sb_info *sbi = F2FS_P_SB(page);
1136        struct node_info ni;
1137        struct f2fs_io_info fio = {
1138                .sbi = sbi,
1139                .type = NODE,
1140                .op = REQ_OP_READ,
1141                .op_flags = op_flags,
1142                .page = page,
1143                .encrypted_page = NULL,
1144        };
1145
1146        if (PageUptodate(page))
1147                return LOCKED_PAGE;
1148
1149        f2fs_get_node_info(sbi, page->index, &ni);
1150
1151        if (unlikely(ni.blk_addr == NULL_ADDR)) {
1152                ClearPageUptodate(page);
1153                return -ENOENT;
1154        }
1155
1156        fio.new_blkaddr = fio.old_blkaddr = ni.blk_addr;
1157        return f2fs_submit_page_bio(&fio);
1158}
1159
1160/*
1161 * Readahead a node page
1162 */
1163void f2fs_ra_node_page(struct f2fs_sb_info *sbi, nid_t nid)
1164{
1165        struct page *apage;
1166        int err;
1167
1168        if (!nid)
1169                return;
1170        if (f2fs_check_nid_range(sbi, nid))
1171                return;
1172
1173        rcu_read_lock();
1174        apage = radix_tree_lookup(&NODE_MAPPING(sbi)->i_pages, nid);
1175        rcu_read_unlock();
1176        if (apage)
1177                return;
1178
1179        apage = f2fs_grab_cache_page(NODE_MAPPING(sbi), nid, false);
1180        if (!apage)
1181                return;
1182
1183        err = read_node_page(apage, REQ_RAHEAD);
1184        f2fs_put_page(apage, err ? 1 : 0);
1185}
1186
1187static struct page *__get_node_page(struct f2fs_sb_info *sbi, pgoff_t nid,
1188                                        struct page *parent, int start)
1189{
1190        struct page *page;
1191        int err;
1192
1193        if (!nid)
1194                return ERR_PTR(-ENOENT);
1195        if (f2fs_check_nid_range(sbi, nid))
1196                return ERR_PTR(-EINVAL);
1197repeat:
1198        page = f2fs_grab_cache_page(NODE_MAPPING(sbi), nid, false);
1199        if (!page)
1200                return ERR_PTR(-ENOMEM);
1201
1202        err = read_node_page(page, 0);
1203        if (err < 0) {
1204                f2fs_put_page(page, 1);
1205                return ERR_PTR(err);
1206        } else if (err == LOCKED_PAGE) {
1207                err = 0;
1208                goto page_hit;
1209        }
1210
1211        if (parent)
1212                f2fs_ra_node_pages(parent, start + 1, MAX_RA_NODE);
1213
1214        lock_page(page);
1215
1216        if (unlikely(page->mapping != NODE_MAPPING(sbi))) {
1217                f2fs_put_page(page, 1);
1218                goto repeat;
1219        }
1220
1221        if (unlikely(!PageUptodate(page))) {
1222                err = -EIO;
1223                goto out_err;
1224        }
1225
1226        if (!f2fs_inode_chksum_verify(sbi, page)) {
1227                err = -EBADMSG;
1228                goto out_err;
1229        }
1230page_hit:
1231        if(unlikely(nid != nid_of_node(page))) {
1232                f2fs_msg(sbi->sb, KERN_WARNING, "inconsistent node block, "
1233                        "nid:%lu, node_footer[nid:%u,ino:%u,ofs:%u,cpver:%llu,blkaddr:%u]",
1234                        nid, nid_of_node(page), ino_of_node(page),
1235                        ofs_of_node(page), cpver_of_node(page),
1236                        next_blkaddr_of_node(page));
1237                err = -EINVAL;
1238out_err:
1239                ClearPageUptodate(page);
1240                f2fs_put_page(page, 1);
1241                return ERR_PTR(err);
1242        }
1243        return page;
1244}
1245
1246struct page *f2fs_get_node_page(struct f2fs_sb_info *sbi, pgoff_t nid)
1247{
1248        return __get_node_page(sbi, nid, NULL, 0);
1249}
1250
1251struct page *f2fs_get_node_page_ra(struct page *parent, int start)
1252{
1253        struct f2fs_sb_info *sbi = F2FS_P_SB(parent);
1254        nid_t nid = get_nid(parent, start, false);
1255
1256        return __get_node_page(sbi, nid, parent, start);
1257}
1258
1259static void flush_inline_data(struct f2fs_sb_info *sbi, nid_t ino)
1260{
1261        struct inode *inode;
1262        struct page *page;
1263        int ret;
1264
1265        /* should flush inline_data before evict_inode */
1266        inode = ilookup(sbi->sb, ino);
1267        if (!inode)
1268                return;
1269
1270        page = f2fs_pagecache_get_page(inode->i_mapping, 0,
1271                                        FGP_LOCK|FGP_NOWAIT, 0);
1272        if (!page)
1273                goto iput_out;
1274
1275        if (!PageUptodate(page))
1276                goto page_out;
1277
1278        if (!PageDirty(page))
1279                goto page_out;
1280
1281        if (!clear_page_dirty_for_io(page))
1282                goto page_out;
1283
1284        ret = f2fs_write_inline_data(inode, page);
1285        inode_dec_dirty_pages(inode);
1286        f2fs_remove_dirty_inode(inode);
1287        if (ret)
1288                set_page_dirty(page);
1289page_out:
1290        f2fs_put_page(page, 1);
1291iput_out:
1292        iput(inode);
1293}
1294
1295static struct page *last_fsync_dnode(struct f2fs_sb_info *sbi, nid_t ino)
1296{
1297        pgoff_t index;
1298        struct pagevec pvec;
1299        struct page *last_page = NULL;
1300        int nr_pages;
1301
1302        pagevec_init(&pvec);
1303        index = 0;
1304
1305        while ((nr_pages = pagevec_lookup_tag(&pvec, NODE_MAPPING(sbi), &index,
1306                                PAGECACHE_TAG_DIRTY))) {
1307                int i;
1308
1309                for (i = 0; i < nr_pages; i++) {
1310                        struct page *page = pvec.pages[i];
1311
1312                        if (unlikely(f2fs_cp_error(sbi))) {
1313                                f2fs_put_page(last_page, 0);
1314                                pagevec_release(&pvec);
1315                                return ERR_PTR(-EIO);
1316                        }
1317
1318                        if (!IS_DNODE(page) || !is_cold_node(page))
1319                                continue;
1320                        if (ino_of_node(page) != ino)
1321                                continue;
1322
1323                        lock_page(page);
1324
1325                        if (unlikely(page->mapping != NODE_MAPPING(sbi))) {
1326continue_unlock:
1327                                unlock_page(page);
1328                                continue;
1329                        }
1330                        if (ino_of_node(page) != ino)
1331                                goto continue_unlock;
1332
1333                        if (!PageDirty(page)) {
1334                                /* someone wrote it for us */
1335                                goto continue_unlock;
1336                        }
1337
1338                        if (last_page)
1339                                f2fs_put_page(last_page, 0);
1340
1341                        get_page(page);
1342                        last_page = page;
1343                        unlock_page(page);
1344                }
1345                pagevec_release(&pvec);
1346                cond_resched();
1347        }
1348        return last_page;
1349}
1350
1351static int __write_node_page(struct page *page, bool atomic, bool *submitted,
1352                                struct writeback_control *wbc, bool do_balance,
1353                                enum iostat_type io_type)
1354{
1355        struct f2fs_sb_info *sbi = F2FS_P_SB(page);
1356        nid_t nid;
1357        struct node_info ni;
1358        struct f2fs_io_info fio = {
1359                .sbi = sbi,
1360                .ino = ino_of_node(page),
1361                .type = NODE,
1362                .op = REQ_OP_WRITE,
1363                .op_flags = wbc_to_write_flags(wbc),
1364                .page = page,
1365                .encrypted_page = NULL,
1366                .submitted = false,
1367                .io_type = io_type,
1368                .io_wbc = wbc,
1369        };
1370
1371        trace_f2fs_writepage(page, NODE);
1372
1373        if (unlikely(f2fs_cp_error(sbi)))
1374                goto redirty_out;
1375
1376        if (unlikely(is_sbi_flag_set(sbi, SBI_POR_DOING)))
1377                goto redirty_out;
1378
1379        /* get old block addr of this node page */
1380        nid = nid_of_node(page);
1381        f2fs_bug_on(sbi, page->index != nid);
1382
1383        if (wbc->for_reclaim) {
1384                if (!down_read_trylock(&sbi->node_write))
1385                        goto redirty_out;
1386        } else {
1387                down_read(&sbi->node_write);
1388        }
1389
1390        f2fs_get_node_info(sbi, nid, &ni);
1391
1392        /* This page is already truncated */
1393        if (unlikely(ni.blk_addr == NULL_ADDR)) {
1394                ClearPageUptodate(page);
1395                dec_page_count(sbi, F2FS_DIRTY_NODES);
1396                up_read(&sbi->node_write);
1397                unlock_page(page);
1398                return 0;
1399        }
1400
1401        if (atomic && !test_opt(sbi, NOBARRIER))
1402                fio.op_flags |= REQ_PREFLUSH | REQ_FUA;
1403
1404        set_page_writeback(page);
1405        ClearPageError(page);
1406        fio.old_blkaddr = ni.blk_addr;
1407        f2fs_do_write_node_page(nid, &fio);
1408        set_node_addr(sbi, &ni, fio.new_blkaddr, is_fsync_dnode(page));
1409        dec_page_count(sbi, F2FS_DIRTY_NODES);
1410        up_read(&sbi->node_write);
1411
1412        if (wbc->for_reclaim) {
1413                f2fs_submit_merged_write_cond(sbi, page->mapping->host, 0,
1414                                                page->index, NODE);
1415                submitted = NULL;
1416        }
1417
1418        unlock_page(page);
1419
1420        if (unlikely(f2fs_cp_error(sbi))) {
1421                f2fs_submit_merged_write(sbi, NODE);
1422                submitted = NULL;
1423        }
1424        if (submitted)
1425                *submitted = fio.submitted;
1426
1427        if (do_balance)
1428                f2fs_balance_fs(sbi, false);
1429        return 0;
1430
1431redirty_out:
1432        redirty_page_for_writepage(wbc, page);
1433        return AOP_WRITEPAGE_ACTIVATE;
1434}
1435
1436void f2fs_move_node_page(struct page *node_page, int gc_type)
1437{
1438        if (gc_type == FG_GC) {
1439                struct writeback_control wbc = {
1440                        .sync_mode = WB_SYNC_ALL,
1441                        .nr_to_write = 1,
1442                        .for_reclaim = 0,
1443                };
1444
1445                set_page_dirty(node_page);
1446                f2fs_wait_on_page_writeback(node_page, NODE, true);
1447
1448                f2fs_bug_on(F2FS_P_SB(node_page), PageWriteback(node_page));
1449                if (!clear_page_dirty_for_io(node_page))
1450                        goto out_page;
1451
1452                if (__write_node_page(node_page, false, NULL,
1453                                        &wbc, false, FS_GC_NODE_IO))
1454                        unlock_page(node_page);
1455                goto release_page;
1456        } else {
1457                /* set page dirty and write it */
1458                if (!PageWriteback(node_page))
1459                        set_page_dirty(node_page);
1460        }
1461out_page:
1462        unlock_page(node_page);
1463release_page:
1464        f2fs_put_page(node_page, 0);
1465}
1466
1467static int f2fs_write_node_page(struct page *page,
1468                                struct writeback_control *wbc)
1469{
1470        return __write_node_page(page, false, NULL, wbc, false, FS_NODE_IO);
1471}
1472
1473int f2fs_fsync_node_pages(struct f2fs_sb_info *sbi, struct inode *inode,
1474                        struct writeback_control *wbc, bool atomic)
1475{
1476        pgoff_t index;
1477        pgoff_t last_idx = ULONG_MAX;
1478        struct pagevec pvec;
1479        int ret = 0;
1480        struct page *last_page = NULL;
1481        bool marked = false;
1482        nid_t ino = inode->i_ino;
1483        int nr_pages;
1484
1485        if (atomic) {
1486                last_page = last_fsync_dnode(sbi, ino);
1487                if (IS_ERR_OR_NULL(last_page))
1488                        return PTR_ERR_OR_ZERO(last_page);
1489        }
1490retry:
1491        pagevec_init(&pvec);
1492        index = 0;
1493
1494        while ((nr_pages = pagevec_lookup_tag(&pvec, NODE_MAPPING(sbi), &index,
1495                                PAGECACHE_TAG_DIRTY))) {
1496                int i;
1497
1498                for (i = 0; i < nr_pages; i++) {
1499                        struct page *page = pvec.pages[i];
1500                        bool submitted = false;
1501
1502                        if (unlikely(f2fs_cp_error(sbi))) {
1503                                f2fs_put_page(last_page, 0);
1504                                pagevec_release(&pvec);
1505                                ret = -EIO;
1506                                goto out;
1507                        }
1508
1509                        if (!IS_DNODE(page) || !is_cold_node(page))
1510                                continue;
1511                        if (ino_of_node(page) != ino)
1512                                continue;
1513
1514                        lock_page(page);
1515
1516                        if (unlikely(page->mapping != NODE_MAPPING(sbi))) {
1517continue_unlock:
1518                                unlock_page(page);
1519                                continue;
1520                        }
1521                        if (ino_of_node(page) != ino)
1522                                goto continue_unlock;
1523
1524                        if (!PageDirty(page) && page != last_page) {
1525                                /* someone wrote it for us */
1526                                goto continue_unlock;
1527                        }
1528
1529                        f2fs_wait_on_page_writeback(page, NODE, true);
1530                        BUG_ON(PageWriteback(page));
1531
1532                        set_fsync_mark(page, 0);
1533                        set_dentry_mark(page, 0);
1534
1535                        if (!atomic || page == last_page) {
1536                                set_fsync_mark(page, 1);
1537                                if (IS_INODE(page)) {
1538                                        if (is_inode_flag_set(inode,
1539                                                                FI_DIRTY_INODE))
1540                                                f2fs_update_inode(inode, page);
1541                                        set_dentry_mark(page,
1542                                                f2fs_need_dentry_mark(sbi, ino));
1543                                }
1544                                /*  may be written by other thread */
1545                                if (!PageDirty(page))
1546                                        set_page_dirty(page);
1547                        }
1548
1549                        if (!clear_page_dirty_for_io(page))
1550                                goto continue_unlock;
1551
1552                        ret = __write_node_page(page, atomic &&
1553                                                page == last_page,
1554                                                &submitted, wbc, true,
1555                                                FS_NODE_IO);
1556                        if (ret) {
1557                                unlock_page(page);
1558                                f2fs_put_page(last_page, 0);
1559                                break;
1560                        } else if (submitted) {
1561                                last_idx = page->index;
1562                        }
1563
1564                        if (page == last_page) {
1565                                f2fs_put_page(page, 0);
1566                                marked = true;
1567                                break;
1568                        }
1569                }
1570                pagevec_release(&pvec);
1571                cond_resched();
1572
1573                if (ret || marked)
1574                        break;
1575        }
1576        if (!ret && atomic && !marked) {
1577                f2fs_msg(sbi->sb, KERN_DEBUG,
1578                        "Retry to write fsync mark: ino=%u, idx=%lx",
1579                                        ino, last_page->index);
1580                lock_page(last_page);
1581                f2fs_wait_on_page_writeback(last_page, NODE, true);
1582                set_page_dirty(last_page);
1583                unlock_page(last_page);
1584                goto retry;
1585        }
1586out:
1587        if (last_idx != ULONG_MAX)
1588                f2fs_submit_merged_write_cond(sbi, NULL, ino, last_idx, NODE);
1589        return ret ? -EIO: 0;
1590}
1591
1592int f2fs_sync_node_pages(struct f2fs_sb_info *sbi,
1593                                struct writeback_control *wbc,
1594                                bool do_balance, enum iostat_type io_type)
1595{
1596        pgoff_t index;
1597        struct pagevec pvec;
1598        int step = 0;
1599        int nwritten = 0;
1600        int ret = 0;
1601        int nr_pages, done = 0;
1602
1603        pagevec_init(&pvec);
1604
1605next_step:
1606        index = 0;
1607
1608        while (!done && (nr_pages = pagevec_lookup_tag(&pvec,
1609                        NODE_MAPPING(sbi), &index, PAGECACHE_TAG_DIRTY))) {
1610                int i;
1611
1612                for (i = 0; i < nr_pages; i++) {
1613                        struct page *page = pvec.pages[i];
1614                        bool submitted = false;
1615
1616                        /* give a priority to WB_SYNC threads */
1617                        if (atomic_read(&sbi->wb_sync_req[NODE]) &&
1618                                        wbc->sync_mode == WB_SYNC_NONE) {
1619                                done = 1;
1620                                break;
1621                        }
1622
1623                        /*
1624                         * flushing sequence with step:
1625                         * 0. indirect nodes
1626                         * 1. dentry dnodes
1627                         * 2. file dnodes
1628                         */
1629                        if (step == 0 && IS_DNODE(page))
1630                                continue;
1631                        if (step == 1 && (!IS_DNODE(page) ||
1632                                                is_cold_node(page)))
1633                                continue;
1634                        if (step == 2 && (!IS_DNODE(page) ||
1635                                                !is_cold_node(page)))
1636                                continue;
1637lock_node:
1638                        if (!trylock_page(page))
1639                                continue;
1640
1641                        if (unlikely(page->mapping != NODE_MAPPING(sbi))) {
1642continue_unlock:
1643                                unlock_page(page);
1644                                continue;
1645                        }
1646
1647                        if (!PageDirty(page)) {
1648                                /* someone wrote it for us */
1649                                goto continue_unlock;
1650                        }
1651
1652                        /* flush inline_data */
1653                        if (is_inline_node(page)) {
1654                                clear_inline_node(page);
1655                                unlock_page(page);
1656                                flush_inline_data(sbi, ino_of_node(page));
1657                                goto lock_node;
1658                        }
1659
1660                        f2fs_wait_on_page_writeback(page, NODE, true);
1661
1662                        BUG_ON(PageWriteback(page));
1663                        if (!clear_page_dirty_for_io(page))
1664                                goto continue_unlock;
1665
1666                        set_fsync_mark(page, 0);
1667                        set_dentry_mark(page, 0);
1668
1669                        ret = __write_node_page(page, false, &submitted,
1670                                                wbc, do_balance, io_type);
1671                        if (ret)
1672                                unlock_page(page);
1673                        else if (submitted)
1674                                nwritten++;
1675
1676                        if (--wbc->nr_to_write == 0)
1677                                break;
1678                }
1679                pagevec_release(&pvec);
1680                cond_resched();
1681
1682                if (wbc->nr_to_write == 0) {
1683                        step = 2;
1684                        break;
1685                }
1686        }
1687
1688        if (step < 2) {
1689                step++;
1690                goto next_step;
1691        }
1692
1693        if (nwritten)
1694                f2fs_submit_merged_write(sbi, NODE);
1695
1696        if (unlikely(f2fs_cp_error(sbi)))
1697                return -EIO;
1698        return ret;
1699}
1700
1701int f2fs_wait_on_node_pages_writeback(struct f2fs_sb_info *sbi, nid_t ino)
1702{
1703        pgoff_t index = 0;
1704        struct pagevec pvec;
1705        int ret2, ret = 0;
1706        int nr_pages;
1707
1708        pagevec_init(&pvec);
1709
1710        while ((nr_pages = pagevec_lookup_tag(&pvec, NODE_MAPPING(sbi), &index,
1711                                PAGECACHE_TAG_WRITEBACK))) {
1712                int i;
1713
1714                for (i = 0; i < nr_pages; i++) {
1715                        struct page *page = pvec.pages[i];
1716
1717                        if (ino && ino_of_node(page) == ino) {
1718                                f2fs_wait_on_page_writeback(page, NODE, true);
1719                                if (TestClearPageError(page))
1720                                        ret = -EIO;
1721                        }
1722                }
1723                pagevec_release(&pvec);
1724                cond_resched();
1725        }
1726
1727        ret2 = filemap_check_errors(NODE_MAPPING(sbi));
1728        if (!ret)
1729                ret = ret2;
1730        return ret;
1731}
1732
1733static int f2fs_write_node_pages(struct address_space *mapping,
1734                            struct writeback_control *wbc)
1735{
1736        struct f2fs_sb_info *sbi = F2FS_M_SB(mapping);
1737        struct blk_plug plug;
1738        long diff;
1739
1740        if (unlikely(is_sbi_flag_set(sbi, SBI_POR_DOING)))
1741                goto skip_write;
1742
1743        /* balancing f2fs's metadata in background */
1744        f2fs_balance_fs_bg(sbi);
1745
1746        /* collect a number of dirty node pages and write together */
1747        if (get_pages(sbi, F2FS_DIRTY_NODES) < nr_pages_to_skip(sbi, NODE))
1748                goto skip_write;
1749
1750        if (wbc->sync_mode == WB_SYNC_ALL)
1751                atomic_inc(&sbi->wb_sync_req[NODE]);
1752        else if (atomic_read(&sbi->wb_sync_req[NODE]))
1753                goto skip_write;
1754
1755        trace_f2fs_writepages(mapping->host, wbc, NODE);
1756
1757        diff = nr_pages_to_write(sbi, NODE, wbc);
1758        blk_start_plug(&plug);
1759        f2fs_sync_node_pages(sbi, wbc, true, FS_NODE_IO);
1760        blk_finish_plug(&plug);
1761        wbc->nr_to_write = max((long)0, wbc->nr_to_write - diff);
1762
1763        if (wbc->sync_mode == WB_SYNC_ALL)
1764                atomic_dec(&sbi->wb_sync_req[NODE]);
1765        return 0;
1766
1767skip_write:
1768        wbc->pages_skipped += get_pages(sbi, F2FS_DIRTY_NODES);
1769        trace_f2fs_writepages(mapping->host, wbc, NODE);
1770        return 0;
1771}
1772
1773static int f2fs_set_node_page_dirty(struct page *page)
1774{
1775        trace_f2fs_set_page_dirty(page, NODE);
1776
1777        if (!PageUptodate(page))
1778                SetPageUptodate(page);
1779        if (!PageDirty(page)) {
1780                __set_page_dirty_nobuffers(page);
1781                inc_page_count(F2FS_P_SB(page), F2FS_DIRTY_NODES);
1782                SetPagePrivate(page);
1783                f2fs_trace_pid(page);
1784                return 1;
1785        }
1786        return 0;
1787}
1788
1789/*
1790 * Structure of the f2fs node operations
1791 */
1792const struct address_space_operations f2fs_node_aops = {
1793        .writepage      = f2fs_write_node_page,
1794        .writepages     = f2fs_write_node_pages,
1795        .set_page_dirty = f2fs_set_node_page_dirty,
1796        .invalidatepage = f2fs_invalidate_page,
1797        .releasepage    = f2fs_release_page,
1798#ifdef CONFIG_MIGRATION
1799        .migratepage    = f2fs_migrate_page,
1800#endif
1801};
1802
1803static struct free_nid *__lookup_free_nid_list(struct f2fs_nm_info *nm_i,
1804                                                nid_t n)
1805{
1806        return radix_tree_lookup(&nm_i->free_nid_root, n);
1807}
1808
1809static int __insert_free_nid(struct f2fs_sb_info *sbi,
1810                        struct free_nid *i, enum nid_state state)
1811{
1812        struct f2fs_nm_info *nm_i = NM_I(sbi);
1813
1814        int err = radix_tree_insert(&nm_i->free_nid_root, i->nid, i);
1815        if (err)
1816                return err;
1817
1818        f2fs_bug_on(sbi, state != i->state);
1819        nm_i->nid_cnt[state]++;
1820        if (state == FREE_NID)
1821                list_add_tail(&i->list, &nm_i->free_nid_list);
1822        return 0;
1823}
1824
1825static void __remove_free_nid(struct f2fs_sb_info *sbi,
1826                        struct free_nid *i, enum nid_state state)
1827{
1828        struct f2fs_nm_info *nm_i = NM_I(sbi);
1829
1830        f2fs_bug_on(sbi, state != i->state);
1831        nm_i->nid_cnt[state]--;
1832        if (state == FREE_NID)
1833                list_del(&i->list);
1834        radix_tree_delete(&nm_i->free_nid_root, i->nid);
1835}
1836
1837static void __move_free_nid(struct f2fs_sb_info *sbi, struct free_nid *i,
1838                        enum nid_state org_state, enum nid_state dst_state)
1839{
1840        struct f2fs_nm_info *nm_i = NM_I(sbi);
1841
1842        f2fs_bug_on(sbi, org_state != i->state);
1843        i->state = dst_state;
1844        nm_i->nid_cnt[org_state]--;
1845        nm_i->nid_cnt[dst_state]++;
1846
1847        switch (dst_state) {
1848        case PREALLOC_NID:
1849                list_del(&i->list);
1850                break;
1851        case FREE_NID:
1852                list_add_tail(&i->list, &nm_i->free_nid_list);
1853                break;
1854        default:
1855                BUG_ON(1);
1856        }
1857}
1858
1859static void update_free_nid_bitmap(struct f2fs_sb_info *sbi, nid_t nid,
1860                                                        bool set, bool build)
1861{
1862        struct f2fs_nm_info *nm_i = NM_I(sbi);
1863        unsigned int nat_ofs = NAT_BLOCK_OFFSET(nid);
1864        unsigned int nid_ofs = nid - START_NID(nid);
1865
1866        if (!test_bit_le(nat_ofs, nm_i->nat_block_bitmap))
1867                return;
1868
1869        if (set) {
1870                if (test_bit_le(nid_ofs, nm_i->free_nid_bitmap[nat_ofs]))
1871                        return;
1872                __set_bit_le(nid_ofs, nm_i->free_nid_bitmap[nat_ofs]);
1873                nm_i->free_nid_count[nat_ofs]++;
1874        } else {
1875                if (!test_bit_le(nid_ofs, nm_i->free_nid_bitmap[nat_ofs]))
1876                        return;
1877                __clear_bit_le(nid_ofs, nm_i->free_nid_bitmap[nat_ofs]);
1878                if (!build)
1879                        nm_i->free_nid_count[nat_ofs]--;
1880        }
1881}
1882
1883/* return if the nid is recognized as free */
1884static bool add_free_nid(struct f2fs_sb_info *sbi,
1885                                nid_t nid, bool build, bool update)
1886{
1887        struct f2fs_nm_info *nm_i = NM_I(sbi);
1888        struct free_nid *i, *e;
1889        struct nat_entry *ne;
1890        int err = -EINVAL;
1891        bool ret = false;
1892
1893        /* 0 nid should not be used */
1894        if (unlikely(nid == 0))
1895                return false;
1896
1897        i = f2fs_kmem_cache_alloc(free_nid_slab, GFP_NOFS);
1898        i->nid = nid;
1899        i->state = FREE_NID;
1900
1901        radix_tree_preload(GFP_NOFS | __GFP_NOFAIL);
1902
1903        spin_lock(&nm_i->nid_list_lock);
1904
1905        if (build) {
1906                /*
1907                 *   Thread A             Thread B
1908                 *  - f2fs_create
1909                 *   - f2fs_new_inode
1910                 *    - f2fs_alloc_nid
1911                 *     - __insert_nid_to_list(PREALLOC_NID)
1912                 *                     - f2fs_balance_fs_bg
1913                 *                      - f2fs_build_free_nids
1914                 *                       - __f2fs_build_free_nids
1915                 *                        - scan_nat_page
1916                 *                         - add_free_nid
1917                 *                          - __lookup_nat_cache
1918                 *  - f2fs_add_link
1919                 *   - f2fs_init_inode_metadata
1920                 *    - f2fs_new_inode_page
1921                 *     - f2fs_new_node_page
1922                 *      - set_node_addr
1923                 *  - f2fs_alloc_nid_done
1924                 *   - __remove_nid_from_list(PREALLOC_NID)
1925                 *                         - __insert_nid_to_list(FREE_NID)
1926                 */
1927                ne = __lookup_nat_cache(nm_i, nid);
1928                if (ne && (!get_nat_flag(ne, IS_CHECKPOINTED) ||
1929                                nat_get_blkaddr(ne) != NULL_ADDR))
1930                        goto err_out;
1931
1932                e = __lookup_free_nid_list(nm_i, nid);
1933                if (e) {
1934                        if (e->state == FREE_NID)
1935                                ret = true;
1936                        goto err_out;
1937                }
1938        }
1939        ret = true;
1940        err = __insert_free_nid(sbi, i, FREE_NID);
1941err_out:
1942        if (update) {
1943                update_free_nid_bitmap(sbi, nid, ret, build);
1944                if (!build)
1945                        nm_i->available_nids++;
1946        }
1947        spin_unlock(&nm_i->nid_list_lock);
1948        radix_tree_preload_end();
1949
1950        if (err)
1951                kmem_cache_free(free_nid_slab, i);
1952        return ret;
1953}
1954
1955static void remove_free_nid(struct f2fs_sb_info *sbi, nid_t nid)
1956{
1957        struct f2fs_nm_info *nm_i = NM_I(sbi);
1958        struct free_nid *i;
1959        bool need_free = false;
1960
1961        spin_lock(&nm_i->nid_list_lock);
1962        i = __lookup_free_nid_list(nm_i, nid);
1963        if (i && i->state == FREE_NID) {
1964                __remove_free_nid(sbi, i, FREE_NID);
1965                need_free = true;
1966        }
1967        spin_unlock(&nm_i->nid_list_lock);
1968
1969        if (need_free)
1970                kmem_cache_free(free_nid_slab, i);
1971}
1972
1973static void scan_nat_page(struct f2fs_sb_info *sbi,
1974                        struct page *nat_page, nid_t start_nid)
1975{
1976        struct f2fs_nm_info *nm_i = NM_I(sbi);
1977        struct f2fs_nat_block *nat_blk = page_address(nat_page);
1978        block_t blk_addr;
1979        unsigned int nat_ofs = NAT_BLOCK_OFFSET(start_nid);
1980        int i;
1981
1982        __set_bit_le(nat_ofs, nm_i->nat_block_bitmap);
1983
1984        i = start_nid % NAT_ENTRY_PER_BLOCK;
1985
1986        for (; i < NAT_ENTRY_PER_BLOCK; i++, start_nid++) {
1987                if (unlikely(start_nid >= nm_i->max_nid))
1988                        break;
1989
1990                blk_addr = le32_to_cpu(nat_blk->entries[i].block_addr);
1991                f2fs_bug_on(sbi, blk_addr == NEW_ADDR);
1992                if (blk_addr == NULL_ADDR) {
1993                        add_free_nid(sbi, start_nid, true, true);
1994                } else {
1995                        spin_lock(&NM_I(sbi)->nid_list_lock);
1996                        update_free_nid_bitmap(sbi, start_nid, false, true);
1997                        spin_unlock(&NM_I(sbi)->nid_list_lock);
1998                }
1999        }
2000}
2001
2002static void scan_curseg_cache(struct f2fs_sb_info *sbi)
2003{
2004        struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_HOT_DATA);
2005        struct f2fs_journal *journal = curseg->journal;
2006        int i;
2007
2008        down_read(&curseg->journal_rwsem);
2009        for (i = 0; i < nats_in_cursum(journal); i++) {
2010                block_t addr;
2011                nid_t nid;
2012
2013                addr = le32_to_cpu(nat_in_journal(journal, i).block_addr);
2014                nid = le32_to_cpu(nid_in_journal(journal, i));
2015                if (addr == NULL_ADDR)
2016                        add_free_nid(sbi, nid, true, false);
2017                else
2018                        remove_free_nid(sbi, nid);
2019        }
2020        up_read(&curseg->journal_rwsem);
2021}
2022
2023static void scan_free_nid_bits(struct f2fs_sb_info *sbi)
2024{
2025        struct f2fs_nm_info *nm_i = NM_I(sbi);
2026        unsigned int i, idx;
2027        nid_t nid;
2028
2029        down_read(&nm_i->nat_tree_lock);
2030
2031        for (i = 0; i < nm_i->nat_blocks; i++) {
2032                if (!test_bit_le(i, nm_i->nat_block_bitmap))
2033                        continue;
2034                if (!nm_i->free_nid_count[i])
2035                        continue;
2036                for (idx = 0; idx < NAT_ENTRY_PER_BLOCK; idx++) {
2037                        idx = find_next_bit_le(nm_i->free_nid_bitmap[i],
2038                                                NAT_ENTRY_PER_BLOCK, idx);
2039                        if (idx >= NAT_ENTRY_PER_BLOCK)
2040                                break;
2041
2042                        nid = i * NAT_ENTRY_PER_BLOCK + idx;
2043                        add_free_nid(sbi, nid, true, false);
2044
2045                        if (nm_i->nid_cnt[FREE_NID] >= MAX_FREE_NIDS)
2046                                goto out;
2047                }
2048        }
2049out:
2050        scan_curseg_cache(sbi);
2051
2052        up_read(&nm_i->nat_tree_lock);
2053}
2054
2055static void __f2fs_build_free_nids(struct f2fs_sb_info *sbi,
2056                                                bool sync, bool mount)
2057{
2058        struct f2fs_nm_info *nm_i = NM_I(sbi);
2059        int i = 0;
2060        nid_t nid = nm_i->next_scan_nid;
2061
2062        if (unlikely(nid >= nm_i->max_nid))
2063                nid = 0;
2064
2065        /* Enough entries */
2066        if (nm_i->nid_cnt[FREE_NID] >= NAT_ENTRY_PER_BLOCK)
2067                return;
2068
2069        if (!sync && !f2fs_available_free_memory(sbi, FREE_NIDS))
2070                return;
2071
2072        if (!mount) {
2073                /* try to find free nids in free_nid_bitmap */
2074                scan_free_nid_bits(sbi);
2075
2076                if (nm_i->nid_cnt[FREE_NID] >= NAT_ENTRY_PER_BLOCK)
2077                        return;
2078        }
2079
2080        /* readahead nat pages to be scanned */
2081        f2fs_ra_meta_pages(sbi, NAT_BLOCK_OFFSET(nid), FREE_NID_PAGES,
2082                                                        META_NAT, true);
2083
2084        down_read(&nm_i->nat_tree_lock);
2085
2086        while (1) {
2087                if (!test_bit_le(NAT_BLOCK_OFFSET(nid),
2088                                                nm_i->nat_block_bitmap)) {
2089                        struct page *page = get_current_nat_page(sbi, nid);
2090
2091                        scan_nat_page(sbi, page, nid);
2092                        f2fs_put_page(page, 1);
2093                }
2094
2095                nid += (NAT_ENTRY_PER_BLOCK - (nid % NAT_ENTRY_PER_BLOCK));
2096                if (unlikely(nid >= nm_i->max_nid))
2097                        nid = 0;
2098
2099                if (++i >= FREE_NID_PAGES)
2100                        break;
2101        }
2102
2103        /* go to the next free nat pages to find free nids abundantly */
2104        nm_i->next_scan_nid = nid;
2105
2106        /* find free nids from current sum_pages */
2107        scan_curseg_cache(sbi);
2108
2109        up_read(&nm_i->nat_tree_lock);
2110
2111        f2fs_ra_meta_pages(sbi, NAT_BLOCK_OFFSET(nm_i->next_scan_nid),
2112                                        nm_i->ra_nid_pages, META_NAT, false);
2113}
2114
2115void f2fs_build_free_nids(struct f2fs_sb_info *sbi, bool sync, bool mount)
2116{
2117        mutex_lock(&NM_I(sbi)->build_lock);
2118        __f2fs_build_free_nids(sbi, sync, mount);
2119        mutex_unlock(&NM_I(sbi)->build_lock);
2120}
2121
2122/*
2123 * If this function returns success, caller can obtain a new nid
2124 * from second parameter of this function.
2125 * The returned nid could be used ino as well as nid when inode is created.
2126 */
2127bool f2fs_alloc_nid(struct f2fs_sb_info *sbi, nid_t *nid)
2128{
2129        struct f2fs_nm_info *nm_i = NM_I(sbi);
2130        struct free_nid *i = NULL;
2131retry:
2132#ifdef CONFIG_F2FS_FAULT_INJECTION
2133        if (time_to_inject(sbi, FAULT_ALLOC_NID)) {
2134                f2fs_show_injection_info(FAULT_ALLOC_NID);
2135                return false;
2136        }
2137#endif
2138        spin_lock(&nm_i->nid_list_lock);
2139
2140        if (unlikely(nm_i->available_nids == 0)) {
2141                spin_unlock(&nm_i->nid_list_lock);
2142                return false;
2143        }
2144
2145        /* We should not use stale free nids created by f2fs_build_free_nids */
2146        if (nm_i->nid_cnt[FREE_NID] && !on_f2fs_build_free_nids(nm_i)) {
2147                f2fs_bug_on(sbi, list_empty(&nm_i->free_nid_list));
2148                i = list_first_entry(&nm_i->free_nid_list,
2149                                        struct free_nid, list);
2150                *nid = i->nid;
2151
2152                __move_free_nid(sbi, i, FREE_NID, PREALLOC_NID);
2153                nm_i->available_nids--;
2154
2155                update_free_nid_bitmap(sbi, *nid, false, false);
2156
2157                spin_unlock(&nm_i->nid_list_lock);
2158                return true;
2159        }
2160        spin_unlock(&nm_i->nid_list_lock);
2161
2162        /* Let's scan nat pages and its caches to get free nids */
2163        f2fs_build_free_nids(sbi, true, false);
2164        goto retry;
2165}
2166
2167/*
2168 * f2fs_alloc_nid() should be called prior to this function.
2169 */
2170void f2fs_alloc_nid_done(struct f2fs_sb_info *sbi, nid_t nid)
2171{
2172        struct f2fs_nm_info *nm_i = NM_I(sbi);
2173        struct free_nid *i;
2174
2175        spin_lock(&nm_i->nid_list_lock);
2176        i = __lookup_free_nid_list(nm_i, nid);
2177        f2fs_bug_on(sbi, !i);
2178        __remove_free_nid(sbi, i, PREALLOC_NID);
2179        spin_unlock(&nm_i->nid_list_lock);
2180
2181        kmem_cache_free(free_nid_slab, i);
2182}
2183
2184/*
2185 * f2fs_alloc_nid() should be called prior to this function.
2186 */
2187void f2fs_alloc_nid_failed(struct f2fs_sb_info *sbi, nid_t nid)
2188{
2189        struct f2fs_nm_info *nm_i = NM_I(sbi);
2190        struct free_nid *i;
2191        bool need_free = false;
2192
2193        if (!nid)
2194                return;
2195
2196        spin_lock(&nm_i->nid_list_lock);
2197        i = __lookup_free_nid_list(nm_i, nid);
2198        f2fs_bug_on(sbi, !i);
2199
2200        if (!f2fs_available_free_memory(sbi, FREE_NIDS)) {
2201                __remove_free_nid(sbi, i, PREALLOC_NID);
2202                need_free = true;
2203        } else {
2204                __move_free_nid(sbi, i, PREALLOC_NID, FREE_NID);
2205        }
2206
2207        nm_i->available_nids++;
2208
2209        update_free_nid_bitmap(sbi, nid, true, false);
2210
2211        spin_unlock(&nm_i->nid_list_lock);
2212
2213        if (need_free)
2214                kmem_cache_free(free_nid_slab, i);
2215}
2216
2217int f2fs_try_to_free_nids(struct f2fs_sb_info *sbi, int nr_shrink)
2218{
2219        struct f2fs_nm_info *nm_i = NM_I(sbi);
2220        struct free_nid *i, *next;
2221        int nr = nr_shrink;
2222
2223        if (nm_i->nid_cnt[FREE_NID] <= MAX_FREE_NIDS)
2224                return 0;
2225
2226        if (!mutex_trylock(&nm_i->build_lock))
2227                return 0;
2228
2229        spin_lock(&nm_i->nid_list_lock);
2230        list_for_each_entry_safe(i, next, &nm_i->free_nid_list, list) {
2231                if (nr_shrink <= 0 ||
2232                                nm_i->nid_cnt[FREE_NID] <= MAX_FREE_NIDS)
2233                        break;
2234
2235                __remove_free_nid(sbi, i, FREE_NID);
2236                kmem_cache_free(free_nid_slab, i);
2237                nr_shrink--;
2238        }
2239        spin_unlock(&nm_i->nid_list_lock);
2240        mutex_unlock(&nm_i->build_lock);
2241
2242        return nr - nr_shrink;
2243}
2244
2245void f2fs_recover_inline_xattr(struct inode *inode, struct page *page)
2246{
2247        void *src_addr, *dst_addr;
2248        size_t inline_size;
2249        struct page *ipage;
2250        struct f2fs_inode *ri;
2251
2252        ipage = f2fs_get_node_page(F2FS_I_SB(inode), inode->i_ino);
2253        f2fs_bug_on(F2FS_I_SB(inode), IS_ERR(ipage));
2254
2255        ri = F2FS_INODE(page);
2256        if (ri->i_inline & F2FS_INLINE_XATTR) {
2257                set_inode_flag(inode, FI_INLINE_XATTR);
2258        } else {
2259                clear_inode_flag(inode, FI_INLINE_XATTR);
2260                goto update_inode;
2261        }
2262
2263        dst_addr = inline_xattr_addr(inode, ipage);
2264        src_addr = inline_xattr_addr(inode, page);
2265        inline_size = inline_xattr_size(inode);
2266
2267        f2fs_wait_on_page_writeback(ipage, NODE, true);
2268        memcpy(dst_addr, src_addr, inline_size);
2269update_inode:
2270        f2fs_update_inode(inode, ipage);
2271        f2fs_put_page(ipage, 1);
2272}
2273
2274int f2fs_recover_xattr_data(struct inode *inode, struct page *page)
2275{
2276        struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
2277        nid_t prev_xnid = F2FS_I(inode)->i_xattr_nid;
2278        nid_t new_xnid;
2279        struct dnode_of_data dn;
2280        struct node_info ni;
2281        struct page *xpage;
2282
2283        if (!prev_xnid)
2284                goto recover_xnid;
2285
2286        /* 1: invalidate the previous xattr nid */
2287        f2fs_get_node_info(sbi, prev_xnid, &ni);
2288        f2fs_invalidate_blocks(sbi, ni.blk_addr);
2289        dec_valid_node_count(sbi, inode, false);
2290        set_node_addr(sbi, &ni, NULL_ADDR, false);
2291
2292recover_xnid:
2293        /* 2: update xattr nid in inode */
2294        if (!f2fs_alloc_nid(sbi, &new_xnid))
2295                return -ENOSPC;
2296
2297        set_new_dnode(&dn, inode, NULL, NULL, new_xnid);
2298        xpage = f2fs_new_node_page(&dn, XATTR_NODE_OFFSET);
2299        if (IS_ERR(xpage)) {
2300                f2fs_alloc_nid_failed(sbi, new_xnid);
2301                return PTR_ERR(xpage);
2302        }
2303
2304        f2fs_alloc_nid_done(sbi, new_xnid);
2305        f2fs_update_inode_page(inode);
2306
2307        /* 3: update and set xattr node page dirty */
2308        memcpy(F2FS_NODE(xpage), F2FS_NODE(page), VALID_XATTR_BLOCK_SIZE);
2309
2310        set_page_dirty(xpage);
2311        f2fs_put_page(xpage, 1);
2312
2313        return 0;
2314}
2315
2316int f2fs_recover_inode_page(struct f2fs_sb_info *sbi, struct page *page)
2317{
2318        struct f2fs_inode *src, *dst;
2319        nid_t ino = ino_of_node(page);
2320        struct node_info old_ni, new_ni;
2321        struct page *ipage;
2322
2323        f2fs_get_node_info(sbi, ino, &old_ni);
2324
2325        if (unlikely(old_ni.blk_addr != NULL_ADDR))
2326                return -EINVAL;
2327retry:
2328        ipage = f2fs_grab_cache_page(NODE_MAPPING(sbi), ino, false);
2329        if (!ipage) {
2330                congestion_wait(BLK_RW_ASYNC, HZ/50);
2331                goto retry;
2332        }
2333
2334        /* Should not use this inode from free nid list */
2335        remove_free_nid(sbi, ino);
2336
2337        if (!PageUptodate(ipage))
2338                SetPageUptodate(ipage);
2339        fill_node_footer(ipage, ino, ino, 0, true);
2340        set_cold_node(page, false);
2341
2342        src = F2FS_INODE(page);
2343        dst = F2FS_INODE(ipage);
2344
2345        memcpy(dst, src, (unsigned long)&src->i_ext - (unsigned long)src);
2346        dst->i_size = 0;
2347        dst->i_blocks = cpu_to_le64(1);
2348        dst->i_links = cpu_to_le32(1);
2349        dst->i_xattr_nid = 0;
2350        dst->i_inline = src->i_inline & (F2FS_INLINE_XATTR | F2FS_EXTRA_ATTR);
2351        if (dst->i_inline & F2FS_EXTRA_ATTR) {
2352                dst->i_extra_isize = src->i_extra_isize;
2353
2354                if (f2fs_sb_has_flexible_inline_xattr(sbi->sb) &&
2355                        F2FS_FITS_IN_INODE(src, le16_to_cpu(src->i_extra_isize),
2356                                                        i_inline_xattr_size))
2357                        dst->i_inline_xattr_size = src->i_inline_xattr_size;
2358
2359                if (f2fs_sb_has_project_quota(sbi->sb) &&
2360                        F2FS_FITS_IN_INODE(src, le16_to_cpu(src->i_extra_isize),
2361                                                                i_projid))
2362                        dst->i_projid = src->i_projid;
2363        }
2364
2365        new_ni = old_ni;
2366        new_ni.ino = ino;
2367
2368        if (unlikely(inc_valid_node_count(sbi, NULL, true)))
2369                WARN_ON(1);
2370        set_node_addr(sbi, &new_ni, NEW_ADDR, false);
2371        inc_valid_inode_count(sbi);
2372        set_page_dirty(ipage);
2373        f2fs_put_page(ipage, 1);
2374        return 0;
2375}
2376
2377void f2fs_restore_node_summary(struct f2fs_sb_info *sbi,
2378                        unsigned int segno, struct f2fs_summary_block *sum)
2379{
2380        struct f2fs_node *rn;
2381        struct f2fs_summary *sum_entry;
2382        block_t addr;
2383        int i, idx, last_offset, nrpages;
2384
2385        /* scan the node segment */
2386        last_offset = sbi->blocks_per_seg;
2387        addr = START_BLOCK(sbi, segno);
2388        sum_entry = &sum->entries[0];
2389
2390        for (i = 0; i < last_offset; i += nrpages, addr += nrpages) {
2391                nrpages = min(last_offset - i, BIO_MAX_PAGES);
2392
2393                /* readahead node pages */
2394                f2fs_ra_meta_pages(sbi, addr, nrpages, META_POR, true);
2395
2396                for (idx = addr; idx < addr + nrpages; idx++) {
2397                        struct page *page = f2fs_get_tmp_page(sbi, idx);
2398
2399                        rn = F2FS_NODE(page);
2400                        sum_entry->nid = rn->footer.nid;
2401                        sum_entry->version = 0;
2402                        sum_entry->ofs_in_node = 0;
2403                        sum_entry++;
2404                        f2fs_put_page(page, 1);
2405                }
2406
2407                invalidate_mapping_pages(META_MAPPING(sbi), addr,
2408                                                        addr + nrpages);
2409        }
2410}
2411
2412static void remove_nats_in_journal(struct f2fs_sb_info *sbi)
2413{
2414        struct f2fs_nm_info *nm_i = NM_I(sbi);
2415        struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_HOT_DATA);
2416        struct f2fs_journal *journal = curseg->journal;
2417        int i;
2418
2419        down_write(&curseg->journal_rwsem);
2420        for (i = 0; i < nats_in_cursum(journal); i++) {
2421                struct nat_entry *ne;
2422                struct f2fs_nat_entry raw_ne;
2423                nid_t nid = le32_to_cpu(nid_in_journal(journal, i));
2424
2425                raw_ne = nat_in_journal(journal, i);
2426
2427                ne = __lookup_nat_cache(nm_i, nid);
2428                if (!ne) {
2429                        ne = __alloc_nat_entry(nid, true);
2430                        __init_nat_entry(nm_i, ne, &raw_ne, true);
2431                }
2432
2433                /*
2434                 * if a free nat in journal has not been used after last
2435                 * checkpoint, we should remove it from available nids,
2436                 * since later we will add it again.
2437                 */
2438                if (!get_nat_flag(ne, IS_DIRTY) &&
2439                                le32_to_cpu(raw_ne.block_addr) == NULL_ADDR) {
2440                        spin_lock(&nm_i->nid_list_lock);
2441                        nm_i->available_nids--;
2442                        spin_unlock(&nm_i->nid_list_lock);
2443                }
2444
2445                __set_nat_cache_dirty(nm_i, ne);
2446        }
2447        update_nats_in_cursum(journal, -i);
2448        up_write(&curseg->journal_rwsem);
2449}
2450
2451static void __adjust_nat_entry_set(struct nat_entry_set *nes,
2452                                                struct list_head *head, int max)
2453{
2454        struct nat_entry_set *cur;
2455
2456        if (nes->entry_cnt >= max)
2457                goto add_out;
2458
2459        list_for_each_entry(cur, head, set_list) {
2460                if (cur->entry_cnt >= nes->entry_cnt) {
2461                        list_add(&nes->set_list, cur->set_list.prev);
2462                        return;
2463                }
2464        }
2465add_out:
2466        list_add_tail(&nes->set_list, head);
2467}
2468
2469static void __update_nat_bits(struct f2fs_sb_info *sbi, nid_t start_nid,
2470                                                struct page *page)
2471{
2472        struct f2fs_nm_info *nm_i = NM_I(sbi);
2473        unsigned int nat_index = start_nid / NAT_ENTRY_PER_BLOCK;
2474        struct f2fs_nat_block *nat_blk = page_address(page);
2475        int valid = 0;
2476        int i = 0;
2477
2478        if (!enabled_nat_bits(sbi, NULL))
2479                return;
2480
2481        if (nat_index == 0) {
2482                valid = 1;
2483                i = 1;
2484        }
2485        for (; i < NAT_ENTRY_PER_BLOCK; i++) {
2486                if (nat_blk->entries[i].block_addr != NULL_ADDR)
2487                        valid++;
2488        }
2489        if (valid == 0) {
2490                __set_bit_le(nat_index, nm_i->empty_nat_bits);
2491                __clear_bit_le(nat_index, nm_i->full_nat_bits);
2492                return;
2493        }
2494
2495        __clear_bit_le(nat_index, nm_i->empty_nat_bits);
2496        if (valid == NAT_ENTRY_PER_BLOCK)
2497                __set_bit_le(nat_index, nm_i->full_nat_bits);
2498        else
2499                __clear_bit_le(nat_index, nm_i->full_nat_bits);
2500}
2501
2502static void __flush_nat_entry_set(struct f2fs_sb_info *sbi,
2503                struct nat_entry_set *set, struct cp_control *cpc)
2504{
2505        struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_HOT_DATA);
2506        struct f2fs_journal *journal = curseg->journal;
2507        nid_t start_nid = set->set * NAT_ENTRY_PER_BLOCK;
2508        bool to_journal = true;
2509        struct f2fs_nat_block *nat_blk;
2510        struct nat_entry *ne, *cur;
2511        struct page *page = NULL;
2512
2513        /*
2514         * there are two steps to flush nat entries:
2515         * #1, flush nat entries to journal in current hot data summary block.
2516         * #2, flush nat entries to nat page.
2517         */
2518        if (enabled_nat_bits(sbi, cpc) ||
2519                !__has_cursum_space(journal, set->entry_cnt, NAT_JOURNAL))
2520                to_journal = false;
2521
2522        if (to_journal) {
2523                down_write(&curseg->journal_rwsem);
2524        } else {
2525                page = get_next_nat_page(sbi, start_nid);
2526                nat_blk = page_address(page);
2527                f2fs_bug_on(sbi, !nat_blk);
2528        }
2529
2530        /* flush dirty nats in nat entry set */
2531        list_for_each_entry_safe(ne, cur, &set->entry_list, list) {
2532                struct f2fs_nat_entry *raw_ne;
2533                nid_t nid = nat_get_nid(ne);
2534                int offset;
2535
2536                f2fs_bug_on(sbi, nat_get_blkaddr(ne) == NEW_ADDR);
2537
2538                if (to_journal) {
2539                        offset = f2fs_lookup_journal_in_cursum(journal,
2540                                                        NAT_JOURNAL, nid, 1);
2541                        f2fs_bug_on(sbi, offset < 0);
2542                        raw_ne = &nat_in_journal(journal, offset);
2543                        nid_in_journal(journal, offset) = cpu_to_le32(nid);
2544                } else {
2545                        raw_ne = &nat_blk->entries[nid - start_nid];
2546                }
2547                raw_nat_from_node_info(raw_ne, &ne->ni);
2548                nat_reset_flag(ne);
2549                __clear_nat_cache_dirty(NM_I(sbi), set, ne);
2550                if (nat_get_blkaddr(ne) == NULL_ADDR) {
2551                        add_free_nid(sbi, nid, false, true);
2552                } else {
2553                        spin_lock(&NM_I(sbi)->nid_list_lock);
2554                        update_free_nid_bitmap(sbi, nid, false, false);
2555                        spin_unlock(&NM_I(sbi)->nid_list_lock);
2556                }
2557        }
2558
2559        if (to_journal) {
2560                up_write(&curseg->journal_rwsem);
2561        } else {
2562                __update_nat_bits(sbi, start_nid, page);
2563                f2fs_put_page(page, 1);
2564        }
2565
2566        /* Allow dirty nats by node block allocation in write_begin */
2567        if (!set->entry_cnt) {
2568                radix_tree_delete(&NM_I(sbi)->nat_set_root, set->set);
2569                kmem_cache_free(nat_entry_set_slab, set);
2570        }
2571}
2572
2573/*
2574 * This function is called during the checkpointing process.
2575 */
2576void f2fs_flush_nat_entries(struct f2fs_sb_info *sbi, struct cp_control *cpc)
2577{
2578        struct f2fs_nm_info *nm_i = NM_I(sbi);
2579        struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_HOT_DATA);
2580        struct f2fs_journal *journal = curseg->journal;
2581        struct nat_entry_set *setvec[SETVEC_SIZE];
2582        struct nat_entry_set *set, *tmp;
2583        unsigned int found;
2584        nid_t set_idx = 0;
2585        LIST_HEAD(sets);
2586
2587        if (!nm_i->dirty_nat_cnt)
2588                return;
2589
2590        down_write(&nm_i->nat_tree_lock);
2591
2592        /*
2593         * if there are no enough space in journal to store dirty nat
2594         * entries, remove all entries from journal and merge them
2595         * into nat entry set.
2596         */
2597        if (enabled_nat_bits(sbi, cpc) ||
2598                !__has_cursum_space(journal, nm_i->dirty_nat_cnt, NAT_JOURNAL))
2599                remove_nats_in_journal(sbi);
2600
2601        while ((found = __gang_lookup_nat_set(nm_i,
2602                                        set_idx, SETVEC_SIZE, setvec))) {
2603                unsigned idx;
2604                set_idx = setvec[found - 1]->set + 1;
2605                for (idx = 0; idx < found; idx++)
2606                        __adjust_nat_entry_set(setvec[idx], &sets,
2607                                                MAX_NAT_JENTRIES(journal));
2608        }
2609
2610        /* flush dirty nats in nat entry set */
2611        list_for_each_entry_safe(set, tmp, &sets, set_list)
2612                __flush_nat_entry_set(sbi, set, cpc);
2613
2614        up_write(&nm_i->nat_tree_lock);
2615        /* Allow dirty nats by node block allocation in write_begin */
2616}
2617
2618static int __get_nat_bitmaps(struct f2fs_sb_info *sbi)
2619{
2620        struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
2621        struct f2fs_nm_info *nm_i = NM_I(sbi);
2622        unsigned int nat_bits_bytes = nm_i->nat_blocks / BITS_PER_BYTE;
2623        unsigned int i;
2624        __u64 cp_ver = cur_cp_version(ckpt);
2625        block_t nat_bits_addr;
2626
2627        if (!enabled_nat_bits(sbi, NULL))
2628                return 0;
2629
2630        nm_i->nat_bits_blocks = F2FS_BLK_ALIGN((nat_bits_bytes << 1) + 8);
2631        nm_i->nat_bits = f2fs_kzalloc(sbi,
2632                        nm_i->nat_bits_blocks << F2FS_BLKSIZE_BITS, GFP_KERNEL);
2633        if (!nm_i->nat_bits)
2634                return -ENOMEM;
2635
2636        nat_bits_addr = __start_cp_addr(sbi) + sbi->blocks_per_seg -
2637                                                nm_i->nat_bits_blocks;
2638        for (i = 0; i < nm_i->nat_bits_blocks; i++) {
2639                struct page *page = f2fs_get_meta_page(sbi, nat_bits_addr++);
2640
2641                memcpy(nm_i->nat_bits + (i << F2FS_BLKSIZE_BITS),
2642                                        page_address(page), F2FS_BLKSIZE);
2643                f2fs_put_page(page, 1);
2644        }
2645
2646        cp_ver |= (cur_cp_crc(ckpt) << 32);
2647        if (cpu_to_le64(cp_ver) != *(__le64 *)nm_i->nat_bits) {
2648                disable_nat_bits(sbi, true);
2649                return 0;
2650        }
2651
2652        nm_i->full_nat_bits = nm_i->nat_bits + 8;
2653        nm_i->empty_nat_bits = nm_i->full_nat_bits + nat_bits_bytes;
2654
2655        f2fs_msg(sbi->sb, KERN_NOTICE, "Found nat_bits in checkpoint");
2656        return 0;
2657}
2658
2659static inline void load_free_nid_bitmap(struct f2fs_sb_info *sbi)
2660{
2661        struct f2fs_nm_info *nm_i = NM_I(sbi);
2662        unsigned int i = 0;
2663        nid_t nid, last_nid;
2664
2665        if (!enabled_nat_bits(sbi, NULL))
2666                return;
2667
2668        for (i = 0; i < nm_i->nat_blocks; i++) {
2669                i = find_next_bit_le(nm_i->empty_nat_bits, nm_i->nat_blocks, i);
2670                if (i >= nm_i->nat_blocks)
2671                        break;
2672
2673                __set_bit_le(i, nm_i->nat_block_bitmap);
2674
2675                nid = i * NAT_ENTRY_PER_BLOCK;
2676                last_nid = nid + NAT_ENTRY_PER_BLOCK;
2677
2678                spin_lock(&NM_I(sbi)->nid_list_lock);
2679                for (; nid < last_nid; nid++)
2680                        update_free_nid_bitmap(sbi, nid, true, true);
2681                spin_unlock(&NM_I(sbi)->nid_list_lock);
2682        }
2683
2684        for (i = 0; i < nm_i->nat_blocks; i++) {
2685                i = find_next_bit_le(nm_i->full_nat_bits, nm_i->nat_blocks, i);
2686                if (i >= nm_i->nat_blocks)
2687                        break;
2688
2689                __set_bit_le(i, nm_i->nat_block_bitmap);
2690        }
2691}
2692
2693static int init_node_manager(struct f2fs_sb_info *sbi)
2694{
2695        struct f2fs_super_block *sb_raw = F2FS_RAW_SUPER(sbi);
2696        struct f2fs_nm_info *nm_i = NM_I(sbi);
2697        unsigned char *version_bitmap;
2698        unsigned int nat_segs;
2699        int err;
2700
2701        nm_i->nat_blkaddr = le32_to_cpu(sb_raw->nat_blkaddr);
2702
2703        /* segment_count_nat includes pair segment so divide to 2. */
2704        nat_segs = le32_to_cpu(sb_raw->segment_count_nat) >> 1;
2705        nm_i->nat_blocks = nat_segs << le32_to_cpu(sb_raw->log_blocks_per_seg);
2706        nm_i->max_nid = NAT_ENTRY_PER_BLOCK * nm_i->nat_blocks;
2707
2708        /* not used nids: 0, node, meta, (and root counted as valid node) */
2709        nm_i->available_nids = nm_i->max_nid - sbi->total_valid_node_count -
2710                                sbi->nquota_files - F2FS_RESERVED_NODE_NUM;
2711        nm_i->nid_cnt[FREE_NID] = 0;
2712        nm_i->nid_cnt[PREALLOC_NID] = 0;
2713        nm_i->nat_cnt = 0;
2714        nm_i->ram_thresh = DEF_RAM_THRESHOLD;
2715        nm_i->ra_nid_pages = DEF_RA_NID_PAGES;
2716        nm_i->dirty_nats_ratio = DEF_DIRTY_NAT_RATIO_THRESHOLD;
2717
2718        INIT_RADIX_TREE(&nm_i->free_nid_root, GFP_ATOMIC);
2719        INIT_LIST_HEAD(&nm_i->free_nid_list);
2720        INIT_RADIX_TREE(&nm_i->nat_root, GFP_NOIO);
2721        INIT_RADIX_TREE(&nm_i->nat_set_root, GFP_NOIO);
2722        INIT_LIST_HEAD(&nm_i->nat_entries);
2723
2724        mutex_init(&nm_i->build_lock);
2725        spin_lock_init(&nm_i->nid_list_lock);
2726        init_rwsem(&nm_i->nat_tree_lock);
2727
2728        nm_i->next_scan_nid = le32_to_cpu(sbi->ckpt->next_free_nid);
2729        nm_i->bitmap_size = __bitmap_size(sbi, NAT_BITMAP);
2730        version_bitmap = __bitmap_ptr(sbi, NAT_BITMAP);
2731        if (!version_bitmap)
2732                return -EFAULT;
2733
2734        nm_i->nat_bitmap = kmemdup(version_bitmap, nm_i->bitmap_size,
2735                                        GFP_KERNEL);
2736        if (!nm_i->nat_bitmap)
2737                return -ENOMEM;
2738
2739        err = __get_nat_bitmaps(sbi);
2740        if (err)
2741                return err;
2742
2743#ifdef CONFIG_F2FS_CHECK_FS
2744        nm_i->nat_bitmap_mir = kmemdup(version_bitmap, nm_i->bitmap_size,
2745                                        GFP_KERNEL);
2746        if (!nm_i->nat_bitmap_mir)
2747                return -ENOMEM;
2748#endif
2749
2750        return 0;
2751}
2752
2753static int init_free_nid_cache(struct f2fs_sb_info *sbi)
2754{
2755        struct f2fs_nm_info *nm_i = NM_I(sbi);
2756        int i;
2757
2758        nm_i->free_nid_bitmap =
2759                f2fs_kzalloc(sbi, array_size(sizeof(unsigned char *),
2760                                             nm_i->nat_blocks),
2761                             GFP_KERNEL);
2762        if (!nm_i->free_nid_bitmap)
2763                return -ENOMEM;
2764
2765        for (i = 0; i < nm_i->nat_blocks; i++) {
2766                nm_i->free_nid_bitmap[i] = f2fs_kvzalloc(sbi,
2767                                NAT_ENTRY_BITMAP_SIZE_ALIGNED, GFP_KERNEL);
2768                if (!nm_i->free_nid_bitmap)
2769                        return -ENOMEM;
2770        }
2771
2772        nm_i->nat_block_bitmap = f2fs_kvzalloc(sbi, nm_i->nat_blocks / 8,
2773                                                                GFP_KERNEL);
2774        if (!nm_i->nat_block_bitmap)
2775                return -ENOMEM;
2776
2777        nm_i->free_nid_count =
2778                f2fs_kvzalloc(sbi, array_size(sizeof(unsigned short),
2779                                              nm_i->nat_blocks),
2780                              GFP_KERNEL);
2781        if (!nm_i->free_nid_count)
2782                return -ENOMEM;
2783        return 0;
2784}
2785
2786int f2fs_build_node_manager(struct f2fs_sb_info *sbi)
2787{
2788        int err;
2789
2790        sbi->nm_info = f2fs_kzalloc(sbi, sizeof(struct f2fs_nm_info),
2791                                                        GFP_KERNEL);
2792        if (!sbi->nm_info)
2793                return -ENOMEM;
2794
2795        err = init_node_manager(sbi);
2796        if (err)
2797                return err;
2798
2799        err = init_free_nid_cache(sbi);
2800        if (err)
2801                return err;
2802
2803        /* load free nid status from nat_bits table */
2804        load_free_nid_bitmap(sbi);
2805
2806        f2fs_build_free_nids(sbi, true, true);
2807        return 0;
2808}
2809
2810void f2fs_destroy_node_manager(struct f2fs_sb_info *sbi)
2811{
2812        struct f2fs_nm_info *nm_i = NM_I(sbi);
2813        struct free_nid *i, *next_i;
2814        struct nat_entry *natvec[NATVEC_SIZE];
2815        struct nat_entry_set *setvec[SETVEC_SIZE];
2816        nid_t nid = 0;
2817        unsigned int found;
2818
2819        if (!nm_i)
2820                return;
2821
2822        /* destroy free nid list */
2823        spin_lock(&nm_i->nid_list_lock);
2824        list_for_each_entry_safe(i, next_i, &nm_i->free_nid_list, list) {
2825                __remove_free_nid(sbi, i, FREE_NID);
2826                spin_unlock(&nm_i->nid_list_lock);
2827                kmem_cache_free(free_nid_slab, i);
2828                spin_lock(&nm_i->nid_list_lock);
2829        }
2830        f2fs_bug_on(sbi, nm_i->nid_cnt[FREE_NID]);
2831        f2fs_bug_on(sbi, nm_i->nid_cnt[PREALLOC_NID]);
2832        f2fs_bug_on(sbi, !list_empty(&nm_i->free_nid_list));
2833        spin_unlock(&nm_i->nid_list_lock);
2834
2835        /* destroy nat cache */
2836        down_write(&nm_i->nat_tree_lock);
2837        while ((found = __gang_lookup_nat_cache(nm_i,
2838                                        nid, NATVEC_SIZE, natvec))) {
2839                unsigned idx;
2840
2841                nid = nat_get_nid(natvec[found - 1]) + 1;
2842                for (idx = 0; idx < found; idx++)
2843                        __del_from_nat_cache(nm_i, natvec[idx]);
2844        }
2845        f2fs_bug_on(sbi, nm_i->nat_cnt);
2846
2847        /* destroy nat set cache */
2848        nid = 0;
2849        while ((found = __gang_lookup_nat_set(nm_i,
2850                                        nid, SETVEC_SIZE, setvec))) {
2851                unsigned idx;
2852
2853                nid = setvec[found - 1]->set + 1;
2854                for (idx = 0; idx < found; idx++) {
2855                        /* entry_cnt is not zero, when cp_error was occurred */
2856                        f2fs_bug_on(sbi, !list_empty(&setvec[idx]->entry_list));
2857                        radix_tree_delete(&nm_i->nat_set_root, setvec[idx]->set);
2858                        kmem_cache_free(nat_entry_set_slab, setvec[idx]);
2859                }
2860        }
2861        up_write(&nm_i->nat_tree_lock);
2862
2863        kvfree(nm_i->nat_block_bitmap);
2864        if (nm_i->free_nid_bitmap) {
2865                int i;
2866
2867                for (i = 0; i < nm_i->nat_blocks; i++)
2868                        kvfree(nm_i->free_nid_bitmap[i]);
2869                kfree(nm_i->free_nid_bitmap);
2870        }
2871        kvfree(nm_i->free_nid_count);
2872
2873        kfree(nm_i->nat_bitmap);
2874        kfree(nm_i->nat_bits);
2875#ifdef CONFIG_F2FS_CHECK_FS
2876        kfree(nm_i->nat_bitmap_mir);
2877#endif
2878        sbi->nm_info = NULL;
2879        kfree(nm_i);
2880}
2881
2882int __init f2fs_create_node_manager_caches(void)
2883{
2884        nat_entry_slab = f2fs_kmem_cache_create("nat_entry",
2885                        sizeof(struct nat_entry));
2886        if (!nat_entry_slab)
2887                goto fail;
2888
2889        free_nid_slab = f2fs_kmem_cache_create("free_nid",
2890                        sizeof(struct free_nid));
2891        if (!free_nid_slab)
2892                goto destroy_nat_entry;
2893
2894        nat_entry_set_slab = f2fs_kmem_cache_create("nat_entry_set",
2895                        sizeof(struct nat_entry_set));
2896        if (!nat_entry_set_slab)
2897                goto destroy_free_nid;
2898        return 0;
2899
2900destroy_free_nid:
2901        kmem_cache_destroy(free_nid_slab);
2902destroy_nat_entry:
2903        kmem_cache_destroy(nat_entry_slab);
2904fail:
2905        return -ENOMEM;
2906}
2907
2908void f2fs_destroy_node_manager_caches(void)
2909{
2910        kmem_cache_destroy(nat_entry_set_slab);
2911        kmem_cache_destroy(free_nid_slab);
2912        kmem_cache_destroy(nat_entry_slab);
2913}
2914