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