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"
126 #ifdef AFS_PTHREAD_ENV
128 #else /* AFS_PTHREAD_ENV */
129 #include "afs/assert.h"
130 #endif /* AFS_PTHREAD_ENV */
137 #if !defined(offsetof)
142 #define afs_stat stat64
143 #define afs_fstat fstat64
144 #define afs_open open64
145 #else /* !O_LARGEFILE */
146 #define afs_stat stat
147 #define afs_fstat fstat
148 #define afs_open open
149 #endif /* !O_LARGEFILE */
151 #ifdef AFS_PTHREAD_ENV
152 pthread_mutex_t vol_glock_mutex;
153 pthread_mutex_t vol_trans_mutex;
154 pthread_cond_t vol_put_volume_cond;
155 pthread_cond_t vol_sleep_cond;
156 pthread_cond_t vol_init_attach_cond;
157 int vol_attach_threads = 1;
158 #endif /* AFS_PTHREAD_ENV */
160 /* start-time configurable I/O parameters */
161 ih_init_params vol_io_params;
163 #ifdef AFS_DEMAND_ATTACH_FS
164 pthread_mutex_t vol_salvsync_mutex;
167 * Set this to 1 to disallow SALVSYNC communication in all threads; used
168 * during shutdown, since the salvageserver may have gone away.
170 static volatile sig_atomic_t vol_disallow_salvsync = 0;
171 #endif /* AFS_DEMAND_ATTACH_FS */
174 extern void *calloc(), *realloc();
177 /*@printflike@*/ extern void Log(const char *format, ...);
179 /* Forward declarations */
180 static Volume *attach2(Error * ec, VolId volumeId, char *path,
181 struct DiskPartition64 *partp, Volume * vp,
182 int isbusy, int mode);
183 static void ReallyFreeVolume(Volume * vp);
184 #ifdef AFS_DEMAND_ATTACH_FS
185 static void FreeVolume(Volume * vp);
186 #else /* !AFS_DEMAND_ATTACH_FS */
187 #define FreeVolume(vp) ReallyFreeVolume(vp)
188 static void VScanUpdateList(void);
189 #endif /* !AFS_DEMAND_ATTACH_FS */
190 static void VInitVolumeHeaderCache(afs_uint32 howMany);
191 static int GetVolumeHeader(register Volume * vp);
192 static void ReleaseVolumeHeader(register struct volHeader *hd);
193 static void FreeVolumeHeader(register Volume * vp);
194 static void AddVolumeToHashTable(register Volume * vp, int hashid);
195 static void DeleteVolumeFromHashTable(register Volume * vp);
197 static int VHold(Volume * vp);
199 static int VHold_r(Volume * vp);
200 static void VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class);
201 static void VReleaseVolumeHandles_r(Volume * vp);
202 static void VCloseVolumeHandles_r(Volume * vp);
203 static void LoadVolumeHeader(Error * ec, Volume * vp);
204 static int VCheckOffline(register Volume * vp);
205 static int VCheckDetach(register Volume * vp);
206 static Volume * GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint, int flags);
208 int LogLevel; /* Vice loglevel--not defined as extern so that it will be
209 * defined when not linked with vice, XXXX */
210 ProgramType programType; /* The type of program using the package */
211 static VolumePackageOptions vol_opts;
213 /* extended volume package statistics */
216 #ifdef VOL_LOCK_DEBUG
217 pthread_t vol_glock_holder = 0;
221 #define VOLUME_BITMAP_GROWSIZE 16 /* bytes, => 128vnodes */
222 /* Must be a multiple of 4 (1 word) !! */
224 /* this parameter needs to be tunable at runtime.
225 * 128 was really inadequate for largish servers -- at 16384 volumes this
226 * puts average chain length at 128, thus an average 65 deref's to find a volptr.
227 * talk about bad spatial locality...
229 * an AVL or splay tree might work a lot better, but we'll just increase
230 * the default hash table size for now
232 #define DEFAULT_VOLUME_HASH_SIZE 256 /* Must be a power of 2!! */
233 #define DEFAULT_VOLUME_HASH_MASK (DEFAULT_VOLUME_HASH_SIZE-1)
234 #define VOLUME_HASH(volumeId) (volumeId&(VolumeHashTable.Mask))
237 * turn volume hash chains into partially ordered lists.
238 * when the threshold is exceeded between two adjacent elements,
239 * perform a chain rebalancing operation.
241 * keep the threshold high in order to keep cache line invalidates
242 * low "enough" on SMPs
244 #define VOLUME_HASH_REORDER_THRESHOLD 200
247 * when possible, don't just reorder single elements, but reorder
248 * entire chains of elements at once. a chain of elements that
249 * exceed the element previous to the pivot by at least CHAIN_THRESH
250 * accesses are moved in front of the chain whose elements have at
251 * least CHAIN_THRESH less accesses than the pivot element
253 #define VOLUME_HASH_REORDER_CHAIN_THRESH (VOLUME_HASH_REORDER_THRESHOLD / 2)
255 #include "rx/rx_queue.h"
258 VolumeHashTable_t VolumeHashTable = {
259 DEFAULT_VOLUME_HASH_SIZE,
260 DEFAULT_VOLUME_HASH_MASK,
265 static void VInitVolumeHash(void);
269 /* This macro is used where an ffs() call does not exist. Was in util/ffs.c */
273 afs_int32 ffs_tmp = x;
277 for (ffs_i = 1;; ffs_i++) {
284 #endif /* !AFS_HAVE_FFS */
286 #ifdef AFS_PTHREAD_ENV
288 * disk partition queue element
290 typedef struct diskpartition_queue_t {
291 struct rx_queue queue; /**< queue header */
292 struct DiskPartition64 *diskP; /**< disk partition table entry */
293 } diskpartition_queue_t;
295 #ifndef AFS_DEMAND_ATTACH_FS
297 typedef struct vinitvolumepackage_thread_t {
298 struct rx_queue queue;
299 pthread_cond_t thread_done_cv;
300 int n_threads_complete;
301 } vinitvolumepackage_thread_t;
302 static void * VInitVolumePackageThread(void * args);
304 #else /* !AFS_DEMAND_ATTTACH_FS */
305 #define VINIT_BATCH_MAX_SIZE 512
308 * disk partition work queue
310 struct partition_queue {
311 struct rx_queue head; /**< diskpartition_queue_t queue */
312 pthread_mutex_t mutex;
317 * volumes parameters for preattach
319 struct volume_init_batch {
320 struct rx_queue queue; /**< queue header */
321 int thread; /**< posting worker thread */
322 int last; /**< indicates thread is done */
323 int size; /**< number of volume ids in batch */
324 Volume *batch[VINIT_BATCH_MAX_SIZE]; /**< volumes ids to preattach */
328 * volume parameters work queue
330 struct volume_init_queue {
331 struct rx_queue head; /**< volume_init_batch queue */
332 pthread_mutex_t mutex;
337 * volume init worker thread parameters
339 struct vinitvolumepackage_thread_param {
340 int nthreads; /**< total number of worker threads */
341 int thread; /**< thread number for this worker thread */
342 struct partition_queue *pq; /**< queue partitions to scan */
343 struct volume_init_queue *vq; /**< queue of volume to preattach */
346 static void *VInitVolumePackageThread(void *args);
347 static struct DiskPartition64 *VInitNextPartition(struct partition_queue *pq);
348 static VolId VInitNextVolumeId(DIR *dirp);
349 static int VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq);
351 #endif /* !AFS_DEMAND_ATTACH_FS */
352 #endif /* AFS_PTHREAD_ENV */
354 #ifndef AFS_DEMAND_ATTACH_FS
355 static int VAttachVolumesByPartition(struct DiskPartition64 *diskP,
356 int * nAttached, int * nUnattached);
357 #endif /* AFS_DEMAND_ATTACH_FS */
360 #ifdef AFS_DEMAND_ATTACH_FS
361 /* demand attach fileserver extensions */
364 * in the future we will support serialization of VLRU state into the fs_state
367 * these structures are the beginning of that effort
369 struct VLRU_DiskHeader {
370 struct versionStamp stamp; /* magic and structure version number */
371 afs_uint32 mtime; /* time of dump to disk */
372 afs_uint32 num_records; /* number of VLRU_DiskEntry records */
375 struct VLRU_DiskEntry {
376 afs_uint32 vid; /* volume ID */
377 afs_uint32 idx; /* generation */
378 afs_uint32 last_get; /* timestamp of last get */
381 struct VLRU_StartupQueue {
382 struct VLRU_DiskEntry * entry;
387 typedef struct vshutdown_thread_t {
389 pthread_mutex_t lock;
391 pthread_cond_t master_cv;
393 int n_threads_complete;
395 int schedule_version;
398 byte n_parts_done_pass;
399 byte part_thread_target[VOLMAXPARTS+1];
400 byte part_done_pass[VOLMAXPARTS+1];
401 struct rx_queue * part_pass_head[VOLMAXPARTS+1];
402 int stats[4][VOLMAXPARTS+1];
403 } vshutdown_thread_t;
404 static void * VShutdownThread(void * args);
407 static Volume * VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode);
408 static int VCheckFree(Volume * vp);
411 static void AddVolumeToVByPList_r(Volume * vp);
412 static void DeleteVolumeFromVByPList_r(Volume * vp);
413 static void VVByPListBeginExclusive_r(struct DiskPartition64 * dp);
414 static void VVByPListEndExclusive_r(struct DiskPartition64 * dp);
415 static void VVByPListWait_r(struct DiskPartition64 * dp);
417 /* online salvager */
418 static int VCheckSalvage(register Volume * vp);
419 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
420 static int VScheduleSalvage_r(Volume * vp);
423 /* Volume hash table */
424 static void VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp);
425 static void VHashBeginExclusive_r(VolumeHashChainHead * head);
426 static void VHashEndExclusive_r(VolumeHashChainHead * head);
427 static void VHashWait_r(VolumeHashChainHead * head);
430 static int ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass);
431 static int ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
432 struct rx_queue ** idx);
433 static void ShutdownController(vshutdown_thread_t * params);
434 static void ShutdownCreateSchedule(vshutdown_thread_t * params);
437 static void VLRU_ComputeConstants(void);
438 static void VInitVLRU(void);
439 static void VLRU_Init_Node_r(Volume * vp);
440 static void VLRU_Add_r(Volume * vp);
441 static void VLRU_Delete_r(Volume * vp);
442 static void VLRU_UpdateAccess_r(Volume * vp);
443 static void * VLRU_ScannerThread(void * args);
444 static void VLRU_Scan_r(int idx);
445 static void VLRU_Promote_r(int idx);
446 static void VLRU_Demote_r(int idx);
447 static void VLRU_SwitchQueues(Volume * vp, int new_idx, int append);
450 static int VCheckSoftDetach(Volume * vp, afs_uint32 thresh);
451 static int VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh);
452 static int VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh);
455 pthread_key_t VThread_key;
456 VThreadOptions_t VThread_defaults = {
457 0 /**< allow salvsync */
459 #endif /* AFS_DEMAND_ATTACH_FS */
462 struct Lock vol_listLock; /* Lock obtained when listing volumes:
463 * prevents a volume from being missed
464 * if the volume is attached during a
468 /* Common message used when the volume goes off line */
469 char *VSalvageMessage =
470 "Files in this volume are currently unavailable; call operations";
472 int VInit; /* 0 - uninitialized,
473 * 1 - initialized but not all volumes have been attached,
474 * 2 - initialized and all volumes have been attached,
475 * 3 - initialized, all volumes have been attached, and
476 * VConnectFS() has completed. */
478 static int vinit_attach_abort = 0;
480 bit32 VolumeCacheCheck; /* Incremented everytime a volume goes on line--
481 * used to stamp volume headers and in-core
482 * vnodes. When the volume goes on-line the
483 * vnode will be invalidated
484 * access only with VOL_LOCK held */
489 /***************************************************/
490 /* Startup routines */
491 /***************************************************/
493 * assign default values to a VolumePackageOptions struct.
495 * Always call this on a VolumePackageOptions struct first, then set any
496 * specific options you want, then call VInitVolumePackage2.
498 * @param[in] pt caller's program type
499 * @param[out] opts volume package options
502 VOptDefaults(ProgramType pt, VolumePackageOptions *opts)
504 opts->nLargeVnodes = opts->nSmallVnodes = 5;
507 opts->canScheduleSalvage = 0;
508 opts->canUseFSSYNC = 0;
509 opts->canUseSALVSYNC = 0;
513 opts->canScheduleSalvage = 1;
514 opts->canUseSALVSYNC = 1;
518 opts->canUseFSSYNC = 1;
522 opts->nLargeVnodes = 0;
523 opts->nSmallVnodes = 0;
525 opts->canScheduleSalvage = 1;
526 opts->canUseFSSYNC = 1;
536 VInitVolumePackage2(ProgramType pt, VolumePackageOptions * opts)
538 int errors = 0; /* Number of errors while finding vice partitions. */
543 memset(&VStats, 0, sizeof(VStats));
544 VStats.hdr_cache_size = 200;
546 VInitPartitionPackage();
548 #ifdef AFS_DEMAND_ATTACH_FS
549 if (programType == fileServer) {
552 VLRU_SetOptions(VLRU_SET_ENABLED, 0);
554 assert(pthread_key_create(&VThread_key, NULL) == 0);
557 #ifdef AFS_PTHREAD_ENV
558 assert(pthread_mutex_init(&vol_glock_mutex, NULL) == 0);
559 assert(pthread_mutex_init(&vol_trans_mutex, NULL) == 0);
560 assert(pthread_cond_init(&vol_put_volume_cond, NULL) == 0);
561 assert(pthread_cond_init(&vol_sleep_cond, NULL) == 0);
562 assert(pthread_cond_init(&vol_init_attach_cond, NULL) == 0);
563 #else /* AFS_PTHREAD_ENV */
565 #endif /* AFS_PTHREAD_ENV */
566 Lock_Init(&vol_listLock);
568 srandom(time(0)); /* For VGetVolumeInfo */
570 #ifdef AFS_DEMAND_ATTACH_FS
571 assert(pthread_mutex_init(&vol_salvsync_mutex, NULL) == 0);
572 #endif /* AFS_DEMAND_ATTACH_FS */
574 /* Ok, we have done enough initialization that fileserver can
575 * start accepting calls, even though the volumes may not be
576 * available just yet.
580 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_SERVER)
581 if (programType == salvageServer) {
584 #endif /* AFS_DEMAND_ATTACH_FS */
585 #ifdef FSSYNC_BUILD_SERVER
586 if (programType == fileServer) {
590 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_CLIENT)
591 if (VCanUseSALVSYNC()) {
592 /* establish a connection to the salvager at this point */
593 assert(VConnectSALV() != 0);
595 #endif /* AFS_DEMAND_ATTACH_FS */
597 if (opts->volcache > VStats.hdr_cache_size)
598 VStats.hdr_cache_size = opts->volcache;
599 VInitVolumeHeaderCache(VStats.hdr_cache_size);
601 VInitVnodes(vLarge, opts->nLargeVnodes);
602 VInitVnodes(vSmall, opts->nSmallVnodes);
605 errors = VAttachPartitions();
609 if (programType != fileServer) {
610 errors = VInitAttachVolumes(programType);
616 #ifdef FSSYNC_BUILD_CLIENT
617 if (VCanUseFSSYNC()) {
619 #ifdef AFS_DEMAND_ATTACH_FS
620 if (programType == salvageServer) {
621 Log("Unable to connect to file server; aborted\n");
624 #endif /* AFS_DEMAND_ATTACH_FS */
625 Log("Unable to connect to file server; will retry at need\n");
628 #endif /* FSSYNC_BUILD_CLIENT */
633 #if !defined(AFS_PTHREAD_ENV)
635 * Attach volumes in vice partitions
637 * @param[in] pt calling program type
640 * @note This is the original, non-threaded version of attach parititions.
642 * @post VInit state is 2
645 VInitAttachVolumes(ProgramType pt)
648 if (pt == fileServer) {
649 struct DiskPartition64 *diskP;
650 /* Attach all the volumes in this partition */
651 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
652 int nAttached = 0, nUnattached = 0;
653 assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
657 VInit = 2; /* Initialized, and all volumes have been attached */
658 LWP_NoYieldSignal(VInitAttachVolumes);
662 #endif /* !AFS_PTHREAD_ENV */
664 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_DEMAND_ATTACH_FS)
666 * Attach volumes in vice partitions
668 * @param[in] pt calling program type
671 * @note Threaded version of attach parititions.
673 * @post VInit state is 2
676 VInitAttachVolumes(ProgramType pt)
679 if (pt == fileServer) {
680 struct DiskPartition64 *diskP;
681 struct vinitvolumepackage_thread_t params;
682 struct diskpartition_queue_t * dpq;
683 int i, threads, parts;
685 pthread_attr_t attrs;
687 assert(pthread_cond_init(¶ms.thread_done_cv,NULL) == 0);
689 params.n_threads_complete = 0;
691 /* create partition work queue */
692 for (parts=0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
693 dpq = (diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
696 queue_Append(¶ms,dpq);
699 threads = MIN(parts, vol_attach_threads);
702 /* spawn off a bunch of initialization threads */
703 assert(pthread_attr_init(&attrs) == 0);
704 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
706 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
707 Log("VInitVolumePackage: using %d threads to attach volumes on %d partitions\n",
711 for (i=0; i < threads; i++) {
714 assert(pthread_create
715 (&tid, &attrs, &VInitVolumePackageThread,
717 AFS_SIGSET_RESTORE();
720 while(params.n_threads_complete < threads) {
721 VOL_CV_WAIT(¶ms.thread_done_cv);
725 assert(pthread_attr_destroy(&attrs) == 0);
727 /* if we're only going to run one init thread, don't bother creating
729 Log("VInitVolumePackage: beginning single-threaded fileserver startup\n");
730 Log("VInitVolumePackage: using 1 thread to attach volumes on %d partition(s)\n",
733 VInitVolumePackageThread(¶ms);
736 assert(pthread_cond_destroy(¶ms.thread_done_cv) == 0);
739 VInit = 2; /* Initialized, and all volumes have been attached */
740 assert(pthread_cond_broadcast(&vol_init_attach_cond) == 0);
746 VInitVolumePackageThread(void * args) {
748 struct DiskPartition64 *diskP;
749 struct vinitvolumepackage_thread_t * params;
750 struct diskpartition_queue_t * dpq;
752 params = (vinitvolumepackage_thread_t *) args;
756 /* Attach all the volumes in this partition */
757 while (queue_IsNotEmpty(params)) {
758 int nAttached = 0, nUnattached = 0;
760 if (vinit_attach_abort) {
761 Log("Aborting initialization\n");
765 dpq = queue_First(params,diskpartition_queue_t);
771 assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
777 params->n_threads_complete++;
778 pthread_cond_signal(¶ms->thread_done_cv);
782 #endif /* AFS_PTHREAD_ENV && !AFS_DEMAND_ATTACH_FS */
784 #if defined(AFS_DEMAND_ATTACH_FS)
786 * Attach volumes in vice partitions
788 * @param[in] pt calling program type
791 * @note Threaded version of attach partitions.
793 * @post VInit state is 2
796 VInitAttachVolumes(ProgramType pt)
799 if (pt == fileServer) {
801 struct DiskPartition64 *diskP;
802 struct partition_queue pq;
803 struct volume_init_queue vq;
805 int i, threads, parts;
807 pthread_attr_t attrs;
809 /* create partition work queue */
811 assert(pthread_cond_init(&(pq.cv), NULL) == 0);
812 assert(pthread_mutex_init(&(pq.mutex), NULL) == 0);
813 for (parts = 0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
814 struct diskpartition_queue_t *dp;
815 dp = (struct diskpartition_queue_t*)malloc(sizeof(struct diskpartition_queue_t));
818 queue_Append(&pq, dp);
821 /* number of worker threads; at least one, not to exceed the number of partitions */
822 threads = MIN(parts, vol_attach_threads);
824 /* create volume work queue */
826 assert(pthread_cond_init(&(vq.cv), NULL) == 0);
827 assert(pthread_mutex_init(&(vq.mutex), NULL) == 0);
829 assert(pthread_attr_init(&attrs) == 0);
830 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
832 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
833 Log("VInitVolumePackage: using %d threads to pre-attach volumes on %d partitions\n",
836 /* create threads to scan disk partitions. */
837 for (i=0; i < threads; i++) {
838 struct vinitvolumepackage_thread_param *params;
839 params = (struct vinitvolumepackage_thread_param *)malloc(sizeof(struct vinitvolumepackage_thread_param));
843 params->nthreads = threads;
844 params->thread = i+1;
848 assert(pthread_create (&tid, &attrs, &VInitVolumePackageThread, (void*)params) == 0);
849 AFS_SIGSET_RESTORE();
852 VInitPreAttachVolumes(threads, &vq);
854 assert(pthread_attr_destroy(&attrs) == 0);
855 assert(pthread_cond_destroy(&pq.cv) == 0);
856 assert(pthread_mutex_destroy(&pq.mutex) == 0);
857 assert(pthread_cond_destroy(&vq.cv) == 0);
858 assert(pthread_mutex_destroy(&vq.mutex) == 0);
862 VInit = 2; /* Initialized, and all volumes have been attached */
863 assert(pthread_cond_broadcast(&vol_init_attach_cond) == 0);
870 * Volume package initialization worker thread. Scan partitions for volume
871 * header files. Gather batches of volume ids and dispatch them to
872 * the main thread to be preattached. The volume preattachement is done
873 * in the main thread to avoid global volume lock contention.
876 VInitVolumePackageThread(void *args)
878 struct vinitvolumepackage_thread_param *params;
879 struct DiskPartition64 *partition;
880 struct partition_queue *pq;
881 struct volume_init_queue *vq;
882 struct volume_init_batch *vb;
885 params = (struct vinitvolumepackage_thread_param *)args;
891 vb = (struct volume_init_batch*)malloc(sizeof(struct volume_init_batch));
893 vb->thread = params->thread;
897 Log("Scanning partitions on thread %d of %d\n", params->thread, params->nthreads);
898 while((partition = VInitNextPartition(pq))) {
902 Log("Partition %s: pre-attaching volumes\n", partition->name);
903 dirp = opendir(VPartitionPath(partition));
905 Log("opendir on Partition %s failed, errno=%d!\n", partition->name, errno);
908 while ((vid = VInitNextVolumeId(dirp))) {
909 Volume *vp = (Volume*)malloc(sizeof(Volume));
911 memset(vp, 0, sizeof(Volume));
912 vp->device = partition->device;
913 vp->partition = partition;
915 queue_Init(&vp->vnode_list);
916 assert(pthread_cond_init(&V_attachCV(vp), NULL) == 0);
918 vb->batch[vb->size++] = vp;
919 if (vb->size == VINIT_BATCH_MAX_SIZE) {
920 assert(pthread_mutex_lock(&vq->mutex) == 0);
921 queue_Append(vq, vb);
922 assert(pthread_cond_broadcast(&vq->cv) == 0);
923 assert(pthread_mutex_unlock(&vq->mutex) == 0);
925 vb = (struct volume_init_batch*)malloc(sizeof(struct volume_init_batch));
927 vb->thread = params->thread;
936 assert(pthread_mutex_lock(&vq->mutex) == 0);
937 queue_Append(vq, vb);
938 assert(pthread_cond_broadcast(&vq->cv) == 0);
939 assert(pthread_mutex_unlock(&vq->mutex) == 0);
941 Log("Partition scan thread %d of %d ended\n", params->thread, params->nthreads);
947 * Read next element from the pre-populated partition list.
949 static struct DiskPartition64*
950 VInitNextPartition(struct partition_queue *pq)
952 struct DiskPartition64 *partition;
953 struct diskpartition_queue_t *dp; /* queue element */
955 if (vinit_attach_abort) {
956 Log("Aborting volume preattach thread.\n");
960 /* get next partition to scan */
961 assert(pthread_mutex_lock(&pq->mutex) == 0);
962 if (queue_IsEmpty(pq)) {
963 assert(pthread_mutex_unlock(&pq->mutex) == 0);
966 dp = queue_First(pq, diskpartition_queue_t);
968 assert(pthread_mutex_unlock(&pq->mutex) == 0);
973 partition = dp->diskP;
979 * Find next volume id on the partition.
982 VInitNextVolumeId(DIR *dirp)
988 while((d = readdir(dirp))) {
989 if (vinit_attach_abort) {
990 Log("Aborting volume preattach thread.\n");
993 ext = strrchr(d->d_name, '.');
994 if (d->d_name[0] == 'V' && ext && strcmp(ext, VHDREXT) == 0) {
995 vid = VolumeNumber(d->d_name);
999 Log("Warning: bogus volume header file: %s\n", d->d_name);
1006 * Preattach volumes in batches to avoid lock contention.
1009 VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq)
1011 struct volume_init_batch *vb;
1015 /* dequeue next volume */
1016 pthread_mutex_lock(&vq->mutex);
1017 if (queue_IsEmpty(vq)) {
1018 pthread_cond_wait(&vq->cv, &vq->mutex);
1020 vb = queue_First(vq, volume_init_batch);
1022 pthread_mutex_unlock(&vq->mutex);
1026 for (i = 0; i<vb->size; i++) {
1032 dup = VLookupVolume_r(&ec, vp->hashid, NULL);
1034 Log("Error looking up volume, code=%d\n", ec);
1037 Log("Warning: Duplicate volume id %d detected.\n", vp->hashid);
1040 /* put pre-attached volume onto the hash table
1041 * and bring it up to the pre-attached state */
1042 AddVolumeToHashTable(vp, vp->hashid);
1043 AddVolumeToVByPList_r(vp);
1044 VLRU_Init_Node_r(vp);
1045 VChangeState_r(vp, VOL_STATE_PREATTACHED);
1058 #endif /* AFS_DEMAND_ATTACH_FS */
1060 #if !defined(AFS_DEMAND_ATTACH_FS)
1062 * attach all volumes on a given disk partition
1065 VAttachVolumesByPartition(struct DiskPartition64 *diskP, int * nAttached, int * nUnattached)
1071 Log("Partition %s: attaching volumes\n", diskP->name);
1072 dirp = opendir(VPartitionPath(diskP));
1074 Log("opendir on Partition %s failed!\n", diskP->name);
1078 while ((dp = readdir(dirp))) {
1080 p = strrchr(dp->d_name, '.');
1082 if (vinit_attach_abort) {
1083 Log("Partition %s: abort attach volumes\n", diskP->name);
1087 if (p != NULL && strcmp(p, VHDREXT) == 0) {
1090 vp = VAttachVolumeByName(&error, diskP->name, dp->d_name,
1092 (*(vp ? nAttached : nUnattached))++;
1093 if (error == VOFFLINE)
1094 Log("Volume %d stays offline (/vice/offline/%s exists)\n", VolumeNumber(dp->d_name), dp->d_name);
1095 else if (LogLevel >= 5) {
1096 Log("Partition %s: attached volume %d (%s)\n",
1097 diskP->name, VolumeNumber(dp->d_name),
1106 Log("Partition %s: attached %d volumes; %d volumes not attached\n", diskP->name, *nAttached, *nUnattached);
1111 #endif /* !AFS_DEMAND_ATTACH_FS */
1113 /***************************************************/
1114 /* Shutdown routines */
1115 /***************************************************/
1119 * highly multithreaded volume package shutdown
1121 * with the demand attach fileserver extensions,
1122 * VShutdown has been modified to be multithreaded.
1123 * In order to achieve optimal use of many threads,
1124 * the shutdown code involves one control thread and
1125 * n shutdown worker threads. The control thread
1126 * periodically examines the number of volumes available
1127 * for shutdown on each partition, and produces a worker
1128 * thread allocation schedule. The idea is to eliminate
1129 * redundant scheduling computation on the workers by
1130 * having a single master scheduler.
1132 * The scheduler's objectives are:
1134 * each partition with volumes remaining gets allocated
1135 * at least 1 thread (assuming sufficient threads)
1137 * threads are allocated proportional to the number of
1138 * volumes remaining to be offlined. This ensures that
1139 * the OS I/O scheduler has many requests to elevator
1140 * seek on partitions that will (presumably) take the
1141 * longest amount of time (from now) to finish shutdown
1142 * (3) keep threads busy
1143 * when there are extra threads, they are assigned to
1144 * partitions using a simple round-robin algorithm
1146 * In the future, we may wish to add the ability to adapt
1147 * to the relative performance patterns of each disk
1152 * multi-step shutdown process
1154 * demand attach shutdown is a four-step process. Each
1155 * shutdown "pass" shuts down increasingly more difficult
1156 * volumes. The main purpose is to achieve better cache
1157 * utilization during shutdown.
1160 * shutdown volumes in the unattached, pre-attached
1163 * shutdown attached volumes with cached volume headers
1165 * shutdown all volumes in non-exclusive states
1167 * shutdown all remaining volumes
1170 #ifdef AFS_DEMAND_ATTACH_FS
1176 struct DiskPartition64 * diskP;
1177 struct diskpartition_queue_t * dpq;
1178 vshutdown_thread_t params;
1180 pthread_attr_t attrs;
1182 memset(¶ms, 0, sizeof(vshutdown_thread_t));
1185 Log("VShutdown: aborting attach volumes\n");
1186 vinit_attach_abort = 1;
1187 VOL_CV_WAIT(&vol_init_attach_cond);
1190 for (params.n_parts=0, diskP = DiskPartitionList;
1191 diskP; diskP = diskP->next, params.n_parts++);
1193 Log("VShutdown: shutting down on-line volumes on %d partition%s...\n",
1194 params.n_parts, params.n_parts > 1 ? "s" : "");
1196 if (vol_attach_threads > 1) {
1197 /* prepare for parallel shutdown */
1198 params.n_threads = vol_attach_threads;
1199 assert(pthread_mutex_init(¶ms.lock, NULL) == 0);
1200 assert(pthread_cond_init(¶ms.cv, NULL) == 0);
1201 assert(pthread_cond_init(¶ms.master_cv, NULL) == 0);
1202 assert(pthread_attr_init(&attrs) == 0);
1203 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
1204 queue_Init(¶ms);
1206 /* setup the basic partition information structures for
1207 * parallel shutdown */
1208 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1210 struct rx_queue * qp, * nqp;
1214 VVByPListWait_r(diskP);
1215 VVByPListBeginExclusive_r(diskP);
1218 for (queue_Scan(&diskP->vol_list, qp, nqp, rx_queue)) {
1219 vp = (Volume *)((char *)qp - offsetof(Volume, vol_list));
1223 Log("VShutdown: partition %s has %d volumes with attached headers\n",
1224 VPartitionPath(diskP), count);
1227 /* build up the pass 0 shutdown work queue */
1228 dpq = (struct diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
1229 assert(dpq != NULL);
1231 queue_Prepend(¶ms, dpq);
1233 params.part_pass_head[diskP->index] = queue_First(&diskP->vol_list, rx_queue);
1236 Log("VShutdown: beginning parallel fileserver shutdown\n");
1237 Log("VShutdown: using %d threads to offline volumes on %d partition%s\n",
1238 vol_attach_threads, params.n_parts, params.n_parts > 1 ? "s" : "" );
1240 /* do pass 0 shutdown */
1241 assert(pthread_mutex_lock(¶ms.lock) == 0);
1242 for (i=0; i < params.n_threads; i++) {
1243 assert(pthread_create
1244 (&tid, &attrs, &VShutdownThread,
1248 /* wait for all the pass 0 shutdowns to complete */
1249 while (params.n_threads_complete < params.n_threads) {
1250 assert(pthread_cond_wait(¶ms.master_cv, ¶ms.lock) == 0);
1252 params.n_threads_complete = 0;
1254 assert(pthread_cond_broadcast(¶ms.cv) == 0);
1255 assert(pthread_mutex_unlock(¶ms.lock) == 0);
1257 Log("VShutdown: pass 0 completed using the 1 thread per partition algorithm\n");
1258 Log("VShutdown: starting passes 1 through 3 using finely-granular mp-fast algorithm\n");
1260 /* run the parallel shutdown scheduler. it will drop the glock internally */
1261 ShutdownController(¶ms);
1263 /* wait for all the workers to finish pass 3 and terminate */
1264 while (params.pass < 4) {
1265 VOL_CV_WAIT(¶ms.cv);
1268 assert(pthread_attr_destroy(&attrs) == 0);
1269 assert(pthread_cond_destroy(¶ms.cv) == 0);
1270 assert(pthread_cond_destroy(¶ms.master_cv) == 0);
1271 assert(pthread_mutex_destroy(¶ms.lock) == 0);
1273 /* drop the VByPList exclusive reservations */
1274 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1275 VVByPListEndExclusive_r(diskP);
1276 Log("VShutdown: %s stats : (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1277 VPartitionPath(diskP),
1278 params.stats[0][diskP->index],
1279 params.stats[1][diskP->index],
1280 params.stats[2][diskP->index],
1281 params.stats[3][diskP->index]);
1284 Log("VShutdown: shutdown finished using %d threads\n", params.n_threads);
1286 /* if we're only going to run one shutdown thread, don't bother creating
1288 Log("VShutdown: beginning single-threaded fileserver shutdown\n");
1290 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1291 VShutdownByPartition_r(diskP);
1295 Log("VShutdown: complete.\n");
1298 #else /* AFS_DEMAND_ATTACH_FS */
1304 register Volume *vp, *np;
1305 register afs_int32 code;
1308 Log("VShutdown: aborting attach volumes\n");
1309 vinit_attach_abort = 1;
1310 #ifdef AFS_PTHREAD_ENV
1311 VOL_CV_WAIT(&vol_init_attach_cond);
1313 LWP_WaitProcess(VInitAttachVolumes);
1314 #endif /* AFS_PTHREAD_ENV */
1317 Log("VShutdown: shutting down on-line volumes...\n");
1318 for (i = 0; i < VolumeHashTable.Size; i++) {
1319 /* try to hold first volume in the hash table */
1320 for (queue_Scan(&VolumeHashTable.Table[i],vp,np,Volume)) {
1324 Log("VShutdown: Attempting to take volume %u offline.\n",
1327 /* next, take the volume offline (drops reference count) */
1328 VOffline_r(vp, "File server was shut down");
1332 Log("VShutdown: complete.\n");
1334 #endif /* AFS_DEMAND_ATTACH_FS */
1347 * stop new activity (e.g. SALVSYNC) from occurring
1349 * Use this to make the volume package less busy; for example, during
1350 * shutdown. This doesn't actually shutdown/detach anything in the
1351 * volume package, but prevents certain processes from ocurring. For
1352 * example, preventing new SALVSYNC communication in DAFS. In theory, we
1353 * could also use this to prevent new volume attachment, or prevent
1354 * other programs from checking out volumes, etc.
1359 #ifdef AFS_DEMAND_ATTACH_FS
1360 /* make sure we don't try to contact the salvageserver, since it may
1361 * not be around anymore */
1362 vol_disallow_salvsync = 1;
1366 #ifdef AFS_DEMAND_ATTACH_FS
1369 * shutdown control thread
1372 ShutdownController(vshutdown_thread_t * params)
1375 struct DiskPartition64 * diskP;
1377 vshutdown_thread_t shadow;
1379 ShutdownCreateSchedule(params);
1381 while ((params->pass < 4) &&
1382 (params->n_threads_complete < params->n_threads)) {
1383 /* recompute schedule once per second */
1385 memcpy(&shadow, params, sizeof(vshutdown_thread_t));
1389 Log("ShutdownController: schedule version=%d, vol_remaining=%d, pass=%d\n",
1390 shadow.schedule_version, shadow.vol_remaining, shadow.pass);
1391 Log("ShutdownController: n_threads_complete=%d, n_parts_done_pass=%d\n",
1392 shadow.n_threads_complete, shadow.n_parts_done_pass);
1393 for (diskP = DiskPartitionList; diskP; diskP=diskP->next) {
1395 Log("ShutdownController: part[%d] : (len=%d, thread_target=%d, done_pass=%d, pass_head=%p)\n",
1397 diskP->vol_list.len,
1398 shadow.part_thread_target[id],
1399 shadow.part_done_pass[id],
1400 shadow.part_pass_head[id]);
1406 ShutdownCreateSchedule(params);
1410 /* create the shutdown thread work schedule.
1411 * this scheduler tries to implement fairness
1412 * by allocating at least 1 thread to each
1413 * partition with volumes to be shutdown,
1414 * and then it attempts to allocate remaining
1415 * threads based upon the amount of work left
1418 ShutdownCreateSchedule(vshutdown_thread_t * params)
1420 struct DiskPartition64 * diskP;
1421 int sum, thr_workload, thr_left;
1422 int part_residue[VOLMAXPARTS+1];
1425 /* compute the total number of outstanding volumes */
1427 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1428 sum += diskP->vol_list.len;
1431 params->schedule_version++;
1432 params->vol_remaining = sum;
1437 /* compute average per-thread workload */
1438 thr_workload = sum / params->n_threads;
1439 if (sum % params->n_threads)
1442 thr_left = params->n_threads;
1443 memset(&part_residue, 0, sizeof(part_residue));
1445 /* for fairness, give every partition with volumes remaining
1446 * at least one thread */
1447 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1449 if (diskP->vol_list.len) {
1450 params->part_thread_target[id] = 1;
1453 params->part_thread_target[id] = 0;
1457 if (thr_left && thr_workload) {
1458 /* compute length-weighted workloads */
1461 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1463 delta = (diskP->vol_list.len / thr_workload) -
1464 params->part_thread_target[id];
1468 if (delta < thr_left) {
1469 params->part_thread_target[id] += delta;
1472 params->part_thread_target[id] += thr_left;
1480 /* try to assign any leftover threads to partitions that
1481 * had volume lengths closer to needing thread_target+1 */
1482 int max_residue, max_id = 0;
1484 /* compute the residues */
1485 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1487 part_residue[id] = diskP->vol_list.len -
1488 (params->part_thread_target[id] * thr_workload);
1491 /* now try to allocate remaining threads to partitions with the
1492 * highest residues */
1495 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1497 if (part_residue[id] > max_residue) {
1498 max_residue = part_residue[id];
1507 params->part_thread_target[max_id]++;
1509 part_residue[max_id] = 0;
1514 /* punt and give any remaining threads equally to each partition */
1516 if (thr_left >= params->n_parts) {
1517 alloc = thr_left / params->n_parts;
1518 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1520 params->part_thread_target[id] += alloc;
1525 /* finish off the last of the threads */
1526 for (diskP = DiskPartitionList; thr_left && diskP; diskP = diskP->next) {
1528 params->part_thread_target[id]++;
1534 /* worker thread for parallel shutdown */
1536 VShutdownThread(void * args)
1538 vshutdown_thread_t * params;
1539 int found, pass, schedule_version_save, count;
1540 struct DiskPartition64 *diskP;
1541 struct diskpartition_queue_t * dpq;
1544 params = (vshutdown_thread_t *) args;
1546 /* acquire the shutdown pass 0 lock */
1547 assert(pthread_mutex_lock(¶ms->lock) == 0);
1549 /* if there's still pass 0 work to be done,
1550 * get a work entry, and do a pass 0 shutdown */
1551 if (queue_IsNotEmpty(params)) {
1552 dpq = queue_First(params, diskpartition_queue_t);
1554 assert(pthread_mutex_unlock(¶ms->lock) == 0);
1560 while (ShutdownVolumeWalk_r(diskP, 0, ¶ms->part_pass_head[id]))
1562 params->stats[0][diskP->index] = count;
1563 assert(pthread_mutex_lock(¶ms->lock) == 0);
1566 params->n_threads_complete++;
1567 if (params->n_threads_complete == params->n_threads) {
1568 /* notify control thread that all workers have completed pass 0 */
1569 assert(pthread_cond_signal(¶ms->master_cv) == 0);
1571 while (params->pass == 0) {
1572 assert(pthread_cond_wait(¶ms->cv, ¶ms->lock) == 0);
1576 assert(pthread_mutex_unlock(¶ms->lock) == 0);
1579 pass = params->pass;
1582 /* now escalate through the more complicated shutdowns */
1584 schedule_version_save = params->schedule_version;
1586 /* find a disk partition to work on */
1587 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1589 if (params->part_thread_target[id] && !params->part_done_pass[id]) {
1590 params->part_thread_target[id]--;
1597 /* hmm. for some reason the controller thread couldn't find anything for
1598 * us to do. let's see if there's anything we can do */
1599 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1601 if (diskP->vol_list.len && !params->part_done_pass[id]) {
1604 } else if (!params->part_done_pass[id]) {
1605 params->part_done_pass[id] = 1;
1606 params->n_parts_done_pass++;
1608 Log("VShutdown: done shutting down volumes on partition %s.\n",
1609 VPartitionPath(diskP));
1615 /* do work on this partition until either the controller
1616 * creates a new schedule, or we run out of things to do
1617 * on this partition */
1620 while (!params->part_done_pass[id] &&
1621 (schedule_version_save == params->schedule_version)) {
1622 /* ShutdownVolumeWalk_r will drop the glock internally */
1623 if (!ShutdownVolumeWalk_r(diskP, pass, ¶ms->part_pass_head[id])) {
1624 if (!params->part_done_pass[id]) {
1625 params->part_done_pass[id] = 1;
1626 params->n_parts_done_pass++;
1628 Log("VShutdown: done shutting down volumes on partition %s.\n",
1629 VPartitionPath(diskP));
1637 params->stats[pass][id] += count;
1639 /* ok, everyone is done this pass, proceed */
1642 params->n_threads_complete++;
1643 while (params->pass == pass) {
1644 if (params->n_threads_complete == params->n_threads) {
1645 /* we are the last thread to complete, so we will
1646 * reinitialize worker pool state for the next pass */
1647 params->n_threads_complete = 0;
1648 params->n_parts_done_pass = 0;
1650 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1652 params->part_done_pass[id] = 0;
1653 params->part_pass_head[id] = queue_First(&diskP->vol_list, rx_queue);
1656 /* compute a new thread schedule before releasing all the workers */
1657 ShutdownCreateSchedule(params);
1659 /* wake up all the workers */
1660 assert(pthread_cond_broadcast(¶ms->cv) == 0);
1663 Log("VShutdown: pass %d completed using %d threads on %d partitions\n",
1664 pass, params->n_threads, params->n_parts);
1667 VOL_CV_WAIT(¶ms->cv);
1670 pass = params->pass;
1684 /* shut down all volumes on a given disk partition
1686 * note that this function will not allow mp-fast
1687 * shutdown of a partition */
1689 VShutdownByPartition_r(struct DiskPartition64 * dp)
1695 /* wait for other exclusive ops to finish */
1696 VVByPListWait_r(dp);
1698 /* begin exclusive access */
1699 VVByPListBeginExclusive_r(dp);
1701 /* pick the low-hanging fruit first,
1702 * then do the complicated ones last
1703 * (has the advantage of keeping
1704 * in-use volumes up until the bitter end) */
1705 for (pass = 0, total=0; pass < 4; pass++) {
1706 pass_stats[pass] = ShutdownVByPForPass_r(dp, pass);
1707 total += pass_stats[pass];
1710 /* end exclusive access */
1711 VVByPListEndExclusive_r(dp);
1713 Log("VShutdownByPartition: shut down %d volumes on %s (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1714 total, VPartitionPath(dp), pass_stats[0], pass_stats[1], pass_stats[2], pass_stats[3]);
1719 /* internal shutdown functionality
1721 * for multi-pass shutdown:
1722 * 0 to only "shutdown" {pre,un}attached and error state volumes
1723 * 1 to also shutdown attached volumes w/ volume header loaded
1724 * 2 to also shutdown attached volumes w/o volume header loaded
1725 * 3 to also shutdown exclusive state volumes
1727 * caller MUST hold exclusive access on the hash chain
1728 * because we drop vol_glock_mutex internally
1730 * this function is reentrant for passes 1--3
1731 * (e.g. multiple threads can cooperate to
1732 * shutdown a partition mp-fast)
1734 * pass 0 is not scaleable because the volume state data is
1735 * synchronized by vol_glock mutex, and the locking overhead
1736 * is too high to drop the lock long enough to do linked list
1740 ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass)
1742 struct rx_queue * q = queue_First(&dp->vol_list, rx_queue);
1745 while (ShutdownVolumeWalk_r(dp, pass, &q))
1751 /* conditionally shutdown one volume on partition dp
1752 * returns 1 if a volume was shutdown in this pass,
1755 ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
1756 struct rx_queue ** idx)
1758 struct rx_queue *qp, *nqp;
1763 for (queue_ScanFrom(&dp->vol_list, qp, qp, nqp, rx_queue)) {
1764 vp = (Volume *) (((char *)qp) - offsetof(Volume, vol_list));
1768 if ((V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1769 (V_attachState(vp) != VOL_STATE_ERROR) &&
1770 (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1774 if ((V_attachState(vp) == VOL_STATE_ATTACHED) &&
1775 (vp->header == NULL)) {
1779 if (VIsExclusiveState(V_attachState(vp))) {
1784 DeleteVolumeFromVByPList_r(vp);
1785 VShutdownVolume_r(vp);
1795 * shutdown a specific volume
1797 /* caller MUST NOT hold a heavyweight ref on vp */
1799 VShutdownVolume_r(Volume * vp)
1803 VCreateReservation_r(vp);
1805 if (LogLevel >= 5) {
1806 Log("VShutdownVolume_r: vid=%u, device=%d, state=%hu\n",
1807 vp->hashid, vp->partition->device, V_attachState(vp));
1810 /* wait for other blocking ops to finish */
1811 VWaitExclusiveState_r(vp);
1813 assert(VIsValidState(V_attachState(vp)));
1815 switch(V_attachState(vp)) {
1816 case VOL_STATE_SALVAGING:
1817 /* Leave salvaging volumes alone. Any in-progress salvages will
1818 * continue working after viced shuts down. This is intentional.
1821 case VOL_STATE_PREATTACHED:
1822 case VOL_STATE_ERROR:
1823 VChangeState_r(vp, VOL_STATE_UNATTACHED);
1824 case VOL_STATE_UNATTACHED:
1826 case VOL_STATE_GOING_OFFLINE:
1827 case VOL_STATE_SHUTTING_DOWN:
1828 case VOL_STATE_ATTACHED:
1832 Log("VShutdown: Attempting to take volume %u offline.\n",
1835 /* take the volume offline (drops reference count) */
1836 VOffline_r(vp, "File server was shut down");
1843 VCancelReservation_r(vp);
1847 #endif /* AFS_DEMAND_ATTACH_FS */
1850 /***************************************************/
1851 /* Header I/O routines */
1852 /***************************************************/
1854 /* open a descriptor for the inode (h),
1855 * read in an on-disk structure into buffer (to) of size (size),
1856 * verify versionstamp in structure has magic (magic) and
1857 * optionally verify version (version) if (version) is nonzero
1860 ReadHeader(Error * ec, IHandle_t * h, char *to, int size, bit32 magic,
1863 struct versionStamp *vsn;
1878 if (FDH_SEEK(fdP, 0, SEEK_SET) < 0) {
1880 FDH_REALLYCLOSE(fdP);
1883 vsn = (struct versionStamp *)to;
1884 if (FDH_READ(fdP, to, size) != size || vsn->magic != magic) {
1886 FDH_REALLYCLOSE(fdP);
1891 /* Check is conditional, in case caller wants to inspect version himself */
1892 if (version && vsn->version != version) {
1898 WriteVolumeHeader_r(Error * ec, Volume * vp)
1900 IHandle_t *h = V_diskDataHandle(vp);
1910 if (FDH_SEEK(fdP, 0, SEEK_SET) < 0) {
1912 FDH_REALLYCLOSE(fdP);
1915 if (FDH_WRITE(fdP, (char *)&V_disk(vp), sizeof(V_disk(vp)))
1916 != sizeof(V_disk(vp))) {
1918 FDH_REALLYCLOSE(fdP);
1924 /* VolumeHeaderToDisk
1925 * Allows for storing 64 bit inode numbers in on-disk volume header
1928 /* convert in-memory representation of a volume header to the
1929 * on-disk representation of a volume header */
1931 VolumeHeaderToDisk(VolumeDiskHeader_t * dh, VolumeHeader_t * h)
1934 memset(dh, 0, sizeof(VolumeDiskHeader_t));
1935 dh->stamp = h->stamp;
1937 dh->parent = h->parent;
1939 #ifdef AFS_64BIT_IOPS_ENV
1940 dh->volumeInfo_lo = (afs_int32) h->volumeInfo & 0xffffffff;
1941 dh->volumeInfo_hi = (afs_int32) (h->volumeInfo >> 32) & 0xffffffff;
1942 dh->smallVnodeIndex_lo = (afs_int32) h->smallVnodeIndex & 0xffffffff;
1943 dh->smallVnodeIndex_hi =
1944 (afs_int32) (h->smallVnodeIndex >> 32) & 0xffffffff;
1945 dh->largeVnodeIndex_lo = (afs_int32) h->largeVnodeIndex & 0xffffffff;
1946 dh->largeVnodeIndex_hi =
1947 (afs_int32) (h->largeVnodeIndex >> 32) & 0xffffffff;
1948 dh->linkTable_lo = (afs_int32) h->linkTable & 0xffffffff;
1949 dh->linkTable_hi = (afs_int32) (h->linkTable >> 32) & 0xffffffff;
1951 dh->volumeInfo_lo = h->volumeInfo;
1952 dh->smallVnodeIndex_lo = h->smallVnodeIndex;
1953 dh->largeVnodeIndex_lo = h->largeVnodeIndex;
1954 dh->linkTable_lo = h->linkTable;
1958 /* DiskToVolumeHeader
1959 * Converts an on-disk representation of a volume header to
1960 * the in-memory representation of a volume header.
1962 * Makes the assumption that AFS has *always*
1963 * zero'd the volume header file so that high parts of inode
1964 * numbers are 0 in older (SGI EFS) volume header files.
1967 DiskToVolumeHeader(VolumeHeader_t * h, VolumeDiskHeader_t * dh)
1969 memset(h, 0, sizeof(VolumeHeader_t));
1970 h->stamp = dh->stamp;
1972 h->parent = dh->parent;
1974 #ifdef AFS_64BIT_IOPS_ENV
1976 (Inode) dh->volumeInfo_lo | ((Inode) dh->volumeInfo_hi << 32);
1978 h->smallVnodeIndex =
1979 (Inode) dh->smallVnodeIndex_lo | ((Inode) dh->
1980 smallVnodeIndex_hi << 32);
1982 h->largeVnodeIndex =
1983 (Inode) dh->largeVnodeIndex_lo | ((Inode) dh->
1984 largeVnodeIndex_hi << 32);
1986 (Inode) dh->linkTable_lo | ((Inode) dh->linkTable_hi << 32);
1988 h->volumeInfo = dh->volumeInfo_lo;
1989 h->smallVnodeIndex = dh->smallVnodeIndex_lo;
1990 h->largeVnodeIndex = dh->largeVnodeIndex_lo;
1991 h->linkTable = dh->linkTable_lo;
1996 /***************************************************/
1997 /* Volume Attachment routines */
1998 /***************************************************/
2000 #ifdef AFS_DEMAND_ATTACH_FS
2002 * pre-attach a volume given its path.
2004 * @param[out] ec outbound error code
2005 * @param[in] partition partition path string
2006 * @param[in] name volume id string
2008 * @return volume object pointer
2010 * @note A pre-attached volume will only have its partition
2011 * and hashid fields initialized. At first call to
2012 * VGetVolume, the volume will be fully attached.
2016 VPreAttachVolumeByName(Error * ec, char *partition, char *name)
2020 vp = VPreAttachVolumeByName_r(ec, partition, name);
2026 * pre-attach a volume given its path.
2028 * @param[out] ec outbound error code
2029 * @param[in] partition path to vice partition
2030 * @param[in] name volume id string
2032 * @return volume object pointer
2034 * @pre VOL_LOCK held
2036 * @internal volume package internal use only.
2039 VPreAttachVolumeByName_r(Error * ec, char *partition, char *name)
2041 return VPreAttachVolumeById_r(ec,
2043 VolumeNumber(name));
2047 * pre-attach a volume given its path and numeric volume id.
2049 * @param[out] ec error code return
2050 * @param[in] partition path to vice partition
2051 * @param[in] volumeId numeric volume id
2053 * @return volume object pointer
2055 * @pre VOL_LOCK held
2057 * @internal volume package internal use only.
2060 VPreAttachVolumeById_r(Error * ec,
2065 struct DiskPartition64 *partp;
2069 assert(programType == fileServer);
2071 if (!(partp = VGetPartition_r(partition, 0))) {
2073 Log("VPreAttachVolumeById_r: Error getting partition (%s)\n", partition);
2077 vp = VLookupVolume_r(ec, volumeId, NULL);
2082 return VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2086 * preattach a volume.
2088 * @param[out] ec outbound error code
2089 * @param[in] partp pointer to partition object
2090 * @param[in] vp pointer to volume object
2091 * @param[in] vid volume id
2093 * @return volume object pointer
2095 * @pre VOL_LOCK is held.
2097 * @warning Returned volume object pointer does not have to
2098 * equal the pointer passed in as argument vp. There
2099 * are potential race conditions which can result in
2100 * the pointers having different values. It is up to
2101 * the caller to make sure that references are handled
2102 * properly in this case.
2104 * @note If there is already a volume object registered with
2105 * the same volume id, its pointer MUST be passed as
2106 * argument vp. Failure to do so will result in a silent
2107 * failure to preattach.
2109 * @internal volume package internal use only.
2112 VPreAttachVolumeByVp_r(Error * ec,
2113 struct DiskPartition64 * partp,
2121 /* check to see if pre-attach already happened */
2123 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
2124 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
2125 !VIsErrorState(V_attachState(vp))) {
2127 * pre-attach is a no-op in all but the following cases:
2129 * - volume is unattached
2130 * - volume is in an error state
2131 * - volume is pre-attached
2133 Log("VPreattachVolumeByVp_r: volume %u not in quiescent state\n", vid);
2136 /* we're re-attaching a volume; clear out some old state */
2137 memset(&vp->salvage, 0, sizeof(struct VolumeOnlineSalvage));
2139 if (V_partition(vp) != partp) {
2140 /* XXX potential race */
2141 DeleteVolumeFromVByPList_r(vp);
2144 /* if we need to allocate a new Volume struct,
2145 * go ahead and drop the vol glock, otherwise
2146 * do the basic setup synchronised, as it's
2147 * probably not worth dropping the lock */
2150 /* allocate the volume structure */
2151 vp = nvp = (Volume *) malloc(sizeof(Volume));
2153 memset(vp, 0, sizeof(Volume));
2154 queue_Init(&vp->vnode_list);
2155 assert(pthread_cond_init(&V_attachCV(vp), NULL) == 0);
2158 /* link the volume with its associated vice partition */
2159 vp->device = partp->device;
2160 vp->partition = partp;
2163 vp->specialStatus = 0;
2165 /* if we dropped the lock, reacquire the lock,
2166 * check for pre-attach races, and then add
2167 * the volume to the hash table */
2170 nvp = VLookupVolume_r(ec, vid, NULL);
2175 } else if (nvp) { /* race detected */
2180 /* hack to make up for VChangeState_r() decrementing
2181 * the old state counter */
2182 VStats.state_levels[0]++;
2186 /* put pre-attached volume onto the hash table
2187 * and bring it up to the pre-attached state */
2188 AddVolumeToHashTable(vp, vp->hashid);
2189 AddVolumeToVByPList_r(vp);
2190 VLRU_Init_Node_r(vp);
2191 VChangeState_r(vp, VOL_STATE_PREATTACHED);
2194 Log("VPreAttachVolumeByVp_r: volume %u pre-attached\n", vp->hashid);
2202 #endif /* AFS_DEMAND_ATTACH_FS */
2204 /* Attach an existing volume, given its pathname, and return a
2205 pointer to the volume header information. The volume also
2206 normally goes online at this time. An offline volume
2207 must be reattached to make it go online */
2209 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
2213 retVal = VAttachVolumeByName_r(ec, partition, name, mode);
2219 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
2221 register Volume *vp = NULL;
2222 struct DiskPartition64 *partp;
2226 #ifdef AFS_DEMAND_ATTACH_FS
2227 VolumeStats stats_save;
2229 #endif /* AFS_DEMAND_ATTACH_FS */
2233 volumeId = VolumeNumber(name);
2235 if (!(partp = VGetPartition_r(partition, 0))) {
2237 Log("VAttachVolume: Error getting partition (%s)\n", partition);
2241 if (VRequiresPartLock()) {
2243 VLockPartition_r(partition);
2244 } else if (programType == fileServer) {
2245 #ifdef AFS_DEMAND_ATTACH_FS
2246 /* lookup the volume in the hash table */
2247 vp = VLookupVolume_r(ec, volumeId, NULL);
2253 /* save any counters that are supposed to
2254 * be monotonically increasing over the
2255 * lifetime of the fileserver */
2256 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2258 memset(&stats_save, 0, sizeof(VolumeStats));
2261 /* if there's something in the hash table, and it's not
2262 * in the pre-attach state, then we may need to detach
2263 * it before proceeding */
2264 if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
2265 VCreateReservation_r(vp);
2266 VWaitExclusiveState_r(vp);
2268 /* at this point state must be one of:
2277 if (vp->specialStatus == VBUSY)
2280 /* if it's already attached, see if we can return it */
2281 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2282 VGetVolumeByVp_r(ec, vp);
2283 if (V_inUse(vp) == fileServer) {
2284 VCancelReservation_r(vp);
2288 /* otherwise, we need to detach, and attempt to re-attach */
2289 VDetachVolume_r(ec, vp);
2291 Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
2294 /* if it isn't fully attached, delete from the hash tables,
2295 and let the refcounter handle the rest */
2296 DeleteVolumeFromHashTable(vp);
2297 DeleteVolumeFromVByPList_r(vp);
2300 VCancelReservation_r(vp);
2304 /* pre-attach volume if it hasn't been done yet */
2306 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2307 (V_attachState(vp) == VOL_STATE_ERROR)) {
2309 vp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2317 /* handle pre-attach races
2319 * multiple threads can race to pre-attach a volume,
2320 * but we can't let them race beyond that
2322 * our solution is to let the first thread to bring
2323 * the volume into an exclusive state win; the other
2324 * threads just wait until it finishes bringing the
2325 * volume online, and then they do a vgetvolumebyvp
2327 if (svp && (svp != vp)) {
2328 /* wait for other exclusive ops to finish */
2329 VCreateReservation_r(vp);
2330 VWaitExclusiveState_r(vp);
2332 /* get a heavyweight ref, kill the lightweight ref, and return */
2333 VGetVolumeByVp_r(ec, vp);
2334 VCancelReservation_r(vp);
2338 /* at this point, we are chosen as the thread to do
2339 * demand attachment for this volume. all other threads
2340 * doing a getvolume on vp->hashid will block until we finish */
2342 /* make sure any old header cache entries are invalidated
2343 * before proceeding */
2344 FreeVolumeHeader(vp);
2346 VChangeState_r(vp, VOL_STATE_ATTACHING);
2348 /* restore any saved counters */
2349 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2350 #else /* AFS_DEMAND_ATTACH_FS */
2351 vp = VGetVolume_r(ec, volumeId);
2353 if (V_inUse(vp) == fileServer)
2355 if (vp->specialStatus == VBUSY)
2357 VDetachVolume_r(ec, vp);
2359 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2363 #endif /* AFS_DEMAND_ATTACH_FS */
2367 strcpy(path, VPartitionPath(partp));
2375 vp = (Volume *) calloc(1, sizeof(Volume));
2377 vp->hashid = volumeId;
2378 vp->device = partp->device;
2379 vp->partition = partp;
2380 queue_Init(&vp->vnode_list);
2381 #ifdef AFS_DEMAND_ATTACH_FS
2382 assert(pthread_cond_init(&V_attachCV(vp), NULL) == 0);
2383 #endif /* AFS_DEMAND_ATTACH_FS */
2386 /* attach2 is entered without any locks, and returns
2387 * with vol_glock_mutex held */
2388 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode);
2390 if (VCanUseFSSYNC() && vp) {
2391 #ifdef AFS_DEMAND_ATTACH_FS
2392 if ((mode == V_VOLUPD) || (VolumeWriteable(vp) && (mode == V_CLONE))) {
2393 /* mark volume header as in use so that volser crashes lead to a
2394 * salvage attempt */
2395 VUpdateVolume_r(ec, vp, 0);
2397 /* for dafs, we should tell the fileserver, except for V_PEEK
2398 * where we know it is not necessary */
2399 if (mode == V_PEEK) {
2400 vp->needsPutBack = 0;
2402 vp->needsPutBack = 1;
2404 #else /* !AFS_DEMAND_ATTACH_FS */
2405 /* duplicate computation in fssync.c about whether the server
2406 * takes the volume offline or not. If the volume isn't
2407 * offline, we must not return it when we detach the volume,
2408 * or the server will abort */
2409 if (mode == V_READONLY || mode == V_PEEK
2410 || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
2411 vp->needsPutBack = 0;
2413 vp->needsPutBack = 1;
2414 #endif /* !AFS_DEMAND_ATTACH_FS */
2416 /* OK, there's a problem here, but one that I don't know how to
2417 * fix right now, and that I don't think should arise often.
2418 * Basically, we should only put back this volume to the server if
2419 * it was given to us by the server, but since we don't have a vp,
2420 * we can't run the VolumeWriteable function to find out as we do
2421 * above when computing vp->needsPutBack. So we send it back, but
2422 * there's a path in VAttachVolume on the server which may abort
2423 * if this volume doesn't have a header. Should be pretty rare
2424 * for all of that to happen, but if it does, probably the right
2425 * fix is for the server to allow the return of readonly volumes
2426 * that it doesn't think are really checked out. */
2427 #ifdef FSSYNC_BUILD_CLIENT
2428 if (VCanUseFSSYNC() && vp == NULL &&
2429 mode != V_SECRETLY && mode != V_PEEK) {
2431 #ifdef AFS_DEMAND_ATTACH_FS
2432 /* If we couldn't attach but we scheduled a salvage, we already
2433 * notified the fileserver; don't online it now */
2434 if (*ec != VSALVAGING)
2435 #endif /* AFS_DEMAND_ATTACH_FS */
2436 FSYNC_VolOp(volumeId, partition, FSYNC_VOL_ON, 0, NULL);
2439 if (programType == fileServer && vp) {
2440 #ifdef AFS_DEMAND_ATTACH_FS
2442 * we can get here in cases where we don't "own"
2443 * the volume (e.g. volume owned by a utility).
2444 * short circuit around potential disk header races.
2446 if (V_attachState(vp) != VOL_STATE_ATTACHED) {
2450 VUpdateVolume_r(ec, vp, 0);
2452 Log("VAttachVolume: Error updating volume\n");
2457 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2458 #ifndef AFS_DEMAND_ATTACH_FS
2459 /* This is a hack: by temporarily setting the incore
2460 * dontSalvage flag ON, the volume will be put back on the
2461 * Update list (with dontSalvage OFF again). It will then
2462 * come back in N minutes with DONT_SALVAGE eventually
2463 * set. This is the way that volumes that have never had
2464 * it set get it set; or that volumes that have been
2465 * offline without DONT SALVAGE having been set also
2466 * eventually get it set */
2467 V_dontSalvage(vp) = DONT_SALVAGE;
2468 #endif /* !AFS_DEMAND_ATTACH_FS */
2469 VAddToVolumeUpdateList_r(ec, vp);
2471 Log("VAttachVolume: Error adding volume to update list\n");
2478 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2483 if (VRequiresPartLock()) {
2484 VUnlockPartition_r(partition);
2487 #ifdef AFS_DEMAND_ATTACH_FS
2488 /* attach failed; make sure we're in error state */
2489 if (vp && !VIsErrorState(V_attachState(vp))) {
2490 VChangeState_r(vp, VOL_STATE_ERROR);
2492 #endif /* AFS_DEMAND_ATTACH_FS */
2499 #ifdef AFS_DEMAND_ATTACH_FS
2500 /* VAttachVolumeByVp_r
2502 * finish attaching a volume that is
2503 * in a less than fully attached state
2505 /* caller MUST hold a ref count on vp */
2507 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
2509 char name[VMAXPATHLEN];
2511 struct DiskPartition64 *partp;
2515 Volume * nvp = NULL;
2516 VolumeStats stats_save;
2519 /* volume utility should never call AttachByVp */
2520 assert(programType == fileServer);
2522 volumeId = vp->hashid;
2523 partp = vp->partition;
2524 VolumeExternalName_r(volumeId, name, sizeof(name));
2527 /* if another thread is performing a blocking op, wait */
2528 VWaitExclusiveState_r(vp);
2530 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2532 /* if it's already attached, see if we can return it */
2533 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2534 VGetVolumeByVp_r(ec, vp);
2535 if (V_inUse(vp) == fileServer) {
2538 if (vp->specialStatus == VBUSY)
2540 VDetachVolume_r(ec, vp);
2542 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2548 /* pre-attach volume if it hasn't been done yet */
2550 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2551 (V_attachState(vp) == VOL_STATE_ERROR)) {
2552 nvp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2558 VCreateReservation_r(nvp);
2564 VChangeState_r(vp, VOL_STATE_ATTACHING);
2566 /* restore monotonically increasing stats */
2567 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2571 /* compute path to disk header */
2572 strcpy(path, VPartitionPath(partp));
2581 * NOTE: attach2 is entered without any locks, and returns
2582 * with vol_glock_mutex held */
2583 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode);
2586 * the event that an error was encountered, or
2587 * the volume was not brought to an attached state
2588 * for any reason, skip to the end. We cannot
2589 * safely call VUpdateVolume unless we "own" it.
2593 (V_attachState(vp) != VOL_STATE_ATTACHED)) {
2597 VUpdateVolume_r(ec, vp, 0);
2599 Log("VAttachVolume: Error updating volume %u\n", vp->hashid);
2603 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2604 #ifndef AFS_DEMAND_ATTACH_FS
2605 /* This is a hack: by temporarily setting the incore
2606 * dontSalvage flag ON, the volume will be put back on the
2607 * Update list (with dontSalvage OFF again). It will then
2608 * come back in N minutes with DONT_SALVAGE eventually
2609 * set. This is the way that volumes that have never had
2610 * it set get it set; or that volumes that have been
2611 * offline without DONT SALVAGE having been set also
2612 * eventually get it set */
2613 V_dontSalvage(vp) = DONT_SALVAGE;
2614 #endif /* !AFS_DEMAND_ATTACH_FS */
2615 VAddToVolumeUpdateList_r(ec, vp);
2617 Log("VAttachVolume: Error adding volume %u to update list\n", vp->hashid);
2624 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2628 VCancelReservation_r(nvp);
2631 if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2632 if (vp && !VIsErrorState(V_attachState(vp))) {
2633 VChangeState_r(vp, VOL_STATE_ERROR);
2642 * lock a volume on disk (non-blocking).
2644 * @param[in] vp The volume to lock
2645 * @param[in] locktype READ_LOCK or WRITE_LOCK
2647 * @return operation status
2648 * @retval 0 success, lock was obtained
2649 * @retval EBUSY a conflicting lock was held by another process
2650 * @retval EIO error acquiring lock
2652 * @pre If we're in the fileserver, vp is in an exclusive state
2654 * @pre vp is not already locked
2657 VLockVolumeNB(Volume *vp, int locktype)
2661 assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2662 assert(!(V_attachFlags(vp) & VOL_LOCKED));
2664 code = VLockVolumeByIdNB(vp->hashid, vp->partition, locktype);
2666 V_attachFlags(vp) |= VOL_LOCKED;
2673 * unlock a volume on disk that was locked with VLockVolumeNB.
2675 * @param[in] vp volume to unlock
2677 * @pre If we're in the fileserver, vp is in an exclusive state
2679 * @pre vp has already been locked
2682 VUnlockVolume(Volume *vp)
2684 assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2685 assert((V_attachFlags(vp) & VOL_LOCKED));
2687 VUnlockVolumeById(vp->hashid, vp->partition);
2689 V_attachFlags(vp) &= ~VOL_LOCKED;
2691 #endif /* AFS_DEMAND_ATTACH_FS */
2694 * read in a vol header, possibly lock the vol header, and possibly check out
2695 * the vol header from the fileserver, as part of volume attachment.
2697 * @param[out] ec error code
2698 * @param[in] vp volume pointer object
2699 * @param[in] partp disk partition object of the attaching partition
2700 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
2702 * @param[in] peek 1 to just try to read in the volume header and make sure
2703 * we don't try to lock the vol, or check it out from
2704 * FSSYNC or anything like that; 0 otherwise, for 'normal'
2707 * @note As part of DAFS volume attachment, the volume header may be either
2708 * read- or write-locked to ensure mutual exclusion of certain volume
2709 * operations. In some cases in order to determine whether we need to
2710 * read- or write-lock the header, we need to read in the header to see
2711 * if the volume is RW or not. So, if we read in the header under a
2712 * read-lock and determine that we actually need a write-lock on the
2713 * volume header, this function will drop the read lock, acquire a write
2714 * lock, and read the header in again.
2717 attach_volume_header(Error *ec, Volume *vp, struct DiskPartition64 *partp,
2720 struct VolumeDiskHeader diskHeader;
2721 struct VolumeHeader header;
2724 int lock_tries = 0, checkout_tries = 0;
2726 VolumeId volid = vp->hashid;
2727 #ifdef FSSYNC_BUILD_CLIENT
2728 int checkout, done_checkout = 0;
2729 #endif /* FSSYNC_BUILD_CLIENT */
2730 #ifdef AFS_DEMAND_ATTACH_FS
2731 int locktype = 0, use_locktype = -1;
2732 #endif /* AFS_DEMAND_ATTACH_FS */
2738 if (lock_tries > VOL_MAX_CHECKOUT_RETRIES) {
2739 Log("VAttachVolume: retried too many times trying to lock header for "
2740 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2741 VPartitionPath(partp));
2745 if (checkout_tries > VOL_MAX_CHECKOUT_RETRIES) {
2746 Log("VAttachVolume: retried too many times trying to checkout "
2747 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2748 VPartitionPath(partp));
2753 if (VReadVolumeDiskHeader(volid, partp, NULL)) {
2754 /* short-circuit the 'volume does not exist' case */
2759 #ifdef FSSYNC_BUILD_CLIENT
2760 checkout = !done_checkout;
2762 if (!peek && checkout && VMustCheckoutVolume(mode)) {
2764 memset(&res, 0, sizeof(res));
2766 if (FSYNC_VolOp(volid, VPartitionPath(partp), FSYNC_VOL_NEEDVOLUME, mode, &res)
2769 if (res.hdr.reason == FSYNC_SALVAGE) {
2770 Log("VAttachVolume: file server says volume %lu is salvaging\n",
2771 afs_printable_uint32_lu(volid));
2774 Log("VAttachVolume: attach of volume %lu apparently denied by file server\n",
2775 afs_printable_uint32_lu(volid));
2776 *ec = VNOVOL; /* XXXX */
2783 #ifdef AFS_DEMAND_ATTACH_FS
2784 if (use_locktype < 0) {
2785 /* don't know whether vol is RO or RW; assume it's RO and we can retry
2786 * if it turns out to be RW */
2787 locktype = VVolLockType(mode, 0);
2790 /* a previous try says we should use use_locktype to lock the volume,
2792 locktype = use_locktype;
2795 if (!peek && locktype) {
2796 code = VLockVolumeNB(vp, locktype);
2798 if (code == EBUSY) {
2799 Log("VAttachVolume: another program has vol %lu locked\n",
2800 afs_printable_uint32_lu(volid));
2802 Log("VAttachVolume: error %d trying to lock vol %lu\n",
2803 code, afs_printable_uint32_lu(volid));
2810 #endif /* AFS_DEMAND_ATTACH_FS */
2812 code = VReadVolumeDiskHeader(volid, partp, &diskHeader);
2822 DiskToVolumeHeader(&header, &diskHeader);
2824 IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header.parent,
2825 header.largeVnodeIndex);
2826 IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header.parent,
2827 header.smallVnodeIndex);
2828 IH_INIT(vp->diskDataHandle, partp->device, header.parent,
2830 IH_INIT(vp->linkHandle, partp->device, header.parent, header.linkTable);
2833 /* only need to do this once */
2835 GetVolumeHeader(vp);
2839 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2840 /* demand attach changes the V_PEEK mechanism
2842 * we can now suck the current disk data structure over
2843 * the fssync interface without going to disk
2845 * (technically, we don't need to restrict this feature
2846 * to demand attach fileservers. However, I'm trying
2847 * to limit the number of common code changes)
2849 if (VCanUseFSSYNC() && (mode == V_PEEK || peek)) {
2851 res.payload.len = sizeof(VolumeDiskData);
2852 res.payload.buf = &vp->header->diskstuff;
2854 if (FSYNC_VolOp(vp->hashid,
2856 FSYNC_VOL_QUERY_HDR,
2859 goto disk_header_loaded;
2862 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2863 (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2864 sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2866 #ifdef AFS_DEMAND_ATTACH_FS
2869 IncUInt64(&VStats.hdr_loads);
2870 IncUInt64(&vp->stats.hdr_loads);
2872 #endif /* AFS_DEMAND_ATTACH_FS */
2875 Log("VAttachVolume: Error reading diskDataHandle header for vol %lu; "
2876 "error=%u\n", afs_printable_uint32_lu(volid), *ec);
2880 #ifdef AFS_DEMAND_ATTACH_FS
2881 # ifdef FSSYNC_BUILD_CLIENT
2883 # endif /* FSSYNC_BUILD_CLIENT */
2885 /* if the lock type we actually used to lock the volume is different than
2886 * the lock type we should have used, retry with the lock type we should
2888 use_locktype = VVolLockType(mode, VolumeWriteable(vp));
2889 if (locktype != use_locktype) {
2893 #endif /* AFS_DEMAND_ATTACH_FS */
2898 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2899 if (!peek && *ec == 0 && retry == 0 && VMustCheckoutVolume(mode)) {
2901 code = FSYNC_VerifyCheckout(volid, VPartitionPath(partp), FSYNC_VOL_NEEDVOLUME, mode);
2903 if (code == SYNC_DENIED) {
2904 /* must retry checkout; fileserver no longer thinks we have
2910 } else if (code != SYNC_OK) {
2914 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2917 /* either we are going to be called again for a second pass, or we
2918 * encountered an error; clean up in either case */
2920 #ifdef AFS_DEMAND_ATTACH_FS
2921 if ((V_attachFlags(vp) & VOL_LOCKED)) {
2924 #endif /* AFS_DEMAND_ATTACH_FS */
2925 if (vp->linkHandle) {
2926 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
2927 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
2928 IH_RELEASE(vp->diskDataHandle);
2929 IH_RELEASE(vp->linkHandle);
2942 #ifdef AFS_DEMAND_ATTACH_FS
2944 attach_check_vop(Error *ec, VolumeId volid, struct DiskPartition64 *partp,
2949 if (vp->pending_vol_op) {
2953 if (vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningUnknown) {
2955 code = VVolOpLeaveOnlineNoHeader_r(vp, vp->pending_vol_op);
2957 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
2958 } else if (code == 0) {
2959 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
2962 /* we need the vol header to determine if the volume can be
2963 * left online for the vop, so... get the header */
2967 /* attach header with peek=1 to avoid checking out the volume
2968 * or locking it; we just want the header info, we're not
2969 * messing with the volume itself at all */
2970 attach_volume_header(ec, vp, partp, V_PEEK, 1);
2977 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
2978 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
2980 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
2983 /* make sure we grab a new vol header and re-open stuff on
2984 * actual attachment; we can't keep the data we grabbed, since
2985 * it was not done under a lock and thus not safe */
2986 FreeVolumeHeader(vp);
2987 VReleaseVolumeHandles_r(vp);
2990 /* see if the pending volume op requires exclusive access */
2991 switch (vp->pending_vol_op->vol_op_state) {
2992 case FSSYNC_VolOpPending:
2993 /* this should never happen */
2994 assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpPending);
2997 case FSSYNC_VolOpRunningUnknown:
2998 /* this should never happen; we resolved 'unknown' above */
2999 assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
3002 case FSSYNC_VolOpRunningOffline:
3003 /* mark the volume down */
3005 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3007 /* do not set V_offlineMessage here; we don't have ownership of
3008 * the volume (and probably do not have the header loaded), so we
3009 * can't alter the disk header */
3011 /* check to see if we should set the specialStatus flag */
3012 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
3013 vp->specialStatus = VBUSY;
3024 #endif /* AFS_DEMAND_ATTACH_FS */
3027 * volume attachment helper function.
3029 * @param[out] ec error code
3030 * @param[in] volumeId volume ID of the attaching volume
3031 * @param[in] path full path to the volume header .vol file
3032 * @param[in] partp disk partition object for the attaching partition
3033 * @param[in] vp volume object; vp->hashid, vp->device, vp->partition,
3034 * vp->vnode_list, and V_attachCV (for DAFS) should already
3036 * @param[in] isbusy 1 if vp->specialStatus should be set to VBUSY; that is,
3037 * if there is a volume operation running for this volume
3038 * that should set the volume to VBUSY during its run. 0
3039 * otherwise. (see VVolOpSetVBusy_r)
3040 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
3043 * @return pointer to the semi-attached volume pointer
3044 * @retval NULL an error occurred (check value of *ec)
3045 * @retval vp volume successfully attaching
3047 * @pre no locks held
3049 * @post VOL_LOCK held
3052 attach2(Error * ec, VolId volumeId, char *path, struct DiskPartition64 *partp,
3053 Volume * vp, int isbusy, int mode)
3055 /* have we read in the header successfully? */
3056 int read_header = 0;
3058 /* should we FreeVolume(vp) instead of VCheckFree(vp) in the error
3064 vp->vnodeIndex[vLarge].handle = NULL;
3065 vp->vnodeIndex[vSmall].handle = NULL;
3066 vp->diskDataHandle = NULL;
3067 vp->linkHandle = NULL;
3069 #ifdef AFS_DEMAND_ATTACH_FS
3070 attach_check_vop(ec, volumeId, partp, vp);
3072 attach_volume_header(ec, vp, partp, mode, 0);
3075 attach_volume_header(ec, vp, partp, mode, 0);
3076 #endif /* !AFS_DEMAND_ATTACH_FS */
3078 if (*ec == VNOVOL) {
3079 /* if the volume doesn't exist, skip straight to 'error' so we don't
3080 * request a salvage */
3087 vp->specialStatus = (byte) (isbusy ? VBUSY : 0);
3088 vp->shuttingDown = 0;
3089 vp->goingOffline = 0;
3091 #ifdef AFS_DEMAND_ATTACH_FS
3092 vp->stats.last_attach = FT_ApproxTime();
3093 vp->stats.attaches++;
3097 IncUInt64(&VStats.attaches);
3098 vp->cacheCheck = ++VolumeCacheCheck;
3099 /* just in case this ever rolls over */
3100 if (!vp->cacheCheck)
3101 vp->cacheCheck = ++VolumeCacheCheck;
3104 #ifdef AFS_DEMAND_ATTACH_FS
3105 V_attachFlags(vp) |= VOL_HDR_LOADED;
3106 vp->stats.last_hdr_load = vp->stats.last_attach;
3107 #endif /* AFS_DEMAND_ATTACH_FS */
3111 struct IndexFileHeader iHead;
3113 #if OPENAFS_VOL_STATS
3115 * We just read in the diskstuff part of the header. If the detailed
3116 * volume stats area has not yet been initialized, we should bzero the
3117 * area and mark it as initialized.
3119 if (!(V_stat_initialized(vp))) {
3120 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
3121 V_stat_initialized(vp) = 1;
3123 #endif /* OPENAFS_VOL_STATS */
3125 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
3126 (char *)&iHead, sizeof(iHead),
3127 SMALLINDEXMAGIC, SMALLINDEXVERSION);
3130 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
3135 struct IndexFileHeader iHead;
3137 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
3138 (char *)&iHead, sizeof(iHead),
3139 LARGEINDEXMAGIC, LARGEINDEXVERSION);
3142 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
3146 #ifdef AFS_NAMEI_ENV
3148 struct versionStamp stamp;
3150 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
3151 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
3154 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
3157 #endif /* AFS_NAMEI_ENV */
3159 #if defined(AFS_DEMAND_ATTACH_FS)
3160 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
3162 if (!VCanScheduleSalvage()) {
3163 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3165 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3170 /* volume operation in progress */
3174 #else /* AFS_DEMAND_ATTACH_FS */
3176 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3180 #endif /* AFS_DEMAND_ATTACH_FS */
3182 if (V_needsSalvaged(vp)) {
3183 if (vp->specialStatus)
3184 vp->specialStatus = 0;
3186 #if defined(AFS_DEMAND_ATTACH_FS)
3187 if (!VCanScheduleSalvage()) {
3188 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
3190 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
3193 #else /* AFS_DEMAND_ATTACH_FS */
3195 #endif /* AFS_DEMAND_ATTACH_FS */
3201 vp->nextVnodeUnique = V_uniquifier(vp);
3203 #ifndef FAST_RESTART
3204 if (VShouldCheckInUse(mode) && V_inUse(vp) && VolumeWriteable(vp)) {
3205 if (!V_needsSalvaged(vp)) {
3206 V_needsSalvaged(vp) = 1;
3207 VUpdateVolume_r(ec, vp, 0);
3209 #if defined(AFS_DEMAND_ATTACH_FS)
3210 if (!VCanScheduleSalvage()) {
3211 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3213 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
3216 #else /* AFS_DEMAND_ATTACH_FS */
3217 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3219 #endif /* AFS_DEMAND_ATTACH_FS */
3223 #endif /* FAST_RESTART */
3225 if (programType == fileServer && V_destroyMe(vp) == DESTROY_ME) {
3226 /* Only check destroyMe if we are the fileserver, since the
3227 * volserver et al sometimes need to work with volumes with
3228 * destroyMe set. Examples are 'temporary' volumes the
3229 * volserver creates, and when we create a volume (destroyMe
3230 * is set on creation; sometimes a separate volserver
3231 * transaction is created to clear destroyMe).
3234 #if defined(AFS_DEMAND_ATTACH_FS)
3235 /* schedule a salvage so the volume goes away on disk */
3236 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3237 VChangeState_r(vp, VOL_STATE_ERROR);
3239 #endif /* AFS_DEMAND_ATTACH_FS */
3240 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
3246 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
3247 #ifndef BITMAP_LATER
3248 if (programType == fileServer && VolumeWriteable(vp)) {
3250 for (i = 0; i < nVNODECLASSES; i++) {
3251 VGetBitmap_r(ec, vp, i);
3253 #ifdef AFS_DEMAND_ATTACH_FS
3254 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3256 #endif /* AFS_DEMAND_ATTACH_FS */
3257 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
3263 #endif /* BITMAP_LATER */
3265 if (VInit >= 2 && V_needsCallback(vp)) {
3266 if (V_BreakVolumeCallbacks) {
3267 Log("VAttachVolume: Volume %lu was changed externally; breaking callbacks\n",
3268 afs_printable_uint32_lu(V_id(vp)));
3269 V_needsCallback(vp) = 0;
3271 (*V_BreakVolumeCallbacks) (V_id(vp));
3274 VUpdateVolume_r(ec, vp, 0);
3276 #ifdef FSSYNC_BUILD_CLIENT
3277 else if (VCanUseFSSYNC()) {
3278 afs_int32 fsync_code;
3280 V_needsCallback(vp) = 0;
3282 fsync_code = FSYNC_VolOp(V_id(vp), NULL, FSYNC_VOL_BREAKCBKS, FSYNC_WHATEVER, NULL);
3286 V_needsCallback(vp) = 1;
3287 Log("Error trying to tell the fileserver to break callbacks for "
3288 "changed volume %lu; error code %ld\n",
3289 afs_printable_uint32_lu(V_id(vp)),
3290 afs_printable_int32_ld(fsync_code));
3292 VUpdateVolume_r(ec, vp, 0);
3295 #endif /* FSSYNC_BUILD_CLIENT */
3298 Log("VAttachVolume: error %d clearing needsCallback on volume "
3299 "%lu; needs salvage\n", (int)*ec,
3300 afs_printable_uint32_lu(V_id(vp)));
3301 #ifdef AFS_DEMAND_ATTACH_FS
3302 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3304 #else /* !AFS_DEMAND_ATTACH_FS */
3306 #endif /* !AFS_DEMAND_ATTACh_FS */
3311 if (programType == fileServer) {
3312 if (vp->specialStatus)
3313 vp->specialStatus = 0;
3314 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
3315 V_inUse(vp) = fileServer;
3316 V_offlineMessage(vp)[0] = '\0';
3319 #ifdef AFS_DEMAND_ATTACH_FS
3320 if ((mode != V_PEEK) && (mode != V_SECRETLY))
3321 V_inUse(vp) = programType;
3322 #endif /* AFS_DEMAND_ATTACH_FS */
3323 V_checkoutMode(vp) = mode;
3326 AddVolumeToHashTable(vp, V_id(vp));
3327 #ifdef AFS_DEMAND_ATTACH_FS
3328 if (VCanUnlockAttached() && (V_attachFlags(vp) & VOL_LOCKED)) {
3331 if ((programType != fileServer) ||
3332 (V_inUse(vp) == fileServer)) {
3333 AddVolumeToVByPList_r(vp);
3335 VChangeState_r(vp, VOL_STATE_ATTACHED);
3337 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3344 #ifdef AFS_DEMAND_ATTACH_FS
3345 if (!VIsErrorState(V_attachState(vp))) {
3346 VChangeState_r(vp, VOL_STATE_ERROR);
3348 #endif /* AFS_DEMAND_ATTACH_FS */
3351 VReleaseVolumeHandles_r(vp);
3354 #ifdef AFS_DEMAND_ATTACH_FS
3361 #else /* !AFS_DEMAND_ATTACH_FS */
3363 #endif /* !AFS_DEMAND_ATTACH_FS */
3367 /* Attach an existing volume.
3368 The volume also normally goes online at this time.
3369 An offline volume must be reattached to make it go online.
3373 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
3377 retVal = VAttachVolume_r(ec, volumeId, mode);
3383 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
3386 VGetVolumePath(ec, volumeId, &part, &name);
3388 register Volume *vp;
3390 vp = VGetVolume_r(&error, volumeId);
3392 assert(V_inUse(vp) == 0);
3393 VDetachVolume_r(ec, vp);
3397 return VAttachVolumeByName_r(ec, part, name, mode);
3400 /* Increment a reference count to a volume, sans context swaps. Requires
3401 * possibly reading the volume header in from the disk, since there's
3402 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
3404 * N.B. This call can fail if we can't read in the header!! In this case
3405 * we still guarantee we won't context swap, but the ref count won't be
3406 * incremented (otherwise we'd violate the invariant).
3408 /* NOTE: with the demand attach fileserver extensions, the global lock
3409 * is dropped within VHold */
3410 #ifdef AFS_DEMAND_ATTACH_FS
3412 VHold_r(register Volume * vp)
3416 VCreateReservation_r(vp);
3417 VWaitExclusiveState_r(vp);
3419 LoadVolumeHeader(&error, vp);
3421 VCancelReservation_r(vp);
3425 VCancelReservation_r(vp);
3428 #else /* AFS_DEMAND_ATTACH_FS */
3430 VHold_r(register Volume * vp)
3434 LoadVolumeHeader(&error, vp);
3440 #endif /* AFS_DEMAND_ATTACH_FS */
3444 VHold(register Volume * vp)
3448 retVal = VHold_r(vp);
3455 /***************************************************/
3456 /* get and put volume routines */
3457 /***************************************************/
3460 * put back a heavyweight reference to a volume object.
3462 * @param[in] vp volume object pointer
3464 * @pre VOL_LOCK held
3466 * @post heavyweight volume reference put back.
3467 * depending on state, volume may have been taken offline,
3468 * detached, salvaged, freed, etc.
3470 * @internal volume package internal use only
3473 VPutVolume_r(register Volume * vp)
3475 assert(--vp->nUsers >= 0);
3476 if (vp->nUsers == 0) {
3478 ReleaseVolumeHeader(vp->header);
3479 #ifdef AFS_DEMAND_ATTACH_FS
3480 if (!VCheckDetach(vp)) {
3484 #else /* AFS_DEMAND_ATTACH_FS */
3486 #endif /* AFS_DEMAND_ATTACH_FS */
3491 VPutVolume(register Volume * vp)
3499 /* Get a pointer to an attached volume. The pointer is returned regardless
3500 of whether or not the volume is in service or on/off line. An error
3501 code, however, is returned with an indication of the volume's status */
3503 VGetVolume(Error * ec, Error * client_ec, VolId volumeId)
3507 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
3512 /* same as VGetVolume, but if a volume is waiting to go offline, we return
3513 * that it is actually offline, instead of waiting for it to go offline */
3515 VGetVolumeNoWait(Error * ec, Error * client_ec, VolId volumeId)
3519 retVal = GetVolume(ec, client_ec, volumeId, NULL, 1);
3525 VGetVolume_r(Error * ec, VolId volumeId)
3527 return GetVolume(ec, NULL, volumeId, NULL, 0);
3530 /* try to get a volume we've previously looked up */
3531 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
3533 VGetVolumeByVp_r(Error * ec, Volume * vp)
3535 return GetVolume(ec, NULL, vp->hashid, vp, 0);
3539 * private interface for getting a volume handle
3541 * @param[out] ec error code (0 if no error)
3542 * @param[out] client_ec wire error code to be given to clients
3543 * @param[in] volumeId ID of the volume we want
3544 * @param[in] hint optional hint for hash lookups, or NULL
3545 * @param[in] nowait 0 to wait for a 'goingOffline' volume to go offline
3546 * before returning, 1 to return immediately
3548 * @return a volume handle for the specified volume
3549 * @retval NULL an error occurred, or the volume is in such a state that
3550 * we cannot load a header or return any volume struct
3552 * @note for DAFS, caller must NOT hold a ref count on 'hint'
3555 GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint, int nowait)
3558 /* pull this profiling/debugging code out of regular builds */
3560 #define VGET_CTR_INC(x) x++
3561 unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
3562 0, V7 = 0, V8 = 0, V9 = 0;
3563 unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
3565 #define VGET_CTR_INC(x)
3567 #ifdef AFS_DEMAND_ATTACH_FS
3568 Volume *avp, * rvp = hint;
3572 * if VInit is zero, the volume package dynamic
3573 * data structures have not been initialized yet,
3574 * and we must immediately return an error
3580 *client_ec = VOFFLINE;
3585 #ifdef AFS_DEMAND_ATTACH_FS
3587 VCreateReservation_r(rvp);
3589 #endif /* AFS_DEMAND_ATTACH_FS */
3597 vp = VLookupVolume_r(ec, volumeId, vp);
3603 #ifdef AFS_DEMAND_ATTACH_FS
3604 if (rvp && (rvp != vp)) {
3605 /* break reservation on old vp */
3606 VCancelReservation_r(rvp);
3609 #endif /* AFS_DEMAND_ATTACH_FS */
3615 /* Until we have reached an initialization level of 2
3616 * we don't know whether this volume exists or not.
3617 * We can't sleep and retry later because before a volume
3618 * is attached, the caller tries to get it first. Just
3619 * return VOFFLINE and the caller can choose whether to
3620 * retry the command or not. */
3630 IncUInt64(&VStats.hdr_gets);
3632 #ifdef AFS_DEMAND_ATTACH_FS
3633 /* block if someone else is performing an exclusive op on this volume */
3636 VCreateReservation_r(rvp);
3638 VWaitExclusiveState_r(vp);
3640 /* short circuit with VNOVOL in the following circumstances:
3643 * - VOL_STATE_SHUTTING_DOWN
3645 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
3646 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN) ||
3647 (V_attachState(vp) == VOL_STATE_GOING_OFFLINE)) {
3654 * short circuit with VOFFLINE in the following circumstances:
3656 * - VOL_STATE_UNATTACHED
3658 if (V_attachState(vp) == VOL_STATE_UNATTACHED) {
3659 if (vp->specialStatus) {
3660 *ec = vp->specialStatus;
3668 /* allowable states:
3674 if (vp->salvage.requested) {
3675 VUpdateSalvagePriority_r(vp);
3678 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
3679 avp = VAttachVolumeByVp_r(ec, vp, 0);
3682 /* VAttachVolumeByVp_r can return a pointer
3683 * != the vp passed to it under certain
3684 * conditions; make sure we don't leak
3685 * reservations if that happens */
3687 VCancelReservation_r(rvp);
3689 VCreateReservation_r(rvp);
3699 if (!vp->pending_vol_op) {
3714 if ((V_attachState(vp) == VOL_STATE_SALVAGING) ||
3715 (*ec == VSALVAGING)) {
3717 /* see CheckVnode() in afsfileprocs.c for an explanation
3718 * of this error code logic */
3719 afs_uint32 now = FT_ApproxTime();
3720 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
3723 *client_ec = VRESTARTING;
3732 #ifdef AFS_DEMAND_ATTACH_FS
3734 * this test MUST happen after VAttachVolymeByVp, so vol_op_state is
3735 * not VolOpRunningUnknown (attach2 would have converted it to Online
3739 /* only valid before/during demand attachment */
3740 assert(!vp->pending_vol_op || vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
3742 /* deny getvolume due to running mutually exclusive vol op */
3743 if (vp->pending_vol_op && vp->pending_vol_op->vol_op_state==FSSYNC_VolOpRunningOffline) {
3745 * volume cannot remain online during this volume operation.
3748 if (vp->specialStatus) {
3750 * special status codes outrank normal VOFFLINE code
3752 *ec = vp->specialStatus;
3754 *client_ec = vp->specialStatus;
3758 /* see CheckVnode() in afsfileprocs.c for an explanation
3759 * of this error code logic */
3760 afs_uint32 now = FT_ApproxTime();
3761 if ((vp->stats.last_vol_op + (10 * 60)) >= now) {
3764 *client_ec = VRESTARTING;
3769 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3770 FreeVolumeHeader(vp);
3774 #endif /* AFS_DEMAND_ATTACH_FS */
3776 LoadVolumeHeader(ec, vp);
3779 /* Only log the error if it was a totally unexpected error. Simply
3780 * a missing inode is likely to be caused by the volume being deleted */
3781 if (errno != ENXIO || LogLevel)
3782 Log("Volume %u: couldn't reread volume header\n",
3784 #ifdef AFS_DEMAND_ATTACH_FS
3785 if (VCanScheduleSalvage()) {
3786 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3791 #else /* AFS_DEMAND_ATTACH_FS */
3794 #endif /* AFS_DEMAND_ATTACH_FS */
3799 if (vp->shuttingDown) {
3806 if (programType == fileServer) {
3808 if (vp->goingOffline && !nowait) {
3810 #ifdef AFS_DEMAND_ATTACH_FS
3811 /* wait for the volume to go offline */
3812 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
3813 VWaitStateChange_r(vp);
3815 #elif defined(AFS_PTHREAD_ENV)
3816 VOL_CV_WAIT(&vol_put_volume_cond);
3817 #else /* AFS_PTHREAD_ENV */
3818 LWP_WaitProcess(VPutVolume);
3819 #endif /* AFS_PTHREAD_ENV */
3822 if (vp->specialStatus) {
3824 *ec = vp->specialStatus;
3825 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3828 } else if (V_inUse(vp) == 0 || vp->goingOffline) {
3839 #ifdef AFS_DEMAND_ATTACH_FS
3840 /* if no error, bump nUsers */
3843 VLRU_UpdateAccess_r(vp);
3846 VCancelReservation_r(rvp);
3849 if (client_ec && !*client_ec) {
3852 #else /* AFS_DEMAND_ATTACH_FS */
3853 /* if no error, bump nUsers */
3860 #endif /* AFS_DEMAND_ATTACH_FS */
3868 /***************************************************/
3869 /* Volume offline/detach routines */
3870 /***************************************************/
3872 /* caller MUST hold a heavyweight ref on vp */
3873 #ifdef AFS_DEMAND_ATTACH_FS
3875 VTakeOffline_r(register Volume * vp)
3879 assert(vp->nUsers > 0);
3880 assert(programType == fileServer);
3882 VCreateReservation_r(vp);
3883 VWaitExclusiveState_r(vp);
3885 vp->goingOffline = 1;
3886 V_needsSalvaged(vp) = 1;
3888 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
3889 VCancelReservation_r(vp);
3891 #else /* AFS_DEMAND_ATTACH_FS */
3893 VTakeOffline_r(register Volume * vp)
3895 assert(vp->nUsers > 0);
3896 assert(programType == fileServer);
3898 vp->goingOffline = 1;
3899 V_needsSalvaged(vp) = 1;
3901 #endif /* AFS_DEMAND_ATTACH_FS */
3904 VTakeOffline(register Volume * vp)
3912 * force a volume offline.
3914 * @param[in] vp volume object pointer
3915 * @param[in] flags flags (see note below)
3917 * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
3918 * used when VUpdateVolume_r needs to call VForceOffline_r
3919 * (which in turn would normally call VUpdateVolume_r)
3921 * @see VUpdateVolume_r
3923 * @pre VOL_LOCK must be held.
3924 * for DAFS, caller must hold ref.
3926 * @note for DAFS, it _is safe_ to call this function from an
3929 * @post needsSalvaged flag is set.
3930 * for DAFS, salvage is requested.
3931 * no further references to the volume through the volume
3932 * package will be honored.
3933 * all file descriptor and vnode caches are invalidated.
3935 * @warning this is a heavy-handed interface. it results in
3936 * a volume going offline regardless of the current
3937 * reference count state.
3939 * @internal volume package internal use only
3942 VForceOffline_r(Volume * vp, int flags)
3946 #ifdef AFS_DEMAND_ATTACH_FS
3947 VChangeState_r(vp, VOL_STATE_ERROR);
3952 strcpy(V_offlineMessage(vp),
3953 "Forced offline due to internal error: volume needs to be salvaged");
3954 Log("Volume %u forced offline: it needs salvaging!\n", V_id(vp));
3957 vp->goingOffline = 0;
3958 V_needsSalvaged(vp) = 1;
3959 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
3960 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
3963 #ifdef AFS_DEMAND_ATTACH_FS
3964 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3965 #endif /* AFS_DEMAND_ATTACH_FS */
3967 #ifdef AFS_PTHREAD_ENV
3968 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3969 #else /* AFS_PTHREAD_ENV */
3970 LWP_NoYieldSignal(VPutVolume);
3971 #endif /* AFS_PTHREAD_ENV */
3973 VReleaseVolumeHandles_r(vp);
3977 * force a volume offline.
3979 * @param[in] vp volume object pointer
3981 * @see VForceOffline_r
3984 VForceOffline(Volume * vp)
3987 VForceOffline_r(vp, 0);
3991 /* The opposite of VAttachVolume. The volume header is written to disk, with
3992 the inUse bit turned off. A copy of the header is maintained in memory,
3993 however (which is why this is VOffline, not VDetach).
3996 VOffline_r(Volume * vp, char *message)
3998 #ifndef AFS_DEMAND_ATTACH_FS
4000 VolumeId vid = V_id(vp);
4003 assert(programType != volumeUtility && programType != volumeServer);
4008 if (V_offlineMessage(vp)[0] == '\0')
4009 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4010 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4012 vp->goingOffline = 1;
4013 #ifdef AFS_DEMAND_ATTACH_FS
4014 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4015 VCreateReservation_r(vp);
4018 /* wait for the volume to go offline */
4019 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
4020 VWaitStateChange_r(vp);
4022 VCancelReservation_r(vp);
4023 #else /* AFS_DEMAND_ATTACH_FS */
4025 vp = VGetVolume_r(&error, vid); /* Wait for it to go offline */
4026 if (vp) /* In case it was reattached... */
4028 #endif /* AFS_DEMAND_ATTACH_FS */
4031 #ifdef AFS_DEMAND_ATTACH_FS
4033 * Take a volume offline in order to perform a volume operation.
4035 * @param[inout] ec address in which to store error code
4036 * @param[in] vp volume object pointer
4037 * @param[in] message volume offline status message
4040 * - VOL_LOCK is held
4041 * - caller MUST hold a heavyweight ref on vp
4044 * - volume is taken offline
4045 * - if possible, volume operation is promoted to running state
4046 * - on failure, *ec is set to nonzero
4048 * @note Although this function does not return any value, it may
4049 * still fail to promote our pending volume operation to
4050 * a running state. Any caller MUST check the value of *ec,
4051 * and MUST NOT blindly assume success.
4053 * @warning if the caller does not hold a lightweight ref on vp,
4054 * then it MUST NOT reference vp after this function
4055 * returns to the caller.
4057 * @internal volume package internal use only
4060 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
4062 assert(vp->pending_vol_op);
4068 if (V_offlineMessage(vp)[0] == '\0')
4069 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4070 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4072 vp->goingOffline = 1;
4073 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4074 VCreateReservation_r(vp);
4077 /* Wait for the volume to go offline */
4078 while (!VIsOfflineState(V_attachState(vp))) {
4079 /* do not give corrupted volumes to the volserver */
4080 if (vp->salvage.requested && vp->pending_vol_op->com.programType != salvageServer) {
4084 VWaitStateChange_r(vp);
4088 VCancelReservation_r(vp);
4090 #endif /* AFS_DEMAND_ATTACH_FS */
4093 VOffline(Volume * vp, char *message)
4096 VOffline_r(vp, message);
4100 /* This gets used for the most part by utility routines that don't want
4101 * to keep all the volume headers around. Generally, the file server won't
4102 * call this routine, because then the offline message in the volume header
4103 * (or other information) won't be available to clients. For NAMEI, also
4104 * close the file handles. However, the fileserver does call this during
4105 * an attach following a volume operation.
4108 VDetachVolume_r(Error * ec, Volume * vp)
4111 struct DiskPartition64 *tpartp;
4112 int notifyServer = 0;
4113 int useDone = FSYNC_VOL_ON;
4115 *ec = 0; /* always "succeeds" */
4116 if (VCanUseFSSYNC()) {
4117 notifyServer = vp->needsPutBack;
4118 if (V_destroyMe(vp) == DESTROY_ME)
4119 useDone = FSYNC_VOL_DONE;
4120 #ifdef AFS_DEMAND_ATTACH_FS
4121 else if (!V_blessed(vp) || !V_inService(vp))
4122 useDone = FSYNC_VOL_LEAVE_OFF;
4125 tpartp = vp->partition;
4127 DeleteVolumeFromHashTable(vp);
4128 vp->shuttingDown = 1;
4129 #ifdef AFS_DEMAND_ATTACH_FS
4130 DeleteVolumeFromVByPList_r(vp);
4132 VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
4134 if (programType != fileServer)
4136 #endif /* AFS_DEMAND_ATTACH_FS */
4138 /* Will be detached sometime in the future--this is OK since volume is offline */
4140 /* XXX the following code should really be moved to VCheckDetach() since the volume
4141 * is not technically detached until the refcounts reach zero
4143 #ifdef FSSYNC_BUILD_CLIENT
4144 if (VCanUseFSSYNC() && notifyServer) {
4146 * Note: The server is not notified in the case of a bogus volume
4147 * explicitly to make it possible to create a volume, do a partial
4148 * restore, then abort the operation without ever putting the volume
4149 * online. This is essential in the case of a volume move operation
4150 * between two partitions on the same server. In that case, there
4151 * would be two instances of the same volume, one of them bogus,
4152 * which the file server would attempt to put on line
4154 FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
4155 /* XXX this code path is only hit by volume utilities, thus
4156 * V_BreakVolumeCallbacks will always be NULL. if we really
4157 * want to break callbacks in this path we need to use FSYNC_VolOp() */
4159 /* Dettaching it so break all callbacks on it */
4160 if (V_BreakVolumeCallbacks) {
4161 Log("volume %u detached; breaking all call backs\n", volume);
4162 (*V_BreakVolumeCallbacks) (volume);
4166 #endif /* FSSYNC_BUILD_CLIENT */
4170 VDetachVolume(Error * ec, Volume * vp)
4173 VDetachVolume_r(ec, vp);
4178 /***************************************************/
4179 /* Volume fd/inode handle closing routines */
4180 /***************************************************/
4182 /* For VDetachVolume, we close all cached file descriptors, but keep
4183 * the Inode handles in case we need to read from a busy volume.
4185 /* for demand attach, caller MUST hold ref count on vp */
4187 VCloseVolumeHandles_r(Volume * vp)
4189 #ifdef AFS_DEMAND_ATTACH_FS
4190 VolState state_save;
4192 state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
4197 * XXX need to investigate whether we can perform
4198 * DFlushVolume outside of vol_glock_mutex...
4200 * VCloseVnodeFiles_r drops the glock internally */
4201 DFlushVolume(vp->hashid);
4202 VCloseVnodeFiles_r(vp);
4204 #ifdef AFS_DEMAND_ATTACH_FS
4208 /* Too time consuming and unnecessary for the volserver */
4209 if (programType == fileServer) {
4210 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4211 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4212 IH_CONDSYNC(vp->diskDataHandle);
4214 IH_CONDSYNC(vp->linkHandle);
4215 #endif /* AFS_NT40_ENV */
4218 IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
4219 IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
4220 IH_REALLYCLOSE(vp->diskDataHandle);
4221 IH_REALLYCLOSE(vp->linkHandle);
4223 #ifdef AFS_DEMAND_ATTACH_FS
4224 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4229 VChangeState_r(vp, state_save);
4233 /* For both VForceOffline and VOffline, we close all relevant handles.
4234 * For VOffline, if we re-attach the volume, the files may possible be
4235 * different than before.
4237 /* for demand attach, caller MUST hold a ref count on vp */
4239 VReleaseVolumeHandles_r(Volume * vp)
4241 #ifdef AFS_DEMAND_ATTACH_FS
4242 VolState state_save;
4244 state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
4247 /* XXX need to investigate whether we can perform
4248 * DFlushVolume outside of vol_glock_mutex... */
4249 DFlushVolume(vp->hashid);
4251 VReleaseVnodeFiles_r(vp); /* releases the glock internally */
4253 #ifdef AFS_DEMAND_ATTACH_FS
4257 /* Too time consuming and unnecessary for the volserver */
4258 if (programType == fileServer) {
4259 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4260 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4261 IH_CONDSYNC(vp->diskDataHandle);
4263 IH_CONDSYNC(vp->linkHandle);
4264 #endif /* AFS_NT40_ENV */
4267 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
4268 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
4269 IH_RELEASE(vp->diskDataHandle);
4270 IH_RELEASE(vp->linkHandle);
4272 #ifdef AFS_DEMAND_ATTACH_FS
4273 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4278 VChangeState_r(vp, state_save);
4283 /***************************************************/
4284 /* Volume write and fsync routines */
4285 /***************************************************/
4288 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
4290 #ifdef AFS_DEMAND_ATTACH_FS
4291 VolState state_save;
4293 if (flags & VOL_UPDATE_WAIT) {
4294 VCreateReservation_r(vp);
4295 VWaitExclusiveState_r(vp);
4300 if (programType == fileServer)
4302 (V_inUse(vp) ? V_nextVnodeUnique(vp) +
4303 200 : V_nextVnodeUnique(vp));
4305 #ifdef AFS_DEMAND_ATTACH_FS
4306 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4310 WriteVolumeHeader_r(ec, vp);
4312 #ifdef AFS_DEMAND_ATTACH_FS
4314 VChangeState_r(vp, state_save);
4315 if (flags & VOL_UPDATE_WAIT) {
4316 VCancelReservation_r(vp);
4321 Log("VUpdateVolume: error updating volume header, volume %u (%s)\n",
4322 V_id(vp), V_name(vp));
4323 /* try to update on-disk header,
4324 * while preventing infinite recursion */
4325 if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
4326 VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
4332 VUpdateVolume(Error * ec, Volume * vp)
4335 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4340 VSyncVolume_r(Error * ec, Volume * vp, int flags)
4344 #ifdef AFS_DEMAND_ATTACH_FS
4345 VolState state_save;
4348 if (flags & VOL_SYNC_WAIT) {
4349 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4351 VUpdateVolume_r(ec, vp, 0);
4354 #ifdef AFS_DEMAND_ATTACH_FS
4355 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4358 fdP = IH_OPEN(V_diskDataHandle(vp));
4359 assert(fdP != NULL);
4360 code = FDH_SYNC(fdP);
4363 #ifdef AFS_DEMAND_ATTACH_FS
4365 VChangeState_r(vp, state_save);
4371 VSyncVolume(Error * ec, Volume * vp)
4374 VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
4379 /***************************************************/
4380 /* Volume dealloaction routines */
4381 /***************************************************/
4383 #ifdef AFS_DEMAND_ATTACH_FS
4385 FreeVolume(Volume * vp)
4387 /* free the heap space, iff it's safe.
4388 * otherwise, pull it out of the hash table, so it
4389 * will get deallocated when all refs to it go away */
4390 if (!VCheckFree(vp)) {
4391 DeleteVolumeFromHashTable(vp);
4392 DeleteVolumeFromVByPList_r(vp);
4394 /* make sure we invalidate the header cache entry */
4395 FreeVolumeHeader(vp);
4398 #endif /* AFS_DEMAND_ATTACH_FS */
4401 ReallyFreeVolume(Volume * vp)
4406 #ifdef AFS_DEMAND_ATTACH_FS
4408 VChangeState_r(vp, VOL_STATE_FREED);
4409 if (vp->pending_vol_op)
4410 free(vp->pending_vol_op);
4411 #endif /* AFS_DEMAND_ATTACH_FS */
4412 for (i = 0; i < nVNODECLASSES; i++)
4413 if (vp->vnodeIndex[i].bitmap)
4414 free(vp->vnodeIndex[i].bitmap);
4415 FreeVolumeHeader(vp);
4416 #ifndef AFS_DEMAND_ATTACH_FS
4417 DeleteVolumeFromHashTable(vp);
4418 #endif /* AFS_DEMAND_ATTACH_FS */
4422 /* check to see if we should shutdown this volume
4423 * returns 1 if volume was freed, 0 otherwise */
4424 #ifdef AFS_DEMAND_ATTACH_FS
4426 VCheckDetach(register Volume * vp)
4431 if (vp->nUsers || vp->nWaiters)
4434 if (vp->shuttingDown) {
4436 if ((programType != fileServer) &&
4437 (V_inUse(vp) == programType) &&
4438 ((V_checkoutMode(vp) == V_VOLUPD) ||
4439 (V_checkoutMode(vp) == V_SECRETLY) ||
4440 ((V_checkoutMode(vp) == V_CLONE) &&
4441 (VolumeWriteable(vp))))) {
4443 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
4445 Log("VCheckDetach: volume header update for volume %u "
4446 "failed with errno %d\n", vp->hashid, errno);
4449 VReleaseVolumeHandles_r(vp);
4451 ReallyFreeVolume(vp);
4452 if (programType == fileServer) {
4453 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
4458 #else /* AFS_DEMAND_ATTACH_FS */
4460 VCheckDetach(register Volume * vp)
4468 if (vp->shuttingDown) {
4470 if ((programType != fileServer) &&
4471 (V_inUse(vp) == programType) &&
4472 ((V_checkoutMode(vp) == V_VOLUPD) ||
4473 (V_checkoutMode(vp) == V_SECRETLY) ||
4474 ((V_checkoutMode(vp) == V_CLONE) &&
4475 (VolumeWriteable(vp))))) {
4477 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
4479 Log("VCheckDetach: volume header update for volume %u failed with errno %d\n",
4483 VReleaseVolumeHandles_r(vp);
4484 ReallyFreeVolume(vp);
4485 if (programType == fileServer) {
4486 #if defined(AFS_PTHREAD_ENV)
4487 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
4488 #else /* AFS_PTHREAD_ENV */
4489 LWP_NoYieldSignal(VPutVolume);
4490 #endif /* AFS_PTHREAD_ENV */
4495 #endif /* AFS_DEMAND_ATTACH_FS */
4497 /* check to see if we should offline this volume
4498 * return 1 if volume went offline, 0 otherwise */
4499 #ifdef AFS_DEMAND_ATTACH_FS
4501 VCheckOffline(register Volume * vp)
4505 if (vp->goingOffline && !vp->nUsers) {
4507 assert(programType == fileServer);
4508 assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
4509 (V_attachState(vp) != VOL_STATE_FREED) &&
4510 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
4511 (V_attachState(vp) != VOL_STATE_UNATTACHED));
4515 * VOL_STATE_GOING_OFFLINE
4516 * VOL_STATE_SHUTTING_DOWN
4517 * VIsErrorState(V_attachState(vp))
4518 * VIsExclusiveState(V_attachState(vp))
4521 VCreateReservation_r(vp);
4522 VChangeState_r(vp, VOL_STATE_OFFLINING);
4525 /* must clear the goingOffline flag before we drop the glock */
4526 vp->goingOffline = 0;
4531 /* perform async operations */
4532 VUpdateVolume_r(&error, vp, 0);
4533 VCloseVolumeHandles_r(vp);
4536 if (V_offlineMessage(vp)[0]) {
4537 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
4538 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
4539 V_offlineMessage(vp));
4541 Log("VOffline: Volume %lu (%s) is now offline\n",
4542 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
4546 /* invalidate the volume header cache entry */
4547 FreeVolumeHeader(vp);
4549 /* if nothing changed state to error or salvaging,
4550 * drop state to unattached */
4551 if (!VIsErrorState(V_attachState(vp))) {
4552 VChangeState_r(vp, VOL_STATE_UNATTACHED);
4554 VCancelReservation_r(vp);
4555 /* no usage of vp is safe beyond this point */
4559 #else /* AFS_DEMAND_ATTACH_FS */
4561 VCheckOffline(register Volume * vp)
4565 if (vp->goingOffline && !vp->nUsers) {
4567 assert(programType == fileServer);
4570 vp->goingOffline = 0;
4572 VUpdateVolume_r(&error, vp, 0);
4573 VCloseVolumeHandles_r(vp);
4575 Log("VOffline: Volume %u (%s) is now offline", V_id(vp),
4577 if (V_offlineMessage(vp)[0])
4578 Log(" (%s)", V_offlineMessage(vp));
4581 FreeVolumeHeader(vp);
4582 #ifdef AFS_PTHREAD_ENV
4583 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
4584 #else /* AFS_PTHREAD_ENV */
4585 LWP_NoYieldSignal(VPutVolume);
4586 #endif /* AFS_PTHREAD_ENV */
4590 #endif /* AFS_DEMAND_ATTACH_FS */
4592 /***************************************************/
4593 /* demand attach fs ref counting routines */
4594 /***************************************************/
4596 #ifdef AFS_DEMAND_ATTACH_FS
4597 /* the following two functions handle reference counting for
4598 * asynchronous operations on volume structs.
4600 * their purpose is to prevent a VDetachVolume or VShutdown
4601 * from free()ing the Volume struct during an async i/o op */
4603 /* register with the async volume op ref counter */
4604 /* VCreateReservation_r moved into inline code header because it
4605 * is now needed in vnode.c -- tkeiser 11/20/2007
4609 * decrement volume-package internal refcount.
4611 * @param vp volume object pointer
4613 * @internal volume package internal use only
4616 * @arg VOL_LOCK is held
4617 * @arg lightweight refcount held
4619 * @post volume waiters refcount is decremented; volume may
4620 * have been deallocated/shutdown/offlined/salvaged/
4621 * whatever during the process
4623 * @warning once you have tossed your last reference (you can acquire
4624 * lightweight refs recursively) it is NOT SAFE to reference
4625 * a volume object pointer ever again
4627 * @see VCreateReservation_r
4629 * @note DEMAND_ATTACH_FS only
4632 VCancelReservation_r(Volume * vp)
4634 assert(--vp->nWaiters >= 0);
4635 if (vp->nWaiters == 0) {
4637 if (!VCheckDetach(vp)) {
4644 /* check to see if we should free this volume now
4645 * return 1 if volume was freed, 0 otherwise */
4647 VCheckFree(Volume * vp)
4650 if ((vp->nUsers == 0) &&
4651 (vp->nWaiters == 0) &&
4652 !(V_attachFlags(vp) & (VOL_IN_HASH |
4656 ReallyFreeVolume(vp);
4661 #endif /* AFS_DEMAND_ATTACH_FS */
4664 /***************************************************/
4665 /* online volume operations routines */
4666 /***************************************************/
4668 #ifdef AFS_DEMAND_ATTACH_FS
4670 * register a volume operation on a given volume.
4672 * @param[in] vp volume object
4673 * @param[in] vopinfo volume operation info object
4675 * @pre VOL_LOCK is held
4677 * @post volume operation info object attached to volume object.
4678 * volume operation statistics updated.
4680 * @note by "attached" we mean a copy of the passed in object is made
4682 * @internal volume package internal use only
4685 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4687 FSSYNC_VolOp_info * info;
4689 /* attach a vol op info node to the volume struct */
4690 info = (FSSYNC_VolOp_info *) malloc(sizeof(FSSYNC_VolOp_info));
4691 assert(info != NULL);
4692 memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
4693 vp->pending_vol_op = info;
4696 vp->stats.last_vol_op = FT_ApproxTime();
4697 vp->stats.vol_ops++;
4698 IncUInt64(&VStats.vol_ops);
4704 * deregister the volume operation attached to this volume.
4706 * @param[in] vp volume object pointer
4708 * @pre VOL_LOCK is held
4710 * @post the volume operation info object is detached from the volume object
4712 * @internal volume package internal use only
4715 VDeregisterVolOp_r(Volume * vp)
4717 if (vp->pending_vol_op) {
4718 free(vp->pending_vol_op);
4719 vp->pending_vol_op = NULL;
4723 #endif /* AFS_DEMAND_ATTACH_FS */
4726 * determine whether it is safe to leave a volume online during
4727 * the volume operation described by the vopinfo object.
4729 * @param[in] vp volume object
4730 * @param[in] vopinfo volume operation info object
4732 * @return whether it is safe to leave volume online
4733 * @retval 0 it is NOT SAFE to leave the volume online
4734 * @retval 1 it is safe to leave the volume online during the operation
4737 * @arg VOL_LOCK is held
4738 * @arg disk header attached to vp (heavyweight ref on vp will guarantee
4739 * this condition is met)
4741 * @internal volume package internal use only
4744 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4746 return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
4747 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4748 (vopinfo->com.reason == V_READONLY ||
4749 (!VolumeWriteable(vp) &&
4750 (vopinfo->com.reason == V_CLONE ||
4751 vopinfo->com.reason == V_DUMP)))));
4755 * same as VVolOpLeaveOnline_r, but does not require a volume with an attached
4758 * @param[in] vp volume object
4759 * @param[in] vopinfo volume operation info object
4761 * @return whether it is safe to leave volume online
4762 * @retval 0 it is NOT SAFE to leave the volume online
4763 * @retval 1 it is safe to leave the volume online during the operation
4764 * @retval -1 unsure; volume header is required in order to know whether or
4765 * not is is safe to leave the volume online
4767 * @pre VOL_LOCK is held
4769 * @internal volume package internal use only
4772 VVolOpLeaveOnlineNoHeader_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4774 /* follow the logic in VVolOpLeaveOnline_r; this is the same, except
4775 * assume that we don't know VolumeWriteable; return -1 if the answer
4776 * depends on VolumeWriteable */
4778 if (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline) {
4781 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4782 vopinfo->com.reason == V_READONLY) {
4786 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4787 (vopinfo->com.reason == V_CLONE ||
4788 vopinfo->com.reason == V_DUMP)) {
4790 /* must know VolumeWriteable */
4797 * determine whether VBUSY should be set during this volume operation.
4799 * @param[in] vp volume object
4800 * @param[in] vopinfo volume operation info object
4802 * @return whether VBUSY should be set
4803 * @retval 0 VBUSY does NOT need to be set
4804 * @retval 1 VBUSY SHOULD be set
4806 * @pre VOL_LOCK is held
4808 * @internal volume package internal use only
4811 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4813 return ((vopinfo->com.command == FSYNC_VOL_OFF &&
4814 vopinfo->com.reason == FSYNC_SALVAGE) ||
4815 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4816 (vopinfo->com.reason == V_CLONE ||
4817 vopinfo->com.reason == V_DUMP)));
4821 /***************************************************/
4822 /* online salvager routines */
4823 /***************************************************/
4824 #if defined(AFS_DEMAND_ATTACH_FS)
4826 * check whether a salvage needs to be performed on this volume.
4828 * @param[in] vp pointer to volume object
4830 * @return status code
4831 * @retval 0 no salvage scheduled
4832 * @retval 1 a salvage has been scheduled with the salvageserver
4834 * @pre VOL_LOCK is held
4836 * @post if salvage request flag is set and nUsers and nWaiters are zero,
4837 * then a salvage will be requested
4839 * @note this is one of the event handlers called by VCancelReservation_r
4841 * @see VCancelReservation_r
4843 * @internal volume package internal use only.
4846 VCheckSalvage(register Volume * vp)
4849 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
4850 if (vp->nUsers || vp->nWaiters)
4852 if (vp->salvage.requested) {
4853 VScheduleSalvage_r(vp);
4856 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
4861 * request volume salvage.
4863 * @param[out] ec computed client error code
4864 * @param[in] vp volume object pointer
4865 * @param[in] reason reason code (passed to salvageserver via SALVSYNC)
4866 * @param[in] flags see flags note below
4869 * VOL_SALVAGE_INVALIDATE_HEADER causes volume header cache entry
4870 * to be invalidated.
4872 * @pre VOL_LOCK is held.
4874 * @post volume state is changed.
4875 * for fileserver, salvage will be requested once refcount reaches zero.
4877 * @return operation status code
4878 * @retval 0 volume salvage will occur
4879 * @retval 1 volume salvage could not be scheduled
4883 * @note in the fileserver, this call does not synchronously schedule a volume
4884 * salvage. rather, it sets volume state so that when volume refcounts
4885 * reach zero, a volume salvage will occur. by "refcounts", we mean both
4886 * nUsers and nWaiters must be zero.
4888 * @internal volume package internal use only.
4891 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
4895 * for DAFS volume utilities that are not supposed to schedule salvages,
4896 * just transition to error state instead
4898 if (!VCanScheduleSalvage()) {
4899 VChangeState_r(vp, VOL_STATE_ERROR);
4904 if (programType != fileServer && !VCanUseFSSYNC()) {
4905 VChangeState_r(vp, VOL_STATE_ERROR);
4910 if (!vp->salvage.requested) {
4911 vp->salvage.requested = 1;
4912 vp->salvage.reason = reason;
4913 vp->stats.last_salvage = FT_ApproxTime();
4915 /* Note that it is not possible for us to reach this point if a
4916 * salvage is already running on this volume (even if the fileserver
4917 * was restarted during the salvage). If a salvage were running, the
4918 * salvager would have write-locked the volume header file, so when
4919 * we tried to lock the volume header, the lock would have failed,
4920 * and we would have failed during attachment prior to calling
4921 * VRequestSalvage. So we know that we can schedule salvages without
4922 * fear of a salvage already running for this volume. */
4924 if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
4925 VChangeState_r(vp, VOL_STATE_SALVAGING);
4928 Log("VRequestSalvage: volume %u online salvaged too many times; forced offline.\n", vp->hashid);
4930 /* make sure neither VScheduleSalvage_r nor
4931 * VUpdateSalvagePriority_r try to schedule another salvage */
4932 vp->salvage.requested = vp->salvage.scheduled = 0;
4934 VChangeState_r(vp, VOL_STATE_ERROR);
4938 if (flags & VOL_SALVAGE_INVALIDATE_HEADER) {
4939 /* Instead of ReleaseVolumeHeader, we do FreeVolumeHeader()
4940 so that the the next VAttachVolumeByVp_r() invocation
4941 of attach2() will pull in a cached header
4942 entry and fail, then load a fresh one from disk and attach
4945 FreeVolumeHeader(vp);
4952 * update salvageserver scheduling priority for a volume.
4954 * @param[in] vp pointer to volume object
4956 * @return operation status
4958 * @retval 1 request denied, or SALVSYNC communications failure
4960 * @pre VOL_LOCK is held.
4962 * @post in-core salvage priority counter is incremented. if at least
4963 * SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
4964 * last SALVSYNC_RAISEPRIO request, we contact the salvageserver
4965 * to update its priority queue. if no salvage is scheduled,
4966 * this function is a no-op.
4968 * @note DAFS fileserver only
4970 * @note this should be called whenever a VGetVolume fails due to a
4971 * pending salvage request
4973 * @todo should set exclusive state and drop glock around salvsync call
4975 * @internal volume package internal use only.
4978 VUpdateSalvagePriority_r(Volume * vp)
4982 #ifdef SALVSYNC_BUILD_CLIENT
4987 now = FT_ApproxTime();
4989 /* update the salvageserver priority queue occasionally so that
4990 * frequently requested volumes get moved to the head of the queue
4992 if ((vp->salvage.scheduled) &&
4993 (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
4994 code = SALVSYNC_SalvageVolume(vp->hashid,
4995 VPartitionPath(vp->partition),
5000 vp->stats.last_salvage_req = now;
5001 if (code != SYNC_OK) {
5005 #endif /* SALVSYNC_BUILD_CLIENT */
5010 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5012 /* A couple of little helper functions. These return true if we tried to
5013 * use this mechanism to schedule a salvage, false if we haven't tried.
5014 * If we did try a salvage then the results are contained in code.
5018 try_SALVSYNC(Volume *vp, char *partName, int *code) {
5019 #ifdef SALVSYNC_BUILD_CLIENT
5020 if (VCanUseSALVSYNC()) {
5021 Log("Scheduling salvage for volume %lu on part %s over SALVSYNC\n",
5022 afs_printable_uint32_lu(vp->hashid), partName);
5024 /* can't use V_id() since there's no guarantee
5025 * we have the disk data header at this point */
5026 *code = SALVSYNC_SalvageVolume(vp->hashid,
5039 try_FSSYNC(Volume *vp, char *partName, int *code) {
5040 #ifdef FSSYNC_BUILD_CLIENT
5041 if (VCanUseFSSYNC()) {
5042 Log("Scheduling salvage for volume %lu on part %s over FSSYNC\n",
5043 afs_printable_uint32_lu(vp->hashid), partName);
5046 * If we aren't the fileserver, tell the fileserver the volume
5047 * needs to be salvaged. We could directly tell the
5048 * salvageserver, but the fileserver keeps track of some stats
5049 * related to salvages, and handles some other salvage-related
5050 * complications for us.
5052 *code = FSYNC_VolOp(vp->hashid, partName,
5053 FSYNC_VOL_FORCE_ERROR, FSYNC_SALVAGE, NULL);
5056 #endif /* FSSYNC_BUILD_CLIENT */
5061 * schedule a salvage with the salvage server or fileserver.
5063 * @param[in] vp pointer to volume object
5065 * @return operation status
5066 * @retval 0 salvage scheduled successfully
5067 * @retval 1 salvage not scheduled, or SALVSYNC/FSSYNC com error
5070 * @arg VOL_LOCK is held.
5071 * @arg nUsers and nWaiters should be zero.
5073 * @post salvageserver or fileserver is sent a salvage request
5075 * @note If we are the fileserver, the request will be sent to the salvage
5076 * server over SALVSYNC. If we are not the fileserver, the request will be
5077 * sent to the fileserver over FSSYNC (FSYNC_VOL_FORCE_ERROR/FSYNC_SALVAGE).
5081 * @internal volume package internal use only.
5084 VScheduleSalvage_r(Volume * vp)
5088 VolState state_save;
5089 VThreadOptions_t * thread_opts;
5092 assert(VCanUseSALVSYNC() || VCanUseFSSYNC());
5094 if (vp->nWaiters || vp->nUsers) {
5098 /* prevent endless salvage,attach,salvage,attach,... loops */
5099 if (vp->stats.salvages >= SALVAGE_COUNT_MAX)
5103 * don't perform salvsync ops on certain threads
5105 thread_opts = pthread_getspecific(VThread_key);
5106 if (thread_opts == NULL) {
5107 thread_opts = &VThread_defaults;
5109 if (thread_opts->disallow_salvsync || vol_disallow_salvsync) {
5114 * XXX the scheduling process should really be done asynchronously
5115 * to avoid fssync deadlocks
5117 if (!vp->salvage.scheduled) {
5118 /* if we haven't previously scheduled a salvage, do so now
5120 * set the volume to an exclusive state and drop the lock
5121 * around the SALVSYNC call
5123 * note that we do NOT acquire a reservation here -- doing so
5124 * could result in unbounded recursion
5126 strlcpy(partName, VPartitionPath(vp->partition), sizeof(partName));
5127 state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
5130 assert(try_SALVSYNC(vp, partName, &code) ||
5131 try_FSSYNC(vp, partName, &code));
5134 VChangeState_r(vp, state_save);
5136 if (code == SYNC_OK) {
5137 vp->salvage.scheduled = 1;
5138 vp->stats.last_salvage_req = FT_ApproxTime();
5139 if (VCanUseSALVSYNC()) {
5140 /* don't record these stats for non-fileservers; let the
5141 * fileserver take care of these */
5142 vp->stats.salvages++;
5143 IncUInt64(&VStats.salvages);
5148 case SYNC_BAD_COMMAND:
5149 case SYNC_COM_ERROR:
5152 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5153 "denied\n", afs_printable_uint32_lu(vp->hashid));
5156 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5157 "received unknown protocol error %d\n",
5158 afs_printable_uint32_lu(vp->hashid), code);
5162 if (VCanUseFSSYNC()) {
5163 VChangeState_r(vp, VOL_STATE_ERROR);
5169 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5171 #ifdef SALVSYNC_BUILD_CLIENT
5174 * connect to the salvageserver SYNC service.
5176 * @return operation status
5180 * @post connection to salvageserver SYNC service established
5182 * @see VConnectSALV_r
5183 * @see VDisconnectSALV
5184 * @see VReconnectSALV
5191 retVal = VConnectSALV_r();
5197 * connect to the salvageserver SYNC service.
5199 * @return operation status
5203 * @pre VOL_LOCK is held.
5205 * @post connection to salvageserver SYNC service established
5208 * @see VDisconnectSALV_r
5209 * @see VReconnectSALV_r
5210 * @see SALVSYNC_clientInit
5212 * @internal volume package internal use only.
5215 VConnectSALV_r(void)
5217 return SALVSYNC_clientInit();
5221 * disconnect from the salvageserver SYNC service.
5223 * @return operation status
5226 * @pre client should have a live connection to the salvageserver
5228 * @post connection to salvageserver SYNC service destroyed
5230 * @see VDisconnectSALV_r
5232 * @see VReconnectSALV
5235 VDisconnectSALV(void)
5238 VDisconnectSALV_r();
5244 * disconnect from the salvageserver SYNC service.
5246 * @return operation status
5250 * @arg VOL_LOCK is held.
5251 * @arg client should have a live connection to the salvageserver.
5253 * @post connection to salvageserver SYNC service destroyed
5255 * @see VDisconnectSALV
5256 * @see VConnectSALV_r
5257 * @see VReconnectSALV_r
5258 * @see SALVSYNC_clientFinis
5260 * @internal volume package internal use only.
5263 VDisconnectSALV_r(void)
5265 return SALVSYNC_clientFinis();
5269 * disconnect and then re-connect to the salvageserver SYNC service.
5271 * @return operation status
5275 * @pre client should have a live connection to the salvageserver
5277 * @post old connection is dropped, and a new one is established
5280 * @see VDisconnectSALV
5281 * @see VReconnectSALV_r
5284 VReconnectSALV(void)
5288 retVal = VReconnectSALV_r();
5294 * disconnect and then re-connect to the salvageserver SYNC service.
5296 * @return operation status
5301 * @arg VOL_LOCK is held.
5302 * @arg client should have a live connection to the salvageserver.
5304 * @post old connection is dropped, and a new one is established
5306 * @see VConnectSALV_r
5307 * @see VDisconnectSALV
5308 * @see VReconnectSALV
5309 * @see SALVSYNC_clientReconnect
5311 * @internal volume package internal use only.
5314 VReconnectSALV_r(void)
5316 return SALVSYNC_clientReconnect();
5318 #endif /* SALVSYNC_BUILD_CLIENT */
5319 #endif /* AFS_DEMAND_ATTACH_FS */
5322 /***************************************************/
5323 /* FSSYNC routines */
5324 /***************************************************/
5326 /* This must be called by any volume utility which needs to run while the
5327 file server is also running. This is separated from VInitVolumePackage2 so
5328 that a utility can fork--and each of the children can independently
5329 initialize communication with the file server */
5330 #ifdef FSSYNC_BUILD_CLIENT
5332 * connect to the fileserver SYNC service.
5334 * @return operation status
5339 * @arg VInit must equal 2.
5340 * @arg Program Type must not be fileserver or salvager.
5342 * @post connection to fileserver SYNC service established
5345 * @see VDisconnectFS
5346 * @see VChildProcReconnectFS
5353 retVal = VConnectFS_r();
5359 * connect to the fileserver SYNC service.
5361 * @return operation status
5366 * @arg VInit must equal 2.
5367 * @arg Program Type must not be fileserver or salvager.
5368 * @arg VOL_LOCK is held.
5370 * @post connection to fileserver SYNC service established
5373 * @see VDisconnectFS_r
5374 * @see VChildProcReconnectFS_r
5376 * @internal volume package internal use only.
5382 assert((VInit == 2) &&
5383 (programType != fileServer) &&
5384 (programType != salvager));
5385 rc = FSYNC_clientInit();
5392 * disconnect from the fileserver SYNC service.
5395 * @arg client should have a live connection to the fileserver.
5396 * @arg VOL_LOCK is held.
5397 * @arg Program Type must not be fileserver or salvager.
5399 * @post connection to fileserver SYNC service destroyed
5401 * @see VDisconnectFS
5403 * @see VChildProcReconnectFS_r
5405 * @internal volume package internal use only.
5408 VDisconnectFS_r(void)
5410 assert((programType != fileServer) &&
5411 (programType != salvager));
5412 FSYNC_clientFinis();
5417 * disconnect from the fileserver SYNC service.
5420 * @arg client should have a live connection to the fileserver.
5421 * @arg Program Type must not be fileserver or salvager.
5423 * @post connection to fileserver SYNC service destroyed
5425 * @see VDisconnectFS_r
5427 * @see VChildProcReconnectFS
5438 * connect to the fileserver SYNC service from a child process following a fork.
5440 * @return operation status
5445 * @arg VOL_LOCK is held.
5446 * @arg current FSYNC handle is shared with a parent process
5448 * @post current FSYNC handle is discarded and a new connection to the
5449 * fileserver SYNC service is established
5451 * @see VChildProcReconnectFS
5453 * @see VDisconnectFS_r
5455 * @internal volume package internal use only.
5458 VChildProcReconnectFS_r(void)
5460 return FSYNC_clientChildProcReconnect();
5464 * connect to the fileserver SYNC service from a child process following a fork.
5466 * @return operation status
5470 * @pre current FSYNC handle is shared with a parent process
5472 * @post current FSYNC handle is discarded and a new connection to the
5473 * fileserver SYNC service is established
5475 * @see VChildProcReconnectFS_r
5477 * @see VDisconnectFS
5480 VChildProcReconnectFS(void)
5484 ret = VChildProcReconnectFS_r();
5488 #endif /* FSSYNC_BUILD_CLIENT */
5491 /***************************************************/
5492 /* volume bitmap routines */
5493 /***************************************************/
5496 * allocate a vnode bitmap number for the vnode
5498 * @param[out] ec error code
5499 * @param[in] vp volume object pointer
5500 * @param[in] index vnode index number for the vnode
5501 * @param[in] flags flag values described in note
5503 * @note for DAFS, flags parameter controls locking behavior.
5504 * If (flags & VOL_ALLOC_BITMAP_WAIT) is set, then this function
5505 * will create a reservation and block on any other exclusive
5506 * operations. Otherwise, this function assumes the caller
5507 * already has exclusive access to vp, and we just change the
5510 * @pre VOL_LOCK held
5512 * @return bit number allocated
5518 VAllocBitmapEntry_r(Error * ec, Volume * vp,
5519 struct vnodeIndex *index, int flags)
5522 register byte *bp, *ep;
5523 #ifdef AFS_DEMAND_ATTACH_FS
5524 VolState state_save;
5525 #endif /* AFS_DEMAND_ATTACH_FS */
5529 /* This test is probably redundant */
5530 if (!VolumeWriteable(vp)) {
5531 *ec = (bit32) VREADONLY;
5535 #ifdef AFS_DEMAND_ATTACH_FS
5536 if (flags & VOL_ALLOC_BITMAP_WAIT) {
5537 VCreateReservation_r(vp);
5538 VWaitExclusiveState_r(vp);
5540 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
5541 #endif /* AFS_DEMAND_ATTACH_FS */
5544 if ((programType == fileServer) && !index->bitmap) {
5546 #ifndef AFS_DEMAND_ATTACH_FS
5547 /* demand attach fs uses the volume state to avoid races.
5548 * specialStatus field is not used at all */
5550 if (vp->specialStatus == VBUSY) {
5551 if (vp->goingOffline) { /* vos dump waiting for the volume to
5552 * go offline. We probably come here
5553 * from AddNewReadableResidency */
5556 while (vp->specialStatus == VBUSY) {
5557 #ifdef AFS_PTHREAD_ENV
5561 #else /* !AFS_PTHREAD_ENV */
5563 #endif /* !AFS_PTHREAD_ENV */
5567 #endif /* !AFS_DEMAND_ATTACH_FS */
5569 if (!index->bitmap) {
5570 #ifndef AFS_DEMAND_ATTACH_FS
5571 vp->specialStatus = VBUSY; /* Stop anyone else from using it. */
5572 #endif /* AFS_DEMAND_ATTACH_FS */
5573 for (i = 0; i < nVNODECLASSES; i++) {
5574 VGetBitmap_r(ec, vp, i);
5576 #ifdef AFS_DEMAND_ATTACH_FS
5577 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
5578 #else /* AFS_DEMAND_ATTACH_FS */
5579 DeleteVolumeFromHashTable(vp);
5580 vp->shuttingDown = 1; /* Let who has it free it. */
5581 vp->specialStatus = 0;
5582 #endif /* AFS_DEMAND_ATTACH_FS */
5586 #ifndef AFS_DEMAND_ATTACH_FS
5588 vp->specialStatus = 0; /* Allow others to have access. */
5589 #endif /* AFS_DEMAND_ATTACH_FS */
5592 #endif /* BITMAP_LATER */
5594 #ifdef AFS_DEMAND_ATTACH_FS
5596 #endif /* AFS_DEMAND_ATTACH_FS */
5597 bp = index->bitmap + index->bitmapOffset;
5598 ep = index->bitmap + index->bitmapSize;
5600 if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
5602 index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
5605 o = ffs(~*bp) - 1; /* ffs is documented in BSTRING(3) */
5607 ret = ((bp - index->bitmap) * 8 + o);
5608 #ifdef AFS_DEMAND_ATTACH_FS
5610 #endif /* AFS_DEMAND_ATTACH_FS */
5613 bp += sizeof(bit32) /* i.e. 4 */ ;
5615 /* No bit map entry--must grow bitmap */
5617 realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
5620 bp += index->bitmapSize;
5621 memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
5622 index->bitmapOffset = index->bitmapSize;
5623 index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
5625 ret = index->bitmapOffset * 8;
5626 #ifdef AFS_DEMAND_ATTACH_FS
5628 #endif /* AFS_DEMAND_ATTACH_FS */
5631 #ifdef AFS_DEMAND_ATTACH_FS
5632 VChangeState_r(vp, state_save);
5633 if (flags & VOL_ALLOC_BITMAP_WAIT) {
5634 VCancelReservation_r(vp);
5636 #endif /* AFS_DEMAND_ATTACH_FS */
5641 VAllocBitmapEntry(Error * ec, Volume * vp, register struct vnodeIndex * index)
5645 retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
5651 VFreeBitMapEntry_r(Error * ec, register struct vnodeIndex *index,
5654 unsigned int offset;
5660 #endif /* BITMAP_LATER */
5661 offset = bitNumber >> 3;
5662 if (offset >= index->bitmapSize) {
5666 if (offset < index->bitmapOffset)
5667 index->bitmapOffset = offset & ~3; /* Truncate to nearest bit32 */
5668 *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
5672 VFreeBitMapEntry(Error * ec, register struct vnodeIndex *index,
5676 VFreeBitMapEntry_r(ec, index, bitNumber);
5680 /* this function will drop the glock internally.
5681 * for old pthread fileservers, this is safe thanks to vbusy.
5683 * for demand attach fs, caller must have already called
5684 * VCreateReservation_r and VWaitExclusiveState_r */
5686 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
5688 StreamHandle_t *file;
5689 afs_sfsize_t nVnodes, size;
5690 struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
5691 struct vnodeIndex *vip = &vp->vnodeIndex[class];
5692 struct VnodeDiskObject *vnode;
5693 unsigned int unique = 0;
5697 #endif /* BITMAP_LATER */
5698 #ifdef AFS_DEMAND_ATTACH_FS
5699 VolState state_save;
5700 #endif /* AFS_DEMAND_ATTACH_FS */
5704 #ifdef AFS_DEMAND_ATTACH_FS
5705 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
5706 #endif /* AFS_DEMAND_ATTACH_FS */
5709 fdP = IH_OPEN(vip->handle);
5710 assert(fdP != NULL);
5711 file = FDH_FDOPEN(fdP, "r");
5712 assert(file != NULL);
5713 vnode = (VnodeDiskObject *) malloc(vcp->diskSize);
5714 assert(vnode != NULL);
5715 size = OS_SIZE(fdP->fd_fd);
5717 nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
5719 vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4; /* The 10 is a little extra so
5720 * a few files can be created in this volume,
5721 * the whole thing is rounded up to nearest 4
5722 * bytes, because the bit map allocator likes
5725 BitMap = (byte *) calloc(1, vip->bitmapSize);
5726 assert(BitMap != NULL);
5727 #else /* BITMAP_LATER */
5728 vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
5729 assert(vip->bitmap != NULL);
5730 vip->bitmapOffset = 0;
5731 #endif /* BITMAP_LATER */
5732 if (STREAM_SEEK(file, vcp->diskSize, 0) != -1) {
5734 for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
5735 if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
5737 if (vnode->type != vNull) {
5738 if (vnode->vnodeMagic != vcp->magic) {
5739 Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
5744 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
5745 #else /* BITMAP_LATER */
5746 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
5747 #endif /* BITMAP_LATER */
5748 if (unique <= vnode->uniquifier)
5749 unique = vnode->uniquifier + 1;
5751 #ifndef AFS_PTHREAD_ENV
5752 if ((bitNumber & 0x00ff) == 0x0ff) { /* every 256 iterations */
5755 #endif /* !AFS_PTHREAD_ENV */
5758 if (vp->nextVnodeUnique < unique) {
5759 Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
5762 /* Paranoia, partly justified--I think fclose after fdopen
5763 * doesn't seem to close fd. In any event, the documentation
5764 * doesn't specify, so it's safer to close it twice.
5772 /* There may have been a racing condition with some other thread, both
5773 * creating the bitmaps for this volume. If the other thread was faster
5774 * the pointer to bitmap should already be filled and we can free ours.
5776 if (vip->bitmap == NULL) {
5777 vip->bitmap = BitMap;
5778 vip->bitmapOffset = 0;
5780 free((byte *) BitMap);
5781 #endif /* BITMAP_LATER */
5782 #ifdef AFS_DEMAND_ATTACH_FS
5783 VChangeState_r(vp, state_save);
5784 #endif /* AFS_DEMAND_ATTACH_FS */
5788 /***************************************************/
5789 /* Volume Path and Volume Number utility routines */
5790 /***************************************************/
5793 * find the first occurrence of a volume header file and return the path.
5795 * @param[out] ec outbound error code
5796 * @param[in] volumeId volume id to find
5797 * @param[out] partitionp pointer to disk partition path string
5798 * @param[out] namep pointer to volume header file name string
5800 * @post path to first occurrence of volume header is returned in partitionp
5801 * and namep, or ec is set accordingly.
5803 * @warning this function is NOT re-entrant -- partitionp and namep point to
5804 * static data segments
5806 * @note if a volume utility inadvertently leaves behind a stale volume header
5807 * on a vice partition, it is possible for callers to get the wrong one,
5808 * depending on the order of the disk partition linked list.
5812 VGetVolumePath(Error * ec, VolId volumeId, char **partitionp, char **namep)
5814 static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
5815 char path[VMAXPATHLEN];
5817 struct DiskPartition64 *dp;
5821 (void)afs_snprintf(&name[1], (sizeof name) - 1, VFORMAT, afs_printable_uint32_lu(volumeId));
5822 for (dp = DiskPartitionList; dp; dp = dp->next) {
5823 struct afs_stat status;
5824 strcpy(path, VPartitionPath(dp));
5826 if (afs_stat(path, &status) == 0) {
5827 strcpy(partition, dp->name);
5834 *partitionp = *namep = NULL;
5836 *partitionp = partition;
5842 * extract a volume number from a volume header filename string.
5844 * @param[in] name volume header filename string
5846 * @return volume number
5848 * @note the string must be of the form VFORMAT. the only permissible
5849 * deviation is a leading '/' character.
5854 VolumeNumber(char *name)
5858 return atoi(name + 1);
5862 * compute the volume header filename.
5864 * @param[in] volumeId
5866 * @return volume header filename
5868 * @post volume header filename string is constructed
5870 * @warning this function is NOT re-entrant -- the returned string is
5871 * stored in a static char array. see VolumeExternalName_r
5872 * for a re-entrant equivalent.
5874 * @see VolumeExternalName_r
5876 * @deprecated due to the above re-entrancy warning, this interface should
5877 * be considered deprecated. Please use VolumeExternalName_r
5881 VolumeExternalName(VolumeId volumeId)
5883 static char name[VMAXPATHLEN];
5884 (void)afs_snprintf(name, sizeof name, VFORMAT, afs_printable_uint32_lu(volumeId));
5889 * compute the volume header filename.
5891 * @param[in] volumeId
5892 * @param[inout] name array in which to store filename
5893 * @param[in] len length of name array
5895 * @return result code from afs_snprintf
5897 * @see VolumeExternalName
5900 * @note re-entrant equivalent of VolumeExternalName
5903 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
5905 return afs_snprintf(name, len, VFORMAT, afs_printable_uint32_lu(volumeId));
5909 /***************************************************/
5910 /* Volume Usage Statistics routines */
5911 /***************************************************/
5913 #if OPENAFS_VOL_STATS
5914 #define OneDay (86400) /* 24 hours' worth of seconds */
5916 #define OneDay (24*60*60) /* 24 hours */
5917 #endif /* OPENAFS_VOL_STATS */
5920 Midnight(time_t t) {
5921 struct tm local, *l;
5924 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
5925 l = localtime_r(&t, &local);
5931 /* the following is strictly speaking problematic on the
5932 switching day to daylight saving time, after the switch,
5933 as tm_isdst does not match. Similarly, on the looong day when
5934 switching back the OneDay check will not do what naively expected!
5935 The effects are minor, though, and more a matter of interpreting
5937 #ifndef AFS_PTHREAD_ENV
5940 local.tm_hour = local.tm_min=local.tm_sec = 0;
5941 midnight = mktime(&local);
5942 if (midnight != (time_t) -1) return(midnight);
5944 return( (t/OneDay)*OneDay );
5948 /*------------------------------------------------------------------------
5949 * [export] VAdjustVolumeStatistics
5952 * If we've passed midnight, we need to update all the day use
5953 * statistics as well as zeroing the detailed volume statistics
5954 * (if we are implementing them).
5957 * vp : Pointer to the volume structure describing the lucky
5958 * volume being considered for update.
5964 * Nothing interesting.
5968 *------------------------------------------------------------------------*/
5971 VAdjustVolumeStatistics_r(register Volume * vp)
5973 unsigned int now = FT_ApproxTime();
5975 if (now - V_dayUseDate(vp) > OneDay) {
5976 register int ndays, i;
5978 ndays = (now - V_dayUseDate(vp)) / OneDay;
5979 for (i = 6; i > ndays - 1; i--)
5980 V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
5981 for (i = 0; i < ndays - 1 && i < 7; i++)
5982 V_weekUse(vp)[i] = 0;
5984 V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
5986 V_dayUseDate(vp) = Midnight(now);
5988 #if OPENAFS_VOL_STATS
5990 * All we need to do is bzero the entire VOL_STATS_BYTES of
5991 * the detailed volume statistics area.
5993 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
5994 #endif /* OPENAFS_VOL_STATS */
5997 /*It's been more than a day of collection */
5999 * Always return happily.
6002 } /*VAdjustVolumeStatistics */
6005 VAdjustVolumeStatistics(register Volume * vp)
6009 retVal = VAdjustVolumeStatistics_r(vp);
6015 VBumpVolumeUsage_r(register Volume * vp)
6017 unsigned int now = FT_ApproxTime();
6018 V_accessDate(vp) = now;
6019 if (now - V_dayUseDate(vp) > OneDay)
6020 VAdjustVolumeStatistics_r(vp);
6022 * Save the volume header image to disk after every 128 bumps to dayUse.
6024 if ((V_dayUse(vp)++ & 127) == 0) {
6026 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
6031 VBumpVolumeUsage(register Volume * vp)
6034 VBumpVolumeUsage_r(vp);
6039 VSetDiskUsage_r(void)
6041 #ifndef AFS_DEMAND_ATTACH_FS
6042 static int FifteenMinuteCounter = 0;
6046 /* NOTE: Don't attempt to access the partitions list until the
6047 * initialization level indicates that all volumes are attached,
6048 * which implies that all partitions are initialized. */
6049 #ifdef AFS_PTHREAD_ENV
6051 #else /* AFS_PTHREAD_ENV */
6053 #endif /* AFS_PTHREAD_ENV */
6056 VResetDiskUsage_r();
6058 #ifndef AFS_DEMAND_ATTACH_FS
6059 if (++FifteenMinuteCounter == 3) {
6060 FifteenMinuteCounter = 0;
6063 #endif /* !AFS_DEMAND_ATTACH_FS */
6075 /***************************************************/
6076 /* Volume Update List routines */
6077 /***************************************************/
6079 /* The number of minutes that a volume hasn't been updated before the
6080 * "Dont salvage" flag in the volume header will be turned on */
6081 #define SALVAGE_INTERVAL (10*60)
6086 * volume update list functionality has been moved into the VLRU
6087 * the DONT_SALVAGE flag is now set during VLRU demotion
6090 #ifndef AFS_DEMAND_ATTACH_FS
6091 static VolumeId *UpdateList = NULL; /* Pointer to array of Volume ID's */
6092 static int nUpdatedVolumes = 0; /* Updated with entry in UpdateList, salvage after crash flag on */
6093 static int updateSize = 0; /* number of entries possible */
6094 #define UPDATE_LIST_SIZE 128 /* initial size increment (must be a power of 2!) */
6095 #endif /* !AFS_DEMAND_ATTACH_FS */
6098 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
6101 vp->updateTime = FT_ApproxTime();
6102 if (V_dontSalvage(vp) == 0)
6104 V_dontSalvage(vp) = 0;
6105 VSyncVolume_r(ec, vp, 0);
6106 #ifdef AFS_DEMAND_ATTACH_FS
6107 V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
6108 #else /* !AFS_DEMAND_ATTACH_FS */
6111 if (UpdateList == NULL) {
6112 updateSize = UPDATE_LIST_SIZE;
6113 UpdateList = (VolumeId *) malloc(sizeof(VolumeId) * updateSize);
6115 if (nUpdatedVolumes == updateSize) {
6117 if (updateSize > 524288) {
6118 Log("warning: there is likely a bug in the volume update scanner\n");
6122 (VolumeId *) realloc(UpdateList,
6123 sizeof(VolumeId) * updateSize);
6126 assert(UpdateList != NULL);
6127 UpdateList[nUpdatedVolumes++] = V_id(vp);
6128 #endif /* !AFS_DEMAND_ATTACH_FS */
6131 #ifndef AFS_DEMAND_ATTACH_FS
6133 VScanUpdateList(void)
6135 register int i, gap;
6136 register Volume *vp;
6138 afs_uint32 now = FT_ApproxTime();
6139 /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
6140 for (i = gap = 0; i < nUpdatedVolumes; i++) {
6142 UpdateList[i - gap] = UpdateList[i];
6144 /* XXX this routine needlessly messes up the Volume LRU by
6145 * breaking the LRU temporal-locality assumptions.....
6146 * we should use a special volume header allocator here */
6147 vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
6150 } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
6151 V_dontSalvage(vp) = DONT_SALVAGE;
6152 VUpdateVolume_r(&error, vp, 0); /* No need to fsync--not critical */
6160 #ifndef AFS_PTHREAD_ENV
6162 #endif /* !AFS_PTHREAD_ENV */
6164 nUpdatedVolumes -= gap;
6166 #endif /* !AFS_DEMAND_ATTACH_FS */
6169 /***************************************************/
6170 /* Volume LRU routines */
6171 /***************************************************/
6176 * with demand attach fs, we attempt to soft detach(1)
6177 * volumes which have not been accessed in a long time
6178 * in order to speed up fileserver shutdown
6180 * (1) by soft detach we mean a process very similar
6181 * to VOffline, except the final state of the
6182 * Volume will be VOL_STATE_PREATTACHED, instead
6183 * of the usual VOL_STATE_UNATTACHED
6185 #ifdef AFS_DEMAND_ATTACH_FS
6187 /* implementation is reminiscent of a generational GC
6189 * queue 0 is newly attached volumes. this queue is
6190 * sorted by attach timestamp
6192 * queue 1 is volumes that have been around a bit
6193 * longer than queue 0. this queue is sorted by
6196 * queue 2 is volumes tha have been around the longest.
6197 * this queue is unsorted
6199 * queue 3 is volumes that have been marked as
6200 * candidates for soft detachment. this queue is
6203 #define VLRU_GENERATIONS 3 /**< number of generations in VLRU */
6204 #define VLRU_QUEUES 5 /**< total number of VLRU queues */
6207 * definition of a VLRU queue.
6210 volatile struct rx_queue q;
6217 * main VLRU data structure.
6220 struct VLRU_q q[VLRU_QUEUES]; /**< VLRU queues */
6223 /** time interval (in seconds) between promotion passes for
6224 * each young generation queue. */
6225 afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
6227 /** time interval (in seconds) between soft detach candidate
6228 * scans for each generation queue.
6230 * scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
6231 * we perform a soft detach pass. */
6232 afs_uint32 scan_interval[VLRU_GENERATIONS+1];
6234 /* scheduler state */
6235 int next_idx; /**< next queue to receive attention */
6236 afs_uint32 last_promotion[VLRU_GENERATIONS-1]; /**< timestamp of last promotion scan */
6237 afs_uint32 last_scan[VLRU_GENERATIONS+1]; /**< timestamp of last detach scan */
6239 int scanner_state; /**< state of scanner thread */
6240 pthread_cond_t cv; /**< state transition CV */
6243 /** global VLRU state */
6244 static struct VLRU volume_LRU;
6247 * defined states for VLRU scanner thread.
6250 VLRU_SCANNER_STATE_OFFLINE = 0, /**< vlru scanner thread is offline */
6251 VLRU_SCANNER_STATE_ONLINE = 1, /**< vlru scanner thread is online */
6252 VLRU_SCANNER_STATE_SHUTTING_DOWN = 2, /**< vlru scanner thread is shutting down */
6253 VLRU_SCANNER_STATE_PAUSING = 3, /**< vlru scanner thread is getting ready to pause */
6254 VLRU_SCANNER_STATE_PAUSED = 4 /**< vlru scanner thread is paused */
6255 } vlru_thread_state_t;
6257 /* vlru disk data header stuff */
6258 #define VLRU_DISK_MAGIC 0x7a8b9cad /**< vlru disk entry magic number */
6259 #define VLRU_DISK_VERSION 1 /**< vlru disk entry version number */
6261 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
6262 #define VLRU_DUMP_EXPIRATION_TIME (60*60*24*7) /* expire vlru data after 1 week */
6265 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
6266 * soft detachment. */
6267 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
6269 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
6270 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
6272 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
6273 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
6275 /** VLRU control flag. non-zero value implies VLRU subsystem is activated. */
6276 static afs_uint32 VLRU_enabled = 1;
6278 /* queue synchronization routines */
6279 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
6280 static void VLRU_EndExclusive_r(struct VLRU_q * q);
6281 static void VLRU_Wait_r(struct VLRU_q * q);
6284 * set VLRU subsystem tunable parameters.
6286 * @param[in] option tunable option to modify
6287 * @param[in] val new value for tunable parameter
6289 * @pre @c VInitVolumePackage2 has not yet been called.
6291 * @post tunable parameter is modified
6295 * @note valid option parameters are:
6296 * @arg @c VLRU_SET_THRESH
6297 * set the period of inactivity after which
6298 * volumes are eligible for soft detachment
6299 * @arg @c VLRU_SET_INTERVAL
6300 * set the time interval between calls
6301 * to the volume LRU "garbage collector"
6302 * @arg @c VLRU_SET_MAX
6303 * set the max number of volumes to deallocate
6307 VLRU_SetOptions(int option, afs_uint32 val)
6309 if (option == VLRU_SET_THRESH) {
6310 VLRU_offline_thresh = val;
6311 } else if (option == VLRU_SET_INTERVAL) {
6312 VLRU_offline_interval = val;
6313 } else if (option == VLRU_SET_MAX) {
6314 VLRU_offline_max = val;
6315 } else if (option == VLRU_SET_ENABLED) {
6318 VLRU_ComputeConstants();
6322 * compute VLRU internal timing parameters.
6324 * @post VLRU scanner thread internal timing parameters are computed
6326 * @note computes internal timing parameters based upon user-modifiable
6327 * tunable parameters.
6331 * @internal volume package internal use only.
6334 VLRU_ComputeConstants(void)
6336 afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
6338 /* compute the candidate scan interval */
6339 volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
6341 /* compute the promotion intervals */
6342 volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
6343 volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
6346 /* compute the gen 0 scan interval */
6347 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
6349 /* compute the gen 0 scan interval */
6350 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
6355 * initialize VLRU subsystem.
6357 * @pre this function has not yet been called
6359 * @post VLRU subsystem is initialized and VLRU scanner thread is starting
6363 * @internal volume package internal use only.
6369 pthread_attr_t attrs;
6372 if (!VLRU_enabled) {
6373 Log("VLRU: disabled\n");
6377 /* initialize each of the VLRU queues */
6378 for (i = 0; i < VLRU_QUEUES; i++) {
6379 queue_Init(&volume_LRU.q[i]);
6380 volume_LRU.q[i].len = 0;
6381 volume_LRU.q[i].busy = 0;
6382 assert(pthread_cond_init(&volume_LRU.q[i].cv, NULL) == 0);
6385 /* setup the timing constants */
6386 VLRU_ComputeConstants();
6388 /* XXX put inside LogLevel check? */
6389 Log("VLRU: starting scanner with the following configuration parameters:\n");
6390 Log("VLRU: offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
6391 Log("VLRU: running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
6392 Log("VLRU: taking up to %d volumes offline per pass\n", VLRU_offline_max);
6393 Log("VLRU: scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
6394 Log("VLRU: scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
6395 Log("VLRU: scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
6397 /* start up the VLRU scanner */
6398 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
6399 if (programType == fileServer) {
6400 assert(pthread_cond_init(&volume_LRU.cv, NULL) == 0);
6401 assert(pthread_attr_init(&attrs) == 0);
6402 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
6403 assert(pthread_create(&tid, &attrs, &VLRU_ScannerThread, NULL) == 0);
6408 * initialize the VLRU-related fields of a newly allocated volume object.
6410 * @param[in] vp pointer to volume object
6413 * @arg @c VOL_LOCK is held.
6414 * @arg volume object is not on a VLRU queue.
6416 * @post VLRU fields are initialized to indicate that volume object is not
6417 * currently registered with the VLRU subsystem
6421 * @internal volume package interal use only.
6424 VLRU_Init_Node_r(Volume * vp)
6429 assert(queue_IsNotOnQueue(&vp->vlru));
6430 vp->vlru.idx = VLRU_QUEUE_INVALID;
6434 * add a volume object to a VLRU queue.
6436 * @param[in] vp pointer to volume object
6439 * @arg @c VOL_LOCK is held.
6440 * @arg caller MUST hold a lightweight ref on @p vp.
6441 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
6443 * @post the volume object is added to the appropriate VLRU queue
6445 * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
6446 * then the volume is added to that queue. Otherwise, the value
6447 * @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
6448 * volume is added to the NEW generation queue.
6450 * @note @c VOL_LOCK may be dropped internally
6452 * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
6453 * during the add operation, and is restored to the previous
6454 * state prior to return.
6458 * @internal volume package internal use only.
6461 VLRU_Add_r(Volume * vp)
6464 VolState state_save;
6469 if (queue_IsOnQueue(&vp->vlru))
6472 state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
6475 if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
6476 idx = VLRU_QUEUE_NEW;
6479 VLRU_Wait_r(&volume_LRU.q[idx]);
6481 /* repeat check since VLRU_Wait_r may have dropped
6483 if (queue_IsNotOnQueue(&vp->vlru)) {
6485 queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
6486 volume_LRU.q[idx].len++;
6487 V_attachFlags(vp) |= VOL_ON_VLRU;
6488 vp->stats.last_promote = FT_ApproxTime();
6491 VChangeState_r(vp, state_save);
6495 * delete a volume object from a VLRU queue.
6497 * @param[in] vp pointer to volume object
6500 * @arg @c VOL_LOCK is held.
6501 * @arg caller MUST hold a lightweight ref on @p vp.
6502 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
6504 * @post volume object is removed from the VLRU queue
6506 * @note @c VOL_LOCK may be dropped internally
6510 * @todo We should probably set volume state to something exlcusive
6511 * (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
6513 * @internal volume package internal use only.
6516 VLRU_Delete_r(Volume * vp)
6523 if (queue_IsNotOnQueue(&vp->vlru))
6529 if (idx == VLRU_QUEUE_INVALID)
6531 VLRU_Wait_r(&volume_LRU.q[idx]);
6532 } while (idx != vp->vlru.idx);
6534 /* now remove from the VLRU and update
6535 * the appropriate counter */
6536 queue_Remove(&vp->vlru);
6537 volume_LRU.q[idx].len--;
6538 vp->vlru.idx = VLRU_QUEUE_INVALID;
6539 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
6543 * tell the VLRU subsystem that a volume was just accessed.
6545 * @param[in] vp pointer to volume object
6548 * @arg @c VOL_LOCK is held
6549 * @arg caller MUST hold a lightweight ref on @p vp
6550 * @arg caller MUST NOT hold exclusive ownership of any VLRU queue
6552 * @post volume VLRU access statistics are updated. If the volume was on
6553 * the VLRU soft detach candidate queue, it is moved to the NEW
6556 * @note @c VOL_LOCK may be dropped internally
6560 * @internal volume package internal use only.
6563 VLRU_UpdateAccess_r(Volume * vp)
6565 Volume * rvp = NULL;
6570 if (queue_IsNotOnQueue(&vp->vlru))
6573 assert(V_attachFlags(vp) & VOL_ON_VLRU);
6575 /* update the access timestamp */
6576 vp->stats.last_get = FT_ApproxTime();
6579 * if the volume is on the soft detach candidate
6580 * list, we need to safely move it back to a
6581 * regular generation. this has to be done
6582 * carefully so we don't race against the scanner
6586 /* if this volume is on the soft detach candidate queue,
6587 * then grab exclusive access to the necessary queues */
6588 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
6590 VCreateReservation_r(rvp);
6592 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
6593 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
6594 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6595 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6598 /* make sure multiple threads don't race to update */
6599 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
6600 VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
6604 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6605 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
6606 VCancelReservation_r(rvp);
6611 * switch a volume between two VLRU queues.
6613 * @param[in] vp pointer to volume object
6614 * @param[in] new_idx index of VLRU queue onto which the volume will be moved
6615 * @param[in] append controls whether the volume will be appended or
6616 * prepended to the queue. A nonzero value means it will
6617 * be appended; zero means it will be prepended.
6619 * @pre The new (and old, if applicable) queue(s) must either be owned
6620 * exclusively by the calling thread for asynchronous manipulation,
6621 * or the queue(s) must be quiescent and VOL_LOCK must be held.
6622 * Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
6623 * for further details of the queue asynchronous processing mechanism.
6625 * @post If the volume object was already on a VLRU queue, it is
6626 * removed from the queue. Depending on the value of the append
6627 * parameter, the volume object is either appended or prepended
6628 * to the VLRU queue referenced by the new_idx parameter.
6632 * @see VLRU_BeginExclusive_r
6633 * @see VLRU_EndExclusive_r
6636 * @internal volume package internal use only.
6639 VLRU_SwitchQueues(Volume * vp, int new_idx, int append)
6641 if (queue_IsNotOnQueue(&vp->vlru))
6644 queue_Remove(&vp->vlru);
6645 volume_LRU.q[vp->vlru.idx].len--;
6647 /* put the volume back on the correct generational queue */
6649 queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
6651 queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
6654 volume_LRU.q[new_idx].len++;
6655 vp->vlru.idx = new_idx;
6659 * VLRU background thread.
6661 * The VLRU Scanner Thread is responsible for periodically scanning through
6662 * each VLRU queue looking for volumes which should be moved to another
6663 * queue, or soft detached.
6665 * @param[in] args unused thread arguments parameter
6667 * @return unused thread return value
6668 * @retval NULL always
6670 * @internal volume package internal use only.
6673 VLRU_ScannerThread(void * args)
6675 afs_uint32 now, min_delay, delay;
6676 int i, min_idx, min_op, overdue, state;
6678 /* set t=0 for promotion cycle to be
6679 * fileserver startup */
6680 now = FT_ApproxTime();
6681 for (i=0; i < VLRU_GENERATIONS-1; i++) {
6682 volume_LRU.last_promotion[i] = now;
6685 /* don't start the scanner until VLRU_offline_thresh
6686 * plus a small delay for VInitVolumePackage2 to finish
6689 sleep(VLRU_offline_thresh + 60);
6691 /* set t=0 for scan cycle to be now */
6692 now = FT_ApproxTime();
6693 for (i=0; i < VLRU_GENERATIONS+1; i++) {
6694 volume_LRU.last_scan[i] = now;
6698 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
6699 volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
6702 while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
6703 /* check to see if we've been asked to pause */
6704 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
6705 volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
6706 assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
6708 VOL_CV_WAIT(&volume_LRU.cv);
6709 } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
6712 /* scheduling can happen outside the glock */
6715 /* figure out what is next on the schedule */
6717 /* figure out a potential schedule for the new generation first */
6719 min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
6722 if (min_delay > volume_LRU.scan_interval[0]) {
6723 /* unsigned overflow -- we're overdue to run this scan */
6728 /* if we're not overdue for gen 0, figure out schedule for candidate gen */
6730 i = VLRU_QUEUE_CANDIDATE;
6731 delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
6732 if (delay < min_delay) {
6736 if (delay > volume_LRU.scan_interval[i]) {
6737 /* unsigned overflow -- we're overdue to run this scan */
6744 /* if we're still not overdue for something, figure out schedules for promotions */
6745 for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
6746 delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
6747 if (delay < min_delay) {
6752 if (delay > volume_LRU.promotion_interval[i]) {
6753 /* unsigned overflow -- we're overdue to run this promotion */
6762 /* sleep as needed */
6767 /* do whatever is next */
6770 VLRU_Promote_r(min_idx);
6771 VLRU_Demote_r(min_idx+1);
6773 VLRU_Scan_r(min_idx);
6775 now = FT_ApproxTime();
6778 Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
6780 /* signal that scanner is down */
6781 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
6782 assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
6788 * promote volumes from one VLRU generation to the next.
6790 * This routine scans a VLRU generation looking for volumes which are
6791 * eligible to be promoted to the next generation. All volumes which
6792 * meet the eligibility requirement are promoted.
6794 * Promotion eligibility is based upon meeting both of the following
6797 * @arg The volume has been accessed since the last promotion:
6798 * @c (vp->stats.last_get >= vp->stats.last_promote)
6799 * @arg The last promotion occurred at least
6800 * @c volume_LRU.promotion_interval[idx] seconds ago
6802 * As a performance optimization, promotions are "globbed". In other
6803 * words, we promote arbitrarily large contiguous sublists of elements
6806 * @param[in] idx VLRU queue index to scan
6810 * @internal VLRU internal use only.
6813 VLRU_Promote_r(int idx)
6815 int len, chaining, promote;
6816 afs_uint32 now, thresh;
6817 struct rx_queue *qp, *nqp;
6818 Volume * vp, *start = NULL, *end = NULL;
6820 /* get exclusive access to two chains, and drop the glock */
6821 VLRU_Wait_r(&volume_LRU.q[idx]);
6822 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
6823 VLRU_Wait_r(&volume_LRU.q[idx+1]);
6824 VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
6827 thresh = volume_LRU.promotion_interval[idx];
6828 now = FT_ApproxTime();
6831 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
6832 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6833 promote = (((vp->stats.last_promote + thresh) <= now) &&
6834 (vp->stats.last_get >= vp->stats.last_promote));
6842 /* promote and prepend chain */
6843 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
6857 /* promote and prepend */
6858 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
6862 volume_LRU.q[idx].len -= len;
6863 volume_LRU.q[idx+1].len += len;
6866 /* release exclusive access to the two chains */
6868 volume_LRU.last_promotion[idx] = now;
6869 VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
6870 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
6873 /* run the demotions */
6875 VLRU_Demote_r(int idx)
6878 int len, chaining, demote;
6879 afs_uint32 now, thresh;
6880 struct rx_queue *qp, *nqp;
6881 Volume * vp, *start = NULL, *end = NULL;
6882 Volume ** salv_flag_vec = NULL;
6883 int salv_vec_offset = 0;
6885 assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
6887 /* get exclusive access to two chains, and drop the glock */
6888 VLRU_Wait_r(&volume_LRU.q[idx-1]);
6889 VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
6890 VLRU_Wait_r(&volume_LRU.q[idx]);
6891 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
6894 /* no big deal if this allocation fails */
6895 if (volume_LRU.q[idx].len) {
6896 salv_flag_vec = (Volume **) malloc(volume_LRU.q[idx].len * sizeof(Volume *));
6899 now = FT_ApproxTime();
6900 thresh = volume_LRU.promotion_interval[idx-1];
6903 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
6904 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6905 demote = (((vp->stats.last_promote + thresh) <= now) &&
6906 (vp->stats.last_get < (now - thresh)));
6908 /* we now do volume update list DONT_SALVAGE flag setting during
6909 * demotion passes */
6910 if (salv_flag_vec &&
6911 !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
6913 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
6914 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
6915 salv_flag_vec[salv_vec_offset++] = vp;
6916 VCreateReservation_r(vp);
6925 /* demote and append chain */
6926 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
6940 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
6944 volume_LRU.q[idx].len -= len;
6945 volume_LRU.q[idx-1].len += len;
6948 /* release exclusive access to the two chains */
6950 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
6951 VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
6953 /* now go back and set the DONT_SALVAGE flags as appropriate */
6954 if (salv_flag_vec) {
6956 for (i = 0; i < salv_vec_offset; i++) {
6957 vp = salv_flag_vec[i];
6958 if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
6959 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
6960 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
6963 V_attachFlags(vp) |= VOL_HDR_DONTSALV;
6964 V_dontSalvage(vp) = DONT_SALVAGE;
6965 VUpdateVolume_r(&ec, vp, 0);
6969 VCancelReservation_r(vp);
6971 free(salv_flag_vec);
6975 /* run a pass of the VLRU GC scanner */
6977 VLRU_Scan_r(int idx)
6979 afs_uint32 now, thresh;
6980 struct rx_queue *qp, *nqp;
6984 assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
6986 /* gain exclusive access to the idx VLRU */
6987 VLRU_Wait_r(&volume_LRU.q[idx]);
6988 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
6990 if (idx != VLRU_QUEUE_CANDIDATE) {
6991 /* gain exclusive access to the candidate VLRU */
6992 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6993 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6996 now = FT_ApproxTime();
6997 thresh = now - VLRU_offline_thresh;
6999 /* perform candidate selection and soft detaching */
7000 if (idx == VLRU_QUEUE_CANDIDATE) {
7001 /* soft detach some volumes from the candidate pool */
7005 for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7006 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7007 if (i >= VLRU_offline_max) {
7010 /* check timestamp to see if it's a candidate for soft detaching */
7011 if (vp->stats.last_get <= thresh) {
7013 if (VCheckSoftDetach(vp, thresh))
7019 /* scan for volumes to become soft detach candidates */
7020 for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
7021 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7023 /* check timestamp to see if it's a candidate for soft detaching */
7024 if (vp->stats.last_get <= thresh) {
7025 VCheckSoftDetachCandidate(vp, thresh);
7028 if (!(i&0x7f)) { /* lock coarsening optimization */
7036 /* relinquish exclusive access to the VLRU chains */
7040 volume_LRU.last_scan[idx] = now;
7041 if (idx != VLRU_QUEUE_CANDIDATE) {
7042 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7044 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7047 /* check whether volume is safe to soft detach
7048 * caller MUST NOT hold a ref count on vp */
7050 VCheckSoftDetach(Volume * vp, afs_uint32 thresh)
7054 if (vp->nUsers || vp->nWaiters)
7057 if (vp->stats.last_get <= thresh) {
7058 ret = VSoftDetachVolume_r(vp, thresh);
7064 /* check whether volume should be made a
7065 * soft detach candidate */
7067 VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh)
7070 if (vp->nUsers || vp->nWaiters)
7075 assert(idx == VLRU_QUEUE_NEW);
7077 if (vp->stats.last_get <= thresh) {
7078 /* move to candidate pool */
7079 queue_Remove(&vp->vlru);
7080 volume_LRU.q[VLRU_QUEUE_NEW].len--;
7081 queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
7082 vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
7083 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
7091 /* begin exclusive access on VLRU */
7093 VLRU_BeginExclusive_r(struct VLRU_q * q)
7095 assert(q->busy == 0);
7099 /* end exclusive access on VLRU */
7101 VLRU_EndExclusive_r(struct VLRU_q * q)
7105 assert(pthread_cond_broadcast(&q->cv) == 0);
7108 /* wait for another thread to end exclusive access on VLRU */
7110 VLRU_Wait_r(struct VLRU_q * q)
7113 VOL_CV_WAIT(&q->cv);
7118 * volume soft detach
7120 * caller MUST NOT hold a ref count on vp */
7122 VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh)
7127 assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7129 ts_save = vp->stats.last_get;
7130 if (ts_save > thresh)
7133 if (vp->nUsers || vp->nWaiters)
7136 if (VIsExclusiveState(V_attachState(vp))) {
7140 switch (V_attachState(vp)) {
7141 case VOL_STATE_UNATTACHED:
7142 case VOL_STATE_PREATTACHED:
7143 case VOL_STATE_ERROR:
7144 case VOL_STATE_GOING_OFFLINE:
7145 case VOL_STATE_SHUTTING_DOWN:
7146 case VOL_STATE_SALVAGING:
7147 volume_LRU.q[vp->vlru.idx].len--;
7149 /* create and cancel a reservation to
7150 * give the volume an opportunity to
7152 VCreateReservation_r(vp);
7153 queue_Remove(&vp->vlru);
7154 vp->vlru.idx = VLRU_QUEUE_INVALID;
7155 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7156 VCancelReservation_r(vp);
7162 /* hold the volume and take it offline.
7163 * no need for reservations, as VHold_r
7164 * takes care of that internally. */
7165 if (VHold_r(vp) == 0) {
7166 /* vhold drops the glock, so now we should
7167 * check to make sure we aren't racing against
7168 * other threads. if we are racing, offlining vp
7169 * would be wasteful, and block the scanner for a while
7173 (vp->shuttingDown) ||
7174 (vp->goingOffline) ||
7175 (vp->stats.last_get != ts_save)) {
7176 /* looks like we're racing someone else. bail */
7180 /* pull it off the VLRU */
7181 assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7182 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
7183 queue_Remove(&vp->vlru);
7184 vp->vlru.idx = VLRU_QUEUE_INVALID;
7185 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7187 /* take if offline */
7188 VOffline_r(vp, "volume has been soft detached");
7190 /* invalidate the volume header cache */
7191 FreeVolumeHeader(vp);
7194 IncUInt64(&VStats.soft_detaches);
7195 vp->stats.soft_detaches++;
7197 /* put in pre-attached state so demand
7198 * attacher can work on it */
7199 VChangeState_r(vp, VOL_STATE_PREATTACHED);
7205 #endif /* AFS_DEMAND_ATTACH_FS */
7208 /***************************************************/
7209 /* Volume Header Cache routines */
7210 /***************************************************/
7213 * volume header cache.
7215 struct volume_hdr_LRU_t volume_hdr_LRU;
7218 * initialize the volume header cache.
7220 * @param[in] howMany number of header cache entries to preallocate
7222 * @pre VOL_LOCK held. Function has never been called before.
7224 * @post howMany cache entries are allocated, initialized, and added
7225 * to the LRU list. Header cache statistics are initialized.
7227 * @note only applicable to fileServer program type. Should only be
7228 * called once during volume package initialization.
7230 * @internal volume package internal use only.
7233 VInitVolumeHeaderCache(afs_uint32 howMany)
7235 register struct volHeader *hp;
7236 if (programType != fileServer)
7238 queue_Init(&volume_hdr_LRU);
7239 volume_hdr_LRU.stats.free = 0;
7240 volume_hdr_LRU.stats.used = howMany;
7241 volume_hdr_LRU.stats.attached = 0;
7242 hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
7246 /* We are using ReleaseVolumeHeader to initialize the values on the header list
7247 * to ensure they have the right values
7249 ReleaseVolumeHeader(hp++);
7253 * get a volume header and attach it to the volume object.
7255 * @param[in] vp pointer to volume object
7257 * @return cache entry status
7258 * @retval 0 volume header was newly attached; cache data is invalid
7259 * @retval 1 volume header was previously attached; cache data is valid
7261 * @pre VOL_LOCK held. For DAFS, lightweight ref must be held on volume object.
7263 * @post volume header attached to volume object. if necessary, header cache
7264 * entry on LRU is synchronized to disk. Header is removed from LRU list.
7266 * @note VOL_LOCK may be dropped
7268 * @warning this interface does not load header data from disk. it merely
7269 * attaches a header object to the volume object, and may sync the old
7270 * header cache data out to disk in the process.
7272 * @internal volume package internal use only.
7275 GetVolumeHeader(register Volume * vp)
7278 register struct volHeader *hd;
7280 static int everLogged = 0;
7282 #ifdef AFS_DEMAND_ATTACH_FS
7283 VolState vp_save = 0, back_save = 0;
7285 /* XXX debug 9/19/05 we've apparently got
7286 * a ref counting bug somewhere that's
7287 * breaking the nUsers == 0 => header on LRU
7289 if (vp->header && queue_IsNotOnQueue(vp->header)) {
7290 Log("nUsers == 0, but header not on LRU\n");
7295 old = (vp->header != NULL); /* old == volume already has a header */
7297 if (programType != fileServer) {
7298 /* for volume utilities, we allocate volHeaders as needed */
7300 hd = (struct volHeader *)calloc(1, sizeof(*vp->header));
7304 #ifdef AFS_DEMAND_ATTACH_FS
7305 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
7309 /* for the fileserver, we keep a volume header cache */
7311 /* the header we previously dropped in the lru is
7312 * still available. pull it off the lru and return */
7315 assert(hd->back == vp);
7316 #ifdef AFS_DEMAND_ATTACH_FS
7317 V_attachFlags(vp) &= ~(VOL_HDR_IN_LRU);
7320 /* we need to grab a new element off the LRU */
7321 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
7322 /* grab an element and pull off of LRU */
7323 hd = queue_First(&volume_hdr_LRU, volHeader);
7326 /* LRU is empty, so allocate a new volHeader
7327 * this is probably indicative of a leak, so let the user know */
7328 hd = (struct volHeader *)calloc(1, sizeof(struct volHeader));
7331 Log("****Allocated more volume headers, probably leak****\n");
7334 volume_hdr_LRU.stats.free++;
7337 /* this header used to belong to someone else.
7338 * we'll need to check if the header needs to
7339 * be sync'd out to disk */
7341 #ifdef AFS_DEMAND_ATTACH_FS
7342 /* if hd->back were in an exclusive state, then
7343 * its volHeader would not be on the LRU... */
7344 assert(!VIsExclusiveState(V_attachState(hd->back)));
7347 if (hd->diskstuff.inUse) {
7348 /* volume was in use, so we'll need to sync
7349 * its header to disk */
7351 #ifdef AFS_DEMAND_ATTACH_FS
7352 back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
7353 vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
7354 VCreateReservation_r(hd->back);
7358 WriteVolumeHeader_r(&error, hd->back);
7359 /* Ignore errors; catch them later */
7361 #ifdef AFS_DEMAND_ATTACH_FS
7366 hd->back->header = NULL;
7367 #ifdef AFS_DEMAND_ATTACH_FS
7368 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
7370 if (hd->diskstuff.inUse) {
7371 VChangeState_r(hd->back, back_save);
7372 VCancelReservation_r(hd->back);
7373 VChangeState_r(vp, vp_save);
7377 volume_hdr_LRU.stats.attached++;
7381 #ifdef AFS_DEMAND_ATTACH_FS
7382 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
7385 volume_hdr_LRU.stats.free--;
7386 volume_hdr_LRU.stats.used++;
7388 IncUInt64(&VStats.hdr_gets);
7389 #ifdef AFS_DEMAND_ATTACH_FS
7390 IncUInt64(&vp->stats.hdr_gets);
7391 vp->stats.last_hdr_get = FT_ApproxTime();
7398 * make sure volume header is attached and contains valid cache data.
7400 * @param[out] ec outbound error code
7401 * @param[in] vp pointer to volume object
7403 * @pre VOL_LOCK held. For DAFS, lightweight ref held on vp.
7405 * @post header cache entry attached, and loaded with valid data, or
7406 * *ec is nonzero, and the header is released back into the LRU.
7408 * @internal volume package internal use only.
7411 LoadVolumeHeader(Error * ec, Volume * vp)
7413 #ifdef AFS_DEMAND_ATTACH_FS
7414 VolState state_save;
7418 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
7419 IncUInt64(&VStats.hdr_loads);
7420 state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
7423 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
7424 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
7426 IncUInt64(&vp->stats.hdr_loads);
7427 now = FT_ApproxTime();
7431 V_attachFlags(vp) |= VOL_HDR_LOADED;
7432 vp->stats.last_hdr_load = now;
7434 VChangeState_r(vp, state_save);
7436 #else /* AFS_DEMAND_ATTACH_FS */
7438 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
7439 IncUInt64(&VStats.hdr_loads);
7441 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
7442 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
7445 #endif /* AFS_DEMAND_ATTACH_FS */
7447 /* maintain (nUsers==0) => header in LRU invariant */
7448 FreeVolumeHeader(vp);
7453 * release a header cache entry back into the LRU list.
7455 * @param[in] hd pointer to volume header cache object
7457 * @pre VOL_LOCK held.
7459 * @post header cache object appended onto end of LRU list.
7461 * @note only applicable to fileServer program type.
7463 * @note used to place a header cache entry back into the
7464 * LRU pool without invalidating it as a cache entry.
7466 * @internal volume package internal use only.
7469 ReleaseVolumeHeader(register struct volHeader *hd)
7471 if (programType != fileServer)
7473 if (!hd || queue_IsOnQueue(hd)) /* no header, or header already released */
7475 queue_Append(&volume_hdr_LRU, hd);
7476 #ifdef AFS_DEMAND_ATTACH_FS
7478 V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
7481 volume_hdr_LRU.stats.free++;
7482 volume_hdr_LRU.stats.used--;
7486 * free/invalidate a volume header cache entry.
7488 * @param[in] vp pointer to volume object
7490 * @pre VOL_LOCK is held.
7492 * @post For fileserver, header cache entry is returned to LRU, and it is
7493 * invalidated as a cache entry. For volume utilities, the header
7494 * cache entry is freed.
7496 * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
7497 * whenever it is necessary to invalidate the header cache entry.
7499 * @see ReleaseVolumeHeader
7501 * @internal volume package internal use only.
7504 FreeVolumeHeader(register Volume * vp)
7506 register struct volHeader *hd = vp->header;
7509 if (programType == fileServer) {
7510 ReleaseVolumeHeader(hd);
7515 #ifdef AFS_DEMAND_ATTACH_FS
7516 V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
7518 volume_hdr_LRU.stats.attached--;
7523 /***************************************************/
7524 /* Volume Hash Table routines */
7525 /***************************************************/
7528 * set size of volume object hash table.
7530 * @param[in] logsize log(2) of desired hash table size
7532 * @return operation status
7534 * @retval -1 failure
7536 * @pre MUST be called prior to VInitVolumePackage2
7538 * @post Volume Hash Table will have 2^logsize buckets
7541 VSetVolHashSize(int logsize)
7543 /* 64 to 16384 hash buckets seems like a reasonable range */
7544 if ((logsize < 6 ) || (logsize > 14)) {
7549 VolumeHashTable.Size = 1 << logsize;
7550 VolumeHashTable.Mask = VolumeHashTable.Size - 1;
7552 /* we can't yet support runtime modification of this
7553 * parameter. we'll need a configuration rwlock to
7554 * make runtime modification feasible.... */
7561 * initialize dynamic data structures for volume hash table.
7563 * @post hash table is allocated, and fields are initialized.
7565 * @internal volume package internal use only.
7568 VInitVolumeHash(void)
7572 VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
7573 sizeof(VolumeHashChainHead));
7574 assert(VolumeHashTable.Table != NULL);
7576 for (i=0; i < VolumeHashTable.Size; i++) {
7577 queue_Init(&VolumeHashTable.Table[i]);
7578 #ifdef AFS_DEMAND_ATTACH_FS
7579 assert(pthread_cond_init(&VolumeHashTable.Table[i].chain_busy_cv, NULL) == 0);
7580 #endif /* AFS_DEMAND_ATTACH_FS */
7585 * add a volume object to the hash table.
7587 * @param[in] vp pointer to volume object
7588 * @param[in] hashid hash of volume id
7590 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
7593 * @post volume is added to hash chain.
7595 * @internal volume package internal use only.
7597 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
7598 * asynchronous hash chain reordering to finish.
7601 AddVolumeToHashTable(register Volume * vp, int hashid)
7603 VolumeHashChainHead * head;
7605 if (queue_IsOnQueue(vp))
7608 head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
7610 #ifdef AFS_DEMAND_ATTACH_FS
7611 /* wait for the hash chain to become available */
7614 V_attachFlags(vp) |= VOL_IN_HASH;
7615 vp->chainCacheCheck = ++head->cacheCheck;
7616 #endif /* AFS_DEMAND_ATTACH_FS */
7619 vp->hashid = hashid;
7620 queue_Append(head, vp);
7621 vp->vnodeHashOffset = VolumeHashOffset_r();
7625 * delete a volume object from the hash table.
7627 * @param[in] vp pointer to volume object
7629 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
7632 * @post volume is removed from hash chain.
7634 * @internal volume package internal use only.
7636 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
7637 * asynchronous hash chain reordering to finish.
7640 DeleteVolumeFromHashTable(register Volume * vp)
7642 VolumeHashChainHead * head;
7644 if (!queue_IsOnQueue(vp))
7647 head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
7649 #ifdef AFS_DEMAND_ATTACH_FS
7650 /* wait for the hash chain to become available */
7653 V_attachFlags(vp) &= ~(VOL_IN_HASH);
7655 #endif /* AFS_DEMAND_ATTACH_FS */
7659 /* do NOT reset hashid to zero, as the online
7660 * salvager package may need to know the volume id
7661 * after the volume is removed from the hash */
7665 * lookup a volume object in the hash table given a volume id.
7667 * @param[out] ec error code return
7668 * @param[in] volumeId volume id
7669 * @param[in] hint volume object which we believe could be the correct
7672 * @return volume object pointer
7673 * @retval NULL no such volume id is registered with the hash table.
7675 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
7678 * @post volume object with the given id is returned. volume object and
7679 * hash chain access statistics are updated. hash chain may have
7682 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
7683 * asynchronous hash chain reordering operation to finish, or
7684 * in order for us to perform an asynchronous chain reordering.
7686 * @note Hash chain reorderings occur when the access count for the
7687 * volume object being looked up exceeds the sum of the previous
7688 * node's (the node ahead of it in the hash chain linked list)
7689 * access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
7691 * @note For DAFS, the hint parameter allows us to short-circuit if the
7692 * cacheCheck fields match between the hash chain head and the
7693 * hint volume object.
7696 VLookupVolume_r(Error * ec, VolId volumeId, Volume * hint)
7698 register int looks = 0;
7700 #ifdef AFS_DEMAND_ATTACH_FS
7703 VolumeHashChainHead * head;
7706 head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
7708 #ifdef AFS_DEMAND_ATTACH_FS
7709 /* wait for the hash chain to become available */
7712 /* check to see if we can short circuit without walking the hash chain */
7713 if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
7714 IncUInt64(&hint->stats.hash_short_circuits);
7717 #endif /* AFS_DEMAND_ATTACH_FS */
7719 /* someday we need to either do per-chain locks, RWlocks,
7720 * or both for volhash access.
7721 * (and move to a data structure with better cache locality) */
7723 /* search the chain for this volume id */
7724 for(queue_Scan(head, vp, np, Volume)) {
7726 if ((vp->hashid == volumeId)) {
7731 if (queue_IsEnd(head, vp)) {
7735 #ifdef AFS_DEMAND_ATTACH_FS
7736 /* update hash chain statistics */
7739 FillInt64(lks, 0, looks);
7740 AddUInt64(head->looks, lks, &head->looks);
7741 AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
7742 IncUInt64(&head->gets);
7747 IncUInt64(&vp->stats.hash_lookups);
7749 /* for demand attach fileserver, we permit occasional hash chain reordering
7750 * so that frequently looked up volumes move towards the head of the chain */
7751 pp = queue_Prev(vp, Volume);
7752 if (!queue_IsEnd(head, pp)) {
7753 FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
7754 AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
7755 if (GEInt64(vp->stats.hash_lookups, thresh)) {
7756 VReorderHash_r(head, pp, vp);
7760 /* update the short-circuit cache check */
7761 vp->chainCacheCheck = head->cacheCheck;
7763 #endif /* AFS_DEMAND_ATTACH_FS */
7768 #ifdef AFS_DEMAND_ATTACH_FS
7769 /* perform volume hash chain reordering.
7771 * advance a subchain beginning at vp ahead of
7772 * the adjacent subchain ending at pp */
7774 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
7776 Volume *tp, *np, *lp;
7777 afs_uint64 move_thresh;
7779 /* this should never be called if the chain is already busy, so
7780 * no need to wait for other exclusive chain ops to finish */
7782 /* this is a rather heavy set of operations,
7783 * so let's set the chain busy flag and drop
7785 VHashBeginExclusive_r(head);
7788 /* scan forward in the chain from vp looking for the last element
7789 * in the chain we want to advance */
7790 FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
7791 AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
7792 for(queue_ScanFrom(head, vp, tp, np, Volume)) {
7793 if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
7797 lp = queue_Prev(tp, Volume);
7799 /* scan backwards from pp to determine where to splice and
7800 * insert the subchain we're advancing */
7801 for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
7802 if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
7806 tp = queue_Next(tp, Volume);
7808 /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
7809 queue_MoveChainBefore(tp,vp,lp);
7812 IncUInt64(&VStats.hash_reorders);
7814 IncUInt64(&head->reorders);
7816 /* wake up any threads waiting for the hash chain */
7817 VHashEndExclusive_r(head);
7821 /* demand-attach fs volume hash
7822 * asynchronous exclusive operations */
7825 * begin an asynchronous exclusive operation on a volume hash chain.
7827 * @param[in] head pointer to volume hash chain head object
7829 * @pre VOL_LOCK held. hash chain is quiescent.
7831 * @post hash chain marked busy.
7833 * @note this interface is used in conjunction with VHashEndExclusive_r and
7834 * VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
7835 * volume hash chain. Its main use case is hash chain reordering, which
7836 * has the potential to be a highly latent operation.
7838 * @see VHashEndExclusive_r
7843 * @internal volume package internal use only.
7846 VHashBeginExclusive_r(VolumeHashChainHead * head)
7848 assert(head->busy == 0);
7853 * relinquish exclusive ownership of a volume hash chain.
7855 * @param[in] head pointer to volume hash chain head object
7857 * @pre VOL_LOCK held. thread owns the hash chain exclusively.
7859 * @post hash chain is marked quiescent. threads awaiting use of
7860 * chain are awakened.
7862 * @see VHashBeginExclusive_r
7867 * @internal volume package internal use only.
7870 VHashEndExclusive_r(VolumeHashChainHead * head)
7874 assert(pthread_cond_broadcast(&head->chain_busy_cv) == 0);
7878 * wait for all asynchronous operations on a hash chain to complete.
7880 * @param[in] head pointer to volume hash chain head object
7882 * @pre VOL_LOCK held.
7884 * @post hash chain object is quiescent.
7886 * @see VHashBeginExclusive_r
7887 * @see VHashEndExclusive_r
7891 * @note This interface should be called before any attempt to
7892 * traverse the hash chain. It is permissible for a thread
7893 * to gain exclusive access to the chain, and then perform
7894 * latent operations on the chain asynchronously wrt the
7897 * @warning if waiting is necessary, VOL_LOCK is dropped
7899 * @internal volume package internal use only.
7902 VHashWait_r(VolumeHashChainHead * head)
7904 while (head->busy) {
7905 VOL_CV_WAIT(&head->chain_busy_cv);
7908 #endif /* AFS_DEMAND_ATTACH_FS */
7911 /***************************************************/
7912 /* Volume by Partition List routines */
7913 /***************************************************/
7916 * demand attach fileserver adds a
7917 * linked list of volumes to each
7918 * partition object, thus allowing
7919 * for quick enumeration of all
7920 * volumes on a partition
7923 #ifdef AFS_DEMAND_ATTACH_FS
7925 * add a volume to its disk partition VByPList.
7927 * @param[in] vp pointer to volume object
7929 * @pre either the disk partition VByPList is owned exclusively
7930 * by the calling thread, or the list is quiescent and
7933 * @post volume is added to disk partition VByPList
7937 * @warning it is the caller's responsibility to ensure list
7940 * @see VVByPListWait_r
7941 * @see VVByPListBeginExclusive_r
7942 * @see VVByPListEndExclusive_r
7944 * @internal volume package internal use only.
7947 AddVolumeToVByPList_r(Volume * vp)
7949 if (queue_IsNotOnQueue(&vp->vol_list)) {
7950 queue_Append(&vp->partition->vol_list, &vp->vol_list);
7951 V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
7952 vp->partition->vol_list.len++;
7957 * delete a volume from its disk partition VByPList.
7959 * @param[in] vp pointer to volume object
7961 * @pre either the disk partition VByPList is owned exclusively
7962 * by the calling thread, or the list is quiescent and
7965 * @post volume is removed from the disk partition VByPList
7969 * @warning it is the caller's responsibility to ensure list
7972 * @see VVByPListWait_r
7973 * @see VVByPListBeginExclusive_r
7974 * @see VVByPListEndExclusive_r
7976 * @internal volume package internal use only.
7979 DeleteVolumeFromVByPList_r(Volume * vp)
7981 if (queue_IsOnQueue(&vp->vol_list)) {
7982 queue_Remove(&vp->vol_list);
7983 V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
7984 vp->partition->vol_list.len--;
7989 * begin an asynchronous exclusive operation on a VByPList.
7991 * @param[in] dp pointer to disk partition object
7993 * @pre VOL_LOCK held. VByPList is quiescent.
7995 * @post VByPList marked busy.
7997 * @note this interface is used in conjunction with VVByPListEndExclusive_r and
7998 * VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8001 * @see VVByPListEndExclusive_r
8002 * @see VVByPListWait_r
8006 * @internal volume package internal use only.
8008 /* take exclusive control over the list */
8010 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
8012 assert(dp->vol_list.busy == 0);
8013 dp->vol_list.busy = 1;
8017 * relinquish exclusive ownership of a VByPList.
8019 * @param[in] dp pointer to disk partition object
8021 * @pre VOL_LOCK held. thread owns the VByPList exclusively.
8023 * @post VByPList is marked quiescent. threads awaiting use of
8024 * the list are awakened.
8026 * @see VVByPListBeginExclusive_r
8027 * @see VVByPListWait_r
8031 * @internal volume package internal use only.
8034 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
8036 assert(dp->vol_list.busy);
8037 dp->vol_list.busy = 0;
8038 assert(pthread_cond_broadcast(&dp->vol_list.cv) == 0);
8042 * wait for all asynchronous operations on a VByPList to complete.
8044 * @param[in] dp pointer to disk partition object
8046 * @pre VOL_LOCK is held.
8048 * @post disk partition's VByP list is quiescent
8052 * @note This interface should be called before any attempt to
8053 * traverse the VByPList. It is permissible for a thread
8054 * to gain exclusive access to the list, and then perform
8055 * latent operations on the list asynchronously wrt the
8058 * @warning if waiting is necessary, VOL_LOCK is dropped
8060 * @see VVByPListEndExclusive_r
8061 * @see VVByPListBeginExclusive_r
8063 * @internal volume package internal use only.
8066 VVByPListWait_r(struct DiskPartition64 * dp)
8068 while (dp->vol_list.busy) {
8069 VOL_CV_WAIT(&dp->vol_list.cv);
8072 #endif /* AFS_DEMAND_ATTACH_FS */
8074 /***************************************************/
8075 /* Volume Cache Statistics routines */
8076 /***************************************************/
8079 VPrintCacheStats_r(void)
8081 afs_uint32 get_hi, get_lo, load_hi, load_lo;
8082 register struct VnodeClassInfo *vcp;
8083 vcp = &VnodeClassInfo[vLarge];
8084 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);
8085 vcp = &VnodeClassInfo[vSmall];
8086 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);
8087 SplitInt64(VStats.hdr_gets, get_hi, get_lo);
8088 SplitInt64(VStats.hdr_loads, load_hi, load_lo);
8089 Log("Volume header cache, %d entries, %d gets, %d replacements\n",
8090 VStats.hdr_cache_size, get_lo, load_lo);
8094 VPrintCacheStats(void)
8097 VPrintCacheStats_r();
8101 #ifdef AFS_DEMAND_ATTACH_FS
8103 UInt64ToDouble(afs_uint64 * x)
8105 static double c32 = 4.0 * 1.073741824 * 1000000000.0;
8107 SplitInt64(*x, h, l);
8108 return (((double)h) * c32) + ((double) l);
8112 DoubleToPrintable(double x, char * buf, int len)
8114 static double billion = 1000000000.0;
8117 y[0] = (afs_uint32) (x / (billion * billion));
8118 y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
8119 y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
8122 snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
8124 snprintf(buf, len, "%d%09d", y[1], y[2]);
8126 snprintf(buf, len, "%d", y[2]);
8132 struct VLRUExtStatsEntry {
8136 struct VLRUExtStats {
8142 } queue_info[VLRU_QUEUE_INVALID];
8143 struct VLRUExtStatsEntry * vec;
8147 * add a 256-entry fudge factor onto the vector in case state changes
8148 * out from under us.
8150 #define VLRU_EXT_STATS_VEC_LEN_FUDGE 256
8153 * collect extended statistics for the VLRU subsystem.
8155 * @param[out] stats pointer to stats structure to be populated
8156 * @param[in] nvols number of volumes currently known to exist
8158 * @pre VOL_LOCK held
8160 * @post stats->vec allocated and populated
8162 * @return operation status
8167 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
8169 afs_uint32 cur, idx, len;
8170 struct rx_queue * qp, * nqp;
8172 struct VLRUExtStatsEntry * vec;
8174 len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
8175 vec = stats->vec = calloc(len,
8176 sizeof(struct VLRUExtStatsEntry));
8182 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
8183 VLRU_Wait_r(&volume_LRU.q[idx]);
8184 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
8187 stats->queue_info[idx].start = cur;
8189 for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
8191 /* out of space in vec */
8194 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
8195 vec[cur].volid = vp->hashid;
8199 stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
8202 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
8210 #define ENUMTOSTRING(en) #en
8211 #define ENUMCASE(en) \
8213 return ENUMTOSTRING(en); \
8217 vlru_idx_to_string(int idx)
8220 ENUMCASE(VLRU_QUEUE_NEW);
8221 ENUMCASE(VLRU_QUEUE_MID);
8222 ENUMCASE(VLRU_QUEUE_OLD);
8223 ENUMCASE(VLRU_QUEUE_CANDIDATE);
8224 ENUMCASE(VLRU_QUEUE_HELD);
8225 ENUMCASE(VLRU_QUEUE_INVALID);
8227 return "**UNKNOWN**";
8232 VPrintExtendedCacheStats_r(int flags)
8235 afs_uint32 vol_sum = 0;
8242 struct stats looks, gets, reorders, len;
8243 struct stats ch_looks, ch_gets, ch_reorders;
8245 VolumeHashChainHead *head;
8247 struct VLRUExtStats vlru_stats;
8249 /* zero out stats */
8250 memset(&looks, 0, sizeof(struct stats));
8251 memset(&gets, 0, sizeof(struct stats));
8252 memset(&reorders, 0, sizeof(struct stats));
8253 memset(&len, 0, sizeof(struct stats));
8254 memset(&ch_looks, 0, sizeof(struct stats));
8255 memset(&ch_gets, 0, sizeof(struct stats));
8256 memset(&ch_reorders, 0, sizeof(struct stats));
8258 for (i = 0; i < VolumeHashTable.Size; i++) {
8259 head = &VolumeHashTable.Table[i];
8262 VHashBeginExclusive_r(head);
8265 ch_looks.sum = UInt64ToDouble(&head->looks);
8266 ch_gets.sum = UInt64ToDouble(&head->gets);
8267 ch_reorders.sum = UInt64ToDouble(&head->reorders);
8269 /* update global statistics */
8271 looks.sum += ch_looks.sum;
8272 gets.sum += ch_gets.sum;
8273 reorders.sum += ch_reorders.sum;
8274 len.sum += (double)head->len;
8275 vol_sum += head->len;
8278 len.min = (double) head->len;
8279 len.max = (double) head->len;
8280 looks.min = ch_looks.sum;
8281 looks.max = ch_looks.sum;
8282 gets.min = ch_gets.sum;
8283 gets.max = ch_gets.sum;
8284 reorders.min = ch_reorders.sum;
8285 reorders.max = ch_reorders.sum;
8287 if (((double)head->len) < len.min)
8288 len.min = (double) head->len;
8289 if (((double)head->len) > len.max)
8290 len.max = (double) head->len;
8291 if (ch_looks.sum < looks.min)
8292 looks.min = ch_looks.sum;
8293 else if (ch_looks.sum > looks.max)
8294 looks.max = ch_looks.sum;
8295 if (ch_gets.sum < gets.min)
8296 gets.min = ch_gets.sum;
8297 else if (ch_gets.sum > gets.max)
8298 gets.max = ch_gets.sum;
8299 if (ch_reorders.sum < reorders.min)
8300 reorders.min = ch_reorders.sum;
8301 else if (ch_reorders.sum > reorders.max)
8302 reorders.max = ch_reorders.sum;
8306 if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
8307 /* compute detailed per-chain stats */
8308 struct stats hdr_loads, hdr_gets;
8309 double v_looks, v_loads, v_gets;
8311 /* initialize stats with data from first element in chain */
8312 vp = queue_First(head, Volume);
8313 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
8314 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
8315 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
8316 ch_gets.min = ch_gets.max = v_looks;
8317 hdr_loads.min = hdr_loads.max = v_loads;
8318 hdr_gets.min = hdr_gets.max = v_gets;
8319 hdr_loads.sum = hdr_gets.sum = 0;
8321 vp = queue_Next(vp, Volume);
8323 /* pull in stats from remaining elements in chain */
8324 for (queue_ScanFrom(head, vp, vp, np, Volume)) {
8325 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
8326 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
8327 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
8329 hdr_loads.sum += v_loads;
8330 hdr_gets.sum += v_gets;
8332 if (v_looks < ch_gets.min)
8333 ch_gets.min = v_looks;
8334 else if (v_looks > ch_gets.max)
8335 ch_gets.max = v_looks;
8337 if (v_loads < hdr_loads.min)
8338 hdr_loads.min = v_loads;
8339 else if (v_loads > hdr_loads.max)
8340 hdr_loads.max = v_loads;
8342 if (v_gets < hdr_gets.min)
8343 hdr_gets.min = v_gets;
8344 else if (v_gets > hdr_gets.max)
8345 hdr_gets.max = v_gets;
8348 /* compute per-chain averages */
8349 ch_gets.avg = ch_gets.sum / ((double)head->len);
8350 hdr_loads.avg = hdr_loads.sum / ((double)head->len);
8351 hdr_gets.avg = hdr_gets.sum / ((double)head->len);
8353 /* dump per-chain stats */
8354 Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
8356 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
8357 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
8358 Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
8359 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
8360 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
8361 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
8362 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
8363 Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
8364 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
8365 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
8366 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
8367 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
8368 Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
8369 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
8370 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
8371 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
8372 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
8373 } else if (flags & VOL_STATS_PER_CHAIN) {
8374 /* dump simple per-chain stats */
8375 Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
8377 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
8378 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
8379 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
8383 VHashEndExclusive_r(head);
8388 /* compute global averages */
8389 len.avg = len.sum / ((double)VolumeHashTable.Size);
8390 looks.avg = looks.sum / ((double)VolumeHashTable.Size);
8391 gets.avg = gets.sum / ((double)VolumeHashTable.Size);
8392 reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
8394 /* dump global stats */
8395 Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
8396 Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
8397 DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
8398 DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
8399 DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
8400 DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
8401 Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
8402 DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
8403 DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
8404 DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
8405 DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
8406 Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
8407 DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
8408 DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
8409 DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
8410 DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
8411 Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
8412 DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
8413 DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
8414 DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
8415 DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
8417 /* print extended disk related statistics */
8419 struct DiskPartition64 * diskP;
8420 afs_uint32 vol_count[VOLMAXPARTS+1];
8421 byte part_exists[VOLMAXPARTS+1];
8425 memset(vol_count, 0, sizeof(vol_count));
8426 memset(part_exists, 0, sizeof(part_exists));
8430 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
8432 vol_count[id] = diskP->vol_list.len;
8433 part_exists[id] = 1;
8437 for (i = 0; i <= VOLMAXPARTS; i++) {
8438 if (part_exists[i]) {
8439 /* XXX while this is currently safe, it is a violation
8440 * of the VGetPartitionById_r interface contract. */
8441 diskP = VGetPartitionById_r(i, 0);
8443 Log("Partition %s has %d online volumes\n",
8444 VPartitionPath(diskP), diskP->vol_list.len);
8451 /* print extended VLRU statistics */
8452 if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
8453 afs_uint32 idx, cur, lpos;
8457 Log("VLRU State Dump:\n\n");
8459 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
8460 Log("\t%s:\n", vlru_idx_to_string(idx));
8463 for (cur = vlru_stats.queue_info[idx].start;
8464 cur < vlru_stats.queue_info[idx].len;
8466 line[lpos++] = vlru_stats.vec[cur].volid;
8468 Log("\t\t%u, %u, %u, %u, %u,\n",
8469 line[0], line[1], line[2], line[3], line[4]);
8478 Log("\t\t%u, %u, %u, %u, %u\n",
8479 line[0], line[1], line[2], line[3], line[4]);
8484 free(vlru_stats.vec);
8491 VPrintExtendedCacheStats(int flags)
8494 VPrintExtendedCacheStats_r(flags);
8497 #endif /* AFS_DEMAND_ATTACH_FS */
8500 VCanScheduleSalvage(void)
8502 return vol_opts.canScheduleSalvage;
8508 return vol_opts.canUseFSSYNC;
8512 VCanUseSALVSYNC(void)
8514 return vol_opts.canUseSALVSYNC;