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);
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;
2242 #ifdef AFS_DEMAND_ATTACH_FS
2243 VolumeStats stats_save;
2245 #endif /* AFS_DEMAND_ATTACH_FS */
2249 volumeId = VolumeNumber(name);
2251 if (!(partp = VGetPartition_r(partition, 0))) {
2253 Log("VAttachVolume: Error getting partition (%s)\n", partition);
2257 if (VRequiresPartLock()) {
2258 osi_Assert(VInit == 3);
2259 VLockPartition_r(partition);
2260 } else if (programType == fileServer) {
2261 #ifdef AFS_DEMAND_ATTACH_FS
2262 /* lookup the volume in the hash table */
2263 vp = VLookupVolume_r(ec, volumeId, NULL);
2269 /* save any counters that are supposed to
2270 * be monotonically increasing over the
2271 * lifetime of the fileserver */
2272 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2274 memset(&stats_save, 0, sizeof(VolumeStats));
2277 /* if there's something in the hash table, and it's not
2278 * in the pre-attach state, then we may need to detach
2279 * it before proceeding */
2280 if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
2281 VCreateReservation_r(vp);
2282 VWaitExclusiveState_r(vp);
2284 /* at this point state must be one of:
2294 if (vp->specialStatus == VBUSY)
2297 /* if it's already attached, see if we can return it */
2298 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2299 VGetVolumeByVp_r(ec, vp);
2300 if (V_inUse(vp) == fileServer) {
2301 VCancelReservation_r(vp);
2305 /* otherwise, we need to detach, and attempt to re-attach */
2306 VDetachVolume_r(ec, vp);
2308 Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
2311 /* if it isn't fully attached, delete from the hash tables,
2312 and let the refcounter handle the rest */
2313 DeleteVolumeFromHashTable(vp);
2314 DeleteVolumeFromVByPList_r(vp);
2317 VCancelReservation_r(vp);
2321 /* pre-attach volume if it hasn't been done yet */
2323 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2324 (V_attachState(vp) == VOL_STATE_DELETED) ||
2325 (V_attachState(vp) == VOL_STATE_ERROR)) {
2327 vp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2333 osi_Assert(vp != NULL);
2335 /* handle pre-attach races
2337 * multiple threads can race to pre-attach a volume,
2338 * but we can't let them race beyond that
2340 * our solution is to let the first thread to bring
2341 * the volume into an exclusive state win; the other
2342 * threads just wait until it finishes bringing the
2343 * volume online, and then they do a vgetvolumebyvp
2345 if (svp && (svp != vp)) {
2346 /* wait for other exclusive ops to finish */
2347 VCreateReservation_r(vp);
2348 VWaitExclusiveState_r(vp);
2350 /* get a heavyweight ref, kill the lightweight ref, and return */
2351 VGetVolumeByVp_r(ec, vp);
2352 VCancelReservation_r(vp);
2356 /* at this point, we are chosen as the thread to do
2357 * demand attachment for this volume. all other threads
2358 * doing a getvolume on vp->hashid will block until we finish */
2360 /* make sure any old header cache entries are invalidated
2361 * before proceeding */
2362 FreeVolumeHeader(vp);
2364 VChangeState_r(vp, VOL_STATE_ATTACHING);
2366 /* restore any saved counters */
2367 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2368 #else /* AFS_DEMAND_ATTACH_FS */
2369 vp = VGetVolume_r(ec, volumeId);
2371 if (V_inUse(vp) == fileServer)
2373 if (vp->specialStatus == VBUSY)
2375 VDetachVolume_r(ec, vp);
2377 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2381 #endif /* AFS_DEMAND_ATTACH_FS */
2385 strcpy(path, VPartitionPath(partp));
2393 vp = (Volume *) calloc(1, sizeof(Volume));
2394 osi_Assert(vp != NULL);
2395 vp->hashid = volumeId;
2396 vp->device = partp->device;
2397 vp->partition = partp;
2398 queue_Init(&vp->vnode_list);
2399 #ifdef AFS_DEMAND_ATTACH_FS
2400 CV_INIT(&V_attachCV(vp), "vp attach", CV_DEFAULT, 0);
2401 #endif /* AFS_DEMAND_ATTACH_FS */
2404 /* attach2 is entered without any locks, and returns
2405 * with vol_glock_mutex held */
2406 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode);
2408 if (VCanUseFSSYNC() && vp) {
2409 #ifdef AFS_DEMAND_ATTACH_FS
2410 if ((mode == V_VOLUPD) || (VolumeWriteable(vp) && (mode == V_CLONE))) {
2411 /* mark volume header as in use so that volser crashes lead to a
2412 * salvage attempt */
2413 VUpdateVolume_r(ec, vp, 0);
2415 /* for dafs, we should tell the fileserver, except for V_PEEK
2416 * where we know it is not necessary */
2417 if (mode == V_PEEK) {
2418 vp->needsPutBack = 0;
2420 vp->needsPutBack = 1;
2422 #else /* !AFS_DEMAND_ATTACH_FS */
2423 /* duplicate computation in fssync.c about whether the server
2424 * takes the volume offline or not. If the volume isn't
2425 * offline, we must not return it when we detach the volume,
2426 * or the server will abort */
2427 if (mode == V_READONLY || mode == V_PEEK
2428 || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
2429 vp->needsPutBack = 0;
2431 vp->needsPutBack = 1;
2432 #endif /* !AFS_DEMAND_ATTACH_FS */
2434 /* OK, there's a problem here, but one that I don't know how to
2435 * fix right now, and that I don't think should arise often.
2436 * Basically, we should only put back this volume to the server if
2437 * it was given to us by the server, but since we don't have a vp,
2438 * we can't run the VolumeWriteable function to find out as we do
2439 * above when computing vp->needsPutBack. So we send it back, but
2440 * there's a path in VAttachVolume on the server which may abort
2441 * if this volume doesn't have a header. Should be pretty rare
2442 * for all of that to happen, but if it does, probably the right
2443 * fix is for the server to allow the return of readonly volumes
2444 * that it doesn't think are really checked out. */
2445 #ifdef FSSYNC_BUILD_CLIENT
2446 if (VCanUseFSSYNC() && vp == NULL &&
2447 mode != V_SECRETLY && mode != V_PEEK) {
2449 #ifdef AFS_DEMAND_ATTACH_FS
2450 /* If we couldn't attach but we scheduled a salvage, we already
2451 * notified the fileserver; don't online it now */
2452 if (*ec != VSALVAGING)
2453 #endif /* AFS_DEMAND_ATTACH_FS */
2454 FSYNC_VolOp(volumeId, partition, FSYNC_VOL_ON, 0, NULL);
2457 if (programType == fileServer && vp) {
2458 #ifdef AFS_DEMAND_ATTACH_FS
2460 * we can get here in cases where we don't "own"
2461 * the volume (e.g. volume owned by a utility).
2462 * short circuit around potential disk header races.
2464 if (V_attachState(vp) != VOL_STATE_ATTACHED) {
2468 VUpdateVolume_r(ec, vp, 0);
2470 Log("VAttachVolume: Error updating volume\n");
2475 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2476 #ifndef AFS_DEMAND_ATTACH_FS
2477 /* This is a hack: by temporarily setting the incore
2478 * dontSalvage flag ON, the volume will be put back on the
2479 * Update list (with dontSalvage OFF again). It will then
2480 * come back in N minutes with DONT_SALVAGE eventually
2481 * set. This is the way that volumes that have never had
2482 * it set get it set; or that volumes that have been
2483 * offline without DONT SALVAGE having been set also
2484 * eventually get it set */
2485 V_dontSalvage(vp) = DONT_SALVAGE;
2486 #endif /* !AFS_DEMAND_ATTACH_FS */
2487 VAddToVolumeUpdateList_r(ec, vp);
2489 Log("VAttachVolume: Error adding volume to update list\n");
2496 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2501 if (VRequiresPartLock()) {
2502 VUnlockPartition_r(partition);
2505 #ifdef AFS_DEMAND_ATTACH_FS
2506 /* attach failed; make sure we're in error state */
2507 if (vp && !VIsErrorState(V_attachState(vp))) {
2508 VChangeState_r(vp, VOL_STATE_ERROR);
2510 #endif /* AFS_DEMAND_ATTACH_FS */
2517 #ifdef AFS_DEMAND_ATTACH_FS
2518 /* VAttachVolumeByVp_r
2520 * finish attaching a volume that is
2521 * in a less than fully attached state
2523 /* caller MUST hold a ref count on vp */
2525 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
2527 char name[VMAXPATHLEN];
2529 struct DiskPartition64 *partp;
2533 Volume * nvp = NULL;
2534 VolumeStats stats_save;
2537 /* volume utility should never call AttachByVp */
2538 osi_Assert(programType == fileServer);
2540 volumeId = vp->hashid;
2541 partp = vp->partition;
2542 VolumeExternalName_r(volumeId, name, sizeof(name));
2545 /* if another thread is performing a blocking op, wait */
2546 VWaitExclusiveState_r(vp);
2548 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2550 /* if it's already attached, see if we can return it */
2551 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2552 VGetVolumeByVp_r(ec, vp);
2553 if (V_inUse(vp) == fileServer) {
2556 if (vp->specialStatus == VBUSY)
2558 VDetachVolume_r(ec, vp);
2560 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2566 /* pre-attach volume if it hasn't been done yet */
2568 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2569 (V_attachState(vp) == VOL_STATE_DELETED) ||
2570 (V_attachState(vp) == VOL_STATE_ERROR)) {
2571 nvp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2577 VCreateReservation_r(nvp);
2582 osi_Assert(vp != NULL);
2583 VChangeState_r(vp, VOL_STATE_ATTACHING);
2585 /* restore monotonically increasing stats */
2586 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2590 /* compute path to disk header */
2591 strcpy(path, VPartitionPath(partp));
2600 * NOTE: attach2 is entered without any locks, and returns
2601 * with vol_glock_mutex held */
2602 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode);
2605 * the event that an error was encountered, or
2606 * the volume was not brought to an attached state
2607 * for any reason, skip to the end. We cannot
2608 * safely call VUpdateVolume unless we "own" it.
2612 (V_attachState(vp) != VOL_STATE_ATTACHED)) {
2616 VUpdateVolume_r(ec, vp, 0);
2618 Log("VAttachVolume: Error updating volume %u\n", vp->hashid);
2622 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2623 #ifndef AFS_DEMAND_ATTACH_FS
2624 /* This is a hack: by temporarily setting the incore
2625 * dontSalvage flag ON, the volume will be put back on the
2626 * Update list (with dontSalvage OFF again). It will then
2627 * come back in N minutes with DONT_SALVAGE eventually
2628 * set. This is the way that volumes that have never had
2629 * it set get it set; or that volumes that have been
2630 * offline without DONT SALVAGE having been set also
2631 * eventually get it set */
2632 V_dontSalvage(vp) = DONT_SALVAGE;
2633 #endif /* !AFS_DEMAND_ATTACH_FS */
2634 VAddToVolumeUpdateList_r(ec, vp);
2636 Log("VAttachVolume: Error adding volume %u to update list\n", vp->hashid);
2643 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2647 VCancelReservation_r(nvp);
2650 if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2651 if (vp && !VIsErrorState(V_attachState(vp))) {
2652 VChangeState_r(vp, VOL_STATE_ERROR);
2661 * lock a volume on disk (non-blocking).
2663 * @param[in] vp The volume to lock
2664 * @param[in] locktype READ_LOCK or WRITE_LOCK
2666 * @return operation status
2667 * @retval 0 success, lock was obtained
2668 * @retval EBUSY a conflicting lock was held by another process
2669 * @retval EIO error acquiring lock
2671 * @pre If we're in the fileserver, vp is in an exclusive state
2673 * @pre vp is not already locked
2676 VLockVolumeNB(Volume *vp, int locktype)
2680 osi_Assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2681 osi_Assert(!(V_attachFlags(vp) & VOL_LOCKED));
2683 code = VLockVolumeByIdNB(vp->hashid, vp->partition, locktype);
2685 V_attachFlags(vp) |= VOL_LOCKED;
2692 * unlock a volume on disk that was locked with VLockVolumeNB.
2694 * @param[in] vp volume to unlock
2696 * @pre If we're in the fileserver, vp is in an exclusive state
2698 * @pre vp has already been locked
2701 VUnlockVolume(Volume *vp)
2703 osi_Assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2704 osi_Assert((V_attachFlags(vp) & VOL_LOCKED));
2706 VUnlockVolumeById(vp->hashid, vp->partition);
2708 V_attachFlags(vp) &= ~VOL_LOCKED;
2710 #endif /* AFS_DEMAND_ATTACH_FS */
2713 * read in a vol header, possibly lock the vol header, and possibly check out
2714 * the vol header from the fileserver, as part of volume attachment.
2716 * @param[out] ec error code
2717 * @param[in] vp volume pointer object
2718 * @param[in] partp disk partition object of the attaching partition
2719 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
2721 * @param[in] peek 1 to just try to read in the volume header and make sure
2722 * we don't try to lock the vol, or check it out from
2723 * FSSYNC or anything like that; 0 otherwise, for 'normal'
2726 * @note As part of DAFS volume attachment, the volume header may be either
2727 * read- or write-locked to ensure mutual exclusion of certain volume
2728 * operations. In some cases in order to determine whether we need to
2729 * read- or write-lock the header, we need to read in the header to see
2730 * if the volume is RW or not. So, if we read in the header under a
2731 * read-lock and determine that we actually need a write-lock on the
2732 * volume header, this function will drop the read lock, acquire a write
2733 * lock, and read the header in again.
2736 attach_volume_header(Error *ec, Volume *vp, struct DiskPartition64 *partp,
2739 struct VolumeDiskHeader diskHeader;
2740 struct VolumeHeader header;
2743 int lock_tries = 0, checkout_tries = 0;
2745 VolumeId volid = vp->hashid;
2746 #ifdef FSSYNC_BUILD_CLIENT
2747 int checkout, done_checkout = 0;
2748 #endif /* FSSYNC_BUILD_CLIENT */
2749 #ifdef AFS_DEMAND_ATTACH_FS
2750 int locktype = 0, use_locktype = -1;
2751 #endif /* AFS_DEMAND_ATTACH_FS */
2757 if (lock_tries > VOL_MAX_CHECKOUT_RETRIES) {
2758 Log("VAttachVolume: retried too many times trying to lock header for "
2759 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2760 VPartitionPath(partp));
2764 if (checkout_tries > VOL_MAX_CHECKOUT_RETRIES) {
2765 Log("VAttachVolume: retried too many times trying to checkout "
2766 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2767 VPartitionPath(partp));
2772 if (VReadVolumeDiskHeader(volid, partp, NULL)) {
2773 /* short-circuit the 'volume does not exist' case */
2778 #ifdef FSSYNC_BUILD_CLIENT
2779 checkout = !done_checkout;
2781 if (!peek && checkout && VMustCheckoutVolume(mode)) {
2783 memset(&res, 0, sizeof(res));
2785 if (FSYNC_VolOp(volid, VPartitionPath(partp), FSYNC_VOL_NEEDVOLUME, mode, &res)
2788 if (res.hdr.reason == FSYNC_SALVAGE) {
2789 Log("VAttachVolume: file server says volume %lu is salvaging\n",
2790 afs_printable_uint32_lu(volid));
2793 Log("VAttachVolume: attach of volume %lu apparently denied by file server\n",
2794 afs_printable_uint32_lu(volid));
2795 *ec = VNOVOL; /* XXXX */
2802 #ifdef AFS_DEMAND_ATTACH_FS
2803 if (use_locktype < 0) {
2804 /* don't know whether vol is RO or RW; assume it's RO and we can retry
2805 * if it turns out to be RW */
2806 locktype = VVolLockType(mode, 0);
2809 /* a previous try says we should use use_locktype to lock the volume,
2811 locktype = use_locktype;
2814 if (!peek && locktype) {
2815 code = VLockVolumeNB(vp, locktype);
2817 if (code == EBUSY) {
2818 Log("VAttachVolume: another program has vol %lu locked\n",
2819 afs_printable_uint32_lu(volid));
2821 Log("VAttachVolume: error %d trying to lock vol %lu\n",
2822 code, afs_printable_uint32_lu(volid));
2829 #endif /* AFS_DEMAND_ATTACH_FS */
2831 code = VReadVolumeDiskHeader(volid, partp, &diskHeader);
2841 DiskToVolumeHeader(&header, &diskHeader);
2843 IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header.parent,
2844 header.largeVnodeIndex);
2845 IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header.parent,
2846 header.smallVnodeIndex);
2847 IH_INIT(vp->diskDataHandle, partp->device, header.parent,
2849 IH_INIT(vp->linkHandle, partp->device, header.parent, header.linkTable);
2852 /* only need to do this once */
2854 GetVolumeHeader(vp);
2858 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2859 /* demand attach changes the V_PEEK mechanism
2861 * we can now suck the current disk data structure over
2862 * the fssync interface without going to disk
2864 * (technically, we don't need to restrict this feature
2865 * to demand attach fileservers. However, I'm trying
2866 * to limit the number of common code changes)
2868 if (VCanUseFSSYNC() && (mode == V_PEEK || peek)) {
2870 res.payload.len = sizeof(VolumeDiskData);
2871 res.payload.buf = &vp->header->diskstuff;
2873 if (FSYNC_VolOp(vp->hashid,
2875 FSYNC_VOL_QUERY_HDR,
2878 goto disk_header_loaded;
2881 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2882 (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2883 sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2885 #ifdef AFS_DEMAND_ATTACH_FS
2888 IncUInt64(&VStats.hdr_loads);
2889 IncUInt64(&vp->stats.hdr_loads);
2891 #endif /* AFS_DEMAND_ATTACH_FS */
2894 Log("VAttachVolume: Error reading diskDataHandle header for vol %lu; "
2895 "error=%u\n", afs_printable_uint32_lu(volid), *ec);
2899 #ifdef AFS_DEMAND_ATTACH_FS
2900 # ifdef FSSYNC_BUILD_CLIENT
2902 # endif /* FSSYNC_BUILD_CLIENT */
2904 /* if the lock type we actually used to lock the volume is different than
2905 * the lock type we should have used, retry with the lock type we should
2907 use_locktype = VVolLockType(mode, VolumeWriteable(vp));
2908 if (locktype != use_locktype) {
2912 #endif /* AFS_DEMAND_ATTACH_FS */
2917 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2918 if (!peek && *ec == 0 && retry == 0 && VMustCheckoutVolume(mode)) {
2920 code = FSYNC_VerifyCheckout(volid, VPartitionPath(partp), FSYNC_VOL_NEEDVOLUME, mode);
2922 if (code == SYNC_DENIED) {
2923 /* must retry checkout; fileserver no longer thinks we have
2929 } else if (code != SYNC_OK) {
2933 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2936 /* either we are going to be called again for a second pass, or we
2937 * encountered an error; clean up in either case */
2939 #ifdef AFS_DEMAND_ATTACH_FS
2940 if ((V_attachFlags(vp) & VOL_LOCKED)) {
2943 #endif /* AFS_DEMAND_ATTACH_FS */
2944 if (vp->linkHandle) {
2945 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
2946 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
2947 IH_RELEASE(vp->diskDataHandle);
2948 IH_RELEASE(vp->linkHandle);
2961 #ifdef AFS_DEMAND_ATTACH_FS
2963 attach_check_vop(Error *ec, VolumeId volid, struct DiskPartition64 *partp,
2968 if (vp->pending_vol_op) {
2972 if (vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningUnknown) {
2974 code = VVolOpLeaveOnlineNoHeader_r(vp, vp->pending_vol_op);
2976 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
2977 } else if (code == 0) {
2978 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
2981 /* we need the vol header to determine if the volume can be
2982 * left online for the vop, so... get the header */
2986 /* attach header with peek=1 to avoid checking out the volume
2987 * or locking it; we just want the header info, we're not
2988 * messing with the volume itself at all */
2989 attach_volume_header(ec, vp, partp, V_PEEK, 1);
2996 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
2997 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
2999 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3002 /* make sure we grab a new vol header and re-open stuff on
3003 * actual attachment; we can't keep the data we grabbed, since
3004 * it was not done under a lock and thus not safe */
3005 FreeVolumeHeader(vp);
3006 VReleaseVolumeHandles_r(vp);
3009 /* see if the pending volume op requires exclusive access */
3010 switch (vp->pending_vol_op->vol_op_state) {
3011 case FSSYNC_VolOpPending:
3012 /* this should never happen */
3013 osi_Assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpPending);
3016 case FSSYNC_VolOpRunningUnknown:
3017 /* this should never happen; we resolved 'unknown' above */
3018 osi_Assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
3021 case FSSYNC_VolOpRunningOffline:
3022 /* mark the volume down */
3024 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3026 /* do not set V_offlineMessage here; we don't have ownership of
3027 * the volume (and probably do not have the header loaded), so we
3028 * can't alter the disk header */
3030 /* check to see if we should set the specialStatus flag */
3031 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
3032 vp->specialStatus = VBUSY;
3043 #endif /* AFS_DEMAND_ATTACH_FS */
3046 * volume attachment helper function.
3048 * @param[out] ec error code
3049 * @param[in] volumeId volume ID of the attaching volume
3050 * @param[in] path full path to the volume header .vol file
3051 * @param[in] partp disk partition object for the attaching partition
3052 * @param[in] vp volume object; vp->hashid, vp->device, vp->partition,
3053 * vp->vnode_list, and V_attachCV (for DAFS) should already
3055 * @param[in] isbusy 1 if vp->specialStatus should be set to VBUSY; that is,
3056 * if there is a volume operation running for this volume
3057 * that should set the volume to VBUSY during its run. 0
3058 * otherwise. (see VVolOpSetVBusy_r)
3059 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
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)
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;
3094 #ifdef AFS_DEMAND_ATTACH_FS
3095 attach_check_vop(ec, volumeId, partp, vp);
3097 attach_volume_header(ec, vp, partp, mode, 0);
3100 attach_volume_header(ec, vp, partp, mode, 0);
3101 #endif /* !AFS_DEMAND_ATTACH_FS */
3103 if (*ec == VNOVOL) {
3104 /* if the volume doesn't exist, skip straight to 'error' so we don't
3105 * request a salvage */
3112 vp->specialStatus = (byte) (isbusy ? VBUSY : 0);
3113 vp->shuttingDown = 0;
3114 vp->goingOffline = 0;
3116 #ifdef AFS_DEMAND_ATTACH_FS
3117 vp->stats.last_attach = FT_ApproxTime();
3118 vp->stats.attaches++;
3122 IncUInt64(&VStats.attaches);
3123 vp->cacheCheck = ++VolumeCacheCheck;
3124 /* just in case this ever rolls over */
3125 if (!vp->cacheCheck)
3126 vp->cacheCheck = ++VolumeCacheCheck;
3129 #ifdef AFS_DEMAND_ATTACH_FS
3130 V_attachFlags(vp) |= VOL_HDR_LOADED;
3131 vp->stats.last_hdr_load = vp->stats.last_attach;
3132 #endif /* AFS_DEMAND_ATTACH_FS */
3136 struct IndexFileHeader iHead;
3138 #if OPENAFS_VOL_STATS
3140 * We just read in the diskstuff part of the header. If the detailed
3141 * volume stats area has not yet been initialized, we should bzero the
3142 * area and mark it as initialized.
3144 if (!(V_stat_initialized(vp))) {
3145 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
3146 V_stat_initialized(vp) = 1;
3148 #endif /* OPENAFS_VOL_STATS */
3150 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
3151 (char *)&iHead, sizeof(iHead),
3152 SMALLINDEXMAGIC, SMALLINDEXVERSION);
3155 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
3160 struct IndexFileHeader iHead;
3162 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
3163 (char *)&iHead, sizeof(iHead),
3164 LARGEINDEXMAGIC, LARGEINDEXVERSION);
3167 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
3171 #ifdef AFS_NAMEI_ENV
3173 struct versionStamp stamp;
3175 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
3176 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
3179 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
3182 #endif /* AFS_NAMEI_ENV */
3184 #if defined(AFS_DEMAND_ATTACH_FS)
3185 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
3187 if (!VCanScheduleSalvage()) {
3188 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3190 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER |
3191 VOL_SALVAGE_NO_OFFLINE);
3196 /* volume operation in progress */
3200 #else /* AFS_DEMAND_ATTACH_FS */
3202 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
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);
3404 #ifdef AFS_DEMAND_ATTACH_FS
3405 if (!VIsErrorState(V_attachState(vp))) {
3406 VChangeState_r(vp, error_state);
3408 #endif /* AFS_DEMAND_ATTACH_FS */
3411 VReleaseVolumeHandles_r(vp);
3414 #ifdef AFS_DEMAND_ATTACH_FS
3421 #else /* !AFS_DEMAND_ATTACH_FS */
3423 #endif /* !AFS_DEMAND_ATTACH_FS */
3427 /* Attach an existing volume.
3428 The volume also normally goes online at this time.
3429 An offline volume must be reattached to make it go online.
3433 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
3437 retVal = VAttachVolume_r(ec, volumeId, mode);
3443 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
3446 VGetVolumePath(ec, volumeId, &part, &name);
3450 vp = VGetVolume_r(&error, volumeId);
3452 osi_Assert(V_inUse(vp) == 0);
3453 VDetachVolume_r(ec, vp);
3457 return VAttachVolumeByName_r(ec, part, name, mode);
3460 /* Increment a reference count to a volume, sans context swaps. Requires
3461 * possibly reading the volume header in from the disk, since there's
3462 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
3464 * N.B. This call can fail if we can't read in the header!! In this case
3465 * we still guarantee we won't context swap, but the ref count won't be
3466 * incremented (otherwise we'd violate the invariant).
3468 /* NOTE: with the demand attach fileserver extensions, the global lock
3469 * is dropped within VHold */
3470 #ifdef AFS_DEMAND_ATTACH_FS
3472 VHold_r(Volume * vp)
3476 VCreateReservation_r(vp);
3477 VWaitExclusiveState_r(vp);
3479 LoadVolumeHeader(&error, vp);
3481 VCancelReservation_r(vp);
3485 VCancelReservation_r(vp);
3488 #else /* AFS_DEMAND_ATTACH_FS */
3490 VHold_r(Volume * vp)
3494 LoadVolumeHeader(&error, vp);
3500 #endif /* AFS_DEMAND_ATTACH_FS */
3508 retVal = VHold_r(vp);
3515 /***************************************************/
3516 /* get and put volume routines */
3517 /***************************************************/
3520 * put back a heavyweight reference to a volume object.
3522 * @param[in] vp volume object pointer
3524 * @pre VOL_LOCK held
3526 * @post heavyweight volume reference put back.
3527 * depending on state, volume may have been taken offline,
3528 * detached, salvaged, freed, etc.
3530 * @internal volume package internal use only
3533 VPutVolume_r(Volume * vp)
3535 osi_Assert(--vp->nUsers >= 0);
3536 if (vp->nUsers == 0) {
3538 ReleaseVolumeHeader(vp->header);
3539 #ifdef AFS_DEMAND_ATTACH_FS
3540 if (!VCheckDetach(vp)) {
3544 #else /* AFS_DEMAND_ATTACH_FS */
3546 #endif /* AFS_DEMAND_ATTACH_FS */
3551 VPutVolume(Volume * vp)
3559 /* Get a pointer to an attached volume. The pointer is returned regardless
3560 of whether or not the volume is in service or on/off line. An error
3561 code, however, is returned with an indication of the volume's status */
3563 VGetVolume(Error * ec, Error * client_ec, VolId volumeId)
3567 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
3572 /* same as VGetVolume, but if a volume is waiting to go offline, we return
3573 * that it is actually offline, instead of waiting for it to go offline */
3575 VGetVolumeNoWait(Error * ec, Error * client_ec, VolId volumeId)
3579 retVal = GetVolume(ec, client_ec, volumeId, NULL, 1);
3585 VGetVolume_r(Error * ec, VolId volumeId)
3587 return GetVolume(ec, NULL, volumeId, NULL, 0);
3590 /* try to get a volume we've previously looked up */
3591 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
3593 VGetVolumeByVp_r(Error * ec, Volume * vp)
3595 return GetVolume(ec, NULL, vp->hashid, vp, 0);
3599 * private interface for getting a volume handle
3601 * @param[out] ec error code (0 if no error)
3602 * @param[out] client_ec wire error code to be given to clients
3603 * @param[in] volumeId ID of the volume we want
3604 * @param[in] hint optional hint for hash lookups, or NULL
3605 * @param[in] nowait 0 to wait for a 'goingOffline' volume to go offline
3606 * before returning, 1 to return immediately
3608 * @return a volume handle for the specified volume
3609 * @retval NULL an error occurred, or the volume is in such a state that
3610 * we cannot load a header or return any volume struct
3612 * @note for DAFS, caller must NOT hold a ref count on 'hint'
3615 GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint, int nowait)
3618 /* pull this profiling/debugging code out of regular builds */
3620 #define VGET_CTR_INC(x) x++
3621 unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
3622 0, V7 = 0, V8 = 0, V9 = 0;
3623 unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
3625 #define VGET_CTR_INC(x)
3627 #ifdef AFS_DEMAND_ATTACH_FS
3628 Volume *avp, * rvp = hint;
3632 * if VInit is zero, the volume package dynamic
3633 * data structures have not been initialized yet,
3634 * and we must immediately return an error
3640 *client_ec = VOFFLINE;
3645 #ifdef AFS_DEMAND_ATTACH_FS
3647 VCreateReservation_r(rvp);
3649 #endif /* AFS_DEMAND_ATTACH_FS */
3657 vp = VLookupVolume_r(ec, volumeId, vp);
3663 #ifdef AFS_DEMAND_ATTACH_FS
3664 if (rvp && (rvp != vp)) {
3665 /* break reservation on old vp */
3666 VCancelReservation_r(rvp);
3669 #endif /* AFS_DEMAND_ATTACH_FS */
3675 /* Until we have reached an initialization level of 2
3676 * we don't know whether this volume exists or not.
3677 * We can't sleep and retry later because before a volume
3678 * is attached, the caller tries to get it first. Just
3679 * return VOFFLINE and the caller can choose whether to
3680 * retry the command or not. */
3690 IncUInt64(&VStats.hdr_gets);
3692 #ifdef AFS_DEMAND_ATTACH_FS
3693 /* block if someone else is performing an exclusive op on this volume */
3696 VCreateReservation_r(rvp);
3698 VWaitExclusiveState_r(vp);
3700 /* short circuit with VNOVOL in the following circumstances:
3703 * - VOL_STATE_SHUTTING_DOWN
3705 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
3706 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN) ||
3707 (V_attachState(vp) == VOL_STATE_GOING_OFFLINE)) {
3714 * short circuit with VOFFLINE for VOL_STATE_UNATTACHED and
3715 * VNOVOL for VOL_STATE_DELETED
3717 if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
3718 (V_attachState(vp) == VOL_STATE_DELETED)) {
3719 if (vp->specialStatus) {
3720 *ec = vp->specialStatus;
3721 } else if (V_attachState(vp) == VOL_STATE_DELETED) {
3730 /* allowable states:
3737 if (vp->salvage.requested) {
3738 VUpdateSalvagePriority_r(vp);
3741 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
3742 avp = VAttachVolumeByVp_r(ec, vp, 0);
3745 /* VAttachVolumeByVp_r can return a pointer
3746 * != the vp passed to it under certain
3747 * conditions; make sure we don't leak
3748 * reservations if that happens */
3750 VCancelReservation_r(rvp);
3752 VCreateReservation_r(rvp);
3762 if (!vp->pending_vol_op) {
3777 if (VIsSalvaging(vp) || (*ec == VSALVAGING)) {
3779 /* see CheckVnode() in afsfileprocs.c for an explanation
3780 * of this error code logic */
3781 afs_uint32 now = FT_ApproxTime();
3782 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
3785 *client_ec = VRESTARTING;
3794 #ifdef AFS_DEMAND_ATTACH_FS
3796 * this test MUST happen after VAttachVolymeByVp, so vol_op_state is
3797 * not VolOpRunningUnknown (attach2 would have converted it to Online
3801 /* only valid before/during demand attachment */
3802 osi_Assert(!vp->pending_vol_op || vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
3804 /* deny getvolume due to running mutually exclusive vol op */
3805 if (vp->pending_vol_op && vp->pending_vol_op->vol_op_state==FSSYNC_VolOpRunningOffline) {
3807 * volume cannot remain online during this volume operation.
3810 if (vp->specialStatus) {
3812 * special status codes outrank normal VOFFLINE code
3814 *ec = vp->specialStatus;
3816 *client_ec = vp->specialStatus;
3820 /* see CheckVnode() in afsfileprocs.c for an explanation
3821 * of this error code logic */
3822 afs_uint32 now = FT_ApproxTime();
3823 if ((vp->stats.last_vol_op + (10 * 60)) >= now) {
3826 *client_ec = VRESTARTING;
3831 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3832 FreeVolumeHeader(vp);
3836 #endif /* AFS_DEMAND_ATTACH_FS */
3838 LoadVolumeHeader(ec, vp);
3841 /* Only log the error if it was a totally unexpected error. Simply
3842 * a missing inode is likely to be caused by the volume being deleted */
3843 if (errno != ENXIO || LogLevel)
3844 Log("Volume %u: couldn't reread volume header\n",
3846 #ifdef AFS_DEMAND_ATTACH_FS
3847 if (VCanScheduleSalvage()) {
3848 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3853 #else /* AFS_DEMAND_ATTACH_FS */
3856 #endif /* AFS_DEMAND_ATTACH_FS */
3861 if (vp->shuttingDown) {
3868 if (programType == fileServer) {
3870 if (vp->goingOffline && !nowait) {
3872 #ifdef AFS_DEMAND_ATTACH_FS
3873 /* wait for the volume to go offline */
3874 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
3875 VWaitStateChange_r(vp);
3877 #elif defined(AFS_PTHREAD_ENV)
3878 VOL_CV_WAIT(&vol_put_volume_cond);
3879 #else /* AFS_PTHREAD_ENV */
3880 LWP_WaitProcess(VPutVolume);
3881 #endif /* AFS_PTHREAD_ENV */
3884 if (vp->specialStatus) {
3886 *ec = vp->specialStatus;
3887 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3890 } else if (V_inUse(vp) == 0 || vp->goingOffline) {
3901 #ifdef AFS_DEMAND_ATTACH_FS
3902 /* if no error, bump nUsers */
3905 VLRU_UpdateAccess_r(vp);
3908 VCancelReservation_r(rvp);
3911 if (client_ec && !*client_ec) {
3914 #else /* AFS_DEMAND_ATTACH_FS */
3915 /* if no error, bump nUsers */
3922 #endif /* AFS_DEMAND_ATTACH_FS */
3925 osi_Assert(vp || *ec);
3930 /***************************************************/
3931 /* Volume offline/detach routines */
3932 /***************************************************/
3934 /* caller MUST hold a heavyweight ref on vp */
3935 #ifdef AFS_DEMAND_ATTACH_FS
3937 VTakeOffline_r(Volume * vp)
3941 osi_Assert(vp->nUsers > 0);
3942 osi_Assert(programType == fileServer);
3944 VCreateReservation_r(vp);
3945 VWaitExclusiveState_r(vp);
3947 vp->goingOffline = 1;
3948 V_needsSalvaged(vp) = 1;
3950 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
3951 VCancelReservation_r(vp);
3953 #else /* AFS_DEMAND_ATTACH_FS */
3955 VTakeOffline_r(Volume * vp)
3957 osi_Assert(vp->nUsers > 0);
3958 osi_Assert(programType == fileServer);
3960 vp->goingOffline = 1;
3961 V_needsSalvaged(vp) = 1;
3963 #endif /* AFS_DEMAND_ATTACH_FS */
3966 VTakeOffline(Volume * vp)
3974 * force a volume offline.
3976 * @param[in] vp volume object pointer
3977 * @param[in] flags flags (see note below)
3979 * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
3980 * used when VUpdateVolume_r needs to call VForceOffline_r
3981 * (which in turn would normally call VUpdateVolume_r)
3983 * @see VUpdateVolume_r
3985 * @pre VOL_LOCK must be held.
3986 * for DAFS, caller must hold ref.
3988 * @note for DAFS, it _is safe_ to call this function from an
3991 * @post needsSalvaged flag is set.
3992 * for DAFS, salvage is requested.
3993 * no further references to the volume through the volume
3994 * package will be honored.
3995 * all file descriptor and vnode caches are invalidated.
3997 * @warning this is a heavy-handed interface. it results in
3998 * a volume going offline regardless of the current
3999 * reference count state.
4001 * @internal volume package internal use only
4004 VForceOffline_r(Volume * vp, int flags)
4008 #ifdef AFS_DEMAND_ATTACH_FS
4009 VChangeState_r(vp, VOL_STATE_ERROR);
4014 strcpy(V_offlineMessage(vp),
4015 "Forced offline due to internal error: volume needs to be salvaged");
4016 Log("Volume %u forced offline: it needs salvaging!\n", V_id(vp));
4019 vp->goingOffline = 0;
4020 V_needsSalvaged(vp) = 1;
4021 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
4022 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
4025 #ifdef AFS_DEMAND_ATTACH_FS
4026 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
4027 #endif /* AFS_DEMAND_ATTACH_FS */
4029 #ifdef AFS_PTHREAD_ENV
4030 CV_BROADCAST(&vol_put_volume_cond);
4031 #else /* AFS_PTHREAD_ENV */
4032 LWP_NoYieldSignal(VPutVolume);
4033 #endif /* AFS_PTHREAD_ENV */
4035 VReleaseVolumeHandles_r(vp);
4039 * force a volume offline.
4041 * @param[in] vp volume object pointer
4043 * @see VForceOffline_r
4046 VForceOffline(Volume * vp)
4049 VForceOffline_r(vp, 0);
4053 /* The opposite of VAttachVolume. The volume header is written to disk, with
4054 the inUse bit turned off. A copy of the header is maintained in memory,
4055 however (which is why this is VOffline, not VDetach).
4058 VOffline_r(Volume * vp, char *message)
4060 #ifndef AFS_DEMAND_ATTACH_FS
4062 VolumeId vid = V_id(vp);
4065 osi_Assert(programType != volumeUtility && programType != volumeServer);
4070 if (V_offlineMessage(vp)[0] == '\0')
4071 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4072 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4074 vp->goingOffline = 1;
4075 #ifdef AFS_DEMAND_ATTACH_FS
4076 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4077 VCreateReservation_r(vp);
4080 /* wait for the volume to go offline */
4081 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
4082 VWaitStateChange_r(vp);
4084 VCancelReservation_r(vp);
4085 #else /* AFS_DEMAND_ATTACH_FS */
4087 vp = VGetVolume_r(&error, vid); /* Wait for it to go offline */
4088 if (vp) /* In case it was reattached... */
4090 #endif /* AFS_DEMAND_ATTACH_FS */
4093 #ifdef AFS_DEMAND_ATTACH_FS
4095 * Take a volume offline in order to perform a volume operation.
4097 * @param[inout] ec address in which to store error code
4098 * @param[in] vp volume object pointer
4099 * @param[in] message volume offline status message
4102 * - VOL_LOCK is held
4103 * - caller MUST hold a heavyweight ref on vp
4106 * - volume is taken offline
4107 * - if possible, volume operation is promoted to running state
4108 * - on failure, *ec is set to nonzero
4110 * @note Although this function does not return any value, it may
4111 * still fail to promote our pending volume operation to
4112 * a running state. Any caller MUST check the value of *ec,
4113 * and MUST NOT blindly assume success.
4115 * @warning if the caller does not hold a lightweight ref on vp,
4116 * then it MUST NOT reference vp after this function
4117 * returns to the caller.
4119 * @internal volume package internal use only
4122 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
4124 osi_Assert(vp->pending_vol_op);
4130 if (V_offlineMessage(vp)[0] == '\0')
4131 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4132 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4134 vp->goingOffline = 1;
4135 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4136 VCreateReservation_r(vp);
4139 /* Wait for the volume to go offline */
4140 while (!VIsOfflineState(V_attachState(vp))) {
4141 /* do not give corrupted volumes to the volserver */
4142 if (vp->salvage.requested && vp->pending_vol_op->com.programType != salvageServer) {
4146 VWaitStateChange_r(vp);
4150 VCancelReservation_r(vp);
4152 #endif /* AFS_DEMAND_ATTACH_FS */
4155 VOffline(Volume * vp, char *message)
4158 VOffline_r(vp, message);
4162 /* This gets used for the most part by utility routines that don't want
4163 * to keep all the volume headers around. Generally, the file server won't
4164 * call this routine, because then the offline message in the volume header
4165 * (or other information) won't be available to clients. For NAMEI, also
4166 * close the file handles. However, the fileserver does call this during
4167 * an attach following a volume operation.
4170 VDetachVolume_r(Error * ec, Volume * vp)
4172 #ifdef FSSYNC_BUILD_CLIENT
4174 struct DiskPartition64 *tpartp;
4175 int notifyServer = 0;
4176 int useDone = FSYNC_VOL_ON;
4178 if (VCanUseFSSYNC()) {
4179 notifyServer = vp->needsPutBack;
4180 if (V_destroyMe(vp) == DESTROY_ME)
4181 useDone = FSYNC_VOL_DONE;
4182 #ifdef AFS_DEMAND_ATTACH_FS
4183 else if (!V_blessed(vp) || !V_inService(vp))
4184 useDone = FSYNC_VOL_LEAVE_OFF;
4187 tpartp = vp->partition;
4189 #endif /* FSSYNC_BUILD_CLIENT */
4191 *ec = 0; /* always "succeeds" */
4192 DeleteVolumeFromHashTable(vp);
4193 vp->shuttingDown = 1;
4194 #ifdef AFS_DEMAND_ATTACH_FS
4195 DeleteVolumeFromVByPList_r(vp);
4197 VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
4199 if (programType != fileServer)
4201 #endif /* AFS_DEMAND_ATTACH_FS */
4203 /* Will be detached sometime in the future--this is OK since volume is offline */
4205 /* XXX the following code should really be moved to VCheckDetach() since the volume
4206 * is not technically detached until the refcounts reach zero
4208 #ifdef FSSYNC_BUILD_CLIENT
4209 if (VCanUseFSSYNC() && notifyServer) {
4211 * Note: The server is not notified in the case of a bogus volume
4212 * explicitly to make it possible to create a volume, do a partial
4213 * restore, then abort the operation without ever putting the volume
4214 * online. This is essential in the case of a volume move operation
4215 * between two partitions on the same server. In that case, there
4216 * would be two instances of the same volume, one of them bogus,
4217 * which the file server would attempt to put on line
4219 FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
4220 /* XXX this code path is only hit by volume utilities, thus
4221 * V_BreakVolumeCallbacks will always be NULL. if we really
4222 * want to break callbacks in this path we need to use FSYNC_VolOp() */
4224 /* Dettaching it so break all callbacks on it */
4225 if (V_BreakVolumeCallbacks) {
4226 Log("volume %u detached; breaking all call backs\n", volume);
4227 (*V_BreakVolumeCallbacks) (volume);
4231 #endif /* FSSYNC_BUILD_CLIENT */
4235 VDetachVolume(Error * ec, Volume * vp)
4238 VDetachVolume_r(ec, vp);
4243 /***************************************************/
4244 /* Volume fd/inode handle closing routines */
4245 /***************************************************/
4247 /* For VDetachVolume, we close all cached file descriptors, but keep
4248 * the Inode handles in case we need to read from a busy volume.
4250 /* for demand attach, caller MUST hold ref count on vp */
4252 VCloseVolumeHandles_r(Volume * vp)
4254 #ifdef AFS_DEMAND_ATTACH_FS
4255 VolState state_save;
4257 state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
4262 * XXX need to investigate whether we can perform
4263 * DFlushVolume outside of vol_glock_mutex...
4265 * VCloseVnodeFiles_r drops the glock internally */
4266 DFlushVolume(vp->hashid);
4267 VCloseVnodeFiles_r(vp);
4269 #ifdef AFS_DEMAND_ATTACH_FS
4273 /* Too time consuming and unnecessary for the volserver */
4274 if (programType == fileServer) {
4275 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4276 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4277 IH_CONDSYNC(vp->diskDataHandle);
4279 IH_CONDSYNC(vp->linkHandle);
4280 #endif /* AFS_NT40_ENV */
4283 IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
4284 IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
4285 IH_REALLYCLOSE(vp->diskDataHandle);
4286 IH_REALLYCLOSE(vp->linkHandle);
4288 #ifdef AFS_DEMAND_ATTACH_FS
4289 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4294 VChangeState_r(vp, state_save);
4298 /* For both VForceOffline and VOffline, we close all relevant handles.
4299 * For VOffline, if we re-attach the volume, the files may possible be
4300 * different than before.
4302 /* for demand attach, caller MUST hold a ref count on vp */
4304 VReleaseVolumeHandles_r(Volume * vp)
4306 #ifdef AFS_DEMAND_ATTACH_FS
4307 VolState state_save;
4309 state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
4312 /* XXX need to investigate whether we can perform
4313 * DFlushVolume outside of vol_glock_mutex... */
4314 DFlushVolume(vp->hashid);
4316 VReleaseVnodeFiles_r(vp); /* releases the glock internally */
4318 #ifdef AFS_DEMAND_ATTACH_FS
4322 /* Too time consuming and unnecessary for the volserver */
4323 if (programType == fileServer) {
4324 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4325 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4326 IH_CONDSYNC(vp->diskDataHandle);
4328 IH_CONDSYNC(vp->linkHandle);
4329 #endif /* AFS_NT40_ENV */
4332 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
4333 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
4334 IH_RELEASE(vp->diskDataHandle);
4335 IH_RELEASE(vp->linkHandle);
4337 #ifdef AFS_DEMAND_ATTACH_FS
4338 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4343 VChangeState_r(vp, state_save);
4348 /***************************************************/
4349 /* Volume write and fsync routines */
4350 /***************************************************/
4353 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
4355 #ifdef AFS_DEMAND_ATTACH_FS
4356 VolState state_save;
4358 if (flags & VOL_UPDATE_WAIT) {
4359 VCreateReservation_r(vp);
4360 VWaitExclusiveState_r(vp);
4365 if (programType == fileServer)
4367 (V_inUse(vp) ? V_nextVnodeUnique(vp) +
4368 200 : V_nextVnodeUnique(vp));
4370 #ifdef AFS_DEMAND_ATTACH_FS
4371 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4375 WriteVolumeHeader_r(ec, vp);
4377 #ifdef AFS_DEMAND_ATTACH_FS
4379 VChangeState_r(vp, state_save);
4380 if (flags & VOL_UPDATE_WAIT) {
4381 VCancelReservation_r(vp);
4386 Log("VUpdateVolume: error updating volume header, volume %u (%s)\n",
4387 V_id(vp), V_name(vp));
4388 /* try to update on-disk header,
4389 * while preventing infinite recursion */
4390 if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
4391 VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
4397 VUpdateVolume(Error * ec, Volume * vp)
4400 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4405 VSyncVolume_r(Error * ec, Volume * vp, int flags)
4409 #ifdef AFS_DEMAND_ATTACH_FS
4410 VolState state_save;
4413 if (flags & VOL_SYNC_WAIT) {
4414 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4416 VUpdateVolume_r(ec, vp, 0);
4419 #ifdef AFS_DEMAND_ATTACH_FS
4420 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4423 fdP = IH_OPEN(V_diskDataHandle(vp));
4424 osi_Assert(fdP != NULL);
4425 code = FDH_SYNC(fdP);
4426 osi_Assert(code == 0);
4428 #ifdef AFS_DEMAND_ATTACH_FS
4430 VChangeState_r(vp, state_save);
4436 VSyncVolume(Error * ec, Volume * vp)
4439 VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
4444 /***************************************************/
4445 /* Volume dealloaction routines */
4446 /***************************************************/
4448 #ifdef AFS_DEMAND_ATTACH_FS
4450 FreeVolume(Volume * vp)
4452 /* free the heap space, iff it's safe.
4453 * otherwise, pull it out of the hash table, so it
4454 * will get deallocated when all refs to it go away */
4455 if (!VCheckFree(vp)) {
4456 DeleteVolumeFromHashTable(vp);
4457 DeleteVolumeFromVByPList_r(vp);
4459 /* make sure we invalidate the header cache entry */
4460 FreeVolumeHeader(vp);
4463 #endif /* AFS_DEMAND_ATTACH_FS */
4466 ReallyFreeVolume(Volume * vp)
4471 #ifdef AFS_DEMAND_ATTACH_FS
4473 VChangeState_r(vp, VOL_STATE_FREED);
4474 if (vp->pending_vol_op)
4475 free(vp->pending_vol_op);
4476 #endif /* AFS_DEMAND_ATTACH_FS */
4477 for (i = 0; i < nVNODECLASSES; i++)
4478 if (vp->vnodeIndex[i].bitmap)
4479 free(vp->vnodeIndex[i].bitmap);
4480 FreeVolumeHeader(vp);
4481 #ifndef AFS_DEMAND_ATTACH_FS
4482 DeleteVolumeFromHashTable(vp);
4483 #endif /* AFS_DEMAND_ATTACH_FS */
4487 /* check to see if we should shutdown this volume
4488 * returns 1 if volume was freed, 0 otherwise */
4489 #ifdef AFS_DEMAND_ATTACH_FS
4491 VCheckDetach(Volume * vp)
4496 if (vp->nUsers || vp->nWaiters)
4499 if (vp->shuttingDown) {
4501 if ((programType != fileServer) &&
4502 (V_inUse(vp) == programType) &&
4503 ((V_checkoutMode(vp) == V_VOLUPD) ||
4504 (V_checkoutMode(vp) == V_SECRETLY) ||
4505 ((V_checkoutMode(vp) == V_CLONE) &&
4506 (VolumeWriteable(vp))))) {
4508 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
4510 Log("VCheckDetach: volume header update for volume %u "
4511 "failed with errno %d\n", vp->hashid, errno);
4514 VReleaseVolumeHandles_r(vp);
4516 ReallyFreeVolume(vp);
4517 if (programType == fileServer) {
4518 CV_BROADCAST(&vol_put_volume_cond);
4523 #else /* AFS_DEMAND_ATTACH_FS */
4525 VCheckDetach(Volume * vp)
4533 if (vp->shuttingDown) {
4535 if ((programType != fileServer) &&
4536 (V_inUse(vp) == programType) &&
4537 ((V_checkoutMode(vp) == V_VOLUPD) ||
4538 (V_checkoutMode(vp) == V_SECRETLY) ||
4539 ((V_checkoutMode(vp) == V_CLONE) &&
4540 (VolumeWriteable(vp))))) {
4542 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
4544 Log("VCheckDetach: volume header update for volume %u failed with errno %d\n",
4548 VReleaseVolumeHandles_r(vp);
4549 ReallyFreeVolume(vp);
4550 if (programType == fileServer) {
4551 #if defined(AFS_PTHREAD_ENV)
4552 CV_BROADCAST(&vol_put_volume_cond);
4553 #else /* AFS_PTHREAD_ENV */
4554 LWP_NoYieldSignal(VPutVolume);
4555 #endif /* AFS_PTHREAD_ENV */
4560 #endif /* AFS_DEMAND_ATTACH_FS */
4562 /* check to see if we should offline this volume
4563 * return 1 if volume went offline, 0 otherwise */
4564 #ifdef AFS_DEMAND_ATTACH_FS
4566 VCheckOffline(Volume * vp)
4570 if (vp->goingOffline && !vp->nUsers) {
4572 osi_Assert(programType == fileServer);
4573 osi_Assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
4574 (V_attachState(vp) != VOL_STATE_FREED) &&
4575 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
4576 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
4577 (V_attachState(vp) != VOL_STATE_DELETED));
4581 * VOL_STATE_GOING_OFFLINE
4582 * VOL_STATE_SHUTTING_DOWN
4583 * VIsErrorState(V_attachState(vp))
4584 * VIsExclusiveState(V_attachState(vp))
4587 VCreateReservation_r(vp);
4588 VChangeState_r(vp, VOL_STATE_OFFLINING);
4591 /* must clear the goingOffline flag before we drop the glock */
4592 vp->goingOffline = 0;
4597 /* perform async operations */
4598 VUpdateVolume_r(&error, vp, 0);
4599 VCloseVolumeHandles_r(vp);
4602 if (V_offlineMessage(vp)[0]) {
4603 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
4604 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
4605 V_offlineMessage(vp));
4607 Log("VOffline: Volume %lu (%s) is now offline\n",
4608 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
4612 /* invalidate the volume header cache entry */
4613 FreeVolumeHeader(vp);
4615 /* if nothing changed state to error or salvaging,
4616 * drop state to unattached */
4617 if (!VIsErrorState(V_attachState(vp))) {
4618 VChangeState_r(vp, VOL_STATE_UNATTACHED);
4620 VCancelReservation_r(vp);
4621 /* no usage of vp is safe beyond this point */
4625 #else /* AFS_DEMAND_ATTACH_FS */
4627 VCheckOffline(Volume * vp)
4631 if (vp->goingOffline && !vp->nUsers) {
4633 osi_Assert(programType == fileServer);
4636 vp->goingOffline = 0;
4638 VUpdateVolume_r(&error, vp, 0);
4639 VCloseVolumeHandles_r(vp);
4641 if (V_offlineMessage(vp)[0]) {
4642 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
4643 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
4644 V_offlineMessage(vp));
4646 Log("VOffline: Volume %lu (%s) is now offline\n",
4647 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
4650 FreeVolumeHeader(vp);
4651 #ifdef AFS_PTHREAD_ENV
4652 CV_BROADCAST(&vol_put_volume_cond);
4653 #else /* AFS_PTHREAD_ENV */
4654 LWP_NoYieldSignal(VPutVolume);
4655 #endif /* AFS_PTHREAD_ENV */
4659 #endif /* AFS_DEMAND_ATTACH_FS */
4661 /***************************************************/
4662 /* demand attach fs ref counting routines */
4663 /***************************************************/
4665 #ifdef AFS_DEMAND_ATTACH_FS
4666 /* the following two functions handle reference counting for
4667 * asynchronous operations on volume structs.
4669 * their purpose is to prevent a VDetachVolume or VShutdown
4670 * from free()ing the Volume struct during an async i/o op */
4672 /* register with the async volume op ref counter */
4673 /* VCreateReservation_r moved into inline code header because it
4674 * is now needed in vnode.c -- tkeiser 11/20/2007
4678 * decrement volume-package internal refcount.
4680 * @param vp volume object pointer
4682 * @internal volume package internal use only
4685 * @arg VOL_LOCK is held
4686 * @arg lightweight refcount held
4688 * @post volume waiters refcount is decremented; volume may
4689 * have been deallocated/shutdown/offlined/salvaged/
4690 * whatever during the process
4692 * @warning once you have tossed your last reference (you can acquire
4693 * lightweight refs recursively) it is NOT SAFE to reference
4694 * a volume object pointer ever again
4696 * @see VCreateReservation_r
4698 * @note DEMAND_ATTACH_FS only
4701 VCancelReservation_r(Volume * vp)
4703 osi_Assert(--vp->nWaiters >= 0);
4704 if (vp->nWaiters == 0) {
4706 if (!VCheckDetach(vp)) {
4713 /* check to see if we should free this volume now
4714 * return 1 if volume was freed, 0 otherwise */
4716 VCheckFree(Volume * vp)
4719 if ((vp->nUsers == 0) &&
4720 (vp->nWaiters == 0) &&
4721 !(V_attachFlags(vp) & (VOL_IN_HASH |
4725 ReallyFreeVolume(vp);
4730 #endif /* AFS_DEMAND_ATTACH_FS */
4733 /***************************************************/
4734 /* online volume operations routines */
4735 /***************************************************/
4737 #ifdef AFS_DEMAND_ATTACH_FS
4739 * register a volume operation on a given volume.
4741 * @param[in] vp volume object
4742 * @param[in] vopinfo volume operation info object
4744 * @pre VOL_LOCK is held
4746 * @post volume operation info object attached to volume object.
4747 * volume operation statistics updated.
4749 * @note by "attached" we mean a copy of the passed in object is made
4751 * @internal volume package internal use only
4754 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4756 FSSYNC_VolOp_info * info;
4758 /* attach a vol op info node to the volume struct */
4759 info = (FSSYNC_VolOp_info *) malloc(sizeof(FSSYNC_VolOp_info));
4760 osi_Assert(info != NULL);
4761 memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
4762 vp->pending_vol_op = info;
4765 vp->stats.last_vol_op = FT_ApproxTime();
4766 vp->stats.vol_ops++;
4767 IncUInt64(&VStats.vol_ops);
4773 * deregister the volume operation attached to this volume.
4775 * @param[in] vp volume object pointer
4777 * @pre VOL_LOCK is held
4779 * @post the volume operation info object is detached from the volume object
4781 * @internal volume package internal use only
4784 VDeregisterVolOp_r(Volume * vp)
4786 if (vp->pending_vol_op) {
4787 free(vp->pending_vol_op);
4788 vp->pending_vol_op = NULL;
4792 #endif /* AFS_DEMAND_ATTACH_FS */
4795 * determine whether it is safe to leave a volume online during
4796 * the volume operation described by the vopinfo object.
4798 * @param[in] vp volume object
4799 * @param[in] vopinfo volume operation info object
4801 * @return whether it is safe to leave volume online
4802 * @retval 0 it is NOT SAFE to leave the volume online
4803 * @retval 1 it is safe to leave the volume online during the operation
4806 * @arg VOL_LOCK is held
4807 * @arg disk header attached to vp (heavyweight ref on vp will guarantee
4808 * this condition is met)
4810 * @internal volume package internal use only
4813 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4815 return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
4816 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4817 (vopinfo->com.reason == V_READONLY ||
4818 (!VolumeWriteable(vp) &&
4819 (vopinfo->com.reason == V_CLONE ||
4820 vopinfo->com.reason == V_DUMP)))));
4824 * same as VVolOpLeaveOnline_r, but does not require a volume with an attached
4827 * @param[in] vp volume object
4828 * @param[in] vopinfo volume operation info object
4830 * @return whether it is safe to leave volume online
4831 * @retval 0 it is NOT SAFE to leave the volume online
4832 * @retval 1 it is safe to leave the volume online during the operation
4833 * @retval -1 unsure; volume header is required in order to know whether or
4834 * not is is safe to leave the volume online
4836 * @pre VOL_LOCK is held
4838 * @internal volume package internal use only
4841 VVolOpLeaveOnlineNoHeader_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4843 /* follow the logic in VVolOpLeaveOnline_r; this is the same, except
4844 * assume that we don't know VolumeWriteable; return -1 if the answer
4845 * depends on VolumeWriteable */
4847 if (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline) {
4850 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4851 vopinfo->com.reason == V_READONLY) {
4855 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4856 (vopinfo->com.reason == V_CLONE ||
4857 vopinfo->com.reason == V_DUMP)) {
4859 /* must know VolumeWriteable */
4866 * determine whether VBUSY should be set during this volume operation.
4868 * @param[in] vp volume object
4869 * @param[in] vopinfo volume operation info object
4871 * @return whether VBUSY should be set
4872 * @retval 0 VBUSY does NOT need to be set
4873 * @retval 1 VBUSY SHOULD be set
4875 * @pre VOL_LOCK is held
4877 * @internal volume package internal use only
4880 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4882 return ((vopinfo->com.command == FSYNC_VOL_OFF &&
4883 vopinfo->com.reason == FSYNC_SALVAGE) ||
4884 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4885 (vopinfo->com.reason == V_CLONE ||
4886 vopinfo->com.reason == V_DUMP)));
4890 /***************************************************/
4891 /* online salvager routines */
4892 /***************************************************/
4893 #if defined(AFS_DEMAND_ATTACH_FS)
4896 * offline a volume to let it be salvaged.
4898 * @param[in] vp Volume to offline
4900 * @return whether we offlined the volume successfully
4901 * @retval 0 volume was not offlined
4902 * @retval 1 volume is now offline
4904 * @note This is similar to VCheckOffline, but slightly different. We do not
4905 * deal with vp->goingOffline, and we try to avoid touching the volume
4906 * header except just to set needsSalvaged
4908 * @pre VOL_LOCK held
4909 * @pre vp->nUsers == 0
4910 * @pre V_attachState(vp) == VOL_STATE_SALVAGE_REQ
4913 VOfflineForSalvage_r(struct Volume *vp)
4917 VCreateReservation_r(vp);
4918 VWaitExclusiveState_r(vp);
4920 if (vp->nUsers || V_attachState(vp) == VOL_STATE_SALVAGING) {
4921 /* Someone's using the volume, or someone got to scheduling the salvage
4922 * before us. I don't think either of these should be possible, as we
4923 * should gain no new heavyweight references while we're trying to
4924 * salvage, but just to be sure... */
4925 VCancelReservation_r(vp);
4929 VChangeState_r(vp, VOL_STATE_OFFLINING);
4933 V_needsSalvaged(vp) = 1;
4934 /* ignore error; updating needsSalvaged is just best effort */
4935 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
4937 VCloseVolumeHandles_r(vp);
4939 FreeVolumeHeader(vp);
4941 /* volume has been effectively offlined; we can mark it in the SALVAGING
4942 * state now, which lets FSSYNC give it away */
4943 VChangeState_r(vp, VOL_STATE_SALVAGING);
4945 VCancelReservation_r(vp);
4951 * check whether a salvage needs to be performed on this volume.
4953 * @param[in] vp pointer to volume object
4955 * @return status code
4956 * @retval 0 no salvage scheduled
4957 * @retval 1 a salvage has been scheduled with the salvageserver
4959 * @pre VOL_LOCK is held
4961 * @post if salvage request flag is set and nUsers and nWaiters are zero,
4962 * then a salvage will be requested
4964 * @note this is one of the event handlers called by VCancelReservation_r
4966 * @see VCancelReservation_r
4968 * @internal volume package internal use only.
4971 VCheckSalvage(Volume * vp)
4974 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
4977 if (!vp->salvage.requested) {
4981 /* prevent recursion; some of the code below creates and removes
4982 * lightweight refs, which can call VCheckSalvage */
4983 if (vp->salvage.scheduling) {
4986 vp->salvage.scheduling = 1;
4988 if (V_attachState(vp) == VOL_STATE_SALVAGE_REQ) {
4989 if (!VOfflineForSalvage_r(vp)) {
4990 vp->salvage.scheduling = 0;
4995 if (vp->salvage.requested) {
4996 VScheduleSalvage_r(vp);
4999 vp->salvage.scheduling = 0;
5000 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5005 * request volume salvage.
5007 * @param[out] ec computed client error code
5008 * @param[in] vp volume object pointer
5009 * @param[in] reason reason code (passed to salvageserver via SALVSYNC)
5010 * @param[in] flags see flags note below
5013 * VOL_SALVAGE_INVALIDATE_HEADER causes volume header cache entry
5014 * to be invalidated.
5016 * @pre VOL_LOCK is held.
5018 * @post volume state is changed.
5019 * for fileserver, salvage will be requested once refcount reaches zero.
5021 * @return operation status code
5022 * @retval 0 volume salvage will occur
5023 * @retval 1 volume salvage could not be scheduled
5027 * @note in the fileserver, this call does not synchronously schedule a volume
5028 * salvage. rather, it sets volume state so that when volume refcounts
5029 * reach zero, a volume salvage will occur. by "refcounts", we mean both
5030 * nUsers and nWaiters must be zero.
5032 * @internal volume package internal use only.
5035 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
5039 * for DAFS volume utilities that are not supposed to schedule salvages,
5040 * just transition to error state instead
5042 if (!VCanScheduleSalvage()) {
5043 VChangeState_r(vp, VOL_STATE_ERROR);
5048 if (programType != fileServer && !VCanUseFSSYNC()) {
5049 VChangeState_r(vp, VOL_STATE_ERROR);
5054 if (!vp->salvage.requested) {
5055 vp->salvage.requested = 1;
5056 vp->salvage.reason = reason;
5057 vp->stats.last_salvage = FT_ApproxTime();
5059 /* Note that it is not possible for us to reach this point if a
5060 * salvage is already running on this volume (even if the fileserver
5061 * was restarted during the salvage). If a salvage were running, the
5062 * salvager would have write-locked the volume header file, so when
5063 * we tried to lock the volume header, the lock would have failed,
5064 * and we would have failed during attachment prior to calling
5065 * VRequestSalvage. So we know that we can schedule salvages without
5066 * fear of a salvage already running for this volume. */
5068 if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
5070 /* if we don't need to offline the volume, we can go directly
5071 * to SALVAGING. SALVAGING says the volume is offline and is
5072 * either salvaging or ready to be handed to the salvager.
5073 * SALVAGE_REQ says that we want to salvage the volume, but we
5074 * are waiting for it to go offline first. */
5075 if (flags & VOL_SALVAGE_NO_OFFLINE) {
5076 VChangeState_r(vp, VOL_STATE_SALVAGING);
5078 VChangeState_r(vp, VOL_STATE_SALVAGE_REQ);
5079 if (vp->nUsers == 0) {
5080 /* normally VOfflineForSalvage_r would be called from
5081 * PutVolume et al when nUsers reaches 0, but if
5082 * it's already 0, just do it ourselves, since PutVolume
5083 * isn't going to get called */
5084 VOfflineForSalvage_r(vp);
5089 Log("VRequestSalvage: volume %u online salvaged too many times; forced offline.\n", vp->hashid);
5091 /* make sure neither VScheduleSalvage_r nor
5092 * VUpdateSalvagePriority_r try to schedule another salvage */
5093 vp->salvage.requested = vp->salvage.scheduled = 0;
5095 VChangeState_r(vp, VOL_STATE_ERROR);
5099 if (flags & VOL_SALVAGE_INVALIDATE_HEADER) {
5100 /* Instead of ReleaseVolumeHeader, we do FreeVolumeHeader()
5101 so that the the next VAttachVolumeByVp_r() invocation
5102 of attach2() will pull in a cached header
5103 entry and fail, then load a fresh one from disk and attach
5106 FreeVolumeHeader(vp);
5113 * update salvageserver scheduling priority for a volume.
5115 * @param[in] vp pointer to volume object
5117 * @return operation status
5119 * @retval 1 request denied, or SALVSYNC communications failure
5121 * @pre VOL_LOCK is held.
5123 * @post in-core salvage priority counter is incremented. if at least
5124 * SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
5125 * last SALVSYNC_RAISEPRIO request, we contact the salvageserver
5126 * to update its priority queue. if no salvage is scheduled,
5127 * this function is a no-op.
5129 * @note DAFS fileserver only
5131 * @note this should be called whenever a VGetVolume fails due to a
5132 * pending salvage request
5134 * @todo should set exclusive state and drop glock around salvsync call
5136 * @internal volume package internal use only.
5139 VUpdateSalvagePriority_r(Volume * vp)
5143 #ifdef SALVSYNC_BUILD_CLIENT
5148 now = FT_ApproxTime();
5150 /* update the salvageserver priority queue occasionally so that
5151 * frequently requested volumes get moved to the head of the queue
5153 if ((vp->salvage.scheduled) &&
5154 (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
5155 code = SALVSYNC_SalvageVolume(vp->hashid,
5156 VPartitionPath(vp->partition),
5161 vp->stats.last_salvage_req = now;
5162 if (code != SYNC_OK) {
5166 #endif /* SALVSYNC_BUILD_CLIENT */
5171 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5173 /* A couple of little helper functions. These return true if we tried to
5174 * use this mechanism to schedule a salvage, false if we haven't tried.
5175 * If we did try a salvage then the results are contained in code.
5179 try_SALVSYNC(Volume *vp, char *partName, int *code) {
5180 #ifdef SALVSYNC_BUILD_CLIENT
5181 if (VCanUseSALVSYNC()) {
5182 Log("Scheduling salvage for volume %lu on part %s over SALVSYNC\n",
5183 afs_printable_uint32_lu(vp->hashid), partName);
5185 /* can't use V_id() since there's no guarantee
5186 * we have the disk data header at this point */
5187 *code = SALVSYNC_SalvageVolume(vp->hashid,
5200 try_FSSYNC(Volume *vp, char *partName, int *code) {
5201 #ifdef FSSYNC_BUILD_CLIENT
5202 if (VCanUseFSSYNC()) {
5203 Log("Scheduling salvage for volume %lu on part %s over FSSYNC\n",
5204 afs_printable_uint32_lu(vp->hashid), partName);
5207 * If we aren't the fileserver, tell the fileserver the volume
5208 * needs to be salvaged. We could directly tell the
5209 * salvageserver, but the fileserver keeps track of some stats
5210 * related to salvages, and handles some other salvage-related
5211 * complications for us.
5213 *code = FSYNC_VolOp(vp->hashid, partName,
5214 FSYNC_VOL_FORCE_ERROR, FSYNC_SALVAGE, NULL);
5217 #endif /* FSSYNC_BUILD_CLIENT */
5222 * schedule a salvage with the salvage server or fileserver.
5224 * @param[in] vp pointer to volume object
5226 * @return operation status
5227 * @retval 0 salvage scheduled successfully
5228 * @retval 1 salvage not scheduled, or SALVSYNC/FSSYNC com error
5231 * @arg VOL_LOCK is held.
5232 * @arg nUsers and nWaiters should be zero.
5234 * @post salvageserver or fileserver is sent a salvage request
5236 * @note If we are the fileserver, the request will be sent to the salvage
5237 * server over SALVSYNC. If we are not the fileserver, the request will be
5238 * sent to the fileserver over FSSYNC (FSYNC_VOL_FORCE_ERROR/FSYNC_SALVAGE).
5242 * @internal volume package internal use only.
5245 VScheduleSalvage_r(Volume * vp)
5249 VolState state_save;
5250 VThreadOptions_t * thread_opts;
5253 osi_Assert(VCanUseSALVSYNC() || VCanUseFSSYNC());
5255 if (vp->nWaiters || vp->nUsers) {
5259 /* prevent endless salvage,attach,salvage,attach,... loops */
5260 if (vp->stats.salvages >= SALVAGE_COUNT_MAX)
5264 * don't perform salvsync ops on certain threads
5266 thread_opts = pthread_getspecific(VThread_key);
5267 if (thread_opts == NULL) {
5268 thread_opts = &VThread_defaults;
5270 if (thread_opts->disallow_salvsync || vol_disallow_salvsync) {
5274 if (vp->salvage.scheduled) {
5278 VCreateReservation_r(vp);
5279 VWaitExclusiveState_r(vp);
5282 * XXX the scheduling process should really be done asynchronously
5283 * to avoid fssync deadlocks
5285 if (!vp->salvage.scheduled) {
5286 /* if we haven't previously scheduled a salvage, do so now
5288 * set the volume to an exclusive state and drop the lock
5289 * around the SALVSYNC call
5291 strlcpy(partName, VPartitionPath(vp->partition), sizeof(partName));
5292 state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
5295 osi_Assert(try_SALVSYNC(vp, partName, &code) ||
5296 try_FSSYNC(vp, partName, &code));
5299 VChangeState_r(vp, state_save);
5301 if (code == SYNC_OK) {
5302 vp->salvage.scheduled = 1;
5303 vp->stats.last_salvage_req = FT_ApproxTime();
5304 if (VCanUseSALVSYNC()) {
5305 /* don't record these stats for non-fileservers; let the
5306 * fileserver take care of these */
5307 vp->stats.salvages++;
5308 IncUInt64(&VStats.salvages);
5313 case SYNC_BAD_COMMAND:
5314 case SYNC_COM_ERROR:
5317 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5318 "denied\n", afs_printable_uint32_lu(vp->hashid));
5321 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5322 "received unknown protocol error %d\n",
5323 afs_printable_uint32_lu(vp->hashid), code);
5327 if (VCanUseFSSYNC()) {
5328 VChangeState_r(vp, VOL_STATE_ERROR);
5332 VCancelReservation_r(vp);
5335 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5337 #ifdef SALVSYNC_BUILD_CLIENT
5340 * connect to the salvageserver SYNC service.
5342 * @return operation status
5346 * @post connection to salvageserver SYNC service established
5348 * @see VConnectSALV_r
5349 * @see VDisconnectSALV
5350 * @see VReconnectSALV
5357 retVal = VConnectSALV_r();
5363 * connect to the salvageserver SYNC service.
5365 * @return operation status
5369 * @pre VOL_LOCK is held.
5371 * @post connection to salvageserver SYNC service established
5374 * @see VDisconnectSALV_r
5375 * @see VReconnectSALV_r
5376 * @see SALVSYNC_clientInit
5378 * @internal volume package internal use only.
5381 VConnectSALV_r(void)
5383 return SALVSYNC_clientInit();
5387 * disconnect from the salvageserver SYNC service.
5389 * @return operation status
5392 * @pre client should have a live connection to the salvageserver
5394 * @post connection to salvageserver SYNC service destroyed
5396 * @see VDisconnectSALV_r
5398 * @see VReconnectSALV
5401 VDisconnectSALV(void)
5404 VDisconnectSALV_r();
5410 * disconnect from the salvageserver SYNC service.
5412 * @return operation status
5416 * @arg VOL_LOCK is held.
5417 * @arg client should have a live connection to the salvageserver.
5419 * @post connection to salvageserver SYNC service destroyed
5421 * @see VDisconnectSALV
5422 * @see VConnectSALV_r
5423 * @see VReconnectSALV_r
5424 * @see SALVSYNC_clientFinis
5426 * @internal volume package internal use only.
5429 VDisconnectSALV_r(void)
5431 return SALVSYNC_clientFinis();
5435 * disconnect and then re-connect to the salvageserver SYNC service.
5437 * @return operation status
5441 * @pre client should have a live connection to the salvageserver
5443 * @post old connection is dropped, and a new one is established
5446 * @see VDisconnectSALV
5447 * @see VReconnectSALV_r
5450 VReconnectSALV(void)
5454 retVal = VReconnectSALV_r();
5460 * disconnect and then re-connect to the salvageserver SYNC service.
5462 * @return operation status
5467 * @arg VOL_LOCK is held.
5468 * @arg client should have a live connection to the salvageserver.
5470 * @post old connection is dropped, and a new one is established
5472 * @see VConnectSALV_r
5473 * @see VDisconnectSALV
5474 * @see VReconnectSALV
5475 * @see SALVSYNC_clientReconnect
5477 * @internal volume package internal use only.
5480 VReconnectSALV_r(void)
5482 return SALVSYNC_clientReconnect();
5484 #endif /* SALVSYNC_BUILD_CLIENT */
5485 #endif /* AFS_DEMAND_ATTACH_FS */
5488 /***************************************************/
5489 /* FSSYNC routines */
5490 /***************************************************/
5492 /* This must be called by any volume utility which needs to run while the
5493 file server is also running. This is separated from VInitVolumePackage2 so
5494 that a utility can fork--and each of the children can independently
5495 initialize communication with the file server */
5496 #ifdef FSSYNC_BUILD_CLIENT
5498 * connect to the fileserver SYNC service.
5500 * @return operation status
5505 * @arg VInit must equal 2.
5506 * @arg Program Type must not be fileserver or salvager.
5508 * @post connection to fileserver SYNC service established
5511 * @see VDisconnectFS
5512 * @see VChildProcReconnectFS
5519 retVal = VConnectFS_r();
5525 * connect to the fileserver SYNC service.
5527 * @return operation status
5532 * @arg VInit must equal 2.
5533 * @arg Program Type must not be fileserver or salvager.
5534 * @arg VOL_LOCK is held.
5536 * @post connection to fileserver SYNC service established
5539 * @see VDisconnectFS_r
5540 * @see VChildProcReconnectFS_r
5542 * @internal volume package internal use only.
5548 osi_Assert((VInit == 2) &&
5549 (programType != fileServer) &&
5550 (programType != salvager));
5551 rc = FSYNC_clientInit();
5559 * disconnect from the fileserver SYNC service.
5562 * @arg client should have a live connection to the fileserver.
5563 * @arg VOL_LOCK is held.
5564 * @arg Program Type must not be fileserver or salvager.
5566 * @post connection to fileserver SYNC service destroyed
5568 * @see VDisconnectFS
5570 * @see VChildProcReconnectFS_r
5572 * @internal volume package internal use only.
5575 VDisconnectFS_r(void)
5577 osi_Assert((programType != fileServer) &&
5578 (programType != salvager));
5579 FSYNC_clientFinis();
5584 * disconnect from the fileserver SYNC service.
5587 * @arg client should have a live connection to the fileserver.
5588 * @arg Program Type must not be fileserver or salvager.
5590 * @post connection to fileserver SYNC service destroyed
5592 * @see VDisconnectFS_r
5594 * @see VChildProcReconnectFS
5605 * connect to the fileserver SYNC service from a child process following a fork.
5607 * @return operation status
5612 * @arg VOL_LOCK is held.
5613 * @arg current FSYNC handle is shared with a parent process
5615 * @post current FSYNC handle is discarded and a new connection to the
5616 * fileserver SYNC service is established
5618 * @see VChildProcReconnectFS
5620 * @see VDisconnectFS_r
5622 * @internal volume package internal use only.
5625 VChildProcReconnectFS_r(void)
5627 return FSYNC_clientChildProcReconnect();
5631 * connect to the fileserver SYNC service from a child process following a fork.
5633 * @return operation status
5637 * @pre current FSYNC handle is shared with a parent process
5639 * @post current FSYNC handle is discarded and a new connection to the
5640 * fileserver SYNC service is established
5642 * @see VChildProcReconnectFS_r
5644 * @see VDisconnectFS
5647 VChildProcReconnectFS(void)
5651 ret = VChildProcReconnectFS_r();
5655 #endif /* FSSYNC_BUILD_CLIENT */
5658 /***************************************************/
5659 /* volume bitmap routines */
5660 /***************************************************/
5663 * allocate a vnode bitmap number for the vnode
5665 * @param[out] ec error code
5666 * @param[in] vp volume object pointer
5667 * @param[in] index vnode index number for the vnode
5668 * @param[in] flags flag values described in note
5670 * @note for DAFS, flags parameter controls locking behavior.
5671 * If (flags & VOL_ALLOC_BITMAP_WAIT) is set, then this function
5672 * will create a reservation and block on any other exclusive
5673 * operations. Otherwise, this function assumes the caller
5674 * already has exclusive access to vp, and we just change the
5677 * @pre VOL_LOCK held
5679 * @return bit number allocated
5685 VAllocBitmapEntry_r(Error * ec, Volume * vp,
5686 struct vnodeIndex *index, int flags)
5690 #ifdef AFS_DEMAND_ATTACH_FS
5691 VolState state_save;
5692 #endif /* AFS_DEMAND_ATTACH_FS */
5696 /* This test is probably redundant */
5697 if (!VolumeWriteable(vp)) {
5698 *ec = (bit32) VREADONLY;
5702 #ifdef AFS_DEMAND_ATTACH_FS
5703 if (flags & VOL_ALLOC_BITMAP_WAIT) {
5704 VCreateReservation_r(vp);
5705 VWaitExclusiveState_r(vp);
5707 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
5708 #endif /* AFS_DEMAND_ATTACH_FS */
5711 if ((programType == fileServer) && !index->bitmap) {
5713 #ifndef AFS_DEMAND_ATTACH_FS
5714 /* demand attach fs uses the volume state to avoid races.
5715 * specialStatus field is not used at all */
5717 if (vp->specialStatus == VBUSY) {
5718 if (vp->goingOffline) { /* vos dump waiting for the volume to
5719 * go offline. We probably come here
5720 * from AddNewReadableResidency */
5723 while (vp->specialStatus == VBUSY) {
5724 #ifdef AFS_PTHREAD_ENV
5728 #else /* !AFS_PTHREAD_ENV */
5730 #endif /* !AFS_PTHREAD_ENV */
5734 #endif /* !AFS_DEMAND_ATTACH_FS */
5736 if (!index->bitmap) {
5737 #ifndef AFS_DEMAND_ATTACH_FS
5738 vp->specialStatus = VBUSY; /* Stop anyone else from using it. */
5739 #endif /* AFS_DEMAND_ATTACH_FS */
5740 for (i = 0; i < nVNODECLASSES; i++) {
5741 VGetBitmap_r(ec, vp, i);
5743 #ifdef AFS_DEMAND_ATTACH_FS
5744 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
5745 #else /* AFS_DEMAND_ATTACH_FS */
5746 DeleteVolumeFromHashTable(vp);
5747 vp->shuttingDown = 1; /* Let who has it free it. */
5748 vp->specialStatus = 0;
5749 #endif /* AFS_DEMAND_ATTACH_FS */
5753 #ifndef AFS_DEMAND_ATTACH_FS
5755 vp->specialStatus = 0; /* Allow others to have access. */
5756 #endif /* AFS_DEMAND_ATTACH_FS */
5759 #endif /* BITMAP_LATER */
5761 #ifdef AFS_DEMAND_ATTACH_FS
5763 #endif /* AFS_DEMAND_ATTACH_FS */
5764 bp = index->bitmap + index->bitmapOffset;
5765 ep = index->bitmap + index->bitmapSize;
5767 if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
5769 index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
5772 o = ffs(~*bp) - 1; /* ffs is documented in BSTRING(3) */
5774 ret = ((bp - index->bitmap) * 8 + o);
5775 #ifdef AFS_DEMAND_ATTACH_FS
5777 #endif /* AFS_DEMAND_ATTACH_FS */
5780 bp += sizeof(bit32) /* i.e. 4 */ ;
5782 /* No bit map entry--must grow bitmap */
5784 realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
5785 osi_Assert(bp != NULL);
5787 bp += index->bitmapSize;
5788 memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
5789 index->bitmapOffset = index->bitmapSize;
5790 index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
5792 ret = index->bitmapOffset * 8;
5793 #ifdef AFS_DEMAND_ATTACH_FS
5795 #endif /* AFS_DEMAND_ATTACH_FS */
5798 #ifdef AFS_DEMAND_ATTACH_FS
5799 VChangeState_r(vp, state_save);
5800 if (flags & VOL_ALLOC_BITMAP_WAIT) {
5801 VCancelReservation_r(vp);
5803 #endif /* AFS_DEMAND_ATTACH_FS */
5808 VAllocBitmapEntry(Error * ec, Volume * vp, struct vnodeIndex * index)
5812 retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
5818 VFreeBitMapEntry_r(Error * ec, struct vnodeIndex *index,
5821 unsigned int offset;
5827 #endif /* BITMAP_LATER */
5828 offset = bitNumber >> 3;
5829 if (offset >= index->bitmapSize) {
5833 if (offset < index->bitmapOffset)
5834 index->bitmapOffset = offset & ~3; /* Truncate to nearest bit32 */
5835 *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
5839 VFreeBitMapEntry(Error * ec, struct vnodeIndex *index,
5843 VFreeBitMapEntry_r(ec, index, bitNumber);
5847 /* this function will drop the glock internally.
5848 * for old pthread fileservers, this is safe thanks to vbusy.
5850 * for demand attach fs, caller must have already called
5851 * VCreateReservation_r and VWaitExclusiveState_r */
5853 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
5855 StreamHandle_t *file;
5856 afs_sfsize_t nVnodes, size;
5857 struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
5858 struct vnodeIndex *vip = &vp->vnodeIndex[class];
5859 struct VnodeDiskObject *vnode;
5860 unsigned int unique = 0;
5864 #endif /* BITMAP_LATER */
5865 #ifdef AFS_DEMAND_ATTACH_FS
5866 VolState state_save;
5867 #endif /* AFS_DEMAND_ATTACH_FS */
5871 #ifdef AFS_DEMAND_ATTACH_FS
5872 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
5873 #endif /* AFS_DEMAND_ATTACH_FS */
5876 fdP = IH_OPEN(vip->handle);
5877 osi_Assert(fdP != NULL);
5878 file = FDH_FDOPEN(fdP, "r");
5879 osi_Assert(file != NULL);
5880 vnode = (VnodeDiskObject *) malloc(vcp->diskSize);
5881 osi_Assert(vnode != NULL);
5882 size = OS_SIZE(fdP->fd_fd);
5883 osi_Assert(size != -1);
5884 nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
5886 vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4; /* The 10 is a little extra so
5887 * a few files can be created in this volume,
5888 * the whole thing is rounded up to nearest 4
5889 * bytes, because the bit map allocator likes
5892 BitMap = (byte *) calloc(1, vip->bitmapSize);
5893 osi_Assert(BitMap != NULL);
5894 #else /* BITMAP_LATER */
5895 vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
5896 osi_Assert(vip->bitmap != NULL);
5897 vip->bitmapOffset = 0;
5898 #endif /* BITMAP_LATER */
5899 if (STREAM_ASEEK(file, vcp->diskSize) != -1) {
5901 for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
5902 if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
5904 if (vnode->type != vNull) {
5905 if (vnode->vnodeMagic != vcp->magic) {
5906 Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
5911 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
5912 #else /* BITMAP_LATER */
5913 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
5914 #endif /* BITMAP_LATER */
5915 if (unique <= vnode->uniquifier)
5916 unique = vnode->uniquifier + 1;
5918 #ifndef AFS_PTHREAD_ENV
5919 if ((bitNumber & 0x00ff) == 0x0ff) { /* every 256 iterations */
5922 #endif /* !AFS_PTHREAD_ENV */
5925 if (vp->nextVnodeUnique < unique) {
5926 Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
5929 /* Paranoia, partly justified--I think fclose after fdopen
5930 * doesn't seem to close fd. In any event, the documentation
5931 * doesn't specify, so it's safer to close it twice.
5939 /* There may have been a racing condition with some other thread, both
5940 * creating the bitmaps for this volume. If the other thread was faster
5941 * the pointer to bitmap should already be filled and we can free ours.
5943 if (vip->bitmap == NULL) {
5944 vip->bitmap = BitMap;
5945 vip->bitmapOffset = 0;
5947 free((byte *) BitMap);
5948 #endif /* BITMAP_LATER */
5949 #ifdef AFS_DEMAND_ATTACH_FS
5950 VChangeState_r(vp, state_save);
5951 #endif /* AFS_DEMAND_ATTACH_FS */
5955 /***************************************************/
5956 /* Volume Path and Volume Number utility routines */
5957 /***************************************************/
5960 * find the first occurrence of a volume header file and return the path.
5962 * @param[out] ec outbound error code
5963 * @param[in] volumeId volume id to find
5964 * @param[out] partitionp pointer to disk partition path string
5965 * @param[out] namep pointer to volume header file name string
5967 * @post path to first occurrence of volume header is returned in partitionp
5968 * and namep, or ec is set accordingly.
5970 * @warning this function is NOT re-entrant -- partitionp and namep point to
5971 * static data segments
5973 * @note if a volume utility inadvertently leaves behind a stale volume header
5974 * on a vice partition, it is possible for callers to get the wrong one,
5975 * depending on the order of the disk partition linked list.
5979 VGetVolumePath(Error * ec, VolId volumeId, char **partitionp, char **namep)
5981 static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
5982 char path[VMAXPATHLEN];
5984 struct DiskPartition64 *dp;
5988 (void)afs_snprintf(&name[1], (sizeof name) - 1, VFORMAT, afs_printable_uint32_lu(volumeId));
5989 for (dp = DiskPartitionList; dp; dp = dp->next) {
5990 struct afs_stat status;
5991 strcpy(path, VPartitionPath(dp));
5993 if (afs_stat(path, &status) == 0) {
5994 strcpy(partition, dp->name);
6001 *partitionp = *namep = NULL;
6003 *partitionp = partition;
6009 * extract a volume number from a volume header filename string.
6011 * @param[in] name volume header filename string
6013 * @return volume number
6015 * @note the string must be of the form VFORMAT. the only permissible
6016 * deviation is a leading '/' character.
6021 VolumeNumber(char *name)
6025 return atoi(name + 1);
6029 * compute the volume header filename.
6031 * @param[in] volumeId
6033 * @return volume header filename
6035 * @post volume header filename string is constructed
6037 * @warning this function is NOT re-entrant -- the returned string is
6038 * stored in a static char array. see VolumeExternalName_r
6039 * for a re-entrant equivalent.
6041 * @see VolumeExternalName_r
6043 * @deprecated due to the above re-entrancy warning, this interface should
6044 * be considered deprecated. Please use VolumeExternalName_r
6048 VolumeExternalName(VolumeId volumeId)
6050 static char name[VMAXPATHLEN];
6051 (void)afs_snprintf(name, sizeof name, VFORMAT, afs_printable_uint32_lu(volumeId));
6056 * compute the volume header filename.
6058 * @param[in] volumeId
6059 * @param[inout] name array in which to store filename
6060 * @param[in] len length of name array
6062 * @return result code from afs_snprintf
6064 * @see VolumeExternalName
6067 * @note re-entrant equivalent of VolumeExternalName
6070 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
6072 return afs_snprintf(name, len, VFORMAT, afs_printable_uint32_lu(volumeId));
6076 /***************************************************/
6077 /* Volume Usage Statistics routines */
6078 /***************************************************/
6080 #if OPENAFS_VOL_STATS
6081 #define OneDay (86400) /* 24 hours' worth of seconds */
6083 #define OneDay (24*60*60) /* 24 hours */
6084 #endif /* OPENAFS_VOL_STATS */
6087 Midnight(time_t t) {
6088 struct tm local, *l;
6091 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
6092 l = localtime_r(&t, &local);
6098 /* the following is strictly speaking problematic on the
6099 switching day to daylight saving time, after the switch,
6100 as tm_isdst does not match. Similarly, on the looong day when
6101 switching back the OneDay check will not do what naively expected!
6102 The effects are minor, though, and more a matter of interpreting
6104 #ifndef AFS_PTHREAD_ENV
6107 local.tm_hour = local.tm_min=local.tm_sec = 0;
6108 midnight = mktime(&local);
6109 if (midnight != (time_t) -1) return(midnight);
6111 return( (t/OneDay)*OneDay );
6115 /*------------------------------------------------------------------------
6116 * [export] VAdjustVolumeStatistics
6119 * If we've passed midnight, we need to update all the day use
6120 * statistics as well as zeroing the detailed volume statistics
6121 * (if we are implementing them).
6124 * vp : Pointer to the volume structure describing the lucky
6125 * volume being considered for update.
6131 * Nothing interesting.
6135 *------------------------------------------------------------------------*/
6138 VAdjustVolumeStatistics_r(Volume * vp)
6140 unsigned int now = FT_ApproxTime();
6142 if (now - V_dayUseDate(vp) > OneDay) {
6145 ndays = (now - V_dayUseDate(vp)) / OneDay;
6146 for (i = 6; i > ndays - 1; i--)
6147 V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
6148 for (i = 0; i < ndays - 1 && i < 7; i++)
6149 V_weekUse(vp)[i] = 0;
6151 V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
6153 V_dayUseDate(vp) = Midnight(now);
6155 #if OPENAFS_VOL_STATS
6157 * All we need to do is bzero the entire VOL_STATS_BYTES of
6158 * the detailed volume statistics area.
6160 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
6161 #endif /* OPENAFS_VOL_STATS */
6164 /*It's been more than a day of collection */
6166 * Always return happily.
6169 } /*VAdjustVolumeStatistics */
6172 VAdjustVolumeStatistics(Volume * vp)
6176 retVal = VAdjustVolumeStatistics_r(vp);
6182 VBumpVolumeUsage_r(Volume * vp)
6184 unsigned int now = FT_ApproxTime();
6185 V_accessDate(vp) = now;
6186 if (now - V_dayUseDate(vp) > OneDay)
6187 VAdjustVolumeStatistics_r(vp);
6189 * Save the volume header image to disk after every 128 bumps to dayUse.
6191 if ((V_dayUse(vp)++ & 127) == 0) {
6193 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
6198 VBumpVolumeUsage(Volume * vp)
6201 VBumpVolumeUsage_r(vp);
6206 VSetDiskUsage_r(void)
6208 #ifndef AFS_DEMAND_ATTACH_FS
6209 static int FifteenMinuteCounter = 0;
6213 /* NOTE: Don't attempt to access the partitions list until the
6214 * initialization level indicates that all volumes are attached,
6215 * which implies that all partitions are initialized. */
6216 #ifdef AFS_PTHREAD_ENV
6217 VOL_CV_WAIT(&vol_vinit_cond);
6218 #else /* AFS_PTHREAD_ENV */
6220 #endif /* AFS_PTHREAD_ENV */
6223 VResetDiskUsage_r();
6225 #ifndef AFS_DEMAND_ATTACH_FS
6226 if (++FifteenMinuteCounter == 3) {
6227 FifteenMinuteCounter = 0;
6230 #endif /* !AFS_DEMAND_ATTACH_FS */
6242 /***************************************************/
6243 /* Volume Update List routines */
6244 /***************************************************/
6246 /* The number of minutes that a volume hasn't been updated before the
6247 * "Dont salvage" flag in the volume header will be turned on */
6248 #define SALVAGE_INTERVAL (10*60)
6253 * volume update list functionality has been moved into the VLRU
6254 * the DONT_SALVAGE flag is now set during VLRU demotion
6257 #ifndef AFS_DEMAND_ATTACH_FS
6258 static VolumeId *UpdateList = NULL; /* Pointer to array of Volume ID's */
6259 static int nUpdatedVolumes = 0; /* Updated with entry in UpdateList, salvage after crash flag on */
6260 static int updateSize = 0; /* number of entries possible */
6261 #define UPDATE_LIST_SIZE 128 /* initial size increment (must be a power of 2!) */
6262 #endif /* !AFS_DEMAND_ATTACH_FS */
6265 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
6268 vp->updateTime = FT_ApproxTime();
6269 if (V_dontSalvage(vp) == 0)
6271 V_dontSalvage(vp) = 0;
6272 VSyncVolume_r(ec, vp, 0);
6273 #ifdef AFS_DEMAND_ATTACH_FS
6274 V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
6275 #else /* !AFS_DEMAND_ATTACH_FS */
6278 if (UpdateList == NULL) {
6279 updateSize = UPDATE_LIST_SIZE;
6280 UpdateList = (VolumeId *) malloc(sizeof(VolumeId) * updateSize);
6282 if (nUpdatedVolumes == updateSize) {
6284 if (updateSize > 524288) {
6285 Log("warning: there is likely a bug in the volume update scanner\n");
6289 (VolumeId *) realloc(UpdateList,
6290 sizeof(VolumeId) * updateSize);
6293 osi_Assert(UpdateList != NULL);
6294 UpdateList[nUpdatedVolumes++] = V_id(vp);
6295 #endif /* !AFS_DEMAND_ATTACH_FS */
6298 #ifndef AFS_DEMAND_ATTACH_FS
6300 VScanUpdateList(void)
6305 afs_uint32 now = FT_ApproxTime();
6306 /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
6307 for (i = gap = 0; i < nUpdatedVolumes; i++) {
6309 UpdateList[i - gap] = UpdateList[i];
6311 /* XXX this routine needlessly messes up the Volume LRU by
6312 * breaking the LRU temporal-locality assumptions.....
6313 * we should use a special volume header allocator here */
6314 vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
6317 } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
6318 V_dontSalvage(vp) = DONT_SALVAGE;
6319 VUpdateVolume_r(&error, vp, 0); /* No need to fsync--not critical */
6327 #ifndef AFS_PTHREAD_ENV
6329 #endif /* !AFS_PTHREAD_ENV */
6331 nUpdatedVolumes -= gap;
6333 #endif /* !AFS_DEMAND_ATTACH_FS */
6336 /***************************************************/
6337 /* Volume LRU routines */
6338 /***************************************************/
6343 * with demand attach fs, we attempt to soft detach(1)
6344 * volumes which have not been accessed in a long time
6345 * in order to speed up fileserver shutdown
6347 * (1) by soft detach we mean a process very similar
6348 * to VOffline, except the final state of the
6349 * Volume will be VOL_STATE_PREATTACHED, instead
6350 * of the usual VOL_STATE_UNATTACHED
6352 #ifdef AFS_DEMAND_ATTACH_FS
6354 /* implementation is reminiscent of a generational GC
6356 * queue 0 is newly attached volumes. this queue is
6357 * sorted by attach timestamp
6359 * queue 1 is volumes that have been around a bit
6360 * longer than queue 0. this queue is sorted by
6363 * queue 2 is volumes tha have been around the longest.
6364 * this queue is unsorted
6366 * queue 3 is volumes that have been marked as
6367 * candidates for soft detachment. this queue is
6370 #define VLRU_GENERATIONS 3 /**< number of generations in VLRU */
6371 #define VLRU_QUEUES 5 /**< total number of VLRU queues */
6374 * definition of a VLRU queue.
6377 volatile struct rx_queue q;
6384 * main VLRU data structure.
6387 struct VLRU_q q[VLRU_QUEUES]; /**< VLRU queues */
6390 /** time interval (in seconds) between promotion passes for
6391 * each young generation queue. */
6392 afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
6394 /** time interval (in seconds) between soft detach candidate
6395 * scans for each generation queue.
6397 * scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
6398 * we perform a soft detach pass. */
6399 afs_uint32 scan_interval[VLRU_GENERATIONS+1];
6401 /* scheduler state */
6402 int next_idx; /**< next queue to receive attention */
6403 afs_uint32 last_promotion[VLRU_GENERATIONS-1]; /**< timestamp of last promotion scan */
6404 afs_uint32 last_scan[VLRU_GENERATIONS+1]; /**< timestamp of last detach scan */
6406 int scanner_state; /**< state of scanner thread */
6407 pthread_cond_t cv; /**< state transition CV */
6410 /** global VLRU state */
6411 static struct VLRU volume_LRU;
6414 * defined states for VLRU scanner thread.
6417 VLRU_SCANNER_STATE_OFFLINE = 0, /**< vlru scanner thread is offline */
6418 VLRU_SCANNER_STATE_ONLINE = 1, /**< vlru scanner thread is online */
6419 VLRU_SCANNER_STATE_SHUTTING_DOWN = 2, /**< vlru scanner thread is shutting down */
6420 VLRU_SCANNER_STATE_PAUSING = 3, /**< vlru scanner thread is getting ready to pause */
6421 VLRU_SCANNER_STATE_PAUSED = 4 /**< vlru scanner thread is paused */
6422 } vlru_thread_state_t;
6424 /* vlru disk data header stuff */
6425 #define VLRU_DISK_MAGIC 0x7a8b9cad /**< vlru disk entry magic number */
6426 #define VLRU_DISK_VERSION 1 /**< vlru disk entry version number */
6428 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
6429 #define VLRU_DUMP_EXPIRATION_TIME (60*60*24*7) /* expire vlru data after 1 week */
6432 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
6433 * soft detachment. */
6434 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
6436 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
6437 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
6439 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
6440 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
6442 /** VLRU control flag. non-zero value implies VLRU subsystem is activated. */
6443 static afs_uint32 VLRU_enabled = 1;
6445 /* queue synchronization routines */
6446 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
6447 static void VLRU_EndExclusive_r(struct VLRU_q * q);
6448 static void VLRU_Wait_r(struct VLRU_q * q);
6451 * set VLRU subsystem tunable parameters.
6453 * @param[in] option tunable option to modify
6454 * @param[in] val new value for tunable parameter
6456 * @pre @c VInitVolumePackage2 has not yet been called.
6458 * @post tunable parameter is modified
6462 * @note valid option parameters are:
6463 * @arg @c VLRU_SET_THRESH
6464 * set the period of inactivity after which
6465 * volumes are eligible for soft detachment
6466 * @arg @c VLRU_SET_INTERVAL
6467 * set the time interval between calls
6468 * to the volume LRU "garbage collector"
6469 * @arg @c VLRU_SET_MAX
6470 * set the max number of volumes to deallocate
6474 VLRU_SetOptions(int option, afs_uint32 val)
6476 if (option == VLRU_SET_THRESH) {
6477 VLRU_offline_thresh = val;
6478 } else if (option == VLRU_SET_INTERVAL) {
6479 VLRU_offline_interval = val;
6480 } else if (option == VLRU_SET_MAX) {
6481 VLRU_offline_max = val;
6482 } else if (option == VLRU_SET_ENABLED) {
6485 VLRU_ComputeConstants();
6489 * compute VLRU internal timing parameters.
6491 * @post VLRU scanner thread internal timing parameters are computed
6493 * @note computes internal timing parameters based upon user-modifiable
6494 * tunable parameters.
6498 * @internal volume package internal use only.
6501 VLRU_ComputeConstants(void)
6503 afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
6505 /* compute the candidate scan interval */
6506 volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
6508 /* compute the promotion intervals */
6509 volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
6510 volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
6513 /* compute the gen 0 scan interval */
6514 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
6516 /* compute the gen 0 scan interval */
6517 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
6522 * initialize VLRU subsystem.
6524 * @pre this function has not yet been called
6526 * @post VLRU subsystem is initialized and VLRU scanner thread is starting
6530 * @internal volume package internal use only.
6536 pthread_attr_t attrs;
6539 if (!VLRU_enabled) {
6540 Log("VLRU: disabled\n");
6544 /* initialize each of the VLRU queues */
6545 for (i = 0; i < VLRU_QUEUES; i++) {
6546 queue_Init(&volume_LRU.q[i]);
6547 volume_LRU.q[i].len = 0;
6548 volume_LRU.q[i].busy = 0;
6549 CV_INIT(&volume_LRU.q[i].cv, "vol lru", CV_DEFAULT, 0);
6552 /* setup the timing constants */
6553 VLRU_ComputeConstants();
6555 /* XXX put inside LogLevel check? */
6556 Log("VLRU: starting scanner with the following configuration parameters:\n");
6557 Log("VLRU: offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
6558 Log("VLRU: running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
6559 Log("VLRU: taking up to %d volumes offline per pass\n", VLRU_offline_max);
6560 Log("VLRU: scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
6561 Log("VLRU: scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
6562 Log("VLRU: scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
6564 /* start up the VLRU scanner */
6565 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
6566 if (programType == fileServer) {
6567 CV_INIT(&volume_LRU.cv, "vol lru", CV_DEFAULT, 0);
6568 osi_Assert(pthread_attr_init(&attrs) == 0);
6569 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
6570 osi_Assert(pthread_create(&tid, &attrs, &VLRU_ScannerThread, NULL) == 0);
6575 * initialize the VLRU-related fields of a newly allocated volume object.
6577 * @param[in] vp pointer to volume object
6580 * @arg @c VOL_LOCK is held.
6581 * @arg volume object is not on a VLRU queue.
6583 * @post VLRU fields are initialized to indicate that volume object is not
6584 * currently registered with the VLRU subsystem
6588 * @internal volume package interal use only.
6591 VLRU_Init_Node_r(Volume * vp)
6596 osi_Assert(queue_IsNotOnQueue(&vp->vlru));
6597 vp->vlru.idx = VLRU_QUEUE_INVALID;
6601 * add a volume object to a VLRU queue.
6603 * @param[in] vp pointer to volume object
6606 * @arg @c VOL_LOCK is held.
6607 * @arg caller MUST hold a lightweight ref on @p vp.
6608 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
6610 * @post the volume object is added to the appropriate VLRU queue
6612 * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
6613 * then the volume is added to that queue. Otherwise, the value
6614 * @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
6615 * volume is added to the NEW generation queue.
6617 * @note @c VOL_LOCK may be dropped internally
6619 * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
6620 * during the add operation, and is restored to the previous
6621 * state prior to return.
6625 * @internal volume package internal use only.
6628 VLRU_Add_r(Volume * vp)
6631 VolState state_save;
6636 if (queue_IsOnQueue(&vp->vlru))
6639 state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
6642 if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
6643 idx = VLRU_QUEUE_NEW;
6646 VLRU_Wait_r(&volume_LRU.q[idx]);
6648 /* repeat check since VLRU_Wait_r may have dropped
6650 if (queue_IsNotOnQueue(&vp->vlru)) {
6652 queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
6653 volume_LRU.q[idx].len++;
6654 V_attachFlags(vp) |= VOL_ON_VLRU;
6655 vp->stats.last_promote = FT_ApproxTime();
6658 VChangeState_r(vp, state_save);
6662 * delete a volume object from a VLRU queue.
6664 * @param[in] vp pointer to volume object
6667 * @arg @c VOL_LOCK is held.
6668 * @arg caller MUST hold a lightweight ref on @p vp.
6669 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
6671 * @post volume object is removed from the VLRU queue
6673 * @note @c VOL_LOCK may be dropped internally
6677 * @todo We should probably set volume state to something exlcusive
6678 * (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
6680 * @internal volume package internal use only.
6683 VLRU_Delete_r(Volume * vp)
6690 if (queue_IsNotOnQueue(&vp->vlru))
6696 if (idx == VLRU_QUEUE_INVALID)
6698 VLRU_Wait_r(&volume_LRU.q[idx]);
6699 } while (idx != vp->vlru.idx);
6701 /* now remove from the VLRU and update
6702 * the appropriate counter */
6703 queue_Remove(&vp->vlru);
6704 volume_LRU.q[idx].len--;
6705 vp->vlru.idx = VLRU_QUEUE_INVALID;
6706 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
6710 * tell the VLRU subsystem that a volume was just accessed.
6712 * @param[in] vp pointer to volume object
6715 * @arg @c VOL_LOCK is held
6716 * @arg caller MUST hold a lightweight ref on @p vp
6717 * @arg caller MUST NOT hold exclusive ownership of any VLRU queue
6719 * @post volume VLRU access statistics are updated. If the volume was on
6720 * the VLRU soft detach candidate queue, it is moved to the NEW
6723 * @note @c VOL_LOCK may be dropped internally
6727 * @internal volume package internal use only.
6730 VLRU_UpdateAccess_r(Volume * vp)
6732 Volume * rvp = NULL;
6737 if (queue_IsNotOnQueue(&vp->vlru))
6740 osi_Assert(V_attachFlags(vp) & VOL_ON_VLRU);
6742 /* update the access timestamp */
6743 vp->stats.last_get = FT_ApproxTime();
6746 * if the volume is on the soft detach candidate
6747 * list, we need to safely move it back to a
6748 * regular generation. this has to be done
6749 * carefully so we don't race against the scanner
6753 /* if this volume is on the soft detach candidate queue,
6754 * then grab exclusive access to the necessary queues */
6755 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
6757 VCreateReservation_r(rvp);
6759 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
6760 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
6761 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6762 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6765 /* make sure multiple threads don't race to update */
6766 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
6767 VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
6771 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6772 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
6773 VCancelReservation_r(rvp);
6778 * switch a volume between two VLRU queues.
6780 * @param[in] vp pointer to volume object
6781 * @param[in] new_idx index of VLRU queue onto which the volume will be moved
6782 * @param[in] append controls whether the volume will be appended or
6783 * prepended to the queue. A nonzero value means it will
6784 * be appended; zero means it will be prepended.
6786 * @pre The new (and old, if applicable) queue(s) must either be owned
6787 * exclusively by the calling thread for asynchronous manipulation,
6788 * or the queue(s) must be quiescent and VOL_LOCK must be held.
6789 * Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
6790 * for further details of the queue asynchronous processing mechanism.
6792 * @post If the volume object was already on a VLRU queue, it is
6793 * removed from the queue. Depending on the value of the append
6794 * parameter, the volume object is either appended or prepended
6795 * to the VLRU queue referenced by the new_idx parameter.
6799 * @see VLRU_BeginExclusive_r
6800 * @see VLRU_EndExclusive_r
6803 * @internal volume package internal use only.
6806 VLRU_SwitchQueues(Volume * vp, int new_idx, int append)
6808 if (queue_IsNotOnQueue(&vp->vlru))
6811 queue_Remove(&vp->vlru);
6812 volume_LRU.q[vp->vlru.idx].len--;
6814 /* put the volume back on the correct generational queue */
6816 queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
6818 queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
6821 volume_LRU.q[new_idx].len++;
6822 vp->vlru.idx = new_idx;
6826 * VLRU background thread.
6828 * The VLRU Scanner Thread is responsible for periodically scanning through
6829 * each VLRU queue looking for volumes which should be moved to another
6830 * queue, or soft detached.
6832 * @param[in] args unused thread arguments parameter
6834 * @return unused thread return value
6835 * @retval NULL always
6837 * @internal volume package internal use only.
6840 VLRU_ScannerThread(void * args)
6842 afs_uint32 now, min_delay, delay;
6843 int i, min_idx, min_op, overdue, state;
6845 /* set t=0 for promotion cycle to be
6846 * fileserver startup */
6847 now = FT_ApproxTime();
6848 for (i=0; i < VLRU_GENERATIONS-1; i++) {
6849 volume_LRU.last_promotion[i] = now;
6852 /* don't start the scanner until VLRU_offline_thresh
6853 * plus a small delay for VInitVolumePackage2 to finish
6856 sleep(VLRU_offline_thresh + 60);
6858 /* set t=0 for scan cycle to be now */
6859 now = FT_ApproxTime();
6860 for (i=0; i < VLRU_GENERATIONS+1; i++) {
6861 volume_LRU.last_scan[i] = now;
6865 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
6866 volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
6869 while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
6870 /* check to see if we've been asked to pause */
6871 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
6872 volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
6873 CV_BROADCAST(&volume_LRU.cv);
6875 VOL_CV_WAIT(&volume_LRU.cv);
6876 } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
6879 /* scheduling can happen outside the glock */
6882 /* figure out what is next on the schedule */
6884 /* figure out a potential schedule for the new generation first */
6886 min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
6889 if (min_delay > volume_LRU.scan_interval[0]) {
6890 /* unsigned overflow -- we're overdue to run this scan */
6895 /* if we're not overdue for gen 0, figure out schedule for candidate gen */
6897 i = VLRU_QUEUE_CANDIDATE;
6898 delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
6899 if (delay < min_delay) {
6903 if (delay > volume_LRU.scan_interval[i]) {
6904 /* unsigned overflow -- we're overdue to run this scan */
6911 /* if we're still not overdue for something, figure out schedules for promotions */
6912 for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
6913 delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
6914 if (delay < min_delay) {
6919 if (delay > volume_LRU.promotion_interval[i]) {
6920 /* unsigned overflow -- we're overdue to run this promotion */
6929 /* sleep as needed */
6934 /* do whatever is next */
6937 VLRU_Promote_r(min_idx);
6938 VLRU_Demote_r(min_idx+1);
6940 VLRU_Scan_r(min_idx);
6942 now = FT_ApproxTime();
6945 Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
6947 /* signal that scanner is down */
6948 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
6949 CV_BROADCAST(&volume_LRU.cv);
6955 * promote volumes from one VLRU generation to the next.
6957 * This routine scans a VLRU generation looking for volumes which are
6958 * eligible to be promoted to the next generation. All volumes which
6959 * meet the eligibility requirement are promoted.
6961 * Promotion eligibility is based upon meeting both of the following
6964 * @arg The volume has been accessed since the last promotion:
6965 * @c (vp->stats.last_get >= vp->stats.last_promote)
6966 * @arg The last promotion occurred at least
6967 * @c volume_LRU.promotion_interval[idx] seconds ago
6969 * As a performance optimization, promotions are "globbed". In other
6970 * words, we promote arbitrarily large contiguous sublists of elements
6973 * @param[in] idx VLRU queue index to scan
6977 * @internal VLRU internal use only.
6980 VLRU_Promote_r(int idx)
6982 int len, chaining, promote;
6983 afs_uint32 now, thresh;
6984 struct rx_queue *qp, *nqp;
6985 Volume * vp, *start = NULL, *end = NULL;
6987 /* get exclusive access to two chains, and drop the glock */
6988 VLRU_Wait_r(&volume_LRU.q[idx]);
6989 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
6990 VLRU_Wait_r(&volume_LRU.q[idx+1]);
6991 VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
6994 thresh = volume_LRU.promotion_interval[idx];
6995 now = FT_ApproxTime();
6998 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
6999 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7000 promote = (((vp->stats.last_promote + thresh) <= now) &&
7001 (vp->stats.last_get >= vp->stats.last_promote));
7009 /* promote and prepend chain */
7010 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7024 /* promote and prepend */
7025 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7029 volume_LRU.q[idx].len -= len;
7030 volume_LRU.q[idx+1].len += len;
7033 /* release exclusive access to the two chains */
7035 volume_LRU.last_promotion[idx] = now;
7036 VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
7037 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7040 /* run the demotions */
7042 VLRU_Demote_r(int idx)
7045 int len, chaining, demote;
7046 afs_uint32 now, thresh;
7047 struct rx_queue *qp, *nqp;
7048 Volume * vp, *start = NULL, *end = NULL;
7049 Volume ** salv_flag_vec = NULL;
7050 int salv_vec_offset = 0;
7052 osi_Assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
7054 /* get exclusive access to two chains, and drop the glock */
7055 VLRU_Wait_r(&volume_LRU.q[idx-1]);
7056 VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
7057 VLRU_Wait_r(&volume_LRU.q[idx]);
7058 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7061 /* no big deal if this allocation fails */
7062 if (volume_LRU.q[idx].len) {
7063 salv_flag_vec = (Volume **) malloc(volume_LRU.q[idx].len * sizeof(Volume *));
7066 now = FT_ApproxTime();
7067 thresh = volume_LRU.promotion_interval[idx-1];
7070 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7071 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7072 demote = (((vp->stats.last_promote + thresh) <= now) &&
7073 (vp->stats.last_get < (now - thresh)));
7075 /* we now do volume update list DONT_SALVAGE flag setting during
7076 * demotion passes */
7077 if (salv_flag_vec &&
7078 !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7080 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7081 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7082 salv_flag_vec[salv_vec_offset++] = vp;
7083 VCreateReservation_r(vp);
7092 /* demote and append chain */
7093 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7107 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7111 volume_LRU.q[idx].len -= len;
7112 volume_LRU.q[idx-1].len += len;
7115 /* release exclusive access to the two chains */
7117 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7118 VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
7120 /* now go back and set the DONT_SALVAGE flags as appropriate */
7121 if (salv_flag_vec) {
7123 for (i = 0; i < salv_vec_offset; i++) {
7124 vp = salv_flag_vec[i];
7125 if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7126 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7127 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7130 V_attachFlags(vp) |= VOL_HDR_DONTSALV;
7131 V_dontSalvage(vp) = DONT_SALVAGE;
7132 VUpdateVolume_r(&ec, vp, 0);
7136 VCancelReservation_r(vp);
7138 free(salv_flag_vec);
7142 /* run a pass of the VLRU GC scanner */
7144 VLRU_Scan_r(int idx)
7146 afs_uint32 now, thresh;
7147 struct rx_queue *qp, *nqp;
7151 osi_Assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
7153 /* gain exclusive access to the idx VLRU */
7154 VLRU_Wait_r(&volume_LRU.q[idx]);
7155 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7157 if (idx != VLRU_QUEUE_CANDIDATE) {
7158 /* gain exclusive access to the candidate VLRU */
7159 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7160 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7163 now = FT_ApproxTime();
7164 thresh = now - VLRU_offline_thresh;
7166 /* perform candidate selection and soft detaching */
7167 if (idx == VLRU_QUEUE_CANDIDATE) {
7168 /* soft detach some volumes from the candidate pool */
7172 for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7173 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7174 if (i >= VLRU_offline_max) {
7177 /* check timestamp to see if it's a candidate for soft detaching */
7178 if (vp->stats.last_get <= thresh) {
7180 if (VCheckSoftDetach(vp, thresh))
7186 /* scan for volumes to become soft detach candidates */
7187 for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
7188 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7190 /* check timestamp to see if it's a candidate for soft detaching */
7191 if (vp->stats.last_get <= thresh) {
7192 VCheckSoftDetachCandidate(vp, thresh);
7195 if (!(i&0x7f)) { /* lock coarsening optimization */
7203 /* relinquish exclusive access to the VLRU chains */
7207 volume_LRU.last_scan[idx] = now;
7208 if (idx != VLRU_QUEUE_CANDIDATE) {
7209 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7211 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7214 /* check whether volume is safe to soft detach
7215 * caller MUST NOT hold a ref count on vp */
7217 VCheckSoftDetach(Volume * vp, afs_uint32 thresh)
7221 if (vp->nUsers || vp->nWaiters)
7224 if (vp->stats.last_get <= thresh) {
7225 ret = VSoftDetachVolume_r(vp, thresh);
7231 /* check whether volume should be made a
7232 * soft detach candidate */
7234 VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh)
7237 if (vp->nUsers || vp->nWaiters)
7242 osi_Assert(idx == VLRU_QUEUE_NEW);
7244 if (vp->stats.last_get <= thresh) {
7245 /* move to candidate pool */
7246 queue_Remove(&vp->vlru);
7247 volume_LRU.q[VLRU_QUEUE_NEW].len--;
7248 queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
7249 vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
7250 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
7258 /* begin exclusive access on VLRU */
7260 VLRU_BeginExclusive_r(struct VLRU_q * q)
7262 osi_Assert(q->busy == 0);
7266 /* end exclusive access on VLRU */
7268 VLRU_EndExclusive_r(struct VLRU_q * q)
7270 osi_Assert(q->busy);
7272 CV_BROADCAST(&q->cv);
7275 /* wait for another thread to end exclusive access on VLRU */
7277 VLRU_Wait_r(struct VLRU_q * q)
7280 VOL_CV_WAIT(&q->cv);
7285 * volume soft detach
7287 * caller MUST NOT hold a ref count on vp */
7289 VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh)
7294 osi_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7296 ts_save = vp->stats.last_get;
7297 if (ts_save > thresh)
7300 if (vp->nUsers || vp->nWaiters)
7303 if (VIsExclusiveState(V_attachState(vp))) {
7307 switch (V_attachState(vp)) {
7308 case VOL_STATE_UNATTACHED:
7309 case VOL_STATE_PREATTACHED:
7310 case VOL_STATE_ERROR:
7311 case VOL_STATE_GOING_OFFLINE:
7312 case VOL_STATE_SHUTTING_DOWN:
7313 case VOL_STATE_SALVAGING:
7314 case VOL_STATE_DELETED:
7315 volume_LRU.q[vp->vlru.idx].len--;
7317 /* create and cancel a reservation to
7318 * give the volume an opportunity to
7320 VCreateReservation_r(vp);
7321 queue_Remove(&vp->vlru);
7322 vp->vlru.idx = VLRU_QUEUE_INVALID;
7323 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7324 VCancelReservation_r(vp);
7330 /* hold the volume and take it offline.
7331 * no need for reservations, as VHold_r
7332 * takes care of that internally. */
7333 if (VHold_r(vp) == 0) {
7334 /* vhold drops the glock, so now we should
7335 * check to make sure we aren't racing against
7336 * other threads. if we are racing, offlining vp
7337 * would be wasteful, and block the scanner for a while
7341 (vp->shuttingDown) ||
7342 (vp->goingOffline) ||
7343 (vp->stats.last_get != ts_save)) {
7344 /* looks like we're racing someone else. bail */
7348 /* pull it off the VLRU */
7349 osi_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7350 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
7351 queue_Remove(&vp->vlru);
7352 vp->vlru.idx = VLRU_QUEUE_INVALID;
7353 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7355 /* take if offline */
7356 VOffline_r(vp, "volume has been soft detached");
7358 /* invalidate the volume header cache */
7359 FreeVolumeHeader(vp);
7362 IncUInt64(&VStats.soft_detaches);
7363 vp->stats.soft_detaches++;
7365 /* put in pre-attached state so demand
7366 * attacher can work on it */
7367 VChangeState_r(vp, VOL_STATE_PREATTACHED);
7373 #endif /* AFS_DEMAND_ATTACH_FS */
7376 /***************************************************/
7377 /* Volume Header Cache routines */
7378 /***************************************************/
7381 * volume header cache.
7383 struct volume_hdr_LRU_t volume_hdr_LRU;
7386 * initialize the volume header cache.
7388 * @param[in] howMany number of header cache entries to preallocate
7390 * @pre VOL_LOCK held. Function has never been called before.
7392 * @post howMany cache entries are allocated, initialized, and added
7393 * to the LRU list. Header cache statistics are initialized.
7395 * @note only applicable to fileServer program type. Should only be
7396 * called once during volume package initialization.
7398 * @internal volume package internal use only.
7401 VInitVolumeHeaderCache(afs_uint32 howMany)
7403 struct volHeader *hp;
7404 if (programType != fileServer)
7406 queue_Init(&volume_hdr_LRU);
7407 volume_hdr_LRU.stats.free = 0;
7408 volume_hdr_LRU.stats.used = howMany;
7409 volume_hdr_LRU.stats.attached = 0;
7410 hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
7411 osi_Assert(hp != NULL);
7414 /* We are using ReleaseVolumeHeader to initialize the values on the header list
7415 * to ensure they have the right values
7417 ReleaseVolumeHeader(hp++);
7421 * get a volume header and attach it to the volume object.
7423 * @param[in] vp pointer to volume object
7425 * @return cache entry status
7426 * @retval 0 volume header was newly attached; cache data is invalid
7427 * @retval 1 volume header was previously attached; cache data is valid
7429 * @pre VOL_LOCK held. For DAFS, lightweight ref must be held on volume object.
7431 * @post volume header attached to volume object. if necessary, header cache
7432 * entry on LRU is synchronized to disk. Header is removed from LRU list.
7434 * @note VOL_LOCK may be dropped
7436 * @warning this interface does not load header data from disk. it merely
7437 * attaches a header object to the volume object, and may sync the old
7438 * header cache data out to disk in the process.
7440 * @internal volume package internal use only.
7443 GetVolumeHeader(Volume * vp)
7446 struct volHeader *hd;
7448 static int everLogged = 0;
7450 #ifdef AFS_DEMAND_ATTACH_FS
7451 VolState vp_save = 0, back_save = 0;
7453 /* XXX debug 9/19/05 we've apparently got
7454 * a ref counting bug somewhere that's
7455 * breaking the nUsers == 0 => header on LRU
7457 if (vp->header && queue_IsNotOnQueue(vp->header)) {
7458 Log("nUsers == 0, but header not on LRU\n");
7463 old = (vp->header != NULL); /* old == volume already has a header */
7465 if (programType != fileServer) {
7466 /* for volume utilities, we allocate volHeaders as needed */
7468 hd = (struct volHeader *)calloc(1, sizeof(*vp->header));
7469 osi_Assert(hd != NULL);
7472 #ifdef AFS_DEMAND_ATTACH_FS
7473 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
7477 /* for the fileserver, we keep a volume header cache */
7479 /* the header we previously dropped in the lru is
7480 * still available. pull it off the lru and return */
7483 osi_Assert(hd->back == vp);
7484 #ifdef AFS_DEMAND_ATTACH_FS
7485 V_attachFlags(vp) &= ~(VOL_HDR_IN_LRU);
7488 /* we need to grab a new element off the LRU */
7489 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
7490 /* grab an element and pull off of LRU */
7491 hd = queue_First(&volume_hdr_LRU, volHeader);
7494 /* LRU is empty, so allocate a new volHeader
7495 * this is probably indicative of a leak, so let the user know */
7496 hd = (struct volHeader *)calloc(1, sizeof(struct volHeader));
7497 osi_Assert(hd != NULL);
7499 Log("****Allocated more volume headers, probably leak****\n");
7502 volume_hdr_LRU.stats.free++;
7505 /* this header used to belong to someone else.
7506 * we'll need to check if the header needs to
7507 * be sync'd out to disk */
7509 #ifdef AFS_DEMAND_ATTACH_FS
7510 /* if hd->back were in an exclusive state, then
7511 * its volHeader would not be on the LRU... */
7512 osi_Assert(!VIsExclusiveState(V_attachState(hd->back)));
7515 if (hd->diskstuff.inUse) {
7516 /* volume was in use, so we'll need to sync
7517 * its header to disk */
7519 #ifdef AFS_DEMAND_ATTACH_FS
7520 back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
7521 vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
7522 VCreateReservation_r(hd->back);
7526 WriteVolumeHeader_r(&error, hd->back);
7527 /* Ignore errors; catch them later */
7529 #ifdef AFS_DEMAND_ATTACH_FS
7534 hd->back->header = NULL;
7535 #ifdef AFS_DEMAND_ATTACH_FS
7536 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
7538 if (hd->diskstuff.inUse) {
7539 VChangeState_r(hd->back, back_save);
7540 VCancelReservation_r(hd->back);
7541 VChangeState_r(vp, vp_save);
7545 volume_hdr_LRU.stats.attached++;
7549 #ifdef AFS_DEMAND_ATTACH_FS
7550 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
7553 volume_hdr_LRU.stats.free--;
7554 volume_hdr_LRU.stats.used++;
7556 IncUInt64(&VStats.hdr_gets);
7557 #ifdef AFS_DEMAND_ATTACH_FS
7558 IncUInt64(&vp->stats.hdr_gets);
7559 vp->stats.last_hdr_get = FT_ApproxTime();
7566 * make sure volume header is attached and contains valid cache data.
7568 * @param[out] ec outbound error code
7569 * @param[in] vp pointer to volume object
7571 * @pre VOL_LOCK held. For DAFS, lightweight ref held on vp.
7573 * @post header cache entry attached, and loaded with valid data, or
7574 * *ec is nonzero, and the header is released back into the LRU.
7576 * @internal volume package internal use only.
7579 LoadVolumeHeader(Error * ec, Volume * vp)
7581 #ifdef AFS_DEMAND_ATTACH_FS
7582 VolState state_save;
7586 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
7587 IncUInt64(&VStats.hdr_loads);
7588 state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
7591 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
7592 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
7594 IncUInt64(&vp->stats.hdr_loads);
7595 now = FT_ApproxTime();
7599 V_attachFlags(vp) |= VOL_HDR_LOADED;
7600 vp->stats.last_hdr_load = now;
7602 VChangeState_r(vp, state_save);
7604 #else /* AFS_DEMAND_ATTACH_FS */
7606 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
7607 IncUInt64(&VStats.hdr_loads);
7609 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
7610 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
7613 #endif /* AFS_DEMAND_ATTACH_FS */
7615 /* maintain (nUsers==0) => header in LRU invariant */
7616 FreeVolumeHeader(vp);
7621 * release a header cache entry back into the LRU list.
7623 * @param[in] hd pointer to volume header cache object
7625 * @pre VOL_LOCK held.
7627 * @post header cache object appended onto end of LRU list.
7629 * @note only applicable to fileServer program type.
7631 * @note used to place a header cache entry back into the
7632 * LRU pool without invalidating it as a cache entry.
7634 * @internal volume package internal use only.
7637 ReleaseVolumeHeader(struct volHeader *hd)
7639 if (programType != fileServer)
7641 if (!hd || queue_IsOnQueue(hd)) /* no header, or header already released */
7643 queue_Append(&volume_hdr_LRU, hd);
7644 #ifdef AFS_DEMAND_ATTACH_FS
7646 V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
7649 volume_hdr_LRU.stats.free++;
7650 volume_hdr_LRU.stats.used--;
7654 * free/invalidate a volume header cache entry.
7656 * @param[in] vp pointer to volume object
7658 * @pre VOL_LOCK is held.
7660 * @post For fileserver, header cache entry is returned to LRU, and it is
7661 * invalidated as a cache entry. For volume utilities, the header
7662 * cache entry is freed.
7664 * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
7665 * whenever it is necessary to invalidate the header cache entry.
7667 * @see ReleaseVolumeHeader
7669 * @internal volume package internal use only.
7672 FreeVolumeHeader(Volume * vp)
7674 struct volHeader *hd = vp->header;
7677 if (programType == fileServer) {
7678 ReleaseVolumeHeader(hd);
7683 #ifdef AFS_DEMAND_ATTACH_FS
7684 V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
7686 volume_hdr_LRU.stats.attached--;
7691 /***************************************************/
7692 /* Volume Hash Table routines */
7693 /***************************************************/
7696 * set size of volume object hash table.
7698 * @param[in] logsize log(2) of desired hash table size
7700 * @return operation status
7702 * @retval -1 failure
7704 * @pre MUST be called prior to VInitVolumePackage2
7706 * @post Volume Hash Table will have 2^logsize buckets
7709 VSetVolHashSize(int logsize)
7711 /* 64 to 268435456 hash buckets seems like a reasonable range */
7712 if ((logsize < 6 ) || (logsize > 28)) {
7717 VolumeHashTable.Size = 1 << logsize;
7718 VolumeHashTable.Mask = VolumeHashTable.Size - 1;
7720 /* we can't yet support runtime modification of this
7721 * parameter. we'll need a configuration rwlock to
7722 * make runtime modification feasible.... */
7729 * initialize dynamic data structures for volume hash table.
7731 * @post hash table is allocated, and fields are initialized.
7733 * @internal volume package internal use only.
7736 VInitVolumeHash(void)
7740 VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
7741 sizeof(VolumeHashChainHead));
7742 osi_Assert(VolumeHashTable.Table != NULL);
7744 for (i=0; i < VolumeHashTable.Size; i++) {
7745 queue_Init(&VolumeHashTable.Table[i]);
7746 #ifdef AFS_DEMAND_ATTACH_FS
7747 CV_INIT(&VolumeHashTable.Table[i].chain_busy_cv, "vhash busy", CV_DEFAULT, 0);
7748 #endif /* AFS_DEMAND_ATTACH_FS */
7753 * add a volume object to the hash table.
7755 * @param[in] vp pointer to volume object
7756 * @param[in] hashid hash of volume id
7758 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
7761 * @post volume is added to hash chain.
7763 * @internal volume package internal use only.
7765 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
7766 * asynchronous hash chain reordering to finish.
7769 AddVolumeToHashTable(Volume * vp, int hashid)
7771 VolumeHashChainHead * head;
7773 if (queue_IsOnQueue(vp))
7776 head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
7778 #ifdef AFS_DEMAND_ATTACH_FS
7779 /* wait for the hash chain to become available */
7782 V_attachFlags(vp) |= VOL_IN_HASH;
7783 vp->chainCacheCheck = ++head->cacheCheck;
7784 #endif /* AFS_DEMAND_ATTACH_FS */
7787 vp->hashid = hashid;
7788 queue_Append(head, vp);
7789 vp->vnodeHashOffset = VolumeHashOffset_r();
7793 * delete a volume object from the hash table.
7795 * @param[in] vp pointer to volume object
7797 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
7800 * @post volume is removed from hash chain.
7802 * @internal volume package internal use only.
7804 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
7805 * asynchronous hash chain reordering to finish.
7808 DeleteVolumeFromHashTable(Volume * vp)
7810 VolumeHashChainHead * head;
7812 if (!queue_IsOnQueue(vp))
7815 head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
7817 #ifdef AFS_DEMAND_ATTACH_FS
7818 /* wait for the hash chain to become available */
7821 V_attachFlags(vp) &= ~(VOL_IN_HASH);
7823 #endif /* AFS_DEMAND_ATTACH_FS */
7827 /* do NOT reset hashid to zero, as the online
7828 * salvager package may need to know the volume id
7829 * after the volume is removed from the hash */
7833 * lookup a volume object in the hash table given a volume id.
7835 * @param[out] ec error code return
7836 * @param[in] volumeId volume id
7837 * @param[in] hint volume object which we believe could be the correct
7840 * @return volume object pointer
7841 * @retval NULL no such volume id is registered with the hash table.
7843 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
7846 * @post volume object with the given id is returned. volume object and
7847 * hash chain access statistics are updated. hash chain may have
7850 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
7851 * asynchronous hash chain reordering operation to finish, or
7852 * in order for us to perform an asynchronous chain reordering.
7854 * @note Hash chain reorderings occur when the access count for the
7855 * volume object being looked up exceeds the sum of the previous
7856 * node's (the node ahead of it in the hash chain linked list)
7857 * access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
7859 * @note For DAFS, the hint parameter allows us to short-circuit if the
7860 * cacheCheck fields match between the hash chain head and the
7861 * hint volume object.
7864 VLookupVolume_r(Error * ec, VolId volumeId, Volume * hint)
7868 #ifdef AFS_DEMAND_ATTACH_FS
7871 VolumeHashChainHead * head;
7874 head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
7876 #ifdef AFS_DEMAND_ATTACH_FS
7877 /* wait for the hash chain to become available */
7880 /* check to see if we can short circuit without walking the hash chain */
7881 if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
7882 IncUInt64(&hint->stats.hash_short_circuits);
7885 #endif /* AFS_DEMAND_ATTACH_FS */
7887 /* someday we need to either do per-chain locks, RWlocks,
7888 * or both for volhash access.
7889 * (and move to a data structure with better cache locality) */
7891 /* search the chain for this volume id */
7892 for(queue_Scan(head, vp, np, Volume)) {
7894 if ((vp->hashid == volumeId)) {
7899 if (queue_IsEnd(head, vp)) {
7903 #ifdef AFS_DEMAND_ATTACH_FS
7904 /* update hash chain statistics */
7907 FillInt64(lks, 0, looks);
7908 AddUInt64(head->looks, lks, &head->looks);
7909 AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
7910 IncUInt64(&head->gets);
7915 IncUInt64(&vp->stats.hash_lookups);
7917 /* for demand attach fileserver, we permit occasional hash chain reordering
7918 * so that frequently looked up volumes move towards the head of the chain */
7919 pp = queue_Prev(vp, Volume);
7920 if (!queue_IsEnd(head, pp)) {
7921 FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
7922 AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
7923 if (GEInt64(vp->stats.hash_lookups, thresh)) {
7924 VReorderHash_r(head, pp, vp);
7928 /* update the short-circuit cache check */
7929 vp->chainCacheCheck = head->cacheCheck;
7931 #endif /* AFS_DEMAND_ATTACH_FS */
7936 #ifdef AFS_DEMAND_ATTACH_FS
7937 /* perform volume hash chain reordering.
7939 * advance a subchain beginning at vp ahead of
7940 * the adjacent subchain ending at pp */
7942 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
7944 Volume *tp, *np, *lp;
7945 afs_uint64 move_thresh;
7947 /* this should never be called if the chain is already busy, so
7948 * no need to wait for other exclusive chain ops to finish */
7950 /* this is a rather heavy set of operations,
7951 * so let's set the chain busy flag and drop
7953 VHashBeginExclusive_r(head);
7956 /* scan forward in the chain from vp looking for the last element
7957 * in the chain we want to advance */
7958 FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
7959 AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
7960 for(queue_ScanFrom(head, vp, tp, np, Volume)) {
7961 if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
7965 lp = queue_Prev(tp, Volume);
7967 /* scan backwards from pp to determine where to splice and
7968 * insert the subchain we're advancing */
7969 for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
7970 if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
7974 tp = queue_Next(tp, Volume);
7976 /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
7977 queue_MoveChainBefore(tp,vp,lp);
7980 IncUInt64(&VStats.hash_reorders);
7982 IncUInt64(&head->reorders);
7984 /* wake up any threads waiting for the hash chain */
7985 VHashEndExclusive_r(head);
7989 /* demand-attach fs volume hash
7990 * asynchronous exclusive operations */
7993 * begin an asynchronous exclusive operation on a volume hash chain.
7995 * @param[in] head pointer to volume hash chain head object
7997 * @pre VOL_LOCK held. hash chain is quiescent.
7999 * @post hash chain marked busy.
8001 * @note this interface is used in conjunction with VHashEndExclusive_r and
8002 * VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8003 * volume hash chain. Its main use case is hash chain reordering, which
8004 * has the potential to be a highly latent operation.
8006 * @see VHashEndExclusive_r
8011 * @internal volume package internal use only.
8014 VHashBeginExclusive_r(VolumeHashChainHead * head)
8016 osi_Assert(head->busy == 0);
8021 * relinquish exclusive ownership of a volume hash chain.
8023 * @param[in] head pointer to volume hash chain head object
8025 * @pre VOL_LOCK held. thread owns the hash chain exclusively.
8027 * @post hash chain is marked quiescent. threads awaiting use of
8028 * chain are awakened.
8030 * @see VHashBeginExclusive_r
8035 * @internal volume package internal use only.
8038 VHashEndExclusive_r(VolumeHashChainHead * head)
8040 osi_Assert(head->busy);
8042 CV_BROADCAST(&head->chain_busy_cv);
8046 * wait for all asynchronous operations on a hash chain to complete.
8048 * @param[in] head pointer to volume hash chain head object
8050 * @pre VOL_LOCK held.
8052 * @post hash chain object is quiescent.
8054 * @see VHashBeginExclusive_r
8055 * @see VHashEndExclusive_r
8059 * @note This interface should be called before any attempt to
8060 * traverse the hash chain. It is permissible for a thread
8061 * to gain exclusive access to the chain, and then perform
8062 * latent operations on the chain asynchronously wrt the
8065 * @warning if waiting is necessary, VOL_LOCK is dropped
8067 * @internal volume package internal use only.
8070 VHashWait_r(VolumeHashChainHead * head)
8072 while (head->busy) {
8073 VOL_CV_WAIT(&head->chain_busy_cv);
8076 #endif /* AFS_DEMAND_ATTACH_FS */
8079 /***************************************************/
8080 /* Volume by Partition List routines */
8081 /***************************************************/
8084 * demand attach fileserver adds a
8085 * linked list of volumes to each
8086 * partition object, thus allowing
8087 * for quick enumeration of all
8088 * volumes on a partition
8091 #ifdef AFS_DEMAND_ATTACH_FS
8093 * add a volume to its disk partition VByPList.
8095 * @param[in] vp pointer to volume object
8097 * @pre either the disk partition VByPList is owned exclusively
8098 * by the calling thread, or the list is quiescent and
8101 * @post volume is added to disk partition VByPList
8105 * @warning it is the caller's responsibility to ensure list
8108 * @see VVByPListWait_r
8109 * @see VVByPListBeginExclusive_r
8110 * @see VVByPListEndExclusive_r
8112 * @internal volume package internal use only.
8115 AddVolumeToVByPList_r(Volume * vp)
8117 if (queue_IsNotOnQueue(&vp->vol_list)) {
8118 queue_Append(&vp->partition->vol_list, &vp->vol_list);
8119 V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
8120 vp->partition->vol_list.len++;
8125 * delete a volume from its disk partition VByPList.
8127 * @param[in] vp pointer to volume object
8129 * @pre either the disk partition VByPList is owned exclusively
8130 * by the calling thread, or the list is quiescent and
8133 * @post volume is removed from the disk partition VByPList
8137 * @warning it is the caller's responsibility to ensure list
8140 * @see VVByPListWait_r
8141 * @see VVByPListBeginExclusive_r
8142 * @see VVByPListEndExclusive_r
8144 * @internal volume package internal use only.
8147 DeleteVolumeFromVByPList_r(Volume * vp)
8149 if (queue_IsOnQueue(&vp->vol_list)) {
8150 queue_Remove(&vp->vol_list);
8151 V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
8152 vp->partition->vol_list.len--;
8157 * begin an asynchronous exclusive operation on a VByPList.
8159 * @param[in] dp pointer to disk partition object
8161 * @pre VOL_LOCK held. VByPList is quiescent.
8163 * @post VByPList marked busy.
8165 * @note this interface is used in conjunction with VVByPListEndExclusive_r and
8166 * VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8169 * @see VVByPListEndExclusive_r
8170 * @see VVByPListWait_r
8174 * @internal volume package internal use only.
8176 /* take exclusive control over the list */
8178 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
8180 osi_Assert(dp->vol_list.busy == 0);
8181 dp->vol_list.busy = 1;
8185 * relinquish exclusive ownership of a VByPList.
8187 * @param[in] dp pointer to disk partition object
8189 * @pre VOL_LOCK held. thread owns the VByPList exclusively.
8191 * @post VByPList is marked quiescent. threads awaiting use of
8192 * the list are awakened.
8194 * @see VVByPListBeginExclusive_r
8195 * @see VVByPListWait_r
8199 * @internal volume package internal use only.
8202 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
8204 osi_Assert(dp->vol_list.busy);
8205 dp->vol_list.busy = 0;
8206 CV_BROADCAST(&dp->vol_list.cv);
8210 * wait for all asynchronous operations on a VByPList to complete.
8212 * @param[in] dp pointer to disk partition object
8214 * @pre VOL_LOCK is held.
8216 * @post disk partition's VByP list is quiescent
8220 * @note This interface should be called before any attempt to
8221 * traverse the VByPList. It is permissible for a thread
8222 * to gain exclusive access to the list, and then perform
8223 * latent operations on the list asynchronously wrt the
8226 * @warning if waiting is necessary, VOL_LOCK is dropped
8228 * @see VVByPListEndExclusive_r
8229 * @see VVByPListBeginExclusive_r
8231 * @internal volume package internal use only.
8234 VVByPListWait_r(struct DiskPartition64 * dp)
8236 while (dp->vol_list.busy) {
8237 VOL_CV_WAIT(&dp->vol_list.cv);
8240 #endif /* AFS_DEMAND_ATTACH_FS */
8242 /***************************************************/
8243 /* Volume Cache Statistics routines */
8244 /***************************************************/
8247 VPrintCacheStats_r(void)
8249 afs_uint32 get_hi, get_lo, load_hi, load_lo;
8250 struct VnodeClassInfo *vcp;
8251 vcp = &VnodeClassInfo[vLarge];
8252 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);
8253 vcp = &VnodeClassInfo[vSmall];
8254 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);
8255 SplitInt64(VStats.hdr_gets, get_hi, get_lo);
8256 SplitInt64(VStats.hdr_loads, load_hi, load_lo);
8257 Log("Volume header cache, %d entries, %d gets, %d replacements\n",
8258 VStats.hdr_cache_size, get_lo, load_lo);
8262 VPrintCacheStats(void)
8265 VPrintCacheStats_r();
8269 #ifdef AFS_DEMAND_ATTACH_FS
8271 UInt64ToDouble(afs_uint64 * x)
8273 static double c32 = 4.0 * 1.073741824 * 1000000000.0;
8275 SplitInt64(*x, h, l);
8276 return (((double)h) * c32) + ((double) l);
8280 DoubleToPrintable(double x, char * buf, int len)
8282 static double billion = 1000000000.0;
8285 y[0] = (afs_uint32) (x / (billion * billion));
8286 y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
8287 y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
8290 snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
8292 snprintf(buf, len, "%d%09d", y[1], y[2]);
8294 snprintf(buf, len, "%d", y[2]);
8300 struct VLRUExtStatsEntry {
8304 struct VLRUExtStats {
8310 } queue_info[VLRU_QUEUE_INVALID];
8311 struct VLRUExtStatsEntry * vec;
8315 * add a 256-entry fudge factor onto the vector in case state changes
8316 * out from under us.
8318 #define VLRU_EXT_STATS_VEC_LEN_FUDGE 256
8321 * collect extended statistics for the VLRU subsystem.
8323 * @param[out] stats pointer to stats structure to be populated
8324 * @param[in] nvols number of volumes currently known to exist
8326 * @pre VOL_LOCK held
8328 * @post stats->vec allocated and populated
8330 * @return operation status
8335 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
8337 afs_uint32 cur, idx, len;
8338 struct rx_queue * qp, * nqp;
8340 struct VLRUExtStatsEntry * vec;
8342 len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
8343 vec = stats->vec = calloc(len,
8344 sizeof(struct VLRUExtStatsEntry));
8350 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
8351 VLRU_Wait_r(&volume_LRU.q[idx]);
8352 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
8355 stats->queue_info[idx].start = cur;
8357 for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
8359 /* out of space in vec */
8362 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
8363 vec[cur].volid = vp->hashid;
8367 stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
8370 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
8378 #define ENUMTOSTRING(en) #en
8379 #define ENUMCASE(en) \
8381 return ENUMTOSTRING(en); \
8385 vlru_idx_to_string(int idx)
8388 ENUMCASE(VLRU_QUEUE_NEW);
8389 ENUMCASE(VLRU_QUEUE_MID);
8390 ENUMCASE(VLRU_QUEUE_OLD);
8391 ENUMCASE(VLRU_QUEUE_CANDIDATE);
8392 ENUMCASE(VLRU_QUEUE_HELD);
8393 ENUMCASE(VLRU_QUEUE_INVALID);
8395 return "**UNKNOWN**";
8400 VPrintExtendedCacheStats_r(int flags)
8403 afs_uint32 vol_sum = 0;
8410 struct stats looks, gets, reorders, len;
8411 struct stats ch_looks, ch_gets, ch_reorders;
8413 VolumeHashChainHead *head;
8415 struct VLRUExtStats vlru_stats;
8417 /* zero out stats */
8418 memset(&looks, 0, sizeof(struct stats));
8419 memset(&gets, 0, sizeof(struct stats));
8420 memset(&reorders, 0, sizeof(struct stats));
8421 memset(&len, 0, sizeof(struct stats));
8422 memset(&ch_looks, 0, sizeof(struct stats));
8423 memset(&ch_gets, 0, sizeof(struct stats));
8424 memset(&ch_reorders, 0, sizeof(struct stats));
8426 for (i = 0; i < VolumeHashTable.Size; i++) {
8427 head = &VolumeHashTable.Table[i];
8430 VHashBeginExclusive_r(head);
8433 ch_looks.sum = UInt64ToDouble(&head->looks);
8434 ch_gets.sum = UInt64ToDouble(&head->gets);
8435 ch_reorders.sum = UInt64ToDouble(&head->reorders);
8437 /* update global statistics */
8439 looks.sum += ch_looks.sum;
8440 gets.sum += ch_gets.sum;
8441 reorders.sum += ch_reorders.sum;
8442 len.sum += (double)head->len;
8443 vol_sum += head->len;
8446 len.min = (double) head->len;
8447 len.max = (double) head->len;
8448 looks.min = ch_looks.sum;
8449 looks.max = ch_looks.sum;
8450 gets.min = ch_gets.sum;
8451 gets.max = ch_gets.sum;
8452 reorders.min = ch_reorders.sum;
8453 reorders.max = ch_reorders.sum;
8455 if (((double)head->len) < len.min)
8456 len.min = (double) head->len;
8457 if (((double)head->len) > len.max)
8458 len.max = (double) head->len;
8459 if (ch_looks.sum < looks.min)
8460 looks.min = ch_looks.sum;
8461 else if (ch_looks.sum > looks.max)
8462 looks.max = ch_looks.sum;
8463 if (ch_gets.sum < gets.min)
8464 gets.min = ch_gets.sum;
8465 else if (ch_gets.sum > gets.max)
8466 gets.max = ch_gets.sum;
8467 if (ch_reorders.sum < reorders.min)
8468 reorders.min = ch_reorders.sum;
8469 else if (ch_reorders.sum > reorders.max)
8470 reorders.max = ch_reorders.sum;
8474 if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
8475 /* compute detailed per-chain stats */
8476 struct stats hdr_loads, hdr_gets;
8477 double v_looks, v_loads, v_gets;
8479 /* initialize stats with data from first element in chain */
8480 vp = queue_First(head, Volume);
8481 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
8482 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
8483 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
8484 ch_gets.min = ch_gets.max = v_looks;
8485 hdr_loads.min = hdr_loads.max = v_loads;
8486 hdr_gets.min = hdr_gets.max = v_gets;
8487 hdr_loads.sum = hdr_gets.sum = 0;
8489 vp = queue_Next(vp, Volume);
8491 /* pull in stats from remaining elements in chain */
8492 for (queue_ScanFrom(head, vp, vp, np, Volume)) {
8493 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
8494 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
8495 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
8497 hdr_loads.sum += v_loads;
8498 hdr_gets.sum += v_gets;
8500 if (v_looks < ch_gets.min)
8501 ch_gets.min = v_looks;
8502 else if (v_looks > ch_gets.max)
8503 ch_gets.max = v_looks;
8505 if (v_loads < hdr_loads.min)
8506 hdr_loads.min = v_loads;
8507 else if (v_loads > hdr_loads.max)
8508 hdr_loads.max = v_loads;
8510 if (v_gets < hdr_gets.min)
8511 hdr_gets.min = v_gets;
8512 else if (v_gets > hdr_gets.max)
8513 hdr_gets.max = v_gets;
8516 /* compute per-chain averages */
8517 ch_gets.avg = ch_gets.sum / ((double)head->len);
8518 hdr_loads.avg = hdr_loads.sum / ((double)head->len);
8519 hdr_gets.avg = hdr_gets.sum / ((double)head->len);
8521 /* dump per-chain stats */
8522 Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
8524 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
8525 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
8526 Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
8527 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
8528 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
8529 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
8530 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
8531 Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
8532 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
8533 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
8534 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
8535 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
8536 Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
8537 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
8538 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
8539 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
8540 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
8541 } else if (flags & VOL_STATS_PER_CHAIN) {
8542 /* dump simple per-chain stats */
8543 Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
8545 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
8546 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
8547 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
8551 VHashEndExclusive_r(head);
8556 /* compute global averages */
8557 len.avg = len.sum / ((double)VolumeHashTable.Size);
8558 looks.avg = looks.sum / ((double)VolumeHashTable.Size);
8559 gets.avg = gets.sum / ((double)VolumeHashTable.Size);
8560 reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
8562 /* dump global stats */
8563 Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
8564 Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
8565 DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
8566 DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
8567 DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
8568 DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
8569 Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
8570 DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
8571 DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
8572 DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
8573 DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
8574 Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
8575 DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
8576 DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
8577 DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
8578 DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
8579 Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
8580 DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
8581 DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
8582 DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
8583 DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
8585 /* print extended disk related statistics */
8587 struct DiskPartition64 * diskP;
8588 afs_uint32 vol_count[VOLMAXPARTS+1];
8589 byte part_exists[VOLMAXPARTS+1];
8593 memset(vol_count, 0, sizeof(vol_count));
8594 memset(part_exists, 0, sizeof(part_exists));
8598 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
8600 vol_count[id] = diskP->vol_list.len;
8601 part_exists[id] = 1;
8605 for (i = 0; i <= VOLMAXPARTS; i++) {
8606 if (part_exists[i]) {
8607 /* XXX while this is currently safe, it is a violation
8608 * of the VGetPartitionById_r interface contract. */
8609 diskP = VGetPartitionById_r(i, 0);
8611 Log("Partition %s has %d online volumes\n",
8612 VPartitionPath(diskP), diskP->vol_list.len);
8619 /* print extended VLRU statistics */
8620 if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
8621 afs_uint32 idx, cur, lpos;
8626 Log("VLRU State Dump:\n\n");
8628 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
8629 Log("\t%s:\n", vlru_idx_to_string(idx));
8632 for (cur = vlru_stats.queue_info[idx].start;
8633 cur < vlru_stats.queue_info[idx].len;
8635 line[lpos++] = vlru_stats.vec[cur].volid;
8637 Log("\t\t%u, %u, %u, %u, %u,\n",
8638 line[0], line[1], line[2], line[3], line[4]);
8647 Log("\t\t%u, %u, %u, %u, %u\n",
8648 line[0], line[1], line[2], line[3], line[4]);
8653 free(vlru_stats.vec);
8660 VPrintExtendedCacheStats(int flags)
8663 VPrintExtendedCacheStats_r(flags);
8666 #endif /* AFS_DEMAND_ATTACH_FS */
8669 VCanScheduleSalvage(void)
8671 return vol_opts.canScheduleSalvage;
8677 return vol_opts.canUseFSSYNC;
8681 VCanUseSALVSYNC(void)
8683 return vol_opts.canUseSALVSYNC;
8687 VCanUnsafeAttach(void)
8689 return vol_opts.unsafe_attach;