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