2 * Copyright 2000, International Business Machines Corporation and others.
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
9 * Portions Copyright (c) 2005-2008 Sine Nomine Associates
12 /* 1/1/89: NB: this stuff is all going to be replaced. Don't take it too seriously */
17 Institution: The Information Technology Center, Carnegie-Mellon University
21 #include <afsconfig.h>
22 #include <afs/param.h>
26 #include <afs/afsint.h>
30 #include <sys/param.h>
31 #if !defined(AFS_SGI_ENV)
34 #else /* AFS_OSF_ENV */
35 #ifdef AFS_VFSINCL_ENV
38 #include <sys/fs/ufs_fs.h>
40 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
41 #include <ufs/ufs/dinode.h>
42 #include <ufs/ffs/fs.h>
47 #else /* AFS_VFSINCL_ENV */
48 #if !defined(AFS_AIX_ENV) && !defined(AFS_LINUX20_ENV) && !defined(AFS_XBSD_ENV)
51 #endif /* AFS_VFSINCL_ENV */
52 #endif /* AFS_OSF_ENV */
53 #endif /* AFS_SGI_ENV */
54 #endif /* AFS_NT40_ENV */
72 #if defined(AFS_SUN_ENV) || defined(AFS_SUN5_ENV)
74 #include <sys/mnttab.h>
75 #include <sys/mntent.h>
81 #if defined(AFS_SGI_ENV)
86 #ifndef AFS_LINUX20_ENV
87 #include <fstab.h> /* Need to find in libc 5, present in libc 6 */
90 #endif /* AFS_SGI_ENV */
92 #endif /* AFS_HPUX_ENV */
96 #include <netinet/in.h>
100 #include <sys/time.h>
101 #endif /* ITIMER_REAL */
102 #endif /* AFS_NT40_ENV */
103 #if defined(AFS_SUN5_ENV) || defined(AFS_NT40_ENV) || defined(AFS_LINUX20_ENV)
110 #include <afs/errors.h>
113 #include <afs/afssyscalls.h>
115 #include <afs/afsutil.h>
119 #include "daemon_com.h"
121 #include "salvsync.h"
124 #include "partition.h"
125 #include "volume_inline.h"
127 #include "afs/afs_assert.h"
134 #if !defined(offsetof)
139 #define afs_stat stat64
140 #define afs_fstat fstat64
141 #define afs_open open64
142 #else /* !O_LARGEFILE */
143 #define afs_stat stat
144 #define afs_fstat fstat
145 #define afs_open open
146 #endif /* !O_LARGEFILE */
148 #ifdef AFS_PTHREAD_ENV
149 pthread_mutex_t vol_glock_mutex;
150 pthread_mutex_t vol_trans_mutex;
151 pthread_cond_t vol_put_volume_cond;
152 pthread_cond_t vol_sleep_cond;
153 pthread_cond_t vol_init_attach_cond;
154 pthread_cond_t vol_vinit_cond;
155 int vol_attach_threads = 1;
156 #endif /* AFS_PTHREAD_ENV */
158 /* start-time configurable I/O parameters */
159 ih_init_params vol_io_params;
161 #ifdef AFS_DEMAND_ATTACH_FS
162 pthread_mutex_t vol_salvsync_mutex;
165 * Set this to 1 to disallow SALVSYNC communication in all threads; used
166 * during shutdown, since the salvageserver may have gone away.
168 static volatile sig_atomic_t vol_disallow_salvsync = 0;
169 #endif /* AFS_DEMAND_ATTACH_FS */
172 extern void *calloc(), *realloc();
175 /* Forward declarations */
176 static Volume *attach2(Error * ec, VolId volumeId, char *path,
177 struct DiskPartition64 *partp, Volume * vp,
178 int isbusy, int mode, int *acheckedOut);
179 static void ReallyFreeVolume(Volume * vp);
180 #ifdef AFS_DEMAND_ATTACH_FS
181 static void FreeVolume(Volume * vp);
182 #else /* !AFS_DEMAND_ATTACH_FS */
183 #define FreeVolume(vp) ReallyFreeVolume(vp)
184 static void VScanUpdateList(void);
185 #endif /* !AFS_DEMAND_ATTACH_FS */
186 static void VInitVolumeHeaderCache(afs_uint32 howMany);
187 static int GetVolumeHeader(Volume * vp);
188 static void ReleaseVolumeHeader(struct volHeader *hd);
189 static void FreeVolumeHeader(Volume * vp);
190 static void AddVolumeToHashTable(Volume * vp, int hashid);
191 static void DeleteVolumeFromHashTable(Volume * vp);
193 static int VHold(Volume * vp);
195 static int VHold_r(Volume * vp);
196 static void VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class);
197 static void VReleaseVolumeHandles_r(Volume * vp);
198 static void VCloseVolumeHandles_r(Volume * vp);
199 static void LoadVolumeHeader(Error * ec, Volume * vp);
200 static int VCheckOffline(Volume * vp);
201 static int VCheckDetach(Volume * vp);
202 static Volume * GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint, int flags);
204 int LogLevel; /* Vice loglevel--not defined as extern so that it will be
205 * defined when not linked with vice, XXXX */
206 ProgramType programType; /* The type of program using the package */
207 static VolumePackageOptions vol_opts;
209 /* extended volume package statistics */
212 #ifdef VOL_LOCK_DEBUG
213 pthread_t vol_glock_holder = 0;
217 #define VOLUME_BITMAP_GROWSIZE 16 /* bytes, => 128vnodes */
218 /* Must be a multiple of 4 (1 word) !! */
220 /* this parameter needs to be tunable at runtime.
221 * 128 was really inadequate for largish servers -- at 16384 volumes this
222 * puts average chain length at 128, thus an average 65 deref's to find a volptr.
223 * talk about bad spatial locality...
225 * an AVL or splay tree might work a lot better, but we'll just increase
226 * the default hash table size for now
228 #define DEFAULT_VOLUME_HASH_SIZE 256 /* Must be a power of 2!! */
229 #define DEFAULT_VOLUME_HASH_MASK (DEFAULT_VOLUME_HASH_SIZE-1)
230 #define VOLUME_HASH(volumeId) (volumeId&(VolumeHashTable.Mask))
233 * turn volume hash chains into partially ordered lists.
234 * when the threshold is exceeded between two adjacent elements,
235 * perform a chain rebalancing operation.
237 * keep the threshold high in order to keep cache line invalidates
238 * low "enough" on SMPs
240 #define VOLUME_HASH_REORDER_THRESHOLD 200
243 * when possible, don't just reorder single elements, but reorder
244 * entire chains of elements at once. a chain of elements that
245 * exceed the element previous to the pivot by at least CHAIN_THRESH
246 * accesses are moved in front of the chain whose elements have at
247 * least CHAIN_THRESH less accesses than the pivot element
249 #define VOLUME_HASH_REORDER_CHAIN_THRESH (VOLUME_HASH_REORDER_THRESHOLD / 2)
251 #include "rx/rx_queue.h"
254 VolumeHashTable_t VolumeHashTable = {
255 DEFAULT_VOLUME_HASH_SIZE,
256 DEFAULT_VOLUME_HASH_MASK,
261 static void VInitVolumeHash(void);
265 /* This macro is used where an ffs() call does not exist. Was in util/ffs.c */
269 afs_int32 ffs_tmp = x;
273 for (ffs_i = 1;; ffs_i++) {
280 #endif /* !AFS_HAVE_FFS */
282 #ifdef AFS_PTHREAD_ENV
284 * disk partition queue element
286 typedef struct diskpartition_queue_t {
287 struct rx_queue queue; /**< queue header */
288 struct DiskPartition64 *diskP; /**< disk partition table entry */
289 } diskpartition_queue_t;
291 #ifndef AFS_DEMAND_ATTACH_FS
293 typedef struct vinitvolumepackage_thread_t {
294 struct rx_queue queue;
295 pthread_cond_t thread_done_cv;
296 int n_threads_complete;
297 } vinitvolumepackage_thread_t;
298 static void * VInitVolumePackageThread(void * args);
300 #else /* !AFS_DEMAND_ATTTACH_FS */
301 #define VINIT_BATCH_MAX_SIZE 512
304 * disk partition work queue
306 struct partition_queue {
307 struct rx_queue head; /**< diskpartition_queue_t queue */
308 pthread_mutex_t mutex;
313 * volumes parameters for preattach
315 struct volume_init_batch {
316 struct rx_queue queue; /**< queue header */
317 int thread; /**< posting worker thread */
318 int last; /**< indicates thread is done */
319 int size; /**< number of volume ids in batch */
320 Volume *batch[VINIT_BATCH_MAX_SIZE]; /**< volumes ids to preattach */
324 * volume parameters work queue
326 struct volume_init_queue {
327 struct rx_queue head; /**< volume_init_batch queue */
328 pthread_mutex_t mutex;
333 * volume init worker thread parameters
335 struct vinitvolumepackage_thread_param {
336 int nthreads; /**< total number of worker threads */
337 int thread; /**< thread number for this worker thread */
338 struct partition_queue *pq; /**< queue partitions to scan */
339 struct volume_init_queue *vq; /**< queue of volume to preattach */
342 static void *VInitVolumePackageThread(void *args);
343 static struct DiskPartition64 *VInitNextPartition(struct partition_queue *pq);
344 static VolId VInitNextVolumeId(DIR *dirp);
345 static int VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq);
347 #endif /* !AFS_DEMAND_ATTACH_FS */
348 #endif /* AFS_PTHREAD_ENV */
350 #ifndef AFS_DEMAND_ATTACH_FS
351 static int VAttachVolumesByPartition(struct DiskPartition64 *diskP,
352 int * nAttached, int * nUnattached);
353 #endif /* AFS_DEMAND_ATTACH_FS */
356 #ifdef AFS_DEMAND_ATTACH_FS
357 /* demand attach fileserver extensions */
360 * in the future we will support serialization of VLRU state into the fs_state
363 * these structures are the beginning of that effort
365 struct VLRU_DiskHeader {
366 struct versionStamp stamp; /* magic and structure version number */
367 afs_uint32 mtime; /* time of dump to disk */
368 afs_uint32 num_records; /* number of VLRU_DiskEntry records */
371 struct VLRU_DiskEntry {
372 afs_uint32 vid; /* volume ID */
373 afs_uint32 idx; /* generation */
374 afs_uint32 last_get; /* timestamp of last get */
377 struct VLRU_StartupQueue {
378 struct VLRU_DiskEntry * entry;
383 typedef struct vshutdown_thread_t {
385 pthread_mutex_t lock;
387 pthread_cond_t master_cv;
389 int n_threads_complete;
391 int schedule_version;
394 byte n_parts_done_pass;
395 byte part_thread_target[VOLMAXPARTS+1];
396 byte part_done_pass[VOLMAXPARTS+1];
397 struct rx_queue * part_pass_head[VOLMAXPARTS+1];
398 int stats[4][VOLMAXPARTS+1];
399 } vshutdown_thread_t;
400 static void * VShutdownThread(void * args);
403 static Volume * VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode);
404 static int VCheckFree(Volume * vp);
407 static void AddVolumeToVByPList_r(Volume * vp);
408 static void DeleteVolumeFromVByPList_r(Volume * vp);
409 static void VVByPListBeginExclusive_r(struct DiskPartition64 * dp);
410 static void VVByPListEndExclusive_r(struct DiskPartition64 * dp);
411 static void VVByPListWait_r(struct DiskPartition64 * dp);
413 /* online salvager */
414 static int VCheckSalvage(Volume * vp);
415 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
416 static int VScheduleSalvage_r(Volume * vp);
419 /* Volume hash table */
420 static void VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp);
421 static void VHashBeginExclusive_r(VolumeHashChainHead * head);
422 static void VHashEndExclusive_r(VolumeHashChainHead * head);
423 static void VHashWait_r(VolumeHashChainHead * head);
426 static int ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass);
427 static int ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
428 struct rx_queue ** idx);
429 static void ShutdownController(vshutdown_thread_t * params);
430 static void ShutdownCreateSchedule(vshutdown_thread_t * params);
433 static void VLRU_ComputeConstants(void);
434 static void VInitVLRU(void);
435 static void VLRU_Init_Node_r(Volume * vp);
436 static void VLRU_Add_r(Volume * vp);
437 static void VLRU_Delete_r(Volume * vp);
438 static void VLRU_UpdateAccess_r(Volume * vp);
439 static void * VLRU_ScannerThread(void * args);
440 static void VLRU_Scan_r(int idx);
441 static void VLRU_Promote_r(int idx);
442 static void VLRU_Demote_r(int idx);
443 static void VLRU_SwitchQueues(Volume * vp, int new_idx, int append);
446 static int VCheckSoftDetach(Volume * vp, afs_uint32 thresh);
447 static int VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh);
448 static int VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh);
451 pthread_key_t VThread_key;
452 VThreadOptions_t VThread_defaults = {
453 0 /**< allow salvsync */
455 #endif /* AFS_DEMAND_ATTACH_FS */
458 struct Lock vol_listLock; /* Lock obtained when listing volumes:
459 * prevents a volume from being missed
460 * if the volume is attached during a
464 /* Common message used when the volume goes off line */
465 char *VSalvageMessage =
466 "Files in this volume are currently unavailable; call operations";
468 int VInit; /* 0 - uninitialized,
469 * 1 - initialized but not all volumes have been attached,
470 * 2 - initialized and all volumes have been attached,
471 * 3 - initialized, all volumes have been attached, and
472 * VConnectFS() has completed. */
474 static int vinit_attach_abort = 0;
476 bit32 VolumeCacheCheck; /* Incremented everytime a volume goes on line--
477 * used to stamp volume headers and in-core
478 * vnodes. When the volume goes on-line the
479 * vnode will be invalidated
480 * access only with VOL_LOCK held */
485 /***************************************************/
486 /* Startup routines */
487 /***************************************************/
489 #if defined(FAST_RESTART) && defined(AFS_DEMAND_ATTACH_FS)
490 # error FAST_RESTART and DAFS are incompatible. For the DAFS equivalent \
491 of FAST_RESTART, use the -unsafe-nosalvage fileserver argument
495 * assign default values to a VolumePackageOptions struct.
497 * Always call this on a VolumePackageOptions struct first, then set any
498 * specific options you want, then call VInitVolumePackage2.
500 * @param[in] pt caller's program type
501 * @param[out] opts volume package options
504 VOptDefaults(ProgramType pt, VolumePackageOptions *opts)
506 opts->nLargeVnodes = opts->nSmallVnodes = 5;
509 opts->canScheduleSalvage = 0;
510 opts->canUseFSSYNC = 0;
511 opts->canUseSALVSYNC = 0;
514 opts->unsafe_attach = 1;
515 #else /* !FAST_RESTART */
516 opts->unsafe_attach = 0;
517 #endif /* !FAST_RESTART */
521 opts->canScheduleSalvage = 1;
522 opts->canUseSALVSYNC = 1;
526 opts->canUseFSSYNC = 1;
530 opts->nLargeVnodes = 0;
531 opts->nSmallVnodes = 0;
533 opts->canScheduleSalvage = 1;
534 opts->canUseFSSYNC = 1;
544 * Set VInit to a certain value, and signal waiters.
546 * @param[in] value the value to set VInit to
551 VSetVInit_r(int value)
554 CV_BROADCAST(&vol_vinit_cond);
558 VInitVolumePackage2(ProgramType pt, VolumePackageOptions * opts)
560 int errors = 0; /* Number of errors while finding vice partitions. */
565 memset(&VStats, 0, sizeof(VStats));
566 VStats.hdr_cache_size = 200;
568 VInitPartitionPackage();
570 #ifdef AFS_DEMAND_ATTACH_FS
571 if (programType == fileServer) {
574 VLRU_SetOptions(VLRU_SET_ENABLED, 0);
576 osi_Assert(pthread_key_create(&VThread_key, NULL) == 0);
579 MUTEX_INIT(&vol_glock_mutex, "vol glock", MUTEX_DEFAULT, 0);
580 MUTEX_INIT(&vol_trans_mutex, "vol trans", MUTEX_DEFAULT, 0);
581 CV_INIT(&vol_put_volume_cond, "vol put", CV_DEFAULT, 0);
582 CV_INIT(&vol_sleep_cond, "vol sleep", CV_DEFAULT, 0);
583 CV_INIT(&vol_init_attach_cond, "vol init attach", CV_DEFAULT, 0);
584 CV_INIT(&vol_vinit_cond, "vol init", CV_DEFAULT, 0);
585 #ifndef AFS_PTHREAD_ENV
587 #endif /* AFS_PTHREAD_ENV */
588 Lock_Init(&vol_listLock);
590 srandom(time(0)); /* For VGetVolumeInfo */
592 #ifdef AFS_DEMAND_ATTACH_FS
593 MUTEX_INIT(&vol_salvsync_mutex, "salvsync", MUTEX_DEFAULT, 0);
594 #endif /* AFS_DEMAND_ATTACH_FS */
596 /* Ok, we have done enough initialization that fileserver can
597 * start accepting calls, even though the volumes may not be
598 * available just yet.
602 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_SERVER)
603 if (programType == salvageServer) {
606 #endif /* AFS_DEMAND_ATTACH_FS */
607 #ifdef FSSYNC_BUILD_SERVER
608 if (programType == fileServer) {
612 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_CLIENT)
613 if (VCanUseSALVSYNC()) {
614 /* establish a connection to the salvager at this point */
615 osi_Assert(VConnectSALV() != 0);
617 #endif /* AFS_DEMAND_ATTACH_FS */
619 if (opts->volcache > VStats.hdr_cache_size)
620 VStats.hdr_cache_size = opts->volcache;
621 VInitVolumeHeaderCache(VStats.hdr_cache_size);
623 VInitVnodes(vLarge, opts->nLargeVnodes);
624 VInitVnodes(vSmall, opts->nSmallVnodes);
627 errors = VAttachPartitions();
631 if (programType != fileServer) {
632 errors = VInitAttachVolumes(programType);
638 #ifdef FSSYNC_BUILD_CLIENT
639 if (VCanUseFSSYNC()) {
641 #ifdef AFS_DEMAND_ATTACH_FS
642 if (programType == salvageServer) {
643 Log("Unable to connect to file server; aborted\n");
646 #endif /* AFS_DEMAND_ATTACH_FS */
647 Log("Unable to connect to file server; will retry at need\n");
650 #endif /* FSSYNC_BUILD_CLIENT */
655 #if !defined(AFS_PTHREAD_ENV)
657 * Attach volumes in vice partitions
659 * @param[in] pt calling program type
662 * @note This is the original, non-threaded version of attach parititions.
664 * @post VInit state is 2
667 VInitAttachVolumes(ProgramType pt)
669 osi_Assert(VInit==1);
670 if (pt == fileServer) {
671 struct DiskPartition64 *diskP;
672 /* Attach all the volumes in this partition */
673 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
674 int nAttached = 0, nUnattached = 0;
675 osi_Assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
679 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
680 LWP_NoYieldSignal(VInitAttachVolumes);
684 #endif /* !AFS_PTHREAD_ENV */
686 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_DEMAND_ATTACH_FS)
688 * Attach volumes in vice partitions
690 * @param[in] pt calling program type
693 * @note Threaded version of attach parititions.
695 * @post VInit state is 2
698 VInitAttachVolumes(ProgramType pt)
700 osi_Assert(VInit==1);
701 if (pt == fileServer) {
702 struct DiskPartition64 *diskP;
703 struct vinitvolumepackage_thread_t params;
704 struct diskpartition_queue_t * dpq;
705 int i, threads, parts;
707 pthread_attr_t attrs;
709 CV_INIT(¶ms.thread_done_cv, "thread done", CV_DEFAULT, 0);
711 params.n_threads_complete = 0;
713 /* create partition work queue */
714 for (parts=0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
715 dpq = (diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
716 osi_Assert(dpq != NULL);
718 queue_Append(¶ms,dpq);
721 threads = MIN(parts, vol_attach_threads);
724 /* spawn off a bunch of initialization threads */
725 osi_Assert(pthread_attr_init(&attrs) == 0);
726 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
728 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
729 Log("VInitVolumePackage: using %d threads to attach volumes on %d partitions\n",
733 for (i=0; i < threads; i++) {
736 osi_Assert(pthread_create
737 (&tid, &attrs, &VInitVolumePackageThread,
739 AFS_SIGSET_RESTORE();
742 while(params.n_threads_complete < threads) {
743 VOL_CV_WAIT(¶ms.thread_done_cv);
747 osi_Assert(pthread_attr_destroy(&attrs) == 0);
749 /* if we're only going to run one init thread, don't bother creating
751 Log("VInitVolumePackage: beginning single-threaded fileserver startup\n");
752 Log("VInitVolumePackage: using 1 thread to attach volumes on %d partition(s)\n",
755 VInitVolumePackageThread(¶ms);
758 CV_DESTROY(¶ms.thread_done_cv);
761 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
762 CV_BROADCAST(&vol_init_attach_cond);
768 VInitVolumePackageThread(void * args) {
770 struct DiskPartition64 *diskP;
771 struct vinitvolumepackage_thread_t * params;
772 struct diskpartition_queue_t * dpq;
774 params = (vinitvolumepackage_thread_t *) args;
778 /* Attach all the volumes in this partition */
779 while (queue_IsNotEmpty(params)) {
780 int nAttached = 0, nUnattached = 0;
782 if (vinit_attach_abort) {
783 Log("Aborting initialization\n");
787 dpq = queue_First(params,diskpartition_queue_t);
793 osi_Assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
799 params->n_threads_complete++;
800 CV_SIGNAL(¶ms->thread_done_cv);
804 #endif /* AFS_PTHREAD_ENV && !AFS_DEMAND_ATTACH_FS */
806 #if defined(AFS_DEMAND_ATTACH_FS)
808 * Attach volumes in vice partitions
810 * @param[in] pt calling program type
813 * @note Threaded version of attach partitions.
815 * @post VInit state is 2
818 VInitAttachVolumes(ProgramType pt)
820 osi_Assert(VInit==1);
821 if (pt == fileServer) {
823 struct DiskPartition64 *diskP;
824 struct partition_queue pq;
825 struct volume_init_queue vq;
827 int i, threads, parts;
829 pthread_attr_t attrs;
831 /* create partition work queue */
833 CV_INIT(&(pq.cv), "partq", CV_DEFAULT, 0);
834 MUTEX_INIT(&(pq.mutex), "partq", MUTEX_DEFAULT, 0);
835 for (parts = 0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
836 struct diskpartition_queue_t *dp;
837 dp = (struct diskpartition_queue_t*)malloc(sizeof(struct diskpartition_queue_t));
838 osi_Assert(dp != NULL);
840 queue_Append(&pq, dp);
843 /* number of worker threads; at least one, not to exceed the number of partitions */
844 threads = MIN(parts, vol_attach_threads);
846 /* create volume work queue */
848 CV_INIT(&(vq.cv), "volq", CV_DEFAULT, 0);
849 MUTEX_INIT(&(vq.mutex), "volq", MUTEX_DEFAULT, 0);
851 osi_Assert(pthread_attr_init(&attrs) == 0);
852 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
854 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
855 Log("VInitVolumePackage: using %d threads to pre-attach volumes on %d partitions\n",
858 /* create threads to scan disk partitions. */
859 for (i=0; i < threads; i++) {
860 struct vinitvolumepackage_thread_param *params;
863 params = (struct vinitvolumepackage_thread_param *)malloc(sizeof(struct vinitvolumepackage_thread_param));
867 params->nthreads = threads;
868 params->thread = i+1;
871 osi_Assert(pthread_create (&tid, &attrs, &VInitVolumePackageThread, (void*)params) == 0);
872 AFS_SIGSET_RESTORE();
875 VInitPreAttachVolumes(threads, &vq);
877 osi_Assert(pthread_attr_destroy(&attrs) == 0);
879 MUTEX_DESTROY(&pq.mutex);
881 MUTEX_DESTROY(&vq.mutex);
885 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
886 CV_BROADCAST(&vol_init_attach_cond);
893 * Volume package initialization worker thread. Scan partitions for volume
894 * header files. Gather batches of volume ids and dispatch them to
895 * the main thread to be preattached. The volume preattachement is done
896 * in the main thread to avoid global volume lock contention.
899 VInitVolumePackageThread(void *args)
901 struct vinitvolumepackage_thread_param *params;
902 struct DiskPartition64 *partition;
903 struct partition_queue *pq;
904 struct volume_init_queue *vq;
905 struct volume_init_batch *vb;
908 params = (struct vinitvolumepackage_thread_param *)args;
914 vb = (struct volume_init_batch*)malloc(sizeof(struct volume_init_batch));
916 vb->thread = params->thread;
920 Log("Scanning partitions on thread %d of %d\n", params->thread, params->nthreads);
921 while((partition = VInitNextPartition(pq))) {
925 Log("Partition %s: pre-attaching volumes\n", partition->name);
926 dirp = opendir(VPartitionPath(partition));
928 Log("opendir on Partition %s failed, errno=%d!\n", partition->name, errno);
931 while ((vid = VInitNextVolumeId(dirp))) {
932 Volume *vp = (Volume*)malloc(sizeof(Volume));
934 memset(vp, 0, sizeof(Volume));
935 vp->device = partition->device;
936 vp->partition = partition;
938 queue_Init(&vp->vnode_list);
939 CV_INIT(&V_attachCV(vp), "partattach", CV_DEFAULT, 0);
941 vb->batch[vb->size++] = vp;
942 if (vb->size == VINIT_BATCH_MAX_SIZE) {
943 MUTEX_ENTER(&vq->mutex);
944 queue_Append(vq, vb);
945 CV_BROADCAST(&vq->cv);
946 MUTEX_EXIT(&vq->mutex);
948 vb = (struct volume_init_batch*)malloc(sizeof(struct volume_init_batch));
950 vb->thread = params->thread;
959 MUTEX_ENTER(&vq->mutex);
960 queue_Append(vq, vb);
961 CV_BROADCAST(&vq->cv);
962 MUTEX_EXIT(&vq->mutex);
964 Log("Partition scan thread %d of %d ended\n", params->thread, params->nthreads);
970 * Read next element from the pre-populated partition list.
972 static struct DiskPartition64*
973 VInitNextPartition(struct partition_queue *pq)
975 struct DiskPartition64 *partition;
976 struct diskpartition_queue_t *dp; /* queue element */
978 if (vinit_attach_abort) {
979 Log("Aborting volume preattach thread.\n");
983 /* get next partition to scan */
984 MUTEX_ENTER(&pq->mutex);
985 if (queue_IsEmpty(pq)) {
986 MUTEX_EXIT(&pq->mutex);
989 dp = queue_First(pq, diskpartition_queue_t);
991 MUTEX_EXIT(&pq->mutex);
994 osi_Assert(dp->diskP);
996 partition = dp->diskP;
1002 * Find next volume id on the partition.
1005 VInitNextVolumeId(DIR *dirp)
1011 while((d = readdir(dirp))) {
1012 if (vinit_attach_abort) {
1013 Log("Aborting volume preattach thread.\n");
1016 ext = strrchr(d->d_name, '.');
1017 if (d->d_name[0] == 'V' && ext && strcmp(ext, VHDREXT) == 0) {
1018 vid = VolumeNumber(d->d_name);
1022 Log("Warning: bogus volume header file: %s\n", d->d_name);
1029 * Preattach volumes in batches to avoid lock contention.
1032 VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq)
1034 struct volume_init_batch *vb;
1038 /* dequeue next volume */
1039 MUTEX_ENTER(&vq->mutex);
1040 if (queue_IsEmpty(vq)) {
1041 CV_WAIT(&vq->cv, &vq->mutex);
1043 vb = queue_First(vq, volume_init_batch);
1045 MUTEX_EXIT(&vq->mutex);
1049 for (i = 0; i<vb->size; i++) {
1055 dup = VLookupVolume_r(&ec, vp->hashid, NULL);
1057 Log("Error looking up volume, code=%d\n", ec);
1060 Log("Warning: Duplicate volume id %d detected.\n", vp->hashid);
1063 /* put pre-attached volume onto the hash table
1064 * and bring it up to the pre-attached state */
1065 AddVolumeToHashTable(vp, vp->hashid);
1066 AddVolumeToVByPList_r(vp);
1067 VLRU_Init_Node_r(vp);
1068 VChangeState_r(vp, VOL_STATE_PREATTACHED);
1081 #endif /* AFS_DEMAND_ATTACH_FS */
1083 #if !defined(AFS_DEMAND_ATTACH_FS)
1085 * attach all volumes on a given disk partition
1088 VAttachVolumesByPartition(struct DiskPartition64 *diskP, int * nAttached, int * nUnattached)
1094 Log("Partition %s: attaching volumes\n", diskP->name);
1095 dirp = opendir(VPartitionPath(diskP));
1097 Log("opendir on Partition %s failed!\n", diskP->name);
1101 while ((dp = readdir(dirp))) {
1103 p = strrchr(dp->d_name, '.');
1105 if (vinit_attach_abort) {
1106 Log("Partition %s: abort attach volumes\n", diskP->name);
1110 if (p != NULL && strcmp(p, VHDREXT) == 0) {
1113 vp = VAttachVolumeByName(&error, diskP->name, dp->d_name,
1115 (*(vp ? nAttached : nUnattached))++;
1116 if (error == VOFFLINE)
1117 Log("Volume %d stays offline (/vice/offline/%s exists)\n", VolumeNumber(dp->d_name), dp->d_name);
1118 else if (LogLevel >= 5) {
1119 Log("Partition %s: attached volume %d (%s)\n",
1120 diskP->name, VolumeNumber(dp->d_name),
1129 Log("Partition %s: attached %d volumes; %d volumes not attached\n", diskP->name, *nAttached, *nUnattached);
1134 #endif /* !AFS_DEMAND_ATTACH_FS */
1136 /***************************************************/
1137 /* Shutdown routines */
1138 /***************************************************/
1142 * highly multithreaded volume package shutdown
1144 * with the demand attach fileserver extensions,
1145 * VShutdown has been modified to be multithreaded.
1146 * In order to achieve optimal use of many threads,
1147 * the shutdown code involves one control thread and
1148 * n shutdown worker threads. The control thread
1149 * periodically examines the number of volumes available
1150 * for shutdown on each partition, and produces a worker
1151 * thread allocation schedule. The idea is to eliminate
1152 * redundant scheduling computation on the workers by
1153 * having a single master scheduler.
1155 * The scheduler's objectives are:
1157 * each partition with volumes remaining gets allocated
1158 * at least 1 thread (assuming sufficient threads)
1160 * threads are allocated proportional to the number of
1161 * volumes remaining to be offlined. This ensures that
1162 * the OS I/O scheduler has many requests to elevator
1163 * seek on partitions that will (presumably) take the
1164 * longest amount of time (from now) to finish shutdown
1165 * (3) keep threads busy
1166 * when there are extra threads, they are assigned to
1167 * partitions using a simple round-robin algorithm
1169 * In the future, we may wish to add the ability to adapt
1170 * to the relative performance patterns of each disk
1175 * multi-step shutdown process
1177 * demand attach shutdown is a four-step process. Each
1178 * shutdown "pass" shuts down increasingly more difficult
1179 * volumes. The main purpose is to achieve better cache
1180 * utilization during shutdown.
1183 * shutdown volumes in the unattached, pre-attached
1186 * shutdown attached volumes with cached volume headers
1188 * shutdown all volumes in non-exclusive states
1190 * shutdown all remaining volumes
1193 #ifdef AFS_DEMAND_ATTACH_FS
1199 struct DiskPartition64 * diskP;
1200 struct diskpartition_queue_t * dpq;
1201 vshutdown_thread_t params;
1203 pthread_attr_t attrs;
1205 memset(¶ms, 0, sizeof(vshutdown_thread_t));
1208 Log("VShutdown: aborting attach volumes\n");
1209 vinit_attach_abort = 1;
1210 VOL_CV_WAIT(&vol_init_attach_cond);
1213 for (params.n_parts=0, diskP = DiskPartitionList;
1214 diskP; diskP = diskP->next, params.n_parts++);
1216 Log("VShutdown: shutting down on-line volumes on %d partition%s...\n",
1217 params.n_parts, params.n_parts > 1 ? "s" : "");
1219 if (vol_attach_threads > 1) {
1220 /* prepare for parallel shutdown */
1221 params.n_threads = vol_attach_threads;
1222 MUTEX_INIT(¶ms.lock, "params", MUTEX_DEFAULT, 0);
1223 CV_INIT(¶ms.cv, "params", CV_DEFAULT, 0);
1224 CV_INIT(¶ms.master_cv, "params master", CV_DEFAULT, 0);
1225 osi_Assert(pthread_attr_init(&attrs) == 0);
1226 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
1227 queue_Init(¶ms);
1229 /* setup the basic partition information structures for
1230 * parallel shutdown */
1231 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1233 struct rx_queue * qp, * nqp;
1237 VVByPListWait_r(diskP);
1238 VVByPListBeginExclusive_r(diskP);
1241 for (queue_Scan(&diskP->vol_list, qp, nqp, rx_queue)) {
1242 vp = (Volume *)((char *)qp - offsetof(Volume, vol_list));
1246 Log("VShutdown: partition %s has %d volumes with attached headers\n",
1247 VPartitionPath(diskP), count);
1250 /* build up the pass 0 shutdown work queue */
1251 dpq = (struct diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
1252 osi_Assert(dpq != NULL);
1254 queue_Prepend(¶ms, dpq);
1256 params.part_pass_head[diskP->index] = queue_First(&diskP->vol_list, rx_queue);
1259 Log("VShutdown: beginning parallel fileserver shutdown\n");
1260 Log("VShutdown: using %d threads to offline volumes on %d partition%s\n",
1261 vol_attach_threads, params.n_parts, params.n_parts > 1 ? "s" : "" );
1263 /* do pass 0 shutdown */
1264 MUTEX_ENTER(¶ms.lock);
1265 for (i=0; i < params.n_threads; i++) {
1266 osi_Assert(pthread_create
1267 (&tid, &attrs, &VShutdownThread,
1271 /* wait for all the pass 0 shutdowns to complete */
1272 while (params.n_threads_complete < params.n_threads) {
1273 CV_WAIT(¶ms.master_cv, ¶ms.lock);
1275 params.n_threads_complete = 0;
1277 CV_BROADCAST(¶ms.cv);
1278 MUTEX_EXIT(¶ms.lock);
1280 Log("VShutdown: pass 0 completed using the 1 thread per partition algorithm\n");
1281 Log("VShutdown: starting passes 1 through 3 using finely-granular mp-fast algorithm\n");
1283 /* run the parallel shutdown scheduler. it will drop the glock internally */
1284 ShutdownController(¶ms);
1286 /* wait for all the workers to finish pass 3 and terminate */
1287 while (params.pass < 4) {
1288 VOL_CV_WAIT(¶ms.cv);
1291 osi_Assert(pthread_attr_destroy(&attrs) == 0);
1292 CV_DESTROY(¶ms.cv);
1293 CV_DESTROY(¶ms.master_cv);
1294 MUTEX_DESTROY(¶ms.lock);
1296 /* drop the VByPList exclusive reservations */
1297 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1298 VVByPListEndExclusive_r(diskP);
1299 Log("VShutdown: %s stats : (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1300 VPartitionPath(diskP),
1301 params.stats[0][diskP->index],
1302 params.stats[1][diskP->index],
1303 params.stats[2][diskP->index],
1304 params.stats[3][diskP->index]);
1307 Log("VShutdown: shutdown finished using %d threads\n", params.n_threads);
1309 /* if we're only going to run one shutdown thread, don't bother creating
1311 Log("VShutdown: beginning single-threaded fileserver shutdown\n");
1313 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1314 VShutdownByPartition_r(diskP);
1318 Log("VShutdown: complete.\n");
1321 #else /* AFS_DEMAND_ATTACH_FS */
1331 Log("VShutdown: aborting attach volumes\n");
1332 vinit_attach_abort = 1;
1333 #ifdef AFS_PTHREAD_ENV
1334 VOL_CV_WAIT(&vol_init_attach_cond);
1336 LWP_WaitProcess(VInitAttachVolumes);
1337 #endif /* AFS_PTHREAD_ENV */
1340 Log("VShutdown: shutting down on-line volumes...\n");
1341 for (i = 0; i < VolumeHashTable.Size; i++) {
1342 /* try to hold first volume in the hash table */
1343 for (queue_Scan(&VolumeHashTable.Table[i],vp,np,Volume)) {
1347 Log("VShutdown: Attempting to take volume %u offline.\n",
1350 /* next, take the volume offline (drops reference count) */
1351 VOffline_r(vp, "File server was shut down");
1355 Log("VShutdown: complete.\n");
1357 #endif /* AFS_DEMAND_ATTACH_FS */
1363 osi_Assert(VInit>0);
1370 * stop new activity (e.g. SALVSYNC) from occurring
1372 * Use this to make the volume package less busy; for example, during
1373 * shutdown. This doesn't actually shutdown/detach anything in the
1374 * volume package, but prevents certain processes from ocurring. For
1375 * example, preventing new SALVSYNC communication in DAFS. In theory, we
1376 * could also use this to prevent new volume attachment, or prevent
1377 * other programs from checking out volumes, etc.
1382 #ifdef AFS_DEMAND_ATTACH_FS
1383 /* make sure we don't try to contact the salvageserver, since it may
1384 * not be around anymore */
1385 vol_disallow_salvsync = 1;
1389 #ifdef AFS_DEMAND_ATTACH_FS
1392 * shutdown control thread
1395 ShutdownController(vshutdown_thread_t * params)
1398 struct DiskPartition64 * diskP;
1400 vshutdown_thread_t shadow;
1402 ShutdownCreateSchedule(params);
1404 while ((params->pass < 4) &&
1405 (params->n_threads_complete < params->n_threads)) {
1406 /* recompute schedule once per second */
1408 memcpy(&shadow, params, sizeof(vshutdown_thread_t));
1412 Log("ShutdownController: schedule version=%d, vol_remaining=%d, pass=%d\n",
1413 shadow.schedule_version, shadow.vol_remaining, shadow.pass);
1414 Log("ShutdownController: n_threads_complete=%d, n_parts_done_pass=%d\n",
1415 shadow.n_threads_complete, shadow.n_parts_done_pass);
1416 for (diskP = DiskPartitionList; diskP; diskP=diskP->next) {
1418 Log("ShutdownController: part[%d] : (len=%d, thread_target=%d, done_pass=%d, pass_head=%p)\n",
1420 diskP->vol_list.len,
1421 shadow.part_thread_target[id],
1422 shadow.part_done_pass[id],
1423 shadow.part_pass_head[id]);
1429 ShutdownCreateSchedule(params);
1433 /* create the shutdown thread work schedule.
1434 * this scheduler tries to implement fairness
1435 * by allocating at least 1 thread to each
1436 * partition with volumes to be shutdown,
1437 * and then it attempts to allocate remaining
1438 * threads based upon the amount of work left
1441 ShutdownCreateSchedule(vshutdown_thread_t * params)
1443 struct DiskPartition64 * diskP;
1444 int sum, thr_workload, thr_left;
1445 int part_residue[VOLMAXPARTS+1];
1448 /* compute the total number of outstanding volumes */
1450 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1451 sum += diskP->vol_list.len;
1454 params->schedule_version++;
1455 params->vol_remaining = sum;
1460 /* compute average per-thread workload */
1461 thr_workload = sum / params->n_threads;
1462 if (sum % params->n_threads)
1465 thr_left = params->n_threads;
1466 memset(&part_residue, 0, sizeof(part_residue));
1468 /* for fairness, give every partition with volumes remaining
1469 * at least one thread */
1470 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1472 if (diskP->vol_list.len) {
1473 params->part_thread_target[id] = 1;
1476 params->part_thread_target[id] = 0;
1480 if (thr_left && thr_workload) {
1481 /* compute length-weighted workloads */
1484 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1486 delta = (diskP->vol_list.len / thr_workload) -
1487 params->part_thread_target[id];
1491 if (delta < thr_left) {
1492 params->part_thread_target[id] += delta;
1495 params->part_thread_target[id] += thr_left;
1503 /* try to assign any leftover threads to partitions that
1504 * had volume lengths closer to needing thread_target+1 */
1505 int max_residue, max_id = 0;
1507 /* compute the residues */
1508 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1510 part_residue[id] = diskP->vol_list.len -
1511 (params->part_thread_target[id] * thr_workload);
1514 /* now try to allocate remaining threads to partitions with the
1515 * highest residues */
1518 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1520 if (part_residue[id] > max_residue) {
1521 max_residue = part_residue[id];
1530 params->part_thread_target[max_id]++;
1532 part_residue[max_id] = 0;
1537 /* punt and give any remaining threads equally to each partition */
1539 if (thr_left >= params->n_parts) {
1540 alloc = thr_left / params->n_parts;
1541 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1543 params->part_thread_target[id] += alloc;
1548 /* finish off the last of the threads */
1549 for (diskP = DiskPartitionList; thr_left && diskP; diskP = diskP->next) {
1551 params->part_thread_target[id]++;
1557 /* worker thread for parallel shutdown */
1559 VShutdownThread(void * args)
1561 vshutdown_thread_t * params;
1562 int found, pass, schedule_version_save, count;
1563 struct DiskPartition64 *diskP;
1564 struct diskpartition_queue_t * dpq;
1567 params = (vshutdown_thread_t *) args;
1569 /* acquire the shutdown pass 0 lock */
1570 MUTEX_ENTER(¶ms->lock);
1572 /* if there's still pass 0 work to be done,
1573 * get a work entry, and do a pass 0 shutdown */
1574 if (queue_IsNotEmpty(params)) {
1575 dpq = queue_First(params, diskpartition_queue_t);
1577 MUTEX_EXIT(¶ms->lock);
1583 while (ShutdownVolumeWalk_r(diskP, 0, ¶ms->part_pass_head[id]))
1585 params->stats[0][diskP->index] = count;
1586 MUTEX_ENTER(¶ms->lock);
1589 params->n_threads_complete++;
1590 if (params->n_threads_complete == params->n_threads) {
1591 /* notify control thread that all workers have completed pass 0 */
1592 CV_SIGNAL(¶ms->master_cv);
1594 while (params->pass == 0) {
1595 CV_WAIT(¶ms->cv, ¶ms->lock);
1599 MUTEX_EXIT(¶ms->lock);
1602 pass = params->pass;
1603 osi_Assert(pass > 0);
1605 /* now escalate through the more complicated shutdowns */
1607 schedule_version_save = params->schedule_version;
1609 /* find a disk partition to work on */
1610 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1612 if (params->part_thread_target[id] && !params->part_done_pass[id]) {
1613 params->part_thread_target[id]--;
1620 /* hmm. for some reason the controller thread couldn't find anything for
1621 * us to do. let's see if there's anything we can do */
1622 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1624 if (diskP->vol_list.len && !params->part_done_pass[id]) {
1627 } else if (!params->part_done_pass[id]) {
1628 params->part_done_pass[id] = 1;
1629 params->n_parts_done_pass++;
1631 Log("VShutdown: done shutting down volumes on partition %s.\n",
1632 VPartitionPath(diskP));
1638 /* do work on this partition until either the controller
1639 * creates a new schedule, or we run out of things to do
1640 * on this partition */
1643 while (!params->part_done_pass[id] &&
1644 (schedule_version_save == params->schedule_version)) {
1645 /* ShutdownVolumeWalk_r will drop the glock internally */
1646 if (!ShutdownVolumeWalk_r(diskP, pass, ¶ms->part_pass_head[id])) {
1647 if (!params->part_done_pass[id]) {
1648 params->part_done_pass[id] = 1;
1649 params->n_parts_done_pass++;
1651 Log("VShutdown: done shutting down volumes on partition %s.\n",
1652 VPartitionPath(diskP));
1660 params->stats[pass][id] += count;
1662 /* ok, everyone is done this pass, proceed */
1665 params->n_threads_complete++;
1666 while (params->pass == pass) {
1667 if (params->n_threads_complete == params->n_threads) {
1668 /* we are the last thread to complete, so we will
1669 * reinitialize worker pool state for the next pass */
1670 params->n_threads_complete = 0;
1671 params->n_parts_done_pass = 0;
1673 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1675 params->part_done_pass[id] = 0;
1676 params->part_pass_head[id] = queue_First(&diskP->vol_list, rx_queue);
1679 /* compute a new thread schedule before releasing all the workers */
1680 ShutdownCreateSchedule(params);
1682 /* wake up all the workers */
1683 CV_BROADCAST(¶ms->cv);
1686 Log("VShutdown: pass %d completed using %d threads on %d partitions\n",
1687 pass, params->n_threads, params->n_parts);
1690 VOL_CV_WAIT(¶ms->cv);
1693 pass = params->pass;
1707 /* shut down all volumes on a given disk partition
1709 * note that this function will not allow mp-fast
1710 * shutdown of a partition */
1712 VShutdownByPartition_r(struct DiskPartition64 * dp)
1718 /* wait for other exclusive ops to finish */
1719 VVByPListWait_r(dp);
1721 /* begin exclusive access */
1722 VVByPListBeginExclusive_r(dp);
1724 /* pick the low-hanging fruit first,
1725 * then do the complicated ones last
1726 * (has the advantage of keeping
1727 * in-use volumes up until the bitter end) */
1728 for (pass = 0, total=0; pass < 4; pass++) {
1729 pass_stats[pass] = ShutdownVByPForPass_r(dp, pass);
1730 total += pass_stats[pass];
1733 /* end exclusive access */
1734 VVByPListEndExclusive_r(dp);
1736 Log("VShutdownByPartition: shut down %d volumes on %s (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1737 total, VPartitionPath(dp), pass_stats[0], pass_stats[1], pass_stats[2], pass_stats[3]);
1742 /* internal shutdown functionality
1744 * for multi-pass shutdown:
1745 * 0 to only "shutdown" {pre,un}attached and error state volumes
1746 * 1 to also shutdown attached volumes w/ volume header loaded
1747 * 2 to also shutdown attached volumes w/o volume header loaded
1748 * 3 to also shutdown exclusive state volumes
1750 * caller MUST hold exclusive access on the hash chain
1751 * because we drop vol_glock_mutex internally
1753 * this function is reentrant for passes 1--3
1754 * (e.g. multiple threads can cooperate to
1755 * shutdown a partition mp-fast)
1757 * pass 0 is not scaleable because the volume state data is
1758 * synchronized by vol_glock mutex, and the locking overhead
1759 * is too high to drop the lock long enough to do linked list
1763 ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass)
1765 struct rx_queue * q = queue_First(&dp->vol_list, rx_queue);
1768 while (ShutdownVolumeWalk_r(dp, pass, &q))
1774 /* conditionally shutdown one volume on partition dp
1775 * returns 1 if a volume was shutdown in this pass,
1778 ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
1779 struct rx_queue ** idx)
1781 struct rx_queue *qp, *nqp;
1786 for (queue_ScanFrom(&dp->vol_list, qp, qp, nqp, rx_queue)) {
1787 vp = (Volume *) (((char *)qp) - offsetof(Volume, vol_list));
1791 if ((V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1792 (V_attachState(vp) != VOL_STATE_ERROR) &&
1793 (V_attachState(vp) != VOL_STATE_DELETED) &&
1794 (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1798 if ((V_attachState(vp) == VOL_STATE_ATTACHED) &&
1799 (vp->header == NULL)) {
1803 if (VIsExclusiveState(V_attachState(vp))) {
1808 DeleteVolumeFromVByPList_r(vp);
1809 VShutdownVolume_r(vp);
1819 * shutdown a specific volume
1821 /* caller MUST NOT hold a heavyweight ref on vp */
1823 VShutdownVolume_r(Volume * vp)
1827 VCreateReservation_r(vp);
1829 if (LogLevel >= 5) {
1830 Log("VShutdownVolume_r: vid=%u, device=%d, state=%hu\n",
1831 vp->hashid, vp->partition->device, V_attachState(vp));
1834 /* wait for other blocking ops to finish */
1835 VWaitExclusiveState_r(vp);
1837 osi_Assert(VIsValidState(V_attachState(vp)));
1839 switch(V_attachState(vp)) {
1840 case VOL_STATE_SALVAGING:
1841 /* Leave salvaging volumes alone. Any in-progress salvages will
1842 * continue working after viced shuts down. This is intentional.
1845 case VOL_STATE_PREATTACHED:
1846 case VOL_STATE_ERROR:
1847 VChangeState_r(vp, VOL_STATE_UNATTACHED);
1848 case VOL_STATE_UNATTACHED:
1849 case VOL_STATE_DELETED:
1851 case VOL_STATE_GOING_OFFLINE:
1852 case VOL_STATE_SHUTTING_DOWN:
1853 case VOL_STATE_ATTACHED:
1857 Log("VShutdown: Attempting to take volume %u offline.\n",
1860 /* take the volume offline (drops reference count) */
1861 VOffline_r(vp, "File server was shut down");
1868 VCancelReservation_r(vp);
1872 #endif /* AFS_DEMAND_ATTACH_FS */
1875 /***************************************************/
1876 /* Header I/O routines */
1877 /***************************************************/
1879 /* open a descriptor for the inode (h),
1880 * read in an on-disk structure into buffer (to) of size (size),
1881 * verify versionstamp in structure has magic (magic) and
1882 * optionally verify version (version) if (version) is nonzero
1885 ReadHeader(Error * ec, IHandle_t * h, char *to, int size, bit32 magic,
1888 struct versionStamp *vsn;
1903 vsn = (struct versionStamp *)to;
1904 if (FDH_PREAD(fdP, to, size, 0) != size || vsn->magic != magic) {
1906 FDH_REALLYCLOSE(fdP);
1911 /* Check is conditional, in case caller wants to inspect version himself */
1912 if (version && vsn->version != version) {
1918 WriteVolumeHeader_r(Error * ec, Volume * vp)
1920 IHandle_t *h = V_diskDataHandle(vp);
1930 if (FDH_PWRITE(fdP, (char *)&V_disk(vp), sizeof(V_disk(vp)), 0)
1931 != sizeof(V_disk(vp))) {
1933 FDH_REALLYCLOSE(fdP);
1939 /* VolumeHeaderToDisk
1940 * Allows for storing 64 bit inode numbers in on-disk volume header
1943 /* convert in-memory representation of a volume header to the
1944 * on-disk representation of a volume header */
1946 VolumeHeaderToDisk(VolumeDiskHeader_t * dh, VolumeHeader_t * h)
1949 memset(dh, 0, sizeof(VolumeDiskHeader_t));
1950 dh->stamp = h->stamp;
1952 dh->parent = h->parent;
1954 #ifdef AFS_64BIT_IOPS_ENV
1955 dh->volumeInfo_lo = (afs_int32) h->volumeInfo & 0xffffffff;
1956 dh->volumeInfo_hi = (afs_int32) (h->volumeInfo >> 32) & 0xffffffff;
1957 dh->smallVnodeIndex_lo = (afs_int32) h->smallVnodeIndex & 0xffffffff;
1958 dh->smallVnodeIndex_hi =
1959 (afs_int32) (h->smallVnodeIndex >> 32) & 0xffffffff;
1960 dh->largeVnodeIndex_lo = (afs_int32) h->largeVnodeIndex & 0xffffffff;
1961 dh->largeVnodeIndex_hi =
1962 (afs_int32) (h->largeVnodeIndex >> 32) & 0xffffffff;
1963 dh->linkTable_lo = (afs_int32) h->linkTable & 0xffffffff;
1964 dh->linkTable_hi = (afs_int32) (h->linkTable >> 32) & 0xffffffff;
1966 dh->volumeInfo_lo = h->volumeInfo;
1967 dh->smallVnodeIndex_lo = h->smallVnodeIndex;
1968 dh->largeVnodeIndex_lo = h->largeVnodeIndex;
1969 dh->linkTable_lo = h->linkTable;
1973 /* DiskToVolumeHeader
1974 * Converts an on-disk representation of a volume header to
1975 * the in-memory representation of a volume header.
1977 * Makes the assumption that AFS has *always*
1978 * zero'd the volume header file so that high parts of inode
1979 * numbers are 0 in older (SGI EFS) volume header files.
1982 DiskToVolumeHeader(VolumeHeader_t * h, VolumeDiskHeader_t * dh)
1984 memset(h, 0, sizeof(VolumeHeader_t));
1985 h->stamp = dh->stamp;
1987 h->parent = dh->parent;
1989 #ifdef AFS_64BIT_IOPS_ENV
1991 (Inode) dh->volumeInfo_lo | ((Inode) dh->volumeInfo_hi << 32);
1993 h->smallVnodeIndex =
1994 (Inode) dh->smallVnodeIndex_lo | ((Inode) dh->
1995 smallVnodeIndex_hi << 32);
1997 h->largeVnodeIndex =
1998 (Inode) dh->largeVnodeIndex_lo | ((Inode) dh->
1999 largeVnodeIndex_hi << 32);
2001 (Inode) dh->linkTable_lo | ((Inode) dh->linkTable_hi << 32);
2003 h->volumeInfo = dh->volumeInfo_lo;
2004 h->smallVnodeIndex = dh->smallVnodeIndex_lo;
2005 h->largeVnodeIndex = dh->largeVnodeIndex_lo;
2006 h->linkTable = dh->linkTable_lo;
2011 /***************************************************/
2012 /* Volume Attachment routines */
2013 /***************************************************/
2015 #ifdef AFS_DEMAND_ATTACH_FS
2017 * pre-attach a volume given its path.
2019 * @param[out] ec outbound error code
2020 * @param[in] partition partition path string
2021 * @param[in] name volume id string
2023 * @return volume object pointer
2025 * @note A pre-attached volume will only have its partition
2026 * and hashid fields initialized. At first call to
2027 * VGetVolume, the volume will be fully attached.
2031 VPreAttachVolumeByName(Error * ec, char *partition, char *name)
2035 vp = VPreAttachVolumeByName_r(ec, partition, name);
2041 * pre-attach a volume given its path.
2043 * @param[out] ec outbound error code
2044 * @param[in] partition path to vice partition
2045 * @param[in] name volume id string
2047 * @return volume object pointer
2049 * @pre VOL_LOCK held
2051 * @internal volume package internal use only.
2054 VPreAttachVolumeByName_r(Error * ec, char *partition, char *name)
2056 return VPreAttachVolumeById_r(ec,
2058 VolumeNumber(name));
2062 * pre-attach a volume given its path and numeric volume id.
2064 * @param[out] ec error code return
2065 * @param[in] partition path to vice partition
2066 * @param[in] volumeId numeric volume id
2068 * @return volume object pointer
2070 * @pre VOL_LOCK held
2072 * @internal volume package internal use only.
2075 VPreAttachVolumeById_r(Error * ec,
2080 struct DiskPartition64 *partp;
2084 osi_Assert(programType == fileServer);
2086 if (!(partp = VGetPartition_r(partition, 0))) {
2088 Log("VPreAttachVolumeById_r: Error getting partition (%s)\n", partition);
2092 vp = VLookupVolume_r(ec, volumeId, NULL);
2097 return VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2101 * preattach a volume.
2103 * @param[out] ec outbound error code
2104 * @param[in] partp pointer to partition object
2105 * @param[in] vp pointer to volume object
2106 * @param[in] vid volume id
2108 * @return volume object pointer
2110 * @pre VOL_LOCK is held.
2112 * @warning Returned volume object pointer does not have to
2113 * equal the pointer passed in as argument vp. There
2114 * are potential race conditions which can result in
2115 * the pointers having different values. It is up to
2116 * the caller to make sure that references are handled
2117 * properly in this case.
2119 * @note If there is already a volume object registered with
2120 * the same volume id, its pointer MUST be passed as
2121 * argument vp. Failure to do so will result in a silent
2122 * failure to preattach.
2124 * @internal volume package internal use only.
2127 VPreAttachVolumeByVp_r(Error * ec,
2128 struct DiskPartition64 * partp,
2136 /* check to see if pre-attach already happened */
2138 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
2139 (V_attachState(vp) != VOL_STATE_DELETED) &&
2140 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
2141 !VIsErrorState(V_attachState(vp))) {
2143 * pre-attach is a no-op in all but the following cases:
2145 * - volume is unattached
2146 * - volume is in an error state
2147 * - volume is pre-attached
2149 Log("VPreattachVolumeByVp_r: volume %u not in quiescent state\n", vid);
2152 /* we're re-attaching a volume; clear out some old state */
2153 memset(&vp->salvage, 0, sizeof(struct VolumeOnlineSalvage));
2155 if (V_partition(vp) != partp) {
2156 /* XXX potential race */
2157 DeleteVolumeFromVByPList_r(vp);
2160 /* if we need to allocate a new Volume struct,
2161 * go ahead and drop the vol glock, otherwise
2162 * do the basic setup synchronised, as it's
2163 * probably not worth dropping the lock */
2166 /* allocate the volume structure */
2167 vp = nvp = (Volume *) malloc(sizeof(Volume));
2168 osi_Assert(vp != NULL);
2169 memset(vp, 0, sizeof(Volume));
2170 queue_Init(&vp->vnode_list);
2171 CV_INIT(&V_attachCV(vp), "vp attach", CV_DEFAULT, 0);
2174 /* link the volume with its associated vice partition */
2175 vp->device = partp->device;
2176 vp->partition = partp;
2179 vp->specialStatus = 0;
2181 /* if we dropped the lock, reacquire the lock,
2182 * check for pre-attach races, and then add
2183 * the volume to the hash table */
2186 nvp = VLookupVolume_r(ec, vid, NULL);
2191 } else if (nvp) { /* race detected */
2196 /* hack to make up for VChangeState_r() decrementing
2197 * the old state counter */
2198 VStats.state_levels[0]++;
2202 /* put pre-attached volume onto the hash table
2203 * and bring it up to the pre-attached state */
2204 AddVolumeToHashTable(vp, vp->hashid);
2205 AddVolumeToVByPList_r(vp);
2206 VLRU_Init_Node_r(vp);
2207 VChangeState_r(vp, VOL_STATE_PREATTACHED);
2210 Log("VPreAttachVolumeByVp_r: volume %u pre-attached\n", vp->hashid);
2218 #endif /* AFS_DEMAND_ATTACH_FS */
2220 /* Attach an existing volume, given its pathname, and return a
2221 pointer to the volume header information. The volume also
2222 normally goes online at this time. An offline volume
2223 must be reattached to make it go online */
2225 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
2229 retVal = VAttachVolumeByName_r(ec, partition, name, mode);
2235 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
2238 struct DiskPartition64 *partp;
2243 #ifdef AFS_DEMAND_ATTACH_FS
2244 VolumeStats stats_save;
2246 #endif /* AFS_DEMAND_ATTACH_FS */
2250 volumeId = VolumeNumber(name);
2252 if (!(partp = VGetPartition_r(partition, 0))) {
2254 Log("VAttachVolume: Error getting partition (%s)\n", partition);
2258 if (VRequiresPartLock()) {
2259 osi_Assert(VInit == 3);
2260 VLockPartition_r(partition);
2261 } else if (programType == fileServer) {
2262 #ifdef AFS_DEMAND_ATTACH_FS
2263 /* lookup the volume in the hash table */
2264 vp = VLookupVolume_r(ec, volumeId, NULL);
2270 /* save any counters that are supposed to
2271 * be monotonically increasing over the
2272 * lifetime of the fileserver */
2273 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2275 memset(&stats_save, 0, sizeof(VolumeStats));
2278 /* if there's something in the hash table, and it's not
2279 * in the pre-attach state, then we may need to detach
2280 * it before proceeding */
2281 if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
2282 VCreateReservation_r(vp);
2283 VWaitExclusiveState_r(vp);
2285 /* at this point state must be one of:
2295 if (vp->specialStatus == VBUSY)
2298 /* if it's already attached, see if we can return it */
2299 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2300 VGetVolumeByVp_r(ec, vp);
2301 if (V_inUse(vp) == fileServer) {
2302 VCancelReservation_r(vp);
2306 /* otherwise, we need to detach, and attempt to re-attach */
2307 VDetachVolume_r(ec, vp);
2309 Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
2312 /* if it isn't fully attached, delete from the hash tables,
2313 and let the refcounter handle the rest */
2314 DeleteVolumeFromHashTable(vp);
2315 DeleteVolumeFromVByPList_r(vp);
2318 VCancelReservation_r(vp);
2322 /* pre-attach volume if it hasn't been done yet */
2324 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2325 (V_attachState(vp) == VOL_STATE_DELETED) ||
2326 (V_attachState(vp) == VOL_STATE_ERROR)) {
2328 vp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2334 osi_Assert(vp != NULL);
2336 /* handle pre-attach races
2338 * multiple threads can race to pre-attach a volume,
2339 * but we can't let them race beyond that
2341 * our solution is to let the first thread to bring
2342 * the volume into an exclusive state win; the other
2343 * threads just wait until it finishes bringing the
2344 * volume online, and then they do a vgetvolumebyvp
2346 if (svp && (svp != vp)) {
2347 /* wait for other exclusive ops to finish */
2348 VCreateReservation_r(vp);
2349 VWaitExclusiveState_r(vp);
2351 /* get a heavyweight ref, kill the lightweight ref, and return */
2352 VGetVolumeByVp_r(ec, vp);
2353 VCancelReservation_r(vp);
2357 /* at this point, we are chosen as the thread to do
2358 * demand attachment for this volume. all other threads
2359 * doing a getvolume on vp->hashid will block until we finish */
2361 /* make sure any old header cache entries are invalidated
2362 * before proceeding */
2363 FreeVolumeHeader(vp);
2365 VChangeState_r(vp, VOL_STATE_ATTACHING);
2367 /* restore any saved counters */
2368 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2369 #else /* AFS_DEMAND_ATTACH_FS */
2370 vp = VGetVolume_r(ec, volumeId);
2372 if (V_inUse(vp) == fileServer)
2374 if (vp->specialStatus == VBUSY)
2376 VDetachVolume_r(ec, vp);
2378 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2382 #endif /* AFS_DEMAND_ATTACH_FS */
2386 strcpy(path, VPartitionPath(partp));
2394 vp = (Volume *) calloc(1, sizeof(Volume));
2395 osi_Assert(vp != NULL);
2396 vp->hashid = volumeId;
2397 vp->device = partp->device;
2398 vp->partition = partp;
2399 queue_Init(&vp->vnode_list);
2400 #ifdef AFS_DEMAND_ATTACH_FS
2401 CV_INIT(&V_attachCV(vp), "vp attach", CV_DEFAULT, 0);
2402 #endif /* AFS_DEMAND_ATTACH_FS */
2405 /* attach2 is entered without any locks, and returns
2406 * with vol_glock_mutex held */
2407 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2409 if (VCanUseFSSYNC() && vp) {
2410 #ifdef AFS_DEMAND_ATTACH_FS
2411 if ((mode == V_VOLUPD) || (VolumeWriteable(vp) && (mode == V_CLONE))) {
2412 /* mark volume header as in use so that volser crashes lead to a
2413 * salvage attempt */
2414 VUpdateVolume_r(ec, vp, 0);
2416 /* for dafs, we should tell the fileserver, except for V_PEEK
2417 * where we know it is not necessary */
2418 if (mode == V_PEEK) {
2419 vp->needsPutBack = 0;
2421 vp->needsPutBack = VOL_PUTBACK;
2423 #else /* !AFS_DEMAND_ATTACH_FS */
2424 /* duplicate computation in fssync.c about whether the server
2425 * takes the volume offline or not. If the volume isn't
2426 * offline, we must not return it when we detach the volume,
2427 * or the server will abort */
2428 if (mode == V_READONLY || mode == V_PEEK
2429 || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
2430 vp->needsPutBack = 0;
2432 vp->needsPutBack = VOL_PUTBACK;
2433 #endif /* !AFS_DEMAND_ATTACH_FS */
2435 #ifdef FSSYNC_BUILD_CLIENT
2436 /* Only give back the vol to the fileserver if we checked it out; attach2
2437 * will set checkedOut only if we successfully checked it out from the
2439 if (VCanUseFSSYNC() && vp == NULL && checkedOut) {
2441 #ifdef AFS_DEMAND_ATTACH_FS
2442 /* If we couldn't attach but we scheduled a salvage, we already
2443 * notified the fileserver; don't online it now */
2444 if (*ec != VSALVAGING)
2445 #endif /* AFS_DEMAND_ATTACH_FS */
2446 FSYNC_VolOp(volumeId, partition, FSYNC_VOL_ON, 0, NULL);
2449 if (programType == fileServer && vp) {
2450 #ifdef AFS_DEMAND_ATTACH_FS
2452 * we can get here in cases where we don't "own"
2453 * the volume (e.g. volume owned by a utility).
2454 * short circuit around potential disk header races.
2456 if (V_attachState(vp) != VOL_STATE_ATTACHED) {
2460 VUpdateVolume_r(ec, vp, 0);
2462 Log("VAttachVolume: Error updating volume\n");
2467 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2468 #ifndef AFS_DEMAND_ATTACH_FS
2469 /* This is a hack: by temporarily setting the incore
2470 * dontSalvage flag ON, the volume will be put back on the
2471 * Update list (with dontSalvage OFF again). It will then
2472 * come back in N minutes with DONT_SALVAGE eventually
2473 * set. This is the way that volumes that have never had
2474 * it set get it set; or that volumes that have been
2475 * offline without DONT SALVAGE having been set also
2476 * eventually get it set */
2477 V_dontSalvage(vp) = DONT_SALVAGE;
2478 #endif /* !AFS_DEMAND_ATTACH_FS */
2479 VAddToVolumeUpdateList_r(ec, vp);
2481 Log("VAttachVolume: Error adding volume to update list\n");
2488 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2493 if (VRequiresPartLock()) {
2494 VUnlockPartition_r(partition);
2497 #ifdef AFS_DEMAND_ATTACH_FS
2498 /* attach failed; make sure we're in error state */
2499 if (vp && !VIsErrorState(V_attachState(vp))) {
2500 VChangeState_r(vp, VOL_STATE_ERROR);
2502 #endif /* AFS_DEMAND_ATTACH_FS */
2509 #ifdef AFS_DEMAND_ATTACH_FS
2510 /* VAttachVolumeByVp_r
2512 * finish attaching a volume that is
2513 * in a less than fully attached state
2515 /* caller MUST hold a ref count on vp */
2517 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
2519 char name[VMAXPATHLEN];
2521 struct DiskPartition64 *partp;
2525 Volume * nvp = NULL;
2526 VolumeStats stats_save;
2530 /* volume utility should never call AttachByVp */
2531 osi_Assert(programType == fileServer);
2533 volumeId = vp->hashid;
2534 partp = vp->partition;
2535 VolumeExternalName_r(volumeId, name, sizeof(name));
2538 /* if another thread is performing a blocking op, wait */
2539 VWaitExclusiveState_r(vp);
2541 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2543 /* if it's already attached, see if we can return it */
2544 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2545 VGetVolumeByVp_r(ec, vp);
2546 if (V_inUse(vp) == fileServer) {
2549 if (vp->specialStatus == VBUSY)
2551 VDetachVolume_r(ec, vp);
2553 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2559 /* pre-attach volume if it hasn't been done yet */
2561 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2562 (V_attachState(vp) == VOL_STATE_DELETED) ||
2563 (V_attachState(vp) == VOL_STATE_ERROR)) {
2564 nvp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2570 VCreateReservation_r(nvp);
2575 osi_Assert(vp != NULL);
2576 VChangeState_r(vp, VOL_STATE_ATTACHING);
2578 /* restore monotonically increasing stats */
2579 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2583 /* compute path to disk header */
2584 strcpy(path, VPartitionPath(partp));
2593 * NOTE: attach2 is entered without any locks, and returns
2594 * with vol_glock_mutex held */
2595 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2598 * the event that an error was encountered, or
2599 * the volume was not brought to an attached state
2600 * for any reason, skip to the end. We cannot
2601 * safely call VUpdateVolume unless we "own" it.
2605 (V_attachState(vp) != VOL_STATE_ATTACHED)) {
2609 VUpdateVolume_r(ec, vp, 0);
2611 Log("VAttachVolume: Error updating volume %u\n", vp->hashid);
2615 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2616 #ifndef AFS_DEMAND_ATTACH_FS
2617 /* This is a hack: by temporarily setting the incore
2618 * dontSalvage flag ON, the volume will be put back on the
2619 * Update list (with dontSalvage OFF again). It will then
2620 * come back in N minutes with DONT_SALVAGE eventually
2621 * set. This is the way that volumes that have never had
2622 * it set get it set; or that volumes that have been
2623 * offline without DONT SALVAGE having been set also
2624 * eventually get it set */
2625 V_dontSalvage(vp) = DONT_SALVAGE;
2626 #endif /* !AFS_DEMAND_ATTACH_FS */
2627 VAddToVolumeUpdateList_r(ec, vp);
2629 Log("VAttachVolume: Error adding volume %u to update list\n", vp->hashid);
2636 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2640 VCancelReservation_r(nvp);
2643 if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2644 if (vp && !VIsErrorState(V_attachState(vp))) {
2645 VChangeState_r(vp, VOL_STATE_ERROR);
2654 * lock a volume on disk (non-blocking).
2656 * @param[in] vp The volume to lock
2657 * @param[in] locktype READ_LOCK or WRITE_LOCK
2659 * @return operation status
2660 * @retval 0 success, lock was obtained
2661 * @retval EBUSY a conflicting lock was held by another process
2662 * @retval EIO error acquiring lock
2664 * @pre If we're in the fileserver, vp is in an exclusive state
2666 * @pre vp is not already locked
2669 VLockVolumeNB(Volume *vp, int locktype)
2673 osi_Assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2674 osi_Assert(!(V_attachFlags(vp) & VOL_LOCKED));
2676 code = VLockVolumeByIdNB(vp->hashid, vp->partition, locktype);
2678 V_attachFlags(vp) |= VOL_LOCKED;
2685 * unlock a volume on disk that was locked with VLockVolumeNB.
2687 * @param[in] vp volume to unlock
2689 * @pre If we're in the fileserver, vp is in an exclusive state
2691 * @pre vp has already been locked
2694 VUnlockVolume(Volume *vp)
2696 osi_Assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2697 osi_Assert((V_attachFlags(vp) & VOL_LOCKED));
2699 VUnlockVolumeById(vp->hashid, vp->partition);
2701 V_attachFlags(vp) &= ~VOL_LOCKED;
2703 #endif /* AFS_DEMAND_ATTACH_FS */
2706 * read in a vol header, possibly lock the vol header, and possibly check out
2707 * the vol header from the fileserver, as part of volume attachment.
2709 * @param[out] ec error code
2710 * @param[in] vp volume pointer object
2711 * @param[in] partp disk partition object of the attaching partition
2712 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
2714 * @param[in] peek 1 to just try to read in the volume header and make sure
2715 * we don't try to lock the vol, or check it out from
2716 * FSSYNC or anything like that; 0 otherwise, for 'normal'
2718 * @param[out] acheckedOut If we successfully checked-out the volume from
2719 * the fileserver (if we needed to), this is set
2720 * to 1, otherwise it is untouched.
2722 * @note As part of DAFS volume attachment, the volume header may be either
2723 * read- or write-locked to ensure mutual exclusion of certain volume
2724 * operations. In some cases in order to determine whether we need to
2725 * read- or write-lock the header, we need to read in the header to see
2726 * if the volume is RW or not. So, if we read in the header under a
2727 * read-lock and determine that we actually need a write-lock on the
2728 * volume header, this function will drop the read lock, acquire a write
2729 * lock, and read the header in again.
2732 attach_volume_header(Error *ec, Volume *vp, struct DiskPartition64 *partp,
2733 int mode, int peek, int *acheckedOut)
2735 struct VolumeDiskHeader diskHeader;
2736 struct VolumeHeader header;
2739 int lock_tries = 0, checkout_tries = 0;
2741 VolumeId volid = vp->hashid;
2742 #ifdef FSSYNC_BUILD_CLIENT
2743 int checkout, done_checkout = 0;
2744 #endif /* FSSYNC_BUILD_CLIENT */
2745 #ifdef AFS_DEMAND_ATTACH_FS
2746 int locktype = 0, use_locktype = -1;
2747 #endif /* AFS_DEMAND_ATTACH_FS */
2753 if (lock_tries > VOL_MAX_CHECKOUT_RETRIES) {
2754 Log("VAttachVolume: retried too many times trying to lock header for "
2755 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2756 VPartitionPath(partp));
2760 if (checkout_tries > VOL_MAX_CHECKOUT_RETRIES) {
2761 Log("VAttachVolume: retried too many times trying to checkout "
2762 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2763 VPartitionPath(partp));
2768 if (VReadVolumeDiskHeader(volid, partp, NULL)) {
2769 /* short-circuit the 'volume does not exist' case */
2774 #ifdef FSSYNC_BUILD_CLIENT
2775 checkout = !done_checkout;
2777 if (!peek && checkout && VMustCheckoutVolume(mode)) {
2779 memset(&res, 0, sizeof(res));
2781 if (FSYNC_VolOp(volid, VPartitionPath(partp), FSYNC_VOL_NEEDVOLUME, mode, &res)
2784 if (res.hdr.reason == FSYNC_SALVAGE) {
2785 Log("VAttachVolume: file server says volume %lu is salvaging\n",
2786 afs_printable_uint32_lu(volid));
2789 Log("VAttachVolume: attach of volume %lu apparently denied by file server\n",
2790 afs_printable_uint32_lu(volid));
2791 *ec = VNOVOL; /* XXXX */
2799 #ifdef AFS_DEMAND_ATTACH_FS
2800 if (use_locktype < 0) {
2801 /* don't know whether vol is RO or RW; assume it's RO and we can retry
2802 * if it turns out to be RW */
2803 locktype = VVolLockType(mode, 0);
2806 /* a previous try says we should use use_locktype to lock the volume,
2808 locktype = use_locktype;
2811 if (!peek && locktype) {
2812 code = VLockVolumeNB(vp, locktype);
2814 if (code == EBUSY) {
2815 Log("VAttachVolume: another program has vol %lu locked\n",
2816 afs_printable_uint32_lu(volid));
2818 Log("VAttachVolume: error %d trying to lock vol %lu\n",
2819 code, afs_printable_uint32_lu(volid));
2826 #endif /* AFS_DEMAND_ATTACH_FS */
2828 code = VReadVolumeDiskHeader(volid, partp, &diskHeader);
2838 DiskToVolumeHeader(&header, &diskHeader);
2840 IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header.parent,
2841 header.largeVnodeIndex);
2842 IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header.parent,
2843 header.smallVnodeIndex);
2844 IH_INIT(vp->diskDataHandle, partp->device, header.parent,
2846 IH_INIT(vp->linkHandle, partp->device, header.parent, header.linkTable);
2849 /* only need to do this once */
2851 GetVolumeHeader(vp);
2855 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2856 /* demand attach changes the V_PEEK mechanism
2858 * we can now suck the current disk data structure over
2859 * the fssync interface without going to disk
2861 * (technically, we don't need to restrict this feature
2862 * to demand attach fileservers. However, I'm trying
2863 * to limit the number of common code changes)
2865 if (VCanUseFSSYNC() && (mode == V_PEEK || peek)) {
2867 res.payload.len = sizeof(VolumeDiskData);
2868 res.payload.buf = &vp->header->diskstuff;
2870 if (FSYNC_VolOp(vp->hashid,
2872 FSYNC_VOL_QUERY_HDR,
2875 goto disk_header_loaded;
2878 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2879 (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2880 sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2882 #ifdef AFS_DEMAND_ATTACH_FS
2885 IncUInt64(&VStats.hdr_loads);
2886 IncUInt64(&vp->stats.hdr_loads);
2888 #endif /* AFS_DEMAND_ATTACH_FS */
2891 Log("VAttachVolume: Error reading diskDataHandle header for vol %lu; "
2892 "error=%u\n", afs_printable_uint32_lu(volid), *ec);
2896 #ifdef AFS_DEMAND_ATTACH_FS
2897 # ifdef FSSYNC_BUILD_CLIENT
2899 # endif /* FSSYNC_BUILD_CLIENT */
2901 /* if the lock type we actually used to lock the volume is different than
2902 * the lock type we should have used, retry with the lock type we should
2904 use_locktype = VVolLockType(mode, VolumeWriteable(vp));
2905 if (locktype != use_locktype) {
2909 #endif /* AFS_DEMAND_ATTACH_FS */
2914 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2915 if (!peek && *ec == 0 && retry == 0 && VMustCheckoutVolume(mode)) {
2917 code = FSYNC_VerifyCheckout(volid, VPartitionPath(partp), FSYNC_VOL_NEEDVOLUME, mode);
2919 if (code == SYNC_DENIED) {
2920 /* must retry checkout; fileserver no longer thinks we have
2926 } else if (code != SYNC_OK) {
2930 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2933 /* either we are going to be called again for a second pass, or we
2934 * encountered an error; clean up in either case */
2936 #ifdef AFS_DEMAND_ATTACH_FS
2937 if ((V_attachFlags(vp) & VOL_LOCKED)) {
2940 #endif /* AFS_DEMAND_ATTACH_FS */
2941 if (vp->linkHandle) {
2942 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
2943 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
2944 IH_RELEASE(vp->diskDataHandle);
2945 IH_RELEASE(vp->linkHandle);
2958 #ifdef AFS_DEMAND_ATTACH_FS
2960 attach_check_vop(Error *ec, VolumeId volid, struct DiskPartition64 *partp,
2961 Volume *vp, int *acheckedOut)
2965 if (vp->pending_vol_op) {
2969 if (vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningUnknown) {
2971 code = VVolOpLeaveOnlineNoHeader_r(vp, vp->pending_vol_op);
2973 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
2974 } else if (code == 0) {
2975 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
2978 /* we need the vol header to determine if the volume can be
2979 * left online for the vop, so... get the header */
2983 /* attach header with peek=1 to avoid checking out the volume
2984 * or locking it; we just want the header info, we're not
2985 * messing with the volume itself at all */
2986 attach_volume_header(ec, vp, partp, V_PEEK, 1, acheckedOut);
2993 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
2994 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
2996 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
2999 /* make sure we grab a new vol header and re-open stuff on
3000 * actual attachment; we can't keep the data we grabbed, since
3001 * it was not done under a lock and thus not safe */
3002 FreeVolumeHeader(vp);
3003 VReleaseVolumeHandles_r(vp);
3006 /* see if the pending volume op requires exclusive access */
3007 switch (vp->pending_vol_op->vol_op_state) {
3008 case FSSYNC_VolOpPending:
3009 /* this should never happen */
3010 osi_Assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpPending);
3013 case FSSYNC_VolOpRunningUnknown:
3014 /* this should never happen; we resolved 'unknown' above */
3015 osi_Assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
3018 case FSSYNC_VolOpRunningOffline:
3019 /* mark the volume down */
3021 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3023 /* do not set V_offlineMessage here; we don't have ownership of
3024 * the volume (and probably do not have the header loaded), so we
3025 * can't alter the disk header */
3027 /* check to see if we should set the specialStatus flag */
3028 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
3029 vp->specialStatus = VBUSY;
3040 #endif /* AFS_DEMAND_ATTACH_FS */
3043 * volume attachment helper function.
3045 * @param[out] ec error code
3046 * @param[in] volumeId volume ID of the attaching volume
3047 * @param[in] path full path to the volume header .vol file
3048 * @param[in] partp disk partition object for the attaching partition
3049 * @param[in] vp volume object; vp->hashid, vp->device, vp->partition,
3050 * vp->vnode_list, and V_attachCV (for DAFS) should already
3052 * @param[in] isbusy 1 if vp->specialStatus should be set to VBUSY; that is,
3053 * if there is a volume operation running for this volume
3054 * that should set the volume to VBUSY during its run. 0
3055 * otherwise. (see VVolOpSetVBusy_r)
3056 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
3058 * @param[out] acheckedOut If we successfully checked-out the volume from
3059 * the fileserver (if we needed to), this is set
3060 * to 1, otherwise it is 0.
3062 * @return pointer to the semi-attached volume pointer
3063 * @retval NULL an error occurred (check value of *ec)
3064 * @retval vp volume successfully attaching
3066 * @pre no locks held
3068 * @post VOL_LOCK held
3071 attach2(Error * ec, VolId volumeId, char *path, struct DiskPartition64 *partp,
3072 Volume * vp, int isbusy, int mode, int *acheckedOut)
3074 /* have we read in the header successfully? */
3075 int read_header = 0;
3077 #ifdef AFS_DEMAND_ATTACH_FS
3078 /* should we FreeVolume(vp) instead of VCheckFree(vp) in the error
3082 /* in the case of an error, to what state should the volume be
3084 VolState error_state = VOL_STATE_ERROR;
3085 #endif /* AFS_DEMAND_ATTACH_FS */
3089 vp->vnodeIndex[vLarge].handle = NULL;
3090 vp->vnodeIndex[vSmall].handle = NULL;
3091 vp->diskDataHandle = NULL;
3092 vp->linkHandle = NULL;
3096 #ifdef AFS_DEMAND_ATTACH_FS
3097 attach_check_vop(ec, volumeId, partp, vp, acheckedOut);
3099 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3102 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3103 #endif /* !AFS_DEMAND_ATTACH_FS */
3105 if (*ec == VNOVOL) {
3106 /* if the volume doesn't exist, skip straight to 'error' so we don't
3107 * request a salvage */
3108 goto unlocked_error;
3114 vp->specialStatus = (byte) (isbusy ? VBUSY : 0);
3115 vp->shuttingDown = 0;
3116 vp->goingOffline = 0;
3118 #ifdef AFS_DEMAND_ATTACH_FS
3119 vp->stats.last_attach = FT_ApproxTime();
3120 vp->stats.attaches++;
3124 IncUInt64(&VStats.attaches);
3125 vp->cacheCheck = ++VolumeCacheCheck;
3126 /* just in case this ever rolls over */
3127 if (!vp->cacheCheck)
3128 vp->cacheCheck = ++VolumeCacheCheck;
3131 #ifdef AFS_DEMAND_ATTACH_FS
3132 V_attachFlags(vp) |= VOL_HDR_LOADED;
3133 vp->stats.last_hdr_load = vp->stats.last_attach;
3134 #endif /* AFS_DEMAND_ATTACH_FS */
3138 struct IndexFileHeader iHead;
3140 #if OPENAFS_VOL_STATS
3142 * We just read in the diskstuff part of the header. If the detailed
3143 * volume stats area has not yet been initialized, we should bzero the
3144 * area and mark it as initialized.
3146 if (!(V_stat_initialized(vp))) {
3147 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
3148 V_stat_initialized(vp) = 1;
3150 #endif /* OPENAFS_VOL_STATS */
3152 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
3153 (char *)&iHead, sizeof(iHead),
3154 SMALLINDEXMAGIC, SMALLINDEXVERSION);
3157 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
3162 struct IndexFileHeader iHead;
3164 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
3165 (char *)&iHead, sizeof(iHead),
3166 LARGEINDEXMAGIC, LARGEINDEXVERSION);
3169 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
3173 #ifdef AFS_NAMEI_ENV
3175 struct versionStamp stamp;
3177 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
3178 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
3181 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
3184 #endif /* AFS_NAMEI_ENV */
3186 #if defined(AFS_DEMAND_ATTACH_FS)
3187 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
3189 if (!VCanScheduleSalvage()) {
3190 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3192 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER |
3193 VOL_SALVAGE_NO_OFFLINE);
3198 /* volume operation in progress */
3199 goto unlocked_error;
3201 #else /* AFS_DEMAND_ATTACH_FS */
3203 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3204 goto unlocked_error;
3206 #endif /* AFS_DEMAND_ATTACH_FS */
3208 if (V_needsSalvaged(vp)) {
3209 if (vp->specialStatus)
3210 vp->specialStatus = 0;
3212 #if defined(AFS_DEMAND_ATTACH_FS)
3213 if (!VCanScheduleSalvage()) {
3214 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
3216 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER |
3217 VOL_SALVAGE_NO_OFFLINE);
3220 #else /* AFS_DEMAND_ATTACH_FS */
3222 #endif /* AFS_DEMAND_ATTACH_FS */
3228 vp->nextVnodeUnique = V_uniquifier(vp);
3230 if (VShouldCheckInUse(mode) && V_inUse(vp) && VolumeWriteable(vp)) {
3231 if (!V_needsSalvaged(vp)) {
3232 V_needsSalvaged(vp) = 1;
3233 VUpdateVolume_r(ec, vp, 0);
3235 #if defined(AFS_DEMAND_ATTACH_FS)
3236 if (!VCanScheduleSalvage()) {
3237 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3239 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER |
3240 VOL_SALVAGE_NO_OFFLINE);
3243 #else /* AFS_DEMAND_ATTACH_FS */
3244 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3246 #endif /* AFS_DEMAND_ATTACH_FS */
3251 if (programType == fileServer && V_destroyMe(vp) == DESTROY_ME) {
3252 /* Only check destroyMe if we are the fileserver, since the
3253 * volserver et al sometimes need to work with volumes with
3254 * destroyMe set. Examples are 'temporary' volumes the
3255 * volserver creates, and when we create a volume (destroyMe
3256 * is set on creation; sometimes a separate volserver
3257 * transaction is created to clear destroyMe).
3260 #if defined(AFS_DEMAND_ATTACH_FS)
3261 /* schedule a salvage so the volume goes away on disk */
3262 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER |
3263 VOL_SALVAGE_NO_OFFLINE);
3264 VChangeState_r(vp, VOL_STATE_ERROR);
3267 #endif /* AFS_DEMAND_ATTACH_FS */
3268 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
3273 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
3274 #ifndef BITMAP_LATER
3275 if (programType == fileServer && VolumeWriteable(vp)) {
3277 for (i = 0; i < nVNODECLASSES; i++) {
3278 VGetBitmap_r(ec, vp, i);
3280 #ifdef AFS_DEMAND_ATTACH_FS
3281 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER |
3282 VOL_SALVAGE_NO_OFFLINE);
3284 #endif /* AFS_DEMAND_ATTACH_FS */
3285 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
3291 #endif /* BITMAP_LATER */
3293 if (VInit >= 2 && V_needsCallback(vp)) {
3294 if (V_BreakVolumeCallbacks) {
3295 Log("VAttachVolume: Volume %lu was changed externally; breaking callbacks\n",
3296 afs_printable_uint32_lu(V_id(vp)));
3297 V_needsCallback(vp) = 0;
3299 (*V_BreakVolumeCallbacks) (V_id(vp));
3302 VUpdateVolume_r(ec, vp, 0);
3304 #ifdef FSSYNC_BUILD_CLIENT
3305 else if (VCanUseFSSYNC()) {
3306 afs_int32 fsync_code;
3308 V_needsCallback(vp) = 0;
3310 fsync_code = FSYNC_VolOp(V_id(vp), NULL, FSYNC_VOL_BREAKCBKS, FSYNC_WHATEVER, NULL);
3314 V_needsCallback(vp) = 1;
3315 Log("Error trying to tell the fileserver to break callbacks for "
3316 "changed volume %lu; error code %ld\n",
3317 afs_printable_uint32_lu(V_id(vp)),
3318 afs_printable_int32_ld(fsync_code));
3320 VUpdateVolume_r(ec, vp, 0);
3323 #endif /* FSSYNC_BUILD_CLIENT */
3326 Log("VAttachVolume: error %d clearing needsCallback on volume "
3327 "%lu; needs salvage\n", (int)*ec,
3328 afs_printable_uint32_lu(V_id(vp)));
3329 #ifdef AFS_DEMAND_ATTACH_FS
3330 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER |
3331 VOL_SALVAGE_NO_OFFLINE);
3333 #else /* !AFS_DEMAND_ATTACH_FS */
3335 #endif /* !AFS_DEMAND_ATTACh_FS */
3340 if (programType == fileServer) {
3341 if (vp->specialStatus)
3342 vp->specialStatus = 0;
3343 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
3344 V_inUse(vp) = fileServer;
3345 V_offlineMessage(vp)[0] = '\0';
3349 #ifdef AFS_DEMAND_ATTACH_FS
3350 /* Put the vol into PREATTACHED state, so if someone tries to
3351 * access it again, we try to attach, see that we're not blessed,
3352 * and give a VNOVOL error again. Putting it into UNATTACHED state
3353 * would result in a VOFFLINE error instead. */
3354 error_state = VOL_STATE_PREATTACHED;
3355 #endif /* AFS_DEMAND_ATTACH_FS */
3357 /* mimic e.g. GetVolume errors */
3358 if (!V_blessed(vp)) {
3359 Log("Volume %lu offline: not blessed\n", afs_printable_uint32_lu(V_id(vp)));
3360 FreeVolumeHeader(vp);
3361 } else if (!V_inService(vp)) {
3362 Log("Volume %lu offline: not in service\n", afs_printable_uint32_lu(V_id(vp)));
3363 FreeVolumeHeader(vp);
3365 Log("Volume %lu offline: needs salvage\n", afs_printable_uint32_lu(V_id(vp)));
3367 #ifdef AFS_DEMAND_ATTACH_FS
3368 error_state = VOL_STATE_ERROR;
3369 /* see if we can recover */
3370 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
3373 #ifdef AFS_DEMAND_ATTACH_FS
3379 #ifdef AFS_DEMAND_ATTACH_FS
3380 if ((mode != V_PEEK) && (mode != V_SECRETLY))
3381 V_inUse(vp) = programType;
3382 #endif /* AFS_DEMAND_ATTACH_FS */
3383 V_checkoutMode(vp) = mode;
3386 AddVolumeToHashTable(vp, V_id(vp));
3387 #ifdef AFS_DEMAND_ATTACH_FS
3388 if (VCanUnlockAttached() && (V_attachFlags(vp) & VOL_LOCKED)) {
3391 if ((programType != fileServer) ||
3392 (V_inUse(vp) == fileServer)) {
3393 AddVolumeToVByPList_r(vp);
3395 VChangeState_r(vp, VOL_STATE_ATTACHED);
3397 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3406 #ifdef AFS_DEMAND_ATTACH_FS
3407 if (!VIsErrorState(V_attachState(vp))) {
3408 VChangeState_r(vp, error_state);
3410 #endif /* AFS_DEMAND_ATTACH_FS */
3413 VReleaseVolumeHandles_r(vp);
3416 #ifdef AFS_DEMAND_ATTACH_FS
3423 #else /* !AFS_DEMAND_ATTACH_FS */
3425 #endif /* !AFS_DEMAND_ATTACH_FS */
3429 /* Attach an existing volume.
3430 The volume also normally goes online at this time.
3431 An offline volume must be reattached to make it go online.
3435 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
3439 retVal = VAttachVolume_r(ec, volumeId, mode);
3445 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
3448 VGetVolumePath(ec, volumeId, &part, &name);
3452 vp = VGetVolume_r(&error, volumeId);
3454 osi_Assert(V_inUse(vp) == 0);
3455 VDetachVolume_r(ec, vp);
3459 return VAttachVolumeByName_r(ec, part, name, mode);
3462 /* Increment a reference count to a volume, sans context swaps. Requires
3463 * possibly reading the volume header in from the disk, since there's
3464 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
3466 * N.B. This call can fail if we can't read in the header!! In this case
3467 * we still guarantee we won't context swap, but the ref count won't be
3468 * incremented (otherwise we'd violate the invariant).
3470 /* NOTE: with the demand attach fileserver extensions, the global lock
3471 * is dropped within VHold */
3472 #ifdef AFS_DEMAND_ATTACH_FS
3474 VHold_r(Volume * vp)
3478 VCreateReservation_r(vp);
3479 VWaitExclusiveState_r(vp);
3481 LoadVolumeHeader(&error, vp);
3483 VCancelReservation_r(vp);
3487 VCancelReservation_r(vp);
3490 #else /* AFS_DEMAND_ATTACH_FS */
3492 VHold_r(Volume * vp)
3496 LoadVolumeHeader(&error, vp);
3502 #endif /* AFS_DEMAND_ATTACH_FS */
3510 retVal = VHold_r(vp);
3517 /***************************************************/
3518 /* get and put volume routines */
3519 /***************************************************/
3522 * put back a heavyweight reference to a volume object.
3524 * @param[in] vp volume object pointer
3526 * @pre VOL_LOCK held
3528 * @post heavyweight volume reference put back.
3529 * depending on state, volume may have been taken offline,
3530 * detached, salvaged, freed, etc.
3532 * @internal volume package internal use only
3535 VPutVolume_r(Volume * vp)
3537 osi_Assert(--vp->nUsers >= 0);
3538 if (vp->nUsers == 0) {
3540 ReleaseVolumeHeader(vp->header);
3541 #ifdef AFS_DEMAND_ATTACH_FS
3542 if (!VCheckDetach(vp)) {
3546 #else /* AFS_DEMAND_ATTACH_FS */
3548 #endif /* AFS_DEMAND_ATTACH_FS */
3553 VPutVolume(Volume * vp)
3561 /* Get a pointer to an attached volume. The pointer is returned regardless
3562 of whether or not the volume is in service or on/off line. An error
3563 code, however, is returned with an indication of the volume's status */
3565 VGetVolume(Error * ec, Error * client_ec, VolId volumeId)
3569 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
3574 /* same as VGetVolume, but if a volume is waiting to go offline, we return
3575 * that it is actually offline, instead of waiting for it to go offline */
3577 VGetVolumeNoWait(Error * ec, Error * client_ec, VolId volumeId)
3581 retVal = GetVolume(ec, client_ec, volumeId, NULL, 1);
3587 VGetVolume_r(Error * ec, VolId volumeId)
3589 return GetVolume(ec, NULL, volumeId, NULL, 0);
3592 /* try to get a volume we've previously looked up */
3593 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
3595 VGetVolumeByVp_r(Error * ec, Volume * vp)
3597 return GetVolume(ec, NULL, vp->hashid, vp, 0);
3601 * private interface for getting a volume handle
3603 * @param[out] ec error code (0 if no error)
3604 * @param[out] client_ec wire error code to be given to clients
3605 * @param[in] volumeId ID of the volume we want
3606 * @param[in] hint optional hint for hash lookups, or NULL
3607 * @param[in] nowait 0 to wait for a 'goingOffline' volume to go offline
3608 * before returning, 1 to return immediately
3610 * @return a volume handle for the specified volume
3611 * @retval NULL an error occurred, or the volume is in such a state that
3612 * we cannot load a header or return any volume struct
3614 * @note for DAFS, caller must NOT hold a ref count on 'hint'
3617 GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint, int nowait)
3620 /* pull this profiling/debugging code out of regular builds */
3622 #define VGET_CTR_INC(x) x++
3623 unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
3624 0, V7 = 0, V8 = 0, V9 = 0;
3625 unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
3627 #define VGET_CTR_INC(x)
3629 #ifdef AFS_DEMAND_ATTACH_FS
3630 Volume *avp, * rvp = hint;
3634 * if VInit is zero, the volume package dynamic
3635 * data structures have not been initialized yet,
3636 * and we must immediately return an error
3642 *client_ec = VOFFLINE;
3647 #ifdef AFS_DEMAND_ATTACH_FS
3649 VCreateReservation_r(rvp);
3651 #endif /* AFS_DEMAND_ATTACH_FS */
3659 vp = VLookupVolume_r(ec, volumeId, vp);
3665 #ifdef AFS_DEMAND_ATTACH_FS
3666 if (rvp && (rvp != vp)) {
3667 /* break reservation on old vp */
3668 VCancelReservation_r(rvp);
3671 #endif /* AFS_DEMAND_ATTACH_FS */
3677 /* Until we have reached an initialization level of 2
3678 * we don't know whether this volume exists or not.
3679 * We can't sleep and retry later because before a volume
3680 * is attached, the caller tries to get it first. Just
3681 * return VOFFLINE and the caller can choose whether to
3682 * retry the command or not. */
3692 IncUInt64(&VStats.hdr_gets);
3694 #ifdef AFS_DEMAND_ATTACH_FS
3695 /* block if someone else is performing an exclusive op on this volume */
3698 VCreateReservation_r(rvp);
3700 VWaitExclusiveState_r(vp);
3702 /* short circuit with VNOVOL in the following circumstances:
3705 * - VOL_STATE_SHUTTING_DOWN
3707 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
3708 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN) ||
3709 (V_attachState(vp) == VOL_STATE_GOING_OFFLINE)) {
3716 * short circuit with VOFFLINE for VOL_STATE_UNATTACHED and
3717 * VNOVOL for VOL_STATE_DELETED
3719 if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
3720 (V_attachState(vp) == VOL_STATE_DELETED)) {
3721 if (vp->specialStatus) {
3722 *ec = vp->specialStatus;
3723 } else if (V_attachState(vp) == VOL_STATE_DELETED) {
3732 /* allowable states:
3739 if (vp->salvage.requested) {
3740 VUpdateSalvagePriority_r(vp);
3743 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
3744 avp = VAttachVolumeByVp_r(ec, vp, 0);
3747 /* VAttachVolumeByVp_r can return a pointer
3748 * != the vp passed to it under certain
3749 * conditions; make sure we don't leak
3750 * reservations if that happens */
3752 VCancelReservation_r(rvp);
3754 VCreateReservation_r(rvp);
3764 if (!vp->pending_vol_op) {
3779 if (VIsSalvaging(vp) || (*ec == VSALVAGING)) {
3781 /* see CheckVnode() in afsfileprocs.c for an explanation
3782 * of this error code logic */
3783 afs_uint32 now = FT_ApproxTime();
3784 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
3787 *client_ec = VRESTARTING;
3796 #ifdef AFS_DEMAND_ATTACH_FS
3798 * this test MUST happen after VAttachVolymeByVp, so vol_op_state is
3799 * not VolOpRunningUnknown (attach2 would have converted it to Online
3803 /* only valid before/during demand attachment */
3804 osi_Assert(!vp->pending_vol_op || vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
3806 /* deny getvolume due to running mutually exclusive vol op */
3807 if (vp->pending_vol_op && vp->pending_vol_op->vol_op_state==FSSYNC_VolOpRunningOffline) {
3809 * volume cannot remain online during this volume operation.
3812 if (vp->specialStatus) {
3814 * special status codes outrank normal VOFFLINE code
3816 *ec = vp->specialStatus;
3818 *client_ec = vp->specialStatus;
3822 /* see CheckVnode() in afsfileprocs.c for an explanation
3823 * of this error code logic */
3824 afs_uint32 now = FT_ApproxTime();
3825 if ((vp->stats.last_vol_op + (10 * 60)) >= now) {
3828 *client_ec = VRESTARTING;
3833 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3834 FreeVolumeHeader(vp);
3838 #endif /* AFS_DEMAND_ATTACH_FS */
3840 LoadVolumeHeader(ec, vp);
3843 /* Only log the error if it was a totally unexpected error. Simply
3844 * a missing inode is likely to be caused by the volume being deleted */
3845 if (errno != ENXIO || LogLevel)
3846 Log("Volume %u: couldn't reread volume header\n",
3848 #ifdef AFS_DEMAND_ATTACH_FS
3849 if (VCanScheduleSalvage()) {
3850 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3855 #else /* AFS_DEMAND_ATTACH_FS */
3858 #endif /* AFS_DEMAND_ATTACH_FS */
3863 if (vp->shuttingDown) {
3870 if (programType == fileServer) {
3872 if (vp->goingOffline && !nowait) {
3874 #ifdef AFS_DEMAND_ATTACH_FS
3875 /* wait for the volume to go offline */
3876 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
3877 VWaitStateChange_r(vp);
3879 #elif defined(AFS_PTHREAD_ENV)
3880 VOL_CV_WAIT(&vol_put_volume_cond);
3881 #else /* AFS_PTHREAD_ENV */
3882 LWP_WaitProcess(VPutVolume);
3883 #endif /* AFS_PTHREAD_ENV */
3886 if (vp->specialStatus) {
3888 *ec = vp->specialStatus;
3889 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3892 } else if (V_inUse(vp) == 0 || vp->goingOffline) {
3903 #ifdef AFS_DEMAND_ATTACH_FS
3904 /* if no error, bump nUsers */
3907 VLRU_UpdateAccess_r(vp);
3910 VCancelReservation_r(rvp);
3913 if (client_ec && !*client_ec) {
3916 #else /* AFS_DEMAND_ATTACH_FS */
3917 /* if no error, bump nUsers */
3924 #endif /* AFS_DEMAND_ATTACH_FS */
3927 osi_Assert(vp || *ec);
3932 /***************************************************/
3933 /* Volume offline/detach routines */
3934 /***************************************************/
3936 /* caller MUST hold a heavyweight ref on vp */
3937 #ifdef AFS_DEMAND_ATTACH_FS
3939 VTakeOffline_r(Volume * vp)
3943 osi_Assert(vp->nUsers > 0);
3944 osi_Assert(programType == fileServer);
3946 VCreateReservation_r(vp);
3947 VWaitExclusiveState_r(vp);
3949 vp->goingOffline = 1;
3950 V_needsSalvaged(vp) = 1;
3952 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
3953 VCancelReservation_r(vp);
3955 #else /* AFS_DEMAND_ATTACH_FS */
3957 VTakeOffline_r(Volume * vp)
3959 osi_Assert(vp->nUsers > 0);
3960 osi_Assert(programType == fileServer);
3962 vp->goingOffline = 1;
3963 V_needsSalvaged(vp) = 1;
3965 #endif /* AFS_DEMAND_ATTACH_FS */
3968 VTakeOffline(Volume * vp)
3976 * force a volume offline.
3978 * @param[in] vp volume object pointer
3979 * @param[in] flags flags (see note below)
3981 * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
3982 * used when VUpdateVolume_r needs to call VForceOffline_r
3983 * (which in turn would normally call VUpdateVolume_r)
3985 * @see VUpdateVolume_r
3987 * @pre VOL_LOCK must be held.
3988 * for DAFS, caller must hold ref.
3990 * @note for DAFS, it _is safe_ to call this function from an
3993 * @post needsSalvaged flag is set.
3994 * for DAFS, salvage is requested.
3995 * no further references to the volume through the volume
3996 * package will be honored.
3997 * all file descriptor and vnode caches are invalidated.
3999 * @warning this is a heavy-handed interface. it results in
4000 * a volume going offline regardless of the current
4001 * reference count state.
4003 * @internal volume package internal use only
4006 VForceOffline_r(Volume * vp, int flags)
4010 #ifdef AFS_DEMAND_ATTACH_FS
4011 VChangeState_r(vp, VOL_STATE_ERROR);
4016 strcpy(V_offlineMessage(vp),
4017 "Forced offline due to internal error: volume needs to be salvaged");
4018 Log("Volume %u forced offline: it needs salvaging!\n", V_id(vp));
4021 vp->goingOffline = 0;
4022 V_needsSalvaged(vp) = 1;
4023 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
4024 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
4027 #ifdef AFS_DEMAND_ATTACH_FS
4028 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
4029 #endif /* AFS_DEMAND_ATTACH_FS */
4031 #ifdef AFS_PTHREAD_ENV
4032 CV_BROADCAST(&vol_put_volume_cond);
4033 #else /* AFS_PTHREAD_ENV */
4034 LWP_NoYieldSignal(VPutVolume);
4035 #endif /* AFS_PTHREAD_ENV */
4037 VReleaseVolumeHandles_r(vp);
4041 * force a volume offline.
4043 * @param[in] vp volume object pointer
4045 * @see VForceOffline_r
4048 VForceOffline(Volume * vp)
4051 VForceOffline_r(vp, 0);
4055 /* The opposite of VAttachVolume. The volume header is written to disk, with
4056 the inUse bit turned off. A copy of the header is maintained in memory,
4057 however (which is why this is VOffline, not VDetach).
4060 VOffline_r(Volume * vp, char *message)
4062 #ifndef AFS_DEMAND_ATTACH_FS
4064 VolumeId vid = V_id(vp);
4067 osi_Assert(programType != volumeUtility && programType != volumeServer);
4072 if (V_offlineMessage(vp)[0] == '\0')
4073 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4074 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4076 vp->goingOffline = 1;
4077 #ifdef AFS_DEMAND_ATTACH_FS
4078 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4079 VCreateReservation_r(vp);
4082 /* wait for the volume to go offline */
4083 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
4084 VWaitStateChange_r(vp);
4086 VCancelReservation_r(vp);
4087 #else /* AFS_DEMAND_ATTACH_FS */
4089 vp = VGetVolume_r(&error, vid); /* Wait for it to go offline */
4090 if (vp) /* In case it was reattached... */
4092 #endif /* AFS_DEMAND_ATTACH_FS */
4095 #ifdef AFS_DEMAND_ATTACH_FS
4097 * Take a volume offline in order to perform a volume operation.
4099 * @param[inout] ec address in which to store error code
4100 * @param[in] vp volume object pointer
4101 * @param[in] message volume offline status message
4104 * - VOL_LOCK is held
4105 * - caller MUST hold a heavyweight ref on vp
4108 * - volume is taken offline
4109 * - if possible, volume operation is promoted to running state
4110 * - on failure, *ec is set to nonzero
4112 * @note Although this function does not return any value, it may
4113 * still fail to promote our pending volume operation to
4114 * a running state. Any caller MUST check the value of *ec,
4115 * and MUST NOT blindly assume success.
4117 * @warning if the caller does not hold a lightweight ref on vp,
4118 * then it MUST NOT reference vp after this function
4119 * returns to the caller.
4121 * @internal volume package internal use only
4124 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
4126 osi_Assert(vp->pending_vol_op);
4132 if (V_offlineMessage(vp)[0] == '\0')
4133 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4134 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4136 vp->goingOffline = 1;
4137 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4138 VCreateReservation_r(vp);
4141 /* Wait for the volume to go offline */
4142 while (!VIsOfflineState(V_attachState(vp))) {
4143 /* do not give corrupted volumes to the volserver */
4144 if (vp->salvage.requested && vp->pending_vol_op->com.programType != salvageServer) {
4148 VWaitStateChange_r(vp);
4152 VCancelReservation_r(vp);
4154 #endif /* AFS_DEMAND_ATTACH_FS */
4157 VOffline(Volume * vp, char *message)
4160 VOffline_r(vp, message);
4164 /* This gets used for the most part by utility routines that don't want
4165 * to keep all the volume headers around. Generally, the file server won't
4166 * call this routine, because then the offline message in the volume header
4167 * (or other information) won't be available to clients. For NAMEI, also
4168 * close the file handles. However, the fileserver does call this during
4169 * an attach following a volume operation.
4172 VDetachVolume_r(Error * ec, Volume * vp)
4174 #ifdef FSSYNC_BUILD_CLIENT
4176 struct DiskPartition64 *tpartp;
4177 int notifyServer = 0;
4178 int useDone = FSYNC_VOL_ON;
4180 if (VCanUseFSSYNC()) {
4181 notifyServer = vp->needsPutBack;
4182 if (V_destroyMe(vp) == DESTROY_ME)
4183 useDone = FSYNC_VOL_LEAVE_OFF;
4184 #ifdef AFS_DEMAND_ATTACH_FS
4185 else if (!V_blessed(vp) || !V_inService(vp))
4186 useDone = FSYNC_VOL_LEAVE_OFF;
4189 tpartp = vp->partition;
4191 #endif /* FSSYNC_BUILD_CLIENT */
4193 *ec = 0; /* always "succeeds" */
4194 DeleteVolumeFromHashTable(vp);
4195 vp->shuttingDown = 1;
4196 #ifdef AFS_DEMAND_ATTACH_FS
4197 DeleteVolumeFromVByPList_r(vp);
4199 VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
4201 if (programType != fileServer)
4203 #endif /* AFS_DEMAND_ATTACH_FS */
4205 /* Will be detached sometime in the future--this is OK since volume is offline */
4207 /* XXX the following code should really be moved to VCheckDetach() since the volume
4208 * is not technically detached until the refcounts reach zero
4210 #ifdef FSSYNC_BUILD_CLIENT
4211 if (VCanUseFSSYNC() && notifyServer) {
4212 if (notifyServer == VOL_PUTBACK_DELETE) {
4213 /* Only send FSYNC_VOL_DONE if the volume was actually deleted.
4214 * volserver code will set needsPutBack to VOL_PUTBACK_DELETE
4215 * to signify a deleted volume. */
4216 useDone = FSYNC_VOL_DONE;
4219 * Note: The server is not notified in the case of a bogus volume
4220 * explicitly to make it possible to create a volume, do a partial
4221 * restore, then abort the operation without ever putting the volume
4222 * online. This is essential in the case of a volume move operation
4223 * between two partitions on the same server. In that case, there
4224 * would be two instances of the same volume, one of them bogus,
4225 * which the file server would attempt to put on line
4227 FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
4228 /* XXX this code path is only hit by volume utilities, thus
4229 * V_BreakVolumeCallbacks will always be NULL. if we really
4230 * want to break callbacks in this path we need to use FSYNC_VolOp() */
4232 /* Dettaching it so break all callbacks on it */
4233 if (V_BreakVolumeCallbacks) {
4234 Log("volume %u detached; breaking all call backs\n", volume);
4235 (*V_BreakVolumeCallbacks) (volume);
4239 #endif /* FSSYNC_BUILD_CLIENT */
4243 VDetachVolume(Error * ec, Volume * vp)
4246 VDetachVolume_r(ec, vp);
4251 /***************************************************/
4252 /* Volume fd/inode handle closing routines */
4253 /***************************************************/
4255 /* For VDetachVolume, we close all cached file descriptors, but keep
4256 * the Inode handles in case we need to read from a busy volume.
4258 /* for demand attach, caller MUST hold ref count on vp */
4260 VCloseVolumeHandles_r(Volume * vp)
4262 #ifdef AFS_DEMAND_ATTACH_FS
4263 VolState state_save;
4265 state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
4270 * XXX need to investigate whether we can perform
4271 * DFlushVolume outside of vol_glock_mutex...
4273 * VCloseVnodeFiles_r drops the glock internally */
4274 DFlushVolume(vp->hashid);
4275 VCloseVnodeFiles_r(vp);
4277 #ifdef AFS_DEMAND_ATTACH_FS
4281 /* Too time consuming and unnecessary for the volserver */
4282 if (programType == fileServer) {
4283 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4284 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4285 IH_CONDSYNC(vp->diskDataHandle);
4287 IH_CONDSYNC(vp->linkHandle);
4288 #endif /* AFS_NT40_ENV */
4291 IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
4292 IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
4293 IH_REALLYCLOSE(vp->diskDataHandle);
4294 IH_REALLYCLOSE(vp->linkHandle);
4296 #ifdef AFS_DEMAND_ATTACH_FS
4297 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4302 VChangeState_r(vp, state_save);
4306 /* For both VForceOffline and VOffline, we close all relevant handles.
4307 * For VOffline, if we re-attach the volume, the files may possible be
4308 * different than before.
4310 /* for demand attach, caller MUST hold a ref count on vp */
4312 VReleaseVolumeHandles_r(Volume * vp)
4314 #ifdef AFS_DEMAND_ATTACH_FS
4315 VolState state_save;
4317 state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
4320 /* XXX need to investigate whether we can perform
4321 * DFlushVolume outside of vol_glock_mutex... */
4322 DFlushVolume(vp->hashid);
4324 VReleaseVnodeFiles_r(vp); /* releases the glock internally */
4326 #ifdef AFS_DEMAND_ATTACH_FS
4330 /* Too time consuming and unnecessary for the volserver */
4331 if (programType == fileServer) {
4332 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4333 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4334 IH_CONDSYNC(vp->diskDataHandle);
4336 IH_CONDSYNC(vp->linkHandle);
4337 #endif /* AFS_NT40_ENV */
4340 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
4341 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
4342 IH_RELEASE(vp->diskDataHandle);
4343 IH_RELEASE(vp->linkHandle);
4345 #ifdef AFS_DEMAND_ATTACH_FS
4346 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4351 VChangeState_r(vp, state_save);
4356 /***************************************************/
4357 /* Volume write and fsync routines */
4358 /***************************************************/
4361 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
4363 #ifdef AFS_DEMAND_ATTACH_FS
4364 VolState state_save;
4366 if (flags & VOL_UPDATE_WAIT) {
4367 VCreateReservation_r(vp);
4368 VWaitExclusiveState_r(vp);
4373 if (programType == fileServer)
4375 (V_inUse(vp) ? V_nextVnodeUnique(vp) +
4376 200 : V_nextVnodeUnique(vp));
4378 #ifdef AFS_DEMAND_ATTACH_FS
4379 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4383 WriteVolumeHeader_r(ec, vp);
4385 #ifdef AFS_DEMAND_ATTACH_FS
4387 VChangeState_r(vp, state_save);
4388 if (flags & VOL_UPDATE_WAIT) {
4389 VCancelReservation_r(vp);
4394 Log("VUpdateVolume: error updating volume header, volume %u (%s)\n",
4395 V_id(vp), V_name(vp));
4396 /* try to update on-disk header,
4397 * while preventing infinite recursion */
4398 if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
4399 VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
4405 VUpdateVolume(Error * ec, Volume * vp)
4408 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4413 VSyncVolume_r(Error * ec, Volume * vp, int flags)
4417 #ifdef AFS_DEMAND_ATTACH_FS
4418 VolState state_save;
4421 if (flags & VOL_SYNC_WAIT) {
4422 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4424 VUpdateVolume_r(ec, vp, 0);
4427 #ifdef AFS_DEMAND_ATTACH_FS
4428 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4431 fdP = IH_OPEN(V_diskDataHandle(vp));
4432 osi_Assert(fdP != NULL);
4433 code = FDH_SYNC(fdP);
4434 osi_Assert(code == 0);
4436 #ifdef AFS_DEMAND_ATTACH_FS
4438 VChangeState_r(vp, state_save);
4444 VSyncVolume(Error * ec, Volume * vp)
4447 VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
4452 /***************************************************/
4453 /* Volume dealloaction routines */
4454 /***************************************************/
4456 #ifdef AFS_DEMAND_ATTACH_FS
4458 FreeVolume(Volume * vp)
4460 /* free the heap space, iff it's safe.
4461 * otherwise, pull it out of the hash table, so it
4462 * will get deallocated when all refs to it go away */
4463 if (!VCheckFree(vp)) {
4464 DeleteVolumeFromHashTable(vp);
4465 DeleteVolumeFromVByPList_r(vp);
4467 /* make sure we invalidate the header cache entry */
4468 FreeVolumeHeader(vp);
4471 #endif /* AFS_DEMAND_ATTACH_FS */
4474 ReallyFreeVolume(Volume * vp)
4479 #ifdef AFS_DEMAND_ATTACH_FS
4481 VChangeState_r(vp, VOL_STATE_FREED);
4482 if (vp->pending_vol_op)
4483 free(vp->pending_vol_op);
4484 #endif /* AFS_DEMAND_ATTACH_FS */
4485 for (i = 0; i < nVNODECLASSES; i++)
4486 if (vp->vnodeIndex[i].bitmap)
4487 free(vp->vnodeIndex[i].bitmap);
4488 FreeVolumeHeader(vp);
4489 #ifndef AFS_DEMAND_ATTACH_FS
4490 DeleteVolumeFromHashTable(vp);
4491 #endif /* AFS_DEMAND_ATTACH_FS */
4495 /* check to see if we should shutdown this volume
4496 * returns 1 if volume was freed, 0 otherwise */
4497 #ifdef AFS_DEMAND_ATTACH_FS
4499 VCheckDetach(Volume * vp)
4504 if (vp->nUsers || vp->nWaiters)
4507 if (vp->shuttingDown) {
4509 if ((programType != fileServer) &&
4510 (V_inUse(vp) == programType) &&
4511 ((V_checkoutMode(vp) == V_VOLUPD) ||
4512 (V_checkoutMode(vp) == V_SECRETLY) ||
4513 ((V_checkoutMode(vp) == V_CLONE) &&
4514 (VolumeWriteable(vp))))) {
4516 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
4518 Log("VCheckDetach: volume header update for volume %u "
4519 "failed with errno %d\n", vp->hashid, errno);
4522 VReleaseVolumeHandles_r(vp);
4524 ReallyFreeVolume(vp);
4525 if (programType == fileServer) {
4526 CV_BROADCAST(&vol_put_volume_cond);
4531 #else /* AFS_DEMAND_ATTACH_FS */
4533 VCheckDetach(Volume * vp)
4541 if (vp->shuttingDown) {
4543 if ((programType != fileServer) &&
4544 (V_inUse(vp) == programType) &&
4545 ((V_checkoutMode(vp) == V_VOLUPD) ||
4546 (V_checkoutMode(vp) == V_SECRETLY) ||
4547 ((V_checkoutMode(vp) == V_CLONE) &&
4548 (VolumeWriteable(vp))))) {
4550 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
4552 Log("VCheckDetach: volume header update for volume %u failed with errno %d\n",
4556 VReleaseVolumeHandles_r(vp);
4557 ReallyFreeVolume(vp);
4558 if (programType == fileServer) {
4559 #if defined(AFS_PTHREAD_ENV)
4560 CV_BROADCAST(&vol_put_volume_cond);
4561 #else /* AFS_PTHREAD_ENV */
4562 LWP_NoYieldSignal(VPutVolume);
4563 #endif /* AFS_PTHREAD_ENV */
4568 #endif /* AFS_DEMAND_ATTACH_FS */
4570 /* check to see if we should offline this volume
4571 * return 1 if volume went offline, 0 otherwise */
4572 #ifdef AFS_DEMAND_ATTACH_FS
4574 VCheckOffline(Volume * vp)
4578 if (vp->goingOffline && !vp->nUsers) {
4580 osi_Assert(programType == fileServer);
4581 osi_Assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
4582 (V_attachState(vp) != VOL_STATE_FREED) &&
4583 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
4584 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
4585 (V_attachState(vp) != VOL_STATE_DELETED));
4589 * VOL_STATE_GOING_OFFLINE
4590 * VOL_STATE_SHUTTING_DOWN
4591 * VIsErrorState(V_attachState(vp))
4592 * VIsExclusiveState(V_attachState(vp))
4595 VCreateReservation_r(vp);
4596 VChangeState_r(vp, VOL_STATE_OFFLINING);
4599 /* must clear the goingOffline flag before we drop the glock */
4600 vp->goingOffline = 0;
4605 /* perform async operations */
4606 VUpdateVolume_r(&error, vp, 0);
4607 VCloseVolumeHandles_r(vp);
4610 if (V_offlineMessage(vp)[0]) {
4611 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
4612 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
4613 V_offlineMessage(vp));
4615 Log("VOffline: Volume %lu (%s) is now offline\n",
4616 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
4620 /* invalidate the volume header cache entry */
4621 FreeVolumeHeader(vp);
4623 /* if nothing changed state to error or salvaging,
4624 * drop state to unattached */
4625 if (!VIsErrorState(V_attachState(vp))) {
4626 VChangeState_r(vp, VOL_STATE_UNATTACHED);
4628 VCancelReservation_r(vp);
4629 /* no usage of vp is safe beyond this point */
4633 #else /* AFS_DEMAND_ATTACH_FS */
4635 VCheckOffline(Volume * vp)
4639 if (vp->goingOffline && !vp->nUsers) {
4641 osi_Assert(programType == fileServer);
4644 vp->goingOffline = 0;
4646 VUpdateVolume_r(&error, vp, 0);
4647 VCloseVolumeHandles_r(vp);
4649 if (V_offlineMessage(vp)[0]) {
4650 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
4651 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
4652 V_offlineMessage(vp));
4654 Log("VOffline: Volume %lu (%s) is now offline\n",
4655 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
4658 FreeVolumeHeader(vp);
4659 #ifdef AFS_PTHREAD_ENV
4660 CV_BROADCAST(&vol_put_volume_cond);
4661 #else /* AFS_PTHREAD_ENV */
4662 LWP_NoYieldSignal(VPutVolume);
4663 #endif /* AFS_PTHREAD_ENV */
4667 #endif /* AFS_DEMAND_ATTACH_FS */
4669 /***************************************************/
4670 /* demand attach fs ref counting routines */
4671 /***************************************************/
4673 #ifdef AFS_DEMAND_ATTACH_FS
4674 /* the following two functions handle reference counting for
4675 * asynchronous operations on volume structs.
4677 * their purpose is to prevent a VDetachVolume or VShutdown
4678 * from free()ing the Volume struct during an async i/o op */
4680 /* register with the async volume op ref counter */
4681 /* VCreateReservation_r moved into inline code header because it
4682 * is now needed in vnode.c -- tkeiser 11/20/2007
4686 * decrement volume-package internal refcount.
4688 * @param vp volume object pointer
4690 * @internal volume package internal use only
4693 * @arg VOL_LOCK is held
4694 * @arg lightweight refcount held
4696 * @post volume waiters refcount is decremented; volume may
4697 * have been deallocated/shutdown/offlined/salvaged/
4698 * whatever during the process
4700 * @warning once you have tossed your last reference (you can acquire
4701 * lightweight refs recursively) it is NOT SAFE to reference
4702 * a volume object pointer ever again
4704 * @see VCreateReservation_r
4706 * @note DEMAND_ATTACH_FS only
4709 VCancelReservation_r(Volume * vp)
4711 osi_Assert(--vp->nWaiters >= 0);
4712 if (vp->nWaiters == 0) {
4714 if (!VCheckDetach(vp)) {
4721 /* check to see if we should free this volume now
4722 * return 1 if volume was freed, 0 otherwise */
4724 VCheckFree(Volume * vp)
4727 if ((vp->nUsers == 0) &&
4728 (vp->nWaiters == 0) &&
4729 !(V_attachFlags(vp) & (VOL_IN_HASH |
4733 ReallyFreeVolume(vp);
4738 #endif /* AFS_DEMAND_ATTACH_FS */
4741 /***************************************************/
4742 /* online volume operations routines */
4743 /***************************************************/
4745 #ifdef AFS_DEMAND_ATTACH_FS
4747 * register a volume operation on a given volume.
4749 * @param[in] vp volume object
4750 * @param[in] vopinfo volume operation info object
4752 * @pre VOL_LOCK is held
4754 * @post volume operation info object attached to volume object.
4755 * volume operation statistics updated.
4757 * @note by "attached" we mean a copy of the passed in object is made
4759 * @internal volume package internal use only
4762 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4764 FSSYNC_VolOp_info * info;
4766 /* attach a vol op info node to the volume struct */
4767 info = (FSSYNC_VolOp_info *) malloc(sizeof(FSSYNC_VolOp_info));
4768 osi_Assert(info != NULL);
4769 memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
4770 vp->pending_vol_op = info;
4773 vp->stats.last_vol_op = FT_ApproxTime();
4774 vp->stats.vol_ops++;
4775 IncUInt64(&VStats.vol_ops);
4781 * deregister the volume operation attached to this volume.
4783 * @param[in] vp volume object pointer
4785 * @pre VOL_LOCK is held
4787 * @post the volume operation info object is detached from the volume object
4789 * @internal volume package internal use only
4792 VDeregisterVolOp_r(Volume * vp)
4794 if (vp->pending_vol_op) {
4795 free(vp->pending_vol_op);
4796 vp->pending_vol_op = NULL;
4800 #endif /* AFS_DEMAND_ATTACH_FS */
4803 * determine whether it is safe to leave a volume online during
4804 * the volume operation described by the vopinfo object.
4806 * @param[in] vp volume object
4807 * @param[in] vopinfo volume operation info object
4809 * @return whether it is safe to leave volume online
4810 * @retval 0 it is NOT SAFE to leave the volume online
4811 * @retval 1 it is safe to leave the volume online during the operation
4814 * @arg VOL_LOCK is held
4815 * @arg disk header attached to vp (heavyweight ref on vp will guarantee
4816 * this condition is met)
4818 * @internal volume package internal use only
4821 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4823 return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
4824 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4825 (vopinfo->com.reason == V_READONLY ||
4826 (!VolumeWriteable(vp) &&
4827 (vopinfo->com.reason == V_CLONE ||
4828 vopinfo->com.reason == V_DUMP)))));
4832 * same as VVolOpLeaveOnline_r, but does not require a volume with an attached
4835 * @param[in] vp volume object
4836 * @param[in] vopinfo volume operation info object
4838 * @return whether it is safe to leave volume online
4839 * @retval 0 it is NOT SAFE to leave the volume online
4840 * @retval 1 it is safe to leave the volume online during the operation
4841 * @retval -1 unsure; volume header is required in order to know whether or
4842 * not is is safe to leave the volume online
4844 * @pre VOL_LOCK is held
4846 * @internal volume package internal use only
4849 VVolOpLeaveOnlineNoHeader_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4851 /* follow the logic in VVolOpLeaveOnline_r; this is the same, except
4852 * assume that we don't know VolumeWriteable; return -1 if the answer
4853 * depends on VolumeWriteable */
4855 if (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline) {
4858 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4859 vopinfo->com.reason == V_READONLY) {
4863 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4864 (vopinfo->com.reason == V_CLONE ||
4865 vopinfo->com.reason == V_DUMP)) {
4867 /* must know VolumeWriteable */
4874 * determine whether VBUSY should be set during this volume operation.
4876 * @param[in] vp volume object
4877 * @param[in] vopinfo volume operation info object
4879 * @return whether VBUSY should be set
4880 * @retval 0 VBUSY does NOT need to be set
4881 * @retval 1 VBUSY SHOULD be set
4883 * @pre VOL_LOCK is held
4885 * @internal volume package internal use only
4888 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4890 return ((vopinfo->com.command == FSYNC_VOL_OFF &&
4891 vopinfo->com.reason == FSYNC_SALVAGE) ||
4892 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4893 (vopinfo->com.reason == V_CLONE ||
4894 vopinfo->com.reason == V_DUMP)));
4898 /***************************************************/
4899 /* online salvager routines */
4900 /***************************************************/
4901 #if defined(AFS_DEMAND_ATTACH_FS)
4904 * offline a volume to let it be salvaged.
4906 * @param[in] vp Volume to offline
4908 * @return whether we offlined the volume successfully
4909 * @retval 0 volume was not offlined
4910 * @retval 1 volume is now offline
4912 * @note This is similar to VCheckOffline, but slightly different. We do not
4913 * deal with vp->goingOffline, and we try to avoid touching the volume
4914 * header except just to set needsSalvaged
4916 * @pre VOL_LOCK held
4917 * @pre vp->nUsers == 0
4918 * @pre V_attachState(vp) == VOL_STATE_SALVAGE_REQ
4921 VOfflineForSalvage_r(struct Volume *vp)
4925 VCreateReservation_r(vp);
4926 VWaitExclusiveState_r(vp);
4928 if (vp->nUsers || V_attachState(vp) == VOL_STATE_SALVAGING) {
4929 /* Someone's using the volume, or someone got to scheduling the salvage
4930 * before us. I don't think either of these should be possible, as we
4931 * should gain no new heavyweight references while we're trying to
4932 * salvage, but just to be sure... */
4933 VCancelReservation_r(vp);
4937 VChangeState_r(vp, VOL_STATE_OFFLINING);
4941 V_needsSalvaged(vp) = 1;
4942 /* ignore error; updating needsSalvaged is just best effort */
4943 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
4945 VCloseVolumeHandles_r(vp);
4947 FreeVolumeHeader(vp);
4949 /* volume has been effectively offlined; we can mark it in the SALVAGING
4950 * state now, which lets FSSYNC give it away */
4951 VChangeState_r(vp, VOL_STATE_SALVAGING);
4953 VCancelReservation_r(vp);
4959 * check whether a salvage needs to be performed on this volume.
4961 * @param[in] vp pointer to volume object
4963 * @return status code
4964 * @retval 0 no salvage scheduled
4965 * @retval 1 a salvage has been scheduled with the salvageserver
4967 * @pre VOL_LOCK is held
4969 * @post if salvage request flag is set and nUsers and nWaiters are zero,
4970 * then a salvage will be requested
4972 * @note this is one of the event handlers called by VCancelReservation_r
4974 * @note the caller must check if the volume needs to be freed after calling
4975 * this; the volume may not have any references or be on any lists after
4976 * we return, and we do not free it
4978 * @see VCancelReservation_r
4980 * @internal volume package internal use only.
4983 VCheckSalvage(Volume * vp)
4986 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
4989 if (!vp->salvage.requested) {
4993 /* prevent recursion; some of the code below creates and removes
4994 * lightweight refs, which can call VCheckSalvage */
4995 if (vp->salvage.scheduling) {
4998 vp->salvage.scheduling = 1;
5000 if (V_attachState(vp) == VOL_STATE_SALVAGE_REQ) {
5001 if (!VOfflineForSalvage_r(vp)) {
5002 vp->salvage.scheduling = 0;
5007 if (vp->salvage.requested) {
5008 VScheduleSalvage_r(vp);
5011 vp->salvage.scheduling = 0;
5012 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5017 * request volume salvage.
5019 * @param[out] ec computed client error code
5020 * @param[in] vp volume object pointer
5021 * @param[in] reason reason code (passed to salvageserver via SALVSYNC)
5022 * @param[in] flags see flags note below
5025 * VOL_SALVAGE_INVALIDATE_HEADER causes volume header cache entry
5026 * to be invalidated.
5028 * @pre VOL_LOCK is held.
5030 * @post volume state is changed.
5031 * for fileserver, salvage will be requested once refcount reaches zero.
5033 * @return operation status code
5034 * @retval 0 volume salvage will occur
5035 * @retval 1 volume salvage could not be scheduled
5039 * @note in the fileserver, this call does not synchronously schedule a volume
5040 * salvage. rather, it sets volume state so that when volume refcounts
5041 * reach zero, a volume salvage will occur. by "refcounts", we mean both
5042 * nUsers and nWaiters must be zero.
5044 * @internal volume package internal use only.
5047 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
5051 * for DAFS volume utilities that are not supposed to schedule salvages,
5052 * just transition to error state instead
5054 if (!VCanScheduleSalvage()) {
5055 VChangeState_r(vp, VOL_STATE_ERROR);
5060 if (programType != fileServer && !VCanUseFSSYNC()) {
5061 VChangeState_r(vp, VOL_STATE_ERROR);
5066 if (!vp->salvage.requested) {
5067 vp->salvage.requested = 1;
5068 vp->salvage.reason = reason;
5069 vp->stats.last_salvage = FT_ApproxTime();
5071 /* Note that it is not possible for us to reach this point if a
5072 * salvage is already running on this volume (even if the fileserver
5073 * was restarted during the salvage). If a salvage were running, the
5074 * salvager would have write-locked the volume header file, so when
5075 * we tried to lock the volume header, the lock would have failed,
5076 * and we would have failed during attachment prior to calling
5077 * VRequestSalvage. So we know that we can schedule salvages without
5078 * fear of a salvage already running for this volume. */
5080 if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
5082 /* if we don't need to offline the volume, we can go directly
5083 * to SALVAGING. SALVAGING says the volume is offline and is
5084 * either salvaging or ready to be handed to the salvager.
5085 * SALVAGE_REQ says that we want to salvage the volume, but we
5086 * are waiting for it to go offline first. */
5087 if (flags & VOL_SALVAGE_NO_OFFLINE) {
5088 VChangeState_r(vp, VOL_STATE_SALVAGING);
5090 VChangeState_r(vp, VOL_STATE_SALVAGE_REQ);
5091 if (vp->nUsers == 0) {
5092 /* normally VOfflineForSalvage_r would be called from
5093 * PutVolume et al when nUsers reaches 0, but if
5094 * it's already 0, just do it ourselves, since PutVolume
5095 * isn't going to get called */
5096 VOfflineForSalvage_r(vp);
5101 Log("VRequestSalvage: volume %u online salvaged too many times; forced offline.\n", vp->hashid);
5103 /* make sure neither VScheduleSalvage_r nor
5104 * VUpdateSalvagePriority_r try to schedule another salvage */
5105 vp->salvage.requested = vp->salvage.scheduled = 0;
5107 VChangeState_r(vp, VOL_STATE_ERROR);
5111 if (flags & VOL_SALVAGE_INVALIDATE_HEADER) {
5112 /* Instead of ReleaseVolumeHeader, we do FreeVolumeHeader()
5113 so that the the next VAttachVolumeByVp_r() invocation
5114 of attach2() will pull in a cached header
5115 entry and fail, then load a fresh one from disk and attach
5118 FreeVolumeHeader(vp);
5125 * update salvageserver scheduling priority for a volume.
5127 * @param[in] vp pointer to volume object
5129 * @return operation status
5131 * @retval 1 request denied, or SALVSYNC communications failure
5133 * @pre VOL_LOCK is held.
5135 * @post in-core salvage priority counter is incremented. if at least
5136 * SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
5137 * last SALVSYNC_RAISEPRIO request, we contact the salvageserver
5138 * to update its priority queue. if no salvage is scheduled,
5139 * this function is a no-op.
5141 * @note DAFS fileserver only
5143 * @note this should be called whenever a VGetVolume fails due to a
5144 * pending salvage request
5146 * @todo should set exclusive state and drop glock around salvsync call
5148 * @internal volume package internal use only.
5151 VUpdateSalvagePriority_r(Volume * vp)
5155 #ifdef SALVSYNC_BUILD_CLIENT
5160 now = FT_ApproxTime();
5162 /* update the salvageserver priority queue occasionally so that
5163 * frequently requested volumes get moved to the head of the queue
5165 if ((vp->salvage.scheduled) &&
5166 (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
5167 code = SALVSYNC_SalvageVolume(vp->hashid,
5168 VPartitionPath(vp->partition),
5173 vp->stats.last_salvage_req = now;
5174 if (code != SYNC_OK) {
5178 #endif /* SALVSYNC_BUILD_CLIENT */
5183 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5185 /* A couple of little helper functions. These return true if we tried to
5186 * use this mechanism to schedule a salvage, false if we haven't tried.
5187 * If we did try a salvage then the results are contained in code.
5191 try_SALVSYNC(Volume *vp, char *partName, int *code) {
5192 #ifdef SALVSYNC_BUILD_CLIENT
5193 if (VCanUseSALVSYNC()) {
5194 Log("Scheduling salvage for volume %lu on part %s over SALVSYNC\n",
5195 afs_printable_uint32_lu(vp->hashid), partName);
5197 /* can't use V_id() since there's no guarantee
5198 * we have the disk data header at this point */
5199 *code = SALVSYNC_SalvageVolume(vp->hashid,
5212 try_FSSYNC(Volume *vp, char *partName, int *code) {
5213 #ifdef FSSYNC_BUILD_CLIENT
5214 if (VCanUseFSSYNC()) {
5215 Log("Scheduling salvage for volume %lu on part %s over FSSYNC\n",
5216 afs_printable_uint32_lu(vp->hashid), partName);
5219 * If we aren't the fileserver, tell the fileserver the volume
5220 * needs to be salvaged. We could directly tell the
5221 * salvageserver, but the fileserver keeps track of some stats
5222 * related to salvages, and handles some other salvage-related
5223 * complications for us.
5225 *code = FSYNC_VolOp(vp->hashid, partName,
5226 FSYNC_VOL_FORCE_ERROR, FSYNC_SALVAGE, NULL);
5229 #endif /* FSSYNC_BUILD_CLIENT */
5234 * schedule a salvage with the salvage server or fileserver.
5236 * @param[in] vp pointer to volume object
5238 * @return operation status
5239 * @retval 0 salvage scheduled successfully
5240 * @retval 1 salvage not scheduled, or SALVSYNC/FSSYNC com error
5243 * @arg VOL_LOCK is held.
5244 * @arg nUsers and nWaiters should be zero.
5246 * @post salvageserver or fileserver is sent a salvage request
5248 * @note If we are the fileserver, the request will be sent to the salvage
5249 * server over SALVSYNC. If we are not the fileserver, the request will be
5250 * sent to the fileserver over FSSYNC (FSYNC_VOL_FORCE_ERROR/FSYNC_SALVAGE).
5252 * @note the caller must check if the volume needs to be freed after calling
5253 * this; the volume may not have any references or be on any lists after
5254 * we return, and we do not free it
5258 * @internal volume package internal use only.
5261 VScheduleSalvage_r(Volume * vp)
5265 VolState state_save;
5266 VThreadOptions_t * thread_opts;
5269 osi_Assert(VCanUseSALVSYNC() || VCanUseFSSYNC());
5271 if (vp->nWaiters || vp->nUsers) {
5275 /* prevent endless salvage,attach,salvage,attach,... loops */
5276 if (vp->stats.salvages >= SALVAGE_COUNT_MAX)
5280 * don't perform salvsync ops on certain threads
5282 thread_opts = pthread_getspecific(VThread_key);
5283 if (thread_opts == NULL) {
5284 thread_opts = &VThread_defaults;
5286 if (thread_opts->disallow_salvsync || vol_disallow_salvsync) {
5290 if (vp->salvage.scheduled) {
5294 VCreateReservation_r(vp);
5295 VWaitExclusiveState_r(vp);
5298 * XXX the scheduling process should really be done asynchronously
5299 * to avoid fssync deadlocks
5301 if (!vp->salvage.scheduled) {
5302 /* if we haven't previously scheduled a salvage, do so now
5304 * set the volume to an exclusive state and drop the lock
5305 * around the SALVSYNC call
5307 strlcpy(partName, VPartitionPath(vp->partition), sizeof(partName));
5308 state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
5311 osi_Assert(try_SALVSYNC(vp, partName, &code) ||
5312 try_FSSYNC(vp, partName, &code));
5315 VChangeState_r(vp, state_save);
5317 if (code == SYNC_OK) {
5318 vp->salvage.scheduled = 1;
5319 vp->stats.last_salvage_req = FT_ApproxTime();
5320 if (VCanUseSALVSYNC()) {
5321 /* don't record these stats for non-fileservers; let the
5322 * fileserver take care of these */
5323 vp->stats.salvages++;
5324 IncUInt64(&VStats.salvages);
5329 case SYNC_BAD_COMMAND:
5330 case SYNC_COM_ERROR:
5333 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5334 "denied\n", afs_printable_uint32_lu(vp->hashid));
5337 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5338 "received unknown protocol error %d\n",
5339 afs_printable_uint32_lu(vp->hashid), code);
5343 if (VCanUseFSSYNC()) {
5344 VChangeState_r(vp, VOL_STATE_ERROR);
5349 /* NB: this is cancelling the reservation we obtained above, but we do
5350 * not call VCancelReservation_r, since that may trigger the vp dtor,
5351 * possibly free'ing the vp. We need to keep the vp around after
5352 * this, as the caller may reference vp without any refs. Instead, it
5353 * is the duty of the caller to inspect 'vp' after we return to see if
5354 * needs to be freed. */
5355 osi_Assert(--vp->nWaiters >= 0);
5358 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5360 #ifdef SALVSYNC_BUILD_CLIENT
5363 * connect to the salvageserver SYNC service.
5365 * @return operation status
5369 * @post connection to salvageserver SYNC service established
5371 * @see VConnectSALV_r
5372 * @see VDisconnectSALV
5373 * @see VReconnectSALV
5380 retVal = VConnectSALV_r();
5386 * connect to the salvageserver SYNC service.
5388 * @return operation status
5392 * @pre VOL_LOCK is held.
5394 * @post connection to salvageserver SYNC service established
5397 * @see VDisconnectSALV_r
5398 * @see VReconnectSALV_r
5399 * @see SALVSYNC_clientInit
5401 * @internal volume package internal use only.
5404 VConnectSALV_r(void)
5406 return SALVSYNC_clientInit();
5410 * disconnect from the salvageserver SYNC service.
5412 * @return operation status
5415 * @pre client should have a live connection to the salvageserver
5417 * @post connection to salvageserver SYNC service destroyed
5419 * @see VDisconnectSALV_r
5421 * @see VReconnectSALV
5424 VDisconnectSALV(void)
5427 VDisconnectSALV_r();
5433 * disconnect from the salvageserver SYNC service.
5435 * @return operation status
5439 * @arg VOL_LOCK is held.
5440 * @arg client should have a live connection to the salvageserver.
5442 * @post connection to salvageserver SYNC service destroyed
5444 * @see VDisconnectSALV
5445 * @see VConnectSALV_r
5446 * @see VReconnectSALV_r
5447 * @see SALVSYNC_clientFinis
5449 * @internal volume package internal use only.
5452 VDisconnectSALV_r(void)
5454 return SALVSYNC_clientFinis();
5458 * disconnect and then re-connect to the salvageserver SYNC service.
5460 * @return operation status
5464 * @pre client should have a live connection to the salvageserver
5466 * @post old connection is dropped, and a new one is established
5469 * @see VDisconnectSALV
5470 * @see VReconnectSALV_r
5473 VReconnectSALV(void)
5477 retVal = VReconnectSALV_r();
5483 * disconnect and then re-connect to the salvageserver SYNC service.
5485 * @return operation status
5490 * @arg VOL_LOCK is held.
5491 * @arg client should have a live connection to the salvageserver.
5493 * @post old connection is dropped, and a new one is established
5495 * @see VConnectSALV_r
5496 * @see VDisconnectSALV
5497 * @see VReconnectSALV
5498 * @see SALVSYNC_clientReconnect
5500 * @internal volume package internal use only.
5503 VReconnectSALV_r(void)
5505 return SALVSYNC_clientReconnect();
5507 #endif /* SALVSYNC_BUILD_CLIENT */
5508 #endif /* AFS_DEMAND_ATTACH_FS */
5511 /***************************************************/
5512 /* FSSYNC routines */
5513 /***************************************************/
5515 /* This must be called by any volume utility which needs to run while the
5516 file server is also running. This is separated from VInitVolumePackage2 so
5517 that a utility can fork--and each of the children can independently
5518 initialize communication with the file server */
5519 #ifdef FSSYNC_BUILD_CLIENT
5521 * connect to the fileserver SYNC service.
5523 * @return operation status
5528 * @arg VInit must equal 2.
5529 * @arg Program Type must not be fileserver or salvager.
5531 * @post connection to fileserver SYNC service established
5534 * @see VDisconnectFS
5535 * @see VChildProcReconnectFS
5542 retVal = VConnectFS_r();
5548 * connect to the fileserver SYNC service.
5550 * @return operation status
5555 * @arg VInit must equal 2.
5556 * @arg Program Type must not be fileserver or salvager.
5557 * @arg VOL_LOCK is held.
5559 * @post connection to fileserver SYNC service established
5562 * @see VDisconnectFS_r
5563 * @see VChildProcReconnectFS_r
5565 * @internal volume package internal use only.
5571 osi_Assert((VInit == 2) &&
5572 (programType != fileServer) &&
5573 (programType != salvager));
5574 rc = FSYNC_clientInit();
5582 * disconnect from the fileserver SYNC service.
5585 * @arg client should have a live connection to the fileserver.
5586 * @arg VOL_LOCK is held.
5587 * @arg Program Type must not be fileserver or salvager.
5589 * @post connection to fileserver SYNC service destroyed
5591 * @see VDisconnectFS
5593 * @see VChildProcReconnectFS_r
5595 * @internal volume package internal use only.
5598 VDisconnectFS_r(void)
5600 osi_Assert((programType != fileServer) &&
5601 (programType != salvager));
5602 FSYNC_clientFinis();
5607 * disconnect from the fileserver SYNC service.
5610 * @arg client should have a live connection to the fileserver.
5611 * @arg Program Type must not be fileserver or salvager.
5613 * @post connection to fileserver SYNC service destroyed
5615 * @see VDisconnectFS_r
5617 * @see VChildProcReconnectFS
5628 * connect to the fileserver SYNC service from a child process following a fork.
5630 * @return operation status
5635 * @arg VOL_LOCK is held.
5636 * @arg current FSYNC handle is shared with a parent process
5638 * @post current FSYNC handle is discarded and a new connection to the
5639 * fileserver SYNC service is established
5641 * @see VChildProcReconnectFS
5643 * @see VDisconnectFS_r
5645 * @internal volume package internal use only.
5648 VChildProcReconnectFS_r(void)
5650 return FSYNC_clientChildProcReconnect();
5654 * connect to the fileserver SYNC service from a child process following a fork.
5656 * @return operation status
5660 * @pre current FSYNC handle is shared with a parent process
5662 * @post current FSYNC handle is discarded and a new connection to the
5663 * fileserver SYNC service is established
5665 * @see VChildProcReconnectFS_r
5667 * @see VDisconnectFS
5670 VChildProcReconnectFS(void)
5674 ret = VChildProcReconnectFS_r();
5678 #endif /* FSSYNC_BUILD_CLIENT */
5681 /***************************************************/
5682 /* volume bitmap routines */
5683 /***************************************************/
5686 * allocate a vnode bitmap number for the vnode
5688 * @param[out] ec error code
5689 * @param[in] vp volume object pointer
5690 * @param[in] index vnode index number for the vnode
5691 * @param[in] flags flag values described in note
5693 * @note for DAFS, flags parameter controls locking behavior.
5694 * If (flags & VOL_ALLOC_BITMAP_WAIT) is set, then this function
5695 * will create a reservation and block on any other exclusive
5696 * operations. Otherwise, this function assumes the caller
5697 * already has exclusive access to vp, and we just change the
5700 * @pre VOL_LOCK held
5702 * @return bit number allocated
5708 VAllocBitmapEntry_r(Error * ec, Volume * vp,
5709 struct vnodeIndex *index, int flags)
5713 #ifdef AFS_DEMAND_ATTACH_FS
5714 VolState state_save;
5715 #endif /* AFS_DEMAND_ATTACH_FS */
5719 /* This test is probably redundant */
5720 if (!VolumeWriteable(vp)) {
5721 *ec = (bit32) VREADONLY;
5725 #ifdef AFS_DEMAND_ATTACH_FS
5726 if (flags & VOL_ALLOC_BITMAP_WAIT) {
5727 VCreateReservation_r(vp);
5728 VWaitExclusiveState_r(vp);
5730 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
5731 #endif /* AFS_DEMAND_ATTACH_FS */
5734 if ((programType == fileServer) && !index->bitmap) {
5736 #ifndef AFS_DEMAND_ATTACH_FS
5737 /* demand attach fs uses the volume state to avoid races.
5738 * specialStatus field is not used at all */
5740 if (vp->specialStatus == VBUSY) {
5741 if (vp->goingOffline) { /* vos dump waiting for the volume to
5742 * go offline. We probably come here
5743 * from AddNewReadableResidency */
5746 while (vp->specialStatus == VBUSY) {
5747 #ifdef AFS_PTHREAD_ENV
5751 #else /* !AFS_PTHREAD_ENV */
5753 #endif /* !AFS_PTHREAD_ENV */
5757 #endif /* !AFS_DEMAND_ATTACH_FS */
5759 if (!index->bitmap) {
5760 #ifndef AFS_DEMAND_ATTACH_FS
5761 vp->specialStatus = VBUSY; /* Stop anyone else from using it. */
5762 #endif /* AFS_DEMAND_ATTACH_FS */
5763 for (i = 0; i < nVNODECLASSES; i++) {
5764 VGetBitmap_r(ec, vp, i);
5766 #ifdef AFS_DEMAND_ATTACH_FS
5767 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
5768 #else /* AFS_DEMAND_ATTACH_FS */
5769 DeleteVolumeFromHashTable(vp);
5770 vp->shuttingDown = 1; /* Let who has it free it. */
5771 vp->specialStatus = 0;
5772 #endif /* AFS_DEMAND_ATTACH_FS */
5776 #ifndef AFS_DEMAND_ATTACH_FS
5778 vp->specialStatus = 0; /* Allow others to have access. */
5779 #endif /* AFS_DEMAND_ATTACH_FS */
5782 #endif /* BITMAP_LATER */
5784 #ifdef AFS_DEMAND_ATTACH_FS
5786 #endif /* AFS_DEMAND_ATTACH_FS */
5787 bp = index->bitmap + index->bitmapOffset;
5788 ep = index->bitmap + index->bitmapSize;
5790 if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
5792 index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
5795 o = ffs(~*bp) - 1; /* ffs is documented in BSTRING(3) */
5797 ret = ((bp - index->bitmap) * 8 + o);
5798 #ifdef AFS_DEMAND_ATTACH_FS
5800 #endif /* AFS_DEMAND_ATTACH_FS */
5803 bp += sizeof(bit32) /* i.e. 4 */ ;
5805 /* No bit map entry--must grow bitmap */
5807 realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
5808 osi_Assert(bp != NULL);
5810 bp += index->bitmapSize;
5811 memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
5812 index->bitmapOffset = index->bitmapSize;
5813 index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
5815 ret = index->bitmapOffset * 8;
5816 #ifdef AFS_DEMAND_ATTACH_FS
5818 #endif /* AFS_DEMAND_ATTACH_FS */
5821 #ifdef AFS_DEMAND_ATTACH_FS
5822 VChangeState_r(vp, state_save);
5823 if (flags & VOL_ALLOC_BITMAP_WAIT) {
5824 VCancelReservation_r(vp);
5826 #endif /* AFS_DEMAND_ATTACH_FS */
5831 VAllocBitmapEntry(Error * ec, Volume * vp, struct vnodeIndex * index)
5835 retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
5841 VFreeBitMapEntry_r(Error * ec, struct vnodeIndex *index,
5844 unsigned int offset;
5850 #endif /* BITMAP_LATER */
5851 offset = bitNumber >> 3;
5852 if (offset >= index->bitmapSize) {
5856 if (offset < index->bitmapOffset)
5857 index->bitmapOffset = offset & ~3; /* Truncate to nearest bit32 */
5858 *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
5862 VFreeBitMapEntry(Error * ec, struct vnodeIndex *index,
5866 VFreeBitMapEntry_r(ec, index, bitNumber);
5870 /* this function will drop the glock internally.
5871 * for old pthread fileservers, this is safe thanks to vbusy.
5873 * for demand attach fs, caller must have already called
5874 * VCreateReservation_r and VWaitExclusiveState_r */
5876 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
5878 StreamHandle_t *file;
5879 afs_sfsize_t nVnodes, size;
5880 struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
5881 struct vnodeIndex *vip = &vp->vnodeIndex[class];
5882 struct VnodeDiskObject *vnode;
5883 unsigned int unique = 0;
5887 #endif /* BITMAP_LATER */
5888 #ifdef AFS_DEMAND_ATTACH_FS
5889 VolState state_save;
5890 #endif /* AFS_DEMAND_ATTACH_FS */
5894 #ifdef AFS_DEMAND_ATTACH_FS
5895 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
5896 #endif /* AFS_DEMAND_ATTACH_FS */
5899 fdP = IH_OPEN(vip->handle);
5900 osi_Assert(fdP != NULL);
5901 file = FDH_FDOPEN(fdP, "r");
5902 osi_Assert(file != NULL);
5903 vnode = (VnodeDiskObject *) malloc(vcp->diskSize);
5904 osi_Assert(vnode != NULL);
5905 size = OS_SIZE(fdP->fd_fd);
5906 osi_Assert(size != -1);
5907 nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
5909 vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4; /* The 10 is a little extra so
5910 * a few files can be created in this volume,
5911 * the whole thing is rounded up to nearest 4
5912 * bytes, because the bit map allocator likes
5915 BitMap = (byte *) calloc(1, vip->bitmapSize);
5916 osi_Assert(BitMap != NULL);
5917 #else /* BITMAP_LATER */
5918 vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
5919 osi_Assert(vip->bitmap != NULL);
5920 vip->bitmapOffset = 0;
5921 #endif /* BITMAP_LATER */
5922 if (STREAM_ASEEK(file, vcp->diskSize) != -1) {
5924 for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
5925 if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
5927 if (vnode->type != vNull) {
5928 if (vnode->vnodeMagic != vcp->magic) {
5929 Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
5934 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
5935 #else /* BITMAP_LATER */
5936 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
5937 #endif /* BITMAP_LATER */
5938 if (unique <= vnode->uniquifier)
5939 unique = vnode->uniquifier + 1;
5941 #ifndef AFS_PTHREAD_ENV
5942 if ((bitNumber & 0x00ff) == 0x0ff) { /* every 256 iterations */
5945 #endif /* !AFS_PTHREAD_ENV */
5948 if (vp->nextVnodeUnique < unique) {
5949 Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
5952 /* Paranoia, partly justified--I think fclose after fdopen
5953 * doesn't seem to close fd. In any event, the documentation
5954 * doesn't specify, so it's safer to close it twice.
5962 /* There may have been a racing condition with some other thread, both
5963 * creating the bitmaps for this volume. If the other thread was faster
5964 * the pointer to bitmap should already be filled and we can free ours.
5966 if (vip->bitmap == NULL) {
5967 vip->bitmap = BitMap;
5968 vip->bitmapOffset = 0;
5970 free((byte *) BitMap);
5971 #endif /* BITMAP_LATER */
5972 #ifdef AFS_DEMAND_ATTACH_FS
5973 VChangeState_r(vp, state_save);
5974 #endif /* AFS_DEMAND_ATTACH_FS */
5978 /***************************************************/
5979 /* Volume Path and Volume Number utility routines */
5980 /***************************************************/
5983 * find the first occurrence of a volume header file and return the path.
5985 * @param[out] ec outbound error code
5986 * @param[in] volumeId volume id to find
5987 * @param[out] partitionp pointer to disk partition path string
5988 * @param[out] namep pointer to volume header file name string
5990 * @post path to first occurrence of volume header is returned in partitionp
5991 * and namep, or ec is set accordingly.
5993 * @warning this function is NOT re-entrant -- partitionp and namep point to
5994 * static data segments
5996 * @note if a volume utility inadvertently leaves behind a stale volume header
5997 * on a vice partition, it is possible for callers to get the wrong one,
5998 * depending on the order of the disk partition linked list.
6002 VGetVolumePath(Error * ec, VolId volumeId, char **partitionp, char **namep)
6004 static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
6005 char path[VMAXPATHLEN];
6007 struct DiskPartition64 *dp;
6011 (void)afs_snprintf(&name[1], (sizeof name) - 1, VFORMAT, afs_printable_uint32_lu(volumeId));
6012 for (dp = DiskPartitionList; dp; dp = dp->next) {
6013 struct afs_stat status;
6014 strcpy(path, VPartitionPath(dp));
6016 if (afs_stat(path, &status) == 0) {
6017 strcpy(partition, dp->name);
6024 *partitionp = *namep = NULL;
6026 *partitionp = partition;
6032 * extract a volume number from a volume header filename string.
6034 * @param[in] name volume header filename string
6036 * @return volume number
6038 * @note the string must be of the form VFORMAT. the only permissible
6039 * deviation is a leading '/' character.
6044 VolumeNumber(char *name)
6048 return atoi(name + 1);
6052 * compute the volume header filename.
6054 * @param[in] volumeId
6056 * @return volume header filename
6058 * @post volume header filename string is constructed
6060 * @warning this function is NOT re-entrant -- the returned string is
6061 * stored in a static char array. see VolumeExternalName_r
6062 * for a re-entrant equivalent.
6064 * @see VolumeExternalName_r
6066 * @deprecated due to the above re-entrancy warning, this interface should
6067 * be considered deprecated. Please use VolumeExternalName_r
6071 VolumeExternalName(VolumeId volumeId)
6073 static char name[VMAXPATHLEN];
6074 (void)afs_snprintf(name, sizeof name, VFORMAT, afs_printable_uint32_lu(volumeId));
6079 * compute the volume header filename.
6081 * @param[in] volumeId
6082 * @param[inout] name array in which to store filename
6083 * @param[in] len length of name array
6085 * @return result code from afs_snprintf
6087 * @see VolumeExternalName
6090 * @note re-entrant equivalent of VolumeExternalName
6093 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
6095 return afs_snprintf(name, len, VFORMAT, afs_printable_uint32_lu(volumeId));
6099 /***************************************************/
6100 /* Volume Usage Statistics routines */
6101 /***************************************************/
6103 #if OPENAFS_VOL_STATS
6104 #define OneDay (86400) /* 24 hours' worth of seconds */
6106 #define OneDay (24*60*60) /* 24 hours */
6107 #endif /* OPENAFS_VOL_STATS */
6110 Midnight(time_t t) {
6111 struct tm local, *l;
6114 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
6115 l = localtime_r(&t, &local);
6121 /* the following is strictly speaking problematic on the
6122 switching day to daylight saving time, after the switch,
6123 as tm_isdst does not match. Similarly, on the looong day when
6124 switching back the OneDay check will not do what naively expected!
6125 The effects are minor, though, and more a matter of interpreting
6127 #ifndef AFS_PTHREAD_ENV
6130 local.tm_hour = local.tm_min=local.tm_sec = 0;
6131 midnight = mktime(&local);
6132 if (midnight != (time_t) -1) return(midnight);
6134 return( (t/OneDay)*OneDay );
6138 /*------------------------------------------------------------------------
6139 * [export] VAdjustVolumeStatistics
6142 * If we've passed midnight, we need to update all the day use
6143 * statistics as well as zeroing the detailed volume statistics
6144 * (if we are implementing them).
6147 * vp : Pointer to the volume structure describing the lucky
6148 * volume being considered for update.
6154 * Nothing interesting.
6158 *------------------------------------------------------------------------*/
6161 VAdjustVolumeStatistics_r(Volume * vp)
6163 unsigned int now = FT_ApproxTime();
6165 if (now - V_dayUseDate(vp) > OneDay) {
6168 ndays = (now - V_dayUseDate(vp)) / OneDay;
6169 for (i = 6; i > ndays - 1; i--)
6170 V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
6171 for (i = 0; i < ndays - 1 && i < 7; i++)
6172 V_weekUse(vp)[i] = 0;
6174 V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
6176 V_dayUseDate(vp) = Midnight(now);
6178 #if OPENAFS_VOL_STATS
6180 * All we need to do is bzero the entire VOL_STATS_BYTES of
6181 * the detailed volume statistics area.
6183 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
6184 #endif /* OPENAFS_VOL_STATS */
6187 /*It's been more than a day of collection */
6189 * Always return happily.
6192 } /*VAdjustVolumeStatistics */
6195 VAdjustVolumeStatistics(Volume * vp)
6199 retVal = VAdjustVolumeStatistics_r(vp);
6205 VBumpVolumeUsage_r(Volume * vp)
6207 unsigned int now = FT_ApproxTime();
6208 V_accessDate(vp) = now;
6209 if (now - V_dayUseDate(vp) > OneDay)
6210 VAdjustVolumeStatistics_r(vp);
6212 * Save the volume header image to disk after every 128 bumps to dayUse.
6214 if ((V_dayUse(vp)++ & 127) == 0) {
6216 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
6221 VBumpVolumeUsage(Volume * vp)
6224 VBumpVolumeUsage_r(vp);
6229 VSetDiskUsage_r(void)
6231 #ifndef AFS_DEMAND_ATTACH_FS
6232 static int FifteenMinuteCounter = 0;
6236 /* NOTE: Don't attempt to access the partitions list until the
6237 * initialization level indicates that all volumes are attached,
6238 * which implies that all partitions are initialized. */
6239 #ifdef AFS_PTHREAD_ENV
6240 VOL_CV_WAIT(&vol_vinit_cond);
6241 #else /* AFS_PTHREAD_ENV */
6243 #endif /* AFS_PTHREAD_ENV */
6246 VResetDiskUsage_r();
6248 #ifndef AFS_DEMAND_ATTACH_FS
6249 if (++FifteenMinuteCounter == 3) {
6250 FifteenMinuteCounter = 0;
6253 #endif /* !AFS_DEMAND_ATTACH_FS */
6265 /***************************************************/
6266 /* Volume Update List routines */
6267 /***************************************************/
6269 /* The number of minutes that a volume hasn't been updated before the
6270 * "Dont salvage" flag in the volume header will be turned on */
6271 #define SALVAGE_INTERVAL (10*60)
6276 * volume update list functionality has been moved into the VLRU
6277 * the DONT_SALVAGE flag is now set during VLRU demotion
6280 #ifndef AFS_DEMAND_ATTACH_FS
6281 static VolumeId *UpdateList = NULL; /* Pointer to array of Volume ID's */
6282 static int nUpdatedVolumes = 0; /* Updated with entry in UpdateList, salvage after crash flag on */
6283 static int updateSize = 0; /* number of entries possible */
6284 #define UPDATE_LIST_SIZE 128 /* initial size increment (must be a power of 2!) */
6285 #endif /* !AFS_DEMAND_ATTACH_FS */
6288 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
6291 vp->updateTime = FT_ApproxTime();
6292 if (V_dontSalvage(vp) == 0)
6294 V_dontSalvage(vp) = 0;
6295 VSyncVolume_r(ec, vp, 0);
6296 #ifdef AFS_DEMAND_ATTACH_FS
6297 V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
6298 #else /* !AFS_DEMAND_ATTACH_FS */
6301 if (UpdateList == NULL) {
6302 updateSize = UPDATE_LIST_SIZE;
6303 UpdateList = (VolumeId *) malloc(sizeof(VolumeId) * updateSize);
6305 if (nUpdatedVolumes == updateSize) {
6307 if (updateSize > 524288) {
6308 Log("warning: there is likely a bug in the volume update scanner\n");
6312 (VolumeId *) realloc(UpdateList,
6313 sizeof(VolumeId) * updateSize);
6316 osi_Assert(UpdateList != NULL);
6317 UpdateList[nUpdatedVolumes++] = V_id(vp);
6318 #endif /* !AFS_DEMAND_ATTACH_FS */
6321 #ifndef AFS_DEMAND_ATTACH_FS
6323 VScanUpdateList(void)
6328 afs_uint32 now = FT_ApproxTime();
6329 /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
6330 for (i = gap = 0; i < nUpdatedVolumes; i++) {
6332 UpdateList[i - gap] = UpdateList[i];
6334 /* XXX this routine needlessly messes up the Volume LRU by
6335 * breaking the LRU temporal-locality assumptions.....
6336 * we should use a special volume header allocator here */
6337 vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
6340 } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
6341 V_dontSalvage(vp) = DONT_SALVAGE;
6342 VUpdateVolume_r(&error, vp, 0); /* No need to fsync--not critical */
6350 #ifndef AFS_PTHREAD_ENV
6352 #endif /* !AFS_PTHREAD_ENV */
6354 nUpdatedVolumes -= gap;
6356 #endif /* !AFS_DEMAND_ATTACH_FS */
6359 /***************************************************/
6360 /* Volume LRU routines */
6361 /***************************************************/
6366 * with demand attach fs, we attempt to soft detach(1)
6367 * volumes which have not been accessed in a long time
6368 * in order to speed up fileserver shutdown
6370 * (1) by soft detach we mean a process very similar
6371 * to VOffline, except the final state of the
6372 * Volume will be VOL_STATE_PREATTACHED, instead
6373 * of the usual VOL_STATE_UNATTACHED
6375 #ifdef AFS_DEMAND_ATTACH_FS
6377 /* implementation is reminiscent of a generational GC
6379 * queue 0 is newly attached volumes. this queue is
6380 * sorted by attach timestamp
6382 * queue 1 is volumes that have been around a bit
6383 * longer than queue 0. this queue is sorted by
6386 * queue 2 is volumes tha have been around the longest.
6387 * this queue is unsorted
6389 * queue 3 is volumes that have been marked as
6390 * candidates for soft detachment. this queue is
6393 #define VLRU_GENERATIONS 3 /**< number of generations in VLRU */
6394 #define VLRU_QUEUES 5 /**< total number of VLRU queues */
6397 * definition of a VLRU queue.
6400 volatile struct rx_queue q;
6407 * main VLRU data structure.
6410 struct VLRU_q q[VLRU_QUEUES]; /**< VLRU queues */
6413 /** time interval (in seconds) between promotion passes for
6414 * each young generation queue. */
6415 afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
6417 /** time interval (in seconds) between soft detach candidate
6418 * scans for each generation queue.
6420 * scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
6421 * we perform a soft detach pass. */
6422 afs_uint32 scan_interval[VLRU_GENERATIONS+1];
6424 /* scheduler state */
6425 int next_idx; /**< next queue to receive attention */
6426 afs_uint32 last_promotion[VLRU_GENERATIONS-1]; /**< timestamp of last promotion scan */
6427 afs_uint32 last_scan[VLRU_GENERATIONS+1]; /**< timestamp of last detach scan */
6429 int scanner_state; /**< state of scanner thread */
6430 pthread_cond_t cv; /**< state transition CV */
6433 /** global VLRU state */
6434 static struct VLRU volume_LRU;
6437 * defined states for VLRU scanner thread.
6440 VLRU_SCANNER_STATE_OFFLINE = 0, /**< vlru scanner thread is offline */
6441 VLRU_SCANNER_STATE_ONLINE = 1, /**< vlru scanner thread is online */
6442 VLRU_SCANNER_STATE_SHUTTING_DOWN = 2, /**< vlru scanner thread is shutting down */
6443 VLRU_SCANNER_STATE_PAUSING = 3, /**< vlru scanner thread is getting ready to pause */
6444 VLRU_SCANNER_STATE_PAUSED = 4 /**< vlru scanner thread is paused */
6445 } vlru_thread_state_t;
6447 /* vlru disk data header stuff */
6448 #define VLRU_DISK_MAGIC 0x7a8b9cad /**< vlru disk entry magic number */
6449 #define VLRU_DISK_VERSION 1 /**< vlru disk entry version number */
6451 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
6452 #define VLRU_DUMP_EXPIRATION_TIME (60*60*24*7) /* expire vlru data after 1 week */
6455 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
6456 * soft detachment. */
6457 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
6459 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
6460 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
6462 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
6463 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
6465 /** VLRU control flag. non-zero value implies VLRU subsystem is activated. */
6466 static afs_uint32 VLRU_enabled = 1;
6468 /* queue synchronization routines */
6469 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
6470 static void VLRU_EndExclusive_r(struct VLRU_q * q);
6471 static void VLRU_Wait_r(struct VLRU_q * q);
6474 * set VLRU subsystem tunable parameters.
6476 * @param[in] option tunable option to modify
6477 * @param[in] val new value for tunable parameter
6479 * @pre @c VInitVolumePackage2 has not yet been called.
6481 * @post tunable parameter is modified
6485 * @note valid option parameters are:
6486 * @arg @c VLRU_SET_THRESH
6487 * set the period of inactivity after which
6488 * volumes are eligible for soft detachment
6489 * @arg @c VLRU_SET_INTERVAL
6490 * set the time interval between calls
6491 * to the volume LRU "garbage collector"
6492 * @arg @c VLRU_SET_MAX
6493 * set the max number of volumes to deallocate
6497 VLRU_SetOptions(int option, afs_uint32 val)
6499 if (option == VLRU_SET_THRESH) {
6500 VLRU_offline_thresh = val;
6501 } else if (option == VLRU_SET_INTERVAL) {
6502 VLRU_offline_interval = val;
6503 } else if (option == VLRU_SET_MAX) {
6504 VLRU_offline_max = val;
6505 } else if (option == VLRU_SET_ENABLED) {
6508 VLRU_ComputeConstants();
6512 * compute VLRU internal timing parameters.
6514 * @post VLRU scanner thread internal timing parameters are computed
6516 * @note computes internal timing parameters based upon user-modifiable
6517 * tunable parameters.
6521 * @internal volume package internal use only.
6524 VLRU_ComputeConstants(void)
6526 afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
6528 /* compute the candidate scan interval */
6529 volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
6531 /* compute the promotion intervals */
6532 volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
6533 volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
6536 /* compute the gen 0 scan interval */
6537 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
6539 /* compute the gen 0 scan interval */
6540 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
6545 * initialize VLRU subsystem.
6547 * @pre this function has not yet been called
6549 * @post VLRU subsystem is initialized and VLRU scanner thread is starting
6553 * @internal volume package internal use only.
6559 pthread_attr_t attrs;
6562 if (!VLRU_enabled) {
6563 Log("VLRU: disabled\n");
6567 /* initialize each of the VLRU queues */
6568 for (i = 0; i < VLRU_QUEUES; i++) {
6569 queue_Init(&volume_LRU.q[i]);
6570 volume_LRU.q[i].len = 0;
6571 volume_LRU.q[i].busy = 0;
6572 CV_INIT(&volume_LRU.q[i].cv, "vol lru", CV_DEFAULT, 0);
6575 /* setup the timing constants */
6576 VLRU_ComputeConstants();
6578 /* XXX put inside LogLevel check? */
6579 Log("VLRU: starting scanner with the following configuration parameters:\n");
6580 Log("VLRU: offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
6581 Log("VLRU: running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
6582 Log("VLRU: taking up to %d volumes offline per pass\n", VLRU_offline_max);
6583 Log("VLRU: scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
6584 Log("VLRU: scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
6585 Log("VLRU: scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
6587 /* start up the VLRU scanner */
6588 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
6589 if (programType == fileServer) {
6590 CV_INIT(&volume_LRU.cv, "vol lru", CV_DEFAULT, 0);
6591 osi_Assert(pthread_attr_init(&attrs) == 0);
6592 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
6593 osi_Assert(pthread_create(&tid, &attrs, &VLRU_ScannerThread, NULL) == 0);
6598 * initialize the VLRU-related fields of a newly allocated volume object.
6600 * @param[in] vp pointer to volume object
6603 * @arg @c VOL_LOCK is held.
6604 * @arg volume object is not on a VLRU queue.
6606 * @post VLRU fields are initialized to indicate that volume object is not
6607 * currently registered with the VLRU subsystem
6611 * @internal volume package interal use only.
6614 VLRU_Init_Node_r(Volume * vp)
6619 osi_Assert(queue_IsNotOnQueue(&vp->vlru));
6620 vp->vlru.idx = VLRU_QUEUE_INVALID;
6624 * add a volume object to a VLRU queue.
6626 * @param[in] vp pointer to volume object
6629 * @arg @c VOL_LOCK is held.
6630 * @arg caller MUST hold a lightweight ref on @p vp.
6631 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
6633 * @post the volume object is added to the appropriate VLRU queue
6635 * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
6636 * then the volume is added to that queue. Otherwise, the value
6637 * @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
6638 * volume is added to the NEW generation queue.
6640 * @note @c VOL_LOCK may be dropped internally
6642 * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
6643 * during the add operation, and is restored to the previous
6644 * state prior to return.
6648 * @internal volume package internal use only.
6651 VLRU_Add_r(Volume * vp)
6654 VolState state_save;
6659 if (queue_IsOnQueue(&vp->vlru))
6662 state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
6665 if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
6666 idx = VLRU_QUEUE_NEW;
6669 VLRU_Wait_r(&volume_LRU.q[idx]);
6671 /* repeat check since VLRU_Wait_r may have dropped
6673 if (queue_IsNotOnQueue(&vp->vlru)) {
6675 queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
6676 volume_LRU.q[idx].len++;
6677 V_attachFlags(vp) |= VOL_ON_VLRU;
6678 vp->stats.last_promote = FT_ApproxTime();
6681 VChangeState_r(vp, state_save);
6685 * delete a volume object from a VLRU queue.
6687 * @param[in] vp pointer to volume object
6690 * @arg @c VOL_LOCK is held.
6691 * @arg caller MUST hold a lightweight ref on @p vp.
6692 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
6694 * @post volume object is removed from the VLRU queue
6696 * @note @c VOL_LOCK may be dropped internally
6700 * @todo We should probably set volume state to something exlcusive
6701 * (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
6703 * @internal volume package internal use only.
6706 VLRU_Delete_r(Volume * vp)
6713 if (queue_IsNotOnQueue(&vp->vlru))
6719 if (idx == VLRU_QUEUE_INVALID)
6721 VLRU_Wait_r(&volume_LRU.q[idx]);
6722 } while (idx != vp->vlru.idx);
6724 /* now remove from the VLRU and update
6725 * the appropriate counter */
6726 queue_Remove(&vp->vlru);
6727 volume_LRU.q[idx].len--;
6728 vp->vlru.idx = VLRU_QUEUE_INVALID;
6729 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
6733 * tell the VLRU subsystem that a volume was just accessed.
6735 * @param[in] vp pointer to volume object
6738 * @arg @c VOL_LOCK is held
6739 * @arg caller MUST hold a lightweight ref on @p vp
6740 * @arg caller MUST NOT hold exclusive ownership of any VLRU queue
6742 * @post volume VLRU access statistics are updated. If the volume was on
6743 * the VLRU soft detach candidate queue, it is moved to the NEW
6746 * @note @c VOL_LOCK may be dropped internally
6750 * @internal volume package internal use only.
6753 VLRU_UpdateAccess_r(Volume * vp)
6755 Volume * rvp = NULL;
6760 if (queue_IsNotOnQueue(&vp->vlru))
6763 osi_Assert(V_attachFlags(vp) & VOL_ON_VLRU);
6765 /* update the access timestamp */
6766 vp->stats.last_get = FT_ApproxTime();
6769 * if the volume is on the soft detach candidate
6770 * list, we need to safely move it back to a
6771 * regular generation. this has to be done
6772 * carefully so we don't race against the scanner
6776 /* if this volume is on the soft detach candidate queue,
6777 * then grab exclusive access to the necessary queues */
6778 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
6780 VCreateReservation_r(rvp);
6782 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
6783 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
6784 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6785 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6788 /* make sure multiple threads don't race to update */
6789 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
6790 VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
6794 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6795 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
6796 VCancelReservation_r(rvp);
6801 * switch a volume between two VLRU queues.
6803 * @param[in] vp pointer to volume object
6804 * @param[in] new_idx index of VLRU queue onto which the volume will be moved
6805 * @param[in] append controls whether the volume will be appended or
6806 * prepended to the queue. A nonzero value means it will
6807 * be appended; zero means it will be prepended.
6809 * @pre The new (and old, if applicable) queue(s) must either be owned
6810 * exclusively by the calling thread for asynchronous manipulation,
6811 * or the queue(s) must be quiescent and VOL_LOCK must be held.
6812 * Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
6813 * for further details of the queue asynchronous processing mechanism.
6815 * @post If the volume object was already on a VLRU queue, it is
6816 * removed from the queue. Depending on the value of the append
6817 * parameter, the volume object is either appended or prepended
6818 * to the VLRU queue referenced by the new_idx parameter.
6822 * @see VLRU_BeginExclusive_r
6823 * @see VLRU_EndExclusive_r
6826 * @internal volume package internal use only.
6829 VLRU_SwitchQueues(Volume * vp, int new_idx, int append)
6831 if (queue_IsNotOnQueue(&vp->vlru))
6834 queue_Remove(&vp->vlru);
6835 volume_LRU.q[vp->vlru.idx].len--;
6837 /* put the volume back on the correct generational queue */
6839 queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
6841 queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
6844 volume_LRU.q[new_idx].len++;
6845 vp->vlru.idx = new_idx;
6849 * VLRU background thread.
6851 * The VLRU Scanner Thread is responsible for periodically scanning through
6852 * each VLRU queue looking for volumes which should be moved to another
6853 * queue, or soft detached.
6855 * @param[in] args unused thread arguments parameter
6857 * @return unused thread return value
6858 * @retval NULL always
6860 * @internal volume package internal use only.
6863 VLRU_ScannerThread(void * args)
6865 afs_uint32 now, min_delay, delay;
6866 int i, min_idx, min_op, overdue, state;
6868 /* set t=0 for promotion cycle to be
6869 * fileserver startup */
6870 now = FT_ApproxTime();
6871 for (i=0; i < VLRU_GENERATIONS-1; i++) {
6872 volume_LRU.last_promotion[i] = now;
6875 /* don't start the scanner until VLRU_offline_thresh
6876 * plus a small delay for VInitVolumePackage2 to finish
6879 sleep(VLRU_offline_thresh + 60);
6881 /* set t=0 for scan cycle to be now */
6882 now = FT_ApproxTime();
6883 for (i=0; i < VLRU_GENERATIONS+1; i++) {
6884 volume_LRU.last_scan[i] = now;
6888 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
6889 volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
6892 while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
6893 /* check to see if we've been asked to pause */
6894 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
6895 volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
6896 CV_BROADCAST(&volume_LRU.cv);
6898 VOL_CV_WAIT(&volume_LRU.cv);
6899 } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
6902 /* scheduling can happen outside the glock */
6905 /* figure out what is next on the schedule */
6907 /* figure out a potential schedule for the new generation first */
6909 min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
6912 if (min_delay > volume_LRU.scan_interval[0]) {
6913 /* unsigned overflow -- we're overdue to run this scan */
6918 /* if we're not overdue for gen 0, figure out schedule for candidate gen */
6920 i = VLRU_QUEUE_CANDIDATE;
6921 delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
6922 if (delay < min_delay) {
6926 if (delay > volume_LRU.scan_interval[i]) {
6927 /* unsigned overflow -- we're overdue to run this scan */
6934 /* if we're still not overdue for something, figure out schedules for promotions */
6935 for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
6936 delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
6937 if (delay < min_delay) {
6942 if (delay > volume_LRU.promotion_interval[i]) {
6943 /* unsigned overflow -- we're overdue to run this promotion */
6952 /* sleep as needed */
6957 /* do whatever is next */
6960 VLRU_Promote_r(min_idx);
6961 VLRU_Demote_r(min_idx+1);
6963 VLRU_Scan_r(min_idx);
6965 now = FT_ApproxTime();
6968 Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
6970 /* signal that scanner is down */
6971 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
6972 CV_BROADCAST(&volume_LRU.cv);
6978 * promote volumes from one VLRU generation to the next.
6980 * This routine scans a VLRU generation looking for volumes which are
6981 * eligible to be promoted to the next generation. All volumes which
6982 * meet the eligibility requirement are promoted.
6984 * Promotion eligibility is based upon meeting both of the following
6987 * @arg The volume has been accessed since the last promotion:
6988 * @c (vp->stats.last_get >= vp->stats.last_promote)
6989 * @arg The last promotion occurred at least
6990 * @c volume_LRU.promotion_interval[idx] seconds ago
6992 * As a performance optimization, promotions are "globbed". In other
6993 * words, we promote arbitrarily large contiguous sublists of elements
6996 * @param[in] idx VLRU queue index to scan
7000 * @internal VLRU internal use only.
7003 VLRU_Promote_r(int idx)
7005 int len, chaining, promote;
7006 afs_uint32 now, thresh;
7007 struct rx_queue *qp, *nqp;
7008 Volume * vp, *start = NULL, *end = NULL;
7010 /* get exclusive access to two chains, and drop the glock */
7011 VLRU_Wait_r(&volume_LRU.q[idx]);
7012 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7013 VLRU_Wait_r(&volume_LRU.q[idx+1]);
7014 VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
7017 thresh = volume_LRU.promotion_interval[idx];
7018 now = FT_ApproxTime();
7021 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7022 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7023 promote = (((vp->stats.last_promote + thresh) <= now) &&
7024 (vp->stats.last_get >= vp->stats.last_promote));
7032 /* promote and prepend chain */
7033 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7047 /* promote and prepend */
7048 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7052 volume_LRU.q[idx].len -= len;
7053 volume_LRU.q[idx+1].len += len;
7056 /* release exclusive access to the two chains */
7058 volume_LRU.last_promotion[idx] = now;
7059 VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
7060 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7063 /* run the demotions */
7065 VLRU_Demote_r(int idx)
7068 int len, chaining, demote;
7069 afs_uint32 now, thresh;
7070 struct rx_queue *qp, *nqp;
7071 Volume * vp, *start = NULL, *end = NULL;
7072 Volume ** salv_flag_vec = NULL;
7073 int salv_vec_offset = 0;
7075 osi_Assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
7077 /* get exclusive access to two chains, and drop the glock */
7078 VLRU_Wait_r(&volume_LRU.q[idx-1]);
7079 VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
7080 VLRU_Wait_r(&volume_LRU.q[idx]);
7081 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7084 /* no big deal if this allocation fails */
7085 if (volume_LRU.q[idx].len) {
7086 salv_flag_vec = (Volume **) malloc(volume_LRU.q[idx].len * sizeof(Volume *));
7089 now = FT_ApproxTime();
7090 thresh = volume_LRU.promotion_interval[idx-1];
7093 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7094 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7095 demote = (((vp->stats.last_promote + thresh) <= now) &&
7096 (vp->stats.last_get < (now - thresh)));
7098 /* we now do volume update list DONT_SALVAGE flag setting during
7099 * demotion passes */
7100 if (salv_flag_vec &&
7101 !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7103 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7104 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7105 salv_flag_vec[salv_vec_offset++] = vp;
7106 VCreateReservation_r(vp);
7115 /* demote and append chain */
7116 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7130 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7134 volume_LRU.q[idx].len -= len;
7135 volume_LRU.q[idx-1].len += len;
7138 /* release exclusive access to the two chains */
7140 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7141 VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
7143 /* now go back and set the DONT_SALVAGE flags as appropriate */
7144 if (salv_flag_vec) {
7146 for (i = 0; i < salv_vec_offset; i++) {
7147 vp = salv_flag_vec[i];
7148 if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7149 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7150 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7153 V_attachFlags(vp) |= VOL_HDR_DONTSALV;
7154 V_dontSalvage(vp) = DONT_SALVAGE;
7155 VUpdateVolume_r(&ec, vp, 0);
7159 VCancelReservation_r(vp);
7161 free(salv_flag_vec);
7165 /* run a pass of the VLRU GC scanner */
7167 VLRU_Scan_r(int idx)
7169 afs_uint32 now, thresh;
7170 struct rx_queue *qp, *nqp;
7174 osi_Assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
7176 /* gain exclusive access to the idx VLRU */
7177 VLRU_Wait_r(&volume_LRU.q[idx]);
7178 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7180 if (idx != VLRU_QUEUE_CANDIDATE) {
7181 /* gain exclusive access to the candidate VLRU */
7182 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7183 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7186 now = FT_ApproxTime();
7187 thresh = now - VLRU_offline_thresh;
7189 /* perform candidate selection and soft detaching */
7190 if (idx == VLRU_QUEUE_CANDIDATE) {
7191 /* soft detach some volumes from the candidate pool */
7195 for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7196 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7197 if (i >= VLRU_offline_max) {
7200 /* check timestamp to see if it's a candidate for soft detaching */
7201 if (vp->stats.last_get <= thresh) {
7203 if (VCheckSoftDetach(vp, thresh))
7209 /* scan for volumes to become soft detach candidates */
7210 for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
7211 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7213 /* check timestamp to see if it's a candidate for soft detaching */
7214 if (vp->stats.last_get <= thresh) {
7215 VCheckSoftDetachCandidate(vp, thresh);
7218 if (!(i&0x7f)) { /* lock coarsening optimization */
7226 /* relinquish exclusive access to the VLRU chains */
7230 volume_LRU.last_scan[idx] = now;
7231 if (idx != VLRU_QUEUE_CANDIDATE) {
7232 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7234 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7237 /* check whether volume is safe to soft detach
7238 * caller MUST NOT hold a ref count on vp */
7240 VCheckSoftDetach(Volume * vp, afs_uint32 thresh)
7244 if (vp->nUsers || vp->nWaiters)
7247 if (vp->stats.last_get <= thresh) {
7248 ret = VSoftDetachVolume_r(vp, thresh);
7254 /* check whether volume should be made a
7255 * soft detach candidate */
7257 VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh)
7260 if (vp->nUsers || vp->nWaiters)
7265 osi_Assert(idx == VLRU_QUEUE_NEW);
7267 if (vp->stats.last_get <= thresh) {
7268 /* move to candidate pool */
7269 queue_Remove(&vp->vlru);
7270 volume_LRU.q[VLRU_QUEUE_NEW].len--;
7271 queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
7272 vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
7273 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
7281 /* begin exclusive access on VLRU */
7283 VLRU_BeginExclusive_r(struct VLRU_q * q)
7285 osi_Assert(q->busy == 0);
7289 /* end exclusive access on VLRU */
7291 VLRU_EndExclusive_r(struct VLRU_q * q)
7293 osi_Assert(q->busy);
7295 CV_BROADCAST(&q->cv);
7298 /* wait for another thread to end exclusive access on VLRU */
7300 VLRU_Wait_r(struct VLRU_q * q)
7303 VOL_CV_WAIT(&q->cv);
7308 * volume soft detach
7310 * caller MUST NOT hold a ref count on vp */
7312 VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh)
7317 osi_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7319 ts_save = vp->stats.last_get;
7320 if (ts_save > thresh)
7323 if (vp->nUsers || vp->nWaiters)
7326 if (VIsExclusiveState(V_attachState(vp))) {
7330 switch (V_attachState(vp)) {
7331 case VOL_STATE_UNATTACHED:
7332 case VOL_STATE_PREATTACHED:
7333 case VOL_STATE_ERROR:
7334 case VOL_STATE_GOING_OFFLINE:
7335 case VOL_STATE_SHUTTING_DOWN:
7336 case VOL_STATE_SALVAGING:
7337 case VOL_STATE_DELETED:
7338 volume_LRU.q[vp->vlru.idx].len--;
7340 /* create and cancel a reservation to
7341 * give the volume an opportunity to
7343 VCreateReservation_r(vp);
7344 queue_Remove(&vp->vlru);
7345 vp->vlru.idx = VLRU_QUEUE_INVALID;
7346 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7347 VCancelReservation_r(vp);
7353 /* hold the volume and take it offline.
7354 * no need for reservations, as VHold_r
7355 * takes care of that internally. */
7356 if (VHold_r(vp) == 0) {
7357 /* vhold drops the glock, so now we should
7358 * check to make sure we aren't racing against
7359 * other threads. if we are racing, offlining vp
7360 * would be wasteful, and block the scanner for a while
7364 (vp->shuttingDown) ||
7365 (vp->goingOffline) ||
7366 (vp->stats.last_get != ts_save)) {
7367 /* looks like we're racing someone else. bail */
7371 /* pull it off the VLRU */
7372 osi_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7373 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
7374 queue_Remove(&vp->vlru);
7375 vp->vlru.idx = VLRU_QUEUE_INVALID;
7376 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7378 /* take if offline */
7379 VOffline_r(vp, "volume has been soft detached");
7381 /* invalidate the volume header cache */
7382 FreeVolumeHeader(vp);
7385 IncUInt64(&VStats.soft_detaches);
7386 vp->stats.soft_detaches++;
7388 /* put in pre-attached state so demand
7389 * attacher can work on it */
7390 VChangeState_r(vp, VOL_STATE_PREATTACHED);
7396 #endif /* AFS_DEMAND_ATTACH_FS */
7399 /***************************************************/
7400 /* Volume Header Cache routines */
7401 /***************************************************/
7404 * volume header cache.
7406 struct volume_hdr_LRU_t volume_hdr_LRU;
7409 * initialize the volume header cache.
7411 * @param[in] howMany number of header cache entries to preallocate
7413 * @pre VOL_LOCK held. Function has never been called before.
7415 * @post howMany cache entries are allocated, initialized, and added
7416 * to the LRU list. Header cache statistics are initialized.
7418 * @note only applicable to fileServer program type. Should only be
7419 * called once during volume package initialization.
7421 * @internal volume package internal use only.
7424 VInitVolumeHeaderCache(afs_uint32 howMany)
7426 struct volHeader *hp;
7427 if (programType != fileServer)
7429 queue_Init(&volume_hdr_LRU);
7430 volume_hdr_LRU.stats.free = 0;
7431 volume_hdr_LRU.stats.used = howMany;
7432 volume_hdr_LRU.stats.attached = 0;
7433 hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
7434 osi_Assert(hp != NULL);
7437 /* We are using ReleaseVolumeHeader to initialize the values on the header list
7438 * to ensure they have the right values
7440 ReleaseVolumeHeader(hp++);
7444 * get a volume header and attach it to the volume object.
7446 * @param[in] vp pointer to volume object
7448 * @return cache entry status
7449 * @retval 0 volume header was newly attached; cache data is invalid
7450 * @retval 1 volume header was previously attached; cache data is valid
7452 * @pre VOL_LOCK held. For DAFS, lightweight ref must be held on volume object.
7454 * @post volume header attached to volume object. if necessary, header cache
7455 * entry on LRU is synchronized to disk. Header is removed from LRU list.
7457 * @note VOL_LOCK may be dropped
7459 * @warning this interface does not load header data from disk. it merely
7460 * attaches a header object to the volume object, and may sync the old
7461 * header cache data out to disk in the process.
7463 * @internal volume package internal use only.
7466 GetVolumeHeader(Volume * vp)
7469 struct volHeader *hd;
7471 static int everLogged = 0;
7473 #ifdef AFS_DEMAND_ATTACH_FS
7474 VolState vp_save = 0, back_save = 0;
7476 /* XXX debug 9/19/05 we've apparently got
7477 * a ref counting bug somewhere that's
7478 * breaking the nUsers == 0 => header on LRU
7480 if (vp->header && queue_IsNotOnQueue(vp->header)) {
7481 Log("nUsers == 0, but header not on LRU\n");
7486 old = (vp->header != NULL); /* old == volume already has a header */
7488 if (programType != fileServer) {
7489 /* for volume utilities, we allocate volHeaders as needed */
7491 hd = (struct volHeader *)calloc(1, sizeof(*vp->header));
7492 osi_Assert(hd != NULL);
7495 #ifdef AFS_DEMAND_ATTACH_FS
7496 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
7500 /* for the fileserver, we keep a volume header cache */
7502 /* the header we previously dropped in the lru is
7503 * still available. pull it off the lru and return */
7506 osi_Assert(hd->back == vp);
7507 #ifdef AFS_DEMAND_ATTACH_FS
7508 V_attachFlags(vp) &= ~(VOL_HDR_IN_LRU);
7511 /* we need to grab a new element off the LRU */
7512 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
7513 /* grab an element and pull off of LRU */
7514 hd = queue_First(&volume_hdr_LRU, volHeader);
7517 /* LRU is empty, so allocate a new volHeader
7518 * this is probably indicative of a leak, so let the user know */
7519 hd = (struct volHeader *)calloc(1, sizeof(struct volHeader));
7520 osi_Assert(hd != NULL);
7522 Log("****Allocated more volume headers, probably leak****\n");
7525 volume_hdr_LRU.stats.free++;
7528 /* this header used to belong to someone else.
7529 * we'll need to check if the header needs to
7530 * be sync'd out to disk */
7532 #ifdef AFS_DEMAND_ATTACH_FS
7533 /* if hd->back were in an exclusive state, then
7534 * its volHeader would not be on the LRU... */
7535 osi_Assert(!VIsExclusiveState(V_attachState(hd->back)));
7538 if (hd->diskstuff.inUse) {
7539 /* volume was in use, so we'll need to sync
7540 * its header to disk */
7542 #ifdef AFS_DEMAND_ATTACH_FS
7543 back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
7544 vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
7545 VCreateReservation_r(hd->back);
7549 WriteVolumeHeader_r(&error, hd->back);
7550 /* Ignore errors; catch them later */
7552 #ifdef AFS_DEMAND_ATTACH_FS
7557 hd->back->header = NULL;
7558 #ifdef AFS_DEMAND_ATTACH_FS
7559 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
7561 if (hd->diskstuff.inUse) {
7562 VChangeState_r(hd->back, back_save);
7563 VCancelReservation_r(hd->back);
7564 VChangeState_r(vp, vp_save);
7568 volume_hdr_LRU.stats.attached++;
7572 #ifdef AFS_DEMAND_ATTACH_FS
7573 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
7576 volume_hdr_LRU.stats.free--;
7577 volume_hdr_LRU.stats.used++;
7579 IncUInt64(&VStats.hdr_gets);
7580 #ifdef AFS_DEMAND_ATTACH_FS
7581 IncUInt64(&vp->stats.hdr_gets);
7582 vp->stats.last_hdr_get = FT_ApproxTime();
7589 * make sure volume header is attached and contains valid cache data.
7591 * @param[out] ec outbound error code
7592 * @param[in] vp pointer to volume object
7594 * @pre VOL_LOCK held. For DAFS, lightweight ref held on vp.
7596 * @post header cache entry attached, and loaded with valid data, or
7597 * *ec is nonzero, and the header is released back into the LRU.
7599 * @internal volume package internal use only.
7602 LoadVolumeHeader(Error * ec, Volume * vp)
7604 #ifdef AFS_DEMAND_ATTACH_FS
7605 VolState state_save;
7609 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
7610 IncUInt64(&VStats.hdr_loads);
7611 state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
7614 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
7615 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
7617 IncUInt64(&vp->stats.hdr_loads);
7618 now = FT_ApproxTime();
7622 V_attachFlags(vp) |= VOL_HDR_LOADED;
7623 vp->stats.last_hdr_load = now;
7625 VChangeState_r(vp, state_save);
7627 #else /* AFS_DEMAND_ATTACH_FS */
7629 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
7630 IncUInt64(&VStats.hdr_loads);
7632 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
7633 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
7636 #endif /* AFS_DEMAND_ATTACH_FS */
7638 /* maintain (nUsers==0) => header in LRU invariant */
7639 FreeVolumeHeader(vp);
7644 * release a header cache entry back into the LRU list.
7646 * @param[in] hd pointer to volume header cache object
7648 * @pre VOL_LOCK held.
7650 * @post header cache object appended onto end of LRU list.
7652 * @note only applicable to fileServer program type.
7654 * @note used to place a header cache entry back into the
7655 * LRU pool without invalidating it as a cache entry.
7657 * @internal volume package internal use only.
7660 ReleaseVolumeHeader(struct volHeader *hd)
7662 if (programType != fileServer)
7664 if (!hd || queue_IsOnQueue(hd)) /* no header, or header already released */
7666 queue_Append(&volume_hdr_LRU, hd);
7667 #ifdef AFS_DEMAND_ATTACH_FS
7669 V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
7672 volume_hdr_LRU.stats.free++;
7673 volume_hdr_LRU.stats.used--;
7677 * free/invalidate a volume header cache entry.
7679 * @param[in] vp pointer to volume object
7681 * @pre VOL_LOCK is held.
7683 * @post For fileserver, header cache entry is returned to LRU, and it is
7684 * invalidated as a cache entry. For volume utilities, the header
7685 * cache entry is freed.
7687 * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
7688 * whenever it is necessary to invalidate the header cache entry.
7690 * @see ReleaseVolumeHeader
7692 * @internal volume package internal use only.
7695 FreeVolumeHeader(Volume * vp)
7697 struct volHeader *hd = vp->header;
7700 if (programType == fileServer) {
7701 ReleaseVolumeHeader(hd);
7706 #ifdef AFS_DEMAND_ATTACH_FS
7707 V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
7709 volume_hdr_LRU.stats.attached--;
7714 /***************************************************/
7715 /* Volume Hash Table routines */
7716 /***************************************************/
7719 * set size of volume object hash table.
7721 * @param[in] logsize log(2) of desired hash table size
7723 * @return operation status
7725 * @retval -1 failure
7727 * @pre MUST be called prior to VInitVolumePackage2
7729 * @post Volume Hash Table will have 2^logsize buckets
7732 VSetVolHashSize(int logsize)
7734 /* 64 to 268435456 hash buckets seems like a reasonable range */
7735 if ((logsize < 6 ) || (logsize > 28)) {
7740 VolumeHashTable.Size = 1 << logsize;
7741 VolumeHashTable.Mask = VolumeHashTable.Size - 1;
7743 /* we can't yet support runtime modification of this
7744 * parameter. we'll need a configuration rwlock to
7745 * make runtime modification feasible.... */
7752 * initialize dynamic data structures for volume hash table.
7754 * @post hash table is allocated, and fields are initialized.
7756 * @internal volume package internal use only.
7759 VInitVolumeHash(void)
7763 VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
7764 sizeof(VolumeHashChainHead));
7765 osi_Assert(VolumeHashTable.Table != NULL);
7767 for (i=0; i < VolumeHashTable.Size; i++) {
7768 queue_Init(&VolumeHashTable.Table[i]);
7769 #ifdef AFS_DEMAND_ATTACH_FS
7770 CV_INIT(&VolumeHashTable.Table[i].chain_busy_cv, "vhash busy", CV_DEFAULT, 0);
7771 #endif /* AFS_DEMAND_ATTACH_FS */
7776 * add a volume object to the hash table.
7778 * @param[in] vp pointer to volume object
7779 * @param[in] hashid hash of volume id
7781 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
7784 * @post volume is added to hash chain.
7786 * @internal volume package internal use only.
7788 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
7789 * asynchronous hash chain reordering to finish.
7792 AddVolumeToHashTable(Volume * vp, int hashid)
7794 VolumeHashChainHead * head;
7796 if (queue_IsOnQueue(vp))
7799 head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
7801 #ifdef AFS_DEMAND_ATTACH_FS
7802 /* wait for the hash chain to become available */
7805 V_attachFlags(vp) |= VOL_IN_HASH;
7806 vp->chainCacheCheck = ++head->cacheCheck;
7807 #endif /* AFS_DEMAND_ATTACH_FS */
7810 vp->hashid = hashid;
7811 queue_Append(head, vp);
7812 vp->vnodeHashOffset = VolumeHashOffset_r();
7816 * delete a volume object from the hash table.
7818 * @param[in] vp pointer to volume object
7820 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
7823 * @post volume is removed from hash chain.
7825 * @internal volume package internal use only.
7827 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
7828 * asynchronous hash chain reordering to finish.
7831 DeleteVolumeFromHashTable(Volume * vp)
7833 VolumeHashChainHead * head;
7835 if (!queue_IsOnQueue(vp))
7838 head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
7840 #ifdef AFS_DEMAND_ATTACH_FS
7841 /* wait for the hash chain to become available */
7844 V_attachFlags(vp) &= ~(VOL_IN_HASH);
7846 #endif /* AFS_DEMAND_ATTACH_FS */
7850 /* do NOT reset hashid to zero, as the online
7851 * salvager package may need to know the volume id
7852 * after the volume is removed from the hash */
7856 * lookup a volume object in the hash table given a volume id.
7858 * @param[out] ec error code return
7859 * @param[in] volumeId volume id
7860 * @param[in] hint volume object which we believe could be the correct
7863 * @return volume object pointer
7864 * @retval NULL no such volume id is registered with the hash table.
7866 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
7869 * @post volume object with the given id is returned. volume object and
7870 * hash chain access statistics are updated. hash chain may have
7873 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
7874 * asynchronous hash chain reordering operation to finish, or
7875 * in order for us to perform an asynchronous chain reordering.
7877 * @note Hash chain reorderings occur when the access count for the
7878 * volume object being looked up exceeds the sum of the previous
7879 * node's (the node ahead of it in the hash chain linked list)
7880 * access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
7882 * @note For DAFS, the hint parameter allows us to short-circuit if the
7883 * cacheCheck fields match between the hash chain head and the
7884 * hint volume object.
7887 VLookupVolume_r(Error * ec, VolId volumeId, Volume * hint)
7891 #ifdef AFS_DEMAND_ATTACH_FS
7894 VolumeHashChainHead * head;
7897 head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
7899 #ifdef AFS_DEMAND_ATTACH_FS
7900 /* wait for the hash chain to become available */
7903 /* check to see if we can short circuit without walking the hash chain */
7904 if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
7905 IncUInt64(&hint->stats.hash_short_circuits);
7908 #endif /* AFS_DEMAND_ATTACH_FS */
7910 /* someday we need to either do per-chain locks, RWlocks,
7911 * or both for volhash access.
7912 * (and move to a data structure with better cache locality) */
7914 /* search the chain for this volume id */
7915 for(queue_Scan(head, vp, np, Volume)) {
7917 if ((vp->hashid == volumeId)) {
7922 if (queue_IsEnd(head, vp)) {
7926 #ifdef AFS_DEMAND_ATTACH_FS
7927 /* update hash chain statistics */
7930 FillInt64(lks, 0, looks);
7931 AddUInt64(head->looks, lks, &head->looks);
7932 AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
7933 IncUInt64(&head->gets);
7938 IncUInt64(&vp->stats.hash_lookups);
7940 /* for demand attach fileserver, we permit occasional hash chain reordering
7941 * so that frequently looked up volumes move towards the head of the chain */
7942 pp = queue_Prev(vp, Volume);
7943 if (!queue_IsEnd(head, pp)) {
7944 FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
7945 AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
7946 if (GEInt64(vp->stats.hash_lookups, thresh)) {
7947 VReorderHash_r(head, pp, vp);
7951 /* update the short-circuit cache check */
7952 vp->chainCacheCheck = head->cacheCheck;
7954 #endif /* AFS_DEMAND_ATTACH_FS */
7959 #ifdef AFS_DEMAND_ATTACH_FS
7960 /* perform volume hash chain reordering.
7962 * advance a subchain beginning at vp ahead of
7963 * the adjacent subchain ending at pp */
7965 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
7967 Volume *tp, *np, *lp;
7968 afs_uint64 move_thresh;
7970 /* this should never be called if the chain is already busy, so
7971 * no need to wait for other exclusive chain ops to finish */
7973 /* this is a rather heavy set of operations,
7974 * so let's set the chain busy flag and drop
7976 VHashBeginExclusive_r(head);
7979 /* scan forward in the chain from vp looking for the last element
7980 * in the chain we want to advance */
7981 FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
7982 AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
7983 for(queue_ScanFrom(head, vp, tp, np, Volume)) {
7984 if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
7988 lp = queue_Prev(tp, Volume);
7990 /* scan backwards from pp to determine where to splice and
7991 * insert the subchain we're advancing */
7992 for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
7993 if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
7997 tp = queue_Next(tp, Volume);
7999 /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
8000 queue_MoveChainBefore(tp,vp,lp);
8003 IncUInt64(&VStats.hash_reorders);
8005 IncUInt64(&head->reorders);
8007 /* wake up any threads waiting for the hash chain */
8008 VHashEndExclusive_r(head);
8012 /* demand-attach fs volume hash
8013 * asynchronous exclusive operations */
8016 * begin an asynchronous exclusive operation on a volume hash chain.
8018 * @param[in] head pointer to volume hash chain head object
8020 * @pre VOL_LOCK held. hash chain is quiescent.
8022 * @post hash chain marked busy.
8024 * @note this interface is used in conjunction with VHashEndExclusive_r and
8025 * VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8026 * volume hash chain. Its main use case is hash chain reordering, which
8027 * has the potential to be a highly latent operation.
8029 * @see VHashEndExclusive_r
8034 * @internal volume package internal use only.
8037 VHashBeginExclusive_r(VolumeHashChainHead * head)
8039 osi_Assert(head->busy == 0);
8044 * relinquish exclusive ownership of a volume hash chain.
8046 * @param[in] head pointer to volume hash chain head object
8048 * @pre VOL_LOCK held. thread owns the hash chain exclusively.
8050 * @post hash chain is marked quiescent. threads awaiting use of
8051 * chain are awakened.
8053 * @see VHashBeginExclusive_r
8058 * @internal volume package internal use only.
8061 VHashEndExclusive_r(VolumeHashChainHead * head)
8063 osi_Assert(head->busy);
8065 CV_BROADCAST(&head->chain_busy_cv);
8069 * wait for all asynchronous operations on a hash chain to complete.
8071 * @param[in] head pointer to volume hash chain head object
8073 * @pre VOL_LOCK held.
8075 * @post hash chain object is quiescent.
8077 * @see VHashBeginExclusive_r
8078 * @see VHashEndExclusive_r
8082 * @note This interface should be called before any attempt to
8083 * traverse the hash chain. It is permissible for a thread
8084 * to gain exclusive access to the chain, and then perform
8085 * latent operations on the chain asynchronously wrt the
8088 * @warning if waiting is necessary, VOL_LOCK is dropped
8090 * @internal volume package internal use only.
8093 VHashWait_r(VolumeHashChainHead * head)
8095 while (head->busy) {
8096 VOL_CV_WAIT(&head->chain_busy_cv);
8099 #endif /* AFS_DEMAND_ATTACH_FS */
8102 /***************************************************/
8103 /* Volume by Partition List routines */
8104 /***************************************************/
8107 * demand attach fileserver adds a
8108 * linked list of volumes to each
8109 * partition object, thus allowing
8110 * for quick enumeration of all
8111 * volumes on a partition
8114 #ifdef AFS_DEMAND_ATTACH_FS
8116 * add a volume to its disk partition VByPList.
8118 * @param[in] vp pointer to volume object
8120 * @pre either the disk partition VByPList is owned exclusively
8121 * by the calling thread, or the list is quiescent and
8124 * @post volume is added to disk partition VByPList
8128 * @warning it is the caller's responsibility to ensure list
8131 * @see VVByPListWait_r
8132 * @see VVByPListBeginExclusive_r
8133 * @see VVByPListEndExclusive_r
8135 * @internal volume package internal use only.
8138 AddVolumeToVByPList_r(Volume * vp)
8140 if (queue_IsNotOnQueue(&vp->vol_list)) {
8141 queue_Append(&vp->partition->vol_list, &vp->vol_list);
8142 V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
8143 vp->partition->vol_list.len++;
8148 * delete a volume from its disk partition VByPList.
8150 * @param[in] vp pointer to volume object
8152 * @pre either the disk partition VByPList is owned exclusively
8153 * by the calling thread, or the list is quiescent and
8156 * @post volume is removed from the disk partition VByPList
8160 * @warning it is the caller's responsibility to ensure list
8163 * @see VVByPListWait_r
8164 * @see VVByPListBeginExclusive_r
8165 * @see VVByPListEndExclusive_r
8167 * @internal volume package internal use only.
8170 DeleteVolumeFromVByPList_r(Volume * vp)
8172 if (queue_IsOnQueue(&vp->vol_list)) {
8173 queue_Remove(&vp->vol_list);
8174 V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
8175 vp->partition->vol_list.len--;
8180 * begin an asynchronous exclusive operation on a VByPList.
8182 * @param[in] dp pointer to disk partition object
8184 * @pre VOL_LOCK held. VByPList is quiescent.
8186 * @post VByPList marked busy.
8188 * @note this interface is used in conjunction with VVByPListEndExclusive_r and
8189 * VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8192 * @see VVByPListEndExclusive_r
8193 * @see VVByPListWait_r
8197 * @internal volume package internal use only.
8199 /* take exclusive control over the list */
8201 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
8203 osi_Assert(dp->vol_list.busy == 0);
8204 dp->vol_list.busy = 1;
8208 * relinquish exclusive ownership of a VByPList.
8210 * @param[in] dp pointer to disk partition object
8212 * @pre VOL_LOCK held. thread owns the VByPList exclusively.
8214 * @post VByPList is marked quiescent. threads awaiting use of
8215 * the list are awakened.
8217 * @see VVByPListBeginExclusive_r
8218 * @see VVByPListWait_r
8222 * @internal volume package internal use only.
8225 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
8227 osi_Assert(dp->vol_list.busy);
8228 dp->vol_list.busy = 0;
8229 CV_BROADCAST(&dp->vol_list.cv);
8233 * wait for all asynchronous operations on a VByPList to complete.
8235 * @param[in] dp pointer to disk partition object
8237 * @pre VOL_LOCK is held.
8239 * @post disk partition's VByP list is quiescent
8243 * @note This interface should be called before any attempt to
8244 * traverse the VByPList. It is permissible for a thread
8245 * to gain exclusive access to the list, and then perform
8246 * latent operations on the list asynchronously wrt the
8249 * @warning if waiting is necessary, VOL_LOCK is dropped
8251 * @see VVByPListEndExclusive_r
8252 * @see VVByPListBeginExclusive_r
8254 * @internal volume package internal use only.
8257 VVByPListWait_r(struct DiskPartition64 * dp)
8259 while (dp->vol_list.busy) {
8260 VOL_CV_WAIT(&dp->vol_list.cv);
8263 #endif /* AFS_DEMAND_ATTACH_FS */
8265 /***************************************************/
8266 /* Volume Cache Statistics routines */
8267 /***************************************************/
8270 VPrintCacheStats_r(void)
8272 afs_uint32 get_hi, get_lo, load_hi, load_lo;
8273 struct VnodeClassInfo *vcp;
8274 vcp = &VnodeClassInfo[vLarge];
8275 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);
8276 vcp = &VnodeClassInfo[vSmall];
8277 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);
8278 SplitInt64(VStats.hdr_gets, get_hi, get_lo);
8279 SplitInt64(VStats.hdr_loads, load_hi, load_lo);
8280 Log("Volume header cache, %d entries, %d gets, %d replacements\n",
8281 VStats.hdr_cache_size, get_lo, load_lo);
8285 VPrintCacheStats(void)
8288 VPrintCacheStats_r();
8292 #ifdef AFS_DEMAND_ATTACH_FS
8294 UInt64ToDouble(afs_uint64 * x)
8296 static double c32 = 4.0 * 1.073741824 * 1000000000.0;
8298 SplitInt64(*x, h, l);
8299 return (((double)h) * c32) + ((double) l);
8303 DoubleToPrintable(double x, char * buf, int len)
8305 static double billion = 1000000000.0;
8308 y[0] = (afs_uint32) (x / (billion * billion));
8309 y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
8310 y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
8313 snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
8315 snprintf(buf, len, "%d%09d", y[1], y[2]);
8317 snprintf(buf, len, "%d", y[2]);
8323 struct VLRUExtStatsEntry {
8327 struct VLRUExtStats {
8333 } queue_info[VLRU_QUEUE_INVALID];
8334 struct VLRUExtStatsEntry * vec;
8338 * add a 256-entry fudge factor onto the vector in case state changes
8339 * out from under us.
8341 #define VLRU_EXT_STATS_VEC_LEN_FUDGE 256
8344 * collect extended statistics for the VLRU subsystem.
8346 * @param[out] stats pointer to stats structure to be populated
8347 * @param[in] nvols number of volumes currently known to exist
8349 * @pre VOL_LOCK held
8351 * @post stats->vec allocated and populated
8353 * @return operation status
8358 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
8360 afs_uint32 cur, idx, len;
8361 struct rx_queue * qp, * nqp;
8363 struct VLRUExtStatsEntry * vec;
8365 len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
8366 vec = stats->vec = calloc(len,
8367 sizeof(struct VLRUExtStatsEntry));
8373 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
8374 VLRU_Wait_r(&volume_LRU.q[idx]);
8375 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
8378 stats->queue_info[idx].start = cur;
8380 for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
8382 /* out of space in vec */
8385 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
8386 vec[cur].volid = vp->hashid;
8390 stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
8393 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
8401 #define ENUMTOSTRING(en) #en
8402 #define ENUMCASE(en) \
8404 return ENUMTOSTRING(en); \
8408 vlru_idx_to_string(int idx)
8411 ENUMCASE(VLRU_QUEUE_NEW);
8412 ENUMCASE(VLRU_QUEUE_MID);
8413 ENUMCASE(VLRU_QUEUE_OLD);
8414 ENUMCASE(VLRU_QUEUE_CANDIDATE);
8415 ENUMCASE(VLRU_QUEUE_HELD);
8416 ENUMCASE(VLRU_QUEUE_INVALID);
8418 return "**UNKNOWN**";
8423 VPrintExtendedCacheStats_r(int flags)
8426 afs_uint32 vol_sum = 0;
8433 struct stats looks, gets, reorders, len;
8434 struct stats ch_looks, ch_gets, ch_reorders;
8436 VolumeHashChainHead *head;
8438 struct VLRUExtStats vlru_stats;
8440 /* zero out stats */
8441 memset(&looks, 0, sizeof(struct stats));
8442 memset(&gets, 0, sizeof(struct stats));
8443 memset(&reorders, 0, sizeof(struct stats));
8444 memset(&len, 0, sizeof(struct stats));
8445 memset(&ch_looks, 0, sizeof(struct stats));
8446 memset(&ch_gets, 0, sizeof(struct stats));
8447 memset(&ch_reorders, 0, sizeof(struct stats));
8449 for (i = 0; i < VolumeHashTable.Size; i++) {
8450 head = &VolumeHashTable.Table[i];
8453 VHashBeginExclusive_r(head);
8456 ch_looks.sum = UInt64ToDouble(&head->looks);
8457 ch_gets.sum = UInt64ToDouble(&head->gets);
8458 ch_reorders.sum = UInt64ToDouble(&head->reorders);
8460 /* update global statistics */
8462 looks.sum += ch_looks.sum;
8463 gets.sum += ch_gets.sum;
8464 reorders.sum += ch_reorders.sum;
8465 len.sum += (double)head->len;
8466 vol_sum += head->len;
8469 len.min = (double) head->len;
8470 len.max = (double) head->len;
8471 looks.min = ch_looks.sum;
8472 looks.max = ch_looks.sum;
8473 gets.min = ch_gets.sum;
8474 gets.max = ch_gets.sum;
8475 reorders.min = ch_reorders.sum;
8476 reorders.max = ch_reorders.sum;
8478 if (((double)head->len) < len.min)
8479 len.min = (double) head->len;
8480 if (((double)head->len) > len.max)
8481 len.max = (double) head->len;
8482 if (ch_looks.sum < looks.min)
8483 looks.min = ch_looks.sum;
8484 else if (ch_looks.sum > looks.max)
8485 looks.max = ch_looks.sum;
8486 if (ch_gets.sum < gets.min)
8487 gets.min = ch_gets.sum;
8488 else if (ch_gets.sum > gets.max)
8489 gets.max = ch_gets.sum;
8490 if (ch_reorders.sum < reorders.min)
8491 reorders.min = ch_reorders.sum;
8492 else if (ch_reorders.sum > reorders.max)
8493 reorders.max = ch_reorders.sum;
8497 if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
8498 /* compute detailed per-chain stats */
8499 struct stats hdr_loads, hdr_gets;
8500 double v_looks, v_loads, v_gets;
8502 /* initialize stats with data from first element in chain */
8503 vp = queue_First(head, Volume);
8504 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
8505 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
8506 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
8507 ch_gets.min = ch_gets.max = v_looks;
8508 hdr_loads.min = hdr_loads.max = v_loads;
8509 hdr_gets.min = hdr_gets.max = v_gets;
8510 hdr_loads.sum = hdr_gets.sum = 0;
8512 vp = queue_Next(vp, Volume);
8514 /* pull in stats from remaining elements in chain */
8515 for (queue_ScanFrom(head, vp, vp, np, Volume)) {
8516 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
8517 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
8518 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
8520 hdr_loads.sum += v_loads;
8521 hdr_gets.sum += v_gets;
8523 if (v_looks < ch_gets.min)
8524 ch_gets.min = v_looks;
8525 else if (v_looks > ch_gets.max)
8526 ch_gets.max = v_looks;
8528 if (v_loads < hdr_loads.min)
8529 hdr_loads.min = v_loads;
8530 else if (v_loads > hdr_loads.max)
8531 hdr_loads.max = v_loads;
8533 if (v_gets < hdr_gets.min)
8534 hdr_gets.min = v_gets;
8535 else if (v_gets > hdr_gets.max)
8536 hdr_gets.max = v_gets;
8539 /* compute per-chain averages */
8540 ch_gets.avg = ch_gets.sum / ((double)head->len);
8541 hdr_loads.avg = hdr_loads.sum / ((double)head->len);
8542 hdr_gets.avg = hdr_gets.sum / ((double)head->len);
8544 /* dump per-chain stats */
8545 Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
8547 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
8548 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
8549 Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
8550 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
8551 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
8552 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
8553 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
8554 Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
8555 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
8556 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
8557 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
8558 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
8559 Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
8560 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
8561 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
8562 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
8563 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
8564 } else if (flags & VOL_STATS_PER_CHAIN) {
8565 /* dump simple per-chain stats */
8566 Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
8568 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
8569 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
8570 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
8574 VHashEndExclusive_r(head);
8579 /* compute global averages */
8580 len.avg = len.sum / ((double)VolumeHashTable.Size);
8581 looks.avg = looks.sum / ((double)VolumeHashTable.Size);
8582 gets.avg = gets.sum / ((double)VolumeHashTable.Size);
8583 reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
8585 /* dump global stats */
8586 Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
8587 Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
8588 DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
8589 DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
8590 DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
8591 DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
8592 Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
8593 DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
8594 DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
8595 DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
8596 DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
8597 Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
8598 DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
8599 DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
8600 DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
8601 DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
8602 Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
8603 DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
8604 DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
8605 DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
8606 DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
8608 /* print extended disk related statistics */
8610 struct DiskPartition64 * diskP;
8611 afs_uint32 vol_count[VOLMAXPARTS+1];
8612 byte part_exists[VOLMAXPARTS+1];
8616 memset(vol_count, 0, sizeof(vol_count));
8617 memset(part_exists, 0, sizeof(part_exists));
8621 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
8623 vol_count[id] = diskP->vol_list.len;
8624 part_exists[id] = 1;
8628 for (i = 0; i <= VOLMAXPARTS; i++) {
8629 if (part_exists[i]) {
8630 /* XXX while this is currently safe, it is a violation
8631 * of the VGetPartitionById_r interface contract. */
8632 diskP = VGetPartitionById_r(i, 0);
8634 Log("Partition %s has %d online volumes\n",
8635 VPartitionPath(diskP), diskP->vol_list.len);
8642 /* print extended VLRU statistics */
8643 if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
8644 afs_uint32 idx, cur, lpos;
8649 Log("VLRU State Dump:\n\n");
8651 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
8652 Log("\t%s:\n", vlru_idx_to_string(idx));
8655 for (cur = vlru_stats.queue_info[idx].start;
8656 cur < vlru_stats.queue_info[idx].len;
8658 line[lpos++] = vlru_stats.vec[cur].volid;
8660 Log("\t\t%u, %u, %u, %u, %u,\n",
8661 line[0], line[1], line[2], line[3], line[4]);
8670 Log("\t\t%u, %u, %u, %u, %u\n",
8671 line[0], line[1], line[2], line[3], line[4]);
8676 free(vlru_stats.vec);
8683 VPrintExtendedCacheStats(int flags)
8686 VPrintExtendedCacheStats_r(flags);
8689 #endif /* AFS_DEMAND_ATTACH_FS */
8692 VCanScheduleSalvage(void)
8694 return vol_opts.canScheduleSalvage;
8700 return vol_opts.canUseFSSYNC;
8704 VCanUseSALVSYNC(void)
8706 return vol_opts.canUseSALVSYNC;
8710 VCanUnsafeAttach(void)
8712 return vol_opts.unsafe_attach;