2 * Copyright 2000, International Business Machines Corporation and others.
5 * This software has been released under the terms of the IBM Public
6 * License. For details, see the LICENSE file in the top-level source
7 * directory or online at http://www.openafs.org/dl/license10.html
9 * Portions Copyright (c) 2005-2008 Sine Nomine Associates
12 /* 1/1/89: NB: this stuff is all going to be replaced. Don't take it too seriously */
17 Institution: The Information Technology Center, Carnegie-Mellon University
21 #include <afsconfig.h>
22 #include <afs/param.h>
26 #include <afs/afsint.h>
30 #include <sys/param.h>
31 #if !defined(AFS_SGI_ENV)
34 #else /* AFS_OSF_ENV */
35 #ifdef AFS_VFSINCL_ENV
38 #include <sys/fs/ufs_fs.h>
40 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
41 #include <ufs/ufs/dinode.h>
42 #include <ufs/ffs/fs.h>
47 #else /* AFS_VFSINCL_ENV */
48 #if !defined(AFS_AIX_ENV) && !defined(AFS_LINUX20_ENV) && !defined(AFS_XBSD_ENV)
51 #endif /* AFS_VFSINCL_ENV */
52 #endif /* AFS_OSF_ENV */
53 #endif /* AFS_SGI_ENV */
54 #endif /* AFS_NT40_ENV */
72 #if defined(AFS_SUN_ENV) || defined(AFS_SUN5_ENV)
74 #include <sys/mnttab.h>
75 #include <sys/mntent.h>
81 #if defined(AFS_SGI_ENV)
86 #ifndef AFS_LINUX20_ENV
87 #include <fstab.h> /* Need to find in libc 5, present in libc 6 */
90 #endif /* AFS_SGI_ENV */
92 #endif /* AFS_HPUX_ENV */
96 #include <netinet/in.h>
100 #include <sys/time.h>
101 #endif /* ITIMER_REAL */
102 #endif /* AFS_NT40_ENV */
103 #if defined(AFS_SUN5_ENV) || defined(AFS_NT40_ENV) || defined(AFS_LINUX20_ENV)
110 #include <afs/errors.h>
113 #include <afs/afssyscalls.h>
115 #include <afs/afsutil.h>
119 #include "daemon_com.h"
121 #include "salvsync.h"
124 #include "partition.h"
125 #include "volume_inline.h"
126 #ifdef AFS_PTHREAD_ENV
128 #else /* AFS_PTHREAD_ENV */
129 #include "afs/assert.h"
130 #endif /* AFS_PTHREAD_ENV */
137 #if !defined(offsetof)
142 #define afs_stat stat64
143 #define afs_fstat fstat64
144 #define afs_open open64
145 #else /* !O_LARGEFILE */
146 #define afs_stat stat
147 #define afs_fstat fstat
148 #define afs_open open
149 #endif /* !O_LARGEFILE */
151 #ifdef AFS_PTHREAD_ENV
152 pthread_mutex_t vol_glock_mutex;
153 pthread_mutex_t vol_trans_mutex;
154 pthread_cond_t vol_put_volume_cond;
155 pthread_cond_t vol_sleep_cond;
156 pthread_cond_t vol_init_attach_cond;
157 int vol_attach_threads = 1;
158 #endif /* AFS_PTHREAD_ENV */
160 #ifdef AFS_DEMAND_ATTACH_FS
161 pthread_mutex_t vol_salvsync_mutex;
164 * Set this to 1 to disallow SALVSYNC communication in all threads; used
165 * during shutdown, since the salvageserver may have gone away.
167 static volatile sig_atomic_t vol_disallow_salvsync = 0;
168 #endif /* AFS_DEMAND_ATTACH_FS */
171 extern void *calloc(), *realloc();
174 /*@printflike@*/ extern void Log(const char *format, ...);
176 /* Forward declarations */
177 static Volume *attach2(Error * ec, VolId vid, char *path,
178 register struct VolumeHeader *header,
179 struct DiskPartition64 *partp, Volume * vp,
180 int isbusy, int mode);
181 static void ReallyFreeVolume(Volume * vp);
182 #ifdef AFS_DEMAND_ATTACH_FS
183 static void FreeVolume(Volume * vp);
184 #else /* !AFS_DEMAND_ATTACH_FS */
185 #define FreeVolume(vp) ReallyFreeVolume(vp)
186 static void VScanUpdateList(void);
187 #endif /* !AFS_DEMAND_ATTACH_FS */
188 static void VInitVolumeHeaderCache(afs_uint32 howMany);
189 static int GetVolumeHeader(register Volume * vp);
190 static void ReleaseVolumeHeader(register struct volHeader *hd);
191 static void FreeVolumeHeader(register Volume * vp);
192 static void AddVolumeToHashTable(register Volume * vp, int hashid);
193 static void DeleteVolumeFromHashTable(register Volume * vp);
195 static int VHold(Volume * vp);
197 static int VHold_r(Volume * vp);
198 static void VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class);
199 static void VReleaseVolumeHandles_r(Volume * vp);
200 static void VCloseVolumeHandles_r(Volume * vp);
201 static void LoadVolumeHeader(Error * ec, Volume * vp);
202 static int VCheckOffline(register Volume * vp);
203 static int VCheckDetach(register Volume * vp);
204 static Volume * GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint, int flags);
205 #ifdef AFS_DEMAND_ATTACH_FS
206 static int VolumeExternalName_r(VolumeId volumeId, char * name, size_t len);
209 int LogLevel; /* Vice loglevel--not defined as extern so that it will be
210 * defined when not linked with vice, XXXX */
211 ProgramType programType; /* The type of program using the package */
213 /* extended volume package statistics */
216 #ifdef VOL_LOCK_DEBUG
217 pthread_t vol_glock_holder = 0;
221 #define VOLUME_BITMAP_GROWSIZE 16 /* bytes, => 128vnodes */
222 /* Must be a multiple of 4 (1 word) !! */
224 /* this parameter needs to be tunable at runtime.
225 * 128 was really inadequate for largish servers -- at 16384 volumes this
226 * puts average chain length at 128, thus an average 65 deref's to find a volptr.
227 * talk about bad spatial locality...
229 * an AVL or splay tree might work a lot better, but we'll just increase
230 * the default hash table size for now
232 #define DEFAULT_VOLUME_HASH_SIZE 256 /* Must be a power of 2!! */
233 #define DEFAULT_VOLUME_HASH_MASK (DEFAULT_VOLUME_HASH_SIZE-1)
234 #define VOLUME_HASH(volumeId) (volumeId&(VolumeHashTable.Mask))
237 * turn volume hash chains into partially ordered lists.
238 * when the threshold is exceeded between two adjacent elements,
239 * perform a chain rebalancing operation.
241 * keep the threshold high in order to keep cache line invalidates
242 * low "enough" on SMPs
244 #define VOLUME_HASH_REORDER_THRESHOLD 200
247 * when possible, don't just reorder single elements, but reorder
248 * entire chains of elements at once. a chain of elements that
249 * exceed the element previous to the pivot by at least CHAIN_THRESH
250 * accesses are moved in front of the chain whose elements have at
251 * least CHAIN_THRESH less accesses than the pivot element
253 #define VOLUME_HASH_REORDER_CHAIN_THRESH (VOLUME_HASH_REORDER_THRESHOLD / 2)
255 #include "rx/rx_queue.h"
258 VolumeHashTable_t VolumeHashTable = {
259 DEFAULT_VOLUME_HASH_SIZE,
260 DEFAULT_VOLUME_HASH_MASK,
265 static void VInitVolumeHash(void);
269 /* This macro is used where an ffs() call does not exist. Was in util/ffs.c */
273 afs_int32 ffs_tmp = x;
277 for (ffs_i = 1;; ffs_i++) {
284 #endif /* !AFS_HAVE_FFS */
286 #ifdef AFS_PTHREAD_ENV
287 typedef struct diskpartition_queue_t {
288 struct rx_queue queue;
289 struct DiskPartition64 * diskP;
290 } diskpartition_queue_t;
291 typedef struct vinitvolumepackage_thread_t {
292 struct rx_queue queue;
293 pthread_cond_t thread_done_cv;
294 int n_threads_complete;
295 } vinitvolumepackage_thread_t;
296 static void * VInitVolumePackageThread(void * args);
297 #endif /* AFS_PTHREAD_ENV */
299 static int VAttachVolumesByPartition(struct DiskPartition64 *diskP,
300 int * nAttached, int * nUnattached);
303 #ifdef AFS_DEMAND_ATTACH_FS
304 /* demand attach fileserver extensions */
307 * in the future we will support serialization of VLRU state into the fs_state
310 * these structures are the beginning of that effort
312 struct VLRU_DiskHeader {
313 struct versionStamp stamp; /* magic and structure version number */
314 afs_uint32 mtime; /* time of dump to disk */
315 afs_uint32 num_records; /* number of VLRU_DiskEntry records */
318 struct VLRU_DiskEntry {
319 afs_uint32 vid; /* volume ID */
320 afs_uint32 idx; /* generation */
321 afs_uint32 last_get; /* timestamp of last get */
324 struct VLRU_StartupQueue {
325 struct VLRU_DiskEntry * entry;
330 typedef struct vshutdown_thread_t {
332 pthread_mutex_t lock;
334 pthread_cond_t master_cv;
336 int n_threads_complete;
338 int schedule_version;
341 byte n_parts_done_pass;
342 byte part_thread_target[VOLMAXPARTS+1];
343 byte part_done_pass[VOLMAXPARTS+1];
344 struct rx_queue * part_pass_head[VOLMAXPARTS+1];
345 int stats[4][VOLMAXPARTS+1];
346 } vshutdown_thread_t;
347 static void * VShutdownThread(void * args);
350 static Volume * VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode);
351 static int VCheckFree(Volume * vp);
354 static void AddVolumeToVByPList_r(Volume * vp);
355 static void DeleteVolumeFromVByPList_r(Volume * vp);
356 static void VVByPListBeginExclusive_r(struct DiskPartition64 * dp);
357 static void VVByPListEndExclusive_r(struct DiskPartition64 * dp);
358 static void VVByPListWait_r(struct DiskPartition64 * dp);
360 /* online salvager */
361 static int VCheckSalvage(register Volume * vp);
362 static int VUpdateSalvagePriority_r(Volume * vp);
363 #ifdef SALVSYNC_BUILD_CLIENT
364 static int VScheduleSalvage_r(Volume * vp);
367 /* Volume hash table */
368 static void VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp);
369 static void VHashBeginExclusive_r(VolumeHashChainHead * head);
370 static void VHashEndExclusive_r(VolumeHashChainHead * head);
371 static void VHashWait_r(VolumeHashChainHead * head);
374 static int ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass);
375 static int ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
376 struct rx_queue ** idx);
377 static void ShutdownController(vshutdown_thread_t * params);
378 static void ShutdownCreateSchedule(vshutdown_thread_t * params);
381 static void VLRU_ComputeConstants(void);
382 static void VInitVLRU(void);
383 static void VLRU_Init_Node_r(Volume * vp);
384 static void VLRU_Add_r(Volume * vp);
385 static void VLRU_Delete_r(Volume * vp);
386 static void VLRU_UpdateAccess_r(Volume * vp);
387 static void * VLRU_ScannerThread(void * args);
388 static void VLRU_Scan_r(int idx);
389 static void VLRU_Promote_r(int idx);
390 static void VLRU_Demote_r(int idx);
391 static void VLRU_SwitchQueues(Volume * vp, int new_idx, int append);
394 static int VCheckSoftDetach(Volume * vp, afs_uint32 thresh);
395 static int VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh);
396 static int VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh);
399 pthread_key_t VThread_key;
400 VThreadOptions_t VThread_defaults = {
401 0 /**< allow salvsync */
403 #endif /* AFS_DEMAND_ATTACH_FS */
406 struct Lock vol_listLock; /* Lock obtained when listing volumes:
407 * prevents a volume from being missed
408 * if the volume is attached during a
412 static int TimeZoneCorrection; /* Number of seconds west of GMT */
414 /* Common message used when the volume goes off line */
415 char *VSalvageMessage =
416 "Files in this volume are currently unavailable; call operations";
418 int VInit; /* 0 - uninitialized,
419 * 1 - initialized but not all volumes have been attached,
420 * 2 - initialized and all volumes have been attached,
421 * 3 - initialized, all volumes have been attached, and
422 * VConnectFS() has completed. */
424 static int vinit_attach_abort = 0;
426 bit32 VolumeCacheCheck; /* Incremented everytime a volume goes on line--
427 * used to stamp volume headers and in-core
428 * vnodes. When the volume goes on-line the
429 * vnode will be invalidated
430 * access only with VOL_LOCK held */
435 /***************************************************/
436 /* Startup routines */
437 /***************************************************/
440 VInitVolumePackage(ProgramType pt, afs_uint32 nLargeVnodes, afs_uint32 nSmallVnodes,
441 int connect, afs_uint32 volcache)
443 int errors = 0; /* Number of errors while finding vice partitions. */
449 memset(&VStats, 0, sizeof(VStats));
450 VStats.hdr_cache_size = 200;
452 VInitPartitionPackage();
454 #ifdef AFS_DEMAND_ATTACH_FS
455 if (programType == fileServer) {
458 VLRU_SetOptions(VLRU_SET_ENABLED, 0);
460 assert(pthread_key_create(&VThread_key, NULL) == 0);
463 #ifdef AFS_PTHREAD_ENV
464 assert(pthread_mutex_init(&vol_glock_mutex, NULL) == 0);
465 assert(pthread_mutex_init(&vol_trans_mutex, NULL) == 0);
466 assert(pthread_cond_init(&vol_put_volume_cond, NULL) == 0);
467 assert(pthread_cond_init(&vol_sleep_cond, NULL) == 0);
468 assert(pthread_cond_init(&vol_init_attach_cond, NULL) == 0);
469 #else /* AFS_PTHREAD_ENV */
471 #endif /* AFS_PTHREAD_ENV */
472 Lock_Init(&vol_listLock);
474 srandom(time(0)); /* For VGetVolumeInfo */
475 gettimeofday(&tv, &tz);
476 TimeZoneCorrection = tz.tz_minuteswest * 60;
478 #ifdef AFS_DEMAND_ATTACH_FS
479 assert(pthread_mutex_init(&vol_salvsync_mutex, NULL) == 0);
480 #endif /* AFS_DEMAND_ATTACH_FS */
482 /* Ok, we have done enough initialization that fileserver can
483 * start accepting calls, even though the volumes may not be
484 * available just yet.
488 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_SERVER)
489 if (programType == salvageServer) {
492 #endif /* AFS_DEMAND_ATTACH_FS */
493 #ifdef FSSYNC_BUILD_SERVER
494 if (programType == fileServer) {
498 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_CLIENT)
499 if (programType == fileServer) {
500 /* establish a connection to the salvager at this point */
501 assert(VConnectSALV() != 0);
503 #endif /* AFS_DEMAND_ATTACH_FS */
505 if (volcache > VStats.hdr_cache_size)
506 VStats.hdr_cache_size = volcache;
507 VInitVolumeHeaderCache(VStats.hdr_cache_size);
509 VInitVnodes(vLarge, nLargeVnodes);
510 VInitVnodes(vSmall, nSmallVnodes);
513 errors = VAttachPartitions();
517 if (programType != fileServer) {
518 errors = VInitAttachVolumes(programType);
524 #ifdef FSSYNC_BUILD_CLIENT
525 if (programType == volumeUtility && connect) {
527 Log("Unable to connect to file server; will retry at need\n");
531 #ifdef AFS_DEMAND_ATTACH_FS
532 else if (programType == salvageServer) {
534 Log("Unable to connect to file server; aborted\n");
538 #endif /* AFS_DEMAND_ATTACH_FS */
539 #endif /* FSSYNC_BUILD_CLIENT */
544 VInitAttachVolumes(ProgramType pt)
547 if (pt == fileServer) {
548 struct DiskPartition64 *diskP;
549 #ifdef AFS_PTHREAD_ENV
550 struct vinitvolumepackage_thread_t params;
551 struct diskpartition_queue_t * dpq;
552 int i, threads, parts;
554 pthread_attr_t attrs;
556 assert(pthread_cond_init(¶ms.thread_done_cv,NULL) == 0);
558 params.n_threads_complete = 0;
560 /* create partition work queue */
561 for (parts=0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
562 dpq = (diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
565 queue_Append(¶ms,dpq);
568 threads = MIN(parts, vol_attach_threads);
571 /* spawn off a bunch of initialization threads */
572 assert(pthread_attr_init(&attrs) == 0);
573 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
575 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
576 #ifdef AFS_DEMAND_ATTACH_FS
577 Log("VInitVolumePackage: using %d threads to pre-attach volumes on %d partitions\n",
579 #else /* AFS_DEMAND_ATTACH_FS */
580 Log("VInitVolumePackage: using %d threads to attach volumes on %d partitions\n",
582 #endif /* AFS_DEMAND_ATTACH_FS */
585 for (i=0; i < threads; i++) {
588 assert(pthread_create
589 (&tid, &attrs, &VInitVolumePackageThread,
591 AFS_SIGSET_RESTORE();
594 while(params.n_threads_complete < threads) {
595 VOL_CV_WAIT(¶ms.thread_done_cv);
599 assert(pthread_attr_destroy(&attrs) == 0);
601 /* if we're only going to run one init thread, don't bother creating
603 Log("VInitVolumePackage: beginning single-threaded fileserver startup\n");
604 #ifdef AFS_DEMAND_ATTACH_FS
605 Log("VInitVolumePackage: using 1 thread to pre-attach volumes on %d partition(s)\n",
607 #else /* AFS_DEMAND_ATTACH_FS */
608 Log("VInitVolumePackage: using 1 thread to attach volumes on %d partition(s)\n",
610 #endif /* AFS_DEMAND_ATTACH_FS */
612 VInitVolumePackageThread(¶ms);
615 assert(pthread_cond_destroy(¶ms.thread_done_cv) == 0);
617 #else /* AFS_PTHREAD_ENV */
619 /* Attach all the volumes in this partition */
620 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
621 int nAttached = 0, nUnattached = 0;
622 assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
624 #endif /* AFS_PTHREAD_ENV */
627 VInit = 2; /* Initialized, and all volumes have been attached */
628 #ifdef AFS_PTHREAD_ENV
629 assert(pthread_cond_broadcast(&vol_init_attach_cond) == 0);
631 LWP_NoYieldSignal(VInitAttachVolumes);
632 #endif /* AFS_PTHREAD_ENV */
637 #ifdef AFS_PTHREAD_ENV
639 VInitVolumePackageThread(void * args) {
641 struct DiskPartition64 *diskP;
642 struct vinitvolumepackage_thread_t * params;
643 struct diskpartition_queue_t * dpq;
645 params = (vinitvolumepackage_thread_t *) args;
649 /* Attach all the volumes in this partition */
650 while (queue_IsNotEmpty(params)) {
651 int nAttached = 0, nUnattached = 0;
653 if (vinit_attach_abort) {
654 Log("Aborting initialization\n");
658 dpq = queue_First(params,diskpartition_queue_t);
664 assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
670 params->n_threads_complete++;
671 pthread_cond_signal(¶ms->thread_done_cv);
675 #endif /* AFS_PTHREAD_ENV */
678 * attach all volumes on a given disk partition
681 VAttachVolumesByPartition(struct DiskPartition64 *diskP, int * nAttached, int * nUnattached)
687 Log("Partition %s: attaching volumes\n", diskP->name);
688 dirp = opendir(VPartitionPath(diskP));
690 Log("opendir on Partition %s failed!\n", diskP->name);
694 while ((dp = readdir(dirp))) {
696 p = strrchr(dp->d_name, '.');
698 if (vinit_attach_abort) {
699 Log("Partition %s: abort attach volumes\n", diskP->name);
703 if (p != NULL && strcmp(p, VHDREXT) == 0) {
706 #ifdef AFS_DEMAND_ATTACH_FS
707 vp = VPreAttachVolumeByName(&error, diskP->name, dp->d_name);
708 #else /* AFS_DEMAND_ATTACH_FS */
709 vp = VAttachVolumeByName(&error, diskP->name, dp->d_name,
711 #endif /* AFS_DEMAND_ATTACH_FS */
712 (*(vp ? nAttached : nUnattached))++;
713 if (error == VOFFLINE)
714 Log("Volume %d stays offline (/vice/offline/%s exists)\n", VolumeNumber(dp->d_name), dp->d_name);
715 else if (LogLevel >= 5) {
716 Log("Partition %s: attached volume %d (%s)\n",
717 diskP->name, VolumeNumber(dp->d_name),
720 #if !defined(AFS_DEMAND_ATTACH_FS)
724 #endif /* AFS_DEMAND_ATTACH_FS */
728 Log("Partition %s: attached %d volumes; %d volumes not attached\n", diskP->name, *nAttached, *nUnattached);
735 /***************************************************/
736 /* Shutdown routines */
737 /***************************************************/
741 * highly multithreaded volume package shutdown
743 * with the demand attach fileserver extensions,
744 * VShutdown has been modified to be multithreaded.
745 * In order to achieve optimal use of many threads,
746 * the shutdown code involves one control thread and
747 * n shutdown worker threads. The control thread
748 * periodically examines the number of volumes available
749 * for shutdown on each partition, and produces a worker
750 * thread allocation schedule. The idea is to eliminate
751 * redundant scheduling computation on the workers by
752 * having a single master scheduler.
754 * The scheduler's objectives are:
756 * each partition with volumes remaining gets allocated
757 * at least 1 thread (assuming sufficient threads)
759 * threads are allocated proportional to the number of
760 * volumes remaining to be offlined. This ensures that
761 * the OS I/O scheduler has many requests to elevator
762 * seek on partitions that will (presumably) take the
763 * longest amount of time (from now) to finish shutdown
764 * (3) keep threads busy
765 * when there are extra threads, they are assigned to
766 * partitions using a simple round-robin algorithm
768 * In the future, we may wish to add the ability to adapt
769 * to the relative performance patterns of each disk
774 * multi-step shutdown process
776 * demand attach shutdown is a four-step process. Each
777 * shutdown "pass" shuts down increasingly more difficult
778 * volumes. The main purpose is to achieve better cache
779 * utilization during shutdown.
782 * shutdown volumes in the unattached, pre-attached
785 * shutdown attached volumes with cached volume headers
787 * shutdown all volumes in non-exclusive states
789 * shutdown all remaining volumes
792 #ifdef AFS_DEMAND_ATTACH_FS
798 struct DiskPartition64 * diskP;
799 struct diskpartition_queue_t * dpq;
800 vshutdown_thread_t params;
802 pthread_attr_t attrs;
804 memset(¶ms, 0, sizeof(vshutdown_thread_t));
807 Log("VShutdown: aborting attach volumes\n");
808 vinit_attach_abort = 1;
809 VOL_CV_WAIT(&vol_init_attach_cond);
812 for (params.n_parts=0, diskP = DiskPartitionList;
813 diskP; diskP = diskP->next, params.n_parts++);
815 Log("VShutdown: shutting down on-line volumes on %d partition%s...\n",
816 params.n_parts, params.n_parts > 1 ? "s" : "");
818 if (vol_attach_threads > 1) {
819 /* prepare for parallel shutdown */
820 params.n_threads = vol_attach_threads;
821 assert(pthread_mutex_init(¶ms.lock, NULL) == 0);
822 assert(pthread_cond_init(¶ms.cv, NULL) == 0);
823 assert(pthread_cond_init(¶ms.master_cv, NULL) == 0);
824 assert(pthread_attr_init(&attrs) == 0);
825 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
828 /* setup the basic partition information structures for
829 * parallel shutdown */
830 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
832 struct rx_queue * qp, * nqp;
836 VVByPListWait_r(diskP);
837 VVByPListBeginExclusive_r(diskP);
840 for (queue_Scan(&diskP->vol_list, qp, nqp, rx_queue)) {
841 vp = (Volume *)((char *)qp - offsetof(Volume, vol_list));
845 Log("VShutdown: partition %s has %d volumes with attached headers\n",
846 VPartitionPath(diskP), count);
849 /* build up the pass 0 shutdown work queue */
850 dpq = (struct diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
853 queue_Prepend(¶ms, dpq);
855 params.part_pass_head[diskP->index] = queue_First(&diskP->vol_list, rx_queue);
858 Log("VShutdown: beginning parallel fileserver shutdown\n");
859 Log("VShutdown: using %d threads to offline volumes on %d partition%s\n",
860 vol_attach_threads, params.n_parts, params.n_parts > 1 ? "s" : "" );
862 /* do pass 0 shutdown */
863 assert(pthread_mutex_lock(¶ms.lock) == 0);
864 for (i=0; i < params.n_threads; i++) {
865 assert(pthread_create
866 (&tid, &attrs, &VShutdownThread,
870 /* wait for all the pass 0 shutdowns to complete */
871 while (params.n_threads_complete < params.n_threads) {
872 assert(pthread_cond_wait(¶ms.master_cv, ¶ms.lock) == 0);
874 params.n_threads_complete = 0;
876 assert(pthread_cond_broadcast(¶ms.cv) == 0);
877 assert(pthread_mutex_unlock(¶ms.lock) == 0);
879 Log("VShutdown: pass 0 completed using the 1 thread per partition algorithm\n");
880 Log("VShutdown: starting passes 1 through 3 using finely-granular mp-fast algorithm\n");
882 /* run the parallel shutdown scheduler. it will drop the glock internally */
883 ShutdownController(¶ms);
885 /* wait for all the workers to finish pass 3 and terminate */
886 while (params.pass < 4) {
887 VOL_CV_WAIT(¶ms.cv);
890 assert(pthread_attr_destroy(&attrs) == 0);
891 assert(pthread_cond_destroy(¶ms.cv) == 0);
892 assert(pthread_cond_destroy(¶ms.master_cv) == 0);
893 assert(pthread_mutex_destroy(¶ms.lock) == 0);
895 /* drop the VByPList exclusive reservations */
896 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
897 VVByPListEndExclusive_r(diskP);
898 Log("VShutdown: %s stats : (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
899 VPartitionPath(diskP),
900 params.stats[0][diskP->index],
901 params.stats[1][diskP->index],
902 params.stats[2][diskP->index],
903 params.stats[3][diskP->index]);
906 Log("VShutdown: shutdown finished using %d threads\n", params.n_threads);
908 /* if we're only going to run one shutdown thread, don't bother creating
910 Log("VShutdown: beginning single-threaded fileserver shutdown\n");
912 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
913 VShutdownByPartition_r(diskP);
917 Log("VShutdown: complete.\n");
920 #else /* AFS_DEMAND_ATTACH_FS */
926 register Volume *vp, *np;
927 register afs_int32 code;
930 Log("VShutdown: aborting attach volumes\n");
931 vinit_attach_abort = 1;
932 #ifdef AFS_PTHREAD_ENV
933 VOL_CV_WAIT(&vol_init_attach_cond);
935 LWP_WaitProcess(VInitAttachVolumes);
936 #endif /* AFS_PTHREAD_ENV */
939 Log("VShutdown: shutting down on-line volumes...\n");
940 for (i = 0; i < VolumeHashTable.Size; i++) {
941 /* try to hold first volume in the hash table */
942 for (queue_Scan(&VolumeHashTable.Table[i],vp,np,Volume)) {
946 Log("VShutdown: Attempting to take volume %u offline.\n",
949 /* next, take the volume offline (drops reference count) */
950 VOffline_r(vp, "File server was shut down");
954 Log("VShutdown: complete.\n");
956 #endif /* AFS_DEMAND_ATTACH_FS */
969 * stop new activity (e.g. SALVSYNC) from occurring
971 * Use this to make the volume package less busy; for example, during
972 * shutdown. This doesn't actually shutdown/detach anything in the
973 * volume package, but prevents certain processes from ocurring. For
974 * example, preventing new SALVSYNC communication in DAFS. In theory, we
975 * could also use this to prevent new volume attachment, or prevent
976 * other programs from checking out volumes, etc.
981 #ifdef AFS_DEMAND_ATTACH_FS
982 /* make sure we don't try to contact the salvageserver, since it may
983 * not be around anymore */
984 vol_disallow_salvsync = 1;
988 #ifdef AFS_DEMAND_ATTACH_FS
991 * shutdown control thread
994 ShutdownController(vshutdown_thread_t * params)
997 struct DiskPartition64 * diskP;
999 vshutdown_thread_t shadow;
1001 ShutdownCreateSchedule(params);
1003 while ((params->pass < 4) &&
1004 (params->n_threads_complete < params->n_threads)) {
1005 /* recompute schedule once per second */
1007 memcpy(&shadow, params, sizeof(vshutdown_thread_t));
1011 Log("ShutdownController: schedule version=%d, vol_remaining=%d, pass=%d\n",
1012 shadow.schedule_version, shadow.vol_remaining, shadow.pass);
1013 Log("ShutdownController: n_threads_complete=%d, n_parts_done_pass=%d\n",
1014 shadow.n_threads_complete, shadow.n_parts_done_pass);
1015 for (diskP = DiskPartitionList; diskP; diskP=diskP->next) {
1017 Log("ShutdownController: part[%d] : (len=%d, thread_target=%d, done_pass=%d, pass_head=%p)\n",
1019 diskP->vol_list.len,
1020 shadow.part_thread_target[id],
1021 shadow.part_done_pass[id],
1022 shadow.part_pass_head[id]);
1028 ShutdownCreateSchedule(params);
1032 /* create the shutdown thread work schedule.
1033 * this scheduler tries to implement fairness
1034 * by allocating at least 1 thread to each
1035 * partition with volumes to be shutdown,
1036 * and then it attempts to allocate remaining
1037 * threads based upon the amount of work left
1040 ShutdownCreateSchedule(vshutdown_thread_t * params)
1042 struct DiskPartition64 * diskP;
1043 int sum, thr_workload, thr_left;
1044 int part_residue[VOLMAXPARTS+1];
1047 /* compute the total number of outstanding volumes */
1049 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1050 sum += diskP->vol_list.len;
1053 params->schedule_version++;
1054 params->vol_remaining = sum;
1059 /* compute average per-thread workload */
1060 thr_workload = sum / params->n_threads;
1061 if (sum % params->n_threads)
1064 thr_left = params->n_threads;
1065 memset(&part_residue, 0, sizeof(part_residue));
1067 /* for fairness, give every partition with volumes remaining
1068 * at least one thread */
1069 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1071 if (diskP->vol_list.len) {
1072 params->part_thread_target[id] = 1;
1075 params->part_thread_target[id] = 0;
1079 if (thr_left && thr_workload) {
1080 /* compute length-weighted workloads */
1083 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1085 delta = (diskP->vol_list.len / thr_workload) -
1086 params->part_thread_target[id];
1090 if (delta < thr_left) {
1091 params->part_thread_target[id] += delta;
1094 params->part_thread_target[id] += thr_left;
1102 /* try to assign any leftover threads to partitions that
1103 * had volume lengths closer to needing thread_target+1 */
1104 int max_residue, max_id = 0;
1106 /* compute the residues */
1107 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1109 part_residue[id] = diskP->vol_list.len -
1110 (params->part_thread_target[id] * thr_workload);
1113 /* now try to allocate remaining threads to partitions with the
1114 * highest residues */
1117 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1119 if (part_residue[id] > max_residue) {
1120 max_residue = part_residue[id];
1129 params->part_thread_target[max_id]++;
1131 part_residue[max_id] = 0;
1136 /* punt and give any remaining threads equally to each partition */
1138 if (thr_left >= params->n_parts) {
1139 alloc = thr_left / params->n_parts;
1140 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1142 params->part_thread_target[id] += alloc;
1147 /* finish off the last of the threads */
1148 for (diskP = DiskPartitionList; thr_left && diskP; diskP = diskP->next) {
1150 params->part_thread_target[id]++;
1156 /* worker thread for parallel shutdown */
1158 VShutdownThread(void * args)
1160 vshutdown_thread_t * params;
1161 int found, pass, schedule_version_save, count;
1162 struct DiskPartition64 *diskP;
1163 struct diskpartition_queue_t * dpq;
1166 params = (vshutdown_thread_t *) args;
1168 /* acquire the shutdown pass 0 lock */
1169 assert(pthread_mutex_lock(¶ms->lock) == 0);
1171 /* if there's still pass 0 work to be done,
1172 * get a work entry, and do a pass 0 shutdown */
1173 if (queue_IsNotEmpty(params)) {
1174 dpq = queue_First(params, diskpartition_queue_t);
1176 assert(pthread_mutex_unlock(¶ms->lock) == 0);
1182 while (ShutdownVolumeWalk_r(diskP, 0, ¶ms->part_pass_head[id]))
1184 params->stats[0][diskP->index] = count;
1185 assert(pthread_mutex_lock(¶ms->lock) == 0);
1188 params->n_threads_complete++;
1189 if (params->n_threads_complete == params->n_threads) {
1190 /* notify control thread that all workers have completed pass 0 */
1191 assert(pthread_cond_signal(¶ms->master_cv) == 0);
1193 while (params->pass == 0) {
1194 assert(pthread_cond_wait(¶ms->cv, ¶ms->lock) == 0);
1198 assert(pthread_mutex_unlock(¶ms->lock) == 0);
1201 pass = params->pass;
1204 /* now escalate through the more complicated shutdowns */
1206 schedule_version_save = params->schedule_version;
1208 /* find a disk partition to work on */
1209 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1211 if (params->part_thread_target[id] && !params->part_done_pass[id]) {
1212 params->part_thread_target[id]--;
1219 /* hmm. for some reason the controller thread couldn't find anything for
1220 * us to do. let's see if there's anything we can do */
1221 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1223 if (diskP->vol_list.len && !params->part_done_pass[id]) {
1226 } else if (!params->part_done_pass[id]) {
1227 params->part_done_pass[id] = 1;
1228 params->n_parts_done_pass++;
1230 Log("VShutdown: done shutting down volumes on partition %s.\n",
1231 VPartitionPath(diskP));
1237 /* do work on this partition until either the controller
1238 * creates a new schedule, or we run out of things to do
1239 * on this partition */
1242 while (!params->part_done_pass[id] &&
1243 (schedule_version_save == params->schedule_version)) {
1244 /* ShutdownVolumeWalk_r will drop the glock internally */
1245 if (!ShutdownVolumeWalk_r(diskP, pass, ¶ms->part_pass_head[id])) {
1246 if (!params->part_done_pass[id]) {
1247 params->part_done_pass[id] = 1;
1248 params->n_parts_done_pass++;
1250 Log("VShutdown: done shutting down volumes on partition %s.\n",
1251 VPartitionPath(diskP));
1259 params->stats[pass][id] += count;
1261 /* ok, everyone is done this pass, proceed */
1264 params->n_threads_complete++;
1265 while (params->pass == pass) {
1266 if (params->n_threads_complete == params->n_threads) {
1267 /* we are the last thread to complete, so we will
1268 * reinitialize worker pool state for the next pass */
1269 params->n_threads_complete = 0;
1270 params->n_parts_done_pass = 0;
1272 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1274 params->part_done_pass[id] = 0;
1275 params->part_pass_head[id] = queue_First(&diskP->vol_list, rx_queue);
1278 /* compute a new thread schedule before releasing all the workers */
1279 ShutdownCreateSchedule(params);
1281 /* wake up all the workers */
1282 assert(pthread_cond_broadcast(¶ms->cv) == 0);
1285 Log("VShutdown: pass %d completed using %d threads on %d partitions\n",
1286 pass, params->n_threads, params->n_parts);
1289 VOL_CV_WAIT(¶ms->cv);
1292 pass = params->pass;
1306 /* shut down all volumes on a given disk partition
1308 * note that this function will not allow mp-fast
1309 * shutdown of a partition */
1311 VShutdownByPartition_r(struct DiskPartition64 * dp)
1317 /* wait for other exclusive ops to finish */
1318 VVByPListWait_r(dp);
1320 /* begin exclusive access */
1321 VVByPListBeginExclusive_r(dp);
1323 /* pick the low-hanging fruit first,
1324 * then do the complicated ones last
1325 * (has the advantage of keeping
1326 * in-use volumes up until the bitter end) */
1327 for (pass = 0, total=0; pass < 4; pass++) {
1328 pass_stats[pass] = ShutdownVByPForPass_r(dp, pass);
1329 total += pass_stats[pass];
1332 /* end exclusive access */
1333 VVByPListEndExclusive_r(dp);
1335 Log("VShutdownByPartition: shut down %d volumes on %s (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1336 total, VPartitionPath(dp), pass_stats[0], pass_stats[1], pass_stats[2], pass_stats[3]);
1341 /* internal shutdown functionality
1343 * for multi-pass shutdown:
1344 * 0 to only "shutdown" {pre,un}attached and error state volumes
1345 * 1 to also shutdown attached volumes w/ volume header loaded
1346 * 2 to also shutdown attached volumes w/o volume header loaded
1347 * 3 to also shutdown exclusive state volumes
1349 * caller MUST hold exclusive access on the hash chain
1350 * because we drop vol_glock_mutex internally
1352 * this function is reentrant for passes 1--3
1353 * (e.g. multiple threads can cooperate to
1354 * shutdown a partition mp-fast)
1356 * pass 0 is not scaleable because the volume state data is
1357 * synchronized by vol_glock mutex, and the locking overhead
1358 * is too high to drop the lock long enough to do linked list
1362 ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass)
1364 struct rx_queue * q = queue_First(&dp->vol_list, rx_queue);
1367 while (ShutdownVolumeWalk_r(dp, pass, &q))
1373 /* conditionally shutdown one volume on partition dp
1374 * returns 1 if a volume was shutdown in this pass,
1377 ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
1378 struct rx_queue ** idx)
1380 struct rx_queue *qp, *nqp;
1385 for (queue_ScanFrom(&dp->vol_list, qp, qp, nqp, rx_queue)) {
1386 vp = (Volume *) (((char *)qp) - offsetof(Volume, vol_list));
1390 if ((V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1391 (V_attachState(vp) != VOL_STATE_ERROR) &&
1392 (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1396 if ((V_attachState(vp) == VOL_STATE_ATTACHED) &&
1397 (vp->header == NULL)) {
1401 if (VIsExclusiveState(V_attachState(vp))) {
1406 DeleteVolumeFromVByPList_r(vp);
1407 VShutdownVolume_r(vp);
1417 * shutdown a specific volume
1419 /* caller MUST NOT hold a heavyweight ref on vp */
1421 VShutdownVolume_r(Volume * vp)
1425 VCreateReservation_r(vp);
1427 if (LogLevel >= 5) {
1428 Log("VShutdownVolume_r: vid=%u, device=%d, state=%hu\n",
1429 vp->hashid, vp->partition->device, V_attachState(vp));
1432 /* wait for other blocking ops to finish */
1433 VWaitExclusiveState_r(vp);
1435 assert(VIsValidState(V_attachState(vp)));
1437 switch(V_attachState(vp)) {
1438 case VOL_STATE_SALVAGING:
1439 /* Leave salvaging volumes alone. Any in-progress salvages will
1440 * continue working after viced shuts down. This is intentional.
1443 case VOL_STATE_PREATTACHED:
1444 case VOL_STATE_ERROR:
1445 VChangeState_r(vp, VOL_STATE_UNATTACHED);
1446 case VOL_STATE_UNATTACHED:
1448 case VOL_STATE_GOING_OFFLINE:
1449 case VOL_STATE_SHUTTING_DOWN:
1450 case VOL_STATE_ATTACHED:
1454 Log("VShutdown: Attempting to take volume %u offline.\n",
1457 /* take the volume offline (drops reference count) */
1458 VOffline_r(vp, "File server was shut down");
1465 VCancelReservation_r(vp);
1469 #endif /* AFS_DEMAND_ATTACH_FS */
1472 /***************************************************/
1473 /* Header I/O routines */
1474 /***************************************************/
1476 /* open a descriptor for the inode (h),
1477 * read in an on-disk structure into buffer (to) of size (size),
1478 * verify versionstamp in structure has magic (magic) and
1479 * optionally verify version (version) if (version) is nonzero
1482 ReadHeader(Error * ec, IHandle_t * h, char *to, int size, bit32 magic,
1485 struct versionStamp *vsn;
1500 if (FDH_SEEK(fdP, 0, SEEK_SET) < 0) {
1502 FDH_REALLYCLOSE(fdP);
1505 vsn = (struct versionStamp *)to;
1506 if (FDH_READ(fdP, to, size) != size || vsn->magic != magic) {
1508 FDH_REALLYCLOSE(fdP);
1513 /* Check is conditional, in case caller wants to inspect version himself */
1514 if (version && vsn->version != version) {
1520 WriteVolumeHeader_r(Error * ec, Volume * vp)
1522 IHandle_t *h = V_diskDataHandle(vp);
1532 if (FDH_SEEK(fdP, 0, SEEK_SET) < 0) {
1534 FDH_REALLYCLOSE(fdP);
1537 if (FDH_WRITE(fdP, (char *)&V_disk(vp), sizeof(V_disk(vp)))
1538 != sizeof(V_disk(vp))) {
1540 FDH_REALLYCLOSE(fdP);
1546 /* VolumeHeaderToDisk
1547 * Allows for storing 64 bit inode numbers in on-disk volume header
1550 /* convert in-memory representation of a volume header to the
1551 * on-disk representation of a volume header */
1553 VolumeHeaderToDisk(VolumeDiskHeader_t * dh, VolumeHeader_t * h)
1556 memset(dh, 0, sizeof(VolumeDiskHeader_t));
1557 dh->stamp = h->stamp;
1559 dh->parent = h->parent;
1561 #ifdef AFS_64BIT_IOPS_ENV
1562 dh->volumeInfo_lo = (afs_int32) h->volumeInfo & 0xffffffff;
1563 dh->volumeInfo_hi = (afs_int32) (h->volumeInfo >> 32) & 0xffffffff;
1564 dh->smallVnodeIndex_lo = (afs_int32) h->smallVnodeIndex & 0xffffffff;
1565 dh->smallVnodeIndex_hi =
1566 (afs_int32) (h->smallVnodeIndex >> 32) & 0xffffffff;
1567 dh->largeVnodeIndex_lo = (afs_int32) h->largeVnodeIndex & 0xffffffff;
1568 dh->largeVnodeIndex_hi =
1569 (afs_int32) (h->largeVnodeIndex >> 32) & 0xffffffff;
1570 dh->linkTable_lo = (afs_int32) h->linkTable & 0xffffffff;
1571 dh->linkTable_hi = (afs_int32) (h->linkTable >> 32) & 0xffffffff;
1573 dh->volumeInfo_lo = h->volumeInfo;
1574 dh->smallVnodeIndex_lo = h->smallVnodeIndex;
1575 dh->largeVnodeIndex_lo = h->largeVnodeIndex;
1576 dh->linkTable_lo = h->linkTable;
1580 /* DiskToVolumeHeader
1581 * Converts an on-disk representation of a volume header to
1582 * the in-memory representation of a volume header.
1584 * Makes the assumption that AFS has *always*
1585 * zero'd the volume header file so that high parts of inode
1586 * numbers are 0 in older (SGI EFS) volume header files.
1589 DiskToVolumeHeader(VolumeHeader_t * h, VolumeDiskHeader_t * dh)
1591 memset(h, 0, sizeof(VolumeHeader_t));
1592 h->stamp = dh->stamp;
1594 h->parent = dh->parent;
1596 #ifdef AFS_64BIT_IOPS_ENV
1598 (Inode) dh->volumeInfo_lo | ((Inode) dh->volumeInfo_hi << 32);
1600 h->smallVnodeIndex =
1601 (Inode) dh->smallVnodeIndex_lo | ((Inode) dh->
1602 smallVnodeIndex_hi << 32);
1604 h->largeVnodeIndex =
1605 (Inode) dh->largeVnodeIndex_lo | ((Inode) dh->
1606 largeVnodeIndex_hi << 32);
1608 (Inode) dh->linkTable_lo | ((Inode) dh->linkTable_hi << 32);
1610 h->volumeInfo = dh->volumeInfo_lo;
1611 h->smallVnodeIndex = dh->smallVnodeIndex_lo;
1612 h->largeVnodeIndex = dh->largeVnodeIndex_lo;
1613 h->linkTable = dh->linkTable_lo;
1618 /***************************************************/
1619 /* Volume Attachment routines */
1620 /***************************************************/
1622 #ifdef AFS_DEMAND_ATTACH_FS
1624 * pre-attach a volume given its path.
1626 * @param[out] ec outbound error code
1627 * @param[in] partition partition path string
1628 * @param[in] name volume id string
1630 * @return volume object pointer
1632 * @note A pre-attached volume will only have its partition
1633 * and hashid fields initialized. At first call to
1634 * VGetVolume, the volume will be fully attached.
1638 VPreAttachVolumeByName(Error * ec, char *partition, char *name)
1642 vp = VPreAttachVolumeByName_r(ec, partition, name);
1648 * pre-attach a volume given its path.
1650 * @param[out] ec outbound error code
1651 * @param[in] partition path to vice partition
1652 * @param[in] name volume id string
1654 * @return volume object pointer
1656 * @pre VOL_LOCK held
1658 * @internal volume package internal use only.
1661 VPreAttachVolumeByName_r(Error * ec, char *partition, char *name)
1663 return VPreAttachVolumeById_r(ec,
1665 VolumeNumber(name));
1669 * pre-attach a volume given its path and numeric volume id.
1671 * @param[out] ec error code return
1672 * @param[in] partition path to vice partition
1673 * @param[in] volumeId numeric volume id
1675 * @return volume object pointer
1677 * @pre VOL_LOCK held
1679 * @internal volume package internal use only.
1682 VPreAttachVolumeById_r(Error * ec,
1687 struct DiskPartition64 *partp;
1691 assert(programType == fileServer);
1693 if (!(partp = VGetPartition_r(partition, 0))) {
1695 Log("VPreAttachVolumeById_r: Error getting partition (%s)\n", partition);
1699 vp = VLookupVolume_r(ec, volumeId, NULL);
1704 return VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
1708 * preattach a volume.
1710 * @param[out] ec outbound error code
1711 * @param[in] partp pointer to partition object
1712 * @param[in] vp pointer to volume object
1713 * @param[in] vid volume id
1715 * @return volume object pointer
1717 * @pre VOL_LOCK is held.
1719 * @warning Returned volume object pointer does not have to
1720 * equal the pointer passed in as argument vp. There
1721 * are potential race conditions which can result in
1722 * the pointers having different values. It is up to
1723 * the caller to make sure that references are handled
1724 * properly in this case.
1726 * @note If there is already a volume object registered with
1727 * the same volume id, its pointer MUST be passed as
1728 * argument vp. Failure to do so will result in a silent
1729 * failure to preattach.
1731 * @internal volume package internal use only.
1734 VPreAttachVolumeByVp_r(Error * ec,
1735 struct DiskPartition64 * partp,
1743 /* check to see if pre-attach already happened */
1745 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1746 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
1747 !VIsErrorState(V_attachState(vp))) {
1749 * pre-attach is a no-op in all but the following cases:
1751 * - volume is unattached
1752 * - volume is in an error state
1753 * - volume is pre-attached
1755 Log("VPreattachVolumeByVp_r: volume %u not in quiescent state\n", vid);
1758 /* we're re-attaching a volume; clear out some old state */
1759 memset(&vp->salvage, 0, sizeof(struct VolumeOnlineSalvage));
1761 if (V_partition(vp) != partp) {
1762 /* XXX potential race */
1763 DeleteVolumeFromVByPList_r(vp);
1766 /* if we need to allocate a new Volume struct,
1767 * go ahead and drop the vol glock, otherwise
1768 * do the basic setup synchronised, as it's
1769 * probably not worth dropping the lock */
1772 /* allocate the volume structure */
1773 vp = nvp = (Volume *) malloc(sizeof(Volume));
1775 memset(vp, 0, sizeof(Volume));
1776 queue_Init(&vp->vnode_list);
1777 assert(pthread_cond_init(&V_attachCV(vp), NULL) == 0);
1780 /* link the volume with its associated vice partition */
1781 vp->device = partp->device;
1782 vp->partition = partp;
1785 vp->specialStatus = 0;
1787 /* if we dropped the lock, reacquire the lock,
1788 * check for pre-attach races, and then add
1789 * the volume to the hash table */
1792 nvp = VLookupVolume_r(ec, vid, NULL);
1797 } else if (nvp) { /* race detected */
1802 /* hack to make up for VChangeState_r() decrementing
1803 * the old state counter */
1804 VStats.state_levels[0]++;
1808 /* put pre-attached volume onto the hash table
1809 * and bring it up to the pre-attached state */
1810 AddVolumeToHashTable(vp, vp->hashid);
1811 AddVolumeToVByPList_r(vp);
1812 VLRU_Init_Node_r(vp);
1813 VChangeState_r(vp, VOL_STATE_PREATTACHED);
1816 Log("VPreAttachVolumeByVp_r: volume %u pre-attached\n", vp->hashid);
1824 #endif /* AFS_DEMAND_ATTACH_FS */
1826 /* Attach an existing volume, given its pathname, and return a
1827 pointer to the volume header information. The volume also
1828 normally goes online at this time. An offline volume
1829 must be reattached to make it go online */
1831 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
1835 retVal = VAttachVolumeByName_r(ec, partition, name, mode);
1841 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
1843 register Volume *vp = NULL;
1845 struct afs_stat status;
1846 struct VolumeDiskHeader diskHeader;
1847 struct VolumeHeader iheader;
1848 struct DiskPartition64 *partp;
1852 #ifdef AFS_DEMAND_ATTACH_FS
1853 VolumeStats stats_save;
1855 #endif /* AFS_DEMAND_ATTACH_FS */
1859 volumeId = VolumeNumber(name);
1861 if (!(partp = VGetPartition_r(partition, 0))) {
1863 Log("VAttachVolume: Error getting partition (%s)\n", partition);
1867 if (programType == volumeUtility) {
1869 VLockPartition_r(partition);
1870 } else if (programType == fileServer) {
1871 #ifdef AFS_DEMAND_ATTACH_FS
1872 /* lookup the volume in the hash table */
1873 vp = VLookupVolume_r(ec, volumeId, NULL);
1879 /* save any counters that are supposed to
1880 * be monotonically increasing over the
1881 * lifetime of the fileserver */
1882 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
1884 memset(&stats_save, 0, sizeof(VolumeStats));
1887 /* if there's something in the hash table, and it's not
1888 * in the pre-attach state, then we may need to detach
1889 * it before proceeding */
1890 if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1891 VCreateReservation_r(vp);
1892 VWaitExclusiveState_r(vp);
1894 /* at this point state must be one of:
1903 if (vp->specialStatus == VBUSY)
1906 /* if it's already attached, see if we can return it */
1907 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
1908 VGetVolumeByVp_r(ec, vp);
1909 if (V_inUse(vp) == fileServer) {
1910 VCancelReservation_r(vp);
1914 /* otherwise, we need to detach, and attempt to re-attach */
1915 VDetachVolume_r(ec, vp);
1917 Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
1920 /* if it isn't fully attached, delete from the hash tables,
1921 and let the refcounter handle the rest */
1922 DeleteVolumeFromHashTable(vp);
1923 DeleteVolumeFromVByPList_r(vp);
1926 VCancelReservation_r(vp);
1930 /* pre-attach volume if it hasn't been done yet */
1932 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
1933 (V_attachState(vp) == VOL_STATE_ERROR)) {
1935 vp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
1943 /* handle pre-attach races
1945 * multiple threads can race to pre-attach a volume,
1946 * but we can't let them race beyond that
1948 * our solution is to let the first thread to bring
1949 * the volume into an exclusive state win; the other
1950 * threads just wait until it finishes bringing the
1951 * volume online, and then they do a vgetvolumebyvp
1953 if (svp && (svp != vp)) {
1954 /* wait for other exclusive ops to finish */
1955 VCreateReservation_r(vp);
1956 VWaitExclusiveState_r(vp);
1958 /* get a heavyweight ref, kill the lightweight ref, and return */
1959 VGetVolumeByVp_r(ec, vp);
1960 VCancelReservation_r(vp);
1964 /* at this point, we are chosen as the thread to do
1965 * demand attachment for this volume. all other threads
1966 * doing a getvolume on vp->hashid will block until we finish */
1968 /* make sure any old header cache entries are invalidated
1969 * before proceeding */
1970 FreeVolumeHeader(vp);
1972 VChangeState_r(vp, VOL_STATE_ATTACHING);
1974 /* restore any saved counters */
1975 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
1976 #else /* AFS_DEMAND_ATTACH_FS */
1977 vp = VGetVolume_r(ec, volumeId);
1979 if (V_inUse(vp) == fileServer)
1981 if (vp->specialStatus == VBUSY)
1983 VDetachVolume_r(ec, vp);
1985 Log("VAttachVolume: Error detaching volume (%s)\n", name);
1989 #endif /* AFS_DEMAND_ATTACH_FS */
1993 strcpy(path, VPartitionPath(partp));
1999 if ((fd = afs_open(path, O_RDONLY)) == -1 || afs_fstat(fd, &status) == -1) {
2000 Log("VAttachVolume: Failed to open %s (errno %d)\n", path, errno);
2007 n = read(fd, &diskHeader, sizeof(diskHeader));
2009 if (n != sizeof(diskHeader)
2010 || diskHeader.stamp.magic != VOLUMEHEADERMAGIC) {
2011 Log("VAttachVolume: Error reading volume header %s\n", path);
2016 if (diskHeader.stamp.version != VOLUMEHEADERVERSION) {
2017 Log("VAttachVolume: Volume %s, version number is incorrect; volume needs salvaged\n", path);
2023 DiskToVolumeHeader(&iheader, &diskHeader);
2024 #ifdef FSSYNC_BUILD_CLIENT
2025 if (programType == volumeUtility && mode != V_SECRETLY && mode != V_PEEK) {
2027 if (FSYNC_VolOp(iheader.id, partition, FSYNC_VOL_NEEDVOLUME, mode, NULL)
2029 Log("VAttachVolume: attach of volume %u apparently denied by file server\n", iheader.id);
2030 *ec = VNOVOL; /* XXXX */
2038 vp = (Volume *) calloc(1, sizeof(Volume));
2040 vp->device = partp->device;
2041 vp->partition = partp;
2042 queue_Init(&vp->vnode_list);
2043 #ifdef AFS_DEMAND_ATTACH_FS
2044 assert(pthread_cond_init(&V_attachCV(vp), NULL) == 0);
2045 #endif /* AFS_DEMAND_ATTACH_FS */
2048 /* attach2 is entered without any locks, and returns
2049 * with vol_glock_mutex held */
2050 vp = attach2(ec, volumeId, path, &iheader, partp, vp, isbusy, mode);
2052 if (programType == volumeUtility && vp) {
2053 if ((mode == V_VOLUPD) || (VolumeWriteable(vp) && (mode == V_CLONE))) {
2054 /* mark volume header as in use so that volser crashes lead to a
2055 * salvage attempt */
2056 VUpdateVolume_r(ec, vp, 0);
2058 #ifdef AFS_DEMAND_ATTACH_FS
2059 /* for dafs, we should tell the fileserver, except for V_PEEK
2060 * where we know it is not necessary */
2061 if (mode == V_PEEK) {
2062 vp->needsPutBack = 0;
2064 vp->needsPutBack = 1;
2066 #else /* !AFS_DEMAND_ATTACH_FS */
2067 /* duplicate computation in fssync.c about whether the server
2068 * takes the volume offline or not. If the volume isn't
2069 * offline, we must not return it when we detach the volume,
2070 * or the server will abort */
2071 if (mode == V_READONLY || mode == V_PEEK
2072 || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
2073 vp->needsPutBack = 0;
2075 vp->needsPutBack = 1;
2076 #endif /* !AFS_DEMAND_ATTACH_FS */
2078 /* OK, there's a problem here, but one that I don't know how to
2079 * fix right now, and that I don't think should arise often.
2080 * Basically, we should only put back this volume to the server if
2081 * it was given to us by the server, but since we don't have a vp,
2082 * we can't run the VolumeWriteable function to find out as we do
2083 * above when computing vp->needsPutBack. So we send it back, but
2084 * there's a path in VAttachVolume on the server which may abort
2085 * if this volume doesn't have a header. Should be pretty rare
2086 * for all of that to happen, but if it does, probably the right
2087 * fix is for the server to allow the return of readonly volumes
2088 * that it doesn't think are really checked out. */
2089 #ifdef FSSYNC_BUILD_CLIENT
2090 if (programType == volumeUtility && vp == NULL &&
2091 mode != V_SECRETLY && mode != V_PEEK) {
2092 FSYNC_VolOp(iheader.id, partition, FSYNC_VOL_ON, 0, NULL);
2095 if (programType == fileServer && vp) {
2096 #ifdef AFS_DEMAND_ATTACH_FS
2098 * we can get here in cases where we don't "own"
2099 * the volume (e.g. volume owned by a utility).
2100 * short circuit around potential disk header races.
2102 if (V_attachState(vp) != VOL_STATE_ATTACHED) {
2106 V_needsCallback(vp) = 0;
2108 if (VInit >= 2 && V_BreakVolumeCallbacks) {
2109 Log("VAttachVolume: Volume %u was changed externally; breaking callbacks\n", V_id(vp));
2110 (*V_BreakVolumeCallbacks) (V_id(vp));
2113 VUpdateVolume_r(ec, vp, 0);
2115 Log("VAttachVolume: Error updating volume\n");
2120 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2121 #ifndef AFS_DEMAND_ATTACH_FS
2122 /* This is a hack: by temporarily setting the incore
2123 * dontSalvage flag ON, the volume will be put back on the
2124 * Update list (with dontSalvage OFF again). It will then
2125 * come back in N minutes with DONT_SALVAGE eventually
2126 * set. This is the way that volumes that have never had
2127 * it set get it set; or that volumes that have been
2128 * offline without DONT SALVAGE having been set also
2129 * eventually get it set */
2130 V_dontSalvage(vp) = DONT_SALVAGE;
2131 #endif /* !AFS_DEMAND_ATTACH_FS */
2132 VAddToVolumeUpdateList_r(ec, vp);
2134 Log("VAttachVolume: Error adding volume to update list\n");
2141 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2146 if (programType == volumeUtility) {
2147 VUnlockPartition_r(partition);
2150 #ifdef AFS_DEMAND_ATTACH_FS
2151 /* attach failed; make sure we're in error state */
2152 if (vp && !VIsErrorState(V_attachState(vp))) {
2153 VChangeState_r(vp, VOL_STATE_ERROR);
2155 #endif /* AFS_DEMAND_ATTACH_FS */
2162 #ifdef AFS_DEMAND_ATTACH_FS
2163 /* VAttachVolumeByVp_r
2165 * finish attaching a volume that is
2166 * in a less than fully attached state
2168 /* caller MUST hold a ref count on vp */
2170 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
2172 char name[VMAXPATHLEN];
2173 int fd, n, reserve = 0;
2174 struct afs_stat status;
2175 struct VolumeDiskHeader diskHeader;
2176 struct VolumeHeader iheader;
2177 struct DiskPartition64 *partp;
2181 Volume * nvp = NULL;
2182 VolumeStats stats_save;
2185 /* volume utility should never call AttachByVp */
2186 assert(programType == fileServer);
2188 volumeId = vp->hashid;
2189 partp = vp->partition;
2190 VolumeExternalName_r(volumeId, name, sizeof(name));
2193 /* if another thread is performing a blocking op, wait */
2194 VWaitExclusiveState_r(vp);
2196 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2198 /* if it's already attached, see if we can return it */
2199 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2200 VGetVolumeByVp_r(ec, vp);
2201 if (V_inUse(vp) == fileServer) {
2204 if (vp->specialStatus == VBUSY)
2206 VDetachVolume_r(ec, vp);
2208 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2214 /* pre-attach volume if it hasn't been done yet */
2216 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2217 (V_attachState(vp) == VOL_STATE_ERROR)) {
2218 nvp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2224 VCreateReservation_r(nvp);
2230 VChangeState_r(vp, VOL_STATE_ATTACHING);
2232 /* restore monotonically increasing stats */
2233 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2238 /* compute path to disk header,
2240 * and verify magic and version stamps */
2241 strcpy(path, VPartitionPath(partp));
2247 if ((fd = afs_open(path, O_RDONLY)) == -1 || afs_fstat(fd, &status) == -1) {
2248 Log("VAttachVolume: Failed to open %s (errno %d)\n", path, errno);
2255 n = read(fd, &diskHeader, sizeof(diskHeader));
2257 if (n != sizeof(diskHeader)
2258 || diskHeader.stamp.magic != VOLUMEHEADERMAGIC) {
2259 Log("VAttachVolume: Error reading volume header %s\n", path);
2264 if (diskHeader.stamp.version != VOLUMEHEADERVERSION) {
2265 Log("VAttachVolume: Volume %s, version number is incorrect; volume needs salvaged\n", path);
2271 /* convert on-disk header format to in-memory header format */
2272 DiskToVolumeHeader(&iheader, &diskHeader);
2276 * NOTE: attach2 is entered without any locks, and returns
2277 * with vol_glock_mutex held */
2278 vp = attach2(ec, volumeId, path, &iheader, partp, vp, isbusy, mode);
2281 * the event that an error was encountered, or
2282 * the volume was not brought to an attached state
2283 * for any reason, skip to the end. We cannot
2284 * safely call VUpdateVolume unless we "own" it.
2288 (V_attachState(vp) != VOL_STATE_ATTACHED)) {
2292 V_needsCallback(vp) = 0;
2293 VUpdateVolume_r(ec, vp, 0);
2295 Log("VAttachVolume: Error updating volume %u\n", vp->hashid);
2299 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2300 #ifndef AFS_DEMAND_ATTACH_FS
2301 /* This is a hack: by temporarily setting the incore
2302 * dontSalvage flag ON, the volume will be put back on the
2303 * Update list (with dontSalvage OFF again). It will then
2304 * come back in N minutes with DONT_SALVAGE eventually
2305 * set. This is the way that volumes that have never had
2306 * it set get it set; or that volumes that have been
2307 * offline without DONT SALVAGE having been set also
2308 * eventually get it set */
2309 V_dontSalvage(vp) = DONT_SALVAGE;
2310 #endif /* !AFS_DEMAND_ATTACH_FS */
2311 VAddToVolumeUpdateList_r(ec, vp);
2313 Log("VAttachVolume: Error adding volume %u to update list\n", vp->hashid);
2320 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2324 VCancelReservation_r(nvp);
2327 if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2328 if (vp && !VIsErrorState(V_attachState(vp))) {
2329 VChangeState_r(vp, VOL_STATE_ERROR);
2336 #endif /* AFS_DEMAND_ATTACH_FS */
2339 * called without any locks held
2340 * returns with vol_glock_mutex held
2343 attach2(Error * ec, VolId volumeId, char *path, register struct VolumeHeader * header,
2344 struct DiskPartition64 * partp, register Volume * vp, int isbusy, int mode)
2346 vp->specialStatus = (byte) (isbusy ? VBUSY : 0);
2347 IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header->parent,
2348 header->largeVnodeIndex);
2349 IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header->parent,
2350 header->smallVnodeIndex);
2351 IH_INIT(vp->diskDataHandle, partp->device, header->parent,
2352 header->volumeInfo);
2353 IH_INIT(vp->linkHandle, partp->device, header->parent, header->linkTable);
2354 vp->shuttingDown = 0;
2355 vp->goingOffline = 0;
2357 #ifdef AFS_DEMAND_ATTACH_FS
2358 vp->stats.last_attach = FT_ApproxTime();
2359 vp->stats.attaches++;
2363 IncUInt64(&VStats.attaches);
2364 vp->cacheCheck = ++VolumeCacheCheck;
2365 /* just in case this ever rolls over */
2366 if (!vp->cacheCheck)
2367 vp->cacheCheck = ++VolumeCacheCheck;
2368 GetVolumeHeader(vp);
2371 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2372 /* demand attach changes the V_PEEK mechanism
2374 * we can now suck the current disk data structure over
2375 * the fssync interface without going to disk
2377 * (technically, we don't need to restrict this feature
2378 * to demand attach fileservers. However, I'm trying
2379 * to limit the number of common code changes)
2381 if (programType != fileServer && mode == V_PEEK) {
2383 res.payload.len = sizeof(VolumeDiskData);
2384 res.payload.buf = &vp->header->diskstuff;
2386 if (FSYNC_VolOp(volumeId,
2388 FSYNC_VOL_QUERY_HDR,
2391 goto disk_header_loaded;
2394 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2395 (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2396 sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2398 #ifdef AFS_DEMAND_ATTACH_FS
2401 IncUInt64(&VStats.hdr_loads);
2402 IncUInt64(&vp->stats.hdr_loads);
2404 #endif /* AFS_DEMAND_ATTACH_FS */
2407 Log("VAttachVolume: Error reading diskDataHandle vol header %s; error=%u\n", path, *ec);
2410 #ifdef AFS_DEMAND_ATTACH_FS
2411 # ifdef FSSYNC_BUILD_CLIENT
2416 /* check for pending volume operations */
2417 if (vp->pending_vol_op) {
2418 /* see if the pending volume op requires exclusive access */
2419 switch (vp->pending_vol_op->vol_op_state) {
2420 case FSSYNC_VolOpPending:
2421 /* this should never happen */
2422 assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpPending);
2425 case FSSYNC_VolOpRunningUnknown:
2426 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
2427 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
2430 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
2431 /* fall through to take volume offline */
2434 case FSSYNC_VolOpRunningOffline:
2435 /* mark the volume down */
2437 VChangeState_r(vp, VOL_STATE_UNATTACHED);
2438 if (V_offlineMessage(vp)[0] == '\0')
2439 strlcpy(V_offlineMessage(vp),
2440 "A volume utility is running.",
2441 sizeof(V_offlineMessage(vp)));
2442 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
2444 /* check to see if we should set the specialStatus flag */
2445 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
2446 vp->specialStatus = VBUSY;
2453 V_attachFlags(vp) |= VOL_HDR_LOADED;
2454 vp->stats.last_hdr_load = vp->stats.last_attach;
2456 #endif /* AFS_DEMAND_ATTACH_FS */
2459 struct IndexFileHeader iHead;
2461 #if OPENAFS_VOL_STATS
2463 * We just read in the diskstuff part of the header. If the detailed
2464 * volume stats area has not yet been initialized, we should bzero the
2465 * area and mark it as initialized.
2467 if (!(V_stat_initialized(vp))) {
2468 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
2469 V_stat_initialized(vp) = 1;
2471 #endif /* OPENAFS_VOL_STATS */
2473 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
2474 (char *)&iHead, sizeof(iHead),
2475 SMALLINDEXMAGIC, SMALLINDEXVERSION);
2478 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
2483 struct IndexFileHeader iHead;
2485 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
2486 (char *)&iHead, sizeof(iHead),
2487 LARGEINDEXMAGIC, LARGEINDEXVERSION);
2490 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
2494 #ifdef AFS_NAMEI_ENV
2496 struct versionStamp stamp;
2498 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
2499 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
2502 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
2505 #endif /* AFS_NAMEI_ENV */
2507 #if defined(AFS_DEMAND_ATTACH_FS)
2508 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
2510 if (programType == fileServer) {
2511 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2514 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
2520 /* volume operation in progress */
2524 #else /* AFS_DEMAND_ATTACH_FS */
2526 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
2531 #endif /* AFS_DEMAND_ATTACH_FS */
2533 if (V_needsSalvaged(vp)) {
2534 if (vp->specialStatus)
2535 vp->specialStatus = 0;
2537 #if defined(AFS_DEMAND_ATTACH_FS)
2538 if (programType == fileServer) {
2539 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
2542 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
2546 #else /* AFS_DEMAND_ATTACH_FS */
2549 #endif /* AFS_DEMAND_ATTACH_FS */
2554 if (programType == fileServer) {
2555 #ifndef FAST_RESTART
2556 if (V_inUse(vp) && VolumeWriteable(vp)) {
2557 if (!V_needsSalvaged(vp)) {
2558 V_needsSalvaged(vp) = 1;
2559 VUpdateVolume_r(ec, vp, 0);
2561 #if defined(AFS_DEMAND_ATTACH_FS)
2562 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
2564 #else /* AFS_DEMAND_ATTACH_FS */
2565 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
2568 #endif /* AFS_DEMAND_ATTACH_FS */
2571 #endif /* FAST_RESTART */
2573 if (V_destroyMe(vp) == DESTROY_ME) {
2574 #if defined(AFS_DEMAND_ATTACH_FS)
2575 /* schedule a salvage so the volume goes away on disk */
2576 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2577 VChangeState_r(vp, VOL_STATE_ERROR);
2579 #endif /* AFS_DEMAND_ATTACH_FS */
2581 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
2587 vp->nextVnodeUnique = V_uniquifier(vp);
2588 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
2589 #ifndef BITMAP_LATER
2590 if (programType == fileServer && VolumeWriteable(vp)) {
2592 for (i = 0; i < nVNODECLASSES; i++) {
2593 VGetBitmap_r(ec, vp, i);
2595 #ifdef AFS_DEMAND_ATTACH_FS
2596 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2598 #else /* AFS_DEMAND_ATTACH_FS */
2600 #endif /* AFS_DEMAND_ATTACH_FS */
2601 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
2607 #endif /* BITMAP_LATER */
2609 if (programType == fileServer) {
2610 if (vp->specialStatus)
2611 vp->specialStatus = 0;
2612 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
2613 V_inUse(vp) = fileServer;
2614 V_offlineMessage(vp)[0] = '\0';
2617 if ((mode != V_PEEK) && (mode != V_SECRETLY))
2618 V_inUse(vp) = programType;
2619 V_checkoutMode(vp) = mode;
2622 AddVolumeToHashTable(vp, V_id(vp));
2623 #ifdef AFS_DEMAND_ATTACH_FS
2624 if ((programType != fileServer) ||
2625 (V_inUse(vp) == fileServer)) {
2626 AddVolumeToVByPList_r(vp);
2628 VChangeState_r(vp, VOL_STATE_ATTACHED);
2630 VChangeState_r(vp, VOL_STATE_UNATTACHED);
2636 /* Attach an existing volume.
2637 The volume also normally goes online at this time.
2638 An offline volume must be reattached to make it go online.
2642 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
2646 retVal = VAttachVolume_r(ec, volumeId, mode);
2652 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
2655 VGetVolumePath(ec, volumeId, &part, &name);
2657 register Volume *vp;
2659 vp = VGetVolume_r(&error, volumeId);
2661 assert(V_inUse(vp) == 0);
2662 VDetachVolume_r(ec, vp);
2666 return VAttachVolumeByName_r(ec, part, name, mode);
2669 /* Increment a reference count to a volume, sans context swaps. Requires
2670 * possibly reading the volume header in from the disk, since there's
2671 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
2673 * N.B. This call can fail if we can't read in the header!! In this case
2674 * we still guarantee we won't context swap, but the ref count won't be
2675 * incremented (otherwise we'd violate the invariant).
2677 /* NOTE: with the demand attach fileserver extensions, the global lock
2678 * is dropped within VHold */
2679 #ifdef AFS_DEMAND_ATTACH_FS
2681 VHold_r(register Volume * vp)
2685 VCreateReservation_r(vp);
2686 VWaitExclusiveState_r(vp);
2688 LoadVolumeHeader(&error, vp);
2690 VCancelReservation_r(vp);
2694 VCancelReservation_r(vp);
2697 #else /* AFS_DEMAND_ATTACH_FS */
2699 VHold_r(register Volume * vp)
2703 LoadVolumeHeader(&error, vp);
2709 #endif /* AFS_DEMAND_ATTACH_FS */
2713 VHold(register Volume * vp)
2717 retVal = VHold_r(vp);
2724 /***************************************************/
2725 /* get and put volume routines */
2726 /***************************************************/
2729 * put back a heavyweight reference to a volume object.
2731 * @param[in] vp volume object pointer
2733 * @pre VOL_LOCK held
2735 * @post heavyweight volume reference put back.
2736 * depending on state, volume may have been taken offline,
2737 * detached, salvaged, freed, etc.
2739 * @internal volume package internal use only
2742 VPutVolume_r(register Volume * vp)
2744 assert(--vp->nUsers >= 0);
2745 if (vp->nUsers == 0) {
2747 ReleaseVolumeHeader(vp->header);
2748 #ifdef AFS_DEMAND_ATTACH_FS
2749 if (!VCheckDetach(vp)) {
2753 #else /* AFS_DEMAND_ATTACH_FS */
2755 #endif /* AFS_DEMAND_ATTACH_FS */
2760 VPutVolume(register Volume * vp)
2768 /* Get a pointer to an attached volume. The pointer is returned regardless
2769 of whether or not the volume is in service or on/off line. An error
2770 code, however, is returned with an indication of the volume's status */
2772 VGetVolume(Error * ec, Error * client_ec, VolId volumeId)
2776 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
2782 VGetVolume_r(Error * ec, VolId volumeId)
2784 return GetVolume(ec, NULL, volumeId, NULL, 0);
2787 /* try to get a volume we've previously looked up */
2788 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
2790 VGetVolumeByVp_r(Error * ec, Volume * vp)
2792 return GetVolume(ec, NULL, vp->hashid, vp, 0);
2795 /* private interface for getting a volume handle
2796 * volumeId must be provided.
2797 * hint is an optional parameter to speed up hash lookups
2798 * flags is not used at this time
2800 /* for demand attach fs, caller MUST NOT hold a ref count on hint */
2802 GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint, int flags)
2805 /* pull this profiling/debugging code out of regular builds */
2807 #define VGET_CTR_INC(x) x++
2808 unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
2809 0, V7 = 0, V8 = 0, V9 = 0;
2810 unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
2812 #define VGET_CTR_INC(x)
2814 #ifdef AFS_DEMAND_ATTACH_FS
2815 Volume *avp, * rvp = hint;
2819 * if VInit is zero, the volume package dynamic
2820 * data structures have not been initialized yet,
2821 * and we must immediately return an error
2827 *client_ec = VOFFLINE;
2832 #ifdef AFS_DEMAND_ATTACH_FS
2834 VCreateReservation_r(rvp);
2836 #endif /* AFS_DEMAND_ATTACH_FS */
2844 vp = VLookupVolume_r(ec, volumeId, vp);
2850 #ifdef AFS_DEMAND_ATTACH_FS
2851 if (rvp && (rvp != vp)) {
2852 /* break reservation on old vp */
2853 VCancelReservation_r(rvp);
2856 #endif /* AFS_DEMAND_ATTACH_FS */
2862 /* Until we have reached an initialization level of 2
2863 * we don't know whether this volume exists or not.
2864 * We can't sleep and retry later because before a volume
2865 * is attached, the caller tries to get it first. Just
2866 * return VOFFLINE and the caller can choose whether to
2867 * retry the command or not. */
2877 IncUInt64(&VStats.hdr_gets);
2879 #ifdef AFS_DEMAND_ATTACH_FS
2880 /* block if someone else is performing an exclusive op on this volume */
2883 VCreateReservation_r(rvp);
2885 VWaitExclusiveState_r(vp);
2887 /* short circuit with VNOVOL in the following circumstances:
2890 * - VOL_STATE_SHUTTING_DOWN
2892 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
2893 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN) ||
2894 (V_attachState(vp) == VOL_STATE_GOING_OFFLINE)) {
2901 * short circuit with VOFFLINE in the following circumstances:
2903 * - VOL_STATE_UNATTACHED
2905 if (V_attachState(vp) == VOL_STATE_UNATTACHED) {
2906 if (vp->specialStatus) {
2907 *ec = vp->specialStatus;
2915 /* allowable states:
2921 if (vp->salvage.requested) {
2922 VUpdateSalvagePriority_r(vp);
2925 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
2926 avp = VAttachVolumeByVp_r(ec, vp, 0);
2929 /* VAttachVolumeByVp_r can return a pointer
2930 * != the vp passed to it under certain
2931 * conditions; make sure we don't leak
2932 * reservations if that happens */
2934 VCancelReservation_r(rvp);
2936 VCreateReservation_r(rvp);
2946 if (!vp->pending_vol_op) {
2961 if ((V_attachState(vp) == VOL_STATE_SALVAGING) ||
2962 (*ec == VSALVAGING)) {
2964 /* see CheckVnode() in afsfileprocs.c for an explanation
2965 * of this error code logic */
2966 afs_uint32 now = FT_ApproxTime();
2967 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
2970 *client_ec = VRESTARTING;
2979 LoadVolumeHeader(ec, vp);
2982 /* Only log the error if it was a totally unexpected error. Simply
2983 * a missing inode is likely to be caused by the volume being deleted */
2984 if (errno != ENXIO || LogLevel)
2985 Log("Volume %u: couldn't reread volume header\n",
2987 #ifdef AFS_DEMAND_ATTACH_FS
2988 if (programType == fileServer) {
2989 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2994 #else /* AFS_DEMAND_ATTACH_FS */
2997 #endif /* AFS_DEMAND_ATTACH_FS */
3001 #ifdef AFS_DEMAND_ATTACH_FS
3003 * this test MUST happen after the volume header is loaded
3006 /* only valid before/during demand attachment */
3007 assert(!vp->pending_vol_op || vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
3009 /* deny getvolume due to running mutually exclusive vol op */
3010 if (vp->pending_vol_op && vp->pending_vol_op->vol_op_state==FSSYNC_VolOpRunningOffline) {
3012 * volume cannot remain online during this volume operation.
3015 if (vp->specialStatus) {
3017 * special status codes outrank normal VOFFLINE code
3019 *ec = vp->specialStatus;
3021 *client_ec = vp->specialStatus;
3025 /* see CheckVnode() in afsfileprocs.c for an explanation
3026 * of this error code logic */
3027 afs_uint32 now = FT_ApproxTime();
3028 if ((vp->stats.last_vol_op + (10 * 60)) >= now) {
3031 *client_ec = VRESTARTING;
3036 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3037 FreeVolumeHeader(vp);
3041 #endif /* AFS_DEMAND_ATTACH_FS */
3044 if (vp->shuttingDown) {
3051 if (programType == fileServer) {
3053 if (vp->goingOffline) {
3055 #ifdef AFS_DEMAND_ATTACH_FS
3056 /* wait for the volume to go offline */
3057 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
3058 VWaitStateChange_r(vp);
3060 #elif defined(AFS_PTHREAD_ENV)
3061 VOL_CV_WAIT(&vol_put_volume_cond);
3062 #else /* AFS_PTHREAD_ENV */
3063 LWP_WaitProcess(VPutVolume);
3064 #endif /* AFS_PTHREAD_ENV */
3067 if (vp->specialStatus) {
3069 *ec = vp->specialStatus;
3070 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3073 } else if (V_inUse(vp) == 0) {
3084 #ifdef AFS_DEMAND_ATTACH_FS
3085 /* if no error, bump nUsers */
3088 VLRU_UpdateAccess_r(vp);
3091 VCancelReservation_r(rvp);
3094 if (client_ec && !*client_ec) {
3097 #else /* AFS_DEMAND_ATTACH_FS */
3098 /* if no error, bump nUsers */
3105 #endif /* AFS_DEMAND_ATTACH_FS */
3113 /***************************************************/
3114 /* Volume offline/detach routines */
3115 /***************************************************/
3117 /* caller MUST hold a heavyweight ref on vp */
3118 #ifdef AFS_DEMAND_ATTACH_FS
3120 VTakeOffline_r(register Volume * vp)
3124 assert(vp->nUsers > 0);
3125 assert(programType == fileServer);
3127 VCreateReservation_r(vp);
3128 VWaitExclusiveState_r(vp);
3130 vp->goingOffline = 1;
3131 V_needsSalvaged(vp) = 1;
3133 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
3134 VCancelReservation_r(vp);
3136 #else /* AFS_DEMAND_ATTACH_FS */
3138 VTakeOffline_r(register Volume * vp)
3140 assert(vp->nUsers > 0);
3141 assert(programType == fileServer);
3143 vp->goingOffline = 1;
3144 V_needsSalvaged(vp) = 1;
3146 #endif /* AFS_DEMAND_ATTACH_FS */
3149 VTakeOffline(register Volume * vp)
3157 * force a volume offline.
3159 * @param[in] vp volume object pointer
3160 * @param[in] flags flags (see note below)
3162 * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
3163 * used when VUpdateVolume_r needs to call VForceOffline_r
3164 * (which in turn would normally call VUpdateVolume_r)
3166 * @see VUpdateVolume_r
3168 * @pre VOL_LOCK must be held.
3169 * for DAFS, caller must hold ref.
3171 * @note for DAFS, it _is safe_ to call this function from an
3174 * @post needsSalvaged flag is set.
3175 * for DAFS, salvage is requested.
3176 * no further references to the volume through the volume
3177 * package will be honored.
3178 * all file descriptor and vnode caches are invalidated.
3180 * @warning this is a heavy-handed interface. it results in
3181 * a volume going offline regardless of the current
3182 * reference count state.
3184 * @internal volume package internal use only
3187 VForceOffline_r(Volume * vp, int flags)
3191 #ifdef AFS_DEMAND_ATTACH_FS
3192 VChangeState_r(vp, VOL_STATE_ERROR);
3197 strcpy(V_offlineMessage(vp),
3198 "Forced offline due to internal error: volume needs to be salvaged");
3199 Log("Volume %u forced offline: it needs salvaging!\n", V_id(vp));
3202 vp->goingOffline = 0;
3203 V_needsSalvaged(vp) = 1;
3204 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
3205 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
3208 #ifdef AFS_DEMAND_ATTACH_FS
3209 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3210 #endif /* AFS_DEMAND_ATTACH_FS */
3212 #ifdef AFS_PTHREAD_ENV
3213 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3214 #else /* AFS_PTHREAD_ENV */
3215 LWP_NoYieldSignal(VPutVolume);
3216 #endif /* AFS_PTHREAD_ENV */
3218 VReleaseVolumeHandles_r(vp);
3222 * force a volume offline.
3224 * @param[in] vp volume object pointer
3226 * @see VForceOffline_r
3229 VForceOffline(Volume * vp)
3232 VForceOffline_r(vp, 0);
3236 /* The opposite of VAttachVolume. The volume header is written to disk, with
3237 the inUse bit turned off. A copy of the header is maintained in memory,
3238 however (which is why this is VOffline, not VDetach).
3241 VOffline_r(Volume * vp, char *message)
3243 #ifndef AFS_DEMAND_ATTACH_FS
3245 VolumeId vid = V_id(vp);
3248 assert(programType != volumeUtility);
3253 if (V_offlineMessage(vp)[0] == '\0')
3254 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
3255 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
3257 vp->goingOffline = 1;
3258 #ifdef AFS_DEMAND_ATTACH_FS
3259 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
3260 VCreateReservation_r(vp);
3263 /* wait for the volume to go offline */
3264 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
3265 VWaitStateChange_r(vp);
3267 VCancelReservation_r(vp);
3268 #else /* AFS_DEMAND_ATTACH_FS */
3270 vp = VGetVolume_r(&error, vid); /* Wait for it to go offline */
3271 if (vp) /* In case it was reattached... */
3273 #endif /* AFS_DEMAND_ATTACH_FS */
3276 #ifdef AFS_DEMAND_ATTACH_FS
3278 * Take a volume offline in order to perform a volume operation.
3280 * @param[inout] ec address in which to store error code
3281 * @param[in] vp volume object pointer
3282 * @param[in] message volume offline status message
3285 * - VOL_LOCK is held
3286 * - caller MUST hold a heavyweight ref on vp
3289 * - volume is taken offline
3290 * - if possible, volume operation is promoted to running state
3291 * - on failure, *ec is set to nonzero
3293 * @note Although this function does not return any value, it may
3294 * still fail to promote our pending volume operation to
3295 * a running state. Any caller MUST check the value of *ec,
3296 * and MUST NOT blindly assume success.
3298 * @warning if the caller does not hold a lightweight ref on vp,
3299 * then it MUST NOT reference vp after this function
3300 * returns to the caller.
3302 * @internal volume package internal use only
3305 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
3307 assert(vp->pending_vol_op);
3313 if (V_offlineMessage(vp)[0] == '\0')
3314 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
3315 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
3317 vp->goingOffline = 1;
3318 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
3319 VCreateReservation_r(vp);
3322 /* Wait for the volume to go offline */
3323 while (!VIsOfflineState(V_attachState(vp))) {
3324 /* do not give corrupted volumes to the volserver */
3325 if (vp->salvage.requested && vp->pending_vol_op->com.programType != salvageServer) {
3329 VWaitStateChange_r(vp);
3333 VCancelReservation_r(vp);
3335 #endif /* AFS_DEMAND_ATTACH_FS */
3338 VOffline(Volume * vp, char *message)
3341 VOffline_r(vp, message);
3345 /* This gets used for the most part by utility routines that don't want
3346 * to keep all the volume headers around. Generally, the file server won't
3347 * call this routine, because then the offline message in the volume header
3348 * (or other information) won't be available to clients. For NAMEI, also
3349 * close the file handles. However, the fileserver does call this during
3350 * an attach following a volume operation.
3353 VDetachVolume_r(Error * ec, Volume * vp)
3356 struct DiskPartition64 *tpartp;
3357 int notifyServer = 0;
3358 int useDone = FSYNC_VOL_ON;
3360 *ec = 0; /* always "succeeds" */
3361 if (programType == volumeUtility) {
3362 notifyServer = vp->needsPutBack;
3363 if (V_destroyMe(vp) == DESTROY_ME)
3364 useDone = FSYNC_VOL_DONE;
3365 #ifdef AFS_DEMAND_ATTACH_FS
3366 else if (!V_blessed(vp) || !V_inService(vp))
3367 useDone = FSYNC_VOL_LEAVE_OFF;
3370 tpartp = vp->partition;
3372 DeleteVolumeFromHashTable(vp);
3373 vp->shuttingDown = 1;
3374 #ifdef AFS_DEMAND_ATTACH_FS
3375 DeleteVolumeFromVByPList_r(vp);
3377 VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
3379 if (programType != fileServer)
3381 #endif /* AFS_DEMAND_ATTACH_FS */
3383 /* Will be detached sometime in the future--this is OK since volume is offline */
3385 /* XXX the following code should really be moved to VCheckDetach() since the volume
3386 * is not technically detached until the refcounts reach zero
3388 #ifdef FSSYNC_BUILD_CLIENT
3389 if (programType == volumeUtility && notifyServer) {
3391 * Note: The server is not notified in the case of a bogus volume
3392 * explicitly to make it possible to create a volume, do a partial
3393 * restore, then abort the operation without ever putting the volume
3394 * online. This is essential in the case of a volume move operation
3395 * between two partitions on the same server. In that case, there
3396 * would be two instances of the same volume, one of them bogus,
3397 * which the file server would attempt to put on line
3399 FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
3400 /* XXX this code path is only hit by volume utilities, thus
3401 * V_BreakVolumeCallbacks will always be NULL. if we really
3402 * want to break callbacks in this path we need to use FSYNC_VolOp() */
3404 /* Dettaching it so break all callbacks on it */
3405 if (V_BreakVolumeCallbacks) {
3406 Log("volume %u detached; breaking all call backs\n", volume);
3407 (*V_BreakVolumeCallbacks) (volume);
3411 #endif /* FSSYNC_BUILD_CLIENT */
3415 VDetachVolume(Error * ec, Volume * vp)
3418 VDetachVolume_r(ec, vp);
3423 /***************************************************/
3424 /* Volume fd/inode handle closing routines */
3425 /***************************************************/
3427 /* For VDetachVolume, we close all cached file descriptors, but keep
3428 * the Inode handles in case we need to read from a busy volume.
3430 /* for demand attach, caller MUST hold ref count on vp */
3432 VCloseVolumeHandles_r(Volume * vp)
3434 #ifdef AFS_DEMAND_ATTACH_FS
3435 VolState state_save;
3437 state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
3442 * XXX need to investigate whether we can perform
3443 * DFlushVolume outside of vol_glock_mutex...
3445 * VCloseVnodeFiles_r drops the glock internally */
3446 DFlushVolume(V_id(vp));
3447 VCloseVnodeFiles_r(vp);
3449 #ifdef AFS_DEMAND_ATTACH_FS
3453 /* Too time consuming and unnecessary for the volserver */
3454 if (programType != volumeUtility) {
3455 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
3456 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
3457 IH_CONDSYNC(vp->diskDataHandle);
3459 IH_CONDSYNC(vp->linkHandle);
3460 #endif /* AFS_NT40_ENV */
3463 IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
3464 IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
3465 IH_REALLYCLOSE(vp->diskDataHandle);
3466 IH_REALLYCLOSE(vp->linkHandle);
3468 #ifdef AFS_DEMAND_ATTACH_FS
3470 VChangeState_r(vp, state_save);
3474 /* For both VForceOffline and VOffline, we close all relevant handles.
3475 * For VOffline, if we re-attach the volume, the files may possible be
3476 * different than before.
3478 /* for demand attach, caller MUST hold a ref count on vp */
3480 VReleaseVolumeHandles_r(Volume * vp)
3482 #ifdef AFS_DEMAND_ATTACH_FS
3483 VolState state_save;
3485 state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
3488 /* XXX need to investigate whether we can perform
3489 * DFlushVolume outside of vol_glock_mutex... */
3490 DFlushVolume(V_id(vp));
3492 VReleaseVnodeFiles_r(vp); /* releases the glock internally */
3494 #ifdef AFS_DEMAND_ATTACH_FS
3498 /* Too time consuming and unnecessary for the volserver */
3499 if (programType != volumeUtility) {
3500 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
3501 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
3502 IH_CONDSYNC(vp->diskDataHandle);
3504 IH_CONDSYNC(vp->linkHandle);
3505 #endif /* AFS_NT40_ENV */
3508 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
3509 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
3510 IH_RELEASE(vp->diskDataHandle);
3511 IH_RELEASE(vp->linkHandle);
3513 #ifdef AFS_DEMAND_ATTACH_FS
3515 VChangeState_r(vp, state_save);
3520 /***************************************************/
3521 /* Volume write and fsync routines */
3522 /***************************************************/
3525 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
3527 #ifdef AFS_DEMAND_ATTACH_FS
3528 VolState state_save;
3530 if (flags & VOL_UPDATE_WAIT) {
3531 VCreateReservation_r(vp);
3532 VWaitExclusiveState_r(vp);
3537 if (programType == fileServer)
3539 (V_inUse(vp) ? V_nextVnodeUnique(vp) +
3540 200 : V_nextVnodeUnique(vp));
3542 #ifdef AFS_DEMAND_ATTACH_FS
3543 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
3547 WriteVolumeHeader_r(ec, vp);
3549 #ifdef AFS_DEMAND_ATTACH_FS
3551 VChangeState_r(vp, state_save);
3552 if (flags & VOL_UPDATE_WAIT) {
3553 VCancelReservation_r(vp);
3558 Log("VUpdateVolume: error updating volume header, volume %u (%s)\n",
3559 V_id(vp), V_name(vp));
3560 /* try to update on-disk header,
3561 * while preventing infinite recursion */
3562 if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
3563 VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
3569 VUpdateVolume(Error * ec, Volume * vp)
3572 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
3577 VSyncVolume_r(Error * ec, Volume * vp, int flags)
3581 #ifdef AFS_DEMAND_ATTACH_FS
3582 VolState state_save;
3585 if (flags & VOL_SYNC_WAIT) {
3586 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
3588 VUpdateVolume_r(ec, vp, 0);
3591 #ifdef AFS_DEMAND_ATTACH_FS
3592 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
3595 fdP = IH_OPEN(V_diskDataHandle(vp));
3596 assert(fdP != NULL);
3597 code = FDH_SYNC(fdP);
3600 #ifdef AFS_DEMAND_ATTACH_FS
3602 VChangeState_r(vp, state_save);
3608 VSyncVolume(Error * ec, Volume * vp)
3611 VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
3616 /***************************************************/
3617 /* Volume dealloaction routines */
3618 /***************************************************/
3620 #ifdef AFS_DEMAND_ATTACH_FS
3622 FreeVolume(Volume * vp)
3624 /* free the heap space, iff it's safe.
3625 * otherwise, pull it out of the hash table, so it
3626 * will get deallocated when all refs to it go away */
3627 if (!VCheckFree(vp)) {
3628 DeleteVolumeFromHashTable(vp);
3629 DeleteVolumeFromVByPList_r(vp);
3631 /* make sure we invalidate the header cache entry */
3632 FreeVolumeHeader(vp);
3635 #endif /* AFS_DEMAND_ATTACH_FS */
3638 ReallyFreeVolume(Volume * vp)
3643 #ifdef AFS_DEMAND_ATTACH_FS
3645 VChangeState_r(vp, VOL_STATE_FREED);
3646 if (vp->pending_vol_op)
3647 free(vp->pending_vol_op);
3648 #endif /* AFS_DEMAND_ATTACH_FS */
3649 for (i = 0; i < nVNODECLASSES; i++)
3650 if (vp->vnodeIndex[i].bitmap)
3651 free(vp->vnodeIndex[i].bitmap);
3652 FreeVolumeHeader(vp);
3653 #ifndef AFS_DEMAND_ATTACH_FS
3654 DeleteVolumeFromHashTable(vp);
3655 #endif /* AFS_DEMAND_ATTACH_FS */
3659 /* check to see if we should shutdown this volume
3660 * returns 1 if volume was freed, 0 otherwise */
3661 #ifdef AFS_DEMAND_ATTACH_FS
3663 VCheckDetach(register Volume * vp)
3668 if (vp->nUsers || vp->nWaiters)
3671 if (vp->shuttingDown) {
3673 if ((programType != fileServer) &&
3674 (V_inUse(vp) == programType) &&
3675 ((V_checkoutMode(vp) == V_VOLUPD) ||
3676 (V_checkoutMode(vp) == V_SECRETLY) ||
3677 ((V_checkoutMode(vp) == V_CLONE) &&
3678 (VolumeWriteable(vp))))) {
3680 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
3682 Log("VCheckDetach: volume header update for volume %u "
3683 "failed with errno %d\n", vp->hashid, errno);
3686 VReleaseVolumeHandles_r(vp);
3688 ReallyFreeVolume(vp);
3689 if (programType == fileServer) {
3690 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3695 #else /* AFS_DEMAND_ATTACH_FS */
3697 VCheckDetach(register Volume * vp)
3705 if (vp->shuttingDown) {
3707 if ((programType != fileServer) &&
3708 (V_inUse(vp) == programType) &&
3709 ((V_checkoutMode(vp) == V_VOLUPD) ||
3710 (V_checkoutMode(vp) == V_SECRETLY) ||
3711 ((V_checkoutMode(vp) == V_CLONE) &&
3712 (VolumeWriteable(vp))))) {
3714 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
3716 Log("VCheckDetach: volume header update for volume %u failed with errno %d\n",
3720 VReleaseVolumeHandles_r(vp);
3721 ReallyFreeVolume(vp);
3722 if (programType == fileServer) {
3723 #if defined(AFS_PTHREAD_ENV)
3724 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3725 #else /* AFS_PTHREAD_ENV */
3726 LWP_NoYieldSignal(VPutVolume);
3727 #endif /* AFS_PTHREAD_ENV */
3732 #endif /* AFS_DEMAND_ATTACH_FS */
3734 /* check to see if we should offline this volume
3735 * return 1 if volume went offline, 0 otherwise */
3736 #ifdef AFS_DEMAND_ATTACH_FS
3738 VCheckOffline(register Volume * vp)
3742 if (vp->goingOffline && !vp->nUsers) {
3744 assert(programType == fileServer);
3745 assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
3746 (V_attachState(vp) != VOL_STATE_FREED) &&
3747 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
3748 (V_attachState(vp) != VOL_STATE_UNATTACHED));
3752 * VOL_STATE_GOING_OFFLINE
3753 * VOL_STATE_SHUTTING_DOWN
3754 * VIsErrorState(V_attachState(vp))
3755 * VIsExclusiveState(V_attachState(vp))
3758 VCreateReservation_r(vp);
3759 VChangeState_r(vp, VOL_STATE_OFFLINING);
3762 /* must clear the goingOffline flag before we drop the glock */
3763 vp->goingOffline = 0;
3768 /* perform async operations */
3769 VUpdateVolume_r(&error, vp, 0);
3770 VCloseVolumeHandles_r(vp);
3773 if (V_offlineMessage(vp)[0]) {
3774 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
3775 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
3776 V_offlineMessage(vp));
3778 Log("VOffline: Volume %lu (%s) is now offline\n",
3779 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
3783 /* invalidate the volume header cache entry */
3784 FreeVolumeHeader(vp);
3786 /* if nothing changed state to error or salvaging,
3787 * drop state to unattached */
3788 if (!VIsErrorState(V_attachState(vp))) {
3789 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3791 VCancelReservation_r(vp);
3792 /* no usage of vp is safe beyond this point */
3796 #else /* AFS_DEMAND_ATTACH_FS */
3798 VCheckOffline(register Volume * vp)
3802 if (vp->goingOffline && !vp->nUsers) {
3804 assert(programType == fileServer);
3807 vp->goingOffline = 0;
3809 VUpdateVolume_r(&error, vp, 0);
3810 VCloseVolumeHandles_r(vp);
3812 Log("VOffline: Volume %u (%s) is now offline", V_id(vp),
3814 if (V_offlineMessage(vp)[0])
3815 Log(" (%s)", V_offlineMessage(vp));
3818 FreeVolumeHeader(vp);
3819 #ifdef AFS_PTHREAD_ENV
3820 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3821 #else /* AFS_PTHREAD_ENV */
3822 LWP_NoYieldSignal(VPutVolume);
3823 #endif /* AFS_PTHREAD_ENV */
3827 #endif /* AFS_DEMAND_ATTACH_FS */
3829 /***************************************************/
3830 /* demand attach fs ref counting routines */
3831 /***************************************************/
3833 #ifdef AFS_DEMAND_ATTACH_FS
3834 /* the following two functions handle reference counting for
3835 * asynchronous operations on volume structs.
3837 * their purpose is to prevent a VDetachVolume or VShutdown
3838 * from free()ing the Volume struct during an async i/o op */
3840 /* register with the async volume op ref counter */
3841 /* VCreateReservation_r moved into inline code header because it
3842 * is now needed in vnode.c -- tkeiser 11/20/2007
3846 * decrement volume-package internal refcount.
3848 * @param vp volume object pointer
3850 * @internal volume package internal use only
3853 * @arg VOL_LOCK is held
3854 * @arg lightweight refcount held
3856 * @post volume waiters refcount is decremented; volume may
3857 * have been deallocated/shutdown/offlined/salvaged/
3858 * whatever during the process
3860 * @warning once you have tossed your last reference (you can acquire
3861 * lightweight refs recursively) it is NOT SAFE to reference
3862 * a volume object pointer ever again
3864 * @see VCreateReservation_r
3866 * @note DEMAND_ATTACH_FS only
3869 VCancelReservation_r(Volume * vp)
3871 assert(--vp->nWaiters >= 0);
3872 if (vp->nWaiters == 0) {
3874 if (!VCheckDetach(vp)) {
3881 /* check to see if we should free this volume now
3882 * return 1 if volume was freed, 0 otherwise */
3884 VCheckFree(Volume * vp)
3887 if ((vp->nUsers == 0) &&
3888 (vp->nWaiters == 0) &&
3889 !(V_attachFlags(vp) & (VOL_IN_HASH |
3893 ReallyFreeVolume(vp);
3898 #endif /* AFS_DEMAND_ATTACH_FS */
3901 /***************************************************/
3902 /* online volume operations routines */
3903 /***************************************************/
3905 #ifdef AFS_DEMAND_ATTACH_FS
3907 * register a volume operation on a given volume.
3909 * @param[in] vp volume object
3910 * @param[in] vopinfo volume operation info object
3912 * @pre VOL_LOCK is held
3914 * @post volume operation info object attached to volume object.
3915 * volume operation statistics updated.
3917 * @note by "attached" we mean a copy of the passed in object is made
3919 * @internal volume package internal use only
3922 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3924 FSSYNC_VolOp_info * info;
3926 /* attach a vol op info node to the volume struct */
3927 info = (FSSYNC_VolOp_info *) malloc(sizeof(FSSYNC_VolOp_info));
3928 assert(info != NULL);
3929 memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
3930 vp->pending_vol_op = info;
3933 vp->stats.last_vol_op = FT_ApproxTime();
3934 vp->stats.vol_ops++;
3935 IncUInt64(&VStats.vol_ops);
3941 * deregister the volume operation attached to this volume.
3943 * @param[in] vp volume object pointer
3945 * @pre VOL_LOCK is held
3947 * @post the volume operation info object is detached from the volume object
3949 * @internal volume package internal use only
3952 VDeregisterVolOp_r(Volume * vp)
3954 if (vp->pending_vol_op) {
3955 free(vp->pending_vol_op);
3956 vp->pending_vol_op = NULL;
3960 #endif /* AFS_DEMAND_ATTACH_FS */
3963 * determine whether it is safe to leave a volume online during
3964 * the volume operation described by the vopinfo object.
3966 * @param[in] vp volume object
3967 * @param[in] vopinfo volume operation info object
3969 * @return whether it is safe to leave volume online
3970 * @retval 0 it is NOT SAFE to leave the volume online
3971 * @retval 1 it is safe to leave the volume online during the operation
3974 * @arg VOL_LOCK is held
3975 * @arg disk header attached to vp (heavyweight ref on vp will guarantee
3976 * this condition is met)
3978 * @internal volume package internal use only
3981 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3983 return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
3984 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
3985 (vopinfo->com.reason == V_READONLY ||
3986 (!VolumeWriteable(vp) &&
3987 (vopinfo->com.reason == V_CLONE ||
3988 vopinfo->com.reason == V_DUMP)))));
3992 * determine whether VBUSY should be set during this volume operation.
3994 * @param[in] vp volume object
3995 * @param[in] vopinfo volume operation info object
3997 * @return whether VBUSY should be set
3998 * @retval 0 VBUSY does NOT need to be set
3999 * @retval 1 VBUSY SHOULD be set
4001 * @pre VOL_LOCK is held
4003 * @internal volume package internal use only
4006 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4008 return ((vopinfo->com.command == FSYNC_VOL_OFF &&
4009 vopinfo->com.reason == FSYNC_SALVAGE) ||
4010 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4011 (vopinfo->com.reason == V_CLONE ||
4012 vopinfo->com.reason == V_DUMP)));
4016 /***************************************************/
4017 /* online salvager routines */
4018 /***************************************************/
4019 #if defined(AFS_DEMAND_ATTACH_FS)
4020 #define SALVAGE_PRIO_UPDATE_INTERVAL 3 /**< number of seconds between prio updates */
4021 #define SALVAGE_COUNT_MAX 16 /**< number of online salvages we
4022 * allow before moving the volume
4023 * into a permanent error state
4025 * once this threshold is reached,
4026 * the operator will have to manually
4027 * issue a 'bos salvage' to bring
4028 * the volume back online
4032 * check whether a salvage needs to be performed on this volume.
4034 * @param[in] vp pointer to volume object
4036 * @return status code
4037 * @retval 0 no salvage scheduled
4038 * @retval 1 a salvage has been scheduled with the salvageserver
4040 * @pre VOL_LOCK is held
4042 * @post if salvage request flag is set and nUsers and nWaiters are zero,
4043 * then a salvage will be requested
4045 * @note this is one of the event handlers called by VCancelReservation_r
4047 * @see VCancelReservation_r
4049 * @internal volume package internal use only.
4052 VCheckSalvage(register Volume * vp)
4055 #ifdef SALVSYNC_BUILD_CLIENT
4056 if (vp->nUsers || vp->nWaiters)
4058 if (vp->salvage.requested) {
4059 VScheduleSalvage_r(vp);
4062 #endif /* SALVSYNC_BUILD_CLIENT */
4067 * request volume salvage.
4069 * @param[out] ec computed client error code
4070 * @param[in] vp volume object pointer
4071 * @param[in] reason reason code (passed to salvageserver via SALVSYNC)
4072 * @param[in] flags see flags note below
4075 * VOL_SALVAGE_INVALIDATE_HEADER causes volume header cache entry
4076 * to be invalidated.
4078 * @pre VOL_LOCK is held.
4080 * @post volume state is changed.
4081 * for fileserver, salvage will be requested once refcount reaches zero.
4083 * @return operation status code
4084 * @retval 0 volume salvage will occur
4085 * @retval 1 volume salvage could not be scheduled
4087 * @note DAFS fileserver only
4089 * @note this call does not synchronously schedule a volume salvage. rather,
4090 * it sets volume state so that when volume refcounts reach zero, a
4091 * volume salvage will occur. by "refcounts", we mean both nUsers and
4092 * nWaiters must be zero.
4094 * @internal volume package internal use only.
4097 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
4101 * for DAFS volume utilities, transition to error state
4102 * (at some point in the future, we should consider
4103 * making volser talk to salsrv)
4105 if (programType != fileServer) {
4106 VChangeState_r(vp, VOL_STATE_ERROR);
4111 if (!vp->salvage.requested) {
4112 vp->salvage.requested = 1;
4113 vp->salvage.reason = reason;
4114 vp->stats.last_salvage = FT_ApproxTime();
4115 if (VIsSalvager(V_inUse(vp))) {
4116 Log("VRequestSalvage: volume %u appears to be salvaging, but we\n", vp->hashid);
4117 Log(" didn't request a salvage. Forcing it offline waiting for the\n");
4118 Log(" salvage to finish; if you are sure no salvage is running,\n");
4119 Log(" run a salvage manually.\n");
4121 /* make sure neither VScheduleSalvage_r nor
4122 * VUpdateSalvagePriority_r try to schedule another salvage */
4123 vp->salvage.requested = vp->salvage.scheduled = 0;
4125 /* these stats aren't correct, but doing this makes them
4126 * slightly closer to being correct */
4127 vp->stats.salvages++;
4128 vp->stats.last_salvage_req = FT_ApproxTime();
4129 IncUInt64(&VStats.salvages);
4131 VChangeState_r(vp, VOL_STATE_ERROR);
4135 } else if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
4136 VChangeState_r(vp, VOL_STATE_SALVAGING);
4139 Log("VRequestSalvage: volume %u online salvaged too many times; forced offline.\n", vp->hashid);
4140 VChangeState_r(vp, VOL_STATE_ERROR);
4144 if (flags & VOL_SALVAGE_INVALIDATE_HEADER) {
4145 /* Instead of ReleaseVolumeHeader, we do FreeVolumeHeader()
4146 so that the the next VAttachVolumeByVp_r() invocation
4147 of attach2() will pull in a cached header
4148 entry and fail, then load a fresh one from disk and attach
4151 FreeVolumeHeader(vp);
4158 * update salvageserver scheduling priority for a volume.
4160 * @param[in] vp pointer to volume object
4162 * @return operation status
4164 * @retval 1 request denied, or SALVSYNC communications failure
4166 * @pre VOL_LOCK is held.
4168 * @post in-core salvage priority counter is incremented. if at least
4169 * SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
4170 * last SALVSYNC_RAISEPRIO request, we contact the salvageserver
4171 * to update its priority queue. if no salvage is scheduled,
4172 * this function is a no-op.
4174 * @note DAFS fileserver only
4176 * @note this should be called whenever a VGetVolume fails due to a
4177 * pending salvage request
4179 * @todo should set exclusive state and drop glock around salvsync call
4181 * @internal volume package internal use only.
4184 VUpdateSalvagePriority_r(Volume * vp)
4188 #ifdef SALVSYNC_BUILD_CLIENT
4193 now = FT_ApproxTime();
4195 /* update the salvageserver priority queue occasionally so that
4196 * frequently requested volumes get moved to the head of the queue
4198 if ((vp->salvage.scheduled) &&
4199 (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
4200 code = SALVSYNC_SalvageVolume(vp->hashid,
4201 VPartitionPath(vp->partition),
4206 vp->stats.last_salvage_req = now;
4207 if (code != SYNC_OK) {
4211 #endif /* SALVSYNC_BUILD_CLIENT */
4216 #ifdef SALVSYNC_BUILD_CLIENT
4218 * schedule a salvage with the salvage server.
4220 * @param[in] vp pointer to volume object
4222 * @return operation status
4223 * @retval 0 salvage scheduled successfully
4224 * @retval 1 salvage not scheduled, or SALVSYNC com error
4227 * @arg VOL_LOCK is held.
4228 * @arg nUsers and nWaiters should be zero.
4230 * @post salvageserver is sent a salvage request
4232 * @note DAFS fileserver only
4234 * @internal volume package internal use only.
4237 VScheduleSalvage_r(Volume * vp)
4241 VolState state_save;
4242 VThreadOptions_t * thread_opts;
4245 if (vp->nWaiters || vp->nUsers) {
4249 /* prevent endless salvage,attach,salvage,attach,... loops */
4250 if (vp->stats.salvages >= SALVAGE_COUNT_MAX)
4254 * don't perform salvsync ops on certain threads
4256 thread_opts = pthread_getspecific(VThread_key);
4257 if (thread_opts == NULL) {
4258 thread_opts = &VThread_defaults;
4260 if (thread_opts->disallow_salvsync || vol_disallow_salvsync) {
4265 * XXX the scheduling process should really be done asynchronously
4266 * to avoid fssync deadlocks
4268 if (!vp->salvage.scheduled) {
4269 /* if we haven't previously scheduled a salvage, do so now
4271 * set the volume to an exclusive state and drop the lock
4272 * around the SALVSYNC call
4274 * note that we do NOT acquire a reservation here -- doing so
4275 * could result in unbounded recursion
4277 strlcpy(partName, VPartitionPath(vp->partition), sizeof(partName));
4278 state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
4281 /* can't use V_id() since there's no guarantee
4282 * we have the disk data header at this point */
4283 code = SALVSYNC_SalvageVolume(vp->hashid,
4290 VChangeState_r(vp, state_save);
4292 if (code == SYNC_OK) {
4293 vp->salvage.scheduled = 1;
4294 vp->stats.salvages++;
4295 vp->stats.last_salvage_req = FT_ApproxTime();
4296 IncUInt64(&VStats.salvages);
4300 case SYNC_BAD_COMMAND:
4301 case SYNC_COM_ERROR:
4304 Log("VScheduleSalvage_r: SALVSYNC request denied\n");
4307 Log("VScheduleSalvage_r: SALVSYNC unknown protocol error\n");
4316 * connect to the salvageserver SYNC service.
4318 * @return operation status
4322 * @post connection to salvageserver SYNC service established
4324 * @see VConnectSALV_r
4325 * @see VDisconnectSALV
4326 * @see VReconnectSALV
4333 retVal = VConnectSALV_r();
4339 * connect to the salvageserver SYNC service.
4341 * @return operation status
4345 * @pre VOL_LOCK is held.
4347 * @post connection to salvageserver SYNC service established
4350 * @see VDisconnectSALV_r
4351 * @see VReconnectSALV_r
4352 * @see SALVSYNC_clientInit
4354 * @internal volume package internal use only.
4357 VConnectSALV_r(void)
4359 return SALVSYNC_clientInit();
4363 * disconnect from the salvageserver SYNC service.
4365 * @return operation status
4368 * @pre client should have a live connection to the salvageserver
4370 * @post connection to salvageserver SYNC service destroyed
4372 * @see VDisconnectSALV_r
4374 * @see VReconnectSALV
4377 VDisconnectSALV(void)
4380 VDisconnectSALV_r();
4386 * disconnect from the salvageserver SYNC service.
4388 * @return operation status
4392 * @arg VOL_LOCK is held.
4393 * @arg client should have a live connection to the salvageserver.
4395 * @post connection to salvageserver SYNC service destroyed
4397 * @see VDisconnectSALV
4398 * @see VConnectSALV_r
4399 * @see VReconnectSALV_r
4400 * @see SALVSYNC_clientFinis
4402 * @internal volume package internal use only.
4405 VDisconnectSALV_r(void)
4407 return SALVSYNC_clientFinis();
4411 * disconnect and then re-connect to the salvageserver SYNC service.
4413 * @return operation status
4417 * @pre client should have a live connection to the salvageserver
4419 * @post old connection is dropped, and a new one is established
4422 * @see VDisconnectSALV
4423 * @see VReconnectSALV_r
4426 VReconnectSALV(void)
4430 retVal = VReconnectSALV_r();
4436 * disconnect and then re-connect to the salvageserver SYNC service.
4438 * @return operation status
4443 * @arg VOL_LOCK is held.
4444 * @arg client should have a live connection to the salvageserver.
4446 * @post old connection is dropped, and a new one is established
4448 * @see VConnectSALV_r
4449 * @see VDisconnectSALV
4450 * @see VReconnectSALV
4451 * @see SALVSYNC_clientReconnect
4453 * @internal volume package internal use only.
4456 VReconnectSALV_r(void)
4458 return SALVSYNC_clientReconnect();
4460 #endif /* SALVSYNC_BUILD_CLIENT */
4461 #endif /* AFS_DEMAND_ATTACH_FS */
4464 /***************************************************/
4465 /* FSSYNC routines */
4466 /***************************************************/
4468 /* This must be called by any volume utility which needs to run while the
4469 file server is also running. This is separated from VInitVolumePackage so
4470 that a utility can fork--and each of the children can independently
4471 initialize communication with the file server */
4472 #ifdef FSSYNC_BUILD_CLIENT
4474 * connect to the fileserver SYNC service.
4476 * @return operation status
4481 * @arg VInit must equal 2.
4482 * @arg Program Type must not be fileserver or salvager.
4484 * @post connection to fileserver SYNC service established
4487 * @see VDisconnectFS
4488 * @see VChildProcReconnectFS
4495 retVal = VConnectFS_r();
4501 * connect to the fileserver SYNC service.
4503 * @return operation status
4508 * @arg VInit must equal 2.
4509 * @arg Program Type must not be fileserver or salvager.
4510 * @arg VOL_LOCK is held.
4512 * @post connection to fileserver SYNC service established
4515 * @see VDisconnectFS_r
4516 * @see VChildProcReconnectFS_r
4518 * @internal volume package internal use only.
4524 assert((VInit == 2) &&
4525 (programType != fileServer) &&
4526 (programType != salvager));
4527 rc = FSYNC_clientInit();
4534 * disconnect from the fileserver SYNC service.
4537 * @arg client should have a live connection to the fileserver.
4538 * @arg VOL_LOCK is held.
4539 * @arg Program Type must not be fileserver or salvager.
4541 * @post connection to fileserver SYNC service destroyed
4543 * @see VDisconnectFS
4545 * @see VChildProcReconnectFS_r
4547 * @internal volume package internal use only.
4550 VDisconnectFS_r(void)
4552 assert((programType != fileServer) &&
4553 (programType != salvager));
4554 FSYNC_clientFinis();
4559 * disconnect from the fileserver SYNC service.
4562 * @arg client should have a live connection to the fileserver.
4563 * @arg Program Type must not be fileserver or salvager.
4565 * @post connection to fileserver SYNC service destroyed
4567 * @see VDisconnectFS_r
4569 * @see VChildProcReconnectFS
4580 * connect to the fileserver SYNC service from a child process following a fork.
4582 * @return operation status
4587 * @arg VOL_LOCK is held.
4588 * @arg current FSYNC handle is shared with a parent process
4590 * @post current FSYNC handle is discarded and a new connection to the
4591 * fileserver SYNC service is established
4593 * @see VChildProcReconnectFS
4595 * @see VDisconnectFS_r
4597 * @internal volume package internal use only.
4600 VChildProcReconnectFS_r(void)
4602 return FSYNC_clientChildProcReconnect();
4606 * connect to the fileserver SYNC service from a child process following a fork.
4608 * @return operation status
4612 * @pre current FSYNC handle is shared with a parent process
4614 * @post current FSYNC handle is discarded and a new connection to the
4615 * fileserver SYNC service is established
4617 * @see VChildProcReconnectFS_r
4619 * @see VDisconnectFS
4622 VChildProcReconnectFS(void)
4626 ret = VChildProcReconnectFS_r();
4630 #endif /* FSSYNC_BUILD_CLIENT */
4633 /***************************************************/
4634 /* volume bitmap routines */
4635 /***************************************************/
4638 * For demand attach fs, flags parameter controls
4639 * locking behavior. If (flags & VOL_ALLOC_BITMAP_WAIT)
4640 * is set, then this function will create a reservation
4641 * and block on any other exclusive operations. Otherwise,
4642 * this function assumes the caller already has exclusive
4643 * access to vp, and we just change the volume state.
4646 VAllocBitmapEntry_r(Error * ec, Volume * vp,
4647 struct vnodeIndex *index, int flags)
4650 register byte *bp, *ep;
4651 #ifdef AFS_DEMAND_ATTACH_FS
4652 VolState state_save;
4653 #endif /* AFS_DEMAND_ATTACH_FS */
4657 /* This test is probably redundant */
4658 if (!VolumeWriteable(vp)) {
4659 *ec = (bit32) VREADONLY;
4663 #ifdef AFS_DEMAND_ATTACH_FS
4664 if (flags & VOL_ALLOC_BITMAP_WAIT) {
4665 VCreateReservation_r(vp);
4666 VWaitExclusiveState_r(vp);
4668 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
4669 #endif /* AFS_DEMAND_ATTACH_FS */
4672 if ((programType == fileServer) && !index->bitmap) {
4674 #ifndef AFS_DEMAND_ATTACH_FS
4675 /* demand attach fs uses the volume state to avoid races.
4676 * specialStatus field is not used at all */
4678 if (vp->specialStatus == VBUSY) {
4679 if (vp->goingOffline) { /* vos dump waiting for the volume to
4680 * go offline. We probably come here
4681 * from AddNewReadableResidency */
4684 while (vp->specialStatus == VBUSY) {
4685 #ifdef AFS_PTHREAD_ENV
4689 #else /* !AFS_PTHREAD_ENV */
4691 #endif /* !AFS_PTHREAD_ENV */
4695 #endif /* !AFS_DEMAND_ATTACH_FS */
4697 if (!index->bitmap) {
4698 #ifndef AFS_DEMAND_ATTACH_FS
4699 vp->specialStatus = VBUSY; /* Stop anyone else from using it. */
4700 #endif /* AFS_DEMAND_ATTACH_FS */
4701 for (i = 0; i < nVNODECLASSES; i++) {
4702 VGetBitmap_r(ec, vp, i);
4704 #ifdef AFS_DEMAND_ATTACH_FS
4705 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
4706 #else /* AFS_DEMAND_ATTACH_FS */
4707 DeleteVolumeFromHashTable(vp);
4708 vp->shuttingDown = 1; /* Let who has it free it. */
4709 vp->specialStatus = 0;
4710 #endif /* AFS_DEMAND_ATTACH_FS */
4715 #ifndef AFS_DEMAND_ATTACH_FS
4717 vp->specialStatus = 0; /* Allow others to have access. */
4718 #endif /* AFS_DEMAND_ATTACH_FS */
4721 #endif /* BITMAP_LATER */
4723 #ifdef AFS_DEMAND_ATTACH_FS
4725 #endif /* AFS_DEMAND_ATTACH_FS */
4726 bp = index->bitmap + index->bitmapOffset;
4727 ep = index->bitmap + index->bitmapSize;
4729 if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
4731 index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
4734 o = ffs(~*bp) - 1; /* ffs is documented in BSTRING(3) */
4736 ret = (VnodeId) ((bp - index->bitmap) * 8 + o);
4737 #ifdef AFS_DEMAND_ATTACH_FS
4739 #endif /* AFS_DEMAND_ATTACH_FS */
4742 bp += sizeof(bit32) /* i.e. 4 */ ;
4744 /* No bit map entry--must grow bitmap */
4746 realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
4749 bp += index->bitmapSize;
4750 memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
4751 index->bitmapOffset = index->bitmapSize;
4752 index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
4754 ret = index->bitmapOffset * 8;
4755 #ifdef AFS_DEMAND_ATTACH_FS
4757 #endif /* AFS_DEMAND_ATTACH_FS */
4760 #ifdef AFS_DEMAND_ATTACH_FS
4761 VChangeState_r(vp, state_save);
4762 if (flags & VOL_ALLOC_BITMAP_WAIT) {
4763 VCancelReservation_r(vp);
4765 #endif /* AFS_DEMAND_ATTACH_FS */
4770 VAllocBitmapEntry(Error * ec, Volume * vp, register struct vnodeIndex * index)
4774 retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
4780 VFreeBitMapEntry_r(Error * ec, register struct vnodeIndex *index,
4783 unsigned int offset;
4789 #endif /* BITMAP_LATER */
4790 offset = bitNumber >> 3;
4791 if (offset >= index->bitmapSize) {
4795 if (offset < index->bitmapOffset)
4796 index->bitmapOffset = offset & ~3; /* Truncate to nearest bit32 */
4797 *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
4801 VFreeBitMapEntry(Error * ec, register struct vnodeIndex *index,
4805 VFreeBitMapEntry_r(ec, index, bitNumber);
4809 /* this function will drop the glock internally.
4810 * for old pthread fileservers, this is safe thanks to vbusy.
4812 * for demand attach fs, caller must have already called
4813 * VCreateReservation_r and VWaitExclusiveState_r */
4815 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
4817 StreamHandle_t *file;
4820 struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
4821 struct vnodeIndex *vip = &vp->vnodeIndex[class];
4822 struct VnodeDiskObject *vnode;
4823 unsigned int unique = 0;
4827 #endif /* BITMAP_LATER */
4828 #ifdef AFS_DEMAND_ATTACH_FS
4829 VolState state_save;
4830 #endif /* AFS_DEMAND_ATTACH_FS */
4834 #ifdef AFS_DEMAND_ATTACH_FS
4835 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
4836 #endif /* AFS_DEMAND_ATTACH_FS */
4839 fdP = IH_OPEN(vip->handle);
4840 assert(fdP != NULL);
4841 file = FDH_FDOPEN(fdP, "r");
4842 assert(file != NULL);
4843 vnode = (VnodeDiskObject *) malloc(vcp->diskSize);
4844 assert(vnode != NULL);
4845 size = OS_SIZE(fdP->fd_fd);
4847 nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
4849 vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4; /* The 10 is a little extra so
4850 * a few files can be created in this volume,
4851 * the whole thing is rounded up to nearest 4
4852 * bytes, because the bit map allocator likes
4855 BitMap = (byte *) calloc(1, vip->bitmapSize);
4856 assert(BitMap != NULL);
4857 #else /* BITMAP_LATER */
4858 vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
4859 assert(vip->bitmap != NULL);
4860 vip->bitmapOffset = 0;
4861 #endif /* BITMAP_LATER */
4862 if (STREAM_SEEK(file, vcp->diskSize, 0) != -1) {
4864 for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
4865 if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
4867 if (vnode->type != vNull) {
4868 if (vnode->vnodeMagic != vcp->magic) {
4869 Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
4874 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
4875 #else /* BITMAP_LATER */
4876 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
4877 #endif /* BITMAP_LATER */
4878 if (unique <= vnode->uniquifier)
4879 unique = vnode->uniquifier + 1;
4881 #ifndef AFS_PTHREAD_ENV
4882 if ((bitNumber & 0x00ff) == 0x0ff) { /* every 256 iterations */
4885 #endif /* !AFS_PTHREAD_ENV */
4888 if (vp->nextVnodeUnique < unique) {
4889 Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
4892 /* Paranoia, partly justified--I think fclose after fdopen
4893 * doesn't seem to close fd. In any event, the documentation
4894 * doesn't specify, so it's safer to close it twice.
4902 /* There may have been a racing condition with some other thread, both
4903 * creating the bitmaps for this volume. If the other thread was faster
4904 * the pointer to bitmap should already be filled and we can free ours.
4906 if (vip->bitmap == NULL) {
4907 vip->bitmap = BitMap;
4908 vip->bitmapOffset = 0;
4910 free((byte *) BitMap);
4911 #endif /* BITMAP_LATER */
4912 #ifdef AFS_DEMAND_ATTACH_FS
4913 VChangeState_r(vp, state_save);
4914 #endif /* AFS_DEMAND_ATTACH_FS */
4918 /***************************************************/
4919 /* Volume Path and Volume Number utility routines */
4920 /***************************************************/
4923 * find the first occurrence of a volume header file and return the path.
4925 * @param[out] ec outbound error code
4926 * @param[in] volumeId volume id to find
4927 * @param[out] partitionp pointer to disk partition path string
4928 * @param[out] namep pointer to volume header file name string
4930 * @post path to first occurrence of volume header is returned in partitionp
4931 * and namep, or ec is set accordingly.
4933 * @warning this function is NOT re-entrant -- partitionp and namep point to
4934 * static data segments
4936 * @note if a volume utility inadvertently leaves behind a stale volume header
4937 * on a vice partition, it is possible for callers to get the wrong one,
4938 * depending on the order of the disk partition linked list.
4942 VGetVolumePath(Error * ec, VolId volumeId, char **partitionp, char **namep)
4944 static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
4945 char path[VMAXPATHLEN];
4947 struct DiskPartition64 *dp;
4951 (void)afs_snprintf(&name[1], (sizeof name) - 1, VFORMAT, afs_printable_uint32_lu(volumeId));
4952 for (dp = DiskPartitionList; dp; dp = dp->next) {
4953 struct afs_stat status;
4954 strcpy(path, VPartitionPath(dp));
4956 if (afs_stat(path, &status) == 0) {
4957 strcpy(partition, dp->name);
4964 *partitionp = *namep = NULL;
4966 *partitionp = partition;
4972 * extract a volume number from a volume header filename string.
4974 * @param[in] name volume header filename string
4976 * @return volume number
4978 * @note the string must be of the form VFORMAT. the only permissible
4979 * deviation is a leading '/' character.
4984 VolumeNumber(char *name)
4988 return atoi(name + 1);
4992 * compute the volume header filename.
4994 * @param[in] volumeId
4996 * @return volume header filename
4998 * @post volume header filename string is constructed
5000 * @warning this function is NOT re-entrant -- the returned string is
5001 * stored in a static char array. see VolumeExternalName_r
5002 * for a re-entrant equivalent.
5004 * @see VolumeExternalName_r
5006 * @deprecated due to the above re-entrancy warning, this interface should
5007 * be considered deprecated. Please use VolumeExternalName_r
5011 VolumeExternalName(VolumeId volumeId)
5013 static char name[VMAXPATHLEN];
5014 (void)afs_snprintf(name, sizeof name, VFORMAT, afs_printable_uint32_lu(volumeId));
5019 * compute the volume header filename.
5021 * @param[in] volumeId
5022 * @param[inout] name array in which to store filename
5023 * @param[in] len length of name array
5025 * @return result code from afs_snprintf
5027 * @see VolumeExternalName
5030 * @note re-entrant equivalent of VolumeExternalName
5032 * @internal volume package internal use only.
5034 #ifdef AFS_DEMAND_ATTACH_FS
5036 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
5038 return afs_snprintf(name, len, VFORMAT, afs_printable_uint32_lu(volumeId));
5043 /***************************************************/
5044 /* Volume Usage Statistics routines */
5045 /***************************************************/
5047 #if OPENAFS_VOL_STATS
5048 #define OneDay (86400) /* 24 hours' worth of seconds */
5050 #define OneDay (24*60*60) /* 24 hours */
5051 #endif /* OPENAFS_VOL_STATS */
5053 #define Midnight(date) ((date-TimeZoneCorrection)/OneDay*OneDay+TimeZoneCorrection)
5055 /*------------------------------------------------------------------------
5056 * [export] VAdjustVolumeStatistics
5059 * If we've passed midnight, we need to update all the day use
5060 * statistics as well as zeroing the detailed volume statistics
5061 * (if we are implementing them).
5064 * vp : Pointer to the volume structure describing the lucky
5065 * volume being considered for update.
5071 * Nothing interesting.
5075 *------------------------------------------------------------------------*/
5078 VAdjustVolumeStatistics_r(register Volume * vp)
5080 unsigned int now = FT_ApproxTime();
5082 if (now - V_dayUseDate(vp) > OneDay) {
5083 register int ndays, i;
5085 ndays = (now - V_dayUseDate(vp)) / OneDay;
5086 for (i = 6; i > ndays - 1; i--)
5087 V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
5088 for (i = 0; i < ndays - 1 && i < 7; i++)
5089 V_weekUse(vp)[i] = 0;
5091 V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
5093 V_dayUseDate(vp) = Midnight(now);
5095 #if OPENAFS_VOL_STATS
5097 * All we need to do is bzero the entire VOL_STATS_BYTES of
5098 * the detailed volume statistics area.
5100 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
5101 #endif /* OPENAFS_VOL_STATS */
5104 /*It's been more than a day of collection */
5106 * Always return happily.
5109 } /*VAdjustVolumeStatistics */
5112 VAdjustVolumeStatistics(register Volume * vp)
5116 retVal = VAdjustVolumeStatistics_r(vp);
5122 VBumpVolumeUsage_r(register Volume * vp)
5124 unsigned int now = FT_ApproxTime();
5125 V_accessDate(vp) = now;
5126 if (now - V_dayUseDate(vp) > OneDay)
5127 VAdjustVolumeStatistics_r(vp);
5129 * Save the volume header image to disk after every 128 bumps to dayUse.
5131 if ((V_dayUse(vp)++ & 127) == 0) {
5133 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
5138 VBumpVolumeUsage(register Volume * vp)
5141 VBumpVolumeUsage_r(vp);
5146 VSetDiskUsage_r(void)
5148 #ifndef AFS_DEMAND_ATTACH_FS
5149 static int FifteenMinuteCounter = 0;
5153 /* NOTE: Don't attempt to access the partitions list until the
5154 * initialization level indicates that all volumes are attached,
5155 * which implies that all partitions are initialized. */
5156 #ifdef AFS_PTHREAD_ENV
5158 #else /* AFS_PTHREAD_ENV */
5160 #endif /* AFS_PTHREAD_ENV */
5163 VResetDiskUsage_r();
5165 #ifndef AFS_DEMAND_ATTACH_FS
5166 if (++FifteenMinuteCounter == 3) {
5167 FifteenMinuteCounter = 0;
5170 #endif /* !AFS_DEMAND_ATTACH_FS */
5182 /***************************************************/
5183 /* Volume Update List routines */
5184 /***************************************************/
5186 /* The number of minutes that a volume hasn't been updated before the
5187 * "Dont salvage" flag in the volume header will be turned on */
5188 #define SALVAGE_INTERVAL (10*60)
5193 * volume update list functionality has been moved into the VLRU
5194 * the DONT_SALVAGE flag is now set during VLRU demotion
5197 #ifndef AFS_DEMAND_ATTACH_FS
5198 static VolumeId *UpdateList = NULL; /* Pointer to array of Volume ID's */
5199 static int nUpdatedVolumes = 0; /* Updated with entry in UpdateList, salvage after crash flag on */
5200 static int updateSize = 0; /* number of entries possible */
5201 #define UPDATE_LIST_SIZE 128 /* initial size increment (must be a power of 2!) */
5202 #endif /* !AFS_DEMAND_ATTACH_FS */
5205 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
5208 vp->updateTime = FT_ApproxTime();
5209 if (V_dontSalvage(vp) == 0)
5211 V_dontSalvage(vp) = 0;
5212 VSyncVolume_r(ec, vp, 0);
5213 #ifdef AFS_DEMAND_ATTACH_FS
5214 V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
5215 #else /* !AFS_DEMAND_ATTACH_FS */
5218 if (UpdateList == NULL) {
5219 updateSize = UPDATE_LIST_SIZE;
5220 UpdateList = (VolumeId *) malloc(sizeof(VolumeId) * updateSize);
5222 if (nUpdatedVolumes == updateSize) {
5224 if (updateSize > 524288) {
5225 Log("warning: there is likely a bug in the volume update scanner\n");
5229 (VolumeId *) realloc(UpdateList,
5230 sizeof(VolumeId) * updateSize);
5233 assert(UpdateList != NULL);
5234 UpdateList[nUpdatedVolumes++] = V_id(vp);
5235 #endif /* !AFS_DEMAND_ATTACH_FS */
5238 #ifndef AFS_DEMAND_ATTACH_FS
5240 VScanUpdateList(void)
5242 register int i, gap;
5243 register Volume *vp;
5245 afs_uint32 now = FT_ApproxTime();
5246 /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
5247 for (i = gap = 0; i < nUpdatedVolumes; i++) {
5249 UpdateList[i - gap] = UpdateList[i];
5251 /* XXX this routine needlessly messes up the Volume LRU by
5252 * breaking the LRU temporal-locality assumptions.....
5253 * we should use a special volume header allocator here */
5254 vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
5257 } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
5258 V_dontSalvage(vp) = DONT_SALVAGE;
5259 VUpdateVolume_r(&error, vp, 0); /* No need to fsync--not critical */
5267 #ifndef AFS_PTHREAD_ENV
5269 #endif /* !AFS_PTHREAD_ENV */
5271 nUpdatedVolumes -= gap;
5273 #endif /* !AFS_DEMAND_ATTACH_FS */
5276 /***************************************************/
5277 /* Volume LRU routines */
5278 /***************************************************/
5283 * with demand attach fs, we attempt to soft detach(1)
5284 * volumes which have not been accessed in a long time
5285 * in order to speed up fileserver shutdown
5287 * (1) by soft detach we mean a process very similar
5288 * to VOffline, except the final state of the
5289 * Volume will be VOL_STATE_PREATTACHED, instead
5290 * of the usual VOL_STATE_UNATTACHED
5292 #ifdef AFS_DEMAND_ATTACH_FS
5294 /* implementation is reminiscent of a generational GC
5296 * queue 0 is newly attached volumes. this queue is
5297 * sorted by attach timestamp
5299 * queue 1 is volumes that have been around a bit
5300 * longer than queue 0. this queue is sorted by
5303 * queue 2 is volumes tha have been around the longest.
5304 * this queue is unsorted
5306 * queue 3 is volumes that have been marked as
5307 * candidates for soft detachment. this queue is
5310 #define VLRU_GENERATIONS 3 /**< number of generations in VLRU */
5311 #define VLRU_QUEUES 5 /**< total number of VLRU queues */
5314 * definition of a VLRU queue.
5317 volatile struct rx_queue q;
5324 * main VLRU data structure.
5327 struct VLRU_q q[VLRU_QUEUES]; /**< VLRU queues */
5330 /** time interval (in seconds) between promotion passes for
5331 * each young generation queue. */
5332 afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
5334 /** time interval (in seconds) between soft detach candidate
5335 * scans for each generation queue.
5337 * scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
5338 * we perform a soft detach pass. */
5339 afs_uint32 scan_interval[VLRU_GENERATIONS+1];
5341 /* scheduler state */
5342 int next_idx; /**< next queue to receive attention */
5343 afs_uint32 last_promotion[VLRU_GENERATIONS-1]; /**< timestamp of last promotion scan */
5344 afs_uint32 last_scan[VLRU_GENERATIONS+1]; /**< timestamp of last detach scan */
5346 int scanner_state; /**< state of scanner thread */
5347 pthread_cond_t cv; /**< state transition CV */
5350 /** global VLRU state */
5351 static struct VLRU volume_LRU;
5354 * defined states for VLRU scanner thread.
5357 VLRU_SCANNER_STATE_OFFLINE = 0, /**< vlru scanner thread is offline */
5358 VLRU_SCANNER_STATE_ONLINE = 1, /**< vlru scanner thread is online */
5359 VLRU_SCANNER_STATE_SHUTTING_DOWN = 2, /**< vlru scanner thread is shutting down */
5360 VLRU_SCANNER_STATE_PAUSING = 3, /**< vlru scanner thread is getting ready to pause */
5361 VLRU_SCANNER_STATE_PAUSED = 4 /**< vlru scanner thread is paused */
5362 } vlru_thread_state_t;
5364 /* vlru disk data header stuff */
5365 #define VLRU_DISK_MAGIC 0x7a8b9cad /**< vlru disk entry magic number */
5366 #define VLRU_DISK_VERSION 1 /**< vlru disk entry version number */
5368 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
5369 #define VLRU_DUMP_EXPIRATION_TIME (60*60*24*7) /* expire vlru data after 1 week */
5372 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
5373 * soft detachment. */
5374 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
5376 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
5377 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
5379 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
5380 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
5382 /** VLRU control flag. non-zero value implies VLRU subsystem is activated. */
5383 static afs_uint32 VLRU_enabled = 1;
5385 /* queue synchronization routines */
5386 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
5387 static void VLRU_EndExclusive_r(struct VLRU_q * q);
5388 static void VLRU_Wait_r(struct VLRU_q * q);
5391 * set VLRU subsystem tunable parameters.
5393 * @param[in] option tunable option to modify
5394 * @param[in] val new value for tunable parameter
5396 * @pre @c VInitVolumePackage has not yet been called.
5398 * @post tunable parameter is modified
5402 * @note valid option parameters are:
5403 * @arg @c VLRU_SET_THRESH
5404 * set the period of inactivity after which
5405 * volumes are eligible for soft detachment
5406 * @arg @c VLRU_SET_INTERVAL
5407 * set the time interval between calls
5408 * to the volume LRU "garbage collector"
5409 * @arg @c VLRU_SET_MAX
5410 * set the max number of volumes to deallocate
5414 VLRU_SetOptions(int option, afs_uint32 val)
5416 if (option == VLRU_SET_THRESH) {
5417 VLRU_offline_thresh = val;
5418 } else if (option == VLRU_SET_INTERVAL) {
5419 VLRU_offline_interval = val;
5420 } else if (option == VLRU_SET_MAX) {
5421 VLRU_offline_max = val;
5422 } else if (option == VLRU_SET_ENABLED) {
5425 VLRU_ComputeConstants();
5429 * compute VLRU internal timing parameters.
5431 * @post VLRU scanner thread internal timing parameters are computed
5433 * @note computes internal timing parameters based upon user-modifiable
5434 * tunable parameters.
5438 * @internal volume package internal use only.
5441 VLRU_ComputeConstants(void)
5443 afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
5445 /* compute the candidate scan interval */
5446 volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
5448 /* compute the promotion intervals */
5449 volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
5450 volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
5453 /* compute the gen 0 scan interval */
5454 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
5456 /* compute the gen 0 scan interval */
5457 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
5462 * initialize VLRU subsystem.
5464 * @pre this function has not yet been called
5466 * @post VLRU subsystem is initialized and VLRU scanner thread is starting
5470 * @internal volume package internal use only.
5476 pthread_attr_t attrs;
5479 if (!VLRU_enabled) {
5480 Log("VLRU: disabled\n");
5484 /* initialize each of the VLRU queues */
5485 for (i = 0; i < VLRU_QUEUES; i++) {
5486 queue_Init(&volume_LRU.q[i]);
5487 volume_LRU.q[i].len = 0;
5488 volume_LRU.q[i].busy = 0;
5489 assert(pthread_cond_init(&volume_LRU.q[i].cv, NULL) == 0);
5492 /* setup the timing constants */
5493 VLRU_ComputeConstants();
5495 /* XXX put inside LogLevel check? */
5496 Log("VLRU: starting scanner with the following configuration parameters:\n");
5497 Log("VLRU: offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
5498 Log("VLRU: running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
5499 Log("VLRU: taking up to %d volumes offline per pass\n", VLRU_offline_max);
5500 Log("VLRU: scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
5501 Log("VLRU: scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
5502 Log("VLRU: scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
5504 /* start up the VLRU scanner */
5505 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
5506 if (programType == fileServer) {
5507 assert(pthread_cond_init(&volume_LRU.cv, NULL) == 0);
5508 assert(pthread_attr_init(&attrs) == 0);
5509 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
5510 assert(pthread_create(&tid, &attrs, &VLRU_ScannerThread, NULL) == 0);
5515 * initialize the VLRU-related fields of a newly allocated volume object.
5517 * @param[in] vp pointer to volume object
5520 * @arg @c VOL_LOCK is held.
5521 * @arg volume object is not on a VLRU queue.
5523 * @post VLRU fields are initialized to indicate that volume object is not
5524 * currently registered with the VLRU subsystem
5528 * @internal volume package interal use only.
5531 VLRU_Init_Node_r(Volume * vp)
5536 assert(queue_IsNotOnQueue(&vp->vlru));
5537 vp->vlru.idx = VLRU_QUEUE_INVALID;
5541 * add a volume object to a VLRU queue.
5543 * @param[in] vp pointer to volume object
5546 * @arg @c VOL_LOCK is held.
5547 * @arg caller MUST hold a lightweight ref on @p vp.
5548 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
5550 * @post the volume object is added to the appropriate VLRU queue
5552 * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
5553 * then the volume is added to that queue. Otherwise, the value
5554 * @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
5555 * volume is added to the NEW generation queue.
5557 * @note @c VOL_LOCK may be dropped internally
5559 * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
5560 * during the add operation, and is restored to the previous
5561 * state prior to return.
5565 * @internal volume package internal use only.
5568 VLRU_Add_r(Volume * vp)
5571 VolState state_save;
5576 if (queue_IsOnQueue(&vp->vlru))
5579 state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
5582 if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
5583 idx = VLRU_QUEUE_NEW;
5586 VLRU_Wait_r(&volume_LRU.q[idx]);
5588 /* repeat check since VLRU_Wait_r may have dropped
5590 if (queue_IsNotOnQueue(&vp->vlru)) {
5592 queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
5593 volume_LRU.q[idx].len++;
5594 V_attachFlags(vp) |= VOL_ON_VLRU;
5595 vp->stats.last_promote = FT_ApproxTime();
5598 VChangeState_r(vp, state_save);
5602 * delete a volume object from a VLRU queue.
5604 * @param[in] vp pointer to volume object
5607 * @arg @c VOL_LOCK is held.
5608 * @arg caller MUST hold a lightweight ref on @p vp.
5609 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
5611 * @post volume object is removed from the VLRU queue
5613 * @note @c VOL_LOCK may be dropped internally
5617 * @todo We should probably set volume state to something exlcusive
5618 * (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
5620 * @internal volume package internal use only.
5623 VLRU_Delete_r(Volume * vp)
5630 if (queue_IsNotOnQueue(&vp->vlru))
5636 if (idx == VLRU_QUEUE_INVALID)
5638 VLRU_Wait_r(&volume_LRU.q[idx]);
5639 } while (idx != vp->vlru.idx);
5641 /* now remove from the VLRU and update
5642 * the appropriate counter */
5643 queue_Remove(&vp->vlru);
5644 volume_LRU.q[idx].len--;
5645 vp->vlru.idx = VLRU_QUEUE_INVALID;
5646 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
5650 * tell the VLRU subsystem that a volume was just accessed.
5652 * @param[in] vp pointer to volume object
5655 * @arg @c VOL_LOCK is held
5656 * @arg caller MUST hold a lightweight ref on @p vp
5657 * @arg caller MUST NOT hold exclusive ownership of any VLRU queue
5659 * @post volume VLRU access statistics are updated. If the volume was on
5660 * the VLRU soft detach candidate queue, it is moved to the NEW
5663 * @note @c VOL_LOCK may be dropped internally
5667 * @internal volume package internal use only.
5670 VLRU_UpdateAccess_r(Volume * vp)
5672 Volume * rvp = NULL;
5677 if (queue_IsNotOnQueue(&vp->vlru))
5680 assert(V_attachFlags(vp) & VOL_ON_VLRU);
5682 /* update the access timestamp */
5683 vp->stats.last_get = FT_ApproxTime();
5686 * if the volume is on the soft detach candidate
5687 * list, we need to safely move it back to a
5688 * regular generation. this has to be done
5689 * carefully so we don't race against the scanner
5693 /* if this volume is on the soft detach candidate queue,
5694 * then grab exclusive access to the necessary queues */
5695 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
5697 VCreateReservation_r(rvp);
5699 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
5700 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
5701 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5702 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5705 /* make sure multiple threads don't race to update */
5706 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
5707 VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
5711 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5712 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
5713 VCancelReservation_r(rvp);
5718 * switch a volume between two VLRU queues.
5720 * @param[in] vp pointer to volume object
5721 * @param[in] new_idx index of VLRU queue onto which the volume will be moved
5722 * @param[in] append controls whether the volume will be appended or
5723 * prepended to the queue. A nonzero value means it will
5724 * be appended; zero means it will be prepended.
5726 * @pre The new (and old, if applicable) queue(s) must either be owned
5727 * exclusively by the calling thread for asynchronous manipulation,
5728 * or the queue(s) must be quiescent and VOL_LOCK must be held.
5729 * Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
5730 * for further details of the queue asynchronous processing mechanism.
5732 * @post If the volume object was already on a VLRU queue, it is
5733 * removed from the queue. Depending on the value of the append
5734 * parameter, the volume object is either appended or prepended
5735 * to the VLRU queue referenced by the new_idx parameter.
5739 * @see VLRU_BeginExclusive_r
5740 * @see VLRU_EndExclusive_r
5743 * @internal volume package internal use only.
5746 VLRU_SwitchQueues(Volume * vp, int new_idx, int append)
5748 if (queue_IsNotOnQueue(&vp->vlru))
5751 queue_Remove(&vp->vlru);
5752 volume_LRU.q[vp->vlru.idx].len--;
5754 /* put the volume back on the correct generational queue */
5756 queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
5758 queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
5761 volume_LRU.q[new_idx].len++;
5762 vp->vlru.idx = new_idx;
5766 * VLRU background thread.
5768 * The VLRU Scanner Thread is responsible for periodically scanning through
5769 * each VLRU queue looking for volumes which should be moved to another
5770 * queue, or soft detached.
5772 * @param[in] args unused thread arguments parameter
5774 * @return unused thread return value
5775 * @retval NULL always
5777 * @internal volume package internal use only.
5780 VLRU_ScannerThread(void * args)
5782 afs_uint32 now, min_delay, delay;
5783 int i, min_idx, min_op, overdue, state;
5785 /* set t=0 for promotion cycle to be
5786 * fileserver startup */
5787 now = FT_ApproxTime();
5788 for (i=0; i < VLRU_GENERATIONS-1; i++) {
5789 volume_LRU.last_promotion[i] = now;
5792 /* don't start the scanner until VLRU_offline_thresh
5793 * plus a small delay for VInitVolumePackage to finish
5796 sleep(VLRU_offline_thresh + 60);
5798 /* set t=0 for scan cycle to be now */
5799 now = FT_ApproxTime();
5800 for (i=0; i < VLRU_GENERATIONS+1; i++) {
5801 volume_LRU.last_scan[i] = now;
5805 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
5806 volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
5809 while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
5810 /* check to see if we've been asked to pause */
5811 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
5812 volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
5813 assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
5815 VOL_CV_WAIT(&volume_LRU.cv);
5816 } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
5819 /* scheduling can happen outside the glock */
5822 /* figure out what is next on the schedule */
5824 /* figure out a potential schedule for the new generation first */
5826 min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
5829 if (min_delay > volume_LRU.scan_interval[0]) {
5830 /* unsigned overflow -- we're overdue to run this scan */
5835 /* if we're not overdue for gen 0, figure out schedule for candidate gen */
5837 i = VLRU_QUEUE_CANDIDATE;
5838 delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
5839 if (delay < min_delay) {
5843 if (delay > volume_LRU.scan_interval[i]) {
5844 /* unsigned overflow -- we're overdue to run this scan */
5851 /* if we're still not overdue for something, figure out schedules for promotions */
5852 for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
5853 delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
5854 if (delay < min_delay) {
5859 if (delay > volume_LRU.promotion_interval[i]) {
5860 /* unsigned overflow -- we're overdue to run this promotion */
5869 /* sleep as needed */
5874 /* do whatever is next */
5877 VLRU_Promote_r(min_idx);
5878 VLRU_Demote_r(min_idx+1);
5880 VLRU_Scan_r(min_idx);
5882 now = FT_ApproxTime();
5885 Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
5887 /* signal that scanner is down */
5888 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
5889 assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
5895 * promote volumes from one VLRU generation to the next.
5897 * This routine scans a VLRU generation looking for volumes which are
5898 * eligible to be promoted to the next generation. All volumes which
5899 * meet the eligibility requirement are promoted.
5901 * Promotion eligibility is based upon meeting both of the following
5904 * @arg The volume has been accessed since the last promotion:
5905 * @c (vp->stats.last_get >= vp->stats.last_promote)
5906 * @arg The last promotion occurred at least
5907 * @c volume_LRU.promotion_interval[idx] seconds ago
5909 * As a performance optimization, promotions are "globbed". In other
5910 * words, we promote arbitrarily large contiguous sublists of elements
5913 * @param[in] idx VLRU queue index to scan
5917 * @internal VLRU internal use only.
5920 VLRU_Promote_r(int idx)
5922 int len, chaining, promote;
5923 afs_uint32 now, thresh;
5924 struct rx_queue *qp, *nqp;
5925 Volume * vp, *start = NULL, *end = NULL;
5927 /* get exclusive access to two chains, and drop the glock */
5928 VLRU_Wait_r(&volume_LRU.q[idx]);
5929 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
5930 VLRU_Wait_r(&volume_LRU.q[idx+1]);
5931 VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
5934 thresh = volume_LRU.promotion_interval[idx];
5935 now = FT_ApproxTime();
5938 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
5939 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
5940 promote = (((vp->stats.last_promote + thresh) <= now) &&
5941 (vp->stats.last_get >= vp->stats.last_promote));
5949 /* promote and prepend chain */
5950 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
5964 /* promote and prepend */
5965 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
5969 volume_LRU.q[idx].len -= len;
5970 volume_LRU.q[idx+1].len += len;
5973 /* release exclusive access to the two chains */
5975 volume_LRU.last_promotion[idx] = now;
5976 VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
5977 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
5980 /* run the demotions */
5982 VLRU_Demote_r(int idx)
5985 int len, chaining, demote;
5986 afs_uint32 now, thresh;
5987 struct rx_queue *qp, *nqp;
5988 Volume * vp, *start = NULL, *end = NULL;
5989 Volume ** salv_flag_vec = NULL;
5990 int salv_vec_offset = 0;
5992 assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
5994 /* get exclusive access to two chains, and drop the glock */
5995 VLRU_Wait_r(&volume_LRU.q[idx-1]);
5996 VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
5997 VLRU_Wait_r(&volume_LRU.q[idx]);
5998 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
6001 /* no big deal if this allocation fails */
6002 if (volume_LRU.q[idx].len) {
6003 salv_flag_vec = (Volume **) malloc(volume_LRU.q[idx].len * sizeof(Volume *));
6006 now = FT_ApproxTime();
6007 thresh = volume_LRU.promotion_interval[idx-1];
6010 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
6011 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6012 demote = (((vp->stats.last_promote + thresh) <= now) &&
6013 (vp->stats.last_get < (now - thresh)));
6015 /* we now do volume update list DONT_SALVAGE flag setting during
6016 * demotion passes */
6017 if (salv_flag_vec &&
6018 !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
6020 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
6021 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
6022 salv_flag_vec[salv_vec_offset++] = vp;
6023 VCreateReservation_r(vp);
6032 /* demote and append chain */
6033 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
6047 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
6051 volume_LRU.q[idx].len -= len;
6052 volume_LRU.q[idx-1].len += len;
6055 /* release exclusive access to the two chains */
6057 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
6058 VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
6060 /* now go back and set the DONT_SALVAGE flags as appropriate */
6061 if (salv_flag_vec) {
6063 for (i = 0; i < salv_vec_offset; i++) {
6064 vp = salv_flag_vec[i];
6065 if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
6066 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
6067 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
6070 V_attachFlags(vp) |= VOL_HDR_DONTSALV;
6071 V_dontSalvage(vp) = DONT_SALVAGE;
6072 VUpdateVolume_r(&ec, vp, 0);
6076 VCancelReservation_r(vp);
6078 free(salv_flag_vec);
6082 /* run a pass of the VLRU GC scanner */
6084 VLRU_Scan_r(int idx)
6086 afs_uint32 now, thresh;
6087 struct rx_queue *qp, *nqp;
6091 assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
6093 /* gain exclusive access to the idx VLRU */
6094 VLRU_Wait_r(&volume_LRU.q[idx]);
6095 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
6097 if (idx != VLRU_QUEUE_CANDIDATE) {
6098 /* gain exclusive access to the candidate VLRU */
6099 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6100 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6103 now = FT_ApproxTime();
6104 thresh = now - VLRU_offline_thresh;
6106 /* perform candidate selection and soft detaching */
6107 if (idx == VLRU_QUEUE_CANDIDATE) {
6108 /* soft detach some volumes from the candidate pool */
6112 for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
6113 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6114 if (i >= VLRU_offline_max) {
6117 /* check timestamp to see if it's a candidate for soft detaching */
6118 if (vp->stats.last_get <= thresh) {
6120 if (VCheckSoftDetach(vp, thresh))
6126 /* scan for volumes to become soft detach candidates */
6127 for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
6128 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6130 /* check timestamp to see if it's a candidate for soft detaching */
6131 if (vp->stats.last_get <= thresh) {
6132 VCheckSoftDetachCandidate(vp, thresh);
6135 if (!(i&0x7f)) { /* lock coarsening optimization */
6143 /* relinquish exclusive access to the VLRU chains */
6147 volume_LRU.last_scan[idx] = now;
6148 if (idx != VLRU_QUEUE_CANDIDATE) {
6149 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6151 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
6154 /* check whether volume is safe to soft detach
6155 * caller MUST NOT hold a ref count on vp */
6157 VCheckSoftDetach(Volume * vp, afs_uint32 thresh)
6161 if (vp->nUsers || vp->nWaiters)
6164 if (vp->stats.last_get <= thresh) {
6165 ret = VSoftDetachVolume_r(vp, thresh);
6171 /* check whether volume should be made a
6172 * soft detach candidate */
6174 VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh)
6177 if (vp->nUsers || vp->nWaiters)
6182 assert(idx == VLRU_QUEUE_NEW);
6184 if (vp->stats.last_get <= thresh) {
6185 /* move to candidate pool */
6186 queue_Remove(&vp->vlru);
6187 volume_LRU.q[VLRU_QUEUE_NEW].len--;
6188 queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
6189 vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
6190 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
6198 /* begin exclusive access on VLRU */
6200 VLRU_BeginExclusive_r(struct VLRU_q * q)
6202 assert(q->busy == 0);
6206 /* end exclusive access on VLRU */
6208 VLRU_EndExclusive_r(struct VLRU_q * q)
6212 assert(pthread_cond_broadcast(&q->cv) == 0);
6215 /* wait for another thread to end exclusive access on VLRU */
6217 VLRU_Wait_r(struct VLRU_q * q)
6220 VOL_CV_WAIT(&q->cv);
6225 * volume soft detach
6227 * caller MUST NOT hold a ref count on vp */
6229 VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh)
6234 assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
6236 ts_save = vp->stats.last_get;
6237 if (ts_save > thresh)
6240 if (vp->nUsers || vp->nWaiters)
6243 if (VIsExclusiveState(V_attachState(vp))) {
6247 switch (V_attachState(vp)) {
6248 case VOL_STATE_UNATTACHED:
6249 case VOL_STATE_PREATTACHED:
6250 case VOL_STATE_ERROR:
6251 case VOL_STATE_GOING_OFFLINE:
6252 case VOL_STATE_SHUTTING_DOWN:
6253 case VOL_STATE_SALVAGING:
6254 volume_LRU.q[vp->vlru.idx].len--;
6256 /* create and cancel a reservation to
6257 * give the volume an opportunity to
6259 VCreateReservation_r(vp);
6260 queue_Remove(&vp->vlru);
6261 vp->vlru.idx = VLRU_QUEUE_INVALID;
6262 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
6263 VCancelReservation_r(vp);
6269 /* hold the volume and take it offline.
6270 * no need for reservations, as VHold_r
6271 * takes care of that internally. */
6272 if (VHold_r(vp) == 0) {
6273 /* vhold drops the glock, so now we should
6274 * check to make sure we aren't racing against
6275 * other threads. if we are racing, offlining vp
6276 * would be wasteful, and block the scanner for a while
6280 (vp->shuttingDown) ||
6281 (vp->goingOffline) ||
6282 (vp->stats.last_get != ts_save)) {
6283 /* looks like we're racing someone else. bail */
6287 /* pull it off the VLRU */
6288 assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
6289 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
6290 queue_Remove(&vp->vlru);
6291 vp->vlru.idx = VLRU_QUEUE_INVALID;
6292 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
6294 /* take if offline */
6295 VOffline_r(vp, "volume has been soft detached");
6297 /* invalidate the volume header cache */
6298 FreeVolumeHeader(vp);
6301 IncUInt64(&VStats.soft_detaches);
6302 vp->stats.soft_detaches++;
6304 /* put in pre-attached state so demand
6305 * attacher can work on it */
6306 VChangeState_r(vp, VOL_STATE_PREATTACHED);
6312 #endif /* AFS_DEMAND_ATTACH_FS */
6315 /***************************************************/
6316 /* Volume Header Cache routines */
6317 /***************************************************/
6320 * volume header cache.
6322 struct volume_hdr_LRU_t volume_hdr_LRU;
6325 * initialize the volume header cache.
6327 * @param[in] howMany number of header cache entries to preallocate
6329 * @pre VOL_LOCK held. Function has never been called before.
6331 * @post howMany cache entries are allocated, initialized, and added
6332 * to the LRU list. Header cache statistics are initialized.
6334 * @note only applicable to fileServer program type. Should only be
6335 * called once during volume package initialization.
6337 * @internal volume package internal use only.
6340 VInitVolumeHeaderCache(afs_uint32 howMany)
6342 register struct volHeader *hp;
6343 if (programType != fileServer)
6345 queue_Init(&volume_hdr_LRU);
6346 volume_hdr_LRU.stats.free = 0;
6347 volume_hdr_LRU.stats.used = howMany;
6348 volume_hdr_LRU.stats.attached = 0;
6349 hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
6353 /* We are using ReleaseVolumeHeader to initialize the values on the header list
6354 * to ensure they have the right values
6356 ReleaseVolumeHeader(hp++);
6360 * get a volume header and attach it to the volume object.
6362 * @param[in] vp pointer to volume object
6364 * @return cache entry status
6365 * @retval 0 volume header was newly attached; cache data is invalid
6366 * @retval 1 volume header was previously attached; cache data is valid
6368 * @pre VOL_LOCK held. For DAFS, lightweight ref must be held on volume object.
6370 * @post volume header attached to volume object. if necessary, header cache
6371 * entry on LRU is synchronized to disk. Header is removed from LRU list.
6373 * @note VOL_LOCK may be dropped
6375 * @warning this interface does not load header data from disk. it merely
6376 * attaches a header object to the volume object, and may sync the old
6377 * header cache data out to disk in the process.
6379 * @internal volume package internal use only.
6382 GetVolumeHeader(register Volume * vp)
6385 register struct volHeader *hd;
6387 static int everLogged = 0;
6389 #ifdef AFS_DEMAND_ATTACH_FS
6390 VolState vp_save = 0, back_save = 0;
6392 /* XXX debug 9/19/05 we've apparently got
6393 * a ref counting bug somewhere that's
6394 * breaking the nUsers == 0 => header on LRU
6396 if (vp->header && queue_IsNotOnQueue(vp->header)) {
6397 Log("nUsers == 0, but header not on LRU\n");
6402 old = (vp->header != NULL); /* old == volume already has a header */
6404 if (programType != fileServer) {
6405 /* for volume utilities, we allocate volHeaders as needed */
6407 hd = (struct volHeader *)calloc(1, sizeof(*vp->header));
6411 #ifdef AFS_DEMAND_ATTACH_FS
6412 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
6416 /* for the fileserver, we keep a volume header cache */
6418 /* the header we previously dropped in the lru is
6419 * still available. pull it off the lru and return */
6422 assert(hd->back == vp);
6424 /* we need to grab a new element off the LRU */
6425 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
6426 /* grab an element and pull off of LRU */
6427 hd = queue_First(&volume_hdr_LRU, volHeader);
6430 /* LRU is empty, so allocate a new volHeader
6431 * this is probably indicative of a leak, so let the user know */
6432 hd = (struct volHeader *)calloc(1, sizeof(struct volHeader));
6435 Log("****Allocated more volume headers, probably leak****\n");
6438 volume_hdr_LRU.stats.free++;
6441 /* this header used to belong to someone else.
6442 * we'll need to check if the header needs to
6443 * be sync'd out to disk */
6445 #ifdef AFS_DEMAND_ATTACH_FS
6446 /* if hd->back were in an exclusive state, then
6447 * its volHeader would not be on the LRU... */
6448 assert(!VIsExclusiveState(V_attachState(hd->back)));
6451 if (hd->diskstuff.inUse) {
6452 /* volume was in use, so we'll need to sync
6453 * its header to disk */
6455 #ifdef AFS_DEMAND_ATTACH_FS
6456 back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
6457 vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
6458 VCreateReservation_r(hd->back);
6462 WriteVolumeHeader_r(&error, hd->back);
6463 /* Ignore errors; catch them later */
6465 #ifdef AFS_DEMAND_ATTACH_FS
6470 hd->back->header = NULL;
6471 #ifdef AFS_DEMAND_ATTACH_FS
6472 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
6474 if (hd->diskstuff.inUse) {
6475 VChangeState_r(hd->back, back_save);
6476 VCancelReservation_r(hd->back);
6477 VChangeState_r(vp, vp_save);
6481 volume_hdr_LRU.stats.attached++;
6485 #ifdef AFS_DEMAND_ATTACH_FS
6486 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
6489 volume_hdr_LRU.stats.free--;
6490 volume_hdr_LRU.stats.used++;
6492 IncUInt64(&VStats.hdr_gets);
6493 #ifdef AFS_DEMAND_ATTACH_FS
6494 IncUInt64(&vp->stats.hdr_gets);
6495 vp->stats.last_hdr_get = FT_ApproxTime();
6502 * make sure volume header is attached and contains valid cache data.
6504 * @param[out] ec outbound error code
6505 * @param[in] vp pointer to volume object
6507 * @pre VOL_LOCK held. For DAFS, lightweight ref held on vp.
6509 * @post header cache entry attached, and loaded with valid data, or
6510 * *ec is nonzero, and the header is released back into the LRU.
6512 * @internal volume package internal use only.
6515 LoadVolumeHeader(Error * ec, Volume * vp)
6517 #ifdef AFS_DEMAND_ATTACH_FS
6518 VolState state_save;
6522 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
6523 IncUInt64(&VStats.hdr_loads);
6524 state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
6527 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
6528 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
6530 IncUInt64(&vp->stats.hdr_loads);
6531 now = FT_ApproxTime();
6535 V_attachFlags(vp) |= VOL_HDR_LOADED;
6536 vp->stats.last_hdr_load = now;
6538 VChangeState_r(vp, state_save);
6540 #else /* AFS_DEMAND_ATTACH_FS */
6542 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
6543 IncUInt64(&VStats.hdr_loads);
6545 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
6546 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
6549 #endif /* AFS_DEMAND_ATTACH_FS */
6551 /* maintain (nUsers==0) => header in LRU invariant */
6552 FreeVolumeHeader(vp);
6557 * release a header cache entry back into the LRU list.
6559 * @param[in] hd pointer to volume header cache object
6561 * @pre VOL_LOCK held.
6563 * @post header cache object appended onto end of LRU list.
6565 * @note only applicable to fileServer program type.
6567 * @note used to place a header cache entry back into the
6568 * LRU pool without invalidating it as a cache entry.
6570 * @internal volume package internal use only.
6573 ReleaseVolumeHeader(register struct volHeader *hd)
6575 if (programType != fileServer)
6577 if (!hd || queue_IsOnQueue(hd)) /* no header, or header already released */
6579 queue_Append(&volume_hdr_LRU, hd);
6580 #ifdef AFS_DEMAND_ATTACH_FS
6582 V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
6585 volume_hdr_LRU.stats.free++;
6586 volume_hdr_LRU.stats.used--;
6590 * free/invalidate a volume header cache entry.
6592 * @param[in] vp pointer to volume object
6594 * @pre VOL_LOCK is held.
6596 * @post For fileserver, header cache entry is returned to LRU, and it is
6597 * invalidated as a cache entry. For volume utilities, the header
6598 * cache entry is freed.
6600 * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
6601 * whenever it is necessary to invalidate the header cache entry.
6603 * @see ReleaseVolumeHeader
6605 * @internal volume package internal use only.
6608 FreeVolumeHeader(register Volume * vp)
6610 register struct volHeader *hd = vp->header;
6613 if (programType == fileServer) {
6614 ReleaseVolumeHeader(hd);
6619 #ifdef AFS_DEMAND_ATTACH_FS
6620 V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
6622 volume_hdr_LRU.stats.attached--;
6627 /***************************************************/
6628 /* Volume Hash Table routines */
6629 /***************************************************/
6632 * set size of volume object hash table.
6634 * @param[in] logsize log(2) of desired hash table size
6636 * @return operation status
6638 * @retval -1 failure
6640 * @pre MUST be called prior to VInitVolumePackage
6642 * @post Volume Hash Table will have 2^logsize buckets
6645 VSetVolHashSize(int logsize)
6647 /* 64 to 16384 hash buckets seems like a reasonable range */
6648 if ((logsize < 6 ) || (logsize > 14)) {
6653 VolumeHashTable.Size = 1 << logsize;
6654 VolumeHashTable.Mask = VolumeHashTable.Size - 1;
6656 /* we can't yet support runtime modification of this
6657 * parameter. we'll need a configuration rwlock to
6658 * make runtime modification feasible.... */
6665 * initialize dynamic data structures for volume hash table.
6667 * @post hash table is allocated, and fields are initialized.
6669 * @internal volume package internal use only.
6672 VInitVolumeHash(void)
6676 VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
6677 sizeof(VolumeHashChainHead));
6678 assert(VolumeHashTable.Table != NULL);
6680 for (i=0; i < VolumeHashTable.Size; i++) {
6681 queue_Init(&VolumeHashTable.Table[i]);
6682 #ifdef AFS_DEMAND_ATTACH_FS
6683 assert(pthread_cond_init(&VolumeHashTable.Table[i].chain_busy_cv, NULL) == 0);
6684 #endif /* AFS_DEMAND_ATTACH_FS */
6689 * add a volume object to the hash table.
6691 * @param[in] vp pointer to volume object
6692 * @param[in] hashid hash of volume id
6694 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
6697 * @post volume is added to hash chain.
6699 * @internal volume package internal use only.
6701 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
6702 * asynchronous hash chain reordering to finish.
6705 AddVolumeToHashTable(register Volume * vp, int hashid)
6707 VolumeHashChainHead * head;
6709 if (queue_IsOnQueue(vp))
6712 head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
6714 #ifdef AFS_DEMAND_ATTACH_FS
6715 /* wait for the hash chain to become available */
6718 V_attachFlags(vp) |= VOL_IN_HASH;
6719 vp->chainCacheCheck = ++head->cacheCheck;
6720 #endif /* AFS_DEMAND_ATTACH_FS */
6723 vp->hashid = hashid;
6724 queue_Append(head, vp);
6725 vp->vnodeHashOffset = VolumeHashOffset_r();
6729 * delete a volume object from the hash table.
6731 * @param[in] vp pointer to volume object
6733 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
6736 * @post volume is removed from hash chain.
6738 * @internal volume package internal use only.
6740 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
6741 * asynchronous hash chain reordering to finish.
6744 DeleteVolumeFromHashTable(register Volume * vp)
6746 VolumeHashChainHead * head;
6748 if (!queue_IsOnQueue(vp))
6751 head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
6753 #ifdef AFS_DEMAND_ATTACH_FS
6754 /* wait for the hash chain to become available */
6757 V_attachFlags(vp) &= ~(VOL_IN_HASH);
6759 #endif /* AFS_DEMAND_ATTACH_FS */
6763 /* do NOT reset hashid to zero, as the online
6764 * salvager package may need to know the volume id
6765 * after the volume is removed from the hash */
6769 * lookup a volume object in the hash table given a volume id.
6771 * @param[out] ec error code return
6772 * @param[in] volumeId volume id
6773 * @param[in] hint volume object which we believe could be the correct
6776 * @return volume object pointer
6777 * @retval NULL no such volume id is registered with the hash table.
6779 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
6782 * @post volume object with the given id is returned. volume object and
6783 * hash chain access statistics are updated. hash chain may have
6786 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
6787 * asynchronous hash chain reordering operation to finish, or
6788 * in order for us to perform an asynchronous chain reordering.
6790 * @note Hash chain reorderings occur when the access count for the
6791 * volume object being looked up exceeds the sum of the previous
6792 * node's (the node ahead of it in the hash chain linked list)
6793 * access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
6795 * @note For DAFS, the hint parameter allows us to short-circuit if the
6796 * cacheCheck fields match between the hash chain head and the
6797 * hint volume object.
6800 VLookupVolume_r(Error * ec, VolId volumeId, Volume * hint)
6802 register int looks = 0;
6804 #ifdef AFS_DEMAND_ATTACH_FS
6807 VolumeHashChainHead * head;
6810 head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
6812 #ifdef AFS_DEMAND_ATTACH_FS
6813 /* wait for the hash chain to become available */
6816 /* check to see if we can short circuit without walking the hash chain */
6817 if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
6818 IncUInt64(&hint->stats.hash_short_circuits);
6821 #endif /* AFS_DEMAND_ATTACH_FS */
6823 /* someday we need to either do per-chain locks, RWlocks,
6824 * or both for volhash access.
6825 * (and move to a data structure with better cache locality) */
6827 /* search the chain for this volume id */
6828 for(queue_Scan(head, vp, np, Volume)) {
6830 if ((vp->hashid == volumeId)) {
6835 if (queue_IsEnd(head, vp)) {
6839 #ifdef AFS_DEMAND_ATTACH_FS
6840 /* update hash chain statistics */
6843 FillInt64(lks, 0, looks);
6844 AddUInt64(head->looks, lks, &head->looks);
6845 AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
6846 IncUInt64(&head->gets);
6851 IncUInt64(&vp->stats.hash_lookups);
6853 /* for demand attach fileserver, we permit occasional hash chain reordering
6854 * so that frequently looked up volumes move towards the head of the chain */
6855 pp = queue_Prev(vp, Volume);
6856 if (!queue_IsEnd(head, pp)) {
6857 FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
6858 AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
6859 if (GEInt64(vp->stats.hash_lookups, thresh)) {
6860 VReorderHash_r(head, pp, vp);
6864 /* update the short-circuit cache check */
6865 vp->chainCacheCheck = head->cacheCheck;
6867 #endif /* AFS_DEMAND_ATTACH_FS */
6872 #ifdef AFS_DEMAND_ATTACH_FS
6873 /* perform volume hash chain reordering.
6875 * advance a subchain beginning at vp ahead of
6876 * the adjacent subchain ending at pp */
6878 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
6880 Volume *tp, *np, *lp;
6881 afs_uint64 move_thresh;
6883 /* this should never be called if the chain is already busy, so
6884 * no need to wait for other exclusive chain ops to finish */
6886 /* this is a rather heavy set of operations,
6887 * so let's set the chain busy flag and drop
6889 VHashBeginExclusive_r(head);
6892 /* scan forward in the chain from vp looking for the last element
6893 * in the chain we want to advance */
6894 FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
6895 AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
6896 for(queue_ScanFrom(head, vp, tp, np, Volume)) {
6897 if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
6901 lp = queue_Prev(tp, Volume);
6903 /* scan backwards from pp to determine where to splice and
6904 * insert the subchain we're advancing */
6905 for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
6906 if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
6910 tp = queue_Next(tp, Volume);
6912 /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
6913 queue_MoveChainBefore(tp,vp,lp);
6916 IncUInt64(&VStats.hash_reorders);
6918 IncUInt64(&head->reorders);
6920 /* wake up any threads waiting for the hash chain */
6921 VHashEndExclusive_r(head);
6925 /* demand-attach fs volume hash
6926 * asynchronous exclusive operations */
6929 * begin an asynchronous exclusive operation on a volume hash chain.
6931 * @param[in] head pointer to volume hash chain head object
6933 * @pre VOL_LOCK held. hash chain is quiescent.
6935 * @post hash chain marked busy.
6937 * @note this interface is used in conjunction with VHashEndExclusive_r and
6938 * VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
6939 * volume hash chain. Its main use case is hash chain reordering, which
6940 * has the potential to be a highly latent operation.
6942 * @see VHashEndExclusive_r
6947 * @internal volume package internal use only.
6950 VHashBeginExclusive_r(VolumeHashChainHead * head)
6952 assert(head->busy == 0);
6957 * relinquish exclusive ownership of a volume hash chain.
6959 * @param[in] head pointer to volume hash chain head object
6961 * @pre VOL_LOCK held. thread owns the hash chain exclusively.
6963 * @post hash chain is marked quiescent. threads awaiting use of
6964 * chain are awakened.
6966 * @see VHashBeginExclusive_r
6971 * @internal volume package internal use only.
6974 VHashEndExclusive_r(VolumeHashChainHead * head)
6978 assert(pthread_cond_broadcast(&head->chain_busy_cv) == 0);
6982 * wait for all asynchronous operations on a hash chain to complete.
6984 * @param[in] head pointer to volume hash chain head object
6986 * @pre VOL_LOCK held.
6988 * @post hash chain object is quiescent.
6990 * @see VHashBeginExclusive_r
6991 * @see VHashEndExclusive_r
6995 * @note This interface should be called before any attempt to
6996 * traverse the hash chain. It is permissible for a thread
6997 * to gain exclusive access to the chain, and then perform
6998 * latent operations on the chain asynchronously wrt the
7001 * @warning if waiting is necessary, VOL_LOCK is dropped
7003 * @internal volume package internal use only.
7006 VHashWait_r(VolumeHashChainHead * head)
7008 while (head->busy) {
7009 VOL_CV_WAIT(&head->chain_busy_cv);
7012 #endif /* AFS_DEMAND_ATTACH_FS */
7015 /***************************************************/
7016 /* Volume by Partition List routines */
7017 /***************************************************/
7020 * demand attach fileserver adds a
7021 * linked list of volumes to each
7022 * partition object, thus allowing
7023 * for quick enumeration of all
7024 * volumes on a partition
7027 #ifdef AFS_DEMAND_ATTACH_FS
7029 * add a volume to its disk partition VByPList.
7031 * @param[in] vp pointer to volume object
7033 * @pre either the disk partition VByPList is owned exclusively
7034 * by the calling thread, or the list is quiescent and
7037 * @post volume is added to disk partition VByPList
7041 * @warning it is the caller's responsibility to ensure list
7044 * @see VVByPListWait_r
7045 * @see VVByPListBeginExclusive_r
7046 * @see VVByPListEndExclusive_r
7048 * @internal volume package internal use only.
7051 AddVolumeToVByPList_r(Volume * vp)
7053 if (queue_IsNotOnQueue(&vp->vol_list)) {
7054 queue_Append(&vp->partition->vol_list, &vp->vol_list);
7055 V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
7056 vp->partition->vol_list.len++;
7061 * delete a volume from its disk partition VByPList.
7063 * @param[in] vp pointer to volume object
7065 * @pre either the disk partition VByPList is owned exclusively
7066 * by the calling thread, or the list is quiescent and
7069 * @post volume is removed from the disk partition VByPList
7073 * @warning it is the caller's responsibility to ensure list
7076 * @see VVByPListWait_r
7077 * @see VVByPListBeginExclusive_r
7078 * @see VVByPListEndExclusive_r
7080 * @internal volume package internal use only.
7083 DeleteVolumeFromVByPList_r(Volume * vp)
7085 if (queue_IsOnQueue(&vp->vol_list)) {
7086 queue_Remove(&vp->vol_list);
7087 V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
7088 vp->partition->vol_list.len--;
7093 * begin an asynchronous exclusive operation on a VByPList.
7095 * @param[in] dp pointer to disk partition object
7097 * @pre VOL_LOCK held. VByPList is quiescent.
7099 * @post VByPList marked busy.
7101 * @note this interface is used in conjunction with VVByPListEndExclusive_r and
7102 * VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
7105 * @see VVByPListEndExclusive_r
7106 * @see VVByPListWait_r
7110 * @internal volume package internal use only.
7112 /* take exclusive control over the list */
7114 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
7116 assert(dp->vol_list.busy == 0);
7117 dp->vol_list.busy = 1;
7121 * relinquish exclusive ownership of a VByPList.
7123 * @param[in] dp pointer to disk partition object
7125 * @pre VOL_LOCK held. thread owns the VByPList exclusively.
7127 * @post VByPList is marked quiescent. threads awaiting use of
7128 * the list are awakened.
7130 * @see VVByPListBeginExclusive_r
7131 * @see VVByPListWait_r
7135 * @internal volume package internal use only.
7138 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
7140 assert(dp->vol_list.busy);
7141 dp->vol_list.busy = 0;
7142 assert(pthread_cond_broadcast(&dp->vol_list.cv) == 0);
7146 * wait for all asynchronous operations on a VByPList to complete.
7148 * @param[in] dp pointer to disk partition object
7150 * @pre VOL_LOCK is held.
7152 * @post disk partition's VByP list is quiescent
7156 * @note This interface should be called before any attempt to
7157 * traverse the VByPList. It is permissible for a thread
7158 * to gain exclusive access to the list, and then perform
7159 * latent operations on the list asynchronously wrt the
7162 * @warning if waiting is necessary, VOL_LOCK is dropped
7164 * @see VVByPListEndExclusive_r
7165 * @see VVByPListBeginExclusive_r
7167 * @internal volume package internal use only.
7170 VVByPListWait_r(struct DiskPartition64 * dp)
7172 while (dp->vol_list.busy) {
7173 VOL_CV_WAIT(&dp->vol_list.cv);
7176 #endif /* AFS_DEMAND_ATTACH_FS */
7178 /***************************************************/
7179 /* Volume Cache Statistics routines */
7180 /***************************************************/
7183 VPrintCacheStats_r(void)
7185 afs_uint32 get_hi, get_lo, load_hi, load_lo;
7186 register struct VnodeClassInfo *vcp;
7187 vcp = &VnodeClassInfo[vLarge];
7188 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);
7189 vcp = &VnodeClassInfo[vSmall];
7190 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);
7191 SplitInt64(VStats.hdr_gets, get_hi, get_lo);
7192 SplitInt64(VStats.hdr_loads, load_hi, load_lo);
7193 Log("Volume header cache, %d entries, %d gets, %d replacements\n",
7194 VStats.hdr_cache_size, get_lo, load_lo);
7198 VPrintCacheStats(void)
7201 VPrintCacheStats_r();
7205 #ifdef AFS_DEMAND_ATTACH_FS
7207 UInt64ToDouble(afs_uint64 * x)
7209 static double c32 = 4.0 * 1.073741824 * 1000000000.0;
7211 SplitInt64(*x, h, l);
7212 return (((double)h) * c32) + ((double) l);
7216 DoubleToPrintable(double x, char * buf, int len)
7218 static double billion = 1000000000.0;
7221 y[0] = (afs_uint32) (x / (billion * billion));
7222 y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
7223 y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
7226 snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
7228 snprintf(buf, len, "%d%09d", y[1], y[2]);
7230 snprintf(buf, len, "%d", y[2]);
7236 struct VLRUExtStatsEntry {
7240 struct VLRUExtStats {
7246 } queue_info[VLRU_QUEUE_INVALID];
7247 struct VLRUExtStatsEntry * vec;
7251 * add a 256-entry fudge factor onto the vector in case state changes
7252 * out from under us.
7254 #define VLRU_EXT_STATS_VEC_LEN_FUDGE 256
7257 * collect extended statistics for the VLRU subsystem.
7259 * @param[out] stats pointer to stats structure to be populated
7260 * @param[in] nvols number of volumes currently known to exist
7262 * @pre VOL_LOCK held
7264 * @post stats->vec allocated and populated
7266 * @return operation status
7271 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
7273 afs_uint32 cur, idx, len;
7274 struct rx_queue * qp, * nqp;
7276 struct VLRUExtStatsEntry * vec;
7278 len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
7279 vec = stats->vec = calloc(len,
7280 sizeof(struct VLRUExtStatsEntry));
7286 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
7287 VLRU_Wait_r(&volume_LRU.q[idx]);
7288 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7291 stats->queue_info[idx].start = cur;
7293 for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7295 /* out of space in vec */
7298 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7299 vec[cur].volid = vp->hashid;
7303 stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
7306 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7314 #define ENUMTOSTRING(en) #en
7315 #define ENUMCASE(en) \
7317 return ENUMTOSTRING(en); \
7321 vlru_idx_to_string(int idx)
7324 ENUMCASE(VLRU_QUEUE_NEW);
7325 ENUMCASE(VLRU_QUEUE_MID);
7326 ENUMCASE(VLRU_QUEUE_OLD);
7327 ENUMCASE(VLRU_QUEUE_CANDIDATE);
7328 ENUMCASE(VLRU_QUEUE_HELD);
7329 ENUMCASE(VLRU_QUEUE_INVALID);
7331 return "**UNKNOWN**";
7336 VPrintExtendedCacheStats_r(int flags)
7339 afs_uint32 vol_sum = 0;
7346 struct stats looks, gets, reorders, len;
7347 struct stats ch_looks, ch_gets, ch_reorders;
7349 VolumeHashChainHead *head;
7351 struct VLRUExtStats vlru_stats;
7353 /* zero out stats */
7354 memset(&looks, 0, sizeof(struct stats));
7355 memset(&gets, 0, sizeof(struct stats));
7356 memset(&reorders, 0, sizeof(struct stats));
7357 memset(&len, 0, sizeof(struct stats));
7358 memset(&ch_looks, 0, sizeof(struct stats));
7359 memset(&ch_gets, 0, sizeof(struct stats));
7360 memset(&ch_reorders, 0, sizeof(struct stats));
7362 for (i = 0; i < VolumeHashTable.Size; i++) {
7363 head = &VolumeHashTable.Table[i];
7366 VHashBeginExclusive_r(head);
7369 ch_looks.sum = UInt64ToDouble(&head->looks);
7370 ch_gets.sum = UInt64ToDouble(&head->gets);
7371 ch_reorders.sum = UInt64ToDouble(&head->reorders);
7373 /* update global statistics */
7375 looks.sum += ch_looks.sum;
7376 gets.sum += ch_gets.sum;
7377 reorders.sum += ch_reorders.sum;
7378 len.sum += (double)head->len;
7379 vol_sum += head->len;
7382 len.min = (double) head->len;
7383 len.max = (double) head->len;
7384 looks.min = ch_looks.sum;
7385 looks.max = ch_looks.sum;
7386 gets.min = ch_gets.sum;
7387 gets.max = ch_gets.sum;
7388 reorders.min = ch_reorders.sum;
7389 reorders.max = ch_reorders.sum;
7391 if (((double)head->len) < len.min)
7392 len.min = (double) head->len;
7393 if (((double)head->len) > len.max)
7394 len.max = (double) head->len;
7395 if (ch_looks.sum < looks.min)
7396 looks.min = ch_looks.sum;
7397 else if (ch_looks.sum > looks.max)
7398 looks.max = ch_looks.sum;
7399 if (ch_gets.sum < gets.min)
7400 gets.min = ch_gets.sum;
7401 else if (ch_gets.sum > gets.max)
7402 gets.max = ch_gets.sum;
7403 if (ch_reorders.sum < reorders.min)
7404 reorders.min = ch_reorders.sum;
7405 else if (ch_reorders.sum > reorders.max)
7406 reorders.max = ch_reorders.sum;
7410 if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
7411 /* compute detailed per-chain stats */
7412 struct stats hdr_loads, hdr_gets;
7413 double v_looks, v_loads, v_gets;
7415 /* initialize stats with data from first element in chain */
7416 vp = queue_First(head, Volume);
7417 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
7418 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
7419 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
7420 ch_gets.min = ch_gets.max = v_looks;
7421 hdr_loads.min = hdr_loads.max = v_loads;
7422 hdr_gets.min = hdr_gets.max = v_gets;
7423 hdr_loads.sum = hdr_gets.sum = 0;
7425 vp = queue_Next(vp, Volume);
7427 /* pull in stats from remaining elements in chain */
7428 for (queue_ScanFrom(head, vp, vp, np, Volume)) {
7429 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
7430 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
7431 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
7433 hdr_loads.sum += v_loads;
7434 hdr_gets.sum += v_gets;
7436 if (v_looks < ch_gets.min)
7437 ch_gets.min = v_looks;
7438 else if (v_looks > ch_gets.max)
7439 ch_gets.max = v_looks;
7441 if (v_loads < hdr_loads.min)
7442 hdr_loads.min = v_loads;
7443 else if (v_loads > hdr_loads.max)
7444 hdr_loads.max = v_loads;
7446 if (v_gets < hdr_gets.min)
7447 hdr_gets.min = v_gets;
7448 else if (v_gets > hdr_gets.max)
7449 hdr_gets.max = v_gets;
7452 /* compute per-chain averages */
7453 ch_gets.avg = ch_gets.sum / ((double)head->len);
7454 hdr_loads.avg = hdr_loads.sum / ((double)head->len);
7455 hdr_gets.avg = hdr_gets.sum / ((double)head->len);
7457 /* dump per-chain stats */
7458 Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
7460 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
7461 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
7462 Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
7463 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
7464 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
7465 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
7466 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
7467 Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
7468 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
7469 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
7470 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
7471 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
7472 Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
7473 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
7474 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
7475 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
7476 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
7477 } else if (flags & VOL_STATS_PER_CHAIN) {
7478 /* dump simple per-chain stats */
7479 Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
7481 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
7482 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
7483 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
7487 VHashEndExclusive_r(head);
7492 /* compute global averages */
7493 len.avg = len.sum / ((double)VolumeHashTable.Size);
7494 looks.avg = looks.sum / ((double)VolumeHashTable.Size);
7495 gets.avg = gets.sum / ((double)VolumeHashTable.Size);
7496 reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
7498 /* dump global stats */
7499 Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
7500 Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
7501 DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
7502 DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
7503 DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
7504 DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
7505 Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
7506 DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
7507 DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
7508 DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
7509 DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
7510 Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
7511 DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
7512 DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
7513 DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
7514 DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
7515 Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
7516 DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
7517 DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
7518 DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
7519 DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
7521 /* print extended disk related statistics */
7523 struct DiskPartition64 * diskP;
7524 afs_uint32 vol_count[VOLMAXPARTS+1];
7525 byte part_exists[VOLMAXPARTS+1];
7529 memset(vol_count, 0, sizeof(vol_count));
7530 memset(part_exists, 0, sizeof(part_exists));
7534 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
7536 vol_count[id] = diskP->vol_list.len;
7537 part_exists[id] = 1;
7541 for (i = 0; i <= VOLMAXPARTS; i++) {
7542 if (part_exists[i]) {
7543 /* XXX while this is currently safe, it is a violation
7544 * of the VGetPartitionById_r interface contract. */
7545 diskP = VGetPartitionById_r(i, 0);
7547 Log("Partition %s has %d online volumes\n",
7548 VPartitionPath(diskP), diskP->vol_list.len);
7555 /* print extended VLRU statistics */
7556 if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
7557 afs_uint32 idx, cur, lpos;
7561 Log("VLRU State Dump:\n\n");
7563 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
7564 Log("\t%s:\n", vlru_idx_to_string(idx));
7567 for (cur = vlru_stats.queue_info[idx].start;
7568 cur < vlru_stats.queue_info[idx].len;
7570 line[lpos++] = vlru_stats.vec[cur].volid;
7572 Log("\t\t%u, %u, %u, %u, %u,\n",
7573 line[0], line[1], line[2], line[3], line[4]);
7582 Log("\t\t%u, %u, %u, %u, %u\n",
7583 line[0], line[1], line[2], line[3], line[4]);
7588 free(vlru_stats.vec);
7595 VPrintExtendedCacheStats(int flags)
7598 VPrintExtendedCacheStats_r(flags);
7601 #endif /* AFS_DEMAND_ATTACH_FS */