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