Linux: Only use automount for volume roots
[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);
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     int 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         dirpos = BlobScan(tdc, offset);
389         if (!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     mutex_lock(&ip->i_mutex);
587 #endif
588     AFS_GLOCK();
589     code = afs_fsync(VTOAFS(ip), credp);
590     AFS_GUNLOCK();
591 #if defined(FOP_FSYNC_TAKES_RANGE)
592     mutex_unlock(&ip->i_mutex);
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)
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)
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 locked = 0;
1145     int force_drop = 0;
1146     afs_uint32 parent_dv;
1147
1148 #ifdef LOOKUP_RCU
1149     /* We don't support RCU path walking */
1150 # if defined(DOP_REVALIDATE_TAKES_UNSIGNED)
1151     if (flags & LOOKUP_RCU)
1152 # else
1153     if (nd->flags & LOOKUP_RCU)
1154 # endif
1155        return -ECHILD;
1156 #endif
1157
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         parent = dget_parent(dp);
1167         pvcp = VTOAFS(parent->d_inode);
1168
1169         if ((vcp->mvstat != AFS_MVSTAT_FILE) ||
1170                 (pvcp->mvstat == AFS_MVSTAT_MTPT && afs_fakestat_enable)) {     /* need to lock */
1171             credp = crref();
1172             AFS_GLOCK();
1173             locked = 1;
1174         }
1175
1176         if (locked) {
1177             if (vcp->mvstat == AFS_MVSTAT_MTPT) {
1178                 if (vcp->mvid.target_root && (vcp->f.states & CMValid)) {
1179                     int tryEvalOnly = 0;
1180                     int code = 0;
1181                     struct vrequest *treq = NULL;
1182
1183                     code = afs_CreateReq(&treq, credp);
1184                     if (code) {
1185                         dput(parent);
1186                         goto bad_dentry;
1187                     }
1188                     if ((strcmp(dp->d_name.name, ".directory") == 0)) {
1189                         tryEvalOnly = 1;
1190                     }
1191                     if (tryEvalOnly)
1192                         code = afs_TryEvalFakeStat(&vcp, &fakestate, treq);
1193                     else
1194                         code = afs_EvalFakeStat(&vcp, &fakestate, treq);
1195                     afs_DestroyReq(treq);
1196                     if ((tryEvalOnly && vcp->mvstat == AFS_MVSTAT_MTPT) || code) {
1197                         /* a mount point, not yet replaced by its directory */
1198                         dput(parent);
1199                         goto bad_dentry;
1200                     }
1201                 }
1202             } else if (vcp->mvstat == AFS_MVSTAT_ROOT && *dp->d_name.name != '/') {
1203                 osi_Assert(vcp->mvid.parent != NULL);
1204             }
1205         }
1206
1207 #ifdef notdef
1208         /* If the last looker changes, we should make sure the current
1209          * looker still has permission to examine this file.  This would
1210          * always require a crref() which would be "slow".
1211          */
1212         if (vcp->last_looker != treq.uid) {
1213             if (!afs_AccessOK(vcp, (vType(vcp) == VREG) ? PRSFS_READ : PRSFS_LOOKUP, &treq, CHECK_MODE_BITS)) {
1214                 dput(parent);
1215                 goto bad_dentry;
1216             }
1217
1218             vcp->last_looker = treq.uid;
1219         }
1220 #endif
1221
1222         parent_dv = parent_vcache_dv(parent->d_inode, credp);
1223
1224         /* If the parent's DataVersion has changed or the vnode
1225          * is longer valid, we need to do a full lookup.  VerifyVCache
1226          * isn't enough since the vnode may have been renamed.
1227          */
1228
1229         if ((!locked) && (parent_dv > dp->d_time || !(vcp->f.states & CStatd)) ) {
1230             credp = crref();
1231             AFS_GLOCK();
1232             locked = 1;
1233         }
1234
1235         if (locked && (parent_dv > dp->d_time || !(vcp->f.states & CStatd))) {
1236             struct vattr *vattr = NULL;
1237             int code;
1238             int lookup_good;
1239
1240             code = afs_lookup(pvcp, (char *)dp->d_name.name, &tvc, credp);
1241
1242             if (code) {
1243                 /* We couldn't perform the lookup, so we're not okay. */
1244                 lookup_good = 0;
1245
1246             } else if (tvc == vcp) {
1247                 /* We got back the same vcache, so we're good. */
1248                 lookup_good = 1;
1249
1250             } else if (tvc == VTOAFS(dp->d_inode)) {
1251                 /* We got back the same vcache, so we're good. This is
1252                  * different from the above case, because sometimes 'vcp' is
1253                  * not the same as the vcache for dp->d_inode, if 'vcp' was a
1254                  * mtpt and we evaluated it to a root dir. In rare cases,
1255                  * afs_lookup might not evalute the mtpt when we do, or vice
1256                  * versa, so the previous case will not succeed. But this is
1257                  * still 'correct', so make sure not to mark the dentry as
1258                  * invalid; it still points to the same thing! */
1259                 lookup_good = 1;
1260
1261             } else {
1262                 /* We got back a different file, so we're definitely not
1263                  * okay. */
1264                 lookup_good = 0;
1265             }
1266
1267             if (!lookup_good) {
1268                 dput(parent);
1269                 /* Force unhash; the name doesn't point to this file
1270                  * anymore. */
1271                 force_drop = 1;
1272                 if (code && code != ENOENT) {
1273                     /* ...except if we couldn't perform the actual lookup,
1274                      * we don't know if the name points to this file or not. */
1275                     force_drop = 0;
1276                 }
1277                 goto bad_dentry;
1278             }
1279
1280             code = afs_CreateAttr(&vattr);
1281             if (code) {
1282                 dput(parent);
1283                 goto bad_dentry;
1284             }
1285
1286             if (afs_getattr(vcp, vattr, credp)) {
1287                 dput(parent);
1288                 afs_DestroyAttr(vattr);
1289                 goto bad_dentry;
1290             }
1291
1292             vattr2inode(AFSTOV(vcp), vattr);
1293             dp->d_time = parent_dv;
1294
1295             afs_DestroyAttr(vattr);
1296         }
1297
1298         /* should we always update the attributes at this point? */
1299         /* unlikely--the vcache entry hasn't changed */
1300
1301         dput(parent);
1302     } else {
1303 #ifdef notyet
1304         /* If this code is ever enabled, we should use dget_parent to handle
1305          * getting the parent, and dput() to dispose of it. See above for an
1306          * example ... */
1307         pvcp = VTOAFS(dp->d_parent->d_inode);
1308         if (hgetlo(pvcp->f.m.DataVersion) > dp->d_time)
1309             goto bad_dentry;
1310 #endif
1311
1312         /* No change in parent's DataVersion so this negative
1313          * lookup is still valid.  BUT, if a server is down a
1314          * negative lookup can result so there should be a
1315          * liftime as well.  For now, always expire.
1316          */
1317
1318         goto bad_dentry;
1319     }
1320
1321   good_dentry:
1322     valid = 1;
1323
1324   done:
1325     /* Clean up */
1326     if (tvc)
1327         afs_PutVCache(tvc);
1328     afs_PutFakeStat(&fakestate);        /* from here on vcp may be no longer valid */
1329     if (locked) {
1330         /* we hold the global lock if we evaluated a mount point */
1331         AFS_GUNLOCK();
1332     }
1333     if (credp)
1334         crfree(credp);
1335
1336     if (!valid) {
1337         /*
1338          * If we had a negative lookup for the name we want to forcibly
1339          * unhash the dentry.
1340          * Otherwise use d_invalidate which will not unhash it if still in use.
1341          */
1342         if (force_drop) {
1343             shrink_dcache_parent(dp);
1344             d_drop(dp);
1345         } else
1346             d_invalidate(dp);
1347     }
1348
1349     return valid;
1350
1351   bad_dentry:
1352     if (have_submounts(dp))
1353         valid = 1;
1354     else 
1355         valid = 0;
1356     goto done;
1357 }
1358
1359 static void
1360 afs_dentry_iput(struct dentry *dp, struct inode *ip)
1361 {
1362     struct vcache *vcp = VTOAFS(ip);
1363
1364     AFS_GLOCK();
1365     if (!AFS_IS_DISCONNECTED || (vcp->f.states & CUnlinked)) {
1366         (void) afs_InactiveVCache(vcp, NULL);
1367     }
1368     AFS_GUNLOCK();
1369     afs_linux_clear_nfsfs_renamed(dp);
1370
1371     iput(ip);
1372 }
1373
1374 static int
1375 #if defined(DOP_D_DELETE_TAKES_CONST)
1376 afs_dentry_delete(const struct dentry *dp)
1377 #else
1378 afs_dentry_delete(struct dentry *dp)
1379 #endif
1380 {
1381     if (dp->d_inode && (VTOAFS(dp->d_inode)->f.states & CUnlinked))
1382         return 1;               /* bad inode? */
1383
1384     return 0;
1385 }
1386
1387 #ifdef STRUCT_DENTRY_OPERATIONS_HAS_D_AUTOMOUNT
1388 static struct vfsmount *
1389 afs_dentry_automount(afs_linux_path_t *path)
1390 {
1391     struct dentry *target;
1392
1393     /* 
1394      * Avoid symlink resolution limits when resolving; we cannot contribute to
1395      * an infinite symlink loop.
1396      *
1397      * On newer kernels the field has moved to the private nameidata structure
1398      * so we can't adjust it here.  This may cause ELOOP when using a path with
1399      * 40 or more directories that are not already in the dentry cache.
1400      */
1401 #if defined(STRUCT_TASK_STRUCT_HAS_TOTAL_LINK_COUNT)
1402     current->total_link_count--;
1403 #endif
1404
1405     target = canonical_dentry(path->dentry->d_inode);
1406
1407     if (target == path->dentry) {
1408         dput(target);
1409         target = NULL;
1410     }
1411
1412     if (target) {
1413         dput(path->dentry);
1414         path->dentry = target;
1415
1416     } else {
1417         spin_lock(&path->dentry->d_lock);
1418         path->dentry->d_flags &= ~DCACHE_NEED_AUTOMOUNT;
1419         spin_unlock(&path->dentry->d_lock);
1420     }
1421
1422     return NULL;
1423 }
1424 #endif /* STRUCT_DENTRY_OPERATIONS_HAS_D_AUTOMOUNT */
1425
1426 struct dentry_operations afs_dentry_operations = {
1427   .d_revalidate =       afs_linux_dentry_revalidate,
1428   .d_delete =           afs_dentry_delete,
1429   .d_iput =             afs_dentry_iput,
1430 #ifdef STRUCT_DENTRY_OPERATIONS_HAS_D_AUTOMOUNT
1431   .d_automount =        afs_dentry_automount,
1432 #endif /* STRUCT_DENTRY_OPERATIONS_HAS_D_AUTOMOUNT */
1433 };
1434
1435 /**********************************************************************
1436  * AFS Linux inode operations
1437  **********************************************************************/
1438
1439 /* afs_linux_create
1440  *
1441  * Merely need to set enough of vattr to get us through the create. Note
1442  * that the higher level code (open_namei) will take care of any tuncation
1443  * explicitly. Exclusive open is also taken care of in open_namei.
1444  *
1445  * name is in kernel space at this point.
1446  */
1447 static int
1448 #if defined(IOP_CREATE_TAKES_BOOL)
1449 afs_linux_create(struct inode *dip, struct dentry *dp, umode_t mode,
1450                  bool excl)
1451 #elif defined(IOP_CREATE_TAKES_UMODE_T)
1452 afs_linux_create(struct inode *dip, struct dentry *dp, umode_t mode,
1453                  struct nameidata *nd)
1454 #elif defined(IOP_CREATE_TAKES_NAMEIDATA)
1455 afs_linux_create(struct inode *dip, struct dentry *dp, int mode,
1456                  struct nameidata *nd)
1457 #else
1458 afs_linux_create(struct inode *dip, struct dentry *dp, int mode)
1459 #endif
1460 {
1461     struct vattr *vattr = NULL;
1462     cred_t *credp = crref();
1463     const char *name = dp->d_name.name;
1464     struct vcache *vcp;
1465     int code;
1466
1467     AFS_GLOCK();
1468
1469     code = afs_CreateAttr(&vattr);
1470     if (code) {
1471         goto out;
1472     }
1473     vattr->va_mode = mode;
1474     vattr->va_type = mode & S_IFMT;
1475
1476     code = afs_create(VTOAFS(dip), (char *)name, vattr, NONEXCL, mode,
1477                       &vcp, credp);
1478
1479     if (!code) {
1480         struct inode *ip = AFSTOV(vcp);
1481
1482         afs_getattr(vcp, vattr, credp);
1483         afs_fill_inode(ip, vattr);
1484         insert_inode_hash(ip);
1485 #if !defined(STRUCT_SUPER_BLOCK_HAS_S_D_OP)
1486         dp->d_op = &afs_dentry_operations;
1487 #endif
1488         dp->d_time = parent_vcache_dv(dip, credp);
1489         d_instantiate(dp, ip);
1490     }
1491
1492     afs_DestroyAttr(vattr);
1493
1494 out:
1495     AFS_GUNLOCK();
1496
1497     crfree(credp);
1498     return afs_convert_code(code);
1499 }
1500
1501 /* afs_linux_lookup */
1502 static struct dentry *
1503 #if defined(IOP_LOOKUP_TAKES_UNSIGNED)
1504 afs_linux_lookup(struct inode *dip, struct dentry *dp,
1505                  unsigned flags)
1506 #elif defined(IOP_LOOKUP_TAKES_NAMEIDATA)
1507 afs_linux_lookup(struct inode *dip, struct dentry *dp,
1508                  struct nameidata *nd)
1509 #else
1510 afs_linux_lookup(struct inode *dip, struct dentry *dp)
1511 #endif
1512 {
1513     cred_t *credp = crref();
1514     struct vcache *vcp = NULL;
1515     const char *comp = dp->d_name.name;
1516     struct inode *ip = NULL;
1517     struct dentry *newdp = NULL;
1518     int code;
1519
1520     AFS_GLOCK();
1521     code = afs_lookup(VTOAFS(dip), (char *)comp, &vcp, credp);
1522     
1523     if (!code) {
1524         struct vattr *vattr = NULL;
1525         struct vcache *parent_vc = VTOAFS(dip);
1526
1527         if (parent_vc == vcp) {
1528             /* This is possible if the parent dir is a mountpoint to a volume,
1529              * and the dir entry we looked up is a mountpoint to the same
1530              * volume. Linux cannot cope with this, so return an error instead
1531              * of risking a deadlock or panic. */
1532             afs_PutVCache(vcp);
1533             code = EDEADLK;
1534             AFS_GUNLOCK();
1535             goto done;
1536         }
1537
1538         code = afs_CreateAttr(&vattr);
1539         if (code) {
1540             afs_PutVCache(vcp);
1541             AFS_GUNLOCK();
1542             goto done;
1543         }
1544
1545         ip = AFSTOV(vcp);
1546         afs_getattr(vcp, vattr, credp);
1547         afs_fill_inode(ip, vattr);
1548         if (hlist_unhashed(&ip->i_hash))
1549             insert_inode_hash(ip);
1550
1551         afs_DestroyAttr(vattr);
1552     }
1553 #if !defined(STRUCT_SUPER_BLOCK_HAS_S_D_OP)
1554     dp->d_op = &afs_dentry_operations;
1555 #endif
1556     dp->d_time = parent_vcache_dv(dip, credp);
1557
1558     AFS_GUNLOCK();
1559
1560     if (ip && S_ISDIR(ip->i_mode)) {
1561         d_prune_aliases(ip);
1562
1563 #ifdef STRUCT_DENTRY_OPERATIONS_HAS_D_AUTOMOUNT
1564         /* Only needed if this is a volume root */
1565         if (vcp->mvstat == 2)
1566             ip->i_flags |= S_AUTOMOUNT;
1567 #endif
1568     }
1569     /*
1570      * Take an extra reference so the inode doesn't go away if
1571      * d_splice_alias drops our reference on error.
1572      */
1573     if (ip)
1574 #ifdef HAVE_LINUX_IHOLD
1575         ihold(ip);
1576 #else
1577         igrab(ip);
1578 #endif
1579
1580     newdp = d_splice_alias(ip, dp);
1581
1582  done:
1583     crfree(credp);
1584
1585     /* It's ok for the file to not be found. That's noted by the caller by
1586      * seeing that the dp->d_inode field is NULL.
1587      */
1588     if (!code || code == ENOENT) {
1589         /*
1590          * d_splice_alias can return an error (EIO) if there is an existing
1591          * connected directory alias for this dentry.
1592          */
1593         if (!IS_ERR(newdp)) {
1594             iput(ip);
1595             return newdp;
1596         } else {
1597             d_add(dp, ip);
1598             /*
1599              * Depending on the kernel version, d_splice_alias may or may
1600              * not drop the inode reference on error.  If it didn't, do it
1601              * here.
1602              */
1603 #if defined(D_SPLICE_ALIAS_LEAK_ON_ERROR)
1604             iput(ip);
1605 #endif
1606             return NULL;
1607         }
1608     } else {
1609         if (ip)
1610             iput(ip);
1611         return ERR_PTR(afs_convert_code(code));
1612     }
1613 }
1614
1615 static int
1616 afs_linux_link(struct dentry *olddp, struct inode *dip, struct dentry *newdp)
1617 {
1618     int code;
1619     cred_t *credp = crref();
1620     const char *name = newdp->d_name.name;
1621     struct inode *oldip = olddp->d_inode;
1622
1623     /* If afs_link returned the vnode, we could instantiate the
1624      * dentry. Since it's not, we drop this one and do a new lookup.
1625      */
1626     d_drop(newdp);
1627
1628     AFS_GLOCK();
1629     code = afs_link(VTOAFS(oldip), VTOAFS(dip), (char *)name, credp);
1630
1631     AFS_GUNLOCK();
1632     crfree(credp);
1633     return afs_convert_code(code);
1634 }
1635
1636 /* We have to have a Linux specific sillyrename function, because we
1637  * also have to keep the dcache up to date when we're doing a silly
1638  * rename - so we don't want the generic vnodeops doing this behind our
1639  * back.
1640  */
1641
1642 static int
1643 afs_linux_sillyrename(struct inode *dir, struct dentry *dentry,
1644                       cred_t *credp)
1645 {
1646     struct vcache *tvc = VTOAFS(dentry->d_inode);
1647     struct dentry *__dp = NULL;
1648     char *__name = NULL;
1649     int code;
1650
1651     if (afs_linux_nfsfs_renamed(dentry))
1652         return EBUSY;
1653
1654     do {
1655         dput(__dp);
1656
1657         AFS_GLOCK();
1658         if (__name)
1659             osi_FreeSmallSpace(__name);
1660         __name = afs_newname();
1661         AFS_GUNLOCK();
1662
1663         __dp = lookup_one_len(__name, dentry->d_parent, strlen(__name));
1664
1665         if (IS_ERR(__dp)) {
1666             osi_FreeSmallSpace(__name);
1667             return EBUSY;
1668         }
1669     } while (__dp->d_inode != NULL);
1670
1671     AFS_GLOCK();
1672     code = afs_rename(VTOAFS(dir), (char *)dentry->d_name.name,
1673                       VTOAFS(dir), (char *)__dp->d_name.name,
1674                       credp);
1675     if (!code) {
1676         tvc->mvid.silly_name = __name;
1677         crhold(credp);
1678         if (tvc->uncred) {
1679             crfree(tvc->uncred);
1680         }
1681         tvc->uncred = credp;
1682         tvc->f.states |= CUnlinked;
1683         afs_linux_set_nfsfs_renamed(dentry);
1684     } else {
1685         osi_FreeSmallSpace(__name);
1686     }
1687     AFS_GUNLOCK();
1688
1689     if (!code) {
1690         __dp->d_time = hgetlo(VTOAFS(dir)->f.m.DataVersion);
1691         d_move(dentry, __dp);
1692     }
1693     dput(__dp);
1694
1695     return code;
1696 }
1697
1698
1699 static int
1700 afs_linux_unlink(struct inode *dip, struct dentry *dp)
1701 {
1702     int code = EBUSY;
1703     cred_t *credp = crref();
1704     const char *name = dp->d_name.name;
1705     struct vcache *tvc = VTOAFS(dp->d_inode);
1706
1707     if (VREFCOUNT(tvc) > 1 && tvc->opens > 0
1708                                 && !(tvc->f.states & CUnlinked)) {
1709
1710         code = afs_linux_sillyrename(dip, dp, credp);
1711     } else {
1712         AFS_GLOCK();
1713         code = afs_remove(VTOAFS(dip), (char *)name, credp);
1714         AFS_GUNLOCK();
1715         if (!code)
1716             d_drop(dp);
1717     }
1718
1719     crfree(credp);
1720     return afs_convert_code(code);
1721 }
1722
1723
1724 static int
1725 afs_linux_symlink(struct inode *dip, struct dentry *dp, const char *target)
1726 {
1727     int code;
1728     cred_t *credp = crref();
1729     struct vattr *vattr = NULL;
1730     const char *name = dp->d_name.name;
1731
1732     /* If afs_symlink returned the vnode, we could instantiate the
1733      * dentry. Since it's not, we drop this one and do a new lookup.
1734      */
1735     d_drop(dp);
1736
1737     AFS_GLOCK();
1738     code = afs_CreateAttr(&vattr);
1739     if (code) {
1740         goto out;
1741     }
1742
1743     code = afs_symlink(VTOAFS(dip), (char *)name, vattr, (char *)target, NULL,
1744                         credp);
1745     afs_DestroyAttr(vattr);
1746
1747 out:
1748     AFS_GUNLOCK();
1749     crfree(credp);
1750     return afs_convert_code(code);
1751 }
1752
1753 static int
1754 #if defined(IOP_MKDIR_TAKES_UMODE_T)
1755 afs_linux_mkdir(struct inode *dip, struct dentry *dp, umode_t mode)
1756 #else
1757 afs_linux_mkdir(struct inode *dip, struct dentry *dp, int mode)
1758 #endif
1759 {
1760     int code;
1761     cred_t *credp = crref();
1762     struct vcache *tvcp = NULL;
1763     struct vattr *vattr = NULL;
1764     const char *name = dp->d_name.name;
1765
1766     AFS_GLOCK();
1767     code = afs_CreateAttr(&vattr);
1768     if (code) {
1769         goto out;
1770     }
1771
1772     vattr->va_mask = ATTR_MODE;
1773     vattr->va_mode = mode;
1774
1775     code = afs_mkdir(VTOAFS(dip), (char *)name, vattr, &tvcp, credp);
1776
1777     if (tvcp) {
1778         struct inode *ip = AFSTOV(tvcp);
1779
1780         afs_getattr(tvcp, vattr, credp);
1781         afs_fill_inode(ip, vattr);
1782
1783 #if !defined(STRUCT_SUPER_BLOCK_HAS_S_D_OP)
1784         dp->d_op = &afs_dentry_operations;
1785 #endif
1786         dp->d_time = hgetlo(VTOAFS(dip)->f.m.DataVersion);
1787         d_instantiate(dp, ip);
1788     }
1789     afs_DestroyAttr(vattr);
1790
1791 out:
1792     AFS_GUNLOCK();
1793
1794     crfree(credp);
1795     return afs_convert_code(code);
1796 }
1797
1798 static int
1799 afs_linux_rmdir(struct inode *dip, struct dentry *dp)
1800 {
1801     int code;
1802     cred_t *credp = crref();
1803     const char *name = dp->d_name.name;
1804
1805     /* locking kernel conflicts with glock? */
1806
1807     AFS_GLOCK();
1808     code = afs_rmdir(VTOAFS(dip), (char *)name, credp);
1809     AFS_GUNLOCK();
1810
1811     /* Linux likes to see ENOTEMPTY returned from an rmdir() syscall
1812      * that failed because a directory is not empty. So, we map
1813      * EEXIST to ENOTEMPTY on linux.
1814      */
1815     if (code == EEXIST) {
1816         code = ENOTEMPTY;
1817     }
1818
1819     if (!code) {
1820         d_drop(dp);
1821     }
1822
1823     crfree(credp);
1824     return afs_convert_code(code);
1825 }
1826
1827
1828 static int
1829 afs_linux_rename(struct inode *oldip, struct dentry *olddp,
1830                  struct inode *newip, struct dentry *newdp)
1831 {
1832     int code;
1833     cred_t *credp = crref();
1834     const char *oldname = olddp->d_name.name;
1835     const char *newname = newdp->d_name.name;
1836     struct dentry *rehash = NULL;
1837
1838     /* Prevent any new references during rename operation. */
1839
1840     if (!d_unhashed(newdp)) {
1841         d_drop(newdp);
1842         rehash = newdp;
1843     }
1844
1845     afs_maybe_shrink_dcache(olddp);
1846
1847     AFS_GLOCK();
1848     code = afs_rename(VTOAFS(oldip), (char *)oldname, VTOAFS(newip), (char *)newname, credp);
1849     AFS_GUNLOCK();
1850
1851     if (!code)
1852         olddp->d_time = 0;      /* force to revalidate */
1853
1854     if (rehash)
1855         d_rehash(rehash);
1856
1857     crfree(credp);
1858     return afs_convert_code(code);
1859 }
1860
1861
1862 /* afs_linux_ireadlink 
1863  * Internal readlink which can return link contents to user or kernel space.
1864  * Note that the buffer is NOT supposed to be null-terminated.
1865  */
1866 static int
1867 afs_linux_ireadlink(struct inode *ip, char *target, int maxlen, uio_seg_t seg)
1868 {
1869     int code;
1870     cred_t *credp = crref();
1871     struct uio tuio;
1872     struct iovec iov;
1873
1874     memset(&tuio, 0, sizeof(tuio));
1875     memset(&iov, 0, sizeof(iov));
1876
1877     setup_uio(&tuio, &iov, target, (afs_offs_t) 0, maxlen, UIO_READ, seg);
1878     code = afs_readlink(VTOAFS(ip), &tuio, credp);
1879     crfree(credp);
1880
1881     if (!code)
1882         return maxlen - tuio.uio_resid;
1883     else
1884         return afs_convert_code(code);
1885 }
1886
1887 #if !defined(USABLE_KERNEL_PAGE_SYMLINK_CACHE)
1888 /* afs_linux_readlink 
1889  * Fill target (which is in user space) with contents of symlink.
1890  */
1891 static int
1892 afs_linux_readlink(struct dentry *dp, char *target, int maxlen)
1893 {
1894     int code;
1895     struct inode *ip = dp->d_inode;
1896
1897     AFS_GLOCK();
1898     code = afs_linux_ireadlink(ip, target, maxlen, AFS_UIOUSER);
1899     AFS_GUNLOCK();
1900     return code;
1901 }
1902
1903
1904 /* afs_linux_follow_link
1905  * a file system dependent link following routine.
1906  */
1907 #if defined(HAVE_LINUX_INODE_OPERATIONS_FOLLOW_LINK_NO_NAMEIDATA)
1908 static const char *afs_linux_follow_link(struct dentry *dentry, void **link_data)
1909 #else
1910 static int afs_linux_follow_link(struct dentry *dentry, struct nameidata *nd)
1911 #endif
1912 {
1913     int code;
1914     char *name;
1915
1916     name = kmalloc(PATH_MAX, GFP_NOFS);
1917     if (!name) {
1918 #if defined(HAVE_LINUX_INODE_OPERATIONS_FOLLOW_LINK_NO_NAMEIDATA)
1919         return ERR_PTR(-EIO);
1920 #else
1921         return -EIO;
1922 #endif
1923     }
1924
1925     AFS_GLOCK();
1926     code = afs_linux_ireadlink(dentry->d_inode, name, PATH_MAX - 1, AFS_UIOSYS);
1927     AFS_GUNLOCK();
1928
1929     if (code < 0) {
1930 #if defined(HAVE_LINUX_INODE_OPERATIONS_FOLLOW_LINK_NO_NAMEIDATA)
1931         return ERR_PTR(code);
1932 #else
1933         return code;
1934 #endif
1935     }
1936
1937     name[code] = '\0';
1938 #if defined(HAVE_LINUX_INODE_OPERATIONS_FOLLOW_LINK_NO_NAMEIDATA)
1939     return *link_data = name;
1940 #else
1941     nd_set_link(nd, name);
1942     return 0;
1943 #endif
1944 }
1945
1946 #if defined(HAVE_LINUX_INODE_OPERATIONS_PUT_LINK_NO_NAMEIDATA)
1947 static void
1948 afs_linux_put_link(struct inode *inode, void *link_data)
1949 {
1950     char *name = link_data;
1951
1952     if (name && !IS_ERR(name))
1953         kfree(name);
1954 }
1955 #else
1956 static void
1957 afs_linux_put_link(struct dentry *dentry, struct nameidata *nd)
1958 {
1959     char *name = nd_get_link(nd);
1960
1961     if (name && !IS_ERR(name))
1962         kfree(name);
1963 }
1964 #endif /* HAVE_LINUX_INODE_OPERATIONS_PUT_LINK_NO_NAMEIDATA */
1965
1966 #endif /* USABLE_KERNEL_PAGE_SYMLINK_CACHE */
1967
1968 /* Populate a page by filling it from the cache file pointed at by cachefp
1969  * (which contains indicated chunk)
1970  * If task is NULL, the page copy occurs syncronously, and the routine
1971  * returns with page still locked. If task is non-NULL, then page copies
1972  * may occur in the background, and the page will be unlocked when it is
1973  * ready for use.
1974  */
1975 static int
1976 afs_linux_read_cache(struct file *cachefp, struct page *page,
1977                      int chunk, struct pagevec *lrupv,
1978                      struct afs_pagecopy_task *task) {
1979     loff_t offset = page_offset(page);
1980     struct inode *cacheinode = cachefp->f_dentry->d_inode;
1981     struct page *newpage, *cachepage;
1982     struct address_space *cachemapping;
1983     int pageindex;
1984     int code = 0;
1985
1986     cachemapping = cacheinode->i_mapping;
1987     newpage = NULL;
1988     cachepage = NULL;
1989
1990     /* If we're trying to read a page that's past the end of the disk
1991      * cache file, then just return a zeroed page */
1992     if (AFS_CHUNKOFFSET(offset) >= i_size_read(cacheinode)) {
1993         zero_user_segment(page, 0, PAGE_CACHE_SIZE);
1994         SetPageUptodate(page);
1995         if (task)
1996             unlock_page(page);
1997         return 0;
1998     }
1999
2000     /* From our offset, we now need to work out which page in the disk
2001      * file it corresponds to. This will be fun ... */
2002     pageindex = (offset - AFS_CHUNKTOBASE(chunk)) >> PAGE_CACHE_SHIFT;
2003
2004     while (cachepage == NULL) {
2005         cachepage = find_get_page(cachemapping, pageindex);
2006         if (!cachepage) {
2007             if (!newpage)
2008                 newpage = page_cache_alloc_cold(cachemapping);
2009             if (!newpage) {
2010                 code = -ENOMEM;
2011                 goto out;
2012             }
2013
2014             code = add_to_page_cache(newpage, cachemapping,
2015                                      pageindex, GFP_KERNEL);
2016             if (code == 0) {
2017                 cachepage = newpage;
2018                 newpage = NULL;
2019
2020                 page_cache_get(cachepage);
2021                 if (!pagevec_add(lrupv, cachepage))
2022                     __pagevec_lru_add_file(lrupv);
2023
2024             } else {
2025                 page_cache_release(newpage);
2026                 newpage = NULL;
2027                 if (code != -EEXIST)
2028                     goto out;
2029             }
2030         } else {
2031             lock_page(cachepage);
2032         }
2033     }
2034
2035     if (!PageUptodate(cachepage)) {
2036         ClearPageError(cachepage);
2037         code = cachemapping->a_ops->readpage(NULL, cachepage);
2038         if (!code && !task) {
2039             wait_on_page_locked(cachepage);
2040         }
2041     } else {
2042         unlock_page(cachepage);
2043     }
2044
2045     if (!code) {
2046         if (PageUptodate(cachepage)) {
2047             copy_highpage(page, cachepage);
2048             flush_dcache_page(page);
2049             SetPageUptodate(page);
2050
2051             if (task)
2052                 unlock_page(page);
2053         } else if (task) {
2054             afs_pagecopy_queue_page(task, cachepage, page);
2055         } else {
2056             code = -EIO;
2057         }
2058     }
2059
2060     if (code && task) {
2061         unlock_page(page);
2062     }
2063
2064 out:
2065     if (cachepage)
2066         page_cache_release(cachepage);
2067
2068     return code;
2069 }
2070
2071 static int inline
2072 afs_linux_readpage_fastpath(struct file *fp, struct page *pp, int *codep)
2073 {
2074     loff_t offset = page_offset(pp);
2075     struct inode *ip = FILE_INODE(fp);
2076     struct vcache *avc = VTOAFS(ip);
2077     struct dcache *tdc;
2078     struct file *cacheFp = NULL;
2079     int code;
2080     int dcLocked = 0;
2081     struct pagevec lrupv;
2082
2083     /* Not a UFS cache, don't do anything */
2084     if (cacheDiskType != AFS_FCACHE_TYPE_UFS)
2085         return 0;
2086
2087     /* No readpage (ex: tmpfs) , skip */
2088     if (cachefs_noreadpage)
2089         return 0;
2090
2091     /* Can't do anything if the vcache isn't statd , or if the read
2092      * crosses a chunk boundary.
2093      */
2094     if (!(avc->f.states & CStatd) ||
2095         AFS_CHUNK(offset) != AFS_CHUNK(offset + PAGE_SIZE)) {
2096         return 0;
2097     }
2098
2099     ObtainWriteLock(&avc->lock, 911);
2100
2101     /* XXX - See if hinting actually makes things faster !!! */
2102
2103     /* See if we have a suitable entry already cached */
2104     tdc = avc->dchint;
2105
2106     if (tdc) {
2107         /* We need to lock xdcache, then dcache, to handle situations where
2108          * the hint is on the free list. However, we can't safely do this
2109          * according to the locking hierarchy. So, use a non blocking lock.
2110          */
2111         ObtainReadLock(&afs_xdcache);
2112         dcLocked = ( 0 == NBObtainReadLock(&tdc->lock));
2113
2114         if (dcLocked && (tdc->index != NULLIDX)
2115             && !FidCmp(&tdc->f.fid, &avc->f.fid)
2116             && tdc->f.chunk == AFS_CHUNK(offset)
2117             && !(afs_indexFlags[tdc->index] & (IFFree | IFDiscarded))) {
2118             /* Bonus - the hint was correct */
2119             afs_RefDCache(tdc);
2120         } else {
2121             /* Only destroy the hint if its actually invalid, not if there's
2122              * just been a locking failure */
2123             if (dcLocked) {
2124                 ReleaseReadLock(&tdc->lock);
2125                 avc->dchint = NULL;
2126             }
2127
2128             tdc = NULL;
2129             dcLocked = 0;
2130         }
2131         ReleaseReadLock(&afs_xdcache);
2132     }
2133
2134     /* No hint, or hint is no longer valid - see if we can get something
2135      * directly from the dcache
2136      */
2137     if (!tdc)
2138         tdc = afs_FindDCache(avc, offset);
2139
2140     if (!tdc) {
2141         ReleaseWriteLock(&avc->lock);
2142         return 0;
2143     }
2144
2145     if (!dcLocked)
2146         ObtainReadLock(&tdc->lock);
2147
2148     /* Is the dcache we've been given currently up to date */
2149     if (!hsame(avc->f.m.DataVersion, tdc->f.versionNo) ||
2150         (tdc->dflags & DFFetching))
2151         goto out;
2152
2153     /* Update our hint for future abuse */
2154     avc->dchint = tdc;
2155
2156     /* Okay, so we've now got a cache file that is up to date */
2157
2158     /* XXX - I suspect we should be locking the inodes before we use them! */
2159     AFS_GUNLOCK();
2160     cacheFp = afs_linux_raw_open(&tdc->f.inode);
2161     if (!cacheFp->f_dentry->d_inode->i_mapping->a_ops->readpage) {
2162         cachefs_noreadpage = 1;
2163         AFS_GLOCK();
2164         goto out;
2165     }
2166     pagevec_init(&lrupv, 0);
2167
2168     code = afs_linux_read_cache(cacheFp, pp, tdc->f.chunk, &lrupv, NULL);
2169
2170     if (pagevec_count(&lrupv))
2171        __pagevec_lru_add_file(&lrupv);
2172
2173     filp_close(cacheFp, NULL);
2174     AFS_GLOCK();
2175
2176     ReleaseReadLock(&tdc->lock);
2177     ReleaseWriteLock(&avc->lock);
2178     afs_PutDCache(tdc);
2179
2180     *codep = code;
2181     return 1;
2182
2183 out:
2184     ReleaseWriteLock(&avc->lock);
2185     ReleaseReadLock(&tdc->lock);
2186     afs_PutDCache(tdc);
2187     return 0;
2188 }
2189
2190 /* afs_linux_readpage
2191  *
2192  * This function is split into two, because prepare_write/begin_write
2193  * require a readpage call which doesn't unlock the resulting page upon
2194  * success.
2195  */
2196 static int
2197 afs_linux_fillpage(struct file *fp, struct page *pp)
2198 {
2199     afs_int32 code;
2200     char *address;
2201     struct uio *auio;
2202     struct iovec *iovecp;
2203     struct inode *ip = FILE_INODE(fp);
2204     afs_int32 cnt = page_count(pp);
2205     struct vcache *avc = VTOAFS(ip);
2206     afs_offs_t offset = page_offset(pp);
2207     cred_t *credp;
2208
2209     AFS_GLOCK();
2210     if (afs_linux_readpage_fastpath(fp, pp, &code)) {
2211         AFS_GUNLOCK();
2212         return code;
2213     }
2214     AFS_GUNLOCK();
2215
2216     credp = crref();
2217     address = kmap(pp);
2218     ClearPageError(pp);
2219
2220     auio = kmalloc(sizeof(struct uio), GFP_NOFS);
2221     iovecp = kmalloc(sizeof(struct iovec), GFP_NOFS);
2222
2223     setup_uio(auio, iovecp, (char *)address, offset, PAGE_SIZE, UIO_READ,
2224               AFS_UIOSYS);
2225
2226     AFS_GLOCK();
2227     AFS_DISCON_LOCK();
2228     afs_Trace4(afs_iclSetp, CM_TRACE_READPAGE, ICL_TYPE_POINTER, ip,
2229                ICL_TYPE_POINTER, pp, ICL_TYPE_INT32, cnt, ICL_TYPE_INT32,
2230                99999);  /* not a possible code value */
2231
2232     code = afs_rdwr(avc, auio, UIO_READ, 0, credp);
2233         
2234     afs_Trace4(afs_iclSetp, CM_TRACE_READPAGE, ICL_TYPE_POINTER, ip,
2235                ICL_TYPE_POINTER, pp, ICL_TYPE_INT32, cnt, ICL_TYPE_INT32,
2236                code);
2237     AFS_DISCON_UNLOCK();
2238     AFS_GUNLOCK();
2239     if (!code) {
2240         /* XXX valid for no-cache also?  Check last bits of files... :)
2241          * Cognate code goes in afs_NoCacheFetchProc.  */
2242         if (auio->uio_resid)    /* zero remainder of page */
2243              memset((void *)(address + (PAGE_SIZE - auio->uio_resid)), 0,
2244                     auio->uio_resid);
2245
2246         flush_dcache_page(pp);
2247         SetPageUptodate(pp);
2248     } /* !code */
2249
2250     kunmap(pp);
2251
2252     kfree(auio);
2253     kfree(iovecp);
2254
2255     crfree(credp);
2256     return afs_convert_code(code);
2257 }
2258
2259 static int
2260 afs_linux_prefetch(struct file *fp, struct page *pp)
2261 {
2262     int code = 0;
2263     struct vcache *avc = VTOAFS(FILE_INODE(fp));
2264     afs_offs_t offset = page_offset(pp);
2265
2266     if (AFS_CHUNKOFFSET(offset) == 0) {
2267         struct dcache *tdc;
2268         struct vrequest *treq = NULL;
2269         cred_t *credp;
2270
2271         credp = crref();
2272         AFS_GLOCK();
2273         code = afs_CreateReq(&treq, credp);
2274         if (!code && !NBObtainWriteLock(&avc->lock, 534)) {
2275             tdc = afs_FindDCache(avc, offset);
2276             if (tdc) {
2277                 if (!(tdc->mflags & DFNextStarted))
2278                     afs_PrefetchChunk(avc, tdc, credp, treq);
2279                     afs_PutDCache(tdc);
2280             }
2281             ReleaseWriteLock(&avc->lock);
2282         }
2283         afs_DestroyReq(treq);
2284         AFS_GUNLOCK();
2285         crfree(credp);
2286     }
2287     return afs_convert_code(code);
2288
2289 }
2290
2291 static int
2292 afs_linux_bypass_readpages(struct file *fp, struct address_space *mapping,
2293                            struct list_head *page_list, unsigned num_pages)
2294 {
2295     afs_int32 page_ix;
2296     struct uio *auio;
2297     afs_offs_t offset;
2298     struct iovec* iovecp;
2299     struct nocache_read_request *ancr;
2300     struct page *pp;
2301     struct pagevec lrupv;
2302     afs_int32 code = 0;
2303
2304     cred_t *credp;
2305     struct inode *ip = FILE_INODE(fp);
2306     struct vcache *avc = VTOAFS(ip);
2307     afs_int32 base_index = 0;
2308     afs_int32 page_count = 0;
2309     afs_int32 isize;
2310
2311     /* background thread must free: iovecp, auio, ancr */
2312     iovecp = osi_Alloc(num_pages * sizeof(struct iovec));
2313
2314     auio = osi_Alloc(sizeof(struct uio));
2315     auio->uio_iov = iovecp;
2316     auio->uio_iovcnt = num_pages;
2317     auio->uio_flag = UIO_READ;
2318     auio->uio_seg = AFS_UIOSYS;
2319     auio->uio_resid = num_pages * PAGE_SIZE;
2320
2321     ancr = osi_Alloc(sizeof(struct nocache_read_request));
2322     ancr->auio = auio;
2323     ancr->offset = auio->uio_offset;
2324     ancr->length = auio->uio_resid;
2325
2326     pagevec_init(&lrupv, 0);
2327
2328     for(page_ix = 0; page_ix < num_pages; ++page_ix) {
2329
2330         if(list_empty(page_list))
2331             break;
2332
2333         pp = list_entry(page_list->prev, struct page, lru);
2334         /* If we allocate a page and don't remove it from page_list,
2335          * the page cache gets upset. */
2336         list_del(&pp->lru);
2337         isize = (i_size_read(fp->f_mapping->host) - 1) >> PAGE_CACHE_SHIFT;
2338         if(pp->index > isize) {
2339             if(PageLocked(pp))
2340                 unlock_page(pp);
2341             continue;
2342         }
2343
2344         if(page_ix == 0) {
2345             offset = page_offset(pp);
2346             ancr->offset = auio->uio_offset = offset;
2347             base_index = pp->index;
2348         }
2349         iovecp[page_ix].iov_len = PAGE_SIZE;
2350         code = add_to_page_cache(pp, mapping, pp->index, GFP_KERNEL);
2351         if(base_index != pp->index) {
2352             if(PageLocked(pp))
2353                  unlock_page(pp);
2354             page_cache_release(pp);
2355             iovecp[page_ix].iov_base = (void *) 0;
2356             base_index++;
2357             ancr->length -= PAGE_SIZE;
2358             continue;
2359         }
2360         base_index++;
2361         if(code) {
2362             if(PageLocked(pp))
2363                 unlock_page(pp);
2364             page_cache_release(pp);
2365             iovecp[page_ix].iov_base = (void *) 0;
2366         } else {
2367             page_count++;
2368             if(!PageLocked(pp)) {
2369                 lock_page(pp);
2370             }
2371
2372             /* increment page refcount--our original design assumed
2373              * that locking it would effectively pin it;  protect
2374              * ourselves from the possiblity that this assumption is
2375              * is faulty, at low cost (provided we do not fail to
2376              * do the corresponding decref on the other side) */
2377             get_page(pp);
2378
2379             /* save the page for background map */
2380             iovecp[page_ix].iov_base = (void*) pp;
2381
2382             /* and put it on the LRU cache */
2383             if (!pagevec_add(&lrupv, pp))
2384                 __pagevec_lru_add_file(&lrupv);
2385         }
2386     }
2387
2388     /* If there were useful pages in the page list, make sure all pages
2389      * are in the LRU cache, then schedule the read */
2390     if(page_count) {
2391         if (pagevec_count(&lrupv))
2392             __pagevec_lru_add_file(&lrupv);
2393         credp = crref();
2394         code = afs_ReadNoCache(avc, ancr, credp);
2395         crfree(credp);
2396     } else {
2397         /* If there is nothing for the background thread to handle,
2398          * it won't be freeing the things that we never gave it */
2399         osi_Free(iovecp, num_pages * sizeof(struct iovec));
2400         osi_Free(auio, sizeof(struct uio));
2401         osi_Free(ancr, sizeof(struct nocache_read_request));
2402     }
2403     /* we do not flush, release, or unmap pages--that will be
2404      * done for us by the background thread as each page comes in
2405      * from the fileserver */
2406     return afs_convert_code(code);
2407 }
2408
2409
2410 static int
2411 afs_linux_bypass_readpage(struct file *fp, struct page *pp)
2412 {
2413     cred_t *credp = NULL;
2414     struct uio *auio;
2415     struct iovec *iovecp;
2416     struct nocache_read_request *ancr;
2417     int code;
2418
2419     /*
2420      * Special case: if page is at or past end of file, just zero it and set
2421      * it as up to date.
2422      */
2423     if (page_offset(pp) >=  i_size_read(fp->f_mapping->host)) {
2424         zero_user_segment(pp, 0, PAGE_CACHE_SIZE);
2425         SetPageUptodate(pp);
2426         unlock_page(pp);
2427         return 0;
2428     }
2429
2430     ClearPageError(pp);
2431
2432     /* receiver frees */
2433     auio = osi_Alloc(sizeof(struct uio));
2434     iovecp = osi_Alloc(sizeof(struct iovec));
2435
2436     /* address can be NULL, because we overwrite it with 'pp', below */
2437     setup_uio(auio, iovecp, NULL, page_offset(pp),
2438               PAGE_SIZE, UIO_READ, AFS_UIOSYS);
2439
2440     /* save the page for background map */
2441     get_page(pp); /* see above */
2442     auio->uio_iov->iov_base = (void*) pp;
2443     /* the background thread will free this */
2444     ancr = osi_Alloc(sizeof(struct nocache_read_request));
2445     ancr->auio = auio;
2446     ancr->offset = page_offset(pp);
2447     ancr->length = PAGE_SIZE;
2448
2449     credp = crref();
2450     code = afs_ReadNoCache(VTOAFS(FILE_INODE(fp)), ancr, credp);
2451     crfree(credp);
2452
2453     return afs_convert_code(code);
2454 }
2455
2456 static inline int
2457 afs_linux_can_bypass(struct inode *ip) {
2458
2459     switch(cache_bypass_strategy) {
2460         case NEVER_BYPASS_CACHE:
2461             return 0;
2462         case ALWAYS_BYPASS_CACHE:
2463             return 1;
2464         case LARGE_FILES_BYPASS_CACHE:
2465             if (i_size_read(ip) > cache_bypass_threshold)
2466                 return 1;
2467         default:
2468             return 0;
2469      }
2470 }
2471
2472 /* Check if a file is permitted to bypass the cache by policy, and modify
2473  * the cache bypass state recorded for that file */
2474
2475 static inline int
2476 afs_linux_bypass_check(struct inode *ip) {
2477     cred_t* credp;
2478
2479     int bypass = afs_linux_can_bypass(ip);
2480
2481     credp = crref();
2482     trydo_cache_transition(VTOAFS(ip), credp, bypass);
2483     crfree(credp);
2484
2485     return bypass;
2486 }
2487
2488
2489 static int
2490 afs_linux_readpage(struct file *fp, struct page *pp)
2491 {
2492     int code;
2493
2494     if (afs_linux_bypass_check(FILE_INODE(fp))) {
2495         code = afs_linux_bypass_readpage(fp, pp);
2496     } else {
2497         code = afs_linux_fillpage(fp, pp);
2498         if (!code)
2499             code = afs_linux_prefetch(fp, pp);
2500         unlock_page(pp);
2501     }
2502
2503     return code;
2504 }
2505
2506 /* Readpages reads a number of pages for a particular file. We use
2507  * this to optimise the reading, by limiting the number of times upon which
2508  * we have to lookup, lock and open vcaches and dcaches
2509  */
2510
2511 static int
2512 afs_linux_readpages(struct file *fp, struct address_space *mapping,
2513                     struct list_head *page_list, unsigned int num_pages)
2514 {
2515     struct inode *inode = mapping->host;
2516     struct vcache *avc = VTOAFS(inode);
2517     struct dcache *tdc;
2518     struct file *cacheFp = NULL;
2519     int code;
2520     unsigned int page_idx;
2521     loff_t offset;
2522     struct pagevec lrupv;
2523     struct afs_pagecopy_task *task;
2524
2525     if (afs_linux_bypass_check(inode))
2526         return afs_linux_bypass_readpages(fp, mapping, page_list, num_pages);
2527
2528     if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
2529         return 0;
2530
2531     /* No readpage (ex: tmpfs) , skip */
2532     if (cachefs_noreadpage)
2533         return 0;
2534
2535     AFS_GLOCK();
2536     if ((code = afs_linux_VerifyVCache(avc, NULL))) {
2537         AFS_GUNLOCK();
2538         return code;
2539     }
2540
2541     ObtainWriteLock(&avc->lock, 912);
2542     AFS_GUNLOCK();
2543
2544     task = afs_pagecopy_init_task();
2545
2546     tdc = NULL;
2547     pagevec_init(&lrupv, 0);
2548     for (page_idx = 0; page_idx < num_pages; page_idx++) {
2549         struct page *page = list_entry(page_list->prev, struct page, lru);
2550         list_del(&page->lru);
2551         offset = page_offset(page);
2552
2553         if (tdc && tdc->f.chunk != AFS_CHUNK(offset)) {
2554             AFS_GLOCK();
2555             ReleaseReadLock(&tdc->lock);
2556             afs_PutDCache(tdc);
2557             AFS_GUNLOCK();
2558             tdc = NULL;
2559             if (cacheFp)
2560                 filp_close(cacheFp, NULL);
2561         }
2562
2563         if (!tdc) {
2564             AFS_GLOCK();
2565             if ((tdc = afs_FindDCache(avc, offset))) {
2566                 ObtainReadLock(&tdc->lock);
2567                 if (!hsame(avc->f.m.DataVersion, tdc->f.versionNo) ||
2568                     (tdc->dflags & DFFetching)) {
2569                     ReleaseReadLock(&tdc->lock);
2570                     afs_PutDCache(tdc);
2571                     tdc = NULL;
2572                 }
2573             }
2574             AFS_GUNLOCK();
2575             if (tdc) {
2576                 cacheFp = afs_linux_raw_open(&tdc->f.inode);
2577                 if (!cacheFp->f_dentry->d_inode->i_mapping->a_ops->readpage) {
2578                     cachefs_noreadpage = 1;
2579                     goto out;
2580                 }
2581             }
2582         }
2583
2584         if (tdc && !add_to_page_cache(page, mapping, page->index,
2585                                       GFP_KERNEL)) {
2586             page_cache_get(page);
2587             if (!pagevec_add(&lrupv, page))
2588                 __pagevec_lru_add_file(&lrupv);
2589
2590             afs_linux_read_cache(cacheFp, page, tdc->f.chunk, &lrupv, task);
2591         }
2592         page_cache_release(page);
2593     }
2594     if (pagevec_count(&lrupv))
2595        __pagevec_lru_add_file(&lrupv);
2596
2597 out:
2598     if (tdc)
2599         filp_close(cacheFp, NULL);
2600
2601     afs_pagecopy_put_task(task);
2602
2603     AFS_GLOCK();
2604     if (tdc) {
2605         ReleaseReadLock(&tdc->lock);
2606         afs_PutDCache(tdc);
2607     }
2608
2609     ReleaseWriteLock(&avc->lock);
2610     AFS_GUNLOCK();
2611     return 0;
2612 }
2613
2614 /* Prepare an AFS vcache for writeback. Should be called with the vcache
2615  * locked */
2616 static inline int
2617 afs_linux_prepare_writeback(struct vcache *avc) {
2618     pid_t pid;
2619     struct pagewriter *pw;
2620
2621     pid = MyPidxx2Pid(MyPidxx);
2622     /* Prevent recursion into the writeback code */
2623     spin_lock(&avc->pagewriter_lock);
2624     list_for_each_entry(pw, &avc->pagewriters, link) {
2625         if (pw->writer == pid) {
2626             spin_unlock(&avc->pagewriter_lock);
2627             return AOP_WRITEPAGE_ACTIVATE;
2628         }
2629     }
2630     spin_unlock(&avc->pagewriter_lock);
2631
2632     /* Add ourselves to writer list */
2633     pw = osi_Alloc(sizeof(struct pagewriter));
2634     pw->writer = pid;
2635     spin_lock(&avc->pagewriter_lock);
2636     list_add_tail(&pw->link, &avc->pagewriters);
2637     spin_unlock(&avc->pagewriter_lock);
2638
2639     return 0;
2640 }
2641
2642 static inline int
2643 afs_linux_dopartialwrite(struct vcache *avc, cred_t *credp) {
2644     struct vrequest *treq = NULL;
2645     int code = 0;
2646
2647     if (!afs_CreateReq(&treq, credp)) {
2648         code = afs_DoPartialWrite(avc, treq);
2649         afs_DestroyReq(treq);
2650     }
2651
2652     return afs_convert_code(code);
2653 }
2654
2655 static inline void
2656 afs_linux_complete_writeback(struct vcache *avc) {
2657     struct pagewriter *pw, *store;
2658     pid_t pid;
2659     struct list_head tofree;
2660
2661     INIT_LIST_HEAD(&tofree);
2662     pid = MyPidxx2Pid(MyPidxx);
2663     /* Remove ourselves from writer list */
2664     spin_lock(&avc->pagewriter_lock);
2665     list_for_each_entry_safe(pw, store, &avc->pagewriters, link) {
2666         if (pw->writer == pid) {
2667             list_del(&pw->link);
2668             /* osi_Free may sleep so we need to defer it */
2669             list_add_tail(&pw->link, &tofree);
2670         }
2671     }
2672     spin_unlock(&avc->pagewriter_lock);
2673     list_for_each_entry_safe(pw, store, &tofree, link) {
2674         list_del(&pw->link);
2675         osi_Free(pw, sizeof(struct pagewriter));
2676     }
2677 }
2678
2679 /* Writeback a given page syncronously. Called with no AFS locks held */
2680 static int
2681 afs_linux_page_writeback(struct inode *ip, struct page *pp,
2682                          unsigned long offset, unsigned int count,
2683                          cred_t *credp)
2684 {
2685     struct vcache *vcp = VTOAFS(ip);
2686     char *buffer;
2687     afs_offs_t base;
2688     int code = 0;
2689     struct uio tuio;
2690     struct iovec iovec;
2691     int f_flags = 0;
2692
2693     memset(&tuio, 0, sizeof(tuio));
2694     memset(&iovec, 0, sizeof(iovec));
2695
2696     buffer = kmap(pp) + offset;
2697     base = page_offset(pp) + offset;
2698
2699     AFS_GLOCK();
2700     afs_Trace4(afs_iclSetp, CM_TRACE_UPDATEPAGE, ICL_TYPE_POINTER, vcp,
2701                ICL_TYPE_POINTER, pp, ICL_TYPE_INT32, page_count(pp),
2702                ICL_TYPE_INT32, 99999);
2703
2704     setup_uio(&tuio, &iovec, buffer, base, count, UIO_WRITE, AFS_UIOSYS);
2705
2706     code = afs_write(vcp, &tuio, f_flags, credp, 0);
2707
2708     i_size_write(ip, vcp->f.m.Length);
2709     ip->i_blocks = ((vcp->f.m.Length + 1023) >> 10) << 1;
2710
2711     code = code ? afs_convert_code(code) : count - tuio.uio_resid;
2712
2713     afs_Trace4(afs_iclSetp, CM_TRACE_UPDATEPAGE, ICL_TYPE_POINTER, vcp,
2714                ICL_TYPE_POINTER, pp, ICL_TYPE_INT32, page_count(pp),
2715                ICL_TYPE_INT32, code);
2716
2717     AFS_GUNLOCK();
2718     kunmap(pp);
2719
2720     return code;
2721 }
2722
2723 static int
2724 afs_linux_writepage_sync(struct inode *ip, struct page *pp,
2725                          unsigned long offset, unsigned int count)
2726 {
2727     int code;
2728     int code1 = 0;
2729     struct vcache *vcp = VTOAFS(ip);
2730     cred_t *credp;
2731
2732     /* Catch recursive writeback. This occurs if the kernel decides
2733      * writeback is required whilst we are writing to the cache, or
2734      * flushing to the server. When we're running syncronously (as
2735      * opposed to from writepage) we can't actually do anything about
2736      * this case - as we can't return AOP_WRITEPAGE_ACTIVATE to write()
2737      */
2738     AFS_GLOCK();
2739     ObtainWriteLock(&vcp->lock, 532);
2740     afs_linux_prepare_writeback(vcp);
2741     ReleaseWriteLock(&vcp->lock);
2742     AFS_GUNLOCK();
2743
2744     credp = crref();
2745     code = afs_linux_page_writeback(ip, pp, offset, count, credp);
2746
2747     AFS_GLOCK();
2748     ObtainWriteLock(&vcp->lock, 533);
2749     if (code > 0)
2750         code1 = afs_linux_dopartialwrite(vcp, credp);
2751     afs_linux_complete_writeback(vcp);
2752     ReleaseWriteLock(&vcp->lock);
2753     AFS_GUNLOCK();
2754     crfree(credp);
2755
2756     if (code1)
2757         return code1;
2758
2759     return code;
2760 }
2761
2762 static int
2763 #ifdef AOP_WRITEPAGE_TAKES_WRITEBACK_CONTROL
2764 afs_linux_writepage(struct page *pp, struct writeback_control *wbc)
2765 #else
2766 afs_linux_writepage(struct page *pp)
2767 #endif
2768 {
2769     struct address_space *mapping = pp->mapping;
2770     struct inode *inode;
2771     struct vcache *vcp;
2772     cred_t *credp;
2773     unsigned int to = PAGE_CACHE_SIZE;
2774     loff_t isize;
2775     int code = 0;
2776     int code1 = 0;
2777
2778     page_cache_get(pp);
2779
2780     inode = mapping->host;
2781     vcp = VTOAFS(inode);
2782     isize = i_size_read(inode);
2783
2784     /* Don't defeat an earlier truncate */
2785     if (page_offset(pp) > isize) {
2786         set_page_writeback(pp);
2787         unlock_page(pp);
2788         goto done;
2789     }
2790
2791     AFS_GLOCK();
2792     ObtainWriteLock(&vcp->lock, 537);
2793     code = afs_linux_prepare_writeback(vcp);
2794     if (code == AOP_WRITEPAGE_ACTIVATE) {
2795         /* WRITEPAGE_ACTIVATE is the only return value that permits us
2796          * to return with the page still locked */
2797         ReleaseWriteLock(&vcp->lock);
2798         AFS_GUNLOCK();
2799         return code;
2800     }
2801
2802     /* Grab the creds structure currently held in the vnode, and
2803      * get a reference to it, in case it goes away ... */
2804     credp = vcp->cred;
2805     if (credp)
2806         crhold(credp);
2807     else
2808         credp = crref();
2809     ReleaseWriteLock(&vcp->lock);
2810     AFS_GUNLOCK();
2811
2812     set_page_writeback(pp);
2813
2814     SetPageUptodate(pp);
2815
2816     /* We can unlock the page here, because it's protected by the
2817      * page_writeback flag. This should make us less vulnerable to
2818      * deadlocking in afs_write and afs_DoPartialWrite
2819      */
2820     unlock_page(pp);
2821
2822     /* If this is the final page, then just write the number of bytes that
2823      * are actually in it */
2824     if ((isize - page_offset(pp)) < to )
2825         to = isize - page_offset(pp);
2826
2827     code = afs_linux_page_writeback(inode, pp, 0, to, credp);
2828
2829     AFS_GLOCK();
2830     ObtainWriteLock(&vcp->lock, 538);
2831
2832     /* As much as we might like to ignore a file server error here,
2833      * and just try again when we close(), unfortunately StoreAllSegments
2834      * will invalidate our chunks if the server returns a permanent error,
2835      * so we need to at least try and get that error back to the user
2836      */
2837     if (code == to)
2838         code1 = afs_linux_dopartialwrite(vcp, credp);
2839
2840     afs_linux_complete_writeback(vcp);
2841     ReleaseWriteLock(&vcp->lock);
2842     crfree(credp);
2843     AFS_GUNLOCK();
2844
2845 done:
2846     end_page_writeback(pp);
2847     page_cache_release(pp);
2848
2849     if (code1)
2850         return code1;
2851
2852     if (code == to)
2853         return 0;
2854
2855     return code;
2856 }
2857
2858 /* afs_linux_permission
2859  * Check access rights - returns error if can't check or permission denied.
2860  */
2861 static int
2862 #if defined(IOP_PERMISSION_TAKES_FLAGS)
2863 afs_linux_permission(struct inode *ip, int mode, unsigned int flags)
2864 #elif defined(IOP_PERMISSION_TAKES_NAMEIDATA)
2865 afs_linux_permission(struct inode *ip, int mode, struct nameidata *nd)
2866 #else
2867 afs_linux_permission(struct inode *ip, int mode)
2868 #endif
2869 {
2870     int code;
2871     cred_t *credp;
2872     int tmp = 0;
2873
2874     /* Check for RCU path walking */
2875 #if defined(IOP_PERMISSION_TAKES_FLAGS)
2876     if (flags & IPERM_FLAG_RCU)
2877        return -ECHILD;
2878 #elif defined(MAY_NOT_BLOCK)
2879     if (mode & MAY_NOT_BLOCK)
2880        return -ECHILD;
2881 #endif
2882
2883     credp = crref();
2884     AFS_GLOCK();
2885     if (mode & MAY_EXEC)
2886         tmp |= VEXEC;
2887     if (mode & MAY_READ)
2888         tmp |= VREAD;
2889     if (mode & MAY_WRITE)
2890         tmp |= VWRITE;
2891     code = afs_access(VTOAFS(ip), tmp, credp);
2892
2893     AFS_GUNLOCK();
2894     crfree(credp);
2895     return afs_convert_code(code);
2896 }
2897
2898 static int
2899 afs_linux_commit_write(struct file *file, struct page *page, unsigned offset,
2900                        unsigned to)
2901 {
2902     int code;
2903     struct inode *inode = FILE_INODE(file);
2904     loff_t pagebase = page_offset(page);
2905
2906     if (i_size_read(inode) < (pagebase + offset))
2907         i_size_write(inode, pagebase + offset);
2908
2909     if (PageChecked(page)) {
2910         SetPageUptodate(page);
2911         ClearPageChecked(page);
2912     }
2913
2914     code = afs_linux_writepage_sync(inode, page, offset, to - offset);
2915
2916     return code;
2917 }
2918
2919 static int
2920 afs_linux_prepare_write(struct file *file, struct page *page, unsigned from,
2921                         unsigned to)
2922 {
2923
2924     /* http://kerneltrap.org/node/4941 details the expected behaviour of
2925      * prepare_write. Essentially, if the page exists within the file,
2926      * and is not being fully written, then we should populate it.
2927      */
2928
2929     if (!PageUptodate(page)) {
2930         loff_t pagebase = page_offset(page);
2931         loff_t isize = i_size_read(page->mapping->host);
2932
2933         /* Is the location we are writing to beyond the end of the file? */
2934         if (pagebase >= isize ||
2935             ((from == 0) && (pagebase + to) >= isize)) {
2936             zero_user_segments(page, 0, from, to, PAGE_CACHE_SIZE);
2937             SetPageChecked(page);
2938         /* Are we we writing a full page */
2939         } else if (from == 0 && to == PAGE_CACHE_SIZE) {
2940             SetPageChecked(page);
2941         /* Is the page readable, if it's wronly, we don't care, because we're
2942          * not actually going to read from it ... */
2943         } else if ((file->f_flags && O_ACCMODE) != O_WRONLY) {
2944             /* We don't care if fillpage fails, because if it does the page
2945              * won't be marked as up to date
2946              */
2947             afs_linux_fillpage(file, page);
2948         }
2949     }
2950     return 0;
2951 }
2952
2953 #if defined(STRUCT_ADDRESS_SPACE_OPERATIONS_HAS_WRITE_BEGIN)
2954 static int
2955 afs_linux_write_end(struct file *file, struct address_space *mapping,
2956                                 loff_t pos, unsigned len, unsigned copied,
2957                                 struct page *page, void *fsdata)
2958 {
2959     int code;
2960     unsigned int from = pos & (PAGE_CACHE_SIZE - 1);
2961
2962     code = afs_linux_commit_write(file, page, from, from + len);
2963
2964     unlock_page(page);
2965     page_cache_release(page);
2966     return code;
2967 }
2968
2969 static int
2970 afs_linux_write_begin(struct file *file, struct address_space *mapping,
2971                                 loff_t pos, unsigned len, unsigned flags,
2972                                 struct page **pagep, void **fsdata)
2973 {
2974     struct page *page;
2975     pgoff_t index = pos >> PAGE_CACHE_SHIFT;
2976     unsigned int from = pos & (PAGE_CACHE_SIZE - 1);
2977     int code;
2978
2979     page = grab_cache_page_write_begin(mapping, index, flags);
2980     *pagep = page;
2981
2982     code = afs_linux_prepare_write(file, page, from, from + len);
2983     if (code) {
2984         unlock_page(page);
2985         page_cache_release(page);
2986     }
2987
2988     return code;
2989 }
2990 #endif
2991
2992 #ifndef STRUCT_DENTRY_OPERATIONS_HAS_D_AUTOMOUNT
2993 static void *
2994 afs_linux_dir_follow_link(struct dentry *dentry, struct nameidata *nd)
2995 {
2996     struct dentry **dpp;
2997     struct dentry *target;
2998
2999     if (current->total_link_count > 0) {
3000         /* avoid symlink resolution limits when resolving; we cannot contribute to
3001          * an infinite symlink loop */
3002         /* only do this for follow_link when total_link_count is positive to be
3003          * on the safe side; there is at least one code path in the Linux
3004          * kernel where it seems like it may be possible to get here without
3005          * total_link_count getting incremented. it is not clear on how that
3006          * path is actually reached, but guard against it just to be safe */
3007         current->total_link_count--;
3008     }
3009
3010     target = canonical_dentry(dentry->d_inode);
3011
3012 # ifdef STRUCT_NAMEIDATA_HAS_PATH
3013     dpp = &nd->path.dentry;
3014 # else
3015     dpp = &nd->dentry;
3016 # endif
3017
3018     dput(*dpp);
3019
3020     if (target) {
3021         *dpp = target;
3022     } else {
3023         *dpp = dget(dentry);
3024     }
3025
3026     nd->last_type = LAST_BIND;
3027
3028     return NULL;
3029 }
3030 #endif /* !STRUCT_DENTRY_OPERATIONS_HAS_D_AUTOMOUNT */
3031
3032
3033 static struct inode_operations afs_file_iops = {
3034   .permission =         afs_linux_permission,
3035   .getattr =            afs_linux_getattr,
3036   .setattr =            afs_notify_change,
3037 };
3038
3039 static struct address_space_operations afs_file_aops = {
3040   .readpage =           afs_linux_readpage,
3041   .readpages =          afs_linux_readpages,
3042   .writepage =          afs_linux_writepage,
3043 #if defined (STRUCT_ADDRESS_SPACE_OPERATIONS_HAS_WRITE_BEGIN)
3044   .write_begin =        afs_linux_write_begin,
3045   .write_end =          afs_linux_write_end,
3046 #else
3047   .commit_write =       afs_linux_commit_write,
3048   .prepare_write =      afs_linux_prepare_write,
3049 #endif
3050 };
3051
3052
3053 /* Separate ops vector for directories. Linux 2.2 tests type of inode
3054  * by what sort of operation is allowed.....
3055  */
3056
3057 static struct inode_operations afs_dir_iops = {
3058   .setattr =            afs_notify_change,
3059   .create =             afs_linux_create,
3060   .lookup =             afs_linux_lookup,
3061   .link =               afs_linux_link,
3062   .unlink =             afs_linux_unlink,
3063   .symlink =            afs_linux_symlink,
3064   .mkdir =              afs_linux_mkdir,
3065   .rmdir =              afs_linux_rmdir,
3066   .rename =             afs_linux_rename,
3067   .getattr =            afs_linux_getattr,
3068   .permission =         afs_linux_permission,
3069 #ifndef STRUCT_DENTRY_OPERATIONS_HAS_D_AUTOMOUNT
3070   .follow_link =        afs_linux_dir_follow_link,
3071 #endif
3072 };
3073
3074 /* We really need a separate symlink set of ops, since do_follow_link()
3075  * determines if it _is_ a link by checking if the follow_link op is set.
3076  */
3077 #if defined(USABLE_KERNEL_PAGE_SYMLINK_CACHE)
3078 static int
3079 afs_symlink_filler(struct file *file, struct page *page)
3080 {
3081     struct inode *ip = (struct inode *)page->mapping->host;
3082     char *p = (char *)kmap(page);
3083     int code;
3084
3085     AFS_GLOCK();
3086     code = afs_linux_ireadlink(ip, p, PAGE_SIZE, AFS_UIOSYS);
3087     AFS_GUNLOCK();
3088
3089     if (code < 0)
3090         goto fail;
3091     p[code] = '\0';             /* null terminate? */
3092
3093     SetPageUptodate(page);
3094     kunmap(page);
3095     unlock_page(page);
3096     return 0;
3097
3098   fail:
3099     SetPageError(page);
3100     kunmap(page);
3101     unlock_page(page);
3102     return code;
3103 }
3104
3105 static struct address_space_operations afs_symlink_aops = {
3106   .readpage =   afs_symlink_filler
3107 };
3108 #endif  /* USABLE_KERNEL_PAGE_SYMLINK_CACHE */
3109
3110 static struct inode_operations afs_symlink_iops = {
3111 #if defined(USABLE_KERNEL_PAGE_SYMLINK_CACHE)
3112   .readlink =           page_readlink,
3113 # if defined(HAVE_LINUX_PAGE_FOLLOW_LINK)
3114   .follow_link =        page_follow_link,
3115 # else
3116   .follow_link =        page_follow_link_light,
3117   .put_link =           page_put_link,
3118 # endif
3119 #else /* !defined(USABLE_KERNEL_PAGE_SYMLINK_CACHE) */
3120   .readlink =           afs_linux_readlink,
3121   .follow_link =        afs_linux_follow_link,
3122   .put_link =           afs_linux_put_link,
3123 #endif /* USABLE_KERNEL_PAGE_SYMLINK_CACHE */
3124   .setattr =            afs_notify_change,
3125 };
3126
3127 void
3128 afs_fill_inode(struct inode *ip, struct vattr *vattr)
3129 {
3130         
3131     if (vattr)
3132         vattr2inode(ip, vattr);
3133
3134 #ifdef STRUCT_ADDRESS_SPACE_HAS_BACKING_DEV_INFO
3135     ip->i_mapping->backing_dev_info = afs_backing_dev_info;
3136 #endif
3137 /* Reset ops if symlink or directory. */
3138     if (S_ISREG(ip->i_mode)) {
3139         ip->i_op = &afs_file_iops;
3140         ip->i_fop = &afs_file_fops;
3141         ip->i_data.a_ops = &afs_file_aops;
3142
3143     } else if (S_ISDIR(ip->i_mode)) {
3144         ip->i_op = &afs_dir_iops;
3145         ip->i_fop = &afs_dir_fops;
3146
3147     } else if (S_ISLNK(ip->i_mode)) {
3148         ip->i_op = &afs_symlink_iops;
3149 #if defined(USABLE_KERNEL_PAGE_SYMLINK_CACHE)
3150         ip->i_data.a_ops = &afs_symlink_aops;
3151         ip->i_mapping = &ip->i_data;
3152 #endif
3153     }
3154
3155 }