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