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"
128 #ifdef AFS_PTHREAD_ENV
130 #else /* AFS_PTHREAD_ENV */
131 #include "afs/assert.h"
132 #endif /* AFS_PTHREAD_ENV */
139 #if !defined(offsetof)
144 #define afs_stat stat64
145 #define afs_fstat fstat64
146 #define afs_open open64
147 #else /* !O_LARGEFILE */
148 #define afs_stat stat
149 #define afs_fstat fstat
150 #define afs_open open
151 #endif /* !O_LARGEFILE */
153 #ifdef AFS_PTHREAD_ENV
154 pthread_mutex_t vol_glock_mutex;
155 pthread_mutex_t vol_trans_mutex;
156 pthread_cond_t vol_put_volume_cond;
157 pthread_cond_t vol_sleep_cond;
158 pthread_cond_t vol_init_attach_cond;
159 int vol_attach_threads = 1;
160 #endif /* AFS_PTHREAD_ENV */
162 /* start-time configurable I/O parameters */
163 ih_init_params vol_io_params;
165 #ifdef AFS_DEMAND_ATTACH_FS
166 pthread_mutex_t vol_salvsync_mutex;
169 * Set this to 1 to disallow SALVSYNC communication in all threads; used
170 * during shutdown, since the salvageserver may have gone away.
172 static volatile sig_atomic_t vol_disallow_salvsync = 0;
173 #endif /* AFS_DEMAND_ATTACH_FS */
176 extern void *calloc(), *realloc();
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 #if defined(FAST_RESTART) && defined(AFS_DEMAND_ATTACH_FS)
494 # error FAST_RESTART and DAFS are incompatible. For the DAFS equivalent \
495 of FAST_RESTART, use the -unsafe-nosalvage fileserver argument
499 * assign default values to a VolumePackageOptions struct.
501 * Always call this on a VolumePackageOptions struct first, then set any
502 * specific options you want, then call VInitVolumePackage2.
504 * @param[in] pt caller's program type
505 * @param[out] opts volume package options
508 VOptDefaults(ProgramType pt, VolumePackageOptions *opts)
510 opts->nLargeVnodes = opts->nSmallVnodes = 5;
513 opts->canScheduleSalvage = 0;
514 opts->canUseFSSYNC = 0;
515 opts->canUseSALVSYNC = 0;
518 opts->unsafe_attach = 1;
519 #else /* !FAST_RESTART */
520 opts->unsafe_attach = 0;
521 #endif /* !FAST_RESTART */
525 opts->canScheduleSalvage = 1;
526 opts->canUseSALVSYNC = 1;
530 opts->canUseFSSYNC = 1;
534 opts->nLargeVnodes = 0;
535 opts->nSmallVnodes = 0;
537 opts->canScheduleSalvage = 1;
538 opts->canUseFSSYNC = 1;
548 VInitVolumePackage2(ProgramType pt, VolumePackageOptions * opts)
550 int errors = 0; /* Number of errors while finding vice partitions. */
555 memset(&VStats, 0, sizeof(VStats));
556 VStats.hdr_cache_size = 200;
558 VInitPartitionPackage();
560 #ifdef AFS_DEMAND_ATTACH_FS
561 if (programType == fileServer) {
564 VLRU_SetOptions(VLRU_SET_ENABLED, 0);
566 assert(pthread_key_create(&VThread_key, NULL) == 0);
569 #ifdef AFS_PTHREAD_ENV
570 assert(pthread_mutex_init(&vol_glock_mutex, NULL) == 0);
571 assert(pthread_mutex_init(&vol_trans_mutex, NULL) == 0);
572 assert(pthread_cond_init(&vol_put_volume_cond, NULL) == 0);
573 assert(pthread_cond_init(&vol_sleep_cond, NULL) == 0);
574 assert(pthread_cond_init(&vol_init_attach_cond, NULL) == 0);
575 #else /* AFS_PTHREAD_ENV */
577 #endif /* AFS_PTHREAD_ENV */
578 Lock_Init(&vol_listLock);
580 srandom(time(0)); /* For VGetVolumeInfo */
582 #ifdef AFS_DEMAND_ATTACH_FS
583 assert(pthread_mutex_init(&vol_salvsync_mutex, NULL) == 0);
584 #endif /* AFS_DEMAND_ATTACH_FS */
586 /* Ok, we have done enough initialization that fileserver can
587 * start accepting calls, even though the volumes may not be
588 * available just yet.
592 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_SERVER)
593 if (programType == salvageServer) {
596 #endif /* AFS_DEMAND_ATTACH_FS */
597 #ifdef FSSYNC_BUILD_SERVER
598 if (programType == fileServer) {
602 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_CLIENT)
603 if (VCanUseSALVSYNC()) {
604 /* establish a connection to the salvager at this point */
605 assert(VConnectSALV() != 0);
607 #endif /* AFS_DEMAND_ATTACH_FS */
609 if (opts->volcache > VStats.hdr_cache_size)
610 VStats.hdr_cache_size = opts->volcache;
611 VInitVolumeHeaderCache(VStats.hdr_cache_size);
613 VInitVnodes(vLarge, opts->nLargeVnodes);
614 VInitVnodes(vSmall, opts->nSmallVnodes);
617 errors = VAttachPartitions();
621 if (programType != fileServer) {
622 errors = VInitAttachVolumes(programType);
628 #ifdef FSSYNC_BUILD_CLIENT
629 if (VCanUseFSSYNC()) {
631 #ifdef AFS_DEMAND_ATTACH_FS
632 if (programType == salvageServer) {
633 Log("Unable to connect to file server; aborted\n");
636 #endif /* AFS_DEMAND_ATTACH_FS */
637 Log("Unable to connect to file server; will retry at need\n");
640 #endif /* FSSYNC_BUILD_CLIENT */
645 #if !defined(AFS_PTHREAD_ENV)
647 * Attach volumes in vice partitions
649 * @param[in] pt calling program type
652 * @note This is the original, non-threaded version of attach parititions.
654 * @post VInit state is 2
657 VInitAttachVolumes(ProgramType pt)
660 if (pt == fileServer) {
661 struct DiskPartition64 *diskP;
662 /* Attach all the volumes in this partition */
663 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
664 int nAttached = 0, nUnattached = 0;
665 assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
669 VInit = 2; /* Initialized, and all volumes have been attached */
670 LWP_NoYieldSignal(VInitAttachVolumes);
674 #endif /* !AFS_PTHREAD_ENV */
676 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_DEMAND_ATTACH_FS)
678 * Attach volumes in vice partitions
680 * @param[in] pt calling program type
683 * @note Threaded version of attach parititions.
685 * @post VInit state is 2
688 VInitAttachVolumes(ProgramType pt)
691 if (pt == fileServer) {
692 struct DiskPartition64 *diskP;
693 struct vinitvolumepackage_thread_t params;
694 struct diskpartition_queue_t * dpq;
695 int i, threads, parts;
697 pthread_attr_t attrs;
699 assert(pthread_cond_init(¶ms.thread_done_cv,NULL) == 0);
701 params.n_threads_complete = 0;
703 /* create partition work queue */
704 for (parts=0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
705 dpq = (diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
708 queue_Append(¶ms,dpq);
711 threads = MIN(parts, vol_attach_threads);
714 /* spawn off a bunch of initialization threads */
715 assert(pthread_attr_init(&attrs) == 0);
716 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
718 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
719 Log("VInitVolumePackage: using %d threads to attach volumes on %d partitions\n",
723 for (i=0; i < threads; i++) {
726 assert(pthread_create
727 (&tid, &attrs, &VInitVolumePackageThread,
729 AFS_SIGSET_RESTORE();
732 while(params.n_threads_complete < threads) {
733 VOL_CV_WAIT(¶ms.thread_done_cv);
737 assert(pthread_attr_destroy(&attrs) == 0);
739 /* if we're only going to run one init thread, don't bother creating
741 Log("VInitVolumePackage: beginning single-threaded fileserver startup\n");
742 Log("VInitVolumePackage: using 1 thread to attach volumes on %d partition(s)\n",
745 VInitVolumePackageThread(¶ms);
748 assert(pthread_cond_destroy(¶ms.thread_done_cv) == 0);
751 VInit = 2; /* Initialized, and all volumes have been attached */
752 assert(pthread_cond_broadcast(&vol_init_attach_cond) == 0);
758 VInitVolumePackageThread(void * args) {
760 struct DiskPartition64 *diskP;
761 struct vinitvolumepackage_thread_t * params;
762 struct diskpartition_queue_t * dpq;
764 params = (vinitvolumepackage_thread_t *) args;
768 /* Attach all the volumes in this partition */
769 while (queue_IsNotEmpty(params)) {
770 int nAttached = 0, nUnattached = 0;
772 if (vinit_attach_abort) {
773 Log("Aborting initialization\n");
777 dpq = queue_First(params,diskpartition_queue_t);
783 assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
789 params->n_threads_complete++;
790 pthread_cond_signal(¶ms->thread_done_cv);
794 #endif /* AFS_PTHREAD_ENV && !AFS_DEMAND_ATTACH_FS */
796 #if defined(AFS_DEMAND_ATTACH_FS)
798 * Attach volumes in vice partitions
800 * @param[in] pt calling program type
803 * @note Threaded version of attach partitions.
805 * @post VInit state is 2
808 VInitAttachVolumes(ProgramType pt)
811 if (pt == fileServer) {
813 struct DiskPartition64 *diskP;
814 struct partition_queue pq;
815 struct volume_init_queue vq;
817 int i, threads, parts;
819 pthread_attr_t attrs;
821 /* create partition work queue */
823 assert(pthread_cond_init(&(pq.cv), NULL) == 0);
824 assert(pthread_mutex_init(&(pq.mutex), NULL) == 0);
825 for (parts = 0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
826 struct diskpartition_queue_t *dp;
827 dp = (struct diskpartition_queue_t*)malloc(sizeof(struct diskpartition_queue_t));
830 queue_Append(&pq, dp);
833 /* number of worker threads; at least one, not to exceed the number of partitions */
834 threads = MIN(parts, vol_attach_threads);
836 /* create volume work queue */
838 assert(pthread_cond_init(&(vq.cv), NULL) == 0);
839 assert(pthread_mutex_init(&(vq.mutex), NULL) == 0);
841 assert(pthread_attr_init(&attrs) == 0);
842 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
844 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
845 Log("VInitVolumePackage: using %d threads to pre-attach volumes on %d partitions\n",
848 /* create threads to scan disk partitions. */
849 for (i=0; i < threads; i++) {
850 struct vinitvolumepackage_thread_param *params;
853 params = (struct vinitvolumepackage_thread_param *)malloc(sizeof(struct vinitvolumepackage_thread_param));
857 params->nthreads = threads;
858 params->thread = i+1;
861 assert(pthread_create (&tid, &attrs, &VInitVolumePackageThread, (void*)params) == 0);
862 AFS_SIGSET_RESTORE();
865 VInitPreAttachVolumes(threads, &vq);
867 assert(pthread_attr_destroy(&attrs) == 0);
868 assert(pthread_cond_destroy(&pq.cv) == 0);
869 assert(pthread_mutex_destroy(&pq.mutex) == 0);
870 assert(pthread_cond_destroy(&vq.cv) == 0);
871 assert(pthread_mutex_destroy(&vq.mutex) == 0);
875 VInit = 2; /* Initialized, and all volumes have been attached */
876 assert(pthread_cond_broadcast(&vol_init_attach_cond) == 0);
883 * Volume package initialization worker thread. Scan partitions for volume
884 * header files. Gather batches of volume ids and dispatch them to
885 * the main thread to be preattached. The volume preattachement is done
886 * in the main thread to avoid global volume lock contention.
889 VInitVolumePackageThread(void *args)
891 struct vinitvolumepackage_thread_param *params;
892 struct DiskPartition64 *partition;
893 struct partition_queue *pq;
894 struct volume_init_queue *vq;
895 struct volume_init_batch *vb;
898 params = (struct vinitvolumepackage_thread_param *)args;
904 vb = (struct volume_init_batch*)malloc(sizeof(struct volume_init_batch));
906 vb->thread = params->thread;
910 Log("Scanning partitions on thread %d of %d\n", params->thread, params->nthreads);
911 while((partition = VInitNextPartition(pq))) {
915 Log("Partition %s: pre-attaching volumes\n", partition->name);
916 dirp = opendir(VPartitionPath(partition));
918 Log("opendir on Partition %s failed, errno=%d!\n", partition->name, errno);
921 while ((vid = VInitNextVolumeId(dirp))) {
922 Volume *vp = (Volume*)malloc(sizeof(Volume));
924 memset(vp, 0, sizeof(Volume));
925 vp->device = partition->device;
926 vp->partition = partition;
928 queue_Init(&vp->vnode_list);
929 assert(pthread_cond_init(&V_attachCV(vp), NULL) == 0);
931 vb->batch[vb->size++] = vp;
932 if (vb->size == VINIT_BATCH_MAX_SIZE) {
933 assert(pthread_mutex_lock(&vq->mutex) == 0);
934 queue_Append(vq, vb);
935 assert(pthread_cond_broadcast(&vq->cv) == 0);
936 assert(pthread_mutex_unlock(&vq->mutex) == 0);
938 vb = (struct volume_init_batch*)malloc(sizeof(struct volume_init_batch));
940 vb->thread = params->thread;
949 assert(pthread_mutex_lock(&vq->mutex) == 0);
950 queue_Append(vq, vb);
951 assert(pthread_cond_broadcast(&vq->cv) == 0);
952 assert(pthread_mutex_unlock(&vq->mutex) == 0);
954 Log("Partition scan thread %d of %d ended\n", params->thread, params->nthreads);
960 * Read next element from the pre-populated partition list.
962 static struct DiskPartition64*
963 VInitNextPartition(struct partition_queue *pq)
965 struct DiskPartition64 *partition;
966 struct diskpartition_queue_t *dp; /* queue element */
968 if (vinit_attach_abort) {
969 Log("Aborting volume preattach thread.\n");
973 /* get next partition to scan */
974 assert(pthread_mutex_lock(&pq->mutex) == 0);
975 if (queue_IsEmpty(pq)) {
976 assert(pthread_mutex_unlock(&pq->mutex) == 0);
979 dp = queue_First(pq, diskpartition_queue_t);
981 assert(pthread_mutex_unlock(&pq->mutex) == 0);
986 partition = dp->diskP;
992 * Find next volume id on the partition.
995 VInitNextVolumeId(DIR *dirp)
1001 while((d = readdir(dirp))) {
1002 if (vinit_attach_abort) {
1003 Log("Aborting volume preattach thread.\n");
1006 ext = strrchr(d->d_name, '.');
1007 if (d->d_name[0] == 'V' && ext && strcmp(ext, VHDREXT) == 0) {
1008 vid = VolumeNumber(d->d_name);
1012 Log("Warning: bogus volume header file: %s\n", d->d_name);
1019 * Preattach volumes in batches to avoid lock contention.
1022 VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq)
1024 struct volume_init_batch *vb;
1028 /* dequeue next volume */
1029 pthread_mutex_lock(&vq->mutex);
1030 if (queue_IsEmpty(vq)) {
1031 pthread_cond_wait(&vq->cv, &vq->mutex);
1033 vb = queue_First(vq, volume_init_batch);
1035 pthread_mutex_unlock(&vq->mutex);
1039 for (i = 0; i<vb->size; i++) {
1045 dup = VLookupVolume_r(&ec, vp->hashid, NULL);
1047 Log("Error looking up volume, code=%d\n", ec);
1050 Log("Warning: Duplicate volume id %d detected.\n", vp->hashid);
1053 /* put pre-attached volume onto the hash table
1054 * and bring it up to the pre-attached state */
1055 AddVolumeToHashTable(vp, vp->hashid);
1056 AddVolumeToVByPList_r(vp);
1057 VLRU_Init_Node_r(vp);
1058 VChangeState_r(vp, VOL_STATE_PREATTACHED);
1071 #endif /* AFS_DEMAND_ATTACH_FS */
1073 #if !defined(AFS_DEMAND_ATTACH_FS)
1075 * attach all volumes on a given disk partition
1078 VAttachVolumesByPartition(struct DiskPartition64 *diskP, int * nAttached, int * nUnattached)
1084 Log("Partition %s: attaching volumes\n", diskP->name);
1085 dirp = opendir(VPartitionPath(diskP));
1087 Log("opendir on Partition %s failed!\n", diskP->name);
1091 while ((dp = readdir(dirp))) {
1093 p = strrchr(dp->d_name, '.');
1095 if (vinit_attach_abort) {
1096 Log("Partition %s: abort attach volumes\n", diskP->name);
1100 if (p != NULL && strcmp(p, VHDREXT) == 0) {
1103 vp = VAttachVolumeByName(&error, diskP->name, dp->d_name,
1105 (*(vp ? nAttached : nUnattached))++;
1106 if (error == VOFFLINE)
1107 Log("Volume %d stays offline (/vice/offline/%s exists)\n", VolumeNumber(dp->d_name), dp->d_name);
1108 else if (LogLevel >= 5) {
1109 Log("Partition %s: attached volume %d (%s)\n",
1110 diskP->name, VolumeNumber(dp->d_name),
1119 Log("Partition %s: attached %d volumes; %d volumes not attached\n", diskP->name, *nAttached, *nUnattached);
1124 #endif /* !AFS_DEMAND_ATTACH_FS */
1126 /***************************************************/
1127 /* Shutdown routines */
1128 /***************************************************/
1132 * highly multithreaded volume package shutdown
1134 * with the demand attach fileserver extensions,
1135 * VShutdown has been modified to be multithreaded.
1136 * In order to achieve optimal use of many threads,
1137 * the shutdown code involves one control thread and
1138 * n shutdown worker threads. The control thread
1139 * periodically examines the number of volumes available
1140 * for shutdown on each partition, and produces a worker
1141 * thread allocation schedule. The idea is to eliminate
1142 * redundant scheduling computation on the workers by
1143 * having a single master scheduler.
1145 * The scheduler's objectives are:
1147 * each partition with volumes remaining gets allocated
1148 * at least 1 thread (assuming sufficient threads)
1150 * threads are allocated proportional to the number of
1151 * volumes remaining to be offlined. This ensures that
1152 * the OS I/O scheduler has many requests to elevator
1153 * seek on partitions that will (presumably) take the
1154 * longest amount of time (from now) to finish shutdown
1155 * (3) keep threads busy
1156 * when there are extra threads, they are assigned to
1157 * partitions using a simple round-robin algorithm
1159 * In the future, we may wish to add the ability to adapt
1160 * to the relative performance patterns of each disk
1165 * multi-step shutdown process
1167 * demand attach shutdown is a four-step process. Each
1168 * shutdown "pass" shuts down increasingly more difficult
1169 * volumes. The main purpose is to achieve better cache
1170 * utilization during shutdown.
1173 * shutdown volumes in the unattached, pre-attached
1176 * shutdown attached volumes with cached volume headers
1178 * shutdown all volumes in non-exclusive states
1180 * shutdown all remaining volumes
1183 #ifdef AFS_DEMAND_ATTACH_FS
1189 struct DiskPartition64 * diskP;
1190 struct diskpartition_queue_t * dpq;
1191 vshutdown_thread_t params;
1193 pthread_attr_t attrs;
1195 memset(¶ms, 0, sizeof(vshutdown_thread_t));
1198 Log("VShutdown: aborting attach volumes\n");
1199 vinit_attach_abort = 1;
1200 VOL_CV_WAIT(&vol_init_attach_cond);
1203 for (params.n_parts=0, diskP = DiskPartitionList;
1204 diskP; diskP = diskP->next, params.n_parts++);
1206 Log("VShutdown: shutting down on-line volumes on %d partition%s...\n",
1207 params.n_parts, params.n_parts > 1 ? "s" : "");
1209 if (vol_attach_threads > 1) {
1210 /* prepare for parallel shutdown */
1211 params.n_threads = vol_attach_threads;
1212 assert(pthread_mutex_init(¶ms.lock, NULL) == 0);
1213 assert(pthread_cond_init(¶ms.cv, NULL) == 0);
1214 assert(pthread_cond_init(¶ms.master_cv, NULL) == 0);
1215 assert(pthread_attr_init(&attrs) == 0);
1216 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
1217 queue_Init(¶ms);
1219 /* setup the basic partition information structures for
1220 * parallel shutdown */
1221 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1223 struct rx_queue * qp, * nqp;
1227 VVByPListWait_r(diskP);
1228 VVByPListBeginExclusive_r(diskP);
1231 for (queue_Scan(&diskP->vol_list, qp, nqp, rx_queue)) {
1232 vp = (Volume *)((char *)qp - offsetof(Volume, vol_list));
1236 Log("VShutdown: partition %s has %d volumes with attached headers\n",
1237 VPartitionPath(diskP), count);
1240 /* build up the pass 0 shutdown work queue */
1241 dpq = (struct diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
1242 assert(dpq != NULL);
1244 queue_Prepend(¶ms, dpq);
1246 params.part_pass_head[diskP->index] = queue_First(&diskP->vol_list, rx_queue);
1249 Log("VShutdown: beginning parallel fileserver shutdown\n");
1250 Log("VShutdown: using %d threads to offline volumes on %d partition%s\n",
1251 vol_attach_threads, params.n_parts, params.n_parts > 1 ? "s" : "" );
1253 /* do pass 0 shutdown */
1254 assert(pthread_mutex_lock(¶ms.lock) == 0);
1255 for (i=0; i < params.n_threads; i++) {
1256 assert(pthread_create
1257 (&tid, &attrs, &VShutdownThread,
1261 /* wait for all the pass 0 shutdowns to complete */
1262 while (params.n_threads_complete < params.n_threads) {
1263 assert(pthread_cond_wait(¶ms.master_cv, ¶ms.lock) == 0);
1265 params.n_threads_complete = 0;
1267 assert(pthread_cond_broadcast(¶ms.cv) == 0);
1268 assert(pthread_mutex_unlock(¶ms.lock) == 0);
1270 Log("VShutdown: pass 0 completed using the 1 thread per partition algorithm\n");
1271 Log("VShutdown: starting passes 1 through 3 using finely-granular mp-fast algorithm\n");
1273 /* run the parallel shutdown scheduler. it will drop the glock internally */
1274 ShutdownController(¶ms);
1276 /* wait for all the workers to finish pass 3 and terminate */
1277 while (params.pass < 4) {
1278 VOL_CV_WAIT(¶ms.cv);
1281 assert(pthread_attr_destroy(&attrs) == 0);
1282 assert(pthread_cond_destroy(¶ms.cv) == 0);
1283 assert(pthread_cond_destroy(¶ms.master_cv) == 0);
1284 assert(pthread_mutex_destroy(¶ms.lock) == 0);
1286 /* drop the VByPList exclusive reservations */
1287 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1288 VVByPListEndExclusive_r(diskP);
1289 Log("VShutdown: %s stats : (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1290 VPartitionPath(diskP),
1291 params.stats[0][diskP->index],
1292 params.stats[1][diskP->index],
1293 params.stats[2][diskP->index],
1294 params.stats[3][diskP->index]);
1297 Log("VShutdown: shutdown finished using %d threads\n", params.n_threads);
1299 /* if we're only going to run one shutdown thread, don't bother creating
1301 Log("VShutdown: beginning single-threaded fileserver shutdown\n");
1303 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1304 VShutdownByPartition_r(diskP);
1308 Log("VShutdown: complete.\n");
1311 #else /* AFS_DEMAND_ATTACH_FS */
1317 register Volume *vp, *np;
1318 register afs_int32 code;
1321 Log("VShutdown: aborting attach volumes\n");
1322 vinit_attach_abort = 1;
1323 #ifdef AFS_PTHREAD_ENV
1324 VOL_CV_WAIT(&vol_init_attach_cond);
1326 LWP_WaitProcess(VInitAttachVolumes);
1327 #endif /* AFS_PTHREAD_ENV */
1330 Log("VShutdown: shutting down on-line volumes...\n");
1331 for (i = 0; i < VolumeHashTable.Size; i++) {
1332 /* try to hold first volume in the hash table */
1333 for (queue_Scan(&VolumeHashTable.Table[i],vp,np,Volume)) {
1337 Log("VShutdown: Attempting to take volume %u offline.\n",
1340 /* next, take the volume offline (drops reference count) */
1341 VOffline_r(vp, "File server was shut down");
1345 Log("VShutdown: complete.\n");
1347 #endif /* AFS_DEMAND_ATTACH_FS */
1360 * stop new activity (e.g. SALVSYNC) from occurring
1362 * Use this to make the volume package less busy; for example, during
1363 * shutdown. This doesn't actually shutdown/detach anything in the
1364 * volume package, but prevents certain processes from ocurring. For
1365 * example, preventing new SALVSYNC communication in DAFS. In theory, we
1366 * could also use this to prevent new volume attachment, or prevent
1367 * other programs from checking out volumes, etc.
1372 #ifdef AFS_DEMAND_ATTACH_FS
1373 /* make sure we don't try to contact the salvageserver, since it may
1374 * not be around anymore */
1375 vol_disallow_salvsync = 1;
1379 #ifdef AFS_DEMAND_ATTACH_FS
1382 * shutdown control thread
1385 ShutdownController(vshutdown_thread_t * params)
1388 struct DiskPartition64 * diskP;
1390 vshutdown_thread_t shadow;
1392 ShutdownCreateSchedule(params);
1394 while ((params->pass < 4) &&
1395 (params->n_threads_complete < params->n_threads)) {
1396 /* recompute schedule once per second */
1398 memcpy(&shadow, params, sizeof(vshutdown_thread_t));
1402 Log("ShutdownController: schedule version=%d, vol_remaining=%d, pass=%d\n",
1403 shadow.schedule_version, shadow.vol_remaining, shadow.pass);
1404 Log("ShutdownController: n_threads_complete=%d, n_parts_done_pass=%d\n",
1405 shadow.n_threads_complete, shadow.n_parts_done_pass);
1406 for (diskP = DiskPartitionList; diskP; diskP=diskP->next) {
1408 Log("ShutdownController: part[%d] : (len=%d, thread_target=%d, done_pass=%d, pass_head=%p)\n",
1410 diskP->vol_list.len,
1411 shadow.part_thread_target[id],
1412 shadow.part_done_pass[id],
1413 shadow.part_pass_head[id]);
1419 ShutdownCreateSchedule(params);
1423 /* create the shutdown thread work schedule.
1424 * this scheduler tries to implement fairness
1425 * by allocating at least 1 thread to each
1426 * partition with volumes to be shutdown,
1427 * and then it attempts to allocate remaining
1428 * threads based upon the amount of work left
1431 ShutdownCreateSchedule(vshutdown_thread_t * params)
1433 struct DiskPartition64 * diskP;
1434 int sum, thr_workload, thr_left;
1435 int part_residue[VOLMAXPARTS+1];
1438 /* compute the total number of outstanding volumes */
1440 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1441 sum += diskP->vol_list.len;
1444 params->schedule_version++;
1445 params->vol_remaining = sum;
1450 /* compute average per-thread workload */
1451 thr_workload = sum / params->n_threads;
1452 if (sum % params->n_threads)
1455 thr_left = params->n_threads;
1456 memset(&part_residue, 0, sizeof(part_residue));
1458 /* for fairness, give every partition with volumes remaining
1459 * at least one thread */
1460 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1462 if (diskP->vol_list.len) {
1463 params->part_thread_target[id] = 1;
1466 params->part_thread_target[id] = 0;
1470 if (thr_left && thr_workload) {
1471 /* compute length-weighted workloads */
1474 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1476 delta = (diskP->vol_list.len / thr_workload) -
1477 params->part_thread_target[id];
1481 if (delta < thr_left) {
1482 params->part_thread_target[id] += delta;
1485 params->part_thread_target[id] += thr_left;
1493 /* try to assign any leftover threads to partitions that
1494 * had volume lengths closer to needing thread_target+1 */
1495 int max_residue, max_id = 0;
1497 /* compute the residues */
1498 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1500 part_residue[id] = diskP->vol_list.len -
1501 (params->part_thread_target[id] * thr_workload);
1504 /* now try to allocate remaining threads to partitions with the
1505 * highest residues */
1508 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1510 if (part_residue[id] > max_residue) {
1511 max_residue = part_residue[id];
1520 params->part_thread_target[max_id]++;
1522 part_residue[max_id] = 0;
1527 /* punt and give any remaining threads equally to each partition */
1529 if (thr_left >= params->n_parts) {
1530 alloc = thr_left / params->n_parts;
1531 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1533 params->part_thread_target[id] += alloc;
1538 /* finish off the last of the threads */
1539 for (diskP = DiskPartitionList; thr_left && diskP; diskP = diskP->next) {
1541 params->part_thread_target[id]++;
1547 /* worker thread for parallel shutdown */
1549 VShutdownThread(void * args)
1551 vshutdown_thread_t * params;
1552 int found, pass, schedule_version_save, count;
1553 struct DiskPartition64 *diskP;
1554 struct diskpartition_queue_t * dpq;
1557 params = (vshutdown_thread_t *) args;
1559 /* acquire the shutdown pass 0 lock */
1560 assert(pthread_mutex_lock(¶ms->lock) == 0);
1562 /* if there's still pass 0 work to be done,
1563 * get a work entry, and do a pass 0 shutdown */
1564 if (queue_IsNotEmpty(params)) {
1565 dpq = queue_First(params, diskpartition_queue_t);
1567 assert(pthread_mutex_unlock(¶ms->lock) == 0);
1573 while (ShutdownVolumeWalk_r(diskP, 0, ¶ms->part_pass_head[id]))
1575 params->stats[0][diskP->index] = count;
1576 assert(pthread_mutex_lock(¶ms->lock) == 0);
1579 params->n_threads_complete++;
1580 if (params->n_threads_complete == params->n_threads) {
1581 /* notify control thread that all workers have completed pass 0 */
1582 assert(pthread_cond_signal(¶ms->master_cv) == 0);
1584 while (params->pass == 0) {
1585 assert(pthread_cond_wait(¶ms->cv, ¶ms->lock) == 0);
1589 assert(pthread_mutex_unlock(¶ms->lock) == 0);
1592 pass = params->pass;
1595 /* now escalate through the more complicated shutdowns */
1597 schedule_version_save = params->schedule_version;
1599 /* find a disk partition to work on */
1600 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1602 if (params->part_thread_target[id] && !params->part_done_pass[id]) {
1603 params->part_thread_target[id]--;
1610 /* hmm. for some reason the controller thread couldn't find anything for
1611 * us to do. let's see if there's anything we can do */
1612 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1614 if (diskP->vol_list.len && !params->part_done_pass[id]) {
1617 } else if (!params->part_done_pass[id]) {
1618 params->part_done_pass[id] = 1;
1619 params->n_parts_done_pass++;
1621 Log("VShutdown: done shutting down volumes on partition %s.\n",
1622 VPartitionPath(diskP));
1628 /* do work on this partition until either the controller
1629 * creates a new schedule, or we run out of things to do
1630 * on this partition */
1633 while (!params->part_done_pass[id] &&
1634 (schedule_version_save == params->schedule_version)) {
1635 /* ShutdownVolumeWalk_r will drop the glock internally */
1636 if (!ShutdownVolumeWalk_r(diskP, pass, ¶ms->part_pass_head[id])) {
1637 if (!params->part_done_pass[id]) {
1638 params->part_done_pass[id] = 1;
1639 params->n_parts_done_pass++;
1641 Log("VShutdown: done shutting down volumes on partition %s.\n",
1642 VPartitionPath(diskP));
1650 params->stats[pass][id] += count;
1652 /* ok, everyone is done this pass, proceed */
1655 params->n_threads_complete++;
1656 while (params->pass == pass) {
1657 if (params->n_threads_complete == params->n_threads) {
1658 /* we are the last thread to complete, so we will
1659 * reinitialize worker pool state for the next pass */
1660 params->n_threads_complete = 0;
1661 params->n_parts_done_pass = 0;
1663 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1665 params->part_done_pass[id] = 0;
1666 params->part_pass_head[id] = queue_First(&diskP->vol_list, rx_queue);
1669 /* compute a new thread schedule before releasing all the workers */
1670 ShutdownCreateSchedule(params);
1672 /* wake up all the workers */
1673 assert(pthread_cond_broadcast(¶ms->cv) == 0);
1676 Log("VShutdown: pass %d completed using %d threads on %d partitions\n",
1677 pass, params->n_threads, params->n_parts);
1680 VOL_CV_WAIT(¶ms->cv);
1683 pass = params->pass;
1697 /* shut down all volumes on a given disk partition
1699 * note that this function will not allow mp-fast
1700 * shutdown of a partition */
1702 VShutdownByPartition_r(struct DiskPartition64 * dp)
1708 /* wait for other exclusive ops to finish */
1709 VVByPListWait_r(dp);
1711 /* begin exclusive access */
1712 VVByPListBeginExclusive_r(dp);
1714 /* pick the low-hanging fruit first,
1715 * then do the complicated ones last
1716 * (has the advantage of keeping
1717 * in-use volumes up until the bitter end) */
1718 for (pass = 0, total=0; pass < 4; pass++) {
1719 pass_stats[pass] = ShutdownVByPForPass_r(dp, pass);
1720 total += pass_stats[pass];
1723 /* end exclusive access */
1724 VVByPListEndExclusive_r(dp);
1726 Log("VShutdownByPartition: shut down %d volumes on %s (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1727 total, VPartitionPath(dp), pass_stats[0], pass_stats[1], pass_stats[2], pass_stats[3]);
1732 /* internal shutdown functionality
1734 * for multi-pass shutdown:
1735 * 0 to only "shutdown" {pre,un}attached and error state volumes
1736 * 1 to also shutdown attached volumes w/ volume header loaded
1737 * 2 to also shutdown attached volumes w/o volume header loaded
1738 * 3 to also shutdown exclusive state volumes
1740 * caller MUST hold exclusive access on the hash chain
1741 * because we drop vol_glock_mutex internally
1743 * this function is reentrant for passes 1--3
1744 * (e.g. multiple threads can cooperate to
1745 * shutdown a partition mp-fast)
1747 * pass 0 is not scaleable because the volume state data is
1748 * synchronized by vol_glock mutex, and the locking overhead
1749 * is too high to drop the lock long enough to do linked list
1753 ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass)
1755 struct rx_queue * q = queue_First(&dp->vol_list, rx_queue);
1758 while (ShutdownVolumeWalk_r(dp, pass, &q))
1764 /* conditionally shutdown one volume on partition dp
1765 * returns 1 if a volume was shutdown in this pass,
1768 ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
1769 struct rx_queue ** idx)
1771 struct rx_queue *qp, *nqp;
1776 for (queue_ScanFrom(&dp->vol_list, qp, qp, nqp, rx_queue)) {
1777 vp = (Volume *) (((char *)qp) - offsetof(Volume, vol_list));
1781 if ((V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1782 (V_attachState(vp) != VOL_STATE_ERROR) &&
1783 (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1787 if ((V_attachState(vp) == VOL_STATE_ATTACHED) &&
1788 (vp->header == NULL)) {
1792 if (VIsExclusiveState(V_attachState(vp))) {
1797 DeleteVolumeFromVByPList_r(vp);
1798 VShutdownVolume_r(vp);
1808 * shutdown a specific volume
1810 /* caller MUST NOT hold a heavyweight ref on vp */
1812 VShutdownVolume_r(Volume * vp)
1816 VCreateReservation_r(vp);
1818 if (LogLevel >= 5) {
1819 Log("VShutdownVolume_r: vid=%u, device=%d, state=%hu\n",
1820 vp->hashid, vp->partition->device, V_attachState(vp));
1823 /* wait for other blocking ops to finish */
1824 VWaitExclusiveState_r(vp);
1826 assert(VIsValidState(V_attachState(vp)));
1828 switch(V_attachState(vp)) {
1829 case VOL_STATE_SALVAGING:
1830 /* Leave salvaging volumes alone. Any in-progress salvages will
1831 * continue working after viced shuts down. This is intentional.
1834 case VOL_STATE_PREATTACHED:
1835 case VOL_STATE_ERROR:
1836 VChangeState_r(vp, VOL_STATE_UNATTACHED);
1837 case VOL_STATE_UNATTACHED:
1839 case VOL_STATE_GOING_OFFLINE:
1840 case VOL_STATE_SHUTTING_DOWN:
1841 case VOL_STATE_ATTACHED:
1845 Log("VShutdown: Attempting to take volume %u offline.\n",
1848 /* take the volume offline (drops reference count) */
1849 VOffline_r(vp, "File server was shut down");
1856 VCancelReservation_r(vp);
1860 #endif /* AFS_DEMAND_ATTACH_FS */
1863 /***************************************************/
1864 /* Header I/O routines */
1865 /***************************************************/
1867 /* open a descriptor for the inode (h),
1868 * read in an on-disk structure into buffer (to) of size (size),
1869 * verify versionstamp in structure has magic (magic) and
1870 * optionally verify version (version) if (version) is nonzero
1873 ReadHeader(Error * ec, IHandle_t * h, char *to, int size, bit32 magic,
1876 struct versionStamp *vsn;
1891 if (FDH_SEEK(fdP, 0, SEEK_SET) < 0) {
1893 FDH_REALLYCLOSE(fdP);
1896 vsn = (struct versionStamp *)to;
1897 if (FDH_READ(fdP, to, size) != size || vsn->magic != magic) {
1899 FDH_REALLYCLOSE(fdP);
1904 /* Check is conditional, in case caller wants to inspect version himself */
1905 if (version && vsn->version != version) {
1911 WriteVolumeHeader_r(Error * ec, Volume * vp)
1913 IHandle_t *h = V_diskDataHandle(vp);
1923 if (FDH_SEEK(fdP, 0, SEEK_SET) < 0) {
1925 FDH_REALLYCLOSE(fdP);
1928 if (FDH_WRITE(fdP, (char *)&V_disk(vp), sizeof(V_disk(vp)))
1929 != sizeof(V_disk(vp))) {
1931 FDH_REALLYCLOSE(fdP);
1937 /* VolumeHeaderToDisk
1938 * Allows for storing 64 bit inode numbers in on-disk volume header
1941 /* convert in-memory representation of a volume header to the
1942 * on-disk representation of a volume header */
1944 VolumeHeaderToDisk(VolumeDiskHeader_t * dh, VolumeHeader_t * h)
1947 memset(dh, 0, sizeof(VolumeDiskHeader_t));
1948 dh->stamp = h->stamp;
1950 dh->parent = h->parent;
1952 #ifdef AFS_64BIT_IOPS_ENV
1953 dh->volumeInfo_lo = (afs_int32) h->volumeInfo & 0xffffffff;
1954 dh->volumeInfo_hi = (afs_int32) (h->volumeInfo >> 32) & 0xffffffff;
1955 dh->smallVnodeIndex_lo = (afs_int32) h->smallVnodeIndex & 0xffffffff;
1956 dh->smallVnodeIndex_hi =
1957 (afs_int32) (h->smallVnodeIndex >> 32) & 0xffffffff;
1958 dh->largeVnodeIndex_lo = (afs_int32) h->largeVnodeIndex & 0xffffffff;
1959 dh->largeVnodeIndex_hi =
1960 (afs_int32) (h->largeVnodeIndex >> 32) & 0xffffffff;
1961 dh->linkTable_lo = (afs_int32) h->linkTable & 0xffffffff;
1962 dh->linkTable_hi = (afs_int32) (h->linkTable >> 32) & 0xffffffff;
1964 dh->volumeInfo_lo = h->volumeInfo;
1965 dh->smallVnodeIndex_lo = h->smallVnodeIndex;
1966 dh->largeVnodeIndex_lo = h->largeVnodeIndex;
1967 dh->linkTable_lo = h->linkTable;
1971 /* DiskToVolumeHeader
1972 * Converts an on-disk representation of a volume header to
1973 * the in-memory representation of a volume header.
1975 * Makes the assumption that AFS has *always*
1976 * zero'd the volume header file so that high parts of inode
1977 * numbers are 0 in older (SGI EFS) volume header files.
1980 DiskToVolumeHeader(VolumeHeader_t * h, VolumeDiskHeader_t * dh)
1982 memset(h, 0, sizeof(VolumeHeader_t));
1983 h->stamp = dh->stamp;
1985 h->parent = dh->parent;
1987 #ifdef AFS_64BIT_IOPS_ENV
1989 (Inode) dh->volumeInfo_lo | ((Inode) dh->volumeInfo_hi << 32);
1991 h->smallVnodeIndex =
1992 (Inode) dh->smallVnodeIndex_lo | ((Inode) dh->
1993 smallVnodeIndex_hi << 32);
1995 h->largeVnodeIndex =
1996 (Inode) dh->largeVnodeIndex_lo | ((Inode) dh->
1997 largeVnodeIndex_hi << 32);
1999 (Inode) dh->linkTable_lo | ((Inode) dh->linkTable_hi << 32);
2001 h->volumeInfo = dh->volumeInfo_lo;
2002 h->smallVnodeIndex = dh->smallVnodeIndex_lo;
2003 h->largeVnodeIndex = dh->largeVnodeIndex_lo;
2004 h->linkTable = dh->linkTable_lo;
2009 /***************************************************/
2010 /* Volume Attachment routines */
2011 /***************************************************/
2013 #ifdef AFS_DEMAND_ATTACH_FS
2015 * pre-attach a volume given its path.
2017 * @param[out] ec outbound error code
2018 * @param[in] partition partition path string
2019 * @param[in] name volume id string
2021 * @return volume object pointer
2023 * @note A pre-attached volume will only have its partition
2024 * and hashid fields initialized. At first call to
2025 * VGetVolume, the volume will be fully attached.
2029 VPreAttachVolumeByName(Error * ec, char *partition, char *name)
2033 vp = VPreAttachVolumeByName_r(ec, partition, name);
2039 * pre-attach a volume given its path.
2041 * @param[out] ec outbound error code
2042 * @param[in] partition path to vice partition
2043 * @param[in] name volume id string
2045 * @return volume object pointer
2047 * @pre VOL_LOCK held
2049 * @internal volume package internal use only.
2052 VPreAttachVolumeByName_r(Error * ec, char *partition, char *name)
2054 return VPreAttachVolumeById_r(ec,
2056 VolumeNumber(name));
2060 * pre-attach a volume given its path and numeric volume id.
2062 * @param[out] ec error code return
2063 * @param[in] partition path to vice partition
2064 * @param[in] volumeId numeric volume id
2066 * @return volume object pointer
2068 * @pre VOL_LOCK held
2070 * @internal volume package internal use only.
2073 VPreAttachVolumeById_r(Error * ec,
2078 struct DiskPartition64 *partp;
2082 assert(programType == fileServer);
2084 if (!(partp = VGetPartition_r(partition, 0))) {
2086 Log("VPreAttachVolumeById_r: Error getting partition (%s)\n", partition);
2090 vp = VLookupVolume_r(ec, volumeId, NULL);
2095 return VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2099 * preattach a volume.
2101 * @param[out] ec outbound error code
2102 * @param[in] partp pointer to partition object
2103 * @param[in] vp pointer to volume object
2104 * @param[in] vid volume id
2106 * @return volume object pointer
2108 * @pre VOL_LOCK is held.
2110 * @warning Returned volume object pointer does not have to
2111 * equal the pointer passed in as argument vp. There
2112 * are potential race conditions which can result in
2113 * the pointers having different values. It is up to
2114 * the caller to make sure that references are handled
2115 * properly in this case.
2117 * @note If there is already a volume object registered with
2118 * the same volume id, its pointer MUST be passed as
2119 * argument vp. Failure to do so will result in a silent
2120 * failure to preattach.
2122 * @internal volume package internal use only.
2125 VPreAttachVolumeByVp_r(Error * ec,
2126 struct DiskPartition64 * partp,
2134 /* check to see if pre-attach already happened */
2136 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
2137 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
2138 !VIsErrorState(V_attachState(vp))) {
2140 * pre-attach is a no-op in all but the following cases:
2142 * - volume is unattached
2143 * - volume is in an error state
2144 * - volume is pre-attached
2146 Log("VPreattachVolumeByVp_r: volume %u not in quiescent state\n", vid);
2149 /* we're re-attaching a volume; clear out some old state */
2150 memset(&vp->salvage, 0, sizeof(struct VolumeOnlineSalvage));
2152 if (V_partition(vp) != partp) {
2153 /* XXX potential race */
2154 DeleteVolumeFromVByPList_r(vp);
2157 /* if we need to allocate a new Volume struct,
2158 * go ahead and drop the vol glock, otherwise
2159 * do the basic setup synchronised, as it's
2160 * probably not worth dropping the lock */
2163 /* allocate the volume structure */
2164 vp = nvp = (Volume *) malloc(sizeof(Volume));
2166 memset(vp, 0, sizeof(Volume));
2167 queue_Init(&vp->vnode_list);
2168 assert(pthread_cond_init(&V_attachCV(vp), NULL) == 0);
2171 /* link the volume with its associated vice partition */
2172 vp->device = partp->device;
2173 vp->partition = partp;
2176 vp->specialStatus = 0;
2178 /* if we dropped the lock, reacquire the lock,
2179 * check for pre-attach races, and then add
2180 * the volume to the hash table */
2183 nvp = VLookupVolume_r(ec, vid, NULL);
2188 } else if (nvp) { /* race detected */
2193 /* hack to make up for VChangeState_r() decrementing
2194 * the old state counter */
2195 VStats.state_levels[0]++;
2199 /* put pre-attached volume onto the hash table
2200 * and bring it up to the pre-attached state */
2201 AddVolumeToHashTable(vp, vp->hashid);
2202 AddVolumeToVByPList_r(vp);
2203 VLRU_Init_Node_r(vp);
2204 VChangeState_r(vp, VOL_STATE_PREATTACHED);
2207 Log("VPreAttachVolumeByVp_r: volume %u pre-attached\n", vp->hashid);
2215 #endif /* AFS_DEMAND_ATTACH_FS */
2217 /* Attach an existing volume, given its pathname, and return a
2218 pointer to the volume header information. The volume also
2219 normally goes online at this time. An offline volume
2220 must be reattached to make it go online */
2222 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
2226 retVal = VAttachVolumeByName_r(ec, partition, name, mode);
2232 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
2234 register Volume *vp = NULL;
2235 struct DiskPartition64 *partp;
2239 #ifdef AFS_DEMAND_ATTACH_FS
2240 VolumeStats stats_save;
2242 #endif /* AFS_DEMAND_ATTACH_FS */
2246 volumeId = VolumeNumber(name);
2248 if (!(partp = VGetPartition_r(partition, 0))) {
2250 Log("VAttachVolume: Error getting partition (%s)\n", partition);
2254 if (VRequiresPartLock()) {
2256 VLockPartition_r(partition);
2257 } else if (programType == fileServer) {
2258 #ifdef AFS_DEMAND_ATTACH_FS
2259 /* lookup the volume in the hash table */
2260 vp = VLookupVolume_r(ec, volumeId, NULL);
2266 /* save any counters that are supposed to
2267 * be monotonically increasing over the
2268 * lifetime of the fileserver */
2269 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2271 memset(&stats_save, 0, sizeof(VolumeStats));
2274 /* if there's something in the hash table, and it's not
2275 * in the pre-attach state, then we may need to detach
2276 * it before proceeding */
2277 if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
2278 VCreateReservation_r(vp);
2279 VWaitExclusiveState_r(vp);
2281 /* at this point state must be one of:
2290 if (vp->specialStatus == VBUSY)
2293 /* if it's already attached, see if we can return it */
2294 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2295 VGetVolumeByVp_r(ec, vp);
2296 if (V_inUse(vp) == fileServer) {
2297 VCancelReservation_r(vp);
2301 /* otherwise, we need to detach, and attempt to re-attach */
2302 VDetachVolume_r(ec, vp);
2304 Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
2307 /* if it isn't fully attached, delete from the hash tables,
2308 and let the refcounter handle the rest */
2309 DeleteVolumeFromHashTable(vp);
2310 DeleteVolumeFromVByPList_r(vp);
2313 VCancelReservation_r(vp);
2317 /* pre-attach volume if it hasn't been done yet */
2319 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2320 (V_attachState(vp) == VOL_STATE_ERROR)) {
2322 vp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2330 /* handle pre-attach races
2332 * multiple threads can race to pre-attach a volume,
2333 * but we can't let them race beyond that
2335 * our solution is to let the first thread to bring
2336 * the volume into an exclusive state win; the other
2337 * threads just wait until it finishes bringing the
2338 * volume online, and then they do a vgetvolumebyvp
2340 if (svp && (svp != vp)) {
2341 /* wait for other exclusive ops to finish */
2342 VCreateReservation_r(vp);
2343 VWaitExclusiveState_r(vp);
2345 /* get a heavyweight ref, kill the lightweight ref, and return */
2346 VGetVolumeByVp_r(ec, vp);
2347 VCancelReservation_r(vp);
2351 /* at this point, we are chosen as the thread to do
2352 * demand attachment for this volume. all other threads
2353 * doing a getvolume on vp->hashid will block until we finish */
2355 /* make sure any old header cache entries are invalidated
2356 * before proceeding */
2357 FreeVolumeHeader(vp);
2359 VChangeState_r(vp, VOL_STATE_ATTACHING);
2361 /* restore any saved counters */
2362 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2363 #else /* AFS_DEMAND_ATTACH_FS */
2364 vp = VGetVolume_r(ec, volumeId);
2366 if (V_inUse(vp) == fileServer)
2368 if (vp->specialStatus == VBUSY)
2370 VDetachVolume_r(ec, vp);
2372 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2376 #endif /* AFS_DEMAND_ATTACH_FS */
2380 strcpy(path, VPartitionPath(partp));
2388 vp = (Volume *) calloc(1, sizeof(Volume));
2390 vp->hashid = volumeId;
2391 vp->device = partp->device;
2392 vp->partition = partp;
2393 queue_Init(&vp->vnode_list);
2394 #ifdef AFS_DEMAND_ATTACH_FS
2395 assert(pthread_cond_init(&V_attachCV(vp), NULL) == 0);
2396 #endif /* AFS_DEMAND_ATTACH_FS */
2399 /* attach2 is entered without any locks, and returns
2400 * with vol_glock_mutex held */
2401 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode);
2403 if (VCanUseFSSYNC() && vp) {
2404 #ifdef AFS_DEMAND_ATTACH_FS
2405 if ((mode == V_VOLUPD) || (VolumeWriteable(vp) && (mode == V_CLONE))) {
2406 /* mark volume header as in use so that volser crashes lead to a
2407 * salvage attempt */
2408 VUpdateVolume_r(ec, vp, 0);
2410 /* for dafs, we should tell the fileserver, except for V_PEEK
2411 * where we know it is not necessary */
2412 if (mode == V_PEEK) {
2413 vp->needsPutBack = 0;
2415 vp->needsPutBack = 1;
2417 #else /* !AFS_DEMAND_ATTACH_FS */
2418 /* duplicate computation in fssync.c about whether the server
2419 * takes the volume offline or not. If the volume isn't
2420 * offline, we must not return it when we detach the volume,
2421 * or the server will abort */
2422 if (mode == V_READONLY || mode == V_PEEK
2423 || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
2424 vp->needsPutBack = 0;
2426 vp->needsPutBack = 1;
2427 #endif /* !AFS_DEMAND_ATTACH_FS */
2429 /* OK, there's a problem here, but one that I don't know how to
2430 * fix right now, and that I don't think should arise often.
2431 * Basically, we should only put back this volume to the server if
2432 * it was given to us by the server, but since we don't have a vp,
2433 * we can't run the VolumeWriteable function to find out as we do
2434 * above when computing vp->needsPutBack. So we send it back, but
2435 * there's a path in VAttachVolume on the server which may abort
2436 * if this volume doesn't have a header. Should be pretty rare
2437 * for all of that to happen, but if it does, probably the right
2438 * fix is for the server to allow the return of readonly volumes
2439 * that it doesn't think are really checked out. */
2440 #ifdef FSSYNC_BUILD_CLIENT
2441 if (VCanUseFSSYNC() && vp == NULL &&
2442 mode != V_SECRETLY && mode != V_PEEK) {
2444 #ifdef AFS_DEMAND_ATTACH_FS
2445 /* If we couldn't attach but we scheduled a salvage, we already
2446 * notified the fileserver; don't online it now */
2447 if (*ec != VSALVAGING)
2448 #endif /* AFS_DEMAND_ATTACH_FS */
2449 FSYNC_VolOp(volumeId, partition, FSYNC_VOL_ON, 0, NULL);
2452 if (programType == fileServer && vp) {
2453 #ifdef AFS_DEMAND_ATTACH_FS
2455 * we can get here in cases where we don't "own"
2456 * the volume (e.g. volume owned by a utility).
2457 * short circuit around potential disk header races.
2459 if (V_attachState(vp) != VOL_STATE_ATTACHED) {
2463 VUpdateVolume_r(ec, vp, 0);
2465 Log("VAttachVolume: Error updating volume\n");
2470 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2471 #ifndef AFS_DEMAND_ATTACH_FS
2472 /* This is a hack: by temporarily setting the incore
2473 * dontSalvage flag ON, the volume will be put back on the
2474 * Update list (with dontSalvage OFF again). It will then
2475 * come back in N minutes with DONT_SALVAGE eventually
2476 * set. This is the way that volumes that have never had
2477 * it set get it set; or that volumes that have been
2478 * offline without DONT SALVAGE having been set also
2479 * eventually get it set */
2480 V_dontSalvage(vp) = DONT_SALVAGE;
2481 #endif /* !AFS_DEMAND_ATTACH_FS */
2482 VAddToVolumeUpdateList_r(ec, vp);
2484 Log("VAttachVolume: Error adding volume to update list\n");
2491 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2496 if (VRequiresPartLock()) {
2497 VUnlockPartition_r(partition);
2500 #ifdef AFS_DEMAND_ATTACH_FS
2501 /* attach failed; make sure we're in error state */
2502 if (vp && !VIsErrorState(V_attachState(vp))) {
2503 VChangeState_r(vp, VOL_STATE_ERROR);
2505 #endif /* AFS_DEMAND_ATTACH_FS */
2512 #ifdef AFS_DEMAND_ATTACH_FS
2513 /* VAttachVolumeByVp_r
2515 * finish attaching a volume that is
2516 * in a less than fully attached state
2518 /* caller MUST hold a ref count on vp */
2520 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
2522 char name[VMAXPATHLEN];
2524 struct DiskPartition64 *partp;
2528 Volume * nvp = NULL;
2529 VolumeStats stats_save;
2532 /* volume utility should never call AttachByVp */
2533 assert(programType == fileServer);
2535 volumeId = vp->hashid;
2536 partp = vp->partition;
2537 VolumeExternalName_r(volumeId, name, sizeof(name));
2540 /* if another thread is performing a blocking op, wait */
2541 VWaitExclusiveState_r(vp);
2543 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2545 /* if it's already attached, see if we can return it */
2546 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2547 VGetVolumeByVp_r(ec, vp);
2548 if (V_inUse(vp) == fileServer) {
2551 if (vp->specialStatus == VBUSY)
2553 VDetachVolume_r(ec, vp);
2555 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2561 /* pre-attach volume if it hasn't been done yet */
2563 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2564 (V_attachState(vp) == VOL_STATE_ERROR)) {
2565 nvp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2571 VCreateReservation_r(nvp);
2577 VChangeState_r(vp, VOL_STATE_ATTACHING);
2579 /* restore monotonically increasing stats */
2580 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2584 /* compute path to disk header */
2585 strcpy(path, VPartitionPath(partp));
2594 * NOTE: attach2 is entered without any locks, and returns
2595 * with vol_glock_mutex held */
2596 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode);
2599 * the event that an error was encountered, or
2600 * the volume was not brought to an attached state
2601 * for any reason, skip to the end. We cannot
2602 * safely call VUpdateVolume unless we "own" it.
2606 (V_attachState(vp) != VOL_STATE_ATTACHED)) {
2610 VUpdateVolume_r(ec, vp, 0);
2612 Log("VAttachVolume: Error updating volume %u\n", vp->hashid);
2616 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2617 #ifndef AFS_DEMAND_ATTACH_FS
2618 /* This is a hack: by temporarily setting the incore
2619 * dontSalvage flag ON, the volume will be put back on the
2620 * Update list (with dontSalvage OFF again). It will then
2621 * come back in N minutes with DONT_SALVAGE eventually
2622 * set. This is the way that volumes that have never had
2623 * it set get it set; or that volumes that have been
2624 * offline without DONT SALVAGE having been set also
2625 * eventually get it set */
2626 V_dontSalvage(vp) = DONT_SALVAGE;
2627 #endif /* !AFS_DEMAND_ATTACH_FS */
2628 VAddToVolumeUpdateList_r(ec, vp);
2630 Log("VAttachVolume: Error adding volume %u to update list\n", vp->hashid);
2637 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2641 VCancelReservation_r(nvp);
2644 if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2645 if (vp && !VIsErrorState(V_attachState(vp))) {
2646 VChangeState_r(vp, VOL_STATE_ERROR);
2655 * lock a volume on disk (non-blocking).
2657 * @param[in] vp The volume to lock
2658 * @param[in] locktype READ_LOCK or WRITE_LOCK
2660 * @return operation status
2661 * @retval 0 success, lock was obtained
2662 * @retval EBUSY a conflicting lock was held by another process
2663 * @retval EIO error acquiring lock
2665 * @pre If we're in the fileserver, vp is in an exclusive state
2667 * @pre vp is not already locked
2670 VLockVolumeNB(Volume *vp, int locktype)
2674 assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2675 assert(!(V_attachFlags(vp) & VOL_LOCKED));
2677 code = VLockVolumeByIdNB(vp->hashid, vp->partition, locktype);
2679 V_attachFlags(vp) |= VOL_LOCKED;
2686 * unlock a volume on disk that was locked with VLockVolumeNB.
2688 * @param[in] vp volume to unlock
2690 * @pre If we're in the fileserver, vp is in an exclusive state
2692 * @pre vp has already been locked
2695 VUnlockVolume(Volume *vp)
2697 assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2698 assert((V_attachFlags(vp) & VOL_LOCKED));
2700 VUnlockVolumeById(vp->hashid, vp->partition);
2702 V_attachFlags(vp) &= ~VOL_LOCKED;
2704 #endif /* AFS_DEMAND_ATTACH_FS */
2707 * read in a vol header, possibly lock the vol header, and possibly check out
2708 * the vol header from the fileserver, as part of volume attachment.
2710 * @param[out] ec error code
2711 * @param[in] vp volume pointer object
2712 * @param[in] partp disk partition object of the attaching partition
2713 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
2715 * @param[in] peek 1 to just try to read in the volume header and make sure
2716 * we don't try to lock the vol, or check it out from
2717 * FSSYNC or anything like that; 0 otherwise, for 'normal'
2720 * @note As part of DAFS volume attachment, the volume header may be either
2721 * read- or write-locked to ensure mutual exclusion of certain volume
2722 * operations. In some cases in order to determine whether we need to
2723 * read- or write-lock the header, we need to read in the header to see
2724 * if the volume is RW or not. So, if we read in the header under a
2725 * read-lock and determine that we actually need a write-lock on the
2726 * volume header, this function will drop the read lock, acquire a write
2727 * lock, and read the header in again.
2730 attach_volume_header(Error *ec, Volume *vp, struct DiskPartition64 *partp,
2733 struct VolumeDiskHeader diskHeader;
2734 struct VolumeHeader header;
2737 int lock_tries = 0, checkout_tries = 0;
2739 VolumeId volid = vp->hashid;
2740 #ifdef FSSYNC_BUILD_CLIENT
2741 int checkout, done_checkout = 0;
2742 #endif /* FSSYNC_BUILD_CLIENT */
2743 #ifdef AFS_DEMAND_ATTACH_FS
2744 int locktype = 0, use_locktype = -1;
2745 #endif /* AFS_DEMAND_ATTACH_FS */
2751 if (lock_tries > VOL_MAX_CHECKOUT_RETRIES) {
2752 Log("VAttachVolume: retried too many times trying to lock header for "
2753 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2754 VPartitionPath(partp));
2758 if (checkout_tries > VOL_MAX_CHECKOUT_RETRIES) {
2759 Log("VAttachVolume: retried too many times trying to checkout "
2760 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2761 VPartitionPath(partp));
2766 if (VReadVolumeDiskHeader(volid, partp, NULL)) {
2767 /* short-circuit the 'volume does not exist' case */
2772 #ifdef FSSYNC_BUILD_CLIENT
2773 checkout = !done_checkout;
2775 if (!peek && checkout && VMustCheckoutVolume(mode)) {
2777 memset(&res, 0, sizeof(res));
2779 if (FSYNC_VolOp(volid, VPartitionPath(partp), FSYNC_VOL_NEEDVOLUME, mode, &res)
2782 if (res.hdr.reason == FSYNC_SALVAGE) {
2783 Log("VAttachVolume: file server says volume %lu is salvaging\n",
2784 afs_printable_uint32_lu(volid));
2787 Log("VAttachVolume: attach of volume %lu apparently denied by file server\n",
2788 afs_printable_uint32_lu(volid));
2789 *ec = VNOVOL; /* XXXX */
2796 #ifdef AFS_DEMAND_ATTACH_FS
2797 if (use_locktype < 0) {
2798 /* don't know whether vol is RO or RW; assume it's RO and we can retry
2799 * if it turns out to be RW */
2800 locktype = VVolLockType(mode, 0);
2803 /* a previous try says we should use use_locktype to lock the volume,
2805 locktype = use_locktype;
2808 if (!peek && locktype) {
2809 code = VLockVolumeNB(vp, locktype);
2811 if (code == EBUSY) {
2812 Log("VAttachVolume: another program has vol %lu locked\n",
2813 afs_printable_uint32_lu(volid));
2815 Log("VAttachVolume: error %d trying to lock vol %lu\n",
2816 code, afs_printable_uint32_lu(volid));
2823 #endif /* AFS_DEMAND_ATTACH_FS */
2825 code = VReadVolumeDiskHeader(volid, partp, &diskHeader);
2835 DiskToVolumeHeader(&header, &diskHeader);
2837 IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header.parent,
2838 header.largeVnodeIndex);
2839 IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header.parent,
2840 header.smallVnodeIndex);
2841 IH_INIT(vp->diskDataHandle, partp->device, header.parent,
2843 IH_INIT(vp->linkHandle, partp->device, header.parent, header.linkTable);
2846 /* only need to do this once */
2848 GetVolumeHeader(vp);
2852 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2853 /* demand attach changes the V_PEEK mechanism
2855 * we can now suck the current disk data structure over
2856 * the fssync interface without going to disk
2858 * (technically, we don't need to restrict this feature
2859 * to demand attach fileservers. However, I'm trying
2860 * to limit the number of common code changes)
2862 if (VCanUseFSSYNC() && (mode == V_PEEK || peek)) {
2864 res.payload.len = sizeof(VolumeDiskData);
2865 res.payload.buf = &vp->header->diskstuff;
2867 if (FSYNC_VolOp(vp->hashid,
2869 FSYNC_VOL_QUERY_HDR,
2872 goto disk_header_loaded;
2875 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2876 (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2877 sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2879 #ifdef AFS_DEMAND_ATTACH_FS
2882 IncUInt64(&VStats.hdr_loads);
2883 IncUInt64(&vp->stats.hdr_loads);
2885 #endif /* AFS_DEMAND_ATTACH_FS */
2888 Log("VAttachVolume: Error reading diskDataHandle header for vol %lu; "
2889 "error=%u\n", afs_printable_uint32_lu(volid), *ec);
2893 #ifdef AFS_DEMAND_ATTACH_FS
2894 # ifdef FSSYNC_BUILD_CLIENT
2896 # endif /* FSSYNC_BUILD_CLIENT */
2898 /* if the lock type we actually used to lock the volume is different than
2899 * the lock type we should have used, retry with the lock type we should
2901 use_locktype = VVolLockType(mode, VolumeWriteable(vp));
2902 if (locktype != use_locktype) {
2906 #endif /* AFS_DEMAND_ATTACH_FS */
2911 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2912 if (!peek && *ec == 0 && retry == 0 && VMustCheckoutVolume(mode)) {
2914 code = FSYNC_VerifyCheckout(volid, VPartitionPath(partp), FSYNC_VOL_NEEDVOLUME, mode);
2916 if (code == SYNC_DENIED) {
2917 /* must retry checkout; fileserver no longer thinks we have
2923 } else if (code != SYNC_OK) {
2927 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2930 /* either we are going to be called again for a second pass, or we
2931 * encountered an error; clean up in either case */
2933 #ifdef AFS_DEMAND_ATTACH_FS
2934 if ((V_attachFlags(vp) & VOL_LOCKED)) {
2937 #endif /* AFS_DEMAND_ATTACH_FS */
2938 if (vp->linkHandle) {
2939 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
2940 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
2941 IH_RELEASE(vp->diskDataHandle);
2942 IH_RELEASE(vp->linkHandle);
2955 #ifdef AFS_DEMAND_ATTACH_FS
2957 attach_check_vop(Error *ec, VolumeId volid, struct DiskPartition64 *partp,
2962 if (vp->pending_vol_op) {
2966 if (vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningUnknown) {
2968 code = VVolOpLeaveOnlineNoHeader_r(vp, vp->pending_vol_op);
2970 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
2971 } else if (code == 0) {
2972 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
2975 /* we need the vol header to determine if the volume can be
2976 * left online for the vop, so... get the header */
2980 /* attach header with peek=1 to avoid checking out the volume
2981 * or locking it; we just want the header info, we're not
2982 * messing with the volume itself at all */
2983 attach_volume_header(ec, vp, partp, V_PEEK, 1);
2990 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
2991 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
2993 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
2996 /* make sure we grab a new vol header and re-open stuff on
2997 * actual attachment; we can't keep the data we grabbed, since
2998 * it was not done under a lock and thus not safe */
2999 FreeVolumeHeader(vp);
3000 VReleaseVolumeHandles_r(vp);
3003 /* see if the pending volume op requires exclusive access */
3004 switch (vp->pending_vol_op->vol_op_state) {
3005 case FSSYNC_VolOpPending:
3006 /* this should never happen */
3007 assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpPending);
3010 case FSSYNC_VolOpRunningUnknown:
3011 /* this should never happen; we resolved 'unknown' above */
3012 assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
3015 case FSSYNC_VolOpRunningOffline:
3016 /* mark the volume down */
3018 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3020 /* do not set V_offlineMessage here; we don't have ownership of
3021 * the volume (and probably do not have the header loaded), so we
3022 * can't alter the disk header */
3024 /* check to see if we should set the specialStatus flag */
3025 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
3026 vp->specialStatus = VBUSY;
3037 #endif /* AFS_DEMAND_ATTACH_FS */
3040 * volume attachment helper function.
3042 * @param[out] ec error code
3043 * @param[in] volumeId volume ID of the attaching volume
3044 * @param[in] path full path to the volume header .vol file
3045 * @param[in] partp disk partition object for the attaching partition
3046 * @param[in] vp volume object; vp->hashid, vp->device, vp->partition,
3047 * vp->vnode_list, and V_attachCV (for DAFS) should already
3049 * @param[in] isbusy 1 if vp->specialStatus should be set to VBUSY; that is,
3050 * if there is a volume operation running for this volume
3051 * that should set the volume to VBUSY during its run. 0
3052 * otherwise. (see VVolOpSetVBusy_r)
3053 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
3056 * @return pointer to the semi-attached volume pointer
3057 * @retval NULL an error occurred (check value of *ec)
3058 * @retval vp volume successfully attaching
3060 * @pre no locks held
3062 * @post VOL_LOCK held
3065 attach2(Error * ec, VolId volumeId, char *path, struct DiskPartition64 *partp,
3066 Volume * vp, int isbusy, int mode)
3068 /* have we read in the header successfully? */
3069 int read_header = 0;
3071 /* should we FreeVolume(vp) instead of VCheckFree(vp) in the error
3077 vp->vnodeIndex[vLarge].handle = NULL;
3078 vp->vnodeIndex[vSmall].handle = NULL;
3079 vp->diskDataHandle = NULL;
3080 vp->linkHandle = NULL;
3082 #ifdef AFS_DEMAND_ATTACH_FS
3083 attach_check_vop(ec, volumeId, partp, vp);
3085 attach_volume_header(ec, vp, partp, mode, 0);
3088 attach_volume_header(ec, vp, partp, mode, 0);
3089 #endif /* !AFS_DEMAND_ATTACH_FS */
3091 if (*ec == VNOVOL) {
3092 /* if the volume doesn't exist, skip straight to 'error' so we don't
3093 * request a salvage */
3100 vp->specialStatus = (byte) (isbusy ? VBUSY : 0);
3101 vp->shuttingDown = 0;
3102 vp->goingOffline = 0;
3104 #ifdef AFS_DEMAND_ATTACH_FS
3105 vp->stats.last_attach = FT_ApproxTime();
3106 vp->stats.attaches++;
3110 IncUInt64(&VStats.attaches);
3111 vp->cacheCheck = ++VolumeCacheCheck;
3112 /* just in case this ever rolls over */
3113 if (!vp->cacheCheck)
3114 vp->cacheCheck = ++VolumeCacheCheck;
3117 #ifdef AFS_DEMAND_ATTACH_FS
3118 V_attachFlags(vp) |= VOL_HDR_LOADED;
3119 vp->stats.last_hdr_load = vp->stats.last_attach;
3120 #endif /* AFS_DEMAND_ATTACH_FS */
3124 struct IndexFileHeader iHead;
3126 #if OPENAFS_VOL_STATS
3128 * We just read in the diskstuff part of the header. If the detailed
3129 * volume stats area has not yet been initialized, we should bzero the
3130 * area and mark it as initialized.
3132 if (!(V_stat_initialized(vp))) {
3133 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
3134 V_stat_initialized(vp) = 1;
3136 #endif /* OPENAFS_VOL_STATS */
3138 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
3139 (char *)&iHead, sizeof(iHead),
3140 SMALLINDEXMAGIC, SMALLINDEXVERSION);
3143 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
3148 struct IndexFileHeader iHead;
3150 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
3151 (char *)&iHead, sizeof(iHead),
3152 LARGEINDEXMAGIC, LARGEINDEXVERSION);
3155 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
3159 #ifdef AFS_NAMEI_ENV
3161 struct versionStamp stamp;
3163 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
3164 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
3167 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
3170 #endif /* AFS_NAMEI_ENV */
3172 #if defined(AFS_DEMAND_ATTACH_FS)
3173 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
3175 if (!VCanScheduleSalvage()) {
3176 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3178 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3183 /* volume operation in progress */
3187 #else /* AFS_DEMAND_ATTACH_FS */
3189 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3193 #endif /* AFS_DEMAND_ATTACH_FS */
3195 if (V_needsSalvaged(vp)) {
3196 if (vp->specialStatus)
3197 vp->specialStatus = 0;
3199 #if defined(AFS_DEMAND_ATTACH_FS)
3200 if (!VCanScheduleSalvage()) {
3201 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
3203 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
3206 #else /* AFS_DEMAND_ATTACH_FS */
3208 #endif /* AFS_DEMAND_ATTACH_FS */
3214 vp->nextVnodeUnique = V_uniquifier(vp);
3216 if (VShouldCheckInUse(mode) && V_inUse(vp) && VolumeWriteable(vp)) {
3217 if (!V_needsSalvaged(vp)) {
3218 V_needsSalvaged(vp) = 1;
3219 VUpdateVolume_r(ec, vp, 0);
3221 #if defined(AFS_DEMAND_ATTACH_FS)
3222 if (!VCanScheduleSalvage()) {
3223 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3225 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
3228 #else /* AFS_DEMAND_ATTACH_FS */
3229 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3231 #endif /* AFS_DEMAND_ATTACH_FS */
3236 if (programType == fileServer && V_destroyMe(vp) == DESTROY_ME) {
3237 /* Only check destroyMe if we are the fileserver, since the
3238 * volserver et al sometimes need to work with volumes with
3239 * destroyMe set. Examples are 'temporary' volumes the
3240 * volserver creates, and when we create a volume (destroyMe
3241 * is set on creation; sometimes a separate volserver
3242 * transaction is created to clear destroyMe).
3245 #if defined(AFS_DEMAND_ATTACH_FS)
3246 /* schedule a salvage so the volume goes away on disk */
3247 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3248 VChangeState_r(vp, VOL_STATE_ERROR);
3250 #endif /* AFS_DEMAND_ATTACH_FS */
3251 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
3257 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
3258 #ifndef BITMAP_LATER
3259 if (programType == fileServer && VolumeWriteable(vp)) {
3261 for (i = 0; i < nVNODECLASSES; i++) {
3262 VGetBitmap_r(ec, vp, i);
3264 #ifdef AFS_DEMAND_ATTACH_FS
3265 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3267 #endif /* AFS_DEMAND_ATTACH_FS */
3268 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
3274 #endif /* BITMAP_LATER */
3276 if (VInit >= 2 && V_needsCallback(vp)) {
3277 if (V_BreakVolumeCallbacks) {
3278 Log("VAttachVolume: Volume %lu was changed externally; breaking callbacks\n",
3279 afs_printable_uint32_lu(V_id(vp)));
3280 V_needsCallback(vp) = 0;
3282 (*V_BreakVolumeCallbacks) (V_id(vp));
3285 VUpdateVolume_r(ec, vp, 0);
3287 #ifdef FSSYNC_BUILD_CLIENT
3288 else if (VCanUseFSSYNC()) {
3289 afs_int32 fsync_code;
3291 V_needsCallback(vp) = 0;
3293 fsync_code = FSYNC_VolOp(V_id(vp), NULL, FSYNC_VOL_BREAKCBKS, FSYNC_WHATEVER, NULL);
3297 V_needsCallback(vp) = 1;
3298 Log("Error trying to tell the fileserver to break callbacks for "
3299 "changed volume %lu; error code %ld\n",
3300 afs_printable_uint32_lu(V_id(vp)),
3301 afs_printable_int32_ld(fsync_code));
3303 VUpdateVolume_r(ec, vp, 0);
3306 #endif /* FSSYNC_BUILD_CLIENT */
3309 Log("VAttachVolume: error %d clearing needsCallback on volume "
3310 "%lu; needs salvage\n", (int)*ec,
3311 afs_printable_uint32_lu(V_id(vp)));
3312 #ifdef AFS_DEMAND_ATTACH_FS
3313 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3315 #else /* !AFS_DEMAND_ATTACH_FS */
3317 #endif /* !AFS_DEMAND_ATTACh_FS */
3322 if (programType == fileServer) {
3323 if (vp->specialStatus)
3324 vp->specialStatus = 0;
3325 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
3326 V_inUse(vp) = fileServer;
3327 V_offlineMessage(vp)[0] = '\0';
3331 /* mimic e.g. GetVolume errors */
3333 Log("Volume %lu offline: not blessed\n", afs_printable_uint32_lu(V_id(vp)));
3334 else if (!V_inService(vp))
3335 Log("Volume %lu offline: not in service\n", afs_printable_uint32_lu(V_id(vp)));
3337 Log("Volume %lu offline: needs salvage\n", afs_printable_uint32_lu(V_id(vp)));
3339 #ifdef AFS_DEMAND_ATTACH_FS
3340 /* see if we can recover */
3341 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
3351 #ifdef AFS_DEMAND_ATTACH_FS
3352 if ((mode != V_PEEK) && (mode != V_SECRETLY))
3353 V_inUse(vp) = programType;
3354 #endif /* AFS_DEMAND_ATTACH_FS */
3355 V_checkoutMode(vp) = mode;
3358 AddVolumeToHashTable(vp, V_id(vp));
3359 #ifdef AFS_DEMAND_ATTACH_FS
3360 if (VCanUnlockAttached() && (V_attachFlags(vp) & VOL_LOCKED)) {
3363 if ((programType != fileServer) ||
3364 (V_inUse(vp) == fileServer)) {
3365 AddVolumeToVByPList_r(vp);
3367 VChangeState_r(vp, VOL_STATE_ATTACHED);
3369 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3376 #ifdef AFS_DEMAND_ATTACH_FS
3377 if (!VIsErrorState(V_attachState(vp))) {
3378 VChangeState_r(vp, VOL_STATE_ERROR);
3380 #endif /* AFS_DEMAND_ATTACH_FS */
3383 VReleaseVolumeHandles_r(vp);
3386 #ifdef AFS_DEMAND_ATTACH_FS
3393 #else /* !AFS_DEMAND_ATTACH_FS */
3395 #endif /* !AFS_DEMAND_ATTACH_FS */
3399 /* Attach an existing volume.
3400 The volume also normally goes online at this time.
3401 An offline volume must be reattached to make it go online.
3405 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
3409 retVal = VAttachVolume_r(ec, volumeId, mode);
3415 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
3418 VGetVolumePath(ec, volumeId, &part, &name);
3420 register Volume *vp;
3422 vp = VGetVolume_r(&error, volumeId);
3424 assert(V_inUse(vp) == 0);
3425 VDetachVolume_r(ec, vp);
3429 return VAttachVolumeByName_r(ec, part, name, mode);
3432 /* Increment a reference count to a volume, sans context swaps. Requires
3433 * possibly reading the volume header in from the disk, since there's
3434 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
3436 * N.B. This call can fail if we can't read in the header!! In this case
3437 * we still guarantee we won't context swap, but the ref count won't be
3438 * incremented (otherwise we'd violate the invariant).
3440 /* NOTE: with the demand attach fileserver extensions, the global lock
3441 * is dropped within VHold */
3442 #ifdef AFS_DEMAND_ATTACH_FS
3444 VHold_r(register Volume * vp)
3448 VCreateReservation_r(vp);
3449 VWaitExclusiveState_r(vp);
3451 LoadVolumeHeader(&error, vp);
3453 VCancelReservation_r(vp);
3457 VCancelReservation_r(vp);
3460 #else /* AFS_DEMAND_ATTACH_FS */
3462 VHold_r(register Volume * vp)
3466 LoadVolumeHeader(&error, vp);
3472 #endif /* AFS_DEMAND_ATTACH_FS */
3476 VHold(register Volume * vp)
3480 retVal = VHold_r(vp);
3487 /***************************************************/
3488 /* get and put volume routines */
3489 /***************************************************/
3492 * put back a heavyweight reference to a volume object.
3494 * @param[in] vp volume object pointer
3496 * @pre VOL_LOCK held
3498 * @post heavyweight volume reference put back.
3499 * depending on state, volume may have been taken offline,
3500 * detached, salvaged, freed, etc.
3502 * @internal volume package internal use only
3505 VPutVolume_r(register Volume * vp)
3507 assert(--vp->nUsers >= 0);
3508 if (vp->nUsers == 0) {
3510 ReleaseVolumeHeader(vp->header);
3511 #ifdef AFS_DEMAND_ATTACH_FS
3512 if (!VCheckDetach(vp)) {
3516 #else /* AFS_DEMAND_ATTACH_FS */
3518 #endif /* AFS_DEMAND_ATTACH_FS */
3523 VPutVolume(register Volume * vp)
3531 /* Get a pointer to an attached volume. The pointer is returned regardless
3532 of whether or not the volume is in service or on/off line. An error
3533 code, however, is returned with an indication of the volume's status */
3535 VGetVolume(Error * ec, Error * client_ec, VolId volumeId)
3539 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
3544 /* same as VGetVolume, but if a volume is waiting to go offline, we return
3545 * that it is actually offline, instead of waiting for it to go offline */
3547 VGetVolumeNoWait(Error * ec, Error * client_ec, VolId volumeId)
3551 retVal = GetVolume(ec, client_ec, volumeId, NULL, 1);
3557 VGetVolume_r(Error * ec, VolId volumeId)
3559 return GetVolume(ec, NULL, volumeId, NULL, 0);
3562 /* try to get a volume we've previously looked up */
3563 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
3565 VGetVolumeByVp_r(Error * ec, Volume * vp)
3567 return GetVolume(ec, NULL, vp->hashid, vp, 0);
3571 * private interface for getting a volume handle
3573 * @param[out] ec error code (0 if no error)
3574 * @param[out] client_ec wire error code to be given to clients
3575 * @param[in] volumeId ID of the volume we want
3576 * @param[in] hint optional hint for hash lookups, or NULL
3577 * @param[in] nowait 0 to wait for a 'goingOffline' volume to go offline
3578 * before returning, 1 to return immediately
3580 * @return a volume handle for the specified volume
3581 * @retval NULL an error occurred, or the volume is in such a state that
3582 * we cannot load a header or return any volume struct
3584 * @note for DAFS, caller must NOT hold a ref count on 'hint'
3587 GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint, int nowait)
3590 /* pull this profiling/debugging code out of regular builds */
3592 #define VGET_CTR_INC(x) x++
3593 unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
3594 0, V7 = 0, V8 = 0, V9 = 0;
3595 unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
3597 #define VGET_CTR_INC(x)
3599 #ifdef AFS_DEMAND_ATTACH_FS
3600 Volume *avp, * rvp = hint;
3604 * if VInit is zero, the volume package dynamic
3605 * data structures have not been initialized yet,
3606 * and we must immediately return an error
3612 *client_ec = VOFFLINE;
3617 #ifdef AFS_DEMAND_ATTACH_FS
3619 VCreateReservation_r(rvp);
3621 #endif /* AFS_DEMAND_ATTACH_FS */
3629 vp = VLookupVolume_r(ec, volumeId, vp);
3635 #ifdef AFS_DEMAND_ATTACH_FS
3636 if (rvp && (rvp != vp)) {
3637 /* break reservation on old vp */
3638 VCancelReservation_r(rvp);
3641 #endif /* AFS_DEMAND_ATTACH_FS */
3647 /* Until we have reached an initialization level of 2
3648 * we don't know whether this volume exists or not.
3649 * We can't sleep and retry later because before a volume
3650 * is attached, the caller tries to get it first. Just
3651 * return VOFFLINE and the caller can choose whether to
3652 * retry the command or not. */
3662 IncUInt64(&VStats.hdr_gets);
3664 #ifdef AFS_DEMAND_ATTACH_FS
3665 /* block if someone else is performing an exclusive op on this volume */
3668 VCreateReservation_r(rvp);
3670 VWaitExclusiveState_r(vp);
3672 /* short circuit with VNOVOL in the following circumstances:
3675 * - VOL_STATE_SHUTTING_DOWN
3677 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
3678 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN) ||
3679 (V_attachState(vp) == VOL_STATE_GOING_OFFLINE)) {
3686 * short circuit with VOFFLINE in the following circumstances:
3688 * - VOL_STATE_UNATTACHED
3690 if (V_attachState(vp) == VOL_STATE_UNATTACHED) {
3691 if (vp->specialStatus) {
3692 *ec = vp->specialStatus;
3700 /* allowable states:
3706 if (vp->salvage.requested) {
3707 VUpdateSalvagePriority_r(vp);
3710 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
3711 avp = VAttachVolumeByVp_r(ec, vp, 0);
3714 /* VAttachVolumeByVp_r can return a pointer
3715 * != the vp passed to it under certain
3716 * conditions; make sure we don't leak
3717 * reservations if that happens */
3719 VCancelReservation_r(rvp);
3721 VCreateReservation_r(rvp);
3731 if (!vp->pending_vol_op) {
3746 if ((V_attachState(vp) == VOL_STATE_SALVAGING) ||
3747 (*ec == VSALVAGING)) {
3749 /* see CheckVnode() in afsfileprocs.c for an explanation
3750 * of this error code logic */
3751 afs_uint32 now = FT_ApproxTime();
3752 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
3755 *client_ec = VRESTARTING;
3764 #ifdef AFS_DEMAND_ATTACH_FS
3766 * this test MUST happen after VAttachVolymeByVp, so vol_op_state is
3767 * not VolOpRunningUnknown (attach2 would have converted it to Online
3771 /* only valid before/during demand attachment */
3772 assert(!vp->pending_vol_op || vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
3774 /* deny getvolume due to running mutually exclusive vol op */
3775 if (vp->pending_vol_op && vp->pending_vol_op->vol_op_state==FSSYNC_VolOpRunningOffline) {
3777 * volume cannot remain online during this volume operation.
3780 if (vp->specialStatus) {
3782 * special status codes outrank normal VOFFLINE code
3784 *ec = vp->specialStatus;
3786 *client_ec = vp->specialStatus;
3790 /* see CheckVnode() in afsfileprocs.c for an explanation
3791 * of this error code logic */
3792 afs_uint32 now = FT_ApproxTime();
3793 if ((vp->stats.last_vol_op + (10 * 60)) >= now) {
3796 *client_ec = VRESTARTING;
3801 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3802 FreeVolumeHeader(vp);
3806 #endif /* AFS_DEMAND_ATTACH_FS */
3808 LoadVolumeHeader(ec, vp);
3811 /* Only log the error if it was a totally unexpected error. Simply
3812 * a missing inode is likely to be caused by the volume being deleted */
3813 if (errno != ENXIO || LogLevel)
3814 Log("Volume %u: couldn't reread volume header\n",
3816 #ifdef AFS_DEMAND_ATTACH_FS
3817 if (VCanScheduleSalvage()) {
3818 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3823 #else /* AFS_DEMAND_ATTACH_FS */
3826 #endif /* AFS_DEMAND_ATTACH_FS */
3831 if (vp->shuttingDown) {
3838 if (programType == fileServer) {
3840 if (vp->goingOffline && !nowait) {
3842 #ifdef AFS_DEMAND_ATTACH_FS
3843 /* wait for the volume to go offline */
3844 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
3845 VWaitStateChange_r(vp);
3847 #elif defined(AFS_PTHREAD_ENV)
3848 VOL_CV_WAIT(&vol_put_volume_cond);
3849 #else /* AFS_PTHREAD_ENV */
3850 LWP_WaitProcess(VPutVolume);
3851 #endif /* AFS_PTHREAD_ENV */
3854 if (vp->specialStatus) {
3856 *ec = vp->specialStatus;
3857 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3860 } else if (V_inUse(vp) == 0 || vp->goingOffline) {
3871 #ifdef AFS_DEMAND_ATTACH_FS
3872 /* if no error, bump nUsers */
3875 VLRU_UpdateAccess_r(vp);
3878 VCancelReservation_r(rvp);
3881 if (client_ec && !*client_ec) {
3884 #else /* AFS_DEMAND_ATTACH_FS */
3885 /* if no error, bump nUsers */
3892 #endif /* AFS_DEMAND_ATTACH_FS */
3900 /***************************************************/
3901 /* Volume offline/detach routines */
3902 /***************************************************/
3904 /* caller MUST hold a heavyweight ref on vp */
3905 #ifdef AFS_DEMAND_ATTACH_FS
3907 VTakeOffline_r(register Volume * vp)
3911 assert(vp->nUsers > 0);
3912 assert(programType == fileServer);
3914 VCreateReservation_r(vp);
3915 VWaitExclusiveState_r(vp);
3917 vp->goingOffline = 1;
3918 V_needsSalvaged(vp) = 1;
3920 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
3921 VCancelReservation_r(vp);
3923 #else /* AFS_DEMAND_ATTACH_FS */
3925 VTakeOffline_r(register Volume * vp)
3927 assert(vp->nUsers > 0);
3928 assert(programType == fileServer);
3930 vp->goingOffline = 1;
3931 V_needsSalvaged(vp) = 1;
3933 #endif /* AFS_DEMAND_ATTACH_FS */
3936 VTakeOffline(register Volume * vp)
3944 * force a volume offline.
3946 * @param[in] vp volume object pointer
3947 * @param[in] flags flags (see note below)
3949 * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
3950 * used when VUpdateVolume_r needs to call VForceOffline_r
3951 * (which in turn would normally call VUpdateVolume_r)
3953 * @see VUpdateVolume_r
3955 * @pre VOL_LOCK must be held.
3956 * for DAFS, caller must hold ref.
3958 * @note for DAFS, it _is safe_ to call this function from an
3961 * @post needsSalvaged flag is set.
3962 * for DAFS, salvage is requested.
3963 * no further references to the volume through the volume
3964 * package will be honored.
3965 * all file descriptor and vnode caches are invalidated.
3967 * @warning this is a heavy-handed interface. it results in
3968 * a volume going offline regardless of the current
3969 * reference count state.
3971 * @internal volume package internal use only
3974 VForceOffline_r(Volume * vp, int flags)
3978 #ifdef AFS_DEMAND_ATTACH_FS
3979 VChangeState_r(vp, VOL_STATE_ERROR);
3984 strcpy(V_offlineMessage(vp),
3985 "Forced offline due to internal error: volume needs to be salvaged");
3986 Log("Volume %u forced offline: it needs salvaging!\n", V_id(vp));
3989 vp->goingOffline = 0;
3990 V_needsSalvaged(vp) = 1;
3991 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
3992 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
3995 #ifdef AFS_DEMAND_ATTACH_FS
3996 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3997 #endif /* AFS_DEMAND_ATTACH_FS */
3999 #ifdef AFS_PTHREAD_ENV
4000 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
4001 #else /* AFS_PTHREAD_ENV */
4002 LWP_NoYieldSignal(VPutVolume);
4003 #endif /* AFS_PTHREAD_ENV */
4005 VReleaseVolumeHandles_r(vp);
4009 * force a volume offline.
4011 * @param[in] vp volume object pointer
4013 * @see VForceOffline_r
4016 VForceOffline(Volume * vp)
4019 VForceOffline_r(vp, 0);
4023 /* The opposite of VAttachVolume. The volume header is written to disk, with
4024 the inUse bit turned off. A copy of the header is maintained in memory,
4025 however (which is why this is VOffline, not VDetach).
4028 VOffline_r(Volume * vp, char *message)
4030 #ifndef AFS_DEMAND_ATTACH_FS
4032 VolumeId vid = V_id(vp);
4035 assert(programType != volumeUtility && programType != volumeServer);
4040 if (V_offlineMessage(vp)[0] == '\0')
4041 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4042 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4044 vp->goingOffline = 1;
4045 #ifdef AFS_DEMAND_ATTACH_FS
4046 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4047 VCreateReservation_r(vp);
4050 /* wait for the volume to go offline */
4051 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
4052 VWaitStateChange_r(vp);
4054 VCancelReservation_r(vp);
4055 #else /* AFS_DEMAND_ATTACH_FS */
4057 vp = VGetVolume_r(&error, vid); /* Wait for it to go offline */
4058 if (vp) /* In case it was reattached... */
4060 #endif /* AFS_DEMAND_ATTACH_FS */
4063 #ifdef AFS_DEMAND_ATTACH_FS
4065 * Take a volume offline in order to perform a volume operation.
4067 * @param[inout] ec address in which to store error code
4068 * @param[in] vp volume object pointer
4069 * @param[in] message volume offline status message
4072 * - VOL_LOCK is held
4073 * - caller MUST hold a heavyweight ref on vp
4076 * - volume is taken offline
4077 * - if possible, volume operation is promoted to running state
4078 * - on failure, *ec is set to nonzero
4080 * @note Although this function does not return any value, it may
4081 * still fail to promote our pending volume operation to
4082 * a running state. Any caller MUST check the value of *ec,
4083 * and MUST NOT blindly assume success.
4085 * @warning if the caller does not hold a lightweight ref on vp,
4086 * then it MUST NOT reference vp after this function
4087 * returns to the caller.
4089 * @internal volume package internal use only
4092 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
4094 assert(vp->pending_vol_op);
4100 if (V_offlineMessage(vp)[0] == '\0')
4101 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4102 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4104 vp->goingOffline = 1;
4105 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4106 VCreateReservation_r(vp);
4109 /* Wait for the volume to go offline */
4110 while (!VIsOfflineState(V_attachState(vp))) {
4111 /* do not give corrupted volumes to the volserver */
4112 if (vp->salvage.requested && vp->pending_vol_op->com.programType != salvageServer) {
4116 VWaitStateChange_r(vp);
4120 VCancelReservation_r(vp);
4122 #endif /* AFS_DEMAND_ATTACH_FS */
4125 VOffline(Volume * vp, char *message)
4128 VOffline_r(vp, message);
4132 /* This gets used for the most part by utility routines that don't want
4133 * to keep all the volume headers around. Generally, the file server won't
4134 * call this routine, because then the offline message in the volume header
4135 * (or other information) won't be available to clients. For NAMEI, also
4136 * close the file handles. However, the fileserver does call this during
4137 * an attach following a volume operation.
4140 VDetachVolume_r(Error * ec, Volume * vp)
4143 struct DiskPartition64 *tpartp;
4144 int notifyServer = 0;
4145 int useDone = FSYNC_VOL_ON;
4147 *ec = 0; /* always "succeeds" */
4148 if (VCanUseFSSYNC()) {
4149 notifyServer = vp->needsPutBack;
4150 if (V_destroyMe(vp) == DESTROY_ME)
4151 useDone = FSYNC_VOL_DONE;
4152 #ifdef AFS_DEMAND_ATTACH_FS
4153 else if (!V_blessed(vp) || !V_inService(vp))
4154 useDone = FSYNC_VOL_LEAVE_OFF;
4157 tpartp = vp->partition;
4159 DeleteVolumeFromHashTable(vp);
4160 vp->shuttingDown = 1;
4161 #ifdef AFS_DEMAND_ATTACH_FS
4162 DeleteVolumeFromVByPList_r(vp);
4164 VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
4166 if (programType != fileServer)
4168 #endif /* AFS_DEMAND_ATTACH_FS */
4170 /* Will be detached sometime in the future--this is OK since volume is offline */
4172 /* XXX the following code should really be moved to VCheckDetach() since the volume
4173 * is not technically detached until the refcounts reach zero
4175 #ifdef FSSYNC_BUILD_CLIENT
4176 if (VCanUseFSSYNC() && notifyServer) {
4178 * Note: The server is not notified in the case of a bogus volume
4179 * explicitly to make it possible to create a volume, do a partial
4180 * restore, then abort the operation without ever putting the volume
4181 * online. This is essential in the case of a volume move operation
4182 * between two partitions on the same server. In that case, there
4183 * would be two instances of the same volume, one of them bogus,
4184 * which the file server would attempt to put on line
4186 FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
4187 /* XXX this code path is only hit by volume utilities, thus
4188 * V_BreakVolumeCallbacks will always be NULL. if we really
4189 * want to break callbacks in this path we need to use FSYNC_VolOp() */
4191 /* Dettaching it so break all callbacks on it */
4192 if (V_BreakVolumeCallbacks) {
4193 Log("volume %u detached; breaking all call backs\n", volume);
4194 (*V_BreakVolumeCallbacks) (volume);
4198 #endif /* FSSYNC_BUILD_CLIENT */
4202 VDetachVolume(Error * ec, Volume * vp)
4205 VDetachVolume_r(ec, vp);
4210 /***************************************************/
4211 /* Volume fd/inode handle closing routines */
4212 /***************************************************/
4214 /* For VDetachVolume, we close all cached file descriptors, but keep
4215 * the Inode handles in case we need to read from a busy volume.
4217 /* for demand attach, caller MUST hold ref count on vp */
4219 VCloseVolumeHandles_r(Volume * vp)
4221 #ifdef AFS_DEMAND_ATTACH_FS
4222 VolState state_save;
4224 state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
4229 * XXX need to investigate whether we can perform
4230 * DFlushVolume outside of vol_glock_mutex...
4232 * VCloseVnodeFiles_r drops the glock internally */
4233 DFlushVolume(vp->hashid);
4234 VCloseVnodeFiles_r(vp);
4236 #ifdef AFS_DEMAND_ATTACH_FS
4240 /* Too time consuming and unnecessary for the volserver */
4241 if (programType == fileServer) {
4242 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4243 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4244 IH_CONDSYNC(vp->diskDataHandle);
4246 IH_CONDSYNC(vp->linkHandle);
4247 #endif /* AFS_NT40_ENV */
4250 IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
4251 IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
4252 IH_REALLYCLOSE(vp->diskDataHandle);
4253 IH_REALLYCLOSE(vp->linkHandle);
4255 #ifdef AFS_DEMAND_ATTACH_FS
4256 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4261 VChangeState_r(vp, state_save);
4265 /* For both VForceOffline and VOffline, we close all relevant handles.
4266 * For VOffline, if we re-attach the volume, the files may possible be
4267 * different than before.
4269 /* for demand attach, caller MUST hold a ref count on vp */
4271 VReleaseVolumeHandles_r(Volume * vp)
4273 #ifdef AFS_DEMAND_ATTACH_FS
4274 VolState state_save;
4276 state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
4279 /* XXX need to investigate whether we can perform
4280 * DFlushVolume outside of vol_glock_mutex... */
4281 DFlushVolume(vp->hashid);
4283 VReleaseVnodeFiles_r(vp); /* releases the glock internally */
4285 #ifdef AFS_DEMAND_ATTACH_FS
4289 /* Too time consuming and unnecessary for the volserver */
4290 if (programType == fileServer) {
4291 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4292 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4293 IH_CONDSYNC(vp->diskDataHandle);
4295 IH_CONDSYNC(vp->linkHandle);
4296 #endif /* AFS_NT40_ENV */
4299 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
4300 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
4301 IH_RELEASE(vp->diskDataHandle);
4302 IH_RELEASE(vp->linkHandle);
4304 #ifdef AFS_DEMAND_ATTACH_FS
4305 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4310 VChangeState_r(vp, state_save);
4315 /***************************************************/
4316 /* Volume write and fsync routines */
4317 /***************************************************/
4320 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
4322 #ifdef AFS_DEMAND_ATTACH_FS
4323 VolState state_save;
4325 if (flags & VOL_UPDATE_WAIT) {
4326 VCreateReservation_r(vp);
4327 VWaitExclusiveState_r(vp);
4332 if (programType == fileServer)
4334 (V_inUse(vp) ? V_nextVnodeUnique(vp) +
4335 200 : V_nextVnodeUnique(vp));
4337 #ifdef AFS_DEMAND_ATTACH_FS
4338 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4342 WriteVolumeHeader_r(ec, vp);
4344 #ifdef AFS_DEMAND_ATTACH_FS
4346 VChangeState_r(vp, state_save);
4347 if (flags & VOL_UPDATE_WAIT) {
4348 VCancelReservation_r(vp);
4353 Log("VUpdateVolume: error updating volume header, volume %u (%s)\n",
4354 V_id(vp), V_name(vp));
4355 /* try to update on-disk header,
4356 * while preventing infinite recursion */
4357 if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
4358 VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
4364 VUpdateVolume(Error * ec, Volume * vp)
4367 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4372 VSyncVolume_r(Error * ec, Volume * vp, int flags)
4376 #ifdef AFS_DEMAND_ATTACH_FS
4377 VolState state_save;
4380 if (flags & VOL_SYNC_WAIT) {
4381 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4383 VUpdateVolume_r(ec, vp, 0);
4386 #ifdef AFS_DEMAND_ATTACH_FS
4387 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4390 fdP = IH_OPEN(V_diskDataHandle(vp));
4391 assert(fdP != NULL);
4392 code = FDH_SYNC(fdP);
4395 #ifdef AFS_DEMAND_ATTACH_FS
4397 VChangeState_r(vp, state_save);
4403 VSyncVolume(Error * ec, Volume * vp)
4406 VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
4411 /***************************************************/
4412 /* Volume dealloaction routines */
4413 /***************************************************/
4415 #ifdef AFS_DEMAND_ATTACH_FS
4417 FreeVolume(Volume * vp)
4419 /* free the heap space, iff it's safe.
4420 * otherwise, pull it out of the hash table, so it
4421 * will get deallocated when all refs to it go away */
4422 if (!VCheckFree(vp)) {
4423 DeleteVolumeFromHashTable(vp);
4424 DeleteVolumeFromVByPList_r(vp);
4426 /* make sure we invalidate the header cache entry */
4427 FreeVolumeHeader(vp);
4430 #endif /* AFS_DEMAND_ATTACH_FS */
4433 ReallyFreeVolume(Volume * vp)
4438 #ifdef AFS_DEMAND_ATTACH_FS
4440 VChangeState_r(vp, VOL_STATE_FREED);
4441 if (vp->pending_vol_op)
4442 free(vp->pending_vol_op);
4443 #endif /* AFS_DEMAND_ATTACH_FS */
4444 for (i = 0; i < nVNODECLASSES; i++)
4445 if (vp->vnodeIndex[i].bitmap)
4446 free(vp->vnodeIndex[i].bitmap);
4447 FreeVolumeHeader(vp);
4448 #ifndef AFS_DEMAND_ATTACH_FS
4449 DeleteVolumeFromHashTable(vp);
4450 #endif /* AFS_DEMAND_ATTACH_FS */
4454 /* check to see if we should shutdown this volume
4455 * returns 1 if volume was freed, 0 otherwise */
4456 #ifdef AFS_DEMAND_ATTACH_FS
4458 VCheckDetach(register Volume * vp)
4463 if (vp->nUsers || vp->nWaiters)
4466 if (vp->shuttingDown) {
4468 if ((programType != fileServer) &&
4469 (V_inUse(vp) == programType) &&
4470 ((V_checkoutMode(vp) == V_VOLUPD) ||
4471 (V_checkoutMode(vp) == V_SECRETLY) ||
4472 ((V_checkoutMode(vp) == V_CLONE) &&
4473 (VolumeWriteable(vp))))) {
4475 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
4477 Log("VCheckDetach: volume header update for volume %u "
4478 "failed with errno %d\n", vp->hashid, errno);
4481 VReleaseVolumeHandles_r(vp);
4483 ReallyFreeVolume(vp);
4484 if (programType == fileServer) {
4485 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
4490 #else /* AFS_DEMAND_ATTACH_FS */
4492 VCheckDetach(register Volume * vp)
4500 if (vp->shuttingDown) {
4502 if ((programType != fileServer) &&
4503 (V_inUse(vp) == programType) &&
4504 ((V_checkoutMode(vp) == V_VOLUPD) ||
4505 (V_checkoutMode(vp) == V_SECRETLY) ||
4506 ((V_checkoutMode(vp) == V_CLONE) &&
4507 (VolumeWriteable(vp))))) {
4509 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
4511 Log("VCheckDetach: volume header update for volume %u failed with errno %d\n",
4515 VReleaseVolumeHandles_r(vp);
4516 ReallyFreeVolume(vp);
4517 if (programType == fileServer) {
4518 #if defined(AFS_PTHREAD_ENV)
4519 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
4520 #else /* AFS_PTHREAD_ENV */
4521 LWP_NoYieldSignal(VPutVolume);
4522 #endif /* AFS_PTHREAD_ENV */
4527 #endif /* AFS_DEMAND_ATTACH_FS */
4529 /* check to see if we should offline this volume
4530 * return 1 if volume went offline, 0 otherwise */
4531 #ifdef AFS_DEMAND_ATTACH_FS
4533 VCheckOffline(register Volume * vp)
4537 if (vp->goingOffline && !vp->nUsers) {
4539 assert(programType == fileServer);
4540 assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
4541 (V_attachState(vp) != VOL_STATE_FREED) &&
4542 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
4543 (V_attachState(vp) != VOL_STATE_UNATTACHED));
4547 * VOL_STATE_GOING_OFFLINE
4548 * VOL_STATE_SHUTTING_DOWN
4549 * VIsErrorState(V_attachState(vp))
4550 * VIsExclusiveState(V_attachState(vp))
4553 VCreateReservation_r(vp);
4554 VChangeState_r(vp, VOL_STATE_OFFLINING);
4557 /* must clear the goingOffline flag before we drop the glock */
4558 vp->goingOffline = 0;
4563 /* perform async operations */
4564 VUpdateVolume_r(&error, vp, 0);
4565 VCloseVolumeHandles_r(vp);
4568 if (V_offlineMessage(vp)[0]) {
4569 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
4570 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
4571 V_offlineMessage(vp));
4573 Log("VOffline: Volume %lu (%s) is now offline\n",
4574 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
4578 /* invalidate the volume header cache entry */
4579 FreeVolumeHeader(vp);
4581 /* if nothing changed state to error or salvaging,
4582 * drop state to unattached */
4583 if (!VIsErrorState(V_attachState(vp))) {
4584 VChangeState_r(vp, VOL_STATE_UNATTACHED);
4586 VCancelReservation_r(vp);
4587 /* no usage of vp is safe beyond this point */
4591 #else /* AFS_DEMAND_ATTACH_FS */
4593 VCheckOffline(register Volume * vp)
4597 if (vp->goingOffline && !vp->nUsers) {
4599 assert(programType == fileServer);
4602 vp->goingOffline = 0;
4604 VUpdateVolume_r(&error, vp, 0);
4605 VCloseVolumeHandles_r(vp);
4607 Log("VOffline: Volume %u (%s) is now offline", V_id(vp),
4609 if (V_offlineMessage(vp)[0])
4610 Log(" (%s)", V_offlineMessage(vp));
4613 FreeVolumeHeader(vp);
4614 #ifdef AFS_PTHREAD_ENV
4615 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
4616 #else /* AFS_PTHREAD_ENV */
4617 LWP_NoYieldSignal(VPutVolume);
4618 #endif /* AFS_PTHREAD_ENV */
4622 #endif /* AFS_DEMAND_ATTACH_FS */
4624 /***************************************************/
4625 /* demand attach fs ref counting routines */
4626 /***************************************************/
4628 #ifdef AFS_DEMAND_ATTACH_FS
4629 /* the following two functions handle reference counting for
4630 * asynchronous operations on volume structs.
4632 * their purpose is to prevent a VDetachVolume or VShutdown
4633 * from free()ing the Volume struct during an async i/o op */
4635 /* register with the async volume op ref counter */
4636 /* VCreateReservation_r moved into inline code header because it
4637 * is now needed in vnode.c -- tkeiser 11/20/2007
4641 * decrement volume-package internal refcount.
4643 * @param vp volume object pointer
4645 * @internal volume package internal use only
4648 * @arg VOL_LOCK is held
4649 * @arg lightweight refcount held
4651 * @post volume waiters refcount is decremented; volume may
4652 * have been deallocated/shutdown/offlined/salvaged/
4653 * whatever during the process
4655 * @warning once you have tossed your last reference (you can acquire
4656 * lightweight refs recursively) it is NOT SAFE to reference
4657 * a volume object pointer ever again
4659 * @see VCreateReservation_r
4661 * @note DEMAND_ATTACH_FS only
4664 VCancelReservation_r(Volume * vp)
4666 assert(--vp->nWaiters >= 0);
4667 if (vp->nWaiters == 0) {
4669 if (!VCheckDetach(vp)) {
4676 /* check to see if we should free this volume now
4677 * return 1 if volume was freed, 0 otherwise */
4679 VCheckFree(Volume * vp)
4682 if ((vp->nUsers == 0) &&
4683 (vp->nWaiters == 0) &&
4684 !(V_attachFlags(vp) & (VOL_IN_HASH |
4688 ReallyFreeVolume(vp);
4693 #endif /* AFS_DEMAND_ATTACH_FS */
4696 /***************************************************/
4697 /* online volume operations routines */
4698 /***************************************************/
4700 #ifdef AFS_DEMAND_ATTACH_FS
4702 * register a volume operation on a given volume.
4704 * @param[in] vp volume object
4705 * @param[in] vopinfo volume operation info object
4707 * @pre VOL_LOCK is held
4709 * @post volume operation info object attached to volume object.
4710 * volume operation statistics updated.
4712 * @note by "attached" we mean a copy of the passed in object is made
4714 * @internal volume package internal use only
4717 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4719 FSSYNC_VolOp_info * info;
4721 /* attach a vol op info node to the volume struct */
4722 info = (FSSYNC_VolOp_info *) malloc(sizeof(FSSYNC_VolOp_info));
4723 assert(info != NULL);
4724 memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
4725 vp->pending_vol_op = info;
4728 vp->stats.last_vol_op = FT_ApproxTime();
4729 vp->stats.vol_ops++;
4730 IncUInt64(&VStats.vol_ops);
4736 * deregister the volume operation attached to this volume.
4738 * @param[in] vp volume object pointer
4740 * @pre VOL_LOCK is held
4742 * @post the volume operation info object is detached from the volume object
4744 * @internal volume package internal use only
4747 VDeregisterVolOp_r(Volume * vp)
4749 if (vp->pending_vol_op) {
4750 free(vp->pending_vol_op);
4751 vp->pending_vol_op = NULL;
4755 #endif /* AFS_DEMAND_ATTACH_FS */
4758 * determine whether it is safe to leave a volume online during
4759 * the volume operation described by the vopinfo object.
4761 * @param[in] vp volume object
4762 * @param[in] vopinfo volume operation info object
4764 * @return whether it is safe to leave volume online
4765 * @retval 0 it is NOT SAFE to leave the volume online
4766 * @retval 1 it is safe to leave the volume online during the operation
4769 * @arg VOL_LOCK is held
4770 * @arg disk header attached to vp (heavyweight ref on vp will guarantee
4771 * this condition is met)
4773 * @internal volume package internal use only
4776 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4778 return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
4779 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4780 (vopinfo->com.reason == V_READONLY ||
4781 (!VolumeWriteable(vp) &&
4782 (vopinfo->com.reason == V_CLONE ||
4783 vopinfo->com.reason == V_DUMP)))));
4787 * same as VVolOpLeaveOnline_r, but does not require a volume with an attached
4790 * @param[in] vp volume object
4791 * @param[in] vopinfo volume operation info object
4793 * @return whether it is safe to leave volume online
4794 * @retval 0 it is NOT SAFE to leave the volume online
4795 * @retval 1 it is safe to leave the volume online during the operation
4796 * @retval -1 unsure; volume header is required in order to know whether or
4797 * not is is safe to leave the volume online
4799 * @pre VOL_LOCK is held
4801 * @internal volume package internal use only
4804 VVolOpLeaveOnlineNoHeader_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4806 /* follow the logic in VVolOpLeaveOnline_r; this is the same, except
4807 * assume that we don't know VolumeWriteable; return -1 if the answer
4808 * depends on VolumeWriteable */
4810 if (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline) {
4813 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4814 vopinfo->com.reason == V_READONLY) {
4818 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4819 (vopinfo->com.reason == V_CLONE ||
4820 vopinfo->com.reason == V_DUMP)) {
4822 /* must know VolumeWriteable */
4829 * determine whether VBUSY should be set during this volume operation.
4831 * @param[in] vp volume object
4832 * @param[in] vopinfo volume operation info object
4834 * @return whether VBUSY should be set
4835 * @retval 0 VBUSY does NOT need to be set
4836 * @retval 1 VBUSY SHOULD be set
4838 * @pre VOL_LOCK is held
4840 * @internal volume package internal use only
4843 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4845 return ((vopinfo->com.command == FSYNC_VOL_OFF &&
4846 vopinfo->com.reason == FSYNC_SALVAGE) ||
4847 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4848 (vopinfo->com.reason == V_CLONE ||
4849 vopinfo->com.reason == V_DUMP)));
4853 /***************************************************/
4854 /* online salvager routines */
4855 /***************************************************/
4856 #if defined(AFS_DEMAND_ATTACH_FS)
4858 * check whether a salvage needs to be performed on this volume.
4860 * @param[in] vp pointer to volume object
4862 * @return status code
4863 * @retval 0 no salvage scheduled
4864 * @retval 1 a salvage has been scheduled with the salvageserver
4866 * @pre VOL_LOCK is held
4868 * @post if salvage request flag is set and nUsers and nWaiters are zero,
4869 * then a salvage will be requested
4871 * @note this is one of the event handlers called by VCancelReservation_r
4873 * @see VCancelReservation_r
4875 * @internal volume package internal use only.
4878 VCheckSalvage(register Volume * vp)
4881 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
4882 if (vp->nUsers || vp->nWaiters)
4884 if (vp->salvage.requested) {
4885 VScheduleSalvage_r(vp);
4888 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
4893 * request volume salvage.
4895 * @param[out] ec computed client error code
4896 * @param[in] vp volume object pointer
4897 * @param[in] reason reason code (passed to salvageserver via SALVSYNC)
4898 * @param[in] flags see flags note below
4901 * VOL_SALVAGE_INVALIDATE_HEADER causes volume header cache entry
4902 * to be invalidated.
4904 * @pre VOL_LOCK is held.
4906 * @post volume state is changed.
4907 * for fileserver, salvage will be requested once refcount reaches zero.
4909 * @return operation status code
4910 * @retval 0 volume salvage will occur
4911 * @retval 1 volume salvage could not be scheduled
4915 * @note in the fileserver, this call does not synchronously schedule a volume
4916 * salvage. rather, it sets volume state so that when volume refcounts
4917 * reach zero, a volume salvage will occur. by "refcounts", we mean both
4918 * nUsers and nWaiters must be zero.
4920 * @internal volume package internal use only.
4923 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
4927 * for DAFS volume utilities that are not supposed to schedule salvages,
4928 * just transition to error state instead
4930 if (!VCanScheduleSalvage()) {
4931 VChangeState_r(vp, VOL_STATE_ERROR);
4936 if (programType != fileServer && !VCanUseFSSYNC()) {
4937 VChangeState_r(vp, VOL_STATE_ERROR);
4942 if (!vp->salvage.requested) {
4943 vp->salvage.requested = 1;
4944 vp->salvage.reason = reason;
4945 vp->stats.last_salvage = FT_ApproxTime();
4947 /* Note that it is not possible for us to reach this point if a
4948 * salvage is already running on this volume (even if the fileserver
4949 * was restarted during the salvage). If a salvage were running, the
4950 * salvager would have write-locked the volume header file, so when
4951 * we tried to lock the volume header, the lock would have failed,
4952 * and we would have failed during attachment prior to calling
4953 * VRequestSalvage. So we know that we can schedule salvages without
4954 * fear of a salvage already running for this volume. */
4956 if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
4957 VChangeState_r(vp, VOL_STATE_SALVAGING);
4960 Log("VRequestSalvage: volume %u online salvaged too many times; forced offline.\n", vp->hashid);
4962 /* make sure neither VScheduleSalvage_r nor
4963 * VUpdateSalvagePriority_r try to schedule another salvage */
4964 vp->salvage.requested = vp->salvage.scheduled = 0;
4966 VChangeState_r(vp, VOL_STATE_ERROR);
4970 if (flags & VOL_SALVAGE_INVALIDATE_HEADER) {
4971 /* Instead of ReleaseVolumeHeader, we do FreeVolumeHeader()
4972 so that the the next VAttachVolumeByVp_r() invocation
4973 of attach2() will pull in a cached header
4974 entry and fail, then load a fresh one from disk and attach
4977 FreeVolumeHeader(vp);
4984 * update salvageserver scheduling priority for a volume.
4986 * @param[in] vp pointer to volume object
4988 * @return operation status
4990 * @retval 1 request denied, or SALVSYNC communications failure
4992 * @pre VOL_LOCK is held.
4994 * @post in-core salvage priority counter is incremented. if at least
4995 * SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
4996 * last SALVSYNC_RAISEPRIO request, we contact the salvageserver
4997 * to update its priority queue. if no salvage is scheduled,
4998 * this function is a no-op.
5000 * @note DAFS fileserver only
5002 * @note this should be called whenever a VGetVolume fails due to a
5003 * pending salvage request
5005 * @todo should set exclusive state and drop glock around salvsync call
5007 * @internal volume package internal use only.
5010 VUpdateSalvagePriority_r(Volume * vp)
5014 #ifdef SALVSYNC_BUILD_CLIENT
5019 now = FT_ApproxTime();
5021 /* update the salvageserver priority queue occasionally so that
5022 * frequently requested volumes get moved to the head of the queue
5024 if ((vp->salvage.scheduled) &&
5025 (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
5026 code = SALVSYNC_SalvageVolume(vp->hashid,
5027 VPartitionPath(vp->partition),
5032 vp->stats.last_salvage_req = now;
5033 if (code != SYNC_OK) {
5037 #endif /* SALVSYNC_BUILD_CLIENT */
5042 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5044 /* A couple of little helper functions. These return true if we tried to
5045 * use this mechanism to schedule a salvage, false if we haven't tried.
5046 * If we did try a salvage then the results are contained in code.
5050 try_SALVSYNC(Volume *vp, char *partName, int *code) {
5051 #ifdef SALVSYNC_BUILD_CLIENT
5052 if (VCanUseSALVSYNC()) {
5053 Log("Scheduling salvage for volume %lu on part %s over SALVSYNC\n",
5054 afs_printable_uint32_lu(vp->hashid), partName);
5056 /* can't use V_id() since there's no guarantee
5057 * we have the disk data header at this point */
5058 *code = SALVSYNC_SalvageVolume(vp->hashid,
5071 try_FSSYNC(Volume *vp, char *partName, int *code) {
5072 #ifdef FSSYNC_BUILD_CLIENT
5073 if (VCanUseFSSYNC()) {
5074 Log("Scheduling salvage for volume %lu on part %s over FSSYNC\n",
5075 afs_printable_uint32_lu(vp->hashid), partName);
5078 * If we aren't the fileserver, tell the fileserver the volume
5079 * needs to be salvaged. We could directly tell the
5080 * salvageserver, but the fileserver keeps track of some stats
5081 * related to salvages, and handles some other salvage-related
5082 * complications for us.
5084 *code = FSYNC_VolOp(vp->hashid, partName,
5085 FSYNC_VOL_FORCE_ERROR, FSYNC_SALVAGE, NULL);
5088 #endif /* FSSYNC_BUILD_CLIENT */
5093 * schedule a salvage with the salvage server or fileserver.
5095 * @param[in] vp pointer to volume object
5097 * @return operation status
5098 * @retval 0 salvage scheduled successfully
5099 * @retval 1 salvage not scheduled, or SALVSYNC/FSSYNC com error
5102 * @arg VOL_LOCK is held.
5103 * @arg nUsers and nWaiters should be zero.
5105 * @post salvageserver or fileserver is sent a salvage request
5107 * @note If we are the fileserver, the request will be sent to the salvage
5108 * server over SALVSYNC. If we are not the fileserver, the request will be
5109 * sent to the fileserver over FSSYNC (FSYNC_VOL_FORCE_ERROR/FSYNC_SALVAGE).
5113 * @internal volume package internal use only.
5116 VScheduleSalvage_r(Volume * vp)
5120 VolState state_save;
5121 VThreadOptions_t * thread_opts;
5124 assert(VCanUseSALVSYNC() || VCanUseFSSYNC());
5126 if (vp->nWaiters || vp->nUsers) {
5130 /* prevent endless salvage,attach,salvage,attach,... loops */
5131 if (vp->stats.salvages >= SALVAGE_COUNT_MAX)
5135 * don't perform salvsync ops on certain threads
5137 thread_opts = pthread_getspecific(VThread_key);
5138 if (thread_opts == NULL) {
5139 thread_opts = &VThread_defaults;
5141 if (thread_opts->disallow_salvsync || vol_disallow_salvsync) {
5146 * XXX the scheduling process should really be done asynchronously
5147 * to avoid fssync deadlocks
5149 if (!vp->salvage.scheduled) {
5150 /* if we haven't previously scheduled a salvage, do so now
5152 * set the volume to an exclusive state and drop the lock
5153 * around the SALVSYNC call
5155 * note that we do NOT acquire a reservation here -- doing so
5156 * could result in unbounded recursion
5158 strlcpy(partName, VPartitionPath(vp->partition), sizeof(partName));
5159 state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
5162 assert(try_SALVSYNC(vp, partName, &code) ||
5163 try_FSSYNC(vp, partName, &code));
5166 VChangeState_r(vp, state_save);
5168 if (code == SYNC_OK) {
5169 vp->salvage.scheduled = 1;
5170 vp->stats.last_salvage_req = FT_ApproxTime();
5171 if (VCanUseSALVSYNC()) {
5172 /* don't record these stats for non-fileservers; let the
5173 * fileserver take care of these */
5174 vp->stats.salvages++;
5175 IncUInt64(&VStats.salvages);
5180 case SYNC_BAD_COMMAND:
5181 case SYNC_COM_ERROR:
5184 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5185 "denied\n", afs_printable_uint32_lu(vp->hashid));
5188 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5189 "received unknown protocol error %d\n",
5190 afs_printable_uint32_lu(vp->hashid), code);
5194 if (VCanUseFSSYNC()) {
5195 VChangeState_r(vp, VOL_STATE_ERROR);
5201 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5203 #ifdef SALVSYNC_BUILD_CLIENT
5206 * connect to the salvageserver SYNC service.
5208 * @return operation status
5212 * @post connection to salvageserver SYNC service established
5214 * @see VConnectSALV_r
5215 * @see VDisconnectSALV
5216 * @see VReconnectSALV
5223 retVal = VConnectSALV_r();
5229 * connect to the salvageserver SYNC service.
5231 * @return operation status
5235 * @pre VOL_LOCK is held.
5237 * @post connection to salvageserver SYNC service established
5240 * @see VDisconnectSALV_r
5241 * @see VReconnectSALV_r
5242 * @see SALVSYNC_clientInit
5244 * @internal volume package internal use only.
5247 VConnectSALV_r(void)
5249 return SALVSYNC_clientInit();
5253 * disconnect from the salvageserver SYNC service.
5255 * @return operation status
5258 * @pre client should have a live connection to the salvageserver
5260 * @post connection to salvageserver SYNC service destroyed
5262 * @see VDisconnectSALV_r
5264 * @see VReconnectSALV
5267 VDisconnectSALV(void)
5270 VDisconnectSALV_r();
5276 * disconnect from the salvageserver SYNC service.
5278 * @return operation status
5282 * @arg VOL_LOCK is held.
5283 * @arg client should have a live connection to the salvageserver.
5285 * @post connection to salvageserver SYNC service destroyed
5287 * @see VDisconnectSALV
5288 * @see VConnectSALV_r
5289 * @see VReconnectSALV_r
5290 * @see SALVSYNC_clientFinis
5292 * @internal volume package internal use only.
5295 VDisconnectSALV_r(void)
5297 return SALVSYNC_clientFinis();
5301 * disconnect and then re-connect to the salvageserver SYNC service.
5303 * @return operation status
5307 * @pre client should have a live connection to the salvageserver
5309 * @post old connection is dropped, and a new one is established
5312 * @see VDisconnectSALV
5313 * @see VReconnectSALV_r
5316 VReconnectSALV(void)
5320 retVal = VReconnectSALV_r();
5326 * disconnect and then re-connect to the salvageserver SYNC service.
5328 * @return operation status
5333 * @arg VOL_LOCK is held.
5334 * @arg client should have a live connection to the salvageserver.
5336 * @post old connection is dropped, and a new one is established
5338 * @see VConnectSALV_r
5339 * @see VDisconnectSALV
5340 * @see VReconnectSALV
5341 * @see SALVSYNC_clientReconnect
5343 * @internal volume package internal use only.
5346 VReconnectSALV_r(void)
5348 return SALVSYNC_clientReconnect();
5350 #endif /* SALVSYNC_BUILD_CLIENT */
5351 #endif /* AFS_DEMAND_ATTACH_FS */
5354 /***************************************************/
5355 /* FSSYNC routines */
5356 /***************************************************/
5358 /* This must be called by any volume utility which needs to run while the
5359 file server is also running. This is separated from VInitVolumePackage2 so
5360 that a utility can fork--and each of the children can independently
5361 initialize communication with the file server */
5362 #ifdef FSSYNC_BUILD_CLIENT
5364 * connect to the fileserver SYNC service.
5366 * @return operation status
5371 * @arg VInit must equal 2.
5372 * @arg Program Type must not be fileserver or salvager.
5374 * @post connection to fileserver SYNC service established
5377 * @see VDisconnectFS
5378 * @see VChildProcReconnectFS
5385 retVal = VConnectFS_r();
5391 * connect to the fileserver SYNC service.
5393 * @return operation status
5398 * @arg VInit must equal 2.
5399 * @arg Program Type must not be fileserver or salvager.
5400 * @arg VOL_LOCK is held.
5402 * @post connection to fileserver SYNC service established
5405 * @see VDisconnectFS_r
5406 * @see VChildProcReconnectFS_r
5408 * @internal volume package internal use only.
5414 assert((VInit == 2) &&
5415 (programType != fileServer) &&
5416 (programType != salvager));
5417 rc = FSYNC_clientInit();
5424 * disconnect from the fileserver SYNC service.
5427 * @arg client should have a live connection to the fileserver.
5428 * @arg VOL_LOCK is held.
5429 * @arg Program Type must not be fileserver or salvager.
5431 * @post connection to fileserver SYNC service destroyed
5433 * @see VDisconnectFS
5435 * @see VChildProcReconnectFS_r
5437 * @internal volume package internal use only.
5440 VDisconnectFS_r(void)
5442 assert((programType != fileServer) &&
5443 (programType != salvager));
5444 FSYNC_clientFinis();
5449 * disconnect from the fileserver SYNC service.
5452 * @arg client should have a live connection to the fileserver.
5453 * @arg Program Type must not be fileserver or salvager.
5455 * @post connection to fileserver SYNC service destroyed
5457 * @see VDisconnectFS_r
5459 * @see VChildProcReconnectFS
5470 * connect to the fileserver SYNC service from a child process following a fork.
5472 * @return operation status
5477 * @arg VOL_LOCK is held.
5478 * @arg current FSYNC handle is shared with a parent process
5480 * @post current FSYNC handle is discarded and a new connection to the
5481 * fileserver SYNC service is established
5483 * @see VChildProcReconnectFS
5485 * @see VDisconnectFS_r
5487 * @internal volume package internal use only.
5490 VChildProcReconnectFS_r(void)
5492 return FSYNC_clientChildProcReconnect();
5496 * connect to the fileserver SYNC service from a child process following a fork.
5498 * @return operation status
5502 * @pre current FSYNC handle is shared with a parent process
5504 * @post current FSYNC handle is discarded and a new connection to the
5505 * fileserver SYNC service is established
5507 * @see VChildProcReconnectFS_r
5509 * @see VDisconnectFS
5512 VChildProcReconnectFS(void)
5516 ret = VChildProcReconnectFS_r();
5520 #endif /* FSSYNC_BUILD_CLIENT */
5523 /***************************************************/
5524 /* volume bitmap routines */
5525 /***************************************************/
5528 * allocate a vnode bitmap number for the vnode
5530 * @param[out] ec error code
5531 * @param[in] vp volume object pointer
5532 * @param[in] index vnode index number for the vnode
5533 * @param[in] flags flag values described in note
5535 * @note for DAFS, flags parameter controls locking behavior.
5536 * If (flags & VOL_ALLOC_BITMAP_WAIT) is set, then this function
5537 * will create a reservation and block on any other exclusive
5538 * operations. Otherwise, this function assumes the caller
5539 * already has exclusive access to vp, and we just change the
5542 * @pre VOL_LOCK held
5544 * @return bit number allocated
5550 VAllocBitmapEntry_r(Error * ec, Volume * vp,
5551 struct vnodeIndex *index, int flags)
5554 register byte *bp, *ep;
5555 #ifdef AFS_DEMAND_ATTACH_FS
5556 VolState state_save;
5557 #endif /* AFS_DEMAND_ATTACH_FS */
5561 /* This test is probably redundant */
5562 if (!VolumeWriteable(vp)) {
5563 *ec = (bit32) VREADONLY;
5567 #ifdef AFS_DEMAND_ATTACH_FS
5568 if (flags & VOL_ALLOC_BITMAP_WAIT) {
5569 VCreateReservation_r(vp);
5570 VWaitExclusiveState_r(vp);
5572 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
5573 #endif /* AFS_DEMAND_ATTACH_FS */
5576 if ((programType == fileServer) && !index->bitmap) {
5578 #ifndef AFS_DEMAND_ATTACH_FS
5579 /* demand attach fs uses the volume state to avoid races.
5580 * specialStatus field is not used at all */
5582 if (vp->specialStatus == VBUSY) {
5583 if (vp->goingOffline) { /* vos dump waiting for the volume to
5584 * go offline. We probably come here
5585 * from AddNewReadableResidency */
5588 while (vp->specialStatus == VBUSY) {
5589 #ifdef AFS_PTHREAD_ENV
5593 #else /* !AFS_PTHREAD_ENV */
5595 #endif /* !AFS_PTHREAD_ENV */
5599 #endif /* !AFS_DEMAND_ATTACH_FS */
5601 if (!index->bitmap) {
5602 #ifndef AFS_DEMAND_ATTACH_FS
5603 vp->specialStatus = VBUSY; /* Stop anyone else from using it. */
5604 #endif /* AFS_DEMAND_ATTACH_FS */
5605 for (i = 0; i < nVNODECLASSES; i++) {
5606 VGetBitmap_r(ec, vp, i);
5608 #ifdef AFS_DEMAND_ATTACH_FS
5609 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
5610 #else /* AFS_DEMAND_ATTACH_FS */
5611 DeleteVolumeFromHashTable(vp);
5612 vp->shuttingDown = 1; /* Let who has it free it. */
5613 vp->specialStatus = 0;
5614 #endif /* AFS_DEMAND_ATTACH_FS */
5618 #ifndef AFS_DEMAND_ATTACH_FS
5620 vp->specialStatus = 0; /* Allow others to have access. */
5621 #endif /* AFS_DEMAND_ATTACH_FS */
5624 #endif /* BITMAP_LATER */
5626 #ifdef AFS_DEMAND_ATTACH_FS
5628 #endif /* AFS_DEMAND_ATTACH_FS */
5629 bp = index->bitmap + index->bitmapOffset;
5630 ep = index->bitmap + index->bitmapSize;
5632 if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
5634 index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
5637 o = ffs(~*bp) - 1; /* ffs is documented in BSTRING(3) */
5639 ret = ((bp - index->bitmap) * 8 + o);
5640 #ifdef AFS_DEMAND_ATTACH_FS
5642 #endif /* AFS_DEMAND_ATTACH_FS */
5645 bp += sizeof(bit32) /* i.e. 4 */ ;
5647 /* No bit map entry--must grow bitmap */
5649 realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
5652 bp += index->bitmapSize;
5653 memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
5654 index->bitmapOffset = index->bitmapSize;
5655 index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
5657 ret = index->bitmapOffset * 8;
5658 #ifdef AFS_DEMAND_ATTACH_FS
5660 #endif /* AFS_DEMAND_ATTACH_FS */
5663 #ifdef AFS_DEMAND_ATTACH_FS
5664 VChangeState_r(vp, state_save);
5665 if (flags & VOL_ALLOC_BITMAP_WAIT) {
5666 VCancelReservation_r(vp);
5668 #endif /* AFS_DEMAND_ATTACH_FS */
5673 VAllocBitmapEntry(Error * ec, Volume * vp, register struct vnodeIndex * index)
5677 retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
5683 VFreeBitMapEntry_r(Error * ec, register struct vnodeIndex *index,
5686 unsigned int offset;
5692 #endif /* BITMAP_LATER */
5693 offset = bitNumber >> 3;
5694 if (offset >= index->bitmapSize) {
5698 if (offset < index->bitmapOffset)
5699 index->bitmapOffset = offset & ~3; /* Truncate to nearest bit32 */
5700 *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
5704 VFreeBitMapEntry(Error * ec, register struct vnodeIndex *index,
5708 VFreeBitMapEntry_r(ec, index, bitNumber);
5712 /* this function will drop the glock internally.
5713 * for old pthread fileservers, this is safe thanks to vbusy.
5715 * for demand attach fs, caller must have already called
5716 * VCreateReservation_r and VWaitExclusiveState_r */
5718 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
5720 StreamHandle_t *file;
5721 afs_sfsize_t nVnodes, size;
5722 struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
5723 struct vnodeIndex *vip = &vp->vnodeIndex[class];
5724 struct VnodeDiskObject *vnode;
5725 unsigned int unique = 0;
5729 #endif /* BITMAP_LATER */
5730 #ifdef AFS_DEMAND_ATTACH_FS
5731 VolState state_save;
5732 #endif /* AFS_DEMAND_ATTACH_FS */
5736 #ifdef AFS_DEMAND_ATTACH_FS
5737 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
5738 #endif /* AFS_DEMAND_ATTACH_FS */
5741 fdP = IH_OPEN(vip->handle);
5742 assert(fdP != NULL);
5743 file = FDH_FDOPEN(fdP, "r");
5744 assert(file != NULL);
5745 vnode = (VnodeDiskObject *) malloc(vcp->diskSize);
5746 assert(vnode != NULL);
5747 size = OS_SIZE(fdP->fd_fd);
5749 nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
5751 vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4; /* The 10 is a little extra so
5752 * a few files can be created in this volume,
5753 * the whole thing is rounded up to nearest 4
5754 * bytes, because the bit map allocator likes
5757 BitMap = (byte *) calloc(1, vip->bitmapSize);
5758 assert(BitMap != NULL);
5759 #else /* BITMAP_LATER */
5760 vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
5761 assert(vip->bitmap != NULL);
5762 vip->bitmapOffset = 0;
5763 #endif /* BITMAP_LATER */
5764 if (STREAM_SEEK(file, vcp->diskSize, 0) != -1) {
5766 for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
5767 if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
5769 if (vnode->type != vNull) {
5770 if (vnode->vnodeMagic != vcp->magic) {
5771 Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
5776 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
5777 #else /* BITMAP_LATER */
5778 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
5779 #endif /* BITMAP_LATER */
5780 if (unique <= vnode->uniquifier)
5781 unique = vnode->uniquifier + 1;
5783 #ifndef AFS_PTHREAD_ENV
5784 if ((bitNumber & 0x00ff) == 0x0ff) { /* every 256 iterations */
5787 #endif /* !AFS_PTHREAD_ENV */
5790 if (vp->nextVnodeUnique < unique) {
5791 Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
5794 /* Paranoia, partly justified--I think fclose after fdopen
5795 * doesn't seem to close fd. In any event, the documentation
5796 * doesn't specify, so it's safer to close it twice.
5804 /* There may have been a racing condition with some other thread, both
5805 * creating the bitmaps for this volume. If the other thread was faster
5806 * the pointer to bitmap should already be filled and we can free ours.
5808 if (vip->bitmap == NULL) {
5809 vip->bitmap = BitMap;
5810 vip->bitmapOffset = 0;
5812 free((byte *) BitMap);
5813 #endif /* BITMAP_LATER */
5814 #ifdef AFS_DEMAND_ATTACH_FS
5815 VChangeState_r(vp, state_save);
5816 #endif /* AFS_DEMAND_ATTACH_FS */
5820 /***************************************************/
5821 /* Volume Path and Volume Number utility routines */
5822 /***************************************************/
5825 * find the first occurrence of a volume header file and return the path.
5827 * @param[out] ec outbound error code
5828 * @param[in] volumeId volume id to find
5829 * @param[out] partitionp pointer to disk partition path string
5830 * @param[out] namep pointer to volume header file name string
5832 * @post path to first occurrence of volume header is returned in partitionp
5833 * and namep, or ec is set accordingly.
5835 * @warning this function is NOT re-entrant -- partitionp and namep point to
5836 * static data segments
5838 * @note if a volume utility inadvertently leaves behind a stale volume header
5839 * on a vice partition, it is possible for callers to get the wrong one,
5840 * depending on the order of the disk partition linked list.
5844 VGetVolumePath(Error * ec, VolId volumeId, char **partitionp, char **namep)
5846 static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
5847 char path[VMAXPATHLEN];
5849 struct DiskPartition64 *dp;
5853 (void)afs_snprintf(&name[1], (sizeof name) - 1, VFORMAT, afs_printable_uint32_lu(volumeId));
5854 for (dp = DiskPartitionList; dp; dp = dp->next) {
5855 struct afs_stat status;
5856 strcpy(path, VPartitionPath(dp));
5858 if (afs_stat(path, &status) == 0) {
5859 strcpy(partition, dp->name);
5866 *partitionp = *namep = NULL;
5868 *partitionp = partition;
5874 * extract a volume number from a volume header filename string.
5876 * @param[in] name volume header filename string
5878 * @return volume number
5880 * @note the string must be of the form VFORMAT. the only permissible
5881 * deviation is a leading '/' character.
5886 VolumeNumber(char *name)
5890 return atoi(name + 1);
5894 * compute the volume header filename.
5896 * @param[in] volumeId
5898 * @return volume header filename
5900 * @post volume header filename string is constructed
5902 * @warning this function is NOT re-entrant -- the returned string is
5903 * stored in a static char array. see VolumeExternalName_r
5904 * for a re-entrant equivalent.
5906 * @see VolumeExternalName_r
5908 * @deprecated due to the above re-entrancy warning, this interface should
5909 * be considered deprecated. Please use VolumeExternalName_r
5913 VolumeExternalName(VolumeId volumeId)
5915 static char name[VMAXPATHLEN];
5916 (void)afs_snprintf(name, sizeof name, VFORMAT, afs_printable_uint32_lu(volumeId));
5921 * compute the volume header filename.
5923 * @param[in] volumeId
5924 * @param[inout] name array in which to store filename
5925 * @param[in] len length of name array
5927 * @return result code from afs_snprintf
5929 * @see VolumeExternalName
5932 * @note re-entrant equivalent of VolumeExternalName
5935 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
5937 return afs_snprintf(name, len, VFORMAT, afs_printable_uint32_lu(volumeId));
5941 /***************************************************/
5942 /* Volume Usage Statistics routines */
5943 /***************************************************/
5945 #if OPENAFS_VOL_STATS
5946 #define OneDay (86400) /* 24 hours' worth of seconds */
5948 #define OneDay (24*60*60) /* 24 hours */
5949 #endif /* OPENAFS_VOL_STATS */
5952 Midnight(time_t t) {
5953 struct tm local, *l;
5956 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
5957 l = localtime_r(&t, &local);
5963 /* the following is strictly speaking problematic on the
5964 switching day to daylight saving time, after the switch,
5965 as tm_isdst does not match. Similarly, on the looong day when
5966 switching back the OneDay check will not do what naively expected!
5967 The effects are minor, though, and more a matter of interpreting
5969 #ifndef AFS_PTHREAD_ENV
5972 local.tm_hour = local.tm_min=local.tm_sec = 0;
5973 midnight = mktime(&local);
5974 if (midnight != (time_t) -1) return(midnight);
5976 return( (t/OneDay)*OneDay );
5980 /*------------------------------------------------------------------------
5981 * [export] VAdjustVolumeStatistics
5984 * If we've passed midnight, we need to update all the day use
5985 * statistics as well as zeroing the detailed volume statistics
5986 * (if we are implementing them).
5989 * vp : Pointer to the volume structure describing the lucky
5990 * volume being considered for update.
5996 * Nothing interesting.
6000 *------------------------------------------------------------------------*/
6003 VAdjustVolumeStatistics_r(register Volume * vp)
6005 unsigned int now = FT_ApproxTime();
6007 if (now - V_dayUseDate(vp) > OneDay) {
6008 register int ndays, i;
6010 ndays = (now - V_dayUseDate(vp)) / OneDay;
6011 for (i = 6; i > ndays - 1; i--)
6012 V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
6013 for (i = 0; i < ndays - 1 && i < 7; i++)
6014 V_weekUse(vp)[i] = 0;
6016 V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
6018 V_dayUseDate(vp) = Midnight(now);
6020 #if OPENAFS_VOL_STATS
6022 * All we need to do is bzero the entire VOL_STATS_BYTES of
6023 * the detailed volume statistics area.
6025 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
6026 #endif /* OPENAFS_VOL_STATS */
6029 /*It's been more than a day of collection */
6031 * Always return happily.
6034 } /*VAdjustVolumeStatistics */
6037 VAdjustVolumeStatistics(register Volume * vp)
6041 retVal = VAdjustVolumeStatistics_r(vp);
6047 VBumpVolumeUsage_r(register Volume * vp)
6049 unsigned int now = FT_ApproxTime();
6050 V_accessDate(vp) = now;
6051 if (now - V_dayUseDate(vp) > OneDay)
6052 VAdjustVolumeStatistics_r(vp);
6054 * Save the volume header image to disk after every 128 bumps to dayUse.
6056 if ((V_dayUse(vp)++ & 127) == 0) {
6058 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
6063 VBumpVolumeUsage(register Volume * vp)
6066 VBumpVolumeUsage_r(vp);
6071 VSetDiskUsage_r(void)
6073 #ifndef AFS_DEMAND_ATTACH_FS
6074 static int FifteenMinuteCounter = 0;
6078 /* NOTE: Don't attempt to access the partitions list until the
6079 * initialization level indicates that all volumes are attached,
6080 * which implies that all partitions are initialized. */
6081 #ifdef AFS_PTHREAD_ENV
6083 #else /* AFS_PTHREAD_ENV */
6085 #endif /* AFS_PTHREAD_ENV */
6088 VResetDiskUsage_r();
6090 #ifndef AFS_DEMAND_ATTACH_FS
6091 if (++FifteenMinuteCounter == 3) {
6092 FifteenMinuteCounter = 0;
6095 #endif /* !AFS_DEMAND_ATTACH_FS */
6107 /***************************************************/
6108 /* Volume Update List routines */
6109 /***************************************************/
6111 /* The number of minutes that a volume hasn't been updated before the
6112 * "Dont salvage" flag in the volume header will be turned on */
6113 #define SALVAGE_INTERVAL (10*60)
6118 * volume update list functionality has been moved into the VLRU
6119 * the DONT_SALVAGE flag is now set during VLRU demotion
6122 #ifndef AFS_DEMAND_ATTACH_FS
6123 static VolumeId *UpdateList = NULL; /* Pointer to array of Volume ID's */
6124 static int nUpdatedVolumes = 0; /* Updated with entry in UpdateList, salvage after crash flag on */
6125 static int updateSize = 0; /* number of entries possible */
6126 #define UPDATE_LIST_SIZE 128 /* initial size increment (must be a power of 2!) */
6127 #endif /* !AFS_DEMAND_ATTACH_FS */
6130 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
6133 vp->updateTime = FT_ApproxTime();
6134 if (V_dontSalvage(vp) == 0)
6136 V_dontSalvage(vp) = 0;
6137 VSyncVolume_r(ec, vp, 0);
6138 #ifdef AFS_DEMAND_ATTACH_FS
6139 V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
6140 #else /* !AFS_DEMAND_ATTACH_FS */
6143 if (UpdateList == NULL) {
6144 updateSize = UPDATE_LIST_SIZE;
6145 UpdateList = (VolumeId *) malloc(sizeof(VolumeId) * updateSize);
6147 if (nUpdatedVolumes == updateSize) {
6149 if (updateSize > 524288) {
6150 Log("warning: there is likely a bug in the volume update scanner\n");
6154 (VolumeId *) realloc(UpdateList,
6155 sizeof(VolumeId) * updateSize);
6158 assert(UpdateList != NULL);
6159 UpdateList[nUpdatedVolumes++] = V_id(vp);
6160 #endif /* !AFS_DEMAND_ATTACH_FS */
6163 #ifndef AFS_DEMAND_ATTACH_FS
6165 VScanUpdateList(void)
6167 register int i, gap;
6168 register Volume *vp;
6170 afs_uint32 now = FT_ApproxTime();
6171 /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
6172 for (i = gap = 0; i < nUpdatedVolumes; i++) {
6174 UpdateList[i - gap] = UpdateList[i];
6176 /* XXX this routine needlessly messes up the Volume LRU by
6177 * breaking the LRU temporal-locality assumptions.....
6178 * we should use a special volume header allocator here */
6179 vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
6182 } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
6183 V_dontSalvage(vp) = DONT_SALVAGE;
6184 VUpdateVolume_r(&error, vp, 0); /* No need to fsync--not critical */
6192 #ifndef AFS_PTHREAD_ENV
6194 #endif /* !AFS_PTHREAD_ENV */
6196 nUpdatedVolumes -= gap;
6198 #endif /* !AFS_DEMAND_ATTACH_FS */
6201 /***************************************************/
6202 /* Volume LRU routines */
6203 /***************************************************/
6208 * with demand attach fs, we attempt to soft detach(1)
6209 * volumes which have not been accessed in a long time
6210 * in order to speed up fileserver shutdown
6212 * (1) by soft detach we mean a process very similar
6213 * to VOffline, except the final state of the
6214 * Volume will be VOL_STATE_PREATTACHED, instead
6215 * of the usual VOL_STATE_UNATTACHED
6217 #ifdef AFS_DEMAND_ATTACH_FS
6219 /* implementation is reminiscent of a generational GC
6221 * queue 0 is newly attached volumes. this queue is
6222 * sorted by attach timestamp
6224 * queue 1 is volumes that have been around a bit
6225 * longer than queue 0. this queue is sorted by
6228 * queue 2 is volumes tha have been around the longest.
6229 * this queue is unsorted
6231 * queue 3 is volumes that have been marked as
6232 * candidates for soft detachment. this queue is
6235 #define VLRU_GENERATIONS 3 /**< number of generations in VLRU */
6236 #define VLRU_QUEUES 5 /**< total number of VLRU queues */
6239 * definition of a VLRU queue.
6242 volatile struct rx_queue q;
6249 * main VLRU data structure.
6252 struct VLRU_q q[VLRU_QUEUES]; /**< VLRU queues */
6255 /** time interval (in seconds) between promotion passes for
6256 * each young generation queue. */
6257 afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
6259 /** time interval (in seconds) between soft detach candidate
6260 * scans for each generation queue.
6262 * scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
6263 * we perform a soft detach pass. */
6264 afs_uint32 scan_interval[VLRU_GENERATIONS+1];
6266 /* scheduler state */
6267 int next_idx; /**< next queue to receive attention */
6268 afs_uint32 last_promotion[VLRU_GENERATIONS-1]; /**< timestamp of last promotion scan */
6269 afs_uint32 last_scan[VLRU_GENERATIONS+1]; /**< timestamp of last detach scan */
6271 int scanner_state; /**< state of scanner thread */
6272 pthread_cond_t cv; /**< state transition CV */
6275 /** global VLRU state */
6276 static struct VLRU volume_LRU;
6279 * defined states for VLRU scanner thread.
6282 VLRU_SCANNER_STATE_OFFLINE = 0, /**< vlru scanner thread is offline */
6283 VLRU_SCANNER_STATE_ONLINE = 1, /**< vlru scanner thread is online */
6284 VLRU_SCANNER_STATE_SHUTTING_DOWN = 2, /**< vlru scanner thread is shutting down */
6285 VLRU_SCANNER_STATE_PAUSING = 3, /**< vlru scanner thread is getting ready to pause */
6286 VLRU_SCANNER_STATE_PAUSED = 4 /**< vlru scanner thread is paused */
6287 } vlru_thread_state_t;
6289 /* vlru disk data header stuff */
6290 #define VLRU_DISK_MAGIC 0x7a8b9cad /**< vlru disk entry magic number */
6291 #define VLRU_DISK_VERSION 1 /**< vlru disk entry version number */
6293 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
6294 #define VLRU_DUMP_EXPIRATION_TIME (60*60*24*7) /* expire vlru data after 1 week */
6297 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
6298 * soft detachment. */
6299 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
6301 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
6302 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
6304 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
6305 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
6307 /** VLRU control flag. non-zero value implies VLRU subsystem is activated. */
6308 static afs_uint32 VLRU_enabled = 1;
6310 /* queue synchronization routines */
6311 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
6312 static void VLRU_EndExclusive_r(struct VLRU_q * q);
6313 static void VLRU_Wait_r(struct VLRU_q * q);
6316 * set VLRU subsystem tunable parameters.
6318 * @param[in] option tunable option to modify
6319 * @param[in] val new value for tunable parameter
6321 * @pre @c VInitVolumePackage2 has not yet been called.
6323 * @post tunable parameter is modified
6327 * @note valid option parameters are:
6328 * @arg @c VLRU_SET_THRESH
6329 * set the period of inactivity after which
6330 * volumes are eligible for soft detachment
6331 * @arg @c VLRU_SET_INTERVAL
6332 * set the time interval between calls
6333 * to the volume LRU "garbage collector"
6334 * @arg @c VLRU_SET_MAX
6335 * set the max number of volumes to deallocate
6339 VLRU_SetOptions(int option, afs_uint32 val)
6341 if (option == VLRU_SET_THRESH) {
6342 VLRU_offline_thresh = val;
6343 } else if (option == VLRU_SET_INTERVAL) {
6344 VLRU_offline_interval = val;
6345 } else if (option == VLRU_SET_MAX) {
6346 VLRU_offline_max = val;
6347 } else if (option == VLRU_SET_ENABLED) {
6350 VLRU_ComputeConstants();
6354 * compute VLRU internal timing parameters.
6356 * @post VLRU scanner thread internal timing parameters are computed
6358 * @note computes internal timing parameters based upon user-modifiable
6359 * tunable parameters.
6363 * @internal volume package internal use only.
6366 VLRU_ComputeConstants(void)
6368 afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
6370 /* compute the candidate scan interval */
6371 volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
6373 /* compute the promotion intervals */
6374 volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
6375 volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
6378 /* compute the gen 0 scan interval */
6379 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
6381 /* compute the gen 0 scan interval */
6382 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
6387 * initialize VLRU subsystem.
6389 * @pre this function has not yet been called
6391 * @post VLRU subsystem is initialized and VLRU scanner thread is starting
6395 * @internal volume package internal use only.
6401 pthread_attr_t attrs;
6404 if (!VLRU_enabled) {
6405 Log("VLRU: disabled\n");
6409 /* initialize each of the VLRU queues */
6410 for (i = 0; i < VLRU_QUEUES; i++) {
6411 queue_Init(&volume_LRU.q[i]);
6412 volume_LRU.q[i].len = 0;
6413 volume_LRU.q[i].busy = 0;
6414 assert(pthread_cond_init(&volume_LRU.q[i].cv, NULL) == 0);
6417 /* setup the timing constants */
6418 VLRU_ComputeConstants();
6420 /* XXX put inside LogLevel check? */
6421 Log("VLRU: starting scanner with the following configuration parameters:\n");
6422 Log("VLRU: offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
6423 Log("VLRU: running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
6424 Log("VLRU: taking up to %d volumes offline per pass\n", VLRU_offline_max);
6425 Log("VLRU: scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
6426 Log("VLRU: scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
6427 Log("VLRU: scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
6429 /* start up the VLRU scanner */
6430 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
6431 if (programType == fileServer) {
6432 assert(pthread_cond_init(&volume_LRU.cv, NULL) == 0);
6433 assert(pthread_attr_init(&attrs) == 0);
6434 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
6435 assert(pthread_create(&tid, &attrs, &VLRU_ScannerThread, NULL) == 0);
6440 * initialize the VLRU-related fields of a newly allocated volume object.
6442 * @param[in] vp pointer to volume object
6445 * @arg @c VOL_LOCK is held.
6446 * @arg volume object is not on a VLRU queue.
6448 * @post VLRU fields are initialized to indicate that volume object is not
6449 * currently registered with the VLRU subsystem
6453 * @internal volume package interal use only.
6456 VLRU_Init_Node_r(Volume * vp)
6461 assert(queue_IsNotOnQueue(&vp->vlru));
6462 vp->vlru.idx = VLRU_QUEUE_INVALID;
6466 * add a volume object to a VLRU queue.
6468 * @param[in] vp pointer to volume object
6471 * @arg @c VOL_LOCK is held.
6472 * @arg caller MUST hold a lightweight ref on @p vp.
6473 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
6475 * @post the volume object is added to the appropriate VLRU queue
6477 * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
6478 * then the volume is added to that queue. Otherwise, the value
6479 * @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
6480 * volume is added to the NEW generation queue.
6482 * @note @c VOL_LOCK may be dropped internally
6484 * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
6485 * during the add operation, and is restored to the previous
6486 * state prior to return.
6490 * @internal volume package internal use only.
6493 VLRU_Add_r(Volume * vp)
6496 VolState state_save;
6501 if (queue_IsOnQueue(&vp->vlru))
6504 state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
6507 if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
6508 idx = VLRU_QUEUE_NEW;
6511 VLRU_Wait_r(&volume_LRU.q[idx]);
6513 /* repeat check since VLRU_Wait_r may have dropped
6515 if (queue_IsNotOnQueue(&vp->vlru)) {
6517 queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
6518 volume_LRU.q[idx].len++;
6519 V_attachFlags(vp) |= VOL_ON_VLRU;
6520 vp->stats.last_promote = FT_ApproxTime();
6523 VChangeState_r(vp, state_save);
6527 * delete a volume object from a VLRU queue.
6529 * @param[in] vp pointer to volume object
6532 * @arg @c VOL_LOCK is held.
6533 * @arg caller MUST hold a lightweight ref on @p vp.
6534 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
6536 * @post volume object is removed from the VLRU queue
6538 * @note @c VOL_LOCK may be dropped internally
6542 * @todo We should probably set volume state to something exlcusive
6543 * (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
6545 * @internal volume package internal use only.
6548 VLRU_Delete_r(Volume * vp)
6555 if (queue_IsNotOnQueue(&vp->vlru))
6561 if (idx == VLRU_QUEUE_INVALID)
6563 VLRU_Wait_r(&volume_LRU.q[idx]);
6564 } while (idx != vp->vlru.idx);
6566 /* now remove from the VLRU and update
6567 * the appropriate counter */
6568 queue_Remove(&vp->vlru);
6569 volume_LRU.q[idx].len--;
6570 vp->vlru.idx = VLRU_QUEUE_INVALID;
6571 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
6575 * tell the VLRU subsystem that a volume was just accessed.
6577 * @param[in] vp pointer to volume object
6580 * @arg @c VOL_LOCK is held
6581 * @arg caller MUST hold a lightweight ref on @p vp
6582 * @arg caller MUST NOT hold exclusive ownership of any VLRU queue
6584 * @post volume VLRU access statistics are updated. If the volume was on
6585 * the VLRU soft detach candidate queue, it is moved to the NEW
6588 * @note @c VOL_LOCK may be dropped internally
6592 * @internal volume package internal use only.
6595 VLRU_UpdateAccess_r(Volume * vp)
6597 Volume * rvp = NULL;
6602 if (queue_IsNotOnQueue(&vp->vlru))
6605 assert(V_attachFlags(vp) & VOL_ON_VLRU);
6607 /* update the access timestamp */
6608 vp->stats.last_get = FT_ApproxTime();
6611 * if the volume is on the soft detach candidate
6612 * list, we need to safely move it back to a
6613 * regular generation. this has to be done
6614 * carefully so we don't race against the scanner
6618 /* if this volume is on the soft detach candidate queue,
6619 * then grab exclusive access to the necessary queues */
6620 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
6622 VCreateReservation_r(rvp);
6624 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
6625 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
6626 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6627 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6630 /* make sure multiple threads don't race to update */
6631 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
6632 VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
6636 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6637 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
6638 VCancelReservation_r(rvp);
6643 * switch a volume between two VLRU queues.
6645 * @param[in] vp pointer to volume object
6646 * @param[in] new_idx index of VLRU queue onto which the volume will be moved
6647 * @param[in] append controls whether the volume will be appended or
6648 * prepended to the queue. A nonzero value means it will
6649 * be appended; zero means it will be prepended.
6651 * @pre The new (and old, if applicable) queue(s) must either be owned
6652 * exclusively by the calling thread for asynchronous manipulation,
6653 * or the queue(s) must be quiescent and VOL_LOCK must be held.
6654 * Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
6655 * for further details of the queue asynchronous processing mechanism.
6657 * @post If the volume object was already on a VLRU queue, it is
6658 * removed from the queue. Depending on the value of the append
6659 * parameter, the volume object is either appended or prepended
6660 * to the VLRU queue referenced by the new_idx parameter.
6664 * @see VLRU_BeginExclusive_r
6665 * @see VLRU_EndExclusive_r
6668 * @internal volume package internal use only.
6671 VLRU_SwitchQueues(Volume * vp, int new_idx, int append)
6673 if (queue_IsNotOnQueue(&vp->vlru))
6676 queue_Remove(&vp->vlru);
6677 volume_LRU.q[vp->vlru.idx].len--;
6679 /* put the volume back on the correct generational queue */
6681 queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
6683 queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
6686 volume_LRU.q[new_idx].len++;
6687 vp->vlru.idx = new_idx;
6691 * VLRU background thread.
6693 * The VLRU Scanner Thread is responsible for periodically scanning through
6694 * each VLRU queue looking for volumes which should be moved to another
6695 * queue, or soft detached.
6697 * @param[in] args unused thread arguments parameter
6699 * @return unused thread return value
6700 * @retval NULL always
6702 * @internal volume package internal use only.
6705 VLRU_ScannerThread(void * args)
6707 afs_uint32 now, min_delay, delay;
6708 int i, min_idx, min_op, overdue, state;
6710 /* set t=0 for promotion cycle to be
6711 * fileserver startup */
6712 now = FT_ApproxTime();
6713 for (i=0; i < VLRU_GENERATIONS-1; i++) {
6714 volume_LRU.last_promotion[i] = now;
6717 /* don't start the scanner until VLRU_offline_thresh
6718 * plus a small delay for VInitVolumePackage2 to finish
6721 sleep(VLRU_offline_thresh + 60);
6723 /* set t=0 for scan cycle to be now */
6724 now = FT_ApproxTime();
6725 for (i=0; i < VLRU_GENERATIONS+1; i++) {
6726 volume_LRU.last_scan[i] = now;
6730 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
6731 volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
6734 while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
6735 /* check to see if we've been asked to pause */
6736 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
6737 volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
6738 assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
6740 VOL_CV_WAIT(&volume_LRU.cv);
6741 } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
6744 /* scheduling can happen outside the glock */
6747 /* figure out what is next on the schedule */
6749 /* figure out a potential schedule for the new generation first */
6751 min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
6754 if (min_delay > volume_LRU.scan_interval[0]) {
6755 /* unsigned overflow -- we're overdue to run this scan */
6760 /* if we're not overdue for gen 0, figure out schedule for candidate gen */
6762 i = VLRU_QUEUE_CANDIDATE;
6763 delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
6764 if (delay < min_delay) {
6768 if (delay > volume_LRU.scan_interval[i]) {
6769 /* unsigned overflow -- we're overdue to run this scan */
6776 /* if we're still not overdue for something, figure out schedules for promotions */
6777 for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
6778 delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
6779 if (delay < min_delay) {
6784 if (delay > volume_LRU.promotion_interval[i]) {
6785 /* unsigned overflow -- we're overdue to run this promotion */
6794 /* sleep as needed */
6799 /* do whatever is next */
6802 VLRU_Promote_r(min_idx);
6803 VLRU_Demote_r(min_idx+1);
6805 VLRU_Scan_r(min_idx);
6807 now = FT_ApproxTime();
6810 Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
6812 /* signal that scanner is down */
6813 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
6814 assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
6820 * promote volumes from one VLRU generation to the next.
6822 * This routine scans a VLRU generation looking for volumes which are
6823 * eligible to be promoted to the next generation. All volumes which
6824 * meet the eligibility requirement are promoted.
6826 * Promotion eligibility is based upon meeting both of the following
6829 * @arg The volume has been accessed since the last promotion:
6830 * @c (vp->stats.last_get >= vp->stats.last_promote)
6831 * @arg The last promotion occurred at least
6832 * @c volume_LRU.promotion_interval[idx] seconds ago
6834 * As a performance optimization, promotions are "globbed". In other
6835 * words, we promote arbitrarily large contiguous sublists of elements
6838 * @param[in] idx VLRU queue index to scan
6842 * @internal VLRU internal use only.
6845 VLRU_Promote_r(int idx)
6847 int len, chaining, promote;
6848 afs_uint32 now, thresh;
6849 struct rx_queue *qp, *nqp;
6850 Volume * vp, *start = NULL, *end = NULL;
6852 /* get exclusive access to two chains, and drop the glock */
6853 VLRU_Wait_r(&volume_LRU.q[idx]);
6854 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
6855 VLRU_Wait_r(&volume_LRU.q[idx+1]);
6856 VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
6859 thresh = volume_LRU.promotion_interval[idx];
6860 now = FT_ApproxTime();
6863 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
6864 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6865 promote = (((vp->stats.last_promote + thresh) <= now) &&
6866 (vp->stats.last_get >= vp->stats.last_promote));
6874 /* promote and prepend chain */
6875 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
6889 /* promote and prepend */
6890 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
6894 volume_LRU.q[idx].len -= len;
6895 volume_LRU.q[idx+1].len += len;
6898 /* release exclusive access to the two chains */
6900 volume_LRU.last_promotion[idx] = now;
6901 VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
6902 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
6905 /* run the demotions */
6907 VLRU_Demote_r(int idx)
6910 int len, chaining, demote;
6911 afs_uint32 now, thresh;
6912 struct rx_queue *qp, *nqp;
6913 Volume * vp, *start = NULL, *end = NULL;
6914 Volume ** salv_flag_vec = NULL;
6915 int salv_vec_offset = 0;
6917 assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
6919 /* get exclusive access to two chains, and drop the glock */
6920 VLRU_Wait_r(&volume_LRU.q[idx-1]);
6921 VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
6922 VLRU_Wait_r(&volume_LRU.q[idx]);
6923 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
6926 /* no big deal if this allocation fails */
6927 if (volume_LRU.q[idx].len) {
6928 salv_flag_vec = (Volume **) malloc(volume_LRU.q[idx].len * sizeof(Volume *));
6931 now = FT_ApproxTime();
6932 thresh = volume_LRU.promotion_interval[idx-1];
6935 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
6936 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6937 demote = (((vp->stats.last_promote + thresh) <= now) &&
6938 (vp->stats.last_get < (now - thresh)));
6940 /* we now do volume update list DONT_SALVAGE flag setting during
6941 * demotion passes */
6942 if (salv_flag_vec &&
6943 !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
6945 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
6946 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
6947 salv_flag_vec[salv_vec_offset++] = vp;
6948 VCreateReservation_r(vp);
6957 /* demote and append chain */
6958 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
6972 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
6976 volume_LRU.q[idx].len -= len;
6977 volume_LRU.q[idx-1].len += len;
6980 /* release exclusive access to the two chains */
6982 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
6983 VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
6985 /* now go back and set the DONT_SALVAGE flags as appropriate */
6986 if (salv_flag_vec) {
6988 for (i = 0; i < salv_vec_offset; i++) {
6989 vp = salv_flag_vec[i];
6990 if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
6991 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
6992 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
6995 V_attachFlags(vp) |= VOL_HDR_DONTSALV;
6996 V_dontSalvage(vp) = DONT_SALVAGE;
6997 VUpdateVolume_r(&ec, vp, 0);
7001 VCancelReservation_r(vp);
7003 free(salv_flag_vec);
7007 /* run a pass of the VLRU GC scanner */
7009 VLRU_Scan_r(int idx)
7011 afs_uint32 now, thresh;
7012 struct rx_queue *qp, *nqp;
7016 assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
7018 /* gain exclusive access to the idx VLRU */
7019 VLRU_Wait_r(&volume_LRU.q[idx]);
7020 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7022 if (idx != VLRU_QUEUE_CANDIDATE) {
7023 /* gain exclusive access to the candidate VLRU */
7024 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7025 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7028 now = FT_ApproxTime();
7029 thresh = now - VLRU_offline_thresh;
7031 /* perform candidate selection and soft detaching */
7032 if (idx == VLRU_QUEUE_CANDIDATE) {
7033 /* soft detach some volumes from the candidate pool */
7037 for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7038 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7039 if (i >= VLRU_offline_max) {
7042 /* check timestamp to see if it's a candidate for soft detaching */
7043 if (vp->stats.last_get <= thresh) {
7045 if (VCheckSoftDetach(vp, thresh))
7051 /* scan for volumes to become soft detach candidates */
7052 for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
7053 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7055 /* check timestamp to see if it's a candidate for soft detaching */
7056 if (vp->stats.last_get <= thresh) {
7057 VCheckSoftDetachCandidate(vp, thresh);
7060 if (!(i&0x7f)) { /* lock coarsening optimization */
7068 /* relinquish exclusive access to the VLRU chains */
7072 volume_LRU.last_scan[idx] = now;
7073 if (idx != VLRU_QUEUE_CANDIDATE) {
7074 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7076 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7079 /* check whether volume is safe to soft detach
7080 * caller MUST NOT hold a ref count on vp */
7082 VCheckSoftDetach(Volume * vp, afs_uint32 thresh)
7086 if (vp->nUsers || vp->nWaiters)
7089 if (vp->stats.last_get <= thresh) {
7090 ret = VSoftDetachVolume_r(vp, thresh);
7096 /* check whether volume should be made a
7097 * soft detach candidate */
7099 VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh)
7102 if (vp->nUsers || vp->nWaiters)
7107 assert(idx == VLRU_QUEUE_NEW);
7109 if (vp->stats.last_get <= thresh) {
7110 /* move to candidate pool */
7111 queue_Remove(&vp->vlru);
7112 volume_LRU.q[VLRU_QUEUE_NEW].len--;
7113 queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
7114 vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
7115 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
7123 /* begin exclusive access on VLRU */
7125 VLRU_BeginExclusive_r(struct VLRU_q * q)
7127 assert(q->busy == 0);
7131 /* end exclusive access on VLRU */
7133 VLRU_EndExclusive_r(struct VLRU_q * q)
7137 assert(pthread_cond_broadcast(&q->cv) == 0);
7140 /* wait for another thread to end exclusive access on VLRU */
7142 VLRU_Wait_r(struct VLRU_q * q)
7145 VOL_CV_WAIT(&q->cv);
7150 * volume soft detach
7152 * caller MUST NOT hold a ref count on vp */
7154 VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh)
7159 assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7161 ts_save = vp->stats.last_get;
7162 if (ts_save > thresh)
7165 if (vp->nUsers || vp->nWaiters)
7168 if (VIsExclusiveState(V_attachState(vp))) {
7172 switch (V_attachState(vp)) {
7173 case VOL_STATE_UNATTACHED:
7174 case VOL_STATE_PREATTACHED:
7175 case VOL_STATE_ERROR:
7176 case VOL_STATE_GOING_OFFLINE:
7177 case VOL_STATE_SHUTTING_DOWN:
7178 case VOL_STATE_SALVAGING:
7179 volume_LRU.q[vp->vlru.idx].len--;
7181 /* create and cancel a reservation to
7182 * give the volume an opportunity to
7184 VCreateReservation_r(vp);
7185 queue_Remove(&vp->vlru);
7186 vp->vlru.idx = VLRU_QUEUE_INVALID;
7187 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7188 VCancelReservation_r(vp);
7194 /* hold the volume and take it offline.
7195 * no need for reservations, as VHold_r
7196 * takes care of that internally. */
7197 if (VHold_r(vp) == 0) {
7198 /* vhold drops the glock, so now we should
7199 * check to make sure we aren't racing against
7200 * other threads. if we are racing, offlining vp
7201 * would be wasteful, and block the scanner for a while
7205 (vp->shuttingDown) ||
7206 (vp->goingOffline) ||
7207 (vp->stats.last_get != ts_save)) {
7208 /* looks like we're racing someone else. bail */
7212 /* pull it off the VLRU */
7213 assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7214 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
7215 queue_Remove(&vp->vlru);
7216 vp->vlru.idx = VLRU_QUEUE_INVALID;
7217 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7219 /* take if offline */
7220 VOffline_r(vp, "volume has been soft detached");
7222 /* invalidate the volume header cache */
7223 FreeVolumeHeader(vp);
7226 IncUInt64(&VStats.soft_detaches);
7227 vp->stats.soft_detaches++;
7229 /* put in pre-attached state so demand
7230 * attacher can work on it */
7231 VChangeState_r(vp, VOL_STATE_PREATTACHED);
7237 #endif /* AFS_DEMAND_ATTACH_FS */
7240 /***************************************************/
7241 /* Volume Header Cache routines */
7242 /***************************************************/
7245 * volume header cache.
7247 struct volume_hdr_LRU_t volume_hdr_LRU;
7250 * initialize the volume header cache.
7252 * @param[in] howMany number of header cache entries to preallocate
7254 * @pre VOL_LOCK held. Function has never been called before.
7256 * @post howMany cache entries are allocated, initialized, and added
7257 * to the LRU list. Header cache statistics are initialized.
7259 * @note only applicable to fileServer program type. Should only be
7260 * called once during volume package initialization.
7262 * @internal volume package internal use only.
7265 VInitVolumeHeaderCache(afs_uint32 howMany)
7267 register struct volHeader *hp;
7268 if (programType != fileServer)
7270 queue_Init(&volume_hdr_LRU);
7271 volume_hdr_LRU.stats.free = 0;
7272 volume_hdr_LRU.stats.used = howMany;
7273 volume_hdr_LRU.stats.attached = 0;
7274 hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
7278 /* We are using ReleaseVolumeHeader to initialize the values on the header list
7279 * to ensure they have the right values
7281 ReleaseVolumeHeader(hp++);
7285 * get a volume header and attach it to the volume object.
7287 * @param[in] vp pointer to volume object
7289 * @return cache entry status
7290 * @retval 0 volume header was newly attached; cache data is invalid
7291 * @retval 1 volume header was previously attached; cache data is valid
7293 * @pre VOL_LOCK held. For DAFS, lightweight ref must be held on volume object.
7295 * @post volume header attached to volume object. if necessary, header cache
7296 * entry on LRU is synchronized to disk. Header is removed from LRU list.
7298 * @note VOL_LOCK may be dropped
7300 * @warning this interface does not load header data from disk. it merely
7301 * attaches a header object to the volume object, and may sync the old
7302 * header cache data out to disk in the process.
7304 * @internal volume package internal use only.
7307 GetVolumeHeader(register Volume * vp)
7310 register struct volHeader *hd;
7312 static int everLogged = 0;
7314 #ifdef AFS_DEMAND_ATTACH_FS
7315 VolState vp_save = 0, back_save = 0;
7317 /* XXX debug 9/19/05 we've apparently got
7318 * a ref counting bug somewhere that's
7319 * breaking the nUsers == 0 => header on LRU
7321 if (vp->header && queue_IsNotOnQueue(vp->header)) {
7322 Log("nUsers == 0, but header not on LRU\n");
7327 old = (vp->header != NULL); /* old == volume already has a header */
7329 if (programType != fileServer) {
7330 /* for volume utilities, we allocate volHeaders as needed */
7332 hd = (struct volHeader *)calloc(1, sizeof(*vp->header));
7336 #ifdef AFS_DEMAND_ATTACH_FS
7337 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
7341 /* for the fileserver, we keep a volume header cache */
7343 /* the header we previously dropped in the lru is
7344 * still available. pull it off the lru and return */
7347 assert(hd->back == vp);
7348 #ifdef AFS_DEMAND_ATTACH_FS
7349 V_attachFlags(vp) &= ~(VOL_HDR_IN_LRU);
7352 /* we need to grab a new element off the LRU */
7353 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
7354 /* grab an element and pull off of LRU */
7355 hd = queue_First(&volume_hdr_LRU, volHeader);
7358 /* LRU is empty, so allocate a new volHeader
7359 * this is probably indicative of a leak, so let the user know */
7360 hd = (struct volHeader *)calloc(1, sizeof(struct volHeader));
7363 Log("****Allocated more volume headers, probably leak****\n");
7366 volume_hdr_LRU.stats.free++;
7369 /* this header used to belong to someone else.
7370 * we'll need to check if the header needs to
7371 * be sync'd out to disk */
7373 #ifdef AFS_DEMAND_ATTACH_FS
7374 /* if hd->back were in an exclusive state, then
7375 * its volHeader would not be on the LRU... */
7376 assert(!VIsExclusiveState(V_attachState(hd->back)));
7379 if (hd->diskstuff.inUse) {
7380 /* volume was in use, so we'll need to sync
7381 * its header to disk */
7383 #ifdef AFS_DEMAND_ATTACH_FS
7384 back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
7385 vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
7386 VCreateReservation_r(hd->back);
7390 WriteVolumeHeader_r(&error, hd->back);
7391 /* Ignore errors; catch them later */
7393 #ifdef AFS_DEMAND_ATTACH_FS
7398 hd->back->header = NULL;
7399 #ifdef AFS_DEMAND_ATTACH_FS
7400 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
7402 if (hd->diskstuff.inUse) {
7403 VChangeState_r(hd->back, back_save);
7404 VCancelReservation_r(hd->back);
7405 VChangeState_r(vp, vp_save);
7409 volume_hdr_LRU.stats.attached++;
7413 #ifdef AFS_DEMAND_ATTACH_FS
7414 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
7417 volume_hdr_LRU.stats.free--;
7418 volume_hdr_LRU.stats.used++;
7420 IncUInt64(&VStats.hdr_gets);
7421 #ifdef AFS_DEMAND_ATTACH_FS
7422 IncUInt64(&vp->stats.hdr_gets);
7423 vp->stats.last_hdr_get = FT_ApproxTime();
7430 * make sure volume header is attached and contains valid cache data.
7432 * @param[out] ec outbound error code
7433 * @param[in] vp pointer to volume object
7435 * @pre VOL_LOCK held. For DAFS, lightweight ref held on vp.
7437 * @post header cache entry attached, and loaded with valid data, or
7438 * *ec is nonzero, and the header is released back into the LRU.
7440 * @internal volume package internal use only.
7443 LoadVolumeHeader(Error * ec, Volume * vp)
7445 #ifdef AFS_DEMAND_ATTACH_FS
7446 VolState state_save;
7450 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
7451 IncUInt64(&VStats.hdr_loads);
7452 state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
7455 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
7456 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
7458 IncUInt64(&vp->stats.hdr_loads);
7459 now = FT_ApproxTime();
7463 V_attachFlags(vp) |= VOL_HDR_LOADED;
7464 vp->stats.last_hdr_load = now;
7466 VChangeState_r(vp, state_save);
7468 #else /* AFS_DEMAND_ATTACH_FS */
7470 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
7471 IncUInt64(&VStats.hdr_loads);
7473 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
7474 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
7477 #endif /* AFS_DEMAND_ATTACH_FS */
7479 /* maintain (nUsers==0) => header in LRU invariant */
7480 FreeVolumeHeader(vp);
7485 * release a header cache entry back into the LRU list.
7487 * @param[in] hd pointer to volume header cache object
7489 * @pre VOL_LOCK held.
7491 * @post header cache object appended onto end of LRU list.
7493 * @note only applicable to fileServer program type.
7495 * @note used to place a header cache entry back into the
7496 * LRU pool without invalidating it as a cache entry.
7498 * @internal volume package internal use only.
7501 ReleaseVolumeHeader(register struct volHeader *hd)
7503 if (programType != fileServer)
7505 if (!hd || queue_IsOnQueue(hd)) /* no header, or header already released */
7507 queue_Append(&volume_hdr_LRU, hd);
7508 #ifdef AFS_DEMAND_ATTACH_FS
7510 V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
7513 volume_hdr_LRU.stats.free++;
7514 volume_hdr_LRU.stats.used--;
7518 * free/invalidate a volume header cache entry.
7520 * @param[in] vp pointer to volume object
7522 * @pre VOL_LOCK is held.
7524 * @post For fileserver, header cache entry is returned to LRU, and it is
7525 * invalidated as a cache entry. For volume utilities, the header
7526 * cache entry is freed.
7528 * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
7529 * whenever it is necessary to invalidate the header cache entry.
7531 * @see ReleaseVolumeHeader
7533 * @internal volume package internal use only.
7536 FreeVolumeHeader(register Volume * vp)
7538 register struct volHeader *hd = vp->header;
7541 if (programType == fileServer) {
7542 ReleaseVolumeHeader(hd);
7547 #ifdef AFS_DEMAND_ATTACH_FS
7548 V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
7550 volume_hdr_LRU.stats.attached--;
7555 /***************************************************/
7556 /* Volume Hash Table routines */
7557 /***************************************************/
7560 * set size of volume object hash table.
7562 * @param[in] logsize log(2) of desired hash table size
7564 * @return operation status
7566 * @retval -1 failure
7568 * @pre MUST be called prior to VInitVolumePackage2
7570 * @post Volume Hash Table will have 2^logsize buckets
7573 VSetVolHashSize(int logsize)
7575 /* 64 to 16384 hash buckets seems like a reasonable range */
7576 if ((logsize < 6 ) || (logsize > 14)) {
7581 VolumeHashTable.Size = 1 << logsize;
7582 VolumeHashTable.Mask = VolumeHashTable.Size - 1;
7584 /* we can't yet support runtime modification of this
7585 * parameter. we'll need a configuration rwlock to
7586 * make runtime modification feasible.... */
7593 * initialize dynamic data structures for volume hash table.
7595 * @post hash table is allocated, and fields are initialized.
7597 * @internal volume package internal use only.
7600 VInitVolumeHash(void)
7604 VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
7605 sizeof(VolumeHashChainHead));
7606 assert(VolumeHashTable.Table != NULL);
7608 for (i=0; i < VolumeHashTable.Size; i++) {
7609 queue_Init(&VolumeHashTable.Table[i]);
7610 #ifdef AFS_DEMAND_ATTACH_FS
7611 assert(pthread_cond_init(&VolumeHashTable.Table[i].chain_busy_cv, NULL) == 0);
7612 #endif /* AFS_DEMAND_ATTACH_FS */
7617 * add a volume object to the hash table.
7619 * @param[in] vp pointer to volume object
7620 * @param[in] hashid hash of volume id
7622 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
7625 * @post volume is added to hash chain.
7627 * @internal volume package internal use only.
7629 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
7630 * asynchronous hash chain reordering to finish.
7633 AddVolumeToHashTable(register Volume * vp, int hashid)
7635 VolumeHashChainHead * head;
7637 if (queue_IsOnQueue(vp))
7640 head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
7642 #ifdef AFS_DEMAND_ATTACH_FS
7643 /* wait for the hash chain to become available */
7646 V_attachFlags(vp) |= VOL_IN_HASH;
7647 vp->chainCacheCheck = ++head->cacheCheck;
7648 #endif /* AFS_DEMAND_ATTACH_FS */
7651 vp->hashid = hashid;
7652 queue_Append(head, vp);
7653 vp->vnodeHashOffset = VolumeHashOffset_r();
7657 * delete a volume object from the hash table.
7659 * @param[in] vp pointer to volume object
7661 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
7664 * @post volume is removed from hash chain.
7666 * @internal volume package internal use only.
7668 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
7669 * asynchronous hash chain reordering to finish.
7672 DeleteVolumeFromHashTable(register Volume * vp)
7674 VolumeHashChainHead * head;
7676 if (!queue_IsOnQueue(vp))
7679 head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
7681 #ifdef AFS_DEMAND_ATTACH_FS
7682 /* wait for the hash chain to become available */
7685 V_attachFlags(vp) &= ~(VOL_IN_HASH);
7687 #endif /* AFS_DEMAND_ATTACH_FS */
7691 /* do NOT reset hashid to zero, as the online
7692 * salvager package may need to know the volume id
7693 * after the volume is removed from the hash */
7697 * lookup a volume object in the hash table given a volume id.
7699 * @param[out] ec error code return
7700 * @param[in] volumeId volume id
7701 * @param[in] hint volume object which we believe could be the correct
7704 * @return volume object pointer
7705 * @retval NULL no such volume id is registered with the hash table.
7707 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
7710 * @post volume object with the given id is returned. volume object and
7711 * hash chain access statistics are updated. hash chain may have
7714 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
7715 * asynchronous hash chain reordering operation to finish, or
7716 * in order for us to perform an asynchronous chain reordering.
7718 * @note Hash chain reorderings occur when the access count for the
7719 * volume object being looked up exceeds the sum of the previous
7720 * node's (the node ahead of it in the hash chain linked list)
7721 * access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
7723 * @note For DAFS, the hint parameter allows us to short-circuit if the
7724 * cacheCheck fields match between the hash chain head and the
7725 * hint volume object.
7728 VLookupVolume_r(Error * ec, VolId volumeId, Volume * hint)
7730 register int looks = 0;
7732 #ifdef AFS_DEMAND_ATTACH_FS
7735 VolumeHashChainHead * head;
7738 head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
7740 #ifdef AFS_DEMAND_ATTACH_FS
7741 /* wait for the hash chain to become available */
7744 /* check to see if we can short circuit without walking the hash chain */
7745 if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
7746 IncUInt64(&hint->stats.hash_short_circuits);
7749 #endif /* AFS_DEMAND_ATTACH_FS */
7751 /* someday we need to either do per-chain locks, RWlocks,
7752 * or both for volhash access.
7753 * (and move to a data structure with better cache locality) */
7755 /* search the chain for this volume id */
7756 for(queue_Scan(head, vp, np, Volume)) {
7758 if ((vp->hashid == volumeId)) {
7763 if (queue_IsEnd(head, vp)) {
7767 #ifdef AFS_DEMAND_ATTACH_FS
7768 /* update hash chain statistics */
7771 FillInt64(lks, 0, looks);
7772 AddUInt64(head->looks, lks, &head->looks);
7773 AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
7774 IncUInt64(&head->gets);
7779 IncUInt64(&vp->stats.hash_lookups);
7781 /* for demand attach fileserver, we permit occasional hash chain reordering
7782 * so that frequently looked up volumes move towards the head of the chain */
7783 pp = queue_Prev(vp, Volume);
7784 if (!queue_IsEnd(head, pp)) {
7785 FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
7786 AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
7787 if (GEInt64(vp->stats.hash_lookups, thresh)) {
7788 VReorderHash_r(head, pp, vp);
7792 /* update the short-circuit cache check */
7793 vp->chainCacheCheck = head->cacheCheck;
7795 #endif /* AFS_DEMAND_ATTACH_FS */
7800 #ifdef AFS_DEMAND_ATTACH_FS
7801 /* perform volume hash chain reordering.
7803 * advance a subchain beginning at vp ahead of
7804 * the adjacent subchain ending at pp */
7806 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
7808 Volume *tp, *np, *lp;
7809 afs_uint64 move_thresh;
7811 /* this should never be called if the chain is already busy, so
7812 * no need to wait for other exclusive chain ops to finish */
7814 /* this is a rather heavy set of operations,
7815 * so let's set the chain busy flag and drop
7817 VHashBeginExclusive_r(head);
7820 /* scan forward in the chain from vp looking for the last element
7821 * in the chain we want to advance */
7822 FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
7823 AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
7824 for(queue_ScanFrom(head, vp, tp, np, Volume)) {
7825 if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
7829 lp = queue_Prev(tp, Volume);
7831 /* scan backwards from pp to determine where to splice and
7832 * insert the subchain we're advancing */
7833 for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
7834 if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
7838 tp = queue_Next(tp, Volume);
7840 /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
7841 queue_MoveChainBefore(tp,vp,lp);
7844 IncUInt64(&VStats.hash_reorders);
7846 IncUInt64(&head->reorders);
7848 /* wake up any threads waiting for the hash chain */
7849 VHashEndExclusive_r(head);
7853 /* demand-attach fs volume hash
7854 * asynchronous exclusive operations */
7857 * begin an asynchronous exclusive operation on a volume hash chain.
7859 * @param[in] head pointer to volume hash chain head object
7861 * @pre VOL_LOCK held. hash chain is quiescent.
7863 * @post hash chain marked busy.
7865 * @note this interface is used in conjunction with VHashEndExclusive_r and
7866 * VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
7867 * volume hash chain. Its main use case is hash chain reordering, which
7868 * has the potential to be a highly latent operation.
7870 * @see VHashEndExclusive_r
7875 * @internal volume package internal use only.
7878 VHashBeginExclusive_r(VolumeHashChainHead * head)
7880 assert(head->busy == 0);
7885 * relinquish exclusive ownership of a volume hash chain.
7887 * @param[in] head pointer to volume hash chain head object
7889 * @pre VOL_LOCK held. thread owns the hash chain exclusively.
7891 * @post hash chain is marked quiescent. threads awaiting use of
7892 * chain are awakened.
7894 * @see VHashBeginExclusive_r
7899 * @internal volume package internal use only.
7902 VHashEndExclusive_r(VolumeHashChainHead * head)
7906 assert(pthread_cond_broadcast(&head->chain_busy_cv) == 0);
7910 * wait for all asynchronous operations on a hash chain to complete.
7912 * @param[in] head pointer to volume hash chain head object
7914 * @pre VOL_LOCK held.
7916 * @post hash chain object is quiescent.
7918 * @see VHashBeginExclusive_r
7919 * @see VHashEndExclusive_r
7923 * @note This interface should be called before any attempt to
7924 * traverse the hash chain. It is permissible for a thread
7925 * to gain exclusive access to the chain, and then perform
7926 * latent operations on the chain asynchronously wrt the
7929 * @warning if waiting is necessary, VOL_LOCK is dropped
7931 * @internal volume package internal use only.
7934 VHashWait_r(VolumeHashChainHead * head)
7936 while (head->busy) {
7937 VOL_CV_WAIT(&head->chain_busy_cv);
7940 #endif /* AFS_DEMAND_ATTACH_FS */
7943 /***************************************************/
7944 /* Volume by Partition List routines */
7945 /***************************************************/
7948 * demand attach fileserver adds a
7949 * linked list of volumes to each
7950 * partition object, thus allowing
7951 * for quick enumeration of all
7952 * volumes on a partition
7955 #ifdef AFS_DEMAND_ATTACH_FS
7957 * add a volume to its disk partition VByPList.
7959 * @param[in] vp pointer to volume object
7961 * @pre either the disk partition VByPList is owned exclusively
7962 * by the calling thread, or the list is quiescent and
7965 * @post volume is added to disk partition VByPList
7969 * @warning it is the caller's responsibility to ensure list
7972 * @see VVByPListWait_r
7973 * @see VVByPListBeginExclusive_r
7974 * @see VVByPListEndExclusive_r
7976 * @internal volume package internal use only.
7979 AddVolumeToVByPList_r(Volume * vp)
7981 if (queue_IsNotOnQueue(&vp->vol_list)) {
7982 queue_Append(&vp->partition->vol_list, &vp->vol_list);
7983 V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
7984 vp->partition->vol_list.len++;
7989 * delete a volume from its disk partition VByPList.
7991 * @param[in] vp pointer to volume object
7993 * @pre either the disk partition VByPList is owned exclusively
7994 * by the calling thread, or the list is quiescent and
7997 * @post volume is removed from the disk partition VByPList
8001 * @warning it is the caller's responsibility to ensure list
8004 * @see VVByPListWait_r
8005 * @see VVByPListBeginExclusive_r
8006 * @see VVByPListEndExclusive_r
8008 * @internal volume package internal use only.
8011 DeleteVolumeFromVByPList_r(Volume * vp)
8013 if (queue_IsOnQueue(&vp->vol_list)) {
8014 queue_Remove(&vp->vol_list);
8015 V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
8016 vp->partition->vol_list.len--;
8021 * begin an asynchronous exclusive operation on a VByPList.
8023 * @param[in] dp pointer to disk partition object
8025 * @pre VOL_LOCK held. VByPList is quiescent.
8027 * @post VByPList marked busy.
8029 * @note this interface is used in conjunction with VVByPListEndExclusive_r and
8030 * VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8033 * @see VVByPListEndExclusive_r
8034 * @see VVByPListWait_r
8038 * @internal volume package internal use only.
8040 /* take exclusive control over the list */
8042 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
8044 assert(dp->vol_list.busy == 0);
8045 dp->vol_list.busy = 1;
8049 * relinquish exclusive ownership of a VByPList.
8051 * @param[in] dp pointer to disk partition object
8053 * @pre VOL_LOCK held. thread owns the VByPList exclusively.
8055 * @post VByPList is marked quiescent. threads awaiting use of
8056 * the list are awakened.
8058 * @see VVByPListBeginExclusive_r
8059 * @see VVByPListWait_r
8063 * @internal volume package internal use only.
8066 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
8068 assert(dp->vol_list.busy);
8069 dp->vol_list.busy = 0;
8070 assert(pthread_cond_broadcast(&dp->vol_list.cv) == 0);
8074 * wait for all asynchronous operations on a VByPList to complete.
8076 * @param[in] dp pointer to disk partition object
8078 * @pre VOL_LOCK is held.
8080 * @post disk partition's VByP list is quiescent
8084 * @note This interface should be called before any attempt to
8085 * traverse the VByPList. It is permissible for a thread
8086 * to gain exclusive access to the list, and then perform
8087 * latent operations on the list asynchronously wrt the
8090 * @warning if waiting is necessary, VOL_LOCK is dropped
8092 * @see VVByPListEndExclusive_r
8093 * @see VVByPListBeginExclusive_r
8095 * @internal volume package internal use only.
8098 VVByPListWait_r(struct DiskPartition64 * dp)
8100 while (dp->vol_list.busy) {
8101 VOL_CV_WAIT(&dp->vol_list.cv);
8104 #endif /* AFS_DEMAND_ATTACH_FS */
8106 /***************************************************/
8107 /* Volume Cache Statistics routines */
8108 /***************************************************/
8111 VPrintCacheStats_r(void)
8113 afs_uint32 get_hi, get_lo, load_hi, load_lo;
8114 register struct VnodeClassInfo *vcp;
8115 vcp = &VnodeClassInfo[vLarge];
8116 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);
8117 vcp = &VnodeClassInfo[vSmall];
8118 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);
8119 SplitInt64(VStats.hdr_gets, get_hi, get_lo);
8120 SplitInt64(VStats.hdr_loads, load_hi, load_lo);
8121 Log("Volume header cache, %d entries, %d gets, %d replacements\n",
8122 VStats.hdr_cache_size, get_lo, load_lo);
8126 VPrintCacheStats(void)
8129 VPrintCacheStats_r();
8133 #ifdef AFS_DEMAND_ATTACH_FS
8135 UInt64ToDouble(afs_uint64 * x)
8137 static double c32 = 4.0 * 1.073741824 * 1000000000.0;
8139 SplitInt64(*x, h, l);
8140 return (((double)h) * c32) + ((double) l);
8144 DoubleToPrintable(double x, char * buf, int len)
8146 static double billion = 1000000000.0;
8149 y[0] = (afs_uint32) (x / (billion * billion));
8150 y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
8151 y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
8154 snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
8156 snprintf(buf, len, "%d%09d", y[1], y[2]);
8158 snprintf(buf, len, "%d", y[2]);
8164 struct VLRUExtStatsEntry {
8168 struct VLRUExtStats {
8174 } queue_info[VLRU_QUEUE_INVALID];
8175 struct VLRUExtStatsEntry * vec;
8179 * add a 256-entry fudge factor onto the vector in case state changes
8180 * out from under us.
8182 #define VLRU_EXT_STATS_VEC_LEN_FUDGE 256
8185 * collect extended statistics for the VLRU subsystem.
8187 * @param[out] stats pointer to stats structure to be populated
8188 * @param[in] nvols number of volumes currently known to exist
8190 * @pre VOL_LOCK held
8192 * @post stats->vec allocated and populated
8194 * @return operation status
8199 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
8201 afs_uint32 cur, idx, len;
8202 struct rx_queue * qp, * nqp;
8204 struct VLRUExtStatsEntry * vec;
8206 len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
8207 vec = stats->vec = calloc(len,
8208 sizeof(struct VLRUExtStatsEntry));
8214 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
8215 VLRU_Wait_r(&volume_LRU.q[idx]);
8216 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
8219 stats->queue_info[idx].start = cur;
8221 for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
8223 /* out of space in vec */
8226 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
8227 vec[cur].volid = vp->hashid;
8231 stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
8234 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
8242 #define ENUMTOSTRING(en) #en
8243 #define ENUMCASE(en) \
8245 return ENUMTOSTRING(en); \
8249 vlru_idx_to_string(int idx)
8252 ENUMCASE(VLRU_QUEUE_NEW);
8253 ENUMCASE(VLRU_QUEUE_MID);
8254 ENUMCASE(VLRU_QUEUE_OLD);
8255 ENUMCASE(VLRU_QUEUE_CANDIDATE);
8256 ENUMCASE(VLRU_QUEUE_HELD);
8257 ENUMCASE(VLRU_QUEUE_INVALID);
8259 return "**UNKNOWN**";
8264 VPrintExtendedCacheStats_r(int flags)
8267 afs_uint32 vol_sum = 0;
8274 struct stats looks, gets, reorders, len;
8275 struct stats ch_looks, ch_gets, ch_reorders;
8277 VolumeHashChainHead *head;
8279 struct VLRUExtStats vlru_stats;
8281 /* zero out stats */
8282 memset(&looks, 0, sizeof(struct stats));
8283 memset(&gets, 0, sizeof(struct stats));
8284 memset(&reorders, 0, sizeof(struct stats));
8285 memset(&len, 0, sizeof(struct stats));
8286 memset(&ch_looks, 0, sizeof(struct stats));
8287 memset(&ch_gets, 0, sizeof(struct stats));
8288 memset(&ch_reorders, 0, sizeof(struct stats));
8290 for (i = 0; i < VolumeHashTable.Size; i++) {
8291 head = &VolumeHashTable.Table[i];
8294 VHashBeginExclusive_r(head);
8297 ch_looks.sum = UInt64ToDouble(&head->looks);
8298 ch_gets.sum = UInt64ToDouble(&head->gets);
8299 ch_reorders.sum = UInt64ToDouble(&head->reorders);
8301 /* update global statistics */
8303 looks.sum += ch_looks.sum;
8304 gets.sum += ch_gets.sum;
8305 reorders.sum += ch_reorders.sum;
8306 len.sum += (double)head->len;
8307 vol_sum += head->len;
8310 len.min = (double) head->len;
8311 len.max = (double) head->len;
8312 looks.min = ch_looks.sum;
8313 looks.max = ch_looks.sum;
8314 gets.min = ch_gets.sum;
8315 gets.max = ch_gets.sum;
8316 reorders.min = ch_reorders.sum;
8317 reorders.max = ch_reorders.sum;
8319 if (((double)head->len) < len.min)
8320 len.min = (double) head->len;
8321 if (((double)head->len) > len.max)
8322 len.max = (double) head->len;
8323 if (ch_looks.sum < looks.min)
8324 looks.min = ch_looks.sum;
8325 else if (ch_looks.sum > looks.max)
8326 looks.max = ch_looks.sum;
8327 if (ch_gets.sum < gets.min)
8328 gets.min = ch_gets.sum;
8329 else if (ch_gets.sum > gets.max)
8330 gets.max = ch_gets.sum;
8331 if (ch_reorders.sum < reorders.min)
8332 reorders.min = ch_reorders.sum;
8333 else if (ch_reorders.sum > reorders.max)
8334 reorders.max = ch_reorders.sum;
8338 if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
8339 /* compute detailed per-chain stats */
8340 struct stats hdr_loads, hdr_gets;
8341 double v_looks, v_loads, v_gets;
8343 /* initialize stats with data from first element in chain */
8344 vp = queue_First(head, Volume);
8345 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
8346 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
8347 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
8348 ch_gets.min = ch_gets.max = v_looks;
8349 hdr_loads.min = hdr_loads.max = v_loads;
8350 hdr_gets.min = hdr_gets.max = v_gets;
8351 hdr_loads.sum = hdr_gets.sum = 0;
8353 vp = queue_Next(vp, Volume);
8355 /* pull in stats from remaining elements in chain */
8356 for (queue_ScanFrom(head, vp, vp, np, Volume)) {
8357 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
8358 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
8359 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
8361 hdr_loads.sum += v_loads;
8362 hdr_gets.sum += v_gets;
8364 if (v_looks < ch_gets.min)
8365 ch_gets.min = v_looks;
8366 else if (v_looks > ch_gets.max)
8367 ch_gets.max = v_looks;
8369 if (v_loads < hdr_loads.min)
8370 hdr_loads.min = v_loads;
8371 else if (v_loads > hdr_loads.max)
8372 hdr_loads.max = v_loads;
8374 if (v_gets < hdr_gets.min)
8375 hdr_gets.min = v_gets;
8376 else if (v_gets > hdr_gets.max)
8377 hdr_gets.max = v_gets;
8380 /* compute per-chain averages */
8381 ch_gets.avg = ch_gets.sum / ((double)head->len);
8382 hdr_loads.avg = hdr_loads.sum / ((double)head->len);
8383 hdr_gets.avg = hdr_gets.sum / ((double)head->len);
8385 /* dump per-chain stats */
8386 Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
8388 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
8389 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
8390 Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
8391 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
8392 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
8393 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
8394 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
8395 Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
8396 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
8397 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
8398 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
8399 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
8400 Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
8401 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
8402 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
8403 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
8404 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
8405 } else if (flags & VOL_STATS_PER_CHAIN) {
8406 /* dump simple per-chain stats */
8407 Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
8409 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
8410 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
8411 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
8415 VHashEndExclusive_r(head);
8420 /* compute global averages */
8421 len.avg = len.sum / ((double)VolumeHashTable.Size);
8422 looks.avg = looks.sum / ((double)VolumeHashTable.Size);
8423 gets.avg = gets.sum / ((double)VolumeHashTable.Size);
8424 reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
8426 /* dump global stats */
8427 Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
8428 Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
8429 DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
8430 DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
8431 DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
8432 DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
8433 Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
8434 DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
8435 DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
8436 DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
8437 DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
8438 Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
8439 DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
8440 DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
8441 DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
8442 DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
8443 Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
8444 DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
8445 DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
8446 DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
8447 DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
8449 /* print extended disk related statistics */
8451 struct DiskPartition64 * diskP;
8452 afs_uint32 vol_count[VOLMAXPARTS+1];
8453 byte part_exists[VOLMAXPARTS+1];
8457 memset(vol_count, 0, sizeof(vol_count));
8458 memset(part_exists, 0, sizeof(part_exists));
8462 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
8464 vol_count[id] = diskP->vol_list.len;
8465 part_exists[id] = 1;
8469 for (i = 0; i <= VOLMAXPARTS; i++) {
8470 if (part_exists[i]) {
8471 /* XXX while this is currently safe, it is a violation
8472 * of the VGetPartitionById_r interface contract. */
8473 diskP = VGetPartitionById_r(i, 0);
8475 Log("Partition %s has %d online volumes\n",
8476 VPartitionPath(diskP), diskP->vol_list.len);
8483 /* print extended VLRU statistics */
8484 if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
8485 afs_uint32 idx, cur, lpos;
8490 Log("VLRU State Dump:\n\n");
8492 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
8493 Log("\t%s:\n", vlru_idx_to_string(idx));
8496 for (cur = vlru_stats.queue_info[idx].start;
8497 cur < vlru_stats.queue_info[idx].len;
8499 line[lpos++] = vlru_stats.vec[cur].volid;
8501 Log("\t\t%u, %u, %u, %u, %u,\n",
8502 line[0], line[1], line[2], line[3], line[4]);
8511 Log("\t\t%u, %u, %u, %u, %u\n",
8512 line[0], line[1], line[2], line[3], line[4]);
8517 free(vlru_stats.vec);
8524 VPrintExtendedCacheStats(int flags)
8527 VPrintExtendedCacheStats_r(flags);
8530 #endif /* AFS_DEMAND_ATTACH_FS */
8533 VCanScheduleSalvage(void)
8535 return vol_opts.canScheduleSalvage;
8541 return vol_opts.canUseFSSYNC;
8545 VCanUseSALVSYNC(void)
8547 return vol_opts.canUseSALVSYNC;
8551 VCanUnsafeAttach(void)
8553 return vol_opts.unsafe_attach;