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