2 * Copyright 2000, International Business Machines Corporation and others.
5 * This software has been released under the terms of the IBM Public
6 * License. For details, see the LICENSE file in the top-level source
7 * directory or online at http://www.openafs.org/dl/license10.html
9 * Portions Copyright (c) 2005-2008 Sine Nomine Associates
12 /* 1/1/89: NB: this stuff is all going to be replaced. Don't take it too seriously */
17 Institution: The Information Technology Center, Carnegie-Mellon University
21 #include <afsconfig.h>
22 #include <afs/param.h>
26 #include <afs/afsint.h>
30 #include <sys/param.h>
31 #if !defined(AFS_SGI_ENV)
34 #else /* AFS_OSF_ENV */
35 #ifdef AFS_VFSINCL_ENV
38 #include <sys/fs/ufs_fs.h>
40 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
41 #include <ufs/ufs/dinode.h>
42 #include <ufs/ffs/fs.h>
47 #else /* AFS_VFSINCL_ENV */
48 #if !defined(AFS_AIX_ENV) && !defined(AFS_LINUX20_ENV) && !defined(AFS_XBSD_ENV)
51 #endif /* AFS_VFSINCL_ENV */
52 #endif /* AFS_OSF_ENV */
53 #endif /* AFS_SGI_ENV */
54 #endif /* AFS_NT40_ENV */
72 #if defined(AFS_SUN_ENV) || defined(AFS_SUN5_ENV)
74 #include <sys/mnttab.h>
75 #include <sys/mntent.h>
81 #if defined(AFS_SGI_ENV)
86 #ifndef AFS_LINUX20_ENV
87 #include <fstab.h> /* Need to find in libc 5, present in libc 6 */
90 #endif /* AFS_SGI_ENV */
92 #endif /* AFS_HPUX_ENV */
96 #include <netinet/in.h>
100 #include <sys/time.h>
101 #endif /* ITIMER_REAL */
102 #endif /* AFS_NT40_ENV */
103 #if defined(AFS_SUN5_ENV) || defined(AFS_NT40_ENV) || defined(AFS_LINUX20_ENV)
110 #include <afs/errors.h>
113 #include <afs/afssyscalls.h>
115 #include <afs/afsutil.h>
119 #include "daemon_com.h"
121 #include "salvsync.h"
124 #include "partition.h"
125 #include "volume_inline.h"
126 #ifdef AFS_PTHREAD_ENV
128 #else /* AFS_PTHREAD_ENV */
129 #include "afs/assert.h"
130 #endif /* AFS_PTHREAD_ENV */
137 #if !defined(offsetof)
142 #define afs_stat stat64
143 #define afs_fstat fstat64
144 #define afs_open open64
145 #else /* !O_LARGEFILE */
146 #define afs_stat stat
147 #define afs_fstat fstat
148 #define afs_open open
149 #endif /* !O_LARGEFILE */
151 #ifdef AFS_PTHREAD_ENV
152 pthread_mutex_t vol_glock_mutex;
153 pthread_mutex_t vol_trans_mutex;
154 pthread_cond_t vol_put_volume_cond;
155 pthread_cond_t vol_sleep_cond;
156 pthread_cond_t vol_init_attach_cond;
157 int vol_attach_threads = 1;
158 #endif /* AFS_PTHREAD_ENV */
160 /* start-time configurable I/O parameters */
161 ih_init_params vol_io_params;
163 #ifdef AFS_DEMAND_ATTACH_FS
164 pthread_mutex_t vol_salvsync_mutex;
167 * Set this to 1 to disallow SALVSYNC communication in all threads; used
168 * during shutdown, since the salvageserver may have gone away.
170 static volatile sig_atomic_t vol_disallow_salvsync = 0;
171 #endif /* AFS_DEMAND_ATTACH_FS */
174 extern void *calloc(), *realloc();
177 /*@printflike@*/ extern void Log(const char *format, ...);
179 /* Forward declarations */
180 static Volume *attach2(Error * ec, VolId volumeId, char *path,
181 struct DiskPartition64 *partp, Volume * vp,
182 int isbusy, int mode);
183 static void ReallyFreeVolume(Volume * vp);
184 #ifdef AFS_DEMAND_ATTACH_FS
185 static void FreeVolume(Volume * vp);
186 #else /* !AFS_DEMAND_ATTACH_FS */
187 #define FreeVolume(vp) ReallyFreeVolume(vp)
188 static void VScanUpdateList(void);
189 #endif /* !AFS_DEMAND_ATTACH_FS */
190 static void VInitVolumeHeaderCache(afs_uint32 howMany);
191 static int GetVolumeHeader(register Volume * vp);
192 static void ReleaseVolumeHeader(register struct volHeader *hd);
193 static void FreeVolumeHeader(register Volume * vp);
194 static void AddVolumeToHashTable(register Volume * vp, int hashid);
195 static void DeleteVolumeFromHashTable(register Volume * vp);
197 static int VHold(Volume * vp);
199 static int VHold_r(Volume * vp);
200 static void VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class);
201 static void VReleaseVolumeHandles_r(Volume * vp);
202 static void VCloseVolumeHandles_r(Volume * vp);
203 static void LoadVolumeHeader(Error * ec, Volume * vp);
204 static int VCheckOffline(register Volume * vp);
205 static int VCheckDetach(register Volume * vp);
206 static Volume * GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint, int flags);
208 int LogLevel; /* Vice loglevel--not defined as extern so that it will be
209 * defined when not linked with vice, XXXX */
210 ProgramType programType; /* The type of program using the package */
211 static VolumePackageOptions vol_opts;
213 /* extended volume package statistics */
216 #ifdef VOL_LOCK_DEBUG
217 pthread_t vol_glock_holder = 0;
221 #define VOLUME_BITMAP_GROWSIZE 16 /* bytes, => 128vnodes */
222 /* Must be a multiple of 4 (1 word) !! */
224 /* this parameter needs to be tunable at runtime.
225 * 128 was really inadequate for largish servers -- at 16384 volumes this
226 * puts average chain length at 128, thus an average 65 deref's to find a volptr.
227 * talk about bad spatial locality...
229 * an AVL or splay tree might work a lot better, but we'll just increase
230 * the default hash table size for now
232 #define DEFAULT_VOLUME_HASH_SIZE 256 /* Must be a power of 2!! */
233 #define DEFAULT_VOLUME_HASH_MASK (DEFAULT_VOLUME_HASH_SIZE-1)
234 #define VOLUME_HASH(volumeId) (volumeId&(VolumeHashTable.Mask))
237 * turn volume hash chains into partially ordered lists.
238 * when the threshold is exceeded between two adjacent elements,
239 * perform a chain rebalancing operation.
241 * keep the threshold high in order to keep cache line invalidates
242 * low "enough" on SMPs
244 #define VOLUME_HASH_REORDER_THRESHOLD 200
247 * when possible, don't just reorder single elements, but reorder
248 * entire chains of elements at once. a chain of elements that
249 * exceed the element previous to the pivot by at least CHAIN_THRESH
250 * accesses are moved in front of the chain whose elements have at
251 * least CHAIN_THRESH less accesses than the pivot element
253 #define VOLUME_HASH_REORDER_CHAIN_THRESH (VOLUME_HASH_REORDER_THRESHOLD / 2)
255 #include "rx/rx_queue.h"
258 VolumeHashTable_t VolumeHashTable = {
259 DEFAULT_VOLUME_HASH_SIZE,
260 DEFAULT_VOLUME_HASH_MASK,
265 static void VInitVolumeHash(void);
269 /* This macro is used where an ffs() call does not exist. Was in util/ffs.c */
273 afs_int32 ffs_tmp = x;
277 for (ffs_i = 1;; ffs_i++) {
284 #endif /* !AFS_HAVE_FFS */
286 #ifdef AFS_PTHREAD_ENV
287 typedef struct diskpartition_queue_t {
288 struct rx_queue queue;
289 struct DiskPartition64 * diskP;
290 } diskpartition_queue_t;
291 typedef struct vinitvolumepackage_thread_t {
292 struct rx_queue queue;
293 pthread_cond_t thread_done_cv;
294 int n_threads_complete;
295 } vinitvolumepackage_thread_t;
296 static void * VInitVolumePackageThread(void * args);
297 #endif /* AFS_PTHREAD_ENV */
299 static int VAttachVolumesByPartition(struct DiskPartition64 *diskP,
300 int * nAttached, int * nUnattached);
303 #ifdef AFS_DEMAND_ATTACH_FS
304 /* demand attach fileserver extensions */
307 * in the future we will support serialization of VLRU state into the fs_state
310 * these structures are the beginning of that effort
312 struct VLRU_DiskHeader {
313 struct versionStamp stamp; /* magic and structure version number */
314 afs_uint32 mtime; /* time of dump to disk */
315 afs_uint32 num_records; /* number of VLRU_DiskEntry records */
318 struct VLRU_DiskEntry {
319 afs_uint32 vid; /* volume ID */
320 afs_uint32 idx; /* generation */
321 afs_uint32 last_get; /* timestamp of last get */
324 struct VLRU_StartupQueue {
325 struct VLRU_DiskEntry * entry;
330 typedef struct vshutdown_thread_t {
332 pthread_mutex_t lock;
334 pthread_cond_t master_cv;
336 int n_threads_complete;
338 int schedule_version;
341 byte n_parts_done_pass;
342 byte part_thread_target[VOLMAXPARTS+1];
343 byte part_done_pass[VOLMAXPARTS+1];
344 struct rx_queue * part_pass_head[VOLMAXPARTS+1];
345 int stats[4][VOLMAXPARTS+1];
346 } vshutdown_thread_t;
347 static void * VShutdownThread(void * args);
350 static Volume * VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode);
351 static int VCheckFree(Volume * vp);
354 static void AddVolumeToVByPList_r(Volume * vp);
355 static void DeleteVolumeFromVByPList_r(Volume * vp);
356 static void VVByPListBeginExclusive_r(struct DiskPartition64 * dp);
357 static void VVByPListEndExclusive_r(struct DiskPartition64 * dp);
358 static void VVByPListWait_r(struct DiskPartition64 * dp);
360 /* online salvager */
361 static int VCheckSalvage(register Volume * vp);
362 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
363 static int VScheduleSalvage_r(Volume * vp);
366 /* Volume hash table */
367 static void VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp);
368 static void VHashBeginExclusive_r(VolumeHashChainHead * head);
369 static void VHashEndExclusive_r(VolumeHashChainHead * head);
370 static void VHashWait_r(VolumeHashChainHead * head);
373 static int ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass);
374 static int ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
375 struct rx_queue ** idx);
376 static void ShutdownController(vshutdown_thread_t * params);
377 static void ShutdownCreateSchedule(vshutdown_thread_t * params);
380 static void VLRU_ComputeConstants(void);
381 static void VInitVLRU(void);
382 static void VLRU_Init_Node_r(Volume * vp);
383 static void VLRU_Add_r(Volume * vp);
384 static void VLRU_Delete_r(Volume * vp);
385 static void VLRU_UpdateAccess_r(Volume * vp);
386 static void * VLRU_ScannerThread(void * args);
387 static void VLRU_Scan_r(int idx);
388 static void VLRU_Promote_r(int idx);
389 static void VLRU_Demote_r(int idx);
390 static void VLRU_SwitchQueues(Volume * vp, int new_idx, int append);
393 static int VCheckSoftDetach(Volume * vp, afs_uint32 thresh);
394 static int VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh);
395 static int VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh);
398 pthread_key_t VThread_key;
399 VThreadOptions_t VThread_defaults = {
400 0 /**< allow salvsync */
402 #endif /* AFS_DEMAND_ATTACH_FS */
405 struct Lock vol_listLock; /* Lock obtained when listing volumes:
406 * prevents a volume from being missed
407 * if the volume is attached during a
411 /* Common message used when the volume goes off line */
412 char *VSalvageMessage =
413 "Files in this volume are currently unavailable; call operations";
415 int VInit; /* 0 - uninitialized,
416 * 1 - initialized but not all volumes have been attached,
417 * 2 - initialized and all volumes have been attached,
418 * 3 - initialized, all volumes have been attached, and
419 * VConnectFS() has completed. */
421 static int vinit_attach_abort = 0;
423 bit32 VolumeCacheCheck; /* Incremented everytime a volume goes on line--
424 * used to stamp volume headers and in-core
425 * vnodes. When the volume goes on-line the
426 * vnode will be invalidated
427 * access only with VOL_LOCK held */
432 /***************************************************/
433 /* Startup routines */
434 /***************************************************/
436 * assign default values to a VolumePackageOptions struct.
438 * Always call this on a VolumePackageOptions struct first, then set any
439 * specific options you want, then call VInitVolumePackage2.
441 * @param[in] pt caller's program type
442 * @param[out] opts volume package options
445 VOptDefaults(ProgramType pt, VolumePackageOptions *opts)
447 opts->nLargeVnodes = opts->nSmallVnodes = 5;
450 opts->canScheduleSalvage = 0;
451 opts->canUseFSSYNC = 0;
452 opts->canUseSALVSYNC = 0;
456 opts->canScheduleSalvage = 1;
457 opts->canUseSALVSYNC = 1;
461 opts->canUseFSSYNC = 1;
465 opts->nLargeVnodes = 0;
466 opts->nSmallVnodes = 0;
468 opts->canScheduleSalvage = 1;
469 opts->canUseFSSYNC = 1;
479 VInitVolumePackage2(ProgramType pt, VolumePackageOptions * opts)
481 int errors = 0; /* Number of errors while finding vice partitions. */
486 memset(&VStats, 0, sizeof(VStats));
487 VStats.hdr_cache_size = 200;
489 VInitPartitionPackage();
491 #ifdef AFS_DEMAND_ATTACH_FS
492 if (programType == fileServer) {
495 VLRU_SetOptions(VLRU_SET_ENABLED, 0);
497 assert(pthread_key_create(&VThread_key, NULL) == 0);
500 #ifdef AFS_PTHREAD_ENV
501 assert(pthread_mutex_init(&vol_glock_mutex, NULL) == 0);
502 assert(pthread_mutex_init(&vol_trans_mutex, NULL) == 0);
503 assert(pthread_cond_init(&vol_put_volume_cond, NULL) == 0);
504 assert(pthread_cond_init(&vol_sleep_cond, NULL) == 0);
505 assert(pthread_cond_init(&vol_init_attach_cond, NULL) == 0);
506 #else /* AFS_PTHREAD_ENV */
508 #endif /* AFS_PTHREAD_ENV */
509 Lock_Init(&vol_listLock);
511 srandom(time(0)); /* For VGetVolumeInfo */
513 #ifdef AFS_DEMAND_ATTACH_FS
514 assert(pthread_mutex_init(&vol_salvsync_mutex, NULL) == 0);
515 #endif /* AFS_DEMAND_ATTACH_FS */
517 /* Ok, we have done enough initialization that fileserver can
518 * start accepting calls, even though the volumes may not be
519 * available just yet.
523 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_SERVER)
524 if (programType == salvageServer) {
527 #endif /* AFS_DEMAND_ATTACH_FS */
528 #ifdef FSSYNC_BUILD_SERVER
529 if (programType == fileServer) {
533 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_CLIENT)
534 if (VCanUseSALVSYNC()) {
535 /* establish a connection to the salvager at this point */
536 assert(VConnectSALV() != 0);
538 #endif /* AFS_DEMAND_ATTACH_FS */
540 if (opts->volcache > VStats.hdr_cache_size)
541 VStats.hdr_cache_size = opts->volcache;
542 VInitVolumeHeaderCache(VStats.hdr_cache_size);
544 VInitVnodes(vLarge, opts->nLargeVnodes);
545 VInitVnodes(vSmall, opts->nSmallVnodes);
548 errors = VAttachPartitions();
552 if (programType != fileServer) {
553 errors = VInitAttachVolumes(programType);
559 #ifdef FSSYNC_BUILD_CLIENT
560 if (VCanUseFSSYNC()) {
562 #ifdef AFS_DEMAND_ATTACH_FS
563 if (programType == salvageServer) {
564 Log("Unable to connect to file server; aborted\n");
567 #endif /* AFS_DEMAND_ATTACH_FS */
568 Log("Unable to connect to file server; will retry at need\n");
571 #endif /* FSSYNC_BUILD_CLIENT */
576 VInitAttachVolumes(ProgramType pt)
579 if (pt == fileServer) {
580 struct DiskPartition64 *diskP;
581 #ifdef AFS_PTHREAD_ENV
582 struct vinitvolumepackage_thread_t params;
583 struct diskpartition_queue_t * dpq;
584 int i, threads, parts;
586 pthread_attr_t attrs;
588 assert(pthread_cond_init(¶ms.thread_done_cv,NULL) == 0);
590 params.n_threads_complete = 0;
592 /* create partition work queue */
593 for (parts=0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
594 dpq = (diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
597 queue_Append(¶ms,dpq);
600 threads = MIN(parts, vol_attach_threads);
603 /* spawn off a bunch of initialization threads */
604 assert(pthread_attr_init(&attrs) == 0);
605 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
607 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
608 #ifdef AFS_DEMAND_ATTACH_FS
609 Log("VInitVolumePackage: using %d threads to pre-attach volumes on %d partitions\n",
611 #else /* AFS_DEMAND_ATTACH_FS */
612 Log("VInitVolumePackage: using %d threads to attach volumes on %d partitions\n",
614 #endif /* AFS_DEMAND_ATTACH_FS */
617 for (i=0; i < threads; i++) {
620 assert(pthread_create
621 (&tid, &attrs, &VInitVolumePackageThread,
623 AFS_SIGSET_RESTORE();
626 while(params.n_threads_complete < threads) {
627 VOL_CV_WAIT(¶ms.thread_done_cv);
631 assert(pthread_attr_destroy(&attrs) == 0);
633 /* if we're only going to run one init thread, don't bother creating
635 Log("VInitVolumePackage: beginning single-threaded fileserver startup\n");
636 #ifdef AFS_DEMAND_ATTACH_FS
637 Log("VInitVolumePackage: using 1 thread to pre-attach volumes on %d partition(s)\n",
639 #else /* AFS_DEMAND_ATTACH_FS */
640 Log("VInitVolumePackage: using 1 thread to attach volumes on %d partition(s)\n",
642 #endif /* AFS_DEMAND_ATTACH_FS */
644 VInitVolumePackageThread(¶ms);
647 assert(pthread_cond_destroy(¶ms.thread_done_cv) == 0);
649 #else /* AFS_PTHREAD_ENV */
651 /* Attach all the volumes in this partition */
652 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
653 int nAttached = 0, nUnattached = 0;
654 assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
656 #endif /* AFS_PTHREAD_ENV */
659 VInit = 2; /* Initialized, and all volumes have been attached */
660 #ifdef AFS_PTHREAD_ENV
661 assert(pthread_cond_broadcast(&vol_init_attach_cond) == 0);
663 LWP_NoYieldSignal(VInitAttachVolumes);
664 #endif /* AFS_PTHREAD_ENV */
669 #ifdef AFS_PTHREAD_ENV
671 VInitVolumePackageThread(void * args) {
673 struct DiskPartition64 *diskP;
674 struct vinitvolumepackage_thread_t * params;
675 struct diskpartition_queue_t * dpq;
677 params = (vinitvolumepackage_thread_t *) args;
681 /* Attach all the volumes in this partition */
682 while (queue_IsNotEmpty(params)) {
683 int nAttached = 0, nUnattached = 0;
685 if (vinit_attach_abort) {
686 Log("Aborting initialization\n");
690 dpq = queue_First(params,diskpartition_queue_t);
696 assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
702 params->n_threads_complete++;
703 pthread_cond_signal(¶ms->thread_done_cv);
707 #endif /* AFS_PTHREAD_ENV */
710 * attach all volumes on a given disk partition
713 VAttachVolumesByPartition(struct DiskPartition64 *diskP, int * nAttached, int * nUnattached)
719 Log("Partition %s: attaching volumes\n", diskP->name);
720 dirp = opendir(VPartitionPath(diskP));
722 Log("opendir on Partition %s failed!\n", diskP->name);
726 while ((dp = readdir(dirp))) {
728 p = strrchr(dp->d_name, '.');
730 if (vinit_attach_abort) {
731 Log("Partition %s: abort attach volumes\n", diskP->name);
735 if (p != NULL && strcmp(p, VHDREXT) == 0) {
738 #ifdef AFS_DEMAND_ATTACH_FS
739 vp = VPreAttachVolumeByName(&error, diskP->name, dp->d_name);
740 #else /* AFS_DEMAND_ATTACH_FS */
741 vp = VAttachVolumeByName(&error, diskP->name, dp->d_name,
743 #endif /* AFS_DEMAND_ATTACH_FS */
744 (*(vp ? nAttached : nUnattached))++;
745 if (error == VOFFLINE)
746 Log("Volume %d stays offline (/vice/offline/%s exists)\n", VolumeNumber(dp->d_name), dp->d_name);
747 else if (LogLevel >= 5) {
748 Log("Partition %s: attached volume %d (%s)\n",
749 diskP->name, VolumeNumber(dp->d_name),
752 #if !defined(AFS_DEMAND_ATTACH_FS)
756 #endif /* AFS_DEMAND_ATTACH_FS */
760 Log("Partition %s: attached %d volumes; %d volumes not attached\n", diskP->name, *nAttached, *nUnattached);
767 /***************************************************/
768 /* Shutdown routines */
769 /***************************************************/
773 * highly multithreaded volume package shutdown
775 * with the demand attach fileserver extensions,
776 * VShutdown has been modified to be multithreaded.
777 * In order to achieve optimal use of many threads,
778 * the shutdown code involves one control thread and
779 * n shutdown worker threads. The control thread
780 * periodically examines the number of volumes available
781 * for shutdown on each partition, and produces a worker
782 * thread allocation schedule. The idea is to eliminate
783 * redundant scheduling computation on the workers by
784 * having a single master scheduler.
786 * The scheduler's objectives are:
788 * each partition with volumes remaining gets allocated
789 * at least 1 thread (assuming sufficient threads)
791 * threads are allocated proportional to the number of
792 * volumes remaining to be offlined. This ensures that
793 * the OS I/O scheduler has many requests to elevator
794 * seek on partitions that will (presumably) take the
795 * longest amount of time (from now) to finish shutdown
796 * (3) keep threads busy
797 * when there are extra threads, they are assigned to
798 * partitions using a simple round-robin algorithm
800 * In the future, we may wish to add the ability to adapt
801 * to the relative performance patterns of each disk
806 * multi-step shutdown process
808 * demand attach shutdown is a four-step process. Each
809 * shutdown "pass" shuts down increasingly more difficult
810 * volumes. The main purpose is to achieve better cache
811 * utilization during shutdown.
814 * shutdown volumes in the unattached, pre-attached
817 * shutdown attached volumes with cached volume headers
819 * shutdown all volumes in non-exclusive states
821 * shutdown all remaining volumes
824 #ifdef AFS_DEMAND_ATTACH_FS
830 struct DiskPartition64 * diskP;
831 struct diskpartition_queue_t * dpq;
832 vshutdown_thread_t params;
834 pthread_attr_t attrs;
836 memset(¶ms, 0, sizeof(vshutdown_thread_t));
839 Log("VShutdown: aborting attach volumes\n");
840 vinit_attach_abort = 1;
841 VOL_CV_WAIT(&vol_init_attach_cond);
844 for (params.n_parts=0, diskP = DiskPartitionList;
845 diskP; diskP = diskP->next, params.n_parts++);
847 Log("VShutdown: shutting down on-line volumes on %d partition%s...\n",
848 params.n_parts, params.n_parts > 1 ? "s" : "");
850 if (vol_attach_threads > 1) {
851 /* prepare for parallel shutdown */
852 params.n_threads = vol_attach_threads;
853 assert(pthread_mutex_init(¶ms.lock, NULL) == 0);
854 assert(pthread_cond_init(¶ms.cv, NULL) == 0);
855 assert(pthread_cond_init(¶ms.master_cv, NULL) == 0);
856 assert(pthread_attr_init(&attrs) == 0);
857 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
860 /* setup the basic partition information structures for
861 * parallel shutdown */
862 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
864 struct rx_queue * qp, * nqp;
868 VVByPListWait_r(diskP);
869 VVByPListBeginExclusive_r(diskP);
872 for (queue_Scan(&diskP->vol_list, qp, nqp, rx_queue)) {
873 vp = (Volume *)((char *)qp - offsetof(Volume, vol_list));
877 Log("VShutdown: partition %s has %d volumes with attached headers\n",
878 VPartitionPath(diskP), count);
881 /* build up the pass 0 shutdown work queue */
882 dpq = (struct diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
885 queue_Prepend(¶ms, dpq);
887 params.part_pass_head[diskP->index] = queue_First(&diskP->vol_list, rx_queue);
890 Log("VShutdown: beginning parallel fileserver shutdown\n");
891 Log("VShutdown: using %d threads to offline volumes on %d partition%s\n",
892 vol_attach_threads, params.n_parts, params.n_parts > 1 ? "s" : "" );
894 /* do pass 0 shutdown */
895 assert(pthread_mutex_lock(¶ms.lock) == 0);
896 for (i=0; i < params.n_threads; i++) {
897 assert(pthread_create
898 (&tid, &attrs, &VShutdownThread,
902 /* wait for all the pass 0 shutdowns to complete */
903 while (params.n_threads_complete < params.n_threads) {
904 assert(pthread_cond_wait(¶ms.master_cv, ¶ms.lock) == 0);
906 params.n_threads_complete = 0;
908 assert(pthread_cond_broadcast(¶ms.cv) == 0);
909 assert(pthread_mutex_unlock(¶ms.lock) == 0);
911 Log("VShutdown: pass 0 completed using the 1 thread per partition algorithm\n");
912 Log("VShutdown: starting passes 1 through 3 using finely-granular mp-fast algorithm\n");
914 /* run the parallel shutdown scheduler. it will drop the glock internally */
915 ShutdownController(¶ms);
917 /* wait for all the workers to finish pass 3 and terminate */
918 while (params.pass < 4) {
919 VOL_CV_WAIT(¶ms.cv);
922 assert(pthread_attr_destroy(&attrs) == 0);
923 assert(pthread_cond_destroy(¶ms.cv) == 0);
924 assert(pthread_cond_destroy(¶ms.master_cv) == 0);
925 assert(pthread_mutex_destroy(¶ms.lock) == 0);
927 /* drop the VByPList exclusive reservations */
928 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
929 VVByPListEndExclusive_r(diskP);
930 Log("VShutdown: %s stats : (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
931 VPartitionPath(diskP),
932 params.stats[0][diskP->index],
933 params.stats[1][diskP->index],
934 params.stats[2][diskP->index],
935 params.stats[3][diskP->index]);
938 Log("VShutdown: shutdown finished using %d threads\n", params.n_threads);
940 /* if we're only going to run one shutdown thread, don't bother creating
942 Log("VShutdown: beginning single-threaded fileserver shutdown\n");
944 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
945 VShutdownByPartition_r(diskP);
949 Log("VShutdown: complete.\n");
952 #else /* AFS_DEMAND_ATTACH_FS */
958 register Volume *vp, *np;
959 register afs_int32 code;
962 Log("VShutdown: aborting attach volumes\n");
963 vinit_attach_abort = 1;
964 #ifdef AFS_PTHREAD_ENV
965 VOL_CV_WAIT(&vol_init_attach_cond);
967 LWP_WaitProcess(VInitAttachVolumes);
968 #endif /* AFS_PTHREAD_ENV */
971 Log("VShutdown: shutting down on-line volumes...\n");
972 for (i = 0; i < VolumeHashTable.Size; i++) {
973 /* try to hold first volume in the hash table */
974 for (queue_Scan(&VolumeHashTable.Table[i],vp,np,Volume)) {
978 Log("VShutdown: Attempting to take volume %u offline.\n",
981 /* next, take the volume offline (drops reference count) */
982 VOffline_r(vp, "File server was shut down");
986 Log("VShutdown: complete.\n");
988 #endif /* AFS_DEMAND_ATTACH_FS */
1001 * stop new activity (e.g. SALVSYNC) from occurring
1003 * Use this to make the volume package less busy; for example, during
1004 * shutdown. This doesn't actually shutdown/detach anything in the
1005 * volume package, but prevents certain processes from ocurring. For
1006 * example, preventing new SALVSYNC communication in DAFS. In theory, we
1007 * could also use this to prevent new volume attachment, or prevent
1008 * other programs from checking out volumes, etc.
1013 #ifdef AFS_DEMAND_ATTACH_FS
1014 /* make sure we don't try to contact the salvageserver, since it may
1015 * not be around anymore */
1016 vol_disallow_salvsync = 1;
1020 #ifdef AFS_DEMAND_ATTACH_FS
1023 * shutdown control thread
1026 ShutdownController(vshutdown_thread_t * params)
1029 struct DiskPartition64 * diskP;
1031 vshutdown_thread_t shadow;
1033 ShutdownCreateSchedule(params);
1035 while ((params->pass < 4) &&
1036 (params->n_threads_complete < params->n_threads)) {
1037 /* recompute schedule once per second */
1039 memcpy(&shadow, params, sizeof(vshutdown_thread_t));
1043 Log("ShutdownController: schedule version=%d, vol_remaining=%d, pass=%d\n",
1044 shadow.schedule_version, shadow.vol_remaining, shadow.pass);
1045 Log("ShutdownController: n_threads_complete=%d, n_parts_done_pass=%d\n",
1046 shadow.n_threads_complete, shadow.n_parts_done_pass);
1047 for (diskP = DiskPartitionList; diskP; diskP=diskP->next) {
1049 Log("ShutdownController: part[%d] : (len=%d, thread_target=%d, done_pass=%d, pass_head=%p)\n",
1051 diskP->vol_list.len,
1052 shadow.part_thread_target[id],
1053 shadow.part_done_pass[id],
1054 shadow.part_pass_head[id]);
1060 ShutdownCreateSchedule(params);
1064 /* create the shutdown thread work schedule.
1065 * this scheduler tries to implement fairness
1066 * by allocating at least 1 thread to each
1067 * partition with volumes to be shutdown,
1068 * and then it attempts to allocate remaining
1069 * threads based upon the amount of work left
1072 ShutdownCreateSchedule(vshutdown_thread_t * params)
1074 struct DiskPartition64 * diskP;
1075 int sum, thr_workload, thr_left;
1076 int part_residue[VOLMAXPARTS+1];
1079 /* compute the total number of outstanding volumes */
1081 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1082 sum += diskP->vol_list.len;
1085 params->schedule_version++;
1086 params->vol_remaining = sum;
1091 /* compute average per-thread workload */
1092 thr_workload = sum / params->n_threads;
1093 if (sum % params->n_threads)
1096 thr_left = params->n_threads;
1097 memset(&part_residue, 0, sizeof(part_residue));
1099 /* for fairness, give every partition with volumes remaining
1100 * at least one thread */
1101 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1103 if (diskP->vol_list.len) {
1104 params->part_thread_target[id] = 1;
1107 params->part_thread_target[id] = 0;
1111 if (thr_left && thr_workload) {
1112 /* compute length-weighted workloads */
1115 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1117 delta = (diskP->vol_list.len / thr_workload) -
1118 params->part_thread_target[id];
1122 if (delta < thr_left) {
1123 params->part_thread_target[id] += delta;
1126 params->part_thread_target[id] += thr_left;
1134 /* try to assign any leftover threads to partitions that
1135 * had volume lengths closer to needing thread_target+1 */
1136 int max_residue, max_id = 0;
1138 /* compute the residues */
1139 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1141 part_residue[id] = diskP->vol_list.len -
1142 (params->part_thread_target[id] * thr_workload);
1145 /* now try to allocate remaining threads to partitions with the
1146 * highest residues */
1149 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1151 if (part_residue[id] > max_residue) {
1152 max_residue = part_residue[id];
1161 params->part_thread_target[max_id]++;
1163 part_residue[max_id] = 0;
1168 /* punt and give any remaining threads equally to each partition */
1170 if (thr_left >= params->n_parts) {
1171 alloc = thr_left / params->n_parts;
1172 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1174 params->part_thread_target[id] += alloc;
1179 /* finish off the last of the threads */
1180 for (diskP = DiskPartitionList; thr_left && diskP; diskP = diskP->next) {
1182 params->part_thread_target[id]++;
1188 /* worker thread for parallel shutdown */
1190 VShutdownThread(void * args)
1192 vshutdown_thread_t * params;
1193 int found, pass, schedule_version_save, count;
1194 struct DiskPartition64 *diskP;
1195 struct diskpartition_queue_t * dpq;
1198 params = (vshutdown_thread_t *) args;
1200 /* acquire the shutdown pass 0 lock */
1201 assert(pthread_mutex_lock(¶ms->lock) == 0);
1203 /* if there's still pass 0 work to be done,
1204 * get a work entry, and do a pass 0 shutdown */
1205 if (queue_IsNotEmpty(params)) {
1206 dpq = queue_First(params, diskpartition_queue_t);
1208 assert(pthread_mutex_unlock(¶ms->lock) == 0);
1214 while (ShutdownVolumeWalk_r(diskP, 0, ¶ms->part_pass_head[id]))
1216 params->stats[0][diskP->index] = count;
1217 assert(pthread_mutex_lock(¶ms->lock) == 0);
1220 params->n_threads_complete++;
1221 if (params->n_threads_complete == params->n_threads) {
1222 /* notify control thread that all workers have completed pass 0 */
1223 assert(pthread_cond_signal(¶ms->master_cv) == 0);
1225 while (params->pass == 0) {
1226 assert(pthread_cond_wait(¶ms->cv, ¶ms->lock) == 0);
1230 assert(pthread_mutex_unlock(¶ms->lock) == 0);
1233 pass = params->pass;
1236 /* now escalate through the more complicated shutdowns */
1238 schedule_version_save = params->schedule_version;
1240 /* find a disk partition to work on */
1241 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1243 if (params->part_thread_target[id] && !params->part_done_pass[id]) {
1244 params->part_thread_target[id]--;
1251 /* hmm. for some reason the controller thread couldn't find anything for
1252 * us to do. let's see if there's anything we can do */
1253 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1255 if (diskP->vol_list.len && !params->part_done_pass[id]) {
1258 } else if (!params->part_done_pass[id]) {
1259 params->part_done_pass[id] = 1;
1260 params->n_parts_done_pass++;
1262 Log("VShutdown: done shutting down volumes on partition %s.\n",
1263 VPartitionPath(diskP));
1269 /* do work on this partition until either the controller
1270 * creates a new schedule, or we run out of things to do
1271 * on this partition */
1274 while (!params->part_done_pass[id] &&
1275 (schedule_version_save == params->schedule_version)) {
1276 /* ShutdownVolumeWalk_r will drop the glock internally */
1277 if (!ShutdownVolumeWalk_r(diskP, pass, ¶ms->part_pass_head[id])) {
1278 if (!params->part_done_pass[id]) {
1279 params->part_done_pass[id] = 1;
1280 params->n_parts_done_pass++;
1282 Log("VShutdown: done shutting down volumes on partition %s.\n",
1283 VPartitionPath(diskP));
1291 params->stats[pass][id] += count;
1293 /* ok, everyone is done this pass, proceed */
1296 params->n_threads_complete++;
1297 while (params->pass == pass) {
1298 if (params->n_threads_complete == params->n_threads) {
1299 /* we are the last thread to complete, so we will
1300 * reinitialize worker pool state for the next pass */
1301 params->n_threads_complete = 0;
1302 params->n_parts_done_pass = 0;
1304 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1306 params->part_done_pass[id] = 0;
1307 params->part_pass_head[id] = queue_First(&diskP->vol_list, rx_queue);
1310 /* compute a new thread schedule before releasing all the workers */
1311 ShutdownCreateSchedule(params);
1313 /* wake up all the workers */
1314 assert(pthread_cond_broadcast(¶ms->cv) == 0);
1317 Log("VShutdown: pass %d completed using %d threads on %d partitions\n",
1318 pass, params->n_threads, params->n_parts);
1321 VOL_CV_WAIT(¶ms->cv);
1324 pass = params->pass;
1338 /* shut down all volumes on a given disk partition
1340 * note that this function will not allow mp-fast
1341 * shutdown of a partition */
1343 VShutdownByPartition_r(struct DiskPartition64 * dp)
1349 /* wait for other exclusive ops to finish */
1350 VVByPListWait_r(dp);
1352 /* begin exclusive access */
1353 VVByPListBeginExclusive_r(dp);
1355 /* pick the low-hanging fruit first,
1356 * then do the complicated ones last
1357 * (has the advantage of keeping
1358 * in-use volumes up until the bitter end) */
1359 for (pass = 0, total=0; pass < 4; pass++) {
1360 pass_stats[pass] = ShutdownVByPForPass_r(dp, pass);
1361 total += pass_stats[pass];
1364 /* end exclusive access */
1365 VVByPListEndExclusive_r(dp);
1367 Log("VShutdownByPartition: shut down %d volumes on %s (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1368 total, VPartitionPath(dp), pass_stats[0], pass_stats[1], pass_stats[2], pass_stats[3]);
1373 /* internal shutdown functionality
1375 * for multi-pass shutdown:
1376 * 0 to only "shutdown" {pre,un}attached and error state volumes
1377 * 1 to also shutdown attached volumes w/ volume header loaded
1378 * 2 to also shutdown attached volumes w/o volume header loaded
1379 * 3 to also shutdown exclusive state volumes
1381 * caller MUST hold exclusive access on the hash chain
1382 * because we drop vol_glock_mutex internally
1384 * this function is reentrant for passes 1--3
1385 * (e.g. multiple threads can cooperate to
1386 * shutdown a partition mp-fast)
1388 * pass 0 is not scaleable because the volume state data is
1389 * synchronized by vol_glock mutex, and the locking overhead
1390 * is too high to drop the lock long enough to do linked list
1394 ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass)
1396 struct rx_queue * q = queue_First(&dp->vol_list, rx_queue);
1399 while (ShutdownVolumeWalk_r(dp, pass, &q))
1405 /* conditionally shutdown one volume on partition dp
1406 * returns 1 if a volume was shutdown in this pass,
1409 ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
1410 struct rx_queue ** idx)
1412 struct rx_queue *qp, *nqp;
1417 for (queue_ScanFrom(&dp->vol_list, qp, qp, nqp, rx_queue)) {
1418 vp = (Volume *) (((char *)qp) - offsetof(Volume, vol_list));
1422 if ((V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1423 (V_attachState(vp) != VOL_STATE_ERROR) &&
1424 (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1428 if ((V_attachState(vp) == VOL_STATE_ATTACHED) &&
1429 (vp->header == NULL)) {
1433 if (VIsExclusiveState(V_attachState(vp))) {
1438 DeleteVolumeFromVByPList_r(vp);
1439 VShutdownVolume_r(vp);
1449 * shutdown a specific volume
1451 /* caller MUST NOT hold a heavyweight ref on vp */
1453 VShutdownVolume_r(Volume * vp)
1457 VCreateReservation_r(vp);
1459 if (LogLevel >= 5) {
1460 Log("VShutdownVolume_r: vid=%u, device=%d, state=%hu\n",
1461 vp->hashid, vp->partition->device, V_attachState(vp));
1464 /* wait for other blocking ops to finish */
1465 VWaitExclusiveState_r(vp);
1467 assert(VIsValidState(V_attachState(vp)));
1469 switch(V_attachState(vp)) {
1470 case VOL_STATE_SALVAGING:
1471 /* Leave salvaging volumes alone. Any in-progress salvages will
1472 * continue working after viced shuts down. This is intentional.
1475 case VOL_STATE_PREATTACHED:
1476 case VOL_STATE_ERROR:
1477 VChangeState_r(vp, VOL_STATE_UNATTACHED);
1478 case VOL_STATE_UNATTACHED:
1480 case VOL_STATE_GOING_OFFLINE:
1481 case VOL_STATE_SHUTTING_DOWN:
1482 case VOL_STATE_ATTACHED:
1486 Log("VShutdown: Attempting to take volume %u offline.\n",
1489 /* take the volume offline (drops reference count) */
1490 VOffline_r(vp, "File server was shut down");
1497 VCancelReservation_r(vp);
1501 #endif /* AFS_DEMAND_ATTACH_FS */
1504 /***************************************************/
1505 /* Header I/O routines */
1506 /***************************************************/
1508 /* open a descriptor for the inode (h),
1509 * read in an on-disk structure into buffer (to) of size (size),
1510 * verify versionstamp in structure has magic (magic) and
1511 * optionally verify version (version) if (version) is nonzero
1514 ReadHeader(Error * ec, IHandle_t * h, char *to, int size, bit32 magic,
1517 struct versionStamp *vsn;
1532 if (FDH_SEEK(fdP, 0, SEEK_SET) < 0) {
1534 FDH_REALLYCLOSE(fdP);
1537 vsn = (struct versionStamp *)to;
1538 if (FDH_READ(fdP, to, size) != size || vsn->magic != magic) {
1540 FDH_REALLYCLOSE(fdP);
1545 /* Check is conditional, in case caller wants to inspect version himself */
1546 if (version && vsn->version != version) {
1552 WriteVolumeHeader_r(Error * ec, Volume * vp)
1554 IHandle_t *h = V_diskDataHandle(vp);
1564 if (FDH_SEEK(fdP, 0, SEEK_SET) < 0) {
1566 FDH_REALLYCLOSE(fdP);
1569 if (FDH_WRITE(fdP, (char *)&V_disk(vp), sizeof(V_disk(vp)))
1570 != sizeof(V_disk(vp))) {
1572 FDH_REALLYCLOSE(fdP);
1578 /* VolumeHeaderToDisk
1579 * Allows for storing 64 bit inode numbers in on-disk volume header
1582 /* convert in-memory representation of a volume header to the
1583 * on-disk representation of a volume header */
1585 VolumeHeaderToDisk(VolumeDiskHeader_t * dh, VolumeHeader_t * h)
1588 memset(dh, 0, sizeof(VolumeDiskHeader_t));
1589 dh->stamp = h->stamp;
1591 dh->parent = h->parent;
1593 #ifdef AFS_64BIT_IOPS_ENV
1594 dh->volumeInfo_lo = (afs_int32) h->volumeInfo & 0xffffffff;
1595 dh->volumeInfo_hi = (afs_int32) (h->volumeInfo >> 32) & 0xffffffff;
1596 dh->smallVnodeIndex_lo = (afs_int32) h->smallVnodeIndex & 0xffffffff;
1597 dh->smallVnodeIndex_hi =
1598 (afs_int32) (h->smallVnodeIndex >> 32) & 0xffffffff;
1599 dh->largeVnodeIndex_lo = (afs_int32) h->largeVnodeIndex & 0xffffffff;
1600 dh->largeVnodeIndex_hi =
1601 (afs_int32) (h->largeVnodeIndex >> 32) & 0xffffffff;
1602 dh->linkTable_lo = (afs_int32) h->linkTable & 0xffffffff;
1603 dh->linkTable_hi = (afs_int32) (h->linkTable >> 32) & 0xffffffff;
1605 dh->volumeInfo_lo = h->volumeInfo;
1606 dh->smallVnodeIndex_lo = h->smallVnodeIndex;
1607 dh->largeVnodeIndex_lo = h->largeVnodeIndex;
1608 dh->linkTable_lo = h->linkTable;
1612 /* DiskToVolumeHeader
1613 * Converts an on-disk representation of a volume header to
1614 * the in-memory representation of a volume header.
1616 * Makes the assumption that AFS has *always*
1617 * zero'd the volume header file so that high parts of inode
1618 * numbers are 0 in older (SGI EFS) volume header files.
1621 DiskToVolumeHeader(VolumeHeader_t * h, VolumeDiskHeader_t * dh)
1623 memset(h, 0, sizeof(VolumeHeader_t));
1624 h->stamp = dh->stamp;
1626 h->parent = dh->parent;
1628 #ifdef AFS_64BIT_IOPS_ENV
1630 (Inode) dh->volumeInfo_lo | ((Inode) dh->volumeInfo_hi << 32);
1632 h->smallVnodeIndex =
1633 (Inode) dh->smallVnodeIndex_lo | ((Inode) dh->
1634 smallVnodeIndex_hi << 32);
1636 h->largeVnodeIndex =
1637 (Inode) dh->largeVnodeIndex_lo | ((Inode) dh->
1638 largeVnodeIndex_hi << 32);
1640 (Inode) dh->linkTable_lo | ((Inode) dh->linkTable_hi << 32);
1642 h->volumeInfo = dh->volumeInfo_lo;
1643 h->smallVnodeIndex = dh->smallVnodeIndex_lo;
1644 h->largeVnodeIndex = dh->largeVnodeIndex_lo;
1645 h->linkTable = dh->linkTable_lo;
1650 /***************************************************/
1651 /* Volume Attachment routines */
1652 /***************************************************/
1654 #ifdef AFS_DEMAND_ATTACH_FS
1656 * pre-attach a volume given its path.
1658 * @param[out] ec outbound error code
1659 * @param[in] partition partition path string
1660 * @param[in] name volume id string
1662 * @return volume object pointer
1664 * @note A pre-attached volume will only have its partition
1665 * and hashid fields initialized. At first call to
1666 * VGetVolume, the volume will be fully attached.
1670 VPreAttachVolumeByName(Error * ec, char *partition, char *name)
1674 vp = VPreAttachVolumeByName_r(ec, partition, name);
1680 * pre-attach a volume given its path.
1682 * @param[out] ec outbound error code
1683 * @param[in] partition path to vice partition
1684 * @param[in] name volume id string
1686 * @return volume object pointer
1688 * @pre VOL_LOCK held
1690 * @internal volume package internal use only.
1693 VPreAttachVolumeByName_r(Error * ec, char *partition, char *name)
1695 return VPreAttachVolumeById_r(ec,
1697 VolumeNumber(name));
1701 * pre-attach a volume given its path and numeric volume id.
1703 * @param[out] ec error code return
1704 * @param[in] partition path to vice partition
1705 * @param[in] volumeId numeric volume id
1707 * @return volume object pointer
1709 * @pre VOL_LOCK held
1711 * @internal volume package internal use only.
1714 VPreAttachVolumeById_r(Error * ec,
1719 struct DiskPartition64 *partp;
1723 assert(programType == fileServer);
1725 if (!(partp = VGetPartition_r(partition, 0))) {
1727 Log("VPreAttachVolumeById_r: Error getting partition (%s)\n", partition);
1731 vp = VLookupVolume_r(ec, volumeId, NULL);
1736 return VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
1740 * preattach a volume.
1742 * @param[out] ec outbound error code
1743 * @param[in] partp pointer to partition object
1744 * @param[in] vp pointer to volume object
1745 * @param[in] vid volume id
1747 * @return volume object pointer
1749 * @pre VOL_LOCK is held.
1751 * @warning Returned volume object pointer does not have to
1752 * equal the pointer passed in as argument vp. There
1753 * are potential race conditions which can result in
1754 * the pointers having different values. It is up to
1755 * the caller to make sure that references are handled
1756 * properly in this case.
1758 * @note If there is already a volume object registered with
1759 * the same volume id, its pointer MUST be passed as
1760 * argument vp. Failure to do so will result in a silent
1761 * failure to preattach.
1763 * @internal volume package internal use only.
1766 VPreAttachVolumeByVp_r(Error * ec,
1767 struct DiskPartition64 * partp,
1775 /* check to see if pre-attach already happened */
1777 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1778 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
1779 !VIsErrorState(V_attachState(vp))) {
1781 * pre-attach is a no-op in all but the following cases:
1783 * - volume is unattached
1784 * - volume is in an error state
1785 * - volume is pre-attached
1787 Log("VPreattachVolumeByVp_r: volume %u not in quiescent state\n", vid);
1790 /* we're re-attaching a volume; clear out some old state */
1791 memset(&vp->salvage, 0, sizeof(struct VolumeOnlineSalvage));
1793 if (V_partition(vp) != partp) {
1794 /* XXX potential race */
1795 DeleteVolumeFromVByPList_r(vp);
1798 /* if we need to allocate a new Volume struct,
1799 * go ahead and drop the vol glock, otherwise
1800 * do the basic setup synchronised, as it's
1801 * probably not worth dropping the lock */
1804 /* allocate the volume structure */
1805 vp = nvp = (Volume *) malloc(sizeof(Volume));
1807 memset(vp, 0, sizeof(Volume));
1808 queue_Init(&vp->vnode_list);
1809 assert(pthread_cond_init(&V_attachCV(vp), NULL) == 0);
1812 /* link the volume with its associated vice partition */
1813 vp->device = partp->device;
1814 vp->partition = partp;
1817 vp->specialStatus = 0;
1819 /* if we dropped the lock, reacquire the lock,
1820 * check for pre-attach races, and then add
1821 * the volume to the hash table */
1824 nvp = VLookupVolume_r(ec, vid, NULL);
1829 } else if (nvp) { /* race detected */
1834 /* hack to make up for VChangeState_r() decrementing
1835 * the old state counter */
1836 VStats.state_levels[0]++;
1840 /* put pre-attached volume onto the hash table
1841 * and bring it up to the pre-attached state */
1842 AddVolumeToHashTable(vp, vp->hashid);
1843 AddVolumeToVByPList_r(vp);
1844 VLRU_Init_Node_r(vp);
1845 VChangeState_r(vp, VOL_STATE_PREATTACHED);
1848 Log("VPreAttachVolumeByVp_r: volume %u pre-attached\n", vp->hashid);
1856 #endif /* AFS_DEMAND_ATTACH_FS */
1858 /* Attach an existing volume, given its pathname, and return a
1859 pointer to the volume header information. The volume also
1860 normally goes online at this time. An offline volume
1861 must be reattached to make it go online */
1863 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
1867 retVal = VAttachVolumeByName_r(ec, partition, name, mode);
1873 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
1875 register Volume *vp = NULL;
1876 struct DiskPartition64 *partp;
1880 #ifdef AFS_DEMAND_ATTACH_FS
1881 VolumeStats stats_save;
1883 #endif /* AFS_DEMAND_ATTACH_FS */
1887 volumeId = VolumeNumber(name);
1889 if (!(partp = VGetPartition_r(partition, 0))) {
1891 Log("VAttachVolume: Error getting partition (%s)\n", partition);
1895 if (VRequiresPartLock()) {
1897 VLockPartition_r(partition);
1898 } else if (programType == fileServer) {
1899 #ifdef AFS_DEMAND_ATTACH_FS
1900 /* lookup the volume in the hash table */
1901 vp = VLookupVolume_r(ec, volumeId, NULL);
1907 /* save any counters that are supposed to
1908 * be monotonically increasing over the
1909 * lifetime of the fileserver */
1910 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
1912 memset(&stats_save, 0, sizeof(VolumeStats));
1915 /* if there's something in the hash table, and it's not
1916 * in the pre-attach state, then we may need to detach
1917 * it before proceeding */
1918 if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1919 VCreateReservation_r(vp);
1920 VWaitExclusiveState_r(vp);
1922 /* at this point state must be one of:
1931 if (vp->specialStatus == VBUSY)
1934 /* if it's already attached, see if we can return it */
1935 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
1936 VGetVolumeByVp_r(ec, vp);
1937 if (V_inUse(vp) == fileServer) {
1938 VCancelReservation_r(vp);
1942 /* otherwise, we need to detach, and attempt to re-attach */
1943 VDetachVolume_r(ec, vp);
1945 Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
1948 /* if it isn't fully attached, delete from the hash tables,
1949 and let the refcounter handle the rest */
1950 DeleteVolumeFromHashTable(vp);
1951 DeleteVolumeFromVByPList_r(vp);
1954 VCancelReservation_r(vp);
1958 /* pre-attach volume if it hasn't been done yet */
1960 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
1961 (V_attachState(vp) == VOL_STATE_ERROR)) {
1963 vp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
1971 /* handle pre-attach races
1973 * multiple threads can race to pre-attach a volume,
1974 * but we can't let them race beyond that
1976 * our solution is to let the first thread to bring
1977 * the volume into an exclusive state win; the other
1978 * threads just wait until it finishes bringing the
1979 * volume online, and then they do a vgetvolumebyvp
1981 if (svp && (svp != vp)) {
1982 /* wait for other exclusive ops to finish */
1983 VCreateReservation_r(vp);
1984 VWaitExclusiveState_r(vp);
1986 /* get a heavyweight ref, kill the lightweight ref, and return */
1987 VGetVolumeByVp_r(ec, vp);
1988 VCancelReservation_r(vp);
1992 /* at this point, we are chosen as the thread to do
1993 * demand attachment for this volume. all other threads
1994 * doing a getvolume on vp->hashid will block until we finish */
1996 /* make sure any old header cache entries are invalidated
1997 * before proceeding */
1998 FreeVolumeHeader(vp);
2000 VChangeState_r(vp, VOL_STATE_ATTACHING);
2002 /* restore any saved counters */
2003 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2004 #else /* AFS_DEMAND_ATTACH_FS */
2005 vp = VGetVolume_r(ec, volumeId);
2007 if (V_inUse(vp) == fileServer)
2009 if (vp->specialStatus == VBUSY)
2011 VDetachVolume_r(ec, vp);
2013 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2017 #endif /* AFS_DEMAND_ATTACH_FS */
2021 strcpy(path, VPartitionPath(partp));
2029 vp = (Volume *) calloc(1, sizeof(Volume));
2031 vp->hashid = volumeId;
2032 vp->device = partp->device;
2033 vp->partition = partp;
2034 queue_Init(&vp->vnode_list);
2035 #ifdef AFS_DEMAND_ATTACH_FS
2036 assert(pthread_cond_init(&V_attachCV(vp), NULL) == 0);
2037 #endif /* AFS_DEMAND_ATTACH_FS */
2040 /* attach2 is entered without any locks, and returns
2041 * with vol_glock_mutex held */
2042 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode);
2044 if (VCanUseFSSYNC() && vp) {
2045 if ((mode == V_VOLUPD) || (VolumeWriteable(vp) && (mode == V_CLONE))) {
2046 /* mark volume header as in use so that volser crashes lead to a
2047 * salvage attempt */
2048 VUpdateVolume_r(ec, vp, 0);
2050 #ifdef AFS_DEMAND_ATTACH_FS
2051 /* for dafs, we should tell the fileserver, except for V_PEEK
2052 * where we know it is not necessary */
2053 if (mode == V_PEEK) {
2054 vp->needsPutBack = 0;
2056 vp->needsPutBack = 1;
2058 #else /* !AFS_DEMAND_ATTACH_FS */
2059 /* duplicate computation in fssync.c about whether the server
2060 * takes the volume offline or not. If the volume isn't
2061 * offline, we must not return it when we detach the volume,
2062 * or the server will abort */
2063 if (mode == V_READONLY || mode == V_PEEK
2064 || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
2065 vp->needsPutBack = 0;
2067 vp->needsPutBack = 1;
2068 #endif /* !AFS_DEMAND_ATTACH_FS */
2070 /* OK, there's a problem here, but one that I don't know how to
2071 * fix right now, and that I don't think should arise often.
2072 * Basically, we should only put back this volume to the server if
2073 * it was given to us by the server, but since we don't have a vp,
2074 * we can't run the VolumeWriteable function to find out as we do
2075 * above when computing vp->needsPutBack. So we send it back, but
2076 * there's a path in VAttachVolume on the server which may abort
2077 * if this volume doesn't have a header. Should be pretty rare
2078 * for all of that to happen, but if it does, probably the right
2079 * fix is for the server to allow the return of readonly volumes
2080 * that it doesn't think are really checked out. */
2081 #ifdef FSSYNC_BUILD_CLIENT
2082 if (VCanUseFSSYNC() && vp == NULL &&
2083 mode != V_SECRETLY && mode != V_PEEK) {
2085 #ifdef AFS_DEMAND_ATTACH_FS
2086 /* If we couldn't attach but we scheduled a salvage, we already
2087 * notified the fileserver; don't online it now */
2088 if (*ec != VSALVAGING)
2089 #endif /* AFS_DEMAND_ATTACH_FS */
2090 FSYNC_VolOp(volumeId, partition, FSYNC_VOL_ON, 0, NULL);
2093 if (programType == fileServer && vp) {
2094 #ifdef AFS_DEMAND_ATTACH_FS
2096 * we can get here in cases where we don't "own"
2097 * the volume (e.g. volume owned by a utility).
2098 * short circuit around potential disk header races.
2100 if (V_attachState(vp) != VOL_STATE_ATTACHED) {
2104 V_needsCallback(vp) = 0;
2106 if (VInit >= 2 && V_BreakVolumeCallbacks) {
2107 Log("VAttachVolume: Volume %u was changed externally; breaking callbacks\n", V_id(vp));
2108 (*V_BreakVolumeCallbacks) (V_id(vp));
2111 VUpdateVolume_r(ec, vp, 0);
2113 Log("VAttachVolume: Error updating volume\n");
2118 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2119 #ifndef AFS_DEMAND_ATTACH_FS
2120 /* This is a hack: by temporarily setting the incore
2121 * dontSalvage flag ON, the volume will be put back on the
2122 * Update list (with dontSalvage OFF again). It will then
2123 * come back in N minutes with DONT_SALVAGE eventually
2124 * set. This is the way that volumes that have never had
2125 * it set get it set; or that volumes that have been
2126 * offline without DONT SALVAGE having been set also
2127 * eventually get it set */
2128 V_dontSalvage(vp) = DONT_SALVAGE;
2129 #endif /* !AFS_DEMAND_ATTACH_FS */
2130 VAddToVolumeUpdateList_r(ec, vp);
2132 Log("VAttachVolume: Error adding volume to update list\n");
2139 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2144 if (VRequiresPartLock()) {
2145 VUnlockPartition_r(partition);
2148 #ifdef AFS_DEMAND_ATTACH_FS
2149 /* attach failed; make sure we're in error state */
2150 if (vp && !VIsErrorState(V_attachState(vp))) {
2151 VChangeState_r(vp, VOL_STATE_ERROR);
2153 #endif /* AFS_DEMAND_ATTACH_FS */
2160 #ifdef AFS_DEMAND_ATTACH_FS
2161 /* VAttachVolumeByVp_r
2163 * finish attaching a volume that is
2164 * in a less than fully attached state
2166 /* caller MUST hold a ref count on vp */
2168 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
2170 char name[VMAXPATHLEN];
2172 struct DiskPartition64 *partp;
2176 Volume * nvp = NULL;
2177 VolumeStats stats_save;
2180 /* volume utility should never call AttachByVp */
2181 assert(programType == fileServer);
2183 volumeId = vp->hashid;
2184 partp = vp->partition;
2185 VolumeExternalName_r(volumeId, name, sizeof(name));
2188 /* if another thread is performing a blocking op, wait */
2189 VWaitExclusiveState_r(vp);
2191 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2193 /* if it's already attached, see if we can return it */
2194 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2195 VGetVolumeByVp_r(ec, vp);
2196 if (V_inUse(vp) == fileServer) {
2199 if (vp->specialStatus == VBUSY)
2201 VDetachVolume_r(ec, vp);
2203 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2209 /* pre-attach volume if it hasn't been done yet */
2211 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2212 (V_attachState(vp) == VOL_STATE_ERROR)) {
2213 nvp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2219 VCreateReservation_r(nvp);
2225 VChangeState_r(vp, VOL_STATE_ATTACHING);
2227 /* restore monotonically increasing stats */
2228 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2232 /* compute path to disk header */
2233 strcpy(path, VPartitionPath(partp));
2242 * NOTE: attach2 is entered without any locks, and returns
2243 * with vol_glock_mutex held */
2244 vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode);
2247 * the event that an error was encountered, or
2248 * the volume was not brought to an attached state
2249 * for any reason, skip to the end. We cannot
2250 * safely call VUpdateVolume unless we "own" it.
2254 (V_attachState(vp) != VOL_STATE_ATTACHED)) {
2258 V_needsCallback(vp) = 0;
2259 VUpdateVolume_r(ec, vp, 0);
2261 Log("VAttachVolume: Error updating volume %u\n", vp->hashid);
2265 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2266 #ifndef AFS_DEMAND_ATTACH_FS
2267 /* This is a hack: by temporarily setting the incore
2268 * dontSalvage flag ON, the volume will be put back on the
2269 * Update list (with dontSalvage OFF again). It will then
2270 * come back in N minutes with DONT_SALVAGE eventually
2271 * set. This is the way that volumes that have never had
2272 * it set get it set; or that volumes that have been
2273 * offline without DONT SALVAGE having been set also
2274 * eventually get it set */
2275 V_dontSalvage(vp) = DONT_SALVAGE;
2276 #endif /* !AFS_DEMAND_ATTACH_FS */
2277 VAddToVolumeUpdateList_r(ec, vp);
2279 Log("VAttachVolume: Error adding volume %u to update list\n", vp->hashid);
2286 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2290 VCancelReservation_r(nvp);
2293 if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2294 if (vp && !VIsErrorState(V_attachState(vp))) {
2295 VChangeState_r(vp, VOL_STATE_ERROR);
2304 * lock a volume on disk (non-blocking).
2306 * @param[in] vp The volume to lock
2307 * @param[in] locktype READ_LOCK or WRITE_LOCK
2309 * @return operation status
2310 * @retval 0 success, lock was obtained
2311 * @retval EBUSY a conflicting lock was held by another process
2312 * @retval EIO error acquiring lock
2314 * @pre If we're in the fileserver, vp is in an exclusive state
2316 * @pre vp is not already locked
2319 VLockVolumeNB(Volume *vp, int locktype)
2323 assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2324 assert(!(V_attachFlags(vp) & VOL_LOCKED));
2326 code = VLockVolumeByIdNB(vp->hashid, vp->partition, locktype);
2328 V_attachFlags(vp) |= VOL_LOCKED;
2335 * unlock a volume on disk that was locked with VLockVolumeNB.
2337 * @param[in] vp volume to unlock
2339 * @pre If we're in the fileserver, vp is in an exclusive state
2341 * @pre vp has already been locked
2344 VUnlockVolume(Volume *vp)
2346 assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2347 assert((V_attachFlags(vp) & VOL_LOCKED));
2349 VUnlockVolumeById(vp->hashid, vp->partition);
2351 V_attachFlags(vp) &= ~VOL_LOCKED;
2353 #endif /* AFS_DEMAND_ATTACH_FS */
2356 * read in a vol header, possibly lock the vol header, and possibly check out
2357 * the vol header from the fileserver, as part of volume attachment.
2359 * @param[out] ec error code
2360 * @param[in] vp volume pointer object
2361 * @param[in] partp disk partition object of the attaching partition
2362 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
2364 * @param[in] peek 1 to just try to read in the volume header and make sure
2365 * we don't try to lock the vol, or check it out from
2366 * FSSYNC or anything like that; 0 otherwise, for 'normal'
2369 * @note As part of DAFS volume attachment, the volume header may be either
2370 * read- or write-locked to ensure mutual exclusion of certain volume
2371 * operations. In some cases in order to determine whether we need to
2372 * read- or write-lock the header, we need to read in the header to see
2373 * if the volume is RW or not. So, if we read in the header under a
2374 * read-lock and determine that we actually need a write-lock on the
2375 * volume header, this function will drop the read lock, acquire a write
2376 * lock, and read the header in again.
2379 attach_volume_header(Error *ec, Volume *vp, struct DiskPartition64 *partp,
2382 struct VolumeDiskHeader diskHeader;
2383 struct VolumeHeader header;
2386 int lock_tries = 0, checkout_tries = 0;
2388 VolumeId volid = vp->hashid;
2389 #ifdef FSSYNC_BUILD_CLIENT
2390 int checkout, done_checkout = 0;
2391 #endif /* FSSYNC_BUILD_CLIENT */
2392 #ifdef AFS_DEMAND_ATTACH_FS
2393 int locktype = 0, use_locktype = -1;
2394 #endif /* AFS_DEMAND_ATTACH_FS */
2400 if (lock_tries > VOL_MAX_CHECKOUT_RETRIES) {
2401 Log("VAttachVolume: retried too many times trying to lock header for "
2402 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2403 VPartitionPath(partp));
2407 if (checkout_tries > VOL_MAX_CHECKOUT_RETRIES) {
2408 Log("VAttachVolume: retried too many times trying to checkout "
2409 "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2410 VPartitionPath(partp));
2415 if (VReadVolumeDiskHeader(volid, partp, NULL)) {
2416 /* short-circuit the 'volume does not exist' case */
2421 #ifdef FSSYNC_BUILD_CLIENT
2422 checkout = !done_checkout;
2424 if (!peek && checkout && VMustCheckoutVolume(mode)) {
2426 memset(&res, 0, sizeof(res));
2428 if (FSYNC_VolOp(volid, VPartitionPath(partp), FSYNC_VOL_NEEDVOLUME, mode, &res)
2431 if (res.hdr.reason == FSYNC_SALVAGE) {
2432 Log("VAttachVolume: file server says volume %lu is salvaging\n",
2433 afs_printable_uint32_lu(volid));
2436 Log("VAttachVolume: attach of volume %lu apparently denied by file server\n",
2437 afs_printable_uint32_lu(volid));
2438 *ec = VNOVOL; /* XXXX */
2445 #ifdef AFS_DEMAND_ATTACH_FS
2446 if (use_locktype < 0) {
2447 /* don't know whether vol is RO or RW; assume it's RO and we can retry
2448 * if it turns out to be RW */
2449 locktype = VVolLockType(mode, 0);
2452 /* a previous try says we should use use_locktype to lock the volume,
2454 locktype = use_locktype;
2457 if (!peek && locktype) {
2458 code = VLockVolumeNB(vp, locktype);
2460 if (code == EBUSY) {
2461 Log("VAttachVolume: another program has vol %lu locked\n",
2462 afs_printable_uint32_lu(volid));
2464 Log("VAttachVolume: error %d trying to lock vol %lu\n",
2465 code, afs_printable_uint32_lu(volid));
2472 #endif /* AFS_DEMAND_ATTACH_FS */
2474 code = VReadVolumeDiskHeader(volid, partp, &diskHeader);
2484 DiskToVolumeHeader(&header, &diskHeader);
2486 IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header.parent,
2487 header.largeVnodeIndex);
2488 IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header.parent,
2489 header.smallVnodeIndex);
2490 IH_INIT(vp->diskDataHandle, partp->device, header.parent,
2492 IH_INIT(vp->linkHandle, partp->device, header.parent, header.linkTable);
2495 /* only need to do this once */
2497 GetVolumeHeader(vp);
2501 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2502 /* demand attach changes the V_PEEK mechanism
2504 * we can now suck the current disk data structure over
2505 * the fssync interface without going to disk
2507 * (technically, we don't need to restrict this feature
2508 * to demand attach fileservers. However, I'm trying
2509 * to limit the number of common code changes)
2511 if (VCanUseFSSYNC() && (mode == V_PEEK || peek)) {
2513 res.payload.len = sizeof(VolumeDiskData);
2514 res.payload.buf = &vp->header->diskstuff;
2516 if (FSYNC_VolOp(vp->hashid,
2518 FSYNC_VOL_QUERY_HDR,
2521 goto disk_header_loaded;
2524 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2525 (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2526 sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2528 #ifdef AFS_DEMAND_ATTACH_FS
2531 IncUInt64(&VStats.hdr_loads);
2532 IncUInt64(&vp->stats.hdr_loads);
2534 #endif /* AFS_DEMAND_ATTACH_FS */
2537 Log("VAttachVolume: Error reading diskDataHandle header for vol %lu; "
2538 "error=%u\n", afs_printable_uint32_lu(volid), *ec);
2542 #ifdef AFS_DEMAND_ATTACH_FS
2543 # ifdef FSSYNC_BUILD_CLIENT
2545 # endif /* FSSYNC_BUILD_CLIENT */
2547 /* if the lock type we actually used to lock the volume is different than
2548 * the lock type we should have used, retry with the lock type we should
2550 use_locktype = VVolLockType(mode, VolumeWriteable(vp));
2551 if (locktype != use_locktype) {
2555 #endif /* AFS_DEMAND_ATTACH_FS */
2560 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2561 if (!peek && *ec == 0 && retry == 0 && VMustCheckoutVolume(mode)) {
2563 code = FSYNC_VerifyCheckout(volid, VPartitionPath(partp), FSYNC_VOL_NEEDVOLUME, mode);
2565 if (code == SYNC_DENIED) {
2566 /* must retry checkout; fileserver no longer thinks we have
2572 } else if (code != SYNC_OK) {
2576 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2579 /* either we are going to be called again for a second pass, or we
2580 * encountered an error; clean up in either case */
2582 #ifdef AFS_DEMAND_ATTACH_FS
2583 if ((V_attachFlags(vp) & VOL_LOCKED)) {
2586 #endif /* AFS_DEMAND_ATTACH_FS */
2587 if (vp->linkHandle) {
2588 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
2589 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
2590 IH_RELEASE(vp->diskDataHandle);
2591 IH_RELEASE(vp->linkHandle);
2604 #ifdef AFS_DEMAND_ATTACH_FS
2606 attach_check_vop(Error *ec, VolumeId volid, struct DiskPartition64 *partp,
2611 if (vp->pending_vol_op) {
2615 if (vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningUnknown) {
2617 code = VVolOpLeaveOnlineNoHeader_r(vp, vp->pending_vol_op);
2619 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
2620 } else if (code == 0) {
2621 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
2624 /* we need the vol header to determine if the volume can be
2625 * left online for the vop, so... get the header */
2629 /* attach header with peek=1 to avoid checking out the volume
2630 * or locking it; we just want the header info, we're not
2631 * messing with the volume itself at all */
2632 attach_volume_header(ec, vp, partp, V_PEEK, 1);
2639 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
2640 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
2642 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
2645 /* make sure we grab a new vol header and re-open stuff on
2646 * actual attachment; we can't keep the data we grabbed, since
2647 * it was not done under a lock and thus not safe */
2648 FreeVolumeHeader(vp);
2649 VReleaseVolumeHandles_r(vp);
2652 /* see if the pending volume op requires exclusive access */
2653 switch (vp->pending_vol_op->vol_op_state) {
2654 case FSSYNC_VolOpPending:
2655 /* this should never happen */
2656 assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpPending);
2659 case FSSYNC_VolOpRunningUnknown:
2660 /* this should never happen; we resolved 'unknown' above */
2661 assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
2664 case FSSYNC_VolOpRunningOffline:
2665 /* mark the volume down */
2667 VChangeState_r(vp, VOL_STATE_UNATTACHED);
2669 /* do not set V_offlineMessage here; we don't have ownership of
2670 * the volume (and probably do not have the header loaded), so we
2671 * can't alter the disk header */
2673 /* check to see if we should set the specialStatus flag */
2674 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
2675 vp->specialStatus = VBUSY;
2686 #endif /* AFS_DEMAND_ATTACH_FS */
2689 * volume attachment helper function.
2691 * @param[out] ec error code
2692 * @param[in] volumeId volume ID of the attaching volume
2693 * @param[in] path full path to the volume header .vol file
2694 * @param[in] partp disk partition object for the attaching partition
2695 * @param[in] vp volume object; vp->hashid, vp->device, vp->partition,
2696 * vp->vnode_list, and V_attachCV (for DAFS) should already
2698 * @param[in] isbusy 1 if vp->specialStatus should be set to VBUSY; that is,
2699 * if there is a volume operation running for this volume
2700 * that should set the volume to VBUSY during its run. 0
2701 * otherwise. (see VVolOpSetVBusy_r)
2702 * @param[in] mode attachment mode such as V_VOLUPD, V_DUMP, etc (see
2705 * @return pointer to the semi-attached volume pointer
2706 * @retval NULL an error occurred (check value of *ec)
2707 * @retval vp volume successfully attaching
2709 * @pre no locks held
2711 * @post VOL_LOCK held
2714 attach2(Error * ec, VolId volumeId, char *path, struct DiskPartition64 *partp,
2715 Volume * vp, int isbusy, int mode)
2717 /* have we read in the header successfully? */
2718 int read_header = 0;
2720 /* should we FreeVolume(vp) instead of VCheckFree(vp) in the error
2726 vp->vnodeIndex[vLarge].handle = NULL;
2727 vp->vnodeIndex[vSmall].handle = NULL;
2728 vp->diskDataHandle = NULL;
2729 vp->linkHandle = NULL;
2731 #ifdef AFS_DEMAND_ATTACH_FS
2732 attach_check_vop(ec, volumeId, partp, vp);
2734 attach_volume_header(ec, vp, partp, mode, 0);
2737 attach_volume_header(ec, vp, partp, mode, 0);
2738 #endif /* !AFS_DEMAND_ATTACH_FS */
2740 if (*ec == VNOVOL) {
2741 /* if the volume doesn't exist, skip straight to 'error' so we don't
2742 * request a salvage */
2749 vp->specialStatus = (byte) (isbusy ? VBUSY : 0);
2750 vp->shuttingDown = 0;
2751 vp->goingOffline = 0;
2753 #ifdef AFS_DEMAND_ATTACH_FS
2754 vp->stats.last_attach = FT_ApproxTime();
2755 vp->stats.attaches++;
2759 IncUInt64(&VStats.attaches);
2760 vp->cacheCheck = ++VolumeCacheCheck;
2761 /* just in case this ever rolls over */
2762 if (!vp->cacheCheck)
2763 vp->cacheCheck = ++VolumeCacheCheck;
2766 #ifdef AFS_DEMAND_ATTACH_FS
2767 V_attachFlags(vp) |= VOL_HDR_LOADED;
2768 vp->stats.last_hdr_load = vp->stats.last_attach;
2769 #endif /* AFS_DEMAND_ATTACH_FS */
2773 struct IndexFileHeader iHead;
2775 #if OPENAFS_VOL_STATS
2777 * We just read in the diskstuff part of the header. If the detailed
2778 * volume stats area has not yet been initialized, we should bzero the
2779 * area and mark it as initialized.
2781 if (!(V_stat_initialized(vp))) {
2782 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
2783 V_stat_initialized(vp) = 1;
2785 #endif /* OPENAFS_VOL_STATS */
2787 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
2788 (char *)&iHead, sizeof(iHead),
2789 SMALLINDEXMAGIC, SMALLINDEXVERSION);
2792 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
2797 struct IndexFileHeader iHead;
2799 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
2800 (char *)&iHead, sizeof(iHead),
2801 LARGEINDEXMAGIC, LARGEINDEXVERSION);
2804 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
2808 #ifdef AFS_NAMEI_ENV
2810 struct versionStamp stamp;
2812 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
2813 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
2816 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
2819 #endif /* AFS_NAMEI_ENV */
2821 #if defined(AFS_DEMAND_ATTACH_FS)
2822 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
2824 if (!VCanScheduleSalvage()) {
2825 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
2827 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2832 /* volume operation in progress */
2836 #else /* AFS_DEMAND_ATTACH_FS */
2838 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
2842 #endif /* AFS_DEMAND_ATTACH_FS */
2844 if (V_needsSalvaged(vp)) {
2845 if (vp->specialStatus)
2846 vp->specialStatus = 0;
2848 #if defined(AFS_DEMAND_ATTACH_FS)
2849 if (!VCanScheduleSalvage()) {
2850 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
2852 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
2855 #else /* AFS_DEMAND_ATTACH_FS */
2857 #endif /* AFS_DEMAND_ATTACH_FS */
2863 if (VShouldCheckInUse(mode)) {
2864 #ifndef FAST_RESTART
2865 if (V_inUse(vp) && VolumeWriteable(vp)) {
2866 if (!V_needsSalvaged(vp)) {
2867 V_needsSalvaged(vp) = 1;
2868 VUpdateVolume_r(ec, vp, 0);
2870 #if defined(AFS_DEMAND_ATTACH_FS)
2871 if (!VCanScheduleSalvage()) {
2872 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
2874 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
2877 #else /* AFS_DEMAND_ATTACH_FS */
2878 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
2880 #endif /* AFS_DEMAND_ATTACH_FS */
2884 #endif /* FAST_RESTART */
2886 if (programType == fileServer && V_destroyMe(vp) == DESTROY_ME) {
2887 /* Only check destroyMe if we are the fileserver, since the
2888 * volserver et al sometimes need to work with volumes with
2889 * destroyMe set. Examples are 'temporary' volumes the
2890 * volserver creates, and when we create a volume (destroyMe
2891 * is set on creation; sometimes a separate volserver
2892 * transaction is created to clear destroyMe).
2895 #if defined(AFS_DEMAND_ATTACH_FS)
2896 /* schedule a salvage so the volume goes away on disk */
2897 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2898 VChangeState_r(vp, VOL_STATE_ERROR);
2900 #endif /* AFS_DEMAND_ATTACH_FS */
2901 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
2908 vp->nextVnodeUnique = V_uniquifier(vp);
2909 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
2910 #ifndef BITMAP_LATER
2911 if (programType == fileServer && VolumeWriteable(vp)) {
2913 for (i = 0; i < nVNODECLASSES; i++) {
2914 VGetBitmap_r(ec, vp, i);
2916 #ifdef AFS_DEMAND_ATTACH_FS
2917 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2919 #endif /* AFS_DEMAND_ATTACH_FS */
2920 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
2926 #endif /* BITMAP_LATER */
2928 if (programType == fileServer) {
2929 if (vp->specialStatus)
2930 vp->specialStatus = 0;
2931 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
2932 V_inUse(vp) = fileServer;
2933 V_offlineMessage(vp)[0] = '\0';
2936 if ((mode != V_PEEK) && (mode != V_SECRETLY))
2937 V_inUse(vp) = programType;
2938 V_checkoutMode(vp) = mode;
2941 AddVolumeToHashTable(vp, V_id(vp));
2942 #ifdef AFS_DEMAND_ATTACH_FS
2943 if (VCanUnlockAttached() && (V_attachFlags(vp) & VOL_LOCKED)) {
2946 if ((programType != fileServer) ||
2947 (V_inUse(vp) == fileServer)) {
2948 AddVolumeToVByPList_r(vp);
2950 VChangeState_r(vp, VOL_STATE_ATTACHED);
2952 VChangeState_r(vp, VOL_STATE_UNATTACHED);
2959 #ifdef AFS_DEMAND_ATTACH_FS
2960 if (!VIsErrorState(V_attachState(vp))) {
2961 VChangeState_r(vp, VOL_STATE_ERROR);
2963 #endif /* AFS_DEMAND_ATTACH_FS */
2966 VReleaseVolumeHandles_r(vp);
2969 #ifdef AFS_DEMAND_ATTACH_FS
2976 #else /* !AFS_DEMAND_ATTACH_FS */
2978 #endif /* !AFS_DEMAND_ATTACH_FS */
2982 /* Attach an existing volume.
2983 The volume also normally goes online at this time.
2984 An offline volume must be reattached to make it go online.
2988 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
2992 retVal = VAttachVolume_r(ec, volumeId, mode);
2998 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
3001 VGetVolumePath(ec, volumeId, &part, &name);
3003 register Volume *vp;
3005 vp = VGetVolume_r(&error, volumeId);
3007 assert(V_inUse(vp) == 0);
3008 VDetachVolume_r(ec, vp);
3012 return VAttachVolumeByName_r(ec, part, name, mode);
3015 /* Increment a reference count to a volume, sans context swaps. Requires
3016 * possibly reading the volume header in from the disk, since there's
3017 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
3019 * N.B. This call can fail if we can't read in the header!! In this case
3020 * we still guarantee we won't context swap, but the ref count won't be
3021 * incremented (otherwise we'd violate the invariant).
3023 /* NOTE: with the demand attach fileserver extensions, the global lock
3024 * is dropped within VHold */
3025 #ifdef AFS_DEMAND_ATTACH_FS
3027 VHold_r(register Volume * vp)
3031 VCreateReservation_r(vp);
3032 VWaitExclusiveState_r(vp);
3034 LoadVolumeHeader(&error, vp);
3036 VCancelReservation_r(vp);
3040 VCancelReservation_r(vp);
3043 #else /* AFS_DEMAND_ATTACH_FS */
3045 VHold_r(register Volume * vp)
3049 LoadVolumeHeader(&error, vp);
3055 #endif /* AFS_DEMAND_ATTACH_FS */
3059 VHold(register Volume * vp)
3063 retVal = VHold_r(vp);
3070 /***************************************************/
3071 /* get and put volume routines */
3072 /***************************************************/
3075 * put back a heavyweight reference to a volume object.
3077 * @param[in] vp volume object pointer
3079 * @pre VOL_LOCK held
3081 * @post heavyweight volume reference put back.
3082 * depending on state, volume may have been taken offline,
3083 * detached, salvaged, freed, etc.
3085 * @internal volume package internal use only
3088 VPutVolume_r(register Volume * vp)
3090 assert(--vp->nUsers >= 0);
3091 if (vp->nUsers == 0) {
3093 ReleaseVolumeHeader(vp->header);
3094 #ifdef AFS_DEMAND_ATTACH_FS
3095 if (!VCheckDetach(vp)) {
3099 #else /* AFS_DEMAND_ATTACH_FS */
3101 #endif /* AFS_DEMAND_ATTACH_FS */
3106 VPutVolume(register Volume * vp)
3114 /* Get a pointer to an attached volume. The pointer is returned regardless
3115 of whether or not the volume is in service or on/off line. An error
3116 code, however, is returned with an indication of the volume's status */
3118 VGetVolume(Error * ec, Error * client_ec, VolId volumeId)
3122 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
3128 VGetVolume_r(Error * ec, VolId volumeId)
3130 return GetVolume(ec, NULL, volumeId, NULL, 0);
3133 /* try to get a volume we've previously looked up */
3134 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
3136 VGetVolumeByVp_r(Error * ec, Volume * vp)
3138 return GetVolume(ec, NULL, vp->hashid, vp, 0);
3141 /* private interface for getting a volume handle
3142 * volumeId must be provided.
3143 * hint is an optional parameter to speed up hash lookups
3144 * flags is not used at this time
3146 /* for demand attach fs, caller MUST NOT hold a ref count on hint */
3148 GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint, int flags)
3151 /* pull this profiling/debugging code out of regular builds */
3153 #define VGET_CTR_INC(x) x++
3154 unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
3155 0, V7 = 0, V8 = 0, V9 = 0;
3156 unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
3158 #define VGET_CTR_INC(x)
3160 #ifdef AFS_DEMAND_ATTACH_FS
3161 Volume *avp, * rvp = hint;
3165 * if VInit is zero, the volume package dynamic
3166 * data structures have not been initialized yet,
3167 * and we must immediately return an error
3173 *client_ec = VOFFLINE;
3178 #ifdef AFS_DEMAND_ATTACH_FS
3180 VCreateReservation_r(rvp);
3182 #endif /* AFS_DEMAND_ATTACH_FS */
3190 vp = VLookupVolume_r(ec, volumeId, vp);
3196 #ifdef AFS_DEMAND_ATTACH_FS
3197 if (rvp && (rvp != vp)) {
3198 /* break reservation on old vp */
3199 VCancelReservation_r(rvp);
3202 #endif /* AFS_DEMAND_ATTACH_FS */
3208 /* Until we have reached an initialization level of 2
3209 * we don't know whether this volume exists or not.
3210 * We can't sleep and retry later because before a volume
3211 * is attached, the caller tries to get it first. Just
3212 * return VOFFLINE and the caller can choose whether to
3213 * retry the command or not. */
3223 IncUInt64(&VStats.hdr_gets);
3225 #ifdef AFS_DEMAND_ATTACH_FS
3226 /* block if someone else is performing an exclusive op on this volume */
3229 VCreateReservation_r(rvp);
3231 VWaitExclusiveState_r(vp);
3233 /* short circuit with VNOVOL in the following circumstances:
3236 * - VOL_STATE_SHUTTING_DOWN
3238 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
3239 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN) ||
3240 (V_attachState(vp) == VOL_STATE_GOING_OFFLINE)) {
3247 * short circuit with VOFFLINE in the following circumstances:
3249 * - VOL_STATE_UNATTACHED
3251 if (V_attachState(vp) == VOL_STATE_UNATTACHED) {
3252 if (vp->specialStatus) {
3253 *ec = vp->specialStatus;
3261 /* allowable states:
3267 if (vp->salvage.requested) {
3268 VUpdateSalvagePriority_r(vp);
3271 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
3272 avp = VAttachVolumeByVp_r(ec, vp, 0);
3275 /* VAttachVolumeByVp_r can return a pointer
3276 * != the vp passed to it under certain
3277 * conditions; make sure we don't leak
3278 * reservations if that happens */
3280 VCancelReservation_r(rvp);
3282 VCreateReservation_r(rvp);
3292 if (!vp->pending_vol_op) {
3307 if ((V_attachState(vp) == VOL_STATE_SALVAGING) ||
3308 (*ec == VSALVAGING)) {
3310 /* see CheckVnode() in afsfileprocs.c for an explanation
3311 * of this error code logic */
3312 afs_uint32 now = FT_ApproxTime();
3313 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
3316 *client_ec = VRESTARTING;
3325 #ifdef AFS_DEMAND_ATTACH_FS
3327 * this test MUST happen after VAttachVolymeByVp, so vol_op_state is
3328 * not VolOpRunningUnknown (attach2 would have converted it to Online
3332 /* only valid before/during demand attachment */
3333 assert(!vp->pending_vol_op || vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
3335 /* deny getvolume due to running mutually exclusive vol op */
3336 if (vp->pending_vol_op && vp->pending_vol_op->vol_op_state==FSSYNC_VolOpRunningOffline) {
3338 * volume cannot remain online during this volume operation.
3341 if (vp->specialStatus) {
3343 * special status codes outrank normal VOFFLINE code
3345 *ec = vp->specialStatus;
3347 *client_ec = vp->specialStatus;
3351 /* see CheckVnode() in afsfileprocs.c for an explanation
3352 * of this error code logic */
3353 afs_uint32 now = FT_ApproxTime();
3354 if ((vp->stats.last_vol_op + (10 * 60)) >= now) {
3357 *client_ec = VRESTARTING;
3362 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3363 FreeVolumeHeader(vp);
3367 #endif /* AFS_DEMAND_ATTACH_FS */
3369 LoadVolumeHeader(ec, vp);
3372 /* Only log the error if it was a totally unexpected error. Simply
3373 * a missing inode is likely to be caused by the volume being deleted */
3374 if (errno != ENXIO || LogLevel)
3375 Log("Volume %u: couldn't reread volume header\n",
3377 #ifdef AFS_DEMAND_ATTACH_FS
3378 if (VCanScheduleSalvage()) {
3379 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3384 #else /* AFS_DEMAND_ATTACH_FS */
3387 #endif /* AFS_DEMAND_ATTACH_FS */
3392 if (vp->shuttingDown) {
3399 if (programType == fileServer) {
3401 if (vp->goingOffline) {
3403 #ifdef AFS_DEMAND_ATTACH_FS
3404 /* wait for the volume to go offline */
3405 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
3406 VWaitStateChange_r(vp);
3408 #elif defined(AFS_PTHREAD_ENV)
3409 VOL_CV_WAIT(&vol_put_volume_cond);
3410 #else /* AFS_PTHREAD_ENV */
3411 LWP_WaitProcess(VPutVolume);
3412 #endif /* AFS_PTHREAD_ENV */
3415 if (vp->specialStatus) {
3417 *ec = vp->specialStatus;
3418 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3421 } else if (V_inUse(vp) == 0) {
3432 #ifdef AFS_DEMAND_ATTACH_FS
3433 /* if no error, bump nUsers */
3436 VLRU_UpdateAccess_r(vp);
3439 VCancelReservation_r(rvp);
3442 if (client_ec && !*client_ec) {
3445 #else /* AFS_DEMAND_ATTACH_FS */
3446 /* if no error, bump nUsers */
3453 #endif /* AFS_DEMAND_ATTACH_FS */
3461 /***************************************************/
3462 /* Volume offline/detach routines */
3463 /***************************************************/
3465 /* caller MUST hold a heavyweight ref on vp */
3466 #ifdef AFS_DEMAND_ATTACH_FS
3468 VTakeOffline_r(register Volume * vp)
3472 assert(vp->nUsers > 0);
3473 assert(programType == fileServer);
3475 VCreateReservation_r(vp);
3476 VWaitExclusiveState_r(vp);
3478 vp->goingOffline = 1;
3479 V_needsSalvaged(vp) = 1;
3481 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
3482 VCancelReservation_r(vp);
3484 #else /* AFS_DEMAND_ATTACH_FS */
3486 VTakeOffline_r(register Volume * vp)
3488 assert(vp->nUsers > 0);
3489 assert(programType == fileServer);
3491 vp->goingOffline = 1;
3492 V_needsSalvaged(vp) = 1;
3494 #endif /* AFS_DEMAND_ATTACH_FS */
3497 VTakeOffline(register Volume * vp)
3505 * force a volume offline.
3507 * @param[in] vp volume object pointer
3508 * @param[in] flags flags (see note below)
3510 * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
3511 * used when VUpdateVolume_r needs to call VForceOffline_r
3512 * (which in turn would normally call VUpdateVolume_r)
3514 * @see VUpdateVolume_r
3516 * @pre VOL_LOCK must be held.
3517 * for DAFS, caller must hold ref.
3519 * @note for DAFS, it _is safe_ to call this function from an
3522 * @post needsSalvaged flag is set.
3523 * for DAFS, salvage is requested.
3524 * no further references to the volume through the volume
3525 * package will be honored.
3526 * all file descriptor and vnode caches are invalidated.
3528 * @warning this is a heavy-handed interface. it results in
3529 * a volume going offline regardless of the current
3530 * reference count state.
3532 * @internal volume package internal use only
3535 VForceOffline_r(Volume * vp, int flags)
3539 #ifdef AFS_DEMAND_ATTACH_FS
3540 VChangeState_r(vp, VOL_STATE_ERROR);
3545 strcpy(V_offlineMessage(vp),
3546 "Forced offline due to internal error: volume needs to be salvaged");
3547 Log("Volume %u forced offline: it needs salvaging!\n", V_id(vp));
3550 vp->goingOffline = 0;
3551 V_needsSalvaged(vp) = 1;
3552 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
3553 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
3556 #ifdef AFS_DEMAND_ATTACH_FS
3557 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3558 #endif /* AFS_DEMAND_ATTACH_FS */
3560 #ifdef AFS_PTHREAD_ENV
3561 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3562 #else /* AFS_PTHREAD_ENV */
3563 LWP_NoYieldSignal(VPutVolume);
3564 #endif /* AFS_PTHREAD_ENV */
3566 VReleaseVolumeHandles_r(vp);
3570 * force a volume offline.
3572 * @param[in] vp volume object pointer
3574 * @see VForceOffline_r
3577 VForceOffline(Volume * vp)
3580 VForceOffline_r(vp, 0);
3584 /* The opposite of VAttachVolume. The volume header is written to disk, with
3585 the inUse bit turned off. A copy of the header is maintained in memory,
3586 however (which is why this is VOffline, not VDetach).
3589 VOffline_r(Volume * vp, char *message)
3591 #ifndef AFS_DEMAND_ATTACH_FS
3593 VolumeId vid = V_id(vp);
3596 assert(programType != volumeUtility && programType != volumeServer);
3601 if (V_offlineMessage(vp)[0] == '\0')
3602 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
3603 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
3605 vp->goingOffline = 1;
3606 #ifdef AFS_DEMAND_ATTACH_FS
3607 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
3608 VCreateReservation_r(vp);
3611 /* wait for the volume to go offline */
3612 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
3613 VWaitStateChange_r(vp);
3615 VCancelReservation_r(vp);
3616 #else /* AFS_DEMAND_ATTACH_FS */
3618 vp = VGetVolume_r(&error, vid); /* Wait for it to go offline */
3619 if (vp) /* In case it was reattached... */
3621 #endif /* AFS_DEMAND_ATTACH_FS */
3624 #ifdef AFS_DEMAND_ATTACH_FS
3626 * Take a volume offline in order to perform a volume operation.
3628 * @param[inout] ec address in which to store error code
3629 * @param[in] vp volume object pointer
3630 * @param[in] message volume offline status message
3633 * - VOL_LOCK is held
3634 * - caller MUST hold a heavyweight ref on vp
3637 * - volume is taken offline
3638 * - if possible, volume operation is promoted to running state
3639 * - on failure, *ec is set to nonzero
3641 * @note Although this function does not return any value, it may
3642 * still fail to promote our pending volume operation to
3643 * a running state. Any caller MUST check the value of *ec,
3644 * and MUST NOT blindly assume success.
3646 * @warning if the caller does not hold a lightweight ref on vp,
3647 * then it MUST NOT reference vp after this function
3648 * returns to the caller.
3650 * @internal volume package internal use only
3653 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
3655 assert(vp->pending_vol_op);
3661 if (V_offlineMessage(vp)[0] == '\0')
3662 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
3663 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
3665 vp->goingOffline = 1;
3666 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
3667 VCreateReservation_r(vp);
3670 /* Wait for the volume to go offline */
3671 while (!VIsOfflineState(V_attachState(vp))) {
3672 /* do not give corrupted volumes to the volserver */
3673 if (vp->salvage.requested && vp->pending_vol_op->com.programType != salvageServer) {
3677 VWaitStateChange_r(vp);
3681 VCancelReservation_r(vp);
3683 #endif /* AFS_DEMAND_ATTACH_FS */
3686 VOffline(Volume * vp, char *message)
3689 VOffline_r(vp, message);
3693 /* This gets used for the most part by utility routines that don't want
3694 * to keep all the volume headers around. Generally, the file server won't
3695 * call this routine, because then the offline message in the volume header
3696 * (or other information) won't be available to clients. For NAMEI, also
3697 * close the file handles. However, the fileserver does call this during
3698 * an attach following a volume operation.
3701 VDetachVolume_r(Error * ec, Volume * vp)
3704 struct DiskPartition64 *tpartp;
3705 int notifyServer = 0;
3706 int useDone = FSYNC_VOL_ON;
3708 *ec = 0; /* always "succeeds" */
3709 if (VCanUseFSSYNC()) {
3710 notifyServer = vp->needsPutBack;
3711 if (V_destroyMe(vp) == DESTROY_ME)
3712 useDone = FSYNC_VOL_DONE;
3713 #ifdef AFS_DEMAND_ATTACH_FS
3714 else if (!V_blessed(vp) || !V_inService(vp))
3715 useDone = FSYNC_VOL_LEAVE_OFF;
3718 tpartp = vp->partition;
3720 DeleteVolumeFromHashTable(vp);
3721 vp->shuttingDown = 1;
3722 #ifdef AFS_DEMAND_ATTACH_FS
3723 DeleteVolumeFromVByPList_r(vp);
3725 VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
3727 if (programType != fileServer)
3729 #endif /* AFS_DEMAND_ATTACH_FS */
3731 /* Will be detached sometime in the future--this is OK since volume is offline */
3733 /* XXX the following code should really be moved to VCheckDetach() since the volume
3734 * is not technically detached until the refcounts reach zero
3736 #ifdef FSSYNC_BUILD_CLIENT
3737 if (VCanUseFSSYNC() && notifyServer) {
3739 * Note: The server is not notified in the case of a bogus volume
3740 * explicitly to make it possible to create a volume, do a partial
3741 * restore, then abort the operation without ever putting the volume
3742 * online. This is essential in the case of a volume move operation
3743 * between two partitions on the same server. In that case, there
3744 * would be two instances of the same volume, one of them bogus,
3745 * which the file server would attempt to put on line
3747 FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
3748 /* XXX this code path is only hit by volume utilities, thus
3749 * V_BreakVolumeCallbacks will always be NULL. if we really
3750 * want to break callbacks in this path we need to use FSYNC_VolOp() */
3752 /* Dettaching it so break all callbacks on it */
3753 if (V_BreakVolumeCallbacks) {
3754 Log("volume %u detached; breaking all call backs\n", volume);
3755 (*V_BreakVolumeCallbacks) (volume);
3759 #endif /* FSSYNC_BUILD_CLIENT */
3763 VDetachVolume(Error * ec, Volume * vp)
3766 VDetachVolume_r(ec, vp);
3771 /***************************************************/
3772 /* Volume fd/inode handle closing routines */
3773 /***************************************************/
3775 /* For VDetachVolume, we close all cached file descriptors, but keep
3776 * the Inode handles in case we need to read from a busy volume.
3778 /* for demand attach, caller MUST hold ref count on vp */
3780 VCloseVolumeHandles_r(Volume * vp)
3782 #ifdef AFS_DEMAND_ATTACH_FS
3783 VolState state_save;
3785 state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
3790 * XXX need to investigate whether we can perform
3791 * DFlushVolume outside of vol_glock_mutex...
3793 * VCloseVnodeFiles_r drops the glock internally */
3794 DFlushVolume(vp->hashid);
3795 VCloseVnodeFiles_r(vp);
3797 #ifdef AFS_DEMAND_ATTACH_FS
3801 /* Too time consuming and unnecessary for the volserver */
3802 if (programType == fileServer) {
3803 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
3804 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
3805 IH_CONDSYNC(vp->diskDataHandle);
3807 IH_CONDSYNC(vp->linkHandle);
3808 #endif /* AFS_NT40_ENV */
3811 IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
3812 IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
3813 IH_REALLYCLOSE(vp->diskDataHandle);
3814 IH_REALLYCLOSE(vp->linkHandle);
3816 #ifdef AFS_DEMAND_ATTACH_FS
3817 if ((V_attachFlags(vp) & VOL_LOCKED)) {
3822 VChangeState_r(vp, state_save);
3826 /* For both VForceOffline and VOffline, we close all relevant handles.
3827 * For VOffline, if we re-attach the volume, the files may possible be
3828 * different than before.
3830 /* for demand attach, caller MUST hold a ref count on vp */
3832 VReleaseVolumeHandles_r(Volume * vp)
3834 #ifdef AFS_DEMAND_ATTACH_FS
3835 VolState state_save;
3837 state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
3840 /* XXX need to investigate whether we can perform
3841 * DFlushVolume outside of vol_glock_mutex... */
3842 DFlushVolume(vp->hashid);
3844 VReleaseVnodeFiles_r(vp); /* releases the glock internally */
3846 #ifdef AFS_DEMAND_ATTACH_FS
3850 /* Too time consuming and unnecessary for the volserver */
3851 if (programType == fileServer) {
3852 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
3853 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
3854 IH_CONDSYNC(vp->diskDataHandle);
3856 IH_CONDSYNC(vp->linkHandle);
3857 #endif /* AFS_NT40_ENV */
3860 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
3861 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
3862 IH_RELEASE(vp->diskDataHandle);
3863 IH_RELEASE(vp->linkHandle);
3865 #ifdef AFS_DEMAND_ATTACH_FS
3866 if ((V_attachFlags(vp) & VOL_LOCKED)) {
3871 VChangeState_r(vp, state_save);
3876 /***************************************************/
3877 /* Volume write and fsync routines */
3878 /***************************************************/
3881 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
3883 #ifdef AFS_DEMAND_ATTACH_FS
3884 VolState state_save;
3886 if (flags & VOL_UPDATE_WAIT) {
3887 VCreateReservation_r(vp);
3888 VWaitExclusiveState_r(vp);
3893 if (programType == fileServer)
3895 (V_inUse(vp) ? V_nextVnodeUnique(vp) +
3896 200 : V_nextVnodeUnique(vp));
3898 #ifdef AFS_DEMAND_ATTACH_FS
3899 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
3903 WriteVolumeHeader_r(ec, vp);
3905 #ifdef AFS_DEMAND_ATTACH_FS
3907 VChangeState_r(vp, state_save);
3908 if (flags & VOL_UPDATE_WAIT) {
3909 VCancelReservation_r(vp);
3914 Log("VUpdateVolume: error updating volume header, volume %u (%s)\n",
3915 V_id(vp), V_name(vp));
3916 /* try to update on-disk header,
3917 * while preventing infinite recursion */
3918 if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
3919 VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
3925 VUpdateVolume(Error * ec, Volume * vp)
3928 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
3933 VSyncVolume_r(Error * ec, Volume * vp, int flags)
3937 #ifdef AFS_DEMAND_ATTACH_FS
3938 VolState state_save;
3941 if (flags & VOL_SYNC_WAIT) {
3942 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
3944 VUpdateVolume_r(ec, vp, 0);
3947 #ifdef AFS_DEMAND_ATTACH_FS
3948 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
3951 fdP = IH_OPEN(V_diskDataHandle(vp));
3952 assert(fdP != NULL);
3953 code = FDH_SYNC(fdP);
3956 #ifdef AFS_DEMAND_ATTACH_FS
3958 VChangeState_r(vp, state_save);
3964 VSyncVolume(Error * ec, Volume * vp)
3967 VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
3972 /***************************************************/
3973 /* Volume dealloaction routines */
3974 /***************************************************/
3976 #ifdef AFS_DEMAND_ATTACH_FS
3978 FreeVolume(Volume * vp)
3980 /* free the heap space, iff it's safe.
3981 * otherwise, pull it out of the hash table, so it
3982 * will get deallocated when all refs to it go away */
3983 if (!VCheckFree(vp)) {
3984 DeleteVolumeFromHashTable(vp);
3985 DeleteVolumeFromVByPList_r(vp);
3987 /* make sure we invalidate the header cache entry */
3988 FreeVolumeHeader(vp);
3991 #endif /* AFS_DEMAND_ATTACH_FS */
3994 ReallyFreeVolume(Volume * vp)
3999 #ifdef AFS_DEMAND_ATTACH_FS
4001 VChangeState_r(vp, VOL_STATE_FREED);
4002 if (vp->pending_vol_op)
4003 free(vp->pending_vol_op);
4004 #endif /* AFS_DEMAND_ATTACH_FS */
4005 for (i = 0; i < nVNODECLASSES; i++)
4006 if (vp->vnodeIndex[i].bitmap)
4007 free(vp->vnodeIndex[i].bitmap);
4008 FreeVolumeHeader(vp);
4009 #ifndef AFS_DEMAND_ATTACH_FS
4010 DeleteVolumeFromHashTable(vp);
4011 #endif /* AFS_DEMAND_ATTACH_FS */
4015 /* check to see if we should shutdown this volume
4016 * returns 1 if volume was freed, 0 otherwise */
4017 #ifdef AFS_DEMAND_ATTACH_FS
4019 VCheckDetach(register Volume * vp)
4024 if (vp->nUsers || vp->nWaiters)
4027 if (vp->shuttingDown) {
4029 if ((programType != fileServer) &&
4030 (V_inUse(vp) == programType) &&
4031 ((V_checkoutMode(vp) == V_VOLUPD) ||
4032 (V_checkoutMode(vp) == V_SECRETLY) ||
4033 ((V_checkoutMode(vp) == V_CLONE) &&
4034 (VolumeWriteable(vp))))) {
4036 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
4038 Log("VCheckDetach: volume header update for volume %u "
4039 "failed with errno %d\n", vp->hashid, errno);
4042 VReleaseVolumeHandles_r(vp);
4044 ReallyFreeVolume(vp);
4045 if (programType == fileServer) {
4046 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
4051 #else /* AFS_DEMAND_ATTACH_FS */
4053 VCheckDetach(register Volume * vp)
4061 if (vp->shuttingDown) {
4063 if ((programType != fileServer) &&
4064 (V_inUse(vp) == programType) &&
4065 ((V_checkoutMode(vp) == V_VOLUPD) ||
4066 (V_checkoutMode(vp) == V_SECRETLY) ||
4067 ((V_checkoutMode(vp) == V_CLONE) &&
4068 (VolumeWriteable(vp))))) {
4070 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
4072 Log("VCheckDetach: volume header update for volume %u failed with errno %d\n",
4076 VReleaseVolumeHandles_r(vp);
4077 ReallyFreeVolume(vp);
4078 if (programType == fileServer) {
4079 #if defined(AFS_PTHREAD_ENV)
4080 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
4081 #else /* AFS_PTHREAD_ENV */
4082 LWP_NoYieldSignal(VPutVolume);
4083 #endif /* AFS_PTHREAD_ENV */
4088 #endif /* AFS_DEMAND_ATTACH_FS */
4090 /* check to see if we should offline this volume
4091 * return 1 if volume went offline, 0 otherwise */
4092 #ifdef AFS_DEMAND_ATTACH_FS
4094 VCheckOffline(register Volume * vp)
4098 if (vp->goingOffline && !vp->nUsers) {
4100 assert(programType == fileServer);
4101 assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
4102 (V_attachState(vp) != VOL_STATE_FREED) &&
4103 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
4104 (V_attachState(vp) != VOL_STATE_UNATTACHED));
4108 * VOL_STATE_GOING_OFFLINE
4109 * VOL_STATE_SHUTTING_DOWN
4110 * VIsErrorState(V_attachState(vp))
4111 * VIsExclusiveState(V_attachState(vp))
4114 VCreateReservation_r(vp);
4115 VChangeState_r(vp, VOL_STATE_OFFLINING);
4118 /* must clear the goingOffline flag before we drop the glock */
4119 vp->goingOffline = 0;
4124 /* perform async operations */
4125 VUpdateVolume_r(&error, vp, 0);
4126 VCloseVolumeHandles_r(vp);
4129 if (V_offlineMessage(vp)[0]) {
4130 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
4131 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
4132 V_offlineMessage(vp));
4134 Log("VOffline: Volume %lu (%s) is now offline\n",
4135 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
4139 /* invalidate the volume header cache entry */
4140 FreeVolumeHeader(vp);
4142 /* if nothing changed state to error or salvaging,
4143 * drop state to unattached */
4144 if (!VIsErrorState(V_attachState(vp))) {
4145 VChangeState_r(vp, VOL_STATE_UNATTACHED);
4147 VCancelReservation_r(vp);
4148 /* no usage of vp is safe beyond this point */
4152 #else /* AFS_DEMAND_ATTACH_FS */
4154 VCheckOffline(register Volume * vp)
4158 if (vp->goingOffline && !vp->nUsers) {
4160 assert(programType == fileServer);
4163 vp->goingOffline = 0;
4165 VUpdateVolume_r(&error, vp, 0);
4166 VCloseVolumeHandles_r(vp);
4168 Log("VOffline: Volume %u (%s) is now offline", V_id(vp),
4170 if (V_offlineMessage(vp)[0])
4171 Log(" (%s)", V_offlineMessage(vp));
4174 FreeVolumeHeader(vp);
4175 #ifdef AFS_PTHREAD_ENV
4176 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
4177 #else /* AFS_PTHREAD_ENV */
4178 LWP_NoYieldSignal(VPutVolume);
4179 #endif /* AFS_PTHREAD_ENV */
4183 #endif /* AFS_DEMAND_ATTACH_FS */
4185 /***************************************************/
4186 /* demand attach fs ref counting routines */
4187 /***************************************************/
4189 #ifdef AFS_DEMAND_ATTACH_FS
4190 /* the following two functions handle reference counting for
4191 * asynchronous operations on volume structs.
4193 * their purpose is to prevent a VDetachVolume or VShutdown
4194 * from free()ing the Volume struct during an async i/o op */
4196 /* register with the async volume op ref counter */
4197 /* VCreateReservation_r moved into inline code header because it
4198 * is now needed in vnode.c -- tkeiser 11/20/2007
4202 * decrement volume-package internal refcount.
4204 * @param vp volume object pointer
4206 * @internal volume package internal use only
4209 * @arg VOL_LOCK is held
4210 * @arg lightweight refcount held
4212 * @post volume waiters refcount is decremented; volume may
4213 * have been deallocated/shutdown/offlined/salvaged/
4214 * whatever during the process
4216 * @warning once you have tossed your last reference (you can acquire
4217 * lightweight refs recursively) it is NOT SAFE to reference
4218 * a volume object pointer ever again
4220 * @see VCreateReservation_r
4222 * @note DEMAND_ATTACH_FS only
4225 VCancelReservation_r(Volume * vp)
4227 assert(--vp->nWaiters >= 0);
4228 if (vp->nWaiters == 0) {
4230 if (!VCheckDetach(vp)) {
4237 /* check to see if we should free this volume now
4238 * return 1 if volume was freed, 0 otherwise */
4240 VCheckFree(Volume * vp)
4243 if ((vp->nUsers == 0) &&
4244 (vp->nWaiters == 0) &&
4245 !(V_attachFlags(vp) & (VOL_IN_HASH |
4249 ReallyFreeVolume(vp);
4254 #endif /* AFS_DEMAND_ATTACH_FS */
4257 /***************************************************/
4258 /* online volume operations routines */
4259 /***************************************************/
4261 #ifdef AFS_DEMAND_ATTACH_FS
4263 * register a volume operation on a given volume.
4265 * @param[in] vp volume object
4266 * @param[in] vopinfo volume operation info object
4268 * @pre VOL_LOCK is held
4270 * @post volume operation info object attached to volume object.
4271 * volume operation statistics updated.
4273 * @note by "attached" we mean a copy of the passed in object is made
4275 * @internal volume package internal use only
4278 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4280 FSSYNC_VolOp_info * info;
4282 /* attach a vol op info node to the volume struct */
4283 info = (FSSYNC_VolOp_info *) malloc(sizeof(FSSYNC_VolOp_info));
4284 assert(info != NULL);
4285 memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
4286 vp->pending_vol_op = info;
4289 vp->stats.last_vol_op = FT_ApproxTime();
4290 vp->stats.vol_ops++;
4291 IncUInt64(&VStats.vol_ops);
4297 * deregister the volume operation attached to this volume.
4299 * @param[in] vp volume object pointer
4301 * @pre VOL_LOCK is held
4303 * @post the volume operation info object is detached from the volume object
4305 * @internal volume package internal use only
4308 VDeregisterVolOp_r(Volume * vp)
4310 if (vp->pending_vol_op) {
4311 free(vp->pending_vol_op);
4312 vp->pending_vol_op = NULL;
4316 #endif /* AFS_DEMAND_ATTACH_FS */
4319 * determine whether it is safe to leave a volume online during
4320 * the volume operation described by the vopinfo object.
4322 * @param[in] vp volume object
4323 * @param[in] vopinfo volume operation info object
4325 * @return whether it is safe to leave volume online
4326 * @retval 0 it is NOT SAFE to leave the volume online
4327 * @retval 1 it is safe to leave the volume online during the operation
4330 * @arg VOL_LOCK is held
4331 * @arg disk header attached to vp (heavyweight ref on vp will guarantee
4332 * this condition is met)
4334 * @internal volume package internal use only
4337 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4339 return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
4340 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4341 (vopinfo->com.reason == V_READONLY ||
4342 (!VolumeWriteable(vp) &&
4343 (vopinfo->com.reason == V_CLONE ||
4344 vopinfo->com.reason == V_DUMP)))));
4348 * same as VVolOpLeaveOnline_r, but does not require a volume with an attached
4351 * @param[in] vp volume object
4352 * @param[in] vopinfo volume operation info object
4354 * @return whether it is safe to leave volume online
4355 * @retval 0 it is NOT SAFE to leave the volume online
4356 * @retval 1 it is safe to leave the volume online during the operation
4357 * @retval -1 unsure; volume header is required in order to know whether or
4358 * not is is safe to leave the volume online
4360 * @pre VOL_LOCK is held
4362 * @internal volume package internal use only
4365 VVolOpLeaveOnlineNoHeader_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4367 /* follow the logic in VVolOpLeaveOnline_r; this is the same, except
4368 * assume that we don't know VolumeWriteable; return -1 if the answer
4369 * depends on VolumeWriteable */
4371 if (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline) {
4374 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4375 vopinfo->com.reason == V_READONLY) {
4379 if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4380 (vopinfo->com.reason == V_CLONE ||
4381 vopinfo->com.reason == V_DUMP)) {
4383 /* must know VolumeWriteable */
4390 * determine whether VBUSY should be set during this volume operation.
4392 * @param[in] vp volume object
4393 * @param[in] vopinfo volume operation info object
4395 * @return whether VBUSY should be set
4396 * @retval 0 VBUSY does NOT need to be set
4397 * @retval 1 VBUSY SHOULD be set
4399 * @pre VOL_LOCK is held
4401 * @internal volume package internal use only
4404 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4406 return ((vopinfo->com.command == FSYNC_VOL_OFF &&
4407 vopinfo->com.reason == FSYNC_SALVAGE) ||
4408 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4409 (vopinfo->com.reason == V_CLONE ||
4410 vopinfo->com.reason == V_DUMP)));
4414 /***************************************************/
4415 /* online salvager routines */
4416 /***************************************************/
4417 #if defined(AFS_DEMAND_ATTACH_FS)
4419 * check whether a salvage needs to be performed on this volume.
4421 * @param[in] vp pointer to volume object
4423 * @return status code
4424 * @retval 0 no salvage scheduled
4425 * @retval 1 a salvage has been scheduled with the salvageserver
4427 * @pre VOL_LOCK is held
4429 * @post if salvage request flag is set and nUsers and nWaiters are zero,
4430 * then a salvage will be requested
4432 * @note this is one of the event handlers called by VCancelReservation_r
4434 * @see VCancelReservation_r
4436 * @internal volume package internal use only.
4439 VCheckSalvage(register Volume * vp)
4442 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
4443 if (vp->nUsers || vp->nWaiters)
4445 if (vp->salvage.requested) {
4446 VScheduleSalvage_r(vp);
4449 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
4454 * request volume salvage.
4456 * @param[out] ec computed client error code
4457 * @param[in] vp volume object pointer
4458 * @param[in] reason reason code (passed to salvageserver via SALVSYNC)
4459 * @param[in] flags see flags note below
4462 * VOL_SALVAGE_INVALIDATE_HEADER causes volume header cache entry
4463 * to be invalidated.
4465 * @pre VOL_LOCK is held.
4467 * @post volume state is changed.
4468 * for fileserver, salvage will be requested once refcount reaches zero.
4470 * @return operation status code
4471 * @retval 0 volume salvage will occur
4472 * @retval 1 volume salvage could not be scheduled
4476 * @note in the fileserver, this call does not synchronously schedule a volume
4477 * salvage. rather, it sets volume state so that when volume refcounts
4478 * reach zero, a volume salvage will occur. by "refcounts", we mean both
4479 * nUsers and nWaiters must be zero.
4481 * @internal volume package internal use only.
4484 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
4488 * for DAFS volume utilities that are not supposed to schedule salvages,
4489 * just transition to error state instead
4491 if (!VCanScheduleSalvage()) {
4492 VChangeState_r(vp, VOL_STATE_ERROR);
4497 if (programType != fileServer && !VCanUseFSSYNC()) {
4498 VChangeState_r(vp, VOL_STATE_ERROR);
4503 if (!vp->salvage.requested) {
4504 vp->salvage.requested = 1;
4505 vp->salvage.reason = reason;
4506 vp->stats.last_salvage = FT_ApproxTime();
4508 /* Note that it is not possible for us to reach this point if a
4509 * salvage is already running on this volume (even if the fileserver
4510 * was restarted during the salvage). If a salvage were running, the
4511 * salvager would have write-locked the volume header file, so when
4512 * we tried to lock the volume header, the lock would have failed,
4513 * and we would have failed during attachment prior to calling
4514 * VRequestSalvage. So we know that we can schedule salvages without
4515 * fear of a salvage already running for this volume. */
4517 if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
4518 VChangeState_r(vp, VOL_STATE_SALVAGING);
4521 Log("VRequestSalvage: volume %u online salvaged too many times; forced offline.\n", vp->hashid);
4523 /* make sure neither VScheduleSalvage_r nor
4524 * VUpdateSalvagePriority_r try to schedule another salvage */
4525 vp->salvage.requested = vp->salvage.scheduled = 0;
4527 VChangeState_r(vp, VOL_STATE_ERROR);
4531 if (flags & VOL_SALVAGE_INVALIDATE_HEADER) {
4532 /* Instead of ReleaseVolumeHeader, we do FreeVolumeHeader()
4533 so that the the next VAttachVolumeByVp_r() invocation
4534 of attach2() will pull in a cached header
4535 entry and fail, then load a fresh one from disk and attach
4538 FreeVolumeHeader(vp);
4545 * update salvageserver scheduling priority for a volume.
4547 * @param[in] vp pointer to volume object
4549 * @return operation status
4551 * @retval 1 request denied, or SALVSYNC communications failure
4553 * @pre VOL_LOCK is held.
4555 * @post in-core salvage priority counter is incremented. if at least
4556 * SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
4557 * last SALVSYNC_RAISEPRIO request, we contact the salvageserver
4558 * to update its priority queue. if no salvage is scheduled,
4559 * this function is a no-op.
4561 * @note DAFS fileserver only
4563 * @note this should be called whenever a VGetVolume fails due to a
4564 * pending salvage request
4566 * @todo should set exclusive state and drop glock around salvsync call
4568 * @internal volume package internal use only.
4571 VUpdateSalvagePriority_r(Volume * vp)
4575 #ifdef SALVSYNC_BUILD_CLIENT
4580 now = FT_ApproxTime();
4582 /* update the salvageserver priority queue occasionally so that
4583 * frequently requested volumes get moved to the head of the queue
4585 if ((vp->salvage.scheduled) &&
4586 (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
4587 code = SALVSYNC_SalvageVolume(vp->hashid,
4588 VPartitionPath(vp->partition),
4593 vp->stats.last_salvage_req = now;
4594 if (code != SYNC_OK) {
4598 #endif /* SALVSYNC_BUILD_CLIENT */
4603 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
4605 * schedule a salvage with the salvage server or fileserver.
4607 * @param[in] vp pointer to volume object
4609 * @return operation status
4610 * @retval 0 salvage scheduled successfully
4611 * @retval 1 salvage not scheduled, or SALVSYNC/FSSYNC com error
4614 * @arg VOL_LOCK is held.
4615 * @arg nUsers and nWaiters should be zero.
4617 * @post salvageserver or fileserver is sent a salvage request
4619 * @note If we are the fileserver, the request will be sent to the salvage
4620 * server over SALVSYNC. If we are not the fileserver, the request will be
4621 * sent to the fileserver over FSSYNC (FSYNC_VOL_FORCE_ERROR/FSYNC_SALVAGE).
4625 * @internal volume package internal use only.
4628 VScheduleSalvage_r(Volume * vp)
4632 VolState state_save;
4633 VThreadOptions_t * thread_opts;
4636 assert(VCanUseSALVSYNC() || VCanUseFSSYNC());
4638 if (vp->nWaiters || vp->nUsers) {
4642 /* prevent endless salvage,attach,salvage,attach,... loops */
4643 if (vp->stats.salvages >= SALVAGE_COUNT_MAX)
4647 * don't perform salvsync ops on certain threads
4649 thread_opts = pthread_getspecific(VThread_key);
4650 if (thread_opts == NULL) {
4651 thread_opts = &VThread_defaults;
4653 if (thread_opts->disallow_salvsync || vol_disallow_salvsync) {
4658 * XXX the scheduling process should really be done asynchronously
4659 * to avoid fssync deadlocks
4661 if (!vp->salvage.scheduled) {
4662 /* if we haven't previously scheduled a salvage, do so now
4664 * set the volume to an exclusive state and drop the lock
4665 * around the SALVSYNC call
4667 * note that we do NOT acquire a reservation here -- doing so
4668 * could result in unbounded recursion
4670 strlcpy(partName, VPartitionPath(vp->partition), sizeof(partName));
4671 state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
4674 #ifdef SALVSYNC_BUILD_CLIENT
4675 if (VCanUseSALVSYNC()) {
4676 /* can't use V_id() since there's no guarantee
4677 * we have the disk data header at this point */
4678 code = SALVSYNC_SalvageVolume(vp->hashid,
4685 #endif /* SALVSYNC_BUILD_CLIENT */
4686 #ifdef FSSYNC_BUILD_CLIENT
4687 if (VCanUseFSSYNC()) {
4689 * If we aren't the fileserver, tell the fileserver the volume
4690 * needs to be salvaged. We could directly tell the
4691 * salvageserver, but the fileserver keeps track of some stats
4692 * related to salvages, and handles some other salvage-related
4693 * complications for us.
4695 code = FSYNC_VolOp(vp->hashid, partName,
4696 FSYNC_VOL_FORCE_ERROR, FSYNC_SALVAGE, NULL);
4698 #endif /* FSSYNC_BUILD_CLIENT */
4701 VChangeState_r(vp, state_save);
4703 if (code == SYNC_OK) {
4704 vp->salvage.scheduled = 1;
4705 vp->stats.last_salvage_req = FT_ApproxTime();
4706 if (VCanUseSALVSYNC()) {
4707 /* don't record these stats for non-fileservers; let the
4708 * fileserver take care of these */
4709 vp->stats.salvages++;
4710 IncUInt64(&VStats.salvages);
4715 case SYNC_BAD_COMMAND:
4716 case SYNC_COM_ERROR:
4719 Log("VScheduleSalvage_r: Salvage request for volume %lu "
4720 "denied\n", afs_printable_uint32_lu(vp->hashid));
4723 Log("VScheduleSalvage_r: Salvage request for volume %lu "
4724 "received unknown protocol error %d\n",
4725 afs_printable_uint32_lu(vp->hashid), code);
4729 if (VCanUseFSSYNC()) {
4730 VChangeState_r(vp, VOL_STATE_ERROR);
4736 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
4738 #ifdef SALVSYNC_BUILD_CLIENT
4741 * connect to the salvageserver SYNC service.
4743 * @return operation status
4747 * @post connection to salvageserver SYNC service established
4749 * @see VConnectSALV_r
4750 * @see VDisconnectSALV
4751 * @see VReconnectSALV
4758 retVal = VConnectSALV_r();
4764 * connect to the salvageserver SYNC service.
4766 * @return operation status
4770 * @pre VOL_LOCK is held.
4772 * @post connection to salvageserver SYNC service established
4775 * @see VDisconnectSALV_r
4776 * @see VReconnectSALV_r
4777 * @see SALVSYNC_clientInit
4779 * @internal volume package internal use only.
4782 VConnectSALV_r(void)
4784 return SALVSYNC_clientInit();
4788 * disconnect from the salvageserver SYNC service.
4790 * @return operation status
4793 * @pre client should have a live connection to the salvageserver
4795 * @post connection to salvageserver SYNC service destroyed
4797 * @see VDisconnectSALV_r
4799 * @see VReconnectSALV
4802 VDisconnectSALV(void)
4805 VDisconnectSALV_r();
4811 * disconnect from the salvageserver SYNC service.
4813 * @return operation status
4817 * @arg VOL_LOCK is held.
4818 * @arg client should have a live connection to the salvageserver.
4820 * @post connection to salvageserver SYNC service destroyed
4822 * @see VDisconnectSALV
4823 * @see VConnectSALV_r
4824 * @see VReconnectSALV_r
4825 * @see SALVSYNC_clientFinis
4827 * @internal volume package internal use only.
4830 VDisconnectSALV_r(void)
4832 return SALVSYNC_clientFinis();
4836 * disconnect and then re-connect to the salvageserver SYNC service.
4838 * @return operation status
4842 * @pre client should have a live connection to the salvageserver
4844 * @post old connection is dropped, and a new one is established
4847 * @see VDisconnectSALV
4848 * @see VReconnectSALV_r
4851 VReconnectSALV(void)
4855 retVal = VReconnectSALV_r();
4861 * disconnect and then re-connect to the salvageserver SYNC service.
4863 * @return operation status
4868 * @arg VOL_LOCK is held.
4869 * @arg client should have a live connection to the salvageserver.
4871 * @post old connection is dropped, and a new one is established
4873 * @see VConnectSALV_r
4874 * @see VDisconnectSALV
4875 * @see VReconnectSALV
4876 * @see SALVSYNC_clientReconnect
4878 * @internal volume package internal use only.
4881 VReconnectSALV_r(void)
4883 return SALVSYNC_clientReconnect();
4885 #endif /* SALVSYNC_BUILD_CLIENT */
4886 #endif /* AFS_DEMAND_ATTACH_FS */
4889 /***************************************************/
4890 /* FSSYNC routines */
4891 /***************************************************/
4893 /* This must be called by any volume utility which needs to run while the
4894 file server is also running. This is separated from VInitVolumePackage2 so
4895 that a utility can fork--and each of the children can independently
4896 initialize communication with the file server */
4897 #ifdef FSSYNC_BUILD_CLIENT
4899 * connect to the fileserver SYNC service.
4901 * @return operation status
4906 * @arg VInit must equal 2.
4907 * @arg Program Type must not be fileserver or salvager.
4909 * @post connection to fileserver SYNC service established
4912 * @see VDisconnectFS
4913 * @see VChildProcReconnectFS
4920 retVal = VConnectFS_r();
4926 * connect to the fileserver SYNC service.
4928 * @return operation status
4933 * @arg VInit must equal 2.
4934 * @arg Program Type must not be fileserver or salvager.
4935 * @arg VOL_LOCK is held.
4937 * @post connection to fileserver SYNC service established
4940 * @see VDisconnectFS_r
4941 * @see VChildProcReconnectFS_r
4943 * @internal volume package internal use only.
4949 assert((VInit == 2) &&
4950 (programType != fileServer) &&
4951 (programType != salvager));
4952 rc = FSYNC_clientInit();
4959 * disconnect from the fileserver SYNC service.
4962 * @arg client should have a live connection to the fileserver.
4963 * @arg VOL_LOCK is held.
4964 * @arg Program Type must not be fileserver or salvager.
4966 * @post connection to fileserver SYNC service destroyed
4968 * @see VDisconnectFS
4970 * @see VChildProcReconnectFS_r
4972 * @internal volume package internal use only.
4975 VDisconnectFS_r(void)
4977 assert((programType != fileServer) &&
4978 (programType != salvager));
4979 FSYNC_clientFinis();
4984 * disconnect from the fileserver SYNC service.
4987 * @arg client should have a live connection to the fileserver.
4988 * @arg Program Type must not be fileserver or salvager.
4990 * @post connection to fileserver SYNC service destroyed
4992 * @see VDisconnectFS_r
4994 * @see VChildProcReconnectFS
5005 * connect to the fileserver SYNC service from a child process following a fork.
5007 * @return operation status
5012 * @arg VOL_LOCK is held.
5013 * @arg current FSYNC handle is shared with a parent process
5015 * @post current FSYNC handle is discarded and a new connection to the
5016 * fileserver SYNC service is established
5018 * @see VChildProcReconnectFS
5020 * @see VDisconnectFS_r
5022 * @internal volume package internal use only.
5025 VChildProcReconnectFS_r(void)
5027 return FSYNC_clientChildProcReconnect();
5031 * connect to the fileserver SYNC service from a child process following a fork.
5033 * @return operation status
5037 * @pre current FSYNC handle is shared with a parent process
5039 * @post current FSYNC handle is discarded and a new connection to the
5040 * fileserver SYNC service is established
5042 * @see VChildProcReconnectFS_r
5044 * @see VDisconnectFS
5047 VChildProcReconnectFS(void)
5051 ret = VChildProcReconnectFS_r();
5055 #endif /* FSSYNC_BUILD_CLIENT */
5058 /***************************************************/
5059 /* volume bitmap routines */
5060 /***************************************************/
5063 * For demand attach fs, flags parameter controls
5064 * locking behavior. If (flags & VOL_ALLOC_BITMAP_WAIT)
5065 * is set, then this function will create a reservation
5066 * and block on any other exclusive operations. Otherwise,
5067 * this function assumes the caller already has exclusive
5068 * access to vp, and we just change the volume state.
5071 VAllocBitmapEntry_r(Error * ec, Volume * vp,
5072 struct vnodeIndex *index, int flags)
5075 register byte *bp, *ep;
5076 #ifdef AFS_DEMAND_ATTACH_FS
5077 VolState state_save;
5078 #endif /* AFS_DEMAND_ATTACH_FS */
5082 /* This test is probably redundant */
5083 if (!VolumeWriteable(vp)) {
5084 *ec = (bit32) VREADONLY;
5088 #ifdef AFS_DEMAND_ATTACH_FS
5089 if (flags & VOL_ALLOC_BITMAP_WAIT) {
5090 VCreateReservation_r(vp);
5091 VWaitExclusiveState_r(vp);
5093 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
5094 #endif /* AFS_DEMAND_ATTACH_FS */
5097 if ((programType == fileServer) && !index->bitmap) {
5099 #ifndef AFS_DEMAND_ATTACH_FS
5100 /* demand attach fs uses the volume state to avoid races.
5101 * specialStatus field is not used at all */
5103 if (vp->specialStatus == VBUSY) {
5104 if (vp->goingOffline) { /* vos dump waiting for the volume to
5105 * go offline. We probably come here
5106 * from AddNewReadableResidency */
5109 while (vp->specialStatus == VBUSY) {
5110 #ifdef AFS_PTHREAD_ENV
5114 #else /* !AFS_PTHREAD_ENV */
5116 #endif /* !AFS_PTHREAD_ENV */
5120 #endif /* !AFS_DEMAND_ATTACH_FS */
5122 if (!index->bitmap) {
5123 #ifndef AFS_DEMAND_ATTACH_FS
5124 vp->specialStatus = VBUSY; /* Stop anyone else from using it. */
5125 #endif /* AFS_DEMAND_ATTACH_FS */
5126 for (i = 0; i < nVNODECLASSES; i++) {
5127 VGetBitmap_r(ec, vp, i);
5129 #ifdef AFS_DEMAND_ATTACH_FS
5130 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
5131 #else /* AFS_DEMAND_ATTACH_FS */
5132 DeleteVolumeFromHashTable(vp);
5133 vp->shuttingDown = 1; /* Let who has it free it. */
5134 vp->specialStatus = 0;
5135 #endif /* AFS_DEMAND_ATTACH_FS */
5140 #ifndef AFS_DEMAND_ATTACH_FS
5142 vp->specialStatus = 0; /* Allow others to have access. */
5143 #endif /* AFS_DEMAND_ATTACH_FS */
5146 #endif /* BITMAP_LATER */
5148 #ifdef AFS_DEMAND_ATTACH_FS
5150 #endif /* AFS_DEMAND_ATTACH_FS */
5151 bp = index->bitmap + index->bitmapOffset;
5152 ep = index->bitmap + index->bitmapSize;
5154 if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
5156 index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
5159 o = ffs(~*bp) - 1; /* ffs is documented in BSTRING(3) */
5161 ret = (VnodeId) ((bp - index->bitmap) * 8 + o);
5162 #ifdef AFS_DEMAND_ATTACH_FS
5164 #endif /* AFS_DEMAND_ATTACH_FS */
5167 bp += sizeof(bit32) /* i.e. 4 */ ;
5169 /* No bit map entry--must grow bitmap */
5171 realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
5174 bp += index->bitmapSize;
5175 memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
5176 index->bitmapOffset = index->bitmapSize;
5177 index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
5179 ret = index->bitmapOffset * 8;
5180 #ifdef AFS_DEMAND_ATTACH_FS
5182 #endif /* AFS_DEMAND_ATTACH_FS */
5185 #ifdef AFS_DEMAND_ATTACH_FS
5186 VChangeState_r(vp, state_save);
5187 if (flags & VOL_ALLOC_BITMAP_WAIT) {
5188 VCancelReservation_r(vp);
5190 #endif /* AFS_DEMAND_ATTACH_FS */
5195 VAllocBitmapEntry(Error * ec, Volume * vp, register struct vnodeIndex * index)
5199 retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
5205 VFreeBitMapEntry_r(Error * ec, register struct vnodeIndex *index,
5208 unsigned int offset;
5214 #endif /* BITMAP_LATER */
5215 offset = bitNumber >> 3;
5216 if (offset >= index->bitmapSize) {
5220 if (offset < index->bitmapOffset)
5221 index->bitmapOffset = offset & ~3; /* Truncate to nearest bit32 */
5222 *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
5226 VFreeBitMapEntry(Error * ec, register struct vnodeIndex *index,
5230 VFreeBitMapEntry_r(ec, index, bitNumber);
5234 /* this function will drop the glock internally.
5235 * for old pthread fileservers, this is safe thanks to vbusy.
5237 * for demand attach fs, caller must have already called
5238 * VCreateReservation_r and VWaitExclusiveState_r */
5240 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
5242 StreamHandle_t *file;
5245 struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
5246 struct vnodeIndex *vip = &vp->vnodeIndex[class];
5247 struct VnodeDiskObject *vnode;
5248 unsigned int unique = 0;
5252 #endif /* BITMAP_LATER */
5253 #ifdef AFS_DEMAND_ATTACH_FS
5254 VolState state_save;
5255 #endif /* AFS_DEMAND_ATTACH_FS */
5259 #ifdef AFS_DEMAND_ATTACH_FS
5260 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
5261 #endif /* AFS_DEMAND_ATTACH_FS */
5264 fdP = IH_OPEN(vip->handle);
5265 assert(fdP != NULL);
5266 file = FDH_FDOPEN(fdP, "r");
5267 assert(file != NULL);
5268 vnode = (VnodeDiskObject *) malloc(vcp->diskSize);
5269 assert(vnode != NULL);
5270 size = OS_SIZE(fdP->fd_fd);
5272 nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
5274 vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4; /* The 10 is a little extra so
5275 * a few files can be created in this volume,
5276 * the whole thing is rounded up to nearest 4
5277 * bytes, because the bit map allocator likes
5280 BitMap = (byte *) calloc(1, vip->bitmapSize);
5281 assert(BitMap != NULL);
5282 #else /* BITMAP_LATER */
5283 vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
5284 assert(vip->bitmap != NULL);
5285 vip->bitmapOffset = 0;
5286 #endif /* BITMAP_LATER */
5287 if (STREAM_SEEK(file, vcp->diskSize, 0) != -1) {
5289 for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
5290 if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
5292 if (vnode->type != vNull) {
5293 if (vnode->vnodeMagic != vcp->magic) {
5294 Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
5299 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
5300 #else /* BITMAP_LATER */
5301 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
5302 #endif /* BITMAP_LATER */
5303 if (unique <= vnode->uniquifier)
5304 unique = vnode->uniquifier + 1;
5306 #ifndef AFS_PTHREAD_ENV
5307 if ((bitNumber & 0x00ff) == 0x0ff) { /* every 256 iterations */
5310 #endif /* !AFS_PTHREAD_ENV */
5313 if (vp->nextVnodeUnique < unique) {
5314 Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
5317 /* Paranoia, partly justified--I think fclose after fdopen
5318 * doesn't seem to close fd. In any event, the documentation
5319 * doesn't specify, so it's safer to close it twice.
5327 /* There may have been a racing condition with some other thread, both
5328 * creating the bitmaps for this volume. If the other thread was faster
5329 * the pointer to bitmap should already be filled and we can free ours.
5331 if (vip->bitmap == NULL) {
5332 vip->bitmap = BitMap;
5333 vip->bitmapOffset = 0;
5335 free((byte *) BitMap);
5336 #endif /* BITMAP_LATER */
5337 #ifdef AFS_DEMAND_ATTACH_FS
5338 VChangeState_r(vp, state_save);
5339 #endif /* AFS_DEMAND_ATTACH_FS */
5343 /***************************************************/
5344 /* Volume Path and Volume Number utility routines */
5345 /***************************************************/
5348 * find the first occurrence of a volume header file and return the path.
5350 * @param[out] ec outbound error code
5351 * @param[in] volumeId volume id to find
5352 * @param[out] partitionp pointer to disk partition path string
5353 * @param[out] namep pointer to volume header file name string
5355 * @post path to first occurrence of volume header is returned in partitionp
5356 * and namep, or ec is set accordingly.
5358 * @warning this function is NOT re-entrant -- partitionp and namep point to
5359 * static data segments
5361 * @note if a volume utility inadvertently leaves behind a stale volume header
5362 * on a vice partition, it is possible for callers to get the wrong one,
5363 * depending on the order of the disk partition linked list.
5367 VGetVolumePath(Error * ec, VolId volumeId, char **partitionp, char **namep)
5369 static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
5370 char path[VMAXPATHLEN];
5372 struct DiskPartition64 *dp;
5376 (void)afs_snprintf(&name[1], (sizeof name) - 1, VFORMAT, afs_printable_uint32_lu(volumeId));
5377 for (dp = DiskPartitionList; dp; dp = dp->next) {
5378 struct afs_stat status;
5379 strcpy(path, VPartitionPath(dp));
5381 if (afs_stat(path, &status) == 0) {
5382 strcpy(partition, dp->name);
5389 *partitionp = *namep = NULL;
5391 *partitionp = partition;
5397 * extract a volume number from a volume header filename string.
5399 * @param[in] name volume header filename string
5401 * @return volume number
5403 * @note the string must be of the form VFORMAT. the only permissible
5404 * deviation is a leading '/' character.
5409 VolumeNumber(char *name)
5413 return atoi(name + 1);
5417 * compute the volume header filename.
5419 * @param[in] volumeId
5421 * @return volume header filename
5423 * @post volume header filename string is constructed
5425 * @warning this function is NOT re-entrant -- the returned string is
5426 * stored in a static char array. see VolumeExternalName_r
5427 * for a re-entrant equivalent.
5429 * @see VolumeExternalName_r
5431 * @deprecated due to the above re-entrancy warning, this interface should
5432 * be considered deprecated. Please use VolumeExternalName_r
5436 VolumeExternalName(VolumeId volumeId)
5438 static char name[VMAXPATHLEN];
5439 (void)afs_snprintf(name, sizeof name, VFORMAT, afs_printable_uint32_lu(volumeId));
5444 * compute the volume header filename.
5446 * @param[in] volumeId
5447 * @param[inout] name array in which to store filename
5448 * @param[in] len length of name array
5450 * @return result code from afs_snprintf
5452 * @see VolumeExternalName
5455 * @note re-entrant equivalent of VolumeExternalName
5458 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
5460 return afs_snprintf(name, len, VFORMAT, afs_printable_uint32_lu(volumeId));
5464 /***************************************************/
5465 /* Volume Usage Statistics routines */
5466 /***************************************************/
5468 #if OPENAFS_VOL_STATS
5469 #define OneDay (86400) /* 24 hours' worth of seconds */
5471 #define OneDay (24*60*60) /* 24 hours */
5472 #endif /* OPENAFS_VOL_STATS */
5475 Midnight(time_t t) {
5476 struct tm local, *l;
5479 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
5480 l = localtime_r(&t, &local);
5486 /* the following is strictly speaking problematic on the
5487 switching day to daylight saving time, after the switch,
5488 as tm_isdst does not match. Similarly, on the looong day when
5489 switching back the OneDay check will not do what naively expected!
5490 The effects are minor, though, and more a matter of interpreting
5492 #ifndef AFS_PTHREAD_ENV
5495 local.tm_hour = local.tm_min=local.tm_sec = 0;
5496 midnight = mktime(&local);
5497 if (midnight != (time_t) -1) return(midnight);
5499 return( (t/OneDay)*OneDay );
5503 /*------------------------------------------------------------------------
5504 * [export] VAdjustVolumeStatistics
5507 * If we've passed midnight, we need to update all the day use
5508 * statistics as well as zeroing the detailed volume statistics
5509 * (if we are implementing them).
5512 * vp : Pointer to the volume structure describing the lucky
5513 * volume being considered for update.
5519 * Nothing interesting.
5523 *------------------------------------------------------------------------*/
5526 VAdjustVolumeStatistics_r(register Volume * vp)
5528 unsigned int now = FT_ApproxTime();
5530 if (now - V_dayUseDate(vp) > OneDay) {
5531 register int ndays, i;
5533 ndays = (now - V_dayUseDate(vp)) / OneDay;
5534 for (i = 6; i > ndays - 1; i--)
5535 V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
5536 for (i = 0; i < ndays - 1 && i < 7; i++)
5537 V_weekUse(vp)[i] = 0;
5539 V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
5541 V_dayUseDate(vp) = Midnight(now);
5543 #if OPENAFS_VOL_STATS
5545 * All we need to do is bzero the entire VOL_STATS_BYTES of
5546 * the detailed volume statistics area.
5548 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
5549 #endif /* OPENAFS_VOL_STATS */
5552 /*It's been more than a day of collection */
5554 * Always return happily.
5557 } /*VAdjustVolumeStatistics */
5560 VAdjustVolumeStatistics(register Volume * vp)
5564 retVal = VAdjustVolumeStatistics_r(vp);
5570 VBumpVolumeUsage_r(register Volume * vp)
5572 unsigned int now = FT_ApproxTime();
5573 V_accessDate(vp) = now;
5574 if (now - V_dayUseDate(vp) > OneDay)
5575 VAdjustVolumeStatistics_r(vp);
5577 * Save the volume header image to disk after every 128 bumps to dayUse.
5579 if ((V_dayUse(vp)++ & 127) == 0) {
5581 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
5586 VBumpVolumeUsage(register Volume * vp)
5589 VBumpVolumeUsage_r(vp);
5594 VSetDiskUsage_r(void)
5596 #ifndef AFS_DEMAND_ATTACH_FS
5597 static int FifteenMinuteCounter = 0;
5601 /* NOTE: Don't attempt to access the partitions list until the
5602 * initialization level indicates that all volumes are attached,
5603 * which implies that all partitions are initialized. */
5604 #ifdef AFS_PTHREAD_ENV
5606 #else /* AFS_PTHREAD_ENV */
5608 #endif /* AFS_PTHREAD_ENV */
5611 VResetDiskUsage_r();
5613 #ifndef AFS_DEMAND_ATTACH_FS
5614 if (++FifteenMinuteCounter == 3) {
5615 FifteenMinuteCounter = 0;
5618 #endif /* !AFS_DEMAND_ATTACH_FS */
5630 /***************************************************/
5631 /* Volume Update List routines */
5632 /***************************************************/
5634 /* The number of minutes that a volume hasn't been updated before the
5635 * "Dont salvage" flag in the volume header will be turned on */
5636 #define SALVAGE_INTERVAL (10*60)
5641 * volume update list functionality has been moved into the VLRU
5642 * the DONT_SALVAGE flag is now set during VLRU demotion
5645 #ifndef AFS_DEMAND_ATTACH_FS
5646 static VolumeId *UpdateList = NULL; /* Pointer to array of Volume ID's */
5647 static int nUpdatedVolumes = 0; /* Updated with entry in UpdateList, salvage after crash flag on */
5648 static int updateSize = 0; /* number of entries possible */
5649 #define UPDATE_LIST_SIZE 128 /* initial size increment (must be a power of 2!) */
5650 #endif /* !AFS_DEMAND_ATTACH_FS */
5653 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
5656 vp->updateTime = FT_ApproxTime();
5657 if (V_dontSalvage(vp) == 0)
5659 V_dontSalvage(vp) = 0;
5660 VSyncVolume_r(ec, vp, 0);
5661 #ifdef AFS_DEMAND_ATTACH_FS
5662 V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
5663 #else /* !AFS_DEMAND_ATTACH_FS */
5666 if (UpdateList == NULL) {
5667 updateSize = UPDATE_LIST_SIZE;
5668 UpdateList = (VolumeId *) malloc(sizeof(VolumeId) * updateSize);
5670 if (nUpdatedVolumes == updateSize) {
5672 if (updateSize > 524288) {
5673 Log("warning: there is likely a bug in the volume update scanner\n");
5677 (VolumeId *) realloc(UpdateList,
5678 sizeof(VolumeId) * updateSize);
5681 assert(UpdateList != NULL);
5682 UpdateList[nUpdatedVolumes++] = V_id(vp);
5683 #endif /* !AFS_DEMAND_ATTACH_FS */
5686 #ifndef AFS_DEMAND_ATTACH_FS
5688 VScanUpdateList(void)
5690 register int i, gap;
5691 register Volume *vp;
5693 afs_uint32 now = FT_ApproxTime();
5694 /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
5695 for (i = gap = 0; i < nUpdatedVolumes; i++) {
5697 UpdateList[i - gap] = UpdateList[i];
5699 /* XXX this routine needlessly messes up the Volume LRU by
5700 * breaking the LRU temporal-locality assumptions.....
5701 * we should use a special volume header allocator here */
5702 vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
5705 } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
5706 V_dontSalvage(vp) = DONT_SALVAGE;
5707 VUpdateVolume_r(&error, vp, 0); /* No need to fsync--not critical */
5715 #ifndef AFS_PTHREAD_ENV
5717 #endif /* !AFS_PTHREAD_ENV */
5719 nUpdatedVolumes -= gap;
5721 #endif /* !AFS_DEMAND_ATTACH_FS */
5724 /***************************************************/
5725 /* Volume LRU routines */
5726 /***************************************************/
5731 * with demand attach fs, we attempt to soft detach(1)
5732 * volumes which have not been accessed in a long time
5733 * in order to speed up fileserver shutdown
5735 * (1) by soft detach we mean a process very similar
5736 * to VOffline, except the final state of the
5737 * Volume will be VOL_STATE_PREATTACHED, instead
5738 * of the usual VOL_STATE_UNATTACHED
5740 #ifdef AFS_DEMAND_ATTACH_FS
5742 /* implementation is reminiscent of a generational GC
5744 * queue 0 is newly attached volumes. this queue is
5745 * sorted by attach timestamp
5747 * queue 1 is volumes that have been around a bit
5748 * longer than queue 0. this queue is sorted by
5751 * queue 2 is volumes tha have been around the longest.
5752 * this queue is unsorted
5754 * queue 3 is volumes that have been marked as
5755 * candidates for soft detachment. this queue is
5758 #define VLRU_GENERATIONS 3 /**< number of generations in VLRU */
5759 #define VLRU_QUEUES 5 /**< total number of VLRU queues */
5762 * definition of a VLRU queue.
5765 volatile struct rx_queue q;
5772 * main VLRU data structure.
5775 struct VLRU_q q[VLRU_QUEUES]; /**< VLRU queues */
5778 /** time interval (in seconds) between promotion passes for
5779 * each young generation queue. */
5780 afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
5782 /** time interval (in seconds) between soft detach candidate
5783 * scans for each generation queue.
5785 * scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
5786 * we perform a soft detach pass. */
5787 afs_uint32 scan_interval[VLRU_GENERATIONS+1];
5789 /* scheduler state */
5790 int next_idx; /**< next queue to receive attention */
5791 afs_uint32 last_promotion[VLRU_GENERATIONS-1]; /**< timestamp of last promotion scan */
5792 afs_uint32 last_scan[VLRU_GENERATIONS+1]; /**< timestamp of last detach scan */
5794 int scanner_state; /**< state of scanner thread */
5795 pthread_cond_t cv; /**< state transition CV */
5798 /** global VLRU state */
5799 static struct VLRU volume_LRU;
5802 * defined states for VLRU scanner thread.
5805 VLRU_SCANNER_STATE_OFFLINE = 0, /**< vlru scanner thread is offline */
5806 VLRU_SCANNER_STATE_ONLINE = 1, /**< vlru scanner thread is online */
5807 VLRU_SCANNER_STATE_SHUTTING_DOWN = 2, /**< vlru scanner thread is shutting down */
5808 VLRU_SCANNER_STATE_PAUSING = 3, /**< vlru scanner thread is getting ready to pause */
5809 VLRU_SCANNER_STATE_PAUSED = 4 /**< vlru scanner thread is paused */
5810 } vlru_thread_state_t;
5812 /* vlru disk data header stuff */
5813 #define VLRU_DISK_MAGIC 0x7a8b9cad /**< vlru disk entry magic number */
5814 #define VLRU_DISK_VERSION 1 /**< vlru disk entry version number */
5816 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
5817 #define VLRU_DUMP_EXPIRATION_TIME (60*60*24*7) /* expire vlru data after 1 week */
5820 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
5821 * soft detachment. */
5822 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
5824 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
5825 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
5827 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
5828 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
5830 /** VLRU control flag. non-zero value implies VLRU subsystem is activated. */
5831 static afs_uint32 VLRU_enabled = 1;
5833 /* queue synchronization routines */
5834 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
5835 static void VLRU_EndExclusive_r(struct VLRU_q * q);
5836 static void VLRU_Wait_r(struct VLRU_q * q);
5839 * set VLRU subsystem tunable parameters.
5841 * @param[in] option tunable option to modify
5842 * @param[in] val new value for tunable parameter
5844 * @pre @c VInitVolumePackage2 has not yet been called.
5846 * @post tunable parameter is modified
5850 * @note valid option parameters are:
5851 * @arg @c VLRU_SET_THRESH
5852 * set the period of inactivity after which
5853 * volumes are eligible for soft detachment
5854 * @arg @c VLRU_SET_INTERVAL
5855 * set the time interval between calls
5856 * to the volume LRU "garbage collector"
5857 * @arg @c VLRU_SET_MAX
5858 * set the max number of volumes to deallocate
5862 VLRU_SetOptions(int option, afs_uint32 val)
5864 if (option == VLRU_SET_THRESH) {
5865 VLRU_offline_thresh = val;
5866 } else if (option == VLRU_SET_INTERVAL) {
5867 VLRU_offline_interval = val;
5868 } else if (option == VLRU_SET_MAX) {
5869 VLRU_offline_max = val;
5870 } else if (option == VLRU_SET_ENABLED) {
5873 VLRU_ComputeConstants();
5877 * compute VLRU internal timing parameters.
5879 * @post VLRU scanner thread internal timing parameters are computed
5881 * @note computes internal timing parameters based upon user-modifiable
5882 * tunable parameters.
5886 * @internal volume package internal use only.
5889 VLRU_ComputeConstants(void)
5891 afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
5893 /* compute the candidate scan interval */
5894 volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
5896 /* compute the promotion intervals */
5897 volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
5898 volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
5901 /* compute the gen 0 scan interval */
5902 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
5904 /* compute the gen 0 scan interval */
5905 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
5910 * initialize VLRU subsystem.
5912 * @pre this function has not yet been called
5914 * @post VLRU subsystem is initialized and VLRU scanner thread is starting
5918 * @internal volume package internal use only.
5924 pthread_attr_t attrs;
5927 if (!VLRU_enabled) {
5928 Log("VLRU: disabled\n");
5932 /* initialize each of the VLRU queues */
5933 for (i = 0; i < VLRU_QUEUES; i++) {
5934 queue_Init(&volume_LRU.q[i]);
5935 volume_LRU.q[i].len = 0;
5936 volume_LRU.q[i].busy = 0;
5937 assert(pthread_cond_init(&volume_LRU.q[i].cv, NULL) == 0);
5940 /* setup the timing constants */
5941 VLRU_ComputeConstants();
5943 /* XXX put inside LogLevel check? */
5944 Log("VLRU: starting scanner with the following configuration parameters:\n");
5945 Log("VLRU: offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
5946 Log("VLRU: running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
5947 Log("VLRU: taking up to %d volumes offline per pass\n", VLRU_offline_max);
5948 Log("VLRU: scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
5949 Log("VLRU: scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
5950 Log("VLRU: scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
5952 /* start up the VLRU scanner */
5953 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
5954 if (programType == fileServer) {
5955 assert(pthread_cond_init(&volume_LRU.cv, NULL) == 0);
5956 assert(pthread_attr_init(&attrs) == 0);
5957 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
5958 assert(pthread_create(&tid, &attrs, &VLRU_ScannerThread, NULL) == 0);
5963 * initialize the VLRU-related fields of a newly allocated volume object.
5965 * @param[in] vp pointer to volume object
5968 * @arg @c VOL_LOCK is held.
5969 * @arg volume object is not on a VLRU queue.
5971 * @post VLRU fields are initialized to indicate that volume object is not
5972 * currently registered with the VLRU subsystem
5976 * @internal volume package interal use only.
5979 VLRU_Init_Node_r(Volume * vp)
5984 assert(queue_IsNotOnQueue(&vp->vlru));
5985 vp->vlru.idx = VLRU_QUEUE_INVALID;
5989 * add a volume object to a VLRU queue.
5991 * @param[in] vp pointer to volume object
5994 * @arg @c VOL_LOCK is held.
5995 * @arg caller MUST hold a lightweight ref on @p vp.
5996 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
5998 * @post the volume object is added to the appropriate VLRU queue
6000 * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
6001 * then the volume is added to that queue. Otherwise, the value
6002 * @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
6003 * volume is added to the NEW generation queue.
6005 * @note @c VOL_LOCK may be dropped internally
6007 * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
6008 * during the add operation, and is restored to the previous
6009 * state prior to return.
6013 * @internal volume package internal use only.
6016 VLRU_Add_r(Volume * vp)
6019 VolState state_save;
6024 if (queue_IsOnQueue(&vp->vlru))
6027 state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
6030 if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
6031 idx = VLRU_QUEUE_NEW;
6034 VLRU_Wait_r(&volume_LRU.q[idx]);
6036 /* repeat check since VLRU_Wait_r may have dropped
6038 if (queue_IsNotOnQueue(&vp->vlru)) {
6040 queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
6041 volume_LRU.q[idx].len++;
6042 V_attachFlags(vp) |= VOL_ON_VLRU;
6043 vp->stats.last_promote = FT_ApproxTime();
6046 VChangeState_r(vp, state_save);
6050 * delete a volume object from a VLRU queue.
6052 * @param[in] vp pointer to volume object
6055 * @arg @c VOL_LOCK is held.
6056 * @arg caller MUST hold a lightweight ref on @p vp.
6057 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
6059 * @post volume object is removed from the VLRU queue
6061 * @note @c VOL_LOCK may be dropped internally
6065 * @todo We should probably set volume state to something exlcusive
6066 * (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
6068 * @internal volume package internal use only.
6071 VLRU_Delete_r(Volume * vp)
6078 if (queue_IsNotOnQueue(&vp->vlru))
6084 if (idx == VLRU_QUEUE_INVALID)
6086 VLRU_Wait_r(&volume_LRU.q[idx]);
6087 } while (idx != vp->vlru.idx);
6089 /* now remove from the VLRU and update
6090 * the appropriate counter */
6091 queue_Remove(&vp->vlru);
6092 volume_LRU.q[idx].len--;
6093 vp->vlru.idx = VLRU_QUEUE_INVALID;
6094 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
6098 * tell the VLRU subsystem that a volume was just accessed.
6100 * @param[in] vp pointer to volume object
6103 * @arg @c VOL_LOCK is held
6104 * @arg caller MUST hold a lightweight ref on @p vp
6105 * @arg caller MUST NOT hold exclusive ownership of any VLRU queue
6107 * @post volume VLRU access statistics are updated. If the volume was on
6108 * the VLRU soft detach candidate queue, it is moved to the NEW
6111 * @note @c VOL_LOCK may be dropped internally
6115 * @internal volume package internal use only.
6118 VLRU_UpdateAccess_r(Volume * vp)
6120 Volume * rvp = NULL;
6125 if (queue_IsNotOnQueue(&vp->vlru))
6128 assert(V_attachFlags(vp) & VOL_ON_VLRU);
6130 /* update the access timestamp */
6131 vp->stats.last_get = FT_ApproxTime();
6134 * if the volume is on the soft detach candidate
6135 * list, we need to safely move it back to a
6136 * regular generation. this has to be done
6137 * carefully so we don't race against the scanner
6141 /* if this volume is on the soft detach candidate queue,
6142 * then grab exclusive access to the necessary queues */
6143 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
6145 VCreateReservation_r(rvp);
6147 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
6148 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
6149 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6150 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6153 /* make sure multiple threads don't race to update */
6154 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
6155 VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
6159 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6160 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
6161 VCancelReservation_r(rvp);
6166 * switch a volume between two VLRU queues.
6168 * @param[in] vp pointer to volume object
6169 * @param[in] new_idx index of VLRU queue onto which the volume will be moved
6170 * @param[in] append controls whether the volume will be appended or
6171 * prepended to the queue. A nonzero value means it will
6172 * be appended; zero means it will be prepended.
6174 * @pre The new (and old, if applicable) queue(s) must either be owned
6175 * exclusively by the calling thread for asynchronous manipulation,
6176 * or the queue(s) must be quiescent and VOL_LOCK must be held.
6177 * Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
6178 * for further details of the queue asynchronous processing mechanism.
6180 * @post If the volume object was already on a VLRU queue, it is
6181 * removed from the queue. Depending on the value of the append
6182 * parameter, the volume object is either appended or prepended
6183 * to the VLRU queue referenced by the new_idx parameter.
6187 * @see VLRU_BeginExclusive_r
6188 * @see VLRU_EndExclusive_r
6191 * @internal volume package internal use only.
6194 VLRU_SwitchQueues(Volume * vp, int new_idx, int append)
6196 if (queue_IsNotOnQueue(&vp->vlru))
6199 queue_Remove(&vp->vlru);
6200 volume_LRU.q[vp->vlru.idx].len--;
6202 /* put the volume back on the correct generational queue */
6204 queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
6206 queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
6209 volume_LRU.q[new_idx].len++;
6210 vp->vlru.idx = new_idx;
6214 * VLRU background thread.
6216 * The VLRU Scanner Thread is responsible for periodically scanning through
6217 * each VLRU queue looking for volumes which should be moved to another
6218 * queue, or soft detached.
6220 * @param[in] args unused thread arguments parameter
6222 * @return unused thread return value
6223 * @retval NULL always
6225 * @internal volume package internal use only.
6228 VLRU_ScannerThread(void * args)
6230 afs_uint32 now, min_delay, delay;
6231 int i, min_idx, min_op, overdue, state;
6233 /* set t=0 for promotion cycle to be
6234 * fileserver startup */
6235 now = FT_ApproxTime();
6236 for (i=0; i < VLRU_GENERATIONS-1; i++) {
6237 volume_LRU.last_promotion[i] = now;
6240 /* don't start the scanner until VLRU_offline_thresh
6241 * plus a small delay for VInitVolumePackage2 to finish
6244 sleep(VLRU_offline_thresh + 60);
6246 /* set t=0 for scan cycle to be now */
6247 now = FT_ApproxTime();
6248 for (i=0; i < VLRU_GENERATIONS+1; i++) {
6249 volume_LRU.last_scan[i] = now;
6253 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
6254 volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
6257 while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
6258 /* check to see if we've been asked to pause */
6259 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
6260 volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
6261 assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
6263 VOL_CV_WAIT(&volume_LRU.cv);
6264 } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
6267 /* scheduling can happen outside the glock */
6270 /* figure out what is next on the schedule */
6272 /* figure out a potential schedule for the new generation first */
6274 min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
6277 if (min_delay > volume_LRU.scan_interval[0]) {
6278 /* unsigned overflow -- we're overdue to run this scan */
6283 /* if we're not overdue for gen 0, figure out schedule for candidate gen */
6285 i = VLRU_QUEUE_CANDIDATE;
6286 delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
6287 if (delay < min_delay) {
6291 if (delay > volume_LRU.scan_interval[i]) {
6292 /* unsigned overflow -- we're overdue to run this scan */
6299 /* if we're still not overdue for something, figure out schedules for promotions */
6300 for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
6301 delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
6302 if (delay < min_delay) {
6307 if (delay > volume_LRU.promotion_interval[i]) {
6308 /* unsigned overflow -- we're overdue to run this promotion */
6317 /* sleep as needed */
6322 /* do whatever is next */
6325 VLRU_Promote_r(min_idx);
6326 VLRU_Demote_r(min_idx+1);
6328 VLRU_Scan_r(min_idx);
6330 now = FT_ApproxTime();
6333 Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
6335 /* signal that scanner is down */
6336 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
6337 assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
6343 * promote volumes from one VLRU generation to the next.
6345 * This routine scans a VLRU generation looking for volumes which are
6346 * eligible to be promoted to the next generation. All volumes which
6347 * meet the eligibility requirement are promoted.
6349 * Promotion eligibility is based upon meeting both of the following
6352 * @arg The volume has been accessed since the last promotion:
6353 * @c (vp->stats.last_get >= vp->stats.last_promote)
6354 * @arg The last promotion occurred at least
6355 * @c volume_LRU.promotion_interval[idx] seconds ago
6357 * As a performance optimization, promotions are "globbed". In other
6358 * words, we promote arbitrarily large contiguous sublists of elements
6361 * @param[in] idx VLRU queue index to scan
6365 * @internal VLRU internal use only.
6368 VLRU_Promote_r(int idx)
6370 int len, chaining, promote;
6371 afs_uint32 now, thresh;
6372 struct rx_queue *qp, *nqp;
6373 Volume * vp, *start = NULL, *end = NULL;
6375 /* get exclusive access to two chains, and drop the glock */
6376 VLRU_Wait_r(&volume_LRU.q[idx]);
6377 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
6378 VLRU_Wait_r(&volume_LRU.q[idx+1]);
6379 VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
6382 thresh = volume_LRU.promotion_interval[idx];
6383 now = FT_ApproxTime();
6386 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
6387 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6388 promote = (((vp->stats.last_promote + thresh) <= now) &&
6389 (vp->stats.last_get >= vp->stats.last_promote));
6397 /* promote and prepend chain */
6398 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
6412 /* promote and prepend */
6413 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
6417 volume_LRU.q[idx].len -= len;
6418 volume_LRU.q[idx+1].len += len;
6421 /* release exclusive access to the two chains */
6423 volume_LRU.last_promotion[idx] = now;
6424 VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
6425 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
6428 /* run the demotions */
6430 VLRU_Demote_r(int idx)
6433 int len, chaining, demote;
6434 afs_uint32 now, thresh;
6435 struct rx_queue *qp, *nqp;
6436 Volume * vp, *start = NULL, *end = NULL;
6437 Volume ** salv_flag_vec = NULL;
6438 int salv_vec_offset = 0;
6440 assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
6442 /* get exclusive access to two chains, and drop the glock */
6443 VLRU_Wait_r(&volume_LRU.q[idx-1]);
6444 VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
6445 VLRU_Wait_r(&volume_LRU.q[idx]);
6446 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
6449 /* no big deal if this allocation fails */
6450 if (volume_LRU.q[idx].len) {
6451 salv_flag_vec = (Volume **) malloc(volume_LRU.q[idx].len * sizeof(Volume *));
6454 now = FT_ApproxTime();
6455 thresh = volume_LRU.promotion_interval[idx-1];
6458 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
6459 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6460 demote = (((vp->stats.last_promote + thresh) <= now) &&
6461 (vp->stats.last_get < (now - thresh)));
6463 /* we now do volume update list DONT_SALVAGE flag setting during
6464 * demotion passes */
6465 if (salv_flag_vec &&
6466 !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
6468 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
6469 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
6470 salv_flag_vec[salv_vec_offset++] = vp;
6471 VCreateReservation_r(vp);
6480 /* demote and append chain */
6481 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
6495 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
6499 volume_LRU.q[idx].len -= len;
6500 volume_LRU.q[idx-1].len += len;
6503 /* release exclusive access to the two chains */
6505 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
6506 VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
6508 /* now go back and set the DONT_SALVAGE flags as appropriate */
6509 if (salv_flag_vec) {
6511 for (i = 0; i < salv_vec_offset; i++) {
6512 vp = salv_flag_vec[i];
6513 if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
6514 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
6515 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
6518 V_attachFlags(vp) |= VOL_HDR_DONTSALV;
6519 V_dontSalvage(vp) = DONT_SALVAGE;
6520 VUpdateVolume_r(&ec, vp, 0);
6524 VCancelReservation_r(vp);
6526 free(salv_flag_vec);
6530 /* run a pass of the VLRU GC scanner */
6532 VLRU_Scan_r(int idx)
6534 afs_uint32 now, thresh;
6535 struct rx_queue *qp, *nqp;
6539 assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
6541 /* gain exclusive access to the idx VLRU */
6542 VLRU_Wait_r(&volume_LRU.q[idx]);
6543 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
6545 if (idx != VLRU_QUEUE_CANDIDATE) {
6546 /* gain exclusive access to the candidate VLRU */
6547 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6548 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6551 now = FT_ApproxTime();
6552 thresh = now - VLRU_offline_thresh;
6554 /* perform candidate selection and soft detaching */
6555 if (idx == VLRU_QUEUE_CANDIDATE) {
6556 /* soft detach some volumes from the candidate pool */
6560 for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
6561 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6562 if (i >= VLRU_offline_max) {
6565 /* check timestamp to see if it's a candidate for soft detaching */
6566 if (vp->stats.last_get <= thresh) {
6568 if (VCheckSoftDetach(vp, thresh))
6574 /* scan for volumes to become soft detach candidates */
6575 for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
6576 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6578 /* check timestamp to see if it's a candidate for soft detaching */
6579 if (vp->stats.last_get <= thresh) {
6580 VCheckSoftDetachCandidate(vp, thresh);
6583 if (!(i&0x7f)) { /* lock coarsening optimization */
6591 /* relinquish exclusive access to the VLRU chains */
6595 volume_LRU.last_scan[idx] = now;
6596 if (idx != VLRU_QUEUE_CANDIDATE) {
6597 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6599 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
6602 /* check whether volume is safe to soft detach
6603 * caller MUST NOT hold a ref count on vp */
6605 VCheckSoftDetach(Volume * vp, afs_uint32 thresh)
6609 if (vp->nUsers || vp->nWaiters)
6612 if (vp->stats.last_get <= thresh) {
6613 ret = VSoftDetachVolume_r(vp, thresh);
6619 /* check whether volume should be made a
6620 * soft detach candidate */
6622 VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh)
6625 if (vp->nUsers || vp->nWaiters)
6630 assert(idx == VLRU_QUEUE_NEW);
6632 if (vp->stats.last_get <= thresh) {
6633 /* move to candidate pool */
6634 queue_Remove(&vp->vlru);
6635 volume_LRU.q[VLRU_QUEUE_NEW].len--;
6636 queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
6637 vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
6638 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
6646 /* begin exclusive access on VLRU */
6648 VLRU_BeginExclusive_r(struct VLRU_q * q)
6650 assert(q->busy == 0);
6654 /* end exclusive access on VLRU */
6656 VLRU_EndExclusive_r(struct VLRU_q * q)
6660 assert(pthread_cond_broadcast(&q->cv) == 0);
6663 /* wait for another thread to end exclusive access on VLRU */
6665 VLRU_Wait_r(struct VLRU_q * q)
6668 VOL_CV_WAIT(&q->cv);
6673 * volume soft detach
6675 * caller MUST NOT hold a ref count on vp */
6677 VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh)
6682 assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
6684 ts_save = vp->stats.last_get;
6685 if (ts_save > thresh)
6688 if (vp->nUsers || vp->nWaiters)
6691 if (VIsExclusiveState(V_attachState(vp))) {
6695 switch (V_attachState(vp)) {
6696 case VOL_STATE_UNATTACHED:
6697 case VOL_STATE_PREATTACHED:
6698 case VOL_STATE_ERROR:
6699 case VOL_STATE_GOING_OFFLINE:
6700 case VOL_STATE_SHUTTING_DOWN:
6701 case VOL_STATE_SALVAGING:
6702 volume_LRU.q[vp->vlru.idx].len--;
6704 /* create and cancel a reservation to
6705 * give the volume an opportunity to
6707 VCreateReservation_r(vp);
6708 queue_Remove(&vp->vlru);
6709 vp->vlru.idx = VLRU_QUEUE_INVALID;
6710 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
6711 VCancelReservation_r(vp);
6717 /* hold the volume and take it offline.
6718 * no need for reservations, as VHold_r
6719 * takes care of that internally. */
6720 if (VHold_r(vp) == 0) {
6721 /* vhold drops the glock, so now we should
6722 * check to make sure we aren't racing against
6723 * other threads. if we are racing, offlining vp
6724 * would be wasteful, and block the scanner for a while
6728 (vp->shuttingDown) ||
6729 (vp->goingOffline) ||
6730 (vp->stats.last_get != ts_save)) {
6731 /* looks like we're racing someone else. bail */
6735 /* pull it off the VLRU */
6736 assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
6737 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
6738 queue_Remove(&vp->vlru);
6739 vp->vlru.idx = VLRU_QUEUE_INVALID;
6740 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
6742 /* take if offline */
6743 VOffline_r(vp, "volume has been soft detached");
6745 /* invalidate the volume header cache */
6746 FreeVolumeHeader(vp);
6749 IncUInt64(&VStats.soft_detaches);
6750 vp->stats.soft_detaches++;
6752 /* put in pre-attached state so demand
6753 * attacher can work on it */
6754 VChangeState_r(vp, VOL_STATE_PREATTACHED);
6760 #endif /* AFS_DEMAND_ATTACH_FS */
6763 /***************************************************/
6764 /* Volume Header Cache routines */
6765 /***************************************************/
6768 * volume header cache.
6770 struct volume_hdr_LRU_t volume_hdr_LRU;
6773 * initialize the volume header cache.
6775 * @param[in] howMany number of header cache entries to preallocate
6777 * @pre VOL_LOCK held. Function has never been called before.
6779 * @post howMany cache entries are allocated, initialized, and added
6780 * to the LRU list. Header cache statistics are initialized.
6782 * @note only applicable to fileServer program type. Should only be
6783 * called once during volume package initialization.
6785 * @internal volume package internal use only.
6788 VInitVolumeHeaderCache(afs_uint32 howMany)
6790 register struct volHeader *hp;
6791 if (programType != fileServer)
6793 queue_Init(&volume_hdr_LRU);
6794 volume_hdr_LRU.stats.free = 0;
6795 volume_hdr_LRU.stats.used = howMany;
6796 volume_hdr_LRU.stats.attached = 0;
6797 hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
6801 /* We are using ReleaseVolumeHeader to initialize the values on the header list
6802 * to ensure they have the right values
6804 ReleaseVolumeHeader(hp++);
6808 * get a volume header and attach it to the volume object.
6810 * @param[in] vp pointer to volume object
6812 * @return cache entry status
6813 * @retval 0 volume header was newly attached; cache data is invalid
6814 * @retval 1 volume header was previously attached; cache data is valid
6816 * @pre VOL_LOCK held. For DAFS, lightweight ref must be held on volume object.
6818 * @post volume header attached to volume object. if necessary, header cache
6819 * entry on LRU is synchronized to disk. Header is removed from LRU list.
6821 * @note VOL_LOCK may be dropped
6823 * @warning this interface does not load header data from disk. it merely
6824 * attaches a header object to the volume object, and may sync the old
6825 * header cache data out to disk in the process.
6827 * @internal volume package internal use only.
6830 GetVolumeHeader(register Volume * vp)
6833 register struct volHeader *hd;
6835 static int everLogged = 0;
6837 #ifdef AFS_DEMAND_ATTACH_FS
6838 VolState vp_save = 0, back_save = 0;
6840 /* XXX debug 9/19/05 we've apparently got
6841 * a ref counting bug somewhere that's
6842 * breaking the nUsers == 0 => header on LRU
6844 if (vp->header && queue_IsNotOnQueue(vp->header)) {
6845 Log("nUsers == 0, but header not on LRU\n");
6850 old = (vp->header != NULL); /* old == volume already has a header */
6852 if (programType != fileServer) {
6853 /* for volume utilities, we allocate volHeaders as needed */
6855 hd = (struct volHeader *)calloc(1, sizeof(*vp->header));
6859 #ifdef AFS_DEMAND_ATTACH_FS
6860 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
6864 /* for the fileserver, we keep a volume header cache */
6866 /* the header we previously dropped in the lru is
6867 * still available. pull it off the lru and return */
6870 assert(hd->back == vp);
6872 /* we need to grab a new element off the LRU */
6873 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
6874 /* grab an element and pull off of LRU */
6875 hd = queue_First(&volume_hdr_LRU, volHeader);
6878 /* LRU is empty, so allocate a new volHeader
6879 * this is probably indicative of a leak, so let the user know */
6880 hd = (struct volHeader *)calloc(1, sizeof(struct volHeader));
6883 Log("****Allocated more volume headers, probably leak****\n");
6886 volume_hdr_LRU.stats.free++;
6889 /* this header used to belong to someone else.
6890 * we'll need to check if the header needs to
6891 * be sync'd out to disk */
6893 #ifdef AFS_DEMAND_ATTACH_FS
6894 /* if hd->back were in an exclusive state, then
6895 * its volHeader would not be on the LRU... */
6896 assert(!VIsExclusiveState(V_attachState(hd->back)));
6899 if (hd->diskstuff.inUse) {
6900 /* volume was in use, so we'll need to sync
6901 * its header to disk */
6903 #ifdef AFS_DEMAND_ATTACH_FS
6904 back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
6905 vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
6906 VCreateReservation_r(hd->back);
6910 WriteVolumeHeader_r(&error, hd->back);
6911 /* Ignore errors; catch them later */
6913 #ifdef AFS_DEMAND_ATTACH_FS
6918 hd->back->header = NULL;
6919 #ifdef AFS_DEMAND_ATTACH_FS
6920 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
6922 if (hd->diskstuff.inUse) {
6923 VChangeState_r(hd->back, back_save);
6924 VCancelReservation_r(hd->back);
6925 VChangeState_r(vp, vp_save);
6929 volume_hdr_LRU.stats.attached++;
6933 #ifdef AFS_DEMAND_ATTACH_FS
6934 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
6937 volume_hdr_LRU.stats.free--;
6938 volume_hdr_LRU.stats.used++;
6940 IncUInt64(&VStats.hdr_gets);
6941 #ifdef AFS_DEMAND_ATTACH_FS
6942 IncUInt64(&vp->stats.hdr_gets);
6943 vp->stats.last_hdr_get = FT_ApproxTime();
6950 * make sure volume header is attached and contains valid cache data.
6952 * @param[out] ec outbound error code
6953 * @param[in] vp pointer to volume object
6955 * @pre VOL_LOCK held. For DAFS, lightweight ref held on vp.
6957 * @post header cache entry attached, and loaded with valid data, or
6958 * *ec is nonzero, and the header is released back into the LRU.
6960 * @internal volume package internal use only.
6963 LoadVolumeHeader(Error * ec, Volume * vp)
6965 #ifdef AFS_DEMAND_ATTACH_FS
6966 VolState state_save;
6970 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
6971 IncUInt64(&VStats.hdr_loads);
6972 state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
6975 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
6976 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
6978 IncUInt64(&vp->stats.hdr_loads);
6979 now = FT_ApproxTime();
6983 V_attachFlags(vp) |= VOL_HDR_LOADED;
6984 vp->stats.last_hdr_load = now;
6986 VChangeState_r(vp, state_save);
6988 #else /* AFS_DEMAND_ATTACH_FS */
6990 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
6991 IncUInt64(&VStats.hdr_loads);
6993 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
6994 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
6997 #endif /* AFS_DEMAND_ATTACH_FS */
6999 /* maintain (nUsers==0) => header in LRU invariant */
7000 FreeVolumeHeader(vp);
7005 * release a header cache entry back into the LRU list.
7007 * @param[in] hd pointer to volume header cache object
7009 * @pre VOL_LOCK held.
7011 * @post header cache object appended onto end of LRU list.
7013 * @note only applicable to fileServer program type.
7015 * @note used to place a header cache entry back into the
7016 * LRU pool without invalidating it as a cache entry.
7018 * @internal volume package internal use only.
7021 ReleaseVolumeHeader(register struct volHeader *hd)
7023 if (programType != fileServer)
7025 if (!hd || queue_IsOnQueue(hd)) /* no header, or header already released */
7027 queue_Append(&volume_hdr_LRU, hd);
7028 #ifdef AFS_DEMAND_ATTACH_FS
7030 V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
7033 volume_hdr_LRU.stats.free++;
7034 volume_hdr_LRU.stats.used--;
7038 * free/invalidate a volume header cache entry.
7040 * @param[in] vp pointer to volume object
7042 * @pre VOL_LOCK is held.
7044 * @post For fileserver, header cache entry is returned to LRU, and it is
7045 * invalidated as a cache entry. For volume utilities, the header
7046 * cache entry is freed.
7048 * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
7049 * whenever it is necessary to invalidate the header cache entry.
7051 * @see ReleaseVolumeHeader
7053 * @internal volume package internal use only.
7056 FreeVolumeHeader(register Volume * vp)
7058 register struct volHeader *hd = vp->header;
7061 if (programType == fileServer) {
7062 ReleaseVolumeHeader(hd);
7067 #ifdef AFS_DEMAND_ATTACH_FS
7068 V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
7070 volume_hdr_LRU.stats.attached--;
7075 /***************************************************/
7076 /* Volume Hash Table routines */
7077 /***************************************************/
7080 * set size of volume object hash table.
7082 * @param[in] logsize log(2) of desired hash table size
7084 * @return operation status
7086 * @retval -1 failure
7088 * @pre MUST be called prior to VInitVolumePackage2
7090 * @post Volume Hash Table will have 2^logsize buckets
7093 VSetVolHashSize(int logsize)
7095 /* 64 to 16384 hash buckets seems like a reasonable range */
7096 if ((logsize < 6 ) || (logsize > 14)) {
7101 VolumeHashTable.Size = 1 << logsize;
7102 VolumeHashTable.Mask = VolumeHashTable.Size - 1;
7104 /* we can't yet support runtime modification of this
7105 * parameter. we'll need a configuration rwlock to
7106 * make runtime modification feasible.... */
7113 * initialize dynamic data structures for volume hash table.
7115 * @post hash table is allocated, and fields are initialized.
7117 * @internal volume package internal use only.
7120 VInitVolumeHash(void)
7124 VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
7125 sizeof(VolumeHashChainHead));
7126 assert(VolumeHashTable.Table != NULL);
7128 for (i=0; i < VolumeHashTable.Size; i++) {
7129 queue_Init(&VolumeHashTable.Table[i]);
7130 #ifdef AFS_DEMAND_ATTACH_FS
7131 assert(pthread_cond_init(&VolumeHashTable.Table[i].chain_busy_cv, NULL) == 0);
7132 #endif /* AFS_DEMAND_ATTACH_FS */
7137 * add a volume object to the hash table.
7139 * @param[in] vp pointer to volume object
7140 * @param[in] hashid hash of volume id
7142 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
7145 * @post volume is added to hash chain.
7147 * @internal volume package internal use only.
7149 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
7150 * asynchronous hash chain reordering to finish.
7153 AddVolumeToHashTable(register Volume * vp, int hashid)
7155 VolumeHashChainHead * head;
7157 if (queue_IsOnQueue(vp))
7160 head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
7162 #ifdef AFS_DEMAND_ATTACH_FS
7163 /* wait for the hash chain to become available */
7166 V_attachFlags(vp) |= VOL_IN_HASH;
7167 vp->chainCacheCheck = ++head->cacheCheck;
7168 #endif /* AFS_DEMAND_ATTACH_FS */
7171 vp->hashid = hashid;
7172 queue_Append(head, vp);
7173 vp->vnodeHashOffset = VolumeHashOffset_r();
7177 * delete a volume object from the hash table.
7179 * @param[in] vp pointer to volume object
7181 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
7184 * @post volume is removed from hash chain.
7186 * @internal volume package internal use only.
7188 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
7189 * asynchronous hash chain reordering to finish.
7192 DeleteVolumeFromHashTable(register Volume * vp)
7194 VolumeHashChainHead * head;
7196 if (!queue_IsOnQueue(vp))
7199 head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
7201 #ifdef AFS_DEMAND_ATTACH_FS
7202 /* wait for the hash chain to become available */
7205 V_attachFlags(vp) &= ~(VOL_IN_HASH);
7207 #endif /* AFS_DEMAND_ATTACH_FS */
7211 /* do NOT reset hashid to zero, as the online
7212 * salvager package may need to know the volume id
7213 * after the volume is removed from the hash */
7217 * lookup a volume object in the hash table given a volume id.
7219 * @param[out] ec error code return
7220 * @param[in] volumeId volume id
7221 * @param[in] hint volume object which we believe could be the correct
7224 * @return volume object pointer
7225 * @retval NULL no such volume id is registered with the hash table.
7227 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
7230 * @post volume object with the given id is returned. volume object and
7231 * hash chain access statistics are updated. hash chain may have
7234 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
7235 * asynchronous hash chain reordering operation to finish, or
7236 * in order for us to perform an asynchronous chain reordering.
7238 * @note Hash chain reorderings occur when the access count for the
7239 * volume object being looked up exceeds the sum of the previous
7240 * node's (the node ahead of it in the hash chain linked list)
7241 * access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
7243 * @note For DAFS, the hint parameter allows us to short-circuit if the
7244 * cacheCheck fields match between the hash chain head and the
7245 * hint volume object.
7248 VLookupVolume_r(Error * ec, VolId volumeId, Volume * hint)
7250 register int looks = 0;
7252 #ifdef AFS_DEMAND_ATTACH_FS
7255 VolumeHashChainHead * head;
7258 head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
7260 #ifdef AFS_DEMAND_ATTACH_FS
7261 /* wait for the hash chain to become available */
7264 /* check to see if we can short circuit without walking the hash chain */
7265 if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
7266 IncUInt64(&hint->stats.hash_short_circuits);
7269 #endif /* AFS_DEMAND_ATTACH_FS */
7271 /* someday we need to either do per-chain locks, RWlocks,
7272 * or both for volhash access.
7273 * (and move to a data structure with better cache locality) */
7275 /* search the chain for this volume id */
7276 for(queue_Scan(head, vp, np, Volume)) {
7278 if ((vp->hashid == volumeId)) {
7283 if (queue_IsEnd(head, vp)) {
7287 #ifdef AFS_DEMAND_ATTACH_FS
7288 /* update hash chain statistics */
7291 FillInt64(lks, 0, looks);
7292 AddUInt64(head->looks, lks, &head->looks);
7293 AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
7294 IncUInt64(&head->gets);
7299 IncUInt64(&vp->stats.hash_lookups);
7301 /* for demand attach fileserver, we permit occasional hash chain reordering
7302 * so that frequently looked up volumes move towards the head of the chain */
7303 pp = queue_Prev(vp, Volume);
7304 if (!queue_IsEnd(head, pp)) {
7305 FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
7306 AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
7307 if (GEInt64(vp->stats.hash_lookups, thresh)) {
7308 VReorderHash_r(head, pp, vp);
7312 /* update the short-circuit cache check */
7313 vp->chainCacheCheck = head->cacheCheck;
7315 #endif /* AFS_DEMAND_ATTACH_FS */
7320 #ifdef AFS_DEMAND_ATTACH_FS
7321 /* perform volume hash chain reordering.
7323 * advance a subchain beginning at vp ahead of
7324 * the adjacent subchain ending at pp */
7326 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
7328 Volume *tp, *np, *lp;
7329 afs_uint64 move_thresh;
7331 /* this should never be called if the chain is already busy, so
7332 * no need to wait for other exclusive chain ops to finish */
7334 /* this is a rather heavy set of operations,
7335 * so let's set the chain busy flag and drop
7337 VHashBeginExclusive_r(head);
7340 /* scan forward in the chain from vp looking for the last element
7341 * in the chain we want to advance */
7342 FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
7343 AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
7344 for(queue_ScanFrom(head, vp, tp, np, Volume)) {
7345 if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
7349 lp = queue_Prev(tp, Volume);
7351 /* scan backwards from pp to determine where to splice and
7352 * insert the subchain we're advancing */
7353 for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
7354 if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
7358 tp = queue_Next(tp, Volume);
7360 /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
7361 queue_MoveChainBefore(tp,vp,lp);
7364 IncUInt64(&VStats.hash_reorders);
7366 IncUInt64(&head->reorders);
7368 /* wake up any threads waiting for the hash chain */
7369 VHashEndExclusive_r(head);
7373 /* demand-attach fs volume hash
7374 * asynchronous exclusive operations */
7377 * begin an asynchronous exclusive operation on a volume hash chain.
7379 * @param[in] head pointer to volume hash chain head object
7381 * @pre VOL_LOCK held. hash chain is quiescent.
7383 * @post hash chain marked busy.
7385 * @note this interface is used in conjunction with VHashEndExclusive_r and
7386 * VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
7387 * volume hash chain. Its main use case is hash chain reordering, which
7388 * has the potential to be a highly latent operation.
7390 * @see VHashEndExclusive_r
7395 * @internal volume package internal use only.
7398 VHashBeginExclusive_r(VolumeHashChainHead * head)
7400 assert(head->busy == 0);
7405 * relinquish exclusive ownership of a volume hash chain.
7407 * @param[in] head pointer to volume hash chain head object
7409 * @pre VOL_LOCK held. thread owns the hash chain exclusively.
7411 * @post hash chain is marked quiescent. threads awaiting use of
7412 * chain are awakened.
7414 * @see VHashBeginExclusive_r
7419 * @internal volume package internal use only.
7422 VHashEndExclusive_r(VolumeHashChainHead * head)
7426 assert(pthread_cond_broadcast(&head->chain_busy_cv) == 0);
7430 * wait for all asynchronous operations on a hash chain to complete.
7432 * @param[in] head pointer to volume hash chain head object
7434 * @pre VOL_LOCK held.
7436 * @post hash chain object is quiescent.
7438 * @see VHashBeginExclusive_r
7439 * @see VHashEndExclusive_r
7443 * @note This interface should be called before any attempt to
7444 * traverse the hash chain. It is permissible for a thread
7445 * to gain exclusive access to the chain, and then perform
7446 * latent operations on the chain asynchronously wrt the
7449 * @warning if waiting is necessary, VOL_LOCK is dropped
7451 * @internal volume package internal use only.
7454 VHashWait_r(VolumeHashChainHead * head)
7456 while (head->busy) {
7457 VOL_CV_WAIT(&head->chain_busy_cv);
7460 #endif /* AFS_DEMAND_ATTACH_FS */
7463 /***************************************************/
7464 /* Volume by Partition List routines */
7465 /***************************************************/
7468 * demand attach fileserver adds a
7469 * linked list of volumes to each
7470 * partition object, thus allowing
7471 * for quick enumeration of all
7472 * volumes on a partition
7475 #ifdef AFS_DEMAND_ATTACH_FS
7477 * add a volume to its disk partition VByPList.
7479 * @param[in] vp pointer to volume object
7481 * @pre either the disk partition VByPList is owned exclusively
7482 * by the calling thread, or the list is quiescent and
7485 * @post volume is added to disk partition VByPList
7489 * @warning it is the caller's responsibility to ensure list
7492 * @see VVByPListWait_r
7493 * @see VVByPListBeginExclusive_r
7494 * @see VVByPListEndExclusive_r
7496 * @internal volume package internal use only.
7499 AddVolumeToVByPList_r(Volume * vp)
7501 if (queue_IsNotOnQueue(&vp->vol_list)) {
7502 queue_Append(&vp->partition->vol_list, &vp->vol_list);
7503 V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
7504 vp->partition->vol_list.len++;
7509 * delete a volume from its disk partition VByPList.
7511 * @param[in] vp pointer to volume object
7513 * @pre either the disk partition VByPList is owned exclusively
7514 * by the calling thread, or the list is quiescent and
7517 * @post volume is removed from the disk partition VByPList
7521 * @warning it is the caller's responsibility to ensure list
7524 * @see VVByPListWait_r
7525 * @see VVByPListBeginExclusive_r
7526 * @see VVByPListEndExclusive_r
7528 * @internal volume package internal use only.
7531 DeleteVolumeFromVByPList_r(Volume * vp)
7533 if (queue_IsOnQueue(&vp->vol_list)) {
7534 queue_Remove(&vp->vol_list);
7535 V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
7536 vp->partition->vol_list.len--;
7541 * begin an asynchronous exclusive operation on a VByPList.
7543 * @param[in] dp pointer to disk partition object
7545 * @pre VOL_LOCK held. VByPList is quiescent.
7547 * @post VByPList marked busy.
7549 * @note this interface is used in conjunction with VVByPListEndExclusive_r and
7550 * VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
7553 * @see VVByPListEndExclusive_r
7554 * @see VVByPListWait_r
7558 * @internal volume package internal use only.
7560 /* take exclusive control over the list */
7562 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
7564 assert(dp->vol_list.busy == 0);
7565 dp->vol_list.busy = 1;
7569 * relinquish exclusive ownership of a VByPList.
7571 * @param[in] dp pointer to disk partition object
7573 * @pre VOL_LOCK held. thread owns the VByPList exclusively.
7575 * @post VByPList is marked quiescent. threads awaiting use of
7576 * the list are awakened.
7578 * @see VVByPListBeginExclusive_r
7579 * @see VVByPListWait_r
7583 * @internal volume package internal use only.
7586 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
7588 assert(dp->vol_list.busy);
7589 dp->vol_list.busy = 0;
7590 assert(pthread_cond_broadcast(&dp->vol_list.cv) == 0);
7594 * wait for all asynchronous operations on a VByPList to complete.
7596 * @param[in] dp pointer to disk partition object
7598 * @pre VOL_LOCK is held.
7600 * @post disk partition's VByP list is quiescent
7604 * @note This interface should be called before any attempt to
7605 * traverse the VByPList. It is permissible for a thread
7606 * to gain exclusive access to the list, and then perform
7607 * latent operations on the list asynchronously wrt the
7610 * @warning if waiting is necessary, VOL_LOCK is dropped
7612 * @see VVByPListEndExclusive_r
7613 * @see VVByPListBeginExclusive_r
7615 * @internal volume package internal use only.
7618 VVByPListWait_r(struct DiskPartition64 * dp)
7620 while (dp->vol_list.busy) {
7621 VOL_CV_WAIT(&dp->vol_list.cv);
7624 #endif /* AFS_DEMAND_ATTACH_FS */
7626 /***************************************************/
7627 /* Volume Cache Statistics routines */
7628 /***************************************************/
7631 VPrintCacheStats_r(void)
7633 afs_uint32 get_hi, get_lo, load_hi, load_lo;
7634 register struct VnodeClassInfo *vcp;
7635 vcp = &VnodeClassInfo[vLarge];
7636 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);
7637 vcp = &VnodeClassInfo[vSmall];
7638 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);
7639 SplitInt64(VStats.hdr_gets, get_hi, get_lo);
7640 SplitInt64(VStats.hdr_loads, load_hi, load_lo);
7641 Log("Volume header cache, %d entries, %d gets, %d replacements\n",
7642 VStats.hdr_cache_size, get_lo, load_lo);
7646 VPrintCacheStats(void)
7649 VPrintCacheStats_r();
7653 #ifdef AFS_DEMAND_ATTACH_FS
7655 UInt64ToDouble(afs_uint64 * x)
7657 static double c32 = 4.0 * 1.073741824 * 1000000000.0;
7659 SplitInt64(*x, h, l);
7660 return (((double)h) * c32) + ((double) l);
7664 DoubleToPrintable(double x, char * buf, int len)
7666 static double billion = 1000000000.0;
7669 y[0] = (afs_uint32) (x / (billion * billion));
7670 y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
7671 y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
7674 snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
7676 snprintf(buf, len, "%d%09d", y[1], y[2]);
7678 snprintf(buf, len, "%d", y[2]);
7684 struct VLRUExtStatsEntry {
7688 struct VLRUExtStats {
7694 } queue_info[VLRU_QUEUE_INVALID];
7695 struct VLRUExtStatsEntry * vec;
7699 * add a 256-entry fudge factor onto the vector in case state changes
7700 * out from under us.
7702 #define VLRU_EXT_STATS_VEC_LEN_FUDGE 256
7705 * collect extended statistics for the VLRU subsystem.
7707 * @param[out] stats pointer to stats structure to be populated
7708 * @param[in] nvols number of volumes currently known to exist
7710 * @pre VOL_LOCK held
7712 * @post stats->vec allocated and populated
7714 * @return operation status
7719 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
7721 afs_uint32 cur, idx, len;
7722 struct rx_queue * qp, * nqp;
7724 struct VLRUExtStatsEntry * vec;
7726 len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
7727 vec = stats->vec = calloc(len,
7728 sizeof(struct VLRUExtStatsEntry));
7734 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
7735 VLRU_Wait_r(&volume_LRU.q[idx]);
7736 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7739 stats->queue_info[idx].start = cur;
7741 for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7743 /* out of space in vec */
7746 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7747 vec[cur].volid = vp->hashid;
7751 stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
7754 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7762 #define ENUMTOSTRING(en) #en
7763 #define ENUMCASE(en) \
7765 return ENUMTOSTRING(en); \
7769 vlru_idx_to_string(int idx)
7772 ENUMCASE(VLRU_QUEUE_NEW);
7773 ENUMCASE(VLRU_QUEUE_MID);
7774 ENUMCASE(VLRU_QUEUE_OLD);
7775 ENUMCASE(VLRU_QUEUE_CANDIDATE);
7776 ENUMCASE(VLRU_QUEUE_HELD);
7777 ENUMCASE(VLRU_QUEUE_INVALID);
7779 return "**UNKNOWN**";
7784 VPrintExtendedCacheStats_r(int flags)
7787 afs_uint32 vol_sum = 0;
7794 struct stats looks, gets, reorders, len;
7795 struct stats ch_looks, ch_gets, ch_reorders;
7797 VolumeHashChainHead *head;
7799 struct VLRUExtStats vlru_stats;
7801 /* zero out stats */
7802 memset(&looks, 0, sizeof(struct stats));
7803 memset(&gets, 0, sizeof(struct stats));
7804 memset(&reorders, 0, sizeof(struct stats));
7805 memset(&len, 0, sizeof(struct stats));
7806 memset(&ch_looks, 0, sizeof(struct stats));
7807 memset(&ch_gets, 0, sizeof(struct stats));
7808 memset(&ch_reorders, 0, sizeof(struct stats));
7810 for (i = 0; i < VolumeHashTable.Size; i++) {
7811 head = &VolumeHashTable.Table[i];
7814 VHashBeginExclusive_r(head);
7817 ch_looks.sum = UInt64ToDouble(&head->looks);
7818 ch_gets.sum = UInt64ToDouble(&head->gets);
7819 ch_reorders.sum = UInt64ToDouble(&head->reorders);
7821 /* update global statistics */
7823 looks.sum += ch_looks.sum;
7824 gets.sum += ch_gets.sum;
7825 reorders.sum += ch_reorders.sum;
7826 len.sum += (double)head->len;
7827 vol_sum += head->len;
7830 len.min = (double) head->len;
7831 len.max = (double) head->len;
7832 looks.min = ch_looks.sum;
7833 looks.max = ch_looks.sum;
7834 gets.min = ch_gets.sum;
7835 gets.max = ch_gets.sum;
7836 reorders.min = ch_reorders.sum;
7837 reorders.max = ch_reorders.sum;
7839 if (((double)head->len) < len.min)
7840 len.min = (double) head->len;
7841 if (((double)head->len) > len.max)
7842 len.max = (double) head->len;
7843 if (ch_looks.sum < looks.min)
7844 looks.min = ch_looks.sum;
7845 else if (ch_looks.sum > looks.max)
7846 looks.max = ch_looks.sum;
7847 if (ch_gets.sum < gets.min)
7848 gets.min = ch_gets.sum;
7849 else if (ch_gets.sum > gets.max)
7850 gets.max = ch_gets.sum;
7851 if (ch_reorders.sum < reorders.min)
7852 reorders.min = ch_reorders.sum;
7853 else if (ch_reorders.sum > reorders.max)
7854 reorders.max = ch_reorders.sum;
7858 if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
7859 /* compute detailed per-chain stats */
7860 struct stats hdr_loads, hdr_gets;
7861 double v_looks, v_loads, v_gets;
7863 /* initialize stats with data from first element in chain */
7864 vp = queue_First(head, Volume);
7865 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
7866 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
7867 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
7868 ch_gets.min = ch_gets.max = v_looks;
7869 hdr_loads.min = hdr_loads.max = v_loads;
7870 hdr_gets.min = hdr_gets.max = v_gets;
7871 hdr_loads.sum = hdr_gets.sum = 0;
7873 vp = queue_Next(vp, Volume);
7875 /* pull in stats from remaining elements in chain */
7876 for (queue_ScanFrom(head, vp, vp, np, Volume)) {
7877 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
7878 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
7879 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
7881 hdr_loads.sum += v_loads;
7882 hdr_gets.sum += v_gets;
7884 if (v_looks < ch_gets.min)
7885 ch_gets.min = v_looks;
7886 else if (v_looks > ch_gets.max)
7887 ch_gets.max = v_looks;
7889 if (v_loads < hdr_loads.min)
7890 hdr_loads.min = v_loads;
7891 else if (v_loads > hdr_loads.max)
7892 hdr_loads.max = v_loads;
7894 if (v_gets < hdr_gets.min)
7895 hdr_gets.min = v_gets;
7896 else if (v_gets > hdr_gets.max)
7897 hdr_gets.max = v_gets;
7900 /* compute per-chain averages */
7901 ch_gets.avg = ch_gets.sum / ((double)head->len);
7902 hdr_loads.avg = hdr_loads.sum / ((double)head->len);
7903 hdr_gets.avg = hdr_gets.sum / ((double)head->len);
7905 /* dump per-chain stats */
7906 Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
7908 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
7909 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
7910 Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
7911 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
7912 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
7913 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
7914 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
7915 Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
7916 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
7917 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
7918 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
7919 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
7920 Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
7921 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
7922 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
7923 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
7924 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
7925 } else if (flags & VOL_STATS_PER_CHAIN) {
7926 /* dump simple per-chain stats */
7927 Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
7929 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
7930 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
7931 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
7935 VHashEndExclusive_r(head);
7940 /* compute global averages */
7941 len.avg = len.sum / ((double)VolumeHashTable.Size);
7942 looks.avg = looks.sum / ((double)VolumeHashTable.Size);
7943 gets.avg = gets.sum / ((double)VolumeHashTable.Size);
7944 reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
7946 /* dump global stats */
7947 Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
7948 Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
7949 DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
7950 DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
7951 DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
7952 DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
7953 Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
7954 DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
7955 DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
7956 DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
7957 DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
7958 Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
7959 DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
7960 DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
7961 DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
7962 DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
7963 Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
7964 DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
7965 DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
7966 DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
7967 DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
7969 /* print extended disk related statistics */
7971 struct DiskPartition64 * diskP;
7972 afs_uint32 vol_count[VOLMAXPARTS+1];
7973 byte part_exists[VOLMAXPARTS+1];
7977 memset(vol_count, 0, sizeof(vol_count));
7978 memset(part_exists, 0, sizeof(part_exists));
7982 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
7984 vol_count[id] = diskP->vol_list.len;
7985 part_exists[id] = 1;
7989 for (i = 0; i <= VOLMAXPARTS; i++) {
7990 if (part_exists[i]) {
7991 /* XXX while this is currently safe, it is a violation
7992 * of the VGetPartitionById_r interface contract. */
7993 diskP = VGetPartitionById_r(i, 0);
7995 Log("Partition %s has %d online volumes\n",
7996 VPartitionPath(diskP), diskP->vol_list.len);
8003 /* print extended VLRU statistics */
8004 if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
8005 afs_uint32 idx, cur, lpos;
8009 Log("VLRU State Dump:\n\n");
8011 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
8012 Log("\t%s:\n", vlru_idx_to_string(idx));
8015 for (cur = vlru_stats.queue_info[idx].start;
8016 cur < vlru_stats.queue_info[idx].len;
8018 line[lpos++] = vlru_stats.vec[cur].volid;
8020 Log("\t\t%u, %u, %u, %u, %u,\n",
8021 line[0], line[1], line[2], line[3], line[4]);
8030 Log("\t\t%u, %u, %u, %u, %u\n",
8031 line[0], line[1], line[2], line[3], line[4]);
8036 free(vlru_stats.vec);
8043 VPrintExtendedCacheStats(int flags)
8046 VPrintExtendedCacheStats_r(flags);
8049 #endif /* AFS_DEMAND_ATTACH_FS */
8052 VCanScheduleSalvage(void)
8054 return vol_opts.canScheduleSalvage;
8060 return vol_opts.canUseFSSYNC;
8064 VCanUseSALVSYNC(void)
8066 return vol_opts.canUseSALVSYNC;