afs: Change VerifyVCache2 calls to VerifyVCache
[openafs.git] / src / afs / LINUX / osi_vnodeops.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  *
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 /*
11  * Linux specific vnodeops. Also includes the glue routines required to call
12  * AFS vnodeops.
13  *
14  * So far the only truly scary part is that Linux relies on the inode cache
15  * to be up to date. Don't you dare break a callback and expect an fstat
16  * to give you meaningful information. This appears to be fixed in the 2.1
17  * development kernels. As it is we can fix this now by intercepting the
18  * stat calls.
19  */
20
21 #include <afsconfig.h>
22 #include "afs/param.h"
23
24
25 #include "afs/sysincludes.h"
26 #include "afsincludes.h"
27 #include "afs/afs_stats.h"
28 #include <linux/mm.h>
29 #ifdef HAVE_MM_INLINE_H
30 #include <linux/mm_inline.h>
31 #endif
32 #include <linux/pagemap.h>
33 #include <linux/writeback.h>
34 #if defined(HAVE_LINUX_LRU_CACHE_ADD_FILE)
35 # include <linux/swap.h>
36 #else
37 # include <linux/pagevec.h>
38 #endif
39 #include <linux/aio.h>
40 #include "afs/lock.h"
41 #include "afs/afs_bypasscache.h"
42
43 #include "osi_compat.h"
44 #include "osi_pagecopy.h"
45
46 #ifndef MAX_ERRNO
47 #define MAX_ERRNO 1000L
48 #endif
49
50 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,34)
51 /* Enable our workaround for a race with d_splice_alias. The race was fixed in
52  * 2.6.34, so don't do it after that point. */
53 # define D_SPLICE_ALIAS_RACE
54 #endif
55
56 /* Workaround for RH 7.5 which introduced file operation iterate() but requires
57  * each file->f_mode to be marked with FMODE_KABI_ITERATE.  Instead OpenAFS will
58  * continue to use file opearation readdir() in this case.
59  */
60 #if defined(STRUCT_FILE_OPERATIONS_HAS_ITERATE) && !defined(FMODE_KABI_ITERATE)
61 #define USE_FOP_ITERATE 1
62 #else
63 #undef USE_FOP_ITERATE
64 #endif
65
66 int cachefs_noreadpage = 0;
67
68 extern struct backing_dev_info *afs_backing_dev_info;
69
70 extern struct vcache *afs_globalVp;
71
72 /* Handle interfacing with Linux's pagevec/lru facilities */
73
74 #if defined(HAVE_LINUX_LRU_CACHE_ADD_FILE)
75
76 /*
77  * Linux's lru_cache_add_file provides a simplified LRU interface without
78  * needing a pagevec
79  */
80 struct afs_lru_pages {
81     char unused;
82 };
83
84 static inline void
85 afs_lru_cache_init(struct afs_lru_pages *alrupages)
86 {
87     return;
88 }
89
90 static inline void
91 afs_lru_cache_add(struct afs_lru_pages *alrupages, struct page *page)
92 {
93     lru_cache_add_file(page);
94 }
95
96 static inline void
97 afs_lru_cache_finalize(struct afs_lru_pages *alrupages)
98 {
99     return;
100 }
101 #else
102
103 /* Linux's pagevec/lru interfaces require a pagevec */
104 struct afs_lru_pages {
105     struct pagevec lrupv;
106 };
107
108 static inline void
109 afs_lru_cache_init(struct afs_lru_pages *alrupages)
110 {
111 # if defined(PAGEVEC_INIT_COLD_ARG)
112     pagevec_init(&alrupages->lrupv, 0);
113 # else
114     pagevec_init(&alrupages->lrupv);
115 # endif
116 }
117
118 # ifndef HAVE_LINUX_PAGEVEC_LRU_ADD_FILE
119 #  define __pagevec_lru_add_file __pagevec_lru_add
120 # endif
121
122 static inline void
123 afs_lru_cache_add(struct afs_lru_pages *alrupages, struct page *page)
124 {
125     get_page(page);
126     if (!pagevec_add(&alrupages->lrupv, page))
127         __pagevec_lru_add_file(&alrupages->lrupv);
128 }
129
130 static inline void
131 afs_lru_cache_finalize(struct afs_lru_pages *alrupages)
132 {
133     if (pagevec_count(&alrupages->lrupv))
134         __pagevec_lru_add_file(&alrupages->lrupv);
135 }
136 #endif /* !HAVE_LINUX_LRU_ADD_FILE */
137
138 /* This function converts a positive error code from AFS into a negative
139  * code suitable for passing into the Linux VFS layer. It checks that the
140  * error code is within the permissable bounds for the ERR_PTR mechanism.
141  *
142  * _All_ error codes which come from the AFS layer should be passed through
143  * this function before being returned to the kernel.
144  */
145
146 static inline int
147 afs_convert_code(int code) {
148     if ((code >= 0) && (code <= MAX_ERRNO))
149         return -code;
150     else
151         return -EIO;
152 }
153
154 /* Linux doesn't require a credp for many functions, and crref is an expensive
155  * operation. This helper function avoids obtaining it for VerifyVCache calls
156  */
157
158 static inline int
159 afs_linux_VerifyVCache(struct vcache *avc, cred_t **retcred) {
160     cred_t *credp = NULL;
161     struct vrequest *treq = NULL;
162     int code;
163
164     if (avc->f.states & CStatd) {
165         if (retcred)
166             *retcred = NULL;
167         return 0;
168     }
169
170     credp = crref();
171
172     code = afs_CreateReq(&treq, credp);
173     if (code == 0) {
174         code = afs_VerifyVCache(avc, treq);
175         afs_DestroyReq(treq);
176     }
177
178     if (retcred != NULL)
179         *retcred = credp;
180     else
181         crfree(credp);
182
183     return afs_convert_code(code);
184 }
185
186 #if defined(STRUCT_FILE_OPERATIONS_HAS_READ_ITER) || defined(HAVE_LINUX_GENERIC_FILE_AIO_READ)
187 # if defined(STRUCT_FILE_OPERATIONS_HAS_READ_ITER)
188 static ssize_t
189 afs_linux_read_iter(struct kiocb *iocb, struct iov_iter *iter)
190 # elif defined(LINUX_HAS_NONVECTOR_AIO)
191 static ssize_t
192 afs_linux_aio_read(struct kiocb *iocb, char __user *buf, size_t bufsize,
193                    loff_t pos)
194 # else
195 static ssize_t
196 afs_linux_aio_read(struct kiocb *iocb, const struct iovec *buf,
197                    unsigned long bufsize, loff_t pos)
198 # endif
199 {
200     struct file *fp = iocb->ki_filp;
201     ssize_t code = 0;
202     struct vcache *vcp = VTOAFS(fp->f_dentry->d_inode);
203 # if defined(STRUCT_FILE_OPERATIONS_HAS_READ_ITER)
204     loff_t pos = iocb->ki_pos;
205     unsigned long bufsize = iter->nr_segs;
206 # endif
207
208
209     AFS_GLOCK();
210     afs_Trace4(afs_iclSetp, CM_TRACE_AIOREADOP, ICL_TYPE_POINTER, vcp,
211                ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(pos), ICL_TYPE_INT32,
212                (afs_int32)bufsize, ICL_TYPE_INT32, 99999);
213     code = afs_linux_VerifyVCache(vcp, NULL);
214
215     if (code == 0) {
216         /* Linux's FlushPages implementation doesn't ever use credp,
217          * so we optimise by not using it */
218         osi_FlushPages(vcp, NULL);      /* ensure stale pages are gone */
219         AFS_GUNLOCK();
220 # if defined(STRUCT_FILE_OPERATIONS_HAS_READ_ITER)
221         code = generic_file_read_iter(iocb, iter);
222 # else
223         code = generic_file_aio_read(iocb, buf, bufsize, pos);
224 # endif
225         AFS_GLOCK();
226     }
227
228     afs_Trace4(afs_iclSetp, CM_TRACE_AIOREADOP, ICL_TYPE_POINTER, vcp,
229                ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(pos), ICL_TYPE_INT32,
230                (afs_int32)bufsize, ICL_TYPE_INT32, code);
231     AFS_GUNLOCK();
232     return code;
233 }
234 #else
235 static ssize_t
236 afs_linux_read(struct file *fp, char *buf, size_t count, loff_t * offp)
237 {
238     ssize_t code = 0;
239     struct vcache *vcp = VTOAFS(fp->f_dentry->d_inode);
240
241     AFS_GLOCK();
242     afs_Trace4(afs_iclSetp, CM_TRACE_READOP, ICL_TYPE_POINTER, vcp,
243                ICL_TYPE_OFFSET, offp, ICL_TYPE_INT32, count, ICL_TYPE_INT32,
244                99999);
245     code = afs_linux_VerifyVCache(vcp, NULL);
246
247     if (code == 0) {
248         /* Linux's FlushPages implementation doesn't ever use credp,
249          * so we optimise by not using it */
250         osi_FlushPages(vcp, NULL);      /* ensure stale pages are gone */
251         AFS_GUNLOCK();
252         code = do_sync_read(fp, buf, count, offp);
253         AFS_GLOCK();
254     }
255
256     afs_Trace4(afs_iclSetp, CM_TRACE_READOP, ICL_TYPE_POINTER, vcp,
257                ICL_TYPE_OFFSET, offp, ICL_TYPE_INT32, count, ICL_TYPE_INT32,
258                code);
259     AFS_GUNLOCK();
260     return code;
261 }
262 #endif
263
264
265 /* Now we have integrated VM for writes as well as reads. the generic write operations
266  * also take care of re-positioning the pointer if file is open in append
267  * mode. Call fake open/close to ensure we do writes of core dumps.
268  */
269 #if defined(STRUCT_FILE_OPERATIONS_HAS_READ_ITER) || defined(HAVE_LINUX_GENERIC_FILE_AIO_READ)
270 # if defined(STRUCT_FILE_OPERATIONS_HAS_READ_ITER)
271 static ssize_t
272 afs_linux_write_iter(struct kiocb *iocb, struct iov_iter *iter)
273 # elif defined(LINUX_HAS_NONVECTOR_AIO)
274 static ssize_t
275 afs_linux_aio_write(struct kiocb *iocb, const char __user *buf, size_t bufsize,
276                     loff_t pos)
277 # else
278 static ssize_t
279 afs_linux_aio_write(struct kiocb *iocb, const struct iovec *buf,
280                     unsigned long bufsize, loff_t pos)
281 # endif
282 {
283     ssize_t code = 0;
284     struct vcache *vcp = VTOAFS(iocb->ki_filp->f_dentry->d_inode);
285     cred_t *credp;
286 # if defined(STRUCT_FILE_OPERATIONS_HAS_READ_ITER)
287     loff_t pos = iocb->ki_pos;
288     unsigned long bufsize = iter->nr_segs;
289 # endif
290
291     AFS_GLOCK();
292
293     afs_Trace4(afs_iclSetp, CM_TRACE_AIOWRITEOP, ICL_TYPE_POINTER, vcp,
294                ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(pos), ICL_TYPE_INT32,
295                (afs_int32)bufsize, ICL_TYPE_INT32,
296                (iocb->ki_filp->f_flags & O_APPEND) ? 99998 : 99999);
297
298     code = afs_linux_VerifyVCache(vcp, &credp);
299
300     ObtainWriteLock(&vcp->lock, 529);
301     afs_FakeOpen(vcp);
302     ReleaseWriteLock(&vcp->lock);
303     if (code == 0) {
304             AFS_GUNLOCK();
305 # if defined(STRUCT_FILE_OPERATIONS_HAS_READ_ITER)
306             code = generic_file_write_iter(iocb, iter);
307 # else
308             code = generic_file_aio_write(iocb, buf, bufsize, pos);
309 # endif
310             AFS_GLOCK();
311     }
312
313     ObtainWriteLock(&vcp->lock, 530);
314
315     if (vcp->execsOrWriters == 1 && !credp)
316       credp = crref();
317
318     afs_FakeClose(vcp, credp);
319     ReleaseWriteLock(&vcp->lock);
320
321     afs_Trace4(afs_iclSetp, CM_TRACE_AIOWRITEOP, ICL_TYPE_POINTER, vcp,
322                ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(pos), ICL_TYPE_INT32,
323                (afs_int32)bufsize, ICL_TYPE_INT32, code);
324
325     if (credp)
326       crfree(credp);
327     AFS_GUNLOCK();
328     return code;
329 }
330 #else
331 static ssize_t
332 afs_linux_write(struct file *fp, const char *buf, size_t count, loff_t * offp)
333 {
334     ssize_t code = 0;
335     struct vcache *vcp = VTOAFS(fp->f_dentry->d_inode);
336     cred_t *credp;
337
338     AFS_GLOCK();
339
340     afs_Trace4(afs_iclSetp, CM_TRACE_WRITEOP, ICL_TYPE_POINTER, vcp,
341                ICL_TYPE_OFFSET, offp, ICL_TYPE_INT32, count, ICL_TYPE_INT32,
342                (fp->f_flags & O_APPEND) ? 99998 : 99999);
343
344     code = afs_linux_VerifyVCache(vcp, &credp);
345
346     ObtainWriteLock(&vcp->lock, 529);
347     afs_FakeOpen(vcp);
348     ReleaseWriteLock(&vcp->lock);
349     if (code == 0) {
350             AFS_GUNLOCK();
351             code = do_sync_write(fp, buf, count, offp);
352             AFS_GLOCK();
353     }
354
355     ObtainWriteLock(&vcp->lock, 530);
356
357     if (vcp->execsOrWriters == 1 && !credp)
358       credp = crref();
359
360     afs_FakeClose(vcp, credp);
361     ReleaseWriteLock(&vcp->lock);
362
363     afs_Trace4(afs_iclSetp, CM_TRACE_WRITEOP, ICL_TYPE_POINTER, vcp,
364                ICL_TYPE_OFFSET, offp, ICL_TYPE_INT32, count, ICL_TYPE_INT32,
365                code);
366
367     if (credp)
368       crfree(credp);
369     AFS_GUNLOCK();
370     return code;
371 }
372 #endif
373
374 extern int BlobScan(struct dcache * afile, afs_int32 ablob, afs_int32 *ablobOut);
375
376 /* This is a complete rewrite of afs_readdir, since we can make use of
377  * filldir instead of afs_readdir_move. Note that changes to vcache/dcache
378  * handling and use of bulkstats will need to be reflected here as well.
379  */
380 static int
381 #if defined(USE_FOP_ITERATE)
382 afs_linux_readdir(struct file *fp, struct dir_context *ctx)
383 #else
384 afs_linux_readdir(struct file *fp, void *dirbuf, filldir_t filldir)
385 #endif
386 {
387     struct vcache *avc = VTOAFS(FILE_INODE(fp));
388     struct vrequest *treq = NULL;
389     struct dcache *tdc;
390     int code;
391     int offset;
392     afs_int32 dirpos;
393     struct DirEntry *de;
394     struct DirBuffer entry;
395     ino_t ino;
396     int len;
397     afs_size_t origOffset, tlen;
398     cred_t *credp = crref();
399     struct afs_fakestat_state fakestat;
400
401     AFS_GLOCK();
402     AFS_STATCNT(afs_readdir);
403
404     code = afs_convert_code(afs_CreateReq(&treq, credp));
405     crfree(credp);
406     if (code)
407         goto out1;
408
409     afs_InitFakeStat(&fakestat);
410     code = afs_convert_code(afs_EvalFakeStat(&avc, &fakestat, treq));
411     if (code)
412         goto out;
413
414     /* update the cache entry */
415   tagain:
416     code = afs_convert_code(afs_VerifyVCache(avc, treq));
417     if (code)
418         goto out;
419
420     /* get a reference to the entire directory */
421     tdc = afs_GetDCache(avc, (afs_size_t) 0, treq, &origOffset, &tlen, 1);
422     len = tlen;
423     if (!tdc) {
424         code = -EIO;
425         goto out;
426     }
427     ObtainWriteLock(&avc->lock, 811);
428     ObtainReadLock(&tdc->lock);
429     /*
430      * Make sure that the data in the cache is current. There are two
431      * cases we need to worry about:
432      * 1. The cache data is being fetched by another process.
433      * 2. The cache data is no longer valid
434      */
435     while ((avc->f.states & CStatd)
436            && (tdc->dflags & DFFetching)
437            && afs_IsDCacheFresh(tdc, avc)) {
438         ReleaseReadLock(&tdc->lock);
439         ReleaseWriteLock(&avc->lock);
440         afs_osi_Sleep(&tdc->validPos);
441         ObtainWriteLock(&avc->lock, 812);
442         ObtainReadLock(&tdc->lock);
443     }
444     if (!(avc->f.states & CStatd)
445         || !afs_IsDCacheFresh(tdc, avc)) {
446         ReleaseReadLock(&tdc->lock);
447         ReleaseWriteLock(&avc->lock);
448         afs_PutDCache(tdc);
449         goto tagain;
450     }
451
452     /* Set the readdir-in-progress flag, and downgrade the lock
453      * to shared so others will be able to acquire a read lock.
454      */
455     avc->f.states |= CReadDir;
456     avc->dcreaddir = tdc;
457     avc->readdir_pid = MyPidxx2Pid(MyPidxx);
458     ConvertWToSLock(&avc->lock);
459
460     /* Fill in until we get an error or we're done. This implementation
461      * takes an offset in units of blobs, rather than bytes.
462      */
463     code = 0;
464 #if defined(USE_FOP_ITERATE)
465     offset = ctx->pos;
466 #else
467     offset = (int) fp->f_pos;
468 #endif
469     while (1) {
470         dirpos = 0;
471         code = BlobScan(tdc, offset, &dirpos);
472         if (code == 0 && dirpos == 0) {
473             /* We've reached EOF of the dir blob, so we can stop looking for
474              * entries. */
475             break;
476         }
477
478         if (code == 0) {
479             code = afs_dir_GetVerifiedBlob(tdc, dirpos, &entry);
480         }
481         if (code) {
482             if (!(avc->f.states & CCorrupt)) {
483                 struct cell *tc = afs_GetCellStale(avc->f.fid.Cell, READ_LOCK);
484                 afs_warn("afs: Corrupt directory (%d.%d.%d.%d [%s] @%lx, pos %d)\n",
485                          avc->f.fid.Cell, avc->f.fid.Fid.Volume,
486                          avc->f.fid.Fid.Vnode, avc->f.fid.Fid.Unique,
487                          tc ? tc->cellName : "",
488                          (unsigned long)&tdc->f.inode, dirpos);
489                 if (tc)
490                     afs_PutCell(tc, READ_LOCK);
491                 UpgradeSToWLock(&avc->lock, 814);
492                 avc->f.states |= CCorrupt;
493             }
494             code = -EIO;
495             goto unlock_out;
496         }
497
498         de = (struct DirEntry *)entry.data;
499         ino = afs_calc_inum (avc->f.fid.Cell, avc->f.fid.Fid.Volume,
500                              ntohl(de->fid.vnode));
501         len = strlen(de->name);
502
503         /* filldir returns -EINVAL when the buffer is full. */
504         {
505             unsigned int type = DT_UNKNOWN;
506             struct VenusFid afid;
507             struct vcache *tvc;
508             int vtype;
509             afid.Cell = avc->f.fid.Cell;
510             afid.Fid.Volume = avc->f.fid.Fid.Volume;
511             afid.Fid.Vnode = ntohl(de->fid.vnode);
512             afid.Fid.Unique = ntohl(de->fid.vunique);
513             if ((avc->f.states & CForeign) == 0 && (ntohl(de->fid.vnode) & 1)) {
514                 type = DT_DIR;
515             } else if ((tvc = afs_FindVCache(&afid, 0, 0))) {
516                 if (tvc->mvstat != AFS_MVSTAT_FILE) {
517                     type = DT_DIR;
518                 } else if (((tvc->f.states) & (CStatd | CTruth))) {
519                     /* CTruth will be set if the object has
520                      *ever* been statd */
521                     vtype = vType(tvc);
522                     if (vtype == VDIR)
523                         type = DT_DIR;
524                     else if (vtype == VREG)
525                         type = DT_REG;
526                     /* Don't do this until we're sure it can't be a mtpt */
527                     /* else if (vtype == VLNK)
528                      * type=DT_LNK; */
529                     /* what other types does AFS support? */
530                 }
531                 /* clean up from afs_FindVCache */
532                 afs_PutVCache(tvc);
533             }
534             /*
535              * If this is NFS readdirplus, then the filler is going to
536              * call getattr on this inode, which will deadlock if we're
537              * holding the GLOCK.
538              */
539             AFS_GUNLOCK();
540 #if defined(USE_FOP_ITERATE)
541             /* dir_emit returns a bool - true when it succeeds.
542              * Inverse the result to fit with how we check "code" */
543             code = !dir_emit(ctx, de->name, len, ino, type);
544 #else
545             code = (*filldir) (dirbuf, de->name, len, offset, ino, type);
546 #endif
547             AFS_GLOCK();
548         }
549         DRelease(&entry, 0);
550         if (code)
551             break;
552         offset = dirpos + 1 + ((len + 16) >> 5);
553     }
554     /* If filldir didn't fill in the last one this is still pointing to that
555      * last attempt.
556      */
557     code = 0;
558
559 unlock_out:
560 #if defined(USE_FOP_ITERATE)
561     ctx->pos = (loff_t) offset;
562 #else
563     fp->f_pos = (loff_t) offset;
564 #endif
565     ReleaseReadLock(&tdc->lock);
566     afs_PutDCache(tdc);
567     UpgradeSToWLock(&avc->lock, 813);
568     avc->f.states &= ~CReadDir;
569     avc->dcreaddir = 0;
570     avc->readdir_pid = 0;
571     ReleaseSharedLock(&avc->lock);
572
573 out:
574     afs_PutFakeStat(&fakestat);
575     afs_DestroyReq(treq);
576 out1:
577     AFS_GUNLOCK();
578     return code;
579 }
580
581
582 /* in afs_pioctl.c */
583 extern int afs_xioctl(struct inode *ip, struct file *fp, unsigned int com,
584                       unsigned long arg);
585
586 #if defined(HAVE_UNLOCKED_IOCTL) || defined(HAVE_COMPAT_IOCTL)
587 static long afs_unlocked_xioctl(struct file *fp, unsigned int com,
588                                unsigned long arg) {
589     return afs_xioctl(FILE_INODE(fp), fp, com, arg);
590
591 }
592 #endif
593
594
595 static int
596 afs_linux_mmap(struct file *fp, struct vm_area_struct *vmap)
597 {
598     struct vcache *vcp = VTOAFS(FILE_INODE(fp));
599     int code;
600
601     AFS_GLOCK();
602     afs_Trace4(afs_iclSetp, CM_TRACE_GMAP, ICL_TYPE_POINTER, vcp,
603                ICL_TYPE_POINTER, vmap->vm_start, ICL_TYPE_LONG,
604                vmap->vm_end - vmap->vm_start, ICL_TYPE_LONG, 0);
605
606     /* get a validated vcache entry */
607     code = afs_linux_VerifyVCache(vcp, NULL);
608
609     if (code == 0) {
610         /* Linux's Flushpage implementation doesn't use credp, so optimise
611          * our code to not need to crref() it */
612         osi_FlushPages(vcp, NULL); /* ensure stale pages are gone */
613         AFS_GUNLOCK();
614         code = generic_file_mmap(fp, vmap);
615         AFS_GLOCK();
616         if (!code)
617             vcp->f.states |= CMAPPED;
618     }
619     AFS_GUNLOCK();
620
621     return code;
622 }
623
624 static int
625 afs_linux_open(struct inode *ip, struct file *fp)
626 {
627     struct vcache *vcp = VTOAFS(ip);
628     cred_t *credp = crref();
629     int code;
630
631     AFS_GLOCK();
632     code = afs_open(&vcp, fp->f_flags, credp);
633     AFS_GUNLOCK();
634
635     crfree(credp);
636     return afs_convert_code(code);
637 }
638
639 static int
640 afs_linux_release(struct inode *ip, struct file *fp)
641 {
642     struct vcache *vcp = VTOAFS(ip);
643     cred_t *credp = crref();
644     int code = 0;
645
646     AFS_GLOCK();
647     code = afs_close(vcp, fp->f_flags, credp);
648     ObtainWriteLock(&vcp->lock, 807);
649     if (vcp->cred) {
650         crfree(vcp->cred);
651         vcp->cred = NULL;
652     }
653     ReleaseWriteLock(&vcp->lock);
654     AFS_GUNLOCK();
655
656     crfree(credp);
657     return afs_convert_code(code);
658 }
659
660 static int
661 #if defined(FOP_FSYNC_TAKES_DENTRY)
662 afs_linux_fsync(struct file *fp, struct dentry *dp, int datasync)
663 #elif defined(FOP_FSYNC_TAKES_RANGE)
664 afs_linux_fsync(struct file *fp, loff_t start, loff_t end, int datasync)
665 #else
666 afs_linux_fsync(struct file *fp, int datasync)
667 #endif
668 {
669     int code;
670     struct inode *ip = FILE_INODE(fp);
671     cred_t *credp = crref();
672
673 #if defined(FOP_FSYNC_TAKES_RANGE)
674     afs_linux_lock_inode(ip);
675 #endif
676     AFS_GLOCK();
677     code = afs_fsync(VTOAFS(ip), credp);
678     AFS_GUNLOCK();
679 #if defined(FOP_FSYNC_TAKES_RANGE)
680     afs_linux_unlock_inode(ip);
681 #endif
682     crfree(credp);
683     return afs_convert_code(code);
684
685 }
686
687
688 static int
689 afs_linux_lock(struct file *fp, int cmd, struct file_lock *flp)
690 {
691     int code = 0;
692     struct vcache *vcp = VTOAFS(FILE_INODE(fp));
693     cred_t *credp = crref();
694     struct AFS_FLOCK flock;
695
696     /* Convert to a lock format afs_lockctl understands. */
697     memset(&flock, 0, sizeof(flock));
698     flock.l_type = flp->fl_type;
699     flock.l_pid = flp->fl_pid;
700     flock.l_whence = 0;
701     flock.l_start = flp->fl_start;
702     if (flp->fl_end == OFFSET_MAX)
703         flock.l_len = 0; /* Lock to end of file */
704     else
705         flock.l_len = flp->fl_end - flp->fl_start + 1;
706
707     /* Safe because there are no large files, yet */
708 #if defined(F_GETLK64) && (F_GETLK != F_GETLK64)
709     if (cmd == F_GETLK64)
710         cmd = F_GETLK;
711     else if (cmd == F_SETLK64)
712         cmd = F_SETLK;
713     else if (cmd == F_SETLKW64)
714         cmd = F_SETLKW;
715 #endif /* F_GETLK64 && F_GETLK != F_GETLK64 */
716
717     AFS_GLOCK();
718     code = afs_convert_code(afs_lockctl(vcp, &flock, cmd, credp));
719     AFS_GUNLOCK();
720
721     if ((code == 0 || flp->fl_type == F_UNLCK) &&
722         (cmd == F_SETLK || cmd == F_SETLKW)) {
723         code = afs_posix_lock_file(fp, flp);
724         if (code && flp->fl_type != F_UNLCK) {
725             struct AFS_FLOCK flock2;
726             flock2 = flock;
727             flock2.l_type = F_UNLCK;
728             AFS_GLOCK();
729             afs_lockctl(vcp, &flock2, F_SETLK, credp);
730             AFS_GUNLOCK();
731         }
732     }
733     /* If lockctl says there are no conflicting locks, then also check with the
734      * kernel, as lockctl knows nothing about byte range locks
735      */
736     if (code == 0 && cmd == F_GETLK && flock.l_type == F_UNLCK) {
737         afs_posix_test_lock(fp, flp);
738         /* If we found a lock in the kernel's structure, return it */
739         if (flp->fl_type != F_UNLCK) {
740             crfree(credp);
741             return 0;
742         }
743     }
744
745     /* Convert flock back to Linux's file_lock */
746     flp->fl_type = flock.l_type;
747     flp->fl_pid = flock.l_pid;
748     flp->fl_start = flock.l_start;
749     if (flock.l_len == 0)
750         flp->fl_end = OFFSET_MAX; /* Lock to end of file */
751     else
752         flp->fl_end = flock.l_start + flock.l_len - 1;
753
754     crfree(credp);
755     return code;
756 }
757
758 #ifdef STRUCT_FILE_OPERATIONS_HAS_FLOCK
759 static int
760 afs_linux_flock(struct file *fp, int cmd, struct file_lock *flp) {
761     int code = 0;
762     struct vcache *vcp = VTOAFS(FILE_INODE(fp));
763     cred_t *credp = crref();
764     struct AFS_FLOCK flock;
765     /* Convert to a lock format afs_lockctl understands. */
766     memset(&flock, 0, sizeof(flock));
767     flock.l_type = flp->fl_type;
768     flock.l_pid = flp->fl_pid;
769     flock.l_whence = 0;
770     flock.l_start = 0;
771     flock.l_len = 0;
772
773     /* Safe because there are no large files, yet */
774 #if defined(F_GETLK64) && (F_GETLK != F_GETLK64)
775     if (cmd == F_GETLK64)
776         cmd = F_GETLK;
777     else if (cmd == F_SETLK64)
778         cmd = F_SETLK;
779     else if (cmd == F_SETLKW64)
780         cmd = F_SETLKW;
781 #endif /* F_GETLK64 && F_GETLK != F_GETLK64 */
782
783     AFS_GLOCK();
784     code = afs_convert_code(afs_lockctl(vcp, &flock, cmd, credp));
785     AFS_GUNLOCK();
786
787     if ((code == 0 || flp->fl_type == F_UNLCK) &&
788         (cmd == F_SETLK || cmd == F_SETLKW)) {
789         flp->fl_flags &=~ FL_SLEEP;
790         code = flock_lock_file_wait(fp, flp);
791         if (code && flp->fl_type != F_UNLCK) {
792             struct AFS_FLOCK flock2;
793             flock2 = flock;
794             flock2.l_type = F_UNLCK;
795             AFS_GLOCK();
796             afs_lockctl(vcp, &flock2, F_SETLK, credp);
797             AFS_GUNLOCK();
798         }
799     }
800     /* Convert flock back to Linux's file_lock */
801     flp->fl_type = flock.l_type;
802     flp->fl_pid = flock.l_pid;
803
804     crfree(credp);
805     return code;
806 }
807 #endif
808
809 /* afs_linux_flush
810  * essentially the same as afs_fsync() but we need to get the return
811  * code for the sys_close() here, not afs_linux_release(), so call
812  * afs_StoreAllSegments() with AFS_LASTSTORE
813  */
814 static int
815 #if defined(FOP_FLUSH_TAKES_FL_OWNER_T)
816 afs_linux_flush(struct file *fp, fl_owner_t id)
817 #else
818 afs_linux_flush(struct file *fp)
819 #endif
820 {
821     struct vrequest *treq = NULL;
822     struct vcache *vcp;
823     cred_t *credp;
824     int code;
825     int bypasscache = 0;
826
827     AFS_GLOCK();
828
829     if ((fp->f_flags & O_ACCMODE) == O_RDONLY) { /* readers dont flush */
830         AFS_GUNLOCK();
831         return 0;
832     }
833
834     AFS_DISCON_LOCK();
835
836     credp = crref();
837     vcp = VTOAFS(FILE_INODE(fp));
838
839     code = afs_CreateReq(&treq, credp);
840     if (code)
841         goto out;
842     /* If caching is bypassed for this file, or globally, just return 0 */
843     if (cache_bypass_strategy == ALWAYS_BYPASS_CACHE)
844         bypasscache = 1;
845     else {
846         ObtainReadLock(&vcp->lock);
847         if (vcp->cachingStates & FCSBypass)
848             bypasscache = 1;
849         ReleaseReadLock(&vcp->lock);
850     }
851     if (bypasscache) {
852         /* future proof: don't rely on 0 return from afs_InitReq */
853         code = 0;
854         goto out;
855     }
856
857     ObtainSharedLock(&vcp->lock, 535);
858     if ((vcp->execsOrWriters > 0) && (file_count(fp) == 1)) {
859         UpgradeSToWLock(&vcp->lock, 536);
860         if (!AFS_IS_DISCONNECTED) {
861                 code = afs_StoreAllSegments(vcp,
862                                 treq,
863                                 AFS_SYNC | AFS_LASTSTORE);
864         } else {
865                 afs_DisconAddDirty(vcp, VDisconWriteOsiFlush, 1);
866         }
867         ConvertWToSLock(&vcp->lock);
868     }
869     code = afs_CheckCode(code, treq, 54);
870     ReleaseSharedLock(&vcp->lock);
871
872 out:
873     afs_DestroyReq(treq);
874     AFS_DISCON_UNLOCK();
875     AFS_GUNLOCK();
876
877     crfree(credp);
878     return afs_convert_code(code);
879 }
880
881 struct file_operations afs_dir_fops = {
882   .read =       generic_read_dir,
883 #if defined(USE_FOP_ITERATE)
884   .iterate =    afs_linux_readdir,
885 #else
886   .readdir =    afs_linux_readdir,
887 #endif
888 #ifdef HAVE_UNLOCKED_IOCTL
889   .unlocked_ioctl = afs_unlocked_xioctl,
890 #else
891   .ioctl =      afs_xioctl,
892 #endif
893 #ifdef HAVE_COMPAT_IOCTL
894   .compat_ioctl = afs_unlocked_xioctl,
895 #endif
896   .open =       afs_linux_open,
897   .release =    afs_linux_release,
898   .llseek =     default_llseek,
899 #ifdef HAVE_LINUX_NOOP_FSYNC
900   .fsync =      noop_fsync,
901 #else
902   .fsync =      simple_sync_file,
903 #endif
904 };
905
906 struct file_operations afs_file_fops = {
907 #ifdef STRUCT_FILE_OPERATIONS_HAS_READ_ITER
908   .read_iter =  afs_linux_read_iter,
909   .write_iter = afs_linux_write_iter,
910 # if !defined(HAVE_LINUX___VFS_WRITE) && !defined(HAVE_LINUX_KERNEL_WRITE)
911   .read =       new_sync_read,
912   .write =      new_sync_write,
913 # endif
914 #elif defined(HAVE_LINUX_GENERIC_FILE_AIO_READ)
915   .aio_read =   afs_linux_aio_read,
916   .aio_write =  afs_linux_aio_write,
917   .read =       do_sync_read,
918   .write =      do_sync_write,
919 #else
920   .read =       afs_linux_read,
921   .write =      afs_linux_write,
922 #endif
923 #ifdef HAVE_UNLOCKED_IOCTL
924   .unlocked_ioctl = afs_unlocked_xioctl,
925 #else
926   .ioctl =      afs_xioctl,
927 #endif
928 #ifdef HAVE_COMPAT_IOCTL
929   .compat_ioctl = afs_unlocked_xioctl,
930 #endif
931   .mmap =       afs_linux_mmap,
932   .open =       afs_linux_open,
933   .flush =      afs_linux_flush,
934 #if defined(STRUCT_FILE_OPERATIONS_HAS_SENDFILE)
935   .sendfile =   generic_file_sendfile,
936 #endif
937 #if defined(STRUCT_FILE_OPERATIONS_HAS_SPLICE) && !defined(HAVE_LINUX_DEFAULT_FILE_SPLICE_READ)
938 # if defined(HAVE_LINUX_ITER_FILE_SPLICE_WRITE)
939   .splice_write = iter_file_splice_write,
940 # else
941   .splice_write = generic_file_splice_write,
942 # endif
943   .splice_read = generic_file_splice_read,
944 #endif
945   .release =    afs_linux_release,
946   .fsync =      afs_linux_fsync,
947   .lock =       afs_linux_lock,
948 #ifdef STRUCT_FILE_OPERATIONS_HAS_FLOCK
949   .flock =      afs_linux_flock,
950 #endif
951   .llseek =     default_llseek,
952 };
953
954 static struct dentry *
955 canonical_dentry(struct inode *ip)
956 {
957     struct vcache *vcp = VTOAFS(ip);
958     struct dentry *first = NULL, *ret = NULL, *cur;
959 #if defined(D_ALIAS_IS_HLIST) && !defined(HLIST_ITERATOR_NO_NODE)
960     struct hlist_node *p;
961 #endif
962
963     /* general strategy:
964      * if vcp->target_link is set, and can be found in ip->i_dentry, use that.
965      * otherwise, use the first dentry in ip->i_dentry.
966      * if ip->i_dentry is empty, use the 'dentry' argument we were given.
967      */
968     /* note that vcp->target_link specifies which dentry to use, but we have
969      * no reference held on that dentry. so, we cannot use or dereference
970      * vcp->target_link itself, since it may have been freed. instead, we only
971      * use it to compare to pointers in the ip->i_dentry list. */
972
973     d_prune_aliases(ip);
974
975     afs_d_alias_lock(ip);
976
977 #if defined(D_ALIAS_IS_HLIST)
978 # if defined(HLIST_ITERATOR_NO_NODE)
979     hlist_for_each_entry(cur, &ip->i_dentry, d_alias) {
980 # else
981     hlist_for_each_entry(cur, p, &ip->i_dentry, d_alias) {
982 # endif
983 #else
984     list_for_each_entry_reverse(cur, &ip->i_dentry, d_alias) {
985 #endif
986
987         if (!vcp->target_link || cur == vcp->target_link) {
988             ret = cur;
989             break;
990         }
991
992         if (!first) {
993             first = cur;
994         }
995     }
996     if (!ret && first) {
997         ret = first;
998     }
999
1000     vcp->target_link = ret;
1001
1002     if (ret) {
1003         afs_linux_dget(ret);
1004     }
1005     afs_d_alias_unlock(ip);
1006
1007     return ret;
1008 }
1009
1010 /**********************************************************************
1011  * AFS Linux dentry operations
1012  **********************************************************************/
1013
1014 /* afs_linux_revalidate
1015  * Ensure vcache is stat'd before use. Return 0 if entry is valid.
1016  */
1017 static int
1018 afs_linux_revalidate(struct dentry *dp)
1019 {
1020     struct vattr *vattr = NULL;
1021     struct vcache *vcp = VTOAFS(dp->d_inode);
1022     cred_t *credp;
1023     int code;
1024
1025     if (afs_shuttingdown != AFS_RUNNING)
1026         return EIO;
1027
1028     AFS_GLOCK();
1029
1030     code = afs_CreateAttr(&vattr);
1031     if (code) {
1032         goto out;
1033     }
1034
1035     /* This avoids the crref when we don't have to do it. Watch for
1036      * changes in afs_getattr that don't get replicated here!
1037      */
1038     if (vcp->f.states & CStatd &&
1039         (!afs_fakestat_enable || vcp->mvstat != AFS_MVSTAT_MTPT) &&
1040         !afs_nfsexporter &&
1041         (vType(vcp) == VDIR || vType(vcp) == VLNK)) {
1042         code = afs_CopyOutAttrs(vcp, vattr);
1043     } else {
1044         credp = crref();
1045         code = afs_getattr(vcp, vattr, credp);
1046         crfree(credp);
1047     }
1048
1049     if (!code)
1050         afs_fill_inode(AFSTOV(vcp), vattr);
1051
1052     afs_DestroyAttr(vattr);
1053
1054 out:
1055     AFS_GUNLOCK();
1056
1057     return afs_convert_code(code);
1058 }
1059
1060 /* vattr_setattr
1061  * Set iattr data into vattr. Assume vattr cleared before call.
1062  */
1063 static void
1064 iattr2vattr(struct vattr *vattrp, struct iattr *iattrp)
1065 {
1066     vattrp->va_mask = iattrp->ia_valid;
1067     if (iattrp->ia_valid & ATTR_MODE)
1068         vattrp->va_mode = iattrp->ia_mode;
1069     if (iattrp->ia_valid & ATTR_UID)
1070         vattrp->va_uid = afs_from_kuid(iattrp->ia_uid);
1071     if (iattrp->ia_valid & ATTR_GID)
1072         vattrp->va_gid = afs_from_kgid(iattrp->ia_gid);
1073     if (iattrp->ia_valid & ATTR_SIZE)
1074         vattrp->va_size = iattrp->ia_size;
1075     if (iattrp->ia_valid & ATTR_ATIME) {
1076         vattrp->va_atime.tv_sec = iattrp->ia_atime.tv_sec;
1077         vattrp->va_atime.tv_nsec = 0;
1078     }
1079     if (iattrp->ia_valid & ATTR_MTIME) {
1080         vattrp->va_mtime.tv_sec = iattrp->ia_mtime.tv_sec;
1081         vattrp->va_mtime.tv_nsec = 0;
1082     }
1083     if (iattrp->ia_valid & ATTR_CTIME) {
1084         vattrp->va_ctime.tv_sec = iattrp->ia_ctime.tv_sec;
1085         vattrp->va_ctime.tv_nsec = 0;
1086     }
1087 }
1088
1089 /* vattr2inode
1090  * Rewrite the inode cache from the attr. Assumes all vattr fields are valid.
1091  */
1092 void
1093 vattr2inode(struct inode *ip, struct vattr *vp)
1094 {
1095     ip->i_ino = vp->va_nodeid;
1096 #ifdef HAVE_LINUX_SET_NLINK
1097     set_nlink(ip, vp->va_nlink);
1098 #else
1099     ip->i_nlink = vp->va_nlink;
1100 #endif
1101     ip->i_blocks = vp->va_blocks;
1102 #ifdef STRUCT_INODE_HAS_I_BLKBITS
1103     ip->i_blkbits = AFS_BLKBITS;
1104 #endif
1105 #ifdef STRUCT_INODE_HAS_I_BLKSIZE
1106     ip->i_blksize = vp->va_blocksize;
1107 #endif
1108     ip->i_rdev = vp->va_rdev;
1109     ip->i_mode = vp->va_mode;
1110     ip->i_uid = afs_make_kuid(vp->va_uid);
1111     ip->i_gid = afs_make_kgid(vp->va_gid);
1112     i_size_write(ip, vp->va_size);
1113     ip->i_atime.tv_sec = vp->va_atime.tv_sec;
1114     ip->i_atime.tv_nsec = 0;
1115     ip->i_mtime.tv_sec = vp->va_mtime.tv_sec;
1116     /* Set the mtime nanoseconds to the sysname generation number.
1117      * This convinces NFS clients that all directories have changed
1118      * any time the sysname list changes.
1119      */
1120     ip->i_mtime.tv_nsec = afs_sysnamegen;
1121     ip->i_ctime.tv_sec = vp->va_ctime.tv_sec;
1122     ip->i_ctime.tv_nsec = 0;
1123 }
1124
1125 /* afs_notify_change
1126  * Linux version of setattr call. What to change is in the iattr struct.
1127  * We need to set bits in both the Linux inode as well as the vcache.
1128  */
1129 static int
1130 afs_notify_change(struct dentry *dp, struct iattr *iattrp)
1131 {
1132     struct vattr *vattr = NULL;
1133     cred_t *credp = crref();
1134     struct inode *ip = dp->d_inode;
1135     int code;
1136
1137     AFS_GLOCK();
1138     code = afs_CreateAttr(&vattr);
1139     if (code) {
1140         goto out;
1141     }
1142
1143     iattr2vattr(vattr, iattrp); /* Convert for AFS vnodeops call. */
1144
1145     code = afs_setattr(VTOAFS(ip), vattr, credp);
1146     if (!code) {
1147         afs_getattr(VTOAFS(ip), vattr, credp);
1148         vattr2inode(ip, vattr);
1149     }
1150     afs_DestroyAttr(vattr);
1151
1152 out:
1153     AFS_GUNLOCK();
1154     crfree(credp);
1155     return afs_convert_code(code);
1156 }
1157
1158 #if defined(IOP_GETATTR_TAKES_PATH_STRUCT)
1159 static int
1160 afs_linux_getattr(const struct path *path, struct kstat *stat, u32 request_mask, unsigned int sync_mode)
1161 {
1162         int err = afs_linux_revalidate(path->dentry);
1163         if (!err) {
1164                 generic_fillattr(path->dentry->d_inode, stat);
1165         }
1166         return err;
1167 }
1168 #else
1169 static int
1170 afs_linux_getattr(struct vfsmount *mnt, struct dentry *dentry, struct kstat *stat)
1171 {
1172         int err = afs_linux_revalidate(dentry);
1173         if (!err) {
1174                 generic_fillattr(dentry->d_inode, stat);
1175         }
1176         return err;
1177 }
1178 #endif
1179
1180 static afs_uint32
1181 parent_vcache_dv(struct inode *inode, cred_t *credp)
1182 {
1183     int free_cred = 0;
1184     struct vcache *pvcp;
1185
1186     /*
1187      * If parent is a mount point and we are using fakestat, we may need
1188      * to look at the fake vcache entry instead of what the vfs is giving
1189      * us.  The fake entry is the one with the useful DataVersion.
1190      */
1191     pvcp = VTOAFS(inode);
1192     if (pvcp->mvstat == AFS_MVSTAT_MTPT && afs_fakestat_enable) {
1193         struct vrequest treq;
1194         struct afs_fakestat_state fakestate;
1195
1196         if (!credp) {
1197             credp = crref();
1198             free_cred = 1;
1199         }
1200         afs_InitReq(&treq, credp);
1201         afs_InitFakeStat(&fakestate);
1202         afs_TryEvalFakeStat(&pvcp, &fakestate, &treq);
1203         if (free_cred)
1204             crfree(credp);
1205         afs_PutFakeStat(&fakestate);
1206     }
1207     return hgetlo(pvcp->f.m.DataVersion);
1208 }
1209
1210 static inline int
1211 filter_enoent(int code)
1212 {
1213 #ifdef HAVE_LINUX_FATAL_SIGNAL_PENDING
1214     if (code == ENOENT && fatal_signal_pending(current)) {
1215         return EINTR;
1216     }
1217 #endif
1218     return code;
1219 }
1220
1221 #ifndef D_SPLICE_ALIAS_RACE
1222
1223 static inline void dentry_race_lock(void) {}
1224 static inline void dentry_race_unlock(void) {}
1225
1226 #else
1227
1228 # if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,16)
1229 static DEFINE_MUTEX(dentry_race_sem);
1230 # else
1231 static DECLARE_MUTEX(dentry_race_sem);
1232 # endif
1233
1234 static inline void
1235 dentry_race_lock(void)
1236 {
1237     mutex_lock(&dentry_race_sem);
1238 }
1239 static inline void
1240 dentry_race_unlock(void)
1241 {
1242     mutex_unlock(&dentry_race_sem);
1243 }
1244
1245 /* Leave some trace that this code is enabled; otherwise it's pretty hard to
1246  * tell. */
1247 static __attribute__((used)) const char dentry_race_marker[] = "d_splice_alias race workaround enabled";
1248
1249 static int
1250 check_dentry_race(struct dentry *dp)
1251 {
1252     int raced = 0;
1253     if (!dp->d_inode) {
1254         /* In Linux, before commit 4919c5e45a91b5db5a41695fe0357fbdff0d5767,
1255          * d_splice_alias can momentarily hash a dentry before it's fully
1256          * populated. This only happens for a moment, since it's unhashed again
1257          * right after (in d_move), but this can make the dentry be found by
1258          * __d_lookup, and then given to us.
1259          *
1260          * So check if the dentry is unhashed; if it is, then the dentry is not
1261          * valid. We lock dentry_race_lock() to ensure that d_splice_alias is
1262          * no longer running. Locking d_lock is required to check the dentry's
1263          * flags, so lock that, too.
1264          */
1265         dentry_race_lock();
1266         spin_lock(&dp->d_lock);
1267         if (d_unhashed(dp)) {
1268             raced = 1;
1269         }
1270         spin_unlock(&dp->d_lock);
1271         dentry_race_unlock();
1272     }
1273     return raced;
1274 }
1275 #endif /* D_SPLICE_ALIAS_RACE */
1276
1277 /* Validate a dentry. Return 1 if unchanged, 0 if VFS layer should re-evaluate.
1278  * In kernels 2.2.10 and above, we are passed an additional flags var which
1279  * may have either the LOOKUP_FOLLOW OR LOOKUP_DIRECTORY set in which case
1280  * we are advised to follow the entry if it is a link or to make sure that
1281  * it is a directory. But since the kernel itself checks these possibilities
1282  * later on, we shouldn't have to do it until later. Perhaps in the future..
1283  *
1284  * The code here assumes that on entry the global lock is not held
1285  */
1286 static int
1287 #if defined(DOP_REVALIDATE_TAKES_UNSIGNED)
1288 afs_linux_dentry_revalidate(struct dentry *dp, unsigned int flags)
1289 #elif defined(DOP_REVALIDATE_TAKES_NAMEIDATA)
1290 afs_linux_dentry_revalidate(struct dentry *dp, struct nameidata *nd)
1291 #else
1292 afs_linux_dentry_revalidate(struct dentry *dp, int flags)
1293 #endif
1294 {
1295     cred_t *credp = NULL;
1296     struct vcache *vcp, *pvcp, *tvc = NULL;
1297     struct dentry *parent;
1298     int valid;
1299     struct afs_fakestat_state fakestate;
1300     int force_drop = 0;
1301     afs_uint32 parent_dv;
1302
1303 #ifdef LOOKUP_RCU
1304     /* We don't support RCU path walking */
1305 # if defined(DOP_REVALIDATE_TAKES_UNSIGNED)
1306     if (flags & LOOKUP_RCU)
1307 # else
1308     if (nd->flags & LOOKUP_RCU)
1309 # endif
1310        return -ECHILD;
1311 #endif
1312
1313 #ifdef D_SPLICE_ALIAS_RACE
1314     if (check_dentry_race(dp)) {
1315         valid = 0;
1316         return valid;
1317     }
1318 #endif
1319
1320     AFS_GLOCK();
1321     afs_InitFakeStat(&fakestate);
1322
1323     if (dp->d_inode) {
1324         vcp = VTOAFS(dp->d_inode);
1325
1326         if (vcp == afs_globalVp)
1327             goto good_dentry;
1328
1329         if (vcp->mvstat == AFS_MVSTAT_MTPT) {
1330             if (vcp->mvid.target_root && (vcp->f.states & CMValid)) {
1331                 int tryEvalOnly = 0;
1332                 int code = 0;
1333                 struct vrequest *treq = NULL;
1334
1335                 credp = crref();
1336
1337                 code = afs_CreateReq(&treq, credp);
1338                 if (code) {
1339                     goto bad_dentry;
1340                 }
1341                 if ((strcmp(dp->d_name.name, ".directory") == 0)) {
1342                     tryEvalOnly = 1;
1343                 }
1344                 if (tryEvalOnly)
1345                     code = afs_TryEvalFakeStat(&vcp, &fakestate, treq);
1346                 else
1347                     code = afs_EvalFakeStat(&vcp, &fakestate, treq);
1348                 afs_DestroyReq(treq);
1349                 if ((tryEvalOnly && vcp->mvstat == AFS_MVSTAT_MTPT) || code) {
1350                     /* a mount point, not yet replaced by its directory */
1351                     goto bad_dentry;
1352                 }
1353             }
1354         } else if (vcp->mvstat == AFS_MVSTAT_ROOT && *dp->d_name.name != '/') {
1355             osi_Assert(vcp->mvid.parent != NULL);
1356         }
1357
1358         parent = dget_parent(dp);
1359         pvcp = VTOAFS(parent->d_inode);
1360         parent_dv = parent_vcache_dv(parent->d_inode, credp);
1361
1362         /* If the parent's DataVersion has changed or the vnode
1363          * is longer valid, we need to do a full lookup.  VerifyVCache
1364          * isn't enough since the vnode may have been renamed.
1365          */
1366
1367         if (parent_dv > dp->d_time || !(vcp->f.states & CStatd)) {
1368             struct vattr *vattr = NULL;
1369             int code;
1370             int lookup_good;
1371
1372             if (credp == NULL) {
1373                 credp = crref();
1374             }
1375             code = afs_lookup(pvcp, (char *)dp->d_name.name, &tvc, credp);
1376             code = filter_enoent(code);
1377
1378             if (code) {
1379                 /* We couldn't perform the lookup, so we're not okay. */
1380                 lookup_good = 0;
1381
1382             } else if (tvc == vcp) {
1383                 /* We got back the same vcache, so we're good. */
1384                 lookup_good = 1;
1385
1386             } else if (tvc == VTOAFS(dp->d_inode)) {
1387                 /* We got back the same vcache, so we're good. This is
1388                  * different from the above case, because sometimes 'vcp' is
1389                  * not the same as the vcache for dp->d_inode, if 'vcp' was a
1390                  * mtpt and we evaluated it to a root dir. In rare cases,
1391                  * afs_lookup might not evalute the mtpt when we do, or vice
1392                  * versa, so the previous case will not succeed. But this is
1393                  * still 'correct', so make sure not to mark the dentry as
1394                  * invalid; it still points to the same thing! */
1395                 lookup_good = 1;
1396
1397             } else {
1398                 /* We got back a different file, so we're definitely not
1399                  * okay. */
1400                 lookup_good = 0;
1401             }
1402
1403             if (!lookup_good) {
1404                 dput(parent);
1405                 /* Force unhash; the name doesn't point to this file
1406                  * anymore. */
1407                 force_drop = 1;
1408                 if (code && code != ENOENT) {
1409                     /* ...except if we couldn't perform the actual lookup,
1410                      * we don't know if the name points to this file or not. */
1411                     force_drop = 0;
1412                 }
1413                 goto bad_dentry;
1414             }
1415
1416             code = afs_CreateAttr(&vattr);
1417             if (code) {
1418                 dput(parent);
1419                 goto bad_dentry;
1420             }
1421
1422             if (afs_getattr(vcp, vattr, credp)) {
1423                 dput(parent);
1424                 afs_DestroyAttr(vattr);
1425                 goto bad_dentry;
1426             }
1427
1428             vattr2inode(AFSTOV(vcp), vattr);
1429             dp->d_time = parent_dv;
1430
1431             afs_DestroyAttr(vattr);
1432         }
1433
1434         /* should we always update the attributes at this point? */
1435         /* unlikely--the vcache entry hasn't changed */
1436
1437         dput(parent);
1438
1439     } else {
1440
1441         /* 'dp' represents a cached negative lookup. */
1442
1443         parent = dget_parent(dp);
1444         pvcp = VTOAFS(parent->d_inode);
1445         parent_dv = parent_vcache_dv(parent->d_inode, credp);
1446
1447         if (parent_dv > dp->d_time || !(pvcp->f.states & CStatd)
1448             || afs_IsDynroot(pvcp)) {
1449             dput(parent);
1450             goto bad_dentry;
1451         }
1452
1453         dput(parent);
1454     }
1455
1456   good_dentry:
1457     valid = 1;
1458     goto done;
1459
1460   bad_dentry:
1461     valid = 0;
1462 #ifndef D_INVALIDATE_IS_VOID
1463     /* When (v3.18) d_invalidate was converted to void, it also started
1464      * being called automatically from revalidate, and automatically
1465      * handled:
1466      *  - shrink_dcache_parent
1467      *  - automatic detach of submounts
1468      *  - d_drop
1469      * Therefore, after that point, OpenAFS revalidate logic no longer needs
1470      * to do any of those things itself for invalid dentry structs.  We only need
1471      * to tell VFS it's invalid (by returning 0), and VFS will handle the rest.
1472      */
1473     if (have_submounts(dp))
1474         valid = 1;
1475 #endif
1476
1477   done:
1478     /* Clean up */
1479     if (tvc)
1480         afs_PutVCache(tvc);
1481     afs_PutFakeStat(&fakestate);
1482     AFS_GUNLOCK();
1483     if (credp)
1484         crfree(credp);
1485
1486 #ifndef D_INVALIDATE_IS_VOID
1487     if (!valid) {
1488         /*
1489          * If we had a negative lookup for the name we want to forcibly
1490          * unhash the dentry.
1491          * Otherwise use d_invalidate which will not unhash it if still in use.
1492          */
1493         if (force_drop) {
1494             shrink_dcache_parent(dp);
1495             d_drop(dp);
1496         } else
1497             d_invalidate(dp);
1498     }
1499 #endif
1500     return valid;
1501
1502 }
1503
1504 static void
1505 afs_dentry_iput(struct dentry *dp, struct inode *ip)
1506 {
1507     struct vcache *vcp = VTOAFS(ip);
1508     int haveGlock = ISAFS_GLOCK();
1509
1510     if (!haveGlock) {
1511         AFS_GLOCK();
1512     }
1513
1514     if (!AFS_IS_DISCONNECTED || (vcp->f.states & CUnlinked)) {
1515         (void) afs_InactiveVCache(vcp, NULL);
1516     }
1517
1518     if (!haveGlock) {
1519         AFS_GUNLOCK();
1520     }
1521
1522     afs_linux_clear_nfsfs_renamed(dp);
1523
1524     iput(ip);
1525 }
1526
1527 static int
1528 #if defined(DOP_D_DELETE_TAKES_CONST)
1529 afs_dentry_delete(const struct dentry *dp)
1530 #else
1531 afs_dentry_delete(struct dentry *dp)
1532 #endif
1533 {
1534     if (dp->d_inode && (VTOAFS(dp->d_inode)->f.states & CUnlinked))
1535         return 1;               /* bad inode? */
1536
1537     return 0;
1538 }
1539
1540 #ifdef STRUCT_DENTRY_OPERATIONS_HAS_D_AUTOMOUNT
1541 static struct vfsmount *
1542 afs_dentry_automount(afs_linux_path_t *path)
1543 {
1544     struct dentry *target;
1545
1546     /*
1547      * Avoid symlink resolution limits when resolving; we cannot contribute to
1548      * an infinite symlink loop.
1549      *
1550      * On newer kernels the field has moved to the private nameidata structure
1551      * so we can't adjust it here.  This may cause ELOOP when using a path with
1552      * 40 or more directories that are not already in the dentry cache.
1553      */
1554 #if defined(STRUCT_TASK_STRUCT_HAS_TOTAL_LINK_COUNT)
1555     current->total_link_count--;
1556 #endif
1557
1558     target = canonical_dentry(path->dentry->d_inode);
1559
1560     if (target == path->dentry) {
1561         dput(target);
1562         target = NULL;
1563     }
1564
1565     if (target) {
1566         dput(path->dentry);
1567         path->dentry = target;
1568
1569     } else {
1570         spin_lock(&path->dentry->d_lock);
1571         path->dentry->d_flags &= ~DCACHE_NEED_AUTOMOUNT;
1572         spin_unlock(&path->dentry->d_lock);
1573     }
1574
1575     return NULL;
1576 }
1577 #endif /* STRUCT_DENTRY_OPERATIONS_HAS_D_AUTOMOUNT */
1578
1579 struct dentry_operations afs_dentry_operations = {
1580   .d_revalidate =       afs_linux_dentry_revalidate,
1581   .d_delete =           afs_dentry_delete,
1582   .d_iput =             afs_dentry_iput,
1583 #ifdef STRUCT_DENTRY_OPERATIONS_HAS_D_AUTOMOUNT
1584   .d_automount =        afs_dentry_automount,
1585 #endif /* STRUCT_DENTRY_OPERATIONS_HAS_D_AUTOMOUNT */
1586 };
1587
1588 /**********************************************************************
1589  * AFS Linux inode operations
1590  **********************************************************************/
1591
1592 /* afs_linux_create
1593  *
1594  * Merely need to set enough of vattr to get us through the create. Note
1595  * that the higher level code (open_namei) will take care of any tuncation
1596  * explicitly. Exclusive open is also taken care of in open_namei.
1597  *
1598  * name is in kernel space at this point.
1599  */
1600 static int
1601 #if defined(IOP_CREATE_TAKES_BOOL)
1602 afs_linux_create(struct inode *dip, struct dentry *dp, umode_t mode,
1603                  bool excl)
1604 #elif defined(IOP_CREATE_TAKES_UMODE_T)
1605 afs_linux_create(struct inode *dip, struct dentry *dp, umode_t mode,
1606                  struct nameidata *nd)
1607 #elif defined(IOP_CREATE_TAKES_NAMEIDATA)
1608 afs_linux_create(struct inode *dip, struct dentry *dp, int mode,
1609                  struct nameidata *nd)
1610 #else
1611 afs_linux_create(struct inode *dip, struct dentry *dp, int mode)
1612 #endif
1613 {
1614     struct vattr *vattr = NULL;
1615     cred_t *credp = crref();
1616     const char *name = dp->d_name.name;
1617     struct vcache *vcp;
1618     int code;
1619
1620     AFS_GLOCK();
1621
1622     code = afs_CreateAttr(&vattr);
1623     if (code) {
1624         goto out;
1625     }
1626     vattr->va_mode = mode;
1627     vattr->va_type = mode & S_IFMT;
1628
1629     code = afs_create(VTOAFS(dip), (char *)name, vattr, NONEXCL, mode,
1630                       &vcp, credp);
1631
1632     if (!code) {
1633         struct inode *ip = AFSTOV(vcp);
1634
1635         afs_getattr(vcp, vattr, credp);
1636         afs_fill_inode(ip, vattr);
1637         insert_inode_hash(ip);
1638 #if !defined(STRUCT_SUPER_BLOCK_HAS_S_D_OP)
1639         dp->d_op = &afs_dentry_operations;
1640 #endif
1641         dp->d_time = parent_vcache_dv(dip, credp);
1642         d_instantiate(dp, ip);
1643     }
1644
1645     afs_DestroyAttr(vattr);
1646
1647 out:
1648     AFS_GUNLOCK();
1649
1650     crfree(credp);
1651     return afs_convert_code(code);
1652 }
1653
1654 /* afs_linux_lookup */
1655 static struct dentry *
1656 #if defined(IOP_LOOKUP_TAKES_UNSIGNED)
1657 afs_linux_lookup(struct inode *dip, struct dentry *dp,
1658                  unsigned flags)
1659 #elif defined(IOP_LOOKUP_TAKES_NAMEIDATA)
1660 afs_linux_lookup(struct inode *dip, struct dentry *dp,
1661                  struct nameidata *nd)
1662 #else
1663 afs_linux_lookup(struct inode *dip, struct dentry *dp)
1664 #endif
1665 {
1666     cred_t *credp = crref();
1667     struct vcache *vcp = NULL;
1668     const char *comp = dp->d_name.name;
1669     struct inode *ip = NULL;
1670     struct dentry *newdp = NULL;
1671     int code;
1672
1673     AFS_GLOCK();
1674
1675     code = afs_lookup(VTOAFS(dip), (char *)comp, &vcp, credp);
1676     code = filter_enoent(code);
1677     if (code == ENOENT) {
1678         /* It's ok for the file to not be found. That's noted by the caller by
1679          * seeing that the dp->d_inode field is NULL (set by d_splice_alias or
1680          * d_add, below). */
1681         code = 0;
1682         osi_Assert(vcp == NULL);
1683     }
1684     if (code) {
1685         AFS_GUNLOCK();
1686         goto done;
1687     }
1688
1689     if (vcp) {
1690         struct vattr *vattr = NULL;
1691         struct vcache *parent_vc = VTOAFS(dip);
1692
1693         if (parent_vc == vcp) {
1694             /* This is possible if the parent dir is a mountpoint to a volume,
1695              * and the dir entry we looked up is a mountpoint to the same
1696              * volume. Linux cannot cope with this, so return an error instead
1697              * of risking a deadlock or panic. */
1698             afs_PutVCache(vcp);
1699             code = EDEADLK;
1700             AFS_GUNLOCK();
1701             goto done;
1702         }
1703
1704         code = afs_CreateAttr(&vattr);
1705         if (code) {
1706             afs_PutVCache(vcp);
1707             AFS_GUNLOCK();
1708             goto done;
1709         }
1710
1711         ip = AFSTOV(vcp);
1712         afs_getattr(vcp, vattr, credp);
1713         afs_fill_inode(ip, vattr);
1714         if (hlist_unhashed(&ip->i_hash))
1715             insert_inode_hash(ip);
1716
1717         afs_DestroyAttr(vattr);
1718     }
1719 #if !defined(STRUCT_SUPER_BLOCK_HAS_S_D_OP)
1720     dp->d_op = &afs_dentry_operations;
1721 #endif
1722     dp->d_time = parent_vcache_dv(dip, credp);
1723
1724     AFS_GUNLOCK();
1725
1726     if (ip && S_ISDIR(ip->i_mode)) {
1727         d_prune_aliases(ip);
1728
1729 #ifdef STRUCT_DENTRY_OPERATIONS_HAS_D_AUTOMOUNT
1730         /* Only needed if this is a volume root */
1731         if (vcp->mvstat == 2)
1732             ip->i_flags |= S_AUTOMOUNT;
1733 #endif
1734     }
1735     /*
1736      * Take an extra reference so the inode doesn't go away if
1737      * d_splice_alias drops our reference on error.
1738      */
1739     if (ip)
1740 #ifdef HAVE_LINUX_IHOLD
1741         ihold(ip);
1742 #else
1743         igrab(ip);
1744 #endif
1745
1746     dentry_race_lock();
1747     newdp = d_splice_alias(ip, dp);
1748     dentry_race_unlock();
1749
1750  done:
1751     crfree(credp);
1752
1753     if (IS_ERR(newdp)) {
1754         /* d_splice_alias can return an error (EIO) if there is an existing
1755          * connected directory alias for this dentry. Add our dentry manually
1756          * ourselves if this happens. */
1757         d_add(dp, ip);
1758
1759 #if defined(D_SPLICE_ALIAS_LEAK_ON_ERROR)
1760         /* Depending on the kernel version, d_splice_alias may or may not drop
1761          * the inode reference on error. If it didn't, do it here. */
1762         iput(ip);
1763 #endif
1764         return NULL;
1765     }
1766
1767     if (code) {
1768         if (ip)
1769             iput(ip);
1770         return ERR_PTR(afs_convert_code(code));
1771     }
1772
1773     iput(ip);
1774     return newdp;
1775 }
1776
1777 static int
1778 afs_linux_link(struct dentry *olddp, struct inode *dip, struct dentry *newdp)
1779 {
1780     int code;
1781     cred_t *credp = crref();
1782     const char *name = newdp->d_name.name;
1783     struct inode *oldip = olddp->d_inode;
1784
1785     /* If afs_link returned the vnode, we could instantiate the
1786      * dentry. Since it's not, we drop this one and do a new lookup.
1787      */
1788     d_drop(newdp);
1789
1790     AFS_GLOCK();
1791     code = afs_link(VTOAFS(oldip), VTOAFS(dip), (char *)name, credp);
1792
1793     AFS_GUNLOCK();
1794     crfree(credp);
1795     return afs_convert_code(code);
1796 }
1797
1798 /* We have to have a Linux specific sillyrename function, because we
1799  * also have to keep the dcache up to date when we're doing a silly
1800  * rename - so we don't want the generic vnodeops doing this behind our
1801  * back.
1802  */
1803
1804 static int
1805 afs_linux_sillyrename(struct inode *dir, struct dentry *dentry,
1806                       cred_t *credp)
1807 {
1808     struct vcache *tvc = VTOAFS(dentry->d_inode);
1809     struct dentry *__dp = NULL;
1810     char *__name = NULL;
1811     int code;
1812
1813     if (afs_linux_nfsfs_renamed(dentry))
1814         return EBUSY;
1815
1816     do {
1817         dput(__dp);
1818
1819         AFS_GLOCK();
1820         if (__name)
1821             osi_FreeSmallSpace(__name);
1822         __name = afs_newname();
1823         AFS_GUNLOCK();
1824
1825         __dp = lookup_one_len(__name, dentry->d_parent, strlen(__name));
1826
1827         if (IS_ERR(__dp)) {
1828             osi_FreeSmallSpace(__name);
1829             return EBUSY;
1830         }
1831     } while (__dp->d_inode != NULL);
1832
1833     AFS_GLOCK();
1834     code = afs_rename(VTOAFS(dir), (char *)dentry->d_name.name,
1835                       VTOAFS(dir), (char *)__dp->d_name.name,
1836                       credp);
1837     if (!code) {
1838         tvc->mvid.silly_name = __name;
1839         crhold(credp);
1840         if (tvc->uncred) {
1841             crfree(tvc->uncred);
1842         }
1843         tvc->uncred = credp;
1844         tvc->f.states |= CUnlinked;
1845         afs_linux_set_nfsfs_renamed(dentry);
1846
1847         __dp->d_time = 0;               /* force to revalidate */
1848         d_move(dentry, __dp);
1849     } else {
1850         osi_FreeSmallSpace(__name);
1851     }
1852     AFS_GUNLOCK();
1853
1854     dput(__dp);
1855
1856     return code;
1857 }
1858
1859
1860 static int
1861 afs_linux_unlink(struct inode *dip, struct dentry *dp)
1862 {
1863     int code = EBUSY;
1864     cred_t *credp = crref();
1865     const char *name = dp->d_name.name;
1866     struct vcache *tvc = VTOAFS(dp->d_inode);
1867
1868     if (VREFCOUNT(tvc) > 1 && tvc->opens > 0
1869                                 && !(tvc->f.states & CUnlinked)) {
1870
1871         code = afs_linux_sillyrename(dip, dp, credp);
1872     } else {
1873         AFS_GLOCK();
1874         code = afs_remove(VTOAFS(dip), (char *)name, credp);
1875         AFS_GUNLOCK();
1876         if (!code)
1877             d_drop(dp);
1878     }
1879
1880     crfree(credp);
1881     return afs_convert_code(code);
1882 }
1883
1884
1885 static int
1886 afs_linux_symlink(struct inode *dip, struct dentry *dp, const char *target)
1887 {
1888     int code;
1889     cred_t *credp = crref();
1890     struct vattr *vattr = NULL;
1891     const char *name = dp->d_name.name;
1892
1893     /* If afs_symlink returned the vnode, we could instantiate the
1894      * dentry. Since it's not, we drop this one and do a new lookup.
1895      */
1896     d_drop(dp);
1897
1898     AFS_GLOCK();
1899     code = afs_CreateAttr(&vattr);
1900     if (code) {
1901         goto out;
1902     }
1903
1904     code = afs_symlink(VTOAFS(dip), (char *)name, vattr, (char *)target, NULL,
1905                         credp);
1906     afs_DestroyAttr(vattr);
1907
1908 out:
1909     AFS_GUNLOCK();
1910     crfree(credp);
1911     return afs_convert_code(code);
1912 }
1913
1914 static int
1915 #if defined(IOP_MKDIR_TAKES_UMODE_T)
1916 afs_linux_mkdir(struct inode *dip, struct dentry *dp, umode_t mode)
1917 #else
1918 afs_linux_mkdir(struct inode *dip, struct dentry *dp, int mode)
1919 #endif
1920 {
1921     int code;
1922     cred_t *credp = crref();
1923     struct vcache *tvcp = NULL;
1924     struct vattr *vattr = NULL;
1925     const char *name = dp->d_name.name;
1926
1927     AFS_GLOCK();
1928     code = afs_CreateAttr(&vattr);
1929     if (code) {
1930         goto out;
1931     }
1932
1933     vattr->va_mask = ATTR_MODE;
1934     vattr->va_mode = mode;
1935
1936     code = afs_mkdir(VTOAFS(dip), (char *)name, vattr, &tvcp, credp);
1937
1938     if (tvcp) {
1939         struct inode *ip = AFSTOV(tvcp);
1940
1941         afs_getattr(tvcp, vattr, credp);
1942         afs_fill_inode(ip, vattr);
1943
1944 #if !defined(STRUCT_SUPER_BLOCK_HAS_S_D_OP)
1945         dp->d_op = &afs_dentry_operations;
1946 #endif
1947         dp->d_time = parent_vcache_dv(dip, credp);
1948         d_instantiate(dp, ip);
1949     }
1950     afs_DestroyAttr(vattr);
1951
1952 out:
1953     AFS_GUNLOCK();
1954
1955     crfree(credp);
1956     return afs_convert_code(code);
1957 }
1958
1959 static int
1960 afs_linux_rmdir(struct inode *dip, struct dentry *dp)
1961 {
1962     int code;
1963     cred_t *credp = crref();
1964     const char *name = dp->d_name.name;
1965
1966     /* locking kernel conflicts with glock? */
1967
1968     AFS_GLOCK();
1969     code = afs_rmdir(VTOAFS(dip), (char *)name, credp);
1970     AFS_GUNLOCK();
1971
1972     /* Linux likes to see ENOTEMPTY returned from an rmdir() syscall
1973      * that failed because a directory is not empty. So, we map
1974      * EEXIST to ENOTEMPTY on linux.
1975      */
1976     if (code == EEXIST) {
1977         code = ENOTEMPTY;
1978     }
1979
1980     if (!code) {
1981         d_drop(dp);
1982     }
1983
1984     crfree(credp);
1985     return afs_convert_code(code);
1986 }
1987
1988
1989 static int
1990 afs_linux_rename(struct inode *oldip, struct dentry *olddp,
1991                  struct inode *newip, struct dentry *newdp
1992 #ifdef HAVE_LINUX_INODE_OPERATIONS_RENAME_TAKES_FLAGS
1993                  , unsigned int flags
1994 #endif
1995                 )
1996 {
1997     int code;
1998     cred_t *credp = crref();
1999     const char *oldname = olddp->d_name.name;
2000     const char *newname = newdp->d_name.name;
2001     struct dentry *rehash = NULL;
2002
2003 #ifdef HAVE_LINUX_INODE_OPERATIONS_RENAME_TAKES_FLAGS
2004     if (flags)
2005         return -EINVAL;         /* no support for new flags yet */
2006 #endif
2007
2008     /* Prevent any new references during rename operation. */
2009
2010     if (!d_unhashed(newdp)) {
2011         d_drop(newdp);
2012         rehash = newdp;
2013     }
2014
2015     afs_maybe_shrink_dcache(olddp);
2016
2017     AFS_GLOCK();
2018     code = afs_rename(VTOAFS(oldip), (char *)oldname, VTOAFS(newip), (char *)newname, credp);
2019     AFS_GUNLOCK();
2020
2021     if (!code)
2022         olddp->d_time = 0;      /* force to revalidate */
2023
2024     if (rehash)
2025         d_rehash(rehash);
2026
2027     crfree(credp);
2028     return afs_convert_code(code);
2029 }
2030
2031
2032 /* afs_linux_ireadlink
2033  * Internal readlink which can return link contents to user or kernel space.
2034  * Note that the buffer is NOT supposed to be null-terminated.
2035  */
2036 static int
2037 afs_linux_ireadlink(struct inode *ip, char *target, int maxlen, uio_seg_t seg)
2038 {
2039     int code;
2040     cred_t *credp = crref();
2041     struct uio tuio;
2042     struct iovec iov;
2043
2044     memset(&tuio, 0, sizeof(tuio));
2045     memset(&iov, 0, sizeof(iov));
2046
2047     setup_uio(&tuio, &iov, target, (afs_offs_t) 0, maxlen, UIO_READ, seg);
2048     code = afs_readlink(VTOAFS(ip), &tuio, credp);
2049     crfree(credp);
2050
2051     if (!code)
2052         return maxlen - tuio.uio_resid;
2053     else
2054         return afs_convert_code(code);
2055 }
2056
2057 #if !defined(USABLE_KERNEL_PAGE_SYMLINK_CACHE)
2058 /* afs_linux_readlink
2059  * Fill target (which is in user space) with contents of symlink.
2060  */
2061 static int
2062 afs_linux_readlink(struct dentry *dp, char *target, int maxlen)
2063 {
2064     int code;
2065     struct inode *ip = dp->d_inode;
2066
2067     AFS_GLOCK();
2068     code = afs_linux_ireadlink(ip, target, maxlen, AFS_UIOUSER);
2069     AFS_GUNLOCK();
2070     return code;
2071 }
2072
2073
2074 /* afs_linux_follow_link
2075  * a file system dependent link following routine.
2076  */
2077 #if defined(HAVE_LINUX_INODE_OPERATIONS_FOLLOW_LINK_NO_NAMEIDATA)
2078 static const char *afs_linux_follow_link(struct dentry *dentry, void **link_data)
2079 #else
2080 static int afs_linux_follow_link(struct dentry *dentry, struct nameidata *nd)
2081 #endif
2082 {
2083     int code;
2084     char *name;
2085
2086     name = kmalloc(PATH_MAX, GFP_NOFS);
2087     if (!name) {
2088 #if defined(HAVE_LINUX_INODE_OPERATIONS_FOLLOW_LINK_NO_NAMEIDATA)
2089         return ERR_PTR(-EIO);
2090 #else
2091         return -EIO;
2092 #endif
2093     }
2094
2095     AFS_GLOCK();
2096     code = afs_linux_ireadlink(dentry->d_inode, name, PATH_MAX - 1, AFS_UIOSYS);
2097     AFS_GUNLOCK();
2098
2099     if (code < 0) {
2100 #if defined(HAVE_LINUX_INODE_OPERATIONS_FOLLOW_LINK_NO_NAMEIDATA)
2101         return ERR_PTR(code);
2102 #else
2103         return code;
2104 #endif
2105     }
2106
2107     name[code] = '\0';
2108 #if defined(HAVE_LINUX_INODE_OPERATIONS_FOLLOW_LINK_NO_NAMEIDATA)
2109     return *link_data = name;
2110 #else
2111     nd_set_link(nd, name);
2112     return 0;
2113 #endif
2114 }
2115
2116 #if defined(HAVE_LINUX_INODE_OPERATIONS_PUT_LINK_NO_NAMEIDATA)
2117 static void
2118 afs_linux_put_link(struct inode *inode, void *link_data)
2119 {
2120     char *name = link_data;
2121
2122     if (name && !IS_ERR(name))
2123         kfree(name);
2124 }
2125 #else
2126 static void
2127 afs_linux_put_link(struct dentry *dentry, struct nameidata *nd)
2128 {
2129     char *name = nd_get_link(nd);
2130
2131     if (name && !IS_ERR(name))
2132         kfree(name);
2133 }
2134 #endif /* HAVE_LINUX_INODE_OPERATIONS_PUT_LINK_NO_NAMEIDATA */
2135
2136 #endif /* USABLE_KERNEL_PAGE_SYMLINK_CACHE */
2137
2138 /* Populate a page by filling it from the cache file pointed at by cachefp
2139  * (which contains indicated chunk)
2140  * If task is NULL, the page copy occurs syncronously, and the routine
2141  * returns with page still locked. If task is non-NULL, then page copies
2142  * may occur in the background, and the page will be unlocked when it is
2143  * ready for use. Note that if task is non-NULL and we encounter an error
2144  * before we start the background copy, we MUST unlock 'page' before we return.
2145  */
2146 static int
2147 afs_linux_read_cache(struct file *cachefp, struct page *page,
2148                      int chunk, struct afs_lru_pages *alrupages,
2149                      struct afs_pagecopy_task *task) {
2150     loff_t offset = page_offset(page);
2151     struct inode *cacheinode = cachefp->f_dentry->d_inode;
2152     struct page *newpage, *cachepage;
2153     struct address_space *cachemapping;
2154     int pageindex;
2155     int code = 0;
2156
2157     cachemapping = cacheinode->i_mapping;
2158     newpage = NULL;
2159     cachepage = NULL;
2160
2161     /* If we're trying to read a page that's past the end of the disk
2162      * cache file, then just return a zeroed page */
2163     if (AFS_CHUNKOFFSET(offset) >= i_size_read(cacheinode)) {
2164         zero_user_segment(page, 0, PAGE_SIZE);
2165         SetPageUptodate(page);
2166         if (task)
2167             unlock_page(page);
2168         return 0;
2169     }
2170
2171     /* From our offset, we now need to work out which page in the disk
2172      * file it corresponds to. This will be fun ... */
2173     pageindex = (offset - AFS_CHUNKTOBASE(chunk)) >> PAGE_SHIFT;
2174
2175     while (cachepage == NULL) {
2176         cachepage = find_get_page(cachemapping, pageindex);
2177         if (!cachepage) {
2178             if (!newpage)
2179                 newpage = page_cache_alloc(cachemapping);
2180             if (!newpage) {
2181                 code = -ENOMEM;
2182                 goto out;
2183             }
2184
2185             code = add_to_page_cache(newpage, cachemapping,
2186                                      pageindex, GFP_KERNEL);
2187             if (code == 0) {
2188                 cachepage = newpage;
2189                 newpage = NULL;
2190                 afs_lru_cache_add(alrupages, cachepage);
2191             } else {
2192                 put_page(newpage);
2193                 newpage = NULL;
2194                 if (code != -EEXIST)
2195                     goto out;
2196             }
2197         } else {
2198             lock_page(cachepage);
2199         }
2200     }
2201
2202     if (!PageUptodate(cachepage)) {
2203         ClearPageError(cachepage);
2204         /* Note that ->readpage always handles unlocking the given page, even
2205          * when an error is returned. */
2206         code = cachemapping->a_ops->readpage(NULL, cachepage);
2207         if (!code && !task) {
2208             wait_on_page_locked(cachepage);
2209         }
2210     } else {
2211         unlock_page(cachepage);
2212     }
2213
2214     if (!code) {
2215         if (PageUptodate(cachepage)) {
2216             copy_highpage(page, cachepage);
2217             flush_dcache_page(page);
2218             SetPageUptodate(page);
2219
2220             if (task)
2221                 unlock_page(page);
2222         } else if (task) {
2223             afs_pagecopy_queue_page(task, cachepage, page);
2224         } else {
2225             code = -EIO;
2226         }
2227     }
2228
2229  out:
2230     if (code && task) {
2231         unlock_page(page);
2232     }
2233
2234     if (cachepage)
2235         put_page(cachepage);
2236
2237     return code;
2238 }
2239
2240 static int inline
2241 afs_linux_readpage_fastpath(struct file *fp, struct page *pp, int *codep)
2242 {
2243     loff_t offset = page_offset(pp);
2244     struct inode *ip = FILE_INODE(fp);
2245     struct vcache *avc = VTOAFS(ip);
2246     struct dcache *tdc;
2247     struct file *cacheFp = NULL;
2248     int code;
2249     int dcLocked = 0;
2250     struct afs_lru_pages lrupages;
2251
2252     /* Not a UFS cache, don't do anything */
2253     if (cacheDiskType != AFS_FCACHE_TYPE_UFS)
2254         return 0;
2255
2256     /* No readpage (ex: tmpfs) , skip */
2257     if (cachefs_noreadpage)
2258         return 0;
2259
2260     /* Can't do anything if the vcache isn't statd , or if the read
2261      * crosses a chunk boundary.
2262      */
2263     if (!(avc->f.states & CStatd) ||
2264         AFS_CHUNK(offset) != AFS_CHUNK(offset + PAGE_SIZE)) {
2265         return 0;
2266     }
2267
2268     ObtainWriteLock(&avc->lock, 911);
2269
2270     /* XXX - See if hinting actually makes things faster !!! */
2271
2272     /* See if we have a suitable entry already cached */
2273     tdc = avc->dchint;
2274
2275     if (tdc) {
2276         /* We need to lock xdcache, then dcache, to handle situations where
2277          * the hint is on the free list. However, we can't safely do this
2278          * according to the locking hierarchy. So, use a non blocking lock.
2279          */
2280         ObtainReadLock(&afs_xdcache);
2281         dcLocked = ( 0 == NBObtainReadLock(&tdc->lock));
2282
2283         if (dcLocked && (tdc->index != NULLIDX)
2284             && !FidCmp(&tdc->f.fid, &avc->f.fid)
2285             && tdc->f.chunk == AFS_CHUNK(offset)
2286             && !(afs_indexFlags[tdc->index] & (IFFree | IFDiscarded))) {
2287             /* Bonus - the hint was correct */
2288             afs_RefDCache(tdc);
2289         } else {
2290             /* Only destroy the hint if its actually invalid, not if there's
2291              * just been a locking failure */
2292             if (dcLocked) {
2293                 ReleaseReadLock(&tdc->lock);
2294                 avc->dchint = NULL;
2295             }
2296
2297             tdc = NULL;
2298             dcLocked = 0;
2299         }
2300         ReleaseReadLock(&afs_xdcache);
2301     }
2302
2303     /* No hint, or hint is no longer valid - see if we can get something
2304      * directly from the dcache
2305      */
2306     if (!tdc)
2307         tdc = afs_FindDCache(avc, offset);
2308
2309     if (!tdc) {
2310         ReleaseWriteLock(&avc->lock);
2311         return 0;
2312     }
2313
2314     if (!dcLocked)
2315         ObtainReadLock(&tdc->lock);
2316
2317     /* Is the dcache we've been given currently up to date */
2318     if (!afs_IsDCacheFresh(tdc, avc) ||
2319         (tdc->dflags & DFFetching))
2320         goto out;
2321
2322     /* Update our hint for future abuse */
2323     avc->dchint = tdc;
2324
2325     /* Okay, so we've now got a cache file that is up to date */
2326
2327     /* XXX - I suspect we should be locking the inodes before we use them! */
2328     AFS_GUNLOCK();
2329     cacheFp = afs_linux_raw_open(&tdc->f.inode);
2330     osi_Assert(cacheFp);
2331     if (!cacheFp->f_dentry->d_inode->i_mapping->a_ops->readpage) {
2332         cachefs_noreadpage = 1;
2333         AFS_GLOCK();
2334         goto out;
2335     }
2336
2337     afs_lru_cache_init(&lrupages);
2338
2339     code = afs_linux_read_cache(cacheFp, pp, tdc->f.chunk, &lrupages, NULL);
2340
2341     afs_lru_cache_finalize(&lrupages);
2342
2343     filp_close(cacheFp, NULL);
2344     AFS_GLOCK();
2345
2346     ReleaseReadLock(&tdc->lock);
2347     ReleaseWriteLock(&avc->lock);
2348     afs_PutDCache(tdc);
2349
2350     *codep = code;
2351     return 1;
2352
2353 out:
2354     ReleaseWriteLock(&avc->lock);
2355     ReleaseReadLock(&tdc->lock);
2356     afs_PutDCache(tdc);
2357     return 0;
2358 }
2359
2360 /* afs_linux_readpage
2361  *
2362  * This function is split into two, because prepare_write/begin_write
2363  * require a readpage call which doesn't unlock the resulting page upon
2364  * success.
2365  */
2366 static int
2367 afs_linux_fillpage(struct file *fp, struct page *pp)
2368 {
2369     afs_int32 code;
2370     char *address;
2371     struct uio *auio;
2372     struct iovec *iovecp;
2373     struct inode *ip = FILE_INODE(fp);
2374     afs_int32 cnt = page_count(pp);
2375     struct vcache *avc = VTOAFS(ip);
2376     afs_offs_t offset = page_offset(pp);
2377     cred_t *credp;
2378
2379     AFS_GLOCK();
2380     if (afs_linux_readpage_fastpath(fp, pp, &code)) {
2381         AFS_GUNLOCK();
2382         return code;
2383     }
2384     AFS_GUNLOCK();
2385
2386     credp = crref();
2387     address = kmap(pp);
2388     ClearPageError(pp);
2389
2390     auio = kmalloc(sizeof(struct uio), GFP_NOFS);
2391     iovecp = kmalloc(sizeof(struct iovec), GFP_NOFS);
2392
2393     setup_uio(auio, iovecp, (char *)address, offset, PAGE_SIZE, UIO_READ,
2394               AFS_UIOSYS);
2395
2396     AFS_GLOCK();
2397     AFS_DISCON_LOCK();
2398     afs_Trace4(afs_iclSetp, CM_TRACE_READPAGE, ICL_TYPE_POINTER, ip,
2399                ICL_TYPE_POINTER, pp, ICL_TYPE_INT32, cnt, ICL_TYPE_INT32,
2400                99999);  /* not a possible code value */
2401
2402     code = afs_rdwr(avc, auio, UIO_READ, 0, credp);
2403
2404     afs_Trace4(afs_iclSetp, CM_TRACE_READPAGE, ICL_TYPE_POINTER, ip,
2405                ICL_TYPE_POINTER, pp, ICL_TYPE_INT32, cnt, ICL_TYPE_INT32,
2406                code);
2407     AFS_DISCON_UNLOCK();
2408     AFS_GUNLOCK();
2409     if (!code) {
2410         /* XXX valid for no-cache also?  Check last bits of files... :)
2411          * Cognate code goes in afs_NoCacheFetchProc.  */
2412         if (auio->uio_resid)    /* zero remainder of page */
2413              memset((void *)(address + (PAGE_SIZE - auio->uio_resid)), 0,
2414                     auio->uio_resid);
2415
2416         flush_dcache_page(pp);
2417         SetPageUptodate(pp);
2418     } /* !code */
2419
2420     kunmap(pp);
2421
2422     kfree(auio);
2423     kfree(iovecp);
2424
2425     crfree(credp);
2426     return afs_convert_code(code);
2427 }
2428
2429 static int
2430 afs_linux_prefetch(struct file *fp, struct page *pp)
2431 {
2432     int code = 0;
2433     struct vcache *avc = VTOAFS(FILE_INODE(fp));
2434     afs_offs_t offset = page_offset(pp);
2435
2436     if (AFS_CHUNKOFFSET(offset) == 0) {
2437         struct dcache *tdc;
2438         struct vrequest *treq = NULL;
2439         cred_t *credp;
2440
2441         credp = crref();
2442         AFS_GLOCK();
2443         code = afs_CreateReq(&treq, credp);
2444         if (!code && !NBObtainWriteLock(&avc->lock, 534)) {
2445             tdc = afs_FindDCache(avc, offset);
2446             if (tdc) {
2447                 if (!(tdc->mflags & DFNextStarted))
2448                     afs_PrefetchChunk(avc, tdc, credp, treq);
2449                 afs_PutDCache(tdc);
2450             }
2451             ReleaseWriteLock(&avc->lock);
2452         }
2453         afs_DestroyReq(treq);
2454         AFS_GUNLOCK();
2455         crfree(credp);
2456     }
2457     return afs_convert_code(code);
2458
2459 }
2460
2461 static int
2462 afs_linux_bypass_readpages(struct file *fp, struct address_space *mapping,
2463                            struct list_head *page_list, unsigned num_pages)
2464 {
2465     afs_int32 page_ix;
2466     struct uio *auio;
2467     afs_offs_t offset;
2468     struct iovec* iovecp;
2469     struct nocache_read_request *ancr;
2470     struct page *pp;
2471     struct afs_lru_pages lrupages;
2472     afs_int32 code = 0;
2473
2474     cred_t *credp;
2475     struct inode *ip = FILE_INODE(fp);
2476     struct vcache *avc = VTOAFS(ip);
2477     afs_int32 base_index = 0;
2478     afs_int32 page_count = 0;
2479     afs_int32 isize;
2480
2481     /* background thread must free: iovecp, auio, ancr */
2482     iovecp = osi_Alloc(num_pages * sizeof(struct iovec));
2483
2484     auio = osi_Alloc(sizeof(struct uio));
2485     auio->uio_iov = iovecp;
2486     auio->uio_iovcnt = num_pages;
2487     auio->uio_flag = UIO_READ;
2488     auio->uio_seg = AFS_UIOSYS;
2489     auio->uio_resid = num_pages * PAGE_SIZE;
2490
2491     ancr = osi_Alloc(sizeof(struct nocache_read_request));
2492     ancr->auio = auio;
2493     ancr->offset = auio->uio_offset;
2494     ancr->length = auio->uio_resid;
2495
2496     afs_lru_cache_init(&lrupages);
2497
2498     for(page_ix = 0; page_ix < num_pages; ++page_ix) {
2499
2500         if(list_empty(page_list))
2501             break;
2502
2503         pp = list_entry(page_list->prev, struct page, lru);
2504         /* If we allocate a page and don't remove it from page_list,
2505          * the page cache gets upset. */
2506         list_del(&pp->lru);
2507         isize = (i_size_read(fp->f_mapping->host) - 1) >> PAGE_SHIFT;
2508         if(pp->index > isize) {
2509             if(PageLocked(pp))
2510                 unlock_page(pp);
2511             continue;
2512         }
2513
2514         if(page_ix == 0) {
2515             offset = page_offset(pp);
2516             ancr->offset = auio->uio_offset = offset;
2517             base_index = pp->index;
2518         }
2519         iovecp[page_ix].iov_len = PAGE_SIZE;
2520         code = add_to_page_cache(pp, mapping, pp->index, GFP_KERNEL);
2521         if(base_index != pp->index) {
2522             if(PageLocked(pp))
2523                  unlock_page(pp);
2524             put_page(pp);
2525             iovecp[page_ix].iov_base = (void *) 0;
2526             base_index++;
2527             ancr->length -= PAGE_SIZE;
2528             continue;
2529         }
2530         base_index++;
2531         if(code) {
2532             if(PageLocked(pp))
2533                 unlock_page(pp);
2534             put_page(pp);
2535             iovecp[page_ix].iov_base = (void *) 0;
2536         } else {
2537             page_count++;
2538             if(!PageLocked(pp)) {
2539                 lock_page(pp);
2540             }
2541
2542             /* save the page for background map */
2543             iovecp[page_ix].iov_base = (void*) pp;
2544
2545             /* and put it on the LRU cache */
2546             afs_lru_cache_add(&lrupages, pp);
2547         }
2548     }
2549
2550     /* If there were useful pages in the page list, make sure all pages
2551      * are in the LRU cache, then schedule the read */
2552     if(page_count) {
2553         afs_lru_cache_finalize(&lrupages);
2554         credp = crref();
2555         code = afs_ReadNoCache(avc, ancr, credp);
2556         crfree(credp);
2557     } else {
2558         /* If there is nothing for the background thread to handle,
2559          * it won't be freeing the things that we never gave it */
2560         osi_Free(iovecp, num_pages * sizeof(struct iovec));
2561         osi_Free(auio, sizeof(struct uio));
2562         osi_Free(ancr, sizeof(struct nocache_read_request));
2563     }
2564     /* we do not flush, release, or unmap pages--that will be
2565      * done for us by the background thread as each page comes in
2566      * from the fileserver */
2567     return afs_convert_code(code);
2568 }
2569
2570
2571 static int
2572 afs_linux_bypass_readpage(struct file *fp, struct page *pp)
2573 {
2574     cred_t *credp = NULL;
2575     struct uio *auio;
2576     struct iovec *iovecp;
2577     struct nocache_read_request *ancr;
2578     int code;
2579
2580     /*
2581      * Special case: if page is at or past end of file, just zero it and set
2582      * it as up to date.
2583      */
2584     if (page_offset(pp) >=  i_size_read(fp->f_mapping->host)) {
2585         zero_user_segment(pp, 0, PAGE_SIZE);
2586         SetPageUptodate(pp);
2587         unlock_page(pp);
2588         return 0;
2589     }
2590
2591     ClearPageError(pp);
2592
2593     /* receiver frees */
2594     auio = osi_Alloc(sizeof(struct uio));
2595     iovecp = osi_Alloc(sizeof(struct iovec));
2596
2597     /* address can be NULL, because we overwrite it with 'pp', below */
2598     setup_uio(auio, iovecp, NULL, page_offset(pp),
2599               PAGE_SIZE, UIO_READ, AFS_UIOSYS);
2600
2601     /* save the page for background map */
2602     get_page(pp); /* see above */
2603     auio->uio_iov->iov_base = (void*) pp;
2604     /* the background thread will free this */
2605     ancr = osi_Alloc(sizeof(struct nocache_read_request));
2606     ancr->auio = auio;
2607     ancr->offset = page_offset(pp);
2608     ancr->length = PAGE_SIZE;
2609
2610     credp = crref();
2611     code = afs_ReadNoCache(VTOAFS(FILE_INODE(fp)), ancr, credp);
2612     crfree(credp);
2613
2614     return afs_convert_code(code);
2615 }
2616
2617 static inline int
2618 afs_linux_can_bypass(struct inode *ip) {
2619
2620     switch(cache_bypass_strategy) {
2621         case NEVER_BYPASS_CACHE:
2622             return 0;
2623         case ALWAYS_BYPASS_CACHE:
2624             return 1;
2625         case LARGE_FILES_BYPASS_CACHE:
2626             if (i_size_read(ip) > cache_bypass_threshold)
2627                 return 1;
2628             /* fall through */
2629         default:
2630             return 0;
2631      }
2632 }
2633
2634 /* Check if a file is permitted to bypass the cache by policy, and modify
2635  * the cache bypass state recorded for that file */
2636
2637 static inline int
2638 afs_linux_bypass_check(struct inode *ip) {
2639     cred_t* credp;
2640
2641     int bypass = afs_linux_can_bypass(ip);
2642
2643     credp = crref();
2644     trydo_cache_transition(VTOAFS(ip), credp, bypass);
2645     crfree(credp);
2646
2647     return bypass;
2648 }
2649
2650
2651 static int
2652 afs_linux_readpage(struct file *fp, struct page *pp)
2653 {
2654     int code;
2655
2656     if (afs_linux_bypass_check(FILE_INODE(fp))) {
2657         code = afs_linux_bypass_readpage(fp, pp);
2658     } else {
2659         code = afs_linux_fillpage(fp, pp);
2660         if (!code)
2661             code = afs_linux_prefetch(fp, pp);
2662         unlock_page(pp);
2663     }
2664
2665     return code;
2666 }
2667
2668 /* Readpages reads a number of pages for a particular file. We use
2669  * this to optimise the reading, by limiting the number of times upon which
2670  * we have to lookup, lock and open vcaches and dcaches
2671  */
2672
2673 static int
2674 afs_linux_readpages(struct file *fp, struct address_space *mapping,
2675                     struct list_head *page_list, unsigned int num_pages)
2676 {
2677     struct inode *inode = mapping->host;
2678     struct vcache *avc = VTOAFS(inode);
2679     struct dcache *tdc;
2680     struct file *cacheFp = NULL;
2681     int code;
2682     unsigned int page_idx;
2683     loff_t offset;
2684     struct afs_lru_pages lrupages;
2685     struct afs_pagecopy_task *task;
2686
2687     if (afs_linux_bypass_check(inode))
2688         return afs_linux_bypass_readpages(fp, mapping, page_list, num_pages);
2689
2690     if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
2691         return 0;
2692
2693     /* No readpage (ex: tmpfs) , skip */
2694     if (cachefs_noreadpage)
2695         return 0;
2696
2697     AFS_GLOCK();
2698     if ((code = afs_linux_VerifyVCache(avc, NULL))) {
2699         AFS_GUNLOCK();
2700         return code;
2701     }
2702
2703     ObtainWriteLock(&avc->lock, 912);
2704     AFS_GUNLOCK();
2705
2706     task = afs_pagecopy_init_task();
2707
2708     tdc = NULL;
2709
2710     afs_lru_cache_init(&lrupages);
2711
2712     for (page_idx = 0; page_idx < num_pages; page_idx++) {
2713         struct page *page = list_entry(page_list->prev, struct page, lru);
2714         list_del(&page->lru);
2715         offset = page_offset(page);
2716
2717         if (tdc && tdc->f.chunk != AFS_CHUNK(offset)) {
2718             AFS_GLOCK();
2719             ReleaseReadLock(&tdc->lock);
2720             afs_PutDCache(tdc);
2721             AFS_GUNLOCK();
2722             tdc = NULL;
2723             if (cacheFp)
2724                 filp_close(cacheFp, NULL);
2725         }
2726
2727         if (!tdc) {
2728             AFS_GLOCK();
2729             if ((tdc = afs_FindDCache(avc, offset))) {
2730                 ObtainReadLock(&tdc->lock);
2731                 if (!afs_IsDCacheFresh(tdc, avc) ||
2732                     (tdc->dflags & DFFetching)) {
2733                     ReleaseReadLock(&tdc->lock);
2734                     afs_PutDCache(tdc);
2735                     tdc = NULL;
2736                 }
2737             }
2738             AFS_GUNLOCK();
2739             if (tdc) {
2740                 cacheFp = afs_linux_raw_open(&tdc->f.inode);
2741                 osi_Assert(cacheFp);
2742                 if (!cacheFp->f_dentry->d_inode->i_mapping->a_ops->readpage) {
2743                     cachefs_noreadpage = 1;
2744                     goto out;
2745                 }
2746             }
2747         }
2748
2749         if (tdc && !add_to_page_cache(page, mapping, page->index,
2750                                       GFP_KERNEL)) {
2751             afs_lru_cache_add(&lrupages, page);
2752
2753             /* Note that add_to_page_cache() locked 'page'.
2754              * afs_linux_read_cache() is guaranteed to handle unlocking it. */
2755             afs_linux_read_cache(cacheFp, page, tdc->f.chunk, &lrupages, task);
2756         }
2757         put_page(page);
2758     }
2759     afs_lru_cache_finalize(&lrupages);
2760
2761 out:
2762     if (tdc)
2763         filp_close(cacheFp, NULL);
2764
2765     afs_pagecopy_put_task(task);
2766
2767     AFS_GLOCK();
2768     if (tdc) {
2769         ReleaseReadLock(&tdc->lock);
2770         afs_PutDCache(tdc);
2771     }
2772
2773     ReleaseWriteLock(&avc->lock);
2774     AFS_GUNLOCK();
2775     return 0;
2776 }
2777
2778 /* Prepare an AFS vcache for writeback. Should be called with the vcache
2779  * locked */
2780 static inline int
2781 afs_linux_prepare_writeback(struct vcache *avc) {
2782     pid_t pid;
2783     struct pagewriter *pw;
2784
2785     pid = MyPidxx2Pid(MyPidxx);
2786     /* Prevent recursion into the writeback code */
2787     spin_lock(&avc->pagewriter_lock);
2788     list_for_each_entry(pw, &avc->pagewriters, link) {
2789         if (pw->writer == pid) {
2790             spin_unlock(&avc->pagewriter_lock);
2791             return AOP_WRITEPAGE_ACTIVATE;
2792         }
2793     }
2794     spin_unlock(&avc->pagewriter_lock);
2795
2796     /* Add ourselves to writer list */
2797     pw = osi_Alloc(sizeof(struct pagewriter));
2798     pw->writer = pid;
2799     spin_lock(&avc->pagewriter_lock);
2800     list_add_tail(&pw->link, &avc->pagewriters);
2801     spin_unlock(&avc->pagewriter_lock);
2802
2803     return 0;
2804 }
2805
2806 static inline int
2807 afs_linux_dopartialwrite(struct vcache *avc, cred_t *credp) {
2808     struct vrequest *treq = NULL;
2809     int code = 0;
2810
2811     if (!afs_CreateReq(&treq, credp)) {
2812         code = afs_DoPartialWrite(avc, treq);
2813         afs_DestroyReq(treq);
2814     }
2815
2816     return afs_convert_code(code);
2817 }
2818
2819 static inline void
2820 afs_linux_complete_writeback(struct vcache *avc) {
2821     struct pagewriter *pw, *store;
2822     pid_t pid;
2823     struct list_head tofree;
2824
2825     INIT_LIST_HEAD(&tofree);
2826     pid = MyPidxx2Pid(MyPidxx);
2827     /* Remove ourselves from writer list */
2828     spin_lock(&avc->pagewriter_lock);
2829     list_for_each_entry_safe(pw, store, &avc->pagewriters, link) {
2830         if (pw->writer == pid) {
2831             list_del(&pw->link);
2832             /* osi_Free may sleep so we need to defer it */
2833             list_add_tail(&pw->link, &tofree);
2834         }
2835     }
2836     spin_unlock(&avc->pagewriter_lock);
2837     list_for_each_entry_safe(pw, store, &tofree, link) {
2838         list_del(&pw->link);
2839         osi_Free(pw, sizeof(struct pagewriter));
2840     }
2841 }
2842
2843 /* Writeback a given page syncronously. Called with no AFS locks held */
2844 static int
2845 afs_linux_page_writeback(struct inode *ip, struct page *pp,
2846                          unsigned long offset, unsigned int count,
2847                          cred_t *credp)
2848 {
2849     struct vcache *vcp = VTOAFS(ip);
2850     char *buffer;
2851     afs_offs_t base;
2852     int code = 0;
2853     struct uio tuio;
2854     struct iovec iovec;
2855     int f_flags = 0;
2856
2857     memset(&tuio, 0, sizeof(tuio));
2858     memset(&iovec, 0, sizeof(iovec));
2859
2860     buffer = kmap(pp) + offset;
2861     base = page_offset(pp) + offset;
2862
2863     AFS_GLOCK();
2864     afs_Trace4(afs_iclSetp, CM_TRACE_UPDATEPAGE, ICL_TYPE_POINTER, vcp,
2865                ICL_TYPE_POINTER, pp, ICL_TYPE_INT32, page_count(pp),
2866                ICL_TYPE_INT32, 99999);
2867
2868     setup_uio(&tuio, &iovec, buffer, base, count, UIO_WRITE, AFS_UIOSYS);
2869
2870     code = afs_write(vcp, &tuio, f_flags, credp, 0);
2871
2872     i_size_write(ip, vcp->f.m.Length);
2873     ip->i_blocks = ((vcp->f.m.Length + 1023) >> 10) << 1;
2874
2875     code = code ? afs_convert_code(code) : count - tuio.uio_resid;
2876
2877     afs_Trace4(afs_iclSetp, CM_TRACE_UPDATEPAGE, ICL_TYPE_POINTER, vcp,
2878                ICL_TYPE_POINTER, pp, ICL_TYPE_INT32, page_count(pp),
2879                ICL_TYPE_INT32, code);
2880
2881     AFS_GUNLOCK();
2882     kunmap(pp);
2883
2884     return code;
2885 }
2886
2887 static int
2888 afs_linux_writepage_sync(struct inode *ip, struct page *pp,
2889                          unsigned long offset, unsigned int count)
2890 {
2891     int code;
2892     int code1 = 0;
2893     struct vcache *vcp = VTOAFS(ip);
2894     cred_t *credp;
2895
2896     /* Catch recursive writeback. This occurs if the kernel decides
2897      * writeback is required whilst we are writing to the cache, or
2898      * flushing to the server. When we're running syncronously (as
2899      * opposed to from writepage) we can't actually do anything about
2900      * this case - as we can't return AOP_WRITEPAGE_ACTIVATE to write()
2901      */
2902     AFS_GLOCK();
2903     ObtainWriteLock(&vcp->lock, 532);
2904     afs_linux_prepare_writeback(vcp);
2905     ReleaseWriteLock(&vcp->lock);
2906     AFS_GUNLOCK();
2907
2908     credp = crref();
2909     code = afs_linux_page_writeback(ip, pp, offset, count, credp);
2910
2911     AFS_GLOCK();
2912     ObtainWriteLock(&vcp->lock, 533);
2913     if (code > 0)
2914         code1 = afs_linux_dopartialwrite(vcp, credp);
2915     afs_linux_complete_writeback(vcp);
2916     ReleaseWriteLock(&vcp->lock);
2917     AFS_GUNLOCK();
2918     crfree(credp);
2919
2920     if (code1)
2921         return code1;
2922
2923     return code;
2924 }
2925
2926 static int
2927 #ifdef AOP_WRITEPAGE_TAKES_WRITEBACK_CONTROL
2928 afs_linux_writepage(struct page *pp, struct writeback_control *wbc)
2929 #else
2930 afs_linux_writepage(struct page *pp)
2931 #endif
2932 {
2933     struct address_space *mapping = pp->mapping;
2934     struct inode *inode;
2935     struct vcache *vcp;
2936     cred_t *credp;
2937     unsigned int to = PAGE_SIZE;
2938     loff_t isize;
2939     int code = 0;
2940     int code1 = 0;
2941
2942     get_page(pp);
2943
2944     inode = mapping->host;
2945     vcp = VTOAFS(inode);
2946     isize = i_size_read(inode);
2947
2948     /* Don't defeat an earlier truncate */
2949     if (page_offset(pp) > isize) {
2950         set_page_writeback(pp);
2951         unlock_page(pp);
2952         goto done;
2953     }
2954
2955     AFS_GLOCK();
2956     ObtainWriteLock(&vcp->lock, 537);
2957     code = afs_linux_prepare_writeback(vcp);
2958     if (code == AOP_WRITEPAGE_ACTIVATE) {
2959         /* WRITEPAGE_ACTIVATE is the only return value that permits us
2960          * to return with the page still locked */
2961         ReleaseWriteLock(&vcp->lock);
2962         AFS_GUNLOCK();
2963         return code;
2964     }
2965
2966     /* Grab the creds structure currently held in the vnode, and
2967      * get a reference to it, in case it goes away ... */
2968     credp = vcp->cred;
2969     if (credp)
2970         crhold(credp);
2971     else
2972         credp = crref();
2973     ReleaseWriteLock(&vcp->lock);
2974     AFS_GUNLOCK();
2975
2976     set_page_writeback(pp);
2977
2978     SetPageUptodate(pp);
2979
2980     /* We can unlock the page here, because it's protected by the
2981      * page_writeback flag. This should make us less vulnerable to
2982      * deadlocking in afs_write and afs_DoPartialWrite
2983      */
2984     unlock_page(pp);
2985
2986     /* If this is the final page, then just write the number of bytes that
2987      * are actually in it */
2988     if ((isize - page_offset(pp)) < to )
2989         to = isize - page_offset(pp);
2990
2991     code = afs_linux_page_writeback(inode, pp, 0, to, credp);
2992
2993     AFS_GLOCK();
2994     ObtainWriteLock(&vcp->lock, 538);
2995
2996     /* As much as we might like to ignore a file server error here,
2997      * and just try again when we close(), unfortunately StoreAllSegments
2998      * will invalidate our chunks if the server returns a permanent error,
2999      * so we need to at least try and get that error back to the user
3000      */
3001     if (code == to)
3002         code1 = afs_linux_dopartialwrite(vcp, credp);
3003
3004     afs_linux_complete_writeback(vcp);
3005     ReleaseWriteLock(&vcp->lock);
3006     crfree(credp);
3007     AFS_GUNLOCK();
3008
3009 done:
3010     end_page_writeback(pp);
3011     put_page(pp);
3012
3013     if (code1)
3014         return code1;
3015
3016     if (code == to)
3017         return 0;
3018
3019     return code;
3020 }
3021
3022 /* afs_linux_permission
3023  * Check access rights - returns error if can't check or permission denied.
3024  */
3025 static int
3026 #if defined(IOP_PERMISSION_TAKES_FLAGS)
3027 afs_linux_permission(struct inode *ip, int mode, unsigned int flags)
3028 #elif defined(IOP_PERMISSION_TAKES_NAMEIDATA)
3029 afs_linux_permission(struct inode *ip, int mode, struct nameidata *nd)
3030 #else
3031 afs_linux_permission(struct inode *ip, int mode)
3032 #endif
3033 {
3034     int code;
3035     cred_t *credp;
3036     int tmp = 0;
3037
3038     /* Check for RCU path walking */
3039 #if defined(IOP_PERMISSION_TAKES_FLAGS)
3040     if (flags & IPERM_FLAG_RCU)
3041        return -ECHILD;
3042 #elif defined(MAY_NOT_BLOCK)
3043     if (mode & MAY_NOT_BLOCK)
3044        return -ECHILD;
3045 #endif
3046
3047     credp = crref();
3048     AFS_GLOCK();
3049     if (mode & MAY_EXEC)
3050         tmp |= VEXEC;
3051     if (mode & MAY_READ)
3052         tmp |= VREAD;
3053     if (mode & MAY_WRITE)
3054         tmp |= VWRITE;
3055     code = afs_access(VTOAFS(ip), tmp, credp);
3056
3057     AFS_GUNLOCK();
3058     crfree(credp);
3059     return afs_convert_code(code);
3060 }
3061
3062 static int
3063 afs_linux_commit_write(struct file *file, struct page *page, unsigned offset,
3064                        unsigned to)
3065 {
3066     int code;
3067     struct inode *inode = FILE_INODE(file);
3068     loff_t pagebase = page_offset(page);
3069
3070     if (i_size_read(inode) < (pagebase + offset))
3071         i_size_write(inode, pagebase + offset);
3072
3073     if (PageChecked(page)) {
3074         SetPageUptodate(page);
3075         ClearPageChecked(page);
3076     }
3077
3078     code = afs_linux_writepage_sync(inode, page, offset, to - offset);
3079
3080     return code;
3081 }
3082
3083 static int
3084 afs_linux_prepare_write(struct file *file, struct page *page, unsigned from,
3085                         unsigned to)
3086 {
3087
3088     /* http://kerneltrap.org/node/4941 details the expected behaviour of
3089      * prepare_write. Essentially, if the page exists within the file,
3090      * and is not being fully written, then we should populate it.
3091      */
3092
3093     if (!PageUptodate(page)) {
3094         loff_t pagebase = page_offset(page);
3095         loff_t isize = i_size_read(page->mapping->host);
3096
3097         /* Is the location we are writing to beyond the end of the file? */
3098         if (pagebase >= isize ||
3099             ((from == 0) && (pagebase + to) >= isize)) {
3100             zero_user_segments(page, 0, from, to, PAGE_SIZE);
3101             SetPageChecked(page);
3102         /* Are we we writing a full page */
3103         } else if (from == 0 && to == PAGE_SIZE) {
3104             SetPageChecked(page);
3105         /* Is the page readable, if it's wronly, we don't care, because we're
3106          * not actually going to read from it ... */
3107         } else if ((file->f_flags && O_ACCMODE) != O_WRONLY) {
3108             /* We don't care if fillpage fails, because if it does the page
3109              * won't be marked as up to date
3110              */
3111             afs_linux_fillpage(file, page);
3112         }
3113     }
3114     return 0;
3115 }
3116
3117 #if defined(STRUCT_ADDRESS_SPACE_OPERATIONS_HAS_WRITE_BEGIN)
3118 static int
3119 afs_linux_write_end(struct file *file, struct address_space *mapping,
3120                                 loff_t pos, unsigned len, unsigned copied,
3121                                 struct page *page, void *fsdata)
3122 {
3123     int code;
3124     unsigned int from = pos & (PAGE_SIZE - 1);
3125
3126     code = afs_linux_commit_write(file, page, from, from + copied);
3127
3128     unlock_page(page);
3129     put_page(page);
3130     return code;
3131 }
3132
3133 static int
3134 afs_linux_write_begin(struct file *file, struct address_space *mapping,
3135                                 loff_t pos, unsigned len, unsigned flags,
3136                                 struct page **pagep, void **fsdata)
3137 {
3138     struct page *page;
3139     pgoff_t index = pos >> PAGE_SHIFT;
3140     unsigned int from = pos & (PAGE_SIZE - 1);
3141     int code;
3142
3143     page = grab_cache_page_write_begin(mapping, index, flags);
3144     if (!page) {
3145         return -ENOMEM;
3146     }
3147
3148     *pagep = page;
3149
3150     code = afs_linux_prepare_write(file, page, from, from + len);
3151     if (code) {
3152         unlock_page(page);
3153         put_page(page);
3154     }
3155
3156     return code;
3157 }
3158 #endif
3159
3160 #ifndef STRUCT_DENTRY_OPERATIONS_HAS_D_AUTOMOUNT
3161 static void *
3162 afs_linux_dir_follow_link(struct dentry *dentry, struct nameidata *nd)
3163 {
3164     struct dentry **dpp;
3165     struct dentry *target;
3166
3167     if (current->total_link_count > 0) {
3168         /* avoid symlink resolution limits when resolving; we cannot contribute to
3169          * an infinite symlink loop */
3170         /* only do this for follow_link when total_link_count is positive to be
3171          * on the safe side; there is at least one code path in the Linux
3172          * kernel where it seems like it may be possible to get here without
3173          * total_link_count getting incremented. it is not clear on how that
3174          * path is actually reached, but guard against it just to be safe */
3175         current->total_link_count--;
3176     }
3177
3178     target = canonical_dentry(dentry->d_inode);
3179
3180 # ifdef STRUCT_NAMEIDATA_HAS_PATH
3181     dpp = &nd->path.dentry;
3182 # else
3183     dpp = &nd->dentry;
3184 # endif
3185
3186     dput(*dpp);
3187
3188     if (target) {
3189         *dpp = target;
3190     } else {
3191         *dpp = dget(dentry);
3192     }
3193
3194     nd->last_type = LAST_BIND;
3195
3196     return NULL;
3197 }
3198 #endif /* !STRUCT_DENTRY_OPERATIONS_HAS_D_AUTOMOUNT */
3199
3200
3201 static struct inode_operations afs_file_iops = {
3202   .permission =         afs_linux_permission,
3203   .getattr =            afs_linux_getattr,
3204   .setattr =            afs_notify_change,
3205 };
3206
3207 static struct address_space_operations afs_file_aops = {
3208   .readpage =           afs_linux_readpage,
3209   .readpages =          afs_linux_readpages,
3210   .writepage =          afs_linux_writepage,
3211 #if defined (STRUCT_ADDRESS_SPACE_OPERATIONS_HAS_WRITE_BEGIN)
3212   .write_begin =        afs_linux_write_begin,
3213   .write_end =          afs_linux_write_end,
3214 #else
3215   .commit_write =       afs_linux_commit_write,
3216   .prepare_write =      afs_linux_prepare_write,
3217 #endif
3218 };
3219
3220
3221 /* Separate ops vector for directories. Linux 2.2 tests type of inode
3222  * by what sort of operation is allowed.....
3223  */
3224
3225 static struct inode_operations afs_dir_iops = {
3226   .setattr =            afs_notify_change,
3227   .create =             afs_linux_create,
3228   .lookup =             afs_linux_lookup,
3229   .link =               afs_linux_link,
3230   .unlink =             afs_linux_unlink,
3231   .symlink =            afs_linux_symlink,
3232   .mkdir =              afs_linux_mkdir,
3233   .rmdir =              afs_linux_rmdir,
3234   .rename =             afs_linux_rename,
3235   .getattr =            afs_linux_getattr,
3236   .permission =         afs_linux_permission,
3237 #ifndef STRUCT_DENTRY_OPERATIONS_HAS_D_AUTOMOUNT
3238   .follow_link =        afs_linux_dir_follow_link,
3239 #endif
3240 };
3241
3242 /* We really need a separate symlink set of ops, since do_follow_link()
3243  * determines if it _is_ a link by checking if the follow_link op is set.
3244  */
3245 #if defined(USABLE_KERNEL_PAGE_SYMLINK_CACHE)
3246 static int
3247 afs_symlink_filler(struct file *file, struct page *page)
3248 {
3249     struct inode *ip = (struct inode *)page->mapping->host;
3250     char *p = (char *)kmap(page);
3251     int code;
3252
3253     AFS_GLOCK();
3254     code = afs_linux_ireadlink(ip, p, PAGE_SIZE, AFS_UIOSYS);
3255     AFS_GUNLOCK();
3256
3257     if (code < 0)
3258         goto fail;
3259     p[code] = '\0';             /* null terminate? */
3260
3261     SetPageUptodate(page);
3262     kunmap(page);
3263     unlock_page(page);
3264     return 0;
3265
3266   fail:
3267     SetPageError(page);
3268     kunmap(page);
3269     unlock_page(page);
3270     return code;
3271 }
3272
3273 static struct address_space_operations afs_symlink_aops = {
3274   .readpage =   afs_symlink_filler
3275 };
3276 #endif  /* USABLE_KERNEL_PAGE_SYMLINK_CACHE */
3277
3278 static struct inode_operations afs_symlink_iops = {
3279 #if defined(USABLE_KERNEL_PAGE_SYMLINK_CACHE)
3280   .readlink =           page_readlink,
3281 # if defined(HAVE_LINUX_PAGE_GET_LINK)
3282   .get_link =           page_get_link,
3283 # elif defined(HAVE_LINUX_PAGE_FOLLOW_LINK)
3284   .follow_link =        page_follow_link,
3285 # else
3286   .follow_link =        page_follow_link_light,
3287   .put_link =           page_put_link,
3288 # endif
3289 #else /* !defined(USABLE_KERNEL_PAGE_SYMLINK_CACHE) */
3290   .readlink =           afs_linux_readlink,
3291   .follow_link =        afs_linux_follow_link,
3292   .put_link =           afs_linux_put_link,
3293 #endif /* USABLE_KERNEL_PAGE_SYMLINK_CACHE */
3294   .setattr =            afs_notify_change,
3295 };
3296
3297 void
3298 afs_fill_inode(struct inode *ip, struct vattr *vattr)
3299 {
3300     if (vattr)
3301         vattr2inode(ip, vattr);
3302
3303 #ifdef STRUCT_ADDRESS_SPACE_HAS_BACKING_DEV_INFO
3304     ip->i_mapping->backing_dev_info = afs_backing_dev_info;
3305 #endif
3306 /* Reset ops if symlink or directory. */
3307     if (S_ISREG(ip->i_mode)) {
3308         ip->i_op = &afs_file_iops;
3309         ip->i_fop = &afs_file_fops;
3310         ip->i_data.a_ops = &afs_file_aops;
3311
3312     } else if (S_ISDIR(ip->i_mode)) {
3313         ip->i_op = &afs_dir_iops;
3314         ip->i_fop = &afs_dir_fops;
3315
3316     } else if (S_ISLNK(ip->i_mode)) {
3317         ip->i_op = &afs_symlink_iops;
3318 #if defined(HAVE_LINUX_INODE_NOHIGHMEM)
3319         inode_nohighmem(ip);
3320 #endif
3321 #if defined(USABLE_KERNEL_PAGE_SYMLINK_CACHE)
3322         ip->i_data.a_ops = &afs_symlink_aops;
3323         ip->i_mapping = &ip->i_data;
3324 #endif
3325     }
3326
3327 }