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