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>
30 #ifdef HAVE_SYS_FILE_H
34 #ifdef AFS_PTHREAD_ENV
35 # include <opr/lock.h>
37 # include <opr/lockstub.h>
40 #include <afs/afsint.h>
42 #include <rx/rx_queue.h>
45 #if !defined(AFS_SGI_ENV)
48 #else /* AFS_OSF_ENV */
49 #ifdef AFS_VFSINCL_ENV
52 #include <sys/fs/ufs_fs.h>
54 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
55 #include <ufs/ufs/dinode.h>
56 #include <ufs/ffs/fs.h>
61 #else /* AFS_VFSINCL_ENV */
62 #if !defined(AFS_AIX_ENV) && !defined(AFS_LINUX20_ENV) && !defined(AFS_XBSD_ENV) && !defined(AFS_DARWIN_ENV)
65 #endif /* AFS_VFSINCL_ENV */
66 #endif /* AFS_OSF_ENV */
67 #endif /* AFS_SGI_ENV */
68 #endif /* !AFS_NT40_ENV */
76 #if defined(AFS_SUN_ENV) || defined(AFS_SUN5_ENV)
78 #include <sys/mnttab.h>
79 #include <sys/mntent.h>
85 #if defined(AFS_SGI_ENV)
88 #ifndef AFS_LINUX20_ENV
89 #include <fstab.h> /* Need to find in libc 5, present in libc 6 */
92 #endif /* AFS_SGI_ENV */
94 #endif /* AFS_HPUX_ENV */
98 #include <afs/errors.h>
101 #include <afs/afssyscalls.h>
103 #include <afs/afsutil.h>
104 #include "daemon_com.h"
106 #include "salvsync.h"
109 #include "partition.h"
110 #include "volume_inline.h"
115 #ifdef AFS_PTHREAD_ENV
116 pthread_mutex_t vol_glock_mutex;
117 pthread_mutex_t vol_trans_mutex;
118 pthread_cond_t vol_put_volume_cond;
119 pthread_cond_t vol_sleep_cond;
120 pthread_cond_t vol_init_attach_cond;
121 pthread_cond_t vol_vinit_cond;
122 int vol_attach_threads = 1;
123 #endif /* AFS_PTHREAD_ENV */
125 /* start-time configurable I/O parameters */
126 ih_init_params vol_io_params;
128 #ifdef AFS_DEMAND_ATTACH_FS
129 pthread_mutex_t vol_salvsync_mutex;
132 * Set this to 1 to disallow SALVSYNC communication in all threads; used
133 * during shutdown, since the salvageserver may have gone away.
135 static volatile sig_atomic_t vol_disallow_salvsync = 0;
136 #endif /* AFS_DEMAND_ATTACH_FS */
139 * has VShutdown_r been called / is VShutdown_r running?
141 static int vol_shutting_down = 0;
144 extern void *calloc(), *realloc();
147 /* Forward declarations */
148 static Volume *attach2(Error * ec, VolumeId volumeId, char *path,
149 struct DiskPartition64 *partp, Volume * vp,
150 int isbusy, int mode, int *acheckedOut);
151 static void ReallyFreeVolume(Volume * vp);
152 #ifdef AFS_DEMAND_ATTACH_FS
153 static void FreeVolume(Volume * vp);
154 #else /* !AFS_DEMAND_ATTACH_FS */
155 #define FreeVolume(vp) ReallyFreeVolume(vp)
156 static void VScanUpdateList(void);
157 #endif /* !AFS_DEMAND_ATTACH_FS */
158 static void VInitVolumeHeaderCache(afs_uint32 howMany);
159 static int GetVolumeHeader(Volume * vp);
160 static void ReleaseVolumeHeader(struct volHeader *hd);
161 static void FreeVolumeHeader(Volume * vp);
162 static void AddVolumeToHashTable(Volume * vp, VolumeId hashid);
163 static void DeleteVolumeFromHashTable(Volume * vp);
165 static int VHold(Volume * vp);
167 static int VHold_r(Volume * vp);
168 static void VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class);
169 static void VReleaseVolumeHandles_r(Volume * vp);
170 static void VCloseVolumeHandles_r(Volume * vp);
171 static void LoadVolumeHeader(Error * ec, Volume * vp);
172 static int VCheckOffline(Volume * vp);
173 static int VCheckDetach(Volume * vp);
174 static Volume * GetVolume(Error * ec, Error * client_ec, VolumeId volumeId,
175 Volume * hint, const struct timespec *ts);
177 int LogLevel; /* Vice loglevel--not defined as extern so that it will be
178 * defined when not linked with vice, XXXX */
179 ProgramType programType; /* The type of program using the package */
180 static VolumePackageOptions vol_opts;
182 /* extended volume package statistics */
185 #ifdef VOL_LOCK_DEBUG
186 pthread_t vol_glock_holder = 0;
190 /* this parameter needs to be tunable at runtime.
191 * 128 was really inadequate for largish servers -- at 16384 volumes this
192 * puts average chain length at 128, thus an average 65 deref's to find a volptr.
193 * talk about bad spatial locality...
195 * an AVL or splay tree might work a lot better, but we'll just increase
196 * the default hash table size for now
198 #define DEFAULT_VOLUME_HASH_SIZE 256 /* Must be a power of 2!! */
199 #define DEFAULT_VOLUME_HASH_MASK (DEFAULT_VOLUME_HASH_SIZE-1)
200 #define VOLUME_HASH(volumeId) (volumeId&(VolumeHashTable.Mask))
203 * turn volume hash chains into partially ordered lists.
204 * when the threshold is exceeded between two adjacent elements,
205 * perform a chain rebalancing operation.
207 * keep the threshold high in order to keep cache line invalidates
208 * low "enough" on SMPs
210 #define VOLUME_HASH_REORDER_THRESHOLD 200
213 * when possible, don't just reorder single elements, but reorder
214 * entire chains of elements at once. a chain of elements that
215 * exceed the element previous to the pivot by at least CHAIN_THRESH
216 * accesses are moved in front of the chain whose elements have at
217 * least CHAIN_THRESH less accesses than the pivot element
219 #define VOLUME_HASH_REORDER_CHAIN_THRESH (VOLUME_HASH_REORDER_THRESHOLD / 2)
222 * The per volume uniquifier is bumped by 200 and and written to disk
223 * every 200 file creates.
225 #define VOLUME_UPDATE_UNIQUIFIER_BUMP 200
227 #include "rx/rx_queue.h"
230 VolumeHashTable_t VolumeHashTable = {
231 DEFAULT_VOLUME_HASH_SIZE,
232 DEFAULT_VOLUME_HASH_MASK,
237 static void VInitVolumeHash(void);
241 /* This macro is used where an ffs() call does not exist. Was in util/ffs.c */
245 afs_int32 ffs_tmp = x;
249 for (ffs_i = 1;; ffs_i++) {
256 #endif /* !AFS_HAVE_FFS */
258 #ifdef AFS_PTHREAD_ENV
260 * disk partition queue element
262 typedef struct diskpartition_queue_t {
263 struct rx_queue queue; /**< queue header */
264 struct DiskPartition64 *diskP; /**< disk partition table entry */
265 } diskpartition_queue_t;
267 #ifndef AFS_DEMAND_ATTACH_FS
269 typedef struct vinitvolumepackage_thread_t {
270 struct rx_queue queue;
271 pthread_cond_t thread_done_cv;
272 int n_threads_complete;
273 } vinitvolumepackage_thread_t;
274 static void * VInitVolumePackageThread(void * args);
276 #else /* !AFS_DEMAND_ATTTACH_FS */
277 #define VINIT_BATCH_MAX_SIZE 512
280 * disk partition work queue
282 struct partition_queue {
283 struct rx_queue head; /**< diskpartition_queue_t queue */
284 pthread_mutex_t mutex;
289 * volumes parameters for preattach
291 struct volume_init_batch {
292 struct rx_queue queue; /**< queue header */
293 int thread; /**< posting worker thread */
294 int last; /**< indicates thread is done */
295 int size; /**< number of volume ids in batch */
296 Volume *batch[VINIT_BATCH_MAX_SIZE]; /**< volumes ids to preattach */
300 * volume parameters work queue
302 struct volume_init_queue {
303 struct rx_queue head; /**< volume_init_batch queue */
304 pthread_mutex_t mutex;
309 * volume init worker thread parameters
311 struct vinitvolumepackage_thread_param {
312 int nthreads; /**< total number of worker threads */
313 int thread; /**< thread number for this worker thread */
314 struct partition_queue *pq; /**< queue partitions to scan */
315 struct volume_init_queue *vq; /**< queue of volume to preattach */
318 static void *VInitVolumePackageThread(void *args);
319 static struct DiskPartition64 *VInitNextPartition(struct partition_queue *pq);
320 static VolumeId VInitNextVolumeId(DIR *dirp);
321 static int VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq);
323 #endif /* !AFS_DEMAND_ATTACH_FS */
324 #endif /* AFS_PTHREAD_ENV */
326 #ifndef AFS_DEMAND_ATTACH_FS
327 static int VAttachVolumesByPartition(struct DiskPartition64 *diskP,
328 int * nAttached, int * nUnattached);
329 #endif /* AFS_DEMAND_ATTACH_FS */
332 #ifdef AFS_DEMAND_ATTACH_FS
333 /* demand attach fileserver extensions */
336 * in the future we will support serialization of VLRU state into the fs_state
339 * these structures are the beginning of that effort
341 struct VLRU_DiskHeader {
342 struct versionStamp stamp; /* magic and structure version number */
343 afs_uint32 mtime; /* time of dump to disk */
344 afs_uint32 num_records; /* number of VLRU_DiskEntry records */
347 struct VLRU_DiskEntry {
348 VolumeId vid; /* volume ID */
349 afs_uint32 idx; /* generation */
350 afs_uint32 last_get; /* timestamp of last get */
353 struct VLRU_StartupQueue {
354 struct VLRU_DiskEntry * entry;
359 typedef struct vshutdown_thread_t {
361 pthread_mutex_t lock;
363 pthread_cond_t master_cv;
365 int n_threads_complete;
367 int schedule_version;
370 byte n_parts_done_pass;
371 byte part_thread_target[VOLMAXPARTS+1];
372 byte part_done_pass[VOLMAXPARTS+1];
373 struct rx_queue * part_pass_head[VOLMAXPARTS+1];
374 int stats[4][VOLMAXPARTS+1];
375 } vshutdown_thread_t;
376 static void * VShutdownThread(void * args);
379 static Volume * VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode);
380 static int VCheckFree(Volume * vp);
383 static void AddVolumeToVByPList_r(Volume * vp);
384 static void DeleteVolumeFromVByPList_r(Volume * vp);
385 static void VVByPListBeginExclusive_r(struct DiskPartition64 * dp);
386 static void VVByPListEndExclusive_r(struct DiskPartition64 * dp);
387 static void VVByPListWait_r(struct DiskPartition64 * dp);
389 /* online salvager */
391 VCHECK_SALVAGE_OK = 0, /**< no pending salvage */
392 VCHECK_SALVAGE_SCHEDULED = 1, /**< salvage has been scheduled */
393 VCHECK_SALVAGE_ASYNC = 2, /**< salvage being scheduled */
394 VCHECK_SALVAGE_DENIED = 3, /**< salvage not scheduled; denied */
395 VCHECK_SALVAGE_FAIL = 4 /**< salvage not scheduled; failed */
397 static int VCheckSalvage(Volume * vp);
398 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
399 static int VScheduleSalvage_r(Volume * vp);
402 /* Volume hash table */
403 static void VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp);
404 static void VHashBeginExclusive_r(VolumeHashChainHead * head);
405 static void VHashEndExclusive_r(VolumeHashChainHead * head);
406 static void VHashWait_r(VolumeHashChainHead * head);
409 static int ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass);
410 static int ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
411 struct rx_queue ** idx);
412 static void ShutdownController(vshutdown_thread_t * params);
413 static void ShutdownCreateSchedule(vshutdown_thread_t * params);
416 static void VLRU_ComputeConstants(void);
417 static void VInitVLRU(void);
418 static void VLRU_Init_Node_r(Volume * vp);
419 static void VLRU_Add_r(Volume * vp);
420 static void VLRU_Delete_r(Volume * vp);
421 static void VLRU_UpdateAccess_r(Volume * vp);
422 static void * VLRU_ScannerThread(void * args);
423 static void VLRU_Scan_r(int idx);
424 static void VLRU_Promote_r(int idx);
425 static void VLRU_Demote_r(int idx);
426 static void VLRU_SwitchQueues(Volume * vp, int new_idx, int append);
429 static int VCheckSoftDetach(Volume * vp, afs_uint32 thresh);
430 static int VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh);
431 static int VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh);
434 pthread_key_t VThread_key;
435 VThreadOptions_t VThread_defaults = {
436 0 /**< allow salvsync */
438 #endif /* AFS_DEMAND_ATTACH_FS */
441 struct Lock vol_listLock; /* Lock obtained when listing volumes:
442 * prevents a volume from being missed
443 * if the volume is attached during a
447 /* Common message used when the volume goes off line */
448 char *VSalvageMessage =
449 "Files in this volume are currently unavailable; call operations";
451 int VInit; /* 0 - uninitialized,
452 * 1 - initialized but not all volumes have been attached,
453 * 2 - initialized and all volumes have been attached,
454 * 3 - initialized, all volumes have been attached, and
455 * VConnectFS() has completed. */
457 static int vinit_attach_abort = 0;
459 bit32 VolumeCacheCheck; /* Incremented everytime a volume goes on line--
460 * used to stamp volume headers and in-core
461 * vnodes. When the volume goes on-line the
462 * vnode will be invalidated
463 * access only with VOL_LOCK held */
468 /***************************************************/
469 /* Startup routines */
470 /***************************************************/
472 #if defined(FAST_RESTART) && defined(AFS_DEMAND_ATTACH_FS)
473 # error FAST_RESTART and DAFS are incompatible. For the DAFS equivalent \
474 of FAST_RESTART, use the -unsafe-nosalvage fileserver argument
478 * assign default values to a VolumePackageOptions struct.
480 * Always call this on a VolumePackageOptions struct first, then set any
481 * specific options you want, then call VInitVolumePackage2.
483 * @param[in] pt caller's program type
484 * @param[out] opts volume package options
487 VOptDefaults(ProgramType pt, VolumePackageOptions *opts)
489 opts->nLargeVnodes = opts->nSmallVnodes = 5;
492 opts->canScheduleSalvage = 0;
493 opts->canUseFSSYNC = 0;
494 opts->canUseSALVSYNC = 0;
496 opts->interrupt_rxcall = NULL;
497 opts->offline_timeout = -1;
498 opts->offline_shutdown_timeout = -1;
499 opts->usage_threshold = 128;
500 opts->usage_rate_limit = 5;
503 opts->unsafe_attach = 1;
504 #else /* !FAST_RESTART */
505 opts->unsafe_attach = 0;
506 #endif /* !FAST_RESTART */
510 opts->canScheduleSalvage = 1;
511 opts->canUseSALVSYNC = 1;
515 opts->canUseFSSYNC = 1;
519 opts->nLargeVnodes = 0;
520 opts->nSmallVnodes = 0;
522 opts->canScheduleSalvage = 1;
523 opts->canUseFSSYNC = 1;
533 * Set VInit to a certain value, and signal waiters.
535 * @param[in] value the value to set VInit to
540 VSetVInit_r(int value)
543 opr_cv_broadcast(&vol_vinit_cond);
547 VLogOfflineTimeout(const char *type, afs_int32 timeout)
553 Log("VInitVolumePackage: Interrupting clients accessing %s "
554 "immediately\n", type);
556 Log("VInitVolumePackage: Interrupting clients accessing %s "
557 "after %ld second%s\n", type, (long)timeout, timeout==1?"":"s");
562 VInitVolumePackage2(ProgramType pt, VolumePackageOptions * opts)
564 int errors = 0; /* Number of errors while finding vice partitions. */
569 #ifndef AFS_PTHREAD_ENV
570 if (opts->offline_timeout != -1 || opts->offline_shutdown_timeout != -1) {
571 Log("VInitVolumePackage: offline_timeout and/or "
572 "offline_shutdown_timeout was specified, but the volume package "
573 "does not support these for LWP builds\n");
577 VLogOfflineTimeout("volumes going offline", opts->offline_timeout);
578 VLogOfflineTimeout("volumes going offline during shutdown",
579 opts->offline_shutdown_timeout);
581 memset(&VStats, 0, sizeof(VStats));
582 VStats.hdr_cache_size = 200;
584 VInitPartitionPackage();
586 #ifdef AFS_DEMAND_ATTACH_FS
587 if (programType == fileServer) {
590 VLRU_SetOptions(VLRU_SET_ENABLED, 0);
592 opr_Verify(pthread_key_create(&VThread_key, NULL) == 0);
595 opr_mutex_init(&vol_glock_mutex);
596 opr_mutex_init(&vol_trans_mutex);
597 opr_cv_init(&vol_put_volume_cond);
598 opr_cv_init(&vol_sleep_cond);
599 opr_cv_init(&vol_init_attach_cond);
600 opr_cv_init(&vol_vinit_cond);
601 #ifndef AFS_PTHREAD_ENV
603 #endif /* AFS_PTHREAD_ENV */
604 Lock_Init(&vol_listLock);
606 srandom(time(0)); /* For VGetVolumeInfo */
608 #ifdef AFS_DEMAND_ATTACH_FS
609 opr_mutex_init(&vol_salvsync_mutex);
610 #endif /* AFS_DEMAND_ATTACH_FS */
612 /* Ok, we have done enough initialization that fileserver can
613 * start accepting calls, even though the volumes may not be
614 * available just yet.
618 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_SERVER)
619 if (programType == salvageServer) {
622 #endif /* AFS_DEMAND_ATTACH_FS */
623 #ifdef FSSYNC_BUILD_SERVER
624 if (programType == fileServer) {
628 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_CLIENT)
629 if (VCanUseSALVSYNC()) {
630 /* establish a connection to the salvager at this point */
631 opr_Verify(VConnectSALV() != 0);
633 #endif /* AFS_DEMAND_ATTACH_FS */
635 if (opts->volcache > VStats.hdr_cache_size)
636 VStats.hdr_cache_size = opts->volcache;
637 VInitVolumeHeaderCache(VStats.hdr_cache_size);
639 VInitVnodes(vLarge, opts->nLargeVnodes);
640 VInitVnodes(vSmall, opts->nSmallVnodes);
643 errors = VAttachPartitions();
647 if (programType != fileServer) {
648 errors = VInitAttachVolumes(programType);
654 #ifdef FSSYNC_BUILD_CLIENT
655 if (VCanUseFSSYNC()) {
657 #ifdef AFS_DEMAND_ATTACH_FS
658 if (programType == salvageServer) {
659 Log("Unable to connect to file server; aborted\n");
662 #endif /* AFS_DEMAND_ATTACH_FS */
663 Log("Unable to connect to file server; will retry at need\n");
666 #endif /* FSSYNC_BUILD_CLIENT */
671 #if !defined(AFS_PTHREAD_ENV)
673 * Attach volumes in vice partitions
675 * @param[in] pt calling program type
678 * @note This is the original, non-threaded version of attach parititions.
680 * @post VInit state is 2
683 VInitAttachVolumes(ProgramType pt)
685 opr_Assert(VInit==1);
686 if (pt == fileServer) {
687 struct DiskPartition64 *diskP;
688 /* Attach all the volumes in this partition */
689 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
690 int nAttached = 0, nUnattached = 0;
691 opr_Verify(VAttachVolumesByPartition(diskP,
692 &nAttached, &nUnattached)
697 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
698 LWP_NoYieldSignal(VInitAttachVolumes);
702 #endif /* !AFS_PTHREAD_ENV */
704 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_DEMAND_ATTACH_FS)
706 * Attach volumes in vice partitions
708 * @param[in] pt calling program type
711 * @note Threaded version of attach parititions.
713 * @post VInit state is 2
716 VInitAttachVolumes(ProgramType pt)
718 opr_Assert(VInit==1);
719 if (pt == fileServer) {
720 struct DiskPartition64 *diskP;
721 struct vinitvolumepackage_thread_t params;
722 struct diskpartition_queue_t * dpq;
723 int i, threads, parts;
725 pthread_attr_t attrs;
727 opr_cv_init(¶ms.thread_done_cv);
729 params.n_threads_complete = 0;
731 /* create partition work queue */
732 for (parts=0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
733 dpq = malloc(sizeof(struct diskpartition_queue_t));
734 opr_Assert(dpq != NULL);
736 queue_Append(¶ms,dpq);
739 threads = min(parts, vol_attach_threads);
742 /* spawn off a bunch of initialization threads */
743 opr_Verify(pthread_attr_init(&attrs) == 0);
744 opr_Verify(pthread_attr_setdetachstate(&attrs,
745 PTHREAD_CREATE_DETACHED)
748 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
749 Log("VInitVolumePackage: using %d threads to attach volumes on %d partitions\n",
753 for (i=0; i < threads; i++) {
756 opr_Verify(pthread_create(&tid, &attrs,
757 &VInitVolumePackageThread,
759 AFS_SIGSET_RESTORE();
762 while(params.n_threads_complete < threads) {
763 VOL_CV_WAIT(¶ms.thread_done_cv);
767 opr_Verify(pthread_attr_destroy(&attrs) == 0);
769 /* if we're only going to run one init thread, don't bother creating
771 Log("VInitVolumePackage: beginning single-threaded fileserver startup\n");
772 Log("VInitVolumePackage: using 1 thread to attach volumes on %d partition(s)\n",
775 VInitVolumePackageThread(¶ms);
778 opr_cv_destroy(¶ms.thread_done_cv);
781 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
782 opr_cv_broadcast(&vol_init_attach_cond);
788 VInitVolumePackageThread(void * args) {
790 struct DiskPartition64 *diskP;
791 struct vinitvolumepackage_thread_t * params;
792 struct diskpartition_queue_t * dpq;
794 params = (vinitvolumepackage_thread_t *) args;
798 /* Attach all the volumes in this partition */
799 while (queue_IsNotEmpty(params)) {
800 int nAttached = 0, nUnattached = 0;
802 if (vinit_attach_abort) {
803 Log("Aborting initialization\n");
807 dpq = queue_First(params,diskpartition_queue_t);
813 opr_Verify(VAttachVolumesByPartition(diskP, &nAttached,
820 params->n_threads_complete++;
821 opr_cv_signal(¶ms->thread_done_cv);
825 #endif /* AFS_PTHREAD_ENV && !AFS_DEMAND_ATTACH_FS */
827 #if defined(AFS_DEMAND_ATTACH_FS)
829 * Attach volumes in vice partitions
831 * @param[in] pt calling program type
834 * @note Threaded version of attach partitions.
836 * @post VInit state is 2
839 VInitAttachVolumes(ProgramType pt)
841 opr_Assert(VInit==1);
842 if (pt == fileServer) {
844 struct DiskPartition64 *diskP;
845 struct partition_queue pq;
846 struct volume_init_queue vq;
848 int i, threads, parts;
850 pthread_attr_t attrs;
852 /* create partition work queue */
855 opr_mutex_init(&pq.mutex);
856 for (parts = 0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
857 struct diskpartition_queue_t *dp;
858 dp = malloc(sizeof(struct diskpartition_queue_t));
859 opr_Assert(dp != NULL);
861 queue_Append(&pq, dp);
864 /* number of worker threads; at least one, not to exceed the number of partitions */
865 threads = min(parts, vol_attach_threads);
867 /* create volume work queue */
870 opr_mutex_init(&vq.mutex);
872 opr_Verify(pthread_attr_init(&attrs) == 0);
873 opr_Verify(pthread_attr_setdetachstate(&attrs,
874 PTHREAD_CREATE_DETACHED) == 0);
876 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
877 Log("VInitVolumePackage: using %d threads to pre-attach volumes on %d partitions\n",
880 /* create threads to scan disk partitions. */
881 for (i=0; i < threads; i++) {
882 struct vinitvolumepackage_thread_param *params;
885 params = malloc(sizeof(struct vinitvolumepackage_thread_param));
889 params->nthreads = threads;
890 params->thread = i+1;
893 opr_Verify(pthread_create(&tid, &attrs,
894 &VInitVolumePackageThread,
895 (void*)params) == 0);
896 AFS_SIGSET_RESTORE();
899 VInitPreAttachVolumes(threads, &vq);
901 opr_Verify(pthread_attr_destroy(&attrs) == 0);
902 opr_cv_destroy(&pq.cv);
903 opr_mutex_destroy(&pq.mutex);
904 opr_cv_destroy(&vq.cv);
905 opr_mutex_destroy(&vq.mutex);
909 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
910 opr_cv_broadcast(&vol_init_attach_cond);
917 * Volume package initialization worker thread. Scan partitions for volume
918 * header files. Gather batches of volume ids and dispatch them to
919 * the main thread to be preattached. The volume preattachement is done
920 * in the main thread to avoid global volume lock contention.
923 VInitVolumePackageThread(void *args)
925 struct vinitvolumepackage_thread_param *params;
926 struct DiskPartition64 *partition;
927 struct partition_queue *pq;
928 struct volume_init_queue *vq;
929 struct volume_init_batch *vb;
932 params = (struct vinitvolumepackage_thread_param *)args;
938 vb = malloc(sizeof(struct volume_init_batch));
940 vb->thread = params->thread;
944 Log("Scanning partitions on thread %d of %d\n", params->thread, params->nthreads);
945 while((partition = VInitNextPartition(pq))) {
949 Log("Partition %s: pre-attaching volumes\n", partition->name);
950 dirp = opendir(VPartitionPath(partition));
952 Log("opendir on Partition %s failed, errno=%d!\n", partition->name, errno);
955 while ((vid = VInitNextVolumeId(dirp))) {
956 Volume *vp = calloc(1, sizeof(Volume));
958 vp->device = partition->device;
959 vp->partition = partition;
961 queue_Init(&vp->vnode_list);
962 queue_Init(&vp->rx_call_list);
963 opr_cv_init(&V_attachCV(vp));
965 vb->batch[vb->size++] = vp;
966 if (vb->size == VINIT_BATCH_MAX_SIZE) {
967 opr_mutex_enter(&vq->mutex);
968 queue_Append(vq, vb);
969 opr_cv_broadcast(&vq->cv);
970 opr_mutex_exit(&vq->mutex);
972 vb = malloc(sizeof(struct volume_init_batch));
974 vb->thread = params->thread;
983 opr_mutex_enter(&vq->mutex);
984 queue_Append(vq, vb);
985 opr_cv_broadcast(&vq->cv);
986 opr_mutex_exit(&vq->mutex);
988 Log("Partition scan thread %d of %d ended\n", params->thread, params->nthreads);
994 * Read next element from the pre-populated partition list.
996 static struct DiskPartition64*
997 VInitNextPartition(struct partition_queue *pq)
999 struct DiskPartition64 *partition;
1000 struct diskpartition_queue_t *dp; /* queue element */
1002 if (vinit_attach_abort) {
1003 Log("Aborting volume preattach thread.\n");
1007 /* get next partition to scan */
1008 opr_mutex_enter(&pq->mutex);
1009 if (queue_IsEmpty(pq)) {
1010 opr_mutex_exit(&pq->mutex);
1013 dp = queue_First(pq, diskpartition_queue_t);
1015 opr_mutex_exit(&pq->mutex);
1018 opr_Assert(dp->diskP);
1020 partition = dp->diskP;
1026 * Find next volume id on the partition.
1029 VInitNextVolumeId(DIR *dirp)
1035 while((d = readdir(dirp))) {
1036 if (vinit_attach_abort) {
1037 Log("Aborting volume preattach thread.\n");
1040 ext = strrchr(d->d_name, '.');
1041 if (d->d_name[0] == 'V' && ext && strcmp(ext, VHDREXT) == 0) {
1042 vid = VolumeNumber(d->d_name);
1046 Log("Warning: bogus volume header file: %s\n", d->d_name);
1053 * Preattach volumes in batches to avoid lock contention.
1056 VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq)
1058 struct volume_init_batch *vb;
1062 /* dequeue next volume */
1063 opr_mutex_enter(&vq->mutex);
1064 if (queue_IsEmpty(vq)) {
1065 opr_cv_wait(&vq->cv, &vq->mutex);
1067 vb = queue_First(vq, volume_init_batch);
1069 opr_mutex_exit(&vq->mutex);
1073 for (i = 0; i<vb->size; i++) {
1079 dup = VLookupVolume_r(&ec, vp->hashid, NULL);
1081 Log("Error looking up volume, code=%d\n", ec);
1084 Log("Warning: Duplicate volume id %" AFS_VOLID_FMT " detected.\n", afs_printable_VolumeId_lu(vp->hashid));
1087 /* put pre-attached volume onto the hash table
1088 * and bring it up to the pre-attached state */
1089 AddVolumeToHashTable(vp, vp->hashid);
1090 AddVolumeToVByPList_r(vp);
1091 VLRU_Init_Node_r(vp);
1092 VChangeState_r(vp, VOL_STATE_PREATTACHED);
1105 #endif /* AFS_DEMAND_ATTACH_FS */
1107 #if !defined(AFS_DEMAND_ATTACH_FS)
1109 * attach all volumes on a given disk partition
1112 VAttachVolumesByPartition(struct DiskPartition64 *diskP, int * nAttached, int * nUnattached)
1118 Log("Partition %s: attaching volumes\n", diskP->name);
1119 dirp = opendir(VPartitionPath(diskP));
1121 Log("opendir on Partition %s failed!\n", diskP->name);
1125 while ((dp = readdir(dirp))) {
1127 p = strrchr(dp->d_name, '.');
1129 if (vinit_attach_abort) {
1130 Log("Partition %s: abort attach volumes\n", diskP->name);
1134 if (p != NULL && strcmp(p, VHDREXT) == 0) {
1137 vp = VAttachVolumeByName(&error, diskP->name, dp->d_name,
1139 (*(vp ? nAttached : nUnattached))++;
1140 if (error == VOFFLINE)
1141 Log("Volume %d stays offline (/vice/offline/%s exists)\n", VolumeNumber(dp->d_name), dp->d_name);
1142 else if (LogLevel >= 5) {
1143 Log("Partition %s: attached volume %d (%s)\n",
1144 diskP->name, VolumeNumber(dp->d_name),
1153 Log("Partition %s: attached %d volumes; %d volumes not attached\n", diskP->name, *nAttached, *nUnattached);
1158 #endif /* !AFS_DEMAND_ATTACH_FS */
1160 /***************************************************/
1161 /* Shutdown routines */
1162 /***************************************************/
1166 * highly multithreaded volume package shutdown
1168 * with the demand attach fileserver extensions,
1169 * VShutdown has been modified to be multithreaded.
1170 * In order to achieve optimal use of many threads,
1171 * the shutdown code involves one control thread and
1172 * n shutdown worker threads. The control thread
1173 * periodically examines the number of volumes available
1174 * for shutdown on each partition, and produces a worker
1175 * thread allocation schedule. The idea is to eliminate
1176 * redundant scheduling computation on the workers by
1177 * having a single master scheduler.
1179 * The scheduler's objectives are:
1181 * each partition with volumes remaining gets allocated
1182 * at least 1 thread (assuming sufficient threads)
1184 * threads are allocated proportional to the number of
1185 * volumes remaining to be offlined. This ensures that
1186 * the OS I/O scheduler has many requests to elevator
1187 * seek on partitions that will (presumably) take the
1188 * longest amount of time (from now) to finish shutdown
1189 * (3) keep threads busy
1190 * when there are extra threads, they are assigned to
1191 * partitions using a simple round-robin algorithm
1193 * In the future, we may wish to add the ability to adapt
1194 * to the relative performance patterns of each disk
1199 * multi-step shutdown process
1201 * demand attach shutdown is a four-step process. Each
1202 * shutdown "pass" shuts down increasingly more difficult
1203 * volumes. The main purpose is to achieve better cache
1204 * utilization during shutdown.
1207 * shutdown volumes in the unattached, pre-attached
1210 * shutdown attached volumes with cached volume headers
1212 * shutdown all volumes in non-exclusive states
1214 * shutdown all remaining volumes
1217 #ifdef AFS_DEMAND_ATTACH_FS
1223 struct DiskPartition64 * diskP;
1224 struct diskpartition_queue_t * dpq;
1225 vshutdown_thread_t params;
1227 pthread_attr_t attrs;
1229 memset(¶ms, 0, sizeof(vshutdown_thread_t));
1232 Log("VShutdown: aborting attach volumes\n");
1233 vinit_attach_abort = 1;
1234 VOL_CV_WAIT(&vol_init_attach_cond);
1237 for (params.n_parts=0, diskP = DiskPartitionList;
1238 diskP; diskP = diskP->next, params.n_parts++);
1240 Log("VShutdown: shutting down on-line volumes on %d partition%s...\n",
1241 params.n_parts, params.n_parts > 1 ? "s" : "");
1243 vol_shutting_down = 1;
1245 if (vol_attach_threads > 1) {
1246 /* prepare for parallel shutdown */
1247 params.n_threads = vol_attach_threads;
1248 opr_mutex_init(¶ms.lock);
1249 opr_cv_init(¶ms.cv);
1250 opr_cv_init(¶ms.master_cv);
1251 opr_Verify(pthread_attr_init(&attrs) == 0);
1252 opr_Verify(pthread_attr_setdetachstate(&attrs,
1253 PTHREAD_CREATE_DETACHED) == 0);
1254 queue_Init(¶ms);
1256 /* setup the basic partition information structures for
1257 * parallel shutdown */
1258 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1260 struct rx_queue * qp, * nqp;
1264 VVByPListWait_r(diskP);
1265 VVByPListBeginExclusive_r(diskP);
1268 for (queue_Scan(&diskP->vol_list, qp, nqp, rx_queue)) {
1269 vp = (Volume *)((char *)qp - offsetof(Volume, vol_list));
1273 Log("VShutdown: partition %s has %d volumes with attached headers\n",
1274 VPartitionPath(diskP), count);
1277 /* build up the pass 0 shutdown work queue */
1278 dpq = malloc(sizeof(struct diskpartition_queue_t));
1279 opr_Assert(dpq != NULL);
1281 queue_Prepend(¶ms, dpq);
1283 params.part_pass_head[diskP->index] = queue_First(&diskP->vol_list, rx_queue);
1286 Log("VShutdown: beginning parallel fileserver shutdown\n");
1287 Log("VShutdown: using %d threads to offline volumes on %d partition%s\n",
1288 vol_attach_threads, params.n_parts, params.n_parts > 1 ? "s" : "" );
1290 /* do pass 0 shutdown */
1291 opr_mutex_enter(¶ms.lock);
1292 for (i=0; i < params.n_threads; i++) {
1293 opr_Verify(pthread_create(&tid, &attrs, &VShutdownThread,
1297 /* wait for all the pass 0 shutdowns to complete */
1298 while (params.n_threads_complete < params.n_threads) {
1299 CV_WAIT(¶ms.master_cv, ¶ms.lock);
1301 params.n_threads_complete = 0;
1303 opr_cv_broadcast(¶ms.cv);
1304 opr_mutex_exit(¶ms.lock);
1306 Log("VShutdown: pass 0 completed using the 1 thread per partition algorithm\n");
1307 Log("VShutdown: starting passes 1 through 3 using finely-granular mp-fast algorithm\n");
1309 /* run the parallel shutdown scheduler. it will drop the glock internally */
1310 ShutdownController(¶ms);
1312 /* wait for all the workers to finish pass 3 and terminate */
1313 while (params.pass < 4) {
1314 VOL_CV_WAIT(¶ms.cv);
1317 opr_Verify(pthread_attr_destroy(&attrs) == 0);
1318 opr_cv_destroy(¶ms.cv);
1319 opr_cv_destroy(¶ms.master_cv);
1320 opr_mutex_destroy(¶ms.lock);
1322 /* drop the VByPList exclusive reservations */
1323 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1324 VVByPListEndExclusive_r(diskP);
1325 Log("VShutdown: %s stats : (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1326 VPartitionPath(diskP),
1327 params.stats[0][diskP->index],
1328 params.stats[1][diskP->index],
1329 params.stats[2][diskP->index],
1330 params.stats[3][diskP->index]);
1333 Log("VShutdown: shutdown finished using %d threads\n", params.n_threads);
1335 /* if we're only going to run one shutdown thread, don't bother creating
1337 Log("VShutdown: beginning single-threaded fileserver shutdown\n");
1339 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1340 VShutdownByPartition_r(diskP);
1344 Log("VShutdown: complete.\n");
1347 #else /* AFS_DEMAND_ATTACH_FS */
1357 Log("VShutdown: aborting attach volumes\n");
1358 vinit_attach_abort = 1;
1359 #ifdef AFS_PTHREAD_ENV
1360 VOL_CV_WAIT(&vol_init_attach_cond);
1362 LWP_WaitProcess(VInitAttachVolumes);
1363 #endif /* AFS_PTHREAD_ENV */
1366 Log("VShutdown: shutting down on-line volumes...\n");
1367 vol_shutting_down = 1;
1368 for (i = 0; i < VolumeHashTable.Size; i++) {
1369 /* try to hold first volume in the hash table */
1370 for (queue_Scan(&VolumeHashTable.Table[i],vp,np,Volume)) {
1374 Log("VShutdown: Attempting to take volume %" AFS_VOLID_FMT " offline.\n",
1375 afs_printable_VolumeId_lu(vp->hashid));
1377 /* next, take the volume offline (drops reference count) */
1378 VOffline_r(vp, "File server was shut down");
1382 Log("VShutdown: complete.\n");
1384 #endif /* AFS_DEMAND_ATTACH_FS */
1390 opr_Assert(VInit>0);
1397 * stop new activity (e.g. SALVSYNC) from occurring
1399 * Use this to make the volume package less busy; for example, during
1400 * shutdown. This doesn't actually shutdown/detach anything in the
1401 * volume package, but prevents certain processes from ocurring. For
1402 * example, preventing new SALVSYNC communication in DAFS. In theory, we
1403 * could also use this to prevent new volume attachment, or prevent
1404 * other programs from checking out volumes, etc.
1409 #ifdef AFS_DEMAND_ATTACH_FS
1410 /* make sure we don't try to contact the salvageserver, since it may
1411 * not be around anymore */
1412 vol_disallow_salvsync = 1;
1416 #ifdef AFS_DEMAND_ATTACH_FS
1419 * shutdown control thread
1422 ShutdownController(vshutdown_thread_t * params)
1425 struct DiskPartition64 * diskP;
1427 vshutdown_thread_t shadow;
1429 ShutdownCreateSchedule(params);
1431 while ((params->pass < 4) &&
1432 (params->n_threads_complete < params->n_threads)) {
1433 /* recompute schedule once per second */
1435 memcpy(&shadow, params, sizeof(vshutdown_thread_t));
1439 Log("ShutdownController: schedule version=%d, vol_remaining=%d, pass=%d\n",
1440 shadow.schedule_version, shadow.vol_remaining, shadow.pass);
1441 Log("ShutdownController: n_threads_complete=%d, n_parts_done_pass=%d\n",
1442 shadow.n_threads_complete, shadow.n_parts_done_pass);
1443 for (diskP = DiskPartitionList; diskP; diskP=diskP->next) {
1445 Log("ShutdownController: part[%d] : (len=%d, thread_target=%d, done_pass=%d, pass_head=%p)\n",
1447 diskP->vol_list.len,
1448 shadow.part_thread_target[id],
1449 shadow.part_done_pass[id],
1450 shadow.part_pass_head[id]);
1456 ShutdownCreateSchedule(params);
1460 /* create the shutdown thread work schedule.
1461 * this scheduler tries to implement fairness
1462 * by allocating at least 1 thread to each
1463 * partition with volumes to be shutdown,
1464 * and then it attempts to allocate remaining
1465 * threads based upon the amount of work left
1468 ShutdownCreateSchedule(vshutdown_thread_t * params)
1470 struct DiskPartition64 * diskP;
1471 int sum, thr_workload, thr_left;
1472 int part_residue[VOLMAXPARTS+1];
1475 /* compute the total number of outstanding volumes */
1477 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1478 sum += diskP->vol_list.len;
1481 params->schedule_version++;
1482 params->vol_remaining = sum;
1487 /* compute average per-thread workload */
1488 thr_workload = sum / params->n_threads;
1489 if (sum % params->n_threads)
1492 thr_left = params->n_threads;
1493 memset(&part_residue, 0, sizeof(part_residue));
1495 /* for fairness, give every partition with volumes remaining
1496 * at least one thread */
1497 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1499 if (diskP->vol_list.len) {
1500 params->part_thread_target[id] = 1;
1503 params->part_thread_target[id] = 0;
1507 if (thr_left && thr_workload) {
1508 /* compute length-weighted workloads */
1511 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1513 delta = (diskP->vol_list.len / thr_workload) -
1514 params->part_thread_target[id];
1518 if (delta < thr_left) {
1519 params->part_thread_target[id] += delta;
1522 params->part_thread_target[id] += thr_left;
1530 /* try to assign any leftover threads to partitions that
1531 * had volume lengths closer to needing thread_target+1 */
1532 int max_residue, max_id = 0;
1534 /* compute the residues */
1535 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1537 part_residue[id] = diskP->vol_list.len -
1538 (params->part_thread_target[id] * thr_workload);
1541 /* now try to allocate remaining threads to partitions with the
1542 * highest residues */
1545 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1547 if (part_residue[id] > max_residue) {
1548 max_residue = part_residue[id];
1557 params->part_thread_target[max_id]++;
1559 part_residue[max_id] = 0;
1564 /* punt and give any remaining threads equally to each partition */
1566 if (thr_left >= params->n_parts) {
1567 alloc = thr_left / params->n_parts;
1568 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1570 params->part_thread_target[id] += alloc;
1575 /* finish off the last of the threads */
1576 for (diskP = DiskPartitionList; thr_left && diskP; diskP = diskP->next) {
1578 params->part_thread_target[id]++;
1584 /* worker thread for parallel shutdown */
1586 VShutdownThread(void * args)
1588 vshutdown_thread_t * params;
1589 int found, pass, schedule_version_save, count;
1590 struct DiskPartition64 *diskP;
1591 struct diskpartition_queue_t * dpq;
1594 params = (vshutdown_thread_t *) args;
1596 /* acquire the shutdown pass 0 lock */
1597 opr_mutex_enter(¶ms->lock);
1599 /* if there's still pass 0 work to be done,
1600 * get a work entry, and do a pass 0 shutdown */
1601 if (queue_IsNotEmpty(params)) {
1602 dpq = queue_First(params, diskpartition_queue_t);
1604 opr_mutex_exit(¶ms->lock);
1610 while (ShutdownVolumeWalk_r(diskP, 0, ¶ms->part_pass_head[id]))
1612 params->stats[0][diskP->index] = count;
1613 opr_mutex_enter(¶ms->lock);
1616 params->n_threads_complete++;
1617 if (params->n_threads_complete == params->n_threads) {
1618 /* notify control thread that all workers have completed pass 0 */
1619 opr_cv_signal(¶ms->master_cv);
1621 while (params->pass == 0) {
1622 opr_cv_wait(¶ms->cv, ¶ms->lock);
1626 opr_mutex_exit(¶ms->lock);
1629 pass = params->pass;
1630 opr_Assert(pass > 0);
1632 /* now escalate through the more complicated shutdowns */
1634 schedule_version_save = params->schedule_version;
1636 /* find a disk partition to work on */
1637 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1639 if (params->part_thread_target[id] && !params->part_done_pass[id]) {
1640 params->part_thread_target[id]--;
1647 /* hmm. for some reason the controller thread couldn't find anything for
1648 * us to do. let's see if there's anything we can do */
1649 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1651 if (diskP->vol_list.len && !params->part_done_pass[id]) {
1654 } else if (!params->part_done_pass[id]) {
1655 params->part_done_pass[id] = 1;
1656 params->n_parts_done_pass++;
1658 Log("VShutdown: done shutting down volumes on partition %s.\n",
1659 VPartitionPath(diskP));
1665 /* do work on this partition until either the controller
1666 * creates a new schedule, or we run out of things to do
1667 * on this partition */
1670 while (!params->part_done_pass[id] &&
1671 (schedule_version_save == params->schedule_version)) {
1672 /* ShutdownVolumeWalk_r will drop the glock internally */
1673 if (!ShutdownVolumeWalk_r(diskP, pass, ¶ms->part_pass_head[id])) {
1674 if (!params->part_done_pass[id]) {
1675 params->part_done_pass[id] = 1;
1676 params->n_parts_done_pass++;
1678 Log("VShutdown: done shutting down volumes on partition %s.\n",
1679 VPartitionPath(diskP));
1687 params->stats[pass][id] += count;
1689 /* ok, everyone is done this pass, proceed */
1692 params->n_threads_complete++;
1693 while (params->pass == pass) {
1694 if (params->n_threads_complete == params->n_threads) {
1695 /* we are the last thread to complete, so we will
1696 * reinitialize worker pool state for the next pass */
1697 params->n_threads_complete = 0;
1698 params->n_parts_done_pass = 0;
1700 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1702 params->part_done_pass[id] = 0;
1703 params->part_pass_head[id] = queue_First(&diskP->vol_list, rx_queue);
1706 /* compute a new thread schedule before releasing all the workers */
1707 ShutdownCreateSchedule(params);
1709 /* wake up all the workers */
1710 opr_cv_broadcast(¶ms->cv);
1713 Log("VShutdown: pass %d completed using %d threads on %d partitions\n",
1714 pass, params->n_threads, params->n_parts);
1717 VOL_CV_WAIT(¶ms->cv);
1720 pass = params->pass;
1734 /* shut down all volumes on a given disk partition
1736 * note that this function will not allow mp-fast
1737 * shutdown of a partition */
1739 VShutdownByPartition_r(struct DiskPartition64 * dp)
1745 /* wait for other exclusive ops to finish */
1746 VVByPListWait_r(dp);
1748 /* begin exclusive access */
1749 VVByPListBeginExclusive_r(dp);
1751 /* pick the low-hanging fruit first,
1752 * then do the complicated ones last
1753 * (has the advantage of keeping
1754 * in-use volumes up until the bitter end) */
1755 for (pass = 0, total=0; pass < 4; pass++) {
1756 pass_stats[pass] = ShutdownVByPForPass_r(dp, pass);
1757 total += pass_stats[pass];
1760 /* end exclusive access */
1761 VVByPListEndExclusive_r(dp);
1763 Log("VShutdownByPartition: shut down %d volumes on %s (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1764 total, VPartitionPath(dp), pass_stats[0], pass_stats[1], pass_stats[2], pass_stats[3]);
1769 /* internal shutdown functionality
1771 * for multi-pass shutdown:
1772 * 0 to only "shutdown" {pre,un}attached and error state volumes
1773 * 1 to also shutdown attached volumes w/ volume header loaded
1774 * 2 to also shutdown attached volumes w/o volume header loaded
1775 * 3 to also shutdown exclusive state volumes
1777 * caller MUST hold exclusive access on the hash chain
1778 * because we drop vol_glock_mutex internally
1780 * this function is reentrant for passes 1--3
1781 * (e.g. multiple threads can cooperate to
1782 * shutdown a partition mp-fast)
1784 * pass 0 is not scaleable because the volume state data is
1785 * synchronized by vol_glock mutex, and the locking overhead
1786 * is too high to drop the lock long enough to do linked list
1790 ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass)
1792 struct rx_queue * q = queue_First(&dp->vol_list, rx_queue);
1794 const char *pass_strs[4] = {"{un/pre}attached vols", "vols w/ vol header loaded", "vols w/o vol header loaded", "vols with exclusive state"};
1796 while (ShutdownVolumeWalk_r(dp, pass, &q)) {
1799 Log("VShutdownByPartition: ... shut down %d volumes on %s in pass %d (%s)\n", i, VPartitionPath(dp), pass, pass_strs[pass]);
1806 /* conditionally shutdown one volume on partition dp
1807 * returns 1 if a volume was shutdown in this pass,
1810 ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
1811 struct rx_queue ** idx)
1813 struct rx_queue *qp, *nqp;
1818 for (queue_ScanFrom(&dp->vol_list, qp, qp, nqp, rx_queue)) {
1819 vp = (Volume *) (((char *)qp) - offsetof(Volume, vol_list));
1823 if ((V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1824 (V_attachState(vp) != VOL_STATE_ERROR) &&
1825 (V_attachState(vp) != VOL_STATE_DELETED) &&
1826 (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1830 if ((V_attachState(vp) == VOL_STATE_ATTACHED) &&
1831 (vp->header == NULL)) {
1835 if (VIsExclusiveState(V_attachState(vp))) {
1840 DeleteVolumeFromVByPList_r(vp);
1841 VShutdownVolume_r(vp);
1851 * shutdown a specific volume
1853 /* caller MUST NOT hold a heavyweight ref on vp */
1855 VShutdownVolume_r(Volume * vp)
1859 VCreateReservation_r(vp);
1861 if (LogLevel >= 5) {
1862 Log("VShutdownVolume_r: vid=%" AFS_VOLID_FMT ", device=%d, state=%u\n",
1863 afs_printable_VolumeId_lu(vp->hashid), vp->partition->device,
1864 (unsigned int) V_attachState(vp));
1867 /* wait for other blocking ops to finish */
1868 VWaitExclusiveState_r(vp);
1870 opr_Assert(VIsValidState(V_attachState(vp)));
1872 switch(V_attachState(vp)) {
1873 case VOL_STATE_SALVAGING:
1874 /* Leave salvaging volumes alone. Any in-progress salvages will
1875 * continue working after viced shuts down. This is intentional.
1878 case VOL_STATE_PREATTACHED:
1879 case VOL_STATE_ERROR:
1880 VChangeState_r(vp, VOL_STATE_UNATTACHED);
1881 case VOL_STATE_UNATTACHED:
1882 case VOL_STATE_DELETED:
1884 case VOL_STATE_GOING_OFFLINE:
1885 case VOL_STATE_SHUTTING_DOWN:
1886 case VOL_STATE_ATTACHED:
1890 Log("VShutdown: Attempting to take volume %" AFS_VOLID_FMT " offline.\n",
1891 afs_printable_VolumeId_lu(vp->hashid));
1893 /* take the volume offline (drops reference count) */
1894 VOffline_r(vp, "File server was shut down");
1901 VCancelReservation_r(vp);
1905 #endif /* AFS_DEMAND_ATTACH_FS */
1908 /***************************************************/
1909 /* Header I/O routines */
1910 /***************************************************/
1913 HeaderName(bit32 magic)
1916 case VOLUMEINFOMAGIC:
1917 return "volume info";
1918 case SMALLINDEXMAGIC:
1919 return "small index";
1920 case LARGEINDEXMAGIC:
1921 return "large index";
1922 case LINKTABLEMAGIC:
1923 return "link table";
1928 /* open a descriptor for the inode (h),
1929 * read in an on-disk structure into buffer (to) of size (size),
1930 * verify versionstamp in structure has magic (magic) and
1931 * optionally verify version (version) if (version) is nonzero
1934 ReadHeader(Error * ec, IHandle_t * h, char *to, int size, bit32 magic,
1937 struct versionStamp *vsn;
1939 afs_sfsize_t nbytes;
1944 Log("ReadHeader: Null inode handle argument for %s header file.\n",
1952 Log("ReadHeader: Failed to open %s header file "
1953 "(volume=%" AFS_VOLID_FMT ", inode=%s); errno=%d\n", HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid),
1954 PrintInode(stmp, h->ih_ino), errno);
1959 vsn = (struct versionStamp *)to;
1960 nbytes = FDH_PREAD(fdP, to, size, 0);
1962 Log("ReadHeader: Failed to read %s header file "
1963 "(volume=%" AFS_VOLID_FMT ", inode=%s); errno=%d\n", HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid),
1964 PrintInode(stmp, h->ih_ino), errno);
1966 FDH_REALLYCLOSE(fdP);
1969 if (nbytes != size) {
1970 Log("ReadHeader: Incorrect number of bytes read from %s header file "
1971 "(volume=%" AFS_VOLID_FMT ", inode=%s); expected=%d, read=%d\n",
1972 HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid),
1973 PrintInode(stmp, h->ih_ino), size, (int)nbytes);
1975 FDH_REALLYCLOSE(fdP);
1978 if (vsn->magic != magic) {
1979 Log("ReadHeader: Incorrect magic for %s header file "
1980 "(volume=%" AFS_VOLID_FMT ", inode=%s); expected=0x%x, read=0x%x\n",
1981 HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid),
1982 PrintInode(stmp, h->ih_ino), magic, vsn->magic);
1984 FDH_REALLYCLOSE(fdP);
1990 /* Check is conditional, in case caller wants to inspect version himself */
1991 if (version && vsn->version != version) {
1992 Log("ReadHeader: Incorrect version for %s header file "
1993 "(volume=%" AFS_VOLID_FMT ", inode=%s); expected=%x, read=%x\n",
1994 HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid), PrintInode(stmp, h->ih_ino),
1995 version, vsn->version);
2001 WriteVolumeHeader_r(Error * ec, Volume * vp)
2003 IHandle_t *h = V_diskDataHandle(vp);
2013 if (FDH_PWRITE(fdP, (char *)&V_disk(vp), sizeof(V_disk(vp)), 0)
2014 != sizeof(V_disk(vp))) {
2016 FDH_REALLYCLOSE(fdP);
2022 /* VolumeHeaderToDisk
2023 * Allows for storing 64 bit inode numbers in on-disk volume header
2026 /* convert in-memory representation of a volume header to the
2027 * on-disk representation of a volume header */
2029 VolumeHeaderToDisk(VolumeDiskHeader_t * dh, VolumeHeader_t * h)
2032 memset(dh, 0, sizeof(VolumeDiskHeader_t));
2033 dh->stamp = h->stamp;
2035 dh->parent = h->parent;
2037 #ifdef AFS_64BIT_IOPS_ENV
2038 dh->volumeInfo_lo = (afs_int32) h->volumeInfo & 0xffffffff;
2039 dh->volumeInfo_hi = (afs_int32) (h->volumeInfo >> 32) & 0xffffffff;
2040 dh->smallVnodeIndex_lo = (afs_int32) h->smallVnodeIndex & 0xffffffff;
2041 dh->smallVnodeIndex_hi =
2042 (afs_int32) (h->smallVnodeIndex >> 32) & 0xffffffff;
2043 dh->largeVnodeIndex_lo = (afs_int32) h->largeVnodeIndex & 0xffffffff;
2044 dh->largeVnodeIndex_hi =
2045 (afs_int32) (h->largeVnodeIndex >> 32) & 0xffffffff;
2046 dh->linkTable_lo = (afs_int32) h->linkTable & 0xffffffff;
2047 dh->linkTable_hi = (afs_int32) (h->linkTable >> 32) & 0xffffffff;
2049 dh->volumeInfo_lo = h->volumeInfo;
2050 dh->smallVnodeIndex_lo = h->smallVnodeIndex;
2051 dh->largeVnodeIndex_lo = h->largeVnodeIndex;
2052 dh->linkTable_lo = h->linkTable;
2056 /* DiskToVolumeHeader
2057 * Converts an on-disk representation of a volume header to
2058 * the in-memory representation of a volume header.
2060 * Makes the assumption that AFS has *always*
2061 * zero'd the volume header file so that high parts of inode
2062 * numbers are 0 in older (SGI EFS) volume header files.
2065 DiskToVolumeHeader(VolumeHeader_t * h, VolumeDiskHeader_t * dh)
2067 memset(h, 0, sizeof(VolumeHeader_t));
2068 h->stamp = dh->stamp;
2070 h->parent = dh->parent;
2072 #ifdef AFS_64BIT_IOPS_ENV
2074 (Inode) dh->volumeInfo_lo | ((Inode) dh->volumeInfo_hi << 32);
2076 h->smallVnodeIndex =
2077 (Inode) dh->smallVnodeIndex_lo | ((Inode) dh->
2078 smallVnodeIndex_hi << 32);
2080 h->largeVnodeIndex =
2081 (Inode) dh->largeVnodeIndex_lo | ((Inode) dh->
2082 largeVnodeIndex_hi << 32);
2084 (Inode) dh->linkTable_lo | ((Inode) dh->linkTable_hi << 32);
2086 h->volumeInfo = dh->volumeInfo_lo;
2087 h->smallVnodeIndex = dh->smallVnodeIndex_lo;
2088 h->largeVnodeIndex = dh->largeVnodeIndex_lo;
2089 h->linkTable = dh->linkTable_lo;
2094 /***************************************************/
2095 /* Volume Attachment routines */
2096 /***************************************************/
2098 #ifdef AFS_DEMAND_ATTACH_FS
2100 * pre-attach a volume given its path.
2102 * @param[out] ec outbound error code
2103 * @param[in] partition partition path string
2104 * @param[in] name volume id string
2106 * @return volume object pointer
2108 * @note A pre-attached volume will only have its partition
2109 * and hashid fields initialized. At first call to
2110 * VGetVolume, the volume will be fully attached.
2114 VPreAttachVolumeByName(Error * ec, char *partition, char *name)
2118 vp = VPreAttachVolumeByName_r(ec, partition, name);
2124 * pre-attach a volume given its path.
2126 * @param[out] ec outbound error code
2127 * @param[in] partition path to vice partition
2128 * @param[in] name volume id string
2130 * @return volume object pointer
2132 * @pre VOL_LOCK held
2134 * @internal volume package internal use only.
2137 VPreAttachVolumeByName_r(Error * ec, char *partition, char *name)
2139 return VPreAttachVolumeById_r(ec,
2141 VolumeNumber(name));
2145 * pre-attach a volume given its path and numeric volume id.
2147 * @param[out] ec error code return
2148 * @param[in] partition path to vice partition
2149 * @param[in] volumeId numeric volume id
2151 * @return volume object pointer
2153 * @pre VOL_LOCK held
2155 * @internal volume package internal use only.
2158 VPreAttachVolumeById_r(Error * ec,
2163 struct DiskPartition64 *partp;
2167 opr_Assert(programType == fileServer);
2169 if (!(partp = VGetPartition_r(partition, 0))) {
2171 Log("VPreAttachVolumeById_r: Error getting partition (%s)\n", partition);
2175 /* ensure that any vp we pass to VPreAttachVolumeByVp_r
2176 * is NOT in exclusive state.
2179 vp = VLookupVolume_r(ec, volumeId, NULL);
2185 if (vp && VIsExclusiveState(V_attachState(vp))) {
2186 VCreateReservation_r(vp);
2187 VWaitExclusiveState_r(vp);
2188 VCancelReservation_r(vp);
2190 goto retry; /* look up volume again */
2193 /* vp == NULL or vp not exclusive both OK */
2195 return VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2199 * preattach a volume.
2201 * @param[out] ec outbound error code
2202 * @param[in] partp pointer to partition object
2203 * @param[in] vp pointer to volume object
2204 * @param[in] vid volume id
2206 * @return volume object pointer
2208 * @pre VOL_LOCK is held.
2210 * @pre vp (if specified) must not be in exclusive state.
2212 * @warning Returned volume object pointer does not have to
2213 * equal the pointer passed in as argument vp. There
2214 * are potential race conditions which can result in
2215 * the pointers having different values. It is up to
2216 * the caller to make sure that references are handled
2217 * properly in this case.
2219 * @note If there is already a volume object registered with
2220 * the same volume id, its pointer MUST be passed as
2221 * argument vp. Failure to do so will result in a silent
2222 * failure to preattach.
2224 * @internal volume package internal use only.
2227 VPreAttachVolumeByVp_r(Error * ec,
2228 struct DiskPartition64 * partp,
2236 /* don't proceed unless it's safe */
2238 opr_Assert(!VIsExclusiveState(V_attachState(vp)));
2241 /* check to see if pre-attach already happened */
2243 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
2244 (V_attachState(vp) != VOL_STATE_DELETED) &&
2245 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
2246 !VIsErrorState(V_attachState(vp))) {
2248 * pre-attach is a no-op in all but the following cases:
2250 * - volume is unattached
2251 * - volume is in an error state
2252 * - volume is pre-attached
2254 Log("VPreattachVolumeByVp_r: volume %" AFS_VOLID_FMT " not in quiescent state (state %u flags 0x%x)\n",
2255 afs_printable_VolumeId_lu(vid), V_attachState(vp),
2259 /* we're re-attaching a volume; clear out some old state */
2260 memset(&vp->salvage, 0, sizeof(struct VolumeOnlineSalvage));
2262 if (V_partition(vp) != partp) {
2263 /* XXX potential race */
2264 DeleteVolumeFromVByPList_r(vp);
2267 /* if we need to allocate a new Volume struct,
2268 * go ahead and drop the vol glock, otherwise
2269 * do the basic setup synchronised, as it's
2270 * probably not worth dropping the lock */
2273 /* allocate the volume structure */
2274 vp = nvp = calloc(1, sizeof(Volume));
2275 opr_Assert(vp != NULL);
2276 queue_Init(&vp->vnode_list);
2277 queue_Init(&vp->rx_call_list);
2278 opr_cv_init(&V_attachCV(vp));
2281 /* link the volume with its associated vice partition */
2282 vp->device = partp->device;
2283 vp->partition = partp;
2286 vp->specialStatus = 0;
2288 /* if we dropped the lock, reacquire the lock,
2289 * check for pre-attach races, and then add
2290 * the volume to the hash table */
2293 nvp = VLookupVolume_r(ec, vid, NULL);
2298 } else if (nvp) { /* race detected */
2303 /* hack to make up for VChangeState_r() decrementing
2304 * the old state counter */
2305 VStats.state_levels[0]++;
2309 /* put pre-attached volume onto the hash table
2310 * and bring it up to the pre-attached state */
2311 AddVolumeToHashTable(vp, vp->hashid);
2312 AddVolumeToVByPList_r(vp);
2313 VLRU_Init_Node_r(vp);
2314 VChangeState_r(vp, VOL_STATE_PREATTACHED);
2317 Log("VPreAttachVolumeByVp_r: volume %" AFS_VOLID_FMT " pre-attached\n", afs_printable_VolumeId_lu(vp->hashid));
2325 #endif /* AFS_DEMAND_ATTACH_FS */
2327 /* Attach an existing volume, given its pathname, and return a
2328 pointer to the volume header information. The volume also
2329 normally goes online at this time. An offline volume
2330 must be reattached to make it go online */
2332 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
2336 retVal = VAttachVolumeByName_r(ec, partition, name, mode);
2342 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
2345 struct DiskPartition64 *partp;
2350 #ifdef AFS_DEMAND_ATTACH_FS
2351 VolumeStats stats_save;
2353 #endif /* AFS_DEMAND_ATTACH_FS */
2357 volumeId = VolumeNumber(name);
2359 if (!(partp = VGetPartition_r(partition, 0))) {
2361 Log("VAttachVolume: Error getting partition (%s)\n", partition);
2365 if (VRequiresPartLock()) {
2366 opr_Assert(VInit == 3);
2367 VLockPartition_r(partition);
2368 } else if (programType == fileServer) {
2369 #ifdef AFS_DEMAND_ATTACH_FS
2370 /* lookup the volume in the hash table */
2371 vp = VLookupVolume_r(ec, volumeId, NULL);
2377 /* save any counters that are supposed to
2378 * be monotonically increasing over the
2379 * lifetime of the fileserver */
2380 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2382 memset(&stats_save, 0, sizeof(VolumeStats));
2385 /* if there's something in the hash table, and it's not
2386 * in the pre-attach state, then we may need to detach
2387 * it before proceeding */
2388 if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
2389 VCreateReservation_r(vp);
2390 VWaitExclusiveState_r(vp);
2392 /* at this point state must be one of:
2402 if (vp->specialStatus == VBUSY)
2405 /* if it's already attached, see if we can return it */
2406 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2407 VGetVolumeByVp_r(ec, vp);
2408 if (V_inUse(vp) == fileServer) {
2409 VCancelReservation_r(vp);
2413 /* otherwise, we need to detach, and attempt to re-attach */
2414 VDetachVolume_r(ec, vp);
2416 Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
2419 /* if it isn't fully attached, delete from the hash tables,
2420 and let the refcounter handle the rest */
2421 DeleteVolumeFromHashTable(vp);
2422 DeleteVolumeFromVByPList_r(vp);
2425 VCancelReservation_r(vp);
2429 /* pre-attach volume if it hasn't been done yet */
2431 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2432 (V_attachState(vp) == VOL_STATE_DELETED) ||
2433 (V_attachState(vp) == VOL_STATE_ERROR)) {
2435 vp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2441 opr_Assert(vp != NULL);
2443 /* handle pre-attach races
2445 * multiple threads can race to pre-attach a volume,
2446 * but we can't let them race beyond that
2448 * our solution is to let the first thread to bring
2449 * the volume into an exclusive state win; the other
2450 * threads just wait until it finishes bringing the
2451 * volume online, and then they do a vgetvolumebyvp
2453 if (svp && (svp != vp)) {
2454 /* wait for other exclusive ops to finish */
2455 VCreateReservation_r(vp);
2456 VWaitExclusiveState_r(vp);
2458 /* get a heavyweight ref, kill the lightweight ref, and return */
2459 VGetVolumeByVp_r(ec, vp);
2460 VCancelReservation_r(vp);
2464 /* at this point, we are chosen as the thread to do
2465 * demand attachment for this volume. all other threads
2466 * doing a getvolume on vp->hashid will block until we finish */
2468 /* make sure any old header cache entries are invalidated
2469 * before proceeding */
2470 FreeVolumeHeader(vp);
2472 VChangeState_r(vp, VOL_STATE_ATTACHING);
2474 /* restore any saved counters */
2475 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2476 #else /* AFS_DEMAND_ATTACH_FS */
2477 vp = VGetVolume_r(ec, volumeId);
2479 if (V_inUse(vp) == fileServer)
2481 if (vp->specialStatus == VBUSY)
2483 VDetachVolume_r(ec, vp);
2485 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2489 #endif /* AFS_DEMAND_ATTACH_FS */
2493 strcpy(path, VPartitionPath(partp));
2497 strcat(path, OS_DIRSEP);
2501 vp = (Volume *) calloc(1, sizeof(Volume));
2502 opr_Assert(vp != NULL);
2503 vp->hashid = volumeId;
2504 vp->device = partp->device;
2505 vp->partition = partp;
2506 queue_Init(&vp->vnode_list);
2507 queue_Init(&vp->rx_call_list);
2508 #ifdef AFS_DEMAND_ATTACH_FS
2509 opr_cv_init(&V_attachCV(vp));
2510 #endif /* AFS_DEMAND_ATTACH_FS */
2513 /* attach2 is entered without any locks, and returns
2514 * with vol_glock_mutex held */
2515 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2517 if (VCanUseFSSYNC() && vp) {
2518 #ifdef AFS_DEMAND_ATTACH_FS
2519 if ((mode == V_VOLUPD) || (VolumeWriteable(vp) && (mode == V_CLONE))) {
2520 /* mark volume header as in use so that volser crashes lead to a
2521 * salvage attempt */
2522 VUpdateVolume_r(ec, vp, 0);
2524 /* for dafs, we should tell the fileserver, except for V_PEEK
2525 * where we know it is not necessary */
2526 if (mode == V_PEEK) {
2527 vp->needsPutBack = 0;
2529 vp->needsPutBack = VOL_PUTBACK;
2531 #else /* !AFS_DEMAND_ATTACH_FS */
2532 /* duplicate computation in fssync.c about whether the server
2533 * takes the volume offline or not. If the volume isn't
2534 * offline, we must not return it when we detach the volume,
2535 * or the server will abort */
2536 if (mode == V_READONLY || mode == V_PEEK
2537 || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
2538 vp->needsPutBack = 0;
2540 vp->needsPutBack = VOL_PUTBACK;
2541 #endif /* !AFS_DEMAND_ATTACH_FS */
2543 #ifdef FSSYNC_BUILD_CLIENT
2544 /* Only give back the vol to the fileserver if we checked it out; attach2
2545 * will set checkedOut only if we successfully checked it out from the
2547 if (VCanUseFSSYNC() && vp == NULL && checkedOut) {
2549 #ifdef AFS_DEMAND_ATTACH_FS
2550 /* If we couldn't attach but we scheduled a salvage, we already
2551 * notified the fileserver; don't online it now */
2552 if (*ec != VSALVAGING)
2553 #endif /* AFS_DEMAND_ATTACH_FS */
2554 FSYNC_VolOp(volumeId, partition, FSYNC_VOL_ON, 0, NULL);
2557 if (programType == fileServer && vp) {
2558 #ifdef AFS_DEMAND_ATTACH_FS
2560 * we can get here in cases where we don't "own"
2561 * the volume (e.g. volume owned by a utility).
2562 * short circuit around potential disk header races.
2564 if (V_attachState(vp) != VOL_STATE_ATTACHED) {
2568 VUpdateVolume_r(ec, vp, 0);
2570 Log("VAttachVolume: Error updating volume\n");
2575 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2576 #ifndef AFS_DEMAND_ATTACH_FS
2577 /* This is a hack: by temporarily setting the incore
2578 * dontSalvage flag ON, the volume will be put back on the
2579 * Update list (with dontSalvage OFF again). It will then
2580 * come back in N minutes with DONT_SALVAGE eventually
2581 * set. This is the way that volumes that have never had
2582 * it set get it set; or that volumes that have been
2583 * offline without DONT SALVAGE having been set also
2584 * eventually get it set */
2585 V_dontSalvage(vp) = DONT_SALVAGE;
2586 #endif /* !AFS_DEMAND_ATTACH_FS */
2587 VAddToVolumeUpdateList_r(ec, vp);
2589 Log("VAttachVolume: Error adding volume to update list\n");
2596 Log("VOnline: volume %" AFS_VOLID_FMT " (%s) attached and online\n", afs_printable_VolumeId_lu(V_id(vp)),
2601 if (VRequiresPartLock()) {
2602 VUnlockPartition_r(partition);
2605 #ifdef AFS_DEMAND_ATTACH_FS
2606 /* attach failed; make sure we're in error state */
2607 if (vp && !VIsErrorState(V_attachState(vp))) {
2608 VChangeState_r(vp, VOL_STATE_ERROR);
2610 #endif /* AFS_DEMAND_ATTACH_FS */
2617 #ifdef AFS_DEMAND_ATTACH_FS
2618 /* VAttachVolumeByVp_r
2620 * finish attaching a volume that is
2621 * in a less than fully attached state
2623 /* caller MUST hold a ref count on vp */
2625 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
2627 char name[VMAXPATHLEN];
2629 struct DiskPartition64 *partp;
2633 Volume * nvp = NULL;
2634 VolumeStats stats_save;
2638 /* volume utility should never call AttachByVp */
2639 opr_Assert(programType == fileServer);
2641 volumeId = vp->hashid;
2642 partp = vp->partition;
2643 VolumeExternalName_r(volumeId, name, sizeof(name));
2646 /* if another thread is performing a blocking op, wait */
2647 VWaitExclusiveState_r(vp);
2649 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2651 /* if it's already attached, see if we can return it */
2652 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2653 VGetVolumeByVp_r(ec, vp);
2654 if (V_inUse(vp) == fileServer) {
2657 if (vp->specialStatus == VBUSY)
2659 VDetachVolume_r(ec, vp);
2661 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2667 /* pre-attach volume if it hasn't been done yet */
2669 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2670 (V_attachState(vp) == VOL_STATE_DELETED) ||
2671 (V_attachState(vp) == VOL_STATE_ERROR)) {
2672 nvp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2678 VCreateReservation_r(nvp);
2683 opr_Assert(vp != NULL);
2684 VChangeState_r(vp, VOL_STATE_ATTACHING);
2686 /* restore monotonically increasing stats */
2687 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2691 /* compute path to disk header */
2692 strcpy(path, VPartitionPath(partp));
2696 strcat(path, OS_DIRSEP);
2701 * NOTE: attach2 is entered without any locks, and returns
2702 * with vol_glock_mutex held */
2703 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2706 * the event that an error was encountered, or
2707 * the volume was not brought to an attached state
2708 * for any reason, skip to the end. We cannot
2709 * safely call VUpdateVolume unless we "own" it.
2713 (V_attachState(vp) != VOL_STATE_ATTACHED)) {
2717 VUpdateVolume_r(ec, vp, 0);
2719 Log("VAttachVolume: Error updating volume %" AFS_VOLID_FMT "\n",
2720 afs_printable_VolumeId_lu(vp->hashid));
2724 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2725 #ifndef AFS_DEMAND_ATTACH_FS
2726 /* This is a hack: by temporarily setting the incore
2727 * dontSalvage flag ON, the volume will be put back on the
2728 * Update list (with dontSalvage OFF again). It will then
2729 * come back in N minutes with DONT_SALVAGE eventually
2730 * set. This is the way that volumes that have never had
2731 * it set get it set; or that volumes that have been
2732 * offline without DONT SALVAGE having been set also
2733 * eventually get it set */
2734 V_dontSalvage(vp) = DONT_SALVAGE;
2735 #endif /* !AFS_DEMAND_ATTACH_FS */
2736 VAddToVolumeUpdateList_r(ec, vp);
2738 Log("VAttachVolume: Error adding volume %" AFS_VOLID_FMT " to update list\n",
2739 afs_printable_VolumeId_lu(vp->hashid));
2746 Log("VOnline: volume %" AFS_VOLID_FMT " (%s) attached and online\n",
2747 afs_printable_VolumeId_lu(V_id(vp)), V_name(vp));
2750 VCancelReservation_r(nvp);
2753 if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2754 if (vp && !VIsErrorState(V_attachState(vp))) {
2755 VChangeState_r(vp, VOL_STATE_ERROR);
2764 * lock a volume on disk (non-blocking).
2766 * @param[in] vp The volume to lock
2767 * @param[in] locktype READ_LOCK or WRITE_LOCK
2769 * @return operation status
2770 * @retval 0 success, lock was obtained
2771 * @retval EBUSY a conflicting lock was held by another process
2772 * @retval EIO error acquiring lock
2774 * @pre If we're in the fileserver, vp is in an exclusive state
2776 * @pre vp is not already locked
2779 VLockVolumeNB(Volume *vp, int locktype)
2783 opr_Assert(programType != fileServer
2784 || VIsExclusiveState(V_attachState(vp)));
2785 opr_Assert(!(V_attachFlags(vp) & VOL_LOCKED));
2787 code = VLockVolumeByIdNB(vp->hashid, vp->partition, locktype);
2789 V_attachFlags(vp) |= VOL_LOCKED;
2796 * unlock a volume on disk that was locked with VLockVolumeNB.
2798 * @param[in] vp volume to unlock
2800 * @pre If we're in the fileserver, vp is in an exclusive state
2802 * @pre vp has already been locked
2805 VUnlockVolume(Volume *vp)
2807 opr_Assert(programType != fileServer
2808 || VIsExclusiveState(V_attachState(vp)));
2809 opr_Assert((V_attachFlags(vp) & VOL_LOCKED));
2811 VUnlockVolumeById(vp->hashid, vp->partition);
2813 V_attachFlags(vp) &= ~VOL_LOCKED;
2815 #endif /* AFS_DEMAND_ATTACH_FS */
2818 * read in a vol header, possibly lock the vol header, and possibly check out
2819 * the vol header from the fileserver, as part of volume attachment.
2821 * @param[out] ec error code
2822 * @param[in] vp volume pointer object
2823 * @param[in] partp disk partition object of the attaching partition
2824 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
2826 * @param[in] peek 1 to just try to read in the volume header and make sure
2827 * we don't try to lock the vol, or check it out from
2828 * FSSYNC or anything like that; 0 otherwise, for 'normal'
2830 * @param[out] acheckedOut If we successfully checked-out the volume from
2831 * the fileserver (if we needed to), this is set
2832 * to 1, otherwise it is untouched.
2834 * @note As part of DAFS volume attachment, the volume header may be either
2835 * read- or write-locked to ensure mutual exclusion of certain volume
2836 * operations. In some cases in order to determine whether we need to
2837 * read- or write-lock the header, we need to read in the header to see
2838 * if the volume is RW or not. So, if we read in the header under a
2839 * read-lock and determine that we actually need a write-lock on the
2840 * volume header, this function will drop the read lock, acquire a write
2841 * lock, and read the header in again.
2844 attach_volume_header(Error *ec, Volume *vp, struct DiskPartition64 *partp,
2845 int mode, int peek, int *acheckedOut)
2847 struct VolumeDiskHeader diskHeader;
2848 struct VolumeHeader header;
2851 int lock_tries = 0, checkout_tries = 0;
2853 VolumeId volid = vp->hashid;
2854 #ifdef FSSYNC_BUILD_CLIENT
2855 int checkout, done_checkout = 0;
2856 #endif /* FSSYNC_BUILD_CLIENT */
2857 #ifdef AFS_DEMAND_ATTACH_FS
2858 int locktype = 0, use_locktype = -1;
2859 #endif /* AFS_DEMAND_ATTACH_FS */
2865 if (lock_tries > VOL_MAX_CHECKOUT_RETRIES) {
2866 Log("VAttachVolume: retried too many times trying to lock header for "
2867 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2868 VPartitionPath(partp));
2872 if (checkout_tries > VOL_MAX_CHECKOUT_RETRIES) {
2873 Log("VAttachVolume: retried too many times trying to checkout "
2874 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2875 VPartitionPath(partp));
2880 if (VReadVolumeDiskHeader(volid, partp, NULL)) {
2881 /* short-circuit the 'volume does not exist' case */
2886 #ifdef FSSYNC_BUILD_CLIENT
2887 checkout = !done_checkout;
2889 if (!peek && checkout && VMustCheckoutVolume(mode)) {
2891 memset(&res, 0, sizeof(res));
2893 if (FSYNC_VolOp(volid, partp->name, FSYNC_VOL_NEEDVOLUME, mode, &res)
2896 if (res.hdr.reason == FSYNC_SALVAGE) {
2897 Log("VAttachVolume: file server says volume %lu is salvaging\n",
2898 afs_printable_uint32_lu(volid));
2901 Log("VAttachVolume: attach of volume %lu apparently denied by file server\n",
2902 afs_printable_uint32_lu(volid));
2903 *ec = VNOVOL; /* XXXX */
2911 #ifdef AFS_DEMAND_ATTACH_FS
2912 if (use_locktype < 0) {
2913 /* don't know whether vol is RO or RW; assume it's RO and we can retry
2914 * if it turns out to be RW */
2915 locktype = VVolLockType(mode, 0);
2918 /* a previous try says we should use use_locktype to lock the volume,
2920 locktype = use_locktype;
2923 if (!peek && locktype) {
2924 code = VLockVolumeNB(vp, locktype);
2926 if (code == EBUSY) {
2927 Log("VAttachVolume: another program has vol %lu locked\n",
2928 afs_printable_uint32_lu(volid));
2930 Log("VAttachVolume: error %d trying to lock vol %lu\n",
2931 code, afs_printable_uint32_lu(volid));
2938 #endif /* AFS_DEMAND_ATTACH_FS */
2940 code = VReadVolumeDiskHeader(volid, partp, &diskHeader);
2950 DiskToVolumeHeader(&header, &diskHeader);
2952 IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header.parent,
2953 header.largeVnodeIndex);
2954 IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header.parent,
2955 header.smallVnodeIndex);
2956 IH_INIT(vp->diskDataHandle, partp->device, header.parent,
2958 IH_INIT(vp->linkHandle, partp->device, header.parent, header.linkTable);
2961 /* only need to do this once */
2963 GetVolumeHeader(vp);
2967 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2968 /* demand attach changes the V_PEEK mechanism
2970 * we can now suck the current disk data structure over
2971 * the fssync interface without going to disk
2973 * (technically, we don't need to restrict this feature
2974 * to demand attach fileservers. However, I'm trying
2975 * to limit the number of common code changes)
2977 if (VCanUseFSSYNC() && (mode == V_PEEK || peek)) {
2979 res.payload.len = sizeof(VolumeDiskData);
2980 res.payload.buf = &(V_disk(vp));
2982 if (FSYNC_VolOp(vp->hashid,
2984 FSYNC_VOL_QUERY_HDR,
2987 goto disk_header_loaded;
2990 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2991 (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2992 sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2994 #ifdef AFS_DEMAND_ATTACH_FS
2997 IncUInt64(&VStats.hdr_loads);
2998 IncUInt64(&vp->stats.hdr_loads);
3000 #endif /* AFS_DEMAND_ATTACH_FS */
3003 Log("VAttachVolume: Error reading diskDataHandle header for vol %lu; "
3004 "error=%u\n", afs_printable_uint32_lu(volid), *ec);
3008 #ifdef AFS_DEMAND_ATTACH_FS
3009 # ifdef FSSYNC_BUILD_CLIENT
3011 # endif /* FSSYNC_BUILD_CLIENT */
3013 /* if the lock type we actually used to lock the volume is different than
3014 * the lock type we should have used, retry with the lock type we should
3016 use_locktype = VVolLockType(mode, VolumeWriteable(vp));
3017 if (locktype != use_locktype) {
3021 #endif /* AFS_DEMAND_ATTACH_FS */
3026 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
3027 if (!peek && *ec == 0 && retry == 0 && VMustCheckoutVolume(mode)) {
3029 code = FSYNC_VerifyCheckout(volid, partp->name, FSYNC_VOL_NEEDVOLUME, mode);
3031 if (code == SYNC_DENIED) {
3032 /* must retry checkout; fileserver no longer thinks we have
3038 } else if (code != SYNC_OK) {
3042 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
3045 /* either we are going to be called again for a second pass, or we
3046 * encountered an error; clean up in either case */
3048 #ifdef AFS_DEMAND_ATTACH_FS
3049 if ((V_attachFlags(vp) & VOL_LOCKED)) {
3052 #endif /* AFS_DEMAND_ATTACH_FS */
3053 if (vp->linkHandle) {
3054 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
3055 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
3056 IH_RELEASE(vp->diskDataHandle);
3057 IH_RELEASE(vp->linkHandle);
3063 FreeVolumeHeader(vp);
3073 #ifdef AFS_DEMAND_ATTACH_FS
3075 attach_check_vop(Error *ec, VolumeId volid, struct DiskPartition64 *partp,
3076 Volume *vp, int *acheckedOut)
3080 if (vp->pending_vol_op) {
3084 if (vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningUnknown) {
3086 code = VVolOpLeaveOnlineNoHeader_r(vp, vp->pending_vol_op);
3088 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3089 } else if (code == 0) {
3090 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3093 /* we need the vol header to determine if the volume can be
3094 * left online for the vop, so... get the header */
3098 /* attach header with peek=1 to avoid checking out the volume
3099 * or locking it; we just want the header info, we're not
3100 * messing with the volume itself at all */
3101 attach_volume_header(ec, vp, partp, V_PEEK, 1, acheckedOut);
3108 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
3109 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3111 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3114 /* make sure we grab a new vol header and re-open stuff on
3115 * actual attachment; we can't keep the data we grabbed, since
3116 * it was not done under a lock and thus not safe */
3117 FreeVolumeHeader(vp);
3118 VReleaseVolumeHandles_r(vp);
3121 /* see if the pending volume op requires exclusive access */
3122 switch (vp->pending_vol_op->vol_op_state) {
3123 case FSSYNC_VolOpPending:
3124 /* this should never happen */
3125 opr_Assert(vp->pending_vol_op->vol_op_state
3126 != FSSYNC_VolOpPending);
3129 case FSSYNC_VolOpRunningUnknown:
3130 /* this should never happen; we resolved 'unknown' above */
3131 opr_Assert(vp->pending_vol_op->vol_op_state
3132 != FSSYNC_VolOpRunningUnknown);
3135 case FSSYNC_VolOpRunningOffline:
3136 /* mark the volume down */
3138 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3140 /* do not set V_offlineMessage here; we don't have ownership of
3141 * the volume (and probably do not have the header loaded), so we
3142 * can't alter the disk header */
3144 /* check to see if we should set the specialStatus flag */
3145 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
3146 /* don't overwrite specialStatus if it was already set to
3147 * something else (e.g. VMOVED) */
3148 if (!vp->specialStatus) {
3149 vp->specialStatus = VBUSY;
3161 #endif /* AFS_DEMAND_ATTACH_FS */
3164 * volume attachment helper function.
3166 * @param[out] ec error code
3167 * @param[in] volumeId volume ID of the attaching volume
3168 * @param[in] path full path to the volume header .vol file
3169 * @param[in] partp disk partition object for the attaching partition
3170 * @param[in] vp volume object; vp->hashid, vp->device, vp->partition,
3171 * vp->vnode_list, vp->rx_call_list, and V_attachCV (for
3172 * DAFS) should already be initialized
3173 * @param[in] isbusy 1 if vp->specialStatus should be set to VBUSY; that is,
3174 * if there is a volume operation running for this volume
3175 * that should set the volume to VBUSY during its run. 0
3176 * otherwise. (see VVolOpSetVBusy_r)
3177 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
3179 * @param[out] acheckedOut If we successfully checked-out the volume from
3180 * the fileserver (if we needed to), this is set
3181 * to 1, otherwise it is 0.
3183 * @return pointer to the semi-attached volume pointer
3184 * @retval NULL an error occurred (check value of *ec)
3185 * @retval vp volume successfully attaching
3187 * @pre no locks held
3189 * @post VOL_LOCK held
3192 attach2(Error * ec, VolumeId volumeId, char *path, struct DiskPartition64 *partp,
3193 Volume * vp, int isbusy, int mode, int *acheckedOut)
3195 /* have we read in the header successfully? */
3196 int read_header = 0;
3198 #ifdef AFS_DEMAND_ATTACH_FS
3199 /* should we FreeVolume(vp) instead of VCheckFree(vp) in the error
3203 /* in the case of an error, to what state should the volume be
3205 VolState error_state = VOL_STATE_ERROR;
3206 #endif /* AFS_DEMAND_ATTACH_FS */
3210 vp->vnodeIndex[vLarge].handle = NULL;
3211 vp->vnodeIndex[vSmall].handle = NULL;
3212 vp->diskDataHandle = NULL;
3213 vp->linkHandle = NULL;
3217 #ifdef AFS_DEMAND_ATTACH_FS
3218 attach_check_vop(ec, volumeId, partp, vp, acheckedOut);
3220 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3223 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3224 #endif /* !AFS_DEMAND_ATTACH_FS */
3226 if (*ec == VNOVOL) {
3227 /* if the volume doesn't exist, skip straight to 'error' so we don't
3228 * request a salvage */
3229 goto unlocked_error;
3235 /* ensure that we don't override specialStatus if it was set to
3236 * something else (e.g. VMOVED) */
3237 if (isbusy && !vp->specialStatus) {
3238 vp->specialStatus = VBUSY;
3240 vp->shuttingDown = 0;
3241 vp->goingOffline = 0;
3243 #ifdef AFS_DEMAND_ATTACH_FS
3244 vp->stats.last_attach = FT_ApproxTime();
3245 vp->stats.attaches++;
3249 IncUInt64(&VStats.attaches);
3250 vp->cacheCheck = ++VolumeCacheCheck;
3251 /* just in case this ever rolls over */
3252 if (!vp->cacheCheck)
3253 vp->cacheCheck = ++VolumeCacheCheck;
3256 #ifdef AFS_DEMAND_ATTACH_FS
3257 V_attachFlags(vp) |= VOL_HDR_LOADED;
3258 vp->stats.last_hdr_load = vp->stats.last_attach;
3259 #endif /* AFS_DEMAND_ATTACH_FS */
3263 struct IndexFileHeader iHead;
3266 * We just read in the diskstuff part of the header. If the detailed
3267 * volume stats area has not yet been initialized, we should bzero the
3268 * area and mark it as initialized.
3270 if (!(V_stat_initialized(vp))) {
3271 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
3272 V_stat_initialized(vp) = 1;
3275 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
3276 (char *)&iHead, sizeof(iHead),
3277 SMALLINDEXMAGIC, SMALLINDEXVERSION);
3280 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
3285 struct IndexFileHeader iHead;
3287 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
3288 (char *)&iHead, sizeof(iHead),
3289 LARGEINDEXMAGIC, LARGEINDEXVERSION);
3292 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
3296 #ifdef AFS_NAMEI_ENV
3298 struct versionStamp stamp;
3300 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
3301 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
3304 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
3307 #endif /* AFS_NAMEI_ENV */
3309 #if defined(AFS_DEMAND_ATTACH_FS)
3310 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
3312 if (!VCanScheduleSalvage()) {
3313 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3315 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3320 /* volume operation in progress */
3322 /* we have already transitioned the vp away from ATTACHING state, so we
3323 * can go right to the end of attach2, and we do not need to transition
3325 goto error_notbroken;
3327 #else /* AFS_DEMAND_ATTACH_FS */
3329 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3330 goto unlocked_error;
3332 #endif /* AFS_DEMAND_ATTACH_FS */
3334 if (V_needsSalvaged(vp)) {
3335 if (vp->specialStatus)
3336 vp->specialStatus = 0;
3338 #if defined(AFS_DEMAND_ATTACH_FS)
3339 if (!VCanScheduleSalvage()) {
3340 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
3342 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3345 #else /* AFS_DEMAND_ATTACH_FS */
3347 #endif /* AFS_DEMAND_ATTACH_FS */
3353 vp->nextVnodeUnique = V_uniquifier(vp);
3355 if (VShouldCheckInUse(mode) && V_inUse(vp) && VolumeWriteable(vp)) {
3356 if (!V_needsSalvaged(vp)) {
3357 V_needsSalvaged(vp) = 1;
3358 VUpdateVolume_r(ec, vp, 0);
3360 #if defined(AFS_DEMAND_ATTACH_FS)
3361 if (!VCanScheduleSalvage()) {
3362 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3364 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3367 #else /* AFS_DEMAND_ATTACH_FS */
3368 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3370 #endif /* AFS_DEMAND_ATTACH_FS */
3375 if (programType == fileServer && V_destroyMe(vp) == DESTROY_ME) {
3376 /* Only check destroyMe if we are the fileserver, since the
3377 * volserver et al sometimes need to work with volumes with
3378 * destroyMe set. Examples are 'temporary' volumes the
3379 * volserver creates, and when we create a volume (destroyMe
3380 * is set on creation; sometimes a separate volserver
3381 * transaction is created to clear destroyMe).
3384 #if defined(AFS_DEMAND_ATTACH_FS)
3385 /* schedule a salvage so the volume goes away on disk */
3386 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3387 VChangeState_r(vp, VOL_STATE_ERROR);
3390 #endif /* AFS_DEMAND_ATTACH_FS */
3391 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
3396 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
3397 #ifndef BITMAP_LATER
3398 if (programType == fileServer && VolumeWriteable(vp)) {
3400 for (i = 0; i < nVNODECLASSES; i++) {
3401 VGetBitmap_r(ec, vp, i);
3403 #ifdef AFS_DEMAND_ATTACH_FS
3404 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3406 #endif /* AFS_DEMAND_ATTACH_FS */
3407 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
3413 #endif /* BITMAP_LATER */
3415 if (VInit >= 2 && V_needsCallback(vp)) {
3416 if (V_BreakVolumeCallbacks) {
3417 Log("VAttachVolume: Volume %lu was changed externally; breaking callbacks\n",
3418 afs_printable_uint32_lu(V_id(vp)));
3419 V_needsCallback(vp) = 0;
3421 (*V_BreakVolumeCallbacks) (V_id(vp));
3424 VUpdateVolume_r(ec, vp, 0);
3426 #ifdef FSSYNC_BUILD_CLIENT
3427 else if (VCanUseFSSYNC()) {
3428 afs_int32 fsync_code;
3430 V_needsCallback(vp) = 0;
3432 fsync_code = FSYNC_VolOp(V_id(vp), NULL, FSYNC_VOL_BREAKCBKS, FSYNC_WHATEVER, NULL);
3436 V_needsCallback(vp) = 1;
3437 Log("Error trying to tell the fileserver to break callbacks for "
3438 "changed volume %lu; error code %ld\n",
3439 afs_printable_uint32_lu(V_id(vp)),
3440 afs_printable_int32_ld(fsync_code));
3442 VUpdateVolume_r(ec, vp, 0);
3445 #endif /* FSSYNC_BUILD_CLIENT */
3448 Log("VAttachVolume: error %d clearing needsCallback on volume "
3449 "%lu; needs salvage\n", (int)*ec,
3450 afs_printable_uint32_lu(V_id(vp)));
3451 #ifdef AFS_DEMAND_ATTACH_FS
3452 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3454 #else /* !AFS_DEMAND_ATTACH_FS */
3456 #endif /* !AFS_DEMAND_ATTACh_FS */
3461 if (programType == fileServer) {
3462 if (vp->specialStatus)
3463 vp->specialStatus = 0;
3464 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
3465 V_inUse(vp) = fileServer;
3466 V_offlineMessage(vp)[0] = '\0';
3468 #ifdef AFS_DEMAND_ATTACH_FS
3469 /* check if the volume is actually usable. only do this for DAFS; for
3470 * non-DAFS, volumes that are not inService/blessed can still be
3471 * attached, even if clients cannot access them. this is relevant
3472 * because for non-DAFS, we try to attach the volume when e.g.
3473 * volserver gives us back then vol when its done with it, but
3474 * volserver may give us back a volume that is not inService/blessed. */
3478 /* Put the vol into PREATTACHED state, so if someone tries to
3479 * access it again, we try to attach, see that we're not blessed,
3480 * and give a VNOVOL error again. Putting it into UNATTACHED state
3481 * would result in a VOFFLINE error instead. */
3482 error_state = VOL_STATE_PREATTACHED;
3484 /* mimic e.g. GetVolume errors */
3485 if (!V_blessed(vp)) {
3486 Log("Volume %lu offline: not blessed\n", afs_printable_uint32_lu(V_id(vp)));
3487 FreeVolumeHeader(vp);
3488 } else if (!V_inService(vp)) {
3489 Log("Volume %lu offline: not in service\n", afs_printable_uint32_lu(V_id(vp)));
3490 FreeVolumeHeader(vp);
3492 Log("Volume %lu offline: needs salvage\n", afs_printable_uint32_lu(V_id(vp)));
3494 error_state = VOL_STATE_ERROR;
3495 /* see if we can recover */
3496 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3501 #endif /* AFS_DEMAND_ATTACH_FS */
3503 #ifdef AFS_DEMAND_ATTACH_FS
3504 if ((mode != V_PEEK) && (mode != V_SECRETLY) && (mode != V_READONLY))
3505 V_inUse(vp) = programType;
3506 #endif /* AFS_DEMAND_ATTACH_FS */
3507 V_checkoutMode(vp) = mode;
3510 AddVolumeToHashTable(vp, V_id(vp));
3511 #ifdef AFS_DEMAND_ATTACH_FS
3512 if (VCanUnlockAttached() && (V_attachFlags(vp) & VOL_LOCKED)) {
3515 if ((programType != fileServer) ||
3516 (V_inUse(vp) == fileServer)) {
3517 AddVolumeToVByPList_r(vp);
3519 VChangeState_r(vp, VOL_STATE_ATTACHED);
3521 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3530 #ifdef AFS_DEMAND_ATTACH_FS
3531 if (!VIsErrorState(V_attachState(vp))) {
3532 if (programType != fileServer && *ec == VNOVOL) {
3533 /* do not log anything in this case; it is common for
3534 * non-fileserver programs to fail here with VNOVOL, since that
3535 * is what happens when they simply try to use a volume, but that
3536 * volume doesn't exist. */
3538 } else if (VIsErrorState(error_state)) {
3539 Log("attach2: forcing vol %" AFS_VOLID_FMT " to error state (state %u flags 0x%x ec %d)\n",
3540 afs_printable_VolumeId_lu(vp->hashid), V_attachState(vp),
3541 V_attachFlags(vp), *ec);
3543 VChangeState_r(vp, error_state);
3545 #endif /* AFS_DEMAND_ATTACH_FS */
3548 VReleaseVolumeHandles_r(vp);
3551 #ifdef AFS_DEMAND_ATTACH_FS
3553 if (VCheckSalvage(vp) == VCHECK_SALVAGE_FAIL) {
3554 /* The salvage could not be scheduled with the salvage server
3555 * due to a hard error. Reset the error code to prevent retry loops by
3557 if (*ec == VSALVAGING) {
3566 #else /* !AFS_DEMAND_ATTACH_FS */
3568 #endif /* !AFS_DEMAND_ATTACH_FS */
3572 /* Attach an existing volume.
3573 The volume also normally goes online at this time.
3574 An offline volume must be reattached to make it go online.
3578 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
3582 retVal = VAttachVolume_r(ec, volumeId, mode);
3588 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
3591 VGetVolumePath(ec, volumeId, &part, &name);
3595 vp = VGetVolume_r(&error, volumeId);
3597 opr_Assert(V_inUse(vp) == 0);
3598 VDetachVolume_r(ec, vp);
3602 return VAttachVolumeByName_r(ec, part, name, mode);
3605 /* Increment a reference count to a volume, sans context swaps. Requires
3606 * possibly reading the volume header in from the disk, since there's
3607 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
3609 * N.B. This call can fail if we can't read in the header!! In this case
3610 * we still guarantee we won't context swap, but the ref count won't be
3611 * incremented (otherwise we'd violate the invariant).
3613 /* NOTE: with the demand attach fileserver extensions, the global lock
3614 * is dropped within VHold */
3615 #ifdef AFS_DEMAND_ATTACH_FS
3617 VHold_r(Volume * vp)
3621 VCreateReservation_r(vp);
3622 VWaitExclusiveState_r(vp);
3624 LoadVolumeHeader(&error, vp);
3626 VCancelReservation_r(vp);
3630 VCancelReservation_r(vp);
3633 #else /* AFS_DEMAND_ATTACH_FS */
3635 VHold_r(Volume * vp)
3639 LoadVolumeHeader(&error, vp);
3645 #endif /* AFS_DEMAND_ATTACH_FS */
3647 /**** volume timeout-related stuff ****/
3649 #ifdef AFS_PTHREAD_ENV
3651 static struct timespec *shutdown_timeout;
3652 static pthread_once_t shutdown_timeout_once = PTHREAD_ONCE_INIT;
3655 VTimedOut(const struct timespec *ts)
3660 if (ts->tv_sec == 0) {
3661 /* short-circuit; this will have always timed out */
3665 code = gettimeofday(&tv, NULL);
3667 Log("Error %d from gettimeofday, assuming we have not timed out\n", errno);
3668 /* assume no timeout; failure mode is we just wait longer than normal
3669 * instead of returning errors when we shouldn't */
3673 if (tv.tv_sec < ts->tv_sec ||
3674 (tv.tv_sec == ts->tv_sec && tv.tv_usec*1000 < ts->tv_nsec)) {
3683 * Calculate an absolute timeout.
3685 * @param[out] ts A timeout that is "timeout" seconds from now, if we return
3686 * NULL, the memory is not touched
3687 * @param[in] timeout How long the timeout should be from now
3689 * @return timeout to use
3690 * @retval NULL no timeout; wait forever
3691 * @retval non-NULL the given value for "ts"
3695 static struct timespec *
3696 VCalcTimeout(struct timespec *ts, afs_int32 timeout)
3706 ts->tv_sec = ts->tv_nsec = 0;
3710 code = gettimeofday(&now, NULL);
3712 Log("Error %d from gettimeofday, falling back to 'forever' timeout\n", errno);
3716 ts->tv_sec = now.tv_sec + timeout;
3717 ts->tv_nsec = now.tv_usec * 1000;
3723 * Initialize the shutdown_timeout global.
3726 VShutdownTimeoutInit(void)
3728 struct timespec *ts;
3730 ts = malloc(sizeof(*ts));
3732 shutdown_timeout = VCalcTimeout(ts, vol_opts.offline_shutdown_timeout);
3734 if (!shutdown_timeout) {
3740 * Figure out the timeout that should be used for waiting for offline volumes.
3742 * @param[out] ats Storage space for a local timeout value if needed
3744 * @return The timeout value that should be used
3745 * @retval NULL No timeout; wait forever for offlining volumes
3746 * @retval non-NULL A pointer to the absolute time that should be used as
3747 * the deadline for waiting for offlining volumes.
3749 * @note If we return non-NULL, the pointer we return may or may not be the
3752 static const struct timespec *
3753 VOfflineTimeout(struct timespec *ats)
3755 if (vol_shutting_down) {
3756 opr_Verify(pthread_once(&shutdown_timeout_once,
3757 VShutdownTimeoutInit) == 0);
3758 return shutdown_timeout;
3760 return VCalcTimeout(ats, vol_opts.offline_timeout);
3764 #else /* AFS_PTHREAD_ENV */
3766 /* Waiting a certain amount of time for offlining volumes is not supported
3767 * for LWP due to a lack of primitives. So, we never time out */
3768 # define VTimedOut(x) (0)
3769 # define VOfflineTimeout(x) (NULL)
3771 #endif /* !AFS_PTHREAD_ENV */
3779 retVal = VHold_r(vp);
3786 VIsGoingOffline_r(struct Volume *vp)
3790 if (vp->goingOffline) {
3791 if (vp->specialStatus) {
3792 code = vp->specialStatus;
3793 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3804 * Tell the caller if a volume is waiting to go offline.
3806 * @param[in] vp The volume we want to know about
3808 * @return volume status
3809 * @retval 0 volume is not waiting to go offline, go ahead and use it
3810 * @retval nonzero volume is waiting to offline, and give the returned code
3811 * as an error to anyone accessing the volume
3813 * @pre VOL_LOCK is NOT held
3814 * @pre caller holds a heavyweight reference on vp
3817 VIsGoingOffline(struct Volume *vp)
3822 code = VIsGoingOffline_r(vp);
3829 * Register an RX call with a volume.
3831 * @param[inout] ec Error code; if unset when passed in, may be set if
3832 * the volume starts going offline
3833 * @param[out] client_ec @see GetVolume
3834 * @param[in] vp Volume struct
3835 * @param[in] cbv VCallByVol struct containing the RX call to register
3837 * @pre VOL_LOCK held
3838 * @pre caller holds heavy ref on vp
3843 VRegisterCall_r(Error *ec, Error *client_ec, Volume *vp, struct VCallByVol *cbv)
3846 #ifdef AFS_DEMAND_ATTACH_FS
3848 /* just in case the volume started going offline after we got the
3849 * reference to it... otherwise, if the volume started going
3850 * offline right at the end of GetVolume(), we might race with the
3851 * RX call scanner, and return success and add our cbv to the
3852 * rx_call_list _after_ the scanner has scanned the list. */
3853 *ec = VIsGoingOffline_r(vp);
3859 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3860 VWaitStateChange_r(vp);
3862 #endif /* AFS_DEMAND_ATTACH_FS */
3864 queue_Prepend(&vp->rx_call_list, cbv);
3869 * Deregister an RX call with a volume.
3871 * @param[in] vp Volume struct
3872 * @param[in] cbv VCallByVol struct containing the RX call to deregister
3874 * @pre VOL_LOCK held
3875 * @pre caller holds heavy ref on vp
3880 VDeregisterCall_r(Volume *vp, struct VCallByVol *cbv)
3882 if (cbv && queue_IsOnQueue(cbv)) {
3883 #ifdef AFS_DEMAND_ATTACH_FS
3884 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3885 VWaitStateChange_r(vp);
3887 #endif /* AFS_DEMAND_ATTACH_FS */
3893 /***************************************************/
3894 /* get and put volume routines */
3895 /***************************************************/
3898 * put back a heavyweight reference to a volume object.
3900 * @param[in] vp volume object pointer
3902 * @pre VOL_LOCK held
3904 * @post heavyweight volume reference put back.
3905 * depending on state, volume may have been taken offline,
3906 * detached, salvaged, freed, etc.
3908 * @internal volume package internal use only
3911 VPutVolume_r(Volume * vp)
3913 opr_Verify(--vp->nUsers >= 0);
3914 if (vp->nUsers == 0) {
3916 ReleaseVolumeHeader(vp->header);
3917 #ifdef AFS_DEMAND_ATTACH_FS
3918 if (!VCheckDetach(vp)) {
3922 #else /* AFS_DEMAND_ATTACH_FS */
3924 #endif /* AFS_DEMAND_ATTACH_FS */
3929 VPutVolume(Volume * vp)
3937 * Puts a volume reference obtained with VGetVolumeWithCall.
3939 * @param[in] vp Volume struct
3940 * @param[in] cbv VCallByVol struct given to VGetVolumeWithCall, or NULL if none
3942 * @pre VOL_LOCK is NOT held
3945 VPutVolumeWithCall(Volume *vp, struct VCallByVol *cbv)
3948 VDeregisterCall_r(vp, cbv);
3953 /* Get a pointer to an attached volume. The pointer is returned regardless
3954 of whether or not the volume is in service or on/off line. An error
3955 code, however, is returned with an indication of the volume's status */
3957 VGetVolume(Error * ec, Error * client_ec, VolumeId volumeId)
3961 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
3967 * Get a volume reference associated with an RX call.
3969 * @param[out] ec @see GetVolume
3970 * @param[out] client_ec @see GetVolume
3971 * @param[in] volumeId @see GetVolume
3972 * @param[in] ts How long to wait for going-offline volumes (absolute time).
3973 * If NULL, wait forever. If ts->tv_sec == 0, return immediately
3974 * with an error if the volume is going offline.
3975 * @param[in] cbv Contains an RX call to be associated with this volume
3976 * reference. This call may be interrupted if the volume is
3977 * requested to go offline while we hold a ref on it. Give NULL
3978 * to not associate an RX call with this reference.
3980 * @return @see GetVolume
3982 * @note for LWP builds, ts must be NULL
3984 * @note A reference obtained with this function MUST be put back with
3985 * VPutVolumeWithCall
3988 VGetVolumeWithCall(Error * ec, Error * client_ec, VolumeId volumeId,
3989 const struct timespec *ts, struct VCallByVol *cbv)
3993 retVal = GetVolume(ec, client_ec, volumeId, NULL, ts);
3994 VRegisterCall_r(ec, client_ec, retVal, cbv);
4000 VGetVolume_r(Error * ec, VolumeId volumeId)
4002 return GetVolume(ec, NULL, volumeId, NULL, NULL);
4005 /* try to get a volume we've previously looked up */
4006 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
4008 VGetVolumeByVp_r(Error * ec, Volume * vp)
4010 return GetVolume(ec, NULL, vp->hashid, vp, NULL);
4014 * private interface for getting a volume handle
4016 * @param[out] ec error code (0 if no error)
4017 * @param[out] client_ec wire error code to be given to clients
4018 * @param[in] volumeId ID of the volume we want
4019 * @param[in] hint optional hint for hash lookups, or NULL
4020 * @param[in] timeout absolute deadline for waiting for the volume to go
4021 * offline, if it is going offline. NULL to wait forever.
4023 * @return a volume handle for the specified volume
4024 * @retval NULL an error occurred, or the volume is in such a state that
4025 * we cannot load a header or return any volume struct
4027 * @note for DAFS, caller must NOT hold a ref count on 'hint'
4029 * @note 'timeout' is only checked if the volume is actually going offline; so
4030 * if you pass timeout->tv_sec = 0, this will exhibit typical
4031 * nonblocking behavior.
4033 * @note for LWP builds, 'timeout' must be NULL
4036 GetVolume(Error * ec, Error * client_ec, VolumeId volumeId, Volume * hint,
4037 const struct timespec *timeout)
4040 /* pull this profiling/debugging code out of regular builds */
4042 #define VGET_CTR_INC(x) x++
4043 unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
4044 0, V7 = 0, V8 = 0, V9 = 0;
4045 unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
4047 #define VGET_CTR_INC(x)
4049 #ifdef AFS_DEMAND_ATTACH_FS
4050 Volume *avp, * rvp = hint;
4054 * if VInit is zero, the volume package dynamic
4055 * data structures have not been initialized yet,
4056 * and we must immediately return an error
4062 *client_ec = VOFFLINE;
4067 #ifdef AFS_DEMAND_ATTACH_FS
4069 VCreateReservation_r(rvp);
4071 #endif /* AFS_DEMAND_ATTACH_FS */
4079 vp = VLookupVolume_r(ec, volumeId, vp);
4085 #ifdef AFS_DEMAND_ATTACH_FS
4086 if (rvp && (rvp != vp)) {
4087 /* break reservation on old vp */
4088 VCancelReservation_r(rvp);
4091 #endif /* AFS_DEMAND_ATTACH_FS */
4097 /* Until we have reached an initialization level of 2
4098 * we don't know whether this volume exists or not.
4099 * We can't sleep and retry later because before a volume
4100 * is attached, the caller tries to get it first. Just
4101 * return VOFFLINE and the caller can choose whether to
4102 * retry the command or not. */
4112 IncUInt64(&VStats.hdr_gets);
4114 #ifdef AFS_DEMAND_ATTACH_FS
4115 /* block if someone else is performing an exclusive op on this volume */
4118 VCreateReservation_r(rvp);
4120 VWaitExclusiveState_r(vp);
4122 /* short circuit with VNOVOL in the following circumstances:
4125 * - VOL_STATE_SHUTTING_DOWN
4127 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
4128 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN)) {
4135 * short circuit with VOFFLINE for VOL_STATE_UNATTACHED/GOING_OFFLINE and
4136 * VNOVOL for VOL_STATE_DELETED
4138 if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
4139 (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) ||
4140 (V_attachState(vp) == VOL_STATE_DELETED)) {
4141 if (vp->specialStatus) {
4142 *ec = vp->specialStatus;
4143 } else if (V_attachState(vp) == VOL_STATE_DELETED) {
4152 /* allowable states:
4159 if (vp->salvage.requested) {
4160 VUpdateSalvagePriority_r(vp);
4163 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
4164 if (vp->specialStatus) {
4165 *ec = vp->specialStatus;
4169 avp = VAttachVolumeByVp_r(ec, vp, 0);
4172 /* VAttachVolumeByVp_r can return a pointer
4173 * != the vp passed to it under certain
4174 * conditions; make sure we don't leak
4175 * reservations if that happens */
4177 VCancelReservation_r(rvp);
4179 VCreateReservation_r(rvp);
4190 if (vp->specialStatus) {
4191 *ec = vp->specialStatus;
4196 if (vp->specialStatus) {
4197 *ec = vp->specialStatus;
4210 if (VIsSalvaging(vp) || (*ec == VSALVAGING)) {
4212 /* see CheckVnode() in afsfileprocs.c for an explanation
4213 * of this error code logic */
4214 afs_uint32 now = FT_ApproxTime();
4215 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
4218 *client_ec = VRESTARTING;
4226 if (VIsErrorState(V_attachState(vp))) {
4227 /* make sure we don't take a vp in VOL_STATE_ERROR state and use
4228 * it, or transition it out of that state */
4237 * this test MUST happen after VAttachVolymeByVp, so we have no
4238 * conflicting vol op. (attach2 would have errored out if we had one;
4239 * specifically attach_check_vop must have detected a conflicting vop)
4241 opr_Assert(!vp->pending_vol_op || vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningOnline);
4243 #endif /* AFS_DEMAND_ATTACH_FS */
4245 LoadVolumeHeader(ec, vp);
4248 /* Only log the error if it was a totally unexpected error. Simply
4249 * a missing inode is likely to be caused by the volume being deleted */
4250 if (errno != ENXIO || LogLevel)
4251 Log("Volume %" AFS_VOLID_FMT ": couldn't reread volume header\n",
4252 afs_printable_VolumeId_lu(vp->hashid));
4253 #ifdef AFS_DEMAND_ATTACH_FS
4254 if (VCanScheduleSalvage()) {
4255 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0 /*flags*/);
4260 #else /* AFS_DEMAND_ATTACH_FS */
4263 #endif /* AFS_DEMAND_ATTACH_FS */
4268 if (vp->shuttingDown) {
4275 if (programType == fileServer) {
4277 if (vp->goingOffline) {
4278 if (timeout && VTimedOut(timeout)) {
4279 /* we've timed out; don't wait for the vol */
4282 #ifdef AFS_DEMAND_ATTACH_FS
4283 /* wait for the volume to go offline */
4284 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
4285 VTimedWaitStateChange_r(vp, timeout, NULL);
4287 #elif defined(AFS_PTHREAD_ENV)
4288 VOL_CV_TIMEDWAIT(&vol_put_volume_cond, timeout, NULL);
4289 #else /* AFS_PTHREAD_ENV */
4290 /* LWP has no timed wait, so the caller better not be
4292 opr_Assert(!timeout);
4293 LWP_WaitProcess(VPutVolume);
4294 #endif /* AFS_PTHREAD_ENV */
4298 if (vp->specialStatus) {
4300 *ec = vp->specialStatus;
4301 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
4304 } else if (V_inUse(vp) == 0 || vp->goingOffline) {
4315 #ifdef AFS_DEMAND_ATTACH_FS
4316 /* if no error, bump nUsers */
4319 VLRU_UpdateAccess_r(vp);
4322 VCancelReservation_r(rvp);
4325 if (client_ec && !*client_ec) {
4328 #else /* AFS_DEMAND_ATTACH_FS */
4329 /* if no error, bump nUsers */
4336 #endif /* AFS_DEMAND_ATTACH_FS */
4339 opr_Assert(vp || *ec);
4344 /***************************************************/
4345 /* Volume offline/detach routines */
4346 /***************************************************/
4348 /* caller MUST hold a heavyweight ref on vp */
4349 #ifdef AFS_DEMAND_ATTACH_FS
4351 VTakeOffline_r(Volume * vp)
4355 opr_Assert(vp->nUsers > 0);
4356 opr_Assert(programType == fileServer);
4358 VCreateReservation_r(vp);
4359 VWaitExclusiveState_r(vp);
4361 vp->goingOffline = 1;
4362 V_needsSalvaged(vp) = 1;
4364 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
4365 VCancelReservation_r(vp);
4367 #else /* AFS_DEMAND_ATTACH_FS */
4369 VTakeOffline_r(Volume * vp)
4371 opr_Assert(vp->nUsers > 0);
4372 opr_Assert(programType == fileServer);
4374 vp->goingOffline = 1;
4375 V_needsSalvaged(vp) = 1;
4377 #endif /* AFS_DEMAND_ATTACH_FS */
4380 VTakeOffline(Volume * vp)
4388 * force a volume offline.
4390 * @param[in] vp volume object pointer
4391 * @param[in] flags flags (see note below)
4393 * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
4394 * used when VUpdateVolume_r needs to call VForceOffline_r
4395 * (which in turn would normally call VUpdateVolume_r)
4397 * @see VUpdateVolume_r
4399 * @pre VOL_LOCK must be held.
4400 * for DAFS, caller must hold ref.
4402 * @note for DAFS, it _is safe_ to call this function from an
4405 * @post needsSalvaged flag is set.
4406 * for DAFS, salvage is requested.
4407 * no further references to the volume through the volume
4408 * package will be honored.
4409 * all file descriptor and vnode caches are invalidated.
4411 * @warning this is a heavy-handed interface. it results in
4412 * a volume going offline regardless of the current
4413 * reference count state.
4415 * @internal volume package internal use only
4418 VForceOffline_r(Volume * vp, int flags)
4422 #ifdef AFS_DEMAND_ATTACH_FS
4423 VChangeState_r(vp, VOL_STATE_ERROR);
4428 strcpy(V_offlineMessage(vp),
4429 "Forced offline due to internal error: volume needs to be salvaged");
4430 Log("Volume %" AFS_VOLID_FMT " forced offline: it needs salvaging!\n", afs_printable_VolumeId_lu(V_id(vp)));
4433 vp->goingOffline = 0;
4434 V_needsSalvaged(vp) = 1;
4435 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
4436 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
4439 #ifdef AFS_DEMAND_ATTACH_FS
4440 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0 /*flags*/);
4441 #endif /* AFS_DEMAND_ATTACH_FS */
4443 #ifdef AFS_PTHREAD_ENV
4444 opr_cv_broadcast(&vol_put_volume_cond);
4445 #else /* AFS_PTHREAD_ENV */
4446 LWP_NoYieldSignal(VPutVolume);
4447 #endif /* AFS_PTHREAD_ENV */
4449 VReleaseVolumeHandles_r(vp);
4453 * force a volume offline.
4455 * @param[in] vp volume object pointer
4457 * @see VForceOffline_r
4460 VForceOffline(Volume * vp)
4463 VForceOffline_r(vp, 0);
4468 * Iterate over the RX calls associated with a volume, and interrupt them.
4470 * @param[in] vp The volume whose RX calls we want to scan
4472 * @pre VOL_LOCK held
4475 VScanCalls_r(struct Volume *vp)
4477 struct VCallByVol *cbv, *ncbv;
4479 #ifdef AFS_DEMAND_ATTACH_FS
4480 VolState state_save;
4483 if (queue_IsEmpty(&vp->rx_call_list))
4484 return; /* no calls to interrupt */
4485 if (!vol_opts.interrupt_rxcall)
4486 return; /* we have no function with which to interrupt calls */
4487 err = VIsGoingOffline_r(vp);
4489 return; /* we're not going offline anymore */
4491 #ifdef AFS_DEMAND_ATTACH_FS
4492 VWaitExclusiveState_r(vp);
4493 state_save = VChangeState_r(vp, VOL_STATE_SCANNING_RXCALLS);
4495 #endif /* AFS_DEMAND_ATTACH_FS */
4497 for(queue_Scan(&vp->rx_call_list, cbv, ncbv, VCallByVol)) {
4499 struct rx_peer *peer;
4501 peer = rx_PeerOf(rx_ConnectionOf(cbv->call));
4503 Log("Offlining volume %" AFS_VOLID_FMT " while client %s:%u is trying to read "
4504 "from it; kicking client off with error %ld\n",
4505 afs_printable_VolumeId_lu(vp->hashid),
4506 afs_inet_ntoa_r(rx_HostOf(peer), hoststr),
4507 (unsigned) ntohs(rx_PortOf(peer)),
4510 (*vol_opts.interrupt_rxcall) (cbv->call, err);
4513 #ifdef AFS_DEMAND_ATTACH_FS
4515 VChangeState_r(vp, state_save);
4516 #endif /* AFS_DEMAND_ATTACH_FS */
4519 #ifdef AFS_DEMAND_ATTACH_FS
4521 * Wait for a vp to go offline.
4523 * @param[out] ec 1 if a salvage on the volume has been requested and
4524 * salvok == 0, 0 otherwise
4525 * @param[in] vp The volume to wait for
4526 * @param[in] salvok If 0, we return immediately with *ec = 1 if the volume
4527 * has been requested to salvage. Otherwise we keep waiting
4528 * until the volume has gone offline.
4530 * @pre VOL_LOCK held
4531 * @pre caller holds a lightweight ref on vp
4536 VWaitForOfflineByVp_r(Error *ec, struct Volume *vp, int salvok)
4538 struct timespec timeout_ts;
4539 const struct timespec *ts;
4542 ts = VOfflineTimeout(&timeout_ts);
4546 while (!VIsOfflineState(V_attachState(vp)) && !timedout) {
4547 if (!salvok && vp->salvage.requested) {
4551 VTimedWaitStateChange_r(vp, ts, &timedout);
4554 /* we didn't time out, so the volume must be offline, so we're done */
4558 /* If we got here, we timed out waiting for the volume to go offline.
4559 * Kick off the accessing RX calls and wait again */
4563 while (!VIsOfflineState(V_attachState(vp))) {
4564 if (!salvok && vp->salvage.requested) {
4569 VWaitStateChange_r(vp);
4573 #else /* AFS_DEMAND_ATTACH_FS */
4576 * Wait for a volume to go offline.
4578 * @pre VOL_LOCK held
4580 * @note non-DAFS only (for DAFS, use @see WaitForOfflineByVp_r)
4583 VWaitForOffline_r(Error *ec, VolumeId volid)
4586 const struct timespec *ts;
4587 #ifdef AFS_PTHREAD_ENV
4588 struct timespec timeout_ts;
4591 ts = VOfflineTimeout(&timeout_ts);
4593 vp = GetVolume(ec, NULL, volid, NULL, ts);
4595 /* error occurred so bad that we can't even get a vp; we have no
4596 * information on the vol so we don't know whether to wait, so just
4600 if (!VIsGoingOffline_r(vp)) {
4601 /* volume is no longer going offline, so we're done */
4606 /* If we got here, we timed out waiting for the volume to go offline.
4607 * Kick off the accessing RX calls and wait again */
4613 vp = VGetVolume_r(ec, volid);
4615 /* In case it was reattached... */
4619 #endif /* !AFS_DEMAND_ATTACH_FS */
4621 /* The opposite of VAttachVolume. The volume header is written to disk, with
4622 the inUse bit turned off. A copy of the header is maintained in memory,
4623 however (which is why this is VOffline, not VDetach).
4626 VOffline_r(Volume * vp, char *message)
4629 #ifndef AFS_DEMAND_ATTACH_FS
4630 VolumeId vid = V_id(vp);
4633 opr_Assert(programType != volumeUtility && programType != volumeServer);
4638 if (V_offlineMessage(vp)[0] == '\0')
4639 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4640 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4642 vp->goingOffline = 1;
4643 #ifdef AFS_DEMAND_ATTACH_FS
4644 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4645 VCreateReservation_r(vp);
4647 VWaitForOfflineByVp_r(&error, vp, 1);
4648 VCancelReservation_r(vp);
4649 #else /* AFS_DEMAND_ATTACH_FS */
4651 VWaitForOffline_r(&error, vid);
4652 #endif /* AFS_DEMAND_ATTACH_FS */
4655 #ifdef AFS_DEMAND_ATTACH_FS
4657 * Take a volume offline in order to perform a volume operation.
4659 * @param[inout] ec address in which to store error code
4660 * @param[in] vp volume object pointer
4661 * @param[in] message volume offline status message
4664 * - VOL_LOCK is held
4665 * - caller MUST hold a heavyweight ref on vp
4668 * - volume is taken offline
4669 * - if possible, volume operation is promoted to running state
4670 * - on failure, *ec is set to nonzero
4672 * @note Although this function does not return any value, it may
4673 * still fail to promote our pending volume operation to
4674 * a running state. Any caller MUST check the value of *ec,
4675 * and MUST NOT blindly assume success.
4677 * @warning if the caller does not hold a lightweight ref on vp,
4678 * then it MUST NOT reference vp after this function
4679 * returns to the caller.
4681 * @internal volume package internal use only
4684 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
4687 opr_Assert(vp->pending_vol_op);
4693 if (V_offlineMessage(vp)[0] == '\0')
4694 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4695 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4697 vp->goingOffline = 1;
4698 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4699 VCreateReservation_r(vp);
4702 if (vp->pending_vol_op->com.programType != salvageServer) {
4703 /* do not give corrupted volumes to the volserver */
4708 VWaitForOfflineByVp_r(ec, vp, salvok);
4710 VCancelReservation_r(vp);
4712 #endif /* AFS_DEMAND_ATTACH_FS */
4715 VOffline(Volume * vp, char *message)
4718 VOffline_r(vp, message);
4722 /* This gets used for the most part by utility routines that don't want
4723 * to keep all the volume headers around. Generally, the file server won't
4724 * call this routine, because then the offline message in the volume header
4725 * (or other information) won't be available to clients. For NAMEI, also
4726 * close the file handles. However, the fileserver does call this during
4727 * an attach following a volume operation.
4730 VDetachVolume_r(Error * ec, Volume * vp)
4732 #ifdef FSSYNC_BUILD_CLIENT
4734 struct DiskPartition64 *tpartp;
4735 int notifyServer = 0;
4736 int useDone = FSYNC_VOL_ON;
4738 if (VCanUseFSSYNC()) {
4739 notifyServer = vp->needsPutBack;
4740 if (V_destroyMe(vp) == DESTROY_ME)
4741 useDone = FSYNC_VOL_LEAVE_OFF;
4742 # ifdef AFS_DEMAND_ATTACH_FS
4743 else if (!V_blessed(vp) || !V_inService(vp))
4744 useDone = FSYNC_VOL_LEAVE_OFF;
4747 # ifdef AFS_DEMAND_ATTACH_FS
4748 if (V_needsSalvaged(vp)) {
4750 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, 0);
4753 tpartp = vp->partition;
4755 #endif /* FSSYNC_BUILD_CLIENT */
4757 *ec = 0; /* always "succeeds" */
4758 DeleteVolumeFromHashTable(vp);
4759 vp->shuttingDown = 1;
4760 #ifdef AFS_DEMAND_ATTACH_FS
4761 DeleteVolumeFromVByPList_r(vp);
4763 VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
4765 if (programType != fileServer)
4767 #endif /* AFS_DEMAND_ATTACH_FS */
4769 /* Will be detached sometime in the future--this is OK since volume is offline */
4771 /* XXX the following code should really be moved to VCheckDetach() since the volume
4772 * is not technically detached until the refcounts reach zero
4774 #ifdef FSSYNC_BUILD_CLIENT
4775 if (VCanUseFSSYNC() && notifyServer) {
4776 if (notifyServer == VOL_PUTBACK_DELETE) {
4777 /* Only send FSYNC_VOL_DONE if the volume was actually deleted.
4778 * volserver code will set needsPutBack to VOL_PUTBACK_DELETE
4779 * to signify a deleted volume. */
4780 useDone = FSYNC_VOL_DONE;
4783 * Note: The server is not notified in the case of a bogus volume
4784 * explicitly to make it possible to create a volume, do a partial
4785 * restore, then abort the operation without ever putting the volume
4786 * online. This is essential in the case of a volume move operation
4787 * between two partitions on the same server. In that case, there
4788 * would be two instances of the same volume, one of them bogus,
4789 * which the file server would attempt to put on line
4791 FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
4792 /* XXX this code path is only hit by volume utilities, thus
4793 * V_BreakVolumeCallbacks will always be NULL. if we really
4794 * want to break callbacks in this path we need to use FSYNC_VolOp() */
4796 /* Dettaching it so break all callbacks on it */
4797 if (V_BreakVolumeCallbacks) {
4798 Log("volume %u detached; breaking all call backs\n", volume);
4799 (*V_BreakVolumeCallbacks) (volume);
4803 #endif /* FSSYNC_BUILD_CLIENT */
4807 VDetachVolume(Error * ec, Volume * vp)
4810 VDetachVolume_r(ec, vp);
4815 /***************************************************/
4816 /* Volume fd/inode handle closing routines */
4817 /***************************************************/
4819 /* For VDetachVolume, we close all cached file descriptors, but keep
4820 * the Inode handles in case we need to read from a busy volume.
4822 /* for demand attach, caller MUST hold ref count on vp */
4824 VCloseVolumeHandles_r(Volume * vp)
4826 #ifdef AFS_DEMAND_ATTACH_FS
4827 VolState state_save;
4829 state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
4834 DFlushVolume(vp->hashid);
4836 #ifdef AFS_DEMAND_ATTACH_FS
4840 /* DAFS: VCloseVnodeFiles_r drops the glock internally */
4841 VCloseVnodeFiles_r(vp);
4843 #ifdef AFS_DEMAND_ATTACH_FS
4847 /* Too time consuming and unnecessary for the volserver */
4848 if (programType == fileServer) {
4849 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4850 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4851 IH_CONDSYNC(vp->diskDataHandle);
4852 #ifdef AFS_NAMEI_ENV
4853 IH_CONDSYNC(vp->linkHandle);
4854 #endif /* AFS_NAMEI_ENV */
4857 IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
4858 IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
4859 IH_REALLYCLOSE(vp->diskDataHandle);
4860 IH_REALLYCLOSE(vp->linkHandle);
4862 #ifdef AFS_DEMAND_ATTACH_FS
4863 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4868 VChangeState_r(vp, state_save);
4872 /* For both VForceOffline and VOffline, we close all relevant handles.
4873 * For VOffline, if we re-attach the volume, the files may possible be
4874 * different than before.
4876 /* for demand attach, caller MUST hold a ref count on vp */
4878 VReleaseVolumeHandles_r(Volume * vp)
4880 #ifdef AFS_DEMAND_ATTACH_FS
4881 VolState state_save;
4883 state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
4888 DFlushVolume(vp->hashid);
4890 #ifdef AFS_DEMAND_ATTACH_FS
4894 VReleaseVnodeFiles_r(vp); /* DAFS: releases the glock internally */
4896 #ifdef AFS_DEMAND_ATTACH_FS
4900 /* Too time consuming and unnecessary for the volserver */
4901 if (programType == fileServer) {
4902 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4903 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4904 IH_CONDSYNC(vp->diskDataHandle);
4905 #ifdef AFS_NAMEI_ENV
4906 IH_CONDSYNC(vp->linkHandle);
4907 #endif /* AFS_NAMEI_ENV */
4910 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
4911 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
4912 IH_RELEASE(vp->diskDataHandle);
4913 IH_RELEASE(vp->linkHandle);
4915 #ifdef AFS_DEMAND_ATTACH_FS
4916 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4921 VChangeState_r(vp, state_save);
4926 /***************************************************/
4927 /* Volume write and fsync routines */
4928 /***************************************************/
4931 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
4933 #ifdef AFS_DEMAND_ATTACH_FS
4934 VolState state_save;
4936 if (flags & VOL_UPDATE_WAIT) {
4937 VCreateReservation_r(vp);
4938 VWaitExclusiveState_r(vp);
4943 if (programType == fileServer) {
4945 V_uniquifier(vp) = V_nextVnodeUnique(vp);
4948 V_nextVnodeUnique(vp) + VOLUME_UPDATE_UNIQUIFIER_BUMP;
4949 if (V_uniquifier(vp) < V_nextVnodeUnique(vp)) {
4950 /* uniquifier rolled over; reset the counters */
4951 V_nextVnodeUnique(vp) = 2; /* 1 is reserved for the root vnode */
4953 V_nextVnodeUnique(vp) + VOLUME_UPDATE_UNIQUIFIER_BUMP;
4958 #ifdef AFS_DEMAND_ATTACH_FS
4959 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4963 WriteVolumeHeader_r(ec, vp);
4965 #ifdef AFS_DEMAND_ATTACH_FS
4967 VChangeState_r(vp, state_save);
4968 if (flags & VOL_UPDATE_WAIT) {
4969 VCancelReservation_r(vp);
4974 Log("VUpdateVolume: error updating volume header, volume %" AFS_VOLID_FMT " (%s)\n",
4975 afs_printable_VolumeId_lu(V_id(vp)), V_name(vp));
4976 /* try to update on-disk header,
4977 * while preventing infinite recursion */
4978 if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
4979 VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
4985 VUpdateVolume(Error * ec, Volume * vp)
4988 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4993 VSyncVolume_r(Error * ec, Volume * vp, int flags)
4997 #ifdef AFS_DEMAND_ATTACH_FS
4998 VolState state_save;
5001 if (flags & VOL_SYNC_WAIT) {
5002 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
5004 VUpdateVolume_r(ec, vp, 0);
5007 #ifdef AFS_DEMAND_ATTACH_FS
5008 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
5011 fdP = IH_OPEN(V_diskDataHandle(vp));
5012 opr_Assert(fdP != NULL);
5013 code = FDH_SYNC(fdP);
5014 opr_Assert(code == 0);
5016 #ifdef AFS_DEMAND_ATTACH_FS
5018 VChangeState_r(vp, state_save);
5024 VSyncVolume(Error * ec, Volume * vp)
5027 VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
5032 /***************************************************/
5033 /* Volume dealloaction routines */
5034 /***************************************************/
5036 #ifdef AFS_DEMAND_ATTACH_FS
5038 FreeVolume(Volume * vp)
5040 /* free the heap space, iff it's safe.
5041 * otherwise, pull it out of the hash table, so it
5042 * will get deallocated when all refs to it go away */
5043 if (!VCheckFree(vp)) {
5044 DeleteVolumeFromHashTable(vp);
5045 DeleteVolumeFromVByPList_r(vp);
5047 /* make sure we invalidate the header cache entry */
5048 FreeVolumeHeader(vp);
5051 #endif /* AFS_DEMAND_ATTACH_FS */
5054 ReallyFreeVolume(Volume * vp)
5059 #ifdef AFS_DEMAND_ATTACH_FS
5061 VChangeState_r(vp, VOL_STATE_FREED);
5062 if (vp->pending_vol_op)
5063 free(vp->pending_vol_op);
5064 #endif /* AFS_DEMAND_ATTACH_FS */
5065 for (i = 0; i < nVNODECLASSES; i++)
5066 if (vp->vnodeIndex[i].bitmap)
5067 free(vp->vnodeIndex[i].bitmap);
5068 FreeVolumeHeader(vp);
5069 #ifndef AFS_DEMAND_ATTACH_FS
5070 DeleteVolumeFromHashTable(vp);
5071 #endif /* AFS_DEMAND_ATTACH_FS */
5075 /* check to see if we should shutdown this volume
5076 * returns 1 if volume was freed, 0 otherwise */
5077 #ifdef AFS_DEMAND_ATTACH_FS
5079 VCheckDetach(Volume * vp)
5084 if (vp->nUsers || vp->nWaiters)
5087 if (vp->shuttingDown) {
5089 if ((programType != fileServer) &&
5090 (V_inUse(vp) == programType) &&
5091 ((V_checkoutMode(vp) == V_VOLUPD) ||
5092 (V_checkoutMode(vp) == V_SECRETLY) ||
5093 ((V_checkoutMode(vp) == V_CLONE) &&
5094 (VolumeWriteable(vp))))) {
5096 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5098 Log("VCheckDetach: volume header update for volume %" AFS_VOLID_FMT " "
5099 "failed with errno %d\n", afs_printable_VolumeId_lu(vp->hashid), errno);
5102 VReleaseVolumeHandles_r(vp);
5104 ReallyFreeVolume(vp);
5105 if (programType == fileServer) {
5106 opr_cv_broadcast(&vol_put_volume_cond);
5111 #else /* AFS_DEMAND_ATTACH_FS */
5113 VCheckDetach(Volume * vp)
5121 if (vp->shuttingDown) {
5123 if ((programType != fileServer) &&
5124 (V_inUse(vp) == programType) &&
5125 ((V_checkoutMode(vp) == V_VOLUPD) ||
5126 (V_checkoutMode(vp) == V_SECRETLY) ||
5127 ((V_checkoutMode(vp) == V_CLONE) &&
5128 (VolumeWriteable(vp))))) {
5130 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5132 Log("VCheckDetach: volume header update for volume %" AFS_VOLID_FMT " failed with errno %d\n",
5133 afs_printable_VolumeId_lu(vp->hashid), errno);
5136 VReleaseVolumeHandles_r(vp);
5137 ReallyFreeVolume(vp);
5138 if (programType == fileServer) {
5139 #if defined(AFS_PTHREAD_ENV)
5140 opr_cv_broadcast(&vol_put_volume_cond);
5141 #else /* AFS_PTHREAD_ENV */
5142 LWP_NoYieldSignal(VPutVolume);
5143 #endif /* AFS_PTHREAD_ENV */
5148 #endif /* AFS_DEMAND_ATTACH_FS */
5150 /* check to see if we should offline this volume
5151 * return 1 if volume went offline, 0 otherwise */
5152 #ifdef AFS_DEMAND_ATTACH_FS
5154 VCheckOffline(Volume * vp)
5158 if (vp->goingOffline && !vp->nUsers) {
5160 opr_Assert(programType == fileServer);
5161 opr_Assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
5162 (V_attachState(vp) != VOL_STATE_FREED) &&
5163 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
5164 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
5165 (V_attachState(vp) != VOL_STATE_DELETED));
5169 * VOL_STATE_GOING_OFFLINE
5170 * VOL_STATE_SHUTTING_DOWN
5171 * VIsErrorState(V_attachState(vp))
5172 * VIsExclusiveState(V_attachState(vp))
5175 VCreateReservation_r(vp);
5176 VChangeState_r(vp, VOL_STATE_OFFLINING);
5179 /* must clear the goingOffline flag before we drop the glock */
5180 vp->goingOffline = 0;
5185 /* perform async operations */
5186 VUpdateVolume_r(&error, vp, 0);
5187 VCloseVolumeHandles_r(vp);
5190 if (V_offlineMessage(vp)[0]) {
5191 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5192 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5193 V_offlineMessage(vp));
5195 Log("VOffline: Volume %lu (%s) is now offline\n",
5196 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5200 /* invalidate the volume header cache entry */
5201 FreeVolumeHeader(vp);
5203 /* if nothing changed state to error or salvaging,
5204 * drop state to unattached */
5205 if (!VIsErrorState(V_attachState(vp))) {
5206 VChangeState_r(vp, VOL_STATE_UNATTACHED);
5208 VCancelReservation_r(vp);
5209 /* no usage of vp is safe beyond this point */
5213 #else /* AFS_DEMAND_ATTACH_FS */
5215 VCheckOffline(Volume * vp)
5219 if (vp->goingOffline && !vp->nUsers) {
5221 opr_Assert(programType == fileServer);
5224 vp->goingOffline = 0;
5226 VUpdateVolume_r(&error, vp, 0);
5227 VCloseVolumeHandles_r(vp);
5229 if (V_offlineMessage(vp)[0]) {
5230 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5231 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5232 V_offlineMessage(vp));
5234 Log("VOffline: Volume %lu (%s) is now offline\n",
5235 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5238 FreeVolumeHeader(vp);
5239 #ifdef AFS_PTHREAD_ENV
5240 opr_cv_broadcast(&vol_put_volume_cond);
5241 #else /* AFS_PTHREAD_ENV */
5242 LWP_NoYieldSignal(VPutVolume);
5243 #endif /* AFS_PTHREAD_ENV */
5247 #endif /* AFS_DEMAND_ATTACH_FS */
5249 /***************************************************/
5250 /* demand attach fs ref counting routines */
5251 /***************************************************/
5253 #ifdef AFS_DEMAND_ATTACH_FS
5254 /* the following two functions handle reference counting for
5255 * asynchronous operations on volume structs.
5257 * their purpose is to prevent a VDetachVolume or VShutdown
5258 * from free()ing the Volume struct during an async i/o op */
5260 /* register with the async volume op ref counter */
5261 /* VCreateReservation_r moved into inline code header because it
5262 * is now needed in vnode.c -- tkeiser 11/20/2007
5266 * decrement volume-package internal refcount.
5268 * @param vp volume object pointer
5270 * @internal volume package internal use only
5273 * @arg VOL_LOCK is held
5274 * @arg lightweight refcount held
5276 * @post volume waiters refcount is decremented; volume may
5277 * have been deallocated/shutdown/offlined/salvaged/
5278 * whatever during the process
5280 * @warning once you have tossed your last reference (you can acquire
5281 * lightweight refs recursively) it is NOT SAFE to reference
5282 * a volume object pointer ever again
5284 * @see VCreateReservation_r
5286 * @note DEMAND_ATTACH_FS only
5289 VCancelReservation_r(Volume * vp)
5291 opr_Verify(--vp->nWaiters >= 0);
5292 if (vp->nWaiters == 0) {
5294 if (!VCheckDetach(vp)) {
5301 /* check to see if we should free this volume now
5302 * return 1 if volume was freed, 0 otherwise */
5304 VCheckFree(Volume * vp)
5307 if ((vp->nUsers == 0) &&
5308 (vp->nWaiters == 0) &&
5309 !(V_attachFlags(vp) & (VOL_IN_HASH |
5313 ReallyFreeVolume(vp);
5318 #endif /* AFS_DEMAND_ATTACH_FS */
5321 /***************************************************/
5322 /* online volume operations routines */
5323 /***************************************************/
5325 #ifdef AFS_DEMAND_ATTACH_FS
5327 * register a volume operation on a given volume.
5329 * @param[in] vp volume object
5330 * @param[in] vopinfo volume operation info object
5332 * @pre VOL_LOCK is held
5334 * @post volume operation info object attached to volume object.
5335 * volume operation statistics updated.
5337 * @note by "attached" we mean a copy of the passed in object is made
5339 * @internal volume package internal use only
5342 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5344 FSSYNC_VolOp_info * info;
5346 /* attach a vol op info node to the volume struct */
5347 info = malloc(sizeof(FSSYNC_VolOp_info));
5348 opr_Assert(info != NULL);
5349 memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
5350 vp->pending_vol_op = info;
5353 vp->stats.last_vol_op = FT_ApproxTime();
5354 vp->stats.vol_ops++;
5355 IncUInt64(&VStats.vol_ops);
5361 * deregister the volume operation attached to this volume.
5363 * @param[in] vp volume object pointer
5365 * @pre VOL_LOCK is held
5367 * @post the volume operation info object is detached from the volume object
5369 * @internal volume package internal use only
5372 VDeregisterVolOp_r(Volume * vp)
5374 if (vp->pending_vol_op) {
5375 free(vp->pending_vol_op);
5376 vp->pending_vol_op = NULL;
5380 #endif /* AFS_DEMAND_ATTACH_FS */
5383 * determine whether it is safe to leave a volume online during
5384 * the volume operation described by the vopinfo object.
5386 * @param[in] vp volume object
5387 * @param[in] vopinfo volume operation info object
5389 * @return whether it is safe to leave volume online
5390 * @retval 0 it is NOT SAFE to leave the volume online
5391 * @retval 1 it is safe to leave the volume online during the operation
5394 * @arg VOL_LOCK is held
5395 * @arg disk header attached to vp (heavyweight ref on vp will guarantee
5396 * this condition is met)
5398 * @internal volume package internal use only
5401 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5403 return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
5404 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5405 (vopinfo->com.reason == V_READONLY ||
5406 (!VolumeWriteable(vp) &&
5407 (vopinfo->com.reason == V_CLONE ||
5408 vopinfo->com.reason == V_DUMP)))));
5412 * same as VVolOpLeaveOnline_r, but does not require a volume with an attached
5415 * @param[in] vp volume object
5416 * @param[in] vopinfo volume operation info object
5418 * @return whether it is safe to leave volume online
5419 * @retval 0 it is NOT SAFE to leave the volume online
5420 * @retval 1 it is safe to leave the volume online during the operation
5421 * @retval -1 unsure; volume header is required in order to know whether or
5422 * not is is safe to leave the volume online
5424 * @pre VOL_LOCK is held
5426 * @internal volume package internal use only
5429 VVolOpLeaveOnlineNoHeader_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5431 /* follow the logic in VVolOpLeaveOnline_r; this is the same, except
5432 * assume that we don't know VolumeWriteable; return -1 if the answer
5433 * depends on VolumeWriteable */
5435 if (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline) {
5438 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5439 vopinfo->com.reason == V_READONLY) {
5443 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5444 (vopinfo->com.reason == V_CLONE ||
5445 vopinfo->com.reason == V_DUMP)) {
5447 /* must know VolumeWriteable */
5454 * determine whether VBUSY should be set during this volume operation.
5456 * @param[in] vp volume object
5457 * @param[in] vopinfo volume operation info object
5459 * @return whether VBUSY should be set
5460 * @retval 0 VBUSY does NOT need to be set
5461 * @retval 1 VBUSY SHOULD be set
5463 * @pre VOL_LOCK is held
5465 * @internal volume package internal use only
5468 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5470 return ((vopinfo->com.command == FSYNC_VOL_OFF &&
5471 vopinfo->com.reason == FSYNC_SALVAGE) ||
5472 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5473 (vopinfo->com.reason == V_CLONE ||
5474 vopinfo->com.reason == V_DUMP)));
5478 /***************************************************/
5479 /* online salvager routines */
5480 /***************************************************/
5481 #if defined(AFS_DEMAND_ATTACH_FS)
5484 * offline a volume to let it be salvaged.
5486 * @param[in] vp Volume to offline
5488 * @return whether we offlined the volume successfully
5489 * @retval 0 volume was not offlined
5490 * @retval 1 volume is now offline
5492 * @note This is similar to VCheckOffline, but slightly different. We do not
5493 * deal with vp->goingOffline, and we try to avoid touching the volume
5494 * header except just to set needsSalvaged
5496 * @pre VOL_LOCK held
5497 * @pre vp->nUsers == 0
5498 * @pre V_attachState(vp) == VOL_STATE_SALVAGE_REQ
5501 VOfflineForSalvage_r(struct Volume *vp)
5505 VCreateReservation_r(vp);
5506 VWaitExclusiveState_r(vp);
5508 if (vp->nUsers || V_attachState(vp) == VOL_STATE_SALVAGING) {
5509 /* Someone's using the volume, or someone got to scheduling the salvage
5510 * before us. I don't think either of these should be possible, as we
5511 * should gain no new heavyweight references while we're trying to
5512 * salvage, but just to be sure... */
5513 VCancelReservation_r(vp);
5517 VChangeState_r(vp, VOL_STATE_OFFLINING);
5521 V_needsSalvaged(vp) = 1;
5522 /* ignore error; updating needsSalvaged is just best effort */
5523 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
5525 VCloseVolumeHandles_r(vp);
5527 FreeVolumeHeader(vp);
5529 /* volume has been effectively offlined; we can mark it in the SALVAGING
5530 * state now, which lets FSSYNC give it away */
5531 VChangeState_r(vp, VOL_STATE_SALVAGING);
5533 VCancelReservation_r(vp);
5539 * check whether a salvage needs to be performed on this volume.
5541 * @param[in] vp pointer to volume object
5543 * @return status code
5544 * @retval VCHECK_SALVAGE_OK (0) no pending salvage
5545 * @retval VCHECK_SALVAGE_SCHEDULED (1) salvage has been scheduled
5546 * @retval VCHECK_SALVAGE_ASYNC (2) salvage being scheduled
5547 * @retval VCHECK_SALVAGE_DENIED (3) salvage not scheduled; denied
5548 * @retval VCHECK_SALVAGE_FAIL (4) salvage not scheduled; failed
5550 * @pre VOL_LOCK is held
5552 * @post if salvage request flag is set and nUsers and nWaiters are zero,
5553 * then a salvage will be requested
5555 * @note this is one of the event handlers called by VCancelReservation_r
5557 * @note the caller must check if the volume needs to be freed after calling
5558 * this; the volume may not have any references or be on any lists after
5559 * we return, and we do not free it
5561 * @see VCancelReservation_r
5563 * @internal volume package internal use only.
5566 VCheckSalvage(Volume * vp)
5568 int ret = VCHECK_SALVAGE_OK;
5570 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5571 if (!vp->salvage.requested) {
5572 return VCHECK_SALVAGE_OK;
5575 return VCHECK_SALVAGE_ASYNC;
5578 /* prevent recursion; some of the code below creates and removes
5579 * lightweight refs, which can call VCheckSalvage */
5580 if (vp->salvage.scheduling) {
5581 return VCHECK_SALVAGE_ASYNC;
5583 vp->salvage.scheduling = 1;
5585 if (V_attachState(vp) == VOL_STATE_SALVAGE_REQ) {
5586 if (!VOfflineForSalvage_r(vp)) {
5587 vp->salvage.scheduling = 0;
5588 return VCHECK_SALVAGE_FAIL;
5592 if (vp->salvage.requested) {
5593 ret = VScheduleSalvage_r(vp);
5595 vp->salvage.scheduling = 0;
5596 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5601 * request volume salvage.
5603 * @param[out] ec computed client error code
5604 * @param[in] vp volume object pointer
5605 * @param[in] reason reason code (passed to salvageserver via SALVSYNC)
5606 * @param[in] flags see flags note below
5609 * VOL_SALVAGE_NO_OFFLINE do not need to wait to offline the volume; it has
5610 * not been fully attached
5612 * @pre VOL_LOCK is held.
5614 * @post volume state is changed.
5615 * for fileserver, salvage will be requested once refcount reaches zero.
5617 * @return operation status code
5618 * @retval 0 volume salvage will occur
5619 * @retval 1 volume salvage could not be scheduled
5623 * @note in the fileserver, this call does not synchronously schedule a volume
5624 * salvage. rather, it sets volume state so that when volume refcounts
5625 * reach zero, a volume salvage will occur. by "refcounts", we mean both
5626 * nUsers and nWaiters must be zero.
5628 * @internal volume package internal use only.
5631 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
5635 * for DAFS volume utilities that are not supposed to schedule salvages,
5636 * just transition to error state instead
5638 if (!VCanScheduleSalvage()) {
5639 VChangeState_r(vp, VOL_STATE_ERROR);
5644 if (programType != fileServer && !VCanUseFSSYNC()) {
5645 VChangeState_r(vp, VOL_STATE_ERROR);
5650 if (!vp->salvage.requested) {
5651 vp->salvage.requested = 1;
5652 vp->salvage.reason = reason;
5653 vp->stats.last_salvage = FT_ApproxTime();
5655 /* Note that it is not possible for us to reach this point if a
5656 * salvage is already running on this volume (even if the fileserver
5657 * was restarted during the salvage). If a salvage were running, the
5658 * salvager would have write-locked the volume header file, so when
5659 * we tried to lock the volume header, the lock would have failed,
5660 * and we would have failed during attachment prior to calling
5661 * VRequestSalvage. So we know that we can schedule salvages without
5662 * fear of a salvage already running for this volume. */
5664 if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
5666 /* if we don't need to offline the volume, we can go directly
5667 * to SALVAGING. SALVAGING says the volume is offline and is
5668 * either salvaging or ready to be handed to the salvager.
5669 * SALVAGE_REQ says that we want to salvage the volume, but we
5670 * are waiting for it to go offline first. */
5671 if (flags & VOL_SALVAGE_NO_OFFLINE) {
5672 VChangeState_r(vp, VOL_STATE_SALVAGING);
5674 VChangeState_r(vp, VOL_STATE_SALVAGE_REQ);
5675 if (vp->nUsers == 0) {
5676 /* normally VOfflineForSalvage_r would be called from
5677 * PutVolume et al when nUsers reaches 0, but if
5678 * it's already 0, just do it ourselves, since PutVolume
5679 * isn't going to get called */
5680 VOfflineForSalvage_r(vp);
5683 /* If we are non-fileserver, we're telling the fileserver to
5684 * salvage the vol, so we don't need to give it back separately. */
5685 vp->needsPutBack = 0;
5689 Log("VRequestSalvage: volume %" AFS_VOLID_FMT " online salvaged too many times; forced offline.\n", afs_printable_VolumeId_lu(vp->hashid));
5691 /* make sure neither VScheduleSalvage_r nor
5692 * VUpdateSalvagePriority_r try to schedule another salvage */
5693 vp->salvage.requested = vp->salvage.scheduled = 0;
5695 VChangeState_r(vp, VOL_STATE_ERROR);
5704 * update salvageserver scheduling priority for a volume.
5706 * @param[in] vp pointer to volume object
5708 * @return operation status
5710 * @retval 1 request denied, or SALVSYNC communications failure
5712 * @pre VOL_LOCK is held.
5714 * @post in-core salvage priority counter is incremented. if at least
5715 * SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
5716 * last SALVSYNC_RAISEPRIO request, we contact the salvageserver
5717 * to update its priority queue. if no salvage is scheduled,
5718 * this function is a no-op.
5720 * @note DAFS fileserver only
5722 * @note this should be called whenever a VGetVolume fails due to a
5723 * pending salvage request
5725 * @todo should set exclusive state and drop glock around salvsync call
5727 * @internal volume package internal use only.
5730 VUpdateSalvagePriority_r(Volume * vp)
5734 #ifdef SALVSYNC_BUILD_CLIENT
5739 now = FT_ApproxTime();
5741 /* update the salvageserver priority queue occasionally so that
5742 * frequently requested volumes get moved to the head of the queue
5744 if ((vp->salvage.scheduled) &&
5745 (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
5746 code = SALVSYNC_SalvageVolume(vp->hashid,
5747 VPartitionPath(vp->partition),
5752 vp->stats.last_salvage_req = now;
5753 if (code != SYNC_OK) {
5757 #endif /* SALVSYNC_BUILD_CLIENT */
5762 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5764 /* A couple of little helper functions. These return true if we tried to
5765 * use this mechanism to schedule a salvage, false if we haven't tried.
5766 * If we did try a salvage then the results are contained in code.
5770 try_SALVSYNC(Volume *vp, char *partName, int *code) {
5771 #ifdef SALVSYNC_BUILD_CLIENT
5772 if (VCanUseSALVSYNC()) {
5773 Log("Scheduling salvage for volume %" AFS_VOLID_FMT " on part %s over SALVSYNC\n",
5774 afs_printable_VolumeId_lu(vp->hashid), partName);
5776 /* can't use V_id() since there's no guarantee
5777 * we have the disk data header at this point */
5778 *code = SALVSYNC_SalvageVolume(vp->hashid,
5791 try_FSSYNC(Volume *vp, char *partName, int *code) {
5792 #ifdef FSSYNC_BUILD_CLIENT
5793 if (VCanUseFSSYNC()) {
5794 Log("Scheduling salvage for volume %" AFS_VOLID_FMT " on part %s over FSSYNC\n",
5795 afs_printable_VolumeId_lu(vp->hashid), partName);
5798 * If we aren't the fileserver, tell the fileserver the volume
5799 * needs to be salvaged. We could directly tell the
5800 * salvageserver, but the fileserver keeps track of some stats
5801 * related to salvages, and handles some other salvage-related
5802 * complications for us.
5804 *code = FSYNC_VolOp(vp->hashid, partName,
5805 FSYNC_VOL_FORCE_ERROR, FSYNC_SALVAGE, NULL);
5808 #endif /* FSSYNC_BUILD_CLIENT */
5813 * schedule a salvage with the salvage server or fileserver.
5815 * @param[in] vp pointer to volume object
5817 * @return operation status
5818 * @retval VCHECK_SALVAGE_OK (0) no pending salvage
5819 * @retval VCHECK_SALVAGE_SCHEDULED (1) salvage has been scheduled
5820 * @retval VCHECK_SALVAGE_ASYNC (2) salvage being scheduled
5821 * @retval VCHECK_SALVAGE_DENIED (3) salvage not scheduled; denied
5822 * @retval VCHECK_SALVAGE_FAIL (4) salvage not scheduled; failed
5825 * @arg VOL_LOCK is held.
5826 * @arg nUsers and nWaiters should be zero.
5828 * @post salvageserver or fileserver is sent a salvage request
5830 * @note If we are the fileserver, the request will be sent to the salvage
5831 * server over SALVSYNC. If we are not the fileserver, the request will be
5832 * sent to the fileserver over FSSYNC (FSYNC_VOL_FORCE_ERROR/FSYNC_SALVAGE).
5834 * @note the caller must check if the volume needs to be freed after calling
5835 * this; the volume may not have any references or be on any lists after
5836 * we return, and we do not free it
5840 * @internal volume package internal use only.
5843 VScheduleSalvage_r(Volume * vp)
5845 int ret = VCHECK_SALVAGE_SCHEDULED;
5847 VolState state_save;
5848 VThreadOptions_t * thread_opts;
5851 opr_Verify(VCanUseSALVSYNC() || VCanUseFSSYNC());
5853 if (vp->nWaiters || vp->nUsers) {
5854 return VCHECK_SALVAGE_ASYNC;
5857 /* prevent endless salvage,attach,salvage,attach,... loops */
5858 if (vp->stats.salvages >= SALVAGE_COUNT_MAX) {
5859 return VCHECK_SALVAGE_FAIL;
5863 * don't perform salvsync ops on certain threads
5865 thread_opts = pthread_getspecific(VThread_key);
5866 if (thread_opts == NULL) {
5867 thread_opts = &VThread_defaults;
5869 if (thread_opts->disallow_salvsync || vol_disallow_salvsync) {
5870 return VCHECK_SALVAGE_ASYNC;
5873 if (vp->salvage.scheduled) {
5874 return VCHECK_SALVAGE_SCHEDULED;
5877 VCreateReservation_r(vp);
5878 VWaitExclusiveState_r(vp);
5881 * XXX the scheduling process should really be done asynchronously
5882 * to avoid fssync deadlocks
5884 if (vp->salvage.scheduled) {
5885 ret = VCHECK_SALVAGE_SCHEDULED;
5887 /* if we haven't previously scheduled a salvage, do so now
5889 * set the volume to an exclusive state and drop the lock
5890 * around the SALVSYNC call
5892 strlcpy(partName, vp->partition->name, sizeof(partName));
5893 state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
5896 opr_Verify(try_SALVSYNC(vp, partName, &code)
5897 || try_FSSYNC(vp, partName, &code));
5900 VChangeState_r(vp, state_save);
5902 if (code == SYNC_OK) {
5903 ret = VCHECK_SALVAGE_SCHEDULED;
5904 vp->salvage.scheduled = 1;
5905 vp->stats.last_salvage_req = FT_ApproxTime();
5906 if (VCanUseSALVSYNC()) {
5907 /* don't record these stats for non-fileservers; let the
5908 * fileserver take care of these */
5909 vp->stats.salvages++;
5910 IncUInt64(&VStats.salvages);
5914 case SYNC_BAD_COMMAND:
5915 case SYNC_COM_ERROR:
5916 ret = VCHECK_SALVAGE_FAIL;
5919 ret = VCHECK_SALVAGE_DENIED;
5920 Log("VScheduleSalvage_r: Salvage request for volume %" AFS_VOLID_FMT " "
5921 "denied\n", afs_printable_VolumeId_lu(vp->hashid));
5924 ret = VCHECK_SALVAGE_FAIL;
5925 Log("VScheduleSalvage_r: Salvage request for volume %" AFS_VOLID_FMT " "
5926 "failed\n", afs_printable_VolumeId_lu(vp->hashid));
5929 ret = VCHECK_SALVAGE_FAIL;
5930 Log("VScheduleSalvage_r: Salvage request for volume %" AFS_VOLID_FMT " "
5931 "received unknown protocol error %d\n",
5932 afs_printable_VolumeId_lu(vp->hashid), code);
5936 if (VCanUseFSSYNC()) {
5937 VChangeState_r(vp, VOL_STATE_ERROR);
5942 /* NB: this is cancelling the reservation we obtained above, but we do
5943 * not call VCancelReservation_r, since that may trigger the vp dtor,
5944 * possibly free'ing the vp. We need to keep the vp around after
5945 * this, as the caller may reference vp without any refs. Instead, it
5946 * is the duty of the caller to inspect 'vp' after we return to see if
5947 * needs to be freed. */
5948 opr_Verify(--vp->nWaiters >= 0);
5951 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5953 #ifdef SALVSYNC_BUILD_CLIENT
5956 * connect to the salvageserver SYNC service.
5958 * @return operation status
5962 * @post connection to salvageserver SYNC service established
5964 * @see VConnectSALV_r
5965 * @see VDisconnectSALV
5966 * @see VReconnectSALV
5973 retVal = VConnectSALV_r();
5979 * connect to the salvageserver SYNC service.
5981 * @return operation status
5985 * @pre VOL_LOCK is held.
5987 * @post connection to salvageserver SYNC service established
5990 * @see VDisconnectSALV_r
5991 * @see VReconnectSALV_r
5992 * @see SALVSYNC_clientInit
5994 * @internal volume package internal use only.
5997 VConnectSALV_r(void)
5999 return SALVSYNC_clientInit();
6003 * disconnect from the salvageserver SYNC service.
6005 * @return operation status
6008 * @pre client should have a live connection to the salvageserver
6010 * @post connection to salvageserver SYNC service destroyed
6012 * @see VDisconnectSALV_r
6014 * @see VReconnectSALV
6017 VDisconnectSALV(void)
6020 VDisconnectSALV_r();
6026 * disconnect from the salvageserver SYNC service.
6028 * @return operation status
6032 * @arg VOL_LOCK is held.
6033 * @arg client should have a live connection to the salvageserver.
6035 * @post connection to salvageserver SYNC service destroyed
6037 * @see VDisconnectSALV
6038 * @see VConnectSALV_r
6039 * @see VReconnectSALV_r
6040 * @see SALVSYNC_clientFinis
6042 * @internal volume package internal use only.
6045 VDisconnectSALV_r(void)
6047 return SALVSYNC_clientFinis();
6051 * disconnect and then re-connect to the salvageserver SYNC service.
6053 * @return operation status
6057 * @pre client should have a live connection to the salvageserver
6059 * @post old connection is dropped, and a new one is established
6062 * @see VDisconnectSALV
6063 * @see VReconnectSALV_r
6066 VReconnectSALV(void)
6070 retVal = VReconnectSALV_r();
6076 * disconnect and then re-connect to the salvageserver SYNC service.
6078 * @return operation status
6083 * @arg VOL_LOCK is held.
6084 * @arg client should have a live connection to the salvageserver.
6086 * @post old connection is dropped, and a new one is established
6088 * @see VConnectSALV_r
6089 * @see VDisconnectSALV
6090 * @see VReconnectSALV
6091 * @see SALVSYNC_clientReconnect
6093 * @internal volume package internal use only.
6096 VReconnectSALV_r(void)
6098 return SALVSYNC_clientReconnect();
6100 #endif /* SALVSYNC_BUILD_CLIENT */
6101 #endif /* AFS_DEMAND_ATTACH_FS */
6104 /***************************************************/
6105 /* FSSYNC routines */
6106 /***************************************************/
6108 /* This must be called by any volume utility which needs to run while the
6109 file server is also running. This is separated from VInitVolumePackage2 so
6110 that a utility can fork--and each of the children can independently
6111 initialize communication with the file server */
6112 #ifdef FSSYNC_BUILD_CLIENT
6114 * connect to the fileserver SYNC service.
6116 * @return operation status
6121 * @arg VInit must equal 2.
6122 * @arg Program Type must not be fileserver or salvager.
6124 * @post connection to fileserver SYNC service established
6127 * @see VDisconnectFS
6128 * @see VChildProcReconnectFS
6135 retVal = VConnectFS_r();
6141 * connect to the fileserver SYNC service.
6143 * @return operation status
6148 * @arg VInit must equal 2.
6149 * @arg Program Type must not be fileserver or salvager.
6150 * @arg VOL_LOCK is held.
6152 * @post connection to fileserver SYNC service established
6155 * @see VDisconnectFS_r
6156 * @see VChildProcReconnectFS_r
6158 * @internal volume package internal use only.
6164 opr_Assert((VInit == 2) &&
6165 (programType != fileServer) &&
6166 (programType != salvager));
6167 rc = FSYNC_clientInit();
6175 * disconnect from the fileserver SYNC service.
6178 * @arg client should have a live connection to the fileserver.
6179 * @arg VOL_LOCK is held.
6180 * @arg Program Type must not be fileserver or salvager.
6182 * @post connection to fileserver SYNC service destroyed
6184 * @see VDisconnectFS
6186 * @see VChildProcReconnectFS_r
6188 * @internal volume package internal use only.
6191 VDisconnectFS_r(void)
6193 opr_Assert((programType != fileServer) &&
6194 (programType != salvager));
6195 FSYNC_clientFinis();
6200 * disconnect from the fileserver SYNC service.
6203 * @arg client should have a live connection to the fileserver.
6204 * @arg Program Type must not be fileserver or salvager.
6206 * @post connection to fileserver SYNC service destroyed
6208 * @see VDisconnectFS_r
6210 * @see VChildProcReconnectFS
6221 * connect to the fileserver SYNC service from a child process following a fork.
6223 * @return operation status
6228 * @arg VOL_LOCK is held.
6229 * @arg current FSYNC handle is shared with a parent process
6231 * @post current FSYNC handle is discarded and a new connection to the
6232 * fileserver SYNC service is established
6234 * @see VChildProcReconnectFS
6236 * @see VDisconnectFS_r
6238 * @internal volume package internal use only.
6241 VChildProcReconnectFS_r(void)
6243 return FSYNC_clientChildProcReconnect();
6247 * connect to the fileserver SYNC service from a child process following a fork.
6249 * @return operation status
6253 * @pre current FSYNC handle is shared with a parent process
6255 * @post current FSYNC handle is discarded and a new connection to the
6256 * fileserver SYNC service is established
6258 * @see VChildProcReconnectFS_r
6260 * @see VDisconnectFS
6263 VChildProcReconnectFS(void)
6267 ret = VChildProcReconnectFS_r();
6271 #endif /* FSSYNC_BUILD_CLIENT */
6274 /***************************************************/
6275 /* volume bitmap routines */
6276 /***************************************************/
6279 * Grow the bitmap by the defined increment
6282 VGrowBitmap(struct vnodeIndex *index)
6286 bp = realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
6287 osi_Assert(bp != NULL);
6289 bp += index->bitmapSize;
6290 memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
6291 index->bitmapOffset = index->bitmapSize;
6292 index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
6298 * allocate a vnode bitmap number for the vnode
6300 * @param[out] ec error code
6301 * @param[in] vp volume object pointer
6302 * @param[in] index vnode index number for the vnode
6303 * @param[in] flags flag values described in note
6305 * @note for DAFS, flags parameter controls locking behavior.
6306 * If (flags & VOL_ALLOC_BITMAP_WAIT) is set, then this function
6307 * will create a reservation and block on any other exclusive
6308 * operations. Otherwise, this function assumes the caller
6309 * already has exclusive access to vp, and we just change the
6312 * @pre VOL_LOCK held
6314 * @return bit number allocated
6320 VAllocBitmapEntry_r(Error * ec, Volume * vp,
6321 struct vnodeIndex *index, int flags)
6325 #ifdef AFS_DEMAND_ATTACH_FS
6326 VolState state_save;
6327 #endif /* AFS_DEMAND_ATTACH_FS */
6331 /* This test is probably redundant */
6332 if (!VolumeWriteable(vp)) {
6333 *ec = (bit32) VREADONLY;
6337 #ifdef AFS_DEMAND_ATTACH_FS
6338 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6339 VCreateReservation_r(vp);
6340 VWaitExclusiveState_r(vp);
6342 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6343 #endif /* AFS_DEMAND_ATTACH_FS */
6346 if ((programType == fileServer) && !index->bitmap) {
6348 #ifndef AFS_DEMAND_ATTACH_FS
6349 /* demand attach fs uses the volume state to avoid races.
6350 * specialStatus field is not used at all */
6352 if (vp->specialStatus == VBUSY) {
6353 if (vp->goingOffline) { /* vos dump waiting for the volume to
6354 * go offline. We probably come here
6355 * from AddNewReadableResidency */
6358 while (vp->specialStatus == VBUSY) {
6359 #ifdef AFS_PTHREAD_ENV
6363 #else /* !AFS_PTHREAD_ENV */
6365 #endif /* !AFS_PTHREAD_ENV */
6369 #endif /* !AFS_DEMAND_ATTACH_FS */
6371 if (!index->bitmap) {
6372 #ifndef AFS_DEMAND_ATTACH_FS
6373 vp->specialStatus = VBUSY; /* Stop anyone else from using it. */
6374 #endif /* AFS_DEMAND_ATTACH_FS */
6375 for (i = 0; i < nVNODECLASSES; i++) {
6376 VGetBitmap_r(ec, vp, i);
6378 #ifdef AFS_DEMAND_ATTACH_FS
6379 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0 /*flags*/);
6380 #else /* AFS_DEMAND_ATTACH_FS */
6381 DeleteVolumeFromHashTable(vp);
6382 vp->shuttingDown = 1; /* Let who has it free it. */
6383 vp->specialStatus = 0;
6384 #endif /* AFS_DEMAND_ATTACH_FS */
6388 #ifndef AFS_DEMAND_ATTACH_FS
6390 vp->specialStatus = 0; /* Allow others to have access. */
6391 #endif /* AFS_DEMAND_ATTACH_FS */
6394 #endif /* BITMAP_LATER */
6396 #ifdef AFS_DEMAND_ATTACH_FS
6398 #endif /* AFS_DEMAND_ATTACH_FS */
6399 bp = index->bitmap + index->bitmapOffset;
6400 ep = index->bitmap + index->bitmapSize;
6402 if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
6404 index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
6407 o = ffs(~*bp) - 1; /* ffs is documented in BSTRING(3) */
6409 ret = ((bp - index->bitmap) * 8 + o);
6410 #ifdef AFS_DEMAND_ATTACH_FS
6412 #endif /* AFS_DEMAND_ATTACH_FS */
6415 bp += sizeof(bit32) /* i.e. 4 */ ;
6417 /* No bit map entry--must grow bitmap */
6419 bp = index->bitmap + index->bitmapOffset;
6421 ret = index->bitmapOffset * 8;
6422 #ifdef AFS_DEMAND_ATTACH_FS
6424 #endif /* AFS_DEMAND_ATTACH_FS */
6427 #ifdef AFS_DEMAND_ATTACH_FS
6428 VChangeState_r(vp, state_save);
6429 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6430 VCancelReservation_r(vp);
6432 #endif /* AFS_DEMAND_ATTACH_FS */
6437 VAllocBitmapEntry(Error * ec, Volume * vp, struct vnodeIndex * index)
6441 retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
6447 VFreeBitMapEntry_r(Error * ec, Volume *vp, struct vnodeIndex *index,
6448 unsigned bitNumber, int flags)
6450 unsigned int offset;
6454 #ifdef AFS_DEMAND_ATTACH_FS
6455 if (flags & VOL_FREE_BITMAP_WAIT) {
6456 /* VAllocBitmapEntry_r allocs bitmap entries under an exclusive volume
6457 * state, so ensure we're not in an exclusive volume state when we update
6459 VCreateReservation_r(vp);
6460 VWaitExclusiveState_r(vp);
6467 #endif /* BITMAP_LATER */
6469 offset = bitNumber >> 3;
6470 if (offset >= index->bitmapSize) {
6474 if (offset < index->bitmapOffset)
6475 index->bitmapOffset = offset & ~3; /* Truncate to nearest bit32 */
6476 *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
6479 #ifdef AFS_DEMAND_ATTACH_FS
6480 VCancelReservation_r(vp);
6482 return; /* make the compiler happy for non-DAFS */
6486 VFreeBitMapEntry(Error * ec, Volume *vp, struct vnodeIndex *index,
6490 VFreeBitMapEntry_r(ec, vp, index, bitNumber, VOL_FREE_BITMAP_WAIT);
6494 /* this function will drop the glock internally.
6495 * for old pthread fileservers, this is safe thanks to vbusy.
6497 * for demand attach fs, caller must have already called
6498 * VCreateReservation_r and VWaitExclusiveState_r */
6500 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
6502 StreamHandle_t *file;
6503 afs_sfsize_t nVnodes, size;
6504 struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
6505 struct vnodeIndex *vip = &vp->vnodeIndex[class];
6506 struct VnodeDiskObject *vnode;
6507 unsigned int unique = 0;
6511 #endif /* BITMAP_LATER */
6512 #ifdef AFS_DEMAND_ATTACH_FS
6513 VolState state_save;
6514 #endif /* AFS_DEMAND_ATTACH_FS */
6518 #ifdef AFS_DEMAND_ATTACH_FS
6519 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6520 #endif /* AFS_DEMAND_ATTACH_FS */
6523 fdP = IH_OPEN(vip->handle);
6524 opr_Assert(fdP != NULL);
6525 file = FDH_FDOPEN(fdP, "r");
6526 opr_Assert(file != NULL);
6527 vnode = malloc(vcp->diskSize);
6528 opr_Assert(vnode != NULL);
6529 size = OS_SIZE(fdP->fd_fd);
6530 opr_Assert(size != -1);
6531 nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
6533 vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4; /* The 10 is a little extra so
6534 * a few files can be created in this volume,
6535 * the whole thing is rounded up to nearest 4
6536 * bytes, because the bit map allocator likes
6539 BitMap = (byte *) calloc(1, vip->bitmapSize);
6540 opr_Assert(BitMap != NULL);
6541 #else /* BITMAP_LATER */
6542 vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
6543 opr_Assert(vip->bitmap != NULL);
6544 vip->bitmapOffset = 0;
6545 #endif /* BITMAP_LATER */
6546 if (STREAM_ASEEK(file, vcp->diskSize) != -1) {
6548 for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
6549 if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
6551 if (vnode->type != vNull) {
6552 if (vnode->vnodeMagic != vcp->magic) {
6553 Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
6558 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6559 #else /* BITMAP_LATER */
6560 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6561 #endif /* BITMAP_LATER */
6562 if (unique <= vnode->uniquifier)
6563 unique = vnode->uniquifier + 1;
6565 #ifndef AFS_PTHREAD_ENV
6566 if ((bitNumber & 0x00ff) == 0x0ff) { /* every 256 iterations */
6569 #endif /* !AFS_PTHREAD_ENV */
6572 if (vp->nextVnodeUnique < unique) {
6573 Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
6576 /* Paranoia, partly justified--I think fclose after fdopen
6577 * doesn't seem to close fd. In any event, the documentation
6578 * doesn't specify, so it's safer to close it twice.
6586 /* There may have been a racing condition with some other thread, both
6587 * creating the bitmaps for this volume. If the other thread was faster
6588 * the pointer to bitmap should already be filled and we can free ours.
6590 if (vip->bitmap == NULL) {
6591 vip->bitmap = BitMap;
6592 vip->bitmapOffset = 0;
6595 #endif /* BITMAP_LATER */
6596 #ifdef AFS_DEMAND_ATTACH_FS
6597 VChangeState_r(vp, state_save);
6598 #endif /* AFS_DEMAND_ATTACH_FS */
6602 /***************************************************/
6603 /* Volume Path and Volume Number utility routines */
6604 /***************************************************/
6607 * find the first occurrence of a volume header file and return the path.
6609 * @param[out] ec outbound error code
6610 * @param[in] volumeId volume id to find
6611 * @param[out] partitionp pointer to disk partition path string
6612 * @param[out] namep pointer to volume header file name string
6614 * @post path to first occurrence of volume header is returned in partitionp
6615 * and namep, or ec is set accordingly.
6617 * @warning this function is NOT re-entrant -- partitionp and namep point to
6618 * static data segments
6620 * @note if a volume utility inadvertently leaves behind a stale volume header
6621 * on a vice partition, it is possible for callers to get the wrong one,
6622 * depending on the order of the disk partition linked list.
6626 VGetVolumePath(Error * ec, VolumeId volumeId, char **partitionp, char **namep)
6628 static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
6629 char path[VMAXPATHLEN];
6631 struct DiskPartition64 *dp;
6634 name[0] = OS_DIRSEPC;
6635 snprintf(&name[1], (sizeof name) - 1, VFORMAT,
6636 afs_printable_VolumeId_lu(volumeId));
6637 for (dp = DiskPartitionList; dp; dp = dp->next) {
6638 struct afs_stat_st status;
6639 strcpy(path, VPartitionPath(dp));
6641 if (afs_stat(path, &status) == 0) {
6642 strcpy(partition, dp->name);
6649 *partitionp = *namep = NULL;
6651 *partitionp = partition;
6657 * extract a volume number from a volume header filename string.
6659 * @param[in] name volume header filename string
6661 * @return volume number
6663 * @note the string must be of the form VFORMAT. the only permissible
6664 * deviation is a leading OS_DIRSEPC character.
6669 VolumeNumber(char *name)
6671 if (*name == OS_DIRSEPC)
6673 return strtoul(name + 1, NULL, 10);
6677 * compute the volume header filename.
6679 * @param[in] volumeId
6681 * @return volume header filename
6683 * @post volume header filename string is constructed
6685 * @warning this function is NOT re-entrant -- the returned string is
6686 * stored in a static char array. see VolumeExternalName_r
6687 * for a re-entrant equivalent.
6689 * @see VolumeExternalName_r
6691 * @deprecated due to the above re-entrancy warning, this interface should
6692 * be considered deprecated. Please use VolumeExternalName_r
6696 VolumeExternalName(VolumeId volumeId)
6698 static char name[VMAXPATHLEN];
6699 snprintf(name, sizeof name, VFORMAT, afs_printable_VolumeId_lu(volumeId));
6704 * compute the volume header filename.
6706 * @param[in] volumeId
6707 * @param[inout] name array in which to store filename
6708 * @param[in] len length of name array
6710 * @return result code from afs_snprintf
6712 * @see VolumeExternalName
6715 * @note re-entrant equivalent of VolumeExternalName
6718 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
6720 return snprintf(name, len, VFORMAT, afs_printable_VolumeId_lu(volumeId));
6724 /***************************************************/
6725 /* Volume Usage Statistics routines */
6726 /***************************************************/
6728 #define OneDay (86400) /* 24 hours' worth of seconds */
6731 Midnight(time_t t) {
6732 struct tm local, *l;
6735 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
6736 l = localtime_r(&t, &local);
6742 /* the following is strictly speaking problematic on the
6743 switching day to daylight saving time, after the switch,
6744 as tm_isdst does not match. Similarly, on the looong day when
6745 switching back the OneDay check will not do what naively expected!
6746 The effects are minor, though, and more a matter of interpreting
6748 #ifndef AFS_PTHREAD_ENV
6751 local.tm_hour = local.tm_min=local.tm_sec = 0;
6752 midnight = mktime(&local);
6753 if (midnight != (time_t) -1) return(midnight);
6755 return( (t/OneDay)*OneDay );
6759 /*------------------------------------------------------------------------
6760 * [export] VAdjustVolumeStatistics
6763 * If we've passed midnight, we need to update all the day use
6764 * statistics as well as zeroing the detailed volume statistics
6765 * (if we are implementing them).
6768 * vp : Pointer to the volume structure describing the lucky
6769 * volume being considered for update.
6775 * Nothing interesting.
6779 *------------------------------------------------------------------------*/
6782 VAdjustVolumeStatistics_r(Volume * vp)
6784 unsigned int now = FT_ApproxTime();
6786 if (now - V_dayUseDate(vp) > OneDay) {
6789 ndays = (now - V_dayUseDate(vp)) / OneDay;
6790 for (i = 6; i > ndays - 1; i--)
6791 V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
6792 for (i = 0; i < ndays - 1 && i < 7; i++)
6793 V_weekUse(vp)[i] = 0;
6795 V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
6797 V_dayUseDate(vp) = Midnight(now);
6800 * All we need to do is bzero the entire VOL_STATS_BYTES of
6801 * the detailed volume statistics area.
6803 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
6806 /*It's been more than a day of collection */
6808 * Always return happily.
6811 } /*VAdjustVolumeStatistics */
6814 VAdjustVolumeStatistics(Volume * vp)
6818 retVal = VAdjustVolumeStatistics_r(vp);
6824 VBumpVolumeUsage_r(Volume * vp)
6826 unsigned int now = FT_ApproxTime();
6827 V_accessDate(vp) = now;
6828 if (now - V_dayUseDate(vp) > OneDay)
6829 VAdjustVolumeStatistics_r(vp);
6831 * Save the volume header image to disk after a threshold of bumps to dayUse,
6832 * at most every usage_rate_limit seconds.
6835 vp->usage_bumps_outstanding++;
6836 if (vp->usage_bumps_outstanding >= vol_opts.usage_threshold
6837 && vp->usage_bumps_next_write <= now) {
6839 vp->usage_bumps_outstanding = 0;
6840 vp->usage_bumps_next_write = now + vol_opts.usage_rate_limit;
6841 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
6846 VBumpVolumeUsage(Volume * vp)
6849 VBumpVolumeUsage_r(vp);
6854 VSetDiskUsage_r(void)
6856 #ifndef AFS_DEMAND_ATTACH_FS
6857 static int FifteenMinuteCounter = 0;
6861 /* NOTE: Don't attempt to access the partitions list until the
6862 * initialization level indicates that all volumes are attached,
6863 * which implies that all partitions are initialized. */
6864 #ifdef AFS_PTHREAD_ENV
6865 VOL_CV_WAIT(&vol_vinit_cond);
6866 #else /* AFS_PTHREAD_ENV */
6868 #endif /* AFS_PTHREAD_ENV */
6871 VResetDiskUsage_r();
6873 #ifndef AFS_DEMAND_ATTACH_FS
6874 if (++FifteenMinuteCounter == 3) {
6875 FifteenMinuteCounter = 0;
6878 #endif /* !AFS_DEMAND_ATTACH_FS */
6890 /***************************************************/
6891 /* Volume Update List routines */
6892 /***************************************************/
6894 /* The number of minutes that a volume hasn't been updated before the
6895 * "Dont salvage" flag in the volume header will be turned on */
6896 #define SALVAGE_INTERVAL (10*60)
6901 * volume update list functionality has been moved into the VLRU
6902 * the DONT_SALVAGE flag is now set during VLRU demotion
6905 #ifndef AFS_DEMAND_ATTACH_FS
6906 static VolumeId *UpdateList = NULL; /* Pointer to array of Volume ID's */
6907 static int nUpdatedVolumes = 0; /* Updated with entry in UpdateList, salvage after crash flag on */
6908 static int updateSize = 0; /* number of entries possible */
6909 #define UPDATE_LIST_SIZE 128 /* initial size increment (must be a power of 2!) */
6910 #endif /* !AFS_DEMAND_ATTACH_FS */
6913 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
6916 vp->updateTime = FT_ApproxTime();
6917 if (V_dontSalvage(vp) == 0)
6919 V_dontSalvage(vp) = 0;
6920 VSyncVolume_r(ec, vp, 0);
6921 #ifdef AFS_DEMAND_ATTACH_FS
6922 V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
6923 #else /* !AFS_DEMAND_ATTACH_FS */
6926 if (UpdateList == NULL) {
6927 updateSize = UPDATE_LIST_SIZE;
6928 UpdateList = malloc(sizeof(VolumeId) * updateSize);
6930 if (nUpdatedVolumes == updateSize) {
6932 if (updateSize > 524288) {
6933 Log("warning: there is likely a bug in the volume update scanner\n");
6936 UpdateList = realloc(UpdateList,
6937 sizeof(VolumeId) * updateSize);
6940 opr_Assert(UpdateList != NULL);
6941 UpdateList[nUpdatedVolumes++] = V_id(vp);
6942 #endif /* !AFS_DEMAND_ATTACH_FS */
6945 #ifndef AFS_DEMAND_ATTACH_FS
6947 VScanUpdateList(void)
6952 afs_uint32 now = FT_ApproxTime();
6953 /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
6954 for (i = gap = 0; i < nUpdatedVolumes; i++) {
6956 UpdateList[i - gap] = UpdateList[i];
6958 /* XXX this routine needlessly messes up the Volume LRU by
6959 * breaking the LRU temporal-locality assumptions.....
6960 * we should use a special volume header allocator here */
6961 vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
6964 } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
6965 V_dontSalvage(vp) = DONT_SALVAGE;
6966 VUpdateVolume_r(&error, vp, 0); /* No need to fsync--not critical */
6974 #ifndef AFS_PTHREAD_ENV
6976 #endif /* !AFS_PTHREAD_ENV */
6978 nUpdatedVolumes -= gap;
6980 #endif /* !AFS_DEMAND_ATTACH_FS */
6983 /***************************************************/
6984 /* Volume LRU routines */
6985 /***************************************************/
6990 * with demand attach fs, we attempt to soft detach(1)
6991 * volumes which have not been accessed in a long time
6992 * in order to speed up fileserver shutdown
6994 * (1) by soft detach we mean a process very similar
6995 * to VOffline, except the final state of the
6996 * Volume will be VOL_STATE_PREATTACHED, instead
6997 * of the usual VOL_STATE_UNATTACHED
6999 #ifdef AFS_DEMAND_ATTACH_FS
7001 /* implementation is reminiscent of a generational GC
7003 * queue 0 is newly attached volumes. this queue is
7004 * sorted by attach timestamp
7006 * queue 1 is volumes that have been around a bit
7007 * longer than queue 0. this queue is sorted by
7010 * queue 2 is volumes tha have been around the longest.
7011 * this queue is unsorted
7013 * queue 3 is volumes that have been marked as
7014 * candidates for soft detachment. this queue is
7017 #define VLRU_GENERATIONS 3 /**< number of generations in VLRU */
7018 #define VLRU_QUEUES 5 /**< total number of VLRU queues */
7021 * definition of a VLRU queue.
7024 volatile struct rx_queue q;
7031 * main VLRU data structure.
7034 struct VLRU_q q[VLRU_QUEUES]; /**< VLRU queues */
7037 /** time interval (in seconds) between promotion passes for
7038 * each young generation queue. */
7039 afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
7041 /** time interval (in seconds) between soft detach candidate
7042 * scans for each generation queue.
7044 * scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
7045 * we perform a soft detach pass. */
7046 afs_uint32 scan_interval[VLRU_GENERATIONS+1];
7048 /* scheduler state */
7049 int next_idx; /**< next queue to receive attention */
7050 afs_uint32 last_promotion[VLRU_GENERATIONS-1]; /**< timestamp of last promotion scan */
7051 afs_uint32 last_scan[VLRU_GENERATIONS+1]; /**< timestamp of last detach scan */
7053 int scanner_state; /**< state of scanner thread */
7054 pthread_cond_t cv; /**< state transition CV */
7057 /** global VLRU state */
7058 static struct VLRU volume_LRU;
7061 * defined states for VLRU scanner thread.
7064 VLRU_SCANNER_STATE_OFFLINE = 0, /**< vlru scanner thread is offline */
7065 VLRU_SCANNER_STATE_ONLINE = 1, /**< vlru scanner thread is online */
7066 VLRU_SCANNER_STATE_SHUTTING_DOWN = 2, /**< vlru scanner thread is shutting down */
7067 VLRU_SCANNER_STATE_PAUSING = 3, /**< vlru scanner thread is getting ready to pause */
7068 VLRU_SCANNER_STATE_PAUSED = 4 /**< vlru scanner thread is paused */
7069 } vlru_thread_state_t;
7071 /* vlru disk data header stuff */
7072 #define VLRU_DISK_MAGIC 0x7a8b9cad /**< vlru disk entry magic number */
7073 #define VLRU_DISK_VERSION 1 /**< vlru disk entry version number */
7075 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
7076 #define VLRU_DUMP_EXPIRATION_TIME (60*60*24*7) /* expire vlru data after 1 week */
7079 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
7080 * soft detachment. */
7081 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
7083 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
7084 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
7086 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
7087 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
7089 /** VLRU control flag. non-zero value implies VLRU subsystem is activated. */
7090 static afs_uint32 VLRU_enabled = 1;
7092 /* queue synchronization routines */
7093 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
7094 static void VLRU_EndExclusive_r(struct VLRU_q * q);
7095 static void VLRU_Wait_r(struct VLRU_q * q);
7098 * set VLRU subsystem tunable parameters.
7100 * @param[in] option tunable option to modify
7101 * @param[in] val new value for tunable parameter
7103 * @pre @c VInitVolumePackage2 has not yet been called.
7105 * @post tunable parameter is modified
7109 * @note valid option parameters are:
7110 * @arg @c VLRU_SET_THRESH
7111 * set the period of inactivity after which
7112 * volumes are eligible for soft detachment
7113 * @arg @c VLRU_SET_INTERVAL
7114 * set the time interval between calls
7115 * to the volume LRU "garbage collector"
7116 * @arg @c VLRU_SET_MAX
7117 * set the max number of volumes to deallocate
7121 VLRU_SetOptions(int option, afs_uint32 val)
7123 if (option == VLRU_SET_THRESH) {
7124 VLRU_offline_thresh = val;
7125 } else if (option == VLRU_SET_INTERVAL) {
7126 VLRU_offline_interval = val;
7127 } else if (option == VLRU_SET_MAX) {
7128 VLRU_offline_max = val;
7129 } else if (option == VLRU_SET_ENABLED) {
7132 VLRU_ComputeConstants();
7136 * compute VLRU internal timing parameters.
7138 * @post VLRU scanner thread internal timing parameters are computed
7140 * @note computes internal timing parameters based upon user-modifiable
7141 * tunable parameters.
7145 * @internal volume package internal use only.
7148 VLRU_ComputeConstants(void)
7150 afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
7152 /* compute the candidate scan interval */
7153 volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
7155 /* compute the promotion intervals */
7156 volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
7157 volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
7160 /* compute the gen 0 scan interval */
7161 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
7163 /* compute the gen 0 scan interval */
7164 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
7169 * initialize VLRU subsystem.
7171 * @pre this function has not yet been called
7173 * @post VLRU subsystem is initialized and VLRU scanner thread is starting
7177 * @internal volume package internal use only.
7183 pthread_attr_t attrs;
7186 if (!VLRU_enabled) {
7187 Log("VLRU: disabled\n");
7191 /* initialize each of the VLRU queues */
7192 for (i = 0; i < VLRU_QUEUES; i++) {
7193 queue_Init(&volume_LRU.q[i]);
7194 volume_LRU.q[i].len = 0;
7195 volume_LRU.q[i].busy = 0;
7196 opr_cv_init(&volume_LRU.q[i].cv);
7199 /* setup the timing constants */
7200 VLRU_ComputeConstants();
7202 /* XXX put inside LogLevel check? */
7203 Log("VLRU: starting scanner with the following configuration parameters:\n");
7204 Log("VLRU: offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
7205 Log("VLRU: running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
7206 Log("VLRU: taking up to %d volumes offline per pass\n", VLRU_offline_max);
7207 Log("VLRU: scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
7208 Log("VLRU: scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
7209 Log("VLRU: scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
7211 /* start up the VLRU scanner */
7212 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7213 if (programType == fileServer) {
7214 opr_cv_init(&volume_LRU.cv);
7215 opr_Verify(pthread_attr_init(&attrs) == 0);
7216 opr_Verify(pthread_attr_setdetachstate(&attrs,
7217 PTHREAD_CREATE_DETACHED) == 0);
7218 opr_Verify(pthread_create(&tid, &attrs,
7219 &VLRU_ScannerThread, NULL) == 0);
7224 * initialize the VLRU-related fields of a newly allocated volume object.
7226 * @param[in] vp pointer to volume object
7229 * @arg @c VOL_LOCK is held.
7230 * @arg volume object is not on a VLRU queue.
7232 * @post VLRU fields are initialized to indicate that volume object is not
7233 * currently registered with the VLRU subsystem
7237 * @internal volume package interal use only.
7240 VLRU_Init_Node_r(Volume * vp)
7245 opr_Assert(queue_IsNotOnQueue(&vp->vlru));
7246 vp->vlru.idx = VLRU_QUEUE_INVALID;
7250 * add a volume object to a VLRU queue.
7252 * @param[in] vp pointer to volume object
7255 * @arg @c VOL_LOCK is held.
7256 * @arg caller MUST hold a lightweight ref on @p vp.
7257 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7259 * @post the volume object is added to the appropriate VLRU queue
7261 * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
7262 * then the volume is added to that queue. Otherwise, the value
7263 * @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
7264 * volume is added to the NEW generation queue.
7266 * @note @c VOL_LOCK may be dropped internally
7268 * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
7269 * during the add operation, and is restored to the previous
7270 * state prior to return.
7274 * @internal volume package internal use only.
7277 VLRU_Add_r(Volume * vp)
7280 VolState state_save;
7285 if (queue_IsOnQueue(&vp->vlru))
7288 state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
7291 if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
7292 idx = VLRU_QUEUE_NEW;
7295 VLRU_Wait_r(&volume_LRU.q[idx]);
7297 /* repeat check since VLRU_Wait_r may have dropped
7299 if (queue_IsNotOnQueue(&vp->vlru)) {
7301 queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
7302 volume_LRU.q[idx].len++;
7303 V_attachFlags(vp) |= VOL_ON_VLRU;
7304 vp->stats.last_promote = FT_ApproxTime();
7307 VChangeState_r(vp, state_save);
7311 * delete a volume object from a VLRU queue.
7313 * @param[in] vp pointer to volume object
7316 * @arg @c VOL_LOCK is held.
7317 * @arg caller MUST hold a lightweight ref on @p vp.
7318 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7320 * @post volume object is removed from the VLRU queue
7322 * @note @c VOL_LOCK may be dropped internally
7326 * @todo We should probably set volume state to something exlcusive
7327 * (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
7329 * @internal volume package internal use only.
7332 VLRU_Delete_r(Volume * vp)
7339 if (queue_IsNotOnQueue(&vp->vlru))
7345 if (idx == VLRU_QUEUE_INVALID)
7347 VLRU_Wait_r(&volume_LRU.q[idx]);
7348 } while (idx != vp->vlru.idx);
7350 /* now remove from the VLRU and update
7351 * the appropriate counter */
7352 queue_Remove(&vp->vlru);
7353 volume_LRU.q[idx].len--;
7354 vp->vlru.idx = VLRU_QUEUE_INVALID;
7355 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7359 * tell the VLRU subsystem that a volume was just accessed.
7361 * @param[in] vp pointer to volume object
7364 * @arg @c VOL_LOCK is held
7365 * @arg caller MUST hold a lightweight ref on @p vp
7366 * @arg caller MUST NOT hold exclusive ownership of any VLRU queue
7368 * @post volume VLRU access statistics are updated. If the volume was on
7369 * the VLRU soft detach candidate queue, it is moved to the NEW
7372 * @note @c VOL_LOCK may be dropped internally
7376 * @internal volume package internal use only.
7379 VLRU_UpdateAccess_r(Volume * vp)
7381 Volume * rvp = NULL;
7386 if (queue_IsNotOnQueue(&vp->vlru))
7389 opr_Assert(V_attachFlags(vp) & VOL_ON_VLRU);
7391 /* update the access timestamp */
7392 vp->stats.last_get = FT_ApproxTime();
7395 * if the volume is on the soft detach candidate
7396 * list, we need to safely move it back to a
7397 * regular generation. this has to be done
7398 * carefully so we don't race against the scanner
7402 /* if this volume is on the soft detach candidate queue,
7403 * then grab exclusive access to the necessary queues */
7404 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7406 VCreateReservation_r(rvp);
7408 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7409 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7410 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7411 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7414 /* make sure multiple threads don't race to update */
7415 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7416 VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
7420 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7421 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7422 VCancelReservation_r(rvp);
7427 * switch a volume between two VLRU queues.
7429 * @param[in] vp pointer to volume object
7430 * @param[in] new_idx index of VLRU queue onto which the volume will be moved
7431 * @param[in] append controls whether the volume will be appended or
7432 * prepended to the queue. A nonzero value means it will
7433 * be appended; zero means it will be prepended.
7435 * @pre The new (and old, if applicable) queue(s) must either be owned
7436 * exclusively by the calling thread for asynchronous manipulation,
7437 * or the queue(s) must be quiescent and VOL_LOCK must be held.
7438 * Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
7439 * for further details of the queue asynchronous processing mechanism.
7441 * @post If the volume object was already on a VLRU queue, it is
7442 * removed from the queue. Depending on the value of the append
7443 * parameter, the volume object is either appended or prepended
7444 * to the VLRU queue referenced by the new_idx parameter.
7448 * @see VLRU_BeginExclusive_r
7449 * @see VLRU_EndExclusive_r
7452 * @internal volume package internal use only.
7455 VLRU_SwitchQueues(Volume * vp, int new_idx, int append)
7457 if (queue_IsNotOnQueue(&vp->vlru))
7460 queue_Remove(&vp->vlru);
7461 volume_LRU.q[vp->vlru.idx].len--;
7463 /* put the volume back on the correct generational queue */
7465 queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
7467 queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
7470 volume_LRU.q[new_idx].len++;
7471 vp->vlru.idx = new_idx;
7475 * VLRU background thread.
7477 * The VLRU Scanner Thread is responsible for periodically scanning through
7478 * each VLRU queue looking for volumes which should be moved to another
7479 * queue, or soft detached.
7481 * @param[in] args unused thread arguments parameter
7483 * @return unused thread return value
7484 * @retval NULL always
7486 * @internal volume package internal use only.
7489 VLRU_ScannerThread(void * args)
7491 afs_uint32 now, min_delay, delay;
7492 int i, min_idx, min_op, overdue, state;
7494 /* set t=0 for promotion cycle to be
7495 * fileserver startup */
7496 now = FT_ApproxTime();
7497 for (i=0; i < VLRU_GENERATIONS-1; i++) {
7498 volume_LRU.last_promotion[i] = now;
7501 /* don't start the scanner until VLRU_offline_thresh
7502 * plus a small delay for VInitVolumePackage2 to finish
7505 sleep(VLRU_offline_thresh + 60);
7507 /* set t=0 for scan cycle to be now */
7508 now = FT_ApproxTime();
7509 for (i=0; i < VLRU_GENERATIONS+1; i++) {
7510 volume_LRU.last_scan[i] = now;
7514 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
7515 volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
7518 while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
7519 /* check to see if we've been asked to pause */
7520 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
7521 volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
7522 opr_cv_broadcast(&volume_LRU.cv);
7524 VOL_CV_WAIT(&volume_LRU.cv);
7525 } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
7528 /* scheduling can happen outside the glock */
7531 /* figure out what is next on the schedule */
7533 /* figure out a potential schedule for the new generation first */
7535 min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
7538 if (min_delay > volume_LRU.scan_interval[0]) {
7539 /* unsigned overflow -- we're overdue to run this scan */
7544 /* if we're not overdue for gen 0, figure out schedule for candidate gen */
7546 i = VLRU_QUEUE_CANDIDATE;
7547 delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
7548 if (delay < min_delay) {
7552 if (delay > volume_LRU.scan_interval[i]) {
7553 /* unsigned overflow -- we're overdue to run this scan */
7560 /* if we're still not overdue for something, figure out schedules for promotions */
7561 for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
7562 delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
7563 if (delay < min_delay) {
7568 if (delay > volume_LRU.promotion_interval[i]) {
7569 /* unsigned overflow -- we're overdue to run this promotion */
7578 /* sleep as needed */
7583 /* do whatever is next */
7586 VLRU_Promote_r(min_idx);
7587 VLRU_Demote_r(min_idx+1);
7589 VLRU_Scan_r(min_idx);
7591 now = FT_ApproxTime();
7594 Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
7596 /* signal that scanner is down */
7597 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7598 opr_cv_broadcast(&volume_LRU.cv);
7604 * promote volumes from one VLRU generation to the next.
7606 * This routine scans a VLRU generation looking for volumes which are
7607 * eligible to be promoted to the next generation. All volumes which
7608 * meet the eligibility requirement are promoted.
7610 * Promotion eligibility is based upon meeting both of the following
7613 * @arg The volume has been accessed since the last promotion:
7614 * @c (vp->stats.last_get >= vp->stats.last_promote)
7615 * @arg The last promotion occurred at least
7616 * @c volume_LRU.promotion_interval[idx] seconds ago
7618 * As a performance optimization, promotions are "globbed". In other
7619 * words, we promote arbitrarily large contiguous sublists of elements
7622 * @param[in] idx VLRU queue index to scan
7626 * @internal VLRU internal use only.
7629 VLRU_Promote_r(int idx)
7631 int len, chaining, promote;
7632 afs_uint32 now, thresh;
7633 struct rx_queue *qp, *nqp;
7634 Volume * vp, *start = NULL, *end = NULL;
7636 /* get exclusive access to two chains, and drop the glock */
7637 VLRU_Wait_r(&volume_LRU.q[idx]);
7638 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7639 VLRU_Wait_r(&volume_LRU.q[idx+1]);
7640 VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
7643 thresh = volume_LRU.promotion_interval[idx];
7644 now = FT_ApproxTime();
7647 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7648 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7649 promote = (((vp->stats.last_promote + thresh) <= now) &&
7650 (vp->stats.last_get >= vp->stats.last_promote));
7658 /* promote and prepend chain */
7659 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7673 /* promote and prepend */
7674 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7678 volume_LRU.q[idx].len -= len;
7679 volume_LRU.q[idx+1].len += len;
7682 /* release exclusive access to the two chains */
7684 volume_LRU.last_promotion[idx] = now;
7685 VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
7686 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7689 /* run the demotions */
7691 VLRU_Demote_r(int idx)
7694 int len, chaining, demote;
7695 afs_uint32 now, thresh;
7696 struct rx_queue *qp, *nqp;
7697 Volume * vp, *start = NULL, *end = NULL;
7698 Volume ** salv_flag_vec = NULL;
7699 int salv_vec_offset = 0;
7701 opr_Assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
7703 /* get exclusive access to two chains, and drop the glock */
7704 VLRU_Wait_r(&volume_LRU.q[idx-1]);
7705 VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
7706 VLRU_Wait_r(&volume_LRU.q[idx]);
7707 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7710 /* no big deal if this allocation fails */
7711 if (volume_LRU.q[idx].len) {
7712 salv_flag_vec = malloc(volume_LRU.q[idx].len * sizeof(Volume *));
7715 now = FT_ApproxTime();
7716 thresh = volume_LRU.promotion_interval[idx-1];
7719 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7720 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7721 demote = (((vp->stats.last_promote + thresh) <= now) &&
7722 (vp->stats.last_get < (now - thresh)));
7724 /* we now do volume update list DONT_SALVAGE flag setting during
7725 * demotion passes */
7726 if (salv_flag_vec &&
7727 !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7729 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7730 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7731 salv_flag_vec[salv_vec_offset++] = vp;
7732 VCreateReservation_r(vp);
7741 /* demote and append chain */
7742 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7756 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7760 volume_LRU.q[idx].len -= len;
7761 volume_LRU.q[idx-1].len += len;
7764 /* release exclusive access to the two chains */
7766 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7767 VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
7769 /* now go back and set the DONT_SALVAGE flags as appropriate */
7770 if (salv_flag_vec) {
7772 for (i = 0; i < salv_vec_offset; i++) {
7773 vp = salv_flag_vec[i];
7774 if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7775 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7776 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7779 V_attachFlags(vp) |= VOL_HDR_DONTSALV;
7780 V_dontSalvage(vp) = DONT_SALVAGE;
7781 VUpdateVolume_r(&ec, vp, 0);
7785 VCancelReservation_r(vp);
7787 free(salv_flag_vec);
7791 /* run a pass of the VLRU GC scanner */
7793 VLRU_Scan_r(int idx)
7795 afs_uint32 now, thresh;
7796 struct rx_queue *qp, *nqp;
7800 opr_Assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
7802 /* gain exclusive access to the idx VLRU */
7803 VLRU_Wait_r(&volume_LRU.q[idx]);
7804 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7806 if (idx != VLRU_QUEUE_CANDIDATE) {
7807 /* gain exclusive access to the candidate VLRU */
7808 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7809 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7812 now = FT_ApproxTime();
7813 thresh = now - VLRU_offline_thresh;
7815 /* perform candidate selection and soft detaching */
7816 if (idx == VLRU_QUEUE_CANDIDATE) {
7817 /* soft detach some volumes from the candidate pool */
7821 for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7822 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7823 if (i >= VLRU_offline_max) {
7826 /* check timestamp to see if it's a candidate for soft detaching */
7827 if (vp->stats.last_get <= thresh) {
7829 if (VCheckSoftDetach(vp, thresh))
7835 /* scan for volumes to become soft detach candidates */
7836 for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
7837 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7839 /* check timestamp to see if it's a candidate for soft detaching */
7840 if (vp->stats.last_get <= thresh) {
7841 VCheckSoftDetachCandidate(vp, thresh);
7844 if (!(i&0x7f)) { /* lock coarsening optimization */
7852 /* relinquish exclusive access to the VLRU chains */
7856 volume_LRU.last_scan[idx] = now;
7857 if (idx != VLRU_QUEUE_CANDIDATE) {
7858 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7860 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7863 /* check whether volume is safe to soft detach
7864 * caller MUST NOT hold a ref count on vp */
7866 VCheckSoftDetach(Volume * vp, afs_uint32 thresh)
7870 if (vp->nUsers || vp->nWaiters)
7873 if (vp->stats.last_get <= thresh) {
7874 ret = VSoftDetachVolume_r(vp, thresh);
7880 /* check whether volume should be made a
7881 * soft detach candidate */
7883 VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh)
7886 if (vp->nUsers || vp->nWaiters)
7891 opr_Assert(idx == VLRU_QUEUE_NEW);
7893 if (vp->stats.last_get <= thresh) {
7894 /* move to candidate pool */
7895 queue_Remove(&vp->vlru);
7896 volume_LRU.q[VLRU_QUEUE_NEW].len--;
7897 queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
7898 vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
7899 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
7907 /* begin exclusive access on VLRU */
7909 VLRU_BeginExclusive_r(struct VLRU_q * q)
7911 opr_Assert(q->busy == 0);
7915 /* end exclusive access on VLRU */
7917 VLRU_EndExclusive_r(struct VLRU_q * q)
7919 opr_Assert(q->busy);
7921 opr_cv_broadcast(&q->cv);
7924 /* wait for another thread to end exclusive access on VLRU */
7926 VLRU_Wait_r(struct VLRU_q * q)
7929 VOL_CV_WAIT(&q->cv);
7934 * volume soft detach
7936 * caller MUST NOT hold a ref count on vp */
7938 VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh)
7943 opr_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7945 ts_save = vp->stats.last_get;
7946 if (ts_save > thresh)
7949 if (vp->nUsers || vp->nWaiters)
7952 if (VIsExclusiveState(V_attachState(vp))) {
7956 switch (V_attachState(vp)) {
7957 case VOL_STATE_UNATTACHED:
7958 case VOL_STATE_PREATTACHED:
7959 case VOL_STATE_ERROR:
7960 case VOL_STATE_GOING_OFFLINE:
7961 case VOL_STATE_SHUTTING_DOWN:
7962 case VOL_STATE_SALVAGING:
7963 case VOL_STATE_DELETED:
7964 volume_LRU.q[vp->vlru.idx].len--;
7966 /* create and cancel a reservation to
7967 * give the volume an opportunity to
7969 VCreateReservation_r(vp);
7970 queue_Remove(&vp->vlru);
7971 vp->vlru.idx = VLRU_QUEUE_INVALID;
7972 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7973 VCancelReservation_r(vp);
7979 /* hold the volume and take it offline.
7980 * no need for reservations, as VHold_r
7981 * takes care of that internally. */
7982 if (VHold_r(vp) == 0) {
7983 /* vhold drops the glock, so now we should
7984 * check to make sure we aren't racing against
7985 * other threads. if we are racing, offlining vp
7986 * would be wasteful, and block the scanner for a while
7990 (vp->shuttingDown) ||
7991 (vp->goingOffline) ||
7992 (vp->stats.last_get != ts_save)) {
7993 /* looks like we're racing someone else. bail */
7997 /* pull it off the VLRU */
7998 opr_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7999 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
8000 queue_Remove(&vp->vlru);
8001 vp->vlru.idx = VLRU_QUEUE_INVALID;
8002 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
8004 /* take if offline */
8005 VOffline_r(vp, "volume has been soft detached");
8007 /* invalidate the volume header cache */
8008 FreeVolumeHeader(vp);
8011 IncUInt64(&VStats.soft_detaches);
8012 vp->stats.soft_detaches++;
8014 /* put in pre-attached state so demand
8015 * attacher can work on it */
8016 VChangeState_r(vp, VOL_STATE_PREATTACHED);
8022 #endif /* AFS_DEMAND_ATTACH_FS */
8025 /***************************************************/
8026 /* Volume Header Cache routines */
8027 /***************************************************/
8030 * volume header cache.
8032 struct volume_hdr_LRU_t volume_hdr_LRU;
8035 * initialize the volume header cache.
8037 * @param[in] howMany number of header cache entries to preallocate
8039 * @pre VOL_LOCK held. Function has never been called before.
8041 * @post howMany cache entries are allocated, initialized, and added
8042 * to the LRU list. Header cache statistics are initialized.
8044 * @note only applicable to fileServer program type. Should only be
8045 * called once during volume package initialization.
8047 * @internal volume package internal use only.
8050 VInitVolumeHeaderCache(afs_uint32 howMany)
8052 struct volHeader *hp;
8053 if (programType != fileServer)
8055 queue_Init(&volume_hdr_LRU);
8056 volume_hdr_LRU.stats.free = 0;
8057 volume_hdr_LRU.stats.used = howMany;
8058 volume_hdr_LRU.stats.attached = 0;
8059 hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
8060 opr_Assert(hp != NULL);
8063 /* We are using ReleaseVolumeHeader to initialize the values on the header list
8064 * to ensure they have the right values
8066 ReleaseVolumeHeader(hp++);
8069 /* get a volume header off of the volume header LRU.
8071 * @return volume header
8072 * @retval NULL no usable volume header is available on the LRU
8074 * @pre VOL_LOCK held
8076 * @post for DAFS, if the returned header is associated with a volume, that
8077 * volume is NOT in an exclusive state
8079 * @internal volume package internal use only.
8081 #ifdef AFS_DEMAND_ATTACH_FS
8082 static struct volHeader*
8083 GetVolHeaderFromLRU(void)
8085 struct volHeader *hd = NULL, *qh, *nqh;
8086 /* Usually, a volume in an exclusive state will not have its header on
8087 * the LRU. However, it is possible for this to occur when a salvage
8088 * request is received over FSSYNC, and possibly in other corner cases.
8089 * So just skip over headers whose volumes are in an exclusive state. We
8090 * could VWaitExclusiveState_r instead, but not waiting is faster and
8092 for (queue_Scan(&volume_hdr_LRU, qh, nqh, volHeader)) {
8093 if (!qh->back || !VIsExclusiveState(V_attachState(qh->back))) {
8101 #else /* AFS_DEMAND_ATTACH_FS */
8102 static struct volHeader*
8103 GetVolHeaderFromLRU(void)
8105 struct volHeader *hd = NULL;
8106 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
8107 hd = queue_First(&volume_hdr_LRU, volHeader);
8112 #endif /* !AFS_DEMAND_ATTACH_FS */
8115 * get a volume header and attach it to the volume object.
8117 * @param[in] vp pointer to volume object
8119 * @return cache entry status
8120 * @retval 0 volume header was newly attached; cache data is invalid
8121 * @retval 1 volume header was previously attached; cache data is valid
8123 * @pre VOL_LOCK held. For DAFS, lightweight ref must be held on volume object.
8125 * @post volume header attached to volume object. if necessary, header cache
8126 * entry on LRU is synchronized to disk. Header is removed from LRU list.
8128 * @note VOL_LOCK may be dropped
8130 * @warning this interface does not load header data from disk. it merely
8131 * attaches a header object to the volume object, and may sync the old
8132 * header cache data out to disk in the process.
8134 * @internal volume package internal use only.
8137 GetVolumeHeader(Volume * vp)
8140 struct volHeader *hd;
8142 static int everLogged = 0;
8144 #ifdef AFS_DEMAND_ATTACH_FS
8145 VolState vp_save = 0, back_save = 0;
8147 /* XXX debug 9/19/05 we've apparently got
8148 * a ref counting bug somewhere that's
8149 * breaking the nUsers == 0 => header on LRU
8151 if (vp->header && queue_IsNotOnQueue(vp->header)) {
8152 Log("nUsers == 0, but header not on LRU\n");
8157 old = (vp->header != NULL); /* old == volume already has a header */
8159 if (programType != fileServer) {
8160 /* for volume utilities, we allocate volHeaders as needed */
8162 hd = calloc(1, sizeof(*vp->header));
8163 opr_Assert(hd != NULL);
8166 #ifdef AFS_DEMAND_ATTACH_FS
8167 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8171 /* for the fileserver, we keep a volume header cache */
8173 /* the header we previously dropped in the lru is
8174 * still available. pull it off the lru and return */
8177 opr_Assert(hd->back == vp);
8178 #ifdef AFS_DEMAND_ATTACH_FS
8179 V_attachFlags(vp) &= ~(VOL_HDR_IN_LRU);
8182 hd = GetVolHeaderFromLRU();
8184 /* LRU is empty, so allocate a new volHeader
8185 * this is probably indicative of a leak, so let the user know */
8186 hd = calloc(1, sizeof(struct volHeader));
8187 opr_Assert(hd != NULL);
8189 Log("****Allocated more volume headers, probably leak****\n");
8192 volume_hdr_LRU.stats.free++;
8195 /* this header used to belong to someone else.
8196 * we'll need to check if the header needs to
8197 * be sync'd out to disk */
8199 #ifdef AFS_DEMAND_ATTACH_FS
8200 /* GetVolHeaderFromLRU had better not give us back a header
8201 * with a volume in exclusive state... */
8202 opr_Assert(!VIsExclusiveState(V_attachState(hd->back)));
8205 if (hd->diskstuff.inUse) {
8206 /* volume was in use, so we'll need to sync
8207 * its header to disk */
8209 #ifdef AFS_DEMAND_ATTACH_FS
8210 back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
8211 vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
8212 VCreateReservation_r(hd->back);
8216 WriteVolumeHeader_r(&error, hd->back);
8217 /* Ignore errors; catch them later */
8219 #ifdef AFS_DEMAND_ATTACH_FS
8224 hd->back->header = NULL;
8225 #ifdef AFS_DEMAND_ATTACH_FS
8226 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
8228 if (hd->diskstuff.inUse) {
8229 VChangeState_r(hd->back, back_save);
8230 VCancelReservation_r(hd->back);
8231 VChangeState_r(vp, vp_save);
8235 volume_hdr_LRU.stats.attached++;
8239 #ifdef AFS_DEMAND_ATTACH_FS
8240 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8243 volume_hdr_LRU.stats.free--;
8244 volume_hdr_LRU.stats.used++;
8246 IncUInt64(&VStats.hdr_gets);
8247 #ifdef AFS_DEMAND_ATTACH_FS
8248 IncUInt64(&vp->stats.hdr_gets);
8249 vp->stats.last_hdr_get = FT_ApproxTime();
8256 * make sure volume header is attached and contains valid cache data.
8258 * @param[out] ec outbound error code
8259 * @param[in] vp pointer to volume object
8261 * @pre VOL_LOCK held. For DAFS, lightweight ref held on vp.
8263 * @post header cache entry attached, and loaded with valid data, or
8264 * *ec is nonzero, and the header is released back into the LRU.
8266 * @internal volume package internal use only.
8269 LoadVolumeHeader(Error * ec, Volume * vp)
8271 #ifdef AFS_DEMAND_ATTACH_FS
8272 VolState state_save;
8276 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8277 IncUInt64(&VStats.hdr_loads);
8278 state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
8281 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8282 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8284 IncUInt64(&vp->stats.hdr_loads);
8285 now = FT_ApproxTime();
8289 V_attachFlags(vp) |= VOL_HDR_LOADED;
8290 vp->stats.last_hdr_load = now;
8292 VChangeState_r(vp, state_save);
8294 #else /* AFS_DEMAND_ATTACH_FS */
8296 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8297 IncUInt64(&VStats.hdr_loads);
8299 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8300 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8303 #endif /* AFS_DEMAND_ATTACH_FS */
8305 /* maintain (nUsers==0) => header in LRU invariant */
8306 FreeVolumeHeader(vp);
8311 * release a header cache entry back into the LRU list.
8313 * @param[in] hd pointer to volume header cache object
8315 * @pre VOL_LOCK held.
8317 * @post header cache object appended onto end of LRU list.
8319 * @note only applicable to fileServer program type.
8321 * @note used to place a header cache entry back into the
8322 * LRU pool without invalidating it as a cache entry.
8324 * @internal volume package internal use only.
8327 ReleaseVolumeHeader(struct volHeader *hd)
8329 if (programType != fileServer)
8331 if (!hd || queue_IsOnQueue(hd)) /* no header, or header already released */
8333 queue_Append(&volume_hdr_LRU, hd);
8334 #ifdef AFS_DEMAND_ATTACH_FS
8336 V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
8339 volume_hdr_LRU.stats.free++;
8340 volume_hdr_LRU.stats.used--;
8344 * free/invalidate a volume header cache entry.
8346 * @param[in] vp pointer to volume object
8348 * @pre VOL_LOCK is held.
8350 * @post For fileserver, header cache entry is returned to LRU, and it is
8351 * invalidated as a cache entry. For volume utilities, the header
8352 * cache entry is freed.
8354 * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
8355 * whenever it is necessary to invalidate the header cache entry.
8357 * @see ReleaseVolumeHeader
8359 * @internal volume package internal use only.
8362 FreeVolumeHeader(Volume * vp)
8364 struct volHeader *hd = vp->header;
8367 if (programType == fileServer) {
8368 ReleaseVolumeHeader(hd);
8373 #ifdef AFS_DEMAND_ATTACH_FS
8374 V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
8376 volume_hdr_LRU.stats.attached--;
8381 /***************************************************/
8382 /* Volume Hash Table routines */
8383 /***************************************************/
8386 * set size of volume object hash table.
8388 * @param[in] logsize log(2) of desired hash table size
8390 * @return operation status
8392 * @retval -1 failure
8394 * @pre MUST be called prior to VInitVolumePackage2
8396 * @post Volume Hash Table will have 2^logsize buckets
8399 VSetVolHashSize(int logsize)
8401 /* 64 to 268435456 hash buckets seems like a reasonable range */
8402 if ((logsize < 6 ) || (logsize > 28)) {
8407 VolumeHashTable.Size = 1 << logsize;
8408 VolumeHashTable.Mask = VolumeHashTable.Size - 1;
8410 /* we can't yet support runtime modification of this
8411 * parameter. we'll need a configuration rwlock to
8412 * make runtime modification feasible.... */
8419 * initialize dynamic data structures for volume hash table.
8421 * @post hash table is allocated, and fields are initialized.
8423 * @internal volume package internal use only.
8426 VInitVolumeHash(void)
8430 VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
8431 sizeof(VolumeHashChainHead));
8432 opr_Assert(VolumeHashTable.Table != NULL);
8434 for (i=0; i < VolumeHashTable.Size; i++) {
8435 queue_Init(&VolumeHashTable.Table[i]);
8436 #ifdef AFS_DEMAND_ATTACH_FS
8437 opr_cv_init(&VolumeHashTable.Table[i].chain_busy_cv);
8438 #endif /* AFS_DEMAND_ATTACH_FS */
8443 * add a volume object to the hash table.
8445 * @param[in] vp pointer to volume object
8446 * @param[in] hashid hash of volume id
8448 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8451 * @post volume is added to hash chain.
8453 * @internal volume package internal use only.
8455 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8456 * asynchronous hash chain reordering to finish.
8459 AddVolumeToHashTable(Volume * vp, VolumeId hashid)
8461 VolumeHashChainHead * head;
8463 if (queue_IsOnQueue(vp))
8466 head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
8468 #ifdef AFS_DEMAND_ATTACH_FS
8469 /* wait for the hash chain to become available */
8472 V_attachFlags(vp) |= VOL_IN_HASH;
8473 vp->chainCacheCheck = ++head->cacheCheck;
8474 #endif /* AFS_DEMAND_ATTACH_FS */
8477 vp->hashid = hashid;
8478 queue_Append(head, vp);
8479 vp->vnodeHashOffset = VolumeHashOffset_r();
8483 * delete a volume object from the hash table.
8485 * @param[in] vp pointer to volume object
8487 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8490 * @post volume is removed from hash chain.
8492 * @internal volume package internal use only.
8494 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8495 * asynchronous hash chain reordering to finish.
8498 DeleteVolumeFromHashTable(Volume * vp)
8500 VolumeHashChainHead * head;
8502 if (!queue_IsOnQueue(vp))
8505 head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
8507 #ifdef AFS_DEMAND_ATTACH_FS
8508 /* wait for the hash chain to become available */
8511 V_attachFlags(vp) &= ~(VOL_IN_HASH);
8513 #endif /* AFS_DEMAND_ATTACH_FS */
8517 /* do NOT reset hashid to zero, as the online
8518 * salvager package may need to know the volume id
8519 * after the volume is removed from the hash */
8523 * lookup a volume object in the hash table given a volume id.
8525 * @param[out] ec error code return
8526 * @param[in] volumeId volume id
8527 * @param[in] hint volume object which we believe could be the correct
8530 * @return volume object pointer
8531 * @retval NULL no such volume id is registered with the hash table.
8533 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8536 * @post volume object with the given id is returned. volume object and
8537 * hash chain access statistics are updated. hash chain may have
8540 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8541 * asynchronous hash chain reordering operation to finish, or
8542 * in order for us to perform an asynchronous chain reordering.
8544 * @note Hash chain reorderings occur when the access count for the
8545 * volume object being looked up exceeds the sum of the previous
8546 * node's (the node ahead of it in the hash chain linked list)
8547 * access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
8549 * @note For DAFS, the hint parameter allows us to short-circuit if the
8550 * cacheCheck fields match between the hash chain head and the
8551 * hint volume object.
8554 VLookupVolume_r(Error * ec, VolumeId volumeId, Volume * hint)
8558 #ifdef AFS_DEMAND_ATTACH_FS
8561 VolumeHashChainHead * head;
8564 head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
8566 #ifdef AFS_DEMAND_ATTACH_FS
8567 /* wait for the hash chain to become available */
8570 /* check to see if we can short circuit without walking the hash chain */
8571 if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
8572 IncUInt64(&hint->stats.hash_short_circuits);
8575 #endif /* AFS_DEMAND_ATTACH_FS */
8577 /* someday we need to either do per-chain locks, RWlocks,
8578 * or both for volhash access.
8579 * (and move to a data structure with better cache locality) */
8581 /* search the chain for this volume id */
8582 for(queue_Scan(head, vp, np, Volume)) {
8584 if (vp->hashid == volumeId) {
8589 if (queue_IsEnd(head, vp)) {
8593 #ifdef AFS_DEMAND_ATTACH_FS
8594 /* update hash chain statistics */
8597 FillInt64(lks, 0, looks);
8598 AddUInt64(head->looks, lks, &head->looks);
8599 AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
8600 IncUInt64(&head->gets);
8605 IncUInt64(&vp->stats.hash_lookups);
8607 /* for demand attach fileserver, we permit occasional hash chain reordering
8608 * so that frequently looked up volumes move towards the head of the chain */
8609 pp = queue_Prev(vp, Volume);
8610 if (!queue_IsEnd(head, pp)) {
8611 FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
8612 AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
8613 if (GEInt64(vp->stats.hash_lookups, thresh)) {
8614 VReorderHash_r(head, pp, vp);
8618 /* update the short-circuit cache check */
8619 vp->chainCacheCheck = head->cacheCheck;
8621 #endif /* AFS_DEMAND_ATTACH_FS */
8626 #ifdef AFS_DEMAND_ATTACH_FS
8627 /* perform volume hash chain reordering.
8629 * advance a subchain beginning at vp ahead of
8630 * the adjacent subchain ending at pp */
8632 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
8634 Volume *tp, *np, *lp;
8635 afs_uint64 move_thresh;
8637 /* this should never be called if the chain is already busy, so
8638 * no need to wait for other exclusive chain ops to finish */
8640 /* this is a rather heavy set of operations,
8641 * so let's set the chain busy flag and drop
8643 VHashBeginExclusive_r(head);
8646 /* scan forward in the chain from vp looking for the last element
8647 * in the chain we want to advance */
8648 FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
8649 AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
8650 for(queue_ScanFrom(head, vp, tp, np, Volume)) {
8651 if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
8655 lp = queue_Prev(tp, Volume);
8657 /* scan backwards from pp to determine where to splice and
8658 * insert the subchain we're advancing */
8659 for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
8660 if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
8664 tp = queue_Next(tp, Volume);
8666 /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
8667 queue_MoveChainBefore(tp,vp,lp);
8670 IncUInt64(&VStats.hash_reorders);
8672 IncUInt64(&head->reorders);
8674 /* wake up any threads waiting for the hash chain */
8675 VHashEndExclusive_r(head);
8679 /* demand-attach fs volume hash
8680 * asynchronous exclusive operations */
8683 * begin an asynchronous exclusive operation on a volume hash chain.
8685 * @param[in] head pointer to volume hash chain head object
8687 * @pre VOL_LOCK held. hash chain is quiescent.
8689 * @post hash chain marked busy.
8691 * @note this interface is used in conjunction with VHashEndExclusive_r and
8692 * VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8693 * volume hash chain. Its main use case is hash chain reordering, which
8694 * has the potential to be a highly latent operation.
8696 * @see VHashEndExclusive_r
8701 * @internal volume package internal use only.
8704 VHashBeginExclusive_r(VolumeHashChainHead * head)
8706 opr_Assert(head->busy == 0);
8711 * relinquish exclusive ownership of a volume hash chain.
8713 * @param[in] head pointer to volume hash chain head object
8715 * @pre VOL_LOCK held. thread owns the hash chain exclusively.
8717 * @post hash chain is marked quiescent. threads awaiting use of
8718 * chain are awakened.
8720 * @see VHashBeginExclusive_r
8725 * @internal volume package internal use only.
8728 VHashEndExclusive_r(VolumeHashChainHead * head)
8730 opr_Assert(head->busy);
8732 opr_cv_broadcast(&head->chain_busy_cv);
8736 * wait for all asynchronous operations on a hash chain to complete.
8738 * @param[in] head pointer to volume hash chain head object
8740 * @pre VOL_LOCK held.
8742 * @post hash chain object is quiescent.
8744 * @see VHashBeginExclusive_r
8745 * @see VHashEndExclusive_r
8749 * @note This interface should be called before any attempt to
8750 * traverse the hash chain. It is permissible for a thread
8751 * to gain exclusive access to the chain, and then perform
8752 * latent operations on the chain asynchronously wrt the
8755 * @warning if waiting is necessary, VOL_LOCK is dropped
8757 * @internal volume package internal use only.
8760 VHashWait_r(VolumeHashChainHead * head)
8762 while (head->busy) {
8763 VOL_CV_WAIT(&head->chain_busy_cv);
8766 #endif /* AFS_DEMAND_ATTACH_FS */
8769 /***************************************************/
8770 /* Volume by Partition List routines */
8771 /***************************************************/
8774 * demand attach fileserver adds a
8775 * linked list of volumes to each
8776 * partition object, thus allowing
8777 * for quick enumeration of all
8778 * volumes on a partition
8781 #ifdef AFS_DEMAND_ATTACH_FS
8783 * add a volume to its disk partition VByPList.
8785 * @param[in] vp pointer to volume object
8787 * @pre either the disk partition VByPList is owned exclusively
8788 * by the calling thread, or the list is quiescent and
8791 * @post volume is added to disk partition VByPList
8795 * @warning it is the caller's responsibility to ensure list
8798 * @see VVByPListWait_r
8799 * @see VVByPListBeginExclusive_r
8800 * @see VVByPListEndExclusive_r
8802 * @internal volume package internal use only.
8805 AddVolumeToVByPList_r(Volume * vp)
8807 if (queue_IsNotOnQueue(&vp->vol_list)) {
8808 queue_Append(&vp->partition->vol_list, &vp->vol_list);
8809 V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
8810 vp->partition->vol_list.len++;
8815 * delete a volume from its disk partition VByPList.
8817 * @param[in] vp pointer to volume object
8819 * @pre either the disk partition VByPList is owned exclusively
8820 * by the calling thread, or the list is quiescent and
8823 * @post volume is removed from the disk partition VByPList
8827 * @warning it is the caller's responsibility to ensure list
8830 * @see VVByPListWait_r
8831 * @see VVByPListBeginExclusive_r
8832 * @see VVByPListEndExclusive_r
8834 * @internal volume package internal use only.
8837 DeleteVolumeFromVByPList_r(Volume * vp)
8839 if (queue_IsOnQueue(&vp->vol_list)) {
8840 queue_Remove(&vp->vol_list);
8841 V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
8842 vp->partition->vol_list.len--;
8847 * begin an asynchronous exclusive operation on a VByPList.
8849 * @param[in] dp pointer to disk partition object
8851 * @pre VOL_LOCK held. VByPList is quiescent.
8853 * @post VByPList marked busy.
8855 * @note this interface is used in conjunction with VVByPListEndExclusive_r and
8856 * VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8859 * @see VVByPListEndExclusive_r
8860 * @see VVByPListWait_r
8864 * @internal volume package internal use only.
8866 /* take exclusive control over the list */
8868 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
8870 opr_Assert(dp->vol_list.busy == 0);
8871 dp->vol_list.busy = 1;
8875 * relinquish exclusive ownership of a VByPList.
8877 * @param[in] dp pointer to disk partition object
8879 * @pre VOL_LOCK held. thread owns the VByPList exclusively.
8881 * @post VByPList is marked quiescent. threads awaiting use of
8882 * the list are awakened.
8884 * @see VVByPListBeginExclusive_r
8885 * @see VVByPListWait_r
8889 * @internal volume package internal use only.
8892 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
8894 opr_Assert(dp->vol_list.busy);
8895 dp->vol_list.busy = 0;
8896 opr_cv_broadcast(&dp->vol_list.cv);
8900 * wait for all asynchronous operations on a VByPList to complete.
8902 * @param[in] dp pointer to disk partition object
8904 * @pre VOL_LOCK is held.
8906 * @post disk partition's VByP list is quiescent
8910 * @note This interface should be called before any attempt to
8911 * traverse the VByPList. It is permissible for a thread
8912 * to gain exclusive access to the list, and then perform
8913 * latent operations on the list asynchronously wrt the
8916 * @warning if waiting is necessary, VOL_LOCK is dropped
8918 * @see VVByPListEndExclusive_r
8919 * @see VVByPListBeginExclusive_r
8921 * @internal volume package internal use only.
8924 VVByPListWait_r(struct DiskPartition64 * dp)
8926 while (dp->vol_list.busy) {
8927 VOL_CV_WAIT(&dp->vol_list.cv);
8930 #endif /* AFS_DEMAND_ATTACH_FS */
8932 /***************************************************/
8933 /* Volume Cache Statistics routines */
8934 /***************************************************/
8937 VPrintCacheStats_r(void)
8939 struct VnodeClassInfo *vcp;
8940 vcp = &VnodeClassInfo[vLarge];
8941 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);
8942 vcp = &VnodeClassInfo[vSmall];
8943 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);
8944 Log("Volume header cache, %d entries, %"AFS_INT64_FMT" gets, "
8945 "%"AFS_INT64_FMT" replacements\n",
8946 VStats.hdr_cache_size, VStats.hdr_gets, VStats.hdr_loads);
8950 VPrintCacheStats(void)
8953 VPrintCacheStats_r();
8957 #ifdef AFS_DEMAND_ATTACH_FS
8959 UInt64ToDouble(afs_uint64 * x)
8961 static double c32 = 4.0 * 1.073741824 * 1000000000.0;
8963 SplitInt64(*x, h, l);
8964 return (((double)h) * c32) + ((double) l);
8968 DoubleToPrintable(double x, char * buf, int len)
8970 static double billion = 1000000000.0;
8973 y[0] = (afs_uint32) (x / (billion * billion));
8974 y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
8975 y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
8978 snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
8980 snprintf(buf, len, "%d%09d", y[1], y[2]);
8982 snprintf(buf, len, "%d", y[2]);
8988 struct VLRUExtStatsEntry {
8992 struct VLRUExtStats {
8998 } queue_info[VLRU_QUEUE_INVALID];
8999 struct VLRUExtStatsEntry * vec;
9003 * add a 256-entry fudge factor onto the vector in case state changes
9004 * out from under us.
9006 #define VLRU_EXT_STATS_VEC_LEN_FUDGE 256
9009 * collect extended statistics for the VLRU subsystem.
9011 * @param[out] stats pointer to stats structure to be populated
9012 * @param[in] nvols number of volumes currently known to exist
9014 * @pre VOL_LOCK held
9016 * @post stats->vec allocated and populated
9018 * @return operation status
9023 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
9025 afs_uint32 cur, idx, len;
9026 struct rx_queue * qp, * nqp;
9028 struct VLRUExtStatsEntry * vec;
9030 len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
9031 vec = stats->vec = calloc(len,
9032 sizeof(struct VLRUExtStatsEntry));
9038 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
9039 VLRU_Wait_r(&volume_LRU.q[idx]);
9040 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
9043 stats->queue_info[idx].start = cur;
9045 for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
9047 /* out of space in vec */
9050 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
9051 vec[cur].volid = vp->hashid;
9055 stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
9058 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
9066 #define ENUMTOSTRING(en) #en
9067 #define ENUMCASE(en) \
9068 case en: return ENUMTOSTRING(en)
9071 vlru_idx_to_string(int idx)
9074 ENUMCASE(VLRU_QUEUE_NEW);
9075 ENUMCASE(VLRU_QUEUE_MID);
9076 ENUMCASE(VLRU_QUEUE_OLD);
9077 ENUMCASE(VLRU_QUEUE_CANDIDATE);
9078 ENUMCASE(VLRU_QUEUE_HELD);
9079 ENUMCASE(VLRU_QUEUE_INVALID);
9081 return "**UNKNOWN**";
9086 VPrintExtendedCacheStats_r(int flags)
9089 afs_uint32 vol_sum = 0;
9096 struct stats looks, gets, reorders, len;
9097 struct stats ch_looks, ch_gets, ch_reorders;
9099 VolumeHashChainHead *head;
9101 struct VLRUExtStats vlru_stats;
9103 /* zero out stats */
9104 memset(&looks, 0, sizeof(struct stats));
9105 memset(&gets, 0, sizeof(struct stats));
9106 memset(&reorders, 0, sizeof(struct stats));
9107 memset(&len, 0, sizeof(struct stats));
9108 memset(&ch_looks, 0, sizeof(struct stats));
9109 memset(&ch_gets, 0, sizeof(struct stats));
9110 memset(&ch_reorders, 0, sizeof(struct stats));
9112 for (i = 0; i < VolumeHashTable.Size; i++) {
9113 head = &VolumeHashTable.Table[i];
9116 VHashBeginExclusive_r(head);
9119 ch_looks.sum = UInt64ToDouble(&head->looks);
9120 ch_gets.sum = UInt64ToDouble(&head->gets);
9121 ch_reorders.sum = UInt64ToDouble(&head->reorders);
9123 /* update global statistics */
9125 looks.sum += ch_looks.sum;
9126 gets.sum += ch_gets.sum;
9127 reorders.sum += ch_reorders.sum;
9128 len.sum += (double)head->len;
9129 vol_sum += head->len;
9132 len.min = (double) head->len;
9133 len.max = (double) head->len;
9134 looks.min = ch_looks.sum;
9135 looks.max = ch_looks.sum;
9136 gets.min = ch_gets.sum;
9137 gets.max = ch_gets.sum;
9138 reorders.min = ch_reorders.sum;
9139 reorders.max = ch_reorders.sum;
9141 if (((double)head->len) < len.min)
9142 len.min = (double) head->len;
9143 if (((double)head->len) > len.max)
9144 len.max = (double) head->len;
9145 if (ch_looks.sum < looks.min)
9146 looks.min = ch_looks.sum;
9147 else if (ch_looks.sum > looks.max)
9148 looks.max = ch_looks.sum;
9149 if (ch_gets.sum < gets.min)
9150 gets.min = ch_gets.sum;
9151 else if (ch_gets.sum > gets.max)
9152 gets.max = ch_gets.sum;
9153 if (ch_reorders.sum < reorders.min)
9154 reorders.min = ch_reorders.sum;
9155 else if (ch_reorders.sum > reorders.max)
9156 reorders.max = ch_reorders.sum;
9160 if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
9161 /* compute detailed per-chain stats */
9162 struct stats hdr_loads, hdr_gets;
9163 double v_looks, v_loads, v_gets;
9165 /* initialize stats with data from first element in chain */
9166 vp = queue_First(head, Volume);
9167 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
9168 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
9169 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
9170 ch_gets.min = ch_gets.max = v_looks;
9171 hdr_loads.min = hdr_loads.max = v_loads;
9172 hdr_gets.min = hdr_gets.max = v_gets;
9173 hdr_loads.sum = hdr_gets.sum = 0;
9175 vp = queue_Next(vp, Volume);
9177 /* pull in stats from remaining elements in chain */
9178 for (queue_ScanFrom(head, vp, vp, np, Volume)) {
9179 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
9180 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
9181 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
9183 hdr_loads.sum += v_loads;
9184 hdr_gets.sum += v_gets;
9186 if (v_looks < ch_gets.min)
9187 ch_gets.min = v_looks;
9188 else if (v_looks > ch_gets.max)
9189 ch_gets.max = v_looks;
9191 if (v_loads < hdr_loads.min)
9192 hdr_loads.min = v_loads;
9193 else if (v_loads > hdr_loads.max)
9194 hdr_loads.max = v_loads;
9196 if (v_gets < hdr_gets.min)
9197 hdr_gets.min = v_gets;
9198 else if (v_gets > hdr_gets.max)
9199 hdr_gets.max = v_gets;
9202 /* compute per-chain averages */
9203 ch_gets.avg = ch_gets.sum / ((double)head->len);
9204 hdr_loads.avg = hdr_loads.sum / ((double)head->len);
9205 hdr_gets.avg = hdr_gets.sum / ((double)head->len);
9207 /* dump per-chain stats */
9208 Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
9210 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9211 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
9212 Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
9213 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9214 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9215 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9216 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9217 Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
9218 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9219 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9220 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9221 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9222 Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
9223 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
9224 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
9225 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
9226 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
9227 } else if (flags & VOL_STATS_PER_CHAIN) {
9228 /* dump simple per-chain stats */
9229 Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
9231 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9232 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
9233 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
9237 VHashEndExclusive_r(head);
9242 /* compute global averages */
9243 len.avg = len.sum / ((double)VolumeHashTable.Size);
9244 looks.avg = looks.sum / ((double)VolumeHashTable.Size);
9245 gets.avg = gets.sum / ((double)VolumeHashTable.Size);
9246 reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
9248 /* dump global stats */
9249 Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
9250 Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
9251 DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
9252 DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
9253 DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
9254 DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
9255 Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
9256 DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
9257 DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
9258 DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
9259 DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
9260 Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
9261 DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
9262 DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
9263 DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9264 DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9265 Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
9266 DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
9267 DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
9268 DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
9269 DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
9271 /* print extended disk related statistics */
9273 struct DiskPartition64 * diskP;
9274 afs_uint32 vol_count[VOLMAXPARTS+1];
9275 byte part_exists[VOLMAXPARTS+1];
9279 memset(vol_count, 0, sizeof(vol_count));
9280 memset(part_exists, 0, sizeof(part_exists));
9284 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
9286 vol_count[id] = diskP->vol_list.len;
9287 part_exists[id] = 1;
9291 for (i = 0; i <= VOLMAXPARTS; i++) {
9292 if (part_exists[i]) {
9293 /* XXX while this is currently safe, it is a violation
9294 * of the VGetPartitionById_r interface contract. */
9295 diskP = VGetPartitionById_r(i, 0);
9297 Log("Partition %s has %d online volumes\n",
9298 VPartitionPath(diskP), diskP->vol_list.len);
9305 /* print extended VLRU statistics */
9306 if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
9307 afs_uint32 idx, cur, lpos;
9312 Log("VLRU State Dump:\n\n");
9314 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
9315 Log("\t%s:\n", vlru_idx_to_string(idx));
9318 for (cur = vlru_stats.queue_info[idx].start;
9319 cur < vlru_stats.queue_info[idx].len;
9321 line[lpos++] = vlru_stats.vec[cur].volid;
9323 Log("\t\t%u, %u, %u, %u, %u,\n",
9324 line[0], line[1], line[2], line[3], line[4]);
9333 Log("\t\t%u, %u, %u, %u, %u\n",
9334 line[0], line[1], line[2], line[3], line[4]);
9339 free(vlru_stats.vec);
9346 VPrintExtendedCacheStats(int flags)
9349 VPrintExtendedCacheStats_r(flags);
9352 #endif /* AFS_DEMAND_ATTACH_FS */
9355 VCanScheduleSalvage(void)
9357 return vol_opts.canScheduleSalvage;
9363 return vol_opts.canUseFSSYNC;
9367 VCanUseSALVSYNC(void)
9369 return vol_opts.canUseSALVSYNC;
9373 VCanUnsafeAttach(void)
9375 return vol_opts.unsafe_attach;