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