Make VLockFile not DAFS-specific
[openafs.git] / src / vol / vnode.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  * Portions Copyright (c) 2005-2008 Sine Nomine Associates
10  */
11
12 /*
13         System:         VICE-TWO
14         Module:         vnode.c
15         Institution:    The Information Technology Center, Carnegie-Mellon University
16
17  */
18 #include <afsconfig.h>
19 #include <afs/param.h>
20 #define MAXINT     (~(1<<((sizeof(int)*8)-1)))
21
22
23 #include <errno.h>
24 #include <stdio.h>
25 #include <string.h>
26 #include <stdarg.h>
27 #ifdef AFS_PTHREAD_ENV
28 #include <assert.h>
29 #else /* AFS_PTHREAD_ENV */
30 #include <afs/assert.h>
31 #endif /* AFS_PTHREAD_ENV */
32
33 #include <rx/xdr.h>
34 #include "rx/rx_queue.h"
35 #include <afs/afsint.h>
36 #include "nfs.h"
37 #include <afs/errors.h>
38 #include "lock.h"
39 #include "lwp.h"
40 #include <afs/afssyscalls.h>
41 #include "ihandle.h"
42 #include "vnode.h"
43 #include "volume.h"
44 #include "volume_inline.h"
45 #include "vnode_inline.h"
46 #include "partition.h"
47 #include "salvsync.h"
48 #if defined(AFS_SGI_ENV)
49 #include "sys/types.h"
50 #include "fcntl.h"
51 #undef min
52 #undef max
53 #include "stdlib.h"
54 #endif
55 #ifdef AFS_NT40_ENV
56 #include <fcntl.h>
57 #include "ntops.h"
58 #else
59 #include <sys/file.h>
60 #ifdef  AFS_SUN5_ENV
61 #include <sys/fcntl.h>
62 #endif
63 #include <unistd.h>
64 #endif /* AFS_NT40_ENV */
65 #include <sys/stat.h>
66
67 #ifdef HAVE_STDINT_H
68 # include <stdint.h>
69 #endif
70
71 /*@printflike@*/ extern void Log(const char *format, ...);
72
73 /*@printflike@*/ extern void Abort(const char *format, ...);
74
75
76 struct VnodeClassInfo VnodeClassInfo[nVNODECLASSES];
77
78 void VNLog(afs_int32 aop, afs_int32 anparms, ... );
79
80 extern int LogLevel;
81
82
83
84
85 #define BAD_IGET        -1000
86
87 /* There are two separate vnode queue types defined here:
88  * Each hash conflict chain -- is singly linked, with a single head
89  * pointer. New entries are added at the beginning. Old
90  * entries are removed by linear search, which generally
91  * only occurs after a disk read).
92  * LRU chain -- is doubly linked, single head pointer.
93  * Entries are added at the head, reclaimed from the tail,
94  * or removed from anywhere in the queue.
95  */
96
97
98 /* Vnode hash table.  Find hash chain by taking lower bits of
99  * (volume_hash_offset + vnode).
100  * This distributes the root inodes of the volumes over the
101  * hash table entries and also distributes the vnodes of
102  * volumes reasonably fairly.  The volume_hash_offset field
103  * for each volume is established as the volume comes on line
104  * by using the VOLUME_HASH_OFFSET macro.  This distributes the
105  * volumes fairly among the cache entries, both when servicing
106  * a small number of volumes and when servicing a large number.
107  */
108
109 /* logging stuff for finding bugs */
110 #define THELOGSIZE      5120
111 static afs_int32 theLog[THELOGSIZE];
112 static afs_int32 vnLogPtr = 0;
113 void
114 VNLog(afs_int32 aop, afs_int32 anparms, ... )
115 {
116     register afs_int32 temp;
117     va_list ap;
118
119     va_start(ap, anparms);
120
121     if (anparms > 4)
122         anparms = 4;            /* do bounds checking */
123
124     temp = (aop << 16) | anparms;
125     theLog[vnLogPtr++] = temp;
126     if (vnLogPtr >= THELOGSIZE)
127         vnLogPtr = 0;
128     for (temp = 0; temp < anparms; temp++) {
129         theLog[vnLogPtr++] = va_arg(ap, afs_int32);
130         if (vnLogPtr >= THELOGSIZE)
131             vnLogPtr = 0;
132     }
133     va_end(ap);
134 }
135
136 /* VolumeHashOffset -- returns a new value to be stored in the
137  * volumeHashOffset of a Volume structure.  Called when a
138  * volume is initialized.  Sets the volumeHashOffset so that
139  * vnode cache entries are distributed reasonably between
140  * volumes (the root vnodes of the volumes will hash to
141  * different values, and spacing is maintained between volumes
142  * when there are not many volumes represented), and spread
143  * equally amongst vnodes within a single volume.
144  */
145 int
146 VolumeHashOffset_r(void)
147 {
148     static int nextVolumeHashOffset = 0;
149     /* hashindex Must be power of two in size */
150 #   define hashShift 3
151 #   define hashMask ((1<<hashShift)-1)
152     static byte hashindex[1 << hashShift] =
153         { 0, 128, 64, 192, 32, 160, 96, 224 };
154     int offset;
155     offset = hashindex[nextVolumeHashOffset & hashMask]
156         + (nextVolumeHashOffset >> hashShift);
157     nextVolumeHashOffset++;
158     return offset;
159 }
160
161 /* Change hashindex (above) if you change this constant */
162 #define VNODE_HASH_TABLE_SIZE 256
163 private Vnode *VnodeHashTable[VNODE_HASH_TABLE_SIZE];
164 #define VNODE_HASH(volumeptr,vnodenumber)\
165     ((volumeptr->vnodeHashOffset + vnodenumber)&(VNODE_HASH_TABLE_SIZE-1))
166
167
168 /**
169  * add a vnode to the volume's vnode list.
170  *
171  * @param[in] vp   volume object pointer
172  * @param[in] vnp  vnode object pointer
173  *
174  * @note for DAFS, it may seem like we should be acquiring a lightweight ref
175  *       on vp, but this would actually break things.  Right now, this is ok
176  *       because we destroy all vnode cache contents during during volume
177  *       detach.
178  *
179  * @pre VOL_LOCK held
180  *
181  * @internal volume package internal use only
182  */
183 void
184 AddToVVnList(Volume * vp, Vnode * vnp)
185 {
186     if (queue_IsOnQueue(vnp))
187         return;
188
189     Vn_volume(vnp) = vp;
190     Vn_cacheCheck(vnp) = vp->cacheCheck;
191     queue_Append(&vp->vnode_list, vnp);
192     Vn_stateFlags(vnp) |= VN_ON_VVN;
193 }
194
195 /**
196  * delete a vnode from the volume's vnode list.
197  *
198  * @pre VOL_LOCK held
199  *
200  * @internal volume package internal use only
201  */
202 void
203 DeleteFromVVnList(register Vnode * vnp)
204 {
205     Vn_volume(vnp) = NULL;
206
207     if (!queue_IsOnQueue(vnp))
208         return;
209
210     queue_Remove(vnp);
211     Vn_stateFlags(vnp) &= ~(VN_ON_VVN);
212 }
213
214 /**
215  * add a vnode to the end of the lru.
216  *
217  * @param[in] vcp  vnode class info object pointer
218  * @param[in] vnp  vnode object pointer
219  *
220  * @internal vnode package internal use only
221  */
222 void
223 AddToVnLRU(struct VnodeClassInfo * vcp, Vnode * vnp)
224 {
225     if (Vn_stateFlags(vnp) & VN_ON_LRU) {
226         return;
227     }
228
229     /* Add it to the circular LRU list */
230     if (vcp->lruHead == NULL)
231         Abort("VPutVnode: vcp->lruHead==NULL");
232     else {
233         vnp->lruNext = vcp->lruHead;
234         vnp->lruPrev = vcp->lruHead->lruPrev;
235         vcp->lruHead->lruPrev = vnp;
236         vnp->lruPrev->lruNext = vnp;
237         vcp->lruHead = vnp;
238     }
239
240     /* If the vnode was just deleted, put it at the end of the chain so it
241      * will be reused immediately */
242     if (vnp->delete)
243         vcp->lruHead = vnp->lruNext;
244
245     Vn_stateFlags(vnp) |= VN_ON_LRU;
246 }
247
248 /**
249  * delete a vnode from the lru.
250  *
251  * @param[in] vcp  vnode class info object pointer
252  * @param[in] vnp  vnode object pointer
253  *
254  * @internal vnode package internal use only
255  */
256 void
257 DeleteFromVnLRU(struct VnodeClassInfo * vcp, Vnode * vnp)
258 {
259     if (!(Vn_stateFlags(vnp) & VN_ON_LRU)) {
260         return;
261     }
262
263     if (vnp == vcp->lruHead)
264         vcp->lruHead = vcp->lruHead->lruNext;
265
266     if ((vnp == vcp->lruHead) || 
267         (vcp->lruHead == NULL))
268         Abort("DeleteFromVnLRU: lru chain addled!\n");
269
270     vnp->lruPrev->lruNext = vnp->lruNext;
271     vnp->lruNext->lruPrev = vnp->lruPrev;
272
273     Vn_stateFlags(vnp) &= ~(VN_ON_LRU);
274 }
275
276 /**
277  * add a vnode to the vnode hash table.
278  *
279  * @param[in] vnp  vnode object pointer
280  *
281  * @pre VOL_LOCK held
282  *
283  * @post vnode on hash
284  *
285  * @internal vnode package internal use only
286  */
287 void
288 AddToVnHash(Vnode * vnp)
289 {
290     unsigned int newHash;
291
292     if (!(Vn_stateFlags(vnp) & VN_ON_HASH)) {
293         newHash = VNODE_HASH(Vn_volume(vnp), Vn_id(vnp));
294         vnp->hashNext = VnodeHashTable[newHash];
295         VnodeHashTable[newHash] = vnp;
296         vnp->hashIndex = newHash;
297
298         Vn_stateFlags(vnp) |= VN_ON_HASH;
299     }
300 }
301
302 /**
303  * delete a vnode from the vnode hash table.
304  *
305  * @param[in] vnp
306  * @param[in] hash
307  *
308  * @pre VOL_LOCK held
309  *
310  * @post vnode removed from hash
311  *
312  * @internal vnode package internal use only
313  */
314 void
315 DeleteFromVnHash(Vnode * vnp)
316 {
317     Vnode * tvnp;
318
319     if (Vn_stateFlags(vnp) & VN_ON_HASH) {
320         tvnp = VnodeHashTable[vnp->hashIndex];
321         if (tvnp == vnp)
322             VnodeHashTable[vnp->hashIndex] = vnp->hashNext;
323         else {
324             while (tvnp && tvnp->hashNext != vnp)
325                 tvnp = tvnp->hashNext;
326             if (tvnp)
327                 tvnp->hashNext = vnp->hashNext;
328         }
329
330         vnp->hashNext = NULL;
331         vnp->hashIndex = 0;
332         Vn_stateFlags(vnp) &= ~(VN_ON_HASH);
333     }
334 }
335
336
337 /**
338  * invalidate a vnode cache entry.
339  *
340  * @param[in] avnode   vnode object pointer
341  *
342  * @pre VOL_LOCK held
343  *
344  * @post vnode metadata invalidated.
345  *       vnode removed from hash table.
346  *       DAFS: vnode state set to VN_STATE_INVALID.
347  *
348  * @internal vnode package internal use only
349  */
350 void
351 VInvalidateVnode_r(register struct Vnode *avnode)
352 {
353     avnode->changed_newTime = 0;        /* don't let it get flushed out again */
354     avnode->changed_oldTime = 0;
355     avnode->delete = 0;         /* it isn't deleted, really */
356     avnode->cacheCheck = 0;     /* invalid: prevents future vnode searches from working */
357     DeleteFromVnHash(avnode);
358 #ifdef AFS_DEMAND_ATTACH_FS
359     VnChangeState_r(avnode, VN_STATE_INVALID);
360 #endif
361 }
362
363
364 /**
365  * initialize vnode cache for a given vnode class.
366  *
367  * @param[in] class    vnode class
368  * @param[in] nVnodes  size of cache
369  *
370  * @post vnode cache allocated and initialized
371  *
372  * @internal volume package internal use only
373  *
374  * @note generally called by VInitVolumePackage_r
375  *
376  * @see VInitVolumePackage_r
377  */
378 int
379 VInitVnodes(VnodeClass class, int nVnodes)
380 {
381     byte *va;
382     register struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
383
384     vcp->allocs = vcp->gets = vcp->reads = vcp->writes = 0;
385     vcp->cacheSize = nVnodes;
386     switch (class) {
387     case vSmall:
388         assert(CHECKSIZE_SMALLVNODE);
389         vcp->lruHead = NULL;
390         vcp->residentSize = SIZEOF_SMALLVNODE;
391         vcp->diskSize = SIZEOF_SMALLDISKVNODE;
392         vcp->magic = SMALLVNODEMAGIC;
393         break;
394     case vLarge:
395         vcp->lruHead = NULL;
396         vcp->residentSize = SIZEOF_LARGEVNODE;
397         vcp->diskSize = SIZEOF_LARGEDISKVNODE;
398         vcp->magic = LARGEVNODEMAGIC;
399         break;
400     }
401     {
402         int s = vcp->diskSize - 1;
403         int n = 0;
404         while (s)
405             s >>= 1, n++;
406         vcp->logSize = n;
407     }
408
409     if (nVnodes == 0)
410         return 0;
411
412     va = (byte *) calloc(nVnodes, vcp->residentSize);
413     assert(va != NULL);
414     while (nVnodes--) {
415         Vnode *vnp = (Vnode *) va;
416         Vn_refcount(vnp) = 0;   /* no context switches */
417         Vn_stateFlags(vnp) |= VN_ON_LRU;
418 #ifdef AFS_DEMAND_ATTACH_FS
419         assert(pthread_cond_init(&Vn_stateCV(vnp), NULL) == 0);
420         Vn_state(vnp) = VN_STATE_INVALID;
421         Vn_readers(vnp) = 0;
422 #else /* !AFS_DEMAND_ATTACH_FS */
423         Lock_Init(&vnp->lock);
424 #endif /* !AFS_DEMAND_ATTACH_FS */
425         vnp->changed_oldTime = 0;
426         vnp->changed_newTime = 0;
427         Vn_volume(vnp) = NULL;
428         Vn_cacheCheck(vnp) = 0;
429         vnp->delete = Vn_id(vnp) = 0;
430 #ifdef AFS_PTHREAD_ENV
431         vnp->writer = (pthread_t) 0;
432 #else /* AFS_PTHREAD_ENV */
433         vnp->writer = (PROCESS) 0;
434 #endif /* AFS_PTHREAD_ENV */
435         vnp->hashIndex = 0;
436         vnp->handle = NULL;
437         Vn_class(vnp) = vcp;
438         if (vcp->lruHead == NULL)
439             vcp->lruHead = vnp->lruNext = vnp->lruPrev = vnp;
440         else {
441             vnp->lruNext = vcp->lruHead;
442             vnp->lruPrev = vcp->lruHead->lruPrev;
443             vcp->lruHead->lruPrev = vnp;
444             vnp->lruPrev->lruNext = vnp;
445             vcp->lruHead = vnp;
446         }
447         va += vcp->residentSize;
448     }
449     return 0;
450 }
451
452
453 /**
454  * allocate an unused vnode from the lru chain.
455  *
456  * @param[in] vcp  vnode class info object pointer
457  *
458  * @pre VOL_LOCK is held
459  *
460  * @post vnode object is removed from lru, and vnode hash table.
461  *       vnode is disassociated from volume object.
462  *       state is set to VN_STATE_INVALID.
463  *       inode handle is released.
464  *
465  * @note we traverse backwards along the lru circlist.  It shouldn't 
466  *       be necessary to specify that nUsers == 0 since if it is in the list, 
467  *       nUsers should be 0.  Things shouldn't be in lruq unless no one is 
468  *       using them.
469  *
470  * @warning DAFS: VOL_LOCK is dropped while doing inode handle release
471  *
472  * @return vnode object pointer
473  */
474 Vnode *
475 VGetFreeVnode_r(struct VnodeClassInfo * vcp)
476 {
477     register Vnode *vnp;
478
479     vnp = vcp->lruHead->lruPrev;
480 #ifdef AFS_DEMAND_ATTACH_FS
481     if (Vn_refcount(vnp) != 0 || VnIsExclusiveState(Vn_state(vnp)) ||
482         Vn_readers(vnp) != 0)
483         Abort("VGetFreeVnode_r: in-use vnode in lruq");
484 #else
485     if (Vn_refcount(vnp) != 0 || CheckLock(&vnp->lock))
486         Abort("VGetFreeVnode_r: locked vnode in lruq");
487 #endif
488     VNLog(1, 2, Vn_id(vnp), (intptr_t)vnp, 0, 0);
489
490     /* 
491      * it's going to be overwritten soon enough.
492      * remove from LRU, delete hash entry, and 
493      * disassociate from old parent volume before
494      * we have a chance to drop the vol glock
495      */
496     DeleteFromVnLRU(vcp, vnp);
497     DeleteFromVnHash(vnp);
498     if (Vn_volume(vnp)) {
499         DeleteFromVVnList(vnp);
500     }
501
502     /* drop the file descriptor */
503     if (vnp->handle) {
504 #ifdef AFS_DEMAND_ATTACH_FS
505         VnChangeState_r(vnp, VN_STATE_RELEASING);
506         VOL_UNLOCK;
507 #endif
508         /* release is, potentially, a highly latent operation due to a couple
509          * factors:
510          *   - ihandle package lock contention
511          *   - closing file descriptor(s) associated with ih
512          *
513          * Hance, we perform outside of the volume package lock in order to 
514          * reduce the probability of contention.
515          */
516         IH_RELEASE(vnp->handle);
517 #ifdef AFS_DEMAND_ATTACH_FS
518         VOL_LOCK;
519 #endif
520     }
521
522 #ifdef AFS_DEMAND_ATTACH_FS
523     VnChangeState_r(vnp, VN_STATE_INVALID);
524 #endif
525
526     return vnp;
527 }
528
529
530 /**
531  * lookup a vnode in the vnode cache hash table.
532  *
533  * @param[in] vp       pointer to volume object
534  * @param[in] vnodeId  vnode id
535  *
536  * @pre VOL_LOCK held
537  *
538  * @post matching vnode object or NULL is returned
539  *
540  * @return vnode object pointer
541  *   @retval NULL   no matching vnode object was found in the cache
542  *
543  * @internal vnode package internal use only
544  *
545  * @note this symbol is exported strictly for fssync debug protocol use
546  */
547 Vnode *
548 VLookupVnode(Volume * vp, VnodeId vnodeId)
549 {
550     Vnode * vnp;
551     unsigned int newHash;
552
553     newHash = VNODE_HASH(vp, vnodeId);
554     for (vnp = VnodeHashTable[newHash];
555          (vnp && 
556           ((Vn_id(vnp) != vnodeId) || 
557            (Vn_volume(vnp) != vp) ||
558            (vp->cacheCheck != Vn_cacheCheck(vnp))));
559          vnp = vnp->hashNext);
560
561     return vnp;
562 }
563
564
565 Vnode *
566 VAllocVnode(Error * ec, Volume * vp, VnodeType type)
567 {
568     Vnode *retVal;
569     VOL_LOCK;
570     retVal = VAllocVnode_r(ec, vp, type);
571     VOL_UNLOCK;
572     return retVal;
573 }
574
575 /**
576  * allocate a new vnode.
577  *
578  * @param[out] ec    error code return
579  * @param[in]  vp    volume object pointer
580  * @param[in]  type  desired vnode type
581  *
582  * @return vnode object pointer
583  *
584  * @pre VOL_LOCK held;
585  *      heavyweight ref held on vp
586  *
587  * @post vnode allocated and returned
588  */
589 Vnode *
590 VAllocVnode_r(Error * ec, Volume * vp, VnodeType type)
591 {
592     register Vnode *vnp;
593     VnodeId vnodeNumber;
594     int bitNumber;
595     register struct VnodeClassInfo *vcp;
596     VnodeClass class;
597     Unique unique;
598 #ifdef AFS_DEMAND_ATTACH_FS
599     VolState vol_state_save;
600 #endif
601
602     *ec = 0;
603
604 #ifdef AFS_DEMAND_ATTACH_FS
605     /*
606      * once a volume has entered an error state, don't permit
607      * further operations to proceed
608      *  -- tkeiser 11/21/2007
609      */
610     VWaitExclusiveState_r(vp);
611     if (VIsErrorState(V_attachState(vp))) {
612         /* XXX is VSALVAGING acceptable here? */
613         *ec = DAFS_VSALVAGE;
614         return NULL;
615     }
616 #endif
617
618     if (programType == fileServer && !V_inUse(vp)) {
619         if (vp->specialStatus) {
620             *ec = vp->specialStatus;
621         } else {
622             *ec = VOFFLINE;
623         }
624         return NULL;
625     }
626     class = vnodeTypeToClass(type);
627     vcp = &VnodeClassInfo[class];
628
629     if (!VolumeWriteable(vp)) {
630         *ec = (bit32) VREADONLY;
631         return NULL;
632     }
633
634     unique = vp->nextVnodeUnique++;
635     if (!unique)
636         unique = vp->nextVnodeUnique++;
637
638     if (vp->nextVnodeUnique > V_uniquifier(vp)) {
639         VUpdateVolume_r(ec, vp, 0);
640         if (*ec)
641             return NULL;
642     }
643
644     if (programType == fileServer) {
645         VAddToVolumeUpdateList_r(ec, vp);
646         if (*ec)
647             return NULL;
648     }
649
650     /* Find a slot in the bit map */
651     bitNumber = VAllocBitmapEntry_r(ec, vp, &vp->vnodeIndex[class],
652                                     VOL_ALLOC_BITMAP_WAIT);
653     if (*ec)
654         return NULL;
655     vnodeNumber = bitNumberToVnodeNumber(bitNumber, class);
656
657     /*
658      * DAFS:
659      * at this point we should be assured that V_attachState(vp) is non-exclusive
660      */
661
662  vnrehash:
663     VNLog(2, 1, vnodeNumber, 0, 0, 0);
664     /* Prepare to move it to the new hash chain */
665     vnp = VLookupVnode(vp, vnodeNumber);
666     if (vnp) {
667         /* slot already exists.  May even not be in lruq (consider store file locking a file being deleted)
668          * so we may have to wait for it below */
669         VNLog(3, 2, vnodeNumber, (intptr_t)vnp, 0, 0);
670
671         VnCreateReservation_r(vnp);
672         if (Vn_refcount(vnp) == 1) {
673             /* we're the only user */
674             /* This won't block */
675             VnLock(vnp, WRITE_LOCK, VOL_LOCK_HELD, WILL_NOT_DEADLOCK);
676         } else {
677             /* other users present; follow locking hierarchy */
678             VnLock(vnp, WRITE_LOCK, VOL_LOCK_HELD, MIGHT_DEADLOCK);
679
680 #ifdef AFS_DEMAND_ATTACH_FS
681             /*
682              * DAFS:
683              * vnode was cached, wait for any existing exclusive ops to finish.
684              * once we have reacquired the lock, re-verify volume state.
685              *
686              * note: any vnode error state is related to the old vnode; disregard.
687              */
688             VnWaitQuiescent_r(vnp);
689             if (VIsErrorState(V_attachState(vp))) {
690                 VnUnlock(vnp, WRITE_LOCK);
691                 VnCancelReservation_r(vnp);
692                 *ec = DAFS_VSALVAGE;
693                 return NULL;
694             }
695 #endif
696
697             /*
698              * verify state of the world hasn't changed
699              *
700              * (technically, this should never happen because cachecheck
701              *  is only updated during a volume attach, which should not
702              *  happen when refs are held)
703              */
704             if (Vn_volume(vnp)->cacheCheck != Vn_cacheCheck(vnp)) {
705                 VnUnlock(vnp, WRITE_LOCK);
706                 VnCancelReservation_r(vnp);
707                 goto vnrehash;
708             }
709         }
710
711     } else {
712         /* no such vnode in the cache */
713
714         vnp = VGetFreeVnode_r(vcp);
715
716         /* Initialize the header fields so noone allocates another
717          * vnode with the same number */
718         Vn_id(vnp) = vnodeNumber;
719         VnCreateReservation_r(vnp);
720         AddToVVnList(vp, vnp);
721 #ifdef AFS_DEMAND_ATTACH_FS
722         AddToVnHash(vnp);
723 #endif
724
725         /* This will never block (guaranteed by check in VGetFreeVnode_r() */
726         VnLock(vnp, WRITE_LOCK, VOL_LOCK_HELD, WILL_NOT_DEADLOCK);
727
728 #ifdef AFS_DEMAND_ATTACH_FS
729         VnChangeState_r(vnp, VN_STATE_ALLOC);
730 #endif
731
732         /* Sanity check:  is this vnode really not in use? */
733         {
734             int size;
735             IHandle_t *ihP = vp->vnodeIndex[class].handle;
736             FdHandle_t *fdP;
737             off_t off = vnodeIndexOffset(vcp, vnodeNumber);
738
739             /* XXX we have a potential race here if two threads
740              * allocate new vnodes at the same time, and they
741              * both decide it's time to extend the index
742              * file size...
743              */
744 #ifdef AFS_DEMAND_ATTACH_FS
745             /*
746              * this race has been eliminated for the DAFS case
747              * using exclusive state VOL_STATE_VNODE_ALLOC
748              *
749              * if this becomes a bottleneck, there are ways to
750              * improve parallelism for this code path
751              *   -- tkeiser 11/28/2007 
752              */
753             VCreateReservation_r(vp);
754             VWaitExclusiveState_r(vp);
755             vol_state_save = VChangeState_r(vp, VOL_STATE_VNODE_ALLOC);
756 #endif
757
758             VOL_UNLOCK;
759             fdP = IH_OPEN(ihP);
760             if (fdP == NULL) {
761                 Log("VAllocVnode: can't open index file!\n");
762                 goto error_encountered;
763             }
764             if ((size = FDH_SIZE(fdP)) < 0) {
765                 Log("VAllocVnode: can't stat index file!\n");
766                 goto error_encountered;
767             }
768             if (FDH_SEEK(fdP, off, SEEK_SET) < 0) {
769                 Log("VAllocVnode: can't seek on index file!\n");
770                 goto error_encountered;
771             }
772             if (off + vcp->diskSize <= size) {
773                 if (FDH_READ(fdP, &vnp->disk, vcp->diskSize) != vcp->diskSize) {
774                     Log("VAllocVnode: can't read index file!\n");
775                     goto error_encountered;
776                 }
777                 if (vnp->disk.type != vNull) {
778                     Log("VAllocVnode:  addled bitmap or index!\n");
779                     goto error_encountered;
780                 }
781             } else {
782                 /* growing file - grow in a reasonable increment */
783                 char *buf = (char *)malloc(16 * 1024);
784                 if (!buf)
785                     Abort("VAllocVnode: malloc failed\n");
786                 memset(buf, 0, 16 * 1024);
787                 (void)FDH_WRITE(fdP, buf, 16 * 1024);
788                 free(buf);
789             }
790             FDH_CLOSE(fdP);
791             VOL_LOCK;
792
793 #ifdef AFS_DEMAND_ATTACH_FS
794             VChangeState_r(vp, vol_state_save);
795             VCancelReservation_r(vp);
796 #endif
797             goto sane;
798
799
800         error_encountered:
801 #ifdef AFS_DEMAND_ATTACH_FS
802             /* 
803              * close the file handle
804              * acquire VOL_LOCK
805              * invalidate the vnode
806              * free up the bitmap entry (although salvager should take care of it)
807              * salvage the volume
808              * drop vnode lock and refs
809              */
810             if (fdP)
811                 FDH_CLOSE(fdP);
812             VOL_LOCK;
813             VFreeBitMapEntry_r(ec, &vp->vnodeIndex[class], bitNumber);
814             VInvalidateVnode_r(vnp);
815             VnUnlock(vnp, WRITE_LOCK);
816             VnCancelReservation_r(vnp);
817             VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0);
818             VCancelReservation_r(vp);
819             return NULL;
820 #else
821             assert(1 == 2);
822 #endif
823
824         }
825     sane:
826         VNLog(4, 2, vnodeNumber, (intptr_t)vnp, 0, 0);
827 #ifndef AFS_DEMAND_ATTACH_FS
828         AddToVnHash(vnp);
829 #endif
830     }
831
832     VNLog(5, 1, (intptr_t)vnp, 0, 0, 0);
833     memset(&vnp->disk, 0, sizeof(vnp->disk));
834     vnp->changed_newTime = 0;   /* set this bit when vnode is updated */
835     vnp->changed_oldTime = 0;   /* set this on CopyOnWrite. */
836     vnp->delete = 0;
837     vnp->disk.vnodeMagic = vcp->magic;
838     vnp->disk.type = type;
839     vnp->disk.uniquifier = unique;
840     vnp->handle = NULL;
841     vcp->allocs++;
842     vp->header->diskstuff.filecount++;
843 #ifdef AFS_DEMAND_ATTACH_FS
844     VnChangeState_r(vnp, VN_STATE_EXCLUSIVE);
845 #endif
846     return vnp;
847 }
848
849 /**
850  * load a vnode from disk.
851  *
852  * @param[out] ec     client error code return
853  * @param[in]  vp     volume object pointer
854  * @param[in]  vnp    vnode object pointer
855  * @param[in]  vcp    vnode class info object pointer
856  * @param[in]  class  vnode class enumeration
857  *
858  * @pre vnode is registered in appropriate data structures;
859  *      caller holds a ref on vnode; VOL_LOCK is held
860  *
861  * @post vnode data is loaded from disk.
862  *       vnode state is set to VN_STATE_ONLINE.
863  *       on failure, vnode is invalidated.
864  *
865  * @internal vnode package internal use only
866  */
867 static void
868 VnLoad(Error * ec, Volume * vp, Vnode * vnp, 
869        struct VnodeClassInfo * vcp, VnodeClass class)
870 {
871     /* vnode not cached */
872     Error error;
873     int n, dosalv = 1;
874     IHandle_t *ihP = vp->vnodeIndex[class].handle;
875     FdHandle_t *fdP;
876
877     *ec = 0;
878     vcp->reads++;
879
880 #ifdef AFS_DEMAND_ATTACH_FS
881     VnChangeState_r(vnp, VN_STATE_LOAD);
882 #endif
883
884     /* This will never block */
885     VnLock(vnp, WRITE_LOCK, VOL_LOCK_HELD, WILL_NOT_DEADLOCK);
886
887     VOL_UNLOCK;
888     fdP = IH_OPEN(ihP);
889     if (fdP == NULL) {
890         Log("VnLoad: can't open index dev=%u, i=%s\n", vp->device,
891             PrintInode(NULL, vp->vnodeIndex[class].handle->ih_ino));
892         *ec = VIO;
893         goto error_encountered_nolock;
894     } else if (FDH_SEEK(fdP, vnodeIndexOffset(vcp, Vn_id(vnp)), SEEK_SET)
895                < 0) {
896         Log("VnLoad: can't seek on index file vn=%u\n", Vn_id(vnp));
897         *ec = VIO;
898         goto error_encountered_nolock;
899     } else if ((n = FDH_READ(fdP, (char *)&vnp->disk, vcp->diskSize))
900                != vcp->diskSize) {
901         /* Don't take volume off line if the inumber is out of range
902          * or the inode table is full. */
903         if (n == BAD_IGET) {
904             Log("VnLoad: bad inumber %s\n",
905                 PrintInode(NULL, vp->vnodeIndex[class].handle->ih_ino));
906             *ec = VIO;
907             dosalv = 0;
908         } else if (n == -1 && errno == EIO) {
909             /* disk error; salvage */
910             Log("VnLoad: Couldn't read vnode %u, volume %u (%s); volume needs salvage\n", Vn_id(vnp), V_id(vp), V_name(vp));
911         } else {
912             /* vnode is not allocated */
913             if (LogLevel >= 5) 
914                 Log("VnLoad: Couldn't read vnode %u, volume %u (%s); read %d bytes, errno %d\n", 
915                     Vn_id(vnp), V_id(vp), V_name(vp), n, errno);
916             *ec = VIO;
917             dosalv = 0;
918         }
919         goto error_encountered_nolock;
920     }
921     FDH_CLOSE(fdP);
922     VOL_LOCK;
923
924     /* Quick check to see that the data is reasonable */
925     if (vnp->disk.vnodeMagic != vcp->magic || vnp->disk.type == vNull) {
926         if (vnp->disk.type == vNull) {
927             *ec = VNOVNODE;
928             dosalv = 0;
929         } else {
930             struct vnodeIndex *index = &vp->vnodeIndex[class];
931             unsigned int bitNumber = vnodeIdToBitNumber(Vn_id(vnp));
932             unsigned int offset = bitNumber >> 3;
933
934             /* Test to see if vnode number is valid. */
935             if ((offset >= index->bitmapSize)
936                 || ((*(index->bitmap + offset) & (1 << (bitNumber & 0x7)))
937                     == 0)) {
938                 Log("VnLoad: Request for unallocated vnode %u, volume %u (%s) denied.\n", Vn_id(vnp), V_id(vp), V_name(vp));
939                 *ec = VNOVNODE;
940                 dosalv = 0;
941             } else {
942                 Log("VnLoad: Bad magic number, vnode %u, volume %u (%s); volume needs salvage\n", Vn_id(vnp), V_id(vp), V_name(vp));
943             }
944         }
945         goto error_encountered;
946     }
947
948     IH_INIT(vnp->handle, V_device(vp), V_parentId(vp), VN_GET_INO(vnp));
949     VnUnlock(vnp, WRITE_LOCK);
950 #ifdef AFS_DEMAND_ATTACH_FS
951     VnChangeState_r(vnp, VN_STATE_ONLINE);
952 #endif
953     return;
954
955
956  error_encountered_nolock:
957     if (fdP) {
958         FDH_REALLYCLOSE(fdP);
959     }
960     VOL_LOCK;
961
962  error_encountered:
963     if (dosalv) {
964 #ifdef AFS_DEMAND_ATTACH_FS
965         VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
966 #else
967         VForceOffline_r(vp, 0);
968         error = VSALVAGE;
969 #endif
970         if (!*ec)
971             *ec = error;
972     }
973
974     VInvalidateVnode_r(vnp);
975     VnUnlock(vnp, WRITE_LOCK);
976 }
977
978 /**
979  * store a vnode to disk.
980  *
981  * @param[out] ec     error code output
982  * @param[in]  vp     volume object pointer
983  * @param[in]  vnp    vnode object pointer
984  * @param[in]  vcp    vnode class info object pointer
985  * @param[in]  class  vnode class enumeration
986  *
987  * @pre VOL_LOCK held.
988  *      caller holds refs to volume and vnode.
989  *      DAFS: caller is responsible for performing state sanity checks.
990  *
991  * @post vnode state is stored to disk.
992  *
993  * @internal vnode package internal use only
994  */
995 static void
996 VnStore(Error * ec, Volume * vp, Vnode * vnp, 
997         struct VnodeClassInfo * vcp, VnodeClass class)
998 {
999     int offset, code;
1000     IHandle_t *ihP = vp->vnodeIndex[class].handle;
1001     FdHandle_t *fdP;
1002 #ifdef AFS_DEMAND_ATTACH_FS
1003     VnState vn_state_save;
1004 #endif
1005
1006     *ec = 0;
1007
1008 #ifdef AFS_DEMAND_ATTACH_FS
1009     vn_state_save = VnChangeState_r(vnp, VN_STATE_STORE);
1010 #endif
1011
1012     offset = vnodeIndexOffset(vcp, Vn_id(vnp));
1013     VOL_UNLOCK;
1014     fdP = IH_OPEN(ihP);
1015     if (fdP == NULL) {
1016         Log("VnStore: can't open index file!\n");
1017         goto error_encountered;
1018     }
1019     if (FDH_SEEK(fdP, offset, SEEK_SET) < 0) {
1020         Log("VnStore: can't seek on index file! fdp=0x%x offset=%d, errno=%d\n",
1021             fdP, offset, errno);
1022         goto error_encountered;
1023     }
1024
1025     code = FDH_WRITE(fdP, &vnp->disk, vcp->diskSize);
1026     if (code != vcp->diskSize) {
1027         /* Don't force volume offline if the inumber is out of
1028          * range or the inode table is full.
1029          */
1030         FDH_REALLYCLOSE(fdP);
1031         if (code == BAD_IGET) {
1032             Log("VnStore: bad inumber %s\n",
1033                 PrintInode(NULL,
1034                            vp->vnodeIndex[class].handle->ih_ino));
1035             *ec = VIO;
1036             VOL_LOCK;
1037 #ifdef AFS_DEMAND_ATTACH_FS
1038             VnChangeState_r(vnp, VN_STATE_ERROR);
1039 #endif
1040         } else {
1041             Log("VnStore: Couldn't write vnode %u, volume %u (%s) (error %d)\n", Vn_id(vnp), V_id(Vn_volume(vnp)), V_name(Vn_volume(vnp)), code);
1042 #ifdef AFS_DEMAND_ATTACH_FS
1043             goto error_encountered;
1044 #else
1045             VOL_LOCK;
1046             VForceOffline_r(vp, 0);
1047             *ec = VSALVAGE;
1048 #endif
1049         }
1050         return;
1051     } else {
1052         FDH_CLOSE(fdP);
1053     }
1054
1055     VOL_LOCK;
1056 #ifdef AFS_DEMAND_ATTACH_FS
1057     VnChangeState_r(vnp, vn_state_save);
1058 #endif
1059     return;
1060     
1061  error_encountered:
1062 #ifdef AFS_DEMAND_ATTACH_FS
1063     /* XXX instead of dumping core, let's try to request a salvage
1064      * and just fail the putvnode */
1065     if (fdP)
1066         FDH_CLOSE(fdP);
1067     VOL_LOCK;
1068     VnChangeState_r(vnp, VN_STATE_ERROR);
1069     VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0);
1070 #else
1071     assert(1 == 2);
1072 #endif
1073 }
1074
1075 /**
1076  * get a handle to a vnode object.
1077  *
1078  * @param[out] ec           error code
1079  * @param[in]  vp           volume object
1080  * @param[in]  vnodeNumber  vnode id
1081  * @param[in]  locktype     type of lock to acquire
1082  *
1083  * @return vnode object pointer
1084  *
1085  * @see VGetVnode_r
1086  */
1087 Vnode *
1088 VGetVnode(Error * ec, Volume * vp, VnodeId vnodeNumber, int locktype)
1089 {                               /* READ_LOCK or WRITE_LOCK, as defined in lock.h */
1090     Vnode *retVal;
1091     VOL_LOCK;
1092     retVal = VGetVnode_r(ec, vp, vnodeNumber, locktype);
1093     VOL_UNLOCK;
1094     return retVal;
1095 }
1096
1097 /**
1098  * get a handle to a vnode object.
1099  *
1100  * @param[out] ec           error code
1101  * @param[in]  vp           volume object
1102  * @param[in]  vnodeNumber  vnode id
1103  * @param[in]  locktype     type of lock to acquire
1104  *
1105  * @return vnode object pointer
1106  *
1107  * @internal vnode package internal use only
1108  *
1109  * @pre VOL_LOCK held.
1110  *      heavyweight ref held on volume object.
1111  */
1112 Vnode *
1113 VGetVnode_r(Error * ec, Volume * vp, VnodeId vnodeNumber, int locktype)
1114 {                               /* READ_LOCK or WRITE_LOCK, as defined in lock.h */
1115     register Vnode *vnp;
1116     VnodeClass class;
1117     struct VnodeClassInfo *vcp;
1118
1119     *ec = 0;
1120
1121     if (vnodeNumber == 0) {
1122         *ec = VNOVNODE;
1123         return NULL;
1124     }
1125
1126     VNLog(100, 1, vnodeNumber, 0, 0, 0);
1127
1128 #ifdef AFS_DEMAND_ATTACH_FS
1129     /*
1130      * once a volume has entered an error state, don't permit
1131      * further operations to proceed
1132      *  -- tkeiser 11/21/2007
1133      */
1134     VWaitExclusiveState_r(vp);
1135     if (VIsErrorState(V_attachState(vp))) {
1136         /* XXX is VSALVAGING acceptable here? */
1137         *ec = VSALVAGING;
1138         return NULL;
1139     }
1140 #endif
1141
1142     if (programType == fileServer && !V_inUse(vp)) {
1143         *ec = (vp->specialStatus ? vp->specialStatus : VOFFLINE);
1144
1145         /* If the volume is VBUSY (being cloned or dumped) and this is
1146          * a READ operation, then don't fail.
1147          */
1148         if ((*ec != VBUSY) || (locktype != READ_LOCK)) {
1149             return NULL;
1150         }
1151         *ec = 0;
1152     }
1153     class = vnodeIdToClass(vnodeNumber);
1154     vcp = &VnodeClassInfo[class];
1155     if (locktype == WRITE_LOCK && !VolumeWriteable(vp)) {
1156         *ec = (bit32) VREADONLY;
1157         return NULL;
1158     }
1159
1160     if (locktype == WRITE_LOCK && programType == fileServer) {
1161         VAddToVolumeUpdateList_r(ec, vp);
1162         if (*ec) {
1163             return NULL;
1164         }
1165     }
1166
1167     vcp->gets++;
1168
1169     /* See whether the vnode is in the cache. */
1170     vnp = VLookupVnode(vp, vnodeNumber);
1171     if (vnp) {
1172         /* vnode is in cache */
1173
1174         VNLog(101, 2, vnodeNumber, (intptr_t)vnp, 0, 0);
1175         VnCreateReservation_r(vnp);
1176
1177 #ifdef AFS_DEMAND_ATTACH_FS
1178         /*
1179          * this is the one DAFS case where we may run into contention.
1180          * here's the basic control flow:
1181          *
1182          * if locktype is READ_LOCK:
1183          *   wait until vnode is not exclusive
1184          *   set to VN_STATE_READ
1185          *   increment read count
1186          *   done
1187          * else
1188          *   wait until vnode is quiescent
1189          *   set to VN_STATE_EXCLUSIVE
1190          *   done
1191          */
1192         if (locktype == READ_LOCK) {
1193             VnWaitExclusiveState_r(vnp);
1194         } else {
1195             VnWaitQuiescent_r(vnp);
1196         }
1197
1198         if (VnIsErrorState(Vn_state(vnp))) {
1199             VnCancelReservation_r(vnp);
1200             *ec = VSALVAGE;
1201             return NULL;
1202         }
1203 #endif /* AFS_DEMAND_ATTACH_FS */
1204     } else {
1205         /* vnode not cached */
1206
1207         /* Not in cache; tentatively grab most distantly used one from the LRU
1208          * chain */
1209         vcp->reads++;
1210         vnp = VGetFreeVnode_r(vcp);
1211
1212         /* Initialize */
1213         vnp->changed_newTime = vnp->changed_oldTime = 0;
1214         vnp->delete = 0;
1215         Vn_id(vnp) = vnodeNumber;
1216         VnCreateReservation_r(vnp);
1217         AddToVVnList(vp, vnp);
1218 #ifdef AFS_DEMAND_ATTACH_FS
1219         AddToVnHash(vnp);
1220 #endif
1221
1222         /*
1223          * XXX for non-DAFS, there is a serious
1224          * race condition here:
1225          *
1226          * two threads can race to load a vnode.  the net
1227          * result is two struct Vnodes can be allocated
1228          * and hashed, which point to the same underlying
1229          * disk data store.  conflicting vnode locks can
1230          * thus be held concurrently.
1231          *
1232          * for non-DAFS to be safe, VOL_LOCK really shouldn't
1233          * be dropped in VnLoad.  Of course, this would likely
1234          * lead to an unacceptable slow-down.
1235          */
1236
1237         VnLoad(ec, vp, vnp, vcp, class);
1238         if (*ec) {
1239             VnCancelReservation_r(vnp);
1240             return NULL;
1241         }
1242 #ifndef AFS_DEMAND_ATTACH_FS
1243         AddToVnHash(vnp);
1244 #endif
1245         /*
1246          * DAFS:
1247          * there is no possibility for contention. we "own" this vnode.
1248          */
1249     }
1250
1251     /*
1252      * DAFS:
1253      * it is imperative that nothing drop vol lock between here
1254      * and the VnBeginRead/VnChangeState stanza below
1255      */
1256
1257     VnLock(vnp, locktype, VOL_LOCK_HELD, MIGHT_DEADLOCK);
1258
1259     /* Check that the vnode hasn't been removed while we were obtaining
1260      * the lock */
1261     VNLog(102, 2, vnodeNumber, (intptr_t) vnp, 0, 0);
1262     if ((vnp->disk.type == vNull) || (Vn_cacheCheck(vnp) == 0)) {
1263         VnUnlock(vnp, locktype);
1264         VnCancelReservation_r(vnp);
1265         *ec = VNOVNODE;
1266         /* vnode is labelled correctly by now, so we don't have to invalidate it */
1267         return NULL;
1268     }
1269
1270 #ifdef AFS_DEMAND_ATTACH_FS
1271     if (locktype == READ_LOCK) {
1272         VnBeginRead_r(vnp);
1273     } else {
1274         VnChangeState_r(vnp, VN_STATE_EXCLUSIVE);
1275     }
1276 #endif
1277
1278     if (programType == fileServer)
1279         VBumpVolumeUsage_r(Vn_volume(vnp));     /* Hack; don't know where it should be
1280                                                  * called from.  Maybe VGetVolume */
1281     return vnp;
1282 }
1283
1284
1285 int TrustVnodeCacheEntry = 1;
1286 /* This variable is bogus--when it's set to 0, the hash chains fill
1287    up with multiple versions of the same vnode.  Should fix this!! */
1288 void
1289 VPutVnode(Error * ec, register Vnode * vnp)
1290 {
1291     VOL_LOCK;
1292     VPutVnode_r(ec, vnp);
1293     VOL_UNLOCK;
1294 }
1295
1296 /**
1297  * put back a handle to a vnode object.
1298  *
1299  * @param[out] ec   client error code
1300  * @param[in]  vnp  vnode object pointer
1301  *
1302  * @pre VOL_LOCK held.
1303  *      ref held on vnode.
1304  *
1305  * @post ref dropped on vnode.
1306  *       if vnode was modified or deleted, it is written out to disk
1307  *       (assuming a write lock was held).
1308  *
1309  * @internal volume package internal use only
1310  */
1311 void
1312 VPutVnode_r(Error * ec, register Vnode * vnp)
1313 {
1314     int writeLocked;
1315     VnodeClass class;
1316     struct VnodeClassInfo *vcp;
1317
1318     *ec = 0;
1319     assert(Vn_refcount(vnp) != 0);
1320     class = vnodeIdToClass(Vn_id(vnp));
1321     vcp = &VnodeClassInfo[class];
1322     assert(vnp->disk.vnodeMagic == vcp->magic);
1323     VNLog(200, 2, Vn_id(vnp), (intptr_t) vnp, 0, 0);
1324
1325 #ifdef AFS_DEMAND_ATTACH_FS
1326     writeLocked = (Vn_state(vnp) == VN_STATE_EXCLUSIVE);
1327 #else
1328     writeLocked = WriteLocked(&vnp->lock);
1329 #endif
1330
1331     if (writeLocked) {
1332         /* sanity checks */
1333 #ifdef AFS_PTHREAD_ENV
1334         pthread_t thisProcess = pthread_self();
1335 #else /* AFS_PTHREAD_ENV */
1336         PROCESS thisProcess;
1337         LWP_CurrentProcess(&thisProcess);
1338 #endif /* AFS_PTHREAD_ENV */
1339         VNLog(201, 2, (intptr_t) vnp,
1340               ((vnp->changed_newTime) << 1) | ((vnp->
1341                                                 changed_oldTime) << 1) | vnp->
1342               delete, 0, 0);
1343         if (thisProcess != vnp->writer)
1344             Abort("VPutVnode: Vnode at 0x%x locked by another process!\n",
1345                   vnp);
1346
1347
1348         if (vnp->changed_oldTime || vnp->changed_newTime || vnp->delete) {
1349             Volume *vp = Vn_volume(vnp);
1350             afs_uint32 now = FT_ApproxTime();
1351             assert(Vn_cacheCheck(vnp) == vp->cacheCheck);
1352
1353             if (vnp->delete) {
1354                 /* No longer any directory entries for this vnode. Free the Vnode */
1355                 memset(&vnp->disk, 0, sizeof(vnp->disk));
1356                 /* delete flag turned off further down */
1357                 VNLog(202, 2, Vn_id(vnp), (intptr_t) vnp, 0, 0);
1358             } else if (vnp->changed_newTime) {
1359                 vnp->disk.serverModifyTime = now;
1360             }
1361             if (vnp->changed_newTime)
1362             {
1363                 V_updateDate(vp) = vp->updateTime = now;
1364                 if(V_volUpCounter(vp)<MAXINT)
1365                         V_volUpCounter(vp)++;
1366             }
1367
1368             /* The vnode has been changed. Write it out to disk */
1369             if (!V_inUse(vp)) {
1370 #ifdef AFS_DEMAND_ATTACH_FS
1371                 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0);
1372 #else
1373                 assert(V_needsSalvaged(vp));
1374                 *ec = VSALVAGE;
1375 #endif
1376             } else {
1377                 VnStore(ec, vp, vnp, vcp, class);
1378
1379                 /* If the vnode is to be deleted, and we wrote the vnode out,
1380                  * free its bitmap entry. Do after the vnode is written so we
1381                  * don't allocate from bitmap before the vnode is written
1382                  * (doing so could cause a "addled bitmap" message).
1383                  */
1384                 if (vnp->delete && !*ec) {
1385                     if (Vn_volume(vnp)->header->diskstuff.filecount-- < 1)
1386                         Vn_volume(vnp)->header->diskstuff.filecount = 0;
1387                     VFreeBitMapEntry_r(ec, &vp->vnodeIndex[class],
1388                                        vnodeIdToBitNumber(Vn_id(vnp)));
1389                 }
1390             }
1391             vcp->writes++;
1392             vnp->changed_newTime = vnp->changed_oldTime = 0;
1393         }
1394 #ifdef AFS_DEMAND_ATTACH_FS
1395         VnChangeState_r(vnp, VN_STATE_ONLINE);
1396 #endif
1397     } else {                    /* Not write locked */
1398         if (vnp->changed_newTime || vnp->changed_oldTime || vnp->delete)
1399             Abort
1400                 ("VPutVnode: Change or delete flag for vnode 0x%x is set but vnode is not write locked!\n",
1401                  vnp);
1402 #ifdef AFS_DEMAND_ATTACH_FS
1403         VnEndRead_r(vnp);
1404 #endif
1405     }
1406
1407     /* Do not look at disk portion of vnode after this point; it may
1408      * have been deleted above */
1409     vnp->delete = 0;
1410     VnUnlock(vnp, ((writeLocked) ? WRITE_LOCK : READ_LOCK));
1411     VnCancelReservation_r(vnp);
1412 }
1413
1414 /*
1415  * Make an attempt to convert a vnode lock from write to read.
1416  * Do nothing if the vnode isn't write locked or the vnode has
1417  * been deleted.
1418  */
1419 int
1420 VVnodeWriteToRead(Error * ec, register Vnode * vnp)
1421 {
1422     int retVal;
1423     VOL_LOCK;
1424     retVal = VVnodeWriteToRead_r(ec, vnp);
1425     VOL_UNLOCK;
1426     return retVal;
1427 }
1428
1429 /**
1430  * convert vnode handle from mutually exclusive to shared access.
1431  *
1432  * @param[out] ec   client error code
1433  * @param[in]  vnp  vnode object pointer
1434  *
1435  * @return unspecified use (see out argument 'ec' for error code return)
1436  *
1437  * @pre VOL_LOCK held.
1438  *      ref held on vnode.
1439  *      write lock held on vnode.
1440  *
1441  * @post read lock held on vnode.
1442  *       if vnode was modified, it has been written to disk.
1443  *
1444  * @internal volume package internal use only
1445  */
1446 int
1447 VVnodeWriteToRead_r(Error * ec, register Vnode * vnp)
1448 {
1449     int writeLocked;
1450     VnodeClass class;
1451     struct VnodeClassInfo *vcp;
1452 #ifdef AFS_PTHREAD_ENV
1453     pthread_t thisProcess;
1454 #else /* AFS_PTHREAD_ENV */
1455     PROCESS thisProcess;
1456 #endif /* AFS_PTHREAD_ENV */
1457
1458     *ec = 0;
1459     assert(Vn_refcount(vnp) != 0);
1460     class = vnodeIdToClass(Vn_id(vnp));
1461     vcp = &VnodeClassInfo[class];
1462     assert(vnp->disk.vnodeMagic == vcp->magic);
1463     VNLog(300, 2, Vn_id(vnp), (intptr_t) vnp, 0, 0);
1464
1465 #ifdef AFS_DEMAND_ATTACH_FS
1466     writeLocked = (Vn_state(vnp) == VN_STATE_EXCLUSIVE);
1467 #else
1468     writeLocked = WriteLocked(&vnp->lock);
1469 #endif
1470     if (!writeLocked) {
1471         return 0;
1472     }
1473
1474
1475     VNLog(301, 2, (intptr_t) vnp,
1476           ((vnp->changed_newTime) << 1) | ((vnp->
1477                                             changed_oldTime) << 1) | vnp->
1478           delete, 0, 0);
1479
1480     /* sanity checks */
1481 #ifdef AFS_PTHREAD_ENV
1482     thisProcess = pthread_self();
1483 #else /* AFS_PTHREAD_ENV */
1484     LWP_CurrentProcess(&thisProcess);
1485 #endif /* AFS_PTHREAD_ENV */
1486     if (thisProcess != vnp->writer)
1487         Abort("VPutVnode: Vnode at 0x%x locked by another process!\n",
1488               (intptr_t)vnp);
1489
1490     if (vnp->delete) {
1491         return 0;
1492     }
1493     if (vnp->changed_oldTime || vnp->changed_newTime) {
1494         Volume *vp = Vn_volume(vnp);
1495         afs_uint32 now = FT_ApproxTime();
1496         assert(Vn_cacheCheck(vnp) == vp->cacheCheck);
1497         if (vnp->changed_newTime)
1498             vnp->disk.serverModifyTime = now;
1499         if (vnp->changed_newTime)
1500             V_updateDate(vp) = vp->updateTime = now;
1501
1502         /* The inode has been changed.  Write it out to disk */
1503         if (!V_inUse(vp)) {
1504 #ifdef AFS_DEMAND_ATTACH_FS
1505             VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0);
1506 #else
1507             assert(V_needsSalvaged(vp));
1508             *ec = VSALVAGE;
1509 #endif
1510         } else {
1511             VnStore(ec, vp, vnp, vcp, class);
1512         }
1513         vcp->writes++;
1514         vnp->changed_newTime = vnp->changed_oldTime = 0;
1515     }
1516
1517     vnp->writer = 0;
1518 #ifdef AFS_DEMAND_ATTACH_FS
1519     VnChangeState_r(vnp, VN_STATE_ONLINE);
1520     VnBeginRead_r(vnp);
1521 #else
1522     ConvertWriteToReadLock(&vnp->lock);
1523 #endif
1524     return 0;
1525 }
1526
1527 /** 
1528  * initial size of ihandle pointer vector.
1529  *
1530  * @see VInvalidateVnodesByVolume_r
1531  */
1532 #define IH_VEC_BASE_SIZE 256
1533
1534 /**
1535  * increment amount for growing ihandle pointer vector.
1536  *
1537  * @see VInvalidateVnodesByVolume_r
1538  */
1539 #define IH_VEC_INCREMENT 256
1540
1541 /**
1542  * Compile list of ihandles to be released/reallyclosed at a later time.
1543  *
1544  * @param[in]   vp            volume object pointer
1545  * @param[out]  vec_out       vector of ihandle pointers to be released/reallyclosed
1546  * @param[out]  vec_len_out   number of valid elements in ihandle vector
1547  *
1548  * @pre - VOL_LOCK is held
1549  *      - volume is in appropriate exclusive state (e.g. VOL_STATE_VNODE_CLOSE,
1550  *        VOL_STATE_VNODE_RELEASE)
1551  *
1552  * @post - all vnodes on VVn list are invalidated
1553  *       - ih_vec is populated with all valid ihandles
1554  *
1555  * @return operation status
1556  *    @retval 0         success
1557  *    @retval ENOMEM    out of memory
1558  *
1559  * @todo we should handle out of memory conditions more gracefully.
1560  *
1561  * @internal vnode package internal use only
1562  */
1563 static int
1564 VInvalidateVnodesByVolume_r(Volume * vp,
1565                             IHandle_t *** vec_out,
1566                             size_t * vec_len_out)
1567 {
1568     int ret = 0;
1569     Vnode *vnp, *nvnp;
1570     size_t i = 0, vec_len;
1571     IHandle_t **ih_vec, **ih_vec_new;
1572
1573 #ifdef AFS_DEMAND_ATTACH_FS
1574     VOL_UNLOCK;
1575 #endif /* AFS_DEMAND_ATTACH_FS */
1576
1577     vec_len = IH_VEC_BASE_SIZE;
1578     ih_vec = malloc(sizeof(IHandle_t *) * vec_len);
1579 #ifdef AFS_DEMAND_ATTACH_FS
1580     VOL_LOCK;
1581 #endif
1582     if (ih_vec == NULL)
1583         return ENOMEM;
1584
1585     /* 
1586      * Traverse the volume's vnode list.  Pull all the ihandles out into a 
1587      * thread-private array for later asynchronous processing.
1588      */
1589 #ifdef AFS_DEMAND_ATTACH_FS
1590 restart_traversal:
1591 #endif
1592     for (queue_Scan(&vp->vnode_list, vnp, nvnp, Vnode)) {
1593         if (vnp->handle != NULL) {
1594             if (i == vec_len) {
1595 #ifdef AFS_DEMAND_ATTACH_FS
1596                 VOL_UNLOCK;
1597 #endif
1598                 vec_len += IH_VEC_INCREMENT;
1599                 ih_vec_new = realloc(ih_vec, sizeof(IHandle_t *) * vec_len);
1600 #ifdef AFS_DEMAND_ATTACH_FS
1601                 VOL_LOCK;
1602 #endif
1603                 if (ih_vec_new == NULL) {
1604                     ret = ENOMEM;
1605                     goto done;
1606                 }
1607                 ih_vec = ih_vec_new;
1608 #ifdef AFS_DEMAND_ATTACH_FS
1609                 /*
1610                  * Theoretically, the volume's VVn list should not change 
1611                  * because the volume is in an exclusive state.  For the
1612                  * sake of safety, we will restart the traversal from the
1613                  * the beginning (which is not expensive because we're
1614                  * deleting the items from the list as we go).
1615                  */
1616                 goto restart_traversal;
1617 #endif
1618             }
1619             ih_vec[i++] = vnp->handle;
1620             vnp->handle = NULL;
1621         }
1622         DeleteFromVVnList(vnp);
1623         VInvalidateVnode_r(vnp);
1624     }
1625
1626  done:
1627     *vec_out = ih_vec;
1628     *vec_len_out = i;
1629
1630     return ret;
1631 }
1632
1633 /* VCloseVnodeFiles - called when a volume is going off line. All open
1634  * files for vnodes in that volume are closed. This might be excessive,
1635  * since we may only be taking one volume of a volume group offline.
1636  */
1637 void
1638 VCloseVnodeFiles_r(Volume * vp)
1639 {
1640 #ifdef AFS_DEMAND_ATTACH_FS
1641     VolState vol_state_save;
1642 #endif
1643     IHandle_t ** ih_vec;
1644     size_t i, vec_len;
1645
1646 #ifdef AFS_DEMAND_ATTACH_FS
1647     vol_state_save = VChangeState_r(vp, VOL_STATE_VNODE_CLOSE);
1648 #endif /* AFS_DEMAND_ATTACH_FS */
1649
1650     /* XXX need better error handling here */
1651     assert(VInvalidateVnodesByVolume_r(vp,
1652                                        &ih_vec,
1653                                        &vec_len) == 0);
1654
1655     /*
1656      * DAFS:
1657      * now we drop VOL_LOCK while we perform some potentially very
1658      * expensive operations in the background
1659      */
1660 #ifdef AFS_DEMAND_ATTACH_FS
1661     VOL_UNLOCK;
1662 #endif
1663
1664     for (i = 0; i < vec_len; i++) {
1665         IH_REALLYCLOSE(ih_vec[i]);
1666     }
1667
1668     free(ih_vec);
1669
1670 #ifdef AFS_DEMAND_ATTACH_FS
1671     VOL_LOCK;
1672     VChangeState_r(vp, vol_state_save);
1673 #endif /* AFS_DEMAND_ATTACH_FS */
1674 }
1675
1676
1677 /**
1678  * shut down all vnode cache state for a given volume.
1679  *
1680  * @param[in] vp  volume object pointer
1681  *
1682  * @pre VOL_LOCK is held
1683  *
1684  * @post all file descriptors closed.
1685  *       all inode handles released.
1686  *       all vnode cache objects disassociated from volume.
1687  *
1688  * @note for DAFS, these operations are performed outside the vol glock under
1689  *       volume exclusive state VOL_STATE_VNODE_RELEASE.  Please further note
1690  *       that it would be a bug to acquire and release a volume reservation
1691  *       during this exclusive operation.  This is due to the fact that we are
1692  *       generally called during the refcount 1->0 transition.
1693  *
1694  * @todo we should handle failures in VInvalidateVnodesByVolume_r more 
1695  *       gracefully.
1696  *
1697  * @see VInvalidateVnodesByVolume_r
1698  *
1699  * @internal this routine is internal to the volume package
1700  */
1701 void
1702 VReleaseVnodeFiles_r(Volume * vp)
1703 {
1704 #ifdef AFS_DEMAND_ATTACH_FS
1705     VolState vol_state_save;
1706 #endif
1707     IHandle_t ** ih_vec;
1708     size_t i, vec_len;
1709
1710 #ifdef AFS_DEMAND_ATTACH_FS
1711     vol_state_save = VChangeState_r(vp, VOL_STATE_VNODE_RELEASE);
1712 #endif /* AFS_DEMAND_ATTACH_FS */
1713
1714     /* XXX need better error handling here */
1715     assert(VInvalidateVnodesByVolume_r(vp,
1716                                        &ih_vec,
1717                                        &vec_len) == 0);
1718
1719     /*
1720      * DAFS:
1721      * now we drop VOL_LOCK while we perform some potentially very
1722      * expensive operations in the background
1723      */
1724 #ifdef AFS_DEMAND_ATTACH_FS
1725     VOL_UNLOCK;
1726 #endif
1727
1728     for (i = 0; i < vec_len; i++) {
1729         IH_RELEASE(ih_vec[i]);
1730     }
1731
1732     free(ih_vec);
1733
1734 #ifdef AFS_DEMAND_ATTACH_FS
1735     VOL_LOCK;
1736     VChangeState_r(vp, vol_state_save);
1737 #endif /* AFS_DEMAND_ATTACH_FS */
1738 }