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