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