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