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 #ifdef SALVSYNC_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);
2571 /* volume operation in progress */
2576 #else /* AFS_DEMAND_ATTACH_FS */
2578 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
2583 #endif /* AFS_DEMAND_ATTACH_FS */
2585 if (V_needsSalvaged(vp)) {
2586 if (vp->specialStatus)
2587 vp->specialStatus = 0;
2589 #if defined(AFS_DEMAND_ATTACH_FS)
2590 if (!VCanScheduleSalvage()) {
2591 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
2593 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
2597 #else /* AFS_DEMAND_ATTACH_FS */
2600 #endif /* AFS_DEMAND_ATTACH_FS */
2605 if (VShouldCheckInUse(mode)) {
2606 #ifndef FAST_RESTART
2607 if (V_inUse(vp) && VolumeWriteable(vp)) {
2608 if (!V_needsSalvaged(vp)) {
2609 V_needsSalvaged(vp) = 1;
2610 VUpdateVolume_r(ec, vp, 0);
2612 #if defined(AFS_DEMAND_ATTACH_FS)
2613 if (!VCanScheduleSalvage()) {
2614 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
2616 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
2620 #else /* AFS_DEMAND_ATTACH_FS */
2621 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
2624 #endif /* AFS_DEMAND_ATTACH_FS */
2627 #endif /* FAST_RESTART */
2629 if (programType == fileServer && V_destroyMe(vp) == DESTROY_ME) {
2630 /* Only check destroyMe if we are the fileserver, since the
2631 * volserver et al sometimes need to work with volumes with
2632 * destroyMe set. Examples are 'temporary' volumes the
2633 * volserver creates, and when we create a volume (destroyMe
2634 * is set on creation; sometimes a separate volserver
2635 * transaction is created to clear destroyMe).
2638 #if defined(AFS_DEMAND_ATTACH_FS)
2639 /* schedule a salvage so the volume goes away on disk */
2640 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2641 VChangeState_r(vp, VOL_STATE_ERROR);
2643 #endif /* AFS_DEMAND_ATTACH_FS */
2645 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
2651 vp->nextVnodeUnique = V_uniquifier(vp);
2652 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
2653 #ifndef BITMAP_LATER
2654 if (programType == fileServer && VolumeWriteable(vp)) {
2656 for (i = 0; i < nVNODECLASSES; i++) {
2657 VGetBitmap_r(ec, vp, i);
2659 #ifdef AFS_DEMAND_ATTACH_FS
2660 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2663 #else /* AFS_DEMAND_ATTACH_FS */
2665 #endif /* AFS_DEMAND_ATTACH_FS */
2666 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
2672 #endif /* BITMAP_LATER */
2674 if (programType == fileServer) {
2675 if (vp->specialStatus)
2676 vp->specialStatus = 0;
2677 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
2678 V_inUse(vp) = fileServer;
2679 V_offlineMessage(vp)[0] = '\0';
2682 if ((mode != V_PEEK) && (mode != V_SECRETLY))
2683 V_inUse(vp) = programType;
2684 V_checkoutMode(vp) = mode;
2687 AddVolumeToHashTable(vp, V_id(vp));
2688 #ifdef AFS_DEMAND_ATTACH_FS
2689 if ((programType != fileServer) ||
2690 (V_inUse(vp) == fileServer)) {
2691 AddVolumeToVByPList_r(vp);
2693 VChangeState_r(vp, VOL_STATE_ATTACHED);
2695 VChangeState_r(vp, VOL_STATE_UNATTACHED);
2701 /* Attach an existing volume.
2702 The volume also normally goes online at this time.
2703 An offline volume must be reattached to make it go online.
2707 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
2711 retVal = VAttachVolume_r(ec, volumeId, mode);
2717 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
2720 VGetVolumePath(ec, volumeId, &part, &name);
2722 register Volume *vp;
2724 vp = VGetVolume_r(&error, volumeId);
2726 assert(V_inUse(vp) == 0);
2727 VDetachVolume_r(ec, vp);
2731 return VAttachVolumeByName_r(ec, part, name, mode);
2734 /* Increment a reference count to a volume, sans context swaps. Requires
2735 * possibly reading the volume header in from the disk, since there's
2736 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
2738 * N.B. This call can fail if we can't read in the header!! In this case
2739 * we still guarantee we won't context swap, but the ref count won't be
2740 * incremented (otherwise we'd violate the invariant).
2742 /* NOTE: with the demand attach fileserver extensions, the global lock
2743 * is dropped within VHold */
2744 #ifdef AFS_DEMAND_ATTACH_FS
2746 VHold_r(register Volume * vp)
2750 VCreateReservation_r(vp);
2751 VWaitExclusiveState_r(vp);
2753 LoadVolumeHeader(&error, vp);
2755 VCancelReservation_r(vp);
2759 VCancelReservation_r(vp);
2762 #else /* AFS_DEMAND_ATTACH_FS */
2764 VHold_r(register Volume * vp)
2768 LoadVolumeHeader(&error, vp);
2774 #endif /* AFS_DEMAND_ATTACH_FS */
2778 VHold(register Volume * vp)
2782 retVal = VHold_r(vp);
2789 /***************************************************/
2790 /* get and put volume routines */
2791 /***************************************************/
2794 * put back a heavyweight reference to a volume object.
2796 * @param[in] vp volume object pointer
2798 * @pre VOL_LOCK held
2800 * @post heavyweight volume reference put back.
2801 * depending on state, volume may have been taken offline,
2802 * detached, salvaged, freed, etc.
2804 * @internal volume package internal use only
2807 VPutVolume_r(register Volume * vp)
2809 assert(--vp->nUsers >= 0);
2810 if (vp->nUsers == 0) {
2812 ReleaseVolumeHeader(vp->header);
2813 #ifdef AFS_DEMAND_ATTACH_FS
2814 if (!VCheckDetach(vp)) {
2818 #else /* AFS_DEMAND_ATTACH_FS */
2820 #endif /* AFS_DEMAND_ATTACH_FS */
2825 VPutVolume(register Volume * vp)
2833 /* Get a pointer to an attached volume. The pointer is returned regardless
2834 of whether or not the volume is in service or on/off line. An error
2835 code, however, is returned with an indication of the volume's status */
2837 VGetVolume(Error * ec, Error * client_ec, VolId volumeId)
2841 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
2847 VGetVolume_r(Error * ec, VolId volumeId)
2849 return GetVolume(ec, NULL, volumeId, NULL, 0);
2852 /* try to get a volume we've previously looked up */
2853 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
2855 VGetVolumeByVp_r(Error * ec, Volume * vp)
2857 return GetVolume(ec, NULL, vp->hashid, vp, 0);
2860 /* private interface for getting a volume handle
2861 * volumeId must be provided.
2862 * hint is an optional parameter to speed up hash lookups
2863 * flags is not used at this time
2865 /* for demand attach fs, caller MUST NOT hold a ref count on hint */
2867 GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint, int flags)
2870 /* pull this profiling/debugging code out of regular builds */
2872 #define VGET_CTR_INC(x) x++
2873 unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
2874 0, V7 = 0, V8 = 0, V9 = 0;
2875 unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
2877 #define VGET_CTR_INC(x)
2879 #ifdef AFS_DEMAND_ATTACH_FS
2880 Volume *avp, * rvp = hint;
2884 * if VInit is zero, the volume package dynamic
2885 * data structures have not been initialized yet,
2886 * and we must immediately return an error
2892 *client_ec = VOFFLINE;
2897 #ifdef AFS_DEMAND_ATTACH_FS
2899 VCreateReservation_r(rvp);
2901 #endif /* AFS_DEMAND_ATTACH_FS */
2909 vp = VLookupVolume_r(ec, volumeId, vp);
2915 #ifdef AFS_DEMAND_ATTACH_FS
2916 if (rvp && (rvp != vp)) {
2917 /* break reservation on old vp */
2918 VCancelReservation_r(rvp);
2921 #endif /* AFS_DEMAND_ATTACH_FS */
2927 /* Until we have reached an initialization level of 2
2928 * we don't know whether this volume exists or not.
2929 * We can't sleep and retry later because before a volume
2930 * is attached, the caller tries to get it first. Just
2931 * return VOFFLINE and the caller can choose whether to
2932 * retry the command or not. */
2942 IncUInt64(&VStats.hdr_gets);
2944 #ifdef AFS_DEMAND_ATTACH_FS
2945 /* block if someone else is performing an exclusive op on this volume */
2948 VCreateReservation_r(rvp);
2950 VWaitExclusiveState_r(vp);
2952 /* short circuit with VNOVOL in the following circumstances:
2955 * - VOL_STATE_SHUTTING_DOWN
2957 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
2958 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN) ||
2959 (V_attachState(vp) == VOL_STATE_GOING_OFFLINE)) {
2966 * short circuit with VOFFLINE in the following circumstances:
2968 * - VOL_STATE_UNATTACHED
2970 if (V_attachState(vp) == VOL_STATE_UNATTACHED) {
2971 if (vp->specialStatus) {
2972 *ec = vp->specialStatus;
2980 /* allowable states:
2986 if (vp->salvage.requested) {
2987 VUpdateSalvagePriority_r(vp);
2990 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
2991 avp = VAttachVolumeByVp_r(ec, vp, 0);
2994 /* VAttachVolumeByVp_r can return a pointer
2995 * != the vp passed to it under certain
2996 * conditions; make sure we don't leak
2997 * reservations if that happens */
2999 VCancelReservation_r(rvp);
3001 VCreateReservation_r(rvp);
3011 if (!vp->pending_vol_op) {
3026 if ((V_attachState(vp) == VOL_STATE_SALVAGING) ||
3027 (*ec == VSALVAGING)) {
3029 /* see CheckVnode() in afsfileprocs.c for an explanation
3030 * of this error code logic */
3031 afs_uint32 now = FT_ApproxTime();
3032 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
3035 *client_ec = VRESTARTING;
3044 LoadVolumeHeader(ec, vp);
3047 /* Only log the error if it was a totally unexpected error. Simply
3048 * a missing inode is likely to be caused by the volume being deleted */
3049 if (errno != ENXIO || LogLevel)
3050 Log("Volume %u: couldn't reread volume header\n",
3052 #ifdef AFS_DEMAND_ATTACH_FS
3053 if (VCanScheduleSalvage()) {
3054 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3059 #else /* AFS_DEMAND_ATTACH_FS */
3062 #endif /* AFS_DEMAND_ATTACH_FS */
3066 #ifdef AFS_DEMAND_ATTACH_FS
3068 * this test MUST happen after the volume header is loaded
3071 /* only valid before/during demand attachment */
3072 assert(!vp->pending_vol_op || vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
3074 /* deny getvolume due to running mutually exclusive vol op */
3075 if (vp->pending_vol_op && vp->pending_vol_op->vol_op_state==FSSYNC_VolOpRunningOffline) {
3077 * volume cannot remain online during this volume operation.
3080 if (vp->specialStatus) {
3082 * special status codes outrank normal VOFFLINE code
3084 *ec = vp->specialStatus;
3086 *client_ec = vp->specialStatus;
3090 /* see CheckVnode() in afsfileprocs.c for an explanation
3091 * of this error code logic */
3092 afs_uint32 now = FT_ApproxTime();
3093 if ((vp->stats.last_vol_op + (10 * 60)) >= now) {
3096 *client_ec = VRESTARTING;
3101 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3102 FreeVolumeHeader(vp);
3106 #endif /* AFS_DEMAND_ATTACH_FS */
3109 if (vp->shuttingDown) {
3116 if (programType == fileServer) {
3118 if (vp->goingOffline) {
3120 #ifdef AFS_DEMAND_ATTACH_FS
3121 /* wait for the volume to go offline */
3122 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
3123 VWaitStateChange_r(vp);
3125 #elif defined(AFS_PTHREAD_ENV)
3126 VOL_CV_WAIT(&vol_put_volume_cond);
3127 #else /* AFS_PTHREAD_ENV */
3128 LWP_WaitProcess(VPutVolume);
3129 #endif /* AFS_PTHREAD_ENV */
3132 if (vp->specialStatus) {
3134 *ec = vp->specialStatus;
3135 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3138 } else if (V_inUse(vp) == 0) {
3149 #ifdef AFS_DEMAND_ATTACH_FS
3150 /* if no error, bump nUsers */
3153 VLRU_UpdateAccess_r(vp);
3156 VCancelReservation_r(rvp);
3159 if (client_ec && !*client_ec) {
3162 #else /* AFS_DEMAND_ATTACH_FS */
3163 /* if no error, bump nUsers */
3170 #endif /* AFS_DEMAND_ATTACH_FS */
3178 /***************************************************/
3179 /* Volume offline/detach routines */
3180 /***************************************************/
3182 /* caller MUST hold a heavyweight ref on vp */
3183 #ifdef AFS_DEMAND_ATTACH_FS
3185 VTakeOffline_r(register Volume * vp)
3189 assert(vp->nUsers > 0);
3190 assert(programType == fileServer);
3192 VCreateReservation_r(vp);
3193 VWaitExclusiveState_r(vp);
3195 vp->goingOffline = 1;
3196 V_needsSalvaged(vp) = 1;
3198 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
3199 VCancelReservation_r(vp);
3201 #else /* AFS_DEMAND_ATTACH_FS */
3203 VTakeOffline_r(register Volume * vp)
3205 assert(vp->nUsers > 0);
3206 assert(programType == fileServer);
3208 vp->goingOffline = 1;
3209 V_needsSalvaged(vp) = 1;
3211 #endif /* AFS_DEMAND_ATTACH_FS */
3214 VTakeOffline(register Volume * vp)
3222 * force a volume offline.
3224 * @param[in] vp volume object pointer
3225 * @param[in] flags flags (see note below)
3227 * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
3228 * used when VUpdateVolume_r needs to call VForceOffline_r
3229 * (which in turn would normally call VUpdateVolume_r)
3231 * @see VUpdateVolume_r
3233 * @pre VOL_LOCK must be held.
3234 * for DAFS, caller must hold ref.
3236 * @note for DAFS, it _is safe_ to call this function from an
3239 * @post needsSalvaged flag is set.
3240 * for DAFS, salvage is requested.
3241 * no further references to the volume through the volume
3242 * package will be honored.
3243 * all file descriptor and vnode caches are invalidated.
3245 * @warning this is a heavy-handed interface. it results in
3246 * a volume going offline regardless of the current
3247 * reference count state.
3249 * @internal volume package internal use only
3252 VForceOffline_r(Volume * vp, int flags)
3256 #ifdef AFS_DEMAND_ATTACH_FS
3257 VChangeState_r(vp, VOL_STATE_ERROR);
3262 strcpy(V_offlineMessage(vp),
3263 "Forced offline due to internal error: volume needs to be salvaged");
3264 Log("Volume %u forced offline: it needs salvaging!\n", V_id(vp));
3267 vp->goingOffline = 0;
3268 V_needsSalvaged(vp) = 1;
3269 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
3270 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
3273 #ifdef AFS_DEMAND_ATTACH_FS
3274 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3275 #endif /* AFS_DEMAND_ATTACH_FS */
3277 #ifdef AFS_PTHREAD_ENV
3278 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3279 #else /* AFS_PTHREAD_ENV */
3280 LWP_NoYieldSignal(VPutVolume);
3281 #endif /* AFS_PTHREAD_ENV */
3283 VReleaseVolumeHandles_r(vp);
3287 * force a volume offline.
3289 * @param[in] vp volume object pointer
3291 * @see VForceOffline_r
3294 VForceOffline(Volume * vp)
3297 VForceOffline_r(vp, 0);
3301 /* The opposite of VAttachVolume. The volume header is written to disk, with
3302 the inUse bit turned off. A copy of the header is maintained in memory,
3303 however (which is why this is VOffline, not VDetach).
3306 VOffline_r(Volume * vp, char *message)
3308 #ifndef AFS_DEMAND_ATTACH_FS
3310 VolumeId vid = V_id(vp);
3313 assert(programType != volumeUtility && programType != volumeServer);
3318 if (V_offlineMessage(vp)[0] == '\0')
3319 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
3320 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
3322 vp->goingOffline = 1;
3323 #ifdef AFS_DEMAND_ATTACH_FS
3324 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
3325 VCreateReservation_r(vp);
3328 /* wait for the volume to go offline */
3329 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
3330 VWaitStateChange_r(vp);
3332 VCancelReservation_r(vp);
3333 #else /* AFS_DEMAND_ATTACH_FS */
3335 vp = VGetVolume_r(&error, vid); /* Wait for it to go offline */
3336 if (vp) /* In case it was reattached... */
3338 #endif /* AFS_DEMAND_ATTACH_FS */
3341 #ifdef AFS_DEMAND_ATTACH_FS
3343 * Take a volume offline in order to perform a volume operation.
3345 * @param[inout] ec address in which to store error code
3346 * @param[in] vp volume object pointer
3347 * @param[in] message volume offline status message
3350 * - VOL_LOCK is held
3351 * - caller MUST hold a heavyweight ref on vp
3354 * - volume is taken offline
3355 * - if possible, volume operation is promoted to running state
3356 * - on failure, *ec is set to nonzero
3358 * @note Although this function does not return any value, it may
3359 * still fail to promote our pending volume operation to
3360 * a running state. Any caller MUST check the value of *ec,
3361 * and MUST NOT blindly assume success.
3363 * @warning if the caller does not hold a lightweight ref on vp,
3364 * then it MUST NOT reference vp after this function
3365 * returns to the caller.
3367 * @internal volume package internal use only
3370 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
3372 assert(vp->pending_vol_op);
3378 if (V_offlineMessage(vp)[0] == '\0')
3379 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
3380 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
3382 vp->goingOffline = 1;
3383 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
3384 VCreateReservation_r(vp);
3387 /* Wait for the volume to go offline */
3388 while (!VIsOfflineState(V_attachState(vp))) {
3389 /* do not give corrupted volumes to the volserver */
3390 if (vp->salvage.requested && vp->pending_vol_op->com.programType != salvageServer) {
3394 VWaitStateChange_r(vp);
3398 VCancelReservation_r(vp);
3400 #endif /* AFS_DEMAND_ATTACH_FS */
3403 VOffline(Volume * vp, char *message)
3406 VOffline_r(vp, message);
3410 /* This gets used for the most part by utility routines that don't want
3411 * to keep all the volume headers around. Generally, the file server won't
3412 * call this routine, because then the offline message in the volume header
3413 * (or other information) won't be available to clients. For NAMEI, also
3414 * close the file handles. However, the fileserver does call this during
3415 * an attach following a volume operation.
3418 VDetachVolume_r(Error * ec, Volume * vp)
3421 struct DiskPartition64 *tpartp;
3422 int notifyServer = 0;
3423 int useDone = FSYNC_VOL_ON;
3425 *ec = 0; /* always "succeeds" */
3426 if (VCanUseFSSYNC()) {
3427 notifyServer = vp->needsPutBack;
3428 if (V_destroyMe(vp) == DESTROY_ME)
3429 useDone = FSYNC_VOL_DONE;
3430 #ifdef AFS_DEMAND_ATTACH_FS
3431 else if (!V_blessed(vp) || !V_inService(vp))
3432 useDone = FSYNC_VOL_LEAVE_OFF;
3435 tpartp = vp->partition;
3437 DeleteVolumeFromHashTable(vp);
3438 vp->shuttingDown = 1;
3439 #ifdef AFS_DEMAND_ATTACH_FS
3440 DeleteVolumeFromVByPList_r(vp);
3442 VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
3444 if (programType != fileServer)
3446 #endif /* AFS_DEMAND_ATTACH_FS */
3448 /* Will be detached sometime in the future--this is OK since volume is offline */
3450 /* XXX the following code should really be moved to VCheckDetach() since the volume
3451 * is not technically detached until the refcounts reach zero
3453 #ifdef FSSYNC_BUILD_CLIENT
3454 if (VCanUseFSSYNC() && notifyServer) {
3456 * Note: The server is not notified in the case of a bogus volume
3457 * explicitly to make it possible to create a volume, do a partial
3458 * restore, then abort the operation without ever putting the volume
3459 * online. This is essential in the case of a volume move operation
3460 * between two partitions on the same server. In that case, there
3461 * would be two instances of the same volume, one of them bogus,
3462 * which the file server would attempt to put on line
3464 FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
3465 /* XXX this code path is only hit by volume utilities, thus
3466 * V_BreakVolumeCallbacks will always be NULL. if we really
3467 * want to break callbacks in this path we need to use FSYNC_VolOp() */
3469 /* Dettaching it so break all callbacks on it */
3470 if (V_BreakVolumeCallbacks) {
3471 Log("volume %u detached; breaking all call backs\n", volume);
3472 (*V_BreakVolumeCallbacks) (volume);
3476 #endif /* FSSYNC_BUILD_CLIENT */
3480 VDetachVolume(Error * ec, Volume * vp)
3483 VDetachVolume_r(ec, vp);
3488 /***************************************************/
3489 /* Volume fd/inode handle closing routines */
3490 /***************************************************/
3492 /* For VDetachVolume, we close all cached file descriptors, but keep
3493 * the Inode handles in case we need to read from a busy volume.
3495 /* for demand attach, caller MUST hold ref count on vp */
3497 VCloseVolumeHandles_r(Volume * vp)
3499 #ifdef AFS_DEMAND_ATTACH_FS
3500 VolState state_save;
3502 state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
3507 * XXX need to investigate whether we can perform
3508 * DFlushVolume outside of vol_glock_mutex...
3510 * VCloseVnodeFiles_r drops the glock internally */
3511 DFlushVolume(V_id(vp));
3512 VCloseVnodeFiles_r(vp);
3514 #ifdef AFS_DEMAND_ATTACH_FS
3518 /* Too time consuming and unnecessary for the volserver */
3519 if (programType == fileServer) {
3520 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
3521 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
3522 IH_CONDSYNC(vp->diskDataHandle);
3524 IH_CONDSYNC(vp->linkHandle);
3525 #endif /* AFS_NT40_ENV */
3528 IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
3529 IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
3530 IH_REALLYCLOSE(vp->diskDataHandle);
3531 IH_REALLYCLOSE(vp->linkHandle);
3533 #ifdef AFS_DEMAND_ATTACH_FS
3535 VChangeState_r(vp, state_save);
3539 /* For both VForceOffline and VOffline, we close all relevant handles.
3540 * For VOffline, if we re-attach the volume, the files may possible be
3541 * different than before.
3543 /* for demand attach, caller MUST hold a ref count on vp */
3545 VReleaseVolumeHandles_r(Volume * vp)
3547 #ifdef AFS_DEMAND_ATTACH_FS
3548 VolState state_save;
3550 state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
3553 /* XXX need to investigate whether we can perform
3554 * DFlushVolume outside of vol_glock_mutex... */
3555 DFlushVolume(V_id(vp));
3557 VReleaseVnodeFiles_r(vp); /* releases the glock internally */
3559 #ifdef AFS_DEMAND_ATTACH_FS
3563 /* Too time consuming and unnecessary for the volserver */
3564 if (programType == fileServer) {
3565 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
3566 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
3567 IH_CONDSYNC(vp->diskDataHandle);
3569 IH_CONDSYNC(vp->linkHandle);
3570 #endif /* AFS_NT40_ENV */
3573 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
3574 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
3575 IH_RELEASE(vp->diskDataHandle);
3576 IH_RELEASE(vp->linkHandle);
3578 #ifdef AFS_DEMAND_ATTACH_FS
3580 VChangeState_r(vp, state_save);
3585 /***************************************************/
3586 /* Volume write and fsync routines */
3587 /***************************************************/
3590 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
3592 #ifdef AFS_DEMAND_ATTACH_FS
3593 VolState state_save;
3595 if (flags & VOL_UPDATE_WAIT) {
3596 VCreateReservation_r(vp);
3597 VWaitExclusiveState_r(vp);
3602 if (programType == fileServer)
3604 (V_inUse(vp) ? V_nextVnodeUnique(vp) +
3605 200 : V_nextVnodeUnique(vp));
3607 #ifdef AFS_DEMAND_ATTACH_FS
3608 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
3612 WriteVolumeHeader_r(ec, vp);
3614 #ifdef AFS_DEMAND_ATTACH_FS
3616 VChangeState_r(vp, state_save);
3617 if (flags & VOL_UPDATE_WAIT) {
3618 VCancelReservation_r(vp);
3623 Log("VUpdateVolume: error updating volume header, volume %u (%s)\n",
3624 V_id(vp), V_name(vp));
3625 /* try to update on-disk header,
3626 * while preventing infinite recursion */
3627 if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
3628 VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
3634 VUpdateVolume(Error * ec, Volume * vp)
3637 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
3642 VSyncVolume_r(Error * ec, Volume * vp, int flags)
3646 #ifdef AFS_DEMAND_ATTACH_FS
3647 VolState state_save;
3650 if (flags & VOL_SYNC_WAIT) {
3651 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
3653 VUpdateVolume_r(ec, vp, 0);
3656 #ifdef AFS_DEMAND_ATTACH_FS
3657 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
3660 fdP = IH_OPEN(V_diskDataHandle(vp));
3661 assert(fdP != NULL);
3662 code = FDH_SYNC(fdP);
3665 #ifdef AFS_DEMAND_ATTACH_FS
3667 VChangeState_r(vp, state_save);
3673 VSyncVolume(Error * ec, Volume * vp)
3676 VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
3681 /***************************************************/
3682 /* Volume dealloaction routines */
3683 /***************************************************/
3685 #ifdef AFS_DEMAND_ATTACH_FS
3687 FreeVolume(Volume * vp)
3689 /* free the heap space, iff it's safe.
3690 * otherwise, pull it out of the hash table, so it
3691 * will get deallocated when all refs to it go away */
3692 if (!VCheckFree(vp)) {
3693 DeleteVolumeFromHashTable(vp);
3694 DeleteVolumeFromVByPList_r(vp);
3696 /* make sure we invalidate the header cache entry */
3697 FreeVolumeHeader(vp);
3700 #endif /* AFS_DEMAND_ATTACH_FS */
3703 ReallyFreeVolume(Volume * vp)
3708 #ifdef AFS_DEMAND_ATTACH_FS
3710 VChangeState_r(vp, VOL_STATE_FREED);
3711 if (vp->pending_vol_op)
3712 free(vp->pending_vol_op);
3713 #endif /* AFS_DEMAND_ATTACH_FS */
3714 for (i = 0; i < nVNODECLASSES; i++)
3715 if (vp->vnodeIndex[i].bitmap)
3716 free(vp->vnodeIndex[i].bitmap);
3717 FreeVolumeHeader(vp);
3718 #ifndef AFS_DEMAND_ATTACH_FS
3719 DeleteVolumeFromHashTable(vp);
3720 #endif /* AFS_DEMAND_ATTACH_FS */
3724 /* check to see if we should shutdown this volume
3725 * returns 1 if volume was freed, 0 otherwise */
3726 #ifdef AFS_DEMAND_ATTACH_FS
3728 VCheckDetach(register Volume * vp)
3733 if (vp->nUsers || vp->nWaiters)
3736 if (vp->shuttingDown) {
3738 if ((programType != fileServer) &&
3739 (V_inUse(vp) == programType) &&
3740 ((V_checkoutMode(vp) == V_VOLUPD) ||
3741 (V_checkoutMode(vp) == V_SECRETLY) ||
3742 ((V_checkoutMode(vp) == V_CLONE) &&
3743 (VolumeWriteable(vp))))) {
3745 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
3747 Log("VCheckDetach: volume header update for volume %u "
3748 "failed with errno %d\n", vp->hashid, errno);
3751 VReleaseVolumeHandles_r(vp);
3753 ReallyFreeVolume(vp);
3754 if (programType == fileServer) {
3755 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3760 #else /* AFS_DEMAND_ATTACH_FS */
3762 VCheckDetach(register Volume * vp)
3770 if (vp->shuttingDown) {
3772 if ((programType != fileServer) &&
3773 (V_inUse(vp) == programType) &&
3774 ((V_checkoutMode(vp) == V_VOLUPD) ||
3775 (V_checkoutMode(vp) == V_SECRETLY) ||
3776 ((V_checkoutMode(vp) == V_CLONE) &&
3777 (VolumeWriteable(vp))))) {
3779 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
3781 Log("VCheckDetach: volume header update for volume %u failed with errno %d\n",
3785 VReleaseVolumeHandles_r(vp);
3786 ReallyFreeVolume(vp);
3787 if (programType == fileServer) {
3788 #if defined(AFS_PTHREAD_ENV)
3789 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3790 #else /* AFS_PTHREAD_ENV */
3791 LWP_NoYieldSignal(VPutVolume);
3792 #endif /* AFS_PTHREAD_ENV */
3797 #endif /* AFS_DEMAND_ATTACH_FS */
3799 /* check to see if we should offline this volume
3800 * return 1 if volume went offline, 0 otherwise */
3801 #ifdef AFS_DEMAND_ATTACH_FS
3803 VCheckOffline(register Volume * vp)
3807 if (vp->goingOffline && !vp->nUsers) {
3809 assert(programType == fileServer);
3810 assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
3811 (V_attachState(vp) != VOL_STATE_FREED) &&
3812 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
3813 (V_attachState(vp) != VOL_STATE_UNATTACHED));
3817 * VOL_STATE_GOING_OFFLINE
3818 * VOL_STATE_SHUTTING_DOWN
3819 * VIsErrorState(V_attachState(vp))
3820 * VIsExclusiveState(V_attachState(vp))
3823 VCreateReservation_r(vp);
3824 VChangeState_r(vp, VOL_STATE_OFFLINING);
3827 /* must clear the goingOffline flag before we drop the glock */
3828 vp->goingOffline = 0;
3833 /* perform async operations */
3834 VUpdateVolume_r(&error, vp, 0);
3835 VCloseVolumeHandles_r(vp);
3838 if (V_offlineMessage(vp)[0]) {
3839 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
3840 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
3841 V_offlineMessage(vp));
3843 Log("VOffline: Volume %lu (%s) is now offline\n",
3844 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
3848 /* invalidate the volume header cache entry */
3849 FreeVolumeHeader(vp);
3851 /* if nothing changed state to error or salvaging,
3852 * drop state to unattached */
3853 if (!VIsErrorState(V_attachState(vp))) {
3854 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3856 VCancelReservation_r(vp);
3857 /* no usage of vp is safe beyond this point */
3861 #else /* AFS_DEMAND_ATTACH_FS */
3863 VCheckOffline(register Volume * vp)
3867 if (vp->goingOffline && !vp->nUsers) {
3869 assert(programType == fileServer);
3872 vp->goingOffline = 0;
3874 VUpdateVolume_r(&error, vp, 0);
3875 VCloseVolumeHandles_r(vp);
3877 Log("VOffline: Volume %u (%s) is now offline", V_id(vp),
3879 if (V_offlineMessage(vp)[0])
3880 Log(" (%s)", V_offlineMessage(vp));
3883 FreeVolumeHeader(vp);
3884 #ifdef AFS_PTHREAD_ENV
3885 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3886 #else /* AFS_PTHREAD_ENV */
3887 LWP_NoYieldSignal(VPutVolume);
3888 #endif /* AFS_PTHREAD_ENV */
3892 #endif /* AFS_DEMAND_ATTACH_FS */
3894 /***************************************************/
3895 /* demand attach fs ref counting routines */
3896 /***************************************************/
3898 #ifdef AFS_DEMAND_ATTACH_FS
3899 /* the following two functions handle reference counting for
3900 * asynchronous operations on volume structs.
3902 * their purpose is to prevent a VDetachVolume or VShutdown
3903 * from free()ing the Volume struct during an async i/o op */
3905 /* register with the async volume op ref counter */
3906 /* VCreateReservation_r moved into inline code header because it
3907 * is now needed in vnode.c -- tkeiser 11/20/2007
3911 * decrement volume-package internal refcount.
3913 * @param vp volume object pointer
3915 * @internal volume package internal use only
3918 * @arg VOL_LOCK is held
3919 * @arg lightweight refcount held
3921 * @post volume waiters refcount is decremented; volume may
3922 * have been deallocated/shutdown/offlined/salvaged/
3923 * whatever during the process
3925 * @warning once you have tossed your last reference (you can acquire
3926 * lightweight refs recursively) it is NOT SAFE to reference
3927 * a volume object pointer ever again
3929 * @see VCreateReservation_r
3931 * @note DEMAND_ATTACH_FS only
3934 VCancelReservation_r(Volume * vp)
3936 assert(--vp->nWaiters >= 0);
3937 if (vp->nWaiters == 0) {
3939 if (!VCheckDetach(vp)) {
3946 /* check to see if we should free this volume now
3947 * return 1 if volume was freed, 0 otherwise */
3949 VCheckFree(Volume * vp)
3952 if ((vp->nUsers == 0) &&
3953 (vp->nWaiters == 0) &&
3954 !(V_attachFlags(vp) & (VOL_IN_HASH |
3958 ReallyFreeVolume(vp);
3963 #endif /* AFS_DEMAND_ATTACH_FS */
3966 /***************************************************/
3967 /* online volume operations routines */
3968 /***************************************************/
3970 #ifdef AFS_DEMAND_ATTACH_FS
3972 * register a volume operation on a given volume.
3974 * @param[in] vp volume object
3975 * @param[in] vopinfo volume operation info object
3977 * @pre VOL_LOCK is held
3979 * @post volume operation info object attached to volume object.
3980 * volume operation statistics updated.
3982 * @note by "attached" we mean a copy of the passed in object is made
3984 * @internal volume package internal use only
3987 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3989 FSSYNC_VolOp_info * info;
3991 /* attach a vol op info node to the volume struct */
3992 info = (FSSYNC_VolOp_info *) malloc(sizeof(FSSYNC_VolOp_info));
3993 assert(info != NULL);
3994 memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
3995 vp->pending_vol_op = info;
3998 vp->stats.last_vol_op = FT_ApproxTime();
3999 vp->stats.vol_ops++;
4000 IncUInt64(&VStats.vol_ops);
4006 * deregister the volume operation attached to this volume.
4008 * @param[in] vp volume object pointer
4010 * @pre VOL_LOCK is held
4012 * @post the volume operation info object is detached from the volume object
4014 * @internal volume package internal use only
4017 VDeregisterVolOp_r(Volume * vp)
4019 if (vp->pending_vol_op) {
4020 free(vp->pending_vol_op);
4021 vp->pending_vol_op = NULL;
4025 #endif /* AFS_DEMAND_ATTACH_FS */
4028 * determine whether it is safe to leave a volume online during
4029 * the volume operation described by the vopinfo object.
4031 * @param[in] vp volume object
4032 * @param[in] vopinfo volume operation info object
4034 * @return whether it is safe to leave volume online
4035 * @retval 0 it is NOT SAFE to leave the volume online
4036 * @retval 1 it is safe to leave the volume online during the operation
4039 * @arg VOL_LOCK is held
4040 * @arg disk header attached to vp (heavyweight ref on vp will guarantee
4041 * this condition is met)
4043 * @internal volume package internal use only
4046 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4048 return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
4049 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4050 (vopinfo->com.reason == V_READONLY ||
4051 (!VolumeWriteable(vp) &&
4052 (vopinfo->com.reason == V_CLONE ||
4053 vopinfo->com.reason == V_DUMP)))));
4057 * determine whether VBUSY should be set during this volume operation.
4059 * @param[in] vp volume object
4060 * @param[in] vopinfo volume operation info object
4062 * @return whether VBUSY should be set
4063 * @retval 0 VBUSY does NOT need to be set
4064 * @retval 1 VBUSY SHOULD be set
4066 * @pre VOL_LOCK is held
4068 * @internal volume package internal use only
4071 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4073 return ((vopinfo->com.command == FSYNC_VOL_OFF &&
4074 vopinfo->com.reason == FSYNC_SALVAGE) ||
4075 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4076 (vopinfo->com.reason == V_CLONE ||
4077 vopinfo->com.reason == V_DUMP)));
4081 /***************************************************/
4082 /* online salvager routines */
4083 /***************************************************/
4084 #if defined(AFS_DEMAND_ATTACH_FS)
4086 * check whether a salvage needs to be performed on this volume.
4088 * @param[in] vp pointer to volume object
4090 * @return status code
4091 * @retval 0 no salvage scheduled
4092 * @retval 1 a salvage has been scheduled with the salvageserver
4094 * @pre VOL_LOCK is held
4096 * @post if salvage request flag is set and nUsers and nWaiters are zero,
4097 * then a salvage will be requested
4099 * @note this is one of the event handlers called by VCancelReservation_r
4101 * @see VCancelReservation_r
4103 * @internal volume package internal use only.
4106 VCheckSalvage(register Volume * vp)
4109 #ifdef SALVSYNC_BUILD_CLIENT
4110 if (vp->nUsers || vp->nWaiters)
4112 if (vp->salvage.requested) {
4113 VScheduleSalvage_r(vp);
4116 #endif /* SALVSYNC_BUILD_CLIENT */
4121 * request volume salvage.
4123 * @param[out] ec computed client error code
4124 * @param[in] vp volume object pointer
4125 * @param[in] reason reason code (passed to salvageserver via SALVSYNC)
4126 * @param[in] flags see flags note below
4129 * VOL_SALVAGE_INVALIDATE_HEADER causes volume header cache entry
4130 * to be invalidated.
4132 * @pre VOL_LOCK is held.
4134 * @post volume state is changed.
4135 * for fileserver, salvage will be requested once refcount reaches zero.
4137 * @return operation status code
4138 * @retval 0 volume salvage will occur
4139 * @retval 1 volume salvage could not be scheduled
4141 * @note DAFS fileserver only
4143 * @note this call does not synchronously schedule a volume salvage. rather,
4144 * it sets volume state so that when volume refcounts reach zero, a
4145 * volume salvage will occur. by "refcounts", we mean both nUsers and
4146 * nWaiters must be zero.
4148 * @internal volume package internal use only.
4151 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
4155 * for DAFS volume utilities, transition to error state
4156 * (at some point in the future, we should consider
4157 * making volser talk to salsrv)
4159 if (!VCanScheduleSalvage()) {
4160 VChangeState_r(vp, VOL_STATE_ERROR);
4165 if (programType != fileServer) {
4166 #ifdef FSSYNC_BUILD_CLIENT
4167 if (VCanUseFSSYNC()) {
4169 * If we aren't the fileserver, tell the fileserver the volume
4170 * needs to be salvaged. We could directly tell the
4171 * salvageserver, but the fileserver keeps track of some stats
4172 * related to salvages, and handles some other salvage-related
4173 * complications for us.
4177 * You might wonder why we don't check for
4178 * VIsSalvager(V_inUse(vp)) here, since we do check for that
4179 * in the fileServer case (below). The reason is that the
4180 * below check is done since the fileServer can't tell if a
4181 * salvage is still running or not when V_inUse refers to a
4182 * salvaging program. However, if we are a non-fileserver,
4183 * to get here we must have checked out the volume from the
4184 * fileserver and locked the partition, meaning there must
4185 * be no salvager running; so we just always try to salvage
4188 code = FSYNC_VolOp(vp->hashid, vp->partition->name,
4189 FSYNC_VOL_FORCE_ERROR, FSYNC_SALVAGE, NULL);
4190 if (code == SYNC_OK) {
4194 Log("VRequestSalvage: force error salvage state of volume %u"
4195 " denied by fileserver\n", vp->hashid);
4197 /* fall through to error condition below */
4199 #endif /* FSSYNC_BUILD_CLIENT */
4200 VChangeState_r(vp, VOL_STATE_ERROR);
4205 if (!vp->salvage.requested) {
4206 vp->salvage.requested = 1;
4207 vp->salvage.reason = reason;
4208 vp->stats.last_salvage = FT_ApproxTime();
4210 if (vp->header && VIsSalvager(V_inUse(vp))) {
4211 /* Right now we can't tell for sure if this indicates a
4212 * salvage is running, or if a running salvage crashed, so
4213 * we always ERROR the volume in case a salvage is running.
4214 * Once we get rid of the partition lock and instead lock
4215 * individual volume header files for salvages, we will
4216 * probably be able to tell if a salvage is running, and we
4217 * can do away with this behavior. */
4218 Log("VRequestSalvage: volume %u appears to be salvaging, but we\n", vp->hashid);
4219 Log(" didn't request a salvage. Forcing it offline waiting for the\n");
4220 Log(" salvage to finish; if you are sure no salvage is running,\n");
4221 Log(" run a salvage manually.\n");
4223 /* make sure neither VScheduleSalvage_r nor
4224 * VUpdateSalvagePriority_r try to schedule another salvage */
4225 vp->salvage.requested = vp->salvage.scheduled = 0;
4227 /* these stats aren't correct, but doing this makes them
4228 * slightly closer to being correct */
4229 vp->stats.salvages++;
4230 vp->stats.last_salvage_req = FT_ApproxTime();
4231 IncUInt64(&VStats.salvages);
4233 VChangeState_r(vp, VOL_STATE_ERROR);
4237 } else if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
4238 VChangeState_r(vp, VOL_STATE_SALVAGING);
4241 Log("VRequestSalvage: volume %u online salvaged too many times; forced offline.\n", vp->hashid);
4243 /* make sure neither VScheduleSalvage_r nor
4244 * VUpdateSalvagePriority_r try to schedule another salvage */
4245 vp->salvage.requested = vp->salvage.scheduled = 0;
4247 VChangeState_r(vp, VOL_STATE_ERROR);
4251 if (flags & VOL_SALVAGE_INVALIDATE_HEADER) {
4252 /* Instead of ReleaseVolumeHeader, we do FreeVolumeHeader()
4253 so that the the next VAttachVolumeByVp_r() invocation
4254 of attach2() will pull in a cached header
4255 entry and fail, then load a fresh one from disk and attach
4258 FreeVolumeHeader(vp);
4265 * update salvageserver scheduling priority for a volume.
4267 * @param[in] vp pointer to volume object
4269 * @return operation status
4271 * @retval 1 request denied, or SALVSYNC communications failure
4273 * @pre VOL_LOCK is held.
4275 * @post in-core salvage priority counter is incremented. if at least
4276 * SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
4277 * last SALVSYNC_RAISEPRIO request, we contact the salvageserver
4278 * to update its priority queue. if no salvage is scheduled,
4279 * this function is a no-op.
4281 * @note DAFS fileserver only
4283 * @note this should be called whenever a VGetVolume fails due to a
4284 * pending salvage request
4286 * @todo should set exclusive state and drop glock around salvsync call
4288 * @internal volume package internal use only.
4291 VUpdateSalvagePriority_r(Volume * vp)
4295 #ifdef SALVSYNC_BUILD_CLIENT
4300 now = FT_ApproxTime();
4302 /* update the salvageserver priority queue occasionally so that
4303 * frequently requested volumes get moved to the head of the queue
4305 if ((vp->salvage.scheduled) &&
4306 (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
4307 code = SALVSYNC_SalvageVolume(vp->hashid,
4308 VPartitionPath(vp->partition),
4313 vp->stats.last_salvage_req = now;
4314 if (code != SYNC_OK) {
4318 #endif /* SALVSYNC_BUILD_CLIENT */
4323 #ifdef SALVSYNC_BUILD_CLIENT
4325 * schedule a salvage with the salvage server.
4327 * @param[in] vp pointer to volume object
4329 * @return operation status
4330 * @retval 0 salvage scheduled successfully
4331 * @retval 1 salvage not scheduled, or SALVSYNC com error
4334 * @arg VOL_LOCK is held.
4335 * @arg nUsers and nWaiters should be zero.
4337 * @post salvageserver is sent a salvage request
4339 * @note DAFS fileserver only
4341 * @internal volume package internal use only.
4344 VScheduleSalvage_r(Volume * vp)
4348 VolState state_save;
4349 VThreadOptions_t * thread_opts;
4352 if (vp->nWaiters || vp->nUsers) {
4356 /* prevent endless salvage,attach,salvage,attach,... loops */
4357 if (vp->stats.salvages >= SALVAGE_COUNT_MAX)
4361 * don't perform salvsync ops on certain threads
4363 thread_opts = pthread_getspecific(VThread_key);
4364 if (thread_opts == NULL) {
4365 thread_opts = &VThread_defaults;
4367 if (thread_opts->disallow_salvsync || vol_disallow_salvsync) {
4372 * XXX the scheduling process should really be done asynchronously
4373 * to avoid fssync deadlocks
4375 if (!vp->salvage.scheduled) {
4376 /* if we haven't previously scheduled a salvage, do so now
4378 * set the volume to an exclusive state and drop the lock
4379 * around the SALVSYNC call
4381 * note that we do NOT acquire a reservation here -- doing so
4382 * could result in unbounded recursion
4384 strlcpy(partName, VPartitionPath(vp->partition), sizeof(partName));
4385 state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
4388 /* can't use V_id() since there's no guarantee
4389 * we have the disk data header at this point */
4390 code = SALVSYNC_SalvageVolume(vp->hashid,
4397 VChangeState_r(vp, state_save);
4399 if (code == SYNC_OK) {
4400 vp->salvage.scheduled = 1;
4401 vp->stats.salvages++;
4402 vp->stats.last_salvage_req = FT_ApproxTime();
4403 IncUInt64(&VStats.salvages);
4407 case SYNC_BAD_COMMAND:
4408 case SYNC_COM_ERROR:
4411 Log("VScheduleSalvage_r: SALVSYNC request denied\n");
4414 Log("VScheduleSalvage_r: SALVSYNC unknown protocol error\n");
4423 * connect to the salvageserver SYNC service.
4425 * @return operation status
4429 * @post connection to salvageserver SYNC service established
4431 * @see VConnectSALV_r
4432 * @see VDisconnectSALV
4433 * @see VReconnectSALV
4440 retVal = VConnectSALV_r();
4446 * connect to the salvageserver SYNC service.
4448 * @return operation status
4452 * @pre VOL_LOCK is held.
4454 * @post connection to salvageserver SYNC service established
4457 * @see VDisconnectSALV_r
4458 * @see VReconnectSALV_r
4459 * @see SALVSYNC_clientInit
4461 * @internal volume package internal use only.
4464 VConnectSALV_r(void)
4466 return SALVSYNC_clientInit();
4470 * disconnect from the salvageserver SYNC service.
4472 * @return operation status
4475 * @pre client should have a live connection to the salvageserver
4477 * @post connection to salvageserver SYNC service destroyed
4479 * @see VDisconnectSALV_r
4481 * @see VReconnectSALV
4484 VDisconnectSALV(void)
4487 VDisconnectSALV_r();
4493 * disconnect from the salvageserver SYNC service.
4495 * @return operation status
4499 * @arg VOL_LOCK is held.
4500 * @arg client should have a live connection to the salvageserver.
4502 * @post connection to salvageserver SYNC service destroyed
4504 * @see VDisconnectSALV
4505 * @see VConnectSALV_r
4506 * @see VReconnectSALV_r
4507 * @see SALVSYNC_clientFinis
4509 * @internal volume package internal use only.
4512 VDisconnectSALV_r(void)
4514 return SALVSYNC_clientFinis();
4518 * disconnect and then re-connect to the salvageserver SYNC service.
4520 * @return operation status
4524 * @pre client should have a live connection to the salvageserver
4526 * @post old connection is dropped, and a new one is established
4529 * @see VDisconnectSALV
4530 * @see VReconnectSALV_r
4533 VReconnectSALV(void)
4537 retVal = VReconnectSALV_r();
4543 * disconnect and then re-connect to the salvageserver SYNC service.
4545 * @return operation status
4550 * @arg VOL_LOCK is held.
4551 * @arg client should have a live connection to the salvageserver.
4553 * @post old connection is dropped, and a new one is established
4555 * @see VConnectSALV_r
4556 * @see VDisconnectSALV
4557 * @see VReconnectSALV
4558 * @see SALVSYNC_clientReconnect
4560 * @internal volume package internal use only.
4563 VReconnectSALV_r(void)
4565 return SALVSYNC_clientReconnect();
4567 #endif /* SALVSYNC_BUILD_CLIENT */
4568 #endif /* AFS_DEMAND_ATTACH_FS */
4571 /***************************************************/
4572 /* FSSYNC routines */
4573 /***************************************************/
4575 /* This must be called by any volume utility which needs to run while the
4576 file server is also running. This is separated from VInitVolumePackage2 so
4577 that a utility can fork--and each of the children can independently
4578 initialize communication with the file server */
4579 #ifdef FSSYNC_BUILD_CLIENT
4581 * connect to the fileserver SYNC service.
4583 * @return operation status
4588 * @arg VInit must equal 2.
4589 * @arg Program Type must not be fileserver or salvager.
4591 * @post connection to fileserver SYNC service established
4594 * @see VDisconnectFS
4595 * @see VChildProcReconnectFS
4602 retVal = VConnectFS_r();
4608 * connect to the fileserver SYNC service.
4610 * @return operation status
4615 * @arg VInit must equal 2.
4616 * @arg Program Type must not be fileserver or salvager.
4617 * @arg VOL_LOCK is held.
4619 * @post connection to fileserver SYNC service established
4622 * @see VDisconnectFS_r
4623 * @see VChildProcReconnectFS_r
4625 * @internal volume package internal use only.
4631 assert((VInit == 2) &&
4632 (programType != fileServer) &&
4633 (programType != salvager));
4634 rc = FSYNC_clientInit();
4641 * disconnect from the fileserver SYNC service.
4644 * @arg client should have a live connection to the fileserver.
4645 * @arg VOL_LOCK is held.
4646 * @arg Program Type must not be fileserver or salvager.
4648 * @post connection to fileserver SYNC service destroyed
4650 * @see VDisconnectFS
4652 * @see VChildProcReconnectFS_r
4654 * @internal volume package internal use only.
4657 VDisconnectFS_r(void)
4659 assert((programType != fileServer) &&
4660 (programType != salvager));
4661 FSYNC_clientFinis();
4666 * disconnect from the fileserver SYNC service.
4669 * @arg client should have a live connection to the fileserver.
4670 * @arg Program Type must not be fileserver or salvager.
4672 * @post connection to fileserver SYNC service destroyed
4674 * @see VDisconnectFS_r
4676 * @see VChildProcReconnectFS
4687 * connect to the fileserver SYNC service from a child process following a fork.
4689 * @return operation status
4694 * @arg VOL_LOCK is held.
4695 * @arg current FSYNC handle is shared with a parent process
4697 * @post current FSYNC handle is discarded and a new connection to the
4698 * fileserver SYNC service is established
4700 * @see VChildProcReconnectFS
4702 * @see VDisconnectFS_r
4704 * @internal volume package internal use only.
4707 VChildProcReconnectFS_r(void)
4709 return FSYNC_clientChildProcReconnect();
4713 * connect to the fileserver SYNC service from a child process following a fork.
4715 * @return operation status
4719 * @pre current FSYNC handle is shared with a parent process
4721 * @post current FSYNC handle is discarded and a new connection to the
4722 * fileserver SYNC service is established
4724 * @see VChildProcReconnectFS_r
4726 * @see VDisconnectFS
4729 VChildProcReconnectFS(void)
4733 ret = VChildProcReconnectFS_r();
4737 #endif /* FSSYNC_BUILD_CLIENT */
4740 /***************************************************/
4741 /* volume bitmap routines */
4742 /***************************************************/
4745 * For demand attach fs, flags parameter controls
4746 * locking behavior. If (flags & VOL_ALLOC_BITMAP_WAIT)
4747 * is set, then this function will create a reservation
4748 * and block on any other exclusive operations. Otherwise,
4749 * this function assumes the caller already has exclusive
4750 * access to vp, and we just change the volume state.
4753 VAllocBitmapEntry_r(Error * ec, Volume * vp,
4754 struct vnodeIndex *index, int flags)
4757 register byte *bp, *ep;
4758 #ifdef AFS_DEMAND_ATTACH_FS
4759 VolState state_save;
4760 #endif /* AFS_DEMAND_ATTACH_FS */
4764 /* This test is probably redundant */
4765 if (!VolumeWriteable(vp)) {
4766 *ec = (bit32) VREADONLY;
4770 #ifdef AFS_DEMAND_ATTACH_FS
4771 if (flags & VOL_ALLOC_BITMAP_WAIT) {
4772 VCreateReservation_r(vp);
4773 VWaitExclusiveState_r(vp);
4775 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
4776 #endif /* AFS_DEMAND_ATTACH_FS */
4779 if ((programType == fileServer) && !index->bitmap) {
4781 #ifndef AFS_DEMAND_ATTACH_FS
4782 /* demand attach fs uses the volume state to avoid races.
4783 * specialStatus field is not used at all */
4785 if (vp->specialStatus == VBUSY) {
4786 if (vp->goingOffline) { /* vos dump waiting for the volume to
4787 * go offline. We probably come here
4788 * from AddNewReadableResidency */
4791 while (vp->specialStatus == VBUSY) {
4792 #ifdef AFS_PTHREAD_ENV
4796 #else /* !AFS_PTHREAD_ENV */
4798 #endif /* !AFS_PTHREAD_ENV */
4802 #endif /* !AFS_DEMAND_ATTACH_FS */
4804 if (!index->bitmap) {
4805 #ifndef AFS_DEMAND_ATTACH_FS
4806 vp->specialStatus = VBUSY; /* Stop anyone else from using it. */
4807 #endif /* AFS_DEMAND_ATTACH_FS */
4808 for (i = 0; i < nVNODECLASSES; i++) {
4809 VGetBitmap_r(ec, vp, i);
4811 #ifdef AFS_DEMAND_ATTACH_FS
4812 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
4813 #else /* AFS_DEMAND_ATTACH_FS */
4814 DeleteVolumeFromHashTable(vp);
4815 vp->shuttingDown = 1; /* Let who has it free it. */
4816 vp->specialStatus = 0;
4817 #endif /* AFS_DEMAND_ATTACH_FS */
4822 #ifndef AFS_DEMAND_ATTACH_FS
4824 vp->specialStatus = 0; /* Allow others to have access. */
4825 #endif /* AFS_DEMAND_ATTACH_FS */
4828 #endif /* BITMAP_LATER */
4830 #ifdef AFS_DEMAND_ATTACH_FS
4832 #endif /* AFS_DEMAND_ATTACH_FS */
4833 bp = index->bitmap + index->bitmapOffset;
4834 ep = index->bitmap + index->bitmapSize;
4836 if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
4838 index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
4841 o = ffs(~*bp) - 1; /* ffs is documented in BSTRING(3) */
4843 ret = (VnodeId) ((bp - index->bitmap) * 8 + o);
4844 #ifdef AFS_DEMAND_ATTACH_FS
4846 #endif /* AFS_DEMAND_ATTACH_FS */
4849 bp += sizeof(bit32) /* i.e. 4 */ ;
4851 /* No bit map entry--must grow bitmap */
4853 realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
4856 bp += index->bitmapSize;
4857 memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
4858 index->bitmapOffset = index->bitmapSize;
4859 index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
4861 ret = index->bitmapOffset * 8;
4862 #ifdef AFS_DEMAND_ATTACH_FS
4864 #endif /* AFS_DEMAND_ATTACH_FS */
4867 #ifdef AFS_DEMAND_ATTACH_FS
4868 VChangeState_r(vp, state_save);
4869 if (flags & VOL_ALLOC_BITMAP_WAIT) {
4870 VCancelReservation_r(vp);
4872 #endif /* AFS_DEMAND_ATTACH_FS */
4877 VAllocBitmapEntry(Error * ec, Volume * vp, register struct vnodeIndex * index)
4881 retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
4887 VFreeBitMapEntry_r(Error * ec, register struct vnodeIndex *index,
4890 unsigned int offset;
4896 #endif /* BITMAP_LATER */
4897 offset = bitNumber >> 3;
4898 if (offset >= index->bitmapSize) {
4902 if (offset < index->bitmapOffset)
4903 index->bitmapOffset = offset & ~3; /* Truncate to nearest bit32 */
4904 *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
4908 VFreeBitMapEntry(Error * ec, register struct vnodeIndex *index,
4912 VFreeBitMapEntry_r(ec, index, bitNumber);
4916 /* this function will drop the glock internally.
4917 * for old pthread fileservers, this is safe thanks to vbusy.
4919 * for demand attach fs, caller must have already called
4920 * VCreateReservation_r and VWaitExclusiveState_r */
4922 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
4924 StreamHandle_t *file;
4927 struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
4928 struct vnodeIndex *vip = &vp->vnodeIndex[class];
4929 struct VnodeDiskObject *vnode;
4930 unsigned int unique = 0;
4934 #endif /* BITMAP_LATER */
4935 #ifdef AFS_DEMAND_ATTACH_FS
4936 VolState state_save;
4937 #endif /* AFS_DEMAND_ATTACH_FS */
4941 #ifdef AFS_DEMAND_ATTACH_FS
4942 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
4943 #endif /* AFS_DEMAND_ATTACH_FS */
4946 fdP = IH_OPEN(vip->handle);
4947 assert(fdP != NULL);
4948 file = FDH_FDOPEN(fdP, "r");
4949 assert(file != NULL);
4950 vnode = (VnodeDiskObject *) malloc(vcp->diskSize);
4951 assert(vnode != NULL);
4952 size = OS_SIZE(fdP->fd_fd);
4954 nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
4956 vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4; /* The 10 is a little extra so
4957 * a few files can be created in this volume,
4958 * the whole thing is rounded up to nearest 4
4959 * bytes, because the bit map allocator likes
4962 BitMap = (byte *) calloc(1, vip->bitmapSize);
4963 assert(BitMap != NULL);
4964 #else /* BITMAP_LATER */
4965 vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
4966 assert(vip->bitmap != NULL);
4967 vip->bitmapOffset = 0;
4968 #endif /* BITMAP_LATER */
4969 if (STREAM_SEEK(file, vcp->diskSize, 0) != -1) {
4971 for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
4972 if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
4974 if (vnode->type != vNull) {
4975 if (vnode->vnodeMagic != vcp->magic) {
4976 Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
4981 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
4982 #else /* BITMAP_LATER */
4983 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
4984 #endif /* BITMAP_LATER */
4985 if (unique <= vnode->uniquifier)
4986 unique = vnode->uniquifier + 1;
4988 #ifndef AFS_PTHREAD_ENV
4989 if ((bitNumber & 0x00ff) == 0x0ff) { /* every 256 iterations */
4992 #endif /* !AFS_PTHREAD_ENV */
4995 if (vp->nextVnodeUnique < unique) {
4996 Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
4999 /* Paranoia, partly justified--I think fclose after fdopen
5000 * doesn't seem to close fd. In any event, the documentation
5001 * doesn't specify, so it's safer to close it twice.
5009 /* There may have been a racing condition with some other thread, both
5010 * creating the bitmaps for this volume. If the other thread was faster
5011 * the pointer to bitmap should already be filled and we can free ours.
5013 if (vip->bitmap == NULL) {
5014 vip->bitmap = BitMap;
5015 vip->bitmapOffset = 0;
5017 free((byte *) BitMap);
5018 #endif /* BITMAP_LATER */
5019 #ifdef AFS_DEMAND_ATTACH_FS
5020 VChangeState_r(vp, state_save);
5021 #endif /* AFS_DEMAND_ATTACH_FS */
5025 /***************************************************/
5026 /* Volume Path and Volume Number utility routines */
5027 /***************************************************/
5030 * find the first occurrence of a volume header file and return the path.
5032 * @param[out] ec outbound error code
5033 * @param[in] volumeId volume id to find
5034 * @param[out] partitionp pointer to disk partition path string
5035 * @param[out] namep pointer to volume header file name string
5037 * @post path to first occurrence of volume header is returned in partitionp
5038 * and namep, or ec is set accordingly.
5040 * @warning this function is NOT re-entrant -- partitionp and namep point to
5041 * static data segments
5043 * @note if a volume utility inadvertently leaves behind a stale volume header
5044 * on a vice partition, it is possible for callers to get the wrong one,
5045 * depending on the order of the disk partition linked list.
5049 VGetVolumePath(Error * ec, VolId volumeId, char **partitionp, char **namep)
5051 static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
5052 char path[VMAXPATHLEN];
5054 struct DiskPartition64 *dp;
5058 (void)afs_snprintf(&name[1], (sizeof name) - 1, VFORMAT, afs_printable_uint32_lu(volumeId));
5059 for (dp = DiskPartitionList; dp; dp = dp->next) {
5060 struct afs_stat status;
5061 strcpy(path, VPartitionPath(dp));
5063 if (afs_stat(path, &status) == 0) {
5064 strcpy(partition, dp->name);
5071 *partitionp = *namep = NULL;
5073 *partitionp = partition;
5079 * extract a volume number from a volume header filename string.
5081 * @param[in] name volume header filename string
5083 * @return volume number
5085 * @note the string must be of the form VFORMAT. the only permissible
5086 * deviation is a leading '/' character.
5091 VolumeNumber(char *name)
5095 return atoi(name + 1);
5099 * compute the volume header filename.
5101 * @param[in] volumeId
5103 * @return volume header filename
5105 * @post volume header filename string is constructed
5107 * @warning this function is NOT re-entrant -- the returned string is
5108 * stored in a static char array. see VolumeExternalName_r
5109 * for a re-entrant equivalent.
5111 * @see VolumeExternalName_r
5113 * @deprecated due to the above re-entrancy warning, this interface should
5114 * be considered deprecated. Please use VolumeExternalName_r
5118 VolumeExternalName(VolumeId volumeId)
5120 static char name[VMAXPATHLEN];
5121 (void)afs_snprintf(name, sizeof name, VFORMAT, afs_printable_uint32_lu(volumeId));
5126 * compute the volume header filename.
5128 * @param[in] volumeId
5129 * @param[inout] name array in which to store filename
5130 * @param[in] len length of name array
5132 * @return result code from afs_snprintf
5134 * @see VolumeExternalName
5137 * @note re-entrant equivalent of VolumeExternalName
5140 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
5142 return afs_snprintf(name, len, VFORMAT, afs_printable_uint32_lu(volumeId));
5146 /***************************************************/
5147 /* Volume Usage Statistics routines */
5148 /***************************************************/
5150 #if OPENAFS_VOL_STATS
5151 #define OneDay (86400) /* 24 hours' worth of seconds */
5153 #define OneDay (24*60*60) /* 24 hours */
5154 #endif /* OPENAFS_VOL_STATS */
5157 Midnight(time_t t) {
5158 struct tm local, *l;
5161 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
5162 l = localtime_r(&t, &local);
5168 /* the following is strictly speaking problematic on the
5169 switching day to daylight saving time, after the switch,
5170 as tm_isdst does not match. Similarly, on the looong day when
5171 switching back the OneDay check will not do what naively expected!
5172 The effects are minor, though, and more a matter of interpreting
5174 #ifndef AFS_PTHREAD_ENV
5177 local.tm_hour = local.tm_min=local.tm_sec = 0;
5178 midnight = mktime(&local);
5179 if (midnight != (time_t) -1) return(midnight);
5181 return( (t/OneDay)*OneDay );
5185 /*------------------------------------------------------------------------
5186 * [export] VAdjustVolumeStatistics
5189 * If we've passed midnight, we need to update all the day use
5190 * statistics as well as zeroing the detailed volume statistics
5191 * (if we are implementing them).
5194 * vp : Pointer to the volume structure describing the lucky
5195 * volume being considered for update.
5201 * Nothing interesting.
5205 *------------------------------------------------------------------------*/
5208 VAdjustVolumeStatistics_r(register Volume * vp)
5210 unsigned int now = FT_ApproxTime();
5212 if (now - V_dayUseDate(vp) > OneDay) {
5213 register int ndays, i;
5215 ndays = (now - V_dayUseDate(vp)) / OneDay;
5216 for (i = 6; i > ndays - 1; i--)
5217 V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
5218 for (i = 0; i < ndays - 1 && i < 7; i++)
5219 V_weekUse(vp)[i] = 0;
5221 V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
5223 V_dayUseDate(vp) = Midnight(now);
5225 #if OPENAFS_VOL_STATS
5227 * All we need to do is bzero the entire VOL_STATS_BYTES of
5228 * the detailed volume statistics area.
5230 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
5231 #endif /* OPENAFS_VOL_STATS */
5234 /*It's been more than a day of collection */
5236 * Always return happily.
5239 } /*VAdjustVolumeStatistics */
5242 VAdjustVolumeStatistics(register Volume * vp)
5246 retVal = VAdjustVolumeStatistics_r(vp);
5252 VBumpVolumeUsage_r(register Volume * vp)
5254 unsigned int now = FT_ApproxTime();
5255 V_accessDate(vp) = now;
5256 if (now - V_dayUseDate(vp) > OneDay)
5257 VAdjustVolumeStatistics_r(vp);
5259 * Save the volume header image to disk after every 128 bumps to dayUse.
5261 if ((V_dayUse(vp)++ & 127) == 0) {
5263 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
5268 VBumpVolumeUsage(register Volume * vp)
5271 VBumpVolumeUsage_r(vp);
5276 VSetDiskUsage_r(void)
5278 #ifndef AFS_DEMAND_ATTACH_FS
5279 static int FifteenMinuteCounter = 0;
5283 /* NOTE: Don't attempt to access the partitions list until the
5284 * initialization level indicates that all volumes are attached,
5285 * which implies that all partitions are initialized. */
5286 #ifdef AFS_PTHREAD_ENV
5288 #else /* AFS_PTHREAD_ENV */
5290 #endif /* AFS_PTHREAD_ENV */
5293 VResetDiskUsage_r();
5295 #ifndef AFS_DEMAND_ATTACH_FS
5296 if (++FifteenMinuteCounter == 3) {
5297 FifteenMinuteCounter = 0;
5300 #endif /* !AFS_DEMAND_ATTACH_FS */
5312 /***************************************************/
5313 /* Volume Update List routines */
5314 /***************************************************/
5316 /* The number of minutes that a volume hasn't been updated before the
5317 * "Dont salvage" flag in the volume header will be turned on */
5318 #define SALVAGE_INTERVAL (10*60)
5323 * volume update list functionality has been moved into the VLRU
5324 * the DONT_SALVAGE flag is now set during VLRU demotion
5327 #ifndef AFS_DEMAND_ATTACH_FS
5328 static VolumeId *UpdateList = NULL; /* Pointer to array of Volume ID's */
5329 static int nUpdatedVolumes = 0; /* Updated with entry in UpdateList, salvage after crash flag on */
5330 static int updateSize = 0; /* number of entries possible */
5331 #define UPDATE_LIST_SIZE 128 /* initial size increment (must be a power of 2!) */
5332 #endif /* !AFS_DEMAND_ATTACH_FS */
5335 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
5338 vp->updateTime = FT_ApproxTime();
5339 if (V_dontSalvage(vp) == 0)
5341 V_dontSalvage(vp) = 0;
5342 VSyncVolume_r(ec, vp, 0);
5343 #ifdef AFS_DEMAND_ATTACH_FS
5344 V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
5345 #else /* !AFS_DEMAND_ATTACH_FS */
5348 if (UpdateList == NULL) {
5349 updateSize = UPDATE_LIST_SIZE;
5350 UpdateList = (VolumeId *) malloc(sizeof(VolumeId) * updateSize);
5352 if (nUpdatedVolumes == updateSize) {
5354 if (updateSize > 524288) {
5355 Log("warning: there is likely a bug in the volume update scanner\n");
5359 (VolumeId *) realloc(UpdateList,
5360 sizeof(VolumeId) * updateSize);
5363 assert(UpdateList != NULL);
5364 UpdateList[nUpdatedVolumes++] = V_id(vp);
5365 #endif /* !AFS_DEMAND_ATTACH_FS */
5368 #ifndef AFS_DEMAND_ATTACH_FS
5370 VScanUpdateList(void)
5372 register int i, gap;
5373 register Volume *vp;
5375 afs_uint32 now = FT_ApproxTime();
5376 /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
5377 for (i = gap = 0; i < nUpdatedVolumes; i++) {
5379 UpdateList[i - gap] = UpdateList[i];
5381 /* XXX this routine needlessly messes up the Volume LRU by
5382 * breaking the LRU temporal-locality assumptions.....
5383 * we should use a special volume header allocator here */
5384 vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
5387 } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
5388 V_dontSalvage(vp) = DONT_SALVAGE;
5389 VUpdateVolume_r(&error, vp, 0); /* No need to fsync--not critical */
5397 #ifndef AFS_PTHREAD_ENV
5399 #endif /* !AFS_PTHREAD_ENV */
5401 nUpdatedVolumes -= gap;
5403 #endif /* !AFS_DEMAND_ATTACH_FS */
5406 /***************************************************/
5407 /* Volume LRU routines */
5408 /***************************************************/
5413 * with demand attach fs, we attempt to soft detach(1)
5414 * volumes which have not been accessed in a long time
5415 * in order to speed up fileserver shutdown
5417 * (1) by soft detach we mean a process very similar
5418 * to VOffline, except the final state of the
5419 * Volume will be VOL_STATE_PREATTACHED, instead
5420 * of the usual VOL_STATE_UNATTACHED
5422 #ifdef AFS_DEMAND_ATTACH_FS
5424 /* implementation is reminiscent of a generational GC
5426 * queue 0 is newly attached volumes. this queue is
5427 * sorted by attach timestamp
5429 * queue 1 is volumes that have been around a bit
5430 * longer than queue 0. this queue is sorted by
5433 * queue 2 is volumes tha have been around the longest.
5434 * this queue is unsorted
5436 * queue 3 is volumes that have been marked as
5437 * candidates for soft detachment. this queue is
5440 #define VLRU_GENERATIONS 3 /**< number of generations in VLRU */
5441 #define VLRU_QUEUES 5 /**< total number of VLRU queues */
5444 * definition of a VLRU queue.
5447 volatile struct rx_queue q;
5454 * main VLRU data structure.
5457 struct VLRU_q q[VLRU_QUEUES]; /**< VLRU queues */
5460 /** time interval (in seconds) between promotion passes for
5461 * each young generation queue. */
5462 afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
5464 /** time interval (in seconds) between soft detach candidate
5465 * scans for each generation queue.
5467 * scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
5468 * we perform a soft detach pass. */
5469 afs_uint32 scan_interval[VLRU_GENERATIONS+1];
5471 /* scheduler state */
5472 int next_idx; /**< next queue to receive attention */
5473 afs_uint32 last_promotion[VLRU_GENERATIONS-1]; /**< timestamp of last promotion scan */
5474 afs_uint32 last_scan[VLRU_GENERATIONS+1]; /**< timestamp of last detach scan */
5476 int scanner_state; /**< state of scanner thread */
5477 pthread_cond_t cv; /**< state transition CV */
5480 /** global VLRU state */
5481 static struct VLRU volume_LRU;
5484 * defined states for VLRU scanner thread.
5487 VLRU_SCANNER_STATE_OFFLINE = 0, /**< vlru scanner thread is offline */
5488 VLRU_SCANNER_STATE_ONLINE = 1, /**< vlru scanner thread is online */
5489 VLRU_SCANNER_STATE_SHUTTING_DOWN = 2, /**< vlru scanner thread is shutting down */
5490 VLRU_SCANNER_STATE_PAUSING = 3, /**< vlru scanner thread is getting ready to pause */
5491 VLRU_SCANNER_STATE_PAUSED = 4 /**< vlru scanner thread is paused */
5492 } vlru_thread_state_t;
5494 /* vlru disk data header stuff */
5495 #define VLRU_DISK_MAGIC 0x7a8b9cad /**< vlru disk entry magic number */
5496 #define VLRU_DISK_VERSION 1 /**< vlru disk entry version number */
5498 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
5499 #define VLRU_DUMP_EXPIRATION_TIME (60*60*24*7) /* expire vlru data after 1 week */
5502 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
5503 * soft detachment. */
5504 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
5506 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
5507 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
5509 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
5510 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
5512 /** VLRU control flag. non-zero value implies VLRU subsystem is activated. */
5513 static afs_uint32 VLRU_enabled = 1;
5515 /* queue synchronization routines */
5516 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
5517 static void VLRU_EndExclusive_r(struct VLRU_q * q);
5518 static void VLRU_Wait_r(struct VLRU_q * q);
5521 * set VLRU subsystem tunable parameters.
5523 * @param[in] option tunable option to modify
5524 * @param[in] val new value for tunable parameter
5526 * @pre @c VInitVolumePackage2 has not yet been called.
5528 * @post tunable parameter is modified
5532 * @note valid option parameters are:
5533 * @arg @c VLRU_SET_THRESH
5534 * set the period of inactivity after which
5535 * volumes are eligible for soft detachment
5536 * @arg @c VLRU_SET_INTERVAL
5537 * set the time interval between calls
5538 * to the volume LRU "garbage collector"
5539 * @arg @c VLRU_SET_MAX
5540 * set the max number of volumes to deallocate
5544 VLRU_SetOptions(int option, afs_uint32 val)
5546 if (option == VLRU_SET_THRESH) {
5547 VLRU_offline_thresh = val;
5548 } else if (option == VLRU_SET_INTERVAL) {
5549 VLRU_offline_interval = val;
5550 } else if (option == VLRU_SET_MAX) {
5551 VLRU_offline_max = val;
5552 } else if (option == VLRU_SET_ENABLED) {
5555 VLRU_ComputeConstants();
5559 * compute VLRU internal timing parameters.
5561 * @post VLRU scanner thread internal timing parameters are computed
5563 * @note computes internal timing parameters based upon user-modifiable
5564 * tunable parameters.
5568 * @internal volume package internal use only.
5571 VLRU_ComputeConstants(void)
5573 afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
5575 /* compute the candidate scan interval */
5576 volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
5578 /* compute the promotion intervals */
5579 volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
5580 volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
5583 /* compute the gen 0 scan interval */
5584 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
5586 /* compute the gen 0 scan interval */
5587 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
5592 * initialize VLRU subsystem.
5594 * @pre this function has not yet been called
5596 * @post VLRU subsystem is initialized and VLRU scanner thread is starting
5600 * @internal volume package internal use only.
5606 pthread_attr_t attrs;
5609 if (!VLRU_enabled) {
5610 Log("VLRU: disabled\n");
5614 /* initialize each of the VLRU queues */
5615 for (i = 0; i < VLRU_QUEUES; i++) {
5616 queue_Init(&volume_LRU.q[i]);
5617 volume_LRU.q[i].len = 0;
5618 volume_LRU.q[i].busy = 0;
5619 assert(pthread_cond_init(&volume_LRU.q[i].cv, NULL) == 0);
5622 /* setup the timing constants */
5623 VLRU_ComputeConstants();
5625 /* XXX put inside LogLevel check? */
5626 Log("VLRU: starting scanner with the following configuration parameters:\n");
5627 Log("VLRU: offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
5628 Log("VLRU: running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
5629 Log("VLRU: taking up to %d volumes offline per pass\n", VLRU_offline_max);
5630 Log("VLRU: scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
5631 Log("VLRU: scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
5632 Log("VLRU: scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
5634 /* start up the VLRU scanner */
5635 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
5636 if (programType == fileServer) {
5637 assert(pthread_cond_init(&volume_LRU.cv, NULL) == 0);
5638 assert(pthread_attr_init(&attrs) == 0);
5639 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
5640 assert(pthread_create(&tid, &attrs, &VLRU_ScannerThread, NULL) == 0);
5645 * initialize the VLRU-related fields of a newly allocated volume object.
5647 * @param[in] vp pointer to volume object
5650 * @arg @c VOL_LOCK is held.
5651 * @arg volume object is not on a VLRU queue.
5653 * @post VLRU fields are initialized to indicate that volume object is not
5654 * currently registered with the VLRU subsystem
5658 * @internal volume package interal use only.
5661 VLRU_Init_Node_r(Volume * vp)
5666 assert(queue_IsNotOnQueue(&vp->vlru));
5667 vp->vlru.idx = VLRU_QUEUE_INVALID;
5671 * add a volume object to a VLRU queue.
5673 * @param[in] vp pointer to volume object
5676 * @arg @c VOL_LOCK is held.
5677 * @arg caller MUST hold a lightweight ref on @p vp.
5678 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
5680 * @post the volume object is added to the appropriate VLRU queue
5682 * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
5683 * then the volume is added to that queue. Otherwise, the value
5684 * @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
5685 * volume is added to the NEW generation queue.
5687 * @note @c VOL_LOCK may be dropped internally
5689 * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
5690 * during the add operation, and is restored to the previous
5691 * state prior to return.
5695 * @internal volume package internal use only.
5698 VLRU_Add_r(Volume * vp)
5701 VolState state_save;
5706 if (queue_IsOnQueue(&vp->vlru))
5709 state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
5712 if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
5713 idx = VLRU_QUEUE_NEW;
5716 VLRU_Wait_r(&volume_LRU.q[idx]);
5718 /* repeat check since VLRU_Wait_r may have dropped
5720 if (queue_IsNotOnQueue(&vp->vlru)) {
5722 queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
5723 volume_LRU.q[idx].len++;
5724 V_attachFlags(vp) |= VOL_ON_VLRU;
5725 vp->stats.last_promote = FT_ApproxTime();
5728 VChangeState_r(vp, state_save);
5732 * delete a volume object from a VLRU queue.
5734 * @param[in] vp pointer to volume object
5737 * @arg @c VOL_LOCK is held.
5738 * @arg caller MUST hold a lightweight ref on @p vp.
5739 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
5741 * @post volume object is removed from the VLRU queue
5743 * @note @c VOL_LOCK may be dropped internally
5747 * @todo We should probably set volume state to something exlcusive
5748 * (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
5750 * @internal volume package internal use only.
5753 VLRU_Delete_r(Volume * vp)
5760 if (queue_IsNotOnQueue(&vp->vlru))
5766 if (idx == VLRU_QUEUE_INVALID)
5768 VLRU_Wait_r(&volume_LRU.q[idx]);
5769 } while (idx != vp->vlru.idx);
5771 /* now remove from the VLRU and update
5772 * the appropriate counter */
5773 queue_Remove(&vp->vlru);
5774 volume_LRU.q[idx].len--;
5775 vp->vlru.idx = VLRU_QUEUE_INVALID;
5776 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
5780 * tell the VLRU subsystem that a volume was just accessed.
5782 * @param[in] vp pointer to volume object
5785 * @arg @c VOL_LOCK is held
5786 * @arg caller MUST hold a lightweight ref on @p vp
5787 * @arg caller MUST NOT hold exclusive ownership of any VLRU queue
5789 * @post volume VLRU access statistics are updated. If the volume was on
5790 * the VLRU soft detach candidate queue, it is moved to the NEW
5793 * @note @c VOL_LOCK may be dropped internally
5797 * @internal volume package internal use only.
5800 VLRU_UpdateAccess_r(Volume * vp)
5802 Volume * rvp = NULL;
5807 if (queue_IsNotOnQueue(&vp->vlru))
5810 assert(V_attachFlags(vp) & VOL_ON_VLRU);
5812 /* update the access timestamp */
5813 vp->stats.last_get = FT_ApproxTime();
5816 * if the volume is on the soft detach candidate
5817 * list, we need to safely move it back to a
5818 * regular generation. this has to be done
5819 * carefully so we don't race against the scanner
5823 /* if this volume is on the soft detach candidate queue,
5824 * then grab exclusive access to the necessary queues */
5825 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
5827 VCreateReservation_r(rvp);
5829 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
5830 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
5831 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5832 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5835 /* make sure multiple threads don't race to update */
5836 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
5837 VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
5841 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5842 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
5843 VCancelReservation_r(rvp);
5848 * switch a volume between two VLRU queues.
5850 * @param[in] vp pointer to volume object
5851 * @param[in] new_idx index of VLRU queue onto which the volume will be moved
5852 * @param[in] append controls whether the volume will be appended or
5853 * prepended to the queue. A nonzero value means it will
5854 * be appended; zero means it will be prepended.
5856 * @pre The new (and old, if applicable) queue(s) must either be owned
5857 * exclusively by the calling thread for asynchronous manipulation,
5858 * or the queue(s) must be quiescent and VOL_LOCK must be held.
5859 * Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
5860 * for further details of the queue asynchronous processing mechanism.
5862 * @post If the volume object was already on a VLRU queue, it is
5863 * removed from the queue. Depending on the value of the append
5864 * parameter, the volume object is either appended or prepended
5865 * to the VLRU queue referenced by the new_idx parameter.
5869 * @see VLRU_BeginExclusive_r
5870 * @see VLRU_EndExclusive_r
5873 * @internal volume package internal use only.
5876 VLRU_SwitchQueues(Volume * vp, int new_idx, int append)
5878 if (queue_IsNotOnQueue(&vp->vlru))
5881 queue_Remove(&vp->vlru);
5882 volume_LRU.q[vp->vlru.idx].len--;
5884 /* put the volume back on the correct generational queue */
5886 queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
5888 queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
5891 volume_LRU.q[new_idx].len++;
5892 vp->vlru.idx = new_idx;
5896 * VLRU background thread.
5898 * The VLRU Scanner Thread is responsible for periodically scanning through
5899 * each VLRU queue looking for volumes which should be moved to another
5900 * queue, or soft detached.
5902 * @param[in] args unused thread arguments parameter
5904 * @return unused thread return value
5905 * @retval NULL always
5907 * @internal volume package internal use only.
5910 VLRU_ScannerThread(void * args)
5912 afs_uint32 now, min_delay, delay;
5913 int i, min_idx, min_op, overdue, state;
5915 /* set t=0 for promotion cycle to be
5916 * fileserver startup */
5917 now = FT_ApproxTime();
5918 for (i=0; i < VLRU_GENERATIONS-1; i++) {
5919 volume_LRU.last_promotion[i] = now;
5922 /* don't start the scanner until VLRU_offline_thresh
5923 * plus a small delay for VInitVolumePackage2 to finish
5926 sleep(VLRU_offline_thresh + 60);
5928 /* set t=0 for scan cycle to be now */
5929 now = FT_ApproxTime();
5930 for (i=0; i < VLRU_GENERATIONS+1; i++) {
5931 volume_LRU.last_scan[i] = now;
5935 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
5936 volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
5939 while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
5940 /* check to see if we've been asked to pause */
5941 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
5942 volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
5943 assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
5945 VOL_CV_WAIT(&volume_LRU.cv);
5946 } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
5949 /* scheduling can happen outside the glock */
5952 /* figure out what is next on the schedule */
5954 /* figure out a potential schedule for the new generation first */
5956 min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
5959 if (min_delay > volume_LRU.scan_interval[0]) {
5960 /* unsigned overflow -- we're overdue to run this scan */
5965 /* if we're not overdue for gen 0, figure out schedule for candidate gen */
5967 i = VLRU_QUEUE_CANDIDATE;
5968 delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
5969 if (delay < min_delay) {
5973 if (delay > volume_LRU.scan_interval[i]) {
5974 /* unsigned overflow -- we're overdue to run this scan */
5981 /* if we're still not overdue for something, figure out schedules for promotions */
5982 for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
5983 delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
5984 if (delay < min_delay) {
5989 if (delay > volume_LRU.promotion_interval[i]) {
5990 /* unsigned overflow -- we're overdue to run this promotion */
5999 /* sleep as needed */
6004 /* do whatever is next */
6007 VLRU_Promote_r(min_idx);
6008 VLRU_Demote_r(min_idx+1);
6010 VLRU_Scan_r(min_idx);
6012 now = FT_ApproxTime();
6015 Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
6017 /* signal that scanner is down */
6018 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
6019 assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
6025 * promote volumes from one VLRU generation to the next.
6027 * This routine scans a VLRU generation looking for volumes which are
6028 * eligible to be promoted to the next generation. All volumes which
6029 * meet the eligibility requirement are promoted.
6031 * Promotion eligibility is based upon meeting both of the following
6034 * @arg The volume has been accessed since the last promotion:
6035 * @c (vp->stats.last_get >= vp->stats.last_promote)
6036 * @arg The last promotion occurred at least
6037 * @c volume_LRU.promotion_interval[idx] seconds ago
6039 * As a performance optimization, promotions are "globbed". In other
6040 * words, we promote arbitrarily large contiguous sublists of elements
6043 * @param[in] idx VLRU queue index to scan
6047 * @internal VLRU internal use only.
6050 VLRU_Promote_r(int idx)
6052 int len, chaining, promote;
6053 afs_uint32 now, thresh;
6054 struct rx_queue *qp, *nqp;
6055 Volume * vp, *start = NULL, *end = NULL;
6057 /* get exclusive access to two chains, and drop the glock */
6058 VLRU_Wait_r(&volume_LRU.q[idx]);
6059 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
6060 VLRU_Wait_r(&volume_LRU.q[idx+1]);
6061 VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
6064 thresh = volume_LRU.promotion_interval[idx];
6065 now = FT_ApproxTime();
6068 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
6069 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6070 promote = (((vp->stats.last_promote + thresh) <= now) &&
6071 (vp->stats.last_get >= vp->stats.last_promote));
6079 /* promote and prepend chain */
6080 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
6094 /* promote and prepend */
6095 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
6099 volume_LRU.q[idx].len -= len;
6100 volume_LRU.q[idx+1].len += len;
6103 /* release exclusive access to the two chains */
6105 volume_LRU.last_promotion[idx] = now;
6106 VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
6107 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
6110 /* run the demotions */
6112 VLRU_Demote_r(int idx)
6115 int len, chaining, demote;
6116 afs_uint32 now, thresh;
6117 struct rx_queue *qp, *nqp;
6118 Volume * vp, *start = NULL, *end = NULL;
6119 Volume ** salv_flag_vec = NULL;
6120 int salv_vec_offset = 0;
6122 assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
6124 /* get exclusive access to two chains, and drop the glock */
6125 VLRU_Wait_r(&volume_LRU.q[idx-1]);
6126 VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
6127 VLRU_Wait_r(&volume_LRU.q[idx]);
6128 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
6131 /* no big deal if this allocation fails */
6132 if (volume_LRU.q[idx].len) {
6133 salv_flag_vec = (Volume **) malloc(volume_LRU.q[idx].len * sizeof(Volume *));
6136 now = FT_ApproxTime();
6137 thresh = volume_LRU.promotion_interval[idx-1];
6140 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
6141 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6142 demote = (((vp->stats.last_promote + thresh) <= now) &&
6143 (vp->stats.last_get < (now - thresh)));
6145 /* we now do volume update list DONT_SALVAGE flag setting during
6146 * demotion passes */
6147 if (salv_flag_vec &&
6148 !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
6150 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
6151 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
6152 salv_flag_vec[salv_vec_offset++] = vp;
6153 VCreateReservation_r(vp);
6162 /* demote and append chain */
6163 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
6177 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
6181 volume_LRU.q[idx].len -= len;
6182 volume_LRU.q[idx-1].len += len;
6185 /* release exclusive access to the two chains */
6187 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
6188 VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
6190 /* now go back and set the DONT_SALVAGE flags as appropriate */
6191 if (salv_flag_vec) {
6193 for (i = 0; i < salv_vec_offset; i++) {
6194 vp = salv_flag_vec[i];
6195 if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
6196 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
6197 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
6200 V_attachFlags(vp) |= VOL_HDR_DONTSALV;
6201 V_dontSalvage(vp) = DONT_SALVAGE;
6202 VUpdateVolume_r(&ec, vp, 0);
6206 VCancelReservation_r(vp);
6208 free(salv_flag_vec);
6212 /* run a pass of the VLRU GC scanner */
6214 VLRU_Scan_r(int idx)
6216 afs_uint32 now, thresh;
6217 struct rx_queue *qp, *nqp;
6221 assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
6223 /* gain exclusive access to the idx VLRU */
6224 VLRU_Wait_r(&volume_LRU.q[idx]);
6225 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
6227 if (idx != VLRU_QUEUE_CANDIDATE) {
6228 /* gain exclusive access to the candidate VLRU */
6229 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6230 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6233 now = FT_ApproxTime();
6234 thresh = now - VLRU_offline_thresh;
6236 /* perform candidate selection and soft detaching */
6237 if (idx == VLRU_QUEUE_CANDIDATE) {
6238 /* soft detach some volumes from the candidate pool */
6242 for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
6243 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6244 if (i >= VLRU_offline_max) {
6247 /* check timestamp to see if it's a candidate for soft detaching */
6248 if (vp->stats.last_get <= thresh) {
6250 if (VCheckSoftDetach(vp, thresh))
6256 /* scan for volumes to become soft detach candidates */
6257 for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
6258 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6260 /* check timestamp to see if it's a candidate for soft detaching */
6261 if (vp->stats.last_get <= thresh) {
6262 VCheckSoftDetachCandidate(vp, thresh);
6265 if (!(i&0x7f)) { /* lock coarsening optimization */
6273 /* relinquish exclusive access to the VLRU chains */
6277 volume_LRU.last_scan[idx] = now;
6278 if (idx != VLRU_QUEUE_CANDIDATE) {
6279 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6281 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
6284 /* check whether volume is safe to soft detach
6285 * caller MUST NOT hold a ref count on vp */
6287 VCheckSoftDetach(Volume * vp, afs_uint32 thresh)
6291 if (vp->nUsers || vp->nWaiters)
6294 if (vp->stats.last_get <= thresh) {
6295 ret = VSoftDetachVolume_r(vp, thresh);
6301 /* check whether volume should be made a
6302 * soft detach candidate */
6304 VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh)
6307 if (vp->nUsers || vp->nWaiters)
6312 assert(idx == VLRU_QUEUE_NEW);
6314 if (vp->stats.last_get <= thresh) {
6315 /* move to candidate pool */
6316 queue_Remove(&vp->vlru);
6317 volume_LRU.q[VLRU_QUEUE_NEW].len--;
6318 queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
6319 vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
6320 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
6328 /* begin exclusive access on VLRU */
6330 VLRU_BeginExclusive_r(struct VLRU_q * q)
6332 assert(q->busy == 0);
6336 /* end exclusive access on VLRU */
6338 VLRU_EndExclusive_r(struct VLRU_q * q)
6342 assert(pthread_cond_broadcast(&q->cv) == 0);
6345 /* wait for another thread to end exclusive access on VLRU */
6347 VLRU_Wait_r(struct VLRU_q * q)
6350 VOL_CV_WAIT(&q->cv);
6355 * volume soft detach
6357 * caller MUST NOT hold a ref count on vp */
6359 VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh)
6364 assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
6366 ts_save = vp->stats.last_get;
6367 if (ts_save > thresh)
6370 if (vp->nUsers || vp->nWaiters)
6373 if (VIsExclusiveState(V_attachState(vp))) {
6377 switch (V_attachState(vp)) {
6378 case VOL_STATE_UNATTACHED:
6379 case VOL_STATE_PREATTACHED:
6380 case VOL_STATE_ERROR:
6381 case VOL_STATE_GOING_OFFLINE:
6382 case VOL_STATE_SHUTTING_DOWN:
6383 case VOL_STATE_SALVAGING:
6384 volume_LRU.q[vp->vlru.idx].len--;
6386 /* create and cancel a reservation to
6387 * give the volume an opportunity to
6389 VCreateReservation_r(vp);
6390 queue_Remove(&vp->vlru);
6391 vp->vlru.idx = VLRU_QUEUE_INVALID;
6392 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
6393 VCancelReservation_r(vp);
6399 /* hold the volume and take it offline.
6400 * no need for reservations, as VHold_r
6401 * takes care of that internally. */
6402 if (VHold_r(vp) == 0) {
6403 /* vhold drops the glock, so now we should
6404 * check to make sure we aren't racing against
6405 * other threads. if we are racing, offlining vp
6406 * would be wasteful, and block the scanner for a while
6410 (vp->shuttingDown) ||
6411 (vp->goingOffline) ||
6412 (vp->stats.last_get != ts_save)) {
6413 /* looks like we're racing someone else. bail */
6417 /* pull it off the VLRU */
6418 assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
6419 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
6420 queue_Remove(&vp->vlru);
6421 vp->vlru.idx = VLRU_QUEUE_INVALID;
6422 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
6424 /* take if offline */
6425 VOffline_r(vp, "volume has been soft detached");
6427 /* invalidate the volume header cache */
6428 FreeVolumeHeader(vp);
6431 IncUInt64(&VStats.soft_detaches);
6432 vp->stats.soft_detaches++;
6434 /* put in pre-attached state so demand
6435 * attacher can work on it */
6436 VChangeState_r(vp, VOL_STATE_PREATTACHED);
6442 #endif /* AFS_DEMAND_ATTACH_FS */
6445 /***************************************************/
6446 /* Volume Header Cache routines */
6447 /***************************************************/
6450 * volume header cache.
6452 struct volume_hdr_LRU_t volume_hdr_LRU;
6455 * initialize the volume header cache.
6457 * @param[in] howMany number of header cache entries to preallocate
6459 * @pre VOL_LOCK held. Function has never been called before.
6461 * @post howMany cache entries are allocated, initialized, and added
6462 * to the LRU list. Header cache statistics are initialized.
6464 * @note only applicable to fileServer program type. Should only be
6465 * called once during volume package initialization.
6467 * @internal volume package internal use only.
6470 VInitVolumeHeaderCache(afs_uint32 howMany)
6472 register struct volHeader *hp;
6473 if (programType != fileServer)
6475 queue_Init(&volume_hdr_LRU);
6476 volume_hdr_LRU.stats.free = 0;
6477 volume_hdr_LRU.stats.used = howMany;
6478 volume_hdr_LRU.stats.attached = 0;
6479 hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
6483 /* We are using ReleaseVolumeHeader to initialize the values on the header list
6484 * to ensure they have the right values
6486 ReleaseVolumeHeader(hp++);
6490 * get a volume header and attach it to the volume object.
6492 * @param[in] vp pointer to volume object
6494 * @return cache entry status
6495 * @retval 0 volume header was newly attached; cache data is invalid
6496 * @retval 1 volume header was previously attached; cache data is valid
6498 * @pre VOL_LOCK held. For DAFS, lightweight ref must be held on volume object.
6500 * @post volume header attached to volume object. if necessary, header cache
6501 * entry on LRU is synchronized to disk. Header is removed from LRU list.
6503 * @note VOL_LOCK may be dropped
6505 * @warning this interface does not load header data from disk. it merely
6506 * attaches a header object to the volume object, and may sync the old
6507 * header cache data out to disk in the process.
6509 * @internal volume package internal use only.
6512 GetVolumeHeader(register Volume * vp)
6515 register struct volHeader *hd;
6517 static int everLogged = 0;
6519 #ifdef AFS_DEMAND_ATTACH_FS
6520 VolState vp_save = 0, back_save = 0;
6522 /* XXX debug 9/19/05 we've apparently got
6523 * a ref counting bug somewhere that's
6524 * breaking the nUsers == 0 => header on LRU
6526 if (vp->header && queue_IsNotOnQueue(vp->header)) {
6527 Log("nUsers == 0, but header not on LRU\n");
6532 old = (vp->header != NULL); /* old == volume already has a header */
6534 if (programType != fileServer) {
6535 /* for volume utilities, we allocate volHeaders as needed */
6537 hd = (struct volHeader *)calloc(1, sizeof(*vp->header));
6541 #ifdef AFS_DEMAND_ATTACH_FS
6542 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
6546 /* for the fileserver, we keep a volume header cache */
6548 /* the header we previously dropped in the lru is
6549 * still available. pull it off the lru and return */
6552 assert(hd->back == vp);
6554 /* we need to grab a new element off the LRU */
6555 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
6556 /* grab an element and pull off of LRU */
6557 hd = queue_First(&volume_hdr_LRU, volHeader);
6560 /* LRU is empty, so allocate a new volHeader
6561 * this is probably indicative of a leak, so let the user know */
6562 hd = (struct volHeader *)calloc(1, sizeof(struct volHeader));
6565 Log("****Allocated more volume headers, probably leak****\n");
6568 volume_hdr_LRU.stats.free++;
6571 /* this header used to belong to someone else.
6572 * we'll need to check if the header needs to
6573 * be sync'd out to disk */
6575 #ifdef AFS_DEMAND_ATTACH_FS
6576 /* if hd->back were in an exclusive state, then
6577 * its volHeader would not be on the LRU... */
6578 assert(!VIsExclusiveState(V_attachState(hd->back)));
6581 if (hd->diskstuff.inUse) {
6582 /* volume was in use, so we'll need to sync
6583 * its header to disk */
6585 #ifdef AFS_DEMAND_ATTACH_FS
6586 back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
6587 vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
6588 VCreateReservation_r(hd->back);
6592 WriteVolumeHeader_r(&error, hd->back);
6593 /* Ignore errors; catch them later */
6595 #ifdef AFS_DEMAND_ATTACH_FS
6600 hd->back->header = NULL;
6601 #ifdef AFS_DEMAND_ATTACH_FS
6602 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
6604 if (hd->diskstuff.inUse) {
6605 VChangeState_r(hd->back, back_save);
6606 VCancelReservation_r(hd->back);
6607 VChangeState_r(vp, vp_save);
6611 volume_hdr_LRU.stats.attached++;
6615 #ifdef AFS_DEMAND_ATTACH_FS
6616 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
6619 volume_hdr_LRU.stats.free--;
6620 volume_hdr_LRU.stats.used++;
6622 IncUInt64(&VStats.hdr_gets);
6623 #ifdef AFS_DEMAND_ATTACH_FS
6624 IncUInt64(&vp->stats.hdr_gets);
6625 vp->stats.last_hdr_get = FT_ApproxTime();
6632 * make sure volume header is attached and contains valid cache data.
6634 * @param[out] ec outbound error code
6635 * @param[in] vp pointer to volume object
6637 * @pre VOL_LOCK held. For DAFS, lightweight ref held on vp.
6639 * @post header cache entry attached, and loaded with valid data, or
6640 * *ec is nonzero, and the header is released back into the LRU.
6642 * @internal volume package internal use only.
6645 LoadVolumeHeader(Error * ec, Volume * vp)
6647 #ifdef AFS_DEMAND_ATTACH_FS
6648 VolState state_save;
6652 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
6653 IncUInt64(&VStats.hdr_loads);
6654 state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
6657 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
6658 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
6660 IncUInt64(&vp->stats.hdr_loads);
6661 now = FT_ApproxTime();
6665 V_attachFlags(vp) |= VOL_HDR_LOADED;
6666 vp->stats.last_hdr_load = now;
6668 VChangeState_r(vp, state_save);
6670 #else /* AFS_DEMAND_ATTACH_FS */
6672 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
6673 IncUInt64(&VStats.hdr_loads);
6675 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
6676 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
6679 #endif /* AFS_DEMAND_ATTACH_FS */
6681 /* maintain (nUsers==0) => header in LRU invariant */
6682 FreeVolumeHeader(vp);
6687 * release a header cache entry back into the LRU list.
6689 * @param[in] hd pointer to volume header cache object
6691 * @pre VOL_LOCK held.
6693 * @post header cache object appended onto end of LRU list.
6695 * @note only applicable to fileServer program type.
6697 * @note used to place a header cache entry back into the
6698 * LRU pool without invalidating it as a cache entry.
6700 * @internal volume package internal use only.
6703 ReleaseVolumeHeader(register struct volHeader *hd)
6705 if (programType != fileServer)
6707 if (!hd || queue_IsOnQueue(hd)) /* no header, or header already released */
6709 queue_Append(&volume_hdr_LRU, hd);
6710 #ifdef AFS_DEMAND_ATTACH_FS
6712 V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
6715 volume_hdr_LRU.stats.free++;
6716 volume_hdr_LRU.stats.used--;
6720 * free/invalidate a volume header cache entry.
6722 * @param[in] vp pointer to volume object
6724 * @pre VOL_LOCK is held.
6726 * @post For fileserver, header cache entry is returned to LRU, and it is
6727 * invalidated as a cache entry. For volume utilities, the header
6728 * cache entry is freed.
6730 * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
6731 * whenever it is necessary to invalidate the header cache entry.
6733 * @see ReleaseVolumeHeader
6735 * @internal volume package internal use only.
6738 FreeVolumeHeader(register Volume * vp)
6740 register struct volHeader *hd = vp->header;
6743 if (programType == fileServer) {
6744 ReleaseVolumeHeader(hd);
6749 #ifdef AFS_DEMAND_ATTACH_FS
6750 V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
6752 volume_hdr_LRU.stats.attached--;
6757 /***************************************************/
6758 /* Volume Hash Table routines */
6759 /***************************************************/
6762 * set size of volume object hash table.
6764 * @param[in] logsize log(2) of desired hash table size
6766 * @return operation status
6768 * @retval -1 failure
6770 * @pre MUST be called prior to VInitVolumePackage2
6772 * @post Volume Hash Table will have 2^logsize buckets
6775 VSetVolHashSize(int logsize)
6777 /* 64 to 16384 hash buckets seems like a reasonable range */
6778 if ((logsize < 6 ) || (logsize > 14)) {
6783 VolumeHashTable.Size = 1 << logsize;
6784 VolumeHashTable.Mask = VolumeHashTable.Size - 1;
6786 /* we can't yet support runtime modification of this
6787 * parameter. we'll need a configuration rwlock to
6788 * make runtime modification feasible.... */
6795 * initialize dynamic data structures for volume hash table.
6797 * @post hash table is allocated, and fields are initialized.
6799 * @internal volume package internal use only.
6802 VInitVolumeHash(void)
6806 VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
6807 sizeof(VolumeHashChainHead));
6808 assert(VolumeHashTable.Table != NULL);
6810 for (i=0; i < VolumeHashTable.Size; i++) {
6811 queue_Init(&VolumeHashTable.Table[i]);
6812 #ifdef AFS_DEMAND_ATTACH_FS
6813 assert(pthread_cond_init(&VolumeHashTable.Table[i].chain_busy_cv, NULL) == 0);
6814 #endif /* AFS_DEMAND_ATTACH_FS */
6819 * add a volume object to the hash table.
6821 * @param[in] vp pointer to volume object
6822 * @param[in] hashid hash of volume id
6824 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
6827 * @post volume is added to hash chain.
6829 * @internal volume package internal use only.
6831 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
6832 * asynchronous hash chain reordering to finish.
6835 AddVolumeToHashTable(register Volume * vp, int hashid)
6837 VolumeHashChainHead * head;
6839 if (queue_IsOnQueue(vp))
6842 head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
6844 #ifdef AFS_DEMAND_ATTACH_FS
6845 /* wait for the hash chain to become available */
6848 V_attachFlags(vp) |= VOL_IN_HASH;
6849 vp->chainCacheCheck = ++head->cacheCheck;
6850 #endif /* AFS_DEMAND_ATTACH_FS */
6853 vp->hashid = hashid;
6854 queue_Append(head, vp);
6855 vp->vnodeHashOffset = VolumeHashOffset_r();
6859 * delete a volume object from the hash table.
6861 * @param[in] vp pointer to volume object
6863 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
6866 * @post volume is removed from hash chain.
6868 * @internal volume package internal use only.
6870 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
6871 * asynchronous hash chain reordering to finish.
6874 DeleteVolumeFromHashTable(register Volume * vp)
6876 VolumeHashChainHead * head;
6878 if (!queue_IsOnQueue(vp))
6881 head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
6883 #ifdef AFS_DEMAND_ATTACH_FS
6884 /* wait for the hash chain to become available */
6887 V_attachFlags(vp) &= ~(VOL_IN_HASH);
6889 #endif /* AFS_DEMAND_ATTACH_FS */
6893 /* do NOT reset hashid to zero, as the online
6894 * salvager package may need to know the volume id
6895 * after the volume is removed from the hash */
6899 * lookup a volume object in the hash table given a volume id.
6901 * @param[out] ec error code return
6902 * @param[in] volumeId volume id
6903 * @param[in] hint volume object which we believe could be the correct
6906 * @return volume object pointer
6907 * @retval NULL no such volume id is registered with the hash table.
6909 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
6912 * @post volume object with the given id is returned. volume object and
6913 * hash chain access statistics are updated. hash chain may have
6916 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
6917 * asynchronous hash chain reordering operation to finish, or
6918 * in order for us to perform an asynchronous chain reordering.
6920 * @note Hash chain reorderings occur when the access count for the
6921 * volume object being looked up exceeds the sum of the previous
6922 * node's (the node ahead of it in the hash chain linked list)
6923 * access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
6925 * @note For DAFS, the hint parameter allows us to short-circuit if the
6926 * cacheCheck fields match between the hash chain head and the
6927 * hint volume object.
6930 VLookupVolume_r(Error * ec, VolId volumeId, Volume * hint)
6932 register int looks = 0;
6934 #ifdef AFS_DEMAND_ATTACH_FS
6937 VolumeHashChainHead * head;
6940 head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
6942 #ifdef AFS_DEMAND_ATTACH_FS
6943 /* wait for the hash chain to become available */
6946 /* check to see if we can short circuit without walking the hash chain */
6947 if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
6948 IncUInt64(&hint->stats.hash_short_circuits);
6951 #endif /* AFS_DEMAND_ATTACH_FS */
6953 /* someday we need to either do per-chain locks, RWlocks,
6954 * or both for volhash access.
6955 * (and move to a data structure with better cache locality) */
6957 /* search the chain for this volume id */
6958 for(queue_Scan(head, vp, np, Volume)) {
6960 if ((vp->hashid == volumeId)) {
6965 if (queue_IsEnd(head, vp)) {
6969 #ifdef AFS_DEMAND_ATTACH_FS
6970 /* update hash chain statistics */
6973 FillInt64(lks, 0, looks);
6974 AddUInt64(head->looks, lks, &head->looks);
6975 AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
6976 IncUInt64(&head->gets);
6981 IncUInt64(&vp->stats.hash_lookups);
6983 /* for demand attach fileserver, we permit occasional hash chain reordering
6984 * so that frequently looked up volumes move towards the head of the chain */
6985 pp = queue_Prev(vp, Volume);
6986 if (!queue_IsEnd(head, pp)) {
6987 FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
6988 AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
6989 if (GEInt64(vp->stats.hash_lookups, thresh)) {
6990 VReorderHash_r(head, pp, vp);
6994 /* update the short-circuit cache check */
6995 vp->chainCacheCheck = head->cacheCheck;
6997 #endif /* AFS_DEMAND_ATTACH_FS */
7002 #ifdef AFS_DEMAND_ATTACH_FS
7003 /* perform volume hash chain reordering.
7005 * advance a subchain beginning at vp ahead of
7006 * the adjacent subchain ending at pp */
7008 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
7010 Volume *tp, *np, *lp;
7011 afs_uint64 move_thresh;
7013 /* this should never be called if the chain is already busy, so
7014 * no need to wait for other exclusive chain ops to finish */
7016 /* this is a rather heavy set of operations,
7017 * so let's set the chain busy flag and drop
7019 VHashBeginExclusive_r(head);
7022 /* scan forward in the chain from vp looking for the last element
7023 * in the chain we want to advance */
7024 FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
7025 AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
7026 for(queue_ScanFrom(head, vp, tp, np, Volume)) {
7027 if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
7031 lp = queue_Prev(tp, Volume);
7033 /* scan backwards from pp to determine where to splice and
7034 * insert the subchain we're advancing */
7035 for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
7036 if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
7040 tp = queue_Next(tp, Volume);
7042 /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
7043 queue_MoveChainBefore(tp,vp,lp);
7046 IncUInt64(&VStats.hash_reorders);
7048 IncUInt64(&head->reorders);
7050 /* wake up any threads waiting for the hash chain */
7051 VHashEndExclusive_r(head);
7055 /* demand-attach fs volume hash
7056 * asynchronous exclusive operations */
7059 * begin an asynchronous exclusive operation on a volume hash chain.
7061 * @param[in] head pointer to volume hash chain head object
7063 * @pre VOL_LOCK held. hash chain is quiescent.
7065 * @post hash chain marked busy.
7067 * @note this interface is used in conjunction with VHashEndExclusive_r and
7068 * VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
7069 * volume hash chain. Its main use case is hash chain reordering, which
7070 * has the potential to be a highly latent operation.
7072 * @see VHashEndExclusive_r
7077 * @internal volume package internal use only.
7080 VHashBeginExclusive_r(VolumeHashChainHead * head)
7082 assert(head->busy == 0);
7087 * relinquish exclusive ownership of a volume hash chain.
7089 * @param[in] head pointer to volume hash chain head object
7091 * @pre VOL_LOCK held. thread owns the hash chain exclusively.
7093 * @post hash chain is marked quiescent. threads awaiting use of
7094 * chain are awakened.
7096 * @see VHashBeginExclusive_r
7101 * @internal volume package internal use only.
7104 VHashEndExclusive_r(VolumeHashChainHead * head)
7108 assert(pthread_cond_broadcast(&head->chain_busy_cv) == 0);
7112 * wait for all asynchronous operations on a hash chain to complete.
7114 * @param[in] head pointer to volume hash chain head object
7116 * @pre VOL_LOCK held.
7118 * @post hash chain object is quiescent.
7120 * @see VHashBeginExclusive_r
7121 * @see VHashEndExclusive_r
7125 * @note This interface should be called before any attempt to
7126 * traverse the hash chain. It is permissible for a thread
7127 * to gain exclusive access to the chain, and then perform
7128 * latent operations on the chain asynchronously wrt the
7131 * @warning if waiting is necessary, VOL_LOCK is dropped
7133 * @internal volume package internal use only.
7136 VHashWait_r(VolumeHashChainHead * head)
7138 while (head->busy) {
7139 VOL_CV_WAIT(&head->chain_busy_cv);
7142 #endif /* AFS_DEMAND_ATTACH_FS */
7145 /***************************************************/
7146 /* Volume by Partition List routines */
7147 /***************************************************/
7150 * demand attach fileserver adds a
7151 * linked list of volumes to each
7152 * partition object, thus allowing
7153 * for quick enumeration of all
7154 * volumes on a partition
7157 #ifdef AFS_DEMAND_ATTACH_FS
7159 * add a volume to its disk partition VByPList.
7161 * @param[in] vp pointer to volume object
7163 * @pre either the disk partition VByPList is owned exclusively
7164 * by the calling thread, or the list is quiescent and
7167 * @post volume is added to disk partition VByPList
7171 * @warning it is the caller's responsibility to ensure list
7174 * @see VVByPListWait_r
7175 * @see VVByPListBeginExclusive_r
7176 * @see VVByPListEndExclusive_r
7178 * @internal volume package internal use only.
7181 AddVolumeToVByPList_r(Volume * vp)
7183 if (queue_IsNotOnQueue(&vp->vol_list)) {
7184 queue_Append(&vp->partition->vol_list, &vp->vol_list);
7185 V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
7186 vp->partition->vol_list.len++;
7191 * delete a volume from its disk partition VByPList.
7193 * @param[in] vp pointer to volume object
7195 * @pre either the disk partition VByPList is owned exclusively
7196 * by the calling thread, or the list is quiescent and
7199 * @post volume is removed from the disk partition VByPList
7203 * @warning it is the caller's responsibility to ensure list
7206 * @see VVByPListWait_r
7207 * @see VVByPListBeginExclusive_r
7208 * @see VVByPListEndExclusive_r
7210 * @internal volume package internal use only.
7213 DeleteVolumeFromVByPList_r(Volume * vp)
7215 if (queue_IsOnQueue(&vp->vol_list)) {
7216 queue_Remove(&vp->vol_list);
7217 V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
7218 vp->partition->vol_list.len--;
7223 * begin an asynchronous exclusive operation on a VByPList.
7225 * @param[in] dp pointer to disk partition object
7227 * @pre VOL_LOCK held. VByPList is quiescent.
7229 * @post VByPList marked busy.
7231 * @note this interface is used in conjunction with VVByPListEndExclusive_r and
7232 * VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
7235 * @see VVByPListEndExclusive_r
7236 * @see VVByPListWait_r
7240 * @internal volume package internal use only.
7242 /* take exclusive control over the list */
7244 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
7246 assert(dp->vol_list.busy == 0);
7247 dp->vol_list.busy = 1;
7251 * relinquish exclusive ownership of a VByPList.
7253 * @param[in] dp pointer to disk partition object
7255 * @pre VOL_LOCK held. thread owns the VByPList exclusively.
7257 * @post VByPList is marked quiescent. threads awaiting use of
7258 * the list are awakened.
7260 * @see VVByPListBeginExclusive_r
7261 * @see VVByPListWait_r
7265 * @internal volume package internal use only.
7268 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
7270 assert(dp->vol_list.busy);
7271 dp->vol_list.busy = 0;
7272 assert(pthread_cond_broadcast(&dp->vol_list.cv) == 0);
7276 * wait for all asynchronous operations on a VByPList to complete.
7278 * @param[in] dp pointer to disk partition object
7280 * @pre VOL_LOCK is held.
7282 * @post disk partition's VByP list is quiescent
7286 * @note This interface should be called before any attempt to
7287 * traverse the VByPList. It is permissible for a thread
7288 * to gain exclusive access to the list, and then perform
7289 * latent operations on the list asynchronously wrt the
7292 * @warning if waiting is necessary, VOL_LOCK is dropped
7294 * @see VVByPListEndExclusive_r
7295 * @see VVByPListBeginExclusive_r
7297 * @internal volume package internal use only.
7300 VVByPListWait_r(struct DiskPartition64 * dp)
7302 while (dp->vol_list.busy) {
7303 VOL_CV_WAIT(&dp->vol_list.cv);
7306 #endif /* AFS_DEMAND_ATTACH_FS */
7308 /***************************************************/
7309 /* Volume Cache Statistics routines */
7310 /***************************************************/
7313 VPrintCacheStats_r(void)
7315 afs_uint32 get_hi, get_lo, load_hi, load_lo;
7316 register struct VnodeClassInfo *vcp;
7317 vcp = &VnodeClassInfo[vLarge];
7318 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);
7319 vcp = &VnodeClassInfo[vSmall];
7320 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);
7321 SplitInt64(VStats.hdr_gets, get_hi, get_lo);
7322 SplitInt64(VStats.hdr_loads, load_hi, load_lo);
7323 Log("Volume header cache, %d entries, %d gets, %d replacements\n",
7324 VStats.hdr_cache_size, get_lo, load_lo);
7328 VPrintCacheStats(void)
7331 VPrintCacheStats_r();
7335 #ifdef AFS_DEMAND_ATTACH_FS
7337 UInt64ToDouble(afs_uint64 * x)
7339 static double c32 = 4.0 * 1.073741824 * 1000000000.0;
7341 SplitInt64(*x, h, l);
7342 return (((double)h) * c32) + ((double) l);
7346 DoubleToPrintable(double x, char * buf, int len)
7348 static double billion = 1000000000.0;
7351 y[0] = (afs_uint32) (x / (billion * billion));
7352 y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
7353 y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
7356 snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
7358 snprintf(buf, len, "%d%09d", y[1], y[2]);
7360 snprintf(buf, len, "%d", y[2]);
7366 struct VLRUExtStatsEntry {
7370 struct VLRUExtStats {
7376 } queue_info[VLRU_QUEUE_INVALID];
7377 struct VLRUExtStatsEntry * vec;
7381 * add a 256-entry fudge factor onto the vector in case state changes
7382 * out from under us.
7384 #define VLRU_EXT_STATS_VEC_LEN_FUDGE 256
7387 * collect extended statistics for the VLRU subsystem.
7389 * @param[out] stats pointer to stats structure to be populated
7390 * @param[in] nvols number of volumes currently known to exist
7392 * @pre VOL_LOCK held
7394 * @post stats->vec allocated and populated
7396 * @return operation status
7401 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
7403 afs_uint32 cur, idx, len;
7404 struct rx_queue * qp, * nqp;
7406 struct VLRUExtStatsEntry * vec;
7408 len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
7409 vec = stats->vec = calloc(len,
7410 sizeof(struct VLRUExtStatsEntry));
7416 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
7417 VLRU_Wait_r(&volume_LRU.q[idx]);
7418 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7421 stats->queue_info[idx].start = cur;
7423 for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7425 /* out of space in vec */
7428 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7429 vec[cur].volid = vp->hashid;
7433 stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
7436 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7444 #define ENUMTOSTRING(en) #en
7445 #define ENUMCASE(en) \
7447 return ENUMTOSTRING(en); \
7451 vlru_idx_to_string(int idx)
7454 ENUMCASE(VLRU_QUEUE_NEW);
7455 ENUMCASE(VLRU_QUEUE_MID);
7456 ENUMCASE(VLRU_QUEUE_OLD);
7457 ENUMCASE(VLRU_QUEUE_CANDIDATE);
7458 ENUMCASE(VLRU_QUEUE_HELD);
7459 ENUMCASE(VLRU_QUEUE_INVALID);
7461 return "**UNKNOWN**";
7466 VPrintExtendedCacheStats_r(int flags)
7469 afs_uint32 vol_sum = 0;
7476 struct stats looks, gets, reorders, len;
7477 struct stats ch_looks, ch_gets, ch_reorders;
7479 VolumeHashChainHead *head;
7481 struct VLRUExtStats vlru_stats;
7483 /* zero out stats */
7484 memset(&looks, 0, sizeof(struct stats));
7485 memset(&gets, 0, sizeof(struct stats));
7486 memset(&reorders, 0, sizeof(struct stats));
7487 memset(&len, 0, sizeof(struct stats));
7488 memset(&ch_looks, 0, sizeof(struct stats));
7489 memset(&ch_gets, 0, sizeof(struct stats));
7490 memset(&ch_reorders, 0, sizeof(struct stats));
7492 for (i = 0; i < VolumeHashTable.Size; i++) {
7493 head = &VolumeHashTable.Table[i];
7496 VHashBeginExclusive_r(head);
7499 ch_looks.sum = UInt64ToDouble(&head->looks);
7500 ch_gets.sum = UInt64ToDouble(&head->gets);
7501 ch_reorders.sum = UInt64ToDouble(&head->reorders);
7503 /* update global statistics */
7505 looks.sum += ch_looks.sum;
7506 gets.sum += ch_gets.sum;
7507 reorders.sum += ch_reorders.sum;
7508 len.sum += (double)head->len;
7509 vol_sum += head->len;
7512 len.min = (double) head->len;
7513 len.max = (double) head->len;
7514 looks.min = ch_looks.sum;
7515 looks.max = ch_looks.sum;
7516 gets.min = ch_gets.sum;
7517 gets.max = ch_gets.sum;
7518 reorders.min = ch_reorders.sum;
7519 reorders.max = ch_reorders.sum;
7521 if (((double)head->len) < len.min)
7522 len.min = (double) head->len;
7523 if (((double)head->len) > len.max)
7524 len.max = (double) head->len;
7525 if (ch_looks.sum < looks.min)
7526 looks.min = ch_looks.sum;
7527 else if (ch_looks.sum > looks.max)
7528 looks.max = ch_looks.sum;
7529 if (ch_gets.sum < gets.min)
7530 gets.min = ch_gets.sum;
7531 else if (ch_gets.sum > gets.max)
7532 gets.max = ch_gets.sum;
7533 if (ch_reorders.sum < reorders.min)
7534 reorders.min = ch_reorders.sum;
7535 else if (ch_reorders.sum > reorders.max)
7536 reorders.max = ch_reorders.sum;
7540 if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
7541 /* compute detailed per-chain stats */
7542 struct stats hdr_loads, hdr_gets;
7543 double v_looks, v_loads, v_gets;
7545 /* initialize stats with data from first element in chain */
7546 vp = queue_First(head, Volume);
7547 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
7548 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
7549 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
7550 ch_gets.min = ch_gets.max = v_looks;
7551 hdr_loads.min = hdr_loads.max = v_loads;
7552 hdr_gets.min = hdr_gets.max = v_gets;
7553 hdr_loads.sum = hdr_gets.sum = 0;
7555 vp = queue_Next(vp, Volume);
7557 /* pull in stats from remaining elements in chain */
7558 for (queue_ScanFrom(head, vp, vp, np, Volume)) {
7559 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
7560 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
7561 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
7563 hdr_loads.sum += v_loads;
7564 hdr_gets.sum += v_gets;
7566 if (v_looks < ch_gets.min)
7567 ch_gets.min = v_looks;
7568 else if (v_looks > ch_gets.max)
7569 ch_gets.max = v_looks;
7571 if (v_loads < hdr_loads.min)
7572 hdr_loads.min = v_loads;
7573 else if (v_loads > hdr_loads.max)
7574 hdr_loads.max = v_loads;
7576 if (v_gets < hdr_gets.min)
7577 hdr_gets.min = v_gets;
7578 else if (v_gets > hdr_gets.max)
7579 hdr_gets.max = v_gets;
7582 /* compute per-chain averages */
7583 ch_gets.avg = ch_gets.sum / ((double)head->len);
7584 hdr_loads.avg = hdr_loads.sum / ((double)head->len);
7585 hdr_gets.avg = hdr_gets.sum / ((double)head->len);
7587 /* dump per-chain stats */
7588 Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
7590 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
7591 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
7592 Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
7593 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
7594 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
7595 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
7596 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
7597 Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
7598 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
7599 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
7600 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
7601 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
7602 Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
7603 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
7604 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
7605 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
7606 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
7607 } else if (flags & VOL_STATS_PER_CHAIN) {
7608 /* dump simple per-chain stats */
7609 Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
7611 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
7612 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
7613 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
7617 VHashEndExclusive_r(head);
7622 /* compute global averages */
7623 len.avg = len.sum / ((double)VolumeHashTable.Size);
7624 looks.avg = looks.sum / ((double)VolumeHashTable.Size);
7625 gets.avg = gets.sum / ((double)VolumeHashTable.Size);
7626 reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
7628 /* dump global stats */
7629 Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
7630 Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
7631 DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
7632 DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
7633 DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
7634 DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
7635 Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
7636 DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
7637 DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
7638 DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
7639 DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
7640 Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
7641 DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
7642 DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
7643 DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
7644 DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
7645 Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
7646 DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
7647 DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
7648 DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
7649 DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
7651 /* print extended disk related statistics */
7653 struct DiskPartition64 * diskP;
7654 afs_uint32 vol_count[VOLMAXPARTS+1];
7655 byte part_exists[VOLMAXPARTS+1];
7659 memset(vol_count, 0, sizeof(vol_count));
7660 memset(part_exists, 0, sizeof(part_exists));
7664 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
7666 vol_count[id] = diskP->vol_list.len;
7667 part_exists[id] = 1;
7671 for (i = 0; i <= VOLMAXPARTS; i++) {
7672 if (part_exists[i]) {
7673 /* XXX while this is currently safe, it is a violation
7674 * of the VGetPartitionById_r interface contract. */
7675 diskP = VGetPartitionById_r(i, 0);
7677 Log("Partition %s has %d online volumes\n",
7678 VPartitionPath(diskP), diskP->vol_list.len);
7685 /* print extended VLRU statistics */
7686 if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
7687 afs_uint32 idx, cur, lpos;
7691 Log("VLRU State Dump:\n\n");
7693 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
7694 Log("\t%s:\n", vlru_idx_to_string(idx));
7697 for (cur = vlru_stats.queue_info[idx].start;
7698 cur < vlru_stats.queue_info[idx].len;
7700 line[lpos++] = vlru_stats.vec[cur].volid;
7702 Log("\t\t%u, %u, %u, %u, %u,\n",
7703 line[0], line[1], line[2], line[3], line[4]);
7712 Log("\t\t%u, %u, %u, %u, %u\n",
7713 line[0], line[1], line[2], line[3], line[4]);
7718 free(vlru_stats.vec);
7725 VPrintExtendedCacheStats(int flags)
7728 VPrintExtendedCacheStats_r(flags);
7731 #endif /* AFS_DEMAND_ATTACH_FS */
7734 VCanScheduleSalvage(void)
7736 return vol_opts.canScheduleSalvage;
7742 return vol_opts.canUseFSSYNC;
7746 VCanUseSALVSYNC(void)
7748 return vol_opts.canUseSALVSYNC;