2 * Copyright 2000, International Business Machines Corporation and others.
5 * This software has been released under the terms of the IBM Public
6 * License. For details, see the LICENSE file in the top-level source
7 * directory or online at http://www.openafs.org/dl/license10.html
9 * Portions Copyright (c) 2005-2008 Sine Nomine Associates
12 /* 1/1/89: NB: this stuff is all going to be replaced. Don't take it too seriously */
17 Institution: The Information Technology Center, Carnegie-Mellon University
21 #include <afsconfig.h>
22 #include <afs/param.h>
26 #include <afs/afsint.h>
29 #include <sys/param.h>
30 #if !defined(AFS_SGI_ENV)
33 #else /* AFS_OSF_ENV */
34 #ifdef AFS_VFSINCL_ENV
37 #include <sys/fs/ufs_fs.h>
39 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
40 #include <ufs/ufs/dinode.h>
41 #include <ufs/ffs/fs.h>
46 #else /* AFS_VFSINCL_ENV */
47 #if !defined(AFS_AIX_ENV) && !defined(AFS_LINUX20_ENV) && !defined(AFS_XBSD_ENV)
50 #endif /* AFS_VFSINCL_ENV */
51 #endif /* AFS_OSF_ENV */
52 #endif /* AFS_SGI_ENV */
53 #endif /* AFS_NT40_ENV */
71 #if defined(AFS_SUN_ENV) || defined(AFS_SUN5_ENV)
73 #include <sys/mnttab.h>
74 #include <sys/mntent.h>
80 #if defined(AFS_SGI_ENV)
85 #ifndef AFS_LINUX20_ENV
86 #include <fstab.h> /* Need to find in libc 5, present in libc 6 */
89 #endif /* AFS_SGI_ENV */
91 #endif /* AFS_HPUX_ENV */
95 #include <netinet/in.h>
100 #endif /* ITIMER_REAL */
101 #endif /* AFS_NT40_ENV */
102 #if defined(AFS_SUN5_ENV) || defined(AFS_NT40_ENV) || defined(AFS_LINUX20_ENV)
109 #include <afs/errors.h>
112 #include <afs/afssyscalls.h>
114 #include <afs/afsutil.h>
118 #include "daemon_com.h"
120 #include "salvsync.h"
123 #include "partition.h"
124 #include "volume_inline.h"
125 #ifdef AFS_PTHREAD_ENV
127 #else /* AFS_PTHREAD_ENV */
128 #include "afs/assert.h"
129 #endif /* AFS_PTHREAD_ENV */
136 #if !defined(offsetof)
141 #define afs_stat stat64
142 #define afs_fstat fstat64
143 #define afs_open open64
144 #else /* !O_LARGEFILE */
145 #define afs_stat stat
146 #define afs_fstat fstat
147 #define afs_open open
148 #endif /* !O_LARGEFILE */
150 #ifdef AFS_PTHREAD_ENV
151 pthread_mutex_t vol_glock_mutex;
152 pthread_mutex_t vol_trans_mutex;
153 pthread_cond_t vol_put_volume_cond;
154 pthread_cond_t vol_sleep_cond;
155 int vol_attach_threads = 1;
156 #endif /* AFS_PTHREAD_ENV */
158 #ifdef AFS_DEMAND_ATTACH_FS
159 pthread_mutex_t vol_salvsync_mutex;
160 #endif /* AFS_DEMAND_ATTACH_FS */
163 extern void *calloc(), *realloc();
166 /*@printflike@*/ extern void Log(const char *format, ...);
168 /* Forward declarations */
169 static Volume *attach2(Error * ec, VolId vid, char *path,
170 register struct VolumeHeader *header,
171 struct DiskPartition64 *partp, Volume * vp,
172 int isbusy, int mode);
173 static void ReallyFreeVolume(Volume * vp);
174 #ifdef AFS_DEMAND_ATTACH_FS
175 static void FreeVolume(Volume * vp);
176 #else /* !AFS_DEMAND_ATTACH_FS */
177 #define FreeVolume(vp) ReallyFreeVolume(vp)
178 static void VScanUpdateList(void);
179 #endif /* !AFS_DEMAND_ATTACH_FS */
180 static void VInitVolumeHeaderCache(afs_uint32 howMany);
181 static int GetVolumeHeader(register Volume * vp);
182 static void ReleaseVolumeHeader(register struct volHeader *hd);
183 static void FreeVolumeHeader(register Volume * vp);
184 static void AddVolumeToHashTable(register Volume * vp, int hashid);
185 static void DeleteVolumeFromHashTable(register Volume * vp);
187 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 #ifdef AFS_DEMAND_ATTACH_FS
198 static int VolumeExternalName_r(VolumeId volumeId, char * name, size_t len);
201 int LogLevel; /* Vice loglevel--not defined as extern so that it will be
202 * defined when not linked with vice, XXXX */
203 ProgramType programType; /* The type of program using the package */
205 /* extended volume package statistics */
208 #ifdef VOL_LOCK_DEBUG
209 pthread_t vol_glock_holder = 0;
213 #define VOLUME_BITMAP_GROWSIZE 16 /* bytes, => 128vnodes */
214 /* Must be a multiple of 4 (1 word) !! */
216 /* this parameter needs to be tunable at runtime.
217 * 128 was really inadequate for largish servers -- at 16384 volumes this
218 * puts average chain length at 128, thus an average 65 deref's to find a volptr.
219 * talk about bad spatial locality...
221 * an AVL or splay tree might work a lot better, but we'll just increase
222 * the default hash table size for now
224 #define DEFAULT_VOLUME_HASH_SIZE 256 /* Must be a power of 2!! */
225 #define DEFAULT_VOLUME_HASH_MASK (DEFAULT_VOLUME_HASH_SIZE-1)
226 #define VOLUME_HASH(volumeId) (volumeId&(VolumeHashTable.Mask))
229 * turn volume hash chains into partially ordered lists.
230 * when the threshold is exceeded between two adjacent elements,
231 * perform a chain rebalancing operation.
233 * keep the threshold high in order to keep cache line invalidates
234 * low "enough" on SMPs
236 #define VOLUME_HASH_REORDER_THRESHOLD 200
239 * when possible, don't just reorder single elements, but reorder
240 * entire chains of elements at once. a chain of elements that
241 * exceed the element previous to the pivot by at least CHAIN_THRESH
242 * accesses are moved in front of the chain whose elements have at
243 * least CHAIN_THRESH less accesses than the pivot element
245 #define VOLUME_HASH_REORDER_CHAIN_THRESH (VOLUME_HASH_REORDER_THRESHOLD / 2)
247 #include "rx/rx_queue.h"
250 VolumeHashTable_t VolumeHashTable = {
251 DEFAULT_VOLUME_HASH_SIZE,
252 DEFAULT_VOLUME_HASH_MASK,
257 static void VInitVolumeHash(void);
261 /* This macro is used where an ffs() call does not exist. Was in util/ffs.c */
265 afs_int32 ffs_tmp = x;
269 for (ffs_i = 1;; ffs_i++) {
276 #endif /* !AFS_HAVE_FFS */
278 #ifdef AFS_PTHREAD_ENV
279 typedef struct diskpartition_queue_t {
280 struct rx_queue queue;
281 struct DiskPartition64 * diskP;
282 } diskpartition_queue_t;
283 typedef struct vinitvolumepackage_thread_t {
284 struct rx_queue queue;
285 pthread_cond_t thread_done_cv;
286 int n_threads_complete;
287 } vinitvolumepackage_thread_t;
288 static void * VInitVolumePackageThread(void * args);
289 #endif /* AFS_PTHREAD_ENV */
291 static int VAttachVolumesByPartition(struct DiskPartition64 *diskP,
292 int * nAttached, int * nUnattached);
295 #ifdef AFS_DEMAND_ATTACH_FS
296 /* demand attach fileserver extensions */
299 * in the future we will support serialization of VLRU state into the fs_state
302 * these structures are the beginning of that effort
304 struct VLRU_DiskHeader {
305 struct versionStamp stamp; /* magic and structure version number */
306 afs_uint32 mtime; /* time of dump to disk */
307 afs_uint32 num_records; /* number of VLRU_DiskEntry records */
310 struct VLRU_DiskEntry {
311 afs_uint32 vid; /* volume ID */
312 afs_uint32 idx; /* generation */
313 afs_uint32 last_get; /* timestamp of last get */
316 struct VLRU_StartupQueue {
317 struct VLRU_DiskEntry * entry;
322 typedef struct vshutdown_thread_t {
324 pthread_mutex_t lock;
326 pthread_cond_t master_cv;
328 int n_threads_complete;
330 int schedule_version;
333 byte n_parts_done_pass;
334 byte part_thread_target[VOLMAXPARTS+1];
335 byte part_done_pass[VOLMAXPARTS+1];
336 struct rx_queue * part_pass_head[VOLMAXPARTS+1];
337 int stats[4][VOLMAXPARTS+1];
338 } vshutdown_thread_t;
339 static void * VShutdownThread(void * args);
342 static Volume * VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode);
343 static int VCheckFree(Volume * vp);
346 static void AddVolumeToVByPList_r(Volume * vp);
347 static void DeleteVolumeFromVByPList_r(Volume * vp);
348 static void VVByPListBeginExclusive_r(struct DiskPartition64 * dp);
349 static void VVByPListEndExclusive_r(struct DiskPartition64 * dp);
350 static void VVByPListWait_r(struct DiskPartition64 * dp);
352 /* online salvager */
353 static int VCheckSalvage(register Volume * vp);
354 static int VUpdateSalvagePriority_r(Volume * vp);
355 static int VScheduleSalvage_r(Volume * vp);
356 static int VCancelSalvage_r(Volume * vp, int reason);
358 /* Volume hash table */
359 static void VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp);
360 static void VHashBeginExclusive_r(VolumeHashChainHead * head);
361 static void VHashEndExclusive_r(VolumeHashChainHead * head);
362 static void VHashWait_r(VolumeHashChainHead * head);
365 static int ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass);
366 static int ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
367 struct rx_queue ** idx);
368 static void ShutdownController(vshutdown_thread_t * params);
369 static void ShutdownCreateSchedule(vshutdown_thread_t * params);
372 static void VLRU_ComputeConstants(void);
373 static void VInitVLRU(void);
374 static void VLRU_Init_Node_r(volatile Volume * vp);
375 static void VLRU_Add_r(volatile Volume * vp);
376 static void VLRU_Delete_r(volatile Volume * vp);
377 static void VLRU_UpdateAccess_r(volatile Volume * vp);
378 static void * VLRU_ScannerThread(void * args);
379 static void VLRU_Scan_r(int idx);
380 static void VLRU_Promote_r(int idx);
381 static void VLRU_Demote_r(int idx);
382 static void VLRU_SwitchQueues(volatile Volume * vp, int new_idx, int append);
385 static int VCheckSoftDetach(volatile Volume * vp, afs_uint32 thresh);
386 static int VCheckSoftDetachCandidate(volatile Volume * vp, afs_uint32 thresh);
387 static int VSoftDetachVolume_r(volatile Volume * vp, afs_uint32 thresh);
390 pthread_key_t VThread_key;
391 VThreadOptions_t VThread_defaults = {
392 0 /**< allow salvsync */
394 #endif /* AFS_DEMAND_ATTACH_FS */
397 struct Lock vol_listLock; /* Lock obtained when listing volumes:
398 * prevents a volume from being missed
399 * if the volume is attached during a
403 static int TimeZoneCorrection; /* Number of seconds west of GMT */
405 /* Common message used when the volume goes off line */
406 char *VSalvageMessage =
407 "Files in this volume are currently unavailable; call operations";
409 int VInit; /* 0 - uninitialized,
410 * 1 - initialized but not all volumes have been attached,
411 * 2 - initialized and all volumes have been attached,
412 * 3 - initialized, all volumes have been attached, and
413 * VConnectFS() has completed. */
416 bit32 VolumeCacheCheck; /* Incremented everytime a volume goes on line--
417 * used to stamp volume headers and in-core
418 * vnodes. When the volume goes on-line the
419 * vnode will be invalidated
420 * access only with VOL_LOCK held */
425 /***************************************************/
426 /* Startup routines */
427 /***************************************************/
430 VInitVolumePackage(ProgramType pt, afs_uint32 nLargeVnodes, afs_uint32 nSmallVnodes,
431 int connect, afs_uint32 volcache)
433 int errors = 0; /* Number of errors while finding vice partitions. */
439 memset(&VStats, 0, sizeof(VStats));
440 VStats.hdr_cache_size = 200;
442 VInitPartitionPackage();
444 #ifdef AFS_DEMAND_ATTACH_FS
445 if (programType == fileServer) {
448 VLRU_SetOptions(VLRU_SET_ENABLED, 0);
450 assert(pthread_key_create(&VThread_key, NULL) == 0);
453 #ifdef AFS_PTHREAD_ENV
454 assert(pthread_mutex_init(&vol_glock_mutex, NULL) == 0);
455 assert(pthread_mutex_init(&vol_trans_mutex, NULL) == 0);
456 assert(pthread_cond_init(&vol_put_volume_cond, NULL) == 0);
457 assert(pthread_cond_init(&vol_sleep_cond, NULL) == 0);
458 #else /* AFS_PTHREAD_ENV */
460 #endif /* AFS_PTHREAD_ENV */
461 Lock_Init(&vol_listLock);
463 srandom(time(0)); /* For VGetVolumeInfo */
464 gettimeofday(&tv, &tz);
465 TimeZoneCorrection = tz.tz_minuteswest * 60;
467 #ifdef AFS_DEMAND_ATTACH_FS
468 assert(pthread_mutex_init(&vol_salvsync_mutex, NULL) == 0);
469 #endif /* AFS_DEMAND_ATTACH_FS */
471 /* Ok, we have done enough initialization that fileserver can
472 * start accepting calls, even though the volumes may not be
473 * available just yet.
477 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_SERVER)
478 if (programType == salvageServer) {
481 #endif /* AFS_DEMAND_ATTACH_FS */
482 #ifdef FSSYNC_BUILD_SERVER
483 if (programType == fileServer) {
487 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_CLIENT)
488 if (programType == fileServer) {
489 /* establish a connection to the salvager at this point */
490 assert(VConnectSALV() != 0);
492 #endif /* AFS_DEMAND_ATTACH_FS */
494 if (volcache > VStats.hdr_cache_size)
495 VStats.hdr_cache_size = volcache;
496 VInitVolumeHeaderCache(VStats.hdr_cache_size);
498 VInitVnodes(vLarge, nLargeVnodes);
499 VInitVnodes(vSmall, nSmallVnodes);
502 errors = VAttachPartitions();
506 if (programType == fileServer) {
507 struct DiskPartition64 *diskP;
508 #ifdef AFS_PTHREAD_ENV
509 struct vinitvolumepackage_thread_t params;
510 struct diskpartition_queue_t * dpq;
511 int i, threads, parts;
513 pthread_attr_t attrs;
515 assert(pthread_cond_init(¶ms.thread_done_cv,NULL) == 0);
517 params.n_threads_complete = 0;
519 /* create partition work queue */
520 for (parts=0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
521 dpq = (diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
524 queue_Append(¶ms,dpq);
527 threads = MIN(parts, vol_attach_threads);
530 /* spawn off a bunch of initialization threads */
531 assert(pthread_attr_init(&attrs) == 0);
532 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
534 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
535 #ifdef AFS_DEMAND_ATTACH_FS
536 Log("VInitVolumePackage: using %d threads to pre-attach volumes on %d partitions\n",
538 #else /* AFS_DEMAND_ATTACH_FS */
539 Log("VInitVolumePackage: using %d threads to attach volumes on %d partitions\n",
541 #endif /* AFS_DEMAND_ATTACH_FS */
544 for (i=0; i < threads; i++) {
545 assert(pthread_create
546 (&tid, &attrs, &VInitVolumePackageThread,
550 while(params.n_threads_complete < threads) {
551 VOL_CV_WAIT(¶ms.thread_done_cv);
555 assert(pthread_attr_destroy(&attrs) == 0);
557 /* if we're only going to run one init thread, don't bother creating
559 Log("VInitVolumePackage: beginning single-threaded fileserver startup\n");
560 #ifdef AFS_DEMAND_ATTACH_FS
561 Log("VInitVolumePackage: using 1 thread to pre-attach volumes on %d partition(s)\n",
563 #else /* AFS_DEMAND_ATTACH_FS */
564 Log("VInitVolumePackage: using 1 thread to attach volumes on %d partition(s)\n",
566 #endif /* AFS_DEMAND_ATTACH_FS */
568 VInitVolumePackageThread(¶ms);
571 assert(pthread_cond_destroy(¶ms.thread_done_cv) == 0);
573 #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;
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;
1763 #endif /* AFS_DEMAND_ATTACH_FS */
1767 volumeId = VolumeNumber(name);
1769 if (!(partp = VGetPartition_r(partition, 0))) {
1771 Log("VAttachVolume: Error getting partition (%s)\n", partition);
1775 if (programType == volumeUtility) {
1777 VLockPartition_r(partition);
1778 } else if (programType == fileServer) {
1779 #ifdef AFS_DEMAND_ATTACH_FS
1780 /* lookup the volume in the hash table */
1781 vp = VLookupVolume_r(ec, volumeId, NULL);
1787 /* save any counters that are supposed to
1788 * be monotonically increasing over the
1789 * lifetime of the fileserver */
1790 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
1792 memset(&stats_save, 0, sizeof(VolumeStats));
1795 /* if there's something in the hash table, and it's not
1796 * in the pre-attach state, then we may need to detach
1797 * it before proceeding */
1798 if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1799 VCreateReservation_r(vp);
1800 VWaitExclusiveState_r(vp);
1802 /* at this point state must be one of:
1811 if (vp->specialStatus == VBUSY)
1814 /* if it's already attached, see if we can return it */
1815 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
1816 VGetVolumeByVp_r(ec, vp);
1817 if (V_inUse(vp) == fileServer) {
1818 VCancelReservation_r(vp);
1822 /* otherwise, we need to detach, and attempt to re-attach */
1823 VDetachVolume_r(ec, vp);
1825 Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
1828 /* if it isn't fully attached, delete from the hash tables,
1829 and let the refcounter handle the rest */
1830 DeleteVolumeFromHashTable(vp);
1831 DeleteVolumeFromVByPList_r(vp);
1834 VCancelReservation_r(vp);
1838 /* pre-attach volume if it hasn't been done yet */
1840 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
1841 (V_attachState(vp) == VOL_STATE_ERROR)) {
1843 vp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
1851 /* handle pre-attach races
1853 * multiple threads can race to pre-attach a volume,
1854 * but we can't let them race beyond that
1856 * our solution is to let the first thread to bring
1857 * the volume into an exclusive state win; the other
1858 * threads just wait until it finishes bringing the
1859 * volume online, and then they do a vgetvolumebyvp
1861 if (svp && (svp != vp)) {
1862 /* wait for other exclusive ops to finish */
1863 VCreateReservation_r(vp);
1864 VWaitExclusiveState_r(vp);
1866 /* get a heavyweight ref, kill the lightweight ref, and return */
1867 VGetVolumeByVp_r(ec, vp);
1868 VCancelReservation_r(vp);
1872 /* at this point, we are chosen as the thread to do
1873 * demand attachment for this volume. all other threads
1874 * doing a getvolume on vp->hashid will block until we finish */
1876 /* make sure any old header cache entries are invalidated
1877 * before proceeding */
1878 FreeVolumeHeader(vp);
1880 VChangeState_r(vp, VOL_STATE_ATTACHING);
1882 /* restore any saved counters */
1883 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
1884 #else /* AFS_DEMAND_ATTACH_FS */
1885 vp = VGetVolume_r(ec, volumeId);
1887 if (V_inUse(vp) == fileServer)
1889 if (vp->specialStatus == VBUSY)
1891 VDetachVolume_r(ec, vp);
1893 Log("VAttachVolume: Error detaching volume (%s)\n", name);
1897 #endif /* AFS_DEMAND_ATTACH_FS */
1901 strcpy(path, VPartitionPath(partp));
1907 if ((fd = afs_open(path, O_RDONLY)) == -1 || afs_fstat(fd, &status) == -1) {
1908 Log("VAttachVolume: Failed to open %s (errno %d)\n", path, errno);
1915 n = read(fd, &diskHeader, sizeof(diskHeader));
1917 if (n != sizeof(diskHeader)
1918 || diskHeader.stamp.magic != VOLUMEHEADERMAGIC) {
1919 Log("VAttachVolume: Error reading volume header %s\n", path);
1924 if (diskHeader.stamp.version != VOLUMEHEADERVERSION) {
1925 Log("VAttachVolume: Volume %s, version number is incorrect; volume needs salvaged\n", path);
1931 DiskToVolumeHeader(&iheader, &diskHeader);
1932 #ifdef FSSYNC_BUILD_CLIENT
1933 if (programType == volumeUtility && mode != V_SECRETLY && mode != V_PEEK) {
1935 if (FSYNC_VolOp(iheader.id, partition, FSYNC_VOL_NEEDVOLUME, mode, NULL)
1937 Log("VAttachVolume: attach of volume %u apparently denied by file server\n", iheader.id);
1938 *ec = VNOVOL; /* XXXX */
1946 vp = (Volume *) calloc(1, sizeof(Volume));
1948 vp->device = partp->device;
1949 vp->partition = partp;
1950 queue_Init(&vp->vnode_list);
1951 #ifdef AFS_DEMAND_ATTACH_FS
1952 assert(pthread_cond_init(&V_attachCV(vp), NULL) == 0);
1953 #endif /* AFS_DEMAND_ATTACH_FS */
1956 /* attach2 is entered without any locks, and returns
1957 * with vol_glock_mutex held */
1958 vp = attach2(ec, volumeId, path, &iheader, partp, vp, isbusy, mode);
1960 if (programType == volumeUtility && vp) {
1961 if ((mode == V_VOLUPD) || (VolumeWriteable(vp) && (mode == V_CLONE))) {
1962 /* mark volume header as in use so that volser crashes lead to a
1963 * salvage attempt */
1964 VUpdateVolume_r(ec, vp, 0);
1966 #ifdef AFS_DEMAND_ATTACH_FS
1967 /* for dafs, we should tell the fileserver, except for V_PEEK
1968 * where we know it is not necessary */
1969 if (mode == V_PEEK) {
1970 vp->needsPutBack = 0;
1972 vp->needsPutBack = 1;
1974 #else /* !AFS_DEMAND_ATTACH_FS */
1975 /* duplicate computation in fssync.c about whether the server
1976 * takes the volume offline or not. If the volume isn't
1977 * offline, we must not return it when we detach the volume,
1978 * or the server will abort */
1979 if (mode == V_READONLY || mode == V_PEEK
1980 || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
1981 vp->needsPutBack = 0;
1983 vp->needsPutBack = 1;
1984 #endif /* !AFS_DEMAND_ATTACH_FS */
1986 /* OK, there's a problem here, but one that I don't know how to
1987 * fix right now, and that I don't think should arise often.
1988 * Basically, we should only put back this volume to the server if
1989 * it was given to us by the server, but since we don't have a vp,
1990 * we can't run the VolumeWriteable function to find out as we do
1991 * above when computing vp->needsPutBack. So we send it back, but
1992 * there's a path in VAttachVolume on the server which may abort
1993 * if this volume doesn't have a header. Should be pretty rare
1994 * for all of that to happen, but if it does, probably the right
1995 * fix is for the server to allow the return of readonly volumes
1996 * that it doesn't think are really checked out. */
1997 #ifdef FSSYNC_BUILD_CLIENT
1998 if (programType == volumeUtility && vp == NULL &&
1999 mode != V_SECRETLY && mode != V_PEEK) {
2000 FSYNC_VolOp(iheader.id, partition, FSYNC_VOL_ON, 0, NULL);
2003 if (programType == fileServer && vp) {
2004 #ifdef AFS_DEMAND_ATTACH_FS
2006 * we can get here in cases where we don't "own"
2007 * the volume (e.g. volume owned by a utility).
2008 * short circuit around potential disk header races.
2010 if (V_attachState(vp) != VOL_STATE_ATTACHED) {
2014 V_needsCallback(vp) = 0;
2016 if (VInit >= 2 && V_BreakVolumeCallbacks) {
2017 Log("VAttachVolume: Volume %u was changed externally; breaking callbacks\n", V_id(vp));
2018 (*V_BreakVolumeCallbacks) (V_id(vp));
2021 VUpdateVolume_r(ec, vp, 0);
2023 Log("VAttachVolume: Error updating volume\n");
2028 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2029 #ifndef AFS_DEMAND_ATTACH_FS
2030 /* This is a hack: by temporarily setting the incore
2031 * dontSalvage flag ON, the volume will be put back on the
2032 * Update list (with dontSalvage OFF again). It will then
2033 * come back in N minutes with DONT_SALVAGE eventually
2034 * set. This is the way that volumes that have never had
2035 * it set get it set; or that volumes that have been
2036 * offline without DONT SALVAGE having been set also
2037 * eventually get it set */
2038 V_dontSalvage(vp) = DONT_SALVAGE;
2039 #endif /* !AFS_DEMAND_ATTACH_FS */
2040 VAddToVolumeUpdateList_r(ec, vp);
2042 Log("VAttachVolume: Error adding volume to update list\n");
2049 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2054 if (programType == volumeUtility) {
2055 VUnlockPartition_r(partition);
2058 #ifdef AFS_DEMAND_ATTACH_FS
2059 /* attach failed; make sure we're in error state */
2060 if (vp && !VIsErrorState(V_attachState(vp))) {
2061 VChangeState_r(vp, VOL_STATE_ERROR);
2063 #endif /* AFS_DEMAND_ATTACH_FS */
2070 #ifdef AFS_DEMAND_ATTACH_FS
2071 /* VAttachVolumeByVp_r
2073 * finish attaching a volume that is
2074 * in a less than fully attached state
2076 /* caller MUST hold a ref count on vp */
2078 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
2080 char name[VMAXPATHLEN];
2081 int fd, n, reserve = 0;
2082 struct afs_stat status;
2083 struct VolumeDiskHeader diskHeader;
2084 struct VolumeHeader iheader;
2085 struct DiskPartition64 *partp;
2090 VolumeStats stats_save;
2093 /* volume utility should never call AttachByVp */
2094 assert(programType == fileServer);
2096 volumeId = vp->hashid;
2097 partp = vp->partition;
2098 VolumeExternalName_r(volumeId, name, sizeof(name));
2101 /* if another thread is performing a blocking op, wait */
2102 VWaitExclusiveState_r(vp);
2104 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2106 /* if it's already attached, see if we can return it */
2107 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2108 VGetVolumeByVp_r(ec, vp);
2109 if (V_inUse(vp) == fileServer) {
2112 if (vp->specialStatus == VBUSY)
2114 VDetachVolume_r(ec, vp);
2116 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2122 /* pre-attach volume if it hasn't been done yet */
2124 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2125 (V_attachState(vp) == VOL_STATE_ERROR)) {
2126 nvp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2132 VCreateReservation_r(nvp);
2138 VChangeState_r(vp, VOL_STATE_ATTACHING);
2140 /* restore monotonically increasing stats */
2141 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2146 /* compute path to disk header,
2148 * and verify magic and version stamps */
2149 strcpy(path, VPartitionPath(partp));
2155 if ((fd = afs_open(path, O_RDONLY)) == -1 || afs_fstat(fd, &status) == -1) {
2156 Log("VAttachVolume: Failed to open %s (errno %d)\n", path, errno);
2163 n = read(fd, &diskHeader, sizeof(diskHeader));
2165 if (n != sizeof(diskHeader)
2166 || diskHeader.stamp.magic != VOLUMEHEADERMAGIC) {
2167 Log("VAttachVolume: Error reading volume header %s\n", path);
2172 if (diskHeader.stamp.version != VOLUMEHEADERVERSION) {
2173 Log("VAttachVolume: Volume %s, version number is incorrect; volume needs salvaged\n", path);
2179 /* convert on-disk header format to in-memory header format */
2180 DiskToVolumeHeader(&iheader, &diskHeader);
2184 * NOTE: attach2 is entered without any locks, and returns
2185 * with vol_glock_mutex held */
2186 vp = attach2(ec, volumeId, path, &iheader, partp, vp, isbusy, mode);
2189 * the event that an error was encountered, or
2190 * the volume was not brought to an attached state
2191 * for any reason, skip to the end. We cannot
2192 * safely call VUpdateVolume unless we "own" it.
2196 (V_attachState(vp) != VOL_STATE_ATTACHED)) {
2200 V_needsCallback(vp) = 0;
2201 VUpdateVolume_r(ec, vp, 0);
2203 Log("VAttachVolume: Error updating volume %u\n", vp->hashid);
2207 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2208 #ifndef AFS_DEMAND_ATTACH_FS
2209 /* This is a hack: by temporarily setting the incore
2210 * dontSalvage flag ON, the volume will be put back on the
2211 * Update list (with dontSalvage OFF again). It will then
2212 * come back in N minutes with DONT_SALVAGE eventually
2213 * set. This is the way that volumes that have never had
2214 * it set get it set; or that volumes that have been
2215 * offline without DONT SALVAGE having been set also
2216 * eventually get it set */
2217 V_dontSalvage(vp) = DONT_SALVAGE;
2218 #endif /* !AFS_DEMAND_ATTACH_FS */
2219 VAddToVolumeUpdateList_r(ec, vp);
2221 Log("VAttachVolume: Error adding volume %u to update list\n", vp->hashid);
2228 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2232 VCancelReservation_r(nvp);
2235 if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2236 if (vp && !VIsErrorState(V_attachState(vp))) {
2237 VChangeState_r(vp, VOL_STATE_ERROR);
2244 #endif /* AFS_DEMAND_ATTACH_FS */
2247 * called without any locks held
2248 * returns with vol_glock_mutex held
2251 attach2(Error * ec, VolId volumeId, char *path, register struct VolumeHeader * header,
2252 struct DiskPartition64 * partp, register Volume * vp, int isbusy, int mode)
2254 vp->specialStatus = (byte) (isbusy ? VBUSY : 0);
2255 IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header->parent,
2256 header->largeVnodeIndex);
2257 IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header->parent,
2258 header->smallVnodeIndex);
2259 IH_INIT(vp->diskDataHandle, partp->device, header->parent,
2260 header->volumeInfo);
2261 IH_INIT(vp->linkHandle, partp->device, header->parent, header->linkTable);
2262 vp->shuttingDown = 0;
2263 vp->goingOffline = 0;
2265 #ifdef AFS_DEMAND_ATTACH_FS
2266 vp->stats.last_attach = FT_ApproxTime();
2267 vp->stats.attaches++;
2271 IncUInt64(&VStats.attaches);
2272 vp->cacheCheck = ++VolumeCacheCheck;
2273 /* just in case this ever rolls over */
2274 if (!vp->cacheCheck)
2275 vp->cacheCheck = ++VolumeCacheCheck;
2276 GetVolumeHeader(vp);
2279 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2280 /* demand attach changes the V_PEEK mechanism
2282 * we can now suck the current disk data structure over
2283 * the fssync interface without going to disk
2285 * (technically, we don't need to restrict this feature
2286 * to demand attach fileservers. However, I'm trying
2287 * to limit the number of common code changes)
2289 if (programType != fileServer && mode == V_PEEK) {
2291 res.payload.len = sizeof(VolumeDiskData);
2292 res.payload.buf = &vp->header->diskstuff;
2294 if (FSYNC_VolOp(volumeId,
2296 FSYNC_VOL_QUERY_HDR,
2299 goto disk_header_loaded;
2302 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2303 (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2304 sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2306 #ifdef AFS_DEMAND_ATTACH_FS
2309 IncUInt64(&VStats.hdr_loads);
2310 IncUInt64(&vp->stats.hdr_loads);
2312 #endif /* AFS_DEMAND_ATTACH_FS */
2315 Log("VAttachVolume: Error reading diskDataHandle vol header %s; error=%u\n", path, *ec);
2318 #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 switch (vp->pending_vol_op->vol_op_state) {
2326 case FSSYNC_VolOpPending:
2327 /* this should never happen */
2328 assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpPending);
2331 case FSSYNC_VolOpRunningUnknown:
2332 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
2333 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
2336 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
2337 /* fall through to take volume offline */
2340 case FSSYNC_VolOpRunningOffline:
2341 /* mark the volume down */
2343 VChangeState_r(vp, VOL_STATE_UNATTACHED);
2344 if (V_offlineMessage(vp)[0] == '\0')
2345 strlcpy(V_offlineMessage(vp),
2346 "A volume utility is running.",
2347 sizeof(V_offlineMessage(vp)));
2348 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
2350 /* check to see if we should set the specialStatus flag */
2351 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
2352 vp->specialStatus = VBUSY;
2357 V_attachFlags(vp) |= VOL_HDR_LOADED;
2358 vp->stats.last_hdr_load = vp->stats.last_attach;
2360 #endif /* AFS_DEMAND_ATTACH_FS */
2363 struct IndexFileHeader iHead;
2365 #if OPENAFS_VOL_STATS
2367 * We just read in the diskstuff part of the header. If the detailed
2368 * volume stats area has not yet been initialized, we should bzero the
2369 * area and mark it as initialized.
2371 if (!(V_stat_initialized(vp))) {
2372 memset((char *)(V_stat_area(vp)), 0, VOL_STATS_BYTES);
2373 V_stat_initialized(vp) = 1;
2375 #endif /* OPENAFS_VOL_STATS */
2377 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
2378 (char *)&iHead, sizeof(iHead),
2379 SMALLINDEXMAGIC, SMALLINDEXVERSION);
2382 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
2387 struct IndexFileHeader iHead;
2389 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
2390 (char *)&iHead, sizeof(iHead),
2391 LARGEINDEXMAGIC, LARGEINDEXVERSION);
2394 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
2398 #ifdef AFS_NAMEI_ENV
2400 struct versionStamp stamp;
2402 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
2403 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
2406 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
2409 #endif /* AFS_NAMEI_ENV */
2411 #if defined(AFS_DEMAND_ATTACH_FS)
2412 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
2414 if (programType == fileServer) {
2415 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2418 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
2424 /* volume operation in progress */
2428 #else /* AFS_DEMAND_ATTACH_FS */
2430 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
2435 #endif /* AFS_DEMAND_ATTACH_FS */
2437 if (V_needsSalvaged(vp)) {
2438 if (vp->specialStatus)
2439 vp->specialStatus = 0;
2441 #if defined(AFS_DEMAND_ATTACH_FS)
2442 if (programType == fileServer) {
2443 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
2446 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
2450 #else /* AFS_DEMAND_ATTACH_FS */
2453 #endif /* AFS_DEMAND_ATTACH_FS */
2458 if (programType == fileServer) {
2459 #ifndef FAST_RESTART
2460 if (V_inUse(vp) && VolumeWriteable(vp)) {
2461 if (!V_needsSalvaged(vp)) {
2462 V_needsSalvaged(vp) = 1;
2463 VUpdateVolume_r(ec, vp, 0);
2465 #if defined(AFS_DEMAND_ATTACH_FS)
2466 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
2468 #else /* AFS_DEMAND_ATTACH_FS */
2469 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
2472 #endif /* AFS_DEMAND_ATTACH_FS */
2475 #endif /* FAST_RESTART */
2477 if (V_destroyMe(vp) == DESTROY_ME) {
2478 #if defined(AFS_DEMAND_ATTACH_FS)
2479 /* schedule a salvage so the volume goes away on disk */
2480 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2481 VChangeState_r(vp, VOL_STATE_ERROR);
2483 #endif /* AFS_DEMAND_ATTACH_FS */
2485 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
2491 vp->nextVnodeUnique = V_uniquifier(vp);
2492 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
2493 #ifndef BITMAP_LATER
2494 if (programType == fileServer && VolumeWriteable(vp)) {
2496 for (i = 0; i < nVNODECLASSES; i++) {
2497 VGetBitmap_r(ec, vp, i);
2499 #ifdef AFS_DEMAND_ATTACH_FS
2500 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2502 #else /* AFS_DEMAND_ATTACH_FS */
2504 #endif /* AFS_DEMAND_ATTACH_FS */
2505 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
2511 #endif /* BITMAP_LATER */
2513 if (programType == fileServer) {
2514 if (vp->specialStatus)
2515 vp->specialStatus = 0;
2516 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
2517 V_inUse(vp) = fileServer;
2518 V_offlineMessage(vp)[0] = '\0';
2521 if ((mode != V_PEEK) && (mode != V_SECRETLY))
2522 V_inUse(vp) = programType;
2523 V_checkoutMode(vp) = mode;
2526 AddVolumeToHashTable(vp, V_id(vp));
2527 #ifdef AFS_DEMAND_ATTACH_FS
2528 if ((programType != fileServer) ||
2529 (V_inUse(vp) == fileServer)) {
2530 AddVolumeToVByPList_r(vp);
2532 VChangeState_r(vp, VOL_STATE_ATTACHED);
2534 VChangeState_r(vp, VOL_STATE_UNATTACHED);
2540 /* Attach an existing volume.
2541 The volume also normally goes online at this time.
2542 An offline volume must be reattached to make it go online.
2546 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
2550 retVal = VAttachVolume_r(ec, volumeId, mode);
2556 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
2559 VGetVolumePath(ec, volumeId, &part, &name);
2561 register Volume *vp;
2563 vp = VGetVolume_r(&error, volumeId);
2565 assert(V_inUse(vp) == 0);
2566 VDetachVolume_r(ec, vp);
2570 return VAttachVolumeByName_r(ec, part, name, mode);
2573 /* Increment a reference count to a volume, sans context swaps. Requires
2574 * possibly reading the volume header in from the disk, since there's
2575 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
2577 * N.B. This call can fail if we can't read in the header!! In this case
2578 * we still guarantee we won't context swap, but the ref count won't be
2579 * incremented (otherwise we'd violate the invariant).
2581 /* NOTE: with the demand attach fileserver extensions, the global lock
2582 * is dropped within VHold */
2583 #ifdef AFS_DEMAND_ATTACH_FS
2585 VHold_r(register Volume * vp)
2589 VCreateReservation_r(vp);
2590 VWaitExclusiveState_r(vp);
2592 LoadVolumeHeader(&error, vp);
2594 VCancelReservation_r(vp);
2598 VCancelReservation_r(vp);
2601 #else /* AFS_DEMAND_ATTACH_FS */
2603 VHold_r(register Volume * vp)
2607 LoadVolumeHeader(&error, vp);
2613 #endif /* AFS_DEMAND_ATTACH_FS */
2617 VHold(register Volume * vp)
2621 retVal = VHold_r(vp);
2628 /***************************************************/
2629 /* get and put volume routines */
2630 /***************************************************/
2633 * put back a heavyweight reference to a volume object.
2635 * @param[in] vp volume object pointer
2637 * @pre VOL_LOCK held
2639 * @post heavyweight volume reference put back.
2640 * depending on state, volume may have been taken offline,
2641 * detached, salvaged, freed, etc.
2643 * @internal volume package internal use only
2646 VPutVolume_r(register Volume * vp)
2648 assert(--vp->nUsers >= 0);
2649 if (vp->nUsers == 0) {
2651 ReleaseVolumeHeader(vp->header);
2652 #ifdef AFS_DEMAND_ATTACH_FS
2653 if (!VCheckDetach(vp)) {
2657 #else /* AFS_DEMAND_ATTACH_FS */
2659 #endif /* AFS_DEMAND_ATTACH_FS */
2664 VPutVolume(register Volume * vp)
2672 /* Get a pointer to an attached volume. The pointer is returned regardless
2673 of whether or not the volume is in service or on/off line. An error
2674 code, however, is returned with an indication of the volume's status */
2676 VGetVolume(Error * ec, Error * client_ec, VolId volumeId)
2680 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
2686 VGetVolume_r(Error * ec, VolId volumeId)
2688 return GetVolume(ec, NULL, volumeId, NULL, 0);
2691 /* try to get a volume we've previously looked up */
2692 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
2694 VGetVolumeByVp_r(Error * ec, Volume * vp)
2696 return GetVolume(ec, NULL, vp->hashid, vp, 0);
2699 /* private interface for getting a volume handle
2700 * volumeId must be provided.
2701 * hint is an optional parameter to speed up hash lookups
2702 * flags is not used at this time
2704 /* for demand attach fs, caller MUST NOT hold a ref count on hint */
2706 GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint, int flags)
2709 /* pull this profiling/debugging code out of regular builds */
2711 #define VGET_CTR_INC(x) x++
2712 unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
2713 0, V7 = 0, V8 = 0, V9 = 0;
2714 unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
2716 #define VGET_CTR_INC(x)
2718 #ifdef AFS_DEMAND_ATTACH_FS
2719 Volume *avp, * rvp = hint;
2723 * if VInit is zero, the volume package dynamic
2724 * data structures have not been initialized yet,
2725 * and we must immediately return an error
2731 *client_ec = VOFFLINE;
2736 #ifdef AFS_DEMAND_ATTACH_FS
2738 VCreateReservation_r(rvp);
2740 #endif /* AFS_DEMAND_ATTACH_FS */
2748 vp = VLookupVolume_r(ec, volumeId, vp);
2754 #ifdef AFS_DEMAND_ATTACH_FS
2755 if (rvp && (rvp != vp)) {
2756 /* break reservation on old vp */
2757 VCancelReservation_r(rvp);
2760 #endif /* AFS_DEMAND_ATTACH_FS */
2766 /* Until we have reached an initialization level of 2
2767 * we don't know whether this volume exists or not.
2768 * We can't sleep and retry later because before a volume
2769 * is attached, the caller tries to get it first. Just
2770 * return VOFFLINE and the caller can choose whether to
2771 * retry the command or not. */
2781 IncUInt64(&VStats.hdr_gets);
2783 #ifdef AFS_DEMAND_ATTACH_FS
2784 /* block if someone else is performing an exclusive op on this volume */
2787 VCreateReservation_r(rvp);
2789 VWaitExclusiveState_r(vp);
2791 /* short circuit with VNOVOL in the following circumstances:
2794 * - VOL_STATE_SHUTTING_DOWN
2796 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
2797 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN) ||
2798 (V_attachState(vp) == VOL_STATE_GOING_OFFLINE)) {
2805 * short circuit with VOFFLINE in the following circumstances:
2807 * - VOL_STATE_UNATTACHED
2809 if (V_attachState(vp) == VOL_STATE_UNATTACHED) {
2810 if (vp->specialStatus) {
2811 *ec = vp->specialStatus;
2819 /* allowable states:
2825 if (vp->salvage.requested) {
2826 VUpdateSalvagePriority_r(vp);
2829 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
2830 avp = VAttachVolumeByVp_r(ec, vp, 0);
2833 /* VAttachVolumeByVp_r can return a pointer
2834 * != the vp passed to it under certain
2835 * conditions; make sure we don't leak
2836 * reservations if that happens */
2838 VCancelReservation_r(rvp);
2840 VCreateReservation_r(rvp);
2850 if (!vp->pending_vol_op) {
2865 if ((V_attachState(vp) == VOL_STATE_SALVAGING) ||
2866 (*ec == VSALVAGING)) {
2868 /* see CheckVnode() in afsfileprocs.c for an explanation
2869 * of this error code logic */
2870 afs_uint32 now = FT_ApproxTime();
2871 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
2874 *client_ec = VRESTARTING;
2883 LoadVolumeHeader(ec, vp);
2886 /* Only log the error if it was a totally unexpected error. Simply
2887 * a missing inode is likely to be caused by the volume being deleted */
2888 if (errno != ENXIO || LogLevel)
2889 Log("Volume %u: couldn't reread volume header\n",
2891 #ifdef AFS_DEMAND_ATTACH_FS
2892 if (programType == fileServer) {
2893 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2898 #else /* AFS_DEMAND_ATTACH_FS */
2901 #endif /* AFS_DEMAND_ATTACH_FS */
2905 #ifdef AFS_DEMAND_ATTACH_FS
2907 * this test MUST happen after the volume header is loaded
2910 /* only valid before/during demand attachment */
2911 assert(!vp->pending_vol_op || vp->pending_vol_op != FSSYNC_VolOpRunningUnknown);
2913 /* deny getvolume due to running mutually exclusive vol op */
2914 if (vp->pending_vol_op && vp->pending_vol_op->vol_op_state==FSSYNC_VolOpRunningOffline) {
2916 * volume cannot remain online during this volume operation.
2919 if (vp->specialStatus) {
2921 * special status codes outrank normal VOFFLINE code
2923 *ec = vp->specialStatus;
2925 *client_ec = vp->specialStatus;
2929 /* see CheckVnode() in afsfileprocs.c for an explanation
2930 * of this error code logic */
2931 afs_uint32 now = FT_ApproxTime();
2932 if ((vp->stats.last_vol_op + (10 * 60)) >= now) {
2935 *client_ec = VRESTARTING;
2940 VChangeState_r(vp, VOL_STATE_UNATTACHED);
2941 FreeVolumeHeader(vp);
2945 #endif /* AFS_DEMAND_ATTACH_FS */
2948 if (vp->shuttingDown) {
2955 if (programType == fileServer) {
2957 if (vp->goingOffline) {
2959 #ifdef AFS_DEMAND_ATTACH_FS
2960 /* wait for the volume to go offline */
2961 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
2962 VWaitStateChange_r(vp);
2964 #elif defined(AFS_PTHREAD_ENV)
2965 VOL_CV_WAIT(&vol_put_volume_cond);
2966 #else /* AFS_PTHREAD_ENV */
2967 LWP_WaitProcess(VPutVolume);
2968 #endif /* AFS_PTHREAD_ENV */
2971 if (vp->specialStatus) {
2973 *ec = vp->specialStatus;
2974 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
2977 } else if (V_inUse(vp) == 0) {
2988 #ifdef AFS_DEMAND_ATTACH_FS
2989 /* if no error, bump nUsers */
2992 VLRU_UpdateAccess_r(vp);
2995 VCancelReservation_r(rvp);
2998 if (client_ec && !*client_ec) {
3001 #else /* AFS_DEMAND_ATTACH_FS */
3002 /* if no error, bump nUsers */
3009 #endif /* AFS_DEMAND_ATTACH_FS */
3017 /***************************************************/
3018 /* Volume offline/detach routines */
3019 /***************************************************/
3021 /* caller MUST hold a heavyweight ref on vp */
3022 #ifdef AFS_DEMAND_ATTACH_FS
3024 VTakeOffline_r(register Volume * vp)
3028 assert(vp->nUsers > 0);
3029 assert(programType == fileServer);
3031 VCreateReservation_r(vp);
3032 VWaitExclusiveState_r(vp);
3034 vp->goingOffline = 1;
3035 V_needsSalvaged(vp) = 1;
3037 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
3038 VCancelReservation_r(vp);
3040 #else /* AFS_DEMAND_ATTACH_FS */
3042 VTakeOffline_r(register Volume * vp)
3044 assert(vp->nUsers > 0);
3045 assert(programType == fileServer);
3047 vp->goingOffline = 1;
3048 V_needsSalvaged(vp) = 1;
3050 #endif /* AFS_DEMAND_ATTACH_FS */
3053 VTakeOffline(register Volume * vp)
3061 * force a volume offline.
3063 * @param[in] vp volume object pointer
3064 * @param[in] flags flags (see note below)
3066 * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
3067 * used when VUpdateVolume_r needs to call VForceOffline_r
3068 * (which in turn would normally call VUpdateVolume_r)
3070 * @see VUpdateVolume_r
3072 * @pre VOL_LOCK must be held.
3073 * for DAFS, caller must hold ref.
3075 * @note for DAFS, it _is safe_ to call this function from an
3078 * @post needsSalvaged flag is set.
3079 * for DAFS, salvage is requested.
3080 * no further references to the volume through the volume
3081 * package will be honored.
3082 * all file descriptor and vnode caches are invalidated.
3084 * @warning this is a heavy-handed interface. it results in
3085 * a volume going offline regardless of the current
3086 * reference count state.
3088 * @internal volume package internal use only
3091 VForceOffline_r(Volume * vp, int flags)
3095 #ifdef AFS_DEMAND_ATTACH_FS
3096 VChangeState_r(vp, VOL_STATE_ERROR);
3101 strcpy(V_offlineMessage(vp),
3102 "Forced offline due to internal error: volume needs to be salvaged");
3103 Log("Volume %u forced offline: it needs salvaging!\n", V_id(vp));
3106 vp->goingOffline = 0;
3107 V_needsSalvaged(vp) = 1;
3108 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
3109 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
3112 #ifdef AFS_DEMAND_ATTACH_FS
3113 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3114 #endif /* AFS_DEMAND_ATTACH_FS */
3116 #ifdef AFS_PTHREAD_ENV
3117 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3118 #else /* AFS_PTHREAD_ENV */
3119 LWP_NoYieldSignal(VPutVolume);
3120 #endif /* AFS_PTHREAD_ENV */
3122 VReleaseVolumeHandles_r(vp);
3126 * force a volume offline.
3128 * @param[in] vp volume object pointer
3130 * @see VForceOffline_r
3133 VForceOffline(Volume * vp)
3136 VForceOffline_r(vp, 0);
3140 /* The opposite of VAttachVolume. The volume header is written to disk, with
3141 the inUse bit turned off. A copy of the header is maintained in memory,
3142 however (which is why this is VOffline, not VDetach).
3145 VOffline_r(Volume * vp, char *message)
3148 VolumeId vid = V_id(vp);
3150 assert(programType != volumeUtility);
3155 if (V_offlineMessage(vp)[0] == '\0')
3156 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
3157 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
3159 vp->goingOffline = 1;
3160 #ifdef AFS_DEMAND_ATTACH_FS
3161 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
3162 VCreateReservation_r(vp);
3165 /* wait for the volume to go offline */
3166 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
3167 VWaitStateChange_r(vp);
3169 VCancelReservation_r(vp);
3170 #else /* AFS_DEMAND_ATTACH_FS */
3172 vp = VGetVolume_r(&error, vid); /* Wait for it to go offline */
3173 if (vp) /* In case it was reattached... */
3175 #endif /* AFS_DEMAND_ATTACH_FS */
3178 #ifdef AFS_DEMAND_ATTACH_FS
3180 * Take a volume offline in order to perform a volume operation.
3182 * @param[inout] ec address in which to store error code
3183 * @param[in] vp volume object pointer
3184 * @param[in] message volume offline status message
3187 * - VOL_LOCK is held
3188 * - caller MUST hold a heavyweight ref on vp
3191 * - volume is taken offline
3192 * - if possible, volume operation is promoted to running state
3193 * - on failure, *ec is set to nonzero
3195 * @note Although this function does not return any value, it may
3196 * still fail to promote our pending volume operation to
3197 * a running state. Any caller MUST check the value of *ec,
3198 * and MUST NOT blindly assume success.
3200 * @warning if the caller does not hold a lightweight ref on vp,
3201 * then it MUST NOT reference vp after this function
3202 * returns to the caller.
3204 * @internal volume package internal use only
3207 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
3209 assert(vp->pending_vol_op);
3215 if (V_offlineMessage(vp)[0] == '\0')
3216 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
3217 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
3219 vp->goingOffline = 1;
3220 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
3221 VCreateReservation_r(vp);
3224 /* Wait for the volume to go offline */
3225 while (!VIsOfflineState(V_attachState(vp))) {
3226 /* do not give corrupted volumes to the volserver */
3227 if (vp->salvage.requested && vp->pending_vol_op->com.programType != salvageServer) {
3231 VWaitStateChange_r(vp);
3235 VCancelReservation_r(vp);
3237 #endif /* AFS_DEMAND_ATTACH_FS */
3240 VOffline(Volume * vp, char *message)
3243 VOffline_r(vp, message);
3247 /* This gets used for the most part by utility routines that don't want
3248 * to keep all the volume headers around. Generally, the file server won't
3249 * call this routine, because then the offline message in the volume header
3250 * (or other information) won't be available to clients. For NAMEI, also
3251 * close the file handles. However, the fileserver does call this during
3252 * an attach following a volume operation.
3255 VDetachVolume_r(Error * ec, Volume * vp)
3258 struct DiskPartition64 *tpartp;
3259 int notifyServer = 0;
3260 int useDone = FSYNC_VOL_ON;
3262 *ec = 0; /* always "succeeds" */
3263 if (programType == volumeUtility) {
3264 notifyServer = vp->needsPutBack;
3265 if (V_destroyMe(vp) == DESTROY_ME)
3266 useDone = FSYNC_VOL_DONE;
3267 #ifdef AFS_DEMAND_ATTACH_FS
3268 else if (!V_blessed(vp) || !V_inService(vp))
3269 useDone = FSYNC_VOL_LEAVE_OFF;
3272 tpartp = vp->partition;
3274 DeleteVolumeFromHashTable(vp);
3275 vp->shuttingDown = 1;
3276 #ifdef AFS_DEMAND_ATTACH_FS
3277 DeleteVolumeFromVByPList_r(vp);
3279 VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
3281 if (programType != fileServer)
3283 #endif /* AFS_DEMAND_ATTACH_FS */
3285 /* Will be detached sometime in the future--this is OK since volume is offline */
3287 /* XXX the following code should really be moved to VCheckDetach() since the volume
3288 * is not technically detached until the refcounts reach zero
3290 #ifdef FSSYNC_BUILD_CLIENT
3291 if (programType == volumeUtility && notifyServer) {
3293 * Note: The server is not notified in the case of a bogus volume
3294 * explicitly to make it possible to create a volume, do a partial
3295 * restore, then abort the operation without ever putting the volume
3296 * online. This is essential in the case of a volume move operation
3297 * between two partitions on the same server. In that case, there
3298 * would be two instances of the same volume, one of them bogus,
3299 * which the file server would attempt to put on line
3301 FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
3302 /* XXX this code path is only hit by volume utilities, thus
3303 * V_BreakVolumeCallbacks will always be NULL. if we really
3304 * want to break callbacks in this path we need to use FSYNC_VolOp() */
3306 /* Dettaching it so break all callbacks on it */
3307 if (V_BreakVolumeCallbacks) {
3308 Log("volume %u detached; breaking all call backs\n", volume);
3309 (*V_BreakVolumeCallbacks) (volume);
3313 #endif /* FSSYNC_BUILD_CLIENT */
3317 VDetachVolume(Error * ec, Volume * vp)
3320 VDetachVolume_r(ec, vp);
3325 /***************************************************/
3326 /* Volume fd/inode handle closing routines */
3327 /***************************************************/
3329 /* For VDetachVolume, we close all cached file descriptors, but keep
3330 * the Inode handles in case we need to read from a busy volume.
3332 /* for demand attach, caller MUST hold ref count on vp */
3334 VCloseVolumeHandles_r(Volume * vp)
3336 #ifdef AFS_DEMAND_ATTACH_FS
3337 VolState state_save;
3339 state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
3344 * XXX need to investigate whether we can perform
3345 * DFlushVolume outside of vol_glock_mutex...
3347 * VCloseVnodeFiles_r drops the glock internally */
3348 DFlushVolume(V_id(vp));
3349 VCloseVnodeFiles_r(vp);
3351 #ifdef AFS_DEMAND_ATTACH_FS
3355 /* Too time consuming and unnecessary for the volserver */
3356 if (programType != volumeUtility) {
3357 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
3358 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
3359 IH_CONDSYNC(vp->diskDataHandle);
3361 IH_CONDSYNC(vp->linkHandle);
3362 #endif /* AFS_NT40_ENV */
3365 IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
3366 IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
3367 IH_REALLYCLOSE(vp->diskDataHandle);
3368 IH_REALLYCLOSE(vp->linkHandle);
3370 #ifdef AFS_DEMAND_ATTACH_FS
3372 VChangeState_r(vp, state_save);
3376 /* For both VForceOffline and VOffline, we close all relevant handles.
3377 * For VOffline, if we re-attach the volume, the files may possible be
3378 * different than before.
3380 /* for demand attach, caller MUST hold a ref count on vp */
3382 VReleaseVolumeHandles_r(Volume * vp)
3384 #ifdef AFS_DEMAND_ATTACH_FS
3385 VolState state_save;
3387 state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
3390 /* XXX need to investigate whether we can perform
3391 * DFlushVolume outside of vol_glock_mutex... */
3392 DFlushVolume(V_id(vp));
3394 VReleaseVnodeFiles_r(vp); /* releases the glock internally */
3396 #ifdef AFS_DEMAND_ATTACH_FS
3400 /* Too time consuming and unnecessary for the volserver */
3401 if (programType != volumeUtility) {
3402 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
3403 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
3404 IH_CONDSYNC(vp->diskDataHandle);
3406 IH_CONDSYNC(vp->linkHandle);
3407 #endif /* AFS_NT40_ENV */
3410 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
3411 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
3412 IH_RELEASE(vp->diskDataHandle);
3413 IH_RELEASE(vp->linkHandle);
3415 #ifdef AFS_DEMAND_ATTACH_FS
3417 VChangeState_r(vp, state_save);
3422 /***************************************************/
3423 /* Volume write and fsync routines */
3424 /***************************************************/
3427 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
3429 #ifdef AFS_DEMAND_ATTACH_FS
3430 VolState state_save;
3432 if (flags & VOL_UPDATE_WAIT) {
3433 VCreateReservation_r(vp);
3434 VWaitExclusiveState_r(vp);
3439 if (programType == fileServer)
3441 (V_inUse(vp) ? V_nextVnodeUnique(vp) +
3442 200 : V_nextVnodeUnique(vp));
3444 #ifdef AFS_DEMAND_ATTACH_FS
3445 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
3449 WriteVolumeHeader_r(ec, vp);
3451 #ifdef AFS_DEMAND_ATTACH_FS
3453 VChangeState_r(vp, state_save);
3454 if (flags & VOL_UPDATE_WAIT) {
3455 VCancelReservation_r(vp);
3460 Log("VUpdateVolume: error updating volume header, volume %u (%s)\n",
3461 V_id(vp), V_name(vp));
3462 /* try to update on-disk header,
3463 * while preventing infinite recursion */
3464 if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
3465 VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
3471 VUpdateVolume(Error * ec, Volume * vp)
3474 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
3479 VSyncVolume_r(Error * ec, Volume * vp, int flags)
3483 #ifdef AFS_DEMAND_ATTACH_FS
3484 VolState state_save;
3487 if (flags & VOL_SYNC_WAIT) {
3488 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
3490 VUpdateVolume_r(ec, vp, 0);
3493 #ifdef AFS_DEMAND_ATTACH_FS
3494 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
3497 fdP = IH_OPEN(V_diskDataHandle(vp));
3498 assert(fdP != NULL);
3499 code = FDH_SYNC(fdP);
3502 #ifdef AFS_DEMAND_ATTACH_FS
3504 VChangeState_r(vp, state_save);
3510 VSyncVolume(Error * ec, Volume * vp)
3513 VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
3518 /***************************************************/
3519 /* Volume dealloaction routines */
3520 /***************************************************/
3522 #ifdef AFS_DEMAND_ATTACH_FS
3524 FreeVolume(Volume * vp)
3526 /* free the heap space, iff it's safe.
3527 * otherwise, pull it out of the hash table, so it
3528 * will get deallocated when all refs to it go away */
3529 if (!VCheckFree(vp)) {
3530 DeleteVolumeFromHashTable(vp);
3531 DeleteVolumeFromVByPList_r(vp);
3533 /* make sure we invalidate the header cache entry */
3534 FreeVolumeHeader(vp);
3537 #endif /* AFS_DEMAND_ATTACH_FS */
3540 ReallyFreeVolume(Volume * vp)
3545 #ifdef AFS_DEMAND_ATTACH_FS
3547 VChangeState_r(vp, VOL_STATE_FREED);
3548 if (vp->pending_vol_op)
3549 free(vp->pending_vol_op);
3550 #endif /* AFS_DEMAND_ATTACH_FS */
3551 for (i = 0; i < nVNODECLASSES; i++)
3552 if (vp->vnodeIndex[i].bitmap)
3553 free(vp->vnodeIndex[i].bitmap);
3554 FreeVolumeHeader(vp);
3555 #ifndef AFS_DEMAND_ATTACH_FS
3556 DeleteVolumeFromHashTable(vp);
3557 #endif /* AFS_DEMAND_ATTACH_FS */
3561 /* check to see if we should shutdown this volume
3562 * returns 1 if volume was freed, 0 otherwise */
3563 #ifdef AFS_DEMAND_ATTACH_FS
3565 VCheckDetach(register Volume * vp)
3570 if (vp->nUsers || vp->nWaiters)
3573 if (vp->shuttingDown) {
3575 if ((programType != fileServer) &&
3576 (V_inUse(vp) == programType) &&
3577 ((V_checkoutMode(vp) == V_VOLUPD) ||
3578 (V_checkoutMode(vp) == V_SECRETLY) ||
3579 ((V_checkoutMode(vp) == V_CLONE) &&
3580 (VolumeWriteable(vp))))) {
3582 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
3584 Log("VCheckDetach: volume header update for volume %u "
3585 "failed with errno %d\n", vp->hashid, errno);
3588 VReleaseVolumeHandles_r(vp);
3590 ReallyFreeVolume(vp);
3591 if (programType == fileServer) {
3592 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3597 #else /* AFS_DEMAND_ATTACH_FS */
3599 VCheckDetach(register Volume * vp)
3607 if (vp->shuttingDown) {
3609 if ((programType != fileServer) &&
3610 (V_inUse(vp) == programType) &&
3611 ((V_checkoutMode(vp) == V_VOLUPD) ||
3612 (V_checkoutMode(vp) == V_SECRETLY) ||
3613 ((V_checkoutMode(vp) == V_CLONE) &&
3614 (VolumeWriteable(vp))))) {
3616 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
3618 Log("VCheckDetach: volume header update for volume %u failed with errno %d\n",
3622 VReleaseVolumeHandles_r(vp);
3623 ReallyFreeVolume(vp);
3624 if (programType == fileServer) {
3625 #if defined(AFS_PTHREAD_ENV)
3626 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3627 #else /* AFS_PTHREAD_ENV */
3628 LWP_NoYieldSignal(VPutVolume);
3629 #endif /* AFS_PTHREAD_ENV */
3634 #endif /* AFS_DEMAND_ATTACH_FS */
3636 /* check to see if we should offline this volume
3637 * return 1 if volume went offline, 0 otherwise */
3638 #ifdef AFS_DEMAND_ATTACH_FS
3640 VCheckOffline(register Volume * vp)
3644 if (vp->goingOffline && !vp->nUsers) {
3646 assert(programType == fileServer);
3647 assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
3648 (V_attachState(vp) != VOL_STATE_FREED) &&
3649 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
3650 (V_attachState(vp) != VOL_STATE_UNATTACHED));
3654 * VOL_STATE_GOING_OFFLINE
3655 * VOL_STATE_SHUTTING_DOWN
3656 * VIsErrorState(V_attachState(vp))
3657 * VIsExclusiveState(V_attachState(vp))
3660 VCreateReservation_r(vp);
3661 VChangeState_r(vp, VOL_STATE_OFFLINING);
3664 /* must clear the goingOffline flag before we drop the glock */
3665 vp->goingOffline = 0;
3670 /* perform async operations */
3671 VUpdateVolume_r(&error, vp, 0);
3672 VCloseVolumeHandles_r(vp);
3675 Log("VOffline: Volume %u (%s) is now offline", V_id(vp),
3677 if (V_offlineMessage(vp)[0])
3678 Log(" (%s)", V_offlineMessage(vp));
3682 /* invalidate the volume header cache entry */
3683 FreeVolumeHeader(vp);
3685 /* if nothing changed state to error or salvaging,
3686 * drop state to unattached */
3687 if (!VIsErrorState(V_attachState(vp))) {
3688 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3690 VCancelReservation_r(vp);
3691 /* no usage of vp is safe beyond this point */
3695 #else /* AFS_DEMAND_ATTACH_FS */
3697 VCheckOffline(register Volume * vp)
3699 Volume * rvp = NULL;
3702 if (vp->goingOffline && !vp->nUsers) {
3704 assert(programType == fileServer);
3707 vp->goingOffline = 0;
3709 VUpdateVolume_r(&error, vp, 0);
3710 VCloseVolumeHandles_r(vp);
3712 Log("VOffline: Volume %u (%s) is now offline", V_id(vp),
3714 if (V_offlineMessage(vp)[0])
3715 Log(" (%s)", V_offlineMessage(vp));
3718 FreeVolumeHeader(vp);
3719 #ifdef AFS_PTHREAD_ENV
3720 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3721 #else /* AFS_PTHREAD_ENV */
3722 LWP_NoYieldSignal(VPutVolume);
3723 #endif /* AFS_PTHREAD_ENV */
3727 #endif /* AFS_DEMAND_ATTACH_FS */
3729 /***************************************************/
3730 /* demand attach fs ref counting routines */
3731 /***************************************************/
3733 #ifdef AFS_DEMAND_ATTACH_FS
3734 /* the following two functions handle reference counting for
3735 * asynchronous operations on volume structs.
3737 * their purpose is to prevent a VDetachVolume or VShutdown
3738 * from free()ing the Volume struct during an async i/o op */
3740 /* register with the async volume op ref counter */
3741 /* VCreateReservation_r moved into inline code header because it
3742 * is now needed in vnode.c -- tkeiser 11/20/2007
3746 * decrement volume-package internal refcount.
3748 * @param vp volume object pointer
3750 * @internal volume package internal use only
3753 * @arg VOL_LOCK is held
3754 * @arg lightweight refcount held
3756 * @post volume waiters refcount is decremented; volume may
3757 * have been deallocated/shutdown/offlined/salvaged/
3758 * whatever during the process
3760 * @warning once you have tossed your last reference (you can acquire
3761 * lightweight refs recursively) it is NOT SAFE to reference
3762 * a volume object pointer ever again
3764 * @see VCreateReservation_r
3766 * @note DEMAND_ATTACH_FS only
3769 VCancelReservation_r(Volume * vp)
3771 assert(--vp->nWaiters >= 0);
3772 if (vp->nWaiters == 0) {
3774 if (!VCheckDetach(vp)) {
3781 /* check to see if we should free this volume now
3782 * return 1 if volume was freed, 0 otherwise */
3784 VCheckFree(Volume * vp)
3787 if ((vp->nUsers == 0) &&
3788 (vp->nWaiters == 0) &&
3789 !(V_attachFlags(vp) & (VOL_IN_HASH |
3793 ReallyFreeVolume(vp);
3798 #endif /* AFS_DEMAND_ATTACH_FS */
3801 /***************************************************/
3802 /* online volume operations routines */
3803 /***************************************************/
3805 #ifdef AFS_DEMAND_ATTACH_FS
3807 * register a volume operation on a given volume.
3809 * @param[in] vp volume object
3810 * @param[in] vopinfo volume operation info object
3812 * @pre VOL_LOCK is held
3814 * @post volume operation info object attached to volume object.
3815 * volume operation statistics updated.
3817 * @note by "attached" we mean a copy of the passed in object is made
3819 * @internal volume package internal use only
3822 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3824 FSSYNC_VolOp_info * info;
3826 /* attach a vol op info node to the volume struct */
3827 info = (FSSYNC_VolOp_info *) malloc(sizeof(FSSYNC_VolOp_info));
3828 assert(info != NULL);
3829 memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
3830 vp->pending_vol_op = info;
3833 vp->stats.last_vol_op = FT_ApproxTime();
3834 vp->stats.vol_ops++;
3835 IncUInt64(&VStats.vol_ops);
3841 * deregister the volume operation attached to this volume.
3843 * @param[in] vp volume object pointer
3845 * @pre VOL_LOCK is held
3847 * @post the volume operation info object is detached from the volume object
3849 * @internal volume package internal use only
3852 VDeregisterVolOp_r(Volume * vp)
3854 if (vp->pending_vol_op) {
3855 free(vp->pending_vol_op);
3856 vp->pending_vol_op = NULL;
3860 #endif /* AFS_DEMAND_ATTACH_FS */
3863 * determine whether it is safe to leave a volume online during
3864 * the volume operation described by the vopinfo object.
3866 * @param[in] vp volume object
3867 * @param[in] vopinfo volume operation info object
3869 * @return whether it is safe to leave volume online
3870 * @retval 0 it is NOT SAFE to leave the volume online
3871 * @retval 1 it is safe to leave the volume online during the operation
3874 * @arg VOL_LOCK is held
3875 * @arg disk header attached to vp (heavyweight ref on vp will guarantee
3876 * this condition is met)
3878 * @internal volume package internal use only
3881 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3883 return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
3884 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
3885 (vopinfo->com.reason == V_READONLY ||
3886 (!VolumeWriteable(vp) &&
3887 (vopinfo->com.reason == V_CLONE ||
3888 vopinfo->com.reason == V_DUMP)))));
3892 * determine whether VBUSY should be set during this volume operation.
3894 * @param[in] vp volume object
3895 * @param[in] vopinfo volume operation info object
3897 * @return whether VBUSY should be set
3898 * @retval 0 VBUSY does NOT need to be set
3899 * @retval 1 VBUSY SHOULD be set
3901 * @pre VOL_LOCK is held
3903 * @internal volume package internal use only
3906 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3908 return ((vopinfo->com.command == FSYNC_VOL_OFF &&
3909 vopinfo->com.reason == FSYNC_SALVAGE) ||
3910 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
3911 (vopinfo->com.reason == V_CLONE ||
3912 vopinfo->com.reason == V_DUMP)));
3916 /***************************************************/
3917 /* online salvager routines */
3918 /***************************************************/
3919 #if defined(AFS_DEMAND_ATTACH_FS)
3920 #define SALVAGE_PRIO_UPDATE_INTERVAL 3 /**< number of seconds between prio updates */
3921 #define SALVAGE_COUNT_MAX 16 /**< number of online salvages we
3922 * allow before moving the volume
3923 * into a permanent error state
3925 * once this threshold is reached,
3926 * the operator will have to manually
3927 * issue a 'bos salvage' to bring
3928 * the volume back online
3932 * check whether a salvage needs to be performed on this volume.
3934 * @param[in] vp pointer to volume object
3936 * @return status code
3937 * @retval 0 no salvage scheduled
3938 * @retval 1 a salvage has been scheduled with the salvageserver
3940 * @pre VOL_LOCK is held
3942 * @post if salvage request flag is set and nUsers and nWaiters are zero,
3943 * then a salvage will be requested
3945 * @note this is one of the event handlers called by VCancelReservation_r
3947 * @see VCancelReservation_r
3949 * @internal volume package internal use only.
3952 VCheckSalvage(register Volume * vp)
3955 #ifdef SALVSYNC_BUILD_CLIENT
3956 if (vp->nUsers || vp->nWaiters)
3958 if (vp->salvage.requested) {
3959 VScheduleSalvage_r(vp);
3962 #endif /* SALVSYNC_BUILD_CLIENT */
3967 * request volume salvage.
3969 * @param[out] ec computed client error code
3970 * @param[in] vp volume object pointer
3971 * @param[in] reason reason code (passed to salvageserver via SALVSYNC)
3972 * @param[in] flags see flags note below
3975 * VOL_SALVAGE_INVALIDATE_HEADER causes volume header cache entry
3976 * to be invalidated.
3978 * @pre VOL_LOCK is held.
3980 * @post volume state is changed.
3981 * for fileserver, salvage will be requested once refcount reaches zero.
3983 * @return operation status code
3984 * @retval 0 volume salvage will occur
3985 * @retval 1 volume salvage could not be scheduled
3987 * @note DAFS fileserver only
3989 * @note this call does not synchronously schedule a volume salvage. rather,
3990 * it sets volume state so that when volume refcounts reach zero, a
3991 * volume salvage will occur. by "refcounts", we mean both nUsers and
3992 * nWaiters must be zero.
3994 * @internal volume package internal use only.
3997 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
4001 * for DAFS volume utilities, transition to error state
4002 * (at some point in the future, we should consider
4003 * making volser talk to salsrv)
4005 if (programType != fileServer) {
4006 VChangeState_r(vp, VOL_STATE_ERROR);
4011 if (!vp->salvage.requested) {
4012 vp->salvage.requested = 1;
4013 vp->salvage.reason = reason;
4014 vp->stats.last_salvage = FT_ApproxTime();
4015 if (flags & VOL_SALVAGE_INVALIDATE_HEADER) {
4016 /* Instead of ReleaseVolumeHeader, we do FreeVolumeHeader()
4017 so that the the next VAttachVolumeByVp_r() invocation
4018 of attach2() will pull in a cached header
4019 entry and fail, then load a fresh one from disk and attach
4022 FreeVolumeHeader(vp);
4024 if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
4025 VChangeState_r(vp, VOL_STATE_SALVAGING);
4028 Log("VRequestSalvage: volume %u online salvaged too many times; forced offline.\n", vp->hashid);
4029 VChangeState_r(vp, VOL_STATE_ERROR);
4038 * update salvageserver scheduling priority for a volume.
4040 * @param[in] vp pointer to volume object
4042 * @return operation status
4044 * @retval 1 request denied, or SALVSYNC communications failure
4046 * @pre VOL_LOCK is held.
4048 * @post in-core salvage priority counter is incremented. if at least
4049 * SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
4050 * last SALVSYNC_RAISEPRIO request, we contact the salvageserver
4051 * to update its priority queue. if no salvage is scheduled,
4052 * this function is a no-op.
4054 * @note DAFS fileserver only
4056 * @note this should be called whenever a VGetVolume fails due to a
4057 * pending salvage request
4059 * @todo should set exclusive state and drop glock around salvsync call
4061 * @internal volume package internal use only.
4064 VUpdateSalvagePriority_r(Volume * vp)
4069 #ifdef SALVSYNC_BUILD_CLIENT
4071 now = FT_ApproxTime();
4073 /* update the salvageserver priority queue occasionally so that
4074 * frequently requested volumes get moved to the head of the queue
4076 if ((vp->salvage.scheduled) &&
4077 (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
4078 code = SALVSYNC_SalvageVolume(vp->hashid,
4079 VPartitionPath(vp->partition),
4084 vp->stats.last_salvage_req = now;
4085 if (code != SYNC_OK) {
4089 #endif /* SALVSYNC_BUILD_CLIENT */
4095 * schedule a salvage with the salvage server.
4097 * @param[in] vp pointer to volume object
4099 * @return operation status
4100 * @retval 0 salvage scheduled successfully
4101 * @retval 1 salvage not scheduled, or SALVSYNC com error
4104 * @arg VOL_LOCK is held.
4105 * @arg nUsers and nWaiters should be zero.
4107 * @post salvageserver is sent a salvage request
4109 * @note DAFS fileserver only
4111 * @internal volume package internal use only.
4114 VScheduleSalvage_r(Volume * vp)
4117 #ifdef SALVSYNC_BUILD_CLIENT
4118 VolState state_save;
4119 VThreadOptions_t * thread_opts;
4122 if (vp->nWaiters || vp->nUsers) {
4126 /* prevent endless salvage,attach,salvage,attach,... loops */
4127 if (vp->stats.salvages >= SALVAGE_COUNT_MAX)
4131 * don't perform salvsync ops on certain threads
4133 thread_opts = pthread_getspecific(VThread_key);
4134 if (thread_opts == NULL) {
4135 thread_opts = &VThread_defaults;
4137 if (thread_opts->disallow_salvsync) {
4142 * XXX the scheduling process should really be done asynchronously
4143 * to avoid fssync deadlocks
4145 if (!vp->salvage.scheduled) {
4146 /* if we haven't previously scheduled a salvage, do so now
4148 * set the volume to an exclusive state and drop the lock
4149 * around the SALVSYNC call
4151 * note that we do NOT acquire a reservation here -- doing so
4152 * could result in unbounded recursion
4154 strlcpy(partName, VPartitionPath(vp->partition), sizeof(partName));
4155 state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
4158 /* can't use V_id() since there's no guarantee
4159 * we have the disk data header at this point */
4160 code = SALVSYNC_SalvageVolume(vp->hashid,
4167 VChangeState_r(vp, state_save);
4169 if (code == SYNC_OK) {
4170 vp->salvage.scheduled = 1;
4171 vp->stats.salvages++;
4172 vp->stats.last_salvage_req = FT_ApproxTime();
4173 IncUInt64(&VStats.salvages);
4177 case SYNC_BAD_COMMAND:
4178 case SYNC_COM_ERROR:
4181 Log("VScheduleSalvage_r: SALVSYNC request denied\n");
4184 Log("VScheduleSalvage_r: SALVSYNC unknown protocol error\n");
4189 #endif /* SALVSYNC_BUILD_CLIENT */
4194 * ask salvageserver to cancel a scheduled salvage operation.
4196 * @param[in] vp pointer to volume object
4197 * @param[in] reason SALVSYNC protocol reason code
4199 * @return operation status
4201 * @retval 1 request failed
4203 * @pre VOL_LOCK is held.
4205 * @post salvageserver is sent a request to cancel the volume salvage.
4206 * volume is transitioned to a hard error state.
4208 * @internal volume package internal use only.
4211 VCancelSalvage_r(Volume * vp, int reason)
4215 #ifdef SALVSYNC_BUILD_CLIENT
4216 if (vp->salvage.scheduled) {
4217 VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
4220 /* can't use V_id() since there's no guarantee
4221 * we have the disk data header at this point */
4222 code = SALVSYNC_SalvageVolume(vp->hashid,
4223 VPartitionPath(vp->partition),
4230 VChangeState_r(vp, VOL_STATE_ERROR);
4232 if (code == SYNC_OK) {
4233 vp->salvage.scheduled = 0;
4234 vp->salvage.requested = 0;
4239 #endif /* SALVSYNC_BUILD_CLIENT */
4244 #ifdef SALVSYNC_BUILD_CLIENT
4246 * connect to the salvageserver SYNC service.
4248 * @return operation status
4252 * @post connection to salvageserver SYNC service established
4254 * @see VConnectSALV_r
4255 * @see VDisconnectSALV
4256 * @see VReconnectSALV
4263 retVal = VConnectSALV_r();
4269 * connect to the salvageserver SYNC service.
4271 * @return operation status
4275 * @pre VOL_LOCK is held.
4277 * @post connection to salvageserver SYNC service established
4280 * @see VDisconnectSALV_r
4281 * @see VReconnectSALV_r
4282 * @see SALVSYNC_clientInit
4284 * @internal volume package internal use only.
4287 VConnectSALV_r(void)
4289 return SALVSYNC_clientInit();
4293 * disconnect from the salvageserver SYNC service.
4295 * @return operation status
4298 * @pre client should have a live connection to the salvageserver
4300 * @post connection to salvageserver SYNC service destroyed
4302 * @see VDisconnectSALV_r
4304 * @see VReconnectSALV
4307 VDisconnectSALV(void)
4311 VDisconnectSALV_r();
4317 * disconnect from the salvageserver SYNC service.
4319 * @return operation status
4323 * @arg VOL_LOCK is held.
4324 * @arg client should have a live connection to the salvageserver.
4326 * @post connection to salvageserver SYNC service destroyed
4328 * @see VDisconnectSALV
4329 * @see VConnectSALV_r
4330 * @see VReconnectSALV_r
4331 * @see SALVSYNC_clientFinis
4333 * @internal volume package internal use only.
4336 VDisconnectSALV_r(void)
4338 return SALVSYNC_clientFinis();
4342 * disconnect and then re-connect to the salvageserver SYNC service.
4344 * @return operation status
4348 * @pre client should have a live connection to the salvageserver
4350 * @post old connection is dropped, and a new one is established
4353 * @see VDisconnectSALV
4354 * @see VReconnectSALV_r
4357 VReconnectSALV(void)
4361 retVal = VReconnectSALV_r();
4367 * disconnect and then re-connect to the salvageserver SYNC service.
4369 * @return operation status
4374 * @arg VOL_LOCK is held.
4375 * @arg client should have a live connection to the salvageserver.
4377 * @post old connection is dropped, and a new one is established
4379 * @see VConnectSALV_r
4380 * @see VDisconnectSALV
4381 * @see VReconnectSALV
4382 * @see SALVSYNC_clientReconnect
4384 * @internal volume package internal use only.
4387 VReconnectSALV_r(void)
4389 return SALVSYNC_clientReconnect();
4391 #endif /* SALVSYNC_BUILD_CLIENT */
4392 #endif /* AFS_DEMAND_ATTACH_FS */
4395 /***************************************************/
4396 /* FSSYNC routines */
4397 /***************************************************/
4399 /* This must be called by any volume utility which needs to run while the
4400 file server is also running. This is separated from VInitVolumePackage so
4401 that a utility can fork--and each of the children can independently
4402 initialize communication with the file server */
4403 #ifdef FSSYNC_BUILD_CLIENT
4405 * connect to the fileserver SYNC service.
4407 * @return operation status
4412 * @arg VInit must equal 2.
4413 * @arg Program Type must not be fileserver or salvager.
4415 * @post connection to fileserver SYNC service established
4418 * @see VDisconnectFS
4419 * @see VChildProcReconnectFS
4426 retVal = VConnectFS_r();
4432 * connect to the fileserver SYNC service.
4434 * @return operation status
4439 * @arg VInit must equal 2.
4440 * @arg Program Type must not be fileserver or salvager.
4441 * @arg VOL_LOCK is held.
4443 * @post connection to fileserver SYNC service established
4446 * @see VDisconnectFS_r
4447 * @see VChildProcReconnectFS_r
4449 * @internal volume package internal use only.
4455 assert((VInit == 2) &&
4456 (programType != fileServer) &&
4457 (programType != salvager));
4458 rc = FSYNC_clientInit();
4465 * disconnect from the fileserver SYNC service.
4468 * @arg client should have a live connection to the fileserver.
4469 * @arg VOL_LOCK is held.
4470 * @arg Program Type must not be fileserver or salvager.
4472 * @post connection to fileserver SYNC service destroyed
4474 * @see VDisconnectFS
4476 * @see VChildProcReconnectFS_r
4478 * @internal volume package internal use only.
4481 VDisconnectFS_r(void)
4483 assert((programType != fileServer) &&
4484 (programType != salvager));
4485 FSYNC_clientFinis();
4490 * disconnect from the fileserver SYNC service.
4493 * @arg client should have a live connection to the fileserver.
4494 * @arg Program Type must not be fileserver or salvager.
4496 * @post connection to fileserver SYNC service destroyed
4498 * @see VDisconnectFS_r
4500 * @see VChildProcReconnectFS
4511 * connect to the fileserver SYNC service from a child process following a fork.
4513 * @return operation status
4518 * @arg VOL_LOCK is held.
4519 * @arg current FSYNC handle is shared with a parent process
4521 * @post current FSYNC handle is discarded and a new connection to the
4522 * fileserver SYNC service is established
4524 * @see VChildProcReconnectFS
4526 * @see VDisconnectFS_r
4528 * @internal volume package internal use only.
4531 VChildProcReconnectFS_r(void)
4533 return FSYNC_clientChildProcReconnect();
4537 * connect to the fileserver SYNC service from a child process following a fork.
4539 * @return operation status
4543 * @pre current FSYNC handle is shared with a parent process
4545 * @post current FSYNC handle is discarded and a new connection to the
4546 * fileserver SYNC service is established
4548 * @see VChildProcReconnectFS_r
4550 * @see VDisconnectFS
4553 VChildProcReconnectFS(void)
4557 ret = VChildProcReconnectFS_r();
4561 #endif /* FSSYNC_BUILD_CLIENT */
4564 /***************************************************/
4565 /* volume bitmap routines */
4566 /***************************************************/
4569 * For demand attach fs, flags parameter controls
4570 * locking behavior. If (flags & VOL_ALLOC_BITMAP_WAIT)
4571 * is set, then this function will create a reservation
4572 * and block on any other exclusive operations. Otherwise,
4573 * this function assumes the caller already has exclusive
4574 * access to vp, and we just change the volume state.
4577 VAllocBitmapEntry_r(Error * ec, Volume * vp,
4578 struct vnodeIndex *index, int flags)
4581 register byte *bp, *ep;
4582 #ifdef AFS_DEMAND_ATTACH_FS
4583 VolState state_save;
4584 #endif /* AFS_DEMAND_ATTACH_FS */
4588 /* This test is probably redundant */
4589 if (!VolumeWriteable(vp)) {
4590 *ec = (bit32) VREADONLY;
4594 #ifdef AFS_DEMAND_ATTACH_FS
4595 if (flags & VOL_ALLOC_BITMAP_WAIT) {
4596 VCreateReservation_r(vp);
4597 VWaitExclusiveState_r(vp);
4599 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
4600 #endif /* AFS_DEMAND_ATTACH_FS */
4603 if ((programType == fileServer) && !index->bitmap) {
4605 #ifndef AFS_DEMAND_ATTACH_FS
4606 /* demand attach fs uses the volume state to avoid races.
4607 * specialStatus field is not used at all */
4609 if (vp->specialStatus == VBUSY) {
4610 if (vp->goingOffline) { /* vos dump waiting for the volume to
4611 * go offline. We probably come here
4612 * from AddNewReadableResidency */
4615 while (vp->specialStatus == VBUSY) {
4616 #ifdef AFS_PTHREAD_ENV
4620 #else /* !AFS_PTHREAD_ENV */
4622 #endif /* !AFS_PTHREAD_ENV */
4626 #endif /* !AFS_DEMAND_ATTACH_FS */
4628 if (!index->bitmap) {
4629 #ifndef AFS_DEMAND_ATTACH_FS
4630 vp->specialStatus = VBUSY; /* Stop anyone else from using it. */
4631 #endif /* AFS_DEMAND_ATTACH_FS */
4632 for (i = 0; i < nVNODECLASSES; i++) {
4633 VGetBitmap_r(ec, vp, i);
4635 #ifdef AFS_DEMAND_ATTACH_FS
4636 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
4637 #else /* AFS_DEMAND_ATTACH_FS */
4638 DeleteVolumeFromHashTable(vp);
4639 vp->shuttingDown = 1; /* Let who has it free it. */
4640 vp->specialStatus = 0;
4641 #endif /* AFS_DEMAND_ATTACH_FS */
4646 #ifndef AFS_DEMAND_ATTACH_FS
4648 vp->specialStatus = 0; /* Allow others to have access. */
4649 #endif /* AFS_DEMAND_ATTACH_FS */
4652 #endif /* BITMAP_LATER */
4654 #ifdef AFS_DEMAND_ATTACH_FS
4656 #endif /* AFS_DEMAND_ATTACH_FS */
4657 bp = index->bitmap + index->bitmapOffset;
4658 ep = index->bitmap + index->bitmapSize;
4660 if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
4662 index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
4665 o = ffs(~*bp) - 1; /* ffs is documented in BSTRING(3) */
4667 ret = (VnodeId) ((bp - index->bitmap) * 8 + o);
4668 #ifdef AFS_DEMAND_ATTACH_FS
4670 #endif /* AFS_DEMAND_ATTACH_FS */
4673 bp += sizeof(bit32) /* i.e. 4 */ ;
4675 /* No bit map entry--must grow bitmap */
4677 realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
4680 bp += index->bitmapSize;
4681 memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
4682 index->bitmapOffset = index->bitmapSize;
4683 index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
4685 ret = index->bitmapOffset * 8;
4686 #ifdef AFS_DEMAND_ATTACH_FS
4688 #endif /* AFS_DEMAND_ATTACH_FS */
4691 #ifdef AFS_DEMAND_ATTACH_FS
4692 VChangeState_r(vp, state_save);
4693 if (flags & VOL_ALLOC_BITMAP_WAIT) {
4694 VCancelReservation_r(vp);
4696 #endif /* AFS_DEMAND_ATTACH_FS */
4701 VAllocBitmapEntry(Error * ec, Volume * vp, register struct vnodeIndex * index)
4705 retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
4711 VFreeBitMapEntry_r(Error * ec, register struct vnodeIndex *index,
4714 unsigned int offset;
4720 #endif /* BITMAP_LATER */
4721 offset = bitNumber >> 3;
4722 if (offset >= index->bitmapSize) {
4726 if (offset < index->bitmapOffset)
4727 index->bitmapOffset = offset & ~3; /* Truncate to nearest bit32 */
4728 *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
4732 VFreeBitMapEntry(Error * ec, register struct vnodeIndex *index,
4736 VFreeBitMapEntry_r(ec, index, bitNumber);
4740 /* this function will drop the glock internally.
4741 * for old pthread fileservers, this is safe thanks to vbusy.
4743 * for demand attach fs, caller must have already called
4744 * VCreateReservation_r and VWaitExclusiveState_r */
4746 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
4748 StreamHandle_t *file;
4751 struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
4752 struct vnodeIndex *vip = &vp->vnodeIndex[class];
4753 struct VnodeDiskObject *vnode;
4754 unsigned int unique = 0;
4758 #endif /* BITMAP_LATER */
4759 #ifdef AFS_DEMAND_ATTACH_FS
4760 VolState state_save;
4761 #endif /* AFS_DEMAND_ATTACH_FS */
4765 #ifdef AFS_DEMAND_ATTACH_FS
4766 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
4767 #endif /* AFS_DEMAND_ATTACH_FS */
4770 fdP = IH_OPEN(vip->handle);
4771 assert(fdP != NULL);
4772 file = FDH_FDOPEN(fdP, "r");
4773 assert(file != NULL);
4774 vnode = (VnodeDiskObject *) malloc(vcp->diskSize);
4775 assert(vnode != NULL);
4776 size = OS_SIZE(fdP->fd_fd);
4778 nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
4780 vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4; /* The 10 is a little extra so
4781 * a few files can be created in this volume,
4782 * the whole thing is rounded up to nearest 4
4783 * bytes, because the bit map allocator likes
4786 BitMap = (byte *) calloc(1, vip->bitmapSize);
4787 assert(BitMap != NULL);
4788 #else /* BITMAP_LATER */
4789 vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
4790 assert(vip->bitmap != NULL);
4791 vip->bitmapOffset = 0;
4792 #endif /* BITMAP_LATER */
4793 if (STREAM_SEEK(file, vcp->diskSize, 0) != -1) {
4795 for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
4796 if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
4798 if (vnode->type != vNull) {
4799 if (vnode->vnodeMagic != vcp->magic) {
4800 Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
4805 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
4806 #else /* BITMAP_LATER */
4807 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
4808 #endif /* BITMAP_LATER */
4809 if (unique <= vnode->uniquifier)
4810 unique = vnode->uniquifier + 1;
4812 #ifndef AFS_PTHREAD_ENV
4813 if ((bitNumber & 0x00ff) == 0x0ff) { /* every 256 iterations */
4816 #endif /* !AFS_PTHREAD_ENV */
4819 if (vp->nextVnodeUnique < unique) {
4820 Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
4823 /* Paranoia, partly justified--I think fclose after fdopen
4824 * doesn't seem to close fd. In any event, the documentation
4825 * doesn't specify, so it's safer to close it twice.
4833 /* There may have been a racing condition with some other thread, both
4834 * creating the bitmaps for this volume. If the other thread was faster
4835 * the pointer to bitmap should already be filled and we can free ours.
4837 if (vip->bitmap == NULL) {
4838 vip->bitmap = BitMap;
4839 vip->bitmapOffset = 0;
4841 free((byte *) BitMap);
4842 #endif /* BITMAP_LATER */
4843 #ifdef AFS_DEMAND_ATTACH_FS
4844 VChangeState_r(vp, state_save);
4845 #endif /* AFS_DEMAND_ATTACH_FS */
4849 /***************************************************/
4850 /* Volume Path and Volume Number utility routines */
4851 /***************************************************/
4854 * find the first occurrence of a volume header file and return the path.
4856 * @param[out] ec outbound error code
4857 * @param[in] volumeId volume id to find
4858 * @param[out] partitionp pointer to disk partition path string
4859 * @param[out] namep pointer to volume header file name string
4861 * @post path to first occurrence of volume header is returned in partitionp
4862 * and namep, or ec is set accordingly.
4864 * @warning this function is NOT re-entrant -- partitionp and namep point to
4865 * static data segments
4867 * @note if a volume utility inadvertently leaves behind a stale volume header
4868 * on a vice partition, it is possible for callers to get the wrong one,
4869 * depending on the order of the disk partition linked list.
4873 VGetVolumePath(Error * ec, VolId volumeId, char **partitionp, char **namep)
4875 static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
4876 char path[VMAXPATHLEN];
4878 struct DiskPartition64 *dp;
4882 (void)afs_snprintf(&name[1], (sizeof name) - 1, VFORMAT, afs_printable_uint32_lu(volumeId));
4883 for (dp = DiskPartitionList; dp; dp = dp->next) {
4884 struct afs_stat status;
4885 strcpy(path, VPartitionPath(dp));
4887 if (afs_stat(path, &status) == 0) {
4888 strcpy(partition, dp->name);
4895 *partitionp = *namep = NULL;
4897 *partitionp = partition;
4903 * extract a volume number from a volume header filename string.
4905 * @param[in] name volume header filename string
4907 * @return volume number
4909 * @note the string must be of the form VFORMAT. the only permissible
4910 * deviation is a leading '/' character.
4915 VolumeNumber(char *name)
4919 return atoi(name + 1);
4923 * compute the volume header filename.
4925 * @param[in] volumeId
4927 * @return volume header filename
4929 * @post volume header filename string is constructed
4931 * @warning this function is NOT re-entrant -- the returned string is
4932 * stored in a static char array. see VolumeExternalName_r
4933 * for a re-entrant equivalent.
4935 * @see VolumeExternalName_r
4937 * @deprecated due to the above re-entrancy warning, this interface should
4938 * be considered deprecated. Please use VolumeExternalName_r
4942 VolumeExternalName(VolumeId volumeId)
4944 static char name[VMAXPATHLEN];
4945 (void)afs_snprintf(name, sizeof name, VFORMAT, afs_printable_uint32_lu(volumeId));
4950 * compute the volume header filename.
4952 * @param[in] volumeId
4953 * @param[inout] name array in which to store filename
4954 * @param[in] len length of name array
4956 * @return result code from afs_snprintf
4958 * @see VolumeExternalName
4961 * @note re-entrant equivalent of VolumeExternalName
4963 * @internal volume package internal use only.
4965 #ifdef AFS_DEMAND_ATTACH_FS
4967 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
4969 return afs_snprintf(name, len, VFORMAT, afs_printable_uint32_lu(volumeId));
4974 /***************************************************/
4975 /* Volume Usage Statistics routines */
4976 /***************************************************/
4978 #if OPENAFS_VOL_STATS
4979 #define OneDay (86400) /* 24 hours' worth of seconds */
4981 #define OneDay (24*60*60) /* 24 hours */
4982 #endif /* OPENAFS_VOL_STATS */
4984 #define Midnight(date) ((date-TimeZoneCorrection)/OneDay*OneDay+TimeZoneCorrection)
4986 /*------------------------------------------------------------------------
4987 * [export] VAdjustVolumeStatistics
4990 * If we've passed midnight, we need to update all the day use
4991 * statistics as well as zeroing the detailed volume statistics
4992 * (if we are implementing them).
4995 * vp : Pointer to the volume structure describing the lucky
4996 * volume being considered for update.
5002 * Nothing interesting.
5006 *------------------------------------------------------------------------*/
5009 VAdjustVolumeStatistics_r(register Volume * vp)
5011 unsigned int now = FT_ApproxTime();
5013 if (now - V_dayUseDate(vp) > OneDay) {
5014 register int ndays, i;
5016 ndays = (now - V_dayUseDate(vp)) / OneDay;
5017 for (i = 6; i > ndays - 1; i--)
5018 V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
5019 for (i = 0; i < ndays - 1 && i < 7; i++)
5020 V_weekUse(vp)[i] = 0;
5022 V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
5024 V_dayUseDate(vp) = Midnight(now);
5026 #if OPENAFS_VOL_STATS
5028 * All we need to do is bzero the entire VOL_STATS_BYTES of
5029 * the detailed volume statistics area.
5031 memset((char *)(V_stat_area(vp)), 0, VOL_STATS_BYTES);
5032 #endif /* OPENAFS_VOL_STATS */
5035 /*It's been more than a day of collection */
5037 * Always return happily.
5040 } /*VAdjustVolumeStatistics */
5043 VAdjustVolumeStatistics(register Volume * vp)
5047 retVal = VAdjustVolumeStatistics_r(vp);
5053 VBumpVolumeUsage_r(register Volume * vp)
5055 unsigned int now = FT_ApproxTime();
5056 if (now - V_dayUseDate(vp) > OneDay)
5057 VAdjustVolumeStatistics_r(vp);
5059 * Save the volume header image to disk after every 128 bumps to dayUse.
5061 if ((V_dayUse(vp)++ & 127) == 0) {
5063 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
5068 VBumpVolumeUsage(register Volume * vp)
5071 VBumpVolumeUsage_r(vp);
5076 VSetDiskUsage_r(void)
5078 #ifndef AFS_DEMAND_ATTACH_FS
5079 static int FifteenMinuteCounter = 0;
5083 /* NOTE: Don't attempt to access the partitions list until the
5084 * initialization level indicates that all volumes are attached,
5085 * which implies that all partitions are initialized. */
5086 #ifdef AFS_PTHREAD_ENV
5088 #else /* AFS_PTHREAD_ENV */
5090 #endif /* AFS_PTHREAD_ENV */
5093 VResetDiskUsage_r();
5095 #ifndef AFS_DEMAND_ATTACH_FS
5096 if (++FifteenMinuteCounter == 3) {
5097 FifteenMinuteCounter = 0;
5100 #endif /* !AFS_DEMAND_ATTACH_FS */
5112 /***************************************************/
5113 /* Volume Update List routines */
5114 /***************************************************/
5116 /* The number of minutes that a volume hasn't been updated before the
5117 * "Dont salvage" flag in the volume header will be turned on */
5118 #define SALVAGE_INTERVAL (10*60)
5123 * volume update list functionality has been moved into the VLRU
5124 * the DONT_SALVAGE flag is now set during VLRU demotion
5127 #ifndef AFS_DEMAND_ATTACH_FS
5128 static VolumeId *UpdateList = NULL; /* Pointer to array of Volume ID's */
5129 static int nUpdatedVolumes = 0; /* Updated with entry in UpdateList, salvage after crash flag on */
5130 static int updateSize = 0; /* number of entries possible */
5131 #define UPDATE_LIST_SIZE 128 /* initial size increment (must be a power of 2!) */
5132 #endif /* !AFS_DEMAND_ATTACH_FS */
5135 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
5138 vp->updateTime = FT_ApproxTime();
5139 if (V_dontSalvage(vp) == 0)
5141 V_dontSalvage(vp) = 0;
5142 VSyncVolume_r(ec, vp, 0);
5143 #ifdef AFS_DEMAND_ATTACH_FS
5144 V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
5145 #else /* !AFS_DEMAND_ATTACH_FS */
5148 if (UpdateList == NULL) {
5149 updateSize = UPDATE_LIST_SIZE;
5150 UpdateList = (VolumeId *) malloc(sizeof(VolumeId) * updateSize);
5152 if (nUpdatedVolumes == updateSize) {
5154 if (updateSize > 524288) {
5155 Log("warning: there is likely a bug in the volume update scanner\n");
5159 (VolumeId *) realloc(UpdateList,
5160 sizeof(VolumeId) * updateSize);
5163 assert(UpdateList != NULL);
5164 UpdateList[nUpdatedVolumes++] = V_id(vp);
5165 #endif /* !AFS_DEMAND_ATTACH_FS */
5168 #ifndef AFS_DEMAND_ATTACH_FS
5170 VScanUpdateList(void)
5172 register int i, gap;
5173 register Volume *vp;
5175 afs_uint32 now = FT_ApproxTime();
5176 /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
5177 for (i = gap = 0; i < nUpdatedVolumes; i++) {
5179 UpdateList[i - gap] = UpdateList[i];
5181 /* XXX this routine needlessly messes up the Volume LRU by
5182 * breaking the LRU temporal-locality assumptions.....
5183 * we should use a special volume header allocator here */
5184 vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
5187 } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
5188 V_dontSalvage(vp) = DONT_SALVAGE;
5189 VUpdateVolume_r(&error, vp, 0); /* No need to fsync--not critical */
5197 #ifndef AFS_PTHREAD_ENV
5199 #endif /* !AFS_PTHREAD_ENV */
5201 nUpdatedVolumes -= gap;
5203 #endif /* !AFS_DEMAND_ATTACH_FS */
5206 /***************************************************/
5207 /* Volume LRU routines */
5208 /***************************************************/
5213 * with demand attach fs, we attempt to soft detach(1)
5214 * volumes which have not been accessed in a long time
5215 * in order to speed up fileserver shutdown
5217 * (1) by soft detach we mean a process very similar
5218 * to VOffline, except the final state of the
5219 * Volume will be VOL_STATE_PREATTACHED, instead
5220 * of the usual VOL_STATE_UNATTACHED
5222 #ifdef AFS_DEMAND_ATTACH_FS
5224 /* implementation is reminiscent of a generational GC
5226 * queue 0 is newly attached volumes. this queue is
5227 * sorted by attach timestamp
5229 * queue 1 is volumes that have been around a bit
5230 * longer than queue 0. this queue is sorted by
5233 * queue 2 is volumes tha have been around the longest.
5234 * this queue is unsorted
5236 * queue 3 is volumes that have been marked as
5237 * candidates for soft detachment. this queue is
5240 #define VLRU_GENERATIONS 3 /**< number of generations in VLRU */
5241 #define VLRU_QUEUES 5 /**< total number of VLRU queues */
5244 * definition of a VLRU queue.
5247 volatile struct rx_queue q;
5254 * main VLRU data structure.
5257 struct VLRU_q q[VLRU_QUEUES]; /**< VLRU queues */
5260 /** time interval (in seconds) between promotion passes for
5261 * each young generation queue. */
5262 afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
5264 /** time interval (in seconds) between soft detach candidate
5265 * scans for each generation queue.
5267 * scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
5268 * we perform a soft detach pass. */
5269 afs_uint32 scan_interval[VLRU_GENERATIONS+1];
5271 /* scheduler state */
5272 int next_idx; /**< next queue to receive attention */
5273 afs_uint32 last_promotion[VLRU_GENERATIONS-1]; /**< timestamp of last promotion scan */
5274 afs_uint32 last_scan[VLRU_GENERATIONS+1]; /**< timestamp of last detach scan */
5276 int scanner_state; /**< state of scanner thread */
5277 pthread_cond_t cv; /**< state transition CV */
5280 /** global VLRU state */
5281 static struct VLRU volume_LRU;
5284 * defined states for VLRU scanner thread.
5287 VLRU_SCANNER_STATE_OFFLINE = 0, /**< vlru scanner thread is offline */
5288 VLRU_SCANNER_STATE_ONLINE = 1, /**< vlru scanner thread is online */
5289 VLRU_SCANNER_STATE_SHUTTING_DOWN = 2, /**< vlru scanner thread is shutting down */
5290 VLRU_SCANNER_STATE_PAUSING = 3, /**< vlru scanner thread is getting ready to pause */
5291 VLRU_SCANNER_STATE_PAUSED = 4 /**< vlru scanner thread is paused */
5292 } vlru_thread_state_t;
5294 /* vlru disk data header stuff */
5295 #define VLRU_DISK_MAGIC 0x7a8b9cad /**< vlru disk entry magic number */
5296 #define VLRU_DISK_VERSION 1 /**< vlru disk entry version number */
5298 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
5299 #define VLRU_DUMP_EXPIRATION_TIME (60*60*24*7) /* expire vlru data after 1 week */
5302 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
5303 * soft detachment. */
5304 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
5306 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
5307 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
5309 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
5310 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
5312 /** VLRU control flag. non-zero value implies VLRU subsystem is activated. */
5313 static afs_uint32 VLRU_enabled = 1;
5315 /* queue synchronization routines */
5316 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
5317 static void VLRU_EndExclusive_r(struct VLRU_q * q);
5318 static void VLRU_Wait_r(struct VLRU_q * q);
5321 * set VLRU subsystem tunable parameters.
5323 * @param[in] option tunable option to modify
5324 * @param[in] val new value for tunable parameter
5326 * @pre @c VInitVolumePackage has not yet been called.
5328 * @post tunable parameter is modified
5332 * @note valid option parameters are:
5333 * @arg @c VLRU_SET_THRESH
5334 * set the period of inactivity after which
5335 * volumes are eligible for soft detachment
5336 * @arg @c VLRU_SET_INTERVAL
5337 * set the time interval between calls
5338 * to the volume LRU "garbage collector"
5339 * @arg @c VLRU_SET_MAX
5340 * set the max number of volumes to deallocate
5344 VLRU_SetOptions(int option, afs_uint32 val)
5346 if (option == VLRU_SET_THRESH) {
5347 VLRU_offline_thresh = val;
5348 } else if (option == VLRU_SET_INTERVAL) {
5349 VLRU_offline_interval = val;
5350 } else if (option == VLRU_SET_MAX) {
5351 VLRU_offline_max = val;
5352 } else if (option == VLRU_SET_ENABLED) {
5355 VLRU_ComputeConstants();
5359 * compute VLRU internal timing parameters.
5361 * @post VLRU scanner thread internal timing parameters are computed
5363 * @note computes internal timing parameters based upon user-modifiable
5364 * tunable parameters.
5368 * @internal volume package internal use only.
5371 VLRU_ComputeConstants(void)
5373 afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
5375 /* compute the candidate scan interval */
5376 volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
5378 /* compute the promotion intervals */
5379 volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
5380 volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
5383 /* compute the gen 0 scan interval */
5384 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
5386 /* compute the gen 0 scan interval */
5387 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
5392 * initialize VLRU subsystem.
5394 * @pre this function has not yet been called
5396 * @post VLRU subsystem is initialized and VLRU scanner thread is starting
5400 * @internal volume package internal use only.
5406 pthread_attr_t attrs;
5409 if (!VLRU_enabled) {
5410 Log("VLRU: disabled\n");
5414 /* initialize each of the VLRU queues */
5415 for (i = 0; i < VLRU_QUEUES; i++) {
5416 queue_Init(&volume_LRU.q[i]);
5417 volume_LRU.q[i].len = 0;
5418 volume_LRU.q[i].busy = 0;
5419 assert(pthread_cond_init(&volume_LRU.q[i].cv, NULL) == 0);
5422 /* setup the timing constants */
5423 VLRU_ComputeConstants();
5425 /* XXX put inside LogLevel check? */
5426 Log("VLRU: starting scanner with the following configuration parameters:\n");
5427 Log("VLRU: offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
5428 Log("VLRU: running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
5429 Log("VLRU: taking up to %d volumes offline per pass\n", VLRU_offline_max);
5430 Log("VLRU: scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
5431 Log("VLRU: scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
5432 Log("VLRU: scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
5434 /* start up the VLRU scanner */
5435 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
5436 if (programType == fileServer) {
5437 assert(pthread_cond_init(&volume_LRU.cv, NULL) == 0);
5438 assert(pthread_attr_init(&attrs) == 0);
5439 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
5440 assert(pthread_create(&tid, &attrs, &VLRU_ScannerThread, NULL) == 0);
5445 * initialize the VLRU-related fields of a newly allocated volume object.
5447 * @param[in] vp pointer to volume object
5450 * @arg @c VOL_LOCK is held.
5451 * @arg volume object is not on a VLRU queue.
5453 * @post VLRU fields are initialized to indicate that volume object is not
5454 * currently registered with the VLRU subsystem
5458 * @internal volume package interal use only.
5461 VLRU_Init_Node_r(volatile Volume * vp)
5466 assert(queue_IsNotOnQueue(&vp->vlru));
5467 vp->vlru.idx = VLRU_QUEUE_INVALID;
5471 * add a volume object to a VLRU queue.
5473 * @param[in] vp pointer to volume object
5476 * @arg @c VOL_LOCK is held.
5477 * @arg caller MUST hold a lightweight ref on @p vp.
5478 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
5480 * @post the volume object is added to the appropriate VLRU queue
5482 * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
5483 * then the volume is added to that queue. Otherwise, the value
5484 * @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
5485 * volume is added to the NEW generation queue.
5487 * @note @c VOL_LOCK may be dropped internally
5489 * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
5490 * during the add operation, and is restored to the previous
5491 * state prior to return.
5495 * @internal volume package internal use only.
5498 VLRU_Add_r(volatile Volume * vp)
5501 VolState state_save;
5506 if (queue_IsOnQueue(&vp->vlru))
5509 state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
5512 if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
5513 idx = VLRU_QUEUE_NEW;
5516 VLRU_Wait_r(&volume_LRU.q[idx]);
5518 /* repeat check since VLRU_Wait_r may have dropped
5520 if (queue_IsNotOnQueue(&vp->vlru)) {
5522 queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
5523 volume_LRU.q[idx].len++;
5524 V_attachFlags(vp) |= VOL_ON_VLRU;
5525 vp->stats.last_promote = FT_ApproxTime();
5528 VChangeState_r(vp, state_save);
5532 * delete a volume object from a VLRU queue.
5534 * @param[in] vp pointer to volume object
5537 * @arg @c VOL_LOCK is held.
5538 * @arg caller MUST hold a lightweight ref on @p vp.
5539 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
5541 * @post volume object is removed from the VLRU queue
5543 * @note @c VOL_LOCK may be dropped internally
5547 * @todo We should probably set volume state to something exlcusive
5548 * (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
5550 * @internal volume package internal use only.
5553 VLRU_Delete_r(volatile Volume * vp)
5560 if (queue_IsNotOnQueue(&vp->vlru))
5566 if (idx == VLRU_QUEUE_INVALID)
5568 VLRU_Wait_r(&volume_LRU.q[idx]);
5569 } while (idx != vp->vlru.idx);
5571 /* now remove from the VLRU and update
5572 * the appropriate counter */
5573 queue_Remove(&vp->vlru);
5574 volume_LRU.q[idx].len--;
5575 vp->vlru.idx = VLRU_QUEUE_INVALID;
5576 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
5580 * tell the VLRU subsystem that a volume was just accessed.
5582 * @param[in] vp pointer to volume object
5585 * @arg @c VOL_LOCK is held
5586 * @arg caller MUST hold a lightweight ref on @p vp
5587 * @arg caller MUST NOT hold exclusive ownership of any VLRU queue
5589 * @post volume VLRU access statistics are updated. If the volume was on
5590 * the VLRU soft detach candidate queue, it is moved to the NEW
5593 * @note @c VOL_LOCK may be dropped internally
5597 * @internal volume package internal use only.
5600 VLRU_UpdateAccess_r(volatile Volume * vp)
5602 afs_uint32 live_interval;
5603 Volume * rvp = NULL;
5608 if (queue_IsNotOnQueue(&vp->vlru))
5611 assert(V_attachFlags(vp) & VOL_ON_VLRU);
5613 /* update the access timestamp */
5614 vp->stats.last_get = FT_ApproxTime();
5617 * if the volume is on the soft detach candidate
5618 * list, we need to safely move it back to a
5619 * regular generation. this has to be done
5620 * carefully so we don't race against the scanner
5624 /* if this volume is on the soft detach candidate queue,
5625 * then grab exclusive access to the necessary queues */
5626 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
5628 VCreateReservation_r(rvp);
5630 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
5631 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
5632 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5633 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5636 /* make sure multiple threads don't race to update */
5637 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
5638 VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
5642 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5643 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
5644 VCancelReservation_r(rvp);
5649 * switch a volume between two VLRU queues.
5651 * @param[in] vp pointer to volume object
5652 * @param[in] new_idx index of VLRU queue onto which the volume will be moved
5653 * @param[in] append controls whether the volume will be appended or
5654 * prepended to the queue. A nonzero value means it will
5655 * be appended; zero means it will be prepended.
5657 * @pre The new (and old, if applicable) queue(s) must either be owned
5658 * exclusively by the calling thread for asynchronous manipulation,
5659 * or the queue(s) must be quiescent and VOL_LOCK must be held.
5660 * Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
5661 * for further details of the queue asynchronous processing mechanism.
5663 * @post If the volume object was already on a VLRU queue, it is
5664 * removed from the queue. Depending on the value of the append
5665 * parameter, the volume object is either appended or prepended
5666 * to the VLRU queue referenced by the new_idx parameter.
5670 * @see VLRU_BeginExclusive_r
5671 * @see VLRU_EndExclusive_r
5674 * @internal volume package internal use only.
5677 VLRU_SwitchQueues(volatile Volume * vp, int new_idx, int append)
5679 if (queue_IsNotOnQueue(&vp->vlru))
5682 queue_Remove(&vp->vlru);
5683 volume_LRU.q[vp->vlru.idx].len--;
5685 /* put the volume back on the correct generational queue */
5687 queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
5689 queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
5692 volume_LRU.q[new_idx].len++;
5693 vp->vlru.idx = new_idx;
5697 * VLRU background thread.
5699 * The VLRU Scanner Thread is responsible for periodically scanning through
5700 * each VLRU queue looking for volumes which should be moved to another
5701 * queue, or soft detached.
5703 * @param[in] args unused thread arguments parameter
5705 * @return unused thread return value
5706 * @retval NULL always
5708 * @internal volume package internal use only.
5711 VLRU_ScannerThread(void * args)
5713 afs_uint32 now, min_delay, delay;
5714 afs_uint32 next_scan[VLRU_GENERATIONS];
5715 afs_uint32 next_promotion[VLRU_GENERATIONS];
5716 int i, min_idx, min_op, overdue, state;
5718 /* set t=0 for promotion cycle to be
5719 * fileserver startup */
5720 now = FT_ApproxTime();
5721 for (i=0; i < VLRU_GENERATIONS-1; i++) {
5722 volume_LRU.last_promotion[i] = now;
5725 /* don't start the scanner until VLRU_offline_thresh
5726 * plus a small delay for VInitVolumePackage to finish
5729 sleep(VLRU_offline_thresh + 60);
5731 /* set t=0 for scan cycle to be now */
5732 now = FT_ApproxTime();
5733 for (i=0; i < VLRU_GENERATIONS+1; i++) {
5734 volume_LRU.last_scan[i] = now;
5738 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
5739 volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
5742 while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
5743 /* check to see if we've been asked to pause */
5744 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
5745 volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
5746 assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
5748 VOL_CV_WAIT(&volume_LRU.cv);
5749 } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
5752 /* scheduling can happen outside the glock */
5755 /* figure out what is next on the schedule */
5757 /* figure out a potential schedule for the new generation first */
5759 min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
5762 if (min_delay > volume_LRU.scan_interval[0]) {
5763 /* unsigned overflow -- we're overdue to run this scan */
5768 /* if we're not overdue for gen 0, figure out schedule for candidate gen */
5770 i = VLRU_QUEUE_CANDIDATE;
5771 delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
5772 if (delay < min_delay) {
5776 if (delay > volume_LRU.scan_interval[i]) {
5777 /* unsigned overflow -- we're overdue to run this scan */
5784 /* if we're still not overdue for something, figure out schedules for promotions */
5785 for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
5786 delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
5787 if (delay < min_delay) {
5792 if (delay > volume_LRU.promotion_interval[i]) {
5793 /* unsigned overflow -- we're overdue to run this promotion */
5802 /* sleep as needed */
5807 /* do whatever is next */
5810 VLRU_Promote_r(min_idx);
5811 VLRU_Demote_r(min_idx+1);
5813 VLRU_Scan_r(min_idx);
5815 now = FT_ApproxTime();
5818 Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
5820 /* signal that scanner is down */
5821 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
5822 assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
5828 * promote volumes from one VLRU generation to the next.
5830 * This routine scans a VLRU generation looking for volumes which are
5831 * eligible to be promoted to the next generation. All volumes which
5832 * meet the eligibility requirement are promoted.
5834 * Promotion eligibility is based upon meeting both of the following
5837 * @arg The volume has been accessed since the last promotion:
5838 * @c (vp->stats.last_get >= vp->stats.last_promote)
5839 * @arg The last promotion occurred at least
5840 * @c volume_LRU.promotion_interval[idx] seconds ago
5842 * As a performance optimization, promotions are "globbed". In other
5843 * words, we promote arbitrarily large contiguous sublists of elements
5846 * @param[in] idx VLRU queue index to scan
5850 * @internal VLRU internal use only.
5853 VLRU_Promote_r(int idx)
5855 int len, chaining, promote;
5856 afs_uint32 now, thresh;
5857 struct rx_queue *qp, *nqp;
5858 Volume * vp, *start, *end;
5860 /* get exclusive access to two chains, and drop the glock */
5861 VLRU_Wait_r(&volume_LRU.q[idx]);
5862 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
5863 VLRU_Wait_r(&volume_LRU.q[idx+1]);
5864 VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
5867 thresh = volume_LRU.promotion_interval[idx];
5868 now = FT_ApproxTime();
5871 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
5872 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
5873 promote = (((vp->stats.last_promote + thresh) <= now) &&
5874 (vp->stats.last_get >= vp->stats.last_promote));
5882 /* promote and prepend chain */
5883 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
5897 /* promote and prepend */
5898 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
5902 volume_LRU.q[idx].len -= len;
5903 volume_LRU.q[idx+1].len += len;
5906 /* release exclusive access to the two chains */
5908 volume_LRU.last_promotion[idx] = now;
5909 VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
5910 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
5913 /* run the demotions */
5915 VLRU_Demote_r(int idx)
5918 int len, chaining, demote;
5919 afs_uint32 now, thresh;
5920 struct rx_queue *qp, *nqp;
5921 Volume * vp, *start, *end;
5922 Volume ** salv_flag_vec = NULL;
5923 int salv_vec_offset = 0;
5925 assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
5927 /* get exclusive access to two chains, and drop the glock */
5928 VLRU_Wait_r(&volume_LRU.q[idx-1]);
5929 VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
5930 VLRU_Wait_r(&volume_LRU.q[idx]);
5931 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
5934 /* no big deal if this allocation fails */
5935 if (volume_LRU.q[idx].len) {
5936 salv_flag_vec = (Volume **) malloc(volume_LRU.q[idx].len * sizeof(Volume *));
5939 now = FT_ApproxTime();
5940 thresh = volume_LRU.promotion_interval[idx-1];
5943 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
5944 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
5945 demote = (((vp->stats.last_promote + thresh) <= now) &&
5946 (vp->stats.last_get < (now - thresh)));
5948 /* we now do volume update list DONT_SALVAGE flag setting during
5949 * demotion passes */
5950 if (salv_flag_vec &&
5951 !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
5953 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
5954 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
5955 salv_flag_vec[salv_vec_offset++] = vp;
5956 VCreateReservation_r(vp);
5965 /* demote and append chain */
5966 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
5980 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
5984 volume_LRU.q[idx].len -= len;
5985 volume_LRU.q[idx-1].len += len;
5988 /* release exclusive access to the two chains */
5990 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
5991 VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
5993 /* now go back and set the DONT_SALVAGE flags as appropriate */
5994 if (salv_flag_vec) {
5996 for (i = 0; i < salv_vec_offset; i++) {
5997 vp = salv_flag_vec[i];
5998 if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
5999 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
6000 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
6003 V_attachFlags(vp) |= VOL_HDR_DONTSALV;
6004 V_dontSalvage(vp) = DONT_SALVAGE;
6005 VUpdateVolume_r(&ec, vp, 0);
6009 VCancelReservation_r(vp);
6011 free(salv_flag_vec);
6015 /* run a pass of the VLRU GC scanner */
6017 VLRU_Scan_r(int idx)
6019 afs_uint32 now, thresh;
6020 struct rx_queue *qp, *nqp;
6021 volatile Volume * vp;
6024 assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
6026 /* gain exclusive access to the idx VLRU */
6027 VLRU_Wait_r(&volume_LRU.q[idx]);
6028 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
6030 if (idx != VLRU_QUEUE_CANDIDATE) {
6031 /* gain exclusive access to the candidate VLRU */
6032 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6033 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6036 now = FT_ApproxTime();
6037 thresh = now - VLRU_offline_thresh;
6039 /* perform candidate selection and soft detaching */
6040 if (idx == VLRU_QUEUE_CANDIDATE) {
6041 /* soft detach some volumes from the candidate pool */
6045 for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
6046 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6047 if (i >= VLRU_offline_max) {
6050 /* check timestamp to see if it's a candidate for soft detaching */
6051 if (vp->stats.last_get <= thresh) {
6053 if (VCheckSoftDetach(vp, thresh))
6059 /* scan for volumes to become soft detach candidates */
6060 for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
6061 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6063 /* check timestamp to see if it's a candidate for soft detaching */
6064 if (vp->stats.last_get <= thresh) {
6065 VCheckSoftDetachCandidate(vp, thresh);
6068 if (!(i&0x7f)) { /* lock coarsening optimization */
6076 /* relinquish exclusive access to the VLRU chains */
6080 volume_LRU.last_scan[idx] = now;
6081 if (idx != VLRU_QUEUE_CANDIDATE) {
6082 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6084 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
6087 /* check whether volume is safe to soft detach
6088 * caller MUST NOT hold a ref count on vp */
6090 VCheckSoftDetach(volatile Volume * vp, afs_uint32 thresh)
6094 if (vp->nUsers || vp->nWaiters)
6097 if (vp->stats.last_get <= thresh) {
6098 ret = VSoftDetachVolume_r(vp, thresh);
6104 /* check whether volume should be made a
6105 * soft detach candidate */
6107 VCheckSoftDetachCandidate(volatile Volume * vp, afs_uint32 thresh)
6110 if (vp->nUsers || vp->nWaiters)
6115 assert(idx == VLRU_QUEUE_NEW);
6117 if (vp->stats.last_get <= thresh) {
6118 /* move to candidate pool */
6119 queue_Remove(&vp->vlru);
6120 volume_LRU.q[VLRU_QUEUE_NEW].len--;
6121 queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
6122 vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
6123 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
6131 /* begin exclusive access on VLRU */
6133 VLRU_BeginExclusive_r(struct VLRU_q * q)
6135 assert(q->busy == 0);
6139 /* end exclusive access on VLRU */
6141 VLRU_EndExclusive_r(struct VLRU_q * q)
6145 assert(pthread_cond_broadcast(&q->cv) == 0);
6148 /* wait for another thread to end exclusive access on VLRU */
6150 VLRU_Wait_r(struct VLRU_q * q)
6153 VOL_CV_WAIT(&q->cv);
6158 * volume soft detach
6160 * caller MUST NOT hold a ref count on vp */
6162 VSoftDetachVolume_r(volatile Volume * vp, afs_uint32 thresh)
6167 assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
6169 ts_save = vp->stats.last_get;
6170 if (ts_save > thresh)
6173 if (vp->nUsers || vp->nWaiters)
6176 if (VIsExclusiveState(V_attachState(vp))) {
6180 switch (V_attachState(vp)) {
6181 case VOL_STATE_UNATTACHED:
6182 case VOL_STATE_PREATTACHED:
6183 case VOL_STATE_ERROR:
6184 case VOL_STATE_GOING_OFFLINE:
6185 case VOL_STATE_SHUTTING_DOWN:
6186 case VOL_STATE_SALVAGING:
6187 volume_LRU.q[vp->vlru.idx].len--;
6189 /* create and cancel a reservation to
6190 * give the volume an opportunity to
6192 VCreateReservation_r(vp);
6193 queue_Remove(&vp->vlru);
6194 vp->vlru.idx = VLRU_QUEUE_INVALID;
6195 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
6196 VCancelReservation_r(vp);
6200 /* hold the volume and take it offline.
6201 * no need for reservations, as VHold_r
6202 * takes care of that internally. */
6203 if (VHold_r(vp) == 0) {
6204 /* vhold drops the glock, so now we should
6205 * check to make sure we aren't racing against
6206 * other threads. if we are racing, offlining vp
6207 * would be wasteful, and block the scanner for a while
6211 (vp->shuttingDown) ||
6212 (vp->goingOffline) ||
6213 (vp->stats.last_get != ts_save)) {
6214 /* looks like we're racing someone else. bail */
6218 /* pull it off the VLRU */
6219 assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
6220 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
6221 queue_Remove(&vp->vlru);
6222 vp->vlru.idx = VLRU_QUEUE_INVALID;
6223 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
6225 /* take if offline */
6226 VOffline_r(vp, "volume has been soft detached");
6228 /* invalidate the volume header cache */
6229 FreeVolumeHeader(vp);
6232 IncUInt64(&VStats.soft_detaches);
6233 vp->stats.soft_detaches++;
6235 /* put in pre-attached state so demand
6236 * attacher can work on it */
6237 VChangeState_r(vp, VOL_STATE_PREATTACHED);
6243 #endif /* AFS_DEMAND_ATTACH_FS */
6246 /***************************************************/
6247 /* Volume Header Cache routines */
6248 /***************************************************/
6251 * volume header cache.
6253 struct volume_hdr_LRU_t volume_hdr_LRU;
6256 * initialize the volume header cache.
6258 * @param[in] howMany number of header cache entries to preallocate
6260 * @pre VOL_LOCK held. Function has never been called before.
6262 * @post howMany cache entries are allocated, initialized, and added
6263 * to the LRU list. Header cache statistics are initialized.
6265 * @note only applicable to fileServer program type. Should only be
6266 * called once during volume package initialization.
6268 * @internal volume package internal use only.
6271 VInitVolumeHeaderCache(afs_uint32 howMany)
6273 register struct volHeader *hp;
6274 if (programType != fileServer)
6276 queue_Init(&volume_hdr_LRU);
6277 volume_hdr_LRU.stats.free = 0;
6278 volume_hdr_LRU.stats.used = howMany;
6279 volume_hdr_LRU.stats.attached = 0;
6280 hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
6284 /* We are using ReleaseVolumeHeader to initialize the values on the header list
6285 * to ensure they have the right values
6287 ReleaseVolumeHeader(hp++);
6291 * get a volume header and attach it to the volume object.
6293 * @param[in] vp pointer to volume object
6295 * @return cache entry status
6296 * @retval 0 volume header was newly attached; cache data is invalid
6297 * @retval 1 volume header was previously attached; cache data is valid
6299 * @pre VOL_LOCK held. For DAFS, lightweight ref must be held on volume object.
6301 * @post volume header attached to volume object. if necessary, header cache
6302 * entry on LRU is synchronized to disk. Header is removed from LRU list.
6304 * @note VOL_LOCK may be dropped
6306 * @warning this interface does not load header data from disk. it merely
6307 * attaches a header object to the volume object, and may sync the old
6308 * header cache data out to disk in the process.
6310 * @internal volume package internal use only.
6313 GetVolumeHeader(register Volume * vp)
6316 register struct volHeader *hd;
6318 static int everLogged = 0;
6320 #ifdef AFS_DEMAND_ATTACH_FS
6321 VolState vp_save, back_save;
6323 /* XXX debug 9/19/05 we've apparently got
6324 * a ref counting bug somewhere that's
6325 * breaking the nUsers == 0 => header on LRU
6327 if (vp->header && queue_IsNotOnQueue(vp->header)) {
6328 Log("nUsers == 0, but header not on LRU\n");
6333 old = (vp->header != NULL); /* old == volume already has a header */
6335 if (programType != fileServer) {
6336 /* for volume utilities, we allocate volHeaders as needed */
6338 hd = (struct volHeader *)calloc(1, sizeof(*vp->header));
6342 #ifdef AFS_DEMAND_ATTACH_FS
6343 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
6347 /* for the fileserver, we keep a volume header cache */
6349 /* the header we previously dropped in the lru is
6350 * still available. pull it off the lru and return */
6353 assert(hd->back == vp);
6355 /* we need to grab a new element off the LRU */
6356 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
6357 /* grab an element and pull off of LRU */
6358 hd = queue_First(&volume_hdr_LRU, volHeader);
6361 /* LRU is empty, so allocate a new volHeader
6362 * this is probably indicative of a leak, so let the user know */
6363 hd = (struct volHeader *)calloc(1, sizeof(struct volHeader));
6366 Log("****Allocated more volume headers, probably leak****\n");
6369 volume_hdr_LRU.stats.free++;
6372 /* this header used to belong to someone else.
6373 * we'll need to check if the header needs to
6374 * be sync'd out to disk */
6376 #ifdef AFS_DEMAND_ATTACH_FS
6377 /* if hd->back were in an exclusive state, then
6378 * its volHeader would not be on the LRU... */
6379 assert(!VIsExclusiveState(V_attachState(hd->back)));
6382 if (hd->diskstuff.inUse) {
6383 /* volume was in use, so we'll need to sync
6384 * its header to disk */
6386 #ifdef AFS_DEMAND_ATTACH_FS
6387 back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
6388 vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
6389 VCreateReservation_r(hd->back);
6393 WriteVolumeHeader_r(&error, hd->back);
6394 /* Ignore errors; catch them later */
6396 #ifdef AFS_DEMAND_ATTACH_FS
6401 hd->back->header = NULL;
6402 #ifdef AFS_DEMAND_ATTACH_FS
6403 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
6405 if (hd->diskstuff.inUse) {
6406 VChangeState_r(hd->back, back_save);
6407 VCancelReservation_r(hd->back);
6408 VChangeState_r(vp, vp_save);
6412 volume_hdr_LRU.stats.attached++;
6416 #ifdef AFS_DEMAND_ATTACH_FS
6417 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
6420 volume_hdr_LRU.stats.free--;
6421 volume_hdr_LRU.stats.used++;
6423 IncUInt64(&VStats.hdr_gets);
6424 #ifdef AFS_DEMAND_ATTACH_FS
6425 IncUInt64(&vp->stats.hdr_gets);
6426 vp->stats.last_hdr_get = FT_ApproxTime();
6433 * make sure volume header is attached and contains valid cache data.
6435 * @param[out] ec outbound error code
6436 * @param[in] vp pointer to volume object
6438 * @pre VOL_LOCK held. For DAFS, lightweight ref held on vp.
6440 * @post header cache entry attached, and loaded with valid data, or
6441 * *ec is nonzero, and the header is released back into the LRU.
6443 * @internal volume package internal use only.
6446 LoadVolumeHeader(Error * ec, Volume * vp)
6448 #ifdef AFS_DEMAND_ATTACH_FS
6449 VolState state_save;
6453 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
6454 IncUInt64(&VStats.hdr_loads);
6455 state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
6458 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
6459 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
6461 IncUInt64(&vp->stats.hdr_loads);
6462 now = FT_ApproxTime();
6466 V_attachFlags(vp) |= VOL_HDR_LOADED;
6467 vp->stats.last_hdr_load = now;
6469 VChangeState_r(vp, state_save);
6471 #else /* AFS_DEMAND_ATTACH_FS */
6473 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
6474 IncUInt64(&VStats.hdr_loads);
6476 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
6477 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
6480 #endif /* AFS_DEMAND_ATTACH_FS */
6482 /* maintain (nUsers==0) => header in LRU invariant */
6483 FreeVolumeHeader(vp);
6488 * release a header cache entry back into the LRU list.
6490 * @param[in] hd pointer to volume header cache object
6492 * @pre VOL_LOCK held.
6494 * @post header cache object appended onto end of LRU list.
6496 * @note only applicable to fileServer program type.
6498 * @note used to place a header cache entry back into the
6499 * LRU pool without invalidating it as a cache entry.
6501 * @internal volume package internal use only.
6504 ReleaseVolumeHeader(register struct volHeader *hd)
6506 if (programType != fileServer)
6508 if (!hd || queue_IsOnQueue(hd)) /* no header, or header already released */
6510 queue_Append(&volume_hdr_LRU, hd);
6511 #ifdef AFS_DEMAND_ATTACH_FS
6513 V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
6516 volume_hdr_LRU.stats.free++;
6517 volume_hdr_LRU.stats.used--;
6521 * free/invalidate a volume header cache entry.
6523 * @param[in] vp pointer to volume object
6525 * @pre VOL_LOCK is held.
6527 * @post For fileserver, header cache entry is returned to LRU, and it is
6528 * invalidated as a cache entry. For volume utilities, the header
6529 * cache entry is freed.
6531 * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
6532 * whenever it is necessary to invalidate the header cache entry.
6534 * @see ReleaseVolumeHeader
6536 * @internal volume package internal use only.
6539 FreeVolumeHeader(register Volume * vp)
6541 register struct volHeader *hd = vp->header;
6544 if (programType == fileServer) {
6545 ReleaseVolumeHeader(hd);
6550 #ifdef AFS_DEMAND_ATTACH_FS
6551 V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
6553 volume_hdr_LRU.stats.attached--;
6558 /***************************************************/
6559 /* Volume Hash Table routines */
6560 /***************************************************/
6563 * set size of volume object hash table.
6565 * @param[in] logsize log(2) of desired hash table size
6567 * @return operation status
6569 * @retval -1 failure
6571 * @pre MUST be called prior to VInitVolumePackage
6573 * @post Volume Hash Table will have 2^logsize buckets
6576 VSetVolHashSize(int logsize)
6578 /* 64 to 16384 hash buckets seems like a reasonable range */
6579 if ((logsize < 6 ) || (logsize > 14)) {
6584 VolumeHashTable.Size = 1 << logsize;
6585 VolumeHashTable.Mask = VolumeHashTable.Size - 1;
6587 /* we can't yet support runtime modification of this
6588 * parameter. we'll need a configuration rwlock to
6589 * make runtime modification feasible.... */
6596 * initialize dynamic data structures for volume hash table.
6598 * @post hash table is allocated, and fields are initialized.
6600 * @internal volume package internal use only.
6603 VInitVolumeHash(void)
6607 VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
6608 sizeof(VolumeHashChainHead));
6609 assert(VolumeHashTable.Table != NULL);
6611 for (i=0; i < VolumeHashTable.Size; i++) {
6612 queue_Init(&VolumeHashTable.Table[i]);
6613 #ifdef AFS_DEMAND_ATTACH_FS
6614 assert(pthread_cond_init(&VolumeHashTable.Table[i].chain_busy_cv, NULL) == 0);
6615 #endif /* AFS_DEMAND_ATTACH_FS */
6620 * add a volume object to the hash table.
6622 * @param[in] vp pointer to volume object
6623 * @param[in] hashid hash of volume id
6625 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
6628 * @post volume is added to hash chain.
6630 * @internal volume package internal use only.
6632 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
6633 * asynchronous hash chain reordering to finish.
6636 AddVolumeToHashTable(register Volume * vp, int hashid)
6638 VolumeHashChainHead * head;
6640 if (queue_IsOnQueue(vp))
6643 head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
6645 #ifdef AFS_DEMAND_ATTACH_FS
6646 /* wait for the hash chain to become available */
6649 V_attachFlags(vp) |= VOL_IN_HASH;
6650 vp->chainCacheCheck = ++head->cacheCheck;
6651 #endif /* AFS_DEMAND_ATTACH_FS */
6654 vp->hashid = hashid;
6655 queue_Append(head, vp);
6656 vp->vnodeHashOffset = VolumeHashOffset_r();
6660 * delete a volume object from the hash table.
6662 * @param[in] vp pointer to volume object
6664 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
6667 * @post volume is removed from hash chain.
6669 * @internal volume package internal use only.
6671 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
6672 * asynchronous hash chain reordering to finish.
6675 DeleteVolumeFromHashTable(register Volume * vp)
6677 VolumeHashChainHead * head;
6679 if (!queue_IsOnQueue(vp))
6682 head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
6684 #ifdef AFS_DEMAND_ATTACH_FS
6685 /* wait for the hash chain to become available */
6688 V_attachFlags(vp) &= ~(VOL_IN_HASH);
6690 #endif /* AFS_DEMAND_ATTACH_FS */
6694 /* do NOT reset hashid to zero, as the online
6695 * salvager package may need to know the volume id
6696 * after the volume is removed from the hash */
6700 * lookup a volume object in the hash table given a volume id.
6702 * @param[out] ec error code return
6703 * @param[in] volumeId volume id
6704 * @param[in] hint volume object which we believe could be the correct
6707 * @return volume object pointer
6708 * @retval NULL no such volume id is registered with the hash table.
6710 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
6713 * @post volume object with the given id is returned. volume object and
6714 * hash chain access statistics are updated. hash chain may have
6717 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
6718 * asynchronous hash chain reordering operation to finish, or
6719 * in order for us to perform an asynchronous chain reordering.
6721 * @note Hash chain reorderings occur when the access count for the
6722 * volume object being looked up exceeds the sum of the previous
6723 * node's (the node ahead of it in the hash chain linked list)
6724 * access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
6726 * @note For DAFS, the hint parameter allows us to short-circuit if the
6727 * cacheCheck fields match between the hash chain head and the
6728 * hint volume object.
6731 VLookupVolume_r(Error * ec, VolId volumeId, Volume * hint)
6733 register int looks = 0;
6735 #ifdef AFS_DEMAND_ATTACH_FS
6738 VolumeHashChainHead * head;
6741 head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
6743 #ifdef AFS_DEMAND_ATTACH_FS
6744 /* wait for the hash chain to become available */
6747 /* check to see if we can short circuit without walking the hash chain */
6748 if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
6749 IncUInt64(&hint->stats.hash_short_circuits);
6752 #endif /* AFS_DEMAND_ATTACH_FS */
6754 /* someday we need to either do per-chain locks, RWlocks,
6755 * or both for volhash access.
6756 * (and move to a data structure with better cache locality) */
6758 /* search the chain for this volume id */
6759 for(queue_Scan(head, vp, np, Volume)) {
6761 if ((vp->hashid == volumeId)) {
6766 if (queue_IsEnd(head, vp)) {
6770 #ifdef AFS_DEMAND_ATTACH_FS
6771 /* update hash chain statistics */
6774 FillInt64(lks, 0, looks);
6775 AddUInt64(head->looks, lks, &head->looks);
6776 AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
6777 IncUInt64(&head->gets);
6782 IncUInt64(&vp->stats.hash_lookups);
6784 /* for demand attach fileserver, we permit occasional hash chain reordering
6785 * so that frequently looked up volumes move towards the head of the chain */
6786 pp = queue_Prev(vp, Volume);
6787 if (!queue_IsEnd(head, pp)) {
6788 FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
6789 AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
6790 if (GEInt64(vp->stats.hash_lookups, thresh)) {
6791 VReorderHash_r(head, pp, vp);
6795 /* update the short-circuit cache check */
6796 vp->chainCacheCheck = head->cacheCheck;
6798 #endif /* AFS_DEMAND_ATTACH_FS */
6803 #ifdef AFS_DEMAND_ATTACH_FS
6804 /* perform volume hash chain reordering.
6806 * advance a subchain beginning at vp ahead of
6807 * the adjacent subchain ending at pp */
6809 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
6811 Volume *tp, *np, *lp;
6812 afs_uint64 move_thresh;
6814 /* this should never be called if the chain is already busy, so
6815 * no need to wait for other exclusive chain ops to finish */
6817 /* this is a rather heavy set of operations,
6818 * so let's set the chain busy flag and drop
6820 VHashBeginExclusive_r(head);
6823 /* scan forward in the chain from vp looking for the last element
6824 * in the chain we want to advance */
6825 FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
6826 AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
6827 for(queue_ScanFrom(head, vp, tp, np, Volume)) {
6828 if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
6832 lp = queue_Prev(tp, Volume);
6834 /* scan backwards from pp to determine where to splice and
6835 * insert the subchain we're advancing */
6836 for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
6837 if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
6841 tp = queue_Next(tp, Volume);
6843 /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
6844 queue_MoveChainBefore(tp,vp,lp);
6847 IncUInt64(&VStats.hash_reorders);
6849 IncUInt64(&head->reorders);
6851 /* wake up any threads waiting for the hash chain */
6852 VHashEndExclusive_r(head);
6856 /* demand-attach fs volume hash
6857 * asynchronous exclusive operations */
6860 * begin an asynchronous exclusive operation on a volume hash chain.
6862 * @param[in] head pointer to volume hash chain head object
6864 * @pre VOL_LOCK held. hash chain is quiescent.
6866 * @post hash chain marked busy.
6868 * @note this interface is used in conjunction with VHashEndExclusive_r and
6869 * VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
6870 * volume hash chain. Its main use case is hash chain reordering, which
6871 * has the potential to be a highly latent operation.
6873 * @see VHashEndExclusive_r
6878 * @internal volume package internal use only.
6881 VHashBeginExclusive_r(VolumeHashChainHead * head)
6883 assert(head->busy == 0);
6888 * relinquish exclusive ownership of a volume hash chain.
6890 * @param[in] head pointer to volume hash chain head object
6892 * @pre VOL_LOCK held. thread owns the hash chain exclusively.
6894 * @post hash chain is marked quiescent. threads awaiting use of
6895 * chain are awakened.
6897 * @see VHashBeginExclusive_r
6902 * @internal volume package internal use only.
6905 VHashEndExclusive_r(VolumeHashChainHead * head)
6909 assert(pthread_cond_broadcast(&head->chain_busy_cv) == 0);
6913 * wait for all asynchronous operations on a hash chain to complete.
6915 * @param[in] head pointer to volume hash chain head object
6917 * @pre VOL_LOCK held.
6919 * @post hash chain object is quiescent.
6921 * @see VHashBeginExclusive_r
6922 * @see VHashEndExclusive_r
6926 * @note This interface should be called before any attempt to
6927 * traverse the hash chain. It is permissible for a thread
6928 * to gain exclusive access to the chain, and then perform
6929 * latent operations on the chain asynchronously wrt the
6932 * @warning if waiting is necessary, VOL_LOCK is dropped
6934 * @internal volume package internal use only.
6937 VHashWait_r(VolumeHashChainHead * head)
6939 while (head->busy) {
6940 VOL_CV_WAIT(&head->chain_busy_cv);
6943 #endif /* AFS_DEMAND_ATTACH_FS */
6946 /***************************************************/
6947 /* Volume by Partition List routines */
6948 /***************************************************/
6951 * demand attach fileserver adds a
6952 * linked list of volumes to each
6953 * partition object, thus allowing
6954 * for quick enumeration of all
6955 * volumes on a partition
6958 #ifdef AFS_DEMAND_ATTACH_FS
6960 * add a volume to its disk partition VByPList.
6962 * @param[in] vp pointer to volume object
6964 * @pre either the disk partition VByPList is owned exclusively
6965 * by the calling thread, or the list is quiescent and
6968 * @post volume is added to disk partition VByPList
6972 * @warning it is the caller's responsibility to ensure list
6975 * @see VVByPListWait_r
6976 * @see VVByPListBeginExclusive_r
6977 * @see VVByPListEndExclusive_r
6979 * @internal volume package internal use only.
6982 AddVolumeToVByPList_r(Volume * vp)
6984 if (queue_IsNotOnQueue(&vp->vol_list)) {
6985 queue_Append(&vp->partition->vol_list, &vp->vol_list);
6986 V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
6987 vp->partition->vol_list.len++;
6992 * delete a volume from its disk partition VByPList.
6994 * @param[in] vp pointer to volume object
6996 * @pre either the disk partition VByPList is owned exclusively
6997 * by the calling thread, or the list is quiescent and
7000 * @post volume is removed from the disk partition VByPList
7004 * @warning it is the caller's responsibility to ensure list
7007 * @see VVByPListWait_r
7008 * @see VVByPListBeginExclusive_r
7009 * @see VVByPListEndExclusive_r
7011 * @internal volume package internal use only.
7014 DeleteVolumeFromVByPList_r(Volume * vp)
7016 if (queue_IsOnQueue(&vp->vol_list)) {
7017 queue_Remove(&vp->vol_list);
7018 V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
7019 vp->partition->vol_list.len--;
7024 * begin an asynchronous exclusive operation on a VByPList.
7026 * @param[in] dp pointer to disk partition object
7028 * @pre VOL_LOCK held. VByPList is quiescent.
7030 * @post VByPList marked busy.
7032 * @note this interface is used in conjunction with VVByPListEndExclusive_r and
7033 * VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
7036 * @see VVByPListEndExclusive_r
7037 * @see VVByPListWait_r
7041 * @internal volume package internal use only.
7043 /* take exclusive control over the list */
7045 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
7047 assert(dp->vol_list.busy == 0);
7048 dp->vol_list.busy = 1;
7052 * relinquish exclusive ownership of a VByPList.
7054 * @param[in] dp pointer to disk partition object
7056 * @pre VOL_LOCK held. thread owns the VByPList exclusively.
7058 * @post VByPList is marked quiescent. threads awaiting use of
7059 * the list are awakened.
7061 * @see VVByPListBeginExclusive_r
7062 * @see VVByPListWait_r
7066 * @internal volume package internal use only.
7069 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
7071 assert(dp->vol_list.busy);
7072 dp->vol_list.busy = 0;
7073 assert(pthread_cond_broadcast(&dp->vol_list.cv) == 0);
7077 * wait for all asynchronous operations on a VByPList to complete.
7079 * @param[in] dp pointer to disk partition object
7081 * @pre VOL_LOCK is held.
7083 * @post disk partition's VByP list is quiescent
7087 * @note This interface should be called before any attempt to
7088 * traverse the VByPList. It is permissible for a thread
7089 * to gain exclusive access to the list, and then perform
7090 * latent operations on the list asynchronously wrt the
7093 * @warning if waiting is necessary, VOL_LOCK is dropped
7095 * @see VVByPListEndExclusive_r
7096 * @see VVByPListBeginExclusive_r
7098 * @internal volume package internal use only.
7101 VVByPListWait_r(struct DiskPartition64 * dp)
7103 while (dp->vol_list.busy) {
7104 VOL_CV_WAIT(&dp->vol_list.cv);
7107 #endif /* AFS_DEMAND_ATTACH_FS */
7109 /***************************************************/
7110 /* Volume Cache Statistics routines */
7111 /***************************************************/
7114 VPrintCacheStats_r(void)
7116 afs_uint32 get_hi, get_lo, load_hi, load_lo;
7117 register struct VnodeClassInfo *vcp;
7118 vcp = &VnodeClassInfo[vLarge];
7119 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);
7120 vcp = &VnodeClassInfo[vSmall];
7121 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);
7122 SplitInt64(VStats.hdr_gets, get_hi, get_lo);
7123 SplitInt64(VStats.hdr_loads, load_hi, load_lo);
7124 Log("Volume header cache, %d entries, %d gets, %d replacements\n",
7125 VStats.hdr_cache_size, get_lo, load_lo);
7129 VPrintCacheStats(void)
7132 VPrintCacheStats_r();
7136 #ifdef AFS_DEMAND_ATTACH_FS
7138 UInt64ToDouble(afs_uint64 * x)
7140 static double c32 = 4.0 * 1.073741824 * 1000000000.0;
7142 SplitInt64(*x, h, l);
7143 return (((double)h) * c32) + ((double) l);
7147 DoubleToPrintable(double x, char * buf, int len)
7149 static double billion = 1000000000.0;
7152 y[0] = (afs_uint32) (x / (billion * billion));
7153 y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
7154 y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
7157 snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
7159 snprintf(buf, len, "%d%09d", y[1], y[2]);
7161 snprintf(buf, len, "%d", y[2]);
7167 struct VLRUExtStatsEntry {
7171 struct VLRUExtStats {
7177 } queue_info[VLRU_QUEUE_INVALID];
7178 struct VLRUExtStatsEntry * vec;
7182 * add a 256-entry fudge factor onto the vector in case state changes
7183 * out from under us.
7185 #define VLRU_EXT_STATS_VEC_LEN_FUDGE 256
7188 * collect extended statistics for the VLRU subsystem.
7190 * @param[out] stats pointer to stats structure to be populated
7191 * @param[in] nvols number of volumes currently known to exist
7193 * @pre VOL_LOCK held
7195 * @post stats->vec allocated and populated
7197 * @return operation status
7202 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
7204 afs_uint32 cur, idx, len;
7205 struct rx_queue * qp, * nqp;
7207 struct VLRUExtStatsEntry * vec;
7209 len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
7210 vec = stats->vec = calloc(len,
7211 sizeof(struct VLRUExtStatsEntry));
7217 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
7218 VLRU_Wait_r(&volume_LRU.q[idx]);
7219 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7222 stats->queue_info[idx].start = cur;
7224 for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7226 /* out of space in vec */
7229 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7230 vec[cur].volid = vp->hashid;
7234 stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
7237 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7245 #define ENUMTOSTRING(en) #en
7246 #define ENUMCASE(en) \
7248 return ENUMTOSTRING(en); \
7252 vlru_idx_to_string(int idx)
7255 ENUMCASE(VLRU_QUEUE_NEW);
7256 ENUMCASE(VLRU_QUEUE_MID);
7257 ENUMCASE(VLRU_QUEUE_OLD);
7258 ENUMCASE(VLRU_QUEUE_CANDIDATE);
7259 ENUMCASE(VLRU_QUEUE_HELD);
7260 ENUMCASE(VLRU_QUEUE_INVALID);
7262 return "**UNKNOWN**";
7267 VPrintExtendedCacheStats_r(int flags)
7270 afs_uint32 vol_sum = 0;
7277 struct stats looks, gets, reorders, len;
7278 struct stats ch_looks, ch_gets, ch_reorders;
7280 VolumeHashChainHead *head;
7282 struct VLRUExtStats vlru_stats;
7284 /* zero out stats */
7285 memset(&looks, 0, sizeof(struct stats));
7286 memset(&gets, 0, sizeof(struct stats));
7287 memset(&reorders, 0, sizeof(struct stats));
7288 memset(&len, 0, sizeof(struct stats));
7289 memset(&ch_looks, 0, sizeof(struct stats));
7290 memset(&ch_gets, 0, sizeof(struct stats));
7291 memset(&ch_reorders, 0, sizeof(struct stats));
7293 for (i = 0; i < VolumeHashTable.Size; i++) {
7294 head = &VolumeHashTable.Table[i];
7297 VHashBeginExclusive_r(head);
7300 ch_looks.sum = UInt64ToDouble(&head->looks);
7301 ch_gets.sum = UInt64ToDouble(&head->gets);
7302 ch_reorders.sum = UInt64ToDouble(&head->reorders);
7304 /* update global statistics */
7306 looks.sum += ch_looks.sum;
7307 gets.sum += ch_gets.sum;
7308 reorders.sum += ch_reorders.sum;
7309 len.sum += (double)head->len;
7310 vol_sum += head->len;
7313 len.min = (double) head->len;
7314 len.max = (double) head->len;
7315 looks.min = ch_looks.sum;
7316 looks.max = ch_looks.sum;
7317 gets.min = ch_gets.sum;
7318 gets.max = ch_gets.sum;
7319 reorders.min = ch_reorders.sum;
7320 reorders.max = ch_reorders.sum;
7322 if (((double)head->len) < len.min)
7323 len.min = (double) head->len;
7324 if (((double)head->len) > len.max)
7325 len.max = (double) head->len;
7326 if (ch_looks.sum < looks.min)
7327 looks.min = ch_looks.sum;
7328 else if (ch_looks.sum > looks.max)
7329 looks.max = ch_looks.sum;
7330 if (ch_gets.sum < gets.min)
7331 gets.min = ch_gets.sum;
7332 else if (ch_gets.sum > gets.max)
7333 gets.max = ch_gets.sum;
7334 if (ch_reorders.sum < reorders.min)
7335 reorders.min = ch_reorders.sum;
7336 else if (ch_reorders.sum > reorders.max)
7337 reorders.max = ch_reorders.sum;
7341 if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
7342 /* compute detailed per-chain stats */
7343 struct stats hdr_loads, hdr_gets;
7344 double v_looks, v_loads, v_gets;
7346 /* initialize stats with data from first element in chain */
7347 vp = queue_First(head, Volume);
7348 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
7349 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
7350 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
7351 ch_gets.min = ch_gets.max = v_looks;
7352 hdr_loads.min = hdr_loads.max = v_loads;
7353 hdr_gets.min = hdr_gets.max = v_gets;
7354 hdr_loads.sum = hdr_gets.sum = 0;
7356 vp = queue_Next(vp, Volume);
7358 /* pull in stats from remaining elements in chain */
7359 for (queue_ScanFrom(head, vp, vp, np, Volume)) {
7360 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
7361 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
7362 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
7364 hdr_loads.sum += v_loads;
7365 hdr_gets.sum += v_gets;
7367 if (v_looks < ch_gets.min)
7368 ch_gets.min = v_looks;
7369 else if (v_looks > ch_gets.max)
7370 ch_gets.max = v_looks;
7372 if (v_loads < hdr_loads.min)
7373 hdr_loads.min = v_loads;
7374 else if (v_loads > hdr_loads.max)
7375 hdr_loads.max = v_loads;
7377 if (v_gets < hdr_gets.min)
7378 hdr_gets.min = v_gets;
7379 else if (v_gets > hdr_gets.max)
7380 hdr_gets.max = v_gets;
7383 /* compute per-chain averages */
7384 ch_gets.avg = ch_gets.sum / ((double)head->len);
7385 hdr_loads.avg = hdr_loads.sum / ((double)head->len);
7386 hdr_gets.avg = hdr_gets.sum / ((double)head->len);
7388 /* dump per-chain stats */
7389 Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
7391 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
7392 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
7393 Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
7394 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
7395 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
7396 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
7397 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
7398 Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
7399 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
7400 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
7401 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
7402 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
7403 Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
7404 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
7405 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
7406 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
7407 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
7408 } else if (flags & VOL_STATS_PER_CHAIN) {
7409 /* dump simple per-chain stats */
7410 Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
7412 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
7413 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
7414 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
7418 VHashEndExclusive_r(head);
7423 /* compute global averages */
7424 len.avg = len.sum / ((double)VolumeHashTable.Size);
7425 looks.avg = looks.sum / ((double)VolumeHashTable.Size);
7426 gets.avg = gets.sum / ((double)VolumeHashTable.Size);
7427 reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
7429 /* dump global stats */
7430 Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
7431 Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
7432 DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
7433 DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
7434 DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
7435 DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
7436 Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
7437 DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
7438 DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
7439 DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
7440 DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
7441 Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
7442 DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
7443 DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
7444 DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
7445 DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
7446 Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
7447 DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
7448 DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
7449 DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
7450 DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
7452 /* print extended disk related statistics */
7454 struct DiskPartition64 * diskP;
7455 afs_uint32 vol_count[VOLMAXPARTS+1];
7456 byte part_exists[VOLMAXPARTS+1];
7460 memset(vol_count, 0, sizeof(vol_count));
7461 memset(part_exists, 0, sizeof(part_exists));
7465 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
7467 vol_count[id] = diskP->vol_list.len;
7468 part_exists[id] = 1;
7472 for (i = 0; i <= VOLMAXPARTS; i++) {
7473 if (part_exists[i]) {
7474 /* XXX while this is currently safe, it is a violation
7475 * of the VGetPartitionById_r interface contract. */
7476 diskP = VGetPartitionById_r(i, 0);
7478 Log("Partition %s has %d online volumes\n",
7479 VPartitionPath(diskP), diskP->vol_list.len);
7486 /* print extended VLRU statistics */
7487 if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
7488 afs_uint32 idx, cur, lpos;
7492 Log("VLRU State Dump:\n\n");
7494 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
7495 Log("\t%s:\n", vlru_idx_to_string(idx));
7498 for (cur = vlru_stats.queue_info[idx].start;
7499 cur < vlru_stats.queue_info[idx].len;
7501 line[lpos++] = vlru_stats.vec[cur].volid;
7503 Log("\t\t%u, %u, %u, %u, %u,\n",
7504 line[0], line[1], line[2], line[3], line[4]);
7513 Log("\t\t%u, %u, %u, %u, %u\n",
7514 line[0], line[1], line[2], line[3], line[4]);
7519 free(vlru_stats.vec);
7526 VPrintExtendedCacheStats(int flags)
7529 VPrintExtendedCacheStats_r(flags);
7532 #endif /* AFS_DEMAND_ATTACH_FS */