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