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