linux/fs/nfs/dir.c
<<
>>
Prefs
   1/*
   2 *  linux/fs/nfs/dir.c
   3 *
   4 *  Copyright (C) 1992  Rick Sladkey
   5 *
   6 *  nfs directory handling functions
   7 *
   8 * 10 Apr 1996  Added silly rename for unlink   --okir
   9 * 28 Sep 1996  Improved directory cache --okir
  10 * 23 Aug 1997  Claus Heine claus@momo.math.rwth-aachen.de 
  11 *              Re-implemented silly rename for unlink, newly implemented
  12 *              silly rename for nfs_rename() following the suggestions
  13 *              of Olaf Kirch (okir) found in this file.
  14 *              Following Linus comments on my original hack, this version
  15 *              depends only on the dcache stuff and doesn't touch the inode
  16 *              layer (iput() and friends).
  17 *  6 Jun 1999  Cache readdir lookups in the page cache. -DaveM
  18 */
  19
  20#include <linux/module.h>
  21#include <linux/time.h>
  22#include <linux/errno.h>
  23#include <linux/stat.h>
  24#include <linux/fcntl.h>
  25#include <linux/string.h>
  26#include <linux/kernel.h>
  27#include <linux/slab.h>
  28#include <linux/mm.h>
  29#include <linux/sunrpc/clnt.h>
  30#include <linux/nfs_fs.h>
  31#include <linux/nfs_mount.h>
  32#include <linux/pagemap.h>
  33#include <linux/pagevec.h>
  34#include <linux/namei.h>
  35#include <linux/mount.h>
  36#include <linux/swap.h>
  37#include <linux/sched.h>
  38#include <linux/kmemleak.h>
  39#include <linux/xattr.h>
  40
  41#include "delegation.h"
  42#include "iostat.h"
  43#include "internal.h"
  44#include "fscache.h"
  45
  46#include "nfstrace.h"
  47
  48/* #define NFS_DEBUG_VERBOSE 1 */
  49
  50static int nfs_opendir(struct inode *, struct file *);
  51static int nfs_closedir(struct inode *, struct file *);
  52static int nfs_readdir(struct file *, void *, filldir_t);
  53static int nfs_fsync_dir(struct file *, loff_t, loff_t, int);
  54static loff_t nfs_llseek_dir(struct file *, loff_t, int);
  55static void nfs_readdir_clear_array(struct page*);
  56
  57const struct file_operations nfs_dir_operations = {
  58        .llseek         = nfs_llseek_dir,
  59        .read           = generic_read_dir,
  60        .readdir        = nfs_readdir,
  61        .open           = nfs_opendir,
  62        .release        = nfs_closedir,
  63        .fsync          = nfs_fsync_dir,
  64};
  65
  66const struct address_space_operations nfs_dir_aops = {
  67        .freepage = nfs_readdir_clear_array,
  68};
  69
  70static struct nfs_open_dir_context *alloc_nfs_open_dir_context(struct inode *dir, struct rpc_cred *cred)
  71{
  72        struct nfs_inode *nfsi = NFS_I(dir);
  73        struct nfs_open_dir_context *ctx;
  74        ctx = kmalloc(sizeof(*ctx), GFP_KERNEL);
  75        if (ctx != NULL) {
  76                ctx->duped = 0;
  77                ctx->attr_gencount = nfsi->attr_gencount;
  78                ctx->dir_cookie = 0;
  79                ctx->dup_cookie = 0;
  80                ctx->cred = get_rpccred(cred);
  81                spin_lock(&dir->i_lock);
  82                list_add(&ctx->list, &nfsi->open_files);
  83                spin_unlock(&dir->i_lock);
  84                return ctx;
  85        }
  86        return  ERR_PTR(-ENOMEM);
  87}
  88
  89static void put_nfs_open_dir_context(struct inode *dir, struct nfs_open_dir_context *ctx)
  90{
  91        spin_lock(&dir->i_lock);
  92        list_del(&ctx->list);
  93        spin_unlock(&dir->i_lock);
  94        put_rpccred(ctx->cred);
  95        kfree(ctx);
  96}
  97
  98/*
  99 * Open file
 100 */
 101static int
 102nfs_opendir(struct inode *inode, struct file *filp)
 103{
 104        int res = 0;
 105        struct nfs_open_dir_context *ctx;
 106        struct rpc_cred *cred;
 107
 108        dfprintk(FILE, "NFS: open dir(%pD2)\n", filp);
 109
 110        nfs_inc_stats(inode, NFSIOS_VFSOPEN);
 111
 112        cred = rpc_lookup_cred();
 113        if (IS_ERR(cred))
 114                return PTR_ERR(cred);
 115        ctx = alloc_nfs_open_dir_context(inode, cred);
 116        if (IS_ERR(ctx)) {
 117                res = PTR_ERR(ctx);
 118                goto out;
 119        }
 120        filp->private_data = ctx;
 121        if (filp->f_path.dentry == filp->f_path.mnt->mnt_root) {
 122                /* This is a mountpoint, so d_revalidate will never
 123                 * have been called, so we need to refresh the
 124                 * inode (for close-open consistency) ourselves.
 125                 */
 126                __nfs_revalidate_inode(NFS_SERVER(inode), inode);
 127        }
 128out:
 129        put_rpccred(cred);
 130        return res;
 131}
 132
 133static int
 134nfs_closedir(struct inode *inode, struct file *filp)
 135{
 136        put_nfs_open_dir_context(filp->f_path.dentry->d_inode, filp->private_data);
 137        return 0;
 138}
 139
 140struct nfs_cache_array_entry {
 141        u64 cookie;
 142        u64 ino;
 143        struct qstr string;
 144        unsigned char d_type;
 145};
 146
 147struct nfs_cache_array {
 148        int size;
 149        int eof_index;
 150        u64 last_cookie;
 151        struct nfs_cache_array_entry array[0];
 152};
 153
 154typedef int (*decode_dirent_t)(struct xdr_stream *, struct nfs_entry *, int);
 155typedef struct {
 156        struct file     *file;
 157        struct page     *page;
 158        unsigned long   page_index;
 159        u64             *dir_cookie;
 160        u64             last_cookie;
 161        loff_t          current_index;
 162        decode_dirent_t decode;
 163
 164        unsigned long   timestamp;
 165        unsigned long   gencount;
 166        unsigned int    cache_entry_index;
 167        unsigned int    plus:1;
 168        unsigned int    eof:1;
 169} nfs_readdir_descriptor_t;
 170
 171/*
 172 * The caller is responsible for calling nfs_readdir_release_array(page)
 173 */
 174static
 175struct nfs_cache_array *nfs_readdir_get_array(struct page *page)
 176{
 177        void *ptr;
 178        if (page == NULL)
 179                return ERR_PTR(-EIO);
 180        ptr = kmap(page);
 181        if (ptr == NULL)
 182                return ERR_PTR(-ENOMEM);
 183        return ptr;
 184}
 185
 186static
 187void nfs_readdir_release_array(struct page *page)
 188{
 189        kunmap(page);
 190}
 191
 192/*
 193 * we are freeing strings created by nfs_add_to_readdir_array()
 194 */
 195static
 196void nfs_readdir_clear_array(struct page *page)
 197{
 198        struct nfs_cache_array *array;
 199        int i;
 200
 201        array = kmap_atomic(page);
 202        for (i = 0; i < array->size; i++)
 203                kfree(array->array[i].string.name);
 204        kunmap_atomic(array);
 205}
 206
 207/*
 208 * the caller is responsible for freeing qstr.name
 209 * when called by nfs_readdir_add_to_array, the strings will be freed in
 210 * nfs_clear_readdir_array()
 211 */
 212static
 213int nfs_readdir_make_qstr(struct qstr *string, const char *name, unsigned int len)
 214{
 215        string->len = len;
 216        string->name = kmemdup(name, len, GFP_KERNEL);
 217        if (string->name == NULL)
 218                return -ENOMEM;
 219        /*
 220         * Avoid a kmemleak false positive. The pointer to the name is stored
 221         * in a page cache page which kmemleak does not scan.
 222         */
 223        kmemleak_not_leak(string->name);
 224        string->hash = full_name_hash(name, len);
 225        return 0;
 226}
 227
 228static
 229int nfs_readdir_add_to_array(struct nfs_entry *entry, struct page *page)
 230{
 231        struct nfs_cache_array *array = nfs_readdir_get_array(page);
 232        struct nfs_cache_array_entry *cache_entry;
 233        int ret;
 234
 235        if (IS_ERR(array))
 236                return PTR_ERR(array);
 237
 238        cache_entry = &array->array[array->size];
 239
 240        /* Check that this entry lies within the page bounds */
 241        ret = -ENOSPC;
 242        if ((char *)&cache_entry[1] - (char *)page_address(page) > PAGE_SIZE)
 243                goto out;
 244
 245        cache_entry->cookie = entry->prev_cookie;
 246        cache_entry->ino = entry->ino;
 247        cache_entry->d_type = entry->d_type;
 248        ret = nfs_readdir_make_qstr(&cache_entry->string, entry->name, entry->len);
 249        if (ret)
 250                goto out;
 251        array->last_cookie = entry->cookie;
 252        array->size++;
 253        if (entry->eof != 0)
 254                array->eof_index = array->size;
 255out:
 256        nfs_readdir_release_array(page);
 257        return ret;
 258}
 259
 260static
 261int nfs_readdir_search_for_pos(struct nfs_cache_array *array, nfs_readdir_descriptor_t *desc)
 262{
 263        loff_t diff = desc->file->f_pos - desc->current_index;
 264        unsigned int index;
 265
 266        if (diff < 0)
 267                goto out_eof;
 268        if (diff >= array->size) {
 269                if (array->eof_index >= 0)
 270                        goto out_eof;
 271                return -EAGAIN;
 272        }
 273
 274        index = (unsigned int)diff;
 275        *desc->dir_cookie = array->array[index].cookie;
 276        desc->cache_entry_index = index;
 277        return 0;
 278out_eof:
 279        desc->eof = 1;
 280        return -EBADCOOKIE;
 281}
 282
 283static bool
 284nfs_readdir_inode_mapping_valid(struct nfs_inode *nfsi)
 285{
 286        if (nfsi->cache_validity & (NFS_INO_INVALID_ATTR|NFS_INO_INVALID_DATA))
 287                return false;
 288        smp_rmb();
 289        return !test_bit(NFS_INO_INVALIDATING, &nfsi->flags);
 290}
 291
 292static
 293int nfs_readdir_search_for_cookie(struct nfs_cache_array *array, nfs_readdir_descriptor_t *desc)
 294{
 295        int i;
 296        loff_t new_pos;
 297        int status = -EAGAIN;
 298
 299        for (i = 0; i < array->size; i++) {
 300                if (array->array[i].cookie == *desc->dir_cookie) {
 301                        struct nfs_inode *nfsi = NFS_I(file_inode(desc->file));
 302                        struct nfs_open_dir_context *ctx = desc->file->private_data;
 303
 304                        new_pos = desc->current_index + i;
 305                        if (ctx->attr_gencount != nfsi->attr_gencount ||
 306                            !nfs_readdir_inode_mapping_valid(nfsi)) {
 307                                ctx->duped = 0;
 308                                ctx->attr_gencount = nfsi->attr_gencount;
 309                        } else if (new_pos < desc->file->f_pos) {
 310                                if (ctx->duped > 0
 311                                    && ctx->dup_cookie == *desc->dir_cookie) {
 312                                        if (printk_ratelimit()) {
 313                                                pr_notice("NFS: directory %pD2 contains a readdir loop."
 314                                                                "Please contact your server vendor.  "
 315                                                                "The file: %.*s has duplicate cookie %llu\n",
 316                                                                desc->file, array->array[i].string.len,
 317                                                                array->array[i].string.name, *desc->dir_cookie);
 318                                        }
 319                                        status = -ELOOP;
 320                                        goto out;
 321                                }
 322                                ctx->dup_cookie = *desc->dir_cookie;
 323                                ctx->duped = -1;
 324                        }
 325                        desc->file->f_pos = new_pos;
 326                        desc->cache_entry_index = i;
 327                        return 0;
 328                }
 329        }
 330        if (array->eof_index >= 0) {
 331                status = -EBADCOOKIE;
 332                if (*desc->dir_cookie == array->last_cookie)
 333                        desc->eof = 1;
 334        }
 335out:
 336        return status;
 337}
 338
 339static
 340int nfs_readdir_search_array(nfs_readdir_descriptor_t *desc)
 341{
 342        struct nfs_cache_array *array;
 343        int status;
 344
 345        array = nfs_readdir_get_array(desc->page);
 346        if (IS_ERR(array)) {
 347                status = PTR_ERR(array);
 348                goto out;
 349        }
 350
 351        if (*desc->dir_cookie == 0)
 352                status = nfs_readdir_search_for_pos(array, desc);
 353        else
 354                status = nfs_readdir_search_for_cookie(array, desc);
 355
 356        if (status == -EAGAIN) {
 357                desc->last_cookie = array->last_cookie;
 358                desc->current_index += array->size;
 359                desc->page_index++;
 360        }
 361        nfs_readdir_release_array(desc->page);
 362out:
 363        return status;
 364}
 365
 366/* Fill a page with xdr information before transferring to the cache page */
 367static
 368int nfs_readdir_xdr_filler(struct page **pages, nfs_readdir_descriptor_t *desc,
 369                        struct nfs_entry *entry, struct file *file, struct inode *inode)
 370{
 371        struct nfs_open_dir_context *ctx = file->private_data;
 372        struct rpc_cred *cred = ctx->cred;
 373        unsigned long   timestamp, gencount;
 374        int             error;
 375
 376 again:
 377        timestamp = jiffies;
 378        gencount = nfs_inc_attr_generation_counter();
 379        error = NFS_PROTO(inode)->readdir(file_dentry(file), cred, entry->cookie, pages,
 380                                          NFS_SERVER(inode)->dtsize, desc->plus);
 381        if (error < 0) {
 382                /* We requested READDIRPLUS, but the server doesn't grok it */
 383                if (error == -ENOTSUPP && desc->plus) {
 384                        NFS_SERVER(inode)->caps &= ~NFS_CAP_READDIRPLUS;
 385                        clear_bit(NFS_INO_ADVISE_RDPLUS, &NFS_I(inode)->flags);
 386                        desc->plus = 0;
 387                        goto again;
 388                }
 389                goto error;
 390        }
 391        desc->timestamp = timestamp;
 392        desc->gencount = gencount;
 393error:
 394        return error;
 395}
 396
 397static int xdr_decode(nfs_readdir_descriptor_t *desc,
 398                      struct nfs_entry *entry, struct xdr_stream *xdr)
 399{
 400        int error;
 401
 402        error = desc->decode(xdr, entry, desc->plus);
 403        if (error)
 404                return error;
 405        entry->fattr->time_start = desc->timestamp;
 406        entry->fattr->gencount = desc->gencount;
 407        return 0;
 408}
 409
 410/* Match file and dirent using either filehandle or fileid
 411 * Note: caller is responsible for checking the fsid
 412 */
 413static
 414int nfs_same_file(struct dentry *dentry, struct nfs_entry *entry)
 415{
 416        struct inode *inode;
 417        struct nfs_inode *nfsi;
 418
 419        if (dentry->d_inode == NULL)
 420                return 0;
 421
 422        inode = dentry->d_inode;
 423        if (is_bad_inode(inode) || NFS_STALE(inode))
 424                return 0;
 425
 426        nfsi = NFS_I(inode);
 427        if (entry->fattr->fileid != nfsi->fileid)
 428                return 0;
 429        if (entry->fh->size && nfs_compare_fh(entry->fh, &nfsi->fh) != 0)
 430                return 0;
 431        return 1;
 432}
 433
 434static
 435bool nfs_use_readdirplus(struct inode *dir, struct file *filp)
 436{
 437        if (!nfs_server_capable(dir, NFS_CAP_READDIRPLUS))
 438                return false;
 439        if (test_and_clear_bit(NFS_INO_ADVISE_RDPLUS, &NFS_I(dir)->flags))
 440                return true;
 441        if (filp->f_pos == 0)
 442                return true;
 443        return false;
 444}
 445
 446/*
 447 * This function is called by the lookup and getattr code to request the
 448 * use of readdirplus to accelerate any future lookups in the same
 449 * directory.
 450 */
 451void nfs_advise_use_readdirplus(struct inode *dir)
 452{
 453        struct nfs_inode *nfsi = NFS_I(dir);
 454
 455        if (nfs_server_capable(dir, NFS_CAP_READDIRPLUS) &&
 456            !list_empty(&nfsi->open_files))
 457                set_bit(NFS_INO_ADVISE_RDPLUS, &nfsi->flags);
 458}
 459
 460/*
 461 * This function is mainly for use by nfs_getattr().
 462 *
 463 * If this is an 'ls -l', we want to force use of readdirplus.
 464 * Do this by checking if there is an active file descriptor
 465 * and calling nfs_advise_use_readdirplus, then forcing a
 466 * cache flush.
 467 */
 468void nfs_force_use_readdirplus(struct inode *dir)
 469{
 470        struct nfs_inode *nfsi = NFS_I(dir);
 471
 472        if (nfs_server_capable(dir, NFS_CAP_READDIRPLUS) &&
 473            !list_empty(&nfsi->open_files)) {
 474                set_bit(NFS_INO_ADVISE_RDPLUS, &nfsi->flags);
 475                invalidate_mapping_pages(dir->i_mapping, 0, -1);
 476        }
 477}
 478
 479static
 480void nfs_prime_dcache(struct dentry *parent, struct nfs_entry *entry)
 481{
 482        struct qstr filename = QSTR_INIT(entry->name, entry->len);
 483        struct dentry *dentry;
 484        struct dentry *alias;
 485        struct inode *dir = parent->d_inode;
 486        struct inode *inode;
 487        int status;
 488
 489        if (!(entry->fattr->valid & NFS_ATTR_FATTR_FILEID))
 490                return;
 491        if (!(entry->fattr->valid & NFS_ATTR_FATTR_FSID))
 492                return;
 493        if (filename.len == 0)
 494                return;
 495        /* Validate that the name doesn't contain any illegal '\0' */
 496        if (strnlen(filename.name, filename.len) != filename.len)
 497                return;
 498        /* ...or '/' */
 499        if (strnchr(filename.name, filename.len, '/'))
 500                return;
 501        if (filename.name[0] == '.') {
 502                if (filename.len == 1)
 503                        return;
 504                if (filename.len == 2 && filename.name[1] == '.')
 505                        return;
 506        }
 507        filename.hash = full_name_hash(filename.name, filename.len);
 508
 509        dentry = d_lookup(parent, &filename);
 510        if (dentry != NULL) {
 511                /* Is there a mountpoint here? If so, just exit */
 512                if (!nfs_fsid_equal(&NFS_SB(dentry->d_sb)->fsid,
 513                                        &entry->fattr->fsid))
 514                        goto out;
 515                if (nfs_same_file(dentry, entry)) {
 516                        if (!entry->fh->size)
 517                                goto out;
 518                        nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
 519                        status = nfs_refresh_inode(dentry->d_inode, entry->fattr);
 520                        if (!status)
 521                                nfs_setsecurity(dentry->d_inode, entry->fattr, entry->label);
 522                        goto out;
 523                } else {
 524                        if (d_invalidate(dentry) != 0)
 525                                goto out;
 526                        dput(dentry);
 527                }
 528        }
 529        if (!entry->fh->size)
 530                goto out;
 531
 532        dentry = d_alloc(parent, &filename);
 533        if (dentry == NULL)
 534                return;
 535
 536        inode = nfs_fhget(dentry->d_sb, entry->fh, entry->fattr, entry->label);
 537        if (IS_ERR(inode))
 538                goto out;
 539
 540        alias = d_materialise_unique(dentry, inode);
 541        if (IS_ERR(alias))
 542                goto out;
 543        else if (alias) {
 544                nfs_set_verifier(alias, nfs_save_change_attribute(dir));
 545                dput(alias);
 546        } else
 547                nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
 548
 549out:
 550        dput(dentry);
 551}
 552
 553/* Perform conversion from xdr to cache array */
 554static
 555int nfs_readdir_page_filler(nfs_readdir_descriptor_t *desc, struct nfs_entry *entry,
 556                                struct page **xdr_pages, struct page *page, unsigned int buflen)
 557{
 558        struct xdr_stream stream;
 559        struct xdr_buf buf;
 560        struct page *scratch;
 561        struct nfs_cache_array *array;
 562        unsigned int count = 0;
 563        int status;
 564
 565        scratch = alloc_page(GFP_KERNEL);
 566        if (scratch == NULL)
 567                return -ENOMEM;
 568
 569        if (buflen == 0)
 570                goto out_nopages;
 571
 572        xdr_init_decode_pages(&stream, &buf, xdr_pages, buflen);
 573        xdr_set_scratch_buffer(&stream, page_address(scratch), PAGE_SIZE);
 574
 575        do {
 576                status = xdr_decode(desc, entry, &stream);
 577                if (status != 0) {
 578                        if (status == -EAGAIN)
 579                                status = 0;
 580                        break;
 581                }
 582
 583                count++;
 584
 585                if (desc->plus != 0)
 586                        nfs_prime_dcache(file_dentry(desc->file), entry);
 587
 588                status = nfs_readdir_add_to_array(entry, page);
 589                if (status != 0)
 590                        break;
 591        } while (!entry->eof);
 592
 593out_nopages:
 594        if (count == 0 || (status == -EBADCOOKIE && entry->eof != 0)) {
 595                array = nfs_readdir_get_array(page);
 596                if (!IS_ERR(array)) {
 597                        array->eof_index = array->size;
 598                        status = 0;
 599                        nfs_readdir_release_array(page);
 600                } else
 601                        status = PTR_ERR(array);
 602        }
 603
 604        put_page(scratch);
 605        return status;
 606}
 607
 608static
 609void nfs_readdir_free_pages(struct page **pages, unsigned int npages)
 610{
 611        unsigned int i;
 612        for (i = 0; i < npages; i++)
 613                put_page(pages[i]);
 614}
 615
 616/*
 617 * nfs_readdir_large_page will allocate pages that must be freed with a call
 618 * to nfs_readdir_free_pagearray
 619 */
 620static
 621int nfs_readdir_alloc_pages(struct page **pages, unsigned int npages)
 622{
 623        unsigned int i;
 624
 625        for (i = 0; i < npages; i++) {
 626                struct page *page = alloc_page(GFP_KERNEL);
 627                if (page == NULL)
 628                        goto out_freepages;
 629                pages[i] = page;
 630        }
 631        return 0;
 632
 633out_freepages:
 634        nfs_readdir_free_pages(pages, i);
 635        return -ENOMEM;
 636}
 637
 638static
 639int nfs_readdir_xdr_to_array(nfs_readdir_descriptor_t *desc, struct page *page, struct inode *inode)
 640{
 641        struct page *pages[NFS_MAX_READDIR_PAGES];
 642        struct nfs_entry entry;
 643        struct file     *file = desc->file;
 644        struct nfs_cache_array *array;
 645        int status = -ENOMEM;
 646        unsigned int array_size = ARRAY_SIZE(pages);
 647
 648        entry.prev_cookie = 0;
 649        entry.cookie = desc->last_cookie;
 650        entry.eof = 0;
 651        entry.fh = nfs_alloc_fhandle();
 652        entry.fattr = nfs_alloc_fattr();
 653        entry.server = NFS_SERVER(inode);
 654        if (entry.fh == NULL || entry.fattr == NULL)
 655                goto out;
 656
 657        entry.label = nfs4_label_alloc(NFS_SERVER(inode), GFP_NOWAIT);
 658        if (IS_ERR(entry.label)) {
 659                status = PTR_ERR(entry.label);
 660                goto out;
 661        }
 662
 663        array = nfs_readdir_get_array(page);
 664        if (IS_ERR(array)) {
 665                status = PTR_ERR(array);
 666                goto out_label_free;
 667        }
 668        memset(array, 0, sizeof(struct nfs_cache_array));
 669        array->eof_index = -1;
 670
 671        status = nfs_readdir_alloc_pages(pages, array_size);
 672        if (status < 0)
 673                goto out_release_array;
 674        do {
 675                unsigned int pglen;
 676                status = nfs_readdir_xdr_filler(pages, desc, &entry, file, inode);
 677
 678                if (status < 0)
 679                        break;
 680                pglen = status;
 681                status = nfs_readdir_page_filler(desc, &entry, pages, page, pglen);
 682                if (status < 0) {
 683                        if (status == -ENOSPC)
 684                                status = 0;
 685                        break;
 686                }
 687        } while (array->eof_index < 0);
 688
 689        nfs_readdir_free_pages(pages, array_size);
 690out_release_array:
 691        nfs_readdir_release_array(page);
 692out_label_free:
 693        nfs4_label_free(entry.label);
 694out:
 695        nfs_free_fattr(entry.fattr);
 696        nfs_free_fhandle(entry.fh);
 697        return status;
 698}
 699
 700/*
 701 * Now we cache directories properly, by converting xdr information
 702 * to an array that can be used for lookups later.  This results in
 703 * fewer cache pages, since we can store more information on each page.
 704 * We only need to convert from xdr once so future lookups are much simpler
 705 */
 706static
 707int nfs_readdir_filler(nfs_readdir_descriptor_t *desc, struct page* page)
 708{
 709        struct inode    *inode = file_inode(desc->file);
 710        int ret;
 711
 712        ret = nfs_readdir_xdr_to_array(desc, page, inode);
 713        if (ret < 0)
 714                goto error;
 715        SetPageUptodate(page);
 716
 717        if (invalidate_inode_pages2_range(inode->i_mapping, page->index + 1, -1) < 0) {
 718                /* Should never happen */
 719                nfs_zap_mapping(inode, inode->i_mapping);
 720        }
 721        unlock_page(page);
 722        return 0;
 723 error:
 724        unlock_page(page);
 725        return ret;
 726}
 727
 728static
 729void cache_page_release(nfs_readdir_descriptor_t *desc)
 730{
 731        if (!desc->page->mapping)
 732                nfs_readdir_clear_array(desc->page);
 733        page_cache_release(desc->page);
 734        desc->page = NULL;
 735}
 736
 737static
 738struct page *get_cache_page(nfs_readdir_descriptor_t *desc)
 739{
 740        return read_cache_page(file_inode(desc->file)->i_mapping,
 741                        desc->page_index, (filler_t *)nfs_readdir_filler, desc);
 742}
 743
 744/*
 745 * Returns 0 if desc->dir_cookie was found on page desc->page_index
 746 */
 747static
 748int find_cache_page(nfs_readdir_descriptor_t *desc)
 749{
 750        int res;
 751
 752        desc->page = get_cache_page(desc);
 753        if (IS_ERR(desc->page))
 754                return PTR_ERR(desc->page);
 755
 756        res = nfs_readdir_search_array(desc);
 757        if (res != 0)
 758                cache_page_release(desc);
 759        return res;
 760}
 761
 762/* Search for desc->dir_cookie from the beginning of the page cache */
 763static inline
 764int readdir_search_pagecache(nfs_readdir_descriptor_t *desc)
 765{
 766        int res;
 767
 768        if (desc->page_index == 0) {
 769                desc->current_index = 0;
 770                desc->last_cookie = 0;
 771        }
 772        do {
 773                res = find_cache_page(desc);
 774        } while (res == -EAGAIN);
 775        return res;
 776}
 777
 778/*
 779 * Once we've found the start of the dirent within a page: fill 'er up...
 780 */
 781static 
 782int nfs_do_filldir(nfs_readdir_descriptor_t *desc, void *dirent,
 783                   filldir_t filldir)
 784{
 785        struct file     *file = desc->file;
 786        int i = 0;
 787        int res = 0;
 788        struct nfs_cache_array *array = NULL;
 789        struct nfs_open_dir_context *ctx = file->private_data;
 790
 791        array = nfs_readdir_get_array(desc->page);
 792        if (IS_ERR(array)) {
 793                res = PTR_ERR(array);
 794                goto out;
 795        }
 796
 797        for (i = desc->cache_entry_index; i < array->size; i++) {
 798                struct nfs_cache_array_entry *ent;
 799
 800                ent = &array->array[i];
 801                if (filldir(dirent, ent->string.name, ent->string.len,
 802                    file->f_pos, nfs_compat_user_ino64(ent->ino),
 803                    ent->d_type) < 0) {
 804                        desc->eof = 1;
 805                        break;
 806                }
 807                file->f_pos++;
 808                if (i < (array->size-1))
 809                        *desc->dir_cookie = array->array[i+1].cookie;
 810                else
 811                        *desc->dir_cookie = array->last_cookie;
 812                if (ctx->duped != 0)
 813                        ctx->duped = 1;
 814        }
 815        if (array->eof_index >= 0)
 816                desc->eof = 1;
 817
 818        nfs_readdir_release_array(desc->page);
 819out:
 820        cache_page_release(desc);
 821        dfprintk(DIRCACHE, "NFS: nfs_do_filldir() filling ended @ cookie %Lu; returning = %d\n",
 822                        (unsigned long long)*desc->dir_cookie, res);
 823        return res;
 824}
 825
 826/*
 827 * If we cannot find a cookie in our cache, we suspect that this is
 828 * because it points to a deleted file, so we ask the server to return
 829 * whatever it thinks is the next entry. We then feed this to filldir.
 830 * If all goes well, we should then be able to find our way round the
 831 * cache on the next call to readdir_search_pagecache();
 832 *
 833 * NOTE: we cannot add the anonymous page to the pagecache because
 834 *       the data it contains might not be page aligned. Besides,
 835 *       we should already have a complete representation of the
 836 *       directory in the page cache by the time we get here.
 837 */
 838static inline
 839int uncached_readdir(nfs_readdir_descriptor_t *desc, void *dirent,
 840                     filldir_t filldir)
 841{
 842        struct page     *page = NULL;
 843        int             status;
 844        struct inode *inode = file_inode(desc->file);
 845        struct nfs_open_dir_context *ctx = desc->file->private_data;
 846
 847        dfprintk(DIRCACHE, "NFS: uncached_readdir() searching for cookie %Lu\n",
 848                        (unsigned long long)*desc->dir_cookie);
 849
 850        page = alloc_page(GFP_HIGHUSER);
 851        if (!page) {
 852                status = -ENOMEM;
 853                goto out;
 854        }
 855
 856        desc->page_index = 0;
 857        desc->last_cookie = *desc->dir_cookie;
 858        desc->page = page;
 859        ctx->duped = 0;
 860
 861        status = nfs_readdir_xdr_to_array(desc, page, inode);
 862        if (status < 0)
 863                goto out_release;
 864
 865        status = nfs_do_filldir(desc, dirent, filldir);
 866
 867 out:
 868        dfprintk(DIRCACHE, "NFS: %s: returns %d\n",
 869                        __func__, status);
 870        return status;
 871 out_release:
 872        cache_page_release(desc);
 873        goto out;
 874}
 875
 876/* The file offset position represents the dirent entry number.  A
 877   last cookie cache takes care of the common case of reading the
 878   whole directory.
 879 */
 880static int nfs_readdir(struct file *filp, void *dirent, filldir_t filldir)
 881{
 882        struct dentry   *dentry = file_dentry(filp);
 883        struct inode    *inode = dentry->d_inode;
 884        nfs_readdir_descriptor_t my_desc,
 885                        *desc = &my_desc;
 886        struct nfs_open_dir_context *dir_ctx = filp->private_data;
 887        int res = 0;
 888
 889        dfprintk(FILE, "NFS: readdir(%pD2) starting at cookie %llu\n",
 890                        filp, (long long)filp->f_pos);
 891        nfs_inc_stats(inode, NFSIOS_VFSGETDENTS);
 892
 893        /*
 894         * filp->f_pos points to the dirent entry number.
 895         * *desc->dir_cookie has the cookie for the next entry. We have
 896         * to either find the entry with the appropriate number or
 897         * revalidate the cookie.
 898         */
 899        memset(desc, 0, sizeof(*desc));
 900
 901        desc->file = filp;
 902        desc->dir_cookie = &dir_ctx->dir_cookie;
 903        desc->decode = NFS_PROTO(inode)->decode_dirent;
 904        desc->plus = nfs_use_readdirplus(inode, filp) ? 1 : 0;
 905
 906        nfs_block_sillyrename(dentry);
 907        if (filp->f_pos == 0 || nfs_attribute_cache_expired(inode))
 908                res = nfs_revalidate_mapping(inode, filp->f_mapping);
 909        if (res < 0)
 910                goto out;
 911
 912        do {
 913                res = readdir_search_pagecache(desc);
 914
 915                if (res == -EBADCOOKIE) {
 916                        res = 0;
 917                        /* This means either end of directory */
 918                        if (*desc->dir_cookie && desc->eof == 0) {
 919                                /* Or that the server has 'lost' a cookie */
 920                                res = uncached_readdir(desc, dirent, filldir);
 921                                if (res == 0)
 922                                        continue;
 923                        }
 924                        break;
 925                }
 926                if (res == -ETOOSMALL && desc->plus) {
 927                        clear_bit(NFS_INO_ADVISE_RDPLUS, &NFS_I(inode)->flags);
 928                        nfs_zap_caches(inode);
 929                        desc->page_index = 0;
 930                        desc->plus = 0;
 931                        desc->eof = 0;
 932                        continue;
 933                }
 934                if (res < 0)
 935                        break;
 936
 937                res = nfs_do_filldir(desc, dirent, filldir);
 938                if (res < 0)
 939                        break;
 940        } while (!desc->eof);
 941out:
 942        nfs_unblock_sillyrename(dentry);
 943        if (res > 0)
 944                res = 0;
 945        dfprintk(FILE, "NFS: readdir(%pD2) returns %d\n", filp, res);
 946        return res;
 947}
 948
 949static loff_t nfs_llseek_dir(struct file *filp, loff_t offset, int whence)
 950{
 951        struct inode *inode = file_inode(filp);
 952        struct nfs_open_dir_context *dir_ctx = filp->private_data;
 953
 954        dfprintk(FILE, "NFS: llseek dir(%pD2, %lld, %d)\n",
 955                        filp, offset, whence);
 956
 957        mutex_lock(&inode->i_mutex);
 958        switch (whence) {
 959                case 1:
 960                        offset += filp->f_pos;
 961                case 0:
 962                        if (offset >= 0)
 963                                break;
 964                default:
 965                        offset = -EINVAL;
 966                        goto out;
 967        }
 968        if (offset != filp->f_pos) {
 969                filp->f_pos = offset;
 970                dir_ctx->dir_cookie = 0;
 971                dir_ctx->duped = 0;
 972        }
 973out:
 974        mutex_unlock(&inode->i_mutex);
 975        return offset;
 976}
 977
 978/*
 979 * All directory operations under NFS are synchronous, so fsync()
 980 * is a dummy operation.
 981 */
 982static int nfs_fsync_dir(struct file *filp, loff_t start, loff_t end,
 983                         int datasync)
 984{
 985        struct inode *inode = file_inode(filp);
 986
 987        dfprintk(FILE, "NFS: fsync dir(%pD2) datasync %d\n", filp, datasync);
 988
 989        mutex_lock(&inode->i_mutex);
 990        nfs_inc_stats(inode, NFSIOS_VFSFSYNC);
 991        mutex_unlock(&inode->i_mutex);
 992        return 0;
 993}
 994
 995/**
 996 * nfs_force_lookup_revalidate - Mark the directory as having changed
 997 * @dir - pointer to directory inode
 998 *
 999 * This forces the revalidation code in nfs_lookup_revalidate() to do a
1000 * full lookup on all child dentries of 'dir' whenever a change occurs
1001 * on the server that might have invalidated our dcache.
1002 *
1003 * The caller should be holding dir->i_lock
1004 */
1005void nfs_force_lookup_revalidate(struct inode *dir)
1006{
1007        NFS_I(dir)->cache_change_attribute++;
1008}
1009EXPORT_SYMBOL_GPL(nfs_force_lookup_revalidate);
1010
1011/*
1012 * A check for whether or not the parent directory has changed.
1013 * In the case it has, we assume that the dentries are untrustworthy
1014 * and may need to be looked up again.
1015 * If rcu_walk prevents us from performing a full check, return 0.
1016 */
1017static int nfs_check_verifier(struct inode *dir, struct dentry *dentry,
1018                              int rcu_walk)
1019{
1020        int ret;
1021
1022        if (IS_ROOT(dentry))
1023                return 1;
1024        if (NFS_SERVER(dir)->flags & NFS_MOUNT_LOOKUP_CACHE_NONE)
1025                return 0;
1026        if (!nfs_verify_change_attribute(dir, dentry->d_time))
1027                return 0;
1028        /* Revalidate nfsi->cache_change_attribute before we declare a match */
1029        if (rcu_walk)
1030                ret = nfs_revalidate_inode_rcu(NFS_SERVER(dir), dir);
1031        else
1032                ret = nfs_revalidate_inode(NFS_SERVER(dir), dir);
1033        if (ret < 0)
1034                return 0;
1035        if (!nfs_verify_change_attribute(dir, dentry->d_time))
1036                return 0;
1037        return 1;
1038}
1039
1040/*
1041 * Use intent information to check whether or not we're going to do
1042 * an O_EXCL create using this path component.
1043 */
1044static int nfs_is_exclusive_create(struct inode *dir, unsigned int flags)
1045{
1046        if (NFS_PROTO(dir)->version == 2)
1047                return 0;
1048        return flags & LOOKUP_EXCL;
1049}
1050
1051/*
1052 * Inode and filehandle revalidation for lookups.
1053 *
1054 * We force revalidation in the cases where the VFS sets LOOKUP_REVAL,
1055 * or if the intent information indicates that we're about to open this
1056 * particular file and the "nocto" mount flag is not set.
1057 *
1058 */
1059static
1060int nfs_lookup_verify_inode(struct inode *inode, unsigned int flags)
1061{
1062        struct nfs_server *server = NFS_SERVER(inode);
1063        int ret;
1064
1065        if (IS_AUTOMOUNT(inode))
1066                return 0;
1067        /* VFS wants an on-the-wire revalidation */
1068        if (flags & LOOKUP_REVAL)
1069                goto out_force;
1070        /* This is an open(2) */
1071        if ((flags & LOOKUP_OPEN) && !(server->flags & NFS_MOUNT_NOCTO) &&
1072            (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode)))
1073                goto out_force;
1074out:
1075        return (inode->i_nlink == 0) ? -ENOENT : 0;
1076out_force:
1077        if (flags & LOOKUP_RCU)
1078                return -ECHILD;
1079        ret = __nfs_revalidate_inode(server, inode);
1080        if (ret != 0)
1081                return ret;
1082        goto out;
1083}
1084
1085/*
1086 * We judge how long we want to trust negative
1087 * dentries by looking at the parent inode mtime.
1088 *
1089 * If parent mtime has changed, we revalidate, else we wait for a
1090 * period corresponding to the parent's attribute cache timeout value.
1091 *
1092 * If LOOKUP_RCU prevents us from performing a full check, return 1
1093 * suggesting a reval is needed.
1094 */
1095static inline
1096int nfs_neg_need_reval(struct inode *dir, struct dentry *dentry,
1097                       unsigned int flags)
1098{
1099        /* Don't revalidate a negative dentry if we're creating a new file */
1100        if (flags & LOOKUP_CREATE)
1101                return 0;
1102        if (NFS_SERVER(dir)->flags & NFS_MOUNT_LOOKUP_CACHE_NONEG)
1103                return 1;
1104        return !nfs_check_verifier(dir, dentry, flags & LOOKUP_RCU);
1105}
1106
1107/*
1108 * This is called every time the dcache has a lookup hit,
1109 * and we should check whether we can really trust that
1110 * lookup.
1111 *
1112 * NOTE! The hit can be a negative hit too, don't assume
1113 * we have an inode!
1114 *
1115 * If the parent directory is seen to have changed, we throw out the
1116 * cached dentry and do a new lookup.
1117 */
1118static int nfs_lookup_revalidate(struct dentry *dentry, unsigned int flags)
1119{
1120        struct inode *dir;
1121        struct inode *inode;
1122        struct dentry *parent;
1123        struct nfs_fh *fhandle = NULL;
1124        struct nfs_fattr *fattr = NULL;
1125        struct nfs4_label *label = NULL;
1126        int error;
1127
1128        if (flags & LOOKUP_RCU) {
1129                parent = ACCESS_ONCE(dentry->d_parent);
1130                dir = ACCESS_ONCE(parent->d_inode);
1131                if (!dir)
1132                        return -ECHILD;
1133        } else {
1134                parent = dget_parent(dentry);
1135                dir = parent->d_inode;
1136        }
1137        nfs_inc_stats(dir, NFSIOS_DENTRYREVALIDATE);
1138        inode = dentry->d_inode;
1139
1140        if (!inode) {
1141                if (nfs_neg_need_reval(dir, dentry, flags)) {
1142                        if (flags & LOOKUP_RCU)
1143                                return -ECHILD;
1144                        goto out_bad;
1145                }
1146                goto out_valid;
1147        }
1148
1149        if (is_bad_inode(inode)) {
1150                if (flags & LOOKUP_RCU)
1151                        return -ECHILD;
1152                dfprintk(LOOKUPCACHE, "%s: %pd2 has dud inode\n",
1153                                __func__, dentry);
1154                goto out_bad;
1155        }
1156
1157        if (NFS_PROTO(dir)->have_delegation(inode, FMODE_READ))
1158                goto out_set_verifier;
1159
1160        /* Force a full look up iff the parent directory has changed */
1161        if (!nfs_is_exclusive_create(dir, flags) &&
1162            nfs_check_verifier(dir, dentry, flags & LOOKUP_RCU)) {
1163                error = nfs_lookup_verify_inode(inode, flags);
1164                if (error) {
1165                        if (flags & LOOKUP_RCU)
1166                                return -ECHILD;
1167                        if (error == -ESTALE)
1168                                goto out_zap_parent;
1169                        goto out_error;
1170                }
1171                nfs_advise_use_readdirplus(dir);
1172                goto out_valid;
1173        }
1174
1175        if (flags & LOOKUP_RCU)
1176                return -ECHILD;
1177
1178        if (NFS_STALE(inode))
1179                goto out_bad;
1180
1181        error = -ENOMEM;
1182        fhandle = nfs_alloc_fhandle();
1183        fattr = nfs_alloc_fattr();
1184        if (fhandle == NULL || fattr == NULL)
1185                goto out_error;
1186
1187        label = nfs4_label_alloc(NFS_SERVER(inode), GFP_NOWAIT);
1188        if (IS_ERR(label))
1189                goto out_error;
1190
1191        trace_nfs_lookup_revalidate_enter(dir, dentry, flags);
1192        error = NFS_PROTO(dir)->lookup(dir, &dentry->d_name, fhandle, fattr, label);
1193        trace_nfs_lookup_revalidate_exit(dir, dentry, flags, error);
1194        if (error == -ESTALE || error == -ENOENT)
1195                goto out_bad;
1196        if (error)
1197                goto out_error;
1198        if (nfs_compare_fh(NFS_FH(inode), fhandle))
1199                goto out_bad;
1200        if ((error = nfs_refresh_inode(inode, fattr)) != 0)
1201                goto out_bad;
1202
1203        nfs_setsecurity(inode, fattr, label);
1204
1205        nfs_free_fattr(fattr);
1206        nfs_free_fhandle(fhandle);
1207        nfs4_label_free(label);
1208
1209        /* set a readdirplus hint that we had a cache miss */
1210        nfs_force_use_readdirplus(dir);
1211
1212out_set_verifier:
1213        nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
1214 out_valid:
1215        if (flags & LOOKUP_RCU) {
1216                if (parent != ACCESS_ONCE(dentry->d_parent))
1217                        return -ECHILD;
1218        } else
1219                dput(parent);
1220        dfprintk(LOOKUPCACHE, "NFS: %s(%pd2) is valid\n",
1221                        __func__, dentry);
1222        return 1;
1223out_zap_parent:
1224        nfs_zap_caches(dir);
1225 out_bad:
1226        WARN_ON(flags & LOOKUP_RCU);
1227        nfs_free_fattr(fattr);
1228        nfs_free_fhandle(fhandle);
1229        nfs4_label_free(label);
1230        nfs_mark_for_revalidate(dir);
1231        if (inode && S_ISDIR(inode->i_mode)) {
1232                /* Purge readdir caches. */
1233                nfs_zap_caches(inode);
1234                /*
1235                 * We can't d_drop the root of a disconnected tree:
1236                 * its d_hash is on the s_anon list and d_drop() would hide
1237                 * it from shrink_dcache_for_unmount(), leading to busy
1238                 * inodes on unmount and further oopses.
1239                 */
1240                if (IS_ROOT(dentry))
1241                        goto out_valid;
1242        }
1243        dput(parent);
1244        dfprintk(LOOKUPCACHE, "NFS: %s(%pd2) is invalid\n",
1245                        __func__, dentry);
1246        return 0;
1247out_error:
1248        WARN_ON(flags & LOOKUP_RCU);
1249        nfs_free_fattr(fattr);
1250        nfs_free_fhandle(fhandle);
1251        nfs4_label_free(label);
1252        dput(parent);
1253        dfprintk(LOOKUPCACHE, "NFS: %s(%pd2) lookup returned error %d\n",
1254                        __func__, dentry, error);
1255        return error;
1256}
1257
1258/*
1259 * A weaker form of d_revalidate for revalidating just the dentry->d_inode
1260 * when we don't really care about the dentry name. This is called when a
1261 * pathwalk ends on a dentry that was not found via a normal lookup in the
1262 * parent dir (e.g.: ".", "..", procfs symlinks or mountpoint traversals).
1263 *
1264 * In this situation, we just want to verify that the inode itself is OK
1265 * since the dentry might have changed on the server.
1266 */
1267static int nfs_weak_revalidate(struct dentry *dentry, unsigned int flags)
1268{
1269        int error;
1270        struct inode *inode = dentry->d_inode;
1271
1272        /*
1273         * I believe we can only get a negative dentry here in the case of a
1274         * procfs-style symlink. Just assume it's correct for now, but we may
1275         * eventually need to do something more here.
1276         */
1277        if (!inode) {
1278                dfprintk(LOOKUPCACHE, "%s: %pd2 has negative inode\n",
1279                                __func__, dentry);
1280                return 1;
1281        }
1282
1283        if (is_bad_inode(inode)) {
1284                dfprintk(LOOKUPCACHE, "%s: %pd2 has dud inode\n",
1285                                __func__, dentry);
1286                return 0;
1287        }
1288
1289        error = nfs_lookup_verify_inode(inode, flags);
1290        dfprintk(LOOKUPCACHE, "NFS: %s: inode %lu is %s\n",
1291                        __func__, inode->i_ino, error ? "invalid" : "valid");
1292        return !error;
1293}
1294
1295/*
1296 * This is called from dput() when d_count is going to 0.
1297 */
1298static int nfs_dentry_delete(const struct dentry *dentry)
1299{
1300        dfprintk(VFS, "NFS: dentry_delete(%pd2, %x)\n",
1301                dentry, dentry->d_flags);
1302
1303        /* Unhash any dentry with a stale inode */
1304        if (dentry->d_inode != NULL && NFS_STALE(dentry->d_inode))
1305                return 1;
1306
1307        if (dentry->d_flags & DCACHE_NFSFS_RENAMED) {
1308                /* Unhash it, so that ->d_iput() would be called */
1309                return 1;
1310        }
1311        if (!(dentry->d_sb->s_flags & MS_ACTIVE)) {
1312                /* Unhash it, so that ancestors of killed async unlink
1313                 * files will be cleaned up during umount */
1314                return 1;
1315        }
1316        return 0;
1317
1318}
1319
1320/* Ensure that we revalidate inode->i_nlink */
1321static void nfs_drop_nlink(struct inode *inode)
1322{
1323        spin_lock(&inode->i_lock);
1324        /* drop the inode if we're reasonably sure this is the last link */
1325        if (inode->i_nlink == 1)
1326                clear_nlink(inode);
1327        NFS_I(inode)->cache_validity |= NFS_INO_INVALID_ATTR;
1328        spin_unlock(&inode->i_lock);
1329}
1330
1331/*
1332 * Called when the dentry loses inode.
1333 * We use it to clean up silly-renamed files.
1334 */
1335static void nfs_dentry_iput(struct dentry *dentry, struct inode *inode)
1336{
1337        if (S_ISDIR(inode->i_mode))
1338                /* drop any readdir cache as it could easily be old */
1339                NFS_I(inode)->cache_validity |= NFS_INO_INVALID_DATA;
1340
1341        if (dentry->d_flags & DCACHE_NFSFS_RENAMED) {
1342                nfs_complete_unlink(dentry, inode);
1343                nfs_drop_nlink(inode);
1344        }
1345        iput(inode);
1346}
1347
1348static void nfs_d_release(struct dentry *dentry)
1349{
1350        /* free cached devname value, if it survived that far */
1351        if (unlikely(dentry->d_fsdata)) {
1352                if (dentry->d_flags & DCACHE_NFSFS_RENAMED)
1353                        WARN_ON(1);
1354                else
1355                        kfree(dentry->d_fsdata);
1356        }
1357}
1358
1359const struct dentry_operations nfs_dentry_operations = {
1360        .d_revalidate   = nfs_lookup_revalidate,
1361        .d_weak_revalidate      = nfs_weak_revalidate,
1362        .d_delete       = nfs_dentry_delete,
1363        .d_iput         = nfs_dentry_iput,
1364        .d_automount    = nfs_d_automount,
1365        .d_release      = nfs_d_release,
1366};
1367EXPORT_SYMBOL_GPL(nfs_dentry_operations);
1368
1369struct dentry *nfs_lookup(struct inode *dir, struct dentry * dentry, unsigned int flags)
1370{
1371        struct dentry *res;
1372        struct dentry *parent;
1373        struct inode *inode = NULL;
1374        struct nfs_fh *fhandle = NULL;
1375        struct nfs_fattr *fattr = NULL;
1376        struct nfs4_label *label = NULL;
1377        int error;
1378
1379        dfprintk(VFS, "NFS: lookup(%pd2)\n", dentry);
1380        nfs_inc_stats(dir, NFSIOS_VFSLOOKUP);
1381
1382        res = ERR_PTR(-ENAMETOOLONG);
1383        if (dentry->d_name.len > NFS_SERVER(dir)->namelen)
1384                goto out;
1385
1386        /*
1387         * If we're doing an exclusive create, optimize away the lookup
1388         * but don't hash the dentry.
1389         */
1390        if (nfs_is_exclusive_create(dir, flags)) {
1391                d_instantiate(dentry, NULL);
1392                res = NULL;
1393                goto out;
1394        }
1395
1396        res = ERR_PTR(-ENOMEM);
1397        fhandle = nfs_alloc_fhandle();
1398        fattr = nfs_alloc_fattr();
1399        if (fhandle == NULL || fattr == NULL)
1400                goto out;
1401
1402        label = nfs4_label_alloc(NFS_SERVER(dir), GFP_NOWAIT);
1403        if (IS_ERR(label))
1404                goto out;
1405
1406        parent = dentry->d_parent;
1407        /* Protect against concurrent sillydeletes */
1408        trace_nfs_lookup_enter(dir, dentry, flags);
1409        nfs_block_sillyrename(parent);
1410        error = NFS_PROTO(dir)->lookup(dir, &dentry->d_name, fhandle, fattr, label);
1411        if (error == -ENOENT)
1412                goto no_entry;
1413        if (error < 0) {
1414                res = ERR_PTR(error);
1415                goto out_unblock_sillyrename;
1416        }
1417        inode = nfs_fhget(dentry->d_sb, fhandle, fattr, label);
1418        res = ERR_CAST(inode);
1419        if (IS_ERR(res))
1420                goto out_unblock_sillyrename;
1421
1422        /* Notify readdir to use READDIRPLUS */
1423        nfs_force_use_readdirplus(dir);
1424
1425no_entry:
1426        res = d_materialise_unique(dentry, inode);
1427        if (res != NULL) {
1428                if (IS_ERR(res))
1429                        goto out_unblock_sillyrename;
1430                dentry = res;
1431        }
1432        nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
1433out_unblock_sillyrename:
1434        nfs_unblock_sillyrename(parent);
1435        trace_nfs_lookup_exit(dir, dentry, flags, error);
1436        nfs4_label_free(label);
1437out:
1438        nfs_free_fattr(fattr);
1439        nfs_free_fhandle(fhandle);
1440        return res;
1441}
1442EXPORT_SYMBOL_GPL(nfs_lookup);
1443
1444#if IS_ENABLED(CONFIG_NFS_V4)
1445static int nfs4_lookup_revalidate(struct dentry *, unsigned int);
1446
1447const struct dentry_operations nfs4_dentry_operations = {
1448        .d_revalidate   = nfs4_lookup_revalidate,
1449        .d_weak_revalidate      = nfs_weak_revalidate,
1450        .d_delete       = nfs_dentry_delete,
1451        .d_iput         = nfs_dentry_iput,
1452        .d_automount    = nfs_d_automount,
1453        .d_release      = nfs_d_release,
1454};
1455EXPORT_SYMBOL_GPL(nfs4_dentry_operations);
1456
1457static fmode_t flags_to_mode(int flags)
1458{
1459        fmode_t res = (__force fmode_t)flags & FMODE_EXEC;
1460        if ((flags & O_ACCMODE) != O_WRONLY)
1461                res |= FMODE_READ;
1462        if ((flags & O_ACCMODE) != O_RDONLY)
1463                res |= FMODE_WRITE;
1464        return res;
1465}
1466
1467static struct nfs_open_context *create_nfs_open_context(struct dentry *dentry, int open_flags, struct file *filp)
1468{
1469        return alloc_nfs_open_context(dentry, flags_to_mode(open_flags), filp);
1470}
1471
1472static int do_open(struct inode *inode, struct file *filp)
1473{
1474        nfs_fscache_open_file(inode, filp);
1475        return 0;
1476}
1477
1478static int nfs_finish_open(struct nfs_open_context *ctx,
1479                           struct dentry *dentry,
1480                           struct file *file, unsigned open_flags,
1481                           int *opened)
1482{
1483        int err;
1484
1485        err = finish_open(file, dentry, do_open, opened);
1486        if (err)
1487                goto out;
1488        nfs_file_set_open_context(file, ctx);
1489
1490out:
1491        return err;
1492}
1493
1494int nfs_atomic_open(struct inode *dir, struct dentry *dentry,
1495                    struct file *file, unsigned open_flags,
1496                    umode_t mode, int *opened)
1497{
1498        struct nfs_open_context *ctx;
1499        struct dentry *res;
1500        struct iattr attr = { .ia_valid = ATTR_OPEN };
1501        struct inode *inode;
1502        unsigned int lookup_flags = 0;
1503        int err;
1504
1505        /* Expect a negative dentry */
1506        BUG_ON(dentry->d_inode);
1507
1508        dfprintk(VFS, "NFS: atomic_open(%s/%lu), %pd\n",
1509                        dir->i_sb->s_id, dir->i_ino, dentry);
1510
1511        err = nfs_check_flags(open_flags);
1512        if (err)
1513                return err;
1514
1515        /* NFS only supports OPEN on regular files */
1516        if ((open_flags & O_DIRECTORY)) {
1517                if (!d_unhashed(dentry)) {
1518                        /*
1519                         * Hashed negative dentry with O_DIRECTORY: dentry was
1520                         * revalidated and is fine, no need to perform lookup
1521                         * again
1522                         */
1523                        return -ENOENT;
1524                }
1525                lookup_flags = LOOKUP_OPEN|LOOKUP_DIRECTORY;
1526                goto no_open;
1527        }
1528
1529        if (dentry->d_name.len > NFS_SERVER(dir)->namelen)
1530                return -ENAMETOOLONG;
1531
1532        if (open_flags & O_CREAT) {
1533                struct nfs_server *server = NFS_SERVER(dir);
1534
1535                if (!(server->attr_bitmask[2] & FATTR4_WORD2_MODE_UMASK))
1536                        mode &= ~current_umask();
1537
1538                attr.ia_valid |= ATTR_MODE;
1539                attr.ia_mode = mode;
1540        }
1541        if (open_flags & O_TRUNC) {
1542                attr.ia_valid |= ATTR_SIZE;
1543                attr.ia_size = 0;
1544        }
1545
1546        ctx = create_nfs_open_context(dentry, open_flags, file);
1547        err = PTR_ERR(ctx);
1548        if (IS_ERR(ctx))
1549                goto out;
1550
1551        trace_nfs_atomic_open_enter(dir, ctx, open_flags);
1552        nfs_block_sillyrename(dentry->d_parent);
1553        inode = NFS_PROTO(dir)->open_context(dir, ctx, open_flags, &attr, opened);
1554        nfs_unblock_sillyrename(dentry->d_parent);
1555        if (IS_ERR(inode)) {
1556                err = PTR_ERR(inode);
1557                trace_nfs_atomic_open_exit(dir, ctx, open_flags, err);
1558                put_nfs_open_context(ctx);
1559                d_drop(dentry);
1560                switch (err) {
1561                case -ENOENT:
1562                        d_add(dentry, NULL);
1563                        nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
1564                        break;
1565                case -EISDIR:
1566                case -ENOTDIR:
1567                        goto no_open;
1568                case -ELOOP:
1569                        if (!(open_flags & O_NOFOLLOW))
1570                                goto no_open;
1571                        break;
1572                        /* case -EINVAL: */
1573                default:
1574                        break;
1575                }
1576                goto out;
1577        }
1578
1579        err = nfs_finish_open(ctx, ctx->dentry, file, open_flags, opened);
1580        trace_nfs_atomic_open_exit(dir, ctx, open_flags, err);
1581        put_nfs_open_context(ctx);
1582out:
1583        return err;
1584
1585no_open:
1586        res = nfs_lookup(dir, dentry, lookup_flags);
1587        err = PTR_ERR(res);
1588        if (IS_ERR(res))
1589                goto out;
1590
1591        return finish_no_open(file, res);
1592}
1593EXPORT_SYMBOL_GPL(nfs_atomic_open);
1594
1595static int nfs4_lookup_revalidate(struct dentry *dentry, unsigned int flags)
1596{
1597        struct inode *inode;
1598        int ret = 0;
1599
1600        if (!(flags & LOOKUP_OPEN) || (flags & LOOKUP_DIRECTORY))
1601                goto no_open;
1602        if (d_mountpoint(dentry))
1603                goto no_open;
1604        if (NFS_SB(dentry->d_sb)->caps & NFS_CAP_ATOMIC_OPEN_V1)
1605                goto no_open;
1606
1607        inode = dentry->d_inode;
1608
1609        /* We can't create new files in nfs_open_revalidate(), so we
1610         * optimize away revalidation of negative dentries.
1611         */
1612        if (inode == NULL) {
1613                struct dentry *parent;
1614                struct inode *dir;
1615
1616                if (flags & LOOKUP_RCU) {
1617                        parent = ACCESS_ONCE(dentry->d_parent);
1618                        dir = ACCESS_ONCE(parent->d_inode);
1619                        if (!dir)
1620                                return -ECHILD;
1621                } else {
1622                        parent = dget_parent(dentry);
1623                        dir = parent->d_inode;
1624                }
1625                if (!nfs_neg_need_reval(dir, dentry, flags))
1626                        ret = 1;
1627                else if (flags & LOOKUP_RCU)
1628                        ret = -ECHILD;
1629                if (!(flags & LOOKUP_RCU))
1630                        dput(parent);
1631                else if (parent != ACCESS_ONCE(dentry->d_parent))
1632                        return -ECHILD;
1633                goto out;
1634        }
1635
1636        /* NFS only supports OPEN on regular files */
1637        if (!S_ISREG(inode->i_mode))
1638                goto no_open;
1639        /* We cannot do exclusive creation on a positive dentry */
1640        if (flags & LOOKUP_EXCL)
1641                goto no_open;
1642
1643        /* Let f_op->open() actually open (and revalidate) the file */
1644        ret = 1;
1645
1646out:
1647        return ret;
1648
1649no_open:
1650        return nfs_lookup_revalidate(dentry, flags);
1651}
1652
1653#endif /* CONFIG_NFSV4 */
1654
1655/*
1656 * Code common to create, mkdir, and mknod.
1657 */
1658int nfs_instantiate(struct dentry *dentry, struct nfs_fh *fhandle,
1659                                struct nfs_fattr *fattr,
1660                                struct nfs4_label *label)
1661{
1662        struct dentry *parent = dget_parent(dentry);
1663        struct inode *dir = parent->d_inode;
1664        struct inode *inode;
1665        int error = -EACCES;
1666
1667        d_drop(dentry);
1668
1669        /* We may have been initialized further down */
1670        if (dentry->d_inode)
1671                goto out;
1672        if (fhandle->size == 0) {
1673                error = NFS_PROTO(dir)->lookup(dir, &dentry->d_name, fhandle, fattr, NULL);
1674                if (error)
1675                        goto out_error;
1676        }
1677        nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
1678        if (!(fattr->valid & NFS_ATTR_FATTR)) {
1679                struct nfs_server *server = NFS_SB(dentry->d_sb);
1680                error = server->nfs_client->rpc_ops->getattr(server, fhandle, fattr, NULL);
1681                if (error < 0)
1682                        goto out_error;
1683        }
1684        inode = nfs_fhget(dentry->d_sb, fhandle, fattr, label);
1685        error = PTR_ERR(inode);
1686        if (IS_ERR(inode))
1687                goto out_error;
1688        d_add(dentry, inode);
1689out:
1690        dput(parent);
1691        return 0;
1692out_error:
1693        nfs_mark_for_revalidate(dir);
1694        dput(parent);
1695        return error;
1696}
1697EXPORT_SYMBOL_GPL(nfs_instantiate);
1698
1699/*
1700 * Following a failed create operation, we drop the dentry rather
1701 * than retain a negative dentry. This avoids a problem in the event
1702 * that the operation succeeded on the server, but an error in the
1703 * reply path made it appear to have failed.
1704 */
1705int nfs_create(struct inode *dir, struct dentry *dentry,
1706                umode_t mode, bool excl)
1707{
1708        struct iattr attr;
1709        int open_flags = excl ? O_CREAT | O_EXCL : O_CREAT;
1710        int error;
1711
1712        dfprintk(VFS, "NFS: create(%s/%lu), %pd\n",
1713                        dir->i_sb->s_id, dir->i_ino, dentry);
1714
1715        attr.ia_mode = mode;
1716        attr.ia_valid = ATTR_MODE;
1717
1718        trace_nfs_create_enter(dir, dentry, open_flags);
1719        error = NFS_PROTO(dir)->create(dir, dentry, &attr, open_flags);
1720        trace_nfs_create_exit(dir, dentry, open_flags, error);
1721        if (error != 0)
1722                goto out_err;
1723        return 0;
1724out_err:
1725        d_drop(dentry);
1726        return error;
1727}
1728EXPORT_SYMBOL_GPL(nfs_create);
1729
1730/*
1731 * See comments for nfs_proc_create regarding failed operations.
1732 */
1733int
1734nfs_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t rdev)
1735{
1736        struct iattr attr;
1737        int status;
1738
1739        dfprintk(VFS, "NFS: mknod(%s/%lu), %pd\n",
1740                        dir->i_sb->s_id, dir->i_ino, dentry);
1741
1742        attr.ia_mode = mode;
1743        attr.ia_valid = ATTR_MODE;
1744
1745        trace_nfs_mknod_enter(dir, dentry);
1746        status = NFS_PROTO(dir)->mknod(dir, dentry, &attr, rdev);
1747        trace_nfs_mknod_exit(dir, dentry, status);
1748        if (status != 0)
1749                goto out_err;
1750        return 0;
1751out_err:
1752        d_drop(dentry);
1753        return status;
1754}
1755EXPORT_SYMBOL_GPL(nfs_mknod);
1756
1757/*
1758 * See comments for nfs_proc_create regarding failed operations.
1759 */
1760int nfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
1761{
1762        struct iattr attr;
1763        int error;
1764
1765        dfprintk(VFS, "NFS: mkdir(%s/%lu), %pd\n",
1766                        dir->i_sb->s_id, dir->i_ino, dentry);
1767
1768        attr.ia_valid = ATTR_MODE;
1769        attr.ia_mode = mode | S_IFDIR;
1770
1771        trace_nfs_mkdir_enter(dir, dentry);
1772        error = NFS_PROTO(dir)->mkdir(dir, dentry, &attr);
1773        trace_nfs_mkdir_exit(dir, dentry, error);
1774        if (error != 0)
1775                goto out_err;
1776        return 0;
1777out_err:
1778        d_drop(dentry);
1779        return error;
1780}
1781EXPORT_SYMBOL_GPL(nfs_mkdir);
1782
1783static void nfs_dentry_handle_enoent(struct dentry *dentry)
1784{
1785        if (dentry->d_inode != NULL && !d_unhashed(dentry))
1786                d_delete(dentry);
1787}
1788
1789int nfs_rmdir(struct inode *dir, struct dentry *dentry)
1790{
1791        int error;
1792
1793        dfprintk(VFS, "NFS: rmdir(%s/%lu), %pd\n",
1794                        dir->i_sb->s_id, dir->i_ino, dentry);
1795
1796        trace_nfs_rmdir_enter(dir, dentry);
1797        if (dentry->d_inode) {
1798                nfs_wait_on_sillyrename(dentry);
1799                error = NFS_PROTO(dir)->rmdir(dir, &dentry->d_name);
1800                /* Ensure the VFS deletes this inode */
1801                switch (error) {
1802                case 0:
1803                        clear_nlink(dentry->d_inode);
1804                        break;
1805                case -ENOENT:
1806                        nfs_dentry_handle_enoent(dentry);
1807                }
1808        } else
1809                error = NFS_PROTO(dir)->rmdir(dir, &dentry->d_name);
1810        trace_nfs_rmdir_exit(dir, dentry, error);
1811
1812        return error;
1813}
1814EXPORT_SYMBOL_GPL(nfs_rmdir);
1815
1816/*
1817 * Remove a file after making sure there are no pending writes,
1818 * and after checking that the file has only one user. 
1819 *
1820 * We invalidate the attribute cache and free the inode prior to the operation
1821 * to avoid possible races if the server reuses the inode.
1822 */
1823static int nfs_safe_remove(struct dentry *dentry)
1824{
1825        struct inode *dir = dentry->d_parent->d_inode;
1826        struct inode *inode = dentry->d_inode;
1827        int error = -EBUSY;
1828                
1829        dfprintk(VFS, "NFS: safe_remove(%pd2)\n", dentry);
1830
1831        /* If the dentry was sillyrenamed, we simply call d_delete() */
1832        if (dentry->d_flags & DCACHE_NFSFS_RENAMED) {
1833                error = 0;
1834                goto out;
1835        }
1836
1837        trace_nfs_remove_enter(dir, dentry);
1838        if (inode != NULL) {
1839                NFS_PROTO(inode)->return_delegation(inode);
1840                error = NFS_PROTO(dir)->remove(dir, &dentry->d_name);
1841                if (error == 0)
1842                        nfs_drop_nlink(inode);
1843        } else
1844                error = NFS_PROTO(dir)->remove(dir, &dentry->d_name);
1845        if (error == -ENOENT)
1846                nfs_dentry_handle_enoent(dentry);
1847        trace_nfs_remove_exit(dir, dentry, error);
1848out:
1849        return error;
1850}
1851
1852/*  We do silly rename. In case sillyrename() returns -EBUSY, the inode
1853 *  belongs to an active ".nfs..." file and we return -EBUSY.
1854 *
1855 *  If sillyrename() returns 0, we do nothing, otherwise we unlink.
1856 */
1857int nfs_unlink(struct inode *dir, struct dentry *dentry)
1858{
1859        int error;
1860        int need_rehash = 0;
1861
1862        dfprintk(VFS, "NFS: unlink(%s/%lu, %pd)\n", dir->i_sb->s_id,
1863                dir->i_ino, dentry);
1864
1865        trace_nfs_unlink_enter(dir, dentry);
1866        spin_lock(&dentry->d_lock);
1867        if (d_count(dentry) > 1) {
1868                spin_unlock(&dentry->d_lock);
1869                /* Start asynchronous writeout of the inode */
1870                write_inode_now(dentry->d_inode, 0);
1871                error = nfs_sillyrename(dir, dentry);
1872                goto out;
1873        }
1874        if (!d_unhashed(dentry)) {
1875                __d_drop(dentry);
1876                need_rehash = 1;
1877        }
1878        spin_unlock(&dentry->d_lock);
1879        error = nfs_safe_remove(dentry);
1880        if (!error || error == -ENOENT) {
1881                nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
1882        } else if (need_rehash)
1883                d_rehash(dentry);
1884out:
1885        trace_nfs_unlink_exit(dir, dentry, error);
1886        return error;
1887}
1888EXPORT_SYMBOL_GPL(nfs_unlink);
1889
1890/*
1891 * To create a symbolic link, most file systems instantiate a new inode,
1892 * add a page to it containing the path, then write it out to the disk
1893 * using prepare_write/commit_write.
1894 *
1895 * Unfortunately the NFS client can't create the in-core inode first
1896 * because it needs a file handle to create an in-core inode (see
1897 * fs/nfs/inode.c:nfs_fhget).  We only have a file handle *after* the
1898 * symlink request has completed on the server.
1899 *
1900 * So instead we allocate a raw page, copy the symname into it, then do
1901 * the SYMLINK request with the page as the buffer.  If it succeeds, we
1902 * now have a new file handle and can instantiate an in-core NFS inode
1903 * and move the raw page into its mapping.
1904 */
1905int nfs_symlink(struct inode *dir, struct dentry *dentry, const char *symname)
1906{
1907        struct page *page;
1908        char *kaddr;
1909        struct iattr attr;
1910        unsigned int pathlen = strlen(symname);
1911        int error;
1912
1913        dfprintk(VFS, "NFS: symlink(%s/%lu, %pd, %s)\n", dir->i_sb->s_id,
1914                dir->i_ino, dentry, symname);
1915
1916        if (pathlen > PAGE_SIZE)
1917                return -ENAMETOOLONG;
1918
1919        attr.ia_mode = S_IFLNK | S_IRWXUGO;
1920        attr.ia_valid = ATTR_MODE;
1921
1922        page = alloc_page(GFP_HIGHUSER);
1923        if (!page)
1924                return -ENOMEM;
1925
1926        kaddr = kmap_atomic(page);
1927        memcpy(kaddr, symname, pathlen);
1928        if (pathlen < PAGE_SIZE)
1929                memset(kaddr + pathlen, 0, PAGE_SIZE - pathlen);
1930        kunmap_atomic(kaddr);
1931
1932        trace_nfs_symlink_enter(dir, dentry);
1933        error = NFS_PROTO(dir)->symlink(dir, dentry, page, pathlen, &attr);
1934        trace_nfs_symlink_exit(dir, dentry, error);
1935        if (error != 0) {
1936                dfprintk(VFS, "NFS: symlink(%s/%lu, %pd, %s) error %d\n",
1937                        dir->i_sb->s_id, dir->i_ino,
1938                        dentry, symname, error);
1939                d_drop(dentry);
1940                __free_page(page);
1941                return error;
1942        }
1943
1944        /*
1945         * No big deal if we can't add this page to the page cache here.
1946         * READLINK will get the missing page from the server if needed.
1947         */
1948        if (!add_to_page_cache_lru(page, dentry->d_inode->i_mapping, 0,
1949                                                        GFP_KERNEL)) {
1950                SetPageUptodate(page);
1951                unlock_page(page);
1952                /*
1953                 * add_to_page_cache_lru() grabs an extra page refcount.
1954                 * Drop it here to avoid leaking this page later.
1955                 */
1956                page_cache_release(page);
1957        } else
1958                __free_page(page);
1959
1960        return 0;
1961}
1962EXPORT_SYMBOL_GPL(nfs_symlink);
1963
1964int
1965nfs_link(struct dentry *old_dentry, struct inode *dir, struct dentry *dentry)
1966{
1967        struct inode *inode = old_dentry->d_inode;
1968        int error;
1969
1970        dfprintk(VFS, "NFS: link(%pd2 -> %pd2)\n",
1971                old_dentry, dentry);
1972
1973        trace_nfs_link_enter(inode, dir, dentry);
1974        NFS_PROTO(inode)->return_delegation(inode);
1975
1976        d_drop(dentry);
1977        error = NFS_PROTO(dir)->link(inode, dir, &dentry->d_name);
1978        if (error == 0) {
1979                ihold(inode);
1980                d_add(dentry, inode);
1981        }
1982        trace_nfs_link_exit(inode, dir, dentry, error);
1983        return error;
1984}
1985EXPORT_SYMBOL_GPL(nfs_link);
1986
1987/*
1988 * RENAME
1989 * FIXME: Some nfsds, like the Linux user space nfsd, may generate a
1990 * different file handle for the same inode after a rename (e.g. when
1991 * moving to a different directory). A fail-safe method to do so would
1992 * be to look up old_dir/old_name, create a link to new_dir/new_name and
1993 * rename the old file using the sillyrename stuff. This way, the original
1994 * file in old_dir will go away when the last process iput()s the inode.
1995 *
1996 * FIXED.
1997 * 
1998 * It actually works quite well. One needs to have the possibility for
1999 * at least one ".nfs..." file in each directory the file ever gets
2000 * moved or linked to which happens automagically with the new
2001 * implementation that only depends on the dcache stuff instead of
2002 * using the inode layer
2003 *
2004 * Unfortunately, things are a little more complicated than indicated
2005 * above. For a cross-directory move, we want to make sure we can get
2006 * rid of the old inode after the operation.  This means there must be
2007 * no pending writes (if it's a file), and the use count must be 1.
2008 * If these conditions are met, we can drop the dentries before doing
2009 * the rename.
2010 */
2011int nfs_rename(struct inode *old_dir, struct dentry *old_dentry,
2012                      struct inode *new_dir, struct dentry *new_dentry)
2013{
2014        struct inode *old_inode = old_dentry->d_inode;
2015        struct inode *new_inode = new_dentry->d_inode;
2016        struct dentry *dentry = NULL, *rehash = NULL;
2017        struct rpc_task *task;
2018        int error = -EBUSY;
2019
2020        dfprintk(VFS, "NFS: rename(%pd2 -> %pd2, ct=%d)\n",
2021                 old_dentry, new_dentry,
2022                 d_count(new_dentry));
2023
2024        trace_nfs_rename_enter(old_dir, old_dentry, new_dir, new_dentry);
2025        /*
2026         * For non-directories, check whether the target is busy and if so,
2027         * make a copy of the dentry and then do a silly-rename. If the
2028         * silly-rename succeeds, the copied dentry is hashed and becomes
2029         * the new target.
2030         */
2031        if (new_inode && !S_ISDIR(new_inode->i_mode)) {
2032                /*
2033                 * To prevent any new references to the target during the
2034                 * rename, we unhash the dentry in advance.
2035                 */
2036                if (!d_unhashed(new_dentry)) {
2037                        d_drop(new_dentry);
2038                        rehash = new_dentry;
2039                }
2040
2041                if (d_count(new_dentry) > 2) {
2042                        int err;
2043
2044                        /* copy the target dentry's name */
2045                        dentry = d_alloc(new_dentry->d_parent,
2046                                         &new_dentry->d_name);
2047                        if (!dentry)
2048                                goto out;
2049
2050                        /* silly-rename the existing target ... */
2051                        err = nfs_sillyrename(new_dir, new_dentry);
2052                        if (err)
2053                                goto out;
2054
2055                        new_dentry = dentry;
2056                        rehash = NULL;
2057                        new_inode = NULL;
2058                }
2059        }
2060
2061        NFS_PROTO(old_inode)->return_delegation(old_inode);
2062        if (new_inode != NULL)
2063                NFS_PROTO(new_inode)->return_delegation(new_inode);
2064
2065        task = nfs_async_rename(old_dir, new_dir, old_dentry, new_dentry, NULL);
2066        if (IS_ERR(task)) {
2067                error = PTR_ERR(task);
2068                goto out;
2069        }
2070
2071        error = rpc_wait_for_completion_task(task);
2072        if (error != 0) {
2073                ((struct nfs_renamedata *)task->tk_calldata)->cancelled = 1;
2074                /* Paired with the atomic_dec_and_test() barrier in rpc_do_put_task() */
2075                smp_wmb();
2076        } else
2077                error = task->tk_status;
2078        rpc_put_task(task);
2079        nfs_mark_for_revalidate(old_inode);
2080out:
2081        if (rehash)
2082                d_rehash(rehash);
2083        trace_nfs_rename_exit(old_dir, old_dentry,
2084                        new_dir, new_dentry, error);
2085        if (!error) {
2086                if (new_inode != NULL)
2087                        nfs_drop_nlink(new_inode);
2088                /*
2089                 * The d_move() should be here instead of in an async RPC completion
2090                 * handler because we need the proper locks to move the dentry.  If
2091                 * we're interrupted by a signal, the async RPC completion handler
2092                 * should mark the directories for revalidation.
2093                 */
2094                d_move(old_dentry, new_dentry);
2095                nfs_set_verifier(new_dentry,
2096                                        nfs_save_change_attribute(new_dir));
2097        } else if (error == -ENOENT)
2098                nfs_dentry_handle_enoent(old_dentry);
2099
2100        /* new dentry created? */
2101        if (dentry)
2102                dput(dentry);
2103        return error;
2104}
2105EXPORT_SYMBOL_GPL(nfs_rename);
2106
2107static DEFINE_SPINLOCK(nfs_access_lru_lock);
2108static LIST_HEAD(nfs_access_lru_list);
2109static atomic_long_t nfs_access_nr_entries;
2110
2111static unsigned long nfs_access_max_cachesize = ULONG_MAX;
2112module_param(nfs_access_max_cachesize, ulong, 0644);
2113MODULE_PARM_DESC(nfs_access_max_cachesize, "NFS access maximum total cache length");
2114
2115static void nfs_access_free_entry(struct nfs_access_entry *entry)
2116{
2117        put_rpccred(entry->cred);
2118        kfree_rcu(entry, rcu_head);
2119        smp_mb__before_atomic_dec();
2120        atomic_long_dec(&nfs_access_nr_entries);
2121        smp_mb__after_atomic_dec();
2122}
2123
2124static void nfs_access_free_list(struct list_head *head)
2125{
2126        struct nfs_access_entry *cache;
2127
2128        while (!list_empty(head)) {
2129                cache = list_entry(head->next, struct nfs_access_entry, lru);
2130                list_del(&cache->lru);
2131                nfs_access_free_entry(cache);
2132        }
2133}
2134
2135int nfs_do_access_cache_shrinker(int nr_to_scan)
2136{
2137        LIST_HEAD(head);
2138        struct nfs_inode *nfsi, *next;
2139        struct nfs_access_entry *cache;
2140
2141        spin_lock(&nfs_access_lru_lock);
2142        list_for_each_entry_safe(nfsi, next, &nfs_access_lru_list, access_cache_inode_lru) {
2143                struct inode *inode;
2144
2145                if (nr_to_scan-- == 0)
2146                        break;
2147                inode = &nfsi->vfs_inode;
2148                spin_lock(&inode->i_lock);
2149                if (list_empty(&nfsi->access_cache_entry_lru))
2150                        goto remove_lru_entry;
2151                cache = list_entry(nfsi->access_cache_entry_lru.next,
2152                                struct nfs_access_entry, lru);
2153                list_move(&cache->lru, &head);
2154                rb_erase(&cache->rb_node, &nfsi->access_cache);
2155                if (!list_empty(&nfsi->access_cache_entry_lru))
2156                        list_move_tail(&nfsi->access_cache_inode_lru,
2157                                        &nfs_access_lru_list);
2158                else {
2159remove_lru_entry:
2160                        list_del_init(&nfsi->access_cache_inode_lru);
2161                        smp_mb__before_clear_bit();
2162                        clear_bit(NFS_INO_ACL_LRU_SET, &nfsi->flags);
2163                        smp_mb__after_clear_bit();
2164                }
2165                spin_unlock(&inode->i_lock);
2166        }
2167        spin_unlock(&nfs_access_lru_lock);
2168        nfs_access_free_list(&head);
2169        return (atomic_long_read(&nfs_access_nr_entries) / 100) * sysctl_vfs_cache_pressure;
2170}
2171
2172int nfs_access_cache_shrinker(struct shrinker *shrink,
2173                              struct shrink_control *sc)
2174{
2175        int nr_to_scan = sc->nr_to_scan;
2176        gfp_t gfp_mask = sc->gfp_mask;
2177
2178        if ((gfp_mask & GFP_KERNEL) != GFP_KERNEL)
2179                return (nr_to_scan == 0) ? 0 : -1;
2180        return nfs_do_access_cache_shrinker(nr_to_scan);
2181}
2182
2183static void
2184nfs_access_cache_enforce_limit(void)
2185{
2186        long nr_entries = atomic_long_read(&nfs_access_nr_entries);
2187        unsigned long diff;
2188        unsigned int nr_to_scan;
2189
2190        if (nr_entries < 0 || nr_entries <= nfs_access_max_cachesize)
2191                return;
2192        nr_to_scan = 100;
2193        diff = nr_entries - nfs_access_max_cachesize;
2194        if (diff < nr_to_scan)
2195                nr_to_scan = diff;
2196        nfs_do_access_cache_shrinker(nr_to_scan);
2197}
2198
2199static void __nfs_access_zap_cache(struct nfs_inode *nfsi, struct list_head *head)
2200{
2201        struct rb_root *root_node = &nfsi->access_cache;
2202        struct rb_node *n;
2203        struct nfs_access_entry *entry;
2204
2205        /* Unhook entries from the cache */
2206        while ((n = rb_first(root_node)) != NULL) {
2207                entry = rb_entry(n, struct nfs_access_entry, rb_node);
2208                rb_erase(n, root_node);
2209                list_move(&entry->lru, head);
2210        }
2211        nfsi->cache_validity &= ~NFS_INO_INVALID_ACCESS;
2212}
2213
2214void nfs_access_zap_cache(struct inode *inode)
2215{
2216        LIST_HEAD(head);
2217
2218        if (test_bit(NFS_INO_ACL_LRU_SET, &NFS_I(inode)->flags) == 0)
2219                return;
2220        /* Remove from global LRU init */
2221        spin_lock(&nfs_access_lru_lock);
2222        if (test_and_clear_bit(NFS_INO_ACL_LRU_SET, &NFS_I(inode)->flags))
2223                list_del_init(&NFS_I(inode)->access_cache_inode_lru);
2224
2225        spin_lock(&inode->i_lock);
2226        __nfs_access_zap_cache(NFS_I(inode), &head);
2227        spin_unlock(&inode->i_lock);
2228        spin_unlock(&nfs_access_lru_lock);
2229        nfs_access_free_list(&head);
2230}
2231EXPORT_SYMBOL_GPL(nfs_access_zap_cache);
2232
2233static struct nfs_access_entry *nfs_access_search_rbtree(struct inode *inode, struct rpc_cred *cred)
2234{
2235        struct rb_node *n = NFS_I(inode)->access_cache.rb_node;
2236        struct nfs_access_entry *entry;
2237
2238        while (n != NULL) {
2239                entry = rb_entry(n, struct nfs_access_entry, rb_node);
2240
2241                if (cred < entry->cred)
2242                        n = n->rb_left;
2243                else if (cred > entry->cred)
2244                        n = n->rb_right;
2245                else
2246                        return entry;
2247        }
2248        return NULL;
2249}
2250
2251static int nfs_access_get_cached(struct inode *inode, struct rpc_cred *cred, struct nfs_access_entry *res)
2252{
2253        struct nfs_inode *nfsi = NFS_I(inode);
2254        struct nfs_access_entry *cache;
2255        int err = -ENOENT;
2256
2257        spin_lock(&inode->i_lock);
2258        if (nfsi->cache_validity & NFS_INO_INVALID_ACCESS)
2259                goto out_zap;
2260        cache = nfs_access_search_rbtree(inode, cred);
2261        if (cache == NULL)
2262                goto out;
2263        if (!nfs_have_delegated_attributes(inode) &&
2264            !time_in_range_open(jiffies, cache->jiffies, cache->jiffies + nfsi->attrtimeo))
2265                goto out_stale;
2266        res->jiffies = cache->jiffies;
2267        res->cred = cache->cred;
2268        res->mask = cache->mask;
2269        list_move_tail(&cache->lru, &nfsi->access_cache_entry_lru);
2270        err = 0;
2271out:
2272        spin_unlock(&inode->i_lock);
2273        return err;
2274out_stale:
2275        rb_erase(&cache->rb_node, &nfsi->access_cache);
2276        list_del(&cache->lru);
2277        spin_unlock(&inode->i_lock);
2278        nfs_access_free_entry(cache);
2279        return -ENOENT;
2280out_zap:
2281        spin_unlock(&inode->i_lock);
2282        nfs_access_zap_cache(inode);
2283        return -ENOENT;
2284}
2285
2286static int nfs_access_get_cached_rcu(struct inode *inode, struct rpc_cred *cred, struct nfs_access_entry *res)
2287{
2288        /* Only check the most recently returned cache entry,
2289         * but do it without locking.
2290         */
2291        struct nfs_inode *nfsi = NFS_I(inode);
2292        struct nfs_access_entry *cache;
2293        int err = -ECHILD;
2294        struct list_head *lh;
2295
2296        rcu_read_lock();
2297        if (nfsi->cache_validity & NFS_INO_INVALID_ACCESS)
2298                goto out;
2299        lh = rcu_dereference(nfsi->access_cache_entry_lru.prev);
2300        cache = list_entry(lh, struct nfs_access_entry, lru);
2301        if (lh == &nfsi->access_cache_entry_lru ||
2302            cred != cache->cred)
2303                cache = NULL;
2304        if (cache == NULL)
2305                goto out;
2306        if (!nfs_have_delegated_attributes(inode) &&
2307            !time_in_range_open(jiffies, cache->jiffies, cache->jiffies + nfsi->attrtimeo))
2308                goto out;
2309        res->jiffies = cache->jiffies;
2310        res->cred = cache->cred;
2311        res->mask = cache->mask;
2312        err = 0;
2313out:
2314        rcu_read_unlock();
2315        return err;
2316}
2317
2318static void nfs_access_add_rbtree(struct inode *inode, struct nfs_access_entry *set)
2319{
2320        struct nfs_inode *nfsi = NFS_I(inode);
2321        struct rb_root *root_node = &nfsi->access_cache;
2322        struct rb_node **p = &root_node->rb_node;
2323        struct rb_node *parent = NULL;
2324        struct nfs_access_entry *entry;
2325
2326        spin_lock(&inode->i_lock);
2327        while (*p != NULL) {
2328                parent = *p;
2329                entry = rb_entry(parent, struct nfs_access_entry, rb_node);
2330
2331                if (set->cred < entry->cred)
2332                        p = &parent->rb_left;
2333                else if (set->cred > entry->cred)
2334                        p = &parent->rb_right;
2335                else
2336                        goto found;
2337        }
2338        rb_link_node(&set->rb_node, parent, p);
2339        rb_insert_color(&set->rb_node, root_node);
2340        list_add_tail(&set->lru, &nfsi->access_cache_entry_lru);
2341        spin_unlock(&inode->i_lock);
2342        return;
2343found:
2344        rb_replace_node(parent, &set->rb_node, root_node);
2345        list_add_tail(&set->lru, &nfsi->access_cache_entry_lru);
2346        list_del(&entry->lru);
2347        spin_unlock(&inode->i_lock);
2348        nfs_access_free_entry(entry);
2349}
2350
2351void nfs_access_add_cache(struct inode *inode, struct nfs_access_entry *set)
2352{
2353        struct nfs_access_entry *cache = kmalloc(sizeof(*cache), GFP_KERNEL);
2354        if (cache == NULL)
2355                return;
2356        RB_CLEAR_NODE(&cache->rb_node);
2357        cache->jiffies = set->jiffies;
2358        cache->cred = get_rpccred(set->cred);
2359        cache->mask = set->mask;
2360
2361        /* The above field assignments must be visible
2362         * before this item appears on the lru.  We cannot easily
2363         * use rcu_assign_pointer, so just force the memory barrier.
2364         */
2365        smp_wmb();
2366        nfs_access_add_rbtree(inode, cache);
2367
2368        /* Update accounting */
2369        smp_mb__before_atomic_inc();
2370        atomic_long_inc(&nfs_access_nr_entries);
2371        smp_mb__after_atomic_inc();
2372
2373        /* Add inode to global LRU list */
2374        if (!test_bit(NFS_INO_ACL_LRU_SET, &NFS_I(inode)->flags)) {
2375                spin_lock(&nfs_access_lru_lock);
2376                if (!test_and_set_bit(NFS_INO_ACL_LRU_SET, &NFS_I(inode)->flags))
2377                        list_add_tail(&NFS_I(inode)->access_cache_inode_lru,
2378                                        &nfs_access_lru_list);
2379                spin_unlock(&nfs_access_lru_lock);
2380        }
2381        nfs_access_cache_enforce_limit();
2382}
2383EXPORT_SYMBOL_GPL(nfs_access_add_cache);
2384
2385void nfs_access_set_mask(struct nfs_access_entry *entry, u32 access_result)
2386{
2387        entry->mask = 0;
2388        if (access_result & NFS4_ACCESS_READ)
2389                entry->mask |= MAY_READ;
2390        if (access_result &
2391            (NFS4_ACCESS_MODIFY | NFS4_ACCESS_EXTEND | NFS4_ACCESS_DELETE))
2392                entry->mask |= MAY_WRITE;
2393        if (access_result & (NFS4_ACCESS_LOOKUP|NFS4_ACCESS_EXECUTE))
2394                entry->mask |= MAY_EXEC;
2395}
2396EXPORT_SYMBOL_GPL(nfs_access_set_mask);
2397
2398static int nfs_do_access(struct inode *inode, struct rpc_cred *cred, int mask)
2399{
2400        struct nfs_access_entry cache;
2401        int status;
2402
2403        trace_nfs_access_enter(inode);
2404
2405        status = nfs_access_get_cached_rcu(inode, cred, &cache);
2406        if (status != 0)
2407                status = nfs_access_get_cached(inode, cred, &cache);
2408        if (status == 0)
2409                goto out_cached;
2410
2411        status = -ECHILD;
2412        if (mask & MAY_NOT_BLOCK)
2413                goto out;
2414
2415        /* Be clever: ask server to check for all possible rights */
2416        cache.mask = MAY_EXEC | MAY_WRITE | MAY_READ;
2417        cache.cred = cred;
2418        cache.jiffies = jiffies;
2419        status = NFS_PROTO(inode)->access(inode, &cache);
2420        if (status != 0) {
2421                if (status == -ESTALE) {
2422                        nfs_zap_caches(inode);
2423                        if (!S_ISDIR(inode->i_mode))
2424                                set_bit(NFS_INO_STALE, &NFS_I(inode)->flags);
2425                }
2426                goto out;
2427        }
2428        nfs_access_add_cache(inode, &cache);
2429out_cached:
2430        if ((mask & ~cache.mask & (MAY_READ | MAY_WRITE | MAY_EXEC)) != 0)
2431                status = -EACCES;
2432out:
2433        trace_nfs_access_exit(inode, status);
2434        return status;
2435}
2436
2437static int nfs_open_permission_mask(int openflags)
2438{
2439        int mask = 0;
2440
2441        if (openflags & __FMODE_EXEC) {
2442                /* ONLY check exec rights */
2443                mask = MAY_EXEC;
2444        } else {
2445                if ((openflags & O_ACCMODE) != O_WRONLY)
2446                        mask |= MAY_READ;
2447                if ((openflags & O_ACCMODE) != O_RDONLY)
2448                        mask |= MAY_WRITE;
2449        }
2450
2451        return mask;
2452}
2453
2454int nfs_may_open(struct inode *inode, struct rpc_cred *cred, int openflags)
2455{
2456        return nfs_do_access(inode, cred, nfs_open_permission_mask(openflags));
2457}
2458EXPORT_SYMBOL_GPL(nfs_may_open);
2459
2460static int nfs_execute_ok(struct inode *inode, int mask)
2461{
2462        struct nfs_server *server = NFS_SERVER(inode);
2463        int ret;
2464
2465        if (mask & MAY_NOT_BLOCK)
2466                ret = nfs_revalidate_inode_rcu(server, inode);
2467        else
2468                ret = nfs_revalidate_inode(server, inode);
2469        if (ret == 0 && !execute_ok(inode))
2470                ret = -EACCES;
2471        return ret;
2472}
2473
2474int nfs_permission(struct inode *inode, int mask)
2475{
2476        struct rpc_cred *cred;
2477        int res = 0;
2478
2479        nfs_inc_stats(inode, NFSIOS_VFSACCESS);
2480
2481        if ((mask & (MAY_READ | MAY_WRITE | MAY_EXEC)) == 0)
2482                goto out;
2483        /* Is this sys_access() ? */
2484        if (mask & (MAY_ACCESS | MAY_CHDIR))
2485                goto force_lookup;
2486
2487        switch (inode->i_mode & S_IFMT) {
2488                case S_IFLNK:
2489                        goto out;
2490                case S_IFREG:
2491                        if ((mask & MAY_OPEN) &&
2492                           nfs_server_capable(inode, NFS_CAP_ATOMIC_OPEN))
2493                                return 0;
2494                        break;
2495                case S_IFDIR:
2496                        /*
2497                         * Optimize away all write operations, since the server
2498                         * will check permissions when we perform the op.
2499                         */
2500                        if ((mask & MAY_WRITE) && !(mask & MAY_READ))
2501                                goto out;
2502        }
2503
2504force_lookup:
2505        if (!NFS_PROTO(inode)->access)
2506                goto out_notsup;
2507
2508        /* Always try fast lookups first */
2509        rcu_read_lock();
2510        cred = rpc_lookup_cred_nonblock();
2511        if (!IS_ERR(cred))
2512                res = nfs_do_access(inode, cred, mask|MAY_NOT_BLOCK);
2513        else
2514                res = PTR_ERR(cred);
2515        rcu_read_unlock();
2516        if (res == -ECHILD && !(mask & MAY_NOT_BLOCK)) {
2517                /* Fast lookup failed, try the slow way */
2518                cred = rpc_lookup_cred();
2519                if (!IS_ERR(cred)) {
2520                        res = nfs_do_access(inode, cred, mask);
2521                        put_rpccred(cred);
2522                } else
2523                        res = PTR_ERR(cred);
2524        }
2525out:
2526        if (!res && (mask & MAY_EXEC))
2527                res = nfs_execute_ok(inode, mask);
2528
2529        dfprintk(VFS, "NFS: permission(%s/%lu), mask=0x%x, res=%d\n",
2530                inode->i_sb->s_id, inode->i_ino, mask, res);
2531        return res;
2532out_notsup:
2533        if (mask & MAY_NOT_BLOCK)
2534                return -ECHILD;
2535
2536        res = nfs_revalidate_inode(NFS_SERVER(inode), inode);
2537        if (res == 0)
2538                res = generic_permission(inode, mask);
2539        goto out;
2540}
2541EXPORT_SYMBOL_GPL(nfs_permission);
2542
2543/*
2544 * Local variables:
2545 *  version-control: t
2546 *  kept-new-versions: 5
2547 * End:
2548 */
2549