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