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)
139 #ifdef AFS_PTHREAD_ENV
140 pthread_mutex_t vol_glock_mutex;
141 pthread_mutex_t vol_trans_mutex;
142 pthread_cond_t vol_put_volume_cond;
143 pthread_cond_t vol_sleep_cond;
144 pthread_cond_t vol_init_attach_cond;
145 pthread_cond_t vol_vinit_cond;
146 int vol_attach_threads = 1;
147 #endif /* AFS_PTHREAD_ENV */
149 /* start-time configurable I/O parameters */
150 ih_init_params vol_io_params;
152 #ifdef AFS_DEMAND_ATTACH_FS
153 pthread_mutex_t vol_salvsync_mutex;
156 * Set this to 1 to disallow SALVSYNC communication in all threads; used
157 * during shutdown, since the salvageserver may have gone away.
159 static volatile sig_atomic_t vol_disallow_salvsync = 0;
160 #endif /* AFS_DEMAND_ATTACH_FS */
163 * has VShutdown_r been called / is VShutdown_r running?
165 static int vol_shutting_down = 0;
168 extern void *calloc(), *realloc();
171 /* Forward declarations */
172 static Volume *attach2(Error * ec, VolId volumeId, char *path,
173 struct DiskPartition64 *partp, Volume * vp,
174 int isbusy, int mode, int *acheckedOut);
175 static void ReallyFreeVolume(Volume * vp);
176 #ifdef AFS_DEMAND_ATTACH_FS
177 static void FreeVolume(Volume * vp);
178 #else /* !AFS_DEMAND_ATTACH_FS */
179 #define FreeVolume(vp) ReallyFreeVolume(vp)
180 static void VScanUpdateList(void);
181 #endif /* !AFS_DEMAND_ATTACH_FS */
182 static void VInitVolumeHeaderCache(afs_uint32 howMany);
183 static int GetVolumeHeader(Volume * vp);
184 static void ReleaseVolumeHeader(struct volHeader *hd);
185 static void FreeVolumeHeader(Volume * vp);
186 static void AddVolumeToHashTable(Volume * vp, int hashid);
187 static void DeleteVolumeFromHashTable(Volume * vp);
189 static int VHold(Volume * vp);
191 static int VHold_r(Volume * vp);
192 static void VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class);
193 static void VReleaseVolumeHandles_r(Volume * vp);
194 static void VCloseVolumeHandles_r(Volume * vp);
195 static void LoadVolumeHeader(Error * ec, Volume * vp);
196 static int VCheckOffline(Volume * vp);
197 static int VCheckDetach(Volume * vp);
198 static Volume * GetVolume(Error * ec, Error * client_ec, VolId volumeId,
199 Volume * hint, const struct timespec *ts);
201 int LogLevel; /* Vice loglevel--not defined as extern so that it will be
202 * defined when not linked with vice, XXXX */
203 ProgramType programType; /* The type of program using the package */
204 static VolumePackageOptions vol_opts;
206 /* extended volume package statistics */
209 #ifdef VOL_LOCK_DEBUG
210 pthread_t vol_glock_holder = 0;
214 #define VOLUME_BITMAP_GROWSIZE 16 /* bytes, => 128vnodes */
215 /* Must be a multiple of 4 (1 word) !! */
217 /* this parameter needs to be tunable at runtime.
218 * 128 was really inadequate for largish servers -- at 16384 volumes this
219 * puts average chain length at 128, thus an average 65 deref's to find a volptr.
220 * talk about bad spatial locality...
222 * an AVL or splay tree might work a lot better, but we'll just increase
223 * the default hash table size for now
225 #define DEFAULT_VOLUME_HASH_SIZE 256 /* Must be a power of 2!! */
226 #define DEFAULT_VOLUME_HASH_MASK (DEFAULT_VOLUME_HASH_SIZE-1)
227 #define VOLUME_HASH(volumeId) (volumeId&(VolumeHashTable.Mask))
230 * turn volume hash chains into partially ordered lists.
231 * when the threshold is exceeded between two adjacent elements,
232 * perform a chain rebalancing operation.
234 * keep the threshold high in order to keep cache line invalidates
235 * low "enough" on SMPs
237 #define VOLUME_HASH_REORDER_THRESHOLD 200
240 * when possible, don't just reorder single elements, but reorder
241 * entire chains of elements at once. a chain of elements that
242 * exceed the element previous to the pivot by at least CHAIN_THRESH
243 * accesses are moved in front of the chain whose elements have at
244 * least CHAIN_THRESH less accesses than the pivot element
246 #define VOLUME_HASH_REORDER_CHAIN_THRESH (VOLUME_HASH_REORDER_THRESHOLD / 2)
248 #include "rx/rx_queue.h"
251 VolumeHashTable_t VolumeHashTable = {
252 DEFAULT_VOLUME_HASH_SIZE,
253 DEFAULT_VOLUME_HASH_MASK,
258 static void VInitVolumeHash(void);
262 /* This macro is used where an ffs() call does not exist. Was in util/ffs.c */
266 afs_int32 ffs_tmp = x;
270 for (ffs_i = 1;; ffs_i++) {
277 #endif /* !AFS_HAVE_FFS */
279 #ifdef AFS_PTHREAD_ENV
281 * disk partition queue element
283 typedef struct diskpartition_queue_t {
284 struct rx_queue queue; /**< queue header */
285 struct DiskPartition64 *diskP; /**< disk partition table entry */
286 } diskpartition_queue_t;
288 #ifndef AFS_DEMAND_ATTACH_FS
290 typedef struct vinitvolumepackage_thread_t {
291 struct rx_queue queue;
292 pthread_cond_t thread_done_cv;
293 int n_threads_complete;
294 } vinitvolumepackage_thread_t;
295 static void * VInitVolumePackageThread(void * args);
297 #else /* !AFS_DEMAND_ATTTACH_FS */
298 #define VINIT_BATCH_MAX_SIZE 512
301 * disk partition work queue
303 struct partition_queue {
304 struct rx_queue head; /**< diskpartition_queue_t queue */
305 pthread_mutex_t mutex;
310 * volumes parameters for preattach
312 struct volume_init_batch {
313 struct rx_queue queue; /**< queue header */
314 int thread; /**< posting worker thread */
315 int last; /**< indicates thread is done */
316 int size; /**< number of volume ids in batch */
317 Volume *batch[VINIT_BATCH_MAX_SIZE]; /**< volumes ids to preattach */
321 * volume parameters work queue
323 struct volume_init_queue {
324 struct rx_queue head; /**< volume_init_batch queue */
325 pthread_mutex_t mutex;
330 * volume init worker thread parameters
332 struct vinitvolumepackage_thread_param {
333 int nthreads; /**< total number of worker threads */
334 int thread; /**< thread number for this worker thread */
335 struct partition_queue *pq; /**< queue partitions to scan */
336 struct volume_init_queue *vq; /**< queue of volume to preattach */
339 static void *VInitVolumePackageThread(void *args);
340 static struct DiskPartition64 *VInitNextPartition(struct partition_queue *pq);
341 static VolId VInitNextVolumeId(DIR *dirp);
342 static int VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq);
344 #endif /* !AFS_DEMAND_ATTACH_FS */
345 #endif /* AFS_PTHREAD_ENV */
347 #ifndef AFS_DEMAND_ATTACH_FS
348 static int VAttachVolumesByPartition(struct DiskPartition64 *diskP,
349 int * nAttached, int * nUnattached);
350 #endif /* AFS_DEMAND_ATTACH_FS */
353 #ifdef AFS_DEMAND_ATTACH_FS
354 /* demand attach fileserver extensions */
357 * in the future we will support serialization of VLRU state into the fs_state
360 * these structures are the beginning of that effort
362 struct VLRU_DiskHeader {
363 struct versionStamp stamp; /* magic and structure version number */
364 afs_uint32 mtime; /* time of dump to disk */
365 afs_uint32 num_records; /* number of VLRU_DiskEntry records */
368 struct VLRU_DiskEntry {
369 afs_uint32 vid; /* volume ID */
370 afs_uint32 idx; /* generation */
371 afs_uint32 last_get; /* timestamp of last get */
374 struct VLRU_StartupQueue {
375 struct VLRU_DiskEntry * entry;
380 typedef struct vshutdown_thread_t {
382 pthread_mutex_t lock;
384 pthread_cond_t master_cv;
386 int n_threads_complete;
388 int schedule_version;
391 byte n_parts_done_pass;
392 byte part_thread_target[VOLMAXPARTS+1];
393 byte part_done_pass[VOLMAXPARTS+1];
394 struct rx_queue * part_pass_head[VOLMAXPARTS+1];
395 int stats[4][VOLMAXPARTS+1];
396 } vshutdown_thread_t;
397 static void * VShutdownThread(void * args);
400 static Volume * VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode);
401 static int VCheckFree(Volume * vp);
404 static void AddVolumeToVByPList_r(Volume * vp);
405 static void DeleteVolumeFromVByPList_r(Volume * vp);
406 static void VVByPListBeginExclusive_r(struct DiskPartition64 * dp);
407 static void VVByPListEndExclusive_r(struct DiskPartition64 * dp);
408 static void VVByPListWait_r(struct DiskPartition64 * dp);
410 /* online salvager */
411 static int VCheckSalvage(Volume * vp);
412 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
413 static int VScheduleSalvage_r(Volume * vp);
416 /* Volume hash table */
417 static void VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp);
418 static void VHashBeginExclusive_r(VolumeHashChainHead * head);
419 static void VHashEndExclusive_r(VolumeHashChainHead * head);
420 static void VHashWait_r(VolumeHashChainHead * head);
423 static int ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass);
424 static int ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
425 struct rx_queue ** idx);
426 static void ShutdownController(vshutdown_thread_t * params);
427 static void ShutdownCreateSchedule(vshutdown_thread_t * params);
430 static void VLRU_ComputeConstants(void);
431 static void VInitVLRU(void);
432 static void VLRU_Init_Node_r(Volume * vp);
433 static void VLRU_Add_r(Volume * vp);
434 static void VLRU_Delete_r(Volume * vp);
435 static void VLRU_UpdateAccess_r(Volume * vp);
436 static void * VLRU_ScannerThread(void * args);
437 static void VLRU_Scan_r(int idx);
438 static void VLRU_Promote_r(int idx);
439 static void VLRU_Demote_r(int idx);
440 static void VLRU_SwitchQueues(Volume * vp, int new_idx, int append);
443 static int VCheckSoftDetach(Volume * vp, afs_uint32 thresh);
444 static int VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh);
445 static int VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh);
448 pthread_key_t VThread_key;
449 VThreadOptions_t VThread_defaults = {
450 0 /**< allow salvsync */
452 #endif /* AFS_DEMAND_ATTACH_FS */
455 struct Lock vol_listLock; /* Lock obtained when listing volumes:
456 * prevents a volume from being missed
457 * if the volume is attached during a
461 /* Common message used when the volume goes off line */
462 char *VSalvageMessage =
463 "Files in this volume are currently unavailable; call operations";
465 int VInit; /* 0 - uninitialized,
466 * 1 - initialized but not all volumes have been attached,
467 * 2 - initialized and all volumes have been attached,
468 * 3 - initialized, all volumes have been attached, and
469 * VConnectFS() has completed. */
471 static int vinit_attach_abort = 0;
473 bit32 VolumeCacheCheck; /* Incremented everytime a volume goes on line--
474 * used to stamp volume headers and in-core
475 * vnodes. When the volume goes on-line the
476 * vnode will be invalidated
477 * access only with VOL_LOCK held */
482 /***************************************************/
483 /* Startup routines */
484 /***************************************************/
486 #if defined(FAST_RESTART) && defined(AFS_DEMAND_ATTACH_FS)
487 # error FAST_RESTART and DAFS are incompatible. For the DAFS equivalent \
488 of FAST_RESTART, use the -unsafe-nosalvage fileserver argument
492 * assign default values to a VolumePackageOptions struct.
494 * Always call this on a VolumePackageOptions struct first, then set any
495 * specific options you want, then call VInitVolumePackage2.
497 * @param[in] pt caller's program type
498 * @param[out] opts volume package options
501 VOptDefaults(ProgramType pt, VolumePackageOptions *opts)
503 opts->nLargeVnodes = opts->nSmallVnodes = 5;
506 opts->canScheduleSalvage = 0;
507 opts->canUseFSSYNC = 0;
508 opts->canUseSALVSYNC = 0;
510 opts->interrupt_rxcall = NULL;
511 opts->offline_timeout = -1;
512 opts->offline_shutdown_timeout = -1;
515 opts->unsafe_attach = 1;
516 #else /* !FAST_RESTART */
517 opts->unsafe_attach = 0;
518 #endif /* !FAST_RESTART */
522 opts->canScheduleSalvage = 1;
523 opts->canUseSALVSYNC = 1;
527 opts->canUseFSSYNC = 1;
531 opts->nLargeVnodes = 0;
532 opts->nSmallVnodes = 0;
534 opts->canScheduleSalvage = 1;
535 opts->canUseFSSYNC = 1;
545 * Set VInit to a certain value, and signal waiters.
547 * @param[in] value the value to set VInit to
552 VSetVInit_r(int value)
555 CV_BROADCAST(&vol_vinit_cond);
559 VLogOfflineTimeout(const char *type, afs_int32 timeout)
565 Log("VInitVolumePackage: Interrupting clients accessing %s "
566 "immediately\n", type);
568 Log("VInitVolumePackage: Interrupting clients accessing %s "
569 "after %ld second%s\n", type, (long)timeout, timeout==1?"":"s");
574 VInitVolumePackage2(ProgramType pt, VolumePackageOptions * opts)
576 int errors = 0; /* Number of errors while finding vice partitions. */
581 #ifndef AFS_PTHREAD_ENV
582 if (opts->offline_timeout != -1 || opts->offline_shutdown_timeout != -1) {
583 Log("VInitVolumePackage: offline_timeout and/or "
584 "offline_shutdown_timeout was specified, but the volume package "
585 "does not support these for LWP builds\n");
589 VLogOfflineTimeout("volumes going offline", opts->offline_timeout);
590 VLogOfflineTimeout("volumes going offline during shutdown",
591 opts->offline_shutdown_timeout);
593 memset(&VStats, 0, sizeof(VStats));
594 VStats.hdr_cache_size = 200;
596 VInitPartitionPackage();
598 #ifdef AFS_DEMAND_ATTACH_FS
599 if (programType == fileServer) {
602 VLRU_SetOptions(VLRU_SET_ENABLED, 0);
604 osi_Assert(pthread_key_create(&VThread_key, NULL) == 0);
607 MUTEX_INIT(&vol_glock_mutex, "vol glock", MUTEX_DEFAULT, 0);
608 MUTEX_INIT(&vol_trans_mutex, "vol trans", MUTEX_DEFAULT, 0);
609 CV_INIT(&vol_put_volume_cond, "vol put", CV_DEFAULT, 0);
610 CV_INIT(&vol_sleep_cond, "vol sleep", CV_DEFAULT, 0);
611 CV_INIT(&vol_init_attach_cond, "vol init attach", CV_DEFAULT, 0);
612 CV_INIT(&vol_vinit_cond, "vol init", CV_DEFAULT, 0);
613 #ifndef AFS_PTHREAD_ENV
615 #endif /* AFS_PTHREAD_ENV */
616 Lock_Init(&vol_listLock);
618 srandom(time(0)); /* For VGetVolumeInfo */
620 #ifdef AFS_DEMAND_ATTACH_FS
621 MUTEX_INIT(&vol_salvsync_mutex, "salvsync", MUTEX_DEFAULT, 0);
622 #endif /* AFS_DEMAND_ATTACH_FS */
624 /* Ok, we have done enough initialization that fileserver can
625 * start accepting calls, even though the volumes may not be
626 * available just yet.
630 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_SERVER)
631 if (programType == salvageServer) {
634 #endif /* AFS_DEMAND_ATTACH_FS */
635 #ifdef FSSYNC_BUILD_SERVER
636 if (programType == fileServer) {
640 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_CLIENT)
641 if (VCanUseSALVSYNC()) {
642 /* establish a connection to the salvager at this point */
643 osi_Assert(VConnectSALV() != 0);
645 #endif /* AFS_DEMAND_ATTACH_FS */
647 if (opts->volcache > VStats.hdr_cache_size)
648 VStats.hdr_cache_size = opts->volcache;
649 VInitVolumeHeaderCache(VStats.hdr_cache_size);
651 VInitVnodes(vLarge, opts->nLargeVnodes);
652 VInitVnodes(vSmall, opts->nSmallVnodes);
655 errors = VAttachPartitions();
659 if (programType != fileServer) {
660 errors = VInitAttachVolumes(programType);
666 #ifdef FSSYNC_BUILD_CLIENT
667 if (VCanUseFSSYNC()) {
669 #ifdef AFS_DEMAND_ATTACH_FS
670 if (programType == salvageServer) {
671 Log("Unable to connect to file server; aborted\n");
674 #endif /* AFS_DEMAND_ATTACH_FS */
675 Log("Unable to connect to file server; will retry at need\n");
678 #endif /* FSSYNC_BUILD_CLIENT */
683 #if !defined(AFS_PTHREAD_ENV)
685 * Attach volumes in vice partitions
687 * @param[in] pt calling program type
690 * @note This is the original, non-threaded version of attach parititions.
692 * @post VInit state is 2
695 VInitAttachVolumes(ProgramType pt)
697 osi_Assert(VInit==1);
698 if (pt == fileServer) {
699 struct DiskPartition64 *diskP;
700 /* Attach all the volumes in this partition */
701 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
702 int nAttached = 0, nUnattached = 0;
703 osi_Assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
707 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
708 LWP_NoYieldSignal(VInitAttachVolumes);
712 #endif /* !AFS_PTHREAD_ENV */
714 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_DEMAND_ATTACH_FS)
716 * Attach volumes in vice partitions
718 * @param[in] pt calling program type
721 * @note Threaded version of attach parititions.
723 * @post VInit state is 2
726 VInitAttachVolumes(ProgramType pt)
728 osi_Assert(VInit==1);
729 if (pt == fileServer) {
730 struct DiskPartition64 *diskP;
731 struct vinitvolumepackage_thread_t params;
732 struct diskpartition_queue_t * dpq;
733 int i, threads, parts;
735 pthread_attr_t attrs;
737 CV_INIT(¶ms.thread_done_cv, "thread done", CV_DEFAULT, 0);
739 params.n_threads_complete = 0;
741 /* create partition work queue */
742 for (parts=0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
743 dpq = (diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
744 osi_Assert(dpq != NULL);
746 queue_Append(¶ms,dpq);
749 threads = MIN(parts, vol_attach_threads);
752 /* spawn off a bunch of initialization threads */
753 osi_Assert(pthread_attr_init(&attrs) == 0);
754 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
756 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
757 Log("VInitVolumePackage: using %d threads to attach volumes on %d partitions\n",
761 for (i=0; i < threads; i++) {
764 osi_Assert(pthread_create
765 (&tid, &attrs, &VInitVolumePackageThread,
767 AFS_SIGSET_RESTORE();
770 while(params.n_threads_complete < threads) {
771 VOL_CV_WAIT(¶ms.thread_done_cv);
775 osi_Assert(pthread_attr_destroy(&attrs) == 0);
777 /* if we're only going to run one init thread, don't bother creating
779 Log("VInitVolumePackage: beginning single-threaded fileserver startup\n");
780 Log("VInitVolumePackage: using 1 thread to attach volumes on %d partition(s)\n",
783 VInitVolumePackageThread(¶ms);
786 CV_DESTROY(¶ms.thread_done_cv);
789 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
790 CV_BROADCAST(&vol_init_attach_cond);
796 VInitVolumePackageThread(void * args) {
798 struct DiskPartition64 *diskP;
799 struct vinitvolumepackage_thread_t * params;
800 struct diskpartition_queue_t * dpq;
802 params = (vinitvolumepackage_thread_t *) args;
806 /* Attach all the volumes in this partition */
807 while (queue_IsNotEmpty(params)) {
808 int nAttached = 0, nUnattached = 0;
810 if (vinit_attach_abort) {
811 Log("Aborting initialization\n");
815 dpq = queue_First(params,diskpartition_queue_t);
821 osi_Assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
827 params->n_threads_complete++;
828 CV_SIGNAL(¶ms->thread_done_cv);
832 #endif /* AFS_PTHREAD_ENV && !AFS_DEMAND_ATTACH_FS */
834 #if defined(AFS_DEMAND_ATTACH_FS)
836 * Attach volumes in vice partitions
838 * @param[in] pt calling program type
841 * @note Threaded version of attach partitions.
843 * @post VInit state is 2
846 VInitAttachVolumes(ProgramType pt)
848 osi_Assert(VInit==1);
849 if (pt == fileServer) {
851 struct DiskPartition64 *diskP;
852 struct partition_queue pq;
853 struct volume_init_queue vq;
855 int i, threads, parts;
857 pthread_attr_t attrs;
859 /* create partition work queue */
861 CV_INIT(&(pq.cv), "partq", CV_DEFAULT, 0);
862 MUTEX_INIT(&(pq.mutex), "partq", MUTEX_DEFAULT, 0);
863 for (parts = 0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
864 struct diskpartition_queue_t *dp;
865 dp = (struct diskpartition_queue_t*)malloc(sizeof(struct diskpartition_queue_t));
866 osi_Assert(dp != NULL);
868 queue_Append(&pq, dp);
871 /* number of worker threads; at least one, not to exceed the number of partitions */
872 threads = MIN(parts, vol_attach_threads);
874 /* create volume work queue */
876 CV_INIT(&(vq.cv), "volq", CV_DEFAULT, 0);
877 MUTEX_INIT(&(vq.mutex), "volq", MUTEX_DEFAULT, 0);
879 osi_Assert(pthread_attr_init(&attrs) == 0);
880 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
882 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
883 Log("VInitVolumePackage: using %d threads to pre-attach volumes on %d partitions\n",
886 /* create threads to scan disk partitions. */
887 for (i=0; i < threads; i++) {
888 struct vinitvolumepackage_thread_param *params;
891 params = (struct vinitvolumepackage_thread_param *)malloc(sizeof(struct vinitvolumepackage_thread_param));
895 params->nthreads = threads;
896 params->thread = i+1;
899 osi_Assert(pthread_create (&tid, &attrs, &VInitVolumePackageThread, (void*)params) == 0);
900 AFS_SIGSET_RESTORE();
903 VInitPreAttachVolumes(threads, &vq);
905 osi_Assert(pthread_attr_destroy(&attrs) == 0);
907 MUTEX_DESTROY(&pq.mutex);
909 MUTEX_DESTROY(&vq.mutex);
913 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
914 CV_BROADCAST(&vol_init_attach_cond);
921 * Volume package initialization worker thread. Scan partitions for volume
922 * header files. Gather batches of volume ids and dispatch them to
923 * the main thread to be preattached. The volume preattachement is done
924 * in the main thread to avoid global volume lock contention.
927 VInitVolumePackageThread(void *args)
929 struct vinitvolumepackage_thread_param *params;
930 struct DiskPartition64 *partition;
931 struct partition_queue *pq;
932 struct volume_init_queue *vq;
933 struct volume_init_batch *vb;
936 params = (struct vinitvolumepackage_thread_param *)args;
942 vb = (struct volume_init_batch*)malloc(sizeof(struct volume_init_batch));
944 vb->thread = params->thread;
948 Log("Scanning partitions on thread %d of %d\n", params->thread, params->nthreads);
949 while((partition = VInitNextPartition(pq))) {
953 Log("Partition %s: pre-attaching volumes\n", partition->name);
954 dirp = opendir(VPartitionPath(partition));
956 Log("opendir on Partition %s failed, errno=%d!\n", partition->name, errno);
959 while ((vid = VInitNextVolumeId(dirp))) {
960 Volume *vp = (Volume*)malloc(sizeof(Volume));
962 memset(vp, 0, sizeof(Volume));
963 vp->device = partition->device;
964 vp->partition = partition;
966 queue_Init(&vp->vnode_list);
967 queue_Init(&vp->rx_call_list);
968 CV_INIT(&V_attachCV(vp), "partattach", CV_DEFAULT, 0);
970 vb->batch[vb->size++] = vp;
971 if (vb->size == VINIT_BATCH_MAX_SIZE) {
972 MUTEX_ENTER(&vq->mutex);
973 queue_Append(vq, vb);
974 CV_BROADCAST(&vq->cv);
975 MUTEX_EXIT(&vq->mutex);
977 vb = (struct volume_init_batch*)malloc(sizeof(struct volume_init_batch));
979 vb->thread = params->thread;
988 MUTEX_ENTER(&vq->mutex);
989 queue_Append(vq, vb);
990 CV_BROADCAST(&vq->cv);
991 MUTEX_EXIT(&vq->mutex);
993 Log("Partition scan thread %d of %d ended\n", params->thread, params->nthreads);
999 * Read next element from the pre-populated partition list.
1001 static struct DiskPartition64*
1002 VInitNextPartition(struct partition_queue *pq)
1004 struct DiskPartition64 *partition;
1005 struct diskpartition_queue_t *dp; /* queue element */
1007 if (vinit_attach_abort) {
1008 Log("Aborting volume preattach thread.\n");
1012 /* get next partition to scan */
1013 MUTEX_ENTER(&pq->mutex);
1014 if (queue_IsEmpty(pq)) {
1015 MUTEX_EXIT(&pq->mutex);
1018 dp = queue_First(pq, diskpartition_queue_t);
1020 MUTEX_EXIT(&pq->mutex);
1023 osi_Assert(dp->diskP);
1025 partition = dp->diskP;
1031 * Find next volume id on the partition.
1034 VInitNextVolumeId(DIR *dirp)
1040 while((d = readdir(dirp))) {
1041 if (vinit_attach_abort) {
1042 Log("Aborting volume preattach thread.\n");
1045 ext = strrchr(d->d_name, '.');
1046 if (d->d_name[0] == 'V' && ext && strcmp(ext, VHDREXT) == 0) {
1047 vid = VolumeNumber(d->d_name);
1051 Log("Warning: bogus volume header file: %s\n", d->d_name);
1058 * Preattach volumes in batches to avoid lock contention.
1061 VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq)
1063 struct volume_init_batch *vb;
1067 /* dequeue next volume */
1068 MUTEX_ENTER(&vq->mutex);
1069 if (queue_IsEmpty(vq)) {
1070 CV_WAIT(&vq->cv, &vq->mutex);
1072 vb = queue_First(vq, volume_init_batch);
1074 MUTEX_EXIT(&vq->mutex);
1078 for (i = 0; i<vb->size; i++) {
1084 dup = VLookupVolume_r(&ec, vp->hashid, NULL);
1086 Log("Error looking up volume, code=%d\n", ec);
1089 Log("Warning: Duplicate volume id %d detected.\n", vp->hashid);
1092 /* put pre-attached volume onto the hash table
1093 * and bring it up to the pre-attached state */
1094 AddVolumeToHashTable(vp, vp->hashid);
1095 AddVolumeToVByPList_r(vp);
1096 VLRU_Init_Node_r(vp);
1097 VChangeState_r(vp, VOL_STATE_PREATTACHED);
1110 #endif /* AFS_DEMAND_ATTACH_FS */
1112 #if !defined(AFS_DEMAND_ATTACH_FS)
1114 * attach all volumes on a given disk partition
1117 VAttachVolumesByPartition(struct DiskPartition64 *diskP, int * nAttached, int * nUnattached)
1123 Log("Partition %s: attaching volumes\n", diskP->name);
1124 dirp = opendir(VPartitionPath(diskP));
1126 Log("opendir on Partition %s failed!\n", diskP->name);
1130 while ((dp = readdir(dirp))) {
1132 p = strrchr(dp->d_name, '.');
1134 if (vinit_attach_abort) {
1135 Log("Partition %s: abort attach volumes\n", diskP->name);
1139 if (p != NULL && strcmp(p, VHDREXT) == 0) {
1142 vp = VAttachVolumeByName(&error, diskP->name, dp->d_name,
1144 (*(vp ? nAttached : nUnattached))++;
1145 if (error == VOFFLINE)
1146 Log("Volume %d stays offline (/vice/offline/%s exists)\n", VolumeNumber(dp->d_name), dp->d_name);
1147 else if (LogLevel >= 5) {
1148 Log("Partition %s: attached volume %d (%s)\n",
1149 diskP->name, VolumeNumber(dp->d_name),
1158 Log("Partition %s: attached %d volumes; %d volumes not attached\n", diskP->name, *nAttached, *nUnattached);
1163 #endif /* !AFS_DEMAND_ATTACH_FS */
1165 /***************************************************/
1166 /* Shutdown routines */
1167 /***************************************************/
1171 * highly multithreaded volume package shutdown
1173 * with the demand attach fileserver extensions,
1174 * VShutdown has been modified to be multithreaded.
1175 * In order to achieve optimal use of many threads,
1176 * the shutdown code involves one control thread and
1177 * n shutdown worker threads. The control thread
1178 * periodically examines the number of volumes available
1179 * for shutdown on each partition, and produces a worker
1180 * thread allocation schedule. The idea is to eliminate
1181 * redundant scheduling computation on the workers by
1182 * having a single master scheduler.
1184 * The scheduler's objectives are:
1186 * each partition with volumes remaining gets allocated
1187 * at least 1 thread (assuming sufficient threads)
1189 * threads are allocated proportional to the number of
1190 * volumes remaining to be offlined. This ensures that
1191 * the OS I/O scheduler has many requests to elevator
1192 * seek on partitions that will (presumably) take the
1193 * longest amount of time (from now) to finish shutdown
1194 * (3) keep threads busy
1195 * when there are extra threads, they are assigned to
1196 * partitions using a simple round-robin algorithm
1198 * In the future, we may wish to add the ability to adapt
1199 * to the relative performance patterns of each disk
1204 * multi-step shutdown process
1206 * demand attach shutdown is a four-step process. Each
1207 * shutdown "pass" shuts down increasingly more difficult
1208 * volumes. The main purpose is to achieve better cache
1209 * utilization during shutdown.
1212 * shutdown volumes in the unattached, pre-attached
1215 * shutdown attached volumes with cached volume headers
1217 * shutdown all volumes in non-exclusive states
1219 * shutdown all remaining volumes
1222 #ifdef AFS_DEMAND_ATTACH_FS
1228 struct DiskPartition64 * diskP;
1229 struct diskpartition_queue_t * dpq;
1230 vshutdown_thread_t params;
1232 pthread_attr_t attrs;
1234 memset(¶ms, 0, sizeof(vshutdown_thread_t));
1237 Log("VShutdown: aborting attach volumes\n");
1238 vinit_attach_abort = 1;
1239 VOL_CV_WAIT(&vol_init_attach_cond);
1242 for (params.n_parts=0, diskP = DiskPartitionList;
1243 diskP; diskP = diskP->next, params.n_parts++);
1245 Log("VShutdown: shutting down on-line volumes on %d partition%s...\n",
1246 params.n_parts, params.n_parts > 1 ? "s" : "");
1248 vol_shutting_down = 1;
1250 if (vol_attach_threads > 1) {
1251 /* prepare for parallel shutdown */
1252 params.n_threads = vol_attach_threads;
1253 MUTEX_INIT(¶ms.lock, "params", MUTEX_DEFAULT, 0);
1254 CV_INIT(¶ms.cv, "params", CV_DEFAULT, 0);
1255 CV_INIT(¶ms.master_cv, "params master", CV_DEFAULT, 0);
1256 osi_Assert(pthread_attr_init(&attrs) == 0);
1257 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
1258 queue_Init(¶ms);
1260 /* setup the basic partition information structures for
1261 * parallel shutdown */
1262 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1264 struct rx_queue * qp, * nqp;
1268 VVByPListWait_r(diskP);
1269 VVByPListBeginExclusive_r(diskP);
1272 for (queue_Scan(&diskP->vol_list, qp, nqp, rx_queue)) {
1273 vp = (Volume *)((char *)qp - offsetof(Volume, vol_list));
1277 Log("VShutdown: partition %s has %d volumes with attached headers\n",
1278 VPartitionPath(diskP), count);
1281 /* build up the pass 0 shutdown work queue */
1282 dpq = (struct diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
1283 osi_Assert(dpq != NULL);
1285 queue_Prepend(¶ms, dpq);
1287 params.part_pass_head[diskP->index] = queue_First(&diskP->vol_list, rx_queue);
1290 Log("VShutdown: beginning parallel fileserver shutdown\n");
1291 Log("VShutdown: using %d threads to offline volumes on %d partition%s\n",
1292 vol_attach_threads, params.n_parts, params.n_parts > 1 ? "s" : "" );
1294 /* do pass 0 shutdown */
1295 MUTEX_ENTER(¶ms.lock);
1296 for (i=0; i < params.n_threads; i++) {
1297 osi_Assert(pthread_create
1298 (&tid, &attrs, &VShutdownThread,
1302 /* wait for all the pass 0 shutdowns to complete */
1303 while (params.n_threads_complete < params.n_threads) {
1304 CV_WAIT(¶ms.master_cv, ¶ms.lock);
1306 params.n_threads_complete = 0;
1308 CV_BROADCAST(¶ms.cv);
1309 MUTEX_EXIT(¶ms.lock);
1311 Log("VShutdown: pass 0 completed using the 1 thread per partition algorithm\n");
1312 Log("VShutdown: starting passes 1 through 3 using finely-granular mp-fast algorithm\n");
1314 /* run the parallel shutdown scheduler. it will drop the glock internally */
1315 ShutdownController(¶ms);
1317 /* wait for all the workers to finish pass 3 and terminate */
1318 while (params.pass < 4) {
1319 VOL_CV_WAIT(¶ms.cv);
1322 osi_Assert(pthread_attr_destroy(&attrs) == 0);
1323 CV_DESTROY(¶ms.cv);
1324 CV_DESTROY(¶ms.master_cv);
1325 MUTEX_DESTROY(¶ms.lock);
1327 /* drop the VByPList exclusive reservations */
1328 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1329 VVByPListEndExclusive_r(diskP);
1330 Log("VShutdown: %s stats : (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1331 VPartitionPath(diskP),
1332 params.stats[0][diskP->index],
1333 params.stats[1][diskP->index],
1334 params.stats[2][diskP->index],
1335 params.stats[3][diskP->index]);
1338 Log("VShutdown: shutdown finished using %d threads\n", params.n_threads);
1340 /* if we're only going to run one shutdown thread, don't bother creating
1342 Log("VShutdown: beginning single-threaded fileserver shutdown\n");
1344 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1345 VShutdownByPartition_r(diskP);
1349 Log("VShutdown: complete.\n");
1352 #else /* AFS_DEMAND_ATTACH_FS */
1362 Log("VShutdown: aborting attach volumes\n");
1363 vinit_attach_abort = 1;
1364 #ifdef AFS_PTHREAD_ENV
1365 VOL_CV_WAIT(&vol_init_attach_cond);
1367 LWP_WaitProcess(VInitAttachVolumes);
1368 #endif /* AFS_PTHREAD_ENV */
1371 Log("VShutdown: shutting down on-line volumes...\n");
1372 vol_shutting_down = 1;
1373 for (i = 0; i < VolumeHashTable.Size; i++) {
1374 /* try to hold first volume in the hash table */
1375 for (queue_Scan(&VolumeHashTable.Table[i],vp,np,Volume)) {
1379 Log("VShutdown: Attempting to take volume %u offline.\n",
1382 /* next, take the volume offline (drops reference count) */
1383 VOffline_r(vp, "File server was shut down");
1387 Log("VShutdown: complete.\n");
1389 #endif /* AFS_DEMAND_ATTACH_FS */
1395 osi_Assert(VInit>0);
1402 * stop new activity (e.g. SALVSYNC) from occurring
1404 * Use this to make the volume package less busy; for example, during
1405 * shutdown. This doesn't actually shutdown/detach anything in the
1406 * volume package, but prevents certain processes from ocurring. For
1407 * example, preventing new SALVSYNC communication in DAFS. In theory, we
1408 * could also use this to prevent new volume attachment, or prevent
1409 * other programs from checking out volumes, etc.
1414 #ifdef AFS_DEMAND_ATTACH_FS
1415 /* make sure we don't try to contact the salvageserver, since it may
1416 * not be around anymore */
1417 vol_disallow_salvsync = 1;
1421 #ifdef AFS_DEMAND_ATTACH_FS
1424 * shutdown control thread
1427 ShutdownController(vshutdown_thread_t * params)
1430 struct DiskPartition64 * diskP;
1432 vshutdown_thread_t shadow;
1434 ShutdownCreateSchedule(params);
1436 while ((params->pass < 4) &&
1437 (params->n_threads_complete < params->n_threads)) {
1438 /* recompute schedule once per second */
1440 memcpy(&shadow, params, sizeof(vshutdown_thread_t));
1444 Log("ShutdownController: schedule version=%d, vol_remaining=%d, pass=%d\n",
1445 shadow.schedule_version, shadow.vol_remaining, shadow.pass);
1446 Log("ShutdownController: n_threads_complete=%d, n_parts_done_pass=%d\n",
1447 shadow.n_threads_complete, shadow.n_parts_done_pass);
1448 for (diskP = DiskPartitionList; diskP; diskP=diskP->next) {
1450 Log("ShutdownController: part[%d] : (len=%d, thread_target=%d, done_pass=%d, pass_head=%p)\n",
1452 diskP->vol_list.len,
1453 shadow.part_thread_target[id],
1454 shadow.part_done_pass[id],
1455 shadow.part_pass_head[id]);
1461 ShutdownCreateSchedule(params);
1465 /* create the shutdown thread work schedule.
1466 * this scheduler tries to implement fairness
1467 * by allocating at least 1 thread to each
1468 * partition with volumes to be shutdown,
1469 * and then it attempts to allocate remaining
1470 * threads based upon the amount of work left
1473 ShutdownCreateSchedule(vshutdown_thread_t * params)
1475 struct DiskPartition64 * diskP;
1476 int sum, thr_workload, thr_left;
1477 int part_residue[VOLMAXPARTS+1];
1480 /* compute the total number of outstanding volumes */
1482 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1483 sum += diskP->vol_list.len;
1486 params->schedule_version++;
1487 params->vol_remaining = sum;
1492 /* compute average per-thread workload */
1493 thr_workload = sum / params->n_threads;
1494 if (sum % params->n_threads)
1497 thr_left = params->n_threads;
1498 memset(&part_residue, 0, sizeof(part_residue));
1500 /* for fairness, give every partition with volumes remaining
1501 * at least one thread */
1502 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1504 if (diskP->vol_list.len) {
1505 params->part_thread_target[id] = 1;
1508 params->part_thread_target[id] = 0;
1512 if (thr_left && thr_workload) {
1513 /* compute length-weighted workloads */
1516 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1518 delta = (diskP->vol_list.len / thr_workload) -
1519 params->part_thread_target[id];
1523 if (delta < thr_left) {
1524 params->part_thread_target[id] += delta;
1527 params->part_thread_target[id] += thr_left;
1535 /* try to assign any leftover threads to partitions that
1536 * had volume lengths closer to needing thread_target+1 */
1537 int max_residue, max_id = 0;
1539 /* compute the residues */
1540 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1542 part_residue[id] = diskP->vol_list.len -
1543 (params->part_thread_target[id] * thr_workload);
1546 /* now try to allocate remaining threads to partitions with the
1547 * highest residues */
1550 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1552 if (part_residue[id] > max_residue) {
1553 max_residue = part_residue[id];
1562 params->part_thread_target[max_id]++;
1564 part_residue[max_id] = 0;
1569 /* punt and give any remaining threads equally to each partition */
1571 if (thr_left >= params->n_parts) {
1572 alloc = thr_left / params->n_parts;
1573 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1575 params->part_thread_target[id] += alloc;
1580 /* finish off the last of the threads */
1581 for (diskP = DiskPartitionList; thr_left && diskP; diskP = diskP->next) {
1583 params->part_thread_target[id]++;
1589 /* worker thread for parallel shutdown */
1591 VShutdownThread(void * args)
1593 vshutdown_thread_t * params;
1594 int found, pass, schedule_version_save, count;
1595 struct DiskPartition64 *diskP;
1596 struct diskpartition_queue_t * dpq;
1599 params = (vshutdown_thread_t *) args;
1601 /* acquire the shutdown pass 0 lock */
1602 MUTEX_ENTER(¶ms->lock);
1604 /* if there's still pass 0 work to be done,
1605 * get a work entry, and do a pass 0 shutdown */
1606 if (queue_IsNotEmpty(params)) {
1607 dpq = queue_First(params, diskpartition_queue_t);
1609 MUTEX_EXIT(¶ms->lock);
1615 while (ShutdownVolumeWalk_r(diskP, 0, ¶ms->part_pass_head[id]))
1617 params->stats[0][diskP->index] = count;
1618 MUTEX_ENTER(¶ms->lock);
1621 params->n_threads_complete++;
1622 if (params->n_threads_complete == params->n_threads) {
1623 /* notify control thread that all workers have completed pass 0 */
1624 CV_SIGNAL(¶ms->master_cv);
1626 while (params->pass == 0) {
1627 CV_WAIT(¶ms->cv, ¶ms->lock);
1631 MUTEX_EXIT(¶ms->lock);
1634 pass = params->pass;
1635 osi_Assert(pass > 0);
1637 /* now escalate through the more complicated shutdowns */
1639 schedule_version_save = params->schedule_version;
1641 /* find a disk partition to work on */
1642 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1644 if (params->part_thread_target[id] && !params->part_done_pass[id]) {
1645 params->part_thread_target[id]--;
1652 /* hmm. for some reason the controller thread couldn't find anything for
1653 * us to do. let's see if there's anything we can do */
1654 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1656 if (diskP->vol_list.len && !params->part_done_pass[id]) {
1659 } else if (!params->part_done_pass[id]) {
1660 params->part_done_pass[id] = 1;
1661 params->n_parts_done_pass++;
1663 Log("VShutdown: done shutting down volumes on partition %s.\n",
1664 VPartitionPath(diskP));
1670 /* do work on this partition until either the controller
1671 * creates a new schedule, or we run out of things to do
1672 * on this partition */
1675 while (!params->part_done_pass[id] &&
1676 (schedule_version_save == params->schedule_version)) {
1677 /* ShutdownVolumeWalk_r will drop the glock internally */
1678 if (!ShutdownVolumeWalk_r(diskP, pass, ¶ms->part_pass_head[id])) {
1679 if (!params->part_done_pass[id]) {
1680 params->part_done_pass[id] = 1;
1681 params->n_parts_done_pass++;
1683 Log("VShutdown: done shutting down volumes on partition %s.\n",
1684 VPartitionPath(diskP));
1692 params->stats[pass][id] += count;
1694 /* ok, everyone is done this pass, proceed */
1697 params->n_threads_complete++;
1698 while (params->pass == pass) {
1699 if (params->n_threads_complete == params->n_threads) {
1700 /* we are the last thread to complete, so we will
1701 * reinitialize worker pool state for the next pass */
1702 params->n_threads_complete = 0;
1703 params->n_parts_done_pass = 0;
1705 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1707 params->part_done_pass[id] = 0;
1708 params->part_pass_head[id] = queue_First(&diskP->vol_list, rx_queue);
1711 /* compute a new thread schedule before releasing all the workers */
1712 ShutdownCreateSchedule(params);
1714 /* wake up all the workers */
1715 CV_BROADCAST(¶ms->cv);
1718 Log("VShutdown: pass %d completed using %d threads on %d partitions\n",
1719 pass, params->n_threads, params->n_parts);
1722 VOL_CV_WAIT(¶ms->cv);
1725 pass = params->pass;
1739 /* shut down all volumes on a given disk partition
1741 * note that this function will not allow mp-fast
1742 * shutdown of a partition */
1744 VShutdownByPartition_r(struct DiskPartition64 * dp)
1750 /* wait for other exclusive ops to finish */
1751 VVByPListWait_r(dp);
1753 /* begin exclusive access */
1754 VVByPListBeginExclusive_r(dp);
1756 /* pick the low-hanging fruit first,
1757 * then do the complicated ones last
1758 * (has the advantage of keeping
1759 * in-use volumes up until the bitter end) */
1760 for (pass = 0, total=0; pass < 4; pass++) {
1761 pass_stats[pass] = ShutdownVByPForPass_r(dp, pass);
1762 total += pass_stats[pass];
1765 /* end exclusive access */
1766 VVByPListEndExclusive_r(dp);
1768 Log("VShutdownByPartition: shut down %d volumes on %s (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1769 total, VPartitionPath(dp), pass_stats[0], pass_stats[1], pass_stats[2], pass_stats[3]);
1774 /* internal shutdown functionality
1776 * for multi-pass shutdown:
1777 * 0 to only "shutdown" {pre,un}attached and error state volumes
1778 * 1 to also shutdown attached volumes w/ volume header loaded
1779 * 2 to also shutdown attached volumes w/o volume header loaded
1780 * 3 to also shutdown exclusive state volumes
1782 * caller MUST hold exclusive access on the hash chain
1783 * because we drop vol_glock_mutex internally
1785 * this function is reentrant for passes 1--3
1786 * (e.g. multiple threads can cooperate to
1787 * shutdown a partition mp-fast)
1789 * pass 0 is not scaleable because the volume state data is
1790 * synchronized by vol_glock mutex, and the locking overhead
1791 * is too high to drop the lock long enough to do linked list
1795 ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass)
1797 struct rx_queue * q = queue_First(&dp->vol_list, rx_queue);
1800 while (ShutdownVolumeWalk_r(dp, pass, &q))
1806 /* conditionally shutdown one volume on partition dp
1807 * returns 1 if a volume was shutdown in this pass,
1810 ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
1811 struct rx_queue ** idx)
1813 struct rx_queue *qp, *nqp;
1818 for (queue_ScanFrom(&dp->vol_list, qp, qp, nqp, rx_queue)) {
1819 vp = (Volume *) (((char *)qp) - offsetof(Volume, vol_list));
1823 if ((V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1824 (V_attachState(vp) != VOL_STATE_ERROR) &&
1825 (V_attachState(vp) != VOL_STATE_DELETED) &&
1826 (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1830 if ((V_attachState(vp) == VOL_STATE_ATTACHED) &&
1831 (vp->header == NULL)) {
1835 if (VIsExclusiveState(V_attachState(vp))) {
1840 DeleteVolumeFromVByPList_r(vp);
1841 VShutdownVolume_r(vp);
1851 * shutdown a specific volume
1853 /* caller MUST NOT hold a heavyweight ref on vp */
1855 VShutdownVolume_r(Volume * vp)
1859 VCreateReservation_r(vp);
1861 if (LogLevel >= 5) {
1862 Log("VShutdownVolume_r: vid=%u, device=%d, state=%hu\n",
1863 vp->hashid, vp->partition->device, V_attachState(vp));
1866 /* wait for other blocking ops to finish */
1867 VWaitExclusiveState_r(vp);
1869 osi_Assert(VIsValidState(V_attachState(vp)));
1871 switch(V_attachState(vp)) {
1872 case VOL_STATE_SALVAGING:
1873 /* Leave salvaging volumes alone. Any in-progress salvages will
1874 * continue working after viced shuts down. This is intentional.
1877 case VOL_STATE_PREATTACHED:
1878 case VOL_STATE_ERROR:
1879 VChangeState_r(vp, VOL_STATE_UNATTACHED);
1880 case VOL_STATE_UNATTACHED:
1881 case VOL_STATE_DELETED:
1883 case VOL_STATE_GOING_OFFLINE:
1884 case VOL_STATE_SHUTTING_DOWN:
1885 case VOL_STATE_ATTACHED:
1889 Log("VShutdown: Attempting to take volume %u offline.\n",
1892 /* take the volume offline (drops reference count) */
1893 VOffline_r(vp, "File server was shut down");
1900 VCancelReservation_r(vp);
1904 #endif /* AFS_DEMAND_ATTACH_FS */
1907 /***************************************************/
1908 /* Header I/O routines */
1909 /***************************************************/
1911 /* open a descriptor for the inode (h),
1912 * read in an on-disk structure into buffer (to) of size (size),
1913 * verify versionstamp in structure has magic (magic) and
1914 * optionally verify version (version) if (version) is nonzero
1917 ReadHeader(Error * ec, IHandle_t * h, char *to, int size, bit32 magic,
1920 struct versionStamp *vsn;
1935 vsn = (struct versionStamp *)to;
1936 if (FDH_PREAD(fdP, to, size, 0) != size || vsn->magic != magic) {
1938 FDH_REALLYCLOSE(fdP);
1943 /* Check is conditional, in case caller wants to inspect version himself */
1944 if (version && vsn->version != version) {
1950 WriteVolumeHeader_r(Error * ec, Volume * vp)
1952 IHandle_t *h = V_diskDataHandle(vp);
1962 if (FDH_PWRITE(fdP, (char *)&V_disk(vp), sizeof(V_disk(vp)), 0)
1963 != sizeof(V_disk(vp))) {
1965 FDH_REALLYCLOSE(fdP);
1971 /* VolumeHeaderToDisk
1972 * Allows for storing 64 bit inode numbers in on-disk volume header
1975 /* convert in-memory representation of a volume header to the
1976 * on-disk representation of a volume header */
1978 VolumeHeaderToDisk(VolumeDiskHeader_t * dh, VolumeHeader_t * h)
1981 memset(dh, 0, sizeof(VolumeDiskHeader_t));
1982 dh->stamp = h->stamp;
1984 dh->parent = h->parent;
1986 #ifdef AFS_64BIT_IOPS_ENV
1987 dh->volumeInfo_lo = (afs_int32) h->volumeInfo & 0xffffffff;
1988 dh->volumeInfo_hi = (afs_int32) (h->volumeInfo >> 32) & 0xffffffff;
1989 dh->smallVnodeIndex_lo = (afs_int32) h->smallVnodeIndex & 0xffffffff;
1990 dh->smallVnodeIndex_hi =
1991 (afs_int32) (h->smallVnodeIndex >> 32) & 0xffffffff;
1992 dh->largeVnodeIndex_lo = (afs_int32) h->largeVnodeIndex & 0xffffffff;
1993 dh->largeVnodeIndex_hi =
1994 (afs_int32) (h->largeVnodeIndex >> 32) & 0xffffffff;
1995 dh->linkTable_lo = (afs_int32) h->linkTable & 0xffffffff;
1996 dh->linkTable_hi = (afs_int32) (h->linkTable >> 32) & 0xffffffff;
1998 dh->volumeInfo_lo = h->volumeInfo;
1999 dh->smallVnodeIndex_lo = h->smallVnodeIndex;
2000 dh->largeVnodeIndex_lo = h->largeVnodeIndex;
2001 dh->linkTable_lo = h->linkTable;
2005 /* DiskToVolumeHeader
2006 * Converts an on-disk representation of a volume header to
2007 * the in-memory representation of a volume header.
2009 * Makes the assumption that AFS has *always*
2010 * zero'd the volume header file so that high parts of inode
2011 * numbers are 0 in older (SGI EFS) volume header files.
2014 DiskToVolumeHeader(VolumeHeader_t * h, VolumeDiskHeader_t * dh)
2016 memset(h, 0, sizeof(VolumeHeader_t));
2017 h->stamp = dh->stamp;
2019 h->parent = dh->parent;
2021 #ifdef AFS_64BIT_IOPS_ENV
2023 (Inode) dh->volumeInfo_lo | ((Inode) dh->volumeInfo_hi << 32);
2025 h->smallVnodeIndex =
2026 (Inode) dh->smallVnodeIndex_lo | ((Inode) dh->
2027 smallVnodeIndex_hi << 32);
2029 h->largeVnodeIndex =
2030 (Inode) dh->largeVnodeIndex_lo | ((Inode) dh->
2031 largeVnodeIndex_hi << 32);
2033 (Inode) dh->linkTable_lo | ((Inode) dh->linkTable_hi << 32);
2035 h->volumeInfo = dh->volumeInfo_lo;
2036 h->smallVnodeIndex = dh->smallVnodeIndex_lo;
2037 h->largeVnodeIndex = dh->largeVnodeIndex_lo;
2038 h->linkTable = dh->linkTable_lo;
2043 /***************************************************/
2044 /* Volume Attachment routines */
2045 /***************************************************/
2047 #ifdef AFS_DEMAND_ATTACH_FS
2049 * pre-attach a volume given its path.
2051 * @param[out] ec outbound error code
2052 * @param[in] partition partition path string
2053 * @param[in] name volume id string
2055 * @return volume object pointer
2057 * @note A pre-attached volume will only have its partition
2058 * and hashid fields initialized. At first call to
2059 * VGetVolume, the volume will be fully attached.
2063 VPreAttachVolumeByName(Error * ec, char *partition, char *name)
2067 vp = VPreAttachVolumeByName_r(ec, partition, name);
2073 * pre-attach a volume given its path.
2075 * @param[out] ec outbound error code
2076 * @param[in] partition path to vice partition
2077 * @param[in] name volume id string
2079 * @return volume object pointer
2081 * @pre VOL_LOCK held
2083 * @internal volume package internal use only.
2086 VPreAttachVolumeByName_r(Error * ec, char *partition, char *name)
2088 return VPreAttachVolumeById_r(ec,
2090 VolumeNumber(name));
2094 * pre-attach a volume given its path and numeric volume id.
2096 * @param[out] ec error code return
2097 * @param[in] partition path to vice partition
2098 * @param[in] volumeId numeric volume id
2100 * @return volume object pointer
2102 * @pre VOL_LOCK held
2104 * @internal volume package internal use only.
2107 VPreAttachVolumeById_r(Error * ec,
2112 struct DiskPartition64 *partp;
2116 osi_Assert(programType == fileServer);
2118 if (!(partp = VGetPartition_r(partition, 0))) {
2120 Log("VPreAttachVolumeById_r: Error getting partition (%s)\n", partition);
2124 vp = VLookupVolume_r(ec, volumeId, NULL);
2129 return VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2133 * preattach a volume.
2135 * @param[out] ec outbound error code
2136 * @param[in] partp pointer to partition object
2137 * @param[in] vp pointer to volume object
2138 * @param[in] vid volume id
2140 * @return volume object pointer
2142 * @pre VOL_LOCK is held.
2144 * @warning Returned volume object pointer does not have to
2145 * equal the pointer passed in as argument vp. There
2146 * are potential race conditions which can result in
2147 * the pointers having different values. It is up to
2148 * the caller to make sure that references are handled
2149 * properly in this case.
2151 * @note If there is already a volume object registered with
2152 * the same volume id, its pointer MUST be passed as
2153 * argument vp. Failure to do so will result in a silent
2154 * failure to preattach.
2156 * @internal volume package internal use only.
2159 VPreAttachVolumeByVp_r(Error * ec,
2160 struct DiskPartition64 * partp,
2168 /* check to see if pre-attach already happened */
2170 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
2171 (V_attachState(vp) != VOL_STATE_DELETED) &&
2172 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
2173 !VIsErrorState(V_attachState(vp))) {
2175 * pre-attach is a no-op in all but the following cases:
2177 * - volume is unattached
2178 * - volume is in an error state
2179 * - volume is pre-attached
2181 Log("VPreattachVolumeByVp_r: volume %u not in quiescent state\n", vid);
2184 /* we're re-attaching a volume; clear out some old state */
2185 memset(&vp->salvage, 0, sizeof(struct VolumeOnlineSalvage));
2187 if (V_partition(vp) != partp) {
2188 /* XXX potential race */
2189 DeleteVolumeFromVByPList_r(vp);
2192 /* if we need to allocate a new Volume struct,
2193 * go ahead and drop the vol glock, otherwise
2194 * do the basic setup synchronised, as it's
2195 * probably not worth dropping the lock */
2198 /* allocate the volume structure */
2199 vp = nvp = (Volume *) malloc(sizeof(Volume));
2200 osi_Assert(vp != NULL);
2201 memset(vp, 0, sizeof(Volume));
2202 queue_Init(&vp->vnode_list);
2203 queue_Init(&vp->rx_call_list);
2204 CV_INIT(&V_attachCV(vp), "vp attach", CV_DEFAULT, 0);
2207 /* link the volume with its associated vice partition */
2208 vp->device = partp->device;
2209 vp->partition = partp;
2212 vp->specialStatus = 0;
2214 /* if we dropped the lock, reacquire the lock,
2215 * check for pre-attach races, and then add
2216 * the volume to the hash table */
2219 nvp = VLookupVolume_r(ec, vid, NULL);
2224 } else if (nvp) { /* race detected */
2229 /* hack to make up for VChangeState_r() decrementing
2230 * the old state counter */
2231 VStats.state_levels[0]++;
2235 /* put pre-attached volume onto the hash table
2236 * and bring it up to the pre-attached state */
2237 AddVolumeToHashTable(vp, vp->hashid);
2238 AddVolumeToVByPList_r(vp);
2239 VLRU_Init_Node_r(vp);
2240 VChangeState_r(vp, VOL_STATE_PREATTACHED);
2243 Log("VPreAttachVolumeByVp_r: volume %u pre-attached\n", vp->hashid);
2251 #endif /* AFS_DEMAND_ATTACH_FS */
2253 /* Attach an existing volume, given its pathname, and return a
2254 pointer to the volume header information. The volume also
2255 normally goes online at this time. An offline volume
2256 must be reattached to make it go online */
2258 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
2262 retVal = VAttachVolumeByName_r(ec, partition, name, mode);
2268 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
2271 struct DiskPartition64 *partp;
2276 #ifdef AFS_DEMAND_ATTACH_FS
2277 VolumeStats stats_save;
2279 #endif /* AFS_DEMAND_ATTACH_FS */
2283 volumeId = VolumeNumber(name);
2285 if (!(partp = VGetPartition_r(partition, 0))) {
2287 Log("VAttachVolume: Error getting partition (%s)\n", partition);
2291 if (VRequiresPartLock()) {
2292 osi_Assert(VInit == 3);
2293 VLockPartition_r(partition);
2294 } else if (programType == fileServer) {
2295 #ifdef AFS_DEMAND_ATTACH_FS
2296 /* lookup the volume in the hash table */
2297 vp = VLookupVolume_r(ec, volumeId, NULL);
2303 /* save any counters that are supposed to
2304 * be monotonically increasing over the
2305 * lifetime of the fileserver */
2306 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2308 memset(&stats_save, 0, sizeof(VolumeStats));
2311 /* if there's something in the hash table, and it's not
2312 * in the pre-attach state, then we may need to detach
2313 * it before proceeding */
2314 if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
2315 VCreateReservation_r(vp);
2316 VWaitExclusiveState_r(vp);
2318 /* at this point state must be one of:
2328 if (vp->specialStatus == VBUSY)
2331 /* if it's already attached, see if we can return it */
2332 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2333 VGetVolumeByVp_r(ec, vp);
2334 if (V_inUse(vp) == fileServer) {
2335 VCancelReservation_r(vp);
2339 /* otherwise, we need to detach, and attempt to re-attach */
2340 VDetachVolume_r(ec, vp);
2342 Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
2345 /* if it isn't fully attached, delete from the hash tables,
2346 and let the refcounter handle the rest */
2347 DeleteVolumeFromHashTable(vp);
2348 DeleteVolumeFromVByPList_r(vp);
2351 VCancelReservation_r(vp);
2355 /* pre-attach volume if it hasn't been done yet */
2357 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2358 (V_attachState(vp) == VOL_STATE_DELETED) ||
2359 (V_attachState(vp) == VOL_STATE_ERROR)) {
2361 vp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2367 osi_Assert(vp != NULL);
2369 /* handle pre-attach races
2371 * multiple threads can race to pre-attach a volume,
2372 * but we can't let them race beyond that
2374 * our solution is to let the first thread to bring
2375 * the volume into an exclusive state win; the other
2376 * threads just wait until it finishes bringing the
2377 * volume online, and then they do a vgetvolumebyvp
2379 if (svp && (svp != vp)) {
2380 /* wait for other exclusive ops to finish */
2381 VCreateReservation_r(vp);
2382 VWaitExclusiveState_r(vp);
2384 /* get a heavyweight ref, kill the lightweight ref, and return */
2385 VGetVolumeByVp_r(ec, vp);
2386 VCancelReservation_r(vp);
2390 /* at this point, we are chosen as the thread to do
2391 * demand attachment for this volume. all other threads
2392 * doing a getvolume on vp->hashid will block until we finish */
2394 /* make sure any old header cache entries are invalidated
2395 * before proceeding */
2396 FreeVolumeHeader(vp);
2398 VChangeState_r(vp, VOL_STATE_ATTACHING);
2400 /* restore any saved counters */
2401 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2402 #else /* AFS_DEMAND_ATTACH_FS */
2403 vp = VGetVolume_r(ec, volumeId);
2405 if (V_inUse(vp) == fileServer)
2407 if (vp->specialStatus == VBUSY)
2409 VDetachVolume_r(ec, vp);
2411 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2415 #endif /* AFS_DEMAND_ATTACH_FS */
2419 strcpy(path, VPartitionPath(partp));
2423 strcat(path, OS_DIRSEP);
2427 vp = (Volume *) calloc(1, sizeof(Volume));
2428 osi_Assert(vp != NULL);
2429 vp->hashid = volumeId;
2430 vp->device = partp->device;
2431 vp->partition = partp;
2432 queue_Init(&vp->vnode_list);
2433 queue_Init(&vp->rx_call_list);
2434 #ifdef AFS_DEMAND_ATTACH_FS
2435 CV_INIT(&V_attachCV(vp), "vp attach", CV_DEFAULT, 0);
2436 #endif /* AFS_DEMAND_ATTACH_FS */
2439 /* attach2 is entered without any locks, and returns
2440 * with vol_glock_mutex held */
2441 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2443 if (VCanUseFSSYNC() && vp) {
2444 #ifdef AFS_DEMAND_ATTACH_FS
2445 if ((mode == V_VOLUPD) || (VolumeWriteable(vp) && (mode == V_CLONE))) {
2446 /* mark volume header as in use so that volser crashes lead to a
2447 * salvage attempt */
2448 VUpdateVolume_r(ec, vp, 0);
2450 /* for dafs, we should tell the fileserver, except for V_PEEK
2451 * where we know it is not necessary */
2452 if (mode == V_PEEK) {
2453 vp->needsPutBack = 0;
2455 vp->needsPutBack = VOL_PUTBACK;
2457 #else /* !AFS_DEMAND_ATTACH_FS */
2458 /* duplicate computation in fssync.c about whether the server
2459 * takes the volume offline or not. If the volume isn't
2460 * offline, we must not return it when we detach the volume,
2461 * or the server will abort */
2462 if (mode == V_READONLY || mode == V_PEEK
2463 || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
2464 vp->needsPutBack = 0;
2466 vp->needsPutBack = VOL_PUTBACK;
2467 #endif /* !AFS_DEMAND_ATTACH_FS */
2469 #ifdef FSSYNC_BUILD_CLIENT
2470 /* Only give back the vol to the fileserver if we checked it out; attach2
2471 * will set checkedOut only if we successfully checked it out from the
2473 if (VCanUseFSSYNC() && vp == NULL && checkedOut) {
2475 #ifdef AFS_DEMAND_ATTACH_FS
2476 /* If we couldn't attach but we scheduled a salvage, we already
2477 * notified the fileserver; don't online it now */
2478 if (*ec != VSALVAGING)
2479 #endif /* AFS_DEMAND_ATTACH_FS */
2480 FSYNC_VolOp(volumeId, partition, FSYNC_VOL_ON, 0, NULL);
2483 if (programType == fileServer && vp) {
2484 #ifdef AFS_DEMAND_ATTACH_FS
2486 * we can get here in cases where we don't "own"
2487 * the volume (e.g. volume owned by a utility).
2488 * short circuit around potential disk header races.
2490 if (V_attachState(vp) != VOL_STATE_ATTACHED) {
2494 VUpdateVolume_r(ec, vp, 0);
2496 Log("VAttachVolume: Error updating volume\n");
2501 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2502 #ifndef AFS_DEMAND_ATTACH_FS
2503 /* This is a hack: by temporarily setting the incore
2504 * dontSalvage flag ON, the volume will be put back on the
2505 * Update list (with dontSalvage OFF again). It will then
2506 * come back in N minutes with DONT_SALVAGE eventually
2507 * set. This is the way that volumes that have never had
2508 * it set get it set; or that volumes that have been
2509 * offline without DONT SALVAGE having been set also
2510 * eventually get it set */
2511 V_dontSalvage(vp) = DONT_SALVAGE;
2512 #endif /* !AFS_DEMAND_ATTACH_FS */
2513 VAddToVolumeUpdateList_r(ec, vp);
2515 Log("VAttachVolume: Error adding volume to update list\n");
2522 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2527 if (VRequiresPartLock()) {
2528 VUnlockPartition_r(partition);
2531 #ifdef AFS_DEMAND_ATTACH_FS
2532 /* attach failed; make sure we're in error state */
2533 if (vp && !VIsErrorState(V_attachState(vp))) {
2534 VChangeState_r(vp, VOL_STATE_ERROR);
2536 #endif /* AFS_DEMAND_ATTACH_FS */
2543 #ifdef AFS_DEMAND_ATTACH_FS
2544 /* VAttachVolumeByVp_r
2546 * finish attaching a volume that is
2547 * in a less than fully attached state
2549 /* caller MUST hold a ref count on vp */
2551 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
2553 char name[VMAXPATHLEN];
2555 struct DiskPartition64 *partp;
2559 Volume * nvp = NULL;
2560 VolumeStats stats_save;
2564 /* volume utility should never call AttachByVp */
2565 osi_Assert(programType == fileServer);
2567 volumeId = vp->hashid;
2568 partp = vp->partition;
2569 VolumeExternalName_r(volumeId, name, sizeof(name));
2572 /* if another thread is performing a blocking op, wait */
2573 VWaitExclusiveState_r(vp);
2575 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2577 /* if it's already attached, see if we can return it */
2578 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2579 VGetVolumeByVp_r(ec, vp);
2580 if (V_inUse(vp) == fileServer) {
2583 if (vp->specialStatus == VBUSY)
2585 VDetachVolume_r(ec, vp);
2587 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2593 /* pre-attach volume if it hasn't been done yet */
2595 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2596 (V_attachState(vp) == VOL_STATE_DELETED) ||
2597 (V_attachState(vp) == VOL_STATE_ERROR)) {
2598 nvp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2604 VCreateReservation_r(nvp);
2609 osi_Assert(vp != NULL);
2610 VChangeState_r(vp, VOL_STATE_ATTACHING);
2612 /* restore monotonically increasing stats */
2613 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2617 /* compute path to disk header */
2618 strcpy(path, VPartitionPath(partp));
2622 strcat(path, OS_DIRSEP);
2627 * NOTE: attach2 is entered without any locks, and returns
2628 * with vol_glock_mutex held */
2629 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2632 * the event that an error was encountered, or
2633 * the volume was not brought to an attached state
2634 * for any reason, skip to the end. We cannot
2635 * safely call VUpdateVolume unless we "own" it.
2639 (V_attachState(vp) != VOL_STATE_ATTACHED)) {
2643 VUpdateVolume_r(ec, vp, 0);
2645 Log("VAttachVolume: Error updating volume %u\n", vp->hashid);
2649 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2650 #ifndef AFS_DEMAND_ATTACH_FS
2651 /* This is a hack: by temporarily setting the incore
2652 * dontSalvage flag ON, the volume will be put back on the
2653 * Update list (with dontSalvage OFF again). It will then
2654 * come back in N minutes with DONT_SALVAGE eventually
2655 * set. This is the way that volumes that have never had
2656 * it set get it set; or that volumes that have been
2657 * offline without DONT SALVAGE having been set also
2658 * eventually get it set */
2659 V_dontSalvage(vp) = DONT_SALVAGE;
2660 #endif /* !AFS_DEMAND_ATTACH_FS */
2661 VAddToVolumeUpdateList_r(ec, vp);
2663 Log("VAttachVolume: Error adding volume %u to update list\n", vp->hashid);
2670 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2674 VCancelReservation_r(nvp);
2677 if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2678 if (vp && !VIsErrorState(V_attachState(vp))) {
2679 VChangeState_r(vp, VOL_STATE_ERROR);
2688 * lock a volume on disk (non-blocking).
2690 * @param[in] vp The volume to lock
2691 * @param[in] locktype READ_LOCK or WRITE_LOCK
2693 * @return operation status
2694 * @retval 0 success, lock was obtained
2695 * @retval EBUSY a conflicting lock was held by another process
2696 * @retval EIO error acquiring lock
2698 * @pre If we're in the fileserver, vp is in an exclusive state
2700 * @pre vp is not already locked
2703 VLockVolumeNB(Volume *vp, int locktype)
2707 osi_Assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2708 osi_Assert(!(V_attachFlags(vp) & VOL_LOCKED));
2710 code = VLockVolumeByIdNB(vp->hashid, vp->partition, locktype);
2712 V_attachFlags(vp) |= VOL_LOCKED;
2719 * unlock a volume on disk that was locked with VLockVolumeNB.
2721 * @param[in] vp volume to unlock
2723 * @pre If we're in the fileserver, vp is in an exclusive state
2725 * @pre vp has already been locked
2728 VUnlockVolume(Volume *vp)
2730 osi_Assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2731 osi_Assert((V_attachFlags(vp) & VOL_LOCKED));
2733 VUnlockVolumeById(vp->hashid, vp->partition);
2735 V_attachFlags(vp) &= ~VOL_LOCKED;
2737 #endif /* AFS_DEMAND_ATTACH_FS */
2740 * read in a vol header, possibly lock the vol header, and possibly check out
2741 * the vol header from the fileserver, as part of volume attachment.
2743 * @param[out] ec error code
2744 * @param[in] vp volume pointer object
2745 * @param[in] partp disk partition object of the attaching partition
2746 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
2748 * @param[in] peek 1 to just try to read in the volume header and make sure
2749 * we don't try to lock the vol, or check it out from
2750 * FSSYNC or anything like that; 0 otherwise, for 'normal'
2752 * @param[out] acheckedOut If we successfully checked-out the volume from
2753 * the fileserver (if we needed to), this is set
2754 * to 1, otherwise it is untouched.
2756 * @note As part of DAFS volume attachment, the volume header may be either
2757 * read- or write-locked to ensure mutual exclusion of certain volume
2758 * operations. In some cases in order to determine whether we need to
2759 * read- or write-lock the header, we need to read in the header to see
2760 * if the volume is RW or not. So, if we read in the header under a
2761 * read-lock and determine that we actually need a write-lock on the
2762 * volume header, this function will drop the read lock, acquire a write
2763 * lock, and read the header in again.
2766 attach_volume_header(Error *ec, Volume *vp, struct DiskPartition64 *partp,
2767 int mode, int peek, int *acheckedOut)
2769 struct VolumeDiskHeader diskHeader;
2770 struct VolumeHeader header;
2773 int lock_tries = 0, checkout_tries = 0;
2775 VolumeId volid = vp->hashid;
2776 #ifdef FSSYNC_BUILD_CLIENT
2777 int checkout, done_checkout = 0;
2778 #endif /* FSSYNC_BUILD_CLIENT */
2779 #ifdef AFS_DEMAND_ATTACH_FS
2780 int locktype = 0, use_locktype = -1;
2781 #endif /* AFS_DEMAND_ATTACH_FS */
2787 if (lock_tries > VOL_MAX_CHECKOUT_RETRIES) {
2788 Log("VAttachVolume: retried too many times trying to lock header for "
2789 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2790 VPartitionPath(partp));
2794 if (checkout_tries > VOL_MAX_CHECKOUT_RETRIES) {
2795 Log("VAttachVolume: retried too many times trying to checkout "
2796 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2797 VPartitionPath(partp));
2802 if (VReadVolumeDiskHeader(volid, partp, NULL)) {
2803 /* short-circuit the 'volume does not exist' case */
2808 #ifdef FSSYNC_BUILD_CLIENT
2809 checkout = !done_checkout;
2811 if (!peek && checkout && VMustCheckoutVolume(mode)) {
2813 memset(&res, 0, sizeof(res));
2815 if (FSYNC_VolOp(volid, VPartitionPath(partp), FSYNC_VOL_NEEDVOLUME, mode, &res)
2818 if (res.hdr.reason == FSYNC_SALVAGE) {
2819 Log("VAttachVolume: file server says volume %lu is salvaging\n",
2820 afs_printable_uint32_lu(volid));
2823 Log("VAttachVolume: attach of volume %lu apparently denied by file server\n",
2824 afs_printable_uint32_lu(volid));
2825 *ec = VNOVOL; /* XXXX */
2833 #ifdef AFS_DEMAND_ATTACH_FS
2834 if (use_locktype < 0) {
2835 /* don't know whether vol is RO or RW; assume it's RO and we can retry
2836 * if it turns out to be RW */
2837 locktype = VVolLockType(mode, 0);
2840 /* a previous try says we should use use_locktype to lock the volume,
2842 locktype = use_locktype;
2845 if (!peek && locktype) {
2846 code = VLockVolumeNB(vp, locktype);
2848 if (code == EBUSY) {
2849 Log("VAttachVolume: another program has vol %lu locked\n",
2850 afs_printable_uint32_lu(volid));
2852 Log("VAttachVolume: error %d trying to lock vol %lu\n",
2853 code, afs_printable_uint32_lu(volid));
2860 #endif /* AFS_DEMAND_ATTACH_FS */
2862 code = VReadVolumeDiskHeader(volid, partp, &diskHeader);
2872 DiskToVolumeHeader(&header, &diskHeader);
2874 IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header.parent,
2875 header.largeVnodeIndex);
2876 IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header.parent,
2877 header.smallVnodeIndex);
2878 IH_INIT(vp->diskDataHandle, partp->device, header.parent,
2880 IH_INIT(vp->linkHandle, partp->device, header.parent, header.linkTable);
2883 /* only need to do this once */
2885 GetVolumeHeader(vp);
2889 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2890 /* demand attach changes the V_PEEK mechanism
2892 * we can now suck the current disk data structure over
2893 * the fssync interface without going to disk
2895 * (technically, we don't need to restrict this feature
2896 * to demand attach fileservers. However, I'm trying
2897 * to limit the number of common code changes)
2899 if (VCanUseFSSYNC() && (mode == V_PEEK || peek)) {
2901 res.payload.len = sizeof(VolumeDiskData);
2902 res.payload.buf = &vp->header->diskstuff;
2904 if (FSYNC_VolOp(vp->hashid,
2906 FSYNC_VOL_QUERY_HDR,
2909 goto disk_header_loaded;
2912 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2913 (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2914 sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2916 #ifdef AFS_DEMAND_ATTACH_FS
2919 IncUInt64(&VStats.hdr_loads);
2920 IncUInt64(&vp->stats.hdr_loads);
2922 #endif /* AFS_DEMAND_ATTACH_FS */
2925 Log("VAttachVolume: Error reading diskDataHandle header for vol %lu; "
2926 "error=%u\n", afs_printable_uint32_lu(volid), *ec);
2930 #ifdef AFS_DEMAND_ATTACH_FS
2931 # ifdef FSSYNC_BUILD_CLIENT
2933 # endif /* FSSYNC_BUILD_CLIENT */
2935 /* if the lock type we actually used to lock the volume is different than
2936 * the lock type we should have used, retry with the lock type we should
2938 use_locktype = VVolLockType(mode, VolumeWriteable(vp));
2939 if (locktype != use_locktype) {
2943 #endif /* AFS_DEMAND_ATTACH_FS */
2948 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2949 if (!peek && *ec == 0 && retry == 0 && VMustCheckoutVolume(mode)) {
2951 code = FSYNC_VerifyCheckout(volid, VPartitionPath(partp), FSYNC_VOL_NEEDVOLUME, mode);
2953 if (code == SYNC_DENIED) {
2954 /* must retry checkout; fileserver no longer thinks we have
2960 } else if (code != SYNC_OK) {
2964 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2967 /* either we are going to be called again for a second pass, or we
2968 * encountered an error; clean up in either case */
2970 #ifdef AFS_DEMAND_ATTACH_FS
2971 if ((V_attachFlags(vp) & VOL_LOCKED)) {
2974 #endif /* AFS_DEMAND_ATTACH_FS */
2975 if (vp->linkHandle) {
2976 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
2977 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
2978 IH_RELEASE(vp->diskDataHandle);
2979 IH_RELEASE(vp->linkHandle);
2992 #ifdef AFS_DEMAND_ATTACH_FS
2994 attach_check_vop(Error *ec, VolumeId volid, struct DiskPartition64 *partp,
2995 Volume *vp, int *acheckedOut)
2999 if (vp->pending_vol_op) {
3003 if (vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningUnknown) {
3005 code = VVolOpLeaveOnlineNoHeader_r(vp, vp->pending_vol_op);
3007 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3008 } else if (code == 0) {
3009 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3012 /* we need the vol header to determine if the volume can be
3013 * left online for the vop, so... get the header */
3017 /* attach header with peek=1 to avoid checking out the volume
3018 * or locking it; we just want the header info, we're not
3019 * messing with the volume itself at all */
3020 attach_volume_header(ec, vp, partp, V_PEEK, 1, acheckedOut);
3027 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
3028 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3030 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3033 /* make sure we grab a new vol header and re-open stuff on
3034 * actual attachment; we can't keep the data we grabbed, since
3035 * it was not done under a lock and thus not safe */
3036 FreeVolumeHeader(vp);
3037 VReleaseVolumeHandles_r(vp);
3040 /* see if the pending volume op requires exclusive access */
3041 switch (vp->pending_vol_op->vol_op_state) {
3042 case FSSYNC_VolOpPending:
3043 /* this should never happen */
3044 osi_Assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpPending);
3047 case FSSYNC_VolOpRunningUnknown:
3048 /* this should never happen; we resolved 'unknown' above */
3049 osi_Assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
3052 case FSSYNC_VolOpRunningOffline:
3053 /* mark the volume down */
3055 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3057 /* do not set V_offlineMessage here; we don't have ownership of
3058 * the volume (and probably do not have the header loaded), so we
3059 * can't alter the disk header */
3061 /* check to see if we should set the specialStatus flag */
3062 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
3063 vp->specialStatus = VBUSY;
3074 #endif /* AFS_DEMAND_ATTACH_FS */
3077 * volume attachment helper function.
3079 * @param[out] ec error code
3080 * @param[in] volumeId volume ID of the attaching volume
3081 * @param[in] path full path to the volume header .vol file
3082 * @param[in] partp disk partition object for the attaching partition
3083 * @param[in] vp volume object; vp->hashid, vp->device, vp->partition,
3084 * vp->vnode_list, vp->rx_call_list, and V_attachCV (for
3085 * DAFS) should already be initialized
3086 * @param[in] isbusy 1 if vp->specialStatus should be set to VBUSY; that is,
3087 * if there is a volume operation running for this volume
3088 * that should set the volume to VBUSY during its run. 0
3089 * otherwise. (see VVolOpSetVBusy_r)
3090 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
3092 * @param[out] acheckedOut If we successfully checked-out the volume from
3093 * the fileserver (if we needed to), this is set
3094 * to 1, otherwise it is 0.
3096 * @return pointer to the semi-attached volume pointer
3097 * @retval NULL an error occurred (check value of *ec)
3098 * @retval vp volume successfully attaching
3100 * @pre no locks held
3102 * @post VOL_LOCK held
3105 attach2(Error * ec, VolId volumeId, char *path, struct DiskPartition64 *partp,
3106 Volume * vp, int isbusy, int mode, int *acheckedOut)
3108 /* have we read in the header successfully? */
3109 int read_header = 0;
3111 #ifdef AFS_DEMAND_ATTACH_FS
3112 /* should we FreeVolume(vp) instead of VCheckFree(vp) in the error
3116 /* in the case of an error, to what state should the volume be
3118 VolState error_state = VOL_STATE_ERROR;
3119 #endif /* AFS_DEMAND_ATTACH_FS */
3123 vp->vnodeIndex[vLarge].handle = NULL;
3124 vp->vnodeIndex[vSmall].handle = NULL;
3125 vp->diskDataHandle = NULL;
3126 vp->linkHandle = NULL;
3130 #ifdef AFS_DEMAND_ATTACH_FS
3131 attach_check_vop(ec, volumeId, partp, vp, acheckedOut);
3133 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3136 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3137 #endif /* !AFS_DEMAND_ATTACH_FS */
3139 if (*ec == VNOVOL) {
3140 /* if the volume doesn't exist, skip straight to 'error' so we don't
3141 * request a salvage */
3142 goto unlocked_error;
3148 vp->specialStatus = (byte) (isbusy ? VBUSY : 0);
3149 vp->shuttingDown = 0;
3150 vp->goingOffline = 0;
3152 #ifdef AFS_DEMAND_ATTACH_FS
3153 vp->stats.last_attach = FT_ApproxTime();
3154 vp->stats.attaches++;
3158 IncUInt64(&VStats.attaches);
3159 vp->cacheCheck = ++VolumeCacheCheck;
3160 /* just in case this ever rolls over */
3161 if (!vp->cacheCheck)
3162 vp->cacheCheck = ++VolumeCacheCheck;
3165 #ifdef AFS_DEMAND_ATTACH_FS
3166 V_attachFlags(vp) |= VOL_HDR_LOADED;
3167 vp->stats.last_hdr_load = vp->stats.last_attach;
3168 #endif /* AFS_DEMAND_ATTACH_FS */
3172 struct IndexFileHeader iHead;
3174 #if OPENAFS_VOL_STATS
3176 * We just read in the diskstuff part of the header. If the detailed
3177 * volume stats area has not yet been initialized, we should bzero the
3178 * area and mark it as initialized.
3180 if (!(V_stat_initialized(vp))) {
3181 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
3182 V_stat_initialized(vp) = 1;
3184 #endif /* OPENAFS_VOL_STATS */
3186 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
3187 (char *)&iHead, sizeof(iHead),
3188 SMALLINDEXMAGIC, SMALLINDEXVERSION);
3191 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
3196 struct IndexFileHeader iHead;
3198 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
3199 (char *)&iHead, sizeof(iHead),
3200 LARGEINDEXMAGIC, LARGEINDEXVERSION);
3203 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
3207 #ifdef AFS_NAMEI_ENV
3209 struct versionStamp stamp;
3211 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
3212 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
3215 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
3218 #endif /* AFS_NAMEI_ENV */
3220 #if defined(AFS_DEMAND_ATTACH_FS)
3221 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
3223 if (!VCanScheduleSalvage()) {
3224 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3226 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER |
3227 VOL_SALVAGE_NO_OFFLINE);
3232 /* volume operation in progress */
3233 goto unlocked_error;
3235 #else /* AFS_DEMAND_ATTACH_FS */
3237 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3238 goto unlocked_error;
3240 #endif /* AFS_DEMAND_ATTACH_FS */
3242 if (V_needsSalvaged(vp)) {
3243 if (vp->specialStatus)
3244 vp->specialStatus = 0;
3246 #if defined(AFS_DEMAND_ATTACH_FS)
3247 if (!VCanScheduleSalvage()) {
3248 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
3250 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER |
3251 VOL_SALVAGE_NO_OFFLINE);
3254 #else /* AFS_DEMAND_ATTACH_FS */
3256 #endif /* AFS_DEMAND_ATTACH_FS */
3262 vp->nextVnodeUnique = V_uniquifier(vp);
3264 if (VShouldCheckInUse(mode) && V_inUse(vp) && VolumeWriteable(vp)) {
3265 if (!V_needsSalvaged(vp)) {
3266 V_needsSalvaged(vp) = 1;
3267 VUpdateVolume_r(ec, vp, 0);
3269 #if defined(AFS_DEMAND_ATTACH_FS)
3270 if (!VCanScheduleSalvage()) {
3271 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3273 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER |
3274 VOL_SALVAGE_NO_OFFLINE);
3277 #else /* AFS_DEMAND_ATTACH_FS */
3278 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3280 #endif /* AFS_DEMAND_ATTACH_FS */
3285 if (programType == fileServer && V_destroyMe(vp) == DESTROY_ME) {
3286 /* Only check destroyMe if we are the fileserver, since the
3287 * volserver et al sometimes need to work with volumes with
3288 * destroyMe set. Examples are 'temporary' volumes the
3289 * volserver creates, and when we create a volume (destroyMe
3290 * is set on creation; sometimes a separate volserver
3291 * transaction is created to clear destroyMe).
3294 #if defined(AFS_DEMAND_ATTACH_FS)
3295 /* schedule a salvage so the volume goes away on disk */
3296 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER |
3297 VOL_SALVAGE_NO_OFFLINE);
3298 VChangeState_r(vp, VOL_STATE_ERROR);
3301 #endif /* AFS_DEMAND_ATTACH_FS */
3302 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
3307 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
3308 #ifndef BITMAP_LATER
3309 if (programType == fileServer && VolumeWriteable(vp)) {
3311 for (i = 0; i < nVNODECLASSES; i++) {
3312 VGetBitmap_r(ec, vp, i);
3314 #ifdef AFS_DEMAND_ATTACH_FS
3315 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER |
3316 VOL_SALVAGE_NO_OFFLINE);
3318 #endif /* AFS_DEMAND_ATTACH_FS */
3319 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
3325 #endif /* BITMAP_LATER */
3327 if (VInit >= 2 && V_needsCallback(vp)) {
3328 if (V_BreakVolumeCallbacks) {
3329 Log("VAttachVolume: Volume %lu was changed externally; breaking callbacks\n",
3330 afs_printable_uint32_lu(V_id(vp)));
3331 V_needsCallback(vp) = 0;
3333 (*V_BreakVolumeCallbacks) (V_id(vp));
3336 VUpdateVolume_r(ec, vp, 0);
3338 #ifdef FSSYNC_BUILD_CLIENT
3339 else if (VCanUseFSSYNC()) {
3340 afs_int32 fsync_code;
3342 V_needsCallback(vp) = 0;
3344 fsync_code = FSYNC_VolOp(V_id(vp), NULL, FSYNC_VOL_BREAKCBKS, FSYNC_WHATEVER, NULL);
3348 V_needsCallback(vp) = 1;
3349 Log("Error trying to tell the fileserver to break callbacks for "
3350 "changed volume %lu; error code %ld\n",
3351 afs_printable_uint32_lu(V_id(vp)),
3352 afs_printable_int32_ld(fsync_code));
3354 VUpdateVolume_r(ec, vp, 0);
3357 #endif /* FSSYNC_BUILD_CLIENT */
3360 Log("VAttachVolume: error %d clearing needsCallback on volume "
3361 "%lu; needs salvage\n", (int)*ec,
3362 afs_printable_uint32_lu(V_id(vp)));
3363 #ifdef AFS_DEMAND_ATTACH_FS
3364 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER |
3365 VOL_SALVAGE_NO_OFFLINE);
3367 #else /* !AFS_DEMAND_ATTACH_FS */
3369 #endif /* !AFS_DEMAND_ATTACh_FS */
3374 if (programType == fileServer) {
3375 if (vp->specialStatus)
3376 vp->specialStatus = 0;
3377 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
3378 V_inUse(vp) = fileServer;
3379 V_offlineMessage(vp)[0] = '\0';
3383 #ifdef AFS_DEMAND_ATTACH_FS
3384 /* Put the vol into PREATTACHED state, so if someone tries to
3385 * access it again, we try to attach, see that we're not blessed,
3386 * and give a VNOVOL error again. Putting it into UNATTACHED state
3387 * would result in a VOFFLINE error instead. */
3388 error_state = VOL_STATE_PREATTACHED;
3389 #endif /* AFS_DEMAND_ATTACH_FS */
3391 /* mimic e.g. GetVolume errors */
3392 if (!V_blessed(vp)) {
3393 Log("Volume %lu offline: not blessed\n", afs_printable_uint32_lu(V_id(vp)));
3394 FreeVolumeHeader(vp);
3395 } else if (!V_inService(vp)) {
3396 Log("Volume %lu offline: not in service\n", afs_printable_uint32_lu(V_id(vp)));
3397 FreeVolumeHeader(vp);
3399 Log("Volume %lu offline: needs salvage\n", afs_printable_uint32_lu(V_id(vp)));
3401 #ifdef AFS_DEMAND_ATTACH_FS
3402 error_state = VOL_STATE_ERROR;
3403 /* see if we can recover */
3404 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
3407 #ifdef AFS_DEMAND_ATTACH_FS
3413 #ifdef AFS_DEMAND_ATTACH_FS
3414 if ((mode != V_PEEK) && (mode != V_SECRETLY))
3415 V_inUse(vp) = programType;
3416 #endif /* AFS_DEMAND_ATTACH_FS */
3417 V_checkoutMode(vp) = mode;
3420 AddVolumeToHashTable(vp, V_id(vp));
3421 #ifdef AFS_DEMAND_ATTACH_FS
3422 if (VCanUnlockAttached() && (V_attachFlags(vp) & VOL_LOCKED)) {
3425 if ((programType != fileServer) ||
3426 (V_inUse(vp) == fileServer)) {
3427 AddVolumeToVByPList_r(vp);
3429 VChangeState_r(vp, VOL_STATE_ATTACHED);
3431 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3440 #ifdef AFS_DEMAND_ATTACH_FS
3441 if (!VIsErrorState(V_attachState(vp))) {
3442 VChangeState_r(vp, error_state);
3444 #endif /* AFS_DEMAND_ATTACH_FS */
3447 VReleaseVolumeHandles_r(vp);
3450 #ifdef AFS_DEMAND_ATTACH_FS
3457 #else /* !AFS_DEMAND_ATTACH_FS */
3459 #endif /* !AFS_DEMAND_ATTACH_FS */
3463 /* Attach an existing volume.
3464 The volume also normally goes online at this time.
3465 An offline volume must be reattached to make it go online.
3469 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
3473 retVal = VAttachVolume_r(ec, volumeId, mode);
3479 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
3482 VGetVolumePath(ec, volumeId, &part, &name);
3486 vp = VGetVolume_r(&error, volumeId);
3488 osi_Assert(V_inUse(vp) == 0);
3489 VDetachVolume_r(ec, vp);
3493 return VAttachVolumeByName_r(ec, part, name, mode);
3496 /* Increment a reference count to a volume, sans context swaps. Requires
3497 * possibly reading the volume header in from the disk, since there's
3498 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
3500 * N.B. This call can fail if we can't read in the header!! In this case
3501 * we still guarantee we won't context swap, but the ref count won't be
3502 * incremented (otherwise we'd violate the invariant).
3504 /* NOTE: with the demand attach fileserver extensions, the global lock
3505 * is dropped within VHold */
3506 #ifdef AFS_DEMAND_ATTACH_FS
3508 VHold_r(Volume * vp)
3512 VCreateReservation_r(vp);
3513 VWaitExclusiveState_r(vp);
3515 LoadVolumeHeader(&error, vp);
3517 VCancelReservation_r(vp);
3521 VCancelReservation_r(vp);
3524 #else /* AFS_DEMAND_ATTACH_FS */
3526 VHold_r(Volume * vp)
3530 LoadVolumeHeader(&error, vp);
3536 #endif /* AFS_DEMAND_ATTACH_FS */
3538 /**** volume timeout-related stuff ****/
3540 #ifdef AFS_PTHREAD_ENV
3542 static struct timespec *shutdown_timeout;
3543 static pthread_once_t shutdown_timeout_once = PTHREAD_ONCE_INIT;
3546 VTimedOut(const struct timespec *ts)
3551 if (ts->tv_sec == 0) {
3552 /* short-circuit; this will have always timed out */
3556 code = gettimeofday(&tv, NULL);
3558 Log("Error %d from gettimeofday, assuming we have not timed out\n", errno);
3559 /* assume no timeout; failure mode is we just wait longer than normal
3560 * instead of returning errors when we shouldn't */
3564 if (tv.tv_sec < ts->tv_sec ||
3565 (tv.tv_sec == ts->tv_sec && tv.tv_usec*1000 < ts->tv_nsec)) {
3574 * Calculate an absolute timeout.
3576 * @param[out] ts A timeout that is "timeout" seconds from now, if we return
3577 * NULL, the memory is not touched
3578 * @param[in] timeout How long the timeout should be from now
3580 * @return timeout to use
3581 * @retval NULL no timeout; wait forever
3582 * @retval non-NULL the given value for "ts"
3586 static struct timespec *
3587 VCalcTimeout(struct timespec *ts, afs_int32 timeout)
3597 ts->tv_sec = ts->tv_nsec = 0;
3601 code = gettimeofday(&now, NULL);
3603 Log("Error %d from gettimeofday, falling back to 'forever' timeout\n", errno);
3607 ts->tv_sec = now.tv_sec + timeout;
3608 ts->tv_nsec = now.tv_usec * 1000;
3614 * Initialize the shutdown_timeout global.
3617 VShutdownTimeoutInit(void)
3619 struct timespec *ts;
3621 ts = malloc(sizeof(*ts));
3623 shutdown_timeout = VCalcTimeout(ts, vol_opts.offline_shutdown_timeout);
3625 if (!shutdown_timeout) {
3631 * Figure out the timeout that should be used for waiting for offline volumes.
3633 * @param[out] ats Storage space for a local timeout value if needed
3635 * @return The timeout value that should be used
3636 * @retval NULL No timeout; wait forever for offlining volumes
3637 * @retval non-NULL A pointer to the absolute time that should be used as
3638 * the deadline for waiting for offlining volumes.
3640 * @note If we return non-NULL, the pointer we return may or may not be the
3643 static const struct timespec *
3644 VOfflineTimeout(struct timespec *ats)
3646 if (vol_shutting_down) {
3647 osi_Assert(pthread_once(&shutdown_timeout_once, VShutdownTimeoutInit) == 0);
3648 return shutdown_timeout;
3650 return VCalcTimeout(ats, vol_opts.offline_timeout);
3654 #else /* AFS_PTHREAD_ENV */
3656 /* Waiting a certain amount of time for offlining volumes is not supported
3657 * for LWP due to a lack of primitives. So, we never time out */
3658 # define VTimedOut(x) (0)
3659 # define VOfflineTimeout(x) (NULL)
3661 #endif /* !AFS_PTHREAD_ENV */
3669 retVal = VHold_r(vp);
3676 VIsGoingOffline_r(struct Volume *vp)
3680 if (vp->goingOffline) {
3681 if (vp->specialStatus) {
3682 code = vp->specialStatus;
3683 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3694 * Tell the caller if a volume is waiting to go offline.
3696 * @param[in] vp The volume we want to know about
3698 * @return volume status
3699 * @retval 0 volume is not waiting to go offline, go ahead and use it
3700 * @retval nonzero volume is waiting to offline, and give the returned code
3701 * as an error to anyone accessing the volume
3703 * @pre VOL_LOCK is NOT held
3704 * @pre caller holds a heavyweight reference on vp
3707 VIsGoingOffline(struct Volume *vp)
3712 code = VIsGoingOffline_r(vp);
3719 * Register an RX call with a volume.
3721 * @param[inout] ec Error code; if unset when passed in, may be set if
3722 * the volume starts going offline
3723 * @param[out] client_ec @see GetVolume
3724 * @param[in] vp Volume struct
3725 * @param[in] cbv VCallByVol struct containing the RX call to register
3727 * @pre VOL_LOCK held
3728 * @pre caller holds heavy ref on vp
3733 VRegisterCall_r(Error *ec, Error *client_ec, Volume *vp, struct VCallByVol *cbv)
3736 #ifdef AFS_DEMAND_ATTACH_FS
3738 /* just in case the volume started going offline after we got the
3739 * reference to it... otherwise, if the volume started going
3740 * offline right at the end of GetVolume(), we might race with the
3741 * RX call scanner, and return success and add our cbv to the
3742 * rx_call_list _after_ the scanner has scanned the list. */
3743 *ec = VIsGoingOffline_r(vp);
3749 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3750 VWaitStateChange_r(vp);
3752 #endif /* AFS_DEMAND_ATTACH_FS */
3754 queue_Prepend(&vp->rx_call_list, cbv);
3759 * Deregister an RX call with a volume.
3761 * @param[in] vp Volume struct
3762 * @param[in] cbv VCallByVol struct containing the RX call to deregister
3764 * @pre VOL_LOCK held
3765 * @pre caller holds heavy ref on vp
3770 VDeregisterCall_r(Volume *vp, struct VCallByVol *cbv)
3772 if (cbv && queue_IsOnQueue(cbv)) {
3773 #ifdef AFS_DEMAND_ATTACH_FS
3774 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3775 VWaitStateChange_r(vp);
3777 #endif /* AFS_DEMAND_ATTACH_FS */
3783 /***************************************************/
3784 /* get and put volume routines */
3785 /***************************************************/
3788 * put back a heavyweight reference to a volume object.
3790 * @param[in] vp volume object pointer
3792 * @pre VOL_LOCK held
3794 * @post heavyweight volume reference put back.
3795 * depending on state, volume may have been taken offline,
3796 * detached, salvaged, freed, etc.
3798 * @internal volume package internal use only
3801 VPutVolume_r(Volume * vp)
3803 osi_Assert(--vp->nUsers >= 0);
3804 if (vp->nUsers == 0) {
3806 ReleaseVolumeHeader(vp->header);
3807 #ifdef AFS_DEMAND_ATTACH_FS
3808 if (!VCheckDetach(vp)) {
3812 #else /* AFS_DEMAND_ATTACH_FS */
3814 #endif /* AFS_DEMAND_ATTACH_FS */
3819 VPutVolume(Volume * vp)
3827 * Puts a volume reference obtained with VGetVolumeWithCall.
3829 * @param[in] vp Volume struct
3830 * @param[in] cbv VCallByVol struct given to VGetVolumeWithCall, or NULL if none
3832 * @pre VOL_LOCK is NOT held
3835 VPutVolumeWithCall(Volume *vp, struct VCallByVol *cbv)
3838 VDeregisterCall_r(vp, cbv);
3843 /* Get a pointer to an attached volume. The pointer is returned regardless
3844 of whether or not the volume is in service or on/off line. An error
3845 code, however, is returned with an indication of the volume's status */
3847 VGetVolume(Error * ec, Error * client_ec, VolId volumeId)
3851 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
3857 * Get a volume reference associated with an RX call.
3859 * @param[out] ec @see GetVolume
3860 * @param[out] client_ec @see GetVolume
3861 * @param[in] volumeId @see GetVolume
3862 * @param[in] ts How long to wait for going-offline volumes (absolute time).
3863 * If NULL, wait forever. If ts->tv_sec == 0, return immediately
3864 * with an error if the volume is going offline.
3865 * @param[in] cbv Contains an RX call to be associated with this volume
3866 * reference. This call may be interrupted if the volume is
3867 * requested to go offline while we hold a ref on it. Give NULL
3868 * to not associate an RX call with this reference.
3870 * @return @see GetVolume
3872 * @note for LWP builds, ts must be NULL
3874 * @note A reference obtained with this function MUST be put back with
3875 * VPutVolumeWithCall
3878 VGetVolumeWithCall(Error * ec, Error * client_ec, VolId volumeId,
3879 const struct timespec *ts, struct VCallByVol *cbv)
3883 retVal = GetVolume(ec, client_ec, volumeId, NULL, ts);
3884 VRegisterCall_r(ec, client_ec, retVal, cbv);
3890 VGetVolume_r(Error * ec, VolId volumeId)
3892 return GetVolume(ec, NULL, volumeId, NULL, NULL);
3895 /* try to get a volume we've previously looked up */
3896 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
3898 VGetVolumeByVp_r(Error * ec, Volume * vp)
3900 return GetVolume(ec, NULL, vp->hashid, vp, NULL);
3904 * private interface for getting a volume handle
3906 * @param[out] ec error code (0 if no error)
3907 * @param[out] client_ec wire error code to be given to clients
3908 * @param[in] volumeId ID of the volume we want
3909 * @param[in] hint optional hint for hash lookups, or NULL
3910 * @param[in] timeout absolute deadline for waiting for the volume to go
3911 * offline, if it is going offline. NULL to wait forever.
3913 * @return a volume handle for the specified volume
3914 * @retval NULL an error occurred, or the volume is in such a state that
3915 * we cannot load a header or return any volume struct
3917 * @note for DAFS, caller must NOT hold a ref count on 'hint'
3919 * @note 'timeout' is only checked if the volume is actually going offline; so
3920 * if you pass timeout->tv_sec = 0, this will exhibit typical
3921 * nonblocking behavior.
3923 * @note for LWP builds, 'timeout' must be NULL
3926 GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint,
3927 const struct timespec *timeout)
3930 /* pull this profiling/debugging code out of regular builds */
3932 #define VGET_CTR_INC(x) x++
3933 unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
3934 0, V7 = 0, V8 = 0, V9 = 0;
3935 unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
3937 #define VGET_CTR_INC(x)
3939 #ifdef AFS_DEMAND_ATTACH_FS
3940 Volume *avp, * rvp = hint;
3944 * if VInit is zero, the volume package dynamic
3945 * data structures have not been initialized yet,
3946 * and we must immediately return an error
3952 *client_ec = VOFFLINE;
3957 #ifdef AFS_DEMAND_ATTACH_FS
3959 VCreateReservation_r(rvp);
3961 #endif /* AFS_DEMAND_ATTACH_FS */
3969 vp = VLookupVolume_r(ec, volumeId, vp);
3975 #ifdef AFS_DEMAND_ATTACH_FS
3976 if (rvp && (rvp != vp)) {
3977 /* break reservation on old vp */
3978 VCancelReservation_r(rvp);
3981 #endif /* AFS_DEMAND_ATTACH_FS */
3987 /* Until we have reached an initialization level of 2
3988 * we don't know whether this volume exists or not.
3989 * We can't sleep and retry later because before a volume
3990 * is attached, the caller tries to get it first. Just
3991 * return VOFFLINE and the caller can choose whether to
3992 * retry the command or not. */
4002 IncUInt64(&VStats.hdr_gets);
4004 #ifdef AFS_DEMAND_ATTACH_FS
4005 /* block if someone else is performing an exclusive op on this volume */
4008 VCreateReservation_r(rvp);
4010 VWaitExclusiveState_r(vp);
4012 /* short circuit with VNOVOL in the following circumstances:
4015 * - VOL_STATE_SHUTTING_DOWN
4017 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
4018 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN) ||
4019 (V_attachState(vp) == VOL_STATE_GOING_OFFLINE)) {
4026 * short circuit with VOFFLINE for VOL_STATE_UNATTACHED and
4027 * VNOVOL for VOL_STATE_DELETED
4029 if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
4030 (V_attachState(vp) == VOL_STATE_DELETED)) {
4031 if (vp->specialStatus) {
4032 *ec = vp->specialStatus;
4033 } else if (V_attachState(vp) == VOL_STATE_DELETED) {
4042 /* allowable states:
4049 if (vp->salvage.requested) {
4050 VUpdateSalvagePriority_r(vp);
4053 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
4054 avp = VAttachVolumeByVp_r(ec, vp, 0);
4057 /* VAttachVolumeByVp_r can return a pointer
4058 * != the vp passed to it under certain
4059 * conditions; make sure we don't leak
4060 * reservations if that happens */
4062 VCancelReservation_r(rvp);
4064 VCreateReservation_r(rvp);
4074 if (!vp->pending_vol_op) {
4089 if (VIsSalvaging(vp) || (*ec == VSALVAGING)) {
4091 /* see CheckVnode() in afsfileprocs.c for an explanation
4092 * of this error code logic */
4093 afs_uint32 now = FT_ApproxTime();
4094 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
4097 *client_ec = VRESTARTING;
4106 #ifdef AFS_DEMAND_ATTACH_FS
4108 * this test MUST happen after VAttachVolymeByVp, so vol_op_state is
4109 * not VolOpRunningUnknown (attach2 would have converted it to Online
4113 /* only valid before/during demand attachment */
4114 osi_Assert(!vp->pending_vol_op || vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
4116 /* deny getvolume due to running mutually exclusive vol op */
4117 if (vp->pending_vol_op && vp->pending_vol_op->vol_op_state==FSSYNC_VolOpRunningOffline) {
4119 * volume cannot remain online during this volume operation.
4122 if (vp->specialStatus) {
4124 * special status codes outrank normal VOFFLINE code
4126 *ec = vp->specialStatus;
4128 *client_ec = vp->specialStatus;
4132 /* see CheckVnode() in afsfileprocs.c for an explanation
4133 * of this error code logic */
4134 afs_uint32 now = FT_ApproxTime();
4135 if ((vp->stats.last_vol_op + (10 * 60)) >= now) {
4138 *client_ec = VRESTARTING;
4143 VChangeState_r(vp, VOL_STATE_UNATTACHED);
4144 FreeVolumeHeader(vp);
4148 #endif /* AFS_DEMAND_ATTACH_FS */
4150 LoadVolumeHeader(ec, vp);
4153 /* Only log the error if it was a totally unexpected error. Simply
4154 * a missing inode is likely to be caused by the volume being deleted */
4155 if (errno != ENXIO || LogLevel)
4156 Log("Volume %u: couldn't reread volume header\n",
4158 #ifdef AFS_DEMAND_ATTACH_FS
4159 if (VCanScheduleSalvage()) {
4160 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
4165 #else /* AFS_DEMAND_ATTACH_FS */
4168 #endif /* AFS_DEMAND_ATTACH_FS */
4173 if (vp->shuttingDown) {
4180 if (programType == fileServer) {
4182 if (vp->goingOffline) {
4183 if (timeout && VTimedOut(timeout)) {
4184 /* we've timed out; don't wait for the vol */
4187 #ifdef AFS_DEMAND_ATTACH_FS
4188 /* wait for the volume to go offline */
4189 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
4190 VTimedWaitStateChange_r(vp, timeout, NULL);
4192 #elif defined(AFS_PTHREAD_ENV)
4193 VOL_CV_TIMEDWAIT(&vol_put_volume_cond, timeout, NULL);
4194 #else /* AFS_PTHREAD_ENV */
4195 /* LWP has no timed wait, so the caller better not be
4197 osi_Assert(!timeout);
4198 LWP_WaitProcess(VPutVolume);
4199 #endif /* AFS_PTHREAD_ENV */
4203 if (vp->specialStatus) {
4205 *ec = vp->specialStatus;
4206 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
4209 } else if (V_inUse(vp) == 0 || vp->goingOffline) {
4220 #ifdef AFS_DEMAND_ATTACH_FS
4221 /* if no error, bump nUsers */
4224 VLRU_UpdateAccess_r(vp);
4227 VCancelReservation_r(rvp);
4230 if (client_ec && !*client_ec) {
4233 #else /* AFS_DEMAND_ATTACH_FS */
4234 /* if no error, bump nUsers */
4241 #endif /* AFS_DEMAND_ATTACH_FS */
4244 osi_Assert(vp || *ec);
4249 /***************************************************/
4250 /* Volume offline/detach routines */
4251 /***************************************************/
4253 /* caller MUST hold a heavyweight ref on vp */
4254 #ifdef AFS_DEMAND_ATTACH_FS
4256 VTakeOffline_r(Volume * vp)
4260 osi_Assert(vp->nUsers > 0);
4261 osi_Assert(programType == fileServer);
4263 VCreateReservation_r(vp);
4264 VWaitExclusiveState_r(vp);
4266 vp->goingOffline = 1;
4267 V_needsSalvaged(vp) = 1;
4269 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
4270 VCancelReservation_r(vp);
4272 #else /* AFS_DEMAND_ATTACH_FS */
4274 VTakeOffline_r(Volume * vp)
4276 osi_Assert(vp->nUsers > 0);
4277 osi_Assert(programType == fileServer);
4279 vp->goingOffline = 1;
4280 V_needsSalvaged(vp) = 1;
4282 #endif /* AFS_DEMAND_ATTACH_FS */
4285 VTakeOffline(Volume * vp)
4293 * force a volume offline.
4295 * @param[in] vp volume object pointer
4296 * @param[in] flags flags (see note below)
4298 * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
4299 * used when VUpdateVolume_r needs to call VForceOffline_r
4300 * (which in turn would normally call VUpdateVolume_r)
4302 * @see VUpdateVolume_r
4304 * @pre VOL_LOCK must be held.
4305 * for DAFS, caller must hold ref.
4307 * @note for DAFS, it _is safe_ to call this function from an
4310 * @post needsSalvaged flag is set.
4311 * for DAFS, salvage is requested.
4312 * no further references to the volume through the volume
4313 * package will be honored.
4314 * all file descriptor and vnode caches are invalidated.
4316 * @warning this is a heavy-handed interface. it results in
4317 * a volume going offline regardless of the current
4318 * reference count state.
4320 * @internal volume package internal use only
4323 VForceOffline_r(Volume * vp, int flags)
4327 #ifdef AFS_DEMAND_ATTACH_FS
4328 VChangeState_r(vp, VOL_STATE_ERROR);
4333 strcpy(V_offlineMessage(vp),
4334 "Forced offline due to internal error: volume needs to be salvaged");
4335 Log("Volume %u forced offline: it needs salvaging!\n", V_id(vp));
4338 vp->goingOffline = 0;
4339 V_needsSalvaged(vp) = 1;
4340 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
4341 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
4344 #ifdef AFS_DEMAND_ATTACH_FS
4345 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
4346 #endif /* AFS_DEMAND_ATTACH_FS */
4348 #ifdef AFS_PTHREAD_ENV
4349 CV_BROADCAST(&vol_put_volume_cond);
4350 #else /* AFS_PTHREAD_ENV */
4351 LWP_NoYieldSignal(VPutVolume);
4352 #endif /* AFS_PTHREAD_ENV */
4354 VReleaseVolumeHandles_r(vp);
4358 * force a volume offline.
4360 * @param[in] vp volume object pointer
4362 * @see VForceOffline_r
4365 VForceOffline(Volume * vp)
4368 VForceOffline_r(vp, 0);
4373 * Iterate over the RX calls associated with a volume, and interrupt them.
4375 * @param[in] vp The volume whose RX calls we want to scan
4377 * @pre VOL_LOCK held
4380 VScanCalls_r(struct Volume *vp)
4382 struct VCallByVol *cbv, *ncbv;
4384 #ifdef AFS_DEMAND_ATTACH_FS
4385 VolState state_save;
4388 if (queue_IsEmpty(&vp->rx_call_list))
4389 return; /* no calls to interrupt */
4390 if (!vol_opts.interrupt_rxcall)
4391 return; /* we have no function with which to interrupt calls */
4392 err = VIsGoingOffline_r(vp);
4394 return; /* we're not going offline anymore */
4396 #ifdef AFS_DEMAND_ATTACH_FS
4397 VWaitExclusiveState_r(vp);
4398 state_save = VChangeState_r(vp, VOL_STATE_SCANNING_RXCALLS);
4400 #endif /* AFS_DEMAND_ATTACH_FS */
4402 for(queue_Scan(&vp->rx_call_list, cbv, ncbv, VCallByVol)) {
4404 struct rx_peer *peer;
4406 peer = rx_PeerOf(rx_ConnectionOf(cbv->call));
4408 Log("Offlining volume %lu while client %s:%u is trying to read "
4409 "from it; kicking client off with error %ld\n",
4410 (long unsigned) vp->hashid,
4411 afs_inet_ntoa_r(rx_HostOf(peer), hoststr),
4412 (unsigned) ntohs(rx_PortOf(peer)),
4415 (*vol_opts.interrupt_rxcall) (cbv->call, err);
4418 #ifdef AFS_DEMAND_ATTACH_FS
4420 VChangeState_r(vp, state_save);
4421 #endif /* AFS_DEMAND_ATTACH_FS */
4424 #ifdef AFS_DEMAND_ATTACH_FS
4426 * Wait for a vp to go offline.
4428 * @param[out] ec 1 if a salvage on the volume has been requested and
4429 * salvok == 0, 0 otherwise
4430 * @param[in] vp The volume to wait for
4431 * @param[in] salvok If 0, we return immediately with *ec = 1 if the volume
4432 * has been requested to salvage. Otherwise we keep waiting
4433 * until the volume has gone offline.
4435 * @pre VOL_LOCK held
4436 * @pre caller holds a lightweight ref on vp
4441 VWaitForOfflineByVp_r(Error *ec, struct Volume *vp, int salvok)
4443 struct timespec timeout_ts;
4444 const struct timespec *ts;
4447 ts = VOfflineTimeout(&timeout_ts);
4451 while (!VIsOfflineState(V_attachState(vp)) && !timedout) {
4452 if (!salvok && vp->salvage.requested) {
4456 VTimedWaitStateChange_r(vp, ts, &timedout);
4459 /* we didn't time out, so the volume must be offline, so we're done */
4463 /* If we got here, we timed out waiting for the volume to go offline.
4464 * Kick off the accessing RX calls and wait again */
4468 while (!VIsOfflineState(V_attachState(vp))) {
4469 if (!salvok && vp->salvage.requested) {
4474 VWaitStateChange_r(vp);
4478 #else /* AFS_DEMAND_ATTACH_FS */
4481 * Wait for a volume to go offline.
4483 * @pre VOL_LOCK held
4485 * @note non-DAFS only (for DAFS, use @see WaitForOfflineByVp_r)
4488 VWaitForOffline_r(Error *ec, VolumeId volid)
4491 const struct timespec *ts;
4492 #ifdef AFS_PTHREAD_ENV
4493 struct timespec timeout_ts;
4496 ts = VOfflineTimeout(&timeout_ts);
4498 vp = GetVolume(ec, NULL, volid, NULL, ts);
4500 /* error occurred so bad that we can't even get a vp; we have no
4501 * information on the vol so we don't know whether to wait, so just
4505 if (!VIsGoingOffline_r(vp)) {
4506 /* volume is no longer going offline, so we're done */
4511 /* If we got here, we timed out waiting for the volume to go offline.
4512 * Kick off the accessing RX calls and wait again */
4518 vp = VGetVolume_r(ec, volid);
4520 /* In case it was reattached... */
4524 #endif /* !AFS_DEMAND_ATTACH_FS */
4526 /* The opposite of VAttachVolume. The volume header is written to disk, with
4527 the inUse bit turned off. A copy of the header is maintained in memory,
4528 however (which is why this is VOffline, not VDetach).
4531 VOffline_r(Volume * vp, char *message)
4534 #ifndef AFS_DEMAND_ATTACH_FS
4535 VolumeId vid = V_id(vp);
4538 osi_Assert(programType != volumeUtility && programType != volumeServer);
4543 if (V_offlineMessage(vp)[0] == '\0')
4544 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4545 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4547 vp->goingOffline = 1;
4548 #ifdef AFS_DEMAND_ATTACH_FS
4549 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4550 VCreateReservation_r(vp);
4552 VWaitForOfflineByVp_r(&error, vp, 1);
4553 VCancelReservation_r(vp);
4554 #else /* AFS_DEMAND_ATTACH_FS */
4556 VWaitForOffline_r(&error, vid);
4557 #endif /* AFS_DEMAND_ATTACH_FS */
4560 #ifdef AFS_DEMAND_ATTACH_FS
4562 * Take a volume offline in order to perform a volume operation.
4564 * @param[inout] ec address in which to store error code
4565 * @param[in] vp volume object pointer
4566 * @param[in] message volume offline status message
4569 * - VOL_LOCK is held
4570 * - caller MUST hold a heavyweight ref on vp
4573 * - volume is taken offline
4574 * - if possible, volume operation is promoted to running state
4575 * - on failure, *ec is set to nonzero
4577 * @note Although this function does not return any value, it may
4578 * still fail to promote our pending volume operation to
4579 * a running state. Any caller MUST check the value of *ec,
4580 * and MUST NOT blindly assume success.
4582 * @warning if the caller does not hold a lightweight ref on vp,
4583 * then it MUST NOT reference vp after this function
4584 * returns to the caller.
4586 * @internal volume package internal use only
4589 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
4592 osi_Assert(vp->pending_vol_op);
4598 if (V_offlineMessage(vp)[0] == '\0')
4599 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4600 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4602 vp->goingOffline = 1;
4603 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4604 VCreateReservation_r(vp);
4607 if (vp->pending_vol_op->com.programType != salvageServer) {
4608 /* do not give corrupted volumes to the volserver */
4613 VWaitForOfflineByVp_r(ec, vp, salvok);
4615 VCancelReservation_r(vp);
4617 #endif /* AFS_DEMAND_ATTACH_FS */
4620 VOffline(Volume * vp, char *message)
4623 VOffline_r(vp, message);
4627 /* This gets used for the most part by utility routines that don't want
4628 * to keep all the volume headers around. Generally, the file server won't
4629 * call this routine, because then the offline message in the volume header
4630 * (or other information) won't be available to clients. For NAMEI, also
4631 * close the file handles. However, the fileserver does call this during
4632 * an attach following a volume operation.
4635 VDetachVolume_r(Error * ec, Volume * vp)
4637 #ifdef FSSYNC_BUILD_CLIENT
4639 struct DiskPartition64 *tpartp;
4640 int notifyServer = 0;
4641 int useDone = FSYNC_VOL_ON;
4643 if (VCanUseFSSYNC()) {
4644 notifyServer = vp->needsPutBack;
4645 if (V_destroyMe(vp) == DESTROY_ME)
4646 useDone = FSYNC_VOL_LEAVE_OFF;
4647 #ifdef AFS_DEMAND_ATTACH_FS
4648 else if (!V_blessed(vp) || !V_inService(vp))
4649 useDone = FSYNC_VOL_LEAVE_OFF;
4652 tpartp = vp->partition;
4654 #endif /* FSSYNC_BUILD_CLIENT */
4656 *ec = 0; /* always "succeeds" */
4657 DeleteVolumeFromHashTable(vp);
4658 vp->shuttingDown = 1;
4659 #ifdef AFS_DEMAND_ATTACH_FS
4660 DeleteVolumeFromVByPList_r(vp);
4662 VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
4664 if (programType != fileServer)
4666 #endif /* AFS_DEMAND_ATTACH_FS */
4668 /* Will be detached sometime in the future--this is OK since volume is offline */
4670 /* XXX the following code should really be moved to VCheckDetach() since the volume
4671 * is not technically detached until the refcounts reach zero
4673 #ifdef FSSYNC_BUILD_CLIENT
4674 if (VCanUseFSSYNC() && notifyServer) {
4675 if (notifyServer == VOL_PUTBACK_DELETE) {
4676 /* Only send FSYNC_VOL_DONE if the volume was actually deleted.
4677 * volserver code will set needsPutBack to VOL_PUTBACK_DELETE
4678 * to signify a deleted volume. */
4679 useDone = FSYNC_VOL_DONE;
4682 * Note: The server is not notified in the case of a bogus volume
4683 * explicitly to make it possible to create a volume, do a partial
4684 * restore, then abort the operation without ever putting the volume
4685 * online. This is essential in the case of a volume move operation
4686 * between two partitions on the same server. In that case, there
4687 * would be two instances of the same volume, one of them bogus,
4688 * which the file server would attempt to put on line
4690 FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
4691 /* XXX this code path is only hit by volume utilities, thus
4692 * V_BreakVolumeCallbacks will always be NULL. if we really
4693 * want to break callbacks in this path we need to use FSYNC_VolOp() */
4695 /* Dettaching it so break all callbacks on it */
4696 if (V_BreakVolumeCallbacks) {
4697 Log("volume %u detached; breaking all call backs\n", volume);
4698 (*V_BreakVolumeCallbacks) (volume);
4702 #endif /* FSSYNC_BUILD_CLIENT */
4706 VDetachVolume(Error * ec, Volume * vp)
4709 VDetachVolume_r(ec, vp);
4714 /***************************************************/
4715 /* Volume fd/inode handle closing routines */
4716 /***************************************************/
4718 /* For VDetachVolume, we close all cached file descriptors, but keep
4719 * the Inode handles in case we need to read from a busy volume.
4721 /* for demand attach, caller MUST hold ref count on vp */
4723 VCloseVolumeHandles_r(Volume * vp)
4725 #ifdef AFS_DEMAND_ATTACH_FS
4726 VolState state_save;
4728 state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
4733 * XXX need to investigate whether we can perform
4734 * DFlushVolume outside of vol_glock_mutex...
4736 * VCloseVnodeFiles_r drops the glock internally */
4737 DFlushVolume(vp->hashid);
4738 VCloseVnodeFiles_r(vp);
4740 #ifdef AFS_DEMAND_ATTACH_FS
4744 /* Too time consuming and unnecessary for the volserver */
4745 if (programType == fileServer) {
4746 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4747 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4748 IH_CONDSYNC(vp->diskDataHandle);
4750 IH_CONDSYNC(vp->linkHandle);
4751 #endif /* AFS_NT40_ENV */
4754 IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
4755 IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
4756 IH_REALLYCLOSE(vp->diskDataHandle);
4757 IH_REALLYCLOSE(vp->linkHandle);
4759 #ifdef AFS_DEMAND_ATTACH_FS
4760 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4765 VChangeState_r(vp, state_save);
4769 /* For both VForceOffline and VOffline, we close all relevant handles.
4770 * For VOffline, if we re-attach the volume, the files may possible be
4771 * different than before.
4773 /* for demand attach, caller MUST hold a ref count on vp */
4775 VReleaseVolumeHandles_r(Volume * vp)
4777 #ifdef AFS_DEMAND_ATTACH_FS
4778 VolState state_save;
4780 state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
4783 /* XXX need to investigate whether we can perform
4784 * DFlushVolume outside of vol_glock_mutex... */
4785 DFlushVolume(vp->hashid);
4787 VReleaseVnodeFiles_r(vp); /* releases the glock internally */
4789 #ifdef AFS_DEMAND_ATTACH_FS
4793 /* Too time consuming and unnecessary for the volserver */
4794 if (programType == fileServer) {
4795 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4796 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4797 IH_CONDSYNC(vp->diskDataHandle);
4799 IH_CONDSYNC(vp->linkHandle);
4800 #endif /* AFS_NT40_ENV */
4803 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
4804 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
4805 IH_RELEASE(vp->diskDataHandle);
4806 IH_RELEASE(vp->linkHandle);
4808 #ifdef AFS_DEMAND_ATTACH_FS
4809 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4814 VChangeState_r(vp, state_save);
4819 /***************************************************/
4820 /* Volume write and fsync routines */
4821 /***************************************************/
4824 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
4826 #ifdef AFS_DEMAND_ATTACH_FS
4827 VolState state_save;
4829 if (flags & VOL_UPDATE_WAIT) {
4830 VCreateReservation_r(vp);
4831 VWaitExclusiveState_r(vp);
4836 if (programType == fileServer)
4838 (V_inUse(vp) ? V_nextVnodeUnique(vp) +
4839 200 : V_nextVnodeUnique(vp));
4841 #ifdef AFS_DEMAND_ATTACH_FS
4842 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4846 WriteVolumeHeader_r(ec, vp);
4848 #ifdef AFS_DEMAND_ATTACH_FS
4850 VChangeState_r(vp, state_save);
4851 if (flags & VOL_UPDATE_WAIT) {
4852 VCancelReservation_r(vp);
4857 Log("VUpdateVolume: error updating volume header, volume %u (%s)\n",
4858 V_id(vp), V_name(vp));
4859 /* try to update on-disk header,
4860 * while preventing infinite recursion */
4861 if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
4862 VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
4868 VUpdateVolume(Error * ec, Volume * vp)
4871 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4876 VSyncVolume_r(Error * ec, Volume * vp, int flags)
4880 #ifdef AFS_DEMAND_ATTACH_FS
4881 VolState state_save;
4884 if (flags & VOL_SYNC_WAIT) {
4885 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4887 VUpdateVolume_r(ec, vp, 0);
4890 #ifdef AFS_DEMAND_ATTACH_FS
4891 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4894 fdP = IH_OPEN(V_diskDataHandle(vp));
4895 osi_Assert(fdP != NULL);
4896 code = FDH_SYNC(fdP);
4897 osi_Assert(code == 0);
4899 #ifdef AFS_DEMAND_ATTACH_FS
4901 VChangeState_r(vp, state_save);
4907 VSyncVolume(Error * ec, Volume * vp)
4910 VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
4915 /***************************************************/
4916 /* Volume dealloaction routines */
4917 /***************************************************/
4919 #ifdef AFS_DEMAND_ATTACH_FS
4921 FreeVolume(Volume * vp)
4923 /* free the heap space, iff it's safe.
4924 * otherwise, pull it out of the hash table, so it
4925 * will get deallocated when all refs to it go away */
4926 if (!VCheckFree(vp)) {
4927 DeleteVolumeFromHashTable(vp);
4928 DeleteVolumeFromVByPList_r(vp);
4930 /* make sure we invalidate the header cache entry */
4931 FreeVolumeHeader(vp);
4934 #endif /* AFS_DEMAND_ATTACH_FS */
4937 ReallyFreeVolume(Volume * vp)
4942 #ifdef AFS_DEMAND_ATTACH_FS
4944 VChangeState_r(vp, VOL_STATE_FREED);
4945 if (vp->pending_vol_op)
4946 free(vp->pending_vol_op);
4947 #endif /* AFS_DEMAND_ATTACH_FS */
4948 for (i = 0; i < nVNODECLASSES; i++)
4949 if (vp->vnodeIndex[i].bitmap)
4950 free(vp->vnodeIndex[i].bitmap);
4951 FreeVolumeHeader(vp);
4952 #ifndef AFS_DEMAND_ATTACH_FS
4953 DeleteVolumeFromHashTable(vp);
4954 #endif /* AFS_DEMAND_ATTACH_FS */
4958 /* check to see if we should shutdown this volume
4959 * returns 1 if volume was freed, 0 otherwise */
4960 #ifdef AFS_DEMAND_ATTACH_FS
4962 VCheckDetach(Volume * vp)
4967 if (vp->nUsers || vp->nWaiters)
4970 if (vp->shuttingDown) {
4972 if ((programType != fileServer) &&
4973 (V_inUse(vp) == programType) &&
4974 ((V_checkoutMode(vp) == V_VOLUPD) ||
4975 (V_checkoutMode(vp) == V_SECRETLY) ||
4976 ((V_checkoutMode(vp) == V_CLONE) &&
4977 (VolumeWriteable(vp))))) {
4979 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
4981 Log("VCheckDetach: volume header update for volume %u "
4982 "failed with errno %d\n", vp->hashid, errno);
4985 VReleaseVolumeHandles_r(vp);
4987 ReallyFreeVolume(vp);
4988 if (programType == fileServer) {
4989 CV_BROADCAST(&vol_put_volume_cond);
4994 #else /* AFS_DEMAND_ATTACH_FS */
4996 VCheckDetach(Volume * vp)
5004 if (vp->shuttingDown) {
5006 if ((programType != fileServer) &&
5007 (V_inUse(vp) == programType) &&
5008 ((V_checkoutMode(vp) == V_VOLUPD) ||
5009 (V_checkoutMode(vp) == V_SECRETLY) ||
5010 ((V_checkoutMode(vp) == V_CLONE) &&
5011 (VolumeWriteable(vp))))) {
5013 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5015 Log("VCheckDetach: volume header update for volume %u failed with errno %d\n",
5019 VReleaseVolumeHandles_r(vp);
5020 ReallyFreeVolume(vp);
5021 if (programType == fileServer) {
5022 #if defined(AFS_PTHREAD_ENV)
5023 CV_BROADCAST(&vol_put_volume_cond);
5024 #else /* AFS_PTHREAD_ENV */
5025 LWP_NoYieldSignal(VPutVolume);
5026 #endif /* AFS_PTHREAD_ENV */
5031 #endif /* AFS_DEMAND_ATTACH_FS */
5033 /* check to see if we should offline this volume
5034 * return 1 if volume went offline, 0 otherwise */
5035 #ifdef AFS_DEMAND_ATTACH_FS
5037 VCheckOffline(Volume * vp)
5041 if (vp->goingOffline && !vp->nUsers) {
5043 osi_Assert(programType == fileServer);
5044 osi_Assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
5045 (V_attachState(vp) != VOL_STATE_FREED) &&
5046 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
5047 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
5048 (V_attachState(vp) != VOL_STATE_DELETED));
5052 * VOL_STATE_GOING_OFFLINE
5053 * VOL_STATE_SHUTTING_DOWN
5054 * VIsErrorState(V_attachState(vp))
5055 * VIsExclusiveState(V_attachState(vp))
5058 VCreateReservation_r(vp);
5059 VChangeState_r(vp, VOL_STATE_OFFLINING);
5062 /* must clear the goingOffline flag before we drop the glock */
5063 vp->goingOffline = 0;
5068 /* perform async operations */
5069 VUpdateVolume_r(&error, vp, 0);
5070 VCloseVolumeHandles_r(vp);
5073 if (V_offlineMessage(vp)[0]) {
5074 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5075 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5076 V_offlineMessage(vp));
5078 Log("VOffline: Volume %lu (%s) is now offline\n",
5079 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5083 /* invalidate the volume header cache entry */
5084 FreeVolumeHeader(vp);
5086 /* if nothing changed state to error or salvaging,
5087 * drop state to unattached */
5088 if (!VIsErrorState(V_attachState(vp))) {
5089 VChangeState_r(vp, VOL_STATE_UNATTACHED);
5091 VCancelReservation_r(vp);
5092 /* no usage of vp is safe beyond this point */
5096 #else /* AFS_DEMAND_ATTACH_FS */
5098 VCheckOffline(Volume * vp)
5102 if (vp->goingOffline && !vp->nUsers) {
5104 osi_Assert(programType == fileServer);
5107 vp->goingOffline = 0;
5109 VUpdateVolume_r(&error, vp, 0);
5110 VCloseVolumeHandles_r(vp);
5112 if (V_offlineMessage(vp)[0]) {
5113 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5114 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5115 V_offlineMessage(vp));
5117 Log("VOffline: Volume %lu (%s) is now offline\n",
5118 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5121 FreeVolumeHeader(vp);
5122 #ifdef AFS_PTHREAD_ENV
5123 CV_BROADCAST(&vol_put_volume_cond);
5124 #else /* AFS_PTHREAD_ENV */
5125 LWP_NoYieldSignal(VPutVolume);
5126 #endif /* AFS_PTHREAD_ENV */
5130 #endif /* AFS_DEMAND_ATTACH_FS */
5132 /***************************************************/
5133 /* demand attach fs ref counting routines */
5134 /***************************************************/
5136 #ifdef AFS_DEMAND_ATTACH_FS
5137 /* the following two functions handle reference counting for
5138 * asynchronous operations on volume structs.
5140 * their purpose is to prevent a VDetachVolume or VShutdown
5141 * from free()ing the Volume struct during an async i/o op */
5143 /* register with the async volume op ref counter */
5144 /* VCreateReservation_r moved into inline code header because it
5145 * is now needed in vnode.c -- tkeiser 11/20/2007
5149 * decrement volume-package internal refcount.
5151 * @param vp volume object pointer
5153 * @internal volume package internal use only
5156 * @arg VOL_LOCK is held
5157 * @arg lightweight refcount held
5159 * @post volume waiters refcount is decremented; volume may
5160 * have been deallocated/shutdown/offlined/salvaged/
5161 * whatever during the process
5163 * @warning once you have tossed your last reference (you can acquire
5164 * lightweight refs recursively) it is NOT SAFE to reference
5165 * a volume object pointer ever again
5167 * @see VCreateReservation_r
5169 * @note DEMAND_ATTACH_FS only
5172 VCancelReservation_r(Volume * vp)
5174 osi_Assert(--vp->nWaiters >= 0);
5175 if (vp->nWaiters == 0) {
5177 if (!VCheckDetach(vp)) {
5184 /* check to see if we should free this volume now
5185 * return 1 if volume was freed, 0 otherwise */
5187 VCheckFree(Volume * vp)
5190 if ((vp->nUsers == 0) &&
5191 (vp->nWaiters == 0) &&
5192 !(V_attachFlags(vp) & (VOL_IN_HASH |
5196 ReallyFreeVolume(vp);
5201 #endif /* AFS_DEMAND_ATTACH_FS */
5204 /***************************************************/
5205 /* online volume operations routines */
5206 /***************************************************/
5208 #ifdef AFS_DEMAND_ATTACH_FS
5210 * register a volume operation on a given volume.
5212 * @param[in] vp volume object
5213 * @param[in] vopinfo volume operation info object
5215 * @pre VOL_LOCK is held
5217 * @post volume operation info object attached to volume object.
5218 * volume operation statistics updated.
5220 * @note by "attached" we mean a copy of the passed in object is made
5222 * @internal volume package internal use only
5225 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5227 FSSYNC_VolOp_info * info;
5229 /* attach a vol op info node to the volume struct */
5230 info = (FSSYNC_VolOp_info *) malloc(sizeof(FSSYNC_VolOp_info));
5231 osi_Assert(info != NULL);
5232 memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
5233 vp->pending_vol_op = info;
5236 vp->stats.last_vol_op = FT_ApproxTime();
5237 vp->stats.vol_ops++;
5238 IncUInt64(&VStats.vol_ops);
5244 * deregister the volume operation attached to this volume.
5246 * @param[in] vp volume object pointer
5248 * @pre VOL_LOCK is held
5250 * @post the volume operation info object is detached from the volume object
5252 * @internal volume package internal use only
5255 VDeregisterVolOp_r(Volume * vp)
5257 if (vp->pending_vol_op) {
5258 free(vp->pending_vol_op);
5259 vp->pending_vol_op = NULL;
5263 #endif /* AFS_DEMAND_ATTACH_FS */
5266 * determine whether it is safe to leave a volume online during
5267 * the volume operation described by the vopinfo object.
5269 * @param[in] vp volume object
5270 * @param[in] vopinfo volume operation info object
5272 * @return whether it is safe to leave volume online
5273 * @retval 0 it is NOT SAFE to leave the volume online
5274 * @retval 1 it is safe to leave the volume online during the operation
5277 * @arg VOL_LOCK is held
5278 * @arg disk header attached to vp (heavyweight ref on vp will guarantee
5279 * this condition is met)
5281 * @internal volume package internal use only
5284 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5286 return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
5287 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5288 (vopinfo->com.reason == V_READONLY ||
5289 (!VolumeWriteable(vp) &&
5290 (vopinfo->com.reason == V_CLONE ||
5291 vopinfo->com.reason == V_DUMP)))));
5295 * same as VVolOpLeaveOnline_r, but does not require a volume with an attached
5298 * @param[in] vp volume object
5299 * @param[in] vopinfo volume operation info object
5301 * @return whether it is safe to leave volume online
5302 * @retval 0 it is NOT SAFE to leave the volume online
5303 * @retval 1 it is safe to leave the volume online during the operation
5304 * @retval -1 unsure; volume header is required in order to know whether or
5305 * not is is safe to leave the volume online
5307 * @pre VOL_LOCK is held
5309 * @internal volume package internal use only
5312 VVolOpLeaveOnlineNoHeader_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5314 /* follow the logic in VVolOpLeaveOnline_r; this is the same, except
5315 * assume that we don't know VolumeWriteable; return -1 if the answer
5316 * depends on VolumeWriteable */
5318 if (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline) {
5321 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5322 vopinfo->com.reason == V_READONLY) {
5326 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5327 (vopinfo->com.reason == V_CLONE ||
5328 vopinfo->com.reason == V_DUMP)) {
5330 /* must know VolumeWriteable */
5337 * determine whether VBUSY should be set during this volume operation.
5339 * @param[in] vp volume object
5340 * @param[in] vopinfo volume operation info object
5342 * @return whether VBUSY should be set
5343 * @retval 0 VBUSY does NOT need to be set
5344 * @retval 1 VBUSY SHOULD be set
5346 * @pre VOL_LOCK is held
5348 * @internal volume package internal use only
5351 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5353 return ((vopinfo->com.command == FSYNC_VOL_OFF &&
5354 vopinfo->com.reason == FSYNC_SALVAGE) ||
5355 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5356 (vopinfo->com.reason == V_CLONE ||
5357 vopinfo->com.reason == V_DUMP)));
5361 /***************************************************/
5362 /* online salvager routines */
5363 /***************************************************/
5364 #if defined(AFS_DEMAND_ATTACH_FS)
5367 * offline a volume to let it be salvaged.
5369 * @param[in] vp Volume to offline
5371 * @return whether we offlined the volume successfully
5372 * @retval 0 volume was not offlined
5373 * @retval 1 volume is now offline
5375 * @note This is similar to VCheckOffline, but slightly different. We do not
5376 * deal with vp->goingOffline, and we try to avoid touching the volume
5377 * header except just to set needsSalvaged
5379 * @pre VOL_LOCK held
5380 * @pre vp->nUsers == 0
5381 * @pre V_attachState(vp) == VOL_STATE_SALVAGE_REQ
5384 VOfflineForSalvage_r(struct Volume *vp)
5388 VCreateReservation_r(vp);
5389 VWaitExclusiveState_r(vp);
5391 if (vp->nUsers || V_attachState(vp) == VOL_STATE_SALVAGING) {
5392 /* Someone's using the volume, or someone got to scheduling the salvage
5393 * before us. I don't think either of these should be possible, as we
5394 * should gain no new heavyweight references while we're trying to
5395 * salvage, but just to be sure... */
5396 VCancelReservation_r(vp);
5400 VChangeState_r(vp, VOL_STATE_OFFLINING);
5404 V_needsSalvaged(vp) = 1;
5405 /* ignore error; updating needsSalvaged is just best effort */
5406 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
5408 VCloseVolumeHandles_r(vp);
5410 FreeVolumeHeader(vp);
5412 /* volume has been effectively offlined; we can mark it in the SALVAGING
5413 * state now, which lets FSSYNC give it away */
5414 VChangeState_r(vp, VOL_STATE_SALVAGING);
5416 VCancelReservation_r(vp);
5422 * check whether a salvage needs to be performed on this volume.
5424 * @param[in] vp pointer to volume object
5426 * @return status code
5427 * @retval 0 no salvage scheduled
5428 * @retval 1 a salvage has been scheduled with the salvageserver
5430 * @pre VOL_LOCK is held
5432 * @post if salvage request flag is set and nUsers and nWaiters are zero,
5433 * then a salvage will be requested
5435 * @note this is one of the event handlers called by VCancelReservation_r
5437 * @note the caller must check if the volume needs to be freed after calling
5438 * this; the volume may not have any references or be on any lists after
5439 * we return, and we do not free it
5441 * @see VCancelReservation_r
5443 * @internal volume package internal use only.
5446 VCheckSalvage(Volume * vp)
5449 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5452 if (!vp->salvage.requested) {
5456 /* prevent recursion; some of the code below creates and removes
5457 * lightweight refs, which can call VCheckSalvage */
5458 if (vp->salvage.scheduling) {
5461 vp->salvage.scheduling = 1;
5463 if (V_attachState(vp) == VOL_STATE_SALVAGE_REQ) {
5464 if (!VOfflineForSalvage_r(vp)) {
5465 vp->salvage.scheduling = 0;
5470 if (vp->salvage.requested) {
5471 VScheduleSalvage_r(vp);
5474 vp->salvage.scheduling = 0;
5475 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5480 * request volume salvage.
5482 * @param[out] ec computed client error code
5483 * @param[in] vp volume object pointer
5484 * @param[in] reason reason code (passed to salvageserver via SALVSYNC)
5485 * @param[in] flags see flags note below
5488 * VOL_SALVAGE_INVALIDATE_HEADER causes volume header cache entry
5489 * to be invalidated.
5491 * @pre VOL_LOCK is held.
5493 * @post volume state is changed.
5494 * for fileserver, salvage will be requested once refcount reaches zero.
5496 * @return operation status code
5497 * @retval 0 volume salvage will occur
5498 * @retval 1 volume salvage could not be scheduled
5502 * @note in the fileserver, this call does not synchronously schedule a volume
5503 * salvage. rather, it sets volume state so that when volume refcounts
5504 * reach zero, a volume salvage will occur. by "refcounts", we mean both
5505 * nUsers and nWaiters must be zero.
5507 * @internal volume package internal use only.
5510 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
5514 * for DAFS volume utilities that are not supposed to schedule salvages,
5515 * just transition to error state instead
5517 if (!VCanScheduleSalvage()) {
5518 VChangeState_r(vp, VOL_STATE_ERROR);
5523 if (programType != fileServer && !VCanUseFSSYNC()) {
5524 VChangeState_r(vp, VOL_STATE_ERROR);
5529 if (!vp->salvage.requested) {
5530 vp->salvage.requested = 1;
5531 vp->salvage.reason = reason;
5532 vp->stats.last_salvage = FT_ApproxTime();
5534 /* Note that it is not possible for us to reach this point if a
5535 * salvage is already running on this volume (even if the fileserver
5536 * was restarted during the salvage). If a salvage were running, the
5537 * salvager would have write-locked the volume header file, so when
5538 * we tried to lock the volume header, the lock would have failed,
5539 * and we would have failed during attachment prior to calling
5540 * VRequestSalvage. So we know that we can schedule salvages without
5541 * fear of a salvage already running for this volume. */
5543 if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
5545 /* if we don't need to offline the volume, we can go directly
5546 * to SALVAGING. SALVAGING says the volume is offline and is
5547 * either salvaging or ready to be handed to the salvager.
5548 * SALVAGE_REQ says that we want to salvage the volume, but we
5549 * are waiting for it to go offline first. */
5550 if (flags & VOL_SALVAGE_NO_OFFLINE) {
5551 VChangeState_r(vp, VOL_STATE_SALVAGING);
5553 VChangeState_r(vp, VOL_STATE_SALVAGE_REQ);
5554 if (vp->nUsers == 0) {
5555 /* normally VOfflineForSalvage_r would be called from
5556 * PutVolume et al when nUsers reaches 0, but if
5557 * it's already 0, just do it ourselves, since PutVolume
5558 * isn't going to get called */
5559 VOfflineForSalvage_r(vp);
5564 Log("VRequestSalvage: volume %u online salvaged too many times; forced offline.\n", vp->hashid);
5566 /* make sure neither VScheduleSalvage_r nor
5567 * VUpdateSalvagePriority_r try to schedule another salvage */
5568 vp->salvage.requested = vp->salvage.scheduled = 0;
5570 VChangeState_r(vp, VOL_STATE_ERROR);
5574 if (flags & VOL_SALVAGE_INVALIDATE_HEADER) {
5575 /* Instead of ReleaseVolumeHeader, we do FreeVolumeHeader()
5576 so that the the next VAttachVolumeByVp_r() invocation
5577 of attach2() will pull in a cached header
5578 entry and fail, then load a fresh one from disk and attach
5581 FreeVolumeHeader(vp);
5588 * update salvageserver scheduling priority for a volume.
5590 * @param[in] vp pointer to volume object
5592 * @return operation status
5594 * @retval 1 request denied, or SALVSYNC communications failure
5596 * @pre VOL_LOCK is held.
5598 * @post in-core salvage priority counter is incremented. if at least
5599 * SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
5600 * last SALVSYNC_RAISEPRIO request, we contact the salvageserver
5601 * to update its priority queue. if no salvage is scheduled,
5602 * this function is a no-op.
5604 * @note DAFS fileserver only
5606 * @note this should be called whenever a VGetVolume fails due to a
5607 * pending salvage request
5609 * @todo should set exclusive state and drop glock around salvsync call
5611 * @internal volume package internal use only.
5614 VUpdateSalvagePriority_r(Volume * vp)
5618 #ifdef SALVSYNC_BUILD_CLIENT
5623 now = FT_ApproxTime();
5625 /* update the salvageserver priority queue occasionally so that
5626 * frequently requested volumes get moved to the head of the queue
5628 if ((vp->salvage.scheduled) &&
5629 (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
5630 code = SALVSYNC_SalvageVolume(vp->hashid,
5631 VPartitionPath(vp->partition),
5636 vp->stats.last_salvage_req = now;
5637 if (code != SYNC_OK) {
5641 #endif /* SALVSYNC_BUILD_CLIENT */
5646 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5648 /* A couple of little helper functions. These return true if we tried to
5649 * use this mechanism to schedule a salvage, false if we haven't tried.
5650 * If we did try a salvage then the results are contained in code.
5654 try_SALVSYNC(Volume *vp, char *partName, int *code) {
5655 #ifdef SALVSYNC_BUILD_CLIENT
5656 if (VCanUseSALVSYNC()) {
5657 Log("Scheduling salvage for volume %lu on part %s over SALVSYNC\n",
5658 afs_printable_uint32_lu(vp->hashid), partName);
5660 /* can't use V_id() since there's no guarantee
5661 * we have the disk data header at this point */
5662 *code = SALVSYNC_SalvageVolume(vp->hashid,
5675 try_FSSYNC(Volume *vp, char *partName, int *code) {
5676 #ifdef FSSYNC_BUILD_CLIENT
5677 if (VCanUseFSSYNC()) {
5678 Log("Scheduling salvage for volume %lu on part %s over FSSYNC\n",
5679 afs_printable_uint32_lu(vp->hashid), partName);
5682 * If we aren't the fileserver, tell the fileserver the volume
5683 * needs to be salvaged. We could directly tell the
5684 * salvageserver, but the fileserver keeps track of some stats
5685 * related to salvages, and handles some other salvage-related
5686 * complications for us.
5688 *code = FSYNC_VolOp(vp->hashid, partName,
5689 FSYNC_VOL_FORCE_ERROR, FSYNC_SALVAGE, NULL);
5692 #endif /* FSSYNC_BUILD_CLIENT */
5697 * schedule a salvage with the salvage server or fileserver.
5699 * @param[in] vp pointer to volume object
5701 * @return operation status
5702 * @retval 0 salvage scheduled successfully
5703 * @retval 1 salvage not scheduled, or SALVSYNC/FSSYNC com error
5706 * @arg VOL_LOCK is held.
5707 * @arg nUsers and nWaiters should be zero.
5709 * @post salvageserver or fileserver is sent a salvage request
5711 * @note If we are the fileserver, the request will be sent to the salvage
5712 * server over SALVSYNC. If we are not the fileserver, the request will be
5713 * sent to the fileserver over FSSYNC (FSYNC_VOL_FORCE_ERROR/FSYNC_SALVAGE).
5715 * @note the caller must check if the volume needs to be freed after calling
5716 * this; the volume may not have any references or be on any lists after
5717 * we return, and we do not free it
5721 * @internal volume package internal use only.
5724 VScheduleSalvage_r(Volume * vp)
5728 VolState state_save;
5729 VThreadOptions_t * thread_opts;
5732 osi_Assert(VCanUseSALVSYNC() || VCanUseFSSYNC());
5734 if (vp->nWaiters || vp->nUsers) {
5738 /* prevent endless salvage,attach,salvage,attach,... loops */
5739 if (vp->stats.salvages >= SALVAGE_COUNT_MAX)
5743 * don't perform salvsync ops on certain threads
5745 thread_opts = pthread_getspecific(VThread_key);
5746 if (thread_opts == NULL) {
5747 thread_opts = &VThread_defaults;
5749 if (thread_opts->disallow_salvsync || vol_disallow_salvsync) {
5753 if (vp->salvage.scheduled) {
5757 VCreateReservation_r(vp);
5758 VWaitExclusiveState_r(vp);
5761 * XXX the scheduling process should really be done asynchronously
5762 * to avoid fssync deadlocks
5764 if (!vp->salvage.scheduled) {
5765 /* if we haven't previously scheduled a salvage, do so now
5767 * set the volume to an exclusive state and drop the lock
5768 * around the SALVSYNC call
5770 strlcpy(partName, VPartitionPath(vp->partition), sizeof(partName));
5771 state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
5774 osi_Assert(try_SALVSYNC(vp, partName, &code) ||
5775 try_FSSYNC(vp, partName, &code));
5778 VChangeState_r(vp, state_save);
5780 if (code == SYNC_OK) {
5781 vp->salvage.scheduled = 1;
5782 vp->stats.last_salvage_req = FT_ApproxTime();
5783 if (VCanUseSALVSYNC()) {
5784 /* don't record these stats for non-fileservers; let the
5785 * fileserver take care of these */
5786 vp->stats.salvages++;
5787 IncUInt64(&VStats.salvages);
5792 case SYNC_BAD_COMMAND:
5793 case SYNC_COM_ERROR:
5796 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5797 "denied\n", afs_printable_uint32_lu(vp->hashid));
5800 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5801 "received unknown protocol error %d\n",
5802 afs_printable_uint32_lu(vp->hashid), code);
5806 if (VCanUseFSSYNC()) {
5807 VChangeState_r(vp, VOL_STATE_ERROR);
5812 /* NB: this is cancelling the reservation we obtained above, but we do
5813 * not call VCancelReservation_r, since that may trigger the vp dtor,
5814 * possibly free'ing the vp. We need to keep the vp around after
5815 * this, as the caller may reference vp without any refs. Instead, it
5816 * is the duty of the caller to inspect 'vp' after we return to see if
5817 * needs to be freed. */
5818 osi_Assert(--vp->nWaiters >= 0);
5821 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5823 #ifdef SALVSYNC_BUILD_CLIENT
5826 * connect to the salvageserver SYNC service.
5828 * @return operation status
5832 * @post connection to salvageserver SYNC service established
5834 * @see VConnectSALV_r
5835 * @see VDisconnectSALV
5836 * @see VReconnectSALV
5843 retVal = VConnectSALV_r();
5849 * connect to the salvageserver SYNC service.
5851 * @return operation status
5855 * @pre VOL_LOCK is held.
5857 * @post connection to salvageserver SYNC service established
5860 * @see VDisconnectSALV_r
5861 * @see VReconnectSALV_r
5862 * @see SALVSYNC_clientInit
5864 * @internal volume package internal use only.
5867 VConnectSALV_r(void)
5869 return SALVSYNC_clientInit();
5873 * disconnect from the salvageserver SYNC service.
5875 * @return operation status
5878 * @pre client should have a live connection to the salvageserver
5880 * @post connection to salvageserver SYNC service destroyed
5882 * @see VDisconnectSALV_r
5884 * @see VReconnectSALV
5887 VDisconnectSALV(void)
5890 VDisconnectSALV_r();
5896 * disconnect from the salvageserver SYNC service.
5898 * @return operation status
5902 * @arg VOL_LOCK is held.
5903 * @arg client should have a live connection to the salvageserver.
5905 * @post connection to salvageserver SYNC service destroyed
5907 * @see VDisconnectSALV
5908 * @see VConnectSALV_r
5909 * @see VReconnectSALV_r
5910 * @see SALVSYNC_clientFinis
5912 * @internal volume package internal use only.
5915 VDisconnectSALV_r(void)
5917 return SALVSYNC_clientFinis();
5921 * disconnect and then re-connect to the salvageserver SYNC service.
5923 * @return operation status
5927 * @pre client should have a live connection to the salvageserver
5929 * @post old connection is dropped, and a new one is established
5932 * @see VDisconnectSALV
5933 * @see VReconnectSALV_r
5936 VReconnectSALV(void)
5940 retVal = VReconnectSALV_r();
5946 * disconnect and then re-connect to the salvageserver SYNC service.
5948 * @return operation status
5953 * @arg VOL_LOCK is held.
5954 * @arg client should have a live connection to the salvageserver.
5956 * @post old connection is dropped, and a new one is established
5958 * @see VConnectSALV_r
5959 * @see VDisconnectSALV
5960 * @see VReconnectSALV
5961 * @see SALVSYNC_clientReconnect
5963 * @internal volume package internal use only.
5966 VReconnectSALV_r(void)
5968 return SALVSYNC_clientReconnect();
5970 #endif /* SALVSYNC_BUILD_CLIENT */
5971 #endif /* AFS_DEMAND_ATTACH_FS */
5974 /***************************************************/
5975 /* FSSYNC routines */
5976 /***************************************************/
5978 /* This must be called by any volume utility which needs to run while the
5979 file server is also running. This is separated from VInitVolumePackage2 so
5980 that a utility can fork--and each of the children can independently
5981 initialize communication with the file server */
5982 #ifdef FSSYNC_BUILD_CLIENT
5984 * connect to the fileserver SYNC service.
5986 * @return operation status
5991 * @arg VInit must equal 2.
5992 * @arg Program Type must not be fileserver or salvager.
5994 * @post connection to fileserver SYNC service established
5997 * @see VDisconnectFS
5998 * @see VChildProcReconnectFS
6005 retVal = VConnectFS_r();
6011 * connect to the fileserver SYNC service.
6013 * @return operation status
6018 * @arg VInit must equal 2.
6019 * @arg Program Type must not be fileserver or salvager.
6020 * @arg VOL_LOCK is held.
6022 * @post connection to fileserver SYNC service established
6025 * @see VDisconnectFS_r
6026 * @see VChildProcReconnectFS_r
6028 * @internal volume package internal use only.
6034 osi_Assert((VInit == 2) &&
6035 (programType != fileServer) &&
6036 (programType != salvager));
6037 rc = FSYNC_clientInit();
6045 * disconnect from the fileserver SYNC service.
6048 * @arg client should have a live connection to the fileserver.
6049 * @arg VOL_LOCK is held.
6050 * @arg Program Type must not be fileserver or salvager.
6052 * @post connection to fileserver SYNC service destroyed
6054 * @see VDisconnectFS
6056 * @see VChildProcReconnectFS_r
6058 * @internal volume package internal use only.
6061 VDisconnectFS_r(void)
6063 osi_Assert((programType != fileServer) &&
6064 (programType != salvager));
6065 FSYNC_clientFinis();
6070 * disconnect from the fileserver SYNC service.
6073 * @arg client should have a live connection to the fileserver.
6074 * @arg Program Type must not be fileserver or salvager.
6076 * @post connection to fileserver SYNC service destroyed
6078 * @see VDisconnectFS_r
6080 * @see VChildProcReconnectFS
6091 * connect to the fileserver SYNC service from a child process following a fork.
6093 * @return operation status
6098 * @arg VOL_LOCK is held.
6099 * @arg current FSYNC handle is shared with a parent process
6101 * @post current FSYNC handle is discarded and a new connection to the
6102 * fileserver SYNC service is established
6104 * @see VChildProcReconnectFS
6106 * @see VDisconnectFS_r
6108 * @internal volume package internal use only.
6111 VChildProcReconnectFS_r(void)
6113 return FSYNC_clientChildProcReconnect();
6117 * connect to the fileserver SYNC service from a child process following a fork.
6119 * @return operation status
6123 * @pre current FSYNC handle is shared with a parent process
6125 * @post current FSYNC handle is discarded and a new connection to the
6126 * fileserver SYNC service is established
6128 * @see VChildProcReconnectFS_r
6130 * @see VDisconnectFS
6133 VChildProcReconnectFS(void)
6137 ret = VChildProcReconnectFS_r();
6141 #endif /* FSSYNC_BUILD_CLIENT */
6144 /***************************************************/
6145 /* volume bitmap routines */
6146 /***************************************************/
6149 * allocate a vnode bitmap number for the vnode
6151 * @param[out] ec error code
6152 * @param[in] vp volume object pointer
6153 * @param[in] index vnode index number for the vnode
6154 * @param[in] flags flag values described in note
6156 * @note for DAFS, flags parameter controls locking behavior.
6157 * If (flags & VOL_ALLOC_BITMAP_WAIT) is set, then this function
6158 * will create a reservation and block on any other exclusive
6159 * operations. Otherwise, this function assumes the caller
6160 * already has exclusive access to vp, and we just change the
6163 * @pre VOL_LOCK held
6165 * @return bit number allocated
6171 VAllocBitmapEntry_r(Error * ec, Volume * vp,
6172 struct vnodeIndex *index, int flags)
6176 #ifdef AFS_DEMAND_ATTACH_FS
6177 VolState state_save;
6178 #endif /* AFS_DEMAND_ATTACH_FS */
6182 /* This test is probably redundant */
6183 if (!VolumeWriteable(vp)) {
6184 *ec = (bit32) VREADONLY;
6188 #ifdef AFS_DEMAND_ATTACH_FS
6189 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6190 VCreateReservation_r(vp);
6191 VWaitExclusiveState_r(vp);
6193 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6194 #endif /* AFS_DEMAND_ATTACH_FS */
6197 if ((programType == fileServer) && !index->bitmap) {
6199 #ifndef AFS_DEMAND_ATTACH_FS
6200 /* demand attach fs uses the volume state to avoid races.
6201 * specialStatus field is not used at all */
6203 if (vp->specialStatus == VBUSY) {
6204 if (vp->goingOffline) { /* vos dump waiting for the volume to
6205 * go offline. We probably come here
6206 * from AddNewReadableResidency */
6209 while (vp->specialStatus == VBUSY) {
6210 #ifdef AFS_PTHREAD_ENV
6214 #else /* !AFS_PTHREAD_ENV */
6216 #endif /* !AFS_PTHREAD_ENV */
6220 #endif /* !AFS_DEMAND_ATTACH_FS */
6222 if (!index->bitmap) {
6223 #ifndef AFS_DEMAND_ATTACH_FS
6224 vp->specialStatus = VBUSY; /* Stop anyone else from using it. */
6225 #endif /* AFS_DEMAND_ATTACH_FS */
6226 for (i = 0; i < nVNODECLASSES; i++) {
6227 VGetBitmap_r(ec, vp, i);
6229 #ifdef AFS_DEMAND_ATTACH_FS
6230 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
6231 #else /* AFS_DEMAND_ATTACH_FS */
6232 DeleteVolumeFromHashTable(vp);
6233 vp->shuttingDown = 1; /* Let who has it free it. */
6234 vp->specialStatus = 0;
6235 #endif /* AFS_DEMAND_ATTACH_FS */
6239 #ifndef AFS_DEMAND_ATTACH_FS
6241 vp->specialStatus = 0; /* Allow others to have access. */
6242 #endif /* AFS_DEMAND_ATTACH_FS */
6245 #endif /* BITMAP_LATER */
6247 #ifdef AFS_DEMAND_ATTACH_FS
6249 #endif /* AFS_DEMAND_ATTACH_FS */
6250 bp = index->bitmap + index->bitmapOffset;
6251 ep = index->bitmap + index->bitmapSize;
6253 if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
6255 index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
6258 o = ffs(~*bp) - 1; /* ffs is documented in BSTRING(3) */
6260 ret = ((bp - index->bitmap) * 8 + o);
6261 #ifdef AFS_DEMAND_ATTACH_FS
6263 #endif /* AFS_DEMAND_ATTACH_FS */
6266 bp += sizeof(bit32) /* i.e. 4 */ ;
6268 /* No bit map entry--must grow bitmap */
6270 realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
6271 osi_Assert(bp != NULL);
6273 bp += index->bitmapSize;
6274 memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
6275 index->bitmapOffset = index->bitmapSize;
6276 index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
6278 ret = index->bitmapOffset * 8;
6279 #ifdef AFS_DEMAND_ATTACH_FS
6281 #endif /* AFS_DEMAND_ATTACH_FS */
6284 #ifdef AFS_DEMAND_ATTACH_FS
6285 VChangeState_r(vp, state_save);
6286 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6287 VCancelReservation_r(vp);
6289 #endif /* AFS_DEMAND_ATTACH_FS */
6294 VAllocBitmapEntry(Error * ec, Volume * vp, struct vnodeIndex * index)
6298 retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
6304 VFreeBitMapEntry_r(Error * ec, Volume *vp, struct vnodeIndex *index,
6305 unsigned bitNumber, int flags)
6307 unsigned int offset;
6311 #ifdef AFS_DEMAND_ATTACH_FS
6312 if (flags & VOL_FREE_BITMAP_WAIT) {
6313 /* VAllocBitmapEntry_r allocs bitmap entries under an exclusive volume
6314 * state, so ensure we're not in an exclusive volume state when we update
6316 VCreateReservation_r(vp);
6317 VWaitExclusiveState_r(vp);
6324 #endif /* BITMAP_LATER */
6326 offset = bitNumber >> 3;
6327 if (offset >= index->bitmapSize) {
6331 if (offset < index->bitmapOffset)
6332 index->bitmapOffset = offset & ~3; /* Truncate to nearest bit32 */
6333 *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
6336 #ifdef AFS_DEMAND_ATTACH_FS
6337 VCancelReservation_r(vp);
6339 return; /* make the compiler happy for non-DAFS */
6343 VFreeBitMapEntry(Error * ec, Volume *vp, struct vnodeIndex *index,
6347 VFreeBitMapEntry_r(ec, vp, index, bitNumber, VOL_FREE_BITMAP_WAIT);
6351 /* this function will drop the glock internally.
6352 * for old pthread fileservers, this is safe thanks to vbusy.
6354 * for demand attach fs, caller must have already called
6355 * VCreateReservation_r and VWaitExclusiveState_r */
6357 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
6359 StreamHandle_t *file;
6360 afs_sfsize_t nVnodes, size;
6361 struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
6362 struct vnodeIndex *vip = &vp->vnodeIndex[class];
6363 struct VnodeDiskObject *vnode;
6364 unsigned int unique = 0;
6368 #endif /* BITMAP_LATER */
6369 #ifdef AFS_DEMAND_ATTACH_FS
6370 VolState state_save;
6371 #endif /* AFS_DEMAND_ATTACH_FS */
6375 #ifdef AFS_DEMAND_ATTACH_FS
6376 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6377 #endif /* AFS_DEMAND_ATTACH_FS */
6380 fdP = IH_OPEN(vip->handle);
6381 osi_Assert(fdP != NULL);
6382 file = FDH_FDOPEN(fdP, "r");
6383 osi_Assert(file != NULL);
6384 vnode = (VnodeDiskObject *) malloc(vcp->diskSize);
6385 osi_Assert(vnode != NULL);
6386 size = OS_SIZE(fdP->fd_fd);
6387 osi_Assert(size != -1);
6388 nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
6390 vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4; /* The 10 is a little extra so
6391 * a few files can be created in this volume,
6392 * the whole thing is rounded up to nearest 4
6393 * bytes, because the bit map allocator likes
6396 BitMap = (byte *) calloc(1, vip->bitmapSize);
6397 osi_Assert(BitMap != NULL);
6398 #else /* BITMAP_LATER */
6399 vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
6400 osi_Assert(vip->bitmap != NULL);
6401 vip->bitmapOffset = 0;
6402 #endif /* BITMAP_LATER */
6403 if (STREAM_ASEEK(file, vcp->diskSize) != -1) {
6405 for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
6406 if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
6408 if (vnode->type != vNull) {
6409 if (vnode->vnodeMagic != vcp->magic) {
6410 Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
6415 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6416 #else /* BITMAP_LATER */
6417 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6418 #endif /* BITMAP_LATER */
6419 if (unique <= vnode->uniquifier)
6420 unique = vnode->uniquifier + 1;
6422 #ifndef AFS_PTHREAD_ENV
6423 if ((bitNumber & 0x00ff) == 0x0ff) { /* every 256 iterations */
6426 #endif /* !AFS_PTHREAD_ENV */
6429 if (vp->nextVnodeUnique < unique) {
6430 Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
6433 /* Paranoia, partly justified--I think fclose after fdopen
6434 * doesn't seem to close fd. In any event, the documentation
6435 * doesn't specify, so it's safer to close it twice.
6443 /* There may have been a racing condition with some other thread, both
6444 * creating the bitmaps for this volume. If the other thread was faster
6445 * the pointer to bitmap should already be filled and we can free ours.
6447 if (vip->bitmap == NULL) {
6448 vip->bitmap = BitMap;
6449 vip->bitmapOffset = 0;
6451 free((byte *) BitMap);
6452 #endif /* BITMAP_LATER */
6453 #ifdef AFS_DEMAND_ATTACH_FS
6454 VChangeState_r(vp, state_save);
6455 #endif /* AFS_DEMAND_ATTACH_FS */
6459 /***************************************************/
6460 /* Volume Path and Volume Number utility routines */
6461 /***************************************************/
6464 * find the first occurrence of a volume header file and return the path.
6466 * @param[out] ec outbound error code
6467 * @param[in] volumeId volume id to find
6468 * @param[out] partitionp pointer to disk partition path string
6469 * @param[out] namep pointer to volume header file name string
6471 * @post path to first occurrence of volume header is returned in partitionp
6472 * and namep, or ec is set accordingly.
6474 * @warning this function is NOT re-entrant -- partitionp and namep point to
6475 * static data segments
6477 * @note if a volume utility inadvertently leaves behind a stale volume header
6478 * on a vice partition, it is possible for callers to get the wrong one,
6479 * depending on the order of the disk partition linked list.
6483 VGetVolumePath(Error * ec, VolId volumeId, char **partitionp, char **namep)
6485 static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
6486 char path[VMAXPATHLEN];
6488 struct DiskPartition64 *dp;
6491 name[0] = OS_DIRSEPC;
6492 (void)afs_snprintf(&name[1], (sizeof name) - 1, VFORMAT, afs_printable_uint32_lu(volumeId));
6493 for (dp = DiskPartitionList; dp; dp = dp->next) {
6494 struct afs_stat status;
6495 strcpy(path, VPartitionPath(dp));
6497 if (afs_stat(path, &status) == 0) {
6498 strcpy(partition, dp->name);
6505 *partitionp = *namep = NULL;
6507 *partitionp = partition;
6513 * extract a volume number from a volume header filename string.
6515 * @param[in] name volume header filename string
6517 * @return volume number
6519 * @note the string must be of the form VFORMAT. the only permissible
6520 * deviation is a leading OS_DIRSEPC character.
6525 VolumeNumber(char *name)
6527 if (*name == OS_DIRSEPC)
6529 return atoi(name + 1);
6533 * compute the volume header filename.
6535 * @param[in] volumeId
6537 * @return volume header filename
6539 * @post volume header filename string is constructed
6541 * @warning this function is NOT re-entrant -- the returned string is
6542 * stored in a static char array. see VolumeExternalName_r
6543 * for a re-entrant equivalent.
6545 * @see VolumeExternalName_r
6547 * @deprecated due to the above re-entrancy warning, this interface should
6548 * be considered deprecated. Please use VolumeExternalName_r
6552 VolumeExternalName(VolumeId volumeId)
6554 static char name[VMAXPATHLEN];
6555 (void)afs_snprintf(name, sizeof name, VFORMAT, afs_printable_uint32_lu(volumeId));
6560 * compute the volume header filename.
6562 * @param[in] volumeId
6563 * @param[inout] name array in which to store filename
6564 * @param[in] len length of name array
6566 * @return result code from afs_snprintf
6568 * @see VolumeExternalName
6571 * @note re-entrant equivalent of VolumeExternalName
6574 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
6576 return afs_snprintf(name, len, VFORMAT, afs_printable_uint32_lu(volumeId));
6580 /***************************************************/
6581 /* Volume Usage Statistics routines */
6582 /***************************************************/
6584 #if OPENAFS_VOL_STATS
6585 #define OneDay (86400) /* 24 hours' worth of seconds */
6587 #define OneDay (24*60*60) /* 24 hours */
6588 #endif /* OPENAFS_VOL_STATS */
6591 Midnight(time_t t) {
6592 struct tm local, *l;
6595 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
6596 l = localtime_r(&t, &local);
6602 /* the following is strictly speaking problematic on the
6603 switching day to daylight saving time, after the switch,
6604 as tm_isdst does not match. Similarly, on the looong day when
6605 switching back the OneDay check will not do what naively expected!
6606 The effects are minor, though, and more a matter of interpreting
6608 #ifndef AFS_PTHREAD_ENV
6611 local.tm_hour = local.tm_min=local.tm_sec = 0;
6612 midnight = mktime(&local);
6613 if (midnight != (time_t) -1) return(midnight);
6615 return( (t/OneDay)*OneDay );
6619 /*------------------------------------------------------------------------
6620 * [export] VAdjustVolumeStatistics
6623 * If we've passed midnight, we need to update all the day use
6624 * statistics as well as zeroing the detailed volume statistics
6625 * (if we are implementing them).
6628 * vp : Pointer to the volume structure describing the lucky
6629 * volume being considered for update.
6635 * Nothing interesting.
6639 *------------------------------------------------------------------------*/
6642 VAdjustVolumeStatistics_r(Volume * vp)
6644 unsigned int now = FT_ApproxTime();
6646 if (now - V_dayUseDate(vp) > OneDay) {
6649 ndays = (now - V_dayUseDate(vp)) / OneDay;
6650 for (i = 6; i > ndays - 1; i--)
6651 V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
6652 for (i = 0; i < ndays - 1 && i < 7; i++)
6653 V_weekUse(vp)[i] = 0;
6655 V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
6657 V_dayUseDate(vp) = Midnight(now);
6659 #if OPENAFS_VOL_STATS
6661 * All we need to do is bzero the entire VOL_STATS_BYTES of
6662 * the detailed volume statistics area.
6664 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
6665 #endif /* OPENAFS_VOL_STATS */
6668 /*It's been more than a day of collection */
6670 * Always return happily.
6673 } /*VAdjustVolumeStatistics */
6676 VAdjustVolumeStatistics(Volume * vp)
6680 retVal = VAdjustVolumeStatistics_r(vp);
6686 VBumpVolumeUsage_r(Volume * vp)
6688 unsigned int now = FT_ApproxTime();
6689 V_accessDate(vp) = now;
6690 if (now - V_dayUseDate(vp) > OneDay)
6691 VAdjustVolumeStatistics_r(vp);
6693 * Save the volume header image to disk after every 128 bumps to dayUse.
6695 if ((V_dayUse(vp)++ & 127) == 0) {
6697 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
6702 VBumpVolumeUsage(Volume * vp)
6705 VBumpVolumeUsage_r(vp);
6710 VSetDiskUsage_r(void)
6712 #ifndef AFS_DEMAND_ATTACH_FS
6713 static int FifteenMinuteCounter = 0;
6717 /* NOTE: Don't attempt to access the partitions list until the
6718 * initialization level indicates that all volumes are attached,
6719 * which implies that all partitions are initialized. */
6720 #ifdef AFS_PTHREAD_ENV
6721 VOL_CV_WAIT(&vol_vinit_cond);
6722 #else /* AFS_PTHREAD_ENV */
6724 #endif /* AFS_PTHREAD_ENV */
6727 VResetDiskUsage_r();
6729 #ifndef AFS_DEMAND_ATTACH_FS
6730 if (++FifteenMinuteCounter == 3) {
6731 FifteenMinuteCounter = 0;
6734 #endif /* !AFS_DEMAND_ATTACH_FS */
6746 /***************************************************/
6747 /* Volume Update List routines */
6748 /***************************************************/
6750 /* The number of minutes that a volume hasn't been updated before the
6751 * "Dont salvage" flag in the volume header will be turned on */
6752 #define SALVAGE_INTERVAL (10*60)
6757 * volume update list functionality has been moved into the VLRU
6758 * the DONT_SALVAGE flag is now set during VLRU demotion
6761 #ifndef AFS_DEMAND_ATTACH_FS
6762 static VolumeId *UpdateList = NULL; /* Pointer to array of Volume ID's */
6763 static int nUpdatedVolumes = 0; /* Updated with entry in UpdateList, salvage after crash flag on */
6764 static int updateSize = 0; /* number of entries possible */
6765 #define UPDATE_LIST_SIZE 128 /* initial size increment (must be a power of 2!) */
6766 #endif /* !AFS_DEMAND_ATTACH_FS */
6769 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
6772 vp->updateTime = FT_ApproxTime();
6773 if (V_dontSalvage(vp) == 0)
6775 V_dontSalvage(vp) = 0;
6776 VSyncVolume_r(ec, vp, 0);
6777 #ifdef AFS_DEMAND_ATTACH_FS
6778 V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
6779 #else /* !AFS_DEMAND_ATTACH_FS */
6782 if (UpdateList == NULL) {
6783 updateSize = UPDATE_LIST_SIZE;
6784 UpdateList = (VolumeId *) malloc(sizeof(VolumeId) * updateSize);
6786 if (nUpdatedVolumes == updateSize) {
6788 if (updateSize > 524288) {
6789 Log("warning: there is likely a bug in the volume update scanner\n");
6793 (VolumeId *) realloc(UpdateList,
6794 sizeof(VolumeId) * updateSize);
6797 osi_Assert(UpdateList != NULL);
6798 UpdateList[nUpdatedVolumes++] = V_id(vp);
6799 #endif /* !AFS_DEMAND_ATTACH_FS */
6802 #ifndef AFS_DEMAND_ATTACH_FS
6804 VScanUpdateList(void)
6809 afs_uint32 now = FT_ApproxTime();
6810 /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
6811 for (i = gap = 0; i < nUpdatedVolumes; i++) {
6813 UpdateList[i - gap] = UpdateList[i];
6815 /* XXX this routine needlessly messes up the Volume LRU by
6816 * breaking the LRU temporal-locality assumptions.....
6817 * we should use a special volume header allocator here */
6818 vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
6821 } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
6822 V_dontSalvage(vp) = DONT_SALVAGE;
6823 VUpdateVolume_r(&error, vp, 0); /* No need to fsync--not critical */
6831 #ifndef AFS_PTHREAD_ENV
6833 #endif /* !AFS_PTHREAD_ENV */
6835 nUpdatedVolumes -= gap;
6837 #endif /* !AFS_DEMAND_ATTACH_FS */
6840 /***************************************************/
6841 /* Volume LRU routines */
6842 /***************************************************/
6847 * with demand attach fs, we attempt to soft detach(1)
6848 * volumes which have not been accessed in a long time
6849 * in order to speed up fileserver shutdown
6851 * (1) by soft detach we mean a process very similar
6852 * to VOffline, except the final state of the
6853 * Volume will be VOL_STATE_PREATTACHED, instead
6854 * of the usual VOL_STATE_UNATTACHED
6856 #ifdef AFS_DEMAND_ATTACH_FS
6858 /* implementation is reminiscent of a generational GC
6860 * queue 0 is newly attached volumes. this queue is
6861 * sorted by attach timestamp
6863 * queue 1 is volumes that have been around a bit
6864 * longer than queue 0. this queue is sorted by
6867 * queue 2 is volumes tha have been around the longest.
6868 * this queue is unsorted
6870 * queue 3 is volumes that have been marked as
6871 * candidates for soft detachment. this queue is
6874 #define VLRU_GENERATIONS 3 /**< number of generations in VLRU */
6875 #define VLRU_QUEUES 5 /**< total number of VLRU queues */
6878 * definition of a VLRU queue.
6881 volatile struct rx_queue q;
6888 * main VLRU data structure.
6891 struct VLRU_q q[VLRU_QUEUES]; /**< VLRU queues */
6894 /** time interval (in seconds) between promotion passes for
6895 * each young generation queue. */
6896 afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
6898 /** time interval (in seconds) between soft detach candidate
6899 * scans for each generation queue.
6901 * scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
6902 * we perform a soft detach pass. */
6903 afs_uint32 scan_interval[VLRU_GENERATIONS+1];
6905 /* scheduler state */
6906 int next_idx; /**< next queue to receive attention */
6907 afs_uint32 last_promotion[VLRU_GENERATIONS-1]; /**< timestamp of last promotion scan */
6908 afs_uint32 last_scan[VLRU_GENERATIONS+1]; /**< timestamp of last detach scan */
6910 int scanner_state; /**< state of scanner thread */
6911 pthread_cond_t cv; /**< state transition CV */
6914 /** global VLRU state */
6915 static struct VLRU volume_LRU;
6918 * defined states for VLRU scanner thread.
6921 VLRU_SCANNER_STATE_OFFLINE = 0, /**< vlru scanner thread is offline */
6922 VLRU_SCANNER_STATE_ONLINE = 1, /**< vlru scanner thread is online */
6923 VLRU_SCANNER_STATE_SHUTTING_DOWN = 2, /**< vlru scanner thread is shutting down */
6924 VLRU_SCANNER_STATE_PAUSING = 3, /**< vlru scanner thread is getting ready to pause */
6925 VLRU_SCANNER_STATE_PAUSED = 4 /**< vlru scanner thread is paused */
6926 } vlru_thread_state_t;
6928 /* vlru disk data header stuff */
6929 #define VLRU_DISK_MAGIC 0x7a8b9cad /**< vlru disk entry magic number */
6930 #define VLRU_DISK_VERSION 1 /**< vlru disk entry version number */
6932 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
6933 #define VLRU_DUMP_EXPIRATION_TIME (60*60*24*7) /* expire vlru data after 1 week */
6936 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
6937 * soft detachment. */
6938 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
6940 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
6941 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
6943 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
6944 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
6946 /** VLRU control flag. non-zero value implies VLRU subsystem is activated. */
6947 static afs_uint32 VLRU_enabled = 1;
6949 /* queue synchronization routines */
6950 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
6951 static void VLRU_EndExclusive_r(struct VLRU_q * q);
6952 static void VLRU_Wait_r(struct VLRU_q * q);
6955 * set VLRU subsystem tunable parameters.
6957 * @param[in] option tunable option to modify
6958 * @param[in] val new value for tunable parameter
6960 * @pre @c VInitVolumePackage2 has not yet been called.
6962 * @post tunable parameter is modified
6966 * @note valid option parameters are:
6967 * @arg @c VLRU_SET_THRESH
6968 * set the period of inactivity after which
6969 * volumes are eligible for soft detachment
6970 * @arg @c VLRU_SET_INTERVAL
6971 * set the time interval between calls
6972 * to the volume LRU "garbage collector"
6973 * @arg @c VLRU_SET_MAX
6974 * set the max number of volumes to deallocate
6978 VLRU_SetOptions(int option, afs_uint32 val)
6980 if (option == VLRU_SET_THRESH) {
6981 VLRU_offline_thresh = val;
6982 } else if (option == VLRU_SET_INTERVAL) {
6983 VLRU_offline_interval = val;
6984 } else if (option == VLRU_SET_MAX) {
6985 VLRU_offline_max = val;
6986 } else if (option == VLRU_SET_ENABLED) {
6989 VLRU_ComputeConstants();
6993 * compute VLRU internal timing parameters.
6995 * @post VLRU scanner thread internal timing parameters are computed
6997 * @note computes internal timing parameters based upon user-modifiable
6998 * tunable parameters.
7002 * @internal volume package internal use only.
7005 VLRU_ComputeConstants(void)
7007 afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
7009 /* compute the candidate scan interval */
7010 volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
7012 /* compute the promotion intervals */
7013 volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
7014 volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
7017 /* compute the gen 0 scan interval */
7018 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
7020 /* compute the gen 0 scan interval */
7021 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
7026 * initialize VLRU subsystem.
7028 * @pre this function has not yet been called
7030 * @post VLRU subsystem is initialized and VLRU scanner thread is starting
7034 * @internal volume package internal use only.
7040 pthread_attr_t attrs;
7043 if (!VLRU_enabled) {
7044 Log("VLRU: disabled\n");
7048 /* initialize each of the VLRU queues */
7049 for (i = 0; i < VLRU_QUEUES; i++) {
7050 queue_Init(&volume_LRU.q[i]);
7051 volume_LRU.q[i].len = 0;
7052 volume_LRU.q[i].busy = 0;
7053 CV_INIT(&volume_LRU.q[i].cv, "vol lru", CV_DEFAULT, 0);
7056 /* setup the timing constants */
7057 VLRU_ComputeConstants();
7059 /* XXX put inside LogLevel check? */
7060 Log("VLRU: starting scanner with the following configuration parameters:\n");
7061 Log("VLRU: offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
7062 Log("VLRU: running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
7063 Log("VLRU: taking up to %d volumes offline per pass\n", VLRU_offline_max);
7064 Log("VLRU: scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
7065 Log("VLRU: scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
7066 Log("VLRU: scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
7068 /* start up the VLRU scanner */
7069 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7070 if (programType == fileServer) {
7071 CV_INIT(&volume_LRU.cv, "vol lru", CV_DEFAULT, 0);
7072 osi_Assert(pthread_attr_init(&attrs) == 0);
7073 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
7074 osi_Assert(pthread_create(&tid, &attrs, &VLRU_ScannerThread, NULL) == 0);
7079 * initialize the VLRU-related fields of a newly allocated volume object.
7081 * @param[in] vp pointer to volume object
7084 * @arg @c VOL_LOCK is held.
7085 * @arg volume object is not on a VLRU queue.
7087 * @post VLRU fields are initialized to indicate that volume object is not
7088 * currently registered with the VLRU subsystem
7092 * @internal volume package interal use only.
7095 VLRU_Init_Node_r(Volume * vp)
7100 osi_Assert(queue_IsNotOnQueue(&vp->vlru));
7101 vp->vlru.idx = VLRU_QUEUE_INVALID;
7105 * add a volume object to a VLRU queue.
7107 * @param[in] vp pointer to volume object
7110 * @arg @c VOL_LOCK is held.
7111 * @arg caller MUST hold a lightweight ref on @p vp.
7112 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7114 * @post the volume object is added to the appropriate VLRU queue
7116 * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
7117 * then the volume is added to that queue. Otherwise, the value
7118 * @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
7119 * volume is added to the NEW generation queue.
7121 * @note @c VOL_LOCK may be dropped internally
7123 * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
7124 * during the add operation, and is restored to the previous
7125 * state prior to return.
7129 * @internal volume package internal use only.
7132 VLRU_Add_r(Volume * vp)
7135 VolState state_save;
7140 if (queue_IsOnQueue(&vp->vlru))
7143 state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
7146 if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
7147 idx = VLRU_QUEUE_NEW;
7150 VLRU_Wait_r(&volume_LRU.q[idx]);
7152 /* repeat check since VLRU_Wait_r may have dropped
7154 if (queue_IsNotOnQueue(&vp->vlru)) {
7156 queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
7157 volume_LRU.q[idx].len++;
7158 V_attachFlags(vp) |= VOL_ON_VLRU;
7159 vp->stats.last_promote = FT_ApproxTime();
7162 VChangeState_r(vp, state_save);
7166 * delete a volume object from a VLRU queue.
7168 * @param[in] vp pointer to volume object
7171 * @arg @c VOL_LOCK is held.
7172 * @arg caller MUST hold a lightweight ref on @p vp.
7173 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7175 * @post volume object is removed from the VLRU queue
7177 * @note @c VOL_LOCK may be dropped internally
7181 * @todo We should probably set volume state to something exlcusive
7182 * (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
7184 * @internal volume package internal use only.
7187 VLRU_Delete_r(Volume * vp)
7194 if (queue_IsNotOnQueue(&vp->vlru))
7200 if (idx == VLRU_QUEUE_INVALID)
7202 VLRU_Wait_r(&volume_LRU.q[idx]);
7203 } while (idx != vp->vlru.idx);
7205 /* now remove from the VLRU and update
7206 * the appropriate counter */
7207 queue_Remove(&vp->vlru);
7208 volume_LRU.q[idx].len--;
7209 vp->vlru.idx = VLRU_QUEUE_INVALID;
7210 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7214 * tell the VLRU subsystem that a volume was just accessed.
7216 * @param[in] vp pointer to volume object
7219 * @arg @c VOL_LOCK is held
7220 * @arg caller MUST hold a lightweight ref on @p vp
7221 * @arg caller MUST NOT hold exclusive ownership of any VLRU queue
7223 * @post volume VLRU access statistics are updated. If the volume was on
7224 * the VLRU soft detach candidate queue, it is moved to the NEW
7227 * @note @c VOL_LOCK may be dropped internally
7231 * @internal volume package internal use only.
7234 VLRU_UpdateAccess_r(Volume * vp)
7236 Volume * rvp = NULL;
7241 if (queue_IsNotOnQueue(&vp->vlru))
7244 osi_Assert(V_attachFlags(vp) & VOL_ON_VLRU);
7246 /* update the access timestamp */
7247 vp->stats.last_get = FT_ApproxTime();
7250 * if the volume is on the soft detach candidate
7251 * list, we need to safely move it back to a
7252 * regular generation. this has to be done
7253 * carefully so we don't race against the scanner
7257 /* if this volume is on the soft detach candidate queue,
7258 * then grab exclusive access to the necessary queues */
7259 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7261 VCreateReservation_r(rvp);
7263 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7264 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7265 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7266 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7269 /* make sure multiple threads don't race to update */
7270 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7271 VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
7275 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7276 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7277 VCancelReservation_r(rvp);
7282 * switch a volume between two VLRU queues.
7284 * @param[in] vp pointer to volume object
7285 * @param[in] new_idx index of VLRU queue onto which the volume will be moved
7286 * @param[in] append controls whether the volume will be appended or
7287 * prepended to the queue. A nonzero value means it will
7288 * be appended; zero means it will be prepended.
7290 * @pre The new (and old, if applicable) queue(s) must either be owned
7291 * exclusively by the calling thread for asynchronous manipulation,
7292 * or the queue(s) must be quiescent and VOL_LOCK must be held.
7293 * Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
7294 * for further details of the queue asynchronous processing mechanism.
7296 * @post If the volume object was already on a VLRU queue, it is
7297 * removed from the queue. Depending on the value of the append
7298 * parameter, the volume object is either appended or prepended
7299 * to the VLRU queue referenced by the new_idx parameter.
7303 * @see VLRU_BeginExclusive_r
7304 * @see VLRU_EndExclusive_r
7307 * @internal volume package internal use only.
7310 VLRU_SwitchQueues(Volume * vp, int new_idx, int append)
7312 if (queue_IsNotOnQueue(&vp->vlru))
7315 queue_Remove(&vp->vlru);
7316 volume_LRU.q[vp->vlru.idx].len--;
7318 /* put the volume back on the correct generational queue */
7320 queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
7322 queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
7325 volume_LRU.q[new_idx].len++;
7326 vp->vlru.idx = new_idx;
7330 * VLRU background thread.
7332 * The VLRU Scanner Thread is responsible for periodically scanning through
7333 * each VLRU queue looking for volumes which should be moved to another
7334 * queue, or soft detached.
7336 * @param[in] args unused thread arguments parameter
7338 * @return unused thread return value
7339 * @retval NULL always
7341 * @internal volume package internal use only.
7344 VLRU_ScannerThread(void * args)
7346 afs_uint32 now, min_delay, delay;
7347 int i, min_idx, min_op, overdue, state;
7349 /* set t=0 for promotion cycle to be
7350 * fileserver startup */
7351 now = FT_ApproxTime();
7352 for (i=0; i < VLRU_GENERATIONS-1; i++) {
7353 volume_LRU.last_promotion[i] = now;
7356 /* don't start the scanner until VLRU_offline_thresh
7357 * plus a small delay for VInitVolumePackage2 to finish
7360 sleep(VLRU_offline_thresh + 60);
7362 /* set t=0 for scan cycle to be now */
7363 now = FT_ApproxTime();
7364 for (i=0; i < VLRU_GENERATIONS+1; i++) {
7365 volume_LRU.last_scan[i] = now;
7369 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
7370 volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
7373 while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
7374 /* check to see if we've been asked to pause */
7375 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
7376 volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
7377 CV_BROADCAST(&volume_LRU.cv);
7379 VOL_CV_WAIT(&volume_LRU.cv);
7380 } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
7383 /* scheduling can happen outside the glock */
7386 /* figure out what is next on the schedule */
7388 /* figure out a potential schedule for the new generation first */
7390 min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
7393 if (min_delay > volume_LRU.scan_interval[0]) {
7394 /* unsigned overflow -- we're overdue to run this scan */
7399 /* if we're not overdue for gen 0, figure out schedule for candidate gen */
7401 i = VLRU_QUEUE_CANDIDATE;
7402 delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
7403 if (delay < min_delay) {
7407 if (delay > volume_LRU.scan_interval[i]) {
7408 /* unsigned overflow -- we're overdue to run this scan */
7415 /* if we're still not overdue for something, figure out schedules for promotions */
7416 for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
7417 delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
7418 if (delay < min_delay) {
7423 if (delay > volume_LRU.promotion_interval[i]) {
7424 /* unsigned overflow -- we're overdue to run this promotion */
7433 /* sleep as needed */
7438 /* do whatever is next */
7441 VLRU_Promote_r(min_idx);
7442 VLRU_Demote_r(min_idx+1);
7444 VLRU_Scan_r(min_idx);
7446 now = FT_ApproxTime();
7449 Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
7451 /* signal that scanner is down */
7452 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7453 CV_BROADCAST(&volume_LRU.cv);
7459 * promote volumes from one VLRU generation to the next.
7461 * This routine scans a VLRU generation looking for volumes which are
7462 * eligible to be promoted to the next generation. All volumes which
7463 * meet the eligibility requirement are promoted.
7465 * Promotion eligibility is based upon meeting both of the following
7468 * @arg The volume has been accessed since the last promotion:
7469 * @c (vp->stats.last_get >= vp->stats.last_promote)
7470 * @arg The last promotion occurred at least
7471 * @c volume_LRU.promotion_interval[idx] seconds ago
7473 * As a performance optimization, promotions are "globbed". In other
7474 * words, we promote arbitrarily large contiguous sublists of elements
7477 * @param[in] idx VLRU queue index to scan
7481 * @internal VLRU internal use only.
7484 VLRU_Promote_r(int idx)
7486 int len, chaining, promote;
7487 afs_uint32 now, thresh;
7488 struct rx_queue *qp, *nqp;
7489 Volume * vp, *start = NULL, *end = NULL;
7491 /* get exclusive access to two chains, and drop the glock */
7492 VLRU_Wait_r(&volume_LRU.q[idx]);
7493 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7494 VLRU_Wait_r(&volume_LRU.q[idx+1]);
7495 VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
7498 thresh = volume_LRU.promotion_interval[idx];
7499 now = FT_ApproxTime();
7502 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7503 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7504 promote = (((vp->stats.last_promote + thresh) <= now) &&
7505 (vp->stats.last_get >= vp->stats.last_promote));
7513 /* promote and prepend chain */
7514 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7528 /* promote and prepend */
7529 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7533 volume_LRU.q[idx].len -= len;
7534 volume_LRU.q[idx+1].len += len;
7537 /* release exclusive access to the two chains */
7539 volume_LRU.last_promotion[idx] = now;
7540 VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
7541 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7544 /* run the demotions */
7546 VLRU_Demote_r(int idx)
7549 int len, chaining, demote;
7550 afs_uint32 now, thresh;
7551 struct rx_queue *qp, *nqp;
7552 Volume * vp, *start = NULL, *end = NULL;
7553 Volume ** salv_flag_vec = NULL;
7554 int salv_vec_offset = 0;
7556 osi_Assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
7558 /* get exclusive access to two chains, and drop the glock */
7559 VLRU_Wait_r(&volume_LRU.q[idx-1]);
7560 VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
7561 VLRU_Wait_r(&volume_LRU.q[idx]);
7562 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7565 /* no big deal if this allocation fails */
7566 if (volume_LRU.q[idx].len) {
7567 salv_flag_vec = (Volume **) malloc(volume_LRU.q[idx].len * sizeof(Volume *));
7570 now = FT_ApproxTime();
7571 thresh = volume_LRU.promotion_interval[idx-1];
7574 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7575 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7576 demote = (((vp->stats.last_promote + thresh) <= now) &&
7577 (vp->stats.last_get < (now - thresh)));
7579 /* we now do volume update list DONT_SALVAGE flag setting during
7580 * demotion passes */
7581 if (salv_flag_vec &&
7582 !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7584 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7585 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7586 salv_flag_vec[salv_vec_offset++] = vp;
7587 VCreateReservation_r(vp);
7596 /* demote and append chain */
7597 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7611 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7615 volume_LRU.q[idx].len -= len;
7616 volume_LRU.q[idx-1].len += len;
7619 /* release exclusive access to the two chains */
7621 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7622 VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
7624 /* now go back and set the DONT_SALVAGE flags as appropriate */
7625 if (salv_flag_vec) {
7627 for (i = 0; i < salv_vec_offset; i++) {
7628 vp = salv_flag_vec[i];
7629 if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7630 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7631 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7634 V_attachFlags(vp) |= VOL_HDR_DONTSALV;
7635 V_dontSalvage(vp) = DONT_SALVAGE;
7636 VUpdateVolume_r(&ec, vp, 0);
7640 VCancelReservation_r(vp);
7642 free(salv_flag_vec);
7646 /* run a pass of the VLRU GC scanner */
7648 VLRU_Scan_r(int idx)
7650 afs_uint32 now, thresh;
7651 struct rx_queue *qp, *nqp;
7655 osi_Assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
7657 /* gain exclusive access to the idx VLRU */
7658 VLRU_Wait_r(&volume_LRU.q[idx]);
7659 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7661 if (idx != VLRU_QUEUE_CANDIDATE) {
7662 /* gain exclusive access to the candidate VLRU */
7663 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7664 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7667 now = FT_ApproxTime();
7668 thresh = now - VLRU_offline_thresh;
7670 /* perform candidate selection and soft detaching */
7671 if (idx == VLRU_QUEUE_CANDIDATE) {
7672 /* soft detach some volumes from the candidate pool */
7676 for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7677 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7678 if (i >= VLRU_offline_max) {
7681 /* check timestamp to see if it's a candidate for soft detaching */
7682 if (vp->stats.last_get <= thresh) {
7684 if (VCheckSoftDetach(vp, thresh))
7690 /* scan for volumes to become soft detach candidates */
7691 for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
7692 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7694 /* check timestamp to see if it's a candidate for soft detaching */
7695 if (vp->stats.last_get <= thresh) {
7696 VCheckSoftDetachCandidate(vp, thresh);
7699 if (!(i&0x7f)) { /* lock coarsening optimization */
7707 /* relinquish exclusive access to the VLRU chains */
7711 volume_LRU.last_scan[idx] = now;
7712 if (idx != VLRU_QUEUE_CANDIDATE) {
7713 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7715 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7718 /* check whether volume is safe to soft detach
7719 * caller MUST NOT hold a ref count on vp */
7721 VCheckSoftDetach(Volume * vp, afs_uint32 thresh)
7725 if (vp->nUsers || vp->nWaiters)
7728 if (vp->stats.last_get <= thresh) {
7729 ret = VSoftDetachVolume_r(vp, thresh);
7735 /* check whether volume should be made a
7736 * soft detach candidate */
7738 VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh)
7741 if (vp->nUsers || vp->nWaiters)
7746 osi_Assert(idx == VLRU_QUEUE_NEW);
7748 if (vp->stats.last_get <= thresh) {
7749 /* move to candidate pool */
7750 queue_Remove(&vp->vlru);
7751 volume_LRU.q[VLRU_QUEUE_NEW].len--;
7752 queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
7753 vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
7754 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
7762 /* begin exclusive access on VLRU */
7764 VLRU_BeginExclusive_r(struct VLRU_q * q)
7766 osi_Assert(q->busy == 0);
7770 /* end exclusive access on VLRU */
7772 VLRU_EndExclusive_r(struct VLRU_q * q)
7774 osi_Assert(q->busy);
7776 CV_BROADCAST(&q->cv);
7779 /* wait for another thread to end exclusive access on VLRU */
7781 VLRU_Wait_r(struct VLRU_q * q)
7784 VOL_CV_WAIT(&q->cv);
7789 * volume soft detach
7791 * caller MUST NOT hold a ref count on vp */
7793 VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh)
7798 osi_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7800 ts_save = vp->stats.last_get;
7801 if (ts_save > thresh)
7804 if (vp->nUsers || vp->nWaiters)
7807 if (VIsExclusiveState(V_attachState(vp))) {
7811 switch (V_attachState(vp)) {
7812 case VOL_STATE_UNATTACHED:
7813 case VOL_STATE_PREATTACHED:
7814 case VOL_STATE_ERROR:
7815 case VOL_STATE_GOING_OFFLINE:
7816 case VOL_STATE_SHUTTING_DOWN:
7817 case VOL_STATE_SALVAGING:
7818 case VOL_STATE_DELETED:
7819 volume_LRU.q[vp->vlru.idx].len--;
7821 /* create and cancel a reservation to
7822 * give the volume an opportunity to
7824 VCreateReservation_r(vp);
7825 queue_Remove(&vp->vlru);
7826 vp->vlru.idx = VLRU_QUEUE_INVALID;
7827 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7828 VCancelReservation_r(vp);
7834 /* hold the volume and take it offline.
7835 * no need for reservations, as VHold_r
7836 * takes care of that internally. */
7837 if (VHold_r(vp) == 0) {
7838 /* vhold drops the glock, so now we should
7839 * check to make sure we aren't racing against
7840 * other threads. if we are racing, offlining vp
7841 * would be wasteful, and block the scanner for a while
7845 (vp->shuttingDown) ||
7846 (vp->goingOffline) ||
7847 (vp->stats.last_get != ts_save)) {
7848 /* looks like we're racing someone else. bail */
7852 /* pull it off the VLRU */
7853 osi_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7854 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
7855 queue_Remove(&vp->vlru);
7856 vp->vlru.idx = VLRU_QUEUE_INVALID;
7857 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7859 /* take if offline */
7860 VOffline_r(vp, "volume has been soft detached");
7862 /* invalidate the volume header cache */
7863 FreeVolumeHeader(vp);
7866 IncUInt64(&VStats.soft_detaches);
7867 vp->stats.soft_detaches++;
7869 /* put in pre-attached state so demand
7870 * attacher can work on it */
7871 VChangeState_r(vp, VOL_STATE_PREATTACHED);
7877 #endif /* AFS_DEMAND_ATTACH_FS */
7880 /***************************************************/
7881 /* Volume Header Cache routines */
7882 /***************************************************/
7885 * volume header cache.
7887 struct volume_hdr_LRU_t volume_hdr_LRU;
7890 * initialize the volume header cache.
7892 * @param[in] howMany number of header cache entries to preallocate
7894 * @pre VOL_LOCK held. Function has never been called before.
7896 * @post howMany cache entries are allocated, initialized, and added
7897 * to the LRU list. Header cache statistics are initialized.
7899 * @note only applicable to fileServer program type. Should only be
7900 * called once during volume package initialization.
7902 * @internal volume package internal use only.
7905 VInitVolumeHeaderCache(afs_uint32 howMany)
7907 struct volHeader *hp;
7908 if (programType != fileServer)
7910 queue_Init(&volume_hdr_LRU);
7911 volume_hdr_LRU.stats.free = 0;
7912 volume_hdr_LRU.stats.used = howMany;
7913 volume_hdr_LRU.stats.attached = 0;
7914 hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
7915 osi_Assert(hp != NULL);
7918 /* We are using ReleaseVolumeHeader to initialize the values on the header list
7919 * to ensure they have the right values
7921 ReleaseVolumeHeader(hp++);
7925 * get a volume header and attach it to the volume object.
7927 * @param[in] vp pointer to volume object
7929 * @return cache entry status
7930 * @retval 0 volume header was newly attached; cache data is invalid
7931 * @retval 1 volume header was previously attached; cache data is valid
7933 * @pre VOL_LOCK held. For DAFS, lightweight ref must be held on volume object.
7935 * @post volume header attached to volume object. if necessary, header cache
7936 * entry on LRU is synchronized to disk. Header is removed from LRU list.
7938 * @note VOL_LOCK may be dropped
7940 * @warning this interface does not load header data from disk. it merely
7941 * attaches a header object to the volume object, and may sync the old
7942 * header cache data out to disk in the process.
7944 * @internal volume package internal use only.
7947 GetVolumeHeader(Volume * vp)
7950 struct volHeader *hd;
7952 static int everLogged = 0;
7954 #ifdef AFS_DEMAND_ATTACH_FS
7955 VolState vp_save = 0, back_save = 0;
7957 /* XXX debug 9/19/05 we've apparently got
7958 * a ref counting bug somewhere that's
7959 * breaking the nUsers == 0 => header on LRU
7961 if (vp->header && queue_IsNotOnQueue(vp->header)) {
7962 Log("nUsers == 0, but header not on LRU\n");
7967 old = (vp->header != NULL); /* old == volume already has a header */
7969 if (programType != fileServer) {
7970 /* for volume utilities, we allocate volHeaders as needed */
7972 hd = (struct volHeader *)calloc(1, sizeof(*vp->header));
7973 osi_Assert(hd != NULL);
7976 #ifdef AFS_DEMAND_ATTACH_FS
7977 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
7981 /* for the fileserver, we keep a volume header cache */
7983 /* the header we previously dropped in the lru is
7984 * still available. pull it off the lru and return */
7987 osi_Assert(hd->back == vp);
7988 #ifdef AFS_DEMAND_ATTACH_FS
7989 V_attachFlags(vp) &= ~(VOL_HDR_IN_LRU);
7992 /* we need to grab a new element off the LRU */
7993 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
7994 /* grab an element and pull off of LRU */
7995 hd = queue_First(&volume_hdr_LRU, volHeader);
7998 /* LRU is empty, so allocate a new volHeader
7999 * this is probably indicative of a leak, so let the user know */
8000 hd = (struct volHeader *)calloc(1, sizeof(struct volHeader));
8001 osi_Assert(hd != NULL);
8003 Log("****Allocated more volume headers, probably leak****\n");
8006 volume_hdr_LRU.stats.free++;
8009 /* this header used to belong to someone else.
8010 * we'll need to check if the header needs to
8011 * be sync'd out to disk */
8013 #ifdef AFS_DEMAND_ATTACH_FS
8014 /* if hd->back were in an exclusive state, then
8015 * its volHeader would not be on the LRU... */
8016 osi_Assert(!VIsExclusiveState(V_attachState(hd->back)));
8019 if (hd->diskstuff.inUse) {
8020 /* volume was in use, so we'll need to sync
8021 * its header to disk */
8023 #ifdef AFS_DEMAND_ATTACH_FS
8024 back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
8025 vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
8026 VCreateReservation_r(hd->back);
8030 WriteVolumeHeader_r(&error, hd->back);
8031 /* Ignore errors; catch them later */
8033 #ifdef AFS_DEMAND_ATTACH_FS
8038 hd->back->header = NULL;
8039 #ifdef AFS_DEMAND_ATTACH_FS
8040 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
8042 if (hd->diskstuff.inUse) {
8043 VChangeState_r(hd->back, back_save);
8044 VCancelReservation_r(hd->back);
8045 VChangeState_r(vp, vp_save);
8049 volume_hdr_LRU.stats.attached++;
8053 #ifdef AFS_DEMAND_ATTACH_FS
8054 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8057 volume_hdr_LRU.stats.free--;
8058 volume_hdr_LRU.stats.used++;
8060 IncUInt64(&VStats.hdr_gets);
8061 #ifdef AFS_DEMAND_ATTACH_FS
8062 IncUInt64(&vp->stats.hdr_gets);
8063 vp->stats.last_hdr_get = FT_ApproxTime();
8070 * make sure volume header is attached and contains valid cache data.
8072 * @param[out] ec outbound error code
8073 * @param[in] vp pointer to volume object
8075 * @pre VOL_LOCK held. For DAFS, lightweight ref held on vp.
8077 * @post header cache entry attached, and loaded with valid data, or
8078 * *ec is nonzero, and the header is released back into the LRU.
8080 * @internal volume package internal use only.
8083 LoadVolumeHeader(Error * ec, Volume * vp)
8085 #ifdef AFS_DEMAND_ATTACH_FS
8086 VolState state_save;
8090 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8091 IncUInt64(&VStats.hdr_loads);
8092 state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
8095 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8096 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8098 IncUInt64(&vp->stats.hdr_loads);
8099 now = FT_ApproxTime();
8103 V_attachFlags(vp) |= VOL_HDR_LOADED;
8104 vp->stats.last_hdr_load = now;
8106 VChangeState_r(vp, state_save);
8108 #else /* AFS_DEMAND_ATTACH_FS */
8110 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8111 IncUInt64(&VStats.hdr_loads);
8113 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8114 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8117 #endif /* AFS_DEMAND_ATTACH_FS */
8119 /* maintain (nUsers==0) => header in LRU invariant */
8120 FreeVolumeHeader(vp);
8125 * release a header cache entry back into the LRU list.
8127 * @param[in] hd pointer to volume header cache object
8129 * @pre VOL_LOCK held.
8131 * @post header cache object appended onto end of LRU list.
8133 * @note only applicable to fileServer program type.
8135 * @note used to place a header cache entry back into the
8136 * LRU pool without invalidating it as a cache entry.
8138 * @internal volume package internal use only.
8141 ReleaseVolumeHeader(struct volHeader *hd)
8143 if (programType != fileServer)
8145 if (!hd || queue_IsOnQueue(hd)) /* no header, or header already released */
8147 queue_Append(&volume_hdr_LRU, hd);
8148 #ifdef AFS_DEMAND_ATTACH_FS
8150 V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
8153 volume_hdr_LRU.stats.free++;
8154 volume_hdr_LRU.stats.used--;
8158 * free/invalidate a volume header cache entry.
8160 * @param[in] vp pointer to volume object
8162 * @pre VOL_LOCK is held.
8164 * @post For fileserver, header cache entry is returned to LRU, and it is
8165 * invalidated as a cache entry. For volume utilities, the header
8166 * cache entry is freed.
8168 * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
8169 * whenever it is necessary to invalidate the header cache entry.
8171 * @see ReleaseVolumeHeader
8173 * @internal volume package internal use only.
8176 FreeVolumeHeader(Volume * vp)
8178 struct volHeader *hd = vp->header;
8181 if (programType == fileServer) {
8182 ReleaseVolumeHeader(hd);
8187 #ifdef AFS_DEMAND_ATTACH_FS
8188 V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
8190 volume_hdr_LRU.stats.attached--;
8195 /***************************************************/
8196 /* Volume Hash Table routines */
8197 /***************************************************/
8200 * set size of volume object hash table.
8202 * @param[in] logsize log(2) of desired hash table size
8204 * @return operation status
8206 * @retval -1 failure
8208 * @pre MUST be called prior to VInitVolumePackage2
8210 * @post Volume Hash Table will have 2^logsize buckets
8213 VSetVolHashSize(int logsize)
8215 /* 64 to 268435456 hash buckets seems like a reasonable range */
8216 if ((logsize < 6 ) || (logsize > 28)) {
8221 VolumeHashTable.Size = 1 << logsize;
8222 VolumeHashTable.Mask = VolumeHashTable.Size - 1;
8224 /* we can't yet support runtime modification of this
8225 * parameter. we'll need a configuration rwlock to
8226 * make runtime modification feasible.... */
8233 * initialize dynamic data structures for volume hash table.
8235 * @post hash table is allocated, and fields are initialized.
8237 * @internal volume package internal use only.
8240 VInitVolumeHash(void)
8244 VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
8245 sizeof(VolumeHashChainHead));
8246 osi_Assert(VolumeHashTable.Table != NULL);
8248 for (i=0; i < VolumeHashTable.Size; i++) {
8249 queue_Init(&VolumeHashTable.Table[i]);
8250 #ifdef AFS_DEMAND_ATTACH_FS
8251 CV_INIT(&VolumeHashTable.Table[i].chain_busy_cv, "vhash busy", CV_DEFAULT, 0);
8252 #endif /* AFS_DEMAND_ATTACH_FS */
8257 * add a volume object to the hash table.
8259 * @param[in] vp pointer to volume object
8260 * @param[in] hashid hash of volume id
8262 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8265 * @post volume is added to hash chain.
8267 * @internal volume package internal use only.
8269 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8270 * asynchronous hash chain reordering to finish.
8273 AddVolumeToHashTable(Volume * vp, int hashid)
8275 VolumeHashChainHead * head;
8277 if (queue_IsOnQueue(vp))
8280 head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
8282 #ifdef AFS_DEMAND_ATTACH_FS
8283 /* wait for the hash chain to become available */
8286 V_attachFlags(vp) |= VOL_IN_HASH;
8287 vp->chainCacheCheck = ++head->cacheCheck;
8288 #endif /* AFS_DEMAND_ATTACH_FS */
8291 vp->hashid = hashid;
8292 queue_Append(head, vp);
8293 vp->vnodeHashOffset = VolumeHashOffset_r();
8297 * delete a volume object from the hash table.
8299 * @param[in] vp pointer to volume object
8301 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8304 * @post volume is removed from hash chain.
8306 * @internal volume package internal use only.
8308 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8309 * asynchronous hash chain reordering to finish.
8312 DeleteVolumeFromHashTable(Volume * vp)
8314 VolumeHashChainHead * head;
8316 if (!queue_IsOnQueue(vp))
8319 head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
8321 #ifdef AFS_DEMAND_ATTACH_FS
8322 /* wait for the hash chain to become available */
8325 V_attachFlags(vp) &= ~(VOL_IN_HASH);
8327 #endif /* AFS_DEMAND_ATTACH_FS */
8331 /* do NOT reset hashid to zero, as the online
8332 * salvager package may need to know the volume id
8333 * after the volume is removed from the hash */
8337 * lookup a volume object in the hash table given a volume id.
8339 * @param[out] ec error code return
8340 * @param[in] volumeId volume id
8341 * @param[in] hint volume object which we believe could be the correct
8344 * @return volume object pointer
8345 * @retval NULL no such volume id is registered with the hash table.
8347 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8350 * @post volume object with the given id is returned. volume object and
8351 * hash chain access statistics are updated. hash chain may have
8354 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8355 * asynchronous hash chain reordering operation to finish, or
8356 * in order for us to perform an asynchronous chain reordering.
8358 * @note Hash chain reorderings occur when the access count for the
8359 * volume object being looked up exceeds the sum of the previous
8360 * node's (the node ahead of it in the hash chain linked list)
8361 * access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
8363 * @note For DAFS, the hint parameter allows us to short-circuit if the
8364 * cacheCheck fields match between the hash chain head and the
8365 * hint volume object.
8368 VLookupVolume_r(Error * ec, VolId volumeId, Volume * hint)
8372 #ifdef AFS_DEMAND_ATTACH_FS
8375 VolumeHashChainHead * head;
8378 head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
8380 #ifdef AFS_DEMAND_ATTACH_FS
8381 /* wait for the hash chain to become available */
8384 /* check to see if we can short circuit without walking the hash chain */
8385 if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
8386 IncUInt64(&hint->stats.hash_short_circuits);
8389 #endif /* AFS_DEMAND_ATTACH_FS */
8391 /* someday we need to either do per-chain locks, RWlocks,
8392 * or both for volhash access.
8393 * (and move to a data structure with better cache locality) */
8395 /* search the chain for this volume id */
8396 for(queue_Scan(head, vp, np, Volume)) {
8398 if ((vp->hashid == volumeId)) {
8403 if (queue_IsEnd(head, vp)) {
8407 #ifdef AFS_DEMAND_ATTACH_FS
8408 /* update hash chain statistics */
8411 FillInt64(lks, 0, looks);
8412 AddUInt64(head->looks, lks, &head->looks);
8413 AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
8414 IncUInt64(&head->gets);
8419 IncUInt64(&vp->stats.hash_lookups);
8421 /* for demand attach fileserver, we permit occasional hash chain reordering
8422 * so that frequently looked up volumes move towards the head of the chain */
8423 pp = queue_Prev(vp, Volume);
8424 if (!queue_IsEnd(head, pp)) {
8425 FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
8426 AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
8427 if (GEInt64(vp->stats.hash_lookups, thresh)) {
8428 VReorderHash_r(head, pp, vp);
8432 /* update the short-circuit cache check */
8433 vp->chainCacheCheck = head->cacheCheck;
8435 #endif /* AFS_DEMAND_ATTACH_FS */
8440 #ifdef AFS_DEMAND_ATTACH_FS
8441 /* perform volume hash chain reordering.
8443 * advance a subchain beginning at vp ahead of
8444 * the adjacent subchain ending at pp */
8446 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
8448 Volume *tp, *np, *lp;
8449 afs_uint64 move_thresh;
8451 /* this should never be called if the chain is already busy, so
8452 * no need to wait for other exclusive chain ops to finish */
8454 /* this is a rather heavy set of operations,
8455 * so let's set the chain busy flag and drop
8457 VHashBeginExclusive_r(head);
8460 /* scan forward in the chain from vp looking for the last element
8461 * in the chain we want to advance */
8462 FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
8463 AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
8464 for(queue_ScanFrom(head, vp, tp, np, Volume)) {
8465 if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
8469 lp = queue_Prev(tp, Volume);
8471 /* scan backwards from pp to determine where to splice and
8472 * insert the subchain we're advancing */
8473 for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
8474 if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
8478 tp = queue_Next(tp, Volume);
8480 /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
8481 queue_MoveChainBefore(tp,vp,lp);
8484 IncUInt64(&VStats.hash_reorders);
8486 IncUInt64(&head->reorders);
8488 /* wake up any threads waiting for the hash chain */
8489 VHashEndExclusive_r(head);
8493 /* demand-attach fs volume hash
8494 * asynchronous exclusive operations */
8497 * begin an asynchronous exclusive operation on a volume hash chain.
8499 * @param[in] head pointer to volume hash chain head object
8501 * @pre VOL_LOCK held. hash chain is quiescent.
8503 * @post hash chain marked busy.
8505 * @note this interface is used in conjunction with VHashEndExclusive_r and
8506 * VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8507 * volume hash chain. Its main use case is hash chain reordering, which
8508 * has the potential to be a highly latent operation.
8510 * @see VHashEndExclusive_r
8515 * @internal volume package internal use only.
8518 VHashBeginExclusive_r(VolumeHashChainHead * head)
8520 osi_Assert(head->busy == 0);
8525 * relinquish exclusive ownership of a volume hash chain.
8527 * @param[in] head pointer to volume hash chain head object
8529 * @pre VOL_LOCK held. thread owns the hash chain exclusively.
8531 * @post hash chain is marked quiescent. threads awaiting use of
8532 * chain are awakened.
8534 * @see VHashBeginExclusive_r
8539 * @internal volume package internal use only.
8542 VHashEndExclusive_r(VolumeHashChainHead * head)
8544 osi_Assert(head->busy);
8546 CV_BROADCAST(&head->chain_busy_cv);
8550 * wait for all asynchronous operations on a hash chain to complete.
8552 * @param[in] head pointer to volume hash chain head object
8554 * @pre VOL_LOCK held.
8556 * @post hash chain object is quiescent.
8558 * @see VHashBeginExclusive_r
8559 * @see VHashEndExclusive_r
8563 * @note This interface should be called before any attempt to
8564 * traverse the hash chain. It is permissible for a thread
8565 * to gain exclusive access to the chain, and then perform
8566 * latent operations on the chain asynchronously wrt the
8569 * @warning if waiting is necessary, VOL_LOCK is dropped
8571 * @internal volume package internal use only.
8574 VHashWait_r(VolumeHashChainHead * head)
8576 while (head->busy) {
8577 VOL_CV_WAIT(&head->chain_busy_cv);
8580 #endif /* AFS_DEMAND_ATTACH_FS */
8583 /***************************************************/
8584 /* Volume by Partition List routines */
8585 /***************************************************/
8588 * demand attach fileserver adds a
8589 * linked list of volumes to each
8590 * partition object, thus allowing
8591 * for quick enumeration of all
8592 * volumes on a partition
8595 #ifdef AFS_DEMAND_ATTACH_FS
8597 * add a volume to its disk partition VByPList.
8599 * @param[in] vp pointer to volume object
8601 * @pre either the disk partition VByPList is owned exclusively
8602 * by the calling thread, or the list is quiescent and
8605 * @post volume is added to disk partition VByPList
8609 * @warning it is the caller's responsibility to ensure list
8612 * @see VVByPListWait_r
8613 * @see VVByPListBeginExclusive_r
8614 * @see VVByPListEndExclusive_r
8616 * @internal volume package internal use only.
8619 AddVolumeToVByPList_r(Volume * vp)
8621 if (queue_IsNotOnQueue(&vp->vol_list)) {
8622 queue_Append(&vp->partition->vol_list, &vp->vol_list);
8623 V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
8624 vp->partition->vol_list.len++;
8629 * delete a volume from its disk partition VByPList.
8631 * @param[in] vp pointer to volume object
8633 * @pre either the disk partition VByPList is owned exclusively
8634 * by the calling thread, or the list is quiescent and
8637 * @post volume is removed from the disk partition VByPList
8641 * @warning it is the caller's responsibility to ensure list
8644 * @see VVByPListWait_r
8645 * @see VVByPListBeginExclusive_r
8646 * @see VVByPListEndExclusive_r
8648 * @internal volume package internal use only.
8651 DeleteVolumeFromVByPList_r(Volume * vp)
8653 if (queue_IsOnQueue(&vp->vol_list)) {
8654 queue_Remove(&vp->vol_list);
8655 V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
8656 vp->partition->vol_list.len--;
8661 * begin an asynchronous exclusive operation on a VByPList.
8663 * @param[in] dp pointer to disk partition object
8665 * @pre VOL_LOCK held. VByPList is quiescent.
8667 * @post VByPList marked busy.
8669 * @note this interface is used in conjunction with VVByPListEndExclusive_r and
8670 * VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8673 * @see VVByPListEndExclusive_r
8674 * @see VVByPListWait_r
8678 * @internal volume package internal use only.
8680 /* take exclusive control over the list */
8682 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
8684 osi_Assert(dp->vol_list.busy == 0);
8685 dp->vol_list.busy = 1;
8689 * relinquish exclusive ownership of a VByPList.
8691 * @param[in] dp pointer to disk partition object
8693 * @pre VOL_LOCK held. thread owns the VByPList exclusively.
8695 * @post VByPList is marked quiescent. threads awaiting use of
8696 * the list are awakened.
8698 * @see VVByPListBeginExclusive_r
8699 * @see VVByPListWait_r
8703 * @internal volume package internal use only.
8706 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
8708 osi_Assert(dp->vol_list.busy);
8709 dp->vol_list.busy = 0;
8710 CV_BROADCAST(&dp->vol_list.cv);
8714 * wait for all asynchronous operations on a VByPList to complete.
8716 * @param[in] dp pointer to disk partition object
8718 * @pre VOL_LOCK is held.
8720 * @post disk partition's VByP list is quiescent
8724 * @note This interface should be called before any attempt to
8725 * traverse the VByPList. It is permissible for a thread
8726 * to gain exclusive access to the list, and then perform
8727 * latent operations on the list asynchronously wrt the
8730 * @warning if waiting is necessary, VOL_LOCK is dropped
8732 * @see VVByPListEndExclusive_r
8733 * @see VVByPListBeginExclusive_r
8735 * @internal volume package internal use only.
8738 VVByPListWait_r(struct DiskPartition64 * dp)
8740 while (dp->vol_list.busy) {
8741 VOL_CV_WAIT(&dp->vol_list.cv);
8744 #endif /* AFS_DEMAND_ATTACH_FS */
8746 /***************************************************/
8747 /* Volume Cache Statistics routines */
8748 /***************************************************/
8751 VPrintCacheStats_r(void)
8753 afs_uint32 get_hi, get_lo, load_hi, load_lo;
8754 struct VnodeClassInfo *vcp;
8755 vcp = &VnodeClassInfo[vLarge];
8756 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);
8757 vcp = &VnodeClassInfo[vSmall];
8758 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);
8759 SplitInt64(VStats.hdr_gets, get_hi, get_lo);
8760 SplitInt64(VStats.hdr_loads, load_hi, load_lo);
8761 Log("Volume header cache, %d entries, %d gets, %d replacements\n",
8762 VStats.hdr_cache_size, get_lo, load_lo);
8766 VPrintCacheStats(void)
8769 VPrintCacheStats_r();
8773 #ifdef AFS_DEMAND_ATTACH_FS
8775 UInt64ToDouble(afs_uint64 * x)
8777 static double c32 = 4.0 * 1.073741824 * 1000000000.0;
8779 SplitInt64(*x, h, l);
8780 return (((double)h) * c32) + ((double) l);
8784 DoubleToPrintable(double x, char * buf, int len)
8786 static double billion = 1000000000.0;
8789 y[0] = (afs_uint32) (x / (billion * billion));
8790 y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
8791 y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
8794 snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
8796 snprintf(buf, len, "%d%09d", y[1], y[2]);
8798 snprintf(buf, len, "%d", y[2]);
8804 struct VLRUExtStatsEntry {
8808 struct VLRUExtStats {
8814 } queue_info[VLRU_QUEUE_INVALID];
8815 struct VLRUExtStatsEntry * vec;
8819 * add a 256-entry fudge factor onto the vector in case state changes
8820 * out from under us.
8822 #define VLRU_EXT_STATS_VEC_LEN_FUDGE 256
8825 * collect extended statistics for the VLRU subsystem.
8827 * @param[out] stats pointer to stats structure to be populated
8828 * @param[in] nvols number of volumes currently known to exist
8830 * @pre VOL_LOCK held
8832 * @post stats->vec allocated and populated
8834 * @return operation status
8839 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
8841 afs_uint32 cur, idx, len;
8842 struct rx_queue * qp, * nqp;
8844 struct VLRUExtStatsEntry * vec;
8846 len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
8847 vec = stats->vec = calloc(len,
8848 sizeof(struct VLRUExtStatsEntry));
8854 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
8855 VLRU_Wait_r(&volume_LRU.q[idx]);
8856 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
8859 stats->queue_info[idx].start = cur;
8861 for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
8863 /* out of space in vec */
8866 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
8867 vec[cur].volid = vp->hashid;
8871 stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
8874 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
8882 #define ENUMTOSTRING(en) #en
8883 #define ENUMCASE(en) \
8884 case en: return ENUMTOSTRING(en)
8887 vlru_idx_to_string(int idx)
8890 ENUMCASE(VLRU_QUEUE_NEW);
8891 ENUMCASE(VLRU_QUEUE_MID);
8892 ENUMCASE(VLRU_QUEUE_OLD);
8893 ENUMCASE(VLRU_QUEUE_CANDIDATE);
8894 ENUMCASE(VLRU_QUEUE_HELD);
8895 ENUMCASE(VLRU_QUEUE_INVALID);
8897 return "**UNKNOWN**";
8902 VPrintExtendedCacheStats_r(int flags)
8905 afs_uint32 vol_sum = 0;
8912 struct stats looks, gets, reorders, len;
8913 struct stats ch_looks, ch_gets, ch_reorders;
8915 VolumeHashChainHead *head;
8917 struct VLRUExtStats vlru_stats;
8919 /* zero out stats */
8920 memset(&looks, 0, sizeof(struct stats));
8921 memset(&gets, 0, sizeof(struct stats));
8922 memset(&reorders, 0, sizeof(struct stats));
8923 memset(&len, 0, sizeof(struct stats));
8924 memset(&ch_looks, 0, sizeof(struct stats));
8925 memset(&ch_gets, 0, sizeof(struct stats));
8926 memset(&ch_reorders, 0, sizeof(struct stats));
8928 for (i = 0; i < VolumeHashTable.Size; i++) {
8929 head = &VolumeHashTable.Table[i];
8932 VHashBeginExclusive_r(head);
8935 ch_looks.sum = UInt64ToDouble(&head->looks);
8936 ch_gets.sum = UInt64ToDouble(&head->gets);
8937 ch_reorders.sum = UInt64ToDouble(&head->reorders);
8939 /* update global statistics */
8941 looks.sum += ch_looks.sum;
8942 gets.sum += ch_gets.sum;
8943 reorders.sum += ch_reorders.sum;
8944 len.sum += (double)head->len;
8945 vol_sum += head->len;
8948 len.min = (double) head->len;
8949 len.max = (double) head->len;
8950 looks.min = ch_looks.sum;
8951 looks.max = ch_looks.sum;
8952 gets.min = ch_gets.sum;
8953 gets.max = ch_gets.sum;
8954 reorders.min = ch_reorders.sum;
8955 reorders.max = ch_reorders.sum;
8957 if (((double)head->len) < len.min)
8958 len.min = (double) head->len;
8959 if (((double)head->len) > len.max)
8960 len.max = (double) head->len;
8961 if (ch_looks.sum < looks.min)
8962 looks.min = ch_looks.sum;
8963 else if (ch_looks.sum > looks.max)
8964 looks.max = ch_looks.sum;
8965 if (ch_gets.sum < gets.min)
8966 gets.min = ch_gets.sum;
8967 else if (ch_gets.sum > gets.max)
8968 gets.max = ch_gets.sum;
8969 if (ch_reorders.sum < reorders.min)
8970 reorders.min = ch_reorders.sum;
8971 else if (ch_reorders.sum > reorders.max)
8972 reorders.max = ch_reorders.sum;
8976 if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
8977 /* compute detailed per-chain stats */
8978 struct stats hdr_loads, hdr_gets;
8979 double v_looks, v_loads, v_gets;
8981 /* initialize stats with data from first element in chain */
8982 vp = queue_First(head, Volume);
8983 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
8984 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
8985 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
8986 ch_gets.min = ch_gets.max = v_looks;
8987 hdr_loads.min = hdr_loads.max = v_loads;
8988 hdr_gets.min = hdr_gets.max = v_gets;
8989 hdr_loads.sum = hdr_gets.sum = 0;
8991 vp = queue_Next(vp, Volume);
8993 /* pull in stats from remaining elements in chain */
8994 for (queue_ScanFrom(head, vp, vp, np, Volume)) {
8995 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
8996 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
8997 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
8999 hdr_loads.sum += v_loads;
9000 hdr_gets.sum += v_gets;
9002 if (v_looks < ch_gets.min)
9003 ch_gets.min = v_looks;
9004 else if (v_looks > ch_gets.max)
9005 ch_gets.max = v_looks;
9007 if (v_loads < hdr_loads.min)
9008 hdr_loads.min = v_loads;
9009 else if (v_loads > hdr_loads.max)
9010 hdr_loads.max = v_loads;
9012 if (v_gets < hdr_gets.min)
9013 hdr_gets.min = v_gets;
9014 else if (v_gets > hdr_gets.max)
9015 hdr_gets.max = v_gets;
9018 /* compute per-chain averages */
9019 ch_gets.avg = ch_gets.sum / ((double)head->len);
9020 hdr_loads.avg = hdr_loads.sum / ((double)head->len);
9021 hdr_gets.avg = hdr_gets.sum / ((double)head->len);
9023 /* dump per-chain stats */
9024 Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
9026 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9027 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
9028 Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
9029 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9030 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9031 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9032 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9033 Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
9034 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9035 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9036 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9037 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9038 Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
9039 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
9040 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
9041 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
9042 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
9043 } else if (flags & VOL_STATS_PER_CHAIN) {
9044 /* dump simple per-chain stats */
9045 Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
9047 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9048 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
9049 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
9053 VHashEndExclusive_r(head);
9058 /* compute global averages */
9059 len.avg = len.sum / ((double)VolumeHashTable.Size);
9060 looks.avg = looks.sum / ((double)VolumeHashTable.Size);
9061 gets.avg = gets.sum / ((double)VolumeHashTable.Size);
9062 reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
9064 /* dump global stats */
9065 Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
9066 Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
9067 DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
9068 DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
9069 DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
9070 DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
9071 Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
9072 DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
9073 DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
9074 DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
9075 DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
9076 Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
9077 DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
9078 DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
9079 DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9080 DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9081 Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
9082 DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
9083 DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
9084 DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
9085 DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
9087 /* print extended disk related statistics */
9089 struct DiskPartition64 * diskP;
9090 afs_uint32 vol_count[VOLMAXPARTS+1];
9091 byte part_exists[VOLMAXPARTS+1];
9095 memset(vol_count, 0, sizeof(vol_count));
9096 memset(part_exists, 0, sizeof(part_exists));
9100 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
9102 vol_count[id] = diskP->vol_list.len;
9103 part_exists[id] = 1;
9107 for (i = 0; i <= VOLMAXPARTS; i++) {
9108 if (part_exists[i]) {
9109 /* XXX while this is currently safe, it is a violation
9110 * of the VGetPartitionById_r interface contract. */
9111 diskP = VGetPartitionById_r(i, 0);
9113 Log("Partition %s has %d online volumes\n",
9114 VPartitionPath(diskP), diskP->vol_list.len);
9121 /* print extended VLRU statistics */
9122 if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
9123 afs_uint32 idx, cur, lpos;
9128 Log("VLRU State Dump:\n\n");
9130 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
9131 Log("\t%s:\n", vlru_idx_to_string(idx));
9134 for (cur = vlru_stats.queue_info[idx].start;
9135 cur < vlru_stats.queue_info[idx].len;
9137 line[lpos++] = vlru_stats.vec[cur].volid;
9139 Log("\t\t%u, %u, %u, %u, %u,\n",
9140 line[0], line[1], line[2], line[3], line[4]);
9149 Log("\t\t%u, %u, %u, %u, %u\n",
9150 line[0], line[1], line[2], line[3], line[4]);
9155 free(vlru_stats.vec);
9162 VPrintExtendedCacheStats(int flags)
9165 VPrintExtendedCacheStats_r(flags);
9168 #endif /* AFS_DEMAND_ATTACH_FS */
9171 VCanScheduleSalvage(void)
9173 return vol_opts.canScheduleSalvage;
9179 return vol_opts.canUseFSSYNC;
9183 VCanUseSALVSYNC(void)
9185 return vol_opts.canUseSALVSYNC;
9189 VCanUnsafeAttach(void)
9191 return vol_opts.unsafe_attach;