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