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