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