parallel-attaching-20061021
[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
2721         if (vp->pending_vol_op && !VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
2722             if (client_ec) {
2723                 /* see CheckVnode() in afsfileprocs.c for an explanation
2724                  * of this error code logic */
2725                 afs_uint32 now = FT_ApproxTime();
2726                 if ((vp->stats.last_vol_op + (10 * 60)) >= now) {
2727                     *client_ec = VBUSY;
2728                 } else {
2729                     *client_ec = VRESTARTING;
2730                 }
2731             }
2732             *ec = VOFFLINE;
2733             vp = NULL;
2734             break;
2735         }
2736
2737         if (V_attachState(vp) == VOL_STATE_UNATTACHED) {
2738             *ec = VOFFLINE;
2739             vp = NULL;
2740             break;
2741         }
2742 #endif /* AFS_DEMAND_ATTACH_FS */
2743         
2744         LoadVolumeHeader(ec, vp);
2745         if (*ec) {
2746             VGET_CTR_INC(V6);
2747             /* Only log the error if it was a totally unexpected error.  Simply
2748              * a missing inode is likely to be caused by the volume being deleted */
2749             if (errno != ENXIO || LogLevel)
2750                 Log("Volume %u: couldn't reread volume header\n",
2751                     vp->hashid);
2752 #ifdef AFS_DEMAND_ATTACH_FS
2753             if (programType == fileServer) {
2754                 VRequestSalvage_r(vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2755                 *ec = VSALVAGING;
2756             } else {
2757                 FreeVolume(vp);
2758                 vp = NULL;
2759             }
2760 #else /* AFS_DEMAND_ATTACH_FS */
2761             FreeVolume(vp);
2762             vp = NULL;
2763 #endif /* AFS_DEMAND_ATTACH_FS */
2764             break;
2765         }
2766
2767         VGET_CTR_INC(V7);
2768         if (vp->shuttingDown) {
2769             VGET_CTR_INC(V8);
2770             *ec = VNOVOL;
2771             vp = NULL;
2772             break;
2773         }
2774
2775         if (programType == fileServer) {
2776             VGET_CTR_INC(V9);
2777             if (vp->goingOffline) {
2778                 VGET_CTR_INC(V10);
2779 #ifdef AFS_DEMAND_ATTACH_FS
2780                 /* wait for the volume to go offline */
2781                 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
2782                     VWaitStateChange_r(vp);
2783                 }
2784 #elif defined(AFS_PTHREAD_ENV)
2785                 assert(pthread_cond_wait(&vol_put_volume_cond, &vol_glock_mutex) == 0);
2786 #else /* AFS_PTHREAD_ENV */
2787                 LWP_WaitProcess(VPutVolume);
2788 #endif /* AFS_PTHREAD_ENV */
2789                 continue;
2790             }
2791             if (vp->specialStatus) {
2792                 VGET_CTR_INC(V11);
2793                 *ec = vp->specialStatus;
2794             } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
2795                 VGET_CTR_INC(V12);
2796                 *ec = VNOVOL;
2797             } else if (V_inUse(vp) == 0) {
2798                 VGET_CTR_INC(V13);
2799                 *ec = VOFFLINE;
2800             } else {
2801                 VGET_CTR_INC(V14);
2802             }
2803         }
2804         break;
2805     }
2806     VGET_CTR_INC(V15);
2807
2808 #ifdef AFS_DEMAND_ATTACH_FS
2809     /* if no error, bump nUsers */
2810     if (vp) {
2811         vp->nUsers++;
2812         VLRU_UpdateAccess_r(vp);
2813     }
2814     if (rvp) {
2815         VCancelReservation_r(rvp);
2816         rvp = NULL;
2817     }
2818     if (client_ec && !*client_ec) {
2819         *client_ec = *ec;
2820     }
2821 #else /* AFS_DEMAND_ATTACH_FS */
2822     /* if no error, bump nUsers */
2823     if (vp) {
2824         vp->nUsers++;
2825     }
2826     if (client_ec) {
2827         *client_ec = *ec;
2828     }
2829 #endif /* AFS_DEMAND_ATTACH_FS */
2830
2831     assert(vp || *ec);
2832     return vp;
2833 }
2834
2835
2836 /***************************************************/
2837 /* Volume offline/detach routines                  */
2838 /***************************************************/
2839
2840 /* caller MUST hold a heavyweight ref on vp */
2841 #ifdef AFS_DEMAND_ATTACH_FS
2842 void
2843 VTakeOffline_r(register Volume * vp)
2844 {
2845     assert(vp->nUsers > 0);
2846     assert(programType == fileServer);
2847
2848     VCreateReservation_r(vp);
2849     VWaitExclusiveState_r(vp);
2850
2851     vp->goingOffline = 1;
2852     V_needsSalvaged(vp) = 1;
2853
2854     VRequestSalvage_r(vp, SALVSYNC_ERROR, 0);
2855     VCancelReservation_r(vp);
2856 }
2857 #else /* AFS_DEMAND_ATTACH_FS */
2858 void
2859 VTakeOffline_r(register Volume * vp)
2860 {
2861     assert(vp->nUsers > 0);
2862     assert(programType == fileServer);
2863
2864     vp->goingOffline = 1;
2865     V_needsSalvaged(vp) = 1;
2866 }
2867 #endif /* AFS_DEMAND_ATTACH_FS */
2868
2869 void
2870 VTakeOffline(register Volume * vp)
2871 {
2872     VOL_LOCK;
2873     VTakeOffline_r(vp);
2874     VOL_UNLOCK;
2875 }
2876
2877 /* Force the volume offline, set the salvage flag.  No further references to
2878  * the volume through the volume package will be honored. */
2879 /* for demand attach, caller MUST hold ref count on vp */
2880 void
2881 VForceOffline_r(Volume * vp, int flags)
2882 {
2883     Error error;
2884     if (!V_inUse(vp))
2885         return;
2886     strcpy(V_offlineMessage(vp),
2887            "Forced offline due to internal error: volume needs to be salvaged");
2888     Log("Volume %u forced offline:  it needs salvaging!\n", V_id(vp));
2889     V_inUse(vp) = 0;
2890     vp->goingOffline = 0;
2891     V_needsSalvaged(vp) = 1;
2892     if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
2893         VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT | VOL_UPDATE_NOFORCEOFF);
2894     }
2895 #ifdef AFS_DEMAND_ATTACH_FS
2896 #ifdef SALVSYNC_BUILD_CLIENT
2897     if (programType == fileServer) {
2898         VRequestSalvage_r(vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2899     }
2900 #endif
2901     VChangeState_r(vp, VOL_STATE_ERROR);
2902 #endif /* AFS_DEMAND_ATTACH_FS */
2903 #ifdef AFS_PTHREAD_ENV
2904     assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
2905 #else /* AFS_PTHREAD_ENV */
2906     LWP_NoYieldSignal(VPutVolume);
2907 #endif /* AFS_PTHREAD_ENV */
2908
2909     VReleaseVolumeHandles_r(vp);
2910 }
2911
2912 void
2913 VForceOffline(Volume * vp)
2914 {
2915     VOL_LOCK;
2916     VForceOffline_r(vp, 0);
2917     VOL_UNLOCK;
2918 }
2919
2920 /* The opposite of VAttachVolume.  The volume header is written to disk, with
2921    the inUse bit turned off.  A copy of the header is maintained in memory,
2922    however (which is why this is VOffline, not VDetach).
2923  */
2924 void
2925 VOffline_r(Volume * vp, char *message)
2926 {
2927     Error error;
2928     VolumeId vid = V_id(vp);
2929
2930     assert(programType != volumeUtility);
2931     if (!V_inUse(vp)) {
2932         VPutVolume_r(vp);
2933         return;
2934     }
2935     if (V_offlineMessage(vp)[0] == '\0')
2936         strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
2937     V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
2938
2939     vp->goingOffline = 1;
2940 #ifdef AFS_DEMAND_ATTACH_FS
2941     VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
2942     VCreateReservation_r(vp);
2943     VPutVolume_r(vp);
2944
2945     /* wait for the volume to go offline */
2946     if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
2947         VWaitStateChange_r(vp);
2948     }
2949     VCancelReservation_r(vp);
2950 #else /* AFS_DEMAND_ATTACH_FS */
2951     VPutVolume_r(vp);
2952     vp = VGetVolume_r(&error, vid);     /* Wait for it to go offline */
2953     if (vp)                     /* In case it was reattached... */
2954         VPutVolume_r(vp);
2955 #endif /* AFS_DEMAND_ATTACH_FS */
2956 }
2957
2958 void
2959 VOffline(Volume * vp, char *message)
2960 {
2961     VOL_LOCK;
2962     VOffline_r(vp, message);
2963     VOL_UNLOCK;
2964 }
2965
2966 /* This gets used for the most part by utility routines that don't want
2967  * to keep all the volume headers around.  Generally, the file server won't
2968  * call this routine, because then the offline message in the volume header
2969  * (or other information) won't be available to clients. For NAMEI, also
2970  * close the file handles.  However, the fileserver does call this during
2971  * an attach following a volume operation.
2972  */
2973 void
2974 VDetachVolume_r(Error * ec, Volume * vp)
2975 {
2976     VolumeId volume;
2977     struct DiskPartition *tpartp;
2978     int notifyServer, useDone;
2979
2980     *ec = 0;                    /* always "succeeds" */
2981     if (programType == volumeUtility) {
2982         notifyServer = vp->needsPutBack;
2983         useDone = (V_destroyMe(vp) == DESTROY_ME);
2984     }
2985     tpartp = vp->partition;
2986     volume = V_id(vp);
2987     DeleteVolumeFromHashTable(vp);
2988     vp->shuttingDown = 1;
2989 #ifdef AFS_DEMAND_ATTACH_FS
2990     DeleteVolumeFromVByPList_r(vp);
2991     VLRU_Delete_r(vp);
2992     VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
2993 #endif /* AFS_DEMAND_ATTACH_FS */
2994     VPutVolume_r(vp);
2995     /* Will be detached sometime in the future--this is OK since volume is offline */
2996
2997     /* XXX the following code should really be moved to VCheckDetach() since the volume
2998      * is not technically detached until the refcounts reach zero
2999      */
3000 #ifdef FSSYNC_BUILD_CLIENT
3001     if (programType == volumeUtility && notifyServer) {
3002         /* 
3003          * Note:  The server is not notified in the case of a bogus volume 
3004          * explicitly to make it possible to create a volume, do a partial 
3005          * restore, then abort the operation without ever putting the volume 
3006          * online.  This is essential in the case of a volume move operation 
3007          * between two partitions on the same server.  In that case, there 
3008          * would be two instances of the same volume, one of them bogus, 
3009          * which the file server would attempt to put on line 
3010          */
3011         if (useDone) {
3012             /* don't put online */
3013             FSYNC_VolOp(volume, tpartp->name, FSYNC_VOL_DONE, 0, NULL);
3014         } else {
3015             /* fs can use it again */
3016             FSYNC_VolOp(volume, tpartp->name, FSYNC_VOL_ON, 0, NULL);
3017
3018             /* XXX this code path is only hit by volume utilities, thus
3019              * V_BreakVolumeCallbacks will always be NULL.  if we really
3020              * want to break callbacks in this path we need to use FSYNC_VolOp() */
3021 #ifdef notdef
3022             /* Dettaching it so break all callbacks on it */
3023             if (V_BreakVolumeCallbacks) {
3024                 Log("volume %u detached; breaking all call backs\n", volume);
3025                 (*V_BreakVolumeCallbacks) (volume);
3026             }
3027 #endif
3028         }
3029     }
3030 #endif /* FSSYNC_BUILD_CLIENT */
3031 }
3032
3033 void
3034 VDetachVolume(Error * ec, Volume * vp)
3035 {
3036     VOL_LOCK;
3037     VDetachVolume_r(ec, vp);
3038     VOL_UNLOCK;
3039 }
3040
3041
3042 /***************************************************/
3043 /* Volume fd/inode handle closing routines         */
3044 /***************************************************/
3045
3046 /* For VDetachVolume, we close all cached file descriptors, but keep
3047  * the Inode handles in case we need to read from a busy volume.
3048  */
3049 /* for demand attach, caller MUST hold ref count on vp */
3050 static void
3051 VCloseVolumeHandles_r(Volume * vp)
3052 {
3053 #ifdef AFS_DEMAND_ATTACH_FS
3054     VolState state_save;
3055
3056     state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
3057 #endif
3058
3059     /* demand attach fs
3060      *
3061      * XXX need to investigate whether we can perform
3062      * DFlushVolume outside of vol_glock_mutex... 
3063      *
3064      * VCloseVnodeFiles_r drops the glock internally */
3065     DFlushVolume(V_id(vp));
3066     VCloseVnodeFiles_r(vp);
3067
3068 #ifdef AFS_DEMAND_ATTACH_FS
3069     VOL_UNLOCK;
3070 #endif
3071
3072     /* Too time consuming and unnecessary for the volserver */
3073     if (programType != volumeUtility) {
3074         IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
3075         IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
3076         IH_CONDSYNC(vp->diskDataHandle);
3077 #ifdef AFS_NT40_ENV
3078         IH_CONDSYNC(vp->linkHandle);
3079 #endif /* AFS_NT40_ENV */
3080     }
3081
3082     IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
3083     IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
3084     IH_REALLYCLOSE(vp->diskDataHandle);
3085     IH_REALLYCLOSE(vp->linkHandle);
3086
3087 #ifdef AFS_DEMAND_ATTACH_FS
3088     VOL_LOCK;
3089     VChangeState_r(vp, state_save);
3090 #endif
3091 }
3092
3093 /* For both VForceOffline and VOffline, we close all relevant handles.
3094  * For VOffline, if we re-attach the volume, the files may possible be
3095  * different than before. 
3096  */
3097 /* for demand attach, caller MUST hold a ref count on vp */
3098 static void
3099 VReleaseVolumeHandles_r(Volume * vp)
3100 {
3101 #ifdef AFS_DEMAND_ATTACH_FS
3102     VolState state_save;
3103
3104     state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
3105 #endif
3106
3107     /* XXX need to investigate whether we can perform
3108      * DFlushVolume outside of vol_glock_mutex... */
3109     DFlushVolume(V_id(vp));
3110
3111     VReleaseVnodeFiles_r(vp); /* releases the glock internally */
3112
3113 #ifdef AFS_DEMAND_ATTACH_FS
3114     VOL_UNLOCK;
3115 #endif
3116
3117     /* Too time consuming and unnecessary for the volserver */
3118     if (programType != volumeUtility) {
3119         IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
3120         IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
3121         IH_CONDSYNC(vp->diskDataHandle);
3122 #ifdef AFS_NT40_ENV
3123         IH_CONDSYNC(vp->linkHandle);
3124 #endif /* AFS_NT40_ENV */
3125     }
3126
3127     IH_RELEASE(vp->vnodeIndex[vLarge].handle);
3128     IH_RELEASE(vp->vnodeIndex[vSmall].handle);
3129     IH_RELEASE(vp->diskDataHandle);
3130     IH_RELEASE(vp->linkHandle);
3131
3132 #ifdef AFS_DEMAND_ATTACH_FS
3133     VOL_LOCK;
3134     VChangeState_r(vp, state_save);
3135 #endif
3136 }
3137
3138
3139 /***************************************************/
3140 /* Volume write and fsync routines                 */
3141 /***************************************************/
3142
3143 void
3144 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
3145 {
3146 #ifdef AFS_DEMAND_ATTACH_FS
3147     VolState state_save;
3148
3149     if (flags & VOL_UPDATE_WAIT) {
3150         VCreateReservation_r(vp);
3151         VWaitExclusiveState_r(vp);
3152     }
3153 #endif
3154
3155     *ec = 0;
3156     if (programType == fileServer)
3157         V_uniquifier(vp) =
3158             (V_inUse(vp) ? V_nextVnodeUnique(vp) +
3159              200 : V_nextVnodeUnique(vp));
3160
3161 #ifdef AFS_DEMAND_ATTACH_FS
3162     state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
3163     VOL_UNLOCK;
3164 #endif
3165
3166     WriteVolumeHeader_r(ec, vp);
3167
3168 #ifdef AFS_DEMAND_ATTACH_FS
3169     VOL_LOCK;
3170     VChangeState_r(vp, state_save);
3171     if (flags & VOL_UPDATE_WAIT) {
3172         VCancelReservation_r(vp);
3173     }
3174 #endif
3175
3176     if (*ec) {
3177         Log("VUpdateVolume: error updating volume header, volume %u (%s)\n",
3178             V_id(vp), V_name(vp));
3179         /* try to update on-disk header, 
3180          * while preventing infinite recursion */
3181         if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
3182             VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
3183         }
3184     }
3185 }
3186
3187 void
3188 VUpdateVolume(Error * ec, Volume * vp)
3189 {
3190     VOL_LOCK;
3191     VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
3192     VOL_UNLOCK;
3193 }
3194
3195 void
3196 VSyncVolume_r(Error * ec, Volume * vp, int flags)
3197 {
3198     FdHandle_t *fdP;
3199     int code;
3200 #ifdef AFS_DEMAND_ATTACH_FS
3201     VolState state_save;
3202 #endif
3203
3204     if (flags & VOL_SYNC_WAIT) {
3205         VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
3206     } else {
3207         VUpdateVolume_r(ec, vp, 0);
3208     }
3209     if (!*ec) {
3210 #ifdef AFS_DEMAND_ATTACH_FS
3211         state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
3212         VOL_UNLOCK;
3213 #endif
3214         fdP = IH_OPEN(V_diskDataHandle(vp));
3215         assert(fdP != NULL);
3216         code = FDH_SYNC(fdP);
3217         assert(code == 0);
3218         FDH_CLOSE(fdP);
3219 #ifdef AFS_DEMAND_ATTACH_FS
3220         VOL_LOCK;
3221         VChangeState_r(vp, state_save);
3222 #endif
3223     }
3224 }
3225
3226 void
3227 VSyncVolume(Error * ec, Volume * vp)
3228 {
3229     VOL_LOCK;
3230     VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
3231     VOL_UNLOCK;
3232 }
3233
3234
3235 /***************************************************/
3236 /* Volume dealloaction routines                    */
3237 /***************************************************/
3238
3239 #ifdef AFS_DEMAND_ATTACH_FS
3240 static void
3241 FreeVolume(Volume * vp)
3242 {
3243     /* free the heap space, iff it's safe.
3244      * otherwise, pull it out of the hash table, so it
3245      * will get deallocated when all refs to it go away */
3246     if (!VCheckFree(vp)) {
3247         DeleteVolumeFromHashTable(vp);
3248         DeleteVolumeFromVByPList_r(vp);
3249
3250         /* make sure we invalidate the header cache entry */
3251         FreeVolumeHeader(vp);
3252     }
3253 }
3254 #endif /* AFS_DEMAND_ATTACH_FS */
3255
3256 static void
3257 ReallyFreeVolume(Volume * vp)
3258 {
3259     int i;
3260     if (!vp)
3261         return;
3262 #ifdef AFS_DEMAND_ATTACH_FS
3263     /* debug */
3264     VChangeState_r(vp, VOL_STATE_FREED);
3265     if (vp->pending_vol_op)
3266         free(vp->pending_vol_op);
3267 #endif /* AFS_DEMAND_ATTACH_FS */
3268     for (i = 0; i < nVNODECLASSES; i++)
3269         if (vp->vnodeIndex[i].bitmap)
3270             free(vp->vnodeIndex[i].bitmap);
3271     FreeVolumeHeader(vp);
3272 #ifndef AFS_DEMAND_ATTACH_FS
3273     DeleteVolumeFromHashTable(vp);
3274 #endif /* AFS_DEMAND_ATTACH_FS */
3275     free(vp);
3276 }
3277
3278 /* check to see if we should shutdown this volume
3279  * returns 1 if volume was freed, 0 otherwise */
3280 #ifdef AFS_DEMAND_ATTACH_FS
3281 static int
3282 VCheckDetach(register Volume * vp)
3283 {
3284     int ret = 0;
3285
3286     if (vp->nUsers || vp->nWaiters)
3287         return ret;
3288
3289     if (vp->shuttingDown) {
3290         ret = 1;
3291         VReleaseVolumeHandles_r(vp);
3292         VCheckSalvage(vp);
3293         ReallyFreeVolume(vp);
3294         if (programType == fileServer) {
3295             assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3296         }
3297     }
3298     return ret;
3299 }
3300 #else /* AFS_DEMAND_ATTACH_FS */
3301 static int
3302 VCheckDetach(register Volume * vp)
3303 {
3304     int ret = 0;
3305
3306     if (vp->nUsers)
3307         return ret;
3308
3309     if (vp->shuttingDown) {
3310         ret = 1;
3311         VReleaseVolumeHandles_r(vp);
3312         ReallyFreeVolume(vp);
3313         if (programType == fileServer) {
3314 #if defined(AFS_PTHREAD_ENV)
3315             assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3316 #else /* AFS_PTHREAD_ENV */
3317             LWP_NoYieldSignal(VPutVolume);
3318 #endif /* AFS_PTHREAD_ENV */
3319         }
3320     }
3321     return ret;
3322 }
3323 #endif /* AFS_DEMAND_ATTACH_FS */
3324
3325 /* check to see if we should offline this volume
3326  * return 1 if volume went offline, 0 otherwise */
3327 #ifdef AFS_DEMAND_ATTACH_FS
3328 static int
3329 VCheckOffline(register Volume * vp)
3330 {
3331     Volume * rvp = NULL;
3332     int ret = 0;
3333
3334     if (vp->goingOffline && !vp->nUsers) {
3335         Error error;
3336         assert(programType == fileServer);
3337         assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
3338                (V_attachState(vp) != VOL_STATE_FREED) &&
3339                (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
3340                (V_attachState(vp) != VOL_STATE_UNATTACHED));
3341
3342         /* valid states:
3343          *
3344          * VOL_STATE_GOING_OFFLINE
3345          * VOL_STATE_SHUTTING_DOWN
3346          * IsErrorState(V_attachState(vp))
3347          * IsExclusiveState(V_attachState(vp))
3348          */
3349
3350         VCreateReservation_r(vp);
3351         VChangeState_r(vp, VOL_STATE_OFFLINING);
3352
3353         ret = 1;
3354         /* must clear the goingOffline flag before we drop the glock */
3355         vp->goingOffline = 0;
3356         V_inUse(vp) = 0;
3357
3358         VLRU_Delete_r(vp);
3359
3360         /* perform async operations */
3361         VUpdateVolume_r(&error, vp, 0);
3362         VCloseVolumeHandles_r(vp);
3363
3364         if (LogLevel) {
3365             Log("VOffline: Volume %u (%s) is now offline", V_id(vp),
3366                 V_name(vp));
3367             if (V_offlineMessage(vp)[0])
3368                 Log(" (%s)", V_offlineMessage(vp));
3369             Log("\n");
3370         }
3371
3372         /* invalidate the volume header cache entry */
3373         FreeVolumeHeader(vp);
3374
3375         /* if nothing changed state to error or salvaging,
3376          * drop state to unattached */
3377         if (!IsErrorState(V_attachState(vp))) {
3378             VChangeState_r(vp, VOL_STATE_UNATTACHED);
3379         }
3380         VCancelReservation_r(vp);
3381         /* no usage of vp is safe beyond this point */
3382     }
3383     return ret;
3384 }
3385 #else /* AFS_DEMAND_ATTACH_FS */
3386 static int
3387 VCheckOffline(register Volume * vp)
3388 {
3389     Volume * rvp = NULL;
3390     int ret = 0;
3391
3392     if (vp->goingOffline && !vp->nUsers) {
3393         Error error;
3394         assert(programType == fileServer);
3395
3396         ret = 1;
3397         vp->goingOffline = 0;
3398         V_inUse(vp) = 0;
3399         VUpdateVolume_r(&error, vp, 0);
3400         VCloseVolumeHandles_r(vp);
3401         if (LogLevel) {
3402             Log("VOffline: Volume %u (%s) is now offline", V_id(vp),
3403                 V_name(vp));
3404             if (V_offlineMessage(vp)[0])
3405                 Log(" (%s)", V_offlineMessage(vp));
3406             Log("\n");
3407         }
3408         FreeVolumeHeader(vp);
3409 #ifdef AFS_PTHREAD_ENV
3410         assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3411 #else /* AFS_PTHREAD_ENV */
3412         LWP_NoYieldSignal(VPutVolume);
3413 #endif /* AFS_PTHREAD_ENV */
3414     }
3415     return ret;
3416 }
3417 #endif /* AFS_DEMAND_ATTACH_FS */
3418
3419 /***************************************************/
3420 /* demand attach fs ref counting routines          */
3421 /***************************************************/
3422
3423 #ifdef AFS_DEMAND_ATTACH_FS
3424 /* the following two functions handle reference counting for
3425  * asynchronous operations on volume structs.
3426  *
3427  * their purpose is to prevent a VDetachVolume or VShutdown
3428  * from free()ing the Volume struct during an async i/o op */
3429
3430 /* register with the async volume op ref counter */
3431 static void
3432 VCreateReservation_r(Volume * vp)
3433 {
3434     vp->nWaiters++;
3435 }
3436
3437 /* unregister with the async volume op ref counter */
3438 static void
3439 VCancelReservation_r(Volume * vp)
3440 {
3441     assert(--vp->nWaiters >= 0);
3442     if (vp->nWaiters == 0) {
3443         VCheckOffline(vp);
3444         if (!VCheckDetach(vp)) {
3445             VCheckSalvage(vp);
3446             VCheckFree(vp);
3447         }
3448     }
3449 }
3450
3451 /* check to see if we should free this volume now
3452  * return 1 if volume was freed, 0 otherwise */
3453 static int
3454 VCheckFree(Volume * vp)
3455 {
3456     int ret = 0;
3457     if ((vp->nUsers == 0) &&
3458         (vp->nWaiters == 0) &&
3459         !(V_attachFlags(vp) & (VOL_IN_HASH | 
3460                                VOL_ON_VBYP_LIST | 
3461                                VOL_IS_BUSY |
3462                                VOL_ON_VLRU))) {
3463         ReallyFreeVolume(vp);
3464         ret = 1;
3465     }
3466     return ret;
3467 }
3468 #endif /* AFS_DEMAND_ATTACH_FS */
3469
3470
3471 /***************************************************/
3472 /* online volume operations routines               */
3473 /***************************************************/
3474
3475 #ifdef AFS_DEMAND_ATTACH_FS
3476 int
3477 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3478 {
3479     FSSYNC_VolOp_info * info;
3480
3481     /* attach a vol op info node to the volume struct */
3482     info = (FSSYNC_VolOp_info *) malloc(sizeof(FSSYNC_VolOp_info));
3483     assert(info != NULL);
3484     memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
3485     vp->pending_vol_op = info;
3486
3487     /* update stats */
3488     vp->stats.last_vol_op = FT_ApproxTime();
3489     vp->stats.vol_ops++;
3490     IncUInt64(&VStats.vol_ops);
3491
3492     return 0;
3493 }
3494
3495 int
3496 VDeregisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3497 {
3498     if (vp->pending_vol_op) {
3499         free(vp->pending_vol_op);
3500         vp->pending_vol_op = NULL;
3501     }
3502     return 0;
3503 }
3504 #endif /* AFS_DEMAND_ATTACH_FS */
3505
3506 int
3507 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3508 {
3509     return (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
3510             (vopinfo->com.reason == V_READONLY ||
3511              (!VolumeWriteable(vp) &&
3512               (vopinfo->com.reason == V_CLONE ||
3513                vopinfo->com.reason == V_DUMP))));
3514 }
3515
3516 int
3517 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3518 {
3519     return (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
3520             (vopinfo->com.reason == V_CLONE ||
3521              vopinfo->com.reason == V_DUMP));
3522 }
3523
3524
3525 /***************************************************/
3526 /* online salvager routines                        */
3527 /***************************************************/
3528 #if defined(AFS_DEMAND_ATTACH_FS)
3529 #define SALVAGE_PRIO_UPDATE_INTERVAL 3      /* number of seconds between prio updates */
3530 #define SALVAGE_COUNT_MAX 16                /* number of online salvages we
3531                                              * allow before moving the volume
3532                                              * into a permanent error state
3533                                              *
3534                                              * once this threshold is reached,
3535                                              * the operator will have to manually
3536                                              * issue a 'bos salvage' to bring
3537                                              * the volume back online
3538                                              */
3539
3540 /* check to see if we should salvage this volume
3541  * returns 1 if salvage scheduled, 0 otherwise */
3542 static int
3543 VCheckSalvage(register Volume * vp)
3544 {
3545     int ret = 0;
3546 #ifdef SALVSYNC_BUILD_CLIENT
3547     if (vp->nUsers || vp->nWaiters)
3548         return ret;
3549     if (vp->salvage.requested) {
3550         VScheduleSalvage_r(vp);
3551         ret = 1;
3552     }
3553 #endif /* SALVSYNC_BUILD_CLIENT */
3554     return ret;
3555 }
3556
3557 /*
3558  * request that a salvage be performed once
3559  * ref counts reach zero
3560  */
3561 int
3562 VRequestSalvage_r(Volume * vp, int reason, int flags)
3563 {
3564 #ifdef SALVSYNC_BUILD_CLIENT
3565     if (programType != fileServer)
3566         return 1;
3567
3568     if (!vp->salvage.requested) {
3569         vp->salvage.requested = 1;
3570         vp->salvage.reason = reason;
3571         vp->stats.last_salvage = FT_ApproxTime();
3572         if (flags & VOL_SALVAGE_INVALIDATE_HEADER) {
3573             ReleaseVolumeHeader(vp->header);
3574         }
3575         if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
3576             VChangeState_r(vp, VOL_STATE_SALVAGING);
3577         } else {
3578             Log("VRequestSalvage: volume %u online salvaged too many times; forced offline.\n", vp->hashid);
3579             VChangeState_r(vp, VOL_STATE_ERROR);
3580         }
3581     }
3582 #endif /* SALVSYNC_BUILD_CLIENT */
3583     return 0;
3584 }
3585
3586 /*
3587  * update salvage priority
3588  */
3589 static int
3590 VUpdateSalvagePriority_r(Volume * vp)
3591 {
3592     int code, ret=0;
3593     afs_uint32 now;
3594
3595 #ifdef SALVSYNC_BUILD_CLIENT
3596     vp->salvage.prio++;
3597     now = FT_ApproxTime();
3598
3599     /* update the salvageserver priority queue occasionally so that
3600      * frequently requested volumes get moved to the head of the queue 
3601      */
3602     if ((vp->salvage.scheduled) &&
3603         (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
3604         code = SALVSYNC_SalvageVolume(vp->hashid,
3605                                       VPartitionPath(vp->partition),
3606                                       SALVSYNC_RAISEPRIO,
3607                                       vp->salvage.reason,
3608                                       vp->salvage.prio,
3609                                       NULL);
3610         vp->stats.last_salvage_req = now;
3611         if (code != SYNC_OK) {
3612             ret = 1;
3613         }
3614     }
3615 #endif /* SALVSYNC_BUILD_CLIENT */
3616     return ret;
3617 }
3618
3619
3620 /*
3621  * schedule a salvage with the salvage server
3622  */
3623 static int
3624 VScheduleSalvage_r(Volume * vp)
3625 {
3626     int code, ret=0;
3627 #ifdef SALVSYNC_BUILD_CLIENT
3628     VolState state_save;
3629     char partName[16];
3630
3631     if (vp->nWaiters || vp->nUsers) {
3632         return 1;
3633     }
3634
3635     /* prevent endless salvage,attach,salvage,attach,... loops */
3636     if (vp->stats.salvages >= SALVAGE_COUNT_MAX)
3637         return 1;
3638
3639     if (!vp->salvage.scheduled) {
3640         /* if we haven't previously scheduled a salvage, do so now 
3641          *
3642          * set the volume to an exclusive state and drop the lock
3643          * around the SALVSYNC call
3644          */
3645         strlcpy(partName, VPartitionPath(vp->partition), sizeof(partName));
3646         state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
3647         V_attachFlags(vp) |= VOL_IS_BUSY;
3648         VOL_UNLOCK;
3649
3650         /* can't use V_id() since there's no guarantee
3651          * we have the disk data header at this point */
3652         code = SALVSYNC_SalvageVolume(vp->hashid,
3653                                       partName,
3654                                       SALVSYNC_SALVAGE,
3655                                       vp->salvage.reason,
3656                                       vp->salvage.prio,
3657                                       NULL);
3658         VOL_LOCK;
3659         VChangeState_r(vp, state_save);
3660         V_attachFlags(vp) &= ~(VOL_IS_BUSY);
3661
3662         if (code == SYNC_OK) {
3663             vp->salvage.scheduled = 1;
3664             vp->stats.salvages++;
3665             vp->stats.last_salvage_req = FT_ApproxTime();
3666             IncUInt64(&VStats.salvages);
3667         } else {
3668             ret = 1;
3669             switch(code) {
3670             case SYNC_BAD_COMMAND:
3671             case SYNC_COM_ERROR:
3672                 break;
3673             case SYNC_DENIED:
3674                 Log("VScheduleSalvage_r:  SALVSYNC request denied\n");
3675                 break;
3676             default:
3677                 Log("VScheduleSalvage_r:  SALVSYNC unknown protocol error\n");
3678                 break;
3679             }
3680         }
3681     }
3682 #endif /* SALVSYNC_BUILD_CLIENT */
3683     return ret;
3684 }
3685
3686 /*
3687  * cancel a scheduled salvage operation
3688  */
3689 static int
3690 VCancelSalvage_r(Volume * vp, int reason)
3691 {
3692     int code, ret = 0;
3693
3694 #ifdef SALVSYNC_BUILD_CLIENT
3695     if (vp->salvage.scheduled) {
3696         code = SALVSYNC_SalvageVolume(vp->hashid,
3697                                       VPartitionPath(vp->partition),
3698                                       SALVSYNC_CANCEL,
3699                                       reason,
3700                                       0,
3701                                       NULL);
3702         if (code == SYNC_OK) {
3703             vp->salvage.scheduled = 0;
3704         } else {
3705             ret = 1;
3706         }
3707     }
3708 #endif /* SALVSYNC_BUILD_CLIENT */
3709     return ret;
3710 }
3711
3712 /* This must be called by any volume utility which needs to run while the
3713    file server is also running.  This is separated from VInitVolumePackage so
3714    that a utility can fork--and each of the children can independently
3715    initialize communication with the file server */
3716 #ifdef SALVSYNC_BUILD_CLIENT
3717 int
3718 VConnectSALV(void)
3719 {
3720     int retVal;
3721     VOL_LOCK;
3722     retVal = VConnectSALV_r();
3723     VOL_UNLOCK;
3724     return retVal;
3725 }
3726
3727 int
3728 VConnectSALV_r(void)
3729 {
3730     assert((programType != salvageServer) &&
3731            (programType != volumeUtility));
3732     return SALVSYNC_clientInit();
3733 }
3734
3735 int
3736 VDisconnectSALV(void)
3737 {
3738     int retVal;
3739     VOL_LOCK;
3740     VDisconnectSALV_r();
3741     VOL_UNLOCK;
3742     return retVal;
3743 }
3744
3745 int
3746 VDisconnectSALV_r(void)
3747
3748     assert((programType != salvageServer) &&
3749            (programType != volumeUtility));
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     assert((programType != salvageServer) &&
3767            (programType != volumeUtility));
3768     return SALVSYNC_clientReconnect();
3769 }
3770 #endif /* SALVSYNC_BUILD_CLIENT */
3771 #endif /* AFS_DEMAND_ATTACH_FS */
3772
3773
3774 /***************************************************/
3775 /* FSSYNC routines                                 */
3776 /***************************************************/
3777
3778 /* This must be called by any volume utility which needs to run while the
3779    file server is also running.  This is separated from VInitVolumePackage so
3780    that a utility can fork--and each of the children can independently
3781    initialize communication with the file server */
3782 #ifdef FSSYNC_BUILD_CLIENT
3783 int
3784 VConnectFS(void)
3785 {
3786     int retVal;
3787     VOL_LOCK;
3788     retVal = VConnectFS_r();
3789     VOL_UNLOCK;
3790     return retVal;
3791 }
3792
3793 int
3794 VConnectFS_r(void)
3795 {
3796     int rc;
3797     assert((VInit == 2) && 
3798            (programType != fileServer) &&
3799            (programType != salvager));
3800     rc = FSYNC_clientInit();
3801     if (rc)
3802         VInit = 3;
3803     return rc;
3804 }
3805
3806 void
3807 VDisconnectFS_r(void)
3808 {
3809     assert((programType != fileServer) &&
3810            (programType != salvager));
3811     FSYNC_clientFinis();
3812     VInit = 2;
3813 }
3814
3815 void
3816 VDisconnectFS(void)
3817 {
3818     VOL_LOCK;
3819     VDisconnectFS_r();
3820     VOL_UNLOCK;
3821 }
3822
3823 static int
3824 VChildProcReconnectFS_r(void)
3825 {
3826     return FSYNC_clientChildProcReconnect();
3827 }
3828
3829 int
3830 VChildProcReconnectFS(void)
3831 {
3832     int ret;
3833     VOL_LOCK;
3834     ret = VChildProcReconnectFS_r();
3835     VOL_UNLOCK;
3836     return ret;
3837 }
3838 #endif /* FSSYNC_BUILD_CLIENT */
3839
3840
3841 /***************************************************/
3842 /* volume bitmap routines                          */
3843 /***************************************************/
3844
3845 /*
3846  * For demand attach fs, flags parameter controls
3847  * locking behavior.  If (flags & VOL_ALLOC_BITMAP_WAIT)
3848  * is set, then this function will create a reservation
3849  * and block on any other exclusive operations.  Otherwise,
3850  * this function assumes the caller already has exclusive
3851  * access to vp, and we just change the volume state.
3852  */
3853 VnodeId
3854 VAllocBitmapEntry_r(Error * ec, Volume * vp, 
3855                     struct vnodeIndex *index, int flags)
3856 {
3857     VnodeId ret;
3858     register byte *bp, *ep;
3859 #ifdef AFS_DEMAND_ATTACH_FS
3860     VolState state_save;
3861 #endif /* AFS_DEMAND_ATTACH_FS */
3862
3863     *ec = 0;
3864
3865     /* This test is probably redundant */
3866     if (!VolumeWriteable(vp)) {
3867         *ec = (bit32) VREADONLY;
3868         return 0;
3869     }
3870
3871 #ifdef AFS_DEMAND_ATTACH_FS
3872     if (flags & VOL_ALLOC_BITMAP_WAIT) {
3873         VCreateReservation_r(vp);
3874         VWaitExclusiveState_r(vp);
3875     }
3876     state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
3877 #endif /* AFS_DEMAND_ATTACH_FS */
3878
3879 #ifdef BITMAP_LATER
3880     if ((programType == fileServer) && !index->bitmap) {
3881         int i;
3882 #ifndef AFS_DEMAND_ATTACH_FS
3883         /* demand attach fs uses the volume state to avoid races.
3884          * specialStatus field is not used at all */
3885         int wasVBUSY = 0;
3886         if (vp->specialStatus == VBUSY) {
3887             if (vp->goingOffline) {     /* vos dump waiting for the volume to
3888                                          * go offline. We probably come here
3889                                          * from AddNewReadableResidency */
3890                 wasVBUSY = 1;
3891             } else {
3892                 while (vp->specialStatus == VBUSY) {
3893 #ifdef AFS_PTHREAD_ENV
3894                     VOL_UNLOCK;
3895                     sleep(2);
3896                     VOL_LOCK;
3897 #else /* AFS_PTHREAD_ENV */
3898                     IOMGR_Sleep(2);
3899 #endif /* AFS_DEMAND_ATTACH_FS */
3900                 }
3901             }
3902         }
3903 #endif /* !AFS_DEMAND_ATTACH_FS */
3904
3905         if (!index->bitmap) {
3906 #ifndef AFS_DEMAND_ATTACH_FS
3907             vp->specialStatus = VBUSY;  /* Stop anyone else from using it. */
3908 #endif /* AFS_DEMAND_ATTACH_FS */
3909             for (i = 0; i < nVNODECLASSES; i++) {
3910                 VGetBitmap_r(ec, vp, i);
3911                 if (*ec) {
3912 #ifdef AFS_DEMAND_ATTACH_FS
3913                     VRequestSalvage_r(vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3914                     *ec = VSALVAGING;
3915 #else /* AFS_DEMAND_ATTACH_FS */
3916                     DeleteVolumeFromHashTable(vp);
3917                     vp->shuttingDown = 1;       /* Let who has it free it. */
3918                     vp->specialStatus = 0;
3919 #endif /* AFS_DEMAND_ATTACH_FS */
3920                     ret = NULL;
3921                     goto done;
3922                 }
3923             }
3924 #ifndef AFS_DEMAND_ATTACH_FS
3925             if (!wasVBUSY)
3926                 vp->specialStatus = 0;  /* Allow others to have access. */
3927 #endif /* AFS_DEMAND_ATTACH_FS */
3928         }
3929     }
3930 #endif /* BITMAP_LATER */
3931
3932 #ifdef AFS_DEMAND_ATTACH_FS
3933     VOL_UNLOCK;
3934 #endif /* AFS_DEMAND_ATTACH_FS */
3935     bp = index->bitmap + index->bitmapOffset;
3936     ep = index->bitmap + index->bitmapSize;
3937     while (bp < ep) {
3938         if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
3939             int o;
3940             index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
3941             while (*bp == 0xff)
3942                 bp++;
3943             o = ffs(~*bp) - 1;  /* ffs is documented in BSTRING(3) */
3944             *bp |= (1 << o);
3945             ret = (VnodeId) ((bp - index->bitmap) * 8 + o);
3946 #ifdef AFS_DEMAND_ATTACH_FS
3947             VOL_LOCK;
3948 #endif /* AFS_DEMAND_ATTACH_FS */
3949             goto done;
3950         }
3951         bp += sizeof(bit32) /* i.e. 4 */ ;
3952     }
3953     /* No bit map entry--must grow bitmap */
3954     bp = (byte *)
3955         realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
3956     assert(bp != NULL);
3957     index->bitmap = bp;
3958     bp += index->bitmapSize;
3959     memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
3960     index->bitmapOffset = index->bitmapSize;
3961     index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
3962     *bp = 1;
3963     ret = index->bitmapOffset * 8;
3964 #ifdef AFS_DEMAND_ATTACH_FS
3965     VOL_LOCK;
3966 #endif /* AFS_DEMAND_ATTACH_FS */
3967
3968  done:
3969 #ifdef AFS_DEMAND_ATTACH_FS
3970     VChangeState_r(vp, state_save);
3971     if (flags & VOL_ALLOC_BITMAP_WAIT) {
3972         VCancelReservation_r(vp);
3973     }
3974 #endif /* AFS_DEMAND_ATTACH_FS */
3975     return ret;
3976 }
3977
3978 VnodeId
3979 VAllocBitmapEntry(Error * ec, Volume * vp, register struct vnodeIndex * index)
3980 {
3981     VnodeId retVal;
3982     VOL_LOCK;
3983     retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
3984     VOL_UNLOCK;
3985     return retVal;
3986 }
3987
3988 void
3989 VFreeBitMapEntry_r(Error * ec, register struct vnodeIndex *index,
3990                    unsigned bitNumber)
3991 {
3992     unsigned int offset;
3993
3994     *ec = 0;
3995 #ifdef BITMAP_LATER
3996     if (!index->bitmap)
3997         return;
3998 #endif /* BITMAP_LATER */
3999     offset = bitNumber >> 3;
4000     if (offset >= index->bitmapSize) {
4001         *ec = VNOVNODE;
4002         return;
4003     }
4004     if (offset < index->bitmapOffset)
4005         index->bitmapOffset = offset & ~3;      /* Truncate to nearest bit32 */
4006     *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
4007 }
4008
4009 void
4010 VFreeBitMapEntry(Error * ec, register struct vnodeIndex *index,
4011                  unsigned bitNumber)
4012 {
4013     VOL_LOCK;
4014     VFreeBitMapEntry_r(ec, index, bitNumber);
4015     VOL_UNLOCK;
4016 }
4017
4018 /* this function will drop the glock internally.
4019  * for old pthread fileservers, this is safe thanks to vbusy.
4020  *
4021  * for demand attach fs, caller must have already called
4022  * VCreateReservation_r and VWaitExclusiveState_r */
4023 static void
4024 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
4025 {
4026     StreamHandle_t *file;
4027     int nVnodes;
4028     int size;
4029     struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
4030     struct vnodeIndex *vip = &vp->vnodeIndex[class];
4031     struct VnodeDiskObject *vnode;
4032     unsigned int unique = 0;
4033     FdHandle_t *fdP;
4034 #ifdef BITMAP_LATER
4035     byte *BitMap = 0;
4036 #endif /* BITMAP_LATER */
4037 #ifdef AFS_DEMAND_ATTACH_FS
4038     VolState state_save;
4039 #endif /* AFS_DEMAND_ATTACH_FS */
4040
4041     *ec = 0;
4042
4043 #ifdef AFS_DEMAND_ATTACH_FS
4044     state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
4045 #endif /* AFS_DEMAND_ATTACH_FS */
4046     VOL_UNLOCK;
4047
4048     fdP = IH_OPEN(vip->handle);
4049     assert(fdP != NULL);
4050     file = FDH_FDOPEN(fdP, "r");
4051     assert(file != NULL);
4052     vnode = (VnodeDiskObject *) malloc(vcp->diskSize);
4053     assert(vnode != NULL);
4054     size = OS_SIZE(fdP->fd_fd);
4055     assert(size != -1);
4056     nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
4057         >> vcp->logSize;
4058     vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4;     /* The 10 is a little extra so
4059                                                          * a few files can be created in this volume,
4060                                                          * the whole thing is rounded up to nearest 4
4061                                                          * bytes, because the bit map allocator likes
4062                                                          * it that way */
4063 #ifdef BITMAP_LATER
4064     BitMap = (byte *) calloc(1, vip->bitmapSize);
4065     assert(BitMap != NULL);
4066 #else /* BITMAP_LATER */
4067     vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
4068     assert(vip->bitmap != NULL);
4069     vip->bitmapOffset = 0;
4070 #endif /* BITMAP_LATER */
4071     if (STREAM_SEEK(file, vcp->diskSize, 0) != -1) {
4072         int bitNumber = 0;
4073         for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
4074             if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
4075                 break;
4076             if (vnode->type != vNull) {
4077                 if (vnode->vnodeMagic != vcp->magic) {
4078                     Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
4079                     *ec = VSALVAGE;
4080                     break;
4081                 }
4082 #ifdef BITMAP_LATER
4083                 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
4084 #else /* BITMAP_LATER */
4085                 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
4086 #endif /* BITMAP_LATER */
4087                 if (unique <= vnode->uniquifier)
4088                     unique = vnode->uniquifier + 1;
4089             }
4090 #ifndef AFS_PTHREAD_ENV
4091             if ((bitNumber & 0x00ff) == 0x0ff) {        /* every 256 iterations */
4092                 IOMGR_Poll();
4093             }
4094 #endif /* !AFS_PTHREAD_ENV */
4095         }
4096     }
4097     if (vp->nextVnodeUnique < unique) {
4098         Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
4099         *ec = VSALVAGE;
4100     }
4101     /* Paranoia, partly justified--I think fclose after fdopen
4102      * doesn't seem to close fd.  In any event, the documentation
4103      * doesn't specify, so it's safer to close it twice.
4104      */
4105     STREAM_CLOSE(file);
4106     FDH_CLOSE(fdP);
4107     free(vnode);
4108
4109     VOL_LOCK;
4110 #ifdef BITMAP_LATER
4111     /* There may have been a racing condition with some other thread, both
4112      * creating the bitmaps for this volume. If the other thread was faster
4113      * the pointer to bitmap should already be filled and we can free ours.
4114      */
4115     if (vip->bitmap == NULL) {
4116         vip->bitmap = BitMap;
4117         vip->bitmapOffset = 0;
4118     } else
4119         free((byte *) BitMap);
4120 #endif /* BITMAP_LATER */
4121 #ifdef AFS_DEMAND_ATTACH_FS
4122     VChangeState_r(vp, state_save);
4123 #endif /* AFS_DEMAND_ATTACH_FS */
4124 }
4125
4126
4127 /***************************************************/
4128 /* demand attach fs state machine routines         */
4129 /***************************************************/
4130
4131 #ifdef AFS_DEMAND_ATTACH_FS
4132 /* wait for the volume to change states */
4133 static void
4134 VWaitStateChange_r(Volume * vp)
4135 {
4136     VolState state_save = V_attachState(vp);
4137
4138     assert(vp->nWaiters || vp->nUsers);
4139     do {
4140         assert(pthread_cond_wait(&V_attachCV(vp), &vol_glock_mutex) == 0);
4141     } while (V_attachState(vp) == state_save);
4142     assert(V_attachState(vp) != VOL_STATE_FREED);
4143 }
4144
4145 /* wait for blocking ops to end */
4146 static void
4147 VWaitExclusiveState_r(Volume * vp)
4148 {
4149     assert(vp->nWaiters || vp->nUsers);
4150     while (IsExclusiveState(V_attachState(vp))) {
4151         assert(pthread_cond_wait(&V_attachCV(vp), &vol_glock_mutex) == 0);
4152     }
4153     assert(V_attachState(vp) != VOL_STATE_FREED);
4154 }
4155
4156 /* change state, and notify other threads,
4157  * return previous state to caller */
4158 VolState
4159 VChangeState_r(Volume * vp, VolState new_state)
4160 {
4161     VolState old_state = V_attachState(vp);
4162
4163     /* XXX profiling need to make sure these counters
4164      * don't kill performance... */
4165     VStats.state_levels[old_state]--;
4166     VStats.state_levels[new_state]++;
4167
4168     V_attachState(vp) = new_state;
4169     assert(pthread_cond_broadcast(&V_attachCV(vp)) == 0);
4170     return old_state;
4171 }
4172
4173 /* tells caller whether or not the current state requires
4174  * exclusive access without holding glock */
4175 static int
4176 IsExclusiveState(VolState state)
4177 {
4178     switch (state) {
4179     case VOL_STATE_UPDATING:
4180     case VOL_STATE_ATTACHING:
4181     case VOL_STATE_GET_BITMAP:
4182     case VOL_STATE_HDR_LOADING:
4183     case VOL_STATE_HDR_ATTACHING:
4184     case VOL_STATE_OFFLINING:
4185     case VOL_STATE_DETACHING:
4186         return 1;
4187     }
4188     return 0;
4189 }
4190
4191 /* tell caller whether V_attachState is an error condition */
4192 static int
4193 IsErrorState(VolState state)
4194 {
4195     switch (state) {
4196     case VOL_STATE_ERROR:
4197     case VOL_STATE_SALVAGING:
4198         return 1;
4199     }
4200     return 0;
4201 }
4202
4203 /* tell caller whether V_attachState is valid */
4204 static int
4205 IsValidState(VolState state)
4206 {
4207     if ((state >= 0) && 
4208         (state < VOL_STATE_COUNT) &&
4209         (state != VOL_STATE_FREED)) {
4210         return 1;
4211     }
4212     return 0;
4213 }
4214 #endif /* AFS_DEMAND_ATTACH_FS */
4215
4216
4217 /***************************************************/
4218 /* Volume Path and Volume Number utility routines  */
4219 /***************************************************/
4220
4221 static void
4222 GetVolumePath(Error * ec, VolId volumeId, char **partitionp, char **namep)
4223 {
4224     static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
4225     char path[VMAXPATHLEN];
4226     int found = 0;
4227     struct DiskPartition *dp;
4228
4229     *ec = 0;
4230     name[0] = '/';
4231     (void)afs_snprintf(&name[1], (sizeof name) - 1, VFORMAT, volumeId);
4232     for (dp = DiskPartitionList; dp; dp = dp->next) {
4233         struct afs_stat status;
4234         strcpy(path, VPartitionPath(dp));
4235         strcat(path, name);
4236         if (afs_stat(path, &status) == 0) {
4237             strcpy(partition, dp->name);
4238             found = 1;
4239             break;
4240         }
4241     }
4242     if (!found) {
4243         *ec = VNOVOL;
4244         *partitionp = *namep = NULL;
4245     } else {
4246         *partitionp = partition;
4247         *namep = name;
4248     }
4249 }
4250
4251 int
4252 VolumeNumber(char *name)
4253 {
4254     if (*name == '/')
4255         name++;
4256     return atoi(name + 1);
4257 }
4258
4259 char *
4260 VolumeExternalName(VolumeId volumeId)
4261 {
4262     static char name[VMAXPATHLEN];
4263     (void)afs_snprintf(name, sizeof name, VFORMAT, volumeId);
4264     return name;
4265 }
4266
4267 static int
4268 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
4269 {
4270     return afs_snprintf(name, len, VFORMAT, volumeId);
4271 }
4272
4273
4274 /***************************************************/
4275 /* Volume Usage Statistics routines                */
4276 /***************************************************/
4277
4278 #if OPENAFS_VOL_STATS
4279 #define OneDay  (86400)         /* 24 hours' worth of seconds */
4280 #else
4281 #define OneDay  (24*60*60)      /* 24 hours */
4282 #endif /* OPENAFS_VOL_STATS */
4283
4284 #define Midnight(date) ((date-TimeZoneCorrection)/OneDay*OneDay+TimeZoneCorrection)
4285
4286 /*------------------------------------------------------------------------
4287  * [export] VAdjustVolumeStatistics
4288  *
4289  * Description:
4290  *      If we've passed midnight, we need to update all the day use
4291  *      statistics as well as zeroing the detailed volume statistics
4292  *      (if we are implementing them).
4293  *
4294  * Arguments:
4295  *      vp : Pointer to the volume structure describing the lucky
4296  *              volume being considered for update.
4297  *
4298  * Returns:
4299  *      0 (always!)
4300  *
4301  * Environment:
4302  *      Nothing interesting.
4303  *
4304  * Side Effects:
4305  *      As described.
4306  *------------------------------------------------------------------------*/
4307
4308 int
4309 VAdjustVolumeStatistics_r(register Volume * vp)
4310 {
4311     unsigned int now = FT_ApproxTime();
4312
4313     if (now - V_dayUseDate(vp) > OneDay) {
4314         register int ndays, i;
4315
4316         ndays = (now - V_dayUseDate(vp)) / OneDay;
4317         for (i = 6; i > ndays - 1; i--)
4318             V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
4319         for (i = 0; i < ndays - 1 && i < 7; i++)
4320             V_weekUse(vp)[i] = 0;
4321         if (ndays <= 7)
4322             V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
4323         V_dayUse(vp) = 0;
4324         V_dayUseDate(vp) = Midnight(now);
4325
4326 #if OPENAFS_VOL_STATS
4327         /*
4328          * All we need to do is bzero the entire VOL_STATS_BYTES of
4329          * the detailed volume statistics area.
4330          */
4331         memset((char *)(V_stat_area(vp)), 0, VOL_STATS_BYTES);
4332 #endif /* OPENAFS_VOL_STATS */
4333     }
4334
4335     /*It's been more than a day of collection */
4336     /*
4337      * Always return happily.
4338      */
4339     return (0);
4340 }                               /*VAdjustVolumeStatistics */
4341
4342 int
4343 VAdjustVolumeStatistics(register Volume * vp)
4344 {
4345     int retVal;
4346     VOL_LOCK;
4347     retVal = VAdjustVolumeStatistics_r(vp);
4348     VOL_UNLOCK;
4349     return retVal;
4350 }
4351
4352 void
4353 VBumpVolumeUsage_r(register Volume * vp)
4354 {
4355     unsigned int now = FT_ApproxTime();
4356     if (now - V_dayUseDate(vp) > OneDay)
4357         VAdjustVolumeStatistics_r(vp);
4358     /*
4359      * Save the volume header image to disk after every 128 bumps to dayUse.
4360      */
4361     if ((V_dayUse(vp)++ & 127) == 0) {
4362         Error error;
4363         VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
4364     }
4365 }
4366
4367 void
4368 VBumpVolumeUsage(register Volume * vp)
4369 {
4370     VOL_LOCK;
4371     VBumpVolumeUsage_r(vp);
4372     VOL_UNLOCK;
4373 }
4374
4375 void
4376 VSetDiskUsage_r(void)
4377 {
4378 #ifndef AFS_DEMAND_ATTACH_FS
4379     static int FifteenMinuteCounter = 0;
4380 #endif
4381
4382     while (VInit < 2) {
4383         /* NOTE: Don't attempt to access the partitions list until the
4384          * initialization level indicates that all volumes are attached,
4385          * which implies that all partitions are initialized. */
4386 #ifdef AFS_PTHREAD_ENV
4387         sleep(10);
4388 #else /* AFS_PTHREAD_ENV */
4389         IOMGR_Sleep(10);
4390 #endif /* AFS_PTHREAD_ENV */
4391     }
4392
4393     VResetDiskUsage_r();
4394
4395 #ifndef AFS_DEMAND_ATTACH_FS
4396     if (++FifteenMinuteCounter == 3) {
4397         FifteenMinuteCounter = 0;
4398         VScanUpdateList();
4399     }
4400 #endif /* !AFS_DEMAND_ATTACH_FS */
4401 }
4402
4403 void
4404 VSetDiskUsage(void)
4405 {
4406     VOL_LOCK;
4407     VSetDiskUsage_r();
4408     VOL_UNLOCK;
4409 }
4410
4411
4412 /***************************************************/
4413 /* Volume Update List routines                     */
4414 /***************************************************/
4415
4416 /* The number of minutes that a volume hasn't been updated before the
4417  * "Dont salvage" flag in the volume header will be turned on */
4418 #define SALVAGE_INTERVAL        (10*60)
4419
4420 /*
4421  * demand attach fs
4422  *
4423  * volume update list functionality has been moved into the VLRU
4424  * the DONT_SALVAGE flag is now set during VLRU demotion
4425  */
4426
4427 #ifndef AFS_DEMAND_ATTACH_FS
4428 static VolumeId *UpdateList = NULL;     /* Pointer to array of Volume ID's */
4429 static int nUpdatedVolumes = 0;         /* Updated with entry in UpdateList, salvage after crash flag on */
4430 static int updateSize = 0;              /* number of entries possible */
4431 #define UPDATE_LIST_SIZE 128            /* initial size increment (must be a power of 2!) */
4432 #endif /* !AFS_DEMAND_ATTACH_FS */
4433
4434 void
4435 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
4436 {
4437     *ec = 0;
4438     vp->updateTime = FT_ApproxTime();
4439     if (V_dontSalvage(vp) == 0)
4440         return;
4441     V_dontSalvage(vp) = 0;
4442     VSyncVolume_r(ec, vp, 0);
4443 #ifdef AFS_DEMAND_ATTACH_FS
4444     V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
4445 #else /* !AFS_DEMAND_ATTACH_FS */
4446     if (*ec)
4447         return;
4448     if (UpdateList == NULL) {
4449         updateSize = UPDATE_LIST_SIZE;
4450         UpdateList = (VolumeId *) malloc(sizeof(VolumeId) * updateSize);
4451     } else {
4452         if (nUpdatedVolumes == updateSize) {
4453             updateSize << 1;
4454             if (updateSize > 524288) {
4455                 Log("warning: there is likely a bug in the volume update scanner\n");
4456                 return;
4457             }
4458             UpdateList =
4459                 (VolumeId *) realloc(UpdateList,
4460                                      sizeof(VolumeId) * updateSize);
4461         }
4462     }
4463     assert(UpdateList != NULL);
4464     UpdateList[nUpdatedVolumes++] = V_id(vp);
4465 #endif /* !AFS_DEMAND_ATTACH_FS */
4466 }
4467
4468 #ifndef AFS_DEMAND_ATTACH_FS
4469 static void
4470 VScanUpdateList(void)
4471 {
4472     register int i, gap;
4473     register Volume *vp;
4474     Error error;
4475     afs_uint32 now = FT_ApproxTime();
4476     /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
4477     for (i = gap = 0; i < nUpdatedVolumes; i++) {
4478         if (gap)
4479             UpdateList[i - gap] = UpdateList[i];
4480
4481         /* XXX this routine needlessly messes up the Volume LRU by
4482          * breaking the LRU temporal-locality assumptions.....
4483          * we should use a special volume header allocator here */
4484         vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
4485         if (error) {
4486             gap++;
4487         } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
4488             V_dontSalvage(vp) = DONT_SALVAGE;
4489             VUpdateVolume_r(&error, vp, 0);     /* No need to fsync--not critical */
4490             gap++;
4491         }
4492
4493         if (vp) {
4494             VPutVolume_r(vp);
4495         }
4496
4497 #ifndef AFS_PTHREAD_ENV
4498         IOMGR_Poll();
4499 #endif /* !AFS_PTHREAD_ENV */
4500     }
4501     nUpdatedVolumes -= gap;
4502 }
4503 #endif /* !AFS_DEMAND_ATTACH_FS */
4504
4505
4506 /***************************************************/
4507 /* Volume LRU routines                             */
4508 /***************************************************/
4509
4510 /* demand attach fs
4511  * volume LRU
4512  *
4513  * with demand attach fs, we attempt to soft detach(1)
4514  * volumes which have not been accessed in a long time
4515  * in order to speed up fileserver shutdown
4516  *
4517  * (1) by soft detach we mean a process very similar
4518  *     to VOffline, except the final state of the 
4519  *     Volume will be VOL_STATE_PREATTACHED, instead
4520  *     of the usual VOL_STATE_UNATTACHED
4521  */
4522 #ifdef AFS_DEMAND_ATTACH_FS
4523
4524 /* implementation is reminiscent of a generational GC
4525  *
4526  * queue 0 is newly attached volumes. this queue is
4527  * sorted by attach timestamp
4528  *
4529  * queue 1 is volumes that have been around a bit
4530  * longer than queue 0. this queue is sorted by
4531  * attach timestamp
4532  *
4533  * queue 2 is volumes tha have been around the longest.
4534  * this queue is unsorted
4535  *
4536  * queue 3 is volumes that have been marked as
4537  * candidates for soft detachment. this queue is
4538  * unsorted
4539  */
4540 #define VLRU_GENERATIONS  3   /* number of generations in VLRU */
4541 #define VLRU_QUEUES       5   /* total number of VLRU queues */
4542 struct VLRU_q {
4543     volatile struct rx_queue q;
4544     volatile int len;
4545     volatile int busy;
4546     pthread_cond_t cv;
4547 };
4548 struct VLRU {
4549     struct VLRU_q q[VLRU_QUEUES];
4550
4551     /* VLRU config */
4552     afs_uint32 promotion_interval[VLRU_GENERATIONS-1];  /* interval between promotions */
4553     afs_uint32 scan_interval[VLRU_GENERATIONS+1];       /* interval between scans for candidates */
4554
4555     /* state */
4556     int next_idx;
4557     afs_uint32 last_promotion[VLRU_GENERATIONS-1];      /* timestamp of last promotion scan */
4558     afs_uint32 last_scan[VLRU_GENERATIONS+1];           /* timestamp of last detach scan */
4559
4560     int scanner_state;                                  /* state of scanner thread */
4561     pthread_cond_t cv;                                  /* state transition CV */
4562 };
4563
4564 static struct VLRU volume_LRU;
4565
4566 /* valid scanner states */
4567 #define VLRU_SCANNER_STATE_OFFLINE        0
4568 #define VLRU_SCANNER_STATE_ONLINE         1
4569 #define VLRU_SCANNER_STATE_SHUTTING_DOWN  2
4570 #define VLRU_SCANNER_STATE_PAUSING        3
4571 #define VLRU_SCANNER_STATE_PAUSED         4
4572
4573 /* vlru disk data header stuff */
4574 #define VLRU_DISK_MAGIC      0x7a8b9cad
4575 #define VLRU_DISK_VERSION    1
4576
4577 /* vlru default expiration time (for eventual fs state serialization of vlru data) */
4578 #define VLRU_DUMP_EXPIRATION_TIME   (60*60*24*7)  /* expire vlru data after 1 week */
4579
4580
4581 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
4582 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
4583 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
4584 static afs_uint32 VLRU_enabled = 1;
4585
4586 /* queue synchronization routines */
4587 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
4588 static void VLRU_EndExclusive_r(struct VLRU_q * q);
4589 static void VLRU_Wait_r(struct VLRU_q * q);
4590
4591 /* set the VLRU parameters 
4592  *
4593  * valid options are:
4594  *  VLRU_SET_THRESH -- set the period of inactivity after
4595  *    which volumes are eligible for being detached
4596  *  VLRU_SET_INTERVAL -- the time interval between calls
4597  *    to the volume LRU "garbage collector"
4598  *  VLRU_SET_MAX -- the max number of volumes to deallocate
4599  *    in one GC pass
4600  */
4601 void
4602 VLRU_SetOptions(int option, afs_uint32 val)
4603 {
4604     if (option == VLRU_SET_THRESH) {
4605         VLRU_offline_thresh = val;
4606     } else if (option == VLRU_SET_INTERVAL) {
4607         VLRU_offline_interval = val;
4608     } else if (option == VLRU_SET_MAX) {
4609         VLRU_offline_max = val;
4610     } else if (option == VLRU_SET_ENABLED) {
4611         VLRU_enabled = val;
4612     }
4613     VLRU_ComputeConstants();
4614 }
4615
4616 /* compute the VLRU internal timing parameters based upon the user's inputs */
4617 static void
4618 VLRU_ComputeConstants(void)
4619 {
4620     afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
4621
4622     /* compute the candidate scan interval */
4623     volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
4624
4625     /* compute the promotion intervals */
4626     volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
4627     volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
4628
4629     if (factor > 16) {
4630         /* compute the gen 0 scan interval */
4631         volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
4632     } else {
4633         /* compute the gen 0 scan interval */
4634         volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
4635     }
4636 }
4637
4638 /* initialize VLRU */
4639 static void
4640 VInitVLRU(void)
4641 {
4642     pthread_t tid;
4643     pthread_attr_t attrs;
4644     int i;
4645
4646     if (!VLRU_enabled) {
4647         Log("VLRU: disabled\n");
4648         return;
4649     }
4650
4651     /* initialize each of the VLRU queues */
4652     for (i = 0; i < VLRU_QUEUES; i++) {
4653         queue_Init(&volume_LRU.q[i]);
4654         volume_LRU.q[i].len = 0;
4655         volume_LRU.q[i].busy = 0;
4656         assert(pthread_cond_init(&volume_LRU.q[i].cv, NULL) == 0);
4657     }
4658
4659     /* setup the timing constants */
4660     VLRU_ComputeConstants();
4661
4662     /* XXX put inside LogLevel check? */
4663     Log("VLRU: starting scanner with the following configuration parameters:\n");
4664     Log("VLRU:  offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
4665     Log("VLRU:  running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
4666     Log("VLRU:  taking up to %d volumes offline per pass\n", VLRU_offline_max);
4667     Log("VLRU:  scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
4668     Log("VLRU:  scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
4669     Log("VLRU:  scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
4670
4671     /* start up the VLRU scanner */
4672     volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
4673     if (programType == fileServer) {
4674         assert(pthread_cond_init(&volume_LRU.cv, NULL) == 0);
4675         assert(pthread_attr_init(&attrs) == 0);
4676         assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
4677         assert(pthread_create(&tid, &attrs, &VLRU_ScannerThread, NULL) == 0);
4678     }
4679 }
4680
4681 /* initialize LRU support for a volume */
4682 static void
4683 VLRU_Init_Node_r(volatile Volume * vp)
4684 {
4685     if (!VLRU_enabled)
4686         return;
4687
4688     assert(queue_IsNotOnQueue(&vp->vlru));
4689     vp->vlru.idx = VLRU_QUEUE_INVALID;
4690 }
4691
4692 /* add volume to VLRU 
4693  * now supports adding to queues other
4694  * than new for vlru state restore
4695  * caller MUST hold a ref count on vp */
4696 static void
4697 VLRU_Add_r(volatile Volume * vp)
4698 {
4699     int idx;
4700
4701     if (!VLRU_enabled)
4702         return;
4703
4704     if (queue_IsOnQueue(&vp->vlru))
4705         return;
4706
4707     VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
4708
4709     /* repeat check since VLRU_Wait_r may have dropped
4710      * the glock */
4711     if (queue_IsNotOnQueue(&vp->vlru)) {
4712         idx = vp->vlru.idx;
4713         if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
4714             idx = vp->vlru.idx = VLRU_QUEUE_NEW;
4715         }
4716         queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
4717         volume_LRU.q[idx].len++;
4718         V_attachFlags(vp) |= VOL_ON_VLRU;
4719         vp->stats.last_promote = FT_ApproxTime();
4720     }
4721 }
4722
4723 /* delete volume from VLRU 
4724  * caller MUST hold a ref count on vp */
4725 static void
4726 VLRU_Delete_r(volatile Volume * vp)
4727 {
4728     int idx;
4729
4730     if (!VLRU_enabled)
4731         return;
4732
4733     if (queue_IsNotOnQueue(&vp->vlru))
4734         return;
4735
4736     /* handle races */
4737     do {
4738       idx = vp->vlru.idx;
4739       if (idx == VLRU_QUEUE_INVALID)
4740           return;
4741       VLRU_Wait_r(&volume_LRU.q[idx]);
4742     } while (idx != vp->vlru.idx);
4743
4744     /* now remove from the VLRU and update 
4745      * the appropriate counter */
4746     queue_Remove(&vp->vlru);
4747     volume_LRU.q[idx].len--;
4748     vp->vlru.idx = VLRU_QUEUE_INVALID;
4749     V_attachFlags(vp) &= ~(VOL_ON_VLRU);
4750 }
4751
4752 /* signal that volume was just accessed.
4753  * caller MUST hold a ref count on vp */
4754 static void
4755 VLRU_UpdateAccess_r(volatile Volume * vp)
4756 {
4757     afs_uint32 live_interval;
4758     Volume * rvp = NULL;
4759
4760     if (!VLRU_enabled)
4761         return;
4762
4763     if (queue_IsNotOnQueue(&vp->vlru))
4764         return;
4765
4766     assert(V_attachFlags(vp) & VOL_ON_VLRU);
4767
4768     /* update the access timestamp */
4769     vp->stats.last_get = FT_ApproxTime();
4770
4771     /*
4772      * if the volume is on the soft detach candidate
4773      * list, we need to safely move it back to a
4774      * regular generation.  this has to be done
4775      * carefully so we don't race against the scanner
4776      * thread.
4777      */
4778
4779     /* if this volume is on the soft detach candidate queue,
4780      * then grab exclusive access to the necessary queues */
4781     if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
4782         rvp = vp;
4783         VCreateReservation_r(rvp);
4784
4785         VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
4786         VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
4787         VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
4788         VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
4789     }
4790
4791     /* make sure multiple threads don't race to update */
4792     if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
4793         VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
4794     }
4795
4796     if (rvp) {
4797       VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
4798       VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
4799       VCancelReservation_r(rvp);
4800     }
4801 }
4802
4803 /* switch a volume between two VLRU queues */
4804 static void
4805 VLRU_SwitchQueues(volatile Volume * vp, int new_idx, int append)
4806 {
4807     if (queue_IsNotOnQueue(&vp->vlru))
4808         return;
4809
4810     queue_Remove(&vp->vlru);
4811     volume_LRU.q[vp->vlru.idx].len--;
4812     
4813     /* put the volume back on the correct generational queue */
4814     if (append) {
4815         queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
4816     } else {
4817         queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
4818     }
4819
4820     volume_LRU.q[new_idx].len++;
4821     vp->vlru.idx = new_idx;
4822 }
4823
4824 /* VLRU GC thread */
4825 static void *
4826 VLRU_ScannerThread(void * args)
4827 {
4828     afs_uint32 now, min_delay, delay;
4829     afs_uint32 next_scan[VLRU_GENERATIONS];
4830     afs_uint32 next_promotion[VLRU_GENERATIONS];
4831     int i, min_idx, min_op, overdue, state;
4832
4833     /* set t=0 for promotion cycle to be 
4834      * fileserver startup */
4835     now = FT_ApproxTime();
4836     for (i=0; i < VLRU_GENERATIONS-1; i++) {
4837         volume_LRU.last_promotion[i] = now;
4838     }
4839
4840     /* don't start the scanner until VLRU_offline_thresh
4841      * plus a small delay for VInitVolumePackage to finish
4842      * has gone by */
4843
4844     sleep(VLRU_offline_thresh + 60);
4845
4846     /* set t=0 for scan cycle to be now */
4847     now = FT_ApproxTime();
4848     for (i=0; i < VLRU_GENERATIONS+1; i++) {
4849         volume_LRU.last_scan[i] = now;
4850     }
4851
4852     VOL_LOCK;
4853     if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
4854         volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
4855     }
4856
4857     while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
4858         /* check to see if we've been asked to pause */
4859         if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
4860             volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
4861             assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
4862             do {
4863                 assert(pthread_cond_wait(&volume_LRU.cv, &vol_glock_mutex) == 0);
4864             } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
4865         }
4866
4867         /* scheduling can happen outside the glock */
4868         VOL_UNLOCK;
4869
4870         /* figure out what is next on the schedule */
4871
4872         /* figure out a potential schedule for the new generation first */
4873         overdue = 0;
4874         min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
4875         min_idx = 0;
4876         min_op = 0;
4877         if (min_delay > volume_LRU.scan_interval[0]) {
4878             /* unsigned overflow -- we're overdue to run this scan */
4879             min_delay = 0;
4880             overdue = 1;
4881         }
4882
4883         /* if we're not overdue for gen 0, figure out schedule for candidate gen */
4884         if (!overdue) {
4885             i = VLRU_QUEUE_CANDIDATE;
4886             delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
4887             if (delay < min_delay) {
4888                 min_delay = delay;
4889                 min_idx = i;
4890             }
4891             if (delay > volume_LRU.scan_interval[i]) {
4892                 /* unsigned overflow -- we're overdue to run this scan */
4893                 min_delay = 0;
4894                 min_idx = i;
4895                 overdue = 1;
4896                 break;
4897             }
4898         }
4899
4900         /* if we're still not overdue for something, figure out schedules for promotions */
4901         for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
4902             delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
4903             if (delay < min_delay) {
4904                 min_delay = delay;
4905                 min_idx = i;
4906                 min_op = 1;
4907             }
4908             if (delay > volume_LRU.promotion_interval[i]) {
4909                 /* unsigned overflow -- we're overdue to run this promotion */
4910                 min_delay = 0;
4911                 min_idx = i;
4912                 min_op = 1;
4913                 overdue = 1;
4914                 break;
4915             }
4916         }
4917
4918         /* sleep as needed */
4919         if (min_delay) {
4920             sleep(min_delay);
4921         }
4922
4923         /* do whatever is next */
4924         VOL_LOCK;
4925         if (min_op) {
4926             VLRU_Promote_r(min_idx);
4927             VLRU_Demote_r(min_idx+1);
4928         } else {
4929             VLRU_Scan_r(min_idx);
4930         }
4931         now = FT_ApproxTime();
4932     }
4933
4934     Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
4935
4936     /* signal that scanner is down */
4937     volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
4938     assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
4939     VOL_UNLOCK;
4940     return NULL;
4941 }
4942
4943 /* run the promotions */
4944 static void
4945 VLRU_Promote_r(int idx)
4946 {
4947     int len, chaining, promote;
4948     afs_uint32 now, thresh;
4949     struct rx_queue *qp, *nqp;
4950     Volume * vp, *start, *end;
4951
4952     /* get exclusive access to two chains, and drop the glock */
4953     VLRU_Wait_r(&volume_LRU.q[idx]);
4954     VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
4955     VLRU_Wait_r(&volume_LRU.q[idx+1]);
4956     VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
4957     VOL_UNLOCK;
4958
4959     thresh = volume_LRU.promotion_interval[idx];
4960     now = FT_ApproxTime();
4961
4962     len = chaining = 0;
4963     for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
4964         vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
4965         promote = (((vp->stats.last_promote + thresh) <= now) &&
4966                    (vp->stats.last_get >= vp->stats.last_promote));
4967
4968         if (chaining) {
4969             if (promote) {
4970                 vp->vlru.idx++;
4971                 len++;
4972                 start = vp;
4973             } else {
4974                 /* promote and prepend chain */
4975                 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
4976                 chaining = 0;
4977             }
4978         } else {
4979             if (promote) {
4980                 vp->vlru.idx++;
4981                 len++;
4982                 chaining = 1;
4983                 start = end = vp;
4984             }
4985         }
4986     }
4987
4988     if (chaining) {
4989         /* promote and prepend */
4990         queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
4991     }
4992
4993     if (len) {
4994         volume_LRU.q[idx].len -= len;
4995         volume_LRU.q[idx+1].len += len;
4996     }
4997
4998     /* release exclusive access to the two chains */
4999     VOL_LOCK;
5000     volume_LRU.last_promotion[idx] = now;
5001     VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
5002     VLRU_EndExclusive_r(&volume_LRU.q[idx]);
5003 }
5004
5005 /* run the demotions */
5006 static void
5007 VLRU_Demote_r(int idx)
5008 {
5009     Error ec;
5010     int len, chaining, demote;
5011     afs_uint32 now, thresh;
5012     struct rx_queue *qp, *nqp;
5013     Volume * vp, *start, *end;
5014     Volume ** salv_flag_vec = NULL;
5015     int salv_vec_offset = 0;
5016
5017     assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
5018
5019     /* get exclusive access to two chains, and drop the glock */
5020     VLRU_Wait_r(&volume_LRU.q[idx-1]);
5021     VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
5022     VLRU_Wait_r(&volume_LRU.q[idx]);
5023     VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
5024     VOL_UNLOCK;
5025
5026     /* no big deal if this allocation fails */
5027     if (volume_LRU.q[idx].len) {
5028         salv_flag_vec = (Volume **) malloc(volume_LRU.q[idx].len * sizeof(Volume *));
5029     }
5030
5031     now = FT_ApproxTime();
5032     thresh = volume_LRU.promotion_interval[idx-1];
5033
5034     len = chaining = 0;
5035     for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
5036         vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
5037         demote = (((vp->stats.last_promote + thresh) <= now) &&
5038                   (vp->stats.last_get < (now - thresh)));
5039
5040         /* we now do volume update list DONT_SALVAGE flag setting during
5041          * demotion passes */
5042         if (salv_flag_vec &&
5043             !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
5044             demote && 
5045             (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
5046             (V_attachState(vp) == VOL_STATE_ATTACHED)) {
5047             salv_flag_vec[salv_vec_offset++] = vp;
5048             VCreateReservation_r(vp);
5049         }
5050
5051         if (chaining) {
5052             if (demote) {
5053                 vp->vlru.idx--;
5054                 len++;
5055                 start = vp;
5056             } else {
5057                 /* demote and append chain */
5058                 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
5059                 chaining = 0;
5060             }
5061         } else {
5062             if (demote) {
5063                 vp->vlru.idx--;
5064                 len++;
5065                 chaining = 1;
5066                 start = end = vp;
5067             }
5068         }
5069     }
5070
5071     if (chaining) {
5072         queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
5073     }
5074
5075     if (len) {
5076         volume_LRU.q[idx].len -= len;
5077         volume_LRU.q[idx-1].len += len;
5078     }
5079
5080     /* release exclusive access to the two chains */
5081     VOL_LOCK;
5082     VLRU_EndExclusive_r(&volume_LRU.q[idx]);
5083     VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
5084
5085     /* now go back and set the DONT_SALVAGE flags as appropriate */
5086     if (salv_flag_vec) {
5087         int i;
5088         for (i = 0; i < salv_vec_offset; i++) {
5089             vp = salv_flag_vec[i];
5090             if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
5091                 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
5092                 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
5093                 ec = VHold_r(vp);
5094                 if (!ec) {
5095                     V_attachFlags(vp) |= VOL_HDR_DONTSALV;
5096                     V_dontSalvage(vp) = DONT_SALVAGE;
5097                     VUpdateVolume_r(&ec, vp, 0);
5098                     VPutVolume_r(vp);
5099                 }
5100             }
5101             VCancelReservation_r(vp);
5102         }
5103         free(salv_flag_vec);
5104     }
5105 }
5106
5107 /* run a pass of the VLRU GC scanner */
5108 static void
5109 VLRU_Scan_r(int idx)
5110 {
5111     afs_uint32 now, thresh;
5112     struct rx_queue *qp, *nqp;
5113     volatile Volume * vp;
5114     int i, locked = 1;
5115
5116     assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
5117
5118     /* gain exclusive access to the idx VLRU */
5119     VLRU_Wait_r(&volume_LRU.q[idx]);
5120     VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
5121
5122     if (idx != VLRU_QUEUE_CANDIDATE) {
5123         /* gain exclusive access to the candidate VLRU */
5124         VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5125         VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5126     }
5127
5128     now = FT_ApproxTime();
5129     thresh = now - VLRU_offline_thresh;
5130
5131     /* perform candidate selection and soft detaching */
5132     if (idx == VLRU_QUEUE_CANDIDATE) {
5133         /* soft detach some volumes from the candidate pool */
5134         VOL_UNLOCK;
5135         locked = 0;
5136
5137         for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
5138             vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
5139             if (i >= VLRU_offline_max) {
5140                 break;
5141             }
5142             /* check timestamp to see if it's a candidate for soft detaching */
5143             if (vp->stats.last_get <= thresh) {
5144                 VOL_LOCK;
5145                 if (VCheckSoftDetach(vp, thresh))
5146                     i++;
5147                 VOL_UNLOCK;
5148             }
5149         }
5150     } else {
5151         /* scan for volumes to become soft detach candidates */
5152         for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
5153             vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
5154
5155             /* check timestamp to see if it's a candidate for soft detaching */
5156             if (vp->stats.last_get <= thresh) {
5157                 VCheckSoftDetachCandidate(vp, thresh);
5158             }
5159
5160             if (!(i&0x7f)) {   /* lock coarsening optimization */
5161                 VOL_UNLOCK;
5162                 pthread_yield();
5163                 VOL_LOCK;
5164             }
5165         }
5166     }
5167
5168     /* relinquish exclusive access to the VLRU chains */
5169     if (!locked) {
5170         VOL_LOCK;
5171     }
5172     volume_LRU.last_scan[idx] = now;
5173     if (idx != VLRU_QUEUE_CANDIDATE) {
5174         VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5175     }
5176     VLRU_EndExclusive_r(&volume_LRU.q[idx]);
5177 }
5178
5179 /* check whether volume is safe to soft detach
5180  * caller MUST NOT hold a ref count on vp */
5181 static int
5182 VCheckSoftDetach(volatile Volume * vp, afs_uint32 thresh)
5183 {
5184     int ret=0;
5185
5186     if (vp->nUsers || vp->nWaiters)
5187         return 0;
5188
5189     if (vp->stats.last_get <= thresh) {
5190         ret = VSoftDetachVolume_r(vp, thresh);
5191     }
5192
5193     return ret;
5194 }
5195
5196 /* check whether volume should be made a 
5197  * soft detach candidate */
5198 static int
5199 VCheckSoftDetachCandidate(volatile Volume * vp, afs_uint32 thresh)
5200 {
5201     int idx, ret = 0;
5202     if (vp->nUsers || vp->nWaiters)
5203         return 0;
5204
5205     idx = vp->vlru.idx;
5206
5207     assert(idx == VLRU_QUEUE_NEW);
5208
5209     if (vp->stats.last_get <= thresh) {
5210         /* move to candidate pool */
5211         queue_Remove(&vp->vlru);
5212         volume_LRU.q[VLRU_QUEUE_NEW].len--;
5213         queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
5214         vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
5215         volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
5216         ret = 1;
5217     }
5218
5219     return ret;
5220 }
5221
5222
5223 /* begin exclusive access on VLRU */
5224 static void
5225 VLRU_BeginExclusive_r(struct VLRU_q * q)
5226 {
5227     assert(q->busy == 0);
5228     q->busy = 1;
5229 }
5230
5231 /* end exclusive access on VLRU */
5232 static void
5233 VLRU_EndExclusive_r(struct VLRU_q * q)
5234 {
5235     assert(q->busy);
5236     q->busy = 0;
5237     assert(pthread_cond_broadcast(&q->cv) == 0);
5238 }
5239
5240 /* wait for another thread to end exclusive access on VLRU */
5241 static void
5242 VLRU_Wait_r(struct VLRU_q * q)
5243 {
5244     while(q->busy) {
5245         assert(pthread_cond_wait(&q->cv, &vol_glock_mutex) == 0);
5246     }
5247 }
5248
5249 /* demand attach fs
5250  * volume soft detach
5251  *
5252  * caller MUST NOT hold a ref count on vp */
5253 static int
5254 VSoftDetachVolume_r(volatile Volume * vp, afs_uint32 thresh)
5255 {
5256     afs_uint32 ts_save;
5257     int ret = 0;
5258
5259     assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
5260
5261     ts_save = vp->stats.last_get;
5262     if (ts_save > thresh)
5263         return 0;
5264
5265     if (vp->nUsers || vp->nWaiters)
5266         return 0;
5267
5268     if (IsExclusiveState(V_attachState(vp))) {
5269         return 0;
5270     }
5271
5272     switch (V_attachState(vp)) {
5273     case VOL_STATE_UNATTACHED:
5274     case VOL_STATE_PREATTACHED:
5275     case VOL_STATE_ERROR:
5276     case VOL_STATE_GOING_OFFLINE:
5277     case VOL_STATE_SHUTTING_DOWN:
5278     case VOL_STATE_SALVAGING:
5279         volume_LRU.q[vp->vlru.idx].len--;
5280
5281         /* create and cancel a reservation to
5282          * give the volume an opportunity to
5283          * be deallocated */
5284         VCreateReservation_r(vp);
5285         queue_Remove(&vp->vlru);
5286         vp->vlru.idx = VLRU_QUEUE_INVALID;
5287         V_attachFlags(vp) &= ~(VOL_ON_VLRU);
5288         VCancelReservation_r(vp);
5289         return 0;
5290     }
5291
5292     /* hold the volume and take it offline.
5293      * no need for reservations, as VHold_r
5294      * takes care of that internally. */
5295     if (VHold_r(vp) == 0) {
5296         /* vhold drops the glock, so now we should
5297          * check to make sure we aren't racing against
5298          * other threads.  if we are racing, offlining vp
5299          * would be wasteful, and block the scanner for a while 
5300          */
5301         if (vp->nWaiters || 
5302             (vp->nUsers > 1) ||
5303             (vp->shuttingDown) ||
5304             (vp->goingOffline) ||
5305             (vp->stats.last_get != ts_save)) {
5306             /* looks like we're racing someone else. bail */
5307             VPutVolume_r(vp);
5308             vp = NULL;
5309         } else {
5310             /* pull it off the VLRU */
5311             assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
5312             volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
5313             queue_Remove(&vp->vlru);
5314             vp->vlru.idx = VLRU_QUEUE_INVALID;
5315             V_attachFlags(vp) &= ~(VOL_ON_VLRU);
5316
5317             /* take if offline */
5318             VOffline_r(vp, "volume has been soft detached");
5319
5320             /* invalidate the volume header cache */
5321             FreeVolumeHeader(vp);
5322
5323             /* update stats */
5324             IncUInt64(&VStats.soft_detaches);
5325             vp->stats.soft_detaches++;
5326
5327             /* put in pre-attached state so demand
5328              * attacher can work on it */
5329             VChangeState_r(vp, VOL_STATE_PREATTACHED);
5330             ret = 1;
5331         }
5332     }
5333     return ret;
5334 }
5335 #endif /* AFS_DEMAND_ATTACH_FS */
5336
5337
5338 /***************************************************/
5339 /* Volume Header Cache routines                    */
5340 /***************************************************/
5341
5342 struct volume_hdr_LRU_t volume_hdr_LRU;
5343
5344 /* Allocate a bunch of headers; string them together */
5345 static void
5346 VInitVolumeHeaderCache(afs_uint32 howMany)
5347 {
5348     register struct volHeader *hp;
5349     if (programType != fileServer)
5350         return;
5351     queue_Init(&volume_hdr_LRU);
5352 #ifdef AFS_DEMAND_ATTACH_FS
5353     volume_hdr_LRU.stats.free = 0;
5354     volume_hdr_LRU.stats.used = howMany;
5355     volume_hdr_LRU.stats.attached = 0;
5356 #endif
5357     hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
5358     while (howMany--)
5359         ReleaseVolumeHeader(hp++);
5360 }
5361
5362 #ifdef AFS_DEMAND_ATTACH_FS
5363 /* Get a volume header from the LRU list; update the old one if necessary */
5364 /* Returns 1 if there was already a header, which is removed from the LRU list */
5365 /* caller MUST has a ref count on vp */
5366 static int
5367 GetVolumeHeader(register Volume * vp)
5368 {
5369     Error error;
5370     register struct volHeader *hd;
5371     int old;
5372     static int everLogged = 0;
5373
5374     /* XXX debug 9/19/05 we've apparently got
5375      * a ref counting bug somewhere that's
5376      * breaking the nUsers == 0 => header on LRU
5377      * assumption */
5378     if (vp->header && queue_IsNotOnQueue(vp->header)) {
5379         Log("nUsers == 0, but header not on LRU\n");
5380         return 1;
5381     }
5382
5383     old = (vp->header != NULL); /* old == volume already has a header */
5384
5385     if (programType != fileServer) {
5386         /* for volume utilities, we allocate volHeaders as needed */
5387         if (!vp->header) {
5388             hd = (struct volHeader *)calloc(1, sizeof(*vp->header));
5389             assert(hd != NULL);
5390             vp->header = hd;
5391             hd->back = vp;
5392             V_attachFlags(vp) |= VOL_HDR_ATTACHED;
5393         }
5394     } else {
5395         if (old) {
5396             /* the header we previously dropped in the lru is
5397              * still available. pull it off the lru and return */
5398             hd = vp->header;
5399             queue_Remove(hd);
5400             assert(hd->back == vp);
5401         } else {
5402             /* we need to grab a new element off the LRU */
5403             if (queue_IsNotEmpty(&volume_hdr_LRU)) {
5404                 /* grab an element and pull off of LRU */
5405                 hd = queue_First(&volume_hdr_LRU, volHeader);
5406                 queue_Remove(hd);
5407             } else {
5408                 /* LRU is empty, so allocate a new volHeader 
5409                  * this is probably indicative of a leak, so let the user know */
5410                 hd = (struct volHeader *)calloc(1, sizeof(struct volHeader));
5411                 assert(hd != NULL);
5412                 if (!everLogged) {
5413                     Log("****Allocated more volume headers, probably leak****\n");
5414                     everLogged = 1;
5415                 }
5416                 volume_hdr_LRU.stats.free++;
5417             }
5418             if (hd->back) {
5419                 VolState vp_save, back_save;
5420                 /* this header used to belong to someone else. 
5421                  * we'll need to check if the header needs to
5422                  * be sync'd out to disk */
5423
5424                 /* if hd->back were in an exclusive state, then
5425                  * its volHeader would not be on the LRU... */
5426                 assert(!IsExclusiveState(V_attachState(hd->back)));
5427
5428                 if (hd->diskstuff.inUse) {
5429                     /* volume was in use, so we'll need to sync
5430                      * its header to disk */
5431                     back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
5432                     vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
5433                     VCreateReservation_r(hd->back);
5434                     VOL_UNLOCK;
5435
5436                     WriteVolumeHeader_r(&error, hd->back);
5437                     /* Ignore errors; catch them later */
5438
5439                     VOL_LOCK;
5440                 }
5441
5442                 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
5443                 hd->back->header = NULL;
5444
5445                 if (hd->diskstuff.inUse) {
5446                     VChangeState_r(hd->back, back_save);
5447                     VCancelReservation_r(hd->back);
5448                     VChangeState_r(vp, vp_save);
5449                 }
5450             } else {
5451                 volume_hdr_LRU.stats.attached++;
5452             }
5453             hd->back = vp;
5454             vp->header = hd;
5455             V_attachFlags(vp) |= VOL_HDR_ATTACHED;
5456         }
5457         volume_hdr_LRU.stats.free--;
5458         volume_hdr_LRU.stats.used++;
5459     }
5460     IncUInt64(&VStats.hdr_gets);
5461     IncUInt64(&vp->stats.hdr_gets);
5462     vp->stats.last_hdr_get = FT_ApproxTime();
5463     return old;
5464 }
5465 #else /* AFS_DEMAND_ATTACH_FS */
5466 /* Get a volume header from the LRU list; update the old one if necessary */
5467 /* Returns 1 if there was already a header, which is removed from the LRU list */
5468 static int
5469 GetVolumeHeader(register Volume * vp)
5470 {
5471     Error error;
5472     register struct volHeader *hd;
5473     int old;
5474     static int everLogged = 0;
5475
5476     old = (vp->header != NULL); /* old == volume already has a header */
5477
5478     if (programType != fileServer) {
5479         /* for volume utilities, we allocate volHeaders as needed */
5480         if (!vp->header) {
5481             hd = (struct volHeader *)calloc(1, sizeof(*vp->header));
5482             assert(hd != NULL);
5483             vp->header = hd;
5484             hd->back = vp;
5485         }
5486     } else {
5487         /* for the fileserver, we keep a volume header cache */
5488         if (old) {
5489             /* the header we previously dropped in the lru is
5490              * still available. pull it off the lru and return */
5491             hd = vp->header;
5492             queue_Remove(hd);
5493             assert(hd->back == vp);
5494         } else {
5495             /* we need to grab a new element off the LRU */
5496             if (queue_IsNotEmpty(&volume_hdr_LRU)) {
5497                 /* grab an element */
5498                 hd = queue_First(&volume_hdr_LRU, volHeader);
5499                 queue_Remove(hd);
5500             } else {
5501                 /* LRU is empty, so allocate a new volHeader 
5502                  * this is probably indicative of a leak, so let the user know */
5503                 hd = (struct volHeader *)calloc(1, sizeof(struct volHeader));
5504                 assert(hd != NULL);
5505                 if (!everLogged) {
5506                     Log("****Allocated more volume headers, probably leak****\n");
5507                     everLogged = 1;
5508                 }
5509             }
5510             if (hd->back) {
5511                 /* this header used to belong to someone else. 
5512                  * we'll need to check if the header needs to
5513                  * be sync'd out to disk */
5514
5515                 if (hd->diskstuff.inUse) {
5516                     WriteVolumeHeader_r(&error, hd->back);
5517                     /* Ignore errors; catch them later */
5518                 }
5519                 hd->back->header = NULL;
5520             }
5521             hd->back = vp;
5522             vp->header = hd;
5523         }
5524     }
5525     return old;
5526 }
5527 #endif /* AFS_DEMAND_ATTACH_FS */
5528
5529
5530 /* make sure a volume header is attached to
5531  * vp, and has the correct data loaded from
5532  * disk. */
5533 #ifdef AFS_DEMAND_ATTACH_FS
5534 /* caller MUST hold a ref count on vp */
5535 static void
5536 LoadVolumeHeader(Error * ec, Volume * vp)
5537 {
5538     VolState state_save;
5539     *ec = 0;
5540
5541     if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
5542         IncUInt64(&VStats.hdr_loads);
5543         state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
5544         VOL_UNLOCK;
5545
5546         ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
5547                    sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
5548                    VOLUMEINFOVERSION);
5549         IncUInt64(&vp->stats.hdr_loads);
5550
5551         VOL_LOCK;
5552         if (!*ec)
5553             V_attachFlags(vp) |= VOL_HDR_LOADED;
5554         VChangeState_r(vp, state_save);
5555     }
5556     if (*ec) {
5557         /* maintain (nUsers==0) => header in LRU invariant */
5558         ReleaseVolumeHeader(vp->header);
5559     }
5560 }
5561 #else /* AFS_DEMAND_ATTACH_FS */
5562 static void
5563 LoadVolumeHeader(Error * ec, Volume * vp)
5564 {
5565     *ec = 0;
5566     if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
5567         IncUInt64(&VStats.hdr_loads);
5568
5569         ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
5570                    sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
5571                    VOLUMEINFOVERSION);
5572     }
5573     if (*ec) {
5574         /* maintain (nUsers==0) => header in LRU invariant */
5575         ReleaseVolumeHeader(vp->header);
5576     }
5577 }
5578 #endif /* AFS_DEMAND_ATTACH_FS */
5579
5580 /* Put it at the top of the LRU chain */
5581 static void
5582 ReleaseVolumeHeader(register struct volHeader *hd)
5583 {
5584     if (programType != fileServer)
5585         return;
5586     if (!hd || queue_IsOnQueue(hd))     /* no header, or header already released */
5587         return;
5588     queue_Append(&volume_hdr_LRU, hd);
5589 #ifdef AFS_DEMAND_ATTACH_FS
5590     if (hd->back) {
5591         V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
5592     }
5593     volume_hdr_LRU.stats.free++;
5594     volume_hdr_LRU.stats.used--;
5595 #endif
5596 }
5597
5598 /* for fileserver, return header to LRU, and
5599  * invalidate it as a cache entry.
5600  *
5601  * for volume utilities, free the heap space */
5602 static void
5603 FreeVolumeHeader(register Volume * vp)
5604 {
5605     register struct volHeader *hd = vp->header;
5606     if (!hd)
5607         return;
5608     if (programType == fileServer) {
5609         ReleaseVolumeHeader(hd);
5610         hd->back = NULL;
5611     } else {
5612         free(hd);
5613     }
5614 #ifdef AFS_DEMAND_ATTACH_FS
5615     V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
5616     volume_hdr_LRU.stats.attached--;
5617 #endif
5618     vp->header = NULL;
5619 }
5620
5621
5622 /***************************************************/
5623 /* Volume Hash Table routines                      */
5624 /***************************************************/
5625
5626 int 
5627 VSetVolHashSize(int logsize)
5628 {
5629     /* 64 to 16384 hash buckets seems like a reasonable range */
5630     if ((logsize < 6 ) || (logsize > 14)) {
5631         return -1;
5632     }
5633     
5634     if (!VInit) {
5635         VolumeHashTable.Size = 1 << logsize;
5636         VolumeHashTable.Mask = VolumeHashTable.Size - 1;
5637     } else {
5638         /* we can't yet support runtime modification of this
5639          * parameter. we'll need a configuration rwlock to
5640          * make runtime modification feasible.... */
5641         return -1;
5642     }
5643     return 0;
5644 }
5645
5646 static void
5647 VInitVolumeHash(void)
5648 {
5649     register int i;
5650
5651     VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size, 
5652                                                            sizeof(VolumeHashChainHead));
5653     assert(VolumeHashTable.Table != NULL);
5654     
5655     for (i=0; i < VolumeHashTable.Size; i++) {
5656         queue_Init(&VolumeHashTable.Table[i]);
5657 #ifdef AFS_DEMAND_ATTACH_FS
5658         assert(pthread_cond_init(&VolumeHashTable.Table[i].chain_busy_cv, NULL) == 0);
5659 #endif /* AFS_DEMAND_ATTACH_FS */
5660     }
5661 }
5662
5663 /* for demand-attach, caller MUST hold a ref count on vp */
5664 static void
5665 AddVolumeToHashTable(register Volume * vp, int hashid)
5666 {
5667     VolumeHashChainHead * head;
5668
5669     if (queue_IsOnQueue(vp))
5670         return;
5671
5672     head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
5673
5674 #ifdef AFS_DEMAND_ATTACH_FS
5675     /* wait for the hash chain to become available */
5676     VHashWait_r(head);
5677
5678     V_attachFlags(vp) |= VOL_IN_HASH;
5679     vp->chainCacheCheck = ++head->cacheCheck;
5680 #endif /* AFS_DEMAND_ATTACH_FS */
5681
5682     head->len++;
5683     vp->hashid = hashid;
5684     queue_Append(head, vp);
5685     vp->vnodeHashOffset = VolumeHashOffset_r();
5686 }
5687
5688 /* for demand-attach, caller MUST hold a ref count on vp */
5689 static void
5690 DeleteVolumeFromHashTable(register Volume * vp)
5691 {
5692     VolumeHashChainHead * head;
5693
5694     if (!queue_IsOnQueue(vp))
5695         return;
5696
5697     head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
5698
5699 #ifdef AFS_DEMAND_ATTACH_FS
5700     /* wait for the hash chain to become available */
5701     VHashWait_r(head);
5702
5703     V_attachFlags(vp) &= ~(VOL_IN_HASH);
5704     head->cacheCheck++;
5705 #endif /* AFS_DEMAND_ATTACH_FS */
5706
5707     head->len--;
5708     queue_Remove(vp);
5709     /* do NOT reset hashid to zero, as the online
5710      * salvager package may need to know the volume id
5711      * after the volume is removed from the hash */
5712 }
5713
5714 /* - look up a volume id in the hash table
5715  * - occasionally rebalance hash chains
5716  * - update lookup statistics accordingly
5717  */
5718 /* the hint parameter allows us to short-circuit on
5719  * DEMAND_ATTACH_FS if the cacheChecks match between
5720  * the hash chain head and hint
5721  * caller MUST hold a refcount on hint */
5722 Volume *
5723 VLookupVolume_r(Error * ec, VolId volumeId, Volume * hint)
5724 {
5725     register int looks = 0;
5726     Volume * vp, *np, *pp;
5727     VolumeHashChainHead * head;
5728     *ec = 0;
5729
5730     head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
5731
5732 #ifdef AFS_DEMAND_ATTACH_FS
5733     /* wait for the hash chain to become available */
5734     VHashWait_r(head);
5735
5736     /* check to see if we can short circuit without walking the hash chain */
5737     if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
5738         IncUInt64(&hint->stats.hash_short_circuits);
5739         return hint;
5740     }
5741 #endif /* AFS_DEMAND_ATTACH_FS */
5742
5743     /* someday we need to either do per-chain locks, RWlocks,
5744      * or both for volhash access. 
5745      * (and move to a data structure with better cache locality) */
5746
5747     /* search the chain for this volume id */
5748     for(queue_Scan(head, vp, np, Volume)) {
5749         looks++;
5750         if ((vp->hashid == volumeId)) {
5751             break;
5752         }
5753     }
5754
5755     if (queue_IsEnd(head, vp)) {
5756         vp = NULL;
5757     }
5758
5759 #ifdef AFS_DEMAND_ATTACH_FS
5760     /* update hash chain statistics */
5761     {
5762         afs_uint64 lks;
5763         FillInt64(lks, 0, looks);
5764         AddUInt64(head->looks, lks, &head->looks);
5765         AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
5766         IncUInt64(&head->gets);
5767     }
5768
5769     if (vp) {
5770         afs_uint64 thresh;
5771         IncUInt64(&vp->stats.hash_lookups);
5772
5773         /* for demand attach fileserver, we permit occasional hash chain reordering
5774          * so that frequently looked up volumes move towards the head of the chain */
5775         pp = queue_Prev(vp, Volume);
5776         if (!queue_IsEnd(head, pp)) {
5777             FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
5778             AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
5779             if (GEInt64(vp->stats.hash_lookups, thresh)) {
5780                 VReorderHash_r(head, pp, vp);
5781             }
5782         }
5783
5784         /* update the short-circuit cache check */
5785         vp->chainCacheCheck = head->cacheCheck;
5786     }
5787 #endif /* AFS_DEMAND_ATTACH_FS */    
5788
5789     return vp;
5790 }
5791
5792 #ifdef AFS_DEMAND_ATTACH_FS
5793 /* perform volume hash chain reordering.
5794  *
5795  * advance a subchain beginning at vp ahead of
5796  * the adjacent subchain ending at pp */
5797 static void
5798 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
5799 {
5800     Volume *tp, *np, *lp;
5801     afs_uint64 move_thresh;
5802
5803     /* this should never be called if the chain is already busy, so
5804      * no need to wait for other exclusive chain ops to finish */
5805
5806     /* this is a rather heavy set of operations,
5807      * so let's set the chain busy flag and drop
5808      * the vol_glock */
5809     VHashBeginExclusive_r(head);
5810     VOL_UNLOCK;
5811
5812     /* scan forward in the chain from vp looking for the last element
5813      * in the chain we want to advance */
5814     FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
5815     AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
5816     for(queue_ScanFrom(head, vp, tp, np, Volume)) {
5817         if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
5818             break;
5819         }
5820     }
5821     lp = queue_Prev(tp, Volume);
5822
5823     /* scan backwards from pp to determine where to splice and
5824      * insert the subchain we're advancing */
5825     for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
5826         if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
5827             break;
5828         }
5829     }
5830     tp = queue_Next(tp, Volume);
5831
5832     /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
5833     queue_MoveChainBefore(tp,vp,lp);
5834
5835     VOL_LOCK;
5836     IncUInt64(&VStats.hash_reorders);
5837     head->cacheCheck++;
5838     IncUInt64(&head->reorders);
5839
5840     /* wake up any threads waiting for the hash chain */
5841     VHashEndExclusive_r(head);
5842 }
5843
5844
5845 /* demand-attach fs volume hash
5846  * asynchronous exclusive operations */
5847
5848 /* take exclusive control over the hash chain */
5849 static void
5850 VHashBeginExclusive_r(VolumeHashChainHead * head)
5851 {
5852     assert(head->busy == 0);
5853     head->busy = 1;
5854 }
5855
5856 /* relinquish exclusive control over the hash chain */
5857 static void
5858 VHashEndExclusive_r(VolumeHashChainHead * head)
5859 {
5860     assert(head->busy);
5861     head->busy = 0;
5862     assert(pthread_cond_broadcast(&head->chain_busy_cv) == 0);
5863 }
5864
5865 /* wait for another thread to finish its exclusive ops */
5866 static void
5867 VHashWait_r(VolumeHashChainHead * head)
5868 {
5869     while (head->busy) {
5870         assert(pthread_cond_wait(&head->chain_busy_cv, &vol_glock_mutex) == 0);
5871     }
5872 }
5873 #endif /* AFS_DEMAND_ATTACH_FS */
5874
5875
5876 /***************************************************/
5877 /* Volume by Partition List routines               */
5878 /***************************************************/
5879
5880 /*
5881  * demand attach fileserver adds a
5882  * linked list of volumes to each
5883  * partition object, thus allowing
5884  * for quick enumeration of all
5885  * volumes on a partition
5886  */
5887
5888 #ifdef AFS_DEMAND_ATTACH_FS
5889 static void
5890 AddVolumeToVByPList_r(Volume * vp)
5891 {
5892     if (queue_IsNotOnQueue(&vp->vol_list)) {
5893         queue_Append(&vp->partition->vol_list, &vp->vol_list);
5894         V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
5895         vp->partition->vol_list.len++;
5896     }
5897 }
5898
5899 static void
5900 DeleteVolumeFromVByPList_r(Volume * vp)
5901 {
5902     if (queue_IsOnQueue(&vp->vol_list)) {
5903         queue_Remove(&vp->vol_list);
5904         V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
5905         vp->partition->vol_list.len--;
5906     }
5907 }
5908
5909 /* take exclusive control over the list */
5910 static void
5911 VVByPListBeginExclusive_r(struct DiskPartition * dp)
5912 {
5913     assert(dp->vol_list.busy == 0);
5914     dp->vol_list.busy = 1;
5915 }
5916
5917 /* relinquish exclusive control over the list */
5918 static void
5919 VVByPListEndExclusive_r(struct DiskPartition * dp)
5920 {
5921     assert(dp->vol_list.busy);
5922     dp->vol_list.busy = 0;
5923     assert(pthread_cond_broadcast(&dp->vol_list.cv) == 0);
5924 }
5925
5926 /* wait for another thread to finish its exclusive ops */
5927 static void
5928 VVByPListWait_r(struct DiskPartition * dp)
5929 {
5930     while (dp->vol_list.busy) {
5931         assert(pthread_cond_wait(&dp->vol_list.cv, &vol_glock_mutex) == 0);
5932     }
5933 }
5934 #endif /* AFS_DEMAND_ATTACH_FS */
5935
5936 /***************************************************/
5937 /* Volume Cache Statistics routines                */
5938 /***************************************************/
5939
5940 void
5941 VPrintCacheStats_r(void)
5942 {
5943     afs_uint32 get_hi, get_lo, load_hi, load_lo;
5944     register struct VnodeClassInfo *vcp;
5945     vcp = &VnodeClassInfo[vLarge];
5946     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);
5947     vcp = &VnodeClassInfo[vSmall];
5948     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);
5949     SplitInt64(VStats.hdr_gets, get_hi, get_lo);
5950     SplitInt64(VStats.hdr_loads, load_hi, load_lo);
5951     Log("Volume header cache, %d entries, %d gets, %d replacements\n",
5952         VStats.hdr_cache_size, get_lo, load_lo);
5953 }
5954
5955 void
5956 VPrintCacheStats(void)
5957 {
5958     VOL_LOCK;
5959     VPrintCacheStats_r();
5960     VOL_UNLOCK;
5961 }
5962
5963 #ifdef AFS_DEMAND_ATTACH_FS
5964 static double
5965 UInt64ToDouble(afs_uint64 * x)
5966 {
5967     static double c32 = 4.0 * 1.073741824 * 1000000000.0;
5968     afs_uint32 h, l;
5969     SplitInt64(*x, h, l);
5970     return (((double)h) * c32) + ((double) l);
5971 }
5972
5973 static char *
5974 DoubleToPrintable(double x, char * buf, int len)
5975 {
5976     static double billion = 1000000000.0;
5977     afs_uint32 y[3];
5978
5979     y[0] = (afs_uint32) (x / (billion * billion));
5980     y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
5981     y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
5982
5983     if (y[0]) {
5984         snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
5985     } else if (y[1]) {
5986         snprintf(buf, len, "%d%09d", y[1], y[2]);
5987     } else {
5988         snprintf(buf, len, "%d", y[2]);
5989     }
5990     buf[len-1] = '\0';
5991     return buf;
5992 }
5993
5994 void
5995 VPrintExtendedCacheStats_r(int flags)
5996 {
5997     int i, j;
5998     struct stats {
5999         double min;
6000         double max;
6001         double sum;
6002         double avg;
6003     };
6004     struct stats looks, gets, reorders, len;
6005     struct stats ch_looks, ch_gets, ch_reorders;
6006     char pr_buf[4][32];
6007     VolumeHashChainHead *head;
6008     Volume *vp, *np;
6009
6010     /* zero out stats */
6011     memset(&looks, 0, sizeof(struct stats));
6012     memset(&gets, 0, sizeof(struct stats));
6013     memset(&reorders, 0, sizeof(struct stats));
6014     memset(&len, 0, sizeof(struct stats));
6015     memset(&ch_looks, 0, sizeof(struct stats));
6016     memset(&ch_gets, 0, sizeof(struct stats));
6017     memset(&ch_reorders, 0, sizeof(struct stats));
6018
6019     for (i = 0; i < VolumeHashTable.Size; i++) {
6020         head = &VolumeHashTable.Table[i];
6021
6022         VHashWait_r(head);
6023         VHashBeginExclusive_r(head);
6024         VOL_UNLOCK;
6025
6026         ch_looks.sum    = UInt64ToDouble(&head->looks);
6027         ch_gets.sum     = UInt64ToDouble(&head->gets);
6028         ch_reorders.sum = UInt64ToDouble(&head->reorders);
6029
6030         /* update global statistics */
6031         {
6032             looks.sum    += ch_looks.sum;
6033             gets.sum     += ch_gets.sum;
6034             reorders.sum += ch_reorders.sum;
6035             len.sum      += (double)head->len;
6036             
6037             if (i == 0) {
6038                 len.min      = (double) head->len;
6039                 len.max      = (double) head->len;
6040                 looks.min    = ch_looks.sum;
6041                 looks.max    = ch_looks.sum;
6042                 gets.min     = ch_gets.sum;
6043                 gets.max     = ch_gets.sum;
6044                 reorders.min = ch_reorders.sum;
6045                 reorders.max = ch_reorders.sum;
6046             } else {
6047                 if (((double)head->len) < len.min)
6048                     len.min = (double) head->len;
6049                 if (((double)head->len) > len.max)
6050                     len.max = (double) head->len;
6051                 if (ch_looks.sum < looks.min)
6052                     looks.min = ch_looks.sum;
6053                 else if (ch_looks.sum > looks.max)
6054                     looks.max = ch_looks.sum;
6055                 if (ch_gets.sum < gets.min)
6056                     gets.min = ch_gets.sum;
6057                 else if (ch_gets.sum > gets.max)
6058                     gets.max = ch_gets.sum;
6059                 if (ch_reorders.sum < reorders.min)
6060                     reorders.min = ch_reorders.sum;
6061                 else if (ch_reorders.sum > reorders.max)
6062                     reorders.max = ch_reorders.sum;
6063             }
6064         }
6065
6066         if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
6067             /* compute detailed per-chain stats */
6068             struct stats hdr_loads, hdr_gets;
6069             double v_looks, v_loads, v_gets;
6070
6071             /* initialize stats with data from first element in chain */
6072             vp = queue_First(head, Volume);
6073             v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
6074             v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
6075             v_gets  = UInt64ToDouble(&vp->stats.hdr_gets);
6076             ch_gets.min = ch_gets.max = v_looks;
6077             hdr_loads.min = hdr_loads.max = v_loads;
6078             hdr_gets.min = hdr_gets.max = v_gets;
6079             hdr_loads.sum = hdr_gets.sum = 0;
6080
6081             vp = queue_Next(vp, Volume);
6082
6083             /* pull in stats from remaining elements in chain */
6084             for (queue_ScanFrom(head, vp, vp, np, Volume)) {
6085                 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
6086                 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
6087                 v_gets  = UInt64ToDouble(&vp->stats.hdr_gets);
6088
6089                 hdr_loads.sum += v_loads;
6090                 hdr_gets.sum += v_gets;
6091
6092                 if (v_looks < ch_gets.min)
6093                     ch_gets.min = v_looks;
6094                 else if (v_looks > ch_gets.max)
6095                     ch_gets.max = v_looks;
6096
6097                 if (v_loads < hdr_loads.min)
6098                     hdr_loads.min = v_loads;
6099                 else if (v_loads > hdr_loads.max)
6100                     hdr_loads.max = v_loads;
6101
6102                 if (v_gets < hdr_gets.min)
6103                     hdr_gets.min = v_gets;
6104                 else if (v_gets > hdr_gets.max)
6105                     hdr_gets.max = v_gets;
6106             }
6107
6108             /* compute per-chain averages */
6109             ch_gets.avg = ch_gets.sum / ((double)head->len);
6110             hdr_loads.avg = hdr_loads.sum / ((double)head->len);
6111             hdr_gets.avg = hdr_gets.sum / ((double)head->len);
6112
6113             /* dump per-chain stats */
6114             Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
6115                 i, head->len, 
6116                 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
6117                 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
6118             Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
6119                 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
6120                 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
6121                 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
6122                 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
6123             Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
6124                 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
6125                 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
6126                 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
6127                 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
6128             Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
6129                 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
6130                 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
6131                 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
6132                 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
6133         } else if (flags & VOL_STATS_PER_CHAIN) {
6134             /* dump simple per-chain stats */
6135             Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
6136                 i, head->len, 
6137                 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
6138                 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
6139                 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
6140         }
6141
6142         VOL_LOCK;
6143         VHashEndExclusive_r(head);
6144     }
6145
6146     VOL_UNLOCK;
6147
6148     /* compute global averages */
6149     len.avg      = len.sum      / ((double)VolumeHashTable.Size);
6150     looks.avg    = looks.sum    / ((double)VolumeHashTable.Size);
6151     gets.avg     = gets.sum     / ((double)VolumeHashTable.Size);
6152     reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
6153
6154     /* dump global stats */
6155     Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
6156     Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
6157         DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
6158         DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
6159         DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
6160         DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
6161     Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
6162         DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
6163         DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
6164         DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
6165         DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
6166     Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
6167         DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
6168         DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
6169         DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
6170         DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
6171     Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
6172         DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
6173         DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
6174         DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
6175         DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
6176
6177     /* print extended disk related statistics */
6178     {
6179         struct DiskPartition * diskP;
6180         afs_uint32 vol_count[VOLMAXPARTS+1];
6181         byte part_exists[VOLMAXPARTS+1];
6182         Device id;
6183         int i;
6184
6185         memset(vol_count, 0, sizeof(vol_count));
6186         memset(part_exists, 0, sizeof(part_exists));
6187
6188         VOL_LOCK;
6189
6190         for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
6191             id = diskP->device;
6192             vol_count[id] = diskP->vol_list.len;
6193             part_exists[id] = 1;
6194         }
6195
6196         VOL_UNLOCK;
6197         for (i = 0; i <= VOLMAXPARTS; i++) {
6198             if (part_exists[i]) {
6199                 diskP = VGetPartitionById_r(i, 0);
6200                 if (diskP) {
6201                     Log("Partition %s has %d online volumes\n", 
6202                         VPartitionPath(diskP), diskP->vol_list.len);
6203                 }
6204             }
6205         }
6206         VOL_LOCK;
6207     }
6208
6209 }
6210
6211 void
6212 VPrintExtendedCacheStats(int flags)
6213 {
6214     VOL_LOCK;
6215     VPrintExtendedCacheStats_r(flags);
6216     VOL_UNLOCK;
6217 }
6218 #endif /* AFS_DEMAND_ATTACH_FS */