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