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>
28 #include <afs/afsint.h>
31 #include <sys/param.h>
32 #if !defined(AFS_SGI_ENV)
35 #else /* AFS_OSF_ENV */
36 #ifdef AFS_VFSINCL_ENV
39 #include <sys/fs/ufs_fs.h>
41 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
42 #include <ufs/ufs/dinode.h>
43 #include <ufs/ffs/fs.h>
48 #else /* AFS_VFSINCL_ENV */
49 #if !defined(AFS_AIX_ENV) && !defined(AFS_LINUX20_ENV) && !defined(AFS_XBSD_ENV)
52 #endif /* AFS_VFSINCL_ENV */
53 #endif /* AFS_OSF_ENV */
54 #endif /* AFS_SGI_ENV */
55 #endif /* AFS_NT40_ENV */
73 #if defined(AFS_SUN_ENV) || defined(AFS_SUN5_ENV)
75 #include <sys/mnttab.h>
76 #include <sys/mntent.h>
82 #if defined(AFS_SGI_ENV)
87 #ifndef AFS_LINUX20_ENV
88 #include <fstab.h> /* Need to find in libc 5, present in libc 6 */
91 #endif /* AFS_SGI_ENV */
93 #endif /* AFS_HPUX_ENV */
97 #include <netinet/in.h>
101 #include <sys/time.h>
102 #endif /* ITIMER_REAL */
103 #endif /* AFS_NT40_ENV */
104 #if defined(AFS_SUN5_ENV) || defined(AFS_NT40_ENV) || defined(AFS_LINUX20_ENV)
111 #include <afs/errors.h>
114 #include <afs/afssyscalls.h>
116 #include <afs/afsutil.h>
120 #include "daemon_com.h"
122 #include "salvsync.h"
125 #include "partition.h"
126 #include "volume_inline.h"
127 #ifdef AFS_PTHREAD_ENV
129 #else /* AFS_PTHREAD_ENV */
130 #include "afs/assert.h"
131 #endif /* AFS_PTHREAD_ENV */
138 #if !defined(offsetof)
143 #define afs_stat stat64
144 #define afs_fstat fstat64
145 #define afs_open open64
146 #else /* !O_LARGEFILE */
147 #define afs_stat stat
148 #define afs_fstat fstat
149 #define afs_open open
150 #endif /* !O_LARGEFILE */
152 #ifdef AFS_PTHREAD_ENV
153 pthread_mutex_t vol_glock_mutex;
154 pthread_mutex_t vol_trans_mutex;
155 pthread_cond_t vol_put_volume_cond;
156 pthread_cond_t vol_sleep_cond;
157 int vol_attach_threads = 1;
158 #endif /* AFS_PTHREAD_ENV */
160 #ifdef AFS_DEMAND_ATTACH_FS
161 pthread_mutex_t vol_salvsync_mutex;
162 #endif /* AFS_DEMAND_ATTACH_FS */
165 extern void *calloc(), *realloc();
168 /*@printflike@*/ extern void Log(const char *format, ...);
170 /* Forward declarations */
171 static Volume *attach2(Error * ec, VolId vid, char *path,
172 register struct VolumeHeader *header,
173 struct DiskPartition64 *partp, Volume * vp,
174 int isbusy, int mode);
175 static void ReallyFreeVolume(Volume * vp);
176 #ifdef AFS_DEMAND_ATTACH_FS
177 static void FreeVolume(Volume * vp);
178 #else /* !AFS_DEMAND_ATTACH_FS */
179 #define FreeVolume(vp) ReallyFreeVolume(vp)
180 static void VScanUpdateList(void);
181 #endif /* !AFS_DEMAND_ATTACH_FS */
182 static void VInitVolumeHeaderCache(afs_uint32 howMany);
183 static int GetVolumeHeader(register Volume * vp);
184 static void ReleaseVolumeHeader(register struct volHeader *hd);
185 static void FreeVolumeHeader(register Volume * vp);
186 static void AddVolumeToHashTable(register Volume * vp, int hashid);
187 static void DeleteVolumeFromHashTable(register Volume * vp);
188 static int VHold(Volume * vp);
189 static int VHold_r(Volume * vp);
190 static void VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class);
191 static void VReleaseVolumeHandles_r(Volume * vp);
192 static void VCloseVolumeHandles_r(Volume * vp);
193 static void LoadVolumeHeader(Error * ec, Volume * vp);
194 static int VCheckOffline(register Volume * vp);
195 static int VCheckDetach(register Volume * vp);
196 static Volume * GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint, int flags);
197 static int VolumeExternalName_r(VolumeId volumeId, char * name, size_t len);
199 int LogLevel; /* Vice loglevel--not defined as extern so that it will be
200 * defined when not linked with vice, XXXX */
201 ProgramType programType; /* The type of program using the package */
203 /* extended volume package statistics */
206 #ifdef VOL_LOCK_DEBUG
207 pthread_t vol_glock_holder = 0;
211 #define VOLUME_BITMAP_GROWSIZE 16 /* bytes, => 128vnodes */
212 /* Must be a multiple of 4 (1 word) !! */
214 /* this parameter needs to be tunable at runtime.
215 * 128 was really inadequate for largish servers -- at 16384 volumes this
216 * puts average chain length at 128, thus an average 65 deref's to find a volptr.
217 * talk about bad spatial locality...
219 * an AVL or splay tree might work a lot better, but we'll just increase
220 * the default hash table size for now
222 #define DEFAULT_VOLUME_HASH_SIZE 256 /* Must be a power of 2!! */
223 #define DEFAULT_VOLUME_HASH_MASK (DEFAULT_VOLUME_HASH_SIZE-1)
224 #define VOLUME_HASH(volumeId) (volumeId&(VolumeHashTable.Mask))
227 * turn volume hash chains into partially ordered lists.
228 * when the threshold is exceeded between two adjacent elements,
229 * perform a chain rebalancing operation.
231 * keep the threshold high in order to keep cache line invalidates
232 * low "enough" on SMPs
234 #define VOLUME_HASH_REORDER_THRESHOLD 200
237 * when possible, don't just reorder single elements, but reorder
238 * entire chains of elements at once. a chain of elements that
239 * exceed the element previous to the pivot by at least CHAIN_THRESH
240 * accesses are moved in front of the chain whose elements have at
241 * least CHAIN_THRESH less accesses than the pivot element
243 #define VOLUME_HASH_REORDER_CHAIN_THRESH (VOLUME_HASH_REORDER_THRESHOLD / 2)
245 #include "rx/rx_queue.h"
248 VolumeHashTable_t VolumeHashTable = {
249 DEFAULT_VOLUME_HASH_SIZE,
250 DEFAULT_VOLUME_HASH_MASK,
255 static void VInitVolumeHash(void);
259 /* This macro is used where an ffs() call does not exist. Was in util/ffs.c */
263 afs_int32 ffs_tmp = x;
267 for (ffs_i = 1;; ffs_i++) {
274 #endif /* !AFS_HAVE_FFS */
276 #ifdef AFS_PTHREAD_ENV
277 typedef struct diskpartition_queue_t {
278 struct rx_queue queue;
279 struct DiskPartition64 * diskP;
280 } diskpartition_queue_t;
281 typedef struct vinitvolumepackage_thread_t {
282 struct rx_queue queue;
283 pthread_cond_t thread_done_cv;
284 int n_threads_complete;
285 } vinitvolumepackage_thread_t;
286 static void * VInitVolumePackageThread(void * args);
287 #endif /* AFS_PTHREAD_ENV */
289 static int VAttachVolumesByPartition(struct DiskPartition64 *diskP,
290 int * nAttached, int * nUnattached);
293 #ifdef AFS_DEMAND_ATTACH_FS
294 /* demand attach fileserver extensions */
297 * in the future we will support serialization of VLRU state into the fs_state
300 * these structures are the beginning of that effort
302 struct VLRU_DiskHeader {
303 struct versionStamp stamp; /* magic and structure version number */
304 afs_uint32 mtime; /* time of dump to disk */
305 afs_uint32 num_records; /* number of VLRU_DiskEntry records */
308 struct VLRU_DiskEntry {
309 afs_uint32 vid; /* volume ID */
310 afs_uint32 idx; /* generation */
311 afs_uint32 last_get; /* timestamp of last get */
314 struct VLRU_StartupQueue {
315 struct VLRU_DiskEntry * entry;
320 typedef struct vshutdown_thread_t {
322 pthread_mutex_t lock;
324 pthread_cond_t master_cv;
326 int n_threads_complete;
328 int schedule_version;
331 byte n_parts_done_pass;
332 byte part_thread_target[VOLMAXPARTS+1];
333 byte part_done_pass[VOLMAXPARTS+1];
334 struct rx_queue * part_pass_head[VOLMAXPARTS+1];
335 int stats[4][VOLMAXPARTS+1];
336 } vshutdown_thread_t;
337 static void * VShutdownThread(void * args);
340 static Volume * VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode);
341 static int VCheckFree(Volume * vp);
344 static void AddVolumeToVByPList_r(Volume * vp);
345 static void DeleteVolumeFromVByPList_r(Volume * vp);
346 static void VVByPListBeginExclusive_r(struct DiskPartition64 * dp);
347 static void VVByPListEndExclusive_r(struct DiskPartition64 * dp);
348 static void VVByPListWait_r(struct DiskPartition64 * dp);
350 /* online salvager */
351 static int VCheckSalvage(register Volume * vp);
352 static int VUpdateSalvagePriority_r(Volume * vp);
353 static int VScheduleSalvage_r(Volume * vp);
354 static int VCancelSalvage_r(Volume * vp, int reason);
356 /* Volume hash table */
357 static void VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp);
358 static void VHashBeginExclusive_r(VolumeHashChainHead * head);
359 static void VHashEndExclusive_r(VolumeHashChainHead * head);
360 static void VHashWait_r(VolumeHashChainHead * head);
363 static int ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass);
364 static int ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
365 struct rx_queue ** idx);
366 static void ShutdownController(vshutdown_thread_t * params);
367 static void ShutdownCreateSchedule(vshutdown_thread_t * params);
370 static void VLRU_ComputeConstants(void);
371 static void VInitVLRU(void);
372 static void VLRU_Init_Node_r(volatile Volume * vp);
373 static void VLRU_Add_r(volatile Volume * vp);
374 static void VLRU_Delete_r(volatile Volume * vp);
375 static void VLRU_UpdateAccess_r(volatile Volume * vp);
376 static void * VLRU_ScannerThread(void * args);
377 static void VLRU_Scan_r(int idx);
378 static void VLRU_Promote_r(int idx);
379 static void VLRU_Demote_r(int idx);
380 static void VLRU_SwitchQueues(volatile Volume * vp, int new_idx, int append);
383 static int VCheckSoftDetach(volatile Volume * vp, afs_uint32 thresh);
384 static int VCheckSoftDetachCandidate(volatile Volume * vp, afs_uint32 thresh);
385 static int VSoftDetachVolume_r(volatile Volume * vp, afs_uint32 thresh);
388 pthread_key_t VThread_key;
389 VThreadOptions_t VThread_defaults = {
390 0 /**< allow salvsync */
392 #endif /* AFS_DEMAND_ATTACH_FS */
395 struct Lock vol_listLock; /* Lock obtained when listing volumes:
396 * prevents a volume from being missed
397 * if the volume is attached during a
401 static int TimeZoneCorrection; /* Number of seconds west of GMT */
403 /* Common message used when the volume goes off line */
404 char *VSalvageMessage =
405 "Files in this volume are currently unavailable; call operations";
407 int VInit; /* 0 - uninitialized,
408 * 1 - initialized but not all volumes have been attached,
409 * 2 - initialized and all volumes have been attached,
410 * 3 - initialized, all volumes have been attached, and
411 * VConnectFS() has completed. */
414 bit32 VolumeCacheCheck; /* Incremented everytime a volume goes on line--
415 * used to stamp volume headers and in-core
416 * vnodes. When the volume goes on-line the
417 * vnode will be invalidated
418 * access only with VOL_LOCK held */
423 /***************************************************/
424 /* Startup routines */
425 /***************************************************/
428 VInitVolumePackage(ProgramType pt, afs_uint32 nLargeVnodes, afs_uint32 nSmallVnodes,
429 int connect, afs_uint32 volcache)
431 int errors = 0; /* Number of errors while finding vice partitions. */
437 memset(&VStats, 0, sizeof(VStats));
438 VStats.hdr_cache_size = 200;
440 VInitPartitionPackage();
442 #ifdef AFS_DEMAND_ATTACH_FS
443 if (programType == fileServer) {
446 VLRU_SetOptions(VLRU_SET_ENABLED, 0);
448 assert(pthread_key_create(&VThread_key, NULL) == 0);
451 #ifdef AFS_PTHREAD_ENV
452 assert(pthread_mutex_init(&vol_glock_mutex, NULL) == 0);
453 assert(pthread_mutex_init(&vol_trans_mutex, NULL) == 0);
454 assert(pthread_cond_init(&vol_put_volume_cond, NULL) == 0);
455 assert(pthread_cond_init(&vol_sleep_cond, NULL) == 0);
456 #else /* AFS_PTHREAD_ENV */
458 #endif /* AFS_PTHREAD_ENV */
459 Lock_Init(&vol_listLock);
461 srandom(time(0)); /* For VGetVolumeInfo */
462 gettimeofday(&tv, &tz);
463 TimeZoneCorrection = tz.tz_minuteswest * 60;
465 #ifdef AFS_DEMAND_ATTACH_FS
466 assert(pthread_mutex_init(&vol_salvsync_mutex, NULL) == 0);
467 #endif /* AFS_DEMAND_ATTACH_FS */
469 /* Ok, we have done enough initialization that fileserver can
470 * start accepting calls, even though the volumes may not be
471 * available just yet.
475 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_SERVER)
476 if (programType == salvageServer) {
479 #endif /* AFS_DEMAND_ATTACH_FS */
480 #ifdef FSSYNC_BUILD_SERVER
481 if (programType == fileServer) {
485 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_CLIENT)
486 if (programType == fileServer) {
487 /* establish a connection to the salvager at this point */
488 assert(VConnectSALV() != 0);
490 #endif /* AFS_DEMAND_ATTACH_FS */
492 if (volcache > VStats.hdr_cache_size)
493 VStats.hdr_cache_size = volcache;
494 VInitVolumeHeaderCache(VStats.hdr_cache_size);
496 VInitVnodes(vLarge, nLargeVnodes);
497 VInitVnodes(vSmall, nSmallVnodes);
500 errors = VAttachPartitions();
504 if (programType == fileServer) {
505 struct DiskPartition64 *diskP;
506 #ifdef AFS_PTHREAD_ENV
507 struct vinitvolumepackage_thread_t params;
508 struct diskpartition_queue_t * dpq;
509 int i, threads, parts;
511 pthread_attr_t attrs;
513 assert(pthread_cond_init(¶ms.thread_done_cv,NULL) == 0);
515 params.n_threads_complete = 0;
517 /* create partition work queue */
518 for (parts=0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
519 dpq = (diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
522 queue_Append(¶ms,dpq);
525 threads = MIN(parts, vol_attach_threads);
528 /* spawn off a bunch of initialization threads */
529 assert(pthread_attr_init(&attrs) == 0);
530 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
532 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
533 #ifdef AFS_DEMAND_ATTACH_FS
534 Log("VInitVolumePackage: using %d threads to pre-attach volumes on %d partitions\n",
536 #else /* AFS_DEMAND_ATTACH_FS */
537 Log("VInitVolumePackage: using %d threads to attach volumes on %d partitions\n",
539 #endif /* AFS_DEMAND_ATTACH_FS */
542 for (i=0; i < threads; i++) {
543 assert(pthread_create
544 (&tid, &attrs, &VInitVolumePackageThread,
548 while(params.n_threads_complete < threads) {
549 VOL_CV_WAIT(¶ms.thread_done_cv);
553 assert(pthread_attr_destroy(&attrs) == 0);
555 /* if we're only going to run one init thread, don't bother creating
557 Log("VInitVolumePackage: beginning single-threaded fileserver startup\n");
558 #ifdef AFS_DEMAND_ATTACH_FS
559 Log("VInitVolumePackage: using 1 thread to pre-attach volumes on %d partition(s)\n",
561 #else /* AFS_DEMAND_ATTACH_FS */
562 Log("VInitVolumePackage: using 1 thread to attach volumes on %d partition(s)\n",
564 #endif /* AFS_DEMAND_ATTACH_FS */
566 VInitVolumePackageThread(¶ms);
569 assert(pthread_cond_destroy(¶ms.thread_done_cv) == 0);
571 #else /* AFS_PTHREAD_ENV */
575 /* Attach all the volumes in this partition */
576 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
577 int nAttached = 0, nUnattached = 0;
578 assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
580 #endif /* AFS_PTHREAD_ENV */
583 VInit = 2; /* Initialized, and all volumes have been attached */
584 #ifdef FSSYNC_BUILD_CLIENT
585 if (programType == volumeUtility && connect) {
587 Log("Unable to connect to file server; will retry at need\n");
591 #ifdef AFS_DEMAND_ATTACH_FS
592 else if (programType == salvageServer) {
594 Log("Unable to connect to file server; aborted\n");
598 #endif /* AFS_DEMAND_ATTACH_FS */
599 #endif /* FSSYNC_BUILD_CLIENT */
603 #ifdef AFS_PTHREAD_ENV
605 VInitVolumePackageThread(void * args) {
606 int errors = 0; /* Number of errors while finding vice partitions. */
610 struct DiskPartition64 *diskP;
611 struct vinitvolumepackage_thread_t * params;
612 struct diskpartition_queue_t * dpq;
614 params = (vinitvolumepackage_thread_t *) args;
618 /* Attach all the volumes in this partition */
619 while (queue_IsNotEmpty(params)) {
620 int nAttached = 0, nUnattached = 0;
622 dpq = queue_First(params,diskpartition_queue_t);
628 assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
633 params->n_threads_complete++;
634 pthread_cond_signal(¶ms->thread_done_cv);
638 #endif /* AFS_PTHREAD_ENV */
641 * attach all volumes on a given disk partition
644 VAttachVolumesByPartition(struct DiskPartition64 *diskP, int * nAttached, int * nUnattached)
650 Log("Partition %s: attaching volumes\n", diskP->name);
651 dirp = opendir(VPartitionPath(diskP));
653 Log("opendir on Partition %s failed!\n", diskP->name);
657 while ((dp = readdir(dirp))) {
659 p = strrchr(dp->d_name, '.');
660 if (p != NULL && strcmp(p, VHDREXT) == 0) {
663 #ifdef AFS_DEMAND_ATTACH_FS
664 vp = VPreAttachVolumeByName(&error, diskP->name, dp->d_name);
665 #else /* AFS_DEMAND_ATTACH_FS */
666 vp = VAttachVolumeByName(&error, diskP->name, dp->d_name,
668 #endif /* AFS_DEMAND_ATTACH_FS */
669 (*(vp ? nAttached : nUnattached))++;
670 if (error == VOFFLINE)
671 Log("Volume %d stays offline (/vice/offline/%s exists)\n", VolumeNumber(dp->d_name), dp->d_name);
672 else if (LogLevel >= 5) {
673 Log("Partition %s: attached volume %d (%s)\n",
674 diskP->name, VolumeNumber(dp->d_name),
677 #if !defined(AFS_DEMAND_ATTACH_FS)
681 #endif /* AFS_DEMAND_ATTACH_FS */
685 Log("Partition %s: attached %d volumes; %d volumes not attached\n", diskP->name, *nAttached, *nUnattached);
691 /***************************************************/
692 /* Shutdown routines */
693 /***************************************************/
697 * highly multithreaded volume package shutdown
699 * with the demand attach fileserver extensions,
700 * VShutdown has been modified to be multithreaded.
701 * In order to achieve optimal use of many threads,
702 * the shutdown code involves one control thread and
703 * n shutdown worker threads. The control thread
704 * periodically examines the number of volumes available
705 * for shutdown on each partition, and produces a worker
706 * thread allocation schedule. The idea is to eliminate
707 * redundant scheduling computation on the workers by
708 * having a single master scheduler.
710 * The scheduler's objectives are:
712 * each partition with volumes remaining gets allocated
713 * at least 1 thread (assuming sufficient threads)
715 * threads are allocated proportional to the number of
716 * volumes remaining to be offlined. This ensures that
717 * the OS I/O scheduler has many requests to elevator
718 * seek on partitions that will (presumably) take the
719 * longest amount of time (from now) to finish shutdown
720 * (3) keep threads busy
721 * when there are extra threads, they are assigned to
722 * partitions using a simple round-robin algorithm
724 * In the future, we may wish to add the ability to adapt
725 * to the relative performance patterns of each disk
730 * multi-step shutdown process
732 * demand attach shutdown is a four-step process. Each
733 * shutdown "pass" shuts down increasingly more difficult
734 * volumes. The main purpose is to achieve better cache
735 * utilization during shutdown.
738 * shutdown volumes in the unattached, pre-attached
741 * shutdown attached volumes with cached volume headers
743 * shutdown all volumes in non-exclusive states
745 * shutdown all remaining volumes
752 register Volume *vp, *np;
753 register afs_int32 code;
754 #ifdef AFS_DEMAND_ATTACH_FS
755 struct DiskPartition64 * diskP;
756 struct diskpartition_queue_t * dpq;
757 vshutdown_thread_t params;
759 pthread_attr_t attrs;
761 memset(¶ms, 0, sizeof(vshutdown_thread_t));
763 for (params.n_parts=0, diskP = DiskPartitionList;
764 diskP; diskP = diskP->next, params.n_parts++);
766 Log("VShutdown: shutting down on-line volumes on %d partition%s...\n",
767 params.n_parts, params.n_parts > 1 ? "s" : "");
769 if (vol_attach_threads > 1) {
770 /* prepare for parallel shutdown */
771 params.n_threads = vol_attach_threads;
772 assert(pthread_mutex_init(¶ms.lock, NULL) == 0);
773 assert(pthread_cond_init(¶ms.cv, NULL) == 0);
774 assert(pthread_cond_init(¶ms.master_cv, NULL) == 0);
775 assert(pthread_attr_init(&attrs) == 0);
776 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
779 /* setup the basic partition information structures for
780 * parallel shutdown */
781 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
783 struct rx_queue * qp, * nqp;
787 VVByPListWait_r(diskP);
788 VVByPListBeginExclusive_r(diskP);
791 for (queue_Scan(&diskP->vol_list, qp, nqp, rx_queue)) {
792 vp = (Volume *)((char *)qp - offsetof(Volume, vol_list));
796 Log("VShutdown: partition %s has %d volumes with attached headers\n",
797 VPartitionPath(diskP), count);
800 /* build up the pass 0 shutdown work queue */
801 dpq = (struct diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
804 queue_Prepend(¶ms, dpq);
806 params.part_pass_head[diskP->index] = queue_First(&diskP->vol_list, rx_queue);
809 Log("VShutdown: beginning parallel fileserver shutdown\n");
810 Log("VShutdown: using %d threads to offline volumes on %d partition%s\n",
811 vol_attach_threads, params.n_parts, params.n_parts > 1 ? "s" : "" );
813 /* do pass 0 shutdown */
814 assert(pthread_mutex_lock(¶ms.lock) == 0);
815 for (i=0; i < params.n_threads; i++) {
816 assert(pthread_create
817 (&tid, &attrs, &VShutdownThread,
821 /* wait for all the pass 0 shutdowns to complete */
822 while (params.n_threads_complete < params.n_threads) {
823 assert(pthread_cond_wait(¶ms.master_cv, ¶ms.lock) == 0);
825 params.n_threads_complete = 0;
827 assert(pthread_cond_broadcast(¶ms.cv) == 0);
828 assert(pthread_mutex_unlock(¶ms.lock) == 0);
830 Log("VShutdown: pass 0 completed using the 1 thread per partition algorithm\n");
831 Log("VShutdown: starting passes 1 through 3 using finely-granular mp-fast algorithm\n");
833 /* run the parallel shutdown scheduler. it will drop the glock internally */
834 ShutdownController(¶ms);
836 /* wait for all the workers to finish pass 3 and terminate */
837 while (params.pass < 4) {
838 VOL_CV_WAIT(¶ms.cv);
841 assert(pthread_attr_destroy(&attrs) == 0);
842 assert(pthread_cond_destroy(¶ms.cv) == 0);
843 assert(pthread_cond_destroy(¶ms.master_cv) == 0);
844 assert(pthread_mutex_destroy(¶ms.lock) == 0);
846 /* drop the VByPList exclusive reservations */
847 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
848 VVByPListEndExclusive_r(diskP);
849 Log("VShutdown: %s stats : (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
850 VPartitionPath(diskP),
851 params.stats[0][diskP->index],
852 params.stats[1][diskP->index],
853 params.stats[2][diskP->index],
854 params.stats[3][diskP->index]);
857 Log("VShutdown: shutdown finished using %d threads\n", params.n_threads);
859 /* if we're only going to run one shutdown thread, don't bother creating
861 Log("VShutdown: beginning single-threaded fileserver shutdown\n");
863 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
864 VShutdownByPartition_r(diskP);
868 Log("VShutdown: complete.\n");
869 #else /* AFS_DEMAND_ATTACH_FS */
870 Log("VShutdown: shutting down on-line volumes...\n");
871 for (i = 0; i < VolumeHashTable.Size; i++) {
872 /* try to hold first volume in the hash table */
873 for (queue_Scan(&VolumeHashTable.Table[i],vp,np,Volume)) {
877 Log("VShutdown: Attempting to take volume %u offline.\n",
880 /* next, take the volume offline (drops reference count) */
881 VOffline_r(vp, "File server was shut down");
885 Log("VShutdown: complete.\n");
886 #endif /* AFS_DEMAND_ATTACH_FS */
897 #ifdef AFS_DEMAND_ATTACH_FS
900 * shutdown control thread
903 ShutdownController(vshutdown_thread_t * params)
906 struct DiskPartition64 * diskP;
908 vshutdown_thread_t shadow;
910 ShutdownCreateSchedule(params);
912 while ((params->pass < 4) &&
913 (params->n_threads_complete < params->n_threads)) {
914 /* recompute schedule once per second */
916 memcpy(&shadow, params, sizeof(vshutdown_thread_t));
920 Log("ShutdownController: schedule version=%d, vol_remaining=%d, pass=%d\n",
921 shadow.schedule_version, shadow.vol_remaining, shadow.pass);
922 Log("ShutdownController: n_threads_complete=%d, n_parts_done_pass=%d\n",
923 shadow.n_threads_complete, shadow.n_parts_done_pass);
924 for (diskP = DiskPartitionList; diskP; diskP=diskP->next) {
926 Log("ShutdownController: part[%d] : (len=%d, thread_target=%d, done_pass=%d, pass_head=%p)\n",
929 shadow.part_thread_target[id],
930 shadow.part_done_pass[id],
931 shadow.part_pass_head[id]);
937 ShutdownCreateSchedule(params);
941 /* create the shutdown thread work schedule.
942 * this scheduler tries to implement fairness
943 * by allocating at least 1 thread to each
944 * partition with volumes to be shutdown,
945 * and then it attempts to allocate remaining
946 * threads based upon the amount of work left
949 ShutdownCreateSchedule(vshutdown_thread_t * params)
951 struct DiskPartition64 * diskP;
952 int sum, thr_workload, thr_left;
953 int part_residue[VOLMAXPARTS+1];
956 /* compute the total number of outstanding volumes */
958 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
959 sum += diskP->vol_list.len;
962 params->schedule_version++;
963 params->vol_remaining = sum;
968 /* compute average per-thread workload */
969 thr_workload = sum / params->n_threads;
970 if (sum % params->n_threads)
973 thr_left = params->n_threads;
974 memset(&part_residue, 0, sizeof(part_residue));
976 /* for fairness, give every partition with volumes remaining
977 * at least one thread */
978 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
980 if (diskP->vol_list.len) {
981 params->part_thread_target[id] = 1;
984 params->part_thread_target[id] = 0;
988 if (thr_left && thr_workload) {
989 /* compute length-weighted workloads */
992 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
994 delta = (diskP->vol_list.len / thr_workload) -
995 params->part_thread_target[id];
999 if (delta < thr_left) {
1000 params->part_thread_target[id] += delta;
1003 params->part_thread_target[id] += thr_left;
1011 /* try to assign any leftover threads to partitions that
1012 * had volume lengths closer to needing thread_target+1 */
1013 int max_residue, max_id;
1015 /* compute the residues */
1016 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1018 part_residue[id] = diskP->vol_list.len -
1019 (params->part_thread_target[id] * thr_workload);
1022 /* now try to allocate remaining threads to partitions with the
1023 * highest residues */
1026 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1028 if (part_residue[id] > max_residue) {
1029 max_residue = part_residue[id];
1038 params->part_thread_target[max_id]++;
1040 part_residue[max_id] = 0;
1045 /* punt and give any remaining threads equally to each partition */
1047 if (thr_left >= params->n_parts) {
1048 alloc = thr_left / params->n_parts;
1049 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1051 params->part_thread_target[id] += alloc;
1056 /* finish off the last of the threads */
1057 for (diskP = DiskPartitionList; thr_left && diskP; diskP = diskP->next) {
1059 params->part_thread_target[id]++;
1065 /* worker thread for parallel shutdown */
1067 VShutdownThread(void * args)
1069 struct rx_queue *qp;
1071 vshutdown_thread_t * params;
1072 int part, code, found, pass, schedule_version_save, count;
1073 struct DiskPartition64 *diskP;
1074 struct diskpartition_queue_t * dpq;
1077 params = (vshutdown_thread_t *) args;
1079 /* acquire the shutdown pass 0 lock */
1080 assert(pthread_mutex_lock(¶ms->lock) == 0);
1082 /* if there's still pass 0 work to be done,
1083 * get a work entry, and do a pass 0 shutdown */
1084 if (queue_IsNotEmpty(params)) {
1085 dpq = queue_First(params, diskpartition_queue_t);
1087 assert(pthread_mutex_unlock(¶ms->lock) == 0);
1093 while (ShutdownVolumeWalk_r(diskP, 0, ¶ms->part_pass_head[id]))
1095 params->stats[0][diskP->index] = count;
1096 assert(pthread_mutex_lock(¶ms->lock) == 0);
1099 params->n_threads_complete++;
1100 if (params->n_threads_complete == params->n_threads) {
1101 /* notify control thread that all workers have completed pass 0 */
1102 assert(pthread_cond_signal(¶ms->master_cv) == 0);
1104 while (params->pass == 0) {
1105 assert(pthread_cond_wait(¶ms->cv, ¶ms->lock) == 0);
1109 assert(pthread_mutex_unlock(¶ms->lock) == 0);
1112 pass = params->pass;
1115 /* now escalate through the more complicated shutdowns */
1117 schedule_version_save = params->schedule_version;
1119 /* find a disk partition to work on */
1120 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1122 if (params->part_thread_target[id] && !params->part_done_pass[id]) {
1123 params->part_thread_target[id]--;
1130 /* hmm. for some reason the controller thread couldn't find anything for
1131 * us to do. let's see if there's anything we can do */
1132 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1134 if (diskP->vol_list.len && !params->part_done_pass[id]) {
1137 } else if (!params->part_done_pass[id]) {
1138 params->part_done_pass[id] = 1;
1139 params->n_parts_done_pass++;
1141 Log("VShutdown: done shutting down volumes on partition %s.\n",
1142 VPartitionPath(diskP));
1148 /* do work on this partition until either the controller
1149 * creates a new schedule, or we run out of things to do
1150 * on this partition */
1153 while (!params->part_done_pass[id] &&
1154 (schedule_version_save == params->schedule_version)) {
1155 /* ShutdownVolumeWalk_r will drop the glock internally */
1156 if (!ShutdownVolumeWalk_r(diskP, pass, ¶ms->part_pass_head[id])) {
1157 if (!params->part_done_pass[id]) {
1158 params->part_done_pass[id] = 1;
1159 params->n_parts_done_pass++;
1161 Log("VShutdown: done shutting down volumes on partition %s.\n",
1162 VPartitionPath(diskP));
1170 params->stats[pass][id] += count;
1172 /* ok, everyone is done this pass, proceed */
1175 params->n_threads_complete++;
1176 while (params->pass == pass) {
1177 if (params->n_threads_complete == params->n_threads) {
1178 /* we are the last thread to complete, so we will
1179 * reinitialize worker pool state for the next pass */
1180 params->n_threads_complete = 0;
1181 params->n_parts_done_pass = 0;
1183 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1185 params->part_done_pass[id] = 0;
1186 params->part_pass_head[id] = queue_First(&diskP->vol_list, rx_queue);
1189 /* compute a new thread schedule before releasing all the workers */
1190 ShutdownCreateSchedule(params);
1192 /* wake up all the workers */
1193 assert(pthread_cond_broadcast(¶ms->cv) == 0);
1196 Log("VShutdown: pass %d completed using %d threads on %d partitions\n",
1197 pass, params->n_threads, params->n_parts);
1200 VOL_CV_WAIT(¶ms->cv);
1203 pass = params->pass;
1217 /* shut down all volumes on a given disk partition
1219 * note that this function will not allow mp-fast
1220 * shutdown of a partition */
1222 VShutdownByPartition_r(struct DiskPartition64 * dp)
1228 /* wait for other exclusive ops to finish */
1229 VVByPListWait_r(dp);
1231 /* begin exclusive access */
1232 VVByPListBeginExclusive_r(dp);
1234 /* pick the low-hanging fruit first,
1235 * then do the complicated ones last
1236 * (has the advantage of keeping
1237 * in-use volumes up until the bitter end) */
1238 for (pass = 0, total=0; pass < 4; pass++) {
1239 pass_stats[pass] = ShutdownVByPForPass_r(dp, pass);
1240 total += pass_stats[pass];
1243 /* end exclusive access */
1244 VVByPListEndExclusive_r(dp);
1246 Log("VShutdownByPartition: shut down %d volumes on %s (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1247 total, VPartitionPath(dp), pass_stats[0], pass_stats[1], pass_stats[2], pass_stats[3]);
1252 /* internal shutdown functionality
1254 * for multi-pass shutdown:
1255 * 0 to only "shutdown" {pre,un}attached and error state volumes
1256 * 1 to also shutdown attached volumes w/ volume header loaded
1257 * 2 to also shutdown attached volumes w/o volume header loaded
1258 * 3 to also shutdown exclusive state volumes
1260 * caller MUST hold exclusive access on the hash chain
1261 * because we drop vol_glock_mutex internally
1263 * this function is reentrant for passes 1--3
1264 * (e.g. multiple threads can cooperate to
1265 * shutdown a partition mp-fast)
1267 * pass 0 is not scaleable because the volume state data is
1268 * synchronized by vol_glock mutex, and the locking overhead
1269 * is too high to drop the lock long enough to do linked list
1273 ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass)
1275 struct rx_queue * q = queue_First(&dp->vol_list, rx_queue);
1278 while (ShutdownVolumeWalk_r(dp, pass, &q))
1284 /* conditionally shutdown one volume on partition dp
1285 * returns 1 if a volume was shutdown in this pass,
1288 ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
1289 struct rx_queue ** idx)
1291 struct rx_queue *qp, *nqp;
1296 for (queue_ScanFrom(&dp->vol_list, qp, qp, nqp, rx_queue)) {
1297 vp = (Volume *) (((char *)qp) - offsetof(Volume, vol_list));
1301 if ((V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1302 (V_attachState(vp) != VOL_STATE_ERROR) &&
1303 (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1307 if ((V_attachState(vp) == VOL_STATE_ATTACHED) &&
1308 (vp->header == NULL)) {
1312 if (VIsExclusiveState(V_attachState(vp))) {
1317 DeleteVolumeFromVByPList_r(vp);
1318 VShutdownVolume_r(vp);
1328 * shutdown a specific volume
1330 /* caller MUST NOT hold a heavyweight ref on vp */
1332 VShutdownVolume_r(Volume * vp)
1336 VCreateReservation_r(vp);
1338 if (LogLevel >= 5) {
1339 Log("VShutdownVolume_r: vid=%u, device=%d, state=%hu\n",
1340 vp->hashid, vp->partition->device, V_attachState(vp));
1343 /* wait for other blocking ops to finish */
1344 VWaitExclusiveState_r(vp);
1346 assert(VIsValidState(V_attachState(vp)));
1348 switch(V_attachState(vp)) {
1349 case VOL_STATE_SALVAGING:
1350 /* make sure salvager knows we don't want
1351 * the volume back */
1352 VCancelSalvage_r(vp, SALVSYNC_SHUTDOWN);
1353 case VOL_STATE_PREATTACHED:
1354 case VOL_STATE_ERROR:
1355 VChangeState_r(vp, VOL_STATE_UNATTACHED);
1356 case VOL_STATE_UNATTACHED:
1358 case VOL_STATE_GOING_OFFLINE:
1359 case VOL_STATE_SHUTTING_DOWN:
1360 case VOL_STATE_ATTACHED:
1364 Log("VShutdown: Attempting to take volume %u offline.\n",
1367 /* take the volume offline (drops reference count) */
1368 VOffline_r(vp, "File server was shut down");
1373 VCancelReservation_r(vp);
1377 #endif /* AFS_DEMAND_ATTACH_FS */
1380 /***************************************************/
1381 /* Header I/O routines */
1382 /***************************************************/
1384 /* open a descriptor for the inode (h),
1385 * read in an on-disk structure into buffer (to) of size (size),
1386 * verify versionstamp in structure has magic (magic) and
1387 * optionally verify version (version) if (version) is nonzero
1390 ReadHeader(Error * ec, IHandle_t * h, char *to, int size, bit32 magic,
1393 struct versionStamp *vsn;
1408 if (FDH_SEEK(fdP, 0, SEEK_SET) < 0) {
1410 FDH_REALLYCLOSE(fdP);
1413 vsn = (struct versionStamp *)to;
1414 if (FDH_READ(fdP, to, size) != size || vsn->magic != magic) {
1416 FDH_REALLYCLOSE(fdP);
1421 /* Check is conditional, in case caller wants to inspect version himself */
1422 if (version && vsn->version != version) {
1428 WriteVolumeHeader_r(Error * ec, Volume * vp)
1430 IHandle_t *h = V_diskDataHandle(vp);
1440 if (FDH_SEEK(fdP, 0, SEEK_SET) < 0) {
1442 FDH_REALLYCLOSE(fdP);
1445 if (FDH_WRITE(fdP, (char *)&V_disk(vp), sizeof(V_disk(vp)))
1446 != sizeof(V_disk(vp))) {
1448 FDH_REALLYCLOSE(fdP);
1454 /* VolumeHeaderToDisk
1455 * Allows for storing 64 bit inode numbers in on-disk volume header
1458 /* convert in-memory representation of a volume header to the
1459 * on-disk representation of a volume header */
1461 VolumeHeaderToDisk(VolumeDiskHeader_t * dh, VolumeHeader_t * h)
1464 memset((char *)dh, 0, sizeof(VolumeDiskHeader_t));
1465 dh->stamp = h->stamp;
1467 dh->parent = h->parent;
1469 #ifdef AFS_64BIT_IOPS_ENV
1470 dh->volumeInfo_lo = (afs_int32) h->volumeInfo & 0xffffffff;
1471 dh->volumeInfo_hi = (afs_int32) (h->volumeInfo >> 32) & 0xffffffff;
1472 dh->smallVnodeIndex_lo = (afs_int32) h->smallVnodeIndex & 0xffffffff;
1473 dh->smallVnodeIndex_hi =
1474 (afs_int32) (h->smallVnodeIndex >> 32) & 0xffffffff;
1475 dh->largeVnodeIndex_lo = (afs_int32) h->largeVnodeIndex & 0xffffffff;
1476 dh->largeVnodeIndex_hi =
1477 (afs_int32) (h->largeVnodeIndex >> 32) & 0xffffffff;
1478 dh->linkTable_lo = (afs_int32) h->linkTable & 0xffffffff;
1479 dh->linkTable_hi = (afs_int32) (h->linkTable >> 32) & 0xffffffff;
1481 dh->volumeInfo_lo = h->volumeInfo;
1482 dh->smallVnodeIndex_lo = h->smallVnodeIndex;
1483 dh->largeVnodeIndex_lo = h->largeVnodeIndex;
1484 dh->linkTable_lo = h->linkTable;
1488 /* DiskToVolumeHeader
1489 * Converts an on-disk representation of a volume header to
1490 * the in-memory representation of a volume header.
1492 * Makes the assumption that AFS has *always*
1493 * zero'd the volume header file so that high parts of inode
1494 * numbers are 0 in older (SGI EFS) volume header files.
1497 DiskToVolumeHeader(VolumeHeader_t * h, VolumeDiskHeader_t * dh)
1499 memset((char *)h, 0, sizeof(VolumeHeader_t));
1500 h->stamp = dh->stamp;
1502 h->parent = dh->parent;
1504 #ifdef AFS_64BIT_IOPS_ENV
1506 (Inode) dh->volumeInfo_lo | ((Inode) dh->volumeInfo_hi << 32);
1508 h->smallVnodeIndex =
1509 (Inode) dh->smallVnodeIndex_lo | ((Inode) dh->
1510 smallVnodeIndex_hi << 32);
1512 h->largeVnodeIndex =
1513 (Inode) dh->largeVnodeIndex_lo | ((Inode) dh->
1514 largeVnodeIndex_hi << 32);
1516 (Inode) dh->linkTable_lo | ((Inode) dh->linkTable_hi << 32);
1518 h->volumeInfo = dh->volumeInfo_lo;
1519 h->smallVnodeIndex = dh->smallVnodeIndex_lo;
1520 h->largeVnodeIndex = dh->largeVnodeIndex_lo;
1521 h->linkTable = dh->linkTable_lo;
1526 /***************************************************/
1527 /* Volume Attachment routines */
1528 /***************************************************/
1530 #ifdef AFS_DEMAND_ATTACH_FS
1532 * pre-attach a volume given its path.
1534 * @param[out] ec outbound error code
1535 * @param[in] partition partition path string
1536 * @param[in] name volume id string
1538 * @return volume object pointer
1540 * @note A pre-attached volume will only have its partition
1541 * and hashid fields initialized. At first call to
1542 * VGetVolume, the volume will be fully attached.
1546 VPreAttachVolumeByName(Error * ec, char *partition, char *name)
1550 vp = VPreAttachVolumeByName_r(ec, partition, name);
1556 * pre-attach a volume given its path.
1558 * @param[out] ec outbound error code
1559 * @param[in] partition path to vice partition
1560 * @param[in] name volume id string
1562 * @return volume object pointer
1564 * @pre VOL_LOCK held
1566 * @internal volume package internal use only.
1569 VPreAttachVolumeByName_r(Error * ec, char *partition, char *name)
1571 return VPreAttachVolumeById_r(ec,
1573 VolumeNumber(name));
1577 * pre-attach a volume given its path and numeric volume id.
1579 * @param[out] ec error code return
1580 * @param[in] partition path to vice partition
1581 * @param[in] volumeId numeric volume id
1583 * @return volume object pointer
1585 * @pre VOL_LOCK held
1587 * @internal volume package internal use only.
1590 VPreAttachVolumeById_r(Error * ec,
1595 struct DiskPartition64 *partp;
1599 assert(programType == fileServer);
1601 if (!(partp = VGetPartition_r(partition, 0))) {
1603 Log("VPreAttachVolumeById_r: Error getting partition (%s)\n", partition);
1607 vp = VLookupVolume_r(ec, volumeId, NULL);
1612 return VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
1616 * preattach a volume.
1618 * @param[out] ec outbound error code
1619 * @param[in] partp pointer to partition object
1620 * @param[in] vp pointer to volume object
1621 * @param[in] vid volume id
1623 * @return volume object pointer
1625 * @pre VOL_LOCK is held.
1627 * @warning Returned volume object pointer does not have to
1628 * equal the pointer passed in as argument vp. There
1629 * are potential race conditions which can result in
1630 * the pointers having different values. It is up to
1631 * the caller to make sure that references are handled
1632 * properly in this case.
1634 * @note If there is already a volume object registered with
1635 * the same volume id, its pointer MUST be passed as
1636 * argument vp. Failure to do so will result in a silent
1637 * failure to preattach.
1639 * @internal volume package internal use only.
1642 VPreAttachVolumeByVp_r(Error * ec,
1643 struct DiskPartition64 * partp,
1651 /* check to see if pre-attach already happened */
1653 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1654 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
1655 !VIsErrorState(V_attachState(vp))) {
1657 * pre-attach is a no-op in all but the following cases:
1659 * - volume is unattached
1660 * - volume is in an error state
1661 * - volume is pre-attached
1663 Log("VPreattachVolumeByVp_r: volume %u not in quiescent state\n", vid);
1666 /* we're re-attaching a volume; clear out some old state */
1667 memset(&vp->salvage, 0, sizeof(struct VolumeOnlineSalvage));
1669 if (V_partition(vp) != partp) {
1670 /* XXX potential race */
1671 DeleteVolumeFromVByPList_r(vp);
1674 /* if we need to allocate a new Volume struct,
1675 * go ahead and drop the vol glock, otherwise
1676 * do the basic setup synchronised, as it's
1677 * probably not worth dropping the lock */
1680 /* allocate the volume structure */
1681 vp = nvp = (Volume *) malloc(sizeof(Volume));
1683 memset(vp, 0, sizeof(Volume));
1684 queue_Init(&vp->vnode_list);
1685 assert(pthread_cond_init(&V_attachCV(vp), NULL) == 0);
1688 /* link the volume with its associated vice partition */
1689 vp->device = partp->device;
1690 vp->partition = partp;
1693 vp->specialStatus = 0;
1695 /* if we dropped the lock, reacquire the lock,
1696 * check for pre-attach races, and then add
1697 * the volume to the hash table */
1700 nvp = VLookupVolume_r(ec, vid, NULL);
1705 } else if (nvp) { /* race detected */
1710 /* hack to make up for VChangeState_r() decrementing
1711 * the old state counter */
1712 VStats.state_levels[0]++;
1716 /* put pre-attached volume onto the hash table
1717 * and bring it up to the pre-attached state */
1718 AddVolumeToHashTable(vp, vp->hashid);
1719 AddVolumeToVByPList_r(vp);
1720 VLRU_Init_Node_r(vp);
1721 VChangeState_r(vp, VOL_STATE_PREATTACHED);
1724 Log("VPreAttachVolumeByVp_r: volume %u pre-attached\n", vp->hashid);
1732 #endif /* AFS_DEMAND_ATTACH_FS */
1734 /* Attach an existing volume, given its pathname, and return a
1735 pointer to the volume header information. The volume also
1736 normally goes online at this time. An offline volume
1737 must be reattached to make it go online */
1739 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
1743 retVal = VAttachVolumeByName_r(ec, partition, name, mode);
1749 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
1751 register Volume *vp = NULL, *svp = NULL;
1753 struct afs_stat status;
1754 struct VolumeDiskHeader diskHeader;
1755 struct VolumeHeader iheader;
1756 struct DiskPartition64 *partp;
1760 #ifdef AFS_DEMAND_ATTACH_FS
1761 VolumeStats stats_save;
1762 #endif /* AFS_DEMAND_ATTACH_FS */
1766 volumeId = VolumeNumber(name);
1768 if (!(partp = VGetPartition_r(partition, 0))) {
1770 Log("VAttachVolume: Error getting partition (%s)\n", partition);
1774 if (programType == volumeUtility) {
1776 VLockPartition_r(partition);
1777 } else if (programType == fileServer) {
1778 #ifdef AFS_DEMAND_ATTACH_FS
1779 /* lookup the volume in the hash table */
1780 vp = VLookupVolume_r(ec, volumeId, NULL);
1786 /* save any counters that are supposed to
1787 * be monotonically increasing over the
1788 * lifetime of the fileserver */
1789 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
1791 memset(&stats_save, 0, sizeof(VolumeStats));
1794 /* if there's something in the hash table, and it's not
1795 * in the pre-attach state, then we may need to detach
1796 * it before proceeding */
1797 if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1798 VCreateReservation_r(vp);
1799 VWaitExclusiveState_r(vp);
1801 /* at this point state must be one of:
1810 if (vp->specialStatus == VBUSY)
1813 /* if it's already attached, see if we can return it */
1814 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
1815 VGetVolumeByVp_r(ec, vp);
1816 if (V_inUse(vp) == fileServer) {
1817 VCancelReservation_r(vp);
1821 /* otherwise, we need to detach, and attempt to re-attach */
1822 VDetachVolume_r(ec, vp);
1824 Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
1827 /* if it isn't fully attached, delete from the hash tables,
1828 and let the refcounter handle the rest */
1829 DeleteVolumeFromHashTable(vp);
1830 DeleteVolumeFromVByPList_r(vp);
1833 VCancelReservation_r(vp);
1837 /* pre-attach volume if it hasn't been done yet */
1839 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
1840 (V_attachState(vp) == VOL_STATE_ERROR)) {
1842 vp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
1850 /* handle pre-attach races
1852 * multiple threads can race to pre-attach a volume,
1853 * but we can't let them race beyond that
1855 * our solution is to let the first thread to bring
1856 * the volume into an exclusive state win; the other
1857 * threads just wait until it finishes bringing the
1858 * volume online, and then they do a vgetvolumebyvp
1860 if (svp && (svp != vp)) {
1861 /* wait for other exclusive ops to finish */
1862 VCreateReservation_r(vp);
1863 VWaitExclusiveState_r(vp);
1865 /* get a heavyweight ref, kill the lightweight ref, and return */
1866 VGetVolumeByVp_r(ec, vp);
1867 VCancelReservation_r(vp);
1871 /* at this point, we are chosen as the thread to do
1872 * demand attachment for this volume. all other threads
1873 * doing a getvolume on vp->hashid will block until we finish */
1875 /* make sure any old header cache entries are invalidated
1876 * before proceeding */
1877 FreeVolumeHeader(vp);
1879 VChangeState_r(vp, VOL_STATE_ATTACHING);
1881 /* restore any saved counters */
1882 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
1883 #else /* AFS_DEMAND_ATTACH_FS */
1884 vp = VGetVolume_r(ec, volumeId);
1886 if (V_inUse(vp) == fileServer)
1888 if (vp->specialStatus == VBUSY)
1890 VDetachVolume_r(ec, vp);
1892 Log("VAttachVolume: Error detaching volume (%s)\n", name);
1896 #endif /* AFS_DEMAND_ATTACH_FS */
1900 strcpy(path, VPartitionPath(partp));
1906 if ((fd = afs_open(path, O_RDONLY)) == -1 || afs_fstat(fd, &status) == -1) {
1907 Log("VAttachVolume: Failed to open %s (errno %d)\n", path, errno);
1914 n = read(fd, &diskHeader, sizeof(diskHeader));
1916 if (n != sizeof(diskHeader)
1917 || diskHeader.stamp.magic != VOLUMEHEADERMAGIC) {
1918 Log("VAttachVolume: Error reading volume header %s\n", path);
1923 if (diskHeader.stamp.version != VOLUMEHEADERVERSION) {
1924 Log("VAttachVolume: Volume %s, version number is incorrect; volume needs salvaged\n", path);
1930 DiskToVolumeHeader(&iheader, &diskHeader);
1931 #ifdef FSSYNC_BUILD_CLIENT
1932 if (programType == volumeUtility && mode != V_SECRETLY && mode != V_PEEK) {
1934 if (FSYNC_VolOp(iheader.id, partition, FSYNC_VOL_NEEDVOLUME, mode, NULL)
1936 Log("VAttachVolume: attach of volume %u apparently denied by file server\n", iheader.id);
1937 *ec = VNOVOL; /* XXXX */
1945 vp = (Volume *) calloc(1, sizeof(Volume));
1947 vp->device = partp->device;
1948 vp->partition = partp;
1949 queue_Init(&vp->vnode_list);
1950 #ifdef AFS_DEMAND_ATTACH_FS
1951 assert(pthread_cond_init(&V_attachCV(vp), NULL) == 0);
1952 #endif /* AFS_DEMAND_ATTACH_FS */
1955 /* attach2 is entered without any locks, and returns
1956 * with vol_glock_mutex held */
1957 vp = attach2(ec, volumeId, path, &iheader, partp, vp, isbusy, mode);
1959 if (programType == volumeUtility && vp) {
1960 if ((mode == V_VOLUPD) || (VolumeWriteable(vp) && (mode == V_CLONE))) {
1961 /* mark volume header as in use so that volser crashes lead to a
1962 * salvage attempt */
1963 VUpdateVolume_r(ec, vp, 0);
1965 #ifdef AFS_DEMAND_ATTACH_FS
1966 /* for dafs, we should tell the fileserver, except for V_PEEK
1967 * where we know it is not necessary */
1968 if (mode == V_PEEK) {
1969 vp->needsPutBack = 0;
1971 vp->needsPutBack = 1;
1973 #else /* !AFS_DEMAND_ATTACH_FS */
1974 /* duplicate computation in fssync.c about whether the server
1975 * takes the volume offline or not. If the volume isn't
1976 * offline, we must not return it when we detach the volume,
1977 * or the server will abort */
1978 if (mode == V_READONLY || mode == V_PEEK
1979 || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
1980 vp->needsPutBack = 0;
1982 vp->needsPutBack = 1;
1983 #endif /* !AFS_DEMAND_ATTACH_FS */
1985 /* OK, there's a problem here, but one that I don't know how to
1986 * fix right now, and that I don't think should arise often.
1987 * Basically, we should only put back this volume to the server if
1988 * it was given to us by the server, but since we don't have a vp,
1989 * we can't run the VolumeWriteable function to find out as we do
1990 * above when computing vp->needsPutBack. So we send it back, but
1991 * there's a path in VAttachVolume on the server which may abort
1992 * if this volume doesn't have a header. Should be pretty rare
1993 * for all of that to happen, but if it does, probably the right
1994 * fix is for the server to allow the return of readonly volumes
1995 * that it doesn't think are really checked out. */
1996 #ifdef FSSYNC_BUILD_CLIENT
1997 if (programType == volumeUtility && vp == NULL &&
1998 mode != V_SECRETLY && mode != V_PEEK) {
1999 FSYNC_VolOp(iheader.id, partition, FSYNC_VOL_ON, 0, NULL);
2002 if (programType == fileServer && vp) {
2003 #ifdef AFS_DEMAND_ATTACH_FS
2005 * we can get here in cases where we don't "own"
2006 * the volume (e.g. volume owned by a utility).
2007 * short circuit around potential disk header races.
2009 if (V_attachState(vp) != VOL_STATE_ATTACHED) {
2013 V_needsCallback(vp) = 0;
2015 if (VInit >= 2 && V_BreakVolumeCallbacks) {
2016 Log("VAttachVolume: Volume %u was changed externally; breaking callbacks\n", V_id(vp));
2017 (*V_BreakVolumeCallbacks) (V_id(vp));
2020 VUpdateVolume_r(ec, vp, 0);
2022 Log("VAttachVolume: Error updating volume\n");
2027 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2028 #ifndef AFS_DEMAND_ATTACH_FS
2029 /* This is a hack: by temporarily setting the incore
2030 * dontSalvage flag ON, the volume will be put back on the
2031 * Update list (with dontSalvage OFF again). It will then
2032 * come back in N minutes with DONT_SALVAGE eventually
2033 * set. This is the way that volumes that have never had
2034 * it set get it set; or that volumes that have been
2035 * offline without DONT SALVAGE having been set also
2036 * eventually get it set */
2037 V_dontSalvage(vp) = DONT_SALVAGE;
2038 #endif /* !AFS_DEMAND_ATTACH_FS */
2039 VAddToVolumeUpdateList_r(ec, vp);
2041 Log("VAttachVolume: Error adding volume to update list\n");
2048 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2053 if (programType == volumeUtility) {
2054 VUnlockPartition_r(partition);
2057 #ifdef AFS_DEMAND_ATTACH_FS
2058 /* attach failed; make sure we're in error state */
2059 if (vp && !VIsErrorState(V_attachState(vp))) {
2060 VChangeState_r(vp, VOL_STATE_ERROR);
2062 #endif /* AFS_DEMAND_ATTACH_FS */
2069 #ifdef AFS_DEMAND_ATTACH_FS
2070 /* VAttachVolumeByVp_r
2072 * finish attaching a volume that is
2073 * in a less than fully attached state
2075 /* caller MUST hold a ref count on vp */
2077 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
2079 char name[VMAXPATHLEN];
2080 int fd, n, reserve = 0;
2081 struct afs_stat status;
2082 struct VolumeDiskHeader diskHeader;
2083 struct VolumeHeader iheader;
2084 struct DiskPartition64 *partp;
2089 VolumeStats stats_save;
2092 /* volume utility should never call AttachByVp */
2093 assert(programType == fileServer);
2095 volumeId = vp->hashid;
2096 partp = vp->partition;
2097 VolumeExternalName_r(volumeId, name, sizeof(name));
2100 /* if another thread is performing a blocking op, wait */
2101 VWaitExclusiveState_r(vp);
2103 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2105 /* if it's already attached, see if we can return it */
2106 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2107 VGetVolumeByVp_r(ec, vp);
2108 if (V_inUse(vp) == fileServer) {
2111 if (vp->specialStatus == VBUSY)
2113 VDetachVolume_r(ec, vp);
2115 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2121 /* pre-attach volume if it hasn't been done yet */
2123 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2124 (V_attachState(vp) == VOL_STATE_ERROR)) {
2125 nvp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2131 VCreateReservation_r(nvp);
2137 VChangeState_r(vp, VOL_STATE_ATTACHING);
2139 /* restore monotonically increasing stats */
2140 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2145 /* compute path to disk header,
2147 * and verify magic and version stamps */
2148 strcpy(path, VPartitionPath(partp));
2154 if ((fd = afs_open(path, O_RDONLY)) == -1 || afs_fstat(fd, &status) == -1) {
2155 Log("VAttachVolume: Failed to open %s (errno %d)\n", path, errno);
2162 n = read(fd, &diskHeader, sizeof(diskHeader));
2164 if (n != sizeof(diskHeader)
2165 || diskHeader.stamp.magic != VOLUMEHEADERMAGIC) {
2166 Log("VAttachVolume: Error reading volume header %s\n", path);
2171 if (diskHeader.stamp.version != VOLUMEHEADERVERSION) {
2172 Log("VAttachVolume: Volume %s, version number is incorrect; volume needs salvaged\n", path);
2178 /* convert on-disk header format to in-memory header format */
2179 DiskToVolumeHeader(&iheader, &diskHeader);
2183 * NOTE: attach2 is entered without any locks, and returns
2184 * with vol_glock_mutex held */
2185 vp = attach2(ec, volumeId, path, &iheader, partp, vp, isbusy, mode);
2188 * the event that an error was encountered, or
2189 * the volume was not brought to an attached state
2190 * for any reason, skip to the end. We cannot
2191 * safely call VUpdateVolume unless we "own" it.
2195 (V_attachState(vp) != VOL_STATE_ATTACHED)) {
2199 V_needsCallback(vp) = 0;
2200 VUpdateVolume_r(ec, vp, 0);
2202 Log("VAttachVolume: Error updating volume %u\n", vp->hashid);
2206 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2207 #ifndef AFS_DEMAND_ATTACH_FS
2208 /* This is a hack: by temporarily setting the incore
2209 * dontSalvage flag ON, the volume will be put back on the
2210 * Update list (with dontSalvage OFF again). It will then
2211 * come back in N minutes with DONT_SALVAGE eventually
2212 * set. This is the way that volumes that have never had
2213 * it set get it set; or that volumes that have been
2214 * offline without DONT SALVAGE having been set also
2215 * eventually get it set */
2216 V_dontSalvage(vp) = DONT_SALVAGE;
2217 #endif /* !AFS_DEMAND_ATTACH_FS */
2218 VAddToVolumeUpdateList_r(ec, vp);
2220 Log("VAttachVolume: Error adding volume %u to update list\n", vp->hashid);
2227 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2231 VCancelReservation_r(nvp);
2234 if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2235 if (vp && !VIsErrorState(V_attachState(vp))) {
2236 VChangeState_r(vp, VOL_STATE_ERROR);
2243 #endif /* AFS_DEMAND_ATTACH_FS */
2246 * called without any locks held
2247 * returns with vol_glock_mutex held
2250 attach2(Error * ec, VolId volumeId, char *path, register struct VolumeHeader * header,
2251 struct DiskPartition64 * partp, register Volume * vp, int isbusy, int mode)
2253 vp->specialStatus = (byte) (isbusy ? VBUSY : 0);
2254 IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header->parent,
2255 header->largeVnodeIndex);
2256 IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header->parent,
2257 header->smallVnodeIndex);
2258 IH_INIT(vp->diskDataHandle, partp->device, header->parent,
2259 header->volumeInfo);
2260 IH_INIT(vp->linkHandle, partp->device, header->parent, header->linkTable);
2261 vp->shuttingDown = 0;
2262 vp->goingOffline = 0;
2264 #ifdef AFS_DEMAND_ATTACH_FS
2265 vp->stats.last_attach = FT_ApproxTime();
2266 vp->stats.attaches++;
2270 IncUInt64(&VStats.attaches);
2271 vp->cacheCheck = ++VolumeCacheCheck;
2272 /* just in case this ever rolls over */
2273 if (!vp->cacheCheck)
2274 vp->cacheCheck = ++VolumeCacheCheck;
2275 GetVolumeHeader(vp);
2278 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2279 /* demand attach changes the V_PEEK mechanism
2281 * we can now suck the current disk data structure over
2282 * the fssync interface without going to disk
2284 * (technically, we don't need to restrict this feature
2285 * to demand attach fileservers. However, I'm trying
2286 * to limit the number of common code changes)
2288 if (programType != fileServer && mode == V_PEEK) {
2290 res.payload.len = sizeof(VolumeDiskData);
2291 res.payload.buf = &vp->header->diskstuff;
2293 if (FSYNC_VolOp(volumeId,
2295 FSYNC_VOL_QUERY_HDR,
2298 goto disk_header_loaded;
2301 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2302 (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2303 sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2305 #ifdef AFS_DEMAND_ATTACH_FS
2308 IncUInt64(&VStats.hdr_loads);
2309 IncUInt64(&vp->stats.hdr_loads);
2311 #endif /* AFS_DEMAND_ATTACH_FS */
2314 Log("VAttachVolume: Error reading diskDataHandle vol header %s; error=%u\n", path, *ec);
2319 #ifdef AFS_DEMAND_ATTACH_FS
2322 /* check for pending volume operations */
2323 if (vp->pending_vol_op) {
2324 /* see if the pending volume op requires exclusive access */
2325 if (!VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
2326 /* mark the volume down */
2328 VChangeState_r(vp, VOL_STATE_UNATTACHED);
2329 if (V_offlineMessage(vp)[0] == '\0')
2330 strlcpy(V_offlineMessage(vp),
2331 "A volume utility is running.",
2332 sizeof(V_offlineMessage(vp)));
2333 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
2335 /* check to see if we should set the specialStatus flag */
2336 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
2337 vp->specialStatus = VBUSY;
2342 V_attachFlags(vp) |= VOL_HDR_LOADED;
2343 vp->stats.last_hdr_load = vp->stats.last_attach;
2345 #endif /* AFS_DEMAND_ATTACH_FS */
2348 struct IndexFileHeader iHead;
2350 #if OPENAFS_VOL_STATS
2352 * We just read in the diskstuff part of the header. If the detailed
2353 * volume stats area has not yet been initialized, we should bzero the
2354 * area and mark it as initialized.
2356 if (!(V_stat_initialized(vp))) {
2357 memset((char *)(V_stat_area(vp)), 0, VOL_STATS_BYTES);
2358 V_stat_initialized(vp) = 1;
2360 #endif /* OPENAFS_VOL_STATS */
2362 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
2363 (char *)&iHead, sizeof(iHead),
2364 SMALLINDEXMAGIC, SMALLINDEXVERSION);
2367 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
2372 struct IndexFileHeader iHead;
2374 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
2375 (char *)&iHead, sizeof(iHead),
2376 LARGEINDEXMAGIC, LARGEINDEXVERSION);
2379 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
2383 #ifdef AFS_NAMEI_ENV
2385 struct versionStamp stamp;
2387 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
2388 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
2391 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
2394 #endif /* AFS_NAMEI_ENV */
2396 #if defined(AFS_DEMAND_ATTACH_FS)
2397 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
2399 if (programType == fileServer) {
2400 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2403 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
2409 /* volume operation in progress */
2413 #else /* AFS_DEMAND_ATTACH_FS */
2415 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
2420 #endif /* AFS_DEMAND_ATTACH_FS */
2422 if (V_needsSalvaged(vp)) {
2423 if (vp->specialStatus)
2424 vp->specialStatus = 0;
2426 #if defined(AFS_DEMAND_ATTACH_FS)
2427 if (programType == fileServer) {
2428 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
2431 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
2435 #else /* AFS_DEMAND_ATTACH_FS */
2438 #endif /* AFS_DEMAND_ATTACH_FS */
2443 if (programType == fileServer) {
2444 #ifndef FAST_RESTART
2445 if (V_inUse(vp) && VolumeWriteable(vp)) {
2446 if (!V_needsSalvaged(vp)) {
2447 V_needsSalvaged(vp) = 1;
2448 VUpdateVolume_r(ec, vp, 0);
2450 #if defined(AFS_DEMAND_ATTACH_FS)
2451 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
2453 #else /* AFS_DEMAND_ATTACH_FS */
2454 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
2457 #endif /* AFS_DEMAND_ATTACH_FS */
2460 #endif /* FAST_RESTART */
2462 if (V_destroyMe(vp) == DESTROY_ME) {
2463 #if defined(AFS_DEMAND_ATTACH_FS)
2464 /* schedule a salvage so the volume goes away on disk */
2465 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2466 VChangeState_r(vp, VOL_STATE_ERROR);
2468 #endif /* AFS_DEMAND_ATTACH_FS */
2470 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
2476 vp->nextVnodeUnique = V_uniquifier(vp);
2477 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
2478 #ifndef BITMAP_LATER
2479 if (programType == fileServer && VolumeWriteable(vp)) {
2481 for (i = 0; i < nVNODECLASSES; i++) {
2482 VGetBitmap_r(ec, vp, i);
2484 #ifdef AFS_DEMAND_ATTACH_FS
2485 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2487 #else /* AFS_DEMAND_ATTACH_FS */
2489 #endif /* AFS_DEMAND_ATTACH_FS */
2490 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
2496 #endif /* BITMAP_LATER */
2498 if (programType == fileServer) {
2499 if (vp->specialStatus)
2500 vp->specialStatus = 0;
2501 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
2502 V_inUse(vp) = fileServer;
2503 V_offlineMessage(vp)[0] = '\0';
2506 V_inUse(vp) = programType;
2507 V_checkoutMode(vp) = mode;
2510 AddVolumeToHashTable(vp, V_id(vp));
2511 #ifdef AFS_DEMAND_ATTACH_FS
2512 if ((programType != fileServer) ||
2513 (V_inUse(vp) == fileServer)) {
2514 AddVolumeToVByPList_r(vp);
2516 VChangeState_r(vp, VOL_STATE_ATTACHED);
2518 VChangeState_r(vp, VOL_STATE_UNATTACHED);
2524 /* Attach an existing volume.
2525 The volume also normally goes online at this time.
2526 An offline volume must be reattached to make it go online.
2530 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
2534 retVal = VAttachVolume_r(ec, volumeId, mode);
2540 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
2543 VGetVolumePath(ec, volumeId, &part, &name);
2545 register Volume *vp;
2547 vp = VGetVolume_r(&error, volumeId);
2549 assert(V_inUse(vp) == 0);
2550 VDetachVolume_r(ec, vp);
2554 return VAttachVolumeByName_r(ec, part, name, mode);
2557 /* Increment a reference count to a volume, sans context swaps. Requires
2558 * possibly reading the volume header in from the disk, since there's
2559 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
2561 * N.B. This call can fail if we can't read in the header!! In this case
2562 * we still guarantee we won't context swap, but the ref count won't be
2563 * incremented (otherwise we'd violate the invariant).
2565 /* NOTE: with the demand attach fileserver extensions, the global lock
2566 * is dropped within VHold */
2567 #ifdef AFS_DEMAND_ATTACH_FS
2569 VHold_r(register Volume * vp)
2573 VCreateReservation_r(vp);
2574 VWaitExclusiveState_r(vp);
2576 LoadVolumeHeader(&error, vp);
2578 VCancelReservation_r(vp);
2582 VCancelReservation_r(vp);
2585 #else /* AFS_DEMAND_ATTACH_FS */
2587 VHold_r(register Volume * vp)
2591 LoadVolumeHeader(&error, vp);
2597 #endif /* AFS_DEMAND_ATTACH_FS */
2600 VHold(register Volume * vp)
2604 retVal = VHold_r(vp);
2610 /***************************************************/
2611 /* get and put volume routines */
2612 /***************************************************/
2615 * put back a heavyweight reference to a volume object.
2617 * @param[in] vp volume object pointer
2619 * @pre VOL_LOCK held
2621 * @post heavyweight volume reference put back.
2622 * depending on state, volume may have been taken offline,
2623 * detached, salvaged, freed, etc.
2625 * @internal volume package internal use only
2628 VPutVolume_r(register Volume * vp)
2630 assert(--vp->nUsers >= 0);
2631 if (vp->nUsers == 0) {
2633 ReleaseVolumeHeader(vp->header);
2634 #ifdef AFS_DEMAND_ATTACH_FS
2635 if (!VCheckDetach(vp)) {
2639 #else /* AFS_DEMAND_ATTACH_FS */
2641 #endif /* AFS_DEMAND_ATTACH_FS */
2646 VPutVolume(register Volume * vp)
2654 /* Get a pointer to an attached volume. The pointer is returned regardless
2655 of whether or not the volume is in service or on/off line. An error
2656 code, however, is returned with an indication of the volume's status */
2658 VGetVolume(Error * ec, Error * client_ec, VolId volumeId)
2662 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
2668 VGetVolume_r(Error * ec, VolId volumeId)
2670 return GetVolume(ec, NULL, volumeId, NULL, 0);
2673 /* try to get a volume we've previously looked up */
2674 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
2676 VGetVolumeByVp_r(Error * ec, Volume * vp)
2678 return GetVolume(ec, NULL, vp->hashid, vp, 0);
2681 /* private interface for getting a volume handle
2682 * volumeId must be provided.
2683 * hint is an optional parameter to speed up hash lookups
2684 * flags is not used at this time
2686 /* for demand attach fs, caller MUST NOT hold a ref count on hint */
2688 GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint, int flags)
2691 /* pull this profiling/debugging code out of regular builds */
2693 #define VGET_CTR_INC(x) x++
2694 unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
2695 0, V7 = 0, V8 = 0, V9 = 0;
2696 unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
2698 #define VGET_CTR_INC(x)
2700 #ifdef AFS_DEMAND_ATTACH_FS
2701 Volume *avp, * rvp = hint;
2705 * if VInit is zero, the volume package dynamic
2706 * data structures have not been initialized yet,
2707 * and we must immediately return an error
2713 *client_ec = VOFFLINE;
2718 #ifdef AFS_DEMAND_ATTACH_FS
2720 VCreateReservation_r(rvp);
2722 #endif /* AFS_DEMAND_ATTACH_FS */
2730 vp = VLookupVolume_r(ec, volumeId, vp);
2736 #ifdef AFS_DEMAND_ATTACH_FS
2737 if (rvp && (rvp != vp)) {
2738 /* break reservation on old vp */
2739 VCancelReservation_r(rvp);
2742 #endif /* AFS_DEMAND_ATTACH_FS */
2748 /* Until we have reached an initialization level of 2
2749 * we don't know whether this volume exists or not.
2750 * We can't sleep and retry later because before a volume
2751 * is attached, the caller tries to get it first. Just
2752 * return VOFFLINE and the caller can choose whether to
2753 * retry the command or not. */
2763 IncUInt64(&VStats.hdr_gets);
2765 #ifdef AFS_DEMAND_ATTACH_FS
2766 /* block if someone else is performing an exclusive op on this volume */
2769 VCreateReservation_r(rvp);
2771 VWaitExclusiveState_r(vp);
2773 /* short circuit with VNOVOL in the following circumstances:
2776 * - VOL_STATE_SHUTTING_DOWN
2778 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
2779 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN)) {
2786 * short circuit with VOFFLINE in the following circumstances:
2788 * - VOL_STATE_UNATTACHED
2790 if (V_attachState(vp) == VOL_STATE_UNATTACHED) {
2791 if (vp->specialStatus) {
2792 *ec = vp->specialStatus;
2800 /* allowable states:
2807 if (vp->salvage.requested) {
2808 VUpdateSalvagePriority_r(vp);
2811 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
2812 avp = VAttachVolumeByVp_r(ec, vp, 0);
2815 /* VAttachVolumeByVp_r can return a pointer
2816 * != the vp passed to it under certain
2817 * conditions; make sure we don't leak
2818 * reservations if that happens */
2820 VCancelReservation_r(rvp);
2822 VCreateReservation_r(rvp);
2832 if (!vp->pending_vol_op) {
2847 if ((V_attachState(vp) == VOL_STATE_SALVAGING) ||
2848 (*ec == VSALVAGING)) {
2850 /* see CheckVnode() in afsfileprocs.c for an explanation
2851 * of this error code logic */
2852 afs_uint32 now = FT_ApproxTime();
2853 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
2856 *client_ec = VRESTARTING;
2865 LoadVolumeHeader(ec, vp);
2868 /* Only log the error if it was a totally unexpected error. Simply
2869 * a missing inode is likely to be caused by the volume being deleted */
2870 if (errno != ENXIO || LogLevel)
2871 Log("Volume %u: couldn't reread volume header\n",
2873 #ifdef AFS_DEMAND_ATTACH_FS
2874 if (programType == fileServer) {
2875 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2880 #else /* AFS_DEMAND_ATTACH_FS */
2883 #endif /* AFS_DEMAND_ATTACH_FS */
2887 #ifdef AFS_DEMAND_ATTACH_FS
2889 * this test MUST happen after the volume header is loaded
2891 if (vp->pending_vol_op && !VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
2893 * volume cannot remain online during this volume operation.
2896 if (vp->specialStatus) {
2898 * special status codes outrank normal VOFFLINE code
2900 *ec = vp->specialStatus;
2902 *client_ec = vp->specialStatus;
2906 /* see CheckVnode() in afsfileprocs.c for an explanation
2907 * of this error code logic */
2908 afs_uint32 now = FT_ApproxTime();
2909 if ((vp->stats.last_vol_op + (10 * 60)) >= now) {
2912 *client_ec = VRESTARTING;
2917 VChangeState_r(vp, VOL_STATE_UNATTACHED);
2918 FreeVolumeHeader(vp);
2922 #endif /* AFS_DEMAND_ATTACH_FS */
2925 if (vp->shuttingDown) {
2932 if (programType == fileServer) {
2934 if (vp->goingOffline) {
2936 #ifdef AFS_DEMAND_ATTACH_FS
2937 /* wait for the volume to go offline */
2938 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
2939 VWaitStateChange_r(vp);
2941 #elif defined(AFS_PTHREAD_ENV)
2942 VOL_CV_WAIT(&vol_put_volume_cond);
2943 #else /* AFS_PTHREAD_ENV */
2944 LWP_WaitProcess(VPutVolume);
2945 #endif /* AFS_PTHREAD_ENV */
2948 if (vp->specialStatus) {
2950 *ec = vp->specialStatus;
2951 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
2954 } else if (V_inUse(vp) == 0) {
2965 #ifdef AFS_DEMAND_ATTACH_FS
2966 /* if no error, bump nUsers */
2969 VLRU_UpdateAccess_r(vp);
2972 VCancelReservation_r(rvp);
2975 if (client_ec && !*client_ec) {
2978 #else /* AFS_DEMAND_ATTACH_FS */
2979 /* if no error, bump nUsers */
2986 #endif /* AFS_DEMAND_ATTACH_FS */
2994 /***************************************************/
2995 /* Volume offline/detach routines */
2996 /***************************************************/
2998 /* caller MUST hold a heavyweight ref on vp */
2999 #ifdef AFS_DEMAND_ATTACH_FS
3001 VTakeOffline_r(register Volume * vp)
3005 assert(vp->nUsers > 0);
3006 assert(programType == fileServer);
3008 VCreateReservation_r(vp);
3009 VWaitExclusiveState_r(vp);
3011 vp->goingOffline = 1;
3012 V_needsSalvaged(vp) = 1;
3014 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
3015 VCancelReservation_r(vp);
3017 #else /* AFS_DEMAND_ATTACH_FS */
3019 VTakeOffline_r(register Volume * vp)
3021 assert(vp->nUsers > 0);
3022 assert(programType == fileServer);
3024 vp->goingOffline = 1;
3025 V_needsSalvaged(vp) = 1;
3027 #endif /* AFS_DEMAND_ATTACH_FS */
3030 VTakeOffline(register Volume * vp)
3038 * force a volume offline.
3040 * @param[in] vp volume object pointer
3041 * @param[in] flags flags (see note below)
3043 * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
3044 * used when VUpdateVolume_r needs to call VForceOffline_r
3045 * (which in turn would normally call VUpdateVolume_r)
3047 * @see VUpdateVolume_r
3049 * @pre VOL_LOCK must be held.
3050 * for DAFS, caller must hold ref.
3052 * @note for DAFS, it _is safe_ to call this function from an
3055 * @post needsSalvaged flag is set.
3056 * for DAFS, salvage is requested.
3057 * no further references to the volume through the volume
3058 * package will be honored.
3059 * all file descriptor and vnode caches are invalidated.
3061 * @warning this is a heavy-handed interface. it results in
3062 * a volume going offline regardless of the current
3063 * reference count state.
3065 * @internal volume package internal use only
3068 VForceOffline_r(Volume * vp, int flags)
3072 #ifdef AFS_DEMAND_ATTACH_FS
3073 VChangeState_r(vp, VOL_STATE_ERROR);
3078 strcpy(V_offlineMessage(vp),
3079 "Forced offline due to internal error: volume needs to be salvaged");
3080 Log("Volume %u forced offline: it needs salvaging!\n", V_id(vp));
3083 vp->goingOffline = 0;
3084 V_needsSalvaged(vp) = 1;
3085 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
3086 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
3089 #ifdef AFS_DEMAND_ATTACH_FS
3090 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3091 #endif /* AFS_DEMAND_ATTACH_FS */
3093 #ifdef AFS_PTHREAD_ENV
3094 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3095 #else /* AFS_PTHREAD_ENV */
3096 LWP_NoYieldSignal(VPutVolume);
3097 #endif /* AFS_PTHREAD_ENV */
3099 VReleaseVolumeHandles_r(vp);
3103 * force a volume offline.
3105 * @param[in] vp volume object pointer
3107 * @see VForceOffline_r
3110 VForceOffline(Volume * vp)
3113 VForceOffline_r(vp, 0);
3117 /* The opposite of VAttachVolume. The volume header is written to disk, with
3118 the inUse bit turned off. A copy of the header is maintained in memory,
3119 however (which is why this is VOffline, not VDetach).
3122 VOffline_r(Volume * vp, char *message)
3125 VolumeId vid = V_id(vp);
3127 assert(programType != volumeUtility);
3132 if (V_offlineMessage(vp)[0] == '\0')
3133 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
3134 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
3136 vp->goingOffline = 1;
3137 #ifdef AFS_DEMAND_ATTACH_FS
3138 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
3139 VCreateReservation_r(vp);
3142 /* wait for the volume to go offline */
3143 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
3144 VWaitStateChange_r(vp);
3146 VCancelReservation_r(vp);
3147 #else /* AFS_DEMAND_ATTACH_FS */
3149 vp = VGetVolume_r(&error, vid); /* Wait for it to go offline */
3150 if (vp) /* In case it was reattached... */
3152 #endif /* AFS_DEMAND_ATTACH_FS */
3156 VOffline(Volume * vp, char *message)
3159 VOffline_r(vp, message);
3163 /* This gets used for the most part by utility routines that don't want
3164 * to keep all the volume headers around. Generally, the file server won't
3165 * call this routine, because then the offline message in the volume header
3166 * (or other information) won't be available to clients. For NAMEI, also
3167 * close the file handles. However, the fileserver does call this during
3168 * an attach following a volume operation.
3171 VDetachVolume_r(Error * ec, Volume * vp)
3174 struct DiskPartition64 *tpartp;
3175 int notifyServer = 0;
3176 int useDone = FSYNC_VOL_ON;
3178 *ec = 0; /* always "succeeds" */
3179 if (programType == volumeUtility) {
3180 notifyServer = vp->needsPutBack;
3181 if (V_destroyMe(vp) == DESTROY_ME)
3182 useDone = FSYNC_VOL_DONE;
3183 #ifdef AFS_DEMAND_ATTACH_FS
3184 else if (!V_blessed(vp) || !V_inService(vp))
3185 useDone = FSYNC_VOL_LEAVE_OFF;
3188 tpartp = vp->partition;
3190 DeleteVolumeFromHashTable(vp);
3191 vp->shuttingDown = 1;
3192 #ifdef AFS_DEMAND_ATTACH_FS
3193 DeleteVolumeFromVByPList_r(vp);
3195 VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
3196 #endif /* AFS_DEMAND_ATTACH_FS */
3198 /* Will be detached sometime in the future--this is OK since volume is offline */
3200 /* XXX the following code should really be moved to VCheckDetach() since the volume
3201 * is not technically detached until the refcounts reach zero
3203 #ifdef FSSYNC_BUILD_CLIENT
3204 if (programType == volumeUtility && notifyServer) {
3206 * Note: The server is not notified in the case of a bogus volume
3207 * explicitly to make it possible to create a volume, do a partial
3208 * restore, then abort the operation without ever putting the volume
3209 * online. This is essential in the case of a volume move operation
3210 * between two partitions on the same server. In that case, there
3211 * would be two instances of the same volume, one of them bogus,
3212 * which the file server would attempt to put on line
3214 FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
3215 /* XXX this code path is only hit by volume utilities, thus
3216 * V_BreakVolumeCallbacks will always be NULL. if we really
3217 * want to break callbacks in this path we need to use FSYNC_VolOp() */
3219 /* Dettaching it so break all callbacks on it */
3220 if (V_BreakVolumeCallbacks) {
3221 Log("volume %u detached; breaking all call backs\n", volume);
3222 (*V_BreakVolumeCallbacks) (volume);
3226 #endif /* FSSYNC_BUILD_CLIENT */
3230 VDetachVolume(Error * ec, Volume * vp)
3233 VDetachVolume_r(ec, vp);
3238 /***************************************************/
3239 /* Volume fd/inode handle closing routines */
3240 /***************************************************/
3242 /* For VDetachVolume, we close all cached file descriptors, but keep
3243 * the Inode handles in case we need to read from a busy volume.
3245 /* for demand attach, caller MUST hold ref count on vp */
3247 VCloseVolumeHandles_r(Volume * vp)
3249 #ifdef AFS_DEMAND_ATTACH_FS
3250 VolState state_save;
3252 state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
3257 * XXX need to investigate whether we can perform
3258 * DFlushVolume outside of vol_glock_mutex...
3260 * VCloseVnodeFiles_r drops the glock internally */
3261 DFlushVolume(V_id(vp));
3262 VCloseVnodeFiles_r(vp);
3264 #ifdef AFS_DEMAND_ATTACH_FS
3268 /* Too time consuming and unnecessary for the volserver */
3269 if (programType != volumeUtility) {
3270 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
3271 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
3272 IH_CONDSYNC(vp->diskDataHandle);
3274 IH_CONDSYNC(vp->linkHandle);
3275 #endif /* AFS_NT40_ENV */
3278 IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
3279 IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
3280 IH_REALLYCLOSE(vp->diskDataHandle);
3281 IH_REALLYCLOSE(vp->linkHandle);
3283 #ifdef AFS_DEMAND_ATTACH_FS
3285 VChangeState_r(vp, state_save);
3289 /* For both VForceOffline and VOffline, we close all relevant handles.
3290 * For VOffline, if we re-attach the volume, the files may possible be
3291 * different than before.
3293 /* for demand attach, caller MUST hold a ref count on vp */
3295 VReleaseVolumeHandles_r(Volume * vp)
3297 #ifdef AFS_DEMAND_ATTACH_FS
3298 VolState state_save;
3300 state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
3303 /* XXX need to investigate whether we can perform
3304 * DFlushVolume outside of vol_glock_mutex... */
3305 DFlushVolume(V_id(vp));
3307 VReleaseVnodeFiles_r(vp); /* releases the glock internally */
3309 #ifdef AFS_DEMAND_ATTACH_FS
3313 /* Too time consuming and unnecessary for the volserver */
3314 if (programType != volumeUtility) {
3315 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
3316 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
3317 IH_CONDSYNC(vp->diskDataHandle);
3319 IH_CONDSYNC(vp->linkHandle);
3320 #endif /* AFS_NT40_ENV */
3323 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
3324 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
3325 IH_RELEASE(vp->diskDataHandle);
3326 IH_RELEASE(vp->linkHandle);
3328 #ifdef AFS_DEMAND_ATTACH_FS
3330 VChangeState_r(vp, state_save);
3335 /***************************************************/
3336 /* Volume write and fsync routines */
3337 /***************************************************/
3340 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
3342 #ifdef AFS_DEMAND_ATTACH_FS
3343 VolState state_save;
3345 if (flags & VOL_UPDATE_WAIT) {
3346 VCreateReservation_r(vp);
3347 VWaitExclusiveState_r(vp);
3352 if (programType == fileServer)
3354 (V_inUse(vp) ? V_nextVnodeUnique(vp) +
3355 200 : V_nextVnodeUnique(vp));
3357 #ifdef AFS_DEMAND_ATTACH_FS
3358 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
3362 WriteVolumeHeader_r(ec, vp);
3364 #ifdef AFS_DEMAND_ATTACH_FS
3366 VChangeState_r(vp, state_save);
3367 if (flags & VOL_UPDATE_WAIT) {
3368 VCancelReservation_r(vp);
3373 Log("VUpdateVolume: error updating volume header, volume %u (%s)\n",
3374 V_id(vp), V_name(vp));
3375 /* try to update on-disk header,
3376 * while preventing infinite recursion */
3377 if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
3378 VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
3384 VUpdateVolume(Error * ec, Volume * vp)
3387 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
3392 VSyncVolume_r(Error * ec, Volume * vp, int flags)
3396 #ifdef AFS_DEMAND_ATTACH_FS
3397 VolState state_save;
3400 if (flags & VOL_SYNC_WAIT) {
3401 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
3403 VUpdateVolume_r(ec, vp, 0);
3406 #ifdef AFS_DEMAND_ATTACH_FS
3407 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
3410 fdP = IH_OPEN(V_diskDataHandle(vp));
3411 assert(fdP != NULL);
3412 code = FDH_SYNC(fdP);
3415 #ifdef AFS_DEMAND_ATTACH_FS
3417 VChangeState_r(vp, state_save);
3423 VSyncVolume(Error * ec, Volume * vp)
3426 VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
3431 /***************************************************/
3432 /* Volume dealloaction routines */
3433 /***************************************************/
3435 #ifdef AFS_DEMAND_ATTACH_FS
3437 FreeVolume(Volume * vp)
3439 /* free the heap space, iff it's safe.
3440 * otherwise, pull it out of the hash table, so it
3441 * will get deallocated when all refs to it go away */
3442 if (!VCheckFree(vp)) {
3443 DeleteVolumeFromHashTable(vp);
3444 DeleteVolumeFromVByPList_r(vp);
3446 /* make sure we invalidate the header cache entry */
3447 FreeVolumeHeader(vp);
3450 #endif /* AFS_DEMAND_ATTACH_FS */
3453 ReallyFreeVolume(Volume * vp)
3458 #ifdef AFS_DEMAND_ATTACH_FS
3460 VChangeState_r(vp, VOL_STATE_FREED);
3461 if (vp->pending_vol_op)
3462 free(vp->pending_vol_op);
3463 #endif /* AFS_DEMAND_ATTACH_FS */
3464 for (i = 0; i < nVNODECLASSES; i++)
3465 if (vp->vnodeIndex[i].bitmap)
3466 free(vp->vnodeIndex[i].bitmap);
3467 FreeVolumeHeader(vp);
3468 #ifndef AFS_DEMAND_ATTACH_FS
3469 DeleteVolumeFromHashTable(vp);
3470 #endif /* AFS_DEMAND_ATTACH_FS */
3474 /* check to see if we should shutdown this volume
3475 * returns 1 if volume was freed, 0 otherwise */
3476 #ifdef AFS_DEMAND_ATTACH_FS
3478 VCheckDetach(register Volume * vp)
3483 if (vp->nUsers || vp->nWaiters)
3486 if (vp->shuttingDown) {
3488 if ((programType != fileServer) &&
3489 (V_inUse(vp) == programType) &&
3490 ((V_checkoutMode(vp) == V_VOLUPD) ||
3491 ((V_checkoutMode(vp) == V_CLONE) &&
3492 (VolumeWriteable(vp))))) {
3494 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
3496 Log("VCheckDetach: volume header update for volume %u "
3497 "failed with errno %d\n", vp->hashid, errno);
3500 VReleaseVolumeHandles_r(vp);
3502 ReallyFreeVolume(vp);
3503 if (programType == fileServer) {
3504 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3509 #else /* AFS_DEMAND_ATTACH_FS */
3511 VCheckDetach(register Volume * vp)
3519 if (vp->shuttingDown) {
3521 if ((programType != fileServer) &&
3522 (V_inUse(vp) == programType) &&
3523 ((V_checkoutMode(vp) == V_VOLUPD) ||
3524 ((V_checkoutMode(vp) == V_CLONE) &&
3525 (VolumeWriteable(vp))))) {
3527 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
3529 Log("VCheckDetach: volume header update for volume %u failed with errno %d\n",
3533 VReleaseVolumeHandles_r(vp);
3534 ReallyFreeVolume(vp);
3535 if (programType == fileServer) {
3536 #if defined(AFS_PTHREAD_ENV)
3537 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3538 #else /* AFS_PTHREAD_ENV */
3539 LWP_NoYieldSignal(VPutVolume);
3540 #endif /* AFS_PTHREAD_ENV */
3545 #endif /* AFS_DEMAND_ATTACH_FS */
3547 /* check to see if we should offline this volume
3548 * return 1 if volume went offline, 0 otherwise */
3549 #ifdef AFS_DEMAND_ATTACH_FS
3551 VCheckOffline(register Volume * vp)
3553 Volume * rvp = NULL;
3556 if (vp->goingOffline && !vp->nUsers) {
3558 assert(programType == fileServer);
3559 assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
3560 (V_attachState(vp) != VOL_STATE_FREED) &&
3561 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
3562 (V_attachState(vp) != VOL_STATE_UNATTACHED));
3566 * VOL_STATE_GOING_OFFLINE
3567 * VOL_STATE_SHUTTING_DOWN
3568 * VIsErrorState(V_attachState(vp))
3569 * VIsExclusiveState(V_attachState(vp))
3572 VCreateReservation_r(vp);
3573 VChangeState_r(vp, VOL_STATE_OFFLINING);
3576 /* must clear the goingOffline flag before we drop the glock */
3577 vp->goingOffline = 0;
3582 /* perform async operations */
3583 VUpdateVolume_r(&error, vp, 0);
3584 VCloseVolumeHandles_r(vp);
3587 Log("VOffline: Volume %u (%s) is now offline", V_id(vp),
3589 if (V_offlineMessage(vp)[0])
3590 Log(" (%s)", V_offlineMessage(vp));
3594 /* invalidate the volume header cache entry */
3595 FreeVolumeHeader(vp);
3597 /* if nothing changed state to error or salvaging,
3598 * drop state to unattached */
3599 if (!VIsErrorState(V_attachState(vp))) {
3600 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3602 VCancelReservation_r(vp);
3603 /* no usage of vp is safe beyond this point */
3607 #else /* AFS_DEMAND_ATTACH_FS */
3609 VCheckOffline(register Volume * vp)
3611 Volume * rvp = NULL;
3614 if (vp->goingOffline && !vp->nUsers) {
3616 assert(programType == fileServer);
3619 vp->goingOffline = 0;
3621 VUpdateVolume_r(&error, vp, 0);
3622 VCloseVolumeHandles_r(vp);
3624 Log("VOffline: Volume %u (%s) is now offline", V_id(vp),
3626 if (V_offlineMessage(vp)[0])
3627 Log(" (%s)", V_offlineMessage(vp));
3630 FreeVolumeHeader(vp);
3631 #ifdef AFS_PTHREAD_ENV
3632 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3633 #else /* AFS_PTHREAD_ENV */
3634 LWP_NoYieldSignal(VPutVolume);
3635 #endif /* AFS_PTHREAD_ENV */
3639 #endif /* AFS_DEMAND_ATTACH_FS */
3641 /***************************************************/
3642 /* demand attach fs ref counting routines */
3643 /***************************************************/
3645 #ifdef AFS_DEMAND_ATTACH_FS
3646 /* the following two functions handle reference counting for
3647 * asynchronous operations on volume structs.
3649 * their purpose is to prevent a VDetachVolume or VShutdown
3650 * from free()ing the Volume struct during an async i/o op */
3652 /* register with the async volume op ref counter */
3653 /* VCreateReservation_r moved into inline code header because it
3654 * is now needed in vnode.c -- tkeiser 11/20/2007
3658 * decrement volume-package internal refcount.
3660 * @param vp volume object pointer
3662 * @internal volume package internal use only
3665 * @arg VOL_LOCK is held
3666 * @arg lightweight refcount held
3668 * @post volume waiters refcount is decremented; volume may
3669 * have been deallocated/shutdown/offlined/salvaged/
3670 * whatever during the process
3672 * @warning once you have tossed your last reference (you can acquire
3673 * lightweight refs recursively) it is NOT SAFE to reference
3674 * a volume object pointer ever again
3676 * @see VCreateReservation_r
3678 * @note DEMAND_ATTACH_FS only
3681 VCancelReservation_r(Volume * vp)
3683 assert(--vp->nWaiters >= 0);
3684 if (vp->nWaiters == 0) {
3686 if (!VCheckDetach(vp)) {
3693 /* check to see if we should free this volume now
3694 * return 1 if volume was freed, 0 otherwise */
3696 VCheckFree(Volume * vp)
3699 if ((vp->nUsers == 0) &&
3700 (vp->nWaiters == 0) &&
3701 !(V_attachFlags(vp) & (VOL_IN_HASH |
3705 ReallyFreeVolume(vp);
3710 #endif /* AFS_DEMAND_ATTACH_FS */
3713 /***************************************************/
3714 /* online volume operations routines */
3715 /***************************************************/
3717 #ifdef AFS_DEMAND_ATTACH_FS
3719 * register a volume operation on a given volume.
3721 * @param[in] vp volume object
3722 * @param[in] vopinfo volume operation info object
3724 * @pre VOL_LOCK is held
3726 * @post volume operation info object attached to volume object.
3727 * volume operation statistics updated.
3729 * @note by "attached" we mean a copy of the passed in object is made
3731 * @internal volume package internal use only
3734 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3736 FSSYNC_VolOp_info * info;
3738 /* attach a vol op info node to the volume struct */
3739 info = (FSSYNC_VolOp_info *) malloc(sizeof(FSSYNC_VolOp_info));
3740 assert(info != NULL);
3741 memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
3742 vp->pending_vol_op = info;
3745 vp->stats.last_vol_op = FT_ApproxTime();
3746 vp->stats.vol_ops++;
3747 IncUInt64(&VStats.vol_ops);
3753 * deregister the volume operation attached to this volume.
3755 * @param[in] vp volume object pointer
3757 * @pre VOL_LOCK is held
3759 * @post the volume operation info object is detached from the volume object
3761 * @internal volume package internal use only
3764 VDeregisterVolOp_r(Volume * vp)
3766 if (vp->pending_vol_op) {
3767 free(vp->pending_vol_op);
3768 vp->pending_vol_op = NULL;
3772 #endif /* AFS_DEMAND_ATTACH_FS */
3775 * determine whether it is safe to leave a volume online during
3776 * the volume operation described by the vopinfo object.
3778 * @param[in] vp volume object
3779 * @param[in] vopinfo volume operation info object
3781 * @return whether it is safe to leave volume online
3782 * @retval 0 it is NOT SAFE to leave the volume online
3783 * @retval 1 it is safe to leave the volume online during the operation
3786 * @arg VOL_LOCK is held
3787 * @arg disk header attached to vp (heavyweight ref on vp will guarantee
3788 * this condition is met)
3790 * @internal volume package internal use only
3793 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3795 return (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
3796 (vopinfo->com.reason == V_READONLY ||
3797 (!VolumeWriteable(vp) &&
3798 (vopinfo->com.reason == V_CLONE ||
3799 vopinfo->com.reason == V_DUMP))));
3803 * determine whether VBUSY should be set during this volume operation.
3805 * @param[in] vp volume object
3806 * @param[in] vopinfo volume operation info object
3808 * @return whether VBUSY should be set
3809 * @retval 0 VBUSY does NOT need to be set
3810 * @retval 1 VBUSY SHOULD be set
3812 * @pre VOL_LOCK is held
3814 * @internal volume package internal use only
3817 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3819 return ((vopinfo->com.command == FSYNC_VOL_OFF &&
3820 vopinfo->com.reason == FSYNC_SALVAGE) ||
3821 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
3822 (vopinfo->com.reason == V_CLONE ||
3823 vopinfo->com.reason == V_DUMP)));
3827 /***************************************************/
3828 /* online salvager routines */
3829 /***************************************************/
3830 #if defined(AFS_DEMAND_ATTACH_FS)
3831 #define SALVAGE_PRIO_UPDATE_INTERVAL 3 /**< number of seconds between prio updates */
3832 #define SALVAGE_COUNT_MAX 16 /**< number of online salvages we
3833 * allow before moving the volume
3834 * into a permanent error state
3836 * once this threshold is reached,
3837 * the operator will have to manually
3838 * issue a 'bos salvage' to bring
3839 * the volume back online
3843 * check whether a salvage needs to be performed on this volume.
3845 * @param[in] vp pointer to volume object
3847 * @return status code
3848 * @retval 0 no salvage scheduled
3849 * @retval 1 a salvage has been scheduled with the salvageserver
3851 * @pre VOL_LOCK is held
3853 * @post if salvage request flag is set and nUsers and nWaiters are zero,
3854 * then a salvage will be requested
3856 * @note this is one of the event handlers called by VCancelReservation_r
3858 * @see VCancelReservation_r
3860 * @internal volume package internal use only.
3863 VCheckSalvage(register Volume * vp)
3866 #ifdef SALVSYNC_BUILD_CLIENT
3867 if (vp->nUsers || vp->nWaiters)
3869 if (vp->salvage.requested) {
3870 VScheduleSalvage_r(vp);
3873 #endif /* SALVSYNC_BUILD_CLIENT */
3878 * request volume salvage.
3880 * @param[out] ec computed client error code
3881 * @param[in] vp volume object pointer
3882 * @param[in] reason reason code (passed to salvageserver via SALVSYNC)
3883 * @param[in] flags see flags note below
3886 * VOL_SALVAGE_INVALIDATE_HEADER causes volume header cache entry
3887 * to be invalidated.
3889 * @pre VOL_LOCK is held.
3891 * @post volume state is changed.
3892 * for fileserver, salvage will be requested once refcount reaches zero.
3894 * @return operation status code
3895 * @retval 0 volume salvage will occur
3896 * @retval 1 volume salvage could not be scheduled
3898 * @note DAFS fileserver only
3900 * @note this call does not synchronously schedule a volume salvage. rather,
3901 * it sets volume state so that when volume refcounts reach zero, a
3902 * volume salvage will occur. by "refcounts", we mean both nUsers and
3903 * nWaiters must be zero.
3905 * @internal volume package internal use only.
3908 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
3912 * for DAFS volume utilities, transition to error state
3913 * (at some point in the future, we should consider
3914 * making volser talk to salsrv)
3916 if (programType != fileServer) {
3917 VChangeState_r(vp, VOL_STATE_ERROR);
3922 if (!vp->salvage.requested) {
3923 vp->salvage.requested = 1;
3924 vp->salvage.reason = reason;
3925 vp->stats.last_salvage = FT_ApproxTime();
3926 if (flags & VOL_SALVAGE_INVALIDATE_HEADER) {
3927 /* Instead of ReleaseVolumeHeader, we do FreeVolumeHeader()
3928 so that the the next VAttachVolumeByVp_r() invocation
3929 of attach2() will pull in a cached header
3930 entry and fail, then load a fresh one from disk and attach
3933 FreeVolumeHeader(vp);
3935 if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
3936 VChangeState_r(vp, VOL_STATE_SALVAGING);
3939 Log("VRequestSalvage: volume %u online salvaged too many times; forced offline.\n", vp->hashid);
3940 VChangeState_r(vp, VOL_STATE_ERROR);
3949 * update salvageserver scheduling priority for a volume.
3951 * @param[in] vp pointer to volume object
3953 * @return operation status
3955 * @retval 1 request denied, or SALVSYNC communications failure
3957 * @pre VOL_LOCK is held.
3959 * @post in-core salvage priority counter is incremented. if at least
3960 * SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
3961 * last SALVSYNC_RAISEPRIO request, we contact the salvageserver
3962 * to update its priority queue. if no salvage is scheduled,
3963 * this function is a no-op.
3965 * @note DAFS fileserver only
3967 * @note this should be called whenever a VGetVolume fails due to a
3968 * pending salvage request
3970 * @todo should set exclusive state and drop glock around salvsync call
3972 * @internal volume package internal use only.
3975 VUpdateSalvagePriority_r(Volume * vp)
3980 #ifdef SALVSYNC_BUILD_CLIENT
3982 now = FT_ApproxTime();
3984 /* update the salvageserver priority queue occasionally so that
3985 * frequently requested volumes get moved to the head of the queue
3987 if ((vp->salvage.scheduled) &&
3988 (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
3989 code = SALVSYNC_SalvageVolume(vp->hashid,
3990 VPartitionPath(vp->partition),
3995 vp->stats.last_salvage_req = now;
3996 if (code != SYNC_OK) {
4000 #endif /* SALVSYNC_BUILD_CLIENT */
4006 * schedule a salvage with the salvage server.
4008 * @param[in] vp pointer to volume object
4010 * @return operation status
4011 * @retval 0 salvage scheduled successfully
4012 * @retval 1 salvage not scheduled, or SALVSYNC com error
4015 * @arg VOL_LOCK is held.
4016 * @arg nUsers and nWaiters should be zero.
4018 * @post salvageserver is sent a salvage request
4020 * @note DAFS fileserver only
4022 * @internal volume package internal use only.
4025 VScheduleSalvage_r(Volume * vp)
4028 #ifdef SALVSYNC_BUILD_CLIENT
4029 VolState state_save;
4030 VThreadOptions_t * thread_opts;
4033 if (vp->nWaiters || vp->nUsers) {
4037 /* prevent endless salvage,attach,salvage,attach,... loops */
4038 if (vp->stats.salvages >= SALVAGE_COUNT_MAX)
4042 * don't perform salvsync ops on certain threads
4044 thread_opts = pthread_getspecific(VThread_key);
4045 if (thread_opts == NULL) {
4046 thread_opts = &VThread_defaults;
4048 if (thread_opts->disallow_salvsync) {
4053 * XXX the scheduling process should really be done asynchronously
4054 * to avoid fssync deadlocks
4056 if (!vp->salvage.scheduled) {
4057 /* if we haven't previously scheduled a salvage, do so now
4059 * set the volume to an exclusive state and drop the lock
4060 * around the SALVSYNC call
4062 * note that we do NOT acquire a reservation here -- doing so
4063 * could result in unbounded recursion
4065 strlcpy(partName, VPartitionPath(vp->partition), sizeof(partName));
4066 state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
4069 /* can't use V_id() since there's no guarantee
4070 * we have the disk data header at this point */
4071 code = SALVSYNC_SalvageVolume(vp->hashid,
4078 VChangeState_r(vp, state_save);
4080 if (code == SYNC_OK) {
4081 vp->salvage.scheduled = 1;
4082 vp->stats.salvages++;
4083 vp->stats.last_salvage_req = FT_ApproxTime();
4084 IncUInt64(&VStats.salvages);
4088 case SYNC_BAD_COMMAND:
4089 case SYNC_COM_ERROR:
4092 Log("VScheduleSalvage_r: SALVSYNC request denied\n");
4095 Log("VScheduleSalvage_r: SALVSYNC unknown protocol error\n");
4100 #endif /* SALVSYNC_BUILD_CLIENT */
4105 * ask salvageserver to cancel a scheduled salvage operation.
4107 * @param[in] vp pointer to volume object
4108 * @param[in] reason SALVSYNC protocol reason code
4110 * @return operation status
4112 * @retval 1 request failed
4114 * @pre VOL_LOCK is held.
4116 * @post salvageserver is sent a request to cancel the volume salvage.
4117 * volume is transitioned to a hard error state.
4119 * @internal volume package internal use only.
4122 VCancelSalvage_r(Volume * vp, int reason)
4126 #ifdef SALVSYNC_BUILD_CLIENT
4127 if (vp->salvage.scheduled) {
4128 VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
4131 /* can't use V_id() since there's no guarantee
4132 * we have the disk data header at this point */
4133 code = SALVSYNC_SalvageVolume(vp->hashid,
4134 VPartitionPath(vp->partition),
4141 VChangeState_r(vp, VOL_STATE_ERROR);
4143 if (code == SYNC_OK) {
4144 vp->salvage.scheduled = 0;
4145 vp->salvage.requested = 0;
4150 #endif /* SALVSYNC_BUILD_CLIENT */
4155 #ifdef SALVSYNC_BUILD_CLIENT
4157 * connect to the salvageserver SYNC service.
4159 * @return operation status
4163 * @post connection to salvageserver SYNC service established
4165 * @see VConnectSALV_r
4166 * @see VDisconnectSALV
4167 * @see VReconnectSALV
4174 retVal = VConnectSALV_r();
4180 * connect to the salvageserver SYNC service.
4182 * @return operation status
4186 * @pre VOL_LOCK is held.
4188 * @post connection to salvageserver SYNC service established
4191 * @see VDisconnectSALV_r
4192 * @see VReconnectSALV_r
4193 * @see SALVSYNC_clientInit
4195 * @internal volume package internal use only.
4198 VConnectSALV_r(void)
4200 return SALVSYNC_clientInit();
4204 * disconnect from the salvageserver SYNC service.
4206 * @return operation status
4209 * @pre client should have a live connection to the salvageserver
4211 * @post connection to salvageserver SYNC service destroyed
4213 * @see VDisconnectSALV_r
4215 * @see VReconnectSALV
4218 VDisconnectSALV(void)
4222 VDisconnectSALV_r();
4228 * disconnect from the salvageserver SYNC service.
4230 * @return operation status
4234 * @arg VOL_LOCK is held.
4235 * @arg client should have a live connection to the salvageserver.
4237 * @post connection to salvageserver SYNC service destroyed
4239 * @see VDisconnectSALV
4240 * @see VConnectSALV_r
4241 * @see VReconnectSALV_r
4242 * @see SALVSYNC_clientFinis
4244 * @internal volume package internal use only.
4247 VDisconnectSALV_r(void)
4249 return SALVSYNC_clientFinis();
4253 * disconnect and then re-connect to the salvageserver SYNC service.
4255 * @return operation status
4259 * @pre client should have a live connection to the salvageserver
4261 * @post old connection is dropped, and a new one is established
4264 * @see VDisconnectSALV
4265 * @see VReconnectSALV_r
4268 VReconnectSALV(void)
4272 retVal = VReconnectSALV_r();
4278 * disconnect and then re-connect to the salvageserver SYNC service.
4280 * @return operation status
4285 * @arg VOL_LOCK is held.
4286 * @arg client should have a live connection to the salvageserver.
4288 * @post old connection is dropped, and a new one is established
4290 * @see VConnectSALV_r
4291 * @see VDisconnectSALV
4292 * @see VReconnectSALV
4293 * @see SALVSYNC_clientReconnect
4295 * @internal volume package internal use only.
4298 VReconnectSALV_r(void)
4300 return SALVSYNC_clientReconnect();
4302 #endif /* SALVSYNC_BUILD_CLIENT */
4303 #endif /* AFS_DEMAND_ATTACH_FS */
4306 /***************************************************/
4307 /* FSSYNC routines */
4308 /***************************************************/
4310 /* This must be called by any volume utility which needs to run while the
4311 file server is also running. This is separated from VInitVolumePackage so
4312 that a utility can fork--and each of the children can independently
4313 initialize communication with the file server */
4314 #ifdef FSSYNC_BUILD_CLIENT
4316 * connect to the fileserver SYNC service.
4318 * @return operation status
4323 * @arg VInit must equal 2.
4324 * @arg Program Type must not be fileserver or salvager.
4326 * @post connection to fileserver SYNC service established
4329 * @see VDisconnectFS
4330 * @see VChildProcReconnectFS
4337 retVal = VConnectFS_r();
4343 * connect to the fileserver SYNC service.
4345 * @return operation status
4350 * @arg VInit must equal 2.
4351 * @arg Program Type must not be fileserver or salvager.
4352 * @arg VOL_LOCK is held.
4354 * @post connection to fileserver SYNC service established
4357 * @see VDisconnectFS_r
4358 * @see VChildProcReconnectFS_r
4360 * @internal volume package internal use only.
4366 assert((VInit == 2) &&
4367 (programType != fileServer) &&
4368 (programType != salvager));
4369 rc = FSYNC_clientInit();
4376 * disconnect from the fileserver SYNC service.
4379 * @arg client should have a live connection to the fileserver.
4380 * @arg VOL_LOCK is held.
4381 * @arg Program Type must not be fileserver or salvager.
4383 * @post connection to fileserver SYNC service destroyed
4385 * @see VDisconnectFS
4387 * @see VChildProcReconnectFS_r
4389 * @internal volume package internal use only.
4392 VDisconnectFS_r(void)
4394 assert((programType != fileServer) &&
4395 (programType != salvager));
4396 FSYNC_clientFinis();
4401 * disconnect from the fileserver SYNC service.
4404 * @arg client should have a live connection to the fileserver.
4405 * @arg Program Type must not be fileserver or salvager.
4407 * @post connection to fileserver SYNC service destroyed
4409 * @see VDisconnectFS_r
4411 * @see VChildProcReconnectFS
4422 * connect to the fileserver SYNC service from a child process following a fork.
4424 * @return operation status
4429 * @arg VOL_LOCK is held.
4430 * @arg current FSYNC handle is shared with a parent process
4432 * @post current FSYNC handle is discarded and a new connection to the
4433 * fileserver SYNC service is established
4435 * @see VChildProcReconnectFS
4437 * @see VDisconnectFS_r
4439 * @internal volume package internal use only.
4442 VChildProcReconnectFS_r(void)
4444 return FSYNC_clientChildProcReconnect();
4448 * connect to the fileserver SYNC service from a child process following a fork.
4450 * @return operation status
4454 * @pre current FSYNC handle is shared with a parent process
4456 * @post current FSYNC handle is discarded and a new connection to the
4457 * fileserver SYNC service is established
4459 * @see VChildProcReconnectFS_r
4461 * @see VDisconnectFS
4464 VChildProcReconnectFS(void)
4468 ret = VChildProcReconnectFS_r();
4472 #endif /* FSSYNC_BUILD_CLIENT */
4475 /***************************************************/
4476 /* volume bitmap routines */
4477 /***************************************************/
4480 * For demand attach fs, flags parameter controls
4481 * locking behavior. If (flags & VOL_ALLOC_BITMAP_WAIT)
4482 * is set, then this function will create a reservation
4483 * and block on any other exclusive operations. Otherwise,
4484 * this function assumes the caller already has exclusive
4485 * access to vp, and we just change the volume state.
4488 VAllocBitmapEntry_r(Error * ec, Volume * vp,
4489 struct vnodeIndex *index, int flags)
4492 register byte *bp, *ep;
4493 #ifdef AFS_DEMAND_ATTACH_FS
4494 VolState state_save;
4495 #endif /* AFS_DEMAND_ATTACH_FS */
4499 /* This test is probably redundant */
4500 if (!VolumeWriteable(vp)) {
4501 *ec = (bit32) VREADONLY;
4505 #ifdef AFS_DEMAND_ATTACH_FS
4506 if (flags & VOL_ALLOC_BITMAP_WAIT) {
4507 VCreateReservation_r(vp);
4508 VWaitExclusiveState_r(vp);
4510 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
4511 #endif /* AFS_DEMAND_ATTACH_FS */
4514 if ((programType == fileServer) && !index->bitmap) {
4516 #ifndef AFS_DEMAND_ATTACH_FS
4517 /* demand attach fs uses the volume state to avoid races.
4518 * specialStatus field is not used at all */
4520 if (vp->specialStatus == VBUSY) {
4521 if (vp->goingOffline) { /* vos dump waiting for the volume to
4522 * go offline. We probably come here
4523 * from AddNewReadableResidency */
4526 while (vp->specialStatus == VBUSY) {
4527 #ifdef AFS_PTHREAD_ENV
4531 #else /* !AFS_PTHREAD_ENV */
4533 #endif /* !AFS_PTHREAD_ENV */
4537 #endif /* !AFS_DEMAND_ATTACH_FS */
4539 if (!index->bitmap) {
4540 #ifndef AFS_DEMAND_ATTACH_FS
4541 vp->specialStatus = VBUSY; /* Stop anyone else from using it. */
4542 #endif /* AFS_DEMAND_ATTACH_FS */
4543 for (i = 0; i < nVNODECLASSES; i++) {
4544 VGetBitmap_r(ec, vp, i);
4546 #ifdef AFS_DEMAND_ATTACH_FS
4547 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
4548 #else /* AFS_DEMAND_ATTACH_FS */
4549 DeleteVolumeFromHashTable(vp);
4550 vp->shuttingDown = 1; /* Let who has it free it. */
4551 vp->specialStatus = 0;
4552 #endif /* AFS_DEMAND_ATTACH_FS */
4557 #ifndef AFS_DEMAND_ATTACH_FS
4559 vp->specialStatus = 0; /* Allow others to have access. */
4560 #endif /* AFS_DEMAND_ATTACH_FS */
4563 #endif /* BITMAP_LATER */
4565 #ifdef AFS_DEMAND_ATTACH_FS
4567 #endif /* AFS_DEMAND_ATTACH_FS */
4568 bp = index->bitmap + index->bitmapOffset;
4569 ep = index->bitmap + index->bitmapSize;
4571 if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
4573 index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
4576 o = ffs(~*bp) - 1; /* ffs is documented in BSTRING(3) */
4578 ret = (VnodeId) ((bp - index->bitmap) * 8 + o);
4579 #ifdef AFS_DEMAND_ATTACH_FS
4581 #endif /* AFS_DEMAND_ATTACH_FS */
4584 bp += sizeof(bit32) /* i.e. 4 */ ;
4586 /* No bit map entry--must grow bitmap */
4588 realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
4591 bp += index->bitmapSize;
4592 memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
4593 index->bitmapOffset = index->bitmapSize;
4594 index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
4596 ret = index->bitmapOffset * 8;
4597 #ifdef AFS_DEMAND_ATTACH_FS
4599 #endif /* AFS_DEMAND_ATTACH_FS */
4602 #ifdef AFS_DEMAND_ATTACH_FS
4603 VChangeState_r(vp, state_save);
4604 if (flags & VOL_ALLOC_BITMAP_WAIT) {
4605 VCancelReservation_r(vp);
4607 #endif /* AFS_DEMAND_ATTACH_FS */
4612 VAllocBitmapEntry(Error * ec, Volume * vp, register struct vnodeIndex * index)
4616 retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
4622 VFreeBitMapEntry_r(Error * ec, register struct vnodeIndex *index,
4625 unsigned int offset;
4631 #endif /* BITMAP_LATER */
4632 offset = bitNumber >> 3;
4633 if (offset >= index->bitmapSize) {
4637 if (offset < index->bitmapOffset)
4638 index->bitmapOffset = offset & ~3; /* Truncate to nearest bit32 */
4639 *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
4643 VFreeBitMapEntry(Error * ec, register struct vnodeIndex *index,
4647 VFreeBitMapEntry_r(ec, index, bitNumber);
4651 /* this function will drop the glock internally.
4652 * for old pthread fileservers, this is safe thanks to vbusy.
4654 * for demand attach fs, caller must have already called
4655 * VCreateReservation_r and VWaitExclusiveState_r */
4657 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
4659 StreamHandle_t *file;
4662 struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
4663 struct vnodeIndex *vip = &vp->vnodeIndex[class];
4664 struct VnodeDiskObject *vnode;
4665 unsigned int unique = 0;
4669 #endif /* BITMAP_LATER */
4670 #ifdef AFS_DEMAND_ATTACH_FS
4671 VolState state_save;
4672 #endif /* AFS_DEMAND_ATTACH_FS */
4676 #ifdef AFS_DEMAND_ATTACH_FS
4677 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
4678 #endif /* AFS_DEMAND_ATTACH_FS */
4681 fdP = IH_OPEN(vip->handle);
4682 assert(fdP != NULL);
4683 file = FDH_FDOPEN(fdP, "r");
4684 assert(file != NULL);
4685 vnode = (VnodeDiskObject *) malloc(vcp->diskSize);
4686 assert(vnode != NULL);
4687 size = OS_SIZE(fdP->fd_fd);
4689 nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
4691 vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4; /* The 10 is a little extra so
4692 * a few files can be created in this volume,
4693 * the whole thing is rounded up to nearest 4
4694 * bytes, because the bit map allocator likes
4697 BitMap = (byte *) calloc(1, vip->bitmapSize);
4698 assert(BitMap != NULL);
4699 #else /* BITMAP_LATER */
4700 vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
4701 assert(vip->bitmap != NULL);
4702 vip->bitmapOffset = 0;
4703 #endif /* BITMAP_LATER */
4704 if (STREAM_SEEK(file, vcp->diskSize, 0) != -1) {
4706 for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
4707 if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
4709 if (vnode->type != vNull) {
4710 if (vnode->vnodeMagic != vcp->magic) {
4711 Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
4716 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
4717 #else /* BITMAP_LATER */
4718 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
4719 #endif /* BITMAP_LATER */
4720 if (unique <= vnode->uniquifier)
4721 unique = vnode->uniquifier + 1;
4723 #ifndef AFS_PTHREAD_ENV
4724 if ((bitNumber & 0x00ff) == 0x0ff) { /* every 256 iterations */
4727 #endif /* !AFS_PTHREAD_ENV */
4730 if (vp->nextVnodeUnique < unique) {
4731 Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
4734 /* Paranoia, partly justified--I think fclose after fdopen
4735 * doesn't seem to close fd. In any event, the documentation
4736 * doesn't specify, so it's safer to close it twice.
4744 /* There may have been a racing condition with some other thread, both
4745 * creating the bitmaps for this volume. If the other thread was faster
4746 * the pointer to bitmap should already be filled and we can free ours.
4748 if (vip->bitmap == NULL) {
4749 vip->bitmap = BitMap;
4750 vip->bitmapOffset = 0;
4752 free((byte *) BitMap);
4753 #endif /* BITMAP_LATER */
4754 #ifdef AFS_DEMAND_ATTACH_FS
4755 VChangeState_r(vp, state_save);
4756 #endif /* AFS_DEMAND_ATTACH_FS */
4760 /***************************************************/
4761 /* Volume Path and Volume Number utility routines */
4762 /***************************************************/
4765 * find the first occurrence of a volume header file and return the path.
4767 * @param[out] ec outbound error code
4768 * @param[in] volumeId volume id to find
4769 * @param[out] partitionp pointer to disk partition path string
4770 * @param[out] namep pointer to volume header file name string
4772 * @post path to first occurrence of volume header is returned in partitionp
4773 * and namep, or ec is set accordingly.
4775 * @warning this function is NOT re-entrant -- partitionp and namep point to
4776 * static data segments
4778 * @note if a volume utility inadvertently leaves behind a stale volume header
4779 * on a vice partition, it is possible for callers to get the wrong one,
4780 * depending on the order of the disk partition linked list.
4784 VGetVolumePath(Error * ec, VolId volumeId, char **partitionp, char **namep)
4786 static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
4787 char path[VMAXPATHLEN];
4789 struct DiskPartition64 *dp;
4793 (void)afs_snprintf(&name[1], (sizeof name) - 1, VFORMAT, volumeId);
4794 for (dp = DiskPartitionList; dp; dp = dp->next) {
4795 struct afs_stat status;
4796 strcpy(path, VPartitionPath(dp));
4798 if (afs_stat(path, &status) == 0) {
4799 strcpy(partition, dp->name);
4806 *partitionp = *namep = NULL;
4808 *partitionp = partition;
4814 * extract a volume number from a volume header filename string.
4816 * @param[in] name volume header filename string
4818 * @return volume number
4820 * @note the string must be of the form VFORMAT. the only permissible
4821 * deviation is a leading '/' character.
4826 VolumeNumber(char *name)
4830 return atoi(name + 1);
4834 * compute the volume header filename.
4836 * @param[in] volumeId
4838 * @return volume header filename
4840 * @post volume header filename string is constructed
4842 * @warning this function is NOT re-entrant -- the returned string is
4843 * stored in a static char array. see VolumeExternalName_r
4844 * for a re-entrant equivalent.
4846 * @see VolumeExternalName_r
4848 * @deprecated due to the above re-entrancy warning, this interface should
4849 * be considered deprecated. Please use VolumeExternalName_r
4853 VolumeExternalName(VolumeId volumeId)
4855 static char name[VMAXPATHLEN];
4856 (void)afs_snprintf(name, sizeof name, VFORMAT, volumeId);
4861 * compute the volume header filename.
4863 * @param[in] volumeId
4864 * @param[inout] name array in which to store filename
4865 * @param[in] len length of name array
4867 * @return result code from afs_snprintf
4869 * @see VolumeExternalName
4872 * @note re-entrant equivalent of VolumeExternalName
4874 * @internal volume package internal use only.
4877 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
4879 return afs_snprintf(name, len, VFORMAT, volumeId);
4883 /***************************************************/
4884 /* Volume Usage Statistics routines */
4885 /***************************************************/
4887 #if OPENAFS_VOL_STATS
4888 #define OneDay (86400) /* 24 hours' worth of seconds */
4890 #define OneDay (24*60*60) /* 24 hours */
4891 #endif /* OPENAFS_VOL_STATS */
4893 #define Midnight(date) ((date-TimeZoneCorrection)/OneDay*OneDay+TimeZoneCorrection)
4895 /*------------------------------------------------------------------------
4896 * [export] VAdjustVolumeStatistics
4899 * If we've passed midnight, we need to update all the day use
4900 * statistics as well as zeroing the detailed volume statistics
4901 * (if we are implementing them).
4904 * vp : Pointer to the volume structure describing the lucky
4905 * volume being considered for update.
4911 * Nothing interesting.
4915 *------------------------------------------------------------------------*/
4918 VAdjustVolumeStatistics_r(register Volume * vp)
4920 unsigned int now = FT_ApproxTime();
4922 if (now - V_dayUseDate(vp) > OneDay) {
4923 register int ndays, i;
4925 ndays = (now - V_dayUseDate(vp)) / OneDay;
4926 for (i = 6; i > ndays - 1; i--)
4927 V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
4928 for (i = 0; i < ndays - 1 && i < 7; i++)
4929 V_weekUse(vp)[i] = 0;
4931 V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
4933 V_dayUseDate(vp) = Midnight(now);
4935 #if OPENAFS_VOL_STATS
4937 * All we need to do is bzero the entire VOL_STATS_BYTES of
4938 * the detailed volume statistics area.
4940 memset((char *)(V_stat_area(vp)), 0, VOL_STATS_BYTES);
4941 #endif /* OPENAFS_VOL_STATS */
4944 /*It's been more than a day of collection */
4946 * Always return happily.
4949 } /*VAdjustVolumeStatistics */
4952 VAdjustVolumeStatistics(register Volume * vp)
4956 retVal = VAdjustVolumeStatistics_r(vp);
4962 VBumpVolumeUsage_r(register Volume * vp)
4964 unsigned int now = FT_ApproxTime();
4965 if (now - V_dayUseDate(vp) > OneDay)
4966 VAdjustVolumeStatistics_r(vp);
4968 * Save the volume header image to disk after every 128 bumps to dayUse.
4970 if ((V_dayUse(vp)++ & 127) == 0) {
4972 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
4977 VBumpVolumeUsage(register Volume * vp)
4980 VBumpVolumeUsage_r(vp);
4985 VSetDiskUsage_r(void)
4987 #ifndef AFS_DEMAND_ATTACH_FS
4988 static int FifteenMinuteCounter = 0;
4992 /* NOTE: Don't attempt to access the partitions list until the
4993 * initialization level indicates that all volumes are attached,
4994 * which implies that all partitions are initialized. */
4995 #ifdef AFS_PTHREAD_ENV
4997 #else /* AFS_PTHREAD_ENV */
4999 #endif /* AFS_PTHREAD_ENV */
5002 VResetDiskUsage_r();
5004 #ifndef AFS_DEMAND_ATTACH_FS
5005 if (++FifteenMinuteCounter == 3) {
5006 FifteenMinuteCounter = 0;
5009 #endif /* !AFS_DEMAND_ATTACH_FS */
5021 /***************************************************/
5022 /* Volume Update List routines */
5023 /***************************************************/
5025 /* The number of minutes that a volume hasn't been updated before the
5026 * "Dont salvage" flag in the volume header will be turned on */
5027 #define SALVAGE_INTERVAL (10*60)
5032 * volume update list functionality has been moved into the VLRU
5033 * the DONT_SALVAGE flag is now set during VLRU demotion
5036 #ifndef AFS_DEMAND_ATTACH_FS
5037 static VolumeId *UpdateList = NULL; /* Pointer to array of Volume ID's */
5038 static int nUpdatedVolumes = 0; /* Updated with entry in UpdateList, salvage after crash flag on */
5039 static int updateSize = 0; /* number of entries possible */
5040 #define UPDATE_LIST_SIZE 128 /* initial size increment (must be a power of 2!) */
5041 #endif /* !AFS_DEMAND_ATTACH_FS */
5044 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
5047 vp->updateTime = FT_ApproxTime();
5048 if (V_dontSalvage(vp) == 0)
5050 V_dontSalvage(vp) = 0;
5051 VSyncVolume_r(ec, vp, 0);
5052 #ifdef AFS_DEMAND_ATTACH_FS
5053 V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
5054 #else /* !AFS_DEMAND_ATTACH_FS */
5057 if (UpdateList == NULL) {
5058 updateSize = UPDATE_LIST_SIZE;
5059 UpdateList = (VolumeId *) malloc(sizeof(VolumeId) * updateSize);
5061 if (nUpdatedVolumes == updateSize) {
5063 if (updateSize > 524288) {
5064 Log("warning: there is likely a bug in the volume update scanner\n");
5068 (VolumeId *) realloc(UpdateList,
5069 sizeof(VolumeId) * updateSize);
5072 assert(UpdateList != NULL);
5073 UpdateList[nUpdatedVolumes++] = V_id(vp);
5074 #endif /* !AFS_DEMAND_ATTACH_FS */
5077 #ifndef AFS_DEMAND_ATTACH_FS
5079 VScanUpdateList(void)
5081 register int i, gap;
5082 register Volume *vp;
5084 afs_uint32 now = FT_ApproxTime();
5085 /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
5086 for (i = gap = 0; i < nUpdatedVolumes; i++) {
5088 UpdateList[i - gap] = UpdateList[i];
5090 /* XXX this routine needlessly messes up the Volume LRU by
5091 * breaking the LRU temporal-locality assumptions.....
5092 * we should use a special volume header allocator here */
5093 vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
5096 } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
5097 V_dontSalvage(vp) = DONT_SALVAGE;
5098 VUpdateVolume_r(&error, vp, 0); /* No need to fsync--not critical */
5106 #ifndef AFS_PTHREAD_ENV
5108 #endif /* !AFS_PTHREAD_ENV */
5110 nUpdatedVolumes -= gap;
5112 #endif /* !AFS_DEMAND_ATTACH_FS */
5115 /***************************************************/
5116 /* Volume LRU routines */
5117 /***************************************************/
5122 * with demand attach fs, we attempt to soft detach(1)
5123 * volumes which have not been accessed in a long time
5124 * in order to speed up fileserver shutdown
5126 * (1) by soft detach we mean a process very similar
5127 * to VOffline, except the final state of the
5128 * Volume will be VOL_STATE_PREATTACHED, instead
5129 * of the usual VOL_STATE_UNATTACHED
5131 #ifdef AFS_DEMAND_ATTACH_FS
5133 /* implementation is reminiscent of a generational GC
5135 * queue 0 is newly attached volumes. this queue is
5136 * sorted by attach timestamp
5138 * queue 1 is volumes that have been around a bit
5139 * longer than queue 0. this queue is sorted by
5142 * queue 2 is volumes tha have been around the longest.
5143 * this queue is unsorted
5145 * queue 3 is volumes that have been marked as
5146 * candidates for soft detachment. this queue is
5149 #define VLRU_GENERATIONS 3 /**< number of generations in VLRU */
5150 #define VLRU_QUEUES 5 /**< total number of VLRU queues */
5153 * definition of a VLRU queue.
5156 volatile struct rx_queue q;
5163 * main VLRU data structure.
5166 struct VLRU_q q[VLRU_QUEUES]; /**< VLRU queues */
5169 /** time interval (in seconds) between promotion passes for
5170 * each young generation queue. */
5171 afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
5173 /** time interval (in seconds) between soft detach candidate
5174 * scans for each generation queue.
5176 * scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
5177 * we perform a soft detach pass. */
5178 afs_uint32 scan_interval[VLRU_GENERATIONS+1];
5180 /* scheduler state */
5181 int next_idx; /**< next queue to receive attention */
5182 afs_uint32 last_promotion[VLRU_GENERATIONS-1]; /**< timestamp of last promotion scan */
5183 afs_uint32 last_scan[VLRU_GENERATIONS+1]; /**< timestamp of last detach scan */
5185 int scanner_state; /**< state of scanner thread */
5186 pthread_cond_t cv; /**< state transition CV */
5189 /** global VLRU state */
5190 static struct VLRU volume_LRU;
5193 * defined states for VLRU scanner thread.
5196 VLRU_SCANNER_STATE_OFFLINE = 0, /**< vlru scanner thread is offline */
5197 VLRU_SCANNER_STATE_ONLINE = 1, /**< vlru scanner thread is online */
5198 VLRU_SCANNER_STATE_SHUTTING_DOWN = 2, /**< vlru scanner thread is shutting down */
5199 VLRU_SCANNER_STATE_PAUSING = 3, /**< vlru scanner thread is getting ready to pause */
5200 VLRU_SCANNER_STATE_PAUSED = 4 /**< vlru scanner thread is paused */
5201 } vlru_thread_state_t;
5203 /* vlru disk data header stuff */
5204 #define VLRU_DISK_MAGIC 0x7a8b9cad /**< vlru disk entry magic number */
5205 #define VLRU_DISK_VERSION 1 /**< vlru disk entry version number */
5207 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
5208 #define VLRU_DUMP_EXPIRATION_TIME (60*60*24*7) /* expire vlru data after 1 week */
5211 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
5212 * soft detachment. */
5213 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
5215 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
5216 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
5218 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
5219 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
5221 /** VLRU control flag. non-zero value implies VLRU subsystem is activated. */
5222 static afs_uint32 VLRU_enabled = 1;
5224 /* queue synchronization routines */
5225 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
5226 static void VLRU_EndExclusive_r(struct VLRU_q * q);
5227 static void VLRU_Wait_r(struct VLRU_q * q);
5230 * set VLRU subsystem tunable parameters.
5232 * @param[in] option tunable option to modify
5233 * @param[in] val new value for tunable parameter
5235 * @pre @c VInitVolumePackage has not yet been called.
5237 * @post tunable parameter is modified
5241 * @note valid option parameters are:
5242 * @arg @c VLRU_SET_THRESH
5243 * set the period of inactivity after which
5244 * volumes are eligible for soft detachment
5245 * @arg @c VLRU_SET_INTERVAL
5246 * set the time interval between calls
5247 * to the volume LRU "garbage collector"
5248 * @arg @c VLRU_SET_MAX
5249 * set the max number of volumes to deallocate
5253 VLRU_SetOptions(int option, afs_uint32 val)
5255 if (option == VLRU_SET_THRESH) {
5256 VLRU_offline_thresh = val;
5257 } else if (option == VLRU_SET_INTERVAL) {
5258 VLRU_offline_interval = val;
5259 } else if (option == VLRU_SET_MAX) {
5260 VLRU_offline_max = val;
5261 } else if (option == VLRU_SET_ENABLED) {
5264 VLRU_ComputeConstants();
5268 * compute VLRU internal timing parameters.
5270 * @post VLRU scanner thread internal timing parameters are computed
5272 * @note computes internal timing parameters based upon user-modifiable
5273 * tunable parameters.
5277 * @internal volume package internal use only.
5280 VLRU_ComputeConstants(void)
5282 afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
5284 /* compute the candidate scan interval */
5285 volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
5287 /* compute the promotion intervals */
5288 volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
5289 volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
5292 /* compute the gen 0 scan interval */
5293 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
5295 /* compute the gen 0 scan interval */
5296 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
5301 * initialize VLRU subsystem.
5303 * @pre this function has not yet been called
5305 * @post VLRU subsystem is initialized and VLRU scanner thread is starting
5309 * @internal volume package internal use only.
5315 pthread_attr_t attrs;
5318 if (!VLRU_enabled) {
5319 Log("VLRU: disabled\n");
5323 /* initialize each of the VLRU queues */
5324 for (i = 0; i < VLRU_QUEUES; i++) {
5325 queue_Init(&volume_LRU.q[i]);
5326 volume_LRU.q[i].len = 0;
5327 volume_LRU.q[i].busy = 0;
5328 assert(pthread_cond_init(&volume_LRU.q[i].cv, NULL) == 0);
5331 /* setup the timing constants */
5332 VLRU_ComputeConstants();
5334 /* XXX put inside LogLevel check? */
5335 Log("VLRU: starting scanner with the following configuration parameters:\n");
5336 Log("VLRU: offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
5337 Log("VLRU: running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
5338 Log("VLRU: taking up to %d volumes offline per pass\n", VLRU_offline_max);
5339 Log("VLRU: scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
5340 Log("VLRU: scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
5341 Log("VLRU: scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
5343 /* start up the VLRU scanner */
5344 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
5345 if (programType == fileServer) {
5346 assert(pthread_cond_init(&volume_LRU.cv, NULL) == 0);
5347 assert(pthread_attr_init(&attrs) == 0);
5348 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
5349 assert(pthread_create(&tid, &attrs, &VLRU_ScannerThread, NULL) == 0);
5354 * initialize the VLRU-related fields of a newly allocated volume object.
5356 * @param[in] vp pointer to volume object
5359 * @arg @c VOL_LOCK is held.
5360 * @arg volume object is not on a VLRU queue.
5362 * @post VLRU fields are initialized to indicate that volume object is not
5363 * currently registered with the VLRU subsystem
5367 * @internal volume package interal use only.
5370 VLRU_Init_Node_r(volatile Volume * vp)
5375 assert(queue_IsNotOnQueue(&vp->vlru));
5376 vp->vlru.idx = VLRU_QUEUE_INVALID;
5380 * add a volume object to a VLRU queue.
5382 * @param[in] vp pointer to volume object
5385 * @arg @c VOL_LOCK is held.
5386 * @arg caller MUST hold a lightweight ref on @p vp.
5387 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
5389 * @post the volume object is added to the appropriate VLRU queue
5391 * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
5392 * then the volume is added to that queue. Otherwise, the value
5393 * @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
5394 * volume is added to the NEW generation queue.
5396 * @note @c VOL_LOCK may be dropped internally
5398 * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
5399 * during the add operation, and is restored to the previous
5400 * state prior to return.
5404 * @internal volume package internal use only.
5407 VLRU_Add_r(volatile Volume * vp)
5410 VolState state_save;
5415 if (queue_IsOnQueue(&vp->vlru))
5418 state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
5421 if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
5422 idx = VLRU_QUEUE_NEW;
5425 VLRU_Wait_r(&volume_LRU.q[idx]);
5427 /* repeat check since VLRU_Wait_r may have dropped
5429 if (queue_IsNotOnQueue(&vp->vlru)) {
5431 queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
5432 volume_LRU.q[idx].len++;
5433 V_attachFlags(vp) |= VOL_ON_VLRU;
5434 vp->stats.last_promote = FT_ApproxTime();
5437 VChangeState_r(vp, state_save);
5441 * delete a volume object from a VLRU queue.
5443 * @param[in] vp pointer to volume object
5446 * @arg @c VOL_LOCK is held.
5447 * @arg caller MUST hold a lightweight ref on @p vp.
5448 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
5450 * @post volume object is removed from the VLRU queue
5452 * @note @c VOL_LOCK may be dropped internally
5456 * @todo We should probably set volume state to something exlcusive
5457 * (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
5459 * @internal volume package internal use only.
5462 VLRU_Delete_r(volatile Volume * vp)
5469 if (queue_IsNotOnQueue(&vp->vlru))
5475 if (idx == VLRU_QUEUE_INVALID)
5477 VLRU_Wait_r(&volume_LRU.q[idx]);
5478 } while (idx != vp->vlru.idx);
5480 /* now remove from the VLRU and update
5481 * the appropriate counter */
5482 queue_Remove(&vp->vlru);
5483 volume_LRU.q[idx].len--;
5484 vp->vlru.idx = VLRU_QUEUE_INVALID;
5485 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
5489 * tell the VLRU subsystem that a volume was just accessed.
5491 * @param[in] vp pointer to volume object
5494 * @arg @c VOL_LOCK is held
5495 * @arg caller MUST hold a lightweight ref on @p vp
5496 * @arg caller MUST NOT hold exclusive ownership of any VLRU queue
5498 * @post volume VLRU access statistics are updated. If the volume was on
5499 * the VLRU soft detach candidate queue, it is moved to the NEW
5502 * @note @c VOL_LOCK may be dropped internally
5506 * @internal volume package internal use only.
5509 VLRU_UpdateAccess_r(volatile Volume * vp)
5511 afs_uint32 live_interval;
5512 Volume * rvp = NULL;
5517 if (queue_IsNotOnQueue(&vp->vlru))
5520 assert(V_attachFlags(vp) & VOL_ON_VLRU);
5522 /* update the access timestamp */
5523 vp->stats.last_get = FT_ApproxTime();
5526 * if the volume is on the soft detach candidate
5527 * list, we need to safely move it back to a
5528 * regular generation. this has to be done
5529 * carefully so we don't race against the scanner
5533 /* if this volume is on the soft detach candidate queue,
5534 * then grab exclusive access to the necessary queues */
5535 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
5537 VCreateReservation_r(rvp);
5539 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
5540 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
5541 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5542 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5545 /* make sure multiple threads don't race to update */
5546 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
5547 VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
5551 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5552 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
5553 VCancelReservation_r(rvp);
5558 * switch a volume between two VLRU queues.
5560 * @param[in] vp pointer to volume object
5561 * @param[in] new_idx index of VLRU queue onto which the volume will be moved
5562 * @param[in] append controls whether the volume will be appended or
5563 * prepended to the queue. A nonzero value means it will
5564 * be appended; zero means it will be prepended.
5566 * @pre The new (and old, if applicable) queue(s) must either be owned
5567 * exclusively by the calling thread for asynchronous manipulation,
5568 * or the queue(s) must be quiescent and VOL_LOCK must be held.
5569 * Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
5570 * for further details of the queue asynchronous processing mechanism.
5572 * @post If the volume object was already on a VLRU queue, it is
5573 * removed from the queue. Depending on the value of the append
5574 * parameter, the volume object is either appended or prepended
5575 * to the VLRU queue referenced by the new_idx parameter.
5579 * @see VLRU_BeginExclusive_r
5580 * @see VLRU_EndExclusive_r
5583 * @internal volume package internal use only.
5586 VLRU_SwitchQueues(volatile Volume * vp, int new_idx, int append)
5588 if (queue_IsNotOnQueue(&vp->vlru))
5591 queue_Remove(&vp->vlru);
5592 volume_LRU.q[vp->vlru.idx].len--;
5594 /* put the volume back on the correct generational queue */
5596 queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
5598 queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
5601 volume_LRU.q[new_idx].len++;
5602 vp->vlru.idx = new_idx;
5606 * VLRU background thread.
5608 * The VLRU Scanner Thread is responsible for periodically scanning through
5609 * each VLRU queue looking for volumes which should be moved to another
5610 * queue, or soft detached.
5612 * @param[in] args unused thread arguments parameter
5614 * @return unused thread return value
5615 * @retval NULL always
5617 * @internal volume package internal use only.
5620 VLRU_ScannerThread(void * args)
5622 afs_uint32 now, min_delay, delay;
5623 afs_uint32 next_scan[VLRU_GENERATIONS];
5624 afs_uint32 next_promotion[VLRU_GENERATIONS];
5625 int i, min_idx, min_op, overdue, state;
5627 /* set t=0 for promotion cycle to be
5628 * fileserver startup */
5629 now = FT_ApproxTime();
5630 for (i=0; i < VLRU_GENERATIONS-1; i++) {
5631 volume_LRU.last_promotion[i] = now;
5634 /* don't start the scanner until VLRU_offline_thresh
5635 * plus a small delay for VInitVolumePackage to finish
5638 sleep(VLRU_offline_thresh + 60);
5640 /* set t=0 for scan cycle to be now */
5641 now = FT_ApproxTime();
5642 for (i=0; i < VLRU_GENERATIONS+1; i++) {
5643 volume_LRU.last_scan[i] = now;
5647 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
5648 volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
5651 while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
5652 /* check to see if we've been asked to pause */
5653 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
5654 volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
5655 assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
5657 VOL_CV_WAIT(&volume_LRU.cv);
5658 } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
5661 /* scheduling can happen outside the glock */
5664 /* figure out what is next on the schedule */
5666 /* figure out a potential schedule for the new generation first */
5668 min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
5671 if (min_delay > volume_LRU.scan_interval[0]) {
5672 /* unsigned overflow -- we're overdue to run this scan */
5677 /* if we're not overdue for gen 0, figure out schedule for candidate gen */
5679 i = VLRU_QUEUE_CANDIDATE;
5680 delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
5681 if (delay < min_delay) {
5685 if (delay > volume_LRU.scan_interval[i]) {
5686 /* unsigned overflow -- we're overdue to run this scan */
5693 /* if we're still not overdue for something, figure out schedules for promotions */
5694 for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
5695 delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
5696 if (delay < min_delay) {
5701 if (delay > volume_LRU.promotion_interval[i]) {
5702 /* unsigned overflow -- we're overdue to run this promotion */
5711 /* sleep as needed */
5716 /* do whatever is next */
5719 VLRU_Promote_r(min_idx);
5720 VLRU_Demote_r(min_idx+1);
5722 VLRU_Scan_r(min_idx);
5724 now = FT_ApproxTime();
5727 Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
5729 /* signal that scanner is down */
5730 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
5731 assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
5737 * promote volumes from one VLRU generation to the next.
5739 * This routine scans a VLRU generation looking for volumes which are
5740 * eligible to be promoted to the next generation. All volumes which
5741 * meet the eligibility requirement are promoted.
5743 * Promotion eligibility is based upon meeting both of the following
5746 * @arg The volume has been accessed since the last promotion:
5747 * @c (vp->stats.last_get >= vp->stats.last_promote)
5748 * @arg The last promotion occurred at least
5749 * @c volume_LRU.promotion_interval[idx] seconds ago
5751 * As a performance optimization, promotions are "globbed". In other
5752 * words, we promote arbitrarily large contiguous sublists of elements
5755 * @param[in] idx VLRU queue index to scan
5759 * @internal VLRU internal use only.
5762 VLRU_Promote_r(int idx)
5764 int len, chaining, promote;
5765 afs_uint32 now, thresh;
5766 struct rx_queue *qp, *nqp;
5767 Volume * vp, *start, *end;
5769 /* get exclusive access to two chains, and drop the glock */
5770 VLRU_Wait_r(&volume_LRU.q[idx]);
5771 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
5772 VLRU_Wait_r(&volume_LRU.q[idx+1]);
5773 VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
5776 thresh = volume_LRU.promotion_interval[idx];
5777 now = FT_ApproxTime();
5780 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
5781 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
5782 promote = (((vp->stats.last_promote + thresh) <= now) &&
5783 (vp->stats.last_get >= vp->stats.last_promote));
5791 /* promote and prepend chain */
5792 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
5806 /* promote and prepend */
5807 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
5811 volume_LRU.q[idx].len -= len;
5812 volume_LRU.q[idx+1].len += len;
5815 /* release exclusive access to the two chains */
5817 volume_LRU.last_promotion[idx] = now;
5818 VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
5819 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
5822 /* run the demotions */
5824 VLRU_Demote_r(int idx)
5827 int len, chaining, demote;
5828 afs_uint32 now, thresh;
5829 struct rx_queue *qp, *nqp;
5830 Volume * vp, *start, *end;
5831 Volume ** salv_flag_vec = NULL;
5832 int salv_vec_offset = 0;
5834 assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
5836 /* get exclusive access to two chains, and drop the glock */
5837 VLRU_Wait_r(&volume_LRU.q[idx-1]);
5838 VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
5839 VLRU_Wait_r(&volume_LRU.q[idx]);
5840 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
5843 /* no big deal if this allocation fails */
5844 if (volume_LRU.q[idx].len) {
5845 salv_flag_vec = (Volume **) malloc(volume_LRU.q[idx].len * sizeof(Volume *));
5848 now = FT_ApproxTime();
5849 thresh = volume_LRU.promotion_interval[idx-1];
5852 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
5853 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
5854 demote = (((vp->stats.last_promote + thresh) <= now) &&
5855 (vp->stats.last_get < (now - thresh)));
5857 /* we now do volume update list DONT_SALVAGE flag setting during
5858 * demotion passes */
5859 if (salv_flag_vec &&
5860 !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
5862 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
5863 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
5864 salv_flag_vec[salv_vec_offset++] = vp;
5865 VCreateReservation_r(vp);
5874 /* demote and append chain */
5875 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
5889 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
5893 volume_LRU.q[idx].len -= len;
5894 volume_LRU.q[idx-1].len += len;
5897 /* release exclusive access to the two chains */
5899 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
5900 VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
5902 /* now go back and set the DONT_SALVAGE flags as appropriate */
5903 if (salv_flag_vec) {
5905 for (i = 0; i < salv_vec_offset; i++) {
5906 vp = salv_flag_vec[i];
5907 if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
5908 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
5909 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
5912 V_attachFlags(vp) |= VOL_HDR_DONTSALV;
5913 V_dontSalvage(vp) = DONT_SALVAGE;
5914 VUpdateVolume_r(&ec, vp, 0);
5918 VCancelReservation_r(vp);
5920 free(salv_flag_vec);
5924 /* run a pass of the VLRU GC scanner */
5926 VLRU_Scan_r(int idx)
5928 afs_uint32 now, thresh;
5929 struct rx_queue *qp, *nqp;
5930 volatile Volume * vp;
5933 assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
5935 /* gain exclusive access to the idx VLRU */
5936 VLRU_Wait_r(&volume_LRU.q[idx]);
5937 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
5939 if (idx != VLRU_QUEUE_CANDIDATE) {
5940 /* gain exclusive access to the candidate VLRU */
5941 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5942 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5945 now = FT_ApproxTime();
5946 thresh = now - VLRU_offline_thresh;
5948 /* perform candidate selection and soft detaching */
5949 if (idx == VLRU_QUEUE_CANDIDATE) {
5950 /* soft detach some volumes from the candidate pool */
5954 for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
5955 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
5956 if (i >= VLRU_offline_max) {
5959 /* check timestamp to see if it's a candidate for soft detaching */
5960 if (vp->stats.last_get <= thresh) {
5962 if (VCheckSoftDetach(vp, thresh))
5968 /* scan for volumes to become soft detach candidates */
5969 for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
5970 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
5972 /* check timestamp to see if it's a candidate for soft detaching */
5973 if (vp->stats.last_get <= thresh) {
5974 VCheckSoftDetachCandidate(vp, thresh);
5977 if (!(i&0x7f)) { /* lock coarsening optimization */
5985 /* relinquish exclusive access to the VLRU chains */
5989 volume_LRU.last_scan[idx] = now;
5990 if (idx != VLRU_QUEUE_CANDIDATE) {
5991 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5993 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
5996 /* check whether volume is safe to soft detach
5997 * caller MUST NOT hold a ref count on vp */
5999 VCheckSoftDetach(volatile Volume * vp, afs_uint32 thresh)
6003 if (vp->nUsers || vp->nWaiters)
6006 if (vp->stats.last_get <= thresh) {
6007 ret = VSoftDetachVolume_r(vp, thresh);
6013 /* check whether volume should be made a
6014 * soft detach candidate */
6016 VCheckSoftDetachCandidate(volatile Volume * vp, afs_uint32 thresh)
6019 if (vp->nUsers || vp->nWaiters)
6024 assert(idx == VLRU_QUEUE_NEW);
6026 if (vp->stats.last_get <= thresh) {
6027 /* move to candidate pool */
6028 queue_Remove(&vp->vlru);
6029 volume_LRU.q[VLRU_QUEUE_NEW].len--;
6030 queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
6031 vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
6032 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
6040 /* begin exclusive access on VLRU */
6042 VLRU_BeginExclusive_r(struct VLRU_q * q)
6044 assert(q->busy == 0);
6048 /* end exclusive access on VLRU */
6050 VLRU_EndExclusive_r(struct VLRU_q * q)
6054 assert(pthread_cond_broadcast(&q->cv) == 0);
6057 /* wait for another thread to end exclusive access on VLRU */
6059 VLRU_Wait_r(struct VLRU_q * q)
6062 VOL_CV_WAIT(&q->cv);
6067 * volume soft detach
6069 * caller MUST NOT hold a ref count on vp */
6071 VSoftDetachVolume_r(volatile Volume * vp, afs_uint32 thresh)
6076 assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
6078 ts_save = vp->stats.last_get;
6079 if (ts_save > thresh)
6082 if (vp->nUsers || vp->nWaiters)
6085 if (VIsExclusiveState(V_attachState(vp))) {
6089 switch (V_attachState(vp)) {
6090 case VOL_STATE_UNATTACHED:
6091 case VOL_STATE_PREATTACHED:
6092 case VOL_STATE_ERROR:
6093 case VOL_STATE_GOING_OFFLINE:
6094 case VOL_STATE_SHUTTING_DOWN:
6095 case VOL_STATE_SALVAGING:
6096 volume_LRU.q[vp->vlru.idx].len--;
6098 /* create and cancel a reservation to
6099 * give the volume an opportunity to
6101 VCreateReservation_r(vp);
6102 queue_Remove(&vp->vlru);
6103 vp->vlru.idx = VLRU_QUEUE_INVALID;
6104 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
6105 VCancelReservation_r(vp);
6109 /* hold the volume and take it offline.
6110 * no need for reservations, as VHold_r
6111 * takes care of that internally. */
6112 if (VHold_r(vp) == 0) {
6113 /* vhold drops the glock, so now we should
6114 * check to make sure we aren't racing against
6115 * other threads. if we are racing, offlining vp
6116 * would be wasteful, and block the scanner for a while
6120 (vp->shuttingDown) ||
6121 (vp->goingOffline) ||
6122 (vp->stats.last_get != ts_save)) {
6123 /* looks like we're racing someone else. bail */
6127 /* pull it off the VLRU */
6128 assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
6129 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
6130 queue_Remove(&vp->vlru);
6131 vp->vlru.idx = VLRU_QUEUE_INVALID;
6132 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
6134 /* take if offline */
6135 VOffline_r(vp, "volume has been soft detached");
6137 /* invalidate the volume header cache */
6138 FreeVolumeHeader(vp);
6141 IncUInt64(&VStats.soft_detaches);
6142 vp->stats.soft_detaches++;
6144 /* put in pre-attached state so demand
6145 * attacher can work on it */
6146 VChangeState_r(vp, VOL_STATE_PREATTACHED);
6152 #endif /* AFS_DEMAND_ATTACH_FS */
6155 /***************************************************/
6156 /* Volume Header Cache routines */
6157 /***************************************************/
6160 * volume header cache.
6162 struct volume_hdr_LRU_t volume_hdr_LRU;
6165 * initialize the volume header cache.
6167 * @param[in] howMany number of header cache entries to preallocate
6169 * @pre VOL_LOCK held. Function has never been called before.
6171 * @post howMany cache entries are allocated, initialized, and added
6172 * to the LRU list. Header cache statistics are initialized.
6174 * @note only applicable to fileServer program type. Should only be
6175 * called once during volume package initialization.
6177 * @internal volume package internal use only.
6180 VInitVolumeHeaderCache(afs_uint32 howMany)
6182 register struct volHeader *hp;
6183 if (programType != fileServer)
6185 queue_Init(&volume_hdr_LRU);
6186 volume_hdr_LRU.stats.free = 0;
6187 volume_hdr_LRU.stats.used = howMany;
6188 volume_hdr_LRU.stats.attached = 0;
6189 hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
6193 /* We are using ReleaseVolumeHeader to initialize the values on the header list
6194 * to ensure they have the right values
6196 ReleaseVolumeHeader(hp++);
6200 * get a volume header and attach it to the volume object.
6202 * @param[in] vp pointer to volume object
6204 * @return cache entry status
6205 * @retval 0 volume header was newly attached; cache data is invalid
6206 * @retval 1 volume header was previously attached; cache data is valid
6208 * @pre VOL_LOCK held. For DAFS, lightweight ref must be held on volume object.
6210 * @post volume header attached to volume object. if necessary, header cache
6211 * entry on LRU is synchronized to disk. Header is removed from LRU list.
6213 * @note VOL_LOCK may be dropped
6215 * @warning this interface does not load header data from disk. it merely
6216 * attaches a header object to the volume object, and may sync the old
6217 * header cache data out to disk in the process.
6219 * @internal volume package internal use only.
6222 GetVolumeHeader(register Volume * vp)
6225 register struct volHeader *hd;
6227 static int everLogged = 0;
6229 #ifdef AFS_DEMAND_ATTACH_FS
6230 VolState vp_save, back_save;
6232 /* XXX debug 9/19/05 we've apparently got
6233 * a ref counting bug somewhere that's
6234 * breaking the nUsers == 0 => header on LRU
6236 if (vp->header && queue_IsNotOnQueue(vp->header)) {
6237 Log("nUsers == 0, but header not on LRU\n");
6242 old = (vp->header != NULL); /* old == volume already has a header */
6244 if (programType != fileServer) {
6245 /* for volume utilities, we allocate volHeaders as needed */
6247 hd = (struct volHeader *)calloc(1, sizeof(*vp->header));
6251 #ifdef AFS_DEMAND_ATTACH_FS
6252 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
6256 /* for the fileserver, we keep a volume header cache */
6258 /* the header we previously dropped in the lru is
6259 * still available. pull it off the lru and return */
6262 assert(hd->back == vp);
6264 /* we need to grab a new element off the LRU */
6265 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
6266 /* grab an element and pull off of LRU */
6267 hd = queue_First(&volume_hdr_LRU, volHeader);
6270 /* LRU is empty, so allocate a new volHeader
6271 * this is probably indicative of a leak, so let the user know */
6272 hd = (struct volHeader *)calloc(1, sizeof(struct volHeader));
6275 Log("****Allocated more volume headers, probably leak****\n");
6278 volume_hdr_LRU.stats.free++;
6281 /* this header used to belong to someone else.
6282 * we'll need to check if the header needs to
6283 * be sync'd out to disk */
6285 #ifdef AFS_DEMAND_ATTACH_FS
6286 /* if hd->back were in an exclusive state, then
6287 * its volHeader would not be on the LRU... */
6288 assert(!VIsExclusiveState(V_attachState(hd->back)));
6291 if (hd->diskstuff.inUse) {
6292 /* volume was in use, so we'll need to sync
6293 * its header to disk */
6295 #ifdef AFS_DEMAND_ATTACH_FS
6296 back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
6297 vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
6298 VCreateReservation_r(hd->back);
6302 WriteVolumeHeader_r(&error, hd->back);
6303 /* Ignore errors; catch them later */
6305 #ifdef AFS_DEMAND_ATTACH_FS
6310 hd->back->header = NULL;
6311 #ifdef AFS_DEMAND_ATTACH_FS
6312 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
6314 if (hd->diskstuff.inUse) {
6315 VChangeState_r(hd->back, back_save);
6316 VCancelReservation_r(hd->back);
6317 VChangeState_r(vp, vp_save);
6321 volume_hdr_LRU.stats.attached++;
6325 #ifdef AFS_DEMAND_ATTACH_FS
6326 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
6329 volume_hdr_LRU.stats.free--;
6330 volume_hdr_LRU.stats.used++;
6332 IncUInt64(&VStats.hdr_gets);
6333 #ifdef AFS_DEMAND_ATTACH_FS
6334 IncUInt64(&vp->stats.hdr_gets);
6335 vp->stats.last_hdr_get = FT_ApproxTime();
6342 * make sure volume header is attached and contains valid cache data.
6344 * @param[out] ec outbound error code
6345 * @param[in] vp pointer to volume object
6347 * @pre VOL_LOCK held. For DAFS, lightweight ref held on vp.
6349 * @post header cache entry attached, and loaded with valid data, or
6350 * *ec is nonzero, and the header is released back into the LRU.
6352 * @internal volume package internal use only.
6355 LoadVolumeHeader(Error * ec, Volume * vp)
6357 #ifdef AFS_DEMAND_ATTACH_FS
6358 VolState state_save;
6362 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
6363 IncUInt64(&VStats.hdr_loads);
6364 state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
6367 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
6368 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
6370 IncUInt64(&vp->stats.hdr_loads);
6371 now = FT_ApproxTime();
6375 V_attachFlags(vp) |= VOL_HDR_LOADED;
6376 vp->stats.last_hdr_load = now;
6378 VChangeState_r(vp, state_save);
6380 #else /* AFS_DEMAND_ATTACH_FS */
6382 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
6383 IncUInt64(&VStats.hdr_loads);
6385 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
6386 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
6389 #endif /* AFS_DEMAND_ATTACH_FS */
6391 /* maintain (nUsers==0) => header in LRU invariant */
6392 FreeVolumeHeader(vp);
6397 * release a header cache entry back into the LRU list.
6399 * @param[in] hd pointer to volume header cache object
6401 * @pre VOL_LOCK held.
6403 * @post header cache object appended onto end of LRU list.
6405 * @note only applicable to fileServer program type.
6407 * @note used to place a header cache entry back into the
6408 * LRU pool without invalidating it as a cache entry.
6410 * @internal volume package internal use only.
6413 ReleaseVolumeHeader(register struct volHeader *hd)
6415 if (programType != fileServer)
6417 if (!hd || queue_IsOnQueue(hd)) /* no header, or header already released */
6419 queue_Append(&volume_hdr_LRU, hd);
6420 #ifdef AFS_DEMAND_ATTACH_FS
6422 V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
6425 volume_hdr_LRU.stats.free++;
6426 volume_hdr_LRU.stats.used--;
6430 * free/invalidate a volume header cache entry.
6432 * @param[in] vp pointer to volume object
6434 * @pre VOL_LOCK is held.
6436 * @post For fileserver, header cache entry is returned to LRU, and it is
6437 * invalidated as a cache entry. For volume utilities, the header
6438 * cache entry is freed.
6440 * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
6441 * whenever it is necessary to invalidate the header cache entry.
6443 * @see ReleaseVolumeHeader
6445 * @internal volume package internal use only.
6448 FreeVolumeHeader(register Volume * vp)
6450 register struct volHeader *hd = vp->header;
6453 if (programType == fileServer) {
6454 ReleaseVolumeHeader(hd);
6459 #ifdef AFS_DEMAND_ATTACH_FS
6460 V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
6462 volume_hdr_LRU.stats.attached--;
6467 /***************************************************/
6468 /* Volume Hash Table routines */
6469 /***************************************************/
6472 * set size of volume object hash table.
6474 * @param[in] logsize log(2) of desired hash table size
6476 * @return operation status
6478 * @retval -1 failure
6480 * @pre MUST be called prior to VInitVolumePackage
6482 * @post Volume Hash Table will have 2^logsize buckets
6485 VSetVolHashSize(int logsize)
6487 /* 64 to 16384 hash buckets seems like a reasonable range */
6488 if ((logsize < 6 ) || (logsize > 14)) {
6493 VolumeHashTable.Size = 1 << logsize;
6494 VolumeHashTable.Mask = VolumeHashTable.Size - 1;
6496 /* we can't yet support runtime modification of this
6497 * parameter. we'll need a configuration rwlock to
6498 * make runtime modification feasible.... */
6505 * initialize dynamic data structures for volume hash table.
6507 * @post hash table is allocated, and fields are initialized.
6509 * @internal volume package internal use only.
6512 VInitVolumeHash(void)
6516 VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
6517 sizeof(VolumeHashChainHead));
6518 assert(VolumeHashTable.Table != NULL);
6520 for (i=0; i < VolumeHashTable.Size; i++) {
6521 queue_Init(&VolumeHashTable.Table[i]);
6522 #ifdef AFS_DEMAND_ATTACH_FS
6523 assert(pthread_cond_init(&VolumeHashTable.Table[i].chain_busy_cv, NULL) == 0);
6524 #endif /* AFS_DEMAND_ATTACH_FS */
6529 * add a volume object to the hash table.
6531 * @param[in] vp pointer to volume object
6532 * @param[in] hashid hash of volume id
6534 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
6537 * @post volume is added to hash chain.
6539 * @internal volume package internal use only.
6541 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
6542 * asynchronous hash chain reordering to finish.
6545 AddVolumeToHashTable(register Volume * vp, int hashid)
6547 VolumeHashChainHead * head;
6549 if (queue_IsOnQueue(vp))
6552 head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
6554 #ifdef AFS_DEMAND_ATTACH_FS
6555 /* wait for the hash chain to become available */
6558 V_attachFlags(vp) |= VOL_IN_HASH;
6559 vp->chainCacheCheck = ++head->cacheCheck;
6560 #endif /* AFS_DEMAND_ATTACH_FS */
6563 vp->hashid = hashid;
6564 queue_Append(head, vp);
6565 vp->vnodeHashOffset = VolumeHashOffset_r();
6569 * delete a volume object from the hash table.
6571 * @param[in] vp pointer to volume object
6573 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
6576 * @post volume is removed from hash chain.
6578 * @internal volume package internal use only.
6580 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
6581 * asynchronous hash chain reordering to finish.
6584 DeleteVolumeFromHashTable(register Volume * vp)
6586 VolumeHashChainHead * head;
6588 if (!queue_IsOnQueue(vp))
6591 head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
6593 #ifdef AFS_DEMAND_ATTACH_FS
6594 /* wait for the hash chain to become available */
6597 V_attachFlags(vp) &= ~(VOL_IN_HASH);
6599 #endif /* AFS_DEMAND_ATTACH_FS */
6603 /* do NOT reset hashid to zero, as the online
6604 * salvager package may need to know the volume id
6605 * after the volume is removed from the hash */
6609 * lookup a volume object in the hash table given a volume id.
6611 * @param[out] ec error code return
6612 * @param[in] volumeId volume id
6613 * @param[in] hint volume object which we believe could be the correct
6616 * @return volume object pointer
6617 * @retval NULL no such volume id is registered with the hash table.
6619 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
6622 * @post volume object with the given id is returned. volume object and
6623 * hash chain access statistics are updated. hash chain may have
6626 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
6627 * asynchronous hash chain reordering operation to finish, or
6628 * in order for us to perform an asynchronous chain reordering.
6630 * @note Hash chain reorderings occur when the access count for the
6631 * volume object being looked up exceeds the sum of the previous
6632 * node's (the node ahead of it in the hash chain linked list)
6633 * access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
6635 * @note For DAFS, the hint parameter allows us to short-circuit if the
6636 * cacheCheck fields match between the hash chain head and the
6637 * hint volume object.
6640 VLookupVolume_r(Error * ec, VolId volumeId, Volume * hint)
6642 register int looks = 0;
6643 Volume * vp, *np, *pp;
6644 VolumeHashChainHead * head;
6647 head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
6649 #ifdef AFS_DEMAND_ATTACH_FS
6650 /* wait for the hash chain to become available */
6653 /* check to see if we can short circuit without walking the hash chain */
6654 if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
6655 IncUInt64(&hint->stats.hash_short_circuits);
6658 #endif /* AFS_DEMAND_ATTACH_FS */
6660 /* someday we need to either do per-chain locks, RWlocks,
6661 * or both for volhash access.
6662 * (and move to a data structure with better cache locality) */
6664 /* search the chain for this volume id */
6665 for(queue_Scan(head, vp, np, Volume)) {
6667 if ((vp->hashid == volumeId)) {
6672 if (queue_IsEnd(head, vp)) {
6676 #ifdef AFS_DEMAND_ATTACH_FS
6677 /* update hash chain statistics */
6680 FillInt64(lks, 0, looks);
6681 AddUInt64(head->looks, lks, &head->looks);
6682 AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
6683 IncUInt64(&head->gets);
6688 IncUInt64(&vp->stats.hash_lookups);
6690 /* for demand attach fileserver, we permit occasional hash chain reordering
6691 * so that frequently looked up volumes move towards the head of the chain */
6692 pp = queue_Prev(vp, Volume);
6693 if (!queue_IsEnd(head, pp)) {
6694 FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
6695 AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
6696 if (GEInt64(vp->stats.hash_lookups, thresh)) {
6697 VReorderHash_r(head, pp, vp);
6701 /* update the short-circuit cache check */
6702 vp->chainCacheCheck = head->cacheCheck;
6704 #endif /* AFS_DEMAND_ATTACH_FS */
6709 #ifdef AFS_DEMAND_ATTACH_FS
6710 /* perform volume hash chain reordering.
6712 * advance a subchain beginning at vp ahead of
6713 * the adjacent subchain ending at pp */
6715 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
6717 Volume *tp, *np, *lp;
6718 afs_uint64 move_thresh;
6720 /* this should never be called if the chain is already busy, so
6721 * no need to wait for other exclusive chain ops to finish */
6723 /* this is a rather heavy set of operations,
6724 * so let's set the chain busy flag and drop
6726 VHashBeginExclusive_r(head);
6729 /* scan forward in the chain from vp looking for the last element
6730 * in the chain we want to advance */
6731 FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
6732 AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
6733 for(queue_ScanFrom(head, vp, tp, np, Volume)) {
6734 if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
6738 lp = queue_Prev(tp, Volume);
6740 /* scan backwards from pp to determine where to splice and
6741 * insert the subchain we're advancing */
6742 for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
6743 if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
6747 tp = queue_Next(tp, Volume);
6749 /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
6750 queue_MoveChainBefore(tp,vp,lp);
6753 IncUInt64(&VStats.hash_reorders);
6755 IncUInt64(&head->reorders);
6757 /* wake up any threads waiting for the hash chain */
6758 VHashEndExclusive_r(head);
6762 /* demand-attach fs volume hash
6763 * asynchronous exclusive operations */
6766 * begin an asynchronous exclusive operation on a volume hash chain.
6768 * @param[in] head pointer to volume hash chain head object
6770 * @pre VOL_LOCK held. hash chain is quiescent.
6772 * @post hash chain marked busy.
6774 * @note this interface is used in conjunction with VHashEndExclusive_r and
6775 * VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
6776 * volume hash chain. Its main use case is hash chain reordering, which
6777 * has the potential to be a highly latent operation.
6779 * @see VHashEndExclusive_r
6784 * @internal volume package internal use only.
6787 VHashBeginExclusive_r(VolumeHashChainHead * head)
6789 assert(head->busy == 0);
6794 * relinquish exclusive ownership of a volume hash chain.
6796 * @param[in] head pointer to volume hash chain head object
6798 * @pre VOL_LOCK held. thread owns the hash chain exclusively.
6800 * @post hash chain is marked quiescent. threads awaiting use of
6801 * chain are awakened.
6803 * @see VHashBeginExclusive_r
6808 * @internal volume package internal use only.
6811 VHashEndExclusive_r(VolumeHashChainHead * head)
6815 assert(pthread_cond_broadcast(&head->chain_busy_cv) == 0);
6819 * wait for all asynchronous operations on a hash chain to complete.
6821 * @param[in] head pointer to volume hash chain head object
6823 * @pre VOL_LOCK held.
6825 * @post hash chain object is quiescent.
6827 * @see VHashBeginExclusive_r
6828 * @see VHashEndExclusive_r
6832 * @note This interface should be called before any attempt to
6833 * traverse the hash chain. It is permissible for a thread
6834 * to gain exclusive access to the chain, and then perform
6835 * latent operations on the chain asynchronously wrt the
6838 * @warning if waiting is necessary, VOL_LOCK is dropped
6840 * @internal volume package internal use only.
6843 VHashWait_r(VolumeHashChainHead * head)
6845 while (head->busy) {
6846 VOL_CV_WAIT(&head->chain_busy_cv);
6849 #endif /* AFS_DEMAND_ATTACH_FS */
6852 /***************************************************/
6853 /* Volume by Partition List routines */
6854 /***************************************************/
6857 * demand attach fileserver adds a
6858 * linked list of volumes to each
6859 * partition object, thus allowing
6860 * for quick enumeration of all
6861 * volumes on a partition
6864 #ifdef AFS_DEMAND_ATTACH_FS
6866 * add a volume to its disk partition VByPList.
6868 * @param[in] vp pointer to volume object
6870 * @pre either the disk partition VByPList is owned exclusively
6871 * by the calling thread, or the list is quiescent and
6874 * @post volume is added to disk partition VByPList
6878 * @warning it is the caller's responsibility to ensure list
6881 * @see VVByPListWait_r
6882 * @see VVByPListBeginExclusive_r
6883 * @see VVByPListEndExclusive_r
6885 * @internal volume package internal use only.
6888 AddVolumeToVByPList_r(Volume * vp)
6890 if (queue_IsNotOnQueue(&vp->vol_list)) {
6891 queue_Append(&vp->partition->vol_list, &vp->vol_list);
6892 V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
6893 vp->partition->vol_list.len++;
6898 * delete a volume from its disk partition VByPList.
6900 * @param[in] vp pointer to volume object
6902 * @pre either the disk partition VByPList is owned exclusively
6903 * by the calling thread, or the list is quiescent and
6906 * @post volume is removed from the disk partition VByPList
6910 * @warning it is the caller's responsibility to ensure list
6913 * @see VVByPListWait_r
6914 * @see VVByPListBeginExclusive_r
6915 * @see VVByPListEndExclusive_r
6917 * @internal volume package internal use only.
6920 DeleteVolumeFromVByPList_r(Volume * vp)
6922 if (queue_IsOnQueue(&vp->vol_list)) {
6923 queue_Remove(&vp->vol_list);
6924 V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
6925 vp->partition->vol_list.len--;
6930 * begin an asynchronous exclusive operation on a VByPList.
6932 * @param[in] dp pointer to disk partition object
6934 * @pre VOL_LOCK held. VByPList is quiescent.
6936 * @post VByPList marked busy.
6938 * @note this interface is used in conjunction with VVByPListEndExclusive_r and
6939 * VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
6942 * @see VVByPListEndExclusive_r
6943 * @see VVByPListWait_r
6947 * @internal volume package internal use only.
6949 /* take exclusive control over the list */
6951 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
6953 assert(dp->vol_list.busy == 0);
6954 dp->vol_list.busy = 1;
6958 * relinquish exclusive ownership of a VByPList.
6960 * @param[in] dp pointer to disk partition object
6962 * @pre VOL_LOCK held. thread owns the VByPList exclusively.
6964 * @post VByPList is marked quiescent. threads awaiting use of
6965 * the list are awakened.
6967 * @see VVByPListBeginExclusive_r
6968 * @see VVByPListWait_r
6972 * @internal volume package internal use only.
6975 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
6977 assert(dp->vol_list.busy);
6978 dp->vol_list.busy = 0;
6979 assert(pthread_cond_broadcast(&dp->vol_list.cv) == 0);
6983 * wait for all asynchronous operations on a VByPList to complete.
6985 * @param[in] dp pointer to disk partition object
6987 * @pre VOL_LOCK is held.
6989 * @post disk partition's VByP list is quiescent
6993 * @note This interface should be called before any attempt to
6994 * traverse the VByPList. It is permissible for a thread
6995 * to gain exclusive access to the list, and then perform
6996 * latent operations on the list asynchronously wrt the
6999 * @warning if waiting is necessary, VOL_LOCK is dropped
7001 * @see VVByPListEndExclusive_r
7002 * @see VVByPListBeginExclusive_r
7004 * @internal volume package internal use only.
7007 VVByPListWait_r(struct DiskPartition64 * dp)
7009 while (dp->vol_list.busy) {
7010 VOL_CV_WAIT(&dp->vol_list.cv);
7013 #endif /* AFS_DEMAND_ATTACH_FS */
7015 /***************************************************/
7016 /* Volume Cache Statistics routines */
7017 /***************************************************/
7020 VPrintCacheStats_r(void)
7022 afs_uint32 get_hi, get_lo, load_hi, load_lo;
7023 register struct VnodeClassInfo *vcp;
7024 vcp = &VnodeClassInfo[vLarge];
7025 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);
7026 vcp = &VnodeClassInfo[vSmall];
7027 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);
7028 SplitInt64(VStats.hdr_gets, get_hi, get_lo);
7029 SplitInt64(VStats.hdr_loads, load_hi, load_lo);
7030 Log("Volume header cache, %d entries, %d gets, %d replacements\n",
7031 VStats.hdr_cache_size, get_lo, load_lo);
7035 VPrintCacheStats(void)
7038 VPrintCacheStats_r();
7042 #ifdef AFS_DEMAND_ATTACH_FS
7044 UInt64ToDouble(afs_uint64 * x)
7046 static double c32 = 4.0 * 1.073741824 * 1000000000.0;
7048 SplitInt64(*x, h, l);
7049 return (((double)h) * c32) + ((double) l);
7053 DoubleToPrintable(double x, char * buf, int len)
7055 static double billion = 1000000000.0;
7058 y[0] = (afs_uint32) (x / (billion * billion));
7059 y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
7060 y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
7063 snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
7065 snprintf(buf, len, "%d%09d", y[1], y[2]);
7067 snprintf(buf, len, "%d", y[2]);
7073 struct VLRUExtStatsEntry {
7077 struct VLRUExtStats {
7083 } queue_info[VLRU_QUEUE_INVALID];
7084 struct VLRUExtStatsEntry * vec;
7088 * add a 256-entry fudge factor onto the vector in case state changes
7089 * out from under us.
7091 #define VLRU_EXT_STATS_VEC_LEN_FUDGE 256
7094 * collect extended statistics for the VLRU subsystem.
7096 * @param[out] stats pointer to stats structure to be populated
7097 * @param[in] nvols number of volumes currently known to exist
7099 * @pre VOL_LOCK held
7101 * @post stats->vec allocated and populated
7103 * @return operation status
7108 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
7110 afs_uint32 cur, idx, len;
7111 struct rx_queue * qp, * nqp;
7113 struct VLRUExtStatsEntry * vec;
7115 len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
7116 vec = stats->vec = calloc(len,
7117 sizeof(struct VLRUExtStatsEntry));
7123 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
7124 VLRU_Wait_r(&volume_LRU.q[idx]);
7125 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7128 stats->queue_info[idx].start = cur;
7130 for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7132 /* out of space in vec */
7135 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7136 vec[cur].volid = vp->hashid;
7140 stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
7143 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7151 #define ENUMTOSTRING(en) #en
7152 #define ENUMCASE(en) \
7154 return ENUMTOSTRING(en); \
7158 vlru_idx_to_string(int idx)
7161 ENUMCASE(VLRU_QUEUE_NEW);
7162 ENUMCASE(VLRU_QUEUE_MID);
7163 ENUMCASE(VLRU_QUEUE_OLD);
7164 ENUMCASE(VLRU_QUEUE_CANDIDATE);
7165 ENUMCASE(VLRU_QUEUE_HELD);
7166 ENUMCASE(VLRU_QUEUE_INVALID);
7168 return "**UNKNOWN**";
7173 VPrintExtendedCacheStats_r(int flags)
7176 afs_uint32 vol_sum = 0;
7183 struct stats looks, gets, reorders, len;
7184 struct stats ch_looks, ch_gets, ch_reorders;
7186 VolumeHashChainHead *head;
7188 struct VLRUExtStats vlru_stats;
7190 /* zero out stats */
7191 memset(&looks, 0, sizeof(struct stats));
7192 memset(&gets, 0, sizeof(struct stats));
7193 memset(&reorders, 0, sizeof(struct stats));
7194 memset(&len, 0, sizeof(struct stats));
7195 memset(&ch_looks, 0, sizeof(struct stats));
7196 memset(&ch_gets, 0, sizeof(struct stats));
7197 memset(&ch_reorders, 0, sizeof(struct stats));
7199 for (i = 0; i < VolumeHashTable.Size; i++) {
7200 head = &VolumeHashTable.Table[i];
7203 VHashBeginExclusive_r(head);
7206 ch_looks.sum = UInt64ToDouble(&head->looks);
7207 ch_gets.sum = UInt64ToDouble(&head->gets);
7208 ch_reorders.sum = UInt64ToDouble(&head->reorders);
7210 /* update global statistics */
7212 looks.sum += ch_looks.sum;
7213 gets.sum += ch_gets.sum;
7214 reorders.sum += ch_reorders.sum;
7215 len.sum += (double)head->len;
7216 vol_sum += head->len;
7219 len.min = (double) head->len;
7220 len.max = (double) head->len;
7221 looks.min = ch_looks.sum;
7222 looks.max = ch_looks.sum;
7223 gets.min = ch_gets.sum;
7224 gets.max = ch_gets.sum;
7225 reorders.min = ch_reorders.sum;
7226 reorders.max = ch_reorders.sum;
7228 if (((double)head->len) < len.min)
7229 len.min = (double) head->len;
7230 if (((double)head->len) > len.max)
7231 len.max = (double) head->len;
7232 if (ch_looks.sum < looks.min)
7233 looks.min = ch_looks.sum;
7234 else if (ch_looks.sum > looks.max)
7235 looks.max = ch_looks.sum;
7236 if (ch_gets.sum < gets.min)
7237 gets.min = ch_gets.sum;
7238 else if (ch_gets.sum > gets.max)
7239 gets.max = ch_gets.sum;
7240 if (ch_reorders.sum < reorders.min)
7241 reorders.min = ch_reorders.sum;
7242 else if (ch_reorders.sum > reorders.max)
7243 reorders.max = ch_reorders.sum;
7247 if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
7248 /* compute detailed per-chain stats */
7249 struct stats hdr_loads, hdr_gets;
7250 double v_looks, v_loads, v_gets;
7252 /* initialize stats with data from first element in chain */
7253 vp = queue_First(head, Volume);
7254 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
7255 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
7256 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
7257 ch_gets.min = ch_gets.max = v_looks;
7258 hdr_loads.min = hdr_loads.max = v_loads;
7259 hdr_gets.min = hdr_gets.max = v_gets;
7260 hdr_loads.sum = hdr_gets.sum = 0;
7262 vp = queue_Next(vp, Volume);
7264 /* pull in stats from remaining elements in chain */
7265 for (queue_ScanFrom(head, vp, vp, np, Volume)) {
7266 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
7267 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
7268 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
7270 hdr_loads.sum += v_loads;
7271 hdr_gets.sum += v_gets;
7273 if (v_looks < ch_gets.min)
7274 ch_gets.min = v_looks;
7275 else if (v_looks > ch_gets.max)
7276 ch_gets.max = v_looks;
7278 if (v_loads < hdr_loads.min)
7279 hdr_loads.min = v_loads;
7280 else if (v_loads > hdr_loads.max)
7281 hdr_loads.max = v_loads;
7283 if (v_gets < hdr_gets.min)
7284 hdr_gets.min = v_gets;
7285 else if (v_gets > hdr_gets.max)
7286 hdr_gets.max = v_gets;
7289 /* compute per-chain averages */
7290 ch_gets.avg = ch_gets.sum / ((double)head->len);
7291 hdr_loads.avg = hdr_loads.sum / ((double)head->len);
7292 hdr_gets.avg = hdr_gets.sum / ((double)head->len);
7294 /* dump per-chain stats */
7295 Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
7297 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
7298 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
7299 Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
7300 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
7301 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
7302 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
7303 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
7304 Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
7305 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
7306 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
7307 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
7308 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
7309 Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
7310 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
7311 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
7312 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
7313 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
7314 } else if (flags & VOL_STATS_PER_CHAIN) {
7315 /* dump simple per-chain stats */
7316 Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
7318 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
7319 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
7320 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
7324 VHashEndExclusive_r(head);
7329 /* compute global averages */
7330 len.avg = len.sum / ((double)VolumeHashTable.Size);
7331 looks.avg = looks.sum / ((double)VolumeHashTable.Size);
7332 gets.avg = gets.sum / ((double)VolumeHashTable.Size);
7333 reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
7335 /* dump global stats */
7336 Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
7337 Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
7338 DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
7339 DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
7340 DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
7341 DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
7342 Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
7343 DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
7344 DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
7345 DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
7346 DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
7347 Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
7348 DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
7349 DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
7350 DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
7351 DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
7352 Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
7353 DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
7354 DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
7355 DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
7356 DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
7358 /* print extended disk related statistics */
7360 struct DiskPartition64 * diskP;
7361 afs_uint32 vol_count[VOLMAXPARTS+1];
7362 byte part_exists[VOLMAXPARTS+1];
7366 memset(vol_count, 0, sizeof(vol_count));
7367 memset(part_exists, 0, sizeof(part_exists));
7371 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
7373 vol_count[id] = diskP->vol_list.len;
7374 part_exists[id] = 1;
7378 for (i = 0; i <= VOLMAXPARTS; i++) {
7379 if (part_exists[i]) {
7380 /* XXX while this is currently safe, it is a violation
7381 * of the VGetPartitionById_r interface contract. */
7382 diskP = VGetPartitionById_r(i, 0);
7384 Log("Partition %s has %d online volumes\n",
7385 VPartitionPath(diskP), diskP->vol_list.len);
7392 /* print extended VLRU statistics */
7393 if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
7394 afs_uint32 idx, cur, lpos;
7398 Log("VLRU State Dump:\n\n");
7400 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
7401 Log("\t%s:\n", vlru_idx_to_string(idx));
7404 for (cur = vlru_stats.queue_info[idx].start;
7405 cur < vlru_stats.queue_info[idx].len;
7407 line[lpos++] = vlru_stats.vec[cur].volid;
7409 Log("\t\t%u, %u, %u, %u, %u,\n",
7410 line[0], line[1], line[2], line[3], line[4]);
7419 Log("\t\t%u, %u, %u, %u, %u\n",
7420 line[0], line[1], line[2], line[3], line[4]);
7425 free(vlru_stats.vec);
7432 VPrintExtendedCacheStats(int flags)
7435 VPrintExtendedCacheStats_r(flags);
7438 #endif /* AFS_DEMAND_ATTACH_FS */