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