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>
29 #ifdef HAVE_SYS_FILE_H
34 #include <afs/afsint.h>
37 #if !defined(AFS_SGI_ENV)
40 #else /* AFS_OSF_ENV */
41 #ifdef AFS_VFSINCL_ENV
44 #include <sys/fs/ufs_fs.h>
46 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
47 #include <ufs/ufs/dinode.h>
48 #include <ufs/ffs/fs.h>
53 #else /* AFS_VFSINCL_ENV */
54 #if !defined(AFS_AIX_ENV) && !defined(AFS_LINUX20_ENV) && !defined(AFS_XBSD_ENV) && !defined(AFS_DARWIN_ENV)
57 #endif /* AFS_VFSINCL_ENV */
58 #endif /* AFS_OSF_ENV */
59 #endif /* AFS_SGI_ENV */
60 #endif /* !AFS_NT40_ENV */
68 #if defined(AFS_SUN_ENV) || defined(AFS_SUN5_ENV)
70 #include <sys/mnttab.h>
71 #include <sys/mntent.h>
77 #if defined(AFS_SGI_ENV)
80 #ifndef AFS_LINUX20_ENV
81 #include <fstab.h> /* Need to find in libc 5, present in libc 6 */
84 #endif /* AFS_SGI_ENV */
86 #endif /* AFS_HPUX_ENV */
90 #include <afs/errors.h>
93 #include <afs/afssyscalls.h>
95 #include <afs/afsutil.h>
96 #include "daemon_com.h"
101 #include "partition.h"
102 #include "volume_inline.h"
104 #include "afs/afs_assert.h"
108 #ifdef AFS_PTHREAD_ENV
109 pthread_mutex_t vol_glock_mutex;
110 pthread_mutex_t vol_trans_mutex;
111 pthread_cond_t vol_put_volume_cond;
112 pthread_cond_t vol_sleep_cond;
113 pthread_cond_t vol_init_attach_cond;
114 pthread_cond_t vol_vinit_cond;
115 int vol_attach_threads = 1;
116 #endif /* AFS_PTHREAD_ENV */
118 /* start-time configurable I/O parameters */
119 ih_init_params vol_io_params;
121 #ifdef AFS_DEMAND_ATTACH_FS
122 pthread_mutex_t vol_salvsync_mutex;
125 * Set this to 1 to disallow SALVSYNC communication in all threads; used
126 * during shutdown, since the salvageserver may have gone away.
128 static volatile sig_atomic_t vol_disallow_salvsync = 0;
129 #endif /* AFS_DEMAND_ATTACH_FS */
132 * has VShutdown_r been called / is VShutdown_r running?
134 static int vol_shutting_down = 0;
137 extern void *calloc(), *realloc();
140 /* Forward declarations */
141 static Volume *attach2(Error * ec, VolId volumeId, char *path,
142 struct DiskPartition64 *partp, Volume * vp,
143 int isbusy, int mode, int *acheckedOut);
144 static void ReallyFreeVolume(Volume * vp);
145 #ifdef AFS_DEMAND_ATTACH_FS
146 static void FreeVolume(Volume * vp);
147 #else /* !AFS_DEMAND_ATTACH_FS */
148 #define FreeVolume(vp) ReallyFreeVolume(vp)
149 static void VScanUpdateList(void);
150 #endif /* !AFS_DEMAND_ATTACH_FS */
151 static void VInitVolumeHeaderCache(afs_uint32 howMany);
152 static int GetVolumeHeader(Volume * vp);
153 static void ReleaseVolumeHeader(struct volHeader *hd);
154 static void FreeVolumeHeader(Volume * vp);
155 static void AddVolumeToHashTable(Volume * vp, int hashid);
156 static void DeleteVolumeFromHashTable(Volume * vp);
158 static int VHold(Volume * vp);
160 static int VHold_r(Volume * vp);
161 static void VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class);
162 static void VReleaseVolumeHandles_r(Volume * vp);
163 static void VCloseVolumeHandles_r(Volume * vp);
164 static void LoadVolumeHeader(Error * ec, Volume * vp);
165 static int VCheckOffline(Volume * vp);
166 static int VCheckDetach(Volume * vp);
167 static Volume * GetVolume(Error * ec, Error * client_ec, VolId volumeId,
168 Volume * hint, const struct timespec *ts);
170 int LogLevel; /* Vice loglevel--not defined as extern so that it will be
171 * defined when not linked with vice, XXXX */
172 ProgramType programType; /* The type of program using the package */
173 static VolumePackageOptions vol_opts;
175 /* extended volume package statistics */
178 #ifdef VOL_LOCK_DEBUG
179 pthread_t vol_glock_holder = 0;
183 #define VOLUME_BITMAP_GROWSIZE 16 /* bytes, => 128vnodes */
184 /* Must be a multiple of 4 (1 word) !! */
186 /* this parameter needs to be tunable at runtime.
187 * 128 was really inadequate for largish servers -- at 16384 volumes this
188 * puts average chain length at 128, thus an average 65 deref's to find a volptr.
189 * talk about bad spatial locality...
191 * an AVL or splay tree might work a lot better, but we'll just increase
192 * the default hash table size for now
194 #define DEFAULT_VOLUME_HASH_SIZE 256 /* Must be a power of 2!! */
195 #define DEFAULT_VOLUME_HASH_MASK (DEFAULT_VOLUME_HASH_SIZE-1)
196 #define VOLUME_HASH(volumeId) (volumeId&(VolumeHashTable.Mask))
199 * turn volume hash chains into partially ordered lists.
200 * when the threshold is exceeded between two adjacent elements,
201 * perform a chain rebalancing operation.
203 * keep the threshold high in order to keep cache line invalidates
204 * low "enough" on SMPs
206 #define VOLUME_HASH_REORDER_THRESHOLD 200
209 * when possible, don't just reorder single elements, but reorder
210 * entire chains of elements at once. a chain of elements that
211 * exceed the element previous to the pivot by at least CHAIN_THRESH
212 * accesses are moved in front of the chain whose elements have at
213 * least CHAIN_THRESH less accesses than the pivot element
215 #define VOLUME_HASH_REORDER_CHAIN_THRESH (VOLUME_HASH_REORDER_THRESHOLD / 2)
217 #include "rx/rx_queue.h"
220 VolumeHashTable_t VolumeHashTable = {
221 DEFAULT_VOLUME_HASH_SIZE,
222 DEFAULT_VOLUME_HASH_MASK,
227 static void VInitVolumeHash(void);
231 /* This macro is used where an ffs() call does not exist. Was in util/ffs.c */
235 afs_int32 ffs_tmp = x;
239 for (ffs_i = 1;; ffs_i++) {
246 #endif /* !AFS_HAVE_FFS */
248 #ifdef AFS_PTHREAD_ENV
250 * disk partition queue element
252 typedef struct diskpartition_queue_t {
253 struct rx_queue queue; /**< queue header */
254 struct DiskPartition64 *diskP; /**< disk partition table entry */
255 } diskpartition_queue_t;
257 #ifndef AFS_DEMAND_ATTACH_FS
259 typedef struct vinitvolumepackage_thread_t {
260 struct rx_queue queue;
261 pthread_cond_t thread_done_cv;
262 int n_threads_complete;
263 } vinitvolumepackage_thread_t;
264 static void * VInitVolumePackageThread(void * args);
266 #else /* !AFS_DEMAND_ATTTACH_FS */
267 #define VINIT_BATCH_MAX_SIZE 512
270 * disk partition work queue
272 struct partition_queue {
273 struct rx_queue head; /**< diskpartition_queue_t queue */
274 pthread_mutex_t mutex;
279 * volumes parameters for preattach
281 struct volume_init_batch {
282 struct rx_queue queue; /**< queue header */
283 int thread; /**< posting worker thread */
284 int last; /**< indicates thread is done */
285 int size; /**< number of volume ids in batch */
286 Volume *batch[VINIT_BATCH_MAX_SIZE]; /**< volumes ids to preattach */
290 * volume parameters work queue
292 struct volume_init_queue {
293 struct rx_queue head; /**< volume_init_batch queue */
294 pthread_mutex_t mutex;
299 * volume init worker thread parameters
301 struct vinitvolumepackage_thread_param {
302 int nthreads; /**< total number of worker threads */
303 int thread; /**< thread number for this worker thread */
304 struct partition_queue *pq; /**< queue partitions to scan */
305 struct volume_init_queue *vq; /**< queue of volume to preattach */
308 static void *VInitVolumePackageThread(void *args);
309 static struct DiskPartition64 *VInitNextPartition(struct partition_queue *pq);
310 static VolId VInitNextVolumeId(DIR *dirp);
311 static int VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq);
313 #endif /* !AFS_DEMAND_ATTACH_FS */
314 #endif /* AFS_PTHREAD_ENV */
316 #ifndef AFS_DEMAND_ATTACH_FS
317 static int VAttachVolumesByPartition(struct DiskPartition64 *diskP,
318 int * nAttached, int * nUnattached);
319 #endif /* AFS_DEMAND_ATTACH_FS */
322 #ifdef AFS_DEMAND_ATTACH_FS
323 /* demand attach fileserver extensions */
326 * in the future we will support serialization of VLRU state into the fs_state
329 * these structures are the beginning of that effort
331 struct VLRU_DiskHeader {
332 struct versionStamp stamp; /* magic and structure version number */
333 afs_uint32 mtime; /* time of dump to disk */
334 afs_uint32 num_records; /* number of VLRU_DiskEntry records */
337 struct VLRU_DiskEntry {
338 afs_uint32 vid; /* volume ID */
339 afs_uint32 idx; /* generation */
340 afs_uint32 last_get; /* timestamp of last get */
343 struct VLRU_StartupQueue {
344 struct VLRU_DiskEntry * entry;
349 typedef struct vshutdown_thread_t {
351 pthread_mutex_t lock;
353 pthread_cond_t master_cv;
355 int n_threads_complete;
357 int schedule_version;
360 byte n_parts_done_pass;
361 byte part_thread_target[VOLMAXPARTS+1];
362 byte part_done_pass[VOLMAXPARTS+1];
363 struct rx_queue * part_pass_head[VOLMAXPARTS+1];
364 int stats[4][VOLMAXPARTS+1];
365 } vshutdown_thread_t;
366 static void * VShutdownThread(void * args);
369 static Volume * VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode);
370 static int VCheckFree(Volume * vp);
373 static void AddVolumeToVByPList_r(Volume * vp);
374 static void DeleteVolumeFromVByPList_r(Volume * vp);
375 static void VVByPListBeginExclusive_r(struct DiskPartition64 * dp);
376 static void VVByPListEndExclusive_r(struct DiskPartition64 * dp);
377 static void VVByPListWait_r(struct DiskPartition64 * dp);
379 /* online salvager */
380 static int VCheckSalvage(Volume * vp);
381 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
382 static int VScheduleSalvage_r(Volume * vp);
385 /* Volume hash table */
386 static void VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp);
387 static void VHashBeginExclusive_r(VolumeHashChainHead * head);
388 static void VHashEndExclusive_r(VolumeHashChainHead * head);
389 static void VHashWait_r(VolumeHashChainHead * head);
392 static int ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass);
393 static int ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
394 struct rx_queue ** idx);
395 static void ShutdownController(vshutdown_thread_t * params);
396 static void ShutdownCreateSchedule(vshutdown_thread_t * params);
399 static void VLRU_ComputeConstants(void);
400 static void VInitVLRU(void);
401 static void VLRU_Init_Node_r(Volume * vp);
402 static void VLRU_Add_r(Volume * vp);
403 static void VLRU_Delete_r(Volume * vp);
404 static void VLRU_UpdateAccess_r(Volume * vp);
405 static void * VLRU_ScannerThread(void * args);
406 static void VLRU_Scan_r(int idx);
407 static void VLRU_Promote_r(int idx);
408 static void VLRU_Demote_r(int idx);
409 static void VLRU_SwitchQueues(Volume * vp, int new_idx, int append);
412 static int VCheckSoftDetach(Volume * vp, afs_uint32 thresh);
413 static int VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh);
414 static int VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh);
417 pthread_key_t VThread_key;
418 VThreadOptions_t VThread_defaults = {
419 0 /**< allow salvsync */
421 #endif /* AFS_DEMAND_ATTACH_FS */
424 struct Lock vol_listLock; /* Lock obtained when listing volumes:
425 * prevents a volume from being missed
426 * if the volume is attached during a
430 /* Common message used when the volume goes off line */
431 char *VSalvageMessage =
432 "Files in this volume are currently unavailable; call operations";
434 int VInit; /* 0 - uninitialized,
435 * 1 - initialized but not all volumes have been attached,
436 * 2 - initialized and all volumes have been attached,
437 * 3 - initialized, all volumes have been attached, and
438 * VConnectFS() has completed. */
440 static int vinit_attach_abort = 0;
442 bit32 VolumeCacheCheck; /* Incremented everytime a volume goes on line--
443 * used to stamp volume headers and in-core
444 * vnodes. When the volume goes on-line the
445 * vnode will be invalidated
446 * access only with VOL_LOCK held */
451 /***************************************************/
452 /* Startup routines */
453 /***************************************************/
455 #if defined(FAST_RESTART) && defined(AFS_DEMAND_ATTACH_FS)
456 # error FAST_RESTART and DAFS are incompatible. For the DAFS equivalent \
457 of FAST_RESTART, use the -unsafe-nosalvage fileserver argument
461 * assign default values to a VolumePackageOptions struct.
463 * Always call this on a VolumePackageOptions struct first, then set any
464 * specific options you want, then call VInitVolumePackage2.
466 * @param[in] pt caller's program type
467 * @param[out] opts volume package options
470 VOptDefaults(ProgramType pt, VolumePackageOptions *opts)
472 opts->nLargeVnodes = opts->nSmallVnodes = 5;
475 opts->canScheduleSalvage = 0;
476 opts->canUseFSSYNC = 0;
477 opts->canUseSALVSYNC = 0;
479 opts->interrupt_rxcall = NULL;
480 opts->offline_timeout = -1;
481 opts->offline_shutdown_timeout = -1;
484 opts->unsafe_attach = 1;
485 #else /* !FAST_RESTART */
486 opts->unsafe_attach = 0;
487 #endif /* !FAST_RESTART */
491 opts->canScheduleSalvage = 1;
492 opts->canUseSALVSYNC = 1;
496 opts->canUseFSSYNC = 1;
500 opts->nLargeVnodes = 0;
501 opts->nSmallVnodes = 0;
503 opts->canScheduleSalvage = 1;
504 opts->canUseFSSYNC = 1;
514 * Set VInit to a certain value, and signal waiters.
516 * @param[in] value the value to set VInit to
521 VSetVInit_r(int value)
524 CV_BROADCAST(&vol_vinit_cond);
528 VLogOfflineTimeout(const char *type, afs_int32 timeout)
534 Log("VInitVolumePackage: Interrupting clients accessing %s "
535 "immediately\n", type);
537 Log("VInitVolumePackage: Interrupting clients accessing %s "
538 "after %ld second%s\n", type, (long)timeout, timeout==1?"":"s");
543 VInitVolumePackage2(ProgramType pt, VolumePackageOptions * opts)
545 int errors = 0; /* Number of errors while finding vice partitions. */
550 #ifndef AFS_PTHREAD_ENV
551 if (opts->offline_timeout != -1 || opts->offline_shutdown_timeout != -1) {
552 Log("VInitVolumePackage: offline_timeout and/or "
553 "offline_shutdown_timeout was specified, but the volume package "
554 "does not support these for LWP builds\n");
558 VLogOfflineTimeout("volumes going offline", opts->offline_timeout);
559 VLogOfflineTimeout("volumes going offline during shutdown",
560 opts->offline_shutdown_timeout);
562 memset(&VStats, 0, sizeof(VStats));
563 VStats.hdr_cache_size = 200;
565 VInitPartitionPackage();
567 #ifdef AFS_DEMAND_ATTACH_FS
568 if (programType == fileServer) {
571 VLRU_SetOptions(VLRU_SET_ENABLED, 0);
573 osi_Assert(pthread_key_create(&VThread_key, NULL) == 0);
576 MUTEX_INIT(&vol_glock_mutex, "vol glock", MUTEX_DEFAULT, 0);
577 MUTEX_INIT(&vol_trans_mutex, "vol trans", MUTEX_DEFAULT, 0);
578 CV_INIT(&vol_put_volume_cond, "vol put", CV_DEFAULT, 0);
579 CV_INIT(&vol_sleep_cond, "vol sleep", CV_DEFAULT, 0);
580 CV_INIT(&vol_init_attach_cond, "vol init attach", CV_DEFAULT, 0);
581 CV_INIT(&vol_vinit_cond, "vol init", CV_DEFAULT, 0);
582 #ifndef AFS_PTHREAD_ENV
584 #endif /* AFS_PTHREAD_ENV */
585 Lock_Init(&vol_listLock);
587 srandom(time(0)); /* For VGetVolumeInfo */
589 #ifdef AFS_DEMAND_ATTACH_FS
590 MUTEX_INIT(&vol_salvsync_mutex, "salvsync", MUTEX_DEFAULT, 0);
591 #endif /* AFS_DEMAND_ATTACH_FS */
593 /* Ok, we have done enough initialization that fileserver can
594 * start accepting calls, even though the volumes may not be
595 * available just yet.
599 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_SERVER)
600 if (programType == salvageServer) {
603 #endif /* AFS_DEMAND_ATTACH_FS */
604 #ifdef FSSYNC_BUILD_SERVER
605 if (programType == fileServer) {
609 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_CLIENT)
610 if (VCanUseSALVSYNC()) {
611 /* establish a connection to the salvager at this point */
612 osi_Assert(VConnectSALV() != 0);
614 #endif /* AFS_DEMAND_ATTACH_FS */
616 if (opts->volcache > VStats.hdr_cache_size)
617 VStats.hdr_cache_size = opts->volcache;
618 VInitVolumeHeaderCache(VStats.hdr_cache_size);
620 VInitVnodes(vLarge, opts->nLargeVnodes);
621 VInitVnodes(vSmall, opts->nSmallVnodes);
624 errors = VAttachPartitions();
628 if (programType != fileServer) {
629 errors = VInitAttachVolumes(programType);
635 #ifdef FSSYNC_BUILD_CLIENT
636 if (VCanUseFSSYNC()) {
638 #ifdef AFS_DEMAND_ATTACH_FS
639 if (programType == salvageServer) {
640 Log("Unable to connect to file server; aborted\n");
643 #endif /* AFS_DEMAND_ATTACH_FS */
644 Log("Unable to connect to file server; will retry at need\n");
647 #endif /* FSSYNC_BUILD_CLIENT */
652 #if !defined(AFS_PTHREAD_ENV)
654 * Attach volumes in vice partitions
656 * @param[in] pt calling program type
659 * @note This is the original, non-threaded version of attach parititions.
661 * @post VInit state is 2
664 VInitAttachVolumes(ProgramType pt)
666 osi_Assert(VInit==1);
667 if (pt == fileServer) {
668 struct DiskPartition64 *diskP;
669 /* Attach all the volumes in this partition */
670 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
671 int nAttached = 0, nUnattached = 0;
672 osi_Assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
676 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
677 LWP_NoYieldSignal(VInitAttachVolumes);
681 #endif /* !AFS_PTHREAD_ENV */
683 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_DEMAND_ATTACH_FS)
685 * Attach volumes in vice partitions
687 * @param[in] pt calling program type
690 * @note Threaded version of attach parititions.
692 * @post VInit state is 2
695 VInitAttachVolumes(ProgramType pt)
697 osi_Assert(VInit==1);
698 if (pt == fileServer) {
699 struct DiskPartition64 *diskP;
700 struct vinitvolumepackage_thread_t params;
701 struct diskpartition_queue_t * dpq;
702 int i, threads, parts;
704 pthread_attr_t attrs;
706 CV_INIT(¶ms.thread_done_cv, "thread done", CV_DEFAULT, 0);
708 params.n_threads_complete = 0;
710 /* create partition work queue */
711 for (parts=0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
712 dpq = (diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
713 osi_Assert(dpq != NULL);
715 queue_Append(¶ms,dpq);
718 threads = MIN(parts, vol_attach_threads);
721 /* spawn off a bunch of initialization threads */
722 osi_Assert(pthread_attr_init(&attrs) == 0);
723 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
725 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
726 Log("VInitVolumePackage: using %d threads to attach volumes on %d partitions\n",
730 for (i=0; i < threads; i++) {
733 osi_Assert(pthread_create
734 (&tid, &attrs, &VInitVolumePackageThread,
736 AFS_SIGSET_RESTORE();
739 while(params.n_threads_complete < threads) {
740 VOL_CV_WAIT(¶ms.thread_done_cv);
744 osi_Assert(pthread_attr_destroy(&attrs) == 0);
746 /* if we're only going to run one init thread, don't bother creating
748 Log("VInitVolumePackage: beginning single-threaded fileserver startup\n");
749 Log("VInitVolumePackage: using 1 thread to attach volumes on %d partition(s)\n",
752 VInitVolumePackageThread(¶ms);
755 CV_DESTROY(¶ms.thread_done_cv);
758 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
759 CV_BROADCAST(&vol_init_attach_cond);
765 VInitVolumePackageThread(void * args) {
767 struct DiskPartition64 *diskP;
768 struct vinitvolumepackage_thread_t * params;
769 struct diskpartition_queue_t * dpq;
771 params = (vinitvolumepackage_thread_t *) args;
775 /* Attach all the volumes in this partition */
776 while (queue_IsNotEmpty(params)) {
777 int nAttached = 0, nUnattached = 0;
779 if (vinit_attach_abort) {
780 Log("Aborting initialization\n");
784 dpq = queue_First(params,diskpartition_queue_t);
790 osi_Assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
796 params->n_threads_complete++;
797 CV_SIGNAL(¶ms->thread_done_cv);
801 #endif /* AFS_PTHREAD_ENV && !AFS_DEMAND_ATTACH_FS */
803 #if defined(AFS_DEMAND_ATTACH_FS)
805 * Attach volumes in vice partitions
807 * @param[in] pt calling program type
810 * @note Threaded version of attach partitions.
812 * @post VInit state is 2
815 VInitAttachVolumes(ProgramType pt)
817 osi_Assert(VInit==1);
818 if (pt == fileServer) {
820 struct DiskPartition64 *diskP;
821 struct partition_queue pq;
822 struct volume_init_queue vq;
824 int i, threads, parts;
826 pthread_attr_t attrs;
828 /* create partition work queue */
830 CV_INIT(&(pq.cv), "partq", CV_DEFAULT, 0);
831 MUTEX_INIT(&(pq.mutex), "partq", MUTEX_DEFAULT, 0);
832 for (parts = 0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
833 struct diskpartition_queue_t *dp;
834 dp = (struct diskpartition_queue_t*)malloc(sizeof(struct diskpartition_queue_t));
835 osi_Assert(dp != NULL);
837 queue_Append(&pq, dp);
840 /* number of worker threads; at least one, not to exceed the number of partitions */
841 threads = MIN(parts, vol_attach_threads);
843 /* create volume work queue */
845 CV_INIT(&(vq.cv), "volq", CV_DEFAULT, 0);
846 MUTEX_INIT(&(vq.mutex), "volq", MUTEX_DEFAULT, 0);
848 osi_Assert(pthread_attr_init(&attrs) == 0);
849 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
851 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
852 Log("VInitVolumePackage: using %d threads to pre-attach volumes on %d partitions\n",
855 /* create threads to scan disk partitions. */
856 for (i=0; i < threads; i++) {
857 struct vinitvolumepackage_thread_param *params;
860 params = (struct vinitvolumepackage_thread_param *)malloc(sizeof(struct vinitvolumepackage_thread_param));
864 params->nthreads = threads;
865 params->thread = i+1;
868 osi_Assert(pthread_create (&tid, &attrs, &VInitVolumePackageThread, (void*)params) == 0);
869 AFS_SIGSET_RESTORE();
872 VInitPreAttachVolumes(threads, &vq);
874 osi_Assert(pthread_attr_destroy(&attrs) == 0);
876 MUTEX_DESTROY(&pq.mutex);
878 MUTEX_DESTROY(&vq.mutex);
882 VSetVInit_r(2); /* Initialized, and all volumes have been attached */
883 CV_BROADCAST(&vol_init_attach_cond);
890 * Volume package initialization worker thread. Scan partitions for volume
891 * header files. Gather batches of volume ids and dispatch them to
892 * the main thread to be preattached. The volume preattachement is done
893 * in the main thread to avoid global volume lock contention.
896 VInitVolumePackageThread(void *args)
898 struct vinitvolumepackage_thread_param *params;
899 struct DiskPartition64 *partition;
900 struct partition_queue *pq;
901 struct volume_init_queue *vq;
902 struct volume_init_batch *vb;
905 params = (struct vinitvolumepackage_thread_param *)args;
911 vb = (struct volume_init_batch*)malloc(sizeof(struct volume_init_batch));
913 vb->thread = params->thread;
917 Log("Scanning partitions on thread %d of %d\n", params->thread, params->nthreads);
918 while((partition = VInitNextPartition(pq))) {
922 Log("Partition %s: pre-attaching volumes\n", partition->name);
923 dirp = opendir(VPartitionPath(partition));
925 Log("opendir on Partition %s failed, errno=%d!\n", partition->name, errno);
928 while ((vid = VInitNextVolumeId(dirp))) {
929 Volume *vp = (Volume*)malloc(sizeof(Volume));
931 memset(vp, 0, sizeof(Volume));
932 vp->device = partition->device;
933 vp->partition = partition;
935 queue_Init(&vp->vnode_list);
936 queue_Init(&vp->rx_call_list);
937 CV_INIT(&V_attachCV(vp), "partattach", CV_DEFAULT, 0);
939 vb->batch[vb->size++] = vp;
940 if (vb->size == VINIT_BATCH_MAX_SIZE) {
941 MUTEX_ENTER(&vq->mutex);
942 queue_Append(vq, vb);
943 CV_BROADCAST(&vq->cv);
944 MUTEX_EXIT(&vq->mutex);
946 vb = (struct volume_init_batch*)malloc(sizeof(struct volume_init_batch));
948 vb->thread = params->thread;
957 MUTEX_ENTER(&vq->mutex);
958 queue_Append(vq, vb);
959 CV_BROADCAST(&vq->cv);
960 MUTEX_EXIT(&vq->mutex);
962 Log("Partition scan thread %d of %d ended\n", params->thread, params->nthreads);
968 * Read next element from the pre-populated partition list.
970 static struct DiskPartition64*
971 VInitNextPartition(struct partition_queue *pq)
973 struct DiskPartition64 *partition;
974 struct diskpartition_queue_t *dp; /* queue element */
976 if (vinit_attach_abort) {
977 Log("Aborting volume preattach thread.\n");
981 /* get next partition to scan */
982 MUTEX_ENTER(&pq->mutex);
983 if (queue_IsEmpty(pq)) {
984 MUTEX_EXIT(&pq->mutex);
987 dp = queue_First(pq, diskpartition_queue_t);
989 MUTEX_EXIT(&pq->mutex);
992 osi_Assert(dp->diskP);
994 partition = dp->diskP;
1000 * Find next volume id on the partition.
1003 VInitNextVolumeId(DIR *dirp)
1009 while((d = readdir(dirp))) {
1010 if (vinit_attach_abort) {
1011 Log("Aborting volume preattach thread.\n");
1014 ext = strrchr(d->d_name, '.');
1015 if (d->d_name[0] == 'V' && ext && strcmp(ext, VHDREXT) == 0) {
1016 vid = VolumeNumber(d->d_name);
1020 Log("Warning: bogus volume header file: %s\n", d->d_name);
1027 * Preattach volumes in batches to avoid lock contention.
1030 VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq)
1032 struct volume_init_batch *vb;
1036 /* dequeue next volume */
1037 MUTEX_ENTER(&vq->mutex);
1038 if (queue_IsEmpty(vq)) {
1039 CV_WAIT(&vq->cv, &vq->mutex);
1041 vb = queue_First(vq, volume_init_batch);
1043 MUTEX_EXIT(&vq->mutex);
1047 for (i = 0; i<vb->size; i++) {
1053 dup = VLookupVolume_r(&ec, vp->hashid, NULL);
1055 Log("Error looking up volume, code=%d\n", ec);
1058 Log("Warning: Duplicate volume id %d detected.\n", vp->hashid);
1061 /* put pre-attached volume onto the hash table
1062 * and bring it up to the pre-attached state */
1063 AddVolumeToHashTable(vp, vp->hashid);
1064 AddVolumeToVByPList_r(vp);
1065 VLRU_Init_Node_r(vp);
1066 VChangeState_r(vp, VOL_STATE_PREATTACHED);
1079 #endif /* AFS_DEMAND_ATTACH_FS */
1081 #if !defined(AFS_DEMAND_ATTACH_FS)
1083 * attach all volumes on a given disk partition
1086 VAttachVolumesByPartition(struct DiskPartition64 *diskP, int * nAttached, int * nUnattached)
1092 Log("Partition %s: attaching volumes\n", diskP->name);
1093 dirp = opendir(VPartitionPath(diskP));
1095 Log("opendir on Partition %s failed!\n", diskP->name);
1099 while ((dp = readdir(dirp))) {
1101 p = strrchr(dp->d_name, '.');
1103 if (vinit_attach_abort) {
1104 Log("Partition %s: abort attach volumes\n", diskP->name);
1108 if (p != NULL && strcmp(p, VHDREXT) == 0) {
1111 vp = VAttachVolumeByName(&error, diskP->name, dp->d_name,
1113 (*(vp ? nAttached : nUnattached))++;
1114 if (error == VOFFLINE)
1115 Log("Volume %d stays offline (/vice/offline/%s exists)\n", VolumeNumber(dp->d_name), dp->d_name);
1116 else if (LogLevel >= 5) {
1117 Log("Partition %s: attached volume %d (%s)\n",
1118 diskP->name, VolumeNumber(dp->d_name),
1127 Log("Partition %s: attached %d volumes; %d volumes not attached\n", diskP->name, *nAttached, *nUnattached);
1132 #endif /* !AFS_DEMAND_ATTACH_FS */
1134 /***************************************************/
1135 /* Shutdown routines */
1136 /***************************************************/
1140 * highly multithreaded volume package shutdown
1142 * with the demand attach fileserver extensions,
1143 * VShutdown has been modified to be multithreaded.
1144 * In order to achieve optimal use of many threads,
1145 * the shutdown code involves one control thread and
1146 * n shutdown worker threads. The control thread
1147 * periodically examines the number of volumes available
1148 * for shutdown on each partition, and produces a worker
1149 * thread allocation schedule. The idea is to eliminate
1150 * redundant scheduling computation on the workers by
1151 * having a single master scheduler.
1153 * The scheduler's objectives are:
1155 * each partition with volumes remaining gets allocated
1156 * at least 1 thread (assuming sufficient threads)
1158 * threads are allocated proportional to the number of
1159 * volumes remaining to be offlined. This ensures that
1160 * the OS I/O scheduler has many requests to elevator
1161 * seek on partitions that will (presumably) take the
1162 * longest amount of time (from now) to finish shutdown
1163 * (3) keep threads busy
1164 * when there are extra threads, they are assigned to
1165 * partitions using a simple round-robin algorithm
1167 * In the future, we may wish to add the ability to adapt
1168 * to the relative performance patterns of each disk
1173 * multi-step shutdown process
1175 * demand attach shutdown is a four-step process. Each
1176 * shutdown "pass" shuts down increasingly more difficult
1177 * volumes. The main purpose is to achieve better cache
1178 * utilization during shutdown.
1181 * shutdown volumes in the unattached, pre-attached
1184 * shutdown attached volumes with cached volume headers
1186 * shutdown all volumes in non-exclusive states
1188 * shutdown all remaining volumes
1191 #ifdef AFS_DEMAND_ATTACH_FS
1197 struct DiskPartition64 * diskP;
1198 struct diskpartition_queue_t * dpq;
1199 vshutdown_thread_t params;
1201 pthread_attr_t attrs;
1203 memset(¶ms, 0, sizeof(vshutdown_thread_t));
1206 Log("VShutdown: aborting attach volumes\n");
1207 vinit_attach_abort = 1;
1208 VOL_CV_WAIT(&vol_init_attach_cond);
1211 for (params.n_parts=0, diskP = DiskPartitionList;
1212 diskP; diskP = diskP->next, params.n_parts++);
1214 Log("VShutdown: shutting down on-line volumes on %d partition%s...\n",
1215 params.n_parts, params.n_parts > 1 ? "s" : "");
1217 vol_shutting_down = 1;
1219 if (vol_attach_threads > 1) {
1220 /* prepare for parallel shutdown */
1221 params.n_threads = vol_attach_threads;
1222 MUTEX_INIT(¶ms.lock, "params", MUTEX_DEFAULT, 0);
1223 CV_INIT(¶ms.cv, "params", CV_DEFAULT, 0);
1224 CV_INIT(¶ms.master_cv, "params master", CV_DEFAULT, 0);
1225 osi_Assert(pthread_attr_init(&attrs) == 0);
1226 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
1227 queue_Init(¶ms);
1229 /* setup the basic partition information structures for
1230 * parallel shutdown */
1231 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1233 struct rx_queue * qp, * nqp;
1237 VVByPListWait_r(diskP);
1238 VVByPListBeginExclusive_r(diskP);
1241 for (queue_Scan(&diskP->vol_list, qp, nqp, rx_queue)) {
1242 vp = (Volume *)((char *)qp - offsetof(Volume, vol_list));
1246 Log("VShutdown: partition %s has %d volumes with attached headers\n",
1247 VPartitionPath(diskP), count);
1250 /* build up the pass 0 shutdown work queue */
1251 dpq = (struct diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
1252 osi_Assert(dpq != NULL);
1254 queue_Prepend(¶ms, dpq);
1256 params.part_pass_head[diskP->index] = queue_First(&diskP->vol_list, rx_queue);
1259 Log("VShutdown: beginning parallel fileserver shutdown\n");
1260 Log("VShutdown: using %d threads to offline volumes on %d partition%s\n",
1261 vol_attach_threads, params.n_parts, params.n_parts > 1 ? "s" : "" );
1263 /* do pass 0 shutdown */
1264 MUTEX_ENTER(¶ms.lock);
1265 for (i=0; i < params.n_threads; i++) {
1266 osi_Assert(pthread_create
1267 (&tid, &attrs, &VShutdownThread,
1271 /* wait for all the pass 0 shutdowns to complete */
1272 while (params.n_threads_complete < params.n_threads) {
1273 CV_WAIT(¶ms.master_cv, ¶ms.lock);
1275 params.n_threads_complete = 0;
1277 CV_BROADCAST(¶ms.cv);
1278 MUTEX_EXIT(¶ms.lock);
1280 Log("VShutdown: pass 0 completed using the 1 thread per partition algorithm\n");
1281 Log("VShutdown: starting passes 1 through 3 using finely-granular mp-fast algorithm\n");
1283 /* run the parallel shutdown scheduler. it will drop the glock internally */
1284 ShutdownController(¶ms);
1286 /* wait for all the workers to finish pass 3 and terminate */
1287 while (params.pass < 4) {
1288 VOL_CV_WAIT(¶ms.cv);
1291 osi_Assert(pthread_attr_destroy(&attrs) == 0);
1292 CV_DESTROY(¶ms.cv);
1293 CV_DESTROY(¶ms.master_cv);
1294 MUTEX_DESTROY(¶ms.lock);
1296 /* drop the VByPList exclusive reservations */
1297 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1298 VVByPListEndExclusive_r(diskP);
1299 Log("VShutdown: %s stats : (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1300 VPartitionPath(diskP),
1301 params.stats[0][diskP->index],
1302 params.stats[1][diskP->index],
1303 params.stats[2][diskP->index],
1304 params.stats[3][diskP->index]);
1307 Log("VShutdown: shutdown finished using %d threads\n", params.n_threads);
1309 /* if we're only going to run one shutdown thread, don't bother creating
1311 Log("VShutdown: beginning single-threaded fileserver shutdown\n");
1313 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1314 VShutdownByPartition_r(diskP);
1318 Log("VShutdown: complete.\n");
1321 #else /* AFS_DEMAND_ATTACH_FS */
1331 Log("VShutdown: aborting attach volumes\n");
1332 vinit_attach_abort = 1;
1333 #ifdef AFS_PTHREAD_ENV
1334 VOL_CV_WAIT(&vol_init_attach_cond);
1336 LWP_WaitProcess(VInitAttachVolumes);
1337 #endif /* AFS_PTHREAD_ENV */
1340 Log("VShutdown: shutting down on-line volumes...\n");
1341 vol_shutting_down = 1;
1342 for (i = 0; i < VolumeHashTable.Size; i++) {
1343 /* try to hold first volume in the hash table */
1344 for (queue_Scan(&VolumeHashTable.Table[i],vp,np,Volume)) {
1348 Log("VShutdown: Attempting to take volume %u offline.\n",
1351 /* next, take the volume offline (drops reference count) */
1352 VOffline_r(vp, "File server was shut down");
1356 Log("VShutdown: complete.\n");
1358 #endif /* AFS_DEMAND_ATTACH_FS */
1364 osi_Assert(VInit>0);
1371 * stop new activity (e.g. SALVSYNC) from occurring
1373 * Use this to make the volume package less busy; for example, during
1374 * shutdown. This doesn't actually shutdown/detach anything in the
1375 * volume package, but prevents certain processes from ocurring. For
1376 * example, preventing new SALVSYNC communication in DAFS. In theory, we
1377 * could also use this to prevent new volume attachment, or prevent
1378 * other programs from checking out volumes, etc.
1383 #ifdef AFS_DEMAND_ATTACH_FS
1384 /* make sure we don't try to contact the salvageserver, since it may
1385 * not be around anymore */
1386 vol_disallow_salvsync = 1;
1390 #ifdef AFS_DEMAND_ATTACH_FS
1393 * shutdown control thread
1396 ShutdownController(vshutdown_thread_t * params)
1399 struct DiskPartition64 * diskP;
1401 vshutdown_thread_t shadow;
1403 ShutdownCreateSchedule(params);
1405 while ((params->pass < 4) &&
1406 (params->n_threads_complete < params->n_threads)) {
1407 /* recompute schedule once per second */
1409 memcpy(&shadow, params, sizeof(vshutdown_thread_t));
1413 Log("ShutdownController: schedule version=%d, vol_remaining=%d, pass=%d\n",
1414 shadow.schedule_version, shadow.vol_remaining, shadow.pass);
1415 Log("ShutdownController: n_threads_complete=%d, n_parts_done_pass=%d\n",
1416 shadow.n_threads_complete, shadow.n_parts_done_pass);
1417 for (diskP = DiskPartitionList; diskP; diskP=diskP->next) {
1419 Log("ShutdownController: part[%d] : (len=%d, thread_target=%d, done_pass=%d, pass_head=%p)\n",
1421 diskP->vol_list.len,
1422 shadow.part_thread_target[id],
1423 shadow.part_done_pass[id],
1424 shadow.part_pass_head[id]);
1430 ShutdownCreateSchedule(params);
1434 /* create the shutdown thread work schedule.
1435 * this scheduler tries to implement fairness
1436 * by allocating at least 1 thread to each
1437 * partition with volumes to be shutdown,
1438 * and then it attempts to allocate remaining
1439 * threads based upon the amount of work left
1442 ShutdownCreateSchedule(vshutdown_thread_t * params)
1444 struct DiskPartition64 * diskP;
1445 int sum, thr_workload, thr_left;
1446 int part_residue[VOLMAXPARTS+1];
1449 /* compute the total number of outstanding volumes */
1451 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1452 sum += diskP->vol_list.len;
1455 params->schedule_version++;
1456 params->vol_remaining = sum;
1461 /* compute average per-thread workload */
1462 thr_workload = sum / params->n_threads;
1463 if (sum % params->n_threads)
1466 thr_left = params->n_threads;
1467 memset(&part_residue, 0, sizeof(part_residue));
1469 /* for fairness, give every partition with volumes remaining
1470 * at least one thread */
1471 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1473 if (diskP->vol_list.len) {
1474 params->part_thread_target[id] = 1;
1477 params->part_thread_target[id] = 0;
1481 if (thr_left && thr_workload) {
1482 /* compute length-weighted workloads */
1485 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1487 delta = (diskP->vol_list.len / thr_workload) -
1488 params->part_thread_target[id];
1492 if (delta < thr_left) {
1493 params->part_thread_target[id] += delta;
1496 params->part_thread_target[id] += thr_left;
1504 /* try to assign any leftover threads to partitions that
1505 * had volume lengths closer to needing thread_target+1 */
1506 int max_residue, max_id = 0;
1508 /* compute the residues */
1509 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1511 part_residue[id] = diskP->vol_list.len -
1512 (params->part_thread_target[id] * thr_workload);
1515 /* now try to allocate remaining threads to partitions with the
1516 * highest residues */
1519 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1521 if (part_residue[id] > max_residue) {
1522 max_residue = part_residue[id];
1531 params->part_thread_target[max_id]++;
1533 part_residue[max_id] = 0;
1538 /* punt and give any remaining threads equally to each partition */
1540 if (thr_left >= params->n_parts) {
1541 alloc = thr_left / params->n_parts;
1542 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1544 params->part_thread_target[id] += alloc;
1549 /* finish off the last of the threads */
1550 for (diskP = DiskPartitionList; thr_left && diskP; diskP = diskP->next) {
1552 params->part_thread_target[id]++;
1558 /* worker thread for parallel shutdown */
1560 VShutdownThread(void * args)
1562 vshutdown_thread_t * params;
1563 int found, pass, schedule_version_save, count;
1564 struct DiskPartition64 *diskP;
1565 struct diskpartition_queue_t * dpq;
1568 params = (vshutdown_thread_t *) args;
1570 /* acquire the shutdown pass 0 lock */
1571 MUTEX_ENTER(¶ms->lock);
1573 /* if there's still pass 0 work to be done,
1574 * get a work entry, and do a pass 0 shutdown */
1575 if (queue_IsNotEmpty(params)) {
1576 dpq = queue_First(params, diskpartition_queue_t);
1578 MUTEX_EXIT(¶ms->lock);
1584 while (ShutdownVolumeWalk_r(diskP, 0, ¶ms->part_pass_head[id]))
1586 params->stats[0][diskP->index] = count;
1587 MUTEX_ENTER(¶ms->lock);
1590 params->n_threads_complete++;
1591 if (params->n_threads_complete == params->n_threads) {
1592 /* notify control thread that all workers have completed pass 0 */
1593 CV_SIGNAL(¶ms->master_cv);
1595 while (params->pass == 0) {
1596 CV_WAIT(¶ms->cv, ¶ms->lock);
1600 MUTEX_EXIT(¶ms->lock);
1603 pass = params->pass;
1604 osi_Assert(pass > 0);
1606 /* now escalate through the more complicated shutdowns */
1608 schedule_version_save = params->schedule_version;
1610 /* find a disk partition to work on */
1611 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1613 if (params->part_thread_target[id] && !params->part_done_pass[id]) {
1614 params->part_thread_target[id]--;
1621 /* hmm. for some reason the controller thread couldn't find anything for
1622 * us to do. let's see if there's anything we can do */
1623 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1625 if (diskP->vol_list.len && !params->part_done_pass[id]) {
1628 } else if (!params->part_done_pass[id]) {
1629 params->part_done_pass[id] = 1;
1630 params->n_parts_done_pass++;
1632 Log("VShutdown: done shutting down volumes on partition %s.\n",
1633 VPartitionPath(diskP));
1639 /* do work on this partition until either the controller
1640 * creates a new schedule, or we run out of things to do
1641 * on this partition */
1644 while (!params->part_done_pass[id] &&
1645 (schedule_version_save == params->schedule_version)) {
1646 /* ShutdownVolumeWalk_r will drop the glock internally */
1647 if (!ShutdownVolumeWalk_r(diskP, pass, ¶ms->part_pass_head[id])) {
1648 if (!params->part_done_pass[id]) {
1649 params->part_done_pass[id] = 1;
1650 params->n_parts_done_pass++;
1652 Log("VShutdown: done shutting down volumes on partition %s.\n",
1653 VPartitionPath(diskP));
1661 params->stats[pass][id] += count;
1663 /* ok, everyone is done this pass, proceed */
1666 params->n_threads_complete++;
1667 while (params->pass == pass) {
1668 if (params->n_threads_complete == params->n_threads) {
1669 /* we are the last thread to complete, so we will
1670 * reinitialize worker pool state for the next pass */
1671 params->n_threads_complete = 0;
1672 params->n_parts_done_pass = 0;
1674 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1676 params->part_done_pass[id] = 0;
1677 params->part_pass_head[id] = queue_First(&diskP->vol_list, rx_queue);
1680 /* compute a new thread schedule before releasing all the workers */
1681 ShutdownCreateSchedule(params);
1683 /* wake up all the workers */
1684 CV_BROADCAST(¶ms->cv);
1687 Log("VShutdown: pass %d completed using %d threads on %d partitions\n",
1688 pass, params->n_threads, params->n_parts);
1691 VOL_CV_WAIT(¶ms->cv);
1694 pass = params->pass;
1708 /* shut down all volumes on a given disk partition
1710 * note that this function will not allow mp-fast
1711 * shutdown of a partition */
1713 VShutdownByPartition_r(struct DiskPartition64 * dp)
1719 /* wait for other exclusive ops to finish */
1720 VVByPListWait_r(dp);
1722 /* begin exclusive access */
1723 VVByPListBeginExclusive_r(dp);
1725 /* pick the low-hanging fruit first,
1726 * then do the complicated ones last
1727 * (has the advantage of keeping
1728 * in-use volumes up until the bitter end) */
1729 for (pass = 0, total=0; pass < 4; pass++) {
1730 pass_stats[pass] = ShutdownVByPForPass_r(dp, pass);
1731 total += pass_stats[pass];
1734 /* end exclusive access */
1735 VVByPListEndExclusive_r(dp);
1737 Log("VShutdownByPartition: shut down %d volumes on %s (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1738 total, VPartitionPath(dp), pass_stats[0], pass_stats[1], pass_stats[2], pass_stats[3]);
1743 /* internal shutdown functionality
1745 * for multi-pass shutdown:
1746 * 0 to only "shutdown" {pre,un}attached and error state volumes
1747 * 1 to also shutdown attached volumes w/ volume header loaded
1748 * 2 to also shutdown attached volumes w/o volume header loaded
1749 * 3 to also shutdown exclusive state volumes
1751 * caller MUST hold exclusive access on the hash chain
1752 * because we drop vol_glock_mutex internally
1754 * this function is reentrant for passes 1--3
1755 * (e.g. multiple threads can cooperate to
1756 * shutdown a partition mp-fast)
1758 * pass 0 is not scaleable because the volume state data is
1759 * synchronized by vol_glock mutex, and the locking overhead
1760 * is too high to drop the lock long enough to do linked list
1764 ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass)
1766 struct rx_queue * q = queue_First(&dp->vol_list, rx_queue);
1769 while (ShutdownVolumeWalk_r(dp, pass, &q))
1775 /* conditionally shutdown one volume on partition dp
1776 * returns 1 if a volume was shutdown in this pass,
1779 ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
1780 struct rx_queue ** idx)
1782 struct rx_queue *qp, *nqp;
1787 for (queue_ScanFrom(&dp->vol_list, qp, qp, nqp, rx_queue)) {
1788 vp = (Volume *) (((char *)qp) - offsetof(Volume, vol_list));
1792 if ((V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1793 (V_attachState(vp) != VOL_STATE_ERROR) &&
1794 (V_attachState(vp) != VOL_STATE_DELETED) &&
1795 (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1799 if ((V_attachState(vp) == VOL_STATE_ATTACHED) &&
1800 (vp->header == NULL)) {
1804 if (VIsExclusiveState(V_attachState(vp))) {
1809 DeleteVolumeFromVByPList_r(vp);
1810 VShutdownVolume_r(vp);
1820 * shutdown a specific volume
1822 /* caller MUST NOT hold a heavyweight ref on vp */
1824 VShutdownVolume_r(Volume * vp)
1828 VCreateReservation_r(vp);
1830 if (LogLevel >= 5) {
1831 Log("VShutdownVolume_r: vid=%u, device=%d, state=%hu\n",
1832 vp->hashid, vp->partition->device, V_attachState(vp));
1835 /* wait for other blocking ops to finish */
1836 VWaitExclusiveState_r(vp);
1838 osi_Assert(VIsValidState(V_attachState(vp)));
1840 switch(V_attachState(vp)) {
1841 case VOL_STATE_SALVAGING:
1842 /* Leave salvaging volumes alone. Any in-progress salvages will
1843 * continue working after viced shuts down. This is intentional.
1846 case VOL_STATE_PREATTACHED:
1847 case VOL_STATE_ERROR:
1848 VChangeState_r(vp, VOL_STATE_UNATTACHED);
1849 case VOL_STATE_UNATTACHED:
1850 case VOL_STATE_DELETED:
1852 case VOL_STATE_GOING_OFFLINE:
1853 case VOL_STATE_SHUTTING_DOWN:
1854 case VOL_STATE_ATTACHED:
1858 Log("VShutdown: Attempting to take volume %u offline.\n",
1861 /* take the volume offline (drops reference count) */
1862 VOffline_r(vp, "File server was shut down");
1869 VCancelReservation_r(vp);
1873 #endif /* AFS_DEMAND_ATTACH_FS */
1876 /***************************************************/
1877 /* Header I/O routines */
1878 /***************************************************/
1880 /* open a descriptor for the inode (h),
1881 * read in an on-disk structure into buffer (to) of size (size),
1882 * verify versionstamp in structure has magic (magic) and
1883 * optionally verify version (version) if (version) is nonzero
1886 ReadHeader(Error * ec, IHandle_t * h, char *to, int size, bit32 magic,
1889 struct versionStamp *vsn;
1904 vsn = (struct versionStamp *)to;
1905 if (FDH_PREAD(fdP, to, size, 0) != size || vsn->magic != magic) {
1907 FDH_REALLYCLOSE(fdP);
1912 /* Check is conditional, in case caller wants to inspect version himself */
1913 if (version && vsn->version != version) {
1919 WriteVolumeHeader_r(Error * ec, Volume * vp)
1921 IHandle_t *h = V_diskDataHandle(vp);
1931 if (FDH_PWRITE(fdP, (char *)&V_disk(vp), sizeof(V_disk(vp)), 0)
1932 != sizeof(V_disk(vp))) {
1934 FDH_REALLYCLOSE(fdP);
1940 /* VolumeHeaderToDisk
1941 * Allows for storing 64 bit inode numbers in on-disk volume header
1944 /* convert in-memory representation of a volume header to the
1945 * on-disk representation of a volume header */
1947 VolumeHeaderToDisk(VolumeDiskHeader_t * dh, VolumeHeader_t * h)
1950 memset(dh, 0, sizeof(VolumeDiskHeader_t));
1951 dh->stamp = h->stamp;
1953 dh->parent = h->parent;
1955 #ifdef AFS_64BIT_IOPS_ENV
1956 dh->volumeInfo_lo = (afs_int32) h->volumeInfo & 0xffffffff;
1957 dh->volumeInfo_hi = (afs_int32) (h->volumeInfo >> 32) & 0xffffffff;
1958 dh->smallVnodeIndex_lo = (afs_int32) h->smallVnodeIndex & 0xffffffff;
1959 dh->smallVnodeIndex_hi =
1960 (afs_int32) (h->smallVnodeIndex >> 32) & 0xffffffff;
1961 dh->largeVnodeIndex_lo = (afs_int32) h->largeVnodeIndex & 0xffffffff;
1962 dh->largeVnodeIndex_hi =
1963 (afs_int32) (h->largeVnodeIndex >> 32) & 0xffffffff;
1964 dh->linkTable_lo = (afs_int32) h->linkTable & 0xffffffff;
1965 dh->linkTable_hi = (afs_int32) (h->linkTable >> 32) & 0xffffffff;
1967 dh->volumeInfo_lo = h->volumeInfo;
1968 dh->smallVnodeIndex_lo = h->smallVnodeIndex;
1969 dh->largeVnodeIndex_lo = h->largeVnodeIndex;
1970 dh->linkTable_lo = h->linkTable;
1974 /* DiskToVolumeHeader
1975 * Converts an on-disk representation of a volume header to
1976 * the in-memory representation of a volume header.
1978 * Makes the assumption that AFS has *always*
1979 * zero'd the volume header file so that high parts of inode
1980 * numbers are 0 in older (SGI EFS) volume header files.
1983 DiskToVolumeHeader(VolumeHeader_t * h, VolumeDiskHeader_t * dh)
1985 memset(h, 0, sizeof(VolumeHeader_t));
1986 h->stamp = dh->stamp;
1988 h->parent = dh->parent;
1990 #ifdef AFS_64BIT_IOPS_ENV
1992 (Inode) dh->volumeInfo_lo | ((Inode) dh->volumeInfo_hi << 32);
1994 h->smallVnodeIndex =
1995 (Inode) dh->smallVnodeIndex_lo | ((Inode) dh->
1996 smallVnodeIndex_hi << 32);
1998 h->largeVnodeIndex =
1999 (Inode) dh->largeVnodeIndex_lo | ((Inode) dh->
2000 largeVnodeIndex_hi << 32);
2002 (Inode) dh->linkTable_lo | ((Inode) dh->linkTable_hi << 32);
2004 h->volumeInfo = dh->volumeInfo_lo;
2005 h->smallVnodeIndex = dh->smallVnodeIndex_lo;
2006 h->largeVnodeIndex = dh->largeVnodeIndex_lo;
2007 h->linkTable = dh->linkTable_lo;
2012 /***************************************************/
2013 /* Volume Attachment routines */
2014 /***************************************************/
2016 #ifdef AFS_DEMAND_ATTACH_FS
2018 * pre-attach a volume given its path.
2020 * @param[out] ec outbound error code
2021 * @param[in] partition partition path string
2022 * @param[in] name volume id string
2024 * @return volume object pointer
2026 * @note A pre-attached volume will only have its partition
2027 * and hashid fields initialized. At first call to
2028 * VGetVolume, the volume will be fully attached.
2032 VPreAttachVolumeByName(Error * ec, char *partition, char *name)
2036 vp = VPreAttachVolumeByName_r(ec, partition, name);
2042 * pre-attach a volume given its path.
2044 * @param[out] ec outbound error code
2045 * @param[in] partition path to vice partition
2046 * @param[in] name volume id string
2048 * @return volume object pointer
2050 * @pre VOL_LOCK held
2052 * @internal volume package internal use only.
2055 VPreAttachVolumeByName_r(Error * ec, char *partition, char *name)
2057 return VPreAttachVolumeById_r(ec,
2059 VolumeNumber(name));
2063 * pre-attach a volume given its path and numeric volume id.
2065 * @param[out] ec error code return
2066 * @param[in] partition path to vice partition
2067 * @param[in] volumeId numeric volume id
2069 * @return volume object pointer
2071 * @pre VOL_LOCK held
2073 * @internal volume package internal use only.
2076 VPreAttachVolumeById_r(Error * ec,
2081 struct DiskPartition64 *partp;
2085 osi_Assert(programType == fileServer);
2087 if (!(partp = VGetPartition_r(partition, 0))) {
2089 Log("VPreAttachVolumeById_r: Error getting partition (%s)\n", partition);
2093 vp = VLookupVolume_r(ec, volumeId, NULL);
2098 return VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2102 * preattach a volume.
2104 * @param[out] ec outbound error code
2105 * @param[in] partp pointer to partition object
2106 * @param[in] vp pointer to volume object
2107 * @param[in] vid volume id
2109 * @return volume object pointer
2111 * @pre VOL_LOCK is held.
2113 * @warning Returned volume object pointer does not have to
2114 * equal the pointer passed in as argument vp. There
2115 * are potential race conditions which can result in
2116 * the pointers having different values. It is up to
2117 * the caller to make sure that references are handled
2118 * properly in this case.
2120 * @note If there is already a volume object registered with
2121 * the same volume id, its pointer MUST be passed as
2122 * argument vp. Failure to do so will result in a silent
2123 * failure to preattach.
2125 * @internal volume package internal use only.
2128 VPreAttachVolumeByVp_r(Error * ec,
2129 struct DiskPartition64 * partp,
2137 /* check to see if pre-attach already happened */
2139 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
2140 (V_attachState(vp) != VOL_STATE_DELETED) &&
2141 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
2142 !VIsErrorState(V_attachState(vp))) {
2144 * pre-attach is a no-op in all but the following cases:
2146 * - volume is unattached
2147 * - volume is in an error state
2148 * - volume is pre-attached
2150 Log("VPreattachVolumeByVp_r: volume %u not in quiescent state\n", vid);
2153 /* we're re-attaching a volume; clear out some old state */
2154 memset(&vp->salvage, 0, sizeof(struct VolumeOnlineSalvage));
2156 if (V_partition(vp) != partp) {
2157 /* XXX potential race */
2158 DeleteVolumeFromVByPList_r(vp);
2161 /* if we need to allocate a new Volume struct,
2162 * go ahead and drop the vol glock, otherwise
2163 * do the basic setup synchronised, as it's
2164 * probably not worth dropping the lock */
2167 /* allocate the volume structure */
2168 vp = nvp = (Volume *) malloc(sizeof(Volume));
2169 osi_Assert(vp != NULL);
2170 memset(vp, 0, sizeof(Volume));
2171 queue_Init(&vp->vnode_list);
2172 queue_Init(&vp->rx_call_list);
2173 CV_INIT(&V_attachCV(vp), "vp attach", CV_DEFAULT, 0);
2176 /* link the volume with its associated vice partition */
2177 vp->device = partp->device;
2178 vp->partition = partp;
2181 vp->specialStatus = 0;
2183 /* if we dropped the lock, reacquire the lock,
2184 * check for pre-attach races, and then add
2185 * the volume to the hash table */
2188 nvp = VLookupVolume_r(ec, vid, NULL);
2193 } else if (nvp) { /* race detected */
2198 /* hack to make up for VChangeState_r() decrementing
2199 * the old state counter */
2200 VStats.state_levels[0]++;
2204 /* put pre-attached volume onto the hash table
2205 * and bring it up to the pre-attached state */
2206 AddVolumeToHashTable(vp, vp->hashid);
2207 AddVolumeToVByPList_r(vp);
2208 VLRU_Init_Node_r(vp);
2209 VChangeState_r(vp, VOL_STATE_PREATTACHED);
2212 Log("VPreAttachVolumeByVp_r: volume %u pre-attached\n", vp->hashid);
2220 #endif /* AFS_DEMAND_ATTACH_FS */
2222 /* Attach an existing volume, given its pathname, and return a
2223 pointer to the volume header information. The volume also
2224 normally goes online at this time. An offline volume
2225 must be reattached to make it go online */
2227 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
2231 retVal = VAttachVolumeByName_r(ec, partition, name, mode);
2237 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
2240 struct DiskPartition64 *partp;
2245 #ifdef AFS_DEMAND_ATTACH_FS
2246 VolumeStats stats_save;
2248 #endif /* AFS_DEMAND_ATTACH_FS */
2252 volumeId = VolumeNumber(name);
2254 if (!(partp = VGetPartition_r(partition, 0))) {
2256 Log("VAttachVolume: Error getting partition (%s)\n", partition);
2260 if (VRequiresPartLock()) {
2261 osi_Assert(VInit == 3);
2262 VLockPartition_r(partition);
2263 } else if (programType == fileServer) {
2264 #ifdef AFS_DEMAND_ATTACH_FS
2265 /* lookup the volume in the hash table */
2266 vp = VLookupVolume_r(ec, volumeId, NULL);
2272 /* save any counters that are supposed to
2273 * be monotonically increasing over the
2274 * lifetime of the fileserver */
2275 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2277 memset(&stats_save, 0, sizeof(VolumeStats));
2280 /* if there's something in the hash table, and it's not
2281 * in the pre-attach state, then we may need to detach
2282 * it before proceeding */
2283 if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
2284 VCreateReservation_r(vp);
2285 VWaitExclusiveState_r(vp);
2287 /* at this point state must be one of:
2297 if (vp->specialStatus == VBUSY)
2300 /* if it's already attached, see if we can return it */
2301 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2302 VGetVolumeByVp_r(ec, vp);
2303 if (V_inUse(vp) == fileServer) {
2304 VCancelReservation_r(vp);
2308 /* otherwise, we need to detach, and attempt to re-attach */
2309 VDetachVolume_r(ec, vp);
2311 Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
2314 /* if it isn't fully attached, delete from the hash tables,
2315 and let the refcounter handle the rest */
2316 DeleteVolumeFromHashTable(vp);
2317 DeleteVolumeFromVByPList_r(vp);
2320 VCancelReservation_r(vp);
2324 /* pre-attach volume if it hasn't been done yet */
2326 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2327 (V_attachState(vp) == VOL_STATE_DELETED) ||
2328 (V_attachState(vp) == VOL_STATE_ERROR)) {
2330 vp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2336 osi_Assert(vp != NULL);
2338 /* handle pre-attach races
2340 * multiple threads can race to pre-attach a volume,
2341 * but we can't let them race beyond that
2343 * our solution is to let the first thread to bring
2344 * the volume into an exclusive state win; the other
2345 * threads just wait until it finishes bringing the
2346 * volume online, and then they do a vgetvolumebyvp
2348 if (svp && (svp != vp)) {
2349 /* wait for other exclusive ops to finish */
2350 VCreateReservation_r(vp);
2351 VWaitExclusiveState_r(vp);
2353 /* get a heavyweight ref, kill the lightweight ref, and return */
2354 VGetVolumeByVp_r(ec, vp);
2355 VCancelReservation_r(vp);
2359 /* at this point, we are chosen as the thread to do
2360 * demand attachment for this volume. all other threads
2361 * doing a getvolume on vp->hashid will block until we finish */
2363 /* make sure any old header cache entries are invalidated
2364 * before proceeding */
2365 FreeVolumeHeader(vp);
2367 VChangeState_r(vp, VOL_STATE_ATTACHING);
2369 /* restore any saved counters */
2370 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2371 #else /* AFS_DEMAND_ATTACH_FS */
2372 vp = VGetVolume_r(ec, volumeId);
2374 if (V_inUse(vp) == fileServer)
2376 if (vp->specialStatus == VBUSY)
2378 VDetachVolume_r(ec, vp);
2380 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2384 #endif /* AFS_DEMAND_ATTACH_FS */
2388 strcpy(path, VPartitionPath(partp));
2392 strcat(path, OS_DIRSEP);
2396 vp = (Volume *) calloc(1, sizeof(Volume));
2397 osi_Assert(vp != NULL);
2398 vp->hashid = volumeId;
2399 vp->device = partp->device;
2400 vp->partition = partp;
2401 queue_Init(&vp->vnode_list);
2402 queue_Init(&vp->rx_call_list);
2403 #ifdef AFS_DEMAND_ATTACH_FS
2404 CV_INIT(&V_attachCV(vp), "vp attach", CV_DEFAULT, 0);
2405 #endif /* AFS_DEMAND_ATTACH_FS */
2408 /* attach2 is entered without any locks, and returns
2409 * with vol_glock_mutex held */
2410 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2412 if (VCanUseFSSYNC() && vp) {
2413 #ifdef AFS_DEMAND_ATTACH_FS
2414 if ((mode == V_VOLUPD) || (VolumeWriteable(vp) && (mode == V_CLONE))) {
2415 /* mark volume header as in use so that volser crashes lead to a
2416 * salvage attempt */
2417 VUpdateVolume_r(ec, vp, 0);
2419 /* for dafs, we should tell the fileserver, except for V_PEEK
2420 * where we know it is not necessary */
2421 if (mode == V_PEEK) {
2422 vp->needsPutBack = 0;
2424 vp->needsPutBack = VOL_PUTBACK;
2426 #else /* !AFS_DEMAND_ATTACH_FS */
2427 /* duplicate computation in fssync.c about whether the server
2428 * takes the volume offline or not. If the volume isn't
2429 * offline, we must not return it when we detach the volume,
2430 * or the server will abort */
2431 if (mode == V_READONLY || mode == V_PEEK
2432 || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
2433 vp->needsPutBack = 0;
2435 vp->needsPutBack = VOL_PUTBACK;
2436 #endif /* !AFS_DEMAND_ATTACH_FS */
2438 #ifdef FSSYNC_BUILD_CLIENT
2439 /* Only give back the vol to the fileserver if we checked it out; attach2
2440 * will set checkedOut only if we successfully checked it out from the
2442 if (VCanUseFSSYNC() && vp == NULL && checkedOut) {
2444 #ifdef AFS_DEMAND_ATTACH_FS
2445 /* If we couldn't attach but we scheduled a salvage, we already
2446 * notified the fileserver; don't online it now */
2447 if (*ec != VSALVAGING)
2448 #endif /* AFS_DEMAND_ATTACH_FS */
2449 FSYNC_VolOp(volumeId, partition, FSYNC_VOL_ON, 0, NULL);
2452 if (programType == fileServer && vp) {
2453 #ifdef AFS_DEMAND_ATTACH_FS
2455 * we can get here in cases where we don't "own"
2456 * the volume (e.g. volume owned by a utility).
2457 * short circuit around potential disk header races.
2459 if (V_attachState(vp) != VOL_STATE_ATTACHED) {
2463 VUpdateVolume_r(ec, vp, 0);
2465 Log("VAttachVolume: Error updating volume\n");
2470 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2471 #ifndef AFS_DEMAND_ATTACH_FS
2472 /* This is a hack: by temporarily setting the incore
2473 * dontSalvage flag ON, the volume will be put back on the
2474 * Update list (with dontSalvage OFF again). It will then
2475 * come back in N minutes with DONT_SALVAGE eventually
2476 * set. This is the way that volumes that have never had
2477 * it set get it set; or that volumes that have been
2478 * offline without DONT SALVAGE having been set also
2479 * eventually get it set */
2480 V_dontSalvage(vp) = DONT_SALVAGE;
2481 #endif /* !AFS_DEMAND_ATTACH_FS */
2482 VAddToVolumeUpdateList_r(ec, vp);
2484 Log("VAttachVolume: Error adding volume to update list\n");
2491 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2496 if (VRequiresPartLock()) {
2497 VUnlockPartition_r(partition);
2500 #ifdef AFS_DEMAND_ATTACH_FS
2501 /* attach failed; make sure we're in error state */
2502 if (vp && !VIsErrorState(V_attachState(vp))) {
2503 VChangeState_r(vp, VOL_STATE_ERROR);
2505 #endif /* AFS_DEMAND_ATTACH_FS */
2512 #ifdef AFS_DEMAND_ATTACH_FS
2513 /* VAttachVolumeByVp_r
2515 * finish attaching a volume that is
2516 * in a less than fully attached state
2518 /* caller MUST hold a ref count on vp */
2520 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
2522 char name[VMAXPATHLEN];
2524 struct DiskPartition64 *partp;
2528 Volume * nvp = NULL;
2529 VolumeStats stats_save;
2533 /* volume utility should never call AttachByVp */
2534 osi_Assert(programType == fileServer);
2536 volumeId = vp->hashid;
2537 partp = vp->partition;
2538 VolumeExternalName_r(volumeId, name, sizeof(name));
2541 /* if another thread is performing a blocking op, wait */
2542 VWaitExclusiveState_r(vp);
2544 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2546 /* if it's already attached, see if we can return it */
2547 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2548 VGetVolumeByVp_r(ec, vp);
2549 if (V_inUse(vp) == fileServer) {
2552 if (vp->specialStatus == VBUSY)
2554 VDetachVolume_r(ec, vp);
2556 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2562 /* pre-attach volume if it hasn't been done yet */
2564 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2565 (V_attachState(vp) == VOL_STATE_DELETED) ||
2566 (V_attachState(vp) == VOL_STATE_ERROR)) {
2567 nvp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2573 VCreateReservation_r(nvp);
2578 osi_Assert(vp != NULL);
2579 VChangeState_r(vp, VOL_STATE_ATTACHING);
2581 /* restore monotonically increasing stats */
2582 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2586 /* compute path to disk header */
2587 strcpy(path, VPartitionPath(partp));
2591 strcat(path, OS_DIRSEP);
2596 * NOTE: attach2 is entered without any locks, and returns
2597 * with vol_glock_mutex held */
2598 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2601 * the event that an error was encountered, or
2602 * the volume was not brought to an attached state
2603 * for any reason, skip to the end. We cannot
2604 * safely call VUpdateVolume unless we "own" it.
2608 (V_attachState(vp) != VOL_STATE_ATTACHED)) {
2612 VUpdateVolume_r(ec, vp, 0);
2614 Log("VAttachVolume: Error updating volume %u\n", vp->hashid);
2618 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2619 #ifndef AFS_DEMAND_ATTACH_FS
2620 /* This is a hack: by temporarily setting the incore
2621 * dontSalvage flag ON, the volume will be put back on the
2622 * Update list (with dontSalvage OFF again). It will then
2623 * come back in N minutes with DONT_SALVAGE eventually
2624 * set. This is the way that volumes that have never had
2625 * it set get it set; or that volumes that have been
2626 * offline without DONT SALVAGE having been set also
2627 * eventually get it set */
2628 V_dontSalvage(vp) = DONT_SALVAGE;
2629 #endif /* !AFS_DEMAND_ATTACH_FS */
2630 VAddToVolumeUpdateList_r(ec, vp);
2632 Log("VAttachVolume: Error adding volume %u to update list\n", vp->hashid);
2639 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2643 VCancelReservation_r(nvp);
2646 if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2647 if (vp && !VIsErrorState(V_attachState(vp))) {
2648 VChangeState_r(vp, VOL_STATE_ERROR);
2657 * lock a volume on disk (non-blocking).
2659 * @param[in] vp The volume to lock
2660 * @param[in] locktype READ_LOCK or WRITE_LOCK
2662 * @return operation status
2663 * @retval 0 success, lock was obtained
2664 * @retval EBUSY a conflicting lock was held by another process
2665 * @retval EIO error acquiring lock
2667 * @pre If we're in the fileserver, vp is in an exclusive state
2669 * @pre vp is not already locked
2672 VLockVolumeNB(Volume *vp, int locktype)
2676 osi_Assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2677 osi_Assert(!(V_attachFlags(vp) & VOL_LOCKED));
2679 code = VLockVolumeByIdNB(vp->hashid, vp->partition, locktype);
2681 V_attachFlags(vp) |= VOL_LOCKED;
2688 * unlock a volume on disk that was locked with VLockVolumeNB.
2690 * @param[in] vp volume to unlock
2692 * @pre If we're in the fileserver, vp is in an exclusive state
2694 * @pre vp has already been locked
2697 VUnlockVolume(Volume *vp)
2699 osi_Assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2700 osi_Assert((V_attachFlags(vp) & VOL_LOCKED));
2702 VUnlockVolumeById(vp->hashid, vp->partition);
2704 V_attachFlags(vp) &= ~VOL_LOCKED;
2706 #endif /* AFS_DEMAND_ATTACH_FS */
2709 * read in a vol header, possibly lock the vol header, and possibly check out
2710 * the vol header from the fileserver, as part of volume attachment.
2712 * @param[out] ec error code
2713 * @param[in] vp volume pointer object
2714 * @param[in] partp disk partition object of the attaching partition
2715 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
2717 * @param[in] peek 1 to just try to read in the volume header and make sure
2718 * we don't try to lock the vol, or check it out from
2719 * FSSYNC or anything like that; 0 otherwise, for 'normal'
2721 * @param[out] acheckedOut If we successfully checked-out the volume from
2722 * the fileserver (if we needed to), this is set
2723 * to 1, otherwise it is untouched.
2725 * @note As part of DAFS volume attachment, the volume header may be either
2726 * read- or write-locked to ensure mutual exclusion of certain volume
2727 * operations. In some cases in order to determine whether we need to
2728 * read- or write-lock the header, we need to read in the header to see
2729 * if the volume is RW or not. So, if we read in the header under a
2730 * read-lock and determine that we actually need a write-lock on the
2731 * volume header, this function will drop the read lock, acquire a write
2732 * lock, and read the header in again.
2735 attach_volume_header(Error *ec, Volume *vp, struct DiskPartition64 *partp,
2736 int mode, int peek, int *acheckedOut)
2738 struct VolumeDiskHeader diskHeader;
2739 struct VolumeHeader header;
2742 int lock_tries = 0, checkout_tries = 0;
2744 VolumeId volid = vp->hashid;
2745 #ifdef FSSYNC_BUILD_CLIENT
2746 int checkout, done_checkout = 0;
2747 #endif /* FSSYNC_BUILD_CLIENT */
2748 #ifdef AFS_DEMAND_ATTACH_FS
2749 int locktype = 0, use_locktype = -1;
2750 #endif /* AFS_DEMAND_ATTACH_FS */
2756 if (lock_tries > VOL_MAX_CHECKOUT_RETRIES) {
2757 Log("VAttachVolume: retried too many times trying to lock header for "
2758 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2759 VPartitionPath(partp));
2763 if (checkout_tries > VOL_MAX_CHECKOUT_RETRIES) {
2764 Log("VAttachVolume: retried too many times trying to checkout "
2765 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2766 VPartitionPath(partp));
2771 if (VReadVolumeDiskHeader(volid, partp, NULL)) {
2772 /* short-circuit the 'volume does not exist' case */
2777 #ifdef FSSYNC_BUILD_CLIENT
2778 checkout = !done_checkout;
2780 if (!peek && checkout && VMustCheckoutVolume(mode)) {
2782 memset(&res, 0, sizeof(res));
2784 if (FSYNC_VolOp(volid, VPartitionPath(partp), FSYNC_VOL_NEEDVOLUME, mode, &res)
2787 if (res.hdr.reason == FSYNC_SALVAGE) {
2788 Log("VAttachVolume: file server says volume %lu is salvaging\n",
2789 afs_printable_uint32_lu(volid));
2792 Log("VAttachVolume: attach of volume %lu apparently denied by file server\n",
2793 afs_printable_uint32_lu(volid));
2794 *ec = VNOVOL; /* XXXX */
2802 #ifdef AFS_DEMAND_ATTACH_FS
2803 if (use_locktype < 0) {
2804 /* don't know whether vol is RO or RW; assume it's RO and we can retry
2805 * if it turns out to be RW */
2806 locktype = VVolLockType(mode, 0);
2809 /* a previous try says we should use use_locktype to lock the volume,
2811 locktype = use_locktype;
2814 if (!peek && locktype) {
2815 code = VLockVolumeNB(vp, locktype);
2817 if (code == EBUSY) {
2818 Log("VAttachVolume: another program has vol %lu locked\n",
2819 afs_printable_uint32_lu(volid));
2821 Log("VAttachVolume: error %d trying to lock vol %lu\n",
2822 code, afs_printable_uint32_lu(volid));
2829 #endif /* AFS_DEMAND_ATTACH_FS */
2831 code = VReadVolumeDiskHeader(volid, partp, &diskHeader);
2841 DiskToVolumeHeader(&header, &diskHeader);
2843 IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header.parent,
2844 header.largeVnodeIndex);
2845 IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header.parent,
2846 header.smallVnodeIndex);
2847 IH_INIT(vp->diskDataHandle, partp->device, header.parent,
2849 IH_INIT(vp->linkHandle, partp->device, header.parent, header.linkTable);
2852 /* only need to do this once */
2854 GetVolumeHeader(vp);
2858 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2859 /* demand attach changes the V_PEEK mechanism
2861 * we can now suck the current disk data structure over
2862 * the fssync interface without going to disk
2864 * (technically, we don't need to restrict this feature
2865 * to demand attach fileservers. However, I'm trying
2866 * to limit the number of common code changes)
2868 if (VCanUseFSSYNC() && (mode == V_PEEK || peek)) {
2870 res.payload.len = sizeof(VolumeDiskData);
2871 res.payload.buf = &vp->header->diskstuff;
2873 if (FSYNC_VolOp(vp->hashid,
2875 FSYNC_VOL_QUERY_HDR,
2878 goto disk_header_loaded;
2881 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2882 (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2883 sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2885 #ifdef AFS_DEMAND_ATTACH_FS
2888 IncUInt64(&VStats.hdr_loads);
2889 IncUInt64(&vp->stats.hdr_loads);
2891 #endif /* AFS_DEMAND_ATTACH_FS */
2894 Log("VAttachVolume: Error reading diskDataHandle header for vol %lu; "
2895 "error=%u\n", afs_printable_uint32_lu(volid), *ec);
2899 #ifdef AFS_DEMAND_ATTACH_FS
2900 # ifdef FSSYNC_BUILD_CLIENT
2902 # endif /* FSSYNC_BUILD_CLIENT */
2904 /* if the lock type we actually used to lock the volume is different than
2905 * the lock type we should have used, retry with the lock type we should
2907 use_locktype = VVolLockType(mode, VolumeWriteable(vp));
2908 if (locktype != use_locktype) {
2912 #endif /* AFS_DEMAND_ATTACH_FS */
2917 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2918 if (!peek && *ec == 0 && retry == 0 && VMustCheckoutVolume(mode)) {
2920 code = FSYNC_VerifyCheckout(volid, VPartitionPath(partp), FSYNC_VOL_NEEDVOLUME, mode);
2922 if (code == SYNC_DENIED) {
2923 /* must retry checkout; fileserver no longer thinks we have
2929 } else if (code != SYNC_OK) {
2933 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2936 /* either we are going to be called again for a second pass, or we
2937 * encountered an error; clean up in either case */
2939 #ifdef AFS_DEMAND_ATTACH_FS
2940 if ((V_attachFlags(vp) & VOL_LOCKED)) {
2943 #endif /* AFS_DEMAND_ATTACH_FS */
2944 if (vp->linkHandle) {
2945 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
2946 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
2947 IH_RELEASE(vp->diskDataHandle);
2948 IH_RELEASE(vp->linkHandle);
2961 #ifdef AFS_DEMAND_ATTACH_FS
2963 attach_check_vop(Error *ec, VolumeId volid, struct DiskPartition64 *partp,
2964 Volume *vp, int *acheckedOut)
2968 if (vp->pending_vol_op) {
2972 if (vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningUnknown) {
2974 code = VVolOpLeaveOnlineNoHeader_r(vp, vp->pending_vol_op);
2976 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
2977 } else if (code == 0) {
2978 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
2981 /* we need the vol header to determine if the volume can be
2982 * left online for the vop, so... get the header */
2986 /* attach header with peek=1 to avoid checking out the volume
2987 * or locking it; we just want the header info, we're not
2988 * messing with the volume itself at all */
2989 attach_volume_header(ec, vp, partp, V_PEEK, 1, acheckedOut);
2996 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
2997 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
2999 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3002 /* make sure we grab a new vol header and re-open stuff on
3003 * actual attachment; we can't keep the data we grabbed, since
3004 * it was not done under a lock and thus not safe */
3005 FreeVolumeHeader(vp);
3006 VReleaseVolumeHandles_r(vp);
3009 /* see if the pending volume op requires exclusive access */
3010 switch (vp->pending_vol_op->vol_op_state) {
3011 case FSSYNC_VolOpPending:
3012 /* this should never happen */
3013 osi_Assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpPending);
3016 case FSSYNC_VolOpRunningUnknown:
3017 /* this should never happen; we resolved 'unknown' above */
3018 osi_Assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
3021 case FSSYNC_VolOpRunningOffline:
3022 /* mark the volume down */
3024 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3026 /* do not set V_offlineMessage here; we don't have ownership of
3027 * the volume (and probably do not have the header loaded), so we
3028 * can't alter the disk header */
3030 /* check to see if we should set the specialStatus flag */
3031 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
3032 /* don't overwrite specialStatus if it was already set to
3033 * something else (e.g. VMOVED) */
3034 if (!vp->specialStatus) {
3035 vp->specialStatus = VBUSY;
3047 #endif /* AFS_DEMAND_ATTACH_FS */
3050 * volume attachment helper function.
3052 * @param[out] ec error code
3053 * @param[in] volumeId volume ID of the attaching volume
3054 * @param[in] path full path to the volume header .vol file
3055 * @param[in] partp disk partition object for the attaching partition
3056 * @param[in] vp volume object; vp->hashid, vp->device, vp->partition,
3057 * vp->vnode_list, vp->rx_call_list, and V_attachCV (for
3058 * DAFS) should already be initialized
3059 * @param[in] isbusy 1 if vp->specialStatus should be set to VBUSY; that is,
3060 * if there is a volume operation running for this volume
3061 * that should set the volume to VBUSY during its run. 0
3062 * otherwise. (see VVolOpSetVBusy_r)
3063 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
3065 * @param[out] acheckedOut If we successfully checked-out the volume from
3066 * the fileserver (if we needed to), this is set
3067 * to 1, otherwise it is 0.
3069 * @return pointer to the semi-attached volume pointer
3070 * @retval NULL an error occurred (check value of *ec)
3071 * @retval vp volume successfully attaching
3073 * @pre no locks held
3075 * @post VOL_LOCK held
3078 attach2(Error * ec, VolId volumeId, char *path, struct DiskPartition64 *partp,
3079 Volume * vp, int isbusy, int mode, int *acheckedOut)
3081 /* have we read in the header successfully? */
3082 int read_header = 0;
3084 #ifdef AFS_DEMAND_ATTACH_FS
3085 /* should we FreeVolume(vp) instead of VCheckFree(vp) in the error
3089 /* in the case of an error, to what state should the volume be
3091 VolState error_state = VOL_STATE_ERROR;
3092 #endif /* AFS_DEMAND_ATTACH_FS */
3096 vp->vnodeIndex[vLarge].handle = NULL;
3097 vp->vnodeIndex[vSmall].handle = NULL;
3098 vp->diskDataHandle = NULL;
3099 vp->linkHandle = NULL;
3103 #ifdef AFS_DEMAND_ATTACH_FS
3104 attach_check_vop(ec, volumeId, partp, vp, acheckedOut);
3106 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3109 attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3110 #endif /* !AFS_DEMAND_ATTACH_FS */
3112 if (*ec == VNOVOL) {
3113 /* if the volume doesn't exist, skip straight to 'error' so we don't
3114 * request a salvage */
3115 goto unlocked_error;
3121 /* ensure that we don't override specialStatus if it was set to
3122 * something else (e.g. VMOVED) */
3123 if (isbusy && !vp->specialStatus) {
3124 vp->specialStatus = VBUSY;
3126 vp->shuttingDown = 0;
3127 vp->goingOffline = 0;
3129 #ifdef AFS_DEMAND_ATTACH_FS
3130 vp->stats.last_attach = FT_ApproxTime();
3131 vp->stats.attaches++;
3135 IncUInt64(&VStats.attaches);
3136 vp->cacheCheck = ++VolumeCacheCheck;
3137 /* just in case this ever rolls over */
3138 if (!vp->cacheCheck)
3139 vp->cacheCheck = ++VolumeCacheCheck;
3142 #ifdef AFS_DEMAND_ATTACH_FS
3143 V_attachFlags(vp) |= VOL_HDR_LOADED;
3144 vp->stats.last_hdr_load = vp->stats.last_attach;
3145 #endif /* AFS_DEMAND_ATTACH_FS */
3149 struct IndexFileHeader iHead;
3151 #if OPENAFS_VOL_STATS
3153 * We just read in the diskstuff part of the header. If the detailed
3154 * volume stats area has not yet been initialized, we should bzero the
3155 * area and mark it as initialized.
3157 if (!(V_stat_initialized(vp))) {
3158 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
3159 V_stat_initialized(vp) = 1;
3161 #endif /* OPENAFS_VOL_STATS */
3163 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
3164 (char *)&iHead, sizeof(iHead),
3165 SMALLINDEXMAGIC, SMALLINDEXVERSION);
3168 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
3173 struct IndexFileHeader iHead;
3175 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
3176 (char *)&iHead, sizeof(iHead),
3177 LARGEINDEXMAGIC, LARGEINDEXVERSION);
3180 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
3184 #ifdef AFS_NAMEI_ENV
3186 struct versionStamp stamp;
3188 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
3189 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
3192 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
3195 #endif /* AFS_NAMEI_ENV */
3197 #if defined(AFS_DEMAND_ATTACH_FS)
3198 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
3200 if (!VCanScheduleSalvage()) {
3201 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3203 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER |
3204 VOL_SALVAGE_NO_OFFLINE);
3209 /* volume operation in progress */
3210 goto unlocked_error;
3212 #else /* AFS_DEMAND_ATTACH_FS */
3214 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3215 goto unlocked_error;
3217 #endif /* AFS_DEMAND_ATTACH_FS */
3219 if (V_needsSalvaged(vp)) {
3220 if (vp->specialStatus)
3221 vp->specialStatus = 0;
3223 #if defined(AFS_DEMAND_ATTACH_FS)
3224 if (!VCanScheduleSalvage()) {
3225 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
3227 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER |
3228 VOL_SALVAGE_NO_OFFLINE);
3231 #else /* AFS_DEMAND_ATTACH_FS */
3233 #endif /* AFS_DEMAND_ATTACH_FS */
3239 vp->nextVnodeUnique = V_uniquifier(vp);
3241 if (VShouldCheckInUse(mode) && V_inUse(vp) && VolumeWriteable(vp)) {
3242 if (!V_needsSalvaged(vp)) {
3243 V_needsSalvaged(vp) = 1;
3244 VUpdateVolume_r(ec, vp, 0);
3246 #if defined(AFS_DEMAND_ATTACH_FS)
3247 if (!VCanScheduleSalvage()) {
3248 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3250 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER |
3251 VOL_SALVAGE_NO_OFFLINE);
3254 #else /* AFS_DEMAND_ATTACH_FS */
3255 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3257 #endif /* AFS_DEMAND_ATTACH_FS */
3262 if (programType == fileServer && V_destroyMe(vp) == DESTROY_ME) {
3263 /* Only check destroyMe if we are the fileserver, since the
3264 * volserver et al sometimes need to work with volumes with
3265 * destroyMe set. Examples are 'temporary' volumes the
3266 * volserver creates, and when we create a volume (destroyMe
3267 * is set on creation; sometimes a separate volserver
3268 * transaction is created to clear destroyMe).
3271 #if defined(AFS_DEMAND_ATTACH_FS)
3272 /* schedule a salvage so the volume goes away on disk */
3273 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER |
3274 VOL_SALVAGE_NO_OFFLINE);
3275 VChangeState_r(vp, VOL_STATE_ERROR);
3278 #endif /* AFS_DEMAND_ATTACH_FS */
3279 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
3284 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
3285 #ifndef BITMAP_LATER
3286 if (programType == fileServer && VolumeWriteable(vp)) {
3288 for (i = 0; i < nVNODECLASSES; i++) {
3289 VGetBitmap_r(ec, vp, i);
3291 #ifdef AFS_DEMAND_ATTACH_FS
3292 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER |
3293 VOL_SALVAGE_NO_OFFLINE);
3295 #endif /* AFS_DEMAND_ATTACH_FS */
3296 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
3302 #endif /* BITMAP_LATER */
3304 if (VInit >= 2 && V_needsCallback(vp)) {
3305 if (V_BreakVolumeCallbacks) {
3306 Log("VAttachVolume: Volume %lu was changed externally; breaking callbacks\n",
3307 afs_printable_uint32_lu(V_id(vp)));
3308 V_needsCallback(vp) = 0;
3310 (*V_BreakVolumeCallbacks) (V_id(vp));
3313 VUpdateVolume_r(ec, vp, 0);
3315 #ifdef FSSYNC_BUILD_CLIENT
3316 else if (VCanUseFSSYNC()) {
3317 afs_int32 fsync_code;
3319 V_needsCallback(vp) = 0;
3321 fsync_code = FSYNC_VolOp(V_id(vp), NULL, FSYNC_VOL_BREAKCBKS, FSYNC_WHATEVER, NULL);
3325 V_needsCallback(vp) = 1;
3326 Log("Error trying to tell the fileserver to break callbacks for "
3327 "changed volume %lu; error code %ld\n",
3328 afs_printable_uint32_lu(V_id(vp)),
3329 afs_printable_int32_ld(fsync_code));
3331 VUpdateVolume_r(ec, vp, 0);
3334 #endif /* FSSYNC_BUILD_CLIENT */
3337 Log("VAttachVolume: error %d clearing needsCallback on volume "
3338 "%lu; needs salvage\n", (int)*ec,
3339 afs_printable_uint32_lu(V_id(vp)));
3340 #ifdef AFS_DEMAND_ATTACH_FS
3341 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER |
3342 VOL_SALVAGE_NO_OFFLINE);
3344 #else /* !AFS_DEMAND_ATTACH_FS */
3346 #endif /* !AFS_DEMAND_ATTACh_FS */
3351 if (programType == fileServer) {
3352 if (vp->specialStatus)
3353 vp->specialStatus = 0;
3354 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
3355 V_inUse(vp) = fileServer;
3356 V_offlineMessage(vp)[0] = '\0';
3360 #ifdef AFS_DEMAND_ATTACH_FS
3361 /* Put the vol into PREATTACHED state, so if someone tries to
3362 * access it again, we try to attach, see that we're not blessed,
3363 * and give a VNOVOL error again. Putting it into UNATTACHED state
3364 * would result in a VOFFLINE error instead. */
3365 error_state = VOL_STATE_PREATTACHED;
3366 #endif /* AFS_DEMAND_ATTACH_FS */
3368 /* mimic e.g. GetVolume errors */
3369 if (!V_blessed(vp)) {
3370 Log("Volume %lu offline: not blessed\n", afs_printable_uint32_lu(V_id(vp)));
3371 FreeVolumeHeader(vp);
3372 } else if (!V_inService(vp)) {
3373 Log("Volume %lu offline: not in service\n", afs_printable_uint32_lu(V_id(vp)));
3374 FreeVolumeHeader(vp);
3376 Log("Volume %lu offline: needs salvage\n", afs_printable_uint32_lu(V_id(vp)));
3378 #ifdef AFS_DEMAND_ATTACH_FS
3379 error_state = VOL_STATE_ERROR;
3380 /* see if we can recover */
3381 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
3384 #ifdef AFS_DEMAND_ATTACH_FS
3390 #ifdef AFS_DEMAND_ATTACH_FS
3391 if ((mode != V_PEEK) && (mode != V_SECRETLY))
3392 V_inUse(vp) = programType;
3393 #endif /* AFS_DEMAND_ATTACH_FS */
3394 V_checkoutMode(vp) = mode;
3397 AddVolumeToHashTable(vp, V_id(vp));
3398 #ifdef AFS_DEMAND_ATTACH_FS
3399 if (VCanUnlockAttached() && (V_attachFlags(vp) & VOL_LOCKED)) {
3402 if ((programType != fileServer) ||
3403 (V_inUse(vp) == fileServer)) {
3404 AddVolumeToVByPList_r(vp);
3406 VChangeState_r(vp, VOL_STATE_ATTACHED);
3408 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3417 #ifdef AFS_DEMAND_ATTACH_FS
3418 if (!VIsErrorState(V_attachState(vp))) {
3419 VChangeState_r(vp, error_state);
3421 #endif /* AFS_DEMAND_ATTACH_FS */
3424 VReleaseVolumeHandles_r(vp);
3427 #ifdef AFS_DEMAND_ATTACH_FS
3434 #else /* !AFS_DEMAND_ATTACH_FS */
3436 #endif /* !AFS_DEMAND_ATTACH_FS */
3440 /* Attach an existing volume.
3441 The volume also normally goes online at this time.
3442 An offline volume must be reattached to make it go online.
3446 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
3450 retVal = VAttachVolume_r(ec, volumeId, mode);
3456 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
3459 VGetVolumePath(ec, volumeId, &part, &name);
3463 vp = VGetVolume_r(&error, volumeId);
3465 osi_Assert(V_inUse(vp) == 0);
3466 VDetachVolume_r(ec, vp);
3470 return VAttachVolumeByName_r(ec, part, name, mode);
3473 /* Increment a reference count to a volume, sans context swaps. Requires
3474 * possibly reading the volume header in from the disk, since there's
3475 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
3477 * N.B. This call can fail if we can't read in the header!! In this case
3478 * we still guarantee we won't context swap, but the ref count won't be
3479 * incremented (otherwise we'd violate the invariant).
3481 /* NOTE: with the demand attach fileserver extensions, the global lock
3482 * is dropped within VHold */
3483 #ifdef AFS_DEMAND_ATTACH_FS
3485 VHold_r(Volume * vp)
3489 VCreateReservation_r(vp);
3490 VWaitExclusiveState_r(vp);
3492 LoadVolumeHeader(&error, vp);
3494 VCancelReservation_r(vp);
3498 VCancelReservation_r(vp);
3501 #else /* AFS_DEMAND_ATTACH_FS */
3503 VHold_r(Volume * vp)
3507 LoadVolumeHeader(&error, vp);
3513 #endif /* AFS_DEMAND_ATTACH_FS */
3515 /**** volume timeout-related stuff ****/
3517 #ifdef AFS_PTHREAD_ENV
3519 static struct timespec *shutdown_timeout;
3520 static pthread_once_t shutdown_timeout_once = PTHREAD_ONCE_INIT;
3523 VTimedOut(const struct timespec *ts)
3528 if (ts->tv_sec == 0) {
3529 /* short-circuit; this will have always timed out */
3533 code = gettimeofday(&tv, NULL);
3535 Log("Error %d from gettimeofday, assuming we have not timed out\n", errno);
3536 /* assume no timeout; failure mode is we just wait longer than normal
3537 * instead of returning errors when we shouldn't */
3541 if (tv.tv_sec < ts->tv_sec ||
3542 (tv.tv_sec == ts->tv_sec && tv.tv_usec*1000 < ts->tv_nsec)) {
3551 * Calculate an absolute timeout.
3553 * @param[out] ts A timeout that is "timeout" seconds from now, if we return
3554 * NULL, the memory is not touched
3555 * @param[in] timeout How long the timeout should be from now
3557 * @return timeout to use
3558 * @retval NULL no timeout; wait forever
3559 * @retval non-NULL the given value for "ts"
3563 static struct timespec *
3564 VCalcTimeout(struct timespec *ts, afs_int32 timeout)
3574 ts->tv_sec = ts->tv_nsec = 0;
3578 code = gettimeofday(&now, NULL);
3580 Log("Error %d from gettimeofday, falling back to 'forever' timeout\n", errno);
3584 ts->tv_sec = now.tv_sec + timeout;
3585 ts->tv_nsec = now.tv_usec * 1000;
3591 * Initialize the shutdown_timeout global.
3594 VShutdownTimeoutInit(void)
3596 struct timespec *ts;
3598 ts = malloc(sizeof(*ts));
3600 shutdown_timeout = VCalcTimeout(ts, vol_opts.offline_shutdown_timeout);
3602 if (!shutdown_timeout) {
3608 * Figure out the timeout that should be used for waiting for offline volumes.
3610 * @param[out] ats Storage space for a local timeout value if needed
3612 * @return The timeout value that should be used
3613 * @retval NULL No timeout; wait forever for offlining volumes
3614 * @retval non-NULL A pointer to the absolute time that should be used as
3615 * the deadline for waiting for offlining volumes.
3617 * @note If we return non-NULL, the pointer we return may or may not be the
3620 static const struct timespec *
3621 VOfflineTimeout(struct timespec *ats)
3623 if (vol_shutting_down) {
3624 osi_Assert(pthread_once(&shutdown_timeout_once, VShutdownTimeoutInit) == 0);
3625 return shutdown_timeout;
3627 return VCalcTimeout(ats, vol_opts.offline_timeout);
3631 #else /* AFS_PTHREAD_ENV */
3633 /* Waiting a certain amount of time for offlining volumes is not supported
3634 * for LWP due to a lack of primitives. So, we never time out */
3635 # define VTimedOut(x) (0)
3636 # define VOfflineTimeout(x) (NULL)
3638 #endif /* !AFS_PTHREAD_ENV */
3646 retVal = VHold_r(vp);
3653 VIsGoingOffline_r(struct Volume *vp)
3657 if (vp->goingOffline) {
3658 if (vp->specialStatus) {
3659 code = vp->specialStatus;
3660 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3671 * Tell the caller if a volume is waiting to go offline.
3673 * @param[in] vp The volume we want to know about
3675 * @return volume status
3676 * @retval 0 volume is not waiting to go offline, go ahead and use it
3677 * @retval nonzero volume is waiting to offline, and give the returned code
3678 * as an error to anyone accessing the volume
3680 * @pre VOL_LOCK is NOT held
3681 * @pre caller holds a heavyweight reference on vp
3684 VIsGoingOffline(struct Volume *vp)
3689 code = VIsGoingOffline_r(vp);
3696 * Register an RX call with a volume.
3698 * @param[inout] ec Error code; if unset when passed in, may be set if
3699 * the volume starts going offline
3700 * @param[out] client_ec @see GetVolume
3701 * @param[in] vp Volume struct
3702 * @param[in] cbv VCallByVol struct containing the RX call to register
3704 * @pre VOL_LOCK held
3705 * @pre caller holds heavy ref on vp
3710 VRegisterCall_r(Error *ec, Error *client_ec, Volume *vp, struct VCallByVol *cbv)
3713 #ifdef AFS_DEMAND_ATTACH_FS
3715 /* just in case the volume started going offline after we got the
3716 * reference to it... otherwise, if the volume started going
3717 * offline right at the end of GetVolume(), we might race with the
3718 * RX call scanner, and return success and add our cbv to the
3719 * rx_call_list _after_ the scanner has scanned the list. */
3720 *ec = VIsGoingOffline_r(vp);
3726 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3727 VWaitStateChange_r(vp);
3729 #endif /* AFS_DEMAND_ATTACH_FS */
3731 queue_Prepend(&vp->rx_call_list, cbv);
3736 * Deregister an RX call with a volume.
3738 * @param[in] vp Volume struct
3739 * @param[in] cbv VCallByVol struct containing the RX call to deregister
3741 * @pre VOL_LOCK held
3742 * @pre caller holds heavy ref on vp
3747 VDeregisterCall_r(Volume *vp, struct VCallByVol *cbv)
3749 if (cbv && queue_IsOnQueue(cbv)) {
3750 #ifdef AFS_DEMAND_ATTACH_FS
3751 while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3752 VWaitStateChange_r(vp);
3754 #endif /* AFS_DEMAND_ATTACH_FS */
3760 /***************************************************/
3761 /* get and put volume routines */
3762 /***************************************************/
3765 * put back a heavyweight reference to a volume object.
3767 * @param[in] vp volume object pointer
3769 * @pre VOL_LOCK held
3771 * @post heavyweight volume reference put back.
3772 * depending on state, volume may have been taken offline,
3773 * detached, salvaged, freed, etc.
3775 * @internal volume package internal use only
3778 VPutVolume_r(Volume * vp)
3780 osi_Assert(--vp->nUsers >= 0);
3781 if (vp->nUsers == 0) {
3783 ReleaseVolumeHeader(vp->header);
3784 #ifdef AFS_DEMAND_ATTACH_FS
3785 if (!VCheckDetach(vp)) {
3789 #else /* AFS_DEMAND_ATTACH_FS */
3791 #endif /* AFS_DEMAND_ATTACH_FS */
3796 VPutVolume(Volume * vp)
3804 * Puts a volume reference obtained with VGetVolumeWithCall.
3806 * @param[in] vp Volume struct
3807 * @param[in] cbv VCallByVol struct given to VGetVolumeWithCall, or NULL if none
3809 * @pre VOL_LOCK is NOT held
3812 VPutVolumeWithCall(Volume *vp, struct VCallByVol *cbv)
3815 VDeregisterCall_r(vp, cbv);
3820 /* Get a pointer to an attached volume. The pointer is returned regardless
3821 of whether or not the volume is in service or on/off line. An error
3822 code, however, is returned with an indication of the volume's status */
3824 VGetVolume(Error * ec, Error * client_ec, VolId volumeId)
3828 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
3834 * Get a volume reference associated with an RX call.
3836 * @param[out] ec @see GetVolume
3837 * @param[out] client_ec @see GetVolume
3838 * @param[in] volumeId @see GetVolume
3839 * @param[in] ts How long to wait for going-offline volumes (absolute time).
3840 * If NULL, wait forever. If ts->tv_sec == 0, return immediately
3841 * with an error if the volume is going offline.
3842 * @param[in] cbv Contains an RX call to be associated with this volume
3843 * reference. This call may be interrupted if the volume is
3844 * requested to go offline while we hold a ref on it. Give NULL
3845 * to not associate an RX call with this reference.
3847 * @return @see GetVolume
3849 * @note for LWP builds, ts must be NULL
3851 * @note A reference obtained with this function MUST be put back with
3852 * VPutVolumeWithCall
3855 VGetVolumeWithCall(Error * ec, Error * client_ec, VolId volumeId,
3856 const struct timespec *ts, struct VCallByVol *cbv)
3860 retVal = GetVolume(ec, client_ec, volumeId, NULL, ts);
3861 VRegisterCall_r(ec, client_ec, retVal, cbv);
3867 VGetVolume_r(Error * ec, VolId volumeId)
3869 return GetVolume(ec, NULL, volumeId, NULL, NULL);
3872 /* try to get a volume we've previously looked up */
3873 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
3875 VGetVolumeByVp_r(Error * ec, Volume * vp)
3877 return GetVolume(ec, NULL, vp->hashid, vp, NULL);
3881 * private interface for getting a volume handle
3883 * @param[out] ec error code (0 if no error)
3884 * @param[out] client_ec wire error code to be given to clients
3885 * @param[in] volumeId ID of the volume we want
3886 * @param[in] hint optional hint for hash lookups, or NULL
3887 * @param[in] timeout absolute deadline for waiting for the volume to go
3888 * offline, if it is going offline. NULL to wait forever.
3890 * @return a volume handle for the specified volume
3891 * @retval NULL an error occurred, or the volume is in such a state that
3892 * we cannot load a header or return any volume struct
3894 * @note for DAFS, caller must NOT hold a ref count on 'hint'
3896 * @note 'timeout' is only checked if the volume is actually going offline; so
3897 * if you pass timeout->tv_sec = 0, this will exhibit typical
3898 * nonblocking behavior.
3900 * @note for LWP builds, 'timeout' must be NULL
3903 GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint,
3904 const struct timespec *timeout)
3907 /* pull this profiling/debugging code out of regular builds */
3909 #define VGET_CTR_INC(x) x++
3910 unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
3911 0, V7 = 0, V8 = 0, V9 = 0;
3912 unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
3914 #define VGET_CTR_INC(x)
3916 #ifdef AFS_DEMAND_ATTACH_FS
3917 Volume *avp, * rvp = hint;
3921 * if VInit is zero, the volume package dynamic
3922 * data structures have not been initialized yet,
3923 * and we must immediately return an error
3929 *client_ec = VOFFLINE;
3934 #ifdef AFS_DEMAND_ATTACH_FS
3936 VCreateReservation_r(rvp);
3938 #endif /* AFS_DEMAND_ATTACH_FS */
3946 vp = VLookupVolume_r(ec, volumeId, vp);
3952 #ifdef AFS_DEMAND_ATTACH_FS
3953 if (rvp && (rvp != vp)) {
3954 /* break reservation on old vp */
3955 VCancelReservation_r(rvp);
3958 #endif /* AFS_DEMAND_ATTACH_FS */
3964 /* Until we have reached an initialization level of 2
3965 * we don't know whether this volume exists or not.
3966 * We can't sleep and retry later because before a volume
3967 * is attached, the caller tries to get it first. Just
3968 * return VOFFLINE and the caller can choose whether to
3969 * retry the command or not. */
3979 IncUInt64(&VStats.hdr_gets);
3981 #ifdef AFS_DEMAND_ATTACH_FS
3982 /* block if someone else is performing an exclusive op on this volume */
3985 VCreateReservation_r(rvp);
3987 VWaitExclusiveState_r(vp);
3989 /* short circuit with VNOVOL in the following circumstances:
3992 * - VOL_STATE_SHUTTING_DOWN
3994 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
3995 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN) ||
3996 (V_attachState(vp) == VOL_STATE_GOING_OFFLINE)) {
4003 * short circuit with VOFFLINE for VOL_STATE_UNATTACHED and
4004 * VNOVOL for VOL_STATE_DELETED
4006 if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
4007 (V_attachState(vp) == VOL_STATE_DELETED)) {
4008 if (vp->specialStatus) {
4009 *ec = vp->specialStatus;
4010 } else if (V_attachState(vp) == VOL_STATE_DELETED) {
4019 /* allowable states:
4026 if (vp->salvage.requested) {
4027 VUpdateSalvagePriority_r(vp);
4030 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
4031 avp = VAttachVolumeByVp_r(ec, vp, 0);
4034 /* VAttachVolumeByVp_r can return a pointer
4035 * != the vp passed to it under certain
4036 * conditions; make sure we don't leak
4037 * reservations if that happens */
4039 VCancelReservation_r(rvp);
4041 VCreateReservation_r(rvp);
4051 if (!vp->pending_vol_op) {
4066 if (VIsSalvaging(vp) || (*ec == VSALVAGING)) {
4068 /* see CheckVnode() in afsfileprocs.c for an explanation
4069 * of this error code logic */
4070 afs_uint32 now = FT_ApproxTime();
4071 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
4074 *client_ec = VRESTARTING;
4083 #ifdef AFS_DEMAND_ATTACH_FS
4085 * this test MUST happen after VAttachVolymeByVp, so vol_op_state is
4086 * not VolOpRunningUnknown (attach2 would have converted it to Online
4090 /* only valid before/during demand attachment */
4091 osi_Assert(!vp->pending_vol_op || vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
4093 /* deny getvolume due to running mutually exclusive vol op */
4094 if (vp->pending_vol_op && vp->pending_vol_op->vol_op_state==FSSYNC_VolOpRunningOffline) {
4096 * volume cannot remain online during this volume operation.
4099 if (vp->specialStatus) {
4101 * special status codes outrank normal VOFFLINE code
4103 *ec = vp->specialStatus;
4105 *client_ec = vp->specialStatus;
4109 /* see CheckVnode() in afsfileprocs.c for an explanation
4110 * of this error code logic */
4111 afs_uint32 now = FT_ApproxTime();
4112 if ((vp->stats.last_vol_op + (10 * 60)) >= now) {
4115 *client_ec = VRESTARTING;
4120 VChangeState_r(vp, VOL_STATE_UNATTACHED);
4121 FreeVolumeHeader(vp);
4125 #endif /* AFS_DEMAND_ATTACH_FS */
4127 LoadVolumeHeader(ec, vp);
4130 /* Only log the error if it was a totally unexpected error. Simply
4131 * a missing inode is likely to be caused by the volume being deleted */
4132 if (errno != ENXIO || LogLevel)
4133 Log("Volume %u: couldn't reread volume header\n",
4135 #ifdef AFS_DEMAND_ATTACH_FS
4136 if (VCanScheduleSalvage()) {
4137 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
4142 #else /* AFS_DEMAND_ATTACH_FS */
4145 #endif /* AFS_DEMAND_ATTACH_FS */
4150 if (vp->shuttingDown) {
4157 if (programType == fileServer) {
4159 if (vp->goingOffline) {
4160 if (timeout && VTimedOut(timeout)) {
4161 /* we've timed out; don't wait for the vol */
4164 #ifdef AFS_DEMAND_ATTACH_FS
4165 /* wait for the volume to go offline */
4166 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
4167 VTimedWaitStateChange_r(vp, timeout, NULL);
4169 #elif defined(AFS_PTHREAD_ENV)
4170 VOL_CV_TIMEDWAIT(&vol_put_volume_cond, timeout, NULL);
4171 #else /* AFS_PTHREAD_ENV */
4172 /* LWP has no timed wait, so the caller better not be
4174 osi_Assert(!timeout);
4175 LWP_WaitProcess(VPutVolume);
4176 #endif /* AFS_PTHREAD_ENV */
4180 if (vp->specialStatus) {
4182 *ec = vp->specialStatus;
4183 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
4186 } else if (V_inUse(vp) == 0 || vp->goingOffline) {
4197 #ifdef AFS_DEMAND_ATTACH_FS
4198 /* if no error, bump nUsers */
4201 VLRU_UpdateAccess_r(vp);
4204 VCancelReservation_r(rvp);
4207 if (client_ec && !*client_ec) {
4210 #else /* AFS_DEMAND_ATTACH_FS */
4211 /* if no error, bump nUsers */
4218 #endif /* AFS_DEMAND_ATTACH_FS */
4221 osi_Assert(vp || *ec);
4226 /***************************************************/
4227 /* Volume offline/detach routines */
4228 /***************************************************/
4230 /* caller MUST hold a heavyweight ref on vp */
4231 #ifdef AFS_DEMAND_ATTACH_FS
4233 VTakeOffline_r(Volume * vp)
4237 osi_Assert(vp->nUsers > 0);
4238 osi_Assert(programType == fileServer);
4240 VCreateReservation_r(vp);
4241 VWaitExclusiveState_r(vp);
4243 vp->goingOffline = 1;
4244 V_needsSalvaged(vp) = 1;
4246 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
4247 VCancelReservation_r(vp);
4249 #else /* AFS_DEMAND_ATTACH_FS */
4251 VTakeOffline_r(Volume * vp)
4253 osi_Assert(vp->nUsers > 0);
4254 osi_Assert(programType == fileServer);
4256 vp->goingOffline = 1;
4257 V_needsSalvaged(vp) = 1;
4259 #endif /* AFS_DEMAND_ATTACH_FS */
4262 VTakeOffline(Volume * vp)
4270 * force a volume offline.
4272 * @param[in] vp volume object pointer
4273 * @param[in] flags flags (see note below)
4275 * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
4276 * used when VUpdateVolume_r needs to call VForceOffline_r
4277 * (which in turn would normally call VUpdateVolume_r)
4279 * @see VUpdateVolume_r
4281 * @pre VOL_LOCK must be held.
4282 * for DAFS, caller must hold ref.
4284 * @note for DAFS, it _is safe_ to call this function from an
4287 * @post needsSalvaged flag is set.
4288 * for DAFS, salvage is requested.
4289 * no further references to the volume through the volume
4290 * package will be honored.
4291 * all file descriptor and vnode caches are invalidated.
4293 * @warning this is a heavy-handed interface. it results in
4294 * a volume going offline regardless of the current
4295 * reference count state.
4297 * @internal volume package internal use only
4300 VForceOffline_r(Volume * vp, int flags)
4304 #ifdef AFS_DEMAND_ATTACH_FS
4305 VChangeState_r(vp, VOL_STATE_ERROR);
4310 strcpy(V_offlineMessage(vp),
4311 "Forced offline due to internal error: volume needs to be salvaged");
4312 Log("Volume %u forced offline: it needs salvaging!\n", V_id(vp));
4315 vp->goingOffline = 0;
4316 V_needsSalvaged(vp) = 1;
4317 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
4318 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
4321 #ifdef AFS_DEMAND_ATTACH_FS
4322 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
4323 #endif /* AFS_DEMAND_ATTACH_FS */
4325 #ifdef AFS_PTHREAD_ENV
4326 CV_BROADCAST(&vol_put_volume_cond);
4327 #else /* AFS_PTHREAD_ENV */
4328 LWP_NoYieldSignal(VPutVolume);
4329 #endif /* AFS_PTHREAD_ENV */
4331 VReleaseVolumeHandles_r(vp);
4335 * force a volume offline.
4337 * @param[in] vp volume object pointer
4339 * @see VForceOffline_r
4342 VForceOffline(Volume * vp)
4345 VForceOffline_r(vp, 0);
4350 * Iterate over the RX calls associated with a volume, and interrupt them.
4352 * @param[in] vp The volume whose RX calls we want to scan
4354 * @pre VOL_LOCK held
4357 VScanCalls_r(struct Volume *vp)
4359 struct VCallByVol *cbv, *ncbv;
4361 #ifdef AFS_DEMAND_ATTACH_FS
4362 VolState state_save;
4365 if (queue_IsEmpty(&vp->rx_call_list))
4366 return; /* no calls to interrupt */
4367 if (!vol_opts.interrupt_rxcall)
4368 return; /* we have no function with which to interrupt calls */
4369 err = VIsGoingOffline_r(vp);
4371 return; /* we're not going offline anymore */
4373 #ifdef AFS_DEMAND_ATTACH_FS
4374 VWaitExclusiveState_r(vp);
4375 state_save = VChangeState_r(vp, VOL_STATE_SCANNING_RXCALLS);
4377 #endif /* AFS_DEMAND_ATTACH_FS */
4379 for(queue_Scan(&vp->rx_call_list, cbv, ncbv, VCallByVol)) {
4381 struct rx_peer *peer;
4383 peer = rx_PeerOf(rx_ConnectionOf(cbv->call));
4385 Log("Offlining volume %lu while client %s:%u is trying to read "
4386 "from it; kicking client off with error %ld\n",
4387 (long unsigned) vp->hashid,
4388 afs_inet_ntoa_r(rx_HostOf(peer), hoststr),
4389 (unsigned) ntohs(rx_PortOf(peer)),
4392 (*vol_opts.interrupt_rxcall) (cbv->call, err);
4395 #ifdef AFS_DEMAND_ATTACH_FS
4397 VChangeState_r(vp, state_save);
4398 #endif /* AFS_DEMAND_ATTACH_FS */
4401 #ifdef AFS_DEMAND_ATTACH_FS
4403 * Wait for a vp to go offline.
4405 * @param[out] ec 1 if a salvage on the volume has been requested and
4406 * salvok == 0, 0 otherwise
4407 * @param[in] vp The volume to wait for
4408 * @param[in] salvok If 0, we return immediately with *ec = 1 if the volume
4409 * has been requested to salvage. Otherwise we keep waiting
4410 * until the volume has gone offline.
4412 * @pre VOL_LOCK held
4413 * @pre caller holds a lightweight ref on vp
4418 VWaitForOfflineByVp_r(Error *ec, struct Volume *vp, int salvok)
4420 struct timespec timeout_ts;
4421 const struct timespec *ts;
4424 ts = VOfflineTimeout(&timeout_ts);
4428 while (!VIsOfflineState(V_attachState(vp)) && !timedout) {
4429 if (!salvok && vp->salvage.requested) {
4433 VTimedWaitStateChange_r(vp, ts, &timedout);
4436 /* we didn't time out, so the volume must be offline, so we're done */
4440 /* If we got here, we timed out waiting for the volume to go offline.
4441 * Kick off the accessing RX calls and wait again */
4445 while (!VIsOfflineState(V_attachState(vp))) {
4446 if (!salvok && vp->salvage.requested) {
4451 VWaitStateChange_r(vp);
4455 #else /* AFS_DEMAND_ATTACH_FS */
4458 * Wait for a volume to go offline.
4460 * @pre VOL_LOCK held
4462 * @note non-DAFS only (for DAFS, use @see WaitForOfflineByVp_r)
4465 VWaitForOffline_r(Error *ec, VolumeId volid)
4468 const struct timespec *ts;
4469 #ifdef AFS_PTHREAD_ENV
4470 struct timespec timeout_ts;
4473 ts = VOfflineTimeout(&timeout_ts);
4475 vp = GetVolume(ec, NULL, volid, NULL, ts);
4477 /* error occurred so bad that we can't even get a vp; we have no
4478 * information on the vol so we don't know whether to wait, so just
4482 if (!VIsGoingOffline_r(vp)) {
4483 /* volume is no longer going offline, so we're done */
4488 /* If we got here, we timed out waiting for the volume to go offline.
4489 * Kick off the accessing RX calls and wait again */
4495 vp = VGetVolume_r(ec, volid);
4497 /* In case it was reattached... */
4501 #endif /* !AFS_DEMAND_ATTACH_FS */
4503 /* The opposite of VAttachVolume. The volume header is written to disk, with
4504 the inUse bit turned off. A copy of the header is maintained in memory,
4505 however (which is why this is VOffline, not VDetach).
4508 VOffline_r(Volume * vp, char *message)
4511 #ifndef AFS_DEMAND_ATTACH_FS
4512 VolumeId vid = V_id(vp);
4515 osi_Assert(programType != volumeUtility && programType != volumeServer);
4520 if (V_offlineMessage(vp)[0] == '\0')
4521 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4522 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4524 vp->goingOffline = 1;
4525 #ifdef AFS_DEMAND_ATTACH_FS
4526 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4527 VCreateReservation_r(vp);
4529 VWaitForOfflineByVp_r(&error, vp, 1);
4530 VCancelReservation_r(vp);
4531 #else /* AFS_DEMAND_ATTACH_FS */
4533 VWaitForOffline_r(&error, vid);
4534 #endif /* AFS_DEMAND_ATTACH_FS */
4537 #ifdef AFS_DEMAND_ATTACH_FS
4539 * Take a volume offline in order to perform a volume operation.
4541 * @param[inout] ec address in which to store error code
4542 * @param[in] vp volume object pointer
4543 * @param[in] message volume offline status message
4546 * - VOL_LOCK is held
4547 * - caller MUST hold a heavyweight ref on vp
4550 * - volume is taken offline
4551 * - if possible, volume operation is promoted to running state
4552 * - on failure, *ec is set to nonzero
4554 * @note Although this function does not return any value, it may
4555 * still fail to promote our pending volume operation to
4556 * a running state. Any caller MUST check the value of *ec,
4557 * and MUST NOT blindly assume success.
4559 * @warning if the caller does not hold a lightweight ref on vp,
4560 * then it MUST NOT reference vp after this function
4561 * returns to the caller.
4563 * @internal volume package internal use only
4566 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
4569 osi_Assert(vp->pending_vol_op);
4575 if (V_offlineMessage(vp)[0] == '\0')
4576 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4577 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4579 vp->goingOffline = 1;
4580 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4581 VCreateReservation_r(vp);
4584 if (vp->pending_vol_op->com.programType != salvageServer) {
4585 /* do not give corrupted volumes to the volserver */
4590 VWaitForOfflineByVp_r(ec, vp, salvok);
4592 VCancelReservation_r(vp);
4594 #endif /* AFS_DEMAND_ATTACH_FS */
4597 VOffline(Volume * vp, char *message)
4600 VOffline_r(vp, message);
4604 /* This gets used for the most part by utility routines that don't want
4605 * to keep all the volume headers around. Generally, the file server won't
4606 * call this routine, because then the offline message in the volume header
4607 * (or other information) won't be available to clients. For NAMEI, also
4608 * close the file handles. However, the fileserver does call this during
4609 * an attach following a volume operation.
4612 VDetachVolume_r(Error * ec, Volume * vp)
4614 #ifdef FSSYNC_BUILD_CLIENT
4616 struct DiskPartition64 *tpartp;
4617 int notifyServer = 0;
4618 int useDone = FSYNC_VOL_ON;
4620 if (VCanUseFSSYNC()) {
4621 notifyServer = vp->needsPutBack;
4622 if (V_destroyMe(vp) == DESTROY_ME)
4623 useDone = FSYNC_VOL_LEAVE_OFF;
4624 # ifdef AFS_DEMAND_ATTACH_FS
4625 else if (!V_blessed(vp) || !V_inService(vp))
4626 useDone = FSYNC_VOL_LEAVE_OFF;
4629 # ifdef AFS_DEMAND_ATTACH_FS
4630 if (V_needsSalvaged(vp)) {
4632 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, 0);
4635 tpartp = vp->partition;
4637 #endif /* FSSYNC_BUILD_CLIENT */
4639 *ec = 0; /* always "succeeds" */
4640 DeleteVolumeFromHashTable(vp);
4641 vp->shuttingDown = 1;
4642 #ifdef AFS_DEMAND_ATTACH_FS
4643 DeleteVolumeFromVByPList_r(vp);
4645 VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
4647 if (programType != fileServer)
4649 #endif /* AFS_DEMAND_ATTACH_FS */
4651 /* Will be detached sometime in the future--this is OK since volume is offline */
4653 /* XXX the following code should really be moved to VCheckDetach() since the volume
4654 * is not technically detached until the refcounts reach zero
4656 #ifdef FSSYNC_BUILD_CLIENT
4657 if (VCanUseFSSYNC() && notifyServer) {
4658 if (notifyServer == VOL_PUTBACK_DELETE) {
4659 /* Only send FSYNC_VOL_DONE if the volume was actually deleted.
4660 * volserver code will set needsPutBack to VOL_PUTBACK_DELETE
4661 * to signify a deleted volume. */
4662 useDone = FSYNC_VOL_DONE;
4665 * Note: The server is not notified in the case of a bogus volume
4666 * explicitly to make it possible to create a volume, do a partial
4667 * restore, then abort the operation without ever putting the volume
4668 * online. This is essential in the case of a volume move operation
4669 * between two partitions on the same server. In that case, there
4670 * would be two instances of the same volume, one of them bogus,
4671 * which the file server would attempt to put on line
4673 FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
4674 /* XXX this code path is only hit by volume utilities, thus
4675 * V_BreakVolumeCallbacks will always be NULL. if we really
4676 * want to break callbacks in this path we need to use FSYNC_VolOp() */
4678 /* Dettaching it so break all callbacks on it */
4679 if (V_BreakVolumeCallbacks) {
4680 Log("volume %u detached; breaking all call backs\n", volume);
4681 (*V_BreakVolumeCallbacks) (volume);
4685 #endif /* FSSYNC_BUILD_CLIENT */
4689 VDetachVolume(Error * ec, Volume * vp)
4692 VDetachVolume_r(ec, vp);
4697 /***************************************************/
4698 /* Volume fd/inode handle closing routines */
4699 /***************************************************/
4701 /* For VDetachVolume, we close all cached file descriptors, but keep
4702 * the Inode handles in case we need to read from a busy volume.
4704 /* for demand attach, caller MUST hold ref count on vp */
4706 VCloseVolumeHandles_r(Volume * vp)
4708 #ifdef AFS_DEMAND_ATTACH_FS
4709 VolState state_save;
4711 state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
4716 DFlushVolume(vp->hashid);
4718 #ifdef AFS_DEMAND_ATTACH_FS
4722 /* DAFS: VCloseVnodeFiles_r drops the glock internally */
4723 VCloseVnodeFiles_r(vp);
4725 #ifdef AFS_DEMAND_ATTACH_FS
4729 /* Too time consuming and unnecessary for the volserver */
4730 if (programType == fileServer) {
4731 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4732 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4733 IH_CONDSYNC(vp->diskDataHandle);
4735 IH_CONDSYNC(vp->linkHandle);
4736 #endif /* AFS_NT40_ENV */
4739 IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
4740 IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
4741 IH_REALLYCLOSE(vp->diskDataHandle);
4742 IH_REALLYCLOSE(vp->linkHandle);
4744 #ifdef AFS_DEMAND_ATTACH_FS
4745 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4750 VChangeState_r(vp, state_save);
4754 /* For both VForceOffline and VOffline, we close all relevant handles.
4755 * For VOffline, if we re-attach the volume, the files may possible be
4756 * different than before.
4758 /* for demand attach, caller MUST hold a ref count on vp */
4760 VReleaseVolumeHandles_r(Volume * vp)
4762 #ifdef AFS_DEMAND_ATTACH_FS
4763 VolState state_save;
4765 state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
4770 DFlushVolume(vp->hashid);
4772 #ifdef AFS_DEMAND_ATTACH_FS
4776 VReleaseVnodeFiles_r(vp); /* DAFS: releases the glock internally */
4778 #ifdef AFS_DEMAND_ATTACH_FS
4782 /* Too time consuming and unnecessary for the volserver */
4783 if (programType == fileServer) {
4784 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4785 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4786 IH_CONDSYNC(vp->diskDataHandle);
4788 IH_CONDSYNC(vp->linkHandle);
4789 #endif /* AFS_NT40_ENV */
4792 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
4793 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
4794 IH_RELEASE(vp->diskDataHandle);
4795 IH_RELEASE(vp->linkHandle);
4797 #ifdef AFS_DEMAND_ATTACH_FS
4798 if ((V_attachFlags(vp) & VOL_LOCKED)) {
4803 VChangeState_r(vp, state_save);
4808 /***************************************************/
4809 /* Volume write and fsync routines */
4810 /***************************************************/
4813 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
4815 #ifdef AFS_DEMAND_ATTACH_FS
4816 VolState state_save;
4818 if (flags & VOL_UPDATE_WAIT) {
4819 VCreateReservation_r(vp);
4820 VWaitExclusiveState_r(vp);
4825 if (programType == fileServer)
4827 (V_inUse(vp) ? V_nextVnodeUnique(vp) +
4828 200 : V_nextVnodeUnique(vp));
4830 #ifdef AFS_DEMAND_ATTACH_FS
4831 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4835 WriteVolumeHeader_r(ec, vp);
4837 #ifdef AFS_DEMAND_ATTACH_FS
4839 VChangeState_r(vp, state_save);
4840 if (flags & VOL_UPDATE_WAIT) {
4841 VCancelReservation_r(vp);
4846 Log("VUpdateVolume: error updating volume header, volume %u (%s)\n",
4847 V_id(vp), V_name(vp));
4848 /* try to update on-disk header,
4849 * while preventing infinite recursion */
4850 if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
4851 VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
4857 VUpdateVolume(Error * ec, Volume * vp)
4860 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4865 VSyncVolume_r(Error * ec, Volume * vp, int flags)
4869 #ifdef AFS_DEMAND_ATTACH_FS
4870 VolState state_save;
4873 if (flags & VOL_SYNC_WAIT) {
4874 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4876 VUpdateVolume_r(ec, vp, 0);
4879 #ifdef AFS_DEMAND_ATTACH_FS
4880 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4883 fdP = IH_OPEN(V_diskDataHandle(vp));
4884 osi_Assert(fdP != NULL);
4885 code = FDH_SYNC(fdP);
4886 osi_Assert(code == 0);
4888 #ifdef AFS_DEMAND_ATTACH_FS
4890 VChangeState_r(vp, state_save);
4896 VSyncVolume(Error * ec, Volume * vp)
4899 VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
4904 /***************************************************/
4905 /* Volume dealloaction routines */
4906 /***************************************************/
4908 #ifdef AFS_DEMAND_ATTACH_FS
4910 FreeVolume(Volume * vp)
4912 /* free the heap space, iff it's safe.
4913 * otherwise, pull it out of the hash table, so it
4914 * will get deallocated when all refs to it go away */
4915 if (!VCheckFree(vp)) {
4916 DeleteVolumeFromHashTable(vp);
4917 DeleteVolumeFromVByPList_r(vp);
4919 /* make sure we invalidate the header cache entry */
4920 FreeVolumeHeader(vp);
4923 #endif /* AFS_DEMAND_ATTACH_FS */
4926 ReallyFreeVolume(Volume * vp)
4931 #ifdef AFS_DEMAND_ATTACH_FS
4933 VChangeState_r(vp, VOL_STATE_FREED);
4934 if (vp->pending_vol_op)
4935 free(vp->pending_vol_op);
4936 #endif /* AFS_DEMAND_ATTACH_FS */
4937 for (i = 0; i < nVNODECLASSES; i++)
4938 if (vp->vnodeIndex[i].bitmap)
4939 free(vp->vnodeIndex[i].bitmap);
4940 FreeVolumeHeader(vp);
4941 #ifndef AFS_DEMAND_ATTACH_FS
4942 DeleteVolumeFromHashTable(vp);
4943 #endif /* AFS_DEMAND_ATTACH_FS */
4947 /* check to see if we should shutdown this volume
4948 * returns 1 if volume was freed, 0 otherwise */
4949 #ifdef AFS_DEMAND_ATTACH_FS
4951 VCheckDetach(Volume * vp)
4956 if (vp->nUsers || vp->nWaiters)
4959 if (vp->shuttingDown) {
4961 if ((programType != fileServer) &&
4962 (V_inUse(vp) == programType) &&
4963 ((V_checkoutMode(vp) == V_VOLUPD) ||
4964 (V_checkoutMode(vp) == V_SECRETLY) ||
4965 ((V_checkoutMode(vp) == V_CLONE) &&
4966 (VolumeWriteable(vp))))) {
4968 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
4970 Log("VCheckDetach: volume header update for volume %u "
4971 "failed with errno %d\n", vp->hashid, errno);
4974 VReleaseVolumeHandles_r(vp);
4976 ReallyFreeVolume(vp);
4977 if (programType == fileServer) {
4978 CV_BROADCAST(&vol_put_volume_cond);
4983 #else /* AFS_DEMAND_ATTACH_FS */
4985 VCheckDetach(Volume * vp)
4993 if (vp->shuttingDown) {
4995 if ((programType != fileServer) &&
4996 (V_inUse(vp) == programType) &&
4997 ((V_checkoutMode(vp) == V_VOLUPD) ||
4998 (V_checkoutMode(vp) == V_SECRETLY) ||
4999 ((V_checkoutMode(vp) == V_CLONE) &&
5000 (VolumeWriteable(vp))))) {
5002 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5004 Log("VCheckDetach: volume header update for volume %u failed with errno %d\n",
5008 VReleaseVolumeHandles_r(vp);
5009 ReallyFreeVolume(vp);
5010 if (programType == fileServer) {
5011 #if defined(AFS_PTHREAD_ENV)
5012 CV_BROADCAST(&vol_put_volume_cond);
5013 #else /* AFS_PTHREAD_ENV */
5014 LWP_NoYieldSignal(VPutVolume);
5015 #endif /* AFS_PTHREAD_ENV */
5020 #endif /* AFS_DEMAND_ATTACH_FS */
5022 /* check to see if we should offline this volume
5023 * return 1 if volume went offline, 0 otherwise */
5024 #ifdef AFS_DEMAND_ATTACH_FS
5026 VCheckOffline(Volume * vp)
5030 if (vp->goingOffline && !vp->nUsers) {
5032 osi_Assert(programType == fileServer);
5033 osi_Assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
5034 (V_attachState(vp) != VOL_STATE_FREED) &&
5035 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
5036 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
5037 (V_attachState(vp) != VOL_STATE_DELETED));
5041 * VOL_STATE_GOING_OFFLINE
5042 * VOL_STATE_SHUTTING_DOWN
5043 * VIsErrorState(V_attachState(vp))
5044 * VIsExclusiveState(V_attachState(vp))
5047 VCreateReservation_r(vp);
5048 VChangeState_r(vp, VOL_STATE_OFFLINING);
5051 /* must clear the goingOffline flag before we drop the glock */
5052 vp->goingOffline = 0;
5057 /* perform async operations */
5058 VUpdateVolume_r(&error, vp, 0);
5059 VCloseVolumeHandles_r(vp);
5062 if (V_offlineMessage(vp)[0]) {
5063 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5064 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5065 V_offlineMessage(vp));
5067 Log("VOffline: Volume %lu (%s) is now offline\n",
5068 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5072 /* invalidate the volume header cache entry */
5073 FreeVolumeHeader(vp);
5075 /* if nothing changed state to error or salvaging,
5076 * drop state to unattached */
5077 if (!VIsErrorState(V_attachState(vp))) {
5078 VChangeState_r(vp, VOL_STATE_UNATTACHED);
5080 VCancelReservation_r(vp);
5081 /* no usage of vp is safe beyond this point */
5085 #else /* AFS_DEMAND_ATTACH_FS */
5087 VCheckOffline(Volume * vp)
5091 if (vp->goingOffline && !vp->nUsers) {
5093 osi_Assert(programType == fileServer);
5096 vp->goingOffline = 0;
5098 VUpdateVolume_r(&error, vp, 0);
5099 VCloseVolumeHandles_r(vp);
5101 if (V_offlineMessage(vp)[0]) {
5102 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5103 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5104 V_offlineMessage(vp));
5106 Log("VOffline: Volume %lu (%s) is now offline\n",
5107 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5110 FreeVolumeHeader(vp);
5111 #ifdef AFS_PTHREAD_ENV
5112 CV_BROADCAST(&vol_put_volume_cond);
5113 #else /* AFS_PTHREAD_ENV */
5114 LWP_NoYieldSignal(VPutVolume);
5115 #endif /* AFS_PTHREAD_ENV */
5119 #endif /* AFS_DEMAND_ATTACH_FS */
5121 /***************************************************/
5122 /* demand attach fs ref counting routines */
5123 /***************************************************/
5125 #ifdef AFS_DEMAND_ATTACH_FS
5126 /* the following two functions handle reference counting for
5127 * asynchronous operations on volume structs.
5129 * their purpose is to prevent a VDetachVolume or VShutdown
5130 * from free()ing the Volume struct during an async i/o op */
5132 /* register with the async volume op ref counter */
5133 /* VCreateReservation_r moved into inline code header because it
5134 * is now needed in vnode.c -- tkeiser 11/20/2007
5138 * decrement volume-package internal refcount.
5140 * @param vp volume object pointer
5142 * @internal volume package internal use only
5145 * @arg VOL_LOCK is held
5146 * @arg lightweight refcount held
5148 * @post volume waiters refcount is decremented; volume may
5149 * have been deallocated/shutdown/offlined/salvaged/
5150 * whatever during the process
5152 * @warning once you have tossed your last reference (you can acquire
5153 * lightweight refs recursively) it is NOT SAFE to reference
5154 * a volume object pointer ever again
5156 * @see VCreateReservation_r
5158 * @note DEMAND_ATTACH_FS only
5161 VCancelReservation_r(Volume * vp)
5163 osi_Assert(--vp->nWaiters >= 0);
5164 if (vp->nWaiters == 0) {
5166 if (!VCheckDetach(vp)) {
5173 /* check to see if we should free this volume now
5174 * return 1 if volume was freed, 0 otherwise */
5176 VCheckFree(Volume * vp)
5179 if ((vp->nUsers == 0) &&
5180 (vp->nWaiters == 0) &&
5181 !(V_attachFlags(vp) & (VOL_IN_HASH |
5185 ReallyFreeVolume(vp);
5190 #endif /* AFS_DEMAND_ATTACH_FS */
5193 /***************************************************/
5194 /* online volume operations routines */
5195 /***************************************************/
5197 #ifdef AFS_DEMAND_ATTACH_FS
5199 * register a volume operation on a given volume.
5201 * @param[in] vp volume object
5202 * @param[in] vopinfo volume operation info object
5204 * @pre VOL_LOCK is held
5206 * @post volume operation info object attached to volume object.
5207 * volume operation statistics updated.
5209 * @note by "attached" we mean a copy of the passed in object is made
5211 * @internal volume package internal use only
5214 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5216 FSSYNC_VolOp_info * info;
5218 /* attach a vol op info node to the volume struct */
5219 info = (FSSYNC_VolOp_info *) malloc(sizeof(FSSYNC_VolOp_info));
5220 osi_Assert(info != NULL);
5221 memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
5222 vp->pending_vol_op = info;
5225 vp->stats.last_vol_op = FT_ApproxTime();
5226 vp->stats.vol_ops++;
5227 IncUInt64(&VStats.vol_ops);
5233 * deregister the volume operation attached to this volume.
5235 * @param[in] vp volume object pointer
5237 * @pre VOL_LOCK is held
5239 * @post the volume operation info object is detached from the volume object
5241 * @internal volume package internal use only
5244 VDeregisterVolOp_r(Volume * vp)
5246 if (vp->pending_vol_op) {
5247 free(vp->pending_vol_op);
5248 vp->pending_vol_op = NULL;
5252 #endif /* AFS_DEMAND_ATTACH_FS */
5255 * determine whether it is safe to leave a volume online during
5256 * the volume operation described by the vopinfo object.
5258 * @param[in] vp volume object
5259 * @param[in] vopinfo volume operation info object
5261 * @return whether it is safe to leave volume online
5262 * @retval 0 it is NOT SAFE to leave the volume online
5263 * @retval 1 it is safe to leave the volume online during the operation
5266 * @arg VOL_LOCK is held
5267 * @arg disk header attached to vp (heavyweight ref on vp will guarantee
5268 * this condition is met)
5270 * @internal volume package internal use only
5273 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5275 return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
5276 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5277 (vopinfo->com.reason == V_READONLY ||
5278 (!VolumeWriteable(vp) &&
5279 (vopinfo->com.reason == V_CLONE ||
5280 vopinfo->com.reason == V_DUMP)))));
5284 * same as VVolOpLeaveOnline_r, but does not require a volume with an attached
5287 * @param[in] vp volume object
5288 * @param[in] vopinfo volume operation info object
5290 * @return whether it is safe to leave volume online
5291 * @retval 0 it is NOT SAFE to leave the volume online
5292 * @retval 1 it is safe to leave the volume online during the operation
5293 * @retval -1 unsure; volume header is required in order to know whether or
5294 * not is is safe to leave the volume online
5296 * @pre VOL_LOCK is held
5298 * @internal volume package internal use only
5301 VVolOpLeaveOnlineNoHeader_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5303 /* follow the logic in VVolOpLeaveOnline_r; this is the same, except
5304 * assume that we don't know VolumeWriteable; return -1 if the answer
5305 * depends on VolumeWriteable */
5307 if (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline) {
5310 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5311 vopinfo->com.reason == V_READONLY) {
5315 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5316 (vopinfo->com.reason == V_CLONE ||
5317 vopinfo->com.reason == V_DUMP)) {
5319 /* must know VolumeWriteable */
5326 * determine whether VBUSY should be set during this volume operation.
5328 * @param[in] vp volume object
5329 * @param[in] vopinfo volume operation info object
5331 * @return whether VBUSY should be set
5332 * @retval 0 VBUSY does NOT need to be set
5333 * @retval 1 VBUSY SHOULD be set
5335 * @pre VOL_LOCK is held
5337 * @internal volume package internal use only
5340 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5342 return ((vopinfo->com.command == FSYNC_VOL_OFF &&
5343 vopinfo->com.reason == FSYNC_SALVAGE) ||
5344 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5345 (vopinfo->com.reason == V_CLONE ||
5346 vopinfo->com.reason == V_DUMP)));
5350 /***************************************************/
5351 /* online salvager routines */
5352 /***************************************************/
5353 #if defined(AFS_DEMAND_ATTACH_FS)
5356 * offline a volume to let it be salvaged.
5358 * @param[in] vp Volume to offline
5360 * @return whether we offlined the volume successfully
5361 * @retval 0 volume was not offlined
5362 * @retval 1 volume is now offline
5364 * @note This is similar to VCheckOffline, but slightly different. We do not
5365 * deal with vp->goingOffline, and we try to avoid touching the volume
5366 * header except just to set needsSalvaged
5368 * @pre VOL_LOCK held
5369 * @pre vp->nUsers == 0
5370 * @pre V_attachState(vp) == VOL_STATE_SALVAGE_REQ
5373 VOfflineForSalvage_r(struct Volume *vp)
5377 VCreateReservation_r(vp);
5378 VWaitExclusiveState_r(vp);
5380 if (vp->nUsers || V_attachState(vp) == VOL_STATE_SALVAGING) {
5381 /* Someone's using the volume, or someone got to scheduling the salvage
5382 * before us. I don't think either of these should be possible, as we
5383 * should gain no new heavyweight references while we're trying to
5384 * salvage, but just to be sure... */
5385 VCancelReservation_r(vp);
5389 VChangeState_r(vp, VOL_STATE_OFFLINING);
5393 V_needsSalvaged(vp) = 1;
5394 /* ignore error; updating needsSalvaged is just best effort */
5395 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
5397 VCloseVolumeHandles_r(vp);
5399 FreeVolumeHeader(vp);
5401 /* volume has been effectively offlined; we can mark it in the SALVAGING
5402 * state now, which lets FSSYNC give it away */
5403 VChangeState_r(vp, VOL_STATE_SALVAGING);
5405 VCancelReservation_r(vp);
5411 * check whether a salvage needs to be performed on this volume.
5413 * @param[in] vp pointer to volume object
5415 * @return status code
5416 * @retval 0 no salvage scheduled
5417 * @retval 1 a salvage has been scheduled with the salvageserver
5419 * @pre VOL_LOCK is held
5421 * @post if salvage request flag is set and nUsers and nWaiters are zero,
5422 * then a salvage will be requested
5424 * @note this is one of the event handlers called by VCancelReservation_r
5426 * @note the caller must check if the volume needs to be freed after calling
5427 * this; the volume may not have any references or be on any lists after
5428 * we return, and we do not free it
5430 * @see VCancelReservation_r
5432 * @internal volume package internal use only.
5435 VCheckSalvage(Volume * vp)
5438 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5441 if (!vp->salvage.requested) {
5445 /* prevent recursion; some of the code below creates and removes
5446 * lightweight refs, which can call VCheckSalvage */
5447 if (vp->salvage.scheduling) {
5450 vp->salvage.scheduling = 1;
5452 if (V_attachState(vp) == VOL_STATE_SALVAGE_REQ) {
5453 if (!VOfflineForSalvage_r(vp)) {
5454 vp->salvage.scheduling = 0;
5459 if (vp->salvage.requested) {
5460 VScheduleSalvage_r(vp);
5463 vp->salvage.scheduling = 0;
5464 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5469 * request volume salvage.
5471 * @param[out] ec computed client error code
5472 * @param[in] vp volume object pointer
5473 * @param[in] reason reason code (passed to salvageserver via SALVSYNC)
5474 * @param[in] flags see flags note below
5477 * VOL_SALVAGE_INVALIDATE_HEADER causes volume header cache entry
5478 * to be invalidated.
5480 * @pre VOL_LOCK is held.
5482 * @post volume state is changed.
5483 * for fileserver, salvage will be requested once refcount reaches zero.
5485 * @return operation status code
5486 * @retval 0 volume salvage will occur
5487 * @retval 1 volume salvage could not be scheduled
5491 * @note in the fileserver, this call does not synchronously schedule a volume
5492 * salvage. rather, it sets volume state so that when volume refcounts
5493 * reach zero, a volume salvage will occur. by "refcounts", we mean both
5494 * nUsers and nWaiters must be zero.
5496 * @internal volume package internal use only.
5499 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
5503 * for DAFS volume utilities that are not supposed to schedule salvages,
5504 * just transition to error state instead
5506 if (!VCanScheduleSalvage()) {
5507 VChangeState_r(vp, VOL_STATE_ERROR);
5512 if (programType != fileServer && !VCanUseFSSYNC()) {
5513 VChangeState_r(vp, VOL_STATE_ERROR);
5518 if (!vp->salvage.requested) {
5519 vp->salvage.requested = 1;
5520 vp->salvage.reason = reason;
5521 vp->stats.last_salvage = FT_ApproxTime();
5523 /* Note that it is not possible for us to reach this point if a
5524 * salvage is already running on this volume (even if the fileserver
5525 * was restarted during the salvage). If a salvage were running, the
5526 * salvager would have write-locked the volume header file, so when
5527 * we tried to lock the volume header, the lock would have failed,
5528 * and we would have failed during attachment prior to calling
5529 * VRequestSalvage. So we know that we can schedule salvages without
5530 * fear of a salvage already running for this volume. */
5532 if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
5534 /* if we don't need to offline the volume, we can go directly
5535 * to SALVAGING. SALVAGING says the volume is offline and is
5536 * either salvaging or ready to be handed to the salvager.
5537 * SALVAGE_REQ says that we want to salvage the volume, but we
5538 * are waiting for it to go offline first. */
5539 if (flags & VOL_SALVAGE_NO_OFFLINE) {
5540 VChangeState_r(vp, VOL_STATE_SALVAGING);
5542 VChangeState_r(vp, VOL_STATE_SALVAGE_REQ);
5543 if (vp->nUsers == 0) {
5544 /* normally VOfflineForSalvage_r would be called from
5545 * PutVolume et al when nUsers reaches 0, but if
5546 * it's already 0, just do it ourselves, since PutVolume
5547 * isn't going to get called */
5548 VOfflineForSalvage_r(vp);
5551 /* If we are non-fileserver, we're telling the fileserver to
5552 * salvage the vol, so we don't need to give it back separately. */
5553 vp->needsPutBack = 0;
5557 Log("VRequestSalvage: volume %u online salvaged too many times; forced offline.\n", vp->hashid);
5559 /* make sure neither VScheduleSalvage_r nor
5560 * VUpdateSalvagePriority_r try to schedule another salvage */
5561 vp->salvage.requested = vp->salvage.scheduled = 0;
5563 VChangeState_r(vp, VOL_STATE_ERROR);
5567 if (flags & VOL_SALVAGE_INVALIDATE_HEADER) {
5568 /* Instead of ReleaseVolumeHeader, we do FreeVolumeHeader()
5569 so that the the next VAttachVolumeByVp_r() invocation
5570 of attach2() will pull in a cached header
5571 entry and fail, then load a fresh one from disk and attach
5574 FreeVolumeHeader(vp);
5581 * update salvageserver scheduling priority for a volume.
5583 * @param[in] vp pointer to volume object
5585 * @return operation status
5587 * @retval 1 request denied, or SALVSYNC communications failure
5589 * @pre VOL_LOCK is held.
5591 * @post in-core salvage priority counter is incremented. if at least
5592 * SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
5593 * last SALVSYNC_RAISEPRIO request, we contact the salvageserver
5594 * to update its priority queue. if no salvage is scheduled,
5595 * this function is a no-op.
5597 * @note DAFS fileserver only
5599 * @note this should be called whenever a VGetVolume fails due to a
5600 * pending salvage request
5602 * @todo should set exclusive state and drop glock around salvsync call
5604 * @internal volume package internal use only.
5607 VUpdateSalvagePriority_r(Volume * vp)
5611 #ifdef SALVSYNC_BUILD_CLIENT
5616 now = FT_ApproxTime();
5618 /* update the salvageserver priority queue occasionally so that
5619 * frequently requested volumes get moved to the head of the queue
5621 if ((vp->salvage.scheduled) &&
5622 (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
5623 code = SALVSYNC_SalvageVolume(vp->hashid,
5624 VPartitionPath(vp->partition),
5629 vp->stats.last_salvage_req = now;
5630 if (code != SYNC_OK) {
5634 #endif /* SALVSYNC_BUILD_CLIENT */
5639 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5641 /* A couple of little helper functions. These return true if we tried to
5642 * use this mechanism to schedule a salvage, false if we haven't tried.
5643 * If we did try a salvage then the results are contained in code.
5647 try_SALVSYNC(Volume *vp, char *partName, int *code) {
5648 #ifdef SALVSYNC_BUILD_CLIENT
5649 if (VCanUseSALVSYNC()) {
5650 Log("Scheduling salvage for volume %lu on part %s over SALVSYNC\n",
5651 afs_printable_uint32_lu(vp->hashid), partName);
5653 /* can't use V_id() since there's no guarantee
5654 * we have the disk data header at this point */
5655 *code = SALVSYNC_SalvageVolume(vp->hashid,
5668 try_FSSYNC(Volume *vp, char *partName, int *code) {
5669 #ifdef FSSYNC_BUILD_CLIENT
5670 if (VCanUseFSSYNC()) {
5671 Log("Scheduling salvage for volume %lu on part %s over FSSYNC\n",
5672 afs_printable_uint32_lu(vp->hashid), partName);
5675 * If we aren't the fileserver, tell the fileserver the volume
5676 * needs to be salvaged. We could directly tell the
5677 * salvageserver, but the fileserver keeps track of some stats
5678 * related to salvages, and handles some other salvage-related
5679 * complications for us.
5681 *code = FSYNC_VolOp(vp->hashid, partName,
5682 FSYNC_VOL_FORCE_ERROR, FSYNC_SALVAGE, NULL);
5685 #endif /* FSSYNC_BUILD_CLIENT */
5690 * schedule a salvage with the salvage server or fileserver.
5692 * @param[in] vp pointer to volume object
5694 * @return operation status
5695 * @retval 0 salvage scheduled successfully
5696 * @retval 1 salvage not scheduled, or SALVSYNC/FSSYNC com error
5699 * @arg VOL_LOCK is held.
5700 * @arg nUsers and nWaiters should be zero.
5702 * @post salvageserver or fileserver is sent a salvage request
5704 * @note If we are the fileserver, the request will be sent to the salvage
5705 * server over SALVSYNC. If we are not the fileserver, the request will be
5706 * sent to the fileserver over FSSYNC (FSYNC_VOL_FORCE_ERROR/FSYNC_SALVAGE).
5708 * @note the caller must check if the volume needs to be freed after calling
5709 * this; the volume may not have any references or be on any lists after
5710 * we return, and we do not free it
5714 * @internal volume package internal use only.
5717 VScheduleSalvage_r(Volume * vp)
5721 VolState state_save;
5722 VThreadOptions_t * thread_opts;
5725 osi_Assert(VCanUseSALVSYNC() || VCanUseFSSYNC());
5727 if (vp->nWaiters || vp->nUsers) {
5731 /* prevent endless salvage,attach,salvage,attach,... loops */
5732 if (vp->stats.salvages >= SALVAGE_COUNT_MAX)
5736 * don't perform salvsync ops on certain threads
5738 thread_opts = pthread_getspecific(VThread_key);
5739 if (thread_opts == NULL) {
5740 thread_opts = &VThread_defaults;
5742 if (thread_opts->disallow_salvsync || vol_disallow_salvsync) {
5746 if (vp->salvage.scheduled) {
5750 VCreateReservation_r(vp);
5751 VWaitExclusiveState_r(vp);
5754 * XXX the scheduling process should really be done asynchronously
5755 * to avoid fssync deadlocks
5757 if (!vp->salvage.scheduled) {
5758 /* if we haven't previously scheduled a salvage, do so now
5760 * set the volume to an exclusive state and drop the lock
5761 * around the SALVSYNC call
5763 strlcpy(partName, VPartitionPath(vp->partition), sizeof(partName));
5764 state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
5767 osi_Assert(try_SALVSYNC(vp, partName, &code) ||
5768 try_FSSYNC(vp, partName, &code));
5771 VChangeState_r(vp, state_save);
5773 if (code == SYNC_OK) {
5774 vp->salvage.scheduled = 1;
5775 vp->stats.last_salvage_req = FT_ApproxTime();
5776 if (VCanUseSALVSYNC()) {
5777 /* don't record these stats for non-fileservers; let the
5778 * fileserver take care of these */
5779 vp->stats.salvages++;
5780 IncUInt64(&VStats.salvages);
5785 case SYNC_BAD_COMMAND:
5786 case SYNC_COM_ERROR:
5789 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5790 "denied\n", afs_printable_uint32_lu(vp->hashid));
5793 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5794 "received unknown protocol error %d\n",
5795 afs_printable_uint32_lu(vp->hashid), code);
5799 if (VCanUseFSSYNC()) {
5800 VChangeState_r(vp, VOL_STATE_ERROR);
5805 /* NB: this is cancelling the reservation we obtained above, but we do
5806 * not call VCancelReservation_r, since that may trigger the vp dtor,
5807 * possibly free'ing the vp. We need to keep the vp around after
5808 * this, as the caller may reference vp without any refs. Instead, it
5809 * is the duty of the caller to inspect 'vp' after we return to see if
5810 * needs to be freed. */
5811 osi_Assert(--vp->nWaiters >= 0);
5814 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5816 #ifdef SALVSYNC_BUILD_CLIENT
5819 * connect to the salvageserver SYNC service.
5821 * @return operation status
5825 * @post connection to salvageserver SYNC service established
5827 * @see VConnectSALV_r
5828 * @see VDisconnectSALV
5829 * @see VReconnectSALV
5836 retVal = VConnectSALV_r();
5842 * connect to the salvageserver SYNC service.
5844 * @return operation status
5848 * @pre VOL_LOCK is held.
5850 * @post connection to salvageserver SYNC service established
5853 * @see VDisconnectSALV_r
5854 * @see VReconnectSALV_r
5855 * @see SALVSYNC_clientInit
5857 * @internal volume package internal use only.
5860 VConnectSALV_r(void)
5862 return SALVSYNC_clientInit();
5866 * disconnect from the salvageserver SYNC service.
5868 * @return operation status
5871 * @pre client should have a live connection to the salvageserver
5873 * @post connection to salvageserver SYNC service destroyed
5875 * @see VDisconnectSALV_r
5877 * @see VReconnectSALV
5880 VDisconnectSALV(void)
5883 VDisconnectSALV_r();
5889 * disconnect from the salvageserver SYNC service.
5891 * @return operation status
5895 * @arg VOL_LOCK is held.
5896 * @arg client should have a live connection to the salvageserver.
5898 * @post connection to salvageserver SYNC service destroyed
5900 * @see VDisconnectSALV
5901 * @see VConnectSALV_r
5902 * @see VReconnectSALV_r
5903 * @see SALVSYNC_clientFinis
5905 * @internal volume package internal use only.
5908 VDisconnectSALV_r(void)
5910 return SALVSYNC_clientFinis();
5914 * disconnect and then re-connect to the salvageserver SYNC service.
5916 * @return operation status
5920 * @pre client should have a live connection to the salvageserver
5922 * @post old connection is dropped, and a new one is established
5925 * @see VDisconnectSALV
5926 * @see VReconnectSALV_r
5929 VReconnectSALV(void)
5933 retVal = VReconnectSALV_r();
5939 * disconnect and then re-connect to the salvageserver SYNC service.
5941 * @return operation status
5946 * @arg VOL_LOCK is held.
5947 * @arg client should have a live connection to the salvageserver.
5949 * @post old connection is dropped, and a new one is established
5951 * @see VConnectSALV_r
5952 * @see VDisconnectSALV
5953 * @see VReconnectSALV
5954 * @see SALVSYNC_clientReconnect
5956 * @internal volume package internal use only.
5959 VReconnectSALV_r(void)
5961 return SALVSYNC_clientReconnect();
5963 #endif /* SALVSYNC_BUILD_CLIENT */
5964 #endif /* AFS_DEMAND_ATTACH_FS */
5967 /***************************************************/
5968 /* FSSYNC routines */
5969 /***************************************************/
5971 /* This must be called by any volume utility which needs to run while the
5972 file server is also running. This is separated from VInitVolumePackage2 so
5973 that a utility can fork--and each of the children can independently
5974 initialize communication with the file server */
5975 #ifdef FSSYNC_BUILD_CLIENT
5977 * connect to the fileserver SYNC service.
5979 * @return operation status
5984 * @arg VInit must equal 2.
5985 * @arg Program Type must not be fileserver or salvager.
5987 * @post connection to fileserver SYNC service established
5990 * @see VDisconnectFS
5991 * @see VChildProcReconnectFS
5998 retVal = VConnectFS_r();
6004 * connect to the fileserver SYNC service.
6006 * @return operation status
6011 * @arg VInit must equal 2.
6012 * @arg Program Type must not be fileserver or salvager.
6013 * @arg VOL_LOCK is held.
6015 * @post connection to fileserver SYNC service established
6018 * @see VDisconnectFS_r
6019 * @see VChildProcReconnectFS_r
6021 * @internal volume package internal use only.
6027 osi_Assert((VInit == 2) &&
6028 (programType != fileServer) &&
6029 (programType != salvager));
6030 rc = FSYNC_clientInit();
6038 * disconnect from the fileserver SYNC service.
6041 * @arg client should have a live connection to the fileserver.
6042 * @arg VOL_LOCK is held.
6043 * @arg Program Type must not be fileserver or salvager.
6045 * @post connection to fileserver SYNC service destroyed
6047 * @see VDisconnectFS
6049 * @see VChildProcReconnectFS_r
6051 * @internal volume package internal use only.
6054 VDisconnectFS_r(void)
6056 osi_Assert((programType != fileServer) &&
6057 (programType != salvager));
6058 FSYNC_clientFinis();
6063 * disconnect from the fileserver SYNC service.
6066 * @arg client should have a live connection to the fileserver.
6067 * @arg Program Type must not be fileserver or salvager.
6069 * @post connection to fileserver SYNC service destroyed
6071 * @see VDisconnectFS_r
6073 * @see VChildProcReconnectFS
6084 * connect to the fileserver SYNC service from a child process following a fork.
6086 * @return operation status
6091 * @arg VOL_LOCK is held.
6092 * @arg current FSYNC handle is shared with a parent process
6094 * @post current FSYNC handle is discarded and a new connection to the
6095 * fileserver SYNC service is established
6097 * @see VChildProcReconnectFS
6099 * @see VDisconnectFS_r
6101 * @internal volume package internal use only.
6104 VChildProcReconnectFS_r(void)
6106 return FSYNC_clientChildProcReconnect();
6110 * connect to the fileserver SYNC service from a child process following a fork.
6112 * @return operation status
6116 * @pre current FSYNC handle is shared with a parent process
6118 * @post current FSYNC handle is discarded and a new connection to the
6119 * fileserver SYNC service is established
6121 * @see VChildProcReconnectFS_r
6123 * @see VDisconnectFS
6126 VChildProcReconnectFS(void)
6130 ret = VChildProcReconnectFS_r();
6134 #endif /* FSSYNC_BUILD_CLIENT */
6137 /***************************************************/
6138 /* volume bitmap routines */
6139 /***************************************************/
6142 * allocate a vnode bitmap number for the vnode
6144 * @param[out] ec error code
6145 * @param[in] vp volume object pointer
6146 * @param[in] index vnode index number for the vnode
6147 * @param[in] flags flag values described in note
6149 * @note for DAFS, flags parameter controls locking behavior.
6150 * If (flags & VOL_ALLOC_BITMAP_WAIT) is set, then this function
6151 * will create a reservation and block on any other exclusive
6152 * operations. Otherwise, this function assumes the caller
6153 * already has exclusive access to vp, and we just change the
6156 * @pre VOL_LOCK held
6158 * @return bit number allocated
6164 VAllocBitmapEntry_r(Error * ec, Volume * vp,
6165 struct vnodeIndex *index, int flags)
6169 #ifdef AFS_DEMAND_ATTACH_FS
6170 VolState state_save;
6171 #endif /* AFS_DEMAND_ATTACH_FS */
6175 /* This test is probably redundant */
6176 if (!VolumeWriteable(vp)) {
6177 *ec = (bit32) VREADONLY;
6181 #ifdef AFS_DEMAND_ATTACH_FS
6182 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6183 VCreateReservation_r(vp);
6184 VWaitExclusiveState_r(vp);
6186 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6187 #endif /* AFS_DEMAND_ATTACH_FS */
6190 if ((programType == fileServer) && !index->bitmap) {
6192 #ifndef AFS_DEMAND_ATTACH_FS
6193 /* demand attach fs uses the volume state to avoid races.
6194 * specialStatus field is not used at all */
6196 if (vp->specialStatus == VBUSY) {
6197 if (vp->goingOffline) { /* vos dump waiting for the volume to
6198 * go offline. We probably come here
6199 * from AddNewReadableResidency */
6202 while (vp->specialStatus == VBUSY) {
6203 #ifdef AFS_PTHREAD_ENV
6207 #else /* !AFS_PTHREAD_ENV */
6209 #endif /* !AFS_PTHREAD_ENV */
6213 #endif /* !AFS_DEMAND_ATTACH_FS */
6215 if (!index->bitmap) {
6216 #ifndef AFS_DEMAND_ATTACH_FS
6217 vp->specialStatus = VBUSY; /* Stop anyone else from using it. */
6218 #endif /* AFS_DEMAND_ATTACH_FS */
6219 for (i = 0; i < nVNODECLASSES; i++) {
6220 VGetBitmap_r(ec, vp, i);
6222 #ifdef AFS_DEMAND_ATTACH_FS
6223 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
6224 #else /* AFS_DEMAND_ATTACH_FS */
6225 DeleteVolumeFromHashTable(vp);
6226 vp->shuttingDown = 1; /* Let who has it free it. */
6227 vp->specialStatus = 0;
6228 #endif /* AFS_DEMAND_ATTACH_FS */
6232 #ifndef AFS_DEMAND_ATTACH_FS
6234 vp->specialStatus = 0; /* Allow others to have access. */
6235 #endif /* AFS_DEMAND_ATTACH_FS */
6238 #endif /* BITMAP_LATER */
6240 #ifdef AFS_DEMAND_ATTACH_FS
6242 #endif /* AFS_DEMAND_ATTACH_FS */
6243 bp = index->bitmap + index->bitmapOffset;
6244 ep = index->bitmap + index->bitmapSize;
6246 if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
6248 index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
6251 o = ffs(~*bp) - 1; /* ffs is documented in BSTRING(3) */
6253 ret = ((bp - index->bitmap) * 8 + o);
6254 #ifdef AFS_DEMAND_ATTACH_FS
6256 #endif /* AFS_DEMAND_ATTACH_FS */
6259 bp += sizeof(bit32) /* i.e. 4 */ ;
6261 /* No bit map entry--must grow bitmap */
6263 realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
6264 osi_Assert(bp != NULL);
6266 bp += index->bitmapSize;
6267 memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
6268 index->bitmapOffset = index->bitmapSize;
6269 index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
6271 ret = index->bitmapOffset * 8;
6272 #ifdef AFS_DEMAND_ATTACH_FS
6274 #endif /* AFS_DEMAND_ATTACH_FS */
6277 #ifdef AFS_DEMAND_ATTACH_FS
6278 VChangeState_r(vp, state_save);
6279 if (flags & VOL_ALLOC_BITMAP_WAIT) {
6280 VCancelReservation_r(vp);
6282 #endif /* AFS_DEMAND_ATTACH_FS */
6287 VAllocBitmapEntry(Error * ec, Volume * vp, struct vnodeIndex * index)
6291 retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
6297 VFreeBitMapEntry_r(Error * ec, Volume *vp, struct vnodeIndex *index,
6298 unsigned bitNumber, int flags)
6300 unsigned int offset;
6304 #ifdef AFS_DEMAND_ATTACH_FS
6305 if (flags & VOL_FREE_BITMAP_WAIT) {
6306 /* VAllocBitmapEntry_r allocs bitmap entries under an exclusive volume
6307 * state, so ensure we're not in an exclusive volume state when we update
6309 VCreateReservation_r(vp);
6310 VWaitExclusiveState_r(vp);
6317 #endif /* BITMAP_LATER */
6319 offset = bitNumber >> 3;
6320 if (offset >= index->bitmapSize) {
6324 if (offset < index->bitmapOffset)
6325 index->bitmapOffset = offset & ~3; /* Truncate to nearest bit32 */
6326 *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
6329 #ifdef AFS_DEMAND_ATTACH_FS
6330 VCancelReservation_r(vp);
6332 return; /* make the compiler happy for non-DAFS */
6336 VFreeBitMapEntry(Error * ec, Volume *vp, struct vnodeIndex *index,
6340 VFreeBitMapEntry_r(ec, vp, index, bitNumber, VOL_FREE_BITMAP_WAIT);
6344 /* this function will drop the glock internally.
6345 * for old pthread fileservers, this is safe thanks to vbusy.
6347 * for demand attach fs, caller must have already called
6348 * VCreateReservation_r and VWaitExclusiveState_r */
6350 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
6352 StreamHandle_t *file;
6353 afs_sfsize_t nVnodes, size;
6354 struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
6355 struct vnodeIndex *vip = &vp->vnodeIndex[class];
6356 struct VnodeDiskObject *vnode;
6357 unsigned int unique = 0;
6361 #endif /* BITMAP_LATER */
6362 #ifdef AFS_DEMAND_ATTACH_FS
6363 VolState state_save;
6364 #endif /* AFS_DEMAND_ATTACH_FS */
6368 #ifdef AFS_DEMAND_ATTACH_FS
6369 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6370 #endif /* AFS_DEMAND_ATTACH_FS */
6373 fdP = IH_OPEN(vip->handle);
6374 osi_Assert(fdP != NULL);
6375 file = FDH_FDOPEN(fdP, "r");
6376 osi_Assert(file != NULL);
6377 vnode = (VnodeDiskObject *) malloc(vcp->diskSize);
6378 osi_Assert(vnode != NULL);
6379 size = OS_SIZE(fdP->fd_fd);
6380 osi_Assert(size != -1);
6381 nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
6383 vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4; /* The 10 is a little extra so
6384 * a few files can be created in this volume,
6385 * the whole thing is rounded up to nearest 4
6386 * bytes, because the bit map allocator likes
6389 BitMap = (byte *) calloc(1, vip->bitmapSize);
6390 osi_Assert(BitMap != NULL);
6391 #else /* BITMAP_LATER */
6392 vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
6393 osi_Assert(vip->bitmap != NULL);
6394 vip->bitmapOffset = 0;
6395 #endif /* BITMAP_LATER */
6396 if (STREAM_ASEEK(file, vcp->diskSize) != -1) {
6398 for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
6399 if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
6401 if (vnode->type != vNull) {
6402 if (vnode->vnodeMagic != vcp->magic) {
6403 Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
6408 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6409 #else /* BITMAP_LATER */
6410 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6411 #endif /* BITMAP_LATER */
6412 if (unique <= vnode->uniquifier)
6413 unique = vnode->uniquifier + 1;
6415 #ifndef AFS_PTHREAD_ENV
6416 if ((bitNumber & 0x00ff) == 0x0ff) { /* every 256 iterations */
6419 #endif /* !AFS_PTHREAD_ENV */
6422 if (vp->nextVnodeUnique < unique) {
6423 Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
6426 /* Paranoia, partly justified--I think fclose after fdopen
6427 * doesn't seem to close fd. In any event, the documentation
6428 * doesn't specify, so it's safer to close it twice.
6436 /* There may have been a racing condition with some other thread, both
6437 * creating the bitmaps for this volume. If the other thread was faster
6438 * the pointer to bitmap should already be filled and we can free ours.
6440 if (vip->bitmap == NULL) {
6441 vip->bitmap = BitMap;
6442 vip->bitmapOffset = 0;
6444 free((byte *) BitMap);
6445 #endif /* BITMAP_LATER */
6446 #ifdef AFS_DEMAND_ATTACH_FS
6447 VChangeState_r(vp, state_save);
6448 #endif /* AFS_DEMAND_ATTACH_FS */
6452 /***************************************************/
6453 /* Volume Path and Volume Number utility routines */
6454 /***************************************************/
6457 * find the first occurrence of a volume header file and return the path.
6459 * @param[out] ec outbound error code
6460 * @param[in] volumeId volume id to find
6461 * @param[out] partitionp pointer to disk partition path string
6462 * @param[out] namep pointer to volume header file name string
6464 * @post path to first occurrence of volume header is returned in partitionp
6465 * and namep, or ec is set accordingly.
6467 * @warning this function is NOT re-entrant -- partitionp and namep point to
6468 * static data segments
6470 * @note if a volume utility inadvertently leaves behind a stale volume header
6471 * on a vice partition, it is possible for callers to get the wrong one,
6472 * depending on the order of the disk partition linked list.
6476 VGetVolumePath(Error * ec, VolId volumeId, char **partitionp, char **namep)
6478 static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
6479 char path[VMAXPATHLEN];
6481 struct DiskPartition64 *dp;
6484 name[0] = OS_DIRSEPC;
6485 snprintf(&name[1], (sizeof name) - 1, VFORMAT,
6486 afs_printable_uint32_lu(volumeId));
6487 for (dp = DiskPartitionList; dp; dp = dp->next) {
6488 struct afs_stat_st status;
6489 strcpy(path, VPartitionPath(dp));
6491 if (afs_stat(path, &status) == 0) {
6492 strcpy(partition, dp->name);
6499 *partitionp = *namep = NULL;
6501 *partitionp = partition;
6507 * extract a volume number from a volume header filename string.
6509 * @param[in] name volume header filename string
6511 * @return volume number
6513 * @note the string must be of the form VFORMAT. the only permissible
6514 * deviation is a leading OS_DIRSEPC character.
6519 VolumeNumber(char *name)
6521 if (*name == OS_DIRSEPC)
6523 return strtoul(name + 1, NULL, 10);
6527 * compute the volume header filename.
6529 * @param[in] volumeId
6531 * @return volume header filename
6533 * @post volume header filename string is constructed
6535 * @warning this function is NOT re-entrant -- the returned string is
6536 * stored in a static char array. see VolumeExternalName_r
6537 * for a re-entrant equivalent.
6539 * @see VolumeExternalName_r
6541 * @deprecated due to the above re-entrancy warning, this interface should
6542 * be considered deprecated. Please use VolumeExternalName_r
6546 VolumeExternalName(VolumeId volumeId)
6548 static char name[VMAXPATHLEN];
6549 snprintf(name, sizeof name, VFORMAT, afs_printable_uint32_lu(volumeId));
6554 * compute the volume header filename.
6556 * @param[in] volumeId
6557 * @param[inout] name array in which to store filename
6558 * @param[in] len length of name array
6560 * @return result code from afs_snprintf
6562 * @see VolumeExternalName
6565 * @note re-entrant equivalent of VolumeExternalName
6568 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
6570 return snprintf(name, len, VFORMAT, afs_printable_uint32_lu(volumeId));
6574 /***************************************************/
6575 /* Volume Usage Statistics routines */
6576 /***************************************************/
6578 #if OPENAFS_VOL_STATS
6579 #define OneDay (86400) /* 24 hours' worth of seconds */
6581 #define OneDay (24*60*60) /* 24 hours */
6582 #endif /* OPENAFS_VOL_STATS */
6585 Midnight(time_t t) {
6586 struct tm local, *l;
6589 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
6590 l = localtime_r(&t, &local);
6596 /* the following is strictly speaking problematic on the
6597 switching day to daylight saving time, after the switch,
6598 as tm_isdst does not match. Similarly, on the looong day when
6599 switching back the OneDay check will not do what naively expected!
6600 The effects are minor, though, and more a matter of interpreting
6602 #ifndef AFS_PTHREAD_ENV
6605 local.tm_hour = local.tm_min=local.tm_sec = 0;
6606 midnight = mktime(&local);
6607 if (midnight != (time_t) -1) return(midnight);
6609 return( (t/OneDay)*OneDay );
6613 /*------------------------------------------------------------------------
6614 * [export] VAdjustVolumeStatistics
6617 * If we've passed midnight, we need to update all the day use
6618 * statistics as well as zeroing the detailed volume statistics
6619 * (if we are implementing them).
6622 * vp : Pointer to the volume structure describing the lucky
6623 * volume being considered for update.
6629 * Nothing interesting.
6633 *------------------------------------------------------------------------*/
6636 VAdjustVolumeStatistics_r(Volume * vp)
6638 unsigned int now = FT_ApproxTime();
6640 if (now - V_dayUseDate(vp) > OneDay) {
6643 ndays = (now - V_dayUseDate(vp)) / OneDay;
6644 for (i = 6; i > ndays - 1; i--)
6645 V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
6646 for (i = 0; i < ndays - 1 && i < 7; i++)
6647 V_weekUse(vp)[i] = 0;
6649 V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
6651 V_dayUseDate(vp) = Midnight(now);
6653 #if OPENAFS_VOL_STATS
6655 * All we need to do is bzero the entire VOL_STATS_BYTES of
6656 * the detailed volume statistics area.
6658 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
6659 #endif /* OPENAFS_VOL_STATS */
6662 /*It's been more than a day of collection */
6664 * Always return happily.
6667 } /*VAdjustVolumeStatistics */
6670 VAdjustVolumeStatistics(Volume * vp)
6674 retVal = VAdjustVolumeStatistics_r(vp);
6680 VBumpVolumeUsage_r(Volume * vp)
6682 unsigned int now = FT_ApproxTime();
6683 V_accessDate(vp) = now;
6684 if (now - V_dayUseDate(vp) > OneDay)
6685 VAdjustVolumeStatistics_r(vp);
6687 * Save the volume header image to disk after every 128 bumps to dayUse.
6689 if ((V_dayUse(vp)++ & 127) == 0) {
6691 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
6696 VBumpVolumeUsage(Volume * vp)
6699 VBumpVolumeUsage_r(vp);
6704 VSetDiskUsage_r(void)
6706 #ifndef AFS_DEMAND_ATTACH_FS
6707 static int FifteenMinuteCounter = 0;
6711 /* NOTE: Don't attempt to access the partitions list until the
6712 * initialization level indicates that all volumes are attached,
6713 * which implies that all partitions are initialized. */
6714 #ifdef AFS_PTHREAD_ENV
6715 VOL_CV_WAIT(&vol_vinit_cond);
6716 #else /* AFS_PTHREAD_ENV */
6718 #endif /* AFS_PTHREAD_ENV */
6721 VResetDiskUsage_r();
6723 #ifndef AFS_DEMAND_ATTACH_FS
6724 if (++FifteenMinuteCounter == 3) {
6725 FifteenMinuteCounter = 0;
6728 #endif /* !AFS_DEMAND_ATTACH_FS */
6740 /***************************************************/
6741 /* Volume Update List routines */
6742 /***************************************************/
6744 /* The number of minutes that a volume hasn't been updated before the
6745 * "Dont salvage" flag in the volume header will be turned on */
6746 #define SALVAGE_INTERVAL (10*60)
6751 * volume update list functionality has been moved into the VLRU
6752 * the DONT_SALVAGE flag is now set during VLRU demotion
6755 #ifndef AFS_DEMAND_ATTACH_FS
6756 static VolumeId *UpdateList = NULL; /* Pointer to array of Volume ID's */
6757 static int nUpdatedVolumes = 0; /* Updated with entry in UpdateList, salvage after crash flag on */
6758 static int updateSize = 0; /* number of entries possible */
6759 #define UPDATE_LIST_SIZE 128 /* initial size increment (must be a power of 2!) */
6760 #endif /* !AFS_DEMAND_ATTACH_FS */
6763 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
6766 vp->updateTime = FT_ApproxTime();
6767 if (V_dontSalvage(vp) == 0)
6769 V_dontSalvage(vp) = 0;
6770 VSyncVolume_r(ec, vp, 0);
6771 #ifdef AFS_DEMAND_ATTACH_FS
6772 V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
6773 #else /* !AFS_DEMAND_ATTACH_FS */
6776 if (UpdateList == NULL) {
6777 updateSize = UPDATE_LIST_SIZE;
6778 UpdateList = (VolumeId *) malloc(sizeof(VolumeId) * updateSize);
6780 if (nUpdatedVolumes == updateSize) {
6782 if (updateSize > 524288) {
6783 Log("warning: there is likely a bug in the volume update scanner\n");
6787 (VolumeId *) realloc(UpdateList,
6788 sizeof(VolumeId) * updateSize);
6791 osi_Assert(UpdateList != NULL);
6792 UpdateList[nUpdatedVolumes++] = V_id(vp);
6793 #endif /* !AFS_DEMAND_ATTACH_FS */
6796 #ifndef AFS_DEMAND_ATTACH_FS
6798 VScanUpdateList(void)
6803 afs_uint32 now = FT_ApproxTime();
6804 /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
6805 for (i = gap = 0; i < nUpdatedVolumes; i++) {
6807 UpdateList[i - gap] = UpdateList[i];
6809 /* XXX this routine needlessly messes up the Volume LRU by
6810 * breaking the LRU temporal-locality assumptions.....
6811 * we should use a special volume header allocator here */
6812 vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
6815 } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
6816 V_dontSalvage(vp) = DONT_SALVAGE;
6817 VUpdateVolume_r(&error, vp, 0); /* No need to fsync--not critical */
6825 #ifndef AFS_PTHREAD_ENV
6827 #endif /* !AFS_PTHREAD_ENV */
6829 nUpdatedVolumes -= gap;
6831 #endif /* !AFS_DEMAND_ATTACH_FS */
6834 /***************************************************/
6835 /* Volume LRU routines */
6836 /***************************************************/
6841 * with demand attach fs, we attempt to soft detach(1)
6842 * volumes which have not been accessed in a long time
6843 * in order to speed up fileserver shutdown
6845 * (1) by soft detach we mean a process very similar
6846 * to VOffline, except the final state of the
6847 * Volume will be VOL_STATE_PREATTACHED, instead
6848 * of the usual VOL_STATE_UNATTACHED
6850 #ifdef AFS_DEMAND_ATTACH_FS
6852 /* implementation is reminiscent of a generational GC
6854 * queue 0 is newly attached volumes. this queue is
6855 * sorted by attach timestamp
6857 * queue 1 is volumes that have been around a bit
6858 * longer than queue 0. this queue is sorted by
6861 * queue 2 is volumes tha have been around the longest.
6862 * this queue is unsorted
6864 * queue 3 is volumes that have been marked as
6865 * candidates for soft detachment. this queue is
6868 #define VLRU_GENERATIONS 3 /**< number of generations in VLRU */
6869 #define VLRU_QUEUES 5 /**< total number of VLRU queues */
6872 * definition of a VLRU queue.
6875 volatile struct rx_queue q;
6882 * main VLRU data structure.
6885 struct VLRU_q q[VLRU_QUEUES]; /**< VLRU queues */
6888 /** time interval (in seconds) between promotion passes for
6889 * each young generation queue. */
6890 afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
6892 /** time interval (in seconds) between soft detach candidate
6893 * scans for each generation queue.
6895 * scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
6896 * we perform a soft detach pass. */
6897 afs_uint32 scan_interval[VLRU_GENERATIONS+1];
6899 /* scheduler state */
6900 int next_idx; /**< next queue to receive attention */
6901 afs_uint32 last_promotion[VLRU_GENERATIONS-1]; /**< timestamp of last promotion scan */
6902 afs_uint32 last_scan[VLRU_GENERATIONS+1]; /**< timestamp of last detach scan */
6904 int scanner_state; /**< state of scanner thread */
6905 pthread_cond_t cv; /**< state transition CV */
6908 /** global VLRU state */
6909 static struct VLRU volume_LRU;
6912 * defined states for VLRU scanner thread.
6915 VLRU_SCANNER_STATE_OFFLINE = 0, /**< vlru scanner thread is offline */
6916 VLRU_SCANNER_STATE_ONLINE = 1, /**< vlru scanner thread is online */
6917 VLRU_SCANNER_STATE_SHUTTING_DOWN = 2, /**< vlru scanner thread is shutting down */
6918 VLRU_SCANNER_STATE_PAUSING = 3, /**< vlru scanner thread is getting ready to pause */
6919 VLRU_SCANNER_STATE_PAUSED = 4 /**< vlru scanner thread is paused */
6920 } vlru_thread_state_t;
6922 /* vlru disk data header stuff */
6923 #define VLRU_DISK_MAGIC 0x7a8b9cad /**< vlru disk entry magic number */
6924 #define VLRU_DISK_VERSION 1 /**< vlru disk entry version number */
6926 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
6927 #define VLRU_DUMP_EXPIRATION_TIME (60*60*24*7) /* expire vlru data after 1 week */
6930 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
6931 * soft detachment. */
6932 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
6934 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
6935 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
6937 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
6938 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
6940 /** VLRU control flag. non-zero value implies VLRU subsystem is activated. */
6941 static afs_uint32 VLRU_enabled = 1;
6943 /* queue synchronization routines */
6944 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
6945 static void VLRU_EndExclusive_r(struct VLRU_q * q);
6946 static void VLRU_Wait_r(struct VLRU_q * q);
6949 * set VLRU subsystem tunable parameters.
6951 * @param[in] option tunable option to modify
6952 * @param[in] val new value for tunable parameter
6954 * @pre @c VInitVolumePackage2 has not yet been called.
6956 * @post tunable parameter is modified
6960 * @note valid option parameters are:
6961 * @arg @c VLRU_SET_THRESH
6962 * set the period of inactivity after which
6963 * volumes are eligible for soft detachment
6964 * @arg @c VLRU_SET_INTERVAL
6965 * set the time interval between calls
6966 * to the volume LRU "garbage collector"
6967 * @arg @c VLRU_SET_MAX
6968 * set the max number of volumes to deallocate
6972 VLRU_SetOptions(int option, afs_uint32 val)
6974 if (option == VLRU_SET_THRESH) {
6975 VLRU_offline_thresh = val;
6976 } else if (option == VLRU_SET_INTERVAL) {
6977 VLRU_offline_interval = val;
6978 } else if (option == VLRU_SET_MAX) {
6979 VLRU_offline_max = val;
6980 } else if (option == VLRU_SET_ENABLED) {
6983 VLRU_ComputeConstants();
6987 * compute VLRU internal timing parameters.
6989 * @post VLRU scanner thread internal timing parameters are computed
6991 * @note computes internal timing parameters based upon user-modifiable
6992 * tunable parameters.
6996 * @internal volume package internal use only.
6999 VLRU_ComputeConstants(void)
7001 afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
7003 /* compute the candidate scan interval */
7004 volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
7006 /* compute the promotion intervals */
7007 volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
7008 volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
7011 /* compute the gen 0 scan interval */
7012 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
7014 /* compute the gen 0 scan interval */
7015 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
7020 * initialize VLRU subsystem.
7022 * @pre this function has not yet been called
7024 * @post VLRU subsystem is initialized and VLRU scanner thread is starting
7028 * @internal volume package internal use only.
7034 pthread_attr_t attrs;
7037 if (!VLRU_enabled) {
7038 Log("VLRU: disabled\n");
7042 /* initialize each of the VLRU queues */
7043 for (i = 0; i < VLRU_QUEUES; i++) {
7044 queue_Init(&volume_LRU.q[i]);
7045 volume_LRU.q[i].len = 0;
7046 volume_LRU.q[i].busy = 0;
7047 CV_INIT(&volume_LRU.q[i].cv, "vol lru", CV_DEFAULT, 0);
7050 /* setup the timing constants */
7051 VLRU_ComputeConstants();
7053 /* XXX put inside LogLevel check? */
7054 Log("VLRU: starting scanner with the following configuration parameters:\n");
7055 Log("VLRU: offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
7056 Log("VLRU: running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
7057 Log("VLRU: taking up to %d volumes offline per pass\n", VLRU_offline_max);
7058 Log("VLRU: scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
7059 Log("VLRU: scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
7060 Log("VLRU: scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
7062 /* start up the VLRU scanner */
7063 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7064 if (programType == fileServer) {
7065 CV_INIT(&volume_LRU.cv, "vol lru", CV_DEFAULT, 0);
7066 osi_Assert(pthread_attr_init(&attrs) == 0);
7067 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
7068 osi_Assert(pthread_create(&tid, &attrs, &VLRU_ScannerThread, NULL) == 0);
7073 * initialize the VLRU-related fields of a newly allocated volume object.
7075 * @param[in] vp pointer to volume object
7078 * @arg @c VOL_LOCK is held.
7079 * @arg volume object is not on a VLRU queue.
7081 * @post VLRU fields are initialized to indicate that volume object is not
7082 * currently registered with the VLRU subsystem
7086 * @internal volume package interal use only.
7089 VLRU_Init_Node_r(Volume * vp)
7094 osi_Assert(queue_IsNotOnQueue(&vp->vlru));
7095 vp->vlru.idx = VLRU_QUEUE_INVALID;
7099 * add a volume object to a VLRU queue.
7101 * @param[in] vp pointer to volume object
7104 * @arg @c VOL_LOCK is held.
7105 * @arg caller MUST hold a lightweight ref on @p vp.
7106 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7108 * @post the volume object is added to the appropriate VLRU queue
7110 * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
7111 * then the volume is added to that queue. Otherwise, the value
7112 * @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
7113 * volume is added to the NEW generation queue.
7115 * @note @c VOL_LOCK may be dropped internally
7117 * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
7118 * during the add operation, and is restored to the previous
7119 * state prior to return.
7123 * @internal volume package internal use only.
7126 VLRU_Add_r(Volume * vp)
7129 VolState state_save;
7134 if (queue_IsOnQueue(&vp->vlru))
7137 state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
7140 if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
7141 idx = VLRU_QUEUE_NEW;
7144 VLRU_Wait_r(&volume_LRU.q[idx]);
7146 /* repeat check since VLRU_Wait_r may have dropped
7148 if (queue_IsNotOnQueue(&vp->vlru)) {
7150 queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
7151 volume_LRU.q[idx].len++;
7152 V_attachFlags(vp) |= VOL_ON_VLRU;
7153 vp->stats.last_promote = FT_ApproxTime();
7156 VChangeState_r(vp, state_save);
7160 * delete a volume object from a VLRU queue.
7162 * @param[in] vp pointer to volume object
7165 * @arg @c VOL_LOCK is held.
7166 * @arg caller MUST hold a lightweight ref on @p vp.
7167 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7169 * @post volume object is removed from the VLRU queue
7171 * @note @c VOL_LOCK may be dropped internally
7175 * @todo We should probably set volume state to something exlcusive
7176 * (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
7178 * @internal volume package internal use only.
7181 VLRU_Delete_r(Volume * vp)
7188 if (queue_IsNotOnQueue(&vp->vlru))
7194 if (idx == VLRU_QUEUE_INVALID)
7196 VLRU_Wait_r(&volume_LRU.q[idx]);
7197 } while (idx != vp->vlru.idx);
7199 /* now remove from the VLRU and update
7200 * the appropriate counter */
7201 queue_Remove(&vp->vlru);
7202 volume_LRU.q[idx].len--;
7203 vp->vlru.idx = VLRU_QUEUE_INVALID;
7204 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7208 * tell the VLRU subsystem that a volume was just accessed.
7210 * @param[in] vp pointer to volume object
7213 * @arg @c VOL_LOCK is held
7214 * @arg caller MUST hold a lightweight ref on @p vp
7215 * @arg caller MUST NOT hold exclusive ownership of any VLRU queue
7217 * @post volume VLRU access statistics are updated. If the volume was on
7218 * the VLRU soft detach candidate queue, it is moved to the NEW
7221 * @note @c VOL_LOCK may be dropped internally
7225 * @internal volume package internal use only.
7228 VLRU_UpdateAccess_r(Volume * vp)
7230 Volume * rvp = NULL;
7235 if (queue_IsNotOnQueue(&vp->vlru))
7238 osi_Assert(V_attachFlags(vp) & VOL_ON_VLRU);
7240 /* update the access timestamp */
7241 vp->stats.last_get = FT_ApproxTime();
7244 * if the volume is on the soft detach candidate
7245 * list, we need to safely move it back to a
7246 * regular generation. this has to be done
7247 * carefully so we don't race against the scanner
7251 /* if this volume is on the soft detach candidate queue,
7252 * then grab exclusive access to the necessary queues */
7253 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7255 VCreateReservation_r(rvp);
7257 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7258 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7259 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7260 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7263 /* make sure multiple threads don't race to update */
7264 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7265 VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
7269 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7270 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7271 VCancelReservation_r(rvp);
7276 * switch a volume between two VLRU queues.
7278 * @param[in] vp pointer to volume object
7279 * @param[in] new_idx index of VLRU queue onto which the volume will be moved
7280 * @param[in] append controls whether the volume will be appended or
7281 * prepended to the queue. A nonzero value means it will
7282 * be appended; zero means it will be prepended.
7284 * @pre The new (and old, if applicable) queue(s) must either be owned
7285 * exclusively by the calling thread for asynchronous manipulation,
7286 * or the queue(s) must be quiescent and VOL_LOCK must be held.
7287 * Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
7288 * for further details of the queue asynchronous processing mechanism.
7290 * @post If the volume object was already on a VLRU queue, it is
7291 * removed from the queue. Depending on the value of the append
7292 * parameter, the volume object is either appended or prepended
7293 * to the VLRU queue referenced by the new_idx parameter.
7297 * @see VLRU_BeginExclusive_r
7298 * @see VLRU_EndExclusive_r
7301 * @internal volume package internal use only.
7304 VLRU_SwitchQueues(Volume * vp, int new_idx, int append)
7306 if (queue_IsNotOnQueue(&vp->vlru))
7309 queue_Remove(&vp->vlru);
7310 volume_LRU.q[vp->vlru.idx].len--;
7312 /* put the volume back on the correct generational queue */
7314 queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
7316 queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
7319 volume_LRU.q[new_idx].len++;
7320 vp->vlru.idx = new_idx;
7324 * VLRU background thread.
7326 * The VLRU Scanner Thread is responsible for periodically scanning through
7327 * each VLRU queue looking for volumes which should be moved to another
7328 * queue, or soft detached.
7330 * @param[in] args unused thread arguments parameter
7332 * @return unused thread return value
7333 * @retval NULL always
7335 * @internal volume package internal use only.
7338 VLRU_ScannerThread(void * args)
7340 afs_uint32 now, min_delay, delay;
7341 int i, min_idx, min_op, overdue, state;
7343 /* set t=0 for promotion cycle to be
7344 * fileserver startup */
7345 now = FT_ApproxTime();
7346 for (i=0; i < VLRU_GENERATIONS-1; i++) {
7347 volume_LRU.last_promotion[i] = now;
7350 /* don't start the scanner until VLRU_offline_thresh
7351 * plus a small delay for VInitVolumePackage2 to finish
7354 sleep(VLRU_offline_thresh + 60);
7356 /* set t=0 for scan cycle to be now */
7357 now = FT_ApproxTime();
7358 for (i=0; i < VLRU_GENERATIONS+1; i++) {
7359 volume_LRU.last_scan[i] = now;
7363 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
7364 volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
7367 while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
7368 /* check to see if we've been asked to pause */
7369 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
7370 volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
7371 CV_BROADCAST(&volume_LRU.cv);
7373 VOL_CV_WAIT(&volume_LRU.cv);
7374 } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
7377 /* scheduling can happen outside the glock */
7380 /* figure out what is next on the schedule */
7382 /* figure out a potential schedule for the new generation first */
7384 min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
7387 if (min_delay > volume_LRU.scan_interval[0]) {
7388 /* unsigned overflow -- we're overdue to run this scan */
7393 /* if we're not overdue for gen 0, figure out schedule for candidate gen */
7395 i = VLRU_QUEUE_CANDIDATE;
7396 delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
7397 if (delay < min_delay) {
7401 if (delay > volume_LRU.scan_interval[i]) {
7402 /* unsigned overflow -- we're overdue to run this scan */
7409 /* if we're still not overdue for something, figure out schedules for promotions */
7410 for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
7411 delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
7412 if (delay < min_delay) {
7417 if (delay > volume_LRU.promotion_interval[i]) {
7418 /* unsigned overflow -- we're overdue to run this promotion */
7427 /* sleep as needed */
7432 /* do whatever is next */
7435 VLRU_Promote_r(min_idx);
7436 VLRU_Demote_r(min_idx+1);
7438 VLRU_Scan_r(min_idx);
7440 now = FT_ApproxTime();
7443 Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
7445 /* signal that scanner is down */
7446 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7447 CV_BROADCAST(&volume_LRU.cv);
7453 * promote volumes from one VLRU generation to the next.
7455 * This routine scans a VLRU generation looking for volumes which are
7456 * eligible to be promoted to the next generation. All volumes which
7457 * meet the eligibility requirement are promoted.
7459 * Promotion eligibility is based upon meeting both of the following
7462 * @arg The volume has been accessed since the last promotion:
7463 * @c (vp->stats.last_get >= vp->stats.last_promote)
7464 * @arg The last promotion occurred at least
7465 * @c volume_LRU.promotion_interval[idx] seconds ago
7467 * As a performance optimization, promotions are "globbed". In other
7468 * words, we promote arbitrarily large contiguous sublists of elements
7471 * @param[in] idx VLRU queue index to scan
7475 * @internal VLRU internal use only.
7478 VLRU_Promote_r(int idx)
7480 int len, chaining, promote;
7481 afs_uint32 now, thresh;
7482 struct rx_queue *qp, *nqp;
7483 Volume * vp, *start = NULL, *end = NULL;
7485 /* get exclusive access to two chains, and drop the glock */
7486 VLRU_Wait_r(&volume_LRU.q[idx]);
7487 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7488 VLRU_Wait_r(&volume_LRU.q[idx+1]);
7489 VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
7492 thresh = volume_LRU.promotion_interval[idx];
7493 now = FT_ApproxTime();
7496 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7497 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7498 promote = (((vp->stats.last_promote + thresh) <= now) &&
7499 (vp->stats.last_get >= vp->stats.last_promote));
7507 /* promote and prepend chain */
7508 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7522 /* promote and prepend */
7523 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7527 volume_LRU.q[idx].len -= len;
7528 volume_LRU.q[idx+1].len += len;
7531 /* release exclusive access to the two chains */
7533 volume_LRU.last_promotion[idx] = now;
7534 VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
7535 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7538 /* run the demotions */
7540 VLRU_Demote_r(int idx)
7543 int len, chaining, demote;
7544 afs_uint32 now, thresh;
7545 struct rx_queue *qp, *nqp;
7546 Volume * vp, *start = NULL, *end = NULL;
7547 Volume ** salv_flag_vec = NULL;
7548 int salv_vec_offset = 0;
7550 osi_Assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
7552 /* get exclusive access to two chains, and drop the glock */
7553 VLRU_Wait_r(&volume_LRU.q[idx-1]);
7554 VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
7555 VLRU_Wait_r(&volume_LRU.q[idx]);
7556 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7559 /* no big deal if this allocation fails */
7560 if (volume_LRU.q[idx].len) {
7561 salv_flag_vec = (Volume **) malloc(volume_LRU.q[idx].len * sizeof(Volume *));
7564 now = FT_ApproxTime();
7565 thresh = volume_LRU.promotion_interval[idx-1];
7568 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7569 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7570 demote = (((vp->stats.last_promote + thresh) <= now) &&
7571 (vp->stats.last_get < (now - thresh)));
7573 /* we now do volume update list DONT_SALVAGE flag setting during
7574 * demotion passes */
7575 if (salv_flag_vec &&
7576 !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7578 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7579 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7580 salv_flag_vec[salv_vec_offset++] = vp;
7581 VCreateReservation_r(vp);
7590 /* demote and append chain */
7591 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7605 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7609 volume_LRU.q[idx].len -= len;
7610 volume_LRU.q[idx-1].len += len;
7613 /* release exclusive access to the two chains */
7615 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7616 VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
7618 /* now go back and set the DONT_SALVAGE flags as appropriate */
7619 if (salv_flag_vec) {
7621 for (i = 0; i < salv_vec_offset; i++) {
7622 vp = salv_flag_vec[i];
7623 if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7624 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7625 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7628 V_attachFlags(vp) |= VOL_HDR_DONTSALV;
7629 V_dontSalvage(vp) = DONT_SALVAGE;
7630 VUpdateVolume_r(&ec, vp, 0);
7634 VCancelReservation_r(vp);
7636 free(salv_flag_vec);
7640 /* run a pass of the VLRU GC scanner */
7642 VLRU_Scan_r(int idx)
7644 afs_uint32 now, thresh;
7645 struct rx_queue *qp, *nqp;
7649 osi_Assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
7651 /* gain exclusive access to the idx VLRU */
7652 VLRU_Wait_r(&volume_LRU.q[idx]);
7653 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7655 if (idx != VLRU_QUEUE_CANDIDATE) {
7656 /* gain exclusive access to the candidate VLRU */
7657 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7658 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7661 now = FT_ApproxTime();
7662 thresh = now - VLRU_offline_thresh;
7664 /* perform candidate selection and soft detaching */
7665 if (idx == VLRU_QUEUE_CANDIDATE) {
7666 /* soft detach some volumes from the candidate pool */
7670 for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7671 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7672 if (i >= VLRU_offline_max) {
7675 /* check timestamp to see if it's a candidate for soft detaching */
7676 if (vp->stats.last_get <= thresh) {
7678 if (VCheckSoftDetach(vp, thresh))
7684 /* scan for volumes to become soft detach candidates */
7685 for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
7686 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7688 /* check timestamp to see if it's a candidate for soft detaching */
7689 if (vp->stats.last_get <= thresh) {
7690 VCheckSoftDetachCandidate(vp, thresh);
7693 if (!(i&0x7f)) { /* lock coarsening optimization */
7701 /* relinquish exclusive access to the VLRU chains */
7705 volume_LRU.last_scan[idx] = now;
7706 if (idx != VLRU_QUEUE_CANDIDATE) {
7707 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7709 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7712 /* check whether volume is safe to soft detach
7713 * caller MUST NOT hold a ref count on vp */
7715 VCheckSoftDetach(Volume * vp, afs_uint32 thresh)
7719 if (vp->nUsers || vp->nWaiters)
7722 if (vp->stats.last_get <= thresh) {
7723 ret = VSoftDetachVolume_r(vp, thresh);
7729 /* check whether volume should be made a
7730 * soft detach candidate */
7732 VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh)
7735 if (vp->nUsers || vp->nWaiters)
7740 osi_Assert(idx == VLRU_QUEUE_NEW);
7742 if (vp->stats.last_get <= thresh) {
7743 /* move to candidate pool */
7744 queue_Remove(&vp->vlru);
7745 volume_LRU.q[VLRU_QUEUE_NEW].len--;
7746 queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
7747 vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
7748 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
7756 /* begin exclusive access on VLRU */
7758 VLRU_BeginExclusive_r(struct VLRU_q * q)
7760 osi_Assert(q->busy == 0);
7764 /* end exclusive access on VLRU */
7766 VLRU_EndExclusive_r(struct VLRU_q * q)
7768 osi_Assert(q->busy);
7770 CV_BROADCAST(&q->cv);
7773 /* wait for another thread to end exclusive access on VLRU */
7775 VLRU_Wait_r(struct VLRU_q * q)
7778 VOL_CV_WAIT(&q->cv);
7783 * volume soft detach
7785 * caller MUST NOT hold a ref count on vp */
7787 VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh)
7792 osi_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7794 ts_save = vp->stats.last_get;
7795 if (ts_save > thresh)
7798 if (vp->nUsers || vp->nWaiters)
7801 if (VIsExclusiveState(V_attachState(vp))) {
7805 switch (V_attachState(vp)) {
7806 case VOL_STATE_UNATTACHED:
7807 case VOL_STATE_PREATTACHED:
7808 case VOL_STATE_ERROR:
7809 case VOL_STATE_GOING_OFFLINE:
7810 case VOL_STATE_SHUTTING_DOWN:
7811 case VOL_STATE_SALVAGING:
7812 case VOL_STATE_DELETED:
7813 volume_LRU.q[vp->vlru.idx].len--;
7815 /* create and cancel a reservation to
7816 * give the volume an opportunity to
7818 VCreateReservation_r(vp);
7819 queue_Remove(&vp->vlru);
7820 vp->vlru.idx = VLRU_QUEUE_INVALID;
7821 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7822 VCancelReservation_r(vp);
7828 /* hold the volume and take it offline.
7829 * no need for reservations, as VHold_r
7830 * takes care of that internally. */
7831 if (VHold_r(vp) == 0) {
7832 /* vhold drops the glock, so now we should
7833 * check to make sure we aren't racing against
7834 * other threads. if we are racing, offlining vp
7835 * would be wasteful, and block the scanner for a while
7839 (vp->shuttingDown) ||
7840 (vp->goingOffline) ||
7841 (vp->stats.last_get != ts_save)) {
7842 /* looks like we're racing someone else. bail */
7846 /* pull it off the VLRU */
7847 osi_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7848 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
7849 queue_Remove(&vp->vlru);
7850 vp->vlru.idx = VLRU_QUEUE_INVALID;
7851 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7853 /* take if offline */
7854 VOffline_r(vp, "volume has been soft detached");
7856 /* invalidate the volume header cache */
7857 FreeVolumeHeader(vp);
7860 IncUInt64(&VStats.soft_detaches);
7861 vp->stats.soft_detaches++;
7863 /* put in pre-attached state so demand
7864 * attacher can work on it */
7865 VChangeState_r(vp, VOL_STATE_PREATTACHED);
7871 #endif /* AFS_DEMAND_ATTACH_FS */
7874 /***************************************************/
7875 /* Volume Header Cache routines */
7876 /***************************************************/
7879 * volume header cache.
7881 struct volume_hdr_LRU_t volume_hdr_LRU;
7884 * initialize the volume header cache.
7886 * @param[in] howMany number of header cache entries to preallocate
7888 * @pre VOL_LOCK held. Function has never been called before.
7890 * @post howMany cache entries are allocated, initialized, and added
7891 * to the LRU list. Header cache statistics are initialized.
7893 * @note only applicable to fileServer program type. Should only be
7894 * called once during volume package initialization.
7896 * @internal volume package internal use only.
7899 VInitVolumeHeaderCache(afs_uint32 howMany)
7901 struct volHeader *hp;
7902 if (programType != fileServer)
7904 queue_Init(&volume_hdr_LRU);
7905 volume_hdr_LRU.stats.free = 0;
7906 volume_hdr_LRU.stats.used = howMany;
7907 volume_hdr_LRU.stats.attached = 0;
7908 hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
7909 osi_Assert(hp != NULL);
7912 /* We are using ReleaseVolumeHeader to initialize the values on the header list
7913 * to ensure they have the right values
7915 ReleaseVolumeHeader(hp++);
7919 * get a volume header and attach it to the volume object.
7921 * @param[in] vp pointer to volume object
7923 * @return cache entry status
7924 * @retval 0 volume header was newly attached; cache data is invalid
7925 * @retval 1 volume header was previously attached; cache data is valid
7927 * @pre VOL_LOCK held. For DAFS, lightweight ref must be held on volume object.
7929 * @post volume header attached to volume object. if necessary, header cache
7930 * entry on LRU is synchronized to disk. Header is removed from LRU list.
7932 * @note VOL_LOCK may be dropped
7934 * @warning this interface does not load header data from disk. it merely
7935 * attaches a header object to the volume object, and may sync the old
7936 * header cache data out to disk in the process.
7938 * @internal volume package internal use only.
7941 GetVolumeHeader(Volume * vp)
7944 struct volHeader *hd;
7946 static int everLogged = 0;
7948 #ifdef AFS_DEMAND_ATTACH_FS
7949 VolState vp_save = 0, back_save = 0;
7951 /* XXX debug 9/19/05 we've apparently got
7952 * a ref counting bug somewhere that's
7953 * breaking the nUsers == 0 => header on LRU
7955 if (vp->header && queue_IsNotOnQueue(vp->header)) {
7956 Log("nUsers == 0, but header not on LRU\n");
7961 old = (vp->header != NULL); /* old == volume already has a header */
7963 if (programType != fileServer) {
7964 /* for volume utilities, we allocate volHeaders as needed */
7966 hd = (struct volHeader *)calloc(1, sizeof(*vp->header));
7967 osi_Assert(hd != NULL);
7970 #ifdef AFS_DEMAND_ATTACH_FS
7971 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
7975 /* for the fileserver, we keep a volume header cache */
7977 /* the header we previously dropped in the lru is
7978 * still available. pull it off the lru and return */
7981 osi_Assert(hd->back == vp);
7982 #ifdef AFS_DEMAND_ATTACH_FS
7983 V_attachFlags(vp) &= ~(VOL_HDR_IN_LRU);
7986 /* we need to grab a new element off the LRU */
7987 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
7988 /* grab an element and pull off of LRU */
7989 hd = queue_First(&volume_hdr_LRU, volHeader);
7992 /* LRU is empty, so allocate a new volHeader
7993 * this is probably indicative of a leak, so let the user know */
7994 hd = (struct volHeader *)calloc(1, sizeof(struct volHeader));
7995 osi_Assert(hd != NULL);
7997 Log("****Allocated more volume headers, probably leak****\n");
8000 volume_hdr_LRU.stats.free++;
8003 /* this header used to belong to someone else.
8004 * we'll need to check if the header needs to
8005 * be sync'd out to disk */
8007 #ifdef AFS_DEMAND_ATTACH_FS
8008 /* if hd->back were in an exclusive state, then
8009 * its volHeader would not be on the LRU... */
8010 osi_Assert(!VIsExclusiveState(V_attachState(hd->back)));
8013 if (hd->diskstuff.inUse) {
8014 /* volume was in use, so we'll need to sync
8015 * its header to disk */
8017 #ifdef AFS_DEMAND_ATTACH_FS
8018 back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
8019 vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
8020 VCreateReservation_r(hd->back);
8024 WriteVolumeHeader_r(&error, hd->back);
8025 /* Ignore errors; catch them later */
8027 #ifdef AFS_DEMAND_ATTACH_FS
8032 hd->back->header = NULL;
8033 #ifdef AFS_DEMAND_ATTACH_FS
8034 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
8036 if (hd->diskstuff.inUse) {
8037 VChangeState_r(hd->back, back_save);
8038 VCancelReservation_r(hd->back);
8039 VChangeState_r(vp, vp_save);
8043 volume_hdr_LRU.stats.attached++;
8047 #ifdef AFS_DEMAND_ATTACH_FS
8048 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8051 volume_hdr_LRU.stats.free--;
8052 volume_hdr_LRU.stats.used++;
8054 IncUInt64(&VStats.hdr_gets);
8055 #ifdef AFS_DEMAND_ATTACH_FS
8056 IncUInt64(&vp->stats.hdr_gets);
8057 vp->stats.last_hdr_get = FT_ApproxTime();
8064 * make sure volume header is attached and contains valid cache data.
8066 * @param[out] ec outbound error code
8067 * @param[in] vp pointer to volume object
8069 * @pre VOL_LOCK held. For DAFS, lightweight ref held on vp.
8071 * @post header cache entry attached, and loaded with valid data, or
8072 * *ec is nonzero, and the header is released back into the LRU.
8074 * @internal volume package internal use only.
8077 LoadVolumeHeader(Error * ec, Volume * vp)
8079 #ifdef AFS_DEMAND_ATTACH_FS
8080 VolState state_save;
8084 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8085 IncUInt64(&VStats.hdr_loads);
8086 state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
8089 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8090 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8092 IncUInt64(&vp->stats.hdr_loads);
8093 now = FT_ApproxTime();
8097 V_attachFlags(vp) |= VOL_HDR_LOADED;
8098 vp->stats.last_hdr_load = now;
8100 VChangeState_r(vp, state_save);
8102 #else /* AFS_DEMAND_ATTACH_FS */
8104 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8105 IncUInt64(&VStats.hdr_loads);
8107 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8108 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8111 #endif /* AFS_DEMAND_ATTACH_FS */
8113 /* maintain (nUsers==0) => header in LRU invariant */
8114 FreeVolumeHeader(vp);
8119 * release a header cache entry back into the LRU list.
8121 * @param[in] hd pointer to volume header cache object
8123 * @pre VOL_LOCK held.
8125 * @post header cache object appended onto end of LRU list.
8127 * @note only applicable to fileServer program type.
8129 * @note used to place a header cache entry back into the
8130 * LRU pool without invalidating it as a cache entry.
8132 * @internal volume package internal use only.
8135 ReleaseVolumeHeader(struct volHeader *hd)
8137 if (programType != fileServer)
8139 if (!hd || queue_IsOnQueue(hd)) /* no header, or header already released */
8141 queue_Append(&volume_hdr_LRU, hd);
8142 #ifdef AFS_DEMAND_ATTACH_FS
8144 V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
8147 volume_hdr_LRU.stats.free++;
8148 volume_hdr_LRU.stats.used--;
8152 * free/invalidate a volume header cache entry.
8154 * @param[in] vp pointer to volume object
8156 * @pre VOL_LOCK is held.
8158 * @post For fileserver, header cache entry is returned to LRU, and it is
8159 * invalidated as a cache entry. For volume utilities, the header
8160 * cache entry is freed.
8162 * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
8163 * whenever it is necessary to invalidate the header cache entry.
8165 * @see ReleaseVolumeHeader
8167 * @internal volume package internal use only.
8170 FreeVolumeHeader(Volume * vp)
8172 struct volHeader *hd = vp->header;
8175 if (programType == fileServer) {
8176 ReleaseVolumeHeader(hd);
8181 #ifdef AFS_DEMAND_ATTACH_FS
8182 V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
8184 volume_hdr_LRU.stats.attached--;
8189 /***************************************************/
8190 /* Volume Hash Table routines */
8191 /***************************************************/
8194 * set size of volume object hash table.
8196 * @param[in] logsize log(2) of desired hash table size
8198 * @return operation status
8200 * @retval -1 failure
8202 * @pre MUST be called prior to VInitVolumePackage2
8204 * @post Volume Hash Table will have 2^logsize buckets
8207 VSetVolHashSize(int logsize)
8209 /* 64 to 268435456 hash buckets seems like a reasonable range */
8210 if ((logsize < 6 ) || (logsize > 28)) {
8215 VolumeHashTable.Size = 1 << logsize;
8216 VolumeHashTable.Mask = VolumeHashTable.Size - 1;
8218 /* we can't yet support runtime modification of this
8219 * parameter. we'll need a configuration rwlock to
8220 * make runtime modification feasible.... */
8227 * initialize dynamic data structures for volume hash table.
8229 * @post hash table is allocated, and fields are initialized.
8231 * @internal volume package internal use only.
8234 VInitVolumeHash(void)
8238 VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
8239 sizeof(VolumeHashChainHead));
8240 osi_Assert(VolumeHashTable.Table != NULL);
8242 for (i=0; i < VolumeHashTable.Size; i++) {
8243 queue_Init(&VolumeHashTable.Table[i]);
8244 #ifdef AFS_DEMAND_ATTACH_FS
8245 CV_INIT(&VolumeHashTable.Table[i].chain_busy_cv, "vhash busy", CV_DEFAULT, 0);
8246 #endif /* AFS_DEMAND_ATTACH_FS */
8251 * add a volume object to the hash table.
8253 * @param[in] vp pointer to volume object
8254 * @param[in] hashid hash of volume id
8256 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8259 * @post volume is added to hash chain.
8261 * @internal volume package internal use only.
8263 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8264 * asynchronous hash chain reordering to finish.
8267 AddVolumeToHashTable(Volume * vp, int hashid)
8269 VolumeHashChainHead * head;
8271 if (queue_IsOnQueue(vp))
8274 head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
8276 #ifdef AFS_DEMAND_ATTACH_FS
8277 /* wait for the hash chain to become available */
8280 V_attachFlags(vp) |= VOL_IN_HASH;
8281 vp->chainCacheCheck = ++head->cacheCheck;
8282 #endif /* AFS_DEMAND_ATTACH_FS */
8285 vp->hashid = hashid;
8286 queue_Append(head, vp);
8287 vp->vnodeHashOffset = VolumeHashOffset_r();
8291 * delete a volume object from the hash table.
8293 * @param[in] vp pointer to volume object
8295 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8298 * @post volume is removed from hash chain.
8300 * @internal volume package internal use only.
8302 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8303 * asynchronous hash chain reordering to finish.
8306 DeleteVolumeFromHashTable(Volume * vp)
8308 VolumeHashChainHead * head;
8310 if (!queue_IsOnQueue(vp))
8313 head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
8315 #ifdef AFS_DEMAND_ATTACH_FS
8316 /* wait for the hash chain to become available */
8319 V_attachFlags(vp) &= ~(VOL_IN_HASH);
8321 #endif /* AFS_DEMAND_ATTACH_FS */
8325 /* do NOT reset hashid to zero, as the online
8326 * salvager package may need to know the volume id
8327 * after the volume is removed from the hash */
8331 * lookup a volume object in the hash table given a volume id.
8333 * @param[out] ec error code return
8334 * @param[in] volumeId volume id
8335 * @param[in] hint volume object which we believe could be the correct
8338 * @return volume object pointer
8339 * @retval NULL no such volume id is registered with the hash table.
8341 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
8344 * @post volume object with the given id is returned. volume object and
8345 * hash chain access statistics are updated. hash chain may have
8348 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8349 * asynchronous hash chain reordering operation to finish, or
8350 * in order for us to perform an asynchronous chain reordering.
8352 * @note Hash chain reorderings occur when the access count for the
8353 * volume object being looked up exceeds the sum of the previous
8354 * node's (the node ahead of it in the hash chain linked list)
8355 * access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
8357 * @note For DAFS, the hint parameter allows us to short-circuit if the
8358 * cacheCheck fields match between the hash chain head and the
8359 * hint volume object.
8362 VLookupVolume_r(Error * ec, VolId volumeId, Volume * hint)
8366 #ifdef AFS_DEMAND_ATTACH_FS
8369 VolumeHashChainHead * head;
8372 head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
8374 #ifdef AFS_DEMAND_ATTACH_FS
8375 /* wait for the hash chain to become available */
8378 /* check to see if we can short circuit without walking the hash chain */
8379 if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
8380 IncUInt64(&hint->stats.hash_short_circuits);
8383 #endif /* AFS_DEMAND_ATTACH_FS */
8385 /* someday we need to either do per-chain locks, RWlocks,
8386 * or both for volhash access.
8387 * (and move to a data structure with better cache locality) */
8389 /* search the chain for this volume id */
8390 for(queue_Scan(head, vp, np, Volume)) {
8392 if ((vp->hashid == volumeId)) {
8397 if (queue_IsEnd(head, vp)) {
8401 #ifdef AFS_DEMAND_ATTACH_FS
8402 /* update hash chain statistics */
8405 FillInt64(lks, 0, looks);
8406 AddUInt64(head->looks, lks, &head->looks);
8407 AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
8408 IncUInt64(&head->gets);
8413 IncUInt64(&vp->stats.hash_lookups);
8415 /* for demand attach fileserver, we permit occasional hash chain reordering
8416 * so that frequently looked up volumes move towards the head of the chain */
8417 pp = queue_Prev(vp, Volume);
8418 if (!queue_IsEnd(head, pp)) {
8419 FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
8420 AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
8421 if (GEInt64(vp->stats.hash_lookups, thresh)) {
8422 VReorderHash_r(head, pp, vp);
8426 /* update the short-circuit cache check */
8427 vp->chainCacheCheck = head->cacheCheck;
8429 #endif /* AFS_DEMAND_ATTACH_FS */
8434 #ifdef AFS_DEMAND_ATTACH_FS
8435 /* perform volume hash chain reordering.
8437 * advance a subchain beginning at vp ahead of
8438 * the adjacent subchain ending at pp */
8440 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
8442 Volume *tp, *np, *lp;
8443 afs_uint64 move_thresh;
8445 /* this should never be called if the chain is already busy, so
8446 * no need to wait for other exclusive chain ops to finish */
8448 /* this is a rather heavy set of operations,
8449 * so let's set the chain busy flag and drop
8451 VHashBeginExclusive_r(head);
8454 /* scan forward in the chain from vp looking for the last element
8455 * in the chain we want to advance */
8456 FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
8457 AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
8458 for(queue_ScanFrom(head, vp, tp, np, Volume)) {
8459 if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
8463 lp = queue_Prev(tp, Volume);
8465 /* scan backwards from pp to determine where to splice and
8466 * insert the subchain we're advancing */
8467 for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
8468 if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
8472 tp = queue_Next(tp, Volume);
8474 /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
8475 queue_MoveChainBefore(tp,vp,lp);
8478 IncUInt64(&VStats.hash_reorders);
8480 IncUInt64(&head->reorders);
8482 /* wake up any threads waiting for the hash chain */
8483 VHashEndExclusive_r(head);
8487 /* demand-attach fs volume hash
8488 * asynchronous exclusive operations */
8491 * begin an asynchronous exclusive operation on a volume hash chain.
8493 * @param[in] head pointer to volume hash chain head object
8495 * @pre VOL_LOCK held. hash chain is quiescent.
8497 * @post hash chain marked busy.
8499 * @note this interface is used in conjunction with VHashEndExclusive_r and
8500 * VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8501 * volume hash chain. Its main use case is hash chain reordering, which
8502 * has the potential to be a highly latent operation.
8504 * @see VHashEndExclusive_r
8509 * @internal volume package internal use only.
8512 VHashBeginExclusive_r(VolumeHashChainHead * head)
8514 osi_Assert(head->busy == 0);
8519 * relinquish exclusive ownership of a volume hash chain.
8521 * @param[in] head pointer to volume hash chain head object
8523 * @pre VOL_LOCK held. thread owns the hash chain exclusively.
8525 * @post hash chain is marked quiescent. threads awaiting use of
8526 * chain are awakened.
8528 * @see VHashBeginExclusive_r
8533 * @internal volume package internal use only.
8536 VHashEndExclusive_r(VolumeHashChainHead * head)
8538 osi_Assert(head->busy);
8540 CV_BROADCAST(&head->chain_busy_cv);
8544 * wait for all asynchronous operations on a hash chain to complete.
8546 * @param[in] head pointer to volume hash chain head object
8548 * @pre VOL_LOCK held.
8550 * @post hash chain object is quiescent.
8552 * @see VHashBeginExclusive_r
8553 * @see VHashEndExclusive_r
8557 * @note This interface should be called before any attempt to
8558 * traverse the hash chain. It is permissible for a thread
8559 * to gain exclusive access to the chain, and then perform
8560 * latent operations on the chain asynchronously wrt the
8563 * @warning if waiting is necessary, VOL_LOCK is dropped
8565 * @internal volume package internal use only.
8568 VHashWait_r(VolumeHashChainHead * head)
8570 while (head->busy) {
8571 VOL_CV_WAIT(&head->chain_busy_cv);
8574 #endif /* AFS_DEMAND_ATTACH_FS */
8577 /***************************************************/
8578 /* Volume by Partition List routines */
8579 /***************************************************/
8582 * demand attach fileserver adds a
8583 * linked list of volumes to each
8584 * partition object, thus allowing
8585 * for quick enumeration of all
8586 * volumes on a partition
8589 #ifdef AFS_DEMAND_ATTACH_FS
8591 * add a volume to its disk partition VByPList.
8593 * @param[in] vp pointer to volume object
8595 * @pre either the disk partition VByPList is owned exclusively
8596 * by the calling thread, or the list is quiescent and
8599 * @post volume is added to disk partition VByPList
8603 * @warning it is the caller's responsibility to ensure list
8606 * @see VVByPListWait_r
8607 * @see VVByPListBeginExclusive_r
8608 * @see VVByPListEndExclusive_r
8610 * @internal volume package internal use only.
8613 AddVolumeToVByPList_r(Volume * vp)
8615 if (queue_IsNotOnQueue(&vp->vol_list)) {
8616 queue_Append(&vp->partition->vol_list, &vp->vol_list);
8617 V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
8618 vp->partition->vol_list.len++;
8623 * delete a volume from its disk partition VByPList.
8625 * @param[in] vp pointer to volume object
8627 * @pre either the disk partition VByPList is owned exclusively
8628 * by the calling thread, or the list is quiescent and
8631 * @post volume is removed from the disk partition VByPList
8635 * @warning it is the caller's responsibility to ensure list
8638 * @see VVByPListWait_r
8639 * @see VVByPListBeginExclusive_r
8640 * @see VVByPListEndExclusive_r
8642 * @internal volume package internal use only.
8645 DeleteVolumeFromVByPList_r(Volume * vp)
8647 if (queue_IsOnQueue(&vp->vol_list)) {
8648 queue_Remove(&vp->vol_list);
8649 V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
8650 vp->partition->vol_list.len--;
8655 * begin an asynchronous exclusive operation on a VByPList.
8657 * @param[in] dp pointer to disk partition object
8659 * @pre VOL_LOCK held. VByPList is quiescent.
8661 * @post VByPList marked busy.
8663 * @note this interface is used in conjunction with VVByPListEndExclusive_r and
8664 * VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8667 * @see VVByPListEndExclusive_r
8668 * @see VVByPListWait_r
8672 * @internal volume package internal use only.
8674 /* take exclusive control over the list */
8676 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
8678 osi_Assert(dp->vol_list.busy == 0);
8679 dp->vol_list.busy = 1;
8683 * relinquish exclusive ownership of a VByPList.
8685 * @param[in] dp pointer to disk partition object
8687 * @pre VOL_LOCK held. thread owns the VByPList exclusively.
8689 * @post VByPList is marked quiescent. threads awaiting use of
8690 * the list are awakened.
8692 * @see VVByPListBeginExclusive_r
8693 * @see VVByPListWait_r
8697 * @internal volume package internal use only.
8700 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
8702 osi_Assert(dp->vol_list.busy);
8703 dp->vol_list.busy = 0;
8704 CV_BROADCAST(&dp->vol_list.cv);
8708 * wait for all asynchronous operations on a VByPList to complete.
8710 * @param[in] dp pointer to disk partition object
8712 * @pre VOL_LOCK is held.
8714 * @post disk partition's VByP list is quiescent
8718 * @note This interface should be called before any attempt to
8719 * traverse the VByPList. It is permissible for a thread
8720 * to gain exclusive access to the list, and then perform
8721 * latent operations on the list asynchronously wrt the
8724 * @warning if waiting is necessary, VOL_LOCK is dropped
8726 * @see VVByPListEndExclusive_r
8727 * @see VVByPListBeginExclusive_r
8729 * @internal volume package internal use only.
8732 VVByPListWait_r(struct DiskPartition64 * dp)
8734 while (dp->vol_list.busy) {
8735 VOL_CV_WAIT(&dp->vol_list.cv);
8738 #endif /* AFS_DEMAND_ATTACH_FS */
8740 /***************************************************/
8741 /* Volume Cache Statistics routines */
8742 /***************************************************/
8745 VPrintCacheStats_r(void)
8747 afs_uint32 get_hi, get_lo, load_hi, load_lo;
8748 struct VnodeClassInfo *vcp;
8749 vcp = &VnodeClassInfo[vLarge];
8750 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);
8751 vcp = &VnodeClassInfo[vSmall];
8752 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);
8753 SplitInt64(VStats.hdr_gets, get_hi, get_lo);
8754 SplitInt64(VStats.hdr_loads, load_hi, load_lo);
8755 Log("Volume header cache, %d entries, %d gets, %d replacements\n",
8756 VStats.hdr_cache_size, get_lo, load_lo);
8760 VPrintCacheStats(void)
8763 VPrintCacheStats_r();
8767 #ifdef AFS_DEMAND_ATTACH_FS
8769 UInt64ToDouble(afs_uint64 * x)
8771 static double c32 = 4.0 * 1.073741824 * 1000000000.0;
8773 SplitInt64(*x, h, l);
8774 return (((double)h) * c32) + ((double) l);
8778 DoubleToPrintable(double x, char * buf, int len)
8780 static double billion = 1000000000.0;
8783 y[0] = (afs_uint32) (x / (billion * billion));
8784 y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
8785 y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
8788 snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
8790 snprintf(buf, len, "%d%09d", y[1], y[2]);
8792 snprintf(buf, len, "%d", y[2]);
8798 struct VLRUExtStatsEntry {
8802 struct VLRUExtStats {
8808 } queue_info[VLRU_QUEUE_INVALID];
8809 struct VLRUExtStatsEntry * vec;
8813 * add a 256-entry fudge factor onto the vector in case state changes
8814 * out from under us.
8816 #define VLRU_EXT_STATS_VEC_LEN_FUDGE 256
8819 * collect extended statistics for the VLRU subsystem.
8821 * @param[out] stats pointer to stats structure to be populated
8822 * @param[in] nvols number of volumes currently known to exist
8824 * @pre VOL_LOCK held
8826 * @post stats->vec allocated and populated
8828 * @return operation status
8833 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
8835 afs_uint32 cur, idx, len;
8836 struct rx_queue * qp, * nqp;
8838 struct VLRUExtStatsEntry * vec;
8840 len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
8841 vec = stats->vec = calloc(len,
8842 sizeof(struct VLRUExtStatsEntry));
8848 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
8849 VLRU_Wait_r(&volume_LRU.q[idx]);
8850 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
8853 stats->queue_info[idx].start = cur;
8855 for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
8857 /* out of space in vec */
8860 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
8861 vec[cur].volid = vp->hashid;
8865 stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
8868 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
8876 #define ENUMTOSTRING(en) #en
8877 #define ENUMCASE(en) \
8878 case en: return ENUMTOSTRING(en)
8881 vlru_idx_to_string(int idx)
8884 ENUMCASE(VLRU_QUEUE_NEW);
8885 ENUMCASE(VLRU_QUEUE_MID);
8886 ENUMCASE(VLRU_QUEUE_OLD);
8887 ENUMCASE(VLRU_QUEUE_CANDIDATE);
8888 ENUMCASE(VLRU_QUEUE_HELD);
8889 ENUMCASE(VLRU_QUEUE_INVALID);
8891 return "**UNKNOWN**";
8896 VPrintExtendedCacheStats_r(int flags)
8899 afs_uint32 vol_sum = 0;
8906 struct stats looks, gets, reorders, len;
8907 struct stats ch_looks, ch_gets, ch_reorders;
8909 VolumeHashChainHead *head;
8911 struct VLRUExtStats vlru_stats;
8913 /* zero out stats */
8914 memset(&looks, 0, sizeof(struct stats));
8915 memset(&gets, 0, sizeof(struct stats));
8916 memset(&reorders, 0, sizeof(struct stats));
8917 memset(&len, 0, sizeof(struct stats));
8918 memset(&ch_looks, 0, sizeof(struct stats));
8919 memset(&ch_gets, 0, sizeof(struct stats));
8920 memset(&ch_reorders, 0, sizeof(struct stats));
8922 for (i = 0; i < VolumeHashTable.Size; i++) {
8923 head = &VolumeHashTable.Table[i];
8926 VHashBeginExclusive_r(head);
8929 ch_looks.sum = UInt64ToDouble(&head->looks);
8930 ch_gets.sum = UInt64ToDouble(&head->gets);
8931 ch_reorders.sum = UInt64ToDouble(&head->reorders);
8933 /* update global statistics */
8935 looks.sum += ch_looks.sum;
8936 gets.sum += ch_gets.sum;
8937 reorders.sum += ch_reorders.sum;
8938 len.sum += (double)head->len;
8939 vol_sum += head->len;
8942 len.min = (double) head->len;
8943 len.max = (double) head->len;
8944 looks.min = ch_looks.sum;
8945 looks.max = ch_looks.sum;
8946 gets.min = ch_gets.sum;
8947 gets.max = ch_gets.sum;
8948 reorders.min = ch_reorders.sum;
8949 reorders.max = ch_reorders.sum;
8951 if (((double)head->len) < len.min)
8952 len.min = (double) head->len;
8953 if (((double)head->len) > len.max)
8954 len.max = (double) head->len;
8955 if (ch_looks.sum < looks.min)
8956 looks.min = ch_looks.sum;
8957 else if (ch_looks.sum > looks.max)
8958 looks.max = ch_looks.sum;
8959 if (ch_gets.sum < gets.min)
8960 gets.min = ch_gets.sum;
8961 else if (ch_gets.sum > gets.max)
8962 gets.max = ch_gets.sum;
8963 if (ch_reorders.sum < reorders.min)
8964 reorders.min = ch_reorders.sum;
8965 else if (ch_reorders.sum > reorders.max)
8966 reorders.max = ch_reorders.sum;
8970 if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
8971 /* compute detailed per-chain stats */
8972 struct stats hdr_loads, hdr_gets;
8973 double v_looks, v_loads, v_gets;
8975 /* initialize stats with data from first element in chain */
8976 vp = queue_First(head, Volume);
8977 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
8978 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
8979 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
8980 ch_gets.min = ch_gets.max = v_looks;
8981 hdr_loads.min = hdr_loads.max = v_loads;
8982 hdr_gets.min = hdr_gets.max = v_gets;
8983 hdr_loads.sum = hdr_gets.sum = 0;
8985 vp = queue_Next(vp, Volume);
8987 /* pull in stats from remaining elements in chain */
8988 for (queue_ScanFrom(head, vp, vp, np, Volume)) {
8989 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
8990 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
8991 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
8993 hdr_loads.sum += v_loads;
8994 hdr_gets.sum += v_gets;
8996 if (v_looks < ch_gets.min)
8997 ch_gets.min = v_looks;
8998 else if (v_looks > ch_gets.max)
8999 ch_gets.max = v_looks;
9001 if (v_loads < hdr_loads.min)
9002 hdr_loads.min = v_loads;
9003 else if (v_loads > hdr_loads.max)
9004 hdr_loads.max = v_loads;
9006 if (v_gets < hdr_gets.min)
9007 hdr_gets.min = v_gets;
9008 else if (v_gets > hdr_gets.max)
9009 hdr_gets.max = v_gets;
9012 /* compute per-chain averages */
9013 ch_gets.avg = ch_gets.sum / ((double)head->len);
9014 hdr_loads.avg = hdr_loads.sum / ((double)head->len);
9015 hdr_gets.avg = hdr_gets.sum / ((double)head->len);
9017 /* dump per-chain stats */
9018 Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
9020 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9021 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
9022 Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
9023 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9024 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9025 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9026 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9027 Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
9028 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9029 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9030 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9031 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9032 Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
9033 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
9034 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
9035 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
9036 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
9037 } else if (flags & VOL_STATS_PER_CHAIN) {
9038 /* dump simple per-chain stats */
9039 Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
9041 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9042 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
9043 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
9047 VHashEndExclusive_r(head);
9052 /* compute global averages */
9053 len.avg = len.sum / ((double)VolumeHashTable.Size);
9054 looks.avg = looks.sum / ((double)VolumeHashTable.Size);
9055 gets.avg = gets.sum / ((double)VolumeHashTable.Size);
9056 reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
9058 /* dump global stats */
9059 Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
9060 Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
9061 DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
9062 DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
9063 DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
9064 DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
9065 Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
9066 DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
9067 DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
9068 DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
9069 DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
9070 Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
9071 DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
9072 DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
9073 DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9074 DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9075 Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
9076 DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
9077 DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
9078 DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
9079 DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
9081 /* print extended disk related statistics */
9083 struct DiskPartition64 * diskP;
9084 afs_uint32 vol_count[VOLMAXPARTS+1];
9085 byte part_exists[VOLMAXPARTS+1];
9089 memset(vol_count, 0, sizeof(vol_count));
9090 memset(part_exists, 0, sizeof(part_exists));
9094 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
9096 vol_count[id] = diskP->vol_list.len;
9097 part_exists[id] = 1;
9101 for (i = 0; i <= VOLMAXPARTS; i++) {
9102 if (part_exists[i]) {
9103 /* XXX while this is currently safe, it is a violation
9104 * of the VGetPartitionById_r interface contract. */
9105 diskP = VGetPartitionById_r(i, 0);
9107 Log("Partition %s has %d online volumes\n",
9108 VPartitionPath(diskP), diskP->vol_list.len);
9115 /* print extended VLRU statistics */
9116 if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
9117 afs_uint32 idx, cur, lpos;
9122 Log("VLRU State Dump:\n\n");
9124 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
9125 Log("\t%s:\n", vlru_idx_to_string(idx));
9128 for (cur = vlru_stats.queue_info[idx].start;
9129 cur < vlru_stats.queue_info[idx].len;
9131 line[lpos++] = vlru_stats.vec[cur].volid;
9133 Log("\t\t%u, %u, %u, %u, %u,\n",
9134 line[0], line[1], line[2], line[3], line[4]);
9143 Log("\t\t%u, %u, %u, %u, %u\n",
9144 line[0], line[1], line[2], line[3], line[4]);
9149 free(vlru_stats.vec);
9156 VPrintExtendedCacheStats(int flags)
9159 VPrintExtendedCacheStats_r(flags);
9162 #endif /* AFS_DEMAND_ATTACH_FS */
9165 VCanScheduleSalvage(void)
9167 return vol_opts.canScheduleSalvage;
9173 return vol_opts.canUseFSSYNC;
9177 VCanUseSALVSYNC(void)
9179 return vol_opts.canUseSALVSYNC;
9183 VCanUnsafeAttach(void)
9185 return vol_opts.unsafe_attach;