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