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