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