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