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 /* start-time configurable I/O parameters */
161 ih_init_params vol_io_params;
163 #ifdef AFS_DEMAND_ATTACH_FS
164 pthread_mutex_t vol_salvsync_mutex;
167 * Set this to 1 to disallow SALVSYNC communication in all threads; used
168 * during shutdown, since the salvageserver may have gone away.
170 static volatile sig_atomic_t vol_disallow_salvsync = 0;
171 #endif /* AFS_DEMAND_ATTACH_FS */
174 extern void *calloc(), *realloc();
177 /*@printflike@*/ extern void Log(const char *format, ...);
179 /* Forward declarations */
180 static Volume *attach2(Error * ec, VolId vid, char *path,
181 register struct VolumeHeader *header,
182 struct DiskPartition64 *partp, Volume * vp,
183 int isbusy, int mode);
184 static void ReallyFreeVolume(Volume * vp);
185 #ifdef AFS_DEMAND_ATTACH_FS
186 static void FreeVolume(Volume * vp);
187 #else /* !AFS_DEMAND_ATTACH_FS */
188 #define FreeVolume(vp) ReallyFreeVolume(vp)
189 static void VScanUpdateList(void);
190 #endif /* !AFS_DEMAND_ATTACH_FS */
191 static void VInitVolumeHeaderCache(afs_uint32 howMany);
192 static int GetVolumeHeader(register Volume * vp);
193 static void ReleaseVolumeHeader(register struct volHeader *hd);
194 static void FreeVolumeHeader(register Volume * vp);
195 static void AddVolumeToHashTable(register Volume * vp, int hashid);
196 static void DeleteVolumeFromHashTable(register Volume * vp);
198 static int VHold(Volume * vp);
200 static int VHold_r(Volume * vp);
201 static void VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class);
202 static void VReleaseVolumeHandles_r(Volume * vp);
203 static void VCloseVolumeHandles_r(Volume * vp);
204 static void LoadVolumeHeader(Error * ec, Volume * vp);
205 static int VCheckOffline(register Volume * vp);
206 static int VCheckDetach(register Volume * vp);
207 static Volume * GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint, int flags);
208 #ifdef AFS_DEMAND_ATTACH_FS
209 static int VolumeExternalName_r(VolumeId volumeId, char * name, size_t len);
212 int LogLevel; /* Vice loglevel--not defined as extern so that it will be
213 * defined when not linked with vice, XXXX */
214 ProgramType programType; /* The type of program using the package */
216 /* extended volume package statistics */
219 #ifdef VOL_LOCK_DEBUG
220 pthread_t vol_glock_holder = 0;
224 #define VOLUME_BITMAP_GROWSIZE 16 /* bytes, => 128vnodes */
225 /* Must be a multiple of 4 (1 word) !! */
227 /* this parameter needs to be tunable at runtime.
228 * 128 was really inadequate for largish servers -- at 16384 volumes this
229 * puts average chain length at 128, thus an average 65 deref's to find a volptr.
230 * talk about bad spatial locality...
232 * an AVL or splay tree might work a lot better, but we'll just increase
233 * the default hash table size for now
235 #define DEFAULT_VOLUME_HASH_SIZE 256 /* Must be a power of 2!! */
236 #define DEFAULT_VOLUME_HASH_MASK (DEFAULT_VOLUME_HASH_SIZE-1)
237 #define VOLUME_HASH(volumeId) (volumeId&(VolumeHashTable.Mask))
240 * turn volume hash chains into partially ordered lists.
241 * when the threshold is exceeded between two adjacent elements,
242 * perform a chain rebalancing operation.
244 * keep the threshold high in order to keep cache line invalidates
245 * low "enough" on SMPs
247 #define VOLUME_HASH_REORDER_THRESHOLD 200
250 * when possible, don't just reorder single elements, but reorder
251 * entire chains of elements at once. a chain of elements that
252 * exceed the element previous to the pivot by at least CHAIN_THRESH
253 * accesses are moved in front of the chain whose elements have at
254 * least CHAIN_THRESH less accesses than the pivot element
256 #define VOLUME_HASH_REORDER_CHAIN_THRESH (VOLUME_HASH_REORDER_THRESHOLD / 2)
258 #include "rx/rx_queue.h"
261 VolumeHashTable_t VolumeHashTable = {
262 DEFAULT_VOLUME_HASH_SIZE,
263 DEFAULT_VOLUME_HASH_MASK,
268 static void VInitVolumeHash(void);
272 /* This macro is used where an ffs() call does not exist. Was in util/ffs.c */
276 afs_int32 ffs_tmp = x;
280 for (ffs_i = 1;; ffs_i++) {
287 #endif /* !AFS_HAVE_FFS */
289 #ifdef AFS_PTHREAD_ENV
290 typedef struct diskpartition_queue_t {
291 struct rx_queue queue;
292 struct DiskPartition64 * diskP;
293 } diskpartition_queue_t;
294 typedef struct vinitvolumepackage_thread_t {
295 struct rx_queue queue;
296 pthread_cond_t thread_done_cv;
297 int n_threads_complete;
298 } vinitvolumepackage_thread_t;
299 static void * VInitVolumePackageThread(void * args);
300 #endif /* AFS_PTHREAD_ENV */
302 static int VAttachVolumesByPartition(struct DiskPartition64 *diskP,
303 int * nAttached, int * nUnattached);
306 #ifdef AFS_DEMAND_ATTACH_FS
307 /* demand attach fileserver extensions */
310 * in the future we will support serialization of VLRU state into the fs_state
313 * these structures are the beginning of that effort
315 struct VLRU_DiskHeader {
316 struct versionStamp stamp; /* magic and structure version number */
317 afs_uint32 mtime; /* time of dump to disk */
318 afs_uint32 num_records; /* number of VLRU_DiskEntry records */
321 struct VLRU_DiskEntry {
322 afs_uint32 vid; /* volume ID */
323 afs_uint32 idx; /* generation */
324 afs_uint32 last_get; /* timestamp of last get */
327 struct VLRU_StartupQueue {
328 struct VLRU_DiskEntry * entry;
333 typedef struct vshutdown_thread_t {
335 pthread_mutex_t lock;
337 pthread_cond_t master_cv;
339 int n_threads_complete;
341 int schedule_version;
344 byte n_parts_done_pass;
345 byte part_thread_target[VOLMAXPARTS+1];
346 byte part_done_pass[VOLMAXPARTS+1];
347 struct rx_queue * part_pass_head[VOLMAXPARTS+1];
348 int stats[4][VOLMAXPARTS+1];
349 } vshutdown_thread_t;
350 static void * VShutdownThread(void * args);
353 static Volume * VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode);
354 static int VCheckFree(Volume * vp);
357 static void AddVolumeToVByPList_r(Volume * vp);
358 static void DeleteVolumeFromVByPList_r(Volume * vp);
359 static void VVByPListBeginExclusive_r(struct DiskPartition64 * dp);
360 static void VVByPListEndExclusive_r(struct DiskPartition64 * dp);
361 static void VVByPListWait_r(struct DiskPartition64 * dp);
363 /* online salvager */
364 static int VCheckSalvage(register Volume * vp);
365 static int VUpdateSalvagePriority_r(Volume * vp);
366 #ifdef SALVSYNC_BUILD_CLIENT
367 static int VScheduleSalvage_r(Volume * vp);
370 /* Volume hash table */
371 static void VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp);
372 static void VHashBeginExclusive_r(VolumeHashChainHead * head);
373 static void VHashEndExclusive_r(VolumeHashChainHead * head);
374 static void VHashWait_r(VolumeHashChainHead * head);
377 static int ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass);
378 static int ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
379 struct rx_queue ** idx);
380 static void ShutdownController(vshutdown_thread_t * params);
381 static void ShutdownCreateSchedule(vshutdown_thread_t * params);
384 static void VLRU_ComputeConstants(void);
385 static void VInitVLRU(void);
386 static void VLRU_Init_Node_r(Volume * vp);
387 static void VLRU_Add_r(Volume * vp);
388 static void VLRU_Delete_r(Volume * vp);
389 static void VLRU_UpdateAccess_r(Volume * vp);
390 static void * VLRU_ScannerThread(void * args);
391 static void VLRU_Scan_r(int idx);
392 static void VLRU_Promote_r(int idx);
393 static void VLRU_Demote_r(int idx);
394 static void VLRU_SwitchQueues(Volume * vp, int new_idx, int append);
397 static int VCheckSoftDetach(Volume * vp, afs_uint32 thresh);
398 static int VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh);
399 static int VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh);
402 pthread_key_t VThread_key;
403 VThreadOptions_t VThread_defaults = {
404 0 /**< allow salvsync */
406 #endif /* AFS_DEMAND_ATTACH_FS */
409 struct Lock vol_listLock; /* Lock obtained when listing volumes:
410 * prevents a volume from being missed
411 * if the volume is attached during a
415 static int TimeZoneCorrection; /* Number of seconds west of GMT */
417 /* Common message used when the volume goes off line */
418 char *VSalvageMessage =
419 "Files in this volume are currently unavailable; call operations";
421 int VInit; /* 0 - uninitialized,
422 * 1 - initialized but not all volumes have been attached,
423 * 2 - initialized and all volumes have been attached,
424 * 3 - initialized, all volumes have been attached, and
425 * VConnectFS() has completed. */
427 static int vinit_attach_abort = 0;
429 bit32 VolumeCacheCheck; /* Incremented everytime a volume goes on line--
430 * used to stamp volume headers and in-core
431 * vnodes. When the volume goes on-line the
432 * vnode will be invalidated
433 * access only with VOL_LOCK held */
438 /***************************************************/
439 /* Startup routines */
440 /***************************************************/
443 VInitVolumePackage(ProgramType pt, afs_uint32 nLargeVnodes, afs_uint32 nSmallVnodes,
444 int connect, afs_uint32 volcache)
446 int errors = 0; /* Number of errors while finding vice partitions. */
452 memset(&VStats, 0, sizeof(VStats));
453 VStats.hdr_cache_size = 200;
455 VInitPartitionPackage();
457 #ifdef AFS_DEMAND_ATTACH_FS
458 if (programType == fileServer) {
461 VLRU_SetOptions(VLRU_SET_ENABLED, 0);
463 assert(pthread_key_create(&VThread_key, NULL) == 0);
466 #ifdef AFS_PTHREAD_ENV
467 assert(pthread_mutex_init(&vol_glock_mutex, NULL) == 0);
468 assert(pthread_mutex_init(&vol_trans_mutex, NULL) == 0);
469 assert(pthread_cond_init(&vol_put_volume_cond, NULL) == 0);
470 assert(pthread_cond_init(&vol_sleep_cond, NULL) == 0);
471 assert(pthread_cond_init(&vol_init_attach_cond, NULL) == 0);
472 #else /* AFS_PTHREAD_ENV */
474 #endif /* AFS_PTHREAD_ENV */
475 Lock_Init(&vol_listLock);
477 srandom(time(0)); /* For VGetVolumeInfo */
478 gettimeofday(&tv, &tz);
479 TimeZoneCorrection = tz.tz_minuteswest * 60;
481 #ifdef AFS_DEMAND_ATTACH_FS
482 assert(pthread_mutex_init(&vol_salvsync_mutex, NULL) == 0);
483 #endif /* AFS_DEMAND_ATTACH_FS */
485 /* Ok, we have done enough initialization that fileserver can
486 * start accepting calls, even though the volumes may not be
487 * available just yet.
491 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_SERVER)
492 if (programType == salvageServer) {
495 #endif /* AFS_DEMAND_ATTACH_FS */
496 #ifdef FSSYNC_BUILD_SERVER
497 if (programType == fileServer) {
501 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_CLIENT)
502 if (programType == fileServer) {
503 /* establish a connection to the salvager at this point */
504 assert(VConnectSALV() != 0);
506 #endif /* AFS_DEMAND_ATTACH_FS */
508 if (volcache > VStats.hdr_cache_size)
509 VStats.hdr_cache_size = volcache;
510 VInitVolumeHeaderCache(VStats.hdr_cache_size);
512 VInitVnodes(vLarge, nLargeVnodes);
513 VInitVnodes(vSmall, nSmallVnodes);
516 errors = VAttachPartitions();
520 if (programType != fileServer) {
521 errors = VInitAttachVolumes(programType);
527 #ifdef FSSYNC_BUILD_CLIENT
528 if (programType == volumeUtility && connect) {
530 Log("Unable to connect to file server; will retry at need\n");
534 #ifdef AFS_DEMAND_ATTACH_FS
535 else if (programType == salvageServer) {
537 Log("Unable to connect to file server; aborted\n");
541 #endif /* AFS_DEMAND_ATTACH_FS */
542 #endif /* FSSYNC_BUILD_CLIENT */
547 VInitAttachVolumes(ProgramType pt)
550 if (pt == fileServer) {
551 struct DiskPartition64 *diskP;
552 #ifdef AFS_PTHREAD_ENV
553 struct vinitvolumepackage_thread_t params;
554 struct diskpartition_queue_t * dpq;
555 int i, threads, parts;
557 pthread_attr_t attrs;
559 assert(pthread_cond_init(¶ms.thread_done_cv,NULL) == 0);
561 params.n_threads_complete = 0;
563 /* create partition work queue */
564 for (parts=0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
565 dpq = (diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
568 queue_Append(¶ms,dpq);
571 threads = MIN(parts, vol_attach_threads);
574 /* spawn off a bunch of initialization threads */
575 assert(pthread_attr_init(&attrs) == 0);
576 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
578 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
579 #ifdef AFS_DEMAND_ATTACH_FS
580 Log("VInitVolumePackage: using %d threads to pre-attach volumes on %d partitions\n",
582 #else /* AFS_DEMAND_ATTACH_FS */
583 Log("VInitVolumePackage: using %d threads to attach volumes on %d partitions\n",
585 #endif /* AFS_DEMAND_ATTACH_FS */
588 for (i=0; i < threads; i++) {
591 assert(pthread_create
592 (&tid, &attrs, &VInitVolumePackageThread,
594 AFS_SIGSET_RESTORE();
597 while(params.n_threads_complete < threads) {
598 VOL_CV_WAIT(¶ms.thread_done_cv);
602 assert(pthread_attr_destroy(&attrs) == 0);
604 /* if we're only going to run one init thread, don't bother creating
606 Log("VInitVolumePackage: beginning single-threaded fileserver startup\n");
607 #ifdef AFS_DEMAND_ATTACH_FS
608 Log("VInitVolumePackage: using 1 thread to pre-attach volumes on %d partition(s)\n",
610 #else /* AFS_DEMAND_ATTACH_FS */
611 Log("VInitVolumePackage: using 1 thread to attach volumes on %d partition(s)\n",
613 #endif /* AFS_DEMAND_ATTACH_FS */
615 VInitVolumePackageThread(¶ms);
618 assert(pthread_cond_destroy(¶ms.thread_done_cv) == 0);
620 #else /* AFS_PTHREAD_ENV */
622 /* Attach all the volumes in this partition */
623 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
624 int nAttached = 0, nUnattached = 0;
625 assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
627 #endif /* AFS_PTHREAD_ENV */
630 VInit = 2; /* Initialized, and all volumes have been attached */
631 #ifdef AFS_PTHREAD_ENV
632 assert(pthread_cond_broadcast(&vol_init_attach_cond) == 0);
634 LWP_NoYieldSignal(VInitAttachVolumes);
635 #endif /* AFS_PTHREAD_ENV */
640 #ifdef AFS_PTHREAD_ENV
642 VInitVolumePackageThread(void * args) {
644 struct DiskPartition64 *diskP;
645 struct vinitvolumepackage_thread_t * params;
646 struct diskpartition_queue_t * dpq;
648 params = (vinitvolumepackage_thread_t *) args;
652 /* Attach all the volumes in this partition */
653 while (queue_IsNotEmpty(params)) {
654 int nAttached = 0, nUnattached = 0;
656 if (vinit_attach_abort) {
657 Log("Aborting initialization\n");
661 dpq = queue_First(params,diskpartition_queue_t);
667 assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
673 params->n_threads_complete++;
674 pthread_cond_signal(¶ms->thread_done_cv);
678 #endif /* AFS_PTHREAD_ENV */
681 * attach all volumes on a given disk partition
684 VAttachVolumesByPartition(struct DiskPartition64 *diskP, int * nAttached, int * nUnattached)
690 Log("Partition %s: attaching volumes\n", diskP->name);
691 dirp = opendir(VPartitionPath(diskP));
693 Log("opendir on Partition %s failed!\n", diskP->name);
697 while ((dp = readdir(dirp))) {
699 p = strrchr(dp->d_name, '.');
701 if (vinit_attach_abort) {
702 Log("Partition %s: abort attach volumes\n", diskP->name);
706 if (p != NULL && strcmp(p, VHDREXT) == 0) {
709 #ifdef AFS_DEMAND_ATTACH_FS
710 vp = VPreAttachVolumeByName(&error, diskP->name, dp->d_name);
711 #else /* AFS_DEMAND_ATTACH_FS */
712 vp = VAttachVolumeByName(&error, diskP->name, dp->d_name,
714 #endif /* AFS_DEMAND_ATTACH_FS */
715 (*(vp ? nAttached : nUnattached))++;
716 if (error == VOFFLINE)
717 Log("Volume %d stays offline (/vice/offline/%s exists)\n", VolumeNumber(dp->d_name), dp->d_name);
718 else if (LogLevel >= 5) {
719 Log("Partition %s: attached volume %d (%s)\n",
720 diskP->name, VolumeNumber(dp->d_name),
723 #if !defined(AFS_DEMAND_ATTACH_FS)
727 #endif /* AFS_DEMAND_ATTACH_FS */
731 Log("Partition %s: attached %d volumes; %d volumes not attached\n", diskP->name, *nAttached, *nUnattached);
738 /***************************************************/
739 /* Shutdown routines */
740 /***************************************************/
744 * highly multithreaded volume package shutdown
746 * with the demand attach fileserver extensions,
747 * VShutdown has been modified to be multithreaded.
748 * In order to achieve optimal use of many threads,
749 * the shutdown code involves one control thread and
750 * n shutdown worker threads. The control thread
751 * periodically examines the number of volumes available
752 * for shutdown on each partition, and produces a worker
753 * thread allocation schedule. The idea is to eliminate
754 * redundant scheduling computation on the workers by
755 * having a single master scheduler.
757 * The scheduler's objectives are:
759 * each partition with volumes remaining gets allocated
760 * at least 1 thread (assuming sufficient threads)
762 * threads are allocated proportional to the number of
763 * volumes remaining to be offlined. This ensures that
764 * the OS I/O scheduler has many requests to elevator
765 * seek on partitions that will (presumably) take the
766 * longest amount of time (from now) to finish shutdown
767 * (3) keep threads busy
768 * when there are extra threads, they are assigned to
769 * partitions using a simple round-robin algorithm
771 * In the future, we may wish to add the ability to adapt
772 * to the relative performance patterns of each disk
777 * multi-step shutdown process
779 * demand attach shutdown is a four-step process. Each
780 * shutdown "pass" shuts down increasingly more difficult
781 * volumes. The main purpose is to achieve better cache
782 * utilization during shutdown.
785 * shutdown volumes in the unattached, pre-attached
788 * shutdown attached volumes with cached volume headers
790 * shutdown all volumes in non-exclusive states
792 * shutdown all remaining volumes
795 #ifdef AFS_DEMAND_ATTACH_FS
801 struct DiskPartition64 * diskP;
802 struct diskpartition_queue_t * dpq;
803 vshutdown_thread_t params;
805 pthread_attr_t attrs;
807 memset(¶ms, 0, sizeof(vshutdown_thread_t));
810 Log("VShutdown: aborting attach volumes\n");
811 vinit_attach_abort = 1;
812 VOL_CV_WAIT(&vol_init_attach_cond);
815 for (params.n_parts=0, diskP = DiskPartitionList;
816 diskP; diskP = diskP->next, params.n_parts++);
818 Log("VShutdown: shutting down on-line volumes on %d partition%s...\n",
819 params.n_parts, params.n_parts > 1 ? "s" : "");
821 if (vol_attach_threads > 1) {
822 /* prepare for parallel shutdown */
823 params.n_threads = vol_attach_threads;
824 assert(pthread_mutex_init(¶ms.lock, NULL) == 0);
825 assert(pthread_cond_init(¶ms.cv, NULL) == 0);
826 assert(pthread_cond_init(¶ms.master_cv, NULL) == 0);
827 assert(pthread_attr_init(&attrs) == 0);
828 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
831 /* setup the basic partition information structures for
832 * parallel shutdown */
833 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
835 struct rx_queue * qp, * nqp;
839 VVByPListWait_r(diskP);
840 VVByPListBeginExclusive_r(diskP);
843 for (queue_Scan(&diskP->vol_list, qp, nqp, rx_queue)) {
844 vp = (Volume *)((char *)qp - offsetof(Volume, vol_list));
848 Log("VShutdown: partition %s has %d volumes with attached headers\n",
849 VPartitionPath(diskP), count);
852 /* build up the pass 0 shutdown work queue */
853 dpq = (struct diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
856 queue_Prepend(¶ms, dpq);
858 params.part_pass_head[diskP->index] = queue_First(&diskP->vol_list, rx_queue);
861 Log("VShutdown: beginning parallel fileserver shutdown\n");
862 Log("VShutdown: using %d threads to offline volumes on %d partition%s\n",
863 vol_attach_threads, params.n_parts, params.n_parts > 1 ? "s" : "" );
865 /* do pass 0 shutdown */
866 assert(pthread_mutex_lock(¶ms.lock) == 0);
867 for (i=0; i < params.n_threads; i++) {
868 assert(pthread_create
869 (&tid, &attrs, &VShutdownThread,
873 /* wait for all the pass 0 shutdowns to complete */
874 while (params.n_threads_complete < params.n_threads) {
875 assert(pthread_cond_wait(¶ms.master_cv, ¶ms.lock) == 0);
877 params.n_threads_complete = 0;
879 assert(pthread_cond_broadcast(¶ms.cv) == 0);
880 assert(pthread_mutex_unlock(¶ms.lock) == 0);
882 Log("VShutdown: pass 0 completed using the 1 thread per partition algorithm\n");
883 Log("VShutdown: starting passes 1 through 3 using finely-granular mp-fast algorithm\n");
885 /* run the parallel shutdown scheduler. it will drop the glock internally */
886 ShutdownController(¶ms);
888 /* wait for all the workers to finish pass 3 and terminate */
889 while (params.pass < 4) {
890 VOL_CV_WAIT(¶ms.cv);
893 assert(pthread_attr_destroy(&attrs) == 0);
894 assert(pthread_cond_destroy(¶ms.cv) == 0);
895 assert(pthread_cond_destroy(¶ms.master_cv) == 0);
896 assert(pthread_mutex_destroy(¶ms.lock) == 0);
898 /* drop the VByPList exclusive reservations */
899 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
900 VVByPListEndExclusive_r(diskP);
901 Log("VShutdown: %s stats : (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
902 VPartitionPath(diskP),
903 params.stats[0][diskP->index],
904 params.stats[1][diskP->index],
905 params.stats[2][diskP->index],
906 params.stats[3][diskP->index]);
909 Log("VShutdown: shutdown finished using %d threads\n", params.n_threads);
911 /* if we're only going to run one shutdown thread, don't bother creating
913 Log("VShutdown: beginning single-threaded fileserver shutdown\n");
915 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
916 VShutdownByPartition_r(diskP);
920 Log("VShutdown: complete.\n");
923 #else /* AFS_DEMAND_ATTACH_FS */
929 register Volume *vp, *np;
930 register afs_int32 code;
933 Log("VShutdown: aborting attach volumes\n");
934 vinit_attach_abort = 1;
935 #ifdef AFS_PTHREAD_ENV
936 VOL_CV_WAIT(&vol_init_attach_cond);
938 LWP_WaitProcess(VInitAttachVolumes);
939 #endif /* AFS_PTHREAD_ENV */
942 Log("VShutdown: shutting down on-line volumes...\n");
943 for (i = 0; i < VolumeHashTable.Size; i++) {
944 /* try to hold first volume in the hash table */
945 for (queue_Scan(&VolumeHashTable.Table[i],vp,np,Volume)) {
949 Log("VShutdown: Attempting to take volume %u offline.\n",
952 /* next, take the volume offline (drops reference count) */
953 VOffline_r(vp, "File server was shut down");
957 Log("VShutdown: complete.\n");
959 #endif /* AFS_DEMAND_ATTACH_FS */
972 * stop new activity (e.g. SALVSYNC) from occurring
974 * Use this to make the volume package less busy; for example, during
975 * shutdown. This doesn't actually shutdown/detach anything in the
976 * volume package, but prevents certain processes from ocurring. For
977 * example, preventing new SALVSYNC communication in DAFS. In theory, we
978 * could also use this to prevent new volume attachment, or prevent
979 * other programs from checking out volumes, etc.
984 #ifdef AFS_DEMAND_ATTACH_FS
985 /* make sure we don't try to contact the salvageserver, since it may
986 * not be around anymore */
987 vol_disallow_salvsync = 1;
991 #ifdef AFS_DEMAND_ATTACH_FS
994 * shutdown control thread
997 ShutdownController(vshutdown_thread_t * params)
1000 struct DiskPartition64 * diskP;
1002 vshutdown_thread_t shadow;
1004 ShutdownCreateSchedule(params);
1006 while ((params->pass < 4) &&
1007 (params->n_threads_complete < params->n_threads)) {
1008 /* recompute schedule once per second */
1010 memcpy(&shadow, params, sizeof(vshutdown_thread_t));
1014 Log("ShutdownController: schedule version=%d, vol_remaining=%d, pass=%d\n",
1015 shadow.schedule_version, shadow.vol_remaining, shadow.pass);
1016 Log("ShutdownController: n_threads_complete=%d, n_parts_done_pass=%d\n",
1017 shadow.n_threads_complete, shadow.n_parts_done_pass);
1018 for (diskP = DiskPartitionList; diskP; diskP=diskP->next) {
1020 Log("ShutdownController: part[%d] : (len=%d, thread_target=%d, done_pass=%d, pass_head=%p)\n",
1022 diskP->vol_list.len,
1023 shadow.part_thread_target[id],
1024 shadow.part_done_pass[id],
1025 shadow.part_pass_head[id]);
1031 ShutdownCreateSchedule(params);
1035 /* create the shutdown thread work schedule.
1036 * this scheduler tries to implement fairness
1037 * by allocating at least 1 thread to each
1038 * partition with volumes to be shutdown,
1039 * and then it attempts to allocate remaining
1040 * threads based upon the amount of work left
1043 ShutdownCreateSchedule(vshutdown_thread_t * params)
1045 struct DiskPartition64 * diskP;
1046 int sum, thr_workload, thr_left;
1047 int part_residue[VOLMAXPARTS+1];
1050 /* compute the total number of outstanding volumes */
1052 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1053 sum += diskP->vol_list.len;
1056 params->schedule_version++;
1057 params->vol_remaining = sum;
1062 /* compute average per-thread workload */
1063 thr_workload = sum / params->n_threads;
1064 if (sum % params->n_threads)
1067 thr_left = params->n_threads;
1068 memset(&part_residue, 0, sizeof(part_residue));
1070 /* for fairness, give every partition with volumes remaining
1071 * at least one thread */
1072 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1074 if (diskP->vol_list.len) {
1075 params->part_thread_target[id] = 1;
1078 params->part_thread_target[id] = 0;
1082 if (thr_left && thr_workload) {
1083 /* compute length-weighted workloads */
1086 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1088 delta = (diskP->vol_list.len / thr_workload) -
1089 params->part_thread_target[id];
1093 if (delta < thr_left) {
1094 params->part_thread_target[id] += delta;
1097 params->part_thread_target[id] += thr_left;
1105 /* try to assign any leftover threads to partitions that
1106 * had volume lengths closer to needing thread_target+1 */
1107 int max_residue, max_id = 0;
1109 /* compute the residues */
1110 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1112 part_residue[id] = diskP->vol_list.len -
1113 (params->part_thread_target[id] * thr_workload);
1116 /* now try to allocate remaining threads to partitions with the
1117 * highest residues */
1120 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1122 if (part_residue[id] > max_residue) {
1123 max_residue = part_residue[id];
1132 params->part_thread_target[max_id]++;
1134 part_residue[max_id] = 0;
1139 /* punt and give any remaining threads equally to each partition */
1141 if (thr_left >= params->n_parts) {
1142 alloc = thr_left / params->n_parts;
1143 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1145 params->part_thread_target[id] += alloc;
1150 /* finish off the last of the threads */
1151 for (diskP = DiskPartitionList; thr_left && diskP; diskP = diskP->next) {
1153 params->part_thread_target[id]++;
1159 /* worker thread for parallel shutdown */
1161 VShutdownThread(void * args)
1163 vshutdown_thread_t * params;
1164 int found, pass, schedule_version_save, count;
1165 struct DiskPartition64 *diskP;
1166 struct diskpartition_queue_t * dpq;
1169 params = (vshutdown_thread_t *) args;
1171 /* acquire the shutdown pass 0 lock */
1172 assert(pthread_mutex_lock(¶ms->lock) == 0);
1174 /* if there's still pass 0 work to be done,
1175 * get a work entry, and do a pass 0 shutdown */
1176 if (queue_IsNotEmpty(params)) {
1177 dpq = queue_First(params, diskpartition_queue_t);
1179 assert(pthread_mutex_unlock(¶ms->lock) == 0);
1185 while (ShutdownVolumeWalk_r(diskP, 0, ¶ms->part_pass_head[id]))
1187 params->stats[0][diskP->index] = count;
1188 assert(pthread_mutex_lock(¶ms->lock) == 0);
1191 params->n_threads_complete++;
1192 if (params->n_threads_complete == params->n_threads) {
1193 /* notify control thread that all workers have completed pass 0 */
1194 assert(pthread_cond_signal(¶ms->master_cv) == 0);
1196 while (params->pass == 0) {
1197 assert(pthread_cond_wait(¶ms->cv, ¶ms->lock) == 0);
1201 assert(pthread_mutex_unlock(¶ms->lock) == 0);
1204 pass = params->pass;
1207 /* now escalate through the more complicated shutdowns */
1209 schedule_version_save = params->schedule_version;
1211 /* find a disk partition to work on */
1212 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1214 if (params->part_thread_target[id] && !params->part_done_pass[id]) {
1215 params->part_thread_target[id]--;
1222 /* hmm. for some reason the controller thread couldn't find anything for
1223 * us to do. let's see if there's anything we can do */
1224 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1226 if (diskP->vol_list.len && !params->part_done_pass[id]) {
1229 } else if (!params->part_done_pass[id]) {
1230 params->part_done_pass[id] = 1;
1231 params->n_parts_done_pass++;
1233 Log("VShutdown: done shutting down volumes on partition %s.\n",
1234 VPartitionPath(diskP));
1240 /* do work on this partition until either the controller
1241 * creates a new schedule, or we run out of things to do
1242 * on this partition */
1245 while (!params->part_done_pass[id] &&
1246 (schedule_version_save == params->schedule_version)) {
1247 /* ShutdownVolumeWalk_r will drop the glock internally */
1248 if (!ShutdownVolumeWalk_r(diskP, pass, ¶ms->part_pass_head[id])) {
1249 if (!params->part_done_pass[id]) {
1250 params->part_done_pass[id] = 1;
1251 params->n_parts_done_pass++;
1253 Log("VShutdown: done shutting down volumes on partition %s.\n",
1254 VPartitionPath(diskP));
1262 params->stats[pass][id] += count;
1264 /* ok, everyone is done this pass, proceed */
1267 params->n_threads_complete++;
1268 while (params->pass == pass) {
1269 if (params->n_threads_complete == params->n_threads) {
1270 /* we are the last thread to complete, so we will
1271 * reinitialize worker pool state for the next pass */
1272 params->n_threads_complete = 0;
1273 params->n_parts_done_pass = 0;
1275 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1277 params->part_done_pass[id] = 0;
1278 params->part_pass_head[id] = queue_First(&diskP->vol_list, rx_queue);
1281 /* compute a new thread schedule before releasing all the workers */
1282 ShutdownCreateSchedule(params);
1284 /* wake up all the workers */
1285 assert(pthread_cond_broadcast(¶ms->cv) == 0);
1288 Log("VShutdown: pass %d completed using %d threads on %d partitions\n",
1289 pass, params->n_threads, params->n_parts);
1292 VOL_CV_WAIT(¶ms->cv);
1295 pass = params->pass;
1309 /* shut down all volumes on a given disk partition
1311 * note that this function will not allow mp-fast
1312 * shutdown of a partition */
1314 VShutdownByPartition_r(struct DiskPartition64 * dp)
1320 /* wait for other exclusive ops to finish */
1321 VVByPListWait_r(dp);
1323 /* begin exclusive access */
1324 VVByPListBeginExclusive_r(dp);
1326 /* pick the low-hanging fruit first,
1327 * then do the complicated ones last
1328 * (has the advantage of keeping
1329 * in-use volumes up until the bitter end) */
1330 for (pass = 0, total=0; pass < 4; pass++) {
1331 pass_stats[pass] = ShutdownVByPForPass_r(dp, pass);
1332 total += pass_stats[pass];
1335 /* end exclusive access */
1336 VVByPListEndExclusive_r(dp);
1338 Log("VShutdownByPartition: shut down %d volumes on %s (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1339 total, VPartitionPath(dp), pass_stats[0], pass_stats[1], pass_stats[2], pass_stats[3]);
1344 /* internal shutdown functionality
1346 * for multi-pass shutdown:
1347 * 0 to only "shutdown" {pre,un}attached and error state volumes
1348 * 1 to also shutdown attached volumes w/ volume header loaded
1349 * 2 to also shutdown attached volumes w/o volume header loaded
1350 * 3 to also shutdown exclusive state volumes
1352 * caller MUST hold exclusive access on the hash chain
1353 * because we drop vol_glock_mutex internally
1355 * this function is reentrant for passes 1--3
1356 * (e.g. multiple threads can cooperate to
1357 * shutdown a partition mp-fast)
1359 * pass 0 is not scaleable because the volume state data is
1360 * synchronized by vol_glock mutex, and the locking overhead
1361 * is too high to drop the lock long enough to do linked list
1365 ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass)
1367 struct rx_queue * q = queue_First(&dp->vol_list, rx_queue);
1370 while (ShutdownVolumeWalk_r(dp, pass, &q))
1376 /* conditionally shutdown one volume on partition dp
1377 * returns 1 if a volume was shutdown in this pass,
1380 ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
1381 struct rx_queue ** idx)
1383 struct rx_queue *qp, *nqp;
1388 for (queue_ScanFrom(&dp->vol_list, qp, qp, nqp, rx_queue)) {
1389 vp = (Volume *) (((char *)qp) - offsetof(Volume, vol_list));
1393 if ((V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1394 (V_attachState(vp) != VOL_STATE_ERROR) &&
1395 (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1399 if ((V_attachState(vp) == VOL_STATE_ATTACHED) &&
1400 (vp->header == NULL)) {
1404 if (VIsExclusiveState(V_attachState(vp))) {
1409 DeleteVolumeFromVByPList_r(vp);
1410 VShutdownVolume_r(vp);
1420 * shutdown a specific volume
1422 /* caller MUST NOT hold a heavyweight ref on vp */
1424 VShutdownVolume_r(Volume * vp)
1428 VCreateReservation_r(vp);
1430 if (LogLevel >= 5) {
1431 Log("VShutdownVolume_r: vid=%u, device=%d, state=%hu\n",
1432 vp->hashid, vp->partition->device, V_attachState(vp));
1435 /* wait for other blocking ops to finish */
1436 VWaitExclusiveState_r(vp);
1438 assert(VIsValidState(V_attachState(vp)));
1440 switch(V_attachState(vp)) {
1441 case VOL_STATE_SALVAGING:
1442 /* Leave salvaging volumes alone. Any in-progress salvages will
1443 * continue working after viced shuts down. This is intentional.
1446 case VOL_STATE_PREATTACHED:
1447 case VOL_STATE_ERROR:
1448 VChangeState_r(vp, VOL_STATE_UNATTACHED);
1449 case VOL_STATE_UNATTACHED:
1451 case VOL_STATE_GOING_OFFLINE:
1452 case VOL_STATE_SHUTTING_DOWN:
1453 case VOL_STATE_ATTACHED:
1457 Log("VShutdown: Attempting to take volume %u offline.\n",
1460 /* take the volume offline (drops reference count) */
1461 VOffline_r(vp, "File server was shut down");
1468 VCancelReservation_r(vp);
1472 #endif /* AFS_DEMAND_ATTACH_FS */
1475 /***************************************************/
1476 /* Header I/O routines */
1477 /***************************************************/
1479 /* open a descriptor for the inode (h),
1480 * read in an on-disk structure into buffer (to) of size (size),
1481 * verify versionstamp in structure has magic (magic) and
1482 * optionally verify version (version) if (version) is nonzero
1485 ReadHeader(Error * ec, IHandle_t * h, char *to, int size, bit32 magic,
1488 struct versionStamp *vsn;
1503 if (FDH_SEEK(fdP, 0, SEEK_SET) < 0) {
1505 FDH_REALLYCLOSE(fdP);
1508 vsn = (struct versionStamp *)to;
1509 if (FDH_READ(fdP, to, size) != size || vsn->magic != magic) {
1511 FDH_REALLYCLOSE(fdP);
1516 /* Check is conditional, in case caller wants to inspect version himself */
1517 if (version && vsn->version != version) {
1523 WriteVolumeHeader_r(Error * ec, Volume * vp)
1525 IHandle_t *h = V_diskDataHandle(vp);
1535 if (FDH_SEEK(fdP, 0, SEEK_SET) < 0) {
1537 FDH_REALLYCLOSE(fdP);
1540 if (FDH_WRITE(fdP, (char *)&V_disk(vp), sizeof(V_disk(vp)))
1541 != sizeof(V_disk(vp))) {
1543 FDH_REALLYCLOSE(fdP);
1549 /* VolumeHeaderToDisk
1550 * Allows for storing 64 bit inode numbers in on-disk volume header
1553 /* convert in-memory representation of a volume header to the
1554 * on-disk representation of a volume header */
1556 VolumeHeaderToDisk(VolumeDiskHeader_t * dh, VolumeHeader_t * h)
1559 memset(dh, 0, sizeof(VolumeDiskHeader_t));
1560 dh->stamp = h->stamp;
1562 dh->parent = h->parent;
1564 #ifdef AFS_64BIT_IOPS_ENV
1565 dh->volumeInfo_lo = (afs_int32) h->volumeInfo & 0xffffffff;
1566 dh->volumeInfo_hi = (afs_int32) (h->volumeInfo >> 32) & 0xffffffff;
1567 dh->smallVnodeIndex_lo = (afs_int32) h->smallVnodeIndex & 0xffffffff;
1568 dh->smallVnodeIndex_hi =
1569 (afs_int32) (h->smallVnodeIndex >> 32) & 0xffffffff;
1570 dh->largeVnodeIndex_lo = (afs_int32) h->largeVnodeIndex & 0xffffffff;
1571 dh->largeVnodeIndex_hi =
1572 (afs_int32) (h->largeVnodeIndex >> 32) & 0xffffffff;
1573 dh->linkTable_lo = (afs_int32) h->linkTable & 0xffffffff;
1574 dh->linkTable_hi = (afs_int32) (h->linkTable >> 32) & 0xffffffff;
1576 dh->volumeInfo_lo = h->volumeInfo;
1577 dh->smallVnodeIndex_lo = h->smallVnodeIndex;
1578 dh->largeVnodeIndex_lo = h->largeVnodeIndex;
1579 dh->linkTable_lo = h->linkTable;
1583 /* DiskToVolumeHeader
1584 * Converts an on-disk representation of a volume header to
1585 * the in-memory representation of a volume header.
1587 * Makes the assumption that AFS has *always*
1588 * zero'd the volume header file so that high parts of inode
1589 * numbers are 0 in older (SGI EFS) volume header files.
1592 DiskToVolumeHeader(VolumeHeader_t * h, VolumeDiskHeader_t * dh)
1594 memset(h, 0, sizeof(VolumeHeader_t));
1595 h->stamp = dh->stamp;
1597 h->parent = dh->parent;
1599 #ifdef AFS_64BIT_IOPS_ENV
1601 (Inode) dh->volumeInfo_lo | ((Inode) dh->volumeInfo_hi << 32);
1603 h->smallVnodeIndex =
1604 (Inode) dh->smallVnodeIndex_lo | ((Inode) dh->
1605 smallVnodeIndex_hi << 32);
1607 h->largeVnodeIndex =
1608 (Inode) dh->largeVnodeIndex_lo | ((Inode) dh->
1609 largeVnodeIndex_hi << 32);
1611 (Inode) dh->linkTable_lo | ((Inode) dh->linkTable_hi << 32);
1613 h->volumeInfo = dh->volumeInfo_lo;
1614 h->smallVnodeIndex = dh->smallVnodeIndex_lo;
1615 h->largeVnodeIndex = dh->largeVnodeIndex_lo;
1616 h->linkTable = dh->linkTable_lo;
1621 /***************************************************/
1622 /* Volume Attachment routines */
1623 /***************************************************/
1625 #ifdef AFS_DEMAND_ATTACH_FS
1627 * pre-attach a volume given its path.
1629 * @param[out] ec outbound error code
1630 * @param[in] partition partition path string
1631 * @param[in] name volume id string
1633 * @return volume object pointer
1635 * @note A pre-attached volume will only have its partition
1636 * and hashid fields initialized. At first call to
1637 * VGetVolume, the volume will be fully attached.
1641 VPreAttachVolumeByName(Error * ec, char *partition, char *name)
1645 vp = VPreAttachVolumeByName_r(ec, partition, name);
1651 * pre-attach a volume given its path.
1653 * @param[out] ec outbound error code
1654 * @param[in] partition path to vice partition
1655 * @param[in] name volume id string
1657 * @return volume object pointer
1659 * @pre VOL_LOCK held
1661 * @internal volume package internal use only.
1664 VPreAttachVolumeByName_r(Error * ec, char *partition, char *name)
1666 return VPreAttachVolumeById_r(ec,
1668 VolumeNumber(name));
1672 * pre-attach a volume given its path and numeric volume id.
1674 * @param[out] ec error code return
1675 * @param[in] partition path to vice partition
1676 * @param[in] volumeId numeric volume id
1678 * @return volume object pointer
1680 * @pre VOL_LOCK held
1682 * @internal volume package internal use only.
1685 VPreAttachVolumeById_r(Error * ec,
1690 struct DiskPartition64 *partp;
1694 assert(programType == fileServer);
1696 if (!(partp = VGetPartition_r(partition, 0))) {
1698 Log("VPreAttachVolumeById_r: Error getting partition (%s)\n", partition);
1702 vp = VLookupVolume_r(ec, volumeId, NULL);
1707 return VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
1711 * preattach a volume.
1713 * @param[out] ec outbound error code
1714 * @param[in] partp pointer to partition object
1715 * @param[in] vp pointer to volume object
1716 * @param[in] vid volume id
1718 * @return volume object pointer
1720 * @pre VOL_LOCK is held.
1722 * @warning Returned volume object pointer does not have to
1723 * equal the pointer passed in as argument vp. There
1724 * are potential race conditions which can result in
1725 * the pointers having different values. It is up to
1726 * the caller to make sure that references are handled
1727 * properly in this case.
1729 * @note If there is already a volume object registered with
1730 * the same volume id, its pointer MUST be passed as
1731 * argument vp. Failure to do so will result in a silent
1732 * failure to preattach.
1734 * @internal volume package internal use only.
1737 VPreAttachVolumeByVp_r(Error * ec,
1738 struct DiskPartition64 * partp,
1746 /* check to see if pre-attach already happened */
1748 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1749 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
1750 !VIsErrorState(V_attachState(vp))) {
1752 * pre-attach is a no-op in all but the following cases:
1754 * - volume is unattached
1755 * - volume is in an error state
1756 * - volume is pre-attached
1758 Log("VPreattachVolumeByVp_r: volume %u not in quiescent state\n", vid);
1761 /* we're re-attaching a volume; clear out some old state */
1762 memset(&vp->salvage, 0, sizeof(struct VolumeOnlineSalvage));
1764 if (V_partition(vp) != partp) {
1765 /* XXX potential race */
1766 DeleteVolumeFromVByPList_r(vp);
1769 /* if we need to allocate a new Volume struct,
1770 * go ahead and drop the vol glock, otherwise
1771 * do the basic setup synchronised, as it's
1772 * probably not worth dropping the lock */
1775 /* allocate the volume structure */
1776 vp = nvp = (Volume *) malloc(sizeof(Volume));
1778 memset(vp, 0, sizeof(Volume));
1779 queue_Init(&vp->vnode_list);
1780 assert(pthread_cond_init(&V_attachCV(vp), NULL) == 0);
1783 /* link the volume with its associated vice partition */
1784 vp->device = partp->device;
1785 vp->partition = partp;
1788 vp->specialStatus = 0;
1790 /* if we dropped the lock, reacquire the lock,
1791 * check for pre-attach races, and then add
1792 * the volume to the hash table */
1795 nvp = VLookupVolume_r(ec, vid, NULL);
1800 } else if (nvp) { /* race detected */
1805 /* hack to make up for VChangeState_r() decrementing
1806 * the old state counter */
1807 VStats.state_levels[0]++;
1811 /* put pre-attached volume onto the hash table
1812 * and bring it up to the pre-attached state */
1813 AddVolumeToHashTable(vp, vp->hashid);
1814 AddVolumeToVByPList_r(vp);
1815 VLRU_Init_Node_r(vp);
1816 VChangeState_r(vp, VOL_STATE_PREATTACHED);
1819 Log("VPreAttachVolumeByVp_r: volume %u pre-attached\n", vp->hashid);
1827 #endif /* AFS_DEMAND_ATTACH_FS */
1829 /* Attach an existing volume, given its pathname, and return a
1830 pointer to the volume header information. The volume also
1831 normally goes online at this time. An offline volume
1832 must be reattached to make it go online */
1834 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
1838 retVal = VAttachVolumeByName_r(ec, partition, name, mode);
1844 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
1846 register Volume *vp = NULL;
1848 struct afs_stat status;
1849 struct VolumeDiskHeader diskHeader;
1850 struct VolumeHeader iheader;
1851 struct DiskPartition64 *partp;
1855 #ifdef AFS_DEMAND_ATTACH_FS
1856 VolumeStats stats_save;
1858 #endif /* AFS_DEMAND_ATTACH_FS */
1862 volumeId = VolumeNumber(name);
1864 if (!(partp = VGetPartition_r(partition, 0))) {
1866 Log("VAttachVolume: Error getting partition (%s)\n", partition);
1870 if (programType == volumeUtility) {
1872 VLockPartition_r(partition);
1873 } else if (programType == fileServer) {
1874 #ifdef AFS_DEMAND_ATTACH_FS
1875 /* lookup the volume in the hash table */
1876 vp = VLookupVolume_r(ec, volumeId, NULL);
1882 /* save any counters that are supposed to
1883 * be monotonically increasing over the
1884 * lifetime of the fileserver */
1885 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
1887 memset(&stats_save, 0, sizeof(VolumeStats));
1890 /* if there's something in the hash table, and it's not
1891 * in the pre-attach state, then we may need to detach
1892 * it before proceeding */
1893 if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1894 VCreateReservation_r(vp);
1895 VWaitExclusiveState_r(vp);
1897 /* at this point state must be one of:
1906 if (vp->specialStatus == VBUSY)
1909 /* if it's already attached, see if we can return it */
1910 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
1911 VGetVolumeByVp_r(ec, vp);
1912 if (V_inUse(vp) == fileServer) {
1913 VCancelReservation_r(vp);
1917 /* otherwise, we need to detach, and attempt to re-attach */
1918 VDetachVolume_r(ec, vp);
1920 Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
1923 /* if it isn't fully attached, delete from the hash tables,
1924 and let the refcounter handle the rest */
1925 DeleteVolumeFromHashTable(vp);
1926 DeleteVolumeFromVByPList_r(vp);
1929 VCancelReservation_r(vp);
1933 /* pre-attach volume if it hasn't been done yet */
1935 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
1936 (V_attachState(vp) == VOL_STATE_ERROR)) {
1938 vp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
1946 /* handle pre-attach races
1948 * multiple threads can race to pre-attach a volume,
1949 * but we can't let them race beyond that
1951 * our solution is to let the first thread to bring
1952 * the volume into an exclusive state win; the other
1953 * threads just wait until it finishes bringing the
1954 * volume online, and then they do a vgetvolumebyvp
1956 if (svp && (svp != vp)) {
1957 /* wait for other exclusive ops to finish */
1958 VCreateReservation_r(vp);
1959 VWaitExclusiveState_r(vp);
1961 /* get a heavyweight ref, kill the lightweight ref, and return */
1962 VGetVolumeByVp_r(ec, vp);
1963 VCancelReservation_r(vp);
1967 /* at this point, we are chosen as the thread to do
1968 * demand attachment for this volume. all other threads
1969 * doing a getvolume on vp->hashid will block until we finish */
1971 /* make sure any old header cache entries are invalidated
1972 * before proceeding */
1973 FreeVolumeHeader(vp);
1975 VChangeState_r(vp, VOL_STATE_ATTACHING);
1977 /* restore any saved counters */
1978 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
1979 #else /* AFS_DEMAND_ATTACH_FS */
1980 vp = VGetVolume_r(ec, volumeId);
1982 if (V_inUse(vp) == fileServer)
1984 if (vp->specialStatus == VBUSY)
1986 VDetachVolume_r(ec, vp);
1988 Log("VAttachVolume: Error detaching volume (%s)\n", name);
1992 #endif /* AFS_DEMAND_ATTACH_FS */
1996 strcpy(path, VPartitionPath(partp));
2002 if ((fd = afs_open(path, O_RDONLY)) == -1 || afs_fstat(fd, &status) == -1) {
2003 Log("VAttachVolume: Failed to open %s (errno %d)\n", path, errno);
2010 n = read(fd, &diskHeader, sizeof(diskHeader));
2012 if (n != sizeof(diskHeader)
2013 || diskHeader.stamp.magic != VOLUMEHEADERMAGIC) {
2014 Log("VAttachVolume: Error reading volume header %s\n", path);
2019 if (diskHeader.stamp.version != VOLUMEHEADERVERSION) {
2020 Log("VAttachVolume: Volume %s, version number is incorrect; volume needs salvaged\n", path);
2026 DiskToVolumeHeader(&iheader, &diskHeader);
2027 #ifdef FSSYNC_BUILD_CLIENT
2028 if (programType == volumeUtility && mode != V_SECRETLY && mode != V_PEEK) {
2030 if (FSYNC_VolOp(iheader.id, partition, FSYNC_VOL_NEEDVOLUME, mode, NULL)
2032 Log("VAttachVolume: attach of volume %u apparently denied by file server\n", iheader.id);
2033 *ec = VNOVOL; /* XXXX */
2041 vp = (Volume *) calloc(1, sizeof(Volume));
2043 vp->device = partp->device;
2044 vp->partition = partp;
2045 queue_Init(&vp->vnode_list);
2046 #ifdef AFS_DEMAND_ATTACH_FS
2047 assert(pthread_cond_init(&V_attachCV(vp), NULL) == 0);
2048 #endif /* AFS_DEMAND_ATTACH_FS */
2051 /* attach2 is entered without any locks, and returns
2052 * with vol_glock_mutex held */
2053 vp = attach2(ec, volumeId, path, &iheader, partp, vp, isbusy, mode);
2055 if (programType == volumeUtility && vp) {
2056 if ((mode == V_VOLUPD) || (VolumeWriteable(vp) && (mode == V_CLONE))) {
2057 /* mark volume header as in use so that volser crashes lead to a
2058 * salvage attempt */
2059 VUpdateVolume_r(ec, vp, 0);
2061 #ifdef AFS_DEMAND_ATTACH_FS
2062 /* for dafs, we should tell the fileserver, except for V_PEEK
2063 * where we know it is not necessary */
2064 if (mode == V_PEEK) {
2065 vp->needsPutBack = 0;
2067 vp->needsPutBack = 1;
2069 #else /* !AFS_DEMAND_ATTACH_FS */
2070 /* duplicate computation in fssync.c about whether the server
2071 * takes the volume offline or not. If the volume isn't
2072 * offline, we must not return it when we detach the volume,
2073 * or the server will abort */
2074 if (mode == V_READONLY || mode == V_PEEK
2075 || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
2076 vp->needsPutBack = 0;
2078 vp->needsPutBack = 1;
2079 #endif /* !AFS_DEMAND_ATTACH_FS */
2081 /* OK, there's a problem here, but one that I don't know how to
2082 * fix right now, and that I don't think should arise often.
2083 * Basically, we should only put back this volume to the server if
2084 * it was given to us by the server, but since we don't have a vp,
2085 * we can't run the VolumeWriteable function to find out as we do
2086 * above when computing vp->needsPutBack. So we send it back, but
2087 * there's a path in VAttachVolume on the server which may abort
2088 * if this volume doesn't have a header. Should be pretty rare
2089 * for all of that to happen, but if it does, probably the right
2090 * fix is for the server to allow the return of readonly volumes
2091 * that it doesn't think are really checked out. */
2092 #ifdef FSSYNC_BUILD_CLIENT
2093 if (programType == volumeUtility && vp == NULL &&
2094 mode != V_SECRETLY && mode != V_PEEK) {
2095 FSYNC_VolOp(iheader.id, partition, FSYNC_VOL_ON, 0, NULL);
2098 if (programType == fileServer && vp) {
2099 #ifdef AFS_DEMAND_ATTACH_FS
2101 * we can get here in cases where we don't "own"
2102 * the volume (e.g. volume owned by a utility).
2103 * short circuit around potential disk header races.
2105 if (V_attachState(vp) != VOL_STATE_ATTACHED) {
2109 V_needsCallback(vp) = 0;
2111 if (VInit >= 2 && V_BreakVolumeCallbacks) {
2112 Log("VAttachVolume: Volume %u was changed externally; breaking callbacks\n", V_id(vp));
2113 (*V_BreakVolumeCallbacks) (V_id(vp));
2116 VUpdateVolume_r(ec, vp, 0);
2118 Log("VAttachVolume: Error updating volume\n");
2123 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2124 #ifndef AFS_DEMAND_ATTACH_FS
2125 /* This is a hack: by temporarily setting the incore
2126 * dontSalvage flag ON, the volume will be put back on the
2127 * Update list (with dontSalvage OFF again). It will then
2128 * come back in N minutes with DONT_SALVAGE eventually
2129 * set. This is the way that volumes that have never had
2130 * it set get it set; or that volumes that have been
2131 * offline without DONT SALVAGE having been set also
2132 * eventually get it set */
2133 V_dontSalvage(vp) = DONT_SALVAGE;
2134 #endif /* !AFS_DEMAND_ATTACH_FS */
2135 VAddToVolumeUpdateList_r(ec, vp);
2137 Log("VAttachVolume: Error adding volume to update list\n");
2144 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2149 if (programType == volumeUtility) {
2150 VUnlockPartition_r(partition);
2153 #ifdef AFS_DEMAND_ATTACH_FS
2154 /* attach failed; make sure we're in error state */
2155 if (vp && !VIsErrorState(V_attachState(vp))) {
2156 VChangeState_r(vp, VOL_STATE_ERROR);
2158 #endif /* AFS_DEMAND_ATTACH_FS */
2165 #ifdef AFS_DEMAND_ATTACH_FS
2166 /* VAttachVolumeByVp_r
2168 * finish attaching a volume that is
2169 * in a less than fully attached state
2171 /* caller MUST hold a ref count on vp */
2173 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
2175 char name[VMAXPATHLEN];
2176 int fd, n, reserve = 0;
2177 struct afs_stat status;
2178 struct VolumeDiskHeader diskHeader;
2179 struct VolumeHeader iheader;
2180 struct DiskPartition64 *partp;
2184 Volume * nvp = NULL;
2185 VolumeStats stats_save;
2188 /* volume utility should never call AttachByVp */
2189 assert(programType == fileServer);
2191 volumeId = vp->hashid;
2192 partp = vp->partition;
2193 VolumeExternalName_r(volumeId, name, sizeof(name));
2196 /* if another thread is performing a blocking op, wait */
2197 VWaitExclusiveState_r(vp);
2199 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2201 /* if it's already attached, see if we can return it */
2202 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2203 VGetVolumeByVp_r(ec, vp);
2204 if (V_inUse(vp) == fileServer) {
2207 if (vp->specialStatus == VBUSY)
2209 VDetachVolume_r(ec, vp);
2211 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2217 /* pre-attach volume if it hasn't been done yet */
2219 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2220 (V_attachState(vp) == VOL_STATE_ERROR)) {
2221 nvp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2227 VCreateReservation_r(nvp);
2233 VChangeState_r(vp, VOL_STATE_ATTACHING);
2235 /* restore monotonically increasing stats */
2236 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2241 /* compute path to disk header,
2243 * and verify magic and version stamps */
2244 strcpy(path, VPartitionPath(partp));
2250 if ((fd = afs_open(path, O_RDONLY)) == -1 || afs_fstat(fd, &status) == -1) {
2251 Log("VAttachVolume: Failed to open %s (errno %d)\n", path, errno);
2258 n = read(fd, &diskHeader, sizeof(diskHeader));
2260 if (n != sizeof(diskHeader)
2261 || diskHeader.stamp.magic != VOLUMEHEADERMAGIC) {
2262 Log("VAttachVolume: Error reading volume header %s\n", path);
2267 if (diskHeader.stamp.version != VOLUMEHEADERVERSION) {
2268 Log("VAttachVolume: Volume %s, version number is incorrect; volume needs salvaged\n", path);
2274 /* convert on-disk header format to in-memory header format */
2275 DiskToVolumeHeader(&iheader, &diskHeader);
2279 * NOTE: attach2 is entered without any locks, and returns
2280 * with vol_glock_mutex held */
2281 vp = attach2(ec, volumeId, path, &iheader, partp, vp, isbusy, mode);
2284 * the event that an error was encountered, or
2285 * the volume was not brought to an attached state
2286 * for any reason, skip to the end. We cannot
2287 * safely call VUpdateVolume unless we "own" it.
2291 (V_attachState(vp) != VOL_STATE_ATTACHED)) {
2295 V_needsCallback(vp) = 0;
2296 VUpdateVolume_r(ec, vp, 0);
2298 Log("VAttachVolume: Error updating volume %u\n", vp->hashid);
2302 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2303 #ifndef AFS_DEMAND_ATTACH_FS
2304 /* This is a hack: by temporarily setting the incore
2305 * dontSalvage flag ON, the volume will be put back on the
2306 * Update list (with dontSalvage OFF again). It will then
2307 * come back in N minutes with DONT_SALVAGE eventually
2308 * set. This is the way that volumes that have never had
2309 * it set get it set; or that volumes that have been
2310 * offline without DONT SALVAGE having been set also
2311 * eventually get it set */
2312 V_dontSalvage(vp) = DONT_SALVAGE;
2313 #endif /* !AFS_DEMAND_ATTACH_FS */
2314 VAddToVolumeUpdateList_r(ec, vp);
2316 Log("VAttachVolume: Error adding volume %u to update list\n", vp->hashid);
2323 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2327 VCancelReservation_r(nvp);
2330 if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2331 if (vp && !VIsErrorState(V_attachState(vp))) {
2332 VChangeState_r(vp, VOL_STATE_ERROR);
2339 #endif /* AFS_DEMAND_ATTACH_FS */
2342 * called without any locks held
2343 * returns with vol_glock_mutex held
2346 attach2(Error * ec, VolId volumeId, char *path, register struct VolumeHeader * header,
2347 struct DiskPartition64 * partp, register Volume * vp, int isbusy, int mode)
2349 vp->specialStatus = (byte) (isbusy ? VBUSY : 0);
2350 IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header->parent,
2351 header->largeVnodeIndex);
2352 IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header->parent,
2353 header->smallVnodeIndex);
2354 IH_INIT(vp->diskDataHandle, partp->device, header->parent,
2355 header->volumeInfo);
2356 IH_INIT(vp->linkHandle, partp->device, header->parent, header->linkTable);
2357 vp->shuttingDown = 0;
2358 vp->goingOffline = 0;
2360 #ifdef AFS_DEMAND_ATTACH_FS
2361 vp->stats.last_attach = FT_ApproxTime();
2362 vp->stats.attaches++;
2366 IncUInt64(&VStats.attaches);
2367 vp->cacheCheck = ++VolumeCacheCheck;
2368 /* just in case this ever rolls over */
2369 if (!vp->cacheCheck)
2370 vp->cacheCheck = ++VolumeCacheCheck;
2371 GetVolumeHeader(vp);
2374 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2375 /* demand attach changes the V_PEEK mechanism
2377 * we can now suck the current disk data structure over
2378 * the fssync interface without going to disk
2380 * (technically, we don't need to restrict this feature
2381 * to demand attach fileservers. However, I'm trying
2382 * to limit the number of common code changes)
2384 if (programType != fileServer && mode == V_PEEK) {
2386 res.payload.len = sizeof(VolumeDiskData);
2387 res.payload.buf = &vp->header->diskstuff;
2389 if (FSYNC_VolOp(volumeId,
2391 FSYNC_VOL_QUERY_HDR,
2394 goto disk_header_loaded;
2397 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2398 (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2399 sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2401 #ifdef AFS_DEMAND_ATTACH_FS
2404 IncUInt64(&VStats.hdr_loads);
2405 IncUInt64(&vp->stats.hdr_loads);
2407 #endif /* AFS_DEMAND_ATTACH_FS */
2410 Log("VAttachVolume: Error reading diskDataHandle vol header %s; error=%u\n", path, *ec);
2413 #ifdef AFS_DEMAND_ATTACH_FS
2414 # ifdef FSSYNC_BUILD_CLIENT
2419 /* check for pending volume operations */
2420 if (vp->pending_vol_op) {
2421 /* see if the pending volume op requires exclusive access */
2422 switch (vp->pending_vol_op->vol_op_state) {
2423 case FSSYNC_VolOpPending:
2424 /* this should never happen */
2425 assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpPending);
2428 case FSSYNC_VolOpRunningUnknown:
2429 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
2430 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
2433 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
2434 /* fall through to take volume offline */
2437 case FSSYNC_VolOpRunningOffline:
2438 /* mark the volume down */
2440 VChangeState_r(vp, VOL_STATE_UNATTACHED);
2441 if (V_offlineMessage(vp)[0] == '\0')
2442 strlcpy(V_offlineMessage(vp),
2443 "A volume utility is running.",
2444 sizeof(V_offlineMessage(vp)));
2445 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
2447 /* check to see if we should set the specialStatus flag */
2448 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
2449 vp->specialStatus = VBUSY;
2456 V_attachFlags(vp) |= VOL_HDR_LOADED;
2457 vp->stats.last_hdr_load = vp->stats.last_attach;
2459 #endif /* AFS_DEMAND_ATTACH_FS */
2462 struct IndexFileHeader iHead;
2464 #if OPENAFS_VOL_STATS
2466 * We just read in the diskstuff part of the header. If the detailed
2467 * volume stats area has not yet been initialized, we should bzero the
2468 * area and mark it as initialized.
2470 if (!(V_stat_initialized(vp))) {
2471 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
2472 V_stat_initialized(vp) = 1;
2474 #endif /* OPENAFS_VOL_STATS */
2476 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
2477 (char *)&iHead, sizeof(iHead),
2478 SMALLINDEXMAGIC, SMALLINDEXVERSION);
2481 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
2486 struct IndexFileHeader iHead;
2488 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
2489 (char *)&iHead, sizeof(iHead),
2490 LARGEINDEXMAGIC, LARGEINDEXVERSION);
2493 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
2497 #ifdef AFS_NAMEI_ENV
2499 struct versionStamp stamp;
2501 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
2502 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
2505 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
2508 #endif /* AFS_NAMEI_ENV */
2510 #if defined(AFS_DEMAND_ATTACH_FS)
2511 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
2513 if (programType == fileServer) {
2514 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2517 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
2523 /* volume operation in progress */
2527 #else /* AFS_DEMAND_ATTACH_FS */
2529 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
2534 #endif /* AFS_DEMAND_ATTACH_FS */
2536 if (V_needsSalvaged(vp)) {
2537 if (vp->specialStatus)
2538 vp->specialStatus = 0;
2540 #if defined(AFS_DEMAND_ATTACH_FS)
2541 if (programType == fileServer) {
2542 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
2545 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
2549 #else /* AFS_DEMAND_ATTACH_FS */
2552 #endif /* AFS_DEMAND_ATTACH_FS */
2557 if (programType == fileServer) {
2558 #ifndef FAST_RESTART
2559 if (V_inUse(vp) && VolumeWriteable(vp)) {
2560 if (!V_needsSalvaged(vp)) {
2561 V_needsSalvaged(vp) = 1;
2562 VUpdateVolume_r(ec, vp, 0);
2564 #if defined(AFS_DEMAND_ATTACH_FS)
2565 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
2567 #else /* AFS_DEMAND_ATTACH_FS */
2568 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
2571 #endif /* AFS_DEMAND_ATTACH_FS */
2574 #endif /* FAST_RESTART */
2576 if (V_destroyMe(vp) == DESTROY_ME) {
2577 #if defined(AFS_DEMAND_ATTACH_FS)
2578 /* schedule a salvage so the volume goes away on disk */
2579 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2580 VChangeState_r(vp, VOL_STATE_ERROR);
2582 #endif /* AFS_DEMAND_ATTACH_FS */
2584 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
2590 vp->nextVnodeUnique = V_uniquifier(vp);
2591 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
2592 #ifndef BITMAP_LATER
2593 if (programType == fileServer && VolumeWriteable(vp)) {
2595 for (i = 0; i < nVNODECLASSES; i++) {
2596 VGetBitmap_r(ec, vp, i);
2598 #ifdef AFS_DEMAND_ATTACH_FS
2599 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2601 #else /* AFS_DEMAND_ATTACH_FS */
2603 #endif /* AFS_DEMAND_ATTACH_FS */
2604 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
2610 #endif /* BITMAP_LATER */
2612 if (programType == fileServer) {
2613 if (vp->specialStatus)
2614 vp->specialStatus = 0;
2615 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
2616 V_inUse(vp) = fileServer;
2617 V_offlineMessage(vp)[0] = '\0';
2620 if ((mode != V_PEEK) && (mode != V_SECRETLY))
2621 V_inUse(vp) = programType;
2622 V_checkoutMode(vp) = mode;
2625 AddVolumeToHashTable(vp, V_id(vp));
2626 #ifdef AFS_DEMAND_ATTACH_FS
2627 if ((programType != fileServer) ||
2628 (V_inUse(vp) == fileServer)) {
2629 AddVolumeToVByPList_r(vp);
2631 VChangeState_r(vp, VOL_STATE_ATTACHED);
2633 VChangeState_r(vp, VOL_STATE_UNATTACHED);
2639 /* Attach an existing volume.
2640 The volume also normally goes online at this time.
2641 An offline volume must be reattached to make it go online.
2645 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
2649 retVal = VAttachVolume_r(ec, volumeId, mode);
2655 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
2658 VGetVolumePath(ec, volumeId, &part, &name);
2660 register Volume *vp;
2662 vp = VGetVolume_r(&error, volumeId);
2664 assert(V_inUse(vp) == 0);
2665 VDetachVolume_r(ec, vp);
2669 return VAttachVolumeByName_r(ec, part, name, mode);
2672 /* Increment a reference count to a volume, sans context swaps. Requires
2673 * possibly reading the volume header in from the disk, since there's
2674 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
2676 * N.B. This call can fail if we can't read in the header!! In this case
2677 * we still guarantee we won't context swap, but the ref count won't be
2678 * incremented (otherwise we'd violate the invariant).
2680 /* NOTE: with the demand attach fileserver extensions, the global lock
2681 * is dropped within VHold */
2682 #ifdef AFS_DEMAND_ATTACH_FS
2684 VHold_r(register Volume * vp)
2688 VCreateReservation_r(vp);
2689 VWaitExclusiveState_r(vp);
2691 LoadVolumeHeader(&error, vp);
2693 VCancelReservation_r(vp);
2697 VCancelReservation_r(vp);
2700 #else /* AFS_DEMAND_ATTACH_FS */
2702 VHold_r(register Volume * vp)
2706 LoadVolumeHeader(&error, vp);
2712 #endif /* AFS_DEMAND_ATTACH_FS */
2716 VHold(register Volume * vp)
2720 retVal = VHold_r(vp);
2727 /***************************************************/
2728 /* get and put volume routines */
2729 /***************************************************/
2732 * put back a heavyweight reference to a volume object.
2734 * @param[in] vp volume object pointer
2736 * @pre VOL_LOCK held
2738 * @post heavyweight volume reference put back.
2739 * depending on state, volume may have been taken offline,
2740 * detached, salvaged, freed, etc.
2742 * @internal volume package internal use only
2745 VPutVolume_r(register Volume * vp)
2747 assert(--vp->nUsers >= 0);
2748 if (vp->nUsers == 0) {
2750 ReleaseVolumeHeader(vp->header);
2751 #ifdef AFS_DEMAND_ATTACH_FS
2752 if (!VCheckDetach(vp)) {
2756 #else /* AFS_DEMAND_ATTACH_FS */
2758 #endif /* AFS_DEMAND_ATTACH_FS */
2763 VPutVolume(register Volume * vp)
2771 /* Get a pointer to an attached volume. The pointer is returned regardless
2772 of whether or not the volume is in service or on/off line. An error
2773 code, however, is returned with an indication of the volume's status */
2775 VGetVolume(Error * ec, Error * client_ec, VolId volumeId)
2779 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
2785 VGetVolume_r(Error * ec, VolId volumeId)
2787 return GetVolume(ec, NULL, volumeId, NULL, 0);
2790 /* try to get a volume we've previously looked up */
2791 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
2793 VGetVolumeByVp_r(Error * ec, Volume * vp)
2795 return GetVolume(ec, NULL, vp->hashid, vp, 0);
2798 /* private interface for getting a volume handle
2799 * volumeId must be provided.
2800 * hint is an optional parameter to speed up hash lookups
2801 * flags is not used at this time
2803 /* for demand attach fs, caller MUST NOT hold a ref count on hint */
2805 GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint, int flags)
2808 /* pull this profiling/debugging code out of regular builds */
2810 #define VGET_CTR_INC(x) x++
2811 unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
2812 0, V7 = 0, V8 = 0, V9 = 0;
2813 unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
2815 #define VGET_CTR_INC(x)
2817 #ifdef AFS_DEMAND_ATTACH_FS
2818 Volume *avp, * rvp = hint;
2822 * if VInit is zero, the volume package dynamic
2823 * data structures have not been initialized yet,
2824 * and we must immediately return an error
2830 *client_ec = VOFFLINE;
2835 #ifdef AFS_DEMAND_ATTACH_FS
2837 VCreateReservation_r(rvp);
2839 #endif /* AFS_DEMAND_ATTACH_FS */
2847 vp = VLookupVolume_r(ec, volumeId, vp);
2853 #ifdef AFS_DEMAND_ATTACH_FS
2854 if (rvp && (rvp != vp)) {
2855 /* break reservation on old vp */
2856 VCancelReservation_r(rvp);
2859 #endif /* AFS_DEMAND_ATTACH_FS */
2865 /* Until we have reached an initialization level of 2
2866 * we don't know whether this volume exists or not.
2867 * We can't sleep and retry later because before a volume
2868 * is attached, the caller tries to get it first. Just
2869 * return VOFFLINE and the caller can choose whether to
2870 * retry the command or not. */
2880 IncUInt64(&VStats.hdr_gets);
2882 #ifdef AFS_DEMAND_ATTACH_FS
2883 /* block if someone else is performing an exclusive op on this volume */
2886 VCreateReservation_r(rvp);
2888 VWaitExclusiveState_r(vp);
2890 /* short circuit with VNOVOL in the following circumstances:
2893 * - VOL_STATE_SHUTTING_DOWN
2895 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
2896 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN) ||
2897 (V_attachState(vp) == VOL_STATE_GOING_OFFLINE)) {
2904 * short circuit with VOFFLINE in the following circumstances:
2906 * - VOL_STATE_UNATTACHED
2908 if (V_attachState(vp) == VOL_STATE_UNATTACHED) {
2909 if (vp->specialStatus) {
2910 *ec = vp->specialStatus;
2918 /* allowable states:
2924 if (vp->salvage.requested) {
2925 VUpdateSalvagePriority_r(vp);
2928 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
2929 avp = VAttachVolumeByVp_r(ec, vp, 0);
2932 /* VAttachVolumeByVp_r can return a pointer
2933 * != the vp passed to it under certain
2934 * conditions; make sure we don't leak
2935 * reservations if that happens */
2937 VCancelReservation_r(rvp);
2939 VCreateReservation_r(rvp);
2949 if (!vp->pending_vol_op) {
2964 if ((V_attachState(vp) == VOL_STATE_SALVAGING) ||
2965 (*ec == VSALVAGING)) {
2967 /* see CheckVnode() in afsfileprocs.c for an explanation
2968 * of this error code logic */
2969 afs_uint32 now = FT_ApproxTime();
2970 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
2973 *client_ec = VRESTARTING;
2982 LoadVolumeHeader(ec, vp);
2985 /* Only log the error if it was a totally unexpected error. Simply
2986 * a missing inode is likely to be caused by the volume being deleted */
2987 if (errno != ENXIO || LogLevel)
2988 Log("Volume %u: couldn't reread volume header\n",
2990 #ifdef AFS_DEMAND_ATTACH_FS
2991 if (programType == fileServer) {
2992 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2997 #else /* AFS_DEMAND_ATTACH_FS */
3000 #endif /* AFS_DEMAND_ATTACH_FS */
3004 #ifdef AFS_DEMAND_ATTACH_FS
3006 * this test MUST happen after the volume header is loaded
3009 /* only valid before/during demand attachment */
3010 assert(!vp->pending_vol_op || vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
3012 /* deny getvolume due to running mutually exclusive vol op */
3013 if (vp->pending_vol_op && vp->pending_vol_op->vol_op_state==FSSYNC_VolOpRunningOffline) {
3015 * volume cannot remain online during this volume operation.
3018 if (vp->specialStatus) {
3020 * special status codes outrank normal VOFFLINE code
3022 *ec = vp->specialStatus;
3024 *client_ec = vp->specialStatus;
3028 /* see CheckVnode() in afsfileprocs.c for an explanation
3029 * of this error code logic */
3030 afs_uint32 now = FT_ApproxTime();
3031 if ((vp->stats.last_vol_op + (10 * 60)) >= now) {
3034 *client_ec = VRESTARTING;
3039 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3040 FreeVolumeHeader(vp);
3044 #endif /* AFS_DEMAND_ATTACH_FS */
3047 if (vp->shuttingDown) {
3054 if (programType == fileServer) {
3056 if (vp->goingOffline) {
3058 #ifdef AFS_DEMAND_ATTACH_FS
3059 /* wait for the volume to go offline */
3060 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
3061 VWaitStateChange_r(vp);
3063 #elif defined(AFS_PTHREAD_ENV)
3064 VOL_CV_WAIT(&vol_put_volume_cond);
3065 #else /* AFS_PTHREAD_ENV */
3066 LWP_WaitProcess(VPutVolume);
3067 #endif /* AFS_PTHREAD_ENV */
3070 if (vp->specialStatus) {
3072 *ec = vp->specialStatus;
3073 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3076 } else if (V_inUse(vp) == 0) {
3087 #ifdef AFS_DEMAND_ATTACH_FS
3088 /* if no error, bump nUsers */
3091 VLRU_UpdateAccess_r(vp);
3094 VCancelReservation_r(rvp);
3097 if (client_ec && !*client_ec) {
3100 #else /* AFS_DEMAND_ATTACH_FS */
3101 /* if no error, bump nUsers */
3108 #endif /* AFS_DEMAND_ATTACH_FS */
3116 /***************************************************/
3117 /* Volume offline/detach routines */
3118 /***************************************************/
3120 /* caller MUST hold a heavyweight ref on vp */
3121 #ifdef AFS_DEMAND_ATTACH_FS
3123 VTakeOffline_r(register Volume * vp)
3127 assert(vp->nUsers > 0);
3128 assert(programType == fileServer);
3130 VCreateReservation_r(vp);
3131 VWaitExclusiveState_r(vp);
3133 vp->goingOffline = 1;
3134 V_needsSalvaged(vp) = 1;
3136 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
3137 VCancelReservation_r(vp);
3139 #else /* AFS_DEMAND_ATTACH_FS */
3141 VTakeOffline_r(register Volume * vp)
3143 assert(vp->nUsers > 0);
3144 assert(programType == fileServer);
3146 vp->goingOffline = 1;
3147 V_needsSalvaged(vp) = 1;
3149 #endif /* AFS_DEMAND_ATTACH_FS */
3152 VTakeOffline(register Volume * vp)
3160 * force a volume offline.
3162 * @param[in] vp volume object pointer
3163 * @param[in] flags flags (see note below)
3165 * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
3166 * used when VUpdateVolume_r needs to call VForceOffline_r
3167 * (which in turn would normally call VUpdateVolume_r)
3169 * @see VUpdateVolume_r
3171 * @pre VOL_LOCK must be held.
3172 * for DAFS, caller must hold ref.
3174 * @note for DAFS, it _is safe_ to call this function from an
3177 * @post needsSalvaged flag is set.
3178 * for DAFS, salvage is requested.
3179 * no further references to the volume through the volume
3180 * package will be honored.
3181 * all file descriptor and vnode caches are invalidated.
3183 * @warning this is a heavy-handed interface. it results in
3184 * a volume going offline regardless of the current
3185 * reference count state.
3187 * @internal volume package internal use only
3190 VForceOffline_r(Volume * vp, int flags)
3194 #ifdef AFS_DEMAND_ATTACH_FS
3195 VChangeState_r(vp, VOL_STATE_ERROR);
3200 strcpy(V_offlineMessage(vp),
3201 "Forced offline due to internal error: volume needs to be salvaged");
3202 Log("Volume %u forced offline: it needs salvaging!\n", V_id(vp));
3205 vp->goingOffline = 0;
3206 V_needsSalvaged(vp) = 1;
3207 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
3208 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
3211 #ifdef AFS_DEMAND_ATTACH_FS
3212 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3213 #endif /* AFS_DEMAND_ATTACH_FS */
3215 #ifdef AFS_PTHREAD_ENV
3216 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3217 #else /* AFS_PTHREAD_ENV */
3218 LWP_NoYieldSignal(VPutVolume);
3219 #endif /* AFS_PTHREAD_ENV */
3221 VReleaseVolumeHandles_r(vp);
3225 * force a volume offline.
3227 * @param[in] vp volume object pointer
3229 * @see VForceOffline_r
3232 VForceOffline(Volume * vp)
3235 VForceOffline_r(vp, 0);
3239 /* The opposite of VAttachVolume. The volume header is written to disk, with
3240 the inUse bit turned off. A copy of the header is maintained in memory,
3241 however (which is why this is VOffline, not VDetach).
3244 VOffline_r(Volume * vp, char *message)
3246 #ifndef AFS_DEMAND_ATTACH_FS
3248 VolumeId vid = V_id(vp);
3251 assert(programType != volumeUtility);
3256 if (V_offlineMessage(vp)[0] == '\0')
3257 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
3258 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
3260 vp->goingOffline = 1;
3261 #ifdef AFS_DEMAND_ATTACH_FS
3262 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
3263 VCreateReservation_r(vp);
3266 /* wait for the volume to go offline */
3267 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
3268 VWaitStateChange_r(vp);
3270 VCancelReservation_r(vp);
3271 #else /* AFS_DEMAND_ATTACH_FS */
3273 vp = VGetVolume_r(&error, vid); /* Wait for it to go offline */
3274 if (vp) /* In case it was reattached... */
3276 #endif /* AFS_DEMAND_ATTACH_FS */
3279 #ifdef AFS_DEMAND_ATTACH_FS
3281 * Take a volume offline in order to perform a volume operation.
3283 * @param[inout] ec address in which to store error code
3284 * @param[in] vp volume object pointer
3285 * @param[in] message volume offline status message
3288 * - VOL_LOCK is held
3289 * - caller MUST hold a heavyweight ref on vp
3292 * - volume is taken offline
3293 * - if possible, volume operation is promoted to running state
3294 * - on failure, *ec is set to nonzero
3296 * @note Although this function does not return any value, it may
3297 * still fail to promote our pending volume operation to
3298 * a running state. Any caller MUST check the value of *ec,
3299 * and MUST NOT blindly assume success.
3301 * @warning if the caller does not hold a lightweight ref on vp,
3302 * then it MUST NOT reference vp after this function
3303 * returns to the caller.
3305 * @internal volume package internal use only
3308 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
3310 assert(vp->pending_vol_op);
3316 if (V_offlineMessage(vp)[0] == '\0')
3317 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
3318 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
3320 vp->goingOffline = 1;
3321 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
3322 VCreateReservation_r(vp);
3325 /* Wait for the volume to go offline */
3326 while (!VIsOfflineState(V_attachState(vp))) {
3327 /* do not give corrupted volumes to the volserver */
3328 if (vp->salvage.requested && vp->pending_vol_op->com.programType != salvageServer) {
3332 VWaitStateChange_r(vp);
3336 VCancelReservation_r(vp);
3338 #endif /* AFS_DEMAND_ATTACH_FS */
3341 VOffline(Volume * vp, char *message)
3344 VOffline_r(vp, message);
3348 /* This gets used for the most part by utility routines that don't want
3349 * to keep all the volume headers around. Generally, the file server won't
3350 * call this routine, because then the offline message in the volume header
3351 * (or other information) won't be available to clients. For NAMEI, also
3352 * close the file handles. However, the fileserver does call this during
3353 * an attach following a volume operation.
3356 VDetachVolume_r(Error * ec, Volume * vp)
3359 struct DiskPartition64 *tpartp;
3360 int notifyServer = 0;
3361 int useDone = FSYNC_VOL_ON;
3363 *ec = 0; /* always "succeeds" */
3364 if (programType == volumeUtility) {
3365 notifyServer = vp->needsPutBack;
3366 if (V_destroyMe(vp) == DESTROY_ME)
3367 useDone = FSYNC_VOL_DONE;
3368 #ifdef AFS_DEMAND_ATTACH_FS
3369 else if (!V_blessed(vp) || !V_inService(vp))
3370 useDone = FSYNC_VOL_LEAVE_OFF;
3373 tpartp = vp->partition;
3375 DeleteVolumeFromHashTable(vp);
3376 vp->shuttingDown = 1;
3377 #ifdef AFS_DEMAND_ATTACH_FS
3378 DeleteVolumeFromVByPList_r(vp);
3380 VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
3382 if (programType != fileServer)
3384 #endif /* AFS_DEMAND_ATTACH_FS */
3386 /* Will be detached sometime in the future--this is OK since volume is offline */
3388 /* XXX the following code should really be moved to VCheckDetach() since the volume
3389 * is not technically detached until the refcounts reach zero
3391 #ifdef FSSYNC_BUILD_CLIENT
3392 if (programType == volumeUtility && notifyServer) {
3394 * Note: The server is not notified in the case of a bogus volume
3395 * explicitly to make it possible to create a volume, do a partial
3396 * restore, then abort the operation without ever putting the volume
3397 * online. This is essential in the case of a volume move operation
3398 * between two partitions on the same server. In that case, there
3399 * would be two instances of the same volume, one of them bogus,
3400 * which the file server would attempt to put on line
3402 FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
3403 /* XXX this code path is only hit by volume utilities, thus
3404 * V_BreakVolumeCallbacks will always be NULL. if we really
3405 * want to break callbacks in this path we need to use FSYNC_VolOp() */
3407 /* Dettaching it so break all callbacks on it */
3408 if (V_BreakVolumeCallbacks) {
3409 Log("volume %u detached; breaking all call backs\n", volume);
3410 (*V_BreakVolumeCallbacks) (volume);
3414 #endif /* FSSYNC_BUILD_CLIENT */
3418 VDetachVolume(Error * ec, Volume * vp)
3421 VDetachVolume_r(ec, vp);
3426 /***************************************************/
3427 /* Volume fd/inode handle closing routines */
3428 /***************************************************/
3430 /* For VDetachVolume, we close all cached file descriptors, but keep
3431 * the Inode handles in case we need to read from a busy volume.
3433 /* for demand attach, caller MUST hold ref count on vp */
3435 VCloseVolumeHandles_r(Volume * vp)
3437 #ifdef AFS_DEMAND_ATTACH_FS
3438 VolState state_save;
3440 state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
3445 * XXX need to investigate whether we can perform
3446 * DFlushVolume outside of vol_glock_mutex...
3448 * VCloseVnodeFiles_r drops the glock internally */
3449 DFlushVolume(V_id(vp));
3450 VCloseVnodeFiles_r(vp);
3452 #ifdef AFS_DEMAND_ATTACH_FS
3456 /* Too time consuming and unnecessary for the volserver */
3457 if (programType != volumeUtility) {
3458 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
3459 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
3460 IH_CONDSYNC(vp->diskDataHandle);
3462 IH_CONDSYNC(vp->linkHandle);
3463 #endif /* AFS_NT40_ENV */
3466 IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
3467 IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
3468 IH_REALLYCLOSE(vp->diskDataHandle);
3469 IH_REALLYCLOSE(vp->linkHandle);
3471 #ifdef AFS_DEMAND_ATTACH_FS
3473 VChangeState_r(vp, state_save);
3477 /* For both VForceOffline and VOffline, we close all relevant handles.
3478 * For VOffline, if we re-attach the volume, the files may possible be
3479 * different than before.
3481 /* for demand attach, caller MUST hold a ref count on vp */
3483 VReleaseVolumeHandles_r(Volume * vp)
3485 #ifdef AFS_DEMAND_ATTACH_FS
3486 VolState state_save;
3488 state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
3491 /* XXX need to investigate whether we can perform
3492 * DFlushVolume outside of vol_glock_mutex... */
3493 DFlushVolume(V_id(vp));
3495 VReleaseVnodeFiles_r(vp); /* releases the glock internally */
3497 #ifdef AFS_DEMAND_ATTACH_FS
3501 /* Too time consuming and unnecessary for the volserver */
3502 if (programType != volumeUtility) {
3503 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
3504 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
3505 IH_CONDSYNC(vp->diskDataHandle);
3507 IH_CONDSYNC(vp->linkHandle);
3508 #endif /* AFS_NT40_ENV */
3511 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
3512 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
3513 IH_RELEASE(vp->diskDataHandle);
3514 IH_RELEASE(vp->linkHandle);
3516 #ifdef AFS_DEMAND_ATTACH_FS
3518 VChangeState_r(vp, state_save);
3523 /***************************************************/
3524 /* Volume write and fsync routines */
3525 /***************************************************/
3528 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
3530 #ifdef AFS_DEMAND_ATTACH_FS
3531 VolState state_save;
3533 if (flags & VOL_UPDATE_WAIT) {
3534 VCreateReservation_r(vp);
3535 VWaitExclusiveState_r(vp);
3540 if (programType == fileServer)
3542 (V_inUse(vp) ? V_nextVnodeUnique(vp) +
3543 200 : V_nextVnodeUnique(vp));
3545 #ifdef AFS_DEMAND_ATTACH_FS
3546 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
3550 WriteVolumeHeader_r(ec, vp);
3552 #ifdef AFS_DEMAND_ATTACH_FS
3554 VChangeState_r(vp, state_save);
3555 if (flags & VOL_UPDATE_WAIT) {
3556 VCancelReservation_r(vp);
3561 Log("VUpdateVolume: error updating volume header, volume %u (%s)\n",
3562 V_id(vp), V_name(vp));
3563 /* try to update on-disk header,
3564 * while preventing infinite recursion */
3565 if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
3566 VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
3572 VUpdateVolume(Error * ec, Volume * vp)
3575 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
3580 VSyncVolume_r(Error * ec, Volume * vp, int flags)
3584 #ifdef AFS_DEMAND_ATTACH_FS
3585 VolState state_save;
3588 if (flags & VOL_SYNC_WAIT) {
3589 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
3591 VUpdateVolume_r(ec, vp, 0);
3594 #ifdef AFS_DEMAND_ATTACH_FS
3595 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
3598 fdP = IH_OPEN(V_diskDataHandle(vp));
3599 assert(fdP != NULL);
3600 code = FDH_SYNC(fdP);
3603 #ifdef AFS_DEMAND_ATTACH_FS
3605 VChangeState_r(vp, state_save);
3611 VSyncVolume(Error * ec, Volume * vp)
3614 VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
3619 /***************************************************/
3620 /* Volume dealloaction routines */
3621 /***************************************************/
3623 #ifdef AFS_DEMAND_ATTACH_FS
3625 FreeVolume(Volume * vp)
3627 /* free the heap space, iff it's safe.
3628 * otherwise, pull it out of the hash table, so it
3629 * will get deallocated when all refs to it go away */
3630 if (!VCheckFree(vp)) {
3631 DeleteVolumeFromHashTable(vp);
3632 DeleteVolumeFromVByPList_r(vp);
3634 /* make sure we invalidate the header cache entry */
3635 FreeVolumeHeader(vp);
3638 #endif /* AFS_DEMAND_ATTACH_FS */
3641 ReallyFreeVolume(Volume * vp)
3646 #ifdef AFS_DEMAND_ATTACH_FS
3648 VChangeState_r(vp, VOL_STATE_FREED);
3649 if (vp->pending_vol_op)
3650 free(vp->pending_vol_op);
3651 #endif /* AFS_DEMAND_ATTACH_FS */
3652 for (i = 0; i < nVNODECLASSES; i++)
3653 if (vp->vnodeIndex[i].bitmap)
3654 free(vp->vnodeIndex[i].bitmap);
3655 FreeVolumeHeader(vp);
3656 #ifndef AFS_DEMAND_ATTACH_FS
3657 DeleteVolumeFromHashTable(vp);
3658 #endif /* AFS_DEMAND_ATTACH_FS */
3662 /* check to see if we should shutdown this volume
3663 * returns 1 if volume was freed, 0 otherwise */
3664 #ifdef AFS_DEMAND_ATTACH_FS
3666 VCheckDetach(register Volume * vp)
3671 if (vp->nUsers || vp->nWaiters)
3674 if (vp->shuttingDown) {
3676 if ((programType != fileServer) &&
3677 (V_inUse(vp) == programType) &&
3678 ((V_checkoutMode(vp) == V_VOLUPD) ||
3679 (V_checkoutMode(vp) == V_SECRETLY) ||
3680 ((V_checkoutMode(vp) == V_CLONE) &&
3681 (VolumeWriteable(vp))))) {
3683 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
3685 Log("VCheckDetach: volume header update for volume %u "
3686 "failed with errno %d\n", vp->hashid, errno);
3689 VReleaseVolumeHandles_r(vp);
3691 ReallyFreeVolume(vp);
3692 if (programType == fileServer) {
3693 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3698 #else /* AFS_DEMAND_ATTACH_FS */
3700 VCheckDetach(register Volume * vp)
3708 if (vp->shuttingDown) {
3710 if ((programType != fileServer) &&
3711 (V_inUse(vp) == programType) &&
3712 ((V_checkoutMode(vp) == V_VOLUPD) ||
3713 (V_checkoutMode(vp) == V_SECRETLY) ||
3714 ((V_checkoutMode(vp) == V_CLONE) &&
3715 (VolumeWriteable(vp))))) {
3717 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
3719 Log("VCheckDetach: volume header update for volume %u failed with errno %d\n",
3723 VReleaseVolumeHandles_r(vp);
3724 ReallyFreeVolume(vp);
3725 if (programType == fileServer) {
3726 #if defined(AFS_PTHREAD_ENV)
3727 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3728 #else /* AFS_PTHREAD_ENV */
3729 LWP_NoYieldSignal(VPutVolume);
3730 #endif /* AFS_PTHREAD_ENV */
3735 #endif /* AFS_DEMAND_ATTACH_FS */
3737 /* check to see if we should offline this volume
3738 * return 1 if volume went offline, 0 otherwise */
3739 #ifdef AFS_DEMAND_ATTACH_FS
3741 VCheckOffline(register Volume * vp)
3745 if (vp->goingOffline && !vp->nUsers) {
3747 assert(programType == fileServer);
3748 assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
3749 (V_attachState(vp) != VOL_STATE_FREED) &&
3750 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
3751 (V_attachState(vp) != VOL_STATE_UNATTACHED));
3755 * VOL_STATE_GOING_OFFLINE
3756 * VOL_STATE_SHUTTING_DOWN
3757 * VIsErrorState(V_attachState(vp))
3758 * VIsExclusiveState(V_attachState(vp))
3761 VCreateReservation_r(vp);
3762 VChangeState_r(vp, VOL_STATE_OFFLINING);
3765 /* must clear the goingOffline flag before we drop the glock */
3766 vp->goingOffline = 0;
3771 /* perform async operations */
3772 VUpdateVolume_r(&error, vp, 0);
3773 VCloseVolumeHandles_r(vp);
3776 if (V_offlineMessage(vp)[0]) {
3777 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
3778 afs_printable_uint32_lu(V_id(vp)), V_name(vp),
3779 V_offlineMessage(vp));
3781 Log("VOffline: Volume %lu (%s) is now offline\n",
3782 afs_printable_uint32_lu(V_id(vp)), V_name(vp));
3786 /* invalidate the volume header cache entry */
3787 FreeVolumeHeader(vp);
3789 /* if nothing changed state to error or salvaging,
3790 * drop state to unattached */
3791 if (!VIsErrorState(V_attachState(vp))) {
3792 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3794 VCancelReservation_r(vp);
3795 /* no usage of vp is safe beyond this point */
3799 #else /* AFS_DEMAND_ATTACH_FS */
3801 VCheckOffline(register Volume * vp)
3805 if (vp->goingOffline && !vp->nUsers) {
3807 assert(programType == fileServer);
3810 vp->goingOffline = 0;
3812 VUpdateVolume_r(&error, vp, 0);
3813 VCloseVolumeHandles_r(vp);
3815 Log("VOffline: Volume %u (%s) is now offline", V_id(vp),
3817 if (V_offlineMessage(vp)[0])
3818 Log(" (%s)", V_offlineMessage(vp));
3821 FreeVolumeHeader(vp);
3822 #ifdef AFS_PTHREAD_ENV
3823 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3824 #else /* AFS_PTHREAD_ENV */
3825 LWP_NoYieldSignal(VPutVolume);
3826 #endif /* AFS_PTHREAD_ENV */
3830 #endif /* AFS_DEMAND_ATTACH_FS */
3832 /***************************************************/
3833 /* demand attach fs ref counting routines */
3834 /***************************************************/
3836 #ifdef AFS_DEMAND_ATTACH_FS
3837 /* the following two functions handle reference counting for
3838 * asynchronous operations on volume structs.
3840 * their purpose is to prevent a VDetachVolume or VShutdown
3841 * from free()ing the Volume struct during an async i/o op */
3843 /* register with the async volume op ref counter */
3844 /* VCreateReservation_r moved into inline code header because it
3845 * is now needed in vnode.c -- tkeiser 11/20/2007
3849 * decrement volume-package internal refcount.
3851 * @param vp volume object pointer
3853 * @internal volume package internal use only
3856 * @arg VOL_LOCK is held
3857 * @arg lightweight refcount held
3859 * @post volume waiters refcount is decremented; volume may
3860 * have been deallocated/shutdown/offlined/salvaged/
3861 * whatever during the process
3863 * @warning once you have tossed your last reference (you can acquire
3864 * lightweight refs recursively) it is NOT SAFE to reference
3865 * a volume object pointer ever again
3867 * @see VCreateReservation_r
3869 * @note DEMAND_ATTACH_FS only
3872 VCancelReservation_r(Volume * vp)
3874 assert(--vp->nWaiters >= 0);
3875 if (vp->nWaiters == 0) {
3877 if (!VCheckDetach(vp)) {
3884 /* check to see if we should free this volume now
3885 * return 1 if volume was freed, 0 otherwise */
3887 VCheckFree(Volume * vp)
3890 if ((vp->nUsers == 0) &&
3891 (vp->nWaiters == 0) &&
3892 !(V_attachFlags(vp) & (VOL_IN_HASH |
3896 ReallyFreeVolume(vp);
3901 #endif /* AFS_DEMAND_ATTACH_FS */
3904 /***************************************************/
3905 /* online volume operations routines */
3906 /***************************************************/
3908 #ifdef AFS_DEMAND_ATTACH_FS
3910 * register a volume operation on a given volume.
3912 * @param[in] vp volume object
3913 * @param[in] vopinfo volume operation info object
3915 * @pre VOL_LOCK is held
3917 * @post volume operation info object attached to volume object.
3918 * volume operation statistics updated.
3920 * @note by "attached" we mean a copy of the passed in object is made
3922 * @internal volume package internal use only
3925 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3927 FSSYNC_VolOp_info * info;
3929 /* attach a vol op info node to the volume struct */
3930 info = (FSSYNC_VolOp_info *) malloc(sizeof(FSSYNC_VolOp_info));
3931 assert(info != NULL);
3932 memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
3933 vp->pending_vol_op = info;
3936 vp->stats.last_vol_op = FT_ApproxTime();
3937 vp->stats.vol_ops++;
3938 IncUInt64(&VStats.vol_ops);
3944 * deregister the volume operation attached to this volume.
3946 * @param[in] vp volume object pointer
3948 * @pre VOL_LOCK is held
3950 * @post the volume operation info object is detached from the volume object
3952 * @internal volume package internal use only
3955 VDeregisterVolOp_r(Volume * vp)
3957 if (vp->pending_vol_op) {
3958 free(vp->pending_vol_op);
3959 vp->pending_vol_op = NULL;
3963 #endif /* AFS_DEMAND_ATTACH_FS */
3966 * determine whether it is safe to leave a volume online during
3967 * the volume operation described by the vopinfo object.
3969 * @param[in] vp volume object
3970 * @param[in] vopinfo volume operation info object
3972 * @return whether it is safe to leave volume online
3973 * @retval 0 it is NOT SAFE to leave the volume online
3974 * @retval 1 it is safe to leave the volume online during the operation
3977 * @arg VOL_LOCK is held
3978 * @arg disk header attached to vp (heavyweight ref on vp will guarantee
3979 * this condition is met)
3981 * @internal volume package internal use only
3984 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3986 return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
3987 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
3988 (vopinfo->com.reason == V_READONLY ||
3989 (!VolumeWriteable(vp) &&
3990 (vopinfo->com.reason == V_CLONE ||
3991 vopinfo->com.reason == V_DUMP)))));
3995 * determine whether VBUSY should be set during this volume operation.
3997 * @param[in] vp volume object
3998 * @param[in] vopinfo volume operation info object
4000 * @return whether VBUSY should be set
4001 * @retval 0 VBUSY does NOT need to be set
4002 * @retval 1 VBUSY SHOULD be set
4004 * @pre VOL_LOCK is held
4006 * @internal volume package internal use only
4009 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4011 return ((vopinfo->com.command == FSYNC_VOL_OFF &&
4012 vopinfo->com.reason == FSYNC_SALVAGE) ||
4013 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4014 (vopinfo->com.reason == V_CLONE ||
4015 vopinfo->com.reason == V_DUMP)));
4019 /***************************************************/
4020 /* online salvager routines */
4021 /***************************************************/
4022 #if defined(AFS_DEMAND_ATTACH_FS)
4023 #define SALVAGE_PRIO_UPDATE_INTERVAL 3 /**< number of seconds between prio updates */
4024 #define SALVAGE_COUNT_MAX 16 /**< number of online salvages we
4025 * allow before moving the volume
4026 * into a permanent error state
4028 * once this threshold is reached,
4029 * the operator will have to manually
4030 * issue a 'bos salvage' to bring
4031 * the volume back online
4035 * check whether a salvage needs to be performed on this volume.
4037 * @param[in] vp pointer to volume object
4039 * @return status code
4040 * @retval 0 no salvage scheduled
4041 * @retval 1 a salvage has been scheduled with the salvageserver
4043 * @pre VOL_LOCK is held
4045 * @post if salvage request flag is set and nUsers and nWaiters are zero,
4046 * then a salvage will be requested
4048 * @note this is one of the event handlers called by VCancelReservation_r
4050 * @see VCancelReservation_r
4052 * @internal volume package internal use only.
4055 VCheckSalvage(register Volume * vp)
4058 #ifdef SALVSYNC_BUILD_CLIENT
4059 if (vp->nUsers || vp->nWaiters)
4061 if (vp->salvage.requested) {
4062 VScheduleSalvage_r(vp);
4065 #endif /* SALVSYNC_BUILD_CLIENT */
4070 * request volume salvage.
4072 * @param[out] ec computed client error code
4073 * @param[in] vp volume object pointer
4074 * @param[in] reason reason code (passed to salvageserver via SALVSYNC)
4075 * @param[in] flags see flags note below
4078 * VOL_SALVAGE_INVALIDATE_HEADER causes volume header cache entry
4079 * to be invalidated.
4081 * @pre VOL_LOCK is held.
4083 * @post volume state is changed.
4084 * for fileserver, salvage will be requested once refcount reaches zero.
4086 * @return operation status code
4087 * @retval 0 volume salvage will occur
4088 * @retval 1 volume salvage could not be scheduled
4090 * @note DAFS fileserver only
4092 * @note this call does not synchronously schedule a volume salvage. rather,
4093 * it sets volume state so that when volume refcounts reach zero, a
4094 * volume salvage will occur. by "refcounts", we mean both nUsers and
4095 * nWaiters must be zero.
4097 * @internal volume package internal use only.
4100 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
4104 * for DAFS volume utilities, transition to error state
4105 * (at some point in the future, we should consider
4106 * making volser talk to salsrv)
4108 if (programType != fileServer) {
4109 VChangeState_r(vp, VOL_STATE_ERROR);
4114 if (!vp->salvage.requested) {
4115 vp->salvage.requested = 1;
4116 vp->salvage.reason = reason;
4117 vp->stats.last_salvage = FT_ApproxTime();
4118 if (VIsSalvager(V_inUse(vp))) {
4119 Log("VRequestSalvage: volume %u appears to be salvaging, but we\n", vp->hashid);
4120 Log(" didn't request a salvage. Forcing it offline waiting for the\n");
4121 Log(" salvage to finish; if you are sure no salvage is running,\n");
4122 Log(" run a salvage manually.\n");
4124 /* make sure neither VScheduleSalvage_r nor
4125 * VUpdateSalvagePriority_r try to schedule another salvage */
4126 vp->salvage.requested = vp->salvage.scheduled = 0;
4128 /* these stats aren't correct, but doing this makes them
4129 * slightly closer to being correct */
4130 vp->stats.salvages++;
4131 vp->stats.last_salvage_req = FT_ApproxTime();
4132 IncUInt64(&VStats.salvages);
4134 VChangeState_r(vp, VOL_STATE_ERROR);
4138 } else if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
4139 VChangeState_r(vp, VOL_STATE_SALVAGING);
4142 Log("VRequestSalvage: volume %u online salvaged too many times; forced offline.\n", vp->hashid);
4143 VChangeState_r(vp, VOL_STATE_ERROR);
4147 if (flags & VOL_SALVAGE_INVALIDATE_HEADER) {
4148 /* Instead of ReleaseVolumeHeader, we do FreeVolumeHeader()
4149 so that the the next VAttachVolumeByVp_r() invocation
4150 of attach2() will pull in a cached header
4151 entry and fail, then load a fresh one from disk and attach
4154 FreeVolumeHeader(vp);
4161 * update salvageserver scheduling priority for a volume.
4163 * @param[in] vp pointer to volume object
4165 * @return operation status
4167 * @retval 1 request denied, or SALVSYNC communications failure
4169 * @pre VOL_LOCK is held.
4171 * @post in-core salvage priority counter is incremented. if at least
4172 * SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
4173 * last SALVSYNC_RAISEPRIO request, we contact the salvageserver
4174 * to update its priority queue. if no salvage is scheduled,
4175 * this function is a no-op.
4177 * @note DAFS fileserver only
4179 * @note this should be called whenever a VGetVolume fails due to a
4180 * pending salvage request
4182 * @todo should set exclusive state and drop glock around salvsync call
4184 * @internal volume package internal use only.
4187 VUpdateSalvagePriority_r(Volume * vp)
4191 #ifdef SALVSYNC_BUILD_CLIENT
4196 now = FT_ApproxTime();
4198 /* update the salvageserver priority queue occasionally so that
4199 * frequently requested volumes get moved to the head of the queue
4201 if ((vp->salvage.scheduled) &&
4202 (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
4203 code = SALVSYNC_SalvageVolume(vp->hashid,
4204 VPartitionPath(vp->partition),
4209 vp->stats.last_salvage_req = now;
4210 if (code != SYNC_OK) {
4214 #endif /* SALVSYNC_BUILD_CLIENT */
4219 #ifdef SALVSYNC_BUILD_CLIENT
4221 * schedule a salvage with the salvage server.
4223 * @param[in] vp pointer to volume object
4225 * @return operation status
4226 * @retval 0 salvage scheduled successfully
4227 * @retval 1 salvage not scheduled, or SALVSYNC com error
4230 * @arg VOL_LOCK is held.
4231 * @arg nUsers and nWaiters should be zero.
4233 * @post salvageserver is sent a salvage request
4235 * @note DAFS fileserver only
4237 * @internal volume package internal use only.
4240 VScheduleSalvage_r(Volume * vp)
4244 VolState state_save;
4245 VThreadOptions_t * thread_opts;
4248 if (vp->nWaiters || vp->nUsers) {
4252 /* prevent endless salvage,attach,salvage,attach,... loops */
4253 if (vp->stats.salvages >= SALVAGE_COUNT_MAX)
4257 * don't perform salvsync ops on certain threads
4259 thread_opts = pthread_getspecific(VThread_key);
4260 if (thread_opts == NULL) {
4261 thread_opts = &VThread_defaults;
4263 if (thread_opts->disallow_salvsync || vol_disallow_salvsync) {
4268 * XXX the scheduling process should really be done asynchronously
4269 * to avoid fssync deadlocks
4271 if (!vp->salvage.scheduled) {
4272 /* if we haven't previously scheduled a salvage, do so now
4274 * set the volume to an exclusive state and drop the lock
4275 * around the SALVSYNC call
4277 * note that we do NOT acquire a reservation here -- doing so
4278 * could result in unbounded recursion
4280 strlcpy(partName, VPartitionPath(vp->partition), sizeof(partName));
4281 state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
4284 /* can't use V_id() since there's no guarantee
4285 * we have the disk data header at this point */
4286 code = SALVSYNC_SalvageVolume(vp->hashid,
4293 VChangeState_r(vp, state_save);
4295 if (code == SYNC_OK) {
4296 vp->salvage.scheduled = 1;
4297 vp->stats.salvages++;
4298 vp->stats.last_salvage_req = FT_ApproxTime();
4299 IncUInt64(&VStats.salvages);
4303 case SYNC_BAD_COMMAND:
4304 case SYNC_COM_ERROR:
4307 Log("VScheduleSalvage_r: SALVSYNC request denied\n");
4310 Log("VScheduleSalvage_r: SALVSYNC unknown protocol error\n");
4319 * connect to the salvageserver SYNC service.
4321 * @return operation status
4325 * @post connection to salvageserver SYNC service established
4327 * @see VConnectSALV_r
4328 * @see VDisconnectSALV
4329 * @see VReconnectSALV
4336 retVal = VConnectSALV_r();
4342 * connect to the salvageserver SYNC service.
4344 * @return operation status
4348 * @pre VOL_LOCK is held.
4350 * @post connection to salvageserver SYNC service established
4353 * @see VDisconnectSALV_r
4354 * @see VReconnectSALV_r
4355 * @see SALVSYNC_clientInit
4357 * @internal volume package internal use only.
4360 VConnectSALV_r(void)
4362 return SALVSYNC_clientInit();
4366 * disconnect from the salvageserver SYNC service.
4368 * @return operation status
4371 * @pre client should have a live connection to the salvageserver
4373 * @post connection to salvageserver SYNC service destroyed
4375 * @see VDisconnectSALV_r
4377 * @see VReconnectSALV
4380 VDisconnectSALV(void)
4383 VDisconnectSALV_r();
4389 * disconnect from the salvageserver SYNC service.
4391 * @return operation status
4395 * @arg VOL_LOCK is held.
4396 * @arg client should have a live connection to the salvageserver.
4398 * @post connection to salvageserver SYNC service destroyed
4400 * @see VDisconnectSALV
4401 * @see VConnectSALV_r
4402 * @see VReconnectSALV_r
4403 * @see SALVSYNC_clientFinis
4405 * @internal volume package internal use only.
4408 VDisconnectSALV_r(void)
4410 return SALVSYNC_clientFinis();
4414 * disconnect and then re-connect to the salvageserver SYNC service.
4416 * @return operation status
4420 * @pre client should have a live connection to the salvageserver
4422 * @post old connection is dropped, and a new one is established
4425 * @see VDisconnectSALV
4426 * @see VReconnectSALV_r
4429 VReconnectSALV(void)
4433 retVal = VReconnectSALV_r();
4439 * disconnect and then re-connect to the salvageserver SYNC service.
4441 * @return operation status
4446 * @arg VOL_LOCK is held.
4447 * @arg client should have a live connection to the salvageserver.
4449 * @post old connection is dropped, and a new one is established
4451 * @see VConnectSALV_r
4452 * @see VDisconnectSALV
4453 * @see VReconnectSALV
4454 * @see SALVSYNC_clientReconnect
4456 * @internal volume package internal use only.
4459 VReconnectSALV_r(void)
4461 return SALVSYNC_clientReconnect();
4463 #endif /* SALVSYNC_BUILD_CLIENT */
4464 #endif /* AFS_DEMAND_ATTACH_FS */
4467 /***************************************************/
4468 /* FSSYNC routines */
4469 /***************************************************/
4471 /* This must be called by any volume utility which needs to run while the
4472 file server is also running. This is separated from VInitVolumePackage so
4473 that a utility can fork--and each of the children can independently
4474 initialize communication with the file server */
4475 #ifdef FSSYNC_BUILD_CLIENT
4477 * connect to the fileserver SYNC service.
4479 * @return operation status
4484 * @arg VInit must equal 2.
4485 * @arg Program Type must not be fileserver or salvager.
4487 * @post connection to fileserver SYNC service established
4490 * @see VDisconnectFS
4491 * @see VChildProcReconnectFS
4498 retVal = VConnectFS_r();
4504 * connect to the fileserver SYNC service.
4506 * @return operation status
4511 * @arg VInit must equal 2.
4512 * @arg Program Type must not be fileserver or salvager.
4513 * @arg VOL_LOCK is held.
4515 * @post connection to fileserver SYNC service established
4518 * @see VDisconnectFS_r
4519 * @see VChildProcReconnectFS_r
4521 * @internal volume package internal use only.
4527 assert((VInit == 2) &&
4528 (programType != fileServer) &&
4529 (programType != salvager));
4530 rc = FSYNC_clientInit();
4537 * disconnect from the fileserver SYNC service.
4540 * @arg client should have a live connection to the fileserver.
4541 * @arg VOL_LOCK is held.
4542 * @arg Program Type must not be fileserver or salvager.
4544 * @post connection to fileserver SYNC service destroyed
4546 * @see VDisconnectFS
4548 * @see VChildProcReconnectFS_r
4550 * @internal volume package internal use only.
4553 VDisconnectFS_r(void)
4555 assert((programType != fileServer) &&
4556 (programType != salvager));
4557 FSYNC_clientFinis();
4562 * disconnect from the fileserver SYNC service.
4565 * @arg client should have a live connection to the fileserver.
4566 * @arg Program Type must not be fileserver or salvager.
4568 * @post connection to fileserver SYNC service destroyed
4570 * @see VDisconnectFS_r
4572 * @see VChildProcReconnectFS
4583 * connect to the fileserver SYNC service from a child process following a fork.
4585 * @return operation status
4590 * @arg VOL_LOCK is held.
4591 * @arg current FSYNC handle is shared with a parent process
4593 * @post current FSYNC handle is discarded and a new connection to the
4594 * fileserver SYNC service is established
4596 * @see VChildProcReconnectFS
4598 * @see VDisconnectFS_r
4600 * @internal volume package internal use only.
4603 VChildProcReconnectFS_r(void)
4605 return FSYNC_clientChildProcReconnect();
4609 * connect to the fileserver SYNC service from a child process following a fork.
4611 * @return operation status
4615 * @pre current FSYNC handle is shared with a parent process
4617 * @post current FSYNC handle is discarded and a new connection to the
4618 * fileserver SYNC service is established
4620 * @see VChildProcReconnectFS_r
4622 * @see VDisconnectFS
4625 VChildProcReconnectFS(void)
4629 ret = VChildProcReconnectFS_r();
4633 #endif /* FSSYNC_BUILD_CLIENT */
4636 /***************************************************/
4637 /* volume bitmap routines */
4638 /***************************************************/
4641 * For demand attach fs, flags parameter controls
4642 * locking behavior. If (flags & VOL_ALLOC_BITMAP_WAIT)
4643 * is set, then this function will create a reservation
4644 * and block on any other exclusive operations. Otherwise,
4645 * this function assumes the caller already has exclusive
4646 * access to vp, and we just change the volume state.
4649 VAllocBitmapEntry_r(Error * ec, Volume * vp,
4650 struct vnodeIndex *index, int flags)
4653 register byte *bp, *ep;
4654 #ifdef AFS_DEMAND_ATTACH_FS
4655 VolState state_save;
4656 #endif /* AFS_DEMAND_ATTACH_FS */
4660 /* This test is probably redundant */
4661 if (!VolumeWriteable(vp)) {
4662 *ec = (bit32) VREADONLY;
4666 #ifdef AFS_DEMAND_ATTACH_FS
4667 if (flags & VOL_ALLOC_BITMAP_WAIT) {
4668 VCreateReservation_r(vp);
4669 VWaitExclusiveState_r(vp);
4671 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
4672 #endif /* AFS_DEMAND_ATTACH_FS */
4675 if ((programType == fileServer) && !index->bitmap) {
4677 #ifndef AFS_DEMAND_ATTACH_FS
4678 /* demand attach fs uses the volume state to avoid races.
4679 * specialStatus field is not used at all */
4681 if (vp->specialStatus == VBUSY) {
4682 if (vp->goingOffline) { /* vos dump waiting for the volume to
4683 * go offline. We probably come here
4684 * from AddNewReadableResidency */
4687 while (vp->specialStatus == VBUSY) {
4688 #ifdef AFS_PTHREAD_ENV
4692 #else /* !AFS_PTHREAD_ENV */
4694 #endif /* !AFS_PTHREAD_ENV */
4698 #endif /* !AFS_DEMAND_ATTACH_FS */
4700 if (!index->bitmap) {
4701 #ifndef AFS_DEMAND_ATTACH_FS
4702 vp->specialStatus = VBUSY; /* Stop anyone else from using it. */
4703 #endif /* AFS_DEMAND_ATTACH_FS */
4704 for (i = 0; i < nVNODECLASSES; i++) {
4705 VGetBitmap_r(ec, vp, i);
4707 #ifdef AFS_DEMAND_ATTACH_FS
4708 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
4709 #else /* AFS_DEMAND_ATTACH_FS */
4710 DeleteVolumeFromHashTable(vp);
4711 vp->shuttingDown = 1; /* Let who has it free it. */
4712 vp->specialStatus = 0;
4713 #endif /* AFS_DEMAND_ATTACH_FS */
4718 #ifndef AFS_DEMAND_ATTACH_FS
4720 vp->specialStatus = 0; /* Allow others to have access. */
4721 #endif /* AFS_DEMAND_ATTACH_FS */
4724 #endif /* BITMAP_LATER */
4726 #ifdef AFS_DEMAND_ATTACH_FS
4728 #endif /* AFS_DEMAND_ATTACH_FS */
4729 bp = index->bitmap + index->bitmapOffset;
4730 ep = index->bitmap + index->bitmapSize;
4732 if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
4734 index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
4737 o = ffs(~*bp) - 1; /* ffs is documented in BSTRING(3) */
4739 ret = (VnodeId) ((bp - index->bitmap) * 8 + o);
4740 #ifdef AFS_DEMAND_ATTACH_FS
4742 #endif /* AFS_DEMAND_ATTACH_FS */
4745 bp += sizeof(bit32) /* i.e. 4 */ ;
4747 /* No bit map entry--must grow bitmap */
4749 realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
4752 bp += index->bitmapSize;
4753 memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
4754 index->bitmapOffset = index->bitmapSize;
4755 index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
4757 ret = index->bitmapOffset * 8;
4758 #ifdef AFS_DEMAND_ATTACH_FS
4760 #endif /* AFS_DEMAND_ATTACH_FS */
4763 #ifdef AFS_DEMAND_ATTACH_FS
4764 VChangeState_r(vp, state_save);
4765 if (flags & VOL_ALLOC_BITMAP_WAIT) {
4766 VCancelReservation_r(vp);
4768 #endif /* AFS_DEMAND_ATTACH_FS */
4773 VAllocBitmapEntry(Error * ec, Volume * vp, register struct vnodeIndex * index)
4777 retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
4783 VFreeBitMapEntry_r(Error * ec, register struct vnodeIndex *index,
4786 unsigned int offset;
4792 #endif /* BITMAP_LATER */
4793 offset = bitNumber >> 3;
4794 if (offset >= index->bitmapSize) {
4798 if (offset < index->bitmapOffset)
4799 index->bitmapOffset = offset & ~3; /* Truncate to nearest bit32 */
4800 *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
4804 VFreeBitMapEntry(Error * ec, register struct vnodeIndex *index,
4808 VFreeBitMapEntry_r(ec, index, bitNumber);
4812 /* this function will drop the glock internally.
4813 * for old pthread fileservers, this is safe thanks to vbusy.
4815 * for demand attach fs, caller must have already called
4816 * VCreateReservation_r and VWaitExclusiveState_r */
4818 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
4820 StreamHandle_t *file;
4823 struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
4824 struct vnodeIndex *vip = &vp->vnodeIndex[class];
4825 struct VnodeDiskObject *vnode;
4826 unsigned int unique = 0;
4830 #endif /* BITMAP_LATER */
4831 #ifdef AFS_DEMAND_ATTACH_FS
4832 VolState state_save;
4833 #endif /* AFS_DEMAND_ATTACH_FS */
4837 #ifdef AFS_DEMAND_ATTACH_FS
4838 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
4839 #endif /* AFS_DEMAND_ATTACH_FS */
4842 fdP = IH_OPEN(vip->handle);
4843 assert(fdP != NULL);
4844 file = FDH_FDOPEN(fdP, "r");
4845 assert(file != NULL);
4846 vnode = (VnodeDiskObject *) malloc(vcp->diskSize);
4847 assert(vnode != NULL);
4848 size = OS_SIZE(fdP->fd_fd);
4850 nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
4852 vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4; /* The 10 is a little extra so
4853 * a few files can be created in this volume,
4854 * the whole thing is rounded up to nearest 4
4855 * bytes, because the bit map allocator likes
4858 BitMap = (byte *) calloc(1, vip->bitmapSize);
4859 assert(BitMap != NULL);
4860 #else /* BITMAP_LATER */
4861 vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
4862 assert(vip->bitmap != NULL);
4863 vip->bitmapOffset = 0;
4864 #endif /* BITMAP_LATER */
4865 if (STREAM_SEEK(file, vcp->diskSize, 0) != -1) {
4867 for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
4868 if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
4870 if (vnode->type != vNull) {
4871 if (vnode->vnodeMagic != vcp->magic) {
4872 Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
4877 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
4878 #else /* BITMAP_LATER */
4879 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
4880 #endif /* BITMAP_LATER */
4881 if (unique <= vnode->uniquifier)
4882 unique = vnode->uniquifier + 1;
4884 #ifndef AFS_PTHREAD_ENV
4885 if ((bitNumber & 0x00ff) == 0x0ff) { /* every 256 iterations */
4888 #endif /* !AFS_PTHREAD_ENV */
4891 if (vp->nextVnodeUnique < unique) {
4892 Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
4895 /* Paranoia, partly justified--I think fclose after fdopen
4896 * doesn't seem to close fd. In any event, the documentation
4897 * doesn't specify, so it's safer to close it twice.
4905 /* There may have been a racing condition with some other thread, both
4906 * creating the bitmaps for this volume. If the other thread was faster
4907 * the pointer to bitmap should already be filled and we can free ours.
4909 if (vip->bitmap == NULL) {
4910 vip->bitmap = BitMap;
4911 vip->bitmapOffset = 0;
4913 free((byte *) BitMap);
4914 #endif /* BITMAP_LATER */
4915 #ifdef AFS_DEMAND_ATTACH_FS
4916 VChangeState_r(vp, state_save);
4917 #endif /* AFS_DEMAND_ATTACH_FS */
4921 /***************************************************/
4922 /* Volume Path and Volume Number utility routines */
4923 /***************************************************/
4926 * find the first occurrence of a volume header file and return the path.
4928 * @param[out] ec outbound error code
4929 * @param[in] volumeId volume id to find
4930 * @param[out] partitionp pointer to disk partition path string
4931 * @param[out] namep pointer to volume header file name string
4933 * @post path to first occurrence of volume header is returned in partitionp
4934 * and namep, or ec is set accordingly.
4936 * @warning this function is NOT re-entrant -- partitionp and namep point to
4937 * static data segments
4939 * @note if a volume utility inadvertently leaves behind a stale volume header
4940 * on a vice partition, it is possible for callers to get the wrong one,
4941 * depending on the order of the disk partition linked list.
4945 VGetVolumePath(Error * ec, VolId volumeId, char **partitionp, char **namep)
4947 static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
4948 char path[VMAXPATHLEN];
4950 struct DiskPartition64 *dp;
4954 (void)afs_snprintf(&name[1], (sizeof name) - 1, VFORMAT, afs_printable_uint32_lu(volumeId));
4955 for (dp = DiskPartitionList; dp; dp = dp->next) {
4956 struct afs_stat status;
4957 strcpy(path, VPartitionPath(dp));
4959 if (afs_stat(path, &status) == 0) {
4960 strcpy(partition, dp->name);
4967 *partitionp = *namep = NULL;
4969 *partitionp = partition;
4975 * extract a volume number from a volume header filename string.
4977 * @param[in] name volume header filename string
4979 * @return volume number
4981 * @note the string must be of the form VFORMAT. the only permissible
4982 * deviation is a leading '/' character.
4987 VolumeNumber(char *name)
4991 return atoi(name + 1);
4995 * compute the volume header filename.
4997 * @param[in] volumeId
4999 * @return volume header filename
5001 * @post volume header filename string is constructed
5003 * @warning this function is NOT re-entrant -- the returned string is
5004 * stored in a static char array. see VolumeExternalName_r
5005 * for a re-entrant equivalent.
5007 * @see VolumeExternalName_r
5009 * @deprecated due to the above re-entrancy warning, this interface should
5010 * be considered deprecated. Please use VolumeExternalName_r
5014 VolumeExternalName(VolumeId volumeId)
5016 static char name[VMAXPATHLEN];
5017 (void)afs_snprintf(name, sizeof name, VFORMAT, afs_printable_uint32_lu(volumeId));
5022 * compute the volume header filename.
5024 * @param[in] volumeId
5025 * @param[inout] name array in which to store filename
5026 * @param[in] len length of name array
5028 * @return result code from afs_snprintf
5030 * @see VolumeExternalName
5033 * @note re-entrant equivalent of VolumeExternalName
5035 * @internal volume package internal use only.
5037 #ifdef AFS_DEMAND_ATTACH_FS
5039 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
5041 return afs_snprintf(name, len, VFORMAT, afs_printable_uint32_lu(volumeId));
5046 /***************************************************/
5047 /* Volume Usage Statistics routines */
5048 /***************************************************/
5050 #if OPENAFS_VOL_STATS
5051 #define OneDay (86400) /* 24 hours' worth of seconds */
5053 #define OneDay (24*60*60) /* 24 hours */
5054 #endif /* OPENAFS_VOL_STATS */
5056 #define Midnight(date) ((date-TimeZoneCorrection)/OneDay*OneDay+TimeZoneCorrection)
5058 /*------------------------------------------------------------------------
5059 * [export] VAdjustVolumeStatistics
5062 * If we've passed midnight, we need to update all the day use
5063 * statistics as well as zeroing the detailed volume statistics
5064 * (if we are implementing them).
5067 * vp : Pointer to the volume structure describing the lucky
5068 * volume being considered for update.
5074 * Nothing interesting.
5078 *------------------------------------------------------------------------*/
5081 VAdjustVolumeStatistics_r(register Volume * vp)
5083 unsigned int now = FT_ApproxTime();
5085 if (now - V_dayUseDate(vp) > OneDay) {
5086 register int ndays, i;
5088 ndays = (now - V_dayUseDate(vp)) / OneDay;
5089 for (i = 6; i > ndays - 1; i--)
5090 V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
5091 for (i = 0; i < ndays - 1 && i < 7; i++)
5092 V_weekUse(vp)[i] = 0;
5094 V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
5096 V_dayUseDate(vp) = Midnight(now);
5098 #if OPENAFS_VOL_STATS
5100 * All we need to do is bzero the entire VOL_STATS_BYTES of
5101 * the detailed volume statistics area.
5103 memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
5104 #endif /* OPENAFS_VOL_STATS */
5107 /*It's been more than a day of collection */
5109 * Always return happily.
5112 } /*VAdjustVolumeStatistics */
5115 VAdjustVolumeStatistics(register Volume * vp)
5119 retVal = VAdjustVolumeStatistics_r(vp);
5125 VBumpVolumeUsage_r(register Volume * vp)
5127 unsigned int now = FT_ApproxTime();
5128 V_accessDate(vp) = now;
5129 if (now - V_dayUseDate(vp) > OneDay)
5130 VAdjustVolumeStatistics_r(vp);
5132 * Save the volume header image to disk after every 128 bumps to dayUse.
5134 if ((V_dayUse(vp)++ & 127) == 0) {
5136 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
5141 VBumpVolumeUsage(register Volume * vp)
5144 VBumpVolumeUsage_r(vp);
5149 VSetDiskUsage_r(void)
5151 #ifndef AFS_DEMAND_ATTACH_FS
5152 static int FifteenMinuteCounter = 0;
5156 /* NOTE: Don't attempt to access the partitions list until the
5157 * initialization level indicates that all volumes are attached,
5158 * which implies that all partitions are initialized. */
5159 #ifdef AFS_PTHREAD_ENV
5161 #else /* AFS_PTHREAD_ENV */
5163 #endif /* AFS_PTHREAD_ENV */
5166 VResetDiskUsage_r();
5168 #ifndef AFS_DEMAND_ATTACH_FS
5169 if (++FifteenMinuteCounter == 3) {
5170 FifteenMinuteCounter = 0;
5173 #endif /* !AFS_DEMAND_ATTACH_FS */
5185 /***************************************************/
5186 /* Volume Update List routines */
5187 /***************************************************/
5189 /* The number of minutes that a volume hasn't been updated before the
5190 * "Dont salvage" flag in the volume header will be turned on */
5191 #define SALVAGE_INTERVAL (10*60)
5196 * volume update list functionality has been moved into the VLRU
5197 * the DONT_SALVAGE flag is now set during VLRU demotion
5200 #ifndef AFS_DEMAND_ATTACH_FS
5201 static VolumeId *UpdateList = NULL; /* Pointer to array of Volume ID's */
5202 static int nUpdatedVolumes = 0; /* Updated with entry in UpdateList, salvage after crash flag on */
5203 static int updateSize = 0; /* number of entries possible */
5204 #define UPDATE_LIST_SIZE 128 /* initial size increment (must be a power of 2!) */
5205 #endif /* !AFS_DEMAND_ATTACH_FS */
5208 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
5211 vp->updateTime = FT_ApproxTime();
5212 if (V_dontSalvage(vp) == 0)
5214 V_dontSalvage(vp) = 0;
5215 VSyncVolume_r(ec, vp, 0);
5216 #ifdef AFS_DEMAND_ATTACH_FS
5217 V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
5218 #else /* !AFS_DEMAND_ATTACH_FS */
5221 if (UpdateList == NULL) {
5222 updateSize = UPDATE_LIST_SIZE;
5223 UpdateList = (VolumeId *) malloc(sizeof(VolumeId) * updateSize);
5225 if (nUpdatedVolumes == updateSize) {
5227 if (updateSize > 524288) {
5228 Log("warning: there is likely a bug in the volume update scanner\n");
5232 (VolumeId *) realloc(UpdateList,
5233 sizeof(VolumeId) * updateSize);
5236 assert(UpdateList != NULL);
5237 UpdateList[nUpdatedVolumes++] = V_id(vp);
5238 #endif /* !AFS_DEMAND_ATTACH_FS */
5241 #ifndef AFS_DEMAND_ATTACH_FS
5243 VScanUpdateList(void)
5245 register int i, gap;
5246 register Volume *vp;
5248 afs_uint32 now = FT_ApproxTime();
5249 /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
5250 for (i = gap = 0; i < nUpdatedVolumes; i++) {
5252 UpdateList[i - gap] = UpdateList[i];
5254 /* XXX this routine needlessly messes up the Volume LRU by
5255 * breaking the LRU temporal-locality assumptions.....
5256 * we should use a special volume header allocator here */
5257 vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
5260 } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
5261 V_dontSalvage(vp) = DONT_SALVAGE;
5262 VUpdateVolume_r(&error, vp, 0); /* No need to fsync--not critical */
5270 #ifndef AFS_PTHREAD_ENV
5272 #endif /* !AFS_PTHREAD_ENV */
5274 nUpdatedVolumes -= gap;
5276 #endif /* !AFS_DEMAND_ATTACH_FS */
5279 /***************************************************/
5280 /* Volume LRU routines */
5281 /***************************************************/
5286 * with demand attach fs, we attempt to soft detach(1)
5287 * volumes which have not been accessed in a long time
5288 * in order to speed up fileserver shutdown
5290 * (1) by soft detach we mean a process very similar
5291 * to VOffline, except the final state of the
5292 * Volume will be VOL_STATE_PREATTACHED, instead
5293 * of the usual VOL_STATE_UNATTACHED
5295 #ifdef AFS_DEMAND_ATTACH_FS
5297 /* implementation is reminiscent of a generational GC
5299 * queue 0 is newly attached volumes. this queue is
5300 * sorted by attach timestamp
5302 * queue 1 is volumes that have been around a bit
5303 * longer than queue 0. this queue is sorted by
5306 * queue 2 is volumes tha have been around the longest.
5307 * this queue is unsorted
5309 * queue 3 is volumes that have been marked as
5310 * candidates for soft detachment. this queue is
5313 #define VLRU_GENERATIONS 3 /**< number of generations in VLRU */
5314 #define VLRU_QUEUES 5 /**< total number of VLRU queues */
5317 * definition of a VLRU queue.
5320 volatile struct rx_queue q;
5327 * main VLRU data structure.
5330 struct VLRU_q q[VLRU_QUEUES]; /**< VLRU queues */
5333 /** time interval (in seconds) between promotion passes for
5334 * each young generation queue. */
5335 afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
5337 /** time interval (in seconds) between soft detach candidate
5338 * scans for each generation queue.
5340 * scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
5341 * we perform a soft detach pass. */
5342 afs_uint32 scan_interval[VLRU_GENERATIONS+1];
5344 /* scheduler state */
5345 int next_idx; /**< next queue to receive attention */
5346 afs_uint32 last_promotion[VLRU_GENERATIONS-1]; /**< timestamp of last promotion scan */
5347 afs_uint32 last_scan[VLRU_GENERATIONS+1]; /**< timestamp of last detach scan */
5349 int scanner_state; /**< state of scanner thread */
5350 pthread_cond_t cv; /**< state transition CV */
5353 /** global VLRU state */
5354 static struct VLRU volume_LRU;
5357 * defined states for VLRU scanner thread.
5360 VLRU_SCANNER_STATE_OFFLINE = 0, /**< vlru scanner thread is offline */
5361 VLRU_SCANNER_STATE_ONLINE = 1, /**< vlru scanner thread is online */
5362 VLRU_SCANNER_STATE_SHUTTING_DOWN = 2, /**< vlru scanner thread is shutting down */
5363 VLRU_SCANNER_STATE_PAUSING = 3, /**< vlru scanner thread is getting ready to pause */
5364 VLRU_SCANNER_STATE_PAUSED = 4 /**< vlru scanner thread is paused */
5365 } vlru_thread_state_t;
5367 /* vlru disk data header stuff */
5368 #define VLRU_DISK_MAGIC 0x7a8b9cad /**< vlru disk entry magic number */
5369 #define VLRU_DISK_VERSION 1 /**< vlru disk entry version number */
5371 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
5372 #define VLRU_DUMP_EXPIRATION_TIME (60*60*24*7) /* expire vlru data after 1 week */
5375 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
5376 * soft detachment. */
5377 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
5379 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
5380 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
5382 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
5383 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
5385 /** VLRU control flag. non-zero value implies VLRU subsystem is activated. */
5386 static afs_uint32 VLRU_enabled = 1;
5388 /* queue synchronization routines */
5389 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
5390 static void VLRU_EndExclusive_r(struct VLRU_q * q);
5391 static void VLRU_Wait_r(struct VLRU_q * q);
5394 * set VLRU subsystem tunable parameters.
5396 * @param[in] option tunable option to modify
5397 * @param[in] val new value for tunable parameter
5399 * @pre @c VInitVolumePackage has not yet been called.
5401 * @post tunable parameter is modified
5405 * @note valid option parameters are:
5406 * @arg @c VLRU_SET_THRESH
5407 * set the period of inactivity after which
5408 * volumes are eligible for soft detachment
5409 * @arg @c VLRU_SET_INTERVAL
5410 * set the time interval between calls
5411 * to the volume LRU "garbage collector"
5412 * @arg @c VLRU_SET_MAX
5413 * set the max number of volumes to deallocate
5417 VLRU_SetOptions(int option, afs_uint32 val)
5419 if (option == VLRU_SET_THRESH) {
5420 VLRU_offline_thresh = val;
5421 } else if (option == VLRU_SET_INTERVAL) {
5422 VLRU_offline_interval = val;
5423 } else if (option == VLRU_SET_MAX) {
5424 VLRU_offline_max = val;
5425 } else if (option == VLRU_SET_ENABLED) {
5428 VLRU_ComputeConstants();
5432 * compute VLRU internal timing parameters.
5434 * @post VLRU scanner thread internal timing parameters are computed
5436 * @note computes internal timing parameters based upon user-modifiable
5437 * tunable parameters.
5441 * @internal volume package internal use only.
5444 VLRU_ComputeConstants(void)
5446 afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
5448 /* compute the candidate scan interval */
5449 volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
5451 /* compute the promotion intervals */
5452 volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
5453 volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
5456 /* compute the gen 0 scan interval */
5457 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
5459 /* compute the gen 0 scan interval */
5460 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
5465 * initialize VLRU subsystem.
5467 * @pre this function has not yet been called
5469 * @post VLRU subsystem is initialized and VLRU scanner thread is starting
5473 * @internal volume package internal use only.
5479 pthread_attr_t attrs;
5482 if (!VLRU_enabled) {
5483 Log("VLRU: disabled\n");
5487 /* initialize each of the VLRU queues */
5488 for (i = 0; i < VLRU_QUEUES; i++) {
5489 queue_Init(&volume_LRU.q[i]);
5490 volume_LRU.q[i].len = 0;
5491 volume_LRU.q[i].busy = 0;
5492 assert(pthread_cond_init(&volume_LRU.q[i].cv, NULL) == 0);
5495 /* setup the timing constants */
5496 VLRU_ComputeConstants();
5498 /* XXX put inside LogLevel check? */
5499 Log("VLRU: starting scanner with the following configuration parameters:\n");
5500 Log("VLRU: offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
5501 Log("VLRU: running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
5502 Log("VLRU: taking up to %d volumes offline per pass\n", VLRU_offline_max);
5503 Log("VLRU: scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
5504 Log("VLRU: scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
5505 Log("VLRU: scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
5507 /* start up the VLRU scanner */
5508 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
5509 if (programType == fileServer) {
5510 assert(pthread_cond_init(&volume_LRU.cv, NULL) == 0);
5511 assert(pthread_attr_init(&attrs) == 0);
5512 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
5513 assert(pthread_create(&tid, &attrs, &VLRU_ScannerThread, NULL) == 0);
5518 * initialize the VLRU-related fields of a newly allocated volume object.
5520 * @param[in] vp pointer to volume object
5523 * @arg @c VOL_LOCK is held.
5524 * @arg volume object is not on a VLRU queue.
5526 * @post VLRU fields are initialized to indicate that volume object is not
5527 * currently registered with the VLRU subsystem
5531 * @internal volume package interal use only.
5534 VLRU_Init_Node_r(Volume * vp)
5539 assert(queue_IsNotOnQueue(&vp->vlru));
5540 vp->vlru.idx = VLRU_QUEUE_INVALID;
5544 * add a volume object to a VLRU queue.
5546 * @param[in] vp pointer to volume object
5549 * @arg @c VOL_LOCK is held.
5550 * @arg caller MUST hold a lightweight ref on @p vp.
5551 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
5553 * @post the volume object is added to the appropriate VLRU queue
5555 * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
5556 * then the volume is added to that queue. Otherwise, the value
5557 * @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
5558 * volume is added to the NEW generation queue.
5560 * @note @c VOL_LOCK may be dropped internally
5562 * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
5563 * during the add operation, and is restored to the previous
5564 * state prior to return.
5568 * @internal volume package internal use only.
5571 VLRU_Add_r(Volume * vp)
5574 VolState state_save;
5579 if (queue_IsOnQueue(&vp->vlru))
5582 state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
5585 if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
5586 idx = VLRU_QUEUE_NEW;
5589 VLRU_Wait_r(&volume_LRU.q[idx]);
5591 /* repeat check since VLRU_Wait_r may have dropped
5593 if (queue_IsNotOnQueue(&vp->vlru)) {
5595 queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
5596 volume_LRU.q[idx].len++;
5597 V_attachFlags(vp) |= VOL_ON_VLRU;
5598 vp->stats.last_promote = FT_ApproxTime();
5601 VChangeState_r(vp, state_save);
5605 * delete a volume object from a VLRU queue.
5607 * @param[in] vp pointer to volume object
5610 * @arg @c VOL_LOCK is held.
5611 * @arg caller MUST hold a lightweight ref on @p vp.
5612 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
5614 * @post volume object is removed from the VLRU queue
5616 * @note @c VOL_LOCK may be dropped internally
5620 * @todo We should probably set volume state to something exlcusive
5621 * (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
5623 * @internal volume package internal use only.
5626 VLRU_Delete_r(Volume * vp)
5633 if (queue_IsNotOnQueue(&vp->vlru))
5639 if (idx == VLRU_QUEUE_INVALID)
5641 VLRU_Wait_r(&volume_LRU.q[idx]);
5642 } while (idx != vp->vlru.idx);
5644 /* now remove from the VLRU and update
5645 * the appropriate counter */
5646 queue_Remove(&vp->vlru);
5647 volume_LRU.q[idx].len--;
5648 vp->vlru.idx = VLRU_QUEUE_INVALID;
5649 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
5653 * tell the VLRU subsystem that a volume was just accessed.
5655 * @param[in] vp pointer to volume object
5658 * @arg @c VOL_LOCK is held
5659 * @arg caller MUST hold a lightweight ref on @p vp
5660 * @arg caller MUST NOT hold exclusive ownership of any VLRU queue
5662 * @post volume VLRU access statistics are updated. If the volume was on
5663 * the VLRU soft detach candidate queue, it is moved to the NEW
5666 * @note @c VOL_LOCK may be dropped internally
5670 * @internal volume package internal use only.
5673 VLRU_UpdateAccess_r(Volume * vp)
5675 Volume * rvp = NULL;
5680 if (queue_IsNotOnQueue(&vp->vlru))
5683 assert(V_attachFlags(vp) & VOL_ON_VLRU);
5685 /* update the access timestamp */
5686 vp->stats.last_get = FT_ApproxTime();
5689 * if the volume is on the soft detach candidate
5690 * list, we need to safely move it back to a
5691 * regular generation. this has to be done
5692 * carefully so we don't race against the scanner
5696 /* if this volume is on the soft detach candidate queue,
5697 * then grab exclusive access to the necessary queues */
5698 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
5700 VCreateReservation_r(rvp);
5702 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
5703 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
5704 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5705 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5708 /* make sure multiple threads don't race to update */
5709 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
5710 VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
5714 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5715 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
5716 VCancelReservation_r(rvp);
5721 * switch a volume between two VLRU queues.
5723 * @param[in] vp pointer to volume object
5724 * @param[in] new_idx index of VLRU queue onto which the volume will be moved
5725 * @param[in] append controls whether the volume will be appended or
5726 * prepended to the queue. A nonzero value means it will
5727 * be appended; zero means it will be prepended.
5729 * @pre The new (and old, if applicable) queue(s) must either be owned
5730 * exclusively by the calling thread for asynchronous manipulation,
5731 * or the queue(s) must be quiescent and VOL_LOCK must be held.
5732 * Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
5733 * for further details of the queue asynchronous processing mechanism.
5735 * @post If the volume object was already on a VLRU queue, it is
5736 * removed from the queue. Depending on the value of the append
5737 * parameter, the volume object is either appended or prepended
5738 * to the VLRU queue referenced by the new_idx parameter.
5742 * @see VLRU_BeginExclusive_r
5743 * @see VLRU_EndExclusive_r
5746 * @internal volume package internal use only.
5749 VLRU_SwitchQueues(Volume * vp, int new_idx, int append)
5751 if (queue_IsNotOnQueue(&vp->vlru))
5754 queue_Remove(&vp->vlru);
5755 volume_LRU.q[vp->vlru.idx].len--;
5757 /* put the volume back on the correct generational queue */
5759 queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
5761 queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
5764 volume_LRU.q[new_idx].len++;
5765 vp->vlru.idx = new_idx;
5769 * VLRU background thread.
5771 * The VLRU Scanner Thread is responsible for periodically scanning through
5772 * each VLRU queue looking for volumes which should be moved to another
5773 * queue, or soft detached.
5775 * @param[in] args unused thread arguments parameter
5777 * @return unused thread return value
5778 * @retval NULL always
5780 * @internal volume package internal use only.
5783 VLRU_ScannerThread(void * args)
5785 afs_uint32 now, min_delay, delay;
5786 int i, min_idx, min_op, overdue, state;
5788 /* set t=0 for promotion cycle to be
5789 * fileserver startup */
5790 now = FT_ApproxTime();
5791 for (i=0; i < VLRU_GENERATIONS-1; i++) {
5792 volume_LRU.last_promotion[i] = now;
5795 /* don't start the scanner until VLRU_offline_thresh
5796 * plus a small delay for VInitVolumePackage to finish
5799 sleep(VLRU_offline_thresh + 60);
5801 /* set t=0 for scan cycle to be now */
5802 now = FT_ApproxTime();
5803 for (i=0; i < VLRU_GENERATIONS+1; i++) {
5804 volume_LRU.last_scan[i] = now;
5808 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
5809 volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
5812 while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
5813 /* check to see if we've been asked to pause */
5814 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
5815 volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
5816 assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
5818 VOL_CV_WAIT(&volume_LRU.cv);
5819 } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
5822 /* scheduling can happen outside the glock */
5825 /* figure out what is next on the schedule */
5827 /* figure out a potential schedule for the new generation first */
5829 min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
5832 if (min_delay > volume_LRU.scan_interval[0]) {
5833 /* unsigned overflow -- we're overdue to run this scan */
5838 /* if we're not overdue for gen 0, figure out schedule for candidate gen */
5840 i = VLRU_QUEUE_CANDIDATE;
5841 delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
5842 if (delay < min_delay) {
5846 if (delay > volume_LRU.scan_interval[i]) {
5847 /* unsigned overflow -- we're overdue to run this scan */
5854 /* if we're still not overdue for something, figure out schedules for promotions */
5855 for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
5856 delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
5857 if (delay < min_delay) {
5862 if (delay > volume_LRU.promotion_interval[i]) {
5863 /* unsigned overflow -- we're overdue to run this promotion */
5872 /* sleep as needed */
5877 /* do whatever is next */
5880 VLRU_Promote_r(min_idx);
5881 VLRU_Demote_r(min_idx+1);
5883 VLRU_Scan_r(min_idx);
5885 now = FT_ApproxTime();
5888 Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
5890 /* signal that scanner is down */
5891 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
5892 assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
5898 * promote volumes from one VLRU generation to the next.
5900 * This routine scans a VLRU generation looking for volumes which are
5901 * eligible to be promoted to the next generation. All volumes which
5902 * meet the eligibility requirement are promoted.
5904 * Promotion eligibility is based upon meeting both of the following
5907 * @arg The volume has been accessed since the last promotion:
5908 * @c (vp->stats.last_get >= vp->stats.last_promote)
5909 * @arg The last promotion occurred at least
5910 * @c volume_LRU.promotion_interval[idx] seconds ago
5912 * As a performance optimization, promotions are "globbed". In other
5913 * words, we promote arbitrarily large contiguous sublists of elements
5916 * @param[in] idx VLRU queue index to scan
5920 * @internal VLRU internal use only.
5923 VLRU_Promote_r(int idx)
5925 int len, chaining, promote;
5926 afs_uint32 now, thresh;
5927 struct rx_queue *qp, *nqp;
5928 Volume * vp, *start = NULL, *end = NULL;
5930 /* get exclusive access to two chains, and drop the glock */
5931 VLRU_Wait_r(&volume_LRU.q[idx]);
5932 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
5933 VLRU_Wait_r(&volume_LRU.q[idx+1]);
5934 VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
5937 thresh = volume_LRU.promotion_interval[idx];
5938 now = FT_ApproxTime();
5941 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
5942 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
5943 promote = (((vp->stats.last_promote + thresh) <= now) &&
5944 (vp->stats.last_get >= vp->stats.last_promote));
5952 /* promote and prepend chain */
5953 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
5967 /* promote and prepend */
5968 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
5972 volume_LRU.q[idx].len -= len;
5973 volume_LRU.q[idx+1].len += len;
5976 /* release exclusive access to the two chains */
5978 volume_LRU.last_promotion[idx] = now;
5979 VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
5980 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
5983 /* run the demotions */
5985 VLRU_Demote_r(int idx)
5988 int len, chaining, demote;
5989 afs_uint32 now, thresh;
5990 struct rx_queue *qp, *nqp;
5991 Volume * vp, *start = NULL, *end = NULL;
5992 Volume ** salv_flag_vec = NULL;
5993 int salv_vec_offset = 0;
5995 assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
5997 /* get exclusive access to two chains, and drop the glock */
5998 VLRU_Wait_r(&volume_LRU.q[idx-1]);
5999 VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
6000 VLRU_Wait_r(&volume_LRU.q[idx]);
6001 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
6004 /* no big deal if this allocation fails */
6005 if (volume_LRU.q[idx].len) {
6006 salv_flag_vec = (Volume **) malloc(volume_LRU.q[idx].len * sizeof(Volume *));
6009 now = FT_ApproxTime();
6010 thresh = volume_LRU.promotion_interval[idx-1];
6013 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
6014 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6015 demote = (((vp->stats.last_promote + thresh) <= now) &&
6016 (vp->stats.last_get < (now - thresh)));
6018 /* we now do volume update list DONT_SALVAGE flag setting during
6019 * demotion passes */
6020 if (salv_flag_vec &&
6021 !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
6023 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
6024 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
6025 salv_flag_vec[salv_vec_offset++] = vp;
6026 VCreateReservation_r(vp);
6035 /* demote and append chain */
6036 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
6050 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
6054 volume_LRU.q[idx].len -= len;
6055 volume_LRU.q[idx-1].len += len;
6058 /* release exclusive access to the two chains */
6060 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
6061 VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
6063 /* now go back and set the DONT_SALVAGE flags as appropriate */
6064 if (salv_flag_vec) {
6066 for (i = 0; i < salv_vec_offset; i++) {
6067 vp = salv_flag_vec[i];
6068 if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
6069 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
6070 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
6073 V_attachFlags(vp) |= VOL_HDR_DONTSALV;
6074 V_dontSalvage(vp) = DONT_SALVAGE;
6075 VUpdateVolume_r(&ec, vp, 0);
6079 VCancelReservation_r(vp);
6081 free(salv_flag_vec);
6085 /* run a pass of the VLRU GC scanner */
6087 VLRU_Scan_r(int idx)
6089 afs_uint32 now, thresh;
6090 struct rx_queue *qp, *nqp;
6094 assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
6096 /* gain exclusive access to the idx VLRU */
6097 VLRU_Wait_r(&volume_LRU.q[idx]);
6098 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
6100 if (idx != VLRU_QUEUE_CANDIDATE) {
6101 /* gain exclusive access to the candidate VLRU */
6102 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6103 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6106 now = FT_ApproxTime();
6107 thresh = now - VLRU_offline_thresh;
6109 /* perform candidate selection and soft detaching */
6110 if (idx == VLRU_QUEUE_CANDIDATE) {
6111 /* soft detach some volumes from the candidate pool */
6115 for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
6116 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6117 if (i >= VLRU_offline_max) {
6120 /* check timestamp to see if it's a candidate for soft detaching */
6121 if (vp->stats.last_get <= thresh) {
6123 if (VCheckSoftDetach(vp, thresh))
6129 /* scan for volumes to become soft detach candidates */
6130 for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
6131 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6133 /* check timestamp to see if it's a candidate for soft detaching */
6134 if (vp->stats.last_get <= thresh) {
6135 VCheckSoftDetachCandidate(vp, thresh);
6138 if (!(i&0x7f)) { /* lock coarsening optimization */
6146 /* relinquish exclusive access to the VLRU chains */
6150 volume_LRU.last_scan[idx] = now;
6151 if (idx != VLRU_QUEUE_CANDIDATE) {
6152 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6154 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
6157 /* check whether volume is safe to soft detach
6158 * caller MUST NOT hold a ref count on vp */
6160 VCheckSoftDetach(Volume * vp, afs_uint32 thresh)
6164 if (vp->nUsers || vp->nWaiters)
6167 if (vp->stats.last_get <= thresh) {
6168 ret = VSoftDetachVolume_r(vp, thresh);
6174 /* check whether volume should be made a
6175 * soft detach candidate */
6177 VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh)
6180 if (vp->nUsers || vp->nWaiters)
6185 assert(idx == VLRU_QUEUE_NEW);
6187 if (vp->stats.last_get <= thresh) {
6188 /* move to candidate pool */
6189 queue_Remove(&vp->vlru);
6190 volume_LRU.q[VLRU_QUEUE_NEW].len--;
6191 queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
6192 vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
6193 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
6201 /* begin exclusive access on VLRU */
6203 VLRU_BeginExclusive_r(struct VLRU_q * q)
6205 assert(q->busy == 0);
6209 /* end exclusive access on VLRU */
6211 VLRU_EndExclusive_r(struct VLRU_q * q)
6215 assert(pthread_cond_broadcast(&q->cv) == 0);
6218 /* wait for another thread to end exclusive access on VLRU */
6220 VLRU_Wait_r(struct VLRU_q * q)
6223 VOL_CV_WAIT(&q->cv);
6228 * volume soft detach
6230 * caller MUST NOT hold a ref count on vp */
6232 VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh)
6237 assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
6239 ts_save = vp->stats.last_get;
6240 if (ts_save > thresh)
6243 if (vp->nUsers || vp->nWaiters)
6246 if (VIsExclusiveState(V_attachState(vp))) {
6250 switch (V_attachState(vp)) {
6251 case VOL_STATE_UNATTACHED:
6252 case VOL_STATE_PREATTACHED:
6253 case VOL_STATE_ERROR:
6254 case VOL_STATE_GOING_OFFLINE:
6255 case VOL_STATE_SHUTTING_DOWN:
6256 case VOL_STATE_SALVAGING:
6257 volume_LRU.q[vp->vlru.idx].len--;
6259 /* create and cancel a reservation to
6260 * give the volume an opportunity to
6262 VCreateReservation_r(vp);
6263 queue_Remove(&vp->vlru);
6264 vp->vlru.idx = VLRU_QUEUE_INVALID;
6265 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
6266 VCancelReservation_r(vp);
6272 /* hold the volume and take it offline.
6273 * no need for reservations, as VHold_r
6274 * takes care of that internally. */
6275 if (VHold_r(vp) == 0) {
6276 /* vhold drops the glock, so now we should
6277 * check to make sure we aren't racing against
6278 * other threads. if we are racing, offlining vp
6279 * would be wasteful, and block the scanner for a while
6283 (vp->shuttingDown) ||
6284 (vp->goingOffline) ||
6285 (vp->stats.last_get != ts_save)) {
6286 /* looks like we're racing someone else. bail */
6290 /* pull it off the VLRU */
6291 assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
6292 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
6293 queue_Remove(&vp->vlru);
6294 vp->vlru.idx = VLRU_QUEUE_INVALID;
6295 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
6297 /* take if offline */
6298 VOffline_r(vp, "volume has been soft detached");
6300 /* invalidate the volume header cache */
6301 FreeVolumeHeader(vp);
6304 IncUInt64(&VStats.soft_detaches);
6305 vp->stats.soft_detaches++;
6307 /* put in pre-attached state so demand
6308 * attacher can work on it */
6309 VChangeState_r(vp, VOL_STATE_PREATTACHED);
6315 #endif /* AFS_DEMAND_ATTACH_FS */
6318 /***************************************************/
6319 /* Volume Header Cache routines */
6320 /***************************************************/
6323 * volume header cache.
6325 struct volume_hdr_LRU_t volume_hdr_LRU;
6328 * initialize the volume header cache.
6330 * @param[in] howMany number of header cache entries to preallocate
6332 * @pre VOL_LOCK held. Function has never been called before.
6334 * @post howMany cache entries are allocated, initialized, and added
6335 * to the LRU list. Header cache statistics are initialized.
6337 * @note only applicable to fileServer program type. Should only be
6338 * called once during volume package initialization.
6340 * @internal volume package internal use only.
6343 VInitVolumeHeaderCache(afs_uint32 howMany)
6345 register struct volHeader *hp;
6346 if (programType != fileServer)
6348 queue_Init(&volume_hdr_LRU);
6349 volume_hdr_LRU.stats.free = 0;
6350 volume_hdr_LRU.stats.used = howMany;
6351 volume_hdr_LRU.stats.attached = 0;
6352 hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
6356 /* We are using ReleaseVolumeHeader to initialize the values on the header list
6357 * to ensure they have the right values
6359 ReleaseVolumeHeader(hp++);
6363 * get a volume header and attach it to the volume object.
6365 * @param[in] vp pointer to volume object
6367 * @return cache entry status
6368 * @retval 0 volume header was newly attached; cache data is invalid
6369 * @retval 1 volume header was previously attached; cache data is valid
6371 * @pre VOL_LOCK held. For DAFS, lightweight ref must be held on volume object.
6373 * @post volume header attached to volume object. if necessary, header cache
6374 * entry on LRU is synchronized to disk. Header is removed from LRU list.
6376 * @note VOL_LOCK may be dropped
6378 * @warning this interface does not load header data from disk. it merely
6379 * attaches a header object to the volume object, and may sync the old
6380 * header cache data out to disk in the process.
6382 * @internal volume package internal use only.
6385 GetVolumeHeader(register Volume * vp)
6388 register struct volHeader *hd;
6390 static int everLogged = 0;
6392 #ifdef AFS_DEMAND_ATTACH_FS
6393 VolState vp_save = 0, back_save = 0;
6395 /* XXX debug 9/19/05 we've apparently got
6396 * a ref counting bug somewhere that's
6397 * breaking the nUsers == 0 => header on LRU
6399 if (vp->header && queue_IsNotOnQueue(vp->header)) {
6400 Log("nUsers == 0, but header not on LRU\n");
6405 old = (vp->header != NULL); /* old == volume already has a header */
6407 if (programType != fileServer) {
6408 /* for volume utilities, we allocate volHeaders as needed */
6410 hd = (struct volHeader *)calloc(1, sizeof(*vp->header));
6414 #ifdef AFS_DEMAND_ATTACH_FS
6415 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
6419 /* for the fileserver, we keep a volume header cache */
6421 /* the header we previously dropped in the lru is
6422 * still available. pull it off the lru and return */
6425 assert(hd->back == vp);
6427 /* we need to grab a new element off the LRU */
6428 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
6429 /* grab an element and pull off of LRU */
6430 hd = queue_First(&volume_hdr_LRU, volHeader);
6433 /* LRU is empty, so allocate a new volHeader
6434 * this is probably indicative of a leak, so let the user know */
6435 hd = (struct volHeader *)calloc(1, sizeof(struct volHeader));
6438 Log("****Allocated more volume headers, probably leak****\n");
6441 volume_hdr_LRU.stats.free++;
6444 /* this header used to belong to someone else.
6445 * we'll need to check if the header needs to
6446 * be sync'd out to disk */
6448 #ifdef AFS_DEMAND_ATTACH_FS
6449 /* if hd->back were in an exclusive state, then
6450 * its volHeader would not be on the LRU... */
6451 assert(!VIsExclusiveState(V_attachState(hd->back)));
6454 if (hd->diskstuff.inUse) {
6455 /* volume was in use, so we'll need to sync
6456 * its header to disk */
6458 #ifdef AFS_DEMAND_ATTACH_FS
6459 back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
6460 vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
6461 VCreateReservation_r(hd->back);
6465 WriteVolumeHeader_r(&error, hd->back);
6466 /* Ignore errors; catch them later */
6468 #ifdef AFS_DEMAND_ATTACH_FS
6473 hd->back->header = NULL;
6474 #ifdef AFS_DEMAND_ATTACH_FS
6475 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
6477 if (hd->diskstuff.inUse) {
6478 VChangeState_r(hd->back, back_save);
6479 VCancelReservation_r(hd->back);
6480 VChangeState_r(vp, vp_save);
6484 volume_hdr_LRU.stats.attached++;
6488 #ifdef AFS_DEMAND_ATTACH_FS
6489 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
6492 volume_hdr_LRU.stats.free--;
6493 volume_hdr_LRU.stats.used++;
6495 IncUInt64(&VStats.hdr_gets);
6496 #ifdef AFS_DEMAND_ATTACH_FS
6497 IncUInt64(&vp->stats.hdr_gets);
6498 vp->stats.last_hdr_get = FT_ApproxTime();
6505 * make sure volume header is attached and contains valid cache data.
6507 * @param[out] ec outbound error code
6508 * @param[in] vp pointer to volume object
6510 * @pre VOL_LOCK held. For DAFS, lightweight ref held on vp.
6512 * @post header cache entry attached, and loaded with valid data, or
6513 * *ec is nonzero, and the header is released back into the LRU.
6515 * @internal volume package internal use only.
6518 LoadVolumeHeader(Error * ec, Volume * vp)
6520 #ifdef AFS_DEMAND_ATTACH_FS
6521 VolState state_save;
6525 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
6526 IncUInt64(&VStats.hdr_loads);
6527 state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
6530 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
6531 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
6533 IncUInt64(&vp->stats.hdr_loads);
6534 now = FT_ApproxTime();
6538 V_attachFlags(vp) |= VOL_HDR_LOADED;
6539 vp->stats.last_hdr_load = now;
6541 VChangeState_r(vp, state_save);
6543 #else /* AFS_DEMAND_ATTACH_FS */
6545 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
6546 IncUInt64(&VStats.hdr_loads);
6548 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
6549 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
6552 #endif /* AFS_DEMAND_ATTACH_FS */
6554 /* maintain (nUsers==0) => header in LRU invariant */
6555 FreeVolumeHeader(vp);
6560 * release a header cache entry back into the LRU list.
6562 * @param[in] hd pointer to volume header cache object
6564 * @pre VOL_LOCK held.
6566 * @post header cache object appended onto end of LRU list.
6568 * @note only applicable to fileServer program type.
6570 * @note used to place a header cache entry back into the
6571 * LRU pool without invalidating it as a cache entry.
6573 * @internal volume package internal use only.
6576 ReleaseVolumeHeader(register struct volHeader *hd)
6578 if (programType != fileServer)
6580 if (!hd || queue_IsOnQueue(hd)) /* no header, or header already released */
6582 queue_Append(&volume_hdr_LRU, hd);
6583 #ifdef AFS_DEMAND_ATTACH_FS
6585 V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
6588 volume_hdr_LRU.stats.free++;
6589 volume_hdr_LRU.stats.used--;
6593 * free/invalidate a volume header cache entry.
6595 * @param[in] vp pointer to volume object
6597 * @pre VOL_LOCK is held.
6599 * @post For fileserver, header cache entry is returned to LRU, and it is
6600 * invalidated as a cache entry. For volume utilities, the header
6601 * cache entry is freed.
6603 * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
6604 * whenever it is necessary to invalidate the header cache entry.
6606 * @see ReleaseVolumeHeader
6608 * @internal volume package internal use only.
6611 FreeVolumeHeader(register Volume * vp)
6613 register struct volHeader *hd = vp->header;
6616 if (programType == fileServer) {
6617 ReleaseVolumeHeader(hd);
6622 #ifdef AFS_DEMAND_ATTACH_FS
6623 V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
6625 volume_hdr_LRU.stats.attached--;
6630 /***************************************************/
6631 /* Volume Hash Table routines */
6632 /***************************************************/
6635 * set size of volume object hash table.
6637 * @param[in] logsize log(2) of desired hash table size
6639 * @return operation status
6641 * @retval -1 failure
6643 * @pre MUST be called prior to VInitVolumePackage
6645 * @post Volume Hash Table will have 2^logsize buckets
6648 VSetVolHashSize(int logsize)
6650 /* 64 to 16384 hash buckets seems like a reasonable range */
6651 if ((logsize < 6 ) || (logsize > 14)) {
6656 VolumeHashTable.Size = 1 << logsize;
6657 VolumeHashTable.Mask = VolumeHashTable.Size - 1;
6659 /* we can't yet support runtime modification of this
6660 * parameter. we'll need a configuration rwlock to
6661 * make runtime modification feasible.... */
6668 * initialize dynamic data structures for volume hash table.
6670 * @post hash table is allocated, and fields are initialized.
6672 * @internal volume package internal use only.
6675 VInitVolumeHash(void)
6679 VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
6680 sizeof(VolumeHashChainHead));
6681 assert(VolumeHashTable.Table != NULL);
6683 for (i=0; i < VolumeHashTable.Size; i++) {
6684 queue_Init(&VolumeHashTable.Table[i]);
6685 #ifdef AFS_DEMAND_ATTACH_FS
6686 assert(pthread_cond_init(&VolumeHashTable.Table[i].chain_busy_cv, NULL) == 0);
6687 #endif /* AFS_DEMAND_ATTACH_FS */
6692 * add a volume object to the hash table.
6694 * @param[in] vp pointer to volume object
6695 * @param[in] hashid hash of volume id
6697 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
6700 * @post volume is added to hash chain.
6702 * @internal volume package internal use only.
6704 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
6705 * asynchronous hash chain reordering to finish.
6708 AddVolumeToHashTable(register Volume * vp, int hashid)
6710 VolumeHashChainHead * head;
6712 if (queue_IsOnQueue(vp))
6715 head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
6717 #ifdef AFS_DEMAND_ATTACH_FS
6718 /* wait for the hash chain to become available */
6721 V_attachFlags(vp) |= VOL_IN_HASH;
6722 vp->chainCacheCheck = ++head->cacheCheck;
6723 #endif /* AFS_DEMAND_ATTACH_FS */
6726 vp->hashid = hashid;
6727 queue_Append(head, vp);
6728 vp->vnodeHashOffset = VolumeHashOffset_r();
6732 * delete a volume object from the hash table.
6734 * @param[in] vp pointer to volume object
6736 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
6739 * @post volume is removed from hash chain.
6741 * @internal volume package internal use only.
6743 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
6744 * asynchronous hash chain reordering to finish.
6747 DeleteVolumeFromHashTable(register Volume * vp)
6749 VolumeHashChainHead * head;
6751 if (!queue_IsOnQueue(vp))
6754 head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
6756 #ifdef AFS_DEMAND_ATTACH_FS
6757 /* wait for the hash chain to become available */
6760 V_attachFlags(vp) &= ~(VOL_IN_HASH);
6762 #endif /* AFS_DEMAND_ATTACH_FS */
6766 /* do NOT reset hashid to zero, as the online
6767 * salvager package may need to know the volume id
6768 * after the volume is removed from the hash */
6772 * lookup a volume object in the hash table given a volume id.
6774 * @param[out] ec error code return
6775 * @param[in] volumeId volume id
6776 * @param[in] hint volume object which we believe could be the correct
6779 * @return volume object pointer
6780 * @retval NULL no such volume id is registered with the hash table.
6782 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
6785 * @post volume object with the given id is returned. volume object and
6786 * hash chain access statistics are updated. hash chain may have
6789 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
6790 * asynchronous hash chain reordering operation to finish, or
6791 * in order for us to perform an asynchronous chain reordering.
6793 * @note Hash chain reorderings occur when the access count for the
6794 * volume object being looked up exceeds the sum of the previous
6795 * node's (the node ahead of it in the hash chain linked list)
6796 * access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
6798 * @note For DAFS, the hint parameter allows us to short-circuit if the
6799 * cacheCheck fields match between the hash chain head and the
6800 * hint volume object.
6803 VLookupVolume_r(Error * ec, VolId volumeId, Volume * hint)
6805 register int looks = 0;
6807 #ifdef AFS_DEMAND_ATTACH_FS
6810 VolumeHashChainHead * head;
6813 head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
6815 #ifdef AFS_DEMAND_ATTACH_FS
6816 /* wait for the hash chain to become available */
6819 /* check to see if we can short circuit without walking the hash chain */
6820 if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
6821 IncUInt64(&hint->stats.hash_short_circuits);
6824 #endif /* AFS_DEMAND_ATTACH_FS */
6826 /* someday we need to either do per-chain locks, RWlocks,
6827 * or both for volhash access.
6828 * (and move to a data structure with better cache locality) */
6830 /* search the chain for this volume id */
6831 for(queue_Scan(head, vp, np, Volume)) {
6833 if ((vp->hashid == volumeId)) {
6838 if (queue_IsEnd(head, vp)) {
6842 #ifdef AFS_DEMAND_ATTACH_FS
6843 /* update hash chain statistics */
6846 FillInt64(lks, 0, looks);
6847 AddUInt64(head->looks, lks, &head->looks);
6848 AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
6849 IncUInt64(&head->gets);
6854 IncUInt64(&vp->stats.hash_lookups);
6856 /* for demand attach fileserver, we permit occasional hash chain reordering
6857 * so that frequently looked up volumes move towards the head of the chain */
6858 pp = queue_Prev(vp, Volume);
6859 if (!queue_IsEnd(head, pp)) {
6860 FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
6861 AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
6862 if (GEInt64(vp->stats.hash_lookups, thresh)) {
6863 VReorderHash_r(head, pp, vp);
6867 /* update the short-circuit cache check */
6868 vp->chainCacheCheck = head->cacheCheck;
6870 #endif /* AFS_DEMAND_ATTACH_FS */
6875 #ifdef AFS_DEMAND_ATTACH_FS
6876 /* perform volume hash chain reordering.
6878 * advance a subchain beginning at vp ahead of
6879 * the adjacent subchain ending at pp */
6881 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
6883 Volume *tp, *np, *lp;
6884 afs_uint64 move_thresh;
6886 /* this should never be called if the chain is already busy, so
6887 * no need to wait for other exclusive chain ops to finish */
6889 /* this is a rather heavy set of operations,
6890 * so let's set the chain busy flag and drop
6892 VHashBeginExclusive_r(head);
6895 /* scan forward in the chain from vp looking for the last element
6896 * in the chain we want to advance */
6897 FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
6898 AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
6899 for(queue_ScanFrom(head, vp, tp, np, Volume)) {
6900 if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
6904 lp = queue_Prev(tp, Volume);
6906 /* scan backwards from pp to determine where to splice and
6907 * insert the subchain we're advancing */
6908 for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
6909 if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
6913 tp = queue_Next(tp, Volume);
6915 /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
6916 queue_MoveChainBefore(tp,vp,lp);
6919 IncUInt64(&VStats.hash_reorders);
6921 IncUInt64(&head->reorders);
6923 /* wake up any threads waiting for the hash chain */
6924 VHashEndExclusive_r(head);
6928 /* demand-attach fs volume hash
6929 * asynchronous exclusive operations */
6932 * begin an asynchronous exclusive operation on a volume hash chain.
6934 * @param[in] head pointer to volume hash chain head object
6936 * @pre VOL_LOCK held. hash chain is quiescent.
6938 * @post hash chain marked busy.
6940 * @note this interface is used in conjunction with VHashEndExclusive_r and
6941 * VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
6942 * volume hash chain. Its main use case is hash chain reordering, which
6943 * has the potential to be a highly latent operation.
6945 * @see VHashEndExclusive_r
6950 * @internal volume package internal use only.
6953 VHashBeginExclusive_r(VolumeHashChainHead * head)
6955 assert(head->busy == 0);
6960 * relinquish exclusive ownership of a volume hash chain.
6962 * @param[in] head pointer to volume hash chain head object
6964 * @pre VOL_LOCK held. thread owns the hash chain exclusively.
6966 * @post hash chain is marked quiescent. threads awaiting use of
6967 * chain are awakened.
6969 * @see VHashBeginExclusive_r
6974 * @internal volume package internal use only.
6977 VHashEndExclusive_r(VolumeHashChainHead * head)
6981 assert(pthread_cond_broadcast(&head->chain_busy_cv) == 0);
6985 * wait for all asynchronous operations on a hash chain to complete.
6987 * @param[in] head pointer to volume hash chain head object
6989 * @pre VOL_LOCK held.
6991 * @post hash chain object is quiescent.
6993 * @see VHashBeginExclusive_r
6994 * @see VHashEndExclusive_r
6998 * @note This interface should be called before any attempt to
6999 * traverse the hash chain. It is permissible for a thread
7000 * to gain exclusive access to the chain, and then perform
7001 * latent operations on the chain asynchronously wrt the
7004 * @warning if waiting is necessary, VOL_LOCK is dropped
7006 * @internal volume package internal use only.
7009 VHashWait_r(VolumeHashChainHead * head)
7011 while (head->busy) {
7012 VOL_CV_WAIT(&head->chain_busy_cv);
7015 #endif /* AFS_DEMAND_ATTACH_FS */
7018 /***************************************************/
7019 /* Volume by Partition List routines */
7020 /***************************************************/
7023 * demand attach fileserver adds a
7024 * linked list of volumes to each
7025 * partition object, thus allowing
7026 * for quick enumeration of all
7027 * volumes on a partition
7030 #ifdef AFS_DEMAND_ATTACH_FS
7032 * add a volume to its disk partition VByPList.
7034 * @param[in] vp pointer to volume object
7036 * @pre either the disk partition VByPList is owned exclusively
7037 * by the calling thread, or the list is quiescent and
7040 * @post volume is added to disk partition VByPList
7044 * @warning it is the caller's responsibility to ensure list
7047 * @see VVByPListWait_r
7048 * @see VVByPListBeginExclusive_r
7049 * @see VVByPListEndExclusive_r
7051 * @internal volume package internal use only.
7054 AddVolumeToVByPList_r(Volume * vp)
7056 if (queue_IsNotOnQueue(&vp->vol_list)) {
7057 queue_Append(&vp->partition->vol_list, &vp->vol_list);
7058 V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
7059 vp->partition->vol_list.len++;
7064 * delete a volume from its disk partition VByPList.
7066 * @param[in] vp pointer to volume object
7068 * @pre either the disk partition VByPList is owned exclusively
7069 * by the calling thread, or the list is quiescent and
7072 * @post volume is removed from the disk partition VByPList
7076 * @warning it is the caller's responsibility to ensure list
7079 * @see VVByPListWait_r
7080 * @see VVByPListBeginExclusive_r
7081 * @see VVByPListEndExclusive_r
7083 * @internal volume package internal use only.
7086 DeleteVolumeFromVByPList_r(Volume * vp)
7088 if (queue_IsOnQueue(&vp->vol_list)) {
7089 queue_Remove(&vp->vol_list);
7090 V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
7091 vp->partition->vol_list.len--;
7096 * begin an asynchronous exclusive operation on a VByPList.
7098 * @param[in] dp pointer to disk partition object
7100 * @pre VOL_LOCK held. VByPList is quiescent.
7102 * @post VByPList marked busy.
7104 * @note this interface is used in conjunction with VVByPListEndExclusive_r and
7105 * VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
7108 * @see VVByPListEndExclusive_r
7109 * @see VVByPListWait_r
7113 * @internal volume package internal use only.
7115 /* take exclusive control over the list */
7117 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
7119 assert(dp->vol_list.busy == 0);
7120 dp->vol_list.busy = 1;
7124 * relinquish exclusive ownership of a VByPList.
7126 * @param[in] dp pointer to disk partition object
7128 * @pre VOL_LOCK held. thread owns the VByPList exclusively.
7130 * @post VByPList is marked quiescent. threads awaiting use of
7131 * the list are awakened.
7133 * @see VVByPListBeginExclusive_r
7134 * @see VVByPListWait_r
7138 * @internal volume package internal use only.
7141 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
7143 assert(dp->vol_list.busy);
7144 dp->vol_list.busy = 0;
7145 assert(pthread_cond_broadcast(&dp->vol_list.cv) == 0);
7149 * wait for all asynchronous operations on a VByPList to complete.
7151 * @param[in] dp pointer to disk partition object
7153 * @pre VOL_LOCK is held.
7155 * @post disk partition's VByP list is quiescent
7159 * @note This interface should be called before any attempt to
7160 * traverse the VByPList. It is permissible for a thread
7161 * to gain exclusive access to the list, and then perform
7162 * latent operations on the list asynchronously wrt the
7165 * @warning if waiting is necessary, VOL_LOCK is dropped
7167 * @see VVByPListEndExclusive_r
7168 * @see VVByPListBeginExclusive_r
7170 * @internal volume package internal use only.
7173 VVByPListWait_r(struct DiskPartition64 * dp)
7175 while (dp->vol_list.busy) {
7176 VOL_CV_WAIT(&dp->vol_list.cv);
7179 #endif /* AFS_DEMAND_ATTACH_FS */
7181 /***************************************************/
7182 /* Volume Cache Statistics routines */
7183 /***************************************************/
7186 VPrintCacheStats_r(void)
7188 afs_uint32 get_hi, get_lo, load_hi, load_lo;
7189 register struct VnodeClassInfo *vcp;
7190 vcp = &VnodeClassInfo[vLarge];
7191 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);
7192 vcp = &VnodeClassInfo[vSmall];
7193 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);
7194 SplitInt64(VStats.hdr_gets, get_hi, get_lo);
7195 SplitInt64(VStats.hdr_loads, load_hi, load_lo);
7196 Log("Volume header cache, %d entries, %d gets, %d replacements\n",
7197 VStats.hdr_cache_size, get_lo, load_lo);
7201 VPrintCacheStats(void)
7204 VPrintCacheStats_r();
7208 #ifdef AFS_DEMAND_ATTACH_FS
7210 UInt64ToDouble(afs_uint64 * x)
7212 static double c32 = 4.0 * 1.073741824 * 1000000000.0;
7214 SplitInt64(*x, h, l);
7215 return (((double)h) * c32) + ((double) l);
7219 DoubleToPrintable(double x, char * buf, int len)
7221 static double billion = 1000000000.0;
7224 y[0] = (afs_uint32) (x / (billion * billion));
7225 y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
7226 y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
7229 snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
7231 snprintf(buf, len, "%d%09d", y[1], y[2]);
7233 snprintf(buf, len, "%d", y[2]);
7239 struct VLRUExtStatsEntry {
7243 struct VLRUExtStats {
7249 } queue_info[VLRU_QUEUE_INVALID];
7250 struct VLRUExtStatsEntry * vec;
7254 * add a 256-entry fudge factor onto the vector in case state changes
7255 * out from under us.
7257 #define VLRU_EXT_STATS_VEC_LEN_FUDGE 256
7260 * collect extended statistics for the VLRU subsystem.
7262 * @param[out] stats pointer to stats structure to be populated
7263 * @param[in] nvols number of volumes currently known to exist
7265 * @pre VOL_LOCK held
7267 * @post stats->vec allocated and populated
7269 * @return operation status
7274 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
7276 afs_uint32 cur, idx, len;
7277 struct rx_queue * qp, * nqp;
7279 struct VLRUExtStatsEntry * vec;
7281 len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
7282 vec = stats->vec = calloc(len,
7283 sizeof(struct VLRUExtStatsEntry));
7289 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
7290 VLRU_Wait_r(&volume_LRU.q[idx]);
7291 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7294 stats->queue_info[idx].start = cur;
7296 for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7298 /* out of space in vec */
7301 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7302 vec[cur].volid = vp->hashid;
7306 stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
7309 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7317 #define ENUMTOSTRING(en) #en
7318 #define ENUMCASE(en) \
7320 return ENUMTOSTRING(en); \
7324 vlru_idx_to_string(int idx)
7327 ENUMCASE(VLRU_QUEUE_NEW);
7328 ENUMCASE(VLRU_QUEUE_MID);
7329 ENUMCASE(VLRU_QUEUE_OLD);
7330 ENUMCASE(VLRU_QUEUE_CANDIDATE);
7331 ENUMCASE(VLRU_QUEUE_HELD);
7332 ENUMCASE(VLRU_QUEUE_INVALID);
7334 return "**UNKNOWN**";
7339 VPrintExtendedCacheStats_r(int flags)
7342 afs_uint32 vol_sum = 0;
7349 struct stats looks, gets, reorders, len;
7350 struct stats ch_looks, ch_gets, ch_reorders;
7352 VolumeHashChainHead *head;
7354 struct VLRUExtStats vlru_stats;
7356 /* zero out stats */
7357 memset(&looks, 0, sizeof(struct stats));
7358 memset(&gets, 0, sizeof(struct stats));
7359 memset(&reorders, 0, sizeof(struct stats));
7360 memset(&len, 0, sizeof(struct stats));
7361 memset(&ch_looks, 0, sizeof(struct stats));
7362 memset(&ch_gets, 0, sizeof(struct stats));
7363 memset(&ch_reorders, 0, sizeof(struct stats));
7365 for (i = 0; i < VolumeHashTable.Size; i++) {
7366 head = &VolumeHashTable.Table[i];
7369 VHashBeginExclusive_r(head);
7372 ch_looks.sum = UInt64ToDouble(&head->looks);
7373 ch_gets.sum = UInt64ToDouble(&head->gets);
7374 ch_reorders.sum = UInt64ToDouble(&head->reorders);
7376 /* update global statistics */
7378 looks.sum += ch_looks.sum;
7379 gets.sum += ch_gets.sum;
7380 reorders.sum += ch_reorders.sum;
7381 len.sum += (double)head->len;
7382 vol_sum += head->len;
7385 len.min = (double) head->len;
7386 len.max = (double) head->len;
7387 looks.min = ch_looks.sum;
7388 looks.max = ch_looks.sum;
7389 gets.min = ch_gets.sum;
7390 gets.max = ch_gets.sum;
7391 reorders.min = ch_reorders.sum;
7392 reorders.max = ch_reorders.sum;
7394 if (((double)head->len) < len.min)
7395 len.min = (double) head->len;
7396 if (((double)head->len) > len.max)
7397 len.max = (double) head->len;
7398 if (ch_looks.sum < looks.min)
7399 looks.min = ch_looks.sum;
7400 else if (ch_looks.sum > looks.max)
7401 looks.max = ch_looks.sum;
7402 if (ch_gets.sum < gets.min)
7403 gets.min = ch_gets.sum;
7404 else if (ch_gets.sum > gets.max)
7405 gets.max = ch_gets.sum;
7406 if (ch_reorders.sum < reorders.min)
7407 reorders.min = ch_reorders.sum;
7408 else if (ch_reorders.sum > reorders.max)
7409 reorders.max = ch_reorders.sum;
7413 if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
7414 /* compute detailed per-chain stats */
7415 struct stats hdr_loads, hdr_gets;
7416 double v_looks, v_loads, v_gets;
7418 /* initialize stats with data from first element in chain */
7419 vp = queue_First(head, Volume);
7420 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
7421 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
7422 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
7423 ch_gets.min = ch_gets.max = v_looks;
7424 hdr_loads.min = hdr_loads.max = v_loads;
7425 hdr_gets.min = hdr_gets.max = v_gets;
7426 hdr_loads.sum = hdr_gets.sum = 0;
7428 vp = queue_Next(vp, Volume);
7430 /* pull in stats from remaining elements in chain */
7431 for (queue_ScanFrom(head, vp, vp, np, Volume)) {
7432 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
7433 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
7434 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
7436 hdr_loads.sum += v_loads;
7437 hdr_gets.sum += v_gets;
7439 if (v_looks < ch_gets.min)
7440 ch_gets.min = v_looks;
7441 else if (v_looks > ch_gets.max)
7442 ch_gets.max = v_looks;
7444 if (v_loads < hdr_loads.min)
7445 hdr_loads.min = v_loads;
7446 else if (v_loads > hdr_loads.max)
7447 hdr_loads.max = v_loads;
7449 if (v_gets < hdr_gets.min)
7450 hdr_gets.min = v_gets;
7451 else if (v_gets > hdr_gets.max)
7452 hdr_gets.max = v_gets;
7455 /* compute per-chain averages */
7456 ch_gets.avg = ch_gets.sum / ((double)head->len);
7457 hdr_loads.avg = hdr_loads.sum / ((double)head->len);
7458 hdr_gets.avg = hdr_gets.sum / ((double)head->len);
7460 /* dump per-chain stats */
7461 Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
7463 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
7464 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
7465 Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
7466 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
7467 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
7468 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
7469 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
7470 Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
7471 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
7472 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
7473 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
7474 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
7475 Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
7476 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
7477 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
7478 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
7479 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
7480 } else if (flags & VOL_STATS_PER_CHAIN) {
7481 /* dump simple per-chain stats */
7482 Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
7484 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
7485 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
7486 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
7490 VHashEndExclusive_r(head);
7495 /* compute global averages */
7496 len.avg = len.sum / ((double)VolumeHashTable.Size);
7497 looks.avg = looks.sum / ((double)VolumeHashTable.Size);
7498 gets.avg = gets.sum / ((double)VolumeHashTable.Size);
7499 reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
7501 /* dump global stats */
7502 Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
7503 Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
7504 DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
7505 DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
7506 DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
7507 DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
7508 Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
7509 DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
7510 DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
7511 DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
7512 DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
7513 Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
7514 DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
7515 DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
7516 DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
7517 DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
7518 Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
7519 DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
7520 DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
7521 DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
7522 DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
7524 /* print extended disk related statistics */
7526 struct DiskPartition64 * diskP;
7527 afs_uint32 vol_count[VOLMAXPARTS+1];
7528 byte part_exists[VOLMAXPARTS+1];
7532 memset(vol_count, 0, sizeof(vol_count));
7533 memset(part_exists, 0, sizeof(part_exists));
7537 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
7539 vol_count[id] = diskP->vol_list.len;
7540 part_exists[id] = 1;
7544 for (i = 0; i <= VOLMAXPARTS; i++) {
7545 if (part_exists[i]) {
7546 /* XXX while this is currently safe, it is a violation
7547 * of the VGetPartitionById_r interface contract. */
7548 diskP = VGetPartitionById_r(i, 0);
7550 Log("Partition %s has %d online volumes\n",
7551 VPartitionPath(diskP), diskP->vol_list.len);
7558 /* print extended VLRU statistics */
7559 if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
7560 afs_uint32 idx, cur, lpos;
7564 Log("VLRU State Dump:\n\n");
7566 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
7567 Log("\t%s:\n", vlru_idx_to_string(idx));
7570 for (cur = vlru_stats.queue_info[idx].start;
7571 cur < vlru_stats.queue_info[idx].len;
7573 line[lpos++] = vlru_stats.vec[cur].volid;
7575 Log("\t\t%u, %u, %u, %u, %u,\n",
7576 line[0], line[1], line[2], line[3], line[4]);
7585 Log("\t\t%u, %u, %u, %u, %u\n",
7586 line[0], line[1], line[2], line[3], line[4]);
7591 free(vlru_stats.vec);
7598 VPrintExtendedCacheStats(int flags)
7601 VPrintExtendedCacheStats_r(flags);
7604 #endif /* AFS_DEMAND_ATTACH_FS */