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)
85 #ifdef AFS_SGI_EFS_IOPS_ENV
86 #define ROOTINO EFS_ROOTINO
87 #include <sys/fs/efs.h>
88 #include "sgiefs/efs.h" /* until 5.1 release */
93 #ifndef AFS_LINUX20_ENV
94 #include <fstab.h> /* Need to find in libc 5, present in libc 6 */
97 #endif /* AFS_SGI_ENV */
99 #endif /* AFS_HPUX_ENV */
103 #include <netinet/in.h>
104 #include <sys/wait.h>
107 #include <sys/time.h>
108 #endif /* ITIMER_REAL */
109 #endif /* AFS_NT40_ENV */
110 #if defined(AFS_SUN5_ENV) || defined(AFS_NT40_ENV) || defined(AFS_LINUX20_ENV)
117 #include <afs/errors.h>
120 #include <afs/afssyscalls.h>
122 #include <afs/afsutil.h>
126 #include "daemon_com.h"
128 #include "salvsync.h"
131 #include "partition.h"
132 #ifdef AFS_PTHREAD_ENV
134 #else /* AFS_PTHREAD_ENV */
135 #include "afs/assert.h"
136 #endif /* AFS_PTHREAD_ENV */
143 #if !defined(offsetof)
148 #define afs_stat stat64
149 #define afs_fstat fstat64
150 #define afs_open open64
151 #else /* !O_LARGEFILE */
152 #define afs_stat stat
153 #define afs_fstat fstat
154 #define afs_open open
155 #endif /* !O_LARGEFILE */
157 #ifdef AFS_PTHREAD_ENV
158 pthread_mutex_t vol_glock_mutex;
159 pthread_mutex_t vol_trans_mutex;
160 pthread_cond_t vol_put_volume_cond;
161 pthread_cond_t vol_sleep_cond;
162 int vol_attach_threads = 1;
163 #endif /* AFS_PTHREAD_ENV */
165 #ifdef AFS_DEMAND_ATTACH_FS
166 pthread_mutex_t vol_salvsync_mutex;
167 #endif /* AFS_DEMAND_ATTACH_FS */
170 extern void *calloc(), *realloc();
173 /*@printflike@*/ extern void Log(const char *format, ...);
175 /* Forward declarations */
176 static Volume *attach2(Error * ec, VolId vid, char *path,
177 register struct VolumeHeader *header,
178 struct DiskPartition *partp, Volume * vp,
179 int isbusy, int mode);
180 static void ReallyFreeVolume(Volume * vp);
181 #ifdef AFS_DEMAND_ATTACH_FS
182 static void FreeVolume(Volume * vp);
183 #else /* !AFS_DEMAND_ATTACH_FS */
184 #define FreeVolume(vp) ReallyFreeVolume(vp)
185 static void VScanUpdateList(void);
186 #endif /* !AFS_DEMAND_ATTACH_FS */
187 static void VInitVolumeHeaderCache(afs_uint32 howMany);
188 static int GetVolumeHeader(register Volume * vp);
189 static void ReleaseVolumeHeader(register struct volHeader *hd);
190 static void FreeVolumeHeader(register Volume * vp);
191 static void AddVolumeToHashTable(register Volume * vp, int hashid);
192 static void DeleteVolumeFromHashTable(register Volume * vp);
193 static int VHold(Volume * vp);
194 static int VHold_r(Volume * vp);
195 static void VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class);
196 static void GetVolumePath(Error * ec, VolId volumeId, char **partitionp,
198 static void VReleaseVolumeHandles_r(Volume * vp);
199 static void VCloseVolumeHandles_r(Volume * vp);
200 static void LoadVolumeHeader(Error * ec, Volume * vp);
201 static int VCheckOffline(register Volume * vp);
202 static int VCheckDetach(register Volume * vp);
203 static Volume * GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint, int flags);
204 static int VolumeExternalName_r(VolumeId volumeId, char * name, size_t len);
206 int LogLevel; /* Vice loglevel--not defined as extern so that it will be
207 * defined when not linked with vice, XXXX */
208 ProgramType programType; /* The type of program using the package */
211 /* extended volume package statistics */
215 #define VOLUME_BITMAP_GROWSIZE 16 /* bytes, => 128vnodes */
216 /* Must be a multiple of 4 (1 word) !! */
218 /* this parameter needs to be tunable at runtime.
219 * 128 was really inadequate for largish servers -- at 16384 volumes this
220 * puts average chain length at 128, thus an average 65 deref's to find a volptr.
221 * talk about bad spatial locality...
223 * an AVL or splay tree might work a lot better, but we'll just increase
224 * the default hash table size for now
226 #define DEFAULT_VOLUME_HASH_SIZE 256 /* Must be a power of 2!! */
227 #define DEFAULT_VOLUME_HASH_MASK (DEFAULT_VOLUME_HASH_SIZE-1)
228 #define VOLUME_HASH(volumeId) (volumeId&(VolumeHashTable.Mask))
231 * turn volume hash chains into partially ordered lists.
232 * when the threshold is exceeded between two adjacent elements,
233 * perform a chain rebalancing operation.
235 * keep the threshold high in order to keep cache line invalidates
236 * low "enough" on SMPs
238 #define VOLUME_HASH_REORDER_THRESHOLD 200
241 * when possible, don't just reorder single elements, but reorder
242 * entire chains of elements at once. a chain of elements that
243 * exceed the element previous to the pivot by at least CHAIN_THRESH
244 * accesses are moved in front of the chain whose elements have at
245 * least CHAIN_THRESH less accesses than the pivot element
247 #define VOLUME_HASH_REORDER_CHAIN_THRESH (VOLUME_HASH_REORDER_THRESHOLD / 2)
249 #include "rx/rx_queue.h"
252 VolumeHashTable_t VolumeHashTable = {
253 DEFAULT_VOLUME_HASH_SIZE,
254 DEFAULT_VOLUME_HASH_MASK,
259 static void VInitVolumeHash(void);
263 /* This macro is used where an ffs() call does not exist. Was in util/ffs.c */
267 afs_int32 ffs_tmp = x;
271 for (ffs_i = 1;; ffs_i++) {
278 #endif /* !AFS_HAVE_FFS */
280 #ifdef AFS_PTHREAD_ENV
281 typedef struct diskpartition_queue_t {
282 struct rx_queue queue;
283 struct DiskPartition * diskP;
284 } diskpartition_queue_t;
285 typedef struct vinitvolumepackage_thread_t {
286 struct rx_queue queue;
287 pthread_cond_t thread_done_cv;
288 int n_threads_complete;
289 } vinitvolumepackage_thread_t;
290 static void * VInitVolumePackageThread(void * args);
291 #endif /* AFS_PTHREAD_ENV */
293 static int VAttachVolumesByPartition(struct DiskPartition *diskP,
294 int * nAttached, int * nUnattached);
297 #ifdef AFS_DEMAND_ATTACH_FS
298 /* demand attach fileserver extensions */
301 * in the future we will support serialization of VLRU state into the fs_state
304 * these structures are the beginning of that effort
306 struct VLRU_DiskHeader {
307 struct versionStamp stamp; /* magic and structure version number */
308 afs_uint32 mtime; /* time of dump to disk */
309 afs_uint32 num_records; /* number of VLRU_DiskEntry records */
312 struct VLRU_DiskEntry {
313 afs_uint32 vid; /* volume ID */
314 afs_uint32 idx; /* generation */
315 afs_uint32 last_get; /* timestamp of last get */
318 struct VLRU_StartupQueue {
319 struct VLRU_DiskEntry * entry;
324 typedef struct vshutdown_thread_t {
326 pthread_mutex_t lock;
328 pthread_cond_t master_cv;
330 int n_threads_complete;
332 int schedule_version;
335 byte n_parts_done_pass;
336 byte part_thread_target[VOLMAXPARTS+1];
337 byte part_done_pass[VOLMAXPARTS+1];
338 struct rx_queue * part_pass_head[VOLMAXPARTS+1];
339 int stats[4][VOLMAXPARTS+1];
340 } vshutdown_thread_t;
341 static void * VShutdownThread(void * args);
344 static Volume * VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode);
345 static int VCheckFree(Volume * vp);
348 static void AddVolumeToVByPList_r(Volume * vp);
349 static void DeleteVolumeFromVByPList_r(Volume * vp);
350 static void VVByPListBeginExclusive_r(struct DiskPartition * dp);
351 static void VVByPListEndExclusive_r(struct DiskPartition * dp);
352 static void VVByPListWait_r(struct DiskPartition * dp);
354 /* online salvager */
355 static int VCheckSalvage(register Volume * vp);
356 static int VUpdateSalvagePriority_r(Volume * vp);
357 static int VScheduleSalvage_r(Volume * vp);
358 static int VCancelSalvage_r(Volume * vp, int reason);
360 /* Volume hash table */
361 static void VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp);
362 static void VHashBeginExclusive_r(VolumeHashChainHead * head);
363 static void VHashEndExclusive_r(VolumeHashChainHead * head);
364 static void VHashWait_r(VolumeHashChainHead * head);
366 /* Volume state machine */
367 static void VCreateReservation_r(Volume * vp);
368 static void VCancelReservation_r(Volume * vp);
369 static void VWaitStateChange_r(Volume * vp);
370 static void VWaitExclusiveState_r(Volume * vp);
371 static int IsExclusiveState(VolState state);
372 static int IsErrorState(VolState state);
373 static int IsValidState(VolState state);
376 static int ShutdownVByPForPass_r(struct DiskPartition * dp, int pass);
377 static int ShutdownVolumeWalk_r(struct DiskPartition * dp, int pass,
378 struct rx_queue ** idx);
379 static void ShutdownController(vshutdown_thread_t * params);
380 static void ShutdownCreateSchedule(vshutdown_thread_t * params);
383 static void VLRU_ComputeConstants(void);
384 static void VInitVLRU(void);
385 static void VLRU_Init_Node_r(volatile Volume * vp);
386 static void VLRU_Add_r(volatile Volume * vp);
387 static void VLRU_Delete_r(volatile Volume * vp);
388 static void VLRU_UpdateAccess_r(volatile Volume * vp);
389 static void * VLRU_ScannerThread(void * args);
390 static void VLRU_Scan_r(int idx);
391 static void VLRU_Promote_r(int idx);
392 static void VLRU_Demote_r(int idx);
393 static void VLRU_SwitchQueues(volatile Volume * vp, int new_idx, int append);
396 static int VCheckSoftDetach(volatile Volume * vp, afs_uint32 thresh);
397 static int VCheckSoftDetachCandidate(volatile Volume * vp, afs_uint32 thresh);
398 static int VSoftDetachVolume_r(volatile Volume * vp, afs_uint32 thresh);
399 #endif /* AFS_DEMAND_ATTACH_FS */
402 struct Lock vol_listLock; /* Lock obtained when listing volumes:
403 * prevents a volume from being missed
404 * if the volume is attached during a
408 static int TimeZoneCorrection; /* Number of seconds west of GMT */
410 /* Common message used when the volume goes off line */
411 char *VSalvageMessage =
412 "Files in this volume are currently unavailable; call operations";
414 int VInit; /* 0 - uninitialized,
415 * 1 - initialized but not all volumes have been attached,
416 * 2 - initialized and all volumes have been attached,
417 * 3 - initialized, all volumes have been attached, and
418 * VConnectFS() has completed. */
421 bit32 VolumeCacheCheck; /* Incremented everytime a volume goes on line--
422 * used to stamp volume headers and in-core
423 * vnodes. When the volume goes on-line the
424 * vnode will be invalidated
425 * access only with VOL_LOCK held */
430 /***************************************************/
431 /* Startup routines */
432 /***************************************************/
435 VInitVolumePackage(ProgramType pt, afs_uint32 nLargeVnodes, afs_uint32 nSmallVnodes,
436 int connect, afs_uint32 volcache)
438 int errors = 0; /* Number of errors while finding vice partitions. */
444 #ifdef AFS_DEMAND_ATTACH_FS
445 memset(&VStats, 0, sizeof(VStats));
446 VStats.hdr_cache_size = 200;
449 VInitPartitionPackage();
451 VInitVnHashByVolume();
452 #ifdef AFS_DEMAND_ATTACH_FS
453 if (programType == fileServer) {
456 VLRU_SetOptions(VLRU_SET_ENABLED, 0);
460 #ifdef AFS_PTHREAD_ENV
461 assert(pthread_mutex_init(&vol_glock_mutex, NULL) == 0);
462 assert(pthread_mutex_init(&vol_trans_mutex, NULL) == 0);
463 assert(pthread_cond_init(&vol_put_volume_cond, NULL) == 0);
464 assert(pthread_cond_init(&vol_sleep_cond, NULL) == 0);
465 #else /* AFS_PTHREAD_ENV */
467 #endif /* AFS_PTHREAD_ENV */
468 Lock_Init(&vol_listLock);
470 srandom(time(0)); /* For VGetVolumeInfo */
471 gettimeofday(&tv, &tz);
472 TimeZoneCorrection = tz.tz_minuteswest * 60;
474 #ifdef AFS_DEMAND_ATTACH_FS
475 assert(pthread_mutex_init(&vol_salvsync_mutex, NULL) == 0);
476 #endif /* AFS_DEMAND_ATTACH_FS */
478 /* Ok, we have done enough initialization that fileserver can
479 * start accepting calls, even though the volumes may not be
480 * available just yet.
484 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_SERVER)
485 if (programType == salvageServer) {
488 #endif /* AFS_DEMAND_ATTACH_FS */
489 #ifdef FSSYNC_BUILD_SERVER
490 if (programType == fileServer) {
494 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_CLIENT)
495 if (programType == fileServer) {
496 /* establish a connection to the salvager at this point */
497 assert(VConnectSALV() != 0);
499 #endif /* AFS_DEMAND_ATTACH_FS */
501 if (volcache > VStats.hdr_cache_size)
502 VStats.hdr_cache_size = volcache;
503 VInitVolumeHeaderCache(VStats.hdr_cache_size);
505 VInitVnodes(vLarge, nLargeVnodes);
506 VInitVnodes(vSmall, nSmallVnodes);
509 errors = VAttachPartitions();
513 if (programType == fileServer) {
514 struct DiskPartition *diskP;
515 #ifdef AFS_PTHREAD_ENV
516 struct vinitvolumepackage_thread_t params;
517 struct diskpartition_queue_t * dpq;
518 int i, threads, parts;
520 pthread_attr_t attrs;
522 assert(pthread_cond_init(¶ms.thread_done_cv,NULL) == 0);
524 params.n_threads_complete = 0;
526 /* create partition work queue */
527 for (parts=0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
528 dpq = (diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
531 queue_Prepend(¶ms,dpq);
534 threads = MIN(parts, vol_attach_threads);
537 /* spawn off a bunch of initialization threads */
538 assert(pthread_attr_init(&attrs) == 0);
539 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
541 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
542 #ifdef AFS_DEMAND_ATTACH_FS
543 Log("VInitVolumePackage: using %d threads to pre-attach volumes on %d partitions\n",
545 #else /* AFS_DEMAND_ATTACH_FS */
546 Log("VInitVolumePackage: using %d threads to attach volumes on %d partitions\n",
548 #endif /* AFS_DEMAND_ATTACH_FS */
551 for (i=0; i < threads; i++) {
552 assert(pthread_create
553 (&tid, &attrs, &VInitVolumePackageThread,
557 while(params.n_threads_complete < threads) {
558 pthread_cond_wait(¶ms.thread_done_cv,&vol_glock_mutex);
562 assert(pthread_attr_destroy(&attrs) == 0);
564 /* if we're only going to run one init thread, don't bother creating
566 Log("VInitVolumePackage: beginning single-threaded fileserver startup\n");
567 #ifdef AFS_DEMAND_ATTACH_FS
568 Log("VInitVolumePackage: using 1 thread to pre-attach volumes on %d partition(s)\n",
570 #else /* AFS_DEMAND_ATTACH_FS */
571 Log("VInitVolumePackage: using 1 thread to attach volumes on %d partition(s)\n",
573 #endif /* AFS_DEMAND_ATTACH_FS */
575 VInitVolumePackageThread(¶ms);
578 assert(pthread_cond_destroy(¶ms.thread_done_cv) == 0);
580 #else /* AFS_PTHREAD_ENV */
584 /* Attach all the volumes in this partition */
585 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
586 int nAttached = 0, nUnattached = 0;
587 assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
589 #endif /* AFS_PTHREAD_ENV */
592 VInit = 2; /* Initialized, and all volumes have been attached */
593 #ifdef FSSYNC_BUILD_CLIENT
594 if (programType == volumeUtility && connect) {
596 Log("Unable to connect to file server; aborted\n");
600 #ifdef AFS_DEMAND_ATTACH_FS
601 else if (programType == salvageServer) {
603 Log("Unable to connect to file server; aborted\n");
607 #endif /* AFS_DEMAND_ATTACH_FS */
608 #endif /* FSSYNC_BUILD_CLIENT */
612 #ifdef AFS_PTHREAD_ENV
614 VInitVolumePackageThread(void * args) {
615 int errors = 0; /* Number of errors while finding vice partitions. */
619 struct DiskPartition *diskP;
620 struct vinitvolumepackage_thread_t * params;
621 struct diskpartition_queue_t * dpq;
623 params = (vinitvolumepackage_thread_t *) args;
627 /* Attach all the volumes in this partition */
628 while (queue_IsNotEmpty(params)) {
629 int nAttached = 0, nUnattached = 0;
631 dpq = queue_First(params,diskpartition_queue_t);
637 assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
642 params->n_threads_complete++;
643 pthread_cond_signal(¶ms->thread_done_cv);
647 #endif /* AFS_PTHREAD_ENV */
650 * attach all volumes on a given disk partition
653 VAttachVolumesByPartition(struct DiskPartition *diskP, int * nAttached, int * nUnattached)
659 Log("Partition %s: attaching volumes\n", diskP->name);
660 dirp = opendir(VPartitionPath(diskP));
662 Log("opendir on Partition %s failed!\n", diskP->name);
666 while ((dp = readdir(dirp))) {
668 p = strrchr(dp->d_name, '.');
669 if (p != NULL && strcmp(p, VHDREXT) == 0) {
672 #ifdef AFS_DEMAND_ATTACH_FS
673 vp = VPreAttachVolumeByName(&error, diskP->name, dp->d_name,
675 #else /* AFS_DEMAND_ATTACH_FS */
676 vp = VAttachVolumeByName(&error, diskP->name, dp->d_name,
678 #endif /* AFS_DEMAND_ATTACH_FS */
679 (*(vp ? nAttached : nUnattached))++;
680 if (error == VOFFLINE)
681 Log("Volume %d stays offline (/vice/offline/%s exists)\n", VolumeNumber(dp->d_name), dp->d_name);
682 else if (LogLevel >= 5) {
683 Log("Partition %s: attached volume %d (%s)\n",
684 diskP->name, VolumeNumber(dp->d_name),
687 #if !defined(AFS_DEMAND_ATTACH_FS)
691 #endif /* AFS_DEMAND_ATTACH_FS */
695 Log("Partition %s: attached %d volumes; %d volumes not attached\n", diskP->name, *nAttached, *nUnattached);
701 /***************************************************/
702 /* Shutdown routines */
703 /***************************************************/
707 * highly multithreaded volume package shutdown
709 * with the demand attach fileserver extensions,
710 * VShutdown has been modified to be multithreaded.
711 * In order to achieve optimal use of many threads,
712 * the shutdown code involves one control thread and
713 * n shutdown worker threads. The control thread
714 * periodically examines the number of volumes available
715 * for shutdown on each partition, and produces a worker
716 * thread allocation schedule. The idea is to eliminate
717 * redundant scheduling computation on the workers by
718 * having a single master scheduler.
720 * The scheduler's objectives are:
722 * each partition with volumes remaining gets allocated
723 * at least 1 thread (assuming sufficient threads)
725 * threads are allocated proportional to the number of
726 * volumes remaining to be offlined. This ensures that
727 * the OS I/O scheduler has many requests to elevator
728 * seek on partitions that will (presumably) take the
729 * longest amount of time (from now) to finish shutdown
730 * (3) keep threads busy
731 * when there are extra threads, they are assigned to
732 * partitions using a simple round-robin algorithm
734 * In the future, we may wish to add the ability to adapt
735 * to the relative performance patterns of each disk
740 * multi-step shutdown process
742 * demand attach shutdown is a four-step process. Each
743 * shutdown "pass" shuts down increasingly more difficult
744 * volumes. The main purpose is to achieve better cache
745 * utilization during shutdown.
748 * shutdown volumes in the unattached, pre-attached
751 * shutdown attached volumes with cached volume headers
753 * shutdown all volumes in non-exclusive states
755 * shutdown all remaining volumes
762 register Volume *vp, *np;
763 register afs_int32 code;
764 #ifdef AFS_DEMAND_ATTACH_FS
765 struct DiskPartition * diskP;
766 struct diskpartition_queue_t * dpq;
767 vshutdown_thread_t params;
769 pthread_attr_t attrs;
771 memset(¶ms, 0, sizeof(vshutdown_thread_t));
773 for (params.n_parts=0, diskP = DiskPartitionList;
774 diskP; diskP = diskP->next, params.n_parts++);
776 Log("VShutdown: shutting down on-line volumes on %d partition%s...\n",
777 params.n_parts, params.n_parts > 1 ? "s" : "");
779 if (vol_attach_threads > 1) {
780 /* prepare for parallel shutdown */
781 params.n_threads = vol_attach_threads;
782 assert(pthread_mutex_init(¶ms.lock, NULL) == 0);
783 assert(pthread_cond_init(¶ms.cv, NULL) == 0);
784 assert(pthread_cond_init(¶ms.master_cv, NULL) == 0);
785 assert(pthread_attr_init(&attrs) == 0);
786 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
789 /* setup the basic partition information structures for
790 * parallel shutdown */
791 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
793 struct rx_queue * qp, * nqp;
797 VVByPListWait_r(diskP);
798 VVByPListBeginExclusive_r(diskP);
801 for (queue_Scan(&diskP->vol_list, qp, nqp, rx_queue)) {
802 vp = (Volume *)((char *)qp - offsetof(Volume, vol_list));
806 Log("VShutdown: partition %s has %d volumes with attached headers\n",
807 VPartitionPath(diskP), count);
810 /* build up the pass 0 shutdown work queue */
811 dpq = (struct diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
814 queue_Prepend(¶ms, dpq);
816 params.part_pass_head[diskP->device] = queue_First(&diskP->vol_list, rx_queue);
819 Log("VShutdown: beginning parallel fileserver shutdown\n");
820 Log("VShutdown: using %d threads to offline volumes on %d partition%s\n",
821 vol_attach_threads, params.n_parts, params.n_parts > 1 ? "s" : "" );
823 /* do pass 0 shutdown */
824 assert(pthread_mutex_lock(¶ms.lock) == 0);
825 for (i=0; i < params.n_threads; i++) {
826 assert(pthread_create
827 (&tid, &attrs, &VShutdownThread,
831 /* wait for all the pass 0 shutdowns to complete */
832 while (params.n_threads_complete < params.n_threads) {
833 assert(pthread_cond_wait(¶ms.master_cv, ¶ms.lock) == 0);
835 params.n_threads_complete = 0;
837 assert(pthread_cond_broadcast(¶ms.cv) == 0);
838 assert(pthread_mutex_unlock(¶ms.lock) == 0);
840 Log("VShutdown: pass 0 completed using the 1 thread per partition algorithm\n");
841 Log("VShutdown: starting passes 1 through 3 using finely-granular mp-fast algorithm\n");
843 /* run the parallel shutdown scheduler. it will drop the glock internally */
844 ShutdownController(¶ms);
846 /* wait for all the workers to finish pass 3 and terminate */
847 while (params.pass < 4) {
848 assert(pthread_cond_wait(¶ms.cv, &vol_glock_mutex) == 0);
851 assert(pthread_attr_destroy(&attrs) == 0);
852 assert(pthread_cond_destroy(¶ms.cv) == 0);
853 assert(pthread_cond_destroy(¶ms.master_cv) == 0);
854 assert(pthread_mutex_destroy(¶ms.lock) == 0);
856 /* drop the VByPList exclusive reservations */
857 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
858 VVByPListEndExclusive_r(diskP);
859 Log("VShutdown: %s stats : (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
860 VPartitionPath(diskP),
861 params.stats[0][diskP->device],
862 params.stats[1][diskP->device],
863 params.stats[2][diskP->device],
864 params.stats[3][diskP->device]);
867 Log("VShutdown: shutdown finished using %d threads\n", params.n_threads);
869 /* if we're only going to run one shutdown thread, don't bother creating
871 Log("VShutdown: beginning single-threaded fileserver shutdown\n");
873 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
874 VShutdownByPartition_r(diskP);
878 Log("VShutdown: complete.\n");
879 #else /* AFS_DEMAND_ATTACH_FS */
880 Log("VShutdown: shutting down on-line volumes...\n");
881 for (i = 0; i < VolumeHashTable.Size; i++) {
882 /* try to hold first volume in the hash table */
883 for (queue_Scan(&VolumeHashTable.Table[i],vp,np,Volume)) {
887 Log("VShutdown: Attempting to take volume %u offline.\n",
890 /* next, take the volume offline (drops reference count) */
891 VOffline_r(vp, "File server was shut down");
895 Log("VShutdown: complete.\n");
896 #endif /* AFS_DEMAND_ATTACH_FS */
907 #ifdef AFS_DEMAND_ATTACH_FS
910 * shutdown control thread
913 ShutdownController(vshutdown_thread_t * params)
916 struct DiskPartition * diskP;
918 vshutdown_thread_t shadow;
920 ShutdownCreateSchedule(params);
922 while ((params->pass < 4) &&
923 (params->n_threads_complete < params->n_threads)) {
924 /* recompute schedule once per second */
926 memcpy(&shadow, params, sizeof(vshutdown_thread_t));
930 Log("ShutdownController: schedule version=%d, vol_remaining=%d, pass=%d\n",
931 shadow.schedule_version, shadow.vol_remaining, shadow.pass);
932 Log("ShutdownController: n_threads_complete=%d, n_parts_done_pass=%d\n",
933 shadow.n_threads_complete, shadow.n_parts_done_pass);
934 for (diskP = DiskPartitionList; diskP; diskP=diskP->next) {
936 Log("ShutdownController: part[%d] : (len=%d, thread_target=%d, done_pass=%d, pass_head=%p)\n",
939 shadow.part_thread_target[id],
940 shadow.part_done_pass[id],
941 shadow.part_pass_head[id]);
947 ShutdownCreateSchedule(params);
951 /* create the shutdown thread work schedule.
952 * this scheduler tries to implement fairness
953 * by allocating at least 1 thread to each
954 * partition with volumes to be shutdown,
955 * and then it attempts to allocate remaining
956 * threads based upon the amount of work left
959 ShutdownCreateSchedule(vshutdown_thread_t * params)
961 struct DiskPartition * diskP;
962 int sum, thr_workload, thr_left;
963 int part_residue[VOLMAXPARTS+1];
966 /* compute the total number of outstanding volumes */
968 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
969 sum += diskP->vol_list.len;
972 params->schedule_version++;
973 params->vol_remaining = sum;
978 /* compute average per-thread workload */
979 thr_workload = sum / params->n_threads;
980 if (sum % params->n_threads)
983 thr_left = params->n_threads;
984 memset(&part_residue, 0, sizeof(part_residue));
986 /* for fairness, give every partition with volumes remaining
987 * at least one thread */
988 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
990 if (diskP->vol_list.len) {
991 params->part_thread_target[id] = 1;
994 params->part_thread_target[id] = 0;
998 if (thr_left && thr_workload) {
999 /* compute length-weighted workloads */
1002 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1004 delta = (diskP->vol_list.len / thr_workload) -
1005 params->part_thread_target[id];
1009 if (delta < thr_left) {
1010 params->part_thread_target[id] += delta;
1013 params->part_thread_target[id] += thr_left;
1021 /* try to assign any leftover threads to partitions that
1022 * had volume lengths closer to needing thread_target+1 */
1023 int max_residue, max_id;
1025 /* compute the residues */
1026 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1028 part_residue[id] = diskP->vol_list.len -
1029 (params->part_thread_target[id] * thr_workload);
1032 /* now try to allocate remaining threads to partitions with the
1033 * highest residues */
1036 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1038 if (part_residue[id] > max_residue) {
1039 max_residue = part_residue[id];
1048 params->part_thread_target[max_id]++;
1050 part_residue[max_id] = 0;
1055 /* punt and give any remaining threads equally to each partition */
1057 if (thr_left >= params->n_parts) {
1058 alloc = thr_left / params->n_parts;
1059 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1061 params->part_thread_target[id] += alloc;
1066 /* finish off the last of the threads */
1067 for (diskP = DiskPartitionList; thr_left && diskP; diskP = diskP->next) {
1069 params->part_thread_target[id]++;
1075 /* worker thread for parallel shutdown */
1077 VShutdownThread(void * args)
1079 struct rx_queue *qp;
1081 vshutdown_thread_t * params;
1082 int part, code, found, pass, schedule_version_save, count;
1083 struct DiskPartition *diskP;
1084 struct diskpartition_queue_t * dpq;
1087 params = (vshutdown_thread_t *) args;
1089 /* acquire the shutdown pass 0 lock */
1090 assert(pthread_mutex_lock(¶ms->lock) == 0);
1092 /* if there's still pass 0 work to be done,
1093 * get a work entry, and do a pass 0 shutdown */
1094 if (queue_IsNotEmpty(params)) {
1095 dpq = queue_First(params, diskpartition_queue_t);
1097 assert(pthread_mutex_unlock(¶ms->lock) == 0);
1103 while (ShutdownVolumeWalk_r(diskP, 0, ¶ms->part_pass_head[id]))
1105 params->stats[0][diskP->device] = count;
1106 assert(pthread_mutex_lock(¶ms->lock) == 0);
1109 params->n_threads_complete++;
1110 if (params->n_threads_complete == params->n_threads) {
1111 /* notify control thread that all workers have completed pass 0 */
1112 assert(pthread_cond_signal(¶ms->master_cv) == 0);
1114 while (params->pass == 0) {
1115 assert(pthread_cond_wait(¶ms->cv, ¶ms->lock) == 0);
1119 assert(pthread_mutex_unlock(¶ms->lock) == 0);
1122 pass = params->pass;
1125 /* now escalate through the more complicated shutdowns */
1127 schedule_version_save = params->schedule_version;
1129 /* find a disk partition to work on */
1130 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1132 if (params->part_thread_target[id] && !params->part_done_pass[id]) {
1133 params->part_thread_target[id]--;
1140 /* hmm. for some reason the controller thread couldn't find anything for
1141 * us to do. let's see if there's anything we can do */
1142 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1144 if (diskP->vol_list.len && !params->part_done_pass[id]) {
1147 } else if (!params->part_done_pass[id]) {
1148 params->part_done_pass[id] = 1;
1149 params->n_parts_done_pass++;
1151 Log("VShutdown: done shutting down volumes on partition %s.\n",
1152 VPartitionPath(diskP));
1158 /* do work on this partition until either the controller
1159 * creates a new schedule, or we run out of things to do
1160 * on this partition */
1163 while (!params->part_done_pass[id] &&
1164 (schedule_version_save == params->schedule_version)) {
1165 /* ShutdownVolumeWalk_r will drop the glock internally */
1166 if (!ShutdownVolumeWalk_r(diskP, pass, ¶ms->part_pass_head[id])) {
1167 if (!params->part_done_pass[id]) {
1168 params->part_done_pass[id] = 1;
1169 params->n_parts_done_pass++;
1171 Log("VShutdown: done shutting down volumes on partition %s.\n",
1172 VPartitionPath(diskP));
1180 params->stats[pass][id] += count;
1182 /* ok, everyone is done this pass, proceed */
1185 params->n_threads_complete++;
1186 while (params->pass == pass) {
1187 if (params->n_threads_complete == params->n_threads) {
1188 /* we are the last thread to complete, so we will
1189 * reinitialize worker pool state for the next pass */
1190 params->n_threads_complete = 0;
1191 params->n_parts_done_pass = 0;
1193 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1195 params->part_done_pass[id] = 0;
1196 params->part_pass_head[id] = queue_First(&diskP->vol_list, rx_queue);
1199 /* compute a new thread schedule before releasing all the workers */
1200 ShutdownCreateSchedule(params);
1202 /* wake up all the workers */
1203 assert(pthread_cond_broadcast(¶ms->cv) == 0);
1206 Log("VShutdown: pass %d completed using %d threads on %d partitions\n",
1207 pass, params->n_threads, params->n_parts);
1210 assert(pthread_cond_wait(¶ms->cv, &vol_glock_mutex) == 0);
1213 pass = params->pass;
1227 /* shut down all volumes on a given disk partition
1229 * note that this function will not allow mp-fast
1230 * shutdown of a partition */
1232 VShutdownByPartition_r(struct DiskPartition * dp)
1238 /* wait for other exclusive ops to finish */
1239 VVByPListWait_r(dp);
1241 /* begin exclusive access */
1242 VVByPListBeginExclusive_r(dp);
1244 /* pick the low-hanging fruit first,
1245 * then do the complicated ones last
1246 * (has the advantage of keeping
1247 * in-use volumes up until the bitter end) */
1248 for (pass = 0, total=0; pass < 4; pass++) {
1249 pass_stats[pass] = ShutdownVByPForPass_r(dp, pass);
1250 total += pass_stats[pass];
1253 /* end exclusive access */
1254 VVByPListEndExclusive_r(dp);
1256 Log("VShutdownByPartition: shut down %d volumes on %s (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1257 total, VPartitionPath(dp), pass_stats[0], pass_stats[1], pass_stats[2], pass_stats[3]);
1262 /* internal shutdown functionality
1264 * for multi-pass shutdown:
1265 * 0 to only "shutdown" {pre,un}attached and error state volumes
1266 * 1 to also shutdown attached volumes w/ volume header loaded
1267 * 2 to also shutdown attached volumes w/o volume header loaded
1268 * 3 to also shutdown exclusive state volumes
1270 * caller MUST hold exclusive access on the hash chain
1271 * because we drop vol_glock_mutex internally
1273 * this function is reentrant for passes 1--3
1274 * (e.g. multiple threads can cooperate to
1275 * shutdown a partition mp-fast)
1277 * pass 0 is not scaleable because the volume state data is
1278 * synchronized by vol_glock mutex, and the locking overhead
1279 * is too high to drop the lock long enough to do linked list
1283 ShutdownVByPForPass_r(struct DiskPartition * dp, int pass)
1285 struct rx_queue * q = queue_First(&dp->vol_list, rx_queue);
1288 while (ShutdownVolumeWalk_r(dp, pass, &q))
1294 /* conditionally shutdown one volume on partition dp
1295 * returns 1 if a volume was shutdown in this pass,
1298 ShutdownVolumeWalk_r(struct DiskPartition * dp, int pass,
1299 struct rx_queue ** idx)
1301 struct rx_queue *qp, *nqp;
1306 for (queue_ScanFrom(&dp->vol_list, qp, qp, nqp, rx_queue)) {
1307 vp = (Volume *) (((char *)qp) - offsetof(Volume, vol_list));
1311 if ((V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1312 (V_attachState(vp) != VOL_STATE_ERROR) &&
1313 (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1317 if ((V_attachState(vp) == VOL_STATE_ATTACHED) &&
1318 (vp->header == NULL)) {
1322 if (IsExclusiveState(V_attachState(vp))) {
1327 DeleteVolumeFromVByPList_r(vp);
1328 VShutdownVolume_r(vp);
1338 * shutdown a specific volume
1340 /* caller MUST NOT hold a heavyweight ref on vp */
1342 VShutdownVolume_r(Volume * vp)
1346 VCreateReservation_r(vp);
1348 if (LogLevel >= 5) {
1349 Log("VShutdownVolume_r: vid=%u, device=%d, state=%hu\n",
1350 vp->hashid, vp->partition->device, V_attachState(vp));
1353 /* wait for other blocking ops to finish */
1354 VWaitExclusiveState_r(vp);
1356 assert(IsValidState(V_attachState(vp)));
1358 switch(V_attachState(vp)) {
1359 case VOL_STATE_SALVAGING:
1360 /* make sure salvager knows we don't want
1361 * the volume back */
1362 VCancelSalvage_r(vp, SALVSYNC_SHUTDOWN);
1363 case VOL_STATE_PREATTACHED:
1364 case VOL_STATE_ERROR:
1365 VChangeState_r(vp, VOL_STATE_UNATTACHED);
1366 case VOL_STATE_UNATTACHED:
1368 case VOL_STATE_GOING_OFFLINE:
1369 case VOL_STATE_SHUTTING_DOWN:
1370 case VOL_STATE_ATTACHED:
1374 Log("VShutdown: Attempting to take volume %u offline.\n",
1377 /* take the volume offline (drops reference count) */
1378 VOffline_r(vp, "File server was shut down");
1383 VCancelReservation_r(vp);
1387 #endif /* AFS_DEMAND_ATTACH_FS */
1390 /***************************************************/
1391 /* Header I/O routines */
1392 /***************************************************/
1394 /* open a descriptor for the inode (h),
1395 * read in an on-disk structure into buffer (to) of size (size),
1396 * verify versionstamp in structure has magic (magic) and
1397 * optionally verify version (version) if (version) is nonzero
1400 ReadHeader(Error * ec, IHandle_t * h, char *to, int size, bit32 magic,
1403 struct versionStamp *vsn;
1418 if (FDH_SEEK(fdP, 0, SEEK_SET) < 0) {
1420 FDH_REALLYCLOSE(fdP);
1423 vsn = (struct versionStamp *)to;
1424 if (FDH_READ(fdP, to, size) != size || vsn->magic != magic) {
1426 FDH_REALLYCLOSE(fdP);
1431 /* Check is conditional, in case caller wants to inspect version himself */
1432 if (version && vsn->version != version) {
1438 WriteVolumeHeader_r(Error * ec, Volume * vp)
1440 IHandle_t *h = V_diskDataHandle(vp);
1450 if (FDH_SEEK(fdP, 0, SEEK_SET) < 0) {
1452 FDH_REALLYCLOSE(fdP);
1455 if (FDH_WRITE(fdP, (char *)&V_disk(vp), sizeof(V_disk(vp)))
1456 != sizeof(V_disk(vp))) {
1458 FDH_REALLYCLOSE(fdP);
1464 /* VolumeHeaderToDisk
1465 * Allows for storing 64 bit inode numbers in on-disk volume header
1468 /* convert in-memory representation of a volume header to the
1469 * on-disk representation of a volume header */
1471 VolumeHeaderToDisk(VolumeDiskHeader_t * dh, VolumeHeader_t * h)
1474 memset((char *)dh, 0, sizeof(VolumeDiskHeader_t));
1475 dh->stamp = h->stamp;
1477 dh->parent = h->parent;
1479 #ifdef AFS_64BIT_IOPS_ENV
1480 dh->volumeInfo_lo = (afs_int32) h->volumeInfo & 0xffffffff;
1481 dh->volumeInfo_hi = (afs_int32) (h->volumeInfo >> 32) & 0xffffffff;
1482 dh->smallVnodeIndex_lo = (afs_int32) h->smallVnodeIndex & 0xffffffff;
1483 dh->smallVnodeIndex_hi =
1484 (afs_int32) (h->smallVnodeIndex >> 32) & 0xffffffff;
1485 dh->largeVnodeIndex_lo = (afs_int32) h->largeVnodeIndex & 0xffffffff;
1486 dh->largeVnodeIndex_hi =
1487 (afs_int32) (h->largeVnodeIndex >> 32) & 0xffffffff;
1488 dh->linkTable_lo = (afs_int32) h->linkTable & 0xffffffff;
1489 dh->linkTable_hi = (afs_int32) (h->linkTable >> 32) & 0xffffffff;
1491 dh->volumeInfo_lo = h->volumeInfo;
1492 dh->smallVnodeIndex_lo = h->smallVnodeIndex;
1493 dh->largeVnodeIndex_lo = h->largeVnodeIndex;
1494 dh->linkTable_lo = h->linkTable;
1498 /* DiskToVolumeHeader
1499 * Converts an on-disk representation of a volume header to
1500 * the in-memory representation of a volume header.
1502 * Makes the assumption that AFS has *always*
1503 * zero'd the volume header file so that high parts of inode
1504 * numbers are 0 in older (SGI EFS) volume header files.
1507 DiskToVolumeHeader(VolumeHeader_t * h, VolumeDiskHeader_t * dh)
1509 memset((char *)h, 0, sizeof(VolumeHeader_t));
1510 h->stamp = dh->stamp;
1512 h->parent = dh->parent;
1514 #ifdef AFS_64BIT_IOPS_ENV
1516 (Inode) dh->volumeInfo_lo | ((Inode) dh->volumeInfo_hi << 32);
1518 h->smallVnodeIndex =
1519 (Inode) dh->smallVnodeIndex_lo | ((Inode) dh->
1520 smallVnodeIndex_hi << 32);
1522 h->largeVnodeIndex =
1523 (Inode) dh->largeVnodeIndex_lo | ((Inode) dh->
1524 largeVnodeIndex_hi << 32);
1526 (Inode) dh->linkTable_lo | ((Inode) dh->linkTable_hi << 32);
1528 h->volumeInfo = dh->volumeInfo_lo;
1529 h->smallVnodeIndex = dh->smallVnodeIndex_lo;
1530 h->largeVnodeIndex = dh->largeVnodeIndex_lo;
1531 h->linkTable = dh->linkTable_lo;
1536 /***************************************************/
1537 /* Volume Attachment routines */
1538 /***************************************************/
1540 #ifdef AFS_DEMAND_ATTACH_FS
1541 /* pre-attach a volume given its path
1543 * a pre-attached volume will only have its partition
1544 * and hashid fields initialized
1546 * at first call to VGetVolume, the volume will be
1550 VPreAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
1554 vp = VPreAttachVolumeByName_r(ec, partition, name, mode);
1560 VPreAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
1562 register Volume *vp = NULL;
1564 struct afs_stat status;
1565 struct DiskPartition *partp;
1571 assert(programType == fileServer);
1573 if (!(partp = VGetPartition_r(partition, 0))) {
1575 Log("VPreAttachVolume: Error getting partition (%s)\n", partition);
1579 volumeId = VolumeNumber(name);
1581 vp = VLookupVolume_r(ec, volumeId, NULL);
1586 return VPreAttachVolumeById_r(ec, partp, vp, volumeId);
1589 /* pre-attach a volume given its partition and volume id
1591 * if vp == NULL, then a new vp is created
1592 * if vp != NULL, then we assumed it is already on the hash chain
1595 VPreAttachVolumeById_r(Error * ec, struct DiskPartition * partp,
1596 Volume * vp, int vid)
1602 /* check to see if pre-attach already happened */
1604 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1605 !IsErrorState(V_attachState(vp))) {
1608 /* we're re-attaching a volume; clear out some old state */
1609 memset(&vp->salvage, 0, sizeof(struct VolumeOnlineSalvage));
1611 /* if we need to allocate a new Volume struct,
1612 * go ahead and drop the vol glock, otherwise
1613 * do the basic setup synchronised, as it's
1614 * probably not worth dropping the lock */
1617 /* allocate the volume structure */
1618 vp = nvp = (Volume *) malloc(sizeof(Volume));
1620 memset(vp, 0, sizeof(Volume));
1621 assert(pthread_cond_init(&V_attachCV(vp), NULL) == 0);
1624 /* link the volume with its associated vice partition */
1625 vp->device = partp->device;
1626 vp->partition = partp;
1629 /* if we dropped the lock, reacquire the lock,
1630 * check for pre-attach races, and then add
1631 * the volume to the hash table */
1634 nvp = VLookupVolume_r(ec, vid, NULL);
1639 } else if (nvp) { /* race detected */
1644 /* hack to make up for VChangeState_r() decrementing
1645 * the old state counter */
1646 VStats.state_levels[0]++;
1650 /* put pre-attached volume onto the hash table
1651 * and bring it up to the pre-attached state */
1652 AddVolumeToHashTable(vp, vp->hashid);
1653 AddVolumeToVByPList_r(vp);
1654 VLRU_Init_Node_r(vp);
1655 VChangeState_r(vp, VOL_STATE_PREATTACHED);
1658 Log("VPreAttachVolumeById_r: volume %u pre-attached\n", vp->hashid);
1666 #endif /* AFS_DEMAND_ATTACH_FS */
1668 /* Attach an existing volume, given its pathname, and return a
1669 pointer to the volume header information. The volume also
1670 normally goes online at this time. An offline volume
1671 must be reattached to make it go online */
1673 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
1677 retVal = VAttachVolumeByName_r(ec, partition, name, mode);
1683 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
1685 register Volume *vp = NULL, *svp = NULL;
1687 struct afs_stat status;
1688 struct VolumeDiskHeader diskHeader;
1689 struct VolumeHeader iheader;
1690 struct DiskPartition *partp;
1694 #ifdef AFS_DEMAND_ATTACH_FS
1695 VolumeStats stats_save;
1696 #endif /* AFS_DEMAND_ATTACH_FS */
1700 volumeId = VolumeNumber(name);
1702 if (!(partp = VGetPartition_r(partition, 0))) {
1704 Log("VAttachVolume: Error getting partition (%s)\n", partition);
1708 if (programType == volumeUtility) {
1710 VLockPartition_r(partition);
1711 } else if (programType == fileServer) {
1712 #ifdef AFS_DEMAND_ATTACH_FS
1713 /* lookup the volume in the hash table */
1714 vp = VLookupVolume_r(ec, volumeId, NULL);
1720 /* save any counters that are supposed to
1721 * be monotonically increasing over the
1722 * lifetime of the fileserver */
1723 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
1725 memset(&stats_save, 0, sizeof(VolumeStats));
1728 /* if there's something in the hash table, and it's not
1729 * in the pre-attach state, then we may need to detach
1730 * it before proceeding */
1731 if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1732 VCreateReservation_r(vp);
1733 VWaitExclusiveState_r(vp);
1735 /* at this point state must be one of:
1744 if (vp->specialStatus == VBUSY)
1747 /* if it's already attached, see if we can return it */
1748 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
1749 VGetVolumeByVp_r(ec, vp);
1751 VCancelReservation_r(vp);
1755 /* otherwise, we need to detach, and attempt to re-attach */
1756 VDetachVolume_r(ec, vp);
1758 Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
1761 /* if it isn't fully attached, delete from the hash tables,
1762 and let the refcounter handle the rest */
1763 DeleteVolumeFromHashTable(vp);
1764 DeleteVolumeFromVByPList_r(vp);
1767 VCancelReservation_r(vp);
1771 /* pre-attach volume if it hasn't been done yet */
1773 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
1774 (V_attachState(vp) == VOL_STATE_ERROR)) {
1776 vp = VPreAttachVolumeById_r(ec, partp, vp, volumeId);
1784 /* handle pre-attach races
1786 * multiple threads can race to pre-attach a volume,
1787 * but we can't let them race beyond that
1789 * our solution is to let the first thread to bring
1790 * the volume into an exclusive state win; the other
1791 * threads just wait until it finishes bringing the
1792 * volume online, and then they do a vgetvolumebyvp
1794 if (svp && (svp != vp)) {
1795 /* wait for other exclusive ops to finish */
1796 VCreateReservation_r(vp);
1797 VWaitExclusiveState_r(vp);
1799 /* get a heavyweight ref, kill the lightweight ref, and return */
1800 VGetVolumeByVp_r(ec, vp);
1801 VCancelReservation_r(vp);
1805 /* at this point, we are chosen as the thread to do
1806 * demand attachment for this volume. all other threads
1807 * doing a getvolume on vp->hashid will block until we finish */
1809 /* make sure any old header cache entries are invalidated
1810 * before proceeding */
1811 FreeVolumeHeader(vp);
1813 VChangeState_r(vp, VOL_STATE_ATTACHING);
1815 /* restore any saved counters */
1816 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
1817 #else /* AFS_DEMAND_ATTACH_FS */
1818 vp = VGetVolume_r(ec, volumeId);
1822 if (vp->specialStatus == VBUSY)
1824 VDetachVolume_r(ec, vp);
1826 Log("VAttachVolume: Error detaching volume (%s)\n", name);
1830 #endif /* AFS_DEMAND_ATTACH_FS */
1834 strcpy(path, VPartitionPath(partp));
1840 if ((fd = afs_open(path, O_RDONLY)) == -1 || afs_fstat(fd, &status) == -1) {
1841 Log("VAttachVolume: Failed to open %s (errno %d)\n", path, errno);
1848 n = read(fd, &diskHeader, sizeof(diskHeader));
1850 if (n != sizeof(diskHeader)
1851 || diskHeader.stamp.magic != VOLUMEHEADERMAGIC) {
1852 Log("VAttachVolume: Error reading volume header %s\n", path);
1857 if (diskHeader.stamp.version != VOLUMEHEADERVERSION) {
1858 Log("VAttachVolume: Volume %s, version number is incorrect; volume needs salvaged\n", path);
1864 DiskToVolumeHeader(&iheader, &diskHeader);
1865 #ifdef FSSYNC_BUILD_CLIENT
1866 if (programType == volumeUtility && mode != V_SECRETLY && mode != V_PEEK) {
1868 if (FSYNC_VolOp(iheader.id, partition, FSYNC_VOL_NEEDVOLUME, mode, NULL)
1870 Log("VAttachVolume: attach of volume %u apparently denied by file server\n", iheader.id);
1871 *ec = VNOVOL; /* XXXX */
1879 vp = (Volume *) calloc(1, sizeof(Volume));
1881 vp->device = partp->device;
1882 vp->partition = partp;
1883 #ifdef AFS_DEMAND_ATTACH_FS
1884 assert(pthread_cond_init(&V_attachCV(vp), NULL) == 0);
1885 #endif /* AFS_DEMAND_ATTACH_FS */
1888 /* attach2 is entered without any locks, and returns
1889 * with vol_glock_mutex held */
1890 vp = attach2(ec, volumeId, path, &iheader, partp, vp, isbusy, mode);
1892 if (programType == volumeUtility && vp) {
1893 #ifdef AFS_DEMAND_ATTACH_FS
1894 /* for dafs, we should tell the fileserver, except for V_PEEK
1895 * where we know it is not necessary */
1896 if (mode == V_PEEK) {
1897 vp->needsPutBack = 0;
1899 vp->needsPutBack = 1;
1901 #else /* !AFS_DEMAND_ATTACH_FS */
1902 /* duplicate computation in fssync.c about whether the server
1903 * takes the volume offline or not. If the volume isn't
1904 * offline, we must not return it when we detach the volume,
1905 * or the server will abort */
1906 if (mode == V_READONLY || mode == V_PEEK
1907 || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
1908 vp->needsPutBack = 0;
1910 vp->needsPutBack = 1;
1911 #endif /* !AFS_DEMAND_ATTACH_FS */
1913 /* OK, there's a problem here, but one that I don't know how to
1914 * fix right now, and that I don't think should arise often.
1915 * Basically, we should only put back this volume to the server if
1916 * it was given to us by the server, but since we don't have a vp,
1917 * we can't run the VolumeWriteable function to find out as we do
1918 * above when computing vp->needsPutBack. So we send it back, but
1919 * there's a path in VAttachVolume on the server which may abort
1920 * if this volume doesn't have a header. Should be pretty rare
1921 * for all of that to happen, but if it does, probably the right
1922 * fix is for the server to allow the return of readonly volumes
1923 * that it doesn't think are really checked out. */
1924 #ifdef FSSYNC_BUILD_CLIENT
1925 if (programType == volumeUtility && vp == NULL &&
1926 mode != V_SECRETLY && mode != V_PEEK) {
1927 FSYNC_VolOp(iheader.id, partition, FSYNC_VOL_ON, 0, NULL);
1930 if (programType == fileServer && vp) {
1931 V_needsCallback(vp) = 0;
1933 if (VInit >= 2 && V_BreakVolumeCallbacks) {
1934 Log("VAttachVolume: Volume %u was changed externally; breaking callbacks\n", V_id(vp));
1935 (*V_BreakVolumeCallbacks) (V_id(vp));
1938 VUpdateVolume_r(ec, vp, 0);
1940 Log("VAttachVolume: Error updating volume\n");
1945 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
1946 #ifndef AFS_DEMAND_ATTACH_FS
1947 /* This is a hack: by temporarily setting the incore
1948 * dontSalvage flag ON, the volume will be put back on the
1949 * Update list (with dontSalvage OFF again). It will then
1950 * come back in N minutes with DONT_SALVAGE eventually
1951 * set. This is the way that volumes that have never had
1952 * it set get it set; or that volumes that have been
1953 * offline without DONT SALVAGE having been set also
1954 * eventually get it set */
1955 V_dontSalvage(vp) = DONT_SALVAGE;
1956 #endif /* !AFS_DEMAND_ATTACH_FS */
1957 VAddToVolumeUpdateList_r(ec, vp);
1959 Log("VAttachVolume: Error adding volume to update list\n");
1966 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
1970 if (programType == volumeUtility) {
1971 VUnlockPartition_r(partition);
1974 #ifdef AFS_DEMAND_ATTACH_FS
1976 V_attachState(vp) = VOL_STATE_ERROR;
1977 assert(pthread_cond_broadcast(&V_attachCV(vp)) == 0);
1979 #endif /* AFS_DEMAND_ATTACH_FS */
1986 #ifdef AFS_DEMAND_ATTACH_FS
1987 /* VAttachVolumeByVp_r
1989 * finish attaching a volume that is
1990 * in a less than fully attached state
1992 /* caller MUST hold a ref count on vp */
1994 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
1996 char name[VMAXPATHLEN];
1997 int fd, n, reserve = 0;
1998 struct afs_stat status;
1999 struct VolumeDiskHeader diskHeader;
2000 struct VolumeHeader iheader;
2001 struct DiskPartition *partp;
2006 VolumeStats stats_save;
2009 /* volume utility should never call AttachByVp */
2010 assert(programType == fileServer);
2012 volumeId = vp->hashid;
2013 partp = vp->partition;
2014 VolumeExternalName_r(volumeId, name, sizeof(name));
2017 /* if another thread is performing a blocking op, wait */
2018 VWaitExclusiveState_r(vp);
2020 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2022 /* if it's already attached, see if we can return it */
2023 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2024 VGetVolumeByVp_r(ec, vp);
2028 if (vp->specialStatus == VBUSY)
2030 VDetachVolume_r(ec, vp);
2032 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2038 /* pre-attach volume if it hasn't been done yet */
2040 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2041 (V_attachState(vp) == VOL_STATE_ERROR)) {
2042 nvp = VPreAttachVolumeById_r(ec, partp, vp, volumeId);
2048 VCreateReservation_r(nvp);
2054 VChangeState_r(vp, VOL_STATE_ATTACHING);
2056 /* restore monotonically increasing stats */
2057 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2062 /* compute path to disk header,
2064 * and verify magic and version stamps */
2065 strcpy(path, VPartitionPath(partp));
2071 if ((fd = afs_open(path, O_RDONLY)) == -1 || afs_fstat(fd, &status) == -1) {
2072 Log("VAttachVolume: Failed to open %s (errno %d)\n", path, errno);
2079 n = read(fd, &diskHeader, sizeof(diskHeader));
2081 if (n != sizeof(diskHeader)
2082 || diskHeader.stamp.magic != VOLUMEHEADERMAGIC) {
2083 Log("VAttachVolume: Error reading volume header %s\n", path);
2088 if (diskHeader.stamp.version != VOLUMEHEADERVERSION) {
2089 Log("VAttachVolume: Volume %s, version number is incorrect; volume needs salvaged\n", path);
2095 /* convert on-disk header format to in-memory header format */
2096 DiskToVolumeHeader(&iheader, &diskHeader);
2100 * NOTE: attach2 is entered without any locks, and returns
2101 * with vol_glock_mutex held */
2102 vp = attach2(ec, volumeId, path, &iheader, partp, vp, isbusy, mode);
2104 if (*ec || vp == NULL) {
2108 V_needsCallback(vp) = 0;
2109 VUpdateVolume_r(ec, vp, 0);
2111 Log("VAttachVolume: Error updating volume %u\n", vp->hashid);
2115 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2116 #ifndef AFS_DEMAND_ATTACH_FS
2117 /* This is a hack: by temporarily setting the incore
2118 * dontSalvage flag ON, the volume will be put back on the
2119 * Update list (with dontSalvage OFF again). It will then
2120 * come back in N minutes with DONT_SALVAGE eventually
2121 * set. This is the way that volumes that have never had
2122 * it set get it set; or that volumes that have been
2123 * offline without DONT SALVAGE having been set also
2124 * eventually get it set */
2125 V_dontSalvage(vp) = DONT_SALVAGE;
2126 #endif /* !AFS_DEMAND_ATTACH_FS */
2127 VAddToVolumeUpdateList_r(ec, vp);
2129 Log("VAttachVolume: Error adding volume %u to update list\n", vp->hashid);
2136 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2140 VCancelReservation_r(nvp);
2143 if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2144 if (vp && !IsErrorState(V_attachState(vp))) {
2145 VChangeState_r(vp, VOL_STATE_ERROR);
2152 #endif /* AFS_DEMAND_ATTACH_FS */
2155 * called without any locks held
2156 * returns with vol_glock_mutex held
2159 attach2(Error * ec, VolId volumeId, char *path, register struct VolumeHeader * header,
2160 struct DiskPartition * partp, register Volume * vp, int isbusy, int mode)
2162 vp->specialStatus = (byte) (isbusy ? VBUSY : 0);
2163 IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header->parent,
2164 header->largeVnodeIndex);
2165 IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header->parent,
2166 header->smallVnodeIndex);
2167 IH_INIT(vp->diskDataHandle, partp->device, header->parent,
2168 header->volumeInfo);
2169 IH_INIT(vp->linkHandle, partp->device, header->parent, header->linkTable);
2170 vp->shuttingDown = 0;
2171 vp->goingOffline = 0;
2173 #ifdef AFS_DEMAND_ATTACH_FS
2174 vp->stats.last_attach = FT_ApproxTime();
2175 vp->stats.attaches++;
2179 #ifdef AFS_DEMAND_ATTACH_FS
2180 IncUInt64(&VStats.attaches);
2182 vp->cacheCheck = ++VolumeCacheCheck;
2183 /* just in case this ever rolls over */
2184 if (!vp->cacheCheck)
2185 vp->cacheCheck = ++VolumeCacheCheck;
2186 GetVolumeHeader(vp);
2189 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2190 /* demand attach changes the V_PEEK mechanism
2192 * we can now suck the current disk data structure over
2193 * the fssync interface without going to disk
2195 * (technically, we don't need to restrict this feature
2196 * to demand attach fileservers. However, I'm trying
2197 * to limit the number of common code changes)
2199 if (programType != fileServer && mode == V_PEEK) {
2201 res.payload.len = sizeof(VolumeDiskData);
2202 res.payload.buf = &vp->header->diskstuff;
2204 if (FSYNC_VolOp(volumeId,
2205 VPartitionPath(partp),
2206 FSYNC_VOL_QUERY_HDR,
2209 goto disk_header_loaded;
2212 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2213 (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2214 sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2216 #ifdef AFS_DEMAND_ATTACH_FS
2219 IncUInt64(&VStats.hdr_loads);
2220 IncUInt64(&vp->stats.hdr_loads);
2222 #endif /* AFS_DEMAND_ATTACH_FS */
2225 Log("VAttachVolume: Error reading diskDataHandle vol header %s; error=%u\n", path, *ec);
2230 #ifdef AFS_DEMAND_ATTACH_FS
2233 /* check for pending volume operations */
2234 if (vp->pending_vol_op) {
2235 /* see if the pending volume op requires exclusive access */
2236 if (!VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
2237 /* mark the volume down */
2239 VChangeState_r(vp, VOL_STATE_UNATTACHED);
2240 if (V_offlineMessage(vp)[0] == '\0')
2241 strlcpy(V_offlineMessage(vp),
2242 "A volume utility is running.",
2243 sizeof(V_offlineMessage(vp)));
2244 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
2246 /* check to see if we should set the specialStatus flag */
2247 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
2248 vp->specialStatus = VBUSY;
2253 V_attachFlags(vp) |= VOL_HDR_LOADED;
2255 #endif /* AFS_DEMAND_ATTACH_FS */
2258 struct IndexFileHeader iHead;
2260 #if OPENAFS_VOL_STATS
2262 * We just read in the diskstuff part of the header. If the detailed
2263 * volume stats area has not yet been initialized, we should bzero the
2264 * area and mark it as initialized.
2266 if (!(V_stat_initialized(vp))) {
2267 memset((char *)(V_stat_area(vp)), 0, VOL_STATS_BYTES);
2268 V_stat_initialized(vp) = 1;
2270 #endif /* OPENAFS_VOL_STATS */
2272 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
2273 (char *)&iHead, sizeof(iHead),
2274 SMALLINDEXMAGIC, SMALLINDEXVERSION);
2277 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
2282 struct IndexFileHeader iHead;
2284 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
2285 (char *)&iHead, sizeof(iHead),
2286 LARGEINDEXMAGIC, LARGEINDEXVERSION);
2289 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
2293 #ifdef AFS_NAMEI_ENV
2295 struct versionStamp stamp;
2297 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
2298 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
2301 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
2304 #endif /* AFS_NAMEI_ENV */
2306 #if defined(AFS_DEMAND_ATTACH_FS)
2307 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
2309 if (programType == fileServer) {
2310 VRequestSalvage_r(vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2314 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
2320 /* volume operation in progress */
2324 #else /* AFS_DEMAND_ATTACH_FS */
2326 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
2331 #endif /* AFS_DEMAND_ATTACH_FS */
2333 if (V_needsSalvaged(vp)) {
2334 if (vp->specialStatus)
2335 vp->specialStatus = 0;
2337 #if defined(AFS_DEMAND_ATTACH_FS)
2338 if (programType == fileServer) {
2339 VRequestSalvage_r(vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
2343 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
2347 #else /* AFS_DEMAND_ATTACH_FS */
2350 #endif /* AFS_DEMAND_ATTACH_FS */
2355 if (programType == fileServer) {
2356 #ifndef FAST_RESTART
2357 if (V_inUse(vp) && VolumeWriteable(vp)) {
2358 if (!V_needsSalvaged(vp)) {
2359 V_needsSalvaged(vp) = 1;
2360 VUpdateVolume_r(ec, vp, 0);
2362 #if defined(AFS_DEMAND_ATTACH_FS)
2363 VRequestSalvage_r(vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
2366 #else /* AFS_DEMAND_ATTACH_FS */
2367 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
2370 #endif /* AFS_DEMAND_ATTACH_FS */
2373 #endif /* FAST_RESTART */
2375 if (V_destroyMe(vp) == DESTROY_ME) {
2376 #if defined(AFS_DEMAND_ATTACH_FS)
2377 /* schedule a salvage so the volume goes away on disk */
2378 VRequestSalvage_r(vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2379 VChangeState_r(vp, VOL_STATE_ERROR);
2381 #endif /* AFS_DEMAND_ATTACH_FS */
2383 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
2389 vp->nextVnodeUnique = V_uniquifier(vp);
2390 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
2391 #ifndef BITMAP_LATER
2392 if (programType == fileServer && VolumeWriteable(vp)) {
2394 for (i = 0; i < nVNODECLASSES; i++) {
2395 VGetBitmap_r(ec, vp, i);
2397 #ifdef AFS_DEMAND_ATTACH_FS
2398 VRequestSalvage_r(vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2401 #else /* AFS_DEMAND_ATTACH_FS */
2403 #endif /* AFS_DEMAND_ATTACH_FS */
2404 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
2410 #endif /* BITMAP_LATER */
2412 if (programType == fileServer) {
2413 if (vp->specialStatus)
2414 vp->specialStatus = 0;
2415 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
2417 V_offlineMessage(vp)[0] = '\0';
2421 AddVolumeToHashTable(vp, V_id(vp));
2422 #ifdef AFS_DEMAND_ATTACH_FS
2423 AddVolumeToVByPList_r(vp);
2425 VChangeState_r(vp, VOL_STATE_ATTACHED);
2430 /* Attach an existing volume.
2431 The volume also normally goes online at this time.
2432 An offline volume must be reattached to make it go online.
2436 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
2440 retVal = VAttachVolume_r(ec, volumeId, mode);
2446 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
2449 GetVolumePath(ec, volumeId, &part, &name);
2451 register Volume *vp;
2453 vp = VGetVolume_r(&error, volumeId);
2455 assert(V_inUse(vp) == 0);
2456 VDetachVolume_r(ec, vp);
2460 return VAttachVolumeByName_r(ec, part, name, mode);
2463 /* Increment a reference count to a volume, sans context swaps. Requires
2464 * possibly reading the volume header in from the disk, since there's
2465 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
2467 * N.B. This call can fail if we can't read in the header!! In this case
2468 * we still guarantee we won't context swap, but the ref count won't be
2469 * incremented (otherwise we'd violate the invariant).
2471 /* NOTE: with the demand attach fileserver extensions, the global lock
2472 * is dropped within VHold */
2473 #ifdef AFS_DEMAND_ATTACH_FS
2475 VHold_r(register Volume * vp)
2479 VCreateReservation_r(vp);
2480 VWaitExclusiveState_r(vp);
2482 LoadVolumeHeader(&error, vp);
2484 VCancelReservation_r(vp);
2488 VCancelReservation_r(vp);
2491 #else /* AFS_DEMAND_ATTACH_FS */
2493 VHold_r(register Volume * vp)
2497 LoadVolumeHeader(&error, vp);
2503 #endif /* AFS_DEMAND_ATTACH_FS */
2506 VHold(register Volume * vp)
2510 retVal = VHold_r(vp);
2516 /***************************************************/
2517 /* get and put volume routines */
2518 /***************************************************/
2521 VPutVolume_r(register Volume * vp)
2523 assert(--vp->nUsers >= 0);
2524 if (vp->nUsers == 0) {
2526 ReleaseVolumeHeader(vp->header);
2527 #ifdef AFS_DEMAND_ATTACH_FS
2528 if (!VCheckDetach(vp)) {
2532 #else /* AFS_DEMAND_ATTACH_FS */
2534 #endif /* AFS_DEMAND_ATTACH_FS */
2539 VPutVolume(register Volume * vp)
2547 /* Get a pointer to an attached volume. The pointer is returned regardless
2548 of whether or not the volume is in service or on/off line. An error
2549 code, however, is returned with an indication of the volume's status */
2551 VGetVolume(Error * ec, Error * client_ec, VolId volumeId)
2555 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
2561 VGetVolume_r(Error * ec, VolId volumeId)
2563 return GetVolume(ec, NULL, volumeId, NULL, 0);
2566 /* try to get a volume we've previously looked up */
2567 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
2569 VGetVolumeByVp_r(Error * ec, Volume * vp)
2571 return GetVolume(ec, NULL, vp->hashid, vp, 0);
2574 /* private interface for getting a volume handle
2575 * volumeId must be provided.
2576 * hint is an optional parameter to speed up hash lookups
2577 * flags is not used at this time
2579 /* for demand attach fs, caller MUST NOT hold a ref count on hint */
2581 GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint, int flags)
2584 /* pull this profiling/debugging code out of regular builds */
2586 #define VGET_CTR_INC(x) x++
2587 unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
2588 0, V7 = 0, V8 = 0, V9 = 0;
2589 unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
2591 #define VGET_CTR_INC(x)
2594 #ifdef AFS_DEMAND_ATTACH_FS
2595 Volume *avp, * rvp = hint;
2598 VCreateReservation_r(rvp);
2600 #endif /* AFS_DEMAND_ATTACH_FS */
2608 vp = VLookupVolume_r(ec, volumeId, vp);
2614 #ifdef AFS_DEMAND_ATTACH_FS
2615 if (rvp && (rvp != vp)) {
2616 /* break reservation on old vp */
2617 VCancelReservation_r(rvp);
2620 #endif /* AFS_DEMAND_ATTACH_FS */
2626 /* Until we have reached an initialization level of 2
2627 * we don't know whether this volume exists or not.
2628 * We can't sleep and retry later because before a volume
2629 * is attached, the caller tries to get it first. Just
2630 * return VOFFLINE and the caller can choose whether to
2631 * retry the command or not. */
2641 IncUInt64(&VStats.hdr_gets);
2643 #ifdef AFS_DEMAND_ATTACH_FS
2644 /* block if someone else is performing an exclusive op on this volume */
2647 VCreateReservation_r(rvp);
2649 VWaitExclusiveState_r(vp);
2651 /* short circuit with VNOVOL in the following circumstances:
2654 * VOL_STATE_SHUTTING_DOWN
2656 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
2657 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN)) {
2663 /* allowable states:
2671 if (vp->salvage.requested) {
2672 VUpdateSalvagePriority_r(vp);
2675 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
2676 avp = VAttachVolumeByVp_r(ec, vp, 0);
2679 /* VAttachVolumeByVp_r can return a pointer
2680 * != the vp passed to it under certain
2681 * conditions; make sure we don't leak
2682 * reservations if that happens */
2684 VCancelReservation_r(rvp);
2686 VCreateReservation_r(rvp);
2696 if (!vp->pending_vol_op) {
2711 if ((V_attachState(vp) == VOL_STATE_SALVAGING) ||
2712 (*ec == VSALVAGING)) {
2714 /* see CheckVnode() in afsfileprocs.c for an explanation
2715 * of this error code logic */
2716 afs_uint32 now = FT_ApproxTime();
2717 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
2720 *client_ec = VRESTARTING;
2728 if (vp->pending_vol_op && !VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
2730 /* see CheckVnode() in afsfileprocs.c for an explanation
2731 * of this error code logic */
2732 afs_uint32 now = FT_ApproxTime();
2733 if ((vp->stats.last_vol_op + (10 * 60)) >= now) {
2736 *client_ec = VRESTARTING;
2744 if (V_attachState(vp) == VOL_STATE_UNATTACHED) {
2749 #endif /* AFS_DEMAND_ATTACH_FS */
2751 LoadVolumeHeader(ec, vp);
2754 /* Only log the error if it was a totally unexpected error. Simply
2755 * a missing inode is likely to be caused by the volume being deleted */
2756 if (errno != ENXIO || LogLevel)
2757 Log("Volume %u: couldn't reread volume header\n",
2759 #ifdef AFS_DEMAND_ATTACH_FS
2760 if (programType == fileServer) {
2761 VRequestSalvage_r(vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2767 #else /* AFS_DEMAND_ATTACH_FS */
2770 #endif /* AFS_DEMAND_ATTACH_FS */
2775 if (vp->shuttingDown) {
2782 if (programType == fileServer) {
2784 if (vp->goingOffline) {
2786 #ifdef AFS_DEMAND_ATTACH_FS
2787 /* wait for the volume to go offline */
2788 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
2789 VWaitStateChange_r(vp);
2791 #elif defined(AFS_PTHREAD_ENV)
2792 assert(pthread_cond_wait(&vol_put_volume_cond, &vol_glock_mutex) == 0);
2793 #else /* AFS_PTHREAD_ENV */
2794 LWP_WaitProcess(VPutVolume);
2795 #endif /* AFS_PTHREAD_ENV */
2798 if (vp->specialStatus) {
2800 *ec = vp->specialStatus;
2801 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
2804 } else if (V_inUse(vp) == 0) {
2815 #ifdef AFS_DEMAND_ATTACH_FS
2816 /* if no error, bump nUsers */
2819 VLRU_UpdateAccess_r(vp);
2822 VCancelReservation_r(rvp);
2825 if (client_ec && !*client_ec) {
2828 #else /* AFS_DEMAND_ATTACH_FS */
2829 /* if no error, bump nUsers */
2836 #endif /* AFS_DEMAND_ATTACH_FS */
2843 /***************************************************/
2844 /* Volume offline/detach routines */
2845 /***************************************************/
2847 /* caller MUST hold a heavyweight ref on vp */
2848 #ifdef AFS_DEMAND_ATTACH_FS
2850 VTakeOffline_r(register Volume * vp)
2852 assert(vp->nUsers > 0);
2853 assert(programType == fileServer);
2855 VCreateReservation_r(vp);
2856 VWaitExclusiveState_r(vp);
2858 vp->goingOffline = 1;
2859 V_needsSalvaged(vp) = 1;
2861 VRequestSalvage_r(vp, SALVSYNC_ERROR, 0);
2862 VCancelReservation_r(vp);
2864 #else /* AFS_DEMAND_ATTACH_FS */
2866 VTakeOffline_r(register Volume * vp)
2868 assert(vp->nUsers > 0);
2869 assert(programType == fileServer);
2871 vp->goingOffline = 1;
2872 V_needsSalvaged(vp) = 1;
2874 #endif /* AFS_DEMAND_ATTACH_FS */
2877 VTakeOffline(register Volume * vp)
2884 /* Force the volume offline, set the salvage flag. No further references to
2885 * the volume through the volume package will be honored. */
2886 /* for demand attach, caller MUST hold ref count on vp */
2888 VForceOffline_r(Volume * vp, int flags)
2893 strcpy(V_offlineMessage(vp),
2894 "Forced offline due to internal error: volume needs to be salvaged");
2895 Log("Volume %u forced offline: it needs salvaging!\n", V_id(vp));
2897 vp->goingOffline = 0;
2898 V_needsSalvaged(vp) = 1;
2899 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
2900 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT | VOL_UPDATE_NOFORCEOFF);
2902 #ifdef AFS_DEMAND_ATTACH_FS
2903 #ifdef SALVSYNC_BUILD_CLIENT
2904 if (programType == fileServer) {
2905 VRequestSalvage_r(vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2908 VChangeState_r(vp, VOL_STATE_ERROR);
2909 #endif /* AFS_DEMAND_ATTACH_FS */
2910 #ifdef AFS_PTHREAD_ENV
2911 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
2912 #else /* AFS_PTHREAD_ENV */
2913 LWP_NoYieldSignal(VPutVolume);
2914 #endif /* AFS_PTHREAD_ENV */
2916 VReleaseVolumeHandles_r(vp);
2920 VForceOffline(Volume * vp)
2923 VForceOffline_r(vp, 0);
2927 /* The opposite of VAttachVolume. The volume header is written to disk, with
2928 the inUse bit turned off. A copy of the header is maintained in memory,
2929 however (which is why this is VOffline, not VDetach).
2932 VOffline_r(Volume * vp, char *message)
2935 VolumeId vid = V_id(vp);
2937 assert(programType != volumeUtility);
2942 if (V_offlineMessage(vp)[0] == '\0')
2943 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
2944 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
2946 vp->goingOffline = 1;
2947 #ifdef AFS_DEMAND_ATTACH_FS
2948 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
2949 VCreateReservation_r(vp);
2952 /* wait for the volume to go offline */
2953 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
2954 VWaitStateChange_r(vp);
2956 VCancelReservation_r(vp);
2957 #else /* AFS_DEMAND_ATTACH_FS */
2959 vp = VGetVolume_r(&error, vid); /* Wait for it to go offline */
2960 if (vp) /* In case it was reattached... */
2962 #endif /* AFS_DEMAND_ATTACH_FS */
2966 VOffline(Volume * vp, char *message)
2969 VOffline_r(vp, message);
2973 /* This gets used for the most part by utility routines that don't want
2974 * to keep all the volume headers around. Generally, the file server won't
2975 * call this routine, because then the offline message in the volume header
2976 * (or other information) won't be available to clients. For NAMEI, also
2977 * close the file handles. However, the fileserver does call this during
2978 * an attach following a volume operation.
2981 VDetachVolume_r(Error * ec, Volume * vp)
2984 struct DiskPartition *tpartp;
2985 int notifyServer, useDone;
2987 *ec = 0; /* always "succeeds" */
2988 if (programType == volumeUtility) {
2989 notifyServer = vp->needsPutBack;
2990 useDone = (V_destroyMe(vp) == DESTROY_ME);
2992 tpartp = vp->partition;
2994 DeleteVolumeFromHashTable(vp);
2995 vp->shuttingDown = 1;
2996 #ifdef AFS_DEMAND_ATTACH_FS
2997 DeleteVolumeFromVByPList_r(vp);
2999 VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
3000 #endif /* AFS_DEMAND_ATTACH_FS */
3002 /* Will be detached sometime in the future--this is OK since volume is offline */
3004 /* XXX the following code should really be moved to VCheckDetach() since the volume
3005 * is not technically detached until the refcounts reach zero
3007 #ifdef FSSYNC_BUILD_CLIENT
3008 if (programType == volumeUtility && notifyServer) {
3010 * Note: The server is not notified in the case of a bogus volume
3011 * explicitly to make it possible to create a volume, do a partial
3012 * restore, then abort the operation without ever putting the volume
3013 * online. This is essential in the case of a volume move operation
3014 * between two partitions on the same server. In that case, there
3015 * would be two instances of the same volume, one of them bogus,
3016 * which the file server would attempt to put on line
3019 /* don't put online */
3020 FSYNC_VolOp(volume, tpartp->name, FSYNC_VOL_DONE, 0, NULL);
3022 /* fs can use it again */
3023 FSYNC_VolOp(volume, tpartp->name, FSYNC_VOL_ON, 0, NULL);
3025 /* XXX this code path is only hit by volume utilities, thus
3026 * V_BreakVolumeCallbacks will always be NULL. if we really
3027 * want to break callbacks in this path we need to use FSYNC_VolOp() */
3029 /* Dettaching it so break all callbacks on it */
3030 if (V_BreakVolumeCallbacks) {
3031 Log("volume %u detached; breaking all call backs\n", volume);
3032 (*V_BreakVolumeCallbacks) (volume);
3037 #endif /* FSSYNC_BUILD_CLIENT */
3041 VDetachVolume(Error * ec, Volume * vp)
3044 VDetachVolume_r(ec, vp);
3049 /***************************************************/
3050 /* Volume fd/inode handle closing routines */
3051 /***************************************************/
3053 /* For VDetachVolume, we close all cached file descriptors, but keep
3054 * the Inode handles in case we need to read from a busy volume.
3056 /* for demand attach, caller MUST hold ref count on vp */
3058 VCloseVolumeHandles_r(Volume * vp)
3060 #ifdef AFS_DEMAND_ATTACH_FS
3061 VolState state_save;
3063 state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
3068 * XXX need to investigate whether we can perform
3069 * DFlushVolume outside of vol_glock_mutex...
3071 * VCloseVnodeFiles_r drops the glock internally */
3072 DFlushVolume(V_id(vp));
3073 VCloseVnodeFiles_r(vp);
3075 #ifdef AFS_DEMAND_ATTACH_FS
3079 /* Too time consuming and unnecessary for the volserver */
3080 if (programType != volumeUtility) {
3081 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
3082 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
3083 IH_CONDSYNC(vp->diskDataHandle);
3085 IH_CONDSYNC(vp->linkHandle);
3086 #endif /* AFS_NT40_ENV */
3089 IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
3090 IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
3091 IH_REALLYCLOSE(vp->diskDataHandle);
3092 IH_REALLYCLOSE(vp->linkHandle);
3094 #ifdef AFS_DEMAND_ATTACH_FS
3096 VChangeState_r(vp, state_save);
3100 /* For both VForceOffline and VOffline, we close all relevant handles.
3101 * For VOffline, if we re-attach the volume, the files may possible be
3102 * different than before.
3104 /* for demand attach, caller MUST hold a ref count on vp */
3106 VReleaseVolumeHandles_r(Volume * vp)
3108 #ifdef AFS_DEMAND_ATTACH_FS
3109 VolState state_save;
3111 state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
3114 /* XXX need to investigate whether we can perform
3115 * DFlushVolume outside of vol_glock_mutex... */
3116 DFlushVolume(V_id(vp));
3118 VReleaseVnodeFiles_r(vp); /* releases the glock internally */
3120 #ifdef AFS_DEMAND_ATTACH_FS
3124 /* Too time consuming and unnecessary for the volserver */
3125 if (programType != volumeUtility) {
3126 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
3127 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
3128 IH_CONDSYNC(vp->diskDataHandle);
3130 IH_CONDSYNC(vp->linkHandle);
3131 #endif /* AFS_NT40_ENV */
3134 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
3135 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
3136 IH_RELEASE(vp->diskDataHandle);
3137 IH_RELEASE(vp->linkHandle);
3139 #ifdef AFS_DEMAND_ATTACH_FS
3141 VChangeState_r(vp, state_save);
3146 /***************************************************/
3147 /* Volume write and fsync routines */
3148 /***************************************************/
3151 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
3153 #ifdef AFS_DEMAND_ATTACH_FS
3154 VolState state_save;
3156 if (flags & VOL_UPDATE_WAIT) {
3157 VCreateReservation_r(vp);
3158 VWaitExclusiveState_r(vp);
3163 if (programType == fileServer)
3165 (V_inUse(vp) ? V_nextVnodeUnique(vp) +
3166 200 : V_nextVnodeUnique(vp));
3168 #ifdef AFS_DEMAND_ATTACH_FS
3169 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
3173 WriteVolumeHeader_r(ec, vp);
3175 #ifdef AFS_DEMAND_ATTACH_FS
3177 VChangeState_r(vp, state_save);
3178 if (flags & VOL_UPDATE_WAIT) {
3179 VCancelReservation_r(vp);
3184 Log("VUpdateVolume: error updating volume header, volume %u (%s)\n",
3185 V_id(vp), V_name(vp));
3186 /* try to update on-disk header,
3187 * while preventing infinite recursion */
3188 if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
3189 VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
3195 VUpdateVolume(Error * ec, Volume * vp)
3198 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
3203 VSyncVolume_r(Error * ec, Volume * vp, int flags)
3207 #ifdef AFS_DEMAND_ATTACH_FS
3208 VolState state_save;
3211 if (flags & VOL_SYNC_WAIT) {
3212 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
3214 VUpdateVolume_r(ec, vp, 0);
3217 #ifdef AFS_DEMAND_ATTACH_FS
3218 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
3221 fdP = IH_OPEN(V_diskDataHandle(vp));
3222 assert(fdP != NULL);
3223 code = FDH_SYNC(fdP);
3226 #ifdef AFS_DEMAND_ATTACH_FS
3228 VChangeState_r(vp, state_save);
3234 VSyncVolume(Error * ec, Volume * vp)
3237 VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
3242 /***************************************************/
3243 /* Volume dealloaction routines */
3244 /***************************************************/
3246 #ifdef AFS_DEMAND_ATTACH_FS
3248 FreeVolume(Volume * vp)
3250 /* free the heap space, iff it's safe.
3251 * otherwise, pull it out of the hash table, so it
3252 * will get deallocated when all refs to it go away */
3253 if (!VCheckFree(vp)) {
3254 DeleteVolumeFromHashTable(vp);
3255 DeleteVolumeFromVByPList_r(vp);
3257 /* make sure we invalidate the header cache entry */
3258 FreeVolumeHeader(vp);
3261 #endif /* AFS_DEMAND_ATTACH_FS */
3264 ReallyFreeVolume(Volume * vp)
3269 #ifdef AFS_DEMAND_ATTACH_FS
3271 VChangeState_r(vp, VOL_STATE_FREED);
3272 if (vp->pending_vol_op)
3273 free(vp->pending_vol_op);
3274 #endif /* AFS_DEMAND_ATTACH_FS */
3275 for (i = 0; i < nVNODECLASSES; i++)
3276 if (vp->vnodeIndex[i].bitmap)
3277 free(vp->vnodeIndex[i].bitmap);
3278 FreeVolumeHeader(vp);
3279 #ifndef AFS_DEMAND_ATTACH_FS
3280 DeleteVolumeFromHashTable(vp);
3281 #endif /* AFS_DEMAND_ATTACH_FS */
3285 /* check to see if we should shutdown this volume
3286 * returns 1 if volume was freed, 0 otherwise */
3287 #ifdef AFS_DEMAND_ATTACH_FS
3289 VCheckDetach(register Volume * vp)
3293 if (vp->nUsers || vp->nWaiters)
3296 if (vp->shuttingDown) {
3298 VReleaseVolumeHandles_r(vp);
3300 ReallyFreeVolume(vp);
3301 if (programType == fileServer) {
3302 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3307 #else /* AFS_DEMAND_ATTACH_FS */
3309 VCheckDetach(register Volume * vp)
3316 if (vp->shuttingDown) {
3318 VReleaseVolumeHandles_r(vp);
3319 ReallyFreeVolume(vp);
3320 if (programType == fileServer) {
3321 #if defined(AFS_PTHREAD_ENV)
3322 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3323 #else /* AFS_PTHREAD_ENV */
3324 LWP_NoYieldSignal(VPutVolume);
3325 #endif /* AFS_PTHREAD_ENV */
3330 #endif /* AFS_DEMAND_ATTACH_FS */
3332 /* check to see if we should offline this volume
3333 * return 1 if volume went offline, 0 otherwise */
3334 #ifdef AFS_DEMAND_ATTACH_FS
3336 VCheckOffline(register Volume * vp)
3338 Volume * rvp = NULL;
3341 if (vp->goingOffline && !vp->nUsers) {
3343 assert(programType == fileServer);
3344 assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
3345 (V_attachState(vp) != VOL_STATE_FREED) &&
3346 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
3347 (V_attachState(vp) != VOL_STATE_UNATTACHED));
3351 * VOL_STATE_GOING_OFFLINE
3352 * VOL_STATE_SHUTTING_DOWN
3353 * IsErrorState(V_attachState(vp))
3354 * IsExclusiveState(V_attachState(vp))
3357 VCreateReservation_r(vp);
3358 VChangeState_r(vp, VOL_STATE_OFFLINING);
3361 /* must clear the goingOffline flag before we drop the glock */
3362 vp->goingOffline = 0;
3367 /* perform async operations */
3368 VUpdateVolume_r(&error, vp, 0);
3369 VCloseVolumeHandles_r(vp);
3371 /* invalidate the volume header cache entry */
3372 FreeVolumeHeader(vp);
3375 Log("VOffline: Volume %u (%s) is now offline", V_id(vp),
3377 if (V_offlineMessage(vp)[0])
3378 Log(" (%s)", V_offlineMessage(vp));
3382 /* if nothing changed state to error or salvaging,
3383 * drop state to unattached */
3384 if (!IsErrorState(V_attachState(vp))) {
3385 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3387 VCancelReservation_r(vp);
3391 #else /* AFS_DEMAND_ATTACH_FS */
3393 VCheckOffline(register Volume * vp)
3395 Volume * rvp = NULL;
3398 if (vp->goingOffline && !vp->nUsers) {
3400 assert(programType == fileServer);
3403 vp->goingOffline = 0;
3405 VUpdateVolume_r(&error, vp, 0);
3406 VCloseVolumeHandles_r(vp);
3407 FreeVolumeHeader(vp);
3409 Log("VOffline: Volume %u (%s) is now offline", V_id(vp),
3411 if (V_offlineMessage(vp)[0])
3412 Log(" (%s)", V_offlineMessage(vp));
3415 #ifdef AFS_PTHREAD_ENV
3416 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3417 #else /* AFS_PTHREAD_ENV */
3418 LWP_NoYieldSignal(VPutVolume);
3419 #endif /* AFS_PTHREAD_ENV */
3423 #endif /* AFS_DEMAND_ATTACH_FS */
3425 /***************************************************/
3426 /* demand attach fs ref counting routines */
3427 /***************************************************/
3429 #ifdef AFS_DEMAND_ATTACH_FS
3430 /* the following two functions handle reference counting for
3431 * asynchronous operations on volume structs.
3433 * their purpose is to prevent a VDetachVolume or VShutdown
3434 * from free()ing the Volume struct during an async i/o op */
3436 /* register with the async volume op ref counter */
3438 VCreateReservation_r(Volume * vp)
3443 /* unregister with the async volume op ref counter */
3445 VCancelReservation_r(Volume * vp)
3447 assert(--vp->nWaiters >= 0);
3448 if (vp->nWaiters == 0) {
3450 if (!VCheckDetach(vp)) {
3457 /* check to see if we should free this volume now
3458 * return 1 if volume was freed, 0 otherwise */
3460 VCheckFree(Volume * vp)
3463 if ((vp->nUsers == 0) &&
3464 (vp->nWaiters == 0) &&
3465 !(V_attachFlags(vp) & (VOL_IN_HASH |
3469 ReallyFreeVolume(vp);
3474 #endif /* AFS_DEMAND_ATTACH_FS */
3477 /***************************************************/
3478 /* online volume operations routines */
3479 /***************************************************/
3481 #ifdef AFS_DEMAND_ATTACH_FS
3483 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3485 FSSYNC_VolOp_info * info;
3487 /* attach a vol op info node to the volume struct */
3488 info = (FSSYNC_VolOp_info *) malloc(sizeof(FSSYNC_VolOp_info));
3489 assert(info != NULL);
3490 memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
3491 vp->pending_vol_op = info;
3494 vp->stats.last_vol_op = FT_ApproxTime();
3495 vp->stats.vol_ops++;
3496 IncUInt64(&VStats.vol_ops);
3502 VDeregisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3504 if (vp->pending_vol_op) {
3505 free(vp->pending_vol_op);
3506 vp->pending_vol_op = NULL;
3510 #endif /* AFS_DEMAND_ATTACH_FS */
3513 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3515 return (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
3516 (vopinfo->com.reason == V_READONLY ||
3517 (!VolumeWriteable(vp) &&
3518 (vopinfo->com.reason == V_CLONE ||
3519 vopinfo->com.reason == V_DUMP))));
3523 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3525 return (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
3526 (vopinfo->com.reason == V_CLONE ||
3527 vopinfo->com.reason == V_DUMP));
3531 /***************************************************/
3532 /* online salvager routines */
3533 /***************************************************/
3534 #if defined(AFS_DEMAND_ATTACH_FS)
3535 #define SALVAGE_PRIO_UPDATE_INTERVAL 3 /* number of seconds between prio updates */
3536 #define SALVAGE_COUNT_MAX 16 /* number of online salvages we
3537 * allow before moving the volume
3538 * into a permanent error state
3540 * once this threshold is reached,
3541 * the operator will have to manually
3542 * issue a 'bos salvage' to bring
3543 * the volume back online
3546 /* check to see if we should salvage this volume
3547 * returns 1 if salvage scheduled, 0 otherwise */
3549 VCheckSalvage(register Volume * vp)
3552 #ifdef SALVSYNC_BUILD_CLIENT
3553 if (vp->nUsers || vp->nWaiters)
3555 if (vp->salvage.requested) {
3556 VScheduleSalvage_r(vp);
3559 #endif /* SALVSYNC_BUILD_CLIENT */
3564 * request that a salvage be performed once
3565 * ref counts reach zero
3568 VRequestSalvage_r(Volume * vp, int reason, int flags)
3570 #ifdef SALVSYNC_BUILD_CLIENT
3571 if (programType != fileServer)
3574 if (!vp->salvage.requested) {
3575 vp->salvage.requested = 1;
3576 vp->salvage.reason = reason;
3577 vp->stats.last_salvage = FT_ApproxTime();
3578 if (flags & VOL_SALVAGE_INVALIDATE_HEADER) {
3579 ReleaseVolumeHeader(vp->header);
3581 if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
3582 VChangeState_r(vp, VOL_STATE_SALVAGING);
3584 Log("VRequestSalvage: volume %u online salvaged too many times; forced offline.\n", vp->hashid);
3585 VChangeState_r(vp, VOL_STATE_ERROR);
3588 #endif /* SALVSYNC_BUILD_CLIENT */
3593 * update salvage priority
3596 VUpdateSalvagePriority_r(Volume * vp)
3601 #ifdef SALVSYNC_BUILD_CLIENT
3603 now = FT_ApproxTime();
3605 /* update the salvageserver priority queue occasionally so that
3606 * frequently requested volumes get moved to the head of the queue
3608 if ((vp->salvage.scheduled) &&
3609 (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
3610 code = SALVSYNC_SalvageVolume(vp->hashid,
3611 VPartitionPath(vp->partition),
3616 vp->stats.last_salvage_req = now;
3617 if (code != SYNC_OK) {
3621 #endif /* SALVSYNC_BUILD_CLIENT */
3627 * schedule a salvage with the salvage server
3630 VScheduleSalvage_r(Volume * vp)
3633 #ifdef SALVSYNC_BUILD_CLIENT
3634 VolState state_save;
3637 if (vp->nWaiters || vp->nUsers) {
3641 /* prevent endless salvage,attach,salvage,attach,... loops */
3642 if (vp->stats.salvages >= SALVAGE_COUNT_MAX)
3645 if (!vp->salvage.scheduled) {
3646 /* if we haven't previously scheduled a salvage, do so now
3648 * set the volume to an exclusive state and drop the lock
3649 * around the SALVSYNC call
3651 strlcpy(partName, VPartitionPath(vp->partition), sizeof(partName));
3652 state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
3653 V_attachFlags(vp) |= VOL_IS_BUSY;
3656 /* can't use V_id() since there's no guarantee
3657 * we have the disk data header at this point */
3658 code = SALVSYNC_SalvageVolume(vp->hashid,
3665 VChangeState_r(vp, state_save);
3666 V_attachFlags(vp) &= ~(VOL_IS_BUSY);
3668 if (code == SYNC_OK) {
3669 vp->salvage.scheduled = 1;
3670 vp->stats.salvages++;
3671 vp->stats.last_salvage_req = FT_ApproxTime();
3672 IncUInt64(&VStats.salvages);
3676 case SYNC_BAD_COMMAND:
3677 case SYNC_COM_ERROR:
3680 Log("VScheduleSalvage_r: SALVSYNC request denied\n");
3683 Log("VScheduleSalvage_r: SALVSYNC unknown protocol error\n");
3688 #endif /* SALVSYNC_BUILD_CLIENT */
3693 * cancel a scheduled salvage operation
3696 VCancelSalvage_r(Volume * vp, int reason)
3700 #ifdef SALVSYNC_BUILD_CLIENT
3701 if (vp->salvage.scheduled) {
3702 code = SALVSYNC_SalvageVolume(vp->hashid,
3703 VPartitionPath(vp->partition),
3708 if (code == SYNC_OK) {
3709 vp->salvage.scheduled = 0;
3714 #endif /* SALVSYNC_BUILD_CLIENT */
3718 /* This must be called by any volume utility which needs to run while the
3719 file server is also running. This is separated from VInitVolumePackage so
3720 that a utility can fork--and each of the children can independently
3721 initialize communication with the file server */
3722 #ifdef SALVSYNC_BUILD_CLIENT
3728 retVal = VConnectSALV_r();
3734 VConnectSALV_r(void)
3736 assert((programType != salvageServer) &&
3737 (programType != volumeUtility));
3738 return SALVSYNC_clientInit();
3742 VDisconnectSALV(void)
3746 VDisconnectSALV_r();
3752 VDisconnectSALV_r(void)
3754 assert((programType != salvageServer) &&
3755 (programType != volumeUtility));
3756 return SALVSYNC_clientFinis();
3760 VReconnectSALV(void)
3764 retVal = VReconnectSALV_r();
3770 VReconnectSALV_r(void)
3772 assert((programType != salvageServer) &&
3773 (programType != volumeUtility));
3774 return SALVSYNC_clientReconnect();
3776 #endif /* SALVSYNC_BUILD_CLIENT */
3777 #endif /* AFS_DEMAND_ATTACH_FS */
3780 /***************************************************/
3781 /* FSSYNC routines */
3782 /***************************************************/
3784 /* This must be called by any volume utility which needs to run while the
3785 file server is also running. This is separated from VInitVolumePackage so
3786 that a utility can fork--and each of the children can independently
3787 initialize communication with the file server */
3788 #ifdef FSSYNC_BUILD_CLIENT
3794 retVal = VConnectFS_r();
3803 assert((VInit == 2) &&
3804 (programType != fileServer) &&
3805 (programType != salvager));
3806 rc = FSYNC_clientInit();
3813 VDisconnectFS_r(void)
3815 assert((programType != fileServer) &&
3816 (programType != salvager));
3817 FSYNC_clientFinis();
3830 VChildProcReconnectFS_r(void)
3832 return FSYNC_clientChildProcReconnect();
3836 VChildProcReconnectFS(void)
3840 ret = VChildProcReconnectFS_r();
3844 #endif /* FSSYNC_BUILD_CLIENT */
3847 /***************************************************/
3848 /* volume bitmap routines */
3849 /***************************************************/
3852 * For demand attach fs, flags parameter controls
3853 * locking behavior. If (flags & VOL_ALLOC_BITMAP_WAIT)
3854 * is set, then this function will create a reservation
3855 * and block on any other exclusive operations. Otherwise,
3856 * this function assumes the caller already has exclusive
3857 * access to vp, and we just change the volume state.
3860 VAllocBitmapEntry_r(Error * ec, Volume * vp,
3861 struct vnodeIndex *index, int flags)
3864 register byte *bp, *ep;
3865 #ifdef AFS_DEMAND_ATTACH_FS
3866 VolState state_save;
3867 #endif /* AFS_DEMAND_ATTACH_FS */
3871 /* This test is probably redundant */
3872 if (!VolumeWriteable(vp)) {
3873 *ec = (bit32) VREADONLY;
3877 #ifdef AFS_DEMAND_ATTACH_FS
3878 if (flags & VOL_ALLOC_BITMAP_WAIT) {
3879 VCreateReservation_r(vp);
3880 VWaitExclusiveState_r(vp);
3882 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
3883 #endif /* AFS_DEMAND_ATTACH_FS */
3886 if ((programType == fileServer) && !index->bitmap) {
3888 #ifndef AFS_DEMAND_ATTACH_FS
3889 /* demand attach fs uses the volume state to avoid races.
3890 * specialStatus field is not used at all */
3892 if (vp->specialStatus == VBUSY) {
3893 if (vp->goingOffline) { /* vos dump waiting for the volume to
3894 * go offline. We probably come here
3895 * from AddNewReadableResidency */
3898 while (vp->specialStatus == VBUSY) {
3899 #ifdef AFS_PTHREAD_ENV
3903 #else /* AFS_PTHREAD_ENV */
3905 #endif /* AFS_DEMAND_ATTACH_FS */
3909 #endif /* !AFS_DEMAND_ATTACH_FS */
3911 if (!index->bitmap) {
3912 #ifndef AFS_DEMAND_ATTACH_FS
3913 vp->specialStatus = VBUSY; /* Stop anyone else from using it. */
3914 #endif /* AFS_DEMAND_ATTACH_FS */
3915 for (i = 0; i < nVNODECLASSES; i++) {
3916 VGetBitmap_r(ec, vp, i);
3918 #ifdef AFS_DEMAND_ATTACH_FS
3919 VRequestSalvage_r(vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3921 #else /* AFS_DEMAND_ATTACH_FS */
3922 DeleteVolumeFromHashTable(vp);
3923 vp->shuttingDown = 1; /* Let who has it free it. */
3924 vp->specialStatus = 0;
3925 #endif /* AFS_DEMAND_ATTACH_FS */
3930 #ifndef AFS_DEMAND_ATTACH_FS
3932 vp->specialStatus = 0; /* Allow others to have access. */
3933 #endif /* AFS_DEMAND_ATTACH_FS */
3936 #endif /* BITMAP_LATER */
3938 #ifdef AFS_DEMAND_ATTACH_FS
3940 #endif /* AFS_DEMAND_ATTACH_FS */
3941 bp = index->bitmap + index->bitmapOffset;
3942 ep = index->bitmap + index->bitmapSize;
3944 if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
3946 index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
3949 o = ffs(~*bp) - 1; /* ffs is documented in BSTRING(3) */
3951 ret = (VnodeId) ((bp - index->bitmap) * 8 + o);
3952 #ifdef AFS_DEMAND_ATTACH_FS
3954 #endif /* AFS_DEMAND_ATTACH_FS */
3957 bp += sizeof(bit32) /* i.e. 4 */ ;
3959 /* No bit map entry--must grow bitmap */
3961 realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
3964 bp += index->bitmapSize;
3965 memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
3966 index->bitmapOffset = index->bitmapSize;
3967 index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
3969 ret = index->bitmapOffset * 8;
3970 #ifdef AFS_DEMAND_ATTACH_FS
3972 #endif /* AFS_DEMAND_ATTACH_FS */
3975 #ifdef AFS_DEMAND_ATTACH_FS
3976 VChangeState_r(vp, state_save);
3977 if (flags & VOL_ALLOC_BITMAP_WAIT) {
3978 VCancelReservation_r(vp);
3980 #endif /* AFS_DEMAND_ATTACH_FS */
3985 VAllocBitmapEntry(Error * ec, Volume * vp, register struct vnodeIndex * index)
3989 retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
3995 VFreeBitMapEntry_r(Error * ec, register struct vnodeIndex *index,
3998 unsigned int offset;
4004 #endif /* BITMAP_LATER */
4005 offset = bitNumber >> 3;
4006 if (offset >= index->bitmapSize) {
4010 if (offset < index->bitmapOffset)
4011 index->bitmapOffset = offset & ~3; /* Truncate to nearest bit32 */
4012 *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
4016 VFreeBitMapEntry(Error * ec, register struct vnodeIndex *index,
4020 VFreeBitMapEntry_r(ec, index, bitNumber);
4024 /* this function will drop the glock internally.
4025 * for old pthread fileservers, this is safe thanks to vbusy.
4027 * for demand attach fs, caller must have already called
4028 * VCreateReservation_r and VWaitExclusiveState_r */
4030 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
4032 StreamHandle_t *file;
4035 struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
4036 struct vnodeIndex *vip = &vp->vnodeIndex[class];
4037 struct VnodeDiskObject *vnode;
4038 unsigned int unique = 0;
4042 #endif /* BITMAP_LATER */
4043 #ifdef AFS_DEMAND_ATTACH_FS
4044 VolState state_save;
4045 #endif /* AFS_DEMAND_ATTACH_FS */
4049 #ifdef AFS_DEMAND_ATTACH_FS
4050 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
4051 #endif /* AFS_DEMAND_ATTACH_FS */
4054 fdP = IH_OPEN(vip->handle);
4055 assert(fdP != NULL);
4056 file = FDH_FDOPEN(fdP, "r");
4057 assert(file != NULL);
4058 vnode = (VnodeDiskObject *) malloc(vcp->diskSize);
4059 assert(vnode != NULL);
4060 size = OS_SIZE(fdP->fd_fd);
4062 nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
4064 vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4; /* The 10 is a little extra so
4065 * a few files can be created in this volume,
4066 * the whole thing is rounded up to nearest 4
4067 * bytes, because the bit map allocator likes
4070 BitMap = (byte *) calloc(1, vip->bitmapSize);
4071 assert(BitMap != NULL);
4072 #else /* BITMAP_LATER */
4073 vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
4074 assert(vip->bitmap != NULL);
4075 vip->bitmapOffset = 0;
4076 #endif /* BITMAP_LATER */
4077 if (STREAM_SEEK(file, vcp->diskSize, 0) != -1) {
4079 for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
4080 if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
4082 if (vnode->type != vNull) {
4083 if (vnode->vnodeMagic != vcp->magic) {
4084 Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
4089 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
4090 #else /* BITMAP_LATER */
4091 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
4092 #endif /* BITMAP_LATER */
4093 if (unique <= vnode->uniquifier)
4094 unique = vnode->uniquifier + 1;
4096 #ifndef AFS_PTHREAD_ENV
4097 if ((bitNumber & 0x00ff) == 0x0ff) { /* every 256 iterations */
4100 #endif /* !AFS_PTHREAD_ENV */
4103 if (vp->nextVnodeUnique < unique) {
4104 Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
4107 /* Paranoia, partly justified--I think fclose after fdopen
4108 * doesn't seem to close fd. In any event, the documentation
4109 * doesn't specify, so it's safer to close it twice.
4117 /* There may have been a racing condition with some other thread, both
4118 * creating the bitmaps for this volume. If the other thread was faster
4119 * the pointer to bitmap should already be filled and we can free ours.
4121 if (vip->bitmap == NULL) {
4122 vip->bitmap = BitMap;
4123 vip->bitmapOffset = 0;
4125 free((byte *) BitMap);
4126 #endif /* BITMAP_LATER */
4127 #ifdef AFS_DEMAND_ATTACH_FS
4128 VChangeState_r(vp, state_save);
4129 #endif /* AFS_DEMAND_ATTACH_FS */
4133 /***************************************************/
4134 /* demand attach fs state machine routines */
4135 /***************************************************/
4137 #ifdef AFS_DEMAND_ATTACH_FS
4138 /* wait for the volume to change states */
4140 VWaitStateChange_r(Volume * vp)
4142 VolState state_save = V_attachState(vp);
4144 assert(vp->nWaiters || vp->nUsers);
4146 assert(pthread_cond_wait(&V_attachCV(vp), &vol_glock_mutex) == 0);
4147 } while (V_attachState(vp) == state_save);
4148 assert(V_attachState(vp) != VOL_STATE_FREED);
4151 /* wait for blocking ops to end */
4153 VWaitExclusiveState_r(Volume * vp)
4155 assert(vp->nWaiters || vp->nUsers);
4156 while (IsExclusiveState(V_attachState(vp))) {
4157 assert(pthread_cond_wait(&V_attachCV(vp), &vol_glock_mutex) == 0);
4159 assert(V_attachState(vp) != VOL_STATE_FREED);
4162 /* change state, and notify other threads,
4163 * return previous state to caller */
4165 VChangeState_r(Volume * vp, VolState new_state)
4167 VolState old_state = V_attachState(vp);
4169 /* XXX profiling need to make sure these counters
4170 * don't kill performance... */
4171 VStats.state_levels[old_state]--;
4172 VStats.state_levels[new_state]++;
4174 V_attachState(vp) = new_state;
4175 assert(pthread_cond_broadcast(&V_attachCV(vp)) == 0);
4179 /* tells caller whether or not the current state requires
4180 * exclusive access without holding glock */
4182 IsExclusiveState(VolState state)
4185 case VOL_STATE_UPDATING:
4186 case VOL_STATE_ATTACHING:
4187 case VOL_STATE_GET_BITMAP:
4188 case VOL_STATE_HDR_LOADING:
4189 case VOL_STATE_HDR_ATTACHING:
4190 case VOL_STATE_OFFLINING:
4191 case VOL_STATE_DETACHING:
4197 /* tell caller whether V_attachState is an error condition */
4199 IsErrorState(VolState state)
4202 case VOL_STATE_ERROR:
4203 case VOL_STATE_SALVAGING:
4209 /* tell caller whether V_attachState is valid */
4211 IsValidState(VolState state)
4214 (state < VOL_STATE_COUNT) &&
4215 (state != VOL_STATE_FREED)) {
4220 #endif /* AFS_DEMAND_ATTACH_FS */
4223 /***************************************************/
4224 /* Volume Path and Volume Number utility routines */
4225 /***************************************************/
4228 GetVolumePath(Error * ec, VolId volumeId, char **partitionp, char **namep)
4230 static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
4231 char path[VMAXPATHLEN];
4233 struct DiskPartition *dp;
4237 (void)afs_snprintf(&name[1], (sizeof name) - 1, VFORMAT, volumeId);
4238 for (dp = DiskPartitionList; dp; dp = dp->next) {
4239 struct afs_stat status;
4240 strcpy(path, VPartitionPath(dp));
4242 if (afs_stat(path, &status) == 0) {
4243 strcpy(partition, dp->name);
4250 *partitionp = *namep = NULL;
4252 *partitionp = partition;
4258 VolumeNumber(char *name)
4262 return atoi(name + 1);
4266 VolumeExternalName(VolumeId volumeId)
4268 static char name[VMAXPATHLEN];
4269 (void)afs_snprintf(name, sizeof name, VFORMAT, volumeId);
4274 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
4276 return afs_snprintf(name, len, VFORMAT, volumeId);
4280 /***************************************************/
4281 /* Volume Usage Statistics routines */
4282 /***************************************************/
4284 #if OPENAFS_VOL_STATS
4285 #define OneDay (86400) /* 24 hours' worth of seconds */
4287 #define OneDay (24*60*60) /* 24 hours */
4288 #endif /* OPENAFS_VOL_STATS */
4290 #define Midnight(date) ((date-TimeZoneCorrection)/OneDay*OneDay+TimeZoneCorrection)
4292 /*------------------------------------------------------------------------
4293 * [export] VAdjustVolumeStatistics
4296 * If we've passed midnight, we need to update all the day use
4297 * statistics as well as zeroing the detailed volume statistics
4298 * (if we are implementing them).
4301 * vp : Pointer to the volume structure describing the lucky
4302 * volume being considered for update.
4308 * Nothing interesting.
4312 *------------------------------------------------------------------------*/
4315 VAdjustVolumeStatistics_r(register Volume * vp)
4317 unsigned int now = FT_ApproxTime();
4319 if (now - V_dayUseDate(vp) > OneDay) {
4320 register int ndays, i;
4322 ndays = (now - V_dayUseDate(vp)) / OneDay;
4323 for (i = 6; i > ndays - 1; i--)
4324 V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
4325 for (i = 0; i < ndays - 1 && i < 7; i++)
4326 V_weekUse(vp)[i] = 0;
4328 V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
4330 V_dayUseDate(vp) = Midnight(now);
4332 #if OPENAFS_VOL_STATS
4334 * All we need to do is bzero the entire VOL_STATS_BYTES of
4335 * the detailed volume statistics area.
4337 memset((char *)(V_stat_area(vp)), 0, VOL_STATS_BYTES);
4338 #endif /* OPENAFS_VOL_STATS */
4341 /*It's been more than a day of collection */
4343 * Always return happily.
4346 } /*VAdjustVolumeStatistics */
4349 VAdjustVolumeStatistics(register Volume * vp)
4353 retVal = VAdjustVolumeStatistics_r(vp);
4359 VBumpVolumeUsage_r(register Volume * vp)
4361 unsigned int now = FT_ApproxTime();
4362 if (now - V_dayUseDate(vp) > OneDay)
4363 VAdjustVolumeStatistics_r(vp);
4365 * Save the volume header image to disk after every 128 bumps to dayUse.
4367 if ((V_dayUse(vp)++ & 127) == 0) {
4369 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
4374 VBumpVolumeUsage(register Volume * vp)
4377 VBumpVolumeUsage_r(vp);
4382 VSetDiskUsage_r(void)
4384 #ifndef AFS_DEMAND_ATTACH_FS
4385 static int FifteenMinuteCounter = 0;
4389 /* NOTE: Don't attempt to access the partitions list until the
4390 * initialization level indicates that all volumes are attached,
4391 * which implies that all partitions are initialized. */
4392 #ifdef AFS_PTHREAD_ENV
4394 #else /* AFS_PTHREAD_ENV */
4396 #endif /* AFS_PTHREAD_ENV */
4399 VResetDiskUsage_r();
4401 #ifndef AFS_DEMAND_ATTACH_FS
4402 if (++FifteenMinuteCounter == 3) {
4403 FifteenMinuteCounter = 0;
4406 #endif /* !AFS_DEMAND_ATTACH_FS */
4418 /***************************************************/
4419 /* Volume Update List routines */
4420 /***************************************************/
4422 /* The number of minutes that a volume hasn't been updated before the
4423 * "Dont salvage" flag in the volume header will be turned on */
4424 #define SALVAGE_INTERVAL (10*60)
4429 * volume update list functionality has been moved into the VLRU
4430 * the DONT_SALVAGE flag is now set during VLRU demotion
4433 #ifndef AFS_DEMAND_ATTACH_FS
4434 static VolumeId *UpdateList = NULL; /* Pointer to array of Volume ID's */
4435 static int nUpdatedVolumes = 0; /* Updated with entry in UpdateList, salvage after crash flag on */
4436 static int updateSize = 0; /* number of entries possible */
4437 #define UPDATE_LIST_SIZE 128 /* initial size increment (must be a power of 2!) */
4438 #endif /* !AFS_DEMAND_ATTACH_FS */
4441 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
4444 vp->updateTime = FT_ApproxTime();
4445 if (V_dontSalvage(vp) == 0)
4447 V_dontSalvage(vp) = 0;
4448 VSyncVolume_r(ec, vp, 0);
4449 #ifdef AFS_DEMAND_ATTACH_FS
4450 V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
4451 #else /* !AFS_DEMAND_ATTACH_FS */
4454 if (UpdateList == NULL) {
4455 updateSize = UPDATE_LIST_SIZE;
4456 UpdateList = (VolumeId *) malloc(sizeof(VolumeId) * updateSize);
4458 if (nUpdatedVolumes == updateSize) {
4460 if (updateSize > 524288) {
4461 Log("warning: there is likely a bug in the volume update scanner\n");
4465 (VolumeId *) realloc(UpdateList,
4466 sizeof(VolumeId) * updateSize);
4469 assert(UpdateList != NULL);
4470 UpdateList[nUpdatedVolumes++] = V_id(vp);
4471 #endif /* !AFS_DEMAND_ATTACH_FS */
4474 #ifndef AFS_DEMAND_ATTACH_FS
4476 VScanUpdateList(void)
4478 register int i, gap;
4479 register Volume *vp;
4481 afs_uint32 now = FT_ApproxTime();
4482 /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
4483 for (i = gap = 0; i < nUpdatedVolumes; i++) {
4485 UpdateList[i - gap] = UpdateList[i];
4487 /* XXX this routine needlessly messes up the Volume LRU by
4488 * breaking the LRU temporal-locality assumptions.....
4489 * we should use a special volume header allocator here */
4490 vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
4493 } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
4494 V_dontSalvage(vp) = DONT_SALVAGE;
4495 VUpdateVolume_r(&error, vp, 0); /* No need to fsync--not critical */
4503 #ifndef AFS_PTHREAD_ENV
4505 #endif /* !AFS_PTHREAD_ENV */
4507 nUpdatedVolumes -= gap;
4509 #endif /* !AFS_DEMAND_ATTACH_FS */
4512 /***************************************************/
4513 /* Volume LRU routines */
4514 /***************************************************/
4519 * with demand attach fs, we attempt to soft detach(1)
4520 * volumes which have not been accessed in a long time
4521 * in order to speed up fileserver shutdown
4523 * (1) by soft detach we mean a process very similar
4524 * to VOffline, except the final state of the
4525 * Volume will be VOL_STATE_PREATTACHED, instead
4526 * of the usual VOL_STATE_UNATTACHED
4528 #ifdef AFS_DEMAND_ATTACH_FS
4530 /* implementation is reminiscent of a generational GC
4532 * queue 0 is newly attached volumes. this queue is
4533 * sorted by attach timestamp
4535 * queue 1 is volumes that have been around a bit
4536 * longer than queue 0. this queue is sorted by
4539 * queue 2 is volumes tha have been around the longest.
4540 * this queue is unsorted
4542 * queue 3 is volumes that have been marked as
4543 * candidates for soft detachment. this queue is
4546 #define VLRU_GENERATIONS 3 /* number of generations in VLRU */
4547 #define VLRU_QUEUES 5 /* total number of VLRU queues */
4549 volatile struct rx_queue q;
4555 struct VLRU_q q[VLRU_QUEUES];
4558 afs_uint32 promotion_interval[VLRU_GENERATIONS-1]; /* interval between promotions */
4559 afs_uint32 scan_interval[VLRU_GENERATIONS+1]; /* interval between scans for candidates */
4563 afs_uint32 last_promotion[VLRU_GENERATIONS-1]; /* timestamp of last promotion scan */
4564 afs_uint32 last_scan[VLRU_GENERATIONS+1]; /* timestamp of last detach scan */
4566 int scanner_state; /* state of scanner thread */
4567 pthread_cond_t cv; /* state transition CV */
4570 static struct VLRU volume_LRU;
4572 /* valid scanner states */
4573 #define VLRU_SCANNER_STATE_OFFLINE 0
4574 #define VLRU_SCANNER_STATE_ONLINE 1
4575 #define VLRU_SCANNER_STATE_SHUTTING_DOWN 2
4576 #define VLRU_SCANNER_STATE_PAUSING 3
4577 #define VLRU_SCANNER_STATE_PAUSED 4
4579 /* vlru disk data header stuff */
4580 #define VLRU_DISK_MAGIC 0x7a8b9cad
4581 #define VLRU_DISK_VERSION 1
4583 /* vlru default expiration time (for eventual fs state serialization of vlru data) */
4584 #define VLRU_DUMP_EXPIRATION_TIME (60*60*24*7) /* expire vlru data after 1 week */
4587 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
4588 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
4589 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
4590 static afs_uint32 VLRU_enabled = 1;
4592 /* queue synchronization routines */
4593 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
4594 static void VLRU_EndExclusive_r(struct VLRU_q * q);
4595 static void VLRU_Wait_r(struct VLRU_q * q);
4597 /* set the VLRU parameters
4599 * valid options are:
4600 * VLRU_SET_THRESH -- set the period of inactivity after
4601 * which volumes are eligible for being detached
4602 * VLRU_SET_INTERVAL -- the time interval between calls
4603 * to the volume LRU "garbage collector"
4604 * VLRU_SET_MAX -- the max number of volumes to deallocate
4608 VLRU_SetOptions(int option, afs_uint32 val)
4610 if (option == VLRU_SET_THRESH) {
4611 VLRU_offline_thresh = val;
4612 } else if (option == VLRU_SET_INTERVAL) {
4613 VLRU_offline_interval = val;
4614 } else if (option == VLRU_SET_MAX) {
4615 VLRU_offline_max = val;
4616 } else if (option == VLRU_SET_ENABLED) {
4619 VLRU_ComputeConstants();
4622 /* compute the VLRU internal timing parameters based upon the user's inputs */
4624 VLRU_ComputeConstants(void)
4626 afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
4628 /* compute the candidate scan interval */
4629 volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
4631 /* compute the promotion intervals */
4632 volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
4633 volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
4636 /* compute the gen 0 scan interval */
4637 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
4639 /* compute the gen 0 scan interval */
4640 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
4644 /* initialize VLRU */
4649 pthread_attr_t attrs;
4652 if (!VLRU_enabled) {
4653 Log("VLRU: disabled\n");
4657 /* initialize each of the VLRU queues */
4658 for (i = 0; i < VLRU_QUEUES; i++) {
4659 queue_Init(&volume_LRU.q[i]);
4660 volume_LRU.q[i].len = 0;
4661 volume_LRU.q[i].busy = 0;
4662 assert(pthread_cond_init(&volume_LRU.q[i].cv, NULL) == 0);
4665 /* setup the timing constants */
4666 VLRU_ComputeConstants();
4668 /* XXX put inside LogLevel check? */
4669 Log("VLRU: starting scanner with the following configuration parameters:\n");
4670 Log("VLRU: offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
4671 Log("VLRU: running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
4672 Log("VLRU: taking up to %d volumes offline per pass\n", VLRU_offline_max);
4673 Log("VLRU: scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
4674 Log("VLRU: scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
4675 Log("VLRU: scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
4677 /* start up the VLRU scanner */
4678 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
4679 if (programType == fileServer) {
4680 assert(pthread_cond_init(&volume_LRU.cv, NULL) == 0);
4681 assert(pthread_attr_init(&attrs) == 0);
4682 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
4683 assert(pthread_create(&tid, &attrs, &VLRU_ScannerThread, NULL) == 0);
4687 /* initialize LRU support for a volume */
4689 VLRU_Init_Node_r(volatile Volume * vp)
4694 assert(queue_IsNotOnQueue(&vp->vlru));
4695 vp->vlru.idx = VLRU_QUEUE_INVALID;
4698 /* add volume to VLRU
4699 * now supports adding to queues other
4700 * than new for vlru state restore
4701 * caller MUST hold a ref count on vp */
4703 VLRU_Add_r(volatile Volume * vp)
4710 if (queue_IsOnQueue(&vp->vlru))
4713 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
4715 /* repeat check since VLRU_Wait_r may have dropped
4717 if (queue_IsNotOnQueue(&vp->vlru)) {
4719 if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
4720 idx = vp->vlru.idx = VLRU_QUEUE_NEW;
4722 queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
4723 volume_LRU.q[idx].len++;
4724 V_attachFlags(vp) |= VOL_ON_VLRU;
4725 vp->stats.last_promote = FT_ApproxTime();
4729 /* delete volume from VLRU
4730 * caller MUST hold a ref count on vp */
4732 VLRU_Delete_r(volatile Volume * vp)
4739 if (queue_IsNotOnQueue(&vp->vlru))
4745 if (idx == VLRU_QUEUE_INVALID)
4747 VLRU_Wait_r(&volume_LRU.q[idx]);
4748 } while (idx != vp->vlru.idx);
4750 /* now remove from the VLRU and update
4751 * the appropriate counter */
4752 queue_Remove(&vp->vlru);
4753 volume_LRU.q[idx].len--;
4754 vp->vlru.idx = VLRU_QUEUE_INVALID;
4755 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
4758 /* signal that volume was just accessed.
4759 * caller MUST hold a ref count on vp */
4761 VLRU_UpdateAccess_r(volatile Volume * vp)
4763 afs_uint32 live_interval;
4764 Volume * rvp = NULL;
4769 if (queue_IsNotOnQueue(&vp->vlru))
4772 assert(V_attachFlags(vp) & VOL_ON_VLRU);
4774 /* update the access timestamp */
4775 vp->stats.last_get = FT_ApproxTime();
4778 * if the volume is on the soft detach candidate
4779 * list, we need to safely move it back to a
4780 * regular generation. this has to be done
4781 * carefully so we don't race against the scanner
4785 /* if this volume is on the soft detach candidate queue,
4786 * then grab exclusive access to the necessary queues */
4787 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
4789 VCreateReservation_r(rvp);
4791 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
4792 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
4793 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
4794 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
4797 /* make sure multiple threads don't race to update */
4798 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
4799 VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
4803 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
4804 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
4805 VCancelReservation_r(rvp);
4809 /* switch a volume between two VLRU queues */
4811 VLRU_SwitchQueues(volatile Volume * vp, int new_idx, int append)
4813 if (queue_IsNotOnQueue(&vp->vlru))
4816 queue_Remove(&vp->vlru);
4817 volume_LRU.q[vp->vlru.idx].len--;
4819 /* put the volume back on the correct generational queue */
4821 queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
4823 queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
4826 volume_LRU.q[new_idx].len++;
4827 vp->vlru.idx = new_idx;
4830 /* VLRU GC thread */
4832 VLRU_ScannerThread(void * args)
4834 afs_uint32 now, min_delay, delay;
4835 afs_uint32 next_scan[VLRU_GENERATIONS];
4836 afs_uint32 next_promotion[VLRU_GENERATIONS];
4837 int i, min_idx, min_op, overdue, state;
4839 /* set t=0 for promotion cycle to be
4840 * fileserver startup */
4841 now = FT_ApproxTime();
4842 for (i=0; i < VLRU_GENERATIONS-1; i++) {
4843 volume_LRU.last_promotion[i] = now;
4846 /* don't start the scanner until VLRU_offline_thresh
4847 * plus a small delay for VInitVolumePackage to finish
4850 sleep(VLRU_offline_thresh + 60);
4852 /* set t=0 for scan cycle to be now */
4853 now = FT_ApproxTime();
4854 for (i=0; i < VLRU_GENERATIONS+1; i++) {
4855 volume_LRU.last_scan[i] = now;
4859 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
4860 volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
4863 while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
4864 /* check to see if we've been asked to pause */
4865 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
4866 volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
4867 assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
4869 assert(pthread_cond_wait(&volume_LRU.cv, &vol_glock_mutex) == 0);
4870 } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
4873 /* scheduling can happen outside the glock */
4876 /* figure out what is next on the schedule */
4878 /* figure out a potential schedule for the new generation first */
4880 min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
4883 if (min_delay > volume_LRU.scan_interval[0]) {
4884 /* unsigned overflow -- we're overdue to run this scan */
4889 /* if we're not overdue for gen 0, figure out schedule for candidate gen */
4891 i = VLRU_QUEUE_CANDIDATE;
4892 delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
4893 if (delay < min_delay) {
4897 if (delay > volume_LRU.scan_interval[i]) {
4898 /* unsigned overflow -- we're overdue to run this scan */
4906 /* if we're still not overdue for something, figure out schedules for promotions */
4907 for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
4908 delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
4909 if (delay < min_delay) {
4914 if (delay > volume_LRU.promotion_interval[i]) {
4915 /* unsigned overflow -- we're overdue to run this promotion */
4924 /* sleep as needed */
4929 /* do whatever is next */
4932 VLRU_Promote_r(min_idx);
4933 VLRU_Demote_r(min_idx+1);
4935 VLRU_Scan_r(min_idx);
4937 now = FT_ApproxTime();
4940 Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
4942 /* signal that scanner is down */
4943 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
4944 assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
4949 /* run the promotions */
4951 VLRU_Promote_r(int idx)
4953 int len, chaining, promote;
4954 afs_uint32 now, thresh;
4955 struct rx_queue *qp, *nqp;
4956 Volume * vp, *start, *end;
4958 /* get exclusive access to two chains, and drop the glock */
4959 VLRU_Wait_r(&volume_LRU.q[idx]);
4960 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
4961 VLRU_Wait_r(&volume_LRU.q[idx+1]);
4962 VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
4965 thresh = volume_LRU.promotion_interval[idx];
4966 now = FT_ApproxTime();
4969 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
4970 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
4971 promote = (((vp->stats.last_promote + thresh) <= now) &&
4972 (vp->stats.last_get >= vp->stats.last_promote));
4980 /* promote and prepend chain */
4981 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
4995 /* promote and prepend */
4996 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
5000 volume_LRU.q[idx].len -= len;
5001 volume_LRU.q[idx+1].len += len;
5004 /* release exclusive access to the two chains */
5006 volume_LRU.last_promotion[idx] = now;
5007 VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
5008 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
5011 /* run the demotions */
5013 VLRU_Demote_r(int idx)
5016 int len, chaining, demote;
5017 afs_uint32 now, thresh;
5018 struct rx_queue *qp, *nqp;
5019 Volume * vp, *start, *end;
5020 Volume ** salv_flag_vec = NULL;
5021 int salv_vec_offset = 0;
5023 assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
5025 /* get exclusive access to two chains, and drop the glock */
5026 VLRU_Wait_r(&volume_LRU.q[idx-1]);
5027 VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
5028 VLRU_Wait_r(&volume_LRU.q[idx]);
5029 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
5032 /* no big deal if this allocation fails */
5033 if (volume_LRU.q[idx].len) {
5034 salv_flag_vec = (Volume **) malloc(volume_LRU.q[idx].len * sizeof(Volume *));
5037 now = FT_ApproxTime();
5038 thresh = volume_LRU.promotion_interval[idx-1];
5041 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
5042 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
5043 demote = (((vp->stats.last_promote + thresh) <= now) &&
5044 (vp->stats.last_get < (now - thresh)));
5046 /* we now do volume update list DONT_SALVAGE flag setting during
5047 * demotion passes */
5048 if (salv_flag_vec &&
5049 !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
5051 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
5052 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
5053 salv_flag_vec[salv_vec_offset++] = vp;
5054 VCreateReservation_r(vp);
5063 /* demote and append chain */
5064 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
5078 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
5082 volume_LRU.q[idx].len -= len;
5083 volume_LRU.q[idx-1].len += len;
5086 /* release exclusive access to the two chains */
5088 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
5089 VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
5091 /* now go back and set the DONT_SALVAGE flags as appropriate */
5092 if (salv_flag_vec) {
5094 for (i = 0; i < salv_vec_offset; i++) {
5095 vp = salv_flag_vec[i];
5096 if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
5097 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
5098 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
5101 V_attachFlags(vp) |= VOL_HDR_DONTSALV;
5102 V_dontSalvage(vp) = DONT_SALVAGE;
5103 VUpdateVolume_r(&ec, vp, 0);
5107 VCancelReservation_r(vp);
5109 free(salv_flag_vec);
5113 /* run a pass of the VLRU GC scanner */
5115 VLRU_Scan_r(int idx)
5117 afs_uint32 now, thresh;
5118 struct rx_queue *qp, *nqp;
5119 volatile Volume * vp;
5122 assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
5124 /* gain exclusive access to the idx VLRU */
5125 VLRU_Wait_r(&volume_LRU.q[idx]);
5126 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
5128 if (idx != VLRU_QUEUE_CANDIDATE) {
5129 /* gain exclusive access to the candidate VLRU */
5130 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5131 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5134 now = FT_ApproxTime();
5135 thresh = now - VLRU_offline_thresh;
5137 /* perform candidate selection and soft detaching */
5138 if (idx == VLRU_QUEUE_CANDIDATE) {
5139 /* soft detach some volumes from the candidate pool */
5143 for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
5144 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
5145 if (i >= VLRU_offline_max) {
5148 /* check timestamp to see if it's a candidate for soft detaching */
5149 if (vp->stats.last_get <= thresh) {
5151 if (VCheckSoftDetach(vp, thresh))
5157 /* scan for volumes to become soft detach candidates */
5158 for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
5159 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
5161 /* check timestamp to see if it's a candidate for soft detaching */
5162 if (vp->stats.last_get <= thresh) {
5163 VCheckSoftDetachCandidate(vp, thresh);
5166 if (!(i&0x7f)) { /* lock coarsening optimization */
5174 /* relinquish exclusive access to the VLRU chains */
5178 volume_LRU.last_scan[idx] = now;
5179 if (idx != VLRU_QUEUE_CANDIDATE) {
5180 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5182 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
5185 /* check whether volume is safe to soft detach
5186 * caller MUST NOT hold a ref count on vp */
5188 VCheckSoftDetach(volatile Volume * vp, afs_uint32 thresh)
5192 if (vp->nUsers || vp->nWaiters)
5195 if (vp->stats.last_get <= thresh) {
5196 ret = VSoftDetachVolume_r(vp, thresh);
5202 /* check whether volume should be made a
5203 * soft detach candidate */
5205 VCheckSoftDetachCandidate(volatile Volume * vp, afs_uint32 thresh)
5208 if (vp->nUsers || vp->nWaiters)
5213 assert(idx == VLRU_QUEUE_NEW);
5215 if (vp->stats.last_get <= thresh) {
5216 /* move to candidate pool */
5217 queue_Remove(&vp->vlru);
5218 volume_LRU.q[VLRU_QUEUE_NEW].len--;
5219 queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
5220 vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
5221 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
5229 /* begin exclusive access on VLRU */
5231 VLRU_BeginExclusive_r(struct VLRU_q * q)
5233 assert(q->busy == 0);
5237 /* end exclusive access on VLRU */
5239 VLRU_EndExclusive_r(struct VLRU_q * q)
5243 assert(pthread_cond_broadcast(&q->cv) == 0);
5246 /* wait for another thread to end exclusive access on VLRU */
5248 VLRU_Wait_r(struct VLRU_q * q)
5251 assert(pthread_cond_wait(&q->cv, &vol_glock_mutex) == 0);
5256 * volume soft detach
5258 * caller MUST NOT hold a ref count on vp */
5260 VSoftDetachVolume_r(volatile Volume * vp, afs_uint32 thresh)
5265 assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
5267 ts_save = vp->stats.last_get;
5268 if (ts_save > thresh)
5271 if (vp->nUsers || vp->nWaiters)
5274 if (IsExclusiveState(V_attachState(vp))) {
5278 switch (V_attachState(vp)) {
5279 case VOL_STATE_UNATTACHED:
5280 case VOL_STATE_PREATTACHED:
5281 case VOL_STATE_ERROR:
5282 case VOL_STATE_GOING_OFFLINE:
5283 case VOL_STATE_SHUTTING_DOWN:
5284 case VOL_STATE_SALVAGING:
5285 volume_LRU.q[vp->vlru.idx].len--;
5287 /* create and cancel a reservation to
5288 * give the volume an opportunity to
5290 VCreateReservation_r(vp);
5291 queue_Remove(&vp->vlru);
5292 vp->vlru.idx = VLRU_QUEUE_INVALID;
5293 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
5294 VCancelReservation_r(vp);
5298 /* hold the volume and take it offline.
5299 * no need for reservations, as VHold_r
5300 * takes care of that internally. */
5301 if (VHold_r(vp) == 0) {
5302 /* vhold drops the glock, so now we should
5303 * check to make sure we aren't racing against
5304 * other threads. if we are racing, offlining vp
5305 * would be wasteful, and block the scanner for a while
5309 (vp->shuttingDown) ||
5310 (vp->goingOffline) ||
5311 (vp->stats.last_get != ts_save)) {
5312 /* looks like we're racing someone else. bail */
5316 /* pull it off the VLRU */
5317 assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
5318 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
5319 queue_Remove(&vp->vlru);
5320 vp->vlru.idx = VLRU_QUEUE_INVALID;
5321 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
5323 /* take if offline */
5324 VOffline_r(vp, "volume has been soft detached");
5326 /* invalidate the volume header cache */
5327 FreeVolumeHeader(vp);
5330 IncUInt64(&VStats.soft_detaches);
5331 vp->stats.soft_detaches++;
5333 /* put in pre-attached state so demand
5334 * attacher can work on it */
5335 VChangeState_r(vp, VOL_STATE_PREATTACHED);
5341 #endif /* AFS_DEMAND_ATTACH_FS */
5344 /***************************************************/
5345 /* Volume Header Cache routines */
5346 /***************************************************/
5348 struct volume_hdr_LRU_t volume_hdr_LRU;
5350 /* Allocate a bunch of headers; string them together */
5352 VInitVolumeHeaderCache(afs_uint32 howMany)
5354 register struct volHeader *hp;
5355 if (programType != fileServer)
5357 queue_Init(&volume_hdr_LRU);
5358 #ifdef AFS_DEMAND_ATTACH_FS
5359 volume_hdr_LRU.stats.free = 0;
5360 volume_hdr_LRU.stats.used = howMany;
5361 volume_hdr_LRU.stats.attached = 0;
5363 hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
5365 ReleaseVolumeHeader(hp++);
5368 #ifdef AFS_DEMAND_ATTACH_FS
5369 /* Get a volume header from the LRU list; update the old one if necessary */
5370 /* Returns 1 if there was already a header, which is removed from the LRU list */
5371 /* caller MUST has a ref count on vp */
5373 GetVolumeHeader(register Volume * vp)
5376 register struct volHeader *hd;
5378 static int everLogged = 0;
5380 /* XXX debug 9/19/05 we've apparently got
5381 * a ref counting bug somewhere that's
5382 * breaking the nUsers == 0 => header on LRU
5384 if (vp->header && queue_IsNotOnQueue(vp->header)) {
5385 Log("nUsers == 0, but header not on LRU\n");
5389 old = (vp->header != NULL); /* old == volume already has a header */
5391 if (programType != fileServer) {
5392 /* for volume utilities, we allocate volHeaders as needed */
5394 hd = (struct volHeader *)calloc(1, sizeof(*vp->header));
5398 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
5402 /* the header we previously dropped in the lru is
5403 * still available. pull it off the lru and return */
5406 assert(hd->back == vp);
5408 /* we need to grab a new element off the LRU */
5409 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
5410 /* grab an element and pull off of LRU */
5411 hd = queue_First(&volume_hdr_LRU, volHeader);
5414 /* LRU is empty, so allocate a new volHeader
5415 * this is probably indicative of a leak, so let the user know */
5416 hd = (struct volHeader *)calloc(1, sizeof(struct volHeader));
5419 Log("****Allocated more volume headers, probably leak****\n");
5422 volume_hdr_LRU.stats.free++;
5425 VolState vp_save, back_save;
5426 /* this header used to belong to someone else.
5427 * we'll need to check if the header needs to
5428 * be sync'd out to disk */
5430 /* if hd->back were in an exclusive state, then
5431 * its volHeader would not be on the LRU... */
5432 assert(!IsExclusiveState(V_attachState(hd->back)));
5434 if (hd->diskstuff.inUse) {
5435 /* volume was in use, so we'll need to sync
5436 * its header to disk */
5437 back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
5438 vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
5439 VCreateReservation_r(hd->back);
5442 WriteVolumeHeader_r(&error, hd->back);
5443 /* Ignore errors; catch them later */
5448 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
5449 hd->back->header = NULL;
5451 if (hd->diskstuff.inUse) {
5452 VChangeState_r(hd->back, back_save);
5453 VCancelReservation_r(hd->back);
5454 VChangeState_r(vp, vp_save);
5457 volume_hdr_LRU.stats.attached++;
5461 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
5463 volume_hdr_LRU.stats.free--;
5464 volume_hdr_LRU.stats.used++;
5466 IncUInt64(&VStats.hdr_gets);
5467 IncUInt64(&vp->stats.hdr_gets);
5468 vp->stats.last_hdr_get = FT_ApproxTime();
5471 #else /* AFS_DEMAND_ATTACH_FS */
5472 /* Get a volume header from the LRU list; update the old one if necessary */
5473 /* Returns 1 if there was already a header, which is removed from the LRU list */
5475 GetVolumeHeader(register Volume * vp)
5478 register struct volHeader *hd;
5480 static int everLogged = 0;
5482 old = (vp->header != NULL); /* old == volume already has a header */
5484 if (programType != fileServer) {
5485 /* for volume utilities, we allocate volHeaders as needed */
5487 hd = (struct volHeader *)calloc(1, sizeof(*vp->header));
5493 /* for the fileserver, we keep a volume header cache */
5495 /* the header we previously dropped in the lru is
5496 * still available. pull it off the lru and return */
5499 assert(hd->back == vp);
5501 /* we need to grab a new element off the LRU */
5502 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
5503 /* grab an element */
5504 hd = queue_First(&volume_hdr_LRU, volHeader);
5507 /* LRU is empty, so allocate a new volHeader
5508 * this is probably indicative of a leak, so let the user know */
5509 hd = (struct volHeader *)calloc(1, sizeof(struct volHeader));
5512 Log("****Allocated more volume headers, probably leak****\n");
5517 /* this header used to belong to someone else.
5518 * we'll need to check if the header needs to
5519 * be sync'd out to disk */
5521 if (hd->diskstuff.inUse) {
5522 WriteVolumeHeader_r(&error, hd->back);
5523 /* Ignore errors; catch them later */
5525 hd->back->header = NULL;
5533 #endif /* AFS_DEMAND_ATTACH_FS */
5536 /* make sure a volume header is attached to
5537 * vp, and has the correct data loaded from
5539 #ifdef AFS_DEMAND_ATTACH_FS
5540 /* caller MUST hold a ref count on vp */
5542 LoadVolumeHeader(Error * ec, Volume * vp)
5544 VolState state_save;
5547 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
5548 IncUInt64(&VStats.hdr_loads);
5549 state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
5552 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
5553 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
5555 IncUInt64(&vp->stats.hdr_loads);
5559 V_attachFlags(vp) |= VOL_HDR_LOADED;
5560 VChangeState_r(vp, state_save);
5563 /* maintain (nUsers==0) => header in LRU invariant */
5564 ReleaseVolumeHeader(vp->header);
5567 #else /* AFS_DEMAND_ATTACH_FS */
5569 LoadVolumeHeader(Error * ec, Volume * vp)
5572 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
5573 IncUInt64(&VStats.hdr_loads);
5575 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
5576 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
5580 /* maintain (nUsers==0) => header in LRU invariant */
5581 ReleaseVolumeHeader(vp->header);
5584 #endif /* AFS_DEMAND_ATTACH_FS */
5586 /* Put it at the top of the LRU chain */
5588 ReleaseVolumeHeader(register struct volHeader *hd)
5590 if (programType != fileServer)
5592 if (!hd || queue_IsOnQueue(hd)) /* no header, or header already released */
5594 queue_Append(&volume_hdr_LRU, hd);
5595 #ifdef AFS_DEMAND_ATTACH_FS
5597 V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
5599 volume_hdr_LRU.stats.free++;
5600 volume_hdr_LRU.stats.used--;
5604 /* for fileserver, return header to LRU, and
5605 * invalidate it as a cache entry.
5607 * for volume utilities, free the heap space */
5609 FreeVolumeHeader(register Volume * vp)
5611 register struct volHeader *hd = vp->header;
5614 if (programType == fileServer) {
5615 ReleaseVolumeHeader(hd);
5620 #ifdef AFS_DEMAND_ATTACH_FS
5621 V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
5622 volume_hdr_LRU.stats.attached--;
5628 /***************************************************/
5629 /* Volume Hash Table routines */
5630 /***************************************************/
5633 VSetVolHashSize(int logsize)
5635 /* 64 to 16384 hash buckets seems like a reasonable range */
5636 if ((logsize < 6 ) || (logsize > 14)) {
5641 VolumeHashTable.Size = 1 << logsize;
5642 VolumeHashTable.Mask = VolumeHashTable.Size - 1;
5644 /* we can't yet support runtime modification of this
5645 * parameter. we'll need a configuration rwlock to
5646 * make runtime modification feasible.... */
5653 VInitVolumeHash(void)
5657 VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
5658 sizeof(VolumeHashChainHead));
5659 assert(VolumeHashTable.Table != NULL);
5661 for (i=0; i < VolumeHashTable.Size; i++) {
5662 queue_Init(&VolumeHashTable.Table[i]);
5663 #ifdef AFS_DEMAND_ATTACH_FS
5664 assert(pthread_cond_init(&VolumeHashTable.Table[i].chain_busy_cv, NULL) == 0);
5665 #endif /* AFS_DEMAND_ATTACH_FS */
5669 /* for demand-attach, caller MUST hold a ref count on vp */
5671 AddVolumeToHashTable(register Volume * vp, int hashid)
5673 VolumeHashChainHead * head;
5675 if (queue_IsOnQueue(vp))
5678 head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
5680 #ifdef AFS_DEMAND_ATTACH_FS
5681 /* wait for the hash chain to become available */
5684 V_attachFlags(vp) |= VOL_IN_HASH;
5685 vp->chainCacheCheck = ++head->cacheCheck;
5686 #endif /* AFS_DEMAND_ATTACH_FS */
5689 vp->hashid = hashid;
5690 queue_Append(head, vp);
5691 vp->vnodeHashOffset = VolumeHashOffset_r();
5694 /* for demand-attach, caller MUST hold a ref count on vp */
5696 DeleteVolumeFromHashTable(register Volume * vp)
5698 VolumeHashChainHead * head;
5700 if (!queue_IsOnQueue(vp))
5703 head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
5705 #ifdef AFS_DEMAND_ATTACH_FS
5706 /* wait for the hash chain to become available */
5709 V_attachFlags(vp) &= ~(VOL_IN_HASH);
5711 #endif /* AFS_DEMAND_ATTACH_FS */
5715 /* do NOT reset hashid to zero, as the online
5716 * salvager package may need to know the volume id
5717 * after the volume is removed from the hash */
5720 /* - look up a volume id in the hash table
5721 * - occasionally rebalance hash chains
5722 * - update lookup statistics accordingly
5724 /* the hint parameter allows us to short-circuit on
5725 * DEMAND_ATTACH_FS if the cacheChecks match between
5726 * the hash chain head and hint
5727 * caller MUST hold a refcount on hint */
5729 VLookupVolume_r(Error * ec, VolId volumeId, Volume * hint)
5731 register int looks = 0;
5732 Volume * vp, *np, *pp;
5733 VolumeHashChainHead * head;
5736 head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
5738 #ifdef AFS_DEMAND_ATTACH_FS
5739 /* wait for the hash chain to become available */
5742 /* check to see if we can short circuit without walking the hash chain */
5743 if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
5744 IncUInt64(&hint->stats.hash_short_circuits);
5747 #endif /* AFS_DEMAND_ATTACH_FS */
5749 /* someday we need to either do per-chain locks, RWlocks,
5750 * or both for volhash access.
5751 * (and move to a data structure with better cache locality) */
5753 /* search the chain for this volume id */
5754 for(queue_Scan(head, vp, np, Volume)) {
5756 if ((vp->hashid == volumeId)) {
5761 if (queue_IsEnd(head, vp)) {
5765 #ifdef AFS_DEMAND_ATTACH_FS
5766 /* update hash chain statistics */
5769 FillInt64(lks, 0, looks);
5770 AddUInt64(head->looks, lks, &head->looks);
5771 AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
5772 IncUInt64(&head->gets);
5777 IncUInt64(&vp->stats.hash_lookups);
5779 /* for demand attach fileserver, we permit occasional hash chain reordering
5780 * so that frequently looked up volumes move towards the head of the chain */
5781 pp = queue_Prev(vp, Volume);
5782 if (!queue_IsEnd(head, pp)) {
5783 FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
5784 AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
5785 if (GEInt64(vp->stats.hash_lookups, thresh)) {
5786 VReorderHash_r(head, pp, vp);
5790 /* update the short-circuit cache check */
5791 vp->chainCacheCheck = head->cacheCheck;
5793 #endif /* AFS_DEMAND_ATTACH_FS */
5798 #ifdef AFS_DEMAND_ATTACH_FS
5799 /* perform volume hash chain reordering.
5801 * advance a subchain beginning at vp ahead of
5802 * the adjacent subchain ending at pp */
5804 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
5806 Volume *tp, *np, *lp;
5807 afs_uint64 move_thresh;
5809 /* this should never be called if the chain is already busy, so
5810 * no need to wait for other exclusive chain ops to finish */
5812 /* this is a rather heavy set of operations,
5813 * so let's set the chain busy flag and drop
5815 VHashBeginExclusive_r(head);
5818 /* scan forward in the chain from vp looking for the last element
5819 * in the chain we want to advance */
5820 FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
5821 AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
5822 for(queue_ScanFrom(head, vp, tp, np, Volume)) {
5823 if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
5827 lp = queue_Prev(tp, Volume);
5829 /* scan backwards from pp to determine where to splice and
5830 * insert the subchain we're advancing */
5831 for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
5832 if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
5836 tp = queue_Next(tp, Volume);
5838 /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
5839 queue_MoveChainBefore(tp,vp,lp);
5842 IncUInt64(&VStats.hash_reorders);
5844 IncUInt64(&head->reorders);
5846 /* wake up any threads waiting for the hash chain */
5847 VHashEndExclusive_r(head);
5851 /* demand-attach fs volume hash
5852 * asynchronous exclusive operations */
5854 /* take exclusive control over the hash chain */
5856 VHashBeginExclusive_r(VolumeHashChainHead * head)
5858 assert(head->busy == 0);
5862 /* relinquish exclusive control over the hash chain */
5864 VHashEndExclusive_r(VolumeHashChainHead * head)
5868 assert(pthread_cond_broadcast(&head->chain_busy_cv) == 0);
5871 /* wait for another thread to finish its exclusive ops */
5873 VHashWait_r(VolumeHashChainHead * head)
5875 while (head->busy) {
5876 assert(pthread_cond_wait(&head->chain_busy_cv, &vol_glock_mutex) == 0);
5879 #endif /* AFS_DEMAND_ATTACH_FS */
5882 /***************************************************/
5883 /* Volume by Partition List routines */
5884 /***************************************************/
5887 * demand attach fileserver adds a
5888 * linked list of volumes to each
5889 * partition object, thus allowing
5890 * for quick enumeration of all
5891 * volumes on a partition
5894 #ifdef AFS_DEMAND_ATTACH_FS
5896 AddVolumeToVByPList_r(Volume * vp)
5898 if (queue_IsNotOnQueue(&vp->vol_list)) {
5899 queue_Append(&vp->partition->vol_list, &vp->vol_list);
5900 V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
5901 vp->partition->vol_list.len++;
5906 DeleteVolumeFromVByPList_r(Volume * vp)
5908 if (queue_IsOnQueue(&vp->vol_list)) {
5909 queue_Remove(&vp->vol_list);
5910 V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
5911 vp->partition->vol_list.len--;
5915 /* take exclusive control over the list */
5917 VVByPListBeginExclusive_r(struct DiskPartition * dp)
5919 assert(dp->vol_list.busy == 0);
5920 dp->vol_list.busy = 1;
5923 /* relinquish exclusive control over the list */
5925 VVByPListEndExclusive_r(struct DiskPartition * dp)
5927 assert(dp->vol_list.busy);
5928 dp->vol_list.busy = 0;
5929 assert(pthread_cond_broadcast(&dp->vol_list.cv) == 0);
5932 /* wait for another thread to finish its exclusive ops */
5934 VVByPListWait_r(struct DiskPartition * dp)
5936 while (dp->vol_list.busy) {
5937 assert(pthread_cond_wait(&dp->vol_list.cv, &vol_glock_mutex) == 0);
5940 #endif /* AFS_DEMAND_ATTACH_FS */
5942 /***************************************************/
5943 /* Volume Cache Statistics routines */
5944 /***************************************************/
5947 VPrintCacheStats_r(void)
5949 afs_uint32 get_hi, get_lo, load_hi, load_lo;
5950 register struct VnodeClassInfo *vcp;
5951 vcp = &VnodeClassInfo[vLarge];
5952 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);
5953 vcp = &VnodeClassInfo[vSmall];
5954 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);
5955 SplitInt64(VStats.hdr_gets, get_hi, get_lo);
5956 SplitInt64(VStats.hdr_loads, load_hi, load_lo);
5957 Log("Volume header cache, %d entries, %d gets, %d replacements\n",
5958 VStats.hdr_cache_size, get_lo, load_lo);
5962 VPrintCacheStats(void)
5965 VPrintCacheStats_r();
5969 #ifdef AFS_DEMAND_ATTACH_FS
5971 UInt64ToDouble(afs_uint64 * x)
5973 static double c32 = 4.0 * 1.073741824 * 1000000000.0;
5975 SplitInt64(*x, h, l);
5976 return (((double)h) * c32) + ((double) l);
5980 DoubleToPrintable(double x, char * buf, int len)
5982 static double billion = 1000000000.0;
5985 y[0] = (afs_uint32) (x / (billion * billion));
5986 y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
5987 y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
5990 snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
5992 snprintf(buf, len, "%d%09d", y[1], y[2]);
5994 snprintf(buf, len, "%d", y[2]);
6001 VPrintExtendedCacheStats_r(int flags)
6010 struct stats looks, gets, reorders, len;
6011 struct stats ch_looks, ch_gets, ch_reorders;
6013 VolumeHashChainHead *head;
6016 /* zero out stats */
6017 memset(&looks, 0, sizeof(struct stats));
6018 memset(&gets, 0, sizeof(struct stats));
6019 memset(&reorders, 0, sizeof(struct stats));
6020 memset(&len, 0, sizeof(struct stats));
6021 memset(&ch_looks, 0, sizeof(struct stats));
6022 memset(&ch_gets, 0, sizeof(struct stats));
6023 memset(&ch_reorders, 0, sizeof(struct stats));
6025 for (i = 0; i < VolumeHashTable.Size; i++) {
6026 head = &VolumeHashTable.Table[i];
6029 VHashBeginExclusive_r(head);
6032 ch_looks.sum = UInt64ToDouble(&head->looks);
6033 ch_gets.sum = UInt64ToDouble(&head->gets);
6034 ch_reorders.sum = UInt64ToDouble(&head->reorders);
6036 /* update global statistics */
6038 looks.sum += ch_looks.sum;
6039 gets.sum += ch_gets.sum;
6040 reorders.sum += ch_reorders.sum;
6041 len.sum += (double)head->len;
6044 len.min = (double) head->len;
6045 len.max = (double) head->len;
6046 looks.min = ch_looks.sum;
6047 looks.max = ch_looks.sum;
6048 gets.min = ch_gets.sum;
6049 gets.max = ch_gets.sum;
6050 reorders.min = ch_reorders.sum;
6051 reorders.max = ch_reorders.sum;
6053 if (((double)head->len) < len.min)
6054 len.min = (double) head->len;
6055 if (((double)head->len) > len.max)
6056 len.max = (double) head->len;
6057 if (ch_looks.sum < looks.min)
6058 looks.min = ch_looks.sum;
6059 else if (ch_looks.sum > looks.max)
6060 looks.max = ch_looks.sum;
6061 if (ch_gets.sum < gets.min)
6062 gets.min = ch_gets.sum;
6063 else if (ch_gets.sum > gets.max)
6064 gets.max = ch_gets.sum;
6065 if (ch_reorders.sum < reorders.min)
6066 reorders.min = ch_reorders.sum;
6067 else if (ch_reorders.sum > reorders.max)
6068 reorders.max = ch_reorders.sum;
6072 if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
6073 /* compute detailed per-chain stats */
6074 struct stats hdr_loads, hdr_gets;
6075 double v_looks, v_loads, v_gets;
6077 /* initialize stats with data from first element in chain */
6078 vp = queue_First(head, Volume);
6079 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
6080 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
6081 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
6082 ch_gets.min = ch_gets.max = v_looks;
6083 hdr_loads.min = hdr_loads.max = v_loads;
6084 hdr_gets.min = hdr_gets.max = v_gets;
6085 hdr_loads.sum = hdr_gets.sum = 0;
6087 vp = queue_Next(vp, Volume);
6089 /* pull in stats from remaining elements in chain */
6090 for (queue_ScanFrom(head, vp, vp, np, Volume)) {
6091 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
6092 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
6093 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
6095 hdr_loads.sum += v_loads;
6096 hdr_gets.sum += v_gets;
6098 if (v_looks < ch_gets.min)
6099 ch_gets.min = v_looks;
6100 else if (v_looks > ch_gets.max)
6101 ch_gets.max = v_looks;
6103 if (v_loads < hdr_loads.min)
6104 hdr_loads.min = v_loads;
6105 else if (v_loads > hdr_loads.max)
6106 hdr_loads.max = v_loads;
6108 if (v_gets < hdr_gets.min)
6109 hdr_gets.min = v_gets;
6110 else if (v_gets > hdr_gets.max)
6111 hdr_gets.max = v_gets;
6114 /* compute per-chain averages */
6115 ch_gets.avg = ch_gets.sum / ((double)head->len);
6116 hdr_loads.avg = hdr_loads.sum / ((double)head->len);
6117 hdr_gets.avg = hdr_gets.sum / ((double)head->len);
6119 /* dump per-chain stats */
6120 Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
6122 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
6123 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
6124 Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
6125 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
6126 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
6127 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
6128 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
6129 Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
6130 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
6131 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
6132 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
6133 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
6134 Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
6135 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
6136 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
6137 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
6138 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
6139 } else if (flags & VOL_STATS_PER_CHAIN) {
6140 /* dump simple per-chain stats */
6141 Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
6143 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
6144 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
6145 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
6149 VHashEndExclusive_r(head);
6154 /* compute global averages */
6155 len.avg = len.sum / ((double)VolumeHashTable.Size);
6156 looks.avg = looks.sum / ((double)VolumeHashTable.Size);
6157 gets.avg = gets.sum / ((double)VolumeHashTable.Size);
6158 reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
6160 /* dump global stats */
6161 Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
6162 Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
6163 DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
6164 DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
6165 DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
6166 DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
6167 Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
6168 DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
6169 DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
6170 DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
6171 DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
6172 Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
6173 DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
6174 DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
6175 DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
6176 DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
6177 Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
6178 DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
6179 DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
6180 DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
6181 DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
6183 /* print extended disk related statistics */
6185 struct DiskPartition * diskP;
6186 afs_uint32 vol_count[VOLMAXPARTS+1];
6187 byte part_exists[VOLMAXPARTS+1];
6191 memset(vol_count, 0, sizeof(vol_count));
6192 memset(part_exists, 0, sizeof(part_exists));
6196 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
6198 vol_count[id] = diskP->vol_list.len;
6199 part_exists[id] = 1;
6203 for (i = 0; i <= VOLMAXPARTS; i++) {
6204 if (part_exists[i]) {
6205 diskP = VGetPartitionById_r(i, 0);
6207 Log("Partition %s has %d online volumes\n",
6208 VPartitionPath(diskP), diskP->vol_list.len);
6218 VPrintExtendedCacheStats(int flags)
6221 VPrintExtendedCacheStats_r(flags);
6224 #endif /* AFS_DEMAND_ATTACH_FS */