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