Merge branch 'for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git/dtor/input
[sfrench/cifs-2.6.git] / fs / nfs / dir.c
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/time.h>
21 #include <linux/errno.h>
22 #include <linux/stat.h>
23 #include <linux/fcntl.h>
24 #include <linux/string.h>
25 #include <linux/kernel.h>
26 #include <linux/slab.h>
27 #include <linux/mm.h>
28 #include <linux/sunrpc/clnt.h>
29 #include <linux/nfs_fs.h>
30 #include <linux/nfs_mount.h>
31 #include <linux/pagemap.h>
32 #include <linux/smp_lock.h>
33 #include <linux/pagevec.h>
34 #include <linux/namei.h>
35 #include <linux/mount.h>
36 #include <linux/sched.h>
37
38 #include "nfs4_fs.h"
39 #include "delegation.h"
40 #include "iostat.h"
41 #include "internal.h"
42
43 /* #define NFS_DEBUG_VERBOSE 1 */
44
45 static int nfs_opendir(struct inode *, struct file *);
46 static int nfs_readdir(struct file *, void *, filldir_t);
47 static struct dentry *nfs_lookup(struct inode *, struct dentry *, struct nameidata *);
48 static int nfs_create(struct inode *, struct dentry *, int, struct nameidata *);
49 static int nfs_mkdir(struct inode *, struct dentry *, int);
50 static int nfs_rmdir(struct inode *, struct dentry *);
51 static int nfs_unlink(struct inode *, struct dentry *);
52 static int nfs_symlink(struct inode *, struct dentry *, const char *);
53 static int nfs_link(struct dentry *, struct inode *, struct dentry *);
54 static int nfs_mknod(struct inode *, struct dentry *, int, dev_t);
55 static int nfs_rename(struct inode *, struct dentry *,
56                       struct inode *, struct dentry *);
57 static int nfs_fsync_dir(struct file *, struct dentry *, int);
58 static loff_t nfs_llseek_dir(struct file *, loff_t, int);
59
60 const struct file_operations nfs_dir_operations = {
61         .llseek         = nfs_llseek_dir,
62         .read           = generic_read_dir,
63         .readdir        = nfs_readdir,
64         .open           = nfs_opendir,
65         .release        = nfs_release,
66         .fsync          = nfs_fsync_dir,
67 };
68
69 const struct inode_operations nfs_dir_inode_operations = {
70         .create         = nfs_create,
71         .lookup         = nfs_lookup,
72         .link           = nfs_link,
73         .unlink         = nfs_unlink,
74         .symlink        = nfs_symlink,
75         .mkdir          = nfs_mkdir,
76         .rmdir          = nfs_rmdir,
77         .mknod          = nfs_mknod,
78         .rename         = nfs_rename,
79         .permission     = nfs_permission,
80         .getattr        = nfs_getattr,
81         .setattr        = nfs_setattr,
82 };
83
84 #ifdef CONFIG_NFS_V3
85 const struct inode_operations nfs3_dir_inode_operations = {
86         .create         = nfs_create,
87         .lookup         = nfs_lookup,
88         .link           = nfs_link,
89         .unlink         = nfs_unlink,
90         .symlink        = nfs_symlink,
91         .mkdir          = nfs_mkdir,
92         .rmdir          = nfs_rmdir,
93         .mknod          = nfs_mknod,
94         .rename         = nfs_rename,
95         .permission     = nfs_permission,
96         .getattr        = nfs_getattr,
97         .setattr        = nfs_setattr,
98         .listxattr      = nfs3_listxattr,
99         .getxattr       = nfs3_getxattr,
100         .setxattr       = nfs3_setxattr,
101         .removexattr    = nfs3_removexattr,
102 };
103 #endif  /* CONFIG_NFS_V3 */
104
105 #ifdef CONFIG_NFS_V4
106
107 static struct dentry *nfs_atomic_lookup(struct inode *, struct dentry *, struct nameidata *);
108 const struct inode_operations nfs4_dir_inode_operations = {
109         .create         = nfs_create,
110         .lookup         = nfs_atomic_lookup,
111         .link           = nfs_link,
112         .unlink         = nfs_unlink,
113         .symlink        = nfs_symlink,
114         .mkdir          = nfs_mkdir,
115         .rmdir          = nfs_rmdir,
116         .mknod          = nfs_mknod,
117         .rename         = nfs_rename,
118         .permission     = nfs_permission,
119         .getattr        = nfs_getattr,
120         .setattr        = nfs_setattr,
121         .getxattr       = nfs4_getxattr,
122         .setxattr       = nfs4_setxattr,
123         .listxattr      = nfs4_listxattr,
124 };
125
126 #endif /* CONFIG_NFS_V4 */
127
128 /*
129  * Open file
130  */
131 static int
132 nfs_opendir(struct inode *inode, struct file *filp)
133 {
134         int res;
135
136         dfprintk(VFS, "NFS: opendir(%s/%ld)\n",
137                         inode->i_sb->s_id, inode->i_ino);
138
139         lock_kernel();
140         /* Call generic open code in order to cache credentials */
141         res = nfs_open(inode, filp);
142         unlock_kernel();
143         return res;
144 }
145
146 typedef __be32 * (*decode_dirent_t)(__be32 *, struct nfs_entry *, int);
147 typedef struct {
148         struct file     *file;
149         struct page     *page;
150         unsigned long   page_index;
151         __be32          *ptr;
152         u64             *dir_cookie;
153         loff_t          current_index;
154         struct nfs_entry *entry;
155         decode_dirent_t decode;
156         int             plus;
157         int             error;
158         unsigned long   timestamp;
159         int             timestamp_valid;
160 } nfs_readdir_descriptor_t;
161
162 /* Now we cache directories properly, by stuffing the dirent
163  * data directly in the page cache.
164  *
165  * Inode invalidation due to refresh etc. takes care of
166  * _everything_, no sloppy entry flushing logic, no extraneous
167  * copying, network direct to page cache, the way it was meant
168  * to be.
169  *
170  * NOTE: Dirent information verification is done always by the
171  *       page-in of the RPC reply, nowhere else, this simplies
172  *       things substantially.
173  */
174 static
175 int nfs_readdir_filler(nfs_readdir_descriptor_t *desc, struct page *page)
176 {
177         struct file     *file = desc->file;
178         struct inode    *inode = file->f_path.dentry->d_inode;
179         struct rpc_cred *cred = nfs_file_cred(file);
180         unsigned long   timestamp;
181         int             error;
182
183         dfprintk(DIRCACHE, "NFS: %s: reading cookie %Lu into page %lu\n",
184                         __FUNCTION__, (long long)desc->entry->cookie,
185                         page->index);
186
187  again:
188         timestamp = jiffies;
189         error = NFS_PROTO(inode)->readdir(file->f_path.dentry, cred, desc->entry->cookie, page,
190                                           NFS_SERVER(inode)->dtsize, desc->plus);
191         if (error < 0) {
192                 /* We requested READDIRPLUS, but the server doesn't grok it */
193                 if (error == -ENOTSUPP && desc->plus) {
194                         NFS_SERVER(inode)->caps &= ~NFS_CAP_READDIRPLUS;
195                         clear_bit(NFS_INO_ADVISE_RDPLUS, &NFS_FLAGS(inode));
196                         desc->plus = 0;
197                         goto again;
198                 }
199                 goto error;
200         }
201         desc->timestamp = timestamp;
202         desc->timestamp_valid = 1;
203         SetPageUptodate(page);
204         /* Ensure consistent page alignment of the data.
205          * Note: assumes we have exclusive access to this mapping either
206          *       through inode->i_mutex or some other mechanism.
207          */
208         if (page->index == 0 && invalidate_inode_pages2_range(inode->i_mapping, PAGE_CACHE_SIZE, -1) < 0) {
209                 /* Should never happen */
210                 nfs_zap_mapping(inode, inode->i_mapping);
211         }
212         unlock_page(page);
213         return 0;
214  error:
215         unlock_page(page);
216         desc->error = error;
217         return -EIO;
218 }
219
220 static inline
221 int dir_decode(nfs_readdir_descriptor_t *desc)
222 {
223         __be32  *p = desc->ptr;
224         p = desc->decode(p, desc->entry, desc->plus);
225         if (IS_ERR(p))
226                 return PTR_ERR(p);
227         desc->ptr = p;
228         if (desc->timestamp_valid)
229                 desc->entry->fattr->time_start = desc->timestamp;
230         else
231                 desc->entry->fattr->valid &= ~NFS_ATTR_FATTR;
232         return 0;
233 }
234
235 static inline
236 void dir_page_release(nfs_readdir_descriptor_t *desc)
237 {
238         kunmap(desc->page);
239         page_cache_release(desc->page);
240         desc->page = NULL;
241         desc->ptr = NULL;
242 }
243
244 /*
245  * Given a pointer to a buffer that has already been filled by a call
246  * to readdir, find the next entry with cookie '*desc->dir_cookie'.
247  *
248  * If the end of the buffer has been reached, return -EAGAIN, if not,
249  * return the offset within the buffer of the next entry to be
250  * read.
251  */
252 static inline
253 int find_dirent(nfs_readdir_descriptor_t *desc)
254 {
255         struct nfs_entry *entry = desc->entry;
256         int             loop_count = 0,
257                         status;
258
259         while((status = dir_decode(desc)) == 0) {
260                 dfprintk(DIRCACHE, "NFS: %s: examining cookie %Lu\n",
261                                 __FUNCTION__, (unsigned long long)entry->cookie);
262                 if (entry->prev_cookie == *desc->dir_cookie)
263                         break;
264                 if (loop_count++ > 200) {
265                         loop_count = 0;
266                         schedule();
267                 }
268         }
269         return status;
270 }
271
272 /*
273  * Given a pointer to a buffer that has already been filled by a call
274  * to readdir, find the entry at offset 'desc->file->f_pos'.
275  *
276  * If the end of the buffer has been reached, return -EAGAIN, if not,
277  * return the offset within the buffer of the next entry to be
278  * read.
279  */
280 static inline
281 int find_dirent_index(nfs_readdir_descriptor_t *desc)
282 {
283         struct nfs_entry *entry = desc->entry;
284         int             loop_count = 0,
285                         status;
286
287         for(;;) {
288                 status = dir_decode(desc);
289                 if (status)
290                         break;
291
292                 dfprintk(DIRCACHE, "NFS: found cookie %Lu at index %Ld\n",
293                                 (unsigned long long)entry->cookie, desc->current_index);
294
295                 if (desc->file->f_pos == desc->current_index) {
296                         *desc->dir_cookie = entry->cookie;
297                         break;
298                 }
299                 desc->current_index++;
300                 if (loop_count++ > 200) {
301                         loop_count = 0;
302                         schedule();
303                 }
304         }
305         return status;
306 }
307
308 /*
309  * Find the given page, and call find_dirent() or find_dirent_index in
310  * order to try to return the next entry.
311  */
312 static inline
313 int find_dirent_page(nfs_readdir_descriptor_t *desc)
314 {
315         struct inode    *inode = desc->file->f_path.dentry->d_inode;
316         struct page     *page;
317         int             status;
318
319         dfprintk(DIRCACHE, "NFS: %s: searching page %ld for target %Lu\n",
320                         __FUNCTION__, desc->page_index,
321                         (long long) *desc->dir_cookie);
322
323         /* If we find the page in the page_cache, we cannot be sure
324          * how fresh the data is, so we will ignore readdir_plus attributes.
325          */
326         desc->timestamp_valid = 0;
327         page = read_cache_page(inode->i_mapping, desc->page_index,
328                                (filler_t *)nfs_readdir_filler, desc);
329         if (IS_ERR(page)) {
330                 status = PTR_ERR(page);
331                 goto out;
332         }
333
334         /* NOTE: Someone else may have changed the READDIRPLUS flag */
335         desc->page = page;
336         desc->ptr = kmap(page);         /* matching kunmap in nfs_do_filldir */
337         if (*desc->dir_cookie != 0)
338                 status = find_dirent(desc);
339         else
340                 status = find_dirent_index(desc);
341         if (status < 0)
342                 dir_page_release(desc);
343  out:
344         dfprintk(DIRCACHE, "NFS: %s: returns %d\n", __FUNCTION__, status);
345         return status;
346 }
347
348 /*
349  * Recurse through the page cache pages, and return a
350  * filled nfs_entry structure of the next directory entry if possible.
351  *
352  * The target for the search is '*desc->dir_cookie' if non-0,
353  * 'desc->file->f_pos' otherwise
354  */
355 static inline
356 int readdir_search_pagecache(nfs_readdir_descriptor_t *desc)
357 {
358         int             loop_count = 0;
359         int             res;
360
361         /* Always search-by-index from the beginning of the cache */
362         if (*desc->dir_cookie == 0) {
363                 dfprintk(DIRCACHE, "NFS: readdir_search_pagecache() searching for offset %Ld\n",
364                                 (long long)desc->file->f_pos);
365                 desc->page_index = 0;
366                 desc->entry->cookie = desc->entry->prev_cookie = 0;
367                 desc->entry->eof = 0;
368                 desc->current_index = 0;
369         } else
370                 dfprintk(DIRCACHE, "NFS: readdir_search_pagecache() searching for cookie %Lu\n",
371                                 (unsigned long long)*desc->dir_cookie);
372
373         for (;;) {
374                 res = find_dirent_page(desc);
375                 if (res != -EAGAIN)
376                         break;
377                 /* Align to beginning of next page */
378                 desc->page_index ++;
379                 if (loop_count++ > 200) {
380                         loop_count = 0;
381                         schedule();
382                 }
383         }
384
385         dfprintk(DIRCACHE, "NFS: %s: returns %d\n", __FUNCTION__, res);
386         return res;
387 }
388
389 static inline unsigned int dt_type(struct inode *inode)
390 {
391         return (inode->i_mode >> 12) & 15;
392 }
393
394 static struct dentry *nfs_readdir_lookup(nfs_readdir_descriptor_t *desc);
395
396 /*
397  * Once we've found the start of the dirent within a page: fill 'er up...
398  */
399 static 
400 int nfs_do_filldir(nfs_readdir_descriptor_t *desc, void *dirent,
401                    filldir_t filldir)
402 {
403         struct file     *file = desc->file;
404         struct nfs_entry *entry = desc->entry;
405         struct dentry   *dentry = NULL;
406         u64             fileid;
407         int             loop_count = 0,
408                         res;
409
410         dfprintk(DIRCACHE, "NFS: nfs_do_filldir() filling starting @ cookie %Lu\n",
411                         (unsigned long long)entry->cookie);
412
413         for(;;) {
414                 unsigned d_type = DT_UNKNOWN;
415                 /* Note: entry->prev_cookie contains the cookie for
416                  *       retrieving the current dirent on the server */
417                 fileid = entry->ino;
418
419                 /* Get a dentry if we have one */
420                 if (dentry != NULL)
421                         dput(dentry);
422                 dentry = nfs_readdir_lookup(desc);
423
424                 /* Use readdirplus info */
425                 if (dentry != NULL && dentry->d_inode != NULL) {
426                         d_type = dt_type(dentry->d_inode);
427                         fileid = NFS_FILEID(dentry->d_inode);
428                 }
429
430                 res = filldir(dirent, entry->name, entry->len, 
431                               file->f_pos, nfs_compat_user_ino64(fileid),
432                               d_type);
433                 if (res < 0)
434                         break;
435                 file->f_pos++;
436                 *desc->dir_cookie = entry->cookie;
437                 if (dir_decode(desc) != 0) {
438                         desc->page_index ++;
439                         break;
440                 }
441                 if (loop_count++ > 200) {
442                         loop_count = 0;
443                         schedule();
444                 }
445         }
446         dir_page_release(desc);
447         if (dentry != NULL)
448                 dput(dentry);
449         dfprintk(DIRCACHE, "NFS: nfs_do_filldir() filling ended @ cookie %Lu; returning = %d\n",
450                         (unsigned long long)*desc->dir_cookie, res);
451         return res;
452 }
453
454 /*
455  * If we cannot find a cookie in our cache, we suspect that this is
456  * because it points to a deleted file, so we ask the server to return
457  * whatever it thinks is the next entry. We then feed this to filldir.
458  * If all goes well, we should then be able to find our way round the
459  * cache on the next call to readdir_search_pagecache();
460  *
461  * NOTE: we cannot add the anonymous page to the pagecache because
462  *       the data it contains might not be page aligned. Besides,
463  *       we should already have a complete representation of the
464  *       directory in the page cache by the time we get here.
465  */
466 static inline
467 int uncached_readdir(nfs_readdir_descriptor_t *desc, void *dirent,
468                      filldir_t filldir)
469 {
470         struct file     *file = desc->file;
471         struct inode    *inode = file->f_path.dentry->d_inode;
472         struct rpc_cred *cred = nfs_file_cred(file);
473         struct page     *page = NULL;
474         int             status;
475         unsigned long   timestamp;
476
477         dfprintk(DIRCACHE, "NFS: uncached_readdir() searching for cookie %Lu\n",
478                         (unsigned long long)*desc->dir_cookie);
479
480         page = alloc_page(GFP_HIGHUSER);
481         if (!page) {
482                 status = -ENOMEM;
483                 goto out;
484         }
485         timestamp = jiffies;
486         desc->error = NFS_PROTO(inode)->readdir(file->f_path.dentry, cred, *desc->dir_cookie,
487                                                 page,
488                                                 NFS_SERVER(inode)->dtsize,
489                                                 desc->plus);
490         desc->page = page;
491         desc->ptr = kmap(page);         /* matching kunmap in nfs_do_filldir */
492         if (desc->error >= 0) {
493                 desc->timestamp = timestamp;
494                 desc->timestamp_valid = 1;
495                 if ((status = dir_decode(desc)) == 0)
496                         desc->entry->prev_cookie = *desc->dir_cookie;
497         } else
498                 status = -EIO;
499         if (status < 0)
500                 goto out_release;
501
502         status = nfs_do_filldir(desc, dirent, filldir);
503
504         /* Reset read descriptor so it searches the page cache from
505          * the start upon the next call to readdir_search_pagecache() */
506         desc->page_index = 0;
507         desc->entry->cookie = desc->entry->prev_cookie = 0;
508         desc->entry->eof = 0;
509  out:
510         dfprintk(DIRCACHE, "NFS: %s: returns %d\n",
511                         __FUNCTION__, status);
512         return status;
513  out_release:
514         dir_page_release(desc);
515         goto out;
516 }
517
518 /* The file offset position represents the dirent entry number.  A
519    last cookie cache takes care of the common case of reading the
520    whole directory.
521  */
522 static int nfs_readdir(struct file *filp, void *dirent, filldir_t filldir)
523 {
524         struct dentry   *dentry = filp->f_path.dentry;
525         struct inode    *inode = dentry->d_inode;
526         nfs_readdir_descriptor_t my_desc,
527                         *desc = &my_desc;
528         struct nfs_entry my_entry;
529         struct nfs_fh    fh;
530         struct nfs_fattr fattr;
531         long            res;
532
533         dfprintk(VFS, "NFS: readdir(%s/%s) starting at cookie %Lu\n",
534                         dentry->d_parent->d_name.name, dentry->d_name.name,
535                         (long long)filp->f_pos);
536         nfs_inc_stats(inode, NFSIOS_VFSGETDENTS);
537
538         lock_kernel();
539
540         res = nfs_revalidate_mapping_nolock(inode, filp->f_mapping);
541         if (res < 0) {
542                 unlock_kernel();
543                 return res;
544         }
545
546         /*
547          * filp->f_pos points to the dirent entry number.
548          * *desc->dir_cookie has the cookie for the next entry. We have
549          * to either find the entry with the appropriate number or
550          * revalidate the cookie.
551          */
552         memset(desc, 0, sizeof(*desc));
553
554         desc->file = filp;
555         desc->dir_cookie = &nfs_file_open_context(filp)->dir_cookie;
556         desc->decode = NFS_PROTO(inode)->decode_dirent;
557         desc->plus = NFS_USE_READDIRPLUS(inode);
558
559         my_entry.cookie = my_entry.prev_cookie = 0;
560         my_entry.eof = 0;
561         my_entry.fh = &fh;
562         my_entry.fattr = &fattr;
563         nfs_fattr_init(&fattr);
564         desc->entry = &my_entry;
565
566         nfs_block_sillyrename(dentry);
567         while(!desc->entry->eof) {
568                 res = readdir_search_pagecache(desc);
569
570                 if (res == -EBADCOOKIE) {
571                         /* This means either end of directory */
572                         if (*desc->dir_cookie && desc->entry->cookie != *desc->dir_cookie) {
573                                 /* Or that the server has 'lost' a cookie */
574                                 res = uncached_readdir(desc, dirent, filldir);
575                                 if (res >= 0)
576                                         continue;
577                         }
578                         res = 0;
579                         break;
580                 }
581                 if (res == -ETOOSMALL && desc->plus) {
582                         clear_bit(NFS_INO_ADVISE_RDPLUS, &NFS_FLAGS(inode));
583                         nfs_zap_caches(inode);
584                         desc->plus = 0;
585                         desc->entry->eof = 0;
586                         continue;
587                 }
588                 if (res < 0)
589                         break;
590
591                 res = nfs_do_filldir(desc, dirent, filldir);
592                 if (res < 0) {
593                         res = 0;
594                         break;
595                 }
596         }
597         nfs_unblock_sillyrename(dentry);
598         unlock_kernel();
599         if (res > 0)
600                 res = 0;
601         dfprintk(VFS, "NFS: readdir(%s/%s) returns %ld\n",
602                         dentry->d_parent->d_name.name, dentry->d_name.name,
603                         res);
604         return res;
605 }
606
607 static loff_t nfs_llseek_dir(struct file *filp, loff_t offset, int origin)
608 {
609         mutex_lock(&filp->f_path.dentry->d_inode->i_mutex);
610         switch (origin) {
611                 case 1:
612                         offset += filp->f_pos;
613                 case 0:
614                         if (offset >= 0)
615                                 break;
616                 default:
617                         offset = -EINVAL;
618                         goto out;
619         }
620         if (offset != filp->f_pos) {
621                 filp->f_pos = offset;
622                 nfs_file_open_context(filp)->dir_cookie = 0;
623         }
624 out:
625         mutex_unlock(&filp->f_path.dentry->d_inode->i_mutex);
626         return offset;
627 }
628
629 /*
630  * All directory operations under NFS are synchronous, so fsync()
631  * is a dummy operation.
632  */
633 static int nfs_fsync_dir(struct file *filp, struct dentry *dentry, int datasync)
634 {
635         dfprintk(VFS, "NFS: fsync_dir(%s/%s) datasync %d\n",
636                         dentry->d_parent->d_name.name, dentry->d_name.name,
637                         datasync);
638
639         return 0;
640 }
641
642 /*
643  * A check for whether or not the parent directory has changed.
644  * In the case it has, we assume that the dentries are untrustworthy
645  * and may need to be looked up again.
646  */
647 static int nfs_check_verifier(struct inode *dir, struct dentry *dentry)
648 {
649         if (IS_ROOT(dentry))
650                 return 1;
651         if (!nfs_verify_change_attribute(dir, dentry->d_time))
652                 return 0;
653         /* Revalidate nfsi->cache_change_attribute before we declare a match */
654         if (nfs_revalidate_inode(NFS_SERVER(dir), dir) < 0)
655                 return 0;
656         if (!nfs_verify_change_attribute(dir, dentry->d_time))
657                 return 0;
658         return 1;
659 }
660
661 /*
662  * Return the intent data that applies to this particular path component
663  *
664  * Note that the current set of intents only apply to the very last
665  * component of the path.
666  * We check for this using LOOKUP_CONTINUE and LOOKUP_PARENT.
667  */
668 static inline unsigned int nfs_lookup_check_intent(struct nameidata *nd, unsigned int mask)
669 {
670         if (nd->flags & (LOOKUP_CONTINUE|LOOKUP_PARENT))
671                 return 0;
672         return nd->flags & mask;
673 }
674
675 /*
676  * Use intent information to check whether or not we're going to do
677  * an O_EXCL create using this path component.
678  */
679 static int nfs_is_exclusive_create(struct inode *dir, struct nameidata *nd)
680 {
681         if (NFS_PROTO(dir)->version == 2)
682                 return 0;
683         if (nd == NULL || nfs_lookup_check_intent(nd, LOOKUP_CREATE) == 0)
684                 return 0;
685         return (nd->intent.open.flags & O_EXCL) != 0;
686 }
687
688 /*
689  * Inode and filehandle revalidation for lookups.
690  *
691  * We force revalidation in the cases where the VFS sets LOOKUP_REVAL,
692  * or if the intent information indicates that we're about to open this
693  * particular file and the "nocto" mount flag is not set.
694  *
695  */
696 static inline
697 int nfs_lookup_verify_inode(struct inode *inode, struct nameidata *nd)
698 {
699         struct nfs_server *server = NFS_SERVER(inode);
700
701         if (nd != NULL) {
702                 /* VFS wants an on-the-wire revalidation */
703                 if (nd->flags & LOOKUP_REVAL)
704                         goto out_force;
705                 /* This is an open(2) */
706                 if (nfs_lookup_check_intent(nd, LOOKUP_OPEN) != 0 &&
707                                 !(server->flags & NFS_MOUNT_NOCTO) &&
708                                 (S_ISREG(inode->i_mode) ||
709                                  S_ISDIR(inode->i_mode)))
710                         goto out_force;
711                 return 0;
712         }
713         return nfs_revalidate_inode(server, inode);
714 out_force:
715         return __nfs_revalidate_inode(server, inode);
716 }
717
718 /*
719  * We judge how long we want to trust negative
720  * dentries by looking at the parent inode mtime.
721  *
722  * If parent mtime has changed, we revalidate, else we wait for a
723  * period corresponding to the parent's attribute cache timeout value.
724  */
725 static inline
726 int nfs_neg_need_reval(struct inode *dir, struct dentry *dentry,
727                        struct nameidata *nd)
728 {
729         /* Don't revalidate a negative dentry if we're creating a new file */
730         if (nd != NULL && nfs_lookup_check_intent(nd, LOOKUP_CREATE) != 0)
731                 return 0;
732         return !nfs_check_verifier(dir, dentry);
733 }
734
735 /*
736  * This is called every time the dcache has a lookup hit,
737  * and we should check whether we can really trust that
738  * lookup.
739  *
740  * NOTE! The hit can be a negative hit too, don't assume
741  * we have an inode!
742  *
743  * If the parent directory is seen to have changed, we throw out the
744  * cached dentry and do a new lookup.
745  */
746 static int nfs_lookup_revalidate(struct dentry * dentry, struct nameidata *nd)
747 {
748         struct inode *dir;
749         struct inode *inode;
750         struct dentry *parent;
751         int error;
752         struct nfs_fh fhandle;
753         struct nfs_fattr fattr;
754
755         parent = dget_parent(dentry);
756         lock_kernel();
757         dir = parent->d_inode;
758         nfs_inc_stats(dir, NFSIOS_DENTRYREVALIDATE);
759         inode = dentry->d_inode;
760
761         if (!inode) {
762                 if (nfs_neg_need_reval(dir, dentry, nd))
763                         goto out_bad;
764                 goto out_valid;
765         }
766
767         if (is_bad_inode(inode)) {
768                 dfprintk(LOOKUPCACHE, "%s: %s/%s has dud inode\n",
769                                 __FUNCTION__, dentry->d_parent->d_name.name,
770                                 dentry->d_name.name);
771                 goto out_bad;
772         }
773
774         /* Force a full look up iff the parent directory has changed */
775         if (!nfs_is_exclusive_create(dir, nd) && nfs_check_verifier(dir, dentry)) {
776                 if (nfs_lookup_verify_inode(inode, nd))
777                         goto out_zap_parent;
778                 goto out_valid;
779         }
780
781         if (NFS_STALE(inode))
782                 goto out_bad;
783
784         error = NFS_PROTO(dir)->lookup(dir, &dentry->d_name, &fhandle, &fattr);
785         if (error)
786                 goto out_bad;
787         if (nfs_compare_fh(NFS_FH(inode), &fhandle))
788                 goto out_bad;
789         if ((error = nfs_refresh_inode(inode, &fattr)) != 0)
790                 goto out_bad;
791
792         nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
793  out_valid:
794         unlock_kernel();
795         dput(parent);
796         dfprintk(LOOKUPCACHE, "NFS: %s(%s/%s) is valid\n",
797                         __FUNCTION__, dentry->d_parent->d_name.name,
798                         dentry->d_name.name);
799         return 1;
800 out_zap_parent:
801         nfs_zap_caches(dir);
802  out_bad:
803         nfs_mark_for_revalidate(dir);
804         if (inode && S_ISDIR(inode->i_mode)) {
805                 /* Purge readdir caches. */
806                 nfs_zap_caches(inode);
807                 /* If we have submounts, don't unhash ! */
808                 if (have_submounts(dentry))
809                         goto out_valid;
810                 shrink_dcache_parent(dentry);
811         }
812         d_drop(dentry);
813         unlock_kernel();
814         dput(parent);
815         dfprintk(LOOKUPCACHE, "NFS: %s(%s/%s) is invalid\n",
816                         __FUNCTION__, dentry->d_parent->d_name.name,
817                         dentry->d_name.name);
818         return 0;
819 }
820
821 /*
822  * This is called from dput() when d_count is going to 0.
823  */
824 static int nfs_dentry_delete(struct dentry *dentry)
825 {
826         dfprintk(VFS, "NFS: dentry_delete(%s/%s, %x)\n",
827                 dentry->d_parent->d_name.name, dentry->d_name.name,
828                 dentry->d_flags);
829
830         if (dentry->d_flags & DCACHE_NFSFS_RENAMED) {
831                 /* Unhash it, so that ->d_iput() would be called */
832                 return 1;
833         }
834         if (!(dentry->d_sb->s_flags & MS_ACTIVE)) {
835                 /* Unhash it, so that ancestors of killed async unlink
836                  * files will be cleaned up during umount */
837                 return 1;
838         }
839         return 0;
840
841 }
842
843 /*
844  * Called when the dentry loses inode.
845  * We use it to clean up silly-renamed files.
846  */
847 static void nfs_dentry_iput(struct dentry *dentry, struct inode *inode)
848 {
849         nfs_inode_return_delegation(inode);
850         if (S_ISDIR(inode->i_mode))
851                 /* drop any readdir cache as it could easily be old */
852                 NFS_I(inode)->cache_validity |= NFS_INO_INVALID_DATA;
853
854         if (dentry->d_flags & DCACHE_NFSFS_RENAMED) {
855                 lock_kernel();
856                 drop_nlink(inode);
857                 nfs_complete_unlink(dentry, inode);
858                 unlock_kernel();
859         }
860         iput(inode);
861 }
862
863 struct dentry_operations nfs_dentry_operations = {
864         .d_revalidate   = nfs_lookup_revalidate,
865         .d_delete       = nfs_dentry_delete,
866         .d_iput         = nfs_dentry_iput,
867 };
868
869 static struct dentry *nfs_lookup(struct inode *dir, struct dentry * dentry, struct nameidata *nd)
870 {
871         struct dentry *res;
872         struct dentry *parent;
873         struct inode *inode = NULL;
874         int error;
875         struct nfs_fh fhandle;
876         struct nfs_fattr fattr;
877
878         dfprintk(VFS, "NFS: lookup(%s/%s)\n",
879                 dentry->d_parent->d_name.name, dentry->d_name.name);
880         nfs_inc_stats(dir, NFSIOS_VFSLOOKUP);
881
882         res = ERR_PTR(-ENAMETOOLONG);
883         if (dentry->d_name.len > NFS_SERVER(dir)->namelen)
884                 goto out;
885
886         res = ERR_PTR(-ENOMEM);
887         dentry->d_op = NFS_PROTO(dir)->dentry_ops;
888
889         lock_kernel();
890
891         /*
892          * If we're doing an exclusive create, optimize away the lookup
893          * but don't hash the dentry.
894          */
895         if (nfs_is_exclusive_create(dir, nd)) {
896                 d_instantiate(dentry, NULL);
897                 res = NULL;
898                 goto out_unlock;
899         }
900
901         parent = dentry->d_parent;
902         /* Protect against concurrent sillydeletes */
903         nfs_block_sillyrename(parent);
904         error = NFS_PROTO(dir)->lookup(dir, &dentry->d_name, &fhandle, &fattr);
905         if (error == -ENOENT)
906                 goto no_entry;
907         if (error < 0) {
908                 res = ERR_PTR(error);
909                 goto out_unblock_sillyrename;
910         }
911         inode = nfs_fhget(dentry->d_sb, &fhandle, &fattr);
912         res = (struct dentry *)inode;
913         if (IS_ERR(res))
914                 goto out_unblock_sillyrename;
915
916 no_entry:
917         res = d_materialise_unique(dentry, inode);
918         if (res != NULL) {
919                 if (IS_ERR(res))
920                         goto out_unblock_sillyrename;
921                 dentry = res;
922         }
923         nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
924 out_unblock_sillyrename:
925         nfs_unblock_sillyrename(parent);
926 out_unlock:
927         unlock_kernel();
928 out:
929         return res;
930 }
931
932 #ifdef CONFIG_NFS_V4
933 static int nfs_open_revalidate(struct dentry *, struct nameidata *);
934
935 struct dentry_operations nfs4_dentry_operations = {
936         .d_revalidate   = nfs_open_revalidate,
937         .d_delete       = nfs_dentry_delete,
938         .d_iput         = nfs_dentry_iput,
939 };
940
941 /*
942  * Use intent information to determine whether we need to substitute
943  * the NFSv4-style stateful OPEN for the LOOKUP call
944  */
945 static int is_atomic_open(struct inode *dir, struct nameidata *nd)
946 {
947         if (nd == NULL || nfs_lookup_check_intent(nd, LOOKUP_OPEN) == 0)
948                 return 0;
949         /* NFS does not (yet) have a stateful open for directories */
950         if (nd->flags & LOOKUP_DIRECTORY)
951                 return 0;
952         /* Are we trying to write to a read only partition? */
953         if (IS_RDONLY(dir) && (nd->intent.open.flags & (O_CREAT|O_TRUNC|FMODE_WRITE)))
954                 return 0;
955         return 1;
956 }
957
958 static struct dentry *nfs_atomic_lookup(struct inode *dir, struct dentry *dentry, struct nameidata *nd)
959 {
960         struct dentry *res = NULL;
961         int error;
962
963         dfprintk(VFS, "NFS: atomic_lookup(%s/%ld), %s\n",
964                         dir->i_sb->s_id, dir->i_ino, dentry->d_name.name);
965
966         /* Check that we are indeed trying to open this file */
967         if (!is_atomic_open(dir, nd))
968                 goto no_open;
969
970         if (dentry->d_name.len > NFS_SERVER(dir)->namelen) {
971                 res = ERR_PTR(-ENAMETOOLONG);
972                 goto out;
973         }
974         dentry->d_op = NFS_PROTO(dir)->dentry_ops;
975
976         /* Let vfs_create() deal with O_EXCL. Instantiate, but don't hash
977          * the dentry. */
978         if (nd->intent.open.flags & O_EXCL) {
979                 d_instantiate(dentry, NULL);
980                 goto out;
981         }
982
983         /* Open the file on the server */
984         lock_kernel();
985         res = nfs4_atomic_open(dir, dentry, nd);
986         unlock_kernel();
987         if (IS_ERR(res)) {
988                 error = PTR_ERR(res);
989                 switch (error) {
990                         /* Make a negative dentry */
991                         case -ENOENT:
992                                 res = NULL;
993                                 goto out;
994                         /* This turned out not to be a regular file */
995                         case -EISDIR:
996                         case -ENOTDIR:
997                                 goto no_open;
998                         case -ELOOP:
999                                 if (!(nd->intent.open.flags & O_NOFOLLOW))
1000                                         goto no_open;
1001                         /* case -EINVAL: */
1002                         default:
1003                                 goto out;
1004                 }
1005         } else if (res != NULL)
1006                 dentry = res;
1007 out:
1008         return res;
1009 no_open:
1010         return nfs_lookup(dir, dentry, nd);
1011 }
1012
1013 static int nfs_open_revalidate(struct dentry *dentry, struct nameidata *nd)
1014 {
1015         struct dentry *parent = NULL;
1016         struct inode *inode = dentry->d_inode;
1017         struct inode *dir;
1018         int openflags, ret = 0;
1019
1020         parent = dget_parent(dentry);
1021         dir = parent->d_inode;
1022         if (!is_atomic_open(dir, nd))
1023                 goto no_open;
1024         /* We can't create new files in nfs_open_revalidate(), so we
1025          * optimize away revalidation of negative dentries.
1026          */
1027         if (inode == NULL) {
1028                 if (!nfs_neg_need_reval(dir, dentry, nd))
1029                         ret = 1;
1030                 goto out;
1031         }
1032
1033         /* NFS only supports OPEN on regular files */
1034         if (!S_ISREG(inode->i_mode))
1035                 goto no_open;
1036         openflags = nd->intent.open.flags;
1037         /* We cannot do exclusive creation on a positive dentry */
1038         if ((openflags & (O_CREAT|O_EXCL)) == (O_CREAT|O_EXCL))
1039                 goto no_open;
1040         /* We can't create new files, or truncate existing ones here */
1041         openflags &= ~(O_CREAT|O_TRUNC);
1042
1043         /*
1044          * Note: we're not holding inode->i_mutex and so may be racing with
1045          * operations that change the directory. We therefore save the
1046          * change attribute *before* we do the RPC call.
1047          */
1048         lock_kernel();
1049         ret = nfs4_open_revalidate(dir, dentry, openflags, nd);
1050         unlock_kernel();
1051 out:
1052         dput(parent);
1053         if (!ret)
1054                 d_drop(dentry);
1055         return ret;
1056 no_open:
1057         dput(parent);
1058         if (inode != NULL && nfs_have_delegation(inode, FMODE_READ))
1059                 return 1;
1060         return nfs_lookup_revalidate(dentry, nd);
1061 }
1062 #endif /* CONFIG_NFSV4 */
1063
1064 static struct dentry *nfs_readdir_lookup(nfs_readdir_descriptor_t *desc)
1065 {
1066         struct dentry *parent = desc->file->f_path.dentry;
1067         struct inode *dir = parent->d_inode;
1068         struct nfs_entry *entry = desc->entry;
1069         struct dentry *dentry, *alias;
1070         struct qstr name = {
1071                 .name = entry->name,
1072                 .len = entry->len,
1073         };
1074         struct inode *inode;
1075         unsigned long verf = nfs_save_change_attribute(dir);
1076
1077         switch (name.len) {
1078                 case 2:
1079                         if (name.name[0] == '.' && name.name[1] == '.')
1080                                 return dget_parent(parent);
1081                         break;
1082                 case 1:
1083                         if (name.name[0] == '.')
1084                                 return dget(parent);
1085         }
1086
1087         spin_lock(&dir->i_lock);
1088         if (NFS_I(dir)->cache_validity & NFS_INO_INVALID_DATA) {
1089                 spin_unlock(&dir->i_lock);
1090                 return NULL;
1091         }
1092         spin_unlock(&dir->i_lock);
1093
1094         name.hash = full_name_hash(name.name, name.len);
1095         dentry = d_lookup(parent, &name);
1096         if (dentry != NULL) {
1097                 /* Is this a positive dentry that matches the readdir info? */
1098                 if (dentry->d_inode != NULL &&
1099                                 (NFS_FILEID(dentry->d_inode) == entry->ino ||
1100                                 d_mountpoint(dentry))) {
1101                         if (!desc->plus || entry->fh->size == 0)
1102                                 return dentry;
1103                         if (nfs_compare_fh(NFS_FH(dentry->d_inode),
1104                                                 entry->fh) == 0)
1105                                 goto out_renew;
1106                 }
1107                 /* No, so d_drop to allow one to be created */
1108                 d_drop(dentry);
1109                 dput(dentry);
1110         }
1111         if (!desc->plus || !(entry->fattr->valid & NFS_ATTR_FATTR))
1112                 return NULL;
1113         if (name.len > NFS_SERVER(dir)->namelen)
1114                 return NULL;
1115         /* Note: caller is already holding the dir->i_mutex! */
1116         dentry = d_alloc(parent, &name);
1117         if (dentry == NULL)
1118                 return NULL;
1119         dentry->d_op = NFS_PROTO(dir)->dentry_ops;
1120         inode = nfs_fhget(dentry->d_sb, entry->fh, entry->fattr);
1121         if (IS_ERR(inode)) {
1122                 dput(dentry);
1123                 return NULL;
1124         }
1125
1126         alias = d_materialise_unique(dentry, inode);
1127         if (alias != NULL) {
1128                 dput(dentry);
1129                 if (IS_ERR(alias))
1130                         return NULL;
1131                 dentry = alias;
1132         }
1133
1134 out_renew:
1135         nfs_set_verifier(dentry, verf);
1136         return dentry;
1137 }
1138
1139 /*
1140  * Code common to create, mkdir, and mknod.
1141  */
1142 int nfs_instantiate(struct dentry *dentry, struct nfs_fh *fhandle,
1143                                 struct nfs_fattr *fattr)
1144 {
1145         struct dentry *parent = dget_parent(dentry);
1146         struct inode *dir = parent->d_inode;
1147         struct inode *inode;
1148         int error = -EACCES;
1149
1150         d_drop(dentry);
1151
1152         /* We may have been initialized further down */
1153         if (dentry->d_inode)
1154                 goto out;
1155         if (fhandle->size == 0) {
1156                 error = NFS_PROTO(dir)->lookup(dir, &dentry->d_name, fhandle, fattr);
1157                 if (error)
1158                         goto out_error;
1159         }
1160         nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
1161         if (!(fattr->valid & NFS_ATTR_FATTR)) {
1162                 struct nfs_server *server = NFS_SB(dentry->d_sb);
1163                 error = server->nfs_client->rpc_ops->getattr(server, fhandle, fattr);
1164                 if (error < 0)
1165                         goto out_error;
1166         }
1167         inode = nfs_fhget(dentry->d_sb, fhandle, fattr);
1168         error = PTR_ERR(inode);
1169         if (IS_ERR(inode))
1170                 goto out_error;
1171         d_add(dentry, inode);
1172 out:
1173         dput(parent);
1174         return 0;
1175 out_error:
1176         nfs_mark_for_revalidate(dir);
1177         dput(parent);
1178         return error;
1179 }
1180
1181 /*
1182  * Following a failed create operation, we drop the dentry rather
1183  * than retain a negative dentry. This avoids a problem in the event
1184  * that the operation succeeded on the server, but an error in the
1185  * reply path made it appear to have failed.
1186  */
1187 static int nfs_create(struct inode *dir, struct dentry *dentry, int mode,
1188                 struct nameidata *nd)
1189 {
1190         struct iattr attr;
1191         int error;
1192         int open_flags = 0;
1193
1194         dfprintk(VFS, "NFS: create(%s/%ld), %s\n",
1195                         dir->i_sb->s_id, dir->i_ino, dentry->d_name.name);
1196
1197         attr.ia_mode = mode;
1198         attr.ia_valid = ATTR_MODE;
1199
1200         if ((nd->flags & LOOKUP_CREATE) != 0)
1201                 open_flags = nd->intent.open.flags;
1202
1203         lock_kernel();
1204         error = NFS_PROTO(dir)->create(dir, dentry, &attr, open_flags, nd);
1205         if (error != 0)
1206                 goto out_err;
1207         unlock_kernel();
1208         return 0;
1209 out_err:
1210         unlock_kernel();
1211         d_drop(dentry);
1212         return error;
1213 }
1214
1215 /*
1216  * See comments for nfs_proc_create regarding failed operations.
1217  */
1218 static int
1219 nfs_mknod(struct inode *dir, struct dentry *dentry, int mode, dev_t rdev)
1220 {
1221         struct iattr attr;
1222         int status;
1223
1224         dfprintk(VFS, "NFS: mknod(%s/%ld), %s\n",
1225                         dir->i_sb->s_id, dir->i_ino, dentry->d_name.name);
1226
1227         if (!new_valid_dev(rdev))
1228                 return -EINVAL;
1229
1230         attr.ia_mode = mode;
1231         attr.ia_valid = ATTR_MODE;
1232
1233         lock_kernel();
1234         status = NFS_PROTO(dir)->mknod(dir, dentry, &attr, rdev);
1235         if (status != 0)
1236                 goto out_err;
1237         unlock_kernel();
1238         return 0;
1239 out_err:
1240         unlock_kernel();
1241         d_drop(dentry);
1242         return status;
1243 }
1244
1245 /*
1246  * See comments for nfs_proc_create regarding failed operations.
1247  */
1248 static int nfs_mkdir(struct inode *dir, struct dentry *dentry, int mode)
1249 {
1250         struct iattr attr;
1251         int error;
1252
1253         dfprintk(VFS, "NFS: mkdir(%s/%ld), %s\n",
1254                         dir->i_sb->s_id, dir->i_ino, dentry->d_name.name);
1255
1256         attr.ia_valid = ATTR_MODE;
1257         attr.ia_mode = mode | S_IFDIR;
1258
1259         lock_kernel();
1260         error = NFS_PROTO(dir)->mkdir(dir, dentry, &attr);
1261         if (error != 0)
1262                 goto out_err;
1263         unlock_kernel();
1264         return 0;
1265 out_err:
1266         d_drop(dentry);
1267         unlock_kernel();
1268         return error;
1269 }
1270
1271 static int nfs_rmdir(struct inode *dir, struct dentry *dentry)
1272 {
1273         int error;
1274
1275         dfprintk(VFS, "NFS: rmdir(%s/%ld), %s\n",
1276                         dir->i_sb->s_id, dir->i_ino, dentry->d_name.name);
1277
1278         lock_kernel();
1279         error = NFS_PROTO(dir)->rmdir(dir, &dentry->d_name);
1280         /* Ensure the VFS deletes this inode */
1281         if (error == 0 && dentry->d_inode != NULL)
1282                 clear_nlink(dentry->d_inode);
1283         unlock_kernel();
1284
1285         return error;
1286 }
1287
1288 static int nfs_sillyrename(struct inode *dir, struct dentry *dentry)
1289 {
1290         static unsigned int sillycounter;
1291         const int      fileidsize  = sizeof(NFS_FILEID(dentry->d_inode))*2;
1292         const int      countersize = sizeof(sillycounter)*2;
1293         const int      slen        = sizeof(".nfs")+fileidsize+countersize-1;
1294         char           silly[slen+1];
1295         struct qstr    qsilly;
1296         struct dentry *sdentry;
1297         int            error = -EIO;
1298
1299         dfprintk(VFS, "NFS: silly-rename(%s/%s, ct=%d)\n",
1300                 dentry->d_parent->d_name.name, dentry->d_name.name, 
1301                 atomic_read(&dentry->d_count));
1302         nfs_inc_stats(dir, NFSIOS_SILLYRENAME);
1303
1304         /*
1305          * We don't allow a dentry to be silly-renamed twice.
1306          */
1307         error = -EBUSY;
1308         if (dentry->d_flags & DCACHE_NFSFS_RENAMED)
1309                 goto out;
1310
1311         sprintf(silly, ".nfs%*.*Lx",
1312                 fileidsize, fileidsize,
1313                 (unsigned long long)NFS_FILEID(dentry->d_inode));
1314
1315         /* Return delegation in anticipation of the rename */
1316         nfs_inode_return_delegation(dentry->d_inode);
1317
1318         sdentry = NULL;
1319         do {
1320                 char *suffix = silly + slen - countersize;
1321
1322                 dput(sdentry);
1323                 sillycounter++;
1324                 sprintf(suffix, "%*.*x", countersize, countersize, sillycounter);
1325
1326                 dfprintk(VFS, "NFS: trying to rename %s to %s\n",
1327                                 dentry->d_name.name, silly);
1328                 
1329                 sdentry = lookup_one_len(silly, dentry->d_parent, slen);
1330                 /*
1331                  * N.B. Better to return EBUSY here ... it could be
1332                  * dangerous to delete the file while it's in use.
1333                  */
1334                 if (IS_ERR(sdentry))
1335                         goto out;
1336         } while(sdentry->d_inode != NULL); /* need negative lookup */
1337
1338         qsilly.name = silly;
1339         qsilly.len  = strlen(silly);
1340         if (dentry->d_inode) {
1341                 error = NFS_PROTO(dir)->rename(dir, &dentry->d_name,
1342                                 dir, &qsilly);
1343                 nfs_mark_for_revalidate(dentry->d_inode);
1344         } else
1345                 error = NFS_PROTO(dir)->rename(dir, &dentry->d_name,
1346                                 dir, &qsilly);
1347         if (!error) {
1348                 nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
1349                 d_move(dentry, sdentry);
1350                 error = nfs_async_unlink(dir, dentry);
1351                 /* If we return 0 we don't unlink */
1352         }
1353         dput(sdentry);
1354 out:
1355         return error;
1356 }
1357
1358 /*
1359  * Remove a file after making sure there are no pending writes,
1360  * and after checking that the file has only one user. 
1361  *
1362  * We invalidate the attribute cache and free the inode prior to the operation
1363  * to avoid possible races if the server reuses the inode.
1364  */
1365 static int nfs_safe_remove(struct dentry *dentry)
1366 {
1367         struct inode *dir = dentry->d_parent->d_inode;
1368         struct inode *inode = dentry->d_inode;
1369         int error = -EBUSY;
1370                 
1371         dfprintk(VFS, "NFS: safe_remove(%s/%s)\n",
1372                 dentry->d_parent->d_name.name, dentry->d_name.name);
1373
1374         /* If the dentry was sillyrenamed, we simply call d_delete() */
1375         if (dentry->d_flags & DCACHE_NFSFS_RENAMED) {
1376                 error = 0;
1377                 goto out;
1378         }
1379
1380         if (inode != NULL) {
1381                 nfs_inode_return_delegation(inode);
1382                 error = NFS_PROTO(dir)->remove(dir, &dentry->d_name);
1383                 /* The VFS may want to delete this inode */
1384                 if (error == 0)
1385                         drop_nlink(inode);
1386                 nfs_mark_for_revalidate(inode);
1387         } else
1388                 error = NFS_PROTO(dir)->remove(dir, &dentry->d_name);
1389 out:
1390         return error;
1391 }
1392
1393 /*  We do silly rename. In case sillyrename() returns -EBUSY, the inode
1394  *  belongs to an active ".nfs..." file and we return -EBUSY.
1395  *
1396  *  If sillyrename() returns 0, we do nothing, otherwise we unlink.
1397  */
1398 static int nfs_unlink(struct inode *dir, struct dentry *dentry)
1399 {
1400         int error;
1401         int need_rehash = 0;
1402
1403         dfprintk(VFS, "NFS: unlink(%s/%ld, %s)\n", dir->i_sb->s_id,
1404                 dir->i_ino, dentry->d_name.name);
1405
1406         lock_kernel();
1407         spin_lock(&dcache_lock);
1408         spin_lock(&dentry->d_lock);
1409         if (atomic_read(&dentry->d_count) > 1) {
1410                 spin_unlock(&dentry->d_lock);
1411                 spin_unlock(&dcache_lock);
1412                 /* Start asynchronous writeout of the inode */
1413                 write_inode_now(dentry->d_inode, 0);
1414                 error = nfs_sillyrename(dir, dentry);
1415                 unlock_kernel();
1416                 return error;
1417         }
1418         if (!d_unhashed(dentry)) {
1419                 __d_drop(dentry);
1420                 need_rehash = 1;
1421         }
1422         spin_unlock(&dentry->d_lock);
1423         spin_unlock(&dcache_lock);
1424         error = nfs_safe_remove(dentry);
1425         if (!error) {
1426                 nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
1427         } else if (need_rehash)
1428                 d_rehash(dentry);
1429         unlock_kernel();
1430         return error;
1431 }
1432
1433 /*
1434  * To create a symbolic link, most file systems instantiate a new inode,
1435  * add a page to it containing the path, then write it out to the disk
1436  * using prepare_write/commit_write.
1437  *
1438  * Unfortunately the NFS client can't create the in-core inode first
1439  * because it needs a file handle to create an in-core inode (see
1440  * fs/nfs/inode.c:nfs_fhget).  We only have a file handle *after* the
1441  * symlink request has completed on the server.
1442  *
1443  * So instead we allocate a raw page, copy the symname into it, then do
1444  * the SYMLINK request with the page as the buffer.  If it succeeds, we
1445  * now have a new file handle and can instantiate an in-core NFS inode
1446  * and move the raw page into its mapping.
1447  */
1448 static int nfs_symlink(struct inode *dir, struct dentry *dentry, const char *symname)
1449 {
1450         struct pagevec lru_pvec;
1451         struct page *page;
1452         char *kaddr;
1453         struct iattr attr;
1454         unsigned int pathlen = strlen(symname);
1455         int error;
1456
1457         dfprintk(VFS, "NFS: symlink(%s/%ld, %s, %s)\n", dir->i_sb->s_id,
1458                 dir->i_ino, dentry->d_name.name, symname);
1459
1460         if (pathlen > PAGE_SIZE)
1461                 return -ENAMETOOLONG;
1462
1463         attr.ia_mode = S_IFLNK | S_IRWXUGO;
1464         attr.ia_valid = ATTR_MODE;
1465
1466         lock_kernel();
1467
1468         page = alloc_page(GFP_HIGHUSER);
1469         if (!page) {
1470                 unlock_kernel();
1471                 return -ENOMEM;
1472         }
1473
1474         kaddr = kmap_atomic(page, KM_USER0);
1475         memcpy(kaddr, symname, pathlen);
1476         if (pathlen < PAGE_SIZE)
1477                 memset(kaddr + pathlen, 0, PAGE_SIZE - pathlen);
1478         kunmap_atomic(kaddr, KM_USER0);
1479
1480         error = NFS_PROTO(dir)->symlink(dir, dentry, page, pathlen, &attr);
1481         if (error != 0) {
1482                 dfprintk(VFS, "NFS: symlink(%s/%ld, %s, %s) error %d\n",
1483                         dir->i_sb->s_id, dir->i_ino,
1484                         dentry->d_name.name, symname, error);
1485                 d_drop(dentry);
1486                 __free_page(page);
1487                 unlock_kernel();
1488                 return error;
1489         }
1490
1491         /*
1492          * No big deal if we can't add this page to the page cache here.
1493          * READLINK will get the missing page from the server if needed.
1494          */
1495         pagevec_init(&lru_pvec, 0);
1496         if (!add_to_page_cache(page, dentry->d_inode->i_mapping, 0,
1497                                                         GFP_KERNEL)) {
1498                 pagevec_add(&lru_pvec, page);
1499                 pagevec_lru_add(&lru_pvec);
1500                 SetPageUptodate(page);
1501                 unlock_page(page);
1502         } else
1503                 __free_page(page);
1504
1505         unlock_kernel();
1506         return 0;
1507 }
1508
1509 static int 
1510 nfs_link(struct dentry *old_dentry, struct inode *dir, struct dentry *dentry)
1511 {
1512         struct inode *inode = old_dentry->d_inode;
1513         int error;
1514
1515         dfprintk(VFS, "NFS: link(%s/%s -> %s/%s)\n",
1516                 old_dentry->d_parent->d_name.name, old_dentry->d_name.name,
1517                 dentry->d_parent->d_name.name, dentry->d_name.name);
1518
1519         lock_kernel();
1520         d_drop(dentry);
1521         error = NFS_PROTO(dir)->link(inode, dir, &dentry->d_name);
1522         if (error == 0) {
1523                 atomic_inc(&inode->i_count);
1524                 d_add(dentry, inode);
1525         }
1526         unlock_kernel();
1527         return error;
1528 }
1529
1530 /*
1531  * RENAME
1532  * FIXME: Some nfsds, like the Linux user space nfsd, may generate a
1533  * different file handle for the same inode after a rename (e.g. when
1534  * moving to a different directory). A fail-safe method to do so would
1535  * be to look up old_dir/old_name, create a link to new_dir/new_name and
1536  * rename the old file using the sillyrename stuff. This way, the original
1537  * file in old_dir will go away when the last process iput()s the inode.
1538  *
1539  * FIXED.
1540  * 
1541  * It actually works quite well. One needs to have the possibility for
1542  * at least one ".nfs..." file in each directory the file ever gets
1543  * moved or linked to which happens automagically with the new
1544  * implementation that only depends on the dcache stuff instead of
1545  * using the inode layer
1546  *
1547  * Unfortunately, things are a little more complicated than indicated
1548  * above. For a cross-directory move, we want to make sure we can get
1549  * rid of the old inode after the operation.  This means there must be
1550  * no pending writes (if it's a file), and the use count must be 1.
1551  * If these conditions are met, we can drop the dentries before doing
1552  * the rename.
1553  */
1554 static int nfs_rename(struct inode *old_dir, struct dentry *old_dentry,
1555                       struct inode *new_dir, struct dentry *new_dentry)
1556 {
1557         struct inode *old_inode = old_dentry->d_inode;
1558         struct inode *new_inode = new_dentry->d_inode;
1559         struct dentry *dentry = NULL, *rehash = NULL;
1560         int error = -EBUSY;
1561
1562         /*
1563          * To prevent any new references to the target during the rename,
1564          * we unhash the dentry and free the inode in advance.
1565          */
1566         lock_kernel();
1567         if (!d_unhashed(new_dentry)) {
1568                 d_drop(new_dentry);
1569                 rehash = new_dentry;
1570         }
1571
1572         dfprintk(VFS, "NFS: rename(%s/%s -> %s/%s, ct=%d)\n",
1573                  old_dentry->d_parent->d_name.name, old_dentry->d_name.name,
1574                  new_dentry->d_parent->d_name.name, new_dentry->d_name.name,
1575                  atomic_read(&new_dentry->d_count));
1576
1577         /*
1578          * First check whether the target is busy ... we can't
1579          * safely do _any_ rename if the target is in use.
1580          *
1581          * For files, make a copy of the dentry and then do a 
1582          * silly-rename. If the silly-rename succeeds, the
1583          * copied dentry is hashed and becomes the new target.
1584          */
1585         if (!new_inode)
1586                 goto go_ahead;
1587         if (S_ISDIR(new_inode->i_mode)) {
1588                 error = -EISDIR;
1589                 if (!S_ISDIR(old_inode->i_mode))
1590                         goto out;
1591         } else if (atomic_read(&new_dentry->d_count) > 2) {
1592                 int err;
1593                 /* copy the target dentry's name */
1594                 dentry = d_alloc(new_dentry->d_parent,
1595                                  &new_dentry->d_name);
1596                 if (!dentry)
1597                         goto out;
1598
1599                 /* silly-rename the existing target ... */
1600                 err = nfs_sillyrename(new_dir, new_dentry);
1601                 if (!err) {
1602                         new_dentry = rehash = dentry;
1603                         new_inode = NULL;
1604                         /* instantiate the replacement target */
1605                         d_instantiate(new_dentry, NULL);
1606                 } else if (atomic_read(&new_dentry->d_count) > 1)
1607                         /* dentry still busy? */
1608                         goto out;
1609         } else
1610                 drop_nlink(new_inode);
1611
1612 go_ahead:
1613         /*
1614          * ... prune child dentries and writebacks if needed.
1615          */
1616         if (atomic_read(&old_dentry->d_count) > 1) {
1617                 if (S_ISREG(old_inode->i_mode))
1618                         nfs_wb_all(old_inode);
1619                 shrink_dcache_parent(old_dentry);
1620         }
1621         nfs_inode_return_delegation(old_inode);
1622
1623         if (new_inode != NULL) {
1624                 nfs_inode_return_delegation(new_inode);
1625                 d_delete(new_dentry);
1626         }
1627
1628         error = NFS_PROTO(old_dir)->rename(old_dir, &old_dentry->d_name,
1629                                            new_dir, &new_dentry->d_name);
1630         nfs_mark_for_revalidate(old_inode);
1631 out:
1632         if (rehash)
1633                 d_rehash(rehash);
1634         if (!error) {
1635                 d_move(old_dentry, new_dentry);
1636                 nfs_set_verifier(new_dentry,
1637                                         nfs_save_change_attribute(new_dir));
1638         }
1639
1640         /* new dentry created? */
1641         if (dentry)
1642                 dput(dentry);
1643         unlock_kernel();
1644         return error;
1645 }
1646
1647 static DEFINE_SPINLOCK(nfs_access_lru_lock);
1648 static LIST_HEAD(nfs_access_lru_list);
1649 static atomic_long_t nfs_access_nr_entries;
1650
1651 static void nfs_access_free_entry(struct nfs_access_entry *entry)
1652 {
1653         put_rpccred(entry->cred);
1654         kfree(entry);
1655         smp_mb__before_atomic_dec();
1656         atomic_long_dec(&nfs_access_nr_entries);
1657         smp_mb__after_atomic_dec();
1658 }
1659
1660 int nfs_access_cache_shrinker(int nr_to_scan, gfp_t gfp_mask)
1661 {
1662         LIST_HEAD(head);
1663         struct nfs_inode *nfsi;
1664         struct nfs_access_entry *cache;
1665
1666 restart:
1667         spin_lock(&nfs_access_lru_lock);
1668         list_for_each_entry(nfsi, &nfs_access_lru_list, access_cache_inode_lru) {
1669                 struct inode *inode;
1670
1671                 if (nr_to_scan-- == 0)
1672                         break;
1673                 inode = igrab(&nfsi->vfs_inode);
1674                 if (inode == NULL)
1675                         continue;
1676                 spin_lock(&inode->i_lock);
1677                 if (list_empty(&nfsi->access_cache_entry_lru))
1678                         goto remove_lru_entry;
1679                 cache = list_entry(nfsi->access_cache_entry_lru.next,
1680                                 struct nfs_access_entry, lru);
1681                 list_move(&cache->lru, &head);
1682                 rb_erase(&cache->rb_node, &nfsi->access_cache);
1683                 if (!list_empty(&nfsi->access_cache_entry_lru))
1684                         list_move_tail(&nfsi->access_cache_inode_lru,
1685                                         &nfs_access_lru_list);
1686                 else {
1687 remove_lru_entry:
1688                         list_del_init(&nfsi->access_cache_inode_lru);
1689                         clear_bit(NFS_INO_ACL_LRU_SET, &nfsi->flags);
1690                 }
1691                 spin_unlock(&inode->i_lock);
1692                 spin_unlock(&nfs_access_lru_lock);
1693                 iput(inode);
1694                 goto restart;
1695         }
1696         spin_unlock(&nfs_access_lru_lock);
1697         while (!list_empty(&head)) {
1698                 cache = list_entry(head.next, struct nfs_access_entry, lru);
1699                 list_del(&cache->lru);
1700                 nfs_access_free_entry(cache);
1701         }
1702         return (atomic_long_read(&nfs_access_nr_entries) / 100) * sysctl_vfs_cache_pressure;
1703 }
1704
1705 static void __nfs_access_zap_cache(struct inode *inode)
1706 {
1707         struct nfs_inode *nfsi = NFS_I(inode);
1708         struct rb_root *root_node = &nfsi->access_cache;
1709         struct rb_node *n, *dispose = NULL;
1710         struct nfs_access_entry *entry;
1711
1712         /* Unhook entries from the cache */
1713         while ((n = rb_first(root_node)) != NULL) {
1714                 entry = rb_entry(n, struct nfs_access_entry, rb_node);
1715                 rb_erase(n, root_node);
1716                 list_del(&entry->lru);
1717                 n->rb_left = dispose;
1718                 dispose = n;
1719         }
1720         nfsi->cache_validity &= ~NFS_INO_INVALID_ACCESS;
1721         spin_unlock(&inode->i_lock);
1722
1723         /* Now kill them all! */
1724         while (dispose != NULL) {
1725                 n = dispose;
1726                 dispose = n->rb_left;
1727                 nfs_access_free_entry(rb_entry(n, struct nfs_access_entry, rb_node));
1728         }
1729 }
1730
1731 void nfs_access_zap_cache(struct inode *inode)
1732 {
1733         /* Remove from global LRU init */
1734         if (test_and_clear_bit(NFS_INO_ACL_LRU_SET, &NFS_FLAGS(inode))) {
1735                 spin_lock(&nfs_access_lru_lock);
1736                 list_del_init(&NFS_I(inode)->access_cache_inode_lru);
1737                 spin_unlock(&nfs_access_lru_lock);
1738         }
1739
1740         spin_lock(&inode->i_lock);
1741         /* This will release the spinlock */
1742         __nfs_access_zap_cache(inode);
1743 }
1744
1745 static struct nfs_access_entry *nfs_access_search_rbtree(struct inode *inode, struct rpc_cred *cred)
1746 {
1747         struct rb_node *n = NFS_I(inode)->access_cache.rb_node;
1748         struct nfs_access_entry *entry;
1749
1750         while (n != NULL) {
1751                 entry = rb_entry(n, struct nfs_access_entry, rb_node);
1752
1753                 if (cred < entry->cred)
1754                         n = n->rb_left;
1755                 else if (cred > entry->cred)
1756                         n = n->rb_right;
1757                 else
1758                         return entry;
1759         }
1760         return NULL;
1761 }
1762
1763 static int nfs_access_get_cached(struct inode *inode, struct rpc_cred *cred, struct nfs_access_entry *res)
1764 {
1765         struct nfs_inode *nfsi = NFS_I(inode);
1766         struct nfs_access_entry *cache;
1767         int err = -ENOENT;
1768
1769         spin_lock(&inode->i_lock);
1770         if (nfsi->cache_validity & NFS_INO_INVALID_ACCESS)
1771                 goto out_zap;
1772         cache = nfs_access_search_rbtree(inode, cred);
1773         if (cache == NULL)
1774                 goto out;
1775         if (!time_in_range(jiffies, cache->jiffies, cache->jiffies + nfsi->attrtimeo))
1776                 goto out_stale;
1777         res->jiffies = cache->jiffies;
1778         res->cred = cache->cred;
1779         res->mask = cache->mask;
1780         list_move_tail(&cache->lru, &nfsi->access_cache_entry_lru);
1781         err = 0;
1782 out:
1783         spin_unlock(&inode->i_lock);
1784         return err;
1785 out_stale:
1786         rb_erase(&cache->rb_node, &nfsi->access_cache);
1787         list_del(&cache->lru);
1788         spin_unlock(&inode->i_lock);
1789         nfs_access_free_entry(cache);
1790         return -ENOENT;
1791 out_zap:
1792         /* This will release the spinlock */
1793         __nfs_access_zap_cache(inode);
1794         return -ENOENT;
1795 }
1796
1797 static void nfs_access_add_rbtree(struct inode *inode, struct nfs_access_entry *set)
1798 {
1799         struct nfs_inode *nfsi = NFS_I(inode);
1800         struct rb_root *root_node = &nfsi->access_cache;
1801         struct rb_node **p = &root_node->rb_node;
1802         struct rb_node *parent = NULL;
1803         struct nfs_access_entry *entry;
1804
1805         spin_lock(&inode->i_lock);
1806         while (*p != NULL) {
1807                 parent = *p;
1808                 entry = rb_entry(parent, struct nfs_access_entry, rb_node);
1809
1810                 if (set->cred < entry->cred)
1811                         p = &parent->rb_left;
1812                 else if (set->cred > entry->cred)
1813                         p = &parent->rb_right;
1814                 else
1815                         goto found;
1816         }
1817         rb_link_node(&set->rb_node, parent, p);
1818         rb_insert_color(&set->rb_node, root_node);
1819         list_add_tail(&set->lru, &nfsi->access_cache_entry_lru);
1820         spin_unlock(&inode->i_lock);
1821         return;
1822 found:
1823         rb_replace_node(parent, &set->rb_node, root_node);
1824         list_add_tail(&set->lru, &nfsi->access_cache_entry_lru);
1825         list_del(&entry->lru);
1826         spin_unlock(&inode->i_lock);
1827         nfs_access_free_entry(entry);
1828 }
1829
1830 static void nfs_access_add_cache(struct inode *inode, struct nfs_access_entry *set)
1831 {
1832         struct nfs_access_entry *cache = kmalloc(sizeof(*cache), GFP_KERNEL);
1833         if (cache == NULL)
1834                 return;
1835         RB_CLEAR_NODE(&cache->rb_node);
1836         cache->jiffies = set->jiffies;
1837         cache->cred = get_rpccred(set->cred);
1838         cache->mask = set->mask;
1839
1840         nfs_access_add_rbtree(inode, cache);
1841
1842         /* Update accounting */
1843         smp_mb__before_atomic_inc();
1844         atomic_long_inc(&nfs_access_nr_entries);
1845         smp_mb__after_atomic_inc();
1846
1847         /* Add inode to global LRU list */
1848         if (!test_and_set_bit(NFS_INO_ACL_LRU_SET, &NFS_FLAGS(inode))) {
1849                 spin_lock(&nfs_access_lru_lock);
1850                 list_add_tail(&NFS_I(inode)->access_cache_inode_lru, &nfs_access_lru_list);
1851                 spin_unlock(&nfs_access_lru_lock);
1852         }
1853 }
1854
1855 static int nfs_do_access(struct inode *inode, struct rpc_cred *cred, int mask)
1856 {
1857         struct nfs_access_entry cache;
1858         int status;
1859
1860         status = nfs_access_get_cached(inode, cred, &cache);
1861         if (status == 0)
1862                 goto out;
1863
1864         /* Be clever: ask server to check for all possible rights */
1865         cache.mask = MAY_EXEC | MAY_WRITE | MAY_READ;
1866         cache.cred = cred;
1867         cache.jiffies = jiffies;
1868         status = NFS_PROTO(inode)->access(inode, &cache);
1869         if (status != 0)
1870                 return status;
1871         nfs_access_add_cache(inode, &cache);
1872 out:
1873         if ((cache.mask & mask) == mask)
1874                 return 0;
1875         return -EACCES;
1876 }
1877
1878 static int nfs_open_permission_mask(int openflags)
1879 {
1880         int mask = 0;
1881
1882         if (openflags & FMODE_READ)
1883                 mask |= MAY_READ;
1884         if (openflags & FMODE_WRITE)
1885                 mask |= MAY_WRITE;
1886         if (openflags & FMODE_EXEC)
1887                 mask |= MAY_EXEC;
1888         return mask;
1889 }
1890
1891 int nfs_may_open(struct inode *inode, struct rpc_cred *cred, int openflags)
1892 {
1893         return nfs_do_access(inode, cred, nfs_open_permission_mask(openflags));
1894 }
1895
1896 int nfs_permission(struct inode *inode, int mask, struct nameidata *nd)
1897 {
1898         struct rpc_cred *cred;
1899         int res = 0;
1900
1901         nfs_inc_stats(inode, NFSIOS_VFSACCESS);
1902
1903         if (mask == 0)
1904                 goto out;
1905         /* Is this sys_access() ? */
1906         if (nd != NULL && (nd->flags & LOOKUP_ACCESS))
1907                 goto force_lookup;
1908
1909         switch (inode->i_mode & S_IFMT) {
1910                 case S_IFLNK:
1911                         goto out;
1912                 case S_IFREG:
1913                         /* NFSv4 has atomic_open... */
1914                         if (nfs_server_capable(inode, NFS_CAP_ATOMIC_OPEN)
1915                                         && nd != NULL
1916                                         && (nd->flags & LOOKUP_OPEN))
1917                                 goto out;
1918                         break;
1919                 case S_IFDIR:
1920                         /*
1921                          * Optimize away all write operations, since the server
1922                          * will check permissions when we perform the op.
1923                          */
1924                         if ((mask & MAY_WRITE) && !(mask & MAY_READ))
1925                                 goto out;
1926         }
1927
1928 force_lookup:
1929         lock_kernel();
1930
1931         if (!NFS_PROTO(inode)->access)
1932                 goto out_notsup;
1933
1934         cred = rpcauth_lookupcred(NFS_CLIENT(inode)->cl_auth, 0);
1935         if (!IS_ERR(cred)) {
1936                 res = nfs_do_access(inode, cred, mask);
1937                 put_rpccred(cred);
1938         } else
1939                 res = PTR_ERR(cred);
1940         unlock_kernel();
1941 out:
1942         dfprintk(VFS, "NFS: permission(%s/%ld), mask=0x%x, res=%d\n",
1943                 inode->i_sb->s_id, inode->i_ino, mask, res);
1944         return res;
1945 out_notsup:
1946         res = nfs_revalidate_inode(NFS_SERVER(inode), inode);
1947         if (res == 0)
1948                 res = generic_permission(inode, mask, NULL);
1949         unlock_kernel();
1950         goto out;
1951 }
1952
1953 /*
1954  * Local variables:
1955  *  version-control: t
1956  *  kept-new-versions: 5
1957  * End:
1958  */