2 * Copyright 2000, International Business Machines Corporation and others.
5 * This software has been released under the terms of the IBM Public
6 * License. For details, see the LICENSE file in the top-level source
7 * directory or online at http://www.openafs.org/dl/license10.html
9 * Portions Copyright (c) 2005-2008 Sine Nomine Associates
12 /* 1/1/89: NB: this stuff is all going to be replaced. Don't take it too seriously */
17 Institution: The Information Technology Center, Carnegie-Mellon University
21 #include <afsconfig.h>
22 #include <afs/param.h>
26 #include <afs/afsint.h>
30 #include <sys/param.h>
31 #if !defined(AFS_SGI_ENV)
34 #else /* AFS_OSF_ENV */
35 #ifdef AFS_VFSINCL_ENV
38 #include <sys/fs/ufs_fs.h>
40 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
41 #include <ufs/ufs/dinode.h>
42 #include <ufs/ffs/fs.h>
47 #else /* AFS_VFSINCL_ENV */
48 #if !defined(AFS_AIX_ENV) && !defined(AFS_LINUX20_ENV) && !defined(AFS_XBSD_ENV)
51 #endif /* AFS_VFSINCL_ENV */
52 #endif /* AFS_OSF_ENV */
53 #endif /* AFS_SGI_ENV */
54 #endif /* AFS_NT40_ENV */
72 #if defined(AFS_SUN_ENV) || defined(AFS_SUN5_ENV)
74 #include <sys/mnttab.h>
75 #include <sys/mntent.h>
81 #if defined(AFS_SGI_ENV)
86 #ifndef AFS_LINUX20_ENV
87 #include <fstab.h> /* Need to find in libc 5, present in libc 6 */
90 #endif /* AFS_SGI_ENV */
92 #endif /* AFS_HPUX_ENV */
96 #include <netinet/in.h>
100 #include <sys/time.h>
101 #endif /* ITIMER_REAL */
102 #endif /* AFS_NT40_ENV */
103 #if defined(AFS_SUN5_ENV) || defined(AFS_NT40_ENV) || defined(AFS_LINUX20_ENV)
110 #include <afs/errors.h>
113 #include <afs/afssyscalls.h>
115 #include <afs/afsutil.h>
119 #include "daemon_com.h"
121 #include "salvsync.h"
124 #include "partition.h"
125 #include "volume_inline.h"
127 #include "afs/afs_assert.h"
134 #if !defined(offsetof)
139 #define afs_stat stat64
140 #define afs_fstat fstat64
141 #define afs_open open64
142 #else /* !O_LARGEFILE */
143 #define afs_stat stat
144 #define afs_fstat fstat
145 #define afs_open open
146 #endif /* !O_LARGEFILE */
148 #ifdef AFS_PTHREAD_ENV
149 pthread_mutex_t vol_glock_mutex;
150 pthread_mutex_t vol_trans_mutex;
151 pthread_cond_t vol_put_volume_cond;
152 pthread_cond_t vol_sleep_cond;
153 pthread_cond_t vol_init_attach_cond;
154 pthread_cond_t vol_vinit_cond;
155 int vol_attach_threads = 1;
156 #endif /* AFS_PTHREAD_ENV */
158 /* start-time configurable I/O parameters */
159 ih_init_params vol_io_params;
161 #ifdef AFS_DEMAND_ATTACH_FS
162 pthread_mutex_t vol_salvsync_mutex;
165 * Set this to 1 to disallow SALVSYNC communication in all threads; used
166 * during shutdown, since the salvageserver may have gone away.
168 static volatile sig_atomic_t vol_disallow_salvsync = 0;
169 #endif /* AFS_DEMAND_ATTACH_FS */
172 * has VShutdown_r been called / is VShutdown_r running?
174 static int vol_shutting_down = 0;
177 extern void *calloc(), *realloc();
180 /* Forward declarations */
181 static Volume *attach2(Error * ec, VolId volumeId, char *path,
182 struct DiskPartition64 *partp, Volume * vp,
183 int isbusy, int mode, int *acheckedOut);
184 static void ReallyFreeVolume(Volume * vp);
185 #ifdef AFS_DEMAND_ATTACH_FS
186 static void FreeVolume(Volume * vp);
187 #else /* !AFS_DEMAND_ATTACH_FS */
188 #define FreeVolume(vp) ReallyFreeVolume(vp)
189 static void VScanUpdateList(void);
190 #endif /* !AFS_DEMAND_ATTACH_FS */
191 static void VInitVolumeHeaderCache(afs_uint32 howMany);
192 static int GetVolumeHeader(Volume * vp);
193 static void ReleaseVolumeHeader(struct volHeader *hd);
194 static void FreeVolumeHeader(Volume * vp);
195 static void AddVolumeToHashTable(Volume * vp, int hashid);
196 static void DeleteVolumeFromHashTable(Volume * vp);
198 static int VHold(Volume * vp);
200 static int VHold_r(Volume * vp);
201 static void VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class);
202 static void VReleaseVolumeHandles_r(Volume * vp);
203 static void VCloseVolumeHandles_r(Volume * vp);
204 static void LoadVolumeHeader(Error * ec, Volume * vp);
205 static int VCheckOffline(Volume * vp);
206 static int VCheckDetach(Volume * vp);
207 static Volume * GetVolume(Error * ec, Error * client_ec, VolId volumeId,
208 Volume * hint, const struct timespec *ts);
210 int LogLevel; /* Vice loglevel--not defined as extern so that it will be
211 * defined when not linked with vice, XXXX */
212 ProgramType programType; /* The type of program using the package */
213 static VolumePackageOptions vol_opts;
215 /* extended volume package statistics */
218 #ifdef VOL_LOCK_DEBUG
219 pthread_t vol_glock_holder = 0;
223 #define VOLUME_BITMAP_GROWSIZE 16 /* bytes, => 128vnodes */
224 /* Must be a multiple of 4 (1 word) !! */
226 /* this parameter needs to be tunable at runtime.
227 * 128 was really inadequate for largish servers -- at 16384 volumes this
228 * puts average chain length at 128, thus an average 65 deref's to find a volptr.
229 * talk about bad spatial locality...
231 * an AVL or splay tree might work a lot better, but we'll just increase
232 * the default hash table size for now
234 #define DEFAULT_VOLUME_HASH_SIZE 256 /* Must be a power of 2!! */
235 #define DEFAULT_VOLUME_HASH_MASK (DEFAULT_VOLUME_HASH_SIZE-1)
236 #define VOLUME_HASH(volumeId) (volumeId&(VolumeHashTable.Mask))
239 * turn volume hash chains into partially ordered lists.
240 * when the threshold is exceeded between two adjacent elements,
241 * perform a chain rebalancing operation.
243 * keep the threshold high in order to keep cache line invalidates
244 * low "enough" on SMPs
246 #define VOLUME_HASH_REORDER_THRESHOLD 200
249 * when possible, don't just reorder single elements, but reorder
250 * entire chains of elements at once. a chain of elements that
251 * exceed the element previous to the pivot by at least CHAIN_THRESH
252 * accesses are moved in front of the chain whose elements have at
253 * least CHAIN_THRESH less accesses than the pivot element
255 #define VOLUME_HASH_REORDER_CHAIN_THRESH (VOLUME_HASH_REORDER_THRESHOLD / 2)
257 #include "rx/rx_queue.h"
260 VolumeHashTable_t VolumeHashTable = {
261 DEFAULT_VOLUME_HASH_SIZE,
262 DEFAULT_VOLUME_HASH_MASK,
267 static void VInitVolumeHash(void);
271 /* This macro is used where an ffs() call does not exist. Was in util/ffs.c */
275 afs_int32 ffs_tmp = x;
279 for (ffs_i = 1;; ffs_i++) {
286 #endif /* !AFS_HAVE_FFS */
288 #ifdef AFS_PTHREAD_ENV
290 * disk partition queue element
292 typedef struct diskpartition_queue_t {
293 struct rx_queue queue; /**< queue header */
294 struct DiskPartition64 *diskP; /**< disk partition table entry */
295 } diskpartition_queue_t;
297 #ifndef AFS_DEMAND_ATTACH_FS
299 typedef struct vinitvolumepackage_thread_t {
300 struct rx_queue queue;
301 pthread_cond_t thread_done_cv;
302 int n_threads_complete;
303 } vinitvolumepackage_thread_t;
304 static void * VInitVolumePackageThread(void * args);
306 #else /* !AFS_DEMAND_ATTTACH_FS */
307 #define VINIT_BATCH_MAX_SIZE 512
310 * disk partition work queue
312 struct partition_queue {
313 struct rx_queue head; /**< diskpartition_queue_t queue */
314 pthread_mutex_t mutex;
319 * volumes parameters for preattach
321 struct volume_init_batch {
322 struct rx_queue queue; /**< queue header */
323 int thread; /**< posting worker thread */
324 int last; /**< indicates thread is done */
325 int size; /**< number of volume ids in batch */
326 Volume *batch[VINIT_BATCH_MAX_SIZE]; /**< volumes ids to preattach */
330 * volume parameters work queue
332 struct volume_init_queue {
333 struct rx_queue head; /**< volume_init_batch queue */
334 pthread_mutex_t mutex;
339 * volume init worker thread parameters
341 struct vinitvolumepackage_thread_param {
342 int nthreads; /**< total number of worker threads */
343 int thread; /**< thread number for this worker thread */
344 struct partition_queue *pq; /**< queue partitions to scan */
345 struct volume_init_queue *vq; /**< queue of volume to preattach */
348 static void *VInitVolumePackageThread(void *args);
349 static struct DiskPartition64 *VInitNextPartition(struct partition_queue *pq);
350 static VolId VInitNextVolumeId(DIR *dirp);
351 static int VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq);
353 #endif /* !AFS_DEMAND_ATTACH_FS */
354 #endif /* AFS_PTHREAD_ENV */
356 #ifndef AFS_DEMAND_ATTACH_FS
357 static int VAttachVolumesByPartition(struct DiskPartition64 *diskP,
358 int * nAttached, int * nUnattached);
359 #endif /* AFS_DEMAND_ATTACH_FS */
362 #ifdef AFS_DEMAND_ATTACH_FS
363 /* demand attach fileserver extensions */
366 * in the future we will support serialization of VLRU state into the fs_state
369 * these structures are the beginning of that effort
371 struct VLRU_DiskHeader {
372 struct versionStamp stamp; /* magic and structure version number */
373 afs_uint32 mtime; /* time of dump to disk */
374 afs_uint32 num_records; /* number of VLRU_DiskEntry records */
377 struct VLRU_DiskEntry {
378 afs_uint32 vid; /* volume ID */
379 afs_uint32 idx; /* generation */
380 afs_uint32 last_get; /* timestamp of last get */
383 struct VLRU_StartupQueue {
384 struct VLRU_DiskEntry * entry;
389 typedef struct vshutdown_thread_t {
391 pthread_mutex_t lock;
393 pthread_cond_t master_cv;
395 int n_threads_complete;
397 int schedule_version;
400 byte n_parts_done_pass;
401 byte part_thread_target[VOLMAXPARTS+1];
402 byte part_done_pass[VOLMAXPARTS+1];
403 struct rx_queue * part_pass_head[VOLMAXPARTS+1];
404 int stats[4][VOLMAXPARTS+1];
405 } vshutdown_thread_t;
406 static void * VShutdownThread(void * args);
409 static Volume * VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode);
410 static int VCheckFree(Volume * vp);
413 static void AddVolumeToVByPList_r(Volume * vp);
414 static void DeleteVolumeFromVByPList_r(Volume * vp);
415 static void VVByPListBeginExclusive_r(struct DiskPartition64 * dp);
416 static void VVByPListEndExclusive_r(struct DiskPartition64 * dp);
417 static void VVByPListWait_r(struct DiskPartition64 * dp);
419 /* online salvager */
420 static int VCheckSalvage(Volume * vp);
421 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
422 static int VScheduleSalvage_r(Volume * vp);
425 /* Volume hash table */
426 static void VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp);
427 static void VHashBeginExclusive_r(VolumeHashChainHead * head);
428 static void VHashEndExclusive_r(VolumeHashChainHead * head);
429 static void VHashWait_r(VolumeHashChainHead * head);
432 static int ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass);
433 static int ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
434 struct rx_queue ** idx);
435 static void ShutdownController(vshutdown_thread_t * params);
436 static void ShutdownCreateSchedule(vshutdown_thread_t * params);
439 static void VLRU_ComputeConstants(void);
440 static void VInitVLRU(void);
441 static void VLRU_Init_Node_r(Volume * vp);
442 static void VLRU_Add_r(Volume * vp);
443 static void VLRU_Delete_r(Volume * vp);
444 static void VLRU_UpdateAccess_r(Volume * vp);
445 static void * VLRU_ScannerThread(void * args);
446 static void VLRU_Scan_r(int idx);
447 static void VLRU_Promote_r(int idx);
448 static void VLRU_Demote_r(int idx);
449 static void VLRU_SwitchQueues(Volume * vp, int new_idx, int append);
452 static int VCheckSoftDetach(Volume * vp, afs_uint32 thresh);
453 static int VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh);
454 static int VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh);
457 pthread_key_t VThread_key;
458 VThreadOptions_t VThread_defaults = {
459 0 /**< allow salvsync */
461 #endif /* AFS_DEMAND_ATTACH_FS */
464 struct Lock vol_listLock; /* Lock obtained when listing volumes:
465 * prevents a volume from being missed
466 * if the volume is attached during a
470 /* Common message used when the volume goes off line */
471 char *VSalvageMessage =
472 "Files in this volume are currently unavailable; call operations";
474 int VInit; /* 0 - uninitialized,
475 * 1 - initialized but not all volumes have been attached,
476 * 2 - initialized and all volumes have been attached,
477 * 3 - initialized, all volumes have been attached, and
478 * VConnectFS() has completed. */
480 static int vinit_attach_abort = 0;
482 bit32 VolumeCacheCheck; /* Incremented everytime a volume goes on line--
483 * used to stamp volume headers and in-core
484 * vnodes. When the volume goes on-line the
485 * vnode will be invalidated
486 * access only with VOL_LOCK held */
491 /***************************************************/
492 /* Startup routines */
493 /***************************************************/
495 #if defined(FAST_RESTART) && defined(AFS_DEMAND_ATTACH_FS)
496 # error FAST_RESTART and DAFS are incompatible. For the DAFS equivalent \
497 of FAST_RESTART, use the -unsafe-nosalvage fileserver argument
501 * assign default values to a VolumePackageOptions struct.
503 * Always call this on a VolumePackageOptions struct first, then set any
504 * specific options you want, then call VInitVolumePackage2.
506 * @param[in] pt caller's program type
507 * @param[out] opts volume package options
510 VOptDefaults(ProgramType pt, VolumePackageOptions *opts)
512 opts->nLargeVnodes = opts->nSmallVnodes = 5;
515 opts->canScheduleSalvage = 0;
516 opts->canUseFSSYNC = 0;
517 opts->canUseSALVSYNC = 0;
519 opts->interrupt_rxcall = NULL;
520 opts->offline_timeout = -1;
521 opts->offline_shutdown_timeout = -1;
524 opts->unsafe_attach = 1;
525 #else /* !FAST_RESTART */
526 opts->unsafe_attach = 0;
527 #endif /* !FAST_RESTART */
531 opts->canScheduleSalvage = 1;
532 opts->canUseSALVSYNC = 1;
536 opts->canUseFSSYNC = 1;
540 opts->nLargeVnodes = 0;
541 opts->nSmallVnodes = 0;
543 opts->canScheduleSalvage = 1;
544 opts->canUseFSSYNC = 1;
554 * Set VInit to a certain value, and signal waiters.
556 * @param[in] value the value to set VInit to
561 VSetVInit_r(int value)
564 CV_BROADCAST(&vol_vinit_cond);
568 VLogOfflineTimeout(const char *type, afs_int32 timeout)
574 Log("VInitVolumePackage: Interrupting clients accessing %s "
575 "immediately\n", type);
577 Log("VInitVolumePackage: Interrupting clients accessing %s "
578 "after %ld second%s\n", type, (long)timeout, timeout==1?"":"s");
583 VInitVolumePackage2(ProgramType pt, VolumePackageOptions * opts)
585 int errors = 0; /* Number of errors while finding vice partitions. */
590 #ifndef AFS_PTHREAD_ENV
591 if (opts->offline_timeout != -1 || opts->offline_shutdown_timeout != -1) {
592 Log("VInitVolumePackage: offline_timeout and/or "
593 "offline_shutdown_timeout was specified, but the volume package "
594 "does not support these for LWP builds\n");
598 VLogOfflineTimeout("volumes going offline", opts->offline_timeout);
599 VLogOfflineTimeout("volumes going offline during shutdown",
600 opts->offline_shutdown_timeout);
602 memset(&VStats, 0, sizeof(VStats));
603 VStats.hdr_cache_size = 200;
605 VInitPartitionPackage();
607 #ifdef AFS_DEMAND_ATTACH_FS
608 if (programType == fileServer) {
611 VLRU_SetOptions(VLRU_SET_ENABLED, 0);
613 osi_Assert(pthread_key_create(&VThread_key, NULL) == 0);
616 MUTEX_INIT(&vol_glock_mutex, "vol glock", MUTEX_DEFAULT, 0);
617 MUTEX_INIT(&vol_trans_mutex, "vol trans", MUTEX_DEFAULT, 0);
618 CV_INIT(&vol_put_volume_cond, "vol put", CV_DEFAULT, 0);
619 CV_INIT(&vol_sleep_cond, "vol sleep", CV_DEFAULT, 0);
620 CV_INIT(&vol_init_attach_cond, "vol init attach", CV_DEFAULT, 0);
621 CV_INIT(&vol_vinit_cond, "vol init", CV_DEFAULT, 0);
622 #ifndef AFS_PTHREAD_ENV
624 #endif /* AFS_PTHREAD_ENV */
625 Lock_Init(&vol_listLock);
627 srandom(time(0)); /* For VGetVolumeInfo */
629 #ifdef AFS_DEMAND_ATTACH_FS
630 MUTEX_INIT(&vol_salvsync_mutex, "salvsync", MUTEX_DEFAULT, 0);
631 #endif /* AFS_DEMAND_ATTACH_FS */
633 /* Ok, we have done enough initialization that fileserver can
634 * start accepting calls, even though the volumes may not be
635 * available just yet.
639 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_SERVER)
640 if (programType == salvageServer) {
643 #endif /* AFS_DEMAND_ATTACH_FS */
644 #ifdef FSSYNC_BUILD_SERVER
645 if (programType == fileServer) {
649 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_CLIENT)
650 if (VCanUseSALVSYNC()) {
651 /* establish a connection to the salvager at this point */
652 osi_Assert(VConnectSALV() != 0);
654 #endif /* AFS_DEMAND_ATTACH_FS */
656 if (opts->volcache > VStats.hdr_cache_size)
657 VStats.hdr_cache_size = opts->volcache;
658 VInitVolumeHeaderCache(VStats.hdr_cache_size);
660 VInitVnodes(vLarge, opts->nLargeVnodes);
661 VInitVnodes(vSmall, opts->nSmallVnodes);
664 errors = VAttachPartitions();
668 if (programType != fileServer) {
669 errors = VInitAttachVolumes(programType);
675 #ifdef FSSYNC_BUILD_CLIENT
676 if (VCanUseFSSYNC()) {
678 #ifdef AFS_DEMAND_ATTACH_FS
679 if (programType == salvageServer) {
680 Log("Unable to connect to file server; aborted\n");
683 #endif /* AFS_DEMAND_ATTACH_FS */
684 Log("Unable to connect to file server; will retry at need\n");
687 #endif /* FSSYNC_BUILD_CLIENT */
692 #if !defined(AFS_PTHREAD_ENV)
694 * Attach volumes in vice partitions
696 * @param[in] pt calling program type
699 * @note This is the original, non-threaded version of attach parititions.
701 * @post VInit state is 2
704 VInitAttachVolumes(ProgramType pt)
706 osi_Assert(VInit==1);
707 if (pt == fileServer) {
708 struct DiskPartition64 *diskP;
709 /* Attach all the volumes in this partition */
710 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
711 int nAttached = 0, nUnattached = 0;
712 osi_Assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
716 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
717 LWP_NoYieldSignal(VInitAttachVolumes);
721 #endif /* !AFS_PTHREAD_ENV */
723 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_DEMAND_ATTACH_FS)
725 * Attach volumes in vice partitions
727 * @param[in] pt calling program type
730 * @note Threaded version of attach parititions.
732 * @post VInit state is 2
735 VInitAttachVolumes(ProgramType pt)
737 osi_Assert(VInit==1);
738 if (pt == fileServer) {
739 struct DiskPartition64 *diskP;
740 struct vinitvolumepackage_thread_t params;
741 struct diskpartition_queue_t * dpq;
742 int i, threads, parts;
744 pthread_attr_t attrs;
746 CV_INIT(¶ms.thread_done_cv, "thread done", CV_DEFAULT, 0);
748 params.n_threads_complete = 0;
750 /* create partition work queue */
751 for (parts=0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
752 dpq = (diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
753 osi_Assert(dpq != NULL);
755 queue_Append(¶ms,dpq);
758 threads = MIN(parts, vol_attach_threads);
761 /* spawn off a bunch of initialization threads */
762 osi_Assert(pthread_attr_init(&attrs) == 0);
763 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
765 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
766 Log("VInitVolumePackage: using %d threads to attach volumes on %d partitions\n",
770 for (i=0; i < threads; i++) {
773 osi_Assert(pthread_create
774 (&tid, &attrs, &VInitVolumePackageThread,
776 AFS_SIGSET_RESTORE();
779 while(params.n_threads_complete < threads) {
780 VOL_CV_WAIT(¶ms.thread_done_cv);
784 osi_Assert(pthread_attr_destroy(&attrs) == 0);
786 /* if we're only going to run one init thread, don't bother creating
788 Log("VInitVolumePackage: beginning single-threaded fileserver startup\n");
789 Log("VInitVolumePackage: using 1 thread to attach volumes on %d partition(s)\n",
792 VInitVolumePackageThread(¶ms);
795 CV_DESTROY(¶ms.thread_done_cv);
798 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
799 CV_BROADCAST(&vol_init_attach_cond);
805 VInitVolumePackageThread(void * args) {
807 struct DiskPartition64 *diskP;
808 struct vinitvolumepackage_thread_t * params;
809 struct diskpartition_queue_t * dpq;
811 params = (vinitvolumepackage_thread_t *) args;
815 /* Attach all the volumes in this partition */
816 while (queue_IsNotEmpty(params)) {
817 int nAttached = 0, nUnattached = 0;
819 if (vinit_attach_abort) {
820 Log("Aborting initialization\n");
824 dpq = queue_First(params,diskpartition_queue_t);
830 osi_Assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
836 params->n_threads_complete++;
837 CV_SIGNAL(¶ms->thread_done_cv);
841 #endif /* AFS_PTHREAD_ENV && !AFS_DEMAND_ATTACH_FS */
843 #if defined(AFS_DEMAND_ATTACH_FS)
845 * Attach volumes in vice partitions
847 * @param[in] pt calling program type
850 * @note Threaded version of attach partitions.
852 * @post VInit state is 2
855 VInitAttachVolumes(ProgramType pt)
857 osi_Assert(VInit==1);
858 if (pt == fileServer) {
860 struct DiskPartition64 *diskP;
861 struct partition_queue pq;
862 struct volume_init_queue vq;
864 int i, threads, parts;
866 pthread_attr_t attrs;
868 /* create partition work queue */
870 CV_INIT(&(pq.cv), "partq", CV_DEFAULT, 0);
871 MUTEX_INIT(&(pq.mutex), "partq", MUTEX_DEFAULT, 0);
872 for (parts = 0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
873 struct diskpartition_queue_t *dp;
874 dp = (struct diskpartition_queue_t*)malloc(sizeof(struct diskpartition_queue_t));
875 osi_Assert(dp != NULL);
877 queue_Append(&pq, dp);
880 /* number of worker threads; at least one, not to exceed the number of partitions */
881 threads = MIN(parts, vol_attach_threads);
883 /* create volume work queue */
885 CV_INIT(&(vq.cv), "volq", CV_DEFAULT, 0);
886 MUTEX_INIT(&(vq.mutex), "volq", MUTEX_DEFAULT, 0);
888 osi_Assert(pthread_attr_init(&attrs) == 0);
889 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
891 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
892 Log("VInitVolumePackage: using %d threads to pre-attach volumes on %d partitions\n",
895 /* create threads to scan disk partitions. */
896 for (i=0; i < threads; i++) {
897 struct vinitvolumepackage_thread_param *params;
900 params = (struct vinitvolumepackage_thread_param *)malloc(sizeof(struct vinitvolumepackage_thread_param));
904 params->nthreads = threads;
905 params->thread = i+1;
908 osi_Assert(pthread_create (&tid, &attrs, &VInitVolumePackageThread, (void*)params) == 0);
909 AFS_SIGSET_RESTORE();
912 VInitPreAttachVolumes(threads, &vq);
914 osi_Assert(pthread_attr_destroy(&attrs) == 0);
916 MUTEX_DESTROY(&pq.mutex);
918 MUTEX_DESTROY(&vq.mutex);
922 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
923 CV_BROADCAST(&vol_init_attach_cond);
930 * Volume package initialization worker thread. Scan partitions for volume
931 * header files. Gather batches of volume ids and dispatch them to
932 * the main thread to be preattached. The volume preattachement is done
933 * in the main thread to avoid global volume lock contention.
936 VInitVolumePackageThread(void *args)
938 struct vinitvolumepackage_thread_param *params;
939 struct DiskPartition64 *partition;
940 struct partition_queue *pq;
941 struct volume_init_queue *vq;
942 struct volume_init_batch *vb;
945 params = (struct vinitvolumepackage_thread_param *)args;
951 vb = (struct volume_init_batch*)malloc(sizeof(struct volume_init_batch));
953 vb->thread = params->thread;
957 Log("Scanning partitions on thread %d of %d\n", params->thread, params->nthreads);
958 while((partition = VInitNextPartition(pq))) {
962 Log("Partition %s: pre-attaching volumes\n", partition->name);
963 dirp = opendir(VPartitionPath(partition));
965 Log("opendir on Partition %s failed, errno=%d!\n", partition->name, errno);
968 while ((vid = VInitNextVolumeId(dirp))) {
969 Volume *vp = (Volume*)malloc(sizeof(Volume));
971 memset(vp, 0, sizeof(Volume));
972 vp->device = partition->device;
973 vp->partition = partition;
975 queue_Init(&vp->vnode_list);
976 queue_Init(&vp->rx_call_list);
977 CV_INIT(&V_attachCV(vp), "partattach", CV_DEFAULT, 0);
979 vb->batch[vb->size++] = vp;
980 if (vb->size == VINIT_BATCH_MAX_SIZE) {
981 MUTEX_ENTER(&vq->mutex);
982 queue_Append(vq, vb);
983 CV_BROADCAST(&vq->cv);
984 MUTEX_EXIT(&vq->mutex);
986 vb = (struct volume_init_batch*)malloc(sizeof(struct volume_init_batch));
988 vb->thread = params->thread;
997 MUTEX_ENTER(&vq->mutex);
998 queue_Append(vq, vb);
999 CV_BROADCAST(&vq->cv);
1000 MUTEX_EXIT(&vq->mutex);
1002 Log("Partition scan thread %d of %d ended\n", params->thread, params->nthreads);
1008 * Read next element from the pre-populated partition list.
1010 static struct DiskPartition64*
1011 VInitNextPartition(struct partition_queue *pq)
1013 struct DiskPartition64 *partition;
1014 struct diskpartition_queue_t *dp; /* queue element */
1016 if (vinit_attach_abort) {
1017 Log("Aborting volume preattach thread.\n");
1021 /* get next partition to scan */
1022 MUTEX_ENTER(&pq->mutex);
1023 if (queue_IsEmpty(pq)) {
1024 MUTEX_EXIT(&pq->mutex);
1027 dp = queue_First(pq, diskpartition_queue_t);
1029 MUTEX_EXIT(&pq->mutex);
1032 osi_Assert(dp->diskP);
1034 partition = dp->diskP;
1040 * Find next volume id on the partition.
1043 VInitNextVolumeId(DIR *dirp)
1049 while((d = readdir(dirp))) {
1050 if (vinit_attach_abort) {
1051 Log("Aborting volume preattach thread.\n");
1054 ext = strrchr(d->d_name, '.');
1055 if (d->d_name[0] == 'V' && ext && strcmp(ext, VHDREXT) == 0) {
1056 vid = VolumeNumber(d->d_name);
1060 Log("Warning: bogus volume header file: %s\n", d->d_name);
1067 * Preattach volumes in batches to avoid lock contention.
1070 VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq)
1072 struct volume_init_batch *vb;
1076 /* dequeue next volume */
1077 MUTEX_ENTER(&vq->mutex);
1078 if (queue_IsEmpty(vq)) {
1079 CV_WAIT(&vq->cv, &vq->mutex);
1081 vb = queue_First(vq, volume_init_batch);
1083 MUTEX_EXIT(&vq->mutex);
1087 for (i = 0; i<vb->size; i++) {
1093 dup = VLookupVolume_r(&ec, vp->hashid, NULL);
1095 Log("Error looking up volume, code=%d\n", ec);
1098 Log("Warning: Duplicate volume id %d detected.\n", vp->hashid);
1101 /* put pre-attached volume onto the hash table
1102 * and bring it up to the pre-attached state */
1103 AddVolumeToHashTable(vp, vp->hashid);
1104 AddVolumeToVByPList_r(vp);
1105 VLRU_Init_Node_r(vp);
1106 VChangeState_r(vp, VOL_STATE_PREATTACHED);
1119 #endif /* AFS_DEMAND_ATTACH_FS */
1121 #if !defined(AFS_DEMAND_ATTACH_FS)
1123 * attach all volumes on a given disk partition
1126 VAttachVolumesByPartition(struct DiskPartition64 *diskP, int * nAttached, int * nUnattached)
1132 Log("Partition %s: attaching volumes\n", diskP->name);
1133 dirp = opendir(VPartitionPath(diskP));
1135 Log("opendir on Partition %s failed!\n", diskP->name);
1139 while ((dp = readdir(dirp))) {
1141 p = strrchr(dp->d_name, '.');
1143 if (vinit_attach_abort) {
1144 Log("Partition %s: abort attach volumes\n", diskP->name);
1148 if (p != NULL && strcmp(p, VHDREXT) == 0) {
1151 vp = VAttachVolumeByName(&error, diskP->name, dp->d_name,
1153 (*(vp ? nAttached : nUnattached))++;
1154 if (error == VOFFLINE)
1155 Log("Volume %d stays offline (/vice/offline/%s exists)\n", VolumeNumber(dp->d_name), dp->d_name);
1156 else if (LogLevel >= 5) {
1157 Log("Partition %s: attached volume %d (%s)\n",
1158 diskP->name, VolumeNumber(dp->d_name),
1167 Log("Partition %s: attached %d volumes; %d volumes not attached\n", diskP->name, *nAttached, *nUnattached);
1172 #endif /* !AFS_DEMAND_ATTACH_FS */
1174 /***************************************************/
1175 /* Shutdown routines */
1176 /***************************************************/
1180 * highly multithreaded volume package shutdown
1182 * with the demand attach fileserver extensions,
1183 * VShutdown has been modified to be multithreaded.
1184 * In order to achieve optimal use of many threads,
1185 * the shutdown code involves one control thread and
1186 * n shutdown worker threads. The control thread
1187 * periodically examines the number of volumes available
1188 * for shutdown on each partition, and produces a worker
1189 * thread allocation schedule. The idea is to eliminate
1190 * redundant scheduling computation on the workers by
1191 * having a single master scheduler.
1193 * The scheduler's objectives are:
1195 * each partition with volumes remaining gets allocated
1196 * at least 1 thread (assuming sufficient threads)
1198 * threads are allocated proportional to the number of
1199 * volumes remaining to be offlined. This ensures that
1200 * the OS I/O scheduler has many requests to elevator
1201 * seek on partitions that will (presumably) take the
1202 * longest amount of time (from now) to finish shutdown
1203 * (3) keep threads busy
1204 * when there are extra threads, they are assigned to
1205 * partitions using a simple round-robin algorithm
1207 * In the future, we may wish to add the ability to adapt
1208 * to the relative performance patterns of each disk
1213 * multi-step shutdown process
1215 * demand attach shutdown is a four-step process. Each
1216 * shutdown "pass" shuts down increasingly more difficult
1217 * volumes. The main purpose is to achieve better cache
1218 * utilization during shutdown.
1221 * shutdown volumes in the unattached, pre-attached
1224 * shutdown attached volumes with cached volume headers
1226 * shutdown all volumes in non-exclusive states
1228 * shutdown all remaining volumes
1231 #ifdef AFS_DEMAND_ATTACH_FS
1237 struct DiskPartition64 * diskP;
1238 struct diskpartition_queue_t * dpq;
1239 vshutdown_thread_t params;
1241 pthread_attr_t attrs;
1243 memset(¶ms, 0, sizeof(vshutdown_thread_t));
1246 Log("VShutdown: aborting attach volumes\n");
1247 vinit_attach_abort = 1;
1248 VOL_CV_WAIT(&vol_init_attach_cond);
1251 for (params.n_parts=0, diskP = DiskPartitionList;
1252 diskP; diskP = diskP->next, params.n_parts++);
1254 Log("VShutdown: shutting down on-line volumes on %d partition%s...\n",
1255 params.n_parts, params.n_parts > 1 ? "s" : "");
1257 vol_shutting_down = 1;
1259 if (vol_attach_threads > 1) {
1260 /* prepare for parallel shutdown */
1261 params.n_threads = vol_attach_threads;
1262 MUTEX_INIT(¶ms.lock, "params", MUTEX_DEFAULT, 0);
1263 CV_INIT(¶ms.cv, "params", CV_DEFAULT, 0);
1264 CV_INIT(¶ms.master_cv, "params master", CV_DEFAULT, 0);
1265 osi_Assert(pthread_attr_init(&attrs) == 0);
1266 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
1267 queue_Init(¶ms);
1269 /* setup the basic partition information structures for
1270 * parallel shutdown */
1271 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1273 struct rx_queue * qp, * nqp;
1277 VVByPListWait_r(diskP);
1278 VVByPListBeginExclusive_r(diskP);
1281 for (queue_Scan(&diskP->vol_list, qp, nqp, rx_queue)) {
1282 vp = (Volume *)((char *)qp - offsetof(Volume, vol_list));
1286 Log("VShutdown: partition %s has %d volumes with attached headers\n",
1287 VPartitionPath(diskP), count);
1290 /* build up the pass 0 shutdown work queue */
1291 dpq = (struct diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
1292 osi_Assert(dpq != NULL);
1294 queue_Prepend(¶ms, dpq);
1296 params.part_pass_head[diskP->index] = queue_First(&diskP->vol_list, rx_queue);
1299 Log("VShutdown: beginning parallel fileserver shutdown\n");
1300 Log("VShutdown: using %d threads to offline volumes on %d partition%s\n",
1301 vol_attach_threads, params.n_parts, params.n_parts > 1 ? "s" : "" );
1303 /* do pass 0 shutdown */
1304 MUTEX_ENTER(¶ms.lock);
1305 for (i=0; i < params.n_threads; i++) {
1306 osi_Assert(pthread_create
1307 (&tid, &attrs, &VShutdownThread,
1311 /* wait for all the pass 0 shutdowns to complete */
1312 while (params.n_threads_complete < params.n_threads) {
1313 CV_WAIT(¶ms.master_cv, ¶ms.lock);
1315 params.n_threads_complete = 0;
1317 CV_BROADCAST(¶ms.cv);
1318 MUTEX_EXIT(¶ms.lock);
1320 Log("VShutdown: pass 0 completed using the 1 thread per partition algorithm\n");
1321 Log("VShutdown: starting passes 1 through 3 using finely-granular mp-fast algorithm\n");
1323 /* run the parallel shutdown scheduler. it will drop the glock internally */
1324 ShutdownController(¶ms);
1326 /* wait for all the workers to finish pass 3 and terminate */
1327 while (params.pass < 4) {
1328 VOL_CV_WAIT(¶ms.cv);
1331 osi_Assert(pthread_attr_destroy(&attrs) == 0);
1332 CV_DESTROY(¶ms.cv);
1333 CV_DESTROY(¶ms.master_cv);
1334 MUTEX_DESTROY(¶ms.lock);
1336 /* drop the VByPList exclusive reservations */
1337 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1338 VVByPListEndExclusive_r(diskP);
1339 Log("VShutdown: %s stats : (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1340 VPartitionPath(diskP),
1341 params.stats[0][diskP->index],
1342 params.stats[1][diskP->index],
1343 params.stats[2][diskP->index],
1344 params.stats[3][diskP->index]);
1347 Log("VShutdown: shutdown finished using %d threads\n", params.n_threads);
1349 /* if we're only going to run one shutdown thread, don't bother creating
1351 Log("VShutdown: beginning single-threaded fileserver shutdown\n");
1353 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1354 VShutdownByPartition_r(diskP);
1358 Log("VShutdown: complete.\n");
1361 #else /* AFS_DEMAND_ATTACH_FS */
1371 Log("VShutdown: aborting attach volumes\n");
1372 vinit_attach_abort = 1;
1373 #ifdef AFS_PTHREAD_ENV
1374 VOL_CV_WAIT(&vol_init_attach_cond);
1376 LWP_WaitProcess(VInitAttachVolumes);
1377 #endif /* AFS_PTHREAD_ENV */
1380 Log("VShutdown: shutting down on-line volumes...\n");
1381 vol_shutting_down = 1;
1382 for (i = 0; i < VolumeHashTable.Size; i++) {
1383 /* try to hold first volume in the hash table */
1384 for (queue_Scan(&VolumeHashTable.Table[i],vp,np,Volume)) {
1388 Log("VShutdown: Attempting to take volume %u offline.\n",
1391 /* next, take the volume offline (drops reference count) */
1392 VOffline_r(vp, "File server was shut down");
1396 Log("VShutdown: complete.\n");
1398 #endif /* AFS_DEMAND_ATTACH_FS */
1404 osi_Assert(VInit>0);
1411 * stop new activity (e.g. SALVSYNC) from occurring
1413 * Use this to make the volume package less busy; for example, during
1414 * shutdown. This doesn't actually shutdown/detach anything in the
1415 * volume package, but prevents certain processes from ocurring. For
1416 * example, preventing new SALVSYNC communication in DAFS. In theory, we
1417 * could also use this to prevent new volume attachment, or prevent
1418 * other programs from checking out volumes, etc.
1423 #ifdef AFS_DEMAND_ATTACH_FS
1424 /* make sure we don't try to contact the salvageserver, since it may
1425 * not be around anymore */
1426 vol_disallow_salvsync = 1;
1430 #ifdef AFS_DEMAND_ATTACH_FS
1433 * shutdown control thread
1436 ShutdownController(vshutdown_thread_t * params)
1439 struct DiskPartition64 * diskP;
1441 vshutdown_thread_t shadow;
1443 ShutdownCreateSchedule(params);
1445 while ((params->pass < 4) &&
1446 (params->n_threads_complete < params->n_threads)) {
1447 /* recompute schedule once per second */
1449 memcpy(&shadow, params, sizeof(vshutdown_thread_t));
1453 Log("ShutdownController: schedule version=%d, vol_remaining=%d, pass=%d\n",
1454 shadow.schedule_version, shadow.vol_remaining, shadow.pass);
1455 Log("ShutdownController: n_threads_complete=%d, n_parts_done_pass=%d\n",
1456 shadow.n_threads_complete, shadow.n_parts_done_pass);
1457 for (diskP = DiskPartitionList; diskP; diskP=diskP->next) {
1459 Log("ShutdownController: part[%d] : (len=%d, thread_target=%d, done_pass=%d, pass_head=%p)\n",
1461 diskP->vol_list.len,
1462 shadow.part_thread_target[id],
1463 shadow.part_done_pass[id],
1464 shadow.part_pass_head[id]);
1470 ShutdownCreateSchedule(params);
1474 /* create the shutdown thread work schedule.
1475 * this scheduler tries to implement fairness
1476 * by allocating at least 1 thread to each
1477 * partition with volumes to be shutdown,
1478 * and then it attempts to allocate remaining
1479 * threads based upon the amount of work left
1482 ShutdownCreateSchedule(vshutdown_thread_t * params)
1484 struct DiskPartition64 * diskP;
1485 int sum, thr_workload, thr_left;
1486 int part_residue[VOLMAXPARTS+1];
1489 /* compute the total number of outstanding volumes */
1491 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1492 sum += diskP->vol_list.len;
1495 params->schedule_version++;
1496 params->vol_remaining = sum;
1501 /* compute average per-thread workload */
1502 thr_workload = sum / params->n_threads;
1503 if (sum % params->n_threads)
1506 thr_left = params->n_threads;
1507 memset(&part_residue, 0, sizeof(part_residue));
1509 /* for fairness, give every partition with volumes remaining
1510 * at least one thread */
1511 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1513 if (diskP->vol_list.len) {
1514 params->part_thread_target[id] = 1;
1517 params->part_thread_target[id] = 0;
1521 if (thr_left && thr_workload) {
1522 /* compute length-weighted workloads */
1525 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1527 delta = (diskP->vol_list.len / thr_workload) -
1528 params->part_thread_target[id];
1532 if (delta < thr_left) {
1533 params->part_thread_target[id] += delta;
1536 params->part_thread_target[id] += thr_left;
1544 /* try to assign any leftover threads to partitions that
1545 * had volume lengths closer to needing thread_target+1 */
1546 int max_residue, max_id = 0;
1548 /* compute the residues */
1549 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1551 part_residue[id] = diskP->vol_list.len -
1552 (params->part_thread_target[id] * thr_workload);
1555 /* now try to allocate remaining threads to partitions with the
1556 * highest residues */
1559 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1561 if (part_residue[id] > max_residue) {
1562 max_residue = part_residue[id];
1571 params->part_thread_target[max_id]++;
1573 part_residue[max_id] = 0;
1578 /* punt and give any remaining threads equally to each partition */
1580 if (thr_left >= params->n_parts) {
1581 alloc = thr_left / params->n_parts;
1582 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1584 params->part_thread_target[id] += alloc;
1589 /* finish off the last of the threads */
1590 for (diskP = DiskPartitionList; thr_left && diskP; diskP = diskP->next) {
1592 params->part_thread_target[id]++;
1598 /* worker thread for parallel shutdown */
1600 VShutdownThread(void * args)
1602 vshutdown_thread_t * params;
1603 int found, pass, schedule_version_save, count;
1604 struct DiskPartition64 *diskP;
1605 struct diskpartition_queue_t * dpq;
1608 params = (vshutdown_thread_t *) args;
1610 /* acquire the shutdown pass 0 lock */
1611 MUTEX_ENTER(¶ms->lock);
1613 /* if there's still pass 0 work to be done,
1614 * get a work entry, and do a pass 0 shutdown */
1615 if (queue_IsNotEmpty(params)) {
1616 dpq = queue_First(params, diskpartition_queue_t);
1618 MUTEX_EXIT(¶ms->lock);
1624 while (ShutdownVolumeWalk_r(diskP, 0, ¶ms->part_pass_head[id]))
1626 params->stats[0][diskP->index] = count;
1627 MUTEX_ENTER(¶ms->lock);
1630 params->n_threads_complete++;
1631 if (params->n_threads_complete == params->n_threads) {
1632 /* notify control thread that all workers have completed pass 0 */
1633 CV_SIGNAL(¶ms->master_cv);
1635 while (params->pass == 0) {
1636 CV_WAIT(¶ms->cv, ¶ms->lock);
1640 MUTEX_EXIT(¶ms->lock);
1643 pass = params->pass;
1644 osi_Assert(pass > 0);
1646 /* now escalate through the more complicated shutdowns */
1648 schedule_version_save = params->schedule_version;
1650 /* find a disk partition to work on */
1651 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1653 if (params->part_thread_target[id] && !params->part_done_pass[id]) {
1654 params->part_thread_target[id]--;
1661 /* hmm. for some reason the controller thread couldn't find anything for
1662 * us to do. let's see if there's anything we can do */
1663 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1665 if (diskP->vol_list.len && !params->part_done_pass[id]) {
1668 } else if (!params->part_done_pass[id]) {
1669 params->part_done_pass[id] = 1;
1670 params->n_parts_done_pass++;
1672 Log("VShutdown: done shutting down volumes on partition %s.\n",
1673 VPartitionPath(diskP));
1679 /* do work on this partition until either the controller
1680 * creates a new schedule, or we run out of things to do
1681 * on this partition */
1684 while (!params->part_done_pass[id] &&
1685 (schedule_version_save == params->schedule_version)) {
1686 /* ShutdownVolumeWalk_r will drop the glock internally */
1687 if (!ShutdownVolumeWalk_r(diskP, pass, ¶ms->part_pass_head[id])) {
1688 if (!params->part_done_pass[id]) {
1689 params->part_done_pass[id] = 1;
1690 params->n_parts_done_pass++;
1692 Log("VShutdown: done shutting down volumes on partition %s.\n",
1693 VPartitionPath(diskP));
1701 params->stats[pass][id] += count;
1703 /* ok, everyone is done this pass, proceed */
1706 params->n_threads_complete++;
1707 while (params->pass == pass) {
1708 if (params->n_threads_complete == params->n_threads) {
1709 /* we are the last thread to complete, so we will
1710 * reinitialize worker pool state for the next pass */
1711 params->n_threads_complete = 0;
1712 params->n_parts_done_pass = 0;
1714 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1716 params->part_done_pass[id] = 0;
1717 params->part_pass_head[id] = queue_First(&diskP->vol_list, rx_queue);
1720 /* compute a new thread schedule before releasing all the workers */
1721 ShutdownCreateSchedule(params);
1723 /* wake up all the workers */
1724 CV_BROADCAST(¶ms->cv);
1727 Log("VShutdown: pass %d completed using %d threads on %d partitions\n",
1728 pass, params->n_threads, params->n_parts);
1731 VOL_CV_WAIT(¶ms->cv);
1734 pass = params->pass;
1748 /* shut down all volumes on a given disk partition
1750 * note that this function will not allow mp-fast
1751 * shutdown of a partition */
1753 VShutdownByPartition_r(struct DiskPartition64 * dp)
1759 /* wait for other exclusive ops to finish */
1760 VVByPListWait_r(dp);
1762 /* begin exclusive access */
1763 VVByPListBeginExclusive_r(dp);
1765 /* pick the low-hanging fruit first,
1766 * then do the complicated ones last
1767 * (has the advantage of keeping
1768 * in-use volumes up until the bitter end) */
1769 for (pass = 0, total=0; pass < 4; pass++) {
1770 pass_stats[pass] = ShutdownVByPForPass_r(dp, pass);
1771 total += pass_stats[pass];
1774 /* end exclusive access */
1775 VVByPListEndExclusive_r(dp);
1777 Log("VShutdownByPartition: shut down %d volumes on %s (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1778 total, VPartitionPath(dp), pass_stats[0], pass_stats[1], pass_stats[2], pass_stats[3]);
1783 /* internal shutdown functionality
1785 * for multi-pass shutdown:
1786 * 0 to only "shutdown" {pre,un}attached and error state volumes
1787 * 1 to also shutdown attached volumes w/ volume header loaded
1788 * 2 to also shutdown attached volumes w/o volume header loaded
1789 * 3 to also shutdown exclusive state volumes
1791 * caller MUST hold exclusive access on the hash chain
1792 * because we drop vol_glock_mutex internally
1794 * this function is reentrant for passes 1--3
1795 * (e.g. multiple threads can cooperate to
1796 * shutdown a partition mp-fast)
1798 * pass 0 is not scaleable because the volume state data is
1799 * synchronized by vol_glock mutex, and the locking overhead
1800 * is too high to drop the lock long enough to do linked list
1804 ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass)
1806 struct rx_queue * q = queue_First(&dp->vol_list, rx_queue);
1809 while (ShutdownVolumeWalk_r(dp, pass, &q))
1815 /* conditionally shutdown one volume on partition dp
1816 * returns 1 if a volume was shutdown in this pass,
1819 ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
1820 struct rx_queue ** idx)
1822 struct rx_queue *qp, *nqp;
1827 for (queue_ScanFrom(&dp->vol_list, qp, qp, nqp, rx_queue)) {
1828 vp = (Volume *) (((char *)qp) - offsetof(Volume, vol_list));
1832 if ((V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1833 (V_attachState(vp) != VOL_STATE_ERROR) &&
1834 (V_attachState(vp) != VOL_STATE_DELETED) &&
1835 (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1839 if ((V_attachState(vp) == VOL_STATE_ATTACHED) &&
1840 (vp->header == NULL)) {
1844 if (VIsExclusiveState(V_attachState(vp))) {
1849 DeleteVolumeFromVByPList_r(vp);
1850 VShutdownVolume_r(vp);
1860 * shutdown a specific volume
1862 /* caller MUST NOT hold a heavyweight ref on vp */
1864 VShutdownVolume_r(Volume * vp)
1868 VCreateReservation_r(vp);
1870 if (LogLevel >= 5) {
1871 Log("VShutdownVolume_r: vid=%u, device=%d, state=%hu\n",
1872 vp->hashid, vp->partition->device, V_attachState(vp));
1875 /* wait for other blocking ops to finish */
1876 VWaitExclusiveState_r(vp);
1878 osi_Assert(VIsValidState(V_attachState(vp)));
1880 switch(V_attachState(vp)) {
1881 case VOL_STATE_SALVAGING:
1882 /* Leave salvaging volumes alone. Any in-progress salvages will
1883 * continue working after viced shuts down. This is intentional.
1886 case VOL_STATE_PREATTACHED:
1887 case VOL_STATE_ERROR:
1888 VChangeState_r(vp, VOL_STATE_UNATTACHED);
1889 case VOL_STATE_UNATTACHED:
1890 case VOL_STATE_DELETED:
1892 case VOL_STATE_GOING_OFFLINE:
1893 case VOL_STATE_SHUTTING_DOWN:
1894 case VOL_STATE_ATTACHED:
1898 Log("VShutdown: Attempting to take volume %u offline.\n",
1901 /* take the volume offline (drops reference count) */
1902 VOffline_r(vp, "File server was shut down");
1909 VCancelReservation_r(vp);
1913 #endif /* AFS_DEMAND_ATTACH_FS */
1916 /***************************************************/
1917 /* Header I/O routines */
1918 /***************************************************/
1920 /* open a descriptor for the inode (h),
1921 * read in an on-disk structure into buffer (to) of size (size),
1922 * verify versionstamp in structure has magic (magic) and
1923 * optionally verify version (version) if (version) is nonzero
1926 ReadHeader(Error * ec, IHandle_t * h, char *to, int size, bit32 magic,
1929 struct versionStamp *vsn;
1944 vsn = (struct versionStamp *)to;
1945 if (FDH_PREAD(fdP, to, size, 0) != size || vsn->magic != magic) {
1947 FDH_REALLYCLOSE(fdP);
1952 /* Check is conditional, in case caller wants to inspect version himself */
1953 if (version && vsn->version != version) {
1959 WriteVolumeHeader_r(Error * ec, Volume * vp)
1961 IHandle_t *h = V_diskDataHandle(vp);
1971 if (FDH_PWRITE(fdP, (char *)&V_disk(vp), sizeof(V_disk(vp)), 0)
1972 != sizeof(V_disk(vp))) {
1974 FDH_REALLYCLOSE(fdP);
1980 /* VolumeHeaderToDisk
1981 * Allows for storing 64 bit inode numbers in on-disk volume header
1984 /* convert in-memory representation of a volume header to the
1985 * on-disk representation of a volume header */
1987 VolumeHeaderToDisk(VolumeDiskHeader_t * dh, VolumeHeader_t * h)
1990 memset(dh, 0, sizeof(VolumeDiskHeader_t));
1991 dh->stamp = h->stamp;
1993 dh->parent = h->parent;
1995 #ifdef AFS_64BIT_IOPS_ENV
1996 dh->volumeInfo_lo = (afs_int32) h->volumeInfo & 0xffffffff;
1997 dh->volumeInfo_hi = (afs_int32) (h->volumeInfo >> 32) & 0xffffffff;
1998 dh->smallVnodeIndex_lo = (afs_int32) h->smallVnodeIndex & 0xffffffff;
1999 dh->smallVnodeIndex_hi =
2000 (afs_int32) (h->smallVnodeIndex >> 32) & 0xffffffff;
2001 dh->largeVnodeIndex_lo = (afs_int32) h->largeVnodeIndex & 0xffffffff;
2002 dh->largeVnodeIndex_hi =
2003 (afs_int32) (h->largeVnodeIndex >> 32) & 0xffffffff;
2004 dh->linkTable_lo = (afs_int32) h->linkTable & 0xffffffff;
2005 dh->linkTable_hi = (afs_int32) (h->linkTable >> 32) & 0xffffffff;
2007 dh->volumeInfo_lo = h->volumeInfo;
2008 dh->smallVnodeIndex_lo = h->smallVnodeIndex;
2009 dh->largeVnodeIndex_lo = h->largeVnodeIndex;
2010 dh->linkTable_lo = h->linkTable;
2014 /* DiskToVolumeHeader
2015 * Converts an on-disk representation of a volume header to
2016 * the in-memory representation of a volume header.
2018 * Makes the assumption that AFS has *always*
2019 * zero'd the volume header file so that high parts of inode
2020 * numbers are 0 in older (SGI EFS) volume header files.
2023 DiskToVolumeHeader(VolumeHeader_t * h, VolumeDiskHeader_t * dh)
2025 memset(h, 0, sizeof(VolumeHeader_t));
2026 h->stamp = dh->stamp;
2028 h->parent = dh->parent;
2030 #ifdef AFS_64BIT_IOPS_ENV
2032 (Inode) dh->volumeInfo_lo | ((Inode) dh->volumeInfo_hi << 32);
2034 h->smallVnodeIndex =
2035 (Inode) dh->smallVnodeIndex_lo | ((Inode) dh->
2036 smallVnodeIndex_hi << 32);
2038 h->largeVnodeIndex =
2039 (Inode) dh->largeVnodeIndex_lo | ((Inode) dh->
2040 largeVnodeIndex_hi << 32);
2042 (Inode) dh->linkTable_lo | ((Inode) dh->linkTable_hi << 32);
2044 h->volumeInfo = dh->volumeInfo_lo;
2045 h->smallVnodeIndex = dh->smallVnodeIndex_lo;
2046 h->largeVnodeIndex = dh->largeVnodeIndex_lo;
2047 h->linkTable = dh->linkTable_lo;
2052 /***************************************************/
2053 /* Volume Attachment routines */
2054 /***************************************************/
2056 #ifdef AFS_DEMAND_ATTACH_FS
2058 * pre-attach a volume given its path.
2060 * @param[out] ec outbound error code
2061 * @param[in] partition partition path string
2062 * @param[in] name volume id string
2064 * @return volume object pointer
2066 * @note A pre-attached volume will only have its partition
2067 * and hashid fields initialized. At first call to
2068 * VGetVolume, the volume will be fully attached.
2072 VPreAttachVolumeByName(Error * ec, char *partition, char *name)
2076 vp = VPreAttachVolumeByName_r(ec, partition, name);
2082 * pre-attach a volume given its path.
2084 * @param[out] ec outbound error code
2085 * @param[in] partition path to vice partition
2086 * @param[in] name volume id string
2088 * @return volume object pointer
2090 * @pre VOL_LOCK held
2092 * @internal volume package internal use only.
2095 VPreAttachVolumeByName_r(Error * ec, char *partition, char *name)
2097 return VPreAttachVolumeById_r(ec,
2099 VolumeNumber(name));
2103 * pre-attach a volume given its path and numeric volume id.
2105 * @param[out] ec error code return
2106 * @param[in] partition path to vice partition
2107 * @param[in] volumeId numeric volume id
2109 * @return volume object pointer
2111 * @pre VOL_LOCK held
2113 * @internal volume package internal use only.
2116 VPreAttachVolumeById_r(Error * ec,
2121 struct DiskPartition64 *partp;
2125 osi_Assert(programType == fileServer);
2127 if (!(partp = VGetPartition_r(partition, 0))) {
2129 Log("VPreAttachVolumeById_r: Error getting partition (%s)\n", partition);
2133 vp = VLookupVolume_r(ec, volumeId, NULL);
2138 return VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2142 * preattach a volume.
2144 * @param[out] ec outbound error code
2145 * @param[in] partp pointer to partition object
2146 * @param[in] vp pointer to volume object
2147 * @param[in] vid volume id
2149 * @return volume object pointer
2151 * @pre VOL_LOCK is held.
2153 * @warning Returned volume object pointer does not have to
2154 * equal the pointer passed in as argument vp. There
2155 * are potential race conditions which can result in
2156 * the pointers having different values. It is up to
2157 * the caller to make sure that references are handled
2158 * properly in this case.
2160 * @note If there is already a volume object registered with
2161 * the same volume id, its pointer MUST be passed as
2162 * argument vp. Failure to do so will result in a silent
2163 * failure to preattach.
2165 * @internal volume package internal use only.
2168 VPreAttachVolumeByVp_r(Error * ec,
2169 struct DiskPartition64 * partp,
2177 /* check to see if pre-attach already happened */
2179 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
2180 (V_attachState(vp) != VOL_STATE_DELETED) &&
2181 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
2182 !VIsErrorState(V_attachState(vp))) {
2184 * pre-attach is a no-op in all but the following cases:
2186 * - volume is unattached
2187 * - volume is in an error state
2188 * - volume is pre-attached
2190 Log("VPreattachVolumeByVp_r: volume %u not in quiescent state\n", vid);
2193 /* we're re-attaching a volume; clear out some old state */
2194 memset(&vp->salvage, 0, sizeof(struct VolumeOnlineSalvage));
2196 if (V_partition(vp) != partp) {
2197 /* XXX potential race */
2198 DeleteVolumeFromVByPList_r(vp);
2201 /* if we need to allocate a new Volume struct,
2202 * go ahead and drop the vol glock, otherwise
2203 * do the basic setup synchronised, as it's
2204 * probably not worth dropping the lock */
2207 /* allocate the volume structure */
2208 vp = nvp = (Volume *) malloc(sizeof(Volume));
2209 osi_Assert(vp != NULL);
2210 memset(vp, 0, sizeof(Volume));
2211 queue_Init(&vp->vnode_list);
2212 queue_Init(&vp->rx_call_list);
2213 CV_INIT(&V_attachCV(vp), "vp attach", CV_DEFAULT, 0);
2216 /* link the volume with its associated vice partition */
2217 vp->device = partp->device;
2218 vp->partition = partp;
2221 vp->specialStatus = 0;
2223 /* if we dropped the lock, reacquire the lock,
2224 * check for pre-attach races, and then add
2225 * the volume to the hash table */
2228 nvp = VLookupVolume_r(ec, vid, NULL);
2233 } else if (nvp) { /* race detected */
2238 /* hack to make up for VChangeState_r() decrementing
2239 * the old state counter */
2240 VStats.state_levels[0]++;
2244 /* put pre-attached volume onto the hash table
2245 * and bring it up to the pre-attached state */
2246 AddVolumeToHashTable(vp, vp->hashid);
2247 AddVolumeToVByPList_r(vp);
2248 VLRU_Init_Node_r(vp);
2249 VChangeState_r(vp, VOL_STATE_PREATTACHED);
2252 Log("VPreAttachVolumeByVp_r: volume %u pre-attached\n", vp->hashid);
2260 #endif /* AFS_DEMAND_ATTACH_FS */
2262 /* Attach an existing volume, given its pathname, and return a
2263 pointer to the volume header information. The volume also
2264 normally goes online at this time. An offline volume
2265 must be reattached to make it go online */
2267 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
2271 retVal = VAttachVolumeByName_r(ec, partition, name, mode);
2277 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
2280 struct DiskPartition64 *partp;
2285 #ifdef AFS_DEMAND_ATTACH_FS
2286 VolumeStats stats_save;
2288 #endif /* AFS_DEMAND_ATTACH_FS */
2292 volumeId = VolumeNumber(name);
2294 if (!(partp = VGetPartition_r(partition, 0))) {
2296 Log("VAttachVolume: Error getting partition (%s)\n", partition);
2300 if (VRequiresPartLock()) {
2301 osi_Assert(VInit == 3);
2302 VLockPartition_r(partition);
2303 } else if (programType == fileServer) {
2304 #ifdef AFS_DEMAND_ATTACH_FS
2305 /* lookup the volume in the hash table */
2306 vp = VLookupVolume_r(ec, volumeId, NULL);
2312 /* save any counters that are supposed to
2313 * be monotonically increasing over the
2314 * lifetime of the fileserver */
2315 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2317 memset(&stats_save, 0, sizeof(VolumeStats));
2320 /* if there's something in the hash table, and it's not
2321 * in the pre-attach state, then we may need to detach
2322 * it before proceeding */
2323 if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
2324 VCreateReservation_r(vp);
2325 VWaitExclusiveState_r(vp);
2327 /* at this point state must be one of:
2337 if (vp->specialStatus == VBUSY)
2340 /* if it's already attached, see if we can return it */
2341 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2342 VGetVolumeByVp_r(ec, vp);
2343 if (V_inUse(vp) == fileServer) {
2344 VCancelReservation_r(vp);
2348 /* otherwise, we need to detach, and attempt to re-attach */
2349 VDetachVolume_r(ec, vp);
2351 Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
2354 /* if it isn't fully attached, delete from the hash tables,
2355 and let the refcounter handle the rest */
2356 DeleteVolumeFromHashTable(vp);
2357 DeleteVolumeFromVByPList_r(vp);
2360 VCancelReservation_r(vp);
2364 /* pre-attach volume if it hasn't been done yet */
2366 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2367 (V_attachState(vp) == VOL_STATE_DELETED) ||
2368 (V_attachState(vp) == VOL_STATE_ERROR)) {
2370 vp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2376 osi_Assert(vp != NULL);
2378 /* handle pre-attach races
2380 * multiple threads can race to pre-attach a volume,
2381 * but we can't let them race beyond that
2383 * our solution is to let the first thread to bring
2384 * the volume into an exclusive state win; the other
2385 * threads just wait until it finishes bringing the
2386 * volume online, and then they do a vgetvolumebyvp
2388 if (svp && (svp != vp)) {
2389 /* wait for other exclusive ops to finish */
2390 VCreateReservation_r(vp);
2391 VWaitExclusiveState_r(vp);
2393 /* get a heavyweight ref, kill the lightweight ref, and return */
2394 VGetVolumeByVp_r(ec, vp);
2395 VCancelReservation_r(vp);
2399 /* at this point, we are chosen as the thread to do
2400 * demand attachment for this volume. all other threads
2401 * doing a getvolume on vp->hashid will block until we finish */
2403 /* make sure any old header cache entries are invalidated
2404 * before proceeding */
2405 FreeVolumeHeader(vp);
2407 VChangeState_r(vp, VOL_STATE_ATTACHING);
2409 /* restore any saved counters */
2410 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2411 #else /* AFS_DEMAND_ATTACH_FS */
2412 vp = VGetVolume_r(ec, volumeId);
2414 if (V_inUse(vp) == fileServer)
2416 if (vp->specialStatus == VBUSY)
2418 VDetachVolume_r(ec, vp);
2420 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2424 #endif /* AFS_DEMAND_ATTACH_FS */
2428 strcpy(path, VPartitionPath(partp));
2436 vp = (Volume *) calloc(1, sizeof(Volume));
2437 osi_Assert(vp != NULL);
2438 vp->hashid = volumeId;
2439 vp->device = partp->device;
2440 vp->partition = partp;
2441 queue_Init(&vp->vnode_list);
2442 queue_Init(&vp->rx_call_list);
2443 #ifdef AFS_DEMAND_ATTACH_FS
2444 CV_INIT(&V_attachCV(vp), "vp attach", CV_DEFAULT, 0);
2445 #endif /* AFS_DEMAND_ATTACH_FS */
2448 /* attach2 is entered without any locks, and returns
2449 * with vol_glock_mutex held */
2450 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2452 if (VCanUseFSSYNC() && vp) {
2453 #ifdef AFS_DEMAND_ATTACH_FS
2454 if ((mode == V_VOLUPD) || (VolumeWriteable(vp) && (mode == V_CLONE))) {
2455 /* mark volume header as in use so that volser crashes lead to a
2456 * salvage attempt */
2457 VUpdateVolume_r(ec, vp, 0);
2459 /* for dafs, we should tell the fileserver, except for V_PEEK
2460 * where we know it is not necessary */
2461 if (mode == V_PEEK) {
2462 vp->needsPutBack = 0;
2464 vp->needsPutBack = VOL_PUTBACK;
2466 #else /* !AFS_DEMAND_ATTACH_FS */
2467 /* duplicate computation in fssync.c about whether the server
2468 * takes the volume offline or not. If the volume isn't
2469 * offline, we must not return it when we detach the volume,
2470 * or the server will abort */
2471 if (mode == V_READONLY || mode == V_PEEK
2472 || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
2473 vp->needsPutBack = 0;
2475 vp->needsPutBack = VOL_PUTBACK;
2476 #endif /* !AFS_DEMAND_ATTACH_FS */
2478 #ifdef FSSYNC_BUILD_CLIENT
2479 /* Only give back the vol to the fileserver if we checked it out; attach2
2480 * will set checkedOut only if we successfully checked it out from the
2482 if (VCanUseFSSYNC() && vp == NULL && checkedOut) {
2484 #ifdef AFS_DEMAND_ATTACH_FS
2485 /* If we couldn't attach but we scheduled a salvage, we already
2486 * notified the fileserver; don't online it now */
2487 if (*ec != VSALVAGING)
2488 #endif /* AFS_DEMAND_ATTACH_FS */
2489 FSYNC_VolOp(volumeId, partition, FSYNC_VOL_ON, 0, NULL);
2492 if (programType == fileServer && vp) {
2493 #ifdef AFS_DEMAND_ATTACH_FS
2495 * we can get here in cases where we don't "own"
2496 * the volume (e.g. volume owned by a utility).
2497 * short circuit around potential disk header races.
2499 if (V_attachState(vp) != VOL_STATE_ATTACHED) {
2503 VUpdateVolume_r(ec, vp, 0);
2505 Log("VAttachVolume: Error updating volume\n");
2510 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2511 #ifndef AFS_DEMAND_ATTACH_FS
2512 /* This is a hack: by temporarily setting the incore
2513 * dontSalvage flag ON, the volume will be put back on the
2514 * Update list (with dontSalvage OFF again). It will then
2515 * come back in N minutes with DONT_SALVAGE eventually
2516 * set. This is the way that volumes that have never had
2517 * it set get it set; or that volumes that have been
2518 * offline without DONT SALVAGE having been set also
2519 * eventually get it set */
2520 V_dontSalvage(vp) = DONT_SALVAGE;
2521 #endif /* !AFS_DEMAND_ATTACH_FS */
2522 VAddToVolumeUpdateList_r(ec, vp);
2524 Log("VAttachVolume: Error adding volume to update list\n");
2531 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2536 if (VRequiresPartLock()) {
2537 VUnlockPartition_r(partition);
2540 #ifdef AFS_DEMAND_ATTACH_FS
2541 /* attach failed; make sure we're in error state */
2542 if (vp && !VIsErrorState(V_attachState(vp))) {
2543 VChangeState_r(vp, VOL_STATE_ERROR);
2545 #endif /* AFS_DEMAND_ATTACH_FS */
2552 #ifdef AFS_DEMAND_ATTACH_FS
2553 /* VAttachVolumeByVp_r
2555 * finish attaching a volume that is
2556 * in a less than fully attached state
2558 /* caller MUST hold a ref count on vp */
2560 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
2562 char name[VMAXPATHLEN];
2564 struct DiskPartition64 *partp;
2568 Volume * nvp = NULL;
2569 VolumeStats stats_save;
2573 /* volume utility should never call AttachByVp */
2574 osi_Assert(programType == fileServer);
2576 volumeId = vp->hashid;
2577 partp = vp->partition;
2578 VolumeExternalName_r(volumeId, name, sizeof(name));
2581 /* if another thread is performing a blocking op, wait */
2582 VWaitExclusiveState_r(vp);
2584 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2586 /* if it's already attached, see if we can return it */
2587 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2588 VGetVolumeByVp_r(ec, vp);
2589 if (V_inUse(vp) == fileServer) {
2592 if (vp->specialStatus == VBUSY)
2594 VDetachVolume_r(ec, vp);
2596 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2602 /* pre-attach volume if it hasn't been done yet */
2604 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2605 (V_attachState(vp) == VOL_STATE_DELETED) ||
2606 (V_attachState(vp) == VOL_STATE_ERROR)) {
2607 nvp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2613 VCreateReservation_r(nvp);
2618 osi_Assert(vp != NULL);
2619 VChangeState_r(vp, VOL_STATE_ATTACHING);
2621 /* restore monotonically increasing stats */
2622 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2626 /* compute path to disk header */
2627 strcpy(path, VPartitionPath(partp));
2636 * NOTE: attach2 is entered without any locks, and returns
2637 * with vol_glock_mutex held */
2638 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2641 * the event that an error was encountered, or
2642 * the volume was not brought to an attached state
2643 * for any reason, skip to the end. We cannot
2644 * safely call VUpdateVolume unless we "own" it.
2648 (V_attachState(vp) != VOL_STATE_ATTACHED)) {
2652 VUpdateVolume_r(ec, vp, 0);
2654 Log("VAttachVolume: Error updating volume %u\n", vp->hashid);
2658 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2659 #ifndef AFS_DEMAND_ATTACH_FS
2660 /* This is a hack: by temporarily setting the incore
2661 * dontSalvage flag ON, the volume will be put back on the
2662 * Update list (with dontSalvage OFF again). It will then
2663 * come back in N minutes with DONT_SALVAGE eventually
2664 * set. This is the way that volumes that have never had
2665 * it set get it set; or that volumes that have been
2666 * offline without DONT SALVAGE having been set also
2667 * eventually get it set */
2668 V_dontSalvage(vp) = DONT_SALVAGE;
2669 #endif /* !AFS_DEMAND_ATTACH_FS */
2670 VAddToVolumeUpdateList_r(ec, vp);
2672 Log("VAttachVolume: Error adding volume %u to update list\n", vp->hashid);
2679 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2683 VCancelReservation_r(nvp);
2686 if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2687 if (vp && !VIsErrorState(V_attachState(vp))) {
2688 VChangeState_r(vp, VOL_STATE_ERROR);
2697 * lock a volume on disk (non-blocking).
2699 * @param[in] vp The volume to lock
2700 * @param[in] locktype READ_LOCK or WRITE_LOCK
2702 * @return operation status
2703 * @retval 0 success, lock was obtained
2704 * @retval EBUSY a conflicting lock was held by another process
2705 * @retval EIO error acquiring lock
2707 * @pre If we're in the fileserver, vp is in an exclusive state
2709 * @pre vp is not already locked
2712 VLockVolumeNB(Volume *vp, int locktype)
2716 osi_Assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2717 osi_Assert(!(V_attachFlags(vp) & VOL_LOCKED));
2719 code = VLockVolumeByIdNB(vp->hashid, vp->partition, locktype);
2721 V_attachFlags(vp) |= VOL_LOCKED;
2728 * unlock a volume on disk that was locked with VLockVolumeNB.
2730 * @param[in] vp volume to unlock
2732 * @pre If we're in the fileserver, vp is in an exclusive state
2734 * @pre vp has already been locked
2737 VUnlockVolume(Volume *vp)
2739 osi_Assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2740 osi_Assert((V_attachFlags(vp) & VOL_LOCKED));
2742 VUnlockVolumeById(vp->hashid, vp->partition);
2744 V_attachFlags(vp) &= ~VOL_LOCKED;
2746 #endif /* AFS_DEMAND_ATTACH_FS */
2749 * read in a vol header, possibly lock the vol header, and possibly check out
2750 * the vol header from the fileserver, as part of volume attachment.
2752 * @param[out] ec error code
2753 * @param[in] vp volume pointer object
2754 * @param[in] partp disk partition object of the attaching partition
2755 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
2757 * @param[in] peek 1 to just try to read in the volume header and make sure
2758 * we don't try to lock the vol, or check it out from
2759 * FSSYNC or anything like that; 0 otherwise, for 'normal'
2761 * @param[out] acheckedOut If we successfully checked-out the volume from
2762 * the fileserver (if we needed to), this is set
2763 * to 1, otherwise it is untouched.
2765 * @note As part of DAFS volume attachment, the volume header may be either
2766 * read- or write-locked to ensure mutual exclusion of certain volume
2767 * operations. In some cases in order to determine whether we need to
2768 * read- or write-lock the header, we need to read in the header to see
2769 * if the volume is RW or not. So, if we read in the header under a
2770 * read-lock and determine that we actually need a write-lock on the
2771 * volume header, this function will drop the read lock, acquire a write
2772 * lock, and read the header in again.
2775 attach_volume_header(Error *ec, Volume *vp, struct DiskPartition64 *partp,
2776 int mode, int peek, int *acheckedOut)
2778 struct VolumeDiskHeader diskHeader;
2779 struct VolumeHeader header;
2782 int lock_tries = 0, checkout_tries = 0;
2784 VolumeId volid = vp->hashid;
2785 #ifdef FSSYNC_BUILD_CLIENT
2786 int checkout, done_checkout = 0;
2787 #endif /* FSSYNC_BUILD_CLIENT */
2788 #ifdef AFS_DEMAND_ATTACH_FS
2789 int locktype = 0, use_locktype = -1;
2790 #endif /* AFS_DEMAND_ATTACH_FS */
2796 if (lock_tries > VOL_MAX_CHECKOUT_RETRIES) {
2797 Log("VAttachVolume: retried too many times trying to lock header for "
2798 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2799 VPartitionPath(partp));
2803 if (checkout_tries > VOL_MAX_CHECKOUT_RETRIES) {
2804 Log("VAttachVolume: retried too many times trying to checkout "
2805 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2806 VPartitionPath(partp));
2811 if (VReadVolumeDiskHeader(volid, partp, NULL)) {
2812 /* short-circuit the 'volume does not exist' case */
2817 #ifdef FSSYNC_BUILD_CLIENT
2818 checkout = !done_checkout;
2820 if (!peek && checkout && VMustCheckoutVolume(mode)) {
2822 memset(&res, 0, sizeof(res));
2824 if (FSYNC_VolOp(volid, VPartitionPath(partp), FSYNC_VOL_NEEDVOLUME, mode, &res)
2827 if (res.hdr.reason == FSYNC_SALVAGE) {
2828 Log("VAttachVolume: file server says volume %lu is salvaging\n",
2829 afs_printable_uint32_lu(volid));
2832 Log("VAttachVolume: attach of volume %lu apparently denied by file server\n",
2833 afs_printable_uint32_lu(volid));
2834 *ec = VNOVOL; /* XXXX */
2842 #ifdef AFS_DEMAND_ATTACH_FS
2843 if (use_locktype < 0) {
2844 /* don't know whether vol is RO or RW; assume it's RO and we can retry
2845 * if it turns out to be RW */
2846 locktype = VVolLockType(mode, 0);
2849 /* a previous try says we should use use_locktype to lock the volume,
2851 locktype = use_locktype;
2854 if (!peek && locktype) {
2855 code = VLockVolumeNB(vp, locktype);
2857 if (code == EBUSY) {
2858 Log("VAttachVolume: another program has vol %lu locked\n",
2859 afs_printable_uint32_lu(volid));
2861 Log("VAttachVolume: error %d trying to lock vol %lu\n",
2862 code, afs_printable_uint32_lu(volid));
2869 #endif /* AFS_DEMAND_ATTACH_FS */
2871 code = VReadVolumeDiskHeader(volid, partp, &diskHeader);
2881 DiskToVolumeHeader(&header, &diskHeader);
2883 IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header.parent,
2884 header.largeVnodeIndex);
2885 IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header.parent,
2886 header.smallVnodeIndex);
2887 IH_INIT(vp->diskDataHandle, partp->device, header.parent,
2889 IH_INIT(vp->linkHandle, partp->device, header.parent, header.linkTable);
2892 /* only need to do this once */
2894 GetVolumeHeader(vp);
2898 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2899 /* demand attach changes the V_PEEK mechanism
2901 * we can now suck the current disk data structure over
2902 * the fssync interface without going to disk
2904 * (technically, we don't need to restrict this feature
2905 * to demand attach fileservers. However, I'm trying
2906 * to limit the number of common code changes)
2908 if (VCanUseFSSYNC() && (mode == V_PEEK || peek)) {
2910 res.payload.len = sizeof(VolumeDiskData);
2911 res.payload.buf = &vp->header->diskstuff;
2913 if (FSYNC_VolOp(vp->hashid,
2915 FSYNC_VOL_QUERY_HDR,
2918 goto disk_header_loaded;
2921 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2922 (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2923 sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2925 #ifdef AFS_DEMAND_ATTACH_FS
2928 IncUInt64(&VStats.hdr_loads);
2929 IncUInt64(&vp->stats.hdr_loads);
2931 #endif /* AFS_DEMAND_ATTACH_FS */
2934 Log("VAttachVolume: Error reading diskDataHandle header for vol %lu; "
2935 "error=%u\n", afs_printable_uint32_lu(volid), *ec);
2939 #ifdef AFS_DEMAND_ATTACH_FS
2940 # ifdef FSSYNC_BUILD_CLIENT
2942 # endif /* FSSYNC_BUILD_CLIENT */
2944 /* if the lock type we actually used to lock the volume is different than
2945 * the lock type we should have used, retry with the lock type we should
2947 use_locktype = VVolLockType(mode, VolumeWriteable(vp));
2948 if (locktype != use_locktype) {
2952 #endif /* AFS_DEMAND_ATTACH_FS */
2957 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2958 if (!peek && *ec == 0 && retry == 0 && VMustCheckoutVolume(mode)) {
2960 code = FSYNC_VerifyCheckout(volid, VPartitionPath(partp), FSYNC_VOL_NEEDVOLUME, mode);
2962 if (code == SYNC_DENIED) {
2963 /* must retry checkout; fileserver no longer thinks we have
2969 } else if (code != SYNC_OK) {
2973 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2976 /* either we are going to be called again for a second pass, or we
2977 * encountered an error; clean up in either case */
2979 #ifdef AFS_DEMAND_ATTACH_FS
2980 if ((V_attachFlags(vp) & VOL_LOCKED)) {
2983 #endif /* AFS_DEMAND_ATTACH_FS */
2984 if (vp->linkHandle) {
2985 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
2986 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
2987 IH_RELEASE(vp->diskDataHandle);
2988 IH_RELEASE(vp->linkHandle);
3001 #ifdef AFS_DEMAND_ATTACH_FS
3003 attach_check_vop(Error *ec, VolumeId volid, struct DiskPartition64 *partp,
3004 Volume *vp, int *acheckedOut)
3008 if (vp->pending_vol_op) {
3012 if (vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningUnknown) {
3014 code = VVolOpLeaveOnlineNoHeader_r(vp, vp->pending_vol_op);
3016 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3017 } else if (code == 0) {
3018 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3021 /* we need the vol header to determine if the volume can be
3022 * left online for the vop, so... get the header */
3026 /* attach header with peek=1 to avoid checking out the volume
3027 * or locking it; we just want the header info, we're not
3028 * messing with the volume itself at all */
3029 attach_volume_header(ec, vp, partp, V_PEEK, 1, acheckedOut);
3036 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
3037 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3039 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3042 /* make sure we grab a new vol header and re-open stuff on
3043 * actual attachment; we can't keep the data we grabbed, since
3044 * it was not done under a lock and thus not safe */
3045 FreeVolumeHeader(vp);
3046 VReleaseVolumeHandles_r(vp);
3049 /* see if the pending volume op requires exclusive access */
3050 switch (vp->pending_vol_op->vol_op_state) {
3051 case FSSYNC_VolOpPending:
3052 /* this should never happen */
3053 osi_Assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpPending);
3056 case FSSYNC_VolOpRunningUnknown:
3057 /* this should never happen; we resolved 'unknown' above */
3058 osi_Assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
3061 case FSSYNC_VolOpRunningOffline:
3062 /* mark the volume down */
3064 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3066 /* do not set V_offlineMessage here; we don't have ownership of
3067 * the volume (and probably do not have the header loaded), so we
3068 * can't alter the disk header */
3070 /* check to see if we should set the specialStatus flag */
3071 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
3072 vp->specialStatus = VBUSY;
3083 #endif /* AFS_DEMAND_ATTACH_FS */
3086 * volume attachment helper function.
3088 * @param[out] ec error code
3089 * @param[in] volumeId volume ID of the attaching volume
3090 * @param[in] path full path to the volume header .vol file
3091 * @param[in] partp disk partition object for the attaching partition
3092 * @param[in] vp volume object; vp->hashid, vp->device, vp->partition,
3093 * vp->vnode_list, vp->rx_call_list, and V_attachCV (for
3094 * DAFS) should already be initialized
3095 * @param[in] isbusy 1 if vp->specialStatus should be set to VBUSY; that is,
3096 * if there is a volume operation running for this volume
3097 * that should set the volume to VBUSY during its run. 0
3098 * otherwise. (see VVolOpSetVBusy_r)
3099 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
3101 * @param[out] acheckedOut If we successfully checked-out the volume from
3102 * the fileserver (if we needed to), this is set
3103 * to 1, otherwise it is 0.
3105 * @return pointer to the semi-attached volume pointer
3106 * @retval NULL an error occurred (check value of *ec)
3107 * @retval vp volume successfully attaching
3109 * @pre no locks held
3111 * @post VOL_LOCK held
3114 attach2(Error * ec, VolId volumeId, char *path, struct DiskPartition64 *partp,
3115 Volume * vp, int isbusy, int mode, int *acheckedOut)
3117 /* have we read in the header successfully? */
3118 int read_header = 0;
3120 #ifdef AFS_DEMAND_ATTACH_FS
3121 /* should we FreeVolume(vp) instead of VCheckFree(vp) in the error
3125 /* in the case of an error, to what state should the volume be
3127 VolState error_state = VOL_STATE_ERROR;
3128 #endif /* AFS_DEMAND_ATTACH_FS */
3132 vp->vnodeIndex[vLarge].handle = NULL;
3133 vp->vnodeIndex[vSmall].handle = NULL;
3134 vp->diskDataHandle = NULL;
3135 vp->linkHandle = NULL;
3139 #ifdef AFS_DEMAND_ATTACH_FS
3140 attach_check_vop(ec, volumeId, partp, vp, acheckedOut);
3142 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3145 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3146 #endif /* !AFS_DEMAND_ATTACH_FS */
3148 if (*ec == VNOVOL) {
3149 /* if the volume doesn't exist, skip straight to 'error' so we don't
3150 * request a salvage */
3151 goto unlocked_error;
3157 vp->specialStatus = (byte) (isbusy ? VBUSY : 0);
3158 vp->shuttingDown = 0;
3159 vp->goingOffline = 0;
3161 #ifdef AFS_DEMAND_ATTACH_FS
3162 vp->stats.last_attach = FT_ApproxTime();
3163 vp->stats.attaches++;
3167 IncUInt64(&VStats.attaches);
3168 vp->cacheCheck = ++VolumeCacheCheck;
3169 /* just in case this ever rolls over */
3170 if (!vp->cacheCheck)
3171 vp->cacheCheck = ++VolumeCacheCheck;
3174 #ifdef AFS_DEMAND_ATTACH_FS
3175 V_attachFlags(vp) |= VOL_HDR_LOADED;
3176 vp->stats.last_hdr_load = vp->stats.last_attach;
3177 #endif /* AFS_DEMAND_ATTACH_FS */
3181 struct IndexFileHeader iHead;
3183 #if OPENAFS_VOL_STATS
3185 * We just read in the diskstuff part of the header. If the detailed
3186 * volume stats area has not yet been initialized, we should bzero the
3187 * area and mark it as initialized.
3189 if (!(V_stat_initialized(vp))) {
3190 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
3191 V_stat_initialized(vp) = 1;
3193 #endif /* OPENAFS_VOL_STATS */
3195 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
3196 (char *)&iHead, sizeof(iHead),
3197 SMALLINDEXMAGIC, SMALLINDEXVERSION);
3200 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
3205 struct IndexFileHeader iHead;
3207 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
3208 (char *)&iHead, sizeof(iHead),
3209 LARGEINDEXMAGIC, LARGEINDEXVERSION);
3212 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
3216 #ifdef AFS_NAMEI_ENV
3218 struct versionStamp stamp;
3220 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
3221 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
3224 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
3227 #endif /* AFS_NAMEI_ENV */
3229 #if defined(AFS_DEMAND_ATTACH_FS)
3230 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
3232 if (!VCanScheduleSalvage()) {
3233 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3235 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER |
3236 VOL_SALVAGE_NO_OFFLINE);
3241 /* volume operation in progress */
3242 goto unlocked_error;
3244 #else /* AFS_DEMAND_ATTACH_FS */
3246 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3247 goto unlocked_error;
3249 #endif /* AFS_DEMAND_ATTACH_FS */
3251 if (V_needsSalvaged(vp)) {
3252 if (vp->specialStatus)
3253 vp->specialStatus = 0;
3255 #if defined(AFS_DEMAND_ATTACH_FS)
3256 if (!VCanScheduleSalvage()) {
3257 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
3259 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER |
3260 VOL_SALVAGE_NO_OFFLINE);
3263 #else /* AFS_DEMAND_ATTACH_FS */
3265 #endif /* AFS_DEMAND_ATTACH_FS */
3271 vp->nextVnodeUnique = V_uniquifier(vp);
3273 if (VShouldCheckInUse(mode) && V_inUse(vp) && VolumeWriteable(vp)) {
3274 if (!V_needsSalvaged(vp)) {
3275 V_needsSalvaged(vp) = 1;
3276 VUpdateVolume_r(ec, vp, 0);
3278 #if defined(AFS_DEMAND_ATTACH_FS)
3279 if (!VCanScheduleSalvage()) {
3280 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3282 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER |
3283 VOL_SALVAGE_NO_OFFLINE);
3286 #else /* AFS_DEMAND_ATTACH_FS */
3287 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3289 #endif /* AFS_DEMAND_ATTACH_FS */
3294 if (programType == fileServer && V_destroyMe(vp) == DESTROY_ME) {
3295 /* Only check destroyMe if we are the fileserver, since the
3296 * volserver et al sometimes need to work with volumes with
3297 * destroyMe set. Examples are 'temporary' volumes the
3298 * volserver creates, and when we create a volume (destroyMe
3299 * is set on creation; sometimes a separate volserver
3300 * transaction is created to clear destroyMe).
3303 #if defined(AFS_DEMAND_ATTACH_FS)
3304 /* schedule a salvage so the volume goes away on disk */
3305 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER |
3306 VOL_SALVAGE_NO_OFFLINE);
3307 VChangeState_r(vp, VOL_STATE_ERROR);
3310 #endif /* AFS_DEMAND_ATTACH_FS */
3311 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
3316 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
3317 #ifndef BITMAP_LATER
3318 if (programType == fileServer && VolumeWriteable(vp)) {
3320 for (i = 0; i < nVNODECLASSES; i++) {
3321 VGetBitmap_r(ec, vp, i);
3323 #ifdef AFS_DEMAND_ATTACH_FS
3324 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER |
3325 VOL_SALVAGE_NO_OFFLINE);
3327 #endif /* AFS_DEMAND_ATTACH_FS */
3328 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
3334 #endif /* BITMAP_LATER */
3336 if (VInit >= 2 && V_needsCallback(vp)) {
3337 if (V_BreakVolumeCallbacks) {
3338 Log("VAttachVolume: Volume %lu was changed externally; breaking callbacks\n",
3339 afs_printable_uint32_lu(V_id(vp)));
3340 V_needsCallback(vp) = 0;
3342 (*V_BreakVolumeCallbacks) (V_id(vp));
3345 VUpdateVolume_r(ec, vp, 0);
3347 #ifdef FSSYNC_BUILD_CLIENT
3348 else if (VCanUseFSSYNC()) {
3349 afs_int32 fsync_code;
3351 V_needsCallback(vp) = 0;
3353 fsync_code = FSYNC_VolOp(V_id(vp), NULL, FSYNC_VOL_BREAKCBKS, FSYNC_WHATEVER, NULL);
3357 V_needsCallback(vp) = 1;
3358 Log("Error trying to tell the fileserver to break callbacks for "
3359 "changed volume %lu; error code %ld\n",
3360 afs_printable_uint32_lu(V_id(vp)),
3361 afs_printable_int32_ld(fsync_code));
3363 VUpdateVolume_r(ec, vp, 0);
3366 #endif /* FSSYNC_BUILD_CLIENT */
3369 Log("VAttachVolume: error %d clearing needsCallback on volume "
3370 "%lu; needs salvage\n", (int)*ec,
3371 afs_printable_uint32_lu(V_id(vp)));
3372 #ifdef AFS_DEMAND_ATTACH_FS
3373 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER |
3374 VOL_SALVAGE_NO_OFFLINE);
3376 #else /* !AFS_DEMAND_ATTACH_FS */
3378 #endif /* !AFS_DEMAND_ATTACh_FS */
3383 if (programType == fileServer) {
3384 if (vp->specialStatus)
3385 vp->specialStatus = 0;
3386 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
3387 V_inUse(vp) = fileServer;
3388 V_offlineMessage(vp)[0] = '\0';
3392 #ifdef AFS_DEMAND_ATTACH_FS
3393 /* Put the vol into PREATTACHED state, so if someone tries to
3394 * access it again, we try to attach, see that we're not blessed,
3395 * and give a VNOVOL error again. Putting it into UNATTACHED state
3396 * would result in a VOFFLINE error instead. */
3397 error_state = VOL_STATE_PREATTACHED;
3398 #endif /* AFS_DEMAND_ATTACH_FS */
3400 /* mimic e.g. GetVolume errors */
3401 if (!V_blessed(vp)) {
3402 Log("Volume %lu offline: not blessed\n", afs_printable_uint32_lu(V_id(vp)));
3403 FreeVolumeHeader(vp);
3404 } else if (!V_inService(vp)) {
3405 Log("Volume %lu offline: not in service\n", afs_printable_uint32_lu(V_id(vp)));
3406 FreeVolumeHeader(vp);
3408 Log("Volume %lu offline: needs salvage\n", afs_printable_uint32_lu(V_id(vp)));
3410 #ifdef AFS_DEMAND_ATTACH_FS
3411 error_state = VOL_STATE_ERROR;
3412 /* see if we can recover */
3413 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
3416 #ifdef AFS_DEMAND_ATTACH_FS
3422 #ifdef AFS_DEMAND_ATTACH_FS
3423 if ((mode != V_PEEK) && (mode != V_SECRETLY))
3424 V_inUse(vp) = programType;
3425 #endif /* AFS_DEMAND_ATTACH_FS */
3426 V_checkoutMode(vp) = mode;
3429 AddVolumeToHashTable(vp, V_id(vp));
3430 #ifdef AFS_DEMAND_ATTACH_FS
3431 if (VCanUnlockAttached() && (V_attachFlags(vp) & VOL_LOCKED)) {
3434 if ((programType != fileServer) ||
3435 (V_inUse(vp) == fileServer)) {
3436 AddVolumeToVByPList_r(vp);
3438 VChangeState_r(vp, VOL_STATE_ATTACHED);
3440 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3449 #ifdef AFS_DEMAND_ATTACH_FS
3450 if (!VIsErrorState(V_attachState(vp))) {
3451 VChangeState_r(vp, error_state);
3453 #endif /* AFS_DEMAND_ATTACH_FS */
3456 VReleaseVolumeHandles_r(vp);
3459 #ifdef AFS_DEMAND_ATTACH_FS
3466 #else /* !AFS_DEMAND_ATTACH_FS */
3468 #endif /* !AFS_DEMAND_ATTACH_FS */
3472 /* Attach an existing volume.
3473 The volume also normally goes online at this time.
3474 An offline volume must be reattached to make it go online.
3478 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
3482 retVal = VAttachVolume_r(ec, volumeId, mode);
3488 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
3491 VGetVolumePath(ec, volumeId, &part, &name);
3495 vp = VGetVolume_r(&error, volumeId);
3497 osi_Assert(V_inUse(vp) == 0);
3498 VDetachVolume_r(ec, vp);
3502 return VAttachVolumeByName_r(ec, part, name, mode);
3505 /* Increment a reference count to a volume, sans context swaps. Requires
3506 * possibly reading the volume header in from the disk, since there's
3507 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
3509 * N.B. This call can fail if we can't read in the header!! In this case
3510 * we still guarantee we won't context swap, but the ref count won't be
3511 * incremented (otherwise we'd violate the invariant).
3513 /* NOTE: with the demand attach fileserver extensions, the global lock
3514 * is dropped within VHold */
3515 #ifdef AFS_DEMAND_ATTACH_FS
3517 VHold_r(Volume * vp)
3521 VCreateReservation_r(vp);
3522 VWaitExclusiveState_r(vp);
3524 LoadVolumeHeader(&error, vp);
3526 VCancelReservation_r(vp);
3530 VCancelReservation_r(vp);
3533 #else /* AFS_DEMAND_ATTACH_FS */
3535 VHold_r(Volume * vp)
3539 LoadVolumeHeader(&error, vp);
3545 #endif /* AFS_DEMAND_ATTACH_FS */
3547 /**** volume timeout-related stuff ****/
3549 #ifdef AFS_PTHREAD_ENV
3551 static struct timespec *shutdown_timeout;
3552 static pthread_once_t shutdown_timeout_once = PTHREAD_ONCE_INIT;
3555 VTimedOut(const struct timespec *ts)
3560 if (ts->tv_sec == 0) {
3561 /* short-circuit; this will have always timed out */
3565 code = gettimeofday(&tv, NULL);
3567 Log("Error %d from gettimeofday, assuming we have not timed out\n", errno);
3568 /* assume no timeout; failure mode is we just wait longer than normal
3569 * instead of returning errors when we shouldn't */
3573 if (tv.tv_sec < ts->tv_sec ||
3574 (tv.tv_sec == ts->tv_sec && tv.tv_usec*1000 < ts->tv_nsec)) {
3583 * Calculate an absolute timeout.
3585 * @param[out] ts A timeout that is "timeout" seconds from now, if we return
3586 * NULL, the memory is not touched
3587 * @param[in] timeout How long the timeout should be from now
3589 * @return timeout to use
3590 * @retval NULL no timeout; wait forever
3591 * @retval non-NULL the given value for "ts"
3595 static struct timespec *
3596 VCalcTimeout(struct timespec *ts, afs_int32 timeout)
3606 ts->tv_sec = ts->tv_nsec = 0;
3610 code = gettimeofday(&now, NULL);
3612 Log("Error %d from gettimeofday, falling back to 'forever' timeout\n", errno);
3616 ts->tv_sec = now.tv_sec + timeout;
3617 ts->tv_nsec = now.tv_usec * 1000;
3623 * Initialize the shutdown_timeout global.
3626 VShutdownTimeoutInit(void)
3628 struct timespec *ts;
3630 ts = malloc(sizeof(*ts));
3632 shutdown_timeout = VCalcTimeout(ts, vol_opts.offline_shutdown_timeout);
3634 if (!shutdown_timeout) {
3640 * Figure out the timeout that should be used for waiting for offline volumes.
3642 * @param[out] ats Storage space for a local timeout value if needed
3644 * @return The timeout value that should be used
3645 * @retval NULL No timeout; wait forever for offlining volumes
3646 * @retval non-NULL A pointer to the absolute time that should be used as
3647 * the deadline for waiting for offlining volumes.
3649 * @note If we return non-NULL, the pointer we return may or may not be the
3652 static const struct timespec *
3653 VOfflineTimeout(struct timespec *ats)
3655 if (vol_shutting_down) {
3656 osi_Assert(pthread_once(&shutdown_timeout_once, VShutdownTimeoutInit) == 0);
3657 return shutdown_timeout;
3659 return VCalcTimeout(ats, vol_opts.offline_timeout);
3663 #else /* AFS_PTHREAD_ENV */
3665 /* Waiting a certain amount of time for offlining volumes is not supported
3666 * for LWP due to a lack of primitives. So, we never time out */
3667 # define VTimedOut(x) (0)
3668 # define VOfflineTimeout(x) (NULL)
3670 #endif /* !AFS_PTHREAD_ENV */
3678 retVal = VHold_r(vp);
3685 VIsGoingOffline_r(struct Volume *vp)
3689 if (vp->goingOffline) {
3690 if (vp->specialStatus) {
3691 code = vp->specialStatus;
3692 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3703 * Tell the caller if a volume is waiting to go offline.
3705 * @param[in] vp The volume we want to know about
3707 * @return volume status
3708 * @retval 0 volume is not waiting to go offline, go ahead and use it
3709 * @retval nonzero volume is waiting to offline, and give the returned code
3710 * as an error to anyone accessing the volume
3712 * @pre VOL_LOCK is NOT held
3713 * @pre caller holds a heavyweight reference on vp
3716 VIsGoingOffline(struct Volume *vp)
3721 code = VIsGoingOffline_r(vp);
3728 * Register an RX call with a volume.
3730 * @param[inout] ec Error code; if unset when passed in, may be set if
3731 * the volume starts going offline
3732 * @param[out] client_ec @see GetVolume
3733 * @param[in] vp Volume struct
3734 * @param[in] cbv VCallByVol struct containing the RX call to register
3736 * @pre VOL_LOCK held
3737 * @pre caller holds heavy ref on vp
3742 VRegisterCall_r(Error *ec, Error *client_ec, Volume *vp, struct VCallByVol *cbv)
3745 #ifdef AFS_DEMAND_ATTACH_FS
3747 /* just in case the volume started going offline after we got the
3748 * reference to it... otherwise, if the volume started going
3749 * offline right at the end of GetVolume(), we might race with the
3750 * RX call scanner, and return success and add our cbv to the
3751 * rx_call_list _after_ the scanner has scanned the list. */
3752 *ec = VIsGoingOffline_r(vp);
3758 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3759 VWaitStateChange_r(vp);
3761 #endif /* AFS_DEMAND_ATTACH_FS */
3763 queue_Prepend(&vp->rx_call_list, cbv);
3768 * Deregister an RX call with a volume.
3770 * @param[in] vp Volume struct
3771 * @param[in] cbv VCallByVol struct containing the RX call to deregister
3773 * @pre VOL_LOCK held
3774 * @pre caller holds heavy ref on vp
3779 VDeregisterCall_r(Volume *vp, struct VCallByVol *cbv)
3781 if (cbv && queue_IsOnQueue(cbv)) {
3782 #ifdef AFS_DEMAND_ATTACH_FS
3783 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3784 VWaitStateChange_r(vp);
3786 #endif /* AFS_DEMAND_ATTACH_FS */
3792 /***************************************************/
3793 /* get and put volume routines */
3794 /***************************************************/
3797 * put back a heavyweight reference to a volume object.
3799 * @param[in] vp volume object pointer
3801 * @pre VOL_LOCK held
3803 * @post heavyweight volume reference put back.
3804 * depending on state, volume may have been taken offline,
3805 * detached, salvaged, freed, etc.
3807 * @internal volume package internal use only
3810 VPutVolume_r(Volume * vp)
3812 osi_Assert(--vp->nUsers >= 0);
3813 if (vp->nUsers == 0) {
3815 ReleaseVolumeHeader(vp->header);
3816 #ifdef AFS_DEMAND_ATTACH_FS
3817 if (!VCheckDetach(vp)) {
3821 #else /* AFS_DEMAND_ATTACH_FS */
3823 #endif /* AFS_DEMAND_ATTACH_FS */
3828 VPutVolume(Volume * vp)
3836 * Puts a volume reference obtained with VGetVolumeWithCall.
3838 * @param[in] vp Volume struct
3839 * @param[in] cbv VCallByVol struct given to VGetVolumeWithCall, or NULL if none
3841 * @pre VOL_LOCK is NOT held
3844 VPutVolumeWithCall(Volume *vp, struct VCallByVol *cbv)
3847 VDeregisterCall_r(vp, cbv);
3852 /* Get a pointer to an attached volume. The pointer is returned regardless
3853 of whether or not the volume is in service or on/off line. An error
3854 code, however, is returned with an indication of the volume's status */
3856 VGetVolume(Error * ec, Error * client_ec, VolId volumeId)
3860 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
3865 /* same as VGetVolume, but if a volume is waiting to go offline, we only wait
3866 * until time ts. If we have waited longer than that, we return that it is
3867 * actually offline, instead of waiting for it to go offline */
3869 VGetVolumeTimed(Error * ec, Error * client_ec, VolId volumeId,
3870 const struct timespec *ts)
3874 retVal = GetVolume(ec, client_ec, volumeId, NULL, ts);
3880 * Get a volume reference associated with an RX call.
3882 * @param[out] ec @see GetVolume
3883 * @param[out] client_ec @see GetVolume
3884 * @param[in] volumeId @see GetVolume
3885 * @param[in] ts How long to wait for going-offline volumes (absolute time).
3886 * If NULL, wait forever. If ts->tv_sec == 0, return immediately
3887 * with an error if the volume is going offline.
3888 * @param[in] cbv Contains an RX call to be associated with this volume
3889 * reference. This call may be interrupted if the volume is
3890 * requested to go offline while we hold a ref on it. Give NULL
3891 * to not associate an RX call with this reference.
3893 * @return @see GetVolume
3895 * @note for LWP builds, ts must be NULL
3897 * @note A reference obtained with this function MUST be put back with
3898 * VPutVolumeWithCall
3901 VGetVolumeWithCall(Error * ec, Error * client_ec, VolId volumeId,
3902 const struct timespec *ts, struct VCallByVol *cbv)
3906 retVal = GetVolume(ec, client_ec, volumeId, NULL, ts);
3907 VRegisterCall_r(ec, client_ec, retVal, cbv);
3913 VGetVolume_r(Error * ec, VolId volumeId)
3915 return GetVolume(ec, NULL, volumeId, NULL, NULL);
3918 /* try to get a volume we've previously looked up */
3919 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
3921 VGetVolumeByVp_r(Error * ec, Volume * vp)
3923 return GetVolume(ec, NULL, vp->hashid, vp, NULL);
3927 * private interface for getting a volume handle
3929 * @param[out] ec error code (0 if no error)
3930 * @param[out] client_ec wire error code to be given to clients
3931 * @param[in] volumeId ID of the volume we want
3932 * @param[in] hint optional hint for hash lookups, or NULL
3933 * @param[in] timeout absolute deadline for waiting for the volume to go
3934 * offline, if it is going offline. NULL to wait forever.
3936 * @return a volume handle for the specified volume
3937 * @retval NULL an error occurred, or the volume is in such a state that
3938 * we cannot load a header or return any volume struct
3940 * @note for DAFS, caller must NOT hold a ref count on 'hint'
3942 * @note 'timeout' is only checked if the volume is actually going offline; so
3943 * if you pass timeout->tv_sec = 0, this will exhibit typical
3944 * nonblocking behavior.
3946 * @note for LWP builds, 'timeout' must be NULL
3949 GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint,
3950 const struct timespec *timeout)
3953 /* pull this profiling/debugging code out of regular builds */
3955 #define VGET_CTR_INC(x) x++
3956 unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
3957 0, V7 = 0, V8 = 0, V9 = 0;
3958 unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
3960 #define VGET_CTR_INC(x)
3962 #ifdef AFS_DEMAND_ATTACH_FS
3963 Volume *avp, * rvp = hint;
3967 * if VInit is zero, the volume package dynamic
3968 * data structures have not been initialized yet,
3969 * and we must immediately return an error
3975 *client_ec = VOFFLINE;
3980 #ifdef AFS_DEMAND_ATTACH_FS
3982 VCreateReservation_r(rvp);
3984 #endif /* AFS_DEMAND_ATTACH_FS */
3992 vp = VLookupVolume_r(ec, volumeId, vp);
3998 #ifdef AFS_DEMAND_ATTACH_FS
3999 if (rvp && (rvp != vp)) {
4000 /* break reservation on old vp */
4001 VCancelReservation_r(rvp);
4004 #endif /* AFS_DEMAND_ATTACH_FS */
4010 /* Until we have reached an initialization level of 2
4011 * we don't know whether this volume exists or not.
4012 * We can't sleep and retry later because before a volume
4013 * is attached, the caller tries to get it first. Just
4014 * return VOFFLINE and the caller can choose whether to
4015 * retry the command or not. */
4025 IncUInt64(&VStats.hdr_gets);
4027 #ifdef AFS_DEMAND_ATTACH_FS
4028 /* block if someone else is performing an exclusive op on this volume */
4031 VCreateReservation_r(rvp);
4033 VWaitExclusiveState_r(vp);
4035 /* short circuit with VNOVOL in the following circumstances:
4038 * - VOL_STATE_SHUTTING_DOWN
4040 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
4041 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN) ||
4042 (V_attachState(vp) == VOL_STATE_GOING_OFFLINE)) {
4049 * short circuit with VOFFLINE for VOL_STATE_UNATTACHED and
4050 * VNOVOL for VOL_STATE_DELETED
4052 if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
4053 (V_attachState(vp) == VOL_STATE_DELETED)) {
4054 if (vp->specialStatus) {
4055 *ec = vp->specialStatus;
4056 } else if (V_attachState(vp) == VOL_STATE_DELETED) {
4065 /* allowable states:
4072 if (vp->salvage.requested) {
4073 VUpdateSalvagePriority_r(vp);
4076 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
4077 avp = VAttachVolumeByVp_r(ec, vp, 0);
4080 /* VAttachVolumeByVp_r can return a pointer
4081 * != the vp passed to it under certain
4082 * conditions; make sure we don't leak
4083 * reservations if that happens */
4085 VCancelReservation_r(rvp);
4087 VCreateReservation_r(rvp);
4097 if (!vp->pending_vol_op) {
4112 if (VIsSalvaging(vp) || (*ec == VSALVAGING)) {
4114 /* see CheckVnode() in afsfileprocs.c for an explanation
4115 * of this error code logic */
4116 afs_uint32 now = FT_ApproxTime();
4117 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
4120 *client_ec = VRESTARTING;
4129 #ifdef AFS_DEMAND_ATTACH_FS
4131 * this test MUST happen after VAttachVolymeByVp, so vol_op_state is
4132 * not VolOpRunningUnknown (attach2 would have converted it to Online
4136 /* only valid before/during demand attachment */
4137 osi_Assert(!vp->pending_vol_op || vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
4139 /* deny getvolume due to running mutually exclusive vol op */
4140 if (vp->pending_vol_op && vp->pending_vol_op->vol_op_state==FSSYNC_VolOpRunningOffline) {
4142 * volume cannot remain online during this volume operation.
4145 if (vp->specialStatus) {
4147 * special status codes outrank normal VOFFLINE code
4149 *ec = vp->specialStatus;
4151 *client_ec = vp->specialStatus;
4155 /* see CheckVnode() in afsfileprocs.c for an explanation
4156 * of this error code logic */
4157 afs_uint32 now = FT_ApproxTime();
4158 if ((vp->stats.last_vol_op + (10 * 60)) >= now) {
4161 *client_ec = VRESTARTING;
4166 VChangeState_r(vp, VOL_STATE_UNATTACHED);
4167 FreeVolumeHeader(vp);
4171 #endif /* AFS_DEMAND_ATTACH_FS */
4173 LoadVolumeHeader(ec, vp);
4176 /* Only log the error if it was a totally unexpected error. Simply
4177 * a missing inode is likely to be caused by the volume being deleted */
4178 if (errno != ENXIO || LogLevel)
4179 Log("Volume %u: couldn't reread volume header\n",
4181 #ifdef AFS_DEMAND_ATTACH_FS
4182 if (VCanScheduleSalvage()) {
4183 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
4188 #else /* AFS_DEMAND_ATTACH_FS */
4191 #endif /* AFS_DEMAND_ATTACH_FS */
4196 if (vp->shuttingDown) {
4203 if (programType == fileServer) {
4205 if (vp->goingOffline) {
4206 if (timeout && VTimedOut(timeout)) {
4207 /* we've timed out; don't wait for the vol */
4210 #ifdef AFS_DEMAND_ATTACH_FS
4211 /* wait for the volume to go offline */
4212 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
4213 VTimedWaitStateChange_r(vp, timeout, NULL);
4215 #elif defined(AFS_PTHREAD_ENV)
4216 VOL_CV_TIMEDWAIT(&vol_put_volume_cond, timeout, NULL);
4217 #else /* AFS_PTHREAD_ENV */
4218 /* LWP has no timed wait, so the caller better not be
4220 osi_Assert(!timeout);
4221 LWP_WaitProcess(VPutVolume);
4222 #endif /* AFS_PTHREAD_ENV */
4226 if (vp->specialStatus) {
4228 *ec = vp->specialStatus;
4229 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
4232 } else if (V_inUse(vp) == 0 || vp->goingOffline) {
4243 #ifdef AFS_DEMAND_ATTACH_FS
4244 /* if no error, bump nUsers */
4247 VLRU_UpdateAccess_r(vp);
4250 VCancelReservation_r(rvp);
4253 if (client_ec && !*client_ec) {
4256 #else /* AFS_DEMAND_ATTACH_FS */
4257 /* if no error, bump nUsers */
4264 #endif /* AFS_DEMAND_ATTACH_FS */
4267 osi_Assert(vp || *ec);
4272 /***************************************************/
4273 /* Volume offline/detach routines */
4274 /***************************************************/
4276 /* caller MUST hold a heavyweight ref on vp */
4277 #ifdef AFS_DEMAND_ATTACH_FS
4279 VTakeOffline_r(Volume * vp)
4283 osi_Assert(vp->nUsers > 0);
4284 osi_Assert(programType == fileServer);
4286 VCreateReservation_r(vp);
4287 VWaitExclusiveState_r(vp);
4289 vp->goingOffline = 1;
4290 V_needsSalvaged(vp) = 1;
4292 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
4293 VCancelReservation_r(vp);
4295 #else /* AFS_DEMAND_ATTACH_FS */
4297 VTakeOffline_r(Volume * vp)
4299 osi_Assert(vp->nUsers > 0);
4300 osi_Assert(programType == fileServer);
4302 vp->goingOffline = 1;
4303 V_needsSalvaged(vp) = 1;
4305 #endif /* AFS_DEMAND_ATTACH_FS */
4308 VTakeOffline(Volume * vp)
4316 * force a volume offline.
4318 * @param[in] vp volume object pointer
4319 * @param[in] flags flags (see note below)
4321 * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
4322 * used when VUpdateVolume_r needs to call VForceOffline_r
4323 * (which in turn would normally call VUpdateVolume_r)
4325 * @see VUpdateVolume_r
4327 * @pre VOL_LOCK must be held.
4328 * for DAFS, caller must hold ref.
4330 * @note for DAFS, it _is safe_ to call this function from an
4333 * @post needsSalvaged flag is set.
4334 * for DAFS, salvage is requested.
4335 * no further references to the volume through the volume
4336 * package will be honored.
4337 * all file descriptor and vnode caches are invalidated.
4339 * @warning this is a heavy-handed interface. it results in
4340 * a volume going offline regardless of the current
4341 * reference count state.
4343 * @internal volume package internal use only
4346 VForceOffline_r(Volume * vp, int flags)
4350 #ifdef AFS_DEMAND_ATTACH_FS
4351 VChangeState_r(vp, VOL_STATE_ERROR);
4356 strcpy(V_offlineMessage(vp),
4357 "Forced offline due to internal error: volume needs to be salvaged");
4358 Log("Volume %u forced offline: it needs salvaging!\n", V_id(vp));
4361 vp->goingOffline = 0;
4362 V_needsSalvaged(vp) = 1;
4363 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
4364 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
4367 #ifdef AFS_DEMAND_ATTACH_FS
4368 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
4369 #endif /* AFS_DEMAND_ATTACH_FS */
4371 #ifdef AFS_PTHREAD_ENV
4372 CV_BROADCAST(&vol_put_volume_cond);
4373 #else /* AFS_PTHREAD_ENV */
4374 LWP_NoYieldSignal(VPutVolume);
4375 #endif /* AFS_PTHREAD_ENV */
4377 VReleaseVolumeHandles_r(vp);
4381 * force a volume offline.
4383 * @param[in] vp volume object pointer
4385 * @see VForceOffline_r
4388 VForceOffline(Volume * vp)
4391 VForceOffline_r(vp, 0);
4396 * Iterate over the RX calls associated with a volume, and interrupt them.
4398 * @param[in] vp The volume whose RX calls we want to scan
4400 * @pre VOL_LOCK held
4403 VScanCalls_r(struct Volume *vp)
4405 struct VCallByVol *cbv, *ncbv;
4407 #ifdef AFS_DEMAND_ATTACH_FS
4408 VolState state_save;
4411 if (queue_IsEmpty(&vp->rx_call_list))
4412 return; /* no calls to interrupt */
4413 if (!vol_opts.interrupt_rxcall)
4414 return; /* we have no function with which to interrupt calls */
4415 err = VIsGoingOffline_r(vp);
4417 return; /* we're not going offline anymore */
4419 #ifdef AFS_DEMAND_ATTACH_FS
4420 VWaitExclusiveState_r(vp);
4421 state_save = VChangeState_r(vp, VOL_STATE_SCANNING_RXCALLS);
4423 #endif /* AFS_DEMAND_ATTACH_FS */
4425 for(queue_Scan(&vp->rx_call_list, cbv, ncbv, VCallByVol)) {
4427 struct rx_peer *peer;
4429 peer = rx_PeerOf(rx_ConnectionOf(cbv->call));
4431 Log("Offlining volume %lu while client %s:%u is trying to read "
4432 "from it; kicking client off with error %ld\n",
4433 (long unsigned) vp->hashid,
4434 afs_inet_ntoa_r(rx_HostOf(peer), hoststr),
4435 (unsigned) ntohs(rx_PortOf(peer)),
4438 (*vol_opts.interrupt_rxcall) (cbv->call, err);
4441 #ifdef AFS_DEMAND_ATTACH_FS
4443 VChangeState_r(vp, state_save);
4444 #endif /* AFS_DEMAND_ATTACH_FS */
4447 #ifdef AFS_DEMAND_ATTACH_FS
4449 * Wait for a vp to go offline.
4451 * @param[out] ec 1 if a salvage on the volume has been requested and
4452 * salvok == 0, 0 otherwise
4453 * @param[in] vp The volume to wait for
4454 * @param[in] salvok If 0, we return immediately with *ec = 1 if the volume
4455 * has been requested to salvage. Otherwise we keep waiting
4456 * until the volume has gone offline.
4458 * @pre VOL_LOCK held
4459 * @pre caller holds a lightweight ref on vp
4464 VWaitForOfflineByVp_r(Error *ec, struct Volume *vp, int salvok)
4466 struct timespec timeout_ts;
4467 const struct timespec *ts;
4470 ts = VOfflineTimeout(&timeout_ts);
4474 while (!VIsOfflineState(V_attachState(vp)) && !timedout) {
4475 if (!salvok && vp->salvage.requested) {
4479 VTimedWaitStateChange_r(vp, ts, &timedout);
4482 /* we didn't time out, so the volume must be offline, so we're done */
4486 /* If we got here, we timed out waiting for the volume to go offline.
4487 * Kick off the accessing RX calls and wait again */
4491 while (!VIsOfflineState(V_attachState(vp))) {
4492 if (!salvok && vp->salvage.requested) {
4497 VWaitStateChange_r(vp);
4501 #else /* AFS_DEMAND_ATTACH_FS */
4504 * Wait for a volume to go offline.
4506 * @pre VOL_LOCK held
4508 * @note non-DAFS only (for DAFS, use @see WaitForOfflineByVp_r)
4511 VWaitForOffline_r(Error *ec, VolumeId volid)
4514 const struct timespec *ts;
4515 #ifdef AFS_PTHREAD_ENV
4516 struct timespec timeout_ts;
4519 ts = VOfflineTimeout(&timeout_ts);
4521 vp = GetVolume(ec, NULL, volid, NULL, ts);
4523 /* error occurred so bad that we can't even get a vp; we have no
4524 * information on the vol so we don't know whether to wait, so just
4528 if (!VIsGoingOffline_r(vp)) {
4529 /* volume is no longer going offline, so we're done */
4534 /* If we got here, we timed out waiting for the volume to go offline.
4535 * Kick off the accessing RX calls and wait again */
4541 vp = VGetVolume_r(ec, volid);
4543 /* In case it was reattached... */
4547 #endif /* !AFS_DEMAND_ATTACH_FS */
4549 /* The opposite of VAttachVolume. The volume header is written to disk, with
4550 the inUse bit turned off. A copy of the header is maintained in memory,
4551 however (which is why this is VOffline, not VDetach).
4554 VOffline_r(Volume * vp, char *message)
4557 #ifndef AFS_DEMAND_ATTACH_FS
4558 VolumeId vid = V_id(vp);
4561 osi_Assert(programType != volumeUtility && programType != volumeServer);
4566 if (V_offlineMessage(vp)[0] == '\0')
4567 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4568 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4570 vp->goingOffline = 1;
4571 #ifdef AFS_DEMAND_ATTACH_FS
4572 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4573 VCreateReservation_r(vp);
4575 VWaitForOfflineByVp_r(&error, vp, 1);
4576 VCancelReservation_r(vp);
4577 #else /* AFS_DEMAND_ATTACH_FS */
4579 VWaitForOffline_r(&error, vid);
4580 #endif /* AFS_DEMAND_ATTACH_FS */
4583 #ifdef AFS_DEMAND_ATTACH_FS
4585 * Take a volume offline in order to perform a volume operation.
4587 * @param[inout] ec address in which to store error code
4588 * @param[in] vp volume object pointer
4589 * @param[in] message volume offline status message
4592 * - VOL_LOCK is held
4593 * - caller MUST hold a heavyweight ref on vp
4596 * - volume is taken offline
4597 * - if possible, volume operation is promoted to running state
4598 * - on failure, *ec is set to nonzero
4600 * @note Although this function does not return any value, it may
4601 * still fail to promote our pending volume operation to
4602 * a running state. Any caller MUST check the value of *ec,
4603 * and MUST NOT blindly assume success.
4605 * @warning if the caller does not hold a lightweight ref on vp,
4606 * then it MUST NOT reference vp after this function
4607 * returns to the caller.
4609 * @internal volume package internal use only
4612 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
4615 osi_Assert(vp->pending_vol_op);
4621 if (V_offlineMessage(vp)[0] == '\0')
4622 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4623 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4625 vp->goingOffline = 1;
4626 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4627 VCreateReservation_r(vp);
4630 if (vp->pending_vol_op->com.programType != salvageServer) {
4631 /* do not give corrupted volumes to the volserver */
4636 VWaitForOfflineByVp_r(ec, vp, salvok);
4638 VCancelReservation_r(vp);
4640 #endif /* AFS_DEMAND_ATTACH_FS */
4643 VOffline(Volume * vp, char *message)
4646 VOffline_r(vp, message);
4650 /* This gets used for the most part by utility routines that don't want
4651 * to keep all the volume headers around. Generally, the file server won't
4652 * call this routine, because then the offline message in the volume header
4653 * (or other information) won't be available to clients. For NAMEI, also
4654 * close the file handles. However, the fileserver does call this during
4655 * an attach following a volume operation.
4658 VDetachVolume_r(Error * ec, Volume * vp)
4660 #ifdef FSSYNC_BUILD_CLIENT
4662 struct DiskPartition64 *tpartp;
4663 int notifyServer = 0;
4664 int useDone = FSYNC_VOL_ON;
4666 if (VCanUseFSSYNC()) {
4667 notifyServer = vp->needsPutBack;
4668 if (V_destroyMe(vp) == DESTROY_ME)
4669 useDone = FSYNC_VOL_LEAVE_OFF;
4670 #ifdef AFS_DEMAND_ATTACH_FS
4671 else if (!V_blessed(vp) || !V_inService(vp))
4672 useDone = FSYNC_VOL_LEAVE_OFF;
4675 tpartp = vp->partition;
4677 #endif /* FSSYNC_BUILD_CLIENT */
4679 *ec = 0; /* always "succeeds" */
4680 DeleteVolumeFromHashTable(vp);
4681 vp->shuttingDown = 1;
4682 #ifdef AFS_DEMAND_ATTACH_FS
4683 DeleteVolumeFromVByPList_r(vp);
4685 VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
4687 if (programType != fileServer)
4689 #endif /* AFS_DEMAND_ATTACH_FS */
4691 /* Will be detached sometime in the future--this is OK since volume is offline */
4693 /* XXX the following code should really be moved to VCheckDetach() since the volume
4694 * is not technically detached until the refcounts reach zero
4696 #ifdef FSSYNC_BUILD_CLIENT
4697 if (VCanUseFSSYNC() && notifyServer) {
4698 if (notifyServer == VOL_PUTBACK_DELETE) {
4699 /* Only send FSYNC_VOL_DONE if the volume was actually deleted.
4700 * volserver code will set needsPutBack to VOL_PUTBACK_DELETE
4701 * to signify a deleted volume. */
4702 useDone = FSYNC_VOL_DONE;
4705 * Note: The server is not notified in the case of a bogus volume
4706 * explicitly to make it possible to create a volume, do a partial
4707 * restore, then abort the operation without ever putting the volume
4708 * online. This is essential in the case of a volume move operation
4709 * between two partitions on the same server. In that case, there
4710 * would be two instances of the same volume, one of them bogus,
4711 * which the file server would attempt to put on line
4713 FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
4714 /* XXX this code path is only hit by volume utilities, thus
4715 * V_BreakVolumeCallbacks will always be NULL. if we really
4716 * want to break callbacks in this path we need to use FSYNC_VolOp() */
4718 /* Dettaching it so break all callbacks on it */
4719 if (V_BreakVolumeCallbacks) {
4720 Log("volume %u detached; breaking all call backs\n", volume);
4721 (*V_BreakVolumeCallbacks) (volume);
4725 #endif /* FSSYNC_BUILD_CLIENT */
4729 VDetachVolume(Error * ec, Volume * vp)
4732 VDetachVolume_r(ec, vp);
4737 /***************************************************/
4738 /* Volume fd/inode handle closing routines */
4739 /***************************************************/
4741 /* For VDetachVolume, we close all cached file descriptors, but keep
4742 * the Inode handles in case we need to read from a busy volume.
4744 /* for demand attach, caller MUST hold ref count on vp */
4746 VCloseVolumeHandles_r(Volume * vp)
4748 #ifdef AFS_DEMAND_ATTACH_FS
4749 VolState state_save;
4751 state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
4756 * XXX need to investigate whether we can perform
4757 * DFlushVolume outside of vol_glock_mutex...
4759 * VCloseVnodeFiles_r drops the glock internally */
4760 DFlushVolume(vp->hashid);
4761 VCloseVnodeFiles_r(vp);
4763 #ifdef AFS_DEMAND_ATTACH_FS
4767 /* Too time consuming and unnecessary for the volserver */
4768 if (programType == fileServer) {
4769 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4770 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4771 IH_CONDSYNC(vp->diskDataHandle);
4773 IH_CONDSYNC(vp->linkHandle);
4774 #endif /* AFS_NT40_ENV */
4777 IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
4778 IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
4779 IH_REALLYCLOSE(vp->diskDataHandle);
4780 IH_REALLYCLOSE(vp->linkHandle);
4782 #ifdef AFS_DEMAND_ATTACH_FS
4783 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4788 VChangeState_r(vp, state_save);
4792 /* For both VForceOffline and VOffline, we close all relevant handles.
4793 * For VOffline, if we re-attach the volume, the files may possible be
4794 * different than before.
4796 /* for demand attach, caller MUST hold a ref count on vp */
4798 VReleaseVolumeHandles_r(Volume * vp)
4800 #ifdef AFS_DEMAND_ATTACH_FS
4801 VolState state_save;
4803 state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
4806 /* XXX need to investigate whether we can perform
4807 * DFlushVolume outside of vol_glock_mutex... */
4808 DFlushVolume(vp->hashid);
4810 VReleaseVnodeFiles_r(vp); /* releases the glock internally */
4812 #ifdef AFS_DEMAND_ATTACH_FS
4816 /* Too time consuming and unnecessary for the volserver */
4817 if (programType == fileServer) {
4818 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4819 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4820 IH_CONDSYNC(vp->diskDataHandle);
4822 IH_CONDSYNC(vp->linkHandle);
4823 #endif /* AFS_NT40_ENV */
4826 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
4827 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
4828 IH_RELEASE(vp->diskDataHandle);
4829 IH_RELEASE(vp->linkHandle);
4831 #ifdef AFS_DEMAND_ATTACH_FS
4832 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4837 VChangeState_r(vp, state_save);
4842 /***************************************************/
4843 /* Volume write and fsync routines */
4844 /***************************************************/
4847 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
4849 #ifdef AFS_DEMAND_ATTACH_FS
4850 VolState state_save;
4852 if (flags & VOL_UPDATE_WAIT) {
4853 VCreateReservation_r(vp);
4854 VWaitExclusiveState_r(vp);
4859 if (programType == fileServer)
4861 (V_inUse(vp) ? V_nextVnodeUnique(vp) +
4862 200 : V_nextVnodeUnique(vp));
4864 #ifdef AFS_DEMAND_ATTACH_FS
4865 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4869 WriteVolumeHeader_r(ec, vp);
4871 #ifdef AFS_DEMAND_ATTACH_FS
4873 VChangeState_r(vp, state_save);
4874 if (flags & VOL_UPDATE_WAIT) {
4875 VCancelReservation_r(vp);
4880 Log("VUpdateVolume: error updating volume header, volume %u (%s)\n",
4881 V_id(vp), V_name(vp));
4882 /* try to update on-disk header,
4883 * while preventing infinite recursion */
4884 if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
4885 VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
4891 VUpdateVolume(Error * ec, Volume * vp)
4894 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4899 VSyncVolume_r(Error * ec, Volume * vp, int flags)
4903 #ifdef AFS_DEMAND_ATTACH_FS
4904 VolState state_save;
4907 if (flags & VOL_SYNC_WAIT) {
4908 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4910 VUpdateVolume_r(ec, vp, 0);
4913 #ifdef AFS_DEMAND_ATTACH_FS
4914 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4917 fdP = IH_OPEN(V_diskDataHandle(vp));
4918 osi_Assert(fdP != NULL);
4919 code = FDH_SYNC(fdP);
4920 osi_Assert(code == 0);
4922 #ifdef AFS_DEMAND_ATTACH_FS
4924 VChangeState_r(vp, state_save);
4930 VSyncVolume(Error * ec, Volume * vp)
4933 VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
4938 /***************************************************/
4939 /* Volume dealloaction routines */
4940 /***************************************************/
4942 #ifdef AFS_DEMAND_ATTACH_FS
4944 FreeVolume(Volume * vp)
4946 /* free the heap space, iff it's safe.
4947 * otherwise, pull it out of the hash table, so it
4948 * will get deallocated when all refs to it go away */
4949 if (!VCheckFree(vp)) {
4950 DeleteVolumeFromHashTable(vp);
4951 DeleteVolumeFromVByPList_r(vp);
4953 /* make sure we invalidate the header cache entry */
4954 FreeVolumeHeader(vp);
4957 #endif /* AFS_DEMAND_ATTACH_FS */
4960 ReallyFreeVolume(Volume * vp)
4965 #ifdef AFS_DEMAND_ATTACH_FS
4967 VChangeState_r(vp, VOL_STATE_FREED);
4968 if (vp->pending_vol_op)
4969 free(vp->pending_vol_op);
4970 #endif /* AFS_DEMAND_ATTACH_FS */
4971 for (i = 0; i < nVNODECLASSES; i++)
4972 if (vp->vnodeIndex[i].bitmap)
4973 free(vp->vnodeIndex[i].bitmap);
4974 FreeVolumeHeader(vp);
4975 #ifndef AFS_DEMAND_ATTACH_FS
4976 DeleteVolumeFromHashTable(vp);
4977 #endif /* AFS_DEMAND_ATTACH_FS */
4981 /* check to see if we should shutdown this volume
4982 * returns 1 if volume was freed, 0 otherwise */
4983 #ifdef AFS_DEMAND_ATTACH_FS
4985 VCheckDetach(Volume * vp)
4990 if (vp->nUsers || vp->nWaiters)
4993 if (vp->shuttingDown) {
4995 if ((programType != fileServer) &&
4996 (V_inUse(vp) == programType) &&
4997 ((V_checkoutMode(vp) == V_VOLUPD) ||
4998 (V_checkoutMode(vp) == V_SECRETLY) ||
4999 ((V_checkoutMode(vp) == V_CLONE) &&
5000 (VolumeWriteable(vp))))) {
5002 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5004 Log("VCheckDetach: volume header update for volume %u "
5005 "failed with errno %d\n", vp->hashid, errno);
5008 VReleaseVolumeHandles_r(vp);
5010 ReallyFreeVolume(vp);
5011 if (programType == fileServer) {
5012 CV_BROADCAST(&vol_put_volume_cond);
5017 #else /* AFS_DEMAND_ATTACH_FS */
5019 VCheckDetach(Volume * vp)
5027 if (vp->shuttingDown) {
5029 if ((programType != fileServer) &&
5030 (V_inUse(vp) == programType) &&
5031 ((V_checkoutMode(vp) == V_VOLUPD) ||
5032 (V_checkoutMode(vp) == V_SECRETLY) ||
5033 ((V_checkoutMode(vp) == V_CLONE) &&
5034 (VolumeWriteable(vp))))) {
5036 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5038 Log("VCheckDetach: volume header update for volume %u failed with errno %d\n",
5042 VReleaseVolumeHandles_r(vp);
5043 ReallyFreeVolume(vp);
5044 if (programType == fileServer) {
5045 #if defined(AFS_PTHREAD_ENV)
5046 CV_BROADCAST(&vol_put_volume_cond);
5047 #else /* AFS_PTHREAD_ENV */
5048 LWP_NoYieldSignal(VPutVolume);
5049 #endif /* AFS_PTHREAD_ENV */
5054 #endif /* AFS_DEMAND_ATTACH_FS */
5056 /* check to see if we should offline this volume
5057 * return 1 if volume went offline, 0 otherwise */
5058 #ifdef AFS_DEMAND_ATTACH_FS
5060 VCheckOffline(Volume * vp)
5064 if (vp->goingOffline && !vp->nUsers) {
5066 osi_Assert(programType == fileServer);
5067 osi_Assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
5068 (V_attachState(vp) != VOL_STATE_FREED) &&
5069 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
5070 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
5071 (V_attachState(vp) != VOL_STATE_DELETED));
5075 * VOL_STATE_GOING_OFFLINE
5076 * VOL_STATE_SHUTTING_DOWN
5077 * VIsErrorState(V_attachState(vp))
5078 * VIsExclusiveState(V_attachState(vp))
5081 VCreateReservation_r(vp);
5082 VChangeState_r(vp, VOL_STATE_OFFLINING);
5085 /* must clear the goingOffline flag before we drop the glock */
5086 vp->goingOffline = 0;
5091 /* perform async operations */
5092 VUpdateVolume_r(&error, vp, 0);
5093 VCloseVolumeHandles_r(vp);
5096 if (V_offlineMessage(vp)[0]) {
5097 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5098 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5099 V_offlineMessage(vp));
5101 Log("VOffline: Volume %lu (%s) is now offline\n",
5102 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5106 /* invalidate the volume header cache entry */
5107 FreeVolumeHeader(vp);
5109 /* if nothing changed state to error or salvaging,
5110 * drop state to unattached */
5111 if (!VIsErrorState(V_attachState(vp))) {
5112 VChangeState_r(vp, VOL_STATE_UNATTACHED);
5114 VCancelReservation_r(vp);
5115 /* no usage of vp is safe beyond this point */
5119 #else /* AFS_DEMAND_ATTACH_FS */
5121 VCheckOffline(Volume * vp)
5125 if (vp->goingOffline && !vp->nUsers) {
5127 osi_Assert(programType == fileServer);
5130 vp->goingOffline = 0;
5132 VUpdateVolume_r(&error, vp, 0);
5133 VCloseVolumeHandles_r(vp);
5135 if (V_offlineMessage(vp)[0]) {
5136 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5137 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5138 V_offlineMessage(vp));
5140 Log("VOffline: Volume %lu (%s) is now offline\n",
5141 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5144 FreeVolumeHeader(vp);
5145 #ifdef AFS_PTHREAD_ENV
5146 CV_BROADCAST(&vol_put_volume_cond);
5147 #else /* AFS_PTHREAD_ENV */
5148 LWP_NoYieldSignal(VPutVolume);
5149 #endif /* AFS_PTHREAD_ENV */
5153 #endif /* AFS_DEMAND_ATTACH_FS */
5155 /***************************************************/
5156 /* demand attach fs ref counting routines */
5157 /***************************************************/
5159 #ifdef AFS_DEMAND_ATTACH_FS
5160 /* the following two functions handle reference counting for
5161 * asynchronous operations on volume structs.
5163 * their purpose is to prevent a VDetachVolume or VShutdown
5164 * from free()ing the Volume struct during an async i/o op */
5166 /* register with the async volume op ref counter */
5167 /* VCreateReservation_r moved into inline code header because it
5168 * is now needed in vnode.c -- tkeiser 11/20/2007
5172 * decrement volume-package internal refcount.
5174 * @param vp volume object pointer
5176 * @internal volume package internal use only
5179 * @arg VOL_LOCK is held
5180 * @arg lightweight refcount held
5182 * @post volume waiters refcount is decremented; volume may
5183 * have been deallocated/shutdown/offlined/salvaged/
5184 * whatever during the process
5186 * @warning once you have tossed your last reference (you can acquire
5187 * lightweight refs recursively) it is NOT SAFE to reference
5188 * a volume object pointer ever again
5190 * @see VCreateReservation_r
5192 * @note DEMAND_ATTACH_FS only
5195 VCancelReservation_r(Volume * vp)
5197 osi_Assert(--vp->nWaiters >= 0);
5198 if (vp->nWaiters == 0) {
5200 if (!VCheckDetach(vp)) {
5207 /* check to see if we should free this volume now
5208 * return 1 if volume was freed, 0 otherwise */
5210 VCheckFree(Volume * vp)
5213 if ((vp->nUsers == 0) &&
5214 (vp->nWaiters == 0) &&
5215 !(V_attachFlags(vp) & (VOL_IN_HASH |
5219 ReallyFreeVolume(vp);
5224 #endif /* AFS_DEMAND_ATTACH_FS */
5227 /***************************************************/
5228 /* online volume operations routines */
5229 /***************************************************/
5231 #ifdef AFS_DEMAND_ATTACH_FS
5233 * register a volume operation on a given volume.
5235 * @param[in] vp volume object
5236 * @param[in] vopinfo volume operation info object
5238 * @pre VOL_LOCK is held
5240 * @post volume operation info object attached to volume object.
5241 * volume operation statistics updated.
5243 * @note by "attached" we mean a copy of the passed in object is made
5245 * @internal volume package internal use only
5248 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5250 FSSYNC_VolOp_info * info;
5252 /* attach a vol op info node to the volume struct */
5253 info = (FSSYNC_VolOp_info *) malloc(sizeof(FSSYNC_VolOp_info));
5254 osi_Assert(info != NULL);
5255 memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
5256 vp->pending_vol_op = info;
5259 vp->stats.last_vol_op = FT_ApproxTime();
5260 vp->stats.vol_ops++;
5261 IncUInt64(&VStats.vol_ops);
5267 * deregister the volume operation attached to this volume.
5269 * @param[in] vp volume object pointer
5271 * @pre VOL_LOCK is held
5273 * @post the volume operation info object is detached from the volume object
5275 * @internal volume package internal use only
5278 VDeregisterVolOp_r(Volume * vp)
5280 if (vp->pending_vol_op) {
5281 free(vp->pending_vol_op);
5282 vp->pending_vol_op = NULL;
5286 #endif /* AFS_DEMAND_ATTACH_FS */
5289 * determine whether it is safe to leave a volume online during
5290 * the volume operation described by the vopinfo object.
5292 * @param[in] vp volume object
5293 * @param[in] vopinfo volume operation info object
5295 * @return whether it is safe to leave volume online
5296 * @retval 0 it is NOT SAFE to leave the volume online
5297 * @retval 1 it is safe to leave the volume online during the operation
5300 * @arg VOL_LOCK is held
5301 * @arg disk header attached to vp (heavyweight ref on vp will guarantee
5302 * this condition is met)
5304 * @internal volume package internal use only
5307 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5309 return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
5310 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5311 (vopinfo->com.reason == V_READONLY ||
5312 (!VolumeWriteable(vp) &&
5313 (vopinfo->com.reason == V_CLONE ||
5314 vopinfo->com.reason == V_DUMP)))));
5318 * same as VVolOpLeaveOnline_r, but does not require a volume with an attached
5321 * @param[in] vp volume object
5322 * @param[in] vopinfo volume operation info object
5324 * @return whether it is safe to leave volume online
5325 * @retval 0 it is NOT SAFE to leave the volume online
5326 * @retval 1 it is safe to leave the volume online during the operation
5327 * @retval -1 unsure; volume header is required in order to know whether or
5328 * not is is safe to leave the volume online
5330 * @pre VOL_LOCK is held
5332 * @internal volume package internal use only
5335 VVolOpLeaveOnlineNoHeader_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5337 /* follow the logic in VVolOpLeaveOnline_r; this is the same, except
5338 * assume that we don't know VolumeWriteable; return -1 if the answer
5339 * depends on VolumeWriteable */
5341 if (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline) {
5344 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5345 vopinfo->com.reason == V_READONLY) {
5349 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5350 (vopinfo->com.reason == V_CLONE ||
5351 vopinfo->com.reason == V_DUMP)) {
5353 /* must know VolumeWriteable */
5360 * determine whether VBUSY should be set during this volume operation.
5362 * @param[in] vp volume object
5363 * @param[in] vopinfo volume operation info object
5365 * @return whether VBUSY should be set
5366 * @retval 0 VBUSY does NOT need to be set
5367 * @retval 1 VBUSY SHOULD be set
5369 * @pre VOL_LOCK is held
5371 * @internal volume package internal use only
5374 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5376 return ((vopinfo->com.command == FSYNC_VOL_OFF &&
5377 vopinfo->com.reason == FSYNC_SALVAGE) ||
5378 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5379 (vopinfo->com.reason == V_CLONE ||
5380 vopinfo->com.reason == V_DUMP)));
5384 /***************************************************/
5385 /* online salvager routines */
5386 /***************************************************/
5387 #if defined(AFS_DEMAND_ATTACH_FS)
5390 * offline a volume to let it be salvaged.
5392 * @param[in] vp Volume to offline
5394 * @return whether we offlined the volume successfully
5395 * @retval 0 volume was not offlined
5396 * @retval 1 volume is now offline
5398 * @note This is similar to VCheckOffline, but slightly different. We do not
5399 * deal with vp->goingOffline, and we try to avoid touching the volume
5400 * header except just to set needsSalvaged
5402 * @pre VOL_LOCK held
5403 * @pre vp->nUsers == 0
5404 * @pre V_attachState(vp) == VOL_STATE_SALVAGE_REQ
5407 VOfflineForSalvage_r(struct Volume *vp)
5411 VCreateReservation_r(vp);
5412 VWaitExclusiveState_r(vp);
5414 if (vp->nUsers || V_attachState(vp) == VOL_STATE_SALVAGING) {
5415 /* Someone's using the volume, or someone got to scheduling the salvage
5416 * before us. I don't think either of these should be possible, as we
5417 * should gain no new heavyweight references while we're trying to
5418 * salvage, but just to be sure... */
5419 VCancelReservation_r(vp);
5423 VChangeState_r(vp, VOL_STATE_OFFLINING);
5427 V_needsSalvaged(vp) = 1;
5428 /* ignore error; updating needsSalvaged is just best effort */
5429 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
5431 VCloseVolumeHandles_r(vp);
5433 FreeVolumeHeader(vp);
5435 /* volume has been effectively offlined; we can mark it in the SALVAGING
5436 * state now, which lets FSSYNC give it away */
5437 VChangeState_r(vp, VOL_STATE_SALVAGING);
5439 VCancelReservation_r(vp);
5445 * check whether a salvage needs to be performed on this volume.
5447 * @param[in] vp pointer to volume object
5449 * @return status code
5450 * @retval 0 no salvage scheduled
5451 * @retval 1 a salvage has been scheduled with the salvageserver
5453 * @pre VOL_LOCK is held
5455 * @post if salvage request flag is set and nUsers and nWaiters are zero,
5456 * then a salvage will be requested
5458 * @note this is one of the event handlers called by VCancelReservation_r
5460 * @note the caller must check if the volume needs to be freed after calling
5461 * this; the volume may not have any references or be on any lists after
5462 * we return, and we do not free it
5464 * @see VCancelReservation_r
5466 * @internal volume package internal use only.
5469 VCheckSalvage(Volume * vp)
5472 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5475 if (!vp->salvage.requested) {
5479 /* prevent recursion; some of the code below creates and removes
5480 * lightweight refs, which can call VCheckSalvage */
5481 if (vp->salvage.scheduling) {
5484 vp->salvage.scheduling = 1;
5486 if (V_attachState(vp) == VOL_STATE_SALVAGE_REQ) {
5487 if (!VOfflineForSalvage_r(vp)) {
5488 vp->salvage.scheduling = 0;
5493 if (vp->salvage.requested) {
5494 VScheduleSalvage_r(vp);
5497 vp->salvage.scheduling = 0;
5498 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5503 * request volume salvage.
5505 * @param[out] ec computed client error code
5506 * @param[in] vp volume object pointer
5507 * @param[in] reason reason code (passed to salvageserver via SALVSYNC)
5508 * @param[in] flags see flags note below
5511 * VOL_SALVAGE_INVALIDATE_HEADER causes volume header cache entry
5512 * to be invalidated.
5514 * @pre VOL_LOCK is held.
5516 * @post volume state is changed.
5517 * for fileserver, salvage will be requested once refcount reaches zero.
5519 * @return operation status code
5520 * @retval 0 volume salvage will occur
5521 * @retval 1 volume salvage could not be scheduled
5525 * @note in the fileserver, this call does not synchronously schedule a volume
5526 * salvage. rather, it sets volume state so that when volume refcounts
5527 * reach zero, a volume salvage will occur. by "refcounts", we mean both
5528 * nUsers and nWaiters must be zero.
5530 * @internal volume package internal use only.
5533 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
5537 * for DAFS volume utilities that are not supposed to schedule salvages,
5538 * just transition to error state instead
5540 if (!VCanScheduleSalvage()) {
5541 VChangeState_r(vp, VOL_STATE_ERROR);
5546 if (programType != fileServer && !VCanUseFSSYNC()) {
5547 VChangeState_r(vp, VOL_STATE_ERROR);
5552 if (!vp->salvage.requested) {
5553 vp->salvage.requested = 1;
5554 vp->salvage.reason = reason;
5555 vp->stats.last_salvage = FT_ApproxTime();
5557 /* Note that it is not possible for us to reach this point if a
5558 * salvage is already running on this volume (even if the fileserver
5559 * was restarted during the salvage). If a salvage were running, the
5560 * salvager would have write-locked the volume header file, so when
5561 * we tried to lock the volume header, the lock would have failed,
5562 * and we would have failed during attachment prior to calling
5563 * VRequestSalvage. So we know that we can schedule salvages without
5564 * fear of a salvage already running for this volume. */
5566 if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
5568 /* if we don't need to offline the volume, we can go directly
5569 * to SALVAGING. SALVAGING says the volume is offline and is
5570 * either salvaging or ready to be handed to the salvager.
5571 * SALVAGE_REQ says that we want to salvage the volume, but we
5572 * are waiting for it to go offline first. */
5573 if (flags & VOL_SALVAGE_NO_OFFLINE) {
5574 VChangeState_r(vp, VOL_STATE_SALVAGING);
5576 VChangeState_r(vp, VOL_STATE_SALVAGE_REQ);
5577 if (vp->nUsers == 0) {
5578 /* normally VOfflineForSalvage_r would be called from
5579 * PutVolume et al when nUsers reaches 0, but if
5580 * it's already 0, just do it ourselves, since PutVolume
5581 * isn't going to get called */
5582 VOfflineForSalvage_r(vp);
5587 Log("VRequestSalvage: volume %u online salvaged too many times; forced offline.\n", vp->hashid);
5589 /* make sure neither VScheduleSalvage_r nor
5590 * VUpdateSalvagePriority_r try to schedule another salvage */
5591 vp->salvage.requested = vp->salvage.scheduled = 0;
5593 VChangeState_r(vp, VOL_STATE_ERROR);
5597 if (flags & VOL_SALVAGE_INVALIDATE_HEADER) {
5598 /* Instead of ReleaseVolumeHeader, we do FreeVolumeHeader()
5599 so that the the next VAttachVolumeByVp_r() invocation
5600 of attach2() will pull in a cached header
5601 entry and fail, then load a fresh one from disk and attach
5604 FreeVolumeHeader(vp);
5611 * update salvageserver scheduling priority for a volume.
5613 * @param[in] vp pointer to volume object
5615 * @return operation status
5617 * @retval 1 request denied, or SALVSYNC communications failure
5619 * @pre VOL_LOCK is held.
5621 * @post in-core salvage priority counter is incremented. if at least
5622 * SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
5623 * last SALVSYNC_RAISEPRIO request, we contact the salvageserver
5624 * to update its priority queue. if no salvage is scheduled,
5625 * this function is a no-op.
5627 * @note DAFS fileserver only
5629 * @note this should be called whenever a VGetVolume fails due to a
5630 * pending salvage request
5632 * @todo should set exclusive state and drop glock around salvsync call
5634 * @internal volume package internal use only.
5637 VUpdateSalvagePriority_r(Volume * vp)
5641 #ifdef SALVSYNC_BUILD_CLIENT
5646 now = FT_ApproxTime();
5648 /* update the salvageserver priority queue occasionally so that
5649 * frequently requested volumes get moved to the head of the queue
5651 if ((vp->salvage.scheduled) &&
5652 (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
5653 code = SALVSYNC_SalvageVolume(vp->hashid,
5654 VPartitionPath(vp->partition),
5659 vp->stats.last_salvage_req = now;
5660 if (code != SYNC_OK) {
5664 #endif /* SALVSYNC_BUILD_CLIENT */
5669 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5671 /* A couple of little helper functions. These return true if we tried to
5672 * use this mechanism to schedule a salvage, false if we haven't tried.
5673 * If we did try a salvage then the results are contained in code.
5677 try_SALVSYNC(Volume *vp, char *partName, int *code) {
5678 #ifdef SALVSYNC_BUILD_CLIENT
5679 if (VCanUseSALVSYNC()) {
5680 Log("Scheduling salvage for volume %lu on part %s over SALVSYNC\n",
5681 afs_printable_uint32_lu(vp->hashid), partName);
5683 /* can't use V_id() since there's no guarantee
5684 * we have the disk data header at this point */
5685 *code = SALVSYNC_SalvageVolume(vp->hashid,
5698 try_FSSYNC(Volume *vp, char *partName, int *code) {
5699 #ifdef FSSYNC_BUILD_CLIENT
5700 if (VCanUseFSSYNC()) {
5701 Log("Scheduling salvage for volume %lu on part %s over FSSYNC\n",
5702 afs_printable_uint32_lu(vp->hashid), partName);
5705 * If we aren't the fileserver, tell the fileserver the volume
5706 * needs to be salvaged. We could directly tell the
5707 * salvageserver, but the fileserver keeps track of some stats
5708 * related to salvages, and handles some other salvage-related
5709 * complications for us.
5711 *code = FSYNC_VolOp(vp->hashid, partName,
5712 FSYNC_VOL_FORCE_ERROR, FSYNC_SALVAGE, NULL);
5715 #endif /* FSSYNC_BUILD_CLIENT */
5720 * schedule a salvage with the salvage server or fileserver.
5722 * @param[in] vp pointer to volume object
5724 * @return operation status
5725 * @retval 0 salvage scheduled successfully
5726 * @retval 1 salvage not scheduled, or SALVSYNC/FSSYNC com error
5729 * @arg VOL_LOCK is held.
5730 * @arg nUsers and nWaiters should be zero.
5732 * @post salvageserver or fileserver is sent a salvage request
5734 * @note If we are the fileserver, the request will be sent to the salvage
5735 * server over SALVSYNC. If we are not the fileserver, the request will be
5736 * sent to the fileserver over FSSYNC (FSYNC_VOL_FORCE_ERROR/FSYNC_SALVAGE).
5738 * @note the caller must check if the volume needs to be freed after calling
5739 * this; the volume may not have any references or be on any lists after
5740 * we return, and we do not free it
5744 * @internal volume package internal use only.
5747 VScheduleSalvage_r(Volume * vp)
5751 VolState state_save;
5752 VThreadOptions_t * thread_opts;
5755 osi_Assert(VCanUseSALVSYNC() || VCanUseFSSYNC());
5757 if (vp->nWaiters || vp->nUsers) {
5761 /* prevent endless salvage,attach,salvage,attach,... loops */
5762 if (vp->stats.salvages >= SALVAGE_COUNT_MAX)
5766 * don't perform salvsync ops on certain threads
5768 thread_opts = pthread_getspecific(VThread_key);
5769 if (thread_opts == NULL) {
5770 thread_opts = &VThread_defaults;
5772 if (thread_opts->disallow_salvsync || vol_disallow_salvsync) {
5776 if (vp->salvage.scheduled) {
5780 VCreateReservation_r(vp);
5781 VWaitExclusiveState_r(vp);
5784 * XXX the scheduling process should really be done asynchronously
5785 * to avoid fssync deadlocks
5787 if (!vp->salvage.scheduled) {
5788 /* if we haven't previously scheduled a salvage, do so now
5790 * set the volume to an exclusive state and drop the lock
5791 * around the SALVSYNC call
5793 strlcpy(partName, VPartitionPath(vp->partition), sizeof(partName));
5794 state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
5797 osi_Assert(try_SALVSYNC(vp, partName, &code) ||
5798 try_FSSYNC(vp, partName, &code));
5801 VChangeState_r(vp, state_save);
5803 if (code == SYNC_OK) {
5804 vp->salvage.scheduled = 1;
5805 vp->stats.last_salvage_req = FT_ApproxTime();
5806 if (VCanUseSALVSYNC()) {
5807 /* don't record these stats for non-fileservers; let the
5808 * fileserver take care of these */
5809 vp->stats.salvages++;
5810 IncUInt64(&VStats.salvages);
5815 case SYNC_BAD_COMMAND:
5816 case SYNC_COM_ERROR:
5819 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5820 "denied\n", afs_printable_uint32_lu(vp->hashid));
5823 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5824 "received unknown protocol error %d\n",
5825 afs_printable_uint32_lu(vp->hashid), code);
5829 if (VCanUseFSSYNC()) {
5830 VChangeState_r(vp, VOL_STATE_ERROR);
5835 /* NB: this is cancelling the reservation we obtained above, but we do
5836 * not call VCancelReservation_r, since that may trigger the vp dtor,
5837 * possibly free'ing the vp. We need to keep the vp around after
5838 * this, as the caller may reference vp without any refs. Instead, it
5839 * is the duty of the caller to inspect 'vp' after we return to see if
5840 * needs to be freed. */
5841 osi_Assert(--vp->nWaiters >= 0);
5844 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5846 #ifdef SALVSYNC_BUILD_CLIENT
5849 * connect to the salvageserver SYNC service.
5851 * @return operation status
5855 * @post connection to salvageserver SYNC service established
5857 * @see VConnectSALV_r
5858 * @see VDisconnectSALV
5859 * @see VReconnectSALV
5866 retVal = VConnectSALV_r();
5872 * connect to the salvageserver SYNC service.
5874 * @return operation status
5878 * @pre VOL_LOCK is held.
5880 * @post connection to salvageserver SYNC service established
5883 * @see VDisconnectSALV_r
5884 * @see VReconnectSALV_r
5885 * @see SALVSYNC_clientInit
5887 * @internal volume package internal use only.
5890 VConnectSALV_r(void)
5892 return SALVSYNC_clientInit();
5896 * disconnect from the salvageserver SYNC service.
5898 * @return operation status
5901 * @pre client should have a live connection to the salvageserver
5903 * @post connection to salvageserver SYNC service destroyed
5905 * @see VDisconnectSALV_r
5907 * @see VReconnectSALV
5910 VDisconnectSALV(void)
5913 VDisconnectSALV_r();
5919 * disconnect from the salvageserver SYNC service.
5921 * @return operation status
5925 * @arg VOL_LOCK is held.
5926 * @arg client should have a live connection to the salvageserver.
5928 * @post connection to salvageserver SYNC service destroyed
5930 * @see VDisconnectSALV
5931 * @see VConnectSALV_r
5932 * @see VReconnectSALV_r
5933 * @see SALVSYNC_clientFinis
5935 * @internal volume package internal use only.
5938 VDisconnectSALV_r(void)
5940 return SALVSYNC_clientFinis();
5944 * disconnect and then re-connect to the salvageserver SYNC service.
5946 * @return operation status
5950 * @pre client should have a live connection to the salvageserver
5952 * @post old connection is dropped, and a new one is established
5955 * @see VDisconnectSALV
5956 * @see VReconnectSALV_r
5959 VReconnectSALV(void)
5963 retVal = VReconnectSALV_r();
5969 * disconnect and then re-connect to the salvageserver SYNC service.
5971 * @return operation status
5976 * @arg VOL_LOCK is held.
5977 * @arg client should have a live connection to the salvageserver.
5979 * @post old connection is dropped, and a new one is established
5981 * @see VConnectSALV_r
5982 * @see VDisconnectSALV
5983 * @see VReconnectSALV
5984 * @see SALVSYNC_clientReconnect
5986 * @internal volume package internal use only.
5989 VReconnectSALV_r(void)
5991 return SALVSYNC_clientReconnect();
5993 #endif /* SALVSYNC_BUILD_CLIENT */
5994 #endif /* AFS_DEMAND_ATTACH_FS */
5997 /***************************************************/
5998 /* FSSYNC routines */
5999 /***************************************************/
6001 /* This must be called by any volume utility which needs to run while the
6002 file server is also running. This is separated from VInitVolumePackage2 so
6003 that a utility can fork--and each of the children can independently
6004 initialize communication with the file server */
6005 #ifdef FSSYNC_BUILD_CLIENT
6007 * connect to the fileserver SYNC service.
6009 * @return operation status
6014 * @arg VInit must equal 2.
6015 * @arg Program Type must not be fileserver or salvager.
6017 * @post connection to fileserver SYNC service established
6020 * @see VDisconnectFS
6021 * @see VChildProcReconnectFS
6028 retVal = VConnectFS_r();
6034 * connect to the fileserver SYNC service.
6036 * @return operation status
6041 * @arg VInit must equal 2.
6042 * @arg Program Type must not be fileserver or salvager.
6043 * @arg VOL_LOCK is held.
6045 * @post connection to fileserver SYNC service established
6048 * @see VDisconnectFS_r
6049 * @see VChildProcReconnectFS_r
6051 * @internal volume package internal use only.
6057 osi_Assert((VInit == 2) &&
6058 (programType != fileServer) &&
6059 (programType != salvager));
6060 rc = FSYNC_clientInit();
6068 * disconnect from the fileserver SYNC service.
6071 * @arg client should have a live connection to the fileserver.
6072 * @arg VOL_LOCK is held.
6073 * @arg Program Type must not be fileserver or salvager.
6075 * @post connection to fileserver SYNC service destroyed
6077 * @see VDisconnectFS
6079 * @see VChildProcReconnectFS_r
6081 * @internal volume package internal use only.
6084 VDisconnectFS_r(void)
6086 osi_Assert((programType != fileServer) &&
6087 (programType != salvager));
6088 FSYNC_clientFinis();
6093 * disconnect from the fileserver SYNC service.
6096 * @arg client should have a live connection to the fileserver.
6097 * @arg Program Type must not be fileserver or salvager.
6099 * @post connection to fileserver SYNC service destroyed
6101 * @see VDisconnectFS_r
6103 * @see VChildProcReconnectFS
6114 * connect to the fileserver SYNC service from a child process following a fork.
6116 * @return operation status
6121 * @arg VOL_LOCK is held.
6122 * @arg current FSYNC handle is shared with a parent process
6124 * @post current FSYNC handle is discarded and a new connection to the
6125 * fileserver SYNC service is established
6127 * @see VChildProcReconnectFS
6129 * @see VDisconnectFS_r
6131 * @internal volume package internal use only.
6134 VChildProcReconnectFS_r(void)
6136 return FSYNC_clientChildProcReconnect();
6140 * connect to the fileserver SYNC service from a child process following a fork.
6142 * @return operation status
6146 * @pre current FSYNC handle is shared with a parent process
6148 * @post current FSYNC handle is discarded and a new connection to the
6149 * fileserver SYNC service is established
6151 * @see VChildProcReconnectFS_r
6153 * @see VDisconnectFS
6156 VChildProcReconnectFS(void)
6160 ret = VChildProcReconnectFS_r();
6164 #endif /* FSSYNC_BUILD_CLIENT */
6167 /***************************************************/
6168 /* volume bitmap routines */
6169 /***************************************************/
6172 * allocate a vnode bitmap number for the vnode
6174 * @param[out] ec error code
6175 * @param[in] vp volume object pointer
6176 * @param[in] index vnode index number for the vnode
6177 * @param[in] flags flag values described in note
6179 * @note for DAFS, flags parameter controls locking behavior.
6180 * If (flags & VOL_ALLOC_BITMAP_WAIT) is set, then this function
6181 * will create a reservation and block on any other exclusive
6182 * operations. Otherwise, this function assumes the caller
6183 * already has exclusive access to vp, and we just change the
6186 * @pre VOL_LOCK held
6188 * @return bit number allocated
6194 VAllocBitmapEntry_r(Error * ec, Volume * vp,
6195 struct vnodeIndex *index, int flags)
6199 #ifdef AFS_DEMAND_ATTACH_FS
6200 VolState state_save;
6201 #endif /* AFS_DEMAND_ATTACH_FS */
6205 /* This test is probably redundant */
6206 if (!VolumeWriteable(vp)) {
6207 *ec = (bit32) VREADONLY;
6211 #ifdef AFS_DEMAND_ATTACH_FS
6212 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6213 VCreateReservation_r(vp);
6214 VWaitExclusiveState_r(vp);
6216 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6217 #endif /* AFS_DEMAND_ATTACH_FS */
6220 if ((programType == fileServer) && !index->bitmap) {
6222 #ifndef AFS_DEMAND_ATTACH_FS
6223 /* demand attach fs uses the volume state to avoid races.
6224 * specialStatus field is not used at all */
6226 if (vp->specialStatus == VBUSY) {
6227 if (vp->goingOffline) { /* vos dump waiting for the volume to
6228 * go offline. We probably come here
6229 * from AddNewReadableResidency */
6232 while (vp->specialStatus == VBUSY) {
6233 #ifdef AFS_PTHREAD_ENV
6237 #else /* !AFS_PTHREAD_ENV */
6239 #endif /* !AFS_PTHREAD_ENV */
6243 #endif /* !AFS_DEMAND_ATTACH_FS */
6245 if (!index->bitmap) {
6246 #ifndef AFS_DEMAND_ATTACH_FS
6247 vp->specialStatus = VBUSY; /* Stop anyone else from using it. */
6248 #endif /* AFS_DEMAND_ATTACH_FS */
6249 for (i = 0; i < nVNODECLASSES; i++) {
6250 VGetBitmap_r(ec, vp, i);
6252 #ifdef AFS_DEMAND_ATTACH_FS
6253 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
6254 #else /* AFS_DEMAND_ATTACH_FS */
6255 DeleteVolumeFromHashTable(vp);
6256 vp->shuttingDown = 1; /* Let who has it free it. */
6257 vp->specialStatus = 0;
6258 #endif /* AFS_DEMAND_ATTACH_FS */
6262 #ifndef AFS_DEMAND_ATTACH_FS
6264 vp->specialStatus = 0; /* Allow others to have access. */
6265 #endif /* AFS_DEMAND_ATTACH_FS */
6268 #endif /* BITMAP_LATER */
6270 #ifdef AFS_DEMAND_ATTACH_FS
6272 #endif /* AFS_DEMAND_ATTACH_FS */
6273 bp = index->bitmap + index->bitmapOffset;
6274 ep = index->bitmap + index->bitmapSize;
6276 if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
6278 index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
6281 o = ffs(~*bp) - 1; /* ffs is documented in BSTRING(3) */
6283 ret = ((bp - index->bitmap) * 8 + o);
6284 #ifdef AFS_DEMAND_ATTACH_FS
6286 #endif /* AFS_DEMAND_ATTACH_FS */
6289 bp += sizeof(bit32) /* i.e. 4 */ ;
6291 /* No bit map entry--must grow bitmap */
6293 realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
6294 osi_Assert(bp != NULL);
6296 bp += index->bitmapSize;
6297 memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
6298 index->bitmapOffset = index->bitmapSize;
6299 index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
6301 ret = index->bitmapOffset * 8;
6302 #ifdef AFS_DEMAND_ATTACH_FS
6304 #endif /* AFS_DEMAND_ATTACH_FS */
6307 #ifdef AFS_DEMAND_ATTACH_FS
6308 VChangeState_r(vp, state_save);
6309 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6310 VCancelReservation_r(vp);
6312 #endif /* AFS_DEMAND_ATTACH_FS */
6317 VAllocBitmapEntry(Error * ec, Volume * vp, struct vnodeIndex * index)
6321 retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
6327 VFreeBitMapEntry_r(Error * ec, struct vnodeIndex *index,
6330 unsigned int offset;
6336 #endif /* BITMAP_LATER */
6337 offset = bitNumber >> 3;
6338 if (offset >= index->bitmapSize) {
6342 if (offset < index->bitmapOffset)
6343 index->bitmapOffset = offset & ~3; /* Truncate to nearest bit32 */
6344 *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
6348 VFreeBitMapEntry(Error * ec, struct vnodeIndex *index,
6352 VFreeBitMapEntry_r(ec, index, bitNumber);
6356 /* this function will drop the glock internally.
6357 * for old pthread fileservers, this is safe thanks to vbusy.
6359 * for demand attach fs, caller must have already called
6360 * VCreateReservation_r and VWaitExclusiveState_r */
6362 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
6364 StreamHandle_t *file;
6365 afs_sfsize_t nVnodes, size;
6366 struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
6367 struct vnodeIndex *vip = &vp->vnodeIndex[class];
6368 struct VnodeDiskObject *vnode;
6369 unsigned int unique = 0;
6373 #endif /* BITMAP_LATER */
6374 #ifdef AFS_DEMAND_ATTACH_FS
6375 VolState state_save;
6376 #endif /* AFS_DEMAND_ATTACH_FS */
6380 #ifdef AFS_DEMAND_ATTACH_FS
6381 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6382 #endif /* AFS_DEMAND_ATTACH_FS */
6385 fdP = IH_OPEN(vip->handle);
6386 osi_Assert(fdP != NULL);
6387 file = FDH_FDOPEN(fdP, "r");
6388 osi_Assert(file != NULL);
6389 vnode = (VnodeDiskObject *) malloc(vcp->diskSize);
6390 osi_Assert(vnode != NULL);
6391 size = OS_SIZE(fdP->fd_fd);
6392 osi_Assert(size != -1);
6393 nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
6395 vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4; /* The 10 is a little extra so
6396 * a few files can be created in this volume,
6397 * the whole thing is rounded up to nearest 4
6398 * bytes, because the bit map allocator likes
6401 BitMap = (byte *) calloc(1, vip->bitmapSize);
6402 osi_Assert(BitMap != NULL);
6403 #else /* BITMAP_LATER */
6404 vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
6405 osi_Assert(vip->bitmap != NULL);
6406 vip->bitmapOffset = 0;
6407 #endif /* BITMAP_LATER */
6408 if (STREAM_ASEEK(file, vcp->diskSize) != -1) {
6410 for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
6411 if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
6413 if (vnode->type != vNull) {
6414 if (vnode->vnodeMagic != vcp->magic) {
6415 Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
6420 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6421 #else /* BITMAP_LATER */
6422 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6423 #endif /* BITMAP_LATER */
6424 if (unique <= vnode->uniquifier)
6425 unique = vnode->uniquifier + 1;
6427 #ifndef AFS_PTHREAD_ENV
6428 if ((bitNumber & 0x00ff) == 0x0ff) { /* every 256 iterations */
6431 #endif /* !AFS_PTHREAD_ENV */
6434 if (vp->nextVnodeUnique < unique) {
6435 Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
6438 /* Paranoia, partly justified--I think fclose after fdopen
6439 * doesn't seem to close fd. In any event, the documentation
6440 * doesn't specify, so it's safer to close it twice.
6448 /* There may have been a racing condition with some other thread, both
6449 * creating the bitmaps for this volume. If the other thread was faster
6450 * the pointer to bitmap should already be filled and we can free ours.
6452 if (vip->bitmap == NULL) {
6453 vip->bitmap = BitMap;
6454 vip->bitmapOffset = 0;
6456 free((byte *) BitMap);
6457 #endif /* BITMAP_LATER */
6458 #ifdef AFS_DEMAND_ATTACH_FS
6459 VChangeState_r(vp, state_save);
6460 #endif /* AFS_DEMAND_ATTACH_FS */
6464 /***************************************************/
6465 /* Volume Path and Volume Number utility routines */
6466 /***************************************************/
6469 * find the first occurrence of a volume header file and return the path.
6471 * @param[out] ec outbound error code
6472 * @param[in] volumeId volume id to find
6473 * @param[out] partitionp pointer to disk partition path string
6474 * @param[out] namep pointer to volume header file name string
6476 * @post path to first occurrence of volume header is returned in partitionp
6477 * and namep, or ec is set accordingly.
6479 * @warning this function is NOT re-entrant -- partitionp and namep point to
6480 * static data segments
6482 * @note if a volume utility inadvertently leaves behind a stale volume header
6483 * on a vice partition, it is possible for callers to get the wrong one,
6484 * depending on the order of the disk partition linked list.
6488 VGetVolumePath(Error * ec, VolId volumeId, char **partitionp, char **namep)
6490 static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
6491 char path[VMAXPATHLEN];
6493 struct DiskPartition64 *dp;
6497 (void)afs_snprintf(&name[1], (sizeof name) - 1, VFORMAT, afs_printable_uint32_lu(volumeId));
6498 for (dp = DiskPartitionList; dp; dp = dp->next) {
6499 struct afs_stat status;
6500 strcpy(path, VPartitionPath(dp));
6502 if (afs_stat(path, &status) == 0) {
6503 strcpy(partition, dp->name);
6510 *partitionp = *namep = NULL;
6512 *partitionp = partition;
6518 * extract a volume number from a volume header filename string.
6520 * @param[in] name volume header filename string
6522 * @return volume number
6524 * @note the string must be of the form VFORMAT. the only permissible
6525 * deviation is a leading '/' character.
6530 VolumeNumber(char *name)
6534 return atoi(name + 1);
6538 * compute the volume header filename.
6540 * @param[in] volumeId
6542 * @return volume header filename
6544 * @post volume header filename string is constructed
6546 * @warning this function is NOT re-entrant -- the returned string is
6547 * stored in a static char array. see VolumeExternalName_r
6548 * for a re-entrant equivalent.
6550 * @see VolumeExternalName_r
6552 * @deprecated due to the above re-entrancy warning, this interface should
6553 * be considered deprecated. Please use VolumeExternalName_r
6557 VolumeExternalName(VolumeId volumeId)
6559 static char name[VMAXPATHLEN];
6560 (void)afs_snprintf(name, sizeof name, VFORMAT, afs_printable_uint32_lu(volumeId));
6565 * compute the volume header filename.
6567 * @param[in] volumeId
6568 * @param[inout] name array in which to store filename
6569 * @param[in] len length of name array
6571 * @return result code from afs_snprintf
6573 * @see VolumeExternalName
6576 * @note re-entrant equivalent of VolumeExternalName
6579 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
6581 return afs_snprintf(name, len, VFORMAT, afs_printable_uint32_lu(volumeId));
6585 /***************************************************/
6586 /* Volume Usage Statistics routines */
6587 /***************************************************/
6589 #if OPENAFS_VOL_STATS
6590 #define OneDay (86400) /* 24 hours' worth of seconds */
6592 #define OneDay (24*60*60) /* 24 hours */
6593 #endif /* OPENAFS_VOL_STATS */
6596 Midnight(time_t t) {
6597 struct tm local, *l;
6600 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
6601 l = localtime_r(&t, &local);
6607 /* the following is strictly speaking problematic on the
6608 switching day to daylight saving time, after the switch,
6609 as tm_isdst does not match. Similarly, on the looong day when
6610 switching back the OneDay check will not do what naively expected!
6611 The effects are minor, though, and more a matter of interpreting
6613 #ifndef AFS_PTHREAD_ENV
6616 local.tm_hour = local.tm_min=local.tm_sec = 0;
6617 midnight = mktime(&local);
6618 if (midnight != (time_t) -1) return(midnight);
6620 return( (t/OneDay)*OneDay );
6624 /*------------------------------------------------------------------------
6625 * [export] VAdjustVolumeStatistics
6628 * If we've passed midnight, we need to update all the day use
6629 * statistics as well as zeroing the detailed volume statistics
6630 * (if we are implementing them).
6633 * vp : Pointer to the volume structure describing the lucky
6634 * volume being considered for update.
6640 * Nothing interesting.
6644 *------------------------------------------------------------------------*/
6647 VAdjustVolumeStatistics_r(Volume * vp)
6649 unsigned int now = FT_ApproxTime();
6651 if (now - V_dayUseDate(vp) > OneDay) {
6654 ndays = (now - V_dayUseDate(vp)) / OneDay;
6655 for (i = 6; i > ndays - 1; i--)
6656 V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
6657 for (i = 0; i < ndays - 1 && i < 7; i++)
6658 V_weekUse(vp)[i] = 0;
6660 V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
6662 V_dayUseDate(vp) = Midnight(now);
6664 #if OPENAFS_VOL_STATS
6666 * All we need to do is bzero the entire VOL_STATS_BYTES of
6667 * the detailed volume statistics area.
6669 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
6670 #endif /* OPENAFS_VOL_STATS */
6673 /*It's been more than a day of collection */
6675 * Always return happily.
6678 } /*VAdjustVolumeStatistics */
6681 VAdjustVolumeStatistics(Volume * vp)
6685 retVal = VAdjustVolumeStatistics_r(vp);
6691 VBumpVolumeUsage_r(Volume * vp)
6693 unsigned int now = FT_ApproxTime();
6694 V_accessDate(vp) = now;
6695 if (now - V_dayUseDate(vp) > OneDay)
6696 VAdjustVolumeStatistics_r(vp);
6698 * Save the volume header image to disk after every 128 bumps to dayUse.
6700 if ((V_dayUse(vp)++ & 127) == 0) {
6702 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
6707 VBumpVolumeUsage(Volume * vp)
6710 VBumpVolumeUsage_r(vp);
6715 VSetDiskUsage_r(void)
6717 #ifndef AFS_DEMAND_ATTACH_FS
6718 static int FifteenMinuteCounter = 0;
6722 /* NOTE: Don't attempt to access the partitions list until the
6723 * initialization level indicates that all volumes are attached,
6724 * which implies that all partitions are initialized. */
6725 #ifdef AFS_PTHREAD_ENV
6726 VOL_CV_WAIT(&vol_vinit_cond);
6727 #else /* AFS_PTHREAD_ENV */
6729 #endif /* AFS_PTHREAD_ENV */
6732 VResetDiskUsage_r();
6734 #ifndef AFS_DEMAND_ATTACH_FS
6735 if (++FifteenMinuteCounter == 3) {
6736 FifteenMinuteCounter = 0;
6739 #endif /* !AFS_DEMAND_ATTACH_FS */
6751 /***************************************************/
6752 /* Volume Update List routines */
6753 /***************************************************/
6755 /* The number of minutes that a volume hasn't been updated before the
6756 * "Dont salvage" flag in the volume header will be turned on */
6757 #define SALVAGE_INTERVAL (10*60)
6762 * volume update list functionality has been moved into the VLRU
6763 * the DONT_SALVAGE flag is now set during VLRU demotion
6766 #ifndef AFS_DEMAND_ATTACH_FS
6767 static VolumeId *UpdateList = NULL; /* Pointer to array of Volume ID's */
6768 static int nUpdatedVolumes = 0; /* Updated with entry in UpdateList, salvage after crash flag on */
6769 static int updateSize = 0; /* number of entries possible */
6770 #define UPDATE_LIST_SIZE 128 /* initial size increment (must be a power of 2!) */
6771 #endif /* !AFS_DEMAND_ATTACH_FS */
6774 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
6777 vp->updateTime = FT_ApproxTime();
6778 if (V_dontSalvage(vp) == 0)
6780 V_dontSalvage(vp) = 0;
6781 VSyncVolume_r(ec, vp, 0);
6782 #ifdef AFS_DEMAND_ATTACH_FS
6783 V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
6784 #else /* !AFS_DEMAND_ATTACH_FS */
6787 if (UpdateList == NULL) {
6788 updateSize = UPDATE_LIST_SIZE;
6789 UpdateList = (VolumeId *) malloc(sizeof(VolumeId) * updateSize);
6791 if (nUpdatedVolumes == updateSize) {
6793 if (updateSize > 524288) {
6794 Log("warning: there is likely a bug in the volume update scanner\n");
6798 (VolumeId *) realloc(UpdateList,
6799 sizeof(VolumeId) * updateSize);
6802 osi_Assert(UpdateList != NULL);
6803 UpdateList[nUpdatedVolumes++] = V_id(vp);
6804 #endif /* !AFS_DEMAND_ATTACH_FS */
6807 #ifndef AFS_DEMAND_ATTACH_FS
6809 VScanUpdateList(void)
6814 afs_uint32 now = FT_ApproxTime();
6815 /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
6816 for (i = gap = 0; i < nUpdatedVolumes; i++) {
6818 UpdateList[i - gap] = UpdateList[i];
6820 /* XXX this routine needlessly messes up the Volume LRU by
6821 * breaking the LRU temporal-locality assumptions.....
6822 * we should use a special volume header allocator here */
6823 vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
6826 } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
6827 V_dontSalvage(vp) = DONT_SALVAGE;
6828 VUpdateVolume_r(&error, vp, 0); /* No need to fsync--not critical */
6836 #ifndef AFS_PTHREAD_ENV
6838 #endif /* !AFS_PTHREAD_ENV */
6840 nUpdatedVolumes -= gap;
6842 #endif /* !AFS_DEMAND_ATTACH_FS */
6845 /***************************************************/
6846 /* Volume LRU routines */
6847 /***************************************************/
6852 * with demand attach fs, we attempt to soft detach(1)
6853 * volumes which have not been accessed in a long time
6854 * in order to speed up fileserver shutdown
6856 * (1) by soft detach we mean a process very similar
6857 * to VOffline, except the final state of the
6858 * Volume will be VOL_STATE_PREATTACHED, instead
6859 * of the usual VOL_STATE_UNATTACHED
6861 #ifdef AFS_DEMAND_ATTACH_FS
6863 /* implementation is reminiscent of a generational GC
6865 * queue 0 is newly attached volumes. this queue is
6866 * sorted by attach timestamp
6868 * queue 1 is volumes that have been around a bit
6869 * longer than queue 0. this queue is sorted by
6872 * queue 2 is volumes tha have been around the longest.
6873 * this queue is unsorted
6875 * queue 3 is volumes that have been marked as
6876 * candidates for soft detachment. this queue is
6879 #define VLRU_GENERATIONS 3 /**< number of generations in VLRU */
6880 #define VLRU_QUEUES 5 /**< total number of VLRU queues */
6883 * definition of a VLRU queue.
6886 volatile struct rx_queue q;
6893 * main VLRU data structure.
6896 struct VLRU_q q[VLRU_QUEUES]; /**< VLRU queues */
6899 /** time interval (in seconds) between promotion passes for
6900 * each young generation queue. */
6901 afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
6903 /** time interval (in seconds) between soft detach candidate
6904 * scans for each generation queue.
6906 * scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
6907 * we perform a soft detach pass. */
6908 afs_uint32 scan_interval[VLRU_GENERATIONS+1];
6910 /* scheduler state */
6911 int next_idx; /**< next queue to receive attention */
6912 afs_uint32 last_promotion[VLRU_GENERATIONS-1]; /**< timestamp of last promotion scan */
6913 afs_uint32 last_scan[VLRU_GENERATIONS+1]; /**< timestamp of last detach scan */
6915 int scanner_state; /**< state of scanner thread */
6916 pthread_cond_t cv; /**< state transition CV */
6919 /** global VLRU state */
6920 static struct VLRU volume_LRU;
6923 * defined states for VLRU scanner thread.
6926 VLRU_SCANNER_STATE_OFFLINE = 0, /**< vlru scanner thread is offline */
6927 VLRU_SCANNER_STATE_ONLINE = 1, /**< vlru scanner thread is online */
6928 VLRU_SCANNER_STATE_SHUTTING_DOWN = 2, /**< vlru scanner thread is shutting down */
6929 VLRU_SCANNER_STATE_PAUSING = 3, /**< vlru scanner thread is getting ready to pause */
6930 VLRU_SCANNER_STATE_PAUSED = 4 /**< vlru scanner thread is paused */
6931 } vlru_thread_state_t;
6933 /* vlru disk data header stuff */
6934 #define VLRU_DISK_MAGIC 0x7a8b9cad /**< vlru disk entry magic number */
6935 #define VLRU_DISK_VERSION 1 /**< vlru disk entry version number */
6937 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
6938 #define VLRU_DUMP_EXPIRATION_TIME (60*60*24*7) /* expire vlru data after 1 week */
6941 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
6942 * soft detachment. */
6943 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
6945 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
6946 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
6948 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
6949 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
6951 /** VLRU control flag. non-zero value implies VLRU subsystem is activated. */
6952 static afs_uint32 VLRU_enabled = 1;
6954 /* queue synchronization routines */
6955 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
6956 static void VLRU_EndExclusive_r(struct VLRU_q * q);
6957 static void VLRU_Wait_r(struct VLRU_q * q);
6960 * set VLRU subsystem tunable parameters.
6962 * @param[in] option tunable option to modify
6963 * @param[in] val new value for tunable parameter
6965 * @pre @c VInitVolumePackage2 has not yet been called.
6967 * @post tunable parameter is modified
6971 * @note valid option parameters are:
6972 * @arg @c VLRU_SET_THRESH
6973 * set the period of inactivity after which
6974 * volumes are eligible for soft detachment
6975 * @arg @c VLRU_SET_INTERVAL
6976 * set the time interval between calls
6977 * to the volume LRU "garbage collector"
6978 * @arg @c VLRU_SET_MAX
6979 * set the max number of volumes to deallocate
6983 VLRU_SetOptions(int option, afs_uint32 val)
6985 if (option == VLRU_SET_THRESH) {
6986 VLRU_offline_thresh = val;
6987 } else if (option == VLRU_SET_INTERVAL) {
6988 VLRU_offline_interval = val;
6989 } else if (option == VLRU_SET_MAX) {
6990 VLRU_offline_max = val;
6991 } else if (option == VLRU_SET_ENABLED) {
6994 VLRU_ComputeConstants();
6998 * compute VLRU internal timing parameters.
7000 * @post VLRU scanner thread internal timing parameters are computed
7002 * @note computes internal timing parameters based upon user-modifiable
7003 * tunable parameters.
7007 * @internal volume package internal use only.
7010 VLRU_ComputeConstants(void)
7012 afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
7014 /* compute the candidate scan interval */
7015 volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
7017 /* compute the promotion intervals */
7018 volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
7019 volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
7022 /* compute the gen 0 scan interval */
7023 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
7025 /* compute the gen 0 scan interval */
7026 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
7031 * initialize VLRU subsystem.
7033 * @pre this function has not yet been called
7035 * @post VLRU subsystem is initialized and VLRU scanner thread is starting
7039 * @internal volume package internal use only.
7045 pthread_attr_t attrs;
7048 if (!VLRU_enabled) {
7049 Log("VLRU: disabled\n");
7053 /* initialize each of the VLRU queues */
7054 for (i = 0; i < VLRU_QUEUES; i++) {
7055 queue_Init(&volume_LRU.q[i]);
7056 volume_LRU.q[i].len = 0;
7057 volume_LRU.q[i].busy = 0;
7058 CV_INIT(&volume_LRU.q[i].cv, "vol lru", CV_DEFAULT, 0);
7061 /* setup the timing constants */
7062 VLRU_ComputeConstants();
7064 /* XXX put inside LogLevel check? */
7065 Log("VLRU: starting scanner with the following configuration parameters:\n");
7066 Log("VLRU: offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
7067 Log("VLRU: running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
7068 Log("VLRU: taking up to %d volumes offline per pass\n", VLRU_offline_max);
7069 Log("VLRU: scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
7070 Log("VLRU: scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
7071 Log("VLRU: scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
7073 /* start up the VLRU scanner */
7074 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7075 if (programType == fileServer) {
7076 CV_INIT(&volume_LRU.cv, "vol lru", CV_DEFAULT, 0);
7077 osi_Assert(pthread_attr_init(&attrs) == 0);
7078 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
7079 osi_Assert(pthread_create(&tid, &attrs, &VLRU_ScannerThread, NULL) == 0);
7084 * initialize the VLRU-related fields of a newly allocated volume object.
7086 * @param[in] vp pointer to volume object
7089 * @arg @c VOL_LOCK is held.
7090 * @arg volume object is not on a VLRU queue.
7092 * @post VLRU fields are initialized to indicate that volume object is not
7093 * currently registered with the VLRU subsystem
7097 * @internal volume package interal use only.
7100 VLRU_Init_Node_r(Volume * vp)
7105 osi_Assert(queue_IsNotOnQueue(&vp->vlru));
7106 vp->vlru.idx = VLRU_QUEUE_INVALID;
7110 * add a volume object to a VLRU queue.
7112 * @param[in] vp pointer to volume object
7115 * @arg @c VOL_LOCK is held.
7116 * @arg caller MUST hold a lightweight ref on @p vp.
7117 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7119 * @post the volume object is added to the appropriate VLRU queue
7121 * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
7122 * then the volume is added to that queue. Otherwise, the value
7123 * @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
7124 * volume is added to the NEW generation queue.
7126 * @note @c VOL_LOCK may be dropped internally
7128 * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
7129 * during the add operation, and is restored to the previous
7130 * state prior to return.
7134 * @internal volume package internal use only.
7137 VLRU_Add_r(Volume * vp)
7140 VolState state_save;
7145 if (queue_IsOnQueue(&vp->vlru))
7148 state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
7151 if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
7152 idx = VLRU_QUEUE_NEW;
7155 VLRU_Wait_r(&volume_LRU.q[idx]);
7157 /* repeat check since VLRU_Wait_r may have dropped
7159 if (queue_IsNotOnQueue(&vp->vlru)) {
7161 queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
7162 volume_LRU.q[idx].len++;
7163 V_attachFlags(vp) |= VOL_ON_VLRU;
7164 vp->stats.last_promote = FT_ApproxTime();
7167 VChangeState_r(vp, state_save);
7171 * delete a volume object from a VLRU queue.
7173 * @param[in] vp pointer to volume object
7176 * @arg @c VOL_LOCK is held.
7177 * @arg caller MUST hold a lightweight ref on @p vp.
7178 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7180 * @post volume object is removed from the VLRU queue
7182 * @note @c VOL_LOCK may be dropped internally
7186 * @todo We should probably set volume state to something exlcusive
7187 * (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
7189 * @internal volume package internal use only.
7192 VLRU_Delete_r(Volume * vp)
7199 if (queue_IsNotOnQueue(&vp->vlru))
7205 if (idx == VLRU_QUEUE_INVALID)
7207 VLRU_Wait_r(&volume_LRU.q[idx]);
7208 } while (idx != vp->vlru.idx);
7210 /* now remove from the VLRU and update
7211 * the appropriate counter */
7212 queue_Remove(&vp->vlru);
7213 volume_LRU.q[idx].len--;
7214 vp->vlru.idx = VLRU_QUEUE_INVALID;
7215 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7219 * tell the VLRU subsystem that a volume was just accessed.
7221 * @param[in] vp pointer to volume object
7224 * @arg @c VOL_LOCK is held
7225 * @arg caller MUST hold a lightweight ref on @p vp
7226 * @arg caller MUST NOT hold exclusive ownership of any VLRU queue
7228 * @post volume VLRU access statistics are updated. If the volume was on
7229 * the VLRU soft detach candidate queue, it is moved to the NEW
7232 * @note @c VOL_LOCK may be dropped internally
7236 * @internal volume package internal use only.
7239 VLRU_UpdateAccess_r(Volume * vp)
7241 Volume * rvp = NULL;
7246 if (queue_IsNotOnQueue(&vp->vlru))
7249 osi_Assert(V_attachFlags(vp) & VOL_ON_VLRU);
7251 /* update the access timestamp */
7252 vp->stats.last_get = FT_ApproxTime();
7255 * if the volume is on the soft detach candidate
7256 * list, we need to safely move it back to a
7257 * regular generation. this has to be done
7258 * carefully so we don't race against the scanner
7262 /* if this volume is on the soft detach candidate queue,
7263 * then grab exclusive access to the necessary queues */
7264 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7266 VCreateReservation_r(rvp);
7268 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7269 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7270 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7271 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7274 /* make sure multiple threads don't race to update */
7275 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7276 VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
7280 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7281 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7282 VCancelReservation_r(rvp);
7287 * switch a volume between two VLRU queues.
7289 * @param[in] vp pointer to volume object
7290 * @param[in] new_idx index of VLRU queue onto which the volume will be moved
7291 * @param[in] append controls whether the volume will be appended or
7292 * prepended to the queue. A nonzero value means it will
7293 * be appended; zero means it will be prepended.
7295 * @pre The new (and old, if applicable) queue(s) must either be owned
7296 * exclusively by the calling thread for asynchronous manipulation,
7297 * or the queue(s) must be quiescent and VOL_LOCK must be held.
7298 * Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
7299 * for further details of the queue asynchronous processing mechanism.
7301 * @post If the volume object was already on a VLRU queue, it is
7302 * removed from the queue. Depending on the value of the append
7303 * parameter, the volume object is either appended or prepended
7304 * to the VLRU queue referenced by the new_idx parameter.
7308 * @see VLRU_BeginExclusive_r
7309 * @see VLRU_EndExclusive_r
7312 * @internal volume package internal use only.
7315 VLRU_SwitchQueues(Volume * vp, int new_idx, int append)
7317 if (queue_IsNotOnQueue(&vp->vlru))
7320 queue_Remove(&vp->vlru);
7321 volume_LRU.q[vp->vlru.idx].len--;
7323 /* put the volume back on the correct generational queue */
7325 queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
7327 queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
7330 volume_LRU.q[new_idx].len++;
7331 vp->vlru.idx = new_idx;
7335 * VLRU background thread.
7337 * The VLRU Scanner Thread is responsible for periodically scanning through
7338 * each VLRU queue looking for volumes which should be moved to another
7339 * queue, or soft detached.
7341 * @param[in] args unused thread arguments parameter
7343 * @return unused thread return value
7344 * @retval NULL always
7346 * @internal volume package internal use only.
7349 VLRU_ScannerThread(void * args)
7351 afs_uint32 now, min_delay, delay;
7352 int i, min_idx, min_op, overdue, state;
7354 /* set t=0 for promotion cycle to be
7355 * fileserver startup */
7356 now = FT_ApproxTime();
7357 for (i=0; i < VLRU_GENERATIONS-1; i++) {
7358 volume_LRU.last_promotion[i] = now;
7361 /* don't start the scanner until VLRU_offline_thresh
7362 * plus a small delay for VInitVolumePackage2 to finish
7365 sleep(VLRU_offline_thresh + 60);
7367 /* set t=0 for scan cycle to be now */
7368 now = FT_ApproxTime();
7369 for (i=0; i < VLRU_GENERATIONS+1; i++) {
7370 volume_LRU.last_scan[i] = now;
7374 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
7375 volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
7378 while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
7379 /* check to see if we've been asked to pause */
7380 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
7381 volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
7382 CV_BROADCAST(&volume_LRU.cv);
7384 VOL_CV_WAIT(&volume_LRU.cv);
7385 } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
7388 /* scheduling can happen outside the glock */
7391 /* figure out what is next on the schedule */
7393 /* figure out a potential schedule for the new generation first */
7395 min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
7398 if (min_delay > volume_LRU.scan_interval[0]) {
7399 /* unsigned overflow -- we're overdue to run this scan */
7404 /* if we're not overdue for gen 0, figure out schedule for candidate gen */
7406 i = VLRU_QUEUE_CANDIDATE;
7407 delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
7408 if (delay < min_delay) {
7412 if (delay > volume_LRU.scan_interval[i]) {
7413 /* unsigned overflow -- we're overdue to run this scan */
7420 /* if we're still not overdue for something, figure out schedules for promotions */
7421 for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
7422 delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
7423 if (delay < min_delay) {
7428 if (delay > volume_LRU.promotion_interval[i]) {
7429 /* unsigned overflow -- we're overdue to run this promotion */
7438 /* sleep as needed */
7443 /* do whatever is next */
7446 VLRU_Promote_r(min_idx);
7447 VLRU_Demote_r(min_idx+1);
7449 VLRU_Scan_r(min_idx);
7451 now = FT_ApproxTime();
7454 Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
7456 /* signal that scanner is down */
7457 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7458 CV_BROADCAST(&volume_LRU.cv);
7464 * promote volumes from one VLRU generation to the next.
7466 * This routine scans a VLRU generation looking for volumes which are
7467 * eligible to be promoted to the next generation. All volumes which
7468 * meet the eligibility requirement are promoted.
7470 * Promotion eligibility is based upon meeting both of the following
7473 * @arg The volume has been accessed since the last promotion:
7474 * @c (vp->stats.last_get >= vp->stats.last_promote)
7475 * @arg The last promotion occurred at least
7476 * @c volume_LRU.promotion_interval[idx] seconds ago
7478 * As a performance optimization, promotions are "globbed". In other
7479 * words, we promote arbitrarily large contiguous sublists of elements
7482 * @param[in] idx VLRU queue index to scan
7486 * @internal VLRU internal use only.
7489 VLRU_Promote_r(int idx)
7491 int len, chaining, promote;
7492 afs_uint32 now, thresh;
7493 struct rx_queue *qp, *nqp;
7494 Volume * vp, *start = NULL, *end = NULL;
7496 /* get exclusive access to two chains, and drop the glock */
7497 VLRU_Wait_r(&volume_LRU.q[idx]);
7498 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7499 VLRU_Wait_r(&volume_LRU.q[idx+1]);
7500 VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
7503 thresh = volume_LRU.promotion_interval[idx];
7504 now = FT_ApproxTime();
7507 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7508 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7509 promote = (((vp->stats.last_promote + thresh) <= now) &&
7510 (vp->stats.last_get >= vp->stats.last_promote));
7518 /* promote and prepend chain */
7519 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7533 /* promote and prepend */
7534 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7538 volume_LRU.q[idx].len -= len;
7539 volume_LRU.q[idx+1].len += len;
7542 /* release exclusive access to the two chains */
7544 volume_LRU.last_promotion[idx] = now;
7545 VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
7546 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7549 /* run the demotions */
7551 VLRU_Demote_r(int idx)
7554 int len, chaining, demote;
7555 afs_uint32 now, thresh;
7556 struct rx_queue *qp, *nqp;
7557 Volume * vp, *start = NULL, *end = NULL;
7558 Volume ** salv_flag_vec = NULL;
7559 int salv_vec_offset = 0;
7561 osi_Assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
7563 /* get exclusive access to two chains, and drop the glock */
7564 VLRU_Wait_r(&volume_LRU.q[idx-1]);
7565 VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
7566 VLRU_Wait_r(&volume_LRU.q[idx]);
7567 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7570 /* no big deal if this allocation fails */
7571 if (volume_LRU.q[idx].len) {
7572 salv_flag_vec = (Volume **) malloc(volume_LRU.q[idx].len * sizeof(Volume *));
7575 now = FT_ApproxTime();
7576 thresh = volume_LRU.promotion_interval[idx-1];
7579 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7580 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7581 demote = (((vp->stats.last_promote + thresh) <= now) &&
7582 (vp->stats.last_get < (now - thresh)));
7584 /* we now do volume update list DONT_SALVAGE flag setting during
7585 * demotion passes */
7586 if (salv_flag_vec &&
7587 !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7589 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7590 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7591 salv_flag_vec[salv_vec_offset++] = vp;
7592 VCreateReservation_r(vp);
7601 /* demote and append chain */
7602 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7616 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7620 volume_LRU.q[idx].len -= len;
7621 volume_LRU.q[idx-1].len += len;
7624 /* release exclusive access to the two chains */
7626 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7627 VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
7629 /* now go back and set the DONT_SALVAGE flags as appropriate */
7630 if (salv_flag_vec) {
7632 for (i = 0; i < salv_vec_offset; i++) {
7633 vp = salv_flag_vec[i];
7634 if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7635 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7636 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7639 V_attachFlags(vp) |= VOL_HDR_DONTSALV;
7640 V_dontSalvage(vp) = DONT_SALVAGE;
7641 VUpdateVolume_r(&ec, vp, 0);
7645 VCancelReservation_r(vp);
7647 free(salv_flag_vec);
7651 /* run a pass of the VLRU GC scanner */
7653 VLRU_Scan_r(int idx)
7655 afs_uint32 now, thresh;
7656 struct rx_queue *qp, *nqp;
7660 osi_Assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
7662 /* gain exclusive access to the idx VLRU */
7663 VLRU_Wait_r(&volume_LRU.q[idx]);
7664 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7666 if (idx != VLRU_QUEUE_CANDIDATE) {
7667 /* gain exclusive access to the candidate VLRU */
7668 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7669 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7672 now = FT_ApproxTime();
7673 thresh = now - VLRU_offline_thresh;
7675 /* perform candidate selection and soft detaching */
7676 if (idx == VLRU_QUEUE_CANDIDATE) {
7677 /* soft detach some volumes from the candidate pool */
7681 for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7682 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7683 if (i >= VLRU_offline_max) {
7686 /* check timestamp to see if it's a candidate for soft detaching */
7687 if (vp->stats.last_get <= thresh) {
7689 if (VCheckSoftDetach(vp, thresh))
7695 /* scan for volumes to become soft detach candidates */
7696 for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
7697 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7699 /* check timestamp to see if it's a candidate for soft detaching */
7700 if (vp->stats.last_get <= thresh) {
7701 VCheckSoftDetachCandidate(vp, thresh);
7704 if (!(i&0x7f)) { /* lock coarsening optimization */
7712 /* relinquish exclusive access to the VLRU chains */
7716 volume_LRU.last_scan[idx] = now;
7717 if (idx != VLRU_QUEUE_CANDIDATE) {
7718 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7720 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7723 /* check whether volume is safe to soft detach
7724 * caller MUST NOT hold a ref count on vp */
7726 VCheckSoftDetach(Volume * vp, afs_uint32 thresh)
7730 if (vp->nUsers || vp->nWaiters)
7733 if (vp->stats.last_get <= thresh) {
7734 ret = VSoftDetachVolume_r(vp, thresh);
7740 /* check whether volume should be made a
7741 * soft detach candidate */
7743 VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh)
7746 if (vp->nUsers || vp->nWaiters)
7751 osi_Assert(idx == VLRU_QUEUE_NEW);
7753 if (vp->stats.last_get <= thresh) {
7754 /* move to candidate pool */
7755 queue_Remove(&vp->vlru);
7756 volume_LRU.q[VLRU_QUEUE_NEW].len--;
7757 queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
7758 vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
7759 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
7767 /* begin exclusive access on VLRU */
7769 VLRU_BeginExclusive_r(struct VLRU_q * q)
7771 osi_Assert(q->busy == 0);
7775 /* end exclusive access on VLRU */
7777 VLRU_EndExclusive_r(struct VLRU_q * q)
7779 osi_Assert(q->busy);
7781 CV_BROADCAST(&q->cv);
7784 /* wait for another thread to end exclusive access on VLRU */
7786 VLRU_Wait_r(struct VLRU_q * q)
7789 VOL_CV_WAIT(&q->cv);
7794 * volume soft detach
7796 * caller MUST NOT hold a ref count on vp */
7798 VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh)
7803 osi_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7805 ts_save = vp->stats.last_get;
7806 if (ts_save > thresh)
7809 if (vp->nUsers || vp->nWaiters)
7812 if (VIsExclusiveState(V_attachState(vp))) {
7816 switch (V_attachState(vp)) {
7817 case VOL_STATE_UNATTACHED:
7818 case VOL_STATE_PREATTACHED:
7819 case VOL_STATE_ERROR:
7820 case VOL_STATE_GOING_OFFLINE:
7821 case VOL_STATE_SHUTTING_DOWN:
7822 case VOL_STATE_SALVAGING:
7823 case VOL_STATE_DELETED:
7824 volume_LRU.q[vp->vlru.idx].len--;
7826 /* create and cancel a reservation to
7827 * give the volume an opportunity to
7829 VCreateReservation_r(vp);
7830 queue_Remove(&vp->vlru);
7831 vp->vlru.idx = VLRU_QUEUE_INVALID;
7832 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7833 VCancelReservation_r(vp);
7839 /* hold the volume and take it offline.
7840 * no need for reservations, as VHold_r
7841 * takes care of that internally. */
7842 if (VHold_r(vp) == 0) {
7843 /* vhold drops the glock, so now we should
7844 * check to make sure we aren't racing against
7845 * other threads. if we are racing, offlining vp
7846 * would be wasteful, and block the scanner for a while
7850 (vp->shuttingDown) ||
7851 (vp->goingOffline) ||
7852 (vp->stats.last_get != ts_save)) {
7853 /* looks like we're racing someone else. bail */
7857 /* pull it off the VLRU */
7858 osi_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7859 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
7860 queue_Remove(&vp->vlru);
7861 vp->vlru.idx = VLRU_QUEUE_INVALID;
7862 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7864 /* take if offline */
7865 VOffline_r(vp, "volume has been soft detached");
7867 /* invalidate the volume header cache */
7868 FreeVolumeHeader(vp);
7871 IncUInt64(&VStats.soft_detaches);
7872 vp->stats.soft_detaches++;
7874 /* put in pre-attached state so demand
7875 * attacher can work on it */
7876 VChangeState_r(vp, VOL_STATE_PREATTACHED);
7882 #endif /* AFS_DEMAND_ATTACH_FS */
7885 /***************************************************/
7886 /* Volume Header Cache routines */
7887 /***************************************************/
7890 * volume header cache.
7892 struct volume_hdr_LRU_t volume_hdr_LRU;
7895 * initialize the volume header cache.
7897 * @param[in] howMany number of header cache entries to preallocate
7899 * @pre VOL_LOCK held. Function has never been called before.
7901 * @post howMany cache entries are allocated, initialized, and added
7902 * to the LRU list. Header cache statistics are initialized.
7904 * @note only applicable to fileServer program type. Should only be
7905 * called once during volume package initialization.
7907 * @internal volume package internal use only.
7910 VInitVolumeHeaderCache(afs_uint32 howMany)
7912 struct volHeader *hp;
7913 if (programType != fileServer)
7915 queue_Init(&volume_hdr_LRU);
7916 volume_hdr_LRU.stats.free = 0;
7917 volume_hdr_LRU.stats.used = howMany;
7918 volume_hdr_LRU.stats.attached = 0;
7919 hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
7920 osi_Assert(hp != NULL);
7923 /* We are using ReleaseVolumeHeader to initialize the values on the header list
7924 * to ensure they have the right values
7926 ReleaseVolumeHeader(hp++);
7930 * get a volume header and attach it to the volume object.
7932 * @param[in] vp pointer to volume object
7934 * @return cache entry status
7935 * @retval 0 volume header was newly attached; cache data is invalid
7936 * @retval 1 volume header was previously attached; cache data is valid
7938 * @pre VOL_LOCK held. For DAFS, lightweight ref must be held on volume object.
7940 * @post volume header attached to volume object. if necessary, header cache
7941 * entry on LRU is synchronized to disk. Header is removed from LRU list.
7943 * @note VOL_LOCK may be dropped
7945 * @warning this interface does not load header data from disk. it merely
7946 * attaches a header object to the volume object, and may sync the old
7947 * header cache data out to disk in the process.
7949 * @internal volume package internal use only.
7952 GetVolumeHeader(Volume * vp)
7955 struct volHeader *hd;
7957 static int everLogged = 0;
7959 #ifdef AFS_DEMAND_ATTACH_FS
7960 VolState vp_save = 0, back_save = 0;
7962 /* XXX debug 9/19/05 we've apparently got
7963 * a ref counting bug somewhere that's
7964 * breaking the nUsers == 0 => header on LRU
7966 if (vp->header && queue_IsNotOnQueue(vp->header)) {
7967 Log("nUsers == 0, but header not on LRU\n");
7972 old = (vp->header != NULL); /* old == volume already has a header */
7974 if (programType != fileServer) {
7975 /* for volume utilities, we allocate volHeaders as needed */
7977 hd = (struct volHeader *)calloc(1, sizeof(*vp->header));
7978 osi_Assert(hd != NULL);
7981 #ifdef AFS_DEMAND_ATTACH_FS
7982 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
7986 /* for the fileserver, we keep a volume header cache */
7988 /* the header we previously dropped in the lru is
7989 * still available. pull it off the lru and return */
7992 osi_Assert(hd->back == vp);
7993 #ifdef AFS_DEMAND_ATTACH_FS
7994 V_attachFlags(vp) &= ~(VOL_HDR_IN_LRU);
7997 /* we need to grab a new element off the LRU */
7998 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
7999 /* grab an element and pull off of LRU */
8000 hd = queue_First(&volume_hdr_LRU, volHeader);
8003 /* LRU is empty, so allocate a new volHeader
8004 * this is probably indicative of a leak, so let the user know */
8005 hd = (struct volHeader *)calloc(1, sizeof(struct volHeader));
8006 osi_Assert(hd != NULL);
8008 Log("****Allocated more volume headers, probably leak****\n");
8011 volume_hdr_LRU.stats.free++;
8014 /* this header used to belong to someone else.
8015 * we'll need to check if the header needs to
8016 * be sync'd out to disk */
8018 #ifdef AFS_DEMAND_ATTACH_FS
8019 /* if hd->back were in an exclusive state, then
8020 * its volHeader would not be on the LRU... */
8021 osi_Assert(!VIsExclusiveState(V_attachState(hd->back)));
8024 if (hd->diskstuff.inUse) {
8025 /* volume was in use, so we'll need to sync
8026 * its header to disk */
8028 #ifdef AFS_DEMAND_ATTACH_FS
8029 back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
8030 vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
8031 VCreateReservation_r(hd->back);
8035 WriteVolumeHeader_r(&error, hd->back);
8036 /* Ignore errors; catch them later */
8038 #ifdef AFS_DEMAND_ATTACH_FS
8043 hd->back->header = NULL;
8044 #ifdef AFS_DEMAND_ATTACH_FS
8045 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
8047 if (hd->diskstuff.inUse) {
8048 VChangeState_r(hd->back, back_save);
8049 VCancelReservation_r(hd->back);
8050 VChangeState_r(vp, vp_save);
8054 volume_hdr_LRU.stats.attached++;
8058 #ifdef AFS_DEMAND_ATTACH_FS
8059 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8062 volume_hdr_LRU.stats.free--;
8063 volume_hdr_LRU.stats.used++;
8065 IncUInt64(&VStats.hdr_gets);
8066 #ifdef AFS_DEMAND_ATTACH_FS
8067 IncUInt64(&vp->stats.hdr_gets);
8068 vp->stats.last_hdr_get = FT_ApproxTime();
8075 * make sure volume header is attached and contains valid cache data.
8077 * @param[out] ec outbound error code
8078 * @param[in] vp pointer to volume object
8080 * @pre VOL_LOCK held. For DAFS, lightweight ref held on vp.
8082 * @post header cache entry attached, and loaded with valid data, or
8083 * *ec is nonzero, and the header is released back into the LRU.
8085 * @internal volume package internal use only.
8088 LoadVolumeHeader(Error * ec, Volume * vp)
8090 #ifdef AFS_DEMAND_ATTACH_FS
8091 VolState state_save;
8095 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8096 IncUInt64(&VStats.hdr_loads);
8097 state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
8100 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8101 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8103 IncUInt64(&vp->stats.hdr_loads);
8104 now = FT_ApproxTime();
8108 V_attachFlags(vp) |= VOL_HDR_LOADED;
8109 vp->stats.last_hdr_load = now;
8111 VChangeState_r(vp, state_save);
8113 #else /* AFS_DEMAND_ATTACH_FS */
8115 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8116 IncUInt64(&VStats.hdr_loads);
8118 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8119 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8122 #endif /* AFS_DEMAND_ATTACH_FS */
8124 /* maintain (nUsers==0) => header in LRU invariant */
8125 FreeVolumeHeader(vp);
8130 * release a header cache entry back into the LRU list.
8132 * @param[in] hd pointer to volume header cache object
8134 * @pre VOL_LOCK held.
8136 * @post header cache object appended onto end of LRU list.
8138 * @note only applicable to fileServer program type.
8140 * @note used to place a header cache entry back into the
8141 * LRU pool without invalidating it as a cache entry.
8143 * @internal volume package internal use only.
8146 ReleaseVolumeHeader(struct volHeader *hd)
8148 if (programType != fileServer)
8150 if (!hd || queue_IsOnQueue(hd)) /* no header, or header already released */
8152 queue_Append(&volume_hdr_LRU, hd);
8153 #ifdef AFS_DEMAND_ATTACH_FS
8155 V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
8158 volume_hdr_LRU.stats.free++;
8159 volume_hdr_LRU.stats.used--;
8163 * free/invalidate a volume header cache entry.
8165 * @param[in] vp pointer to volume object
8167 * @pre VOL_LOCK is held.
8169 * @post For fileserver, header cache entry is returned to LRU, and it is
8170 * invalidated as a cache entry. For volume utilities, the header
8171 * cache entry is freed.
8173 * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
8174 * whenever it is necessary to invalidate the header cache entry.
8176 * @see ReleaseVolumeHeader
8178 * @internal volume package internal use only.
8181 FreeVolumeHeader(Volume * vp)
8183 struct volHeader *hd = vp->header;
8186 if (programType == fileServer) {
8187 ReleaseVolumeHeader(hd);
8192 #ifdef AFS_DEMAND_ATTACH_FS
8193 V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
8195 volume_hdr_LRU.stats.attached--;
8200 /***************************************************/
8201 /* Volume Hash Table routines */
8202 /***************************************************/
8205 * set size of volume object hash table.
8207 * @param[in] logsize log(2) of desired hash table size
8209 * @return operation status
8211 * @retval -1 failure
8213 * @pre MUST be called prior to VInitVolumePackage2
8215 * @post Volume Hash Table will have 2^logsize buckets
8218 VSetVolHashSize(int logsize)
8220 /* 64 to 268435456 hash buckets seems like a reasonable range */
8221 if ((logsize < 6 ) || (logsize > 28)) {
8226 VolumeHashTable.Size = 1 << logsize;
8227 VolumeHashTable.Mask = VolumeHashTable.Size - 1;
8229 /* we can't yet support runtime modification of this
8230 * parameter. we'll need a configuration rwlock to
8231 * make runtime modification feasible.... */
8238 * initialize dynamic data structures for volume hash table.
8240 * @post hash table is allocated, and fields are initialized.
8242 * @internal volume package internal use only.
8245 VInitVolumeHash(void)
8249 VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
8250 sizeof(VolumeHashChainHead));
8251 osi_Assert(VolumeHashTable.Table != NULL);
8253 for (i=0; i < VolumeHashTable.Size; i++) {
8254 queue_Init(&VolumeHashTable.Table[i]);
8255 #ifdef AFS_DEMAND_ATTACH_FS
8256 CV_INIT(&VolumeHashTable.Table[i].chain_busy_cv, "vhash busy", CV_DEFAULT, 0);
8257 #endif /* AFS_DEMAND_ATTACH_FS */
8262 * add a volume object to the hash table.
8264 * @param[in] vp pointer to volume object
8265 * @param[in] hashid hash of volume id
8267 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8270 * @post volume is added to hash chain.
8272 * @internal volume package internal use only.
8274 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8275 * asynchronous hash chain reordering to finish.
8278 AddVolumeToHashTable(Volume * vp, int hashid)
8280 VolumeHashChainHead * head;
8282 if (queue_IsOnQueue(vp))
8285 head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
8287 #ifdef AFS_DEMAND_ATTACH_FS
8288 /* wait for the hash chain to become available */
8291 V_attachFlags(vp) |= VOL_IN_HASH;
8292 vp->chainCacheCheck = ++head->cacheCheck;
8293 #endif /* AFS_DEMAND_ATTACH_FS */
8296 vp->hashid = hashid;
8297 queue_Append(head, vp);
8298 vp->vnodeHashOffset = VolumeHashOffset_r();
8302 * delete a volume object from the hash table.
8304 * @param[in] vp pointer to volume object
8306 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8309 * @post volume is removed from hash chain.
8311 * @internal volume package internal use only.
8313 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8314 * asynchronous hash chain reordering to finish.
8317 DeleteVolumeFromHashTable(Volume * vp)
8319 VolumeHashChainHead * head;
8321 if (!queue_IsOnQueue(vp))
8324 head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
8326 #ifdef AFS_DEMAND_ATTACH_FS
8327 /* wait for the hash chain to become available */
8330 V_attachFlags(vp) &= ~(VOL_IN_HASH);
8332 #endif /* AFS_DEMAND_ATTACH_FS */
8336 /* do NOT reset hashid to zero, as the online
8337 * salvager package may need to know the volume id
8338 * after the volume is removed from the hash */
8342 * lookup a volume object in the hash table given a volume id.
8344 * @param[out] ec error code return
8345 * @param[in] volumeId volume id
8346 * @param[in] hint volume object which we believe could be the correct
8349 * @return volume object pointer
8350 * @retval NULL no such volume id is registered with the hash table.
8352 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8355 * @post volume object with the given id is returned. volume object and
8356 * hash chain access statistics are updated. hash chain may have
8359 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8360 * asynchronous hash chain reordering operation to finish, or
8361 * in order for us to perform an asynchronous chain reordering.
8363 * @note Hash chain reorderings occur when the access count for the
8364 * volume object being looked up exceeds the sum of the previous
8365 * node's (the node ahead of it in the hash chain linked list)
8366 * access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
8368 * @note For DAFS, the hint parameter allows us to short-circuit if the
8369 * cacheCheck fields match between the hash chain head and the
8370 * hint volume object.
8373 VLookupVolume_r(Error * ec, VolId volumeId, Volume * hint)
8377 #ifdef AFS_DEMAND_ATTACH_FS
8380 VolumeHashChainHead * head;
8383 head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
8385 #ifdef AFS_DEMAND_ATTACH_FS
8386 /* wait for the hash chain to become available */
8389 /* check to see if we can short circuit without walking the hash chain */
8390 if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
8391 IncUInt64(&hint->stats.hash_short_circuits);
8394 #endif /* AFS_DEMAND_ATTACH_FS */
8396 /* someday we need to either do per-chain locks, RWlocks,
8397 * or both for volhash access.
8398 * (and move to a data structure with better cache locality) */
8400 /* search the chain for this volume id */
8401 for(queue_Scan(head, vp, np, Volume)) {
8403 if ((vp->hashid == volumeId)) {
8408 if (queue_IsEnd(head, vp)) {
8412 #ifdef AFS_DEMAND_ATTACH_FS
8413 /* update hash chain statistics */
8416 FillInt64(lks, 0, looks);
8417 AddUInt64(head->looks, lks, &head->looks);
8418 AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
8419 IncUInt64(&head->gets);
8424 IncUInt64(&vp->stats.hash_lookups);
8426 /* for demand attach fileserver, we permit occasional hash chain reordering
8427 * so that frequently looked up volumes move towards the head of the chain */
8428 pp = queue_Prev(vp, Volume);
8429 if (!queue_IsEnd(head, pp)) {
8430 FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
8431 AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
8432 if (GEInt64(vp->stats.hash_lookups, thresh)) {
8433 VReorderHash_r(head, pp, vp);
8437 /* update the short-circuit cache check */
8438 vp->chainCacheCheck = head->cacheCheck;
8440 #endif /* AFS_DEMAND_ATTACH_FS */
8445 #ifdef AFS_DEMAND_ATTACH_FS
8446 /* perform volume hash chain reordering.
8448 * advance a subchain beginning at vp ahead of
8449 * the adjacent subchain ending at pp */
8451 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
8453 Volume *tp, *np, *lp;
8454 afs_uint64 move_thresh;
8456 /* this should never be called if the chain is already busy, so
8457 * no need to wait for other exclusive chain ops to finish */
8459 /* this is a rather heavy set of operations,
8460 * so let's set the chain busy flag and drop
8462 VHashBeginExclusive_r(head);
8465 /* scan forward in the chain from vp looking for the last element
8466 * in the chain we want to advance */
8467 FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
8468 AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
8469 for(queue_ScanFrom(head, vp, tp, np, Volume)) {
8470 if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
8474 lp = queue_Prev(tp, Volume);
8476 /* scan backwards from pp to determine where to splice and
8477 * insert the subchain we're advancing */
8478 for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
8479 if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
8483 tp = queue_Next(tp, Volume);
8485 /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
8486 queue_MoveChainBefore(tp,vp,lp);
8489 IncUInt64(&VStats.hash_reorders);
8491 IncUInt64(&head->reorders);
8493 /* wake up any threads waiting for the hash chain */
8494 VHashEndExclusive_r(head);
8498 /* demand-attach fs volume hash
8499 * asynchronous exclusive operations */
8502 * begin an asynchronous exclusive operation on a volume hash chain.
8504 * @param[in] head pointer to volume hash chain head object
8506 * @pre VOL_LOCK held. hash chain is quiescent.
8508 * @post hash chain marked busy.
8510 * @note this interface is used in conjunction with VHashEndExclusive_r and
8511 * VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8512 * volume hash chain. Its main use case is hash chain reordering, which
8513 * has the potential to be a highly latent operation.
8515 * @see VHashEndExclusive_r
8520 * @internal volume package internal use only.
8523 VHashBeginExclusive_r(VolumeHashChainHead * head)
8525 osi_Assert(head->busy == 0);
8530 * relinquish exclusive ownership of a volume hash chain.
8532 * @param[in] head pointer to volume hash chain head object
8534 * @pre VOL_LOCK held. thread owns the hash chain exclusively.
8536 * @post hash chain is marked quiescent. threads awaiting use of
8537 * chain are awakened.
8539 * @see VHashBeginExclusive_r
8544 * @internal volume package internal use only.
8547 VHashEndExclusive_r(VolumeHashChainHead * head)
8549 osi_Assert(head->busy);
8551 CV_BROADCAST(&head->chain_busy_cv);
8555 * wait for all asynchronous operations on a hash chain to complete.
8557 * @param[in] head pointer to volume hash chain head object
8559 * @pre VOL_LOCK held.
8561 * @post hash chain object is quiescent.
8563 * @see VHashBeginExclusive_r
8564 * @see VHashEndExclusive_r
8568 * @note This interface should be called before any attempt to
8569 * traverse the hash chain. It is permissible for a thread
8570 * to gain exclusive access to the chain, and then perform
8571 * latent operations on the chain asynchronously wrt the
8574 * @warning if waiting is necessary, VOL_LOCK is dropped
8576 * @internal volume package internal use only.
8579 VHashWait_r(VolumeHashChainHead * head)
8581 while (head->busy) {
8582 VOL_CV_WAIT(&head->chain_busy_cv);
8585 #endif /* AFS_DEMAND_ATTACH_FS */
8588 /***************************************************/
8589 /* Volume by Partition List routines */
8590 /***************************************************/
8593 * demand attach fileserver adds a
8594 * linked list of volumes to each
8595 * partition object, thus allowing
8596 * for quick enumeration of all
8597 * volumes on a partition
8600 #ifdef AFS_DEMAND_ATTACH_FS
8602 * add a volume to its disk partition VByPList.
8604 * @param[in] vp pointer to volume object
8606 * @pre either the disk partition VByPList is owned exclusively
8607 * by the calling thread, or the list is quiescent and
8610 * @post volume is added to disk partition VByPList
8614 * @warning it is the caller's responsibility to ensure list
8617 * @see VVByPListWait_r
8618 * @see VVByPListBeginExclusive_r
8619 * @see VVByPListEndExclusive_r
8621 * @internal volume package internal use only.
8624 AddVolumeToVByPList_r(Volume * vp)
8626 if (queue_IsNotOnQueue(&vp->vol_list)) {
8627 queue_Append(&vp->partition->vol_list, &vp->vol_list);
8628 V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
8629 vp->partition->vol_list.len++;
8634 * delete a volume from its disk partition VByPList.
8636 * @param[in] vp pointer to volume object
8638 * @pre either the disk partition VByPList is owned exclusively
8639 * by the calling thread, or the list is quiescent and
8642 * @post volume is removed from the disk partition VByPList
8646 * @warning it is the caller's responsibility to ensure list
8649 * @see VVByPListWait_r
8650 * @see VVByPListBeginExclusive_r
8651 * @see VVByPListEndExclusive_r
8653 * @internal volume package internal use only.
8656 DeleteVolumeFromVByPList_r(Volume * vp)
8658 if (queue_IsOnQueue(&vp->vol_list)) {
8659 queue_Remove(&vp->vol_list);
8660 V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
8661 vp->partition->vol_list.len--;
8666 * begin an asynchronous exclusive operation on a VByPList.
8668 * @param[in] dp pointer to disk partition object
8670 * @pre VOL_LOCK held. VByPList is quiescent.
8672 * @post VByPList marked busy.
8674 * @note this interface is used in conjunction with VVByPListEndExclusive_r and
8675 * VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8678 * @see VVByPListEndExclusive_r
8679 * @see VVByPListWait_r
8683 * @internal volume package internal use only.
8685 /* take exclusive control over the list */
8687 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
8689 osi_Assert(dp->vol_list.busy == 0);
8690 dp->vol_list.busy = 1;
8694 * relinquish exclusive ownership of a VByPList.
8696 * @param[in] dp pointer to disk partition object
8698 * @pre VOL_LOCK held. thread owns the VByPList exclusively.
8700 * @post VByPList is marked quiescent. threads awaiting use of
8701 * the list are awakened.
8703 * @see VVByPListBeginExclusive_r
8704 * @see VVByPListWait_r
8708 * @internal volume package internal use only.
8711 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
8713 osi_Assert(dp->vol_list.busy);
8714 dp->vol_list.busy = 0;
8715 CV_BROADCAST(&dp->vol_list.cv);
8719 * wait for all asynchronous operations on a VByPList to complete.
8721 * @param[in] dp pointer to disk partition object
8723 * @pre VOL_LOCK is held.
8725 * @post disk partition's VByP list is quiescent
8729 * @note This interface should be called before any attempt to
8730 * traverse the VByPList. It is permissible for a thread
8731 * to gain exclusive access to the list, and then perform
8732 * latent operations on the list asynchronously wrt the
8735 * @warning if waiting is necessary, VOL_LOCK is dropped
8737 * @see VVByPListEndExclusive_r
8738 * @see VVByPListBeginExclusive_r
8740 * @internal volume package internal use only.
8743 VVByPListWait_r(struct DiskPartition64 * dp)
8745 while (dp->vol_list.busy) {
8746 VOL_CV_WAIT(&dp->vol_list.cv);
8749 #endif /* AFS_DEMAND_ATTACH_FS */
8751 /***************************************************/
8752 /* Volume Cache Statistics routines */
8753 /***************************************************/
8756 VPrintCacheStats_r(void)
8758 afs_uint32 get_hi, get_lo, load_hi, load_lo;
8759 struct VnodeClassInfo *vcp;
8760 vcp = &VnodeClassInfo[vLarge];
8761 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);
8762 vcp = &VnodeClassInfo[vSmall];
8763 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);
8764 SplitInt64(VStats.hdr_gets, get_hi, get_lo);
8765 SplitInt64(VStats.hdr_loads, load_hi, load_lo);
8766 Log("Volume header cache, %d entries, %d gets, %d replacements\n",
8767 VStats.hdr_cache_size, get_lo, load_lo);
8771 VPrintCacheStats(void)
8774 VPrintCacheStats_r();
8778 #ifdef AFS_DEMAND_ATTACH_FS
8780 UInt64ToDouble(afs_uint64 * x)
8782 static double c32 = 4.0 * 1.073741824 * 1000000000.0;
8784 SplitInt64(*x, h, l);
8785 return (((double)h) * c32) + ((double) l);
8789 DoubleToPrintable(double x, char * buf, int len)
8791 static double billion = 1000000000.0;
8794 y[0] = (afs_uint32) (x / (billion * billion));
8795 y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
8796 y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
8799 snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
8801 snprintf(buf, len, "%d%09d", y[1], y[2]);
8803 snprintf(buf, len, "%d", y[2]);
8809 struct VLRUExtStatsEntry {
8813 struct VLRUExtStats {
8819 } queue_info[VLRU_QUEUE_INVALID];
8820 struct VLRUExtStatsEntry * vec;
8824 * add a 256-entry fudge factor onto the vector in case state changes
8825 * out from under us.
8827 #define VLRU_EXT_STATS_VEC_LEN_FUDGE 256
8830 * collect extended statistics for the VLRU subsystem.
8832 * @param[out] stats pointer to stats structure to be populated
8833 * @param[in] nvols number of volumes currently known to exist
8835 * @pre VOL_LOCK held
8837 * @post stats->vec allocated and populated
8839 * @return operation status
8844 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
8846 afs_uint32 cur, idx, len;
8847 struct rx_queue * qp, * nqp;
8849 struct VLRUExtStatsEntry * vec;
8851 len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
8852 vec = stats->vec = calloc(len,
8853 sizeof(struct VLRUExtStatsEntry));
8859 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
8860 VLRU_Wait_r(&volume_LRU.q[idx]);
8861 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
8864 stats->queue_info[idx].start = cur;
8866 for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
8868 /* out of space in vec */
8871 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
8872 vec[cur].volid = vp->hashid;
8876 stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
8879 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
8887 #define ENUMTOSTRING(en) #en
8888 #define ENUMCASE(en) \
8890 return ENUMTOSTRING(en); \
8894 vlru_idx_to_string(int idx)
8897 ENUMCASE(VLRU_QUEUE_NEW);
8898 ENUMCASE(VLRU_QUEUE_MID);
8899 ENUMCASE(VLRU_QUEUE_OLD);
8900 ENUMCASE(VLRU_QUEUE_CANDIDATE);
8901 ENUMCASE(VLRU_QUEUE_HELD);
8902 ENUMCASE(VLRU_QUEUE_INVALID);
8904 return "**UNKNOWN**";
8909 VPrintExtendedCacheStats_r(int flags)
8912 afs_uint32 vol_sum = 0;
8919 struct stats looks, gets, reorders, len;
8920 struct stats ch_looks, ch_gets, ch_reorders;
8922 VolumeHashChainHead *head;
8924 struct VLRUExtStats vlru_stats;
8926 /* zero out stats */
8927 memset(&looks, 0, sizeof(struct stats));
8928 memset(&gets, 0, sizeof(struct stats));
8929 memset(&reorders, 0, sizeof(struct stats));
8930 memset(&len, 0, sizeof(struct stats));
8931 memset(&ch_looks, 0, sizeof(struct stats));
8932 memset(&ch_gets, 0, sizeof(struct stats));
8933 memset(&ch_reorders, 0, sizeof(struct stats));
8935 for (i = 0; i < VolumeHashTable.Size; i++) {
8936 head = &VolumeHashTable.Table[i];
8939 VHashBeginExclusive_r(head);
8942 ch_looks.sum = UInt64ToDouble(&head->looks);
8943 ch_gets.sum = UInt64ToDouble(&head->gets);
8944 ch_reorders.sum = UInt64ToDouble(&head->reorders);
8946 /* update global statistics */
8948 looks.sum += ch_looks.sum;
8949 gets.sum += ch_gets.sum;
8950 reorders.sum += ch_reorders.sum;
8951 len.sum += (double)head->len;
8952 vol_sum += head->len;
8955 len.min = (double) head->len;
8956 len.max = (double) head->len;
8957 looks.min = ch_looks.sum;
8958 looks.max = ch_looks.sum;
8959 gets.min = ch_gets.sum;
8960 gets.max = ch_gets.sum;
8961 reorders.min = ch_reorders.sum;
8962 reorders.max = ch_reorders.sum;
8964 if (((double)head->len) < len.min)
8965 len.min = (double) head->len;
8966 if (((double)head->len) > len.max)
8967 len.max = (double) head->len;
8968 if (ch_looks.sum < looks.min)
8969 looks.min = ch_looks.sum;
8970 else if (ch_looks.sum > looks.max)
8971 looks.max = ch_looks.sum;
8972 if (ch_gets.sum < gets.min)
8973 gets.min = ch_gets.sum;
8974 else if (ch_gets.sum > gets.max)
8975 gets.max = ch_gets.sum;
8976 if (ch_reorders.sum < reorders.min)
8977 reorders.min = ch_reorders.sum;
8978 else if (ch_reorders.sum > reorders.max)
8979 reorders.max = ch_reorders.sum;
8983 if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
8984 /* compute detailed per-chain stats */
8985 struct stats hdr_loads, hdr_gets;
8986 double v_looks, v_loads, v_gets;
8988 /* initialize stats with data from first element in chain */
8989 vp = queue_First(head, Volume);
8990 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
8991 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
8992 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
8993 ch_gets.min = ch_gets.max = v_looks;
8994 hdr_loads.min = hdr_loads.max = v_loads;
8995 hdr_gets.min = hdr_gets.max = v_gets;
8996 hdr_loads.sum = hdr_gets.sum = 0;
8998 vp = queue_Next(vp, Volume);
9000 /* pull in stats from remaining elements in chain */
9001 for (queue_ScanFrom(head, vp, vp, np, Volume)) {
9002 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
9003 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
9004 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
9006 hdr_loads.sum += v_loads;
9007 hdr_gets.sum += v_gets;
9009 if (v_looks < ch_gets.min)
9010 ch_gets.min = v_looks;
9011 else if (v_looks > ch_gets.max)
9012 ch_gets.max = v_looks;
9014 if (v_loads < hdr_loads.min)
9015 hdr_loads.min = v_loads;
9016 else if (v_loads > hdr_loads.max)
9017 hdr_loads.max = v_loads;
9019 if (v_gets < hdr_gets.min)
9020 hdr_gets.min = v_gets;
9021 else if (v_gets > hdr_gets.max)
9022 hdr_gets.max = v_gets;
9025 /* compute per-chain averages */
9026 ch_gets.avg = ch_gets.sum / ((double)head->len);
9027 hdr_loads.avg = hdr_loads.sum / ((double)head->len);
9028 hdr_gets.avg = hdr_gets.sum / ((double)head->len);
9030 /* dump per-chain stats */
9031 Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
9033 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9034 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
9035 Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
9036 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9037 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9038 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9039 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9040 Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
9041 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9042 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9043 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9044 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9045 Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
9046 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
9047 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
9048 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
9049 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
9050 } else if (flags & VOL_STATS_PER_CHAIN) {
9051 /* dump simple per-chain stats */
9052 Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
9054 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9055 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
9056 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
9060 VHashEndExclusive_r(head);
9065 /* compute global averages */
9066 len.avg = len.sum / ((double)VolumeHashTable.Size);
9067 looks.avg = looks.sum / ((double)VolumeHashTable.Size);
9068 gets.avg = gets.sum / ((double)VolumeHashTable.Size);
9069 reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
9071 /* dump global stats */
9072 Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
9073 Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
9074 DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
9075 DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
9076 DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
9077 DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
9078 Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
9079 DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
9080 DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
9081 DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
9082 DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
9083 Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
9084 DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
9085 DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
9086 DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9087 DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9088 Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
9089 DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
9090 DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
9091 DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
9092 DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
9094 /* print extended disk related statistics */
9096 struct DiskPartition64 * diskP;
9097 afs_uint32 vol_count[VOLMAXPARTS+1];
9098 byte part_exists[VOLMAXPARTS+1];
9102 memset(vol_count, 0, sizeof(vol_count));
9103 memset(part_exists, 0, sizeof(part_exists));
9107 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
9109 vol_count[id] = diskP->vol_list.len;
9110 part_exists[id] = 1;
9114 for (i = 0; i <= VOLMAXPARTS; i++) {
9115 if (part_exists[i]) {
9116 /* XXX while this is currently safe, it is a violation
9117 * of the VGetPartitionById_r interface contract. */
9118 diskP = VGetPartitionById_r(i, 0);
9120 Log("Partition %s has %d online volumes\n",
9121 VPartitionPath(diskP), diskP->vol_list.len);
9128 /* print extended VLRU statistics */
9129 if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
9130 afs_uint32 idx, cur, lpos;
9135 Log("VLRU State Dump:\n\n");
9137 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
9138 Log("\t%s:\n", vlru_idx_to_string(idx));
9141 for (cur = vlru_stats.queue_info[idx].start;
9142 cur < vlru_stats.queue_info[idx].len;
9144 line[lpos++] = vlru_stats.vec[cur].volid;
9146 Log("\t\t%u, %u, %u, %u, %u,\n",
9147 line[0], line[1], line[2], line[3], line[4]);
9156 Log("\t\t%u, %u, %u, %u, %u\n",
9157 line[0], line[1], line[2], line[3], line[4]);
9162 free(vlru_stats.vec);
9169 VPrintExtendedCacheStats(int flags)
9172 VPrintExtendedCacheStats_r(flags);
9175 #endif /* AFS_DEMAND_ATTACH_FS */
9178 VCanScheduleSalvage(void)
9180 return vol_opts.canScheduleSalvage;
9186 return vol_opts.canUseFSSYNC;
9190 VCanUseSALVSYNC(void)
9192 return vol_opts.canUseSALVSYNC;
9196 VCanUnsafeAttach(void)
9198 return vol_opts.unsafe_attach;