4da49fe2be37566c44b0156aabfbc72fc48969b8
[openafs.git] / src / vol / volume.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) 2006 Sine Nomine Associates
10  */
11
12 /* 1/1/89: NB:  this stuff is all going to be replaced.  Don't take it too seriously */
13 /*
14
15         System:         VICE-TWO
16         Module:         volume.c
17         Institution:    The Information Technology Center, Carnegie-Mellon University
18
19  */
20
21 #include <afsconfig.h>
22 #include <afs/param.h>
23
24 RCSID
25     ("$Header$");
26
27 #include <rx/xdr.h>
28 #include <afs/afsint.h>
29 #include <ctype.h>
30 #ifndef AFS_NT40_ENV
31 #include <sys/param.h>
32 #if !defined(AFS_SGI_ENV)
33 #ifdef  AFS_OSF_ENV
34 #include <ufs/fs.h>
35 #else /* AFS_OSF_ENV */
36 #ifdef AFS_VFSINCL_ENV
37 #define VFS
38 #ifdef  AFS_SUN5_ENV
39 #include <sys/fs/ufs_fs.h>
40 #else
41 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
42 #include <ufs/ufs/dinode.h>
43 #include <ufs/ffs/fs.h>
44 #else
45 #include <ufs/fs.h>
46 #endif
47 #endif
48 #else /* AFS_VFSINCL_ENV */
49 #if !defined(AFS_AIX_ENV) && !defined(AFS_LINUX20_ENV) && !defined(AFS_XBSD_ENV)
50 #include <sys/fs.h>
51 #endif
52 #endif /* AFS_VFSINCL_ENV */
53 #endif /* AFS_OSF_ENV */
54 #endif /* AFS_SGI_ENV */
55 #endif /* AFS_NT40_ENV */
56 #include <errno.h>
57 #include <sys/stat.h>
58 #include <stdio.h>
59 #ifdef AFS_NT40_ENV
60 #include <fcntl.h>
61 #else
62 #include <sys/file.h>
63 #endif
64 #include <dirent.h>
65 #ifdef  AFS_AIX_ENV
66 #include <sys/vfs.h>
67 #include <fcntl.h>
68 #else
69 #ifdef  AFS_HPUX_ENV
70 #include <fcntl.h>
71 #include <mntent.h>
72 #else
73 #if     defined(AFS_SUN_ENV) || defined(AFS_SUN5_ENV)
74 #ifdef  AFS_SUN5_ENV
75 #include <sys/mnttab.h>
76 #include <sys/mntent.h>
77 #else
78 #include <mntent.h>
79 #endif
80 #else
81 #ifndef AFS_NT40_ENV
82 #if defined(AFS_SGI_ENV)
83 #include <fcntl.h>
84 #include <mntent.h>
85
86 #else
87 #ifndef AFS_LINUX20_ENV
88 #include <fstab.h>              /* Need to find in libc 5, present in libc 6 */
89 #endif
90 #endif
91 #endif /* AFS_SGI_ENV */
92 #endif
93 #endif /* AFS_HPUX_ENV */
94 #endif
95 #ifndef AFS_NT40_ENV
96 #include <netdb.h>
97 #include <netinet/in.h>
98 #include <sys/wait.h>
99 #include <setjmp.h>
100 #ifndef ITIMER_REAL
101 #include <sys/time.h>
102 #endif /* ITIMER_REAL */
103 #endif /* AFS_NT40_ENV */
104 #if defined(AFS_SUN5_ENV) || defined(AFS_NT40_ENV) || defined(AFS_LINUX20_ENV)
105 #include <string.h>
106 #else
107 #include <strings.h>
108 #endif
109
110 #include "nfs.h"
111 #include <afs/errors.h>
112 #include "lock.h"
113 #include "lwp.h"
114 #include <afs/afssyscalls.h>
115 #include "ihandle.h"
116 #include <afs/afsutil.h>
117 #ifdef AFS_NT40_ENV
118 #include <io.h>
119 #endif
120 #include "daemon_com.h"
121 #include "fssync.h"
122 #include "salvsync.h"
123 #include "vnode.h"
124 #include "volume.h"
125 #include "partition.h"
126 #ifdef AFS_PTHREAD_ENV
127 #include <assert.h>
128 #else /* AFS_PTHREAD_ENV */
129 #include "afs/assert.h"
130 #endif /* AFS_PTHREAD_ENV */
131 #include "vutils.h"
132 #ifndef AFS_NT40_ENV
133 #include <dir/dir.h>
134 #include <unistd.h>
135 #endif
136
137 #if !defined(offsetof)
138 #include <stddef.h>
139 #endif
140
141 #ifdef O_LARGEFILE
142 #define afs_stat        stat64
143 #define afs_fstat       fstat64
144 #define afs_open        open64
145 #else /* !O_LARGEFILE */
146 #define afs_stat        stat
147 #define afs_fstat       fstat
148 #define afs_open        open
149 #endif /* !O_LARGEFILE */
150
151 #ifdef AFS_PTHREAD_ENV
152 pthread_mutex_t vol_glock_mutex;
153 pthread_mutex_t vol_trans_mutex;
154 pthread_cond_t vol_put_volume_cond;
155 pthread_cond_t vol_sleep_cond;
156 int vol_attach_threads = 1;
157 #endif /* AFS_PTHREAD_ENV */
158
159 #ifdef AFS_DEMAND_ATTACH_FS
160 pthread_mutex_t vol_salvsync_mutex;
161 #endif /* AFS_DEMAND_ATTACH_FS */
162
163 #ifdef  AFS_OSF_ENV
164 extern void *calloc(), *realloc();
165 #endif
166
167 /*@printflike@*/ extern void Log(const char *format, ...);
168
169 /* Forward declarations */
170 static Volume *attach2(Error * ec, VolId vid, char *path,
171                        register struct VolumeHeader *header,
172                        struct DiskPartition *partp, Volume * vp, 
173                        int isbusy, int mode);
174 static void ReallyFreeVolume(Volume * vp);
175 #ifdef AFS_DEMAND_ATTACH_FS
176 static void FreeVolume(Volume * vp);
177 #else /* !AFS_DEMAND_ATTACH_FS */
178 #define FreeVolume(vp) ReallyFreeVolume(vp)
179 static void VScanUpdateList(void);
180 #endif /* !AFS_DEMAND_ATTACH_FS */
181 static void VInitVolumeHeaderCache(afs_uint32 howMany);
182 static int GetVolumeHeader(register Volume * vp);
183 static void ReleaseVolumeHeader(register struct volHeader *hd);
184 static void FreeVolumeHeader(register Volume * vp);
185 static void AddVolumeToHashTable(register Volume * vp, int hashid);
186 static void DeleteVolumeFromHashTable(register Volume * vp);
187 static int VHold(Volume * vp);
188 static int VHold_r(Volume * vp);
189 static void VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class);
190 static void GetVolumePath(Error * ec, VolId volumeId, char **partitionp,
191                           char **namep);
192 static void VReleaseVolumeHandles_r(Volume * vp);
193 static void VCloseVolumeHandles_r(Volume * vp);
194 static void LoadVolumeHeader(Error * ec, Volume * vp);
195 static int VCheckOffline(register Volume * vp);
196 static int VCheckDetach(register Volume * vp);
197 static Volume * GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint, int flags);
198 static int VolumeExternalName_r(VolumeId volumeId, char * name, size_t len);
199
200 int LogLevel;                   /* Vice loglevel--not defined as extern so that it will be
201                                  * defined when not linked with vice, XXXX */
202 ProgramType programType;        /* The type of program using the package */
203
204 /* extended volume package statistics */
205 VolPkgStats VStats;
206
207
208 #define VOLUME_BITMAP_GROWSIZE  16      /* bytes, => 128vnodes */
209                                         /* Must be a multiple of 4 (1 word) !! */
210
211 /* this parameter needs to be tunable at runtime.
212  * 128 was really inadequate for largish servers -- at 16384 volumes this
213  * puts average chain length at 128, thus an average 65 deref's to find a volptr.
214  * talk about bad spatial locality...
215  *
216  * an AVL or splay tree might work a lot better, but we'll just increase
217  * the default hash table size for now
218  */
219 #define DEFAULT_VOLUME_HASH_SIZE 256   /* Must be a power of 2!! */
220 #define DEFAULT_VOLUME_HASH_MASK (DEFAULT_VOLUME_HASH_SIZE-1)
221 #define VOLUME_HASH(volumeId) (volumeId&(VolumeHashTable.Mask))
222
223 /*
224  * turn volume hash chains into partially ordered lists.
225  * when the threshold is exceeded between two adjacent elements,
226  * perform a chain rebalancing operation.
227  *
228  * keep the threshold high in order to keep cache line invalidates
229  * low "enough" on SMPs
230  */
231 #define VOLUME_HASH_REORDER_THRESHOLD 200
232
233 /*
234  * when possible, don't just reorder single elements, but reorder
235  * entire chains of elements at once.  a chain of elements that
236  * exceed the element previous to the pivot by at least CHAIN_THRESH 
237  * accesses are moved in front of the chain whose elements have at
238  * least CHAIN_THRESH less accesses than the pivot element
239  */
240 #define VOLUME_HASH_REORDER_CHAIN_THRESH (VOLUME_HASH_REORDER_THRESHOLD / 2)
241
242 #include "rx/rx_queue.h"
243
244
245 VolumeHashTable_t VolumeHashTable = {
246     DEFAULT_VOLUME_HASH_SIZE,
247     DEFAULT_VOLUME_HASH_MASK,
248     NULL
249 };
250
251
252 static void VInitVolumeHash(void);
253
254
255 #ifndef AFS_HAVE_FFS
256 /* This macro is used where an ffs() call does not exist. Was in util/ffs.c */
257 ffs(x)
258 {
259     afs_int32 ffs_i;
260     afs_int32 ffs_tmp = x;
261     if (ffs_tmp == 0)
262         return (-1);
263     else
264         for (ffs_i = 1;; ffs_i++) {
265             if (ffs_tmp & 1)
266                 return (ffs_i);
267             else
268                 ffs_tmp >>= 1;
269         }
270 }
271 #endif /* !AFS_HAVE_FFS */
272
273 #ifdef AFS_PTHREAD_ENV
274 typedef struct diskpartition_queue_t {
275     struct rx_queue queue;
276     struct DiskPartition * diskP;
277 } diskpartition_queue_t;
278 typedef struct vinitvolumepackage_thread_t {
279     struct rx_queue queue;
280     pthread_cond_t thread_done_cv;
281     int n_threads_complete;
282 } vinitvolumepackage_thread_t;
283 static void * VInitVolumePackageThread(void * args);
284 #endif /* AFS_PTHREAD_ENV */
285
286 static int VAttachVolumesByPartition(struct DiskPartition *diskP, 
287                                      int * nAttached, int * nUnattached);
288
289
290 #ifdef AFS_DEMAND_ATTACH_FS
291 /* demand attach fileserver extensions */
292
293 /* XXX
294  * in the future we will support serialization of VLRU state into the fs_state
295  * disk dumps
296  *
297  * these structures are the beginning of that effort
298  */
299 struct VLRU_DiskHeader {
300     struct versionStamp stamp;            /* magic and structure version number */
301     afs_uint32 mtime;                     /* time of dump to disk */
302     afs_uint32 num_records;               /* number of VLRU_DiskEntry records */
303 };
304
305 struct VLRU_DiskEntry {
306     afs_uint32 vid;                       /* volume ID */
307     afs_uint32 idx;                       /* generation */
308     afs_uint32 last_get;                  /* timestamp of last get */
309 };
310
311 struct VLRU_StartupQueue {
312     struct VLRU_DiskEntry * entry;
313     int num_entries;
314     int next_idx;
315 };
316
317 typedef struct vshutdown_thread_t {
318     struct rx_queue q;
319     pthread_mutex_t lock;
320     pthread_cond_t cv;
321     pthread_cond_t master_cv;
322     int n_threads;
323     int n_threads_complete;
324     int vol_remaining;
325     int schedule_version;
326     int pass;
327     byte n_parts;
328     byte n_parts_done_pass;
329     byte part_thread_target[VOLMAXPARTS+1];
330     byte part_done_pass[VOLMAXPARTS+1];
331     struct rx_queue * part_pass_head[VOLMAXPARTS+1];
332     int stats[4][VOLMAXPARTS+1];
333 } vshutdown_thread_t;
334 static void * VShutdownThread(void * args);
335
336
337 static Volume * VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode);
338 static int VCheckFree(Volume * vp);
339
340 /* VByP List */
341 static void AddVolumeToVByPList_r(Volume * vp);
342 static void DeleteVolumeFromVByPList_r(Volume * vp);
343 static void VVByPListBeginExclusive_r(struct DiskPartition * dp);
344 static void VVByPListEndExclusive_r(struct DiskPartition * dp);
345 static void VVByPListWait_r(struct DiskPartition * dp);
346
347 /* online salvager */
348 static int VCheckSalvage(register Volume * vp);
349 static int VUpdateSalvagePriority_r(Volume * vp);
350 static int VScheduleSalvage_r(Volume * vp);
351 static int VCancelSalvage_r(Volume * vp, int reason);
352
353 /* Volume hash table */
354 static void VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp);
355 static void VHashBeginExclusive_r(VolumeHashChainHead * head);
356 static void VHashEndExclusive_r(VolumeHashChainHead * head);
357 static void VHashWait_r(VolumeHashChainHead * head);
358
359 /* Volume state machine */
360 static void VCreateReservation_r(Volume * vp);
361 static void VCancelReservation_r(Volume * vp);
362 static void VWaitStateChange_r(Volume * vp);
363 static void VWaitExclusiveState_r(Volume * vp);
364 static int IsExclusiveState(VolState state);
365 static int IsErrorState(VolState state);
366 static int IsValidState(VolState state);
367
368 /* shutdown */
369 static int ShutdownVByPForPass_r(struct DiskPartition * dp, int pass);
370 static int ShutdownVolumeWalk_r(struct DiskPartition * dp, int pass,
371                                 struct rx_queue ** idx);
372 static void ShutdownController(vshutdown_thread_t * params);
373 static void ShutdownCreateSchedule(vshutdown_thread_t * params);
374
375 /* VLRU */
376 static void VLRU_ComputeConstants(void);
377 static void VInitVLRU(void);
378 static void VLRU_Init_Node_r(volatile Volume * vp);
379 static void VLRU_Add_r(volatile Volume * vp);
380 static void VLRU_Delete_r(volatile Volume * vp);
381 static void VLRU_UpdateAccess_r(volatile Volume * vp);
382 static void * VLRU_ScannerThread(void * args);
383 static void VLRU_Scan_r(int idx);
384 static void VLRU_Promote_r(int idx);
385 static void VLRU_Demote_r(int idx);
386 static void VLRU_SwitchQueues(volatile Volume * vp, int new_idx, int append);
387
388 /* soft detach */
389 static int VCheckSoftDetach(volatile Volume * vp, afs_uint32 thresh);
390 static int VCheckSoftDetachCandidate(volatile Volume * vp, afs_uint32 thresh);
391 static int VSoftDetachVolume_r(volatile Volume * vp, afs_uint32 thresh);
392 #endif /* AFS_DEMAND_ATTACH_FS */
393
394
395 struct Lock vol_listLock;       /* Lock obtained when listing volumes:  
396                                  * prevents a volume from being missed 
397                                  * if the volume is attached during a 
398                                  * list volumes */
399
400
401 static int TimeZoneCorrection;  /* Number of seconds west of GMT */
402
403 /* Common message used when the volume goes off line */
404 char *VSalvageMessage =
405     "Files in this volume are currently unavailable; call operations";
406
407 int VInit;                      /* 0 - uninitialized,
408                                  * 1 - initialized but not all volumes have been attached,
409                                  * 2 - initialized and all volumes have been attached,
410                                  * 3 - initialized, all volumes have been attached, and
411                                  * VConnectFS() has completed. */
412
413
414 bit32 VolumeCacheCheck;         /* Incremented everytime a volume goes on line--
415                                  * used to stamp volume headers and in-core
416                                  * vnodes.  When the volume goes on-line the
417                                  * vnode will be invalidated
418                                  * access only with VOL_LOCK held */
419
420
421
422
423 /***************************************************/
424 /* Startup routines                                */
425 /***************************************************/
426
427 int
428 VInitVolumePackage(ProgramType pt, afs_uint32 nLargeVnodes, afs_uint32 nSmallVnodes,
429                    int connect, afs_uint32 volcache)
430 {
431     int errors = 0;             /* Number of errors while finding vice partitions. */
432     struct timeval tv;
433     struct timezone tz;
434
435     programType = pt;
436
437 #ifdef AFS_DEMAND_ATTACH_FS
438     memset(&VStats, 0, sizeof(VStats));
439     VStats.hdr_cache_size = 200;
440 #endif
441
442     VInitPartitionPackage();
443     VInitVolumeHash();
444     VInitVnHashByVolume();
445 #ifdef AFS_DEMAND_ATTACH_FS
446     if (programType == fileServer) {
447         VInitVLRU();
448     } else {
449         VLRU_SetOptions(VLRU_SET_ENABLED, 0);
450     }
451 #endif
452
453 #ifdef AFS_PTHREAD_ENV
454     assert(pthread_mutex_init(&vol_glock_mutex, NULL) == 0);
455     assert(pthread_mutex_init(&vol_trans_mutex, NULL) == 0);
456     assert(pthread_cond_init(&vol_put_volume_cond, NULL) == 0);
457     assert(pthread_cond_init(&vol_sleep_cond, NULL) == 0);
458 #else /* AFS_PTHREAD_ENV */
459     IOMGR_Initialize();
460 #endif /* AFS_PTHREAD_ENV */
461     Lock_Init(&vol_listLock);
462
463     srandom(time(0));           /* For VGetVolumeInfo */
464     gettimeofday(&tv, &tz);
465     TimeZoneCorrection = tz.tz_minuteswest * 60;
466
467 #ifdef AFS_DEMAND_ATTACH_FS
468     assert(pthread_mutex_init(&vol_salvsync_mutex, NULL) == 0);
469 #endif /* AFS_DEMAND_ATTACH_FS */
470
471     /* Ok, we have done enough initialization that fileserver can 
472      * start accepting calls, even though the volumes may not be 
473      * available just yet.
474      */
475     VInit = 1;
476
477 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_SERVER)
478     if (programType == salvageServer) {
479         SALVSYNC_salvInit();
480     }
481 #endif /* AFS_DEMAND_ATTACH_FS */
482 #ifdef FSSYNC_BUILD_SERVER
483     if (programType == fileServer) {
484         FSYNC_fsInit();
485     }
486 #endif
487 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_CLIENT)
488     if (programType == fileServer) {
489         /* establish a connection to the salvager at this point */
490         assert(VConnectSALV() != 0);
491     }
492 #endif /* AFS_DEMAND_ATTACH_FS */
493
494     if (volcache > VStats.hdr_cache_size)
495         VStats.hdr_cache_size = volcache;
496     VInitVolumeHeaderCache(VStats.hdr_cache_size);
497
498     VInitVnodes(vLarge, nLargeVnodes);
499     VInitVnodes(vSmall, nSmallVnodes);
500
501
502     errors = VAttachPartitions();
503     if (errors)
504         return -1;
505
506     if (programType == fileServer) {
507         struct DiskPartition *diskP;
508 #ifdef AFS_PTHREAD_ENV
509         struct vinitvolumepackage_thread_t params;
510         struct diskpartition_queue_t * dpq;
511         int i, threads, parts;
512         pthread_t tid;
513         pthread_attr_t attrs;
514
515         assert(pthread_cond_init(&params.thread_done_cv,NULL) == 0);
516         queue_Init(&params);
517         params.n_threads_complete = 0;
518
519         /* create partition work queue */
520         for (parts=0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
521             dpq = (diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
522             assert(dpq != NULL);
523             dpq->diskP = diskP;
524             queue_Append(&params,dpq);
525         }
526
527         threads = MIN(parts, vol_attach_threads);
528
529         if (threads > 1) {
530             /* spawn off a bunch of initialization threads */
531             assert(pthread_attr_init(&attrs) == 0);
532             assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
533
534             Log("VInitVolumePackage: beginning parallel fileserver startup\n");
535 #ifdef AFS_DEMAND_ATTACH_FS
536             Log("VInitVolumePackage: using %d threads to pre-attach volumes on %d partitions\n",
537                 threads, parts);
538 #else /* AFS_DEMAND_ATTACH_FS */
539             Log("VInitVolumePackage: using %d threads to attach volumes on %d partitions\n",
540                 threads, parts);
541 #endif /* AFS_DEMAND_ATTACH_FS */
542
543             VOL_LOCK;
544             for (i=0; i < threads; i++) {
545                 assert(pthread_create
546                        (&tid, &attrs, &VInitVolumePackageThread,
547                         &params) == 0);
548             }
549
550             while(params.n_threads_complete < threads) {
551                 pthread_cond_wait(&params.thread_done_cv,&vol_glock_mutex);
552             }
553             VOL_UNLOCK;
554
555             assert(pthread_attr_destroy(&attrs) == 0);
556         } else {
557             /* if we're only going to run one init thread, don't bother creating
558              * another LWP */
559             Log("VInitVolumePackage: beginning single-threaded fileserver startup\n");
560 #ifdef AFS_DEMAND_ATTACH_FS
561             Log("VInitVolumePackage: using 1 thread to pre-attach volumes on %d partition(s)\n",
562                 parts);
563 #else /* AFS_DEMAND_ATTACH_FS */
564             Log("VInitVolumePackage: using 1 thread to attach volumes on %d partition(s)\n",
565                 parts);
566 #endif /* AFS_DEMAND_ATTACH_FS */
567
568             VInitVolumePackageThread(&params);
569         }
570
571         assert(pthread_cond_destroy(&params.thread_done_cv) == 0);
572
573 #else /* AFS_PTHREAD_ENV */
574         DIR *dirp;
575         struct dirent *dp;
576
577         /* Attach all the volumes in this partition */
578         for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
579             int nAttached = 0, nUnattached = 0;
580             assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
581         }
582 #endif /* AFS_PTHREAD_ENV */
583     }
584
585     VInit = 2;                  /* Initialized, and all volumes have been attached */
586 #ifdef FSSYNC_BUILD_CLIENT
587     if (programType == volumeUtility && connect) {
588         if (!VConnectFS()) {
589             Log("Unable to connect to file server; aborted\n");
590             exit(1);
591         }
592     }
593 #ifdef AFS_DEMAND_ATTACH_FS
594     else if (programType == salvageServer) {
595         if (!VConnectFS()) {
596             Log("Unable to connect to file server; aborted\n");
597             exit(1);
598         }
599     }
600 #endif /* AFS_DEMAND_ATTACH_FS */
601 #endif /* FSSYNC_BUILD_CLIENT */
602     return 0;
603 }
604
605 #ifdef AFS_PTHREAD_ENV
606 static void *
607 VInitVolumePackageThread(void * args) {
608     int errors = 0;             /* Number of errors while finding vice partitions. */
609
610     DIR *dirp;
611     struct dirent *dp;
612     struct DiskPartition *diskP;
613     struct vinitvolumepackage_thread_t * params;
614     struct diskpartition_queue_t * dpq;
615
616     params = (vinitvolumepackage_thread_t *) args;
617
618
619     VOL_LOCK;
620     /* Attach all the volumes in this partition */
621     while (queue_IsNotEmpty(params)) {
622         int nAttached = 0, nUnattached = 0;
623
624         dpq = queue_First(params,diskpartition_queue_t);
625         queue_Remove(dpq);
626         VOL_UNLOCK;
627         diskP = dpq->diskP;
628         free(dpq);
629
630         assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
631
632         VOL_LOCK;
633     }
634
635     params->n_threads_complete++;
636     pthread_cond_signal(&params->thread_done_cv);
637     VOL_UNLOCK;
638     return NULL;
639 }
640 #endif /* AFS_PTHREAD_ENV */
641
642 /*
643  * attach all volumes on a given disk partition
644  */
645 static int
646 VAttachVolumesByPartition(struct DiskPartition *diskP, int * nAttached, int * nUnattached)
647 {
648   DIR * dirp;
649   struct dirent * dp;
650   int ret = 0;
651
652   Log("Partition %s: attaching volumes\n", diskP->name);
653   dirp = opendir(VPartitionPath(diskP));
654   if (!dirp) {
655     Log("opendir on Partition %s failed!\n", diskP->name);
656     return 1;
657   }
658
659   while ((dp = readdir(dirp))) {
660     char *p;
661     p = strrchr(dp->d_name, '.');
662     if (p != NULL && strcmp(p, VHDREXT) == 0) {
663       Error error;
664       Volume *vp;
665 #ifdef AFS_DEMAND_ATTACH_FS
666       vp = VPreAttachVolumeByName(&error, diskP->name, dp->d_name,
667                                   V_VOLUPD);
668 #else /* AFS_DEMAND_ATTACH_FS */
669       vp = VAttachVolumeByName(&error, diskP->name, dp->d_name,
670                                V_VOLUPD);
671 #endif /* AFS_DEMAND_ATTACH_FS */
672       (*(vp ? nAttached : nUnattached))++;
673       if (error == VOFFLINE)
674         Log("Volume %d stays offline (/vice/offline/%s exists)\n", VolumeNumber(dp->d_name), dp->d_name);
675       else if (LogLevel >= 5) {
676         Log("Partition %s: attached volume %d (%s)\n",
677             diskP->name, VolumeNumber(dp->d_name),
678             dp->d_name);
679       }
680 #if !defined(AFS_DEMAND_ATTACH_FS)
681       if (vp) {
682         VPutVolume(vp);
683       }
684 #endif /* AFS_DEMAND_ATTACH_FS */
685     }
686   }
687
688   Log("Partition %s: attached %d volumes; %d volumes not attached\n", diskP->name, *nAttached, *nUnattached);
689   closedir(dirp);
690   return ret;
691 }
692
693
694 /***************************************************/
695 /* Shutdown routines                               */
696 /***************************************************/
697
698 /*
699  * demand attach fs
700  * highly multithreaded volume package shutdown
701  *
702  * with the demand attach fileserver extensions,
703  * VShutdown has been modified to be multithreaded.
704  * In order to achieve optimal use of many threads,
705  * the shutdown code involves one control thread and
706  * n shutdown worker threads.  The control thread
707  * periodically examines the number of volumes available
708  * for shutdown on each partition, and produces a worker
709  * thread allocation schedule.  The idea is to eliminate
710  * redundant scheduling computation on the workers by
711  * having a single master scheduler.
712  *
713  * The scheduler's objectives are:
714  * (1) fairness
715  *   each partition with volumes remaining gets allocated
716  *   at least 1 thread (assuming sufficient threads)
717  * (2) performance
718  *   threads are allocated proportional to the number of
719  *   volumes remaining to be offlined.  This ensures that
720  *   the OS I/O scheduler has many requests to elevator
721  *   seek on partitions that will (presumably) take the
722  *   longest amount of time (from now) to finish shutdown
723  * (3) keep threads busy
724  *   when there are extra threads, they are assigned to
725  *   partitions using a simple round-robin algorithm
726  *
727  * In the future, we may wish to add the ability to adapt
728  * to the relative performance patterns of each disk
729  * partition.
730  *
731  *
732  * demand attach fs
733  * multi-step shutdown process
734  *
735  * demand attach shutdown is a four-step process. Each
736  * shutdown "pass" shuts down increasingly more difficult
737  * volumes.  The main purpose is to achieve better cache
738  * utilization during shutdown.
739  *
740  * pass 0
741  *   shutdown volumes in the unattached, pre-attached
742  *   and error states
743  * pass 1
744  *   shutdown attached volumes with cached volume headers
745  * pass 2
746  *   shutdown all volumes in non-exclusive states
747  * pass 3
748  *   shutdown all remaining volumes
749  */
750
751 void
752 VShutdown_r(void)
753 {
754     int i;
755     register Volume *vp, *np;
756     register afs_int32 code;
757 #ifdef AFS_DEMAND_ATTACH_FS
758     struct DiskPartition * diskP;
759     struct diskpartition_queue_t * dpq;
760     vshutdown_thread_t params;
761     pthread_t tid;
762     pthread_attr_t attrs;
763
764     memset(&params, 0, sizeof(vshutdown_thread_t));
765
766     for (params.n_parts=0, diskP = DiskPartitionList;
767          diskP; diskP = diskP->next, params.n_parts++);
768
769     Log("VShutdown:  shutting down on-line volumes on %d partition%s...\n", 
770         params.n_parts, params.n_parts > 1 ? "s" : "");
771
772     if (vol_attach_threads > 1) {
773         /* prepare for parallel shutdown */
774         params.n_threads = vol_attach_threads;
775         assert(pthread_mutex_init(&params.lock, NULL) == 0);
776         assert(pthread_cond_init(&params.cv, NULL) == 0);
777         assert(pthread_cond_init(&params.master_cv, NULL) == 0);
778         assert(pthread_attr_init(&attrs) == 0);
779         assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
780         queue_Init(&params);
781
782         /* setup the basic partition information structures for
783          * parallel shutdown */
784         for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
785             /* XXX debug */
786             struct rx_queue * qp, * nqp;
787             Volume * vp;
788             int count = 0;
789
790             VVByPListWait_r(diskP);
791             VVByPListBeginExclusive_r(diskP);
792
793             /* XXX debug */
794             for (queue_Scan(&diskP->vol_list, qp, nqp, rx_queue)) {
795                 vp = (Volume *)((char *)qp - offsetof(Volume, vol_list));
796                 if (vp->header)
797                     count++;
798             }
799             Log("VShutdown: partition %s has %d volumes with attached headers\n",
800                 VPartitionPath(diskP), count);
801                 
802
803             /* build up the pass 0 shutdown work queue */
804             dpq = (struct diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
805             assert(dpq != NULL);
806             dpq->diskP = diskP;
807             queue_Prepend(&params, dpq);
808
809             params.part_pass_head[diskP->device] = queue_First(&diskP->vol_list, rx_queue);
810         }
811
812         Log("VShutdown:  beginning parallel fileserver shutdown\n");
813         Log("VShutdown:  using %d threads to offline volumes on %d partition%s\n",
814             vol_attach_threads, params.n_parts, params.n_parts > 1 ? "s" : "" );
815
816         /* do pass 0 shutdown */
817         assert(pthread_mutex_lock(&params.lock) == 0);
818         for (i=0; i < params.n_threads; i++) {
819             assert(pthread_create
820                    (&tid, &attrs, &VShutdownThread,
821                     &params) == 0);
822         }
823         
824         /* wait for all the pass 0 shutdowns to complete */
825         while (params.n_threads_complete < params.n_threads) {
826             assert(pthread_cond_wait(&params.master_cv, &params.lock) == 0);
827         }
828         params.n_threads_complete = 0;
829         params.pass = 1;
830         assert(pthread_cond_broadcast(&params.cv) == 0);
831         assert(pthread_mutex_unlock(&params.lock) == 0);
832
833         Log("VShutdown:  pass 0 completed using the 1 thread per partition algorithm\n");
834         Log("VShutdown:  starting passes 1 through 3 using finely-granular mp-fast algorithm\n");
835
836         /* run the parallel shutdown scheduler. it will drop the glock internally */
837         ShutdownController(&params);
838         
839         /* wait for all the workers to finish pass 3 and terminate */
840         while (params.pass < 4) {
841             assert(pthread_cond_wait(&params.cv, &vol_glock_mutex) == 0);
842         }
843         
844         assert(pthread_attr_destroy(&attrs) == 0);
845         assert(pthread_cond_destroy(&params.cv) == 0);
846         assert(pthread_cond_destroy(&params.master_cv) == 0);
847         assert(pthread_mutex_destroy(&params.lock) == 0);
848
849         /* drop the VByPList exclusive reservations */
850         for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
851             VVByPListEndExclusive_r(diskP);
852             Log("VShutdown:  %s stats : (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
853                 VPartitionPath(diskP),
854                 params.stats[0][diskP->device],
855                 params.stats[1][diskP->device],
856                 params.stats[2][diskP->device],
857                 params.stats[3][diskP->device]);
858         }
859
860         Log("VShutdown:  shutdown finished using %d threads\n", params.n_threads);
861     } else {
862         /* if we're only going to run one shutdown thread, don't bother creating
863          * another LWP */
864         Log("VShutdown:  beginning single-threaded fileserver shutdown\n");
865
866         for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
867             VShutdownByPartition_r(diskP);
868         }
869     }
870
871     Log("VShutdown:  complete.\n");
872 #else /* AFS_DEMAND_ATTACH_FS */
873     Log("VShutdown:  shutting down on-line volumes...\n");
874     for (i = 0; i < VolumeHashTable.Size; i++) {
875         /* try to hold first volume in the hash table */
876         for (queue_Scan(&VolumeHashTable.Table[i],vp,np,Volume)) {
877             code = VHold_r(vp);
878             if (code == 0) {
879                 if (LogLevel >= 5)
880                     Log("VShutdown:  Attempting to take volume %u offline.\n",
881                         vp->hashid);
882                 
883                 /* next, take the volume offline (drops reference count) */
884                 VOffline_r(vp, "File server was shut down");
885             }
886         }
887     }
888     Log("VShutdown:  complete.\n");
889 #endif /* AFS_DEMAND_ATTACH_FS */
890 }
891
892 void
893 VShutdown(void)
894 {
895     VOL_LOCK;
896     VShutdown_r();
897     VOL_UNLOCK;
898 }
899
900 #ifdef AFS_DEMAND_ATTACH_FS
901 /*
902  * demand attach fs
903  * shutdown control thread
904  */
905 static void
906 ShutdownController(vshutdown_thread_t * params)
907 {
908     /* XXX debug */
909     struct DiskPartition * diskP;
910     Device id;
911     vshutdown_thread_t shadow;
912
913     ShutdownCreateSchedule(params);
914
915     while ((params->pass < 4) &&
916            (params->n_threads_complete < params->n_threads)) {
917         /* recompute schedule once per second */
918
919         memcpy(&shadow, params, sizeof(vshutdown_thread_t));
920
921         VOL_UNLOCK;
922         /* XXX debug */
923         Log("ShutdownController:  schedule version=%d, vol_remaining=%d, pass=%d\n",
924             shadow.schedule_version, shadow.vol_remaining, shadow.pass);
925         Log("ShutdownController:  n_threads_complete=%d, n_parts_done_pass=%d\n",
926             shadow.n_threads_complete, shadow.n_parts_done_pass);
927         for (diskP = DiskPartitionList; diskP; diskP=diskP->next) {
928             id = diskP->device;
929             Log("ShutdownController:  part[%d] : (len=%d, thread_target=%d, done_pass=%d, pass_head=%p)\n",
930                 id, 
931                 diskP->vol_list.len,
932                 shadow.part_thread_target[id], 
933                 shadow.part_done_pass[id], 
934                 shadow.part_pass_head[id]);
935         }
936
937         sleep(1);
938         VOL_LOCK;
939
940         ShutdownCreateSchedule(params);
941     }
942 }
943
944 /* create the shutdown thread work schedule.
945  * this scheduler tries to implement fairness
946  * by allocating at least 1 thread to each 
947  * partition with volumes to be shutdown,
948  * and then it attempts to allocate remaining
949  * threads based upon the amount of work left
950  */
951 static void
952 ShutdownCreateSchedule(vshutdown_thread_t * params)
953 {
954     struct DiskPartition * diskP;
955     int sum, thr_workload, thr_left;
956     int part_residue[VOLMAXPARTS+1];
957     Device id;
958
959     /* compute the total number of outstanding volumes */
960     sum = 0;
961     for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
962         sum += diskP->vol_list.len;
963     }
964     
965     params->schedule_version++;
966     params->vol_remaining = sum;
967
968     if (!sum)
969         return;
970
971     /* compute average per-thread workload */
972     thr_workload = sum / params->n_threads;
973     if (sum % params->n_threads)
974         thr_workload++;
975
976     thr_left = params->n_threads;
977     memset(&part_residue, 0, sizeof(part_residue));
978
979     /* for fairness, give every partition with volumes remaining
980      * at least one thread */
981     for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
982         id = diskP->device;
983         if (diskP->vol_list.len) {
984             params->part_thread_target[id] = 1;
985             thr_left--;
986         } else {
987             params->part_thread_target[id] = 0;
988         }
989     }
990
991     if (thr_left && thr_workload) {
992         /* compute length-weighted workloads */
993         int delta;
994
995         for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
996             id = diskP->device;
997             delta = (diskP->vol_list.len / thr_workload) -
998                 params->part_thread_target[id];
999             if (delta < 0) {
1000                 continue;
1001             }
1002             if (delta < thr_left) {
1003                 params->part_thread_target[id] += delta;
1004                 thr_left -= delta;
1005             } else {
1006                 params->part_thread_target[id] += thr_left;
1007                 thr_left = 0;
1008                 break;
1009             }
1010         }
1011     }
1012
1013     if (thr_left) {
1014         /* try to assign any leftover threads to partitions that
1015          * had volume lengths closer to needing thread_target+1 */
1016         int max_residue, max_id;
1017
1018         /* compute the residues */
1019         for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1020             id = diskP->device;
1021             part_residue[id] = diskP->vol_list.len - 
1022                 (params->part_thread_target[id] * thr_workload);
1023         }
1024
1025         /* now try to allocate remaining threads to partitions with the
1026          * highest residues */
1027         while (thr_left) {
1028             max_residue = 0;
1029             for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1030                 id = diskP->device;
1031                 if (part_residue[id] > max_residue) {
1032                     max_residue = part_residue[id];
1033                     max_id = id;
1034                 }
1035             }
1036
1037             if (!max_residue) {
1038                 break;
1039             }
1040
1041             params->part_thread_target[max_id]++;
1042             thr_left--;
1043             part_residue[max_id] = 0;
1044         }
1045     }
1046
1047     if (thr_left) {
1048         /* punt and give any remaining threads equally to each partition */
1049         int alloc;
1050         if (thr_left >= params->n_parts) {
1051             alloc = thr_left / params->n_parts;
1052             for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1053                 id = diskP->device;
1054                 params->part_thread_target[id] += alloc;
1055                 thr_left -= alloc;
1056             }
1057         }
1058
1059         /* finish off the last of the threads */
1060         for (diskP = DiskPartitionList; thr_left && diskP; diskP = diskP->next) {
1061             id = diskP->device;
1062             params->part_thread_target[id]++;
1063             thr_left--;
1064         }
1065     }
1066 }
1067
1068 /* worker thread for parallel shutdown */
1069 static void *
1070 VShutdownThread(void * args)
1071 {
1072     struct rx_queue *qp;
1073     Volume * vp;
1074     vshutdown_thread_t * params;
1075     int part, code, found, pass, schedule_version_save, count;
1076     struct DiskPartition *diskP;
1077     struct diskpartition_queue_t * dpq;
1078     Device id;
1079
1080     params = (vshutdown_thread_t *) args;
1081
1082     /* acquire the shutdown pass 0 lock */
1083     assert(pthread_mutex_lock(&params->lock) == 0);
1084
1085     /* if there's still pass 0 work to be done,
1086      * get a work entry, and do a pass 0 shutdown */
1087     if (queue_IsNotEmpty(params)) {
1088         dpq = queue_First(params, diskpartition_queue_t);
1089         queue_Remove(dpq);
1090         assert(pthread_mutex_unlock(&params->lock) == 0);
1091         diskP = dpq->diskP;
1092         free(dpq);
1093         id = diskP->device;
1094
1095         count = 0;
1096         while (ShutdownVolumeWalk_r(diskP, 0, &params->part_pass_head[id]))
1097             count++;
1098         params->stats[0][diskP->device] = count;
1099         assert(pthread_mutex_lock(&params->lock) == 0);
1100     }
1101
1102     params->n_threads_complete++;
1103     if (params->n_threads_complete == params->n_threads) {
1104       /* notify control thread that all workers have completed pass 0 */
1105       assert(pthread_cond_signal(&params->master_cv) == 0);
1106     }
1107     while (params->pass == 0) {
1108       assert(pthread_cond_wait(&params->cv, &params->lock) == 0);
1109     }
1110
1111     /* switch locks */
1112     assert(pthread_mutex_unlock(&params->lock) == 0);
1113     VOL_LOCK;
1114
1115     pass = params->pass;
1116     assert(pass > 0);
1117
1118     /* now escalate through the more complicated shutdowns */
1119     while (pass <= 3) {
1120         schedule_version_save = params->schedule_version;
1121         found = 0;
1122         /* find a disk partition to work on */
1123         for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1124             id = diskP->device;
1125             if (params->part_thread_target[id] && !params->part_done_pass[id]) {
1126                 params->part_thread_target[id]--;
1127                 found = 1;
1128                 break;
1129             }
1130         }
1131         
1132         if (!found) {
1133             /* hmm. for some reason the controller thread couldn't find anything for 
1134              * us to do. let's see if there's anything we can do */
1135             for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1136                 id = diskP->device;
1137                 if (diskP->vol_list.len && !params->part_done_pass[id]) {
1138                     found = 1;
1139                     break;
1140                 } else if (!params->part_done_pass[id]) {
1141                     params->part_done_pass[id] = 1;
1142                     params->n_parts_done_pass++;
1143                     if (pass == 3) {
1144                         Log("VShutdown:  done shutting down volumes on partition %s.\n",
1145                             VPartitionPath(diskP));
1146                     }
1147                 }
1148             }
1149         }
1150         
1151         /* do work on this partition until either the controller
1152          * creates a new schedule, or we run out of things to do
1153          * on this partition */
1154         if (found) {
1155             count = 0;
1156             while (!params->part_done_pass[id] &&
1157                    (schedule_version_save == params->schedule_version)) {
1158                 /* ShutdownVolumeWalk_r will drop the glock internally */
1159                 if (!ShutdownVolumeWalk_r(diskP, pass, &params->part_pass_head[id])) {
1160                     if (!params->part_done_pass[id]) {
1161                         params->part_done_pass[id] = 1;
1162                         params->n_parts_done_pass++;
1163                         if (pass == 3) {
1164                             Log("VShutdown:  done shutting down volumes on partition %s.\n",
1165                                 VPartitionPath(diskP));
1166                         }
1167                     }
1168                     break;
1169                 }
1170                 count++;
1171             }
1172
1173             params->stats[pass][id] += count;
1174         } else {
1175             /* ok, everyone is done this pass, proceed */
1176
1177             /* barrier lock */
1178             params->n_threads_complete++;
1179             while (params->pass == pass) {
1180                 if (params->n_threads_complete == params->n_threads) {
1181                     /* we are the last thread to complete, so we will
1182                      * reinitialize worker pool state for the next pass */
1183                     params->n_threads_complete = 0;
1184                     params->n_parts_done_pass = 0;
1185                     params->pass++;
1186                     for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1187                         id = diskP->device;
1188                         params->part_done_pass[id] = 0;
1189                         params->part_pass_head[id] = queue_First(&diskP->vol_list, rx_queue);
1190                     }
1191
1192                     /* compute a new thread schedule before releasing all the workers */
1193                     ShutdownCreateSchedule(params);
1194
1195                     /* wake up all the workers */
1196                     assert(pthread_cond_broadcast(&params->cv) == 0);
1197
1198                     VOL_UNLOCK;
1199                     Log("VShutdown:  pass %d completed using %d threads on %d partitions\n",
1200                         pass, params->n_threads, params->n_parts);
1201                     VOL_LOCK;
1202                 } else {
1203                     assert(pthread_cond_wait(&params->cv, &vol_glock_mutex) == 0);
1204                 }
1205             }
1206             pass = params->pass;
1207         }
1208         
1209         /* for fairness */
1210         VOL_UNLOCK;
1211         pthread_yield();
1212         VOL_LOCK;
1213     }
1214
1215     VOL_UNLOCK;
1216
1217     return NULL;
1218 }
1219
1220 /* shut down all volumes on a given disk partition 
1221  *
1222  * note that this function will not allow mp-fast
1223  * shutdown of a partition */
1224 int
1225 VShutdownByPartition_r(struct DiskPartition * dp)
1226 {
1227     int pass, retVal;
1228     int pass_stats[4];
1229     int total;
1230
1231     /* wait for other exclusive ops to finish */
1232     VVByPListWait_r(dp);
1233
1234     /* begin exclusive access */
1235     VVByPListBeginExclusive_r(dp);
1236
1237     /* pick the low-hanging fruit first,
1238      * then do the complicated ones last 
1239      * (has the advantage of keeping
1240      *  in-use volumes up until the bitter end) */
1241     for (pass = 0, total=0; pass < 4; pass++) {
1242         pass_stats[pass] = ShutdownVByPForPass_r(dp, pass);
1243         total += pass_stats[pass];
1244     }
1245
1246     /* end exclusive access */
1247     VVByPListEndExclusive_r(dp);
1248
1249     Log("VShutdownByPartition:  shut down %d volumes on %s (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1250         total, VPartitionPath(dp), pass_stats[0], pass_stats[1], pass_stats[2], pass_stats[3]);
1251
1252     return retVal;
1253 }
1254
1255 /* internal shutdown functionality
1256  *
1257  * for multi-pass shutdown:
1258  * 0 to only "shutdown" {pre,un}attached and error state volumes
1259  * 1 to also shutdown attached volumes w/ volume header loaded
1260  * 2 to also shutdown attached volumes w/o volume header loaded
1261  * 3 to also shutdown exclusive state volumes 
1262  *
1263  * caller MUST hold exclusive access on the hash chain
1264  * because we drop vol_glock_mutex internally
1265  * 
1266  * this function is reentrant for passes 1--3 
1267  * (e.g. multiple threads can cooperate to 
1268  *  shutdown a partition mp-fast)
1269  *
1270  * pass 0 is not scaleable because the volume state data is
1271  * synchronized by vol_glock mutex, and the locking overhead
1272  * is too high to drop the lock long enough to do linked list
1273  * traversal
1274  */
1275 static int
1276 ShutdownVByPForPass_r(struct DiskPartition * dp, int pass)
1277 {
1278     struct rx_queue * q = queue_First(&dp->vol_list, rx_queue);
1279     register int i = 0;
1280
1281     while (ShutdownVolumeWalk_r(dp, pass, &q))
1282         i++;
1283
1284     return i;
1285 }
1286
1287 /* conditionally shutdown one volume on partition dp
1288  * returns 1 if a volume was shutdown in this pass,
1289  * 0 otherwise */
1290 static int
1291 ShutdownVolumeWalk_r(struct DiskPartition * dp, int pass,
1292                      struct rx_queue ** idx)
1293 {
1294     struct rx_queue *qp, *nqp;
1295     Volume * vp;
1296
1297     qp = *idx;
1298
1299     for (queue_ScanFrom(&dp->vol_list, qp, qp, nqp, rx_queue)) {
1300         vp = (Volume *) (((char *)qp) - offsetof(Volume, vol_list));
1301         
1302         switch (pass) {
1303         case 0:
1304             if ((V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1305                 (V_attachState(vp) != VOL_STATE_ERROR) &&
1306                 (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1307                 break;
1308             }
1309         case 1:
1310             if ((V_attachState(vp) == VOL_STATE_ATTACHED) &&
1311                 (vp->header == NULL)) {
1312                 break;
1313             }
1314         case 2:
1315             if (IsExclusiveState(V_attachState(vp))) {
1316                 break;
1317             }
1318         case 3:
1319             *idx = nqp;
1320             DeleteVolumeFromVByPList_r(vp);
1321             VShutdownVolume_r(vp);
1322             vp = NULL;
1323             return 1;
1324         }
1325     }
1326
1327     return 0;
1328 }
1329
1330 /*
1331  * shutdown a specific volume
1332  */
1333 /* caller MUST NOT hold a heavyweight ref on vp */
1334 int
1335 VShutdownVolume_r(Volume * vp)
1336 {
1337     int code;
1338
1339     VCreateReservation_r(vp);
1340
1341     if (LogLevel >= 5) {
1342         Log("VShutdownVolume_r:  vid=%u, device=%d, state=%hu\n",
1343             vp->hashid, vp->partition->device, V_attachState(vp));
1344     }
1345
1346     /* wait for other blocking ops to finish */
1347     VWaitExclusiveState_r(vp);
1348
1349     assert(IsValidState(V_attachState(vp)));
1350     
1351     switch(V_attachState(vp)) {
1352     case VOL_STATE_SALVAGING:
1353         /* make sure salvager knows we don't want
1354          * the volume back */
1355         VCancelSalvage_r(vp, SALVSYNC_SHUTDOWN);
1356     case VOL_STATE_PREATTACHED:
1357     case VOL_STATE_ERROR:
1358         VChangeState_r(vp, VOL_STATE_UNATTACHED);
1359     case VOL_STATE_UNATTACHED:
1360         break;
1361     case VOL_STATE_GOING_OFFLINE:
1362     case VOL_STATE_SHUTTING_DOWN:
1363     case VOL_STATE_ATTACHED:
1364         code = VHold_r(vp);
1365         if (!code) {
1366             if (LogLevel >= 5)
1367                 Log("VShutdown:  Attempting to take volume %u offline.\n",
1368                     vp->hashid);
1369
1370             /* take the volume offline (drops reference count) */
1371             VOffline_r(vp, "File server was shut down");
1372         }
1373         break;
1374     }
1375     
1376     VCancelReservation_r(vp);
1377     vp = NULL;
1378     return 0;
1379 }
1380 #endif /* AFS_DEMAND_ATTACH_FS */
1381
1382
1383 /***************************************************/
1384 /* Header I/O routines                             */
1385 /***************************************************/
1386
1387 /* open a descriptor for the inode (h),
1388  * read in an on-disk structure into buffer (to) of size (size),
1389  * verify versionstamp in structure has magic (magic) and
1390  * optionally verify version (version) if (version) is nonzero
1391  */
1392 static void
1393 ReadHeader(Error * ec, IHandle_t * h, char *to, int size, bit32 magic,
1394            bit32 version)
1395 {
1396     struct versionStamp *vsn;
1397     FdHandle_t *fdP;
1398
1399     *ec = 0;
1400     if (h == NULL) {
1401         *ec = VSALVAGE;
1402         return;
1403     }
1404
1405     fdP = IH_OPEN(h);
1406     if (fdP == NULL) {
1407         *ec = VSALVAGE;
1408         return;
1409     }
1410
1411     if (FDH_SEEK(fdP, 0, SEEK_SET) < 0) {
1412         *ec = VSALVAGE;
1413         FDH_REALLYCLOSE(fdP);
1414         return;
1415     }
1416     vsn = (struct versionStamp *)to;
1417     if (FDH_READ(fdP, to, size) != size || vsn->magic != magic) {
1418         *ec = VSALVAGE;
1419         FDH_REALLYCLOSE(fdP);
1420         return;
1421     }
1422     FDH_CLOSE(fdP);
1423
1424     /* Check is conditional, in case caller wants to inspect version himself */
1425     if (version && vsn->version != version) {
1426         *ec = VSALVAGE;
1427     }
1428 }
1429
1430 void
1431 WriteVolumeHeader_r(Error * ec, Volume * vp)
1432 {
1433     IHandle_t *h = V_diskDataHandle(vp);
1434     FdHandle_t *fdP;
1435
1436     *ec = 0;
1437
1438     fdP = IH_OPEN(h);
1439     if (fdP == NULL) {
1440         *ec = VSALVAGE;
1441         return;
1442     }
1443     if (FDH_SEEK(fdP, 0, SEEK_SET) < 0) {
1444         *ec = VSALVAGE;
1445         FDH_REALLYCLOSE(fdP);
1446         return;
1447     }
1448     if (FDH_WRITE(fdP, (char *)&V_disk(vp), sizeof(V_disk(vp)))
1449         != sizeof(V_disk(vp))) {
1450         *ec = VSALVAGE;
1451         FDH_REALLYCLOSE(fdP);
1452         return;
1453     }
1454     FDH_CLOSE(fdP);
1455 }
1456
1457 /* VolumeHeaderToDisk
1458  * Allows for storing 64 bit inode numbers in on-disk volume header
1459  * file.
1460  */
1461 /* convert in-memory representation of a volume header to the
1462  * on-disk representation of a volume header */
1463 void
1464 VolumeHeaderToDisk(VolumeDiskHeader_t * dh, VolumeHeader_t * h)
1465 {
1466
1467     memset((char *)dh, 0, sizeof(VolumeDiskHeader_t));
1468     dh->stamp = h->stamp;
1469     dh->id = h->id;
1470     dh->parent = h->parent;
1471
1472 #ifdef AFS_64BIT_IOPS_ENV
1473     dh->volumeInfo_lo = (afs_int32) h->volumeInfo & 0xffffffff;
1474     dh->volumeInfo_hi = (afs_int32) (h->volumeInfo >> 32) & 0xffffffff;
1475     dh->smallVnodeIndex_lo = (afs_int32) h->smallVnodeIndex & 0xffffffff;
1476     dh->smallVnodeIndex_hi =
1477         (afs_int32) (h->smallVnodeIndex >> 32) & 0xffffffff;
1478     dh->largeVnodeIndex_lo = (afs_int32) h->largeVnodeIndex & 0xffffffff;
1479     dh->largeVnodeIndex_hi =
1480         (afs_int32) (h->largeVnodeIndex >> 32) & 0xffffffff;
1481     dh->linkTable_lo = (afs_int32) h->linkTable & 0xffffffff;
1482     dh->linkTable_hi = (afs_int32) (h->linkTable >> 32) & 0xffffffff;
1483 #else
1484     dh->volumeInfo_lo = h->volumeInfo;
1485     dh->smallVnodeIndex_lo = h->smallVnodeIndex;
1486     dh->largeVnodeIndex_lo = h->largeVnodeIndex;
1487     dh->linkTable_lo = h->linkTable;
1488 #endif
1489 }
1490
1491 /* DiskToVolumeHeader
1492  * Converts an on-disk representation of a volume header to
1493  * the in-memory representation of a volume header.
1494  *
1495  * Makes the assumption that AFS has *always* 
1496  * zero'd the volume header file so that high parts of inode
1497  * numbers are 0 in older (SGI EFS) volume header files.
1498  */
1499 void
1500 DiskToVolumeHeader(VolumeHeader_t * h, VolumeDiskHeader_t * dh)
1501 {
1502     memset((char *)h, 0, sizeof(VolumeHeader_t));
1503     h->stamp = dh->stamp;
1504     h->id = dh->id;
1505     h->parent = dh->parent;
1506
1507 #ifdef AFS_64BIT_IOPS_ENV
1508     h->volumeInfo =
1509         (Inode) dh->volumeInfo_lo | ((Inode) dh->volumeInfo_hi << 32);
1510
1511     h->smallVnodeIndex =
1512         (Inode) dh->smallVnodeIndex_lo | ((Inode) dh->
1513                                           smallVnodeIndex_hi << 32);
1514
1515     h->largeVnodeIndex =
1516         (Inode) dh->largeVnodeIndex_lo | ((Inode) dh->
1517                                           largeVnodeIndex_hi << 32);
1518     h->linkTable =
1519         (Inode) dh->linkTable_lo | ((Inode) dh->linkTable_hi << 32);
1520 #else
1521     h->volumeInfo = dh->volumeInfo_lo;
1522     h->smallVnodeIndex = dh->smallVnodeIndex_lo;
1523     h->largeVnodeIndex = dh->largeVnodeIndex_lo;
1524     h->linkTable = dh->linkTable_lo;
1525 #endif
1526 }
1527
1528
1529 /***************************************************/
1530 /* Volume Attachment routines                      */
1531 /***************************************************/
1532
1533 #ifdef AFS_DEMAND_ATTACH_FS
1534 /* pre-attach a volume given its path 
1535  *
1536  * a pre-attached volume will only have its partition
1537  * and hashid fields initialized
1538  *
1539  * at first call to VGetVolume, the volume will be
1540  * fully attached
1541  */
1542 Volume *
1543 VPreAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
1544 {
1545     Volume * vp;
1546     VOL_LOCK;
1547     vp = VPreAttachVolumeByName_r(ec, partition, name, mode);
1548     VOL_UNLOCK;
1549     return vp;
1550 }
1551
1552 Volume *
1553 VPreAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
1554 {
1555     register Volume *vp = NULL;
1556     int fd, n;
1557     struct afs_stat status;
1558     struct DiskPartition *partp;
1559     char path[64];
1560     int isbusy = 0;
1561     VolId volumeId;
1562     *ec = 0;
1563
1564     assert(programType == fileServer);
1565
1566     if (!(partp = VGetPartition_r(partition, 0))) {
1567         *ec = VNOVOL;
1568         Log("VPreAttachVolume:  Error getting partition (%s)\n", partition);
1569         return NULL;
1570     }
1571
1572     volumeId = VolumeNumber(name);
1573
1574     vp = VLookupVolume_r(ec, volumeId, NULL);
1575     if (*ec) {
1576         return NULL;
1577     }
1578
1579     return VPreAttachVolumeById_r(ec, partp, vp, volumeId);
1580 }
1581
1582 /* pre-attach a volume given its partition and volume id
1583  *
1584  * if vp == NULL, then a new vp is created
1585  * if vp != NULL, then we assumed it is already on the hash chain
1586  */
1587 Volume * 
1588 VPreAttachVolumeById_r(Error * ec, struct DiskPartition * partp, 
1589                        Volume * vp, int vid)
1590 {
1591     Volume *nvp = NULL;
1592
1593     *ec = 0;
1594
1595     /* check to see if pre-attach already happened */
1596     if (vp && 
1597         (V_attachState(vp) != VOL_STATE_UNATTACHED) && 
1598         !IsErrorState(V_attachState(vp))) {
1599         goto done;
1600     } else if (vp) {
1601         /* we're re-attaching a volume; clear out some old state */
1602         memset(&vp->salvage, 0, sizeof(struct VolumeOnlineSalvage));
1603     } else {
1604         /* if we need to allocate a new Volume struct,
1605          * go ahead and drop the vol glock, otherwise
1606          * do the basic setup synchronised, as it's
1607          * probably not worth dropping the lock */
1608         VOL_UNLOCK;
1609
1610         /* allocate the volume structure */
1611         vp = nvp = (Volume *) malloc(sizeof(Volume));
1612         assert(vp != NULL);
1613         memset(vp, 0, sizeof(Volume));
1614         assert(pthread_cond_init(&V_attachCV(vp), NULL) == 0);
1615     }
1616
1617     /* link the volume with its associated vice partition */
1618     vp->device = partp->device;
1619     vp->partition = partp;
1620     vp->hashid = vid;
1621
1622     /* if we dropped the lock, reacquire the lock,
1623      * check for pre-attach races, and then add
1624      * the volume to the hash table */
1625     if (nvp) {
1626         VOL_LOCK;
1627         nvp = VLookupVolume_r(ec, vid, NULL);
1628         if (*ec) {
1629             free(vp);
1630             vp = NULL;
1631             goto done;
1632         } else if (nvp) { /* race detected */
1633             free(vp);
1634             vp = nvp;
1635             goto done;
1636         } else {
1637           /* hack to make up for VChangeState_r() decrementing 
1638            * the old state counter */
1639           VStats.state_levels[0]++;
1640         }
1641     }
1642
1643     /* put pre-attached volume onto the hash table
1644      * and bring it up to the pre-attached state */
1645     AddVolumeToHashTable(vp, vp->hashid);
1646     AddVolumeToVByPList_r(vp);
1647     VLRU_Init_Node_r(vp);
1648     VChangeState_r(vp, VOL_STATE_PREATTACHED);
1649
1650     if (LogLevel >= 5)
1651         Log("VPreAttachVolumeById_r:  volume %u pre-attached\n", vp->hashid);
1652
1653   done:
1654     if (*ec)
1655         return NULL;
1656     else
1657         return vp;
1658 }
1659 #endif /* AFS_DEMAND_ATTACH_FS */
1660
1661 /* Attach an existing volume, given its pathname, and return a
1662    pointer to the volume header information.  The volume also
1663    normally goes online at this time.  An offline volume
1664    must be reattached to make it go online */
1665 Volume *
1666 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
1667 {
1668     Volume *retVal;
1669     VOL_LOCK;
1670     retVal = VAttachVolumeByName_r(ec, partition, name, mode);
1671     VOL_UNLOCK;
1672     return retVal;
1673 }
1674
1675 Volume *
1676 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
1677 {
1678     register Volume *vp = NULL, *svp = NULL;
1679     int fd, n;
1680     struct afs_stat status;
1681     struct VolumeDiskHeader diskHeader;
1682     struct VolumeHeader iheader;
1683     struct DiskPartition *partp;
1684     char path[64];
1685     int isbusy = 0;
1686     VolId volumeId;
1687 #ifdef AFS_DEMAND_ATTACH_FS
1688     VolumeStats stats_save;
1689 #endif /* AFS_DEMAND_ATTACH_FS */
1690
1691     *ec = 0;
1692    
1693     volumeId = VolumeNumber(name);
1694
1695     if (!(partp = VGetPartition_r(partition, 0))) {
1696         *ec = VNOVOL;
1697         Log("VAttachVolume: Error getting partition (%s)\n", partition);
1698         goto done;
1699     }
1700
1701     if (programType == volumeUtility) {
1702         assert(VInit == 3);
1703         VLockPartition_r(partition);
1704     } else if (programType == fileServer) {
1705 #ifdef AFS_DEMAND_ATTACH_FS
1706         /* lookup the volume in the hash table */
1707         vp = VLookupVolume_r(ec, volumeId, NULL);
1708         if (*ec) {
1709             return NULL;
1710         }
1711
1712         if (vp) {
1713             /* save any counters that are supposed to
1714              * be monotonically increasing over the
1715              * lifetime of the fileserver */
1716             memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
1717         } else {
1718             memset(&stats_save, 0, sizeof(VolumeStats));
1719         }
1720
1721         /* if there's something in the hash table, and it's not
1722          * in the pre-attach state, then we may need to detach
1723          * it before proceeding */
1724         if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1725             VCreateReservation_r(vp);
1726             VWaitExclusiveState_r(vp);
1727
1728             /* at this point state must be one of:
1729              *   UNATTACHED,
1730              *   ATTACHED,
1731              *   SHUTTING_DOWN,
1732              *   GOING_OFFLINE,
1733              *   SALVAGING,
1734              *   ERROR
1735              */
1736
1737             if (vp->specialStatus == VBUSY)
1738                 isbusy = 1;
1739             
1740             /* if it's already attached, see if we can return it */
1741             if (V_attachState(vp) == VOL_STATE_ATTACHED) {
1742                 VGetVolumeByVp_r(ec, vp);
1743                 if (V_inUse(vp)) {
1744                     VCancelReservation_r(vp);
1745                     return vp;
1746                 }
1747
1748                 /* otherwise, we need to detach, and attempt to re-attach */
1749                 VDetachVolume_r(ec, vp);
1750                 if (*ec) {
1751                     Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
1752                 }
1753             } else {
1754                 /* if it isn't fully attached, delete from the hash tables,
1755                    and let the refcounter handle the rest */
1756                 DeleteVolumeFromHashTable(vp);
1757                 DeleteVolumeFromVByPList_r(vp);
1758             }
1759
1760             VCancelReservation_r(vp);
1761             vp = NULL;
1762         }
1763
1764         /* pre-attach volume if it hasn't been done yet */
1765         if (!vp || 
1766             (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
1767             (V_attachState(vp) == VOL_STATE_ERROR)) {
1768             svp = vp;
1769             vp = VPreAttachVolumeById_r(ec, partp, vp, volumeId);
1770             if (*ec) {
1771                 return NULL;
1772             }
1773         }
1774
1775         assert(vp != NULL);
1776
1777         /* handle pre-attach races 
1778          *
1779          * multiple threads can race to pre-attach a volume,
1780          * but we can't let them race beyond that
1781          * 
1782          * our solution is to let the first thread to bring
1783          * the volume into an exclusive state win; the other
1784          * threads just wait until it finishes bringing the
1785          * volume online, and then they do a vgetvolumebyvp
1786          */
1787         if (svp && (svp != vp)) {
1788             /* wait for other exclusive ops to finish */
1789             VCreateReservation_r(vp);
1790             VWaitExclusiveState_r(vp);
1791
1792             /* get a heavyweight ref, kill the lightweight ref, and return */
1793             VGetVolumeByVp_r(ec, vp);
1794             VCancelReservation_r(vp);
1795             return vp;
1796         }
1797
1798         /* at this point, we are chosen as the thread to do
1799          * demand attachment for this volume. all other threads
1800          * doing a getvolume on vp->hashid will block until we finish */
1801
1802         /* make sure any old header cache entries are invalidated
1803          * before proceeding */
1804         FreeVolumeHeader(vp);
1805
1806         VChangeState_r(vp, VOL_STATE_ATTACHING);
1807
1808         /* restore any saved counters */
1809         memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
1810 #else /* AFS_DEMAND_ATTACH_FS */
1811         vp = VGetVolume_r(ec, volumeId);
1812         if (vp) {
1813             if (V_inUse(vp))
1814                 return vp;
1815             if (vp->specialStatus == VBUSY)
1816                 isbusy = 1;
1817             VDetachVolume_r(ec, vp);
1818             if (*ec) {
1819                 Log("VAttachVolume: Error detaching volume (%s)\n", name);
1820             }
1821             vp = NULL;
1822         }
1823 #endif /* AFS_DEMAND_ATTACH_FS */
1824     }
1825
1826     *ec = 0;
1827     strcpy(path, VPartitionPath(partp));
1828
1829     VOL_UNLOCK;
1830
1831     strcat(path, "/");
1832     strcat(path, name);
1833     if ((fd = afs_open(path, O_RDONLY)) == -1 || afs_fstat(fd, &status) == -1) {
1834         Log("VAttachVolume: Failed to open %s (errno %d)\n", path, errno);
1835         if (fd > -1)
1836             close(fd);
1837         *ec = VNOVOL;
1838         VOL_LOCK;
1839         goto done;
1840     }
1841     n = read(fd, &diskHeader, sizeof(diskHeader));
1842     close(fd);
1843     if (n != sizeof(diskHeader)
1844         || diskHeader.stamp.magic != VOLUMEHEADERMAGIC) {
1845         Log("VAttachVolume: Error reading volume header %s\n", path);
1846         *ec = VSALVAGE;
1847         VOL_LOCK;
1848         goto done;
1849     }
1850     if (diskHeader.stamp.version != VOLUMEHEADERVERSION) {
1851         Log("VAttachVolume: Volume %s, version number is incorrect; volume needs salvaged\n", path);
1852         *ec = VSALVAGE;
1853         VOL_LOCK;
1854         goto done;
1855     }
1856
1857     DiskToVolumeHeader(&iheader, &diskHeader);
1858 #ifdef FSSYNC_BUILD_CLIENT
1859     if (programType == volumeUtility && mode != V_SECRETLY && mode != V_PEEK) {
1860         VOL_LOCK;
1861         if (FSYNC_VolOp(iheader.id, partition, FSYNC_VOL_NEEDVOLUME, mode, NULL)
1862             != SYNC_OK) {
1863             Log("VAttachVolume: attach of volume %u apparently denied by file server\n", iheader.id);
1864             *ec = VNOVOL;       /* XXXX */
1865             goto done;
1866         }
1867         VOL_UNLOCK;
1868     }
1869 #endif
1870
1871     if (!vp) {
1872       vp = (Volume *) calloc(1, sizeof(Volume));
1873       assert(vp != NULL);
1874       vp->device = partp->device;
1875       vp->partition = partp;
1876 #ifdef AFS_DEMAND_ATTACH_FS
1877       assert(pthread_cond_init(&V_attachCV(vp), NULL) == 0);
1878 #endif /* AFS_DEMAND_ATTACH_FS */
1879     }
1880
1881     /* attach2 is entered without any locks, and returns
1882      * with vol_glock_mutex held */
1883     vp = attach2(ec, volumeId, path, &iheader, partp, vp, isbusy, mode);
1884
1885     if (programType == volumeUtility && vp) {
1886 #ifdef AFS_DEMAND_ATTACH_FS
1887         /* for dafs, we should tell the fileserver, except for V_PEEK
1888          * where we know it is not necessary */
1889         if (mode == V_PEEK) {
1890             vp->needsPutBack = 0;
1891         } else {
1892             vp->needsPutBack = 1;
1893         }
1894 #else /* !AFS_DEMAND_ATTACH_FS */
1895         /* duplicate computation in fssync.c about whether the server
1896          * takes the volume offline or not.  If the volume isn't
1897          * offline, we must not return it when we detach the volume,
1898          * or the server will abort */
1899         if (mode == V_READONLY || mode == V_PEEK
1900             || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
1901             vp->needsPutBack = 0;
1902         else
1903             vp->needsPutBack = 1;
1904 #endif /* !AFS_DEMAND_ATTACH_FS */
1905     }
1906     /* OK, there's a problem here, but one that I don't know how to
1907      * fix right now, and that I don't think should arise often.
1908      * Basically, we should only put back this volume to the server if
1909      * it was given to us by the server, but since we don't have a vp,
1910      * we can't run the VolumeWriteable function to find out as we do
1911      * above when computing vp->needsPutBack.  So we send it back, but
1912      * there's a path in VAttachVolume on the server which may abort
1913      * if this volume doesn't have a header.  Should be pretty rare
1914      * for all of that to happen, but if it does, probably the right
1915      * fix is for the server to allow the return of readonly volumes
1916      * that it doesn't think are really checked out. */
1917 #ifdef FSSYNC_BUILD_CLIENT
1918     if (programType == volumeUtility && vp == NULL &&
1919         mode != V_SECRETLY && mode != V_PEEK) {
1920         FSYNC_VolOp(iheader.id, partition, FSYNC_VOL_ON, 0, NULL);
1921     } else 
1922 #endif
1923     if (programType == fileServer && vp) {
1924         V_needsCallback(vp) = 0;
1925 #ifdef  notdef
1926         if (VInit >= 2 && V_BreakVolumeCallbacks) {
1927             Log("VAttachVolume: Volume %u was changed externally; breaking callbacks\n", V_id(vp));
1928             (*V_BreakVolumeCallbacks) (V_id(vp));
1929         }
1930 #endif
1931         VUpdateVolume_r(ec, vp, 0);
1932         if (*ec) {
1933             Log("VAttachVolume: Error updating volume\n");
1934             if (vp)
1935                 VPutVolume_r(vp);
1936             goto done;
1937         }
1938         if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
1939 #ifndef AFS_DEMAND_ATTACH_FS
1940             /* This is a hack: by temporarily setting the incore
1941              * dontSalvage flag ON, the volume will be put back on the
1942              * Update list (with dontSalvage OFF again).  It will then
1943              * come back in N minutes with DONT_SALVAGE eventually
1944              * set.  This is the way that volumes that have never had
1945              * it set get it set; or that volumes that have been
1946              * offline without DONT SALVAGE having been set also
1947              * eventually get it set */
1948             V_dontSalvage(vp) = DONT_SALVAGE;
1949 #endif /* !AFS_DEMAND_ATTACH_FS */
1950             VAddToVolumeUpdateList_r(ec, vp);
1951             if (*ec) {
1952                 Log("VAttachVolume: Error adding volume to update list\n");
1953                 if (vp)
1954                     VPutVolume_r(vp);
1955                 goto done;
1956             }
1957         }
1958         if (LogLevel)
1959             Log("VOnline:  volume %u (%s) attached and online\n", V_id(vp),
1960                 V_name(vp));
1961     }
1962   done:
1963     if (programType == volumeUtility) {
1964         VUnlockPartition_r(partition);
1965     }
1966     if (*ec) {
1967 #ifdef AFS_DEMAND_ATTACH_FS
1968         if (vp) {
1969             V_attachState(vp) = VOL_STATE_ERROR;
1970             assert(pthread_cond_broadcast(&V_attachCV(vp)) == 0);
1971         }
1972 #endif /* AFS_DEMAND_ATTACH_FS */
1973         return NULL;
1974     } else {
1975         return vp;
1976     }
1977 }
1978
1979 #ifdef AFS_DEMAND_ATTACH_FS
1980 /* VAttachVolumeByVp_r
1981  *
1982  * finish attaching a volume that is
1983  * in a less than fully attached state
1984  */
1985 /* caller MUST hold a ref count on vp */
1986 static Volume *
1987 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
1988 {
1989     char name[VMAXPATHLEN];
1990     int fd, n, reserve = 0;
1991     struct afs_stat status;
1992     struct VolumeDiskHeader diskHeader;
1993     struct VolumeHeader iheader;
1994     struct DiskPartition *partp;
1995     char path[64];
1996     int isbusy = 0;
1997     VolId volumeId;
1998     Volume * nvp;
1999     VolumeStats stats_save;
2000     *ec = 0;
2001
2002     /* volume utility should never call AttachByVp */
2003     assert(programType == fileServer);
2004    
2005     volumeId = vp->hashid;
2006     partp = vp->partition;
2007     VolumeExternalName_r(volumeId, name, sizeof(name));
2008
2009
2010     /* if another thread is performing a blocking op, wait */
2011     VWaitExclusiveState_r(vp);
2012
2013     memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2014
2015     /* if it's already attached, see if we can return it */
2016     if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2017         VGetVolumeByVp_r(ec, vp);
2018         if (V_inUse(vp)) {
2019             return vp;
2020         } else {
2021             if (vp->specialStatus == VBUSY)
2022                 isbusy = 1;
2023             VDetachVolume_r(ec, vp);
2024             if (*ec) {
2025                 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2026             }
2027             vp = NULL;
2028         }
2029     }
2030
2031     /* pre-attach volume if it hasn't been done yet */
2032     if (!vp || 
2033         (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2034         (V_attachState(vp) == VOL_STATE_ERROR)) {
2035         nvp = VPreAttachVolumeById_r(ec, partp, vp, volumeId);
2036         if (*ec) {
2037             return NULL;
2038         }
2039         if (nvp != vp) {
2040             reserve = 1;
2041             VCreateReservation_r(nvp);
2042             vp = nvp;
2043         }
2044     }
2045     
2046     assert(vp != NULL);
2047     VChangeState_r(vp, VOL_STATE_ATTACHING);
2048
2049     /* restore monotonically increasing stats */
2050     memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2051
2052     *ec = 0;
2053
2054
2055     /* compute path to disk header, 
2056      * read in header, 
2057      * and verify magic and version stamps */
2058     strcpy(path, VPartitionPath(partp));
2059
2060     VOL_UNLOCK;
2061
2062     strcat(path, "/");
2063     strcat(path, name);
2064     if ((fd = afs_open(path, O_RDONLY)) == -1 || afs_fstat(fd, &status) == -1) {
2065         Log("VAttachVolume: Failed to open %s (errno %d)\n", path, errno);
2066         if (fd > -1)
2067             close(fd);
2068         *ec = VNOVOL;
2069         VOL_LOCK;
2070         goto done;
2071     }
2072     n = read(fd, &diskHeader, sizeof(diskHeader));
2073     close(fd);
2074     if (n != sizeof(diskHeader)
2075         || diskHeader.stamp.magic != VOLUMEHEADERMAGIC) {
2076         Log("VAttachVolume: Error reading volume header %s\n", path);
2077         *ec = VSALVAGE;
2078         VOL_LOCK;
2079         goto done;
2080     }
2081     if (diskHeader.stamp.version != VOLUMEHEADERVERSION) {
2082         Log("VAttachVolume: Volume %s, version number is incorrect; volume needs salvaged\n", path);
2083         *ec = VSALVAGE;
2084         VOL_LOCK;
2085         goto done;
2086     }
2087
2088     /* convert on-disk header format to in-memory header format */
2089     DiskToVolumeHeader(&iheader, &diskHeader);
2090
2091     /* do volume attach
2092      *
2093      * NOTE: attach2 is entered without any locks, and returns
2094      * with vol_glock_mutex held */
2095     vp = attach2(ec, volumeId, path, &iheader, partp, vp, isbusy, mode);
2096
2097     if (*ec || vp == NULL) {
2098         goto done;
2099     }
2100
2101     V_needsCallback(vp) = 0;
2102     VUpdateVolume_r(ec, vp, 0);
2103     if (*ec) {
2104         Log("VAttachVolume: Error updating volume %u\n", vp->hashid);
2105         VPutVolume_r(vp);
2106         goto done;
2107     }
2108     if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2109 #ifndef AFS_DEMAND_ATTACH_FS
2110         /* This is a hack: by temporarily setting the incore
2111          * dontSalvage flag ON, the volume will be put back on the
2112          * Update list (with dontSalvage OFF again).  It will then
2113          * come back in N minutes with DONT_SALVAGE eventually
2114          * set.  This is the way that volumes that have never had
2115          * it set get it set; or that volumes that have been
2116          * offline without DONT SALVAGE having been set also
2117          * eventually get it set */
2118         V_dontSalvage(vp) = DONT_SALVAGE;
2119 #endif /* !AFS_DEMAND_ATTACH_FS */
2120         VAddToVolumeUpdateList_r(ec, vp);
2121         if (*ec) {
2122             Log("VAttachVolume: Error adding volume %u to update list\n", vp->hashid);
2123             if (vp)
2124                 VPutVolume_r(vp);
2125             goto done;
2126         }
2127     }
2128     if (LogLevel)
2129         Log("VOnline:  volume %u (%s) attached and online\n", V_id(vp),
2130             V_name(vp));
2131   done:
2132     if (reserve) {
2133         VCancelReservation_r(nvp);
2134         reserve = 0;
2135     }
2136     if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2137         if (vp && !IsErrorState(V_attachState(vp))) {
2138             VChangeState_r(vp, VOL_STATE_ERROR);
2139         }
2140         return NULL;
2141     } else {
2142         return vp;
2143     }
2144 }
2145 #endif /* AFS_DEMAND_ATTACH_FS */
2146
2147 /*
2148  * called without any locks held
2149  * returns with vol_glock_mutex held
2150  */
2151 private Volume * 
2152 attach2(Error * ec, VolId volumeId, char *path, register struct VolumeHeader * header,
2153         struct DiskPartition * partp, register Volume * vp, int isbusy, int mode)
2154 {
2155     vp->specialStatus = (byte) (isbusy ? VBUSY : 0);
2156     IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header->parent,
2157             header->largeVnodeIndex);
2158     IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header->parent,
2159             header->smallVnodeIndex);
2160     IH_INIT(vp->diskDataHandle, partp->device, header->parent,
2161             header->volumeInfo);
2162     IH_INIT(vp->linkHandle, partp->device, header->parent, header->linkTable);
2163     vp->shuttingDown = 0;
2164     vp->goingOffline = 0;
2165     vp->nUsers = 1;
2166 #ifdef AFS_DEMAND_ATTACH_FS
2167     vp->stats.last_attach = FT_ApproxTime();
2168     vp->stats.attaches++;
2169 #endif
2170
2171     VOL_LOCK;
2172 #ifdef AFS_DEMAND_ATTACH_FS
2173     IncUInt64(&VStats.attaches);
2174 #endif
2175     vp->cacheCheck = ++VolumeCacheCheck;
2176     /* just in case this ever rolls over */
2177     if (!vp->cacheCheck)
2178         vp->cacheCheck = ++VolumeCacheCheck;
2179     GetVolumeHeader(vp);
2180     VOL_UNLOCK;
2181
2182 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2183     /* demand attach changes the V_PEEK mechanism
2184      *
2185      * we can now suck the current disk data structure over
2186      * the fssync interface without going to disk
2187      *
2188      * (technically, we don't need to restrict this feature
2189      *  to demand attach fileservers.  However, I'm trying
2190      *  to limit the number of common code changes)
2191      */
2192     if (programType != fileServer && mode == V_PEEK) {
2193         SYNC_response res;
2194         res.payload.len = sizeof(VolumeDiskData);
2195         res.payload.buf = &vp->header->diskstuff;
2196
2197         if (FSYNC_VolOp(volumeId,
2198                         VPartitionPath(partp),
2199                         FSYNC_VOL_QUERY_HDR,
2200                         FSYNC_WHATEVER,
2201                         &res) == SYNC_OK) {
2202             goto disk_header_loaded;
2203         }
2204     }
2205 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2206     (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2207                      sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2208
2209 #ifdef AFS_DEMAND_ATTACH_FS
2210     /* update stats */
2211     VOL_LOCK;
2212     IncUInt64(&VStats.hdr_loads);
2213     IncUInt64(&vp->stats.hdr_loads);
2214     VOL_UNLOCK;
2215 #endif /* AFS_DEMAND_ATTACH_FS */
2216     
2217     if (*ec) {
2218         Log("VAttachVolume: Error reading diskDataHandle vol header %s; error=%u\n", path, *ec);
2219     }
2220
2221  disk_header_loaded:
2222
2223 #ifdef AFS_DEMAND_ATTACH_FS
2224     if (!*ec) {
2225
2226         /* check for pending volume operations */
2227         if (vp->pending_vol_op) {
2228             /* see if the pending volume op requires exclusive access */
2229             if (!VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
2230                 /* mark the volume down */
2231                 *ec = VOFFLINE;
2232                 VChangeState_r(vp, VOL_STATE_UNATTACHED);
2233                 if (V_offlineMessage(vp)[0] == '\0')
2234                     strlcpy(V_offlineMessage(vp),
2235                             "A volume utility is running.", 
2236                             sizeof(V_offlineMessage(vp)));
2237                 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
2238
2239                 /* check to see if we should set the specialStatus flag */
2240                 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
2241                     vp->specialStatus = VBUSY;
2242                 }
2243             }
2244         }
2245
2246         V_attachFlags(vp) |= VOL_HDR_LOADED;
2247     }
2248 #endif /* AFS_DEMAND_ATTACH_FS */
2249
2250     if (!*ec) {
2251         struct IndexFileHeader iHead;
2252
2253 #if OPENAFS_VOL_STATS
2254         /*
2255          * We just read in the diskstuff part of the header.  If the detailed
2256          * volume stats area has not yet been initialized, we should bzero the
2257          * area and mark it as initialized.
2258          */
2259         if (!(V_stat_initialized(vp))) {
2260             memset((char *)(V_stat_area(vp)), 0, VOL_STATS_BYTES);
2261             V_stat_initialized(vp) = 1;
2262         }
2263 #endif /* OPENAFS_VOL_STATS */
2264
2265         (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
2266                          (char *)&iHead, sizeof(iHead),
2267                          SMALLINDEXMAGIC, SMALLINDEXVERSION);
2268
2269         if (*ec) {
2270             Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
2271         }
2272     }
2273
2274     if (!*ec) {
2275         struct IndexFileHeader iHead;
2276
2277         (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
2278                          (char *)&iHead, sizeof(iHead),
2279                          LARGEINDEXMAGIC, LARGEINDEXVERSION);
2280
2281         if (*ec) {
2282             Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
2283         }
2284     }
2285
2286 #ifdef AFS_NAMEI_ENV
2287     if (!*ec) {
2288         struct versionStamp stamp;
2289
2290         (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
2291                          sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
2292
2293         if (*ec) {
2294             Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
2295         }
2296     }
2297 #endif /* AFS_NAMEI_ENV */
2298
2299 #if defined(AFS_DEMAND_ATTACH_FS)
2300     if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
2301         VOL_LOCK;
2302         if (programType == fileServer) {
2303             VRequestSalvage_r(vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2304             vp->nUsers = 0;
2305             *ec = VSALVAGING;
2306         } else {
2307             Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
2308             FreeVolume(vp);
2309             *ec = VSALVAGE;
2310         }
2311         return NULL;
2312     } else if (*ec) {
2313         /* volume operation in progress */
2314         VOL_LOCK;
2315         return NULL;
2316     }
2317 #else /* AFS_DEMAND_ATTACH_FS */
2318     if (*ec) {
2319         Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
2320         VOL_LOCK;
2321         FreeVolume(vp);
2322         return NULL;
2323     }
2324 #endif /* AFS_DEMAND_ATTACH_FS */
2325
2326     if (V_needsSalvaged(vp)) {
2327         if (vp->specialStatus)
2328             vp->specialStatus = 0;
2329         VOL_LOCK;
2330 #if defined(AFS_DEMAND_ATTACH_FS)
2331         if (programType == fileServer) {
2332             VRequestSalvage_r(vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
2333             vp->nUsers = 0;
2334             *ec = VSALVAGING;
2335         } else {
2336             Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
2337             FreeVolume(vp);
2338             *ec = VSALVAGE;
2339         }
2340 #else /* AFS_DEMAND_ATTACH_FS */
2341         FreeVolume(vp);
2342         *ec = VSALVAGE;
2343 #endif /* AFS_DEMAND_ATTACH_FS */
2344         return NULL;
2345     }
2346
2347     VOL_LOCK;
2348     if (programType == fileServer) {
2349 #ifndef FAST_RESTART
2350         if (V_inUse(vp) && VolumeWriteable(vp)) {
2351             if (!V_needsSalvaged(vp)) {
2352                 V_needsSalvaged(vp) = 1;
2353                 VUpdateVolume_r(ec, vp, 0);
2354             }
2355 #if defined(AFS_DEMAND_ATTACH_FS)
2356             VRequestSalvage_r(vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
2357             vp->nUsers = 0;
2358             *ec = VSALVAGING;
2359 #else /* AFS_DEMAND_ATTACH_FS */
2360             Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
2361             FreeVolume(vp);
2362             *ec = VSALVAGE;
2363 #endif /* AFS_DEMAND_ATTACH_FS */
2364             return NULL;
2365         }
2366 #endif /* FAST_RESTART */
2367
2368         if (V_destroyMe(vp) == DESTROY_ME) {
2369 #if defined(AFS_DEMAND_ATTACH_FS)
2370             /* schedule a salvage so the volume goes away on disk */
2371             VRequestSalvage_r(vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2372             VChangeState_r(vp, VOL_STATE_ERROR);
2373             vp->nUsers = 0;
2374 #endif /* AFS_DEMAND_ATTACH_FS */
2375             FreeVolume(vp);
2376             Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
2377             *ec = VNOVOL;
2378             return NULL;
2379         }
2380     }
2381
2382     vp->nextVnodeUnique = V_uniquifier(vp);
2383     vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
2384 #ifndef BITMAP_LATER
2385     if (programType == fileServer && VolumeWriteable(vp)) {
2386         int i;
2387         for (i = 0; i < nVNODECLASSES; i++) {
2388             VGetBitmap_r(ec, vp, i);
2389             if (*ec) {
2390 #ifdef AFS_DEMAND_ATTACH_FS
2391                 VRequestSalvage_r(vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2392                 vp->nUsers = 0;
2393                 *ec = VSALVAGING;
2394 #else /* AFS_DEMAND_ATTACH_FS */
2395                 FreeVolume(vp);
2396 #endif /* AFS_DEMAND_ATTACH_FS */
2397                 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
2398                     path);
2399                 return NULL;
2400             }
2401         }
2402     }
2403 #endif /* BITMAP_LATER */
2404
2405     if (programType == fileServer) {
2406         if (vp->specialStatus)
2407             vp->specialStatus = 0;
2408         if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
2409             V_inUse(vp) = 1;
2410             V_offlineMessage(vp)[0] = '\0';
2411         }
2412     }
2413
2414     AddVolumeToHashTable(vp, V_id(vp));
2415 #ifdef AFS_DEMAND_ATTACH_FS
2416     AddVolumeToVByPList_r(vp);
2417     VLRU_Add_r(vp);
2418     VChangeState_r(vp, VOL_STATE_ATTACHED);
2419 #endif
2420     return vp;
2421 }
2422
2423 /* Attach an existing volume.
2424    The volume also normally goes online at this time.
2425    An offline volume must be reattached to make it go online.
2426  */
2427
2428 Volume *
2429 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
2430 {
2431     Volume *retVal;
2432     VOL_LOCK;
2433     retVal = VAttachVolume_r(ec, volumeId, mode);
2434     VOL_UNLOCK;
2435     return retVal;
2436 }
2437
2438 Volume *
2439 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
2440 {
2441     char *part, *name;
2442     GetVolumePath(ec, volumeId, &part, &name);
2443     if (*ec) {
2444         register Volume *vp;
2445         Error error;
2446         vp = VGetVolume_r(&error, volumeId);
2447         if (vp) {
2448             assert(V_inUse(vp) == 0);
2449             VDetachVolume_r(ec, vp);
2450         }
2451         return NULL;
2452     }
2453     return VAttachVolumeByName_r(ec, part, name, mode);
2454 }
2455
2456 /* Increment a reference count to a volume, sans context swaps.  Requires
2457  * possibly reading the volume header in from the disk, since there's
2458  * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
2459  *
2460  * N.B. This call can fail if we can't read in the header!!  In this case
2461  * we still guarantee we won't context swap, but the ref count won't be
2462  * incremented (otherwise we'd violate the invariant).
2463  */
2464 /* NOTE: with the demand attach fileserver extensions, the global lock
2465  * is dropped within VHold */
2466 #ifdef AFS_DEMAND_ATTACH_FS
2467 static int
2468 VHold_r(register Volume * vp)
2469 {
2470     Error error;
2471
2472     VCreateReservation_r(vp);
2473     VWaitExclusiveState_r(vp);
2474
2475     LoadVolumeHeader(&error, vp);
2476     if (error) {
2477         VCancelReservation_r(vp);
2478         return error;
2479     }
2480     vp->nUsers++;
2481     VCancelReservation_r(vp);
2482     return 0;
2483 }
2484 #else /* AFS_DEMAND_ATTACH_FS */
2485 static int
2486 VHold_r(register Volume * vp)
2487 {
2488     Error error;
2489
2490     LoadVolumeHeader(&error, vp);
2491     if (error)
2492         return error;
2493     vp->nUsers++;
2494     return 0;
2495 }
2496 #endif /* AFS_DEMAND_ATTACH_FS */
2497
2498 static int
2499 VHold(register Volume * vp)
2500 {
2501     int retVal;
2502     VOL_LOCK;
2503     retVal = VHold_r(vp);
2504     VOL_UNLOCK;
2505     return retVal;
2506 }
2507
2508
2509 /***************************************************/
2510 /* get and put volume routines                     */
2511 /***************************************************/
2512
2513 void
2514 VPutVolume_r(register Volume * vp)
2515 {
2516     assert(--vp->nUsers >= 0);
2517     if (vp->nUsers == 0) {
2518         VCheckOffline(vp);
2519         ReleaseVolumeHeader(vp->header);
2520 #ifdef AFS_DEMAND_ATTACH_FS
2521         if (!VCheckDetach(vp)) {
2522             VCheckSalvage(vp);
2523             VCheckFree(vp);
2524         }
2525 #else /* AFS_DEMAND_ATTACH_FS */
2526         VCheckDetach(vp);
2527 #endif /* AFS_DEMAND_ATTACH_FS */
2528     }
2529 }
2530
2531 void
2532 VPutVolume(register Volume * vp)
2533 {
2534     VOL_LOCK;
2535     VPutVolume_r(vp);
2536     VOL_UNLOCK;
2537 }
2538
2539
2540 /* Get a pointer to an attached volume.  The pointer is returned regardless
2541    of whether or not the volume is in service or on/off line.  An error
2542    code, however, is returned with an indication of the volume's status */
2543 Volume *
2544 VGetVolume(Error * ec, Error * client_ec, VolId volumeId)
2545 {
2546     Volume *retVal;
2547     VOL_LOCK;
2548     retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
2549     VOL_UNLOCK;
2550     return retVal;
2551 }
2552
2553 Volume *
2554 VGetVolume_r(Error * ec, VolId volumeId)
2555 {
2556     return GetVolume(ec, NULL, volumeId, NULL, 0);
2557 }
2558
2559 /* try to get a volume we've previously looked up */
2560 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
2561 Volume * 
2562 VGetVolumeByVp_r(Error * ec, Volume * vp)
2563 {
2564     return GetVolume(ec, NULL, vp->hashid, vp, 0);
2565 }
2566
2567 /* private interface for getting a volume handle
2568  * volumeId must be provided.
2569  * hint is an optional parameter to speed up hash lookups
2570  * flags is not used at this time
2571  */
2572 /* for demand attach fs, caller MUST NOT hold a ref count on hint */
2573 static Volume *
2574 GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint, int flags)
2575 {
2576     Volume *vp = hint;
2577     /* pull this profiling/debugging code out of regular builds */
2578 #ifdef notdef
2579 #define VGET_CTR_INC(x) x++
2580     unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
2581         0, V7 = 0, V8 = 0, V9 = 0;
2582     unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
2583 #else
2584 #define VGET_CTR_INC(x)
2585 #endif
2586
2587 #ifdef AFS_DEMAND_ATTACH_FS
2588     Volume *avp, * rvp = hint;
2589
2590     if (rvp) {
2591         VCreateReservation_r(rvp);
2592     }
2593 #endif /* AFS_DEMAND_ATTACH_FS */
2594
2595     for (;;) {
2596         *ec = 0;
2597         if (client_ec)
2598             *client_ec = 0;
2599         VGET_CTR_INC(V0);
2600
2601         vp = VLookupVolume_r(ec, volumeId, vp);
2602         if (*ec) {
2603             vp = NULL;
2604             break;
2605         }
2606
2607 #ifdef AFS_DEMAND_ATTACH_FS
2608         if (rvp && (rvp != vp)) {
2609             /* break reservation on old vp */
2610             VCancelReservation_r(rvp);
2611             rvp = NULL;
2612         }
2613 #endif /* AFS_DEMAND_ATTACH_FS */
2614
2615         if (!vp) {
2616             VGET_CTR_INC(V1);
2617             if (VInit < 2) {
2618                 VGET_CTR_INC(V2);
2619                 /* Until we have reached an initialization level of 2
2620                  * we don't know whether this volume exists or not.
2621                  * We can't sleep and retry later because before a volume
2622                  * is attached, the caller tries to get it first.  Just
2623                  * return VOFFLINE and the caller can choose whether to
2624                  * retry the command or not. */
2625                 *ec = VOFFLINE;
2626                 break;
2627             }
2628
2629             *ec = VNOVOL;
2630             break;
2631         }
2632
2633         VGET_CTR_INC(V3);
2634         IncUInt64(&VStats.hdr_gets);
2635         
2636 #ifdef AFS_DEMAND_ATTACH_FS
2637         /* block if someone else is performing an exclusive op on this volume */
2638         if (rvp != vp) {
2639             rvp = vp;
2640             VCreateReservation_r(rvp);
2641         }
2642         VWaitExclusiveState_r(vp);
2643
2644         /* short circuit with VNOVOL in the following circumstances:
2645          *
2646          *   VOL_STATE_ERROR
2647          *   VOL_STATE_SHUTTING_DOWN
2648          */
2649         if ((V_attachState(vp) == VOL_STATE_ERROR) ||
2650             (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN)) {
2651             *ec = VNOVOL;
2652             vp = NULL;
2653             break;
2654         }
2655
2656         /* allowable states:
2657          *   UNATTACHED
2658          *   PREATTACHED
2659          *   ATTACHED
2660          *   GOING_OFFLINE
2661          *   SALVAGING
2662          */
2663
2664         if (vp->salvage.requested) {
2665             VUpdateSalvagePriority_r(vp);
2666         }
2667
2668         if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
2669             avp = VAttachVolumeByVp_r(ec, vp, 0);
2670             if (avp) {
2671                 if (vp != avp) {
2672                     /* VAttachVolumeByVp_r can return a pointer
2673                      * != the vp passed to it under certain
2674                      * conditions; make sure we don't leak
2675                      * reservations if that happens */
2676                     vp = avp;
2677                     VCancelReservation_r(rvp);
2678                     rvp = avp;
2679                     VCreateReservation_r(rvp);
2680                 }
2681                 VPutVolume_r(avp);
2682             }
2683             if (*ec) {
2684                 int endloop = 0;
2685                 switch (*ec) {
2686                 case VSALVAGING:
2687                     break;
2688                 case VOFFLINE:
2689                     if (!vp->pending_vol_op) {
2690                         endloop = 1;
2691                     }
2692                     break;
2693                 default:
2694                     *ec = VNOVOL;
2695                     endloop = 1;
2696                 }
2697                 if (endloop) {
2698                     vp = NULL;
2699                     break;
2700                 }
2701             }
2702         }
2703
2704         if ((V_attachState(vp) == VOL_STATE_SALVAGING) ||
2705             (*ec == VSALVAGING)) {
2706             if (client_ec) {
2707                 /* see CheckVnode() in afsfileprocs.c for an explanation
2708                  * of this error code logic */
2709                 afs_uint32 now = FT_ApproxTime();
2710                 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
2711                     *client_ec = VBUSY;
2712                 } else {
2713                     *client_ec = VRESTARTING;
2714                 }
2715             }
2716             *ec = VSALVAGING;
2717             vp = NULL;
2718             break;
2719         }
2720 #endif
2721
2722         LoadVolumeHeader(ec, vp);
2723         if (*ec) {
2724             VGET_CTR_INC(V6);
2725             /* Only log the error if it was a totally unexpected error.  Simply
2726              * a missing inode is likely to be caused by the volume being deleted */
2727             if (errno != ENXIO || LogLevel)
2728                 Log("Volume %u: couldn't reread volume header\n",
2729                     vp->hashid);
2730 #ifdef AFS_DEMAND_ATTACH_FS
2731             if (programType == fileServer) {
2732                 VRequestSalvage_r(vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2733                 *ec = VSALVAGING;
2734             } else {
2735                 FreeVolume(vp);
2736                 vp = NULL;
2737             }
2738 #else /* AFS_DEMAND_ATTACH_FS */
2739             FreeVolume(vp);
2740             vp = NULL;
2741 #endif /* AFS_DEMAND_ATTACH_FS */
2742             break;
2743         }
2744
2745 #ifdef AFS_DEMAND_ATTACH_FS
2746         if (vp->pending_vol_op && !VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
2747             if (client_ec) {
2748                 /* see CheckVnode() in afsfileprocs.c for an explanation
2749                  * of this error code logic */
2750                 afs_uint32 now = FT_ApproxTime();
2751                 if ((vp->stats.last_vol_op + (10 * 60)) >= now) {
2752                     *client_ec = VBUSY;
2753                 } else {
2754                     *client_ec = VRESTARTING;
2755                 }
2756             }
2757             *ec = VOFFLINE;
2758             ReleaseVolumeHeader(vp->header);
2759             vp = NULL;
2760             break;
2761         }
2762
2763         if (V_attachState(vp) == VOL_STATE_UNATTACHED) {
2764             *ec = VOFFLINE;
2765             ReleaseVolumeHeader(vp->header);
2766             vp = NULL;
2767             break;
2768         }
2769 #endif /* AFS_DEMAND_ATTACH_FS */
2770         
2771         VGET_CTR_INC(V7);
2772         if (vp->shuttingDown) {
2773             VGET_CTR_INC(V8);
2774             *ec = VNOVOL;
2775             vp = NULL;
2776             break;
2777         }
2778
2779         if (programType == fileServer) {
2780             VGET_CTR_INC(V9);
2781             if (vp->goingOffline) {
2782                 VGET_CTR_INC(V10);
2783 #ifdef AFS_DEMAND_ATTACH_FS
2784                 /* wait for the volume to go offline */
2785                 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
2786                     VWaitStateChange_r(vp);
2787                 }
2788 #elif defined(AFS_PTHREAD_ENV)
2789                 assert(pthread_cond_wait(&vol_put_volume_cond, &vol_glock_mutex) == 0);
2790 #else /* AFS_PTHREAD_ENV */
2791                 LWP_WaitProcess(VPutVolume);
2792 #endif /* AFS_PTHREAD_ENV */
2793                 continue;
2794             }
2795             if (vp->specialStatus) {
2796                 VGET_CTR_INC(V11);
2797                 *ec = vp->specialStatus;
2798             } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
2799                 VGET_CTR_INC(V12);
2800                 *ec = VNOVOL;
2801             } else if (V_inUse(vp) == 0) {
2802                 VGET_CTR_INC(V13);
2803                 *ec = VOFFLINE;
2804             } else {
2805                 VGET_CTR_INC(V14);
2806             }
2807         }
2808         break;
2809     }
2810     VGET_CTR_INC(V15);
2811
2812 #ifdef AFS_DEMAND_ATTACH_FS
2813     /* if no error, bump nUsers */
2814     if (vp) {
2815         vp->nUsers++;
2816         VLRU_UpdateAccess_r(vp);
2817     }
2818     if (rvp) {
2819         VCancelReservation_r(rvp);
2820         rvp = NULL;
2821     }
2822     if (client_ec && !*client_ec) {
2823         *client_ec = *ec;
2824     }
2825 #else /* AFS_DEMAND_ATTACH_FS */
2826     /* if no error, bump nUsers */
2827     if (vp) {
2828         vp->nUsers++;
2829     }
2830     if (client_ec) {
2831         *client_ec = *ec;
2832     }
2833 #endif /* AFS_DEMAND_ATTACH_FS */
2834
2835     assert(vp || *ec);
2836     return vp;
2837 }
2838
2839
2840 /***************************************************/
2841 /* Volume offline/detach routines                  */
2842 /***************************************************/
2843
2844 /* caller MUST hold a heavyweight ref on vp */
2845 #ifdef AFS_DEMAND_ATTACH_FS
2846 void
2847 VTakeOffline_r(register Volume * vp)
2848 {
2849     assert(vp->nUsers > 0);
2850     assert(programType == fileServer);
2851
2852     VCreateReservation_r(vp);
2853     VWaitExclusiveState_r(vp);
2854
2855     vp->goingOffline = 1;
2856     V_needsSalvaged(vp) = 1;
2857
2858     VRequestSalvage_r(vp, SALVSYNC_ERROR, 0);
2859     VCancelReservation_r(vp);
2860 }
2861 #else /* AFS_DEMAND_ATTACH_FS */
2862 void
2863 VTakeOffline_r(register Volume * vp)
2864 {
2865     assert(vp->nUsers > 0);
2866     assert(programType == fileServer);
2867
2868     vp->goingOffline = 1;
2869     V_needsSalvaged(vp) = 1;
2870 }
2871 #endif /* AFS_DEMAND_ATTACH_FS */
2872
2873 void
2874 VTakeOffline(register Volume * vp)
2875 {
2876     VOL_LOCK;
2877     VTakeOffline_r(vp);
2878     VOL_UNLOCK;
2879 }
2880
2881 /* Force the volume offline, set the salvage flag.  No further references to
2882  * the volume through the volume package will be honored. */
2883 /* for demand attach, caller MUST hold ref count on vp */
2884 void
2885 VForceOffline_r(Volume * vp, int flags)
2886 {
2887     Error error;
2888     if (!V_inUse(vp))
2889         return;
2890     strcpy(V_offlineMessage(vp),
2891            "Forced offline due to internal error: volume needs to be salvaged");
2892     Log("Volume %u forced offline:  it needs salvaging!\n", V_id(vp));
2893     V_inUse(vp) = 0;
2894     vp->goingOffline = 0;
2895     V_needsSalvaged(vp) = 1;
2896     if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
2897         VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT | VOL_UPDATE_NOFORCEOFF);
2898     }
2899 #ifdef AFS_DEMAND_ATTACH_FS
2900 #ifdef SALVSYNC_BUILD_CLIENT
2901     if (programType == fileServer) {
2902         VRequestSalvage_r(vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2903     }
2904 #endif
2905     VChangeState_r(vp, VOL_STATE_ERROR);
2906 #endif /* AFS_DEMAND_ATTACH_FS */
2907 #ifdef AFS_PTHREAD_ENV
2908     assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
2909 #else /* AFS_PTHREAD_ENV */
2910     LWP_NoYieldSignal(VPutVolume);
2911 #endif /* AFS_PTHREAD_ENV */
2912
2913     VReleaseVolumeHandles_r(vp);
2914 }
2915
2916 void
2917 VForceOffline(Volume * vp)
2918 {
2919     VOL_LOCK;
2920     VForceOffline_r(vp, 0);
2921     VOL_UNLOCK;
2922 }
2923
2924 /* The opposite of VAttachVolume.  The volume header is written to disk, with
2925    the inUse bit turned off.  A copy of the header is maintained in memory,
2926    however (which is why this is VOffline, not VDetach).
2927  */
2928 void
2929 VOffline_r(Volume * vp, char *message)
2930 {
2931     Error error;
2932     VolumeId vid = V_id(vp);
2933
2934     assert(programType != volumeUtility);
2935     if (!V_inUse(vp)) {
2936         VPutVolume_r(vp);
2937         return;
2938     }
2939     if (V_offlineMessage(vp)[0] == '\0')
2940         strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
2941     V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
2942
2943     vp->goingOffline = 1;
2944 #ifdef AFS_DEMAND_ATTACH_FS
2945     VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
2946     VCreateReservation_r(vp);
2947     VPutVolume_r(vp);
2948
2949     /* wait for the volume to go offline */
2950     if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
2951         VWaitStateChange_r(vp);
2952     }
2953     VCancelReservation_r(vp);
2954 #else /* AFS_DEMAND_ATTACH_FS */
2955     VPutVolume_r(vp);
2956     vp = VGetVolume_r(&error, vid);     /* Wait for it to go offline */
2957     if (vp)                     /* In case it was reattached... */
2958         VPutVolume_r(vp);
2959 #endif /* AFS_DEMAND_ATTACH_FS */
2960 }
2961
2962 void
2963 VOffline(Volume * vp, char *message)
2964 {
2965     VOL_LOCK;
2966     VOffline_r(vp, message);
2967     VOL_UNLOCK;
2968 }
2969
2970 /* This gets used for the most part by utility routines that don't want
2971  * to keep all the volume headers around.  Generally, the file server won't
2972  * call this routine, because then the offline message in the volume header
2973  * (or other information) won't be available to clients. For NAMEI, also
2974  * close the file handles.  However, the fileserver does call this during
2975  * an attach following a volume operation.
2976  */
2977 void
2978 VDetachVolume_r(Error * ec, Volume * vp)
2979 {
2980     VolumeId volume;
2981     struct DiskPartition *tpartp;
2982     int notifyServer, useDone;
2983
2984     *ec = 0;                    /* always "succeeds" */
2985     if (programType == volumeUtility) {
2986         notifyServer = vp->needsPutBack;
2987         useDone = (V_destroyMe(vp) == DESTROY_ME);
2988     }
2989     tpartp = vp->partition;
2990     volume = V_id(vp);
2991     DeleteVolumeFromHashTable(vp);
2992     vp->shuttingDown = 1;
2993 #ifdef AFS_DEMAND_ATTACH_FS
2994     DeleteVolumeFromVByPList_r(vp);
2995     VLRU_Delete_r(vp);
2996     VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
2997 #endif /* AFS_DEMAND_ATTACH_FS */
2998     VPutVolume_r(vp);
2999     /* Will be detached sometime in the future--this is OK since volume is offline */
3000
3001     /* XXX the following code should really be moved to VCheckDetach() since the volume
3002      * is not technically detached until the refcounts reach zero
3003      */
3004 #ifdef FSSYNC_BUILD_CLIENT
3005     if (programType == volumeUtility && notifyServer) {
3006         /* 
3007          * Note:  The server is not notified in the case of a bogus volume 
3008          * explicitly to make it possible to create a volume, do a partial 
3009          * restore, then abort the operation without ever putting the volume 
3010          * online.  This is essential in the case of a volume move operation 
3011          * between two partitions on the same server.  In that case, there 
3012          * would be two instances of the same volume, one of them bogus, 
3013          * which the file server would attempt to put on line 
3014          */
3015         if (useDone) {
3016             /* don't put online */
3017             FSYNC_VolOp(volume, tpartp->name, FSYNC_VOL_DONE, 0, NULL);
3018         } else {
3019             /* fs can use it again */
3020             FSYNC_VolOp(volume, tpartp->name, FSYNC_VOL_ON, 0, NULL);
3021
3022             /* XXX this code path is only hit by volume utilities, thus
3023              * V_BreakVolumeCallbacks will always be NULL.  if we really
3024              * want to break callbacks in this path we need to use FSYNC_VolOp() */
3025 #ifdef notdef
3026             /* Dettaching it so break all callbacks on it */
3027             if (V_BreakVolumeCallbacks) {
3028                 Log("volume %u detached; breaking all call backs\n", volume);
3029                 (*V_BreakVolumeCallbacks) (volume);
3030             }
3031 #endif
3032         }
3033     }
3034 #endif /* FSSYNC_BUILD_CLIENT */
3035 }
3036
3037 void
3038 VDetachVolume(Error * ec, Volume * vp)
3039 {
3040     VOL_LOCK;
3041     VDetachVolume_r(ec, vp);
3042     VOL_UNLOCK;
3043 }
3044
3045
3046 /***************************************************/
3047 /* Volume fd/inode handle closing routines         */
3048 /***************************************************/
3049
3050 /* For VDetachVolume, we close all cached file descriptors, but keep
3051  * the Inode handles in case we need to read from a busy volume.
3052  */
3053 /* for demand attach, caller MUST hold ref count on vp */
3054 static void
3055 VCloseVolumeHandles_r(Volume * vp)
3056 {
3057 #ifdef AFS_DEMAND_ATTACH_FS
3058     VolState state_save;
3059
3060     state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
3061 #endif
3062
3063     /* demand attach fs
3064      *
3065      * XXX need to investigate whether we can perform
3066      * DFlushVolume outside of vol_glock_mutex... 
3067      *
3068      * VCloseVnodeFiles_r drops the glock internally */
3069     DFlushVolume(V_id(vp));
3070     VCloseVnodeFiles_r(vp);
3071
3072 #ifdef AFS_DEMAND_ATTACH_FS
3073     VOL_UNLOCK;
3074 #endif
3075
3076     /* Too time consuming and unnecessary for the volserver */
3077     if (programType != volumeUtility) {
3078         IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
3079         IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
3080         IH_CONDSYNC(vp->diskDataHandle);
3081 #ifdef AFS_NT40_ENV
3082         IH_CONDSYNC(vp->linkHandle);
3083 #endif /* AFS_NT40_ENV */
3084     }
3085
3086     IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
3087     IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
3088     IH_REALLYCLOSE(vp->diskDataHandle);
3089     IH_REALLYCLOSE(vp->linkHandle);
3090
3091 #ifdef AFS_DEMAND_ATTACH_FS
3092     VOL_LOCK;
3093     VChangeState_r(vp, state_save);
3094 #endif
3095 }
3096
3097 /* For both VForceOffline and VOffline, we close all relevant handles.
3098  * For VOffline, if we re-attach the volume, the files may possible be
3099  * different than before. 
3100  */
3101 /* for demand attach, caller MUST hold a ref count on vp */
3102 static void
3103 VReleaseVolumeHandles_r(Volume * vp)
3104 {
3105 #ifdef AFS_DEMAND_ATTACH_FS
3106     VolState state_save;
3107
3108     state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
3109 #endif
3110
3111     /* XXX need to investigate whether we can perform
3112      * DFlushVolume outside of vol_glock_mutex... */
3113     DFlushVolume(V_id(vp));
3114
3115     VReleaseVnodeFiles_r(vp); /* releases the glock internally */
3116
3117 #ifdef AFS_DEMAND_ATTACH_FS
3118     VOL_UNLOCK;
3119 #endif
3120
3121     /* Too time consuming and unnecessary for the volserver */
3122     if (programType != volumeUtility) {
3123         IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
3124         IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
3125         IH_CONDSYNC(vp->diskDataHandle);
3126 #ifdef AFS_NT40_ENV
3127         IH_CONDSYNC(vp->linkHandle);
3128 #endif /* AFS_NT40_ENV */
3129     }
3130
3131     IH_RELEASE(vp->vnodeIndex[vLarge].handle);
3132     IH_RELEASE(vp->vnodeIndex[vSmall].handle);
3133     IH_RELEASE(vp->diskDataHandle);
3134     IH_RELEASE(vp->linkHandle);
3135
3136 #ifdef AFS_DEMAND_ATTACH_FS
3137     VOL_LOCK;
3138     VChangeState_r(vp, state_save);
3139 #endif
3140 }
3141
3142
3143 /***************************************************/
3144 /* Volume write and fsync routines                 */
3145 /***************************************************/
3146
3147 void
3148 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
3149 {
3150 #ifdef AFS_DEMAND_ATTACH_FS
3151     VolState state_save;
3152
3153     if (flags & VOL_UPDATE_WAIT) {
3154         VCreateReservation_r(vp);
3155         VWaitExclusiveState_r(vp);
3156     }
3157 #endif
3158
3159     *ec = 0;
3160     if (programType == fileServer)
3161         V_uniquifier(vp) =
3162             (V_inUse(vp) ? V_nextVnodeUnique(vp) +
3163              200 : V_nextVnodeUnique(vp));
3164
3165 #ifdef AFS_DEMAND_ATTACH_FS
3166     state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
3167     VOL_UNLOCK;
3168 #endif
3169
3170     WriteVolumeHeader_r(ec, vp);
3171
3172 #ifdef AFS_DEMAND_ATTACH_FS
3173     VOL_LOCK;
3174     VChangeState_r(vp, state_save);
3175     if (flags & VOL_UPDATE_WAIT) {
3176         VCancelReservation_r(vp);
3177     }
3178 #endif
3179
3180     if (*ec) {
3181         Log("VUpdateVolume: error updating volume header, volume %u (%s)\n",
3182             V_id(vp), V_name(vp));
3183         /* try to update on-disk header, 
3184          * while preventing infinite recursion */
3185         if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
3186             VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
3187         }
3188     }
3189 }
3190
3191 void
3192 VUpdateVolume(Error * ec, Volume * vp)
3193 {
3194     VOL_LOCK;
3195     VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
3196     VOL_UNLOCK;
3197 }
3198
3199 void
3200 VSyncVolume_r(Error * ec, Volume * vp, int flags)
3201 {
3202     FdHandle_t *fdP;
3203     int code;
3204 #ifdef AFS_DEMAND_ATTACH_FS
3205     VolState state_save;
3206 #endif
3207
3208     if (flags & VOL_SYNC_WAIT) {
3209         VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
3210     } else {
3211         VUpdateVolume_r(ec, vp, 0);
3212     }
3213     if (!*ec) {
3214 #ifdef AFS_DEMAND_ATTACH_FS
3215         state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
3216         VOL_UNLOCK;
3217 #endif
3218         fdP = IH_OPEN(V_diskDataHandle(vp));
3219         assert(fdP != NULL);
3220         code = FDH_SYNC(fdP);
3221         assert(code == 0);
3222         FDH_CLOSE(fdP);
3223 #ifdef AFS_DEMAND_ATTACH_FS
3224         VOL_LOCK;
3225         VChangeState_r(vp, state_save);
3226 #endif
3227     }
3228 }
3229
3230 void
3231 VSyncVolume(Error * ec, Volume * vp)
3232 {
3233     VOL_LOCK;
3234     VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
3235     VOL_UNLOCK;
3236 }
3237
3238
3239 /***************************************************/
3240 /* Volume dealloaction routines                    */
3241 /***************************************************/
3242
3243 #ifdef AFS_DEMAND_ATTACH_FS
3244 static void
3245 FreeVolume(Volume * vp)
3246 {
3247     /* free the heap space, iff it's safe.
3248      * otherwise, pull it out of the hash table, so it
3249      * will get deallocated when all refs to it go away */
3250     if (!VCheckFree(vp)) {
3251         DeleteVolumeFromHashTable(vp);
3252         DeleteVolumeFromVByPList_r(vp);
3253
3254         /* make sure we invalidate the header cache entry */
3255         FreeVolumeHeader(vp);
3256     }
3257 }
3258 #endif /* AFS_DEMAND_ATTACH_FS */
3259
3260 static void
3261 ReallyFreeVolume(Volume * vp)
3262 {
3263     int i;
3264     if (!vp)
3265         return;
3266 #ifdef AFS_DEMAND_ATTACH_FS
3267     /* debug */
3268     VChangeState_r(vp, VOL_STATE_FREED);
3269     if (vp->pending_vol_op)
3270         free(vp->pending_vol_op);
3271 #endif /* AFS_DEMAND_ATTACH_FS */
3272     for (i = 0; i < nVNODECLASSES; i++)
3273         if (vp->vnodeIndex[i].bitmap)
3274             free(vp->vnodeIndex[i].bitmap);
3275     FreeVolumeHeader(vp);
3276 #ifndef AFS_DEMAND_ATTACH_FS
3277     DeleteVolumeFromHashTable(vp);
3278 #endif /* AFS_DEMAND_ATTACH_FS */
3279     free(vp);
3280 }
3281
3282 /* check to see if we should shutdown this volume
3283  * returns 1 if volume was freed, 0 otherwise */
3284 #ifdef AFS_DEMAND_ATTACH_FS
3285 static int
3286 VCheckDetach(register Volume * vp)
3287 {
3288     int ret = 0;
3289
3290     if (vp->nUsers || vp->nWaiters)
3291         return ret;
3292
3293     if (vp->shuttingDown) {
3294         ret = 1;
3295         VReleaseVolumeHandles_r(vp);
3296         VCheckSalvage(vp);
3297         ReallyFreeVolume(vp);
3298         if (programType == fileServer) {
3299             assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3300         }
3301     }
3302     return ret;
3303 }
3304 #else /* AFS_DEMAND_ATTACH_FS */
3305 static int
3306 VCheckDetach(register Volume * vp)
3307 {
3308     int ret = 0;
3309
3310     if (vp->nUsers)
3311         return ret;
3312
3313     if (vp->shuttingDown) {
3314         ret = 1;
3315         VReleaseVolumeHandles_r(vp);
3316         ReallyFreeVolume(vp);
3317         if (programType == fileServer) {
3318 #if defined(AFS_PTHREAD_ENV)
3319             assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3320 #else /* AFS_PTHREAD_ENV */
3321             LWP_NoYieldSignal(VPutVolume);
3322 #endif /* AFS_PTHREAD_ENV */
3323         }
3324     }
3325     return ret;
3326 }
3327 #endif /* AFS_DEMAND_ATTACH_FS */
3328
3329 /* check to see if we should offline this volume
3330  * return 1 if volume went offline, 0 otherwise */
3331 #ifdef AFS_DEMAND_ATTACH_FS
3332 static int
3333 VCheckOffline(register Volume * vp)
3334 {
3335     Volume * rvp = NULL;
3336     int ret = 0;
3337
3338     if (vp->goingOffline && !vp->nUsers) {
3339         Error error;
3340         assert(programType == fileServer);
3341         assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
3342                (V_attachState(vp) != VOL_STATE_FREED) &&
3343                (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
3344                (V_attachState(vp) != VOL_STATE_UNATTACHED));
3345
3346         /* valid states:
3347          *
3348          * VOL_STATE_GOING_OFFLINE
3349          * VOL_STATE_SHUTTING_DOWN
3350          * IsErrorState(V_attachState(vp))
3351          * IsExclusiveState(V_attachState(vp))
3352          */
3353
3354         VCreateReservation_r(vp);
3355         VChangeState_r(vp, VOL_STATE_OFFLINING);
3356
3357         ret = 1;
3358         /* must clear the goingOffline flag before we drop the glock */
3359         vp->goingOffline = 0;
3360         V_inUse(vp) = 0;
3361
3362         VLRU_Delete_r(vp);
3363
3364         /* perform async operations */
3365         VUpdateVolume_r(&error, vp, 0);
3366         VCloseVolumeHandles_r(vp);
3367
3368         if (LogLevel) {
3369             Log("VOffline: Volume %u (%s) is now offline", V_id(vp),
3370                 V_name(vp));
3371             if (V_offlineMessage(vp)[0])
3372                 Log(" (%s)", V_offlineMessage(vp));
3373             Log("\n");
3374         }
3375
3376         /* invalidate the volume header cache entry */
3377         FreeVolumeHeader(vp);
3378
3379         /* if nothing changed state to error or salvaging,
3380          * drop state to unattached */
3381         if (!IsErrorState(V_attachState(vp))) {
3382             VChangeState_r(vp, VOL_STATE_UNATTACHED);
3383         }
3384         VCancelReservation_r(vp);
3385         /* no usage of vp is safe beyond this point */
3386     }
3387     return ret;
3388 }
3389 #else /* AFS_DEMAND_ATTACH_FS */
3390 static int
3391 VCheckOffline(register Volume * vp)
3392 {
3393     Volume * rvp = NULL;
3394     int ret = 0;
3395
3396     if (vp->goingOffline && !vp->nUsers) {
3397         Error error;
3398         assert(programType == fileServer);
3399
3400         ret = 1;
3401         vp->goingOffline = 0;
3402         V_inUse(vp) = 0;
3403         VUpdateVolume_r(&error, vp, 0);
3404         VCloseVolumeHandles_r(vp);
3405         if (LogLevel) {
3406             Log("VOffline: Volume %u (%s) is now offline", V_id(vp),
3407                 V_name(vp));
3408             if (V_offlineMessage(vp)[0])
3409                 Log(" (%s)", V_offlineMessage(vp));
3410             Log("\n");
3411         }
3412         FreeVolumeHeader(vp);
3413 #ifdef AFS_PTHREAD_ENV
3414         assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3415 #else /* AFS_PTHREAD_ENV */
3416         LWP_NoYieldSignal(VPutVolume);
3417 #endif /* AFS_PTHREAD_ENV */
3418     }
3419     return ret;
3420 }
3421 #endif /* AFS_DEMAND_ATTACH_FS */
3422
3423 /***************************************************/
3424 /* demand attach fs ref counting routines          */
3425 /***************************************************/
3426
3427 #ifdef AFS_DEMAND_ATTACH_FS
3428 /* the following two functions handle reference counting for
3429  * asynchronous operations on volume structs.
3430  *
3431  * their purpose is to prevent a VDetachVolume or VShutdown
3432  * from free()ing the Volume struct during an async i/o op */
3433
3434 /* register with the async volume op ref counter */
3435 static void
3436 VCreateReservation_r(Volume * vp)
3437 {
3438     vp->nWaiters++;
3439 }
3440
3441 /* unregister with the async volume op ref counter */
3442 static void
3443 VCancelReservation_r(Volume * vp)
3444 {
3445     assert(--vp->nWaiters >= 0);
3446     if (vp->nWaiters == 0) {
3447         VCheckOffline(vp);
3448         if (!VCheckDetach(vp)) {
3449             VCheckSalvage(vp);
3450             VCheckFree(vp);
3451         }
3452     }
3453 }
3454
3455 /* check to see if we should free this volume now
3456  * return 1 if volume was freed, 0 otherwise */
3457 static int
3458 VCheckFree(Volume * vp)
3459 {
3460     int ret = 0;
3461     if ((vp->nUsers == 0) &&
3462         (vp->nWaiters == 0) &&
3463         !(V_attachFlags(vp) & (VOL_IN_HASH | 
3464                                VOL_ON_VBYP_LIST | 
3465                                VOL_IS_BUSY |
3466                                VOL_ON_VLRU))) {
3467         ReallyFreeVolume(vp);
3468         ret = 1;
3469     }
3470     return ret;
3471 }
3472 #endif /* AFS_DEMAND_ATTACH_FS */
3473
3474
3475 /***************************************************/
3476 /* online volume operations routines               */
3477 /***************************************************/
3478
3479 #ifdef AFS_DEMAND_ATTACH_FS
3480 int
3481 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3482 {
3483     FSSYNC_VolOp_info * info;
3484
3485     /* attach a vol op info node to the volume struct */
3486     info = (FSSYNC_VolOp_info *) malloc(sizeof(FSSYNC_VolOp_info));
3487     assert(info != NULL);
3488     memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
3489     vp->pending_vol_op = info;
3490
3491     /* update stats */
3492     vp->stats.last_vol_op = FT_ApproxTime();
3493     vp->stats.vol_ops++;
3494     IncUInt64(&VStats.vol_ops);
3495
3496     return 0;
3497 }
3498
3499 int
3500 VDeregisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3501 {
3502     if (vp->pending_vol_op) {
3503         free(vp->pending_vol_op);
3504         vp->pending_vol_op = NULL;
3505     }
3506     return 0;
3507 }
3508 #endif /* AFS_DEMAND_ATTACH_FS */
3509
3510 int
3511 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3512 {
3513     return (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
3514             (vopinfo->com.reason == V_READONLY ||
3515              (!VolumeWriteable(vp) &&
3516               (vopinfo->com.reason == V_CLONE ||
3517                vopinfo->com.reason == V_DUMP))));
3518 }
3519
3520 int
3521 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3522 {
3523     return (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
3524             (vopinfo->com.reason == V_CLONE ||
3525              vopinfo->com.reason == V_DUMP));
3526 }
3527
3528
3529 /***************************************************/
3530 /* online salvager routines                        */
3531 /***************************************************/
3532 #if defined(AFS_DEMAND_ATTACH_FS)
3533 #define SALVAGE_PRIO_UPDATE_INTERVAL 3      /* number of seconds between prio updates */
3534 #define SALVAGE_COUNT_MAX 16                /* number of online salvages we
3535                                              * allow before moving the volume
3536                                              * into a permanent error state
3537                                              *
3538                                              * once this threshold is reached,
3539                                              * the operator will have to manually
3540                                              * issue a 'bos salvage' to bring
3541                                              * the volume back online
3542                                              */
3543
3544 /* check to see if we should salvage this volume
3545  * returns 1 if salvage scheduled, 0 otherwise */
3546 static int
3547 VCheckSalvage(register Volume * vp)
3548 {
3549     int ret = 0;
3550 #ifdef SALVSYNC_BUILD_CLIENT
3551     if (vp->nUsers || vp->nWaiters)
3552         return ret;
3553     if (vp->salvage.requested) {
3554         VScheduleSalvage_r(vp);
3555         ret = 1;
3556     }
3557 #endif /* SALVSYNC_BUILD_CLIENT */
3558     return ret;
3559 }
3560
3561 /*
3562  * request that a salvage be performed once
3563  * ref counts reach zero
3564  */
3565 int
3566 VRequestSalvage_r(Volume * vp, int reason, int flags)
3567 {
3568 #ifdef SALVSYNC_BUILD_CLIENT
3569     if (programType != fileServer)
3570         return 1;
3571
3572     if (!vp->salvage.requested) {
3573         vp->salvage.requested = 1;
3574         vp->salvage.reason = reason;
3575         vp->stats.last_salvage = FT_ApproxTime();
3576         if (flags & VOL_SALVAGE_INVALIDATE_HEADER) {
3577             ReleaseVolumeHeader(vp->header);
3578         }
3579         if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
3580             VChangeState_r(vp, VOL_STATE_SALVAGING);
3581         } else {
3582             Log("VRequestSalvage: volume %u online salvaged too many times; forced offline.\n", vp->hashid);
3583             VChangeState_r(vp, VOL_STATE_ERROR);
3584         }
3585     }
3586 #endif /* SALVSYNC_BUILD_CLIENT */
3587     return 0;
3588 }
3589
3590 /*
3591  * update salvage priority
3592  */
3593 static int
3594 VUpdateSalvagePriority_r(Volume * vp)
3595 {
3596     int code, ret=0;
3597     afs_uint32 now;
3598
3599 #ifdef SALVSYNC_BUILD_CLIENT
3600     vp->salvage.prio++;
3601     now = FT_ApproxTime();
3602
3603     /* update the salvageserver priority queue occasionally so that
3604      * frequently requested volumes get moved to the head of the queue 
3605      */
3606     if ((vp->salvage.scheduled) &&
3607         (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
3608         code = SALVSYNC_SalvageVolume(vp->hashid,
3609                                       VPartitionPath(vp->partition),
3610                                       SALVSYNC_RAISEPRIO,
3611                                       vp->salvage.reason,
3612                                       vp->salvage.prio,
3613                                       NULL);
3614         vp->stats.last_salvage_req = now;
3615         if (code != SYNC_OK) {
3616             ret = 1;
3617         }
3618     }
3619 #endif /* SALVSYNC_BUILD_CLIENT */
3620     return ret;
3621 }
3622
3623
3624 /*
3625  * schedule a salvage with the salvage server
3626  */
3627 static int
3628 VScheduleSalvage_r(Volume * vp)
3629 {
3630     int code, ret=0;
3631 #ifdef SALVSYNC_BUILD_CLIENT
3632     VolState state_save;
3633     char partName[16];
3634
3635     if (vp->nWaiters || vp->nUsers) {
3636         return 1;
3637     }
3638
3639     /* prevent endless salvage,attach,salvage,attach,... loops */
3640     if (vp->stats.salvages >= SALVAGE_COUNT_MAX)
3641         return 1;
3642
3643     if (!vp->salvage.scheduled) {
3644         /* if we haven't previously scheduled a salvage, do so now 
3645          *
3646          * set the volume to an exclusive state and drop the lock
3647          * around the SALVSYNC call
3648          */
3649         strlcpy(partName, VPartitionPath(vp->partition), sizeof(partName));
3650         state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
3651         V_attachFlags(vp) |= VOL_IS_BUSY;
3652         VOL_UNLOCK;
3653
3654         /* can't use V_id() since there's no guarantee
3655          * we have the disk data header at this point */
3656         code = SALVSYNC_SalvageVolume(vp->hashid,
3657                                       partName,
3658                                       SALVSYNC_SALVAGE,
3659                                       vp->salvage.reason,
3660                                       vp->salvage.prio,
3661                                       NULL);
3662         VOL_LOCK;
3663         VChangeState_r(vp, state_save);
3664         V_attachFlags(vp) &= ~(VOL_IS_BUSY);
3665
3666         if (code == SYNC_OK) {
3667             vp->salvage.scheduled = 1;
3668             vp->stats.salvages++;
3669             vp->stats.last_salvage_req = FT_ApproxTime();
3670             IncUInt64(&VStats.salvages);
3671         } else {
3672             ret = 1;
3673             switch(code) {
3674             case SYNC_BAD_COMMAND:
3675             case SYNC_COM_ERROR:
3676                 break;
3677             case SYNC_DENIED:
3678                 Log("VScheduleSalvage_r:  SALVSYNC request denied\n");
3679                 break;
3680             default:
3681                 Log("VScheduleSalvage_r:  SALVSYNC unknown protocol error\n");
3682                 break;
3683             }
3684         }
3685     }
3686 #endif /* SALVSYNC_BUILD_CLIENT */
3687     return ret;
3688 }
3689
3690 /*
3691  * cancel a scheduled salvage operation
3692  */
3693 static int
3694 VCancelSalvage_r(Volume * vp, int reason)
3695 {
3696     int code, ret = 0;
3697
3698 #ifdef SALVSYNC_BUILD_CLIENT
3699     if (vp->salvage.scheduled) {
3700         code = SALVSYNC_SalvageVolume(vp->hashid,
3701                                       VPartitionPath(vp->partition),
3702                                       SALVSYNC_CANCEL,
3703                                       reason,
3704                                       0,
3705                                       NULL);
3706         if (code == SYNC_OK) {
3707             vp->salvage.scheduled = 0;
3708         } else {
3709             ret = 1;
3710         }
3711     }
3712 #endif /* SALVSYNC_BUILD_CLIENT */
3713     return ret;
3714 }
3715
3716 /* This must be called by any volume utility which needs to run while the
3717    file server is also running.  This is separated from VInitVolumePackage so
3718    that a utility can fork--and each of the children can independently
3719    initialize communication with the file server */
3720 #ifdef SALVSYNC_BUILD_CLIENT
3721 int
3722 VConnectSALV(void)
3723 {
3724     int retVal;
3725     VOL_LOCK;
3726     retVal = VConnectSALV_r();
3727     VOL_UNLOCK;
3728     return retVal;
3729 }
3730
3731 int
3732 VConnectSALV_r(void)
3733 {
3734     return SALVSYNC_clientInit();
3735 }
3736
3737 int
3738 VDisconnectSALV(void)
3739 {
3740     int retVal;
3741     VOL_LOCK;
3742     VDisconnectSALV_r();
3743     VOL_UNLOCK;
3744     return retVal;
3745 }
3746
3747 int
3748 VDisconnectSALV_r(void)
3749
3750     return SALVSYNC_clientFinis();
3751 }
3752
3753 int
3754 VReconnectSALV(void)
3755 {
3756     int retVal;
3757     VOL_LOCK;
3758     retVal = VReconnectSALV_r();
3759     VOL_UNLOCK;
3760     return retVal;
3761 }
3762
3763 int
3764 VReconnectSALV_r(void)
3765 {
3766     return SALVSYNC_clientReconnect();
3767 }
3768 #endif /* SALVSYNC_BUILD_CLIENT */
3769 #endif /* AFS_DEMAND_ATTACH_FS */
3770
3771
3772 /***************************************************/
3773 /* FSSYNC routines                                 */
3774 /***************************************************/
3775
3776 /* This must be called by any volume utility which needs to run while the
3777    file server is also running.  This is separated from VInitVolumePackage so
3778    that a utility can fork--and each of the children can independently
3779    initialize communication with the file server */
3780 #ifdef FSSYNC_BUILD_CLIENT
3781 int
3782 VConnectFS(void)
3783 {
3784     int retVal;
3785     VOL_LOCK;
3786     retVal = VConnectFS_r();
3787     VOL_UNLOCK;
3788     return retVal;
3789 }
3790
3791 int
3792 VConnectFS_r(void)
3793 {
3794     int rc;
3795     assert((VInit == 2) && 
3796            (programType != fileServer) &&
3797            (programType != salvager));
3798     rc = FSYNC_clientInit();
3799     if (rc)
3800         VInit = 3;
3801     return rc;
3802 }
3803
3804 void
3805 VDisconnectFS_r(void)
3806 {
3807     assert((programType != fileServer) &&
3808            (programType != salvager));
3809     FSYNC_clientFinis();
3810     VInit = 2;
3811 }
3812
3813 void
3814 VDisconnectFS(void)
3815 {
3816     VOL_LOCK;
3817     VDisconnectFS_r();
3818     VOL_UNLOCK;
3819 }
3820
3821 int
3822 VChildProcReconnectFS_r(void)
3823 {
3824     return FSYNC_clientChildProcReconnect();
3825 }
3826
3827 int
3828 VChildProcReconnectFS(void)
3829 {
3830     int ret;
3831     VOL_LOCK;
3832     ret = VChildProcReconnectFS_r();
3833     VOL_UNLOCK;
3834     return ret;
3835 }
3836 #endif /* FSSYNC_BUILD_CLIENT */
3837
3838
3839 /***************************************************/
3840 /* volume bitmap routines                          */
3841 /***************************************************/
3842
3843 /*
3844  * For demand attach fs, flags parameter controls
3845  * locking behavior.  If (flags & VOL_ALLOC_BITMAP_WAIT)
3846  * is set, then this function will create a reservation
3847  * and block on any other exclusive operations.  Otherwise,
3848  * this function assumes the caller already has exclusive
3849  * access to vp, and we just change the volume state.
3850  */
3851 VnodeId
3852 VAllocBitmapEntry_r(Error * ec, Volume * vp, 
3853                     struct vnodeIndex *index, int flags)
3854 {
3855     VnodeId ret;
3856     register byte *bp, *ep;
3857 #ifdef AFS_DEMAND_ATTACH_FS
3858     VolState state_save;
3859 #endif /* AFS_DEMAND_ATTACH_FS */
3860
3861     *ec = 0;
3862
3863     /* This test is probably redundant */
3864     if (!VolumeWriteable(vp)) {
3865         *ec = (bit32) VREADONLY;
3866         return 0;
3867     }
3868
3869 #ifdef AFS_DEMAND_ATTACH_FS
3870     if (flags & VOL_ALLOC_BITMAP_WAIT) {
3871         VCreateReservation_r(vp);
3872         VWaitExclusiveState_r(vp);
3873     }
3874     state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
3875 #endif /* AFS_DEMAND_ATTACH_FS */
3876
3877 #ifdef BITMAP_LATER
3878     if ((programType == fileServer) && !index->bitmap) {
3879         int i;
3880 #ifndef AFS_DEMAND_ATTACH_FS
3881         /* demand attach fs uses the volume state to avoid races.
3882          * specialStatus field is not used at all */
3883         int wasVBUSY = 0;
3884         if (vp->specialStatus == VBUSY) {
3885             if (vp->goingOffline) {     /* vos dump waiting for the volume to
3886                                          * go offline. We probably come here
3887                                          * from AddNewReadableResidency */
3888                 wasVBUSY = 1;
3889             } else {
3890                 while (vp->specialStatus == VBUSY) {
3891 #ifdef AFS_PTHREAD_ENV
3892                     VOL_UNLOCK;
3893                     sleep(2);
3894                     VOL_LOCK;
3895 #else /* AFS_PTHREAD_ENV */
3896                     IOMGR_Sleep(2);
3897 #endif /* AFS_DEMAND_ATTACH_FS */
3898                 }
3899             }
3900         }
3901 #endif /* !AFS_DEMAND_ATTACH_FS */
3902
3903         if (!index->bitmap) {
3904 #ifndef AFS_DEMAND_ATTACH_FS
3905             vp->specialStatus = VBUSY;  /* Stop anyone else from using it. */
3906 #endif /* AFS_DEMAND_ATTACH_FS */
3907             for (i = 0; i < nVNODECLASSES; i++) {
3908                 VGetBitmap_r(ec, vp, i);
3909                 if (*ec) {
3910 #ifdef AFS_DEMAND_ATTACH_FS
3911                     VRequestSalvage_r(vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3912                     *ec = VSALVAGING;
3913 #else /* AFS_DEMAND_ATTACH_FS */
3914                     DeleteVolumeFromHashTable(vp);
3915                     vp->shuttingDown = 1;       /* Let who has it free it. */
3916                     vp->specialStatus = 0;
3917 #endif /* AFS_DEMAND_ATTACH_FS */
3918                     ret = NULL;
3919                     goto done;
3920                 }
3921             }
3922 #ifndef AFS_DEMAND_ATTACH_FS
3923             if (!wasVBUSY)
3924                 vp->specialStatus = 0;  /* Allow others to have access. */
3925 #endif /* AFS_DEMAND_ATTACH_FS */
3926         }
3927     }
3928 #endif /* BITMAP_LATER */
3929
3930 #ifdef AFS_DEMAND_ATTACH_FS
3931     VOL_UNLOCK;
3932 #endif /* AFS_DEMAND_ATTACH_FS */
3933     bp = index->bitmap + index->bitmapOffset;
3934     ep = index->bitmap + index->bitmapSize;
3935     while (bp < ep) {
3936         if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
3937             int o;
3938             index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
3939             while (*bp == 0xff)
3940                 bp++;
3941             o = ffs(~*bp) - 1;  /* ffs is documented in BSTRING(3) */
3942             *bp |= (1 << o);
3943             ret = (VnodeId) ((bp - index->bitmap) * 8 + o);
3944 #ifdef AFS_DEMAND_ATTACH_FS
3945             VOL_LOCK;
3946 #endif /* AFS_DEMAND_ATTACH_FS */
3947             goto done;
3948         }
3949         bp += sizeof(bit32) /* i.e. 4 */ ;
3950     }
3951     /* No bit map entry--must grow bitmap */
3952     bp = (byte *)
3953         realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
3954     assert(bp != NULL);
3955     index->bitmap = bp;
3956     bp += index->bitmapSize;
3957     memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
3958     index->bitmapOffset = index->bitmapSize;
3959     index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
3960     *bp = 1;
3961     ret = index->bitmapOffset * 8;
3962 #ifdef AFS_DEMAND_ATTACH_FS
3963     VOL_LOCK;
3964 #endif /* AFS_DEMAND_ATTACH_FS */
3965
3966  done:
3967 #ifdef AFS_DEMAND_ATTACH_FS
3968     VChangeState_r(vp, state_save);
3969     if (flags & VOL_ALLOC_BITMAP_WAIT) {
3970         VCancelReservation_r(vp);
3971     }
3972 #endif /* AFS_DEMAND_ATTACH_FS */
3973     return ret;
3974 }
3975
3976 VnodeId
3977 VAllocBitmapEntry(Error * ec, Volume * vp, register struct vnodeIndex * index)
3978 {
3979     VnodeId retVal;
3980     VOL_LOCK;
3981     retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
3982     VOL_UNLOCK;
3983     return retVal;
3984 }
3985
3986 void
3987 VFreeBitMapEntry_r(Error * ec, register struct vnodeIndex *index,
3988                    unsigned bitNumber)
3989 {
3990     unsigned int offset;
3991
3992     *ec = 0;
3993 #ifdef BITMAP_LATER
3994     if (!index->bitmap)
3995         return;
3996 #endif /* BITMAP_LATER */
3997     offset = bitNumber >> 3;
3998     if (offset >= index->bitmapSize) {
3999         *ec = VNOVNODE;
4000         return;
4001     }
4002     if (offset < index->bitmapOffset)
4003         index->bitmapOffset = offset & ~3;      /* Truncate to nearest bit32 */
4004     *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
4005 }
4006
4007 void
4008 VFreeBitMapEntry(Error * ec, register struct vnodeIndex *index,
4009                  unsigned bitNumber)
4010 {
4011     VOL_LOCK;
4012     VFreeBitMapEntry_r(ec, index, bitNumber);
4013     VOL_UNLOCK;
4014 }
4015
4016 /* this function will drop the glock internally.
4017  * for old pthread fileservers, this is safe thanks to vbusy.
4018  *
4019  * for demand attach fs, caller must have already called
4020  * VCreateReservation_r and VWaitExclusiveState_r */
4021 static void
4022 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
4023 {
4024     StreamHandle_t *file;
4025     int nVnodes;
4026     int size;
4027     struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
4028     struct vnodeIndex *vip = &vp->vnodeIndex[class];
4029     struct VnodeDiskObject *vnode;
4030     unsigned int unique = 0;
4031     FdHandle_t *fdP;
4032 #ifdef BITMAP_LATER
4033     byte *BitMap = 0;
4034 #endif /* BITMAP_LATER */
4035 #ifdef AFS_DEMAND_ATTACH_FS
4036     VolState state_save;
4037 #endif /* AFS_DEMAND_ATTACH_FS */
4038
4039     *ec = 0;
4040
4041 #ifdef AFS_DEMAND_ATTACH_FS
4042     state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
4043 #endif /* AFS_DEMAND_ATTACH_FS */
4044     VOL_UNLOCK;
4045
4046     fdP = IH_OPEN(vip->handle);
4047     assert(fdP != NULL);
4048     file = FDH_FDOPEN(fdP, "r");
4049     assert(file != NULL);
4050     vnode = (VnodeDiskObject *) malloc(vcp->diskSize);
4051     assert(vnode != NULL);
4052     size = OS_SIZE(fdP->fd_fd);
4053     assert(size != -1);
4054     nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
4055         >> vcp->logSize;
4056     vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4;     /* The 10 is a little extra so
4057                                                          * a few files can be created in this volume,
4058                                                          * the whole thing is rounded up to nearest 4
4059                                                          * bytes, because the bit map allocator likes
4060                                                          * it that way */
4061 #ifdef BITMAP_LATER
4062     BitMap = (byte *) calloc(1, vip->bitmapSize);
4063     assert(BitMap != NULL);
4064 #else /* BITMAP_LATER */
4065     vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
4066     assert(vip->bitmap != NULL);
4067     vip->bitmapOffset = 0;
4068 #endif /* BITMAP_LATER */
4069     if (STREAM_SEEK(file, vcp->diskSize, 0) != -1) {
4070         int bitNumber = 0;
4071         for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
4072             if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
4073                 break;
4074             if (vnode->type != vNull) {
4075                 if (vnode->vnodeMagic != vcp->magic) {
4076                     Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
4077                     *ec = VSALVAGE;
4078                     break;
4079                 }
4080 #ifdef BITMAP_LATER
4081                 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
4082 #else /* BITMAP_LATER */
4083                 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
4084 #endif /* BITMAP_LATER */
4085                 if (unique <= vnode->uniquifier)
4086                     unique = vnode->uniquifier + 1;
4087             }
4088 #ifndef AFS_PTHREAD_ENV
4089             if ((bitNumber & 0x00ff) == 0x0ff) {        /* every 256 iterations */
4090                 IOMGR_Poll();
4091             }
4092 #endif /* !AFS_PTHREAD_ENV */
4093         }
4094     }
4095     if (vp->nextVnodeUnique < unique) {
4096         Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
4097         *ec = VSALVAGE;
4098     }
4099     /* Paranoia, partly justified--I think fclose after fdopen
4100      * doesn't seem to close fd.  In any event, the documentation
4101      * doesn't specify, so it's safer to close it twice.
4102      */
4103     STREAM_CLOSE(file);
4104     FDH_CLOSE(fdP);
4105     free(vnode);
4106
4107     VOL_LOCK;
4108 #ifdef BITMAP_LATER
4109     /* There may have been a racing condition with some other thread, both
4110      * creating the bitmaps for this volume. If the other thread was faster
4111      * the pointer to bitmap should already be filled and we can free ours.
4112      */
4113     if (vip->bitmap == NULL) {
4114         vip->bitmap = BitMap;
4115         vip->bitmapOffset = 0;
4116     } else
4117         free((byte *) BitMap);
4118 #endif /* BITMAP_LATER */
4119 #ifdef AFS_DEMAND_ATTACH_FS
4120     VChangeState_r(vp, state_save);
4121 #endif /* AFS_DEMAND_ATTACH_FS */
4122 }
4123
4124
4125 /***************************************************/
4126 /* demand attach fs state machine routines         */
4127 /***************************************************/
4128
4129 #ifdef AFS_DEMAND_ATTACH_FS
4130 /* wait for the volume to change states */
4131 static void
4132 VWaitStateChange_r(Volume * vp)
4133 {
4134     VolState state_save = V_attachState(vp);
4135
4136     assert(vp->nWaiters || vp->nUsers);
4137     do {
4138         assert(pthread_cond_wait(&V_attachCV(vp), &vol_glock_mutex) == 0);
4139     } while (V_attachState(vp) == state_save);
4140     assert(V_attachState(vp) != VOL_STATE_FREED);
4141 }
4142
4143 /* wait for blocking ops to end */
4144 static void
4145 VWaitExclusiveState_r(Volume * vp)
4146 {
4147     assert(vp->nWaiters || vp->nUsers);
4148     while (IsExclusiveState(V_attachState(vp))) {
4149         assert(pthread_cond_wait(&V_attachCV(vp), &vol_glock_mutex) == 0);
4150     }
4151     assert(V_attachState(vp) != VOL_STATE_FREED);
4152 }
4153
4154 /* change state, and notify other threads,
4155  * return previous state to caller */
4156 VolState
4157 VChangeState_r(Volume * vp, VolState new_state)
4158 {
4159     VolState old_state = V_attachState(vp);
4160
4161     /* XXX profiling need to make sure these counters
4162      * don't kill performance... */
4163     VStats.state_levels[old_state]--;
4164     VStats.state_levels[new_state]++;
4165
4166     V_attachState(vp) = new_state;
4167     assert(pthread_cond_broadcast(&V_attachCV(vp)) == 0);
4168     return old_state;
4169 }
4170
4171 /* tells caller whether or not the current state requires
4172  * exclusive access without holding glock */
4173 static int
4174 IsExclusiveState(VolState state)
4175 {
4176     switch (state) {
4177     case VOL_STATE_UPDATING:
4178     case VOL_STATE_ATTACHING:
4179     case VOL_STATE_GET_BITMAP:
4180     case VOL_STATE_HDR_LOADING:
4181     case VOL_STATE_HDR_ATTACHING:
4182     case VOL_STATE_OFFLINING:
4183     case VOL_STATE_DETACHING:
4184         return 1;
4185     }
4186     return 0;
4187 }
4188
4189 /* tell caller whether V_attachState is an error condition */
4190 static int
4191 IsErrorState(VolState state)
4192 {
4193     switch (state) {
4194     case VOL_STATE_ERROR:
4195     case VOL_STATE_SALVAGING:
4196         return 1;
4197     }
4198     return 0;
4199 }
4200
4201 /* tell caller whether V_attachState is valid */
4202 static int
4203 IsValidState(VolState state)
4204 {
4205     if ((state >= 0) && 
4206         (state < VOL_STATE_COUNT) &&
4207         (state != VOL_STATE_FREED)) {
4208         return 1;
4209     }
4210     return 0;
4211 }
4212 #endif /* AFS_DEMAND_ATTACH_FS */
4213
4214
4215 /***************************************************/
4216 /* Volume Path and Volume Number utility routines  */
4217 /***************************************************/
4218
4219 static void
4220 GetVolumePath(Error * ec, VolId volumeId, char **partitionp, char **namep)
4221 {
4222     static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
4223     char path[VMAXPATHLEN];
4224     int found = 0;
4225     struct DiskPartition *dp;
4226
4227     *ec = 0;
4228     name[0] = '/';
4229     (void)afs_snprintf(&name[1], (sizeof name) - 1, VFORMAT, volumeId);
4230     for (dp = DiskPartitionList; dp; dp = dp->next) {
4231         struct afs_stat status;
4232         strcpy(path, VPartitionPath(dp));
4233         strcat(path, name);
4234         if (afs_stat(path, &status) == 0) {
4235             strcpy(partition, dp->name);
4236             found = 1;
4237             break;
4238         }
4239     }
4240     if (!found) {
4241         *ec = VNOVOL;
4242         *partitionp = *namep = NULL;
4243     } else {
4244         *partitionp = partition;
4245         *namep = name;
4246     }
4247 }
4248
4249 int
4250 VolumeNumber(char *name)
4251 {
4252     if (*name == '/')
4253         name++;
4254     return atoi(name + 1);
4255 }
4256
4257 char *
4258 VolumeExternalName(VolumeId volumeId)
4259 {
4260     static char name[VMAXPATHLEN];
4261     (void)afs_snprintf(name, sizeof name, VFORMAT, volumeId);
4262     return name;
4263 }
4264
4265 static int
4266 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
4267 {
4268     return afs_snprintf(name, len, VFORMAT, volumeId);
4269 }
4270
4271
4272 /***************************************************/
4273 /* Volume Usage Statistics routines                */
4274 /***************************************************/
4275
4276 #if OPENAFS_VOL_STATS
4277 #define OneDay  (86400)         /* 24 hours' worth of seconds */
4278 #else
4279 #define OneDay  (24*60*60)      /* 24 hours */
4280 #endif /* OPENAFS_VOL_STATS */
4281
4282 #define Midnight(date) ((date-TimeZoneCorrection)/OneDay*OneDay+TimeZoneCorrection)
4283
4284 /*------------------------------------------------------------------------
4285  * [export] VAdjustVolumeStatistics
4286  *
4287  * Description:
4288  *      If we've passed midnight, we need to update all the day use
4289  *      statistics as well as zeroing the detailed volume statistics
4290  *      (if we are implementing them).
4291  *
4292  * Arguments:
4293  *      vp : Pointer to the volume structure describing the lucky
4294  *              volume being considered for update.
4295  *
4296  * Returns:
4297  *      0 (always!)
4298  *
4299  * Environment:
4300  *      Nothing interesting.
4301  *
4302  * Side Effects:
4303  *      As described.
4304  *------------------------------------------------------------------------*/
4305
4306 int
4307 VAdjustVolumeStatistics_r(register Volume * vp)
4308 {
4309     unsigned int now = FT_ApproxTime();
4310
4311     if (now - V_dayUseDate(vp) > OneDay) {
4312         register int ndays, i;
4313
4314         ndays = (now - V_dayUseDate(vp)) / OneDay;
4315         for (i = 6; i > ndays - 1; i--)
4316             V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
4317         for (i = 0; i < ndays - 1 && i < 7; i++)
4318             V_weekUse(vp)[i] = 0;
4319         if (ndays <= 7)
4320             V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
4321         V_dayUse(vp) = 0;
4322         V_dayUseDate(vp) = Midnight(now);
4323
4324 #if OPENAFS_VOL_STATS
4325         /*
4326          * All we need to do is bzero the entire VOL_STATS_BYTES of
4327          * the detailed volume statistics area.
4328          */
4329         memset((char *)(V_stat_area(vp)), 0, VOL_STATS_BYTES);
4330 #endif /* OPENAFS_VOL_STATS */
4331     }
4332
4333     /*It's been more than a day of collection */
4334     /*
4335      * Always return happily.
4336      */
4337     return (0);
4338 }                               /*VAdjustVolumeStatistics */
4339
4340 int
4341 VAdjustVolumeStatistics(register Volume * vp)
4342 {
4343     int retVal;
4344     VOL_LOCK;
4345     retVal = VAdjustVolumeStatistics_r(vp);
4346     VOL_UNLOCK;
4347     return retVal;
4348 }
4349
4350 void
4351 VBumpVolumeUsage_r(register Volume * vp)
4352 {
4353     unsigned int now = FT_ApproxTime();
4354     if (now - V_dayUseDate(vp) > OneDay)
4355         VAdjustVolumeStatistics_r(vp);
4356     /*
4357      * Save the volume header image to disk after every 128 bumps to dayUse.
4358      */
4359     if ((V_dayUse(vp)++ & 127) == 0) {
4360         Error error;
4361         VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
4362     }
4363 }
4364
4365 void
4366 VBumpVolumeUsage(register Volume * vp)
4367 {
4368     VOL_LOCK;
4369     VBumpVolumeUsage_r(vp);
4370     VOL_UNLOCK;
4371 }
4372
4373 void
4374 VSetDiskUsage_r(void)
4375 {
4376 #ifndef AFS_DEMAND_ATTACH_FS
4377     static int FifteenMinuteCounter = 0;
4378 #endif
4379
4380     while (VInit < 2) {
4381         /* NOTE: Don't attempt to access the partitions list until the
4382          * initialization level indicates that all volumes are attached,
4383          * which implies that all partitions are initialized. */
4384 #ifdef AFS_PTHREAD_ENV
4385         sleep(10);
4386 #else /* AFS_PTHREAD_ENV */
4387         IOMGR_Sleep(10);
4388 #endif /* AFS_PTHREAD_ENV */
4389     }
4390
4391     VResetDiskUsage_r();
4392
4393 #ifndef AFS_DEMAND_ATTACH_FS
4394     if (++FifteenMinuteCounter == 3) {
4395         FifteenMinuteCounter = 0;
4396         VScanUpdateList();
4397     }
4398 #endif /* !AFS_DEMAND_ATTACH_FS */
4399 }
4400
4401 void
4402 VSetDiskUsage(void)
4403 {
4404     VOL_LOCK;
4405     VSetDiskUsage_r();
4406     VOL_UNLOCK;
4407 }
4408
4409
4410 /***************************************************/
4411 /* Volume Update List routines                     */
4412 /***************************************************/
4413
4414 /* The number of minutes that a volume hasn't been updated before the
4415  * "Dont salvage" flag in the volume header will be turned on */
4416 #define SALVAGE_INTERVAL        (10*60)
4417
4418 /*
4419  * demand attach fs
4420  *
4421  * volume update list functionality has been moved into the VLRU
4422  * the DONT_SALVAGE flag is now set during VLRU demotion
4423  */
4424
4425 #ifndef AFS_DEMAND_ATTACH_FS
4426 static VolumeId *UpdateList = NULL;     /* Pointer to array of Volume ID's */
4427 static int nUpdatedVolumes = 0;         /* Updated with entry in UpdateList, salvage after crash flag on */
4428 static int updateSize = 0;              /* number of entries possible */
4429 #define UPDATE_LIST_SIZE 128            /* initial size increment (must be a power of 2!) */
4430 #endif /* !AFS_DEMAND_ATTACH_FS */
4431
4432 void
4433 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
4434 {
4435     *ec = 0;
4436     vp->updateTime = FT_ApproxTime();
4437     if (V_dontSalvage(vp) == 0)
4438         return;
4439     V_dontSalvage(vp) = 0;
4440     VSyncVolume_r(ec, vp, 0);
4441 #ifdef AFS_DEMAND_ATTACH_FS
4442     V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
4443 #else /* !AFS_DEMAND_ATTACH_FS */
4444     if (*ec)
4445         return;
4446     if (UpdateList == NULL) {
4447         updateSize = UPDATE_LIST_SIZE;
4448         UpdateList = (VolumeId *) malloc(sizeof(VolumeId) * updateSize);
4449     } else {
4450         if (nUpdatedVolumes == updateSize) {
4451             updateSize <<= 1;
4452             if (updateSize > 524288) {
4453                 Log("warning: there is likely a bug in the volume update scanner\n");
4454                 return;
4455             }
4456             UpdateList =
4457                 (VolumeId *) realloc(UpdateList,
4458                                      sizeof(VolumeId) * updateSize);
4459         }
4460     }
4461     assert(UpdateList != NULL);
4462     UpdateList[nUpdatedVolumes++] = V_id(vp);
4463 #endif /* !AFS_DEMAND_ATTACH_FS */
4464 }
4465
4466 #ifndef AFS_DEMAND_ATTACH_FS
4467 static void
4468 VScanUpdateList(void)
4469 {
4470     register int i, gap;
4471     register Volume *vp;
4472     Error error;
4473     afs_uint32 now = FT_ApproxTime();
4474     /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
4475     for (i = gap = 0; i < nUpdatedVolumes; i++) {
4476         if (gap)
4477             UpdateList[i - gap] = UpdateList[i];
4478
4479         /* XXX this routine needlessly messes up the Volume LRU by
4480          * breaking the LRU temporal-locality assumptions.....
4481          * we should use a special volume header allocator here */
4482         vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
4483         if (error) {
4484             gap++;
4485         } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
4486             V_dontSalvage(vp) = DONT_SALVAGE;
4487             VUpdateVolume_r(&error, vp, 0);     /* No need to fsync--not critical */
4488             gap++;
4489         }
4490
4491         if (vp) {
4492             VPutVolume_r(vp);
4493         }
4494
4495 #ifndef AFS_PTHREAD_ENV
4496         IOMGR_Poll();
4497 #endif /* !AFS_PTHREAD_ENV */
4498     }
4499     nUpdatedVolumes -= gap;
4500 }
4501 #endif /* !AFS_DEMAND_ATTACH_FS */
4502
4503
4504 /***************************************************/
4505 /* Volume LRU routines                             */
4506 /***************************************************/
4507
4508 /* demand attach fs
4509  * volume LRU
4510  *
4511  * with demand attach fs, we attempt to soft detach(1)
4512  * volumes which have not been accessed in a long time
4513  * in order to speed up fileserver shutdown
4514  *
4515  * (1) by soft detach we mean a process very similar
4516  *     to VOffline, except the final state of the 
4517  *     Volume will be VOL_STATE_PREATTACHED, instead
4518  *     of the usual VOL_STATE_UNATTACHED
4519  */
4520 #ifdef AFS_DEMAND_ATTACH_FS
4521
4522 /* implementation is reminiscent of a generational GC
4523  *
4524  * queue 0 is newly attached volumes. this queue is
4525  * sorted by attach timestamp
4526  *
4527  * queue 1 is volumes that have been around a bit
4528  * longer than queue 0. this queue is sorted by
4529  * attach timestamp
4530  *
4531  * queue 2 is volumes tha have been around the longest.
4532  * this queue is unsorted
4533  *
4534  * queue 3 is volumes that have been marked as
4535  * candidates for soft detachment. this queue is
4536  * unsorted
4537  */
4538 #define VLRU_GENERATIONS  3   /* number of generations in VLRU */
4539 #define VLRU_QUEUES       5   /* total number of VLRU queues */
4540 struct VLRU_q {
4541     volatile struct rx_queue q;
4542     volatile int len;
4543     volatile int busy;
4544     pthread_cond_t cv;
4545 };
4546 struct VLRU {
4547     struct VLRU_q q[VLRU_QUEUES];
4548
4549     /* VLRU config */
4550     afs_uint32 promotion_interval[VLRU_GENERATIONS-1];  /* interval between promotions */
4551     afs_uint32 scan_interval[VLRU_GENERATIONS+1];       /* interval between scans for candidates */
4552
4553     /* state */
4554     int next_idx;
4555     afs_uint32 last_promotion[VLRU_GENERATIONS-1];      /* timestamp of last promotion scan */
4556     afs_uint32 last_scan[VLRU_GENERATIONS+1];           /* timestamp of last detach scan */
4557
4558     int scanner_state;                                  /* state of scanner thread */
4559     pthread_cond_t cv;                                  /* state transition CV */
4560 };
4561
4562 static struct VLRU volume_LRU;
4563
4564 /* valid scanner states */
4565 #define VLRU_SCANNER_STATE_OFFLINE        0
4566 #define VLRU_SCANNER_STATE_ONLINE         1
4567 #define VLRU_SCANNER_STATE_SHUTTING_DOWN  2
4568 #define VLRU_SCANNER_STATE_PAUSING        3
4569 #define VLRU_SCANNER_STATE_PAUSED         4
4570
4571 /* vlru disk data header stuff */
4572 #define VLRU_DISK_MAGIC      0x7a8b9cad
4573 #define VLRU_DISK_VERSION    1
4574
4575 /* vlru default expiration time (for eventual fs state serialization of vlru data) */
4576 #define VLRU_DUMP_EXPIRATION_TIME   (60*60*24*7)  /* expire vlru data after 1 week */
4577
4578
4579 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
4580 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
4581 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
4582 static afs_uint32 VLRU_enabled = 1;
4583
4584 /* queue synchronization routines */
4585 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
4586 static void VLRU_EndExclusive_r(struct VLRU_q * q);
4587 static void VLRU_Wait_r(struct VLRU_q * q);
4588
4589 /* set the VLRU parameters 
4590  *
4591  * valid options are:
4592  *  VLRU_SET_THRESH -- set the period of inactivity after
4593  *    which volumes are eligible for being detached
4594  *  VLRU_SET_INTERVAL -- the time interval between calls
4595  *    to the volume LRU "garbage collector"
4596  *  VLRU_SET_MAX -- the max number of volumes to deallocate
4597  *    in one GC pass
4598  */
4599 void
4600 VLRU_SetOptions(int option, afs_uint32 val)
4601 {
4602     if (option == VLRU_SET_THRESH) {
4603         VLRU_offline_thresh = val;
4604     } else if (option == VLRU_SET_INTERVAL) {
4605         VLRU_offline_interval = val;
4606     } else if (option == VLRU_SET_MAX) {
4607         VLRU_offline_max = val;
4608     } else if (option == VLRU_SET_ENABLED) {
4609         VLRU_enabled = val;
4610     }
4611     VLRU_ComputeConstants();
4612 }
4613
4614 /* compute the VLRU internal timing parameters based upon the user's inputs */
4615 static void
4616 VLRU_ComputeConstants(void)
4617 {
4618     afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
4619
4620     /* compute the candidate scan interval */
4621     volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
4622
4623     /* compute the promotion intervals */
4624     volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
4625     volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
4626
4627     if (factor > 16) {
4628         /* compute the gen 0 scan interval */
4629         volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
4630     } else {
4631         /* compute the gen 0 scan interval */
4632         volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
4633     }
4634 }
4635
4636 /* initialize VLRU */
4637 static void
4638 VInitVLRU(void)
4639 {
4640     pthread_t tid;
4641     pthread_attr_t attrs;
4642     int i;
4643
4644     if (!VLRU_enabled) {
4645         Log("VLRU: disabled\n");
4646         return;
4647     }
4648
4649     /* initialize each of the VLRU queues */
4650     for (i = 0; i < VLRU_QUEUES; i++) {
4651         queue_Init(&volume_LRU.q[i]);
4652         volume_LRU.q[i].len = 0;
4653         volume_LRU.q[i].busy = 0;
4654         assert(pthread_cond_init(&volume_LRU.q[i].cv, NULL) == 0);
4655     }
4656
4657     /* setup the timing constants */
4658     VLRU_ComputeConstants();
4659
4660     /* XXX put inside LogLevel check? */
4661     Log("VLRU: starting scanner with the following configuration parameters:\n");
4662     Log("VLRU:  offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
4663     Log("VLRU:  running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
4664     Log("VLRU:  taking up to %d volumes offline per pass\n", VLRU_offline_max);
4665     Log("VLRU:  scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
4666     Log("VLRU:  scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
4667     Log("VLRU:  scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
4668
4669     /* start up the VLRU scanner */
4670     volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
4671     if (programType == fileServer) {
4672         assert(pthread_cond_init(&volume_LRU.cv, NULL) == 0);
4673         assert(pthread_attr_init(&attrs) == 0);
4674         assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
4675         assert(pthread_create(&tid, &attrs, &VLRU_ScannerThread, NULL) == 0);
4676     }
4677 }
4678
4679 /* initialize LRU support for a volume */
4680 static void
4681 VLRU_Init_Node_r(volatile Volume * vp)
4682 {
4683     if (!VLRU_enabled)
4684         return;
4685
4686     assert(queue_IsNotOnQueue(&vp->vlru));
4687     vp->vlru.idx = VLRU_QUEUE_INVALID;
4688 }
4689
4690 /* add volume to VLRU 
4691  * now supports adding to queues other
4692  * than new for vlru state restore
4693  * caller MUST hold a ref count on vp */
4694 static void
4695 VLRU_Add_r(volatile Volume * vp)
4696 {
4697     int idx;
4698
4699     if (!VLRU_enabled)
4700         return;
4701
4702     if (queue_IsOnQueue(&vp->vlru))
4703         return;
4704
4705     VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
4706
4707     /* repeat check since VLRU_Wait_r may have dropped
4708      * the glock */
4709     if (queue_IsNotOnQueue(&vp->vlru)) {
4710         idx = vp->vlru.idx;
4711         if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
4712             idx = vp->vlru.idx = VLRU_QUEUE_NEW;
4713         }
4714         queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
4715         volume_LRU.q[idx].len++;
4716         V_attachFlags(vp) |= VOL_ON_VLRU;
4717         vp->stats.last_promote = FT_ApproxTime();
4718     }
4719 }
4720
4721 /* delete volume from VLRU 
4722  * caller MUST hold a ref count on vp */
4723 static void
4724 VLRU_Delete_r(volatile Volume * vp)
4725 {
4726     int idx;
4727
4728     if (!VLRU_enabled)
4729         return;
4730
4731     if (queue_IsNotOnQueue(&vp->vlru))
4732         return;
4733
4734     /* handle races */
4735     do {
4736       idx = vp->vlru.idx;
4737       if (idx == VLRU_QUEUE_INVALID)
4738           return;
4739       VLRU_Wait_r(&volume_LRU.q[idx]);
4740     } while (idx != vp->vlru.idx);
4741
4742     /* now remove from the VLRU and update 
4743      * the appropriate counter */
4744     queue_Remove(&vp->vlru);
4745     volume_LRU.q[idx].len--;
4746     vp->vlru.idx = VLRU_QUEUE_INVALID;
4747     V_attachFlags(vp) &= ~(VOL_ON_VLRU);
4748 }
4749
4750 /* signal that volume was just accessed.
4751  * caller MUST hold a ref count on vp */
4752 static void
4753 VLRU_UpdateAccess_r(volatile Volume * vp)
4754 {
4755     afs_uint32 live_interval;
4756     Volume * rvp = NULL;
4757
4758     if (!VLRU_enabled)
4759         return;
4760
4761     if (queue_IsNotOnQueue(&vp->vlru))
4762         return;
4763
4764     assert(V_attachFlags(vp) & VOL_ON_VLRU);
4765
4766     /* update the access timestamp */
4767     vp->stats.last_get = FT_ApproxTime();
4768
4769     /*
4770      * if the volume is on the soft detach candidate
4771      * list, we need to safely move it back to a
4772      * regular generation.  this has to be done
4773      * carefully so we don't race against the scanner
4774      * thread.
4775      */
4776
4777     /* if this volume is on the soft detach candidate queue,
4778      * then grab exclusive access to the necessary queues */
4779     if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
4780         rvp = vp;
4781         VCreateReservation_r(rvp);
4782
4783         VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
4784         VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
4785         VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
4786         VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
4787     }
4788
4789     /* make sure multiple threads don't race to update */
4790     if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
4791         VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
4792     }
4793
4794     if (rvp) {
4795       VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
4796       VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
4797       VCancelReservation_r(rvp);
4798     }
4799 }
4800
4801 /* switch a volume between two VLRU queues */
4802 static void
4803 VLRU_SwitchQueues(volatile Volume * vp, int new_idx, int append)
4804 {
4805     if (queue_IsNotOnQueue(&vp->vlru))
4806         return;
4807
4808     queue_Remove(&vp->vlru);
4809     volume_LRU.q[vp->vlru.idx].len--;
4810     
4811     /* put the volume back on the correct generational queue */
4812     if (append) {
4813         queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
4814     } else {
4815         queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
4816     }
4817
4818     volume_LRU.q[new_idx].len++;
4819     vp->vlru.idx = new_idx;
4820 }
4821
4822 /* VLRU GC thread */
4823 static void *
4824 VLRU_ScannerThread(void * args)
4825 {
4826     afs_uint32 now, min_delay, delay;
4827     afs_uint32 next_scan[VLRU_GENERATIONS];
4828     afs_uint32 next_promotion[VLRU_GENERATIONS];
4829     int i, min_idx, min_op, overdue, state;
4830
4831     /* set t=0 for promotion cycle to be 
4832      * fileserver startup */
4833     now = FT_ApproxTime();
4834     for (i=0; i < VLRU_GENERATIONS-1; i++) {
4835         volume_LRU.last_promotion[i] = now;
4836     }
4837
4838     /* don't start the scanner until VLRU_offline_thresh
4839      * plus a small delay for VInitVolumePackage to finish
4840      * has gone by */
4841
4842     sleep(VLRU_offline_thresh + 60);
4843
4844     /* set t=0 for scan cycle to be now */
4845     now = FT_ApproxTime();
4846     for (i=0; i < VLRU_GENERATIONS+1; i++) {
4847         volume_LRU.last_scan[i] = now;
4848     }
4849
4850     VOL_LOCK;
4851     if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
4852         volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
4853     }
4854
4855     while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
4856         /* check to see if we've been asked to pause */
4857         if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
4858             volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
4859             assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
4860             do {
4861                 assert(pthread_cond_wait(&volume_LRU.cv, &vol_glock_mutex) == 0);
4862             } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
4863         }
4864
4865         /* scheduling can happen outside the glock */
4866         VOL_UNLOCK;
4867
4868         /* figure out what is next on the schedule */
4869
4870         /* figure out a potential schedule for the new generation first */
4871         overdue = 0;
4872         min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
4873         min_idx = 0;
4874         min_op = 0;
4875         if (min_delay > volume_LRU.scan_interval[0]) {
4876             /* unsigned overflow -- we're overdue to run this scan */
4877             min_delay = 0;
4878             overdue = 1;
4879         }
4880
4881         /* if we're not overdue for gen 0, figure out schedule for candidate gen */
4882         if (!overdue) {
4883             i = VLRU_QUEUE_CANDIDATE;
4884             delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
4885             if (delay < min_delay) {
4886                 min_delay = delay;
4887                 min_idx = i;
4888             }
4889             if (delay > volume_LRU.scan_interval[i]) {
4890                 /* unsigned overflow -- we're overdue to run this scan */
4891                 min_delay = 0;
4892                 min_idx = i;
4893                 overdue = 1;
4894                 break;
4895             }
4896         }
4897
4898         /* if we're still not overdue for something, figure out schedules for promotions */
4899         for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
4900             delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
4901             if (delay < min_delay) {
4902                 min_delay = delay;
4903                 min_idx = i;
4904                 min_op = 1;
4905             }
4906             if (delay > volume_LRU.promotion_interval[i]) {
4907                 /* unsigned overflow -- we're overdue to run this promotion */
4908                 min_delay = 0;
4909                 min_idx = i;
4910                 min_op = 1;
4911                 overdue = 1;
4912                 break;
4913             }
4914         }
4915
4916         /* sleep as needed */
4917         if (min_delay) {
4918             sleep(min_delay);
4919         }
4920
4921         /* do whatever is next */
4922         VOL_LOCK;
4923         if (min_op) {
4924             VLRU_Promote_r(min_idx);
4925             VLRU_Demote_r(min_idx+1);
4926         } else {
4927             VLRU_Scan_r(min_idx);
4928         }
4929         now = FT_ApproxTime();
4930     }
4931
4932     Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
4933
4934     /* signal that scanner is down */
4935     volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
4936     assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
4937     VOL_UNLOCK;
4938     return NULL;
4939 }
4940
4941 /* run the promotions */
4942 static void
4943 VLRU_Promote_r(int idx)
4944 {
4945     int len, chaining, promote;
4946     afs_uint32 now, thresh;
4947     struct rx_queue *qp, *nqp;
4948     Volume * vp, *start, *end;
4949
4950     /* get exclusive access to two chains, and drop the glock */
4951     VLRU_Wait_r(&volume_LRU.q[idx]);
4952     VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
4953     VLRU_Wait_r(&volume_LRU.q[idx+1]);
4954     VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
4955     VOL_UNLOCK;
4956
4957     thresh = volume_LRU.promotion_interval[idx];
4958     now = FT_ApproxTime();
4959
4960     len = chaining = 0;
4961     for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
4962         vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
4963         promote = (((vp->stats.last_promote + thresh) <= now) &&
4964                    (vp->stats.last_get >= vp->stats.last_promote));
4965
4966         if (chaining) {
4967             if (promote) {
4968                 vp->vlru.idx++;
4969                 len++;
4970                 start = vp;
4971             } else {
4972                 /* promote and prepend chain */
4973                 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
4974                 chaining = 0;
4975             }
4976         } else {
4977             if (promote) {
4978                 vp->vlru.idx++;
4979                 len++;
4980                 chaining = 1;
4981                 start = end = vp;
4982             }
4983         }
4984     }
4985
4986     if (chaining) {
4987         /* promote and prepend */
4988         queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
4989     }
4990
4991     if (len) {
4992         volume_LRU.q[idx].len -= len;
4993         volume_LRU.q[idx+1].len += len;
4994     }
4995
4996     /* release exclusive access to the two chains */
4997     VOL_LOCK;
4998     volume_LRU.last_promotion[idx] = now;
4999     VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
5000     VLRU_EndExclusive_r(&volume_LRU.q[idx]);
5001 }
5002
5003 /* run the demotions */
5004 static void
5005 VLRU_Demote_r(int idx)
5006 {
5007     Error ec;
5008     int len, chaining, demote;
5009     afs_uint32 now, thresh;
5010     struct rx_queue *qp, *nqp;
5011     Volume * vp, *start, *end;
5012     Volume ** salv_flag_vec = NULL;
5013     int salv_vec_offset = 0;
5014
5015     assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
5016
5017     /* get exclusive access to two chains, and drop the glock */
5018     VLRU_Wait_r(&volume_LRU.q[idx-1]);
5019     VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
5020     VLRU_Wait_r(&volume_LRU.q[idx]);
5021     VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
5022     VOL_UNLOCK;
5023
5024     /* no big deal if this allocation fails */
5025     if (volume_LRU.q[idx].len) {
5026         salv_flag_vec = (Volume **) malloc(volume_LRU.q[idx].len * sizeof(Volume *));
5027     }
5028
5029     now = FT_ApproxTime();
5030     thresh = volume_LRU.promotion_interval[idx-1];
5031
5032     len = chaining = 0;
5033     for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
5034         vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
5035         demote = (((vp->stats.last_promote + thresh) <= now) &&
5036                   (vp->stats.last_get < (now - thresh)));
5037
5038         /* we now do volume update list DONT_SALVAGE flag setting during
5039          * demotion passes */
5040         if (salv_flag_vec &&
5041             !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
5042             demote && 
5043             (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
5044             (V_attachState(vp) == VOL_STATE_ATTACHED)) {
5045             salv_flag_vec[salv_vec_offset++] = vp;
5046             VCreateReservation_r(vp);
5047         }
5048
5049         if (chaining) {
5050             if (demote) {
5051                 vp->vlru.idx--;
5052                 len++;
5053                 start = vp;
5054             } else {
5055                 /* demote and append chain */
5056                 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
5057                 chaining = 0;
5058             }
5059         } else {
5060             if (demote) {
5061                 vp->vlru.idx--;
5062                 len++;
5063                 chaining = 1;
5064                 start = end = vp;
5065             }
5066         }
5067     }
5068
5069     if (chaining) {
5070         queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
5071     }
5072
5073     if (len) {
5074         volume_LRU.q[idx].len -= len;
5075         volume_LRU.q[idx-1].len += len;
5076     }
5077
5078     /* release exclusive access to the two chains */
5079     VOL_LOCK;
5080     VLRU_EndExclusive_r(&volume_LRU.q[idx]);
5081     VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
5082
5083     /* now go back and set the DONT_SALVAGE flags as appropriate */
5084     if (salv_flag_vec) {
5085         int i;
5086         for (i = 0; i < salv_vec_offset; i++) {
5087             vp = salv_flag_vec[i];
5088             if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
5089                 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
5090                 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
5091                 ec = VHold_r(vp);
5092                 if (!ec) {
5093                     V_attachFlags(vp) |= VOL_HDR_DONTSALV;
5094                     V_dontSalvage(vp) = DONT_SALVAGE;
5095                     VUpdateVolume_r(&ec, vp, 0);
5096                     VPutVolume_r(vp);
5097                 }
5098             }
5099             VCancelReservation_r(vp);
5100         }
5101         free(salv_flag_vec);
5102     }
5103 }
5104
5105 /* run a pass of the VLRU GC scanner */
5106 static void
5107 VLRU_Scan_r(int idx)
5108 {
5109     afs_uint32 now, thresh;
5110     struct rx_queue *qp, *nqp;
5111     volatile Volume * vp;
5112     int i, locked = 1;
5113
5114     assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
5115
5116     /* gain exclusive access to the idx VLRU */
5117     VLRU_Wait_r(&volume_LRU.q[idx]);
5118     VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
5119
5120     if (idx != VLRU_QUEUE_CANDIDATE) {
5121         /* gain exclusive access to the candidate VLRU */
5122         VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5123         VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5124     }
5125
5126     now = FT_ApproxTime();
5127     thresh = now - VLRU_offline_thresh;
5128
5129     /* perform candidate selection and soft detaching */
5130     if (idx == VLRU_QUEUE_CANDIDATE) {
5131         /* soft detach some volumes from the candidate pool */
5132         VOL_UNLOCK;
5133         locked = 0;
5134
5135         for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
5136             vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
5137             if (i >= VLRU_offline_max) {
5138                 break;
5139             }
5140             /* check timestamp to see if it's a candidate for soft detaching */
5141             if (vp->stats.last_get <= thresh) {
5142                 VOL_LOCK;
5143                 if (VCheckSoftDetach(vp, thresh))
5144                     i++;
5145                 VOL_UNLOCK;
5146             }
5147         }
5148     } else {
5149         /* scan for volumes to become soft detach candidates */
5150         for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
5151             vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
5152
5153             /* check timestamp to see if it's a candidate for soft detaching */
5154             if (vp->stats.last_get <= thresh) {
5155                 VCheckSoftDetachCandidate(vp, thresh);
5156             }
5157
5158             if (!(i&0x7f)) {   /* lock coarsening optimization */
5159                 VOL_UNLOCK;
5160                 pthread_yield();
5161                 VOL_LOCK;
5162             }
5163         }
5164     }
5165
5166     /* relinquish exclusive access to the VLRU chains */
5167     if (!locked) {
5168         VOL_LOCK;
5169     }
5170     volume_LRU.last_scan[idx] = now;
5171     if (idx != VLRU_QUEUE_CANDIDATE) {
5172         VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5173     }
5174     VLRU_EndExclusive_r(&volume_LRU.q[idx]);
5175 }
5176
5177 /* check whether volume is safe to soft detach
5178  * caller MUST NOT hold a ref count on vp */
5179 static int
5180 VCheckSoftDetach(volatile Volume * vp, afs_uint32 thresh)
5181 {
5182     int ret=0;
5183
5184     if (vp->nUsers || vp->nWaiters)
5185         return 0;
5186
5187     if (vp->stats.last_get <= thresh) {
5188         ret = VSoftDetachVolume_r(vp, thresh);
5189     }
5190
5191     return ret;
5192 }
5193
5194 /* check whether volume should be made a 
5195  * soft detach candidate */
5196 static int
5197 VCheckSoftDetachCandidate(volatile Volume * vp, afs_uint32 thresh)
5198 {
5199     int idx, ret = 0;
5200     if (vp->nUsers || vp->nWaiters)
5201         return 0;
5202
5203     idx = vp->vlru.idx;
5204
5205     assert(idx == VLRU_QUEUE_NEW);
5206
5207     if (vp->stats.last_get <= thresh) {
5208         /* move to candidate pool */
5209         queue_Remove(&vp->vlru);
5210         volume_LRU.q[VLRU_QUEUE_NEW].len--;
5211         queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
5212         vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
5213         volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
5214         ret = 1;
5215     }
5216
5217     return ret;
5218 }
5219
5220
5221 /* begin exclusive access on VLRU */
5222 static void
5223 VLRU_BeginExclusive_r(struct VLRU_q * q)
5224 {
5225     assert(q->busy == 0);
5226     q->busy = 1;
5227 }
5228
5229 /* end exclusive access on VLRU */
5230 static void
5231 VLRU_EndExclusive_r(struct VLRU_q * q)
5232 {
5233     assert(q->busy);
5234     q->busy = 0;
5235     assert(pthread_cond_broadcast(&q->cv) == 0);
5236 }
5237
5238 /* wait for another thread to end exclusive access on VLRU */
5239 static void
5240 VLRU_Wait_r(struct VLRU_q * q)
5241 {
5242     while(q->busy) {
5243         assert(pthread_cond_wait(&q->cv, &vol_glock_mutex) == 0);
5244     }
5245 }
5246
5247 /* demand attach fs
5248  * volume soft detach
5249  *
5250  * caller MUST NOT hold a ref count on vp */
5251 static int
5252 VSoftDetachVolume_r(volatile Volume * vp, afs_uint32 thresh)
5253 {
5254     afs_uint32 ts_save;
5255     int ret = 0;
5256
5257     assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
5258
5259     ts_save = vp->stats.last_get;
5260     if (ts_save > thresh)
5261         return 0;
5262
5263     if (vp->nUsers || vp->nWaiters)
5264         return 0;
5265
5266     if (IsExclusiveState(V_attachState(vp))) {
5267         return 0;
5268     }
5269
5270     switch (V_attachState(vp)) {
5271     case VOL_STATE_UNATTACHED:
5272     case VOL_STATE_PREATTACHED:
5273     case VOL_STATE_ERROR:
5274     case VOL_STATE_GOING_OFFLINE:
5275     case VOL_STATE_SHUTTING_DOWN:
5276     case VOL_STATE_SALVAGING:
5277         volume_LRU.q[vp->vlru.idx].len--;
5278
5279         /* create and cancel a reservation to
5280          * give the volume an opportunity to
5281          * be deallocated */
5282         VCreateReservation_r(vp);
5283         queue_Remove(&vp->vlru);
5284         vp->vlru.idx = VLRU_QUEUE_INVALID;
5285         V_attachFlags(vp) &= ~(VOL_ON_VLRU);
5286         VCancelReservation_r(vp);
5287         return 0;
5288     }
5289
5290     /* hold the volume and take it offline.
5291      * no need for reservations, as VHold_r
5292      * takes care of that internally. */
5293     if (VHold_r(vp) == 0) {
5294         /* vhold drops the glock, so now we should
5295          * check to make sure we aren't racing against
5296          * other threads.  if we are racing, offlining vp
5297          * would be wasteful, and block the scanner for a while 
5298          */
5299         if (vp->nWaiters || 
5300             (vp->nUsers > 1) ||
5301             (vp->shuttingDown) ||
5302             (vp->goingOffline) ||
5303             (vp->stats.last_get != ts_save)) {
5304             /* looks like we're racing someone else. bail */
5305             VPutVolume_r(vp);
5306             vp = NULL;
5307         } else {
5308             /* pull it off the VLRU */
5309             assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
5310             volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
5311             queue_Remove(&vp->vlru);
5312             vp->vlru.idx = VLRU_QUEUE_INVALID;
5313             V_attachFlags(vp) &= ~(VOL_ON_VLRU);
5314
5315             /* take if offline */
5316             VOffline_r(vp, "volume has been soft detached");
5317
5318             /* invalidate the volume header cache */
5319             FreeVolumeHeader(vp);
5320
5321             /* update stats */
5322             IncUInt64(&VStats.soft_detaches);
5323             vp->stats.soft_detaches++;
5324
5325             /* put in pre-attached state so demand
5326              * attacher can work on it */
5327             VChangeState_r(vp, VOL_STATE_PREATTACHED);
5328             ret = 1;
5329         }
5330     }
5331     return ret;
5332 }
5333 #endif /* AFS_DEMAND_ATTACH_FS */
5334
5335
5336 /***************************************************/
5337 /* Volume Header Cache routines                    */
5338 /***************************************************/
5339
5340 struct volume_hdr_LRU_t volume_hdr_LRU;
5341
5342 /* Allocate a bunch of headers; string them together */
5343 static void
5344 VInitVolumeHeaderCache(afs_uint32 howMany)
5345 {
5346     register struct volHeader *hp;
5347     if (programType != fileServer)
5348         return;
5349     queue_Init(&volume_hdr_LRU);
5350 #ifdef AFS_DEMAND_ATTACH_FS
5351     volume_hdr_LRU.stats.free = 0;
5352     volume_hdr_LRU.stats.used = howMany;
5353     volume_hdr_LRU.stats.attached = 0;
5354 #endif
5355     hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
5356     while (howMany--)
5357         ReleaseVolumeHeader(hp++);
5358 }
5359
5360 #ifdef AFS_DEMAND_ATTACH_FS
5361 /* Get a volume header from the LRU list; update the old one if necessary */
5362 /* Returns 1 if there was already a header, which is removed from the LRU list */
5363 /* caller MUST has a ref count on vp */
5364 static int
5365 GetVolumeHeader(register Volume * vp)
5366 {
5367     Error error;
5368     register struct volHeader *hd;
5369     int old;
5370     static int everLogged = 0;
5371
5372     /* XXX debug 9/19/05 we've apparently got
5373      * a ref counting bug somewhere that's
5374      * breaking the nUsers == 0 => header on LRU
5375      * assumption */
5376     if (vp->header && queue_IsNotOnQueue(vp->header)) {
5377         Log("nUsers == 0, but header not on LRU\n");
5378         return 1;
5379     }
5380
5381     old = (vp->header != NULL); /* old == volume already has a header */
5382
5383     if (programType != fileServer) {
5384         /* for volume utilities, we allocate volHeaders as needed */
5385         if (!vp->header) {
5386             hd = (struct volHeader *)calloc(1, sizeof(*vp->header));
5387             assert(hd != NULL);
5388             vp->header = hd;
5389             hd->back = vp;
5390             V_attachFlags(vp) |= VOL_HDR_ATTACHED;
5391         }
5392     } else {
5393         if (old) {
5394             /* the header we previously dropped in the lru is
5395              * still available. pull it off the lru and return */
5396             hd = vp->header;
5397             queue_Remove(hd);
5398             assert(hd->back == vp);
5399         } else {
5400             /* we need to grab a new element off the LRU */
5401             if (queue_IsNotEmpty(&volume_hdr_LRU)) {
5402                 /* grab an element and pull off of LRU */
5403                 hd = queue_First(&volume_hdr_LRU, volHeader);
5404                 queue_Remove(hd);
5405             } else {
5406                 /* LRU is empty, so allocate a new volHeader 
5407                  * this is probably indicative of a leak, so let the user know */
5408                 hd = (struct volHeader *)calloc(1, sizeof(struct volHeader));
5409                 assert(hd != NULL);
5410                 if (!everLogged) {
5411                     Log("****Allocated more volume headers, probably leak****\n");
5412                     everLogged = 1;
5413                 }
5414                 volume_hdr_LRU.stats.free++;
5415             }
5416             if (hd->back) {
5417                 VolState vp_save, back_save;
5418                 /* this header used to belong to someone else. 
5419                  * we'll need to check if the header needs to
5420                  * be sync'd out to disk */
5421
5422                 /* if hd->back were in an exclusive state, then
5423                  * its volHeader would not be on the LRU... */
5424                 assert(!IsExclusiveState(V_attachState(hd->back)));
5425
5426                 if (hd->diskstuff.inUse) {
5427                     /* volume was in use, so we'll need to sync
5428                      * its header to disk */
5429                     back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
5430                     vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
5431                     VCreateReservation_r(hd->back);
5432                     VOL_UNLOCK;
5433
5434                     WriteVolumeHeader_r(&error, hd->back);
5435                     /* Ignore errors; catch them later */
5436
5437                     VOL_LOCK;
5438                 }
5439
5440                 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
5441                 hd->back->header = NULL;
5442
5443                 if (hd->diskstuff.inUse) {
5444                     VChangeState_r(hd->back, back_save);
5445                     VCancelReservation_r(hd->back);
5446                     VChangeState_r(vp, vp_save);
5447                 }
5448             } else {
5449                 volume_hdr_LRU.stats.attached++;
5450             }
5451             hd->back = vp;
5452             vp->header = hd;
5453             V_attachFlags(vp) |= VOL_HDR_ATTACHED;
5454         }
5455         volume_hdr_LRU.stats.free--;
5456         volume_hdr_LRU.stats.used++;
5457     }
5458     IncUInt64(&VStats.hdr_gets);
5459     IncUInt64(&vp->stats.hdr_gets);
5460     vp->stats.last_hdr_get = FT_ApproxTime();
5461     return old;
5462 }
5463 #else /* AFS_DEMAND_ATTACH_FS */
5464 /* Get a volume header from the LRU list; update the old one if necessary */
5465 /* Returns 1 if there was already a header, which is removed from the LRU list */
5466 static int
5467 GetVolumeHeader(register Volume * vp)
5468 {
5469     Error error;
5470     register struct volHeader *hd;
5471     int old;
5472     static int everLogged = 0;
5473
5474     old = (vp->header != NULL); /* old == volume already has a header */
5475
5476     if (programType != fileServer) {
5477         /* for volume utilities, we allocate volHeaders as needed */
5478         if (!vp->header) {
5479             hd = (struct volHeader *)calloc(1, sizeof(*vp->header));
5480             assert(hd != NULL);
5481             vp->header = hd;
5482             hd->back = vp;
5483         }
5484     } else {
5485         /* for the fileserver, we keep a volume header cache */
5486         if (old) {
5487             /* the header we previously dropped in the lru is
5488              * still available. pull it off the lru and return */
5489             hd = vp->header;
5490             queue_Remove(hd);
5491             assert(hd->back == vp);
5492         } else {
5493             /* we need to grab a new element off the LRU */
5494             if (queue_IsNotEmpty(&volume_hdr_LRU)) {
5495                 /* grab an element */
5496                 hd = queue_First(&volume_hdr_LRU, volHeader);
5497                 queue_Remove(hd);
5498             } else {
5499                 /* LRU is empty, so allocate a new volHeader 
5500                  * this is probably indicative of a leak, so let the user know */
5501                 hd = (struct volHeader *)calloc(1, sizeof(struct volHeader));
5502                 assert(hd != NULL);
5503                 if (!everLogged) {
5504                     Log("****Allocated more volume headers, probably leak****\n");
5505                     everLogged = 1;
5506                 }
5507             }
5508             if (hd->back) {
5509                 /* this header used to belong to someone else. 
5510                  * we'll need to check if the header needs to
5511                  * be sync'd out to disk */
5512
5513                 if (hd->diskstuff.inUse) {
5514                     WriteVolumeHeader_r(&error, hd->back);
5515                     /* Ignore errors; catch them later */
5516                 }
5517                 hd->back->header = NULL;
5518             }
5519             hd->back = vp;
5520             vp->header = hd;
5521         }
5522     }
5523     return old;
5524 }
5525 #endif /* AFS_DEMAND_ATTACH_FS */
5526
5527
5528 /* make sure a volume header is attached to
5529  * vp, and has the correct data loaded from
5530  * disk. */
5531 #ifdef AFS_DEMAND_ATTACH_FS
5532 /* caller MUST hold a ref count on vp */
5533 static void
5534 LoadVolumeHeader(Error * ec, Volume * vp)
5535 {
5536     VolState state_save;
5537     *ec = 0;
5538
5539     if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
5540         IncUInt64(&VStats.hdr_loads);
5541         state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
5542         VOL_UNLOCK;
5543
5544         ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
5545                    sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
5546                    VOLUMEINFOVERSION);
5547         IncUInt64(&vp->stats.hdr_loads);
5548
5549         VOL_LOCK;
5550         if (!*ec)
5551             V_attachFlags(vp) |= VOL_HDR_LOADED;
5552         VChangeState_r(vp, state_save);
5553     }
5554     if (*ec) {
5555         /* maintain (nUsers==0) => header in LRU invariant */
5556         ReleaseVolumeHeader(vp->header);
5557     }
5558 }
5559 #else /* AFS_DEMAND_ATTACH_FS */
5560 static void
5561 LoadVolumeHeader(Error * ec, Volume * vp)
5562 {
5563     *ec = 0;
5564     if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
5565         IncUInt64(&VStats.hdr_loads);
5566
5567         ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
5568                    sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
5569                    VOLUMEINFOVERSION);
5570     }
5571     if (*ec) {
5572         /* maintain (nUsers==0) => header in LRU invariant */
5573         ReleaseVolumeHeader(vp->header);
5574     }
5575 }
5576 #endif /* AFS_DEMAND_ATTACH_FS */
5577
5578 /* Put it at the top of the LRU chain */
5579 static void
5580 ReleaseVolumeHeader(register struct volHeader *hd)
5581 {
5582     if (programType != fileServer)
5583         return;
5584     if (!hd || queue_IsOnQueue(hd))     /* no header, or header already released */
5585         return;
5586     queue_Append(&volume_hdr_LRU, hd);
5587 #ifdef AFS_DEMAND_ATTACH_FS
5588     if (hd->back) {
5589         V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
5590     }
5591     volume_hdr_LRU.stats.free++;
5592     volume_hdr_LRU.stats.used--;
5593 #endif
5594 }
5595
5596 /* for fileserver, return header to LRU, and
5597  * invalidate it as a cache entry.
5598  *
5599  * for volume utilities, free the heap space */
5600 static void
5601 FreeVolumeHeader(register Volume * vp)
5602 {
5603     register struct volHeader *hd = vp->header;
5604     if (!hd)
5605         return;
5606     if (programType == fileServer) {
5607         ReleaseVolumeHeader(hd);
5608         hd->back = NULL;
5609     } else {
5610         free(hd);
5611     }
5612 #ifdef AFS_DEMAND_ATTACH_FS
5613     V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
5614     volume_hdr_LRU.stats.attached--;
5615 #endif
5616     vp->header = NULL;
5617 }
5618
5619
5620 /***************************************************/
5621 /* Volume Hash Table routines                      */
5622 /***************************************************/
5623
5624 int 
5625 VSetVolHashSize(int logsize)
5626 {
5627     /* 64 to 16384 hash buckets seems like a reasonable range */
5628     if ((logsize < 6 ) || (logsize > 14)) {
5629         return -1;
5630     }
5631     
5632     if (!VInit) {
5633         VolumeHashTable.Size = 1 << logsize;
5634         VolumeHashTable.Mask = VolumeHashTable.Size - 1;
5635     } else {
5636         /* we can't yet support runtime modification of this
5637          * parameter. we'll need a configuration rwlock to
5638          * make runtime modification feasible.... */
5639         return -1;
5640     }
5641     return 0;
5642 }
5643
5644 static void
5645 VInitVolumeHash(void)
5646 {
5647     register int i;
5648
5649     VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size, 
5650                                                            sizeof(VolumeHashChainHead));
5651     assert(VolumeHashTable.Table != NULL);
5652     
5653     for (i=0; i < VolumeHashTable.Size; i++) {
5654         queue_Init(&VolumeHashTable.Table[i]);
5655 #ifdef AFS_DEMAND_ATTACH_FS
5656         assert(pthread_cond_init(&VolumeHashTable.Table[i].chain_busy_cv, NULL) == 0);
5657 #endif /* AFS_DEMAND_ATTACH_FS */
5658     }
5659 }
5660
5661 /* for demand-attach, caller MUST hold a ref count on vp */
5662 static void
5663 AddVolumeToHashTable(register Volume * vp, int hashid)
5664 {
5665     VolumeHashChainHead * head;
5666
5667     if (queue_IsOnQueue(vp))
5668         return;
5669
5670     head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
5671
5672 #ifdef AFS_DEMAND_ATTACH_FS
5673     /* wait for the hash chain to become available */
5674     VHashWait_r(head);
5675
5676     V_attachFlags(vp) |= VOL_IN_HASH;
5677     vp->chainCacheCheck = ++head->cacheCheck;
5678 #endif /* AFS_DEMAND_ATTACH_FS */
5679
5680     head->len++;
5681     vp->hashid = hashid;
5682     queue_Append(head, vp);
5683     vp->vnodeHashOffset = VolumeHashOffset_r();
5684 }
5685
5686 /* for demand-attach, caller MUST hold a ref count on vp */
5687 static void
5688 DeleteVolumeFromHashTable(register Volume * vp)
5689 {
5690     VolumeHashChainHead * head;
5691
5692     if (!queue_IsOnQueue(vp))
5693         return;
5694
5695     head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
5696
5697 #ifdef AFS_DEMAND_ATTACH_FS
5698     /* wait for the hash chain to become available */
5699     VHashWait_r(head);
5700
5701     V_attachFlags(vp) &= ~(VOL_IN_HASH);
5702     head->cacheCheck++;
5703 #endif /* AFS_DEMAND_ATTACH_FS */
5704
5705     head->len--;
5706     queue_Remove(vp);
5707     /* do NOT reset hashid to zero, as the online
5708      * salvager package may need to know the volume id
5709      * after the volume is removed from the hash */
5710 }
5711
5712 /* - look up a volume id in the hash table
5713  * - occasionally rebalance hash chains
5714  * - update lookup statistics accordingly
5715  */
5716 /* the hint parameter allows us to short-circuit on
5717  * DEMAND_ATTACH_FS if the cacheChecks match between
5718  * the hash chain head and hint
5719  * caller MUST hold a refcount on hint */
5720 Volume *
5721 VLookupVolume_r(Error * ec, VolId volumeId, Volume * hint)
5722 {
5723     register int looks = 0;
5724     Volume * vp, *np, *pp;
5725     VolumeHashChainHead * head;
5726     *ec = 0;
5727
5728     head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
5729
5730 #ifdef AFS_DEMAND_ATTACH_FS
5731     /* wait for the hash chain to become available */
5732     VHashWait_r(head);
5733
5734     /* check to see if we can short circuit without walking the hash chain */
5735     if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
5736         IncUInt64(&hint->stats.hash_short_circuits);
5737         return hint;
5738     }
5739 #endif /* AFS_DEMAND_ATTACH_FS */
5740
5741     /* someday we need to either do per-chain locks, RWlocks,
5742      * or both for volhash access. 
5743      * (and move to a data structure with better cache locality) */
5744
5745     /* search the chain for this volume id */
5746     for(queue_Scan(head, vp, np, Volume)) {
5747         looks++;
5748         if ((vp->hashid == volumeId)) {
5749             break;
5750         }
5751     }
5752
5753     if (queue_IsEnd(head, vp)) {
5754         vp = NULL;
5755     }
5756
5757 #ifdef AFS_DEMAND_ATTACH_FS
5758     /* update hash chain statistics */
5759     {
5760         afs_uint64 lks;
5761         FillInt64(lks, 0, looks);
5762         AddUInt64(head->looks, lks, &head->looks);
5763         AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
5764         IncUInt64(&head->gets);
5765     }
5766
5767     if (vp) {
5768         afs_uint64 thresh;
5769         IncUInt64(&vp->stats.hash_lookups);
5770
5771         /* for demand attach fileserver, we permit occasional hash chain reordering
5772          * so that frequently looked up volumes move towards the head of the chain */
5773         pp = queue_Prev(vp, Volume);
5774         if (!queue_IsEnd(head, pp)) {
5775             FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
5776             AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
5777             if (GEInt64(vp->stats.hash_lookups, thresh)) {
5778                 VReorderHash_r(head, pp, vp);
5779             }
5780         }
5781
5782         /* update the short-circuit cache check */
5783         vp->chainCacheCheck = head->cacheCheck;
5784     }
5785 #endif /* AFS_DEMAND_ATTACH_FS */    
5786
5787     return vp;
5788 }
5789
5790 #ifdef AFS_DEMAND_ATTACH_FS
5791 /* perform volume hash chain reordering.
5792  *
5793  * advance a subchain beginning at vp ahead of
5794  * the adjacent subchain ending at pp */
5795 static void
5796 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
5797 {
5798     Volume *tp, *np, *lp;
5799     afs_uint64 move_thresh;
5800
5801     /* this should never be called if the chain is already busy, so
5802      * no need to wait for other exclusive chain ops to finish */
5803
5804     /* this is a rather heavy set of operations,
5805      * so let's set the chain busy flag and drop
5806      * the vol_glock */
5807     VHashBeginExclusive_r(head);
5808     VOL_UNLOCK;
5809
5810     /* scan forward in the chain from vp looking for the last element
5811      * in the chain we want to advance */
5812     FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
5813     AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
5814     for(queue_ScanFrom(head, vp, tp, np, Volume)) {
5815         if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
5816             break;
5817         }
5818     }
5819     lp = queue_Prev(tp, Volume);
5820
5821     /* scan backwards from pp to determine where to splice and
5822      * insert the subchain we're advancing */
5823     for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
5824         if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
5825             break;
5826         }
5827     }
5828     tp = queue_Next(tp, Volume);
5829
5830     /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
5831     queue_MoveChainBefore(tp,vp,lp);
5832
5833     VOL_LOCK;
5834     IncUInt64(&VStats.hash_reorders);
5835     head->cacheCheck++;
5836     IncUInt64(&head->reorders);
5837
5838     /* wake up any threads waiting for the hash chain */
5839     VHashEndExclusive_r(head);
5840 }
5841
5842
5843 /* demand-attach fs volume hash
5844  * asynchronous exclusive operations */
5845
5846 /* take exclusive control over the hash chain */
5847 static void
5848 VHashBeginExclusive_r(VolumeHashChainHead * head)
5849 {
5850     assert(head->busy == 0);
5851     head->busy = 1;
5852 }
5853
5854 /* relinquish exclusive control over the hash chain */
5855 static void
5856 VHashEndExclusive_r(VolumeHashChainHead * head)
5857 {
5858     assert(head->busy);
5859     head->busy = 0;
5860     assert(pthread_cond_broadcast(&head->chain_busy_cv) == 0);
5861 }
5862
5863 /* wait for another thread to finish its exclusive ops */
5864 static void
5865 VHashWait_r(VolumeHashChainHead * head)
5866 {
5867     while (head->busy) {
5868         assert(pthread_cond_wait(&head->chain_busy_cv, &vol_glock_mutex) == 0);
5869     }
5870 }
5871 #endif /* AFS_DEMAND_ATTACH_FS */
5872
5873
5874 /***************************************************/
5875 /* Volume by Partition List routines               */
5876 /***************************************************/
5877
5878 /*
5879  * demand attach fileserver adds a
5880  * linked list of volumes to each
5881  * partition object, thus allowing
5882  * for quick enumeration of all
5883  * volumes on a partition
5884  */
5885
5886 #ifdef AFS_DEMAND_ATTACH_FS
5887 static void
5888 AddVolumeToVByPList_r(Volume * vp)
5889 {
5890     if (queue_IsNotOnQueue(&vp->vol_list)) {
5891         queue_Append(&vp->partition->vol_list, &vp->vol_list);
5892         V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
5893         vp->partition->vol_list.len++;
5894     }
5895 }
5896
5897 static void
5898 DeleteVolumeFromVByPList_r(Volume * vp)
5899 {
5900     if (queue_IsOnQueue(&vp->vol_list)) {
5901         queue_Remove(&vp->vol_list);
5902         V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
5903         vp->partition->vol_list.len--;
5904     }
5905 }
5906
5907 /* take exclusive control over the list */
5908 static void
5909 VVByPListBeginExclusive_r(struct DiskPartition * dp)
5910 {
5911     assert(dp->vol_list.busy == 0);
5912     dp->vol_list.busy = 1;
5913 }
5914
5915 /* relinquish exclusive control over the list */
5916 static void
5917 VVByPListEndExclusive_r(struct DiskPartition * dp)
5918 {
5919     assert(dp->vol_list.busy);
5920     dp->vol_list.busy = 0;
5921     assert(pthread_cond_broadcast(&dp->vol_list.cv) == 0);
5922 }
5923
5924 /* wait for another thread to finish its exclusive ops */
5925 static void
5926 VVByPListWait_r(struct DiskPartition * dp)
5927 {
5928     while (dp->vol_list.busy) {
5929         assert(pthread_cond_wait(&dp->vol_list.cv, &vol_glock_mutex) == 0);
5930     }
5931 }
5932 #endif /* AFS_DEMAND_ATTACH_FS */
5933
5934 /***************************************************/
5935 /* Volume Cache Statistics routines                */
5936 /***************************************************/
5937
5938 void
5939 VPrintCacheStats_r(void)
5940 {
5941     afs_uint32 get_hi, get_lo, load_hi, load_lo;
5942     register struct VnodeClassInfo *vcp;
5943     vcp = &VnodeClassInfo[vLarge];
5944     Log("Large vnode cache, %d entries, %d allocs, %d gets (%d reads), %d writes\n", vcp->cacheSize, vcp->allocs, vcp->gets, vcp->reads, vcp->writes);
5945     vcp = &VnodeClassInfo[vSmall];
5946     Log("Small vnode cache,%d entries, %d allocs, %d gets (%d reads), %d writes\n", vcp->cacheSize, vcp->allocs, vcp->gets, vcp->reads, vcp->writes);
5947     SplitInt64(VStats.hdr_gets, get_hi, get_lo);
5948     SplitInt64(VStats.hdr_loads, load_hi, load_lo);
5949     Log("Volume header cache, %d entries, %d gets, %d replacements\n",
5950         VStats.hdr_cache_size, get_lo, load_lo);
5951 }
5952
5953 void
5954 VPrintCacheStats(void)
5955 {
5956     VOL_LOCK;
5957     VPrintCacheStats_r();
5958     VOL_UNLOCK;
5959 }
5960
5961 #ifdef AFS_DEMAND_ATTACH_FS
5962 static double
5963 UInt64ToDouble(afs_uint64 * x)
5964 {
5965     static double c32 = 4.0 * 1.073741824 * 1000000000.0;
5966     afs_uint32 h, l;
5967     SplitInt64(*x, h, l);
5968     return (((double)h) * c32) + ((double) l);
5969 }
5970
5971 static char *
5972 DoubleToPrintable(double x, char * buf, int len)
5973 {
5974     static double billion = 1000000000.0;
5975     afs_uint32 y[3];
5976
5977     y[0] = (afs_uint32) (x / (billion * billion));
5978     y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
5979     y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
5980
5981     if (y[0]) {
5982         snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
5983     } else if (y[1]) {
5984         snprintf(buf, len, "%d%09d", y[1], y[2]);
5985     } else {
5986         snprintf(buf, len, "%d", y[2]);
5987     }
5988     buf[len-1] = '\0';
5989     return buf;
5990 }
5991
5992 void
5993 VPrintExtendedCacheStats_r(int flags)
5994 {
5995     int i, j;
5996     struct stats {
5997         double min;
5998         double max;
5999         double sum;
6000         double avg;
6001     };
6002     struct stats looks, gets, reorders, len;
6003     struct stats ch_looks, ch_gets, ch_reorders;
6004     char pr_buf[4][32];
6005     VolumeHashChainHead *head;
6006     Volume *vp, *np;
6007
6008     /* zero out stats */
6009     memset(&looks, 0, sizeof(struct stats));
6010     memset(&gets, 0, sizeof(struct stats));
6011     memset(&reorders, 0, sizeof(struct stats));
6012     memset(&len, 0, sizeof(struct stats));
6013     memset(&ch_looks, 0, sizeof(struct stats));
6014     memset(&ch_gets, 0, sizeof(struct stats));
6015     memset(&ch_reorders, 0, sizeof(struct stats));
6016
6017     for (i = 0; i < VolumeHashTable.Size; i++) {
6018         head = &VolumeHashTable.Table[i];
6019
6020         VHashWait_r(head);
6021         VHashBeginExclusive_r(head);
6022         VOL_UNLOCK;
6023
6024         ch_looks.sum    = UInt64ToDouble(&head->looks);
6025         ch_gets.sum     = UInt64ToDouble(&head->gets);
6026         ch_reorders.sum = UInt64ToDouble(&head->reorders);
6027
6028         /* update global statistics */
6029         {
6030             looks.sum    += ch_looks.sum;
6031             gets.sum     += ch_gets.sum;
6032             reorders.sum += ch_reorders.sum;
6033             len.sum      += (double)head->len;
6034             
6035             if (i == 0) {
6036                 len.min      = (double) head->len;
6037                 len.max      = (double) head->len;
6038                 looks.min    = ch_looks.sum;
6039                 looks.max    = ch_looks.sum;
6040                 gets.min     = ch_gets.sum;
6041                 gets.max     = ch_gets.sum;
6042                 reorders.min = ch_reorders.sum;
6043                 reorders.max = ch_reorders.sum;
6044             } else {
6045                 if (((double)head->len) < len.min)
6046                     len.min = (double) head->len;
6047                 if (((double)head->len) > len.max)
6048                     len.max = (double) head->len;
6049                 if (ch_looks.sum < looks.min)
6050                     looks.min = ch_looks.sum;
6051                 else if (ch_looks.sum > looks.max)
6052                     looks.max = ch_looks.sum;
6053                 if (ch_gets.sum < gets.min)
6054                     gets.min = ch_gets.sum;
6055                 else if (ch_gets.sum > gets.max)
6056                     gets.max = ch_gets.sum;
6057                 if (ch_reorders.sum < reorders.min)
6058                     reorders.min = ch_reorders.sum;
6059                 else if (ch_reorders.sum > reorders.max)
6060                     reorders.max = ch_reorders.sum;
6061             }
6062         }
6063
6064         if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
6065             /* compute detailed per-chain stats */
6066             struct stats hdr_loads, hdr_gets;
6067             double v_looks, v_loads, v_gets;
6068
6069             /* initialize stats with data from first element in chain */
6070             vp = queue_First(head, Volume);
6071             v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
6072             v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
6073             v_gets  = UInt64ToDouble(&vp->stats.hdr_gets);
6074             ch_gets.min = ch_gets.max = v_looks;
6075             hdr_loads.min = hdr_loads.max = v_loads;
6076             hdr_gets.min = hdr_gets.max = v_gets;
6077             hdr_loads.sum = hdr_gets.sum = 0;
6078
6079             vp = queue_Next(vp, Volume);
6080
6081             /* pull in stats from remaining elements in chain */
6082             for (queue_ScanFrom(head, vp, vp, np, Volume)) {
6083                 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
6084                 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
6085                 v_gets  = UInt64ToDouble(&vp->stats.hdr_gets);
6086
6087                 hdr_loads.sum += v_loads;
6088                 hdr_gets.sum += v_gets;
6089
6090                 if (v_looks < ch_gets.min)
6091                     ch_gets.min = v_looks;
6092                 else if (v_looks > ch_gets.max)
6093                     ch_gets.max = v_looks;
6094
6095                 if (v_loads < hdr_loads.min)
6096                     hdr_loads.min = v_loads;
6097                 else if (v_loads > hdr_loads.max)
6098                     hdr_loads.max = v_loads;
6099
6100                 if (v_gets < hdr_gets.min)
6101                     hdr_gets.min = v_gets;
6102                 else if (v_gets > hdr_gets.max)
6103                     hdr_gets.max = v_gets;
6104             }
6105
6106             /* compute per-chain averages */
6107             ch_gets.avg = ch_gets.sum / ((double)head->len);
6108             hdr_loads.avg = hdr_loads.sum / ((double)head->len);
6109             hdr_gets.avg = hdr_gets.sum / ((double)head->len);
6110
6111             /* dump per-chain stats */
6112             Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
6113                 i, head->len, 
6114                 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
6115                 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
6116             Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
6117                 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
6118                 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
6119                 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
6120                 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
6121             Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
6122                 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
6123                 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
6124                 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
6125                 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
6126             Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
6127                 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
6128                 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
6129                 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
6130                 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
6131         } else if (flags & VOL_STATS_PER_CHAIN) {
6132             /* dump simple per-chain stats */
6133             Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
6134                 i, head->len, 
6135                 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
6136                 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
6137                 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
6138         }
6139
6140         VOL_LOCK;
6141         VHashEndExclusive_r(head);
6142     }
6143
6144     VOL_UNLOCK;
6145
6146     /* compute global averages */
6147     len.avg      = len.sum      / ((double)VolumeHashTable.Size);
6148     looks.avg    = looks.sum    / ((double)VolumeHashTable.Size);
6149     gets.avg     = gets.sum     / ((double)VolumeHashTable.Size);
6150     reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
6151
6152     /* dump global stats */
6153     Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
6154     Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
6155         DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
6156         DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
6157         DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
6158         DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
6159     Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
6160         DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
6161         DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
6162         DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
6163         DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
6164     Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
6165         DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
6166         DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
6167         DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
6168         DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
6169     Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
6170         DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
6171         DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
6172         DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
6173         DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
6174
6175     /* print extended disk related statistics */
6176     {
6177         struct DiskPartition * diskP;
6178         afs_uint32 vol_count[VOLMAXPARTS+1];
6179         byte part_exists[VOLMAXPARTS+1];
6180         Device id;
6181         int i;
6182
6183         memset(vol_count, 0, sizeof(vol_count));
6184         memset(part_exists, 0, sizeof(part_exists));
6185
6186         VOL_LOCK;
6187
6188         for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
6189             id = diskP->index;
6190             vol_count[id] = diskP->vol_list.len;
6191             part_exists[id] = 1;
6192         }
6193
6194         VOL_UNLOCK;
6195         for (i = 0; i <= VOLMAXPARTS; i++) {
6196             if (part_exists[i]) {
6197                 diskP = VGetPartitionById_r(i, 0);
6198                 if (diskP) {
6199                     Log("Partition %s has %d online volumes\n", 
6200                         VPartitionPath(diskP), diskP->vol_list.len);
6201                 }
6202             }
6203         }
6204         VOL_LOCK;
6205     }
6206
6207 }
6208
6209 void
6210 VPrintExtendedCacheStats(int flags)
6211 {
6212     VOL_LOCK;
6213     VPrintExtendedCacheStats_r(flags);
6214     VOL_UNLOCK;
6215 }
6216 #endif /* AFS_DEMAND_ATTACH_FS */