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