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>
27 #include <afs/afsint.h>
31 #include <sys/param.h>
32 #if !defined(AFS_SGI_ENV)
35 #else /* AFS_OSF_ENV */
36 #ifdef AFS_VFSINCL_ENV
39 #include <sys/fs/ufs_fs.h>
41 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
42 #include <ufs/ufs/dinode.h>
43 #include <ufs/ffs/fs.h>
48 #else /* AFS_VFSINCL_ENV */
49 #if !defined(AFS_AIX_ENV) && !defined(AFS_LINUX20_ENV) && !defined(AFS_XBSD_ENV) && !defined(AFS_ARM_DARWIN_ENV)
52 #endif /* AFS_VFSINCL_ENV */
53 #endif /* AFS_OSF_ENV */
54 #endif /* AFS_SGI_ENV */
55 #endif /* AFS_NT40_ENV */
73 #if defined(AFS_SUN_ENV) || defined(AFS_SUN5_ENV)
75 #include <sys/mnttab.h>
76 #include <sys/mntent.h>
82 #if defined(AFS_SGI_ENV)
87 #ifndef AFS_LINUX20_ENV
88 #include <fstab.h> /* Need to find in libc 5, present in libc 6 */
91 #endif /* AFS_SGI_ENV */
93 #endif /* AFS_HPUX_ENV */
97 #include <netinet/in.h>
101 #include <sys/time.h>
102 #endif /* ITIMER_REAL */
103 #endif /* AFS_NT40_ENV */
104 #if defined(AFS_SUN5_ENV) || defined(AFS_NT40_ENV) || defined(AFS_LINUX20_ENV)
111 #include <afs/errors.h>
114 #include <afs/afssyscalls.h>
116 #include <afs/afsutil.h>
120 #include "daemon_com.h"
122 #include "salvsync.h"
125 #include "partition.h"
126 #include "volume_inline.h"
128 #include "afs/afs_assert.h"
135 #if !defined(offsetof)
140 #define afs_stat stat64
141 #define afs_fstat fstat64
142 #define afs_open open64
143 #else /* !O_LARGEFILE */
144 #define afs_stat stat
145 #define afs_fstat fstat
146 #define afs_open open
147 #endif /* !O_LARGEFILE */
149 #ifdef AFS_PTHREAD_ENV
150 pthread_mutex_t vol_glock_mutex;
151 pthread_mutex_t vol_trans_mutex;
152 pthread_cond_t vol_put_volume_cond;
153 pthread_cond_t vol_sleep_cond;
154 pthread_cond_t vol_init_attach_cond;
155 pthread_cond_t vol_vinit_cond;
156 int vol_attach_threads = 1;
157 #endif /* AFS_PTHREAD_ENV */
159 /* start-time configurable I/O parameters */
160 ih_init_params vol_io_params;
162 #ifdef AFS_DEMAND_ATTACH_FS
163 pthread_mutex_t vol_salvsync_mutex;
166 * Set this to 1 to disallow SALVSYNC communication in all threads; used
167 * during shutdown, since the salvageserver may have gone away.
169 static volatile sig_atomic_t vol_disallow_salvsync = 0;
170 #endif /* AFS_DEMAND_ATTACH_FS */
173 * has VShutdown_r been called / is VShutdown_r running?
175 static int vol_shutting_down = 0;
178 extern void *calloc(), *realloc();
181 /* Forward declarations */
182 static Volume *attach2(Error * ec, VolId volumeId, char *path,
183 struct DiskPartition64 *partp, Volume * vp,
184 int isbusy, int mode, int *acheckedOut);
185 static void ReallyFreeVolume(Volume * vp);
186 #ifdef AFS_DEMAND_ATTACH_FS
187 static void FreeVolume(Volume * vp);
188 #else /* !AFS_DEMAND_ATTACH_FS */
189 #define FreeVolume(vp) ReallyFreeVolume(vp)
190 static void VScanUpdateList(void);
191 #endif /* !AFS_DEMAND_ATTACH_FS */
192 static void VInitVolumeHeaderCache(afs_uint32 howMany);
193 static int GetVolumeHeader(Volume * vp);
194 static void ReleaseVolumeHeader(struct volHeader *hd);
195 static void FreeVolumeHeader(Volume * vp);
196 static void AddVolumeToHashTable(Volume * vp, int hashid);
197 static void DeleteVolumeFromHashTable(Volume * vp);
199 static int VHold(Volume * vp);
201 static int VHold_r(Volume * vp);
202 static void VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class);
203 static void VReleaseVolumeHandles_r(Volume * vp);
204 static void VCloseVolumeHandles_r(Volume * vp);
205 static void LoadVolumeHeader(Error * ec, Volume * vp);
206 static int VCheckOffline(Volume * vp);
207 static int VCheckDetach(Volume * vp);
208 static Volume * GetVolume(Error * ec, Error * client_ec, VolId volumeId,
209 Volume * hint, const struct timespec *ts);
211 int LogLevel; /* Vice loglevel--not defined as extern so that it will be
212 * defined when not linked with vice, XXXX */
213 ProgramType programType; /* The type of program using the package */
214 static VolumePackageOptions vol_opts;
216 /* extended volume package statistics */
219 #ifdef VOL_LOCK_DEBUG
220 pthread_t vol_glock_holder = 0;
224 #define VOLUME_BITMAP_GROWSIZE 16 /* bytes, => 128vnodes */
225 /* Must be a multiple of 4 (1 word) !! */
227 /* this parameter needs to be tunable at runtime.
228 * 128 was really inadequate for largish servers -- at 16384 volumes this
229 * puts average chain length at 128, thus an average 65 deref's to find a volptr.
230 * talk about bad spatial locality...
232 * an AVL or splay tree might work a lot better, but we'll just increase
233 * the default hash table size for now
235 #define DEFAULT_VOLUME_HASH_SIZE 256 /* Must be a power of 2!! */
236 #define DEFAULT_VOLUME_HASH_MASK (DEFAULT_VOLUME_HASH_SIZE-1)
237 #define VOLUME_HASH(volumeId) (volumeId&(VolumeHashTable.Mask))
240 * turn volume hash chains into partially ordered lists.
241 * when the threshold is exceeded between two adjacent elements,
242 * perform a chain rebalancing operation.
244 * keep the threshold high in order to keep cache line invalidates
245 * low "enough" on SMPs
247 #define VOLUME_HASH_REORDER_THRESHOLD 200
250 * when possible, don't just reorder single elements, but reorder
251 * entire chains of elements at once. a chain of elements that
252 * exceed the element previous to the pivot by at least CHAIN_THRESH
253 * accesses are moved in front of the chain whose elements have at
254 * least CHAIN_THRESH less accesses than the pivot element
256 #define VOLUME_HASH_REORDER_CHAIN_THRESH (VOLUME_HASH_REORDER_THRESHOLD / 2)
258 #include "rx/rx_queue.h"
261 VolumeHashTable_t VolumeHashTable = {
262 DEFAULT_VOLUME_HASH_SIZE,
263 DEFAULT_VOLUME_HASH_MASK,
268 static void VInitVolumeHash(void);
272 /* This macro is used where an ffs() call does not exist. Was in util/ffs.c */
276 afs_int32 ffs_tmp = x;
280 for (ffs_i = 1;; ffs_i++) {
287 #endif /* !AFS_HAVE_FFS */
289 #ifdef AFS_PTHREAD_ENV
291 * disk partition queue element
293 typedef struct diskpartition_queue_t {
294 struct rx_queue queue; /**< queue header */
295 struct DiskPartition64 *diskP; /**< disk partition table entry */
296 } diskpartition_queue_t;
298 #ifndef AFS_DEMAND_ATTACH_FS
300 typedef struct vinitvolumepackage_thread_t {
301 struct rx_queue queue;
302 pthread_cond_t thread_done_cv;
303 int n_threads_complete;
304 } vinitvolumepackage_thread_t;
305 static void * VInitVolumePackageThread(void * args);
307 #else /* !AFS_DEMAND_ATTTACH_FS */
308 #define VINIT_BATCH_MAX_SIZE 512
311 * disk partition work queue
313 struct partition_queue {
314 struct rx_queue head; /**< diskpartition_queue_t queue */
315 pthread_mutex_t mutex;
320 * volumes parameters for preattach
322 struct volume_init_batch {
323 struct rx_queue queue; /**< queue header */
324 int thread; /**< posting worker thread */
325 int last; /**< indicates thread is done */
326 int size; /**< number of volume ids in batch */
327 Volume *batch[VINIT_BATCH_MAX_SIZE]; /**< volumes ids to preattach */
331 * volume parameters work queue
333 struct volume_init_queue {
334 struct rx_queue head; /**< volume_init_batch queue */
335 pthread_mutex_t mutex;
340 * volume init worker thread parameters
342 struct vinitvolumepackage_thread_param {
343 int nthreads; /**< total number of worker threads */
344 int thread; /**< thread number for this worker thread */
345 struct partition_queue *pq; /**< queue partitions to scan */
346 struct volume_init_queue *vq; /**< queue of volume to preattach */
349 static void *VInitVolumePackageThread(void *args);
350 static struct DiskPartition64 *VInitNextPartition(struct partition_queue *pq);
351 static VolId VInitNextVolumeId(DIR *dirp);
352 static int VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq);
354 #endif /* !AFS_DEMAND_ATTACH_FS */
355 #endif /* AFS_PTHREAD_ENV */
357 #ifndef AFS_DEMAND_ATTACH_FS
358 static int VAttachVolumesByPartition(struct DiskPartition64 *diskP,
359 int * nAttached, int * nUnattached);
360 #endif /* AFS_DEMAND_ATTACH_FS */
363 #ifdef AFS_DEMAND_ATTACH_FS
364 /* demand attach fileserver extensions */
367 * in the future we will support serialization of VLRU state into the fs_state
370 * these structures are the beginning of that effort
372 struct VLRU_DiskHeader {
373 struct versionStamp stamp; /* magic and structure version number */
374 afs_uint32 mtime; /* time of dump to disk */
375 afs_uint32 num_records; /* number of VLRU_DiskEntry records */
378 struct VLRU_DiskEntry {
379 afs_uint32 vid; /* volume ID */
380 afs_uint32 idx; /* generation */
381 afs_uint32 last_get; /* timestamp of last get */
384 struct VLRU_StartupQueue {
385 struct VLRU_DiskEntry * entry;
390 typedef struct vshutdown_thread_t {
392 pthread_mutex_t lock;
394 pthread_cond_t master_cv;
396 int n_threads_complete;
398 int schedule_version;
401 byte n_parts_done_pass;
402 byte part_thread_target[VOLMAXPARTS+1];
403 byte part_done_pass[VOLMAXPARTS+1];
404 struct rx_queue * part_pass_head[VOLMAXPARTS+1];
405 int stats[4][VOLMAXPARTS+1];
406 } vshutdown_thread_t;
407 static void * VShutdownThread(void * args);
410 static Volume * VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode);
411 static int VCheckFree(Volume * vp);
414 static void AddVolumeToVByPList_r(Volume * vp);
415 static void DeleteVolumeFromVByPList_r(Volume * vp);
416 static void VVByPListBeginExclusive_r(struct DiskPartition64 * dp);
417 static void VVByPListEndExclusive_r(struct DiskPartition64 * dp);
418 static void VVByPListWait_r(struct DiskPartition64 * dp);
420 /* online salvager */
421 static int VCheckSalvage(Volume * vp);
422 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
423 static int VScheduleSalvage_r(Volume * vp);
426 /* Volume hash table */
427 static void VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp);
428 static void VHashBeginExclusive_r(VolumeHashChainHead * head);
429 static void VHashEndExclusive_r(VolumeHashChainHead * head);
430 static void VHashWait_r(VolumeHashChainHead * head);
433 static int ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass);
434 static int ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
435 struct rx_queue ** idx);
436 static void ShutdownController(vshutdown_thread_t * params);
437 static void ShutdownCreateSchedule(vshutdown_thread_t * params);
440 static void VLRU_ComputeConstants(void);
441 static void VInitVLRU(void);
442 static void VLRU_Init_Node_r(Volume * vp);
443 static void VLRU_Add_r(Volume * vp);
444 static void VLRU_Delete_r(Volume * vp);
445 static void VLRU_UpdateAccess_r(Volume * vp);
446 static void * VLRU_ScannerThread(void * args);
447 static void VLRU_Scan_r(int idx);
448 static void VLRU_Promote_r(int idx);
449 static void VLRU_Demote_r(int idx);
450 static void VLRU_SwitchQueues(Volume * vp, int new_idx, int append);
453 static int VCheckSoftDetach(Volume * vp, afs_uint32 thresh);
454 static int VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh);
455 static int VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh);
458 pthread_key_t VThread_key;
459 VThreadOptions_t VThread_defaults = {
460 0 /**< allow salvsync */
462 #endif /* AFS_DEMAND_ATTACH_FS */
465 struct Lock vol_listLock; /* Lock obtained when listing volumes:
466 * prevents a volume from being missed
467 * if the volume is attached during a
471 /* Common message used when the volume goes off line */
472 char *VSalvageMessage =
473 "Files in this volume are currently unavailable; call operations";
475 int VInit; /* 0 - uninitialized,
476 * 1 - initialized but not all volumes have been attached,
477 * 2 - initialized and all volumes have been attached,
478 * 3 - initialized, all volumes have been attached, and
479 * VConnectFS() has completed. */
481 static int vinit_attach_abort = 0;
483 bit32 VolumeCacheCheck; /* Incremented everytime a volume goes on line--
484 * used to stamp volume headers and in-core
485 * vnodes. When the volume goes on-line the
486 * vnode will be invalidated
487 * access only with VOL_LOCK held */
492 /***************************************************/
493 /* Startup routines */
494 /***************************************************/
496 #if defined(FAST_RESTART) && defined(AFS_DEMAND_ATTACH_FS)
497 # error FAST_RESTART and DAFS are incompatible. For the DAFS equivalent \
498 of FAST_RESTART, use the -unsafe-nosalvage fileserver argument
502 * assign default values to a VolumePackageOptions struct.
504 * Always call this on a VolumePackageOptions struct first, then set any
505 * specific options you want, then call VInitVolumePackage2.
507 * @param[in] pt caller's program type
508 * @param[out] opts volume package options
511 VOptDefaults(ProgramType pt, VolumePackageOptions *opts)
513 opts->nLargeVnodes = opts->nSmallVnodes = 5;
516 opts->canScheduleSalvage = 0;
517 opts->canUseFSSYNC = 0;
518 opts->canUseSALVSYNC = 0;
520 opts->interrupt_rxcall = NULL;
521 opts->offline_timeout = -1;
522 opts->offline_shutdown_timeout = -1;
525 opts->unsafe_attach = 1;
526 #else /* !FAST_RESTART */
527 opts->unsafe_attach = 0;
528 #endif /* !FAST_RESTART */
532 opts->canScheduleSalvage = 1;
533 opts->canUseSALVSYNC = 1;
537 opts->canUseFSSYNC = 1;
541 opts->nLargeVnodes = 0;
542 opts->nSmallVnodes = 0;
544 opts->canScheduleSalvage = 1;
545 opts->canUseFSSYNC = 1;
555 * Set VInit to a certain value, and signal waiters.
557 * @param[in] value the value to set VInit to
562 VSetVInit_r(int value)
565 CV_BROADCAST(&vol_vinit_cond);
569 VLogOfflineTimeout(const char *type, afs_int32 timeout)
575 Log("VInitVolumePackage: Interrupting clients accessing %s "
576 "immediately\n", type);
578 Log("VInitVolumePackage: Interrupting clients accessing %s "
579 "after %ld second%s\n", type, (long)timeout, timeout==1?"":"s");
584 VInitVolumePackage2(ProgramType pt, VolumePackageOptions * opts)
586 int errors = 0; /* Number of errors while finding vice partitions. */
591 #ifndef AFS_PTHREAD_ENV
592 if (opts->offline_timeout != -1 || opts->offline_shutdown_timeout != -1) {
593 Log("VInitVolumePackage: offline_timeout and/or "
594 "offline_shutdown_timeout was specified, but the volume package "
595 "does not support these for LWP builds\n");
599 VLogOfflineTimeout("volumes going offline", opts->offline_timeout);
600 VLogOfflineTimeout("volumes going offline during shutdown",
601 opts->offline_shutdown_timeout);
603 memset(&VStats, 0, sizeof(VStats));
604 VStats.hdr_cache_size = 200;
606 VInitPartitionPackage();
608 #ifdef AFS_DEMAND_ATTACH_FS
609 if (programType == fileServer) {
612 VLRU_SetOptions(VLRU_SET_ENABLED, 0);
614 osi_Assert(pthread_key_create(&VThread_key, NULL) == 0);
617 MUTEX_INIT(&vol_glock_mutex, "vol glock", MUTEX_DEFAULT, 0);
618 MUTEX_INIT(&vol_trans_mutex, "vol trans", MUTEX_DEFAULT, 0);
619 CV_INIT(&vol_put_volume_cond, "vol put", CV_DEFAULT, 0);
620 CV_INIT(&vol_sleep_cond, "vol sleep", CV_DEFAULT, 0);
621 CV_INIT(&vol_init_attach_cond, "vol init attach", CV_DEFAULT, 0);
622 CV_INIT(&vol_vinit_cond, "vol init", CV_DEFAULT, 0);
623 #ifndef AFS_PTHREAD_ENV
625 #endif /* AFS_PTHREAD_ENV */
626 Lock_Init(&vol_listLock);
628 srandom(time(0)); /* For VGetVolumeInfo */
630 #ifdef AFS_DEMAND_ATTACH_FS
631 MUTEX_INIT(&vol_salvsync_mutex, "salvsync", MUTEX_DEFAULT, 0);
632 #endif /* AFS_DEMAND_ATTACH_FS */
634 /* Ok, we have done enough initialization that fileserver can
635 * start accepting calls, even though the volumes may not be
636 * available just yet.
640 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_SERVER)
641 if (programType == salvageServer) {
644 #endif /* AFS_DEMAND_ATTACH_FS */
645 #ifdef FSSYNC_BUILD_SERVER
646 if (programType == fileServer) {
650 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_CLIENT)
651 if (VCanUseSALVSYNC()) {
652 /* establish a connection to the salvager at this point */
653 osi_Assert(VConnectSALV() != 0);
655 #endif /* AFS_DEMAND_ATTACH_FS */
657 if (opts->volcache > VStats.hdr_cache_size)
658 VStats.hdr_cache_size = opts->volcache;
659 VInitVolumeHeaderCache(VStats.hdr_cache_size);
661 VInitVnodes(vLarge, opts->nLargeVnodes);
662 VInitVnodes(vSmall, opts->nSmallVnodes);
665 errors = VAttachPartitions();
669 if (programType != fileServer) {
670 errors = VInitAttachVolumes(programType);
676 #ifdef FSSYNC_BUILD_CLIENT
677 if (VCanUseFSSYNC()) {
679 #ifdef AFS_DEMAND_ATTACH_FS
680 if (programType == salvageServer) {
681 Log("Unable to connect to file server; aborted\n");
684 #endif /* AFS_DEMAND_ATTACH_FS */
685 Log("Unable to connect to file server; will retry at need\n");
688 #endif /* FSSYNC_BUILD_CLIENT */
693 #if !defined(AFS_PTHREAD_ENV)
695 * Attach volumes in vice partitions
697 * @param[in] pt calling program type
700 * @note This is the original, non-threaded version of attach parititions.
702 * @post VInit state is 2
705 VInitAttachVolumes(ProgramType pt)
707 osi_Assert(VInit==1);
708 if (pt == fileServer) {
709 struct DiskPartition64 *diskP;
710 /* Attach all the volumes in this partition */
711 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
712 int nAttached = 0, nUnattached = 0;
713 osi_Assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
717 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
718 LWP_NoYieldSignal(VInitAttachVolumes);
722 #endif /* !AFS_PTHREAD_ENV */
724 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_DEMAND_ATTACH_FS)
726 * Attach volumes in vice partitions
728 * @param[in] pt calling program type
731 * @note Threaded version of attach parititions.
733 * @post VInit state is 2
736 VInitAttachVolumes(ProgramType pt)
738 osi_Assert(VInit==1);
739 if (pt == fileServer) {
740 struct DiskPartition64 *diskP;
741 struct vinitvolumepackage_thread_t params;
742 struct diskpartition_queue_t * dpq;
743 int i, threads, parts;
745 pthread_attr_t attrs;
747 CV_INIT(¶ms.thread_done_cv, "thread done", CV_DEFAULT, 0);
749 params.n_threads_complete = 0;
751 /* create partition work queue */
752 for (parts=0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
753 dpq = (diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
754 osi_Assert(dpq != NULL);
756 queue_Append(¶ms,dpq);
759 threads = MIN(parts, vol_attach_threads);
762 /* spawn off a bunch of initialization threads */
763 osi_Assert(pthread_attr_init(&attrs) == 0);
764 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
766 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
767 Log("VInitVolumePackage: using %d threads to attach volumes on %d partitions\n",
771 for (i=0; i < threads; i++) {
774 osi_Assert(pthread_create
775 (&tid, &attrs, &VInitVolumePackageThread,
777 AFS_SIGSET_RESTORE();
780 while(params.n_threads_complete < threads) {
781 VOL_CV_WAIT(¶ms.thread_done_cv);
785 osi_Assert(pthread_attr_destroy(&attrs) == 0);
787 /* if we're only going to run one init thread, don't bother creating
789 Log("VInitVolumePackage: beginning single-threaded fileserver startup\n");
790 Log("VInitVolumePackage: using 1 thread to attach volumes on %d partition(s)\n",
793 VInitVolumePackageThread(¶ms);
796 CV_DESTROY(¶ms.thread_done_cv);
799 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
800 CV_BROADCAST(&vol_init_attach_cond);
806 VInitVolumePackageThread(void * args) {
808 struct DiskPartition64 *diskP;
809 struct vinitvolumepackage_thread_t * params;
810 struct diskpartition_queue_t * dpq;
812 params = (vinitvolumepackage_thread_t *) args;
816 /* Attach all the volumes in this partition */
817 while (queue_IsNotEmpty(params)) {
818 int nAttached = 0, nUnattached = 0;
820 if (vinit_attach_abort) {
821 Log("Aborting initialization\n");
825 dpq = queue_First(params,diskpartition_queue_t);
831 osi_Assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
837 params->n_threads_complete++;
838 CV_SIGNAL(¶ms->thread_done_cv);
842 #endif /* AFS_PTHREAD_ENV && !AFS_DEMAND_ATTACH_FS */
844 #if defined(AFS_DEMAND_ATTACH_FS)
846 * Attach volumes in vice partitions
848 * @param[in] pt calling program type
851 * @note Threaded version of attach partitions.
853 * @post VInit state is 2
856 VInitAttachVolumes(ProgramType pt)
858 osi_Assert(VInit==1);
859 if (pt == fileServer) {
861 struct DiskPartition64 *diskP;
862 struct partition_queue pq;
863 struct volume_init_queue vq;
865 int i, threads, parts;
867 pthread_attr_t attrs;
869 /* create partition work queue */
871 CV_INIT(&(pq.cv), "partq", CV_DEFAULT, 0);
872 MUTEX_INIT(&(pq.mutex), "partq", MUTEX_DEFAULT, 0);
873 for (parts = 0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
874 struct diskpartition_queue_t *dp;
875 dp = (struct diskpartition_queue_t*)malloc(sizeof(struct diskpartition_queue_t));
876 osi_Assert(dp != NULL);
878 queue_Append(&pq, dp);
881 /* number of worker threads; at least one, not to exceed the number of partitions */
882 threads = MIN(parts, vol_attach_threads);
884 /* create volume work queue */
886 CV_INIT(&(vq.cv), "volq", CV_DEFAULT, 0);
887 MUTEX_INIT(&(vq.mutex), "volq", MUTEX_DEFAULT, 0);
889 osi_Assert(pthread_attr_init(&attrs) == 0);
890 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
892 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
893 Log("VInitVolumePackage: using %d threads to pre-attach volumes on %d partitions\n",
896 /* create threads to scan disk partitions. */
897 for (i=0; i < threads; i++) {
898 struct vinitvolumepackage_thread_param *params;
901 params = (struct vinitvolumepackage_thread_param *)malloc(sizeof(struct vinitvolumepackage_thread_param));
905 params->nthreads = threads;
906 params->thread = i+1;
909 osi_Assert(pthread_create (&tid, &attrs, &VInitVolumePackageThread, (void*)params) == 0);
910 AFS_SIGSET_RESTORE();
913 VInitPreAttachVolumes(threads, &vq);
915 osi_Assert(pthread_attr_destroy(&attrs) == 0);
917 MUTEX_DESTROY(&pq.mutex);
919 MUTEX_DESTROY(&vq.mutex);
923 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
924 CV_BROADCAST(&vol_init_attach_cond);
931 * Volume package initialization worker thread. Scan partitions for volume
932 * header files. Gather batches of volume ids and dispatch them to
933 * the main thread to be preattached. The volume preattachement is done
934 * in the main thread to avoid global volume lock contention.
937 VInitVolumePackageThread(void *args)
939 struct vinitvolumepackage_thread_param *params;
940 struct DiskPartition64 *partition;
941 struct partition_queue *pq;
942 struct volume_init_queue *vq;
943 struct volume_init_batch *vb;
946 params = (struct vinitvolumepackage_thread_param *)args;
952 vb = (struct volume_init_batch*)malloc(sizeof(struct volume_init_batch));
954 vb->thread = params->thread;
958 Log("Scanning partitions on thread %d of %d\n", params->thread, params->nthreads);
959 while((partition = VInitNextPartition(pq))) {
963 Log("Partition %s: pre-attaching volumes\n", partition->name);
964 dirp = opendir(VPartitionPath(partition));
966 Log("opendir on Partition %s failed, errno=%d!\n", partition->name, errno);
969 while ((vid = VInitNextVolumeId(dirp))) {
970 Volume *vp = (Volume*)malloc(sizeof(Volume));
972 memset(vp, 0, sizeof(Volume));
973 vp->device = partition->device;
974 vp->partition = partition;
976 queue_Init(&vp->vnode_list);
977 queue_Init(&vp->rx_call_list);
978 CV_INIT(&V_attachCV(vp), "partattach", CV_DEFAULT, 0);
980 vb->batch[vb->size++] = vp;
981 if (vb->size == VINIT_BATCH_MAX_SIZE) {
982 MUTEX_ENTER(&vq->mutex);
983 queue_Append(vq, vb);
984 CV_BROADCAST(&vq->cv);
985 MUTEX_EXIT(&vq->mutex);
987 vb = (struct volume_init_batch*)malloc(sizeof(struct volume_init_batch));
989 vb->thread = params->thread;
998 MUTEX_ENTER(&vq->mutex);
999 queue_Append(vq, vb);
1000 CV_BROADCAST(&vq->cv);
1001 MUTEX_EXIT(&vq->mutex);
1003 Log("Partition scan thread %d of %d ended\n", params->thread, params->nthreads);
1009 * Read next element from the pre-populated partition list.
1011 static struct DiskPartition64*
1012 VInitNextPartition(struct partition_queue *pq)
1014 struct DiskPartition64 *partition;
1015 struct diskpartition_queue_t *dp; /* queue element */
1017 if (vinit_attach_abort) {
1018 Log("Aborting volume preattach thread.\n");
1022 /* get next partition to scan */
1023 MUTEX_ENTER(&pq->mutex);
1024 if (queue_IsEmpty(pq)) {
1025 MUTEX_EXIT(&pq->mutex);
1028 dp = queue_First(pq, diskpartition_queue_t);
1030 MUTEX_EXIT(&pq->mutex);
1033 osi_Assert(dp->diskP);
1035 partition = dp->diskP;
1041 * Find next volume id on the partition.
1044 VInitNextVolumeId(DIR *dirp)
1050 while((d = readdir(dirp))) {
1051 if (vinit_attach_abort) {
1052 Log("Aborting volume preattach thread.\n");
1055 ext = strrchr(d->d_name, '.');
1056 if (d->d_name[0] == 'V' && ext && strcmp(ext, VHDREXT) == 0) {
1057 vid = VolumeNumber(d->d_name);
1061 Log("Warning: bogus volume header file: %s\n", d->d_name);
1068 * Preattach volumes in batches to avoid lock contention.
1071 VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq)
1073 struct volume_init_batch *vb;
1077 /* dequeue next volume */
1078 MUTEX_ENTER(&vq->mutex);
1079 if (queue_IsEmpty(vq)) {
1080 CV_WAIT(&vq->cv, &vq->mutex);
1082 vb = queue_First(vq, volume_init_batch);
1084 MUTEX_EXIT(&vq->mutex);
1088 for (i = 0; i<vb->size; i++) {
1094 dup = VLookupVolume_r(&ec, vp->hashid, NULL);
1096 Log("Error looking up volume, code=%d\n", ec);
1099 Log("Warning: Duplicate volume id %d detected.\n", vp->hashid);
1102 /* put pre-attached volume onto the hash table
1103 * and bring it up to the pre-attached state */
1104 AddVolumeToHashTable(vp, vp->hashid);
1105 AddVolumeToVByPList_r(vp);
1106 VLRU_Init_Node_r(vp);
1107 VChangeState_r(vp, VOL_STATE_PREATTACHED);
1120 #endif /* AFS_DEMAND_ATTACH_FS */
1122 #if !defined(AFS_DEMAND_ATTACH_FS)
1124 * attach all volumes on a given disk partition
1127 VAttachVolumesByPartition(struct DiskPartition64 *diskP, int * nAttached, int * nUnattached)
1133 Log("Partition %s: attaching volumes\n", diskP->name);
1134 dirp = opendir(VPartitionPath(diskP));
1136 Log("opendir on Partition %s failed!\n", diskP->name);
1140 while ((dp = readdir(dirp))) {
1142 p = strrchr(dp->d_name, '.');
1144 if (vinit_attach_abort) {
1145 Log("Partition %s: abort attach volumes\n", diskP->name);
1149 if (p != NULL && strcmp(p, VHDREXT) == 0) {
1152 vp = VAttachVolumeByName(&error, diskP->name, dp->d_name,
1154 (*(vp ? nAttached : nUnattached))++;
1155 if (error == VOFFLINE)
1156 Log("Volume %d stays offline (/vice/offline/%s exists)\n", VolumeNumber(dp->d_name), dp->d_name);
1157 else if (LogLevel >= 5) {
1158 Log("Partition %s: attached volume %d (%s)\n",
1159 diskP->name, VolumeNumber(dp->d_name),
1168 Log("Partition %s: attached %d volumes; %d volumes not attached\n", diskP->name, *nAttached, *nUnattached);
1173 #endif /* !AFS_DEMAND_ATTACH_FS */
1175 /***************************************************/
1176 /* Shutdown routines */
1177 /***************************************************/
1181 * highly multithreaded volume package shutdown
1183 * with the demand attach fileserver extensions,
1184 * VShutdown has been modified to be multithreaded.
1185 * In order to achieve optimal use of many threads,
1186 * the shutdown code involves one control thread and
1187 * n shutdown worker threads. The control thread
1188 * periodically examines the number of volumes available
1189 * for shutdown on each partition, and produces a worker
1190 * thread allocation schedule. The idea is to eliminate
1191 * redundant scheduling computation on the workers by
1192 * having a single master scheduler.
1194 * The scheduler's objectives are:
1196 * each partition with volumes remaining gets allocated
1197 * at least 1 thread (assuming sufficient threads)
1199 * threads are allocated proportional to the number of
1200 * volumes remaining to be offlined. This ensures that
1201 * the OS I/O scheduler has many requests to elevator
1202 * seek on partitions that will (presumably) take the
1203 * longest amount of time (from now) to finish shutdown
1204 * (3) keep threads busy
1205 * when there are extra threads, they are assigned to
1206 * partitions using a simple round-robin algorithm
1208 * In the future, we may wish to add the ability to adapt
1209 * to the relative performance patterns of each disk
1214 * multi-step shutdown process
1216 * demand attach shutdown is a four-step process. Each
1217 * shutdown "pass" shuts down increasingly more difficult
1218 * volumes. The main purpose is to achieve better cache
1219 * utilization during shutdown.
1222 * shutdown volumes in the unattached, pre-attached
1225 * shutdown attached volumes with cached volume headers
1227 * shutdown all volumes in non-exclusive states
1229 * shutdown all remaining volumes
1232 #ifdef AFS_DEMAND_ATTACH_FS
1238 struct DiskPartition64 * diskP;
1239 struct diskpartition_queue_t * dpq;
1240 vshutdown_thread_t params;
1242 pthread_attr_t attrs;
1244 memset(¶ms, 0, sizeof(vshutdown_thread_t));
1247 Log("VShutdown: aborting attach volumes\n");
1248 vinit_attach_abort = 1;
1249 VOL_CV_WAIT(&vol_init_attach_cond);
1252 for (params.n_parts=0, diskP = DiskPartitionList;
1253 diskP; diskP = diskP->next, params.n_parts++);
1255 Log("VShutdown: shutting down on-line volumes on %d partition%s...\n",
1256 params.n_parts, params.n_parts > 1 ? "s" : "");
1258 vol_shutting_down = 1;
1260 if (vol_attach_threads > 1) {
1261 /* prepare for parallel shutdown */
1262 params.n_threads = vol_attach_threads;
1263 MUTEX_INIT(¶ms.lock, "params", MUTEX_DEFAULT, 0);
1264 CV_INIT(¶ms.cv, "params", CV_DEFAULT, 0);
1265 CV_INIT(¶ms.master_cv, "params master", CV_DEFAULT, 0);
1266 osi_Assert(pthread_attr_init(&attrs) == 0);
1267 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
1268 queue_Init(¶ms);
1270 /* setup the basic partition information structures for
1271 * parallel shutdown */
1272 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1274 struct rx_queue * qp, * nqp;
1278 VVByPListWait_r(diskP);
1279 VVByPListBeginExclusive_r(diskP);
1282 for (queue_Scan(&diskP->vol_list, qp, nqp, rx_queue)) {
1283 vp = (Volume *)((char *)qp - offsetof(Volume, vol_list));
1287 Log("VShutdown: partition %s has %d volumes with attached headers\n",
1288 VPartitionPath(diskP), count);
1291 /* build up the pass 0 shutdown work queue */
1292 dpq = (struct diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
1293 osi_Assert(dpq != NULL);
1295 queue_Prepend(¶ms, dpq);
1297 params.part_pass_head[diskP->index] = queue_First(&diskP->vol_list, rx_queue);
1300 Log("VShutdown: beginning parallel fileserver shutdown\n");
1301 Log("VShutdown: using %d threads to offline volumes on %d partition%s\n",
1302 vol_attach_threads, params.n_parts, params.n_parts > 1 ? "s" : "" );
1304 /* do pass 0 shutdown */
1305 MUTEX_ENTER(¶ms.lock);
1306 for (i=0; i < params.n_threads; i++) {
1307 osi_Assert(pthread_create
1308 (&tid, &attrs, &VShutdownThread,
1312 /* wait for all the pass 0 shutdowns to complete */
1313 while (params.n_threads_complete < params.n_threads) {
1314 CV_WAIT(¶ms.master_cv, ¶ms.lock);
1316 params.n_threads_complete = 0;
1318 CV_BROADCAST(¶ms.cv);
1319 MUTEX_EXIT(¶ms.lock);
1321 Log("VShutdown: pass 0 completed using the 1 thread per partition algorithm\n");
1322 Log("VShutdown: starting passes 1 through 3 using finely-granular mp-fast algorithm\n");
1324 /* run the parallel shutdown scheduler. it will drop the glock internally */
1325 ShutdownController(¶ms);
1327 /* wait for all the workers to finish pass 3 and terminate */
1328 while (params.pass < 4) {
1329 VOL_CV_WAIT(¶ms.cv);
1332 osi_Assert(pthread_attr_destroy(&attrs) == 0);
1333 CV_DESTROY(¶ms.cv);
1334 CV_DESTROY(¶ms.master_cv);
1335 MUTEX_DESTROY(¶ms.lock);
1337 /* drop the VByPList exclusive reservations */
1338 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1339 VVByPListEndExclusive_r(diskP);
1340 Log("VShutdown: %s stats : (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1341 VPartitionPath(diskP),
1342 params.stats[0][diskP->index],
1343 params.stats[1][diskP->index],
1344 params.stats[2][diskP->index],
1345 params.stats[3][diskP->index]);
1348 Log("VShutdown: shutdown finished using %d threads\n", params.n_threads);
1350 /* if we're only going to run one shutdown thread, don't bother creating
1352 Log("VShutdown: beginning single-threaded fileserver shutdown\n");
1354 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1355 VShutdownByPartition_r(diskP);
1359 Log("VShutdown: complete.\n");
1362 #else /* AFS_DEMAND_ATTACH_FS */
1372 Log("VShutdown: aborting attach volumes\n");
1373 vinit_attach_abort = 1;
1374 #ifdef AFS_PTHREAD_ENV
1375 VOL_CV_WAIT(&vol_init_attach_cond);
1377 LWP_WaitProcess(VInitAttachVolumes);
1378 #endif /* AFS_PTHREAD_ENV */
1381 Log("VShutdown: shutting down on-line volumes...\n");
1382 vol_shutting_down = 1;
1383 for (i = 0; i < VolumeHashTable.Size; i++) {
1384 /* try to hold first volume in the hash table */
1385 for (queue_Scan(&VolumeHashTable.Table[i],vp,np,Volume)) {
1389 Log("VShutdown: Attempting to take volume %u offline.\n",
1392 /* next, take the volume offline (drops reference count) */
1393 VOffline_r(vp, "File server was shut down");
1397 Log("VShutdown: complete.\n");
1399 #endif /* AFS_DEMAND_ATTACH_FS */
1405 osi_Assert(VInit>0);
1412 * stop new activity (e.g. SALVSYNC) from occurring
1414 * Use this to make the volume package less busy; for example, during
1415 * shutdown. This doesn't actually shutdown/detach anything in the
1416 * volume package, but prevents certain processes from ocurring. For
1417 * example, preventing new SALVSYNC communication in DAFS. In theory, we
1418 * could also use this to prevent new volume attachment, or prevent
1419 * other programs from checking out volumes, etc.
1424 #ifdef AFS_DEMAND_ATTACH_FS
1425 /* make sure we don't try to contact the salvageserver, since it may
1426 * not be around anymore */
1427 vol_disallow_salvsync = 1;
1431 #ifdef AFS_DEMAND_ATTACH_FS
1434 * shutdown control thread
1437 ShutdownController(vshutdown_thread_t * params)
1440 struct DiskPartition64 * diskP;
1442 vshutdown_thread_t shadow;
1444 ShutdownCreateSchedule(params);
1446 while ((params->pass < 4) &&
1447 (params->n_threads_complete < params->n_threads)) {
1448 /* recompute schedule once per second */
1450 memcpy(&shadow, params, sizeof(vshutdown_thread_t));
1454 Log("ShutdownController: schedule version=%d, vol_remaining=%d, pass=%d\n",
1455 shadow.schedule_version, shadow.vol_remaining, shadow.pass);
1456 Log("ShutdownController: n_threads_complete=%d, n_parts_done_pass=%d\n",
1457 shadow.n_threads_complete, shadow.n_parts_done_pass);
1458 for (diskP = DiskPartitionList; diskP; diskP=diskP->next) {
1460 Log("ShutdownController: part[%d] : (len=%d, thread_target=%d, done_pass=%d, pass_head=%p)\n",
1462 diskP->vol_list.len,
1463 shadow.part_thread_target[id],
1464 shadow.part_done_pass[id],
1465 shadow.part_pass_head[id]);
1471 ShutdownCreateSchedule(params);
1475 /* create the shutdown thread work schedule.
1476 * this scheduler tries to implement fairness
1477 * by allocating at least 1 thread to each
1478 * partition with volumes to be shutdown,
1479 * and then it attempts to allocate remaining
1480 * threads based upon the amount of work left
1483 ShutdownCreateSchedule(vshutdown_thread_t * params)
1485 struct DiskPartition64 * diskP;
1486 int sum, thr_workload, thr_left;
1487 int part_residue[VOLMAXPARTS+1];
1490 /* compute the total number of outstanding volumes */
1492 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1493 sum += diskP->vol_list.len;
1496 params->schedule_version++;
1497 params->vol_remaining = sum;
1502 /* compute average per-thread workload */
1503 thr_workload = sum / params->n_threads;
1504 if (sum % params->n_threads)
1507 thr_left = params->n_threads;
1508 memset(&part_residue, 0, sizeof(part_residue));
1510 /* for fairness, give every partition with volumes remaining
1511 * at least one thread */
1512 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1514 if (diskP->vol_list.len) {
1515 params->part_thread_target[id] = 1;
1518 params->part_thread_target[id] = 0;
1522 if (thr_left && thr_workload) {
1523 /* compute length-weighted workloads */
1526 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1528 delta = (diskP->vol_list.len / thr_workload) -
1529 params->part_thread_target[id];
1533 if (delta < thr_left) {
1534 params->part_thread_target[id] += delta;
1537 params->part_thread_target[id] += thr_left;
1545 /* try to assign any leftover threads to partitions that
1546 * had volume lengths closer to needing thread_target+1 */
1547 int max_residue, max_id = 0;
1549 /* compute the residues */
1550 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1552 part_residue[id] = diskP->vol_list.len -
1553 (params->part_thread_target[id] * thr_workload);
1556 /* now try to allocate remaining threads to partitions with the
1557 * highest residues */
1560 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1562 if (part_residue[id] > max_residue) {
1563 max_residue = part_residue[id];
1572 params->part_thread_target[max_id]++;
1574 part_residue[max_id] = 0;
1579 /* punt and give any remaining threads equally to each partition */
1581 if (thr_left >= params->n_parts) {
1582 alloc = thr_left / params->n_parts;
1583 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1585 params->part_thread_target[id] += alloc;
1590 /* finish off the last of the threads */
1591 for (diskP = DiskPartitionList; thr_left && diskP; diskP = diskP->next) {
1593 params->part_thread_target[id]++;
1599 /* worker thread for parallel shutdown */
1601 VShutdownThread(void * args)
1603 vshutdown_thread_t * params;
1604 int found, pass, schedule_version_save, count;
1605 struct DiskPartition64 *diskP;
1606 struct diskpartition_queue_t * dpq;
1609 params = (vshutdown_thread_t *) args;
1611 /* acquire the shutdown pass 0 lock */
1612 MUTEX_ENTER(¶ms->lock);
1614 /* if there's still pass 0 work to be done,
1615 * get a work entry, and do a pass 0 shutdown */
1616 if (queue_IsNotEmpty(params)) {
1617 dpq = queue_First(params, diskpartition_queue_t);
1619 MUTEX_EXIT(¶ms->lock);
1625 while (ShutdownVolumeWalk_r(diskP, 0, ¶ms->part_pass_head[id]))
1627 params->stats[0][diskP->index] = count;
1628 MUTEX_ENTER(¶ms->lock);
1631 params->n_threads_complete++;
1632 if (params->n_threads_complete == params->n_threads) {
1633 /* notify control thread that all workers have completed pass 0 */
1634 CV_SIGNAL(¶ms->master_cv);
1636 while (params->pass == 0) {
1637 CV_WAIT(¶ms->cv, ¶ms->lock);
1641 MUTEX_EXIT(¶ms->lock);
1644 pass = params->pass;
1645 osi_Assert(pass > 0);
1647 /* now escalate through the more complicated shutdowns */
1649 schedule_version_save = params->schedule_version;
1651 /* find a disk partition to work on */
1652 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1654 if (params->part_thread_target[id] && !params->part_done_pass[id]) {
1655 params->part_thread_target[id]--;
1662 /* hmm. for some reason the controller thread couldn't find anything for
1663 * us to do. let's see if there's anything we can do */
1664 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1666 if (diskP->vol_list.len && !params->part_done_pass[id]) {
1669 } else if (!params->part_done_pass[id]) {
1670 params->part_done_pass[id] = 1;
1671 params->n_parts_done_pass++;
1673 Log("VShutdown: done shutting down volumes on partition %s.\n",
1674 VPartitionPath(diskP));
1680 /* do work on this partition until either the controller
1681 * creates a new schedule, or we run out of things to do
1682 * on this partition */
1685 while (!params->part_done_pass[id] &&
1686 (schedule_version_save == params->schedule_version)) {
1687 /* ShutdownVolumeWalk_r will drop the glock internally */
1688 if (!ShutdownVolumeWalk_r(diskP, pass, ¶ms->part_pass_head[id])) {
1689 if (!params->part_done_pass[id]) {
1690 params->part_done_pass[id] = 1;
1691 params->n_parts_done_pass++;
1693 Log("VShutdown: done shutting down volumes on partition %s.\n",
1694 VPartitionPath(diskP));
1702 params->stats[pass][id] += count;
1704 /* ok, everyone is done this pass, proceed */
1707 params->n_threads_complete++;
1708 while (params->pass == pass) {
1709 if (params->n_threads_complete == params->n_threads) {
1710 /* we are the last thread to complete, so we will
1711 * reinitialize worker pool state for the next pass */
1712 params->n_threads_complete = 0;
1713 params->n_parts_done_pass = 0;
1715 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1717 params->part_done_pass[id] = 0;
1718 params->part_pass_head[id] = queue_First(&diskP->vol_list, rx_queue);
1721 /* compute a new thread schedule before releasing all the workers */
1722 ShutdownCreateSchedule(params);
1724 /* wake up all the workers */
1725 CV_BROADCAST(¶ms->cv);
1728 Log("VShutdown: pass %d completed using %d threads on %d partitions\n",
1729 pass, params->n_threads, params->n_parts);
1732 VOL_CV_WAIT(¶ms->cv);
1735 pass = params->pass;
1749 /* shut down all volumes on a given disk partition
1751 * note that this function will not allow mp-fast
1752 * shutdown of a partition */
1754 VShutdownByPartition_r(struct DiskPartition64 * dp)
1760 /* wait for other exclusive ops to finish */
1761 VVByPListWait_r(dp);
1763 /* begin exclusive access */
1764 VVByPListBeginExclusive_r(dp);
1766 /* pick the low-hanging fruit first,
1767 * then do the complicated ones last
1768 * (has the advantage of keeping
1769 * in-use volumes up until the bitter end) */
1770 for (pass = 0, total=0; pass < 4; pass++) {
1771 pass_stats[pass] = ShutdownVByPForPass_r(dp, pass);
1772 total += pass_stats[pass];
1775 /* end exclusive access */
1776 VVByPListEndExclusive_r(dp);
1778 Log("VShutdownByPartition: shut down %d volumes on %s (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1779 total, VPartitionPath(dp), pass_stats[0], pass_stats[1], pass_stats[2], pass_stats[3]);
1784 /* internal shutdown functionality
1786 * for multi-pass shutdown:
1787 * 0 to only "shutdown" {pre,un}attached and error state volumes
1788 * 1 to also shutdown attached volumes w/ volume header loaded
1789 * 2 to also shutdown attached volumes w/o volume header loaded
1790 * 3 to also shutdown exclusive state volumes
1792 * caller MUST hold exclusive access on the hash chain
1793 * because we drop vol_glock_mutex internally
1795 * this function is reentrant for passes 1--3
1796 * (e.g. multiple threads can cooperate to
1797 * shutdown a partition mp-fast)
1799 * pass 0 is not scaleable because the volume state data is
1800 * synchronized by vol_glock mutex, and the locking overhead
1801 * is too high to drop the lock long enough to do linked list
1805 ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass)
1807 struct rx_queue * q = queue_First(&dp->vol_list, rx_queue);
1810 while (ShutdownVolumeWalk_r(dp, pass, &q))
1816 /* conditionally shutdown one volume on partition dp
1817 * returns 1 if a volume was shutdown in this pass,
1820 ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
1821 struct rx_queue ** idx)
1823 struct rx_queue *qp, *nqp;
1828 for (queue_ScanFrom(&dp->vol_list, qp, qp, nqp, rx_queue)) {
1829 vp = (Volume *) (((char *)qp) - offsetof(Volume, vol_list));
1833 if ((V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1834 (V_attachState(vp) != VOL_STATE_ERROR) &&
1835 (V_attachState(vp) != VOL_STATE_DELETED) &&
1836 (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1840 if ((V_attachState(vp) == VOL_STATE_ATTACHED) &&
1841 (vp->header == NULL)) {
1845 if (VIsExclusiveState(V_attachState(vp))) {
1850 DeleteVolumeFromVByPList_r(vp);
1851 VShutdownVolume_r(vp);
1861 * shutdown a specific volume
1863 /* caller MUST NOT hold a heavyweight ref on vp */
1865 VShutdownVolume_r(Volume * vp)
1869 VCreateReservation_r(vp);
1871 if (LogLevel >= 5) {
1872 Log("VShutdownVolume_r: vid=%u, device=%d, state=%hu\n",
1873 vp->hashid, vp->partition->device, V_attachState(vp));
1876 /* wait for other blocking ops to finish */
1877 VWaitExclusiveState_r(vp);
1879 osi_Assert(VIsValidState(V_attachState(vp)));
1881 switch(V_attachState(vp)) {
1882 case VOL_STATE_SALVAGING:
1883 /* Leave salvaging volumes alone. Any in-progress salvages will
1884 * continue working after viced shuts down. This is intentional.
1887 case VOL_STATE_PREATTACHED:
1888 case VOL_STATE_ERROR:
1889 VChangeState_r(vp, VOL_STATE_UNATTACHED);
1890 case VOL_STATE_UNATTACHED:
1891 case VOL_STATE_DELETED:
1893 case VOL_STATE_GOING_OFFLINE:
1894 case VOL_STATE_SHUTTING_DOWN:
1895 case VOL_STATE_ATTACHED:
1899 Log("VShutdown: Attempting to take volume %u offline.\n",
1902 /* take the volume offline (drops reference count) */
1903 VOffline_r(vp, "File server was shut down");
1910 VCancelReservation_r(vp);
1914 #endif /* AFS_DEMAND_ATTACH_FS */
1917 /***************************************************/
1918 /* Header I/O routines */
1919 /***************************************************/
1921 /* open a descriptor for the inode (h),
1922 * read in an on-disk structure into buffer (to) of size (size),
1923 * verify versionstamp in structure has magic (magic) and
1924 * optionally verify version (version) if (version) is nonzero
1927 ReadHeader(Error * ec, IHandle_t * h, char *to, int size, bit32 magic,
1930 struct versionStamp *vsn;
1945 vsn = (struct versionStamp *)to;
1946 if (FDH_PREAD(fdP, to, size, 0) != size || vsn->magic != magic) {
1948 FDH_REALLYCLOSE(fdP);
1953 /* Check is conditional, in case caller wants to inspect version himself */
1954 if (version && vsn->version != version) {
1960 WriteVolumeHeader_r(Error * ec, Volume * vp)
1962 IHandle_t *h = V_diskDataHandle(vp);
1972 if (FDH_PWRITE(fdP, (char *)&V_disk(vp), sizeof(V_disk(vp)), 0)
1973 != sizeof(V_disk(vp))) {
1975 FDH_REALLYCLOSE(fdP);
1981 /* VolumeHeaderToDisk
1982 * Allows for storing 64 bit inode numbers in on-disk volume header
1985 /* convert in-memory representation of a volume header to the
1986 * on-disk representation of a volume header */
1988 VolumeHeaderToDisk(VolumeDiskHeader_t * dh, VolumeHeader_t * h)
1991 memset(dh, 0, sizeof(VolumeDiskHeader_t));
1992 dh->stamp = h->stamp;
1994 dh->parent = h->parent;
1996 #ifdef AFS_64BIT_IOPS_ENV
1997 dh->volumeInfo_lo = (afs_int32) h->volumeInfo & 0xffffffff;
1998 dh->volumeInfo_hi = (afs_int32) (h->volumeInfo >> 32) & 0xffffffff;
1999 dh->smallVnodeIndex_lo = (afs_int32) h->smallVnodeIndex & 0xffffffff;
2000 dh->smallVnodeIndex_hi =
2001 (afs_int32) (h->smallVnodeIndex >> 32) & 0xffffffff;
2002 dh->largeVnodeIndex_lo = (afs_int32) h->largeVnodeIndex & 0xffffffff;
2003 dh->largeVnodeIndex_hi =
2004 (afs_int32) (h->largeVnodeIndex >> 32) & 0xffffffff;
2005 dh->linkTable_lo = (afs_int32) h->linkTable & 0xffffffff;
2006 dh->linkTable_hi = (afs_int32) (h->linkTable >> 32) & 0xffffffff;
2008 dh->volumeInfo_lo = h->volumeInfo;
2009 dh->smallVnodeIndex_lo = h->smallVnodeIndex;
2010 dh->largeVnodeIndex_lo = h->largeVnodeIndex;
2011 dh->linkTable_lo = h->linkTable;
2015 /* DiskToVolumeHeader
2016 * Converts an on-disk representation of a volume header to
2017 * the in-memory representation of a volume header.
2019 * Makes the assumption that AFS has *always*
2020 * zero'd the volume header file so that high parts of inode
2021 * numbers are 0 in older (SGI EFS) volume header files.
2024 DiskToVolumeHeader(VolumeHeader_t * h, VolumeDiskHeader_t * dh)
2026 memset(h, 0, sizeof(VolumeHeader_t));
2027 h->stamp = dh->stamp;
2029 h->parent = dh->parent;
2031 #ifdef AFS_64BIT_IOPS_ENV
2033 (Inode) dh->volumeInfo_lo | ((Inode) dh->volumeInfo_hi << 32);
2035 h->smallVnodeIndex =
2036 (Inode) dh->smallVnodeIndex_lo | ((Inode) dh->
2037 smallVnodeIndex_hi << 32);
2039 h->largeVnodeIndex =
2040 (Inode) dh->largeVnodeIndex_lo | ((Inode) dh->
2041 largeVnodeIndex_hi << 32);
2043 (Inode) dh->linkTable_lo | ((Inode) dh->linkTable_hi << 32);
2045 h->volumeInfo = dh->volumeInfo_lo;
2046 h->smallVnodeIndex = dh->smallVnodeIndex_lo;
2047 h->largeVnodeIndex = dh->largeVnodeIndex_lo;
2048 h->linkTable = dh->linkTable_lo;
2053 /***************************************************/
2054 /* Volume Attachment routines */
2055 /***************************************************/
2057 #ifdef AFS_DEMAND_ATTACH_FS
2059 * pre-attach a volume given its path.
2061 * @param[out] ec outbound error code
2062 * @param[in] partition partition path string
2063 * @param[in] name volume id string
2065 * @return volume object pointer
2067 * @note A pre-attached volume will only have its partition
2068 * and hashid fields initialized. At first call to
2069 * VGetVolume, the volume will be fully attached.
2073 VPreAttachVolumeByName(Error * ec, char *partition, char *name)
2077 vp = VPreAttachVolumeByName_r(ec, partition, name);
2083 * pre-attach a volume given its path.
2085 * @param[out] ec outbound error code
2086 * @param[in] partition path to vice partition
2087 * @param[in] name volume id string
2089 * @return volume object pointer
2091 * @pre VOL_LOCK held
2093 * @internal volume package internal use only.
2096 VPreAttachVolumeByName_r(Error * ec, char *partition, char *name)
2098 return VPreAttachVolumeById_r(ec,
2100 VolumeNumber(name));
2104 * pre-attach a volume given its path and numeric volume id.
2106 * @param[out] ec error code return
2107 * @param[in] partition path to vice partition
2108 * @param[in] volumeId numeric volume id
2110 * @return volume object pointer
2112 * @pre VOL_LOCK held
2114 * @internal volume package internal use only.
2117 VPreAttachVolumeById_r(Error * ec,
2122 struct DiskPartition64 *partp;
2126 osi_Assert(programType == fileServer);
2128 if (!(partp = VGetPartition_r(partition, 0))) {
2130 Log("VPreAttachVolumeById_r: Error getting partition (%s)\n", partition);
2134 vp = VLookupVolume_r(ec, volumeId, NULL);
2139 return VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2143 * preattach a volume.
2145 * @param[out] ec outbound error code
2146 * @param[in] partp pointer to partition object
2147 * @param[in] vp pointer to volume object
2148 * @param[in] vid volume id
2150 * @return volume object pointer
2152 * @pre VOL_LOCK is held.
2154 * @warning Returned volume object pointer does not have to
2155 * equal the pointer passed in as argument vp. There
2156 * are potential race conditions which can result in
2157 * the pointers having different values. It is up to
2158 * the caller to make sure that references are handled
2159 * properly in this case.
2161 * @note If there is already a volume object registered with
2162 * the same volume id, its pointer MUST be passed as
2163 * argument vp. Failure to do so will result in a silent
2164 * failure to preattach.
2166 * @internal volume package internal use only.
2169 VPreAttachVolumeByVp_r(Error * ec,
2170 struct DiskPartition64 * partp,
2178 /* check to see if pre-attach already happened */
2180 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
2181 (V_attachState(vp) != VOL_STATE_DELETED) &&
2182 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
2183 !VIsErrorState(V_attachState(vp))) {
2185 * pre-attach is a no-op in all but the following cases:
2187 * - volume is unattached
2188 * - volume is in an error state
2189 * - volume is pre-attached
2191 Log("VPreattachVolumeByVp_r: volume %u not in quiescent state\n", vid);
2194 /* we're re-attaching a volume; clear out some old state */
2195 memset(&vp->salvage, 0, sizeof(struct VolumeOnlineSalvage));
2197 if (V_partition(vp) != partp) {
2198 /* XXX potential race */
2199 DeleteVolumeFromVByPList_r(vp);
2202 /* if we need to allocate a new Volume struct,
2203 * go ahead and drop the vol glock, otherwise
2204 * do the basic setup synchronised, as it's
2205 * probably not worth dropping the lock */
2208 /* allocate the volume structure */
2209 vp = nvp = (Volume *) malloc(sizeof(Volume));
2210 osi_Assert(vp != NULL);
2211 memset(vp, 0, sizeof(Volume));
2212 queue_Init(&vp->vnode_list);
2213 queue_Init(&vp->rx_call_list);
2214 CV_INIT(&V_attachCV(vp), "vp attach", CV_DEFAULT, 0);
2217 /* link the volume with its associated vice partition */
2218 vp->device = partp->device;
2219 vp->partition = partp;
2222 vp->specialStatus = 0;
2224 /* if we dropped the lock, reacquire the lock,
2225 * check for pre-attach races, and then add
2226 * the volume to the hash table */
2229 nvp = VLookupVolume_r(ec, vid, NULL);
2234 } else if (nvp) { /* race detected */
2239 /* hack to make up for VChangeState_r() decrementing
2240 * the old state counter */
2241 VStats.state_levels[0]++;
2245 /* put pre-attached volume onto the hash table
2246 * and bring it up to the pre-attached state */
2247 AddVolumeToHashTable(vp, vp->hashid);
2248 AddVolumeToVByPList_r(vp);
2249 VLRU_Init_Node_r(vp);
2250 VChangeState_r(vp, VOL_STATE_PREATTACHED);
2253 Log("VPreAttachVolumeByVp_r: volume %u pre-attached\n", vp->hashid);
2261 #endif /* AFS_DEMAND_ATTACH_FS */
2263 /* Attach an existing volume, given its pathname, and return a
2264 pointer to the volume header information. The volume also
2265 normally goes online at this time. An offline volume
2266 must be reattached to make it go online */
2268 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
2272 retVal = VAttachVolumeByName_r(ec, partition, name, mode);
2278 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
2281 struct DiskPartition64 *partp;
2286 #ifdef AFS_DEMAND_ATTACH_FS
2287 VolumeStats stats_save;
2289 #endif /* AFS_DEMAND_ATTACH_FS */
2293 volumeId = VolumeNumber(name);
2295 if (!(partp = VGetPartition_r(partition, 0))) {
2297 Log("VAttachVolume: Error getting partition (%s)\n", partition);
2301 if (VRequiresPartLock()) {
2302 osi_Assert(VInit == 3);
2303 VLockPartition_r(partition);
2304 } else if (programType == fileServer) {
2305 #ifdef AFS_DEMAND_ATTACH_FS
2306 /* lookup the volume in the hash table */
2307 vp = VLookupVolume_r(ec, volumeId, NULL);
2313 /* save any counters that are supposed to
2314 * be monotonically increasing over the
2315 * lifetime of the fileserver */
2316 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2318 memset(&stats_save, 0, sizeof(VolumeStats));
2321 /* if there's something in the hash table, and it's not
2322 * in the pre-attach state, then we may need to detach
2323 * it before proceeding */
2324 if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
2325 VCreateReservation_r(vp);
2326 VWaitExclusiveState_r(vp);
2328 /* at this point state must be one of:
2338 if (vp->specialStatus == VBUSY)
2341 /* if it's already attached, see if we can return it */
2342 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2343 VGetVolumeByVp_r(ec, vp);
2344 if (V_inUse(vp) == fileServer) {
2345 VCancelReservation_r(vp);
2349 /* otherwise, we need to detach, and attempt to re-attach */
2350 VDetachVolume_r(ec, vp);
2352 Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
2355 /* if it isn't fully attached, delete from the hash tables,
2356 and let the refcounter handle the rest */
2357 DeleteVolumeFromHashTable(vp);
2358 DeleteVolumeFromVByPList_r(vp);
2361 VCancelReservation_r(vp);
2365 /* pre-attach volume if it hasn't been done yet */
2367 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2368 (V_attachState(vp) == VOL_STATE_DELETED) ||
2369 (V_attachState(vp) == VOL_STATE_ERROR)) {
2371 vp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2377 osi_Assert(vp != NULL);
2379 /* handle pre-attach races
2381 * multiple threads can race to pre-attach a volume,
2382 * but we can't let them race beyond that
2384 * our solution is to let the first thread to bring
2385 * the volume into an exclusive state win; the other
2386 * threads just wait until it finishes bringing the
2387 * volume online, and then they do a vgetvolumebyvp
2389 if (svp && (svp != vp)) {
2390 /* wait for other exclusive ops to finish */
2391 VCreateReservation_r(vp);
2392 VWaitExclusiveState_r(vp);
2394 /* get a heavyweight ref, kill the lightweight ref, and return */
2395 VGetVolumeByVp_r(ec, vp);
2396 VCancelReservation_r(vp);
2400 /* at this point, we are chosen as the thread to do
2401 * demand attachment for this volume. all other threads
2402 * doing a getvolume on vp->hashid will block until we finish */
2404 /* make sure any old header cache entries are invalidated
2405 * before proceeding */
2406 FreeVolumeHeader(vp);
2408 VChangeState_r(vp, VOL_STATE_ATTACHING);
2410 /* restore any saved counters */
2411 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2412 #else /* AFS_DEMAND_ATTACH_FS */
2413 vp = VGetVolume_r(ec, volumeId);
2415 if (V_inUse(vp) == fileServer)
2417 if (vp->specialStatus == VBUSY)
2419 VDetachVolume_r(ec, vp);
2421 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2425 #endif /* AFS_DEMAND_ATTACH_FS */
2429 strcpy(path, VPartitionPath(partp));
2433 strcat(path, OS_DIRSEP);
2437 vp = (Volume *) calloc(1, sizeof(Volume));
2438 osi_Assert(vp != NULL);
2439 vp->hashid = volumeId;
2440 vp->device = partp->device;
2441 vp->partition = partp;
2442 queue_Init(&vp->vnode_list);
2443 queue_Init(&vp->rx_call_list);
2444 #ifdef AFS_DEMAND_ATTACH_FS
2445 CV_INIT(&V_attachCV(vp), "vp attach", CV_DEFAULT, 0);
2446 #endif /* AFS_DEMAND_ATTACH_FS */
2449 /* attach2 is entered without any locks, and returns
2450 * with vol_glock_mutex held */
2451 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2453 if (VCanUseFSSYNC() && vp) {
2454 #ifdef AFS_DEMAND_ATTACH_FS
2455 if ((mode == V_VOLUPD) || (VolumeWriteable(vp) && (mode == V_CLONE))) {
2456 /* mark volume header as in use so that volser crashes lead to a
2457 * salvage attempt */
2458 VUpdateVolume_r(ec, vp, 0);
2460 /* for dafs, we should tell the fileserver, except for V_PEEK
2461 * where we know it is not necessary */
2462 if (mode == V_PEEK) {
2463 vp->needsPutBack = 0;
2465 vp->needsPutBack = VOL_PUTBACK;
2467 #else /* !AFS_DEMAND_ATTACH_FS */
2468 /* duplicate computation in fssync.c about whether the server
2469 * takes the volume offline or not. If the volume isn't
2470 * offline, we must not return it when we detach the volume,
2471 * or the server will abort */
2472 if (mode == V_READONLY || mode == V_PEEK
2473 || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
2474 vp->needsPutBack = 0;
2476 vp->needsPutBack = VOL_PUTBACK;
2477 #endif /* !AFS_DEMAND_ATTACH_FS */
2479 #ifdef FSSYNC_BUILD_CLIENT
2480 /* Only give back the vol to the fileserver if we checked it out; attach2
2481 * will set checkedOut only if we successfully checked it out from the
2483 if (VCanUseFSSYNC() && vp == NULL && checkedOut) {
2485 #ifdef AFS_DEMAND_ATTACH_FS
2486 /* If we couldn't attach but we scheduled a salvage, we already
2487 * notified the fileserver; don't online it now */
2488 if (*ec != VSALVAGING)
2489 #endif /* AFS_DEMAND_ATTACH_FS */
2490 FSYNC_VolOp(volumeId, partition, FSYNC_VOL_ON, 0, NULL);
2493 if (programType == fileServer && vp) {
2494 #ifdef AFS_DEMAND_ATTACH_FS
2496 * we can get here in cases where we don't "own"
2497 * the volume (e.g. volume owned by a utility).
2498 * short circuit around potential disk header races.
2500 if (V_attachState(vp) != VOL_STATE_ATTACHED) {
2504 VUpdateVolume_r(ec, vp, 0);
2506 Log("VAttachVolume: Error updating volume\n");
2511 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2512 #ifndef AFS_DEMAND_ATTACH_FS
2513 /* This is a hack: by temporarily setting the incore
2514 * dontSalvage flag ON, the volume will be put back on the
2515 * Update list (with dontSalvage OFF again). It will then
2516 * come back in N minutes with DONT_SALVAGE eventually
2517 * set. This is the way that volumes that have never had
2518 * it set get it set; or that volumes that have been
2519 * offline without DONT SALVAGE having been set also
2520 * eventually get it set */
2521 V_dontSalvage(vp) = DONT_SALVAGE;
2522 #endif /* !AFS_DEMAND_ATTACH_FS */
2523 VAddToVolumeUpdateList_r(ec, vp);
2525 Log("VAttachVolume: Error adding volume to update list\n");
2532 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2537 if (VRequiresPartLock()) {
2538 VUnlockPartition_r(partition);
2541 #ifdef AFS_DEMAND_ATTACH_FS
2542 /* attach failed; make sure we're in error state */
2543 if (vp && !VIsErrorState(V_attachState(vp))) {
2544 VChangeState_r(vp, VOL_STATE_ERROR);
2546 #endif /* AFS_DEMAND_ATTACH_FS */
2553 #ifdef AFS_DEMAND_ATTACH_FS
2554 /* VAttachVolumeByVp_r
2556 * finish attaching a volume that is
2557 * in a less than fully attached state
2559 /* caller MUST hold a ref count on vp */
2561 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
2563 char name[VMAXPATHLEN];
2565 struct DiskPartition64 *partp;
2569 Volume * nvp = NULL;
2570 VolumeStats stats_save;
2574 /* volume utility should never call AttachByVp */
2575 osi_Assert(programType == fileServer);
2577 volumeId = vp->hashid;
2578 partp = vp->partition;
2579 VolumeExternalName_r(volumeId, name, sizeof(name));
2582 /* if another thread is performing a blocking op, wait */
2583 VWaitExclusiveState_r(vp);
2585 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2587 /* if it's already attached, see if we can return it */
2588 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2589 VGetVolumeByVp_r(ec, vp);
2590 if (V_inUse(vp) == fileServer) {
2593 if (vp->specialStatus == VBUSY)
2595 VDetachVolume_r(ec, vp);
2597 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2603 /* pre-attach volume if it hasn't been done yet */
2605 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2606 (V_attachState(vp) == VOL_STATE_DELETED) ||
2607 (V_attachState(vp) == VOL_STATE_ERROR)) {
2608 nvp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2614 VCreateReservation_r(nvp);
2619 osi_Assert(vp != NULL);
2620 VChangeState_r(vp, VOL_STATE_ATTACHING);
2622 /* restore monotonically increasing stats */
2623 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2627 /* compute path to disk header */
2628 strcpy(path, VPartitionPath(partp));
2632 strcat(path, OS_DIRSEP);
2637 * NOTE: attach2 is entered without any locks, and returns
2638 * with vol_glock_mutex held */
2639 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2642 * the event that an error was encountered, or
2643 * the volume was not brought to an attached state
2644 * for any reason, skip to the end. We cannot
2645 * safely call VUpdateVolume unless we "own" it.
2649 (V_attachState(vp) != VOL_STATE_ATTACHED)) {
2653 VUpdateVolume_r(ec, vp, 0);
2655 Log("VAttachVolume: Error updating volume %u\n", vp->hashid);
2659 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2660 #ifndef AFS_DEMAND_ATTACH_FS
2661 /* This is a hack: by temporarily setting the incore
2662 * dontSalvage flag ON, the volume will be put back on the
2663 * Update list (with dontSalvage OFF again). It will then
2664 * come back in N minutes with DONT_SALVAGE eventually
2665 * set. This is the way that volumes that have never had
2666 * it set get it set; or that volumes that have been
2667 * offline without DONT SALVAGE having been set also
2668 * eventually get it set */
2669 V_dontSalvage(vp) = DONT_SALVAGE;
2670 #endif /* !AFS_DEMAND_ATTACH_FS */
2671 VAddToVolumeUpdateList_r(ec, vp);
2673 Log("VAttachVolume: Error adding volume %u to update list\n", vp->hashid);
2680 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2684 VCancelReservation_r(nvp);
2687 if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2688 if (vp && !VIsErrorState(V_attachState(vp))) {
2689 VChangeState_r(vp, VOL_STATE_ERROR);
2698 * lock a volume on disk (non-blocking).
2700 * @param[in] vp The volume to lock
2701 * @param[in] locktype READ_LOCK or WRITE_LOCK
2703 * @return operation status
2704 * @retval 0 success, lock was obtained
2705 * @retval EBUSY a conflicting lock was held by another process
2706 * @retval EIO error acquiring lock
2708 * @pre If we're in the fileserver, vp is in an exclusive state
2710 * @pre vp is not already locked
2713 VLockVolumeNB(Volume *vp, int locktype)
2717 osi_Assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2718 osi_Assert(!(V_attachFlags(vp) & VOL_LOCKED));
2720 code = VLockVolumeByIdNB(vp->hashid, vp->partition, locktype);
2722 V_attachFlags(vp) |= VOL_LOCKED;
2729 * unlock a volume on disk that was locked with VLockVolumeNB.
2731 * @param[in] vp volume to unlock
2733 * @pre If we're in the fileserver, vp is in an exclusive state
2735 * @pre vp has already been locked
2738 VUnlockVolume(Volume *vp)
2740 osi_Assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2741 osi_Assert((V_attachFlags(vp) & VOL_LOCKED));
2743 VUnlockVolumeById(vp->hashid, vp->partition);
2745 V_attachFlags(vp) &= ~VOL_LOCKED;
2747 #endif /* AFS_DEMAND_ATTACH_FS */
2750 * read in a vol header, possibly lock the vol header, and possibly check out
2751 * the vol header from the fileserver, as part of volume attachment.
2753 * @param[out] ec error code
2754 * @param[in] vp volume pointer object
2755 * @param[in] partp disk partition object of the attaching partition
2756 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
2758 * @param[in] peek 1 to just try to read in the volume header and make sure
2759 * we don't try to lock the vol, or check it out from
2760 * FSSYNC or anything like that; 0 otherwise, for 'normal'
2762 * @param[out] acheckedOut If we successfully checked-out the volume from
2763 * the fileserver (if we needed to), this is set
2764 * to 1, otherwise it is untouched.
2766 * @note As part of DAFS volume attachment, the volume header may be either
2767 * read- or write-locked to ensure mutual exclusion of certain volume
2768 * operations. In some cases in order to determine whether we need to
2769 * read- or write-lock the header, we need to read in the header to see
2770 * if the volume is RW or not. So, if we read in the header under a
2771 * read-lock and determine that we actually need a write-lock on the
2772 * volume header, this function will drop the read lock, acquire a write
2773 * lock, and read the header in again.
2776 attach_volume_header(Error *ec, Volume *vp, struct DiskPartition64 *partp,
2777 int mode, int peek, int *acheckedOut)
2779 struct VolumeDiskHeader diskHeader;
2780 struct VolumeHeader header;
2783 int lock_tries = 0, checkout_tries = 0;
2785 VolumeId volid = vp->hashid;
2786 #ifdef FSSYNC_BUILD_CLIENT
2787 int checkout, done_checkout = 0;
2788 #endif /* FSSYNC_BUILD_CLIENT */
2789 #ifdef AFS_DEMAND_ATTACH_FS
2790 int locktype = 0, use_locktype = -1;
2791 #endif /* AFS_DEMAND_ATTACH_FS */
2797 if (lock_tries > VOL_MAX_CHECKOUT_RETRIES) {
2798 Log("VAttachVolume: retried too many times trying to lock header for "
2799 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2800 VPartitionPath(partp));
2804 if (checkout_tries > VOL_MAX_CHECKOUT_RETRIES) {
2805 Log("VAttachVolume: retried too many times trying to checkout "
2806 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2807 VPartitionPath(partp));
2812 if (VReadVolumeDiskHeader(volid, partp, NULL)) {
2813 /* short-circuit the 'volume does not exist' case */
2818 #ifdef FSSYNC_BUILD_CLIENT
2819 checkout = !done_checkout;
2821 if (!peek && checkout && VMustCheckoutVolume(mode)) {
2823 memset(&res, 0, sizeof(res));
2825 if (FSYNC_VolOp(volid, VPartitionPath(partp), FSYNC_VOL_NEEDVOLUME, mode, &res)
2828 if (res.hdr.reason == FSYNC_SALVAGE) {
2829 Log("VAttachVolume: file server says volume %lu is salvaging\n",
2830 afs_printable_uint32_lu(volid));
2833 Log("VAttachVolume: attach of volume %lu apparently denied by file server\n",
2834 afs_printable_uint32_lu(volid));
2835 *ec = VNOVOL; /* XXXX */
2843 #ifdef AFS_DEMAND_ATTACH_FS
2844 if (use_locktype < 0) {
2845 /* don't know whether vol is RO or RW; assume it's RO and we can retry
2846 * if it turns out to be RW */
2847 locktype = VVolLockType(mode, 0);
2850 /* a previous try says we should use use_locktype to lock the volume,
2852 locktype = use_locktype;
2855 if (!peek && locktype) {
2856 code = VLockVolumeNB(vp, locktype);
2858 if (code == EBUSY) {
2859 Log("VAttachVolume: another program has vol %lu locked\n",
2860 afs_printable_uint32_lu(volid));
2862 Log("VAttachVolume: error %d trying to lock vol %lu\n",
2863 code, afs_printable_uint32_lu(volid));
2870 #endif /* AFS_DEMAND_ATTACH_FS */
2872 code = VReadVolumeDiskHeader(volid, partp, &diskHeader);
2882 DiskToVolumeHeader(&header, &diskHeader);
2884 IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header.parent,
2885 header.largeVnodeIndex);
2886 IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header.parent,
2887 header.smallVnodeIndex);
2888 IH_INIT(vp->diskDataHandle, partp->device, header.parent,
2890 IH_INIT(vp->linkHandle, partp->device, header.parent, header.linkTable);
2893 /* only need to do this once */
2895 GetVolumeHeader(vp);
2899 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2900 /* demand attach changes the V_PEEK mechanism
2902 * we can now suck the current disk data structure over
2903 * the fssync interface without going to disk
2905 * (technically, we don't need to restrict this feature
2906 * to demand attach fileservers. However, I'm trying
2907 * to limit the number of common code changes)
2909 if (VCanUseFSSYNC() && (mode == V_PEEK || peek)) {
2911 res.payload.len = sizeof(VolumeDiskData);
2912 res.payload.buf = &vp->header->diskstuff;
2914 if (FSYNC_VolOp(vp->hashid,
2916 FSYNC_VOL_QUERY_HDR,
2919 goto disk_header_loaded;
2922 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2923 (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2924 sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2926 #ifdef AFS_DEMAND_ATTACH_FS
2929 IncUInt64(&VStats.hdr_loads);
2930 IncUInt64(&vp->stats.hdr_loads);
2932 #endif /* AFS_DEMAND_ATTACH_FS */
2935 Log("VAttachVolume: Error reading diskDataHandle header for vol %lu; "
2936 "error=%u\n", afs_printable_uint32_lu(volid), *ec);
2940 #ifdef AFS_DEMAND_ATTACH_FS
2941 # ifdef FSSYNC_BUILD_CLIENT
2943 # endif /* FSSYNC_BUILD_CLIENT */
2945 /* if the lock type we actually used to lock the volume is different than
2946 * the lock type we should have used, retry with the lock type we should
2948 use_locktype = VVolLockType(mode, VolumeWriteable(vp));
2949 if (locktype != use_locktype) {
2953 #endif /* AFS_DEMAND_ATTACH_FS */
2958 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2959 if (!peek && *ec == 0 && retry == 0 && VMustCheckoutVolume(mode)) {
2961 code = FSYNC_VerifyCheckout(volid, VPartitionPath(partp), FSYNC_VOL_NEEDVOLUME, mode);
2963 if (code == SYNC_DENIED) {
2964 /* must retry checkout; fileserver no longer thinks we have
2970 } else if (code != SYNC_OK) {
2974 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2977 /* either we are going to be called again for a second pass, or we
2978 * encountered an error; clean up in either case */
2980 #ifdef AFS_DEMAND_ATTACH_FS
2981 if ((V_attachFlags(vp) & VOL_LOCKED)) {
2984 #endif /* AFS_DEMAND_ATTACH_FS */
2985 if (vp->linkHandle) {
2986 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
2987 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
2988 IH_RELEASE(vp->diskDataHandle);
2989 IH_RELEASE(vp->linkHandle);
3002 #ifdef AFS_DEMAND_ATTACH_FS
3004 attach_check_vop(Error *ec, VolumeId volid, struct DiskPartition64 *partp,
3005 Volume *vp, int *acheckedOut)
3009 if (vp->pending_vol_op) {
3013 if (vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningUnknown) {
3015 code = VVolOpLeaveOnlineNoHeader_r(vp, vp->pending_vol_op);
3017 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3018 } else if (code == 0) {
3019 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3022 /* we need the vol header to determine if the volume can be
3023 * left online for the vop, so... get the header */
3027 /* attach header with peek=1 to avoid checking out the volume
3028 * or locking it; we just want the header info, we're not
3029 * messing with the volume itself at all */
3030 attach_volume_header(ec, vp, partp, V_PEEK, 1, acheckedOut);
3037 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
3038 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3040 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3043 /* make sure we grab a new vol header and re-open stuff on
3044 * actual attachment; we can't keep the data we grabbed, since
3045 * it was not done under a lock and thus not safe */
3046 FreeVolumeHeader(vp);
3047 VReleaseVolumeHandles_r(vp);
3050 /* see if the pending volume op requires exclusive access */
3051 switch (vp->pending_vol_op->vol_op_state) {
3052 case FSSYNC_VolOpPending:
3053 /* this should never happen */
3054 osi_Assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpPending);
3057 case FSSYNC_VolOpRunningUnknown:
3058 /* this should never happen; we resolved 'unknown' above */
3059 osi_Assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
3062 case FSSYNC_VolOpRunningOffline:
3063 /* mark the volume down */
3065 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3067 /* do not set V_offlineMessage here; we don't have ownership of
3068 * the volume (and probably do not have the header loaded), so we
3069 * can't alter the disk header */
3071 /* check to see if we should set the specialStatus flag */
3072 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
3073 vp->specialStatus = VBUSY;
3084 #endif /* AFS_DEMAND_ATTACH_FS */
3087 * volume attachment helper function.
3089 * @param[out] ec error code
3090 * @param[in] volumeId volume ID of the attaching volume
3091 * @param[in] path full path to the volume header .vol file
3092 * @param[in] partp disk partition object for the attaching partition
3093 * @param[in] vp volume object; vp->hashid, vp->device, vp->partition,
3094 * vp->vnode_list, vp->rx_call_list, and V_attachCV (for
3095 * DAFS) should already be initialized
3096 * @param[in] isbusy 1 if vp->specialStatus should be set to VBUSY; that is,
3097 * if there is a volume operation running for this volume
3098 * that should set the volume to VBUSY during its run. 0
3099 * otherwise. (see VVolOpSetVBusy_r)
3100 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
3102 * @param[out] acheckedOut If we successfully checked-out the volume from
3103 * the fileserver (if we needed to), this is set
3104 * to 1, otherwise it is 0.
3106 * @return pointer to the semi-attached volume pointer
3107 * @retval NULL an error occurred (check value of *ec)
3108 * @retval vp volume successfully attaching
3110 * @pre no locks held
3112 * @post VOL_LOCK held
3115 attach2(Error * ec, VolId volumeId, char *path, struct DiskPartition64 *partp,
3116 Volume * vp, int isbusy, int mode, int *acheckedOut)
3118 /* have we read in the header successfully? */
3119 int read_header = 0;
3121 #ifdef AFS_DEMAND_ATTACH_FS
3122 /* should we FreeVolume(vp) instead of VCheckFree(vp) in the error
3126 /* in the case of an error, to what state should the volume be
3128 VolState error_state = VOL_STATE_ERROR;
3129 #endif /* AFS_DEMAND_ATTACH_FS */
3133 vp->vnodeIndex[vLarge].handle = NULL;
3134 vp->vnodeIndex[vSmall].handle = NULL;
3135 vp->diskDataHandle = NULL;
3136 vp->linkHandle = NULL;
3140 #ifdef AFS_DEMAND_ATTACH_FS
3141 attach_check_vop(ec, volumeId, partp, vp, acheckedOut);
3143 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3146 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3147 #endif /* !AFS_DEMAND_ATTACH_FS */
3149 if (*ec == VNOVOL) {
3150 /* if the volume doesn't exist, skip straight to 'error' so we don't
3151 * request a salvage */
3152 goto unlocked_error;
3158 vp->specialStatus = (byte) (isbusy ? VBUSY : 0);
3159 vp->shuttingDown = 0;
3160 vp->goingOffline = 0;
3162 #ifdef AFS_DEMAND_ATTACH_FS
3163 vp->stats.last_attach = FT_ApproxTime();
3164 vp->stats.attaches++;
3168 IncUInt64(&VStats.attaches);
3169 vp->cacheCheck = ++VolumeCacheCheck;
3170 /* just in case this ever rolls over */
3171 if (!vp->cacheCheck)
3172 vp->cacheCheck = ++VolumeCacheCheck;
3175 #ifdef AFS_DEMAND_ATTACH_FS
3176 V_attachFlags(vp) |= VOL_HDR_LOADED;
3177 vp->stats.last_hdr_load = vp->stats.last_attach;
3178 #endif /* AFS_DEMAND_ATTACH_FS */
3182 struct IndexFileHeader iHead;
3184 #if OPENAFS_VOL_STATS
3186 * We just read in the diskstuff part of the header. If the detailed
3187 * volume stats area has not yet been initialized, we should bzero the
3188 * area and mark it as initialized.
3190 if (!(V_stat_initialized(vp))) {
3191 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
3192 V_stat_initialized(vp) = 1;
3194 #endif /* OPENAFS_VOL_STATS */
3196 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
3197 (char *)&iHead, sizeof(iHead),
3198 SMALLINDEXMAGIC, SMALLINDEXVERSION);
3201 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
3206 struct IndexFileHeader iHead;
3208 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
3209 (char *)&iHead, sizeof(iHead),
3210 LARGEINDEXMAGIC, LARGEINDEXVERSION);
3213 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
3217 #ifdef AFS_NAMEI_ENV
3219 struct versionStamp stamp;
3221 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
3222 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
3225 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
3228 #endif /* AFS_NAMEI_ENV */
3230 #if defined(AFS_DEMAND_ATTACH_FS)
3231 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
3233 if (!VCanScheduleSalvage()) {
3234 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3236 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER |
3237 VOL_SALVAGE_NO_OFFLINE);
3242 /* volume operation in progress */
3243 goto unlocked_error;
3245 #else /* AFS_DEMAND_ATTACH_FS */
3247 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3248 goto unlocked_error;
3250 #endif /* AFS_DEMAND_ATTACH_FS */
3252 if (V_needsSalvaged(vp)) {
3253 if (vp->specialStatus)
3254 vp->specialStatus = 0;
3256 #if defined(AFS_DEMAND_ATTACH_FS)
3257 if (!VCanScheduleSalvage()) {
3258 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
3260 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER |
3261 VOL_SALVAGE_NO_OFFLINE);
3264 #else /* AFS_DEMAND_ATTACH_FS */
3266 #endif /* AFS_DEMAND_ATTACH_FS */
3272 vp->nextVnodeUnique = V_uniquifier(vp);
3274 if (VShouldCheckInUse(mode) && V_inUse(vp) && VolumeWriteable(vp)) {
3275 if (!V_needsSalvaged(vp)) {
3276 V_needsSalvaged(vp) = 1;
3277 VUpdateVolume_r(ec, vp, 0);
3279 #if defined(AFS_DEMAND_ATTACH_FS)
3280 if (!VCanScheduleSalvage()) {
3281 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3283 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER |
3284 VOL_SALVAGE_NO_OFFLINE);
3287 #else /* AFS_DEMAND_ATTACH_FS */
3288 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3290 #endif /* AFS_DEMAND_ATTACH_FS */
3295 if (programType == fileServer && V_destroyMe(vp) == DESTROY_ME) {
3296 /* Only check destroyMe if we are the fileserver, since the
3297 * volserver et al sometimes need to work with volumes with
3298 * destroyMe set. Examples are 'temporary' volumes the
3299 * volserver creates, and when we create a volume (destroyMe
3300 * is set on creation; sometimes a separate volserver
3301 * transaction is created to clear destroyMe).
3304 #if defined(AFS_DEMAND_ATTACH_FS)
3305 /* schedule a salvage so the volume goes away on disk */
3306 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER |
3307 VOL_SALVAGE_NO_OFFLINE);
3308 VChangeState_r(vp, VOL_STATE_ERROR);
3311 #endif /* AFS_DEMAND_ATTACH_FS */
3312 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
3317 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
3318 #ifndef BITMAP_LATER
3319 if (programType == fileServer && VolumeWriteable(vp)) {
3321 for (i = 0; i < nVNODECLASSES; i++) {
3322 VGetBitmap_r(ec, vp, i);
3324 #ifdef AFS_DEMAND_ATTACH_FS
3325 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER |
3326 VOL_SALVAGE_NO_OFFLINE);
3328 #endif /* AFS_DEMAND_ATTACH_FS */
3329 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
3335 #endif /* BITMAP_LATER */
3337 if (VInit >= 2 && V_needsCallback(vp)) {
3338 if (V_BreakVolumeCallbacks) {
3339 Log("VAttachVolume: Volume %lu was changed externally; breaking callbacks\n",
3340 afs_printable_uint32_lu(V_id(vp)));
3341 V_needsCallback(vp) = 0;
3343 (*V_BreakVolumeCallbacks) (V_id(vp));
3346 VUpdateVolume_r(ec, vp, 0);
3348 #ifdef FSSYNC_BUILD_CLIENT
3349 else if (VCanUseFSSYNC()) {
3350 afs_int32 fsync_code;
3352 V_needsCallback(vp) = 0;
3354 fsync_code = FSYNC_VolOp(V_id(vp), NULL, FSYNC_VOL_BREAKCBKS, FSYNC_WHATEVER, NULL);
3358 V_needsCallback(vp) = 1;
3359 Log("Error trying to tell the fileserver to break callbacks for "
3360 "changed volume %lu; error code %ld\n",
3361 afs_printable_uint32_lu(V_id(vp)),
3362 afs_printable_int32_ld(fsync_code));
3364 VUpdateVolume_r(ec, vp, 0);
3367 #endif /* FSSYNC_BUILD_CLIENT */
3370 Log("VAttachVolume: error %d clearing needsCallback on volume "
3371 "%lu; needs salvage\n", (int)*ec,
3372 afs_printable_uint32_lu(V_id(vp)));
3373 #ifdef AFS_DEMAND_ATTACH_FS
3374 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER |
3375 VOL_SALVAGE_NO_OFFLINE);
3377 #else /* !AFS_DEMAND_ATTACH_FS */
3379 #endif /* !AFS_DEMAND_ATTACh_FS */
3384 if (programType == fileServer) {
3385 if (vp->specialStatus)
3386 vp->specialStatus = 0;
3387 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
3388 V_inUse(vp) = fileServer;
3389 V_offlineMessage(vp)[0] = '\0';
3393 #ifdef AFS_DEMAND_ATTACH_FS
3394 /* Put the vol into PREATTACHED state, so if someone tries to
3395 * access it again, we try to attach, see that we're not blessed,
3396 * and give a VNOVOL error again. Putting it into UNATTACHED state
3397 * would result in a VOFFLINE error instead. */
3398 error_state = VOL_STATE_PREATTACHED;
3399 #endif /* AFS_DEMAND_ATTACH_FS */
3401 /* mimic e.g. GetVolume errors */
3402 if (!V_blessed(vp)) {
3403 Log("Volume %lu offline: not blessed\n", afs_printable_uint32_lu(V_id(vp)));
3404 FreeVolumeHeader(vp);
3405 } else if (!V_inService(vp)) {
3406 Log("Volume %lu offline: not in service\n", afs_printable_uint32_lu(V_id(vp)));
3407 FreeVolumeHeader(vp);
3409 Log("Volume %lu offline: needs salvage\n", afs_printable_uint32_lu(V_id(vp)));
3411 #ifdef AFS_DEMAND_ATTACH_FS
3412 error_state = VOL_STATE_ERROR;
3413 /* see if we can recover */
3414 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
3417 #ifdef AFS_DEMAND_ATTACH_FS
3423 #ifdef AFS_DEMAND_ATTACH_FS
3424 if ((mode != V_PEEK) && (mode != V_SECRETLY))
3425 V_inUse(vp) = programType;
3426 #endif /* AFS_DEMAND_ATTACH_FS */
3427 V_checkoutMode(vp) = mode;
3430 AddVolumeToHashTable(vp, V_id(vp));
3431 #ifdef AFS_DEMAND_ATTACH_FS
3432 if (VCanUnlockAttached() && (V_attachFlags(vp) & VOL_LOCKED)) {
3435 if ((programType != fileServer) ||
3436 (V_inUse(vp) == fileServer)) {
3437 AddVolumeToVByPList_r(vp);
3439 VChangeState_r(vp, VOL_STATE_ATTACHED);
3441 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3450 #ifdef AFS_DEMAND_ATTACH_FS
3451 if (!VIsErrorState(V_attachState(vp))) {
3452 VChangeState_r(vp, error_state);
3454 #endif /* AFS_DEMAND_ATTACH_FS */
3457 VReleaseVolumeHandles_r(vp);
3460 #ifdef AFS_DEMAND_ATTACH_FS
3467 #else /* !AFS_DEMAND_ATTACH_FS */
3469 #endif /* !AFS_DEMAND_ATTACH_FS */
3473 /* Attach an existing volume.
3474 The volume also normally goes online at this time.
3475 An offline volume must be reattached to make it go online.
3479 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
3483 retVal = VAttachVolume_r(ec, volumeId, mode);
3489 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
3492 VGetVolumePath(ec, volumeId, &part, &name);
3496 vp = VGetVolume_r(&error, volumeId);
3498 osi_Assert(V_inUse(vp) == 0);
3499 VDetachVolume_r(ec, vp);
3503 return VAttachVolumeByName_r(ec, part, name, mode);
3506 /* Increment a reference count to a volume, sans context swaps. Requires
3507 * possibly reading the volume header in from the disk, since there's
3508 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
3510 * N.B. This call can fail if we can't read in the header!! In this case
3511 * we still guarantee we won't context swap, but the ref count won't be
3512 * incremented (otherwise we'd violate the invariant).
3514 /* NOTE: with the demand attach fileserver extensions, the global lock
3515 * is dropped within VHold */
3516 #ifdef AFS_DEMAND_ATTACH_FS
3518 VHold_r(Volume * vp)
3522 VCreateReservation_r(vp);
3523 VWaitExclusiveState_r(vp);
3525 LoadVolumeHeader(&error, vp);
3527 VCancelReservation_r(vp);
3531 VCancelReservation_r(vp);
3534 #else /* AFS_DEMAND_ATTACH_FS */
3536 VHold_r(Volume * vp)
3540 LoadVolumeHeader(&error, vp);
3546 #endif /* AFS_DEMAND_ATTACH_FS */
3548 /**** volume timeout-related stuff ****/
3550 #ifdef AFS_PTHREAD_ENV
3552 static struct timespec *shutdown_timeout;
3553 static pthread_once_t shutdown_timeout_once = PTHREAD_ONCE_INIT;
3556 VTimedOut(const struct timespec *ts)
3561 if (ts->tv_sec == 0) {
3562 /* short-circuit; this will have always timed out */
3566 code = gettimeofday(&tv, NULL);
3568 Log("Error %d from gettimeofday, assuming we have not timed out\n", errno);
3569 /* assume no timeout; failure mode is we just wait longer than normal
3570 * instead of returning errors when we shouldn't */
3574 if (tv.tv_sec < ts->tv_sec ||
3575 (tv.tv_sec == ts->tv_sec && tv.tv_usec*1000 < ts->tv_nsec)) {
3584 * Calculate an absolute timeout.
3586 * @param[out] ts A timeout that is "timeout" seconds from now, if we return
3587 * NULL, the memory is not touched
3588 * @param[in] timeout How long the timeout should be from now
3590 * @return timeout to use
3591 * @retval NULL no timeout; wait forever
3592 * @retval non-NULL the given value for "ts"
3596 static struct timespec *
3597 VCalcTimeout(struct timespec *ts, afs_int32 timeout)
3607 ts->tv_sec = ts->tv_nsec = 0;
3611 code = gettimeofday(&now, NULL);
3613 Log("Error %d from gettimeofday, falling back to 'forever' timeout\n", errno);
3617 ts->tv_sec = now.tv_sec + timeout;
3618 ts->tv_nsec = now.tv_usec * 1000;
3624 * Initialize the shutdown_timeout global.
3627 VShutdownTimeoutInit(void)
3629 struct timespec *ts;
3631 ts = malloc(sizeof(*ts));
3633 shutdown_timeout = VCalcTimeout(ts, vol_opts.offline_shutdown_timeout);
3635 if (!shutdown_timeout) {
3641 * Figure out the timeout that should be used for waiting for offline volumes.
3643 * @param[out] ats Storage space for a local timeout value if needed
3645 * @return The timeout value that should be used
3646 * @retval NULL No timeout; wait forever for offlining volumes
3647 * @retval non-NULL A pointer to the absolute time that should be used as
3648 * the deadline for waiting for offlining volumes.
3650 * @note If we return non-NULL, the pointer we return may or may not be the
3653 static const struct timespec *
3654 VOfflineTimeout(struct timespec *ats)
3656 if (vol_shutting_down) {
3657 osi_Assert(pthread_once(&shutdown_timeout_once, VShutdownTimeoutInit) == 0);
3658 return shutdown_timeout;
3660 return VCalcTimeout(ats, vol_opts.offline_timeout);
3664 #else /* AFS_PTHREAD_ENV */
3666 /* Waiting a certain amount of time for offlining volumes is not supported
3667 * for LWP due to a lack of primitives. So, we never time out */
3668 # define VTimedOut(x) (0)
3669 # define VOfflineTimeout(x) (NULL)
3671 #endif /* !AFS_PTHREAD_ENV */
3679 retVal = VHold_r(vp);
3686 VIsGoingOffline_r(struct Volume *vp)
3690 if (vp->goingOffline) {
3691 if (vp->specialStatus) {
3692 code = vp->specialStatus;
3693 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3704 * Tell the caller if a volume is waiting to go offline.
3706 * @param[in] vp The volume we want to know about
3708 * @return volume status
3709 * @retval 0 volume is not waiting to go offline, go ahead and use it
3710 * @retval nonzero volume is waiting to offline, and give the returned code
3711 * as an error to anyone accessing the volume
3713 * @pre VOL_LOCK is NOT held
3714 * @pre caller holds a heavyweight reference on vp
3717 VIsGoingOffline(struct Volume *vp)
3722 code = VIsGoingOffline_r(vp);
3729 * Register an RX call with a volume.
3731 * @param[inout] ec Error code; if unset when passed in, may be set if
3732 * the volume starts going offline
3733 * @param[out] client_ec @see GetVolume
3734 * @param[in] vp Volume struct
3735 * @param[in] cbv VCallByVol struct containing the RX call to register
3737 * @pre VOL_LOCK held
3738 * @pre caller holds heavy ref on vp
3743 VRegisterCall_r(Error *ec, Error *client_ec, Volume *vp, struct VCallByVol *cbv)
3746 #ifdef AFS_DEMAND_ATTACH_FS
3748 /* just in case the volume started going offline after we got the
3749 * reference to it... otherwise, if the volume started going
3750 * offline right at the end of GetVolume(), we might race with the
3751 * RX call scanner, and return success and add our cbv to the
3752 * rx_call_list _after_ the scanner has scanned the list. */
3753 *ec = VIsGoingOffline_r(vp);
3759 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3760 VWaitStateChange_r(vp);
3762 #endif /* AFS_DEMAND_ATTACH_FS */
3764 queue_Prepend(&vp->rx_call_list, cbv);
3769 * Deregister an RX call with a volume.
3771 * @param[in] vp Volume struct
3772 * @param[in] cbv VCallByVol struct containing the RX call to deregister
3774 * @pre VOL_LOCK held
3775 * @pre caller holds heavy ref on vp
3780 VDeregisterCall_r(Volume *vp, struct VCallByVol *cbv)
3782 if (cbv && queue_IsOnQueue(cbv)) {
3783 #ifdef AFS_DEMAND_ATTACH_FS
3784 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3785 VWaitStateChange_r(vp);
3787 #endif /* AFS_DEMAND_ATTACH_FS */
3793 /***************************************************/
3794 /* get and put volume routines */
3795 /***************************************************/
3798 * put back a heavyweight reference to a volume object.
3800 * @param[in] vp volume object pointer
3802 * @pre VOL_LOCK held
3804 * @post heavyweight volume reference put back.
3805 * depending on state, volume may have been taken offline,
3806 * detached, salvaged, freed, etc.
3808 * @internal volume package internal use only
3811 VPutVolume_r(Volume * vp)
3813 osi_Assert(--vp->nUsers >= 0);
3814 if (vp->nUsers == 0) {
3816 ReleaseVolumeHeader(vp->header);
3817 #ifdef AFS_DEMAND_ATTACH_FS
3818 if (!VCheckDetach(vp)) {
3822 #else /* AFS_DEMAND_ATTACH_FS */
3824 #endif /* AFS_DEMAND_ATTACH_FS */
3829 VPutVolume(Volume * vp)
3837 * Puts a volume reference obtained with VGetVolumeWithCall.
3839 * @param[in] vp Volume struct
3840 * @param[in] cbv VCallByVol struct given to VGetVolumeWithCall, or NULL if none
3842 * @pre VOL_LOCK is NOT held
3845 VPutVolumeWithCall(Volume *vp, struct VCallByVol *cbv)
3848 VDeregisterCall_r(vp, cbv);
3853 /* Get a pointer to an attached volume. The pointer is returned regardless
3854 of whether or not the volume is in service or on/off line. An error
3855 code, however, is returned with an indication of the volume's status */
3857 VGetVolume(Error * ec, Error * client_ec, VolId volumeId)
3861 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
3867 * Get a volume reference associated with an RX call.
3869 * @param[out] ec @see GetVolume
3870 * @param[out] client_ec @see GetVolume
3871 * @param[in] volumeId @see GetVolume
3872 * @param[in] ts How long to wait for going-offline volumes (absolute time).
3873 * If NULL, wait forever. If ts->tv_sec == 0, return immediately
3874 * with an error if the volume is going offline.
3875 * @param[in] cbv Contains an RX call to be associated with this volume
3876 * reference. This call may be interrupted if the volume is
3877 * requested to go offline while we hold a ref on it. Give NULL
3878 * to not associate an RX call with this reference.
3880 * @return @see GetVolume
3882 * @note for LWP builds, ts must be NULL
3884 * @note A reference obtained with this function MUST be put back with
3885 * VPutVolumeWithCall
3888 VGetVolumeWithCall(Error * ec, Error * client_ec, VolId volumeId,
3889 const struct timespec *ts, struct VCallByVol *cbv)
3893 retVal = GetVolume(ec, client_ec, volumeId, NULL, ts);
3894 VRegisterCall_r(ec, client_ec, retVal, cbv);
3900 VGetVolume_r(Error * ec, VolId volumeId)
3902 return GetVolume(ec, NULL, volumeId, NULL, NULL);
3905 /* try to get a volume we've previously looked up */
3906 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
3908 VGetVolumeByVp_r(Error * ec, Volume * vp)
3910 return GetVolume(ec, NULL, vp->hashid, vp, NULL);
3914 * private interface for getting a volume handle
3916 * @param[out] ec error code (0 if no error)
3917 * @param[out] client_ec wire error code to be given to clients
3918 * @param[in] volumeId ID of the volume we want
3919 * @param[in] hint optional hint for hash lookups, or NULL
3920 * @param[in] timeout absolute deadline for waiting for the volume to go
3921 * offline, if it is going offline. NULL to wait forever.
3923 * @return a volume handle for the specified volume
3924 * @retval NULL an error occurred, or the volume is in such a state that
3925 * we cannot load a header or return any volume struct
3927 * @note for DAFS, caller must NOT hold a ref count on 'hint'
3929 * @note 'timeout' is only checked if the volume is actually going offline; so
3930 * if you pass timeout->tv_sec = 0, this will exhibit typical
3931 * nonblocking behavior.
3933 * @note for LWP builds, 'timeout' must be NULL
3936 GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint,
3937 const struct timespec *timeout)
3940 /* pull this profiling/debugging code out of regular builds */
3942 #define VGET_CTR_INC(x) x++
3943 unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
3944 0, V7 = 0, V8 = 0, V9 = 0;
3945 unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
3947 #define VGET_CTR_INC(x)
3949 #ifdef AFS_DEMAND_ATTACH_FS
3950 Volume *avp, * rvp = hint;
3954 * if VInit is zero, the volume package dynamic
3955 * data structures have not been initialized yet,
3956 * and we must immediately return an error
3962 *client_ec = VOFFLINE;
3967 #ifdef AFS_DEMAND_ATTACH_FS
3969 VCreateReservation_r(rvp);
3971 #endif /* AFS_DEMAND_ATTACH_FS */
3979 vp = VLookupVolume_r(ec, volumeId, vp);
3985 #ifdef AFS_DEMAND_ATTACH_FS
3986 if (rvp && (rvp != vp)) {
3987 /* break reservation on old vp */
3988 VCancelReservation_r(rvp);
3991 #endif /* AFS_DEMAND_ATTACH_FS */
3997 /* Until we have reached an initialization level of 2
3998 * we don't know whether this volume exists or not.
3999 * We can't sleep and retry later because before a volume
4000 * is attached, the caller tries to get it first. Just
4001 * return VOFFLINE and the caller can choose whether to
4002 * retry the command or not. */
4012 IncUInt64(&VStats.hdr_gets);
4014 #ifdef AFS_DEMAND_ATTACH_FS
4015 /* block if someone else is performing an exclusive op on this volume */
4018 VCreateReservation_r(rvp);
4020 VWaitExclusiveState_r(vp);
4022 /* short circuit with VNOVOL in the following circumstances:
4025 * - VOL_STATE_SHUTTING_DOWN
4027 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
4028 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN) ||
4029 (V_attachState(vp) == VOL_STATE_GOING_OFFLINE)) {
4036 * short circuit with VOFFLINE for VOL_STATE_UNATTACHED and
4037 * VNOVOL for VOL_STATE_DELETED
4039 if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
4040 (V_attachState(vp) == VOL_STATE_DELETED)) {
4041 if (vp->specialStatus) {
4042 *ec = vp->specialStatus;
4043 } else if (V_attachState(vp) == VOL_STATE_DELETED) {
4052 /* allowable states:
4059 if (vp->salvage.requested) {
4060 VUpdateSalvagePriority_r(vp);
4063 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
4064 avp = VAttachVolumeByVp_r(ec, vp, 0);
4067 /* VAttachVolumeByVp_r can return a pointer
4068 * != the vp passed to it under certain
4069 * conditions; make sure we don't leak
4070 * reservations if that happens */
4072 VCancelReservation_r(rvp);
4074 VCreateReservation_r(rvp);
4084 if (!vp->pending_vol_op) {
4099 if (VIsSalvaging(vp) || (*ec == VSALVAGING)) {
4101 /* see CheckVnode() in afsfileprocs.c for an explanation
4102 * of this error code logic */
4103 afs_uint32 now = FT_ApproxTime();
4104 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
4107 *client_ec = VRESTARTING;
4116 #ifdef AFS_DEMAND_ATTACH_FS
4118 * this test MUST happen after VAttachVolymeByVp, so vol_op_state is
4119 * not VolOpRunningUnknown (attach2 would have converted it to Online
4123 /* only valid before/during demand attachment */
4124 osi_Assert(!vp->pending_vol_op || vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
4126 /* deny getvolume due to running mutually exclusive vol op */
4127 if (vp->pending_vol_op && vp->pending_vol_op->vol_op_state==FSSYNC_VolOpRunningOffline) {
4129 * volume cannot remain online during this volume operation.
4132 if (vp->specialStatus) {
4134 * special status codes outrank normal VOFFLINE code
4136 *ec = vp->specialStatus;
4138 *client_ec = vp->specialStatus;
4142 /* see CheckVnode() in afsfileprocs.c for an explanation
4143 * of this error code logic */
4144 afs_uint32 now = FT_ApproxTime();
4145 if ((vp->stats.last_vol_op + (10 * 60)) >= now) {
4148 *client_ec = VRESTARTING;
4153 VChangeState_r(vp, VOL_STATE_UNATTACHED);
4154 FreeVolumeHeader(vp);
4158 #endif /* AFS_DEMAND_ATTACH_FS */
4160 LoadVolumeHeader(ec, vp);
4163 /* Only log the error if it was a totally unexpected error. Simply
4164 * a missing inode is likely to be caused by the volume being deleted */
4165 if (errno != ENXIO || LogLevel)
4166 Log("Volume %u: couldn't reread volume header\n",
4168 #ifdef AFS_DEMAND_ATTACH_FS
4169 if (VCanScheduleSalvage()) {
4170 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
4175 #else /* AFS_DEMAND_ATTACH_FS */
4178 #endif /* AFS_DEMAND_ATTACH_FS */
4183 if (vp->shuttingDown) {
4190 if (programType == fileServer) {
4192 if (vp->goingOffline) {
4193 if (timeout && VTimedOut(timeout)) {
4194 /* we've timed out; don't wait for the vol */
4197 #ifdef AFS_DEMAND_ATTACH_FS
4198 /* wait for the volume to go offline */
4199 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
4200 VTimedWaitStateChange_r(vp, timeout, NULL);
4202 #elif defined(AFS_PTHREAD_ENV)
4203 VOL_CV_TIMEDWAIT(&vol_put_volume_cond, timeout, NULL);
4204 #else /* AFS_PTHREAD_ENV */
4205 /* LWP has no timed wait, so the caller better not be
4207 osi_Assert(!timeout);
4208 LWP_WaitProcess(VPutVolume);
4209 #endif /* AFS_PTHREAD_ENV */
4213 if (vp->specialStatus) {
4215 *ec = vp->specialStatus;
4216 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
4219 } else if (V_inUse(vp) == 0 || vp->goingOffline) {
4230 #ifdef AFS_DEMAND_ATTACH_FS
4231 /* if no error, bump nUsers */
4234 VLRU_UpdateAccess_r(vp);
4237 VCancelReservation_r(rvp);
4240 if (client_ec && !*client_ec) {
4243 #else /* AFS_DEMAND_ATTACH_FS */
4244 /* if no error, bump nUsers */
4251 #endif /* AFS_DEMAND_ATTACH_FS */
4254 osi_Assert(vp || *ec);
4259 /***************************************************/
4260 /* Volume offline/detach routines */
4261 /***************************************************/
4263 /* caller MUST hold a heavyweight ref on vp */
4264 #ifdef AFS_DEMAND_ATTACH_FS
4266 VTakeOffline_r(Volume * vp)
4270 osi_Assert(vp->nUsers > 0);
4271 osi_Assert(programType == fileServer);
4273 VCreateReservation_r(vp);
4274 VWaitExclusiveState_r(vp);
4276 vp->goingOffline = 1;
4277 V_needsSalvaged(vp) = 1;
4279 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
4280 VCancelReservation_r(vp);
4282 #else /* AFS_DEMAND_ATTACH_FS */
4284 VTakeOffline_r(Volume * vp)
4286 osi_Assert(vp->nUsers > 0);
4287 osi_Assert(programType == fileServer);
4289 vp->goingOffline = 1;
4290 V_needsSalvaged(vp) = 1;
4292 #endif /* AFS_DEMAND_ATTACH_FS */
4295 VTakeOffline(Volume * vp)
4303 * force a volume offline.
4305 * @param[in] vp volume object pointer
4306 * @param[in] flags flags (see note below)
4308 * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
4309 * used when VUpdateVolume_r needs to call VForceOffline_r
4310 * (which in turn would normally call VUpdateVolume_r)
4312 * @see VUpdateVolume_r
4314 * @pre VOL_LOCK must be held.
4315 * for DAFS, caller must hold ref.
4317 * @note for DAFS, it _is safe_ to call this function from an
4320 * @post needsSalvaged flag is set.
4321 * for DAFS, salvage is requested.
4322 * no further references to the volume through the volume
4323 * package will be honored.
4324 * all file descriptor and vnode caches are invalidated.
4326 * @warning this is a heavy-handed interface. it results in
4327 * a volume going offline regardless of the current
4328 * reference count state.
4330 * @internal volume package internal use only
4333 VForceOffline_r(Volume * vp, int flags)
4337 #ifdef AFS_DEMAND_ATTACH_FS
4338 VChangeState_r(vp, VOL_STATE_ERROR);
4343 strcpy(V_offlineMessage(vp),
4344 "Forced offline due to internal error: volume needs to be salvaged");
4345 Log("Volume %u forced offline: it needs salvaging!\n", V_id(vp));
4348 vp->goingOffline = 0;
4349 V_needsSalvaged(vp) = 1;
4350 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
4351 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
4354 #ifdef AFS_DEMAND_ATTACH_FS
4355 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
4356 #endif /* AFS_DEMAND_ATTACH_FS */
4358 #ifdef AFS_PTHREAD_ENV
4359 CV_BROADCAST(&vol_put_volume_cond);
4360 #else /* AFS_PTHREAD_ENV */
4361 LWP_NoYieldSignal(VPutVolume);
4362 #endif /* AFS_PTHREAD_ENV */
4364 VReleaseVolumeHandles_r(vp);
4368 * force a volume offline.
4370 * @param[in] vp volume object pointer
4372 * @see VForceOffline_r
4375 VForceOffline(Volume * vp)
4378 VForceOffline_r(vp, 0);
4383 * Iterate over the RX calls associated with a volume, and interrupt them.
4385 * @param[in] vp The volume whose RX calls we want to scan
4387 * @pre VOL_LOCK held
4390 VScanCalls_r(struct Volume *vp)
4392 struct VCallByVol *cbv, *ncbv;
4394 #ifdef AFS_DEMAND_ATTACH_FS
4395 VolState state_save;
4398 if (queue_IsEmpty(&vp->rx_call_list))
4399 return; /* no calls to interrupt */
4400 if (!vol_opts.interrupt_rxcall)
4401 return; /* we have no function with which to interrupt calls */
4402 err = VIsGoingOffline_r(vp);
4404 return; /* we're not going offline anymore */
4406 #ifdef AFS_DEMAND_ATTACH_FS
4407 VWaitExclusiveState_r(vp);
4408 state_save = VChangeState_r(vp, VOL_STATE_SCANNING_RXCALLS);
4410 #endif /* AFS_DEMAND_ATTACH_FS */
4412 for(queue_Scan(&vp->rx_call_list, cbv, ncbv, VCallByVol)) {
4414 struct rx_peer *peer;
4416 peer = rx_PeerOf(rx_ConnectionOf(cbv->call));
4418 Log("Offlining volume %lu while client %s:%u is trying to read "
4419 "from it; kicking client off with error %ld\n",
4420 (long unsigned) vp->hashid,
4421 afs_inet_ntoa_r(rx_HostOf(peer), hoststr),
4422 (unsigned) ntohs(rx_PortOf(peer)),
4425 (*vol_opts.interrupt_rxcall) (cbv->call, err);
4428 #ifdef AFS_DEMAND_ATTACH_FS
4430 VChangeState_r(vp, state_save);
4431 #endif /* AFS_DEMAND_ATTACH_FS */
4434 #ifdef AFS_DEMAND_ATTACH_FS
4436 * Wait for a vp to go offline.
4438 * @param[out] ec 1 if a salvage on the volume has been requested and
4439 * salvok == 0, 0 otherwise
4440 * @param[in] vp The volume to wait for
4441 * @param[in] salvok If 0, we return immediately with *ec = 1 if the volume
4442 * has been requested to salvage. Otherwise we keep waiting
4443 * until the volume has gone offline.
4445 * @pre VOL_LOCK held
4446 * @pre caller holds a lightweight ref on vp
4451 VWaitForOfflineByVp_r(Error *ec, struct Volume *vp, int salvok)
4453 struct timespec timeout_ts;
4454 const struct timespec *ts;
4457 ts = VOfflineTimeout(&timeout_ts);
4461 while (!VIsOfflineState(V_attachState(vp)) && !timedout) {
4462 if (!salvok && vp->salvage.requested) {
4466 VTimedWaitStateChange_r(vp, ts, &timedout);
4469 /* we didn't time out, so the volume must be offline, so we're done */
4473 /* If we got here, we timed out waiting for the volume to go offline.
4474 * Kick off the accessing RX calls and wait again */
4478 while (!VIsOfflineState(V_attachState(vp))) {
4479 if (!salvok && vp->salvage.requested) {
4484 VWaitStateChange_r(vp);
4488 #else /* AFS_DEMAND_ATTACH_FS */
4491 * Wait for a volume to go offline.
4493 * @pre VOL_LOCK held
4495 * @note non-DAFS only (for DAFS, use @see WaitForOfflineByVp_r)
4498 VWaitForOffline_r(Error *ec, VolumeId volid)
4501 const struct timespec *ts;
4502 #ifdef AFS_PTHREAD_ENV
4503 struct timespec timeout_ts;
4506 ts = VOfflineTimeout(&timeout_ts);
4508 vp = GetVolume(ec, NULL, volid, NULL, ts);
4510 /* error occurred so bad that we can't even get a vp; we have no
4511 * information on the vol so we don't know whether to wait, so just
4515 if (!VIsGoingOffline_r(vp)) {
4516 /* volume is no longer going offline, so we're done */
4521 /* If we got here, we timed out waiting for the volume to go offline.
4522 * Kick off the accessing RX calls and wait again */
4528 vp = VGetVolume_r(ec, volid);
4530 /* In case it was reattached... */
4534 #endif /* !AFS_DEMAND_ATTACH_FS */
4536 /* The opposite of VAttachVolume. The volume header is written to disk, with
4537 the inUse bit turned off. A copy of the header is maintained in memory,
4538 however (which is why this is VOffline, not VDetach).
4541 VOffline_r(Volume * vp, char *message)
4544 #ifndef AFS_DEMAND_ATTACH_FS
4545 VolumeId vid = V_id(vp);
4548 osi_Assert(programType != volumeUtility && programType != volumeServer);
4553 if (V_offlineMessage(vp)[0] == '\0')
4554 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4555 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4557 vp->goingOffline = 1;
4558 #ifdef AFS_DEMAND_ATTACH_FS
4559 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4560 VCreateReservation_r(vp);
4562 VWaitForOfflineByVp_r(&error, vp, 1);
4563 VCancelReservation_r(vp);
4564 #else /* AFS_DEMAND_ATTACH_FS */
4566 VWaitForOffline_r(&error, vid);
4567 #endif /* AFS_DEMAND_ATTACH_FS */
4570 #ifdef AFS_DEMAND_ATTACH_FS
4572 * Take a volume offline in order to perform a volume operation.
4574 * @param[inout] ec address in which to store error code
4575 * @param[in] vp volume object pointer
4576 * @param[in] message volume offline status message
4579 * - VOL_LOCK is held
4580 * - caller MUST hold a heavyweight ref on vp
4583 * - volume is taken offline
4584 * - if possible, volume operation is promoted to running state
4585 * - on failure, *ec is set to nonzero
4587 * @note Although this function does not return any value, it may
4588 * still fail to promote our pending volume operation to
4589 * a running state. Any caller MUST check the value of *ec,
4590 * and MUST NOT blindly assume success.
4592 * @warning if the caller does not hold a lightweight ref on vp,
4593 * then it MUST NOT reference vp after this function
4594 * returns to the caller.
4596 * @internal volume package internal use only
4599 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
4602 osi_Assert(vp->pending_vol_op);
4608 if (V_offlineMessage(vp)[0] == '\0')
4609 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4610 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4612 vp->goingOffline = 1;
4613 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4614 VCreateReservation_r(vp);
4617 if (vp->pending_vol_op->com.programType != salvageServer) {
4618 /* do not give corrupted volumes to the volserver */
4623 VWaitForOfflineByVp_r(ec, vp, salvok);
4625 VCancelReservation_r(vp);
4627 #endif /* AFS_DEMAND_ATTACH_FS */
4630 VOffline(Volume * vp, char *message)
4633 VOffline_r(vp, message);
4637 /* This gets used for the most part by utility routines that don't want
4638 * to keep all the volume headers around. Generally, the file server won't
4639 * call this routine, because then the offline message in the volume header
4640 * (or other information) won't be available to clients. For NAMEI, also
4641 * close the file handles. However, the fileserver does call this during
4642 * an attach following a volume operation.
4645 VDetachVolume_r(Error * ec, Volume * vp)
4647 #ifdef FSSYNC_BUILD_CLIENT
4649 struct DiskPartition64 *tpartp;
4650 int notifyServer = 0;
4651 int useDone = FSYNC_VOL_ON;
4653 if (VCanUseFSSYNC()) {
4654 notifyServer = vp->needsPutBack;
4655 if (V_destroyMe(vp) == DESTROY_ME)
4656 useDone = FSYNC_VOL_LEAVE_OFF;
4657 #ifdef AFS_DEMAND_ATTACH_FS
4658 else if (!V_blessed(vp) || !V_inService(vp))
4659 useDone = FSYNC_VOL_LEAVE_OFF;
4662 tpartp = vp->partition;
4664 #endif /* FSSYNC_BUILD_CLIENT */
4666 *ec = 0; /* always "succeeds" */
4667 DeleteVolumeFromHashTable(vp);
4668 vp->shuttingDown = 1;
4669 #ifdef AFS_DEMAND_ATTACH_FS
4670 DeleteVolumeFromVByPList_r(vp);
4672 VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
4674 if (programType != fileServer)
4676 #endif /* AFS_DEMAND_ATTACH_FS */
4678 /* Will be detached sometime in the future--this is OK since volume is offline */
4680 /* XXX the following code should really be moved to VCheckDetach() since the volume
4681 * is not technically detached until the refcounts reach zero
4683 #ifdef FSSYNC_BUILD_CLIENT
4684 if (VCanUseFSSYNC() && notifyServer) {
4685 if (notifyServer == VOL_PUTBACK_DELETE) {
4686 /* Only send FSYNC_VOL_DONE if the volume was actually deleted.
4687 * volserver code will set needsPutBack to VOL_PUTBACK_DELETE
4688 * to signify a deleted volume. */
4689 useDone = FSYNC_VOL_DONE;
4692 * Note: The server is not notified in the case of a bogus volume
4693 * explicitly to make it possible to create a volume, do a partial
4694 * restore, then abort the operation without ever putting the volume
4695 * online. This is essential in the case of a volume move operation
4696 * between two partitions on the same server. In that case, there
4697 * would be two instances of the same volume, one of them bogus,
4698 * which the file server would attempt to put on line
4700 FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
4701 /* XXX this code path is only hit by volume utilities, thus
4702 * V_BreakVolumeCallbacks will always be NULL. if we really
4703 * want to break callbacks in this path we need to use FSYNC_VolOp() */
4705 /* Dettaching it so break all callbacks on it */
4706 if (V_BreakVolumeCallbacks) {
4707 Log("volume %u detached; breaking all call backs\n", volume);
4708 (*V_BreakVolumeCallbacks) (volume);
4712 #endif /* FSSYNC_BUILD_CLIENT */
4716 VDetachVolume(Error * ec, Volume * vp)
4719 VDetachVolume_r(ec, vp);
4724 /***************************************************/
4725 /* Volume fd/inode handle closing routines */
4726 /***************************************************/
4728 /* For VDetachVolume, we close all cached file descriptors, but keep
4729 * the Inode handles in case we need to read from a busy volume.
4731 /* for demand attach, caller MUST hold ref count on vp */
4733 VCloseVolumeHandles_r(Volume * vp)
4735 #ifdef AFS_DEMAND_ATTACH_FS
4736 VolState state_save;
4738 state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
4743 * XXX need to investigate whether we can perform
4744 * DFlushVolume outside of vol_glock_mutex...
4746 * VCloseVnodeFiles_r drops the glock internally */
4747 DFlushVolume(vp->hashid);
4748 VCloseVnodeFiles_r(vp);
4750 #ifdef AFS_DEMAND_ATTACH_FS
4754 /* Too time consuming and unnecessary for the volserver */
4755 if (programType == fileServer) {
4756 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4757 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4758 IH_CONDSYNC(vp->diskDataHandle);
4760 IH_CONDSYNC(vp->linkHandle);
4761 #endif /* AFS_NT40_ENV */
4764 IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
4765 IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
4766 IH_REALLYCLOSE(vp->diskDataHandle);
4767 IH_REALLYCLOSE(vp->linkHandle);
4769 #ifdef AFS_DEMAND_ATTACH_FS
4770 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4775 VChangeState_r(vp, state_save);
4779 /* For both VForceOffline and VOffline, we close all relevant handles.
4780 * For VOffline, if we re-attach the volume, the files may possible be
4781 * different than before.
4783 /* for demand attach, caller MUST hold a ref count on vp */
4785 VReleaseVolumeHandles_r(Volume * vp)
4787 #ifdef AFS_DEMAND_ATTACH_FS
4788 VolState state_save;
4790 state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
4793 /* XXX need to investigate whether we can perform
4794 * DFlushVolume outside of vol_glock_mutex... */
4795 DFlushVolume(vp->hashid);
4797 VReleaseVnodeFiles_r(vp); /* releases the glock internally */
4799 #ifdef AFS_DEMAND_ATTACH_FS
4803 /* Too time consuming and unnecessary for the volserver */
4804 if (programType == fileServer) {
4805 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4806 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4807 IH_CONDSYNC(vp->diskDataHandle);
4809 IH_CONDSYNC(vp->linkHandle);
4810 #endif /* AFS_NT40_ENV */
4813 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
4814 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
4815 IH_RELEASE(vp->diskDataHandle);
4816 IH_RELEASE(vp->linkHandle);
4818 #ifdef AFS_DEMAND_ATTACH_FS
4819 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4824 VChangeState_r(vp, state_save);
4829 /***************************************************/
4830 /* Volume write and fsync routines */
4831 /***************************************************/
4834 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
4836 #ifdef AFS_DEMAND_ATTACH_FS
4837 VolState state_save;
4839 if (flags & VOL_UPDATE_WAIT) {
4840 VCreateReservation_r(vp);
4841 VWaitExclusiveState_r(vp);
4846 if (programType == fileServer)
4848 (V_inUse(vp) ? V_nextVnodeUnique(vp) +
4849 200 : V_nextVnodeUnique(vp));
4851 #ifdef AFS_DEMAND_ATTACH_FS
4852 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4856 WriteVolumeHeader_r(ec, vp);
4858 #ifdef AFS_DEMAND_ATTACH_FS
4860 VChangeState_r(vp, state_save);
4861 if (flags & VOL_UPDATE_WAIT) {
4862 VCancelReservation_r(vp);
4867 Log("VUpdateVolume: error updating volume header, volume %u (%s)\n",
4868 V_id(vp), V_name(vp));
4869 /* try to update on-disk header,
4870 * while preventing infinite recursion */
4871 if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
4872 VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
4878 VUpdateVolume(Error * ec, Volume * vp)
4881 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4886 VSyncVolume_r(Error * ec, Volume * vp, int flags)
4890 #ifdef AFS_DEMAND_ATTACH_FS
4891 VolState state_save;
4894 if (flags & VOL_SYNC_WAIT) {
4895 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4897 VUpdateVolume_r(ec, vp, 0);
4900 #ifdef AFS_DEMAND_ATTACH_FS
4901 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4904 fdP = IH_OPEN(V_diskDataHandle(vp));
4905 osi_Assert(fdP != NULL);
4906 code = FDH_SYNC(fdP);
4907 osi_Assert(code == 0);
4909 #ifdef AFS_DEMAND_ATTACH_FS
4911 VChangeState_r(vp, state_save);
4917 VSyncVolume(Error * ec, Volume * vp)
4920 VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
4925 /***************************************************/
4926 /* Volume dealloaction routines */
4927 /***************************************************/
4929 #ifdef AFS_DEMAND_ATTACH_FS
4931 FreeVolume(Volume * vp)
4933 /* free the heap space, iff it's safe.
4934 * otherwise, pull it out of the hash table, so it
4935 * will get deallocated when all refs to it go away */
4936 if (!VCheckFree(vp)) {
4937 DeleteVolumeFromHashTable(vp);
4938 DeleteVolumeFromVByPList_r(vp);
4940 /* make sure we invalidate the header cache entry */
4941 FreeVolumeHeader(vp);
4944 #endif /* AFS_DEMAND_ATTACH_FS */
4947 ReallyFreeVolume(Volume * vp)
4952 #ifdef AFS_DEMAND_ATTACH_FS
4954 VChangeState_r(vp, VOL_STATE_FREED);
4955 if (vp->pending_vol_op)
4956 free(vp->pending_vol_op);
4957 #endif /* AFS_DEMAND_ATTACH_FS */
4958 for (i = 0; i < nVNODECLASSES; i++)
4959 if (vp->vnodeIndex[i].bitmap)
4960 free(vp->vnodeIndex[i].bitmap);
4961 FreeVolumeHeader(vp);
4962 #ifndef AFS_DEMAND_ATTACH_FS
4963 DeleteVolumeFromHashTable(vp);
4964 #endif /* AFS_DEMAND_ATTACH_FS */
4968 /* check to see if we should shutdown this volume
4969 * returns 1 if volume was freed, 0 otherwise */
4970 #ifdef AFS_DEMAND_ATTACH_FS
4972 VCheckDetach(Volume * vp)
4977 if (vp->nUsers || vp->nWaiters)
4980 if (vp->shuttingDown) {
4982 if ((programType != fileServer) &&
4983 (V_inUse(vp) == programType) &&
4984 ((V_checkoutMode(vp) == V_VOLUPD) ||
4985 (V_checkoutMode(vp) == V_SECRETLY) ||
4986 ((V_checkoutMode(vp) == V_CLONE) &&
4987 (VolumeWriteable(vp))))) {
4989 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
4991 Log("VCheckDetach: volume header update for volume %u "
4992 "failed with errno %d\n", vp->hashid, errno);
4995 VReleaseVolumeHandles_r(vp);
4997 ReallyFreeVolume(vp);
4998 if (programType == fileServer) {
4999 CV_BROADCAST(&vol_put_volume_cond);
5004 #else /* AFS_DEMAND_ATTACH_FS */
5006 VCheckDetach(Volume * vp)
5014 if (vp->shuttingDown) {
5016 if ((programType != fileServer) &&
5017 (V_inUse(vp) == programType) &&
5018 ((V_checkoutMode(vp) == V_VOLUPD) ||
5019 (V_checkoutMode(vp) == V_SECRETLY) ||
5020 ((V_checkoutMode(vp) == V_CLONE) &&
5021 (VolumeWriteable(vp))))) {
5023 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5025 Log("VCheckDetach: volume header update for volume %u failed with errno %d\n",
5029 VReleaseVolumeHandles_r(vp);
5030 ReallyFreeVolume(vp);
5031 if (programType == fileServer) {
5032 #if defined(AFS_PTHREAD_ENV)
5033 CV_BROADCAST(&vol_put_volume_cond);
5034 #else /* AFS_PTHREAD_ENV */
5035 LWP_NoYieldSignal(VPutVolume);
5036 #endif /* AFS_PTHREAD_ENV */
5041 #endif /* AFS_DEMAND_ATTACH_FS */
5043 /* check to see if we should offline this volume
5044 * return 1 if volume went offline, 0 otherwise */
5045 #ifdef AFS_DEMAND_ATTACH_FS
5047 VCheckOffline(Volume * vp)
5051 if (vp->goingOffline && !vp->nUsers) {
5053 osi_Assert(programType == fileServer);
5054 osi_Assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
5055 (V_attachState(vp) != VOL_STATE_FREED) &&
5056 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
5057 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
5058 (V_attachState(vp) != VOL_STATE_DELETED));
5062 * VOL_STATE_GOING_OFFLINE
5063 * VOL_STATE_SHUTTING_DOWN
5064 * VIsErrorState(V_attachState(vp))
5065 * VIsExclusiveState(V_attachState(vp))
5068 VCreateReservation_r(vp);
5069 VChangeState_r(vp, VOL_STATE_OFFLINING);
5072 /* must clear the goingOffline flag before we drop the glock */
5073 vp->goingOffline = 0;
5078 /* perform async operations */
5079 VUpdateVolume_r(&error, vp, 0);
5080 VCloseVolumeHandles_r(vp);
5083 if (V_offlineMessage(vp)[0]) {
5084 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5085 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5086 V_offlineMessage(vp));
5088 Log("VOffline: Volume %lu (%s) is now offline\n",
5089 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5093 /* invalidate the volume header cache entry */
5094 FreeVolumeHeader(vp);
5096 /* if nothing changed state to error or salvaging,
5097 * drop state to unattached */
5098 if (!VIsErrorState(V_attachState(vp))) {
5099 VChangeState_r(vp, VOL_STATE_UNATTACHED);
5101 VCancelReservation_r(vp);
5102 /* no usage of vp is safe beyond this point */
5106 #else /* AFS_DEMAND_ATTACH_FS */
5108 VCheckOffline(Volume * vp)
5112 if (vp->goingOffline && !vp->nUsers) {
5114 osi_Assert(programType == fileServer);
5117 vp->goingOffline = 0;
5119 VUpdateVolume_r(&error, vp, 0);
5120 VCloseVolumeHandles_r(vp);
5122 if (V_offlineMessage(vp)[0]) {
5123 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5124 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5125 V_offlineMessage(vp));
5127 Log("VOffline: Volume %lu (%s) is now offline\n",
5128 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5131 FreeVolumeHeader(vp);
5132 #ifdef AFS_PTHREAD_ENV
5133 CV_BROADCAST(&vol_put_volume_cond);
5134 #else /* AFS_PTHREAD_ENV */
5135 LWP_NoYieldSignal(VPutVolume);
5136 #endif /* AFS_PTHREAD_ENV */
5140 #endif /* AFS_DEMAND_ATTACH_FS */
5142 /***************************************************/
5143 /* demand attach fs ref counting routines */
5144 /***************************************************/
5146 #ifdef AFS_DEMAND_ATTACH_FS
5147 /* the following two functions handle reference counting for
5148 * asynchronous operations on volume structs.
5150 * their purpose is to prevent a VDetachVolume or VShutdown
5151 * from free()ing the Volume struct during an async i/o op */
5153 /* register with the async volume op ref counter */
5154 /* VCreateReservation_r moved into inline code header because it
5155 * is now needed in vnode.c -- tkeiser 11/20/2007
5159 * decrement volume-package internal refcount.
5161 * @param vp volume object pointer
5163 * @internal volume package internal use only
5166 * @arg VOL_LOCK is held
5167 * @arg lightweight refcount held
5169 * @post volume waiters refcount is decremented; volume may
5170 * have been deallocated/shutdown/offlined/salvaged/
5171 * whatever during the process
5173 * @warning once you have tossed your last reference (you can acquire
5174 * lightweight refs recursively) it is NOT SAFE to reference
5175 * a volume object pointer ever again
5177 * @see VCreateReservation_r
5179 * @note DEMAND_ATTACH_FS only
5182 VCancelReservation_r(Volume * vp)
5184 osi_Assert(--vp->nWaiters >= 0);
5185 if (vp->nWaiters == 0) {
5187 if (!VCheckDetach(vp)) {
5194 /* check to see if we should free this volume now
5195 * return 1 if volume was freed, 0 otherwise */
5197 VCheckFree(Volume * vp)
5200 if ((vp->nUsers == 0) &&
5201 (vp->nWaiters == 0) &&
5202 !(V_attachFlags(vp) & (VOL_IN_HASH |
5206 ReallyFreeVolume(vp);
5211 #endif /* AFS_DEMAND_ATTACH_FS */
5214 /***************************************************/
5215 /* online volume operations routines */
5216 /***************************************************/
5218 #ifdef AFS_DEMAND_ATTACH_FS
5220 * register a volume operation on a given volume.
5222 * @param[in] vp volume object
5223 * @param[in] vopinfo volume operation info object
5225 * @pre VOL_LOCK is held
5227 * @post volume operation info object attached to volume object.
5228 * volume operation statistics updated.
5230 * @note by "attached" we mean a copy of the passed in object is made
5232 * @internal volume package internal use only
5235 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5237 FSSYNC_VolOp_info * info;
5239 /* attach a vol op info node to the volume struct */
5240 info = (FSSYNC_VolOp_info *) malloc(sizeof(FSSYNC_VolOp_info));
5241 osi_Assert(info != NULL);
5242 memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
5243 vp->pending_vol_op = info;
5246 vp->stats.last_vol_op = FT_ApproxTime();
5247 vp->stats.vol_ops++;
5248 IncUInt64(&VStats.vol_ops);
5254 * deregister the volume operation attached to this volume.
5256 * @param[in] vp volume object pointer
5258 * @pre VOL_LOCK is held
5260 * @post the volume operation info object is detached from the volume object
5262 * @internal volume package internal use only
5265 VDeregisterVolOp_r(Volume * vp)
5267 if (vp->pending_vol_op) {
5268 free(vp->pending_vol_op);
5269 vp->pending_vol_op = NULL;
5273 #endif /* AFS_DEMAND_ATTACH_FS */
5276 * determine whether it is safe to leave a volume online during
5277 * the volume operation described by the vopinfo object.
5279 * @param[in] vp volume object
5280 * @param[in] vopinfo volume operation info object
5282 * @return whether it is safe to leave volume online
5283 * @retval 0 it is NOT SAFE to leave the volume online
5284 * @retval 1 it is safe to leave the volume online during the operation
5287 * @arg VOL_LOCK is held
5288 * @arg disk header attached to vp (heavyweight ref on vp will guarantee
5289 * this condition is met)
5291 * @internal volume package internal use only
5294 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5296 return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
5297 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5298 (vopinfo->com.reason == V_READONLY ||
5299 (!VolumeWriteable(vp) &&
5300 (vopinfo->com.reason == V_CLONE ||
5301 vopinfo->com.reason == V_DUMP)))));
5305 * same as VVolOpLeaveOnline_r, but does not require a volume with an attached
5308 * @param[in] vp volume object
5309 * @param[in] vopinfo volume operation info object
5311 * @return whether it is safe to leave volume online
5312 * @retval 0 it is NOT SAFE to leave the volume online
5313 * @retval 1 it is safe to leave the volume online during the operation
5314 * @retval -1 unsure; volume header is required in order to know whether or
5315 * not is is safe to leave the volume online
5317 * @pre VOL_LOCK is held
5319 * @internal volume package internal use only
5322 VVolOpLeaveOnlineNoHeader_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5324 /* follow the logic in VVolOpLeaveOnline_r; this is the same, except
5325 * assume that we don't know VolumeWriteable; return -1 if the answer
5326 * depends on VolumeWriteable */
5328 if (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline) {
5331 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5332 vopinfo->com.reason == V_READONLY) {
5336 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5337 (vopinfo->com.reason == V_CLONE ||
5338 vopinfo->com.reason == V_DUMP)) {
5340 /* must know VolumeWriteable */
5347 * determine whether VBUSY should be set during this volume operation.
5349 * @param[in] vp volume object
5350 * @param[in] vopinfo volume operation info object
5352 * @return whether VBUSY should be set
5353 * @retval 0 VBUSY does NOT need to be set
5354 * @retval 1 VBUSY SHOULD be set
5356 * @pre VOL_LOCK is held
5358 * @internal volume package internal use only
5361 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5363 return ((vopinfo->com.command == FSYNC_VOL_OFF &&
5364 vopinfo->com.reason == FSYNC_SALVAGE) ||
5365 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5366 (vopinfo->com.reason == V_CLONE ||
5367 vopinfo->com.reason == V_DUMP)));
5371 /***************************************************/
5372 /* online salvager routines */
5373 /***************************************************/
5374 #if defined(AFS_DEMAND_ATTACH_FS)
5377 * offline a volume to let it be salvaged.
5379 * @param[in] vp Volume to offline
5381 * @return whether we offlined the volume successfully
5382 * @retval 0 volume was not offlined
5383 * @retval 1 volume is now offline
5385 * @note This is similar to VCheckOffline, but slightly different. We do not
5386 * deal with vp->goingOffline, and we try to avoid touching the volume
5387 * header except just to set needsSalvaged
5389 * @pre VOL_LOCK held
5390 * @pre vp->nUsers == 0
5391 * @pre V_attachState(vp) == VOL_STATE_SALVAGE_REQ
5394 VOfflineForSalvage_r(struct Volume *vp)
5398 VCreateReservation_r(vp);
5399 VWaitExclusiveState_r(vp);
5401 if (vp->nUsers || V_attachState(vp) == VOL_STATE_SALVAGING) {
5402 /* Someone's using the volume, or someone got to scheduling the salvage
5403 * before us. I don't think either of these should be possible, as we
5404 * should gain no new heavyweight references while we're trying to
5405 * salvage, but just to be sure... */
5406 VCancelReservation_r(vp);
5410 VChangeState_r(vp, VOL_STATE_OFFLINING);
5414 V_needsSalvaged(vp) = 1;
5415 /* ignore error; updating needsSalvaged is just best effort */
5416 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
5418 VCloseVolumeHandles_r(vp);
5420 FreeVolumeHeader(vp);
5422 /* volume has been effectively offlined; we can mark it in the SALVAGING
5423 * state now, which lets FSSYNC give it away */
5424 VChangeState_r(vp, VOL_STATE_SALVAGING);
5426 VCancelReservation_r(vp);
5432 * check whether a salvage needs to be performed on this volume.
5434 * @param[in] vp pointer to volume object
5436 * @return status code
5437 * @retval 0 no salvage scheduled
5438 * @retval 1 a salvage has been scheduled with the salvageserver
5440 * @pre VOL_LOCK is held
5442 * @post if salvage request flag is set and nUsers and nWaiters are zero,
5443 * then a salvage will be requested
5445 * @note this is one of the event handlers called by VCancelReservation_r
5447 * @note the caller must check if the volume needs to be freed after calling
5448 * this; the volume may not have any references or be on any lists after
5449 * we return, and we do not free it
5451 * @see VCancelReservation_r
5453 * @internal volume package internal use only.
5456 VCheckSalvage(Volume * vp)
5459 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5462 if (!vp->salvage.requested) {
5466 /* prevent recursion; some of the code below creates and removes
5467 * lightweight refs, which can call VCheckSalvage */
5468 if (vp->salvage.scheduling) {
5471 vp->salvage.scheduling = 1;
5473 if (V_attachState(vp) == VOL_STATE_SALVAGE_REQ) {
5474 if (!VOfflineForSalvage_r(vp)) {
5475 vp->salvage.scheduling = 0;
5480 if (vp->salvage.requested) {
5481 VScheduleSalvage_r(vp);
5484 vp->salvage.scheduling = 0;
5485 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5490 * request volume salvage.
5492 * @param[out] ec computed client error code
5493 * @param[in] vp volume object pointer
5494 * @param[in] reason reason code (passed to salvageserver via SALVSYNC)
5495 * @param[in] flags see flags note below
5498 * VOL_SALVAGE_INVALIDATE_HEADER causes volume header cache entry
5499 * to be invalidated.
5501 * @pre VOL_LOCK is held.
5503 * @post volume state is changed.
5504 * for fileserver, salvage will be requested once refcount reaches zero.
5506 * @return operation status code
5507 * @retval 0 volume salvage will occur
5508 * @retval 1 volume salvage could not be scheduled
5512 * @note in the fileserver, this call does not synchronously schedule a volume
5513 * salvage. rather, it sets volume state so that when volume refcounts
5514 * reach zero, a volume salvage will occur. by "refcounts", we mean both
5515 * nUsers and nWaiters must be zero.
5517 * @internal volume package internal use only.
5520 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
5524 * for DAFS volume utilities that are not supposed to schedule salvages,
5525 * just transition to error state instead
5527 if (!VCanScheduleSalvage()) {
5528 VChangeState_r(vp, VOL_STATE_ERROR);
5533 if (programType != fileServer && !VCanUseFSSYNC()) {
5534 VChangeState_r(vp, VOL_STATE_ERROR);
5539 if (!vp->salvage.requested) {
5540 vp->salvage.requested = 1;
5541 vp->salvage.reason = reason;
5542 vp->stats.last_salvage = FT_ApproxTime();
5544 /* Note that it is not possible for us to reach this point if a
5545 * salvage is already running on this volume (even if the fileserver
5546 * was restarted during the salvage). If a salvage were running, the
5547 * salvager would have write-locked the volume header file, so when
5548 * we tried to lock the volume header, the lock would have failed,
5549 * and we would have failed during attachment prior to calling
5550 * VRequestSalvage. So we know that we can schedule salvages without
5551 * fear of a salvage already running for this volume. */
5553 if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
5555 /* if we don't need to offline the volume, we can go directly
5556 * to SALVAGING. SALVAGING says the volume is offline and is
5557 * either salvaging or ready to be handed to the salvager.
5558 * SALVAGE_REQ says that we want to salvage the volume, but we
5559 * are waiting for it to go offline first. */
5560 if (flags & VOL_SALVAGE_NO_OFFLINE) {
5561 VChangeState_r(vp, VOL_STATE_SALVAGING);
5563 VChangeState_r(vp, VOL_STATE_SALVAGE_REQ);
5564 if (vp->nUsers == 0) {
5565 /* normally VOfflineForSalvage_r would be called from
5566 * PutVolume et al when nUsers reaches 0, but if
5567 * it's already 0, just do it ourselves, since PutVolume
5568 * isn't going to get called */
5569 VOfflineForSalvage_r(vp);
5574 Log("VRequestSalvage: volume %u online salvaged too many times; forced offline.\n", vp->hashid);
5576 /* make sure neither VScheduleSalvage_r nor
5577 * VUpdateSalvagePriority_r try to schedule another salvage */
5578 vp->salvage.requested = vp->salvage.scheduled = 0;
5580 VChangeState_r(vp, VOL_STATE_ERROR);
5584 if (flags & VOL_SALVAGE_INVALIDATE_HEADER) {
5585 /* Instead of ReleaseVolumeHeader, we do FreeVolumeHeader()
5586 so that the the next VAttachVolumeByVp_r() invocation
5587 of attach2() will pull in a cached header
5588 entry and fail, then load a fresh one from disk and attach
5591 FreeVolumeHeader(vp);
5598 * update salvageserver scheduling priority for a volume.
5600 * @param[in] vp pointer to volume object
5602 * @return operation status
5604 * @retval 1 request denied, or SALVSYNC communications failure
5606 * @pre VOL_LOCK is held.
5608 * @post in-core salvage priority counter is incremented. if at least
5609 * SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
5610 * last SALVSYNC_RAISEPRIO request, we contact the salvageserver
5611 * to update its priority queue. if no salvage is scheduled,
5612 * this function is a no-op.
5614 * @note DAFS fileserver only
5616 * @note this should be called whenever a VGetVolume fails due to a
5617 * pending salvage request
5619 * @todo should set exclusive state and drop glock around salvsync call
5621 * @internal volume package internal use only.
5624 VUpdateSalvagePriority_r(Volume * vp)
5628 #ifdef SALVSYNC_BUILD_CLIENT
5633 now = FT_ApproxTime();
5635 /* update the salvageserver priority queue occasionally so that
5636 * frequently requested volumes get moved to the head of the queue
5638 if ((vp->salvage.scheduled) &&
5639 (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
5640 code = SALVSYNC_SalvageVolume(vp->hashid,
5641 VPartitionPath(vp->partition),
5646 vp->stats.last_salvage_req = now;
5647 if (code != SYNC_OK) {
5651 #endif /* SALVSYNC_BUILD_CLIENT */
5656 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5658 /* A couple of little helper functions. These return true if we tried to
5659 * use this mechanism to schedule a salvage, false if we haven't tried.
5660 * If we did try a salvage then the results are contained in code.
5664 try_SALVSYNC(Volume *vp, char *partName, int *code) {
5665 #ifdef SALVSYNC_BUILD_CLIENT
5666 if (VCanUseSALVSYNC()) {
5667 Log("Scheduling salvage for volume %lu on part %s over SALVSYNC\n",
5668 afs_printable_uint32_lu(vp->hashid), partName);
5670 /* can't use V_id() since there's no guarantee
5671 * we have the disk data header at this point */
5672 *code = SALVSYNC_SalvageVolume(vp->hashid,
5685 try_FSSYNC(Volume *vp, char *partName, int *code) {
5686 #ifdef FSSYNC_BUILD_CLIENT
5687 if (VCanUseFSSYNC()) {
5688 Log("Scheduling salvage for volume %lu on part %s over FSSYNC\n",
5689 afs_printable_uint32_lu(vp->hashid), partName);
5692 * If we aren't the fileserver, tell the fileserver the volume
5693 * needs to be salvaged. We could directly tell the
5694 * salvageserver, but the fileserver keeps track of some stats
5695 * related to salvages, and handles some other salvage-related
5696 * complications for us.
5698 *code = FSYNC_VolOp(vp->hashid, partName,
5699 FSYNC_VOL_FORCE_ERROR, FSYNC_SALVAGE, NULL);
5702 #endif /* FSSYNC_BUILD_CLIENT */
5707 * schedule a salvage with the salvage server or fileserver.
5709 * @param[in] vp pointer to volume object
5711 * @return operation status
5712 * @retval 0 salvage scheduled successfully
5713 * @retval 1 salvage not scheduled, or SALVSYNC/FSSYNC com error
5716 * @arg VOL_LOCK is held.
5717 * @arg nUsers and nWaiters should be zero.
5719 * @post salvageserver or fileserver is sent a salvage request
5721 * @note If we are the fileserver, the request will be sent to the salvage
5722 * server over SALVSYNC. If we are not the fileserver, the request will be
5723 * sent to the fileserver over FSSYNC (FSYNC_VOL_FORCE_ERROR/FSYNC_SALVAGE).
5725 * @note the caller must check if the volume needs to be freed after calling
5726 * this; the volume may not have any references or be on any lists after
5727 * we return, and we do not free it
5731 * @internal volume package internal use only.
5734 VScheduleSalvage_r(Volume * vp)
5738 VolState state_save;
5739 VThreadOptions_t * thread_opts;
5742 osi_Assert(VCanUseSALVSYNC() || VCanUseFSSYNC());
5744 if (vp->nWaiters || vp->nUsers) {
5748 /* prevent endless salvage,attach,salvage,attach,... loops */
5749 if (vp->stats.salvages >= SALVAGE_COUNT_MAX)
5753 * don't perform salvsync ops on certain threads
5755 thread_opts = pthread_getspecific(VThread_key);
5756 if (thread_opts == NULL) {
5757 thread_opts = &VThread_defaults;
5759 if (thread_opts->disallow_salvsync || vol_disallow_salvsync) {
5763 if (vp->salvage.scheduled) {
5767 VCreateReservation_r(vp);
5768 VWaitExclusiveState_r(vp);
5771 * XXX the scheduling process should really be done asynchronously
5772 * to avoid fssync deadlocks
5774 if (!vp->salvage.scheduled) {
5775 /* if we haven't previously scheduled a salvage, do so now
5777 * set the volume to an exclusive state and drop the lock
5778 * around the SALVSYNC call
5780 strlcpy(partName, VPartitionPath(vp->partition), sizeof(partName));
5781 state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
5784 osi_Assert(try_SALVSYNC(vp, partName, &code) ||
5785 try_FSSYNC(vp, partName, &code));
5788 VChangeState_r(vp, state_save);
5790 if (code == SYNC_OK) {
5791 vp->salvage.scheduled = 1;
5792 vp->stats.last_salvage_req = FT_ApproxTime();
5793 if (VCanUseSALVSYNC()) {
5794 /* don't record these stats for non-fileservers; let the
5795 * fileserver take care of these */
5796 vp->stats.salvages++;
5797 IncUInt64(&VStats.salvages);
5802 case SYNC_BAD_COMMAND:
5803 case SYNC_COM_ERROR:
5806 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5807 "denied\n", afs_printable_uint32_lu(vp->hashid));
5810 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5811 "received unknown protocol error %d\n",
5812 afs_printable_uint32_lu(vp->hashid), code);
5816 if (VCanUseFSSYNC()) {
5817 VChangeState_r(vp, VOL_STATE_ERROR);
5822 /* NB: this is cancelling the reservation we obtained above, but we do
5823 * not call VCancelReservation_r, since that may trigger the vp dtor,
5824 * possibly free'ing the vp. We need to keep the vp around after
5825 * this, as the caller may reference vp without any refs. Instead, it
5826 * is the duty of the caller to inspect 'vp' after we return to see if
5827 * needs to be freed. */
5828 osi_Assert(--vp->nWaiters >= 0);
5831 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5833 #ifdef SALVSYNC_BUILD_CLIENT
5836 * connect to the salvageserver SYNC service.
5838 * @return operation status
5842 * @post connection to salvageserver SYNC service established
5844 * @see VConnectSALV_r
5845 * @see VDisconnectSALV
5846 * @see VReconnectSALV
5853 retVal = VConnectSALV_r();
5859 * connect to the salvageserver SYNC service.
5861 * @return operation status
5865 * @pre VOL_LOCK is held.
5867 * @post connection to salvageserver SYNC service established
5870 * @see VDisconnectSALV_r
5871 * @see VReconnectSALV_r
5872 * @see SALVSYNC_clientInit
5874 * @internal volume package internal use only.
5877 VConnectSALV_r(void)
5879 return SALVSYNC_clientInit();
5883 * disconnect from the salvageserver SYNC service.
5885 * @return operation status
5888 * @pre client should have a live connection to the salvageserver
5890 * @post connection to salvageserver SYNC service destroyed
5892 * @see VDisconnectSALV_r
5894 * @see VReconnectSALV
5897 VDisconnectSALV(void)
5900 VDisconnectSALV_r();
5906 * disconnect from the salvageserver SYNC service.
5908 * @return operation status
5912 * @arg VOL_LOCK is held.
5913 * @arg client should have a live connection to the salvageserver.
5915 * @post connection to salvageserver SYNC service destroyed
5917 * @see VDisconnectSALV
5918 * @see VConnectSALV_r
5919 * @see VReconnectSALV_r
5920 * @see SALVSYNC_clientFinis
5922 * @internal volume package internal use only.
5925 VDisconnectSALV_r(void)
5927 return SALVSYNC_clientFinis();
5931 * disconnect and then re-connect to the salvageserver SYNC service.
5933 * @return operation status
5937 * @pre client should have a live connection to the salvageserver
5939 * @post old connection is dropped, and a new one is established
5942 * @see VDisconnectSALV
5943 * @see VReconnectSALV_r
5946 VReconnectSALV(void)
5950 retVal = VReconnectSALV_r();
5956 * disconnect and then re-connect to the salvageserver SYNC service.
5958 * @return operation status
5963 * @arg VOL_LOCK is held.
5964 * @arg client should have a live connection to the salvageserver.
5966 * @post old connection is dropped, and a new one is established
5968 * @see VConnectSALV_r
5969 * @see VDisconnectSALV
5970 * @see VReconnectSALV
5971 * @see SALVSYNC_clientReconnect
5973 * @internal volume package internal use only.
5976 VReconnectSALV_r(void)
5978 return SALVSYNC_clientReconnect();
5980 #endif /* SALVSYNC_BUILD_CLIENT */
5981 #endif /* AFS_DEMAND_ATTACH_FS */
5984 /***************************************************/
5985 /* FSSYNC routines */
5986 /***************************************************/
5988 /* This must be called by any volume utility which needs to run while the
5989 file server is also running. This is separated from VInitVolumePackage2 so
5990 that a utility can fork--and each of the children can independently
5991 initialize communication with the file server */
5992 #ifdef FSSYNC_BUILD_CLIENT
5994 * connect to the fileserver SYNC service.
5996 * @return operation status
6001 * @arg VInit must equal 2.
6002 * @arg Program Type must not be fileserver or salvager.
6004 * @post connection to fileserver SYNC service established
6007 * @see VDisconnectFS
6008 * @see VChildProcReconnectFS
6015 retVal = VConnectFS_r();
6021 * connect to the fileserver SYNC service.
6023 * @return operation status
6028 * @arg VInit must equal 2.
6029 * @arg Program Type must not be fileserver or salvager.
6030 * @arg VOL_LOCK is held.
6032 * @post connection to fileserver SYNC service established
6035 * @see VDisconnectFS_r
6036 * @see VChildProcReconnectFS_r
6038 * @internal volume package internal use only.
6044 osi_Assert((VInit == 2) &&
6045 (programType != fileServer) &&
6046 (programType != salvager));
6047 rc = FSYNC_clientInit();
6055 * disconnect from the fileserver SYNC service.
6058 * @arg client should have a live connection to the fileserver.
6059 * @arg VOL_LOCK is held.
6060 * @arg Program Type must not be fileserver or salvager.
6062 * @post connection to fileserver SYNC service destroyed
6064 * @see VDisconnectFS
6066 * @see VChildProcReconnectFS_r
6068 * @internal volume package internal use only.
6071 VDisconnectFS_r(void)
6073 osi_Assert((programType != fileServer) &&
6074 (programType != salvager));
6075 FSYNC_clientFinis();
6080 * disconnect from the fileserver SYNC service.
6083 * @arg client should have a live connection to the fileserver.
6084 * @arg Program Type must not be fileserver or salvager.
6086 * @post connection to fileserver SYNC service destroyed
6088 * @see VDisconnectFS_r
6090 * @see VChildProcReconnectFS
6101 * connect to the fileserver SYNC service from a child process following a fork.
6103 * @return operation status
6108 * @arg VOL_LOCK is held.
6109 * @arg current FSYNC handle is shared with a parent process
6111 * @post current FSYNC handle is discarded and a new connection to the
6112 * fileserver SYNC service is established
6114 * @see VChildProcReconnectFS
6116 * @see VDisconnectFS_r
6118 * @internal volume package internal use only.
6121 VChildProcReconnectFS_r(void)
6123 return FSYNC_clientChildProcReconnect();
6127 * connect to the fileserver SYNC service from a child process following a fork.
6129 * @return operation status
6133 * @pre current FSYNC handle is shared with a parent process
6135 * @post current FSYNC handle is discarded and a new connection to the
6136 * fileserver SYNC service is established
6138 * @see VChildProcReconnectFS_r
6140 * @see VDisconnectFS
6143 VChildProcReconnectFS(void)
6147 ret = VChildProcReconnectFS_r();
6151 #endif /* FSSYNC_BUILD_CLIENT */
6154 /***************************************************/
6155 /* volume bitmap routines */
6156 /***************************************************/
6159 * allocate a vnode bitmap number for the vnode
6161 * @param[out] ec error code
6162 * @param[in] vp volume object pointer
6163 * @param[in] index vnode index number for the vnode
6164 * @param[in] flags flag values described in note
6166 * @note for DAFS, flags parameter controls locking behavior.
6167 * If (flags & VOL_ALLOC_BITMAP_WAIT) is set, then this function
6168 * will create a reservation and block on any other exclusive
6169 * operations. Otherwise, this function assumes the caller
6170 * already has exclusive access to vp, and we just change the
6173 * @pre VOL_LOCK held
6175 * @return bit number allocated
6181 VAllocBitmapEntry_r(Error * ec, Volume * vp,
6182 struct vnodeIndex *index, int flags)
6186 #ifdef AFS_DEMAND_ATTACH_FS
6187 VolState state_save;
6188 #endif /* AFS_DEMAND_ATTACH_FS */
6192 /* This test is probably redundant */
6193 if (!VolumeWriteable(vp)) {
6194 *ec = (bit32) VREADONLY;
6198 #ifdef AFS_DEMAND_ATTACH_FS
6199 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6200 VCreateReservation_r(vp);
6201 VWaitExclusiveState_r(vp);
6203 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6204 #endif /* AFS_DEMAND_ATTACH_FS */
6207 if ((programType == fileServer) && !index->bitmap) {
6209 #ifndef AFS_DEMAND_ATTACH_FS
6210 /* demand attach fs uses the volume state to avoid races.
6211 * specialStatus field is not used at all */
6213 if (vp->specialStatus == VBUSY) {
6214 if (vp->goingOffline) { /* vos dump waiting for the volume to
6215 * go offline. We probably come here
6216 * from AddNewReadableResidency */
6219 while (vp->specialStatus == VBUSY) {
6220 #ifdef AFS_PTHREAD_ENV
6224 #else /* !AFS_PTHREAD_ENV */
6226 #endif /* !AFS_PTHREAD_ENV */
6230 #endif /* !AFS_DEMAND_ATTACH_FS */
6232 if (!index->bitmap) {
6233 #ifndef AFS_DEMAND_ATTACH_FS
6234 vp->specialStatus = VBUSY; /* Stop anyone else from using it. */
6235 #endif /* AFS_DEMAND_ATTACH_FS */
6236 for (i = 0; i < nVNODECLASSES; i++) {
6237 VGetBitmap_r(ec, vp, i);
6239 #ifdef AFS_DEMAND_ATTACH_FS
6240 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
6241 #else /* AFS_DEMAND_ATTACH_FS */
6242 DeleteVolumeFromHashTable(vp);
6243 vp->shuttingDown = 1; /* Let who has it free it. */
6244 vp->specialStatus = 0;
6245 #endif /* AFS_DEMAND_ATTACH_FS */
6249 #ifndef AFS_DEMAND_ATTACH_FS
6251 vp->specialStatus = 0; /* Allow others to have access. */
6252 #endif /* AFS_DEMAND_ATTACH_FS */
6255 #endif /* BITMAP_LATER */
6257 #ifdef AFS_DEMAND_ATTACH_FS
6259 #endif /* AFS_DEMAND_ATTACH_FS */
6260 bp = index->bitmap + index->bitmapOffset;
6261 ep = index->bitmap + index->bitmapSize;
6263 if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
6265 index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
6268 o = ffs(~*bp) - 1; /* ffs is documented in BSTRING(3) */
6270 ret = ((bp - index->bitmap) * 8 + o);
6271 #ifdef AFS_DEMAND_ATTACH_FS
6273 #endif /* AFS_DEMAND_ATTACH_FS */
6276 bp += sizeof(bit32) /* i.e. 4 */ ;
6278 /* No bit map entry--must grow bitmap */
6280 realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
6281 osi_Assert(bp != NULL);
6283 bp += index->bitmapSize;
6284 memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
6285 index->bitmapOffset = index->bitmapSize;
6286 index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
6288 ret = index->bitmapOffset * 8;
6289 #ifdef AFS_DEMAND_ATTACH_FS
6291 #endif /* AFS_DEMAND_ATTACH_FS */
6294 #ifdef AFS_DEMAND_ATTACH_FS
6295 VChangeState_r(vp, state_save);
6296 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6297 VCancelReservation_r(vp);
6299 #endif /* AFS_DEMAND_ATTACH_FS */
6304 VAllocBitmapEntry(Error * ec, Volume * vp, struct vnodeIndex * index)
6308 retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
6314 VFreeBitMapEntry_r(Error * ec, struct vnodeIndex *index,
6317 unsigned int offset;
6323 #endif /* BITMAP_LATER */
6324 offset = bitNumber >> 3;
6325 if (offset >= index->bitmapSize) {
6329 if (offset < index->bitmapOffset)
6330 index->bitmapOffset = offset & ~3; /* Truncate to nearest bit32 */
6331 *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
6335 VFreeBitMapEntry(Error * ec, struct vnodeIndex *index,
6339 VFreeBitMapEntry_r(ec, index, bitNumber);
6343 /* this function will drop the glock internally.
6344 * for old pthread fileservers, this is safe thanks to vbusy.
6346 * for demand attach fs, caller must have already called
6347 * VCreateReservation_r and VWaitExclusiveState_r */
6349 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
6351 StreamHandle_t *file;
6352 afs_sfsize_t nVnodes, size;
6353 struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
6354 struct vnodeIndex *vip = &vp->vnodeIndex[class];
6355 struct VnodeDiskObject *vnode;
6356 unsigned int unique = 0;
6360 #endif /* BITMAP_LATER */
6361 #ifdef AFS_DEMAND_ATTACH_FS
6362 VolState state_save;
6363 #endif /* AFS_DEMAND_ATTACH_FS */
6367 #ifdef AFS_DEMAND_ATTACH_FS
6368 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6369 #endif /* AFS_DEMAND_ATTACH_FS */
6372 fdP = IH_OPEN(vip->handle);
6373 osi_Assert(fdP != NULL);
6374 file = FDH_FDOPEN(fdP, "r");
6375 osi_Assert(file != NULL);
6376 vnode = (VnodeDiskObject *) malloc(vcp->diskSize);
6377 osi_Assert(vnode != NULL);
6378 size = OS_SIZE(fdP->fd_fd);
6379 osi_Assert(size != -1);
6380 nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
6382 vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4; /* The 10 is a little extra so
6383 * a few files can be created in this volume,
6384 * the whole thing is rounded up to nearest 4
6385 * bytes, because the bit map allocator likes
6388 BitMap = (byte *) calloc(1, vip->bitmapSize);
6389 osi_Assert(BitMap != NULL);
6390 #else /* BITMAP_LATER */
6391 vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
6392 osi_Assert(vip->bitmap != NULL);
6393 vip->bitmapOffset = 0;
6394 #endif /* BITMAP_LATER */
6395 if (STREAM_ASEEK(file, vcp->diskSize) != -1) {
6397 for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
6398 if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
6400 if (vnode->type != vNull) {
6401 if (vnode->vnodeMagic != vcp->magic) {
6402 Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
6407 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6408 #else /* BITMAP_LATER */
6409 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6410 #endif /* BITMAP_LATER */
6411 if (unique <= vnode->uniquifier)
6412 unique = vnode->uniquifier + 1;
6414 #ifndef AFS_PTHREAD_ENV
6415 if ((bitNumber & 0x00ff) == 0x0ff) { /* every 256 iterations */
6418 #endif /* !AFS_PTHREAD_ENV */
6421 if (vp->nextVnodeUnique < unique) {
6422 Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
6425 /* Paranoia, partly justified--I think fclose after fdopen
6426 * doesn't seem to close fd. In any event, the documentation
6427 * doesn't specify, so it's safer to close it twice.
6435 /* There may have been a racing condition with some other thread, both
6436 * creating the bitmaps for this volume. If the other thread was faster
6437 * the pointer to bitmap should already be filled and we can free ours.
6439 if (vip->bitmap == NULL) {
6440 vip->bitmap = BitMap;
6441 vip->bitmapOffset = 0;
6443 free((byte *) BitMap);
6444 #endif /* BITMAP_LATER */
6445 #ifdef AFS_DEMAND_ATTACH_FS
6446 VChangeState_r(vp, state_save);
6447 #endif /* AFS_DEMAND_ATTACH_FS */
6451 /***************************************************/
6452 /* Volume Path and Volume Number utility routines */
6453 /***************************************************/
6456 * find the first occurrence of a volume header file and return the path.
6458 * @param[out] ec outbound error code
6459 * @param[in] volumeId volume id to find
6460 * @param[out] partitionp pointer to disk partition path string
6461 * @param[out] namep pointer to volume header file name string
6463 * @post path to first occurrence of volume header is returned in partitionp
6464 * and namep, or ec is set accordingly.
6466 * @warning this function is NOT re-entrant -- partitionp and namep point to
6467 * static data segments
6469 * @note if a volume utility inadvertently leaves behind a stale volume header
6470 * on a vice partition, it is possible for callers to get the wrong one,
6471 * depending on the order of the disk partition linked list.
6475 VGetVolumePath(Error * ec, VolId volumeId, char **partitionp, char **namep)
6477 static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
6478 char path[VMAXPATHLEN];
6480 struct DiskPartition64 *dp;
6483 name[0] = OS_DIRSEPC;
6484 (void)afs_snprintf(&name[1], (sizeof name) - 1, VFORMAT, afs_printable_uint32_lu(volumeId));
6485 for (dp = DiskPartitionList; dp; dp = dp->next) {
6486 struct afs_stat status;
6487 strcpy(path, VPartitionPath(dp));
6489 if (afs_stat(path, &status) == 0) {
6490 strcpy(partition, dp->name);
6497 *partitionp = *namep = NULL;
6499 *partitionp = partition;
6505 * extract a volume number from a volume header filename string.
6507 * @param[in] name volume header filename string
6509 * @return volume number
6511 * @note the string must be of the form VFORMAT. the only permissible
6512 * deviation is a leading OS_DIRSEPC character.
6517 VolumeNumber(char *name)
6519 if (*name == OS_DIRSEPC)
6521 return atoi(name + 1);
6525 * compute the volume header filename.
6527 * @param[in] volumeId
6529 * @return volume header filename
6531 * @post volume header filename string is constructed
6533 * @warning this function is NOT re-entrant -- the returned string is
6534 * stored in a static char array. see VolumeExternalName_r
6535 * for a re-entrant equivalent.
6537 * @see VolumeExternalName_r
6539 * @deprecated due to the above re-entrancy warning, this interface should
6540 * be considered deprecated. Please use VolumeExternalName_r
6544 VolumeExternalName(VolumeId volumeId)
6546 static char name[VMAXPATHLEN];
6547 (void)afs_snprintf(name, sizeof name, VFORMAT, afs_printable_uint32_lu(volumeId));
6552 * compute the volume header filename.
6554 * @param[in] volumeId
6555 * @param[inout] name array in which to store filename
6556 * @param[in] len length of name array
6558 * @return result code from afs_snprintf
6560 * @see VolumeExternalName
6563 * @note re-entrant equivalent of VolumeExternalName
6566 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
6568 return afs_snprintf(name, len, VFORMAT, afs_printable_uint32_lu(volumeId));
6572 /***************************************************/
6573 /* Volume Usage Statistics routines */
6574 /***************************************************/
6576 #if OPENAFS_VOL_STATS
6577 #define OneDay (86400) /* 24 hours' worth of seconds */
6579 #define OneDay (24*60*60) /* 24 hours */
6580 #endif /* OPENAFS_VOL_STATS */
6583 Midnight(time_t t) {
6584 struct tm local, *l;
6587 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
6588 l = localtime_r(&t, &local);
6594 /* the following is strictly speaking problematic on the
6595 switching day to daylight saving time, after the switch,
6596 as tm_isdst does not match. Similarly, on the looong day when
6597 switching back the OneDay check will not do what naively expected!
6598 The effects are minor, though, and more a matter of interpreting
6600 #ifndef AFS_PTHREAD_ENV
6603 local.tm_hour = local.tm_min=local.tm_sec = 0;
6604 midnight = mktime(&local);
6605 if (midnight != (time_t) -1) return(midnight);
6607 return( (t/OneDay)*OneDay );
6611 /*------------------------------------------------------------------------
6612 * [export] VAdjustVolumeStatistics
6615 * If we've passed midnight, we need to update all the day use
6616 * statistics as well as zeroing the detailed volume statistics
6617 * (if we are implementing them).
6620 * vp : Pointer to the volume structure describing the lucky
6621 * volume being considered for update.
6627 * Nothing interesting.
6631 *------------------------------------------------------------------------*/
6634 VAdjustVolumeStatistics_r(Volume * vp)
6636 unsigned int now = FT_ApproxTime();
6638 if (now - V_dayUseDate(vp) > OneDay) {
6641 ndays = (now - V_dayUseDate(vp)) / OneDay;
6642 for (i = 6; i > ndays - 1; i--)
6643 V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
6644 for (i = 0; i < ndays - 1 && i < 7; i++)
6645 V_weekUse(vp)[i] = 0;
6647 V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
6649 V_dayUseDate(vp) = Midnight(now);
6651 #if OPENAFS_VOL_STATS
6653 * All we need to do is bzero the entire VOL_STATS_BYTES of
6654 * the detailed volume statistics area.
6656 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
6657 #endif /* OPENAFS_VOL_STATS */
6660 /*It's been more than a day of collection */
6662 * Always return happily.
6665 } /*VAdjustVolumeStatistics */
6668 VAdjustVolumeStatistics(Volume * vp)
6672 retVal = VAdjustVolumeStatistics_r(vp);
6678 VBumpVolumeUsage_r(Volume * vp)
6680 unsigned int now = FT_ApproxTime();
6681 V_accessDate(vp) = now;
6682 if (now - V_dayUseDate(vp) > OneDay)
6683 VAdjustVolumeStatistics_r(vp);
6685 * Save the volume header image to disk after every 128 bumps to dayUse.
6687 if ((V_dayUse(vp)++ & 127) == 0) {
6689 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
6694 VBumpVolumeUsage(Volume * vp)
6697 VBumpVolumeUsage_r(vp);
6702 VSetDiskUsage_r(void)
6704 #ifndef AFS_DEMAND_ATTACH_FS
6705 static int FifteenMinuteCounter = 0;
6709 /* NOTE: Don't attempt to access the partitions list until the
6710 * initialization level indicates that all volumes are attached,
6711 * which implies that all partitions are initialized. */
6712 #ifdef AFS_PTHREAD_ENV
6713 VOL_CV_WAIT(&vol_vinit_cond);
6714 #else /* AFS_PTHREAD_ENV */
6716 #endif /* AFS_PTHREAD_ENV */
6719 VResetDiskUsage_r();
6721 #ifndef AFS_DEMAND_ATTACH_FS
6722 if (++FifteenMinuteCounter == 3) {
6723 FifteenMinuteCounter = 0;
6726 #endif /* !AFS_DEMAND_ATTACH_FS */
6738 /***************************************************/
6739 /* Volume Update List routines */
6740 /***************************************************/
6742 /* The number of minutes that a volume hasn't been updated before the
6743 * "Dont salvage" flag in the volume header will be turned on */
6744 #define SALVAGE_INTERVAL (10*60)
6749 * volume update list functionality has been moved into the VLRU
6750 * the DONT_SALVAGE flag is now set during VLRU demotion
6753 #ifndef AFS_DEMAND_ATTACH_FS
6754 static VolumeId *UpdateList = NULL; /* Pointer to array of Volume ID's */
6755 static int nUpdatedVolumes = 0; /* Updated with entry in UpdateList, salvage after crash flag on */
6756 static int updateSize = 0; /* number of entries possible */
6757 #define UPDATE_LIST_SIZE 128 /* initial size increment (must be a power of 2!) */
6758 #endif /* !AFS_DEMAND_ATTACH_FS */
6761 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
6764 vp->updateTime = FT_ApproxTime();
6765 if (V_dontSalvage(vp) == 0)
6767 V_dontSalvage(vp) = 0;
6768 VSyncVolume_r(ec, vp, 0);
6769 #ifdef AFS_DEMAND_ATTACH_FS
6770 V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
6771 #else /* !AFS_DEMAND_ATTACH_FS */
6774 if (UpdateList == NULL) {
6775 updateSize = UPDATE_LIST_SIZE;
6776 UpdateList = (VolumeId *) malloc(sizeof(VolumeId) * updateSize);
6778 if (nUpdatedVolumes == updateSize) {
6780 if (updateSize > 524288) {
6781 Log("warning: there is likely a bug in the volume update scanner\n");
6785 (VolumeId *) realloc(UpdateList,
6786 sizeof(VolumeId) * updateSize);
6789 osi_Assert(UpdateList != NULL);
6790 UpdateList[nUpdatedVolumes++] = V_id(vp);
6791 #endif /* !AFS_DEMAND_ATTACH_FS */
6794 #ifndef AFS_DEMAND_ATTACH_FS
6796 VScanUpdateList(void)
6801 afs_uint32 now = FT_ApproxTime();
6802 /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
6803 for (i = gap = 0; i < nUpdatedVolumes; i++) {
6805 UpdateList[i - gap] = UpdateList[i];
6807 /* XXX this routine needlessly messes up the Volume LRU by
6808 * breaking the LRU temporal-locality assumptions.....
6809 * we should use a special volume header allocator here */
6810 vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
6813 } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
6814 V_dontSalvage(vp) = DONT_SALVAGE;
6815 VUpdateVolume_r(&error, vp, 0); /* No need to fsync--not critical */
6823 #ifndef AFS_PTHREAD_ENV
6825 #endif /* !AFS_PTHREAD_ENV */
6827 nUpdatedVolumes -= gap;
6829 #endif /* !AFS_DEMAND_ATTACH_FS */
6832 /***************************************************/
6833 /* Volume LRU routines */
6834 /***************************************************/
6839 * with demand attach fs, we attempt to soft detach(1)
6840 * volumes which have not been accessed in a long time
6841 * in order to speed up fileserver shutdown
6843 * (1) by soft detach we mean a process very similar
6844 * to VOffline, except the final state of the
6845 * Volume will be VOL_STATE_PREATTACHED, instead
6846 * of the usual VOL_STATE_UNATTACHED
6848 #ifdef AFS_DEMAND_ATTACH_FS
6850 /* implementation is reminiscent of a generational GC
6852 * queue 0 is newly attached volumes. this queue is
6853 * sorted by attach timestamp
6855 * queue 1 is volumes that have been around a bit
6856 * longer than queue 0. this queue is sorted by
6859 * queue 2 is volumes tha have been around the longest.
6860 * this queue is unsorted
6862 * queue 3 is volumes that have been marked as
6863 * candidates for soft detachment. this queue is
6866 #define VLRU_GENERATIONS 3 /**< number of generations in VLRU */
6867 #define VLRU_QUEUES 5 /**< total number of VLRU queues */
6870 * definition of a VLRU queue.
6873 volatile struct rx_queue q;
6880 * main VLRU data structure.
6883 struct VLRU_q q[VLRU_QUEUES]; /**< VLRU queues */
6886 /** time interval (in seconds) between promotion passes for
6887 * each young generation queue. */
6888 afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
6890 /** time interval (in seconds) between soft detach candidate
6891 * scans for each generation queue.
6893 * scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
6894 * we perform a soft detach pass. */
6895 afs_uint32 scan_interval[VLRU_GENERATIONS+1];
6897 /* scheduler state */
6898 int next_idx; /**< next queue to receive attention */
6899 afs_uint32 last_promotion[VLRU_GENERATIONS-1]; /**< timestamp of last promotion scan */
6900 afs_uint32 last_scan[VLRU_GENERATIONS+1]; /**< timestamp of last detach scan */
6902 int scanner_state; /**< state of scanner thread */
6903 pthread_cond_t cv; /**< state transition CV */
6906 /** global VLRU state */
6907 static struct VLRU volume_LRU;
6910 * defined states for VLRU scanner thread.
6913 VLRU_SCANNER_STATE_OFFLINE = 0, /**< vlru scanner thread is offline */
6914 VLRU_SCANNER_STATE_ONLINE = 1, /**< vlru scanner thread is online */
6915 VLRU_SCANNER_STATE_SHUTTING_DOWN = 2, /**< vlru scanner thread is shutting down */
6916 VLRU_SCANNER_STATE_PAUSING = 3, /**< vlru scanner thread is getting ready to pause */
6917 VLRU_SCANNER_STATE_PAUSED = 4 /**< vlru scanner thread is paused */
6918 } vlru_thread_state_t;
6920 /* vlru disk data header stuff */
6921 #define VLRU_DISK_MAGIC 0x7a8b9cad /**< vlru disk entry magic number */
6922 #define VLRU_DISK_VERSION 1 /**< vlru disk entry version number */
6924 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
6925 #define VLRU_DUMP_EXPIRATION_TIME (60*60*24*7) /* expire vlru data after 1 week */
6928 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
6929 * soft detachment. */
6930 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
6932 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
6933 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
6935 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
6936 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
6938 /** VLRU control flag. non-zero value implies VLRU subsystem is activated. */
6939 static afs_uint32 VLRU_enabled = 1;
6941 /* queue synchronization routines */
6942 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
6943 static void VLRU_EndExclusive_r(struct VLRU_q * q);
6944 static void VLRU_Wait_r(struct VLRU_q * q);
6947 * set VLRU subsystem tunable parameters.
6949 * @param[in] option tunable option to modify
6950 * @param[in] val new value for tunable parameter
6952 * @pre @c VInitVolumePackage2 has not yet been called.
6954 * @post tunable parameter is modified
6958 * @note valid option parameters are:
6959 * @arg @c VLRU_SET_THRESH
6960 * set the period of inactivity after which
6961 * volumes are eligible for soft detachment
6962 * @arg @c VLRU_SET_INTERVAL
6963 * set the time interval between calls
6964 * to the volume LRU "garbage collector"
6965 * @arg @c VLRU_SET_MAX
6966 * set the max number of volumes to deallocate
6970 VLRU_SetOptions(int option, afs_uint32 val)
6972 if (option == VLRU_SET_THRESH) {
6973 VLRU_offline_thresh = val;
6974 } else if (option == VLRU_SET_INTERVAL) {
6975 VLRU_offline_interval = val;
6976 } else if (option == VLRU_SET_MAX) {
6977 VLRU_offline_max = val;
6978 } else if (option == VLRU_SET_ENABLED) {
6981 VLRU_ComputeConstants();
6985 * compute VLRU internal timing parameters.
6987 * @post VLRU scanner thread internal timing parameters are computed
6989 * @note computes internal timing parameters based upon user-modifiable
6990 * tunable parameters.
6994 * @internal volume package internal use only.
6997 VLRU_ComputeConstants(void)
6999 afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
7001 /* compute the candidate scan interval */
7002 volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
7004 /* compute the promotion intervals */
7005 volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
7006 volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
7009 /* compute the gen 0 scan interval */
7010 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
7012 /* compute the gen 0 scan interval */
7013 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
7018 * initialize VLRU subsystem.
7020 * @pre this function has not yet been called
7022 * @post VLRU subsystem is initialized and VLRU scanner thread is starting
7026 * @internal volume package internal use only.
7032 pthread_attr_t attrs;
7035 if (!VLRU_enabled) {
7036 Log("VLRU: disabled\n");
7040 /* initialize each of the VLRU queues */
7041 for (i = 0; i < VLRU_QUEUES; i++) {
7042 queue_Init(&volume_LRU.q[i]);
7043 volume_LRU.q[i].len = 0;
7044 volume_LRU.q[i].busy = 0;
7045 CV_INIT(&volume_LRU.q[i].cv, "vol lru", CV_DEFAULT, 0);
7048 /* setup the timing constants */
7049 VLRU_ComputeConstants();
7051 /* XXX put inside LogLevel check? */
7052 Log("VLRU: starting scanner with the following configuration parameters:\n");
7053 Log("VLRU: offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
7054 Log("VLRU: running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
7055 Log("VLRU: taking up to %d volumes offline per pass\n", VLRU_offline_max);
7056 Log("VLRU: scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
7057 Log("VLRU: scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
7058 Log("VLRU: scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
7060 /* start up the VLRU scanner */
7061 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7062 if (programType == fileServer) {
7063 CV_INIT(&volume_LRU.cv, "vol lru", CV_DEFAULT, 0);
7064 osi_Assert(pthread_attr_init(&attrs) == 0);
7065 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
7066 osi_Assert(pthread_create(&tid, &attrs, &VLRU_ScannerThread, NULL) == 0);
7071 * initialize the VLRU-related fields of a newly allocated volume object.
7073 * @param[in] vp pointer to volume object
7076 * @arg @c VOL_LOCK is held.
7077 * @arg volume object is not on a VLRU queue.
7079 * @post VLRU fields are initialized to indicate that volume object is not
7080 * currently registered with the VLRU subsystem
7084 * @internal volume package interal use only.
7087 VLRU_Init_Node_r(Volume * vp)
7092 osi_Assert(queue_IsNotOnQueue(&vp->vlru));
7093 vp->vlru.idx = VLRU_QUEUE_INVALID;
7097 * add a volume object to a VLRU queue.
7099 * @param[in] vp pointer to volume object
7102 * @arg @c VOL_LOCK is held.
7103 * @arg caller MUST hold a lightweight ref on @p vp.
7104 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7106 * @post the volume object is added to the appropriate VLRU queue
7108 * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
7109 * then the volume is added to that queue. Otherwise, the value
7110 * @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
7111 * volume is added to the NEW generation queue.
7113 * @note @c VOL_LOCK may be dropped internally
7115 * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
7116 * during the add operation, and is restored to the previous
7117 * state prior to return.
7121 * @internal volume package internal use only.
7124 VLRU_Add_r(Volume * vp)
7127 VolState state_save;
7132 if (queue_IsOnQueue(&vp->vlru))
7135 state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
7138 if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
7139 idx = VLRU_QUEUE_NEW;
7142 VLRU_Wait_r(&volume_LRU.q[idx]);
7144 /* repeat check since VLRU_Wait_r may have dropped
7146 if (queue_IsNotOnQueue(&vp->vlru)) {
7148 queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
7149 volume_LRU.q[idx].len++;
7150 V_attachFlags(vp) |= VOL_ON_VLRU;
7151 vp->stats.last_promote = FT_ApproxTime();
7154 VChangeState_r(vp, state_save);
7158 * delete a volume object from a VLRU queue.
7160 * @param[in] vp pointer to volume object
7163 * @arg @c VOL_LOCK is held.
7164 * @arg caller MUST hold a lightweight ref on @p vp.
7165 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7167 * @post volume object is removed from the VLRU queue
7169 * @note @c VOL_LOCK may be dropped internally
7173 * @todo We should probably set volume state to something exlcusive
7174 * (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
7176 * @internal volume package internal use only.
7179 VLRU_Delete_r(Volume * vp)
7186 if (queue_IsNotOnQueue(&vp->vlru))
7192 if (idx == VLRU_QUEUE_INVALID)
7194 VLRU_Wait_r(&volume_LRU.q[idx]);
7195 } while (idx != vp->vlru.idx);
7197 /* now remove from the VLRU and update
7198 * the appropriate counter */
7199 queue_Remove(&vp->vlru);
7200 volume_LRU.q[idx].len--;
7201 vp->vlru.idx = VLRU_QUEUE_INVALID;
7202 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7206 * tell the VLRU subsystem that a volume was just accessed.
7208 * @param[in] vp pointer to volume object
7211 * @arg @c VOL_LOCK is held
7212 * @arg caller MUST hold a lightweight ref on @p vp
7213 * @arg caller MUST NOT hold exclusive ownership of any VLRU queue
7215 * @post volume VLRU access statistics are updated. If the volume was on
7216 * the VLRU soft detach candidate queue, it is moved to the NEW
7219 * @note @c VOL_LOCK may be dropped internally
7223 * @internal volume package internal use only.
7226 VLRU_UpdateAccess_r(Volume * vp)
7228 Volume * rvp = NULL;
7233 if (queue_IsNotOnQueue(&vp->vlru))
7236 osi_Assert(V_attachFlags(vp) & VOL_ON_VLRU);
7238 /* update the access timestamp */
7239 vp->stats.last_get = FT_ApproxTime();
7242 * if the volume is on the soft detach candidate
7243 * list, we need to safely move it back to a
7244 * regular generation. this has to be done
7245 * carefully so we don't race against the scanner
7249 /* if this volume is on the soft detach candidate queue,
7250 * then grab exclusive access to the necessary queues */
7251 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7253 VCreateReservation_r(rvp);
7255 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7256 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7257 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7258 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7261 /* make sure multiple threads don't race to update */
7262 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7263 VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
7267 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7268 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7269 VCancelReservation_r(rvp);
7274 * switch a volume between two VLRU queues.
7276 * @param[in] vp pointer to volume object
7277 * @param[in] new_idx index of VLRU queue onto which the volume will be moved
7278 * @param[in] append controls whether the volume will be appended or
7279 * prepended to the queue. A nonzero value means it will
7280 * be appended; zero means it will be prepended.
7282 * @pre The new (and old, if applicable) queue(s) must either be owned
7283 * exclusively by the calling thread for asynchronous manipulation,
7284 * or the queue(s) must be quiescent and VOL_LOCK must be held.
7285 * Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
7286 * for further details of the queue asynchronous processing mechanism.
7288 * @post If the volume object was already on a VLRU queue, it is
7289 * removed from the queue. Depending on the value of the append
7290 * parameter, the volume object is either appended or prepended
7291 * to the VLRU queue referenced by the new_idx parameter.
7295 * @see VLRU_BeginExclusive_r
7296 * @see VLRU_EndExclusive_r
7299 * @internal volume package internal use only.
7302 VLRU_SwitchQueues(Volume * vp, int new_idx, int append)
7304 if (queue_IsNotOnQueue(&vp->vlru))
7307 queue_Remove(&vp->vlru);
7308 volume_LRU.q[vp->vlru.idx].len--;
7310 /* put the volume back on the correct generational queue */
7312 queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
7314 queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
7317 volume_LRU.q[new_idx].len++;
7318 vp->vlru.idx = new_idx;
7322 * VLRU background thread.
7324 * The VLRU Scanner Thread is responsible for periodically scanning through
7325 * each VLRU queue looking for volumes which should be moved to another
7326 * queue, or soft detached.
7328 * @param[in] args unused thread arguments parameter
7330 * @return unused thread return value
7331 * @retval NULL always
7333 * @internal volume package internal use only.
7336 VLRU_ScannerThread(void * args)
7338 afs_uint32 now, min_delay, delay;
7339 int i, min_idx, min_op, overdue, state;
7341 /* set t=0 for promotion cycle to be
7342 * fileserver startup */
7343 now = FT_ApproxTime();
7344 for (i=0; i < VLRU_GENERATIONS-1; i++) {
7345 volume_LRU.last_promotion[i] = now;
7348 /* don't start the scanner until VLRU_offline_thresh
7349 * plus a small delay for VInitVolumePackage2 to finish
7352 sleep(VLRU_offline_thresh + 60);
7354 /* set t=0 for scan cycle to be now */
7355 now = FT_ApproxTime();
7356 for (i=0; i < VLRU_GENERATIONS+1; i++) {
7357 volume_LRU.last_scan[i] = now;
7361 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
7362 volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
7365 while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
7366 /* check to see if we've been asked to pause */
7367 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
7368 volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
7369 CV_BROADCAST(&volume_LRU.cv);
7371 VOL_CV_WAIT(&volume_LRU.cv);
7372 } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
7375 /* scheduling can happen outside the glock */
7378 /* figure out what is next on the schedule */
7380 /* figure out a potential schedule for the new generation first */
7382 min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
7385 if (min_delay > volume_LRU.scan_interval[0]) {
7386 /* unsigned overflow -- we're overdue to run this scan */
7391 /* if we're not overdue for gen 0, figure out schedule for candidate gen */
7393 i = VLRU_QUEUE_CANDIDATE;
7394 delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
7395 if (delay < min_delay) {
7399 if (delay > volume_LRU.scan_interval[i]) {
7400 /* unsigned overflow -- we're overdue to run this scan */
7407 /* if we're still not overdue for something, figure out schedules for promotions */
7408 for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
7409 delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
7410 if (delay < min_delay) {
7415 if (delay > volume_LRU.promotion_interval[i]) {
7416 /* unsigned overflow -- we're overdue to run this promotion */
7425 /* sleep as needed */
7430 /* do whatever is next */
7433 VLRU_Promote_r(min_idx);
7434 VLRU_Demote_r(min_idx+1);
7436 VLRU_Scan_r(min_idx);
7438 now = FT_ApproxTime();
7441 Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
7443 /* signal that scanner is down */
7444 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7445 CV_BROADCAST(&volume_LRU.cv);
7451 * promote volumes from one VLRU generation to the next.
7453 * This routine scans a VLRU generation looking for volumes which are
7454 * eligible to be promoted to the next generation. All volumes which
7455 * meet the eligibility requirement are promoted.
7457 * Promotion eligibility is based upon meeting both of the following
7460 * @arg The volume has been accessed since the last promotion:
7461 * @c (vp->stats.last_get >= vp->stats.last_promote)
7462 * @arg The last promotion occurred at least
7463 * @c volume_LRU.promotion_interval[idx] seconds ago
7465 * As a performance optimization, promotions are "globbed". In other
7466 * words, we promote arbitrarily large contiguous sublists of elements
7469 * @param[in] idx VLRU queue index to scan
7473 * @internal VLRU internal use only.
7476 VLRU_Promote_r(int idx)
7478 int len, chaining, promote;
7479 afs_uint32 now, thresh;
7480 struct rx_queue *qp, *nqp;
7481 Volume * vp, *start = NULL, *end = NULL;
7483 /* get exclusive access to two chains, and drop the glock */
7484 VLRU_Wait_r(&volume_LRU.q[idx]);
7485 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7486 VLRU_Wait_r(&volume_LRU.q[idx+1]);
7487 VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
7490 thresh = volume_LRU.promotion_interval[idx];
7491 now = FT_ApproxTime();
7494 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7495 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7496 promote = (((vp->stats.last_promote + thresh) <= now) &&
7497 (vp->stats.last_get >= vp->stats.last_promote));
7505 /* promote and prepend chain */
7506 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7520 /* promote and prepend */
7521 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7525 volume_LRU.q[idx].len -= len;
7526 volume_LRU.q[idx+1].len += len;
7529 /* release exclusive access to the two chains */
7531 volume_LRU.last_promotion[idx] = now;
7532 VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
7533 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7536 /* run the demotions */
7538 VLRU_Demote_r(int idx)
7541 int len, chaining, demote;
7542 afs_uint32 now, thresh;
7543 struct rx_queue *qp, *nqp;
7544 Volume * vp, *start = NULL, *end = NULL;
7545 Volume ** salv_flag_vec = NULL;
7546 int salv_vec_offset = 0;
7548 osi_Assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
7550 /* get exclusive access to two chains, and drop the glock */
7551 VLRU_Wait_r(&volume_LRU.q[idx-1]);
7552 VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
7553 VLRU_Wait_r(&volume_LRU.q[idx]);
7554 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7557 /* no big deal if this allocation fails */
7558 if (volume_LRU.q[idx].len) {
7559 salv_flag_vec = (Volume **) malloc(volume_LRU.q[idx].len * sizeof(Volume *));
7562 now = FT_ApproxTime();
7563 thresh = volume_LRU.promotion_interval[idx-1];
7566 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7567 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7568 demote = (((vp->stats.last_promote + thresh) <= now) &&
7569 (vp->stats.last_get < (now - thresh)));
7571 /* we now do volume update list DONT_SALVAGE flag setting during
7572 * demotion passes */
7573 if (salv_flag_vec &&
7574 !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7576 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7577 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7578 salv_flag_vec[salv_vec_offset++] = vp;
7579 VCreateReservation_r(vp);
7588 /* demote and append chain */
7589 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7603 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7607 volume_LRU.q[idx].len -= len;
7608 volume_LRU.q[idx-1].len += len;
7611 /* release exclusive access to the two chains */
7613 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7614 VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
7616 /* now go back and set the DONT_SALVAGE flags as appropriate */
7617 if (salv_flag_vec) {
7619 for (i = 0; i < salv_vec_offset; i++) {
7620 vp = salv_flag_vec[i];
7621 if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7622 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7623 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7626 V_attachFlags(vp) |= VOL_HDR_DONTSALV;
7627 V_dontSalvage(vp) = DONT_SALVAGE;
7628 VUpdateVolume_r(&ec, vp, 0);
7632 VCancelReservation_r(vp);
7634 free(salv_flag_vec);
7638 /* run a pass of the VLRU GC scanner */
7640 VLRU_Scan_r(int idx)
7642 afs_uint32 now, thresh;
7643 struct rx_queue *qp, *nqp;
7647 osi_Assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
7649 /* gain exclusive access to the idx VLRU */
7650 VLRU_Wait_r(&volume_LRU.q[idx]);
7651 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7653 if (idx != VLRU_QUEUE_CANDIDATE) {
7654 /* gain exclusive access to the candidate VLRU */
7655 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7656 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7659 now = FT_ApproxTime();
7660 thresh = now - VLRU_offline_thresh;
7662 /* perform candidate selection and soft detaching */
7663 if (idx == VLRU_QUEUE_CANDIDATE) {
7664 /* soft detach some volumes from the candidate pool */
7668 for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7669 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7670 if (i >= VLRU_offline_max) {
7673 /* check timestamp to see if it's a candidate for soft detaching */
7674 if (vp->stats.last_get <= thresh) {
7676 if (VCheckSoftDetach(vp, thresh))
7682 /* scan for volumes to become soft detach candidates */
7683 for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
7684 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7686 /* check timestamp to see if it's a candidate for soft detaching */
7687 if (vp->stats.last_get <= thresh) {
7688 VCheckSoftDetachCandidate(vp, thresh);
7691 if (!(i&0x7f)) { /* lock coarsening optimization */
7699 /* relinquish exclusive access to the VLRU chains */
7703 volume_LRU.last_scan[idx] = now;
7704 if (idx != VLRU_QUEUE_CANDIDATE) {
7705 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7707 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7710 /* check whether volume is safe to soft detach
7711 * caller MUST NOT hold a ref count on vp */
7713 VCheckSoftDetach(Volume * vp, afs_uint32 thresh)
7717 if (vp->nUsers || vp->nWaiters)
7720 if (vp->stats.last_get <= thresh) {
7721 ret = VSoftDetachVolume_r(vp, thresh);
7727 /* check whether volume should be made a
7728 * soft detach candidate */
7730 VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh)
7733 if (vp->nUsers || vp->nWaiters)
7738 osi_Assert(idx == VLRU_QUEUE_NEW);
7740 if (vp->stats.last_get <= thresh) {
7741 /* move to candidate pool */
7742 queue_Remove(&vp->vlru);
7743 volume_LRU.q[VLRU_QUEUE_NEW].len--;
7744 queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
7745 vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
7746 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
7754 /* begin exclusive access on VLRU */
7756 VLRU_BeginExclusive_r(struct VLRU_q * q)
7758 osi_Assert(q->busy == 0);
7762 /* end exclusive access on VLRU */
7764 VLRU_EndExclusive_r(struct VLRU_q * q)
7766 osi_Assert(q->busy);
7768 CV_BROADCAST(&q->cv);
7771 /* wait for another thread to end exclusive access on VLRU */
7773 VLRU_Wait_r(struct VLRU_q * q)
7776 VOL_CV_WAIT(&q->cv);
7781 * volume soft detach
7783 * caller MUST NOT hold a ref count on vp */
7785 VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh)
7790 osi_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7792 ts_save = vp->stats.last_get;
7793 if (ts_save > thresh)
7796 if (vp->nUsers || vp->nWaiters)
7799 if (VIsExclusiveState(V_attachState(vp))) {
7803 switch (V_attachState(vp)) {
7804 case VOL_STATE_UNATTACHED:
7805 case VOL_STATE_PREATTACHED:
7806 case VOL_STATE_ERROR:
7807 case VOL_STATE_GOING_OFFLINE:
7808 case VOL_STATE_SHUTTING_DOWN:
7809 case VOL_STATE_SALVAGING:
7810 case VOL_STATE_DELETED:
7811 volume_LRU.q[vp->vlru.idx].len--;
7813 /* create and cancel a reservation to
7814 * give the volume an opportunity to
7816 VCreateReservation_r(vp);
7817 queue_Remove(&vp->vlru);
7818 vp->vlru.idx = VLRU_QUEUE_INVALID;
7819 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7820 VCancelReservation_r(vp);
7826 /* hold the volume and take it offline.
7827 * no need for reservations, as VHold_r
7828 * takes care of that internally. */
7829 if (VHold_r(vp) == 0) {
7830 /* vhold drops the glock, so now we should
7831 * check to make sure we aren't racing against
7832 * other threads. if we are racing, offlining vp
7833 * would be wasteful, and block the scanner for a while
7837 (vp->shuttingDown) ||
7838 (vp->goingOffline) ||
7839 (vp->stats.last_get != ts_save)) {
7840 /* looks like we're racing someone else. bail */
7844 /* pull it off the VLRU */
7845 osi_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7846 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
7847 queue_Remove(&vp->vlru);
7848 vp->vlru.idx = VLRU_QUEUE_INVALID;
7849 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7851 /* take if offline */
7852 VOffline_r(vp, "volume has been soft detached");
7854 /* invalidate the volume header cache */
7855 FreeVolumeHeader(vp);
7858 IncUInt64(&VStats.soft_detaches);
7859 vp->stats.soft_detaches++;
7861 /* put in pre-attached state so demand
7862 * attacher can work on it */
7863 VChangeState_r(vp, VOL_STATE_PREATTACHED);
7869 #endif /* AFS_DEMAND_ATTACH_FS */
7872 /***************************************************/
7873 /* Volume Header Cache routines */
7874 /***************************************************/
7877 * volume header cache.
7879 struct volume_hdr_LRU_t volume_hdr_LRU;
7882 * initialize the volume header cache.
7884 * @param[in] howMany number of header cache entries to preallocate
7886 * @pre VOL_LOCK held. Function has never been called before.
7888 * @post howMany cache entries are allocated, initialized, and added
7889 * to the LRU list. Header cache statistics are initialized.
7891 * @note only applicable to fileServer program type. Should only be
7892 * called once during volume package initialization.
7894 * @internal volume package internal use only.
7897 VInitVolumeHeaderCache(afs_uint32 howMany)
7899 struct volHeader *hp;
7900 if (programType != fileServer)
7902 queue_Init(&volume_hdr_LRU);
7903 volume_hdr_LRU.stats.free = 0;
7904 volume_hdr_LRU.stats.used = howMany;
7905 volume_hdr_LRU.stats.attached = 0;
7906 hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
7907 osi_Assert(hp != NULL);
7910 /* We are using ReleaseVolumeHeader to initialize the values on the header list
7911 * to ensure they have the right values
7913 ReleaseVolumeHeader(hp++);
7917 * get a volume header and attach it to the volume object.
7919 * @param[in] vp pointer to volume object
7921 * @return cache entry status
7922 * @retval 0 volume header was newly attached; cache data is invalid
7923 * @retval 1 volume header was previously attached; cache data is valid
7925 * @pre VOL_LOCK held. For DAFS, lightweight ref must be held on volume object.
7927 * @post volume header attached to volume object. if necessary, header cache
7928 * entry on LRU is synchronized to disk. Header is removed from LRU list.
7930 * @note VOL_LOCK may be dropped
7932 * @warning this interface does not load header data from disk. it merely
7933 * attaches a header object to the volume object, and may sync the old
7934 * header cache data out to disk in the process.
7936 * @internal volume package internal use only.
7939 GetVolumeHeader(Volume * vp)
7942 struct volHeader *hd;
7944 static int everLogged = 0;
7946 #ifdef AFS_DEMAND_ATTACH_FS
7947 VolState vp_save = 0, back_save = 0;
7949 /* XXX debug 9/19/05 we've apparently got
7950 * a ref counting bug somewhere that's
7951 * breaking the nUsers == 0 => header on LRU
7953 if (vp->header && queue_IsNotOnQueue(vp->header)) {
7954 Log("nUsers == 0, but header not on LRU\n");
7959 old = (vp->header != NULL); /* old == volume already has a header */
7961 if (programType != fileServer) {
7962 /* for volume utilities, we allocate volHeaders as needed */
7964 hd = (struct volHeader *)calloc(1, sizeof(*vp->header));
7965 osi_Assert(hd != NULL);
7968 #ifdef AFS_DEMAND_ATTACH_FS
7969 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
7973 /* for the fileserver, we keep a volume header cache */
7975 /* the header we previously dropped in the lru is
7976 * still available. pull it off the lru and return */
7979 osi_Assert(hd->back == vp);
7980 #ifdef AFS_DEMAND_ATTACH_FS
7981 V_attachFlags(vp) &= ~(VOL_HDR_IN_LRU);
7984 /* we need to grab a new element off the LRU */
7985 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
7986 /* grab an element and pull off of LRU */
7987 hd = queue_First(&volume_hdr_LRU, volHeader);
7990 /* LRU is empty, so allocate a new volHeader
7991 * this is probably indicative of a leak, so let the user know */
7992 hd = (struct volHeader *)calloc(1, sizeof(struct volHeader));
7993 osi_Assert(hd != NULL);
7995 Log("****Allocated more volume headers, probably leak****\n");
7998 volume_hdr_LRU.stats.free++;
8001 /* this header used to belong to someone else.
8002 * we'll need to check if the header needs to
8003 * be sync'd out to disk */
8005 #ifdef AFS_DEMAND_ATTACH_FS
8006 /* if hd->back were in an exclusive state, then
8007 * its volHeader would not be on the LRU... */
8008 osi_Assert(!VIsExclusiveState(V_attachState(hd->back)));
8011 if (hd->diskstuff.inUse) {
8012 /* volume was in use, so we'll need to sync
8013 * its header to disk */
8015 #ifdef AFS_DEMAND_ATTACH_FS
8016 back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
8017 vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
8018 VCreateReservation_r(hd->back);
8022 WriteVolumeHeader_r(&error, hd->back);
8023 /* Ignore errors; catch them later */
8025 #ifdef AFS_DEMAND_ATTACH_FS
8030 hd->back->header = NULL;
8031 #ifdef AFS_DEMAND_ATTACH_FS
8032 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
8034 if (hd->diskstuff.inUse) {
8035 VChangeState_r(hd->back, back_save);
8036 VCancelReservation_r(hd->back);
8037 VChangeState_r(vp, vp_save);
8041 volume_hdr_LRU.stats.attached++;
8045 #ifdef AFS_DEMAND_ATTACH_FS
8046 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8049 volume_hdr_LRU.stats.free--;
8050 volume_hdr_LRU.stats.used++;
8052 IncUInt64(&VStats.hdr_gets);
8053 #ifdef AFS_DEMAND_ATTACH_FS
8054 IncUInt64(&vp->stats.hdr_gets);
8055 vp->stats.last_hdr_get = FT_ApproxTime();
8062 * make sure volume header is attached and contains valid cache data.
8064 * @param[out] ec outbound error code
8065 * @param[in] vp pointer to volume object
8067 * @pre VOL_LOCK held. For DAFS, lightweight ref held on vp.
8069 * @post header cache entry attached, and loaded with valid data, or
8070 * *ec is nonzero, and the header is released back into the LRU.
8072 * @internal volume package internal use only.
8075 LoadVolumeHeader(Error * ec, Volume * vp)
8077 #ifdef AFS_DEMAND_ATTACH_FS
8078 VolState state_save;
8082 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8083 IncUInt64(&VStats.hdr_loads);
8084 state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
8087 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8088 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8090 IncUInt64(&vp->stats.hdr_loads);
8091 now = FT_ApproxTime();
8095 V_attachFlags(vp) |= VOL_HDR_LOADED;
8096 vp->stats.last_hdr_load = now;
8098 VChangeState_r(vp, state_save);
8100 #else /* AFS_DEMAND_ATTACH_FS */
8102 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8103 IncUInt64(&VStats.hdr_loads);
8105 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8106 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8109 #endif /* AFS_DEMAND_ATTACH_FS */
8111 /* maintain (nUsers==0) => header in LRU invariant */
8112 FreeVolumeHeader(vp);
8117 * release a header cache entry back into the LRU list.
8119 * @param[in] hd pointer to volume header cache object
8121 * @pre VOL_LOCK held.
8123 * @post header cache object appended onto end of LRU list.
8125 * @note only applicable to fileServer program type.
8127 * @note used to place a header cache entry back into the
8128 * LRU pool without invalidating it as a cache entry.
8130 * @internal volume package internal use only.
8133 ReleaseVolumeHeader(struct volHeader *hd)
8135 if (programType != fileServer)
8137 if (!hd || queue_IsOnQueue(hd)) /* no header, or header already released */
8139 queue_Append(&volume_hdr_LRU, hd);
8140 #ifdef AFS_DEMAND_ATTACH_FS
8142 V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
8145 volume_hdr_LRU.stats.free++;
8146 volume_hdr_LRU.stats.used--;
8150 * free/invalidate a volume header cache entry.
8152 * @param[in] vp pointer to volume object
8154 * @pre VOL_LOCK is held.
8156 * @post For fileserver, header cache entry is returned to LRU, and it is
8157 * invalidated as a cache entry. For volume utilities, the header
8158 * cache entry is freed.
8160 * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
8161 * whenever it is necessary to invalidate the header cache entry.
8163 * @see ReleaseVolumeHeader
8165 * @internal volume package internal use only.
8168 FreeVolumeHeader(Volume * vp)
8170 struct volHeader *hd = vp->header;
8173 if (programType == fileServer) {
8174 ReleaseVolumeHeader(hd);
8179 #ifdef AFS_DEMAND_ATTACH_FS
8180 V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
8182 volume_hdr_LRU.stats.attached--;
8187 /***************************************************/
8188 /* Volume Hash Table routines */
8189 /***************************************************/
8192 * set size of volume object hash table.
8194 * @param[in] logsize log(2) of desired hash table size
8196 * @return operation status
8198 * @retval -1 failure
8200 * @pre MUST be called prior to VInitVolumePackage2
8202 * @post Volume Hash Table will have 2^logsize buckets
8205 VSetVolHashSize(int logsize)
8207 /* 64 to 268435456 hash buckets seems like a reasonable range */
8208 if ((logsize < 6 ) || (logsize > 28)) {
8213 VolumeHashTable.Size = 1 << logsize;
8214 VolumeHashTable.Mask = VolumeHashTable.Size - 1;
8216 /* we can't yet support runtime modification of this
8217 * parameter. we'll need a configuration rwlock to
8218 * make runtime modification feasible.... */
8225 * initialize dynamic data structures for volume hash table.
8227 * @post hash table is allocated, and fields are initialized.
8229 * @internal volume package internal use only.
8232 VInitVolumeHash(void)
8236 VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
8237 sizeof(VolumeHashChainHead));
8238 osi_Assert(VolumeHashTable.Table != NULL);
8240 for (i=0; i < VolumeHashTable.Size; i++) {
8241 queue_Init(&VolumeHashTable.Table[i]);
8242 #ifdef AFS_DEMAND_ATTACH_FS
8243 CV_INIT(&VolumeHashTable.Table[i].chain_busy_cv, "vhash busy", CV_DEFAULT, 0);
8244 #endif /* AFS_DEMAND_ATTACH_FS */
8249 * add a volume object to the hash table.
8251 * @param[in] vp pointer to volume object
8252 * @param[in] hashid hash of volume id
8254 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8257 * @post volume is added to hash chain.
8259 * @internal volume package internal use only.
8261 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8262 * asynchronous hash chain reordering to finish.
8265 AddVolumeToHashTable(Volume * vp, int hashid)
8267 VolumeHashChainHead * head;
8269 if (queue_IsOnQueue(vp))
8272 head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
8274 #ifdef AFS_DEMAND_ATTACH_FS
8275 /* wait for the hash chain to become available */
8278 V_attachFlags(vp) |= VOL_IN_HASH;
8279 vp->chainCacheCheck = ++head->cacheCheck;
8280 #endif /* AFS_DEMAND_ATTACH_FS */
8283 vp->hashid = hashid;
8284 queue_Append(head, vp);
8285 vp->vnodeHashOffset = VolumeHashOffset_r();
8289 * delete a volume object from the hash table.
8291 * @param[in] vp pointer to volume object
8293 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8296 * @post volume is removed from hash chain.
8298 * @internal volume package internal use only.
8300 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8301 * asynchronous hash chain reordering to finish.
8304 DeleteVolumeFromHashTable(Volume * vp)
8306 VolumeHashChainHead * head;
8308 if (!queue_IsOnQueue(vp))
8311 head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
8313 #ifdef AFS_DEMAND_ATTACH_FS
8314 /* wait for the hash chain to become available */
8317 V_attachFlags(vp) &= ~(VOL_IN_HASH);
8319 #endif /* AFS_DEMAND_ATTACH_FS */
8323 /* do NOT reset hashid to zero, as the online
8324 * salvager package may need to know the volume id
8325 * after the volume is removed from the hash */
8329 * lookup a volume object in the hash table given a volume id.
8331 * @param[out] ec error code return
8332 * @param[in] volumeId volume id
8333 * @param[in] hint volume object which we believe could be the correct
8336 * @return volume object pointer
8337 * @retval NULL no such volume id is registered with the hash table.
8339 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8342 * @post volume object with the given id is returned. volume object and
8343 * hash chain access statistics are updated. hash chain may have
8346 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8347 * asynchronous hash chain reordering operation to finish, or
8348 * in order for us to perform an asynchronous chain reordering.
8350 * @note Hash chain reorderings occur when the access count for the
8351 * volume object being looked up exceeds the sum of the previous
8352 * node's (the node ahead of it in the hash chain linked list)
8353 * access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
8355 * @note For DAFS, the hint parameter allows us to short-circuit if the
8356 * cacheCheck fields match between the hash chain head and the
8357 * hint volume object.
8360 VLookupVolume_r(Error * ec, VolId volumeId, Volume * hint)
8364 #ifdef AFS_DEMAND_ATTACH_FS
8367 VolumeHashChainHead * head;
8370 head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
8372 #ifdef AFS_DEMAND_ATTACH_FS
8373 /* wait for the hash chain to become available */
8376 /* check to see if we can short circuit without walking the hash chain */
8377 if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
8378 IncUInt64(&hint->stats.hash_short_circuits);
8381 #endif /* AFS_DEMAND_ATTACH_FS */
8383 /* someday we need to either do per-chain locks, RWlocks,
8384 * or both for volhash access.
8385 * (and move to a data structure with better cache locality) */
8387 /* search the chain for this volume id */
8388 for(queue_Scan(head, vp, np, Volume)) {
8390 if ((vp->hashid == volumeId)) {
8395 if (queue_IsEnd(head, vp)) {
8399 #ifdef AFS_DEMAND_ATTACH_FS
8400 /* update hash chain statistics */
8403 FillInt64(lks, 0, looks);
8404 AddUInt64(head->looks, lks, &head->looks);
8405 AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
8406 IncUInt64(&head->gets);
8411 IncUInt64(&vp->stats.hash_lookups);
8413 /* for demand attach fileserver, we permit occasional hash chain reordering
8414 * so that frequently looked up volumes move towards the head of the chain */
8415 pp = queue_Prev(vp, Volume);
8416 if (!queue_IsEnd(head, pp)) {
8417 FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
8418 AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
8419 if (GEInt64(vp->stats.hash_lookups, thresh)) {
8420 VReorderHash_r(head, pp, vp);
8424 /* update the short-circuit cache check */
8425 vp->chainCacheCheck = head->cacheCheck;
8427 #endif /* AFS_DEMAND_ATTACH_FS */
8432 #ifdef AFS_DEMAND_ATTACH_FS
8433 /* perform volume hash chain reordering.
8435 * advance a subchain beginning at vp ahead of
8436 * the adjacent subchain ending at pp */
8438 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
8440 Volume *tp, *np, *lp;
8441 afs_uint64 move_thresh;
8443 /* this should never be called if the chain is already busy, so
8444 * no need to wait for other exclusive chain ops to finish */
8446 /* this is a rather heavy set of operations,
8447 * so let's set the chain busy flag and drop
8449 VHashBeginExclusive_r(head);
8452 /* scan forward in the chain from vp looking for the last element
8453 * in the chain we want to advance */
8454 FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
8455 AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
8456 for(queue_ScanFrom(head, vp, tp, np, Volume)) {
8457 if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
8461 lp = queue_Prev(tp, Volume);
8463 /* scan backwards from pp to determine where to splice and
8464 * insert the subchain we're advancing */
8465 for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
8466 if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
8470 tp = queue_Next(tp, Volume);
8472 /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
8473 queue_MoveChainBefore(tp,vp,lp);
8476 IncUInt64(&VStats.hash_reorders);
8478 IncUInt64(&head->reorders);
8480 /* wake up any threads waiting for the hash chain */
8481 VHashEndExclusive_r(head);
8485 /* demand-attach fs volume hash
8486 * asynchronous exclusive operations */
8489 * begin an asynchronous exclusive operation on a volume hash chain.
8491 * @param[in] head pointer to volume hash chain head object
8493 * @pre VOL_LOCK held. hash chain is quiescent.
8495 * @post hash chain marked busy.
8497 * @note this interface is used in conjunction with VHashEndExclusive_r and
8498 * VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8499 * volume hash chain. Its main use case is hash chain reordering, which
8500 * has the potential to be a highly latent operation.
8502 * @see VHashEndExclusive_r
8507 * @internal volume package internal use only.
8510 VHashBeginExclusive_r(VolumeHashChainHead * head)
8512 osi_Assert(head->busy == 0);
8517 * relinquish exclusive ownership of a volume hash chain.
8519 * @param[in] head pointer to volume hash chain head object
8521 * @pre VOL_LOCK held. thread owns the hash chain exclusively.
8523 * @post hash chain is marked quiescent. threads awaiting use of
8524 * chain are awakened.
8526 * @see VHashBeginExclusive_r
8531 * @internal volume package internal use only.
8534 VHashEndExclusive_r(VolumeHashChainHead * head)
8536 osi_Assert(head->busy);
8538 CV_BROADCAST(&head->chain_busy_cv);
8542 * wait for all asynchronous operations on a hash chain to complete.
8544 * @param[in] head pointer to volume hash chain head object
8546 * @pre VOL_LOCK held.
8548 * @post hash chain object is quiescent.
8550 * @see VHashBeginExclusive_r
8551 * @see VHashEndExclusive_r
8555 * @note This interface should be called before any attempt to
8556 * traverse the hash chain. It is permissible for a thread
8557 * to gain exclusive access to the chain, and then perform
8558 * latent operations on the chain asynchronously wrt the
8561 * @warning if waiting is necessary, VOL_LOCK is dropped
8563 * @internal volume package internal use only.
8566 VHashWait_r(VolumeHashChainHead * head)
8568 while (head->busy) {
8569 VOL_CV_WAIT(&head->chain_busy_cv);
8572 #endif /* AFS_DEMAND_ATTACH_FS */
8575 /***************************************************/
8576 /* Volume by Partition List routines */
8577 /***************************************************/
8580 * demand attach fileserver adds a
8581 * linked list of volumes to each
8582 * partition object, thus allowing
8583 * for quick enumeration of all
8584 * volumes on a partition
8587 #ifdef AFS_DEMAND_ATTACH_FS
8589 * add a volume to its disk partition VByPList.
8591 * @param[in] vp pointer to volume object
8593 * @pre either the disk partition VByPList is owned exclusively
8594 * by the calling thread, or the list is quiescent and
8597 * @post volume is added to disk partition VByPList
8601 * @warning it is the caller's responsibility to ensure list
8604 * @see VVByPListWait_r
8605 * @see VVByPListBeginExclusive_r
8606 * @see VVByPListEndExclusive_r
8608 * @internal volume package internal use only.
8611 AddVolumeToVByPList_r(Volume * vp)
8613 if (queue_IsNotOnQueue(&vp->vol_list)) {
8614 queue_Append(&vp->partition->vol_list, &vp->vol_list);
8615 V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
8616 vp->partition->vol_list.len++;
8621 * delete a volume from its disk partition VByPList.
8623 * @param[in] vp pointer to volume object
8625 * @pre either the disk partition VByPList is owned exclusively
8626 * by the calling thread, or the list is quiescent and
8629 * @post volume is removed from the disk partition VByPList
8633 * @warning it is the caller's responsibility to ensure list
8636 * @see VVByPListWait_r
8637 * @see VVByPListBeginExclusive_r
8638 * @see VVByPListEndExclusive_r
8640 * @internal volume package internal use only.
8643 DeleteVolumeFromVByPList_r(Volume * vp)
8645 if (queue_IsOnQueue(&vp->vol_list)) {
8646 queue_Remove(&vp->vol_list);
8647 V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
8648 vp->partition->vol_list.len--;
8653 * begin an asynchronous exclusive operation on a VByPList.
8655 * @param[in] dp pointer to disk partition object
8657 * @pre VOL_LOCK held. VByPList is quiescent.
8659 * @post VByPList marked busy.
8661 * @note this interface is used in conjunction with VVByPListEndExclusive_r and
8662 * VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8665 * @see VVByPListEndExclusive_r
8666 * @see VVByPListWait_r
8670 * @internal volume package internal use only.
8672 /* take exclusive control over the list */
8674 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
8676 osi_Assert(dp->vol_list.busy == 0);
8677 dp->vol_list.busy = 1;
8681 * relinquish exclusive ownership of a VByPList.
8683 * @param[in] dp pointer to disk partition object
8685 * @pre VOL_LOCK held. thread owns the VByPList exclusively.
8687 * @post VByPList is marked quiescent. threads awaiting use of
8688 * the list are awakened.
8690 * @see VVByPListBeginExclusive_r
8691 * @see VVByPListWait_r
8695 * @internal volume package internal use only.
8698 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
8700 osi_Assert(dp->vol_list.busy);
8701 dp->vol_list.busy = 0;
8702 CV_BROADCAST(&dp->vol_list.cv);
8706 * wait for all asynchronous operations on a VByPList to complete.
8708 * @param[in] dp pointer to disk partition object
8710 * @pre VOL_LOCK is held.
8712 * @post disk partition's VByP list is quiescent
8716 * @note This interface should be called before any attempt to
8717 * traverse the VByPList. It is permissible for a thread
8718 * to gain exclusive access to the list, and then perform
8719 * latent operations on the list asynchronously wrt the
8722 * @warning if waiting is necessary, VOL_LOCK is dropped
8724 * @see VVByPListEndExclusive_r
8725 * @see VVByPListBeginExclusive_r
8727 * @internal volume package internal use only.
8730 VVByPListWait_r(struct DiskPartition64 * dp)
8732 while (dp->vol_list.busy) {
8733 VOL_CV_WAIT(&dp->vol_list.cv);
8736 #endif /* AFS_DEMAND_ATTACH_FS */
8738 /***************************************************/
8739 /* Volume Cache Statistics routines */
8740 /***************************************************/
8743 VPrintCacheStats_r(void)
8745 afs_uint32 get_hi, get_lo, load_hi, load_lo;
8746 struct VnodeClassInfo *vcp;
8747 vcp = &VnodeClassInfo[vLarge];
8748 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);
8749 vcp = &VnodeClassInfo[vSmall];
8750 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);
8751 SplitInt64(VStats.hdr_gets, get_hi, get_lo);
8752 SplitInt64(VStats.hdr_loads, load_hi, load_lo);
8753 Log("Volume header cache, %d entries, %d gets, %d replacements\n",
8754 VStats.hdr_cache_size, get_lo, load_lo);
8758 VPrintCacheStats(void)
8761 VPrintCacheStats_r();
8765 #ifdef AFS_DEMAND_ATTACH_FS
8767 UInt64ToDouble(afs_uint64 * x)
8769 static double c32 = 4.0 * 1.073741824 * 1000000000.0;
8771 SplitInt64(*x, h, l);
8772 return (((double)h) * c32) + ((double) l);
8776 DoubleToPrintable(double x, char * buf, int len)
8778 static double billion = 1000000000.0;
8781 y[0] = (afs_uint32) (x / (billion * billion));
8782 y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
8783 y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
8786 snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
8788 snprintf(buf, len, "%d%09d", y[1], y[2]);
8790 snprintf(buf, len, "%d", y[2]);
8796 struct VLRUExtStatsEntry {
8800 struct VLRUExtStats {
8806 } queue_info[VLRU_QUEUE_INVALID];
8807 struct VLRUExtStatsEntry * vec;
8811 * add a 256-entry fudge factor onto the vector in case state changes
8812 * out from under us.
8814 #define VLRU_EXT_STATS_VEC_LEN_FUDGE 256
8817 * collect extended statistics for the VLRU subsystem.
8819 * @param[out] stats pointer to stats structure to be populated
8820 * @param[in] nvols number of volumes currently known to exist
8822 * @pre VOL_LOCK held
8824 * @post stats->vec allocated and populated
8826 * @return operation status
8831 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
8833 afs_uint32 cur, idx, len;
8834 struct rx_queue * qp, * nqp;
8836 struct VLRUExtStatsEntry * vec;
8838 len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
8839 vec = stats->vec = calloc(len,
8840 sizeof(struct VLRUExtStatsEntry));
8846 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
8847 VLRU_Wait_r(&volume_LRU.q[idx]);
8848 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
8851 stats->queue_info[idx].start = cur;
8853 for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
8855 /* out of space in vec */
8858 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
8859 vec[cur].volid = vp->hashid;
8863 stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
8866 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
8874 #define ENUMTOSTRING(en) #en
8875 #define ENUMCASE(en) \
8876 case en: return ENUMTOSTRING(en)
8879 vlru_idx_to_string(int idx)
8882 ENUMCASE(VLRU_QUEUE_NEW);
8883 ENUMCASE(VLRU_QUEUE_MID);
8884 ENUMCASE(VLRU_QUEUE_OLD);
8885 ENUMCASE(VLRU_QUEUE_CANDIDATE);
8886 ENUMCASE(VLRU_QUEUE_HELD);
8887 ENUMCASE(VLRU_QUEUE_INVALID);
8889 return "**UNKNOWN**";
8894 VPrintExtendedCacheStats_r(int flags)
8897 afs_uint32 vol_sum = 0;
8904 struct stats looks, gets, reorders, len;
8905 struct stats ch_looks, ch_gets, ch_reorders;
8907 VolumeHashChainHead *head;
8909 struct VLRUExtStats vlru_stats;
8911 /* zero out stats */
8912 memset(&looks, 0, sizeof(struct stats));
8913 memset(&gets, 0, sizeof(struct stats));
8914 memset(&reorders, 0, sizeof(struct stats));
8915 memset(&len, 0, sizeof(struct stats));
8916 memset(&ch_looks, 0, sizeof(struct stats));
8917 memset(&ch_gets, 0, sizeof(struct stats));
8918 memset(&ch_reorders, 0, sizeof(struct stats));
8920 for (i = 0; i < VolumeHashTable.Size; i++) {
8921 head = &VolumeHashTable.Table[i];
8924 VHashBeginExclusive_r(head);
8927 ch_looks.sum = UInt64ToDouble(&head->looks);
8928 ch_gets.sum = UInt64ToDouble(&head->gets);
8929 ch_reorders.sum = UInt64ToDouble(&head->reorders);
8931 /* update global statistics */
8933 looks.sum += ch_looks.sum;
8934 gets.sum += ch_gets.sum;
8935 reorders.sum += ch_reorders.sum;
8936 len.sum += (double)head->len;
8937 vol_sum += head->len;
8940 len.min = (double) head->len;
8941 len.max = (double) head->len;
8942 looks.min = ch_looks.sum;
8943 looks.max = ch_looks.sum;
8944 gets.min = ch_gets.sum;
8945 gets.max = ch_gets.sum;
8946 reorders.min = ch_reorders.sum;
8947 reorders.max = ch_reorders.sum;
8949 if (((double)head->len) < len.min)
8950 len.min = (double) head->len;
8951 if (((double)head->len) > len.max)
8952 len.max = (double) head->len;
8953 if (ch_looks.sum < looks.min)
8954 looks.min = ch_looks.sum;
8955 else if (ch_looks.sum > looks.max)
8956 looks.max = ch_looks.sum;
8957 if (ch_gets.sum < gets.min)
8958 gets.min = ch_gets.sum;
8959 else if (ch_gets.sum > gets.max)
8960 gets.max = ch_gets.sum;
8961 if (ch_reorders.sum < reorders.min)
8962 reorders.min = ch_reorders.sum;
8963 else if (ch_reorders.sum > reorders.max)
8964 reorders.max = ch_reorders.sum;
8968 if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
8969 /* compute detailed per-chain stats */
8970 struct stats hdr_loads, hdr_gets;
8971 double v_looks, v_loads, v_gets;
8973 /* initialize stats with data from first element in chain */
8974 vp = queue_First(head, Volume);
8975 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
8976 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
8977 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
8978 ch_gets.min = ch_gets.max = v_looks;
8979 hdr_loads.min = hdr_loads.max = v_loads;
8980 hdr_gets.min = hdr_gets.max = v_gets;
8981 hdr_loads.sum = hdr_gets.sum = 0;
8983 vp = queue_Next(vp, Volume);
8985 /* pull in stats from remaining elements in chain */
8986 for (queue_ScanFrom(head, vp, vp, np, Volume)) {
8987 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
8988 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
8989 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
8991 hdr_loads.sum += v_loads;
8992 hdr_gets.sum += v_gets;
8994 if (v_looks < ch_gets.min)
8995 ch_gets.min = v_looks;
8996 else if (v_looks > ch_gets.max)
8997 ch_gets.max = v_looks;
8999 if (v_loads < hdr_loads.min)
9000 hdr_loads.min = v_loads;
9001 else if (v_loads > hdr_loads.max)
9002 hdr_loads.max = v_loads;
9004 if (v_gets < hdr_gets.min)
9005 hdr_gets.min = v_gets;
9006 else if (v_gets > hdr_gets.max)
9007 hdr_gets.max = v_gets;
9010 /* compute per-chain averages */
9011 ch_gets.avg = ch_gets.sum / ((double)head->len);
9012 hdr_loads.avg = hdr_loads.sum / ((double)head->len);
9013 hdr_gets.avg = hdr_gets.sum / ((double)head->len);
9015 /* dump per-chain stats */
9016 Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
9018 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9019 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
9020 Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
9021 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9022 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9023 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9024 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9025 Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
9026 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9027 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9028 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9029 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9030 Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
9031 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
9032 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
9033 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
9034 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
9035 } else if (flags & VOL_STATS_PER_CHAIN) {
9036 /* dump simple per-chain stats */
9037 Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
9039 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9040 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
9041 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
9045 VHashEndExclusive_r(head);
9050 /* compute global averages */
9051 len.avg = len.sum / ((double)VolumeHashTable.Size);
9052 looks.avg = looks.sum / ((double)VolumeHashTable.Size);
9053 gets.avg = gets.sum / ((double)VolumeHashTable.Size);
9054 reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
9056 /* dump global stats */
9057 Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
9058 Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
9059 DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
9060 DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
9061 DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
9062 DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
9063 Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
9064 DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
9065 DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
9066 DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
9067 DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
9068 Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
9069 DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
9070 DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
9071 DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9072 DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9073 Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
9074 DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
9075 DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
9076 DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
9077 DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
9079 /* print extended disk related statistics */
9081 struct DiskPartition64 * diskP;
9082 afs_uint32 vol_count[VOLMAXPARTS+1];
9083 byte part_exists[VOLMAXPARTS+1];
9087 memset(vol_count, 0, sizeof(vol_count));
9088 memset(part_exists, 0, sizeof(part_exists));
9092 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
9094 vol_count[id] = diskP->vol_list.len;
9095 part_exists[id] = 1;
9099 for (i = 0; i <= VOLMAXPARTS; i++) {
9100 if (part_exists[i]) {
9101 /* XXX while this is currently safe, it is a violation
9102 * of the VGetPartitionById_r interface contract. */
9103 diskP = VGetPartitionById_r(i, 0);
9105 Log("Partition %s has %d online volumes\n",
9106 VPartitionPath(diskP), diskP->vol_list.len);
9113 /* print extended VLRU statistics */
9114 if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
9115 afs_uint32 idx, cur, lpos;
9120 Log("VLRU State Dump:\n\n");
9122 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
9123 Log("\t%s:\n", vlru_idx_to_string(idx));
9126 for (cur = vlru_stats.queue_info[idx].start;
9127 cur < vlru_stats.queue_info[idx].len;
9129 line[lpos++] = vlru_stats.vec[cur].volid;
9131 Log("\t\t%u, %u, %u, %u, %u,\n",
9132 line[0], line[1], line[2], line[3], line[4]);
9141 Log("\t\t%u, %u, %u, %u, %u\n",
9142 line[0], line[1], line[2], line[3], line[4]);
9147 free(vlru_stats.vec);
9154 VPrintExtendedCacheStats(int flags)
9157 VPrintExtendedCacheStats_r(flags);
9160 #endif /* AFS_DEMAND_ATTACH_FS */
9163 VCanScheduleSalvage(void)
9165 return vol_opts.canScheduleSalvage;
9171 return vol_opts.canUseFSSYNC;
9175 VCanUseSALVSYNC(void)
9177 return vol_opts.canUseSALVSYNC;
9181 VCanUnsafeAttach(void)
9183 return vol_opts.unsafe_attach;