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