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 vid, char *path,
181 register struct VolumeHeader *header,
182 struct DiskPartition64 *partp, Volume * vp,
183 int isbusy, int mode);
184 static void ReallyFreeVolume(Volume * vp);
185 #ifdef AFS_DEMAND_ATTACH_FS
186 static void FreeVolume(Volume * vp);
187 #else /* !AFS_DEMAND_ATTACH_FS */
188 #define FreeVolume(vp) ReallyFreeVolume(vp)
189 static void VScanUpdateList(void);
190 #endif /* !AFS_DEMAND_ATTACH_FS */
191 static void VInitVolumeHeaderCache(afs_uint32 howMany);
192 static int GetVolumeHeader(register Volume * vp);
193 static void ReleaseVolumeHeader(register struct volHeader *hd);
194 static void FreeVolumeHeader(register Volume * vp);
195 static void AddVolumeToHashTable(register Volume * vp, int hashid);
196 static void DeleteVolumeFromHashTable(register Volume * vp);
198 static int VHold(Volume * vp);
200 static int VHold_r(Volume * vp);
201 static void VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class);
202 static void VReleaseVolumeHandles_r(Volume * vp);
203 static void VCloseVolumeHandles_r(Volume * vp);
204 static void LoadVolumeHeader(Error * ec, Volume * vp);
205 static int VCheckOffline(register Volume * vp);
206 static int VCheckDetach(register Volume * vp);
207 static Volume * GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint, int flags);
209 int LogLevel; /* Vice loglevel--not defined as extern so that it will be
210 * defined when not linked with vice, XXXX */
211 ProgramType programType; /* The type of program using the package */
212 static VolumePackageOptions vol_opts;
214 /* extended volume package statistics */
217 #ifdef VOL_LOCK_DEBUG
218 pthread_t vol_glock_holder = 0;
222 #define VOLUME_BITMAP_GROWSIZE 16 /* bytes, => 128vnodes */
223 /* Must be a multiple of 4 (1 word) !! */
225 /* this parameter needs to be tunable at runtime.
226 * 128 was really inadequate for largish servers -- at 16384 volumes this
227 * puts average chain length at 128, thus an average 65 deref's to find a volptr.
228 * talk about bad spatial locality...
230 * an AVL or splay tree might work a lot better, but we'll just increase
231 * the default hash table size for now
233 #define DEFAULT_VOLUME_HASH_SIZE 256 /* Must be a power of 2!! */
234 #define DEFAULT_VOLUME_HASH_MASK (DEFAULT_VOLUME_HASH_SIZE-1)
235 #define VOLUME_HASH(volumeId) (volumeId&(VolumeHashTable.Mask))
238 * turn volume hash chains into partially ordered lists.
239 * when the threshold is exceeded between two adjacent elements,
240 * perform a chain rebalancing operation.
242 * keep the threshold high in order to keep cache line invalidates
243 * low "enough" on SMPs
245 #define VOLUME_HASH_REORDER_THRESHOLD 200
248 * when possible, don't just reorder single elements, but reorder
249 * entire chains of elements at once. a chain of elements that
250 * exceed the element previous to the pivot by at least CHAIN_THRESH
251 * accesses are moved in front of the chain whose elements have at
252 * least CHAIN_THRESH less accesses than the pivot element
254 #define VOLUME_HASH_REORDER_CHAIN_THRESH (VOLUME_HASH_REORDER_THRESHOLD / 2)
256 #include "rx/rx_queue.h"
259 VolumeHashTable_t VolumeHashTable = {
260 DEFAULT_VOLUME_HASH_SIZE,
261 DEFAULT_VOLUME_HASH_MASK,
266 static void VInitVolumeHash(void);
270 /* This macro is used where an ffs() call does not exist. Was in util/ffs.c */
274 afs_int32 ffs_tmp = x;
278 for (ffs_i = 1;; ffs_i++) {
285 #endif /* !AFS_HAVE_FFS */
287 #ifdef AFS_PTHREAD_ENV
288 typedef struct diskpartition_queue_t {
289 struct rx_queue queue;
290 struct DiskPartition64 * diskP;
291 } diskpartition_queue_t;
292 typedef struct vinitvolumepackage_thread_t {
293 struct rx_queue queue;
294 pthread_cond_t thread_done_cv;
295 int n_threads_complete;
296 } vinitvolumepackage_thread_t;
297 static void * VInitVolumePackageThread(void * args);
298 #endif /* AFS_PTHREAD_ENV */
300 static int VAttachVolumesByPartition(struct DiskPartition64 *diskP,
301 int * nAttached, int * nUnattached);
304 #ifdef AFS_DEMAND_ATTACH_FS
305 /* demand attach fileserver extensions */
308 * in the future we will support serialization of VLRU state into the fs_state
311 * these structures are the beginning of that effort
313 struct VLRU_DiskHeader {
314 struct versionStamp stamp; /* magic and structure version number */
315 afs_uint32 mtime; /* time of dump to disk */
316 afs_uint32 num_records; /* number of VLRU_DiskEntry records */
319 struct VLRU_DiskEntry {
320 afs_uint32 vid; /* volume ID */
321 afs_uint32 idx; /* generation */
322 afs_uint32 last_get; /* timestamp of last get */
325 struct VLRU_StartupQueue {
326 struct VLRU_DiskEntry * entry;
331 typedef struct vshutdown_thread_t {
333 pthread_mutex_t lock;
335 pthread_cond_t master_cv;
337 int n_threads_complete;
339 int schedule_version;
342 byte n_parts_done_pass;
343 byte part_thread_target[VOLMAXPARTS+1];
344 byte part_done_pass[VOLMAXPARTS+1];
345 struct rx_queue * part_pass_head[VOLMAXPARTS+1];
346 int stats[4][VOLMAXPARTS+1];
347 } vshutdown_thread_t;
348 static void * VShutdownThread(void * args);
351 static Volume * VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode);
352 static int VCheckFree(Volume * vp);
355 static void AddVolumeToVByPList_r(Volume * vp);
356 static void DeleteVolumeFromVByPList_r(Volume * vp);
357 static void VVByPListBeginExclusive_r(struct DiskPartition64 * dp);
358 static void VVByPListEndExclusive_r(struct DiskPartition64 * dp);
359 static void VVByPListWait_r(struct DiskPartition64 * dp);
361 /* online salvager */
362 static int VCheckSalvage(register Volume * vp);
363 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
364 static int VScheduleSalvage_r(Volume * vp);
367 /* Volume hash table */
368 static void VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp);
369 static void VHashBeginExclusive_r(VolumeHashChainHead * head);
370 static void VHashEndExclusive_r(VolumeHashChainHead * head);
371 static void VHashWait_r(VolumeHashChainHead * head);
374 static int ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass);
375 static int ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
376 struct rx_queue ** idx);
377 static void ShutdownController(vshutdown_thread_t * params);
378 static void ShutdownCreateSchedule(vshutdown_thread_t * params);
381 static void VLRU_ComputeConstants(void);
382 static void VInitVLRU(void);
383 static void VLRU_Init_Node_r(Volume * vp);
384 static void VLRU_Add_r(Volume * vp);
385 static void VLRU_Delete_r(Volume * vp);
386 static void VLRU_UpdateAccess_r(Volume * vp);
387 static void * VLRU_ScannerThread(void * args);
388 static void VLRU_Scan_r(int idx);
389 static void VLRU_Promote_r(int idx);
390 static void VLRU_Demote_r(int idx);
391 static void VLRU_SwitchQueues(Volume * vp, int new_idx, int append);
394 static int VCheckSoftDetach(Volume * vp, afs_uint32 thresh);
395 static int VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh);
396 static int VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh);
399 pthread_key_t VThread_key;
400 VThreadOptions_t VThread_defaults = {
401 0 /**< allow salvsync */
403 #endif /* AFS_DEMAND_ATTACH_FS */
406 struct Lock vol_listLock; /* Lock obtained when listing volumes:
407 * prevents a volume from being missed
408 * if the volume is attached during a
412 /* Common message used when the volume goes off line */
413 char *VSalvageMessage =
414 "Files in this volume are currently unavailable; call operations";
416 int VInit; /* 0 - uninitialized,
417 * 1 - initialized but not all volumes have been attached,
418 * 2 - initialized and all volumes have been attached,
419 * 3 - initialized, all volumes have been attached, and
420 * VConnectFS() has completed. */
422 static int vinit_attach_abort = 0;
424 bit32 VolumeCacheCheck; /* Incremented everytime a volume goes on line--
425 * used to stamp volume headers and in-core
426 * vnodes. When the volume goes on-line the
427 * vnode will be invalidated
428 * access only with VOL_LOCK held */
433 /***************************************************/
434 /* Startup routines */
435 /***************************************************/
437 * assign default values to a VolumePackageOptions struct.
439 * Always call this on a VolumePackageOptions struct first, then set any
440 * specific options you want, then call VInitVolumePackage2.
442 * @param[in] pt caller's program type
443 * @param[out] opts volume package options
446 VOptDefaults(ProgramType pt, VolumePackageOptions *opts)
448 opts->nLargeVnodes = opts->nSmallVnodes = 5;
451 opts->canScheduleSalvage = 0;
452 opts->canUseFSSYNC = 0;
453 opts->canUseSALVSYNC = 0;
457 opts->canScheduleSalvage = 1;
458 opts->canUseSALVSYNC = 1;
462 opts->canUseFSSYNC = 1;
466 opts->nLargeVnodes = 0;
467 opts->nSmallVnodes = 0;
469 opts->canScheduleSalvage = 1;
470 opts->canUseFSSYNC = 1;
480 VInitVolumePackage2(ProgramType pt, VolumePackageOptions * opts)
482 int errors = 0; /* Number of errors while finding vice partitions. */
487 memset(&VStats, 0, sizeof(VStats));
488 VStats.hdr_cache_size = 200;
490 VInitPartitionPackage();
492 #ifdef AFS_DEMAND_ATTACH_FS
493 if (programType == fileServer) {
496 VLRU_SetOptions(VLRU_SET_ENABLED, 0);
498 assert(pthread_key_create(&VThread_key, NULL) == 0);
501 #ifdef AFS_PTHREAD_ENV
502 assert(pthread_mutex_init(&vol_glock_mutex, NULL) == 0);
503 assert(pthread_mutex_init(&vol_trans_mutex, NULL) == 0);
504 assert(pthread_cond_init(&vol_put_volume_cond, NULL) == 0);
505 assert(pthread_cond_init(&vol_sleep_cond, NULL) == 0);
506 assert(pthread_cond_init(&vol_init_attach_cond, NULL) == 0);
507 #else /* AFS_PTHREAD_ENV */
509 #endif /* AFS_PTHREAD_ENV */
510 Lock_Init(&vol_listLock);
512 srandom(time(0)); /* For VGetVolumeInfo */
514 #ifdef AFS_DEMAND_ATTACH_FS
515 assert(pthread_mutex_init(&vol_salvsync_mutex, NULL) == 0);
516 #endif /* AFS_DEMAND_ATTACH_FS */
518 /* Ok, we have done enough initialization that fileserver can
519 * start accepting calls, even though the volumes may not be
520 * available just yet.
524 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_SERVER)
525 if (programType == salvageServer) {
528 #endif /* AFS_DEMAND_ATTACH_FS */
529 #ifdef FSSYNC_BUILD_SERVER
530 if (programType == fileServer) {
534 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_CLIENT)
535 if (VCanUseSALVSYNC()) {
536 /* establish a connection to the salvager at this point */
537 assert(VConnectSALV() != 0);
539 #endif /* AFS_DEMAND_ATTACH_FS */
541 if (opts->volcache > VStats.hdr_cache_size)
542 VStats.hdr_cache_size = opts->volcache;
543 VInitVolumeHeaderCache(VStats.hdr_cache_size);
545 VInitVnodes(vLarge, opts->nLargeVnodes);
546 VInitVnodes(vSmall, opts->nSmallVnodes);
549 errors = VAttachPartitions();
553 if (programType != fileServer) {
554 errors = VInitAttachVolumes(programType);
560 #ifdef FSSYNC_BUILD_CLIENT
561 if (VCanUseFSSYNC()) {
563 #ifdef AFS_DEMAND_ATTACH_FS
564 if (programType == salvageServer) {
565 Log("Unable to connect to file server; aborted\n");
568 #endif /* AFS_DEMAND_ATTACH_FS */
569 Log("Unable to connect to file server; will retry at need\n");
572 #endif /* FSSYNC_BUILD_CLIENT */
577 VInitAttachVolumes(ProgramType pt)
580 if (pt == fileServer) {
581 struct DiskPartition64 *diskP;
582 #ifdef AFS_PTHREAD_ENV
583 struct vinitvolumepackage_thread_t params;
584 struct diskpartition_queue_t * dpq;
585 int i, threads, parts;
587 pthread_attr_t attrs;
589 assert(pthread_cond_init(¶ms.thread_done_cv,NULL) == 0);
591 params.n_threads_complete = 0;
593 /* create partition work queue */
594 for (parts=0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
595 dpq = (diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
598 queue_Append(¶ms,dpq);
601 threads = MIN(parts, vol_attach_threads);
604 /* spawn off a bunch of initialization threads */
605 assert(pthread_attr_init(&attrs) == 0);
606 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
608 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
609 #ifdef AFS_DEMAND_ATTACH_FS
610 Log("VInitVolumePackage: using %d threads to pre-attach volumes on %d partitions\n",
612 #else /* AFS_DEMAND_ATTACH_FS */
613 Log("VInitVolumePackage: using %d threads to attach volumes on %d partitions\n",
615 #endif /* AFS_DEMAND_ATTACH_FS */
618 for (i=0; i < threads; i++) {
621 assert(pthread_create
622 (&tid, &attrs, &VInitVolumePackageThread,
624 AFS_SIGSET_RESTORE();
627 while(params.n_threads_complete < threads) {
628 VOL_CV_WAIT(¶ms.thread_done_cv);
632 assert(pthread_attr_destroy(&attrs) == 0);
634 /* if we're only going to run one init thread, don't bother creating
636 Log("VInitVolumePackage: beginning single-threaded fileserver startup\n");
637 #ifdef AFS_DEMAND_ATTACH_FS
638 Log("VInitVolumePackage: using 1 thread to pre-attach volumes on %d partition(s)\n",
640 #else /* AFS_DEMAND_ATTACH_FS */
641 Log("VInitVolumePackage: using 1 thread to attach volumes on %d partition(s)\n",
643 #endif /* AFS_DEMAND_ATTACH_FS */
645 VInitVolumePackageThread(¶ms);
648 assert(pthread_cond_destroy(¶ms.thread_done_cv) == 0);
650 #else /* AFS_PTHREAD_ENV */
652 /* Attach all the volumes in this partition */
653 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
654 int nAttached = 0, nUnattached = 0;
655 assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
657 #endif /* AFS_PTHREAD_ENV */
660 VInit = 2; /* Initialized, and all volumes have been attached */
661 #ifdef AFS_PTHREAD_ENV
662 assert(pthread_cond_broadcast(&vol_init_attach_cond) == 0);
664 LWP_NoYieldSignal(VInitAttachVolumes);
665 #endif /* AFS_PTHREAD_ENV */
670 #ifdef AFS_PTHREAD_ENV
672 VInitVolumePackageThread(void * args) {
674 struct DiskPartition64 *diskP;
675 struct vinitvolumepackage_thread_t * params;
676 struct diskpartition_queue_t * dpq;
678 params = (vinitvolumepackage_thread_t *) args;
682 /* Attach all the volumes in this partition */
683 while (queue_IsNotEmpty(params)) {
684 int nAttached = 0, nUnattached = 0;
686 if (vinit_attach_abort) {
687 Log("Aborting initialization\n");
691 dpq = queue_First(params,diskpartition_queue_t);
697 assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
703 params->n_threads_complete++;
704 pthread_cond_signal(¶ms->thread_done_cv);
708 #endif /* AFS_PTHREAD_ENV */
711 * attach all volumes on a given disk partition
714 VAttachVolumesByPartition(struct DiskPartition64 *diskP, int * nAttached, int * nUnattached)
720 Log("Partition %s: attaching volumes\n", diskP->name);
721 dirp = opendir(VPartitionPath(diskP));
723 Log("opendir on Partition %s failed!\n", diskP->name);
727 while ((dp = readdir(dirp))) {
729 p = strrchr(dp->d_name, '.');
731 if (vinit_attach_abort) {
732 Log("Partition %s: abort attach volumes\n", diskP->name);
736 if (p != NULL && strcmp(p, VHDREXT) == 0) {
739 #ifdef AFS_DEMAND_ATTACH_FS
740 vp = VPreAttachVolumeByName(&error, diskP->name, dp->d_name);
741 #else /* AFS_DEMAND_ATTACH_FS */
742 vp = VAttachVolumeByName(&error, diskP->name, dp->d_name,
744 #endif /* AFS_DEMAND_ATTACH_FS */
745 (*(vp ? nAttached : nUnattached))++;
746 if (error == VOFFLINE)
747 Log("Volume %d stays offline (/vice/offline/%s exists)\n", VolumeNumber(dp->d_name), dp->d_name);
748 else if (LogLevel >= 5) {
749 Log("Partition %s: attached volume %d (%s)\n",
750 diskP->name, VolumeNumber(dp->d_name),
753 #if !defined(AFS_DEMAND_ATTACH_FS)
757 #endif /* AFS_DEMAND_ATTACH_FS */
761 Log("Partition %s: attached %d volumes; %d volumes not attached\n", diskP->name, *nAttached, *nUnattached);
768 /***************************************************/
769 /* Shutdown routines */
770 /***************************************************/
774 * highly multithreaded volume package shutdown
776 * with the demand attach fileserver extensions,
777 * VShutdown has been modified to be multithreaded.
778 * In order to achieve optimal use of many threads,
779 * the shutdown code involves one control thread and
780 * n shutdown worker threads. The control thread
781 * periodically examines the number of volumes available
782 * for shutdown on each partition, and produces a worker
783 * thread allocation schedule. The idea is to eliminate
784 * redundant scheduling computation on the workers by
785 * having a single master scheduler.
787 * The scheduler's objectives are:
789 * each partition with volumes remaining gets allocated
790 * at least 1 thread (assuming sufficient threads)
792 * threads are allocated proportional to the number of
793 * volumes remaining to be offlined. This ensures that
794 * the OS I/O scheduler has many requests to elevator
795 * seek on partitions that will (presumably) take the
796 * longest amount of time (from now) to finish shutdown
797 * (3) keep threads busy
798 * when there are extra threads, they are assigned to
799 * partitions using a simple round-robin algorithm
801 * In the future, we may wish to add the ability to adapt
802 * to the relative performance patterns of each disk
807 * multi-step shutdown process
809 * demand attach shutdown is a four-step process. Each
810 * shutdown "pass" shuts down increasingly more difficult
811 * volumes. The main purpose is to achieve better cache
812 * utilization during shutdown.
815 * shutdown volumes in the unattached, pre-attached
818 * shutdown attached volumes with cached volume headers
820 * shutdown all volumes in non-exclusive states
822 * shutdown all remaining volumes
825 #ifdef AFS_DEMAND_ATTACH_FS
831 struct DiskPartition64 * diskP;
832 struct diskpartition_queue_t * dpq;
833 vshutdown_thread_t params;
835 pthread_attr_t attrs;
837 memset(¶ms, 0, sizeof(vshutdown_thread_t));
840 Log("VShutdown: aborting attach volumes\n");
841 vinit_attach_abort = 1;
842 VOL_CV_WAIT(&vol_init_attach_cond);
845 for (params.n_parts=0, diskP = DiskPartitionList;
846 diskP; diskP = diskP->next, params.n_parts++);
848 Log("VShutdown: shutting down on-line volumes on %d partition%s...\n",
849 params.n_parts, params.n_parts > 1 ? "s" : "");
851 if (vol_attach_threads > 1) {
852 /* prepare for parallel shutdown */
853 params.n_threads = vol_attach_threads;
854 assert(pthread_mutex_init(¶ms.lock, NULL) == 0);
855 assert(pthread_cond_init(¶ms.cv, NULL) == 0);
856 assert(pthread_cond_init(¶ms.master_cv, NULL) == 0);
857 assert(pthread_attr_init(&attrs) == 0);
858 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
861 /* setup the basic partition information structures for
862 * parallel shutdown */
863 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
865 struct rx_queue * qp, * nqp;
869 VVByPListWait_r(diskP);
870 VVByPListBeginExclusive_r(diskP);
873 for (queue_Scan(&diskP->vol_list, qp, nqp, rx_queue)) {
874 vp = (Volume *)((char *)qp - offsetof(Volume, vol_list));
878 Log("VShutdown: partition %s has %d volumes with attached headers\n",
879 VPartitionPath(diskP), count);
882 /* build up the pass 0 shutdown work queue */
883 dpq = (struct diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
886 queue_Prepend(¶ms, dpq);
888 params.part_pass_head[diskP->index] = queue_First(&diskP->vol_list, rx_queue);
891 Log("VShutdown: beginning parallel fileserver shutdown\n");
892 Log("VShutdown: using %d threads to offline volumes on %d partition%s\n",
893 vol_attach_threads, params.n_parts, params.n_parts > 1 ? "s" : "" );
895 /* do pass 0 shutdown */
896 assert(pthread_mutex_lock(¶ms.lock) == 0);
897 for (i=0; i < params.n_threads; i++) {
898 assert(pthread_create
899 (&tid, &attrs, &VShutdownThread,
903 /* wait for all the pass 0 shutdowns to complete */
904 while (params.n_threads_complete < params.n_threads) {
905 assert(pthread_cond_wait(¶ms.master_cv, ¶ms.lock) == 0);
907 params.n_threads_complete = 0;
909 assert(pthread_cond_broadcast(¶ms.cv) == 0);
910 assert(pthread_mutex_unlock(¶ms.lock) == 0);
912 Log("VShutdown: pass 0 completed using the 1 thread per partition algorithm\n");
913 Log("VShutdown: starting passes 1 through 3 using finely-granular mp-fast algorithm\n");
915 /* run the parallel shutdown scheduler. it will drop the glock internally */
916 ShutdownController(¶ms);
918 /* wait for all the workers to finish pass 3 and terminate */
919 while (params.pass < 4) {
920 VOL_CV_WAIT(¶ms.cv);
923 assert(pthread_attr_destroy(&attrs) == 0);
924 assert(pthread_cond_destroy(¶ms.cv) == 0);
925 assert(pthread_cond_destroy(¶ms.master_cv) == 0);
926 assert(pthread_mutex_destroy(¶ms.lock) == 0);
928 /* drop the VByPList exclusive reservations */
929 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
930 VVByPListEndExclusive_r(diskP);
931 Log("VShutdown: %s stats : (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
932 VPartitionPath(diskP),
933 params.stats[0][diskP->index],
934 params.stats[1][diskP->index],
935 params.stats[2][diskP->index],
936 params.stats[3][diskP->index]);
939 Log("VShutdown: shutdown finished using %d threads\n", params.n_threads);
941 /* if we're only going to run one shutdown thread, don't bother creating
943 Log("VShutdown: beginning single-threaded fileserver shutdown\n");
945 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
946 VShutdownByPartition_r(diskP);
950 Log("VShutdown: complete.\n");
953 #else /* AFS_DEMAND_ATTACH_FS */
959 register Volume *vp, *np;
960 register afs_int32 code;
963 Log("VShutdown: aborting attach volumes\n");
964 vinit_attach_abort = 1;
965 #ifdef AFS_PTHREAD_ENV
966 VOL_CV_WAIT(&vol_init_attach_cond);
968 LWP_WaitProcess(VInitAttachVolumes);
969 #endif /* AFS_PTHREAD_ENV */
972 Log("VShutdown: shutting down on-line volumes...\n");
973 for (i = 0; i < VolumeHashTable.Size; i++) {
974 /* try to hold first volume in the hash table */
975 for (queue_Scan(&VolumeHashTable.Table[i],vp,np,Volume)) {
979 Log("VShutdown: Attempting to take volume %u offline.\n",
982 /* next, take the volume offline (drops reference count) */
983 VOffline_r(vp, "File server was shut down");
987 Log("VShutdown: complete.\n");
989 #endif /* AFS_DEMAND_ATTACH_FS */
1002 * stop new activity (e.g. SALVSYNC) from occurring
1004 * Use this to make the volume package less busy; for example, during
1005 * shutdown. This doesn't actually shutdown/detach anything in the
1006 * volume package, but prevents certain processes from ocurring. For
1007 * example, preventing new SALVSYNC communication in DAFS. In theory, we
1008 * could also use this to prevent new volume attachment, or prevent
1009 * other programs from checking out volumes, etc.
1014 #ifdef AFS_DEMAND_ATTACH_FS
1015 /* make sure we don't try to contact the salvageserver, since it may
1016 * not be around anymore */
1017 vol_disallow_salvsync = 1;
1021 #ifdef AFS_DEMAND_ATTACH_FS
1024 * shutdown control thread
1027 ShutdownController(vshutdown_thread_t * params)
1030 struct DiskPartition64 * diskP;
1032 vshutdown_thread_t shadow;
1034 ShutdownCreateSchedule(params);
1036 while ((params->pass < 4) &&
1037 (params->n_threads_complete < params->n_threads)) {
1038 /* recompute schedule once per second */
1040 memcpy(&shadow, params, sizeof(vshutdown_thread_t));
1044 Log("ShutdownController: schedule version=%d, vol_remaining=%d, pass=%d\n",
1045 shadow.schedule_version, shadow.vol_remaining, shadow.pass);
1046 Log("ShutdownController: n_threads_complete=%d, n_parts_done_pass=%d\n",
1047 shadow.n_threads_complete, shadow.n_parts_done_pass);
1048 for (diskP = DiskPartitionList; diskP; diskP=diskP->next) {
1050 Log("ShutdownController: part[%d] : (len=%d, thread_target=%d, done_pass=%d, pass_head=%p)\n",
1052 diskP->vol_list.len,
1053 shadow.part_thread_target[id],
1054 shadow.part_done_pass[id],
1055 shadow.part_pass_head[id]);
1061 ShutdownCreateSchedule(params);
1065 /* create the shutdown thread work schedule.
1066 * this scheduler tries to implement fairness
1067 * by allocating at least 1 thread to each
1068 * partition with volumes to be shutdown,
1069 * and then it attempts to allocate remaining
1070 * threads based upon the amount of work left
1073 ShutdownCreateSchedule(vshutdown_thread_t * params)
1075 struct DiskPartition64 * diskP;
1076 int sum, thr_workload, thr_left;
1077 int part_residue[VOLMAXPARTS+1];
1080 /* compute the total number of outstanding volumes */
1082 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1083 sum += diskP->vol_list.len;
1086 params->schedule_version++;
1087 params->vol_remaining = sum;
1092 /* compute average per-thread workload */
1093 thr_workload = sum / params->n_threads;
1094 if (sum % params->n_threads)
1097 thr_left = params->n_threads;
1098 memset(&part_residue, 0, sizeof(part_residue));
1100 /* for fairness, give every partition with volumes remaining
1101 * at least one thread */
1102 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1104 if (diskP->vol_list.len) {
1105 params->part_thread_target[id] = 1;
1108 params->part_thread_target[id] = 0;
1112 if (thr_left && thr_workload) {
1113 /* compute length-weighted workloads */
1116 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1118 delta = (diskP->vol_list.len / thr_workload) -
1119 params->part_thread_target[id];
1123 if (delta < thr_left) {
1124 params->part_thread_target[id] += delta;
1127 params->part_thread_target[id] += thr_left;
1135 /* try to assign any leftover threads to partitions that
1136 * had volume lengths closer to needing thread_target+1 */
1137 int max_residue, max_id = 0;
1139 /* compute the residues */
1140 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1142 part_residue[id] = diskP->vol_list.len -
1143 (params->part_thread_target[id] * thr_workload);
1146 /* now try to allocate remaining threads to partitions with the
1147 * highest residues */
1150 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1152 if (part_residue[id] > max_residue) {
1153 max_residue = part_residue[id];
1162 params->part_thread_target[max_id]++;
1164 part_residue[max_id] = 0;
1169 /* punt and give any remaining threads equally to each partition */
1171 if (thr_left >= params->n_parts) {
1172 alloc = thr_left / params->n_parts;
1173 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1175 params->part_thread_target[id] += alloc;
1180 /* finish off the last of the threads */
1181 for (diskP = DiskPartitionList; thr_left && diskP; diskP = diskP->next) {
1183 params->part_thread_target[id]++;
1189 /* worker thread for parallel shutdown */
1191 VShutdownThread(void * args)
1193 vshutdown_thread_t * params;
1194 int found, pass, schedule_version_save, count;
1195 struct DiskPartition64 *diskP;
1196 struct diskpartition_queue_t * dpq;
1199 params = (vshutdown_thread_t *) args;
1201 /* acquire the shutdown pass 0 lock */
1202 assert(pthread_mutex_lock(¶ms->lock) == 0);
1204 /* if there's still pass 0 work to be done,
1205 * get a work entry, and do a pass 0 shutdown */
1206 if (queue_IsNotEmpty(params)) {
1207 dpq = queue_First(params, diskpartition_queue_t);
1209 assert(pthread_mutex_unlock(¶ms->lock) == 0);
1215 while (ShutdownVolumeWalk_r(diskP, 0, ¶ms->part_pass_head[id]))
1217 params->stats[0][diskP->index] = count;
1218 assert(pthread_mutex_lock(¶ms->lock) == 0);
1221 params->n_threads_complete++;
1222 if (params->n_threads_complete == params->n_threads) {
1223 /* notify control thread that all workers have completed pass 0 */
1224 assert(pthread_cond_signal(¶ms->master_cv) == 0);
1226 while (params->pass == 0) {
1227 assert(pthread_cond_wait(¶ms->cv, ¶ms->lock) == 0);
1231 assert(pthread_mutex_unlock(¶ms->lock) == 0);
1234 pass = params->pass;
1237 /* now escalate through the more complicated shutdowns */
1239 schedule_version_save = params->schedule_version;
1241 /* find a disk partition to work on */
1242 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1244 if (params->part_thread_target[id] && !params->part_done_pass[id]) {
1245 params->part_thread_target[id]--;
1252 /* hmm. for some reason the controller thread couldn't find anything for
1253 * us to do. let's see if there's anything we can do */
1254 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1256 if (diskP->vol_list.len && !params->part_done_pass[id]) {
1259 } else if (!params->part_done_pass[id]) {
1260 params->part_done_pass[id] = 1;
1261 params->n_parts_done_pass++;
1263 Log("VShutdown: done shutting down volumes on partition %s.\n",
1264 VPartitionPath(diskP));
1270 /* do work on this partition until either the controller
1271 * creates a new schedule, or we run out of things to do
1272 * on this partition */
1275 while (!params->part_done_pass[id] &&
1276 (schedule_version_save == params->schedule_version)) {
1277 /* ShutdownVolumeWalk_r will drop the glock internally */
1278 if (!ShutdownVolumeWalk_r(diskP, pass, ¶ms->part_pass_head[id])) {
1279 if (!params->part_done_pass[id]) {
1280 params->part_done_pass[id] = 1;
1281 params->n_parts_done_pass++;
1283 Log("VShutdown: done shutting down volumes on partition %s.\n",
1284 VPartitionPath(diskP));
1292 params->stats[pass][id] += count;
1294 /* ok, everyone is done this pass, proceed */
1297 params->n_threads_complete++;
1298 while (params->pass == pass) {
1299 if (params->n_threads_complete == params->n_threads) {
1300 /* we are the last thread to complete, so we will
1301 * reinitialize worker pool state for the next pass */
1302 params->n_threads_complete = 0;
1303 params->n_parts_done_pass = 0;
1305 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1307 params->part_done_pass[id] = 0;
1308 params->part_pass_head[id] = queue_First(&diskP->vol_list, rx_queue);
1311 /* compute a new thread schedule before releasing all the workers */
1312 ShutdownCreateSchedule(params);
1314 /* wake up all the workers */
1315 assert(pthread_cond_broadcast(¶ms->cv) == 0);
1318 Log("VShutdown: pass %d completed using %d threads on %d partitions\n",
1319 pass, params->n_threads, params->n_parts);
1322 VOL_CV_WAIT(¶ms->cv);
1325 pass = params->pass;
1339 /* shut down all volumes on a given disk partition
1341 * note that this function will not allow mp-fast
1342 * shutdown of a partition */
1344 VShutdownByPartition_r(struct DiskPartition64 * dp)
1350 /* wait for other exclusive ops to finish */
1351 VVByPListWait_r(dp);
1353 /* begin exclusive access */
1354 VVByPListBeginExclusive_r(dp);
1356 /* pick the low-hanging fruit first,
1357 * then do the complicated ones last
1358 * (has the advantage of keeping
1359 * in-use volumes up until the bitter end) */
1360 for (pass = 0, total=0; pass < 4; pass++) {
1361 pass_stats[pass] = ShutdownVByPForPass_r(dp, pass);
1362 total += pass_stats[pass];
1365 /* end exclusive access */
1366 VVByPListEndExclusive_r(dp);
1368 Log("VShutdownByPartition: shut down %d volumes on %s (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1369 total, VPartitionPath(dp), pass_stats[0], pass_stats[1], pass_stats[2], pass_stats[3]);
1374 /* internal shutdown functionality
1376 * for multi-pass shutdown:
1377 * 0 to only "shutdown" {pre,un}attached and error state volumes
1378 * 1 to also shutdown attached volumes w/ volume header loaded
1379 * 2 to also shutdown attached volumes w/o volume header loaded
1380 * 3 to also shutdown exclusive state volumes
1382 * caller MUST hold exclusive access on the hash chain
1383 * because we drop vol_glock_mutex internally
1385 * this function is reentrant for passes 1--3
1386 * (e.g. multiple threads can cooperate to
1387 * shutdown a partition mp-fast)
1389 * pass 0 is not scaleable because the volume state data is
1390 * synchronized by vol_glock mutex, and the locking overhead
1391 * is too high to drop the lock long enough to do linked list
1395 ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass)
1397 struct rx_queue * q = queue_First(&dp->vol_list, rx_queue);
1400 while (ShutdownVolumeWalk_r(dp, pass, &q))
1406 /* conditionally shutdown one volume on partition dp
1407 * returns 1 if a volume was shutdown in this pass,
1410 ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
1411 struct rx_queue ** idx)
1413 struct rx_queue *qp, *nqp;
1418 for (queue_ScanFrom(&dp->vol_list, qp, qp, nqp, rx_queue)) {
1419 vp = (Volume *) (((char *)qp) - offsetof(Volume, vol_list));
1423 if ((V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1424 (V_attachState(vp) != VOL_STATE_ERROR) &&
1425 (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1429 if ((V_attachState(vp) == VOL_STATE_ATTACHED) &&
1430 (vp->header == NULL)) {
1434 if (VIsExclusiveState(V_attachState(vp))) {
1439 DeleteVolumeFromVByPList_r(vp);
1440 VShutdownVolume_r(vp);
1450 * shutdown a specific volume
1452 /* caller MUST NOT hold a heavyweight ref on vp */
1454 VShutdownVolume_r(Volume * vp)
1458 VCreateReservation_r(vp);
1460 if (LogLevel >= 5) {
1461 Log("VShutdownVolume_r: vid=%u, device=%d, state=%hu\n",
1462 vp->hashid, vp->partition->device, V_attachState(vp));
1465 /* wait for other blocking ops to finish */
1466 VWaitExclusiveState_r(vp);
1468 assert(VIsValidState(V_attachState(vp)));
1470 switch(V_attachState(vp)) {
1471 case VOL_STATE_SALVAGING:
1472 /* Leave salvaging volumes alone. Any in-progress salvages will
1473 * continue working after viced shuts down. This is intentional.
1476 case VOL_STATE_PREATTACHED:
1477 case VOL_STATE_ERROR:
1478 VChangeState_r(vp, VOL_STATE_UNATTACHED);
1479 case VOL_STATE_UNATTACHED:
1481 case VOL_STATE_GOING_OFFLINE:
1482 case VOL_STATE_SHUTTING_DOWN:
1483 case VOL_STATE_ATTACHED:
1487 Log("VShutdown: Attempting to take volume %u offline.\n",
1490 /* take the volume offline (drops reference count) */
1491 VOffline_r(vp, "File server was shut down");
1498 VCancelReservation_r(vp);
1502 #endif /* AFS_DEMAND_ATTACH_FS */
1505 /***************************************************/
1506 /* Header I/O routines */
1507 /***************************************************/
1509 /* open a descriptor for the inode (h),
1510 * read in an on-disk structure into buffer (to) of size (size),
1511 * verify versionstamp in structure has magic (magic) and
1512 * optionally verify version (version) if (version) is nonzero
1515 ReadHeader(Error * ec, IHandle_t * h, char *to, int size, bit32 magic,
1518 struct versionStamp *vsn;
1533 if (FDH_SEEK(fdP, 0, SEEK_SET) < 0) {
1535 FDH_REALLYCLOSE(fdP);
1538 vsn = (struct versionStamp *)to;
1539 if (FDH_READ(fdP, to, size) != size || vsn->magic != magic) {
1541 FDH_REALLYCLOSE(fdP);
1546 /* Check is conditional, in case caller wants to inspect version himself */
1547 if (version && vsn->version != version) {
1553 WriteVolumeHeader_r(Error * ec, Volume * vp)
1555 IHandle_t *h = V_diskDataHandle(vp);
1565 if (FDH_SEEK(fdP, 0, SEEK_SET) < 0) {
1567 FDH_REALLYCLOSE(fdP);
1570 if (FDH_WRITE(fdP, (char *)&V_disk(vp), sizeof(V_disk(vp)))
1571 != sizeof(V_disk(vp))) {
1573 FDH_REALLYCLOSE(fdP);
1579 /* VolumeHeaderToDisk
1580 * Allows for storing 64 bit inode numbers in on-disk volume header
1583 /* convert in-memory representation of a volume header to the
1584 * on-disk representation of a volume header */
1586 VolumeHeaderToDisk(VolumeDiskHeader_t * dh, VolumeHeader_t * h)
1589 memset(dh, 0, sizeof(VolumeDiskHeader_t));
1590 dh->stamp = h->stamp;
1592 dh->parent = h->parent;
1594 #ifdef AFS_64BIT_IOPS_ENV
1595 dh->volumeInfo_lo = (afs_int32) h->volumeInfo & 0xffffffff;
1596 dh->volumeInfo_hi = (afs_int32) (h->volumeInfo >> 32) & 0xffffffff;
1597 dh->smallVnodeIndex_lo = (afs_int32) h->smallVnodeIndex & 0xffffffff;
1598 dh->smallVnodeIndex_hi =
1599 (afs_int32) (h->smallVnodeIndex >> 32) & 0xffffffff;
1600 dh->largeVnodeIndex_lo = (afs_int32) h->largeVnodeIndex & 0xffffffff;
1601 dh->largeVnodeIndex_hi =
1602 (afs_int32) (h->largeVnodeIndex >> 32) & 0xffffffff;
1603 dh->linkTable_lo = (afs_int32) h->linkTable & 0xffffffff;
1604 dh->linkTable_hi = (afs_int32) (h->linkTable >> 32) & 0xffffffff;
1606 dh->volumeInfo_lo = h->volumeInfo;
1607 dh->smallVnodeIndex_lo = h->smallVnodeIndex;
1608 dh->largeVnodeIndex_lo = h->largeVnodeIndex;
1609 dh->linkTable_lo = h->linkTable;
1613 /* DiskToVolumeHeader
1614 * Converts an on-disk representation of a volume header to
1615 * the in-memory representation of a volume header.
1617 * Makes the assumption that AFS has *always*
1618 * zero'd the volume header file so that high parts of inode
1619 * numbers are 0 in older (SGI EFS) volume header files.
1622 DiskToVolumeHeader(VolumeHeader_t * h, VolumeDiskHeader_t * dh)
1624 memset(h, 0, sizeof(VolumeHeader_t));
1625 h->stamp = dh->stamp;
1627 h->parent = dh->parent;
1629 #ifdef AFS_64BIT_IOPS_ENV
1631 (Inode) dh->volumeInfo_lo | ((Inode) dh->volumeInfo_hi << 32);
1633 h->smallVnodeIndex =
1634 (Inode) dh->smallVnodeIndex_lo | ((Inode) dh->
1635 smallVnodeIndex_hi << 32);
1637 h->largeVnodeIndex =
1638 (Inode) dh->largeVnodeIndex_lo | ((Inode) dh->
1639 largeVnodeIndex_hi << 32);
1641 (Inode) dh->linkTable_lo | ((Inode) dh->linkTable_hi << 32);
1643 h->volumeInfo = dh->volumeInfo_lo;
1644 h->smallVnodeIndex = dh->smallVnodeIndex_lo;
1645 h->largeVnodeIndex = dh->largeVnodeIndex_lo;
1646 h->linkTable = dh->linkTable_lo;
1651 /***************************************************/
1652 /* Volume Attachment routines */
1653 /***************************************************/
1655 #ifdef AFS_DEMAND_ATTACH_FS
1657 * pre-attach a volume given its path.
1659 * @param[out] ec outbound error code
1660 * @param[in] partition partition path string
1661 * @param[in] name volume id string
1663 * @return volume object pointer
1665 * @note A pre-attached volume will only have its partition
1666 * and hashid fields initialized. At first call to
1667 * VGetVolume, the volume will be fully attached.
1671 VPreAttachVolumeByName(Error * ec, char *partition, char *name)
1675 vp = VPreAttachVolumeByName_r(ec, partition, name);
1681 * pre-attach a volume given its path.
1683 * @param[out] ec outbound error code
1684 * @param[in] partition path to vice partition
1685 * @param[in] name volume id string
1687 * @return volume object pointer
1689 * @pre VOL_LOCK held
1691 * @internal volume package internal use only.
1694 VPreAttachVolumeByName_r(Error * ec, char *partition, char *name)
1696 return VPreAttachVolumeById_r(ec,
1698 VolumeNumber(name));
1702 * pre-attach a volume given its path and numeric volume id.
1704 * @param[out] ec error code return
1705 * @param[in] partition path to vice partition
1706 * @param[in] volumeId numeric volume id
1708 * @return volume object pointer
1710 * @pre VOL_LOCK held
1712 * @internal volume package internal use only.
1715 VPreAttachVolumeById_r(Error * ec,
1720 struct DiskPartition64 *partp;
1724 assert(programType == fileServer);
1726 if (!(partp = VGetPartition_r(partition, 0))) {
1728 Log("VPreAttachVolumeById_r: Error getting partition (%s)\n", partition);
1732 vp = VLookupVolume_r(ec, volumeId, NULL);
1737 return VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
1741 * preattach a volume.
1743 * @param[out] ec outbound error code
1744 * @param[in] partp pointer to partition object
1745 * @param[in] vp pointer to volume object
1746 * @param[in] vid volume id
1748 * @return volume object pointer
1750 * @pre VOL_LOCK is held.
1752 * @warning Returned volume object pointer does not have to
1753 * equal the pointer passed in as argument vp. There
1754 * are potential race conditions which can result in
1755 * the pointers having different values. It is up to
1756 * the caller to make sure that references are handled
1757 * properly in this case.
1759 * @note If there is already a volume object registered with
1760 * the same volume id, its pointer MUST be passed as
1761 * argument vp. Failure to do so will result in a silent
1762 * failure to preattach.
1764 * @internal volume package internal use only.
1767 VPreAttachVolumeByVp_r(Error * ec,
1768 struct DiskPartition64 * partp,
1776 /* check to see if pre-attach already happened */
1778 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1779 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
1780 !VIsErrorState(V_attachState(vp))) {
1782 * pre-attach is a no-op in all but the following cases:
1784 * - volume is unattached
1785 * - volume is in an error state
1786 * - volume is pre-attached
1788 Log("VPreattachVolumeByVp_r: volume %u not in quiescent state\n", vid);
1791 /* we're re-attaching a volume; clear out some old state */
1792 memset(&vp->salvage, 0, sizeof(struct VolumeOnlineSalvage));
1794 if (V_partition(vp) != partp) {
1795 /* XXX potential race */
1796 DeleteVolumeFromVByPList_r(vp);
1799 /* if we need to allocate a new Volume struct,
1800 * go ahead and drop the vol glock, otherwise
1801 * do the basic setup synchronised, as it's
1802 * probably not worth dropping the lock */
1805 /* allocate the volume structure */
1806 vp = nvp = (Volume *) malloc(sizeof(Volume));
1808 memset(vp, 0, sizeof(Volume));
1809 queue_Init(&vp->vnode_list);
1810 assert(pthread_cond_init(&V_attachCV(vp), NULL) == 0);
1813 /* link the volume with its associated vice partition */
1814 vp->device = partp->device;
1815 vp->partition = partp;
1818 vp->specialStatus = 0;
1820 /* if we dropped the lock, reacquire the lock,
1821 * check for pre-attach races, and then add
1822 * the volume to the hash table */
1825 nvp = VLookupVolume_r(ec, vid, NULL);
1830 } else if (nvp) { /* race detected */
1835 /* hack to make up for VChangeState_r() decrementing
1836 * the old state counter */
1837 VStats.state_levels[0]++;
1841 /* put pre-attached volume onto the hash table
1842 * and bring it up to the pre-attached state */
1843 AddVolumeToHashTable(vp, vp->hashid);
1844 AddVolumeToVByPList_r(vp);
1845 VLRU_Init_Node_r(vp);
1846 VChangeState_r(vp, VOL_STATE_PREATTACHED);
1849 Log("VPreAttachVolumeByVp_r: volume %u pre-attached\n", vp->hashid);
1857 #endif /* AFS_DEMAND_ATTACH_FS */
1859 /* Attach an existing volume, given its pathname, and return a
1860 pointer to the volume header information. The volume also
1861 normally goes online at this time. An offline volume
1862 must be reattached to make it go online */
1864 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
1868 retVal = VAttachVolumeByName_r(ec, partition, name, mode);
1874 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
1876 register Volume *vp = NULL;
1878 struct afs_stat status;
1879 struct VolumeDiskHeader diskHeader;
1880 struct VolumeHeader iheader;
1881 struct DiskPartition64 *partp;
1885 #ifdef AFS_DEMAND_ATTACH_FS
1886 VolumeStats stats_save;
1888 #endif /* AFS_DEMAND_ATTACH_FS */
1892 volumeId = VolumeNumber(name);
1894 if (!(partp = VGetPartition_r(partition, 0))) {
1896 Log("VAttachVolume: Error getting partition (%s)\n", partition);
1900 if (VRequiresPartLock()) {
1902 VLockPartition_r(partition);
1903 } else if (programType == fileServer) {
1904 #ifdef AFS_DEMAND_ATTACH_FS
1905 /* lookup the volume in the hash table */
1906 vp = VLookupVolume_r(ec, volumeId, NULL);
1912 /* save any counters that are supposed to
1913 * be monotonically increasing over the
1914 * lifetime of the fileserver */
1915 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
1917 memset(&stats_save, 0, sizeof(VolumeStats));
1920 /* if there's something in the hash table, and it's not
1921 * in the pre-attach state, then we may need to detach
1922 * it before proceeding */
1923 if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1924 VCreateReservation_r(vp);
1925 VWaitExclusiveState_r(vp);
1927 /* at this point state must be one of:
1936 if (vp->specialStatus == VBUSY)
1939 /* if it's already attached, see if we can return it */
1940 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
1941 VGetVolumeByVp_r(ec, vp);
1942 if (V_inUse(vp) == fileServer) {
1943 VCancelReservation_r(vp);
1947 /* otherwise, we need to detach, and attempt to re-attach */
1948 VDetachVolume_r(ec, vp);
1950 Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
1953 /* if it isn't fully attached, delete from the hash tables,
1954 and let the refcounter handle the rest */
1955 DeleteVolumeFromHashTable(vp);
1956 DeleteVolumeFromVByPList_r(vp);
1959 VCancelReservation_r(vp);
1963 /* pre-attach volume if it hasn't been done yet */
1965 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
1966 (V_attachState(vp) == VOL_STATE_ERROR)) {
1968 vp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
1976 /* handle pre-attach races
1978 * multiple threads can race to pre-attach a volume,
1979 * but we can't let them race beyond that
1981 * our solution is to let the first thread to bring
1982 * the volume into an exclusive state win; the other
1983 * threads just wait until it finishes bringing the
1984 * volume online, and then they do a vgetvolumebyvp
1986 if (svp && (svp != vp)) {
1987 /* wait for other exclusive ops to finish */
1988 VCreateReservation_r(vp);
1989 VWaitExclusiveState_r(vp);
1991 /* get a heavyweight ref, kill the lightweight ref, and return */
1992 VGetVolumeByVp_r(ec, vp);
1993 VCancelReservation_r(vp);
1997 /* at this point, we are chosen as the thread to do
1998 * demand attachment for this volume. all other threads
1999 * doing a getvolume on vp->hashid will block until we finish */
2001 /* make sure any old header cache entries are invalidated
2002 * before proceeding */
2003 FreeVolumeHeader(vp);
2005 VChangeState_r(vp, VOL_STATE_ATTACHING);
2007 /* restore any saved counters */
2008 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2009 #else /* AFS_DEMAND_ATTACH_FS */
2010 vp = VGetVolume_r(ec, volumeId);
2012 if (V_inUse(vp) == fileServer)
2014 if (vp->specialStatus == VBUSY)
2016 VDetachVolume_r(ec, vp);
2018 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2022 #endif /* AFS_DEMAND_ATTACH_FS */
2026 strcpy(path, VPartitionPath(partp));
2032 if ((fd = afs_open(path, O_RDONLY)) == -1 || afs_fstat(fd, &status) == -1) {
2033 Log("VAttachVolume: Failed to open %s (errno %d)\n", path, errno);
2040 n = read(fd, &diskHeader, sizeof(diskHeader));
2042 if (n != sizeof(diskHeader)
2043 || diskHeader.stamp.magic != VOLUMEHEADERMAGIC) {
2044 Log("VAttachVolume: Error reading volume header %s\n", path);
2049 if (diskHeader.stamp.version != VOLUMEHEADERVERSION) {
2050 Log("VAttachVolume: Volume %s, version number is incorrect; volume needs salvaged\n", path);
2056 DiskToVolumeHeader(&iheader, &diskHeader);
2057 #ifdef FSSYNC_BUILD_CLIENT
2058 if (VCanUseFSSYNC() && mode != V_SECRETLY && mode != V_PEEK) {
2060 memset(&res, 0, sizeof(res));
2063 if (FSYNC_VolOp(iheader.id, partition, FSYNC_VOL_NEEDVOLUME, mode, &res)
2066 if (res.hdr.reason == FSYNC_SALVAGE) {
2067 Log("VAttachVolume: file server says volume %u is salvaging\n",
2071 Log("VAttachVolume: attach of volume %u apparently denied by file server\n",
2073 *ec = VNOVOL; /* XXXX */
2083 vp = (Volume *) calloc(1, sizeof(Volume));
2085 vp->hashid = volumeId;
2086 vp->device = partp->device;
2087 vp->partition = partp;
2088 queue_Init(&vp->vnode_list);
2089 #ifdef AFS_DEMAND_ATTACH_FS
2090 assert(pthread_cond_init(&V_attachCV(vp), NULL) == 0);
2091 #endif /* AFS_DEMAND_ATTACH_FS */
2094 /* attach2 is entered without any locks, and returns
2095 * with vol_glock_mutex held */
2096 vp = attach2(ec, volumeId, path, &iheader, partp, vp, isbusy, mode);
2098 if (VCanUseFSSYNC() && vp) {
2099 if ((mode == V_VOLUPD) || (VolumeWriteable(vp) && (mode == V_CLONE))) {
2100 /* mark volume header as in use so that volser crashes lead to a
2101 * salvage attempt */
2102 VUpdateVolume_r(ec, vp, 0);
2104 #ifdef AFS_DEMAND_ATTACH_FS
2105 /* for dafs, we should tell the fileserver, except for V_PEEK
2106 * where we know it is not necessary */
2107 if (mode == V_PEEK) {
2108 vp->needsPutBack = 0;
2110 vp->needsPutBack = 1;
2112 #else /* !AFS_DEMAND_ATTACH_FS */
2113 /* duplicate computation in fssync.c about whether the server
2114 * takes the volume offline or not. If the volume isn't
2115 * offline, we must not return it when we detach the volume,
2116 * or the server will abort */
2117 if (mode == V_READONLY || mode == V_PEEK
2118 || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
2119 vp->needsPutBack = 0;
2121 vp->needsPutBack = 1;
2122 #endif /* !AFS_DEMAND_ATTACH_FS */
2124 /* OK, there's a problem here, but one that I don't know how to
2125 * fix right now, and that I don't think should arise often.
2126 * Basically, we should only put back this volume to the server if
2127 * it was given to us by the server, but since we don't have a vp,
2128 * we can't run the VolumeWriteable function to find out as we do
2129 * above when computing vp->needsPutBack. So we send it back, but
2130 * there's a path in VAttachVolume on the server which may abort
2131 * if this volume doesn't have a header. Should be pretty rare
2132 * for all of that to happen, but if it does, probably the right
2133 * fix is for the server to allow the return of readonly volumes
2134 * that it doesn't think are really checked out. */
2135 #ifdef FSSYNC_BUILD_CLIENT
2136 if (VCanUseFSSYNC() && vp == NULL &&
2137 mode != V_SECRETLY && mode != V_PEEK) {
2139 #ifdef AFS_DEMAND_ATTACH_FS
2140 /* If we couldn't attach but we scheduled a salvage, we already
2141 * notified the fileserver; don't online it now */
2142 if (*ec != VSALVAGING)
2143 #endif /* AFS_DEMAND_ATTACH_FS */
2144 FSYNC_VolOp(iheader.id, partition, FSYNC_VOL_ON, 0, NULL);
2147 if (programType == fileServer && vp) {
2148 #ifdef AFS_DEMAND_ATTACH_FS
2150 * we can get here in cases where we don't "own"
2151 * the volume (e.g. volume owned by a utility).
2152 * short circuit around potential disk header races.
2154 if (V_attachState(vp) != VOL_STATE_ATTACHED) {
2158 V_needsCallback(vp) = 0;
2160 if (VInit >= 2 && V_BreakVolumeCallbacks) {
2161 Log("VAttachVolume: Volume %u was changed externally; breaking callbacks\n", V_id(vp));
2162 (*V_BreakVolumeCallbacks) (V_id(vp));
2165 VUpdateVolume_r(ec, vp, 0);
2167 Log("VAttachVolume: Error updating volume\n");
2172 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2173 #ifndef AFS_DEMAND_ATTACH_FS
2174 /* This is a hack: by temporarily setting the incore
2175 * dontSalvage flag ON, the volume will be put back on the
2176 * Update list (with dontSalvage OFF again). It will then
2177 * come back in N minutes with DONT_SALVAGE eventually
2178 * set. This is the way that volumes that have never had
2179 * it set get it set; or that volumes that have been
2180 * offline without DONT SALVAGE having been set also
2181 * eventually get it set */
2182 V_dontSalvage(vp) = DONT_SALVAGE;
2183 #endif /* !AFS_DEMAND_ATTACH_FS */
2184 VAddToVolumeUpdateList_r(ec, vp);
2186 Log("VAttachVolume: Error adding volume to update list\n");
2193 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2198 if (VRequiresPartLock()) {
2199 VUnlockPartition_r(partition);
2202 #ifdef AFS_DEMAND_ATTACH_FS
2203 /* attach failed; make sure we're in error state */
2204 if (vp && !VIsErrorState(V_attachState(vp))) {
2205 VChangeState_r(vp, VOL_STATE_ERROR);
2207 #endif /* AFS_DEMAND_ATTACH_FS */
2214 #ifdef AFS_DEMAND_ATTACH_FS
2215 /* VAttachVolumeByVp_r
2217 * finish attaching a volume that is
2218 * in a less than fully attached state
2220 /* caller MUST hold a ref count on vp */
2222 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
2224 char name[VMAXPATHLEN];
2225 int fd, n, reserve = 0;
2226 struct afs_stat status;
2227 struct VolumeDiskHeader diskHeader;
2228 struct VolumeHeader iheader;
2229 struct DiskPartition64 *partp;
2233 Volume * nvp = NULL;
2234 VolumeStats stats_save;
2237 /* volume utility should never call AttachByVp */
2238 assert(programType == fileServer);
2240 volumeId = vp->hashid;
2241 partp = vp->partition;
2242 VolumeExternalName_r(volumeId, name, sizeof(name));
2245 /* if another thread is performing a blocking op, wait */
2246 VWaitExclusiveState_r(vp);
2248 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2250 /* if it's already attached, see if we can return it */
2251 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2252 VGetVolumeByVp_r(ec, vp);
2253 if (V_inUse(vp) == fileServer) {
2256 if (vp->specialStatus == VBUSY)
2258 VDetachVolume_r(ec, vp);
2260 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2266 /* pre-attach volume if it hasn't been done yet */
2268 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2269 (V_attachState(vp) == VOL_STATE_ERROR)) {
2270 nvp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2276 VCreateReservation_r(nvp);
2282 VChangeState_r(vp, VOL_STATE_ATTACHING);
2284 /* restore monotonically increasing stats */
2285 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2290 /* compute path to disk header,
2292 * and verify magic and version stamps */
2293 strcpy(path, VPartitionPath(partp));
2299 if ((fd = afs_open(path, O_RDONLY)) == -1 || afs_fstat(fd, &status) == -1) {
2300 Log("VAttachVolume: Failed to open %s (errno %d)\n", path, errno);
2307 n = read(fd, &diskHeader, sizeof(diskHeader));
2309 if (n != sizeof(diskHeader)
2310 || diskHeader.stamp.magic != VOLUMEHEADERMAGIC) {
2311 Log("VAttachVolume: Error reading volume header %s\n", path);
2316 if (diskHeader.stamp.version != VOLUMEHEADERVERSION) {
2317 Log("VAttachVolume: Volume %s, version number is incorrect; volume needs salvaged\n", path);
2323 /* convert on-disk header format to in-memory header format */
2324 DiskToVolumeHeader(&iheader, &diskHeader);
2328 * NOTE: attach2 is entered without any locks, and returns
2329 * with vol_glock_mutex held */
2330 vp = attach2(ec, volumeId, path, &iheader, partp, vp, isbusy, mode);
2333 * the event that an error was encountered, or
2334 * the volume was not brought to an attached state
2335 * for any reason, skip to the end. We cannot
2336 * safely call VUpdateVolume unless we "own" it.
2340 (V_attachState(vp) != VOL_STATE_ATTACHED)) {
2344 V_needsCallback(vp) = 0;
2345 VUpdateVolume_r(ec, vp, 0);
2347 Log("VAttachVolume: Error updating volume %u\n", vp->hashid);
2351 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2352 #ifndef AFS_DEMAND_ATTACH_FS
2353 /* This is a hack: by temporarily setting the incore
2354 * dontSalvage flag ON, the volume will be put back on the
2355 * Update list (with dontSalvage OFF again). It will then
2356 * come back in N minutes with DONT_SALVAGE eventually
2357 * set. This is the way that volumes that have never had
2358 * it set get it set; or that volumes that have been
2359 * offline without DONT SALVAGE having been set also
2360 * eventually get it set */
2361 V_dontSalvage(vp) = DONT_SALVAGE;
2362 #endif /* !AFS_DEMAND_ATTACH_FS */
2363 VAddToVolumeUpdateList_r(ec, vp);
2365 Log("VAttachVolume: Error adding volume %u to update list\n", vp->hashid);
2372 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2376 VCancelReservation_r(nvp);
2379 if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2380 if (vp && !VIsErrorState(V_attachState(vp))) {
2381 VChangeState_r(vp, VOL_STATE_ERROR);
2390 * lock a volume on disk (non-blocking).
2392 * @param[in] vp The volume to lock
2393 * @param[in] locktype READ_LOCK or WRITE_LOCK
2395 * @return operation status
2396 * @retval 0 success, lock was obtained
2397 * @retval EBUSY a conflicting lock was held by another process
2398 * @retval EIO error acquiring lock
2400 * @pre If we're in the fileserver, vp is in an exclusive state
2402 * @pre vp is not already locked
2405 VLockVolumeNB(Volume *vp, int locktype)
2409 assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2410 assert(!(V_attachFlags(vp) & VOL_LOCKED));
2412 code = VLockVolumeByIdNB(vp->hashid, vp->partition, locktype);
2414 V_attachFlags(vp) |= VOL_LOCKED;
2421 * unlock a volume on disk that was locked with VLockVolumeNB.
2423 * @param[in] vp volume to unlock
2425 * @pre If we're in the fileserver, vp is in an exclusive state
2427 * @pre vp has already been locked
2430 VUnlockVolume(Volume *vp)
2432 assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2433 assert((V_attachFlags(vp) & VOL_LOCKED));
2435 VUnlockVolumeById(vp->hashid, vp->partition);
2437 V_attachFlags(vp) &= ~VOL_LOCKED;
2439 #endif /* AFS_DEMAND_ATTACH_FS */
2442 * called without any locks held
2443 * returns with vol_glock_mutex held
2446 attach2(Error * ec, VolId volumeId, char *path, register struct VolumeHeader * header,
2447 struct DiskPartition64 * partp, register Volume * vp, int isbusy, int mode)
2449 vp->specialStatus = (byte) (isbusy ? VBUSY : 0);
2450 IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header->parent,
2451 header->largeVnodeIndex);
2452 IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header->parent,
2453 header->smallVnodeIndex);
2454 IH_INIT(vp->diskDataHandle, partp->device, header->parent,
2455 header->volumeInfo);
2456 IH_INIT(vp->linkHandle, partp->device, header->parent, header->linkTable);
2457 vp->shuttingDown = 0;
2458 vp->goingOffline = 0;
2460 #ifdef AFS_DEMAND_ATTACH_FS
2461 vp->stats.last_attach = FT_ApproxTime();
2462 vp->stats.attaches++;
2466 IncUInt64(&VStats.attaches);
2467 vp->cacheCheck = ++VolumeCacheCheck;
2468 /* just in case this ever rolls over */
2469 if (!vp->cacheCheck)
2470 vp->cacheCheck = ++VolumeCacheCheck;
2471 GetVolumeHeader(vp);
2474 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2475 /* demand attach changes the V_PEEK mechanism
2477 * we can now suck the current disk data structure over
2478 * the fssync interface without going to disk
2480 * (technically, we don't need to restrict this feature
2481 * to demand attach fileservers. However, I'm trying
2482 * to limit the number of common code changes)
2484 if (programType != fileServer && mode == V_PEEK) {
2486 res.payload.len = sizeof(VolumeDiskData);
2487 res.payload.buf = &vp->header->diskstuff;
2489 if (FSYNC_VolOp(volumeId,
2491 FSYNC_VOL_QUERY_HDR,
2494 goto disk_header_loaded;
2497 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2498 (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2499 sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2501 #ifdef AFS_DEMAND_ATTACH_FS
2504 IncUInt64(&VStats.hdr_loads);
2505 IncUInt64(&vp->stats.hdr_loads);
2507 #endif /* AFS_DEMAND_ATTACH_FS */
2510 Log("VAttachVolume: Error reading diskDataHandle vol header %s; error=%u\n", path, *ec);
2513 #ifdef AFS_DEMAND_ATTACH_FS
2514 # ifdef FSSYNC_BUILD_CLIENT
2519 /* check for pending volume operations */
2520 if (vp->pending_vol_op) {
2521 /* see if the pending volume op requires exclusive access */
2522 switch (vp->pending_vol_op->vol_op_state) {
2523 case FSSYNC_VolOpPending:
2524 /* this should never happen */
2525 assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpPending);
2528 case FSSYNC_VolOpRunningUnknown:
2529 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
2530 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
2533 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
2534 /* fall through to take volume offline */
2537 case FSSYNC_VolOpRunningOffline:
2538 /* mark the volume down */
2540 VChangeState_r(vp, VOL_STATE_UNATTACHED);
2541 if (V_offlineMessage(vp)[0] == '\0')
2542 strlcpy(V_offlineMessage(vp),
2543 "A volume utility is running.",
2544 sizeof(V_offlineMessage(vp)));
2545 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
2547 /* check to see if we should set the specialStatus flag */
2548 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
2549 vp->specialStatus = VBUSY;
2556 V_attachFlags(vp) |= VOL_HDR_LOADED;
2557 vp->stats.last_hdr_load = vp->stats.last_attach;
2559 #endif /* AFS_DEMAND_ATTACH_FS */
2562 struct IndexFileHeader iHead;
2564 #if OPENAFS_VOL_STATS
2566 * We just read in the diskstuff part of the header. If the detailed
2567 * volume stats area has not yet been initialized, we should bzero the
2568 * area and mark it as initialized.
2570 if (!(V_stat_initialized(vp))) {
2571 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
2572 V_stat_initialized(vp) = 1;
2574 #endif /* OPENAFS_VOL_STATS */
2576 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
2577 (char *)&iHead, sizeof(iHead),
2578 SMALLINDEXMAGIC, SMALLINDEXVERSION);
2581 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
2586 struct IndexFileHeader iHead;
2588 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
2589 (char *)&iHead, sizeof(iHead),
2590 LARGEINDEXMAGIC, LARGEINDEXVERSION);
2593 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
2597 #ifdef AFS_NAMEI_ENV
2599 struct versionStamp stamp;
2601 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
2602 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
2605 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
2608 #endif /* AFS_NAMEI_ENV */
2610 #if defined(AFS_DEMAND_ATTACH_FS)
2611 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
2613 if (!VCanScheduleSalvage()) {
2614 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
2616 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2621 /* volume operation in progress */
2625 #else /* AFS_DEMAND_ATTACH_FS */
2627 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
2631 #endif /* AFS_DEMAND_ATTACH_FS */
2633 if (V_needsSalvaged(vp)) {
2634 if (vp->specialStatus)
2635 vp->specialStatus = 0;
2637 #if defined(AFS_DEMAND_ATTACH_FS)
2638 if (!VCanScheduleSalvage()) {
2639 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
2641 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
2644 #else /* AFS_DEMAND_ATTACH_FS */
2646 #endif /* AFS_DEMAND_ATTACH_FS */
2651 if (VShouldCheckInUse(mode)) {
2652 #ifndef FAST_RESTART
2653 if (V_inUse(vp) && VolumeWriteable(vp)) {
2654 if (!V_needsSalvaged(vp)) {
2655 V_needsSalvaged(vp) = 1;
2656 VUpdateVolume_r(ec, vp, 0);
2658 #if defined(AFS_DEMAND_ATTACH_FS)
2659 if (!VCanScheduleSalvage()) {
2660 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
2662 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
2665 #else /* AFS_DEMAND_ATTACH_FS */
2666 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
2668 #endif /* AFS_DEMAND_ATTACH_FS */
2672 #endif /* FAST_RESTART */
2674 if (programType == fileServer && V_destroyMe(vp) == DESTROY_ME) {
2675 /* Only check destroyMe if we are the fileserver, since the
2676 * volserver et al sometimes need to work with volumes with
2677 * destroyMe set. Examples are 'temporary' volumes the
2678 * volserver creates, and when we create a volume (destroyMe
2679 * is set on creation; sometimes a separate volserver
2680 * transaction is created to clear destroyMe).
2683 #if defined(AFS_DEMAND_ATTACH_FS)
2684 /* schedule a salvage so the volume goes away on disk */
2685 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2686 VChangeState_r(vp, VOL_STATE_ERROR);
2688 #endif /* AFS_DEMAND_ATTACH_FS */
2690 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
2696 vp->nextVnodeUnique = V_uniquifier(vp);
2697 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
2698 #ifndef BITMAP_LATER
2699 if (programType == fileServer && VolumeWriteable(vp)) {
2701 for (i = 0; i < nVNODECLASSES; i++) {
2702 VGetBitmap_r(ec, vp, i);
2704 #ifdef AFS_DEMAND_ATTACH_FS
2705 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2707 #endif /* AFS_DEMAND_ATTACH_FS */
2708 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
2714 #endif /* BITMAP_LATER */
2716 if (programType == fileServer) {
2717 if (vp->specialStatus)
2718 vp->specialStatus = 0;
2719 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
2720 V_inUse(vp) = fileServer;
2721 V_offlineMessage(vp)[0] = '\0';
2724 if ((mode != V_PEEK) && (mode != V_SECRETLY))
2725 V_inUse(vp) = programType;
2726 V_checkoutMode(vp) = mode;
2729 AddVolumeToHashTable(vp, V_id(vp));
2730 #ifdef AFS_DEMAND_ATTACH_FS
2731 if ((programType != fileServer) ||
2732 (V_inUse(vp) == fileServer)) {
2733 AddVolumeToVByPList_r(vp);
2735 VChangeState_r(vp, VOL_STATE_ATTACHED);
2737 VChangeState_r(vp, VOL_STATE_UNATTACHED);
2743 #ifdef AFS_DEMAND_ATTACH_FS
2744 if (!VIsErrorState(V_attachState(vp))) {
2745 VChangeState_r(vp, VOL_STATE_ERROR);
2747 #endif /* AFS_DEMAND_ATTACH_FS */
2749 VReleaseVolumeHandles_r(vp);
2751 #ifdef AFS_DEMAND_ATTACH_FS
2754 #else /* !AFS_DEMAND_ATTACH_FS */
2756 #endif /* !AFS_DEMAND_ATTACH_FS */
2760 /* Attach an existing volume.
2761 The volume also normally goes online at this time.
2762 An offline volume must be reattached to make it go online.
2766 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
2770 retVal = VAttachVolume_r(ec, volumeId, mode);
2776 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
2779 VGetVolumePath(ec, volumeId, &part, &name);
2781 register Volume *vp;
2783 vp = VGetVolume_r(&error, volumeId);
2785 assert(V_inUse(vp) == 0);
2786 VDetachVolume_r(ec, vp);
2790 return VAttachVolumeByName_r(ec, part, name, mode);
2793 /* Increment a reference count to a volume, sans context swaps. Requires
2794 * possibly reading the volume header in from the disk, since there's
2795 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
2797 * N.B. This call can fail if we can't read in the header!! In this case
2798 * we still guarantee we won't context swap, but the ref count won't be
2799 * incremented (otherwise we'd violate the invariant).
2801 /* NOTE: with the demand attach fileserver extensions, the global lock
2802 * is dropped within VHold */
2803 #ifdef AFS_DEMAND_ATTACH_FS
2805 VHold_r(register Volume * vp)
2809 VCreateReservation_r(vp);
2810 VWaitExclusiveState_r(vp);
2812 LoadVolumeHeader(&error, vp);
2814 VCancelReservation_r(vp);
2818 VCancelReservation_r(vp);
2821 #else /* AFS_DEMAND_ATTACH_FS */
2823 VHold_r(register Volume * vp)
2827 LoadVolumeHeader(&error, vp);
2833 #endif /* AFS_DEMAND_ATTACH_FS */
2837 VHold(register Volume * vp)
2841 retVal = VHold_r(vp);
2848 /***************************************************/
2849 /* get and put volume routines */
2850 /***************************************************/
2853 * put back a heavyweight reference to a volume object.
2855 * @param[in] vp volume object pointer
2857 * @pre VOL_LOCK held
2859 * @post heavyweight volume reference put back.
2860 * depending on state, volume may have been taken offline,
2861 * detached, salvaged, freed, etc.
2863 * @internal volume package internal use only
2866 VPutVolume_r(register Volume * vp)
2868 assert(--vp->nUsers >= 0);
2869 if (vp->nUsers == 0) {
2871 ReleaseVolumeHeader(vp->header);
2872 #ifdef AFS_DEMAND_ATTACH_FS
2873 if (!VCheckDetach(vp)) {
2877 #else /* AFS_DEMAND_ATTACH_FS */
2879 #endif /* AFS_DEMAND_ATTACH_FS */
2884 VPutVolume(register Volume * vp)
2892 /* Get a pointer to an attached volume. The pointer is returned regardless
2893 of whether or not the volume is in service or on/off line. An error
2894 code, however, is returned with an indication of the volume's status */
2896 VGetVolume(Error * ec, Error * client_ec, VolId volumeId)
2900 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
2906 VGetVolume_r(Error * ec, VolId volumeId)
2908 return GetVolume(ec, NULL, volumeId, NULL, 0);
2911 /* try to get a volume we've previously looked up */
2912 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
2914 VGetVolumeByVp_r(Error * ec, Volume * vp)
2916 return GetVolume(ec, NULL, vp->hashid, vp, 0);
2919 /* private interface for getting a volume handle
2920 * volumeId must be provided.
2921 * hint is an optional parameter to speed up hash lookups
2922 * flags is not used at this time
2924 /* for demand attach fs, caller MUST NOT hold a ref count on hint */
2926 GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint, int flags)
2929 /* pull this profiling/debugging code out of regular builds */
2931 #define VGET_CTR_INC(x) x++
2932 unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
2933 0, V7 = 0, V8 = 0, V9 = 0;
2934 unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
2936 #define VGET_CTR_INC(x)
2938 #ifdef AFS_DEMAND_ATTACH_FS
2939 Volume *avp, * rvp = hint;
2943 * if VInit is zero, the volume package dynamic
2944 * data structures have not been initialized yet,
2945 * and we must immediately return an error
2951 *client_ec = VOFFLINE;
2956 #ifdef AFS_DEMAND_ATTACH_FS
2958 VCreateReservation_r(rvp);
2960 #endif /* AFS_DEMAND_ATTACH_FS */
2968 vp = VLookupVolume_r(ec, volumeId, vp);
2974 #ifdef AFS_DEMAND_ATTACH_FS
2975 if (rvp && (rvp != vp)) {
2976 /* break reservation on old vp */
2977 VCancelReservation_r(rvp);
2980 #endif /* AFS_DEMAND_ATTACH_FS */
2986 /* Until we have reached an initialization level of 2
2987 * we don't know whether this volume exists or not.
2988 * We can't sleep and retry later because before a volume
2989 * is attached, the caller tries to get it first. Just
2990 * return VOFFLINE and the caller can choose whether to
2991 * retry the command or not. */
3001 IncUInt64(&VStats.hdr_gets);
3003 #ifdef AFS_DEMAND_ATTACH_FS
3004 /* block if someone else is performing an exclusive op on this volume */
3007 VCreateReservation_r(rvp);
3009 VWaitExclusiveState_r(vp);
3011 /* short circuit with VNOVOL in the following circumstances:
3014 * - VOL_STATE_SHUTTING_DOWN
3016 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
3017 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN) ||
3018 (V_attachState(vp) == VOL_STATE_GOING_OFFLINE)) {
3025 * short circuit with VOFFLINE in the following circumstances:
3027 * - VOL_STATE_UNATTACHED
3029 if (V_attachState(vp) == VOL_STATE_UNATTACHED) {
3030 if (vp->specialStatus) {
3031 *ec = vp->specialStatus;
3039 /* allowable states:
3045 if (vp->salvage.requested) {
3046 VUpdateSalvagePriority_r(vp);
3049 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
3050 avp = VAttachVolumeByVp_r(ec, vp, 0);
3053 /* VAttachVolumeByVp_r can return a pointer
3054 * != the vp passed to it under certain
3055 * conditions; make sure we don't leak
3056 * reservations if that happens */
3058 VCancelReservation_r(rvp);
3060 VCreateReservation_r(rvp);
3070 if (!vp->pending_vol_op) {
3085 if ((V_attachState(vp) == VOL_STATE_SALVAGING) ||
3086 (*ec == VSALVAGING)) {
3088 /* see CheckVnode() in afsfileprocs.c for an explanation
3089 * of this error code logic */
3090 afs_uint32 now = FT_ApproxTime();
3091 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
3094 *client_ec = VRESTARTING;
3103 LoadVolumeHeader(ec, vp);
3106 /* Only log the error if it was a totally unexpected error. Simply
3107 * a missing inode is likely to be caused by the volume being deleted */
3108 if (errno != ENXIO || LogLevel)
3109 Log("Volume %u: couldn't reread volume header\n",
3111 #ifdef AFS_DEMAND_ATTACH_FS
3112 if (VCanScheduleSalvage()) {
3113 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3118 #else /* AFS_DEMAND_ATTACH_FS */
3121 #endif /* AFS_DEMAND_ATTACH_FS */
3125 #ifdef AFS_DEMAND_ATTACH_FS
3127 * this test MUST happen after the volume header is loaded
3130 /* only valid before/during demand attachment */
3131 assert(!vp->pending_vol_op || vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
3133 /* deny getvolume due to running mutually exclusive vol op */
3134 if (vp->pending_vol_op && vp->pending_vol_op->vol_op_state==FSSYNC_VolOpRunningOffline) {
3136 * volume cannot remain online during this volume operation.
3139 if (vp->specialStatus) {
3141 * special status codes outrank normal VOFFLINE code
3143 *ec = vp->specialStatus;
3145 *client_ec = vp->specialStatus;
3149 /* see CheckVnode() in afsfileprocs.c for an explanation
3150 * of this error code logic */
3151 afs_uint32 now = FT_ApproxTime();
3152 if ((vp->stats.last_vol_op + (10 * 60)) >= now) {
3155 *client_ec = VRESTARTING;
3160 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3161 FreeVolumeHeader(vp);
3165 #endif /* AFS_DEMAND_ATTACH_FS */
3168 if (vp->shuttingDown) {
3175 if (programType == fileServer) {
3177 if (vp->goingOffline) {
3179 #ifdef AFS_DEMAND_ATTACH_FS
3180 /* wait for the volume to go offline */
3181 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
3182 VWaitStateChange_r(vp);
3184 #elif defined(AFS_PTHREAD_ENV)
3185 VOL_CV_WAIT(&vol_put_volume_cond);
3186 #else /* AFS_PTHREAD_ENV */
3187 LWP_WaitProcess(VPutVolume);
3188 #endif /* AFS_PTHREAD_ENV */
3191 if (vp->specialStatus) {
3193 *ec = vp->specialStatus;
3194 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3197 } else if (V_inUse(vp) == 0) {
3208 #ifdef AFS_DEMAND_ATTACH_FS
3209 /* if no error, bump nUsers */
3212 VLRU_UpdateAccess_r(vp);
3215 VCancelReservation_r(rvp);
3218 if (client_ec && !*client_ec) {
3221 #else /* AFS_DEMAND_ATTACH_FS */
3222 /* if no error, bump nUsers */
3229 #endif /* AFS_DEMAND_ATTACH_FS */
3237 /***************************************************/
3238 /* Volume offline/detach routines */
3239 /***************************************************/
3241 /* caller MUST hold a heavyweight ref on vp */
3242 #ifdef AFS_DEMAND_ATTACH_FS
3244 VTakeOffline_r(register Volume * vp)
3248 assert(vp->nUsers > 0);
3249 assert(programType == fileServer);
3251 VCreateReservation_r(vp);
3252 VWaitExclusiveState_r(vp);
3254 vp->goingOffline = 1;
3255 V_needsSalvaged(vp) = 1;
3257 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
3258 VCancelReservation_r(vp);
3260 #else /* AFS_DEMAND_ATTACH_FS */
3262 VTakeOffline_r(register Volume * vp)
3264 assert(vp->nUsers > 0);
3265 assert(programType == fileServer);
3267 vp->goingOffline = 1;
3268 V_needsSalvaged(vp) = 1;
3270 #endif /* AFS_DEMAND_ATTACH_FS */
3273 VTakeOffline(register Volume * vp)
3281 * force a volume offline.
3283 * @param[in] vp volume object pointer
3284 * @param[in] flags flags (see note below)
3286 * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
3287 * used when VUpdateVolume_r needs to call VForceOffline_r
3288 * (which in turn would normally call VUpdateVolume_r)
3290 * @see VUpdateVolume_r
3292 * @pre VOL_LOCK must be held.
3293 * for DAFS, caller must hold ref.
3295 * @note for DAFS, it _is safe_ to call this function from an
3298 * @post needsSalvaged flag is set.
3299 * for DAFS, salvage is requested.
3300 * no further references to the volume through the volume
3301 * package will be honored.
3302 * all file descriptor and vnode caches are invalidated.
3304 * @warning this is a heavy-handed interface. it results in
3305 * a volume going offline regardless of the current
3306 * reference count state.
3308 * @internal volume package internal use only
3311 VForceOffline_r(Volume * vp, int flags)
3315 #ifdef AFS_DEMAND_ATTACH_FS
3316 VChangeState_r(vp, VOL_STATE_ERROR);
3321 strcpy(V_offlineMessage(vp),
3322 "Forced offline due to internal error: volume needs to be salvaged");
3323 Log("Volume %u forced offline: it needs salvaging!\n", V_id(vp));
3326 vp->goingOffline = 0;
3327 V_needsSalvaged(vp) = 1;
3328 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
3329 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
3332 #ifdef AFS_DEMAND_ATTACH_FS
3333 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3334 #endif /* AFS_DEMAND_ATTACH_FS */
3336 #ifdef AFS_PTHREAD_ENV
3337 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3338 #else /* AFS_PTHREAD_ENV */
3339 LWP_NoYieldSignal(VPutVolume);
3340 #endif /* AFS_PTHREAD_ENV */
3342 VReleaseVolumeHandles_r(vp);
3346 * force a volume offline.
3348 * @param[in] vp volume object pointer
3350 * @see VForceOffline_r
3353 VForceOffline(Volume * vp)
3356 VForceOffline_r(vp, 0);
3360 /* The opposite of VAttachVolume. The volume header is written to disk, with
3361 the inUse bit turned off. A copy of the header is maintained in memory,
3362 however (which is why this is VOffline, not VDetach).
3365 VOffline_r(Volume * vp, char *message)
3367 #ifndef AFS_DEMAND_ATTACH_FS
3369 VolumeId vid = V_id(vp);
3372 assert(programType != volumeUtility && programType != volumeServer);
3377 if (V_offlineMessage(vp)[0] == '\0')
3378 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
3379 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
3381 vp->goingOffline = 1;
3382 #ifdef AFS_DEMAND_ATTACH_FS
3383 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
3384 VCreateReservation_r(vp);
3387 /* wait for the volume to go offline */
3388 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
3389 VWaitStateChange_r(vp);
3391 VCancelReservation_r(vp);
3392 #else /* AFS_DEMAND_ATTACH_FS */
3394 vp = VGetVolume_r(&error, vid); /* Wait for it to go offline */
3395 if (vp) /* In case it was reattached... */
3397 #endif /* AFS_DEMAND_ATTACH_FS */
3400 #ifdef AFS_DEMAND_ATTACH_FS
3402 * Take a volume offline in order to perform a volume operation.
3404 * @param[inout] ec address in which to store error code
3405 * @param[in] vp volume object pointer
3406 * @param[in] message volume offline status message
3409 * - VOL_LOCK is held
3410 * - caller MUST hold a heavyweight ref on vp
3413 * - volume is taken offline
3414 * - if possible, volume operation is promoted to running state
3415 * - on failure, *ec is set to nonzero
3417 * @note Although this function does not return any value, it may
3418 * still fail to promote our pending volume operation to
3419 * a running state. Any caller MUST check the value of *ec,
3420 * and MUST NOT blindly assume success.
3422 * @warning if the caller does not hold a lightweight ref on vp,
3423 * then it MUST NOT reference vp after this function
3424 * returns to the caller.
3426 * @internal volume package internal use only
3429 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
3431 assert(vp->pending_vol_op);
3437 if (V_offlineMessage(vp)[0] == '\0')
3438 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
3439 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
3441 vp->goingOffline = 1;
3442 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
3443 VCreateReservation_r(vp);
3446 /* Wait for the volume to go offline */
3447 while (!VIsOfflineState(V_attachState(vp))) {
3448 /* do not give corrupted volumes to the volserver */
3449 if (vp->salvage.requested && vp->pending_vol_op->com.programType != salvageServer) {
3453 VWaitStateChange_r(vp);
3457 VCancelReservation_r(vp);
3459 #endif /* AFS_DEMAND_ATTACH_FS */
3462 VOffline(Volume * vp, char *message)
3465 VOffline_r(vp, message);
3469 /* This gets used for the most part by utility routines that don't want
3470 * to keep all the volume headers around. Generally, the file server won't
3471 * call this routine, because then the offline message in the volume header
3472 * (or other information) won't be available to clients. For NAMEI, also
3473 * close the file handles. However, the fileserver does call this during
3474 * an attach following a volume operation.
3477 VDetachVolume_r(Error * ec, Volume * vp)
3480 struct DiskPartition64 *tpartp;
3481 int notifyServer = 0;
3482 int useDone = FSYNC_VOL_ON;
3484 *ec = 0; /* always "succeeds" */
3485 if (VCanUseFSSYNC()) {
3486 notifyServer = vp->needsPutBack;
3487 if (V_destroyMe(vp) == DESTROY_ME)
3488 useDone = FSYNC_VOL_DONE;
3489 #ifdef AFS_DEMAND_ATTACH_FS
3490 else if (!V_blessed(vp) || !V_inService(vp))
3491 useDone = FSYNC_VOL_LEAVE_OFF;
3494 tpartp = vp->partition;
3496 DeleteVolumeFromHashTable(vp);
3497 vp->shuttingDown = 1;
3498 #ifdef AFS_DEMAND_ATTACH_FS
3499 DeleteVolumeFromVByPList_r(vp);
3501 VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
3503 if (programType != fileServer)
3505 #endif /* AFS_DEMAND_ATTACH_FS */
3507 /* Will be detached sometime in the future--this is OK since volume is offline */
3509 /* XXX the following code should really be moved to VCheckDetach() since the volume
3510 * is not technically detached until the refcounts reach zero
3512 #ifdef FSSYNC_BUILD_CLIENT
3513 if (VCanUseFSSYNC() && notifyServer) {
3515 * Note: The server is not notified in the case of a bogus volume
3516 * explicitly to make it possible to create a volume, do a partial
3517 * restore, then abort the operation without ever putting the volume
3518 * online. This is essential in the case of a volume move operation
3519 * between two partitions on the same server. In that case, there
3520 * would be two instances of the same volume, one of them bogus,
3521 * which the file server would attempt to put on line
3523 FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
3524 /* XXX this code path is only hit by volume utilities, thus
3525 * V_BreakVolumeCallbacks will always be NULL. if we really
3526 * want to break callbacks in this path we need to use FSYNC_VolOp() */
3528 /* Dettaching it so break all callbacks on it */
3529 if (V_BreakVolumeCallbacks) {
3530 Log("volume %u detached; breaking all call backs\n", volume);
3531 (*V_BreakVolumeCallbacks) (volume);
3535 #endif /* FSSYNC_BUILD_CLIENT */
3539 VDetachVolume(Error * ec, Volume * vp)
3542 VDetachVolume_r(ec, vp);
3547 /***************************************************/
3548 /* Volume fd/inode handle closing routines */
3549 /***************************************************/
3551 /* For VDetachVolume, we close all cached file descriptors, but keep
3552 * the Inode handles in case we need to read from a busy volume.
3554 /* for demand attach, caller MUST hold ref count on vp */
3556 VCloseVolumeHandles_r(Volume * vp)
3558 #ifdef AFS_DEMAND_ATTACH_FS
3559 VolState state_save;
3561 state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
3566 * XXX need to investigate whether we can perform
3567 * DFlushVolume outside of vol_glock_mutex...
3569 * VCloseVnodeFiles_r drops the glock internally */
3570 DFlushVolume(vp->hashid);
3571 VCloseVnodeFiles_r(vp);
3573 #ifdef AFS_DEMAND_ATTACH_FS
3577 /* Too time consuming and unnecessary for the volserver */
3578 if (programType == fileServer) {
3579 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
3580 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
3581 IH_CONDSYNC(vp->diskDataHandle);
3583 IH_CONDSYNC(vp->linkHandle);
3584 #endif /* AFS_NT40_ENV */
3587 IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
3588 IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
3589 IH_REALLYCLOSE(vp->diskDataHandle);
3590 IH_REALLYCLOSE(vp->linkHandle);
3592 #ifdef AFS_DEMAND_ATTACH_FS
3594 VChangeState_r(vp, state_save);
3598 /* For both VForceOffline and VOffline, we close all relevant handles.
3599 * For VOffline, if we re-attach the volume, the files may possible be
3600 * different than before.
3602 /* for demand attach, caller MUST hold a ref count on vp */
3604 VReleaseVolumeHandles_r(Volume * vp)
3606 #ifdef AFS_DEMAND_ATTACH_FS
3607 VolState state_save;
3609 state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
3612 /* XXX need to investigate whether we can perform
3613 * DFlushVolume outside of vol_glock_mutex... */
3614 DFlushVolume(vp->hashid);
3616 VReleaseVnodeFiles_r(vp); /* releases the glock internally */
3618 #ifdef AFS_DEMAND_ATTACH_FS
3622 /* Too time consuming and unnecessary for the volserver */
3623 if (programType == fileServer) {
3624 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
3625 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
3626 IH_CONDSYNC(vp->diskDataHandle);
3628 IH_CONDSYNC(vp->linkHandle);
3629 #endif /* AFS_NT40_ENV */
3632 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
3633 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
3634 IH_RELEASE(vp->diskDataHandle);
3635 IH_RELEASE(vp->linkHandle);
3637 #ifdef AFS_DEMAND_ATTACH_FS
3639 VChangeState_r(vp, state_save);
3644 /***************************************************/
3645 /* Volume write and fsync routines */
3646 /***************************************************/
3649 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
3651 #ifdef AFS_DEMAND_ATTACH_FS
3652 VolState state_save;
3654 if (flags & VOL_UPDATE_WAIT) {
3655 VCreateReservation_r(vp);
3656 VWaitExclusiveState_r(vp);
3661 if (programType == fileServer)
3663 (V_inUse(vp) ? V_nextVnodeUnique(vp) +
3664 200 : V_nextVnodeUnique(vp));
3666 #ifdef AFS_DEMAND_ATTACH_FS
3667 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
3671 WriteVolumeHeader_r(ec, vp);
3673 #ifdef AFS_DEMAND_ATTACH_FS
3675 VChangeState_r(vp, state_save);
3676 if (flags & VOL_UPDATE_WAIT) {
3677 VCancelReservation_r(vp);
3682 Log("VUpdateVolume: error updating volume header, volume %u (%s)\n",
3683 V_id(vp), V_name(vp));
3684 /* try to update on-disk header,
3685 * while preventing infinite recursion */
3686 if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
3687 VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
3693 VUpdateVolume(Error * ec, Volume * vp)
3696 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
3701 VSyncVolume_r(Error * ec, Volume * vp, int flags)
3705 #ifdef AFS_DEMAND_ATTACH_FS
3706 VolState state_save;
3709 if (flags & VOL_SYNC_WAIT) {
3710 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
3712 VUpdateVolume_r(ec, vp, 0);
3715 #ifdef AFS_DEMAND_ATTACH_FS
3716 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
3719 fdP = IH_OPEN(V_diskDataHandle(vp));
3720 assert(fdP != NULL);
3721 code = FDH_SYNC(fdP);
3724 #ifdef AFS_DEMAND_ATTACH_FS
3726 VChangeState_r(vp, state_save);
3732 VSyncVolume(Error * ec, Volume * vp)
3735 VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
3740 /***************************************************/
3741 /* Volume dealloaction routines */
3742 /***************************************************/
3744 #ifdef AFS_DEMAND_ATTACH_FS
3746 FreeVolume(Volume * vp)
3748 /* free the heap space, iff it's safe.
3749 * otherwise, pull it out of the hash table, so it
3750 * will get deallocated when all refs to it go away */
3751 if (!VCheckFree(vp)) {
3752 DeleteVolumeFromHashTable(vp);
3753 DeleteVolumeFromVByPList_r(vp);
3755 /* make sure we invalidate the header cache entry */
3756 FreeVolumeHeader(vp);
3759 #endif /* AFS_DEMAND_ATTACH_FS */
3762 ReallyFreeVolume(Volume * vp)
3767 #ifdef AFS_DEMAND_ATTACH_FS
3769 VChangeState_r(vp, VOL_STATE_FREED);
3770 if (vp->pending_vol_op)
3771 free(vp->pending_vol_op);
3772 #endif /* AFS_DEMAND_ATTACH_FS */
3773 for (i = 0; i < nVNODECLASSES; i++)
3774 if (vp->vnodeIndex[i].bitmap)
3775 free(vp->vnodeIndex[i].bitmap);
3776 FreeVolumeHeader(vp);
3777 #ifndef AFS_DEMAND_ATTACH_FS
3778 DeleteVolumeFromHashTable(vp);
3779 #endif /* AFS_DEMAND_ATTACH_FS */
3783 /* check to see if we should shutdown this volume
3784 * returns 1 if volume was freed, 0 otherwise */
3785 #ifdef AFS_DEMAND_ATTACH_FS
3787 VCheckDetach(register Volume * vp)
3792 if (vp->nUsers || vp->nWaiters)
3795 if (vp->shuttingDown) {
3797 if ((programType != fileServer) &&
3798 (V_inUse(vp) == programType) &&
3799 ((V_checkoutMode(vp) == V_VOLUPD) ||
3800 (V_checkoutMode(vp) == V_SECRETLY) ||
3801 ((V_checkoutMode(vp) == V_CLONE) &&
3802 (VolumeWriteable(vp))))) {
3804 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
3806 Log("VCheckDetach: volume header update for volume %u "
3807 "failed with errno %d\n", vp->hashid, errno);
3810 VReleaseVolumeHandles_r(vp);
3812 ReallyFreeVolume(vp);
3813 if (programType == fileServer) {
3814 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3819 #else /* AFS_DEMAND_ATTACH_FS */
3821 VCheckDetach(register Volume * vp)
3829 if (vp->shuttingDown) {
3831 if ((programType != fileServer) &&
3832 (V_inUse(vp) == programType) &&
3833 ((V_checkoutMode(vp) == V_VOLUPD) ||
3834 (V_checkoutMode(vp) == V_SECRETLY) ||
3835 ((V_checkoutMode(vp) == V_CLONE) &&
3836 (VolumeWriteable(vp))))) {
3838 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
3840 Log("VCheckDetach: volume header update for volume %u failed with errno %d\n",
3844 VReleaseVolumeHandles_r(vp);
3845 ReallyFreeVolume(vp);
3846 if (programType == fileServer) {
3847 #if defined(AFS_PTHREAD_ENV)
3848 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3849 #else /* AFS_PTHREAD_ENV */
3850 LWP_NoYieldSignal(VPutVolume);
3851 #endif /* AFS_PTHREAD_ENV */
3856 #endif /* AFS_DEMAND_ATTACH_FS */
3858 /* check to see if we should offline this volume
3859 * return 1 if volume went offline, 0 otherwise */
3860 #ifdef AFS_DEMAND_ATTACH_FS
3862 VCheckOffline(register Volume * vp)
3866 if (vp->goingOffline && !vp->nUsers) {
3868 assert(programType == fileServer);
3869 assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
3870 (V_attachState(vp) != VOL_STATE_FREED) &&
3871 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
3872 (V_attachState(vp) != VOL_STATE_UNATTACHED));
3876 * VOL_STATE_GOING_OFFLINE
3877 * VOL_STATE_SHUTTING_DOWN
3878 * VIsErrorState(V_attachState(vp))
3879 * VIsExclusiveState(V_attachState(vp))
3882 VCreateReservation_r(vp);
3883 VChangeState_r(vp, VOL_STATE_OFFLINING);
3886 /* must clear the goingOffline flag before we drop the glock */
3887 vp->goingOffline = 0;
3892 /* perform async operations */
3893 VUpdateVolume_r(&error, vp, 0);
3894 VCloseVolumeHandles_r(vp);
3897 if (V_offlineMessage(vp)[0]) {
3898 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
3899 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
3900 V_offlineMessage(vp));
3902 Log("VOffline: Volume %lu (%s) is now offline\n",
3903 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
3907 /* invalidate the volume header cache entry */
3908 FreeVolumeHeader(vp);
3910 /* if nothing changed state to error or salvaging,
3911 * drop state to unattached */
3912 if (!VIsErrorState(V_attachState(vp))) {
3913 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3915 VCancelReservation_r(vp);
3916 /* no usage of vp is safe beyond this point */
3920 #else /* AFS_DEMAND_ATTACH_FS */
3922 VCheckOffline(register Volume * vp)
3926 if (vp->goingOffline && !vp->nUsers) {
3928 assert(programType == fileServer);
3931 vp->goingOffline = 0;
3933 VUpdateVolume_r(&error, vp, 0);
3934 VCloseVolumeHandles_r(vp);
3936 Log("VOffline: Volume %u (%s) is now offline", V_id(vp),
3938 if (V_offlineMessage(vp)[0])
3939 Log(" (%s)", V_offlineMessage(vp));
3942 FreeVolumeHeader(vp);
3943 #ifdef AFS_PTHREAD_ENV
3944 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3945 #else /* AFS_PTHREAD_ENV */
3946 LWP_NoYieldSignal(VPutVolume);
3947 #endif /* AFS_PTHREAD_ENV */
3951 #endif /* AFS_DEMAND_ATTACH_FS */
3953 /***************************************************/
3954 /* demand attach fs ref counting routines */
3955 /***************************************************/
3957 #ifdef AFS_DEMAND_ATTACH_FS
3958 /* the following two functions handle reference counting for
3959 * asynchronous operations on volume structs.
3961 * their purpose is to prevent a VDetachVolume or VShutdown
3962 * from free()ing the Volume struct during an async i/o op */
3964 /* register with the async volume op ref counter */
3965 /* VCreateReservation_r moved into inline code header because it
3966 * is now needed in vnode.c -- tkeiser 11/20/2007
3970 * decrement volume-package internal refcount.
3972 * @param vp volume object pointer
3974 * @internal volume package internal use only
3977 * @arg VOL_LOCK is held
3978 * @arg lightweight refcount held
3980 * @post volume waiters refcount is decremented; volume may
3981 * have been deallocated/shutdown/offlined/salvaged/
3982 * whatever during the process
3984 * @warning once you have tossed your last reference (you can acquire
3985 * lightweight refs recursively) it is NOT SAFE to reference
3986 * a volume object pointer ever again
3988 * @see VCreateReservation_r
3990 * @note DEMAND_ATTACH_FS only
3993 VCancelReservation_r(Volume * vp)
3995 assert(--vp->nWaiters >= 0);
3996 if (vp->nWaiters == 0) {
3998 if (!VCheckDetach(vp)) {
4005 /* check to see if we should free this volume now
4006 * return 1 if volume was freed, 0 otherwise */
4008 VCheckFree(Volume * vp)
4011 if ((vp->nUsers == 0) &&
4012 (vp->nWaiters == 0) &&
4013 !(V_attachFlags(vp) & (VOL_IN_HASH |
4017 ReallyFreeVolume(vp);
4022 #endif /* AFS_DEMAND_ATTACH_FS */
4025 /***************************************************/
4026 /* online volume operations routines */
4027 /***************************************************/
4029 #ifdef AFS_DEMAND_ATTACH_FS
4031 * register a volume operation on a given volume.
4033 * @param[in] vp volume object
4034 * @param[in] vopinfo volume operation info object
4036 * @pre VOL_LOCK is held
4038 * @post volume operation info object attached to volume object.
4039 * volume operation statistics updated.
4041 * @note by "attached" we mean a copy of the passed in object is made
4043 * @internal volume package internal use only
4046 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4048 FSSYNC_VolOp_info * info;
4050 /* attach a vol op info node to the volume struct */
4051 info = (FSSYNC_VolOp_info *) malloc(sizeof(FSSYNC_VolOp_info));
4052 assert(info != NULL);
4053 memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
4054 vp->pending_vol_op = info;
4057 vp->stats.last_vol_op = FT_ApproxTime();
4058 vp->stats.vol_ops++;
4059 IncUInt64(&VStats.vol_ops);
4065 * deregister the volume operation attached to this volume.
4067 * @param[in] vp volume object pointer
4069 * @pre VOL_LOCK is held
4071 * @post the volume operation info object is detached from the volume object
4073 * @internal volume package internal use only
4076 VDeregisterVolOp_r(Volume * vp)
4078 if (vp->pending_vol_op) {
4079 free(vp->pending_vol_op);
4080 vp->pending_vol_op = NULL;
4084 #endif /* AFS_DEMAND_ATTACH_FS */
4087 * determine whether it is safe to leave a volume online during
4088 * the volume operation described by the vopinfo object.
4090 * @param[in] vp volume object
4091 * @param[in] vopinfo volume operation info object
4093 * @return whether it is safe to leave volume online
4094 * @retval 0 it is NOT SAFE to leave the volume online
4095 * @retval 1 it is safe to leave the volume online during the operation
4098 * @arg VOL_LOCK is held
4099 * @arg disk header attached to vp (heavyweight ref on vp will guarantee
4100 * this condition is met)
4102 * @internal volume package internal use only
4105 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4107 return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
4108 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4109 (vopinfo->com.reason == V_READONLY ||
4110 (!VolumeWriteable(vp) &&
4111 (vopinfo->com.reason == V_CLONE ||
4112 vopinfo->com.reason == V_DUMP)))));
4116 * determine whether VBUSY should be set during this volume operation.
4118 * @param[in] vp volume object
4119 * @param[in] vopinfo volume operation info object
4121 * @return whether VBUSY should be set
4122 * @retval 0 VBUSY does NOT need to be set
4123 * @retval 1 VBUSY SHOULD be set
4125 * @pre VOL_LOCK is held
4127 * @internal volume package internal use only
4130 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4132 return ((vopinfo->com.command == FSYNC_VOL_OFF &&
4133 vopinfo->com.reason == FSYNC_SALVAGE) ||
4134 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4135 (vopinfo->com.reason == V_CLONE ||
4136 vopinfo->com.reason == V_DUMP)));
4140 /***************************************************/
4141 /* online salvager routines */
4142 /***************************************************/
4143 #if defined(AFS_DEMAND_ATTACH_FS)
4145 * check whether a salvage needs to be performed on this volume.
4147 * @param[in] vp pointer to volume object
4149 * @return status code
4150 * @retval 0 no salvage scheduled
4151 * @retval 1 a salvage has been scheduled with the salvageserver
4153 * @pre VOL_LOCK is held
4155 * @post if salvage request flag is set and nUsers and nWaiters are zero,
4156 * then a salvage will be requested
4158 * @note this is one of the event handlers called by VCancelReservation_r
4160 * @see VCancelReservation_r
4162 * @internal volume package internal use only.
4165 VCheckSalvage(register Volume * vp)
4168 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
4169 if (vp->nUsers || vp->nWaiters)
4171 if (vp->salvage.requested) {
4172 VScheduleSalvage_r(vp);
4175 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
4180 * request volume salvage.
4182 * @param[out] ec computed client error code
4183 * @param[in] vp volume object pointer
4184 * @param[in] reason reason code (passed to salvageserver via SALVSYNC)
4185 * @param[in] flags see flags note below
4188 * VOL_SALVAGE_INVALIDATE_HEADER causes volume header cache entry
4189 * to be invalidated.
4191 * @pre VOL_LOCK is held.
4193 * @post volume state is changed.
4194 * for fileserver, salvage will be requested once refcount reaches zero.
4196 * @return operation status code
4197 * @retval 0 volume salvage will occur
4198 * @retval 1 volume salvage could not be scheduled
4200 * @note DAFS fileserver only
4202 * @note this call does not synchronously schedule a volume salvage. rather,
4203 * it sets volume state so that when volume refcounts reach zero, a
4204 * volume salvage will occur. by "refcounts", we mean both nUsers and
4205 * nWaiters must be zero.
4207 * @internal volume package internal use only.
4210 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
4214 * for DAFS volume utilities, transition to error state
4215 * (at some point in the future, we should consider
4216 * making volser talk to salsrv)
4218 if (!VCanScheduleSalvage()) {
4219 VChangeState_r(vp, VOL_STATE_ERROR);
4224 if (programType != fileServer && !VCanUseFSSYNC()) {
4225 VChangeState_r(vp, VOL_STATE_ERROR);
4230 if (!vp->salvage.requested) {
4231 vp->salvage.requested = 1;
4232 vp->salvage.reason = reason;
4233 vp->stats.last_salvage = FT_ApproxTime();
4235 if (programType == fileServer && vp->header && VIsSalvager(V_inUse(vp))) {
4236 /* Right now we can't tell for sure if this indicates a
4237 * salvage is running, or if a running salvage crashed, so
4238 * we always ERROR the volume in case a salvage is running.
4239 * Once we get rid of the partition lock and instead lock
4240 * individual volume header files for salvages, we will
4241 * probably be able to tell if a salvage is running, and we
4242 * can do away with this behavior. */
4243 /* Note that we can avoid this check for non-fileserver programs,
4244 * since they must lock the partition in order to attach a volume.
4245 * Since the salvager also locks the partition to salvage, we
4246 * could not have reached this point for non-fileservers if this
4247 * volume was being salvaged; so we assume it is not. */
4248 Log("VRequestSalvage: volume %u appears to be salvaging, but we\n", vp->hashid);
4249 Log(" didn't request a salvage. Forcing it offline waiting for the\n");
4250 Log(" salvage to finish; if you are sure no salvage is running,\n");
4251 Log(" run a salvage manually.\n");
4253 /* make sure neither VScheduleSalvage_r nor
4254 * VUpdateSalvagePriority_r try to schedule another salvage */
4255 vp->salvage.requested = vp->salvage.scheduled = 0;
4257 /* these stats aren't correct, but doing this makes them
4258 * slightly closer to being correct */
4259 vp->stats.salvages++;
4260 vp->stats.last_salvage_req = FT_ApproxTime();
4261 IncUInt64(&VStats.salvages);
4263 VChangeState_r(vp, VOL_STATE_ERROR);
4267 } else if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
4268 VChangeState_r(vp, VOL_STATE_SALVAGING);
4271 Log("VRequestSalvage: volume %u online salvaged too many times; forced offline.\n", vp->hashid);
4273 /* make sure neither VScheduleSalvage_r nor
4274 * VUpdateSalvagePriority_r try to schedule another salvage */
4275 vp->salvage.requested = vp->salvage.scheduled = 0;
4277 VChangeState_r(vp, VOL_STATE_ERROR);
4281 if (flags & VOL_SALVAGE_INVALIDATE_HEADER) {
4282 /* Instead of ReleaseVolumeHeader, we do FreeVolumeHeader()
4283 so that the the next VAttachVolumeByVp_r() invocation
4284 of attach2() will pull in a cached header
4285 entry and fail, then load a fresh one from disk and attach
4288 FreeVolumeHeader(vp);
4295 * update salvageserver scheduling priority for a volume.
4297 * @param[in] vp pointer to volume object
4299 * @return operation status
4301 * @retval 1 request denied, or SALVSYNC communications failure
4303 * @pre VOL_LOCK is held.
4305 * @post in-core salvage priority counter is incremented. if at least
4306 * SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
4307 * last SALVSYNC_RAISEPRIO request, we contact the salvageserver
4308 * to update its priority queue. if no salvage is scheduled,
4309 * this function is a no-op.
4311 * @note DAFS fileserver only
4313 * @note this should be called whenever a VGetVolume fails due to a
4314 * pending salvage request
4316 * @todo should set exclusive state and drop glock around salvsync call
4318 * @internal volume package internal use only.
4321 VUpdateSalvagePriority_r(Volume * vp)
4325 #ifdef SALVSYNC_BUILD_CLIENT
4330 now = FT_ApproxTime();
4332 /* update the salvageserver priority queue occasionally so that
4333 * frequently requested volumes get moved to the head of the queue
4335 if ((vp->salvage.scheduled) &&
4336 (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
4337 code = SALVSYNC_SalvageVolume(vp->hashid,
4338 VPartitionPath(vp->partition),
4343 vp->stats.last_salvage_req = now;
4344 if (code != SYNC_OK) {
4348 #endif /* SALVSYNC_BUILD_CLIENT */
4353 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
4355 * schedule a salvage with the salvage server or fileserver.
4357 * @param[in] vp pointer to volume object
4359 * @return operation status
4360 * @retval 0 salvage scheduled successfully
4361 * @retval 1 salvage not scheduled, or SALVSYNC/FSSYNC com error
4364 * @arg VOL_LOCK is held.
4365 * @arg nUsers and nWaiters should be zero.
4367 * @post salvageserver or fileserver is sent a salvage request
4369 * @note If we are the fileserver, the request will be sent to the salvage
4370 * server over SALVSYNC. If we are not the fileserver, the request will be
4371 * sent to the fileserver over FSSYNC (FSYNC_VOL_FORCE_ERROR/FSYNC_SALVAGE).
4375 * @internal volume package internal use only.
4378 VScheduleSalvage_r(Volume * vp)
4382 VolState state_save;
4383 VThreadOptions_t * thread_opts;
4386 assert(VCanUseSALVSYNC() || VCanUseFSSYNC());
4388 if (vp->nWaiters || vp->nUsers) {
4392 /* prevent endless salvage,attach,salvage,attach,... loops */
4393 if (vp->stats.salvages >= SALVAGE_COUNT_MAX)
4397 * don't perform salvsync ops on certain threads
4399 thread_opts = pthread_getspecific(VThread_key);
4400 if (thread_opts == NULL) {
4401 thread_opts = &VThread_defaults;
4403 if (thread_opts->disallow_salvsync || vol_disallow_salvsync) {
4408 * XXX the scheduling process should really be done asynchronously
4409 * to avoid fssync deadlocks
4411 if (!vp->salvage.scheduled) {
4412 /* if we haven't previously scheduled a salvage, do so now
4414 * set the volume to an exclusive state and drop the lock
4415 * around the SALVSYNC call
4417 * note that we do NOT acquire a reservation here -- doing so
4418 * could result in unbounded recursion
4420 strlcpy(partName, VPartitionPath(vp->partition), sizeof(partName));
4421 state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
4424 #ifdef SALVSYNC_BUILD_CLIENT
4425 if (VCanUseSALVSYNC()) {
4426 /* can't use V_id() since there's no guarantee
4427 * we have the disk data header at this point */
4428 code = SALVSYNC_SalvageVolume(vp->hashid,
4435 #endif /* SALVSYNC_BUILD_CLIENT */
4436 #ifdef FSSYNC_BUILD_CLIENT
4437 if (VCanUseFSSYNC()) {
4439 * If we aren't the fileserver, tell the fileserver the volume
4440 * needs to be salvaged. We could directly tell the
4441 * salvageserver, but the fileserver keeps track of some stats
4442 * related to salvages, and handles some other salvage-related
4443 * complications for us.
4445 code = FSYNC_VolOp(vp->hashid, partName,
4446 FSYNC_VOL_FORCE_ERROR, FSYNC_SALVAGE, NULL);
4448 #endif /* FSSYNC_BUILD_CLIENT */
4451 VChangeState_r(vp, state_save);
4453 if (code == SYNC_OK) {
4454 vp->salvage.scheduled = 1;
4455 vp->stats.last_salvage_req = FT_ApproxTime();
4456 if (VCanUseSALVSYNC()) {
4457 /* don't record these stats for non-fileservers; let the
4458 * fileserver take care of these */
4459 vp->stats.salvages++;
4460 IncUInt64(&VStats.salvages);
4465 case SYNC_BAD_COMMAND:
4466 case SYNC_COM_ERROR:
4469 Log("VScheduleSalvage_r: Salvage request for volume %lu "
4470 "denied\n", afs_printable_uint32_lu(vp->hashid));
4473 Log("VScheduleSalvage_r: Salvage request for volume %lu "
4474 "received unknown protocol error %d\n",
4475 afs_printable_uint32_lu(vp->hashid), code);
4479 if (VCanUseFSSYNC()) {
4480 VChangeState_r(vp, VOL_STATE_ERROR);
4486 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
4488 #ifdef SALVSYNC_BUILD_CLIENT
4491 * connect to the salvageserver SYNC service.
4493 * @return operation status
4497 * @post connection to salvageserver SYNC service established
4499 * @see VConnectSALV_r
4500 * @see VDisconnectSALV
4501 * @see VReconnectSALV
4508 retVal = VConnectSALV_r();
4514 * connect to the salvageserver SYNC service.
4516 * @return operation status
4520 * @pre VOL_LOCK is held.
4522 * @post connection to salvageserver SYNC service established
4525 * @see VDisconnectSALV_r
4526 * @see VReconnectSALV_r
4527 * @see SALVSYNC_clientInit
4529 * @internal volume package internal use only.
4532 VConnectSALV_r(void)
4534 return SALVSYNC_clientInit();
4538 * disconnect from the salvageserver SYNC service.
4540 * @return operation status
4543 * @pre client should have a live connection to the salvageserver
4545 * @post connection to salvageserver SYNC service destroyed
4547 * @see VDisconnectSALV_r
4549 * @see VReconnectSALV
4552 VDisconnectSALV(void)
4555 VDisconnectSALV_r();
4561 * disconnect from the salvageserver SYNC service.
4563 * @return operation status
4567 * @arg VOL_LOCK is held.
4568 * @arg client should have a live connection to the salvageserver.
4570 * @post connection to salvageserver SYNC service destroyed
4572 * @see VDisconnectSALV
4573 * @see VConnectSALV_r
4574 * @see VReconnectSALV_r
4575 * @see SALVSYNC_clientFinis
4577 * @internal volume package internal use only.
4580 VDisconnectSALV_r(void)
4582 return SALVSYNC_clientFinis();
4586 * disconnect and then re-connect to the salvageserver SYNC service.
4588 * @return operation status
4592 * @pre client should have a live connection to the salvageserver
4594 * @post old connection is dropped, and a new one is established
4597 * @see VDisconnectSALV
4598 * @see VReconnectSALV_r
4601 VReconnectSALV(void)
4605 retVal = VReconnectSALV_r();
4611 * disconnect and then re-connect to the salvageserver SYNC service.
4613 * @return operation status
4618 * @arg VOL_LOCK is held.
4619 * @arg client should have a live connection to the salvageserver.
4621 * @post old connection is dropped, and a new one is established
4623 * @see VConnectSALV_r
4624 * @see VDisconnectSALV
4625 * @see VReconnectSALV
4626 * @see SALVSYNC_clientReconnect
4628 * @internal volume package internal use only.
4631 VReconnectSALV_r(void)
4633 return SALVSYNC_clientReconnect();
4635 #endif /* SALVSYNC_BUILD_CLIENT */
4636 #endif /* AFS_DEMAND_ATTACH_FS */
4639 /***************************************************/
4640 /* FSSYNC routines */
4641 /***************************************************/
4643 /* This must be called by any volume utility which needs to run while the
4644 file server is also running. This is separated from VInitVolumePackage2 so
4645 that a utility can fork--and each of the children can independently
4646 initialize communication with the file server */
4647 #ifdef FSSYNC_BUILD_CLIENT
4649 * connect to the fileserver SYNC service.
4651 * @return operation status
4656 * @arg VInit must equal 2.
4657 * @arg Program Type must not be fileserver or salvager.
4659 * @post connection to fileserver SYNC service established
4662 * @see VDisconnectFS
4663 * @see VChildProcReconnectFS
4670 retVal = VConnectFS_r();
4676 * connect to the fileserver SYNC service.
4678 * @return operation status
4683 * @arg VInit must equal 2.
4684 * @arg Program Type must not be fileserver or salvager.
4685 * @arg VOL_LOCK is held.
4687 * @post connection to fileserver SYNC service established
4690 * @see VDisconnectFS_r
4691 * @see VChildProcReconnectFS_r
4693 * @internal volume package internal use only.
4699 assert((VInit == 2) &&
4700 (programType != fileServer) &&
4701 (programType != salvager));
4702 rc = FSYNC_clientInit();
4709 * disconnect from the fileserver SYNC service.
4712 * @arg client should have a live connection to the fileserver.
4713 * @arg VOL_LOCK is held.
4714 * @arg Program Type must not be fileserver or salvager.
4716 * @post connection to fileserver SYNC service destroyed
4718 * @see VDisconnectFS
4720 * @see VChildProcReconnectFS_r
4722 * @internal volume package internal use only.
4725 VDisconnectFS_r(void)
4727 assert((programType != fileServer) &&
4728 (programType != salvager));
4729 FSYNC_clientFinis();
4734 * disconnect from the fileserver SYNC service.
4737 * @arg client should have a live connection to the fileserver.
4738 * @arg Program Type must not be fileserver or salvager.
4740 * @post connection to fileserver SYNC service destroyed
4742 * @see VDisconnectFS_r
4744 * @see VChildProcReconnectFS
4755 * connect to the fileserver SYNC service from a child process following a fork.
4757 * @return operation status
4762 * @arg VOL_LOCK is held.
4763 * @arg current FSYNC handle is shared with a parent process
4765 * @post current FSYNC handle is discarded and a new connection to the
4766 * fileserver SYNC service is established
4768 * @see VChildProcReconnectFS
4770 * @see VDisconnectFS_r
4772 * @internal volume package internal use only.
4775 VChildProcReconnectFS_r(void)
4777 return FSYNC_clientChildProcReconnect();
4781 * connect to the fileserver SYNC service from a child process following a fork.
4783 * @return operation status
4787 * @pre current FSYNC handle is shared with a parent process
4789 * @post current FSYNC handle is discarded and a new connection to the
4790 * fileserver SYNC service is established
4792 * @see VChildProcReconnectFS_r
4794 * @see VDisconnectFS
4797 VChildProcReconnectFS(void)
4801 ret = VChildProcReconnectFS_r();
4805 #endif /* FSSYNC_BUILD_CLIENT */
4808 /***************************************************/
4809 /* volume bitmap routines */
4810 /***************************************************/
4813 * For demand attach fs, flags parameter controls
4814 * locking behavior. If (flags & VOL_ALLOC_BITMAP_WAIT)
4815 * is set, then this function will create a reservation
4816 * and block on any other exclusive operations. Otherwise,
4817 * this function assumes the caller already has exclusive
4818 * access to vp, and we just change the volume state.
4821 VAllocBitmapEntry_r(Error * ec, Volume * vp,
4822 struct vnodeIndex *index, int flags)
4825 register byte *bp, *ep;
4826 #ifdef AFS_DEMAND_ATTACH_FS
4827 VolState state_save;
4828 #endif /* AFS_DEMAND_ATTACH_FS */
4832 /* This test is probably redundant */
4833 if (!VolumeWriteable(vp)) {
4834 *ec = (bit32) VREADONLY;
4838 #ifdef AFS_DEMAND_ATTACH_FS
4839 if (flags & VOL_ALLOC_BITMAP_WAIT) {
4840 VCreateReservation_r(vp);
4841 VWaitExclusiveState_r(vp);
4843 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
4844 #endif /* AFS_DEMAND_ATTACH_FS */
4847 if ((programType == fileServer) && !index->bitmap) {
4849 #ifndef AFS_DEMAND_ATTACH_FS
4850 /* demand attach fs uses the volume state to avoid races.
4851 * specialStatus field is not used at all */
4853 if (vp->specialStatus == VBUSY) {
4854 if (vp->goingOffline) { /* vos dump waiting for the volume to
4855 * go offline. We probably come here
4856 * from AddNewReadableResidency */
4859 while (vp->specialStatus == VBUSY) {
4860 #ifdef AFS_PTHREAD_ENV
4864 #else /* !AFS_PTHREAD_ENV */
4866 #endif /* !AFS_PTHREAD_ENV */
4870 #endif /* !AFS_DEMAND_ATTACH_FS */
4872 if (!index->bitmap) {
4873 #ifndef AFS_DEMAND_ATTACH_FS
4874 vp->specialStatus = VBUSY; /* Stop anyone else from using it. */
4875 #endif /* AFS_DEMAND_ATTACH_FS */
4876 for (i = 0; i < nVNODECLASSES; i++) {
4877 VGetBitmap_r(ec, vp, i);
4879 #ifdef AFS_DEMAND_ATTACH_FS
4880 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
4881 #else /* AFS_DEMAND_ATTACH_FS */
4882 DeleteVolumeFromHashTable(vp);
4883 vp->shuttingDown = 1; /* Let who has it free it. */
4884 vp->specialStatus = 0;
4885 #endif /* AFS_DEMAND_ATTACH_FS */
4890 #ifndef AFS_DEMAND_ATTACH_FS
4892 vp->specialStatus = 0; /* Allow others to have access. */
4893 #endif /* AFS_DEMAND_ATTACH_FS */
4896 #endif /* BITMAP_LATER */
4898 #ifdef AFS_DEMAND_ATTACH_FS
4900 #endif /* AFS_DEMAND_ATTACH_FS */
4901 bp = index->bitmap + index->bitmapOffset;
4902 ep = index->bitmap + index->bitmapSize;
4904 if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
4906 index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
4909 o = ffs(~*bp) - 1; /* ffs is documented in BSTRING(3) */
4911 ret = (VnodeId) ((bp - index->bitmap) * 8 + o);
4912 #ifdef AFS_DEMAND_ATTACH_FS
4914 #endif /* AFS_DEMAND_ATTACH_FS */
4917 bp += sizeof(bit32) /* i.e. 4 */ ;
4919 /* No bit map entry--must grow bitmap */
4921 realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
4924 bp += index->bitmapSize;
4925 memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
4926 index->bitmapOffset = index->bitmapSize;
4927 index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
4929 ret = index->bitmapOffset * 8;
4930 #ifdef AFS_DEMAND_ATTACH_FS
4932 #endif /* AFS_DEMAND_ATTACH_FS */
4935 #ifdef AFS_DEMAND_ATTACH_FS
4936 VChangeState_r(vp, state_save);
4937 if (flags & VOL_ALLOC_BITMAP_WAIT) {
4938 VCancelReservation_r(vp);
4940 #endif /* AFS_DEMAND_ATTACH_FS */
4945 VAllocBitmapEntry(Error * ec, Volume * vp, register struct vnodeIndex * index)
4949 retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
4955 VFreeBitMapEntry_r(Error * ec, register struct vnodeIndex *index,
4958 unsigned int offset;
4964 #endif /* BITMAP_LATER */
4965 offset = bitNumber >> 3;
4966 if (offset >= index->bitmapSize) {
4970 if (offset < index->bitmapOffset)
4971 index->bitmapOffset = offset & ~3; /* Truncate to nearest bit32 */
4972 *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
4976 VFreeBitMapEntry(Error * ec, register struct vnodeIndex *index,
4980 VFreeBitMapEntry_r(ec, index, bitNumber);
4984 /* this function will drop the glock internally.
4985 * for old pthread fileservers, this is safe thanks to vbusy.
4987 * for demand attach fs, caller must have already called
4988 * VCreateReservation_r and VWaitExclusiveState_r */
4990 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
4992 StreamHandle_t *file;
4995 struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
4996 struct vnodeIndex *vip = &vp->vnodeIndex[class];
4997 struct VnodeDiskObject *vnode;
4998 unsigned int unique = 0;
5002 #endif /* BITMAP_LATER */
5003 #ifdef AFS_DEMAND_ATTACH_FS
5004 VolState state_save;
5005 #endif /* AFS_DEMAND_ATTACH_FS */
5009 #ifdef AFS_DEMAND_ATTACH_FS
5010 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
5011 #endif /* AFS_DEMAND_ATTACH_FS */
5014 fdP = IH_OPEN(vip->handle);
5015 assert(fdP != NULL);
5016 file = FDH_FDOPEN(fdP, "r");
5017 assert(file != NULL);
5018 vnode = (VnodeDiskObject *) malloc(vcp->diskSize);
5019 assert(vnode != NULL);
5020 size = OS_SIZE(fdP->fd_fd);
5022 nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
5024 vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4; /* The 10 is a little extra so
5025 * a few files can be created in this volume,
5026 * the whole thing is rounded up to nearest 4
5027 * bytes, because the bit map allocator likes
5030 BitMap = (byte *) calloc(1, vip->bitmapSize);
5031 assert(BitMap != NULL);
5032 #else /* BITMAP_LATER */
5033 vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
5034 assert(vip->bitmap != NULL);
5035 vip->bitmapOffset = 0;
5036 #endif /* BITMAP_LATER */
5037 if (STREAM_SEEK(file, vcp->diskSize, 0) != -1) {
5039 for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
5040 if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
5042 if (vnode->type != vNull) {
5043 if (vnode->vnodeMagic != vcp->magic) {
5044 Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
5049 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
5050 #else /* BITMAP_LATER */
5051 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
5052 #endif /* BITMAP_LATER */
5053 if (unique <= vnode->uniquifier)
5054 unique = vnode->uniquifier + 1;
5056 #ifndef AFS_PTHREAD_ENV
5057 if ((bitNumber & 0x00ff) == 0x0ff) { /* every 256 iterations */
5060 #endif /* !AFS_PTHREAD_ENV */
5063 if (vp->nextVnodeUnique < unique) {
5064 Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
5067 /* Paranoia, partly justified--I think fclose after fdopen
5068 * doesn't seem to close fd. In any event, the documentation
5069 * doesn't specify, so it's safer to close it twice.
5077 /* There may have been a racing condition with some other thread, both
5078 * creating the bitmaps for this volume. If the other thread was faster
5079 * the pointer to bitmap should already be filled and we can free ours.
5081 if (vip->bitmap == NULL) {
5082 vip->bitmap = BitMap;
5083 vip->bitmapOffset = 0;
5085 free((byte *) BitMap);
5086 #endif /* BITMAP_LATER */
5087 #ifdef AFS_DEMAND_ATTACH_FS
5088 VChangeState_r(vp, state_save);
5089 #endif /* AFS_DEMAND_ATTACH_FS */
5093 /***************************************************/
5094 /* Volume Path and Volume Number utility routines */
5095 /***************************************************/
5098 * find the first occurrence of a volume header file and return the path.
5100 * @param[out] ec outbound error code
5101 * @param[in] volumeId volume id to find
5102 * @param[out] partitionp pointer to disk partition path string
5103 * @param[out] namep pointer to volume header file name string
5105 * @post path to first occurrence of volume header is returned in partitionp
5106 * and namep, or ec is set accordingly.
5108 * @warning this function is NOT re-entrant -- partitionp and namep point to
5109 * static data segments
5111 * @note if a volume utility inadvertently leaves behind a stale volume header
5112 * on a vice partition, it is possible for callers to get the wrong one,
5113 * depending on the order of the disk partition linked list.
5117 VGetVolumePath(Error * ec, VolId volumeId, char **partitionp, char **namep)
5119 static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
5120 char path[VMAXPATHLEN];
5122 struct DiskPartition64 *dp;
5126 (void)afs_snprintf(&name[1], (sizeof name) - 1, VFORMAT, afs_printable_uint32_lu(volumeId));
5127 for (dp = DiskPartitionList; dp; dp = dp->next) {
5128 struct afs_stat status;
5129 strcpy(path, VPartitionPath(dp));
5131 if (afs_stat(path, &status) == 0) {
5132 strcpy(partition, dp->name);
5139 *partitionp = *namep = NULL;
5141 *partitionp = partition;
5147 * extract a volume number from a volume header filename string.
5149 * @param[in] name volume header filename string
5151 * @return volume number
5153 * @note the string must be of the form VFORMAT. the only permissible
5154 * deviation is a leading '/' character.
5159 VolumeNumber(char *name)
5163 return atoi(name + 1);
5167 * compute the volume header filename.
5169 * @param[in] volumeId
5171 * @return volume header filename
5173 * @post volume header filename string is constructed
5175 * @warning this function is NOT re-entrant -- the returned string is
5176 * stored in a static char array. see VolumeExternalName_r
5177 * for a re-entrant equivalent.
5179 * @see VolumeExternalName_r
5181 * @deprecated due to the above re-entrancy warning, this interface should
5182 * be considered deprecated. Please use VolumeExternalName_r
5186 VolumeExternalName(VolumeId volumeId)
5188 static char name[VMAXPATHLEN];
5189 (void)afs_snprintf(name, sizeof name, VFORMAT, afs_printable_uint32_lu(volumeId));
5194 * compute the volume header filename.
5196 * @param[in] volumeId
5197 * @param[inout] name array in which to store filename
5198 * @param[in] len length of name array
5200 * @return result code from afs_snprintf
5202 * @see VolumeExternalName
5205 * @note re-entrant equivalent of VolumeExternalName
5208 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
5210 return afs_snprintf(name, len, VFORMAT, afs_printable_uint32_lu(volumeId));
5214 /***************************************************/
5215 /* Volume Usage Statistics routines */
5216 /***************************************************/
5218 #if OPENAFS_VOL_STATS
5219 #define OneDay (86400) /* 24 hours' worth of seconds */
5221 #define OneDay (24*60*60) /* 24 hours */
5222 #endif /* OPENAFS_VOL_STATS */
5225 Midnight(time_t t) {
5226 struct tm local, *l;
5229 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
5230 l = localtime_r(&t, &local);
5236 /* the following is strictly speaking problematic on the
5237 switching day to daylight saving time, after the switch,
5238 as tm_isdst does not match. Similarly, on the looong day when
5239 switching back the OneDay check will not do what naively expected!
5240 The effects are minor, though, and more a matter of interpreting
5242 #ifndef AFS_PTHREAD_ENV
5245 local.tm_hour = local.tm_min=local.tm_sec = 0;
5246 midnight = mktime(&local);
5247 if (midnight != (time_t) -1) return(midnight);
5249 return( (t/OneDay)*OneDay );
5253 /*------------------------------------------------------------------------
5254 * [export] VAdjustVolumeStatistics
5257 * If we've passed midnight, we need to update all the day use
5258 * statistics as well as zeroing the detailed volume statistics
5259 * (if we are implementing them).
5262 * vp : Pointer to the volume structure describing the lucky
5263 * volume being considered for update.
5269 * Nothing interesting.
5273 *------------------------------------------------------------------------*/
5276 VAdjustVolumeStatistics_r(register Volume * vp)
5278 unsigned int now = FT_ApproxTime();
5280 if (now - V_dayUseDate(vp) > OneDay) {
5281 register int ndays, i;
5283 ndays = (now - V_dayUseDate(vp)) / OneDay;
5284 for (i = 6; i > ndays - 1; i--)
5285 V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
5286 for (i = 0; i < ndays - 1 && i < 7; i++)
5287 V_weekUse(vp)[i] = 0;
5289 V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
5291 V_dayUseDate(vp) = Midnight(now);
5293 #if OPENAFS_VOL_STATS
5295 * All we need to do is bzero the entire VOL_STATS_BYTES of
5296 * the detailed volume statistics area.
5298 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
5299 #endif /* OPENAFS_VOL_STATS */
5302 /*It's been more than a day of collection */
5304 * Always return happily.
5307 } /*VAdjustVolumeStatistics */
5310 VAdjustVolumeStatistics(register Volume * vp)
5314 retVal = VAdjustVolumeStatistics_r(vp);
5320 VBumpVolumeUsage_r(register Volume * vp)
5322 unsigned int now = FT_ApproxTime();
5323 V_accessDate(vp) = now;
5324 if (now - V_dayUseDate(vp) > OneDay)
5325 VAdjustVolumeStatistics_r(vp);
5327 * Save the volume header image to disk after every 128 bumps to dayUse.
5329 if ((V_dayUse(vp)++ & 127) == 0) {
5331 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
5336 VBumpVolumeUsage(register Volume * vp)
5339 VBumpVolumeUsage_r(vp);
5344 VSetDiskUsage_r(void)
5346 #ifndef AFS_DEMAND_ATTACH_FS
5347 static int FifteenMinuteCounter = 0;
5351 /* NOTE: Don't attempt to access the partitions list until the
5352 * initialization level indicates that all volumes are attached,
5353 * which implies that all partitions are initialized. */
5354 #ifdef AFS_PTHREAD_ENV
5356 #else /* AFS_PTHREAD_ENV */
5358 #endif /* AFS_PTHREAD_ENV */
5361 VResetDiskUsage_r();
5363 #ifndef AFS_DEMAND_ATTACH_FS
5364 if (++FifteenMinuteCounter == 3) {
5365 FifteenMinuteCounter = 0;
5368 #endif /* !AFS_DEMAND_ATTACH_FS */
5380 /***************************************************/
5381 /* Volume Update List routines */
5382 /***************************************************/
5384 /* The number of minutes that a volume hasn't been updated before the
5385 * "Dont salvage" flag in the volume header will be turned on */
5386 #define SALVAGE_INTERVAL (10*60)
5391 * volume update list functionality has been moved into the VLRU
5392 * the DONT_SALVAGE flag is now set during VLRU demotion
5395 #ifndef AFS_DEMAND_ATTACH_FS
5396 static VolumeId *UpdateList = NULL; /* Pointer to array of Volume ID's */
5397 static int nUpdatedVolumes = 0; /* Updated with entry in UpdateList, salvage after crash flag on */
5398 static int updateSize = 0; /* number of entries possible */
5399 #define UPDATE_LIST_SIZE 128 /* initial size increment (must be a power of 2!) */
5400 #endif /* !AFS_DEMAND_ATTACH_FS */
5403 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
5406 vp->updateTime = FT_ApproxTime();
5407 if (V_dontSalvage(vp) == 0)
5409 V_dontSalvage(vp) = 0;
5410 VSyncVolume_r(ec, vp, 0);
5411 #ifdef AFS_DEMAND_ATTACH_FS
5412 V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
5413 #else /* !AFS_DEMAND_ATTACH_FS */
5416 if (UpdateList == NULL) {
5417 updateSize = UPDATE_LIST_SIZE;
5418 UpdateList = (VolumeId *) malloc(sizeof(VolumeId) * updateSize);
5420 if (nUpdatedVolumes == updateSize) {
5422 if (updateSize > 524288) {
5423 Log("warning: there is likely a bug in the volume update scanner\n");
5427 (VolumeId *) realloc(UpdateList,
5428 sizeof(VolumeId) * updateSize);
5431 assert(UpdateList != NULL);
5432 UpdateList[nUpdatedVolumes++] = V_id(vp);
5433 #endif /* !AFS_DEMAND_ATTACH_FS */
5436 #ifndef AFS_DEMAND_ATTACH_FS
5438 VScanUpdateList(void)
5440 register int i, gap;
5441 register Volume *vp;
5443 afs_uint32 now = FT_ApproxTime();
5444 /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
5445 for (i = gap = 0; i < nUpdatedVolumes; i++) {
5447 UpdateList[i - gap] = UpdateList[i];
5449 /* XXX this routine needlessly messes up the Volume LRU by
5450 * breaking the LRU temporal-locality assumptions.....
5451 * we should use a special volume header allocator here */
5452 vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
5455 } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
5456 V_dontSalvage(vp) = DONT_SALVAGE;
5457 VUpdateVolume_r(&error, vp, 0); /* No need to fsync--not critical */
5465 #ifndef AFS_PTHREAD_ENV
5467 #endif /* !AFS_PTHREAD_ENV */
5469 nUpdatedVolumes -= gap;
5471 #endif /* !AFS_DEMAND_ATTACH_FS */
5474 /***************************************************/
5475 /* Volume LRU routines */
5476 /***************************************************/
5481 * with demand attach fs, we attempt to soft detach(1)
5482 * volumes which have not been accessed in a long time
5483 * in order to speed up fileserver shutdown
5485 * (1) by soft detach we mean a process very similar
5486 * to VOffline, except the final state of the
5487 * Volume will be VOL_STATE_PREATTACHED, instead
5488 * of the usual VOL_STATE_UNATTACHED
5490 #ifdef AFS_DEMAND_ATTACH_FS
5492 /* implementation is reminiscent of a generational GC
5494 * queue 0 is newly attached volumes. this queue is
5495 * sorted by attach timestamp
5497 * queue 1 is volumes that have been around a bit
5498 * longer than queue 0. this queue is sorted by
5501 * queue 2 is volumes tha have been around the longest.
5502 * this queue is unsorted
5504 * queue 3 is volumes that have been marked as
5505 * candidates for soft detachment. this queue is
5508 #define VLRU_GENERATIONS 3 /**< number of generations in VLRU */
5509 #define VLRU_QUEUES 5 /**< total number of VLRU queues */
5512 * definition of a VLRU queue.
5515 volatile struct rx_queue q;
5522 * main VLRU data structure.
5525 struct VLRU_q q[VLRU_QUEUES]; /**< VLRU queues */
5528 /** time interval (in seconds) between promotion passes for
5529 * each young generation queue. */
5530 afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
5532 /** time interval (in seconds) between soft detach candidate
5533 * scans for each generation queue.
5535 * scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
5536 * we perform a soft detach pass. */
5537 afs_uint32 scan_interval[VLRU_GENERATIONS+1];
5539 /* scheduler state */
5540 int next_idx; /**< next queue to receive attention */
5541 afs_uint32 last_promotion[VLRU_GENERATIONS-1]; /**< timestamp of last promotion scan */
5542 afs_uint32 last_scan[VLRU_GENERATIONS+1]; /**< timestamp of last detach scan */
5544 int scanner_state; /**< state of scanner thread */
5545 pthread_cond_t cv; /**< state transition CV */
5548 /** global VLRU state */
5549 static struct VLRU volume_LRU;
5552 * defined states for VLRU scanner thread.
5555 VLRU_SCANNER_STATE_OFFLINE = 0, /**< vlru scanner thread is offline */
5556 VLRU_SCANNER_STATE_ONLINE = 1, /**< vlru scanner thread is online */
5557 VLRU_SCANNER_STATE_SHUTTING_DOWN = 2, /**< vlru scanner thread is shutting down */
5558 VLRU_SCANNER_STATE_PAUSING = 3, /**< vlru scanner thread is getting ready to pause */
5559 VLRU_SCANNER_STATE_PAUSED = 4 /**< vlru scanner thread is paused */
5560 } vlru_thread_state_t;
5562 /* vlru disk data header stuff */
5563 #define VLRU_DISK_MAGIC 0x7a8b9cad /**< vlru disk entry magic number */
5564 #define VLRU_DISK_VERSION 1 /**< vlru disk entry version number */
5566 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
5567 #define VLRU_DUMP_EXPIRATION_TIME (60*60*24*7) /* expire vlru data after 1 week */
5570 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
5571 * soft detachment. */
5572 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
5574 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
5575 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
5577 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
5578 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
5580 /** VLRU control flag. non-zero value implies VLRU subsystem is activated. */
5581 static afs_uint32 VLRU_enabled = 1;
5583 /* queue synchronization routines */
5584 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
5585 static void VLRU_EndExclusive_r(struct VLRU_q * q);
5586 static void VLRU_Wait_r(struct VLRU_q * q);
5589 * set VLRU subsystem tunable parameters.
5591 * @param[in] option tunable option to modify
5592 * @param[in] val new value for tunable parameter
5594 * @pre @c VInitVolumePackage2 has not yet been called.
5596 * @post tunable parameter is modified
5600 * @note valid option parameters are:
5601 * @arg @c VLRU_SET_THRESH
5602 * set the period of inactivity after which
5603 * volumes are eligible for soft detachment
5604 * @arg @c VLRU_SET_INTERVAL
5605 * set the time interval between calls
5606 * to the volume LRU "garbage collector"
5607 * @arg @c VLRU_SET_MAX
5608 * set the max number of volumes to deallocate
5612 VLRU_SetOptions(int option, afs_uint32 val)
5614 if (option == VLRU_SET_THRESH) {
5615 VLRU_offline_thresh = val;
5616 } else if (option == VLRU_SET_INTERVAL) {
5617 VLRU_offline_interval = val;
5618 } else if (option == VLRU_SET_MAX) {
5619 VLRU_offline_max = val;
5620 } else if (option == VLRU_SET_ENABLED) {
5623 VLRU_ComputeConstants();
5627 * compute VLRU internal timing parameters.
5629 * @post VLRU scanner thread internal timing parameters are computed
5631 * @note computes internal timing parameters based upon user-modifiable
5632 * tunable parameters.
5636 * @internal volume package internal use only.
5639 VLRU_ComputeConstants(void)
5641 afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
5643 /* compute the candidate scan interval */
5644 volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
5646 /* compute the promotion intervals */
5647 volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
5648 volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
5651 /* compute the gen 0 scan interval */
5652 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
5654 /* compute the gen 0 scan interval */
5655 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
5660 * initialize VLRU subsystem.
5662 * @pre this function has not yet been called
5664 * @post VLRU subsystem is initialized and VLRU scanner thread is starting
5668 * @internal volume package internal use only.
5674 pthread_attr_t attrs;
5677 if (!VLRU_enabled) {
5678 Log("VLRU: disabled\n");
5682 /* initialize each of the VLRU queues */
5683 for (i = 0; i < VLRU_QUEUES; i++) {
5684 queue_Init(&volume_LRU.q[i]);
5685 volume_LRU.q[i].len = 0;
5686 volume_LRU.q[i].busy = 0;
5687 assert(pthread_cond_init(&volume_LRU.q[i].cv, NULL) == 0);
5690 /* setup the timing constants */
5691 VLRU_ComputeConstants();
5693 /* XXX put inside LogLevel check? */
5694 Log("VLRU: starting scanner with the following configuration parameters:\n");
5695 Log("VLRU: offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
5696 Log("VLRU: running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
5697 Log("VLRU: taking up to %d volumes offline per pass\n", VLRU_offline_max);
5698 Log("VLRU: scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
5699 Log("VLRU: scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
5700 Log("VLRU: scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
5702 /* start up the VLRU scanner */
5703 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
5704 if (programType == fileServer) {
5705 assert(pthread_cond_init(&volume_LRU.cv, NULL) == 0);
5706 assert(pthread_attr_init(&attrs) == 0);
5707 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
5708 assert(pthread_create(&tid, &attrs, &VLRU_ScannerThread, NULL) == 0);
5713 * initialize the VLRU-related fields of a newly allocated volume object.
5715 * @param[in] vp pointer to volume object
5718 * @arg @c VOL_LOCK is held.
5719 * @arg volume object is not on a VLRU queue.
5721 * @post VLRU fields are initialized to indicate that volume object is not
5722 * currently registered with the VLRU subsystem
5726 * @internal volume package interal use only.
5729 VLRU_Init_Node_r(Volume * vp)
5734 assert(queue_IsNotOnQueue(&vp->vlru));
5735 vp->vlru.idx = VLRU_QUEUE_INVALID;
5739 * add a volume object to a VLRU queue.
5741 * @param[in] vp pointer to volume object
5744 * @arg @c VOL_LOCK is held.
5745 * @arg caller MUST hold a lightweight ref on @p vp.
5746 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
5748 * @post the volume object is added to the appropriate VLRU queue
5750 * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
5751 * then the volume is added to that queue. Otherwise, the value
5752 * @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
5753 * volume is added to the NEW generation queue.
5755 * @note @c VOL_LOCK may be dropped internally
5757 * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
5758 * during the add operation, and is restored to the previous
5759 * state prior to return.
5763 * @internal volume package internal use only.
5766 VLRU_Add_r(Volume * vp)
5769 VolState state_save;
5774 if (queue_IsOnQueue(&vp->vlru))
5777 state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
5780 if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
5781 idx = VLRU_QUEUE_NEW;
5784 VLRU_Wait_r(&volume_LRU.q[idx]);
5786 /* repeat check since VLRU_Wait_r may have dropped
5788 if (queue_IsNotOnQueue(&vp->vlru)) {
5790 queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
5791 volume_LRU.q[idx].len++;
5792 V_attachFlags(vp) |= VOL_ON_VLRU;
5793 vp->stats.last_promote = FT_ApproxTime();
5796 VChangeState_r(vp, state_save);
5800 * delete a volume object from a VLRU queue.
5802 * @param[in] vp pointer to volume object
5805 * @arg @c VOL_LOCK is held.
5806 * @arg caller MUST hold a lightweight ref on @p vp.
5807 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
5809 * @post volume object is removed from the VLRU queue
5811 * @note @c VOL_LOCK may be dropped internally
5815 * @todo We should probably set volume state to something exlcusive
5816 * (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
5818 * @internal volume package internal use only.
5821 VLRU_Delete_r(Volume * vp)
5828 if (queue_IsNotOnQueue(&vp->vlru))
5834 if (idx == VLRU_QUEUE_INVALID)
5836 VLRU_Wait_r(&volume_LRU.q[idx]);
5837 } while (idx != vp->vlru.idx);
5839 /* now remove from the VLRU and update
5840 * the appropriate counter */
5841 queue_Remove(&vp->vlru);
5842 volume_LRU.q[idx].len--;
5843 vp->vlru.idx = VLRU_QUEUE_INVALID;
5844 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
5848 * tell the VLRU subsystem that a volume was just accessed.
5850 * @param[in] vp pointer to volume object
5853 * @arg @c VOL_LOCK is held
5854 * @arg caller MUST hold a lightweight ref on @p vp
5855 * @arg caller MUST NOT hold exclusive ownership of any VLRU queue
5857 * @post volume VLRU access statistics are updated. If the volume was on
5858 * the VLRU soft detach candidate queue, it is moved to the NEW
5861 * @note @c VOL_LOCK may be dropped internally
5865 * @internal volume package internal use only.
5868 VLRU_UpdateAccess_r(Volume * vp)
5870 Volume * rvp = NULL;
5875 if (queue_IsNotOnQueue(&vp->vlru))
5878 assert(V_attachFlags(vp) & VOL_ON_VLRU);
5880 /* update the access timestamp */
5881 vp->stats.last_get = FT_ApproxTime();
5884 * if the volume is on the soft detach candidate
5885 * list, we need to safely move it back to a
5886 * regular generation. this has to be done
5887 * carefully so we don't race against the scanner
5891 /* if this volume is on the soft detach candidate queue,
5892 * then grab exclusive access to the necessary queues */
5893 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
5895 VCreateReservation_r(rvp);
5897 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
5898 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
5899 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5900 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5903 /* make sure multiple threads don't race to update */
5904 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
5905 VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
5909 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5910 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
5911 VCancelReservation_r(rvp);
5916 * switch a volume between two VLRU queues.
5918 * @param[in] vp pointer to volume object
5919 * @param[in] new_idx index of VLRU queue onto which the volume will be moved
5920 * @param[in] append controls whether the volume will be appended or
5921 * prepended to the queue. A nonzero value means it will
5922 * be appended; zero means it will be prepended.
5924 * @pre The new (and old, if applicable) queue(s) must either be owned
5925 * exclusively by the calling thread for asynchronous manipulation,
5926 * or the queue(s) must be quiescent and VOL_LOCK must be held.
5927 * Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
5928 * for further details of the queue asynchronous processing mechanism.
5930 * @post If the volume object was already on a VLRU queue, it is
5931 * removed from the queue. Depending on the value of the append
5932 * parameter, the volume object is either appended or prepended
5933 * to the VLRU queue referenced by the new_idx parameter.
5937 * @see VLRU_BeginExclusive_r
5938 * @see VLRU_EndExclusive_r
5941 * @internal volume package internal use only.
5944 VLRU_SwitchQueues(Volume * vp, int new_idx, int append)
5946 if (queue_IsNotOnQueue(&vp->vlru))
5949 queue_Remove(&vp->vlru);
5950 volume_LRU.q[vp->vlru.idx].len--;
5952 /* put the volume back on the correct generational queue */
5954 queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
5956 queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
5959 volume_LRU.q[new_idx].len++;
5960 vp->vlru.idx = new_idx;
5964 * VLRU background thread.
5966 * The VLRU Scanner Thread is responsible for periodically scanning through
5967 * each VLRU queue looking for volumes which should be moved to another
5968 * queue, or soft detached.
5970 * @param[in] args unused thread arguments parameter
5972 * @return unused thread return value
5973 * @retval NULL always
5975 * @internal volume package internal use only.
5978 VLRU_ScannerThread(void * args)
5980 afs_uint32 now, min_delay, delay;
5981 int i, min_idx, min_op, overdue, state;
5983 /* set t=0 for promotion cycle to be
5984 * fileserver startup */
5985 now = FT_ApproxTime();
5986 for (i=0; i < VLRU_GENERATIONS-1; i++) {
5987 volume_LRU.last_promotion[i] = now;
5990 /* don't start the scanner until VLRU_offline_thresh
5991 * plus a small delay for VInitVolumePackage2 to finish
5994 sleep(VLRU_offline_thresh + 60);
5996 /* set t=0 for scan cycle to be now */
5997 now = FT_ApproxTime();
5998 for (i=0; i < VLRU_GENERATIONS+1; i++) {
5999 volume_LRU.last_scan[i] = now;
6003 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
6004 volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
6007 while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
6008 /* check to see if we've been asked to pause */
6009 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
6010 volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
6011 assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
6013 VOL_CV_WAIT(&volume_LRU.cv);
6014 } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
6017 /* scheduling can happen outside the glock */
6020 /* figure out what is next on the schedule */
6022 /* figure out a potential schedule for the new generation first */
6024 min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
6027 if (min_delay > volume_LRU.scan_interval[0]) {
6028 /* unsigned overflow -- we're overdue to run this scan */
6033 /* if we're not overdue for gen 0, figure out schedule for candidate gen */
6035 i = VLRU_QUEUE_CANDIDATE;
6036 delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
6037 if (delay < min_delay) {
6041 if (delay > volume_LRU.scan_interval[i]) {
6042 /* unsigned overflow -- we're overdue to run this scan */
6049 /* if we're still not overdue for something, figure out schedules for promotions */
6050 for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
6051 delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
6052 if (delay < min_delay) {
6057 if (delay > volume_LRU.promotion_interval[i]) {
6058 /* unsigned overflow -- we're overdue to run this promotion */
6067 /* sleep as needed */
6072 /* do whatever is next */
6075 VLRU_Promote_r(min_idx);
6076 VLRU_Demote_r(min_idx+1);
6078 VLRU_Scan_r(min_idx);
6080 now = FT_ApproxTime();
6083 Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
6085 /* signal that scanner is down */
6086 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
6087 assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
6093 * promote volumes from one VLRU generation to the next.
6095 * This routine scans a VLRU generation looking for volumes which are
6096 * eligible to be promoted to the next generation. All volumes which
6097 * meet the eligibility requirement are promoted.
6099 * Promotion eligibility is based upon meeting both of the following
6102 * @arg The volume has been accessed since the last promotion:
6103 * @c (vp->stats.last_get >= vp->stats.last_promote)
6104 * @arg The last promotion occurred at least
6105 * @c volume_LRU.promotion_interval[idx] seconds ago
6107 * As a performance optimization, promotions are "globbed". In other
6108 * words, we promote arbitrarily large contiguous sublists of elements
6111 * @param[in] idx VLRU queue index to scan
6115 * @internal VLRU internal use only.
6118 VLRU_Promote_r(int idx)
6120 int len, chaining, promote;
6121 afs_uint32 now, thresh;
6122 struct rx_queue *qp, *nqp;
6123 Volume * vp, *start = NULL, *end = NULL;
6125 /* get exclusive access to two chains, and drop the glock */
6126 VLRU_Wait_r(&volume_LRU.q[idx]);
6127 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
6128 VLRU_Wait_r(&volume_LRU.q[idx+1]);
6129 VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
6132 thresh = volume_LRU.promotion_interval[idx];
6133 now = FT_ApproxTime();
6136 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
6137 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6138 promote = (((vp->stats.last_promote + thresh) <= now) &&
6139 (vp->stats.last_get >= vp->stats.last_promote));
6147 /* promote and prepend chain */
6148 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
6162 /* promote and prepend */
6163 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
6167 volume_LRU.q[idx].len -= len;
6168 volume_LRU.q[idx+1].len += len;
6171 /* release exclusive access to the two chains */
6173 volume_LRU.last_promotion[idx] = now;
6174 VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
6175 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
6178 /* run the demotions */
6180 VLRU_Demote_r(int idx)
6183 int len, chaining, demote;
6184 afs_uint32 now, thresh;
6185 struct rx_queue *qp, *nqp;
6186 Volume * vp, *start = NULL, *end = NULL;
6187 Volume ** salv_flag_vec = NULL;
6188 int salv_vec_offset = 0;
6190 assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
6192 /* get exclusive access to two chains, and drop the glock */
6193 VLRU_Wait_r(&volume_LRU.q[idx-1]);
6194 VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
6195 VLRU_Wait_r(&volume_LRU.q[idx]);
6196 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
6199 /* no big deal if this allocation fails */
6200 if (volume_LRU.q[idx].len) {
6201 salv_flag_vec = (Volume **) malloc(volume_LRU.q[idx].len * sizeof(Volume *));
6204 now = FT_ApproxTime();
6205 thresh = volume_LRU.promotion_interval[idx-1];
6208 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
6209 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6210 demote = (((vp->stats.last_promote + thresh) <= now) &&
6211 (vp->stats.last_get < (now - thresh)));
6213 /* we now do volume update list DONT_SALVAGE flag setting during
6214 * demotion passes */
6215 if (salv_flag_vec &&
6216 !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
6218 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
6219 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
6220 salv_flag_vec[salv_vec_offset++] = vp;
6221 VCreateReservation_r(vp);
6230 /* demote and append chain */
6231 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
6245 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
6249 volume_LRU.q[idx].len -= len;
6250 volume_LRU.q[idx-1].len += len;
6253 /* release exclusive access to the two chains */
6255 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
6256 VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
6258 /* now go back and set the DONT_SALVAGE flags as appropriate */
6259 if (salv_flag_vec) {
6261 for (i = 0; i < salv_vec_offset; i++) {
6262 vp = salv_flag_vec[i];
6263 if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
6264 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
6265 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
6268 V_attachFlags(vp) |= VOL_HDR_DONTSALV;
6269 V_dontSalvage(vp) = DONT_SALVAGE;
6270 VUpdateVolume_r(&ec, vp, 0);
6274 VCancelReservation_r(vp);
6276 free(salv_flag_vec);
6280 /* run a pass of the VLRU GC scanner */
6282 VLRU_Scan_r(int idx)
6284 afs_uint32 now, thresh;
6285 struct rx_queue *qp, *nqp;
6289 assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
6291 /* gain exclusive access to the idx VLRU */
6292 VLRU_Wait_r(&volume_LRU.q[idx]);
6293 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
6295 if (idx != VLRU_QUEUE_CANDIDATE) {
6296 /* gain exclusive access to the candidate VLRU */
6297 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6298 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6301 now = FT_ApproxTime();
6302 thresh = now - VLRU_offline_thresh;
6304 /* perform candidate selection and soft detaching */
6305 if (idx == VLRU_QUEUE_CANDIDATE) {
6306 /* soft detach some volumes from the candidate pool */
6310 for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
6311 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6312 if (i >= VLRU_offline_max) {
6315 /* check timestamp to see if it's a candidate for soft detaching */
6316 if (vp->stats.last_get <= thresh) {
6318 if (VCheckSoftDetach(vp, thresh))
6324 /* scan for volumes to become soft detach candidates */
6325 for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
6326 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6328 /* check timestamp to see if it's a candidate for soft detaching */
6329 if (vp->stats.last_get <= thresh) {
6330 VCheckSoftDetachCandidate(vp, thresh);
6333 if (!(i&0x7f)) { /* lock coarsening optimization */
6341 /* relinquish exclusive access to the VLRU chains */
6345 volume_LRU.last_scan[idx] = now;
6346 if (idx != VLRU_QUEUE_CANDIDATE) {
6347 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6349 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
6352 /* check whether volume is safe to soft detach
6353 * caller MUST NOT hold a ref count on vp */
6355 VCheckSoftDetach(Volume * vp, afs_uint32 thresh)
6359 if (vp->nUsers || vp->nWaiters)
6362 if (vp->stats.last_get <= thresh) {
6363 ret = VSoftDetachVolume_r(vp, thresh);
6369 /* check whether volume should be made a
6370 * soft detach candidate */
6372 VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh)
6375 if (vp->nUsers || vp->nWaiters)
6380 assert(idx == VLRU_QUEUE_NEW);
6382 if (vp->stats.last_get <= thresh) {
6383 /* move to candidate pool */
6384 queue_Remove(&vp->vlru);
6385 volume_LRU.q[VLRU_QUEUE_NEW].len--;
6386 queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
6387 vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
6388 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
6396 /* begin exclusive access on VLRU */
6398 VLRU_BeginExclusive_r(struct VLRU_q * q)
6400 assert(q->busy == 0);
6404 /* end exclusive access on VLRU */
6406 VLRU_EndExclusive_r(struct VLRU_q * q)
6410 assert(pthread_cond_broadcast(&q->cv) == 0);
6413 /* wait for another thread to end exclusive access on VLRU */
6415 VLRU_Wait_r(struct VLRU_q * q)
6418 VOL_CV_WAIT(&q->cv);
6423 * volume soft detach
6425 * caller MUST NOT hold a ref count on vp */
6427 VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh)
6432 assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
6434 ts_save = vp->stats.last_get;
6435 if (ts_save > thresh)
6438 if (vp->nUsers || vp->nWaiters)
6441 if (VIsExclusiveState(V_attachState(vp))) {
6445 switch (V_attachState(vp)) {
6446 case VOL_STATE_UNATTACHED:
6447 case VOL_STATE_PREATTACHED:
6448 case VOL_STATE_ERROR:
6449 case VOL_STATE_GOING_OFFLINE:
6450 case VOL_STATE_SHUTTING_DOWN:
6451 case VOL_STATE_SALVAGING:
6452 volume_LRU.q[vp->vlru.idx].len--;
6454 /* create and cancel a reservation to
6455 * give the volume an opportunity to
6457 VCreateReservation_r(vp);
6458 queue_Remove(&vp->vlru);
6459 vp->vlru.idx = VLRU_QUEUE_INVALID;
6460 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
6461 VCancelReservation_r(vp);
6467 /* hold the volume and take it offline.
6468 * no need for reservations, as VHold_r
6469 * takes care of that internally. */
6470 if (VHold_r(vp) == 0) {
6471 /* vhold drops the glock, so now we should
6472 * check to make sure we aren't racing against
6473 * other threads. if we are racing, offlining vp
6474 * would be wasteful, and block the scanner for a while
6478 (vp->shuttingDown) ||
6479 (vp->goingOffline) ||
6480 (vp->stats.last_get != ts_save)) {
6481 /* looks like we're racing someone else. bail */
6485 /* pull it off the VLRU */
6486 assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
6487 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
6488 queue_Remove(&vp->vlru);
6489 vp->vlru.idx = VLRU_QUEUE_INVALID;
6490 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
6492 /* take if offline */
6493 VOffline_r(vp, "volume has been soft detached");
6495 /* invalidate the volume header cache */
6496 FreeVolumeHeader(vp);
6499 IncUInt64(&VStats.soft_detaches);
6500 vp->stats.soft_detaches++;
6502 /* put in pre-attached state so demand
6503 * attacher can work on it */
6504 VChangeState_r(vp, VOL_STATE_PREATTACHED);
6510 #endif /* AFS_DEMAND_ATTACH_FS */
6513 /***************************************************/
6514 /* Volume Header Cache routines */
6515 /***************************************************/
6518 * volume header cache.
6520 struct volume_hdr_LRU_t volume_hdr_LRU;
6523 * initialize the volume header cache.
6525 * @param[in] howMany number of header cache entries to preallocate
6527 * @pre VOL_LOCK held. Function has never been called before.
6529 * @post howMany cache entries are allocated, initialized, and added
6530 * to the LRU list. Header cache statistics are initialized.
6532 * @note only applicable to fileServer program type. Should only be
6533 * called once during volume package initialization.
6535 * @internal volume package internal use only.
6538 VInitVolumeHeaderCache(afs_uint32 howMany)
6540 register struct volHeader *hp;
6541 if (programType != fileServer)
6543 queue_Init(&volume_hdr_LRU);
6544 volume_hdr_LRU.stats.free = 0;
6545 volume_hdr_LRU.stats.used = howMany;
6546 volume_hdr_LRU.stats.attached = 0;
6547 hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
6551 /* We are using ReleaseVolumeHeader to initialize the values on the header list
6552 * to ensure they have the right values
6554 ReleaseVolumeHeader(hp++);
6558 * get a volume header and attach it to the volume object.
6560 * @param[in] vp pointer to volume object
6562 * @return cache entry status
6563 * @retval 0 volume header was newly attached; cache data is invalid
6564 * @retval 1 volume header was previously attached; cache data is valid
6566 * @pre VOL_LOCK held. For DAFS, lightweight ref must be held on volume object.
6568 * @post volume header attached to volume object. if necessary, header cache
6569 * entry on LRU is synchronized to disk. Header is removed from LRU list.
6571 * @note VOL_LOCK may be dropped
6573 * @warning this interface does not load header data from disk. it merely
6574 * attaches a header object to the volume object, and may sync the old
6575 * header cache data out to disk in the process.
6577 * @internal volume package internal use only.
6580 GetVolumeHeader(register Volume * vp)
6583 register struct volHeader *hd;
6585 static int everLogged = 0;
6587 #ifdef AFS_DEMAND_ATTACH_FS
6588 VolState vp_save = 0, back_save = 0;
6590 /* XXX debug 9/19/05 we've apparently got
6591 * a ref counting bug somewhere that's
6592 * breaking the nUsers == 0 => header on LRU
6594 if (vp->header && queue_IsNotOnQueue(vp->header)) {
6595 Log("nUsers == 0, but header not on LRU\n");
6600 old = (vp->header != NULL); /* old == volume already has a header */
6602 if (programType != fileServer) {
6603 /* for volume utilities, we allocate volHeaders as needed */
6605 hd = (struct volHeader *)calloc(1, sizeof(*vp->header));
6609 #ifdef AFS_DEMAND_ATTACH_FS
6610 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
6614 /* for the fileserver, we keep a volume header cache */
6616 /* the header we previously dropped in the lru is
6617 * still available. pull it off the lru and return */
6620 assert(hd->back == vp);
6622 /* we need to grab a new element off the LRU */
6623 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
6624 /* grab an element and pull off of LRU */
6625 hd = queue_First(&volume_hdr_LRU, volHeader);
6628 /* LRU is empty, so allocate a new volHeader
6629 * this is probably indicative of a leak, so let the user know */
6630 hd = (struct volHeader *)calloc(1, sizeof(struct volHeader));
6633 Log("****Allocated more volume headers, probably leak****\n");
6636 volume_hdr_LRU.stats.free++;
6639 /* this header used to belong to someone else.
6640 * we'll need to check if the header needs to
6641 * be sync'd out to disk */
6643 #ifdef AFS_DEMAND_ATTACH_FS
6644 /* if hd->back were in an exclusive state, then
6645 * its volHeader would not be on the LRU... */
6646 assert(!VIsExclusiveState(V_attachState(hd->back)));
6649 if (hd->diskstuff.inUse) {
6650 /* volume was in use, so we'll need to sync
6651 * its header to disk */
6653 #ifdef AFS_DEMAND_ATTACH_FS
6654 back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
6655 vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
6656 VCreateReservation_r(hd->back);
6660 WriteVolumeHeader_r(&error, hd->back);
6661 /* Ignore errors; catch them later */
6663 #ifdef AFS_DEMAND_ATTACH_FS
6668 hd->back->header = NULL;
6669 #ifdef AFS_DEMAND_ATTACH_FS
6670 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
6672 if (hd->diskstuff.inUse) {
6673 VChangeState_r(hd->back, back_save);
6674 VCancelReservation_r(hd->back);
6675 VChangeState_r(vp, vp_save);
6679 volume_hdr_LRU.stats.attached++;
6683 #ifdef AFS_DEMAND_ATTACH_FS
6684 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
6687 volume_hdr_LRU.stats.free--;
6688 volume_hdr_LRU.stats.used++;
6690 IncUInt64(&VStats.hdr_gets);
6691 #ifdef AFS_DEMAND_ATTACH_FS
6692 IncUInt64(&vp->stats.hdr_gets);
6693 vp->stats.last_hdr_get = FT_ApproxTime();
6700 * make sure volume header is attached and contains valid cache data.
6702 * @param[out] ec outbound error code
6703 * @param[in] vp pointer to volume object
6705 * @pre VOL_LOCK held. For DAFS, lightweight ref held on vp.
6707 * @post header cache entry attached, and loaded with valid data, or
6708 * *ec is nonzero, and the header is released back into the LRU.
6710 * @internal volume package internal use only.
6713 LoadVolumeHeader(Error * ec, Volume * vp)
6715 #ifdef AFS_DEMAND_ATTACH_FS
6716 VolState state_save;
6720 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
6721 IncUInt64(&VStats.hdr_loads);
6722 state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
6725 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
6726 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
6728 IncUInt64(&vp->stats.hdr_loads);
6729 now = FT_ApproxTime();
6733 V_attachFlags(vp) |= VOL_HDR_LOADED;
6734 vp->stats.last_hdr_load = now;
6736 VChangeState_r(vp, state_save);
6738 #else /* AFS_DEMAND_ATTACH_FS */
6740 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
6741 IncUInt64(&VStats.hdr_loads);
6743 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
6744 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
6747 #endif /* AFS_DEMAND_ATTACH_FS */
6749 /* maintain (nUsers==0) => header in LRU invariant */
6750 FreeVolumeHeader(vp);
6755 * release a header cache entry back into the LRU list.
6757 * @param[in] hd pointer to volume header cache object
6759 * @pre VOL_LOCK held.
6761 * @post header cache object appended onto end of LRU list.
6763 * @note only applicable to fileServer program type.
6765 * @note used to place a header cache entry back into the
6766 * LRU pool without invalidating it as a cache entry.
6768 * @internal volume package internal use only.
6771 ReleaseVolumeHeader(register struct volHeader *hd)
6773 if (programType != fileServer)
6775 if (!hd || queue_IsOnQueue(hd)) /* no header, or header already released */
6777 queue_Append(&volume_hdr_LRU, hd);
6778 #ifdef AFS_DEMAND_ATTACH_FS
6780 V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
6783 volume_hdr_LRU.stats.free++;
6784 volume_hdr_LRU.stats.used--;
6788 * free/invalidate a volume header cache entry.
6790 * @param[in] vp pointer to volume object
6792 * @pre VOL_LOCK is held.
6794 * @post For fileserver, header cache entry is returned to LRU, and it is
6795 * invalidated as a cache entry. For volume utilities, the header
6796 * cache entry is freed.
6798 * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
6799 * whenever it is necessary to invalidate the header cache entry.
6801 * @see ReleaseVolumeHeader
6803 * @internal volume package internal use only.
6806 FreeVolumeHeader(register Volume * vp)
6808 register struct volHeader *hd = vp->header;
6811 if (programType == fileServer) {
6812 ReleaseVolumeHeader(hd);
6817 #ifdef AFS_DEMAND_ATTACH_FS
6818 V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
6820 volume_hdr_LRU.stats.attached--;
6825 /***************************************************/
6826 /* Volume Hash Table routines */
6827 /***************************************************/
6830 * set size of volume object hash table.
6832 * @param[in] logsize log(2) of desired hash table size
6834 * @return operation status
6836 * @retval -1 failure
6838 * @pre MUST be called prior to VInitVolumePackage2
6840 * @post Volume Hash Table will have 2^logsize buckets
6843 VSetVolHashSize(int logsize)
6845 /* 64 to 16384 hash buckets seems like a reasonable range */
6846 if ((logsize < 6 ) || (logsize > 14)) {
6851 VolumeHashTable.Size = 1 << logsize;
6852 VolumeHashTable.Mask = VolumeHashTable.Size - 1;
6854 /* we can't yet support runtime modification of this
6855 * parameter. we'll need a configuration rwlock to
6856 * make runtime modification feasible.... */
6863 * initialize dynamic data structures for volume hash table.
6865 * @post hash table is allocated, and fields are initialized.
6867 * @internal volume package internal use only.
6870 VInitVolumeHash(void)
6874 VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
6875 sizeof(VolumeHashChainHead));
6876 assert(VolumeHashTable.Table != NULL);
6878 for (i=0; i < VolumeHashTable.Size; i++) {
6879 queue_Init(&VolumeHashTable.Table[i]);
6880 #ifdef AFS_DEMAND_ATTACH_FS
6881 assert(pthread_cond_init(&VolumeHashTable.Table[i].chain_busy_cv, NULL) == 0);
6882 #endif /* AFS_DEMAND_ATTACH_FS */
6887 * add a volume object to the hash table.
6889 * @param[in] vp pointer to volume object
6890 * @param[in] hashid hash of volume id
6892 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
6895 * @post volume is added to hash chain.
6897 * @internal volume package internal use only.
6899 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
6900 * asynchronous hash chain reordering to finish.
6903 AddVolumeToHashTable(register Volume * vp, int hashid)
6905 VolumeHashChainHead * head;
6907 if (queue_IsOnQueue(vp))
6910 head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
6912 #ifdef AFS_DEMAND_ATTACH_FS
6913 /* wait for the hash chain to become available */
6916 V_attachFlags(vp) |= VOL_IN_HASH;
6917 vp->chainCacheCheck = ++head->cacheCheck;
6918 #endif /* AFS_DEMAND_ATTACH_FS */
6921 vp->hashid = hashid;
6922 queue_Append(head, vp);
6923 vp->vnodeHashOffset = VolumeHashOffset_r();
6927 * delete a volume object from the hash table.
6929 * @param[in] vp pointer to volume object
6931 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
6934 * @post volume is removed from hash chain.
6936 * @internal volume package internal use only.
6938 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
6939 * asynchronous hash chain reordering to finish.
6942 DeleteVolumeFromHashTable(register Volume * vp)
6944 VolumeHashChainHead * head;
6946 if (!queue_IsOnQueue(vp))
6949 head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
6951 #ifdef AFS_DEMAND_ATTACH_FS
6952 /* wait for the hash chain to become available */
6955 V_attachFlags(vp) &= ~(VOL_IN_HASH);
6957 #endif /* AFS_DEMAND_ATTACH_FS */
6961 /* do NOT reset hashid to zero, as the online
6962 * salvager package may need to know the volume id
6963 * after the volume is removed from the hash */
6967 * lookup a volume object in the hash table given a volume id.
6969 * @param[out] ec error code return
6970 * @param[in] volumeId volume id
6971 * @param[in] hint volume object which we believe could be the correct
6974 * @return volume object pointer
6975 * @retval NULL no such volume id is registered with the hash table.
6977 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
6980 * @post volume object with the given id is returned. volume object and
6981 * hash chain access statistics are updated. hash chain may have
6984 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
6985 * asynchronous hash chain reordering operation to finish, or
6986 * in order for us to perform an asynchronous chain reordering.
6988 * @note Hash chain reorderings occur when the access count for the
6989 * volume object being looked up exceeds the sum of the previous
6990 * node's (the node ahead of it in the hash chain linked list)
6991 * access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
6993 * @note For DAFS, the hint parameter allows us to short-circuit if the
6994 * cacheCheck fields match between the hash chain head and the
6995 * hint volume object.
6998 VLookupVolume_r(Error * ec, VolId volumeId, Volume * hint)
7000 register int looks = 0;
7002 #ifdef AFS_DEMAND_ATTACH_FS
7005 VolumeHashChainHead * head;
7008 head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
7010 #ifdef AFS_DEMAND_ATTACH_FS
7011 /* wait for the hash chain to become available */
7014 /* check to see if we can short circuit without walking the hash chain */
7015 if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
7016 IncUInt64(&hint->stats.hash_short_circuits);
7019 #endif /* AFS_DEMAND_ATTACH_FS */
7021 /* someday we need to either do per-chain locks, RWlocks,
7022 * or both for volhash access.
7023 * (and move to a data structure with better cache locality) */
7025 /* search the chain for this volume id */
7026 for(queue_Scan(head, vp, np, Volume)) {
7028 if ((vp->hashid == volumeId)) {
7033 if (queue_IsEnd(head, vp)) {
7037 #ifdef AFS_DEMAND_ATTACH_FS
7038 /* update hash chain statistics */
7041 FillInt64(lks, 0, looks);
7042 AddUInt64(head->looks, lks, &head->looks);
7043 AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
7044 IncUInt64(&head->gets);
7049 IncUInt64(&vp->stats.hash_lookups);
7051 /* for demand attach fileserver, we permit occasional hash chain reordering
7052 * so that frequently looked up volumes move towards the head of the chain */
7053 pp = queue_Prev(vp, Volume);
7054 if (!queue_IsEnd(head, pp)) {
7055 FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
7056 AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
7057 if (GEInt64(vp->stats.hash_lookups, thresh)) {
7058 VReorderHash_r(head, pp, vp);
7062 /* update the short-circuit cache check */
7063 vp->chainCacheCheck = head->cacheCheck;
7065 #endif /* AFS_DEMAND_ATTACH_FS */
7070 #ifdef AFS_DEMAND_ATTACH_FS
7071 /* perform volume hash chain reordering.
7073 * advance a subchain beginning at vp ahead of
7074 * the adjacent subchain ending at pp */
7076 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
7078 Volume *tp, *np, *lp;
7079 afs_uint64 move_thresh;
7081 /* this should never be called if the chain is already busy, so
7082 * no need to wait for other exclusive chain ops to finish */
7084 /* this is a rather heavy set of operations,
7085 * so let's set the chain busy flag and drop
7087 VHashBeginExclusive_r(head);
7090 /* scan forward in the chain from vp looking for the last element
7091 * in the chain we want to advance */
7092 FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
7093 AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
7094 for(queue_ScanFrom(head, vp, tp, np, Volume)) {
7095 if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
7099 lp = queue_Prev(tp, Volume);
7101 /* scan backwards from pp to determine where to splice and
7102 * insert the subchain we're advancing */
7103 for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
7104 if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
7108 tp = queue_Next(tp, Volume);
7110 /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
7111 queue_MoveChainBefore(tp,vp,lp);
7114 IncUInt64(&VStats.hash_reorders);
7116 IncUInt64(&head->reorders);
7118 /* wake up any threads waiting for the hash chain */
7119 VHashEndExclusive_r(head);
7123 /* demand-attach fs volume hash
7124 * asynchronous exclusive operations */
7127 * begin an asynchronous exclusive operation on a volume hash chain.
7129 * @param[in] head pointer to volume hash chain head object
7131 * @pre VOL_LOCK held. hash chain is quiescent.
7133 * @post hash chain marked busy.
7135 * @note this interface is used in conjunction with VHashEndExclusive_r and
7136 * VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
7137 * volume hash chain. Its main use case is hash chain reordering, which
7138 * has the potential to be a highly latent operation.
7140 * @see VHashEndExclusive_r
7145 * @internal volume package internal use only.
7148 VHashBeginExclusive_r(VolumeHashChainHead * head)
7150 assert(head->busy == 0);
7155 * relinquish exclusive ownership of a volume hash chain.
7157 * @param[in] head pointer to volume hash chain head object
7159 * @pre VOL_LOCK held. thread owns the hash chain exclusively.
7161 * @post hash chain is marked quiescent. threads awaiting use of
7162 * chain are awakened.
7164 * @see VHashBeginExclusive_r
7169 * @internal volume package internal use only.
7172 VHashEndExclusive_r(VolumeHashChainHead * head)
7176 assert(pthread_cond_broadcast(&head->chain_busy_cv) == 0);
7180 * wait for all asynchronous operations on a hash chain to complete.
7182 * @param[in] head pointer to volume hash chain head object
7184 * @pre VOL_LOCK held.
7186 * @post hash chain object is quiescent.
7188 * @see VHashBeginExclusive_r
7189 * @see VHashEndExclusive_r
7193 * @note This interface should be called before any attempt to
7194 * traverse the hash chain. It is permissible for a thread
7195 * to gain exclusive access to the chain, and then perform
7196 * latent operations on the chain asynchronously wrt the
7199 * @warning if waiting is necessary, VOL_LOCK is dropped
7201 * @internal volume package internal use only.
7204 VHashWait_r(VolumeHashChainHead * head)
7206 while (head->busy) {
7207 VOL_CV_WAIT(&head->chain_busy_cv);
7210 #endif /* AFS_DEMAND_ATTACH_FS */
7213 /***************************************************/
7214 /* Volume by Partition List routines */
7215 /***************************************************/
7218 * demand attach fileserver adds a
7219 * linked list of volumes to each
7220 * partition object, thus allowing
7221 * for quick enumeration of all
7222 * volumes on a partition
7225 #ifdef AFS_DEMAND_ATTACH_FS
7227 * add a volume to its disk partition VByPList.
7229 * @param[in] vp pointer to volume object
7231 * @pre either the disk partition VByPList is owned exclusively
7232 * by the calling thread, or the list is quiescent and
7235 * @post volume is added to disk partition VByPList
7239 * @warning it is the caller's responsibility to ensure list
7242 * @see VVByPListWait_r
7243 * @see VVByPListBeginExclusive_r
7244 * @see VVByPListEndExclusive_r
7246 * @internal volume package internal use only.
7249 AddVolumeToVByPList_r(Volume * vp)
7251 if (queue_IsNotOnQueue(&vp->vol_list)) {
7252 queue_Append(&vp->partition->vol_list, &vp->vol_list);
7253 V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
7254 vp->partition->vol_list.len++;
7259 * delete a volume from its disk partition VByPList.
7261 * @param[in] vp pointer to volume object
7263 * @pre either the disk partition VByPList is owned exclusively
7264 * by the calling thread, or the list is quiescent and
7267 * @post volume is removed from the disk partition VByPList
7271 * @warning it is the caller's responsibility to ensure list
7274 * @see VVByPListWait_r
7275 * @see VVByPListBeginExclusive_r
7276 * @see VVByPListEndExclusive_r
7278 * @internal volume package internal use only.
7281 DeleteVolumeFromVByPList_r(Volume * vp)
7283 if (queue_IsOnQueue(&vp->vol_list)) {
7284 queue_Remove(&vp->vol_list);
7285 V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
7286 vp->partition->vol_list.len--;
7291 * begin an asynchronous exclusive operation on a VByPList.
7293 * @param[in] dp pointer to disk partition object
7295 * @pre VOL_LOCK held. VByPList is quiescent.
7297 * @post VByPList marked busy.
7299 * @note this interface is used in conjunction with VVByPListEndExclusive_r and
7300 * VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
7303 * @see VVByPListEndExclusive_r
7304 * @see VVByPListWait_r
7308 * @internal volume package internal use only.
7310 /* take exclusive control over the list */
7312 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
7314 assert(dp->vol_list.busy == 0);
7315 dp->vol_list.busy = 1;
7319 * relinquish exclusive ownership of a VByPList.
7321 * @param[in] dp pointer to disk partition object
7323 * @pre VOL_LOCK held. thread owns the VByPList exclusively.
7325 * @post VByPList is marked quiescent. threads awaiting use of
7326 * the list are awakened.
7328 * @see VVByPListBeginExclusive_r
7329 * @see VVByPListWait_r
7333 * @internal volume package internal use only.
7336 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
7338 assert(dp->vol_list.busy);
7339 dp->vol_list.busy = 0;
7340 assert(pthread_cond_broadcast(&dp->vol_list.cv) == 0);
7344 * wait for all asynchronous operations on a VByPList to complete.
7346 * @param[in] dp pointer to disk partition object
7348 * @pre VOL_LOCK is held.
7350 * @post disk partition's VByP list is quiescent
7354 * @note This interface should be called before any attempt to
7355 * traverse the VByPList. It is permissible for a thread
7356 * to gain exclusive access to the list, and then perform
7357 * latent operations on the list asynchronously wrt the
7360 * @warning if waiting is necessary, VOL_LOCK is dropped
7362 * @see VVByPListEndExclusive_r
7363 * @see VVByPListBeginExclusive_r
7365 * @internal volume package internal use only.
7368 VVByPListWait_r(struct DiskPartition64 * dp)
7370 while (dp->vol_list.busy) {
7371 VOL_CV_WAIT(&dp->vol_list.cv);
7374 #endif /* AFS_DEMAND_ATTACH_FS */
7376 /***************************************************/
7377 /* Volume Cache Statistics routines */
7378 /***************************************************/
7381 VPrintCacheStats_r(void)
7383 afs_uint32 get_hi, get_lo, load_hi, load_lo;
7384 register struct VnodeClassInfo *vcp;
7385 vcp = &VnodeClassInfo[vLarge];
7386 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);
7387 vcp = &VnodeClassInfo[vSmall];
7388 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);
7389 SplitInt64(VStats.hdr_gets, get_hi, get_lo);
7390 SplitInt64(VStats.hdr_loads, load_hi, load_lo);
7391 Log("Volume header cache, %d entries, %d gets, %d replacements\n",
7392 VStats.hdr_cache_size, get_lo, load_lo);
7396 VPrintCacheStats(void)
7399 VPrintCacheStats_r();
7403 #ifdef AFS_DEMAND_ATTACH_FS
7405 UInt64ToDouble(afs_uint64 * x)
7407 static double c32 = 4.0 * 1.073741824 * 1000000000.0;
7409 SplitInt64(*x, h, l);
7410 return (((double)h) * c32) + ((double) l);
7414 DoubleToPrintable(double x, char * buf, int len)
7416 static double billion = 1000000000.0;
7419 y[0] = (afs_uint32) (x / (billion * billion));
7420 y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
7421 y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
7424 snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
7426 snprintf(buf, len, "%d%09d", y[1], y[2]);
7428 snprintf(buf, len, "%d", y[2]);
7434 struct VLRUExtStatsEntry {
7438 struct VLRUExtStats {
7444 } queue_info[VLRU_QUEUE_INVALID];
7445 struct VLRUExtStatsEntry * vec;
7449 * add a 256-entry fudge factor onto the vector in case state changes
7450 * out from under us.
7452 #define VLRU_EXT_STATS_VEC_LEN_FUDGE 256
7455 * collect extended statistics for the VLRU subsystem.
7457 * @param[out] stats pointer to stats structure to be populated
7458 * @param[in] nvols number of volumes currently known to exist
7460 * @pre VOL_LOCK held
7462 * @post stats->vec allocated and populated
7464 * @return operation status
7469 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
7471 afs_uint32 cur, idx, len;
7472 struct rx_queue * qp, * nqp;
7474 struct VLRUExtStatsEntry * vec;
7476 len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
7477 vec = stats->vec = calloc(len,
7478 sizeof(struct VLRUExtStatsEntry));
7484 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
7485 VLRU_Wait_r(&volume_LRU.q[idx]);
7486 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7489 stats->queue_info[idx].start = cur;
7491 for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7493 /* out of space in vec */
7496 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7497 vec[cur].volid = vp->hashid;
7501 stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
7504 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7512 #define ENUMTOSTRING(en) #en
7513 #define ENUMCASE(en) \
7515 return ENUMTOSTRING(en); \
7519 vlru_idx_to_string(int idx)
7522 ENUMCASE(VLRU_QUEUE_NEW);
7523 ENUMCASE(VLRU_QUEUE_MID);
7524 ENUMCASE(VLRU_QUEUE_OLD);
7525 ENUMCASE(VLRU_QUEUE_CANDIDATE);
7526 ENUMCASE(VLRU_QUEUE_HELD);
7527 ENUMCASE(VLRU_QUEUE_INVALID);
7529 return "**UNKNOWN**";
7534 VPrintExtendedCacheStats_r(int flags)
7537 afs_uint32 vol_sum = 0;
7544 struct stats looks, gets, reorders, len;
7545 struct stats ch_looks, ch_gets, ch_reorders;
7547 VolumeHashChainHead *head;
7549 struct VLRUExtStats vlru_stats;
7551 /* zero out stats */
7552 memset(&looks, 0, sizeof(struct stats));
7553 memset(&gets, 0, sizeof(struct stats));
7554 memset(&reorders, 0, sizeof(struct stats));
7555 memset(&len, 0, sizeof(struct stats));
7556 memset(&ch_looks, 0, sizeof(struct stats));
7557 memset(&ch_gets, 0, sizeof(struct stats));
7558 memset(&ch_reorders, 0, sizeof(struct stats));
7560 for (i = 0; i < VolumeHashTable.Size; i++) {
7561 head = &VolumeHashTable.Table[i];
7564 VHashBeginExclusive_r(head);
7567 ch_looks.sum = UInt64ToDouble(&head->looks);
7568 ch_gets.sum = UInt64ToDouble(&head->gets);
7569 ch_reorders.sum = UInt64ToDouble(&head->reorders);
7571 /* update global statistics */
7573 looks.sum += ch_looks.sum;
7574 gets.sum += ch_gets.sum;
7575 reorders.sum += ch_reorders.sum;
7576 len.sum += (double)head->len;
7577 vol_sum += head->len;
7580 len.min = (double) head->len;
7581 len.max = (double) head->len;
7582 looks.min = ch_looks.sum;
7583 looks.max = ch_looks.sum;
7584 gets.min = ch_gets.sum;
7585 gets.max = ch_gets.sum;
7586 reorders.min = ch_reorders.sum;
7587 reorders.max = ch_reorders.sum;
7589 if (((double)head->len) < len.min)
7590 len.min = (double) head->len;
7591 if (((double)head->len) > len.max)
7592 len.max = (double) head->len;
7593 if (ch_looks.sum < looks.min)
7594 looks.min = ch_looks.sum;
7595 else if (ch_looks.sum > looks.max)
7596 looks.max = ch_looks.sum;
7597 if (ch_gets.sum < gets.min)
7598 gets.min = ch_gets.sum;
7599 else if (ch_gets.sum > gets.max)
7600 gets.max = ch_gets.sum;
7601 if (ch_reorders.sum < reorders.min)
7602 reorders.min = ch_reorders.sum;
7603 else if (ch_reorders.sum > reorders.max)
7604 reorders.max = ch_reorders.sum;
7608 if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
7609 /* compute detailed per-chain stats */
7610 struct stats hdr_loads, hdr_gets;
7611 double v_looks, v_loads, v_gets;
7613 /* initialize stats with data from first element in chain */
7614 vp = queue_First(head, Volume);
7615 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
7616 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
7617 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
7618 ch_gets.min = ch_gets.max = v_looks;
7619 hdr_loads.min = hdr_loads.max = v_loads;
7620 hdr_gets.min = hdr_gets.max = v_gets;
7621 hdr_loads.sum = hdr_gets.sum = 0;
7623 vp = queue_Next(vp, Volume);
7625 /* pull in stats from remaining elements in chain */
7626 for (queue_ScanFrom(head, vp, vp, np, Volume)) {
7627 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
7628 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
7629 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
7631 hdr_loads.sum += v_loads;
7632 hdr_gets.sum += v_gets;
7634 if (v_looks < ch_gets.min)
7635 ch_gets.min = v_looks;
7636 else if (v_looks > ch_gets.max)
7637 ch_gets.max = v_looks;
7639 if (v_loads < hdr_loads.min)
7640 hdr_loads.min = v_loads;
7641 else if (v_loads > hdr_loads.max)
7642 hdr_loads.max = v_loads;
7644 if (v_gets < hdr_gets.min)
7645 hdr_gets.min = v_gets;
7646 else if (v_gets > hdr_gets.max)
7647 hdr_gets.max = v_gets;
7650 /* compute per-chain averages */
7651 ch_gets.avg = ch_gets.sum / ((double)head->len);
7652 hdr_loads.avg = hdr_loads.sum / ((double)head->len);
7653 hdr_gets.avg = hdr_gets.sum / ((double)head->len);
7655 /* dump per-chain stats */
7656 Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
7658 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
7659 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
7660 Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
7661 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
7662 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
7663 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
7664 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
7665 Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
7666 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
7667 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
7668 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
7669 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
7670 Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
7671 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
7672 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
7673 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
7674 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
7675 } else if (flags & VOL_STATS_PER_CHAIN) {
7676 /* dump simple per-chain stats */
7677 Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
7679 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
7680 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
7681 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
7685 VHashEndExclusive_r(head);
7690 /* compute global averages */
7691 len.avg = len.sum / ((double)VolumeHashTable.Size);
7692 looks.avg = looks.sum / ((double)VolumeHashTable.Size);
7693 gets.avg = gets.sum / ((double)VolumeHashTable.Size);
7694 reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
7696 /* dump global stats */
7697 Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
7698 Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
7699 DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
7700 DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
7701 DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
7702 DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
7703 Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
7704 DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
7705 DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
7706 DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
7707 DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
7708 Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
7709 DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
7710 DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
7711 DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
7712 DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
7713 Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
7714 DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
7715 DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
7716 DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
7717 DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
7719 /* print extended disk related statistics */
7721 struct DiskPartition64 * diskP;
7722 afs_uint32 vol_count[VOLMAXPARTS+1];
7723 byte part_exists[VOLMAXPARTS+1];
7727 memset(vol_count, 0, sizeof(vol_count));
7728 memset(part_exists, 0, sizeof(part_exists));
7732 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
7734 vol_count[id] = diskP->vol_list.len;
7735 part_exists[id] = 1;
7739 for (i = 0; i <= VOLMAXPARTS; i++) {
7740 if (part_exists[i]) {
7741 /* XXX while this is currently safe, it is a violation
7742 * of the VGetPartitionById_r interface contract. */
7743 diskP = VGetPartitionById_r(i, 0);
7745 Log("Partition %s has %d online volumes\n",
7746 VPartitionPath(diskP), diskP->vol_list.len);
7753 /* print extended VLRU statistics */
7754 if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
7755 afs_uint32 idx, cur, lpos;
7759 Log("VLRU State Dump:\n\n");
7761 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
7762 Log("\t%s:\n", vlru_idx_to_string(idx));
7765 for (cur = vlru_stats.queue_info[idx].start;
7766 cur < vlru_stats.queue_info[idx].len;
7768 line[lpos++] = vlru_stats.vec[cur].volid;
7770 Log("\t\t%u, %u, %u, %u, %u,\n",
7771 line[0], line[1], line[2], line[3], line[4]);
7780 Log("\t\t%u, %u, %u, %u, %u\n",
7781 line[0], line[1], line[2], line[3], line[4]);
7786 free(vlru_stats.vec);
7793 VPrintExtendedCacheStats(int flags)
7796 VPrintExtendedCacheStats_r(flags);
7799 #endif /* AFS_DEMAND_ATTACH_FS */
7802 VCanScheduleSalvage(void)
7804 return vol_opts.canScheduleSalvage;
7810 return vol_opts.canUseFSSYNC;
7814 VCanUseSALVSYNC(void)
7816 return vol_opts.canUseSALVSYNC;