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);
2388 #endif /* AFS_DEMAND_ATTACH_FS */
2391 * called without any locks held
2392 * returns with vol_glock_mutex held
2395 attach2(Error * ec, VolId volumeId, char *path, register struct VolumeHeader * header,
2396 struct DiskPartition64 * partp, register Volume * vp, int isbusy, int mode)
2398 vp->specialStatus = (byte) (isbusy ? VBUSY : 0);
2399 IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header->parent,
2400 header->largeVnodeIndex);
2401 IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header->parent,
2402 header->smallVnodeIndex);
2403 IH_INIT(vp->diskDataHandle, partp->device, header->parent,
2404 header->volumeInfo);
2405 IH_INIT(vp->linkHandle, partp->device, header->parent, header->linkTable);
2406 vp->shuttingDown = 0;
2407 vp->goingOffline = 0;
2409 #ifdef AFS_DEMAND_ATTACH_FS
2410 vp->stats.last_attach = FT_ApproxTime();
2411 vp->stats.attaches++;
2415 IncUInt64(&VStats.attaches);
2416 vp->cacheCheck = ++VolumeCacheCheck;
2417 /* just in case this ever rolls over */
2418 if (!vp->cacheCheck)
2419 vp->cacheCheck = ++VolumeCacheCheck;
2420 GetVolumeHeader(vp);
2423 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2424 /* demand attach changes the V_PEEK mechanism
2426 * we can now suck the current disk data structure over
2427 * the fssync interface without going to disk
2429 * (technically, we don't need to restrict this feature
2430 * to demand attach fileservers. However, I'm trying
2431 * to limit the number of common code changes)
2433 if (programType != fileServer && mode == V_PEEK) {
2435 res.payload.len = sizeof(VolumeDiskData);
2436 res.payload.buf = &vp->header->diskstuff;
2438 if (FSYNC_VolOp(volumeId,
2440 FSYNC_VOL_QUERY_HDR,
2443 goto disk_header_loaded;
2446 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2447 (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2448 sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2450 #ifdef AFS_DEMAND_ATTACH_FS
2453 IncUInt64(&VStats.hdr_loads);
2454 IncUInt64(&vp->stats.hdr_loads);
2456 #endif /* AFS_DEMAND_ATTACH_FS */
2459 Log("VAttachVolume: Error reading diskDataHandle vol header %s; error=%u\n", path, *ec);
2462 #ifdef AFS_DEMAND_ATTACH_FS
2463 # ifdef FSSYNC_BUILD_CLIENT
2468 /* check for pending volume operations */
2469 if (vp->pending_vol_op) {
2470 /* see if the pending volume op requires exclusive access */
2471 switch (vp->pending_vol_op->vol_op_state) {
2472 case FSSYNC_VolOpPending:
2473 /* this should never happen */
2474 assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpPending);
2477 case FSSYNC_VolOpRunningUnknown:
2478 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
2479 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
2482 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
2483 /* fall through to take volume offline */
2486 case FSSYNC_VolOpRunningOffline:
2487 /* mark the volume down */
2489 VChangeState_r(vp, VOL_STATE_UNATTACHED);
2490 if (V_offlineMessage(vp)[0] == '\0')
2491 strlcpy(V_offlineMessage(vp),
2492 "A volume utility is running.",
2493 sizeof(V_offlineMessage(vp)));
2494 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
2496 /* check to see if we should set the specialStatus flag */
2497 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
2498 vp->specialStatus = VBUSY;
2505 V_attachFlags(vp) |= VOL_HDR_LOADED;
2506 vp->stats.last_hdr_load = vp->stats.last_attach;
2508 #endif /* AFS_DEMAND_ATTACH_FS */
2511 struct IndexFileHeader iHead;
2513 #if OPENAFS_VOL_STATS
2515 * We just read in the diskstuff part of the header. If the detailed
2516 * volume stats area has not yet been initialized, we should bzero the
2517 * area and mark it as initialized.
2519 if (!(V_stat_initialized(vp))) {
2520 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
2521 V_stat_initialized(vp) = 1;
2523 #endif /* OPENAFS_VOL_STATS */
2525 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
2526 (char *)&iHead, sizeof(iHead),
2527 SMALLINDEXMAGIC, SMALLINDEXVERSION);
2530 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
2535 struct IndexFileHeader iHead;
2537 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
2538 (char *)&iHead, sizeof(iHead),
2539 LARGEINDEXMAGIC, LARGEINDEXVERSION);
2542 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
2546 #ifdef AFS_NAMEI_ENV
2548 struct versionStamp stamp;
2550 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
2551 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
2554 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
2557 #endif /* AFS_NAMEI_ENV */
2559 #if defined(AFS_DEMAND_ATTACH_FS)
2560 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
2562 if (!VCanScheduleSalvage()) {
2563 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
2565 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2570 /* volume operation in progress */
2574 #else /* AFS_DEMAND_ATTACH_FS */
2576 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
2580 #endif /* AFS_DEMAND_ATTACH_FS */
2582 if (V_needsSalvaged(vp)) {
2583 if (vp->specialStatus)
2584 vp->specialStatus = 0;
2586 #if defined(AFS_DEMAND_ATTACH_FS)
2587 if (!VCanScheduleSalvage()) {
2588 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
2590 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
2593 #else /* AFS_DEMAND_ATTACH_FS */
2595 #endif /* AFS_DEMAND_ATTACH_FS */
2600 if (VShouldCheckInUse(mode)) {
2601 #ifndef FAST_RESTART
2602 if (V_inUse(vp) && VolumeWriteable(vp)) {
2603 if (!V_needsSalvaged(vp)) {
2604 V_needsSalvaged(vp) = 1;
2605 VUpdateVolume_r(ec, vp, 0);
2607 #if defined(AFS_DEMAND_ATTACH_FS)
2608 if (!VCanScheduleSalvage()) {
2609 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
2611 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
2614 #else /* AFS_DEMAND_ATTACH_FS */
2615 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
2617 #endif /* AFS_DEMAND_ATTACH_FS */
2621 #endif /* FAST_RESTART */
2623 if (programType == fileServer && V_destroyMe(vp) == DESTROY_ME) {
2624 /* Only check destroyMe if we are the fileserver, since the
2625 * volserver et al sometimes need to work with volumes with
2626 * destroyMe set. Examples are 'temporary' volumes the
2627 * volserver creates, and when we create a volume (destroyMe
2628 * is set on creation; sometimes a separate volserver
2629 * transaction is created to clear destroyMe).
2632 #if defined(AFS_DEMAND_ATTACH_FS)
2633 /* schedule a salvage so the volume goes away on disk */
2634 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2635 VChangeState_r(vp, VOL_STATE_ERROR);
2637 #endif /* AFS_DEMAND_ATTACH_FS */
2639 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
2645 vp->nextVnodeUnique = V_uniquifier(vp);
2646 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
2647 #ifndef BITMAP_LATER
2648 if (programType == fileServer && VolumeWriteable(vp)) {
2650 for (i = 0; i < nVNODECLASSES; i++) {
2651 VGetBitmap_r(ec, vp, i);
2653 #ifdef AFS_DEMAND_ATTACH_FS
2654 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2656 #endif /* AFS_DEMAND_ATTACH_FS */
2657 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
2663 #endif /* BITMAP_LATER */
2665 if (programType == fileServer) {
2666 if (vp->specialStatus)
2667 vp->specialStatus = 0;
2668 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
2669 V_inUse(vp) = fileServer;
2670 V_offlineMessage(vp)[0] = '\0';
2673 if ((mode != V_PEEK) && (mode != V_SECRETLY))
2674 V_inUse(vp) = programType;
2675 V_checkoutMode(vp) = mode;
2678 AddVolumeToHashTable(vp, V_id(vp));
2679 #ifdef AFS_DEMAND_ATTACH_FS
2680 if ((programType != fileServer) ||
2681 (V_inUse(vp) == fileServer)) {
2682 AddVolumeToVByPList_r(vp);
2684 VChangeState_r(vp, VOL_STATE_ATTACHED);
2686 VChangeState_r(vp, VOL_STATE_UNATTACHED);
2692 #ifdef AFS_DEMAND_ATTACH_FS
2693 if (!VIsErrorState(V_attachState(vp))) {
2694 VChangeState_r(vp, VOL_STATE_ERROR);
2696 #endif /* AFS_DEMAND_ATTACH_FS */
2698 VReleaseVolumeHandles_r(vp);
2700 #ifdef AFS_DEMAND_ATTACH_FS
2703 #else /* !AFS_DEMAND_ATTACH_FS */
2705 #endif /* !AFS_DEMAND_ATTACH_FS */
2709 /* Attach an existing volume.
2710 The volume also normally goes online at this time.
2711 An offline volume must be reattached to make it go online.
2715 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
2719 retVal = VAttachVolume_r(ec, volumeId, mode);
2725 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
2728 VGetVolumePath(ec, volumeId, &part, &name);
2730 register Volume *vp;
2732 vp = VGetVolume_r(&error, volumeId);
2734 assert(V_inUse(vp) == 0);
2735 VDetachVolume_r(ec, vp);
2739 return VAttachVolumeByName_r(ec, part, name, mode);
2742 /* Increment a reference count to a volume, sans context swaps. Requires
2743 * possibly reading the volume header in from the disk, since there's
2744 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
2746 * N.B. This call can fail if we can't read in the header!! In this case
2747 * we still guarantee we won't context swap, but the ref count won't be
2748 * incremented (otherwise we'd violate the invariant).
2750 /* NOTE: with the demand attach fileserver extensions, the global lock
2751 * is dropped within VHold */
2752 #ifdef AFS_DEMAND_ATTACH_FS
2754 VHold_r(register Volume * vp)
2758 VCreateReservation_r(vp);
2759 VWaitExclusiveState_r(vp);
2761 LoadVolumeHeader(&error, vp);
2763 VCancelReservation_r(vp);
2767 VCancelReservation_r(vp);
2770 #else /* AFS_DEMAND_ATTACH_FS */
2772 VHold_r(register Volume * vp)
2776 LoadVolumeHeader(&error, vp);
2782 #endif /* AFS_DEMAND_ATTACH_FS */
2786 VHold(register Volume * vp)
2790 retVal = VHold_r(vp);
2797 /***************************************************/
2798 /* get and put volume routines */
2799 /***************************************************/
2802 * put back a heavyweight reference to a volume object.
2804 * @param[in] vp volume object pointer
2806 * @pre VOL_LOCK held
2808 * @post heavyweight volume reference put back.
2809 * depending on state, volume may have been taken offline,
2810 * detached, salvaged, freed, etc.
2812 * @internal volume package internal use only
2815 VPutVolume_r(register Volume * vp)
2817 assert(--vp->nUsers >= 0);
2818 if (vp->nUsers == 0) {
2820 ReleaseVolumeHeader(vp->header);
2821 #ifdef AFS_DEMAND_ATTACH_FS
2822 if (!VCheckDetach(vp)) {
2826 #else /* AFS_DEMAND_ATTACH_FS */
2828 #endif /* AFS_DEMAND_ATTACH_FS */
2833 VPutVolume(register Volume * vp)
2841 /* Get a pointer to an attached volume. The pointer is returned regardless
2842 of whether or not the volume is in service or on/off line. An error
2843 code, however, is returned with an indication of the volume's status */
2845 VGetVolume(Error * ec, Error * client_ec, VolId volumeId)
2849 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
2855 VGetVolume_r(Error * ec, VolId volumeId)
2857 return GetVolume(ec, NULL, volumeId, NULL, 0);
2860 /* try to get a volume we've previously looked up */
2861 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
2863 VGetVolumeByVp_r(Error * ec, Volume * vp)
2865 return GetVolume(ec, NULL, vp->hashid, vp, 0);
2868 /* private interface for getting a volume handle
2869 * volumeId must be provided.
2870 * hint is an optional parameter to speed up hash lookups
2871 * flags is not used at this time
2873 /* for demand attach fs, caller MUST NOT hold a ref count on hint */
2875 GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint, int flags)
2878 /* pull this profiling/debugging code out of regular builds */
2880 #define VGET_CTR_INC(x) x++
2881 unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
2882 0, V7 = 0, V8 = 0, V9 = 0;
2883 unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
2885 #define VGET_CTR_INC(x)
2887 #ifdef AFS_DEMAND_ATTACH_FS
2888 Volume *avp, * rvp = hint;
2892 * if VInit is zero, the volume package dynamic
2893 * data structures have not been initialized yet,
2894 * and we must immediately return an error
2900 *client_ec = VOFFLINE;
2905 #ifdef AFS_DEMAND_ATTACH_FS
2907 VCreateReservation_r(rvp);
2909 #endif /* AFS_DEMAND_ATTACH_FS */
2917 vp = VLookupVolume_r(ec, volumeId, vp);
2923 #ifdef AFS_DEMAND_ATTACH_FS
2924 if (rvp && (rvp != vp)) {
2925 /* break reservation on old vp */
2926 VCancelReservation_r(rvp);
2929 #endif /* AFS_DEMAND_ATTACH_FS */
2935 /* Until we have reached an initialization level of 2
2936 * we don't know whether this volume exists or not.
2937 * We can't sleep and retry later because before a volume
2938 * is attached, the caller tries to get it first. Just
2939 * return VOFFLINE and the caller can choose whether to
2940 * retry the command or not. */
2950 IncUInt64(&VStats.hdr_gets);
2952 #ifdef AFS_DEMAND_ATTACH_FS
2953 /* block if someone else is performing an exclusive op on this volume */
2956 VCreateReservation_r(rvp);
2958 VWaitExclusiveState_r(vp);
2960 /* short circuit with VNOVOL in the following circumstances:
2963 * - VOL_STATE_SHUTTING_DOWN
2965 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
2966 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN) ||
2967 (V_attachState(vp) == VOL_STATE_GOING_OFFLINE)) {
2974 * short circuit with VOFFLINE in the following circumstances:
2976 * - VOL_STATE_UNATTACHED
2978 if (V_attachState(vp) == VOL_STATE_UNATTACHED) {
2979 if (vp->specialStatus) {
2980 *ec = vp->specialStatus;
2988 /* allowable states:
2994 if (vp->salvage.requested) {
2995 VUpdateSalvagePriority_r(vp);
2998 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
2999 avp = VAttachVolumeByVp_r(ec, vp, 0);
3002 /* VAttachVolumeByVp_r can return a pointer
3003 * != the vp passed to it under certain
3004 * conditions; make sure we don't leak
3005 * reservations if that happens */
3007 VCancelReservation_r(rvp);
3009 VCreateReservation_r(rvp);
3019 if (!vp->pending_vol_op) {
3034 if ((V_attachState(vp) == VOL_STATE_SALVAGING) ||
3035 (*ec == VSALVAGING)) {
3037 /* see CheckVnode() in afsfileprocs.c for an explanation
3038 * of this error code logic */
3039 afs_uint32 now = FT_ApproxTime();
3040 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
3043 *client_ec = VRESTARTING;
3052 LoadVolumeHeader(ec, vp);
3055 /* Only log the error if it was a totally unexpected error. Simply
3056 * a missing inode is likely to be caused by the volume being deleted */
3057 if (errno != ENXIO || LogLevel)
3058 Log("Volume %u: couldn't reread volume header\n",
3060 #ifdef AFS_DEMAND_ATTACH_FS
3061 if (VCanScheduleSalvage()) {
3062 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3067 #else /* AFS_DEMAND_ATTACH_FS */
3070 #endif /* AFS_DEMAND_ATTACH_FS */
3074 #ifdef AFS_DEMAND_ATTACH_FS
3076 * this test MUST happen after the volume header is loaded
3079 /* only valid before/during demand attachment */
3080 assert(!vp->pending_vol_op || vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
3082 /* deny getvolume due to running mutually exclusive vol op */
3083 if (vp->pending_vol_op && vp->pending_vol_op->vol_op_state==FSSYNC_VolOpRunningOffline) {
3085 * volume cannot remain online during this volume operation.
3088 if (vp->specialStatus) {
3090 * special status codes outrank normal VOFFLINE code
3092 *ec = vp->specialStatus;
3094 *client_ec = vp->specialStatus;
3098 /* see CheckVnode() in afsfileprocs.c for an explanation
3099 * of this error code logic */
3100 afs_uint32 now = FT_ApproxTime();
3101 if ((vp->stats.last_vol_op + (10 * 60)) >= now) {
3104 *client_ec = VRESTARTING;
3109 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3110 FreeVolumeHeader(vp);
3114 #endif /* AFS_DEMAND_ATTACH_FS */
3117 if (vp->shuttingDown) {
3124 if (programType == fileServer) {
3126 if (vp->goingOffline) {
3128 #ifdef AFS_DEMAND_ATTACH_FS
3129 /* wait for the volume to go offline */
3130 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
3131 VWaitStateChange_r(vp);
3133 #elif defined(AFS_PTHREAD_ENV)
3134 VOL_CV_WAIT(&vol_put_volume_cond);
3135 #else /* AFS_PTHREAD_ENV */
3136 LWP_WaitProcess(VPutVolume);
3137 #endif /* AFS_PTHREAD_ENV */
3140 if (vp->specialStatus) {
3142 *ec = vp->specialStatus;
3143 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3146 } else if (V_inUse(vp) == 0) {
3157 #ifdef AFS_DEMAND_ATTACH_FS
3158 /* if no error, bump nUsers */
3161 VLRU_UpdateAccess_r(vp);
3164 VCancelReservation_r(rvp);
3167 if (client_ec && !*client_ec) {
3170 #else /* AFS_DEMAND_ATTACH_FS */
3171 /* if no error, bump nUsers */
3178 #endif /* AFS_DEMAND_ATTACH_FS */
3186 /***************************************************/
3187 /* Volume offline/detach routines */
3188 /***************************************************/
3190 /* caller MUST hold a heavyweight ref on vp */
3191 #ifdef AFS_DEMAND_ATTACH_FS
3193 VTakeOffline_r(register Volume * vp)
3197 assert(vp->nUsers > 0);
3198 assert(programType == fileServer);
3200 VCreateReservation_r(vp);
3201 VWaitExclusiveState_r(vp);
3203 vp->goingOffline = 1;
3204 V_needsSalvaged(vp) = 1;
3206 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
3207 VCancelReservation_r(vp);
3209 #else /* AFS_DEMAND_ATTACH_FS */
3211 VTakeOffline_r(register Volume * vp)
3213 assert(vp->nUsers > 0);
3214 assert(programType == fileServer);
3216 vp->goingOffline = 1;
3217 V_needsSalvaged(vp) = 1;
3219 #endif /* AFS_DEMAND_ATTACH_FS */
3222 VTakeOffline(register Volume * vp)
3230 * force a volume offline.
3232 * @param[in] vp volume object pointer
3233 * @param[in] flags flags (see note below)
3235 * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
3236 * used when VUpdateVolume_r needs to call VForceOffline_r
3237 * (which in turn would normally call VUpdateVolume_r)
3239 * @see VUpdateVolume_r
3241 * @pre VOL_LOCK must be held.
3242 * for DAFS, caller must hold ref.
3244 * @note for DAFS, it _is safe_ to call this function from an
3247 * @post needsSalvaged flag is set.
3248 * for DAFS, salvage is requested.
3249 * no further references to the volume through the volume
3250 * package will be honored.
3251 * all file descriptor and vnode caches are invalidated.
3253 * @warning this is a heavy-handed interface. it results in
3254 * a volume going offline regardless of the current
3255 * reference count state.
3257 * @internal volume package internal use only
3260 VForceOffline_r(Volume * vp, int flags)
3264 #ifdef AFS_DEMAND_ATTACH_FS
3265 VChangeState_r(vp, VOL_STATE_ERROR);
3270 strcpy(V_offlineMessage(vp),
3271 "Forced offline due to internal error: volume needs to be salvaged");
3272 Log("Volume %u forced offline: it needs salvaging!\n", V_id(vp));
3275 vp->goingOffline = 0;
3276 V_needsSalvaged(vp) = 1;
3277 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
3278 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
3281 #ifdef AFS_DEMAND_ATTACH_FS
3282 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3283 #endif /* AFS_DEMAND_ATTACH_FS */
3285 #ifdef AFS_PTHREAD_ENV
3286 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3287 #else /* AFS_PTHREAD_ENV */
3288 LWP_NoYieldSignal(VPutVolume);
3289 #endif /* AFS_PTHREAD_ENV */
3291 VReleaseVolumeHandles_r(vp);
3295 * force a volume offline.
3297 * @param[in] vp volume object pointer
3299 * @see VForceOffline_r
3302 VForceOffline(Volume * vp)
3305 VForceOffline_r(vp, 0);
3309 /* The opposite of VAttachVolume. The volume header is written to disk, with
3310 the inUse bit turned off. A copy of the header is maintained in memory,
3311 however (which is why this is VOffline, not VDetach).
3314 VOffline_r(Volume * vp, char *message)
3316 #ifndef AFS_DEMAND_ATTACH_FS
3318 VolumeId vid = V_id(vp);
3321 assert(programType != volumeUtility && programType != volumeServer);
3326 if (V_offlineMessage(vp)[0] == '\0')
3327 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
3328 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
3330 vp->goingOffline = 1;
3331 #ifdef AFS_DEMAND_ATTACH_FS
3332 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
3333 VCreateReservation_r(vp);
3336 /* wait for the volume to go offline */
3337 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
3338 VWaitStateChange_r(vp);
3340 VCancelReservation_r(vp);
3341 #else /* AFS_DEMAND_ATTACH_FS */
3343 vp = VGetVolume_r(&error, vid); /* Wait for it to go offline */
3344 if (vp) /* In case it was reattached... */
3346 #endif /* AFS_DEMAND_ATTACH_FS */
3349 #ifdef AFS_DEMAND_ATTACH_FS
3351 * Take a volume offline in order to perform a volume operation.
3353 * @param[inout] ec address in which to store error code
3354 * @param[in] vp volume object pointer
3355 * @param[in] message volume offline status message
3358 * - VOL_LOCK is held
3359 * - caller MUST hold a heavyweight ref on vp
3362 * - volume is taken offline
3363 * - if possible, volume operation is promoted to running state
3364 * - on failure, *ec is set to nonzero
3366 * @note Although this function does not return any value, it may
3367 * still fail to promote our pending volume operation to
3368 * a running state. Any caller MUST check the value of *ec,
3369 * and MUST NOT blindly assume success.
3371 * @warning if the caller does not hold a lightweight ref on vp,
3372 * then it MUST NOT reference vp after this function
3373 * returns to the caller.
3375 * @internal volume package internal use only
3378 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
3380 assert(vp->pending_vol_op);
3386 if (V_offlineMessage(vp)[0] == '\0')
3387 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
3388 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
3390 vp->goingOffline = 1;
3391 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
3392 VCreateReservation_r(vp);
3395 /* Wait for the volume to go offline */
3396 while (!VIsOfflineState(V_attachState(vp))) {
3397 /* do not give corrupted volumes to the volserver */
3398 if (vp->salvage.requested && vp->pending_vol_op->com.programType != salvageServer) {
3402 VWaitStateChange_r(vp);
3406 VCancelReservation_r(vp);
3408 #endif /* AFS_DEMAND_ATTACH_FS */
3411 VOffline(Volume * vp, char *message)
3414 VOffline_r(vp, message);
3418 /* This gets used for the most part by utility routines that don't want
3419 * to keep all the volume headers around. Generally, the file server won't
3420 * call this routine, because then the offline message in the volume header
3421 * (or other information) won't be available to clients. For NAMEI, also
3422 * close the file handles. However, the fileserver does call this during
3423 * an attach following a volume operation.
3426 VDetachVolume_r(Error * ec, Volume * vp)
3429 struct DiskPartition64 *tpartp;
3430 int notifyServer = 0;
3431 int useDone = FSYNC_VOL_ON;
3433 *ec = 0; /* always "succeeds" */
3434 if (VCanUseFSSYNC()) {
3435 notifyServer = vp->needsPutBack;
3436 if (V_destroyMe(vp) == DESTROY_ME)
3437 useDone = FSYNC_VOL_DONE;
3438 #ifdef AFS_DEMAND_ATTACH_FS
3439 else if (!V_blessed(vp) || !V_inService(vp))
3440 useDone = FSYNC_VOL_LEAVE_OFF;
3443 tpartp = vp->partition;
3445 DeleteVolumeFromHashTable(vp);
3446 vp->shuttingDown = 1;
3447 #ifdef AFS_DEMAND_ATTACH_FS
3448 DeleteVolumeFromVByPList_r(vp);
3450 VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
3452 if (programType != fileServer)
3454 #endif /* AFS_DEMAND_ATTACH_FS */
3456 /* Will be detached sometime in the future--this is OK since volume is offline */
3458 /* XXX the following code should really be moved to VCheckDetach() since the volume
3459 * is not technically detached until the refcounts reach zero
3461 #ifdef FSSYNC_BUILD_CLIENT
3462 if (VCanUseFSSYNC() && notifyServer) {
3464 * Note: The server is not notified in the case of a bogus volume
3465 * explicitly to make it possible to create a volume, do a partial
3466 * restore, then abort the operation without ever putting the volume
3467 * online. This is essential in the case of a volume move operation
3468 * between two partitions on the same server. In that case, there
3469 * would be two instances of the same volume, one of them bogus,
3470 * which the file server would attempt to put on line
3472 FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
3473 /* XXX this code path is only hit by volume utilities, thus
3474 * V_BreakVolumeCallbacks will always be NULL. if we really
3475 * want to break callbacks in this path we need to use FSYNC_VolOp() */
3477 /* Dettaching it so break all callbacks on it */
3478 if (V_BreakVolumeCallbacks) {
3479 Log("volume %u detached; breaking all call backs\n", volume);
3480 (*V_BreakVolumeCallbacks) (volume);
3484 #endif /* FSSYNC_BUILD_CLIENT */
3488 VDetachVolume(Error * ec, Volume * vp)
3491 VDetachVolume_r(ec, vp);
3496 /***************************************************/
3497 /* Volume fd/inode handle closing routines */
3498 /***************************************************/
3500 /* For VDetachVolume, we close all cached file descriptors, but keep
3501 * the Inode handles in case we need to read from a busy volume.
3503 /* for demand attach, caller MUST hold ref count on vp */
3505 VCloseVolumeHandles_r(Volume * vp)
3507 #ifdef AFS_DEMAND_ATTACH_FS
3508 VolState state_save;
3510 state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
3515 * XXX need to investigate whether we can perform
3516 * DFlushVolume outside of vol_glock_mutex...
3518 * VCloseVnodeFiles_r drops the glock internally */
3519 DFlushVolume(vp->hashid);
3520 VCloseVnodeFiles_r(vp);
3522 #ifdef AFS_DEMAND_ATTACH_FS
3526 /* Too time consuming and unnecessary for the volserver */
3527 if (programType == fileServer) {
3528 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
3529 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
3530 IH_CONDSYNC(vp->diskDataHandle);
3532 IH_CONDSYNC(vp->linkHandle);
3533 #endif /* AFS_NT40_ENV */
3536 IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
3537 IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
3538 IH_REALLYCLOSE(vp->diskDataHandle);
3539 IH_REALLYCLOSE(vp->linkHandle);
3541 #ifdef AFS_DEMAND_ATTACH_FS
3543 VChangeState_r(vp, state_save);
3547 /* For both VForceOffline and VOffline, we close all relevant handles.
3548 * For VOffline, if we re-attach the volume, the files may possible be
3549 * different than before.
3551 /* for demand attach, caller MUST hold a ref count on vp */
3553 VReleaseVolumeHandles_r(Volume * vp)
3555 #ifdef AFS_DEMAND_ATTACH_FS
3556 VolState state_save;
3558 state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
3561 /* XXX need to investigate whether we can perform
3562 * DFlushVolume outside of vol_glock_mutex... */
3563 DFlushVolume(vp->hashid);
3565 VReleaseVnodeFiles_r(vp); /* releases the glock internally */
3567 #ifdef AFS_DEMAND_ATTACH_FS
3571 /* Too time consuming and unnecessary for the volserver */
3572 if (programType == fileServer) {
3573 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
3574 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
3575 IH_CONDSYNC(vp->diskDataHandle);
3577 IH_CONDSYNC(vp->linkHandle);
3578 #endif /* AFS_NT40_ENV */
3581 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
3582 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
3583 IH_RELEASE(vp->diskDataHandle);
3584 IH_RELEASE(vp->linkHandle);
3586 #ifdef AFS_DEMAND_ATTACH_FS
3588 VChangeState_r(vp, state_save);
3593 /***************************************************/
3594 /* Volume write and fsync routines */
3595 /***************************************************/
3598 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
3600 #ifdef AFS_DEMAND_ATTACH_FS
3601 VolState state_save;
3603 if (flags & VOL_UPDATE_WAIT) {
3604 VCreateReservation_r(vp);
3605 VWaitExclusiveState_r(vp);
3610 if (programType == fileServer)
3612 (V_inUse(vp) ? V_nextVnodeUnique(vp) +
3613 200 : V_nextVnodeUnique(vp));
3615 #ifdef AFS_DEMAND_ATTACH_FS
3616 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
3620 WriteVolumeHeader_r(ec, vp);
3622 #ifdef AFS_DEMAND_ATTACH_FS
3624 VChangeState_r(vp, state_save);
3625 if (flags & VOL_UPDATE_WAIT) {
3626 VCancelReservation_r(vp);
3631 Log("VUpdateVolume: error updating volume header, volume %u (%s)\n",
3632 V_id(vp), V_name(vp));
3633 /* try to update on-disk header,
3634 * while preventing infinite recursion */
3635 if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
3636 VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
3642 VUpdateVolume(Error * ec, Volume * vp)
3645 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
3650 VSyncVolume_r(Error * ec, Volume * vp, int flags)
3654 #ifdef AFS_DEMAND_ATTACH_FS
3655 VolState state_save;
3658 if (flags & VOL_SYNC_WAIT) {
3659 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
3661 VUpdateVolume_r(ec, vp, 0);
3664 #ifdef AFS_DEMAND_ATTACH_FS
3665 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
3668 fdP = IH_OPEN(V_diskDataHandle(vp));
3669 assert(fdP != NULL);
3670 code = FDH_SYNC(fdP);
3673 #ifdef AFS_DEMAND_ATTACH_FS
3675 VChangeState_r(vp, state_save);
3681 VSyncVolume(Error * ec, Volume * vp)
3684 VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
3689 /***************************************************/
3690 /* Volume dealloaction routines */
3691 /***************************************************/
3693 #ifdef AFS_DEMAND_ATTACH_FS
3695 FreeVolume(Volume * vp)
3697 /* free the heap space, iff it's safe.
3698 * otherwise, pull it out of the hash table, so it
3699 * will get deallocated when all refs to it go away */
3700 if (!VCheckFree(vp)) {
3701 DeleteVolumeFromHashTable(vp);
3702 DeleteVolumeFromVByPList_r(vp);
3704 /* make sure we invalidate the header cache entry */
3705 FreeVolumeHeader(vp);
3708 #endif /* AFS_DEMAND_ATTACH_FS */
3711 ReallyFreeVolume(Volume * vp)
3716 #ifdef AFS_DEMAND_ATTACH_FS
3718 VChangeState_r(vp, VOL_STATE_FREED);
3719 if (vp->pending_vol_op)
3720 free(vp->pending_vol_op);
3721 #endif /* AFS_DEMAND_ATTACH_FS */
3722 for (i = 0; i < nVNODECLASSES; i++)
3723 if (vp->vnodeIndex[i].bitmap)
3724 free(vp->vnodeIndex[i].bitmap);
3725 FreeVolumeHeader(vp);
3726 #ifndef AFS_DEMAND_ATTACH_FS
3727 DeleteVolumeFromHashTable(vp);
3728 #endif /* AFS_DEMAND_ATTACH_FS */
3732 /* check to see if we should shutdown this volume
3733 * returns 1 if volume was freed, 0 otherwise */
3734 #ifdef AFS_DEMAND_ATTACH_FS
3736 VCheckDetach(register Volume * vp)
3741 if (vp->nUsers || vp->nWaiters)
3744 if (vp->shuttingDown) {
3746 if ((programType != fileServer) &&
3747 (V_inUse(vp) == programType) &&
3748 ((V_checkoutMode(vp) == V_VOLUPD) ||
3749 (V_checkoutMode(vp) == V_SECRETLY) ||
3750 ((V_checkoutMode(vp) == V_CLONE) &&
3751 (VolumeWriteable(vp))))) {
3753 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
3755 Log("VCheckDetach: volume header update for volume %u "
3756 "failed with errno %d\n", vp->hashid, errno);
3759 VReleaseVolumeHandles_r(vp);
3761 ReallyFreeVolume(vp);
3762 if (programType == fileServer) {
3763 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3768 #else /* AFS_DEMAND_ATTACH_FS */
3770 VCheckDetach(register Volume * vp)
3778 if (vp->shuttingDown) {
3780 if ((programType != fileServer) &&
3781 (V_inUse(vp) == programType) &&
3782 ((V_checkoutMode(vp) == V_VOLUPD) ||
3783 (V_checkoutMode(vp) == V_SECRETLY) ||
3784 ((V_checkoutMode(vp) == V_CLONE) &&
3785 (VolumeWriteable(vp))))) {
3787 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
3789 Log("VCheckDetach: volume header update for volume %u failed with errno %d\n",
3793 VReleaseVolumeHandles_r(vp);
3794 ReallyFreeVolume(vp);
3795 if (programType == fileServer) {
3796 #if defined(AFS_PTHREAD_ENV)
3797 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3798 #else /* AFS_PTHREAD_ENV */
3799 LWP_NoYieldSignal(VPutVolume);
3800 #endif /* AFS_PTHREAD_ENV */
3805 #endif /* AFS_DEMAND_ATTACH_FS */
3807 /* check to see if we should offline this volume
3808 * return 1 if volume went offline, 0 otherwise */
3809 #ifdef AFS_DEMAND_ATTACH_FS
3811 VCheckOffline(register Volume * vp)
3815 if (vp->goingOffline && !vp->nUsers) {
3817 assert(programType == fileServer);
3818 assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
3819 (V_attachState(vp) != VOL_STATE_FREED) &&
3820 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
3821 (V_attachState(vp) != VOL_STATE_UNATTACHED));
3825 * VOL_STATE_GOING_OFFLINE
3826 * VOL_STATE_SHUTTING_DOWN
3827 * VIsErrorState(V_attachState(vp))
3828 * VIsExclusiveState(V_attachState(vp))
3831 VCreateReservation_r(vp);
3832 VChangeState_r(vp, VOL_STATE_OFFLINING);
3835 /* must clear the goingOffline flag before we drop the glock */
3836 vp->goingOffline = 0;
3841 /* perform async operations */
3842 VUpdateVolume_r(&error, vp, 0);
3843 VCloseVolumeHandles_r(vp);
3846 if (V_offlineMessage(vp)[0]) {
3847 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
3848 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
3849 V_offlineMessage(vp));
3851 Log("VOffline: Volume %lu (%s) is now offline\n",
3852 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
3856 /* invalidate the volume header cache entry */
3857 FreeVolumeHeader(vp);
3859 /* if nothing changed state to error or salvaging,
3860 * drop state to unattached */
3861 if (!VIsErrorState(V_attachState(vp))) {
3862 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3864 VCancelReservation_r(vp);
3865 /* no usage of vp is safe beyond this point */
3869 #else /* AFS_DEMAND_ATTACH_FS */
3871 VCheckOffline(register Volume * vp)
3875 if (vp->goingOffline && !vp->nUsers) {
3877 assert(programType == fileServer);
3880 vp->goingOffline = 0;
3882 VUpdateVolume_r(&error, vp, 0);
3883 VCloseVolumeHandles_r(vp);
3885 Log("VOffline: Volume %u (%s) is now offline", V_id(vp),
3887 if (V_offlineMessage(vp)[0])
3888 Log(" (%s)", V_offlineMessage(vp));
3891 FreeVolumeHeader(vp);
3892 #ifdef AFS_PTHREAD_ENV
3893 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3894 #else /* AFS_PTHREAD_ENV */
3895 LWP_NoYieldSignal(VPutVolume);
3896 #endif /* AFS_PTHREAD_ENV */
3900 #endif /* AFS_DEMAND_ATTACH_FS */
3902 /***************************************************/
3903 /* demand attach fs ref counting routines */
3904 /***************************************************/
3906 #ifdef AFS_DEMAND_ATTACH_FS
3907 /* the following two functions handle reference counting for
3908 * asynchronous operations on volume structs.
3910 * their purpose is to prevent a VDetachVolume or VShutdown
3911 * from free()ing the Volume struct during an async i/o op */
3913 /* register with the async volume op ref counter */
3914 /* VCreateReservation_r moved into inline code header because it
3915 * is now needed in vnode.c -- tkeiser 11/20/2007
3919 * decrement volume-package internal refcount.
3921 * @param vp volume object pointer
3923 * @internal volume package internal use only
3926 * @arg VOL_LOCK is held
3927 * @arg lightweight refcount held
3929 * @post volume waiters refcount is decremented; volume may
3930 * have been deallocated/shutdown/offlined/salvaged/
3931 * whatever during the process
3933 * @warning once you have tossed your last reference (you can acquire
3934 * lightweight refs recursively) it is NOT SAFE to reference
3935 * a volume object pointer ever again
3937 * @see VCreateReservation_r
3939 * @note DEMAND_ATTACH_FS only
3942 VCancelReservation_r(Volume * vp)
3944 assert(--vp->nWaiters >= 0);
3945 if (vp->nWaiters == 0) {
3947 if (!VCheckDetach(vp)) {
3954 /* check to see if we should free this volume now
3955 * return 1 if volume was freed, 0 otherwise */
3957 VCheckFree(Volume * vp)
3960 if ((vp->nUsers == 0) &&
3961 (vp->nWaiters == 0) &&
3962 !(V_attachFlags(vp) & (VOL_IN_HASH |
3966 ReallyFreeVolume(vp);
3971 #endif /* AFS_DEMAND_ATTACH_FS */
3974 /***************************************************/
3975 /* online volume operations routines */
3976 /***************************************************/
3978 #ifdef AFS_DEMAND_ATTACH_FS
3980 * register a volume operation on a given volume.
3982 * @param[in] vp volume object
3983 * @param[in] vopinfo volume operation info object
3985 * @pre VOL_LOCK is held
3987 * @post volume operation info object attached to volume object.
3988 * volume operation statistics updated.
3990 * @note by "attached" we mean a copy of the passed in object is made
3992 * @internal volume package internal use only
3995 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3997 FSSYNC_VolOp_info * info;
3999 /* attach a vol op info node to the volume struct */
4000 info = (FSSYNC_VolOp_info *) malloc(sizeof(FSSYNC_VolOp_info));
4001 assert(info != NULL);
4002 memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
4003 vp->pending_vol_op = info;
4006 vp->stats.last_vol_op = FT_ApproxTime();
4007 vp->stats.vol_ops++;
4008 IncUInt64(&VStats.vol_ops);
4014 * deregister the volume operation attached to this volume.
4016 * @param[in] vp volume object pointer
4018 * @pre VOL_LOCK is held
4020 * @post the volume operation info object is detached from the volume object
4022 * @internal volume package internal use only
4025 VDeregisterVolOp_r(Volume * vp)
4027 if (vp->pending_vol_op) {
4028 free(vp->pending_vol_op);
4029 vp->pending_vol_op = NULL;
4033 #endif /* AFS_DEMAND_ATTACH_FS */
4036 * determine whether it is safe to leave a volume online during
4037 * the volume operation described by the vopinfo object.
4039 * @param[in] vp volume object
4040 * @param[in] vopinfo volume operation info object
4042 * @return whether it is safe to leave volume online
4043 * @retval 0 it is NOT SAFE to leave the volume online
4044 * @retval 1 it is safe to leave the volume online during the operation
4047 * @arg VOL_LOCK is held
4048 * @arg disk header attached to vp (heavyweight ref on vp will guarantee
4049 * this condition is met)
4051 * @internal volume package internal use only
4054 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4056 return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
4057 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4058 (vopinfo->com.reason == V_READONLY ||
4059 (!VolumeWriteable(vp) &&
4060 (vopinfo->com.reason == V_CLONE ||
4061 vopinfo->com.reason == V_DUMP)))));
4065 * determine whether VBUSY should be set during this volume operation.
4067 * @param[in] vp volume object
4068 * @param[in] vopinfo volume operation info object
4070 * @return whether VBUSY should be set
4071 * @retval 0 VBUSY does NOT need to be set
4072 * @retval 1 VBUSY SHOULD be set
4074 * @pre VOL_LOCK is held
4076 * @internal volume package internal use only
4079 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4081 return ((vopinfo->com.command == FSYNC_VOL_OFF &&
4082 vopinfo->com.reason == FSYNC_SALVAGE) ||
4083 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4084 (vopinfo->com.reason == V_CLONE ||
4085 vopinfo->com.reason == V_DUMP)));
4089 /***************************************************/
4090 /* online salvager routines */
4091 /***************************************************/
4092 #if defined(AFS_DEMAND_ATTACH_FS)
4094 * check whether a salvage needs to be performed on this volume.
4096 * @param[in] vp pointer to volume object
4098 * @return status code
4099 * @retval 0 no salvage scheduled
4100 * @retval 1 a salvage has been scheduled with the salvageserver
4102 * @pre VOL_LOCK is held
4104 * @post if salvage request flag is set and nUsers and nWaiters are zero,
4105 * then a salvage will be requested
4107 * @note this is one of the event handlers called by VCancelReservation_r
4109 * @see VCancelReservation_r
4111 * @internal volume package internal use only.
4114 VCheckSalvage(register Volume * vp)
4117 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
4118 if (vp->nUsers || vp->nWaiters)
4120 if (vp->salvage.requested) {
4121 VScheduleSalvage_r(vp);
4124 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
4129 * request volume salvage.
4131 * @param[out] ec computed client error code
4132 * @param[in] vp volume object pointer
4133 * @param[in] reason reason code (passed to salvageserver via SALVSYNC)
4134 * @param[in] flags see flags note below
4137 * VOL_SALVAGE_INVALIDATE_HEADER causes volume header cache entry
4138 * to be invalidated.
4140 * @pre VOL_LOCK is held.
4142 * @post volume state is changed.
4143 * for fileserver, salvage will be requested once refcount reaches zero.
4145 * @return operation status code
4146 * @retval 0 volume salvage will occur
4147 * @retval 1 volume salvage could not be scheduled
4149 * @note DAFS fileserver only
4151 * @note this call does not synchronously schedule a volume salvage. rather,
4152 * it sets volume state so that when volume refcounts reach zero, a
4153 * volume salvage will occur. by "refcounts", we mean both nUsers and
4154 * nWaiters must be zero.
4156 * @internal volume package internal use only.
4159 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
4163 * for DAFS volume utilities, transition to error state
4164 * (at some point in the future, we should consider
4165 * making volser talk to salsrv)
4167 if (!VCanScheduleSalvage()) {
4168 VChangeState_r(vp, VOL_STATE_ERROR);
4173 if (programType != fileServer && !VCanUseFSSYNC()) {
4174 VChangeState_r(vp, VOL_STATE_ERROR);
4179 if (!vp->salvage.requested) {
4180 vp->salvage.requested = 1;
4181 vp->salvage.reason = reason;
4182 vp->stats.last_salvage = FT_ApproxTime();
4184 if (programType == fileServer && vp->header && VIsSalvager(V_inUse(vp))) {
4185 /* Right now we can't tell for sure if this indicates a
4186 * salvage is running, or if a running salvage crashed, so
4187 * we always ERROR the volume in case a salvage is running.
4188 * Once we get rid of the partition lock and instead lock
4189 * individual volume header files for salvages, we will
4190 * probably be able to tell if a salvage is running, and we
4191 * can do away with this behavior. */
4192 /* Note that we can avoid this check for non-fileserver programs,
4193 * since they must lock the partition in order to attach a volume.
4194 * Since the salvager also locks the partition to salvage, we
4195 * could not have reached this point for non-fileservers if this
4196 * volume was being salvaged; so we assume it is not. */
4197 Log("VRequestSalvage: volume %u appears to be salvaging, but we\n", vp->hashid);
4198 Log(" didn't request a salvage. Forcing it offline waiting for the\n");
4199 Log(" salvage to finish; if you are sure no salvage is running,\n");
4200 Log(" run a salvage manually.\n");
4202 /* make sure neither VScheduleSalvage_r nor
4203 * VUpdateSalvagePriority_r try to schedule another salvage */
4204 vp->salvage.requested = vp->salvage.scheduled = 0;
4206 /* these stats aren't correct, but doing this makes them
4207 * slightly closer to being correct */
4208 vp->stats.salvages++;
4209 vp->stats.last_salvage_req = FT_ApproxTime();
4210 IncUInt64(&VStats.salvages);
4212 VChangeState_r(vp, VOL_STATE_ERROR);
4216 } else if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
4217 VChangeState_r(vp, VOL_STATE_SALVAGING);
4220 Log("VRequestSalvage: volume %u online salvaged too many times; forced offline.\n", vp->hashid);
4222 /* make sure neither VScheduleSalvage_r nor
4223 * VUpdateSalvagePriority_r try to schedule another salvage */
4224 vp->salvage.requested = vp->salvage.scheduled = 0;
4226 VChangeState_r(vp, VOL_STATE_ERROR);
4230 if (flags & VOL_SALVAGE_INVALIDATE_HEADER) {
4231 /* Instead of ReleaseVolumeHeader, we do FreeVolumeHeader()
4232 so that the the next VAttachVolumeByVp_r() invocation
4233 of attach2() will pull in a cached header
4234 entry and fail, then load a fresh one from disk and attach
4237 FreeVolumeHeader(vp);
4244 * update salvageserver scheduling priority for a volume.
4246 * @param[in] vp pointer to volume object
4248 * @return operation status
4250 * @retval 1 request denied, or SALVSYNC communications failure
4252 * @pre VOL_LOCK is held.
4254 * @post in-core salvage priority counter is incremented. if at least
4255 * SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
4256 * last SALVSYNC_RAISEPRIO request, we contact the salvageserver
4257 * to update its priority queue. if no salvage is scheduled,
4258 * this function is a no-op.
4260 * @note DAFS fileserver only
4262 * @note this should be called whenever a VGetVolume fails due to a
4263 * pending salvage request
4265 * @todo should set exclusive state and drop glock around salvsync call
4267 * @internal volume package internal use only.
4270 VUpdateSalvagePriority_r(Volume * vp)
4274 #ifdef SALVSYNC_BUILD_CLIENT
4279 now = FT_ApproxTime();
4281 /* update the salvageserver priority queue occasionally so that
4282 * frequently requested volumes get moved to the head of the queue
4284 if ((vp->salvage.scheduled) &&
4285 (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
4286 code = SALVSYNC_SalvageVolume(vp->hashid,
4287 VPartitionPath(vp->partition),
4292 vp->stats.last_salvage_req = now;
4293 if (code != SYNC_OK) {
4297 #endif /* SALVSYNC_BUILD_CLIENT */
4302 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
4304 * schedule a salvage with the salvage server or fileserver.
4306 * @param[in] vp pointer to volume object
4308 * @return operation status
4309 * @retval 0 salvage scheduled successfully
4310 * @retval 1 salvage not scheduled, or SALVSYNC/FSSYNC com error
4313 * @arg VOL_LOCK is held.
4314 * @arg nUsers and nWaiters should be zero.
4316 * @post salvageserver or fileserver is sent a salvage request
4318 * @note If we are the fileserver, the request will be sent to the salvage
4319 * server over SALVSYNC. If we are not the fileserver, the request will be
4320 * sent to the fileserver over FSSYNC (FSYNC_VOL_FORCE_ERROR/FSYNC_SALVAGE).
4324 * @internal volume package internal use only.
4327 VScheduleSalvage_r(Volume * vp)
4331 VolState state_save;
4332 VThreadOptions_t * thread_opts;
4335 assert(VCanUseSALVSYNC() || VCanUseFSSYNC());
4337 if (vp->nWaiters || vp->nUsers) {
4341 /* prevent endless salvage,attach,salvage,attach,... loops */
4342 if (vp->stats.salvages >= SALVAGE_COUNT_MAX)
4346 * don't perform salvsync ops on certain threads
4348 thread_opts = pthread_getspecific(VThread_key);
4349 if (thread_opts == NULL) {
4350 thread_opts = &VThread_defaults;
4352 if (thread_opts->disallow_salvsync || vol_disallow_salvsync) {
4357 * XXX the scheduling process should really be done asynchronously
4358 * to avoid fssync deadlocks
4360 if (!vp->salvage.scheduled) {
4361 /* if we haven't previously scheduled a salvage, do so now
4363 * set the volume to an exclusive state and drop the lock
4364 * around the SALVSYNC call
4366 * note that we do NOT acquire a reservation here -- doing so
4367 * could result in unbounded recursion
4369 strlcpy(partName, VPartitionPath(vp->partition), sizeof(partName));
4370 state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
4373 #ifdef SALVSYNC_BUILD_CLIENT
4374 if (VCanUseSALVSYNC()) {
4375 /* can't use V_id() since there's no guarantee
4376 * we have the disk data header at this point */
4377 code = SALVSYNC_SalvageVolume(vp->hashid,
4384 #endif /* SALVSYNC_BUILD_CLIENT */
4385 #ifdef FSSYNC_BUILD_CLIENT
4386 if (VCanUseFSSYNC()) {
4388 * If we aren't the fileserver, tell the fileserver the volume
4389 * needs to be salvaged. We could directly tell the
4390 * salvageserver, but the fileserver keeps track of some stats
4391 * related to salvages, and handles some other salvage-related
4392 * complications for us.
4394 code = FSYNC_VolOp(vp->hashid, partName,
4395 FSYNC_VOL_FORCE_ERROR, FSYNC_SALVAGE, NULL);
4397 #endif /* FSSYNC_BUILD_CLIENT */
4400 VChangeState_r(vp, state_save);
4402 if (code == SYNC_OK) {
4403 vp->salvage.scheduled = 1;
4404 vp->stats.last_salvage_req = FT_ApproxTime();
4405 if (VCanUseSALVSYNC()) {
4406 /* don't record these stats for non-fileservers; let the
4407 * fileserver take care of these */
4408 vp->stats.salvages++;
4409 IncUInt64(&VStats.salvages);
4414 case SYNC_BAD_COMMAND:
4415 case SYNC_COM_ERROR:
4418 Log("VScheduleSalvage_r: Salvage request for volume %lu "
4419 "denied\n", afs_printable_uint32_lu(vp->hashid));
4422 Log("VScheduleSalvage_r: Salvage request for volume %lu "
4423 "received unknown protocol error %d\n",
4424 afs_printable_uint32_lu(vp->hashid), code);
4428 if (VCanUseFSSYNC()) {
4429 VChangeState_r(vp, VOL_STATE_ERROR);
4435 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
4437 #ifdef SALVSYNC_BUILD_CLIENT
4440 * connect to the salvageserver SYNC service.
4442 * @return operation status
4446 * @post connection to salvageserver SYNC service established
4448 * @see VConnectSALV_r
4449 * @see VDisconnectSALV
4450 * @see VReconnectSALV
4457 retVal = VConnectSALV_r();
4463 * connect to the salvageserver SYNC service.
4465 * @return operation status
4469 * @pre VOL_LOCK is held.
4471 * @post connection to salvageserver SYNC service established
4474 * @see VDisconnectSALV_r
4475 * @see VReconnectSALV_r
4476 * @see SALVSYNC_clientInit
4478 * @internal volume package internal use only.
4481 VConnectSALV_r(void)
4483 return SALVSYNC_clientInit();
4487 * disconnect from the salvageserver SYNC service.
4489 * @return operation status
4492 * @pre client should have a live connection to the salvageserver
4494 * @post connection to salvageserver SYNC service destroyed
4496 * @see VDisconnectSALV_r
4498 * @see VReconnectSALV
4501 VDisconnectSALV(void)
4504 VDisconnectSALV_r();
4510 * disconnect from the salvageserver SYNC service.
4512 * @return operation status
4516 * @arg VOL_LOCK is held.
4517 * @arg client should have a live connection to the salvageserver.
4519 * @post connection to salvageserver SYNC service destroyed
4521 * @see VDisconnectSALV
4522 * @see VConnectSALV_r
4523 * @see VReconnectSALV_r
4524 * @see SALVSYNC_clientFinis
4526 * @internal volume package internal use only.
4529 VDisconnectSALV_r(void)
4531 return SALVSYNC_clientFinis();
4535 * disconnect and then re-connect to the salvageserver SYNC service.
4537 * @return operation status
4541 * @pre client should have a live connection to the salvageserver
4543 * @post old connection is dropped, and a new one is established
4546 * @see VDisconnectSALV
4547 * @see VReconnectSALV_r
4550 VReconnectSALV(void)
4554 retVal = VReconnectSALV_r();
4560 * disconnect and then re-connect to the salvageserver SYNC service.
4562 * @return operation status
4567 * @arg VOL_LOCK is held.
4568 * @arg client should have a live connection to the salvageserver.
4570 * @post old connection is dropped, and a new one is established
4572 * @see VConnectSALV_r
4573 * @see VDisconnectSALV
4574 * @see VReconnectSALV
4575 * @see SALVSYNC_clientReconnect
4577 * @internal volume package internal use only.
4580 VReconnectSALV_r(void)
4582 return SALVSYNC_clientReconnect();
4584 #endif /* SALVSYNC_BUILD_CLIENT */
4585 #endif /* AFS_DEMAND_ATTACH_FS */
4588 /***************************************************/
4589 /* FSSYNC routines */
4590 /***************************************************/
4592 /* This must be called by any volume utility which needs to run while the
4593 file server is also running. This is separated from VInitVolumePackage2 so
4594 that a utility can fork--and each of the children can independently
4595 initialize communication with the file server */
4596 #ifdef FSSYNC_BUILD_CLIENT
4598 * connect to the fileserver SYNC service.
4600 * @return operation status
4605 * @arg VInit must equal 2.
4606 * @arg Program Type must not be fileserver or salvager.
4608 * @post connection to fileserver SYNC service established
4611 * @see VDisconnectFS
4612 * @see VChildProcReconnectFS
4619 retVal = VConnectFS_r();
4625 * connect to the fileserver SYNC service.
4627 * @return operation status
4632 * @arg VInit must equal 2.
4633 * @arg Program Type must not be fileserver or salvager.
4634 * @arg VOL_LOCK is held.
4636 * @post connection to fileserver SYNC service established
4639 * @see VDisconnectFS_r
4640 * @see VChildProcReconnectFS_r
4642 * @internal volume package internal use only.
4648 assert((VInit == 2) &&
4649 (programType != fileServer) &&
4650 (programType != salvager));
4651 rc = FSYNC_clientInit();
4658 * disconnect from the fileserver SYNC service.
4661 * @arg client should have a live connection to the fileserver.
4662 * @arg VOL_LOCK is held.
4663 * @arg Program Type must not be fileserver or salvager.
4665 * @post connection to fileserver SYNC service destroyed
4667 * @see VDisconnectFS
4669 * @see VChildProcReconnectFS_r
4671 * @internal volume package internal use only.
4674 VDisconnectFS_r(void)
4676 assert((programType != fileServer) &&
4677 (programType != salvager));
4678 FSYNC_clientFinis();
4683 * disconnect from the fileserver SYNC service.
4686 * @arg client should have a live connection to the fileserver.
4687 * @arg Program Type must not be fileserver or salvager.
4689 * @post connection to fileserver SYNC service destroyed
4691 * @see VDisconnectFS_r
4693 * @see VChildProcReconnectFS
4704 * connect to the fileserver SYNC service from a child process following a fork.
4706 * @return operation status
4711 * @arg VOL_LOCK is held.
4712 * @arg current FSYNC handle is shared with a parent process
4714 * @post current FSYNC handle is discarded and a new connection to the
4715 * fileserver SYNC service is established
4717 * @see VChildProcReconnectFS
4719 * @see VDisconnectFS_r
4721 * @internal volume package internal use only.
4724 VChildProcReconnectFS_r(void)
4726 return FSYNC_clientChildProcReconnect();
4730 * connect to the fileserver SYNC service from a child process following a fork.
4732 * @return operation status
4736 * @pre current FSYNC handle is shared with a parent process
4738 * @post current FSYNC handle is discarded and a new connection to the
4739 * fileserver SYNC service is established
4741 * @see VChildProcReconnectFS_r
4743 * @see VDisconnectFS
4746 VChildProcReconnectFS(void)
4750 ret = VChildProcReconnectFS_r();
4754 #endif /* FSSYNC_BUILD_CLIENT */
4757 /***************************************************/
4758 /* volume bitmap routines */
4759 /***************************************************/
4762 * For demand attach fs, flags parameter controls
4763 * locking behavior. If (flags & VOL_ALLOC_BITMAP_WAIT)
4764 * is set, then this function will create a reservation
4765 * and block on any other exclusive operations. Otherwise,
4766 * this function assumes the caller already has exclusive
4767 * access to vp, and we just change the volume state.
4770 VAllocBitmapEntry_r(Error * ec, Volume * vp,
4771 struct vnodeIndex *index, int flags)
4774 register byte *bp, *ep;
4775 #ifdef AFS_DEMAND_ATTACH_FS
4776 VolState state_save;
4777 #endif /* AFS_DEMAND_ATTACH_FS */
4781 /* This test is probably redundant */
4782 if (!VolumeWriteable(vp)) {
4783 *ec = (bit32) VREADONLY;
4787 #ifdef AFS_DEMAND_ATTACH_FS
4788 if (flags & VOL_ALLOC_BITMAP_WAIT) {
4789 VCreateReservation_r(vp);
4790 VWaitExclusiveState_r(vp);
4792 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
4793 #endif /* AFS_DEMAND_ATTACH_FS */
4796 if ((programType == fileServer) && !index->bitmap) {
4798 #ifndef AFS_DEMAND_ATTACH_FS
4799 /* demand attach fs uses the volume state to avoid races.
4800 * specialStatus field is not used at all */
4802 if (vp->specialStatus == VBUSY) {
4803 if (vp->goingOffline) { /* vos dump waiting for the volume to
4804 * go offline. We probably come here
4805 * from AddNewReadableResidency */
4808 while (vp->specialStatus == VBUSY) {
4809 #ifdef AFS_PTHREAD_ENV
4813 #else /* !AFS_PTHREAD_ENV */
4815 #endif /* !AFS_PTHREAD_ENV */
4819 #endif /* !AFS_DEMAND_ATTACH_FS */
4821 if (!index->bitmap) {
4822 #ifndef AFS_DEMAND_ATTACH_FS
4823 vp->specialStatus = VBUSY; /* Stop anyone else from using it. */
4824 #endif /* AFS_DEMAND_ATTACH_FS */
4825 for (i = 0; i < nVNODECLASSES; i++) {
4826 VGetBitmap_r(ec, vp, i);
4828 #ifdef AFS_DEMAND_ATTACH_FS
4829 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
4830 #else /* AFS_DEMAND_ATTACH_FS */
4831 DeleteVolumeFromHashTable(vp);
4832 vp->shuttingDown = 1; /* Let who has it free it. */
4833 vp->specialStatus = 0;
4834 #endif /* AFS_DEMAND_ATTACH_FS */
4839 #ifndef AFS_DEMAND_ATTACH_FS
4841 vp->specialStatus = 0; /* Allow others to have access. */
4842 #endif /* AFS_DEMAND_ATTACH_FS */
4845 #endif /* BITMAP_LATER */
4847 #ifdef AFS_DEMAND_ATTACH_FS
4849 #endif /* AFS_DEMAND_ATTACH_FS */
4850 bp = index->bitmap + index->bitmapOffset;
4851 ep = index->bitmap + index->bitmapSize;
4853 if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
4855 index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
4858 o = ffs(~*bp) - 1; /* ffs is documented in BSTRING(3) */
4860 ret = (VnodeId) ((bp - index->bitmap) * 8 + o);
4861 #ifdef AFS_DEMAND_ATTACH_FS
4863 #endif /* AFS_DEMAND_ATTACH_FS */
4866 bp += sizeof(bit32) /* i.e. 4 */ ;
4868 /* No bit map entry--must grow bitmap */
4870 realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
4873 bp += index->bitmapSize;
4874 memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
4875 index->bitmapOffset = index->bitmapSize;
4876 index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
4878 ret = index->bitmapOffset * 8;
4879 #ifdef AFS_DEMAND_ATTACH_FS
4881 #endif /* AFS_DEMAND_ATTACH_FS */
4884 #ifdef AFS_DEMAND_ATTACH_FS
4885 VChangeState_r(vp, state_save);
4886 if (flags & VOL_ALLOC_BITMAP_WAIT) {
4887 VCancelReservation_r(vp);
4889 #endif /* AFS_DEMAND_ATTACH_FS */
4894 VAllocBitmapEntry(Error * ec, Volume * vp, register struct vnodeIndex * index)
4898 retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
4904 VFreeBitMapEntry_r(Error * ec, register struct vnodeIndex *index,
4907 unsigned int offset;
4913 #endif /* BITMAP_LATER */
4914 offset = bitNumber >> 3;
4915 if (offset >= index->bitmapSize) {
4919 if (offset < index->bitmapOffset)
4920 index->bitmapOffset = offset & ~3; /* Truncate to nearest bit32 */
4921 *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
4925 VFreeBitMapEntry(Error * ec, register struct vnodeIndex *index,
4929 VFreeBitMapEntry_r(ec, index, bitNumber);
4933 /* this function will drop the glock internally.
4934 * for old pthread fileservers, this is safe thanks to vbusy.
4936 * for demand attach fs, caller must have already called
4937 * VCreateReservation_r and VWaitExclusiveState_r */
4939 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
4941 StreamHandle_t *file;
4944 struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
4945 struct vnodeIndex *vip = &vp->vnodeIndex[class];
4946 struct VnodeDiskObject *vnode;
4947 unsigned int unique = 0;
4951 #endif /* BITMAP_LATER */
4952 #ifdef AFS_DEMAND_ATTACH_FS
4953 VolState state_save;
4954 #endif /* AFS_DEMAND_ATTACH_FS */
4958 #ifdef AFS_DEMAND_ATTACH_FS
4959 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
4960 #endif /* AFS_DEMAND_ATTACH_FS */
4963 fdP = IH_OPEN(vip->handle);
4964 assert(fdP != NULL);
4965 file = FDH_FDOPEN(fdP, "r");
4966 assert(file != NULL);
4967 vnode = (VnodeDiskObject *) malloc(vcp->diskSize);
4968 assert(vnode != NULL);
4969 size = OS_SIZE(fdP->fd_fd);
4971 nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
4973 vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4; /* The 10 is a little extra so
4974 * a few files can be created in this volume,
4975 * the whole thing is rounded up to nearest 4
4976 * bytes, because the bit map allocator likes
4979 BitMap = (byte *) calloc(1, vip->bitmapSize);
4980 assert(BitMap != NULL);
4981 #else /* BITMAP_LATER */
4982 vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
4983 assert(vip->bitmap != NULL);
4984 vip->bitmapOffset = 0;
4985 #endif /* BITMAP_LATER */
4986 if (STREAM_SEEK(file, vcp->diskSize, 0) != -1) {
4988 for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
4989 if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
4991 if (vnode->type != vNull) {
4992 if (vnode->vnodeMagic != vcp->magic) {
4993 Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
4998 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
4999 #else /* BITMAP_LATER */
5000 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
5001 #endif /* BITMAP_LATER */
5002 if (unique <= vnode->uniquifier)
5003 unique = vnode->uniquifier + 1;
5005 #ifndef AFS_PTHREAD_ENV
5006 if ((bitNumber & 0x00ff) == 0x0ff) { /* every 256 iterations */
5009 #endif /* !AFS_PTHREAD_ENV */
5012 if (vp->nextVnodeUnique < unique) {
5013 Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
5016 /* Paranoia, partly justified--I think fclose after fdopen
5017 * doesn't seem to close fd. In any event, the documentation
5018 * doesn't specify, so it's safer to close it twice.
5026 /* There may have been a racing condition with some other thread, both
5027 * creating the bitmaps for this volume. If the other thread was faster
5028 * the pointer to bitmap should already be filled and we can free ours.
5030 if (vip->bitmap == NULL) {
5031 vip->bitmap = BitMap;
5032 vip->bitmapOffset = 0;
5034 free((byte *) BitMap);
5035 #endif /* BITMAP_LATER */
5036 #ifdef AFS_DEMAND_ATTACH_FS
5037 VChangeState_r(vp, state_save);
5038 #endif /* AFS_DEMAND_ATTACH_FS */
5042 /***************************************************/
5043 /* Volume Path and Volume Number utility routines */
5044 /***************************************************/
5047 * find the first occurrence of a volume header file and return the path.
5049 * @param[out] ec outbound error code
5050 * @param[in] volumeId volume id to find
5051 * @param[out] partitionp pointer to disk partition path string
5052 * @param[out] namep pointer to volume header file name string
5054 * @post path to first occurrence of volume header is returned in partitionp
5055 * and namep, or ec is set accordingly.
5057 * @warning this function is NOT re-entrant -- partitionp and namep point to
5058 * static data segments
5060 * @note if a volume utility inadvertently leaves behind a stale volume header
5061 * on a vice partition, it is possible for callers to get the wrong one,
5062 * depending on the order of the disk partition linked list.
5066 VGetVolumePath(Error * ec, VolId volumeId, char **partitionp, char **namep)
5068 static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
5069 char path[VMAXPATHLEN];
5071 struct DiskPartition64 *dp;
5075 (void)afs_snprintf(&name[1], (sizeof name) - 1, VFORMAT, afs_printable_uint32_lu(volumeId));
5076 for (dp = DiskPartitionList; dp; dp = dp->next) {
5077 struct afs_stat status;
5078 strcpy(path, VPartitionPath(dp));
5080 if (afs_stat(path, &status) == 0) {
5081 strcpy(partition, dp->name);
5088 *partitionp = *namep = NULL;
5090 *partitionp = partition;
5096 * extract a volume number from a volume header filename string.
5098 * @param[in] name volume header filename string
5100 * @return volume number
5102 * @note the string must be of the form VFORMAT. the only permissible
5103 * deviation is a leading '/' character.
5108 VolumeNumber(char *name)
5112 return atoi(name + 1);
5116 * compute the volume header filename.
5118 * @param[in] volumeId
5120 * @return volume header filename
5122 * @post volume header filename string is constructed
5124 * @warning this function is NOT re-entrant -- the returned string is
5125 * stored in a static char array. see VolumeExternalName_r
5126 * for a re-entrant equivalent.
5128 * @see VolumeExternalName_r
5130 * @deprecated due to the above re-entrancy warning, this interface should
5131 * be considered deprecated. Please use VolumeExternalName_r
5135 VolumeExternalName(VolumeId volumeId)
5137 static char name[VMAXPATHLEN];
5138 (void)afs_snprintf(name, sizeof name, VFORMAT, afs_printable_uint32_lu(volumeId));
5143 * compute the volume header filename.
5145 * @param[in] volumeId
5146 * @param[inout] name array in which to store filename
5147 * @param[in] len length of name array
5149 * @return result code from afs_snprintf
5151 * @see VolumeExternalName
5154 * @note re-entrant equivalent of VolumeExternalName
5157 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
5159 return afs_snprintf(name, len, VFORMAT, afs_printable_uint32_lu(volumeId));
5163 /***************************************************/
5164 /* Volume Usage Statistics routines */
5165 /***************************************************/
5167 #if OPENAFS_VOL_STATS
5168 #define OneDay (86400) /* 24 hours' worth of seconds */
5170 #define OneDay (24*60*60) /* 24 hours */
5171 #endif /* OPENAFS_VOL_STATS */
5174 Midnight(time_t t) {
5175 struct tm local, *l;
5178 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
5179 l = localtime_r(&t, &local);
5185 /* the following is strictly speaking problematic on the
5186 switching day to daylight saving time, after the switch,
5187 as tm_isdst does not match. Similarly, on the looong day when
5188 switching back the OneDay check will not do what naively expected!
5189 The effects are minor, though, and more a matter of interpreting
5191 #ifndef AFS_PTHREAD_ENV
5194 local.tm_hour = local.tm_min=local.tm_sec = 0;
5195 midnight = mktime(&local);
5196 if (midnight != (time_t) -1) return(midnight);
5198 return( (t/OneDay)*OneDay );
5202 /*------------------------------------------------------------------------
5203 * [export] VAdjustVolumeStatistics
5206 * If we've passed midnight, we need to update all the day use
5207 * statistics as well as zeroing the detailed volume statistics
5208 * (if we are implementing them).
5211 * vp : Pointer to the volume structure describing the lucky
5212 * volume being considered for update.
5218 * Nothing interesting.
5222 *------------------------------------------------------------------------*/
5225 VAdjustVolumeStatistics_r(register Volume * vp)
5227 unsigned int now = FT_ApproxTime();
5229 if (now - V_dayUseDate(vp) > OneDay) {
5230 register int ndays, i;
5232 ndays = (now - V_dayUseDate(vp)) / OneDay;
5233 for (i = 6; i > ndays - 1; i--)
5234 V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
5235 for (i = 0; i < ndays - 1 && i < 7; i++)
5236 V_weekUse(vp)[i] = 0;
5238 V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
5240 V_dayUseDate(vp) = Midnight(now);
5242 #if OPENAFS_VOL_STATS
5244 * All we need to do is bzero the entire VOL_STATS_BYTES of
5245 * the detailed volume statistics area.
5247 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
5248 #endif /* OPENAFS_VOL_STATS */
5251 /*It's been more than a day of collection */
5253 * Always return happily.
5256 } /*VAdjustVolumeStatistics */
5259 VAdjustVolumeStatistics(register Volume * vp)
5263 retVal = VAdjustVolumeStatistics_r(vp);
5269 VBumpVolumeUsage_r(register Volume * vp)
5271 unsigned int now = FT_ApproxTime();
5272 V_accessDate(vp) = now;
5273 if (now - V_dayUseDate(vp) > OneDay)
5274 VAdjustVolumeStatistics_r(vp);
5276 * Save the volume header image to disk after every 128 bumps to dayUse.
5278 if ((V_dayUse(vp)++ & 127) == 0) {
5280 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
5285 VBumpVolumeUsage(register Volume * vp)
5288 VBumpVolumeUsage_r(vp);
5293 VSetDiskUsage_r(void)
5295 #ifndef AFS_DEMAND_ATTACH_FS
5296 static int FifteenMinuteCounter = 0;
5300 /* NOTE: Don't attempt to access the partitions list until the
5301 * initialization level indicates that all volumes are attached,
5302 * which implies that all partitions are initialized. */
5303 #ifdef AFS_PTHREAD_ENV
5305 #else /* AFS_PTHREAD_ENV */
5307 #endif /* AFS_PTHREAD_ENV */
5310 VResetDiskUsage_r();
5312 #ifndef AFS_DEMAND_ATTACH_FS
5313 if (++FifteenMinuteCounter == 3) {
5314 FifteenMinuteCounter = 0;
5317 #endif /* !AFS_DEMAND_ATTACH_FS */
5329 /***************************************************/
5330 /* Volume Update List routines */
5331 /***************************************************/
5333 /* The number of minutes that a volume hasn't been updated before the
5334 * "Dont salvage" flag in the volume header will be turned on */
5335 #define SALVAGE_INTERVAL (10*60)
5340 * volume update list functionality has been moved into the VLRU
5341 * the DONT_SALVAGE flag is now set during VLRU demotion
5344 #ifndef AFS_DEMAND_ATTACH_FS
5345 static VolumeId *UpdateList = NULL; /* Pointer to array of Volume ID's */
5346 static int nUpdatedVolumes = 0; /* Updated with entry in UpdateList, salvage after crash flag on */
5347 static int updateSize = 0; /* number of entries possible */
5348 #define UPDATE_LIST_SIZE 128 /* initial size increment (must be a power of 2!) */
5349 #endif /* !AFS_DEMAND_ATTACH_FS */
5352 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
5355 vp->updateTime = FT_ApproxTime();
5356 if (V_dontSalvage(vp) == 0)
5358 V_dontSalvage(vp) = 0;
5359 VSyncVolume_r(ec, vp, 0);
5360 #ifdef AFS_DEMAND_ATTACH_FS
5361 V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
5362 #else /* !AFS_DEMAND_ATTACH_FS */
5365 if (UpdateList == NULL) {
5366 updateSize = UPDATE_LIST_SIZE;
5367 UpdateList = (VolumeId *) malloc(sizeof(VolumeId) * updateSize);
5369 if (nUpdatedVolumes == updateSize) {
5371 if (updateSize > 524288) {
5372 Log("warning: there is likely a bug in the volume update scanner\n");
5376 (VolumeId *) realloc(UpdateList,
5377 sizeof(VolumeId) * updateSize);
5380 assert(UpdateList != NULL);
5381 UpdateList[nUpdatedVolumes++] = V_id(vp);
5382 #endif /* !AFS_DEMAND_ATTACH_FS */
5385 #ifndef AFS_DEMAND_ATTACH_FS
5387 VScanUpdateList(void)
5389 register int i, gap;
5390 register Volume *vp;
5392 afs_uint32 now = FT_ApproxTime();
5393 /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
5394 for (i = gap = 0; i < nUpdatedVolumes; i++) {
5396 UpdateList[i - gap] = UpdateList[i];
5398 /* XXX this routine needlessly messes up the Volume LRU by
5399 * breaking the LRU temporal-locality assumptions.....
5400 * we should use a special volume header allocator here */
5401 vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
5404 } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
5405 V_dontSalvage(vp) = DONT_SALVAGE;
5406 VUpdateVolume_r(&error, vp, 0); /* No need to fsync--not critical */
5414 #ifndef AFS_PTHREAD_ENV
5416 #endif /* !AFS_PTHREAD_ENV */
5418 nUpdatedVolumes -= gap;
5420 #endif /* !AFS_DEMAND_ATTACH_FS */
5423 /***************************************************/
5424 /* Volume LRU routines */
5425 /***************************************************/
5430 * with demand attach fs, we attempt to soft detach(1)
5431 * volumes which have not been accessed in a long time
5432 * in order to speed up fileserver shutdown
5434 * (1) by soft detach we mean a process very similar
5435 * to VOffline, except the final state of the
5436 * Volume will be VOL_STATE_PREATTACHED, instead
5437 * of the usual VOL_STATE_UNATTACHED
5439 #ifdef AFS_DEMAND_ATTACH_FS
5441 /* implementation is reminiscent of a generational GC
5443 * queue 0 is newly attached volumes. this queue is
5444 * sorted by attach timestamp
5446 * queue 1 is volumes that have been around a bit
5447 * longer than queue 0. this queue is sorted by
5450 * queue 2 is volumes tha have been around the longest.
5451 * this queue is unsorted
5453 * queue 3 is volumes that have been marked as
5454 * candidates for soft detachment. this queue is
5457 #define VLRU_GENERATIONS 3 /**< number of generations in VLRU */
5458 #define VLRU_QUEUES 5 /**< total number of VLRU queues */
5461 * definition of a VLRU queue.
5464 volatile struct rx_queue q;
5471 * main VLRU data structure.
5474 struct VLRU_q q[VLRU_QUEUES]; /**< VLRU queues */
5477 /** time interval (in seconds) between promotion passes for
5478 * each young generation queue. */
5479 afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
5481 /** time interval (in seconds) between soft detach candidate
5482 * scans for each generation queue.
5484 * scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
5485 * we perform a soft detach pass. */
5486 afs_uint32 scan_interval[VLRU_GENERATIONS+1];
5488 /* scheduler state */
5489 int next_idx; /**< next queue to receive attention */
5490 afs_uint32 last_promotion[VLRU_GENERATIONS-1]; /**< timestamp of last promotion scan */
5491 afs_uint32 last_scan[VLRU_GENERATIONS+1]; /**< timestamp of last detach scan */
5493 int scanner_state; /**< state of scanner thread */
5494 pthread_cond_t cv; /**< state transition CV */
5497 /** global VLRU state */
5498 static struct VLRU volume_LRU;
5501 * defined states for VLRU scanner thread.
5504 VLRU_SCANNER_STATE_OFFLINE = 0, /**< vlru scanner thread is offline */
5505 VLRU_SCANNER_STATE_ONLINE = 1, /**< vlru scanner thread is online */
5506 VLRU_SCANNER_STATE_SHUTTING_DOWN = 2, /**< vlru scanner thread is shutting down */
5507 VLRU_SCANNER_STATE_PAUSING = 3, /**< vlru scanner thread is getting ready to pause */
5508 VLRU_SCANNER_STATE_PAUSED = 4 /**< vlru scanner thread is paused */
5509 } vlru_thread_state_t;
5511 /* vlru disk data header stuff */
5512 #define VLRU_DISK_MAGIC 0x7a8b9cad /**< vlru disk entry magic number */
5513 #define VLRU_DISK_VERSION 1 /**< vlru disk entry version number */
5515 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
5516 #define VLRU_DUMP_EXPIRATION_TIME (60*60*24*7) /* expire vlru data after 1 week */
5519 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
5520 * soft detachment. */
5521 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
5523 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
5524 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
5526 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
5527 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
5529 /** VLRU control flag. non-zero value implies VLRU subsystem is activated. */
5530 static afs_uint32 VLRU_enabled = 1;
5532 /* queue synchronization routines */
5533 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
5534 static void VLRU_EndExclusive_r(struct VLRU_q * q);
5535 static void VLRU_Wait_r(struct VLRU_q * q);
5538 * set VLRU subsystem tunable parameters.
5540 * @param[in] option tunable option to modify
5541 * @param[in] val new value for tunable parameter
5543 * @pre @c VInitVolumePackage2 has not yet been called.
5545 * @post tunable parameter is modified
5549 * @note valid option parameters are:
5550 * @arg @c VLRU_SET_THRESH
5551 * set the period of inactivity after which
5552 * volumes are eligible for soft detachment
5553 * @arg @c VLRU_SET_INTERVAL
5554 * set the time interval between calls
5555 * to the volume LRU "garbage collector"
5556 * @arg @c VLRU_SET_MAX
5557 * set the max number of volumes to deallocate
5561 VLRU_SetOptions(int option, afs_uint32 val)
5563 if (option == VLRU_SET_THRESH) {
5564 VLRU_offline_thresh = val;
5565 } else if (option == VLRU_SET_INTERVAL) {
5566 VLRU_offline_interval = val;
5567 } else if (option == VLRU_SET_MAX) {
5568 VLRU_offline_max = val;
5569 } else if (option == VLRU_SET_ENABLED) {
5572 VLRU_ComputeConstants();
5576 * compute VLRU internal timing parameters.
5578 * @post VLRU scanner thread internal timing parameters are computed
5580 * @note computes internal timing parameters based upon user-modifiable
5581 * tunable parameters.
5585 * @internal volume package internal use only.
5588 VLRU_ComputeConstants(void)
5590 afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
5592 /* compute the candidate scan interval */
5593 volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
5595 /* compute the promotion intervals */
5596 volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
5597 volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
5600 /* compute the gen 0 scan interval */
5601 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
5603 /* compute the gen 0 scan interval */
5604 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
5609 * initialize VLRU subsystem.
5611 * @pre this function has not yet been called
5613 * @post VLRU subsystem is initialized and VLRU scanner thread is starting
5617 * @internal volume package internal use only.
5623 pthread_attr_t attrs;
5626 if (!VLRU_enabled) {
5627 Log("VLRU: disabled\n");
5631 /* initialize each of the VLRU queues */
5632 for (i = 0; i < VLRU_QUEUES; i++) {
5633 queue_Init(&volume_LRU.q[i]);
5634 volume_LRU.q[i].len = 0;
5635 volume_LRU.q[i].busy = 0;
5636 assert(pthread_cond_init(&volume_LRU.q[i].cv, NULL) == 0);
5639 /* setup the timing constants */
5640 VLRU_ComputeConstants();
5642 /* XXX put inside LogLevel check? */
5643 Log("VLRU: starting scanner with the following configuration parameters:\n");
5644 Log("VLRU: offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
5645 Log("VLRU: running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
5646 Log("VLRU: taking up to %d volumes offline per pass\n", VLRU_offline_max);
5647 Log("VLRU: scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
5648 Log("VLRU: scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
5649 Log("VLRU: scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
5651 /* start up the VLRU scanner */
5652 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
5653 if (programType == fileServer) {
5654 assert(pthread_cond_init(&volume_LRU.cv, NULL) == 0);
5655 assert(pthread_attr_init(&attrs) == 0);
5656 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
5657 assert(pthread_create(&tid, &attrs, &VLRU_ScannerThread, NULL) == 0);
5662 * initialize the VLRU-related fields of a newly allocated volume object.
5664 * @param[in] vp pointer to volume object
5667 * @arg @c VOL_LOCK is held.
5668 * @arg volume object is not on a VLRU queue.
5670 * @post VLRU fields are initialized to indicate that volume object is not
5671 * currently registered with the VLRU subsystem
5675 * @internal volume package interal use only.
5678 VLRU_Init_Node_r(Volume * vp)
5683 assert(queue_IsNotOnQueue(&vp->vlru));
5684 vp->vlru.idx = VLRU_QUEUE_INVALID;
5688 * add a volume object to a VLRU queue.
5690 * @param[in] vp pointer to volume object
5693 * @arg @c VOL_LOCK is held.
5694 * @arg caller MUST hold a lightweight ref on @p vp.
5695 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
5697 * @post the volume object is added to the appropriate VLRU queue
5699 * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
5700 * then the volume is added to that queue. Otherwise, the value
5701 * @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
5702 * volume is added to the NEW generation queue.
5704 * @note @c VOL_LOCK may be dropped internally
5706 * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
5707 * during the add operation, and is restored to the previous
5708 * state prior to return.
5712 * @internal volume package internal use only.
5715 VLRU_Add_r(Volume * vp)
5718 VolState state_save;
5723 if (queue_IsOnQueue(&vp->vlru))
5726 state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
5729 if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
5730 idx = VLRU_QUEUE_NEW;
5733 VLRU_Wait_r(&volume_LRU.q[idx]);
5735 /* repeat check since VLRU_Wait_r may have dropped
5737 if (queue_IsNotOnQueue(&vp->vlru)) {
5739 queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
5740 volume_LRU.q[idx].len++;
5741 V_attachFlags(vp) |= VOL_ON_VLRU;
5742 vp->stats.last_promote = FT_ApproxTime();
5745 VChangeState_r(vp, state_save);
5749 * delete a volume object from a VLRU queue.
5751 * @param[in] vp pointer to volume object
5754 * @arg @c VOL_LOCK is held.
5755 * @arg caller MUST hold a lightweight ref on @p vp.
5756 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
5758 * @post volume object is removed from the VLRU queue
5760 * @note @c VOL_LOCK may be dropped internally
5764 * @todo We should probably set volume state to something exlcusive
5765 * (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
5767 * @internal volume package internal use only.
5770 VLRU_Delete_r(Volume * vp)
5777 if (queue_IsNotOnQueue(&vp->vlru))
5783 if (idx == VLRU_QUEUE_INVALID)
5785 VLRU_Wait_r(&volume_LRU.q[idx]);
5786 } while (idx != vp->vlru.idx);
5788 /* now remove from the VLRU and update
5789 * the appropriate counter */
5790 queue_Remove(&vp->vlru);
5791 volume_LRU.q[idx].len--;
5792 vp->vlru.idx = VLRU_QUEUE_INVALID;
5793 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
5797 * tell the VLRU subsystem that a volume was just accessed.
5799 * @param[in] vp pointer to volume object
5802 * @arg @c VOL_LOCK is held
5803 * @arg caller MUST hold a lightweight ref on @p vp
5804 * @arg caller MUST NOT hold exclusive ownership of any VLRU queue
5806 * @post volume VLRU access statistics are updated. If the volume was on
5807 * the VLRU soft detach candidate queue, it is moved to the NEW
5810 * @note @c VOL_LOCK may be dropped internally
5814 * @internal volume package internal use only.
5817 VLRU_UpdateAccess_r(Volume * vp)
5819 Volume * rvp = NULL;
5824 if (queue_IsNotOnQueue(&vp->vlru))
5827 assert(V_attachFlags(vp) & VOL_ON_VLRU);
5829 /* update the access timestamp */
5830 vp->stats.last_get = FT_ApproxTime();
5833 * if the volume is on the soft detach candidate
5834 * list, we need to safely move it back to a
5835 * regular generation. this has to be done
5836 * carefully so we don't race against the scanner
5840 /* if this volume is on the soft detach candidate queue,
5841 * then grab exclusive access to the necessary queues */
5842 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
5844 VCreateReservation_r(rvp);
5846 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
5847 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
5848 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5849 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5852 /* make sure multiple threads don't race to update */
5853 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
5854 VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
5858 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5859 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
5860 VCancelReservation_r(rvp);
5865 * switch a volume between two VLRU queues.
5867 * @param[in] vp pointer to volume object
5868 * @param[in] new_idx index of VLRU queue onto which the volume will be moved
5869 * @param[in] append controls whether the volume will be appended or
5870 * prepended to the queue. A nonzero value means it will
5871 * be appended; zero means it will be prepended.
5873 * @pre The new (and old, if applicable) queue(s) must either be owned
5874 * exclusively by the calling thread for asynchronous manipulation,
5875 * or the queue(s) must be quiescent and VOL_LOCK must be held.
5876 * Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
5877 * for further details of the queue asynchronous processing mechanism.
5879 * @post If the volume object was already on a VLRU queue, it is
5880 * removed from the queue. Depending on the value of the append
5881 * parameter, the volume object is either appended or prepended
5882 * to the VLRU queue referenced by the new_idx parameter.
5886 * @see VLRU_BeginExclusive_r
5887 * @see VLRU_EndExclusive_r
5890 * @internal volume package internal use only.
5893 VLRU_SwitchQueues(Volume * vp, int new_idx, int append)
5895 if (queue_IsNotOnQueue(&vp->vlru))
5898 queue_Remove(&vp->vlru);
5899 volume_LRU.q[vp->vlru.idx].len--;
5901 /* put the volume back on the correct generational queue */
5903 queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
5905 queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
5908 volume_LRU.q[new_idx].len++;
5909 vp->vlru.idx = new_idx;
5913 * VLRU background thread.
5915 * The VLRU Scanner Thread is responsible for periodically scanning through
5916 * each VLRU queue looking for volumes which should be moved to another
5917 * queue, or soft detached.
5919 * @param[in] args unused thread arguments parameter
5921 * @return unused thread return value
5922 * @retval NULL always
5924 * @internal volume package internal use only.
5927 VLRU_ScannerThread(void * args)
5929 afs_uint32 now, min_delay, delay;
5930 int i, min_idx, min_op, overdue, state;
5932 /* set t=0 for promotion cycle to be
5933 * fileserver startup */
5934 now = FT_ApproxTime();
5935 for (i=0; i < VLRU_GENERATIONS-1; i++) {
5936 volume_LRU.last_promotion[i] = now;
5939 /* don't start the scanner until VLRU_offline_thresh
5940 * plus a small delay for VInitVolumePackage2 to finish
5943 sleep(VLRU_offline_thresh + 60);
5945 /* set t=0 for scan cycle to be now */
5946 now = FT_ApproxTime();
5947 for (i=0; i < VLRU_GENERATIONS+1; i++) {
5948 volume_LRU.last_scan[i] = now;
5952 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
5953 volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
5956 while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
5957 /* check to see if we've been asked to pause */
5958 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
5959 volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
5960 assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
5962 VOL_CV_WAIT(&volume_LRU.cv);
5963 } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
5966 /* scheduling can happen outside the glock */
5969 /* figure out what is next on the schedule */
5971 /* figure out a potential schedule for the new generation first */
5973 min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
5976 if (min_delay > volume_LRU.scan_interval[0]) {
5977 /* unsigned overflow -- we're overdue to run this scan */
5982 /* if we're not overdue for gen 0, figure out schedule for candidate gen */
5984 i = VLRU_QUEUE_CANDIDATE;
5985 delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
5986 if (delay < min_delay) {
5990 if (delay > volume_LRU.scan_interval[i]) {
5991 /* unsigned overflow -- we're overdue to run this scan */
5998 /* if we're still not overdue for something, figure out schedules for promotions */
5999 for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
6000 delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
6001 if (delay < min_delay) {
6006 if (delay > volume_LRU.promotion_interval[i]) {
6007 /* unsigned overflow -- we're overdue to run this promotion */
6016 /* sleep as needed */
6021 /* do whatever is next */
6024 VLRU_Promote_r(min_idx);
6025 VLRU_Demote_r(min_idx+1);
6027 VLRU_Scan_r(min_idx);
6029 now = FT_ApproxTime();
6032 Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
6034 /* signal that scanner is down */
6035 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
6036 assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
6042 * promote volumes from one VLRU generation to the next.
6044 * This routine scans a VLRU generation looking for volumes which are
6045 * eligible to be promoted to the next generation. All volumes which
6046 * meet the eligibility requirement are promoted.
6048 * Promotion eligibility is based upon meeting both of the following
6051 * @arg The volume has been accessed since the last promotion:
6052 * @c (vp->stats.last_get >= vp->stats.last_promote)
6053 * @arg The last promotion occurred at least
6054 * @c volume_LRU.promotion_interval[idx] seconds ago
6056 * As a performance optimization, promotions are "globbed". In other
6057 * words, we promote arbitrarily large contiguous sublists of elements
6060 * @param[in] idx VLRU queue index to scan
6064 * @internal VLRU internal use only.
6067 VLRU_Promote_r(int idx)
6069 int len, chaining, promote;
6070 afs_uint32 now, thresh;
6071 struct rx_queue *qp, *nqp;
6072 Volume * vp, *start = NULL, *end = NULL;
6074 /* get exclusive access to two chains, and drop the glock */
6075 VLRU_Wait_r(&volume_LRU.q[idx]);
6076 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
6077 VLRU_Wait_r(&volume_LRU.q[idx+1]);
6078 VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
6081 thresh = volume_LRU.promotion_interval[idx];
6082 now = FT_ApproxTime();
6085 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
6086 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6087 promote = (((vp->stats.last_promote + thresh) <= now) &&
6088 (vp->stats.last_get >= vp->stats.last_promote));
6096 /* promote and prepend chain */
6097 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
6111 /* promote and prepend */
6112 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
6116 volume_LRU.q[idx].len -= len;
6117 volume_LRU.q[idx+1].len += len;
6120 /* release exclusive access to the two chains */
6122 volume_LRU.last_promotion[idx] = now;
6123 VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
6124 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
6127 /* run the demotions */
6129 VLRU_Demote_r(int idx)
6132 int len, chaining, demote;
6133 afs_uint32 now, thresh;
6134 struct rx_queue *qp, *nqp;
6135 Volume * vp, *start = NULL, *end = NULL;
6136 Volume ** salv_flag_vec = NULL;
6137 int salv_vec_offset = 0;
6139 assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
6141 /* get exclusive access to two chains, and drop the glock */
6142 VLRU_Wait_r(&volume_LRU.q[idx-1]);
6143 VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
6144 VLRU_Wait_r(&volume_LRU.q[idx]);
6145 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
6148 /* no big deal if this allocation fails */
6149 if (volume_LRU.q[idx].len) {
6150 salv_flag_vec = (Volume **) malloc(volume_LRU.q[idx].len * sizeof(Volume *));
6153 now = FT_ApproxTime();
6154 thresh = volume_LRU.promotion_interval[idx-1];
6157 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
6158 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6159 demote = (((vp->stats.last_promote + thresh) <= now) &&
6160 (vp->stats.last_get < (now - thresh)));
6162 /* we now do volume update list DONT_SALVAGE flag setting during
6163 * demotion passes */
6164 if (salv_flag_vec &&
6165 !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
6167 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
6168 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
6169 salv_flag_vec[salv_vec_offset++] = vp;
6170 VCreateReservation_r(vp);
6179 /* demote and append chain */
6180 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
6194 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
6198 volume_LRU.q[idx].len -= len;
6199 volume_LRU.q[idx-1].len += len;
6202 /* release exclusive access to the two chains */
6204 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
6205 VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
6207 /* now go back and set the DONT_SALVAGE flags as appropriate */
6208 if (salv_flag_vec) {
6210 for (i = 0; i < salv_vec_offset; i++) {
6211 vp = salv_flag_vec[i];
6212 if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
6213 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
6214 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
6217 V_attachFlags(vp) |= VOL_HDR_DONTSALV;
6218 V_dontSalvage(vp) = DONT_SALVAGE;
6219 VUpdateVolume_r(&ec, vp, 0);
6223 VCancelReservation_r(vp);
6225 free(salv_flag_vec);
6229 /* run a pass of the VLRU GC scanner */
6231 VLRU_Scan_r(int idx)
6233 afs_uint32 now, thresh;
6234 struct rx_queue *qp, *nqp;
6238 assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
6240 /* gain exclusive access to the idx VLRU */
6241 VLRU_Wait_r(&volume_LRU.q[idx]);
6242 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
6244 if (idx != VLRU_QUEUE_CANDIDATE) {
6245 /* gain exclusive access to the candidate VLRU */
6246 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6247 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6250 now = FT_ApproxTime();
6251 thresh = now - VLRU_offline_thresh;
6253 /* perform candidate selection and soft detaching */
6254 if (idx == VLRU_QUEUE_CANDIDATE) {
6255 /* soft detach some volumes from the candidate pool */
6259 for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
6260 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6261 if (i >= VLRU_offline_max) {
6264 /* check timestamp to see if it's a candidate for soft detaching */
6265 if (vp->stats.last_get <= thresh) {
6267 if (VCheckSoftDetach(vp, thresh))
6273 /* scan for volumes to become soft detach candidates */
6274 for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
6275 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6277 /* check timestamp to see if it's a candidate for soft detaching */
6278 if (vp->stats.last_get <= thresh) {
6279 VCheckSoftDetachCandidate(vp, thresh);
6282 if (!(i&0x7f)) { /* lock coarsening optimization */
6290 /* relinquish exclusive access to the VLRU chains */
6294 volume_LRU.last_scan[idx] = now;
6295 if (idx != VLRU_QUEUE_CANDIDATE) {
6296 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6298 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
6301 /* check whether volume is safe to soft detach
6302 * caller MUST NOT hold a ref count on vp */
6304 VCheckSoftDetach(Volume * vp, afs_uint32 thresh)
6308 if (vp->nUsers || vp->nWaiters)
6311 if (vp->stats.last_get <= thresh) {
6312 ret = VSoftDetachVolume_r(vp, thresh);
6318 /* check whether volume should be made a
6319 * soft detach candidate */
6321 VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh)
6324 if (vp->nUsers || vp->nWaiters)
6329 assert(idx == VLRU_QUEUE_NEW);
6331 if (vp->stats.last_get <= thresh) {
6332 /* move to candidate pool */
6333 queue_Remove(&vp->vlru);
6334 volume_LRU.q[VLRU_QUEUE_NEW].len--;
6335 queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
6336 vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
6337 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
6345 /* begin exclusive access on VLRU */
6347 VLRU_BeginExclusive_r(struct VLRU_q * q)
6349 assert(q->busy == 0);
6353 /* end exclusive access on VLRU */
6355 VLRU_EndExclusive_r(struct VLRU_q * q)
6359 assert(pthread_cond_broadcast(&q->cv) == 0);
6362 /* wait for another thread to end exclusive access on VLRU */
6364 VLRU_Wait_r(struct VLRU_q * q)
6367 VOL_CV_WAIT(&q->cv);
6372 * volume soft detach
6374 * caller MUST NOT hold a ref count on vp */
6376 VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh)
6381 assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
6383 ts_save = vp->stats.last_get;
6384 if (ts_save > thresh)
6387 if (vp->nUsers || vp->nWaiters)
6390 if (VIsExclusiveState(V_attachState(vp))) {
6394 switch (V_attachState(vp)) {
6395 case VOL_STATE_UNATTACHED:
6396 case VOL_STATE_PREATTACHED:
6397 case VOL_STATE_ERROR:
6398 case VOL_STATE_GOING_OFFLINE:
6399 case VOL_STATE_SHUTTING_DOWN:
6400 case VOL_STATE_SALVAGING:
6401 volume_LRU.q[vp->vlru.idx].len--;
6403 /* create and cancel a reservation to
6404 * give the volume an opportunity to
6406 VCreateReservation_r(vp);
6407 queue_Remove(&vp->vlru);
6408 vp->vlru.idx = VLRU_QUEUE_INVALID;
6409 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
6410 VCancelReservation_r(vp);
6416 /* hold the volume and take it offline.
6417 * no need for reservations, as VHold_r
6418 * takes care of that internally. */
6419 if (VHold_r(vp) == 0) {
6420 /* vhold drops the glock, so now we should
6421 * check to make sure we aren't racing against
6422 * other threads. if we are racing, offlining vp
6423 * would be wasteful, and block the scanner for a while
6427 (vp->shuttingDown) ||
6428 (vp->goingOffline) ||
6429 (vp->stats.last_get != ts_save)) {
6430 /* looks like we're racing someone else. bail */
6434 /* pull it off the VLRU */
6435 assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
6436 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
6437 queue_Remove(&vp->vlru);
6438 vp->vlru.idx = VLRU_QUEUE_INVALID;
6439 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
6441 /* take if offline */
6442 VOffline_r(vp, "volume has been soft detached");
6444 /* invalidate the volume header cache */
6445 FreeVolumeHeader(vp);
6448 IncUInt64(&VStats.soft_detaches);
6449 vp->stats.soft_detaches++;
6451 /* put in pre-attached state so demand
6452 * attacher can work on it */
6453 VChangeState_r(vp, VOL_STATE_PREATTACHED);
6459 #endif /* AFS_DEMAND_ATTACH_FS */
6462 /***************************************************/
6463 /* Volume Header Cache routines */
6464 /***************************************************/
6467 * volume header cache.
6469 struct volume_hdr_LRU_t volume_hdr_LRU;
6472 * initialize the volume header cache.
6474 * @param[in] howMany number of header cache entries to preallocate
6476 * @pre VOL_LOCK held. Function has never been called before.
6478 * @post howMany cache entries are allocated, initialized, and added
6479 * to the LRU list. Header cache statistics are initialized.
6481 * @note only applicable to fileServer program type. Should only be
6482 * called once during volume package initialization.
6484 * @internal volume package internal use only.
6487 VInitVolumeHeaderCache(afs_uint32 howMany)
6489 register struct volHeader *hp;
6490 if (programType != fileServer)
6492 queue_Init(&volume_hdr_LRU);
6493 volume_hdr_LRU.stats.free = 0;
6494 volume_hdr_LRU.stats.used = howMany;
6495 volume_hdr_LRU.stats.attached = 0;
6496 hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
6500 /* We are using ReleaseVolumeHeader to initialize the values on the header list
6501 * to ensure they have the right values
6503 ReleaseVolumeHeader(hp++);
6507 * get a volume header and attach it to the volume object.
6509 * @param[in] vp pointer to volume object
6511 * @return cache entry status
6512 * @retval 0 volume header was newly attached; cache data is invalid
6513 * @retval 1 volume header was previously attached; cache data is valid
6515 * @pre VOL_LOCK held. For DAFS, lightweight ref must be held on volume object.
6517 * @post volume header attached to volume object. if necessary, header cache
6518 * entry on LRU is synchronized to disk. Header is removed from LRU list.
6520 * @note VOL_LOCK may be dropped
6522 * @warning this interface does not load header data from disk. it merely
6523 * attaches a header object to the volume object, and may sync the old
6524 * header cache data out to disk in the process.
6526 * @internal volume package internal use only.
6529 GetVolumeHeader(register Volume * vp)
6532 register struct volHeader *hd;
6534 static int everLogged = 0;
6536 #ifdef AFS_DEMAND_ATTACH_FS
6537 VolState vp_save = 0, back_save = 0;
6539 /* XXX debug 9/19/05 we've apparently got
6540 * a ref counting bug somewhere that's
6541 * breaking the nUsers == 0 => header on LRU
6543 if (vp->header && queue_IsNotOnQueue(vp->header)) {
6544 Log("nUsers == 0, but header not on LRU\n");
6549 old = (vp->header != NULL); /* old == volume already has a header */
6551 if (programType != fileServer) {
6552 /* for volume utilities, we allocate volHeaders as needed */
6554 hd = (struct volHeader *)calloc(1, sizeof(*vp->header));
6558 #ifdef AFS_DEMAND_ATTACH_FS
6559 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
6563 /* for the fileserver, we keep a volume header cache */
6565 /* the header we previously dropped in the lru is
6566 * still available. pull it off the lru and return */
6569 assert(hd->back == vp);
6571 /* we need to grab a new element off the LRU */
6572 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
6573 /* grab an element and pull off of LRU */
6574 hd = queue_First(&volume_hdr_LRU, volHeader);
6577 /* LRU is empty, so allocate a new volHeader
6578 * this is probably indicative of a leak, so let the user know */
6579 hd = (struct volHeader *)calloc(1, sizeof(struct volHeader));
6582 Log("****Allocated more volume headers, probably leak****\n");
6585 volume_hdr_LRU.stats.free++;
6588 /* this header used to belong to someone else.
6589 * we'll need to check if the header needs to
6590 * be sync'd out to disk */
6592 #ifdef AFS_DEMAND_ATTACH_FS
6593 /* if hd->back were in an exclusive state, then
6594 * its volHeader would not be on the LRU... */
6595 assert(!VIsExclusiveState(V_attachState(hd->back)));
6598 if (hd->diskstuff.inUse) {
6599 /* volume was in use, so we'll need to sync
6600 * its header to disk */
6602 #ifdef AFS_DEMAND_ATTACH_FS
6603 back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
6604 vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
6605 VCreateReservation_r(hd->back);
6609 WriteVolumeHeader_r(&error, hd->back);
6610 /* Ignore errors; catch them later */
6612 #ifdef AFS_DEMAND_ATTACH_FS
6617 hd->back->header = NULL;
6618 #ifdef AFS_DEMAND_ATTACH_FS
6619 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
6621 if (hd->diskstuff.inUse) {
6622 VChangeState_r(hd->back, back_save);
6623 VCancelReservation_r(hd->back);
6624 VChangeState_r(vp, vp_save);
6628 volume_hdr_LRU.stats.attached++;
6632 #ifdef AFS_DEMAND_ATTACH_FS
6633 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
6636 volume_hdr_LRU.stats.free--;
6637 volume_hdr_LRU.stats.used++;
6639 IncUInt64(&VStats.hdr_gets);
6640 #ifdef AFS_DEMAND_ATTACH_FS
6641 IncUInt64(&vp->stats.hdr_gets);
6642 vp->stats.last_hdr_get = FT_ApproxTime();
6649 * make sure volume header is attached and contains valid cache data.
6651 * @param[out] ec outbound error code
6652 * @param[in] vp pointer to volume object
6654 * @pre VOL_LOCK held. For DAFS, lightweight ref held on vp.
6656 * @post header cache entry attached, and loaded with valid data, or
6657 * *ec is nonzero, and the header is released back into the LRU.
6659 * @internal volume package internal use only.
6662 LoadVolumeHeader(Error * ec, Volume * vp)
6664 #ifdef AFS_DEMAND_ATTACH_FS
6665 VolState state_save;
6669 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
6670 IncUInt64(&VStats.hdr_loads);
6671 state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
6674 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
6675 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
6677 IncUInt64(&vp->stats.hdr_loads);
6678 now = FT_ApproxTime();
6682 V_attachFlags(vp) |= VOL_HDR_LOADED;
6683 vp->stats.last_hdr_load = now;
6685 VChangeState_r(vp, state_save);
6687 #else /* AFS_DEMAND_ATTACH_FS */
6689 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
6690 IncUInt64(&VStats.hdr_loads);
6692 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
6693 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
6696 #endif /* AFS_DEMAND_ATTACH_FS */
6698 /* maintain (nUsers==0) => header in LRU invariant */
6699 FreeVolumeHeader(vp);
6704 * release a header cache entry back into the LRU list.
6706 * @param[in] hd pointer to volume header cache object
6708 * @pre VOL_LOCK held.
6710 * @post header cache object appended onto end of LRU list.
6712 * @note only applicable to fileServer program type.
6714 * @note used to place a header cache entry back into the
6715 * LRU pool without invalidating it as a cache entry.
6717 * @internal volume package internal use only.
6720 ReleaseVolumeHeader(register struct volHeader *hd)
6722 if (programType != fileServer)
6724 if (!hd || queue_IsOnQueue(hd)) /* no header, or header already released */
6726 queue_Append(&volume_hdr_LRU, hd);
6727 #ifdef AFS_DEMAND_ATTACH_FS
6729 V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
6732 volume_hdr_LRU.stats.free++;
6733 volume_hdr_LRU.stats.used--;
6737 * free/invalidate a volume header cache entry.
6739 * @param[in] vp pointer to volume object
6741 * @pre VOL_LOCK is held.
6743 * @post For fileserver, header cache entry is returned to LRU, and it is
6744 * invalidated as a cache entry. For volume utilities, the header
6745 * cache entry is freed.
6747 * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
6748 * whenever it is necessary to invalidate the header cache entry.
6750 * @see ReleaseVolumeHeader
6752 * @internal volume package internal use only.
6755 FreeVolumeHeader(register Volume * vp)
6757 register struct volHeader *hd = vp->header;
6760 if (programType == fileServer) {
6761 ReleaseVolumeHeader(hd);
6766 #ifdef AFS_DEMAND_ATTACH_FS
6767 V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
6769 volume_hdr_LRU.stats.attached--;
6774 /***************************************************/
6775 /* Volume Hash Table routines */
6776 /***************************************************/
6779 * set size of volume object hash table.
6781 * @param[in] logsize log(2) of desired hash table size
6783 * @return operation status
6785 * @retval -1 failure
6787 * @pre MUST be called prior to VInitVolumePackage2
6789 * @post Volume Hash Table will have 2^logsize buckets
6792 VSetVolHashSize(int logsize)
6794 /* 64 to 16384 hash buckets seems like a reasonable range */
6795 if ((logsize < 6 ) || (logsize > 14)) {
6800 VolumeHashTable.Size = 1 << logsize;
6801 VolumeHashTable.Mask = VolumeHashTable.Size - 1;
6803 /* we can't yet support runtime modification of this
6804 * parameter. we'll need a configuration rwlock to
6805 * make runtime modification feasible.... */
6812 * initialize dynamic data structures for volume hash table.
6814 * @post hash table is allocated, and fields are initialized.
6816 * @internal volume package internal use only.
6819 VInitVolumeHash(void)
6823 VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
6824 sizeof(VolumeHashChainHead));
6825 assert(VolumeHashTable.Table != NULL);
6827 for (i=0; i < VolumeHashTable.Size; i++) {
6828 queue_Init(&VolumeHashTable.Table[i]);
6829 #ifdef AFS_DEMAND_ATTACH_FS
6830 assert(pthread_cond_init(&VolumeHashTable.Table[i].chain_busy_cv, NULL) == 0);
6831 #endif /* AFS_DEMAND_ATTACH_FS */
6836 * add a volume object to the hash table.
6838 * @param[in] vp pointer to volume object
6839 * @param[in] hashid hash of volume id
6841 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
6844 * @post volume is added to hash chain.
6846 * @internal volume package internal use only.
6848 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
6849 * asynchronous hash chain reordering to finish.
6852 AddVolumeToHashTable(register Volume * vp, int hashid)
6854 VolumeHashChainHead * head;
6856 if (queue_IsOnQueue(vp))
6859 head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
6861 #ifdef AFS_DEMAND_ATTACH_FS
6862 /* wait for the hash chain to become available */
6865 V_attachFlags(vp) |= VOL_IN_HASH;
6866 vp->chainCacheCheck = ++head->cacheCheck;
6867 #endif /* AFS_DEMAND_ATTACH_FS */
6870 vp->hashid = hashid;
6871 queue_Append(head, vp);
6872 vp->vnodeHashOffset = VolumeHashOffset_r();
6876 * delete a volume object from the hash table.
6878 * @param[in] vp pointer to volume object
6880 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
6883 * @post volume is removed from hash chain.
6885 * @internal volume package internal use only.
6887 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
6888 * asynchronous hash chain reordering to finish.
6891 DeleteVolumeFromHashTable(register Volume * vp)
6893 VolumeHashChainHead * head;
6895 if (!queue_IsOnQueue(vp))
6898 head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
6900 #ifdef AFS_DEMAND_ATTACH_FS
6901 /* wait for the hash chain to become available */
6904 V_attachFlags(vp) &= ~(VOL_IN_HASH);
6906 #endif /* AFS_DEMAND_ATTACH_FS */
6910 /* do NOT reset hashid to zero, as the online
6911 * salvager package may need to know the volume id
6912 * after the volume is removed from the hash */
6916 * lookup a volume object in the hash table given a volume id.
6918 * @param[out] ec error code return
6919 * @param[in] volumeId volume id
6920 * @param[in] hint volume object which we believe could be the correct
6923 * @return volume object pointer
6924 * @retval NULL no such volume id is registered with the hash table.
6926 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
6929 * @post volume object with the given id is returned. volume object and
6930 * hash chain access statistics are updated. hash chain may have
6933 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
6934 * asynchronous hash chain reordering operation to finish, or
6935 * in order for us to perform an asynchronous chain reordering.
6937 * @note Hash chain reorderings occur when the access count for the
6938 * volume object being looked up exceeds the sum of the previous
6939 * node's (the node ahead of it in the hash chain linked list)
6940 * access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
6942 * @note For DAFS, the hint parameter allows us to short-circuit if the
6943 * cacheCheck fields match between the hash chain head and the
6944 * hint volume object.
6947 VLookupVolume_r(Error * ec, VolId volumeId, Volume * hint)
6949 register int looks = 0;
6951 #ifdef AFS_DEMAND_ATTACH_FS
6954 VolumeHashChainHead * head;
6957 head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
6959 #ifdef AFS_DEMAND_ATTACH_FS
6960 /* wait for the hash chain to become available */
6963 /* check to see if we can short circuit without walking the hash chain */
6964 if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
6965 IncUInt64(&hint->stats.hash_short_circuits);
6968 #endif /* AFS_DEMAND_ATTACH_FS */
6970 /* someday we need to either do per-chain locks, RWlocks,
6971 * or both for volhash access.
6972 * (and move to a data structure with better cache locality) */
6974 /* search the chain for this volume id */
6975 for(queue_Scan(head, vp, np, Volume)) {
6977 if ((vp->hashid == volumeId)) {
6982 if (queue_IsEnd(head, vp)) {
6986 #ifdef AFS_DEMAND_ATTACH_FS
6987 /* update hash chain statistics */
6990 FillInt64(lks, 0, looks);
6991 AddUInt64(head->looks, lks, &head->looks);
6992 AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
6993 IncUInt64(&head->gets);
6998 IncUInt64(&vp->stats.hash_lookups);
7000 /* for demand attach fileserver, we permit occasional hash chain reordering
7001 * so that frequently looked up volumes move towards the head of the chain */
7002 pp = queue_Prev(vp, Volume);
7003 if (!queue_IsEnd(head, pp)) {
7004 FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
7005 AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
7006 if (GEInt64(vp->stats.hash_lookups, thresh)) {
7007 VReorderHash_r(head, pp, vp);
7011 /* update the short-circuit cache check */
7012 vp->chainCacheCheck = head->cacheCheck;
7014 #endif /* AFS_DEMAND_ATTACH_FS */
7019 #ifdef AFS_DEMAND_ATTACH_FS
7020 /* perform volume hash chain reordering.
7022 * advance a subchain beginning at vp ahead of
7023 * the adjacent subchain ending at pp */
7025 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
7027 Volume *tp, *np, *lp;
7028 afs_uint64 move_thresh;
7030 /* this should never be called if the chain is already busy, so
7031 * no need to wait for other exclusive chain ops to finish */
7033 /* this is a rather heavy set of operations,
7034 * so let's set the chain busy flag and drop
7036 VHashBeginExclusive_r(head);
7039 /* scan forward in the chain from vp looking for the last element
7040 * in the chain we want to advance */
7041 FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
7042 AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
7043 for(queue_ScanFrom(head, vp, tp, np, Volume)) {
7044 if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
7048 lp = queue_Prev(tp, Volume);
7050 /* scan backwards from pp to determine where to splice and
7051 * insert the subchain we're advancing */
7052 for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
7053 if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
7057 tp = queue_Next(tp, Volume);
7059 /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
7060 queue_MoveChainBefore(tp,vp,lp);
7063 IncUInt64(&VStats.hash_reorders);
7065 IncUInt64(&head->reorders);
7067 /* wake up any threads waiting for the hash chain */
7068 VHashEndExclusive_r(head);
7072 /* demand-attach fs volume hash
7073 * asynchronous exclusive operations */
7076 * begin an asynchronous exclusive operation on a volume hash chain.
7078 * @param[in] head pointer to volume hash chain head object
7080 * @pre VOL_LOCK held. hash chain is quiescent.
7082 * @post hash chain marked busy.
7084 * @note this interface is used in conjunction with VHashEndExclusive_r and
7085 * VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
7086 * volume hash chain. Its main use case is hash chain reordering, which
7087 * has the potential to be a highly latent operation.
7089 * @see VHashEndExclusive_r
7094 * @internal volume package internal use only.
7097 VHashBeginExclusive_r(VolumeHashChainHead * head)
7099 assert(head->busy == 0);
7104 * relinquish exclusive ownership of a volume hash chain.
7106 * @param[in] head pointer to volume hash chain head object
7108 * @pre VOL_LOCK held. thread owns the hash chain exclusively.
7110 * @post hash chain is marked quiescent. threads awaiting use of
7111 * chain are awakened.
7113 * @see VHashBeginExclusive_r
7118 * @internal volume package internal use only.
7121 VHashEndExclusive_r(VolumeHashChainHead * head)
7125 assert(pthread_cond_broadcast(&head->chain_busy_cv) == 0);
7129 * wait for all asynchronous operations on a hash chain to complete.
7131 * @param[in] head pointer to volume hash chain head object
7133 * @pre VOL_LOCK held.
7135 * @post hash chain object is quiescent.
7137 * @see VHashBeginExclusive_r
7138 * @see VHashEndExclusive_r
7142 * @note This interface should be called before any attempt to
7143 * traverse the hash chain. It is permissible for a thread
7144 * to gain exclusive access to the chain, and then perform
7145 * latent operations on the chain asynchronously wrt the
7148 * @warning if waiting is necessary, VOL_LOCK is dropped
7150 * @internal volume package internal use only.
7153 VHashWait_r(VolumeHashChainHead * head)
7155 while (head->busy) {
7156 VOL_CV_WAIT(&head->chain_busy_cv);
7159 #endif /* AFS_DEMAND_ATTACH_FS */
7162 /***************************************************/
7163 /* Volume by Partition List routines */
7164 /***************************************************/
7167 * demand attach fileserver adds a
7168 * linked list of volumes to each
7169 * partition object, thus allowing
7170 * for quick enumeration of all
7171 * volumes on a partition
7174 #ifdef AFS_DEMAND_ATTACH_FS
7176 * add a volume to its disk partition VByPList.
7178 * @param[in] vp pointer to volume object
7180 * @pre either the disk partition VByPList is owned exclusively
7181 * by the calling thread, or the list is quiescent and
7184 * @post volume is added to disk partition VByPList
7188 * @warning it is the caller's responsibility to ensure list
7191 * @see VVByPListWait_r
7192 * @see VVByPListBeginExclusive_r
7193 * @see VVByPListEndExclusive_r
7195 * @internal volume package internal use only.
7198 AddVolumeToVByPList_r(Volume * vp)
7200 if (queue_IsNotOnQueue(&vp->vol_list)) {
7201 queue_Append(&vp->partition->vol_list, &vp->vol_list);
7202 V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
7203 vp->partition->vol_list.len++;
7208 * delete a volume from its disk partition VByPList.
7210 * @param[in] vp pointer to volume object
7212 * @pre either the disk partition VByPList is owned exclusively
7213 * by the calling thread, or the list is quiescent and
7216 * @post volume is removed from the disk partition VByPList
7220 * @warning it is the caller's responsibility to ensure list
7223 * @see VVByPListWait_r
7224 * @see VVByPListBeginExclusive_r
7225 * @see VVByPListEndExclusive_r
7227 * @internal volume package internal use only.
7230 DeleteVolumeFromVByPList_r(Volume * vp)
7232 if (queue_IsOnQueue(&vp->vol_list)) {
7233 queue_Remove(&vp->vol_list);
7234 V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
7235 vp->partition->vol_list.len--;
7240 * begin an asynchronous exclusive operation on a VByPList.
7242 * @param[in] dp pointer to disk partition object
7244 * @pre VOL_LOCK held. VByPList is quiescent.
7246 * @post VByPList marked busy.
7248 * @note this interface is used in conjunction with VVByPListEndExclusive_r and
7249 * VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
7252 * @see VVByPListEndExclusive_r
7253 * @see VVByPListWait_r
7257 * @internal volume package internal use only.
7259 /* take exclusive control over the list */
7261 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
7263 assert(dp->vol_list.busy == 0);
7264 dp->vol_list.busy = 1;
7268 * relinquish exclusive ownership of a VByPList.
7270 * @param[in] dp pointer to disk partition object
7272 * @pre VOL_LOCK held. thread owns the VByPList exclusively.
7274 * @post VByPList is marked quiescent. threads awaiting use of
7275 * the list are awakened.
7277 * @see VVByPListBeginExclusive_r
7278 * @see VVByPListWait_r
7282 * @internal volume package internal use only.
7285 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
7287 assert(dp->vol_list.busy);
7288 dp->vol_list.busy = 0;
7289 assert(pthread_cond_broadcast(&dp->vol_list.cv) == 0);
7293 * wait for all asynchronous operations on a VByPList to complete.
7295 * @param[in] dp pointer to disk partition object
7297 * @pre VOL_LOCK is held.
7299 * @post disk partition's VByP list is quiescent
7303 * @note This interface should be called before any attempt to
7304 * traverse the VByPList. It is permissible for a thread
7305 * to gain exclusive access to the list, and then perform
7306 * latent operations on the list asynchronously wrt the
7309 * @warning if waiting is necessary, VOL_LOCK is dropped
7311 * @see VVByPListEndExclusive_r
7312 * @see VVByPListBeginExclusive_r
7314 * @internal volume package internal use only.
7317 VVByPListWait_r(struct DiskPartition64 * dp)
7319 while (dp->vol_list.busy) {
7320 VOL_CV_WAIT(&dp->vol_list.cv);
7323 #endif /* AFS_DEMAND_ATTACH_FS */
7325 /***************************************************/
7326 /* Volume Cache Statistics routines */
7327 /***************************************************/
7330 VPrintCacheStats_r(void)
7332 afs_uint32 get_hi, get_lo, load_hi, load_lo;
7333 register struct VnodeClassInfo *vcp;
7334 vcp = &VnodeClassInfo[vLarge];
7335 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);
7336 vcp = &VnodeClassInfo[vSmall];
7337 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);
7338 SplitInt64(VStats.hdr_gets, get_hi, get_lo);
7339 SplitInt64(VStats.hdr_loads, load_hi, load_lo);
7340 Log("Volume header cache, %d entries, %d gets, %d replacements\n",
7341 VStats.hdr_cache_size, get_lo, load_lo);
7345 VPrintCacheStats(void)
7348 VPrintCacheStats_r();
7352 #ifdef AFS_DEMAND_ATTACH_FS
7354 UInt64ToDouble(afs_uint64 * x)
7356 static double c32 = 4.0 * 1.073741824 * 1000000000.0;
7358 SplitInt64(*x, h, l);
7359 return (((double)h) * c32) + ((double) l);
7363 DoubleToPrintable(double x, char * buf, int len)
7365 static double billion = 1000000000.0;
7368 y[0] = (afs_uint32) (x / (billion * billion));
7369 y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
7370 y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
7373 snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
7375 snprintf(buf, len, "%d%09d", y[1], y[2]);
7377 snprintf(buf, len, "%d", y[2]);
7383 struct VLRUExtStatsEntry {
7387 struct VLRUExtStats {
7393 } queue_info[VLRU_QUEUE_INVALID];
7394 struct VLRUExtStatsEntry * vec;
7398 * add a 256-entry fudge factor onto the vector in case state changes
7399 * out from under us.
7401 #define VLRU_EXT_STATS_VEC_LEN_FUDGE 256
7404 * collect extended statistics for the VLRU subsystem.
7406 * @param[out] stats pointer to stats structure to be populated
7407 * @param[in] nvols number of volumes currently known to exist
7409 * @pre VOL_LOCK held
7411 * @post stats->vec allocated and populated
7413 * @return operation status
7418 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
7420 afs_uint32 cur, idx, len;
7421 struct rx_queue * qp, * nqp;
7423 struct VLRUExtStatsEntry * vec;
7425 len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
7426 vec = stats->vec = calloc(len,
7427 sizeof(struct VLRUExtStatsEntry));
7433 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
7434 VLRU_Wait_r(&volume_LRU.q[idx]);
7435 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7438 stats->queue_info[idx].start = cur;
7440 for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7442 /* out of space in vec */
7445 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7446 vec[cur].volid = vp->hashid;
7450 stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
7453 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7461 #define ENUMTOSTRING(en) #en
7462 #define ENUMCASE(en) \
7464 return ENUMTOSTRING(en); \
7468 vlru_idx_to_string(int idx)
7471 ENUMCASE(VLRU_QUEUE_NEW);
7472 ENUMCASE(VLRU_QUEUE_MID);
7473 ENUMCASE(VLRU_QUEUE_OLD);
7474 ENUMCASE(VLRU_QUEUE_CANDIDATE);
7475 ENUMCASE(VLRU_QUEUE_HELD);
7476 ENUMCASE(VLRU_QUEUE_INVALID);
7478 return "**UNKNOWN**";
7483 VPrintExtendedCacheStats_r(int flags)
7486 afs_uint32 vol_sum = 0;
7493 struct stats looks, gets, reorders, len;
7494 struct stats ch_looks, ch_gets, ch_reorders;
7496 VolumeHashChainHead *head;
7498 struct VLRUExtStats vlru_stats;
7500 /* zero out stats */
7501 memset(&looks, 0, sizeof(struct stats));
7502 memset(&gets, 0, sizeof(struct stats));
7503 memset(&reorders, 0, sizeof(struct stats));
7504 memset(&len, 0, sizeof(struct stats));
7505 memset(&ch_looks, 0, sizeof(struct stats));
7506 memset(&ch_gets, 0, sizeof(struct stats));
7507 memset(&ch_reorders, 0, sizeof(struct stats));
7509 for (i = 0; i < VolumeHashTable.Size; i++) {
7510 head = &VolumeHashTable.Table[i];
7513 VHashBeginExclusive_r(head);
7516 ch_looks.sum = UInt64ToDouble(&head->looks);
7517 ch_gets.sum = UInt64ToDouble(&head->gets);
7518 ch_reorders.sum = UInt64ToDouble(&head->reorders);
7520 /* update global statistics */
7522 looks.sum += ch_looks.sum;
7523 gets.sum += ch_gets.sum;
7524 reorders.sum += ch_reorders.sum;
7525 len.sum += (double)head->len;
7526 vol_sum += head->len;
7529 len.min = (double) head->len;
7530 len.max = (double) head->len;
7531 looks.min = ch_looks.sum;
7532 looks.max = ch_looks.sum;
7533 gets.min = ch_gets.sum;
7534 gets.max = ch_gets.sum;
7535 reorders.min = ch_reorders.sum;
7536 reorders.max = ch_reorders.sum;
7538 if (((double)head->len) < len.min)
7539 len.min = (double) head->len;
7540 if (((double)head->len) > len.max)
7541 len.max = (double) head->len;
7542 if (ch_looks.sum < looks.min)
7543 looks.min = ch_looks.sum;
7544 else if (ch_looks.sum > looks.max)
7545 looks.max = ch_looks.sum;
7546 if (ch_gets.sum < gets.min)
7547 gets.min = ch_gets.sum;
7548 else if (ch_gets.sum > gets.max)
7549 gets.max = ch_gets.sum;
7550 if (ch_reorders.sum < reorders.min)
7551 reorders.min = ch_reorders.sum;
7552 else if (ch_reorders.sum > reorders.max)
7553 reorders.max = ch_reorders.sum;
7557 if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
7558 /* compute detailed per-chain stats */
7559 struct stats hdr_loads, hdr_gets;
7560 double v_looks, v_loads, v_gets;
7562 /* initialize stats with data from first element in chain */
7563 vp = queue_First(head, Volume);
7564 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
7565 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
7566 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
7567 ch_gets.min = ch_gets.max = v_looks;
7568 hdr_loads.min = hdr_loads.max = v_loads;
7569 hdr_gets.min = hdr_gets.max = v_gets;
7570 hdr_loads.sum = hdr_gets.sum = 0;
7572 vp = queue_Next(vp, Volume);
7574 /* pull in stats from remaining elements in chain */
7575 for (queue_ScanFrom(head, vp, vp, np, Volume)) {
7576 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
7577 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
7578 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
7580 hdr_loads.sum += v_loads;
7581 hdr_gets.sum += v_gets;
7583 if (v_looks < ch_gets.min)
7584 ch_gets.min = v_looks;
7585 else if (v_looks > ch_gets.max)
7586 ch_gets.max = v_looks;
7588 if (v_loads < hdr_loads.min)
7589 hdr_loads.min = v_loads;
7590 else if (v_loads > hdr_loads.max)
7591 hdr_loads.max = v_loads;
7593 if (v_gets < hdr_gets.min)
7594 hdr_gets.min = v_gets;
7595 else if (v_gets > hdr_gets.max)
7596 hdr_gets.max = v_gets;
7599 /* compute per-chain averages */
7600 ch_gets.avg = ch_gets.sum / ((double)head->len);
7601 hdr_loads.avg = hdr_loads.sum / ((double)head->len);
7602 hdr_gets.avg = hdr_gets.sum / ((double)head->len);
7604 /* dump per-chain stats */
7605 Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
7607 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
7608 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
7609 Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
7610 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
7611 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
7612 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
7613 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
7614 Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
7615 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
7616 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
7617 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
7618 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
7619 Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
7620 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
7621 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
7622 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
7623 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
7624 } else if (flags & VOL_STATS_PER_CHAIN) {
7625 /* dump simple per-chain stats */
7626 Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
7628 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
7629 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
7630 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
7634 VHashEndExclusive_r(head);
7639 /* compute global averages */
7640 len.avg = len.sum / ((double)VolumeHashTable.Size);
7641 looks.avg = looks.sum / ((double)VolumeHashTable.Size);
7642 gets.avg = gets.sum / ((double)VolumeHashTable.Size);
7643 reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
7645 /* dump global stats */
7646 Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
7647 Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
7648 DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
7649 DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
7650 DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
7651 DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
7652 Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
7653 DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
7654 DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
7655 DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
7656 DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
7657 Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
7658 DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
7659 DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
7660 DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
7661 DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
7662 Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
7663 DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
7664 DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
7665 DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
7666 DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
7668 /* print extended disk related statistics */
7670 struct DiskPartition64 * diskP;
7671 afs_uint32 vol_count[VOLMAXPARTS+1];
7672 byte part_exists[VOLMAXPARTS+1];
7676 memset(vol_count, 0, sizeof(vol_count));
7677 memset(part_exists, 0, sizeof(part_exists));
7681 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
7683 vol_count[id] = diskP->vol_list.len;
7684 part_exists[id] = 1;
7688 for (i = 0; i <= VOLMAXPARTS; i++) {
7689 if (part_exists[i]) {
7690 /* XXX while this is currently safe, it is a violation
7691 * of the VGetPartitionById_r interface contract. */
7692 diskP = VGetPartitionById_r(i, 0);
7694 Log("Partition %s has %d online volumes\n",
7695 VPartitionPath(diskP), diskP->vol_list.len);
7702 /* print extended VLRU statistics */
7703 if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
7704 afs_uint32 idx, cur, lpos;
7708 Log("VLRU State Dump:\n\n");
7710 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
7711 Log("\t%s:\n", vlru_idx_to_string(idx));
7714 for (cur = vlru_stats.queue_info[idx].start;
7715 cur < vlru_stats.queue_info[idx].len;
7717 line[lpos++] = vlru_stats.vec[cur].volid;
7719 Log("\t\t%u, %u, %u, %u, %u,\n",
7720 line[0], line[1], line[2], line[3], line[4]);
7729 Log("\t\t%u, %u, %u, %u, %u\n",
7730 line[0], line[1], line[2], line[3], line[4]);
7735 free(vlru_stats.vec);
7742 VPrintExtendedCacheStats(int flags)
7745 VPrintExtendedCacheStats_r(flags);
7748 #endif /* AFS_DEMAND_ATTACH_FS */
7751 VCanScheduleSalvage(void)
7753 return vol_opts.canScheduleSalvage;
7759 return vol_opts.canUseFSSYNC;
7763 VCanUseSALVSYNC(void)
7765 return vol_opts.canUseSALVSYNC;