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;
841 params = (struct vinitvolumepackage_thread_param *)malloc(sizeof(struct vinitvolumepackage_thread_param));
845 params->nthreads = threads;
846 params->thread = i+1;
849 assert(pthread_create (&tid, &attrs, &VInitVolumePackageThread, (void*)params) == 0);
850 AFS_SIGSET_RESTORE();
853 VInitPreAttachVolumes(threads, &vq);
855 assert(pthread_attr_destroy(&attrs) == 0);
856 assert(pthread_cond_destroy(&pq.cv) == 0);
857 assert(pthread_mutex_destroy(&pq.mutex) == 0);
858 assert(pthread_cond_destroy(&vq.cv) == 0);
859 assert(pthread_mutex_destroy(&vq.mutex) == 0);
863 VInit = 2; /* Initialized, and all volumes have been attached */
864 assert(pthread_cond_broadcast(&vol_init_attach_cond) == 0);
871 * Volume package initialization worker thread. Scan partitions for volume
872 * header files. Gather batches of volume ids and dispatch them to
873 * the main thread to be preattached. The volume preattachement is done
874 * in the main thread to avoid global volume lock contention.
877 VInitVolumePackageThread(void *args)
879 struct vinitvolumepackage_thread_param *params;
880 struct DiskPartition64 *partition;
881 struct partition_queue *pq;
882 struct volume_init_queue *vq;
883 struct volume_init_batch *vb;
886 params = (struct vinitvolumepackage_thread_param *)args;
892 vb = (struct volume_init_batch*)malloc(sizeof(struct volume_init_batch));
894 vb->thread = params->thread;
898 Log("Scanning partitions on thread %d of %d\n", params->thread, params->nthreads);
899 while((partition = VInitNextPartition(pq))) {
903 Log("Partition %s: pre-attaching volumes\n", partition->name);
904 dirp = opendir(VPartitionPath(partition));
906 Log("opendir on Partition %s failed, errno=%d!\n", partition->name, errno);
909 while ((vid = VInitNextVolumeId(dirp))) {
910 Volume *vp = (Volume*)malloc(sizeof(Volume));
912 memset(vp, 0, sizeof(Volume));
913 vp->device = partition->device;
914 vp->partition = partition;
916 queue_Init(&vp->vnode_list);
917 assert(pthread_cond_init(&V_attachCV(vp), NULL) == 0);
919 vb->batch[vb->size++] = vp;
920 if (vb->size == VINIT_BATCH_MAX_SIZE) {
921 assert(pthread_mutex_lock(&vq->mutex) == 0);
922 queue_Append(vq, vb);
923 assert(pthread_cond_broadcast(&vq->cv) == 0);
924 assert(pthread_mutex_unlock(&vq->mutex) == 0);
926 vb = (struct volume_init_batch*)malloc(sizeof(struct volume_init_batch));
928 vb->thread = params->thread;
937 assert(pthread_mutex_lock(&vq->mutex) == 0);
938 queue_Append(vq, vb);
939 assert(pthread_cond_broadcast(&vq->cv) == 0);
940 assert(pthread_mutex_unlock(&vq->mutex) == 0);
942 Log("Partition scan thread %d of %d ended\n", params->thread, params->nthreads);
948 * Read next element from the pre-populated partition list.
950 static struct DiskPartition64*
951 VInitNextPartition(struct partition_queue *pq)
953 struct DiskPartition64 *partition;
954 struct diskpartition_queue_t *dp; /* queue element */
956 if (vinit_attach_abort) {
957 Log("Aborting volume preattach thread.\n");
961 /* get next partition to scan */
962 assert(pthread_mutex_lock(&pq->mutex) == 0);
963 if (queue_IsEmpty(pq)) {
964 assert(pthread_mutex_unlock(&pq->mutex) == 0);
967 dp = queue_First(pq, diskpartition_queue_t);
969 assert(pthread_mutex_unlock(&pq->mutex) == 0);
974 partition = dp->diskP;
980 * Find next volume id on the partition.
983 VInitNextVolumeId(DIR *dirp)
989 while((d = readdir(dirp))) {
990 if (vinit_attach_abort) {
991 Log("Aborting volume preattach thread.\n");
994 ext = strrchr(d->d_name, '.');
995 if (d->d_name[0] == 'V' && ext && strcmp(ext, VHDREXT) == 0) {
996 vid = VolumeNumber(d->d_name);
1000 Log("Warning: bogus volume header file: %s\n", d->d_name);
1007 * Preattach volumes in batches to avoid lock contention.
1010 VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq)
1012 struct volume_init_batch *vb;
1016 /* dequeue next volume */
1017 pthread_mutex_lock(&vq->mutex);
1018 if (queue_IsEmpty(vq)) {
1019 pthread_cond_wait(&vq->cv, &vq->mutex);
1021 vb = queue_First(vq, volume_init_batch);
1023 pthread_mutex_unlock(&vq->mutex);
1027 for (i = 0; i<vb->size; i++) {
1033 dup = VLookupVolume_r(&ec, vp->hashid, NULL);
1035 Log("Error looking up volume, code=%d\n", ec);
1038 Log("Warning: Duplicate volume id %d detected.\n", vp->hashid);
1041 /* put pre-attached volume onto the hash table
1042 * and bring it up to the pre-attached state */
1043 AddVolumeToHashTable(vp, vp->hashid);
1044 AddVolumeToVByPList_r(vp);
1045 VLRU_Init_Node_r(vp);
1046 VChangeState_r(vp, VOL_STATE_PREATTACHED);
1059 #endif /* AFS_DEMAND_ATTACH_FS */
1061 #if !defined(AFS_DEMAND_ATTACH_FS)
1063 * attach all volumes on a given disk partition
1066 VAttachVolumesByPartition(struct DiskPartition64 *diskP, int * nAttached, int * nUnattached)
1072 Log("Partition %s: attaching volumes\n", diskP->name);
1073 dirp = opendir(VPartitionPath(diskP));
1075 Log("opendir on Partition %s failed!\n", diskP->name);
1079 while ((dp = readdir(dirp))) {
1081 p = strrchr(dp->d_name, '.');
1083 if (vinit_attach_abort) {
1084 Log("Partition %s: abort attach volumes\n", diskP->name);
1088 if (p != NULL && strcmp(p, VHDREXT) == 0) {
1091 vp = VAttachVolumeByName(&error, diskP->name, dp->d_name,
1093 (*(vp ? nAttached : nUnattached))++;
1094 if (error == VOFFLINE)
1095 Log("Volume %d stays offline (/vice/offline/%s exists)\n", VolumeNumber(dp->d_name), dp->d_name);
1096 else if (LogLevel >= 5) {
1097 Log("Partition %s: attached volume %d (%s)\n",
1098 diskP->name, VolumeNumber(dp->d_name),
1107 Log("Partition %s: attached %d volumes; %d volumes not attached\n", diskP->name, *nAttached, *nUnattached);
1112 #endif /* !AFS_DEMAND_ATTACH_FS */
1114 /***************************************************/
1115 /* Shutdown routines */
1116 /***************************************************/
1120 * highly multithreaded volume package shutdown
1122 * with the demand attach fileserver extensions,
1123 * VShutdown has been modified to be multithreaded.
1124 * In order to achieve optimal use of many threads,
1125 * the shutdown code involves one control thread and
1126 * n shutdown worker threads. The control thread
1127 * periodically examines the number of volumes available
1128 * for shutdown on each partition, and produces a worker
1129 * thread allocation schedule. The idea is to eliminate
1130 * redundant scheduling computation on the workers by
1131 * having a single master scheduler.
1133 * The scheduler's objectives are:
1135 * each partition with volumes remaining gets allocated
1136 * at least 1 thread (assuming sufficient threads)
1138 * threads are allocated proportional to the number of
1139 * volumes remaining to be offlined. This ensures that
1140 * the OS I/O scheduler has many requests to elevator
1141 * seek on partitions that will (presumably) take the
1142 * longest amount of time (from now) to finish shutdown
1143 * (3) keep threads busy
1144 * when there are extra threads, they are assigned to
1145 * partitions using a simple round-robin algorithm
1147 * In the future, we may wish to add the ability to adapt
1148 * to the relative performance patterns of each disk
1153 * multi-step shutdown process
1155 * demand attach shutdown is a four-step process. Each
1156 * shutdown "pass" shuts down increasingly more difficult
1157 * volumes. The main purpose is to achieve better cache
1158 * utilization during shutdown.
1161 * shutdown volumes in the unattached, pre-attached
1164 * shutdown attached volumes with cached volume headers
1166 * shutdown all volumes in non-exclusive states
1168 * shutdown all remaining volumes
1171 #ifdef AFS_DEMAND_ATTACH_FS
1177 struct DiskPartition64 * diskP;
1178 struct diskpartition_queue_t * dpq;
1179 vshutdown_thread_t params;
1181 pthread_attr_t attrs;
1183 memset(¶ms, 0, sizeof(vshutdown_thread_t));
1186 Log("VShutdown: aborting attach volumes\n");
1187 vinit_attach_abort = 1;
1188 VOL_CV_WAIT(&vol_init_attach_cond);
1191 for (params.n_parts=0, diskP = DiskPartitionList;
1192 diskP; diskP = diskP->next, params.n_parts++);
1194 Log("VShutdown: shutting down on-line volumes on %d partition%s...\n",
1195 params.n_parts, params.n_parts > 1 ? "s" : "");
1197 if (vol_attach_threads > 1) {
1198 /* prepare for parallel shutdown */
1199 params.n_threads = vol_attach_threads;
1200 assert(pthread_mutex_init(¶ms.lock, NULL) == 0);
1201 assert(pthread_cond_init(¶ms.cv, NULL) == 0);
1202 assert(pthread_cond_init(¶ms.master_cv, NULL) == 0);
1203 assert(pthread_attr_init(&attrs) == 0);
1204 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
1205 queue_Init(¶ms);
1207 /* setup the basic partition information structures for
1208 * parallel shutdown */
1209 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1211 struct rx_queue * qp, * nqp;
1215 VVByPListWait_r(diskP);
1216 VVByPListBeginExclusive_r(diskP);
1219 for (queue_Scan(&diskP->vol_list, qp, nqp, rx_queue)) {
1220 vp = (Volume *)((char *)qp - offsetof(Volume, vol_list));
1224 Log("VShutdown: partition %s has %d volumes with attached headers\n",
1225 VPartitionPath(diskP), count);
1228 /* build up the pass 0 shutdown work queue */
1229 dpq = (struct diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
1230 assert(dpq != NULL);
1232 queue_Prepend(¶ms, dpq);
1234 params.part_pass_head[diskP->index] = queue_First(&diskP->vol_list, rx_queue);
1237 Log("VShutdown: beginning parallel fileserver shutdown\n");
1238 Log("VShutdown: using %d threads to offline volumes on %d partition%s\n",
1239 vol_attach_threads, params.n_parts, params.n_parts > 1 ? "s" : "" );
1241 /* do pass 0 shutdown */
1242 assert(pthread_mutex_lock(¶ms.lock) == 0);
1243 for (i=0; i < params.n_threads; i++) {
1244 assert(pthread_create
1245 (&tid, &attrs, &VShutdownThread,
1249 /* wait for all the pass 0 shutdowns to complete */
1250 while (params.n_threads_complete < params.n_threads) {
1251 assert(pthread_cond_wait(¶ms.master_cv, ¶ms.lock) == 0);
1253 params.n_threads_complete = 0;
1255 assert(pthread_cond_broadcast(¶ms.cv) == 0);
1256 assert(pthread_mutex_unlock(¶ms.lock) == 0);
1258 Log("VShutdown: pass 0 completed using the 1 thread per partition algorithm\n");
1259 Log("VShutdown: starting passes 1 through 3 using finely-granular mp-fast algorithm\n");
1261 /* run the parallel shutdown scheduler. it will drop the glock internally */
1262 ShutdownController(¶ms);
1264 /* wait for all the workers to finish pass 3 and terminate */
1265 while (params.pass < 4) {
1266 VOL_CV_WAIT(¶ms.cv);
1269 assert(pthread_attr_destroy(&attrs) == 0);
1270 assert(pthread_cond_destroy(¶ms.cv) == 0);
1271 assert(pthread_cond_destroy(¶ms.master_cv) == 0);
1272 assert(pthread_mutex_destroy(¶ms.lock) == 0);
1274 /* drop the VByPList exclusive reservations */
1275 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1276 VVByPListEndExclusive_r(diskP);
1277 Log("VShutdown: %s stats : (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1278 VPartitionPath(diskP),
1279 params.stats[0][diskP->index],
1280 params.stats[1][diskP->index],
1281 params.stats[2][diskP->index],
1282 params.stats[3][diskP->index]);
1285 Log("VShutdown: shutdown finished using %d threads\n", params.n_threads);
1287 /* if we're only going to run one shutdown thread, don't bother creating
1289 Log("VShutdown: beginning single-threaded fileserver shutdown\n");
1291 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1292 VShutdownByPartition_r(diskP);
1296 Log("VShutdown: complete.\n");
1299 #else /* AFS_DEMAND_ATTACH_FS */
1305 register Volume *vp, *np;
1306 register afs_int32 code;
1309 Log("VShutdown: aborting attach volumes\n");
1310 vinit_attach_abort = 1;
1311 #ifdef AFS_PTHREAD_ENV
1312 VOL_CV_WAIT(&vol_init_attach_cond);
1314 LWP_WaitProcess(VInitAttachVolumes);
1315 #endif /* AFS_PTHREAD_ENV */
1318 Log("VShutdown: shutting down on-line volumes...\n");
1319 for (i = 0; i < VolumeHashTable.Size; i++) {
1320 /* try to hold first volume in the hash table */
1321 for (queue_Scan(&VolumeHashTable.Table[i],vp,np,Volume)) {
1325 Log("VShutdown: Attempting to take volume %u offline.\n",
1328 /* next, take the volume offline (drops reference count) */
1329 VOffline_r(vp, "File server was shut down");
1333 Log("VShutdown: complete.\n");
1335 #endif /* AFS_DEMAND_ATTACH_FS */
1348 * stop new activity (e.g. SALVSYNC) from occurring
1350 * Use this to make the volume package less busy; for example, during
1351 * shutdown. This doesn't actually shutdown/detach anything in the
1352 * volume package, but prevents certain processes from ocurring. For
1353 * example, preventing new SALVSYNC communication in DAFS. In theory, we
1354 * could also use this to prevent new volume attachment, or prevent
1355 * other programs from checking out volumes, etc.
1360 #ifdef AFS_DEMAND_ATTACH_FS
1361 /* make sure we don't try to contact the salvageserver, since it may
1362 * not be around anymore */
1363 vol_disallow_salvsync = 1;
1367 #ifdef AFS_DEMAND_ATTACH_FS
1370 * shutdown control thread
1373 ShutdownController(vshutdown_thread_t * params)
1376 struct DiskPartition64 * diskP;
1378 vshutdown_thread_t shadow;
1380 ShutdownCreateSchedule(params);
1382 while ((params->pass < 4) &&
1383 (params->n_threads_complete < params->n_threads)) {
1384 /* recompute schedule once per second */
1386 memcpy(&shadow, params, sizeof(vshutdown_thread_t));
1390 Log("ShutdownController: schedule version=%d, vol_remaining=%d, pass=%d\n",
1391 shadow.schedule_version, shadow.vol_remaining, shadow.pass);
1392 Log("ShutdownController: n_threads_complete=%d, n_parts_done_pass=%d\n",
1393 shadow.n_threads_complete, shadow.n_parts_done_pass);
1394 for (diskP = DiskPartitionList; diskP; diskP=diskP->next) {
1396 Log("ShutdownController: part[%d] : (len=%d, thread_target=%d, done_pass=%d, pass_head=%p)\n",
1398 diskP->vol_list.len,
1399 shadow.part_thread_target[id],
1400 shadow.part_done_pass[id],
1401 shadow.part_pass_head[id]);
1407 ShutdownCreateSchedule(params);
1411 /* create the shutdown thread work schedule.
1412 * this scheduler tries to implement fairness
1413 * by allocating at least 1 thread to each
1414 * partition with volumes to be shutdown,
1415 * and then it attempts to allocate remaining
1416 * threads based upon the amount of work left
1419 ShutdownCreateSchedule(vshutdown_thread_t * params)
1421 struct DiskPartition64 * diskP;
1422 int sum, thr_workload, thr_left;
1423 int part_residue[VOLMAXPARTS+1];
1426 /* compute the total number of outstanding volumes */
1428 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1429 sum += diskP->vol_list.len;
1432 params->schedule_version++;
1433 params->vol_remaining = sum;
1438 /* compute average per-thread workload */
1439 thr_workload = sum / params->n_threads;
1440 if (sum % params->n_threads)
1443 thr_left = params->n_threads;
1444 memset(&part_residue, 0, sizeof(part_residue));
1446 /* for fairness, give every partition with volumes remaining
1447 * at least one thread */
1448 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1450 if (diskP->vol_list.len) {
1451 params->part_thread_target[id] = 1;
1454 params->part_thread_target[id] = 0;
1458 if (thr_left && thr_workload) {
1459 /* compute length-weighted workloads */
1462 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1464 delta = (diskP->vol_list.len / thr_workload) -
1465 params->part_thread_target[id];
1469 if (delta < thr_left) {
1470 params->part_thread_target[id] += delta;
1473 params->part_thread_target[id] += thr_left;
1481 /* try to assign any leftover threads to partitions that
1482 * had volume lengths closer to needing thread_target+1 */
1483 int max_residue, max_id = 0;
1485 /* compute the residues */
1486 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1488 part_residue[id] = diskP->vol_list.len -
1489 (params->part_thread_target[id] * thr_workload);
1492 /* now try to allocate remaining threads to partitions with the
1493 * highest residues */
1496 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1498 if (part_residue[id] > max_residue) {
1499 max_residue = part_residue[id];
1508 params->part_thread_target[max_id]++;
1510 part_residue[max_id] = 0;
1515 /* punt and give any remaining threads equally to each partition */
1517 if (thr_left >= params->n_parts) {
1518 alloc = thr_left / params->n_parts;
1519 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1521 params->part_thread_target[id] += alloc;
1526 /* finish off the last of the threads */
1527 for (diskP = DiskPartitionList; thr_left && diskP; diskP = diskP->next) {
1529 params->part_thread_target[id]++;
1535 /* worker thread for parallel shutdown */
1537 VShutdownThread(void * args)
1539 vshutdown_thread_t * params;
1540 int found, pass, schedule_version_save, count;
1541 struct DiskPartition64 *diskP;
1542 struct diskpartition_queue_t * dpq;
1545 params = (vshutdown_thread_t *) args;
1547 /* acquire the shutdown pass 0 lock */
1548 assert(pthread_mutex_lock(¶ms->lock) == 0);
1550 /* if there's still pass 0 work to be done,
1551 * get a work entry, and do a pass 0 shutdown */
1552 if (queue_IsNotEmpty(params)) {
1553 dpq = queue_First(params, diskpartition_queue_t);
1555 assert(pthread_mutex_unlock(¶ms->lock) == 0);
1561 while (ShutdownVolumeWalk_r(diskP, 0, ¶ms->part_pass_head[id]))
1563 params->stats[0][diskP->index] = count;
1564 assert(pthread_mutex_lock(¶ms->lock) == 0);
1567 params->n_threads_complete++;
1568 if (params->n_threads_complete == params->n_threads) {
1569 /* notify control thread that all workers have completed pass 0 */
1570 assert(pthread_cond_signal(¶ms->master_cv) == 0);
1572 while (params->pass == 0) {
1573 assert(pthread_cond_wait(¶ms->cv, ¶ms->lock) == 0);
1577 assert(pthread_mutex_unlock(¶ms->lock) == 0);
1580 pass = params->pass;
1583 /* now escalate through the more complicated shutdowns */
1585 schedule_version_save = params->schedule_version;
1587 /* find a disk partition to work on */
1588 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1590 if (params->part_thread_target[id] && !params->part_done_pass[id]) {
1591 params->part_thread_target[id]--;
1598 /* hmm. for some reason the controller thread couldn't find anything for
1599 * us to do. let's see if there's anything we can do */
1600 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1602 if (diskP->vol_list.len && !params->part_done_pass[id]) {
1605 } else if (!params->part_done_pass[id]) {
1606 params->part_done_pass[id] = 1;
1607 params->n_parts_done_pass++;
1609 Log("VShutdown: done shutting down volumes on partition %s.\n",
1610 VPartitionPath(diskP));
1616 /* do work on this partition until either the controller
1617 * creates a new schedule, or we run out of things to do
1618 * on this partition */
1621 while (!params->part_done_pass[id] &&
1622 (schedule_version_save == params->schedule_version)) {
1623 /* ShutdownVolumeWalk_r will drop the glock internally */
1624 if (!ShutdownVolumeWalk_r(diskP, pass, ¶ms->part_pass_head[id])) {
1625 if (!params->part_done_pass[id]) {
1626 params->part_done_pass[id] = 1;
1627 params->n_parts_done_pass++;
1629 Log("VShutdown: done shutting down volumes on partition %s.\n",
1630 VPartitionPath(diskP));
1638 params->stats[pass][id] += count;
1640 /* ok, everyone is done this pass, proceed */
1643 params->n_threads_complete++;
1644 while (params->pass == pass) {
1645 if (params->n_threads_complete == params->n_threads) {
1646 /* we are the last thread to complete, so we will
1647 * reinitialize worker pool state for the next pass */
1648 params->n_threads_complete = 0;
1649 params->n_parts_done_pass = 0;
1651 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1653 params->part_done_pass[id] = 0;
1654 params->part_pass_head[id] = queue_First(&diskP->vol_list, rx_queue);
1657 /* compute a new thread schedule before releasing all the workers */
1658 ShutdownCreateSchedule(params);
1660 /* wake up all the workers */
1661 assert(pthread_cond_broadcast(¶ms->cv) == 0);
1664 Log("VShutdown: pass %d completed using %d threads on %d partitions\n",
1665 pass, params->n_threads, params->n_parts);
1668 VOL_CV_WAIT(¶ms->cv);
1671 pass = params->pass;
1685 /* shut down all volumes on a given disk partition
1687 * note that this function will not allow mp-fast
1688 * shutdown of a partition */
1690 VShutdownByPartition_r(struct DiskPartition64 * dp)
1696 /* wait for other exclusive ops to finish */
1697 VVByPListWait_r(dp);
1699 /* begin exclusive access */
1700 VVByPListBeginExclusive_r(dp);
1702 /* pick the low-hanging fruit first,
1703 * then do the complicated ones last
1704 * (has the advantage of keeping
1705 * in-use volumes up until the bitter end) */
1706 for (pass = 0, total=0; pass < 4; pass++) {
1707 pass_stats[pass] = ShutdownVByPForPass_r(dp, pass);
1708 total += pass_stats[pass];
1711 /* end exclusive access */
1712 VVByPListEndExclusive_r(dp);
1714 Log("VShutdownByPartition: shut down %d volumes on %s (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1715 total, VPartitionPath(dp), pass_stats[0], pass_stats[1], pass_stats[2], pass_stats[3]);
1720 /* internal shutdown functionality
1722 * for multi-pass shutdown:
1723 * 0 to only "shutdown" {pre,un}attached and error state volumes
1724 * 1 to also shutdown attached volumes w/ volume header loaded
1725 * 2 to also shutdown attached volumes w/o volume header loaded
1726 * 3 to also shutdown exclusive state volumes
1728 * caller MUST hold exclusive access on the hash chain
1729 * because we drop vol_glock_mutex internally
1731 * this function is reentrant for passes 1--3
1732 * (e.g. multiple threads can cooperate to
1733 * shutdown a partition mp-fast)
1735 * pass 0 is not scaleable because the volume state data is
1736 * synchronized by vol_glock mutex, and the locking overhead
1737 * is too high to drop the lock long enough to do linked list
1741 ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass)
1743 struct rx_queue * q = queue_First(&dp->vol_list, rx_queue);
1746 while (ShutdownVolumeWalk_r(dp, pass, &q))
1752 /* conditionally shutdown one volume on partition dp
1753 * returns 1 if a volume was shutdown in this pass,
1756 ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
1757 struct rx_queue ** idx)
1759 struct rx_queue *qp, *nqp;
1764 for (queue_ScanFrom(&dp->vol_list, qp, qp, nqp, rx_queue)) {
1765 vp = (Volume *) (((char *)qp) - offsetof(Volume, vol_list));
1769 if ((V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1770 (V_attachState(vp) != VOL_STATE_ERROR) &&
1771 (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1775 if ((V_attachState(vp) == VOL_STATE_ATTACHED) &&
1776 (vp->header == NULL)) {
1780 if (VIsExclusiveState(V_attachState(vp))) {
1785 DeleteVolumeFromVByPList_r(vp);
1786 VShutdownVolume_r(vp);
1796 * shutdown a specific volume
1798 /* caller MUST NOT hold a heavyweight ref on vp */
1800 VShutdownVolume_r(Volume * vp)
1804 VCreateReservation_r(vp);
1806 if (LogLevel >= 5) {
1807 Log("VShutdownVolume_r: vid=%u, device=%d, state=%hu\n",
1808 vp->hashid, vp->partition->device, V_attachState(vp));
1811 /* wait for other blocking ops to finish */
1812 VWaitExclusiveState_r(vp);
1814 assert(VIsValidState(V_attachState(vp)));
1816 switch(V_attachState(vp)) {
1817 case VOL_STATE_SALVAGING:
1818 /* Leave salvaging volumes alone. Any in-progress salvages will
1819 * continue working after viced shuts down. This is intentional.
1822 case VOL_STATE_PREATTACHED:
1823 case VOL_STATE_ERROR:
1824 VChangeState_r(vp, VOL_STATE_UNATTACHED);
1825 case VOL_STATE_UNATTACHED:
1827 case VOL_STATE_GOING_OFFLINE:
1828 case VOL_STATE_SHUTTING_DOWN:
1829 case VOL_STATE_ATTACHED:
1833 Log("VShutdown: Attempting to take volume %u offline.\n",
1836 /* take the volume offline (drops reference count) */
1837 VOffline_r(vp, "File server was shut down");
1844 VCancelReservation_r(vp);
1848 #endif /* AFS_DEMAND_ATTACH_FS */
1851 /***************************************************/
1852 /* Header I/O routines */
1853 /***************************************************/
1855 /* open a descriptor for the inode (h),
1856 * read in an on-disk structure into buffer (to) of size (size),
1857 * verify versionstamp in structure has magic (magic) and
1858 * optionally verify version (version) if (version) is nonzero
1861 ReadHeader(Error * ec, IHandle_t * h, char *to, int size, bit32 magic,
1864 struct versionStamp *vsn;
1879 if (FDH_SEEK(fdP, 0, SEEK_SET) < 0) {
1881 FDH_REALLYCLOSE(fdP);
1884 vsn = (struct versionStamp *)to;
1885 if (FDH_READ(fdP, to, size) != size || vsn->magic != magic) {
1887 FDH_REALLYCLOSE(fdP);
1892 /* Check is conditional, in case caller wants to inspect version himself */
1893 if (version && vsn->version != version) {
1899 WriteVolumeHeader_r(Error * ec, Volume * vp)
1901 IHandle_t *h = V_diskDataHandle(vp);
1911 if (FDH_SEEK(fdP, 0, SEEK_SET) < 0) {
1913 FDH_REALLYCLOSE(fdP);
1916 if (FDH_WRITE(fdP, (char *)&V_disk(vp), sizeof(V_disk(vp)))
1917 != sizeof(V_disk(vp))) {
1919 FDH_REALLYCLOSE(fdP);
1925 /* VolumeHeaderToDisk
1926 * Allows for storing 64 bit inode numbers in on-disk volume header
1929 /* convert in-memory representation of a volume header to the
1930 * on-disk representation of a volume header */
1932 VolumeHeaderToDisk(VolumeDiskHeader_t * dh, VolumeHeader_t * h)
1935 memset(dh, 0, sizeof(VolumeDiskHeader_t));
1936 dh->stamp = h->stamp;
1938 dh->parent = h->parent;
1940 #ifdef AFS_64BIT_IOPS_ENV
1941 dh->volumeInfo_lo = (afs_int32) h->volumeInfo & 0xffffffff;
1942 dh->volumeInfo_hi = (afs_int32) (h->volumeInfo >> 32) & 0xffffffff;
1943 dh->smallVnodeIndex_lo = (afs_int32) h->smallVnodeIndex & 0xffffffff;
1944 dh->smallVnodeIndex_hi =
1945 (afs_int32) (h->smallVnodeIndex >> 32) & 0xffffffff;
1946 dh->largeVnodeIndex_lo = (afs_int32) h->largeVnodeIndex & 0xffffffff;
1947 dh->largeVnodeIndex_hi =
1948 (afs_int32) (h->largeVnodeIndex >> 32) & 0xffffffff;
1949 dh->linkTable_lo = (afs_int32) h->linkTable & 0xffffffff;
1950 dh->linkTable_hi = (afs_int32) (h->linkTable >> 32) & 0xffffffff;
1952 dh->volumeInfo_lo = h->volumeInfo;
1953 dh->smallVnodeIndex_lo = h->smallVnodeIndex;
1954 dh->largeVnodeIndex_lo = h->largeVnodeIndex;
1955 dh->linkTable_lo = h->linkTable;
1959 /* DiskToVolumeHeader
1960 * Converts an on-disk representation of a volume header to
1961 * the in-memory representation of a volume header.
1963 * Makes the assumption that AFS has *always*
1964 * zero'd the volume header file so that high parts of inode
1965 * numbers are 0 in older (SGI EFS) volume header files.
1968 DiskToVolumeHeader(VolumeHeader_t * h, VolumeDiskHeader_t * dh)
1970 memset(h, 0, sizeof(VolumeHeader_t));
1971 h->stamp = dh->stamp;
1973 h->parent = dh->parent;
1975 #ifdef AFS_64BIT_IOPS_ENV
1977 (Inode) dh->volumeInfo_lo | ((Inode) dh->volumeInfo_hi << 32);
1979 h->smallVnodeIndex =
1980 (Inode) dh->smallVnodeIndex_lo | ((Inode) dh->
1981 smallVnodeIndex_hi << 32);
1983 h->largeVnodeIndex =
1984 (Inode) dh->largeVnodeIndex_lo | ((Inode) dh->
1985 largeVnodeIndex_hi << 32);
1987 (Inode) dh->linkTable_lo | ((Inode) dh->linkTable_hi << 32);
1989 h->volumeInfo = dh->volumeInfo_lo;
1990 h->smallVnodeIndex = dh->smallVnodeIndex_lo;
1991 h->largeVnodeIndex = dh->largeVnodeIndex_lo;
1992 h->linkTable = dh->linkTable_lo;
1997 /***************************************************/
1998 /* Volume Attachment routines */
1999 /***************************************************/
2001 #ifdef AFS_DEMAND_ATTACH_FS
2003 * pre-attach a volume given its path.
2005 * @param[out] ec outbound error code
2006 * @param[in] partition partition path string
2007 * @param[in] name volume id string
2009 * @return volume object pointer
2011 * @note A pre-attached volume will only have its partition
2012 * and hashid fields initialized. At first call to
2013 * VGetVolume, the volume will be fully attached.
2017 VPreAttachVolumeByName(Error * ec, char *partition, char *name)
2021 vp = VPreAttachVolumeByName_r(ec, partition, name);
2027 * pre-attach a volume given its path.
2029 * @param[out] ec outbound error code
2030 * @param[in] partition path to vice partition
2031 * @param[in] name volume id string
2033 * @return volume object pointer
2035 * @pre VOL_LOCK held
2037 * @internal volume package internal use only.
2040 VPreAttachVolumeByName_r(Error * ec, char *partition, char *name)
2042 return VPreAttachVolumeById_r(ec,
2044 VolumeNumber(name));
2048 * pre-attach a volume given its path and numeric volume id.
2050 * @param[out] ec error code return
2051 * @param[in] partition path to vice partition
2052 * @param[in] volumeId numeric volume id
2054 * @return volume object pointer
2056 * @pre VOL_LOCK held
2058 * @internal volume package internal use only.
2061 VPreAttachVolumeById_r(Error * ec,
2066 struct DiskPartition64 *partp;
2070 assert(programType == fileServer);
2072 if (!(partp = VGetPartition_r(partition, 0))) {
2074 Log("VPreAttachVolumeById_r: Error getting partition (%s)\n", partition);
2078 vp = VLookupVolume_r(ec, volumeId, NULL);
2083 return VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2087 * preattach a volume.
2089 * @param[out] ec outbound error code
2090 * @param[in] partp pointer to partition object
2091 * @param[in] vp pointer to volume object
2092 * @param[in] vid volume id
2094 * @return volume object pointer
2096 * @pre VOL_LOCK is held.
2098 * @warning Returned volume object pointer does not have to
2099 * equal the pointer passed in as argument vp. There
2100 * are potential race conditions which can result in
2101 * the pointers having different values. It is up to
2102 * the caller to make sure that references are handled
2103 * properly in this case.
2105 * @note If there is already a volume object registered with
2106 * the same volume id, its pointer MUST be passed as
2107 * argument vp. Failure to do so will result in a silent
2108 * failure to preattach.
2110 * @internal volume package internal use only.
2113 VPreAttachVolumeByVp_r(Error * ec,
2114 struct DiskPartition64 * partp,
2122 /* check to see if pre-attach already happened */
2124 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
2125 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
2126 !VIsErrorState(V_attachState(vp))) {
2128 * pre-attach is a no-op in all but the following cases:
2130 * - volume is unattached
2131 * - volume is in an error state
2132 * - volume is pre-attached
2134 Log("VPreattachVolumeByVp_r: volume %u not in quiescent state\n", vid);
2137 /* we're re-attaching a volume; clear out some old state */
2138 memset(&vp->salvage, 0, sizeof(struct VolumeOnlineSalvage));
2140 if (V_partition(vp) != partp) {
2141 /* XXX potential race */
2142 DeleteVolumeFromVByPList_r(vp);
2145 /* if we need to allocate a new Volume struct,
2146 * go ahead and drop the vol glock, otherwise
2147 * do the basic setup synchronised, as it's
2148 * probably not worth dropping the lock */
2151 /* allocate the volume structure */
2152 vp = nvp = (Volume *) malloc(sizeof(Volume));
2154 memset(vp, 0, sizeof(Volume));
2155 queue_Init(&vp->vnode_list);
2156 assert(pthread_cond_init(&V_attachCV(vp), NULL) == 0);
2159 /* link the volume with its associated vice partition */
2160 vp->device = partp->device;
2161 vp->partition = partp;
2164 vp->specialStatus = 0;
2166 /* if we dropped the lock, reacquire the lock,
2167 * check for pre-attach races, and then add
2168 * the volume to the hash table */
2171 nvp = VLookupVolume_r(ec, vid, NULL);
2176 } else if (nvp) { /* race detected */
2181 /* hack to make up for VChangeState_r() decrementing
2182 * the old state counter */
2183 VStats.state_levels[0]++;
2187 /* put pre-attached volume onto the hash table
2188 * and bring it up to the pre-attached state */
2189 AddVolumeToHashTable(vp, vp->hashid);
2190 AddVolumeToVByPList_r(vp);
2191 VLRU_Init_Node_r(vp);
2192 VChangeState_r(vp, VOL_STATE_PREATTACHED);
2195 Log("VPreAttachVolumeByVp_r: volume %u pre-attached\n", vp->hashid);
2203 #endif /* AFS_DEMAND_ATTACH_FS */
2205 /* Attach an existing volume, given its pathname, and return a
2206 pointer to the volume header information. The volume also
2207 normally goes online at this time. An offline volume
2208 must be reattached to make it go online */
2210 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
2214 retVal = VAttachVolumeByName_r(ec, partition, name, mode);
2220 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
2222 register Volume *vp = NULL;
2223 struct DiskPartition64 *partp;
2227 #ifdef AFS_DEMAND_ATTACH_FS
2228 VolumeStats stats_save;
2230 #endif /* AFS_DEMAND_ATTACH_FS */
2234 volumeId = VolumeNumber(name);
2236 if (!(partp = VGetPartition_r(partition, 0))) {
2238 Log("VAttachVolume: Error getting partition (%s)\n", partition);
2242 if (VRequiresPartLock()) {
2244 VLockPartition_r(partition);
2245 } else if (programType == fileServer) {
2246 #ifdef AFS_DEMAND_ATTACH_FS
2247 /* lookup the volume in the hash table */
2248 vp = VLookupVolume_r(ec, volumeId, NULL);
2254 /* save any counters that are supposed to
2255 * be monotonically increasing over the
2256 * lifetime of the fileserver */
2257 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2259 memset(&stats_save, 0, sizeof(VolumeStats));
2262 /* if there's something in the hash table, and it's not
2263 * in the pre-attach state, then we may need to detach
2264 * it before proceeding */
2265 if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
2266 VCreateReservation_r(vp);
2267 VWaitExclusiveState_r(vp);
2269 /* at this point state must be one of:
2278 if (vp->specialStatus == VBUSY)
2281 /* if it's already attached, see if we can return it */
2282 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2283 VGetVolumeByVp_r(ec, vp);
2284 if (V_inUse(vp) == fileServer) {
2285 VCancelReservation_r(vp);
2289 /* otherwise, we need to detach, and attempt to re-attach */
2290 VDetachVolume_r(ec, vp);
2292 Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
2295 /* if it isn't fully attached, delete from the hash tables,
2296 and let the refcounter handle the rest */
2297 DeleteVolumeFromHashTable(vp);
2298 DeleteVolumeFromVByPList_r(vp);
2301 VCancelReservation_r(vp);
2305 /* pre-attach volume if it hasn't been done yet */
2307 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2308 (V_attachState(vp) == VOL_STATE_ERROR)) {
2310 vp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2318 /* handle pre-attach races
2320 * multiple threads can race to pre-attach a volume,
2321 * but we can't let them race beyond that
2323 * our solution is to let the first thread to bring
2324 * the volume into an exclusive state win; the other
2325 * threads just wait until it finishes bringing the
2326 * volume online, and then they do a vgetvolumebyvp
2328 if (svp && (svp != vp)) {
2329 /* wait for other exclusive ops to finish */
2330 VCreateReservation_r(vp);
2331 VWaitExclusiveState_r(vp);
2333 /* get a heavyweight ref, kill the lightweight ref, and return */
2334 VGetVolumeByVp_r(ec, vp);
2335 VCancelReservation_r(vp);
2339 /* at this point, we are chosen as the thread to do
2340 * demand attachment for this volume. all other threads
2341 * doing a getvolume on vp->hashid will block until we finish */
2343 /* make sure any old header cache entries are invalidated
2344 * before proceeding */
2345 FreeVolumeHeader(vp);
2347 VChangeState_r(vp, VOL_STATE_ATTACHING);
2349 /* restore any saved counters */
2350 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2351 #else /* AFS_DEMAND_ATTACH_FS */
2352 vp = VGetVolume_r(ec, volumeId);
2354 if (V_inUse(vp) == fileServer)
2356 if (vp->specialStatus == VBUSY)
2358 VDetachVolume_r(ec, vp);
2360 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2364 #endif /* AFS_DEMAND_ATTACH_FS */
2368 strcpy(path, VPartitionPath(partp));
2376 vp = (Volume *) calloc(1, sizeof(Volume));
2378 vp->hashid = volumeId;
2379 vp->device = partp->device;
2380 vp->partition = partp;
2381 queue_Init(&vp->vnode_list);
2382 #ifdef AFS_DEMAND_ATTACH_FS
2383 assert(pthread_cond_init(&V_attachCV(vp), NULL) == 0);
2384 #endif /* AFS_DEMAND_ATTACH_FS */
2387 /* attach2 is entered without any locks, and returns
2388 * with vol_glock_mutex held */
2389 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode);
2391 if (VCanUseFSSYNC() && vp) {
2392 #ifdef AFS_DEMAND_ATTACH_FS
2393 if ((mode == V_VOLUPD) || (VolumeWriteable(vp) && (mode == V_CLONE))) {
2394 /* mark volume header as in use so that volser crashes lead to a
2395 * salvage attempt */
2396 VUpdateVolume_r(ec, vp, 0);
2398 /* for dafs, we should tell the fileserver, except for V_PEEK
2399 * where we know it is not necessary */
2400 if (mode == V_PEEK) {
2401 vp->needsPutBack = 0;
2403 vp->needsPutBack = 1;
2405 #else /* !AFS_DEMAND_ATTACH_FS */
2406 /* duplicate computation in fssync.c about whether the server
2407 * takes the volume offline or not. If the volume isn't
2408 * offline, we must not return it when we detach the volume,
2409 * or the server will abort */
2410 if (mode == V_READONLY || mode == V_PEEK
2411 || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
2412 vp->needsPutBack = 0;
2414 vp->needsPutBack = 1;
2415 #endif /* !AFS_DEMAND_ATTACH_FS */
2417 /* OK, there's a problem here, but one that I don't know how to
2418 * fix right now, and that I don't think should arise often.
2419 * Basically, we should only put back this volume to the server if
2420 * it was given to us by the server, but since we don't have a vp,
2421 * we can't run the VolumeWriteable function to find out as we do
2422 * above when computing vp->needsPutBack. So we send it back, but
2423 * there's a path in VAttachVolume on the server which may abort
2424 * if this volume doesn't have a header. Should be pretty rare
2425 * for all of that to happen, but if it does, probably the right
2426 * fix is for the server to allow the return of readonly volumes
2427 * that it doesn't think are really checked out. */
2428 #ifdef FSSYNC_BUILD_CLIENT
2429 if (VCanUseFSSYNC() && vp == NULL &&
2430 mode != V_SECRETLY && mode != V_PEEK) {
2432 #ifdef AFS_DEMAND_ATTACH_FS
2433 /* If we couldn't attach but we scheduled a salvage, we already
2434 * notified the fileserver; don't online it now */
2435 if (*ec != VSALVAGING)
2436 #endif /* AFS_DEMAND_ATTACH_FS */
2437 FSYNC_VolOp(volumeId, partition, FSYNC_VOL_ON, 0, NULL);
2440 if (programType == fileServer && vp) {
2441 #ifdef AFS_DEMAND_ATTACH_FS
2443 * we can get here in cases where we don't "own"
2444 * the volume (e.g. volume owned by a utility).
2445 * short circuit around potential disk header races.
2447 if (V_attachState(vp) != VOL_STATE_ATTACHED) {
2451 VUpdateVolume_r(ec, vp, 0);
2453 Log("VAttachVolume: Error updating volume\n");
2458 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2459 #ifndef AFS_DEMAND_ATTACH_FS
2460 /* This is a hack: by temporarily setting the incore
2461 * dontSalvage flag ON, the volume will be put back on the
2462 * Update list (with dontSalvage OFF again). It will then
2463 * come back in N minutes with DONT_SALVAGE eventually
2464 * set. This is the way that volumes that have never had
2465 * it set get it set; or that volumes that have been
2466 * offline without DONT SALVAGE having been set also
2467 * eventually get it set */
2468 V_dontSalvage(vp) = DONT_SALVAGE;
2469 #endif /* !AFS_DEMAND_ATTACH_FS */
2470 VAddToVolumeUpdateList_r(ec, vp);
2472 Log("VAttachVolume: Error adding volume to update list\n");
2479 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2484 if (VRequiresPartLock()) {
2485 VUnlockPartition_r(partition);
2488 #ifdef AFS_DEMAND_ATTACH_FS
2489 /* attach failed; make sure we're in error state */
2490 if (vp && !VIsErrorState(V_attachState(vp))) {
2491 VChangeState_r(vp, VOL_STATE_ERROR);
2493 #endif /* AFS_DEMAND_ATTACH_FS */
2500 #ifdef AFS_DEMAND_ATTACH_FS
2501 /* VAttachVolumeByVp_r
2503 * finish attaching a volume that is
2504 * in a less than fully attached state
2506 /* caller MUST hold a ref count on vp */
2508 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
2510 char name[VMAXPATHLEN];
2512 struct DiskPartition64 *partp;
2516 Volume * nvp = NULL;
2517 VolumeStats stats_save;
2520 /* volume utility should never call AttachByVp */
2521 assert(programType == fileServer);
2523 volumeId = vp->hashid;
2524 partp = vp->partition;
2525 VolumeExternalName_r(volumeId, name, sizeof(name));
2528 /* if another thread is performing a blocking op, wait */
2529 VWaitExclusiveState_r(vp);
2531 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2533 /* if it's already attached, see if we can return it */
2534 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2535 VGetVolumeByVp_r(ec, vp);
2536 if (V_inUse(vp) == fileServer) {
2539 if (vp->specialStatus == VBUSY)
2541 VDetachVolume_r(ec, vp);
2543 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2549 /* pre-attach volume if it hasn't been done yet */
2551 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2552 (V_attachState(vp) == VOL_STATE_ERROR)) {
2553 nvp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2559 VCreateReservation_r(nvp);
2565 VChangeState_r(vp, VOL_STATE_ATTACHING);
2567 /* restore monotonically increasing stats */
2568 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2572 /* compute path to disk header */
2573 strcpy(path, VPartitionPath(partp));
2582 * NOTE: attach2 is entered without any locks, and returns
2583 * with vol_glock_mutex held */
2584 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode);
2587 * the event that an error was encountered, or
2588 * the volume was not brought to an attached state
2589 * for any reason, skip to the end. We cannot
2590 * safely call VUpdateVolume unless we "own" it.
2594 (V_attachState(vp) != VOL_STATE_ATTACHED)) {
2598 VUpdateVolume_r(ec, vp, 0);
2600 Log("VAttachVolume: Error updating volume %u\n", vp->hashid);
2604 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2605 #ifndef AFS_DEMAND_ATTACH_FS
2606 /* This is a hack: by temporarily setting the incore
2607 * dontSalvage flag ON, the volume will be put back on the
2608 * Update list (with dontSalvage OFF again). It will then
2609 * come back in N minutes with DONT_SALVAGE eventually
2610 * set. This is the way that volumes that have never had
2611 * it set get it set; or that volumes that have been
2612 * offline without DONT SALVAGE having been set also
2613 * eventually get it set */
2614 V_dontSalvage(vp) = DONT_SALVAGE;
2615 #endif /* !AFS_DEMAND_ATTACH_FS */
2616 VAddToVolumeUpdateList_r(ec, vp);
2618 Log("VAttachVolume: Error adding volume %u to update list\n", vp->hashid);
2625 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2629 VCancelReservation_r(nvp);
2632 if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2633 if (vp && !VIsErrorState(V_attachState(vp))) {
2634 VChangeState_r(vp, VOL_STATE_ERROR);
2643 * lock a volume on disk (non-blocking).
2645 * @param[in] vp The volume to lock
2646 * @param[in] locktype READ_LOCK or WRITE_LOCK
2648 * @return operation status
2649 * @retval 0 success, lock was obtained
2650 * @retval EBUSY a conflicting lock was held by another process
2651 * @retval EIO error acquiring lock
2653 * @pre If we're in the fileserver, vp is in an exclusive state
2655 * @pre vp is not already locked
2658 VLockVolumeNB(Volume *vp, int locktype)
2662 assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2663 assert(!(V_attachFlags(vp) & VOL_LOCKED));
2665 code = VLockVolumeByIdNB(vp->hashid, vp->partition, locktype);
2667 V_attachFlags(vp) |= VOL_LOCKED;
2674 * unlock a volume on disk that was locked with VLockVolumeNB.
2676 * @param[in] vp volume to unlock
2678 * @pre If we're in the fileserver, vp is in an exclusive state
2680 * @pre vp has already been locked
2683 VUnlockVolume(Volume *vp)
2685 assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2686 assert((V_attachFlags(vp) & VOL_LOCKED));
2688 VUnlockVolumeById(vp->hashid, vp->partition);
2690 V_attachFlags(vp) &= ~VOL_LOCKED;
2692 #endif /* AFS_DEMAND_ATTACH_FS */
2695 * read in a vol header, possibly lock the vol header, and possibly check out
2696 * the vol header from the fileserver, as part of volume attachment.
2698 * @param[out] ec error code
2699 * @param[in] vp volume pointer object
2700 * @param[in] partp disk partition object of the attaching partition
2701 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
2703 * @param[in] peek 1 to just try to read in the volume header and make sure
2704 * we don't try to lock the vol, or check it out from
2705 * FSSYNC or anything like that; 0 otherwise, for 'normal'
2708 * @note As part of DAFS volume attachment, the volume header may be either
2709 * read- or write-locked to ensure mutual exclusion of certain volume
2710 * operations. In some cases in order to determine whether we need to
2711 * read- or write-lock the header, we need to read in the header to see
2712 * if the volume is RW or not. So, if we read in the header under a
2713 * read-lock and determine that we actually need a write-lock on the
2714 * volume header, this function will drop the read lock, acquire a write
2715 * lock, and read the header in again.
2718 attach_volume_header(Error *ec, Volume *vp, struct DiskPartition64 *partp,
2721 struct VolumeDiskHeader diskHeader;
2722 struct VolumeHeader header;
2725 int lock_tries = 0, checkout_tries = 0;
2727 VolumeId volid = vp->hashid;
2728 #ifdef FSSYNC_BUILD_CLIENT
2729 int checkout, done_checkout = 0;
2730 #endif /* FSSYNC_BUILD_CLIENT */
2731 #ifdef AFS_DEMAND_ATTACH_FS
2732 int locktype = 0, use_locktype = -1;
2733 #endif /* AFS_DEMAND_ATTACH_FS */
2739 if (lock_tries > VOL_MAX_CHECKOUT_RETRIES) {
2740 Log("VAttachVolume: retried too many times trying to lock header for "
2741 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2742 VPartitionPath(partp));
2746 if (checkout_tries > VOL_MAX_CHECKOUT_RETRIES) {
2747 Log("VAttachVolume: retried too many times trying to checkout "
2748 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2749 VPartitionPath(partp));
2754 if (VReadVolumeDiskHeader(volid, partp, NULL)) {
2755 /* short-circuit the 'volume does not exist' case */
2760 #ifdef FSSYNC_BUILD_CLIENT
2761 checkout = !done_checkout;
2763 if (!peek && checkout && VMustCheckoutVolume(mode)) {
2765 memset(&res, 0, sizeof(res));
2767 if (FSYNC_VolOp(volid, VPartitionPath(partp), FSYNC_VOL_NEEDVOLUME, mode, &res)
2770 if (res.hdr.reason == FSYNC_SALVAGE) {
2771 Log("VAttachVolume: file server says volume %lu is salvaging\n",
2772 afs_printable_uint32_lu(volid));
2775 Log("VAttachVolume: attach of volume %lu apparently denied by file server\n",
2776 afs_printable_uint32_lu(volid));
2777 *ec = VNOVOL; /* XXXX */
2784 #ifdef AFS_DEMAND_ATTACH_FS
2785 if (use_locktype < 0) {
2786 /* don't know whether vol is RO or RW; assume it's RO and we can retry
2787 * if it turns out to be RW */
2788 locktype = VVolLockType(mode, 0);
2791 /* a previous try says we should use use_locktype to lock the volume,
2793 locktype = use_locktype;
2796 if (!peek && locktype) {
2797 code = VLockVolumeNB(vp, locktype);
2799 if (code == EBUSY) {
2800 Log("VAttachVolume: another program has vol %lu locked\n",
2801 afs_printable_uint32_lu(volid));
2803 Log("VAttachVolume: error %d trying to lock vol %lu\n",
2804 code, afs_printable_uint32_lu(volid));
2811 #endif /* AFS_DEMAND_ATTACH_FS */
2813 code = VReadVolumeDiskHeader(volid, partp, &diskHeader);
2823 DiskToVolumeHeader(&header, &diskHeader);
2825 IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header.parent,
2826 header.largeVnodeIndex);
2827 IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header.parent,
2828 header.smallVnodeIndex);
2829 IH_INIT(vp->diskDataHandle, partp->device, header.parent,
2831 IH_INIT(vp->linkHandle, partp->device, header.parent, header.linkTable);
2834 /* only need to do this once */
2836 GetVolumeHeader(vp);
2840 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2841 /* demand attach changes the V_PEEK mechanism
2843 * we can now suck the current disk data structure over
2844 * the fssync interface without going to disk
2846 * (technically, we don't need to restrict this feature
2847 * to demand attach fileservers. However, I'm trying
2848 * to limit the number of common code changes)
2850 if (VCanUseFSSYNC() && (mode == V_PEEK || peek)) {
2852 res.payload.len = sizeof(VolumeDiskData);
2853 res.payload.buf = &vp->header->diskstuff;
2855 if (FSYNC_VolOp(vp->hashid,
2857 FSYNC_VOL_QUERY_HDR,
2860 goto disk_header_loaded;
2863 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2864 (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2865 sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2867 #ifdef AFS_DEMAND_ATTACH_FS
2870 IncUInt64(&VStats.hdr_loads);
2871 IncUInt64(&vp->stats.hdr_loads);
2873 #endif /* AFS_DEMAND_ATTACH_FS */
2876 Log("VAttachVolume: Error reading diskDataHandle header for vol %lu; "
2877 "error=%u\n", afs_printable_uint32_lu(volid), *ec);
2881 #ifdef AFS_DEMAND_ATTACH_FS
2882 # ifdef FSSYNC_BUILD_CLIENT
2884 # endif /* FSSYNC_BUILD_CLIENT */
2886 /* if the lock type we actually used to lock the volume is different than
2887 * the lock type we should have used, retry with the lock type we should
2889 use_locktype = VVolLockType(mode, VolumeWriteable(vp));
2890 if (locktype != use_locktype) {
2894 #endif /* AFS_DEMAND_ATTACH_FS */
2899 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2900 if (!peek && *ec == 0 && retry == 0 && VMustCheckoutVolume(mode)) {
2902 code = FSYNC_VerifyCheckout(volid, VPartitionPath(partp), FSYNC_VOL_NEEDVOLUME, mode);
2904 if (code == SYNC_DENIED) {
2905 /* must retry checkout; fileserver no longer thinks we have
2911 } else if (code != SYNC_OK) {
2915 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2918 /* either we are going to be called again for a second pass, or we
2919 * encountered an error; clean up in either case */
2921 #ifdef AFS_DEMAND_ATTACH_FS
2922 if ((V_attachFlags(vp) & VOL_LOCKED)) {
2925 #endif /* AFS_DEMAND_ATTACH_FS */
2926 if (vp->linkHandle) {
2927 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
2928 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
2929 IH_RELEASE(vp->diskDataHandle);
2930 IH_RELEASE(vp->linkHandle);
2943 #ifdef AFS_DEMAND_ATTACH_FS
2945 attach_check_vop(Error *ec, VolumeId volid, struct DiskPartition64 *partp,
2950 if (vp->pending_vol_op) {
2954 if (vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningUnknown) {
2956 code = VVolOpLeaveOnlineNoHeader_r(vp, vp->pending_vol_op);
2958 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
2959 } else if (code == 0) {
2960 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
2963 /* we need the vol header to determine if the volume can be
2964 * left online for the vop, so... get the header */
2968 /* attach header with peek=1 to avoid checking out the volume
2969 * or locking it; we just want the header info, we're not
2970 * messing with the volume itself at all */
2971 attach_volume_header(ec, vp, partp, V_PEEK, 1);
2978 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
2979 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
2981 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
2984 /* make sure we grab a new vol header and re-open stuff on
2985 * actual attachment; we can't keep the data we grabbed, since
2986 * it was not done under a lock and thus not safe */
2987 FreeVolumeHeader(vp);
2988 VReleaseVolumeHandles_r(vp);
2991 /* see if the pending volume op requires exclusive access */
2992 switch (vp->pending_vol_op->vol_op_state) {
2993 case FSSYNC_VolOpPending:
2994 /* this should never happen */
2995 assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpPending);
2998 case FSSYNC_VolOpRunningUnknown:
2999 /* this should never happen; we resolved 'unknown' above */
3000 assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
3003 case FSSYNC_VolOpRunningOffline:
3004 /* mark the volume down */
3006 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3008 /* do not set V_offlineMessage here; we don't have ownership of
3009 * the volume (and probably do not have the header loaded), so we
3010 * can't alter the disk header */
3012 /* check to see if we should set the specialStatus flag */
3013 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
3014 vp->specialStatus = VBUSY;
3025 #endif /* AFS_DEMAND_ATTACH_FS */
3028 * volume attachment helper function.
3030 * @param[out] ec error code
3031 * @param[in] volumeId volume ID of the attaching volume
3032 * @param[in] path full path to the volume header .vol file
3033 * @param[in] partp disk partition object for the attaching partition
3034 * @param[in] vp volume object; vp->hashid, vp->device, vp->partition,
3035 * vp->vnode_list, and V_attachCV (for DAFS) should already
3037 * @param[in] isbusy 1 if vp->specialStatus should be set to VBUSY; that is,
3038 * if there is a volume operation running for this volume
3039 * that should set the volume to VBUSY during its run. 0
3040 * otherwise. (see VVolOpSetVBusy_r)
3041 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
3044 * @return pointer to the semi-attached volume pointer
3045 * @retval NULL an error occurred (check value of *ec)
3046 * @retval vp volume successfully attaching
3048 * @pre no locks held
3050 * @post VOL_LOCK held
3053 attach2(Error * ec, VolId volumeId, char *path, struct DiskPartition64 *partp,
3054 Volume * vp, int isbusy, int mode)
3056 /* have we read in the header successfully? */
3057 int read_header = 0;
3059 /* should we FreeVolume(vp) instead of VCheckFree(vp) in the error
3065 vp->vnodeIndex[vLarge].handle = NULL;
3066 vp->vnodeIndex[vSmall].handle = NULL;
3067 vp->diskDataHandle = NULL;
3068 vp->linkHandle = NULL;
3070 #ifdef AFS_DEMAND_ATTACH_FS
3071 attach_check_vop(ec, volumeId, partp, vp);
3073 attach_volume_header(ec, vp, partp, mode, 0);
3076 attach_volume_header(ec, vp, partp, mode, 0);
3077 #endif /* !AFS_DEMAND_ATTACH_FS */
3079 if (*ec == VNOVOL) {
3080 /* if the volume doesn't exist, skip straight to 'error' so we don't
3081 * request a salvage */
3088 vp->specialStatus = (byte) (isbusy ? VBUSY : 0);
3089 vp->shuttingDown = 0;
3090 vp->goingOffline = 0;
3092 #ifdef AFS_DEMAND_ATTACH_FS
3093 vp->stats.last_attach = FT_ApproxTime();
3094 vp->stats.attaches++;
3098 IncUInt64(&VStats.attaches);
3099 vp->cacheCheck = ++VolumeCacheCheck;
3100 /* just in case this ever rolls over */
3101 if (!vp->cacheCheck)
3102 vp->cacheCheck = ++VolumeCacheCheck;
3105 #ifdef AFS_DEMAND_ATTACH_FS
3106 V_attachFlags(vp) |= VOL_HDR_LOADED;
3107 vp->stats.last_hdr_load = vp->stats.last_attach;
3108 #endif /* AFS_DEMAND_ATTACH_FS */
3112 struct IndexFileHeader iHead;
3114 #if OPENAFS_VOL_STATS
3116 * We just read in the diskstuff part of the header. If the detailed
3117 * volume stats area has not yet been initialized, we should bzero the
3118 * area and mark it as initialized.
3120 if (!(V_stat_initialized(vp))) {
3121 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
3122 V_stat_initialized(vp) = 1;
3124 #endif /* OPENAFS_VOL_STATS */
3126 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
3127 (char *)&iHead, sizeof(iHead),
3128 SMALLINDEXMAGIC, SMALLINDEXVERSION);
3131 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
3136 struct IndexFileHeader iHead;
3138 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
3139 (char *)&iHead, sizeof(iHead),
3140 LARGEINDEXMAGIC, LARGEINDEXVERSION);
3143 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
3147 #ifdef AFS_NAMEI_ENV
3149 struct versionStamp stamp;
3151 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
3152 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
3155 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
3158 #endif /* AFS_NAMEI_ENV */
3160 #if defined(AFS_DEMAND_ATTACH_FS)
3161 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
3163 if (!VCanScheduleSalvage()) {
3164 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3166 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3171 /* volume operation in progress */
3175 #else /* AFS_DEMAND_ATTACH_FS */
3177 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3181 #endif /* AFS_DEMAND_ATTACH_FS */
3183 if (V_needsSalvaged(vp)) {
3184 if (vp->specialStatus)
3185 vp->specialStatus = 0;
3187 #if defined(AFS_DEMAND_ATTACH_FS)
3188 if (!VCanScheduleSalvage()) {
3189 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
3191 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
3194 #else /* AFS_DEMAND_ATTACH_FS */
3196 #endif /* AFS_DEMAND_ATTACH_FS */
3202 vp->nextVnodeUnique = V_uniquifier(vp);
3204 #ifndef FAST_RESTART
3205 if (VShouldCheckInUse(mode) && V_inUse(vp) && VolumeWriteable(vp)) {
3206 if (!V_needsSalvaged(vp)) {
3207 V_needsSalvaged(vp) = 1;
3208 VUpdateVolume_r(ec, vp, 0);
3210 #if defined(AFS_DEMAND_ATTACH_FS)
3211 if (!VCanScheduleSalvage()) {
3212 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3214 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
3217 #else /* AFS_DEMAND_ATTACH_FS */
3218 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3220 #endif /* AFS_DEMAND_ATTACH_FS */
3224 #endif /* FAST_RESTART */
3226 if (programType == fileServer && V_destroyMe(vp) == DESTROY_ME) {
3227 /* Only check destroyMe if we are the fileserver, since the
3228 * volserver et al sometimes need to work with volumes with
3229 * destroyMe set. Examples are 'temporary' volumes the
3230 * volserver creates, and when we create a volume (destroyMe
3231 * is set on creation; sometimes a separate volserver
3232 * transaction is created to clear destroyMe).
3235 #if defined(AFS_DEMAND_ATTACH_FS)
3236 /* schedule a salvage so the volume goes away on disk */
3237 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3238 VChangeState_r(vp, VOL_STATE_ERROR);
3240 #endif /* AFS_DEMAND_ATTACH_FS */
3241 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
3247 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
3248 #ifndef BITMAP_LATER
3249 if (programType == fileServer && VolumeWriteable(vp)) {
3251 for (i = 0; i < nVNODECLASSES; i++) {
3252 VGetBitmap_r(ec, vp, i);
3254 #ifdef AFS_DEMAND_ATTACH_FS
3255 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3257 #endif /* AFS_DEMAND_ATTACH_FS */
3258 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
3264 #endif /* BITMAP_LATER */
3266 if (VInit >= 2 && V_needsCallback(vp)) {
3267 if (V_BreakVolumeCallbacks) {
3268 Log("VAttachVolume: Volume %lu was changed externally; breaking callbacks\n",
3269 afs_printable_uint32_lu(V_id(vp)));
3270 V_needsCallback(vp) = 0;
3272 (*V_BreakVolumeCallbacks) (V_id(vp));
3275 VUpdateVolume_r(ec, vp, 0);
3277 #ifdef FSSYNC_BUILD_CLIENT
3278 else if (VCanUseFSSYNC()) {
3279 afs_int32 fsync_code;
3281 V_needsCallback(vp) = 0;
3283 fsync_code = FSYNC_VolOp(V_id(vp), NULL, FSYNC_VOL_BREAKCBKS, FSYNC_WHATEVER, NULL);
3287 V_needsCallback(vp) = 1;
3288 Log("Error trying to tell the fileserver to break callbacks for "
3289 "changed volume %lu; error code %ld\n",
3290 afs_printable_uint32_lu(V_id(vp)),
3291 afs_printable_int32_ld(fsync_code));
3293 VUpdateVolume_r(ec, vp, 0);
3296 #endif /* FSSYNC_BUILD_CLIENT */
3299 Log("VAttachVolume: error %d clearing needsCallback on volume "
3300 "%lu; needs salvage\n", (int)*ec,
3301 afs_printable_uint32_lu(V_id(vp)));
3302 #ifdef AFS_DEMAND_ATTACH_FS
3303 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3305 #else /* !AFS_DEMAND_ATTACH_FS */
3307 #endif /* !AFS_DEMAND_ATTACh_FS */
3312 if (programType == fileServer) {
3313 if (vp->specialStatus)
3314 vp->specialStatus = 0;
3315 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
3316 V_inUse(vp) = fileServer;
3317 V_offlineMessage(vp)[0] = '\0';
3320 #ifdef AFS_DEMAND_ATTACH_FS
3321 if ((mode != V_PEEK) && (mode != V_SECRETLY))
3322 V_inUse(vp) = programType;
3323 #endif /* AFS_DEMAND_ATTACH_FS */
3324 V_checkoutMode(vp) = mode;
3327 AddVolumeToHashTable(vp, V_id(vp));
3328 #ifdef AFS_DEMAND_ATTACH_FS
3329 if (VCanUnlockAttached() && (V_attachFlags(vp) & VOL_LOCKED)) {
3332 if ((programType != fileServer) ||
3333 (V_inUse(vp) == fileServer)) {
3334 AddVolumeToVByPList_r(vp);
3336 VChangeState_r(vp, VOL_STATE_ATTACHED);
3338 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3345 #ifdef AFS_DEMAND_ATTACH_FS
3346 if (!VIsErrorState(V_attachState(vp))) {
3347 VChangeState_r(vp, VOL_STATE_ERROR);
3349 #endif /* AFS_DEMAND_ATTACH_FS */
3352 VReleaseVolumeHandles_r(vp);
3355 #ifdef AFS_DEMAND_ATTACH_FS
3362 #else /* !AFS_DEMAND_ATTACH_FS */
3364 #endif /* !AFS_DEMAND_ATTACH_FS */
3368 /* Attach an existing volume.
3369 The volume also normally goes online at this time.
3370 An offline volume must be reattached to make it go online.
3374 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
3378 retVal = VAttachVolume_r(ec, volumeId, mode);
3384 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
3387 VGetVolumePath(ec, volumeId, &part, &name);
3389 register Volume *vp;
3391 vp = VGetVolume_r(&error, volumeId);
3393 assert(V_inUse(vp) == 0);
3394 VDetachVolume_r(ec, vp);
3398 return VAttachVolumeByName_r(ec, part, name, mode);
3401 /* Increment a reference count to a volume, sans context swaps. Requires
3402 * possibly reading the volume header in from the disk, since there's
3403 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
3405 * N.B. This call can fail if we can't read in the header!! In this case
3406 * we still guarantee we won't context swap, but the ref count won't be
3407 * incremented (otherwise we'd violate the invariant).
3409 /* NOTE: with the demand attach fileserver extensions, the global lock
3410 * is dropped within VHold */
3411 #ifdef AFS_DEMAND_ATTACH_FS
3413 VHold_r(register Volume * vp)
3417 VCreateReservation_r(vp);
3418 VWaitExclusiveState_r(vp);
3420 LoadVolumeHeader(&error, vp);
3422 VCancelReservation_r(vp);
3426 VCancelReservation_r(vp);
3429 #else /* AFS_DEMAND_ATTACH_FS */
3431 VHold_r(register Volume * vp)
3435 LoadVolumeHeader(&error, vp);
3441 #endif /* AFS_DEMAND_ATTACH_FS */
3445 VHold(register Volume * vp)
3449 retVal = VHold_r(vp);
3456 /***************************************************/
3457 /* get and put volume routines */
3458 /***************************************************/
3461 * put back a heavyweight reference to a volume object.
3463 * @param[in] vp volume object pointer
3465 * @pre VOL_LOCK held
3467 * @post heavyweight volume reference put back.
3468 * depending on state, volume may have been taken offline,
3469 * detached, salvaged, freed, etc.
3471 * @internal volume package internal use only
3474 VPutVolume_r(register Volume * vp)
3476 assert(--vp->nUsers >= 0);
3477 if (vp->nUsers == 0) {
3479 ReleaseVolumeHeader(vp->header);
3480 #ifdef AFS_DEMAND_ATTACH_FS
3481 if (!VCheckDetach(vp)) {
3485 #else /* AFS_DEMAND_ATTACH_FS */
3487 #endif /* AFS_DEMAND_ATTACH_FS */
3492 VPutVolume(register Volume * vp)
3500 /* Get a pointer to an attached volume. The pointer is returned regardless
3501 of whether or not the volume is in service or on/off line. An error
3502 code, however, is returned with an indication of the volume's status */
3504 VGetVolume(Error * ec, Error * client_ec, VolId volumeId)
3508 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
3513 /* same as VGetVolume, but if a volume is waiting to go offline, we return
3514 * that it is actually offline, instead of waiting for it to go offline */
3516 VGetVolumeNoWait(Error * ec, Error * client_ec, VolId volumeId)
3520 retVal = GetVolume(ec, client_ec, volumeId, NULL, 1);
3526 VGetVolume_r(Error * ec, VolId volumeId)
3528 return GetVolume(ec, NULL, volumeId, NULL, 0);
3531 /* try to get a volume we've previously looked up */
3532 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
3534 VGetVolumeByVp_r(Error * ec, Volume * vp)
3536 return GetVolume(ec, NULL, vp->hashid, vp, 0);
3540 * private interface for getting a volume handle
3542 * @param[out] ec error code (0 if no error)
3543 * @param[out] client_ec wire error code to be given to clients
3544 * @param[in] volumeId ID of the volume we want
3545 * @param[in] hint optional hint for hash lookups, or NULL
3546 * @param[in] nowait 0 to wait for a 'goingOffline' volume to go offline
3547 * before returning, 1 to return immediately
3549 * @return a volume handle for the specified volume
3550 * @retval NULL an error occurred, or the volume is in such a state that
3551 * we cannot load a header or return any volume struct
3553 * @note for DAFS, caller must NOT hold a ref count on 'hint'
3556 GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint, int nowait)
3559 /* pull this profiling/debugging code out of regular builds */
3561 #define VGET_CTR_INC(x) x++
3562 unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
3563 0, V7 = 0, V8 = 0, V9 = 0;
3564 unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
3566 #define VGET_CTR_INC(x)
3568 #ifdef AFS_DEMAND_ATTACH_FS
3569 Volume *avp, * rvp = hint;
3573 * if VInit is zero, the volume package dynamic
3574 * data structures have not been initialized yet,
3575 * and we must immediately return an error
3581 *client_ec = VOFFLINE;
3586 #ifdef AFS_DEMAND_ATTACH_FS
3588 VCreateReservation_r(rvp);
3590 #endif /* AFS_DEMAND_ATTACH_FS */
3598 vp = VLookupVolume_r(ec, volumeId, vp);
3604 #ifdef AFS_DEMAND_ATTACH_FS
3605 if (rvp && (rvp != vp)) {
3606 /* break reservation on old vp */
3607 VCancelReservation_r(rvp);
3610 #endif /* AFS_DEMAND_ATTACH_FS */
3616 /* Until we have reached an initialization level of 2
3617 * we don't know whether this volume exists or not.
3618 * We can't sleep and retry later because before a volume
3619 * is attached, the caller tries to get it first. Just
3620 * return VOFFLINE and the caller can choose whether to
3621 * retry the command or not. */
3631 IncUInt64(&VStats.hdr_gets);
3633 #ifdef AFS_DEMAND_ATTACH_FS
3634 /* block if someone else is performing an exclusive op on this volume */
3637 VCreateReservation_r(rvp);
3639 VWaitExclusiveState_r(vp);
3641 /* short circuit with VNOVOL in the following circumstances:
3644 * - VOL_STATE_SHUTTING_DOWN
3646 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
3647 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN) ||
3648 (V_attachState(vp) == VOL_STATE_GOING_OFFLINE)) {
3655 * short circuit with VOFFLINE in the following circumstances:
3657 * - VOL_STATE_UNATTACHED
3659 if (V_attachState(vp) == VOL_STATE_UNATTACHED) {
3660 if (vp->specialStatus) {
3661 *ec = vp->specialStatus;
3669 /* allowable states:
3675 if (vp->salvage.requested) {
3676 VUpdateSalvagePriority_r(vp);
3679 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
3680 avp = VAttachVolumeByVp_r(ec, vp, 0);
3683 /* VAttachVolumeByVp_r can return a pointer
3684 * != the vp passed to it under certain
3685 * conditions; make sure we don't leak
3686 * reservations if that happens */
3688 VCancelReservation_r(rvp);
3690 VCreateReservation_r(rvp);
3700 if (!vp->pending_vol_op) {
3715 if ((V_attachState(vp) == VOL_STATE_SALVAGING) ||
3716 (*ec == VSALVAGING)) {
3718 /* see CheckVnode() in afsfileprocs.c for an explanation
3719 * of this error code logic */
3720 afs_uint32 now = FT_ApproxTime();
3721 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
3724 *client_ec = VRESTARTING;
3733 #ifdef AFS_DEMAND_ATTACH_FS
3735 * this test MUST happen after VAttachVolymeByVp, so vol_op_state is
3736 * not VolOpRunningUnknown (attach2 would have converted it to Online
3740 /* only valid before/during demand attachment */
3741 assert(!vp->pending_vol_op || vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
3743 /* deny getvolume due to running mutually exclusive vol op */
3744 if (vp->pending_vol_op && vp->pending_vol_op->vol_op_state==FSSYNC_VolOpRunningOffline) {
3746 * volume cannot remain online during this volume operation.
3749 if (vp->specialStatus) {
3751 * special status codes outrank normal VOFFLINE code
3753 *ec = vp->specialStatus;
3755 *client_ec = vp->specialStatus;
3759 /* see CheckVnode() in afsfileprocs.c for an explanation
3760 * of this error code logic */
3761 afs_uint32 now = FT_ApproxTime();
3762 if ((vp->stats.last_vol_op + (10 * 60)) >= now) {
3765 *client_ec = VRESTARTING;
3770 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3771 FreeVolumeHeader(vp);
3775 #endif /* AFS_DEMAND_ATTACH_FS */
3777 LoadVolumeHeader(ec, vp);
3780 /* Only log the error if it was a totally unexpected error. Simply
3781 * a missing inode is likely to be caused by the volume being deleted */
3782 if (errno != ENXIO || LogLevel)
3783 Log("Volume %u: couldn't reread volume header\n",
3785 #ifdef AFS_DEMAND_ATTACH_FS
3786 if (VCanScheduleSalvage()) {
3787 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3792 #else /* AFS_DEMAND_ATTACH_FS */
3795 #endif /* AFS_DEMAND_ATTACH_FS */
3800 if (vp->shuttingDown) {
3807 if (programType == fileServer) {
3809 if (vp->goingOffline && !nowait) {
3811 #ifdef AFS_DEMAND_ATTACH_FS
3812 /* wait for the volume to go offline */
3813 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
3814 VWaitStateChange_r(vp);
3816 #elif defined(AFS_PTHREAD_ENV)
3817 VOL_CV_WAIT(&vol_put_volume_cond);
3818 #else /* AFS_PTHREAD_ENV */
3819 LWP_WaitProcess(VPutVolume);
3820 #endif /* AFS_PTHREAD_ENV */
3823 if (vp->specialStatus) {
3825 *ec = vp->specialStatus;
3826 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3829 } else if (V_inUse(vp) == 0 || vp->goingOffline) {
3840 #ifdef AFS_DEMAND_ATTACH_FS
3841 /* if no error, bump nUsers */
3844 VLRU_UpdateAccess_r(vp);
3847 VCancelReservation_r(rvp);
3850 if (client_ec && !*client_ec) {
3853 #else /* AFS_DEMAND_ATTACH_FS */
3854 /* if no error, bump nUsers */
3861 #endif /* AFS_DEMAND_ATTACH_FS */
3869 /***************************************************/
3870 /* Volume offline/detach routines */
3871 /***************************************************/
3873 /* caller MUST hold a heavyweight ref on vp */
3874 #ifdef AFS_DEMAND_ATTACH_FS
3876 VTakeOffline_r(register Volume * vp)
3880 assert(vp->nUsers > 0);
3881 assert(programType == fileServer);
3883 VCreateReservation_r(vp);
3884 VWaitExclusiveState_r(vp);
3886 vp->goingOffline = 1;
3887 V_needsSalvaged(vp) = 1;
3889 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
3890 VCancelReservation_r(vp);
3892 #else /* AFS_DEMAND_ATTACH_FS */
3894 VTakeOffline_r(register Volume * vp)
3896 assert(vp->nUsers > 0);
3897 assert(programType == fileServer);
3899 vp->goingOffline = 1;
3900 V_needsSalvaged(vp) = 1;
3902 #endif /* AFS_DEMAND_ATTACH_FS */
3905 VTakeOffline(register Volume * vp)
3913 * force a volume offline.
3915 * @param[in] vp volume object pointer
3916 * @param[in] flags flags (see note below)
3918 * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
3919 * used when VUpdateVolume_r needs to call VForceOffline_r
3920 * (which in turn would normally call VUpdateVolume_r)
3922 * @see VUpdateVolume_r
3924 * @pre VOL_LOCK must be held.
3925 * for DAFS, caller must hold ref.
3927 * @note for DAFS, it _is safe_ to call this function from an
3930 * @post needsSalvaged flag is set.
3931 * for DAFS, salvage is requested.
3932 * no further references to the volume through the volume
3933 * package will be honored.
3934 * all file descriptor and vnode caches are invalidated.
3936 * @warning this is a heavy-handed interface. it results in
3937 * a volume going offline regardless of the current
3938 * reference count state.
3940 * @internal volume package internal use only
3943 VForceOffline_r(Volume * vp, int flags)
3947 #ifdef AFS_DEMAND_ATTACH_FS
3948 VChangeState_r(vp, VOL_STATE_ERROR);
3953 strcpy(V_offlineMessage(vp),
3954 "Forced offline due to internal error: volume needs to be salvaged");
3955 Log("Volume %u forced offline: it needs salvaging!\n", V_id(vp));
3958 vp->goingOffline = 0;
3959 V_needsSalvaged(vp) = 1;
3960 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
3961 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
3964 #ifdef AFS_DEMAND_ATTACH_FS
3965 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3966 #endif /* AFS_DEMAND_ATTACH_FS */
3968 #ifdef AFS_PTHREAD_ENV
3969 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3970 #else /* AFS_PTHREAD_ENV */
3971 LWP_NoYieldSignal(VPutVolume);
3972 #endif /* AFS_PTHREAD_ENV */
3974 VReleaseVolumeHandles_r(vp);
3978 * force a volume offline.
3980 * @param[in] vp volume object pointer
3982 * @see VForceOffline_r
3985 VForceOffline(Volume * vp)
3988 VForceOffline_r(vp, 0);
3992 /* The opposite of VAttachVolume. The volume header is written to disk, with
3993 the inUse bit turned off. A copy of the header is maintained in memory,
3994 however (which is why this is VOffline, not VDetach).
3997 VOffline_r(Volume * vp, char *message)
3999 #ifndef AFS_DEMAND_ATTACH_FS
4001 VolumeId vid = V_id(vp);
4004 assert(programType != volumeUtility && programType != volumeServer);
4009 if (V_offlineMessage(vp)[0] == '\0')
4010 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4011 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4013 vp->goingOffline = 1;
4014 #ifdef AFS_DEMAND_ATTACH_FS
4015 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4016 VCreateReservation_r(vp);
4019 /* wait for the volume to go offline */
4020 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
4021 VWaitStateChange_r(vp);
4023 VCancelReservation_r(vp);
4024 #else /* AFS_DEMAND_ATTACH_FS */
4026 vp = VGetVolume_r(&error, vid); /* Wait for it to go offline */
4027 if (vp) /* In case it was reattached... */
4029 #endif /* AFS_DEMAND_ATTACH_FS */
4032 #ifdef AFS_DEMAND_ATTACH_FS
4034 * Take a volume offline in order to perform a volume operation.
4036 * @param[inout] ec address in which to store error code
4037 * @param[in] vp volume object pointer
4038 * @param[in] message volume offline status message
4041 * - VOL_LOCK is held
4042 * - caller MUST hold a heavyweight ref on vp
4045 * - volume is taken offline
4046 * - if possible, volume operation is promoted to running state
4047 * - on failure, *ec is set to nonzero
4049 * @note Although this function does not return any value, it may
4050 * still fail to promote our pending volume operation to
4051 * a running state. Any caller MUST check the value of *ec,
4052 * and MUST NOT blindly assume success.
4054 * @warning if the caller does not hold a lightweight ref on vp,
4055 * then it MUST NOT reference vp after this function
4056 * returns to the caller.
4058 * @internal volume package internal use only
4061 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
4063 assert(vp->pending_vol_op);
4069 if (V_offlineMessage(vp)[0] == '\0')
4070 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4071 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4073 vp->goingOffline = 1;
4074 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4075 VCreateReservation_r(vp);
4078 /* Wait for the volume to go offline */
4079 while (!VIsOfflineState(V_attachState(vp))) {
4080 /* do not give corrupted volumes to the volserver */
4081 if (vp->salvage.requested && vp->pending_vol_op->com.programType != salvageServer) {
4085 VWaitStateChange_r(vp);
4089 VCancelReservation_r(vp);
4091 #endif /* AFS_DEMAND_ATTACH_FS */
4094 VOffline(Volume * vp, char *message)
4097 VOffline_r(vp, message);
4101 /* This gets used for the most part by utility routines that don't want
4102 * to keep all the volume headers around. Generally, the file server won't
4103 * call this routine, because then the offline message in the volume header
4104 * (or other information) won't be available to clients. For NAMEI, also
4105 * close the file handles. However, the fileserver does call this during
4106 * an attach following a volume operation.
4109 VDetachVolume_r(Error * ec, Volume * vp)
4112 struct DiskPartition64 *tpartp;
4113 int notifyServer = 0;
4114 int useDone = FSYNC_VOL_ON;
4116 *ec = 0; /* always "succeeds" */
4117 if (VCanUseFSSYNC()) {
4118 notifyServer = vp->needsPutBack;
4119 if (V_destroyMe(vp) == DESTROY_ME)
4120 useDone = FSYNC_VOL_DONE;
4121 #ifdef AFS_DEMAND_ATTACH_FS
4122 else if (!V_blessed(vp) || !V_inService(vp))
4123 useDone = FSYNC_VOL_LEAVE_OFF;
4126 tpartp = vp->partition;
4128 DeleteVolumeFromHashTable(vp);
4129 vp->shuttingDown = 1;
4130 #ifdef AFS_DEMAND_ATTACH_FS
4131 DeleteVolumeFromVByPList_r(vp);
4133 VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
4135 if (programType != fileServer)
4137 #endif /* AFS_DEMAND_ATTACH_FS */
4139 /* Will be detached sometime in the future--this is OK since volume is offline */
4141 /* XXX the following code should really be moved to VCheckDetach() since the volume
4142 * is not technically detached until the refcounts reach zero
4144 #ifdef FSSYNC_BUILD_CLIENT
4145 if (VCanUseFSSYNC() && notifyServer) {
4147 * Note: The server is not notified in the case of a bogus volume
4148 * explicitly to make it possible to create a volume, do a partial
4149 * restore, then abort the operation without ever putting the volume
4150 * online. This is essential in the case of a volume move operation
4151 * between two partitions on the same server. In that case, there
4152 * would be two instances of the same volume, one of them bogus,
4153 * which the file server would attempt to put on line
4155 FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
4156 /* XXX this code path is only hit by volume utilities, thus
4157 * V_BreakVolumeCallbacks will always be NULL. if we really
4158 * want to break callbacks in this path we need to use FSYNC_VolOp() */
4160 /* Dettaching it so break all callbacks on it */
4161 if (V_BreakVolumeCallbacks) {
4162 Log("volume %u detached; breaking all call backs\n", volume);
4163 (*V_BreakVolumeCallbacks) (volume);
4167 #endif /* FSSYNC_BUILD_CLIENT */
4171 VDetachVolume(Error * ec, Volume * vp)
4174 VDetachVolume_r(ec, vp);
4179 /***************************************************/
4180 /* Volume fd/inode handle closing routines */
4181 /***************************************************/
4183 /* For VDetachVolume, we close all cached file descriptors, but keep
4184 * the Inode handles in case we need to read from a busy volume.
4186 /* for demand attach, caller MUST hold ref count on vp */
4188 VCloseVolumeHandles_r(Volume * vp)
4190 #ifdef AFS_DEMAND_ATTACH_FS
4191 VolState state_save;
4193 state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
4198 * XXX need to investigate whether we can perform
4199 * DFlushVolume outside of vol_glock_mutex...
4201 * VCloseVnodeFiles_r drops the glock internally */
4202 DFlushVolume(vp->hashid);
4203 VCloseVnodeFiles_r(vp);
4205 #ifdef AFS_DEMAND_ATTACH_FS
4209 /* Too time consuming and unnecessary for the volserver */
4210 if (programType == fileServer) {
4211 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4212 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4213 IH_CONDSYNC(vp->diskDataHandle);
4215 IH_CONDSYNC(vp->linkHandle);
4216 #endif /* AFS_NT40_ENV */
4219 IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
4220 IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
4221 IH_REALLYCLOSE(vp->diskDataHandle);
4222 IH_REALLYCLOSE(vp->linkHandle);
4224 #ifdef AFS_DEMAND_ATTACH_FS
4225 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4230 VChangeState_r(vp, state_save);
4234 /* For both VForceOffline and VOffline, we close all relevant handles.
4235 * For VOffline, if we re-attach the volume, the files may possible be
4236 * different than before.
4238 /* for demand attach, caller MUST hold a ref count on vp */
4240 VReleaseVolumeHandles_r(Volume * vp)
4242 #ifdef AFS_DEMAND_ATTACH_FS
4243 VolState state_save;
4245 state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
4248 /* XXX need to investigate whether we can perform
4249 * DFlushVolume outside of vol_glock_mutex... */
4250 DFlushVolume(vp->hashid);
4252 VReleaseVnodeFiles_r(vp); /* releases the glock internally */
4254 #ifdef AFS_DEMAND_ATTACH_FS
4258 /* Too time consuming and unnecessary for the volserver */
4259 if (programType == fileServer) {
4260 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4261 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4262 IH_CONDSYNC(vp->diskDataHandle);
4264 IH_CONDSYNC(vp->linkHandle);
4265 #endif /* AFS_NT40_ENV */
4268 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
4269 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
4270 IH_RELEASE(vp->diskDataHandle);
4271 IH_RELEASE(vp->linkHandle);
4273 #ifdef AFS_DEMAND_ATTACH_FS
4274 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4279 VChangeState_r(vp, state_save);
4284 /***************************************************/
4285 /* Volume write and fsync routines */
4286 /***************************************************/
4289 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
4291 #ifdef AFS_DEMAND_ATTACH_FS
4292 VolState state_save;
4294 if (flags & VOL_UPDATE_WAIT) {
4295 VCreateReservation_r(vp);
4296 VWaitExclusiveState_r(vp);
4301 if (programType == fileServer)
4303 (V_inUse(vp) ? V_nextVnodeUnique(vp) +
4304 200 : V_nextVnodeUnique(vp));
4306 #ifdef AFS_DEMAND_ATTACH_FS
4307 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4311 WriteVolumeHeader_r(ec, vp);
4313 #ifdef AFS_DEMAND_ATTACH_FS
4315 VChangeState_r(vp, state_save);
4316 if (flags & VOL_UPDATE_WAIT) {
4317 VCancelReservation_r(vp);
4322 Log("VUpdateVolume: error updating volume header, volume %u (%s)\n",
4323 V_id(vp), V_name(vp));
4324 /* try to update on-disk header,
4325 * while preventing infinite recursion */
4326 if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
4327 VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
4333 VUpdateVolume(Error * ec, Volume * vp)
4336 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4341 VSyncVolume_r(Error * ec, Volume * vp, int flags)
4345 #ifdef AFS_DEMAND_ATTACH_FS
4346 VolState state_save;
4349 if (flags & VOL_SYNC_WAIT) {
4350 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4352 VUpdateVolume_r(ec, vp, 0);
4355 #ifdef AFS_DEMAND_ATTACH_FS
4356 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4359 fdP = IH_OPEN(V_diskDataHandle(vp));
4360 assert(fdP != NULL);
4361 code = FDH_SYNC(fdP);
4364 #ifdef AFS_DEMAND_ATTACH_FS
4366 VChangeState_r(vp, state_save);
4372 VSyncVolume(Error * ec, Volume * vp)
4375 VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
4380 /***************************************************/
4381 /* Volume dealloaction routines */
4382 /***************************************************/
4384 #ifdef AFS_DEMAND_ATTACH_FS
4386 FreeVolume(Volume * vp)
4388 /* free the heap space, iff it's safe.
4389 * otherwise, pull it out of the hash table, so it
4390 * will get deallocated when all refs to it go away */
4391 if (!VCheckFree(vp)) {
4392 DeleteVolumeFromHashTable(vp);
4393 DeleteVolumeFromVByPList_r(vp);
4395 /* make sure we invalidate the header cache entry */
4396 FreeVolumeHeader(vp);
4399 #endif /* AFS_DEMAND_ATTACH_FS */
4402 ReallyFreeVolume(Volume * vp)
4407 #ifdef AFS_DEMAND_ATTACH_FS
4409 VChangeState_r(vp, VOL_STATE_FREED);
4410 if (vp->pending_vol_op)
4411 free(vp->pending_vol_op);
4412 #endif /* AFS_DEMAND_ATTACH_FS */
4413 for (i = 0; i < nVNODECLASSES; i++)
4414 if (vp->vnodeIndex[i].bitmap)
4415 free(vp->vnodeIndex[i].bitmap);
4416 FreeVolumeHeader(vp);
4417 #ifndef AFS_DEMAND_ATTACH_FS
4418 DeleteVolumeFromHashTable(vp);
4419 #endif /* AFS_DEMAND_ATTACH_FS */
4423 /* check to see if we should shutdown this volume
4424 * returns 1 if volume was freed, 0 otherwise */
4425 #ifdef AFS_DEMAND_ATTACH_FS
4427 VCheckDetach(register Volume * vp)
4432 if (vp->nUsers || vp->nWaiters)
4435 if (vp->shuttingDown) {
4437 if ((programType != fileServer) &&
4438 (V_inUse(vp) == programType) &&
4439 ((V_checkoutMode(vp) == V_VOLUPD) ||
4440 (V_checkoutMode(vp) == V_SECRETLY) ||
4441 ((V_checkoutMode(vp) == V_CLONE) &&
4442 (VolumeWriteable(vp))))) {
4444 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
4446 Log("VCheckDetach: volume header update for volume %u "
4447 "failed with errno %d\n", vp->hashid, errno);
4450 VReleaseVolumeHandles_r(vp);
4452 ReallyFreeVolume(vp);
4453 if (programType == fileServer) {
4454 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
4459 #else /* AFS_DEMAND_ATTACH_FS */
4461 VCheckDetach(register Volume * vp)
4469 if (vp->shuttingDown) {
4471 if ((programType != fileServer) &&
4472 (V_inUse(vp) == programType) &&
4473 ((V_checkoutMode(vp) == V_VOLUPD) ||
4474 (V_checkoutMode(vp) == V_SECRETLY) ||
4475 ((V_checkoutMode(vp) == V_CLONE) &&
4476 (VolumeWriteable(vp))))) {
4478 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
4480 Log("VCheckDetach: volume header update for volume %u failed with errno %d\n",
4484 VReleaseVolumeHandles_r(vp);
4485 ReallyFreeVolume(vp);
4486 if (programType == fileServer) {
4487 #if defined(AFS_PTHREAD_ENV)
4488 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
4489 #else /* AFS_PTHREAD_ENV */
4490 LWP_NoYieldSignal(VPutVolume);
4491 #endif /* AFS_PTHREAD_ENV */
4496 #endif /* AFS_DEMAND_ATTACH_FS */
4498 /* check to see if we should offline this volume
4499 * return 1 if volume went offline, 0 otherwise */
4500 #ifdef AFS_DEMAND_ATTACH_FS
4502 VCheckOffline(register Volume * vp)
4506 if (vp->goingOffline && !vp->nUsers) {
4508 assert(programType == fileServer);
4509 assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
4510 (V_attachState(vp) != VOL_STATE_FREED) &&
4511 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
4512 (V_attachState(vp) != VOL_STATE_UNATTACHED));
4516 * VOL_STATE_GOING_OFFLINE
4517 * VOL_STATE_SHUTTING_DOWN
4518 * VIsErrorState(V_attachState(vp))
4519 * VIsExclusiveState(V_attachState(vp))
4522 VCreateReservation_r(vp);
4523 VChangeState_r(vp, VOL_STATE_OFFLINING);
4526 /* must clear the goingOffline flag before we drop the glock */
4527 vp->goingOffline = 0;
4532 /* perform async operations */
4533 VUpdateVolume_r(&error, vp, 0);
4534 VCloseVolumeHandles_r(vp);
4537 if (V_offlineMessage(vp)[0]) {
4538 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
4539 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
4540 V_offlineMessage(vp));
4542 Log("VOffline: Volume %lu (%s) is now offline\n",
4543 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
4547 /* invalidate the volume header cache entry */
4548 FreeVolumeHeader(vp);
4550 /* if nothing changed state to error or salvaging,
4551 * drop state to unattached */
4552 if (!VIsErrorState(V_attachState(vp))) {
4553 VChangeState_r(vp, VOL_STATE_UNATTACHED);
4555 VCancelReservation_r(vp);
4556 /* no usage of vp is safe beyond this point */
4560 #else /* AFS_DEMAND_ATTACH_FS */
4562 VCheckOffline(register Volume * vp)
4566 if (vp->goingOffline && !vp->nUsers) {
4568 assert(programType == fileServer);
4571 vp->goingOffline = 0;
4573 VUpdateVolume_r(&error, vp, 0);
4574 VCloseVolumeHandles_r(vp);
4576 Log("VOffline: Volume %u (%s) is now offline", V_id(vp),
4578 if (V_offlineMessage(vp)[0])
4579 Log(" (%s)", V_offlineMessage(vp));
4582 FreeVolumeHeader(vp);
4583 #ifdef AFS_PTHREAD_ENV
4584 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
4585 #else /* AFS_PTHREAD_ENV */
4586 LWP_NoYieldSignal(VPutVolume);
4587 #endif /* AFS_PTHREAD_ENV */
4591 #endif /* AFS_DEMAND_ATTACH_FS */
4593 /***************************************************/
4594 /* demand attach fs ref counting routines */
4595 /***************************************************/
4597 #ifdef AFS_DEMAND_ATTACH_FS
4598 /* the following two functions handle reference counting for
4599 * asynchronous operations on volume structs.
4601 * their purpose is to prevent a VDetachVolume or VShutdown
4602 * from free()ing the Volume struct during an async i/o op */
4604 /* register with the async volume op ref counter */
4605 /* VCreateReservation_r moved into inline code header because it
4606 * is now needed in vnode.c -- tkeiser 11/20/2007
4610 * decrement volume-package internal refcount.
4612 * @param vp volume object pointer
4614 * @internal volume package internal use only
4617 * @arg VOL_LOCK is held
4618 * @arg lightweight refcount held
4620 * @post volume waiters refcount is decremented; volume may
4621 * have been deallocated/shutdown/offlined/salvaged/
4622 * whatever during the process
4624 * @warning once you have tossed your last reference (you can acquire
4625 * lightweight refs recursively) it is NOT SAFE to reference
4626 * a volume object pointer ever again
4628 * @see VCreateReservation_r
4630 * @note DEMAND_ATTACH_FS only
4633 VCancelReservation_r(Volume * vp)
4635 assert(--vp->nWaiters >= 0);
4636 if (vp->nWaiters == 0) {
4638 if (!VCheckDetach(vp)) {
4645 /* check to see if we should free this volume now
4646 * return 1 if volume was freed, 0 otherwise */
4648 VCheckFree(Volume * vp)
4651 if ((vp->nUsers == 0) &&
4652 (vp->nWaiters == 0) &&
4653 !(V_attachFlags(vp) & (VOL_IN_HASH |
4657 ReallyFreeVolume(vp);
4662 #endif /* AFS_DEMAND_ATTACH_FS */
4665 /***************************************************/
4666 /* online volume operations routines */
4667 /***************************************************/
4669 #ifdef AFS_DEMAND_ATTACH_FS
4671 * register a volume operation on a given volume.
4673 * @param[in] vp volume object
4674 * @param[in] vopinfo volume operation info object
4676 * @pre VOL_LOCK is held
4678 * @post volume operation info object attached to volume object.
4679 * volume operation statistics updated.
4681 * @note by "attached" we mean a copy of the passed in object is made
4683 * @internal volume package internal use only
4686 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4688 FSSYNC_VolOp_info * info;
4690 /* attach a vol op info node to the volume struct */
4691 info = (FSSYNC_VolOp_info *) malloc(sizeof(FSSYNC_VolOp_info));
4692 assert(info != NULL);
4693 memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
4694 vp->pending_vol_op = info;
4697 vp->stats.last_vol_op = FT_ApproxTime();
4698 vp->stats.vol_ops++;
4699 IncUInt64(&VStats.vol_ops);
4705 * deregister the volume operation attached to this volume.
4707 * @param[in] vp volume object pointer
4709 * @pre VOL_LOCK is held
4711 * @post the volume operation info object is detached from the volume object
4713 * @internal volume package internal use only
4716 VDeregisterVolOp_r(Volume * vp)
4718 if (vp->pending_vol_op) {
4719 free(vp->pending_vol_op);
4720 vp->pending_vol_op = NULL;
4724 #endif /* AFS_DEMAND_ATTACH_FS */
4727 * determine whether it is safe to leave a volume online during
4728 * the volume operation described by the vopinfo object.
4730 * @param[in] vp volume object
4731 * @param[in] vopinfo volume operation info object
4733 * @return whether it is safe to leave volume online
4734 * @retval 0 it is NOT SAFE to leave the volume online
4735 * @retval 1 it is safe to leave the volume online during the operation
4738 * @arg VOL_LOCK is held
4739 * @arg disk header attached to vp (heavyweight ref on vp will guarantee
4740 * this condition is met)
4742 * @internal volume package internal use only
4745 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4747 return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
4748 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4749 (vopinfo->com.reason == V_READONLY ||
4750 (!VolumeWriteable(vp) &&
4751 (vopinfo->com.reason == V_CLONE ||
4752 vopinfo->com.reason == V_DUMP)))));
4756 * same as VVolOpLeaveOnline_r, but does not require a volume with an attached
4759 * @param[in] vp volume object
4760 * @param[in] vopinfo volume operation info object
4762 * @return whether it is safe to leave volume online
4763 * @retval 0 it is NOT SAFE to leave the volume online
4764 * @retval 1 it is safe to leave the volume online during the operation
4765 * @retval -1 unsure; volume header is required in order to know whether or
4766 * not is is safe to leave the volume online
4768 * @pre VOL_LOCK is held
4770 * @internal volume package internal use only
4773 VVolOpLeaveOnlineNoHeader_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4775 /* follow the logic in VVolOpLeaveOnline_r; this is the same, except
4776 * assume that we don't know VolumeWriteable; return -1 if the answer
4777 * depends on VolumeWriteable */
4779 if (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline) {
4782 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4783 vopinfo->com.reason == V_READONLY) {
4787 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4788 (vopinfo->com.reason == V_CLONE ||
4789 vopinfo->com.reason == V_DUMP)) {
4791 /* must know VolumeWriteable */
4798 * determine whether VBUSY should be set during this volume operation.
4800 * @param[in] vp volume object
4801 * @param[in] vopinfo volume operation info object
4803 * @return whether VBUSY should be set
4804 * @retval 0 VBUSY does NOT need to be set
4805 * @retval 1 VBUSY SHOULD be set
4807 * @pre VOL_LOCK is held
4809 * @internal volume package internal use only
4812 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4814 return ((vopinfo->com.command == FSYNC_VOL_OFF &&
4815 vopinfo->com.reason == FSYNC_SALVAGE) ||
4816 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4817 (vopinfo->com.reason == V_CLONE ||
4818 vopinfo->com.reason == V_DUMP)));
4822 /***************************************************/
4823 /* online salvager routines */
4824 /***************************************************/
4825 #if defined(AFS_DEMAND_ATTACH_FS)
4827 * check whether a salvage needs to be performed on this volume.
4829 * @param[in] vp pointer to volume object
4831 * @return status code
4832 * @retval 0 no salvage scheduled
4833 * @retval 1 a salvage has been scheduled with the salvageserver
4835 * @pre VOL_LOCK is held
4837 * @post if salvage request flag is set and nUsers and nWaiters are zero,
4838 * then a salvage will be requested
4840 * @note this is one of the event handlers called by VCancelReservation_r
4842 * @see VCancelReservation_r
4844 * @internal volume package internal use only.
4847 VCheckSalvage(register Volume * vp)
4850 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
4851 if (vp->nUsers || vp->nWaiters)
4853 if (vp->salvage.requested) {
4854 VScheduleSalvage_r(vp);
4857 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
4862 * request volume salvage.
4864 * @param[out] ec computed client error code
4865 * @param[in] vp volume object pointer
4866 * @param[in] reason reason code (passed to salvageserver via SALVSYNC)
4867 * @param[in] flags see flags note below
4870 * VOL_SALVAGE_INVALIDATE_HEADER causes volume header cache entry
4871 * to be invalidated.
4873 * @pre VOL_LOCK is held.
4875 * @post volume state is changed.
4876 * for fileserver, salvage will be requested once refcount reaches zero.
4878 * @return operation status code
4879 * @retval 0 volume salvage will occur
4880 * @retval 1 volume salvage could not be scheduled
4884 * @note in the fileserver, this call does not synchronously schedule a volume
4885 * salvage. rather, it sets volume state so that when volume refcounts
4886 * reach zero, a volume salvage will occur. by "refcounts", we mean both
4887 * nUsers and nWaiters must be zero.
4889 * @internal volume package internal use only.
4892 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
4896 * for DAFS volume utilities that are not supposed to schedule salvages,
4897 * just transition to error state instead
4899 if (!VCanScheduleSalvage()) {
4900 VChangeState_r(vp, VOL_STATE_ERROR);
4905 if (programType != fileServer && !VCanUseFSSYNC()) {
4906 VChangeState_r(vp, VOL_STATE_ERROR);
4911 if (!vp->salvage.requested) {
4912 vp->salvage.requested = 1;
4913 vp->salvage.reason = reason;
4914 vp->stats.last_salvage = FT_ApproxTime();
4916 /* Note that it is not possible for us to reach this point if a
4917 * salvage is already running on this volume (even if the fileserver
4918 * was restarted during the salvage). If a salvage were running, the
4919 * salvager would have write-locked the volume header file, so when
4920 * we tried to lock the volume header, the lock would have failed,
4921 * and we would have failed during attachment prior to calling
4922 * VRequestSalvage. So we know that we can schedule salvages without
4923 * fear of a salvage already running for this volume. */
4925 if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
4926 VChangeState_r(vp, VOL_STATE_SALVAGING);
4929 Log("VRequestSalvage: volume %u online salvaged too many times; forced offline.\n", vp->hashid);
4931 /* make sure neither VScheduleSalvage_r nor
4932 * VUpdateSalvagePriority_r try to schedule another salvage */
4933 vp->salvage.requested = vp->salvage.scheduled = 0;
4935 VChangeState_r(vp, VOL_STATE_ERROR);
4939 if (flags & VOL_SALVAGE_INVALIDATE_HEADER) {
4940 /* Instead of ReleaseVolumeHeader, we do FreeVolumeHeader()
4941 so that the the next VAttachVolumeByVp_r() invocation
4942 of attach2() will pull in a cached header
4943 entry and fail, then load a fresh one from disk and attach
4946 FreeVolumeHeader(vp);
4953 * update salvageserver scheduling priority for a volume.
4955 * @param[in] vp pointer to volume object
4957 * @return operation status
4959 * @retval 1 request denied, or SALVSYNC communications failure
4961 * @pre VOL_LOCK is held.
4963 * @post in-core salvage priority counter is incremented. if at least
4964 * SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
4965 * last SALVSYNC_RAISEPRIO request, we contact the salvageserver
4966 * to update its priority queue. if no salvage is scheduled,
4967 * this function is a no-op.
4969 * @note DAFS fileserver only
4971 * @note this should be called whenever a VGetVolume fails due to a
4972 * pending salvage request
4974 * @todo should set exclusive state and drop glock around salvsync call
4976 * @internal volume package internal use only.
4979 VUpdateSalvagePriority_r(Volume * vp)
4983 #ifdef SALVSYNC_BUILD_CLIENT
4988 now = FT_ApproxTime();
4990 /* update the salvageserver priority queue occasionally so that
4991 * frequently requested volumes get moved to the head of the queue
4993 if ((vp->salvage.scheduled) &&
4994 (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
4995 code = SALVSYNC_SalvageVolume(vp->hashid,
4996 VPartitionPath(vp->partition),
5001 vp->stats.last_salvage_req = now;
5002 if (code != SYNC_OK) {
5006 #endif /* SALVSYNC_BUILD_CLIENT */
5011 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5013 /* A couple of little helper functions. These return true if we tried to
5014 * use this mechanism to schedule a salvage, false if we haven't tried.
5015 * If we did try a salvage then the results are contained in code.
5019 try_SALVSYNC(Volume *vp, char *partName, int *code) {
5020 #ifdef SALVSYNC_BUILD_CLIENT
5021 if (VCanUseSALVSYNC()) {
5022 Log("Scheduling salvage for volume %lu on part %s over SALVSYNC\n",
5023 afs_printable_uint32_lu(vp->hashid), partName);
5025 /* can't use V_id() since there's no guarantee
5026 * we have the disk data header at this point */
5027 *code = SALVSYNC_SalvageVolume(vp->hashid,
5040 try_FSSYNC(Volume *vp, char *partName, int *code) {
5041 #ifdef FSSYNC_BUILD_CLIENT
5042 if (VCanUseFSSYNC()) {
5043 Log("Scheduling salvage for volume %lu on part %s over FSSYNC\n",
5044 afs_printable_uint32_lu(vp->hashid), partName);
5047 * If we aren't the fileserver, tell the fileserver the volume
5048 * needs to be salvaged. We could directly tell the
5049 * salvageserver, but the fileserver keeps track of some stats
5050 * related to salvages, and handles some other salvage-related
5051 * complications for us.
5053 *code = FSYNC_VolOp(vp->hashid, partName,
5054 FSYNC_VOL_FORCE_ERROR, FSYNC_SALVAGE, NULL);
5057 #endif /* FSSYNC_BUILD_CLIENT */
5062 * schedule a salvage with the salvage server or fileserver.
5064 * @param[in] vp pointer to volume object
5066 * @return operation status
5067 * @retval 0 salvage scheduled successfully
5068 * @retval 1 salvage not scheduled, or SALVSYNC/FSSYNC com error
5071 * @arg VOL_LOCK is held.
5072 * @arg nUsers and nWaiters should be zero.
5074 * @post salvageserver or fileserver is sent a salvage request
5076 * @note If we are the fileserver, the request will be sent to the salvage
5077 * server over SALVSYNC. If we are not the fileserver, the request will be
5078 * sent to the fileserver over FSSYNC (FSYNC_VOL_FORCE_ERROR/FSYNC_SALVAGE).
5082 * @internal volume package internal use only.
5085 VScheduleSalvage_r(Volume * vp)
5089 VolState state_save;
5090 VThreadOptions_t * thread_opts;
5093 assert(VCanUseSALVSYNC() || VCanUseFSSYNC());
5095 if (vp->nWaiters || vp->nUsers) {
5099 /* prevent endless salvage,attach,salvage,attach,... loops */
5100 if (vp->stats.salvages >= SALVAGE_COUNT_MAX)
5104 * don't perform salvsync ops on certain threads
5106 thread_opts = pthread_getspecific(VThread_key);
5107 if (thread_opts == NULL) {
5108 thread_opts = &VThread_defaults;
5110 if (thread_opts->disallow_salvsync || vol_disallow_salvsync) {
5115 * XXX the scheduling process should really be done asynchronously
5116 * to avoid fssync deadlocks
5118 if (!vp->salvage.scheduled) {
5119 /* if we haven't previously scheduled a salvage, do so now
5121 * set the volume to an exclusive state and drop the lock
5122 * around the SALVSYNC call
5124 * note that we do NOT acquire a reservation here -- doing so
5125 * could result in unbounded recursion
5127 strlcpy(partName, VPartitionPath(vp->partition), sizeof(partName));
5128 state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
5131 assert(try_SALVSYNC(vp, partName, &code) ||
5132 try_FSSYNC(vp, partName, &code));
5135 VChangeState_r(vp, state_save);
5137 if (code == SYNC_OK) {
5138 vp->salvage.scheduled = 1;
5139 vp->stats.last_salvage_req = FT_ApproxTime();
5140 if (VCanUseSALVSYNC()) {
5141 /* don't record these stats for non-fileservers; let the
5142 * fileserver take care of these */
5143 vp->stats.salvages++;
5144 IncUInt64(&VStats.salvages);
5149 case SYNC_BAD_COMMAND:
5150 case SYNC_COM_ERROR:
5153 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5154 "denied\n", afs_printable_uint32_lu(vp->hashid));
5157 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5158 "received unknown protocol error %d\n",
5159 afs_printable_uint32_lu(vp->hashid), code);
5163 if (VCanUseFSSYNC()) {
5164 VChangeState_r(vp, VOL_STATE_ERROR);
5170 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5172 #ifdef SALVSYNC_BUILD_CLIENT
5175 * connect to the salvageserver SYNC service.
5177 * @return operation status
5181 * @post connection to salvageserver SYNC service established
5183 * @see VConnectSALV_r
5184 * @see VDisconnectSALV
5185 * @see VReconnectSALV
5192 retVal = VConnectSALV_r();
5198 * connect to the salvageserver SYNC service.
5200 * @return operation status
5204 * @pre VOL_LOCK is held.
5206 * @post connection to salvageserver SYNC service established
5209 * @see VDisconnectSALV_r
5210 * @see VReconnectSALV_r
5211 * @see SALVSYNC_clientInit
5213 * @internal volume package internal use only.
5216 VConnectSALV_r(void)
5218 return SALVSYNC_clientInit();
5222 * disconnect from the salvageserver SYNC service.
5224 * @return operation status
5227 * @pre client should have a live connection to the salvageserver
5229 * @post connection to salvageserver SYNC service destroyed
5231 * @see VDisconnectSALV_r
5233 * @see VReconnectSALV
5236 VDisconnectSALV(void)
5239 VDisconnectSALV_r();
5245 * disconnect from the salvageserver SYNC service.
5247 * @return operation status
5251 * @arg VOL_LOCK is held.
5252 * @arg client should have a live connection to the salvageserver.
5254 * @post connection to salvageserver SYNC service destroyed
5256 * @see VDisconnectSALV
5257 * @see VConnectSALV_r
5258 * @see VReconnectSALV_r
5259 * @see SALVSYNC_clientFinis
5261 * @internal volume package internal use only.
5264 VDisconnectSALV_r(void)
5266 return SALVSYNC_clientFinis();
5270 * disconnect and then re-connect to the salvageserver SYNC service.
5272 * @return operation status
5276 * @pre client should have a live connection to the salvageserver
5278 * @post old connection is dropped, and a new one is established
5281 * @see VDisconnectSALV
5282 * @see VReconnectSALV_r
5285 VReconnectSALV(void)
5289 retVal = VReconnectSALV_r();
5295 * disconnect and then re-connect to the salvageserver SYNC service.
5297 * @return operation status
5302 * @arg VOL_LOCK is held.
5303 * @arg client should have a live connection to the salvageserver.
5305 * @post old connection is dropped, and a new one is established
5307 * @see VConnectSALV_r
5308 * @see VDisconnectSALV
5309 * @see VReconnectSALV
5310 * @see SALVSYNC_clientReconnect
5312 * @internal volume package internal use only.
5315 VReconnectSALV_r(void)
5317 return SALVSYNC_clientReconnect();
5319 #endif /* SALVSYNC_BUILD_CLIENT */
5320 #endif /* AFS_DEMAND_ATTACH_FS */
5323 /***************************************************/
5324 /* FSSYNC routines */
5325 /***************************************************/
5327 /* This must be called by any volume utility which needs to run while the
5328 file server is also running. This is separated from VInitVolumePackage2 so
5329 that a utility can fork--and each of the children can independently
5330 initialize communication with the file server */
5331 #ifdef FSSYNC_BUILD_CLIENT
5333 * connect to the fileserver SYNC service.
5335 * @return operation status
5340 * @arg VInit must equal 2.
5341 * @arg Program Type must not be fileserver or salvager.
5343 * @post connection to fileserver SYNC service established
5346 * @see VDisconnectFS
5347 * @see VChildProcReconnectFS
5354 retVal = VConnectFS_r();
5360 * connect to the fileserver SYNC service.
5362 * @return operation status
5367 * @arg VInit must equal 2.
5368 * @arg Program Type must not be fileserver or salvager.
5369 * @arg VOL_LOCK is held.
5371 * @post connection to fileserver SYNC service established
5374 * @see VDisconnectFS_r
5375 * @see VChildProcReconnectFS_r
5377 * @internal volume package internal use only.
5383 assert((VInit == 2) &&
5384 (programType != fileServer) &&
5385 (programType != salvager));
5386 rc = FSYNC_clientInit();
5393 * disconnect from the fileserver SYNC service.
5396 * @arg client should have a live connection to the fileserver.
5397 * @arg VOL_LOCK is held.
5398 * @arg Program Type must not be fileserver or salvager.
5400 * @post connection to fileserver SYNC service destroyed
5402 * @see VDisconnectFS
5404 * @see VChildProcReconnectFS_r
5406 * @internal volume package internal use only.
5409 VDisconnectFS_r(void)
5411 assert((programType != fileServer) &&
5412 (programType != salvager));
5413 FSYNC_clientFinis();
5418 * disconnect from the fileserver SYNC service.
5421 * @arg client should have a live connection to the fileserver.
5422 * @arg Program Type must not be fileserver or salvager.
5424 * @post connection to fileserver SYNC service destroyed
5426 * @see VDisconnectFS_r
5428 * @see VChildProcReconnectFS
5439 * connect to the fileserver SYNC service from a child process following a fork.
5441 * @return operation status
5446 * @arg VOL_LOCK is held.
5447 * @arg current FSYNC handle is shared with a parent process
5449 * @post current FSYNC handle is discarded and a new connection to the
5450 * fileserver SYNC service is established
5452 * @see VChildProcReconnectFS
5454 * @see VDisconnectFS_r
5456 * @internal volume package internal use only.
5459 VChildProcReconnectFS_r(void)
5461 return FSYNC_clientChildProcReconnect();
5465 * connect to the fileserver SYNC service from a child process following a fork.
5467 * @return operation status
5471 * @pre current FSYNC handle is shared with a parent process
5473 * @post current FSYNC handle is discarded and a new connection to the
5474 * fileserver SYNC service is established
5476 * @see VChildProcReconnectFS_r
5478 * @see VDisconnectFS
5481 VChildProcReconnectFS(void)
5485 ret = VChildProcReconnectFS_r();
5489 #endif /* FSSYNC_BUILD_CLIENT */
5492 /***************************************************/
5493 /* volume bitmap routines */
5494 /***************************************************/
5497 * allocate a vnode bitmap number for the vnode
5499 * @param[out] ec error code
5500 * @param[in] vp volume object pointer
5501 * @param[in] index vnode index number for the vnode
5502 * @param[in] flags flag values described in note
5504 * @note for DAFS, flags parameter controls locking behavior.
5505 * If (flags & VOL_ALLOC_BITMAP_WAIT) is set, then this function
5506 * will create a reservation and block on any other exclusive
5507 * operations. Otherwise, this function assumes the caller
5508 * already has exclusive access to vp, and we just change the
5511 * @pre VOL_LOCK held
5513 * @return bit number allocated
5519 VAllocBitmapEntry_r(Error * ec, Volume * vp,
5520 struct vnodeIndex *index, int flags)
5523 register byte *bp, *ep;
5524 #ifdef AFS_DEMAND_ATTACH_FS
5525 VolState state_save;
5526 #endif /* AFS_DEMAND_ATTACH_FS */
5530 /* This test is probably redundant */
5531 if (!VolumeWriteable(vp)) {
5532 *ec = (bit32) VREADONLY;
5536 #ifdef AFS_DEMAND_ATTACH_FS
5537 if (flags & VOL_ALLOC_BITMAP_WAIT) {
5538 VCreateReservation_r(vp);
5539 VWaitExclusiveState_r(vp);
5541 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
5542 #endif /* AFS_DEMAND_ATTACH_FS */
5545 if ((programType == fileServer) && !index->bitmap) {
5547 #ifndef AFS_DEMAND_ATTACH_FS
5548 /* demand attach fs uses the volume state to avoid races.
5549 * specialStatus field is not used at all */
5551 if (vp->specialStatus == VBUSY) {
5552 if (vp->goingOffline) { /* vos dump waiting for the volume to
5553 * go offline. We probably come here
5554 * from AddNewReadableResidency */
5557 while (vp->specialStatus == VBUSY) {
5558 #ifdef AFS_PTHREAD_ENV
5562 #else /* !AFS_PTHREAD_ENV */
5564 #endif /* !AFS_PTHREAD_ENV */
5568 #endif /* !AFS_DEMAND_ATTACH_FS */
5570 if (!index->bitmap) {
5571 #ifndef AFS_DEMAND_ATTACH_FS
5572 vp->specialStatus = VBUSY; /* Stop anyone else from using it. */
5573 #endif /* AFS_DEMAND_ATTACH_FS */
5574 for (i = 0; i < nVNODECLASSES; i++) {
5575 VGetBitmap_r(ec, vp, i);
5577 #ifdef AFS_DEMAND_ATTACH_FS
5578 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
5579 #else /* AFS_DEMAND_ATTACH_FS */
5580 DeleteVolumeFromHashTable(vp);
5581 vp->shuttingDown = 1; /* Let who has it free it. */
5582 vp->specialStatus = 0;
5583 #endif /* AFS_DEMAND_ATTACH_FS */
5587 #ifndef AFS_DEMAND_ATTACH_FS
5589 vp->specialStatus = 0; /* Allow others to have access. */
5590 #endif /* AFS_DEMAND_ATTACH_FS */
5593 #endif /* BITMAP_LATER */
5595 #ifdef AFS_DEMAND_ATTACH_FS
5597 #endif /* AFS_DEMAND_ATTACH_FS */
5598 bp = index->bitmap + index->bitmapOffset;
5599 ep = index->bitmap + index->bitmapSize;
5601 if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
5603 index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
5606 o = ffs(~*bp) - 1; /* ffs is documented in BSTRING(3) */
5608 ret = ((bp - index->bitmap) * 8 + o);
5609 #ifdef AFS_DEMAND_ATTACH_FS
5611 #endif /* AFS_DEMAND_ATTACH_FS */
5614 bp += sizeof(bit32) /* i.e. 4 */ ;
5616 /* No bit map entry--must grow bitmap */
5618 realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
5621 bp += index->bitmapSize;
5622 memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
5623 index->bitmapOffset = index->bitmapSize;
5624 index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
5626 ret = index->bitmapOffset * 8;
5627 #ifdef AFS_DEMAND_ATTACH_FS
5629 #endif /* AFS_DEMAND_ATTACH_FS */
5632 #ifdef AFS_DEMAND_ATTACH_FS
5633 VChangeState_r(vp, state_save);
5634 if (flags & VOL_ALLOC_BITMAP_WAIT) {
5635 VCancelReservation_r(vp);
5637 #endif /* AFS_DEMAND_ATTACH_FS */
5642 VAllocBitmapEntry(Error * ec, Volume * vp, register struct vnodeIndex * index)
5646 retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
5652 VFreeBitMapEntry_r(Error * ec, register struct vnodeIndex *index,
5655 unsigned int offset;
5661 #endif /* BITMAP_LATER */
5662 offset = bitNumber >> 3;
5663 if (offset >= index->bitmapSize) {
5667 if (offset < index->bitmapOffset)
5668 index->bitmapOffset = offset & ~3; /* Truncate to nearest bit32 */
5669 *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
5673 VFreeBitMapEntry(Error * ec, register struct vnodeIndex *index,
5677 VFreeBitMapEntry_r(ec, index, bitNumber);
5681 /* this function will drop the glock internally.
5682 * for old pthread fileservers, this is safe thanks to vbusy.
5684 * for demand attach fs, caller must have already called
5685 * VCreateReservation_r and VWaitExclusiveState_r */
5687 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
5689 StreamHandle_t *file;
5690 afs_sfsize_t nVnodes, size;
5691 struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
5692 struct vnodeIndex *vip = &vp->vnodeIndex[class];
5693 struct VnodeDiskObject *vnode;
5694 unsigned int unique = 0;
5698 #endif /* BITMAP_LATER */
5699 #ifdef AFS_DEMAND_ATTACH_FS
5700 VolState state_save;
5701 #endif /* AFS_DEMAND_ATTACH_FS */
5705 #ifdef AFS_DEMAND_ATTACH_FS
5706 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
5707 #endif /* AFS_DEMAND_ATTACH_FS */
5710 fdP = IH_OPEN(vip->handle);
5711 assert(fdP != NULL);
5712 file = FDH_FDOPEN(fdP, "r");
5713 assert(file != NULL);
5714 vnode = (VnodeDiskObject *) malloc(vcp->diskSize);
5715 assert(vnode != NULL);
5716 size = OS_SIZE(fdP->fd_fd);
5718 nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
5720 vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4; /* The 10 is a little extra so
5721 * a few files can be created in this volume,
5722 * the whole thing is rounded up to nearest 4
5723 * bytes, because the bit map allocator likes
5726 BitMap = (byte *) calloc(1, vip->bitmapSize);
5727 assert(BitMap != NULL);
5728 #else /* BITMAP_LATER */
5729 vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
5730 assert(vip->bitmap != NULL);
5731 vip->bitmapOffset = 0;
5732 #endif /* BITMAP_LATER */
5733 if (STREAM_SEEK(file, vcp->diskSize, 0) != -1) {
5735 for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
5736 if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
5738 if (vnode->type != vNull) {
5739 if (vnode->vnodeMagic != vcp->magic) {
5740 Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
5745 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
5746 #else /* BITMAP_LATER */
5747 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
5748 #endif /* BITMAP_LATER */
5749 if (unique <= vnode->uniquifier)
5750 unique = vnode->uniquifier + 1;
5752 #ifndef AFS_PTHREAD_ENV
5753 if ((bitNumber & 0x00ff) == 0x0ff) { /* every 256 iterations */
5756 #endif /* !AFS_PTHREAD_ENV */
5759 if (vp->nextVnodeUnique < unique) {
5760 Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
5763 /* Paranoia, partly justified--I think fclose after fdopen
5764 * doesn't seem to close fd. In any event, the documentation
5765 * doesn't specify, so it's safer to close it twice.
5773 /* There may have been a racing condition with some other thread, both
5774 * creating the bitmaps for this volume. If the other thread was faster
5775 * the pointer to bitmap should already be filled and we can free ours.
5777 if (vip->bitmap == NULL) {
5778 vip->bitmap = BitMap;
5779 vip->bitmapOffset = 0;
5781 free((byte *) BitMap);
5782 #endif /* BITMAP_LATER */
5783 #ifdef AFS_DEMAND_ATTACH_FS
5784 VChangeState_r(vp, state_save);
5785 #endif /* AFS_DEMAND_ATTACH_FS */
5789 /***************************************************/
5790 /* Volume Path and Volume Number utility routines */
5791 /***************************************************/
5794 * find the first occurrence of a volume header file and return the path.
5796 * @param[out] ec outbound error code
5797 * @param[in] volumeId volume id to find
5798 * @param[out] partitionp pointer to disk partition path string
5799 * @param[out] namep pointer to volume header file name string
5801 * @post path to first occurrence of volume header is returned in partitionp
5802 * and namep, or ec is set accordingly.
5804 * @warning this function is NOT re-entrant -- partitionp and namep point to
5805 * static data segments
5807 * @note if a volume utility inadvertently leaves behind a stale volume header
5808 * on a vice partition, it is possible for callers to get the wrong one,
5809 * depending on the order of the disk partition linked list.
5813 VGetVolumePath(Error * ec, VolId volumeId, char **partitionp, char **namep)
5815 static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
5816 char path[VMAXPATHLEN];
5818 struct DiskPartition64 *dp;
5822 (void)afs_snprintf(&name[1], (sizeof name) - 1, VFORMAT, afs_printable_uint32_lu(volumeId));
5823 for (dp = DiskPartitionList; dp; dp = dp->next) {
5824 struct afs_stat status;
5825 strcpy(path, VPartitionPath(dp));
5827 if (afs_stat(path, &status) == 0) {
5828 strcpy(partition, dp->name);
5835 *partitionp = *namep = NULL;
5837 *partitionp = partition;
5843 * extract a volume number from a volume header filename string.
5845 * @param[in] name volume header filename string
5847 * @return volume number
5849 * @note the string must be of the form VFORMAT. the only permissible
5850 * deviation is a leading '/' character.
5855 VolumeNumber(char *name)
5859 return atoi(name + 1);
5863 * compute the volume header filename.
5865 * @param[in] volumeId
5867 * @return volume header filename
5869 * @post volume header filename string is constructed
5871 * @warning this function is NOT re-entrant -- the returned string is
5872 * stored in a static char array. see VolumeExternalName_r
5873 * for a re-entrant equivalent.
5875 * @see VolumeExternalName_r
5877 * @deprecated due to the above re-entrancy warning, this interface should
5878 * be considered deprecated. Please use VolumeExternalName_r
5882 VolumeExternalName(VolumeId volumeId)
5884 static char name[VMAXPATHLEN];
5885 (void)afs_snprintf(name, sizeof name, VFORMAT, afs_printable_uint32_lu(volumeId));
5890 * compute the volume header filename.
5892 * @param[in] volumeId
5893 * @param[inout] name array in which to store filename
5894 * @param[in] len length of name array
5896 * @return result code from afs_snprintf
5898 * @see VolumeExternalName
5901 * @note re-entrant equivalent of VolumeExternalName
5904 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
5906 return afs_snprintf(name, len, VFORMAT, afs_printable_uint32_lu(volumeId));
5910 /***************************************************/
5911 /* Volume Usage Statistics routines */
5912 /***************************************************/
5914 #if OPENAFS_VOL_STATS
5915 #define OneDay (86400) /* 24 hours' worth of seconds */
5917 #define OneDay (24*60*60) /* 24 hours */
5918 #endif /* OPENAFS_VOL_STATS */
5921 Midnight(time_t t) {
5922 struct tm local, *l;
5925 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
5926 l = localtime_r(&t, &local);
5932 /* the following is strictly speaking problematic on the
5933 switching day to daylight saving time, after the switch,
5934 as tm_isdst does not match. Similarly, on the looong day when
5935 switching back the OneDay check will not do what naively expected!
5936 The effects are minor, though, and more a matter of interpreting
5938 #ifndef AFS_PTHREAD_ENV
5941 local.tm_hour = local.tm_min=local.tm_sec = 0;
5942 midnight = mktime(&local);
5943 if (midnight != (time_t) -1) return(midnight);
5945 return( (t/OneDay)*OneDay );
5949 /*------------------------------------------------------------------------
5950 * [export] VAdjustVolumeStatistics
5953 * If we've passed midnight, we need to update all the day use
5954 * statistics as well as zeroing the detailed volume statistics
5955 * (if we are implementing them).
5958 * vp : Pointer to the volume structure describing the lucky
5959 * volume being considered for update.
5965 * Nothing interesting.
5969 *------------------------------------------------------------------------*/
5972 VAdjustVolumeStatistics_r(register Volume * vp)
5974 unsigned int now = FT_ApproxTime();
5976 if (now - V_dayUseDate(vp) > OneDay) {
5977 register int ndays, i;
5979 ndays = (now - V_dayUseDate(vp)) / OneDay;
5980 for (i = 6; i > ndays - 1; i--)
5981 V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
5982 for (i = 0; i < ndays - 1 && i < 7; i++)
5983 V_weekUse(vp)[i] = 0;
5985 V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
5987 V_dayUseDate(vp) = Midnight(now);
5989 #if OPENAFS_VOL_STATS
5991 * All we need to do is bzero the entire VOL_STATS_BYTES of
5992 * the detailed volume statistics area.
5994 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
5995 #endif /* OPENAFS_VOL_STATS */
5998 /*It's been more than a day of collection */
6000 * Always return happily.
6003 } /*VAdjustVolumeStatistics */
6006 VAdjustVolumeStatistics(register Volume * vp)
6010 retVal = VAdjustVolumeStatistics_r(vp);
6016 VBumpVolumeUsage_r(register Volume * vp)
6018 unsigned int now = FT_ApproxTime();
6019 V_accessDate(vp) = now;
6020 if (now - V_dayUseDate(vp) > OneDay)
6021 VAdjustVolumeStatistics_r(vp);
6023 * Save the volume header image to disk after every 128 bumps to dayUse.
6025 if ((V_dayUse(vp)++ & 127) == 0) {
6027 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
6032 VBumpVolumeUsage(register Volume * vp)
6035 VBumpVolumeUsage_r(vp);
6040 VSetDiskUsage_r(void)
6042 #ifndef AFS_DEMAND_ATTACH_FS
6043 static int FifteenMinuteCounter = 0;
6047 /* NOTE: Don't attempt to access the partitions list until the
6048 * initialization level indicates that all volumes are attached,
6049 * which implies that all partitions are initialized. */
6050 #ifdef AFS_PTHREAD_ENV
6052 #else /* AFS_PTHREAD_ENV */
6054 #endif /* AFS_PTHREAD_ENV */
6057 VResetDiskUsage_r();
6059 #ifndef AFS_DEMAND_ATTACH_FS
6060 if (++FifteenMinuteCounter == 3) {
6061 FifteenMinuteCounter = 0;
6064 #endif /* !AFS_DEMAND_ATTACH_FS */
6076 /***************************************************/
6077 /* Volume Update List routines */
6078 /***************************************************/
6080 /* The number of minutes that a volume hasn't been updated before the
6081 * "Dont salvage" flag in the volume header will be turned on */
6082 #define SALVAGE_INTERVAL (10*60)
6087 * volume update list functionality has been moved into the VLRU
6088 * the DONT_SALVAGE flag is now set during VLRU demotion
6091 #ifndef AFS_DEMAND_ATTACH_FS
6092 static VolumeId *UpdateList = NULL; /* Pointer to array of Volume ID's */
6093 static int nUpdatedVolumes = 0; /* Updated with entry in UpdateList, salvage after crash flag on */
6094 static int updateSize = 0; /* number of entries possible */
6095 #define UPDATE_LIST_SIZE 128 /* initial size increment (must be a power of 2!) */
6096 #endif /* !AFS_DEMAND_ATTACH_FS */
6099 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
6102 vp->updateTime = FT_ApproxTime();
6103 if (V_dontSalvage(vp) == 0)
6105 V_dontSalvage(vp) = 0;
6106 VSyncVolume_r(ec, vp, 0);
6107 #ifdef AFS_DEMAND_ATTACH_FS
6108 V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
6109 #else /* !AFS_DEMAND_ATTACH_FS */
6112 if (UpdateList == NULL) {
6113 updateSize = UPDATE_LIST_SIZE;
6114 UpdateList = (VolumeId *) malloc(sizeof(VolumeId) * updateSize);
6116 if (nUpdatedVolumes == updateSize) {
6118 if (updateSize > 524288) {
6119 Log("warning: there is likely a bug in the volume update scanner\n");
6123 (VolumeId *) realloc(UpdateList,
6124 sizeof(VolumeId) * updateSize);
6127 assert(UpdateList != NULL);
6128 UpdateList[nUpdatedVolumes++] = V_id(vp);
6129 #endif /* !AFS_DEMAND_ATTACH_FS */
6132 #ifndef AFS_DEMAND_ATTACH_FS
6134 VScanUpdateList(void)
6136 register int i, gap;
6137 register Volume *vp;
6139 afs_uint32 now = FT_ApproxTime();
6140 /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
6141 for (i = gap = 0; i < nUpdatedVolumes; i++) {
6143 UpdateList[i - gap] = UpdateList[i];
6145 /* XXX this routine needlessly messes up the Volume LRU by
6146 * breaking the LRU temporal-locality assumptions.....
6147 * we should use a special volume header allocator here */
6148 vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
6151 } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
6152 V_dontSalvage(vp) = DONT_SALVAGE;
6153 VUpdateVolume_r(&error, vp, 0); /* No need to fsync--not critical */
6161 #ifndef AFS_PTHREAD_ENV
6163 #endif /* !AFS_PTHREAD_ENV */
6165 nUpdatedVolumes -= gap;
6167 #endif /* !AFS_DEMAND_ATTACH_FS */
6170 /***************************************************/
6171 /* Volume LRU routines */
6172 /***************************************************/
6177 * with demand attach fs, we attempt to soft detach(1)
6178 * volumes which have not been accessed in a long time
6179 * in order to speed up fileserver shutdown
6181 * (1) by soft detach we mean a process very similar
6182 * to VOffline, except the final state of the
6183 * Volume will be VOL_STATE_PREATTACHED, instead
6184 * of the usual VOL_STATE_UNATTACHED
6186 #ifdef AFS_DEMAND_ATTACH_FS
6188 /* implementation is reminiscent of a generational GC
6190 * queue 0 is newly attached volumes. this queue is
6191 * sorted by attach timestamp
6193 * queue 1 is volumes that have been around a bit
6194 * longer than queue 0. this queue is sorted by
6197 * queue 2 is volumes tha have been around the longest.
6198 * this queue is unsorted
6200 * queue 3 is volumes that have been marked as
6201 * candidates for soft detachment. this queue is
6204 #define VLRU_GENERATIONS 3 /**< number of generations in VLRU */
6205 #define VLRU_QUEUES 5 /**< total number of VLRU queues */
6208 * definition of a VLRU queue.
6211 volatile struct rx_queue q;
6218 * main VLRU data structure.
6221 struct VLRU_q q[VLRU_QUEUES]; /**< VLRU queues */
6224 /** time interval (in seconds) between promotion passes for
6225 * each young generation queue. */
6226 afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
6228 /** time interval (in seconds) between soft detach candidate
6229 * scans for each generation queue.
6231 * scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
6232 * we perform a soft detach pass. */
6233 afs_uint32 scan_interval[VLRU_GENERATIONS+1];
6235 /* scheduler state */
6236 int next_idx; /**< next queue to receive attention */
6237 afs_uint32 last_promotion[VLRU_GENERATIONS-1]; /**< timestamp of last promotion scan */
6238 afs_uint32 last_scan[VLRU_GENERATIONS+1]; /**< timestamp of last detach scan */
6240 int scanner_state; /**< state of scanner thread */
6241 pthread_cond_t cv; /**< state transition CV */
6244 /** global VLRU state */
6245 static struct VLRU volume_LRU;
6248 * defined states for VLRU scanner thread.
6251 VLRU_SCANNER_STATE_OFFLINE = 0, /**< vlru scanner thread is offline */
6252 VLRU_SCANNER_STATE_ONLINE = 1, /**< vlru scanner thread is online */
6253 VLRU_SCANNER_STATE_SHUTTING_DOWN = 2, /**< vlru scanner thread is shutting down */
6254 VLRU_SCANNER_STATE_PAUSING = 3, /**< vlru scanner thread is getting ready to pause */
6255 VLRU_SCANNER_STATE_PAUSED = 4 /**< vlru scanner thread is paused */
6256 } vlru_thread_state_t;
6258 /* vlru disk data header stuff */
6259 #define VLRU_DISK_MAGIC 0x7a8b9cad /**< vlru disk entry magic number */
6260 #define VLRU_DISK_VERSION 1 /**< vlru disk entry version number */
6262 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
6263 #define VLRU_DUMP_EXPIRATION_TIME (60*60*24*7) /* expire vlru data after 1 week */
6266 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
6267 * soft detachment. */
6268 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
6270 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
6271 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
6273 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
6274 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
6276 /** VLRU control flag. non-zero value implies VLRU subsystem is activated. */
6277 static afs_uint32 VLRU_enabled = 1;
6279 /* queue synchronization routines */
6280 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
6281 static void VLRU_EndExclusive_r(struct VLRU_q * q);
6282 static void VLRU_Wait_r(struct VLRU_q * q);
6285 * set VLRU subsystem tunable parameters.
6287 * @param[in] option tunable option to modify
6288 * @param[in] val new value for tunable parameter
6290 * @pre @c VInitVolumePackage2 has not yet been called.
6292 * @post tunable parameter is modified
6296 * @note valid option parameters are:
6297 * @arg @c VLRU_SET_THRESH
6298 * set the period of inactivity after which
6299 * volumes are eligible for soft detachment
6300 * @arg @c VLRU_SET_INTERVAL
6301 * set the time interval between calls
6302 * to the volume LRU "garbage collector"
6303 * @arg @c VLRU_SET_MAX
6304 * set the max number of volumes to deallocate
6308 VLRU_SetOptions(int option, afs_uint32 val)
6310 if (option == VLRU_SET_THRESH) {
6311 VLRU_offline_thresh = val;
6312 } else if (option == VLRU_SET_INTERVAL) {
6313 VLRU_offline_interval = val;
6314 } else if (option == VLRU_SET_MAX) {
6315 VLRU_offline_max = val;
6316 } else if (option == VLRU_SET_ENABLED) {
6319 VLRU_ComputeConstants();
6323 * compute VLRU internal timing parameters.
6325 * @post VLRU scanner thread internal timing parameters are computed
6327 * @note computes internal timing parameters based upon user-modifiable
6328 * tunable parameters.
6332 * @internal volume package internal use only.
6335 VLRU_ComputeConstants(void)
6337 afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
6339 /* compute the candidate scan interval */
6340 volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
6342 /* compute the promotion intervals */
6343 volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
6344 volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
6347 /* compute the gen 0 scan interval */
6348 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
6350 /* compute the gen 0 scan interval */
6351 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
6356 * initialize VLRU subsystem.
6358 * @pre this function has not yet been called
6360 * @post VLRU subsystem is initialized and VLRU scanner thread is starting
6364 * @internal volume package internal use only.
6370 pthread_attr_t attrs;
6373 if (!VLRU_enabled) {
6374 Log("VLRU: disabled\n");
6378 /* initialize each of the VLRU queues */
6379 for (i = 0; i < VLRU_QUEUES; i++) {
6380 queue_Init(&volume_LRU.q[i]);
6381 volume_LRU.q[i].len = 0;
6382 volume_LRU.q[i].busy = 0;
6383 assert(pthread_cond_init(&volume_LRU.q[i].cv, NULL) == 0);
6386 /* setup the timing constants */
6387 VLRU_ComputeConstants();
6389 /* XXX put inside LogLevel check? */
6390 Log("VLRU: starting scanner with the following configuration parameters:\n");
6391 Log("VLRU: offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
6392 Log("VLRU: running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
6393 Log("VLRU: taking up to %d volumes offline per pass\n", VLRU_offline_max);
6394 Log("VLRU: scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
6395 Log("VLRU: scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
6396 Log("VLRU: scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
6398 /* start up the VLRU scanner */
6399 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
6400 if (programType == fileServer) {
6401 assert(pthread_cond_init(&volume_LRU.cv, NULL) == 0);
6402 assert(pthread_attr_init(&attrs) == 0);
6403 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
6404 assert(pthread_create(&tid, &attrs, &VLRU_ScannerThread, NULL) == 0);
6409 * initialize the VLRU-related fields of a newly allocated volume object.
6411 * @param[in] vp pointer to volume object
6414 * @arg @c VOL_LOCK is held.
6415 * @arg volume object is not on a VLRU queue.
6417 * @post VLRU fields are initialized to indicate that volume object is not
6418 * currently registered with the VLRU subsystem
6422 * @internal volume package interal use only.
6425 VLRU_Init_Node_r(Volume * vp)
6430 assert(queue_IsNotOnQueue(&vp->vlru));
6431 vp->vlru.idx = VLRU_QUEUE_INVALID;
6435 * add a volume object to a VLRU queue.
6437 * @param[in] vp pointer to volume object
6440 * @arg @c VOL_LOCK is held.
6441 * @arg caller MUST hold a lightweight ref on @p vp.
6442 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
6444 * @post the volume object is added to the appropriate VLRU queue
6446 * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
6447 * then the volume is added to that queue. Otherwise, the value
6448 * @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
6449 * volume is added to the NEW generation queue.
6451 * @note @c VOL_LOCK may be dropped internally
6453 * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
6454 * during the add operation, and is restored to the previous
6455 * state prior to return.
6459 * @internal volume package internal use only.
6462 VLRU_Add_r(Volume * vp)
6465 VolState state_save;
6470 if (queue_IsOnQueue(&vp->vlru))
6473 state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
6476 if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
6477 idx = VLRU_QUEUE_NEW;
6480 VLRU_Wait_r(&volume_LRU.q[idx]);
6482 /* repeat check since VLRU_Wait_r may have dropped
6484 if (queue_IsNotOnQueue(&vp->vlru)) {
6486 queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
6487 volume_LRU.q[idx].len++;
6488 V_attachFlags(vp) |= VOL_ON_VLRU;
6489 vp->stats.last_promote = FT_ApproxTime();
6492 VChangeState_r(vp, state_save);
6496 * delete a volume object from a VLRU queue.
6498 * @param[in] vp pointer to volume object
6501 * @arg @c VOL_LOCK is held.
6502 * @arg caller MUST hold a lightweight ref on @p vp.
6503 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
6505 * @post volume object is removed from the VLRU queue
6507 * @note @c VOL_LOCK may be dropped internally
6511 * @todo We should probably set volume state to something exlcusive
6512 * (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
6514 * @internal volume package internal use only.
6517 VLRU_Delete_r(Volume * vp)
6524 if (queue_IsNotOnQueue(&vp->vlru))
6530 if (idx == VLRU_QUEUE_INVALID)
6532 VLRU_Wait_r(&volume_LRU.q[idx]);
6533 } while (idx != vp->vlru.idx);
6535 /* now remove from the VLRU and update
6536 * the appropriate counter */
6537 queue_Remove(&vp->vlru);
6538 volume_LRU.q[idx].len--;
6539 vp->vlru.idx = VLRU_QUEUE_INVALID;
6540 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
6544 * tell the VLRU subsystem that a volume was just accessed.
6546 * @param[in] vp pointer to volume object
6549 * @arg @c VOL_LOCK is held
6550 * @arg caller MUST hold a lightweight ref on @p vp
6551 * @arg caller MUST NOT hold exclusive ownership of any VLRU queue
6553 * @post volume VLRU access statistics are updated. If the volume was on
6554 * the VLRU soft detach candidate queue, it is moved to the NEW
6557 * @note @c VOL_LOCK may be dropped internally
6561 * @internal volume package internal use only.
6564 VLRU_UpdateAccess_r(Volume * vp)
6566 Volume * rvp = NULL;
6571 if (queue_IsNotOnQueue(&vp->vlru))
6574 assert(V_attachFlags(vp) & VOL_ON_VLRU);
6576 /* update the access timestamp */
6577 vp->stats.last_get = FT_ApproxTime();
6580 * if the volume is on the soft detach candidate
6581 * list, we need to safely move it back to a
6582 * regular generation. this has to be done
6583 * carefully so we don't race against the scanner
6587 /* if this volume is on the soft detach candidate queue,
6588 * then grab exclusive access to the necessary queues */
6589 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
6591 VCreateReservation_r(rvp);
6593 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
6594 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
6595 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6596 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6599 /* make sure multiple threads don't race to update */
6600 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
6601 VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
6605 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6606 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
6607 VCancelReservation_r(rvp);
6612 * switch a volume between two VLRU queues.
6614 * @param[in] vp pointer to volume object
6615 * @param[in] new_idx index of VLRU queue onto which the volume will be moved
6616 * @param[in] append controls whether the volume will be appended or
6617 * prepended to the queue. A nonzero value means it will
6618 * be appended; zero means it will be prepended.
6620 * @pre The new (and old, if applicable) queue(s) must either be owned
6621 * exclusively by the calling thread for asynchronous manipulation,
6622 * or the queue(s) must be quiescent and VOL_LOCK must be held.
6623 * Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
6624 * for further details of the queue asynchronous processing mechanism.
6626 * @post If the volume object was already on a VLRU queue, it is
6627 * removed from the queue. Depending on the value of the append
6628 * parameter, the volume object is either appended or prepended
6629 * to the VLRU queue referenced by the new_idx parameter.
6633 * @see VLRU_BeginExclusive_r
6634 * @see VLRU_EndExclusive_r
6637 * @internal volume package internal use only.
6640 VLRU_SwitchQueues(Volume * vp, int new_idx, int append)
6642 if (queue_IsNotOnQueue(&vp->vlru))
6645 queue_Remove(&vp->vlru);
6646 volume_LRU.q[vp->vlru.idx].len--;
6648 /* put the volume back on the correct generational queue */
6650 queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
6652 queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
6655 volume_LRU.q[new_idx].len++;
6656 vp->vlru.idx = new_idx;
6660 * VLRU background thread.
6662 * The VLRU Scanner Thread is responsible for periodically scanning through
6663 * each VLRU queue looking for volumes which should be moved to another
6664 * queue, or soft detached.
6666 * @param[in] args unused thread arguments parameter
6668 * @return unused thread return value
6669 * @retval NULL always
6671 * @internal volume package internal use only.
6674 VLRU_ScannerThread(void * args)
6676 afs_uint32 now, min_delay, delay;
6677 int i, min_idx, min_op, overdue, state;
6679 /* set t=0 for promotion cycle to be
6680 * fileserver startup */
6681 now = FT_ApproxTime();
6682 for (i=0; i < VLRU_GENERATIONS-1; i++) {
6683 volume_LRU.last_promotion[i] = now;
6686 /* don't start the scanner until VLRU_offline_thresh
6687 * plus a small delay for VInitVolumePackage2 to finish
6690 sleep(VLRU_offline_thresh + 60);
6692 /* set t=0 for scan cycle to be now */
6693 now = FT_ApproxTime();
6694 for (i=0; i < VLRU_GENERATIONS+1; i++) {
6695 volume_LRU.last_scan[i] = now;
6699 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
6700 volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
6703 while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
6704 /* check to see if we've been asked to pause */
6705 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
6706 volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
6707 assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
6709 VOL_CV_WAIT(&volume_LRU.cv);
6710 } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
6713 /* scheduling can happen outside the glock */
6716 /* figure out what is next on the schedule */
6718 /* figure out a potential schedule for the new generation first */
6720 min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
6723 if (min_delay > volume_LRU.scan_interval[0]) {
6724 /* unsigned overflow -- we're overdue to run this scan */
6729 /* if we're not overdue for gen 0, figure out schedule for candidate gen */
6731 i = VLRU_QUEUE_CANDIDATE;
6732 delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
6733 if (delay < min_delay) {
6737 if (delay > volume_LRU.scan_interval[i]) {
6738 /* unsigned overflow -- we're overdue to run this scan */
6745 /* if we're still not overdue for something, figure out schedules for promotions */
6746 for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
6747 delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
6748 if (delay < min_delay) {
6753 if (delay > volume_LRU.promotion_interval[i]) {
6754 /* unsigned overflow -- we're overdue to run this promotion */
6763 /* sleep as needed */
6768 /* do whatever is next */
6771 VLRU_Promote_r(min_idx);
6772 VLRU_Demote_r(min_idx+1);
6774 VLRU_Scan_r(min_idx);
6776 now = FT_ApproxTime();
6779 Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
6781 /* signal that scanner is down */
6782 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
6783 assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
6789 * promote volumes from one VLRU generation to the next.
6791 * This routine scans a VLRU generation looking for volumes which are
6792 * eligible to be promoted to the next generation. All volumes which
6793 * meet the eligibility requirement are promoted.
6795 * Promotion eligibility is based upon meeting both of the following
6798 * @arg The volume has been accessed since the last promotion:
6799 * @c (vp->stats.last_get >= vp->stats.last_promote)
6800 * @arg The last promotion occurred at least
6801 * @c volume_LRU.promotion_interval[idx] seconds ago
6803 * As a performance optimization, promotions are "globbed". In other
6804 * words, we promote arbitrarily large contiguous sublists of elements
6807 * @param[in] idx VLRU queue index to scan
6811 * @internal VLRU internal use only.
6814 VLRU_Promote_r(int idx)
6816 int len, chaining, promote;
6817 afs_uint32 now, thresh;
6818 struct rx_queue *qp, *nqp;
6819 Volume * vp, *start = NULL, *end = NULL;
6821 /* get exclusive access to two chains, and drop the glock */
6822 VLRU_Wait_r(&volume_LRU.q[idx]);
6823 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
6824 VLRU_Wait_r(&volume_LRU.q[idx+1]);
6825 VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
6828 thresh = volume_LRU.promotion_interval[idx];
6829 now = FT_ApproxTime();
6832 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
6833 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6834 promote = (((vp->stats.last_promote + thresh) <= now) &&
6835 (vp->stats.last_get >= vp->stats.last_promote));
6843 /* promote and prepend chain */
6844 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
6858 /* promote and prepend */
6859 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
6863 volume_LRU.q[idx].len -= len;
6864 volume_LRU.q[idx+1].len += len;
6867 /* release exclusive access to the two chains */
6869 volume_LRU.last_promotion[idx] = now;
6870 VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
6871 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
6874 /* run the demotions */
6876 VLRU_Demote_r(int idx)
6879 int len, chaining, demote;
6880 afs_uint32 now, thresh;
6881 struct rx_queue *qp, *nqp;
6882 Volume * vp, *start = NULL, *end = NULL;
6883 Volume ** salv_flag_vec = NULL;
6884 int salv_vec_offset = 0;
6886 assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
6888 /* get exclusive access to two chains, and drop the glock */
6889 VLRU_Wait_r(&volume_LRU.q[idx-1]);
6890 VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
6891 VLRU_Wait_r(&volume_LRU.q[idx]);
6892 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
6895 /* no big deal if this allocation fails */
6896 if (volume_LRU.q[idx].len) {
6897 salv_flag_vec = (Volume **) malloc(volume_LRU.q[idx].len * sizeof(Volume *));
6900 now = FT_ApproxTime();
6901 thresh = volume_LRU.promotion_interval[idx-1];
6904 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
6905 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6906 demote = (((vp->stats.last_promote + thresh) <= now) &&
6907 (vp->stats.last_get < (now - thresh)));
6909 /* we now do volume update list DONT_SALVAGE flag setting during
6910 * demotion passes */
6911 if (salv_flag_vec &&
6912 !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
6914 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
6915 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
6916 salv_flag_vec[salv_vec_offset++] = vp;
6917 VCreateReservation_r(vp);
6926 /* demote and append chain */
6927 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
6941 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
6945 volume_LRU.q[idx].len -= len;
6946 volume_LRU.q[idx-1].len += len;
6949 /* release exclusive access to the two chains */
6951 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
6952 VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
6954 /* now go back and set the DONT_SALVAGE flags as appropriate */
6955 if (salv_flag_vec) {
6957 for (i = 0; i < salv_vec_offset; i++) {
6958 vp = salv_flag_vec[i];
6959 if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
6960 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
6961 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
6964 V_attachFlags(vp) |= VOL_HDR_DONTSALV;
6965 V_dontSalvage(vp) = DONT_SALVAGE;
6966 VUpdateVolume_r(&ec, vp, 0);
6970 VCancelReservation_r(vp);
6972 free(salv_flag_vec);
6976 /* run a pass of the VLRU GC scanner */
6978 VLRU_Scan_r(int idx)
6980 afs_uint32 now, thresh;
6981 struct rx_queue *qp, *nqp;
6985 assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
6987 /* gain exclusive access to the idx VLRU */
6988 VLRU_Wait_r(&volume_LRU.q[idx]);
6989 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
6991 if (idx != VLRU_QUEUE_CANDIDATE) {
6992 /* gain exclusive access to the candidate VLRU */
6993 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6994 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6997 now = FT_ApproxTime();
6998 thresh = now - VLRU_offline_thresh;
7000 /* perform candidate selection and soft detaching */
7001 if (idx == VLRU_QUEUE_CANDIDATE) {
7002 /* soft detach some volumes from the candidate pool */
7006 for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7007 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7008 if (i >= VLRU_offline_max) {
7011 /* check timestamp to see if it's a candidate for soft detaching */
7012 if (vp->stats.last_get <= thresh) {
7014 if (VCheckSoftDetach(vp, thresh))
7020 /* scan for volumes to become soft detach candidates */
7021 for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
7022 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7024 /* check timestamp to see if it's a candidate for soft detaching */
7025 if (vp->stats.last_get <= thresh) {
7026 VCheckSoftDetachCandidate(vp, thresh);
7029 if (!(i&0x7f)) { /* lock coarsening optimization */
7037 /* relinquish exclusive access to the VLRU chains */
7041 volume_LRU.last_scan[idx] = now;
7042 if (idx != VLRU_QUEUE_CANDIDATE) {
7043 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7045 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7048 /* check whether volume is safe to soft detach
7049 * caller MUST NOT hold a ref count on vp */
7051 VCheckSoftDetach(Volume * vp, afs_uint32 thresh)
7055 if (vp->nUsers || vp->nWaiters)
7058 if (vp->stats.last_get <= thresh) {
7059 ret = VSoftDetachVolume_r(vp, thresh);
7065 /* check whether volume should be made a
7066 * soft detach candidate */
7068 VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh)
7071 if (vp->nUsers || vp->nWaiters)
7076 assert(idx == VLRU_QUEUE_NEW);
7078 if (vp->stats.last_get <= thresh) {
7079 /* move to candidate pool */
7080 queue_Remove(&vp->vlru);
7081 volume_LRU.q[VLRU_QUEUE_NEW].len--;
7082 queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
7083 vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
7084 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
7092 /* begin exclusive access on VLRU */
7094 VLRU_BeginExclusive_r(struct VLRU_q * q)
7096 assert(q->busy == 0);
7100 /* end exclusive access on VLRU */
7102 VLRU_EndExclusive_r(struct VLRU_q * q)
7106 assert(pthread_cond_broadcast(&q->cv) == 0);
7109 /* wait for another thread to end exclusive access on VLRU */
7111 VLRU_Wait_r(struct VLRU_q * q)
7114 VOL_CV_WAIT(&q->cv);
7119 * volume soft detach
7121 * caller MUST NOT hold a ref count on vp */
7123 VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh)
7128 assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7130 ts_save = vp->stats.last_get;
7131 if (ts_save > thresh)
7134 if (vp->nUsers || vp->nWaiters)
7137 if (VIsExclusiveState(V_attachState(vp))) {
7141 switch (V_attachState(vp)) {
7142 case VOL_STATE_UNATTACHED:
7143 case VOL_STATE_PREATTACHED:
7144 case VOL_STATE_ERROR:
7145 case VOL_STATE_GOING_OFFLINE:
7146 case VOL_STATE_SHUTTING_DOWN:
7147 case VOL_STATE_SALVAGING:
7148 volume_LRU.q[vp->vlru.idx].len--;
7150 /* create and cancel a reservation to
7151 * give the volume an opportunity to
7153 VCreateReservation_r(vp);
7154 queue_Remove(&vp->vlru);
7155 vp->vlru.idx = VLRU_QUEUE_INVALID;
7156 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7157 VCancelReservation_r(vp);
7163 /* hold the volume and take it offline.
7164 * no need for reservations, as VHold_r
7165 * takes care of that internally. */
7166 if (VHold_r(vp) == 0) {
7167 /* vhold drops the glock, so now we should
7168 * check to make sure we aren't racing against
7169 * other threads. if we are racing, offlining vp
7170 * would be wasteful, and block the scanner for a while
7174 (vp->shuttingDown) ||
7175 (vp->goingOffline) ||
7176 (vp->stats.last_get != ts_save)) {
7177 /* looks like we're racing someone else. bail */
7181 /* pull it off the VLRU */
7182 assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7183 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
7184 queue_Remove(&vp->vlru);
7185 vp->vlru.idx = VLRU_QUEUE_INVALID;
7186 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7188 /* take if offline */
7189 VOffline_r(vp, "volume has been soft detached");
7191 /* invalidate the volume header cache */
7192 FreeVolumeHeader(vp);
7195 IncUInt64(&VStats.soft_detaches);
7196 vp->stats.soft_detaches++;
7198 /* put in pre-attached state so demand
7199 * attacher can work on it */
7200 VChangeState_r(vp, VOL_STATE_PREATTACHED);
7206 #endif /* AFS_DEMAND_ATTACH_FS */
7209 /***************************************************/
7210 /* Volume Header Cache routines */
7211 /***************************************************/
7214 * volume header cache.
7216 struct volume_hdr_LRU_t volume_hdr_LRU;
7219 * initialize the volume header cache.
7221 * @param[in] howMany number of header cache entries to preallocate
7223 * @pre VOL_LOCK held. Function has never been called before.
7225 * @post howMany cache entries are allocated, initialized, and added
7226 * to the LRU list. Header cache statistics are initialized.
7228 * @note only applicable to fileServer program type. Should only be
7229 * called once during volume package initialization.
7231 * @internal volume package internal use only.
7234 VInitVolumeHeaderCache(afs_uint32 howMany)
7236 register struct volHeader *hp;
7237 if (programType != fileServer)
7239 queue_Init(&volume_hdr_LRU);
7240 volume_hdr_LRU.stats.free = 0;
7241 volume_hdr_LRU.stats.used = howMany;
7242 volume_hdr_LRU.stats.attached = 0;
7243 hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
7247 /* We are using ReleaseVolumeHeader to initialize the values on the header list
7248 * to ensure they have the right values
7250 ReleaseVolumeHeader(hp++);
7254 * get a volume header and attach it to the volume object.
7256 * @param[in] vp pointer to volume object
7258 * @return cache entry status
7259 * @retval 0 volume header was newly attached; cache data is invalid
7260 * @retval 1 volume header was previously attached; cache data is valid
7262 * @pre VOL_LOCK held. For DAFS, lightweight ref must be held on volume object.
7264 * @post volume header attached to volume object. if necessary, header cache
7265 * entry on LRU is synchronized to disk. Header is removed from LRU list.
7267 * @note VOL_LOCK may be dropped
7269 * @warning this interface does not load header data from disk. it merely
7270 * attaches a header object to the volume object, and may sync the old
7271 * header cache data out to disk in the process.
7273 * @internal volume package internal use only.
7276 GetVolumeHeader(register Volume * vp)
7279 register struct volHeader *hd;
7281 static int everLogged = 0;
7283 #ifdef AFS_DEMAND_ATTACH_FS
7284 VolState vp_save = 0, back_save = 0;
7286 /* XXX debug 9/19/05 we've apparently got
7287 * a ref counting bug somewhere that's
7288 * breaking the nUsers == 0 => header on LRU
7290 if (vp->header && queue_IsNotOnQueue(vp->header)) {
7291 Log("nUsers == 0, but header not on LRU\n");
7296 old = (vp->header != NULL); /* old == volume already has a header */
7298 if (programType != fileServer) {
7299 /* for volume utilities, we allocate volHeaders as needed */
7301 hd = (struct volHeader *)calloc(1, sizeof(*vp->header));
7305 #ifdef AFS_DEMAND_ATTACH_FS
7306 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
7310 /* for the fileserver, we keep a volume header cache */
7312 /* the header we previously dropped in the lru is
7313 * still available. pull it off the lru and return */
7316 assert(hd->back == vp);
7317 #ifdef AFS_DEMAND_ATTACH_FS
7318 V_attachFlags(vp) &= ~(VOL_HDR_IN_LRU);
7321 /* we need to grab a new element off the LRU */
7322 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
7323 /* grab an element and pull off of LRU */
7324 hd = queue_First(&volume_hdr_LRU, volHeader);
7327 /* LRU is empty, so allocate a new volHeader
7328 * this is probably indicative of a leak, so let the user know */
7329 hd = (struct volHeader *)calloc(1, sizeof(struct volHeader));
7332 Log("****Allocated more volume headers, probably leak****\n");
7335 volume_hdr_LRU.stats.free++;
7338 /* this header used to belong to someone else.
7339 * we'll need to check if the header needs to
7340 * be sync'd out to disk */
7342 #ifdef AFS_DEMAND_ATTACH_FS
7343 /* if hd->back were in an exclusive state, then
7344 * its volHeader would not be on the LRU... */
7345 assert(!VIsExclusiveState(V_attachState(hd->back)));
7348 if (hd->diskstuff.inUse) {
7349 /* volume was in use, so we'll need to sync
7350 * its header to disk */
7352 #ifdef AFS_DEMAND_ATTACH_FS
7353 back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
7354 vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
7355 VCreateReservation_r(hd->back);
7359 WriteVolumeHeader_r(&error, hd->back);
7360 /* Ignore errors; catch them later */
7362 #ifdef AFS_DEMAND_ATTACH_FS
7367 hd->back->header = NULL;
7368 #ifdef AFS_DEMAND_ATTACH_FS
7369 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
7371 if (hd->diskstuff.inUse) {
7372 VChangeState_r(hd->back, back_save);
7373 VCancelReservation_r(hd->back);
7374 VChangeState_r(vp, vp_save);
7378 volume_hdr_LRU.stats.attached++;
7382 #ifdef AFS_DEMAND_ATTACH_FS
7383 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
7386 volume_hdr_LRU.stats.free--;
7387 volume_hdr_LRU.stats.used++;
7389 IncUInt64(&VStats.hdr_gets);
7390 #ifdef AFS_DEMAND_ATTACH_FS
7391 IncUInt64(&vp->stats.hdr_gets);
7392 vp->stats.last_hdr_get = FT_ApproxTime();
7399 * make sure volume header is attached and contains valid cache data.
7401 * @param[out] ec outbound error code
7402 * @param[in] vp pointer to volume object
7404 * @pre VOL_LOCK held. For DAFS, lightweight ref held on vp.
7406 * @post header cache entry attached, and loaded with valid data, or
7407 * *ec is nonzero, and the header is released back into the LRU.
7409 * @internal volume package internal use only.
7412 LoadVolumeHeader(Error * ec, Volume * vp)
7414 #ifdef AFS_DEMAND_ATTACH_FS
7415 VolState state_save;
7419 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
7420 IncUInt64(&VStats.hdr_loads);
7421 state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
7424 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
7425 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
7427 IncUInt64(&vp->stats.hdr_loads);
7428 now = FT_ApproxTime();
7432 V_attachFlags(vp) |= VOL_HDR_LOADED;
7433 vp->stats.last_hdr_load = now;
7435 VChangeState_r(vp, state_save);
7437 #else /* AFS_DEMAND_ATTACH_FS */
7439 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
7440 IncUInt64(&VStats.hdr_loads);
7442 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
7443 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
7446 #endif /* AFS_DEMAND_ATTACH_FS */
7448 /* maintain (nUsers==0) => header in LRU invariant */
7449 FreeVolumeHeader(vp);
7454 * release a header cache entry back into the LRU list.
7456 * @param[in] hd pointer to volume header cache object
7458 * @pre VOL_LOCK held.
7460 * @post header cache object appended onto end of LRU list.
7462 * @note only applicable to fileServer program type.
7464 * @note used to place a header cache entry back into the
7465 * LRU pool without invalidating it as a cache entry.
7467 * @internal volume package internal use only.
7470 ReleaseVolumeHeader(register struct volHeader *hd)
7472 if (programType != fileServer)
7474 if (!hd || queue_IsOnQueue(hd)) /* no header, or header already released */
7476 queue_Append(&volume_hdr_LRU, hd);
7477 #ifdef AFS_DEMAND_ATTACH_FS
7479 V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
7482 volume_hdr_LRU.stats.free++;
7483 volume_hdr_LRU.stats.used--;
7487 * free/invalidate a volume header cache entry.
7489 * @param[in] vp pointer to volume object
7491 * @pre VOL_LOCK is held.
7493 * @post For fileserver, header cache entry is returned to LRU, and it is
7494 * invalidated as a cache entry. For volume utilities, the header
7495 * cache entry is freed.
7497 * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
7498 * whenever it is necessary to invalidate the header cache entry.
7500 * @see ReleaseVolumeHeader
7502 * @internal volume package internal use only.
7505 FreeVolumeHeader(register Volume * vp)
7507 register struct volHeader *hd = vp->header;
7510 if (programType == fileServer) {
7511 ReleaseVolumeHeader(hd);
7516 #ifdef AFS_DEMAND_ATTACH_FS
7517 V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
7519 volume_hdr_LRU.stats.attached--;
7524 /***************************************************/
7525 /* Volume Hash Table routines */
7526 /***************************************************/
7529 * set size of volume object hash table.
7531 * @param[in] logsize log(2) of desired hash table size
7533 * @return operation status
7535 * @retval -1 failure
7537 * @pre MUST be called prior to VInitVolumePackage2
7539 * @post Volume Hash Table will have 2^logsize buckets
7542 VSetVolHashSize(int logsize)
7544 /* 64 to 16384 hash buckets seems like a reasonable range */
7545 if ((logsize < 6 ) || (logsize > 14)) {
7550 VolumeHashTable.Size = 1 << logsize;
7551 VolumeHashTable.Mask = VolumeHashTable.Size - 1;
7553 /* we can't yet support runtime modification of this
7554 * parameter. we'll need a configuration rwlock to
7555 * make runtime modification feasible.... */
7562 * initialize dynamic data structures for volume hash table.
7564 * @post hash table is allocated, and fields are initialized.
7566 * @internal volume package internal use only.
7569 VInitVolumeHash(void)
7573 VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
7574 sizeof(VolumeHashChainHead));
7575 assert(VolumeHashTable.Table != NULL);
7577 for (i=0; i < VolumeHashTable.Size; i++) {
7578 queue_Init(&VolumeHashTable.Table[i]);
7579 #ifdef AFS_DEMAND_ATTACH_FS
7580 assert(pthread_cond_init(&VolumeHashTable.Table[i].chain_busy_cv, NULL) == 0);
7581 #endif /* AFS_DEMAND_ATTACH_FS */
7586 * add a volume object to the hash table.
7588 * @param[in] vp pointer to volume object
7589 * @param[in] hashid hash of volume id
7591 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
7594 * @post volume is added to hash chain.
7596 * @internal volume package internal use only.
7598 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
7599 * asynchronous hash chain reordering to finish.
7602 AddVolumeToHashTable(register Volume * vp, int hashid)
7604 VolumeHashChainHead * head;
7606 if (queue_IsOnQueue(vp))
7609 head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
7611 #ifdef AFS_DEMAND_ATTACH_FS
7612 /* wait for the hash chain to become available */
7615 V_attachFlags(vp) |= VOL_IN_HASH;
7616 vp->chainCacheCheck = ++head->cacheCheck;
7617 #endif /* AFS_DEMAND_ATTACH_FS */
7620 vp->hashid = hashid;
7621 queue_Append(head, vp);
7622 vp->vnodeHashOffset = VolumeHashOffset_r();
7626 * delete a volume object from the hash table.
7628 * @param[in] vp pointer to volume object
7630 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
7633 * @post volume is removed from hash chain.
7635 * @internal volume package internal use only.
7637 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
7638 * asynchronous hash chain reordering to finish.
7641 DeleteVolumeFromHashTable(register Volume * vp)
7643 VolumeHashChainHead * head;
7645 if (!queue_IsOnQueue(vp))
7648 head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
7650 #ifdef AFS_DEMAND_ATTACH_FS
7651 /* wait for the hash chain to become available */
7654 V_attachFlags(vp) &= ~(VOL_IN_HASH);
7656 #endif /* AFS_DEMAND_ATTACH_FS */
7660 /* do NOT reset hashid to zero, as the online
7661 * salvager package may need to know the volume id
7662 * after the volume is removed from the hash */
7666 * lookup a volume object in the hash table given a volume id.
7668 * @param[out] ec error code return
7669 * @param[in] volumeId volume id
7670 * @param[in] hint volume object which we believe could be the correct
7673 * @return volume object pointer
7674 * @retval NULL no such volume id is registered with the hash table.
7676 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
7679 * @post volume object with the given id is returned. volume object and
7680 * hash chain access statistics are updated. hash chain may have
7683 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
7684 * asynchronous hash chain reordering operation to finish, or
7685 * in order for us to perform an asynchronous chain reordering.
7687 * @note Hash chain reorderings occur when the access count for the
7688 * volume object being looked up exceeds the sum of the previous
7689 * node's (the node ahead of it in the hash chain linked list)
7690 * access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
7692 * @note For DAFS, the hint parameter allows us to short-circuit if the
7693 * cacheCheck fields match between the hash chain head and the
7694 * hint volume object.
7697 VLookupVolume_r(Error * ec, VolId volumeId, Volume * hint)
7699 register int looks = 0;
7701 #ifdef AFS_DEMAND_ATTACH_FS
7704 VolumeHashChainHead * head;
7707 head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
7709 #ifdef AFS_DEMAND_ATTACH_FS
7710 /* wait for the hash chain to become available */
7713 /* check to see if we can short circuit without walking the hash chain */
7714 if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
7715 IncUInt64(&hint->stats.hash_short_circuits);
7718 #endif /* AFS_DEMAND_ATTACH_FS */
7720 /* someday we need to either do per-chain locks, RWlocks,
7721 * or both for volhash access.
7722 * (and move to a data structure with better cache locality) */
7724 /* search the chain for this volume id */
7725 for(queue_Scan(head, vp, np, Volume)) {
7727 if ((vp->hashid == volumeId)) {
7732 if (queue_IsEnd(head, vp)) {
7736 #ifdef AFS_DEMAND_ATTACH_FS
7737 /* update hash chain statistics */
7740 FillInt64(lks, 0, looks);
7741 AddUInt64(head->looks, lks, &head->looks);
7742 AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
7743 IncUInt64(&head->gets);
7748 IncUInt64(&vp->stats.hash_lookups);
7750 /* for demand attach fileserver, we permit occasional hash chain reordering
7751 * so that frequently looked up volumes move towards the head of the chain */
7752 pp = queue_Prev(vp, Volume);
7753 if (!queue_IsEnd(head, pp)) {
7754 FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
7755 AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
7756 if (GEInt64(vp->stats.hash_lookups, thresh)) {
7757 VReorderHash_r(head, pp, vp);
7761 /* update the short-circuit cache check */
7762 vp->chainCacheCheck = head->cacheCheck;
7764 #endif /* AFS_DEMAND_ATTACH_FS */
7769 #ifdef AFS_DEMAND_ATTACH_FS
7770 /* perform volume hash chain reordering.
7772 * advance a subchain beginning at vp ahead of
7773 * the adjacent subchain ending at pp */
7775 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
7777 Volume *tp, *np, *lp;
7778 afs_uint64 move_thresh;
7780 /* this should never be called if the chain is already busy, so
7781 * no need to wait for other exclusive chain ops to finish */
7783 /* this is a rather heavy set of operations,
7784 * so let's set the chain busy flag and drop
7786 VHashBeginExclusive_r(head);
7789 /* scan forward in the chain from vp looking for the last element
7790 * in the chain we want to advance */
7791 FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
7792 AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
7793 for(queue_ScanFrom(head, vp, tp, np, Volume)) {
7794 if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
7798 lp = queue_Prev(tp, Volume);
7800 /* scan backwards from pp to determine where to splice and
7801 * insert the subchain we're advancing */
7802 for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
7803 if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
7807 tp = queue_Next(tp, Volume);
7809 /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
7810 queue_MoveChainBefore(tp,vp,lp);
7813 IncUInt64(&VStats.hash_reorders);
7815 IncUInt64(&head->reorders);
7817 /* wake up any threads waiting for the hash chain */
7818 VHashEndExclusive_r(head);
7822 /* demand-attach fs volume hash
7823 * asynchronous exclusive operations */
7826 * begin an asynchronous exclusive operation on a volume hash chain.
7828 * @param[in] head pointer to volume hash chain head object
7830 * @pre VOL_LOCK held. hash chain is quiescent.
7832 * @post hash chain marked busy.
7834 * @note this interface is used in conjunction with VHashEndExclusive_r and
7835 * VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
7836 * volume hash chain. Its main use case is hash chain reordering, which
7837 * has the potential to be a highly latent operation.
7839 * @see VHashEndExclusive_r
7844 * @internal volume package internal use only.
7847 VHashBeginExclusive_r(VolumeHashChainHead * head)
7849 assert(head->busy == 0);
7854 * relinquish exclusive ownership of a volume hash chain.
7856 * @param[in] head pointer to volume hash chain head object
7858 * @pre VOL_LOCK held. thread owns the hash chain exclusively.
7860 * @post hash chain is marked quiescent. threads awaiting use of
7861 * chain are awakened.
7863 * @see VHashBeginExclusive_r
7868 * @internal volume package internal use only.
7871 VHashEndExclusive_r(VolumeHashChainHead * head)
7875 assert(pthread_cond_broadcast(&head->chain_busy_cv) == 0);
7879 * wait for all asynchronous operations on a hash chain to complete.
7881 * @param[in] head pointer to volume hash chain head object
7883 * @pre VOL_LOCK held.
7885 * @post hash chain object is quiescent.
7887 * @see VHashBeginExclusive_r
7888 * @see VHashEndExclusive_r
7892 * @note This interface should be called before any attempt to
7893 * traverse the hash chain. It is permissible for a thread
7894 * to gain exclusive access to the chain, and then perform
7895 * latent operations on the chain asynchronously wrt the
7898 * @warning if waiting is necessary, VOL_LOCK is dropped
7900 * @internal volume package internal use only.
7903 VHashWait_r(VolumeHashChainHead * head)
7905 while (head->busy) {
7906 VOL_CV_WAIT(&head->chain_busy_cv);
7909 #endif /* AFS_DEMAND_ATTACH_FS */
7912 /***************************************************/
7913 /* Volume by Partition List routines */
7914 /***************************************************/
7917 * demand attach fileserver adds a
7918 * linked list of volumes to each
7919 * partition object, thus allowing
7920 * for quick enumeration of all
7921 * volumes on a partition
7924 #ifdef AFS_DEMAND_ATTACH_FS
7926 * add a volume to its disk partition VByPList.
7928 * @param[in] vp pointer to volume object
7930 * @pre either the disk partition VByPList is owned exclusively
7931 * by the calling thread, or the list is quiescent and
7934 * @post volume is added to disk partition VByPList
7938 * @warning it is the caller's responsibility to ensure list
7941 * @see VVByPListWait_r
7942 * @see VVByPListBeginExclusive_r
7943 * @see VVByPListEndExclusive_r
7945 * @internal volume package internal use only.
7948 AddVolumeToVByPList_r(Volume * vp)
7950 if (queue_IsNotOnQueue(&vp->vol_list)) {
7951 queue_Append(&vp->partition->vol_list, &vp->vol_list);
7952 V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
7953 vp->partition->vol_list.len++;
7958 * delete a volume from its disk partition VByPList.
7960 * @param[in] vp pointer to volume object
7962 * @pre either the disk partition VByPList is owned exclusively
7963 * by the calling thread, or the list is quiescent and
7966 * @post volume is removed from the disk partition VByPList
7970 * @warning it is the caller's responsibility to ensure list
7973 * @see VVByPListWait_r
7974 * @see VVByPListBeginExclusive_r
7975 * @see VVByPListEndExclusive_r
7977 * @internal volume package internal use only.
7980 DeleteVolumeFromVByPList_r(Volume * vp)
7982 if (queue_IsOnQueue(&vp->vol_list)) {
7983 queue_Remove(&vp->vol_list);
7984 V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
7985 vp->partition->vol_list.len--;
7990 * begin an asynchronous exclusive operation on a VByPList.
7992 * @param[in] dp pointer to disk partition object
7994 * @pre VOL_LOCK held. VByPList is quiescent.
7996 * @post VByPList marked busy.
7998 * @note this interface is used in conjunction with VVByPListEndExclusive_r and
7999 * VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8002 * @see VVByPListEndExclusive_r
8003 * @see VVByPListWait_r
8007 * @internal volume package internal use only.
8009 /* take exclusive control over the list */
8011 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
8013 assert(dp->vol_list.busy == 0);
8014 dp->vol_list.busy = 1;
8018 * relinquish exclusive ownership of a VByPList.
8020 * @param[in] dp pointer to disk partition object
8022 * @pre VOL_LOCK held. thread owns the VByPList exclusively.
8024 * @post VByPList is marked quiescent. threads awaiting use of
8025 * the list are awakened.
8027 * @see VVByPListBeginExclusive_r
8028 * @see VVByPListWait_r
8032 * @internal volume package internal use only.
8035 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
8037 assert(dp->vol_list.busy);
8038 dp->vol_list.busy = 0;
8039 assert(pthread_cond_broadcast(&dp->vol_list.cv) == 0);
8043 * wait for all asynchronous operations on a VByPList to complete.
8045 * @param[in] dp pointer to disk partition object
8047 * @pre VOL_LOCK is held.
8049 * @post disk partition's VByP list is quiescent
8053 * @note This interface should be called before any attempt to
8054 * traverse the VByPList. It is permissible for a thread
8055 * to gain exclusive access to the list, and then perform
8056 * latent operations on the list asynchronously wrt the
8059 * @warning if waiting is necessary, VOL_LOCK is dropped
8061 * @see VVByPListEndExclusive_r
8062 * @see VVByPListBeginExclusive_r
8064 * @internal volume package internal use only.
8067 VVByPListWait_r(struct DiskPartition64 * dp)
8069 while (dp->vol_list.busy) {
8070 VOL_CV_WAIT(&dp->vol_list.cv);
8073 #endif /* AFS_DEMAND_ATTACH_FS */
8075 /***************************************************/
8076 /* Volume Cache Statistics routines */
8077 /***************************************************/
8080 VPrintCacheStats_r(void)
8082 afs_uint32 get_hi, get_lo, load_hi, load_lo;
8083 register struct VnodeClassInfo *vcp;
8084 vcp = &VnodeClassInfo[vLarge];
8085 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);
8086 vcp = &VnodeClassInfo[vSmall];
8087 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);
8088 SplitInt64(VStats.hdr_gets, get_hi, get_lo);
8089 SplitInt64(VStats.hdr_loads, load_hi, load_lo);
8090 Log("Volume header cache, %d entries, %d gets, %d replacements\n",
8091 VStats.hdr_cache_size, get_lo, load_lo);
8095 VPrintCacheStats(void)
8098 VPrintCacheStats_r();
8102 #ifdef AFS_DEMAND_ATTACH_FS
8104 UInt64ToDouble(afs_uint64 * x)
8106 static double c32 = 4.0 * 1.073741824 * 1000000000.0;
8108 SplitInt64(*x, h, l);
8109 return (((double)h) * c32) + ((double) l);
8113 DoubleToPrintable(double x, char * buf, int len)
8115 static double billion = 1000000000.0;
8118 y[0] = (afs_uint32) (x / (billion * billion));
8119 y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
8120 y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
8123 snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
8125 snprintf(buf, len, "%d%09d", y[1], y[2]);
8127 snprintf(buf, len, "%d", y[2]);
8133 struct VLRUExtStatsEntry {
8137 struct VLRUExtStats {
8143 } queue_info[VLRU_QUEUE_INVALID];
8144 struct VLRUExtStatsEntry * vec;
8148 * add a 256-entry fudge factor onto the vector in case state changes
8149 * out from under us.
8151 #define VLRU_EXT_STATS_VEC_LEN_FUDGE 256
8154 * collect extended statistics for the VLRU subsystem.
8156 * @param[out] stats pointer to stats structure to be populated
8157 * @param[in] nvols number of volumes currently known to exist
8159 * @pre VOL_LOCK held
8161 * @post stats->vec allocated and populated
8163 * @return operation status
8168 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
8170 afs_uint32 cur, idx, len;
8171 struct rx_queue * qp, * nqp;
8173 struct VLRUExtStatsEntry * vec;
8175 len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
8176 vec = stats->vec = calloc(len,
8177 sizeof(struct VLRUExtStatsEntry));
8183 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
8184 VLRU_Wait_r(&volume_LRU.q[idx]);
8185 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
8188 stats->queue_info[idx].start = cur;
8190 for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
8192 /* out of space in vec */
8195 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
8196 vec[cur].volid = vp->hashid;
8200 stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
8203 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
8211 #define ENUMTOSTRING(en) #en
8212 #define ENUMCASE(en) \
8214 return ENUMTOSTRING(en); \
8218 vlru_idx_to_string(int idx)
8221 ENUMCASE(VLRU_QUEUE_NEW);
8222 ENUMCASE(VLRU_QUEUE_MID);
8223 ENUMCASE(VLRU_QUEUE_OLD);
8224 ENUMCASE(VLRU_QUEUE_CANDIDATE);
8225 ENUMCASE(VLRU_QUEUE_HELD);
8226 ENUMCASE(VLRU_QUEUE_INVALID);
8228 return "**UNKNOWN**";
8233 VPrintExtendedCacheStats_r(int flags)
8236 afs_uint32 vol_sum = 0;
8243 struct stats looks, gets, reorders, len;
8244 struct stats ch_looks, ch_gets, ch_reorders;
8246 VolumeHashChainHead *head;
8248 struct VLRUExtStats vlru_stats;
8250 /* zero out stats */
8251 memset(&looks, 0, sizeof(struct stats));
8252 memset(&gets, 0, sizeof(struct stats));
8253 memset(&reorders, 0, sizeof(struct stats));
8254 memset(&len, 0, sizeof(struct stats));
8255 memset(&ch_looks, 0, sizeof(struct stats));
8256 memset(&ch_gets, 0, sizeof(struct stats));
8257 memset(&ch_reorders, 0, sizeof(struct stats));
8259 for (i = 0; i < VolumeHashTable.Size; i++) {
8260 head = &VolumeHashTable.Table[i];
8263 VHashBeginExclusive_r(head);
8266 ch_looks.sum = UInt64ToDouble(&head->looks);
8267 ch_gets.sum = UInt64ToDouble(&head->gets);
8268 ch_reorders.sum = UInt64ToDouble(&head->reorders);
8270 /* update global statistics */
8272 looks.sum += ch_looks.sum;
8273 gets.sum += ch_gets.sum;
8274 reorders.sum += ch_reorders.sum;
8275 len.sum += (double)head->len;
8276 vol_sum += head->len;
8279 len.min = (double) head->len;
8280 len.max = (double) head->len;
8281 looks.min = ch_looks.sum;
8282 looks.max = ch_looks.sum;
8283 gets.min = ch_gets.sum;
8284 gets.max = ch_gets.sum;
8285 reorders.min = ch_reorders.sum;
8286 reorders.max = ch_reorders.sum;
8288 if (((double)head->len) < len.min)
8289 len.min = (double) head->len;
8290 if (((double)head->len) > len.max)
8291 len.max = (double) head->len;
8292 if (ch_looks.sum < looks.min)
8293 looks.min = ch_looks.sum;
8294 else if (ch_looks.sum > looks.max)
8295 looks.max = ch_looks.sum;
8296 if (ch_gets.sum < gets.min)
8297 gets.min = ch_gets.sum;
8298 else if (ch_gets.sum > gets.max)
8299 gets.max = ch_gets.sum;
8300 if (ch_reorders.sum < reorders.min)
8301 reorders.min = ch_reorders.sum;
8302 else if (ch_reorders.sum > reorders.max)
8303 reorders.max = ch_reorders.sum;
8307 if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
8308 /* compute detailed per-chain stats */
8309 struct stats hdr_loads, hdr_gets;
8310 double v_looks, v_loads, v_gets;
8312 /* initialize stats with data from first element in chain */
8313 vp = queue_First(head, Volume);
8314 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
8315 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
8316 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
8317 ch_gets.min = ch_gets.max = v_looks;
8318 hdr_loads.min = hdr_loads.max = v_loads;
8319 hdr_gets.min = hdr_gets.max = v_gets;
8320 hdr_loads.sum = hdr_gets.sum = 0;
8322 vp = queue_Next(vp, Volume);
8324 /* pull in stats from remaining elements in chain */
8325 for (queue_ScanFrom(head, vp, vp, np, Volume)) {
8326 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
8327 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
8328 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
8330 hdr_loads.sum += v_loads;
8331 hdr_gets.sum += v_gets;
8333 if (v_looks < ch_gets.min)
8334 ch_gets.min = v_looks;
8335 else if (v_looks > ch_gets.max)
8336 ch_gets.max = v_looks;
8338 if (v_loads < hdr_loads.min)
8339 hdr_loads.min = v_loads;
8340 else if (v_loads > hdr_loads.max)
8341 hdr_loads.max = v_loads;
8343 if (v_gets < hdr_gets.min)
8344 hdr_gets.min = v_gets;
8345 else if (v_gets > hdr_gets.max)
8346 hdr_gets.max = v_gets;
8349 /* compute per-chain averages */
8350 ch_gets.avg = ch_gets.sum / ((double)head->len);
8351 hdr_loads.avg = hdr_loads.sum / ((double)head->len);
8352 hdr_gets.avg = hdr_gets.sum / ((double)head->len);
8354 /* dump per-chain stats */
8355 Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
8357 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
8358 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
8359 Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
8360 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
8361 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
8362 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
8363 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
8364 Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
8365 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
8366 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
8367 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
8368 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
8369 Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
8370 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
8371 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
8372 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
8373 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
8374 } else if (flags & VOL_STATS_PER_CHAIN) {
8375 /* dump simple per-chain stats */
8376 Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
8378 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
8379 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
8380 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
8384 VHashEndExclusive_r(head);
8389 /* compute global averages */
8390 len.avg = len.sum / ((double)VolumeHashTable.Size);
8391 looks.avg = looks.sum / ((double)VolumeHashTable.Size);
8392 gets.avg = gets.sum / ((double)VolumeHashTable.Size);
8393 reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
8395 /* dump global stats */
8396 Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
8397 Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
8398 DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
8399 DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
8400 DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
8401 DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
8402 Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
8403 DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
8404 DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
8405 DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
8406 DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
8407 Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
8408 DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
8409 DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
8410 DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
8411 DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
8412 Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
8413 DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
8414 DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
8415 DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
8416 DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
8418 /* print extended disk related statistics */
8420 struct DiskPartition64 * diskP;
8421 afs_uint32 vol_count[VOLMAXPARTS+1];
8422 byte part_exists[VOLMAXPARTS+1];
8426 memset(vol_count, 0, sizeof(vol_count));
8427 memset(part_exists, 0, sizeof(part_exists));
8431 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
8433 vol_count[id] = diskP->vol_list.len;
8434 part_exists[id] = 1;
8438 for (i = 0; i <= VOLMAXPARTS; i++) {
8439 if (part_exists[i]) {
8440 /* XXX while this is currently safe, it is a violation
8441 * of the VGetPartitionById_r interface contract. */
8442 diskP = VGetPartitionById_r(i, 0);
8444 Log("Partition %s has %d online volumes\n",
8445 VPartitionPath(diskP), diskP->vol_list.len);
8452 /* print extended VLRU statistics */
8453 if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
8454 afs_uint32 idx, cur, lpos;
8459 Log("VLRU State Dump:\n\n");
8461 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
8462 Log("\t%s:\n", vlru_idx_to_string(idx));
8465 for (cur = vlru_stats.queue_info[idx].start;
8466 cur < vlru_stats.queue_info[idx].len;
8468 line[lpos++] = vlru_stats.vec[cur].volid;
8470 Log("\t\t%u, %u, %u, %u, %u,\n",
8471 line[0], line[1], line[2], line[3], line[4]);
8480 Log("\t\t%u, %u, %u, %u, %u\n",
8481 line[0], line[1], line[2], line[3], line[4]);
8486 free(vlru_stats.vec);
8493 VPrintExtendedCacheStats(int flags)
8496 VPrintExtendedCacheStats_r(flags);
8499 #endif /* AFS_DEMAND_ATTACH_FS */
8502 VCanScheduleSalvage(void)
8504 return vol_opts.canScheduleSalvage;
8510 return vol_opts.canUseFSSYNC;
8514 VCanUseSALVSYNC(void)
8516 return vol_opts.canUseSALVSYNC;