Linux: Remove the BKL
[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/smp_lock.h>
34 #include <linux/writeback.h>
35 #include <linux/pagevec.h>
36 #if defined(AFS_CACHE_BYPASS)
37 #include "afs/lock.h"
38 #include "afs/afs_bypasscache.h"
39 #endif
40
41 #include "osi_compat.h"
42 #include "osi_pagecopy.h"
43
44 #ifndef HAVE_LINUX_PAGEVEC_LRU_ADD_FILE
45 #define __pagevec_lru_add_file __pagevec_lru_add
46 #endif
47
48 #ifndef MAX_ERRNO
49 #define MAX_ERRNO 1000L
50 #endif
51
52 extern struct backing_dev_info *afs_backing_dev_info;
53
54 extern struct vcache *afs_globalVp;
55 extern int afs_notify_change(struct dentry *dp, struct iattr *iattrp);
56
57 /* This function converts a positive error code from AFS into a negative
58  * code suitable for passing into the Linux VFS layer. It checks that the
59  * error code is within the permissable bounds for the ERR_PTR mechanism.
60  *
61  * _All_ error codes which come from the AFS layer should be passed through
62  * this function before being returned to the kernel.
63  */
64
65 static inline int
66 afs_convert_code(int code) {
67     if ((code >= 0) && (code <= MAX_ERRNO))
68         return -code;
69     else
70         return -EIO;
71 }
72
73 /* Linux doesn't require a credp for many functions, and crref is an expensive
74  * operation. This helper function avoids obtaining it for VerifyVCache calls
75  */
76
77 static inline int
78 afs_linux_VerifyVCache(struct vcache *avc, cred_t **retcred) {
79     cred_t *credp = NULL;
80     struct vrequest treq;
81     int code;
82
83     if (avc->f.states & CStatd) {
84         if (retcred)
85             *retcred = NULL;
86         return 0;
87     }
88
89     credp = crref();
90
91     code = afs_InitReq(&treq, credp);
92     if (code == 0)
93         code = afs_VerifyVCache2(avc, &treq);
94
95     if (retcred != NULL)
96         *retcred = credp;
97     else
98         crfree(credp);
99
100     return afs_convert_code(code);
101 }
102
103 static ssize_t
104 afs_linux_read(struct file *fp, char *buf, size_t count, loff_t * offp)
105 {
106     ssize_t code = 0;
107     struct vcache *vcp = VTOAFS(fp->f_dentry->d_inode);
108
109     AFS_GLOCK();
110     afs_Trace4(afs_iclSetp, CM_TRACE_READOP, ICL_TYPE_POINTER, vcp,
111                ICL_TYPE_OFFSET, offp, ICL_TYPE_INT32, count, ICL_TYPE_INT32,
112                99999);
113     code = afs_linux_VerifyVCache(vcp, NULL);
114
115     if (code == 0) {
116         /* Linux's FlushPages implementation doesn't ever use credp,
117          * so we optimise by not using it */
118         osi_FlushPages(vcp, NULL);      /* ensure stale pages are gone */
119         AFS_GUNLOCK();
120         code = do_sync_read(fp, buf, count, offp);
121         AFS_GLOCK();
122     }
123
124     afs_Trace4(afs_iclSetp, CM_TRACE_READOP, ICL_TYPE_POINTER, vcp,
125                ICL_TYPE_OFFSET, offp, ICL_TYPE_INT32, count, ICL_TYPE_INT32,
126                code);
127     AFS_GUNLOCK();
128     return code;
129 }
130
131
132 /* Now we have integrated VM for writes as well as reads. generic_file_write
133  * also takes care of re-positioning the pointer if file is open in append
134  * mode. Call fake open/close to ensure we do writes of core dumps.
135  */
136 static ssize_t
137 afs_linux_write(struct file *fp, const char *buf, size_t count, loff_t * offp)
138 {
139     ssize_t code = 0;
140     struct vcache *vcp = VTOAFS(fp->f_dentry->d_inode);
141     cred_t *credp;
142
143     AFS_GLOCK();
144
145     afs_Trace4(afs_iclSetp, CM_TRACE_WRITEOP, ICL_TYPE_POINTER, vcp,
146                ICL_TYPE_OFFSET, offp, ICL_TYPE_INT32, count, ICL_TYPE_INT32,
147                (fp->f_flags & O_APPEND) ? 99998 : 99999);
148
149     code = afs_linux_VerifyVCache(vcp, &credp);
150
151     ObtainWriteLock(&vcp->lock, 529);
152     afs_FakeOpen(vcp);
153     ReleaseWriteLock(&vcp->lock);
154     if (code == 0) {
155             AFS_GUNLOCK();
156             code = do_sync_write(fp, buf, count, offp);
157             AFS_GLOCK();
158     }
159
160     ObtainWriteLock(&vcp->lock, 530);
161
162     if (vcp->execsOrWriters == 1 && !credp)
163       credp = crref();
164
165     afs_FakeClose(vcp, credp);
166     ReleaseWriteLock(&vcp->lock);
167
168     afs_Trace4(afs_iclSetp, CM_TRACE_WRITEOP, ICL_TYPE_POINTER, vcp,
169                ICL_TYPE_OFFSET, offp, ICL_TYPE_INT32, count, ICL_TYPE_INT32,
170                code);
171
172     if (credp)
173       crfree(credp);
174     AFS_GUNLOCK();
175     return code;
176 }
177
178 extern int BlobScan(struct dcache * afile, afs_int32 ablob);
179
180 /* This is a complete rewrite of afs_readdir, since we can make use of
181  * filldir instead of afs_readdir_move. Note that changes to vcache/dcache
182  * handling and use of bulkstats will need to be reflected here as well.
183  */
184 static int
185 afs_linux_readdir(struct file *fp, void *dirbuf, filldir_t filldir)
186 {
187     struct vcache *avc = VTOAFS(FILE_INODE(fp));
188     struct vrequest treq;
189     register struct dcache *tdc;
190     int code;
191     int offset;
192     int dirpos;
193     struct DirEntry *de;
194     ino_t ino;
195     int len;
196     afs_size_t origOffset, tlen;
197     cred_t *credp = crref();
198     struct afs_fakestat_state fakestat;
199
200     AFS_GLOCK();
201     AFS_STATCNT(afs_readdir);
202
203     code = afs_convert_code(afs_InitReq(&treq, credp));
204     crfree(credp);
205     if (code)
206         goto out1;
207
208     afs_InitFakeStat(&fakestat);
209     code = afs_convert_code(afs_EvalFakeStat(&avc, &fakestat, &treq));
210     if (code)
211         goto out;
212
213     /* update the cache entry */
214   tagain:
215     code = afs_convert_code(afs_VerifyVCache2(avc, &treq));
216     if (code)
217         goto out;
218
219     /* get a reference to the entire directory */
220     tdc = afs_GetDCache(avc, (afs_size_t) 0, &treq, &origOffset, &tlen, 1);
221     len = tlen;
222     if (!tdc) {
223         code = -ENOENT;
224         goto out;
225     }
226     ObtainSharedLock(&avc->lock, 810);
227     UpgradeSToWLock(&avc->lock, 811);
228     ObtainReadLock(&tdc->lock);
229     /*
230      * Make sure that the data in the cache is current. There are two
231      * cases we need to worry about:
232      * 1. The cache data is being fetched by another process.
233      * 2. The cache data is no longer valid
234      */
235     while ((avc->f.states & CStatd)
236            && (tdc->dflags & DFFetching)
237            && hsame(avc->f.m.DataVersion, tdc->f.versionNo)) {
238         ReleaseReadLock(&tdc->lock);
239         ReleaseSharedLock(&avc->lock);
240         afs_osi_Sleep(&tdc->validPos);
241         ObtainSharedLock(&avc->lock, 812);
242         ObtainReadLock(&tdc->lock);
243     }
244     if (!(avc->f.states & CStatd)
245         || !hsame(avc->f.m.DataVersion, tdc->f.versionNo)) {
246         ReleaseReadLock(&tdc->lock);
247         ReleaseSharedLock(&avc->lock);
248         afs_PutDCache(tdc);
249         goto tagain;
250     }
251
252     /* Set the readdir-in-progress flag, and downgrade the lock
253      * to shared so others will be able to acquire a read lock.
254      */
255     avc->f.states |= CReadDir;
256     avc->dcreaddir = tdc;
257     avc->readdir_pid = MyPidxx2Pid(MyPidxx);
258     ConvertWToSLock(&avc->lock);
259
260     /* Fill in until we get an error or we're done. This implementation
261      * takes an offset in units of blobs, rather than bytes.
262      */
263     code = 0;
264     offset = (int) fp->f_pos;
265     while (1) {
266         dirpos = BlobScan(tdc, offset);
267         if (!dirpos)
268             break;
269
270         de = afs_dir_GetBlob(tdc, dirpos);
271         if (!de)
272             break;
273
274         ino = afs_calc_inum (avc->f.fid.Fid.Volume, ntohl(de->fid.vnode));
275
276         if (de->name)
277             len = strlen(de->name);
278         else {
279             printf("afs_linux_readdir: afs_dir_GetBlob failed, null name (inode %lx, dirpos %d)\n", 
280                    (unsigned long)&tdc->f.inode, dirpos);
281             DRelease(de, 0);
282             ReleaseSharedLock(&avc->lock);
283             afs_PutDCache(tdc);
284             code = -ENOENT;
285             goto out;
286         }
287
288         /* filldir returns -EINVAL when the buffer is full. */
289         {
290             unsigned int type = DT_UNKNOWN;
291             struct VenusFid afid;
292             struct vcache *tvc;
293             int vtype;
294             afid.Cell = avc->f.fid.Cell;
295             afid.Fid.Volume = avc->f.fid.Fid.Volume;
296             afid.Fid.Vnode = ntohl(de->fid.vnode);
297             afid.Fid.Unique = ntohl(de->fid.vunique);
298             if ((avc->f.states & CForeign) == 0 && (ntohl(de->fid.vnode) & 1)) {
299                 type = DT_DIR;
300             } else if ((tvc = afs_FindVCache(&afid, 0, 0))) {
301                 if (tvc->mvstat) {
302                     type = DT_DIR;
303                 } else if (((tvc->f.states) & (CStatd | CTruth))) {
304                     /* CTruth will be set if the object has
305                      *ever* been statd */
306                     vtype = vType(tvc);
307                     if (vtype == VDIR)
308                         type = DT_DIR;
309                     else if (vtype == VREG)
310                         type = DT_REG;
311                     /* Don't do this until we're sure it can't be a mtpt */
312                     /* else if (vtype == VLNK)
313                      * type=DT_LNK; */
314                     /* what other types does AFS support? */
315                 }
316                 /* clean up from afs_FindVCache */
317                 afs_PutVCache(tvc);
318             }
319             /* 
320              * If this is NFS readdirplus, then the filler is going to
321              * call getattr on this inode, which will deadlock if we're
322              * holding the GLOCK.
323              */
324             AFS_GUNLOCK();
325             code = (*filldir) (dirbuf, de->name, len, offset, ino, type);
326             AFS_GLOCK();
327         }
328         DRelease(de, 0);
329         if (code)
330             break;
331         offset = dirpos + 1 + ((len + 16) >> 5);
332     }
333     /* If filldir didn't fill in the last one this is still pointing to that
334      * last attempt.
335      */
336     fp->f_pos = (loff_t) offset;
337
338     ReleaseReadLock(&tdc->lock);
339     afs_PutDCache(tdc);
340     UpgradeSToWLock(&avc->lock, 813);
341     avc->f.states &= ~CReadDir;
342     avc->dcreaddir = 0;
343     avc->readdir_pid = 0;
344     ReleaseSharedLock(&avc->lock);
345     code = 0;
346
347 out:
348     afs_PutFakeStat(&fakestat);
349 out1:
350     AFS_GUNLOCK();
351     return code;
352 }
353
354
355 /* in afs_pioctl.c */
356 extern int afs_xioctl(struct inode *ip, struct file *fp, unsigned int com,
357                       unsigned long arg);
358
359 #if defined(HAVE_UNLOCKED_IOCTL) || defined(HAVE_COMPAT_IOCTL)
360 static long afs_unlocked_xioctl(struct file *fp, unsigned int com,
361                                unsigned long arg) {
362     return afs_xioctl(FILE_INODE(fp), fp, com, arg);
363
364 }
365 #endif
366
367
368 static int
369 afs_linux_mmap(struct file *fp, struct vm_area_struct *vmap)
370 {
371     struct vcache *vcp = VTOAFS(FILE_INODE(fp));
372     int code;
373
374     AFS_GLOCK();
375     afs_Trace3(afs_iclSetp, CM_TRACE_GMAP, ICL_TYPE_POINTER, vcp,
376                ICL_TYPE_POINTER, vmap->vm_start, ICL_TYPE_INT32,
377                vmap->vm_end - vmap->vm_start);
378
379     /* get a validated vcache entry */
380     code = afs_linux_VerifyVCache(vcp, NULL);
381
382     /* Linux's Flushpage implementation doesn't use credp, so optimise
383      * our code to not need to crref() it */
384     osi_FlushPages(vcp, NULL); /* ensure stale pages are gone */
385     AFS_GUNLOCK();
386     code = generic_file_mmap(fp, vmap);
387     AFS_GLOCK();
388     if (!code)
389         vcp->f.states |= CMAPPED;
390
391     AFS_GUNLOCK();
392     return code;
393 }
394
395 static int
396 afs_linux_open(struct inode *ip, struct file *fp)
397 {
398     struct vcache *vcp = VTOAFS(ip);
399     cred_t *credp = crref();
400     int code;
401
402     AFS_GLOCK();
403     code = afs_open(&vcp, fp->f_flags, credp);
404     AFS_GUNLOCK();
405
406     crfree(credp);
407     return afs_convert_code(code);
408 }
409
410 static int
411 afs_linux_release(struct inode *ip, struct file *fp)
412 {
413     struct vcache *vcp = VTOAFS(ip);
414     cred_t *credp = crref();
415     int code = 0;
416
417     AFS_GLOCK();
418     code = afs_close(vcp, fp->f_flags, credp);
419     ObtainWriteLock(&vcp->lock, 807);
420     if (vcp->cred) {
421         crfree(vcp->cred);
422         vcp->cred = NULL;
423     }
424     ReleaseWriteLock(&vcp->lock);
425     AFS_GUNLOCK();
426
427     crfree(credp);
428     return afs_convert_code(code);
429 }
430
431 static int
432 #if defined(FOP_FSYNC_TAKES_DENTRY)
433 afs_linux_fsync(struct file *fp, struct dentry *dp, int datasync)
434 #else
435 afs_linux_fsync(struct file *fp, int datasync)
436 #endif
437 {
438     int code;
439     struct inode *ip = FILE_INODE(fp);
440     cred_t *credp = crref();
441
442     AFS_GLOCK();
443     code = afs_fsync(VTOAFS(ip), credp);
444     AFS_GUNLOCK();
445     crfree(credp);
446     return afs_convert_code(code);
447
448 }
449
450
451 static int
452 afs_linux_lock(struct file *fp, int cmd, struct file_lock *flp)
453 {
454     int code = 0;
455     struct vcache *vcp = VTOAFS(FILE_INODE(fp));
456     cred_t *credp = crref();
457     struct AFS_FLOCK flock;
458     
459     /* Convert to a lock format afs_lockctl understands. */
460     memset(&flock, 0, sizeof(flock));
461     flock.l_type = flp->fl_type;
462     flock.l_pid = flp->fl_pid;
463     flock.l_whence = 0;
464     flock.l_start = flp->fl_start;
465     if (flp->fl_end == OFFSET_MAX)
466         flock.l_len = 0; /* Lock to end of file */
467     else
468         flock.l_len = flp->fl_end - flp->fl_start + 1;
469
470     /* Safe because there are no large files, yet */
471 #if defined(F_GETLK64) && (F_GETLK != F_GETLK64)
472     if (cmd == F_GETLK64)
473         cmd = F_GETLK;
474     else if (cmd == F_SETLK64)
475         cmd = F_SETLK;
476     else if (cmd == F_SETLKW64)
477         cmd = F_SETLKW;
478 #endif /* F_GETLK64 && F_GETLK != F_GETLK64 */
479
480     AFS_GLOCK();
481     code = afs_lockctl(vcp, &flock, cmd, credp);
482     AFS_GUNLOCK();
483
484     if ((code == 0 || flp->fl_type == F_UNLCK) && 
485         (cmd == F_SETLK || cmd == F_SETLKW)) {
486         code = afs_posix_lock_file(fp, flp);
487         if (code && flp->fl_type != F_UNLCK) {
488             struct AFS_FLOCK flock2;
489             flock2 = flock;
490             flock2.l_type = F_UNLCK;
491             AFS_GLOCK();
492             afs_lockctl(vcp, &flock2, F_SETLK, credp);
493             AFS_GUNLOCK();
494         }
495     }
496     /* If lockctl says there are no conflicting locks, then also check with the
497      * kernel, as lockctl knows nothing about byte range locks
498      */
499     if (code == 0 && cmd == F_GETLK && flock.l_type == F_UNLCK) {
500         afs_posix_test_lock(fp, flp);
501         /* If we found a lock in the kernel's structure, return it */
502         if (flp->fl_type != F_UNLCK) {
503             crfree(credp);
504             return 0;
505         }
506     }
507     
508     /* Convert flock back to Linux's file_lock */
509     flp->fl_type = flock.l_type;
510     flp->fl_pid = flock.l_pid;
511     flp->fl_start = flock.l_start;
512     if (flock.l_len == 0)
513         flp->fl_end = OFFSET_MAX; /* Lock to end of file */
514     else
515         flp->fl_end = flock.l_start + flock.l_len - 1;
516
517     crfree(credp);
518     return afs_convert_code(code);
519 }
520
521 #ifdef STRUCT_FILE_OPERATIONS_HAS_FLOCK
522 static int
523 afs_linux_flock(struct file *fp, int cmd, struct file_lock *flp) {
524     int code = 0;
525     struct vcache *vcp = VTOAFS(FILE_INODE(fp));
526     cred_t *credp = crref();
527     struct AFS_FLOCK flock;
528     /* Convert to a lock format afs_lockctl understands. */
529     memset(&flock, 0, sizeof(flock));
530     flock.l_type = flp->fl_type;
531     flock.l_pid = flp->fl_pid;
532     flock.l_whence = 0;
533     flock.l_start = 0;
534     flock.l_len = 0;
535
536     /* Safe because there are no large files, yet */
537 #if defined(F_GETLK64) && (F_GETLK != F_GETLK64)
538     if (cmd == F_GETLK64)
539         cmd = F_GETLK;
540     else if (cmd == F_SETLK64)
541         cmd = F_SETLK;
542     else if (cmd == F_SETLKW64)
543         cmd = F_SETLKW;
544 #endif /* F_GETLK64 && F_GETLK != F_GETLK64 */
545
546     AFS_GLOCK();
547     code = afs_lockctl(vcp, &flock, cmd, credp);
548     AFS_GUNLOCK();
549
550     if ((code == 0 || flp->fl_type == F_UNLCK) && 
551         (cmd == F_SETLK || cmd == F_SETLKW)) {
552         flp->fl_flags &=~ FL_SLEEP;
553         code = flock_lock_file_wait(fp, flp);
554         if (code && flp->fl_type != F_UNLCK) {
555             struct AFS_FLOCK flock2;
556             flock2 = flock;
557             flock2.l_type = F_UNLCK;
558             AFS_GLOCK();
559             afs_lockctl(vcp, &flock2, F_SETLK, credp);
560             AFS_GUNLOCK();
561         }
562     }
563     /* Convert flock back to Linux's file_lock */
564     flp->fl_type = flock.l_type;
565     flp->fl_pid = flock.l_pid;
566
567     crfree(credp);
568     return afs_convert_code(code);
569 }
570 #endif
571
572 /* afs_linux_flush
573  * essentially the same as afs_fsync() but we need to get the return
574  * code for the sys_close() here, not afs_linux_release(), so call
575  * afs_StoreAllSegments() with AFS_LASTSTORE
576  */
577 static int
578 #if defined(FOP_FLUSH_TAKES_FL_OWNER_T)
579 afs_linux_flush(struct file *fp, fl_owner_t id)
580 #else
581 afs_linux_flush(struct file *fp)
582 #endif
583 {
584     struct vrequest treq;
585     struct vcache *vcp;
586     cred_t *credp;
587     int code;
588 #if defined(AFS_CACHE_BYPASS)
589     int bypasscache;
590 #endif
591
592     AFS_GLOCK();
593
594     if ((fp->f_flags & O_ACCMODE) == O_RDONLY) { /* readers dont flush */
595         AFS_GUNLOCK();
596         return 0;
597     }
598
599     AFS_DISCON_LOCK();
600
601     credp = crref();
602     vcp = VTOAFS(FILE_INODE(fp));
603
604     code = afs_InitReq(&treq, credp);
605     if (code)
606         goto out;
607 #if defined(AFS_CACHE_BYPASS)
608         /* If caching is bypassed for this file, or globally, just return 0 */
609         if(cache_bypass_strategy == ALWAYS_BYPASS_CACHE)
610                 bypasscache = 1;
611         else {
612                 ObtainReadLock(&vcp->lock);
613                 if(vcp->cachingStates & FCSBypass)
614                         bypasscache = 1;
615                 ReleaseReadLock(&vcp->lock);
616         }
617         if(bypasscache) {
618             /* future proof: don't rely on 0 return from afs_InitReq */
619             code = 0; goto out;
620         }
621 #endif
622
623     ObtainSharedLock(&vcp->lock, 535);
624     if ((vcp->execsOrWriters > 0) && (file_count(fp) == 1)) {
625         UpgradeSToWLock(&vcp->lock, 536);
626         if (!AFS_IS_DISCONNECTED) {
627                 code = afs_StoreAllSegments(vcp,
628                                 &treq,
629                                 AFS_SYNC | AFS_LASTSTORE);
630         } else {
631                 afs_DisconAddDirty(vcp, VDisconWriteOsiFlush, 1);
632         }
633         ConvertWToSLock(&vcp->lock);
634     }
635     code = afs_CheckCode(code, &treq, 54);
636     ReleaseSharedLock(&vcp->lock);
637
638 out:
639     AFS_DISCON_UNLOCK();
640     AFS_GUNLOCK();
641
642     crfree(credp);
643     return afs_convert_code(code);
644 }
645
646 struct file_operations afs_dir_fops = {
647   .read =       generic_read_dir,
648   .readdir =    afs_linux_readdir,
649 #ifdef HAVE_UNLOCKED_IOCTL
650   .unlocked_ioctl = afs_unlocked_xioctl,
651 #else
652   .ioctl =      afs_xioctl,
653 #endif
654 #ifdef HAVE_COMPAT_IOCTL
655   .compat_ioctl = afs_unlocked_xioctl,
656 #endif
657   .open =       afs_linux_open,
658   .release =    afs_linux_release,
659 };
660
661 struct file_operations afs_file_fops = {
662   .read =       afs_linux_read,
663   .write =      afs_linux_write,
664 #ifdef HAVE_LINUX_GENERIC_FILE_AIO_READ
665   .aio_read =   generic_file_aio_read,
666   .aio_write =  generic_file_aio_write,
667 #endif
668 #ifdef HAVE_UNLOCKED_IOCTL
669   .unlocked_ioctl = afs_unlocked_xioctl,
670 #else
671   .ioctl =      afs_xioctl,
672 #endif
673 #ifdef HAVE_COMPAT_IOCTL
674   .compat_ioctl = afs_unlocked_xioctl,
675 #endif
676   .mmap =       afs_linux_mmap,
677   .open =       afs_linux_open,
678   .flush =      afs_linux_flush,
679 #if defined(STRUCT_FILE_OPERATIONS_HAS_SENDFILE)
680   .sendfile =   generic_file_sendfile,
681 #endif
682 #if defined(STRUCT_FILE_OPERATIONS_HAS_SPLICE)
683   .splice_write = generic_file_splice_write,
684   .splice_read = generic_file_splice_read,
685 #endif
686   .release =    afs_linux_release,
687   .fsync =      afs_linux_fsync,
688   .lock =       afs_linux_lock,
689 #ifdef STRUCT_FILE_OPERATIONS_HAS_FLOCK
690   .flock =      afs_linux_flock,
691 #endif
692 };
693
694
695 /**********************************************************************
696  * AFS Linux dentry operations
697  **********************************************************************/
698
699 /* check_bad_parent() : Checks if this dentry's vcache is a root vcache
700  * that has its mvid (parent dir's fid) pointer set to the wrong directory
701  * due to being mounted in multiple points at once. If so, check_bad_parent()
702  * calls afs_lookup() to correct the vcache's mvid, as well as the volume's
703  * dotdotfid and mtpoint fid members.
704  * Parameters:
705  *   dp - dentry to be checked.
706  * Return Values:
707  *   None.
708  * Sideeffects:
709  *   This dentry's vcache's mvid will be set to the correct parent directory's
710  *   fid.
711  *   This root vnode's volume will have its dotdotfid and mtpoint fids set
712  *   to the correct parent and mountpoint fids.
713  */
714
715 static inline void
716 check_bad_parent(struct dentry *dp)
717 {
718     cred_t *credp;
719     struct dentry *parent;
720     struct vcache *vcp, *pvc, *avc = NULL;
721
722     vcp = VTOAFS(dp->d_inode);
723     parent = dget_parent(dp);
724     pvc = VTOAFS(parent->d_inode);
725
726     if (vcp->mvid->Fid.Volume != pvc->f.fid.Fid.Volume) {       /* bad parent */
727         credp = crref();
728
729         /* force a lookup, so vcp->mvid is fixed up */
730         afs_lookup(pvc, (char *)dp->d_name.name, &avc, credp);
731         if (!avc || vcp != avc) {       /* bad, very bad.. */
732             afs_Trace4(afs_iclSetp, CM_TRACE_TMP_1S3L, ICL_TYPE_STRING,
733                        "check_bad_parent: bad pointer returned from afs_lookup origvc newvc dentry",
734                        ICL_TYPE_POINTER, vcp, ICL_TYPE_POINTER, avc,
735                        ICL_TYPE_POINTER, dp);
736         }
737         if (avc)
738             AFS_RELE(AFSTOV(avc));
739         crfree(credp);
740     }
741
742     dput(parent);
743
744     return;
745 }
746
747 /* afs_linux_revalidate
748  * Ensure vcache is stat'd before use. Return 0 if entry is valid.
749  */
750 static int
751 afs_linux_revalidate(struct dentry *dp)
752 {
753     struct vattr vattr;
754     struct vcache *vcp = VTOAFS(dp->d_inode);
755     cred_t *credp;
756     int code;
757
758     if (afs_shuttingdown)
759         return EIO;
760
761     AFS_GLOCK();
762
763 #ifdef notyet
764     /* Make this a fast path (no crref), since it's called so often. */
765     if (vcp->f.states & CStatd) {
766
767         if (*dp->d_name.name != '/' && vcp->mvstat == 2)        /* root vnode */
768             check_bad_parent(dp);       /* check and correct mvid */
769
770         AFS_GUNLOCK();
771         return 0;
772     }
773 #endif
774
775     /* This avoids the crref when we don't have to do it. Watch for
776      * changes in afs_getattr that don't get replicated here!
777      */
778     if (vcp->f.states & CStatd &&
779         (!afs_fakestat_enable || vcp->mvstat != 1) &&
780         !afs_nfsexporter &&
781         (vType(vcp) == VDIR || vType(vcp) == VLNK)) {
782         code = afs_CopyOutAttrs(vcp, &vattr);
783     } else {
784         credp = crref();
785         code = afs_getattr(vcp, &vattr, credp);
786         crfree(credp);
787     }
788     if (!code)
789         afs_fill_inode(AFSTOV(vcp), &vattr);
790
791     AFS_GUNLOCK();
792
793     return afs_convert_code(code);
794 }
795
796 static int
797 afs_linux_getattr(struct vfsmount *mnt, struct dentry *dentry, struct kstat *stat)
798 {
799         int err = afs_linux_revalidate(dentry);
800         if (!err) {
801                 generic_fillattr(dentry->d_inode, stat);
802 }
803         return err;
804 }
805
806 /* Validate a dentry. Return 1 if unchanged, 0 if VFS layer should re-evaluate.
807  * In kernels 2.2.10 and above, we are passed an additional flags var which
808  * may have either the LOOKUP_FOLLOW OR LOOKUP_DIRECTORY set in which case
809  * we are advised to follow the entry if it is a link or to make sure that 
810  * it is a directory. But since the kernel itself checks these possibilities
811  * later on, we shouldn't have to do it until later. Perhaps in the future..
812  */
813 static int
814 #ifdef DOP_REVALIDATE_TAKES_NAMEIDATA
815 afs_linux_dentry_revalidate(struct dentry *dp, struct nameidata *nd)
816 #else
817 afs_linux_dentry_revalidate(struct dentry *dp, int flags)
818 #endif
819 {
820     struct vattr vattr;
821     cred_t *credp = NULL;
822     struct vcache *vcp, *pvcp, *tvc = NULL;
823     struct dentry *parent;
824     int valid;
825     struct afs_fakestat_state fakestate;
826
827     AFS_GLOCK();
828     afs_InitFakeStat(&fakestate);
829
830     if (dp->d_inode) {
831         vcp = VTOAFS(dp->d_inode);
832
833         if (vcp == afs_globalVp)
834             goto good_dentry;
835
836         if (vcp->mvstat == 1) {         /* mount point */
837             if (vcp->mvid && (vcp->f.states & CMValid)) {
838                 int tryEvalOnly = 0;
839                 int code = 0;
840                 struct vrequest treq;
841
842                 credp = crref();
843                 code = afs_InitReq(&treq, credp);
844                 if (
845                     (strcmp(dp->d_name.name, ".directory") == 0)) {
846                     tryEvalOnly = 1;
847                 }
848                 if (tryEvalOnly)
849                     code = afs_TryEvalFakeStat(&vcp, &fakestate, &treq);
850                 else
851                     code = afs_EvalFakeStat(&vcp, &fakestate, &treq);
852                 if ((tryEvalOnly && vcp->mvstat == 1) || code) {
853                     /* a mount point, not yet replaced by its directory */
854                     goto bad_dentry;
855                 }
856             }
857         } else
858             if (*dp->d_name.name != '/' && vcp->mvstat == 2) /* root vnode */
859                 check_bad_parent(dp);   /* check and correct mvid */
860
861 #ifdef notdef
862         /* If the last looker changes, we should make sure the current
863          * looker still has permission to examine this file.  This would
864          * always require a crref() which would be "slow".
865          */
866         if (vcp->last_looker != treq.uid) {
867             if (!afs_AccessOK(vcp, (vType(vcp) == VREG) ? PRSFS_READ : PRSFS_LOOKUP, &treq, CHECK_MODE_BITS))
868                 goto bad_dentry;
869
870             vcp->last_looker = treq.uid;
871         }
872 #endif
873
874         parent = dget_parent(dp);
875         pvcp = VTOAFS(parent->d_inode);
876
877         /* If the parent's DataVersion has changed or the vnode
878          * is longer valid, we need to do a full lookup.  VerifyVCache
879          * isn't enough since the vnode may have been renamed.
880          */
881
882         if (hgetlo(pvcp->f.m.DataVersion) > dp->d_time || !(vcp->f.states & CStatd)) {
883
884             credp = crref();
885             afs_lookup(pvcp, (char *)dp->d_name.name, &tvc, credp);
886             if (!tvc || tvc != vcp) {
887                 dput(parent);
888                 goto bad_dentry;
889             }
890
891             if (afs_getattr(vcp, &vattr, credp)) {
892                 dput(parent);
893                 goto bad_dentry;
894             }
895
896             vattr2inode(AFSTOV(vcp), &vattr);
897             dp->d_time = hgetlo(pvcp->f.m.DataVersion);
898         }
899
900         /* should we always update the attributes at this point? */
901         /* unlikely--the vcache entry hasn't changed */
902
903         dput(parent);
904     } else {
905 #ifdef notyet
906         /* If this code is ever enabled, we should use dget_parent to handle
907          * getting the parent, and dput() to dispose of it. See above for an
908          * example ... */
909         pvcp = VTOAFS(dp->d_parent->d_inode);
910         if (hgetlo(pvcp->f.m.DataVersion) > dp->d_time)
911             goto bad_dentry;
912 #endif
913
914         /* No change in parent's DataVersion so this negative
915          * lookup is still valid.  BUT, if a server is down a
916          * negative lookup can result so there should be a
917          * liftime as well.  For now, always expire.
918          */
919
920         goto bad_dentry;
921     }
922
923   good_dentry:
924     valid = 1;
925
926   done:
927     /* Clean up */
928     if (tvc)
929         afs_PutVCache(tvc);
930     afs_PutFakeStat(&fakestate);
931     AFS_GUNLOCK();
932     if (credp)
933         crfree(credp);
934
935     if (!valid) {
936         shrink_dcache_parent(dp);
937         d_drop(dp);
938     }
939     return valid;
940
941   bad_dentry:
942     if (have_submounts(dp))
943         valid = 1;
944     else 
945         valid = 0;
946     goto done;
947 }
948
949 static void
950 afs_dentry_iput(struct dentry *dp, struct inode *ip)
951 {
952     struct vcache *vcp = VTOAFS(ip);
953
954     AFS_GLOCK();
955     if (!AFS_IS_DISCONNECTED || (vcp->f.states & CUnlinked)) {
956         (void) afs_InactiveVCache(vcp, NULL);
957     }
958     AFS_GUNLOCK();
959     afs_linux_clear_nfsfs_renamed(dp);
960
961     iput(ip);
962 }
963
964 static int
965 afs_dentry_delete(struct dentry *dp)
966 {
967     if (dp->d_inode && (VTOAFS(dp->d_inode)->f.states & CUnlinked))
968         return 1;               /* bad inode? */
969
970     return 0;
971 }
972
973 struct dentry_operations afs_dentry_operations = {
974   .d_revalidate =       afs_linux_dentry_revalidate,
975   .d_delete =           afs_dentry_delete,
976   .d_iput =             afs_dentry_iput,
977 };
978
979 /**********************************************************************
980  * AFS Linux inode operations
981  **********************************************************************/
982
983 /* afs_linux_create
984  *
985  * Merely need to set enough of vattr to get us through the create. Note
986  * that the higher level code (open_namei) will take care of any tuncation
987  * explicitly. Exclusive open is also taken care of in open_namei.
988  *
989  * name is in kernel space at this point.
990  */
991 static int
992 #ifdef IOP_CREATE_TAKES_NAMEIDATA
993 afs_linux_create(struct inode *dip, struct dentry *dp, int mode,
994                  struct nameidata *nd)
995 #else
996 afs_linux_create(struct inode *dip, struct dentry *dp, int mode)
997 #endif
998 {
999     struct vattr vattr;
1000     cred_t *credp = crref();
1001     const char *name = dp->d_name.name;
1002     struct vcache *vcp;
1003     int code;
1004
1005     VATTR_NULL(&vattr);
1006     vattr.va_mode = mode;
1007     vattr.va_type = mode & S_IFMT;
1008
1009     AFS_GLOCK();
1010     code = afs_create(VTOAFS(dip), (char *)name, &vattr, NONEXCL, mode,
1011                       &vcp, credp);
1012
1013     if (!code) {
1014         struct inode *ip = AFSTOV(vcp);
1015
1016         afs_getattr(vcp, &vattr, credp);
1017         afs_fill_inode(ip, &vattr);
1018         insert_inode_hash(ip);
1019         dp->d_op = &afs_dentry_operations;
1020         dp->d_time = hgetlo(VTOAFS(dip)->f.m.DataVersion);
1021         d_instantiate(dp, ip);
1022     }
1023     AFS_GUNLOCK();
1024
1025     crfree(credp);
1026     return afs_convert_code(code);
1027 }
1028
1029 /* afs_linux_lookup */
1030 static struct dentry *
1031 #ifdef IOP_LOOKUP_TAKES_NAMEIDATA
1032 afs_linux_lookup(struct inode *dip, struct dentry *dp,
1033                  struct nameidata *nd)
1034 #else
1035 afs_linux_lookup(struct inode *dip, struct dentry *dp)
1036 #endif
1037 {
1038     cred_t *credp = crref();
1039     struct vcache *vcp = NULL;
1040     const char *comp = dp->d_name.name;
1041     struct inode *ip = NULL;
1042     struct dentry *newdp = NULL;
1043     int code;
1044
1045     AFS_GLOCK();
1046     code = afs_lookup(VTOAFS(dip), (char *)comp, &vcp, credp);
1047     
1048     if (vcp) {
1049         struct vattr vattr;
1050
1051         ip = AFSTOV(vcp);
1052         afs_getattr(vcp, &vattr, credp);
1053         afs_fill_inode(ip, &vattr);
1054         if (hlist_unhashed(&ip->i_hash))
1055             insert_inode_hash(ip);
1056     }
1057     dp->d_op = &afs_dentry_operations;
1058     dp->d_time = hgetlo(VTOAFS(dip)->f.m.DataVersion);
1059     AFS_GUNLOCK();
1060
1061     if (ip && S_ISDIR(ip->i_mode)) {
1062         struct dentry *alias;
1063
1064         /* Try to invalidate an existing alias in favor of our new one */
1065         alias = d_find_alias(ip);
1066         /* But not if it's disconnected; then we want d_splice_alias below */
1067         if (alias && !(alias->d_flags & DCACHE_DISCONNECTED)) {
1068             if (d_invalidate(alias) == 0) {
1069                 dput(alias);
1070             } else {
1071                 iput(ip);
1072                 crfree(credp);
1073                 return alias;
1074             }
1075         }
1076     }
1077     newdp = d_splice_alias(ip, dp);
1078
1079     crfree(credp);
1080
1081     /* It's ok for the file to not be found. That's noted by the caller by
1082      * seeing that the dp->d_inode field is NULL.
1083      */
1084     if (!code || code == ENOENT)
1085         return newdp;
1086     else 
1087         return ERR_PTR(afs_convert_code(code));
1088 }
1089
1090 static int
1091 afs_linux_link(struct dentry *olddp, struct inode *dip, struct dentry *newdp)
1092 {
1093     int code;
1094     cred_t *credp = crref();
1095     const char *name = newdp->d_name.name;
1096     struct inode *oldip = olddp->d_inode;
1097
1098     /* If afs_link returned the vnode, we could instantiate the
1099      * dentry. Since it's not, we drop this one and do a new lookup.
1100      */
1101     d_drop(newdp);
1102
1103     AFS_GLOCK();
1104     code = afs_link(VTOAFS(oldip), VTOAFS(dip), (char *)name, credp);
1105
1106     AFS_GUNLOCK();
1107     crfree(credp);
1108     return afs_convert_code(code);
1109 }
1110
1111 /* We have to have a Linux specific sillyrename function, because we
1112  * also have to keep the dcache up to date when we're doing a silly
1113  * rename - so we don't want the generic vnodeops doing this behind our
1114  * back.
1115  */
1116
1117 static int
1118 afs_linux_sillyrename(struct inode *dir, struct dentry *dentry,
1119                       cred_t *credp)
1120 {
1121     struct vcache *tvc = VTOAFS(dentry->d_inode);
1122     struct dentry *__dp = NULL;
1123     char *__name = NULL;
1124     int code;
1125
1126     if (afs_linux_nfsfs_renamed(dentry))
1127         return EBUSY;
1128
1129     do {
1130         dput(__dp);
1131
1132         AFS_GLOCK();
1133         if (__name)
1134             osi_FreeSmallSpace(__name);
1135         __name = afs_newname();
1136         AFS_GUNLOCK();
1137
1138         __dp = lookup_one_len(__name, dentry->d_parent, strlen(__name));
1139
1140         if (IS_ERR(__dp)) {
1141             osi_FreeSmallSpace(__name);
1142             return EBUSY;
1143         }
1144     } while (__dp->d_inode != NULL);
1145
1146     AFS_GLOCK();
1147     code = afs_rename(VTOAFS(dir), (char *)dentry->d_name.name,
1148                       VTOAFS(dir), (char *)__dp->d_name.name,
1149                       credp);
1150     if (!code) {
1151         tvc->mvid = (void *) __name;
1152         crhold(credp);
1153         if (tvc->uncred) {
1154             crfree(tvc->uncred);
1155         }
1156         tvc->uncred = credp;
1157         tvc->f.states |= CUnlinked;
1158         afs_linux_set_nfsfs_renamed(dentry);
1159     } else {
1160         osi_FreeSmallSpace(__name);
1161     }
1162     AFS_GUNLOCK();
1163
1164     if (!code) {
1165         __dp->d_time = hgetlo(VTOAFS(dir)->f.m.DataVersion);
1166         d_move(dentry, __dp);
1167     }
1168     dput(__dp);
1169
1170     return code;
1171 }
1172
1173
1174 static int
1175 afs_linux_unlink(struct inode *dip, struct dentry *dp)
1176 {
1177     int code = EBUSY;
1178     cred_t *credp = crref();
1179     const char *name = dp->d_name.name;
1180     struct vcache *tvc = VTOAFS(dp->d_inode);
1181
1182     if (VREFCOUNT(tvc) > 1 && tvc->opens > 0
1183                                 && !(tvc->f.states & CUnlinked)) {
1184
1185         code = afs_linux_sillyrename(dip, dp, credp);
1186     } else {
1187         AFS_GLOCK();
1188         code = afs_remove(VTOAFS(dip), (char *)name, credp);
1189         AFS_GUNLOCK();
1190         if (!code)
1191             d_drop(dp);
1192     }
1193
1194     crfree(credp);
1195     return afs_convert_code(code);
1196 }
1197
1198
1199 static int
1200 afs_linux_symlink(struct inode *dip, struct dentry *dp, const char *target)
1201 {
1202     int code;
1203     cred_t *credp = crref();
1204     struct vattr vattr;
1205     const char *name = dp->d_name.name;
1206
1207     /* If afs_symlink returned the vnode, we could instantiate the
1208      * dentry. Since it's not, we drop this one and do a new lookup.
1209      */
1210     d_drop(dp);
1211
1212     VATTR_NULL(&vattr);
1213     AFS_GLOCK();
1214     code = afs_symlink(VTOAFS(dip), (char *)name, &vattr, (char *)target, credp);
1215     AFS_GUNLOCK();
1216     crfree(credp);
1217     return afs_convert_code(code);
1218 }
1219
1220 static int
1221 afs_linux_mkdir(struct inode *dip, struct dentry *dp, int mode)
1222 {
1223     int code;
1224     cred_t *credp = crref();
1225     struct vcache *tvcp = NULL;
1226     struct vattr vattr;
1227     const char *name = dp->d_name.name;
1228
1229     VATTR_NULL(&vattr);
1230     vattr.va_mask = ATTR_MODE;
1231     vattr.va_mode = mode;
1232     AFS_GLOCK();
1233     code = afs_mkdir(VTOAFS(dip), (char *)name, &vattr, &tvcp, credp);
1234
1235     if (tvcp) {
1236         struct inode *ip = AFSTOV(tvcp);
1237
1238         afs_getattr(tvcp, &vattr, credp);
1239         afs_fill_inode(ip, &vattr);
1240
1241         dp->d_op = &afs_dentry_operations;
1242         dp->d_time = hgetlo(VTOAFS(dip)->f.m.DataVersion);
1243         d_instantiate(dp, ip);
1244     }
1245     AFS_GUNLOCK();
1246
1247     crfree(credp);
1248     return afs_convert_code(code);
1249 }
1250
1251 static int
1252 afs_linux_rmdir(struct inode *dip, struct dentry *dp)
1253 {
1254     int code;
1255     cred_t *credp = crref();
1256     const char *name = dp->d_name.name;
1257
1258     /* locking kernel conflicts with glock? */
1259
1260     AFS_GLOCK();
1261     code = afs_rmdir(VTOAFS(dip), (char *)name, credp);
1262     AFS_GUNLOCK();
1263
1264     /* Linux likes to see ENOTEMPTY returned from an rmdir() syscall
1265      * that failed because a directory is not empty. So, we map
1266      * EEXIST to ENOTEMPTY on linux.
1267      */
1268     if (code == EEXIST) {
1269         code = ENOTEMPTY;
1270     }
1271
1272     if (!code) {
1273         d_drop(dp);
1274     }
1275
1276     crfree(credp);
1277     return afs_convert_code(code);
1278 }
1279
1280
1281 static int
1282 afs_linux_rename(struct inode *oldip, struct dentry *olddp,
1283                  struct inode *newip, struct dentry *newdp)
1284 {
1285     int code;
1286     cred_t *credp = crref();
1287     const char *oldname = olddp->d_name.name;
1288     const char *newname = newdp->d_name.name;
1289     struct dentry *rehash = NULL;
1290
1291     /* Prevent any new references during rename operation. */
1292
1293     if (!d_unhashed(newdp)) {
1294         d_drop(newdp);
1295         rehash = newdp;
1296     }
1297
1298     if (atomic_read(&olddp->d_count) > 1)
1299         shrink_dcache_parent(olddp);
1300
1301     AFS_GLOCK();
1302     code = afs_rename(VTOAFS(oldip), (char *)oldname, VTOAFS(newip), (char *)newname, credp);
1303     AFS_GUNLOCK();
1304
1305     if (!code)
1306         olddp->d_time = 0;      /* force to revalidate */
1307
1308     if (rehash)
1309         d_rehash(rehash);
1310
1311     crfree(credp);
1312     return afs_convert_code(code);
1313 }
1314
1315
1316 /* afs_linux_ireadlink 
1317  * Internal readlink which can return link contents to user or kernel space.
1318  * Note that the buffer is NOT supposed to be null-terminated.
1319  */
1320 static int
1321 afs_linux_ireadlink(struct inode *ip, char *target, int maxlen, uio_seg_t seg)
1322 {
1323     int code;
1324     cred_t *credp = crref();
1325     uio_t tuio;
1326     struct iovec iov;
1327
1328     setup_uio(&tuio, &iov, target, (afs_offs_t) 0, maxlen, UIO_READ, seg);
1329     code = afs_readlink(VTOAFS(ip), &tuio, credp);
1330     crfree(credp);
1331
1332     if (!code)
1333         return maxlen - tuio.uio_resid;
1334     else
1335         return afs_convert_code(code);
1336 }
1337
1338 #if !defined(USABLE_KERNEL_PAGE_SYMLINK_CACHE)
1339 /* afs_linux_readlink 
1340  * Fill target (which is in user space) with contents of symlink.
1341  */
1342 static int
1343 afs_linux_readlink(struct dentry *dp, char *target, int maxlen)
1344 {
1345     int code;
1346     struct inode *ip = dp->d_inode;
1347
1348     AFS_GLOCK();
1349     code = afs_linux_ireadlink(ip, target, maxlen, AFS_UIOUSER);
1350     AFS_GUNLOCK();
1351     return code;
1352 }
1353
1354
1355 /* afs_linux_follow_link
1356  * a file system dependent link following routine.
1357  */
1358 static int afs_linux_follow_link(struct dentry *dentry, struct nameidata *nd)
1359 {
1360     int code;
1361     char *name;
1362
1363     name = osi_Alloc(PATH_MAX);
1364     if (!name) {
1365         return -EIO;
1366     }
1367
1368     AFS_GLOCK();
1369     code = afs_linux_ireadlink(dentry->d_inode, name, PATH_MAX - 1, AFS_UIOSYS);
1370     AFS_GUNLOCK();
1371
1372     if (code < 0) {
1373         goto out;
1374     }
1375
1376     name[code] = '\0';
1377     code = vfs_follow_link(nd, name);
1378
1379 out:
1380     osi_Free(name, PATH_MAX);
1381
1382     return code;
1383 }
1384
1385 #endif /* USABLE_KERNEL_PAGE_SYMLINK_CACHE */
1386
1387 #if defined(AFS_CACHE_BYPASS)
1388 #endif /* defined(AFS_CACHE_BYPASS */
1389
1390 /* Populate a page by filling it from the cache file pointed at by cachefp
1391  * (which contains indicated chunk)
1392  * If task is NULL, the page copy occurs syncronously, and the routine
1393  * returns with page still locked. If task is non-NULL, then page copies
1394  * may occur in the background, and the page will be unlocked when it is
1395  * ready for use.
1396  */
1397 static int
1398 afs_linux_read_cache(struct file *cachefp, struct page *page,
1399                      int chunk, struct pagevec *lrupv,
1400                      struct afs_pagecopy_task *task) {
1401     loff_t offset = page_offset(page);
1402     struct page *newpage, *cachepage;
1403     struct address_space *cachemapping;
1404     int pageindex;
1405     int code = 0;
1406
1407     cachemapping = cachefp->f_dentry->d_inode->i_mapping;
1408     newpage = NULL;
1409     cachepage = NULL;
1410
1411     /* From our offset, we now need to work out which page in the disk
1412      * file it corresponds to. This will be fun ... */
1413     pageindex = (offset - AFS_CHUNKTOBASE(chunk)) >> PAGE_CACHE_SHIFT;
1414
1415     while (cachepage == NULL) {
1416         cachepage = find_get_page(cachemapping, pageindex);
1417         if (!cachepage) {
1418             if (!newpage)
1419                 newpage = page_cache_alloc_cold(cachemapping);
1420             if (!newpage) {
1421                 code = -ENOMEM;
1422                 goto out;
1423             }
1424
1425             code = add_to_page_cache(newpage, cachemapping,
1426                                      pageindex, GFP_KERNEL);
1427             if (code == 0) {
1428                 cachepage = newpage;
1429                 newpage = NULL;
1430
1431                 page_cache_get(cachepage);
1432                 if (!pagevec_add(lrupv, cachepage))
1433                     __pagevec_lru_add_file(lrupv);
1434
1435             } else {
1436                 page_cache_release(newpage);
1437                 newpage = NULL;
1438                 if (code != -EEXIST)
1439                     goto out;
1440             }
1441         } else {
1442             lock_page(cachepage);
1443         }
1444     }
1445
1446     if (!PageUptodate(cachepage)) {
1447         ClearPageError(cachepage);
1448         code = cachemapping->a_ops->readpage(NULL, cachepage);
1449         if (!code && !task) {
1450             wait_on_page_locked(cachepage);
1451         }
1452     } else {
1453         unlock_page(cachepage);
1454     }
1455
1456     if (!code) {
1457         if (PageUptodate(cachepage)) {
1458             copy_highpage(page, cachepage);
1459             flush_dcache_page(page);
1460             SetPageUptodate(page);
1461
1462             if (task)
1463                 unlock_page(page);
1464         } else if (task) {
1465             afs_pagecopy_queue_page(task, cachepage, page);
1466         } else {
1467             code = -EIO;
1468         }
1469     }
1470
1471     if (code && task) {
1472         unlock_page(page);
1473     }
1474
1475 out:
1476     if (cachepage)
1477         page_cache_release(cachepage);
1478
1479     return code;
1480 }
1481
1482 static int inline
1483 afs_linux_readpage_fastpath(struct file *fp, struct page *pp, int *codep)
1484 {
1485     loff_t offset = page_offset(pp);
1486     struct inode *ip = FILE_INODE(fp);
1487     struct vcache *avc = VTOAFS(ip);
1488     struct dcache *tdc;
1489     struct file *cacheFp = NULL;
1490     int code;
1491     int dcLocked = 0;
1492     struct pagevec lrupv;
1493
1494     /* Not a UFS cache, don't do anything */
1495     if (cacheDiskType != AFS_FCACHE_TYPE_UFS)
1496         return 0;
1497
1498     /* Can't do anything if the vcache isn't statd , or if the read
1499      * crosses a chunk boundary.
1500      */
1501     if (!(avc->f.states & CStatd) ||
1502         AFS_CHUNK(offset) != AFS_CHUNK(offset + PAGE_SIZE)) {
1503         return 0;
1504     }
1505
1506     ObtainWriteLock(&avc->lock, 911);
1507
1508     /* XXX - See if hinting actually makes things faster !!! */
1509
1510     /* See if we have a suitable entry already cached */
1511     tdc = avc->dchint;
1512
1513     if (tdc) {
1514         /* We need to lock xdcache, then dcache, to handle situations where
1515          * the hint is on the free list. However, we can't safely do this
1516          * according to the locking hierarchy. So, use a non blocking lock.
1517          */
1518         ObtainReadLock(&afs_xdcache);
1519         dcLocked = ( 0 == NBObtainReadLock(&tdc->lock));
1520
1521         if (dcLocked && (tdc->index != NULLIDX)
1522             && !FidCmp(&tdc->f.fid, &avc->f.fid)
1523             && tdc->f.chunk == AFS_CHUNK(offset)
1524             && !(afs_indexFlags[tdc->index] & (IFFree | IFDiscarded))) {
1525             /* Bonus - the hint was correct */
1526             afs_RefDCache(tdc);
1527         } else {
1528             /* Only destroy the hint if its actually invalid, not if there's
1529              * just been a locking failure */
1530             if (dcLocked) {
1531                 ReleaseReadLock(&tdc->lock);
1532                 avc->dchint = NULL;
1533             }
1534
1535             tdc = NULL;
1536             dcLocked = 0;
1537         }
1538         ReleaseReadLock(&afs_xdcache);
1539     }
1540
1541     /* No hint, or hint is no longer valid - see if we can get something
1542      * directly from the dcache
1543      */
1544     if (!tdc)
1545         tdc = afs_FindDCache(avc, offset);
1546
1547     if (!tdc) {
1548         ReleaseWriteLock(&avc->lock);
1549         return 0;
1550     }
1551
1552     if (!dcLocked)
1553         ObtainReadLock(&tdc->lock);
1554
1555     /* Is the dcache we've been given currently up to date */
1556     if (!hsame(avc->f.m.DataVersion, tdc->f.versionNo) ||
1557         (tdc->dflags & DFFetching)) {
1558         ReleaseWriteLock(&avc->lock);
1559         ReleaseReadLock(&tdc->lock);
1560         afs_PutDCache(tdc);
1561         return 0;
1562     }
1563
1564     /* Update our hint for future abuse */
1565     avc->dchint = tdc;
1566
1567     /* Okay, so we've now got a cache file that is up to date */
1568
1569     /* XXX - I suspect we should be locking the inodes before we use them! */
1570     AFS_GUNLOCK();
1571     cacheFp = afs_linux_raw_open(&tdc->f.inode);
1572     pagevec_init(&lrupv, 0);
1573
1574     code = afs_linux_read_cache(cacheFp, pp, tdc->f.chunk, &lrupv, NULL);
1575
1576     if (pagevec_count(&lrupv))
1577        __pagevec_lru_add_file(&lrupv);
1578
1579     filp_close(cacheFp, NULL);
1580     AFS_GLOCK();
1581
1582     ReleaseReadLock(&tdc->lock);
1583     ReleaseWriteLock(&avc->lock);
1584     afs_PutDCache(tdc);
1585
1586     *codep = code;
1587     return 1;
1588 }
1589
1590 /* afs_linux_readpage
1591  *
1592  * This function is split into two, because prepare_write/begin_write
1593  * require a readpage call which doesn't unlock the resulting page upon
1594  * success.
1595  */
1596 static int
1597 afs_linux_fillpage(struct file *fp, struct page *pp)
1598 {
1599     afs_int32 code;
1600     char *address;
1601     uio_t *auio;
1602     struct iovec *iovecp;
1603     struct inode *ip = FILE_INODE(fp);
1604     afs_int32 cnt = page_count(pp);
1605     struct vcache *avc = VTOAFS(ip);
1606     afs_offs_t offset = page_offset(pp);
1607     cred_t *credp;
1608
1609     AFS_GLOCK();
1610     if (afs_linux_readpage_fastpath(fp, pp, &code)) {
1611         AFS_GUNLOCK();
1612         return code;
1613     }
1614     AFS_GUNLOCK();
1615
1616     credp = crref();
1617     address = kmap(pp);
1618     ClearPageError(pp);
1619
1620     auio = osi_Alloc(sizeof(uio_t));
1621     iovecp = osi_Alloc(sizeof(struct iovec));
1622
1623     setup_uio(auio, iovecp, (char *)address, offset, PAGE_SIZE, UIO_READ,
1624               AFS_UIOSYS);
1625
1626     AFS_GLOCK();
1627     AFS_DISCON_LOCK();
1628     afs_Trace4(afs_iclSetp, CM_TRACE_READPAGE, ICL_TYPE_POINTER, ip,
1629                ICL_TYPE_POINTER, pp, ICL_TYPE_INT32, cnt, ICL_TYPE_INT32,
1630                99999);  /* not a possible code value */
1631
1632     code = afs_rdwr(avc, auio, UIO_READ, 0, credp);
1633         
1634     afs_Trace4(afs_iclSetp, CM_TRACE_READPAGE, ICL_TYPE_POINTER, ip,
1635                ICL_TYPE_POINTER, pp, ICL_TYPE_INT32, cnt, ICL_TYPE_INT32,
1636                code);
1637     AFS_DISCON_UNLOCK();
1638     AFS_GUNLOCK();
1639     if (!code) {
1640         /* XXX valid for no-cache also?  Check last bits of files... :)
1641          * Cognate code goes in afs_NoCacheFetchProc.  */
1642         if (auio->uio_resid)    /* zero remainder of page */
1643              memset((void *)(address + (PAGE_SIZE - auio->uio_resid)), 0,
1644                     auio->uio_resid);
1645
1646         flush_dcache_page(pp);
1647         SetPageUptodate(pp);
1648     } /* !code */
1649
1650     kunmap(pp);
1651
1652     osi_Free(auio, sizeof(uio_t));
1653     osi_Free(iovecp, sizeof(struct iovec));
1654
1655     crfree(credp);
1656     return afs_convert_code(code);
1657 }
1658
1659 static int
1660 afs_linux_prefetch(struct file *fp, struct page *pp)
1661 {
1662     int code = 0;
1663     struct vcache *avc = VTOAFS(FILE_INODE(fp));
1664     afs_offs_t offset = page_offset(pp);
1665
1666     if (AFS_CHUNKOFFSET(offset) == 0) {
1667         struct dcache *tdc;
1668         struct vrequest treq;
1669         cred_t *credp;
1670
1671         credp = crref();
1672         AFS_GLOCK();
1673         code = afs_InitReq(&treq, credp);
1674         if (!code && !NBObtainWriteLock(&avc->lock, 534)) {
1675             tdc = afs_FindDCache(avc, offset);
1676             if (tdc) {
1677                 if (!(tdc->mflags & DFNextStarted))
1678                     afs_PrefetchChunk(avc, tdc, credp, &treq);
1679                     afs_PutDCache(tdc);
1680             }
1681             ReleaseWriteLock(&avc->lock);
1682         }
1683         AFS_GUNLOCK();
1684         crfree(credp);
1685     }
1686     return afs_convert_code(code);
1687
1688 }
1689
1690 #if defined(AFS_CACHE_BYPASS)
1691
1692 static int
1693 afs_linux_bypass_readpages(struct file *fp, struct address_space *mapping,
1694                            struct list_head *page_list, unsigned num_pages)
1695 {
1696     afs_int32 page_ix;
1697     uio_t *auio;
1698     afs_offs_t offset;
1699     struct iovec* iovecp;
1700     struct nocache_read_request *ancr;
1701     struct page *pp;
1702     struct pagevec lrupv;
1703     afs_int32 code = 0;
1704
1705     cred_t *credp;
1706     struct inode *ip = FILE_INODE(fp);
1707     struct vcache *avc = VTOAFS(ip);
1708     afs_int32 base_index = 0;
1709     afs_int32 page_count = 0;
1710     afs_int32 isize;
1711
1712     /* background thread must free: iovecp, auio, ancr */
1713     iovecp = osi_Alloc(num_pages * sizeof(struct iovec));
1714
1715     auio = osi_Alloc(sizeof(uio_t));
1716     auio->uio_iov = iovecp;
1717     auio->uio_iovcnt = num_pages;
1718     auio->uio_flag = UIO_READ;
1719     auio->uio_seg = AFS_UIOSYS;
1720     auio->uio_resid = num_pages * PAGE_SIZE;
1721
1722     ancr = osi_Alloc(sizeof(struct nocache_read_request));
1723     ancr->auio = auio;
1724     ancr->offset = auio->uio_offset;
1725     ancr->length = auio->uio_resid;
1726
1727     pagevec_init(&lrupv, 0);
1728
1729     for(page_ix = 0; page_ix < num_pages; ++page_ix) {
1730
1731         if(list_empty(page_list))
1732             break;
1733
1734         pp = list_entry(page_list->prev, struct page, lru);
1735         /* If we allocate a page and don't remove it from page_list,
1736          * the page cache gets upset. */
1737         list_del(&pp->lru);
1738         isize = (i_size_read(fp->f_mapping->host) - 1) >> PAGE_CACHE_SHIFT;
1739         if(pp->index > isize) {
1740             if(PageLocked(pp))
1741                 unlock_page(pp);
1742             continue;
1743         }
1744
1745         if(page_ix == 0) {
1746             offset = page_offset(pp);
1747             auio->uio_offset = offset;
1748             base_index = pp->index;
1749         }
1750         iovecp[page_ix].iov_len = PAGE_SIZE;
1751         code = add_to_page_cache(pp, mapping, pp->index, GFP_KERNEL);
1752         if(base_index != pp->index) {
1753             if(PageLocked(pp))
1754                  unlock_page(pp);
1755             page_cache_release(pp);
1756             iovecp[page_ix].iov_base = (void *) 0;
1757             base_index++;
1758             continue;
1759         }
1760         base_index++;
1761         if(code) {
1762             if(PageLocked(pp))
1763                 unlock_page(pp);
1764             page_cache_release(pp);
1765             iovecp[page_ix].iov_base = (void *) 0;
1766         } else {
1767             page_count++;
1768             if(!PageLocked(pp)) {
1769                 lock_page(pp);
1770             }
1771
1772             /* save the page for background map */
1773             iovecp[page_ix].iov_base = (void*) pp;
1774
1775             /* and put it on the LRU cache */
1776             if (!pagevec_add(&lrupv, pp))
1777                 __pagevec_lru_add(&lrupv);
1778         }
1779     }
1780
1781     /* If there were useful pages in the page list, make sure all pages
1782      * are in the LRU cache, then schedule the read */
1783     if(page_count) {
1784         pagevec_lru_add(&lrupv);
1785         credp = crref();
1786         code = afs_ReadNoCache(avc, ancr, credp);
1787         crfree(credp);
1788     } else {
1789         /* If there is nothing for the background thread to handle,
1790          * it won't be freeing the things that we never gave it */
1791         osi_Free(iovecp, num_pages * sizeof(struct iovec));
1792         osi_Free(auio, sizeof(uio_t));
1793         osi_Free(ancr, sizeof(struct nocache_read_request));
1794     }
1795     /* we do not flush, release, or unmap pages--that will be
1796      * done for us by the background thread as each page comes in
1797      * from the fileserver */
1798     return afs_convert_code(code);
1799 }
1800
1801
1802 static int
1803 afs_linux_bypass_readpage(struct file *fp, struct page *pp)
1804 {
1805     cred_t *credp = NULL;
1806     uio_t *auio;
1807     struct iovec *iovecp;
1808     struct nocache_read_request *ancr;
1809     int code;
1810
1811     ClearPageError(pp);
1812
1813     /* receiver frees */
1814     auio = osi_Alloc(sizeof(uio_t));
1815     iovecp = osi_Alloc(sizeof(struct iovec));
1816
1817     /* address can be NULL, because we overwrite it with 'pp', below */
1818     setup_uio(auio, iovecp, NULL, page_offset(pp),
1819               PAGE_SIZE, UIO_READ, AFS_UIOSYS);
1820
1821     /* save the page for background map */
1822     /* XXX - Shouldn't we get a reference count here? */
1823     auio->uio_iov->iov_base = (void*) pp;
1824     /* the background thread will free this */
1825     ancr = osi_Alloc(sizeof(struct nocache_read_request));
1826     ancr->auio = auio;
1827     ancr->offset = page_offset(pp);
1828     ancr->length = PAGE_SIZE;
1829
1830     credp = crref();
1831     code = afs_ReadNoCache(VTOAFS(FILE_INODE(fp)), ancr, credp);
1832     crfree(credp);
1833
1834     return afs_convert_code(code);
1835 }
1836
1837 static inline int
1838 afs_linux_can_bypass(struct inode *ip) {
1839     switch(cache_bypass_strategy) {
1840         case NEVER_BYPASS_CACHE:
1841             return 0;
1842         case ALWAYS_BYPASS_CACHE:
1843             return 1;
1844         case LARGE_FILES_BYPASS_CACHE:
1845             if(i_size_read(ip) > cache_bypass_threshold)
1846                 return 1;
1847         default:
1848             return 0;
1849      }
1850 }
1851
1852 /* Check if a file is permitted to bypass the cache by policy, and modify
1853  * the cache bypass state recorded for that file */
1854
1855 static inline int
1856 afs_linux_bypass_check(struct inode *ip) {
1857     cred_t* credp;
1858
1859     int bypass = afs_linux_can_bypass(ip);
1860
1861     credp = crref();
1862     trydo_cache_transition(VTOAFS(ip), credp, bypass);
1863     crfree(credp);
1864
1865     return bypass;
1866 }
1867
1868 #else
1869 static inline int
1870 afs_linux_bypass_check(struct inode *ip) {
1871     return 0;
1872 }
1873 static inline int
1874 afs_linux_bypass_readpage(struct file *fp, struct page *pp) {
1875     return 0;
1876 }
1877 static inline int
1878 afs_linux_bypass_readpages(struct file *fp, struct address_space *mapping,
1879                     struct list_head *page_list, unsigned int num_pages) {
1880     return 0;
1881 }
1882 #endif
1883
1884 static int
1885 afs_linux_readpage(struct file *fp, struct page *pp)
1886 {
1887     int code;
1888
1889     if (afs_linux_bypass_check(FILE_INODE(fp))) {
1890         code = afs_linux_bypass_readpage(fp, pp);
1891     } else {
1892         code = afs_linux_fillpage(fp, pp);
1893         if (!code)
1894             code = afs_linux_prefetch(fp, pp);
1895         unlock_page(pp);
1896     }
1897
1898     return code;
1899 }
1900
1901 /* Readpages reads a number of pages for a particular file. We use
1902  * this to optimise the reading, by limiting the number of times upon which
1903  * we have to lookup, lock and open vcaches and dcaches
1904  */
1905
1906 static int
1907 afs_linux_readpages(struct file *fp, struct address_space *mapping,
1908                     struct list_head *page_list, unsigned int num_pages)
1909 {
1910     struct inode *inode = mapping->host;
1911     struct vcache *avc = VTOAFS(inode);
1912     struct dcache *tdc;
1913     struct file *cacheFp = NULL;
1914     int code;
1915     unsigned int page_idx;
1916     loff_t offset;
1917     struct pagevec lrupv;
1918     struct afs_pagecopy_task *task;
1919
1920     if (afs_linux_bypass_check(inode))
1921         return afs_linux_bypass_readpages(fp, mapping, page_list, num_pages);
1922
1923     if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
1924         return 0;
1925
1926     AFS_GLOCK();
1927     if ((code = afs_linux_VerifyVCache(avc, NULL))) {
1928         AFS_GUNLOCK();
1929         return code;
1930     }
1931
1932     ObtainWriteLock(&avc->lock, 912);
1933     AFS_GUNLOCK();
1934
1935     task = afs_pagecopy_init_task();
1936
1937     tdc = NULL;
1938     pagevec_init(&lrupv, 0);
1939     for (page_idx = 0; page_idx < num_pages; page_idx++) {
1940         struct page *page = list_entry(page_list->prev, struct page, lru);
1941         list_del(&page->lru);
1942         offset = page_offset(page);
1943
1944         if (tdc && tdc->f.chunk != AFS_CHUNK(offset)) {
1945             AFS_GLOCK();
1946             ReleaseReadLock(&tdc->lock);
1947             afs_PutDCache(tdc);
1948             AFS_GUNLOCK();
1949             tdc = NULL;
1950             if (cacheFp)
1951                 filp_close(cacheFp, NULL);
1952         }
1953
1954         if (!tdc) {
1955             AFS_GLOCK();
1956             if ((tdc = afs_FindDCache(avc, offset))) {
1957                 ObtainReadLock(&tdc->lock);
1958                 if (!hsame(avc->f.m.DataVersion, tdc->f.versionNo) ||
1959                     (tdc->dflags & DFFetching)) {
1960                     ReleaseReadLock(&tdc->lock);
1961                     afs_PutDCache(tdc);
1962                     tdc = NULL;
1963                 }
1964             }
1965             AFS_GUNLOCK();
1966             if (tdc)
1967                 cacheFp = afs_linux_raw_open(&tdc->f.inode);
1968         }
1969
1970         if (tdc && !add_to_page_cache(page, mapping, page->index,
1971                                       GFP_KERNEL)) {
1972             page_cache_get(page);
1973             if (!pagevec_add(&lrupv, page))
1974                 __pagevec_lru_add_file(&lrupv);
1975
1976             afs_linux_read_cache(cacheFp, page, tdc->f.chunk, &lrupv, task);
1977         }
1978         page_cache_release(page);
1979     }
1980     if (pagevec_count(&lrupv))
1981        __pagevec_lru_add_file(&lrupv);
1982
1983     if (tdc)
1984         filp_close(cacheFp, NULL);
1985
1986     afs_pagecopy_put_task(task);
1987
1988     AFS_GLOCK();
1989     if (tdc) {
1990         ReleaseReadLock(&tdc->lock);
1991         afs_PutDCache(tdc);
1992     }
1993
1994     ReleaseWriteLock(&avc->lock);
1995     AFS_GUNLOCK();
1996     return 0;
1997 }
1998
1999 /* Prepare an AFS vcache for writeback. Should be called with the vcache
2000  * locked */
2001 static inline int
2002 afs_linux_prepare_writeback(struct vcache *avc) {
2003     if (avc->f.states & CPageWrite) {
2004         return AOP_WRITEPAGE_ACTIVATE;
2005     }
2006     avc->f.states |= CPageWrite;
2007     return 0;
2008 }
2009
2010 static inline int
2011 afs_linux_dopartialwrite(struct vcache *avc, cred_t *credp) {
2012     struct vrequest treq;
2013     int code = 0;
2014
2015     if (!afs_InitReq(&treq, credp))
2016         code = afs_DoPartialWrite(avc, &treq);
2017
2018     return afs_convert_code(code);
2019 }
2020
2021 static inline void
2022 afs_linux_complete_writeback(struct vcache *avc) {
2023     avc->f.states &= ~CPageWrite;
2024 }
2025
2026 /* Writeback a given page syncronously. Called with no AFS locks held */
2027 static int
2028 afs_linux_page_writeback(struct inode *ip, struct page *pp,
2029                          unsigned long offset, unsigned int count,
2030                          cred_t *credp)
2031 {
2032     struct vcache *vcp = VTOAFS(ip);
2033     char *buffer;
2034     afs_offs_t base;
2035     int code = 0;
2036     uio_t tuio;
2037     struct iovec iovec;
2038     int f_flags = 0;
2039
2040     buffer = kmap(pp) + offset;
2041     base = page_offset(pp) + offset;
2042
2043     AFS_GLOCK();
2044     afs_Trace4(afs_iclSetp, CM_TRACE_UPDATEPAGE, ICL_TYPE_POINTER, vcp,
2045                ICL_TYPE_POINTER, pp, ICL_TYPE_INT32, page_count(pp),
2046                ICL_TYPE_INT32, 99999);
2047
2048     setup_uio(&tuio, &iovec, buffer, base, count, UIO_WRITE, AFS_UIOSYS);
2049
2050     code = afs_write(vcp, &tuio, f_flags, credp, 0);
2051
2052     i_size_write(ip, vcp->f.m.Length);
2053     ip->i_blocks = ((vcp->f.m.Length + 1023) >> 10) << 1;
2054
2055     code = code ? afs_convert_code(code) : count - tuio.uio_resid;
2056
2057     afs_Trace4(afs_iclSetp, CM_TRACE_UPDATEPAGE, ICL_TYPE_POINTER, vcp,
2058                ICL_TYPE_POINTER, pp, ICL_TYPE_INT32, page_count(pp),
2059                ICL_TYPE_INT32, code);
2060
2061     AFS_GUNLOCK();
2062     kunmap(pp);
2063
2064     return code;
2065 }
2066
2067 static int
2068 afs_linux_writepage_sync(struct inode *ip, struct page *pp,
2069                          unsigned long offset, unsigned int count)
2070 {
2071     int code;
2072     int code1 = 0;
2073     struct vcache *vcp = VTOAFS(ip);
2074     cred_t *credp;
2075
2076     /* Catch recursive writeback. This occurs if the kernel decides
2077      * writeback is required whilst we are writing to the cache, or
2078      * flushing to the server. When we're running syncronously (as
2079      * opposed to from writepage) we can't actually do anything about
2080      * this case - as we can't return AOP_WRITEPAGE_ACTIVATE to write()
2081      */
2082     AFS_GLOCK();
2083     ObtainWriteLock(&vcp->lock, 532);
2084     afs_linux_prepare_writeback(vcp);
2085     ReleaseWriteLock(&vcp->lock);
2086     AFS_GUNLOCK();
2087
2088     credp = crref();
2089     code = afs_linux_page_writeback(ip, pp, offset, count, credp);
2090
2091     AFS_GLOCK();
2092     ObtainWriteLock(&vcp->lock, 533);
2093     if (code > 0)
2094         code1 = afs_linux_dopartialwrite(vcp, credp);
2095     afs_linux_complete_writeback(vcp);
2096     ReleaseWriteLock(&vcp->lock);
2097     AFS_GUNLOCK();
2098     crfree(credp);
2099
2100     if (code1)
2101         return code1;
2102
2103     return code;
2104 }
2105
2106 static int
2107 #ifdef AOP_WRITEPAGE_TAKES_WRITEBACK_CONTROL
2108 afs_linux_writepage(struct page *pp, struct writeback_control *wbc)
2109 #else
2110 afs_linux_writepage(struct page *pp)
2111 #endif
2112 {
2113     struct address_space *mapping = pp->mapping;
2114     struct inode *inode;
2115     struct vcache *vcp;
2116     cred_t *credp;
2117     unsigned int to = PAGE_CACHE_SIZE;
2118     loff_t isize;
2119     int code = 0;
2120     int code1 = 0;
2121
2122     if (PageReclaim(pp)) {
2123         return AOP_WRITEPAGE_ACTIVATE;
2124         /* XXX - Do we need to redirty the page here? */
2125     }
2126
2127     page_cache_get(pp);
2128
2129     inode = mapping->host;
2130     vcp = VTOAFS(inode);
2131     isize = i_size_read(inode);
2132
2133     /* Don't defeat an earlier truncate */
2134     if (page_offset(pp) > isize) {
2135         set_page_writeback(pp);
2136         unlock_page(pp);
2137         goto done;
2138     }
2139
2140     AFS_GLOCK();
2141     ObtainWriteLock(&vcp->lock, 537);
2142     code = afs_linux_prepare_writeback(vcp);
2143     if (code == AOP_WRITEPAGE_ACTIVATE) {
2144         /* WRITEPAGE_ACTIVATE is the only return value that permits us
2145          * to return with the page still locked */
2146         ReleaseWriteLock(&vcp->lock);
2147         AFS_GUNLOCK();
2148         return code;
2149     }
2150
2151     /* Grab the creds structure currently held in the vnode, and
2152      * get a reference to it, in case it goes away ... */
2153     credp = vcp->cred;
2154     if (credp)
2155         crhold(credp);
2156     else
2157         credp = crref();
2158     ReleaseWriteLock(&vcp->lock);
2159     AFS_GUNLOCK();
2160
2161     set_page_writeback(pp);
2162
2163     SetPageUptodate(pp);
2164
2165     /* We can unlock the page here, because it's protected by the
2166      * page_writeback flag. This should make us less vulnerable to
2167      * deadlocking in afs_write and afs_DoPartialWrite
2168      */
2169     unlock_page(pp);
2170
2171     /* If this is the final page, then just write the number of bytes that
2172      * are actually in it */
2173     if ((isize - page_offset(pp)) < to )
2174         to = isize - page_offset(pp);
2175
2176     code = afs_linux_page_writeback(inode, pp, 0, to, credp);
2177
2178     AFS_GLOCK();
2179     ObtainWriteLock(&vcp->lock, 538);
2180
2181     /* As much as we might like to ignore a file server error here,
2182      * and just try again when we close(), unfortunately StoreAllSegments
2183      * will invalidate our chunks if the server returns a permanent error,
2184      * so we need to at least try and get that error back to the user
2185      */
2186     if (code == to)
2187         code1 = afs_linux_dopartialwrite(vcp, credp);
2188
2189     afs_linux_complete_writeback(vcp);
2190     ReleaseWriteLock(&vcp->lock);
2191     crfree(credp);
2192     AFS_GUNLOCK();
2193
2194 done:
2195     end_page_writeback(pp);
2196     page_cache_release(pp);
2197
2198     if (code1)
2199         return code1;
2200
2201     if (code == to)
2202         return 0;
2203
2204     return code;
2205 }
2206
2207 /* afs_linux_permission
2208  * Check access rights - returns error if can't check or permission denied.
2209  */
2210 static int
2211 #ifdef IOP_PERMISSION_TAKES_NAMEIDATA
2212 afs_linux_permission(struct inode *ip, int mode, struct nameidata *nd)
2213 #else
2214 afs_linux_permission(struct inode *ip, int mode)
2215 #endif
2216 {
2217     int code;
2218     cred_t *credp = crref();
2219     int tmp = 0;
2220
2221     AFS_GLOCK();
2222     if (mode & MAY_EXEC)
2223         tmp |= VEXEC;
2224     if (mode & MAY_READ)
2225         tmp |= VREAD;
2226     if (mode & MAY_WRITE)
2227         tmp |= VWRITE;
2228     code = afs_access(VTOAFS(ip), tmp, credp);
2229
2230     AFS_GUNLOCK();
2231     crfree(credp);
2232     return afs_convert_code(code);
2233 }
2234
2235 static int
2236 afs_linux_commit_write(struct file *file, struct page *page, unsigned offset,
2237                        unsigned to)
2238 {
2239     int code;
2240     struct inode *inode = FILE_INODE(file);
2241     loff_t pagebase = page_offset(page);
2242
2243     if (i_size_read(inode) < (pagebase + offset))
2244         i_size_write(inode, pagebase + offset);
2245
2246     if (PageChecked(page)) {
2247         SetPageUptodate(page);
2248         ClearPageChecked(page);
2249     }
2250
2251     code = afs_linux_writepage_sync(inode, page, offset, to - offset);
2252
2253     return code;
2254 }
2255
2256 static int
2257 afs_linux_prepare_write(struct file *file, struct page *page, unsigned from,
2258                         unsigned to)
2259 {
2260
2261     /* http://kerneltrap.org/node/4941 details the expected behaviour of
2262      * prepare_write. Essentially, if the page exists within the file,
2263      * and is not being fully written, then we should populate it.
2264      */
2265
2266     if (!PageUptodate(page)) {
2267         loff_t pagebase = page_offset(page);
2268         loff_t isize = i_size_read(page->mapping->host);
2269
2270         /* Is the location we are writing to beyond the end of the file? */
2271         if (pagebase >= isize ||
2272             ((from == 0) && (pagebase + to) >= isize)) {
2273             zero_user_segments(page, 0, from, to, PAGE_CACHE_SIZE);
2274             SetPageChecked(page);
2275         /* Are we we writing a full page */
2276         } else if (from == 0 && to == PAGE_CACHE_SIZE) {
2277             SetPageChecked(page);
2278         /* Is the page readable, if it's wronly, we don't care, because we're
2279          * not actually going to read from it ... */
2280         } else if ((file->f_flags && O_ACCMODE) != O_WRONLY) {
2281             /* We don't care if fillpage fails, because if it does the page
2282              * won't be marked as up to date
2283              */
2284             afs_linux_fillpage(file, page);
2285         }
2286     }
2287     return 0;
2288 }
2289
2290 #if defined(STRUCT_ADDRESS_SPACE_OPERATIONS_HAS_WRITE_BEGIN)
2291 static int
2292 afs_linux_write_end(struct file *file, struct address_space *mapping,
2293                                 loff_t pos, unsigned len, unsigned copied,
2294                                 struct page *page, void *fsdata)
2295 {
2296     int code;
2297     unsigned int from = pos & (PAGE_CACHE_SIZE - 1);
2298
2299     code = afs_linux_commit_write(file, page, from, from + len);
2300
2301     unlock_page(page);
2302     page_cache_release(page);
2303     return code;
2304 }
2305
2306 static int
2307 afs_linux_write_begin(struct file *file, struct address_space *mapping,
2308                                 loff_t pos, unsigned len, unsigned flags,
2309                                 struct page **pagep, void **fsdata)
2310 {
2311     struct page *page;
2312     pgoff_t index = pos >> PAGE_CACHE_SHIFT;
2313     unsigned int from = pos & (PAGE_CACHE_SIZE - 1);
2314     int code;
2315
2316     page = grab_cache_page_write_begin(mapping, index, flags);
2317     *pagep = page;
2318
2319     code = afs_linux_prepare_write(file, page, from, from + len);
2320     if (code) {
2321         unlock_page(page);
2322         page_cache_release(page);
2323     }
2324
2325     return code;
2326 }
2327 #endif
2328
2329
2330 static struct inode_operations afs_file_iops = {
2331   .permission =         afs_linux_permission,
2332   .getattr =            afs_linux_getattr,
2333   .setattr =            afs_notify_change,
2334 };
2335
2336 static struct address_space_operations afs_file_aops = {
2337   .readpage =           afs_linux_readpage,
2338   .readpages =          afs_linux_readpages,
2339   .writepage =          afs_linux_writepage,
2340 #if defined (STRUCT_ADDRESS_SPACE_OPERATIONS_HAS_WRITE_BEGIN)
2341   .write_begin =        afs_linux_write_begin,
2342   .write_end =          afs_linux_write_end,
2343 #else
2344   .commit_write =       afs_linux_commit_write,
2345   .prepare_write =      afs_linux_prepare_write,
2346 #endif
2347 };
2348
2349
2350 /* Separate ops vector for directories. Linux 2.2 tests type of inode
2351  * by what sort of operation is allowed.....
2352  */
2353
2354 static struct inode_operations afs_dir_iops = {
2355   .setattr =            afs_notify_change,
2356   .create =             afs_linux_create,
2357   .lookup =             afs_linux_lookup,
2358   .link =               afs_linux_link,
2359   .unlink =             afs_linux_unlink,
2360   .symlink =            afs_linux_symlink,
2361   .mkdir =              afs_linux_mkdir,
2362   .rmdir =              afs_linux_rmdir,
2363   .rename =             afs_linux_rename,
2364   .getattr =            afs_linux_getattr,
2365   .permission =         afs_linux_permission,
2366 };
2367
2368 /* We really need a separate symlink set of ops, since do_follow_link()
2369  * determines if it _is_ a link by checking if the follow_link op is set.
2370  */
2371 #if defined(USABLE_KERNEL_PAGE_SYMLINK_CACHE)
2372 static int
2373 afs_symlink_filler(struct file *file, struct page *page)
2374 {
2375     struct inode *ip = (struct inode *)page->mapping->host;
2376     char *p = (char *)kmap(page);
2377     int code;
2378
2379     AFS_GLOCK();
2380     code = afs_linux_ireadlink(ip, p, PAGE_SIZE, AFS_UIOSYS);
2381     AFS_GUNLOCK();
2382
2383     if (code < 0)
2384         goto fail;
2385     p[code] = '\0';             /* null terminate? */
2386
2387     SetPageUptodate(page);
2388     kunmap(page);
2389     unlock_page(page);
2390     return 0;
2391
2392   fail:
2393     SetPageError(page);
2394     kunmap(page);
2395     unlock_page(page);
2396     return code;
2397 }
2398
2399 static struct address_space_operations afs_symlink_aops = {
2400   .readpage =   afs_symlink_filler
2401 };
2402 #endif  /* USABLE_KERNEL_PAGE_SYMLINK_CACHE */
2403
2404 static struct inode_operations afs_symlink_iops = {
2405 #if defined(USABLE_KERNEL_PAGE_SYMLINK_CACHE)
2406   .readlink =           page_readlink,
2407 # if defined(HAVE_LINUX_PAGE_FOLLOW_LINK)
2408   .follow_link =        page_follow_link,
2409 # else
2410   .follow_link =        page_follow_link_light,
2411   .put_link =           page_put_link,
2412 # endif
2413 #else /* !defined(USABLE_KERNEL_PAGE_SYMLINK_CACHE) */
2414   .readlink =           afs_linux_readlink,
2415   .follow_link =        afs_linux_follow_link,
2416 #endif /* USABLE_KERNEL_PAGE_SYMLINK_CACHE */
2417   .setattr =            afs_notify_change,
2418 };
2419
2420 void
2421 afs_fill_inode(struct inode *ip, struct vattr *vattr)
2422 {
2423         
2424     if (vattr)
2425         vattr2inode(ip, vattr);
2426
2427     ip->i_mapping->backing_dev_info = afs_backing_dev_info;
2428 /* Reset ops if symlink or directory. */
2429     if (S_ISREG(ip->i_mode)) {
2430         ip->i_op = &afs_file_iops;
2431         ip->i_fop = &afs_file_fops;
2432         ip->i_data.a_ops = &afs_file_aops;
2433
2434     } else if (S_ISDIR(ip->i_mode)) {
2435         ip->i_op = &afs_dir_iops;
2436         ip->i_fop = &afs_dir_fops;
2437
2438     } else if (S_ISLNK(ip->i_mode)) {
2439         ip->i_op = &afs_symlink_iops;
2440 #if defined(USABLE_KERNEL_PAGE_SYMLINK_CACHE)
2441         ip->i_data.a_ops = &afs_symlink_aops;
2442         ip->i_mapping = &ip->i_data;
2443 #endif
2444     }
2445
2446 }