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