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