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