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) 2006 Sine Nomine Associates
12 /* 1/1/89: NB: this stuff is all going to be replaced. Don't take it too seriously */
17 Institution: The Information Technology Center, Carnegie-Mellon University
21 #include <afsconfig.h>
22 #include <afs/param.h>
28 #include <afs/afsint.h>
31 #include <sys/param.h>
32 #if !defined(AFS_SGI_ENV)
35 #else /* AFS_OSF_ENV */
36 #ifdef AFS_VFSINCL_ENV
39 #include <sys/fs/ufs_fs.h>
41 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
42 #include <ufs/ufs/dinode.h>
43 #include <ufs/ffs/fs.h>
48 #else /* AFS_VFSINCL_ENV */
49 #if !defined(AFS_AIX_ENV) && !defined(AFS_LINUX20_ENV) && !defined(AFS_XBSD_ENV)
52 #endif /* AFS_VFSINCL_ENV */
53 #endif /* AFS_OSF_ENV */
54 #endif /* AFS_SGI_ENV */
55 #endif /* AFS_NT40_ENV */
73 #if defined(AFS_SUN_ENV) || defined(AFS_SUN5_ENV)
75 #include <sys/mnttab.h>
76 #include <sys/mntent.h>
82 #if defined(AFS_SGI_ENV)
87 #ifndef AFS_LINUX20_ENV
88 #include <fstab.h> /* Need to find in libc 5, present in libc 6 */
91 #endif /* AFS_SGI_ENV */
93 #endif /* AFS_HPUX_ENV */
97 #include <netinet/in.h>
101 #include <sys/time.h>
102 #endif /* ITIMER_REAL */
103 #endif /* AFS_NT40_ENV */
104 #if defined(AFS_SUN5_ENV) || defined(AFS_NT40_ENV) || defined(AFS_LINUX20_ENV)
111 #include <afs/errors.h>
114 #include <afs/afssyscalls.h>
116 #include <afs/afsutil.h>
120 #include "daemon_com.h"
122 #include "salvsync.h"
125 #include "partition.h"
126 #ifdef AFS_PTHREAD_ENV
128 #else /* AFS_PTHREAD_ENV */
129 #include "afs/assert.h"
130 #endif /* AFS_PTHREAD_ENV */
137 #if !defined(offsetof)
142 #define afs_stat stat64
143 #define afs_fstat fstat64
144 #define afs_open open64
145 #else /* !O_LARGEFILE */
146 #define afs_stat stat
147 #define afs_fstat fstat
148 #define afs_open open
149 #endif /* !O_LARGEFILE */
151 #ifdef AFS_PTHREAD_ENV
152 pthread_mutex_t vol_glock_mutex;
153 pthread_mutex_t vol_trans_mutex;
154 pthread_cond_t vol_put_volume_cond;
155 pthread_cond_t vol_sleep_cond;
156 int vol_attach_threads = 1;
157 #endif /* AFS_PTHREAD_ENV */
159 #ifdef AFS_DEMAND_ATTACH_FS
160 pthread_mutex_t vol_salvsync_mutex;
161 #endif /* AFS_DEMAND_ATTACH_FS */
164 extern void *calloc(), *realloc();
167 /*@printflike@*/ extern void Log(const char *format, ...);
169 /* Forward declarations */
170 static Volume *attach2(Error * ec, VolId vid, char *path,
171 register struct VolumeHeader *header,
172 struct DiskPartition *partp, Volume * vp,
173 int isbusy, int mode);
174 static void ReallyFreeVolume(Volume * vp);
175 #ifdef AFS_DEMAND_ATTACH_FS
176 static void FreeVolume(Volume * vp);
177 #else /* !AFS_DEMAND_ATTACH_FS */
178 #define FreeVolume(vp) ReallyFreeVolume(vp)
179 static void VScanUpdateList(void);
180 #endif /* !AFS_DEMAND_ATTACH_FS */
181 static void VInitVolumeHeaderCache(afs_uint32 howMany);
182 static int GetVolumeHeader(register Volume * vp);
183 static void ReleaseVolumeHeader(register struct volHeader *hd);
184 static void FreeVolumeHeader(register Volume * vp);
185 static void AddVolumeToHashTable(register Volume * vp, int hashid);
186 static void DeleteVolumeFromHashTable(register Volume * vp);
187 static int VHold(Volume * vp);
188 static int VHold_r(Volume * vp);
189 static void VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class);
190 static void GetVolumePath(Error * ec, VolId volumeId, char **partitionp,
192 static void VReleaseVolumeHandles_r(Volume * vp);
193 static void VCloseVolumeHandles_r(Volume * vp);
194 static void LoadVolumeHeader(Error * ec, Volume * vp);
195 static int VCheckOffline(register Volume * vp);
196 static int VCheckDetach(register Volume * vp);
197 static Volume * GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint, int flags);
198 static int VolumeExternalName_r(VolumeId volumeId, char * name, size_t len);
200 int LogLevel; /* Vice loglevel--not defined as extern so that it will be
201 * defined when not linked with vice, XXXX */
202 ProgramType programType; /* The type of program using the package */
204 /* extended volume package statistics */
208 #define VOLUME_BITMAP_GROWSIZE 16 /* bytes, => 128vnodes */
209 /* Must be a multiple of 4 (1 word) !! */
211 /* this parameter needs to be tunable at runtime.
212 * 128 was really inadequate for largish servers -- at 16384 volumes this
213 * puts average chain length at 128, thus an average 65 deref's to find a volptr.
214 * talk about bad spatial locality...
216 * an AVL or splay tree might work a lot better, but we'll just increase
217 * the default hash table size for now
219 #define DEFAULT_VOLUME_HASH_SIZE 256 /* Must be a power of 2!! */
220 #define DEFAULT_VOLUME_HASH_MASK (DEFAULT_VOLUME_HASH_SIZE-1)
221 #define VOLUME_HASH(volumeId) (volumeId&(VolumeHashTable.Mask))
224 * turn volume hash chains into partially ordered lists.
225 * when the threshold is exceeded between two adjacent elements,
226 * perform a chain rebalancing operation.
228 * keep the threshold high in order to keep cache line invalidates
229 * low "enough" on SMPs
231 #define VOLUME_HASH_REORDER_THRESHOLD 200
234 * when possible, don't just reorder single elements, but reorder
235 * entire chains of elements at once. a chain of elements that
236 * exceed the element previous to the pivot by at least CHAIN_THRESH
237 * accesses are moved in front of the chain whose elements have at
238 * least CHAIN_THRESH less accesses than the pivot element
240 #define VOLUME_HASH_REORDER_CHAIN_THRESH (VOLUME_HASH_REORDER_THRESHOLD / 2)
242 #include "rx/rx_queue.h"
245 VolumeHashTable_t VolumeHashTable = {
246 DEFAULT_VOLUME_HASH_SIZE,
247 DEFAULT_VOLUME_HASH_MASK,
252 static void VInitVolumeHash(void);
256 /* This macro is used where an ffs() call does not exist. Was in util/ffs.c */
260 afs_int32 ffs_tmp = x;
264 for (ffs_i = 1;; ffs_i++) {
271 #endif /* !AFS_HAVE_FFS */
273 #ifdef AFS_PTHREAD_ENV
274 typedef struct diskpartition_queue_t {
275 struct rx_queue queue;
276 struct DiskPartition * diskP;
277 } diskpartition_queue_t;
278 typedef struct vinitvolumepackage_thread_t {
279 struct rx_queue queue;
280 pthread_cond_t thread_done_cv;
281 int n_threads_complete;
282 } vinitvolumepackage_thread_t;
283 static void * VInitVolumePackageThread(void * args);
284 #endif /* AFS_PTHREAD_ENV */
286 static int VAttachVolumesByPartition(struct DiskPartition *diskP,
287 int * nAttached, int * nUnattached);
290 #ifdef AFS_DEMAND_ATTACH_FS
291 /* demand attach fileserver extensions */
294 * in the future we will support serialization of VLRU state into the fs_state
297 * these structures are the beginning of that effort
299 struct VLRU_DiskHeader {
300 struct versionStamp stamp; /* magic and structure version number */
301 afs_uint32 mtime; /* time of dump to disk */
302 afs_uint32 num_records; /* number of VLRU_DiskEntry records */
305 struct VLRU_DiskEntry {
306 afs_uint32 vid; /* volume ID */
307 afs_uint32 idx; /* generation */
308 afs_uint32 last_get; /* timestamp of last get */
311 struct VLRU_StartupQueue {
312 struct VLRU_DiskEntry * entry;
317 typedef struct vshutdown_thread_t {
319 pthread_mutex_t lock;
321 pthread_cond_t master_cv;
323 int n_threads_complete;
325 int schedule_version;
328 byte n_parts_done_pass;
329 byte part_thread_target[VOLMAXPARTS+1];
330 byte part_done_pass[VOLMAXPARTS+1];
331 struct rx_queue * part_pass_head[VOLMAXPARTS+1];
332 int stats[4][VOLMAXPARTS+1];
333 } vshutdown_thread_t;
334 static void * VShutdownThread(void * args);
337 static Volume * VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode);
338 static int VCheckFree(Volume * vp);
341 static void AddVolumeToVByPList_r(Volume * vp);
342 static void DeleteVolumeFromVByPList_r(Volume * vp);
343 static void VVByPListBeginExclusive_r(struct DiskPartition * dp);
344 static void VVByPListEndExclusive_r(struct DiskPartition * dp);
345 static void VVByPListWait_r(struct DiskPartition * dp);
347 /* online salvager */
348 static int VCheckSalvage(register Volume * vp);
349 static int VUpdateSalvagePriority_r(Volume * vp);
350 static int VScheduleSalvage_r(Volume * vp);
351 static int VCancelSalvage_r(Volume * vp, int reason);
353 /* Volume hash table */
354 static void VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp);
355 static void VHashBeginExclusive_r(VolumeHashChainHead * head);
356 static void VHashEndExclusive_r(VolumeHashChainHead * head);
357 static void VHashWait_r(VolumeHashChainHead * head);
359 /* Volume state machine */
360 static void VCreateReservation_r(Volume * vp);
361 static void VCancelReservation_r(Volume * vp);
362 static void VWaitStateChange_r(Volume * vp);
363 static void VWaitExclusiveState_r(Volume * vp);
364 static int IsExclusiveState(VolState state);
365 static int IsErrorState(VolState state);
366 static int IsValidState(VolState state);
369 static int ShutdownVByPForPass_r(struct DiskPartition * dp, int pass);
370 static int ShutdownVolumeWalk_r(struct DiskPartition * dp, int pass,
371 struct rx_queue ** idx);
372 static void ShutdownController(vshutdown_thread_t * params);
373 static void ShutdownCreateSchedule(vshutdown_thread_t * params);
376 static void VLRU_ComputeConstants(void);
377 static void VInitVLRU(void);
378 static void VLRU_Init_Node_r(volatile Volume * vp);
379 static void VLRU_Add_r(volatile Volume * vp);
380 static void VLRU_Delete_r(volatile Volume * vp);
381 static void VLRU_UpdateAccess_r(volatile Volume * vp);
382 static void * VLRU_ScannerThread(void * args);
383 static void VLRU_Scan_r(int idx);
384 static void VLRU_Promote_r(int idx);
385 static void VLRU_Demote_r(int idx);
386 static void VLRU_SwitchQueues(volatile Volume * vp, int new_idx, int append);
389 static int VCheckSoftDetach(volatile Volume * vp, afs_uint32 thresh);
390 static int VCheckSoftDetachCandidate(volatile Volume * vp, afs_uint32 thresh);
391 static int VSoftDetachVolume_r(volatile Volume * vp, afs_uint32 thresh);
392 #endif /* AFS_DEMAND_ATTACH_FS */
395 struct Lock vol_listLock; /* Lock obtained when listing volumes:
396 * prevents a volume from being missed
397 * if the volume is attached during a
401 static int TimeZoneCorrection; /* Number of seconds west of GMT */
403 /* Common message used when the volume goes off line */
404 char *VSalvageMessage =
405 "Files in this volume are currently unavailable; call operations";
407 int VInit; /* 0 - uninitialized,
408 * 1 - initialized but not all volumes have been attached,
409 * 2 - initialized and all volumes have been attached,
410 * 3 - initialized, all volumes have been attached, and
411 * VConnectFS() has completed. */
414 bit32 VolumeCacheCheck; /* Incremented everytime a volume goes on line--
415 * used to stamp volume headers and in-core
416 * vnodes. When the volume goes on-line the
417 * vnode will be invalidated
418 * access only with VOL_LOCK held */
423 /***************************************************/
424 /* Startup routines */
425 /***************************************************/
428 VInitVolumePackage(ProgramType pt, afs_uint32 nLargeVnodes, afs_uint32 nSmallVnodes,
429 int connect, afs_uint32 volcache)
431 int errors = 0; /* Number of errors while finding vice partitions. */
437 #ifdef AFS_DEMAND_ATTACH_FS
438 memset(&VStats, 0, sizeof(VStats));
439 VStats.hdr_cache_size = 200;
442 VInitPartitionPackage();
444 VInitVnHashByVolume();
445 #ifdef AFS_DEMAND_ATTACH_FS
446 if (programType == fileServer) {
449 VLRU_SetOptions(VLRU_SET_ENABLED, 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 DiskPartition *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 pthread_cond_wait(¶ms.thread_done_cv,&vol_glock_mutex);
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 */
577 /* Attach all the volumes in this partition */
578 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
579 int nAttached = 0, nUnattached = 0;
580 assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
582 #endif /* AFS_PTHREAD_ENV */
585 VInit = 2; /* Initialized, and all volumes have been attached */
586 #ifdef FSSYNC_BUILD_CLIENT
587 if (programType == volumeUtility && connect) {
589 Log("Unable to connect to file server; aborted\n");
593 #ifdef AFS_DEMAND_ATTACH_FS
594 else if (programType == salvageServer) {
596 Log("Unable to connect to file server; aborted\n");
600 #endif /* AFS_DEMAND_ATTACH_FS */
601 #endif /* FSSYNC_BUILD_CLIENT */
605 #ifdef AFS_PTHREAD_ENV
607 VInitVolumePackageThread(void * args) {
608 int errors = 0; /* Number of errors while finding vice partitions. */
612 struct DiskPartition *diskP;
613 struct vinitvolumepackage_thread_t * params;
614 struct diskpartition_queue_t * dpq;
616 params = (vinitvolumepackage_thread_t *) args;
620 /* Attach all the volumes in this partition */
621 while (queue_IsNotEmpty(params)) {
622 int nAttached = 0, nUnattached = 0;
624 dpq = queue_First(params,diskpartition_queue_t);
630 assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
635 params->n_threads_complete++;
636 pthread_cond_signal(¶ms->thread_done_cv);
640 #endif /* AFS_PTHREAD_ENV */
643 * attach all volumes on a given disk partition
646 VAttachVolumesByPartition(struct DiskPartition *diskP, int * nAttached, int * nUnattached)
652 Log("Partition %s: attaching volumes\n", diskP->name);
653 dirp = opendir(VPartitionPath(diskP));
655 Log("opendir on Partition %s failed!\n", diskP->name);
659 while ((dp = readdir(dirp))) {
661 p = strrchr(dp->d_name, '.');
662 if (p != NULL && strcmp(p, VHDREXT) == 0) {
665 #ifdef AFS_DEMAND_ATTACH_FS
666 vp = VPreAttachVolumeByName(&error, diskP->name, dp->d_name,
668 #else /* AFS_DEMAND_ATTACH_FS */
669 vp = VAttachVolumeByName(&error, diskP->name, dp->d_name,
671 #endif /* AFS_DEMAND_ATTACH_FS */
672 (*(vp ? nAttached : nUnattached))++;
673 if (error == VOFFLINE)
674 Log("Volume %d stays offline (/vice/offline/%s exists)\n", VolumeNumber(dp->d_name), dp->d_name);
675 else if (LogLevel >= 5) {
676 Log("Partition %s: attached volume %d (%s)\n",
677 diskP->name, VolumeNumber(dp->d_name),
680 #if !defined(AFS_DEMAND_ATTACH_FS)
684 #endif /* AFS_DEMAND_ATTACH_FS */
688 Log("Partition %s: attached %d volumes; %d volumes not attached\n", diskP->name, *nAttached, *nUnattached);
694 /***************************************************/
695 /* Shutdown routines */
696 /***************************************************/
700 * highly multithreaded volume package shutdown
702 * with the demand attach fileserver extensions,
703 * VShutdown has been modified to be multithreaded.
704 * In order to achieve optimal use of many threads,
705 * the shutdown code involves one control thread and
706 * n shutdown worker threads. The control thread
707 * periodically examines the number of volumes available
708 * for shutdown on each partition, and produces a worker
709 * thread allocation schedule. The idea is to eliminate
710 * redundant scheduling computation on the workers by
711 * having a single master scheduler.
713 * The scheduler's objectives are:
715 * each partition with volumes remaining gets allocated
716 * at least 1 thread (assuming sufficient threads)
718 * threads are allocated proportional to the number of
719 * volumes remaining to be offlined. This ensures that
720 * the OS I/O scheduler has many requests to elevator
721 * seek on partitions that will (presumably) take the
722 * longest amount of time (from now) to finish shutdown
723 * (3) keep threads busy
724 * when there are extra threads, they are assigned to
725 * partitions using a simple round-robin algorithm
727 * In the future, we may wish to add the ability to adapt
728 * to the relative performance patterns of each disk
733 * multi-step shutdown process
735 * demand attach shutdown is a four-step process. Each
736 * shutdown "pass" shuts down increasingly more difficult
737 * volumes. The main purpose is to achieve better cache
738 * utilization during shutdown.
741 * shutdown volumes in the unattached, pre-attached
744 * shutdown attached volumes with cached volume headers
746 * shutdown all volumes in non-exclusive states
748 * shutdown all remaining volumes
755 register Volume *vp, *np;
756 register afs_int32 code;
757 #ifdef AFS_DEMAND_ATTACH_FS
758 struct DiskPartition * diskP;
759 struct diskpartition_queue_t * dpq;
760 vshutdown_thread_t params;
762 pthread_attr_t attrs;
764 memset(¶ms, 0, sizeof(vshutdown_thread_t));
766 for (params.n_parts=0, diskP = DiskPartitionList;
767 diskP; diskP = diskP->next, params.n_parts++);
769 Log("VShutdown: shutting down on-line volumes on %d partition%s...\n",
770 params.n_parts, params.n_parts > 1 ? "s" : "");
772 if (vol_attach_threads > 1) {
773 /* prepare for parallel shutdown */
774 params.n_threads = vol_attach_threads;
775 assert(pthread_mutex_init(¶ms.lock, NULL) == 0);
776 assert(pthread_cond_init(¶ms.cv, NULL) == 0);
777 assert(pthread_cond_init(¶ms.master_cv, NULL) == 0);
778 assert(pthread_attr_init(&attrs) == 0);
779 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
782 /* setup the basic partition information structures for
783 * parallel shutdown */
784 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
786 struct rx_queue * qp, * nqp;
790 VVByPListWait_r(diskP);
791 VVByPListBeginExclusive_r(diskP);
794 for (queue_Scan(&diskP->vol_list, qp, nqp, rx_queue)) {
795 vp = (Volume *)((char *)qp - offsetof(Volume, vol_list));
799 Log("VShutdown: partition %s has %d volumes with attached headers\n",
800 VPartitionPath(diskP), count);
803 /* build up the pass 0 shutdown work queue */
804 dpq = (struct diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
807 queue_Prepend(¶ms, dpq);
809 params.part_pass_head[diskP->device] = queue_First(&diskP->vol_list, rx_queue);
812 Log("VShutdown: beginning parallel fileserver shutdown\n");
813 Log("VShutdown: using %d threads to offline volumes on %d partition%s\n",
814 vol_attach_threads, params.n_parts, params.n_parts > 1 ? "s" : "" );
816 /* do pass 0 shutdown */
817 assert(pthread_mutex_lock(¶ms.lock) == 0);
818 for (i=0; i < params.n_threads; i++) {
819 assert(pthread_create
820 (&tid, &attrs, &VShutdownThread,
824 /* wait for all the pass 0 shutdowns to complete */
825 while (params.n_threads_complete < params.n_threads) {
826 assert(pthread_cond_wait(¶ms.master_cv, ¶ms.lock) == 0);
828 params.n_threads_complete = 0;
830 assert(pthread_cond_broadcast(¶ms.cv) == 0);
831 assert(pthread_mutex_unlock(¶ms.lock) == 0);
833 Log("VShutdown: pass 0 completed using the 1 thread per partition algorithm\n");
834 Log("VShutdown: starting passes 1 through 3 using finely-granular mp-fast algorithm\n");
836 /* run the parallel shutdown scheduler. it will drop the glock internally */
837 ShutdownController(¶ms);
839 /* wait for all the workers to finish pass 3 and terminate */
840 while (params.pass < 4) {
841 assert(pthread_cond_wait(¶ms.cv, &vol_glock_mutex) == 0);
844 assert(pthread_attr_destroy(&attrs) == 0);
845 assert(pthread_cond_destroy(¶ms.cv) == 0);
846 assert(pthread_cond_destroy(¶ms.master_cv) == 0);
847 assert(pthread_mutex_destroy(¶ms.lock) == 0);
849 /* drop the VByPList exclusive reservations */
850 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
851 VVByPListEndExclusive_r(diskP);
852 Log("VShutdown: %s stats : (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
853 VPartitionPath(diskP),
854 params.stats[0][diskP->device],
855 params.stats[1][diskP->device],
856 params.stats[2][diskP->device],
857 params.stats[3][diskP->device]);
860 Log("VShutdown: shutdown finished using %d threads\n", params.n_threads);
862 /* if we're only going to run one shutdown thread, don't bother creating
864 Log("VShutdown: beginning single-threaded fileserver shutdown\n");
866 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
867 VShutdownByPartition_r(diskP);
871 Log("VShutdown: complete.\n");
872 #else /* AFS_DEMAND_ATTACH_FS */
873 Log("VShutdown: shutting down on-line volumes...\n");
874 for (i = 0; i < VolumeHashTable.Size; i++) {
875 /* try to hold first volume in the hash table */
876 for (queue_Scan(&VolumeHashTable.Table[i],vp,np,Volume)) {
880 Log("VShutdown: Attempting to take volume %u offline.\n",
883 /* next, take the volume offline (drops reference count) */
884 VOffline_r(vp, "File server was shut down");
888 Log("VShutdown: complete.\n");
889 #endif /* AFS_DEMAND_ATTACH_FS */
900 #ifdef AFS_DEMAND_ATTACH_FS
903 * shutdown control thread
906 ShutdownController(vshutdown_thread_t * params)
909 struct DiskPartition * diskP;
911 vshutdown_thread_t shadow;
913 ShutdownCreateSchedule(params);
915 while ((params->pass < 4) &&
916 (params->n_threads_complete < params->n_threads)) {
917 /* recompute schedule once per second */
919 memcpy(&shadow, params, sizeof(vshutdown_thread_t));
923 Log("ShutdownController: schedule version=%d, vol_remaining=%d, pass=%d\n",
924 shadow.schedule_version, shadow.vol_remaining, shadow.pass);
925 Log("ShutdownController: n_threads_complete=%d, n_parts_done_pass=%d\n",
926 shadow.n_threads_complete, shadow.n_parts_done_pass);
927 for (diskP = DiskPartitionList; diskP; diskP=diskP->next) {
929 Log("ShutdownController: part[%d] : (len=%d, thread_target=%d, done_pass=%d, pass_head=%p)\n",
932 shadow.part_thread_target[id],
933 shadow.part_done_pass[id],
934 shadow.part_pass_head[id]);
940 ShutdownCreateSchedule(params);
944 /* create the shutdown thread work schedule.
945 * this scheduler tries to implement fairness
946 * by allocating at least 1 thread to each
947 * partition with volumes to be shutdown,
948 * and then it attempts to allocate remaining
949 * threads based upon the amount of work left
952 ShutdownCreateSchedule(vshutdown_thread_t * params)
954 struct DiskPartition * diskP;
955 int sum, thr_workload, thr_left;
956 int part_residue[VOLMAXPARTS+1];
959 /* compute the total number of outstanding volumes */
961 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
962 sum += diskP->vol_list.len;
965 params->schedule_version++;
966 params->vol_remaining = sum;
971 /* compute average per-thread workload */
972 thr_workload = sum / params->n_threads;
973 if (sum % params->n_threads)
976 thr_left = params->n_threads;
977 memset(&part_residue, 0, sizeof(part_residue));
979 /* for fairness, give every partition with volumes remaining
980 * at least one thread */
981 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
983 if (diskP->vol_list.len) {
984 params->part_thread_target[id] = 1;
987 params->part_thread_target[id] = 0;
991 if (thr_left && thr_workload) {
992 /* compute length-weighted workloads */
995 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
997 delta = (diskP->vol_list.len / thr_workload) -
998 params->part_thread_target[id];
1002 if (delta < thr_left) {
1003 params->part_thread_target[id] += delta;
1006 params->part_thread_target[id] += thr_left;
1014 /* try to assign any leftover threads to partitions that
1015 * had volume lengths closer to needing thread_target+1 */
1016 int max_residue, max_id;
1018 /* compute the residues */
1019 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1021 part_residue[id] = diskP->vol_list.len -
1022 (params->part_thread_target[id] * thr_workload);
1025 /* now try to allocate remaining threads to partitions with the
1026 * highest residues */
1029 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1031 if (part_residue[id] > max_residue) {
1032 max_residue = part_residue[id];
1041 params->part_thread_target[max_id]++;
1043 part_residue[max_id] = 0;
1048 /* punt and give any remaining threads equally to each partition */
1050 if (thr_left >= params->n_parts) {
1051 alloc = thr_left / params->n_parts;
1052 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1054 params->part_thread_target[id] += alloc;
1059 /* finish off the last of the threads */
1060 for (diskP = DiskPartitionList; thr_left && diskP; diskP = diskP->next) {
1062 params->part_thread_target[id]++;
1068 /* worker thread for parallel shutdown */
1070 VShutdownThread(void * args)
1072 struct rx_queue *qp;
1074 vshutdown_thread_t * params;
1075 int part, code, found, pass, schedule_version_save, count;
1076 struct DiskPartition *diskP;
1077 struct diskpartition_queue_t * dpq;
1080 params = (vshutdown_thread_t *) args;
1082 /* acquire the shutdown pass 0 lock */
1083 assert(pthread_mutex_lock(¶ms->lock) == 0);
1085 /* if there's still pass 0 work to be done,
1086 * get a work entry, and do a pass 0 shutdown */
1087 if (queue_IsNotEmpty(params)) {
1088 dpq = queue_First(params, diskpartition_queue_t);
1090 assert(pthread_mutex_unlock(¶ms->lock) == 0);
1096 while (ShutdownVolumeWalk_r(diskP, 0, ¶ms->part_pass_head[id]))
1098 params->stats[0][diskP->device] = count;
1099 assert(pthread_mutex_lock(¶ms->lock) == 0);
1102 params->n_threads_complete++;
1103 if (params->n_threads_complete == params->n_threads) {
1104 /* notify control thread that all workers have completed pass 0 */
1105 assert(pthread_cond_signal(¶ms->master_cv) == 0);
1107 while (params->pass == 0) {
1108 assert(pthread_cond_wait(¶ms->cv, ¶ms->lock) == 0);
1112 assert(pthread_mutex_unlock(¶ms->lock) == 0);
1115 pass = params->pass;
1118 /* now escalate through the more complicated shutdowns */
1120 schedule_version_save = params->schedule_version;
1122 /* find a disk partition to work on */
1123 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1125 if (params->part_thread_target[id] && !params->part_done_pass[id]) {
1126 params->part_thread_target[id]--;
1133 /* hmm. for some reason the controller thread couldn't find anything for
1134 * us to do. let's see if there's anything we can do */
1135 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1137 if (diskP->vol_list.len && !params->part_done_pass[id]) {
1140 } else if (!params->part_done_pass[id]) {
1141 params->part_done_pass[id] = 1;
1142 params->n_parts_done_pass++;
1144 Log("VShutdown: done shutting down volumes on partition %s.\n",
1145 VPartitionPath(diskP));
1151 /* do work on this partition until either the controller
1152 * creates a new schedule, or we run out of things to do
1153 * on this partition */
1156 while (!params->part_done_pass[id] &&
1157 (schedule_version_save == params->schedule_version)) {
1158 /* ShutdownVolumeWalk_r will drop the glock internally */
1159 if (!ShutdownVolumeWalk_r(diskP, pass, ¶ms->part_pass_head[id])) {
1160 if (!params->part_done_pass[id]) {
1161 params->part_done_pass[id] = 1;
1162 params->n_parts_done_pass++;
1164 Log("VShutdown: done shutting down volumes on partition %s.\n",
1165 VPartitionPath(diskP));
1173 params->stats[pass][id] += count;
1175 /* ok, everyone is done this pass, proceed */
1178 params->n_threads_complete++;
1179 while (params->pass == pass) {
1180 if (params->n_threads_complete == params->n_threads) {
1181 /* we are the last thread to complete, so we will
1182 * reinitialize worker pool state for the next pass */
1183 params->n_threads_complete = 0;
1184 params->n_parts_done_pass = 0;
1186 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1188 params->part_done_pass[id] = 0;
1189 params->part_pass_head[id] = queue_First(&diskP->vol_list, rx_queue);
1192 /* compute a new thread schedule before releasing all the workers */
1193 ShutdownCreateSchedule(params);
1195 /* wake up all the workers */
1196 assert(pthread_cond_broadcast(¶ms->cv) == 0);
1199 Log("VShutdown: pass %d completed using %d threads on %d partitions\n",
1200 pass, params->n_threads, params->n_parts);
1203 assert(pthread_cond_wait(¶ms->cv, &vol_glock_mutex) == 0);
1206 pass = params->pass;
1220 /* shut down all volumes on a given disk partition
1222 * note that this function will not allow mp-fast
1223 * shutdown of a partition */
1225 VShutdownByPartition_r(struct DiskPartition * dp)
1231 /* wait for other exclusive ops to finish */
1232 VVByPListWait_r(dp);
1234 /* begin exclusive access */
1235 VVByPListBeginExclusive_r(dp);
1237 /* pick the low-hanging fruit first,
1238 * then do the complicated ones last
1239 * (has the advantage of keeping
1240 * in-use volumes up until the bitter end) */
1241 for (pass = 0, total=0; pass < 4; pass++) {
1242 pass_stats[pass] = ShutdownVByPForPass_r(dp, pass);
1243 total += pass_stats[pass];
1246 /* end exclusive access */
1247 VVByPListEndExclusive_r(dp);
1249 Log("VShutdownByPartition: shut down %d volumes on %s (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1250 total, VPartitionPath(dp), pass_stats[0], pass_stats[1], pass_stats[2], pass_stats[3]);
1255 /* internal shutdown functionality
1257 * for multi-pass shutdown:
1258 * 0 to only "shutdown" {pre,un}attached and error state volumes
1259 * 1 to also shutdown attached volumes w/ volume header loaded
1260 * 2 to also shutdown attached volumes w/o volume header loaded
1261 * 3 to also shutdown exclusive state volumes
1263 * caller MUST hold exclusive access on the hash chain
1264 * because we drop vol_glock_mutex internally
1266 * this function is reentrant for passes 1--3
1267 * (e.g. multiple threads can cooperate to
1268 * shutdown a partition mp-fast)
1270 * pass 0 is not scaleable because the volume state data is
1271 * synchronized by vol_glock mutex, and the locking overhead
1272 * is too high to drop the lock long enough to do linked list
1276 ShutdownVByPForPass_r(struct DiskPartition * dp, int pass)
1278 struct rx_queue * q = queue_First(&dp->vol_list, rx_queue);
1281 while (ShutdownVolumeWalk_r(dp, pass, &q))
1287 /* conditionally shutdown one volume on partition dp
1288 * returns 1 if a volume was shutdown in this pass,
1291 ShutdownVolumeWalk_r(struct DiskPartition * dp, int pass,
1292 struct rx_queue ** idx)
1294 struct rx_queue *qp, *nqp;
1299 for (queue_ScanFrom(&dp->vol_list, qp, qp, nqp, rx_queue)) {
1300 vp = (Volume *) (((char *)qp) - offsetof(Volume, vol_list));
1304 if ((V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1305 (V_attachState(vp) != VOL_STATE_ERROR) &&
1306 (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1310 if ((V_attachState(vp) == VOL_STATE_ATTACHED) &&
1311 (vp->header == NULL)) {
1315 if (IsExclusiveState(V_attachState(vp))) {
1320 DeleteVolumeFromVByPList_r(vp);
1321 VShutdownVolume_r(vp);
1331 * shutdown a specific volume
1333 /* caller MUST NOT hold a heavyweight ref on vp */
1335 VShutdownVolume_r(Volume * vp)
1339 VCreateReservation_r(vp);
1341 if (LogLevel >= 5) {
1342 Log("VShutdownVolume_r: vid=%u, device=%d, state=%hu\n",
1343 vp->hashid, vp->partition->device, V_attachState(vp));
1346 /* wait for other blocking ops to finish */
1347 VWaitExclusiveState_r(vp);
1349 assert(IsValidState(V_attachState(vp)));
1351 switch(V_attachState(vp)) {
1352 case VOL_STATE_SALVAGING:
1353 /* make sure salvager knows we don't want
1354 * the volume back */
1355 VCancelSalvage_r(vp, SALVSYNC_SHUTDOWN);
1356 case VOL_STATE_PREATTACHED:
1357 case VOL_STATE_ERROR:
1358 VChangeState_r(vp, VOL_STATE_UNATTACHED);
1359 case VOL_STATE_UNATTACHED:
1361 case VOL_STATE_GOING_OFFLINE:
1362 case VOL_STATE_SHUTTING_DOWN:
1363 case VOL_STATE_ATTACHED:
1367 Log("VShutdown: Attempting to take volume %u offline.\n",
1370 /* take the volume offline (drops reference count) */
1371 VOffline_r(vp, "File server was shut down");
1376 VCancelReservation_r(vp);
1380 #endif /* AFS_DEMAND_ATTACH_FS */
1383 /***************************************************/
1384 /* Header I/O routines */
1385 /***************************************************/
1387 /* open a descriptor for the inode (h),
1388 * read in an on-disk structure into buffer (to) of size (size),
1389 * verify versionstamp in structure has magic (magic) and
1390 * optionally verify version (version) if (version) is nonzero
1393 ReadHeader(Error * ec, IHandle_t * h, char *to, int size, bit32 magic,
1396 struct versionStamp *vsn;
1411 if (FDH_SEEK(fdP, 0, SEEK_SET) < 0) {
1413 FDH_REALLYCLOSE(fdP);
1416 vsn = (struct versionStamp *)to;
1417 if (FDH_READ(fdP, to, size) != size || vsn->magic != magic) {
1419 FDH_REALLYCLOSE(fdP);
1424 /* Check is conditional, in case caller wants to inspect version himself */
1425 if (version && vsn->version != version) {
1431 WriteVolumeHeader_r(Error * ec, Volume * vp)
1433 IHandle_t *h = V_diskDataHandle(vp);
1443 if (FDH_SEEK(fdP, 0, SEEK_SET) < 0) {
1445 FDH_REALLYCLOSE(fdP);
1448 if (FDH_WRITE(fdP, (char *)&V_disk(vp), sizeof(V_disk(vp)))
1449 != sizeof(V_disk(vp))) {
1451 FDH_REALLYCLOSE(fdP);
1457 /* VolumeHeaderToDisk
1458 * Allows for storing 64 bit inode numbers in on-disk volume header
1461 /* convert in-memory representation of a volume header to the
1462 * on-disk representation of a volume header */
1464 VolumeHeaderToDisk(VolumeDiskHeader_t * dh, VolumeHeader_t * h)
1467 memset((char *)dh, 0, sizeof(VolumeDiskHeader_t));
1468 dh->stamp = h->stamp;
1470 dh->parent = h->parent;
1472 #ifdef AFS_64BIT_IOPS_ENV
1473 dh->volumeInfo_lo = (afs_int32) h->volumeInfo & 0xffffffff;
1474 dh->volumeInfo_hi = (afs_int32) (h->volumeInfo >> 32) & 0xffffffff;
1475 dh->smallVnodeIndex_lo = (afs_int32) h->smallVnodeIndex & 0xffffffff;
1476 dh->smallVnodeIndex_hi =
1477 (afs_int32) (h->smallVnodeIndex >> 32) & 0xffffffff;
1478 dh->largeVnodeIndex_lo = (afs_int32) h->largeVnodeIndex & 0xffffffff;
1479 dh->largeVnodeIndex_hi =
1480 (afs_int32) (h->largeVnodeIndex >> 32) & 0xffffffff;
1481 dh->linkTable_lo = (afs_int32) h->linkTable & 0xffffffff;
1482 dh->linkTable_hi = (afs_int32) (h->linkTable >> 32) & 0xffffffff;
1484 dh->volumeInfo_lo = h->volumeInfo;
1485 dh->smallVnodeIndex_lo = h->smallVnodeIndex;
1486 dh->largeVnodeIndex_lo = h->largeVnodeIndex;
1487 dh->linkTable_lo = h->linkTable;
1491 /* DiskToVolumeHeader
1492 * Converts an on-disk representation of a volume header to
1493 * the in-memory representation of a volume header.
1495 * Makes the assumption that AFS has *always*
1496 * zero'd the volume header file so that high parts of inode
1497 * numbers are 0 in older (SGI EFS) volume header files.
1500 DiskToVolumeHeader(VolumeHeader_t * h, VolumeDiskHeader_t * dh)
1502 memset((char *)h, 0, sizeof(VolumeHeader_t));
1503 h->stamp = dh->stamp;
1505 h->parent = dh->parent;
1507 #ifdef AFS_64BIT_IOPS_ENV
1509 (Inode) dh->volumeInfo_lo | ((Inode) dh->volumeInfo_hi << 32);
1511 h->smallVnodeIndex =
1512 (Inode) dh->smallVnodeIndex_lo | ((Inode) dh->
1513 smallVnodeIndex_hi << 32);
1515 h->largeVnodeIndex =
1516 (Inode) dh->largeVnodeIndex_lo | ((Inode) dh->
1517 largeVnodeIndex_hi << 32);
1519 (Inode) dh->linkTable_lo | ((Inode) dh->linkTable_hi << 32);
1521 h->volumeInfo = dh->volumeInfo_lo;
1522 h->smallVnodeIndex = dh->smallVnodeIndex_lo;
1523 h->largeVnodeIndex = dh->largeVnodeIndex_lo;
1524 h->linkTable = dh->linkTable_lo;
1529 /***************************************************/
1530 /* Volume Attachment routines */
1531 /***************************************************/
1533 #ifdef AFS_DEMAND_ATTACH_FS
1534 /* pre-attach a volume given its path
1536 * a pre-attached volume will only have its partition
1537 * and hashid fields initialized
1539 * at first call to VGetVolume, the volume will be
1543 VPreAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
1547 vp = VPreAttachVolumeByName_r(ec, partition, name, mode);
1553 VPreAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
1555 register Volume *vp = NULL;
1557 struct afs_stat status;
1558 struct DiskPartition *partp;
1564 assert(programType == fileServer);
1566 if (!(partp = VGetPartition_r(partition, 0))) {
1568 Log("VPreAttachVolume: Error getting partition (%s)\n", partition);
1572 volumeId = VolumeNumber(name);
1574 vp = VLookupVolume_r(ec, volumeId, NULL);
1579 return VPreAttachVolumeById_r(ec, partp, vp, volumeId);
1582 /* pre-attach a volume given its partition and volume id
1584 * if vp == NULL, then a new vp is created
1585 * if vp != NULL, then we assumed it is already on the hash chain
1588 VPreAttachVolumeById_r(Error * ec, struct DiskPartition * partp,
1589 Volume * vp, int vid)
1595 /* check to see if pre-attach already happened */
1597 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1598 !IsErrorState(V_attachState(vp))) {
1601 /* we're re-attaching a volume; clear out some old state */
1602 memset(&vp->salvage, 0, sizeof(struct VolumeOnlineSalvage));
1604 /* if we need to allocate a new Volume struct,
1605 * go ahead and drop the vol glock, otherwise
1606 * do the basic setup synchronised, as it's
1607 * probably not worth dropping the lock */
1610 /* allocate the volume structure */
1611 vp = nvp = (Volume *) malloc(sizeof(Volume));
1613 memset(vp, 0, sizeof(Volume));
1614 assert(pthread_cond_init(&V_attachCV(vp), NULL) == 0);
1617 /* link the volume with its associated vice partition */
1618 vp->device = partp->device;
1619 vp->partition = partp;
1622 /* if we dropped the lock, reacquire the lock,
1623 * check for pre-attach races, and then add
1624 * the volume to the hash table */
1627 nvp = VLookupVolume_r(ec, vid, NULL);
1632 } else if (nvp) { /* race detected */
1637 /* hack to make up for VChangeState_r() decrementing
1638 * the old state counter */
1639 VStats.state_levels[0]++;
1643 /* put pre-attached volume onto the hash table
1644 * and bring it up to the pre-attached state */
1645 AddVolumeToHashTable(vp, vp->hashid);
1646 AddVolumeToVByPList_r(vp);
1647 VLRU_Init_Node_r(vp);
1648 VChangeState_r(vp, VOL_STATE_PREATTACHED);
1651 Log("VPreAttachVolumeById_r: volume %u pre-attached\n", vp->hashid);
1659 #endif /* AFS_DEMAND_ATTACH_FS */
1661 /* Attach an existing volume, given its pathname, and return a
1662 pointer to the volume header information. The volume also
1663 normally goes online at this time. An offline volume
1664 must be reattached to make it go online */
1666 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
1670 retVal = VAttachVolumeByName_r(ec, partition, name, mode);
1676 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
1678 register Volume *vp = NULL, *svp = NULL;
1680 struct afs_stat status;
1681 struct VolumeDiskHeader diskHeader;
1682 struct VolumeHeader iheader;
1683 struct DiskPartition *partp;
1687 #ifdef AFS_DEMAND_ATTACH_FS
1688 VolumeStats stats_save;
1689 #endif /* AFS_DEMAND_ATTACH_FS */
1693 volumeId = VolumeNumber(name);
1695 if (!(partp = VGetPartition_r(partition, 0))) {
1697 Log("VAttachVolume: Error getting partition (%s)\n", partition);
1701 if (programType == volumeUtility) {
1703 VLockPartition_r(partition);
1704 } else if (programType == fileServer) {
1705 #ifdef AFS_DEMAND_ATTACH_FS
1706 /* lookup the volume in the hash table */
1707 vp = VLookupVolume_r(ec, volumeId, NULL);
1713 /* save any counters that are supposed to
1714 * be monotonically increasing over the
1715 * lifetime of the fileserver */
1716 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
1718 memset(&stats_save, 0, sizeof(VolumeStats));
1721 /* if there's something in the hash table, and it's not
1722 * in the pre-attach state, then we may need to detach
1723 * it before proceeding */
1724 if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1725 VCreateReservation_r(vp);
1726 VWaitExclusiveState_r(vp);
1728 /* at this point state must be one of:
1737 if (vp->specialStatus == VBUSY)
1740 /* if it's already attached, see if we can return it */
1741 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
1742 VGetVolumeByVp_r(ec, vp);
1744 VCancelReservation_r(vp);
1748 /* otherwise, we need to detach, and attempt to re-attach */
1749 VDetachVolume_r(ec, vp);
1751 Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
1754 /* if it isn't fully attached, delete from the hash tables,
1755 and let the refcounter handle the rest */
1756 DeleteVolumeFromHashTable(vp);
1757 DeleteVolumeFromVByPList_r(vp);
1760 VCancelReservation_r(vp);
1764 /* pre-attach volume if it hasn't been done yet */
1766 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
1767 (V_attachState(vp) == VOL_STATE_ERROR)) {
1769 vp = VPreAttachVolumeById_r(ec, partp, vp, volumeId);
1777 /* handle pre-attach races
1779 * multiple threads can race to pre-attach a volume,
1780 * but we can't let them race beyond that
1782 * our solution is to let the first thread to bring
1783 * the volume into an exclusive state win; the other
1784 * threads just wait until it finishes bringing the
1785 * volume online, and then they do a vgetvolumebyvp
1787 if (svp && (svp != vp)) {
1788 /* wait for other exclusive ops to finish */
1789 VCreateReservation_r(vp);
1790 VWaitExclusiveState_r(vp);
1792 /* get a heavyweight ref, kill the lightweight ref, and return */
1793 VGetVolumeByVp_r(ec, vp);
1794 VCancelReservation_r(vp);
1798 /* at this point, we are chosen as the thread to do
1799 * demand attachment for this volume. all other threads
1800 * doing a getvolume on vp->hashid will block until we finish */
1802 /* make sure any old header cache entries are invalidated
1803 * before proceeding */
1804 FreeVolumeHeader(vp);
1806 VChangeState_r(vp, VOL_STATE_ATTACHING);
1808 /* restore any saved counters */
1809 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
1810 #else /* AFS_DEMAND_ATTACH_FS */
1811 vp = VGetVolume_r(ec, volumeId);
1815 if (vp->specialStatus == VBUSY)
1817 VDetachVolume_r(ec, vp);
1819 Log("VAttachVolume: Error detaching volume (%s)\n", name);
1823 #endif /* AFS_DEMAND_ATTACH_FS */
1827 strcpy(path, VPartitionPath(partp));
1833 if ((fd = afs_open(path, O_RDONLY)) == -1 || afs_fstat(fd, &status) == -1) {
1834 Log("VAttachVolume: Failed to open %s (errno %d)\n", path, errno);
1841 n = read(fd, &diskHeader, sizeof(diskHeader));
1843 if (n != sizeof(diskHeader)
1844 || diskHeader.stamp.magic != VOLUMEHEADERMAGIC) {
1845 Log("VAttachVolume: Error reading volume header %s\n", path);
1850 if (diskHeader.stamp.version != VOLUMEHEADERVERSION) {
1851 Log("VAttachVolume: Volume %s, version number is incorrect; volume needs salvaged\n", path);
1857 DiskToVolumeHeader(&iheader, &diskHeader);
1858 #ifdef FSSYNC_BUILD_CLIENT
1859 if (programType == volumeUtility && mode != V_SECRETLY && mode != V_PEEK) {
1861 if (FSYNC_VolOp(iheader.id, partition, FSYNC_VOL_NEEDVOLUME, mode, NULL)
1863 Log("VAttachVolume: attach of volume %u apparently denied by file server\n", iheader.id);
1864 *ec = VNOVOL; /* XXXX */
1872 vp = (Volume *) calloc(1, sizeof(Volume));
1874 vp->device = partp->device;
1875 vp->partition = partp;
1876 #ifdef AFS_DEMAND_ATTACH_FS
1877 assert(pthread_cond_init(&V_attachCV(vp), NULL) == 0);
1878 #endif /* AFS_DEMAND_ATTACH_FS */
1881 /* attach2 is entered without any locks, and returns
1882 * with vol_glock_mutex held */
1883 vp = attach2(ec, volumeId, path, &iheader, partp, vp, isbusy, mode);
1885 if (programType == volumeUtility && vp) {
1886 #ifdef AFS_DEMAND_ATTACH_FS
1887 /* for dafs, we should tell the fileserver, except for V_PEEK
1888 * where we know it is not necessary */
1889 if (mode == V_PEEK) {
1890 vp->needsPutBack = 0;
1892 vp->needsPutBack = 1;
1894 #else /* !AFS_DEMAND_ATTACH_FS */
1895 /* duplicate computation in fssync.c about whether the server
1896 * takes the volume offline or not. If the volume isn't
1897 * offline, we must not return it when we detach the volume,
1898 * or the server will abort */
1899 if (mode == V_READONLY || mode == V_PEEK
1900 || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
1901 vp->needsPutBack = 0;
1903 vp->needsPutBack = 1;
1904 #endif /* !AFS_DEMAND_ATTACH_FS */
1906 /* OK, there's a problem here, but one that I don't know how to
1907 * fix right now, and that I don't think should arise often.
1908 * Basically, we should only put back this volume to the server if
1909 * it was given to us by the server, but since we don't have a vp,
1910 * we can't run the VolumeWriteable function to find out as we do
1911 * above when computing vp->needsPutBack. So we send it back, but
1912 * there's a path in VAttachVolume on the server which may abort
1913 * if this volume doesn't have a header. Should be pretty rare
1914 * for all of that to happen, but if it does, probably the right
1915 * fix is for the server to allow the return of readonly volumes
1916 * that it doesn't think are really checked out. */
1917 #ifdef FSSYNC_BUILD_CLIENT
1918 if (programType == volumeUtility && vp == NULL &&
1919 mode != V_SECRETLY && mode != V_PEEK) {
1920 FSYNC_VolOp(iheader.id, partition, FSYNC_VOL_ON, 0, NULL);
1923 if (programType == fileServer && vp) {
1924 V_needsCallback(vp) = 0;
1926 if (VInit >= 2 && V_BreakVolumeCallbacks) {
1927 Log("VAttachVolume: Volume %u was changed externally; breaking callbacks\n", V_id(vp));
1928 (*V_BreakVolumeCallbacks) (V_id(vp));
1931 VUpdateVolume_r(ec, vp, 0);
1933 Log("VAttachVolume: Error updating volume\n");
1938 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
1939 #ifndef AFS_DEMAND_ATTACH_FS
1940 /* This is a hack: by temporarily setting the incore
1941 * dontSalvage flag ON, the volume will be put back on the
1942 * Update list (with dontSalvage OFF again). It will then
1943 * come back in N minutes with DONT_SALVAGE eventually
1944 * set. This is the way that volumes that have never had
1945 * it set get it set; or that volumes that have been
1946 * offline without DONT SALVAGE having been set also
1947 * eventually get it set */
1948 V_dontSalvage(vp) = DONT_SALVAGE;
1949 #endif /* !AFS_DEMAND_ATTACH_FS */
1950 VAddToVolumeUpdateList_r(ec, vp);
1952 Log("VAttachVolume: Error adding volume to update list\n");
1959 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
1963 if (programType == volumeUtility) {
1964 VUnlockPartition_r(partition);
1967 #ifdef AFS_DEMAND_ATTACH_FS
1969 V_attachState(vp) = VOL_STATE_ERROR;
1970 assert(pthread_cond_broadcast(&V_attachCV(vp)) == 0);
1972 #endif /* AFS_DEMAND_ATTACH_FS */
1979 #ifdef AFS_DEMAND_ATTACH_FS
1980 /* VAttachVolumeByVp_r
1982 * finish attaching a volume that is
1983 * in a less than fully attached state
1985 /* caller MUST hold a ref count on vp */
1987 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
1989 char name[VMAXPATHLEN];
1990 int fd, n, reserve = 0;
1991 struct afs_stat status;
1992 struct VolumeDiskHeader diskHeader;
1993 struct VolumeHeader iheader;
1994 struct DiskPartition *partp;
1999 VolumeStats stats_save;
2002 /* volume utility should never call AttachByVp */
2003 assert(programType == fileServer);
2005 volumeId = vp->hashid;
2006 partp = vp->partition;
2007 VolumeExternalName_r(volumeId, name, sizeof(name));
2010 /* if another thread is performing a blocking op, wait */
2011 VWaitExclusiveState_r(vp);
2013 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2015 /* if it's already attached, see if we can return it */
2016 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2017 VGetVolumeByVp_r(ec, vp);
2021 if (vp->specialStatus == VBUSY)
2023 VDetachVolume_r(ec, vp);
2025 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2031 /* pre-attach volume if it hasn't been done yet */
2033 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2034 (V_attachState(vp) == VOL_STATE_ERROR)) {
2035 nvp = VPreAttachVolumeById_r(ec, partp, vp, volumeId);
2041 VCreateReservation_r(nvp);
2047 VChangeState_r(vp, VOL_STATE_ATTACHING);
2049 /* restore monotonically increasing stats */
2050 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2055 /* compute path to disk header,
2057 * and verify magic and version stamps */
2058 strcpy(path, VPartitionPath(partp));
2064 if ((fd = afs_open(path, O_RDONLY)) == -1 || afs_fstat(fd, &status) == -1) {
2065 Log("VAttachVolume: Failed to open %s (errno %d)\n", path, errno);
2072 n = read(fd, &diskHeader, sizeof(diskHeader));
2074 if (n != sizeof(diskHeader)
2075 || diskHeader.stamp.magic != VOLUMEHEADERMAGIC) {
2076 Log("VAttachVolume: Error reading volume header %s\n", path);
2081 if (diskHeader.stamp.version != VOLUMEHEADERVERSION) {
2082 Log("VAttachVolume: Volume %s, version number is incorrect; volume needs salvaged\n", path);
2088 /* convert on-disk header format to in-memory header format */
2089 DiskToVolumeHeader(&iheader, &diskHeader);
2093 * NOTE: attach2 is entered without any locks, and returns
2094 * with vol_glock_mutex held */
2095 vp = attach2(ec, volumeId, path, &iheader, partp, vp, isbusy, mode);
2097 if (*ec || vp == NULL) {
2101 V_needsCallback(vp) = 0;
2102 VUpdateVolume_r(ec, vp, 0);
2104 Log("VAttachVolume: Error updating volume %u\n", vp->hashid);
2108 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2109 #ifndef AFS_DEMAND_ATTACH_FS
2110 /* This is a hack: by temporarily setting the incore
2111 * dontSalvage flag ON, the volume will be put back on the
2112 * Update list (with dontSalvage OFF again). It will then
2113 * come back in N minutes with DONT_SALVAGE eventually
2114 * set. This is the way that volumes that have never had
2115 * it set get it set; or that volumes that have been
2116 * offline without DONT SALVAGE having been set also
2117 * eventually get it set */
2118 V_dontSalvage(vp) = DONT_SALVAGE;
2119 #endif /* !AFS_DEMAND_ATTACH_FS */
2120 VAddToVolumeUpdateList_r(ec, vp);
2122 Log("VAttachVolume: Error adding volume %u to update list\n", vp->hashid);
2129 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2133 VCancelReservation_r(nvp);
2136 if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2137 if (vp && !IsErrorState(V_attachState(vp))) {
2138 VChangeState_r(vp, VOL_STATE_ERROR);
2145 #endif /* AFS_DEMAND_ATTACH_FS */
2148 * called without any locks held
2149 * returns with vol_glock_mutex held
2152 attach2(Error * ec, VolId volumeId, char *path, register struct VolumeHeader * header,
2153 struct DiskPartition * partp, register Volume * vp, int isbusy, int mode)
2155 vp->specialStatus = (byte) (isbusy ? VBUSY : 0);
2156 IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header->parent,
2157 header->largeVnodeIndex);
2158 IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header->parent,
2159 header->smallVnodeIndex);
2160 IH_INIT(vp->diskDataHandle, partp->device, header->parent,
2161 header->volumeInfo);
2162 IH_INIT(vp->linkHandle, partp->device, header->parent, header->linkTable);
2163 vp->shuttingDown = 0;
2164 vp->goingOffline = 0;
2166 #ifdef AFS_DEMAND_ATTACH_FS
2167 vp->stats.last_attach = FT_ApproxTime();
2168 vp->stats.attaches++;
2172 #ifdef AFS_DEMAND_ATTACH_FS
2173 IncUInt64(&VStats.attaches);
2175 vp->cacheCheck = ++VolumeCacheCheck;
2176 /* just in case this ever rolls over */
2177 if (!vp->cacheCheck)
2178 vp->cacheCheck = ++VolumeCacheCheck;
2179 GetVolumeHeader(vp);
2182 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2183 /* demand attach changes the V_PEEK mechanism
2185 * we can now suck the current disk data structure over
2186 * the fssync interface without going to disk
2188 * (technically, we don't need to restrict this feature
2189 * to demand attach fileservers. However, I'm trying
2190 * to limit the number of common code changes)
2192 if (programType != fileServer && mode == V_PEEK) {
2194 res.payload.len = sizeof(VolumeDiskData);
2195 res.payload.buf = &vp->header->diskstuff;
2197 if (FSYNC_VolOp(volumeId,
2198 VPartitionPath(partp),
2199 FSYNC_VOL_QUERY_HDR,
2202 goto disk_header_loaded;
2205 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2206 (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2207 sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2209 #ifdef AFS_DEMAND_ATTACH_FS
2212 IncUInt64(&VStats.hdr_loads);
2213 IncUInt64(&vp->stats.hdr_loads);
2215 #endif /* AFS_DEMAND_ATTACH_FS */
2218 Log("VAttachVolume: Error reading diskDataHandle vol header %s; error=%u\n", path, *ec);
2223 #ifdef AFS_DEMAND_ATTACH_FS
2226 /* check for pending volume operations */
2227 if (vp->pending_vol_op) {
2228 /* see if the pending volume op requires exclusive access */
2229 if (!VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
2230 /* mark the volume down */
2232 VChangeState_r(vp, VOL_STATE_UNATTACHED);
2233 if (V_offlineMessage(vp)[0] == '\0')
2234 strlcpy(V_offlineMessage(vp),
2235 "A volume utility is running.",
2236 sizeof(V_offlineMessage(vp)));
2237 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
2239 /* check to see if we should set the specialStatus flag */
2240 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
2241 vp->specialStatus = VBUSY;
2246 V_attachFlags(vp) |= VOL_HDR_LOADED;
2248 #endif /* AFS_DEMAND_ATTACH_FS */
2251 struct IndexFileHeader iHead;
2253 #if OPENAFS_VOL_STATS
2255 * We just read in the diskstuff part of the header. If the detailed
2256 * volume stats area has not yet been initialized, we should bzero the
2257 * area and mark it as initialized.
2259 if (!(V_stat_initialized(vp))) {
2260 memset((char *)(V_stat_area(vp)), 0, VOL_STATS_BYTES);
2261 V_stat_initialized(vp) = 1;
2263 #endif /* OPENAFS_VOL_STATS */
2265 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
2266 (char *)&iHead, sizeof(iHead),
2267 SMALLINDEXMAGIC, SMALLINDEXVERSION);
2270 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
2275 struct IndexFileHeader iHead;
2277 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
2278 (char *)&iHead, sizeof(iHead),
2279 LARGEINDEXMAGIC, LARGEINDEXVERSION);
2282 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
2286 #ifdef AFS_NAMEI_ENV
2288 struct versionStamp stamp;
2290 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
2291 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
2294 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
2297 #endif /* AFS_NAMEI_ENV */
2299 #if defined(AFS_DEMAND_ATTACH_FS)
2300 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
2302 if (programType == fileServer) {
2303 VRequestSalvage_r(vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2307 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
2313 /* volume operation in progress */
2317 #else /* AFS_DEMAND_ATTACH_FS */
2319 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
2324 #endif /* AFS_DEMAND_ATTACH_FS */
2326 if (V_needsSalvaged(vp)) {
2327 if (vp->specialStatus)
2328 vp->specialStatus = 0;
2330 #if defined(AFS_DEMAND_ATTACH_FS)
2331 if (programType == fileServer) {
2332 VRequestSalvage_r(vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
2336 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
2340 #else /* AFS_DEMAND_ATTACH_FS */
2343 #endif /* AFS_DEMAND_ATTACH_FS */
2348 if (programType == fileServer) {
2349 #ifndef FAST_RESTART
2350 if (V_inUse(vp) && VolumeWriteable(vp)) {
2351 if (!V_needsSalvaged(vp)) {
2352 V_needsSalvaged(vp) = 1;
2353 VUpdateVolume_r(ec, vp, 0);
2355 #if defined(AFS_DEMAND_ATTACH_FS)
2356 VRequestSalvage_r(vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
2359 #else /* AFS_DEMAND_ATTACH_FS */
2360 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
2363 #endif /* AFS_DEMAND_ATTACH_FS */
2366 #endif /* FAST_RESTART */
2368 if (V_destroyMe(vp) == DESTROY_ME) {
2369 #if defined(AFS_DEMAND_ATTACH_FS)
2370 /* schedule a salvage so the volume goes away on disk */
2371 VRequestSalvage_r(vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2372 VChangeState_r(vp, VOL_STATE_ERROR);
2374 #endif /* AFS_DEMAND_ATTACH_FS */
2376 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
2382 vp->nextVnodeUnique = V_uniquifier(vp);
2383 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
2384 #ifndef BITMAP_LATER
2385 if (programType == fileServer && VolumeWriteable(vp)) {
2387 for (i = 0; i < nVNODECLASSES; i++) {
2388 VGetBitmap_r(ec, vp, i);
2390 #ifdef AFS_DEMAND_ATTACH_FS
2391 VRequestSalvage_r(vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2394 #else /* AFS_DEMAND_ATTACH_FS */
2396 #endif /* AFS_DEMAND_ATTACH_FS */
2397 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
2403 #endif /* BITMAP_LATER */
2405 if (programType == fileServer) {
2406 if (vp->specialStatus)
2407 vp->specialStatus = 0;
2408 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
2410 V_offlineMessage(vp)[0] = '\0';
2414 AddVolumeToHashTable(vp, V_id(vp));
2415 #ifdef AFS_DEMAND_ATTACH_FS
2416 AddVolumeToVByPList_r(vp);
2418 VChangeState_r(vp, VOL_STATE_ATTACHED);
2423 /* Attach an existing volume.
2424 The volume also normally goes online at this time.
2425 An offline volume must be reattached to make it go online.
2429 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
2433 retVal = VAttachVolume_r(ec, volumeId, mode);
2439 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
2442 GetVolumePath(ec, volumeId, &part, &name);
2444 register Volume *vp;
2446 vp = VGetVolume_r(&error, volumeId);
2448 assert(V_inUse(vp) == 0);
2449 VDetachVolume_r(ec, vp);
2453 return VAttachVolumeByName_r(ec, part, name, mode);
2456 /* Increment a reference count to a volume, sans context swaps. Requires
2457 * possibly reading the volume header in from the disk, since there's
2458 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
2460 * N.B. This call can fail if we can't read in the header!! In this case
2461 * we still guarantee we won't context swap, but the ref count won't be
2462 * incremented (otherwise we'd violate the invariant).
2464 /* NOTE: with the demand attach fileserver extensions, the global lock
2465 * is dropped within VHold */
2466 #ifdef AFS_DEMAND_ATTACH_FS
2468 VHold_r(register Volume * vp)
2472 VCreateReservation_r(vp);
2473 VWaitExclusiveState_r(vp);
2475 LoadVolumeHeader(&error, vp);
2477 VCancelReservation_r(vp);
2481 VCancelReservation_r(vp);
2484 #else /* AFS_DEMAND_ATTACH_FS */
2486 VHold_r(register Volume * vp)
2490 LoadVolumeHeader(&error, vp);
2496 #endif /* AFS_DEMAND_ATTACH_FS */
2499 VHold(register Volume * vp)
2503 retVal = VHold_r(vp);
2509 /***************************************************/
2510 /* get and put volume routines */
2511 /***************************************************/
2514 VPutVolume_r(register Volume * vp)
2516 assert(--vp->nUsers >= 0);
2517 if (vp->nUsers == 0) {
2519 ReleaseVolumeHeader(vp->header);
2520 #ifdef AFS_DEMAND_ATTACH_FS
2521 if (!VCheckDetach(vp)) {
2525 #else /* AFS_DEMAND_ATTACH_FS */
2527 #endif /* AFS_DEMAND_ATTACH_FS */
2532 VPutVolume(register Volume * vp)
2540 /* Get a pointer to an attached volume. The pointer is returned regardless
2541 of whether or not the volume is in service or on/off line. An error
2542 code, however, is returned with an indication of the volume's status */
2544 VGetVolume(Error * ec, Error * client_ec, VolId volumeId)
2548 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
2554 VGetVolume_r(Error * ec, VolId volumeId)
2556 return GetVolume(ec, NULL, volumeId, NULL, 0);
2559 /* try to get a volume we've previously looked up */
2560 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
2562 VGetVolumeByVp_r(Error * ec, Volume * vp)
2564 return GetVolume(ec, NULL, vp->hashid, vp, 0);
2567 /* private interface for getting a volume handle
2568 * volumeId must be provided.
2569 * hint is an optional parameter to speed up hash lookups
2570 * flags is not used at this time
2572 /* for demand attach fs, caller MUST NOT hold a ref count on hint */
2574 GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint, int flags)
2577 /* pull this profiling/debugging code out of regular builds */
2579 #define VGET_CTR_INC(x) x++
2580 unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
2581 0, V7 = 0, V8 = 0, V9 = 0;
2582 unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
2584 #define VGET_CTR_INC(x)
2587 #ifdef AFS_DEMAND_ATTACH_FS
2588 Volume *avp, * rvp = hint;
2591 VCreateReservation_r(rvp);
2593 #endif /* AFS_DEMAND_ATTACH_FS */
2601 vp = VLookupVolume_r(ec, volumeId, vp);
2607 #ifdef AFS_DEMAND_ATTACH_FS
2608 if (rvp && (rvp != vp)) {
2609 /* break reservation on old vp */
2610 VCancelReservation_r(rvp);
2613 #endif /* AFS_DEMAND_ATTACH_FS */
2619 /* Until we have reached an initialization level of 2
2620 * we don't know whether this volume exists or not.
2621 * We can't sleep and retry later because before a volume
2622 * is attached, the caller tries to get it first. Just
2623 * return VOFFLINE and the caller can choose whether to
2624 * retry the command or not. */
2634 IncUInt64(&VStats.hdr_gets);
2636 #ifdef AFS_DEMAND_ATTACH_FS
2637 /* block if someone else is performing an exclusive op on this volume */
2640 VCreateReservation_r(rvp);
2642 VWaitExclusiveState_r(vp);
2644 /* short circuit with VNOVOL in the following circumstances:
2647 * VOL_STATE_SHUTTING_DOWN
2649 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
2650 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN)) {
2656 /* allowable states:
2664 if (vp->salvage.requested) {
2665 VUpdateSalvagePriority_r(vp);
2668 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
2669 avp = VAttachVolumeByVp_r(ec, vp, 0);
2672 /* VAttachVolumeByVp_r can return a pointer
2673 * != the vp passed to it under certain
2674 * conditions; make sure we don't leak
2675 * reservations if that happens */
2677 VCancelReservation_r(rvp);
2679 VCreateReservation_r(rvp);
2689 if (!vp->pending_vol_op) {
2704 if ((V_attachState(vp) == VOL_STATE_SALVAGING) ||
2705 (*ec == VSALVAGING)) {
2707 /* see CheckVnode() in afsfileprocs.c for an explanation
2708 * of this error code logic */
2709 afs_uint32 now = FT_ApproxTime();
2710 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
2713 *client_ec = VRESTARTING;
2721 if (vp->pending_vol_op && !VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
2723 /* see CheckVnode() in afsfileprocs.c for an explanation
2724 * of this error code logic */
2725 afs_uint32 now = FT_ApproxTime();
2726 if ((vp->stats.last_vol_op + (10 * 60)) >= now) {
2729 *client_ec = VRESTARTING;
2737 if (V_attachState(vp) == VOL_STATE_UNATTACHED) {
2742 #endif /* AFS_DEMAND_ATTACH_FS */
2744 LoadVolumeHeader(ec, vp);
2747 /* Only log the error if it was a totally unexpected error. Simply
2748 * a missing inode is likely to be caused by the volume being deleted */
2749 if (errno != ENXIO || LogLevel)
2750 Log("Volume %u: couldn't reread volume header\n",
2752 #ifdef AFS_DEMAND_ATTACH_FS
2753 if (programType == fileServer) {
2754 VRequestSalvage_r(vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2760 #else /* AFS_DEMAND_ATTACH_FS */
2763 #endif /* AFS_DEMAND_ATTACH_FS */
2768 if (vp->shuttingDown) {
2775 if (programType == fileServer) {
2777 if (vp->goingOffline) {
2779 #ifdef AFS_DEMAND_ATTACH_FS
2780 /* wait for the volume to go offline */
2781 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
2782 VWaitStateChange_r(vp);
2784 #elif defined(AFS_PTHREAD_ENV)
2785 assert(pthread_cond_wait(&vol_put_volume_cond, &vol_glock_mutex) == 0);
2786 #else /* AFS_PTHREAD_ENV */
2787 LWP_WaitProcess(VPutVolume);
2788 #endif /* AFS_PTHREAD_ENV */
2791 if (vp->specialStatus) {
2793 *ec = vp->specialStatus;
2794 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
2797 } else if (V_inUse(vp) == 0) {
2808 #ifdef AFS_DEMAND_ATTACH_FS
2809 /* if no error, bump nUsers */
2812 VLRU_UpdateAccess_r(vp);
2815 VCancelReservation_r(rvp);
2818 if (client_ec && !*client_ec) {
2821 #else /* AFS_DEMAND_ATTACH_FS */
2822 /* if no error, bump nUsers */
2829 #endif /* AFS_DEMAND_ATTACH_FS */
2836 /***************************************************/
2837 /* Volume offline/detach routines */
2838 /***************************************************/
2840 /* caller MUST hold a heavyweight ref on vp */
2841 #ifdef AFS_DEMAND_ATTACH_FS
2843 VTakeOffline_r(register Volume * vp)
2845 assert(vp->nUsers > 0);
2846 assert(programType == fileServer);
2848 VCreateReservation_r(vp);
2849 VWaitExclusiveState_r(vp);
2851 vp->goingOffline = 1;
2852 V_needsSalvaged(vp) = 1;
2854 VRequestSalvage_r(vp, SALVSYNC_ERROR, 0);
2855 VCancelReservation_r(vp);
2857 #else /* AFS_DEMAND_ATTACH_FS */
2859 VTakeOffline_r(register Volume * vp)
2861 assert(vp->nUsers > 0);
2862 assert(programType == fileServer);
2864 vp->goingOffline = 1;
2865 V_needsSalvaged(vp) = 1;
2867 #endif /* AFS_DEMAND_ATTACH_FS */
2870 VTakeOffline(register Volume * vp)
2877 /* Force the volume offline, set the salvage flag. No further references to
2878 * the volume through the volume package will be honored. */
2879 /* for demand attach, caller MUST hold ref count on vp */
2881 VForceOffline_r(Volume * vp, int flags)
2886 strcpy(V_offlineMessage(vp),
2887 "Forced offline due to internal error: volume needs to be salvaged");
2888 Log("Volume %u forced offline: it needs salvaging!\n", V_id(vp));
2890 vp->goingOffline = 0;
2891 V_needsSalvaged(vp) = 1;
2892 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
2893 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT | VOL_UPDATE_NOFORCEOFF);
2895 #ifdef AFS_DEMAND_ATTACH_FS
2896 #ifdef SALVSYNC_BUILD_CLIENT
2897 if (programType == fileServer) {
2898 VRequestSalvage_r(vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2901 VChangeState_r(vp, VOL_STATE_ERROR);
2902 #endif /* AFS_DEMAND_ATTACH_FS */
2903 #ifdef AFS_PTHREAD_ENV
2904 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
2905 #else /* AFS_PTHREAD_ENV */
2906 LWP_NoYieldSignal(VPutVolume);
2907 #endif /* AFS_PTHREAD_ENV */
2909 VReleaseVolumeHandles_r(vp);
2913 VForceOffline(Volume * vp)
2916 VForceOffline_r(vp, 0);
2920 /* The opposite of VAttachVolume. The volume header is written to disk, with
2921 the inUse bit turned off. A copy of the header is maintained in memory,
2922 however (which is why this is VOffline, not VDetach).
2925 VOffline_r(Volume * vp, char *message)
2928 VolumeId vid = V_id(vp);
2930 assert(programType != volumeUtility);
2935 if (V_offlineMessage(vp)[0] == '\0')
2936 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
2937 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
2939 vp->goingOffline = 1;
2940 #ifdef AFS_DEMAND_ATTACH_FS
2941 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
2942 VCreateReservation_r(vp);
2945 /* wait for the volume to go offline */
2946 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
2947 VWaitStateChange_r(vp);
2949 VCancelReservation_r(vp);
2950 #else /* AFS_DEMAND_ATTACH_FS */
2952 vp = VGetVolume_r(&error, vid); /* Wait for it to go offline */
2953 if (vp) /* In case it was reattached... */
2955 #endif /* AFS_DEMAND_ATTACH_FS */
2959 VOffline(Volume * vp, char *message)
2962 VOffline_r(vp, message);
2966 /* This gets used for the most part by utility routines that don't want
2967 * to keep all the volume headers around. Generally, the file server won't
2968 * call this routine, because then the offline message in the volume header
2969 * (or other information) won't be available to clients. For NAMEI, also
2970 * close the file handles. However, the fileserver does call this during
2971 * an attach following a volume operation.
2974 VDetachVolume_r(Error * ec, Volume * vp)
2977 struct DiskPartition *tpartp;
2978 int notifyServer, useDone;
2980 *ec = 0; /* always "succeeds" */
2981 if (programType == volumeUtility) {
2982 notifyServer = vp->needsPutBack;
2983 useDone = (V_destroyMe(vp) == DESTROY_ME);
2985 tpartp = vp->partition;
2987 DeleteVolumeFromHashTable(vp);
2988 vp->shuttingDown = 1;
2989 #ifdef AFS_DEMAND_ATTACH_FS
2990 DeleteVolumeFromVByPList_r(vp);
2992 VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
2993 #endif /* AFS_DEMAND_ATTACH_FS */
2995 /* Will be detached sometime in the future--this is OK since volume is offline */
2997 /* XXX the following code should really be moved to VCheckDetach() since the volume
2998 * is not technically detached until the refcounts reach zero
3000 #ifdef FSSYNC_BUILD_CLIENT
3001 if (programType == volumeUtility && notifyServer) {
3003 * Note: The server is not notified in the case of a bogus volume
3004 * explicitly to make it possible to create a volume, do a partial
3005 * restore, then abort the operation without ever putting the volume
3006 * online. This is essential in the case of a volume move operation
3007 * between two partitions on the same server. In that case, there
3008 * would be two instances of the same volume, one of them bogus,
3009 * which the file server would attempt to put on line
3012 /* don't put online */
3013 FSYNC_VolOp(volume, tpartp->name, FSYNC_VOL_DONE, 0, NULL);
3015 /* fs can use it again */
3016 FSYNC_VolOp(volume, tpartp->name, FSYNC_VOL_ON, 0, NULL);
3018 /* XXX this code path is only hit by volume utilities, thus
3019 * V_BreakVolumeCallbacks will always be NULL. if we really
3020 * want to break callbacks in this path we need to use FSYNC_VolOp() */
3022 /* Dettaching it so break all callbacks on it */
3023 if (V_BreakVolumeCallbacks) {
3024 Log("volume %u detached; breaking all call backs\n", volume);
3025 (*V_BreakVolumeCallbacks) (volume);
3030 #endif /* FSSYNC_BUILD_CLIENT */
3034 VDetachVolume(Error * ec, Volume * vp)
3037 VDetachVolume_r(ec, vp);
3042 /***************************************************/
3043 /* Volume fd/inode handle closing routines */
3044 /***************************************************/
3046 /* For VDetachVolume, we close all cached file descriptors, but keep
3047 * the Inode handles in case we need to read from a busy volume.
3049 /* for demand attach, caller MUST hold ref count on vp */
3051 VCloseVolumeHandles_r(Volume * vp)
3053 #ifdef AFS_DEMAND_ATTACH_FS
3054 VolState state_save;
3056 state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
3061 * XXX need to investigate whether we can perform
3062 * DFlushVolume outside of vol_glock_mutex...
3064 * VCloseVnodeFiles_r drops the glock internally */
3065 DFlushVolume(V_id(vp));
3066 VCloseVnodeFiles_r(vp);
3068 #ifdef AFS_DEMAND_ATTACH_FS
3072 /* Too time consuming and unnecessary for the volserver */
3073 if (programType != volumeUtility) {
3074 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
3075 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
3076 IH_CONDSYNC(vp->diskDataHandle);
3078 IH_CONDSYNC(vp->linkHandle);
3079 #endif /* AFS_NT40_ENV */
3082 IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
3083 IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
3084 IH_REALLYCLOSE(vp->diskDataHandle);
3085 IH_REALLYCLOSE(vp->linkHandle);
3087 #ifdef AFS_DEMAND_ATTACH_FS
3089 VChangeState_r(vp, state_save);
3093 /* For both VForceOffline and VOffline, we close all relevant handles.
3094 * For VOffline, if we re-attach the volume, the files may possible be
3095 * different than before.
3097 /* for demand attach, caller MUST hold a ref count on vp */
3099 VReleaseVolumeHandles_r(Volume * vp)
3101 #ifdef AFS_DEMAND_ATTACH_FS
3102 VolState state_save;
3104 state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
3107 /* XXX need to investigate whether we can perform
3108 * DFlushVolume outside of vol_glock_mutex... */
3109 DFlushVolume(V_id(vp));
3111 VReleaseVnodeFiles_r(vp); /* releases the glock internally */
3113 #ifdef AFS_DEMAND_ATTACH_FS
3117 /* Too time consuming and unnecessary for the volserver */
3118 if (programType != volumeUtility) {
3119 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
3120 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
3121 IH_CONDSYNC(vp->diskDataHandle);
3123 IH_CONDSYNC(vp->linkHandle);
3124 #endif /* AFS_NT40_ENV */
3127 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
3128 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
3129 IH_RELEASE(vp->diskDataHandle);
3130 IH_RELEASE(vp->linkHandle);
3132 #ifdef AFS_DEMAND_ATTACH_FS
3134 VChangeState_r(vp, state_save);
3139 /***************************************************/
3140 /* Volume write and fsync routines */
3141 /***************************************************/
3144 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
3146 #ifdef AFS_DEMAND_ATTACH_FS
3147 VolState state_save;
3149 if (flags & VOL_UPDATE_WAIT) {
3150 VCreateReservation_r(vp);
3151 VWaitExclusiveState_r(vp);
3156 if (programType == fileServer)
3158 (V_inUse(vp) ? V_nextVnodeUnique(vp) +
3159 200 : V_nextVnodeUnique(vp));
3161 #ifdef AFS_DEMAND_ATTACH_FS
3162 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
3166 WriteVolumeHeader_r(ec, vp);
3168 #ifdef AFS_DEMAND_ATTACH_FS
3170 VChangeState_r(vp, state_save);
3171 if (flags & VOL_UPDATE_WAIT) {
3172 VCancelReservation_r(vp);
3177 Log("VUpdateVolume: error updating volume header, volume %u (%s)\n",
3178 V_id(vp), V_name(vp));
3179 /* try to update on-disk header,
3180 * while preventing infinite recursion */
3181 if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
3182 VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
3188 VUpdateVolume(Error * ec, Volume * vp)
3191 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
3196 VSyncVolume_r(Error * ec, Volume * vp, int flags)
3200 #ifdef AFS_DEMAND_ATTACH_FS
3201 VolState state_save;
3204 if (flags & VOL_SYNC_WAIT) {
3205 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
3207 VUpdateVolume_r(ec, vp, 0);
3210 #ifdef AFS_DEMAND_ATTACH_FS
3211 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
3214 fdP = IH_OPEN(V_diskDataHandle(vp));
3215 assert(fdP != NULL);
3216 code = FDH_SYNC(fdP);
3219 #ifdef AFS_DEMAND_ATTACH_FS
3221 VChangeState_r(vp, state_save);
3227 VSyncVolume(Error * ec, Volume * vp)
3230 VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
3235 /***************************************************/
3236 /* Volume dealloaction routines */
3237 /***************************************************/
3239 #ifdef AFS_DEMAND_ATTACH_FS
3241 FreeVolume(Volume * vp)
3243 /* free the heap space, iff it's safe.
3244 * otherwise, pull it out of the hash table, so it
3245 * will get deallocated when all refs to it go away */
3246 if (!VCheckFree(vp)) {
3247 DeleteVolumeFromHashTable(vp);
3248 DeleteVolumeFromVByPList_r(vp);
3250 /* make sure we invalidate the header cache entry */
3251 FreeVolumeHeader(vp);
3254 #endif /* AFS_DEMAND_ATTACH_FS */
3257 ReallyFreeVolume(Volume * vp)
3262 #ifdef AFS_DEMAND_ATTACH_FS
3264 VChangeState_r(vp, VOL_STATE_FREED);
3265 if (vp->pending_vol_op)
3266 free(vp->pending_vol_op);
3267 #endif /* AFS_DEMAND_ATTACH_FS */
3268 for (i = 0; i < nVNODECLASSES; i++)
3269 if (vp->vnodeIndex[i].bitmap)
3270 free(vp->vnodeIndex[i].bitmap);
3271 FreeVolumeHeader(vp);
3272 #ifndef AFS_DEMAND_ATTACH_FS
3273 DeleteVolumeFromHashTable(vp);
3274 #endif /* AFS_DEMAND_ATTACH_FS */
3278 /* check to see if we should shutdown this volume
3279 * returns 1 if volume was freed, 0 otherwise */
3280 #ifdef AFS_DEMAND_ATTACH_FS
3282 VCheckDetach(register Volume * vp)
3286 if (vp->nUsers || vp->nWaiters)
3289 if (vp->shuttingDown) {
3291 VReleaseVolumeHandles_r(vp);
3293 ReallyFreeVolume(vp);
3294 if (programType == fileServer) {
3295 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3300 #else /* AFS_DEMAND_ATTACH_FS */
3302 VCheckDetach(register Volume * vp)
3309 if (vp->shuttingDown) {
3311 VReleaseVolumeHandles_r(vp);
3312 ReallyFreeVolume(vp);
3313 if (programType == fileServer) {
3314 #if defined(AFS_PTHREAD_ENV)
3315 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3316 #else /* AFS_PTHREAD_ENV */
3317 LWP_NoYieldSignal(VPutVolume);
3318 #endif /* AFS_PTHREAD_ENV */
3323 #endif /* AFS_DEMAND_ATTACH_FS */
3325 /* check to see if we should offline this volume
3326 * return 1 if volume went offline, 0 otherwise */
3327 #ifdef AFS_DEMAND_ATTACH_FS
3329 VCheckOffline(register Volume * vp)
3331 Volume * rvp = NULL;
3334 if (vp->goingOffline && !vp->nUsers) {
3336 assert(programType == fileServer);
3337 assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
3338 (V_attachState(vp) != VOL_STATE_FREED) &&
3339 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
3340 (V_attachState(vp) != VOL_STATE_UNATTACHED));
3344 * VOL_STATE_GOING_OFFLINE
3345 * VOL_STATE_SHUTTING_DOWN
3346 * IsErrorState(V_attachState(vp))
3347 * IsExclusiveState(V_attachState(vp))
3350 VCreateReservation_r(vp);
3351 VChangeState_r(vp, VOL_STATE_OFFLINING);
3354 /* must clear the goingOffline flag before we drop the glock */
3355 vp->goingOffline = 0;
3360 /* perform async operations */
3361 VUpdateVolume_r(&error, vp, 0);
3362 VCloseVolumeHandles_r(vp);
3365 Log("VOffline: Volume %u (%s) is now offline", V_id(vp),
3367 if (V_offlineMessage(vp)[0])
3368 Log(" (%s)", V_offlineMessage(vp));
3372 /* invalidate the volume header cache entry */
3373 FreeVolumeHeader(vp);
3375 /* if nothing changed state to error or salvaging,
3376 * drop state to unattached */
3377 if (!IsErrorState(V_attachState(vp))) {
3378 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3380 VCancelReservation_r(vp);
3381 /* no usage of vp is safe beyond this point */
3385 #else /* AFS_DEMAND_ATTACH_FS */
3387 VCheckOffline(register Volume * vp)
3389 Volume * rvp = NULL;
3392 if (vp->goingOffline && !vp->nUsers) {
3394 assert(programType == fileServer);
3397 vp->goingOffline = 0;
3399 VUpdateVolume_r(&error, vp, 0);
3400 VCloseVolumeHandles_r(vp);
3402 Log("VOffline: Volume %u (%s) is now offline", V_id(vp),
3404 if (V_offlineMessage(vp)[0])
3405 Log(" (%s)", V_offlineMessage(vp));
3408 FreeVolumeHeader(vp);
3409 #ifdef AFS_PTHREAD_ENV
3410 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3411 #else /* AFS_PTHREAD_ENV */
3412 LWP_NoYieldSignal(VPutVolume);
3413 #endif /* AFS_PTHREAD_ENV */
3417 #endif /* AFS_DEMAND_ATTACH_FS */
3419 /***************************************************/
3420 /* demand attach fs ref counting routines */
3421 /***************************************************/
3423 #ifdef AFS_DEMAND_ATTACH_FS
3424 /* the following two functions handle reference counting for
3425 * asynchronous operations on volume structs.
3427 * their purpose is to prevent a VDetachVolume or VShutdown
3428 * from free()ing the Volume struct during an async i/o op */
3430 /* register with the async volume op ref counter */
3432 VCreateReservation_r(Volume * vp)
3437 /* unregister with the async volume op ref counter */
3439 VCancelReservation_r(Volume * vp)
3441 assert(--vp->nWaiters >= 0);
3442 if (vp->nWaiters == 0) {
3444 if (!VCheckDetach(vp)) {
3451 /* check to see if we should free this volume now
3452 * return 1 if volume was freed, 0 otherwise */
3454 VCheckFree(Volume * vp)
3457 if ((vp->nUsers == 0) &&
3458 (vp->nWaiters == 0) &&
3459 !(V_attachFlags(vp) & (VOL_IN_HASH |
3463 ReallyFreeVolume(vp);
3468 #endif /* AFS_DEMAND_ATTACH_FS */
3471 /***************************************************/
3472 /* online volume operations routines */
3473 /***************************************************/
3475 #ifdef AFS_DEMAND_ATTACH_FS
3477 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3479 FSSYNC_VolOp_info * info;
3481 /* attach a vol op info node to the volume struct */
3482 info = (FSSYNC_VolOp_info *) malloc(sizeof(FSSYNC_VolOp_info));
3483 assert(info != NULL);
3484 memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
3485 vp->pending_vol_op = info;
3488 vp->stats.last_vol_op = FT_ApproxTime();
3489 vp->stats.vol_ops++;
3490 IncUInt64(&VStats.vol_ops);
3496 VDeregisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3498 if (vp->pending_vol_op) {
3499 free(vp->pending_vol_op);
3500 vp->pending_vol_op = NULL;
3504 #endif /* AFS_DEMAND_ATTACH_FS */
3507 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3509 return (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
3510 (vopinfo->com.reason == V_READONLY ||
3511 (!VolumeWriteable(vp) &&
3512 (vopinfo->com.reason == V_CLONE ||
3513 vopinfo->com.reason == V_DUMP))));
3517 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3519 return (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
3520 (vopinfo->com.reason == V_CLONE ||
3521 vopinfo->com.reason == V_DUMP));
3525 /***************************************************/
3526 /* online salvager routines */
3527 /***************************************************/
3528 #if defined(AFS_DEMAND_ATTACH_FS)
3529 #define SALVAGE_PRIO_UPDATE_INTERVAL 3 /* number of seconds between prio updates */
3530 #define SALVAGE_COUNT_MAX 16 /* number of online salvages we
3531 * allow before moving the volume
3532 * into a permanent error state
3534 * once this threshold is reached,
3535 * the operator will have to manually
3536 * issue a 'bos salvage' to bring
3537 * the volume back online
3540 /* check to see if we should salvage this volume
3541 * returns 1 if salvage scheduled, 0 otherwise */
3543 VCheckSalvage(register Volume * vp)
3546 #ifdef SALVSYNC_BUILD_CLIENT
3547 if (vp->nUsers || vp->nWaiters)
3549 if (vp->salvage.requested) {
3550 VScheduleSalvage_r(vp);
3553 #endif /* SALVSYNC_BUILD_CLIENT */
3558 * request that a salvage be performed once
3559 * ref counts reach zero
3562 VRequestSalvage_r(Volume * vp, int reason, int flags)
3564 #ifdef SALVSYNC_BUILD_CLIENT
3565 if (programType != fileServer)
3568 if (!vp->salvage.requested) {
3569 vp->salvage.requested = 1;
3570 vp->salvage.reason = reason;
3571 vp->stats.last_salvage = FT_ApproxTime();
3572 if (flags & VOL_SALVAGE_INVALIDATE_HEADER) {
3573 ReleaseVolumeHeader(vp->header);
3575 if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
3576 VChangeState_r(vp, VOL_STATE_SALVAGING);
3578 Log("VRequestSalvage: volume %u online salvaged too many times; forced offline.\n", vp->hashid);
3579 VChangeState_r(vp, VOL_STATE_ERROR);
3582 #endif /* SALVSYNC_BUILD_CLIENT */
3587 * update salvage priority
3590 VUpdateSalvagePriority_r(Volume * vp)
3595 #ifdef SALVSYNC_BUILD_CLIENT
3597 now = FT_ApproxTime();
3599 /* update the salvageserver priority queue occasionally so that
3600 * frequently requested volumes get moved to the head of the queue
3602 if ((vp->salvage.scheduled) &&
3603 (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
3604 code = SALVSYNC_SalvageVolume(vp->hashid,
3605 VPartitionPath(vp->partition),
3610 vp->stats.last_salvage_req = now;
3611 if (code != SYNC_OK) {
3615 #endif /* SALVSYNC_BUILD_CLIENT */
3621 * schedule a salvage with the salvage server
3624 VScheduleSalvage_r(Volume * vp)
3627 #ifdef SALVSYNC_BUILD_CLIENT
3628 VolState state_save;
3631 if (vp->nWaiters || vp->nUsers) {
3635 /* prevent endless salvage,attach,salvage,attach,... loops */
3636 if (vp->stats.salvages >= SALVAGE_COUNT_MAX)
3639 if (!vp->salvage.scheduled) {
3640 /* if we haven't previously scheduled a salvage, do so now
3642 * set the volume to an exclusive state and drop the lock
3643 * around the SALVSYNC call
3645 strlcpy(partName, VPartitionPath(vp->partition), sizeof(partName));
3646 state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
3647 V_attachFlags(vp) |= VOL_IS_BUSY;
3650 /* can't use V_id() since there's no guarantee
3651 * we have the disk data header at this point */
3652 code = SALVSYNC_SalvageVolume(vp->hashid,
3659 VChangeState_r(vp, state_save);
3660 V_attachFlags(vp) &= ~(VOL_IS_BUSY);
3662 if (code == SYNC_OK) {
3663 vp->salvage.scheduled = 1;
3664 vp->stats.salvages++;
3665 vp->stats.last_salvage_req = FT_ApproxTime();
3666 IncUInt64(&VStats.salvages);
3670 case SYNC_BAD_COMMAND:
3671 case SYNC_COM_ERROR:
3674 Log("VScheduleSalvage_r: SALVSYNC request denied\n");
3677 Log("VScheduleSalvage_r: SALVSYNC unknown protocol error\n");
3682 #endif /* SALVSYNC_BUILD_CLIENT */
3687 * cancel a scheduled salvage operation
3690 VCancelSalvage_r(Volume * vp, int reason)
3694 #ifdef SALVSYNC_BUILD_CLIENT
3695 if (vp->salvage.scheduled) {
3696 code = SALVSYNC_SalvageVolume(vp->hashid,
3697 VPartitionPath(vp->partition),
3702 if (code == SYNC_OK) {
3703 vp->salvage.scheduled = 0;
3708 #endif /* SALVSYNC_BUILD_CLIENT */
3712 /* This must be called by any volume utility which needs to run while the
3713 file server is also running. This is separated from VInitVolumePackage so
3714 that a utility can fork--and each of the children can independently
3715 initialize communication with the file server */
3716 #ifdef SALVSYNC_BUILD_CLIENT
3722 retVal = VConnectSALV_r();
3728 VConnectSALV_r(void)
3730 assert((programType != salvageServer) &&
3731 (programType != volumeUtility));
3732 return SALVSYNC_clientInit();
3736 VDisconnectSALV(void)
3740 VDisconnectSALV_r();
3746 VDisconnectSALV_r(void)
3748 assert((programType != salvageServer) &&
3749 (programType != volumeUtility));
3750 return SALVSYNC_clientFinis();
3754 VReconnectSALV(void)
3758 retVal = VReconnectSALV_r();
3764 VReconnectSALV_r(void)
3766 assert((programType != salvageServer) &&
3767 (programType != volumeUtility));
3768 return SALVSYNC_clientReconnect();
3770 #endif /* SALVSYNC_BUILD_CLIENT */
3771 #endif /* AFS_DEMAND_ATTACH_FS */
3774 /***************************************************/
3775 /* FSSYNC routines */
3776 /***************************************************/
3778 /* This must be called by any volume utility which needs to run while the
3779 file server is also running. This is separated from VInitVolumePackage so
3780 that a utility can fork--and each of the children can independently
3781 initialize communication with the file server */
3782 #ifdef FSSYNC_BUILD_CLIENT
3788 retVal = VConnectFS_r();
3797 assert((VInit == 2) &&
3798 (programType != fileServer) &&
3799 (programType != salvager));
3800 rc = FSYNC_clientInit();
3807 VDisconnectFS_r(void)
3809 assert((programType != fileServer) &&
3810 (programType != salvager));
3811 FSYNC_clientFinis();
3824 VChildProcReconnectFS_r(void)
3826 return FSYNC_clientChildProcReconnect();
3830 VChildProcReconnectFS(void)
3834 ret = VChildProcReconnectFS_r();
3838 #endif /* FSSYNC_BUILD_CLIENT */
3841 /***************************************************/
3842 /* volume bitmap routines */
3843 /***************************************************/
3846 * For demand attach fs, flags parameter controls
3847 * locking behavior. If (flags & VOL_ALLOC_BITMAP_WAIT)
3848 * is set, then this function will create a reservation
3849 * and block on any other exclusive operations. Otherwise,
3850 * this function assumes the caller already has exclusive
3851 * access to vp, and we just change the volume state.
3854 VAllocBitmapEntry_r(Error * ec, Volume * vp,
3855 struct vnodeIndex *index, int flags)
3858 register byte *bp, *ep;
3859 #ifdef AFS_DEMAND_ATTACH_FS
3860 VolState state_save;
3861 #endif /* AFS_DEMAND_ATTACH_FS */
3865 /* This test is probably redundant */
3866 if (!VolumeWriteable(vp)) {
3867 *ec = (bit32) VREADONLY;
3871 #ifdef AFS_DEMAND_ATTACH_FS
3872 if (flags & VOL_ALLOC_BITMAP_WAIT) {
3873 VCreateReservation_r(vp);
3874 VWaitExclusiveState_r(vp);
3876 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
3877 #endif /* AFS_DEMAND_ATTACH_FS */
3880 if ((programType == fileServer) && !index->bitmap) {
3882 #ifndef AFS_DEMAND_ATTACH_FS
3883 /* demand attach fs uses the volume state to avoid races.
3884 * specialStatus field is not used at all */
3886 if (vp->specialStatus == VBUSY) {
3887 if (vp->goingOffline) { /* vos dump waiting for the volume to
3888 * go offline. We probably come here
3889 * from AddNewReadableResidency */
3892 while (vp->specialStatus == VBUSY) {
3893 #ifdef AFS_PTHREAD_ENV
3897 #else /* AFS_PTHREAD_ENV */
3899 #endif /* AFS_DEMAND_ATTACH_FS */
3903 #endif /* !AFS_DEMAND_ATTACH_FS */
3905 if (!index->bitmap) {
3906 #ifndef AFS_DEMAND_ATTACH_FS
3907 vp->specialStatus = VBUSY; /* Stop anyone else from using it. */
3908 #endif /* AFS_DEMAND_ATTACH_FS */
3909 for (i = 0; i < nVNODECLASSES; i++) {
3910 VGetBitmap_r(ec, vp, i);
3912 #ifdef AFS_DEMAND_ATTACH_FS
3913 VRequestSalvage_r(vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3915 #else /* AFS_DEMAND_ATTACH_FS */
3916 DeleteVolumeFromHashTable(vp);
3917 vp->shuttingDown = 1; /* Let who has it free it. */
3918 vp->specialStatus = 0;
3919 #endif /* AFS_DEMAND_ATTACH_FS */
3924 #ifndef AFS_DEMAND_ATTACH_FS
3926 vp->specialStatus = 0; /* Allow others to have access. */
3927 #endif /* AFS_DEMAND_ATTACH_FS */
3930 #endif /* BITMAP_LATER */
3932 #ifdef AFS_DEMAND_ATTACH_FS
3934 #endif /* AFS_DEMAND_ATTACH_FS */
3935 bp = index->bitmap + index->bitmapOffset;
3936 ep = index->bitmap + index->bitmapSize;
3938 if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
3940 index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
3943 o = ffs(~*bp) - 1; /* ffs is documented in BSTRING(3) */
3945 ret = (VnodeId) ((bp - index->bitmap) * 8 + o);
3946 #ifdef AFS_DEMAND_ATTACH_FS
3948 #endif /* AFS_DEMAND_ATTACH_FS */
3951 bp += sizeof(bit32) /* i.e. 4 */ ;
3953 /* No bit map entry--must grow bitmap */
3955 realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
3958 bp += index->bitmapSize;
3959 memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
3960 index->bitmapOffset = index->bitmapSize;
3961 index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
3963 ret = index->bitmapOffset * 8;
3964 #ifdef AFS_DEMAND_ATTACH_FS
3966 #endif /* AFS_DEMAND_ATTACH_FS */
3969 #ifdef AFS_DEMAND_ATTACH_FS
3970 VChangeState_r(vp, state_save);
3971 if (flags & VOL_ALLOC_BITMAP_WAIT) {
3972 VCancelReservation_r(vp);
3974 #endif /* AFS_DEMAND_ATTACH_FS */
3979 VAllocBitmapEntry(Error * ec, Volume * vp, register struct vnodeIndex * index)
3983 retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
3989 VFreeBitMapEntry_r(Error * ec, register struct vnodeIndex *index,
3992 unsigned int offset;
3998 #endif /* BITMAP_LATER */
3999 offset = bitNumber >> 3;
4000 if (offset >= index->bitmapSize) {
4004 if (offset < index->bitmapOffset)
4005 index->bitmapOffset = offset & ~3; /* Truncate to nearest bit32 */
4006 *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
4010 VFreeBitMapEntry(Error * ec, register struct vnodeIndex *index,
4014 VFreeBitMapEntry_r(ec, index, bitNumber);
4018 /* this function will drop the glock internally.
4019 * for old pthread fileservers, this is safe thanks to vbusy.
4021 * for demand attach fs, caller must have already called
4022 * VCreateReservation_r and VWaitExclusiveState_r */
4024 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
4026 StreamHandle_t *file;
4029 struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
4030 struct vnodeIndex *vip = &vp->vnodeIndex[class];
4031 struct VnodeDiskObject *vnode;
4032 unsigned int unique = 0;
4036 #endif /* BITMAP_LATER */
4037 #ifdef AFS_DEMAND_ATTACH_FS
4038 VolState state_save;
4039 #endif /* AFS_DEMAND_ATTACH_FS */
4043 #ifdef AFS_DEMAND_ATTACH_FS
4044 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
4045 #endif /* AFS_DEMAND_ATTACH_FS */
4048 fdP = IH_OPEN(vip->handle);
4049 assert(fdP != NULL);
4050 file = FDH_FDOPEN(fdP, "r");
4051 assert(file != NULL);
4052 vnode = (VnodeDiskObject *) malloc(vcp->diskSize);
4053 assert(vnode != NULL);
4054 size = OS_SIZE(fdP->fd_fd);
4056 nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
4058 vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4; /* The 10 is a little extra so
4059 * a few files can be created in this volume,
4060 * the whole thing is rounded up to nearest 4
4061 * bytes, because the bit map allocator likes
4064 BitMap = (byte *) calloc(1, vip->bitmapSize);
4065 assert(BitMap != NULL);
4066 #else /* BITMAP_LATER */
4067 vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
4068 assert(vip->bitmap != NULL);
4069 vip->bitmapOffset = 0;
4070 #endif /* BITMAP_LATER */
4071 if (STREAM_SEEK(file, vcp->diskSize, 0) != -1) {
4073 for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
4074 if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
4076 if (vnode->type != vNull) {
4077 if (vnode->vnodeMagic != vcp->magic) {
4078 Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
4083 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
4084 #else /* BITMAP_LATER */
4085 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
4086 #endif /* BITMAP_LATER */
4087 if (unique <= vnode->uniquifier)
4088 unique = vnode->uniquifier + 1;
4090 #ifndef AFS_PTHREAD_ENV
4091 if ((bitNumber & 0x00ff) == 0x0ff) { /* every 256 iterations */
4094 #endif /* !AFS_PTHREAD_ENV */
4097 if (vp->nextVnodeUnique < unique) {
4098 Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
4101 /* Paranoia, partly justified--I think fclose after fdopen
4102 * doesn't seem to close fd. In any event, the documentation
4103 * doesn't specify, so it's safer to close it twice.
4111 /* There may have been a racing condition with some other thread, both
4112 * creating the bitmaps for this volume. If the other thread was faster
4113 * the pointer to bitmap should already be filled and we can free ours.
4115 if (vip->bitmap == NULL) {
4116 vip->bitmap = BitMap;
4117 vip->bitmapOffset = 0;
4119 free((byte *) BitMap);
4120 #endif /* BITMAP_LATER */
4121 #ifdef AFS_DEMAND_ATTACH_FS
4122 VChangeState_r(vp, state_save);
4123 #endif /* AFS_DEMAND_ATTACH_FS */
4127 /***************************************************/
4128 /* demand attach fs state machine routines */
4129 /***************************************************/
4131 #ifdef AFS_DEMAND_ATTACH_FS
4132 /* wait for the volume to change states */
4134 VWaitStateChange_r(Volume * vp)
4136 VolState state_save = V_attachState(vp);
4138 assert(vp->nWaiters || vp->nUsers);
4140 assert(pthread_cond_wait(&V_attachCV(vp), &vol_glock_mutex) == 0);
4141 } while (V_attachState(vp) == state_save);
4142 assert(V_attachState(vp) != VOL_STATE_FREED);
4145 /* wait for blocking ops to end */
4147 VWaitExclusiveState_r(Volume * vp)
4149 assert(vp->nWaiters || vp->nUsers);
4150 while (IsExclusiveState(V_attachState(vp))) {
4151 assert(pthread_cond_wait(&V_attachCV(vp), &vol_glock_mutex) == 0);
4153 assert(V_attachState(vp) != VOL_STATE_FREED);
4156 /* change state, and notify other threads,
4157 * return previous state to caller */
4159 VChangeState_r(Volume * vp, VolState new_state)
4161 VolState old_state = V_attachState(vp);
4163 /* XXX profiling need to make sure these counters
4164 * don't kill performance... */
4165 VStats.state_levels[old_state]--;
4166 VStats.state_levels[new_state]++;
4168 V_attachState(vp) = new_state;
4169 assert(pthread_cond_broadcast(&V_attachCV(vp)) == 0);
4173 /* tells caller whether or not the current state requires
4174 * exclusive access without holding glock */
4176 IsExclusiveState(VolState state)
4179 case VOL_STATE_UPDATING:
4180 case VOL_STATE_ATTACHING:
4181 case VOL_STATE_GET_BITMAP:
4182 case VOL_STATE_HDR_LOADING:
4183 case VOL_STATE_HDR_ATTACHING:
4184 case VOL_STATE_OFFLINING:
4185 case VOL_STATE_DETACHING:
4191 /* tell caller whether V_attachState is an error condition */
4193 IsErrorState(VolState state)
4196 case VOL_STATE_ERROR:
4197 case VOL_STATE_SALVAGING:
4203 /* tell caller whether V_attachState is valid */
4205 IsValidState(VolState state)
4208 (state < VOL_STATE_COUNT) &&
4209 (state != VOL_STATE_FREED)) {
4214 #endif /* AFS_DEMAND_ATTACH_FS */
4217 /***************************************************/
4218 /* Volume Path and Volume Number utility routines */
4219 /***************************************************/
4222 GetVolumePath(Error * ec, VolId volumeId, char **partitionp, char **namep)
4224 static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
4225 char path[VMAXPATHLEN];
4227 struct DiskPartition *dp;
4231 (void)afs_snprintf(&name[1], (sizeof name) - 1, VFORMAT, volumeId);
4232 for (dp = DiskPartitionList; dp; dp = dp->next) {
4233 struct afs_stat status;
4234 strcpy(path, VPartitionPath(dp));
4236 if (afs_stat(path, &status) == 0) {
4237 strcpy(partition, dp->name);
4244 *partitionp = *namep = NULL;
4246 *partitionp = partition;
4252 VolumeNumber(char *name)
4256 return atoi(name + 1);
4260 VolumeExternalName(VolumeId volumeId)
4262 static char name[VMAXPATHLEN];
4263 (void)afs_snprintf(name, sizeof name, VFORMAT, volumeId);
4268 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
4270 return afs_snprintf(name, len, VFORMAT, volumeId);
4274 /***************************************************/
4275 /* Volume Usage Statistics routines */
4276 /***************************************************/
4278 #if OPENAFS_VOL_STATS
4279 #define OneDay (86400) /* 24 hours' worth of seconds */
4281 #define OneDay (24*60*60) /* 24 hours */
4282 #endif /* OPENAFS_VOL_STATS */
4284 #define Midnight(date) ((date-TimeZoneCorrection)/OneDay*OneDay+TimeZoneCorrection)
4286 /*------------------------------------------------------------------------
4287 * [export] VAdjustVolumeStatistics
4290 * If we've passed midnight, we need to update all the day use
4291 * statistics as well as zeroing the detailed volume statistics
4292 * (if we are implementing them).
4295 * vp : Pointer to the volume structure describing the lucky
4296 * volume being considered for update.
4302 * Nothing interesting.
4306 *------------------------------------------------------------------------*/
4309 VAdjustVolumeStatistics_r(register Volume * vp)
4311 unsigned int now = FT_ApproxTime();
4313 if (now - V_dayUseDate(vp) > OneDay) {
4314 register int ndays, i;
4316 ndays = (now - V_dayUseDate(vp)) / OneDay;
4317 for (i = 6; i > ndays - 1; i--)
4318 V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
4319 for (i = 0; i < ndays - 1 && i < 7; i++)
4320 V_weekUse(vp)[i] = 0;
4322 V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
4324 V_dayUseDate(vp) = Midnight(now);
4326 #if OPENAFS_VOL_STATS
4328 * All we need to do is bzero the entire VOL_STATS_BYTES of
4329 * the detailed volume statistics area.
4331 memset((char *)(V_stat_area(vp)), 0, VOL_STATS_BYTES);
4332 #endif /* OPENAFS_VOL_STATS */
4335 /*It's been more than a day of collection */
4337 * Always return happily.
4340 } /*VAdjustVolumeStatistics */
4343 VAdjustVolumeStatistics(register Volume * vp)
4347 retVal = VAdjustVolumeStatistics_r(vp);
4353 VBumpVolumeUsage_r(register Volume * vp)
4355 unsigned int now = FT_ApproxTime();
4356 if (now - V_dayUseDate(vp) > OneDay)
4357 VAdjustVolumeStatistics_r(vp);
4359 * Save the volume header image to disk after every 128 bumps to dayUse.
4361 if ((V_dayUse(vp)++ & 127) == 0) {
4363 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
4368 VBumpVolumeUsage(register Volume * vp)
4371 VBumpVolumeUsage_r(vp);
4376 VSetDiskUsage_r(void)
4378 #ifndef AFS_DEMAND_ATTACH_FS
4379 static int FifteenMinuteCounter = 0;
4383 /* NOTE: Don't attempt to access the partitions list until the
4384 * initialization level indicates that all volumes are attached,
4385 * which implies that all partitions are initialized. */
4386 #ifdef AFS_PTHREAD_ENV
4388 #else /* AFS_PTHREAD_ENV */
4390 #endif /* AFS_PTHREAD_ENV */
4393 VResetDiskUsage_r();
4395 #ifndef AFS_DEMAND_ATTACH_FS
4396 if (++FifteenMinuteCounter == 3) {
4397 FifteenMinuteCounter = 0;
4400 #endif /* !AFS_DEMAND_ATTACH_FS */
4412 /***************************************************/
4413 /* Volume Update List routines */
4414 /***************************************************/
4416 /* The number of minutes that a volume hasn't been updated before the
4417 * "Dont salvage" flag in the volume header will be turned on */
4418 #define SALVAGE_INTERVAL (10*60)
4423 * volume update list functionality has been moved into the VLRU
4424 * the DONT_SALVAGE flag is now set during VLRU demotion
4427 #ifndef AFS_DEMAND_ATTACH_FS
4428 static VolumeId *UpdateList = NULL; /* Pointer to array of Volume ID's */
4429 static int nUpdatedVolumes = 0; /* Updated with entry in UpdateList, salvage after crash flag on */
4430 static int updateSize = 0; /* number of entries possible */
4431 #define UPDATE_LIST_SIZE 128 /* initial size increment (must be a power of 2!) */
4432 #endif /* !AFS_DEMAND_ATTACH_FS */
4435 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
4438 vp->updateTime = FT_ApproxTime();
4439 if (V_dontSalvage(vp) == 0)
4441 V_dontSalvage(vp) = 0;
4442 VSyncVolume_r(ec, vp, 0);
4443 #ifdef AFS_DEMAND_ATTACH_FS
4444 V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
4445 #else /* !AFS_DEMAND_ATTACH_FS */
4448 if (UpdateList == NULL) {
4449 updateSize = UPDATE_LIST_SIZE;
4450 UpdateList = (VolumeId *) malloc(sizeof(VolumeId) * updateSize);
4452 if (nUpdatedVolumes == updateSize) {
4454 if (updateSize > 524288) {
4455 Log("warning: there is likely a bug in the volume update scanner\n");
4459 (VolumeId *) realloc(UpdateList,
4460 sizeof(VolumeId) * updateSize);
4463 assert(UpdateList != NULL);
4464 UpdateList[nUpdatedVolumes++] = V_id(vp);
4465 #endif /* !AFS_DEMAND_ATTACH_FS */
4468 #ifndef AFS_DEMAND_ATTACH_FS
4470 VScanUpdateList(void)
4472 register int i, gap;
4473 register Volume *vp;
4475 afs_uint32 now = FT_ApproxTime();
4476 /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
4477 for (i = gap = 0; i < nUpdatedVolumes; i++) {
4479 UpdateList[i - gap] = UpdateList[i];
4481 /* XXX this routine needlessly messes up the Volume LRU by
4482 * breaking the LRU temporal-locality assumptions.....
4483 * we should use a special volume header allocator here */
4484 vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
4487 } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
4488 V_dontSalvage(vp) = DONT_SALVAGE;
4489 VUpdateVolume_r(&error, vp, 0); /* No need to fsync--not critical */
4497 #ifndef AFS_PTHREAD_ENV
4499 #endif /* !AFS_PTHREAD_ENV */
4501 nUpdatedVolumes -= gap;
4503 #endif /* !AFS_DEMAND_ATTACH_FS */
4506 /***************************************************/
4507 /* Volume LRU routines */
4508 /***************************************************/
4513 * with demand attach fs, we attempt to soft detach(1)
4514 * volumes which have not been accessed in a long time
4515 * in order to speed up fileserver shutdown
4517 * (1) by soft detach we mean a process very similar
4518 * to VOffline, except the final state of the
4519 * Volume will be VOL_STATE_PREATTACHED, instead
4520 * of the usual VOL_STATE_UNATTACHED
4522 #ifdef AFS_DEMAND_ATTACH_FS
4524 /* implementation is reminiscent of a generational GC
4526 * queue 0 is newly attached volumes. this queue is
4527 * sorted by attach timestamp
4529 * queue 1 is volumes that have been around a bit
4530 * longer than queue 0. this queue is sorted by
4533 * queue 2 is volumes tha have been around the longest.
4534 * this queue is unsorted
4536 * queue 3 is volumes that have been marked as
4537 * candidates for soft detachment. this queue is
4540 #define VLRU_GENERATIONS 3 /* number of generations in VLRU */
4541 #define VLRU_QUEUES 5 /* total number of VLRU queues */
4543 volatile struct rx_queue q;
4549 struct VLRU_q q[VLRU_QUEUES];
4552 afs_uint32 promotion_interval[VLRU_GENERATIONS-1]; /* interval between promotions */
4553 afs_uint32 scan_interval[VLRU_GENERATIONS+1]; /* interval between scans for candidates */
4557 afs_uint32 last_promotion[VLRU_GENERATIONS-1]; /* timestamp of last promotion scan */
4558 afs_uint32 last_scan[VLRU_GENERATIONS+1]; /* timestamp of last detach scan */
4560 int scanner_state; /* state of scanner thread */
4561 pthread_cond_t cv; /* state transition CV */
4564 static struct VLRU volume_LRU;
4566 /* valid scanner states */
4567 #define VLRU_SCANNER_STATE_OFFLINE 0
4568 #define VLRU_SCANNER_STATE_ONLINE 1
4569 #define VLRU_SCANNER_STATE_SHUTTING_DOWN 2
4570 #define VLRU_SCANNER_STATE_PAUSING 3
4571 #define VLRU_SCANNER_STATE_PAUSED 4
4573 /* vlru disk data header stuff */
4574 #define VLRU_DISK_MAGIC 0x7a8b9cad
4575 #define VLRU_DISK_VERSION 1
4577 /* vlru default expiration time (for eventual fs state serialization of vlru data) */
4578 #define VLRU_DUMP_EXPIRATION_TIME (60*60*24*7) /* expire vlru data after 1 week */
4581 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
4582 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
4583 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
4584 static afs_uint32 VLRU_enabled = 1;
4586 /* queue synchronization routines */
4587 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
4588 static void VLRU_EndExclusive_r(struct VLRU_q * q);
4589 static void VLRU_Wait_r(struct VLRU_q * q);
4591 /* set the VLRU parameters
4593 * valid options are:
4594 * VLRU_SET_THRESH -- set the period of inactivity after
4595 * which volumes are eligible for being detached
4596 * VLRU_SET_INTERVAL -- the time interval between calls
4597 * to the volume LRU "garbage collector"
4598 * VLRU_SET_MAX -- the max number of volumes to deallocate
4602 VLRU_SetOptions(int option, afs_uint32 val)
4604 if (option == VLRU_SET_THRESH) {
4605 VLRU_offline_thresh = val;
4606 } else if (option == VLRU_SET_INTERVAL) {
4607 VLRU_offline_interval = val;
4608 } else if (option == VLRU_SET_MAX) {
4609 VLRU_offline_max = val;
4610 } else if (option == VLRU_SET_ENABLED) {
4613 VLRU_ComputeConstants();
4616 /* compute the VLRU internal timing parameters based upon the user's inputs */
4618 VLRU_ComputeConstants(void)
4620 afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
4622 /* compute the candidate scan interval */
4623 volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
4625 /* compute the promotion intervals */
4626 volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
4627 volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
4630 /* compute the gen 0 scan interval */
4631 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
4633 /* compute the gen 0 scan interval */
4634 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
4638 /* initialize VLRU */
4643 pthread_attr_t attrs;
4646 if (!VLRU_enabled) {
4647 Log("VLRU: disabled\n");
4651 /* initialize each of the VLRU queues */
4652 for (i = 0; i < VLRU_QUEUES; i++) {
4653 queue_Init(&volume_LRU.q[i]);
4654 volume_LRU.q[i].len = 0;
4655 volume_LRU.q[i].busy = 0;
4656 assert(pthread_cond_init(&volume_LRU.q[i].cv, NULL) == 0);
4659 /* setup the timing constants */
4660 VLRU_ComputeConstants();
4662 /* XXX put inside LogLevel check? */
4663 Log("VLRU: starting scanner with the following configuration parameters:\n");
4664 Log("VLRU: offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
4665 Log("VLRU: running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
4666 Log("VLRU: taking up to %d volumes offline per pass\n", VLRU_offline_max);
4667 Log("VLRU: scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
4668 Log("VLRU: scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
4669 Log("VLRU: scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
4671 /* start up the VLRU scanner */
4672 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
4673 if (programType == fileServer) {
4674 assert(pthread_cond_init(&volume_LRU.cv, NULL) == 0);
4675 assert(pthread_attr_init(&attrs) == 0);
4676 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
4677 assert(pthread_create(&tid, &attrs, &VLRU_ScannerThread, NULL) == 0);
4681 /* initialize LRU support for a volume */
4683 VLRU_Init_Node_r(volatile Volume * vp)
4688 assert(queue_IsNotOnQueue(&vp->vlru));
4689 vp->vlru.idx = VLRU_QUEUE_INVALID;
4692 /* add volume to VLRU
4693 * now supports adding to queues other
4694 * than new for vlru state restore
4695 * caller MUST hold a ref count on vp */
4697 VLRU_Add_r(volatile Volume * vp)
4704 if (queue_IsOnQueue(&vp->vlru))
4707 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
4709 /* repeat check since VLRU_Wait_r may have dropped
4711 if (queue_IsNotOnQueue(&vp->vlru)) {
4713 if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
4714 idx = vp->vlru.idx = VLRU_QUEUE_NEW;
4716 queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
4717 volume_LRU.q[idx].len++;
4718 V_attachFlags(vp) |= VOL_ON_VLRU;
4719 vp->stats.last_promote = FT_ApproxTime();
4723 /* delete volume from VLRU
4724 * caller MUST hold a ref count on vp */
4726 VLRU_Delete_r(volatile Volume * vp)
4733 if (queue_IsNotOnQueue(&vp->vlru))
4739 if (idx == VLRU_QUEUE_INVALID)
4741 VLRU_Wait_r(&volume_LRU.q[idx]);
4742 } while (idx != vp->vlru.idx);
4744 /* now remove from the VLRU and update
4745 * the appropriate counter */
4746 queue_Remove(&vp->vlru);
4747 volume_LRU.q[idx].len--;
4748 vp->vlru.idx = VLRU_QUEUE_INVALID;
4749 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
4752 /* signal that volume was just accessed.
4753 * caller MUST hold a ref count on vp */
4755 VLRU_UpdateAccess_r(volatile Volume * vp)
4757 afs_uint32 live_interval;
4758 Volume * rvp = NULL;
4763 if (queue_IsNotOnQueue(&vp->vlru))
4766 assert(V_attachFlags(vp) & VOL_ON_VLRU);
4768 /* update the access timestamp */
4769 vp->stats.last_get = FT_ApproxTime();
4772 * if the volume is on the soft detach candidate
4773 * list, we need to safely move it back to a
4774 * regular generation. this has to be done
4775 * carefully so we don't race against the scanner
4779 /* if this volume is on the soft detach candidate queue,
4780 * then grab exclusive access to the necessary queues */
4781 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
4783 VCreateReservation_r(rvp);
4785 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
4786 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
4787 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
4788 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
4791 /* make sure multiple threads don't race to update */
4792 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
4793 VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
4797 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
4798 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
4799 VCancelReservation_r(rvp);
4803 /* switch a volume between two VLRU queues */
4805 VLRU_SwitchQueues(volatile Volume * vp, int new_idx, int append)
4807 if (queue_IsNotOnQueue(&vp->vlru))
4810 queue_Remove(&vp->vlru);
4811 volume_LRU.q[vp->vlru.idx].len--;
4813 /* put the volume back on the correct generational queue */
4815 queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
4817 queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
4820 volume_LRU.q[new_idx].len++;
4821 vp->vlru.idx = new_idx;
4824 /* VLRU GC thread */
4826 VLRU_ScannerThread(void * args)
4828 afs_uint32 now, min_delay, delay;
4829 afs_uint32 next_scan[VLRU_GENERATIONS];
4830 afs_uint32 next_promotion[VLRU_GENERATIONS];
4831 int i, min_idx, min_op, overdue, state;
4833 /* set t=0 for promotion cycle to be
4834 * fileserver startup */
4835 now = FT_ApproxTime();
4836 for (i=0; i < VLRU_GENERATIONS-1; i++) {
4837 volume_LRU.last_promotion[i] = now;
4840 /* don't start the scanner until VLRU_offline_thresh
4841 * plus a small delay for VInitVolumePackage to finish
4844 sleep(VLRU_offline_thresh + 60);
4846 /* set t=0 for scan cycle to be now */
4847 now = FT_ApproxTime();
4848 for (i=0; i < VLRU_GENERATIONS+1; i++) {
4849 volume_LRU.last_scan[i] = now;
4853 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
4854 volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
4857 while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
4858 /* check to see if we've been asked to pause */
4859 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
4860 volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
4861 assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
4863 assert(pthread_cond_wait(&volume_LRU.cv, &vol_glock_mutex) == 0);
4864 } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
4867 /* scheduling can happen outside the glock */
4870 /* figure out what is next on the schedule */
4872 /* figure out a potential schedule for the new generation first */
4874 min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
4877 if (min_delay > volume_LRU.scan_interval[0]) {
4878 /* unsigned overflow -- we're overdue to run this scan */
4883 /* if we're not overdue for gen 0, figure out schedule for candidate gen */
4885 i = VLRU_QUEUE_CANDIDATE;
4886 delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
4887 if (delay < min_delay) {
4891 if (delay > volume_LRU.scan_interval[i]) {
4892 /* unsigned overflow -- we're overdue to run this scan */
4900 /* if we're still not overdue for something, figure out schedules for promotions */
4901 for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
4902 delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
4903 if (delay < min_delay) {
4908 if (delay > volume_LRU.promotion_interval[i]) {
4909 /* unsigned overflow -- we're overdue to run this promotion */
4918 /* sleep as needed */
4923 /* do whatever is next */
4926 VLRU_Promote_r(min_idx);
4927 VLRU_Demote_r(min_idx+1);
4929 VLRU_Scan_r(min_idx);
4931 now = FT_ApproxTime();
4934 Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
4936 /* signal that scanner is down */
4937 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
4938 assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
4943 /* run the promotions */
4945 VLRU_Promote_r(int idx)
4947 int len, chaining, promote;
4948 afs_uint32 now, thresh;
4949 struct rx_queue *qp, *nqp;
4950 Volume * vp, *start, *end;
4952 /* get exclusive access to two chains, and drop the glock */
4953 VLRU_Wait_r(&volume_LRU.q[idx]);
4954 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
4955 VLRU_Wait_r(&volume_LRU.q[idx+1]);
4956 VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
4959 thresh = volume_LRU.promotion_interval[idx];
4960 now = FT_ApproxTime();
4963 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
4964 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
4965 promote = (((vp->stats.last_promote + thresh) <= now) &&
4966 (vp->stats.last_get >= vp->stats.last_promote));
4974 /* promote and prepend chain */
4975 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
4989 /* promote and prepend */
4990 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
4994 volume_LRU.q[idx].len -= len;
4995 volume_LRU.q[idx+1].len += len;
4998 /* release exclusive access to the two chains */
5000 volume_LRU.last_promotion[idx] = now;
5001 VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
5002 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
5005 /* run the demotions */
5007 VLRU_Demote_r(int idx)
5010 int len, chaining, demote;
5011 afs_uint32 now, thresh;
5012 struct rx_queue *qp, *nqp;
5013 Volume * vp, *start, *end;
5014 Volume ** salv_flag_vec = NULL;
5015 int salv_vec_offset = 0;
5017 assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
5019 /* get exclusive access to two chains, and drop the glock */
5020 VLRU_Wait_r(&volume_LRU.q[idx-1]);
5021 VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
5022 VLRU_Wait_r(&volume_LRU.q[idx]);
5023 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
5026 /* no big deal if this allocation fails */
5027 if (volume_LRU.q[idx].len) {
5028 salv_flag_vec = (Volume **) malloc(volume_LRU.q[idx].len * sizeof(Volume *));
5031 now = FT_ApproxTime();
5032 thresh = volume_LRU.promotion_interval[idx-1];
5035 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
5036 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
5037 demote = (((vp->stats.last_promote + thresh) <= now) &&
5038 (vp->stats.last_get < (now - thresh)));
5040 /* we now do volume update list DONT_SALVAGE flag setting during
5041 * demotion passes */
5042 if (salv_flag_vec &&
5043 !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
5045 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
5046 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
5047 salv_flag_vec[salv_vec_offset++] = vp;
5048 VCreateReservation_r(vp);
5057 /* demote and append chain */
5058 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
5072 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
5076 volume_LRU.q[idx].len -= len;
5077 volume_LRU.q[idx-1].len += len;
5080 /* release exclusive access to the two chains */
5082 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
5083 VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
5085 /* now go back and set the DONT_SALVAGE flags as appropriate */
5086 if (salv_flag_vec) {
5088 for (i = 0; i < salv_vec_offset; i++) {
5089 vp = salv_flag_vec[i];
5090 if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
5091 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
5092 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
5095 V_attachFlags(vp) |= VOL_HDR_DONTSALV;
5096 V_dontSalvage(vp) = DONT_SALVAGE;
5097 VUpdateVolume_r(&ec, vp, 0);
5101 VCancelReservation_r(vp);
5103 free(salv_flag_vec);
5107 /* run a pass of the VLRU GC scanner */
5109 VLRU_Scan_r(int idx)
5111 afs_uint32 now, thresh;
5112 struct rx_queue *qp, *nqp;
5113 volatile Volume * vp;
5116 assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
5118 /* gain exclusive access to the idx VLRU */
5119 VLRU_Wait_r(&volume_LRU.q[idx]);
5120 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
5122 if (idx != VLRU_QUEUE_CANDIDATE) {
5123 /* gain exclusive access to the candidate VLRU */
5124 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5125 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5128 now = FT_ApproxTime();
5129 thresh = now - VLRU_offline_thresh;
5131 /* perform candidate selection and soft detaching */
5132 if (idx == VLRU_QUEUE_CANDIDATE) {
5133 /* soft detach some volumes from the candidate pool */
5137 for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
5138 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
5139 if (i >= VLRU_offline_max) {
5142 /* check timestamp to see if it's a candidate for soft detaching */
5143 if (vp->stats.last_get <= thresh) {
5145 if (VCheckSoftDetach(vp, thresh))
5151 /* scan for volumes to become soft detach candidates */
5152 for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
5153 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
5155 /* check timestamp to see if it's a candidate for soft detaching */
5156 if (vp->stats.last_get <= thresh) {
5157 VCheckSoftDetachCandidate(vp, thresh);
5160 if (!(i&0x7f)) { /* lock coarsening optimization */
5168 /* relinquish exclusive access to the VLRU chains */
5172 volume_LRU.last_scan[idx] = now;
5173 if (idx != VLRU_QUEUE_CANDIDATE) {
5174 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5176 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
5179 /* check whether volume is safe to soft detach
5180 * caller MUST NOT hold a ref count on vp */
5182 VCheckSoftDetach(volatile Volume * vp, afs_uint32 thresh)
5186 if (vp->nUsers || vp->nWaiters)
5189 if (vp->stats.last_get <= thresh) {
5190 ret = VSoftDetachVolume_r(vp, thresh);
5196 /* check whether volume should be made a
5197 * soft detach candidate */
5199 VCheckSoftDetachCandidate(volatile Volume * vp, afs_uint32 thresh)
5202 if (vp->nUsers || vp->nWaiters)
5207 assert(idx == VLRU_QUEUE_NEW);
5209 if (vp->stats.last_get <= thresh) {
5210 /* move to candidate pool */
5211 queue_Remove(&vp->vlru);
5212 volume_LRU.q[VLRU_QUEUE_NEW].len--;
5213 queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
5214 vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
5215 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
5223 /* begin exclusive access on VLRU */
5225 VLRU_BeginExclusive_r(struct VLRU_q * q)
5227 assert(q->busy == 0);
5231 /* end exclusive access on VLRU */
5233 VLRU_EndExclusive_r(struct VLRU_q * q)
5237 assert(pthread_cond_broadcast(&q->cv) == 0);
5240 /* wait for another thread to end exclusive access on VLRU */
5242 VLRU_Wait_r(struct VLRU_q * q)
5245 assert(pthread_cond_wait(&q->cv, &vol_glock_mutex) == 0);
5250 * volume soft detach
5252 * caller MUST NOT hold a ref count on vp */
5254 VSoftDetachVolume_r(volatile Volume * vp, afs_uint32 thresh)
5259 assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
5261 ts_save = vp->stats.last_get;
5262 if (ts_save > thresh)
5265 if (vp->nUsers || vp->nWaiters)
5268 if (IsExclusiveState(V_attachState(vp))) {
5272 switch (V_attachState(vp)) {
5273 case VOL_STATE_UNATTACHED:
5274 case VOL_STATE_PREATTACHED:
5275 case VOL_STATE_ERROR:
5276 case VOL_STATE_GOING_OFFLINE:
5277 case VOL_STATE_SHUTTING_DOWN:
5278 case VOL_STATE_SALVAGING:
5279 volume_LRU.q[vp->vlru.idx].len--;
5281 /* create and cancel a reservation to
5282 * give the volume an opportunity to
5284 VCreateReservation_r(vp);
5285 queue_Remove(&vp->vlru);
5286 vp->vlru.idx = VLRU_QUEUE_INVALID;
5287 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
5288 VCancelReservation_r(vp);
5292 /* hold the volume and take it offline.
5293 * no need for reservations, as VHold_r
5294 * takes care of that internally. */
5295 if (VHold_r(vp) == 0) {
5296 /* vhold drops the glock, so now we should
5297 * check to make sure we aren't racing against
5298 * other threads. if we are racing, offlining vp
5299 * would be wasteful, and block the scanner for a while
5303 (vp->shuttingDown) ||
5304 (vp->goingOffline) ||
5305 (vp->stats.last_get != ts_save)) {
5306 /* looks like we're racing someone else. bail */
5310 /* pull it off the VLRU */
5311 assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
5312 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
5313 queue_Remove(&vp->vlru);
5314 vp->vlru.idx = VLRU_QUEUE_INVALID;
5315 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
5317 /* take if offline */
5318 VOffline_r(vp, "volume has been soft detached");
5320 /* invalidate the volume header cache */
5321 FreeVolumeHeader(vp);
5324 IncUInt64(&VStats.soft_detaches);
5325 vp->stats.soft_detaches++;
5327 /* put in pre-attached state so demand
5328 * attacher can work on it */
5329 VChangeState_r(vp, VOL_STATE_PREATTACHED);
5335 #endif /* AFS_DEMAND_ATTACH_FS */
5338 /***************************************************/
5339 /* Volume Header Cache routines */
5340 /***************************************************/
5342 struct volume_hdr_LRU_t volume_hdr_LRU;
5344 /* Allocate a bunch of headers; string them together */
5346 VInitVolumeHeaderCache(afs_uint32 howMany)
5348 register struct volHeader *hp;
5349 if (programType != fileServer)
5351 queue_Init(&volume_hdr_LRU);
5352 #ifdef AFS_DEMAND_ATTACH_FS
5353 volume_hdr_LRU.stats.free = 0;
5354 volume_hdr_LRU.stats.used = howMany;
5355 volume_hdr_LRU.stats.attached = 0;
5357 hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
5359 ReleaseVolumeHeader(hp++);
5362 #ifdef AFS_DEMAND_ATTACH_FS
5363 /* Get a volume header from the LRU list; update the old one if necessary */
5364 /* Returns 1 if there was already a header, which is removed from the LRU list */
5365 /* caller MUST has a ref count on vp */
5367 GetVolumeHeader(register Volume * vp)
5370 register struct volHeader *hd;
5372 static int everLogged = 0;
5374 /* XXX debug 9/19/05 we've apparently got
5375 * a ref counting bug somewhere that's
5376 * breaking the nUsers == 0 => header on LRU
5378 if (vp->header && queue_IsNotOnQueue(vp->header)) {
5379 Log("nUsers == 0, but header not on LRU\n");
5383 old = (vp->header != NULL); /* old == volume already has a header */
5385 if (programType != fileServer) {
5386 /* for volume utilities, we allocate volHeaders as needed */
5388 hd = (struct volHeader *)calloc(1, sizeof(*vp->header));
5392 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
5396 /* the header we previously dropped in the lru is
5397 * still available. pull it off the lru and return */
5400 assert(hd->back == vp);
5402 /* we need to grab a new element off the LRU */
5403 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
5404 /* grab an element and pull off of LRU */
5405 hd = queue_First(&volume_hdr_LRU, volHeader);
5408 /* LRU is empty, so allocate a new volHeader
5409 * this is probably indicative of a leak, so let the user know */
5410 hd = (struct volHeader *)calloc(1, sizeof(struct volHeader));
5413 Log("****Allocated more volume headers, probably leak****\n");
5416 volume_hdr_LRU.stats.free++;
5419 VolState vp_save, back_save;
5420 /* this header used to belong to someone else.
5421 * we'll need to check if the header needs to
5422 * be sync'd out to disk */
5424 /* if hd->back were in an exclusive state, then
5425 * its volHeader would not be on the LRU... */
5426 assert(!IsExclusiveState(V_attachState(hd->back)));
5428 if (hd->diskstuff.inUse) {
5429 /* volume was in use, so we'll need to sync
5430 * its header to disk */
5431 back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
5432 vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
5433 VCreateReservation_r(hd->back);
5436 WriteVolumeHeader_r(&error, hd->back);
5437 /* Ignore errors; catch them later */
5442 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
5443 hd->back->header = NULL;
5445 if (hd->diskstuff.inUse) {
5446 VChangeState_r(hd->back, back_save);
5447 VCancelReservation_r(hd->back);
5448 VChangeState_r(vp, vp_save);
5451 volume_hdr_LRU.stats.attached++;
5455 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
5457 volume_hdr_LRU.stats.free--;
5458 volume_hdr_LRU.stats.used++;
5460 IncUInt64(&VStats.hdr_gets);
5461 IncUInt64(&vp->stats.hdr_gets);
5462 vp->stats.last_hdr_get = FT_ApproxTime();
5465 #else /* AFS_DEMAND_ATTACH_FS */
5466 /* Get a volume header from the LRU list; update the old one if necessary */
5467 /* Returns 1 if there was already a header, which is removed from the LRU list */
5469 GetVolumeHeader(register Volume * vp)
5472 register struct volHeader *hd;
5474 static int everLogged = 0;
5476 old = (vp->header != NULL); /* old == volume already has a header */
5478 if (programType != fileServer) {
5479 /* for volume utilities, we allocate volHeaders as needed */
5481 hd = (struct volHeader *)calloc(1, sizeof(*vp->header));
5487 /* for the fileserver, we keep a volume header cache */
5489 /* the header we previously dropped in the lru is
5490 * still available. pull it off the lru and return */
5493 assert(hd->back == vp);
5495 /* we need to grab a new element off the LRU */
5496 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
5497 /* grab an element */
5498 hd = queue_First(&volume_hdr_LRU, volHeader);
5501 /* LRU is empty, so allocate a new volHeader
5502 * this is probably indicative of a leak, so let the user know */
5503 hd = (struct volHeader *)calloc(1, sizeof(struct volHeader));
5506 Log("****Allocated more volume headers, probably leak****\n");
5511 /* this header used to belong to someone else.
5512 * we'll need to check if the header needs to
5513 * be sync'd out to disk */
5515 if (hd->diskstuff.inUse) {
5516 WriteVolumeHeader_r(&error, hd->back);
5517 /* Ignore errors; catch them later */
5519 hd->back->header = NULL;
5527 #endif /* AFS_DEMAND_ATTACH_FS */
5530 /* make sure a volume header is attached to
5531 * vp, and has the correct data loaded from
5533 #ifdef AFS_DEMAND_ATTACH_FS
5534 /* caller MUST hold a ref count on vp */
5536 LoadVolumeHeader(Error * ec, Volume * vp)
5538 VolState state_save;
5541 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
5542 IncUInt64(&VStats.hdr_loads);
5543 state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
5546 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
5547 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
5549 IncUInt64(&vp->stats.hdr_loads);
5553 V_attachFlags(vp) |= VOL_HDR_LOADED;
5554 VChangeState_r(vp, state_save);
5557 /* maintain (nUsers==0) => header in LRU invariant */
5558 ReleaseVolumeHeader(vp->header);
5561 #else /* AFS_DEMAND_ATTACH_FS */
5563 LoadVolumeHeader(Error * ec, Volume * vp)
5566 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
5567 IncUInt64(&VStats.hdr_loads);
5569 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
5570 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
5574 /* maintain (nUsers==0) => header in LRU invariant */
5575 ReleaseVolumeHeader(vp->header);
5578 #endif /* AFS_DEMAND_ATTACH_FS */
5580 /* Put it at the top of the LRU chain */
5582 ReleaseVolumeHeader(register struct volHeader *hd)
5584 if (programType != fileServer)
5586 if (!hd || queue_IsOnQueue(hd)) /* no header, or header already released */
5588 queue_Append(&volume_hdr_LRU, hd);
5589 #ifdef AFS_DEMAND_ATTACH_FS
5591 V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
5593 volume_hdr_LRU.stats.free++;
5594 volume_hdr_LRU.stats.used--;
5598 /* for fileserver, return header to LRU, and
5599 * invalidate it as a cache entry.
5601 * for volume utilities, free the heap space */
5603 FreeVolumeHeader(register Volume * vp)
5605 register struct volHeader *hd = vp->header;
5608 if (programType == fileServer) {
5609 ReleaseVolumeHeader(hd);
5614 #ifdef AFS_DEMAND_ATTACH_FS
5615 V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
5616 volume_hdr_LRU.stats.attached--;
5622 /***************************************************/
5623 /* Volume Hash Table routines */
5624 /***************************************************/
5627 VSetVolHashSize(int logsize)
5629 /* 64 to 16384 hash buckets seems like a reasonable range */
5630 if ((logsize < 6 ) || (logsize > 14)) {
5635 VolumeHashTable.Size = 1 << logsize;
5636 VolumeHashTable.Mask = VolumeHashTable.Size - 1;
5638 /* we can't yet support runtime modification of this
5639 * parameter. we'll need a configuration rwlock to
5640 * make runtime modification feasible.... */
5647 VInitVolumeHash(void)
5651 VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
5652 sizeof(VolumeHashChainHead));
5653 assert(VolumeHashTable.Table != NULL);
5655 for (i=0; i < VolumeHashTable.Size; i++) {
5656 queue_Init(&VolumeHashTable.Table[i]);
5657 #ifdef AFS_DEMAND_ATTACH_FS
5658 assert(pthread_cond_init(&VolumeHashTable.Table[i].chain_busy_cv, NULL) == 0);
5659 #endif /* AFS_DEMAND_ATTACH_FS */
5663 /* for demand-attach, caller MUST hold a ref count on vp */
5665 AddVolumeToHashTable(register Volume * vp, int hashid)
5667 VolumeHashChainHead * head;
5669 if (queue_IsOnQueue(vp))
5672 head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
5674 #ifdef AFS_DEMAND_ATTACH_FS
5675 /* wait for the hash chain to become available */
5678 V_attachFlags(vp) |= VOL_IN_HASH;
5679 vp->chainCacheCheck = ++head->cacheCheck;
5680 #endif /* AFS_DEMAND_ATTACH_FS */
5683 vp->hashid = hashid;
5684 queue_Append(head, vp);
5685 vp->vnodeHashOffset = VolumeHashOffset_r();
5688 /* for demand-attach, caller MUST hold a ref count on vp */
5690 DeleteVolumeFromHashTable(register Volume * vp)
5692 VolumeHashChainHead * head;
5694 if (!queue_IsOnQueue(vp))
5697 head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
5699 #ifdef AFS_DEMAND_ATTACH_FS
5700 /* wait for the hash chain to become available */
5703 V_attachFlags(vp) &= ~(VOL_IN_HASH);
5705 #endif /* AFS_DEMAND_ATTACH_FS */
5709 /* do NOT reset hashid to zero, as the online
5710 * salvager package may need to know the volume id
5711 * after the volume is removed from the hash */
5714 /* - look up a volume id in the hash table
5715 * - occasionally rebalance hash chains
5716 * - update lookup statistics accordingly
5718 /* the hint parameter allows us to short-circuit on
5719 * DEMAND_ATTACH_FS if the cacheChecks match between
5720 * the hash chain head and hint
5721 * caller MUST hold a refcount on hint */
5723 VLookupVolume_r(Error * ec, VolId volumeId, Volume * hint)
5725 register int looks = 0;
5726 Volume * vp, *np, *pp;
5727 VolumeHashChainHead * head;
5730 head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
5732 #ifdef AFS_DEMAND_ATTACH_FS
5733 /* wait for the hash chain to become available */
5736 /* check to see if we can short circuit without walking the hash chain */
5737 if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
5738 IncUInt64(&hint->stats.hash_short_circuits);
5741 #endif /* AFS_DEMAND_ATTACH_FS */
5743 /* someday we need to either do per-chain locks, RWlocks,
5744 * or both for volhash access.
5745 * (and move to a data structure with better cache locality) */
5747 /* search the chain for this volume id */
5748 for(queue_Scan(head, vp, np, Volume)) {
5750 if ((vp->hashid == volumeId)) {
5755 if (queue_IsEnd(head, vp)) {
5759 #ifdef AFS_DEMAND_ATTACH_FS
5760 /* update hash chain statistics */
5763 FillInt64(lks, 0, looks);
5764 AddUInt64(head->looks, lks, &head->looks);
5765 AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
5766 IncUInt64(&head->gets);
5771 IncUInt64(&vp->stats.hash_lookups);
5773 /* for demand attach fileserver, we permit occasional hash chain reordering
5774 * so that frequently looked up volumes move towards the head of the chain */
5775 pp = queue_Prev(vp, Volume);
5776 if (!queue_IsEnd(head, pp)) {
5777 FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
5778 AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
5779 if (GEInt64(vp->stats.hash_lookups, thresh)) {
5780 VReorderHash_r(head, pp, vp);
5784 /* update the short-circuit cache check */
5785 vp->chainCacheCheck = head->cacheCheck;
5787 #endif /* AFS_DEMAND_ATTACH_FS */
5792 #ifdef AFS_DEMAND_ATTACH_FS
5793 /* perform volume hash chain reordering.
5795 * advance a subchain beginning at vp ahead of
5796 * the adjacent subchain ending at pp */
5798 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
5800 Volume *tp, *np, *lp;
5801 afs_uint64 move_thresh;
5803 /* this should never be called if the chain is already busy, so
5804 * no need to wait for other exclusive chain ops to finish */
5806 /* this is a rather heavy set of operations,
5807 * so let's set the chain busy flag and drop
5809 VHashBeginExclusive_r(head);
5812 /* scan forward in the chain from vp looking for the last element
5813 * in the chain we want to advance */
5814 FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
5815 AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
5816 for(queue_ScanFrom(head, vp, tp, np, Volume)) {
5817 if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
5821 lp = queue_Prev(tp, Volume);
5823 /* scan backwards from pp to determine where to splice and
5824 * insert the subchain we're advancing */
5825 for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
5826 if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
5830 tp = queue_Next(tp, Volume);
5832 /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
5833 queue_MoveChainBefore(tp,vp,lp);
5836 IncUInt64(&VStats.hash_reorders);
5838 IncUInt64(&head->reorders);
5840 /* wake up any threads waiting for the hash chain */
5841 VHashEndExclusive_r(head);
5845 /* demand-attach fs volume hash
5846 * asynchronous exclusive operations */
5848 /* take exclusive control over the hash chain */
5850 VHashBeginExclusive_r(VolumeHashChainHead * head)
5852 assert(head->busy == 0);
5856 /* relinquish exclusive control over the hash chain */
5858 VHashEndExclusive_r(VolumeHashChainHead * head)
5862 assert(pthread_cond_broadcast(&head->chain_busy_cv) == 0);
5865 /* wait for another thread to finish its exclusive ops */
5867 VHashWait_r(VolumeHashChainHead * head)
5869 while (head->busy) {
5870 assert(pthread_cond_wait(&head->chain_busy_cv, &vol_glock_mutex) == 0);
5873 #endif /* AFS_DEMAND_ATTACH_FS */
5876 /***************************************************/
5877 /* Volume by Partition List routines */
5878 /***************************************************/
5881 * demand attach fileserver adds a
5882 * linked list of volumes to each
5883 * partition object, thus allowing
5884 * for quick enumeration of all
5885 * volumes on a partition
5888 #ifdef AFS_DEMAND_ATTACH_FS
5890 AddVolumeToVByPList_r(Volume * vp)
5892 if (queue_IsNotOnQueue(&vp->vol_list)) {
5893 queue_Append(&vp->partition->vol_list, &vp->vol_list);
5894 V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
5895 vp->partition->vol_list.len++;
5900 DeleteVolumeFromVByPList_r(Volume * vp)
5902 if (queue_IsOnQueue(&vp->vol_list)) {
5903 queue_Remove(&vp->vol_list);
5904 V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
5905 vp->partition->vol_list.len--;
5909 /* take exclusive control over the list */
5911 VVByPListBeginExclusive_r(struct DiskPartition * dp)
5913 assert(dp->vol_list.busy == 0);
5914 dp->vol_list.busy = 1;
5917 /* relinquish exclusive control over the list */
5919 VVByPListEndExclusive_r(struct DiskPartition * dp)
5921 assert(dp->vol_list.busy);
5922 dp->vol_list.busy = 0;
5923 assert(pthread_cond_broadcast(&dp->vol_list.cv) == 0);
5926 /* wait for another thread to finish its exclusive ops */
5928 VVByPListWait_r(struct DiskPartition * dp)
5930 while (dp->vol_list.busy) {
5931 assert(pthread_cond_wait(&dp->vol_list.cv, &vol_glock_mutex) == 0);
5934 #endif /* AFS_DEMAND_ATTACH_FS */
5936 /***************************************************/
5937 /* Volume Cache Statistics routines */
5938 /***************************************************/
5941 VPrintCacheStats_r(void)
5943 afs_uint32 get_hi, get_lo, load_hi, load_lo;
5944 register struct VnodeClassInfo *vcp;
5945 vcp = &VnodeClassInfo[vLarge];
5946 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);
5947 vcp = &VnodeClassInfo[vSmall];
5948 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);
5949 SplitInt64(VStats.hdr_gets, get_hi, get_lo);
5950 SplitInt64(VStats.hdr_loads, load_hi, load_lo);
5951 Log("Volume header cache, %d entries, %d gets, %d replacements\n",
5952 VStats.hdr_cache_size, get_lo, load_lo);
5956 VPrintCacheStats(void)
5959 VPrintCacheStats_r();
5963 #ifdef AFS_DEMAND_ATTACH_FS
5965 UInt64ToDouble(afs_uint64 * x)
5967 static double c32 = 4.0 * 1.073741824 * 1000000000.0;
5969 SplitInt64(*x, h, l);
5970 return (((double)h) * c32) + ((double) l);
5974 DoubleToPrintable(double x, char * buf, int len)
5976 static double billion = 1000000000.0;
5979 y[0] = (afs_uint32) (x / (billion * billion));
5980 y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
5981 y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
5984 snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
5986 snprintf(buf, len, "%d%09d", y[1], y[2]);
5988 snprintf(buf, len, "%d", y[2]);
5995 VPrintExtendedCacheStats_r(int flags)
6004 struct stats looks, gets, reorders, len;
6005 struct stats ch_looks, ch_gets, ch_reorders;
6007 VolumeHashChainHead *head;
6010 /* zero out stats */
6011 memset(&looks, 0, sizeof(struct stats));
6012 memset(&gets, 0, sizeof(struct stats));
6013 memset(&reorders, 0, sizeof(struct stats));
6014 memset(&len, 0, sizeof(struct stats));
6015 memset(&ch_looks, 0, sizeof(struct stats));
6016 memset(&ch_gets, 0, sizeof(struct stats));
6017 memset(&ch_reorders, 0, sizeof(struct stats));
6019 for (i = 0; i < VolumeHashTable.Size; i++) {
6020 head = &VolumeHashTable.Table[i];
6023 VHashBeginExclusive_r(head);
6026 ch_looks.sum = UInt64ToDouble(&head->looks);
6027 ch_gets.sum = UInt64ToDouble(&head->gets);
6028 ch_reorders.sum = UInt64ToDouble(&head->reorders);
6030 /* update global statistics */
6032 looks.sum += ch_looks.sum;
6033 gets.sum += ch_gets.sum;
6034 reorders.sum += ch_reorders.sum;
6035 len.sum += (double)head->len;
6038 len.min = (double) head->len;
6039 len.max = (double) head->len;
6040 looks.min = ch_looks.sum;
6041 looks.max = ch_looks.sum;
6042 gets.min = ch_gets.sum;
6043 gets.max = ch_gets.sum;
6044 reorders.min = ch_reorders.sum;
6045 reorders.max = ch_reorders.sum;
6047 if (((double)head->len) < len.min)
6048 len.min = (double) head->len;
6049 if (((double)head->len) > len.max)
6050 len.max = (double) head->len;
6051 if (ch_looks.sum < looks.min)
6052 looks.min = ch_looks.sum;
6053 else if (ch_looks.sum > looks.max)
6054 looks.max = ch_looks.sum;
6055 if (ch_gets.sum < gets.min)
6056 gets.min = ch_gets.sum;
6057 else if (ch_gets.sum > gets.max)
6058 gets.max = ch_gets.sum;
6059 if (ch_reorders.sum < reorders.min)
6060 reorders.min = ch_reorders.sum;
6061 else if (ch_reorders.sum > reorders.max)
6062 reorders.max = ch_reorders.sum;
6066 if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
6067 /* compute detailed per-chain stats */
6068 struct stats hdr_loads, hdr_gets;
6069 double v_looks, v_loads, v_gets;
6071 /* initialize stats with data from first element in chain */
6072 vp = queue_First(head, Volume);
6073 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
6074 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
6075 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
6076 ch_gets.min = ch_gets.max = v_looks;
6077 hdr_loads.min = hdr_loads.max = v_loads;
6078 hdr_gets.min = hdr_gets.max = v_gets;
6079 hdr_loads.sum = hdr_gets.sum = 0;
6081 vp = queue_Next(vp, Volume);
6083 /* pull in stats from remaining elements in chain */
6084 for (queue_ScanFrom(head, vp, vp, np, Volume)) {
6085 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
6086 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
6087 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
6089 hdr_loads.sum += v_loads;
6090 hdr_gets.sum += v_gets;
6092 if (v_looks < ch_gets.min)
6093 ch_gets.min = v_looks;
6094 else if (v_looks > ch_gets.max)
6095 ch_gets.max = v_looks;
6097 if (v_loads < hdr_loads.min)
6098 hdr_loads.min = v_loads;
6099 else if (v_loads > hdr_loads.max)
6100 hdr_loads.max = v_loads;
6102 if (v_gets < hdr_gets.min)
6103 hdr_gets.min = v_gets;
6104 else if (v_gets > hdr_gets.max)
6105 hdr_gets.max = v_gets;
6108 /* compute per-chain averages */
6109 ch_gets.avg = ch_gets.sum / ((double)head->len);
6110 hdr_loads.avg = hdr_loads.sum / ((double)head->len);
6111 hdr_gets.avg = hdr_gets.sum / ((double)head->len);
6113 /* dump per-chain stats */
6114 Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
6116 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
6117 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
6118 Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
6119 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
6120 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
6121 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
6122 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
6123 Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
6124 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
6125 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
6126 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
6127 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
6128 Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
6129 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
6130 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
6131 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
6132 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
6133 } else if (flags & VOL_STATS_PER_CHAIN) {
6134 /* dump simple per-chain stats */
6135 Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
6137 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
6138 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
6139 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
6143 VHashEndExclusive_r(head);
6148 /* compute global averages */
6149 len.avg = len.sum / ((double)VolumeHashTable.Size);
6150 looks.avg = looks.sum / ((double)VolumeHashTable.Size);
6151 gets.avg = gets.sum / ((double)VolumeHashTable.Size);
6152 reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
6154 /* dump global stats */
6155 Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
6156 Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
6157 DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
6158 DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
6159 DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
6160 DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
6161 Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
6162 DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
6163 DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
6164 DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
6165 DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
6166 Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
6167 DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
6168 DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
6169 DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
6170 DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
6171 Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
6172 DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
6173 DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
6174 DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
6175 DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
6177 /* print extended disk related statistics */
6179 struct DiskPartition * diskP;
6180 afs_uint32 vol_count[VOLMAXPARTS+1];
6181 byte part_exists[VOLMAXPARTS+1];
6185 memset(vol_count, 0, sizeof(vol_count));
6186 memset(part_exists, 0, sizeof(part_exists));
6190 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
6192 vol_count[id] = diskP->vol_list.len;
6193 part_exists[id] = 1;
6197 for (i = 0; i <= VOLMAXPARTS; i++) {
6198 if (part_exists[i]) {
6199 diskP = VGetPartitionById_r(i, 0);
6201 Log("Partition %s has %d online volumes\n",
6202 VPartitionPath(diskP), diskP->vol_list.len);
6212 VPrintExtendedCacheStats(int flags)
6215 VPrintExtendedCacheStats_r(flags);
6218 #endif /* AFS_DEMAND_ATTACH_FS */