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);
3195 /* volume operation in progress */
3199 #else /* AFS_DEMAND_ATTACH_FS */
3201 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3205 #endif /* AFS_DEMAND_ATTACH_FS */
3207 if (V_needsSalvaged(vp)) {
3208 if (vp->specialStatus)
3209 vp->specialStatus = 0;
3211 #if defined(AFS_DEMAND_ATTACH_FS)
3212 if (!VCanScheduleSalvage()) {
3213 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
3215 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
3218 #else /* AFS_DEMAND_ATTACH_FS */
3220 #endif /* AFS_DEMAND_ATTACH_FS */
3226 vp->nextVnodeUnique = V_uniquifier(vp);
3228 if (VShouldCheckInUse(mode) && V_inUse(vp) && VolumeWriteable(vp)) {
3229 if (!V_needsSalvaged(vp)) {
3230 V_needsSalvaged(vp) = 1;
3231 VUpdateVolume_r(ec, vp, 0);
3233 #if defined(AFS_DEMAND_ATTACH_FS)
3234 if (!VCanScheduleSalvage()) {
3235 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3237 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
3240 #else /* AFS_DEMAND_ATTACH_FS */
3241 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3243 #endif /* AFS_DEMAND_ATTACH_FS */
3248 if (programType == fileServer && V_destroyMe(vp) == DESTROY_ME) {
3249 /* Only check destroyMe if we are the fileserver, since the
3250 * volserver et al sometimes need to work with volumes with
3251 * destroyMe set. Examples are 'temporary' volumes the
3252 * volserver creates, and when we create a volume (destroyMe
3253 * is set on creation; sometimes a separate volserver
3254 * transaction is created to clear destroyMe).
3257 #if defined(AFS_DEMAND_ATTACH_FS)
3258 /* schedule a salvage so the volume goes away on disk */
3259 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3260 VChangeState_r(vp, VOL_STATE_ERROR);
3263 #endif /* AFS_DEMAND_ATTACH_FS */
3264 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
3269 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
3270 #ifndef BITMAP_LATER
3271 if (programType == fileServer && VolumeWriteable(vp)) {
3273 for (i = 0; i < nVNODECLASSES; i++) {
3274 VGetBitmap_r(ec, vp, i);
3276 #ifdef AFS_DEMAND_ATTACH_FS
3277 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3279 #endif /* AFS_DEMAND_ATTACH_FS */
3280 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
3286 #endif /* BITMAP_LATER */
3288 if (VInit >= 2 && V_needsCallback(vp)) {
3289 if (V_BreakVolumeCallbacks) {
3290 Log("VAttachVolume: Volume %lu was changed externally; breaking callbacks\n",
3291 afs_printable_uint32_lu(V_id(vp)));
3292 V_needsCallback(vp) = 0;
3294 (*V_BreakVolumeCallbacks) (V_id(vp));
3297 VUpdateVolume_r(ec, vp, 0);
3299 #ifdef FSSYNC_BUILD_CLIENT
3300 else if (VCanUseFSSYNC()) {
3301 afs_int32 fsync_code;
3303 V_needsCallback(vp) = 0;
3305 fsync_code = FSYNC_VolOp(V_id(vp), NULL, FSYNC_VOL_BREAKCBKS, FSYNC_WHATEVER, NULL);
3309 V_needsCallback(vp) = 1;
3310 Log("Error trying to tell the fileserver to break callbacks for "
3311 "changed volume %lu; error code %ld\n",
3312 afs_printable_uint32_lu(V_id(vp)),
3313 afs_printable_int32_ld(fsync_code));
3315 VUpdateVolume_r(ec, vp, 0);
3318 #endif /* FSSYNC_BUILD_CLIENT */
3321 Log("VAttachVolume: error %d clearing needsCallback on volume "
3322 "%lu; needs salvage\n", (int)*ec,
3323 afs_printable_uint32_lu(V_id(vp)));
3324 #ifdef AFS_DEMAND_ATTACH_FS
3325 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3327 #else /* !AFS_DEMAND_ATTACH_FS */
3329 #endif /* !AFS_DEMAND_ATTACh_FS */
3334 if (programType == fileServer) {
3335 if (vp->specialStatus)
3336 vp->specialStatus = 0;
3337 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
3338 V_inUse(vp) = fileServer;
3339 V_offlineMessage(vp)[0] = '\0';
3343 #ifdef AFS_DEMAND_ATTACH_FS
3344 /* Put the vol into PREATTACHED state, so if someone tries to
3345 * access it again, we try to attach, see that we're not blessed,
3346 * and give a VNOVOL error again. Putting it into UNATTACHED state
3347 * would result in a VOFFLINE error instead. */
3348 error_state = VOL_STATE_PREATTACHED;
3349 #endif /* AFS_DEMAND_ATTACH_FS */
3351 /* mimic e.g. GetVolume errors */
3352 if (!V_blessed(vp)) {
3353 Log("Volume %lu offline: not blessed\n", afs_printable_uint32_lu(V_id(vp)));
3354 FreeVolumeHeader(vp);
3355 } else if (!V_inService(vp)) {
3356 Log("Volume %lu offline: not in service\n", afs_printable_uint32_lu(V_id(vp)));
3357 FreeVolumeHeader(vp);
3359 Log("Volume %lu offline: needs salvage\n", afs_printable_uint32_lu(V_id(vp)));
3361 #ifdef AFS_DEMAND_ATTACH_FS
3362 error_state = VOL_STATE_ERROR;
3363 /* see if we can recover */
3364 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
3367 #ifdef AFS_DEMAND_ATTACH_FS
3373 #ifdef AFS_DEMAND_ATTACH_FS
3374 if ((mode != V_PEEK) && (mode != V_SECRETLY))
3375 V_inUse(vp) = programType;
3376 #endif /* AFS_DEMAND_ATTACH_FS */
3377 V_checkoutMode(vp) = mode;
3380 AddVolumeToHashTable(vp, V_id(vp));
3381 #ifdef AFS_DEMAND_ATTACH_FS
3382 if (VCanUnlockAttached() && (V_attachFlags(vp) & VOL_LOCKED)) {
3385 if ((programType != fileServer) ||
3386 (V_inUse(vp) == fileServer)) {
3387 AddVolumeToVByPList_r(vp);
3389 VChangeState_r(vp, VOL_STATE_ATTACHED);
3391 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3398 #ifdef AFS_DEMAND_ATTACH_FS
3399 if (!VIsErrorState(V_attachState(vp))) {
3400 VChangeState_r(vp, error_state);
3402 #endif /* AFS_DEMAND_ATTACH_FS */
3405 VReleaseVolumeHandles_r(vp);
3408 #ifdef AFS_DEMAND_ATTACH_FS
3415 #else /* !AFS_DEMAND_ATTACH_FS */
3417 #endif /* !AFS_DEMAND_ATTACH_FS */
3421 /* Attach an existing volume.
3422 The volume also normally goes online at this time.
3423 An offline volume must be reattached to make it go online.
3427 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
3431 retVal = VAttachVolume_r(ec, volumeId, mode);
3437 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
3440 VGetVolumePath(ec, volumeId, &part, &name);
3444 vp = VGetVolume_r(&error, volumeId);
3446 osi_Assert(V_inUse(vp) == 0);
3447 VDetachVolume_r(ec, vp);
3451 return VAttachVolumeByName_r(ec, part, name, mode);
3454 /* Increment a reference count to a volume, sans context swaps. Requires
3455 * possibly reading the volume header in from the disk, since there's
3456 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
3458 * N.B. This call can fail if we can't read in the header!! In this case
3459 * we still guarantee we won't context swap, but the ref count won't be
3460 * incremented (otherwise we'd violate the invariant).
3462 /* NOTE: with the demand attach fileserver extensions, the global lock
3463 * is dropped within VHold */
3464 #ifdef AFS_DEMAND_ATTACH_FS
3466 VHold_r(Volume * vp)
3470 VCreateReservation_r(vp);
3471 VWaitExclusiveState_r(vp);
3473 LoadVolumeHeader(&error, vp);
3475 VCancelReservation_r(vp);
3479 VCancelReservation_r(vp);
3482 #else /* AFS_DEMAND_ATTACH_FS */
3484 VHold_r(Volume * vp)
3488 LoadVolumeHeader(&error, vp);
3494 #endif /* AFS_DEMAND_ATTACH_FS */
3502 retVal = VHold_r(vp);
3509 /***************************************************/
3510 /* get and put volume routines */
3511 /***************************************************/
3514 * put back a heavyweight reference to a volume object.
3516 * @param[in] vp volume object pointer
3518 * @pre VOL_LOCK held
3520 * @post heavyweight volume reference put back.
3521 * depending on state, volume may have been taken offline,
3522 * detached, salvaged, freed, etc.
3524 * @internal volume package internal use only
3527 VPutVolume_r(Volume * vp)
3529 osi_Assert(--vp->nUsers >= 0);
3530 if (vp->nUsers == 0) {
3532 ReleaseVolumeHeader(vp->header);
3533 #ifdef AFS_DEMAND_ATTACH_FS
3534 if (!VCheckDetach(vp)) {
3538 #else /* AFS_DEMAND_ATTACH_FS */
3540 #endif /* AFS_DEMAND_ATTACH_FS */
3545 VPutVolume(Volume * vp)
3553 /* Get a pointer to an attached volume. The pointer is returned regardless
3554 of whether or not the volume is in service or on/off line. An error
3555 code, however, is returned with an indication of the volume's status */
3557 VGetVolume(Error * ec, Error * client_ec, VolId volumeId)
3561 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
3566 /* same as VGetVolume, but if a volume is waiting to go offline, we return
3567 * that it is actually offline, instead of waiting for it to go offline */
3569 VGetVolumeNoWait(Error * ec, Error * client_ec, VolId volumeId)
3573 retVal = GetVolume(ec, client_ec, volumeId, NULL, 1);
3579 VGetVolume_r(Error * ec, VolId volumeId)
3581 return GetVolume(ec, NULL, volumeId, NULL, 0);
3584 /* try to get a volume we've previously looked up */
3585 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
3587 VGetVolumeByVp_r(Error * ec, Volume * vp)
3589 return GetVolume(ec, NULL, vp->hashid, vp, 0);
3593 * private interface for getting a volume handle
3595 * @param[out] ec error code (0 if no error)
3596 * @param[out] client_ec wire error code to be given to clients
3597 * @param[in] volumeId ID of the volume we want
3598 * @param[in] hint optional hint for hash lookups, or NULL
3599 * @param[in] nowait 0 to wait for a 'goingOffline' volume to go offline
3600 * before returning, 1 to return immediately
3602 * @return a volume handle for the specified volume
3603 * @retval NULL an error occurred, or the volume is in such a state that
3604 * we cannot load a header or return any volume struct
3606 * @note for DAFS, caller must NOT hold a ref count on 'hint'
3609 GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint, int nowait)
3612 /* pull this profiling/debugging code out of regular builds */
3614 #define VGET_CTR_INC(x) x++
3615 unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
3616 0, V7 = 0, V8 = 0, V9 = 0;
3617 unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
3619 #define VGET_CTR_INC(x)
3621 #ifdef AFS_DEMAND_ATTACH_FS
3622 Volume *avp, * rvp = hint;
3626 * if VInit is zero, the volume package dynamic
3627 * data structures have not been initialized yet,
3628 * and we must immediately return an error
3634 *client_ec = VOFFLINE;
3639 #ifdef AFS_DEMAND_ATTACH_FS
3641 VCreateReservation_r(rvp);
3643 #endif /* AFS_DEMAND_ATTACH_FS */
3651 vp = VLookupVolume_r(ec, volumeId, vp);
3657 #ifdef AFS_DEMAND_ATTACH_FS
3658 if (rvp && (rvp != vp)) {
3659 /* break reservation on old vp */
3660 VCancelReservation_r(rvp);
3663 #endif /* AFS_DEMAND_ATTACH_FS */
3669 /* Until we have reached an initialization level of 2
3670 * we don't know whether this volume exists or not.
3671 * We can't sleep and retry later because before a volume
3672 * is attached, the caller tries to get it first. Just
3673 * return VOFFLINE and the caller can choose whether to
3674 * retry the command or not. */
3684 IncUInt64(&VStats.hdr_gets);
3686 #ifdef AFS_DEMAND_ATTACH_FS
3687 /* block if someone else is performing an exclusive op on this volume */
3690 VCreateReservation_r(rvp);
3692 VWaitExclusiveState_r(vp);
3694 /* short circuit with VNOVOL in the following circumstances:
3697 * - VOL_STATE_SHUTTING_DOWN
3699 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
3700 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN) ||
3701 (V_attachState(vp) == VOL_STATE_GOING_OFFLINE)) {
3708 * short circuit with VOFFLINE for VOL_STATE_UNATTACHED and
3709 * VNOVOL for VOL_STATE_DELETED
3711 if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
3712 (V_attachState(vp) == VOL_STATE_DELETED)) {
3713 if (vp->specialStatus) {
3714 *ec = vp->specialStatus;
3715 } else if (V_attachState(vp) == VOL_STATE_DELETED) {
3724 /* allowable states:
3730 if (vp->salvage.requested) {
3731 VUpdateSalvagePriority_r(vp);
3734 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
3735 avp = VAttachVolumeByVp_r(ec, vp, 0);
3738 /* VAttachVolumeByVp_r can return a pointer
3739 * != the vp passed to it under certain
3740 * conditions; make sure we don't leak
3741 * reservations if that happens */
3743 VCancelReservation_r(rvp);
3745 VCreateReservation_r(rvp);
3755 if (!vp->pending_vol_op) {
3770 if ((V_attachState(vp) == VOL_STATE_SALVAGING) ||
3771 (*ec == VSALVAGING)) {
3773 /* see CheckVnode() in afsfileprocs.c for an explanation
3774 * of this error code logic */
3775 afs_uint32 now = FT_ApproxTime();
3776 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
3779 *client_ec = VRESTARTING;
3788 #ifdef AFS_DEMAND_ATTACH_FS
3790 * this test MUST happen after VAttachVolymeByVp, so vol_op_state is
3791 * not VolOpRunningUnknown (attach2 would have converted it to Online
3795 /* only valid before/during demand attachment */
3796 osi_Assert(!vp->pending_vol_op || vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
3798 /* deny getvolume due to running mutually exclusive vol op */
3799 if (vp->pending_vol_op && vp->pending_vol_op->vol_op_state==FSSYNC_VolOpRunningOffline) {
3801 * volume cannot remain online during this volume operation.
3804 if (vp->specialStatus) {
3806 * special status codes outrank normal VOFFLINE code
3808 *ec = vp->specialStatus;
3810 *client_ec = vp->specialStatus;
3814 /* see CheckVnode() in afsfileprocs.c for an explanation
3815 * of this error code logic */
3816 afs_uint32 now = FT_ApproxTime();
3817 if ((vp->stats.last_vol_op + (10 * 60)) >= now) {
3820 *client_ec = VRESTARTING;
3825 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3826 FreeVolumeHeader(vp);
3830 #endif /* AFS_DEMAND_ATTACH_FS */
3832 LoadVolumeHeader(ec, vp);
3835 /* Only log the error if it was a totally unexpected error. Simply
3836 * a missing inode is likely to be caused by the volume being deleted */
3837 if (errno != ENXIO || LogLevel)
3838 Log("Volume %u: couldn't reread volume header\n",
3840 #ifdef AFS_DEMAND_ATTACH_FS
3841 if (VCanScheduleSalvage()) {
3842 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3847 #else /* AFS_DEMAND_ATTACH_FS */
3850 #endif /* AFS_DEMAND_ATTACH_FS */
3855 if (vp->shuttingDown) {
3862 if (programType == fileServer) {
3864 if (vp->goingOffline && !nowait) {
3866 #ifdef AFS_DEMAND_ATTACH_FS
3867 /* wait for the volume to go offline */
3868 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
3869 VWaitStateChange_r(vp);
3871 #elif defined(AFS_PTHREAD_ENV)
3872 VOL_CV_WAIT(&vol_put_volume_cond);
3873 #else /* AFS_PTHREAD_ENV */
3874 LWP_WaitProcess(VPutVolume);
3875 #endif /* AFS_PTHREAD_ENV */
3878 if (vp->specialStatus) {
3880 *ec = vp->specialStatus;
3881 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3884 } else if (V_inUse(vp) == 0 || vp->goingOffline) {
3895 #ifdef AFS_DEMAND_ATTACH_FS
3896 /* if no error, bump nUsers */
3899 VLRU_UpdateAccess_r(vp);
3902 VCancelReservation_r(rvp);
3905 if (client_ec && !*client_ec) {
3908 #else /* AFS_DEMAND_ATTACH_FS */
3909 /* if no error, bump nUsers */
3916 #endif /* AFS_DEMAND_ATTACH_FS */
3919 osi_Assert(vp || *ec);
3924 /***************************************************/
3925 /* Volume offline/detach routines */
3926 /***************************************************/
3928 /* caller MUST hold a heavyweight ref on vp */
3929 #ifdef AFS_DEMAND_ATTACH_FS
3931 VTakeOffline_r(Volume * vp)
3935 osi_Assert(vp->nUsers > 0);
3936 osi_Assert(programType == fileServer);
3938 VCreateReservation_r(vp);
3939 VWaitExclusiveState_r(vp);
3941 vp->goingOffline = 1;
3942 V_needsSalvaged(vp) = 1;
3944 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
3945 VCancelReservation_r(vp);
3947 #else /* AFS_DEMAND_ATTACH_FS */
3949 VTakeOffline_r(Volume * vp)
3951 osi_Assert(vp->nUsers > 0);
3952 osi_Assert(programType == fileServer);
3954 vp->goingOffline = 1;
3955 V_needsSalvaged(vp) = 1;
3957 #endif /* AFS_DEMAND_ATTACH_FS */
3960 VTakeOffline(Volume * vp)
3968 * force a volume offline.
3970 * @param[in] vp volume object pointer
3971 * @param[in] flags flags (see note below)
3973 * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
3974 * used when VUpdateVolume_r needs to call VForceOffline_r
3975 * (which in turn would normally call VUpdateVolume_r)
3977 * @see VUpdateVolume_r
3979 * @pre VOL_LOCK must be held.
3980 * for DAFS, caller must hold ref.
3982 * @note for DAFS, it _is safe_ to call this function from an
3985 * @post needsSalvaged flag is set.
3986 * for DAFS, salvage is requested.
3987 * no further references to the volume through the volume
3988 * package will be honored.
3989 * all file descriptor and vnode caches are invalidated.
3991 * @warning this is a heavy-handed interface. it results in
3992 * a volume going offline regardless of the current
3993 * reference count state.
3995 * @internal volume package internal use only
3998 VForceOffline_r(Volume * vp, int flags)
4002 #ifdef AFS_DEMAND_ATTACH_FS
4003 VChangeState_r(vp, VOL_STATE_ERROR);
4008 strcpy(V_offlineMessage(vp),
4009 "Forced offline due to internal error: volume needs to be salvaged");
4010 Log("Volume %u forced offline: it needs salvaging!\n", V_id(vp));
4013 vp->goingOffline = 0;
4014 V_needsSalvaged(vp) = 1;
4015 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
4016 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
4019 #ifdef AFS_DEMAND_ATTACH_FS
4020 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
4021 #endif /* AFS_DEMAND_ATTACH_FS */
4023 #ifdef AFS_PTHREAD_ENV
4024 CV_BROADCAST(&vol_put_volume_cond);
4025 #else /* AFS_PTHREAD_ENV */
4026 LWP_NoYieldSignal(VPutVolume);
4027 #endif /* AFS_PTHREAD_ENV */
4029 VReleaseVolumeHandles_r(vp);
4033 * force a volume offline.
4035 * @param[in] vp volume object pointer
4037 * @see VForceOffline_r
4040 VForceOffline(Volume * vp)
4043 VForceOffline_r(vp, 0);
4047 /* The opposite of VAttachVolume. The volume header is written to disk, with
4048 the inUse bit turned off. A copy of the header is maintained in memory,
4049 however (which is why this is VOffline, not VDetach).
4052 VOffline_r(Volume * vp, char *message)
4054 #ifndef AFS_DEMAND_ATTACH_FS
4056 VolumeId vid = V_id(vp);
4059 osi_Assert(programType != volumeUtility && programType != volumeServer);
4064 if (V_offlineMessage(vp)[0] == '\0')
4065 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4066 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4068 vp->goingOffline = 1;
4069 #ifdef AFS_DEMAND_ATTACH_FS
4070 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4071 VCreateReservation_r(vp);
4074 /* wait for the volume to go offline */
4075 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
4076 VWaitStateChange_r(vp);
4078 VCancelReservation_r(vp);
4079 #else /* AFS_DEMAND_ATTACH_FS */
4081 vp = VGetVolume_r(&error, vid); /* Wait for it to go offline */
4082 if (vp) /* In case it was reattached... */
4084 #endif /* AFS_DEMAND_ATTACH_FS */
4087 #ifdef AFS_DEMAND_ATTACH_FS
4089 * Take a volume offline in order to perform a volume operation.
4091 * @param[inout] ec address in which to store error code
4092 * @param[in] vp volume object pointer
4093 * @param[in] message volume offline status message
4096 * - VOL_LOCK is held
4097 * - caller MUST hold a heavyweight ref on vp
4100 * - volume is taken offline
4101 * - if possible, volume operation is promoted to running state
4102 * - on failure, *ec is set to nonzero
4104 * @note Although this function does not return any value, it may
4105 * still fail to promote our pending volume operation to
4106 * a running state. Any caller MUST check the value of *ec,
4107 * and MUST NOT blindly assume success.
4109 * @warning if the caller does not hold a lightweight ref on vp,
4110 * then it MUST NOT reference vp after this function
4111 * returns to the caller.
4113 * @internal volume package internal use only
4116 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
4118 osi_Assert(vp->pending_vol_op);
4124 if (V_offlineMessage(vp)[0] == '\0')
4125 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4126 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4128 vp->goingOffline = 1;
4129 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4130 VCreateReservation_r(vp);
4133 /* Wait for the volume to go offline */
4134 while (!VIsOfflineState(V_attachState(vp))) {
4135 /* do not give corrupted volumes to the volserver */
4136 if (vp->salvage.requested && vp->pending_vol_op->com.programType != salvageServer) {
4140 VWaitStateChange_r(vp);
4144 VCancelReservation_r(vp);
4146 #endif /* AFS_DEMAND_ATTACH_FS */
4149 VOffline(Volume * vp, char *message)
4152 VOffline_r(vp, message);
4156 /* This gets used for the most part by utility routines that don't want
4157 * to keep all the volume headers around. Generally, the file server won't
4158 * call this routine, because then the offline message in the volume header
4159 * (or other information) won't be available to clients. For NAMEI, also
4160 * close the file handles. However, the fileserver does call this during
4161 * an attach following a volume operation.
4164 VDetachVolume_r(Error * ec, Volume * vp)
4166 #ifdef FSSYNC_BUILD_CLIENT
4168 struct DiskPartition64 *tpartp;
4169 int notifyServer = 0;
4170 int useDone = FSYNC_VOL_ON;
4172 if (VCanUseFSSYNC()) {
4173 notifyServer = vp->needsPutBack;
4174 if (V_destroyMe(vp) == DESTROY_ME)
4175 useDone = FSYNC_VOL_DONE;
4176 #ifdef AFS_DEMAND_ATTACH_FS
4177 else if (!V_blessed(vp) || !V_inService(vp))
4178 useDone = FSYNC_VOL_LEAVE_OFF;
4181 tpartp = vp->partition;
4183 #endif /* FSSYNC_BUILD_CLIENT */
4185 *ec = 0; /* always "succeeds" */
4186 DeleteVolumeFromHashTable(vp);
4187 vp->shuttingDown = 1;
4188 #ifdef AFS_DEMAND_ATTACH_FS
4189 DeleteVolumeFromVByPList_r(vp);
4191 VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
4193 if (programType != fileServer)
4195 #endif /* AFS_DEMAND_ATTACH_FS */
4197 /* Will be detached sometime in the future--this is OK since volume is offline */
4199 /* XXX the following code should really be moved to VCheckDetach() since the volume
4200 * is not technically detached until the refcounts reach zero
4202 #ifdef FSSYNC_BUILD_CLIENT
4203 if (VCanUseFSSYNC() && notifyServer) {
4205 * Note: The server is not notified in the case of a bogus volume
4206 * explicitly to make it possible to create a volume, do a partial
4207 * restore, then abort the operation without ever putting the volume
4208 * online. This is essential in the case of a volume move operation
4209 * between two partitions on the same server. In that case, there
4210 * would be two instances of the same volume, one of them bogus,
4211 * which the file server would attempt to put on line
4213 FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
4214 /* XXX this code path is only hit by volume utilities, thus
4215 * V_BreakVolumeCallbacks will always be NULL. if we really
4216 * want to break callbacks in this path we need to use FSYNC_VolOp() */
4218 /* Dettaching it so break all callbacks on it */
4219 if (V_BreakVolumeCallbacks) {
4220 Log("volume %u detached; breaking all call backs\n", volume);
4221 (*V_BreakVolumeCallbacks) (volume);
4225 #endif /* FSSYNC_BUILD_CLIENT */
4229 VDetachVolume(Error * ec, Volume * vp)
4232 VDetachVolume_r(ec, vp);
4237 /***************************************************/
4238 /* Volume fd/inode handle closing routines */
4239 /***************************************************/
4241 /* For VDetachVolume, we close all cached file descriptors, but keep
4242 * the Inode handles in case we need to read from a busy volume.
4244 /* for demand attach, caller MUST hold ref count on vp */
4246 VCloseVolumeHandles_r(Volume * vp)
4248 #ifdef AFS_DEMAND_ATTACH_FS
4249 VolState state_save;
4251 state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
4256 * XXX need to investigate whether we can perform
4257 * DFlushVolume outside of vol_glock_mutex...
4259 * VCloseVnodeFiles_r drops the glock internally */
4260 DFlushVolume(vp->hashid);
4261 VCloseVnodeFiles_r(vp);
4263 #ifdef AFS_DEMAND_ATTACH_FS
4267 /* Too time consuming and unnecessary for the volserver */
4268 if (programType == fileServer) {
4269 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4270 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4271 IH_CONDSYNC(vp->diskDataHandle);
4273 IH_CONDSYNC(vp->linkHandle);
4274 #endif /* AFS_NT40_ENV */
4277 IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
4278 IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
4279 IH_REALLYCLOSE(vp->diskDataHandle);
4280 IH_REALLYCLOSE(vp->linkHandle);
4282 #ifdef AFS_DEMAND_ATTACH_FS
4283 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4288 VChangeState_r(vp, state_save);
4292 /* For both VForceOffline and VOffline, we close all relevant handles.
4293 * For VOffline, if we re-attach the volume, the files may possible be
4294 * different than before.
4296 /* for demand attach, caller MUST hold a ref count on vp */
4298 VReleaseVolumeHandles_r(Volume * vp)
4300 #ifdef AFS_DEMAND_ATTACH_FS
4301 VolState state_save;
4303 state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
4306 /* XXX need to investigate whether we can perform
4307 * DFlushVolume outside of vol_glock_mutex... */
4308 DFlushVolume(vp->hashid);
4310 VReleaseVnodeFiles_r(vp); /* releases the glock internally */
4312 #ifdef AFS_DEMAND_ATTACH_FS
4316 /* Too time consuming and unnecessary for the volserver */
4317 if (programType == fileServer) {
4318 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4319 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4320 IH_CONDSYNC(vp->diskDataHandle);
4322 IH_CONDSYNC(vp->linkHandle);
4323 #endif /* AFS_NT40_ENV */
4326 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
4327 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
4328 IH_RELEASE(vp->diskDataHandle);
4329 IH_RELEASE(vp->linkHandle);
4331 #ifdef AFS_DEMAND_ATTACH_FS
4332 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4337 VChangeState_r(vp, state_save);
4342 /***************************************************/
4343 /* Volume write and fsync routines */
4344 /***************************************************/
4347 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
4349 #ifdef AFS_DEMAND_ATTACH_FS
4350 VolState state_save;
4352 if (flags & VOL_UPDATE_WAIT) {
4353 VCreateReservation_r(vp);
4354 VWaitExclusiveState_r(vp);
4359 if (programType == fileServer)
4361 (V_inUse(vp) ? V_nextVnodeUnique(vp) +
4362 200 : V_nextVnodeUnique(vp));
4364 #ifdef AFS_DEMAND_ATTACH_FS
4365 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4369 WriteVolumeHeader_r(ec, vp);
4371 #ifdef AFS_DEMAND_ATTACH_FS
4373 VChangeState_r(vp, state_save);
4374 if (flags & VOL_UPDATE_WAIT) {
4375 VCancelReservation_r(vp);
4380 Log("VUpdateVolume: error updating volume header, volume %u (%s)\n",
4381 V_id(vp), V_name(vp));
4382 /* try to update on-disk header,
4383 * while preventing infinite recursion */
4384 if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
4385 VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
4391 VUpdateVolume(Error * ec, Volume * vp)
4394 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4399 VSyncVolume_r(Error * ec, Volume * vp, int flags)
4403 #ifdef AFS_DEMAND_ATTACH_FS
4404 VolState state_save;
4407 if (flags & VOL_SYNC_WAIT) {
4408 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4410 VUpdateVolume_r(ec, vp, 0);
4413 #ifdef AFS_DEMAND_ATTACH_FS
4414 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4417 fdP = IH_OPEN(V_diskDataHandle(vp));
4418 osi_Assert(fdP != NULL);
4419 code = FDH_SYNC(fdP);
4420 osi_Assert(code == 0);
4422 #ifdef AFS_DEMAND_ATTACH_FS
4424 VChangeState_r(vp, state_save);
4430 VSyncVolume(Error * ec, Volume * vp)
4433 VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
4438 /***************************************************/
4439 /* Volume dealloaction routines */
4440 /***************************************************/
4442 #ifdef AFS_DEMAND_ATTACH_FS
4444 FreeVolume(Volume * vp)
4446 /* free the heap space, iff it's safe.
4447 * otherwise, pull it out of the hash table, so it
4448 * will get deallocated when all refs to it go away */
4449 if (!VCheckFree(vp)) {
4450 DeleteVolumeFromHashTable(vp);
4451 DeleteVolumeFromVByPList_r(vp);
4453 /* make sure we invalidate the header cache entry */
4454 FreeVolumeHeader(vp);
4457 #endif /* AFS_DEMAND_ATTACH_FS */
4460 ReallyFreeVolume(Volume * vp)
4465 #ifdef AFS_DEMAND_ATTACH_FS
4467 VChangeState_r(vp, VOL_STATE_FREED);
4468 if (vp->pending_vol_op)
4469 free(vp->pending_vol_op);
4470 #endif /* AFS_DEMAND_ATTACH_FS */
4471 for (i = 0; i < nVNODECLASSES; i++)
4472 if (vp->vnodeIndex[i].bitmap)
4473 free(vp->vnodeIndex[i].bitmap);
4474 FreeVolumeHeader(vp);
4475 #ifndef AFS_DEMAND_ATTACH_FS
4476 DeleteVolumeFromHashTable(vp);
4477 #endif /* AFS_DEMAND_ATTACH_FS */
4481 /* check to see if we should shutdown this volume
4482 * returns 1 if volume was freed, 0 otherwise */
4483 #ifdef AFS_DEMAND_ATTACH_FS
4485 VCheckDetach(Volume * vp)
4490 if (vp->nUsers || vp->nWaiters)
4493 if (vp->shuttingDown) {
4495 if ((programType != fileServer) &&
4496 (V_inUse(vp) == programType) &&
4497 ((V_checkoutMode(vp) == V_VOLUPD) ||
4498 (V_checkoutMode(vp) == V_SECRETLY) ||
4499 ((V_checkoutMode(vp) == V_CLONE) &&
4500 (VolumeWriteable(vp))))) {
4502 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
4504 Log("VCheckDetach: volume header update for volume %u "
4505 "failed with errno %d\n", vp->hashid, errno);
4508 VReleaseVolumeHandles_r(vp);
4510 ReallyFreeVolume(vp);
4511 if (programType == fileServer) {
4512 CV_BROADCAST(&vol_put_volume_cond);
4517 #else /* AFS_DEMAND_ATTACH_FS */
4519 VCheckDetach(Volume * vp)
4527 if (vp->shuttingDown) {
4529 if ((programType != fileServer) &&
4530 (V_inUse(vp) == programType) &&
4531 ((V_checkoutMode(vp) == V_VOLUPD) ||
4532 (V_checkoutMode(vp) == V_SECRETLY) ||
4533 ((V_checkoutMode(vp) == V_CLONE) &&
4534 (VolumeWriteable(vp))))) {
4536 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
4538 Log("VCheckDetach: volume header update for volume %u failed with errno %d\n",
4542 VReleaseVolumeHandles_r(vp);
4543 ReallyFreeVolume(vp);
4544 if (programType == fileServer) {
4545 #if defined(AFS_PTHREAD_ENV)
4546 CV_BROADCAST(&vol_put_volume_cond);
4547 #else /* AFS_PTHREAD_ENV */
4548 LWP_NoYieldSignal(VPutVolume);
4549 #endif /* AFS_PTHREAD_ENV */
4554 #endif /* AFS_DEMAND_ATTACH_FS */
4556 /* check to see if we should offline this volume
4557 * return 1 if volume went offline, 0 otherwise */
4558 #ifdef AFS_DEMAND_ATTACH_FS
4560 VCheckOffline(Volume * vp)
4564 if (vp->goingOffline && !vp->nUsers) {
4566 osi_Assert(programType == fileServer);
4567 osi_Assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
4568 (V_attachState(vp) != VOL_STATE_FREED) &&
4569 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
4570 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
4571 (V_attachState(vp) != VOL_STATE_DELETED));
4575 * VOL_STATE_GOING_OFFLINE
4576 * VOL_STATE_SHUTTING_DOWN
4577 * VIsErrorState(V_attachState(vp))
4578 * VIsExclusiveState(V_attachState(vp))
4581 VCreateReservation_r(vp);
4582 VChangeState_r(vp, VOL_STATE_OFFLINING);
4585 /* must clear the goingOffline flag before we drop the glock */
4586 vp->goingOffline = 0;
4591 /* perform async operations */
4592 VUpdateVolume_r(&error, vp, 0);
4593 VCloseVolumeHandles_r(vp);
4596 if (V_offlineMessage(vp)[0]) {
4597 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
4598 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
4599 V_offlineMessage(vp));
4601 Log("VOffline: Volume %lu (%s) is now offline\n",
4602 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
4606 /* invalidate the volume header cache entry */
4607 FreeVolumeHeader(vp);
4609 /* if nothing changed state to error or salvaging,
4610 * drop state to unattached */
4611 if (!VIsErrorState(V_attachState(vp))) {
4612 VChangeState_r(vp, VOL_STATE_UNATTACHED);
4614 VCancelReservation_r(vp);
4615 /* no usage of vp is safe beyond this point */
4619 #else /* AFS_DEMAND_ATTACH_FS */
4621 VCheckOffline(Volume * vp)
4625 if (vp->goingOffline && !vp->nUsers) {
4627 osi_Assert(programType == fileServer);
4630 vp->goingOffline = 0;
4632 VUpdateVolume_r(&error, vp, 0);
4633 VCloseVolumeHandles_r(vp);
4635 Log("VOffline: Volume %u (%s) is now offline", V_id(vp),
4637 if (V_offlineMessage(vp)[0])
4638 Log(" (%s)", V_offlineMessage(vp));
4641 FreeVolumeHeader(vp);
4642 #ifdef AFS_PTHREAD_ENV
4643 CV_BROADCAST(&vol_put_volume_cond);
4644 #else /* AFS_PTHREAD_ENV */
4645 LWP_NoYieldSignal(VPutVolume);
4646 #endif /* AFS_PTHREAD_ENV */
4650 #endif /* AFS_DEMAND_ATTACH_FS */
4652 /***************************************************/
4653 /* demand attach fs ref counting routines */
4654 /***************************************************/
4656 #ifdef AFS_DEMAND_ATTACH_FS
4657 /* the following two functions handle reference counting for
4658 * asynchronous operations on volume structs.
4660 * their purpose is to prevent a VDetachVolume or VShutdown
4661 * from free()ing the Volume struct during an async i/o op */
4663 /* register with the async volume op ref counter */
4664 /* VCreateReservation_r moved into inline code header because it
4665 * is now needed in vnode.c -- tkeiser 11/20/2007
4669 * decrement volume-package internal refcount.
4671 * @param vp volume object pointer
4673 * @internal volume package internal use only
4676 * @arg VOL_LOCK is held
4677 * @arg lightweight refcount held
4679 * @post volume waiters refcount is decremented; volume may
4680 * have been deallocated/shutdown/offlined/salvaged/
4681 * whatever during the process
4683 * @warning once you have tossed your last reference (you can acquire
4684 * lightweight refs recursively) it is NOT SAFE to reference
4685 * a volume object pointer ever again
4687 * @see VCreateReservation_r
4689 * @note DEMAND_ATTACH_FS only
4692 VCancelReservation_r(Volume * vp)
4694 osi_Assert(--vp->nWaiters >= 0);
4695 if (vp->nWaiters == 0) {
4697 if (!VCheckDetach(vp)) {
4704 /* check to see if we should free this volume now
4705 * return 1 if volume was freed, 0 otherwise */
4707 VCheckFree(Volume * vp)
4710 if ((vp->nUsers == 0) &&
4711 (vp->nWaiters == 0) &&
4712 !(V_attachFlags(vp) & (VOL_IN_HASH |
4716 ReallyFreeVolume(vp);
4721 #endif /* AFS_DEMAND_ATTACH_FS */
4724 /***************************************************/
4725 /* online volume operations routines */
4726 /***************************************************/
4728 #ifdef AFS_DEMAND_ATTACH_FS
4730 * register a volume operation on a given volume.
4732 * @param[in] vp volume object
4733 * @param[in] vopinfo volume operation info object
4735 * @pre VOL_LOCK is held
4737 * @post volume operation info object attached to volume object.
4738 * volume operation statistics updated.
4740 * @note by "attached" we mean a copy of the passed in object is made
4742 * @internal volume package internal use only
4745 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4747 FSSYNC_VolOp_info * info;
4749 /* attach a vol op info node to the volume struct */
4750 info = (FSSYNC_VolOp_info *) malloc(sizeof(FSSYNC_VolOp_info));
4751 osi_Assert(info != NULL);
4752 memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
4753 vp->pending_vol_op = info;
4756 vp->stats.last_vol_op = FT_ApproxTime();
4757 vp->stats.vol_ops++;
4758 IncUInt64(&VStats.vol_ops);
4764 * deregister the volume operation attached to this volume.
4766 * @param[in] vp volume object pointer
4768 * @pre VOL_LOCK is held
4770 * @post the volume operation info object is detached from the volume object
4772 * @internal volume package internal use only
4775 VDeregisterVolOp_r(Volume * vp)
4777 if (vp->pending_vol_op) {
4778 free(vp->pending_vol_op);
4779 vp->pending_vol_op = NULL;
4783 #endif /* AFS_DEMAND_ATTACH_FS */
4786 * determine whether it is safe to leave a volume online during
4787 * the volume operation described by the vopinfo object.
4789 * @param[in] vp volume object
4790 * @param[in] vopinfo volume operation info object
4792 * @return whether it is safe to leave volume online
4793 * @retval 0 it is NOT SAFE to leave the volume online
4794 * @retval 1 it is safe to leave the volume online during the operation
4797 * @arg VOL_LOCK is held
4798 * @arg disk header attached to vp (heavyweight ref on vp will guarantee
4799 * this condition is met)
4801 * @internal volume package internal use only
4804 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4806 return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
4807 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4808 (vopinfo->com.reason == V_READONLY ||
4809 (!VolumeWriteable(vp) &&
4810 (vopinfo->com.reason == V_CLONE ||
4811 vopinfo->com.reason == V_DUMP)))));
4815 * same as VVolOpLeaveOnline_r, but does not require a volume with an attached
4818 * @param[in] vp volume object
4819 * @param[in] vopinfo volume operation info object
4821 * @return whether it is safe to leave volume online
4822 * @retval 0 it is NOT SAFE to leave the volume online
4823 * @retval 1 it is safe to leave the volume online during the operation
4824 * @retval -1 unsure; volume header is required in order to know whether or
4825 * not is is safe to leave the volume online
4827 * @pre VOL_LOCK is held
4829 * @internal volume package internal use only
4832 VVolOpLeaveOnlineNoHeader_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4834 /* follow the logic in VVolOpLeaveOnline_r; this is the same, except
4835 * assume that we don't know VolumeWriteable; return -1 if the answer
4836 * depends on VolumeWriteable */
4838 if (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline) {
4841 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4842 vopinfo->com.reason == V_READONLY) {
4846 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4847 (vopinfo->com.reason == V_CLONE ||
4848 vopinfo->com.reason == V_DUMP)) {
4850 /* must know VolumeWriteable */
4857 * determine whether VBUSY should be set during this volume operation.
4859 * @param[in] vp volume object
4860 * @param[in] vopinfo volume operation info object
4862 * @return whether VBUSY should be set
4863 * @retval 0 VBUSY does NOT need to be set
4864 * @retval 1 VBUSY SHOULD be set
4866 * @pre VOL_LOCK is held
4868 * @internal volume package internal use only
4871 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4873 return ((vopinfo->com.command == FSYNC_VOL_OFF &&
4874 vopinfo->com.reason == FSYNC_SALVAGE) ||
4875 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4876 (vopinfo->com.reason == V_CLONE ||
4877 vopinfo->com.reason == V_DUMP)));
4881 /***************************************************/
4882 /* online salvager routines */
4883 /***************************************************/
4884 #if defined(AFS_DEMAND_ATTACH_FS)
4886 * check whether a salvage needs to be performed on this volume.
4888 * @param[in] vp pointer to volume object
4890 * @return status code
4891 * @retval 0 no salvage scheduled
4892 * @retval 1 a salvage has been scheduled with the salvageserver
4894 * @pre VOL_LOCK is held
4896 * @post if salvage request flag is set and nUsers and nWaiters are zero,
4897 * then a salvage will be requested
4899 * @note this is one of the event handlers called by VCancelReservation_r
4901 * @see VCancelReservation_r
4903 * @internal volume package internal use only.
4906 VCheckSalvage(Volume * vp)
4909 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
4910 if (vp->nUsers || vp->nWaiters)
4912 if (vp->salvage.requested) {
4913 VScheduleSalvage_r(vp);
4916 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
4921 * request volume salvage.
4923 * @param[out] ec computed client error code
4924 * @param[in] vp volume object pointer
4925 * @param[in] reason reason code (passed to salvageserver via SALVSYNC)
4926 * @param[in] flags see flags note below
4929 * VOL_SALVAGE_INVALIDATE_HEADER causes volume header cache entry
4930 * to be invalidated.
4932 * @pre VOL_LOCK is held.
4934 * @post volume state is changed.
4935 * for fileserver, salvage will be requested once refcount reaches zero.
4937 * @return operation status code
4938 * @retval 0 volume salvage will occur
4939 * @retval 1 volume salvage could not be scheduled
4943 * @note in the fileserver, this call does not synchronously schedule a volume
4944 * salvage. rather, it sets volume state so that when volume refcounts
4945 * reach zero, a volume salvage will occur. by "refcounts", we mean both
4946 * nUsers and nWaiters must be zero.
4948 * @internal volume package internal use only.
4951 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
4955 * for DAFS volume utilities that are not supposed to schedule salvages,
4956 * just transition to error state instead
4958 if (!VCanScheduleSalvage()) {
4959 VChangeState_r(vp, VOL_STATE_ERROR);
4964 if (programType != fileServer && !VCanUseFSSYNC()) {
4965 VChangeState_r(vp, VOL_STATE_ERROR);
4970 if (!vp->salvage.requested) {
4971 vp->salvage.requested = 1;
4972 vp->salvage.reason = reason;
4973 vp->stats.last_salvage = FT_ApproxTime();
4975 /* Note that it is not possible for us to reach this point if a
4976 * salvage is already running on this volume (even if the fileserver
4977 * was restarted during the salvage). If a salvage were running, the
4978 * salvager would have write-locked the volume header file, so when
4979 * we tried to lock the volume header, the lock would have failed,
4980 * and we would have failed during attachment prior to calling
4981 * VRequestSalvage. So we know that we can schedule salvages without
4982 * fear of a salvage already running for this volume. */
4984 if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
4985 VChangeState_r(vp, VOL_STATE_SALVAGING);
4988 Log("VRequestSalvage: volume %u online salvaged too many times; forced offline.\n", vp->hashid);
4990 /* make sure neither VScheduleSalvage_r nor
4991 * VUpdateSalvagePriority_r try to schedule another salvage */
4992 vp->salvage.requested = vp->salvage.scheduled = 0;
4994 VChangeState_r(vp, VOL_STATE_ERROR);
4998 if (flags & VOL_SALVAGE_INVALIDATE_HEADER) {
4999 /* Instead of ReleaseVolumeHeader, we do FreeVolumeHeader()
5000 so that the the next VAttachVolumeByVp_r() invocation
5001 of attach2() will pull in a cached header
5002 entry and fail, then load a fresh one from disk and attach
5005 FreeVolumeHeader(vp);
5012 * update salvageserver scheduling priority for a volume.
5014 * @param[in] vp pointer to volume object
5016 * @return operation status
5018 * @retval 1 request denied, or SALVSYNC communications failure
5020 * @pre VOL_LOCK is held.
5022 * @post in-core salvage priority counter is incremented. if at least
5023 * SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
5024 * last SALVSYNC_RAISEPRIO request, we contact the salvageserver
5025 * to update its priority queue. if no salvage is scheduled,
5026 * this function is a no-op.
5028 * @note DAFS fileserver only
5030 * @note this should be called whenever a VGetVolume fails due to a
5031 * pending salvage request
5033 * @todo should set exclusive state and drop glock around salvsync call
5035 * @internal volume package internal use only.
5038 VUpdateSalvagePriority_r(Volume * vp)
5042 #ifdef SALVSYNC_BUILD_CLIENT
5047 now = FT_ApproxTime();
5049 /* update the salvageserver priority queue occasionally so that
5050 * frequently requested volumes get moved to the head of the queue
5052 if ((vp->salvage.scheduled) &&
5053 (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
5054 code = SALVSYNC_SalvageVolume(vp->hashid,
5055 VPartitionPath(vp->partition),
5060 vp->stats.last_salvage_req = now;
5061 if (code != SYNC_OK) {
5065 #endif /* SALVSYNC_BUILD_CLIENT */
5070 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5072 /* A couple of little helper functions. These return true if we tried to
5073 * use this mechanism to schedule a salvage, false if we haven't tried.
5074 * If we did try a salvage then the results are contained in code.
5078 try_SALVSYNC(Volume *vp, char *partName, int *code) {
5079 #ifdef SALVSYNC_BUILD_CLIENT
5080 if (VCanUseSALVSYNC()) {
5081 Log("Scheduling salvage for volume %lu on part %s over SALVSYNC\n",
5082 afs_printable_uint32_lu(vp->hashid), partName);
5084 /* can't use V_id() since there's no guarantee
5085 * we have the disk data header at this point */
5086 *code = SALVSYNC_SalvageVolume(vp->hashid,
5099 try_FSSYNC(Volume *vp, char *partName, int *code) {
5100 #ifdef FSSYNC_BUILD_CLIENT
5101 if (VCanUseFSSYNC()) {
5102 Log("Scheduling salvage for volume %lu on part %s over FSSYNC\n",
5103 afs_printable_uint32_lu(vp->hashid), partName);
5106 * If we aren't the fileserver, tell the fileserver the volume
5107 * needs to be salvaged. We could directly tell the
5108 * salvageserver, but the fileserver keeps track of some stats
5109 * related to salvages, and handles some other salvage-related
5110 * complications for us.
5112 *code = FSYNC_VolOp(vp->hashid, partName,
5113 FSYNC_VOL_FORCE_ERROR, FSYNC_SALVAGE, NULL);
5116 #endif /* FSSYNC_BUILD_CLIENT */
5121 * schedule a salvage with the salvage server or fileserver.
5123 * @param[in] vp pointer to volume object
5125 * @return operation status
5126 * @retval 0 salvage scheduled successfully
5127 * @retval 1 salvage not scheduled, or SALVSYNC/FSSYNC com error
5130 * @arg VOL_LOCK is held.
5131 * @arg nUsers and nWaiters should be zero.
5133 * @post salvageserver or fileserver is sent a salvage request
5135 * @note If we are the fileserver, the request will be sent to the salvage
5136 * server over SALVSYNC. If we are not the fileserver, the request will be
5137 * sent to the fileserver over FSSYNC (FSYNC_VOL_FORCE_ERROR/FSYNC_SALVAGE).
5141 * @internal volume package internal use only.
5144 VScheduleSalvage_r(Volume * vp)
5148 VolState state_save;
5149 VThreadOptions_t * thread_opts;
5152 osi_Assert(VCanUseSALVSYNC() || VCanUseFSSYNC());
5154 if (vp->nWaiters || vp->nUsers) {
5158 /* prevent endless salvage,attach,salvage,attach,... loops */
5159 if (vp->stats.salvages >= SALVAGE_COUNT_MAX)
5163 * don't perform salvsync ops on certain threads
5165 thread_opts = pthread_getspecific(VThread_key);
5166 if (thread_opts == NULL) {
5167 thread_opts = &VThread_defaults;
5169 if (thread_opts->disallow_salvsync || vol_disallow_salvsync) {
5174 * XXX the scheduling process should really be done asynchronously
5175 * to avoid fssync deadlocks
5177 if (!vp->salvage.scheduled) {
5178 /* if we haven't previously scheduled a salvage, do so now
5180 * set the volume to an exclusive state and drop the lock
5181 * around the SALVSYNC call
5183 * note that we do NOT acquire a reservation here -- doing so
5184 * could result in unbounded recursion
5186 strlcpy(partName, VPartitionPath(vp->partition), sizeof(partName));
5187 state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
5190 osi_Assert(try_SALVSYNC(vp, partName, &code) ||
5191 try_FSSYNC(vp, partName, &code));
5194 VChangeState_r(vp, state_save);
5196 if (code == SYNC_OK) {
5197 vp->salvage.scheduled = 1;
5198 vp->stats.last_salvage_req = FT_ApproxTime();
5199 if (VCanUseSALVSYNC()) {
5200 /* don't record these stats for non-fileservers; let the
5201 * fileserver take care of these */
5202 vp->stats.salvages++;
5203 IncUInt64(&VStats.salvages);
5208 case SYNC_BAD_COMMAND:
5209 case SYNC_COM_ERROR:
5212 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5213 "denied\n", afs_printable_uint32_lu(vp->hashid));
5216 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5217 "received unknown protocol error %d\n",
5218 afs_printable_uint32_lu(vp->hashid), code);
5222 if (VCanUseFSSYNC()) {
5223 VChangeState_r(vp, VOL_STATE_ERROR);
5229 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5231 #ifdef SALVSYNC_BUILD_CLIENT
5234 * connect to the salvageserver SYNC service.
5236 * @return operation status
5240 * @post connection to salvageserver SYNC service established
5242 * @see VConnectSALV_r
5243 * @see VDisconnectSALV
5244 * @see VReconnectSALV
5251 retVal = VConnectSALV_r();
5257 * connect to the salvageserver SYNC service.
5259 * @return operation status
5263 * @pre VOL_LOCK is held.
5265 * @post connection to salvageserver SYNC service established
5268 * @see VDisconnectSALV_r
5269 * @see VReconnectSALV_r
5270 * @see SALVSYNC_clientInit
5272 * @internal volume package internal use only.
5275 VConnectSALV_r(void)
5277 return SALVSYNC_clientInit();
5281 * disconnect from the salvageserver SYNC service.
5283 * @return operation status
5286 * @pre client should have a live connection to the salvageserver
5288 * @post connection to salvageserver SYNC service destroyed
5290 * @see VDisconnectSALV_r
5292 * @see VReconnectSALV
5295 VDisconnectSALV(void)
5298 VDisconnectSALV_r();
5304 * disconnect from the salvageserver SYNC service.
5306 * @return operation status
5310 * @arg VOL_LOCK is held.
5311 * @arg client should have a live connection to the salvageserver.
5313 * @post connection to salvageserver SYNC service destroyed
5315 * @see VDisconnectSALV
5316 * @see VConnectSALV_r
5317 * @see VReconnectSALV_r
5318 * @see SALVSYNC_clientFinis
5320 * @internal volume package internal use only.
5323 VDisconnectSALV_r(void)
5325 return SALVSYNC_clientFinis();
5329 * disconnect and then re-connect to the salvageserver SYNC service.
5331 * @return operation status
5335 * @pre client should have a live connection to the salvageserver
5337 * @post old connection is dropped, and a new one is established
5340 * @see VDisconnectSALV
5341 * @see VReconnectSALV_r
5344 VReconnectSALV(void)
5348 retVal = VReconnectSALV_r();
5354 * disconnect and then re-connect to the salvageserver SYNC service.
5356 * @return operation status
5361 * @arg VOL_LOCK is held.
5362 * @arg client should have a live connection to the salvageserver.
5364 * @post old connection is dropped, and a new one is established
5366 * @see VConnectSALV_r
5367 * @see VDisconnectSALV
5368 * @see VReconnectSALV
5369 * @see SALVSYNC_clientReconnect
5371 * @internal volume package internal use only.
5374 VReconnectSALV_r(void)
5376 return SALVSYNC_clientReconnect();
5378 #endif /* SALVSYNC_BUILD_CLIENT */
5379 #endif /* AFS_DEMAND_ATTACH_FS */
5382 /***************************************************/
5383 /* FSSYNC routines */
5384 /***************************************************/
5386 /* This must be called by any volume utility which needs to run while the
5387 file server is also running. This is separated from VInitVolumePackage2 so
5388 that a utility can fork--and each of the children can independently
5389 initialize communication with the file server */
5390 #ifdef FSSYNC_BUILD_CLIENT
5392 * connect to the fileserver SYNC service.
5394 * @return operation status
5399 * @arg VInit must equal 2.
5400 * @arg Program Type must not be fileserver or salvager.
5402 * @post connection to fileserver SYNC service established
5405 * @see VDisconnectFS
5406 * @see VChildProcReconnectFS
5413 retVal = VConnectFS_r();
5419 * connect to the fileserver SYNC service.
5421 * @return operation status
5426 * @arg VInit must equal 2.
5427 * @arg Program Type must not be fileserver or salvager.
5428 * @arg VOL_LOCK is held.
5430 * @post connection to fileserver SYNC service established
5433 * @see VDisconnectFS_r
5434 * @see VChildProcReconnectFS_r
5436 * @internal volume package internal use only.
5442 osi_Assert((VInit == 2) &&
5443 (programType != fileServer) &&
5444 (programType != salvager));
5445 rc = FSYNC_clientInit();
5453 * disconnect from the fileserver SYNC service.
5456 * @arg client should have a live connection to the fileserver.
5457 * @arg VOL_LOCK is held.
5458 * @arg Program Type must not be fileserver or salvager.
5460 * @post connection to fileserver SYNC service destroyed
5462 * @see VDisconnectFS
5464 * @see VChildProcReconnectFS_r
5466 * @internal volume package internal use only.
5469 VDisconnectFS_r(void)
5471 osi_Assert((programType != fileServer) &&
5472 (programType != salvager));
5473 FSYNC_clientFinis();
5478 * disconnect from the fileserver SYNC service.
5481 * @arg client should have a live connection to the fileserver.
5482 * @arg Program Type must not be fileserver or salvager.
5484 * @post connection to fileserver SYNC service destroyed
5486 * @see VDisconnectFS_r
5488 * @see VChildProcReconnectFS
5499 * connect to the fileserver SYNC service from a child process following a fork.
5501 * @return operation status
5506 * @arg VOL_LOCK is held.
5507 * @arg current FSYNC handle is shared with a parent process
5509 * @post current FSYNC handle is discarded and a new connection to the
5510 * fileserver SYNC service is established
5512 * @see VChildProcReconnectFS
5514 * @see VDisconnectFS_r
5516 * @internal volume package internal use only.
5519 VChildProcReconnectFS_r(void)
5521 return FSYNC_clientChildProcReconnect();
5525 * connect to the fileserver SYNC service from a child process following a fork.
5527 * @return operation status
5531 * @pre current FSYNC handle is shared with a parent process
5533 * @post current FSYNC handle is discarded and a new connection to the
5534 * fileserver SYNC service is established
5536 * @see VChildProcReconnectFS_r
5538 * @see VDisconnectFS
5541 VChildProcReconnectFS(void)
5545 ret = VChildProcReconnectFS_r();
5549 #endif /* FSSYNC_BUILD_CLIENT */
5552 /***************************************************/
5553 /* volume bitmap routines */
5554 /***************************************************/
5557 * allocate a vnode bitmap number for the vnode
5559 * @param[out] ec error code
5560 * @param[in] vp volume object pointer
5561 * @param[in] index vnode index number for the vnode
5562 * @param[in] flags flag values described in note
5564 * @note for DAFS, flags parameter controls locking behavior.
5565 * If (flags & VOL_ALLOC_BITMAP_WAIT) is set, then this function
5566 * will create a reservation and block on any other exclusive
5567 * operations. Otherwise, this function assumes the caller
5568 * already has exclusive access to vp, and we just change the
5571 * @pre VOL_LOCK held
5573 * @return bit number allocated
5579 VAllocBitmapEntry_r(Error * ec, Volume * vp,
5580 struct vnodeIndex *index, int flags)
5584 #ifdef AFS_DEMAND_ATTACH_FS
5585 VolState state_save;
5586 #endif /* AFS_DEMAND_ATTACH_FS */
5590 /* This test is probably redundant */
5591 if (!VolumeWriteable(vp)) {
5592 *ec = (bit32) VREADONLY;
5596 #ifdef AFS_DEMAND_ATTACH_FS
5597 if (flags & VOL_ALLOC_BITMAP_WAIT) {
5598 VCreateReservation_r(vp);
5599 VWaitExclusiveState_r(vp);
5601 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
5602 #endif /* AFS_DEMAND_ATTACH_FS */
5605 if ((programType == fileServer) && !index->bitmap) {
5607 #ifndef AFS_DEMAND_ATTACH_FS
5608 /* demand attach fs uses the volume state to avoid races.
5609 * specialStatus field is not used at all */
5611 if (vp->specialStatus == VBUSY) {
5612 if (vp->goingOffline) { /* vos dump waiting for the volume to
5613 * go offline. We probably come here
5614 * from AddNewReadableResidency */
5617 while (vp->specialStatus == VBUSY) {
5618 #ifdef AFS_PTHREAD_ENV
5622 #else /* !AFS_PTHREAD_ENV */
5624 #endif /* !AFS_PTHREAD_ENV */
5628 #endif /* !AFS_DEMAND_ATTACH_FS */
5630 if (!index->bitmap) {
5631 #ifndef AFS_DEMAND_ATTACH_FS
5632 vp->specialStatus = VBUSY; /* Stop anyone else from using it. */
5633 #endif /* AFS_DEMAND_ATTACH_FS */
5634 for (i = 0; i < nVNODECLASSES; i++) {
5635 VGetBitmap_r(ec, vp, i);
5637 #ifdef AFS_DEMAND_ATTACH_FS
5638 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
5639 #else /* AFS_DEMAND_ATTACH_FS */
5640 DeleteVolumeFromHashTable(vp);
5641 vp->shuttingDown = 1; /* Let who has it free it. */
5642 vp->specialStatus = 0;
5643 #endif /* AFS_DEMAND_ATTACH_FS */
5647 #ifndef AFS_DEMAND_ATTACH_FS
5649 vp->specialStatus = 0; /* Allow others to have access. */
5650 #endif /* AFS_DEMAND_ATTACH_FS */
5653 #endif /* BITMAP_LATER */
5655 #ifdef AFS_DEMAND_ATTACH_FS
5657 #endif /* AFS_DEMAND_ATTACH_FS */
5658 bp = index->bitmap + index->bitmapOffset;
5659 ep = index->bitmap + index->bitmapSize;
5661 if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
5663 index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
5666 o = ffs(~*bp) - 1; /* ffs is documented in BSTRING(3) */
5668 ret = ((bp - index->bitmap) * 8 + o);
5669 #ifdef AFS_DEMAND_ATTACH_FS
5671 #endif /* AFS_DEMAND_ATTACH_FS */
5674 bp += sizeof(bit32) /* i.e. 4 */ ;
5676 /* No bit map entry--must grow bitmap */
5678 realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
5679 osi_Assert(bp != NULL);
5681 bp += index->bitmapSize;
5682 memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
5683 index->bitmapOffset = index->bitmapSize;
5684 index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
5686 ret = index->bitmapOffset * 8;
5687 #ifdef AFS_DEMAND_ATTACH_FS
5689 #endif /* AFS_DEMAND_ATTACH_FS */
5692 #ifdef AFS_DEMAND_ATTACH_FS
5693 VChangeState_r(vp, state_save);
5694 if (flags & VOL_ALLOC_BITMAP_WAIT) {
5695 VCancelReservation_r(vp);
5697 #endif /* AFS_DEMAND_ATTACH_FS */
5702 VAllocBitmapEntry(Error * ec, Volume * vp, struct vnodeIndex * index)
5706 retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
5712 VFreeBitMapEntry_r(Error * ec, struct vnodeIndex *index,
5715 unsigned int offset;
5721 #endif /* BITMAP_LATER */
5722 offset = bitNumber >> 3;
5723 if (offset >= index->bitmapSize) {
5727 if (offset < index->bitmapOffset)
5728 index->bitmapOffset = offset & ~3; /* Truncate to nearest bit32 */
5729 *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
5733 VFreeBitMapEntry(Error * ec, struct vnodeIndex *index,
5737 VFreeBitMapEntry_r(ec, index, bitNumber);
5741 /* this function will drop the glock internally.
5742 * for old pthread fileservers, this is safe thanks to vbusy.
5744 * for demand attach fs, caller must have already called
5745 * VCreateReservation_r and VWaitExclusiveState_r */
5747 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
5749 StreamHandle_t *file;
5750 afs_sfsize_t nVnodes, size;
5751 struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
5752 struct vnodeIndex *vip = &vp->vnodeIndex[class];
5753 struct VnodeDiskObject *vnode;
5754 unsigned int unique = 0;
5758 #endif /* BITMAP_LATER */
5759 #ifdef AFS_DEMAND_ATTACH_FS
5760 VolState state_save;
5761 #endif /* AFS_DEMAND_ATTACH_FS */
5765 #ifdef AFS_DEMAND_ATTACH_FS
5766 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
5767 #endif /* AFS_DEMAND_ATTACH_FS */
5770 fdP = IH_OPEN(vip->handle);
5771 osi_Assert(fdP != NULL);
5772 file = FDH_FDOPEN(fdP, "r");
5773 osi_Assert(file != NULL);
5774 vnode = (VnodeDiskObject *) malloc(vcp->diskSize);
5775 osi_Assert(vnode != NULL);
5776 size = OS_SIZE(fdP->fd_fd);
5777 osi_Assert(size != -1);
5778 nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
5780 vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4; /* The 10 is a little extra so
5781 * a few files can be created in this volume,
5782 * the whole thing is rounded up to nearest 4
5783 * bytes, because the bit map allocator likes
5786 BitMap = (byte *) calloc(1, vip->bitmapSize);
5787 osi_Assert(BitMap != NULL);
5788 #else /* BITMAP_LATER */
5789 vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
5790 osi_Assert(vip->bitmap != NULL);
5791 vip->bitmapOffset = 0;
5792 #endif /* BITMAP_LATER */
5793 if (STREAM_ASEEK(file, vcp->diskSize) != -1) {
5795 for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
5796 if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
5798 if (vnode->type != vNull) {
5799 if (vnode->vnodeMagic != vcp->magic) {
5800 Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
5805 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
5806 #else /* BITMAP_LATER */
5807 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
5808 #endif /* BITMAP_LATER */
5809 if (unique <= vnode->uniquifier)
5810 unique = vnode->uniquifier + 1;
5812 #ifndef AFS_PTHREAD_ENV
5813 if ((bitNumber & 0x00ff) == 0x0ff) { /* every 256 iterations */
5816 #endif /* !AFS_PTHREAD_ENV */
5819 if (vp->nextVnodeUnique < unique) {
5820 Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
5823 /* Paranoia, partly justified--I think fclose after fdopen
5824 * doesn't seem to close fd. In any event, the documentation
5825 * doesn't specify, so it's safer to close it twice.
5833 /* There may have been a racing condition with some other thread, both
5834 * creating the bitmaps for this volume. If the other thread was faster
5835 * the pointer to bitmap should already be filled and we can free ours.
5837 if (vip->bitmap == NULL) {
5838 vip->bitmap = BitMap;
5839 vip->bitmapOffset = 0;
5841 free((byte *) BitMap);
5842 #endif /* BITMAP_LATER */
5843 #ifdef AFS_DEMAND_ATTACH_FS
5844 VChangeState_r(vp, state_save);
5845 #endif /* AFS_DEMAND_ATTACH_FS */
5849 /***************************************************/
5850 /* Volume Path and Volume Number utility routines */
5851 /***************************************************/
5854 * find the first occurrence of a volume header file and return the path.
5856 * @param[out] ec outbound error code
5857 * @param[in] volumeId volume id to find
5858 * @param[out] partitionp pointer to disk partition path string
5859 * @param[out] namep pointer to volume header file name string
5861 * @post path to first occurrence of volume header is returned in partitionp
5862 * and namep, or ec is set accordingly.
5864 * @warning this function is NOT re-entrant -- partitionp and namep point to
5865 * static data segments
5867 * @note if a volume utility inadvertently leaves behind a stale volume header
5868 * on a vice partition, it is possible for callers to get the wrong one,
5869 * depending on the order of the disk partition linked list.
5873 VGetVolumePath(Error * ec, VolId volumeId, char **partitionp, char **namep)
5875 static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
5876 char path[VMAXPATHLEN];
5878 struct DiskPartition64 *dp;
5882 (void)afs_snprintf(&name[1], (sizeof name) - 1, VFORMAT, afs_printable_uint32_lu(volumeId));
5883 for (dp = DiskPartitionList; dp; dp = dp->next) {
5884 struct afs_stat status;
5885 strcpy(path, VPartitionPath(dp));
5887 if (afs_stat(path, &status) == 0) {
5888 strcpy(partition, dp->name);
5895 *partitionp = *namep = NULL;
5897 *partitionp = partition;
5903 * extract a volume number from a volume header filename string.
5905 * @param[in] name volume header filename string
5907 * @return volume number
5909 * @note the string must be of the form VFORMAT. the only permissible
5910 * deviation is a leading '/' character.
5915 VolumeNumber(char *name)
5919 return atoi(name + 1);
5923 * compute the volume header filename.
5925 * @param[in] volumeId
5927 * @return volume header filename
5929 * @post volume header filename string is constructed
5931 * @warning this function is NOT re-entrant -- the returned string is
5932 * stored in a static char array. see VolumeExternalName_r
5933 * for a re-entrant equivalent.
5935 * @see VolumeExternalName_r
5937 * @deprecated due to the above re-entrancy warning, this interface should
5938 * be considered deprecated. Please use VolumeExternalName_r
5942 VolumeExternalName(VolumeId volumeId)
5944 static char name[VMAXPATHLEN];
5945 (void)afs_snprintf(name, sizeof name, VFORMAT, afs_printable_uint32_lu(volumeId));
5950 * compute the volume header filename.
5952 * @param[in] volumeId
5953 * @param[inout] name array in which to store filename
5954 * @param[in] len length of name array
5956 * @return result code from afs_snprintf
5958 * @see VolumeExternalName
5961 * @note re-entrant equivalent of VolumeExternalName
5964 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
5966 return afs_snprintf(name, len, VFORMAT, afs_printable_uint32_lu(volumeId));
5970 /***************************************************/
5971 /* Volume Usage Statistics routines */
5972 /***************************************************/
5974 #if OPENAFS_VOL_STATS
5975 #define OneDay (86400) /* 24 hours' worth of seconds */
5977 #define OneDay (24*60*60) /* 24 hours */
5978 #endif /* OPENAFS_VOL_STATS */
5981 Midnight(time_t t) {
5982 struct tm local, *l;
5985 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
5986 l = localtime_r(&t, &local);
5992 /* the following is strictly speaking problematic on the
5993 switching day to daylight saving time, after the switch,
5994 as tm_isdst does not match. Similarly, on the looong day when
5995 switching back the OneDay check will not do what naively expected!
5996 The effects are minor, though, and more a matter of interpreting
5998 #ifndef AFS_PTHREAD_ENV
6001 local.tm_hour = local.tm_min=local.tm_sec = 0;
6002 midnight = mktime(&local);
6003 if (midnight != (time_t) -1) return(midnight);
6005 return( (t/OneDay)*OneDay );
6009 /*------------------------------------------------------------------------
6010 * [export] VAdjustVolumeStatistics
6013 * If we've passed midnight, we need to update all the day use
6014 * statistics as well as zeroing the detailed volume statistics
6015 * (if we are implementing them).
6018 * vp : Pointer to the volume structure describing the lucky
6019 * volume being considered for update.
6025 * Nothing interesting.
6029 *------------------------------------------------------------------------*/
6032 VAdjustVolumeStatistics_r(Volume * vp)
6034 unsigned int now = FT_ApproxTime();
6036 if (now - V_dayUseDate(vp) > OneDay) {
6039 ndays = (now - V_dayUseDate(vp)) / OneDay;
6040 for (i = 6; i > ndays - 1; i--)
6041 V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
6042 for (i = 0; i < ndays - 1 && i < 7; i++)
6043 V_weekUse(vp)[i] = 0;
6045 V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
6047 V_dayUseDate(vp) = Midnight(now);
6049 #if OPENAFS_VOL_STATS
6051 * All we need to do is bzero the entire VOL_STATS_BYTES of
6052 * the detailed volume statistics area.
6054 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
6055 #endif /* OPENAFS_VOL_STATS */
6058 /*It's been more than a day of collection */
6060 * Always return happily.
6063 } /*VAdjustVolumeStatistics */
6066 VAdjustVolumeStatistics(Volume * vp)
6070 retVal = VAdjustVolumeStatistics_r(vp);
6076 VBumpVolumeUsage_r(Volume * vp)
6078 unsigned int now = FT_ApproxTime();
6079 V_accessDate(vp) = now;
6080 if (now - V_dayUseDate(vp) > OneDay)
6081 VAdjustVolumeStatistics_r(vp);
6083 * Save the volume header image to disk after every 128 bumps to dayUse.
6085 if ((V_dayUse(vp)++ & 127) == 0) {
6087 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
6092 VBumpVolumeUsage(Volume * vp)
6095 VBumpVolumeUsage_r(vp);
6100 VSetDiskUsage_r(void)
6102 #ifndef AFS_DEMAND_ATTACH_FS
6103 static int FifteenMinuteCounter = 0;
6107 /* NOTE: Don't attempt to access the partitions list until the
6108 * initialization level indicates that all volumes are attached,
6109 * which implies that all partitions are initialized. */
6110 #ifdef AFS_PTHREAD_ENV
6111 VOL_CV_WAIT(&vol_vinit_cond);
6112 #else /* AFS_PTHREAD_ENV */
6114 #endif /* AFS_PTHREAD_ENV */
6117 VResetDiskUsage_r();
6119 #ifndef AFS_DEMAND_ATTACH_FS
6120 if (++FifteenMinuteCounter == 3) {
6121 FifteenMinuteCounter = 0;
6124 #endif /* !AFS_DEMAND_ATTACH_FS */
6136 /***************************************************/
6137 /* Volume Update List routines */
6138 /***************************************************/
6140 /* The number of minutes that a volume hasn't been updated before the
6141 * "Dont salvage" flag in the volume header will be turned on */
6142 #define SALVAGE_INTERVAL (10*60)
6147 * volume update list functionality has been moved into the VLRU
6148 * the DONT_SALVAGE flag is now set during VLRU demotion
6151 #ifndef AFS_DEMAND_ATTACH_FS
6152 static VolumeId *UpdateList = NULL; /* Pointer to array of Volume ID's */
6153 static int nUpdatedVolumes = 0; /* Updated with entry in UpdateList, salvage after crash flag on */
6154 static int updateSize = 0; /* number of entries possible */
6155 #define UPDATE_LIST_SIZE 128 /* initial size increment (must be a power of 2!) */
6156 #endif /* !AFS_DEMAND_ATTACH_FS */
6159 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
6162 vp->updateTime = FT_ApproxTime();
6163 if (V_dontSalvage(vp) == 0)
6165 V_dontSalvage(vp) = 0;
6166 VSyncVolume_r(ec, vp, 0);
6167 #ifdef AFS_DEMAND_ATTACH_FS
6168 V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
6169 #else /* !AFS_DEMAND_ATTACH_FS */
6172 if (UpdateList == NULL) {
6173 updateSize = UPDATE_LIST_SIZE;
6174 UpdateList = (VolumeId *) malloc(sizeof(VolumeId) * updateSize);
6176 if (nUpdatedVolumes == updateSize) {
6178 if (updateSize > 524288) {
6179 Log("warning: there is likely a bug in the volume update scanner\n");
6183 (VolumeId *) realloc(UpdateList,
6184 sizeof(VolumeId) * updateSize);
6187 osi_Assert(UpdateList != NULL);
6188 UpdateList[nUpdatedVolumes++] = V_id(vp);
6189 #endif /* !AFS_DEMAND_ATTACH_FS */
6192 #ifndef AFS_DEMAND_ATTACH_FS
6194 VScanUpdateList(void)
6199 afs_uint32 now = FT_ApproxTime();
6200 /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
6201 for (i = gap = 0; i < nUpdatedVolumes; i++) {
6203 UpdateList[i - gap] = UpdateList[i];
6205 /* XXX this routine needlessly messes up the Volume LRU by
6206 * breaking the LRU temporal-locality assumptions.....
6207 * we should use a special volume header allocator here */
6208 vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
6211 } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
6212 V_dontSalvage(vp) = DONT_SALVAGE;
6213 VUpdateVolume_r(&error, vp, 0); /* No need to fsync--not critical */
6221 #ifndef AFS_PTHREAD_ENV
6223 #endif /* !AFS_PTHREAD_ENV */
6225 nUpdatedVolumes -= gap;
6227 #endif /* !AFS_DEMAND_ATTACH_FS */
6230 /***************************************************/
6231 /* Volume LRU routines */
6232 /***************************************************/
6237 * with demand attach fs, we attempt to soft detach(1)
6238 * volumes which have not been accessed in a long time
6239 * in order to speed up fileserver shutdown
6241 * (1) by soft detach we mean a process very similar
6242 * to VOffline, except the final state of the
6243 * Volume will be VOL_STATE_PREATTACHED, instead
6244 * of the usual VOL_STATE_UNATTACHED
6246 #ifdef AFS_DEMAND_ATTACH_FS
6248 /* implementation is reminiscent of a generational GC
6250 * queue 0 is newly attached volumes. this queue is
6251 * sorted by attach timestamp
6253 * queue 1 is volumes that have been around a bit
6254 * longer than queue 0. this queue is sorted by
6257 * queue 2 is volumes tha have been around the longest.
6258 * this queue is unsorted
6260 * queue 3 is volumes that have been marked as
6261 * candidates for soft detachment. this queue is
6264 #define VLRU_GENERATIONS 3 /**< number of generations in VLRU */
6265 #define VLRU_QUEUES 5 /**< total number of VLRU queues */
6268 * definition of a VLRU queue.
6271 volatile struct rx_queue q;
6278 * main VLRU data structure.
6281 struct VLRU_q q[VLRU_QUEUES]; /**< VLRU queues */
6284 /** time interval (in seconds) between promotion passes for
6285 * each young generation queue. */
6286 afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
6288 /** time interval (in seconds) between soft detach candidate
6289 * scans for each generation queue.
6291 * scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
6292 * we perform a soft detach pass. */
6293 afs_uint32 scan_interval[VLRU_GENERATIONS+1];
6295 /* scheduler state */
6296 int next_idx; /**< next queue to receive attention */
6297 afs_uint32 last_promotion[VLRU_GENERATIONS-1]; /**< timestamp of last promotion scan */
6298 afs_uint32 last_scan[VLRU_GENERATIONS+1]; /**< timestamp of last detach scan */
6300 int scanner_state; /**< state of scanner thread */
6301 pthread_cond_t cv; /**< state transition CV */
6304 /** global VLRU state */
6305 static struct VLRU volume_LRU;
6308 * defined states for VLRU scanner thread.
6311 VLRU_SCANNER_STATE_OFFLINE = 0, /**< vlru scanner thread is offline */
6312 VLRU_SCANNER_STATE_ONLINE = 1, /**< vlru scanner thread is online */
6313 VLRU_SCANNER_STATE_SHUTTING_DOWN = 2, /**< vlru scanner thread is shutting down */
6314 VLRU_SCANNER_STATE_PAUSING = 3, /**< vlru scanner thread is getting ready to pause */
6315 VLRU_SCANNER_STATE_PAUSED = 4 /**< vlru scanner thread is paused */
6316 } vlru_thread_state_t;
6318 /* vlru disk data header stuff */
6319 #define VLRU_DISK_MAGIC 0x7a8b9cad /**< vlru disk entry magic number */
6320 #define VLRU_DISK_VERSION 1 /**< vlru disk entry version number */
6322 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
6323 #define VLRU_DUMP_EXPIRATION_TIME (60*60*24*7) /* expire vlru data after 1 week */
6326 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
6327 * soft detachment. */
6328 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
6330 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
6331 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
6333 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
6334 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
6336 /** VLRU control flag. non-zero value implies VLRU subsystem is activated. */
6337 static afs_uint32 VLRU_enabled = 1;
6339 /* queue synchronization routines */
6340 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
6341 static void VLRU_EndExclusive_r(struct VLRU_q * q);
6342 static void VLRU_Wait_r(struct VLRU_q * q);
6345 * set VLRU subsystem tunable parameters.
6347 * @param[in] option tunable option to modify
6348 * @param[in] val new value for tunable parameter
6350 * @pre @c VInitVolumePackage2 has not yet been called.
6352 * @post tunable parameter is modified
6356 * @note valid option parameters are:
6357 * @arg @c VLRU_SET_THRESH
6358 * set the period of inactivity after which
6359 * volumes are eligible for soft detachment
6360 * @arg @c VLRU_SET_INTERVAL
6361 * set the time interval between calls
6362 * to the volume LRU "garbage collector"
6363 * @arg @c VLRU_SET_MAX
6364 * set the max number of volumes to deallocate
6368 VLRU_SetOptions(int option, afs_uint32 val)
6370 if (option == VLRU_SET_THRESH) {
6371 VLRU_offline_thresh = val;
6372 } else if (option == VLRU_SET_INTERVAL) {
6373 VLRU_offline_interval = val;
6374 } else if (option == VLRU_SET_MAX) {
6375 VLRU_offline_max = val;
6376 } else if (option == VLRU_SET_ENABLED) {
6379 VLRU_ComputeConstants();
6383 * compute VLRU internal timing parameters.
6385 * @post VLRU scanner thread internal timing parameters are computed
6387 * @note computes internal timing parameters based upon user-modifiable
6388 * tunable parameters.
6392 * @internal volume package internal use only.
6395 VLRU_ComputeConstants(void)
6397 afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
6399 /* compute the candidate scan interval */
6400 volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
6402 /* compute the promotion intervals */
6403 volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
6404 volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
6407 /* compute the gen 0 scan interval */
6408 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
6410 /* compute the gen 0 scan interval */
6411 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
6416 * initialize VLRU subsystem.
6418 * @pre this function has not yet been called
6420 * @post VLRU subsystem is initialized and VLRU scanner thread is starting
6424 * @internal volume package internal use only.
6430 pthread_attr_t attrs;
6433 if (!VLRU_enabled) {
6434 Log("VLRU: disabled\n");
6438 /* initialize each of the VLRU queues */
6439 for (i = 0; i < VLRU_QUEUES; i++) {
6440 queue_Init(&volume_LRU.q[i]);
6441 volume_LRU.q[i].len = 0;
6442 volume_LRU.q[i].busy = 0;
6443 CV_INIT(&volume_LRU.q[i].cv, "vol lru", CV_DEFAULT, 0);
6446 /* setup the timing constants */
6447 VLRU_ComputeConstants();
6449 /* XXX put inside LogLevel check? */
6450 Log("VLRU: starting scanner with the following configuration parameters:\n");
6451 Log("VLRU: offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
6452 Log("VLRU: running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
6453 Log("VLRU: taking up to %d volumes offline per pass\n", VLRU_offline_max);
6454 Log("VLRU: scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
6455 Log("VLRU: scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
6456 Log("VLRU: scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
6458 /* start up the VLRU scanner */
6459 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
6460 if (programType == fileServer) {
6461 CV_INIT(&volume_LRU.cv, "vol lru", CV_DEFAULT, 0);
6462 osi_Assert(pthread_attr_init(&attrs) == 0);
6463 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
6464 osi_Assert(pthread_create(&tid, &attrs, &VLRU_ScannerThread, NULL) == 0);
6469 * initialize the VLRU-related fields of a newly allocated volume object.
6471 * @param[in] vp pointer to volume object
6474 * @arg @c VOL_LOCK is held.
6475 * @arg volume object is not on a VLRU queue.
6477 * @post VLRU fields are initialized to indicate that volume object is not
6478 * currently registered with the VLRU subsystem
6482 * @internal volume package interal use only.
6485 VLRU_Init_Node_r(Volume * vp)
6490 osi_Assert(queue_IsNotOnQueue(&vp->vlru));
6491 vp->vlru.idx = VLRU_QUEUE_INVALID;
6495 * add a volume object to a VLRU queue.
6497 * @param[in] vp pointer to volume object
6500 * @arg @c VOL_LOCK is held.
6501 * @arg caller MUST hold a lightweight ref on @p vp.
6502 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
6504 * @post the volume object is added to the appropriate VLRU queue
6506 * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
6507 * then the volume is added to that queue. Otherwise, the value
6508 * @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
6509 * volume is added to the NEW generation queue.
6511 * @note @c VOL_LOCK may be dropped internally
6513 * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
6514 * during the add operation, and is restored to the previous
6515 * state prior to return.
6519 * @internal volume package internal use only.
6522 VLRU_Add_r(Volume * vp)
6525 VolState state_save;
6530 if (queue_IsOnQueue(&vp->vlru))
6533 state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
6536 if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
6537 idx = VLRU_QUEUE_NEW;
6540 VLRU_Wait_r(&volume_LRU.q[idx]);
6542 /* repeat check since VLRU_Wait_r may have dropped
6544 if (queue_IsNotOnQueue(&vp->vlru)) {
6546 queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
6547 volume_LRU.q[idx].len++;
6548 V_attachFlags(vp) |= VOL_ON_VLRU;
6549 vp->stats.last_promote = FT_ApproxTime();
6552 VChangeState_r(vp, state_save);
6556 * delete a volume object from a VLRU queue.
6558 * @param[in] vp pointer to volume object
6561 * @arg @c VOL_LOCK is held.
6562 * @arg caller MUST hold a lightweight ref on @p vp.
6563 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
6565 * @post volume object is removed from the VLRU queue
6567 * @note @c VOL_LOCK may be dropped internally
6571 * @todo We should probably set volume state to something exlcusive
6572 * (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
6574 * @internal volume package internal use only.
6577 VLRU_Delete_r(Volume * vp)
6584 if (queue_IsNotOnQueue(&vp->vlru))
6590 if (idx == VLRU_QUEUE_INVALID)
6592 VLRU_Wait_r(&volume_LRU.q[idx]);
6593 } while (idx != vp->vlru.idx);
6595 /* now remove from the VLRU and update
6596 * the appropriate counter */
6597 queue_Remove(&vp->vlru);
6598 volume_LRU.q[idx].len--;
6599 vp->vlru.idx = VLRU_QUEUE_INVALID;
6600 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
6604 * tell the VLRU subsystem that a volume was just accessed.
6606 * @param[in] vp pointer to volume object
6609 * @arg @c VOL_LOCK is held
6610 * @arg caller MUST hold a lightweight ref on @p vp
6611 * @arg caller MUST NOT hold exclusive ownership of any VLRU queue
6613 * @post volume VLRU access statistics are updated. If the volume was on
6614 * the VLRU soft detach candidate queue, it is moved to the NEW
6617 * @note @c VOL_LOCK may be dropped internally
6621 * @internal volume package internal use only.
6624 VLRU_UpdateAccess_r(Volume * vp)
6626 Volume * rvp = NULL;
6631 if (queue_IsNotOnQueue(&vp->vlru))
6634 osi_Assert(V_attachFlags(vp) & VOL_ON_VLRU);
6636 /* update the access timestamp */
6637 vp->stats.last_get = FT_ApproxTime();
6640 * if the volume is on the soft detach candidate
6641 * list, we need to safely move it back to a
6642 * regular generation. this has to be done
6643 * carefully so we don't race against the scanner
6647 /* if this volume is on the soft detach candidate queue,
6648 * then grab exclusive access to the necessary queues */
6649 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
6651 VCreateReservation_r(rvp);
6653 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
6654 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
6655 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6656 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6659 /* make sure multiple threads don't race to update */
6660 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
6661 VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
6665 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6666 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
6667 VCancelReservation_r(rvp);
6672 * switch a volume between two VLRU queues.
6674 * @param[in] vp pointer to volume object
6675 * @param[in] new_idx index of VLRU queue onto which the volume will be moved
6676 * @param[in] append controls whether the volume will be appended or
6677 * prepended to the queue. A nonzero value means it will
6678 * be appended; zero means it will be prepended.
6680 * @pre The new (and old, if applicable) queue(s) must either be owned
6681 * exclusively by the calling thread for asynchronous manipulation,
6682 * or the queue(s) must be quiescent and VOL_LOCK must be held.
6683 * Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
6684 * for further details of the queue asynchronous processing mechanism.
6686 * @post If the volume object was already on a VLRU queue, it is
6687 * removed from the queue. Depending on the value of the append
6688 * parameter, the volume object is either appended or prepended
6689 * to the VLRU queue referenced by the new_idx parameter.
6693 * @see VLRU_BeginExclusive_r
6694 * @see VLRU_EndExclusive_r
6697 * @internal volume package internal use only.
6700 VLRU_SwitchQueues(Volume * vp, int new_idx, int append)
6702 if (queue_IsNotOnQueue(&vp->vlru))
6705 queue_Remove(&vp->vlru);
6706 volume_LRU.q[vp->vlru.idx].len--;
6708 /* put the volume back on the correct generational queue */
6710 queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
6712 queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
6715 volume_LRU.q[new_idx].len++;
6716 vp->vlru.idx = new_idx;
6720 * VLRU background thread.
6722 * The VLRU Scanner Thread is responsible for periodically scanning through
6723 * each VLRU queue looking for volumes which should be moved to another
6724 * queue, or soft detached.
6726 * @param[in] args unused thread arguments parameter
6728 * @return unused thread return value
6729 * @retval NULL always
6731 * @internal volume package internal use only.
6734 VLRU_ScannerThread(void * args)
6736 afs_uint32 now, min_delay, delay;
6737 int i, min_idx, min_op, overdue, state;
6739 /* set t=0 for promotion cycle to be
6740 * fileserver startup */
6741 now = FT_ApproxTime();
6742 for (i=0; i < VLRU_GENERATIONS-1; i++) {
6743 volume_LRU.last_promotion[i] = now;
6746 /* don't start the scanner until VLRU_offline_thresh
6747 * plus a small delay for VInitVolumePackage2 to finish
6750 sleep(VLRU_offline_thresh + 60);
6752 /* set t=0 for scan cycle to be now */
6753 now = FT_ApproxTime();
6754 for (i=0; i < VLRU_GENERATIONS+1; i++) {
6755 volume_LRU.last_scan[i] = now;
6759 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
6760 volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
6763 while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
6764 /* check to see if we've been asked to pause */
6765 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
6766 volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
6767 CV_BROADCAST(&volume_LRU.cv);
6769 VOL_CV_WAIT(&volume_LRU.cv);
6770 } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
6773 /* scheduling can happen outside the glock */
6776 /* figure out what is next on the schedule */
6778 /* figure out a potential schedule for the new generation first */
6780 min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
6783 if (min_delay > volume_LRU.scan_interval[0]) {
6784 /* unsigned overflow -- we're overdue to run this scan */
6789 /* if we're not overdue for gen 0, figure out schedule for candidate gen */
6791 i = VLRU_QUEUE_CANDIDATE;
6792 delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
6793 if (delay < min_delay) {
6797 if (delay > volume_LRU.scan_interval[i]) {
6798 /* unsigned overflow -- we're overdue to run this scan */
6805 /* if we're still not overdue for something, figure out schedules for promotions */
6806 for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
6807 delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
6808 if (delay < min_delay) {
6813 if (delay > volume_LRU.promotion_interval[i]) {
6814 /* unsigned overflow -- we're overdue to run this promotion */
6823 /* sleep as needed */
6828 /* do whatever is next */
6831 VLRU_Promote_r(min_idx);
6832 VLRU_Demote_r(min_idx+1);
6834 VLRU_Scan_r(min_idx);
6836 now = FT_ApproxTime();
6839 Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
6841 /* signal that scanner is down */
6842 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
6843 CV_BROADCAST(&volume_LRU.cv);
6849 * promote volumes from one VLRU generation to the next.
6851 * This routine scans a VLRU generation looking for volumes which are
6852 * eligible to be promoted to the next generation. All volumes which
6853 * meet the eligibility requirement are promoted.
6855 * Promotion eligibility is based upon meeting both of the following
6858 * @arg The volume has been accessed since the last promotion:
6859 * @c (vp->stats.last_get >= vp->stats.last_promote)
6860 * @arg The last promotion occurred at least
6861 * @c volume_LRU.promotion_interval[idx] seconds ago
6863 * As a performance optimization, promotions are "globbed". In other
6864 * words, we promote arbitrarily large contiguous sublists of elements
6867 * @param[in] idx VLRU queue index to scan
6871 * @internal VLRU internal use only.
6874 VLRU_Promote_r(int idx)
6876 int len, chaining, promote;
6877 afs_uint32 now, thresh;
6878 struct rx_queue *qp, *nqp;
6879 Volume * vp, *start = NULL, *end = NULL;
6881 /* get exclusive access to two chains, and drop the glock */
6882 VLRU_Wait_r(&volume_LRU.q[idx]);
6883 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
6884 VLRU_Wait_r(&volume_LRU.q[idx+1]);
6885 VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
6888 thresh = volume_LRU.promotion_interval[idx];
6889 now = FT_ApproxTime();
6892 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
6893 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6894 promote = (((vp->stats.last_promote + thresh) <= now) &&
6895 (vp->stats.last_get >= vp->stats.last_promote));
6903 /* promote and prepend chain */
6904 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
6918 /* promote and prepend */
6919 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
6923 volume_LRU.q[idx].len -= len;
6924 volume_LRU.q[idx+1].len += len;
6927 /* release exclusive access to the two chains */
6929 volume_LRU.last_promotion[idx] = now;
6930 VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
6931 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
6934 /* run the demotions */
6936 VLRU_Demote_r(int idx)
6939 int len, chaining, demote;
6940 afs_uint32 now, thresh;
6941 struct rx_queue *qp, *nqp;
6942 Volume * vp, *start = NULL, *end = NULL;
6943 Volume ** salv_flag_vec = NULL;
6944 int salv_vec_offset = 0;
6946 osi_Assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
6948 /* get exclusive access to two chains, and drop the glock */
6949 VLRU_Wait_r(&volume_LRU.q[idx-1]);
6950 VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
6951 VLRU_Wait_r(&volume_LRU.q[idx]);
6952 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
6955 /* no big deal if this allocation fails */
6956 if (volume_LRU.q[idx].len) {
6957 salv_flag_vec = (Volume **) malloc(volume_LRU.q[idx].len * sizeof(Volume *));
6960 now = FT_ApproxTime();
6961 thresh = volume_LRU.promotion_interval[idx-1];
6964 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
6965 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6966 demote = (((vp->stats.last_promote + thresh) <= now) &&
6967 (vp->stats.last_get < (now - thresh)));
6969 /* we now do volume update list DONT_SALVAGE flag setting during
6970 * demotion passes */
6971 if (salv_flag_vec &&
6972 !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
6974 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
6975 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
6976 salv_flag_vec[salv_vec_offset++] = vp;
6977 VCreateReservation_r(vp);
6986 /* demote and append chain */
6987 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7001 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7005 volume_LRU.q[idx].len -= len;
7006 volume_LRU.q[idx-1].len += len;
7009 /* release exclusive access to the two chains */
7011 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7012 VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
7014 /* now go back and set the DONT_SALVAGE flags as appropriate */
7015 if (salv_flag_vec) {
7017 for (i = 0; i < salv_vec_offset; i++) {
7018 vp = salv_flag_vec[i];
7019 if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7020 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7021 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7024 V_attachFlags(vp) |= VOL_HDR_DONTSALV;
7025 V_dontSalvage(vp) = DONT_SALVAGE;
7026 VUpdateVolume_r(&ec, vp, 0);
7030 VCancelReservation_r(vp);
7032 free(salv_flag_vec);
7036 /* run a pass of the VLRU GC scanner */
7038 VLRU_Scan_r(int idx)
7040 afs_uint32 now, thresh;
7041 struct rx_queue *qp, *nqp;
7045 osi_Assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
7047 /* gain exclusive access to the idx VLRU */
7048 VLRU_Wait_r(&volume_LRU.q[idx]);
7049 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7051 if (idx != VLRU_QUEUE_CANDIDATE) {
7052 /* gain exclusive access to the candidate VLRU */
7053 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7054 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7057 now = FT_ApproxTime();
7058 thresh = now - VLRU_offline_thresh;
7060 /* perform candidate selection and soft detaching */
7061 if (idx == VLRU_QUEUE_CANDIDATE) {
7062 /* soft detach some volumes from the candidate pool */
7066 for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7067 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7068 if (i >= VLRU_offline_max) {
7071 /* check timestamp to see if it's a candidate for soft detaching */
7072 if (vp->stats.last_get <= thresh) {
7074 if (VCheckSoftDetach(vp, thresh))
7080 /* scan for volumes to become soft detach candidates */
7081 for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
7082 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7084 /* check timestamp to see if it's a candidate for soft detaching */
7085 if (vp->stats.last_get <= thresh) {
7086 VCheckSoftDetachCandidate(vp, thresh);
7089 if (!(i&0x7f)) { /* lock coarsening optimization */
7097 /* relinquish exclusive access to the VLRU chains */
7101 volume_LRU.last_scan[idx] = now;
7102 if (idx != VLRU_QUEUE_CANDIDATE) {
7103 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7105 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7108 /* check whether volume is safe to soft detach
7109 * caller MUST NOT hold a ref count on vp */
7111 VCheckSoftDetach(Volume * vp, afs_uint32 thresh)
7115 if (vp->nUsers || vp->nWaiters)
7118 if (vp->stats.last_get <= thresh) {
7119 ret = VSoftDetachVolume_r(vp, thresh);
7125 /* check whether volume should be made a
7126 * soft detach candidate */
7128 VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh)
7131 if (vp->nUsers || vp->nWaiters)
7136 osi_Assert(idx == VLRU_QUEUE_NEW);
7138 if (vp->stats.last_get <= thresh) {
7139 /* move to candidate pool */
7140 queue_Remove(&vp->vlru);
7141 volume_LRU.q[VLRU_QUEUE_NEW].len--;
7142 queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
7143 vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
7144 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
7152 /* begin exclusive access on VLRU */
7154 VLRU_BeginExclusive_r(struct VLRU_q * q)
7156 osi_Assert(q->busy == 0);
7160 /* end exclusive access on VLRU */
7162 VLRU_EndExclusive_r(struct VLRU_q * q)
7164 osi_Assert(q->busy);
7166 CV_BROADCAST(&q->cv);
7169 /* wait for another thread to end exclusive access on VLRU */
7171 VLRU_Wait_r(struct VLRU_q * q)
7174 VOL_CV_WAIT(&q->cv);
7179 * volume soft detach
7181 * caller MUST NOT hold a ref count on vp */
7183 VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh)
7188 osi_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7190 ts_save = vp->stats.last_get;
7191 if (ts_save > thresh)
7194 if (vp->nUsers || vp->nWaiters)
7197 if (VIsExclusiveState(V_attachState(vp))) {
7201 switch (V_attachState(vp)) {
7202 case VOL_STATE_UNATTACHED:
7203 case VOL_STATE_PREATTACHED:
7204 case VOL_STATE_ERROR:
7205 case VOL_STATE_GOING_OFFLINE:
7206 case VOL_STATE_SHUTTING_DOWN:
7207 case VOL_STATE_SALVAGING:
7208 case VOL_STATE_DELETED:
7209 volume_LRU.q[vp->vlru.idx].len--;
7211 /* create and cancel a reservation to
7212 * give the volume an opportunity to
7214 VCreateReservation_r(vp);
7215 queue_Remove(&vp->vlru);
7216 vp->vlru.idx = VLRU_QUEUE_INVALID;
7217 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7218 VCancelReservation_r(vp);
7224 /* hold the volume and take it offline.
7225 * no need for reservations, as VHold_r
7226 * takes care of that internally. */
7227 if (VHold_r(vp) == 0) {
7228 /* vhold drops the glock, so now we should
7229 * check to make sure we aren't racing against
7230 * other threads. if we are racing, offlining vp
7231 * would be wasteful, and block the scanner for a while
7235 (vp->shuttingDown) ||
7236 (vp->goingOffline) ||
7237 (vp->stats.last_get != ts_save)) {
7238 /* looks like we're racing someone else. bail */
7242 /* pull it off the VLRU */
7243 osi_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7244 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
7245 queue_Remove(&vp->vlru);
7246 vp->vlru.idx = VLRU_QUEUE_INVALID;
7247 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7249 /* take if offline */
7250 VOffline_r(vp, "volume has been soft detached");
7252 /* invalidate the volume header cache */
7253 FreeVolumeHeader(vp);
7256 IncUInt64(&VStats.soft_detaches);
7257 vp->stats.soft_detaches++;
7259 /* put in pre-attached state so demand
7260 * attacher can work on it */
7261 VChangeState_r(vp, VOL_STATE_PREATTACHED);
7267 #endif /* AFS_DEMAND_ATTACH_FS */
7270 /***************************************************/
7271 /* Volume Header Cache routines */
7272 /***************************************************/
7275 * volume header cache.
7277 struct volume_hdr_LRU_t volume_hdr_LRU;
7280 * initialize the volume header cache.
7282 * @param[in] howMany number of header cache entries to preallocate
7284 * @pre VOL_LOCK held. Function has never been called before.
7286 * @post howMany cache entries are allocated, initialized, and added
7287 * to the LRU list. Header cache statistics are initialized.
7289 * @note only applicable to fileServer program type. Should only be
7290 * called once during volume package initialization.
7292 * @internal volume package internal use only.
7295 VInitVolumeHeaderCache(afs_uint32 howMany)
7297 struct volHeader *hp;
7298 if (programType != fileServer)
7300 queue_Init(&volume_hdr_LRU);
7301 volume_hdr_LRU.stats.free = 0;
7302 volume_hdr_LRU.stats.used = howMany;
7303 volume_hdr_LRU.stats.attached = 0;
7304 hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
7305 osi_Assert(hp != NULL);
7308 /* We are using ReleaseVolumeHeader to initialize the values on the header list
7309 * to ensure they have the right values
7311 ReleaseVolumeHeader(hp++);
7315 * get a volume header and attach it to the volume object.
7317 * @param[in] vp pointer to volume object
7319 * @return cache entry status
7320 * @retval 0 volume header was newly attached; cache data is invalid
7321 * @retval 1 volume header was previously attached; cache data is valid
7323 * @pre VOL_LOCK held. For DAFS, lightweight ref must be held on volume object.
7325 * @post volume header attached to volume object. if necessary, header cache
7326 * entry on LRU is synchronized to disk. Header is removed from LRU list.
7328 * @note VOL_LOCK may be dropped
7330 * @warning this interface does not load header data from disk. it merely
7331 * attaches a header object to the volume object, and may sync the old
7332 * header cache data out to disk in the process.
7334 * @internal volume package internal use only.
7337 GetVolumeHeader(Volume * vp)
7340 struct volHeader *hd;
7342 static int everLogged = 0;
7344 #ifdef AFS_DEMAND_ATTACH_FS
7345 VolState vp_save = 0, back_save = 0;
7347 /* XXX debug 9/19/05 we've apparently got
7348 * a ref counting bug somewhere that's
7349 * breaking the nUsers == 0 => header on LRU
7351 if (vp->header && queue_IsNotOnQueue(vp->header)) {
7352 Log("nUsers == 0, but header not on LRU\n");
7357 old = (vp->header != NULL); /* old == volume already has a header */
7359 if (programType != fileServer) {
7360 /* for volume utilities, we allocate volHeaders as needed */
7362 hd = (struct volHeader *)calloc(1, sizeof(*vp->header));
7363 osi_Assert(hd != NULL);
7366 #ifdef AFS_DEMAND_ATTACH_FS
7367 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
7371 /* for the fileserver, we keep a volume header cache */
7373 /* the header we previously dropped in the lru is
7374 * still available. pull it off the lru and return */
7377 osi_Assert(hd->back == vp);
7378 #ifdef AFS_DEMAND_ATTACH_FS
7379 V_attachFlags(vp) &= ~(VOL_HDR_IN_LRU);
7382 /* we need to grab a new element off the LRU */
7383 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
7384 /* grab an element and pull off of LRU */
7385 hd = queue_First(&volume_hdr_LRU, volHeader);
7388 /* LRU is empty, so allocate a new volHeader
7389 * this is probably indicative of a leak, so let the user know */
7390 hd = (struct volHeader *)calloc(1, sizeof(struct volHeader));
7391 osi_Assert(hd != NULL);
7393 Log("****Allocated more volume headers, probably leak****\n");
7396 volume_hdr_LRU.stats.free++;
7399 /* this header used to belong to someone else.
7400 * we'll need to check if the header needs to
7401 * be sync'd out to disk */
7403 #ifdef AFS_DEMAND_ATTACH_FS
7404 /* if hd->back were in an exclusive state, then
7405 * its volHeader would not be on the LRU... */
7406 osi_Assert(!VIsExclusiveState(V_attachState(hd->back)));
7409 if (hd->diskstuff.inUse) {
7410 /* volume was in use, so we'll need to sync
7411 * its header to disk */
7413 #ifdef AFS_DEMAND_ATTACH_FS
7414 back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
7415 vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
7416 VCreateReservation_r(hd->back);
7420 WriteVolumeHeader_r(&error, hd->back);
7421 /* Ignore errors; catch them later */
7423 #ifdef AFS_DEMAND_ATTACH_FS
7428 hd->back->header = NULL;
7429 #ifdef AFS_DEMAND_ATTACH_FS
7430 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
7432 if (hd->diskstuff.inUse) {
7433 VChangeState_r(hd->back, back_save);
7434 VCancelReservation_r(hd->back);
7435 VChangeState_r(vp, vp_save);
7439 volume_hdr_LRU.stats.attached++;
7443 #ifdef AFS_DEMAND_ATTACH_FS
7444 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
7447 volume_hdr_LRU.stats.free--;
7448 volume_hdr_LRU.stats.used++;
7450 IncUInt64(&VStats.hdr_gets);
7451 #ifdef AFS_DEMAND_ATTACH_FS
7452 IncUInt64(&vp->stats.hdr_gets);
7453 vp->stats.last_hdr_get = FT_ApproxTime();
7460 * make sure volume header is attached and contains valid cache data.
7462 * @param[out] ec outbound error code
7463 * @param[in] vp pointer to volume object
7465 * @pre VOL_LOCK held. For DAFS, lightweight ref held on vp.
7467 * @post header cache entry attached, and loaded with valid data, or
7468 * *ec is nonzero, and the header is released back into the LRU.
7470 * @internal volume package internal use only.
7473 LoadVolumeHeader(Error * ec, Volume * vp)
7475 #ifdef AFS_DEMAND_ATTACH_FS
7476 VolState state_save;
7480 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
7481 IncUInt64(&VStats.hdr_loads);
7482 state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
7485 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
7486 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
7488 IncUInt64(&vp->stats.hdr_loads);
7489 now = FT_ApproxTime();
7493 V_attachFlags(vp) |= VOL_HDR_LOADED;
7494 vp->stats.last_hdr_load = now;
7496 VChangeState_r(vp, state_save);
7498 #else /* AFS_DEMAND_ATTACH_FS */
7500 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
7501 IncUInt64(&VStats.hdr_loads);
7503 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
7504 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
7507 #endif /* AFS_DEMAND_ATTACH_FS */
7509 /* maintain (nUsers==0) => header in LRU invariant */
7510 FreeVolumeHeader(vp);
7515 * release a header cache entry back into the LRU list.
7517 * @param[in] hd pointer to volume header cache object
7519 * @pre VOL_LOCK held.
7521 * @post header cache object appended onto end of LRU list.
7523 * @note only applicable to fileServer program type.
7525 * @note used to place a header cache entry back into the
7526 * LRU pool without invalidating it as a cache entry.
7528 * @internal volume package internal use only.
7531 ReleaseVolumeHeader(struct volHeader *hd)
7533 if (programType != fileServer)
7535 if (!hd || queue_IsOnQueue(hd)) /* no header, or header already released */
7537 queue_Append(&volume_hdr_LRU, hd);
7538 #ifdef AFS_DEMAND_ATTACH_FS
7540 V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
7543 volume_hdr_LRU.stats.free++;
7544 volume_hdr_LRU.stats.used--;
7548 * free/invalidate a volume header cache entry.
7550 * @param[in] vp pointer to volume object
7552 * @pre VOL_LOCK is held.
7554 * @post For fileserver, header cache entry is returned to LRU, and it is
7555 * invalidated as a cache entry. For volume utilities, the header
7556 * cache entry is freed.
7558 * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
7559 * whenever it is necessary to invalidate the header cache entry.
7561 * @see ReleaseVolumeHeader
7563 * @internal volume package internal use only.
7566 FreeVolumeHeader(Volume * vp)
7568 struct volHeader *hd = vp->header;
7571 if (programType == fileServer) {
7572 ReleaseVolumeHeader(hd);
7577 #ifdef AFS_DEMAND_ATTACH_FS
7578 V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
7580 volume_hdr_LRU.stats.attached--;
7585 /***************************************************/
7586 /* Volume Hash Table routines */
7587 /***************************************************/
7590 * set size of volume object hash table.
7592 * @param[in] logsize log(2) of desired hash table size
7594 * @return operation status
7596 * @retval -1 failure
7598 * @pre MUST be called prior to VInitVolumePackage2
7600 * @post Volume Hash Table will have 2^logsize buckets
7603 VSetVolHashSize(int logsize)
7605 /* 64 to 268435456 hash buckets seems like a reasonable range */
7606 if ((logsize < 6 ) || (logsize > 28)) {
7611 VolumeHashTable.Size = 1 << logsize;
7612 VolumeHashTable.Mask = VolumeHashTable.Size - 1;
7614 /* we can't yet support runtime modification of this
7615 * parameter. we'll need a configuration rwlock to
7616 * make runtime modification feasible.... */
7623 * initialize dynamic data structures for volume hash table.
7625 * @post hash table is allocated, and fields are initialized.
7627 * @internal volume package internal use only.
7630 VInitVolumeHash(void)
7634 VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
7635 sizeof(VolumeHashChainHead));
7636 osi_Assert(VolumeHashTable.Table != NULL);
7638 for (i=0; i < VolumeHashTable.Size; i++) {
7639 queue_Init(&VolumeHashTable.Table[i]);
7640 #ifdef AFS_DEMAND_ATTACH_FS
7641 CV_INIT(&VolumeHashTable.Table[i].chain_busy_cv, "vhash busy", CV_DEFAULT, 0);
7642 #endif /* AFS_DEMAND_ATTACH_FS */
7647 * add a volume object to the hash table.
7649 * @param[in] vp pointer to volume object
7650 * @param[in] hashid hash of volume id
7652 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
7655 * @post volume is added to hash chain.
7657 * @internal volume package internal use only.
7659 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
7660 * asynchronous hash chain reordering to finish.
7663 AddVolumeToHashTable(Volume * vp, int hashid)
7665 VolumeHashChainHead * head;
7667 if (queue_IsOnQueue(vp))
7670 head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
7672 #ifdef AFS_DEMAND_ATTACH_FS
7673 /* wait for the hash chain to become available */
7676 V_attachFlags(vp) |= VOL_IN_HASH;
7677 vp->chainCacheCheck = ++head->cacheCheck;
7678 #endif /* AFS_DEMAND_ATTACH_FS */
7681 vp->hashid = hashid;
7682 queue_Append(head, vp);
7683 vp->vnodeHashOffset = VolumeHashOffset_r();
7687 * delete a volume object from the hash table.
7689 * @param[in] vp pointer to volume object
7691 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
7694 * @post volume is removed from hash chain.
7696 * @internal volume package internal use only.
7698 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
7699 * asynchronous hash chain reordering to finish.
7702 DeleteVolumeFromHashTable(Volume * vp)
7704 VolumeHashChainHead * head;
7706 if (!queue_IsOnQueue(vp))
7709 head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
7711 #ifdef AFS_DEMAND_ATTACH_FS
7712 /* wait for the hash chain to become available */
7715 V_attachFlags(vp) &= ~(VOL_IN_HASH);
7717 #endif /* AFS_DEMAND_ATTACH_FS */
7721 /* do NOT reset hashid to zero, as the online
7722 * salvager package may need to know the volume id
7723 * after the volume is removed from the hash */
7727 * lookup a volume object in the hash table given a volume id.
7729 * @param[out] ec error code return
7730 * @param[in] volumeId volume id
7731 * @param[in] hint volume object which we believe could be the correct
7734 * @return volume object pointer
7735 * @retval NULL no such volume id is registered with the hash table.
7737 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
7740 * @post volume object with the given id is returned. volume object and
7741 * hash chain access statistics are updated. hash chain may have
7744 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
7745 * asynchronous hash chain reordering operation to finish, or
7746 * in order for us to perform an asynchronous chain reordering.
7748 * @note Hash chain reorderings occur when the access count for the
7749 * volume object being looked up exceeds the sum of the previous
7750 * node's (the node ahead of it in the hash chain linked list)
7751 * access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
7753 * @note For DAFS, the hint parameter allows us to short-circuit if the
7754 * cacheCheck fields match between the hash chain head and the
7755 * hint volume object.
7758 VLookupVolume_r(Error * ec, VolId volumeId, Volume * hint)
7762 #ifdef AFS_DEMAND_ATTACH_FS
7765 VolumeHashChainHead * head;
7768 head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
7770 #ifdef AFS_DEMAND_ATTACH_FS
7771 /* wait for the hash chain to become available */
7774 /* check to see if we can short circuit without walking the hash chain */
7775 if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
7776 IncUInt64(&hint->stats.hash_short_circuits);
7779 #endif /* AFS_DEMAND_ATTACH_FS */
7781 /* someday we need to either do per-chain locks, RWlocks,
7782 * or both for volhash access.
7783 * (and move to a data structure with better cache locality) */
7785 /* search the chain for this volume id */
7786 for(queue_Scan(head, vp, np, Volume)) {
7788 if ((vp->hashid == volumeId)) {
7793 if (queue_IsEnd(head, vp)) {
7797 #ifdef AFS_DEMAND_ATTACH_FS
7798 /* update hash chain statistics */
7801 FillInt64(lks, 0, looks);
7802 AddUInt64(head->looks, lks, &head->looks);
7803 AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
7804 IncUInt64(&head->gets);
7809 IncUInt64(&vp->stats.hash_lookups);
7811 /* for demand attach fileserver, we permit occasional hash chain reordering
7812 * so that frequently looked up volumes move towards the head of the chain */
7813 pp = queue_Prev(vp, Volume);
7814 if (!queue_IsEnd(head, pp)) {
7815 FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
7816 AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
7817 if (GEInt64(vp->stats.hash_lookups, thresh)) {
7818 VReorderHash_r(head, pp, vp);
7822 /* update the short-circuit cache check */
7823 vp->chainCacheCheck = head->cacheCheck;
7825 #endif /* AFS_DEMAND_ATTACH_FS */
7830 #ifdef AFS_DEMAND_ATTACH_FS
7831 /* perform volume hash chain reordering.
7833 * advance a subchain beginning at vp ahead of
7834 * the adjacent subchain ending at pp */
7836 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
7838 Volume *tp, *np, *lp;
7839 afs_uint64 move_thresh;
7841 /* this should never be called if the chain is already busy, so
7842 * no need to wait for other exclusive chain ops to finish */
7844 /* this is a rather heavy set of operations,
7845 * so let's set the chain busy flag and drop
7847 VHashBeginExclusive_r(head);
7850 /* scan forward in the chain from vp looking for the last element
7851 * in the chain we want to advance */
7852 FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
7853 AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
7854 for(queue_ScanFrom(head, vp, tp, np, Volume)) {
7855 if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
7859 lp = queue_Prev(tp, Volume);
7861 /* scan backwards from pp to determine where to splice and
7862 * insert the subchain we're advancing */
7863 for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
7864 if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
7868 tp = queue_Next(tp, Volume);
7870 /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
7871 queue_MoveChainBefore(tp,vp,lp);
7874 IncUInt64(&VStats.hash_reorders);
7876 IncUInt64(&head->reorders);
7878 /* wake up any threads waiting for the hash chain */
7879 VHashEndExclusive_r(head);
7883 /* demand-attach fs volume hash
7884 * asynchronous exclusive operations */
7887 * begin an asynchronous exclusive operation on a volume hash chain.
7889 * @param[in] head pointer to volume hash chain head object
7891 * @pre VOL_LOCK held. hash chain is quiescent.
7893 * @post hash chain marked busy.
7895 * @note this interface is used in conjunction with VHashEndExclusive_r and
7896 * VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
7897 * volume hash chain. Its main use case is hash chain reordering, which
7898 * has the potential to be a highly latent operation.
7900 * @see VHashEndExclusive_r
7905 * @internal volume package internal use only.
7908 VHashBeginExclusive_r(VolumeHashChainHead * head)
7910 osi_Assert(head->busy == 0);
7915 * relinquish exclusive ownership of a volume hash chain.
7917 * @param[in] head pointer to volume hash chain head object
7919 * @pre VOL_LOCK held. thread owns the hash chain exclusively.
7921 * @post hash chain is marked quiescent. threads awaiting use of
7922 * chain are awakened.
7924 * @see VHashBeginExclusive_r
7929 * @internal volume package internal use only.
7932 VHashEndExclusive_r(VolumeHashChainHead * head)
7934 osi_Assert(head->busy);
7936 CV_BROADCAST(&head->chain_busy_cv);
7940 * wait for all asynchronous operations on a hash chain to complete.
7942 * @param[in] head pointer to volume hash chain head object
7944 * @pre VOL_LOCK held.
7946 * @post hash chain object is quiescent.
7948 * @see VHashBeginExclusive_r
7949 * @see VHashEndExclusive_r
7953 * @note This interface should be called before any attempt to
7954 * traverse the hash chain. It is permissible for a thread
7955 * to gain exclusive access to the chain, and then perform
7956 * latent operations on the chain asynchronously wrt the
7959 * @warning if waiting is necessary, VOL_LOCK is dropped
7961 * @internal volume package internal use only.
7964 VHashWait_r(VolumeHashChainHead * head)
7966 while (head->busy) {
7967 VOL_CV_WAIT(&head->chain_busy_cv);
7970 #endif /* AFS_DEMAND_ATTACH_FS */
7973 /***************************************************/
7974 /* Volume by Partition List routines */
7975 /***************************************************/
7978 * demand attach fileserver adds a
7979 * linked list of volumes to each
7980 * partition object, thus allowing
7981 * for quick enumeration of all
7982 * volumes on a partition
7985 #ifdef AFS_DEMAND_ATTACH_FS
7987 * add a volume to its disk partition VByPList.
7989 * @param[in] vp pointer to volume object
7991 * @pre either the disk partition VByPList is owned exclusively
7992 * by the calling thread, or the list is quiescent and
7995 * @post volume is added to disk partition VByPList
7999 * @warning it is the caller's responsibility to ensure list
8002 * @see VVByPListWait_r
8003 * @see VVByPListBeginExclusive_r
8004 * @see VVByPListEndExclusive_r
8006 * @internal volume package internal use only.
8009 AddVolumeToVByPList_r(Volume * vp)
8011 if (queue_IsNotOnQueue(&vp->vol_list)) {
8012 queue_Append(&vp->partition->vol_list, &vp->vol_list);
8013 V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
8014 vp->partition->vol_list.len++;
8019 * delete a volume from its disk partition VByPList.
8021 * @param[in] vp pointer to volume object
8023 * @pre either the disk partition VByPList is owned exclusively
8024 * by the calling thread, or the list is quiescent and
8027 * @post volume is removed from the disk partition VByPList
8031 * @warning it is the caller's responsibility to ensure list
8034 * @see VVByPListWait_r
8035 * @see VVByPListBeginExclusive_r
8036 * @see VVByPListEndExclusive_r
8038 * @internal volume package internal use only.
8041 DeleteVolumeFromVByPList_r(Volume * vp)
8043 if (queue_IsOnQueue(&vp->vol_list)) {
8044 queue_Remove(&vp->vol_list);
8045 V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
8046 vp->partition->vol_list.len--;
8051 * begin an asynchronous exclusive operation on a VByPList.
8053 * @param[in] dp pointer to disk partition object
8055 * @pre VOL_LOCK held. VByPList is quiescent.
8057 * @post VByPList marked busy.
8059 * @note this interface is used in conjunction with VVByPListEndExclusive_r and
8060 * VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8063 * @see VVByPListEndExclusive_r
8064 * @see VVByPListWait_r
8068 * @internal volume package internal use only.
8070 /* take exclusive control over the list */
8072 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
8074 osi_Assert(dp->vol_list.busy == 0);
8075 dp->vol_list.busy = 1;
8079 * relinquish exclusive ownership of a VByPList.
8081 * @param[in] dp pointer to disk partition object
8083 * @pre VOL_LOCK held. thread owns the VByPList exclusively.
8085 * @post VByPList is marked quiescent. threads awaiting use of
8086 * the list are awakened.
8088 * @see VVByPListBeginExclusive_r
8089 * @see VVByPListWait_r
8093 * @internal volume package internal use only.
8096 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
8098 osi_Assert(dp->vol_list.busy);
8099 dp->vol_list.busy = 0;
8100 CV_BROADCAST(&dp->vol_list.cv);
8104 * wait for all asynchronous operations on a VByPList to complete.
8106 * @param[in] dp pointer to disk partition object
8108 * @pre VOL_LOCK is held.
8110 * @post disk partition's VByP list is quiescent
8114 * @note This interface should be called before any attempt to
8115 * traverse the VByPList. It is permissible for a thread
8116 * to gain exclusive access to the list, and then perform
8117 * latent operations on the list asynchronously wrt the
8120 * @warning if waiting is necessary, VOL_LOCK is dropped
8122 * @see VVByPListEndExclusive_r
8123 * @see VVByPListBeginExclusive_r
8125 * @internal volume package internal use only.
8128 VVByPListWait_r(struct DiskPartition64 * dp)
8130 while (dp->vol_list.busy) {
8131 VOL_CV_WAIT(&dp->vol_list.cv);
8134 #endif /* AFS_DEMAND_ATTACH_FS */
8136 /***************************************************/
8137 /* Volume Cache Statistics routines */
8138 /***************************************************/
8141 VPrintCacheStats_r(void)
8143 afs_uint32 get_hi, get_lo, load_hi, load_lo;
8144 struct VnodeClassInfo *vcp;
8145 vcp = &VnodeClassInfo[vLarge];
8146 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);
8147 vcp = &VnodeClassInfo[vSmall];
8148 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);
8149 SplitInt64(VStats.hdr_gets, get_hi, get_lo);
8150 SplitInt64(VStats.hdr_loads, load_hi, load_lo);
8151 Log("Volume header cache, %d entries, %d gets, %d replacements\n",
8152 VStats.hdr_cache_size, get_lo, load_lo);
8156 VPrintCacheStats(void)
8159 VPrintCacheStats_r();
8163 #ifdef AFS_DEMAND_ATTACH_FS
8165 UInt64ToDouble(afs_uint64 * x)
8167 static double c32 = 4.0 * 1.073741824 * 1000000000.0;
8169 SplitInt64(*x, h, l);
8170 return (((double)h) * c32) + ((double) l);
8174 DoubleToPrintable(double x, char * buf, int len)
8176 static double billion = 1000000000.0;
8179 y[0] = (afs_uint32) (x / (billion * billion));
8180 y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
8181 y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
8184 snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
8186 snprintf(buf, len, "%d%09d", y[1], y[2]);
8188 snprintf(buf, len, "%d", y[2]);
8194 struct VLRUExtStatsEntry {
8198 struct VLRUExtStats {
8204 } queue_info[VLRU_QUEUE_INVALID];
8205 struct VLRUExtStatsEntry * vec;
8209 * add a 256-entry fudge factor onto the vector in case state changes
8210 * out from under us.
8212 #define VLRU_EXT_STATS_VEC_LEN_FUDGE 256
8215 * collect extended statistics for the VLRU subsystem.
8217 * @param[out] stats pointer to stats structure to be populated
8218 * @param[in] nvols number of volumes currently known to exist
8220 * @pre VOL_LOCK held
8222 * @post stats->vec allocated and populated
8224 * @return operation status
8229 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
8231 afs_uint32 cur, idx, len;
8232 struct rx_queue * qp, * nqp;
8234 struct VLRUExtStatsEntry * vec;
8236 len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
8237 vec = stats->vec = calloc(len,
8238 sizeof(struct VLRUExtStatsEntry));
8244 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
8245 VLRU_Wait_r(&volume_LRU.q[idx]);
8246 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
8249 stats->queue_info[idx].start = cur;
8251 for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
8253 /* out of space in vec */
8256 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
8257 vec[cur].volid = vp->hashid;
8261 stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
8264 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
8272 #define ENUMTOSTRING(en) #en
8273 #define ENUMCASE(en) \
8275 return ENUMTOSTRING(en); \
8279 vlru_idx_to_string(int idx)
8282 ENUMCASE(VLRU_QUEUE_NEW);
8283 ENUMCASE(VLRU_QUEUE_MID);
8284 ENUMCASE(VLRU_QUEUE_OLD);
8285 ENUMCASE(VLRU_QUEUE_CANDIDATE);
8286 ENUMCASE(VLRU_QUEUE_HELD);
8287 ENUMCASE(VLRU_QUEUE_INVALID);
8289 return "**UNKNOWN**";
8294 VPrintExtendedCacheStats_r(int flags)
8297 afs_uint32 vol_sum = 0;
8304 struct stats looks, gets, reorders, len;
8305 struct stats ch_looks, ch_gets, ch_reorders;
8307 VolumeHashChainHead *head;
8309 struct VLRUExtStats vlru_stats;
8311 /* zero out stats */
8312 memset(&looks, 0, sizeof(struct stats));
8313 memset(&gets, 0, sizeof(struct stats));
8314 memset(&reorders, 0, sizeof(struct stats));
8315 memset(&len, 0, sizeof(struct stats));
8316 memset(&ch_looks, 0, sizeof(struct stats));
8317 memset(&ch_gets, 0, sizeof(struct stats));
8318 memset(&ch_reorders, 0, sizeof(struct stats));
8320 for (i = 0; i < VolumeHashTable.Size; i++) {
8321 head = &VolumeHashTable.Table[i];
8324 VHashBeginExclusive_r(head);
8327 ch_looks.sum = UInt64ToDouble(&head->looks);
8328 ch_gets.sum = UInt64ToDouble(&head->gets);
8329 ch_reorders.sum = UInt64ToDouble(&head->reorders);
8331 /* update global statistics */
8333 looks.sum += ch_looks.sum;
8334 gets.sum += ch_gets.sum;
8335 reorders.sum += ch_reorders.sum;
8336 len.sum += (double)head->len;
8337 vol_sum += head->len;
8340 len.min = (double) head->len;
8341 len.max = (double) head->len;
8342 looks.min = ch_looks.sum;
8343 looks.max = ch_looks.sum;
8344 gets.min = ch_gets.sum;
8345 gets.max = ch_gets.sum;
8346 reorders.min = ch_reorders.sum;
8347 reorders.max = ch_reorders.sum;
8349 if (((double)head->len) < len.min)
8350 len.min = (double) head->len;
8351 if (((double)head->len) > len.max)
8352 len.max = (double) head->len;
8353 if (ch_looks.sum < looks.min)
8354 looks.min = ch_looks.sum;
8355 else if (ch_looks.sum > looks.max)
8356 looks.max = ch_looks.sum;
8357 if (ch_gets.sum < gets.min)
8358 gets.min = ch_gets.sum;
8359 else if (ch_gets.sum > gets.max)
8360 gets.max = ch_gets.sum;
8361 if (ch_reorders.sum < reorders.min)
8362 reorders.min = ch_reorders.sum;
8363 else if (ch_reorders.sum > reorders.max)
8364 reorders.max = ch_reorders.sum;
8368 if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
8369 /* compute detailed per-chain stats */
8370 struct stats hdr_loads, hdr_gets;
8371 double v_looks, v_loads, v_gets;
8373 /* initialize stats with data from first element in chain */
8374 vp = queue_First(head, Volume);
8375 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
8376 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
8377 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
8378 ch_gets.min = ch_gets.max = v_looks;
8379 hdr_loads.min = hdr_loads.max = v_loads;
8380 hdr_gets.min = hdr_gets.max = v_gets;
8381 hdr_loads.sum = hdr_gets.sum = 0;
8383 vp = queue_Next(vp, Volume);
8385 /* pull in stats from remaining elements in chain */
8386 for (queue_ScanFrom(head, vp, vp, np, Volume)) {
8387 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
8388 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
8389 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
8391 hdr_loads.sum += v_loads;
8392 hdr_gets.sum += v_gets;
8394 if (v_looks < ch_gets.min)
8395 ch_gets.min = v_looks;
8396 else if (v_looks > ch_gets.max)
8397 ch_gets.max = v_looks;
8399 if (v_loads < hdr_loads.min)
8400 hdr_loads.min = v_loads;
8401 else if (v_loads > hdr_loads.max)
8402 hdr_loads.max = v_loads;
8404 if (v_gets < hdr_gets.min)
8405 hdr_gets.min = v_gets;
8406 else if (v_gets > hdr_gets.max)
8407 hdr_gets.max = v_gets;
8410 /* compute per-chain averages */
8411 ch_gets.avg = ch_gets.sum / ((double)head->len);
8412 hdr_loads.avg = hdr_loads.sum / ((double)head->len);
8413 hdr_gets.avg = hdr_gets.sum / ((double)head->len);
8415 /* dump per-chain stats */
8416 Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
8418 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
8419 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
8420 Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
8421 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
8422 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
8423 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
8424 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
8425 Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
8426 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
8427 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
8428 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
8429 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
8430 Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
8431 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
8432 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
8433 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
8434 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
8435 } else if (flags & VOL_STATS_PER_CHAIN) {
8436 /* dump simple per-chain stats */
8437 Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
8439 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
8440 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
8441 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
8445 VHashEndExclusive_r(head);
8450 /* compute global averages */
8451 len.avg = len.sum / ((double)VolumeHashTable.Size);
8452 looks.avg = looks.sum / ((double)VolumeHashTable.Size);
8453 gets.avg = gets.sum / ((double)VolumeHashTable.Size);
8454 reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
8456 /* dump global stats */
8457 Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
8458 Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
8459 DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
8460 DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
8461 DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
8462 DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
8463 Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
8464 DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
8465 DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
8466 DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
8467 DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
8468 Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
8469 DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
8470 DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
8471 DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
8472 DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
8473 Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
8474 DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
8475 DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
8476 DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
8477 DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
8479 /* print extended disk related statistics */
8481 struct DiskPartition64 * diskP;
8482 afs_uint32 vol_count[VOLMAXPARTS+1];
8483 byte part_exists[VOLMAXPARTS+1];
8487 memset(vol_count, 0, sizeof(vol_count));
8488 memset(part_exists, 0, sizeof(part_exists));
8492 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
8494 vol_count[id] = diskP->vol_list.len;
8495 part_exists[id] = 1;
8499 for (i = 0; i <= VOLMAXPARTS; i++) {
8500 if (part_exists[i]) {
8501 /* XXX while this is currently safe, it is a violation
8502 * of the VGetPartitionById_r interface contract. */
8503 diskP = VGetPartitionById_r(i, 0);
8505 Log("Partition %s has %d online volumes\n",
8506 VPartitionPath(diskP), diskP->vol_list.len);
8513 /* print extended VLRU statistics */
8514 if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
8515 afs_uint32 idx, cur, lpos;
8520 Log("VLRU State Dump:\n\n");
8522 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
8523 Log("\t%s:\n", vlru_idx_to_string(idx));
8526 for (cur = vlru_stats.queue_info[idx].start;
8527 cur < vlru_stats.queue_info[idx].len;
8529 line[lpos++] = vlru_stats.vec[cur].volid;
8531 Log("\t\t%u, %u, %u, %u, %u,\n",
8532 line[0], line[1], line[2], line[3], line[4]);
8541 Log("\t\t%u, %u, %u, %u, %u\n",
8542 line[0], line[1], line[2], line[3], line[4]);
8547 free(vlru_stats.vec);
8554 VPrintExtendedCacheStats(int flags)
8557 VPrintExtendedCacheStats_r(flags);
8560 #endif /* AFS_DEMAND_ATTACH_FS */
8563 VCanScheduleSalvage(void)
8565 return vol_opts.canScheduleSalvage;
8571 return vol_opts.canUseFSSYNC;
8575 VCanUseSALVSYNC(void)
8577 return vol_opts.canUseSALVSYNC;
8581 VCanUnsafeAttach(void)
8583 return vol_opts.unsafe_attach;