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>
28 #include <afs/afsint.h>
31 #include <sys/param.h>
32 #if !defined(AFS_SGI_ENV)
35 #else /* AFS_OSF_ENV */
36 #ifdef AFS_VFSINCL_ENV
39 #include <sys/fs/ufs_fs.h>
41 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
42 #include <ufs/ufs/dinode.h>
43 #include <ufs/ffs/fs.h>
48 #else /* AFS_VFSINCL_ENV */
49 #if !defined(AFS_AIX_ENV) && !defined(AFS_LINUX20_ENV) && !defined(AFS_XBSD_ENV)
52 #endif /* AFS_VFSINCL_ENV */
53 #endif /* AFS_OSF_ENV */
54 #endif /* AFS_SGI_ENV */
55 #endif /* AFS_NT40_ENV */
73 #if defined(AFS_SUN_ENV) || defined(AFS_SUN5_ENV)
75 #include <sys/mnttab.h>
76 #include <sys/mntent.h>
82 #if defined(AFS_SGI_ENV)
87 #ifndef AFS_LINUX20_ENV
88 #include <fstab.h> /* Need to find in libc 5, present in libc 6 */
91 #endif /* AFS_SGI_ENV */
93 #endif /* AFS_HPUX_ENV */
97 #include <netinet/in.h>
101 #include <sys/time.h>
102 #endif /* ITIMER_REAL */
103 #endif /* AFS_NT40_ENV */
104 #if defined(AFS_SUN5_ENV) || defined(AFS_NT40_ENV) || defined(AFS_LINUX20_ENV)
111 #include <afs/errors.h>
114 #include <afs/afssyscalls.h>
116 #include <afs/afsutil.h>
120 #include "daemon_com.h"
122 #include "salvsync.h"
125 #include "partition.h"
126 #include "volume_inline.h"
127 #ifdef AFS_PTHREAD_ENV
129 #else /* AFS_PTHREAD_ENV */
130 #include "afs/assert.h"
131 #endif /* AFS_PTHREAD_ENV */
138 #if !defined(offsetof)
143 #define afs_stat stat64
144 #define afs_fstat fstat64
145 #define afs_open open64
146 #else /* !O_LARGEFILE */
147 #define afs_stat stat
148 #define afs_fstat fstat
149 #define afs_open open
150 #endif /* !O_LARGEFILE */
152 #ifdef AFS_PTHREAD_ENV
153 pthread_mutex_t vol_glock_mutex;
154 pthread_mutex_t vol_trans_mutex;
155 pthread_cond_t vol_put_volume_cond;
156 pthread_cond_t vol_sleep_cond;
157 int vol_attach_threads = 1;
158 #endif /* AFS_PTHREAD_ENV */
160 #ifdef AFS_DEMAND_ATTACH_FS
161 pthread_mutex_t vol_salvsync_mutex;
162 #endif /* AFS_DEMAND_ATTACH_FS */
165 extern void *calloc(), *realloc();
168 /*@printflike@*/ extern void Log(const char *format, ...);
170 /* Forward declarations */
171 static Volume *attach2(Error * ec, VolId vid, char *path,
172 register struct VolumeHeader *header,
173 struct DiskPartition64 *partp, Volume * vp,
174 int isbusy, int mode);
175 static void ReallyFreeVolume(Volume * vp);
176 #ifdef AFS_DEMAND_ATTACH_FS
177 static void FreeVolume(Volume * vp);
178 #else /* !AFS_DEMAND_ATTACH_FS */
179 #define FreeVolume(vp) ReallyFreeVolume(vp)
180 static void VScanUpdateList(void);
181 #endif /* !AFS_DEMAND_ATTACH_FS */
182 static void VInitVolumeHeaderCache(afs_uint32 howMany);
183 static int GetVolumeHeader(register Volume * vp);
184 static void ReleaseVolumeHeader(register struct volHeader *hd);
185 static void FreeVolumeHeader(register Volume * vp);
186 static void AddVolumeToHashTable(register Volume * vp, int hashid);
187 static void DeleteVolumeFromHashTable(register Volume * vp);
189 static int VHold(Volume * vp);
191 static int VHold_r(Volume * vp);
192 static void VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class);
193 static void VReleaseVolumeHandles_r(Volume * vp);
194 static void VCloseVolumeHandles_r(Volume * vp);
195 static void LoadVolumeHeader(Error * ec, Volume * vp);
196 static int VCheckOffline(register Volume * vp);
197 static int VCheckDetach(register Volume * vp);
198 static Volume * GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint, int flags);
200 static int VolumeExternalName_r(VolumeId volumeId, char * name, size_t len);
203 int LogLevel; /* Vice loglevel--not defined as extern so that it will be
204 * defined when not linked with vice, XXXX */
205 ProgramType programType; /* The type of program using the package */
207 /* extended volume package statistics */
210 #ifdef VOL_LOCK_DEBUG
211 pthread_t vol_glock_holder = 0;
215 #define VOLUME_BITMAP_GROWSIZE 16 /* bytes, => 128vnodes */
216 /* Must be a multiple of 4 (1 word) !! */
218 /* this parameter needs to be tunable at runtime.
219 * 128 was really inadequate for largish servers -- at 16384 volumes this
220 * puts average chain length at 128, thus an average 65 deref's to find a volptr.
221 * talk about bad spatial locality...
223 * an AVL or splay tree might work a lot better, but we'll just increase
224 * the default hash table size for now
226 #define DEFAULT_VOLUME_HASH_SIZE 256 /* Must be a power of 2!! */
227 #define DEFAULT_VOLUME_HASH_MASK (DEFAULT_VOLUME_HASH_SIZE-1)
228 #define VOLUME_HASH(volumeId) (volumeId&(VolumeHashTable.Mask))
231 * turn volume hash chains into partially ordered lists.
232 * when the threshold is exceeded between two adjacent elements,
233 * perform a chain rebalancing operation.
235 * keep the threshold high in order to keep cache line invalidates
236 * low "enough" on SMPs
238 #define VOLUME_HASH_REORDER_THRESHOLD 200
241 * when possible, don't just reorder single elements, but reorder
242 * entire chains of elements at once. a chain of elements that
243 * exceed the element previous to the pivot by at least CHAIN_THRESH
244 * accesses are moved in front of the chain whose elements have at
245 * least CHAIN_THRESH less accesses than the pivot element
247 #define VOLUME_HASH_REORDER_CHAIN_THRESH (VOLUME_HASH_REORDER_THRESHOLD / 2)
249 #include "rx/rx_queue.h"
252 VolumeHashTable_t VolumeHashTable = {
253 DEFAULT_VOLUME_HASH_SIZE,
254 DEFAULT_VOLUME_HASH_MASK,
259 static void VInitVolumeHash(void);
263 /* This macro is used where an ffs() call does not exist. Was in util/ffs.c */
267 afs_int32 ffs_tmp = x;
271 for (ffs_i = 1;; ffs_i++) {
278 #endif /* !AFS_HAVE_FFS */
280 #ifdef AFS_PTHREAD_ENV
281 typedef struct diskpartition_queue_t {
282 struct rx_queue queue;
283 struct DiskPartition64 * diskP;
284 } diskpartition_queue_t;
285 typedef struct vinitvolumepackage_thread_t {
286 struct rx_queue queue;
287 pthread_cond_t thread_done_cv;
288 int n_threads_complete;
289 } vinitvolumepackage_thread_t;
290 static void * VInitVolumePackageThread(void * args);
291 #endif /* AFS_PTHREAD_ENV */
293 static int VAttachVolumesByPartition(struct DiskPartition64 *diskP,
294 int * nAttached, int * nUnattached);
297 #ifdef AFS_DEMAND_ATTACH_FS
298 /* demand attach fileserver extensions */
301 * in the future we will support serialization of VLRU state into the fs_state
304 * these structures are the beginning of that effort
306 struct VLRU_DiskHeader {
307 struct versionStamp stamp; /* magic and structure version number */
308 afs_uint32 mtime; /* time of dump to disk */
309 afs_uint32 num_records; /* number of VLRU_DiskEntry records */
312 struct VLRU_DiskEntry {
313 afs_uint32 vid; /* volume ID */
314 afs_uint32 idx; /* generation */
315 afs_uint32 last_get; /* timestamp of last get */
318 struct VLRU_StartupQueue {
319 struct VLRU_DiskEntry * entry;
324 typedef struct vshutdown_thread_t {
326 pthread_mutex_t lock;
328 pthread_cond_t master_cv;
330 int n_threads_complete;
332 int schedule_version;
335 byte n_parts_done_pass;
336 byte part_thread_target[VOLMAXPARTS+1];
337 byte part_done_pass[VOLMAXPARTS+1];
338 struct rx_queue * part_pass_head[VOLMAXPARTS+1];
339 int stats[4][VOLMAXPARTS+1];
340 } vshutdown_thread_t;
341 static void * VShutdownThread(void * args);
344 static Volume * VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode);
345 static int VCheckFree(Volume * vp);
348 static void AddVolumeToVByPList_r(Volume * vp);
349 static void DeleteVolumeFromVByPList_r(Volume * vp);
350 static void VVByPListBeginExclusive_r(struct DiskPartition64 * dp);
351 static void VVByPListEndExclusive_r(struct DiskPartition64 * dp);
352 static void VVByPListWait_r(struct DiskPartition64 * dp);
354 /* online salvager */
355 static int VCheckSalvage(register Volume * vp);
356 static int VUpdateSalvagePriority_r(Volume * vp);
357 static int VScheduleSalvage_r(Volume * vp);
358 static int VCancelSalvage_r(Volume * vp, int reason);
360 /* Volume hash table */
361 static void VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp);
362 static void VHashBeginExclusive_r(VolumeHashChainHead * head);
363 static void VHashEndExclusive_r(VolumeHashChainHead * head);
364 static void VHashWait_r(VolumeHashChainHead * head);
367 static int ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass);
368 static int ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
369 struct rx_queue ** idx);
370 static void ShutdownController(vshutdown_thread_t * params);
371 static void ShutdownCreateSchedule(vshutdown_thread_t * params);
374 static void VLRU_ComputeConstants(void);
375 static void VInitVLRU(void);
376 static void VLRU_Init_Node_r(volatile Volume * vp);
377 static void VLRU_Add_r(volatile Volume * vp);
378 static void VLRU_Delete_r(volatile Volume * vp);
379 static void VLRU_UpdateAccess_r(volatile Volume * vp);
380 static void * VLRU_ScannerThread(void * args);
381 static void VLRU_Scan_r(int idx);
382 static void VLRU_Promote_r(int idx);
383 static void VLRU_Demote_r(int idx);
384 static void VLRU_SwitchQueues(volatile Volume * vp, int new_idx, int append);
387 static int VCheckSoftDetach(volatile Volume * vp, afs_uint32 thresh);
388 static int VCheckSoftDetachCandidate(volatile Volume * vp, afs_uint32 thresh);
389 static int VSoftDetachVolume_r(volatile Volume * vp, afs_uint32 thresh);
392 pthread_key_t VThread_key;
393 VThreadOptions_t VThread_defaults = {
394 0 /**< allow salvsync */
396 #endif /* AFS_DEMAND_ATTACH_FS */
399 struct Lock vol_listLock; /* Lock obtained when listing volumes:
400 * prevents a volume from being missed
401 * if the volume is attached during a
405 static int TimeZoneCorrection; /* Number of seconds west of GMT */
407 /* Common message used when the volume goes off line */
408 char *VSalvageMessage =
409 "Files in this volume are currently unavailable; call operations";
411 int VInit; /* 0 - uninitialized,
412 * 1 - initialized but not all volumes have been attached,
413 * 2 - initialized and all volumes have been attached,
414 * 3 - initialized, all volumes have been attached, and
415 * VConnectFS() has completed. */
418 bit32 VolumeCacheCheck; /* Incremented everytime a volume goes on line--
419 * used to stamp volume headers and in-core
420 * vnodes. When the volume goes on-line the
421 * vnode will be invalidated
422 * access only with VOL_LOCK held */
427 /***************************************************/
428 /* Startup routines */
429 /***************************************************/
432 VInitVolumePackage(ProgramType pt, afs_uint32 nLargeVnodes, afs_uint32 nSmallVnodes,
433 int connect, afs_uint32 volcache)
435 int errors = 0; /* Number of errors while finding vice partitions. */
441 memset(&VStats, 0, sizeof(VStats));
442 VStats.hdr_cache_size = 200;
444 VInitPartitionPackage();
446 #ifdef AFS_DEMAND_ATTACH_FS
447 if (programType == fileServer) {
450 VLRU_SetOptions(VLRU_SET_ENABLED, 0);
452 assert(pthread_key_create(&VThread_key, NULL) == 0);
455 #ifdef AFS_PTHREAD_ENV
456 assert(pthread_mutex_init(&vol_glock_mutex, NULL) == 0);
457 assert(pthread_mutex_init(&vol_trans_mutex, NULL) == 0);
458 assert(pthread_cond_init(&vol_put_volume_cond, NULL) == 0);
459 assert(pthread_cond_init(&vol_sleep_cond, NULL) == 0);
460 #else /* AFS_PTHREAD_ENV */
462 #endif /* AFS_PTHREAD_ENV */
463 Lock_Init(&vol_listLock);
465 srandom(time(0)); /* For VGetVolumeInfo */
466 gettimeofday(&tv, &tz);
467 TimeZoneCorrection = tz.tz_minuteswest * 60;
469 #ifdef AFS_DEMAND_ATTACH_FS
470 assert(pthread_mutex_init(&vol_salvsync_mutex, NULL) == 0);
471 #endif /* AFS_DEMAND_ATTACH_FS */
473 /* Ok, we have done enough initialization that fileserver can
474 * start accepting calls, even though the volumes may not be
475 * available just yet.
479 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_SERVER)
480 if (programType == salvageServer) {
483 #endif /* AFS_DEMAND_ATTACH_FS */
484 #ifdef FSSYNC_BUILD_SERVER
485 if (programType == fileServer) {
489 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_CLIENT)
490 if (programType == fileServer) {
491 /* establish a connection to the salvager at this point */
492 assert(VConnectSALV() != 0);
494 #endif /* AFS_DEMAND_ATTACH_FS */
496 if (volcache > VStats.hdr_cache_size)
497 VStats.hdr_cache_size = volcache;
498 VInitVolumeHeaderCache(VStats.hdr_cache_size);
500 VInitVnodes(vLarge, nLargeVnodes);
501 VInitVnodes(vSmall, nSmallVnodes);
504 errors = VAttachPartitions();
508 if (programType == fileServer) {
509 struct DiskPartition64 *diskP;
510 #ifdef AFS_PTHREAD_ENV
511 struct vinitvolumepackage_thread_t params;
512 struct diskpartition_queue_t * dpq;
513 int i, threads, parts;
515 pthread_attr_t attrs;
517 assert(pthread_cond_init(¶ms.thread_done_cv,NULL) == 0);
519 params.n_threads_complete = 0;
521 /* create partition work queue */
522 for (parts=0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
523 dpq = (diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
526 queue_Append(¶ms,dpq);
529 threads = MIN(parts, vol_attach_threads);
532 /* spawn off a bunch of initialization threads */
533 assert(pthread_attr_init(&attrs) == 0);
534 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
536 Log("VInitVolumePackage: beginning parallel fileserver startup\n");
537 #ifdef AFS_DEMAND_ATTACH_FS
538 Log("VInitVolumePackage: using %d threads to pre-attach volumes on %d partitions\n",
540 #else /* AFS_DEMAND_ATTACH_FS */
541 Log("VInitVolumePackage: using %d threads to attach volumes on %d partitions\n",
543 #endif /* AFS_DEMAND_ATTACH_FS */
546 for (i=0; i < threads; i++) {
547 assert(pthread_create
548 (&tid, &attrs, &VInitVolumePackageThread,
552 while(params.n_threads_complete < threads) {
553 VOL_CV_WAIT(¶ms.thread_done_cv);
557 assert(pthread_attr_destroy(&attrs) == 0);
559 /* if we're only going to run one init thread, don't bother creating
561 Log("VInitVolumePackage: beginning single-threaded fileserver startup\n");
562 #ifdef AFS_DEMAND_ATTACH_FS
563 Log("VInitVolumePackage: using 1 thread to pre-attach volumes on %d partition(s)\n",
565 #else /* AFS_DEMAND_ATTACH_FS */
566 Log("VInitVolumePackage: using 1 thread to attach volumes on %d partition(s)\n",
568 #endif /* AFS_DEMAND_ATTACH_FS */
570 VInitVolumePackageThread(¶ms);
573 assert(pthread_cond_destroy(¶ms.thread_done_cv) == 0);
575 #else /* AFS_PTHREAD_ENV */
577 /* Attach all the volumes in this partition */
578 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
579 int nAttached = 0, nUnattached = 0;
580 assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
582 #endif /* AFS_PTHREAD_ENV */
585 VInit = 2; /* Initialized, and all volumes have been attached */
586 #ifdef FSSYNC_BUILD_CLIENT
587 if (programType == volumeUtility && connect) {
589 Log("Unable to connect to file server; will retry at need\n");
593 #ifdef AFS_DEMAND_ATTACH_FS
594 else if (programType == salvageServer) {
596 Log("Unable to connect to file server; aborted\n");
600 #endif /* AFS_DEMAND_ATTACH_FS */
601 #endif /* FSSYNC_BUILD_CLIENT */
605 #ifdef AFS_PTHREAD_ENV
607 VInitVolumePackageThread(void * args) {
608 int errors = 0; /* Number of errors while finding vice partitions. */
612 struct DiskPartition64 *diskP;
613 struct vinitvolumepackage_thread_t * params;
614 struct diskpartition_queue_t * dpq;
616 params = (vinitvolumepackage_thread_t *) args;
620 /* Attach all the volumes in this partition */
621 while (queue_IsNotEmpty(params)) {
622 int nAttached = 0, nUnattached = 0;
624 dpq = queue_First(params,diskpartition_queue_t);
630 assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
635 params->n_threads_complete++;
636 pthread_cond_signal(¶ms->thread_done_cv);
640 #endif /* AFS_PTHREAD_ENV */
643 * attach all volumes on a given disk partition
646 VAttachVolumesByPartition(struct DiskPartition64 *diskP, int * nAttached, int * nUnattached)
652 Log("Partition %s: attaching volumes\n", diskP->name);
653 dirp = opendir(VPartitionPath(diskP));
655 Log("opendir on Partition %s failed!\n", diskP->name);
659 while ((dp = readdir(dirp))) {
661 p = strrchr(dp->d_name, '.');
662 if (p != NULL && strcmp(p, VHDREXT) == 0) {
665 #ifdef AFS_DEMAND_ATTACH_FS
666 vp = VPreAttachVolumeByName(&error, diskP->name, dp->d_name);
667 #else /* AFS_DEMAND_ATTACH_FS */
668 vp = VAttachVolumeByName(&error, diskP->name, dp->d_name,
670 #endif /* AFS_DEMAND_ATTACH_FS */
671 (*(vp ? nAttached : nUnattached))++;
672 if (error == VOFFLINE)
673 Log("Volume %d stays offline (/vice/offline/%s exists)\n", VolumeNumber(dp->d_name), dp->d_name);
674 else if (LogLevel >= 5) {
675 Log("Partition %s: attached volume %d (%s)\n",
676 diskP->name, VolumeNumber(dp->d_name),
679 #if !defined(AFS_DEMAND_ATTACH_FS)
683 #endif /* AFS_DEMAND_ATTACH_FS */
687 Log("Partition %s: attached %d volumes; %d volumes not attached\n", diskP->name, *nAttached, *nUnattached);
693 /***************************************************/
694 /* Shutdown routines */
695 /***************************************************/
699 * highly multithreaded volume package shutdown
701 * with the demand attach fileserver extensions,
702 * VShutdown has been modified to be multithreaded.
703 * In order to achieve optimal use of many threads,
704 * the shutdown code involves one control thread and
705 * n shutdown worker threads. The control thread
706 * periodically examines the number of volumes available
707 * for shutdown on each partition, and produces a worker
708 * thread allocation schedule. The idea is to eliminate
709 * redundant scheduling computation on the workers by
710 * having a single master scheduler.
712 * The scheduler's objectives are:
714 * each partition with volumes remaining gets allocated
715 * at least 1 thread (assuming sufficient threads)
717 * threads are allocated proportional to the number of
718 * volumes remaining to be offlined. This ensures that
719 * the OS I/O scheduler has many requests to elevator
720 * seek on partitions that will (presumably) take the
721 * longest amount of time (from now) to finish shutdown
722 * (3) keep threads busy
723 * when there are extra threads, they are assigned to
724 * partitions using a simple round-robin algorithm
726 * In the future, we may wish to add the ability to adapt
727 * to the relative performance patterns of each disk
732 * multi-step shutdown process
734 * demand attach shutdown is a four-step process. Each
735 * shutdown "pass" shuts down increasingly more difficult
736 * volumes. The main purpose is to achieve better cache
737 * utilization during shutdown.
740 * shutdown volumes in the unattached, pre-attached
743 * shutdown attached volumes with cached volume headers
745 * shutdown all volumes in non-exclusive states
747 * shutdown all remaining volumes
754 register Volume *vp, *np;
755 register afs_int32 code;
756 #ifdef AFS_DEMAND_ATTACH_FS
757 struct DiskPartition64 * diskP;
758 struct diskpartition_queue_t * dpq;
759 vshutdown_thread_t params;
761 pthread_attr_t attrs;
763 memset(¶ms, 0, sizeof(vshutdown_thread_t));
765 for (params.n_parts=0, diskP = DiskPartitionList;
766 diskP; diskP = diskP->next, params.n_parts++);
768 Log("VShutdown: shutting down on-line volumes on %d partition%s...\n",
769 params.n_parts, params.n_parts > 1 ? "s" : "");
771 if (vol_attach_threads > 1) {
772 /* prepare for parallel shutdown */
773 params.n_threads = vol_attach_threads;
774 assert(pthread_mutex_init(¶ms.lock, NULL) == 0);
775 assert(pthread_cond_init(¶ms.cv, NULL) == 0);
776 assert(pthread_cond_init(¶ms.master_cv, NULL) == 0);
777 assert(pthread_attr_init(&attrs) == 0);
778 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
781 /* setup the basic partition information structures for
782 * parallel shutdown */
783 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
785 struct rx_queue * qp, * nqp;
789 VVByPListWait_r(diskP);
790 VVByPListBeginExclusive_r(diskP);
793 for (queue_Scan(&diskP->vol_list, qp, nqp, rx_queue)) {
794 vp = (Volume *)((char *)qp - offsetof(Volume, vol_list));
798 Log("VShutdown: partition %s has %d volumes with attached headers\n",
799 VPartitionPath(diskP), count);
802 /* build up the pass 0 shutdown work queue */
803 dpq = (struct diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
806 queue_Prepend(¶ms, dpq);
808 params.part_pass_head[diskP->index] = queue_First(&diskP->vol_list, rx_queue);
811 Log("VShutdown: beginning parallel fileserver shutdown\n");
812 Log("VShutdown: using %d threads to offline volumes on %d partition%s\n",
813 vol_attach_threads, params.n_parts, params.n_parts > 1 ? "s" : "" );
815 /* do pass 0 shutdown */
816 assert(pthread_mutex_lock(¶ms.lock) == 0);
817 for (i=0; i < params.n_threads; i++) {
818 assert(pthread_create
819 (&tid, &attrs, &VShutdownThread,
823 /* wait for all the pass 0 shutdowns to complete */
824 while (params.n_threads_complete < params.n_threads) {
825 assert(pthread_cond_wait(¶ms.master_cv, ¶ms.lock) == 0);
827 params.n_threads_complete = 0;
829 assert(pthread_cond_broadcast(¶ms.cv) == 0);
830 assert(pthread_mutex_unlock(¶ms.lock) == 0);
832 Log("VShutdown: pass 0 completed using the 1 thread per partition algorithm\n");
833 Log("VShutdown: starting passes 1 through 3 using finely-granular mp-fast algorithm\n");
835 /* run the parallel shutdown scheduler. it will drop the glock internally */
836 ShutdownController(¶ms);
838 /* wait for all the workers to finish pass 3 and terminate */
839 while (params.pass < 4) {
840 VOL_CV_WAIT(¶ms.cv);
843 assert(pthread_attr_destroy(&attrs) == 0);
844 assert(pthread_cond_destroy(¶ms.cv) == 0);
845 assert(pthread_cond_destroy(¶ms.master_cv) == 0);
846 assert(pthread_mutex_destroy(¶ms.lock) == 0);
848 /* drop the VByPList exclusive reservations */
849 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
850 VVByPListEndExclusive_r(diskP);
851 Log("VShutdown: %s stats : (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
852 VPartitionPath(diskP),
853 params.stats[0][diskP->index],
854 params.stats[1][diskP->index],
855 params.stats[2][diskP->index],
856 params.stats[3][diskP->index]);
859 Log("VShutdown: shutdown finished using %d threads\n", params.n_threads);
861 /* if we're only going to run one shutdown thread, don't bother creating
863 Log("VShutdown: beginning single-threaded fileserver shutdown\n");
865 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
866 VShutdownByPartition_r(diskP);
870 Log("VShutdown: complete.\n");
871 #else /* AFS_DEMAND_ATTACH_FS */
872 Log("VShutdown: shutting down on-line volumes...\n");
873 for (i = 0; i < VolumeHashTable.Size; i++) {
874 /* try to hold first volume in the hash table */
875 for (queue_Scan(&VolumeHashTable.Table[i],vp,np,Volume)) {
879 Log("VShutdown: Attempting to take volume %u offline.\n",
882 /* next, take the volume offline (drops reference count) */
883 VOffline_r(vp, "File server was shut down");
887 Log("VShutdown: complete.\n");
888 #endif /* AFS_DEMAND_ATTACH_FS */
899 #ifdef AFS_DEMAND_ATTACH_FS
902 * shutdown control thread
905 ShutdownController(vshutdown_thread_t * params)
908 struct DiskPartition64 * diskP;
910 vshutdown_thread_t shadow;
912 ShutdownCreateSchedule(params);
914 while ((params->pass < 4) &&
915 (params->n_threads_complete < params->n_threads)) {
916 /* recompute schedule once per second */
918 memcpy(&shadow, params, sizeof(vshutdown_thread_t));
922 Log("ShutdownController: schedule version=%d, vol_remaining=%d, pass=%d\n",
923 shadow.schedule_version, shadow.vol_remaining, shadow.pass);
924 Log("ShutdownController: n_threads_complete=%d, n_parts_done_pass=%d\n",
925 shadow.n_threads_complete, shadow.n_parts_done_pass);
926 for (diskP = DiskPartitionList; diskP; diskP=diskP->next) {
928 Log("ShutdownController: part[%d] : (len=%d, thread_target=%d, done_pass=%d, pass_head=%p)\n",
931 shadow.part_thread_target[id],
932 shadow.part_done_pass[id],
933 shadow.part_pass_head[id]);
939 ShutdownCreateSchedule(params);
943 /* create the shutdown thread work schedule.
944 * this scheduler tries to implement fairness
945 * by allocating at least 1 thread to each
946 * partition with volumes to be shutdown,
947 * and then it attempts to allocate remaining
948 * threads based upon the amount of work left
951 ShutdownCreateSchedule(vshutdown_thread_t * params)
953 struct DiskPartition64 * diskP;
954 int sum, thr_workload, thr_left;
955 int part_residue[VOLMAXPARTS+1];
958 /* compute the total number of outstanding volumes */
960 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
961 sum += diskP->vol_list.len;
964 params->schedule_version++;
965 params->vol_remaining = sum;
970 /* compute average per-thread workload */
971 thr_workload = sum / params->n_threads;
972 if (sum % params->n_threads)
975 thr_left = params->n_threads;
976 memset(&part_residue, 0, sizeof(part_residue));
978 /* for fairness, give every partition with volumes remaining
979 * at least one thread */
980 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
982 if (diskP->vol_list.len) {
983 params->part_thread_target[id] = 1;
986 params->part_thread_target[id] = 0;
990 if (thr_left && thr_workload) {
991 /* compute length-weighted workloads */
994 for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
996 delta = (diskP->vol_list.len / thr_workload) -
997 params->part_thread_target[id];
1001 if (delta < thr_left) {
1002 params->part_thread_target[id] += delta;
1005 params->part_thread_target[id] += thr_left;
1013 /* try to assign any leftover threads to partitions that
1014 * had volume lengths closer to needing thread_target+1 */
1015 int max_residue, max_id;
1017 /* compute the residues */
1018 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1020 part_residue[id] = diskP->vol_list.len -
1021 (params->part_thread_target[id] * thr_workload);
1024 /* now try to allocate remaining threads to partitions with the
1025 * highest residues */
1028 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1030 if (part_residue[id] > max_residue) {
1031 max_residue = part_residue[id];
1040 params->part_thread_target[max_id]++;
1042 part_residue[max_id] = 0;
1047 /* punt and give any remaining threads equally to each partition */
1049 if (thr_left >= params->n_parts) {
1050 alloc = thr_left / params->n_parts;
1051 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1053 params->part_thread_target[id] += alloc;
1058 /* finish off the last of the threads */
1059 for (diskP = DiskPartitionList; thr_left && diskP; diskP = diskP->next) {
1061 params->part_thread_target[id]++;
1067 /* worker thread for parallel shutdown */
1069 VShutdownThread(void * args)
1071 struct rx_queue *qp;
1073 vshutdown_thread_t * params;
1074 int part, code, found, pass, schedule_version_save, count;
1075 struct DiskPartition64 *diskP;
1076 struct diskpartition_queue_t * dpq;
1079 params = (vshutdown_thread_t *) args;
1081 /* acquire the shutdown pass 0 lock */
1082 assert(pthread_mutex_lock(¶ms->lock) == 0);
1084 /* if there's still pass 0 work to be done,
1085 * get a work entry, and do a pass 0 shutdown */
1086 if (queue_IsNotEmpty(params)) {
1087 dpq = queue_First(params, diskpartition_queue_t);
1089 assert(pthread_mutex_unlock(¶ms->lock) == 0);
1095 while (ShutdownVolumeWalk_r(diskP, 0, ¶ms->part_pass_head[id]))
1097 params->stats[0][diskP->index] = count;
1098 assert(pthread_mutex_lock(¶ms->lock) == 0);
1101 params->n_threads_complete++;
1102 if (params->n_threads_complete == params->n_threads) {
1103 /* notify control thread that all workers have completed pass 0 */
1104 assert(pthread_cond_signal(¶ms->master_cv) == 0);
1106 while (params->pass == 0) {
1107 assert(pthread_cond_wait(¶ms->cv, ¶ms->lock) == 0);
1111 assert(pthread_mutex_unlock(¶ms->lock) == 0);
1114 pass = params->pass;
1117 /* now escalate through the more complicated shutdowns */
1119 schedule_version_save = params->schedule_version;
1121 /* find a disk partition to work on */
1122 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1124 if (params->part_thread_target[id] && !params->part_done_pass[id]) {
1125 params->part_thread_target[id]--;
1132 /* hmm. for some reason the controller thread couldn't find anything for
1133 * us to do. let's see if there's anything we can do */
1134 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1136 if (diskP->vol_list.len && !params->part_done_pass[id]) {
1139 } else if (!params->part_done_pass[id]) {
1140 params->part_done_pass[id] = 1;
1141 params->n_parts_done_pass++;
1143 Log("VShutdown: done shutting down volumes on partition %s.\n",
1144 VPartitionPath(diskP));
1150 /* do work on this partition until either the controller
1151 * creates a new schedule, or we run out of things to do
1152 * on this partition */
1155 while (!params->part_done_pass[id] &&
1156 (schedule_version_save == params->schedule_version)) {
1157 /* ShutdownVolumeWalk_r will drop the glock internally */
1158 if (!ShutdownVolumeWalk_r(diskP, pass, ¶ms->part_pass_head[id])) {
1159 if (!params->part_done_pass[id]) {
1160 params->part_done_pass[id] = 1;
1161 params->n_parts_done_pass++;
1163 Log("VShutdown: done shutting down volumes on partition %s.\n",
1164 VPartitionPath(diskP));
1172 params->stats[pass][id] += count;
1174 /* ok, everyone is done this pass, proceed */
1177 params->n_threads_complete++;
1178 while (params->pass == pass) {
1179 if (params->n_threads_complete == params->n_threads) {
1180 /* we are the last thread to complete, so we will
1181 * reinitialize worker pool state for the next pass */
1182 params->n_threads_complete = 0;
1183 params->n_parts_done_pass = 0;
1185 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1187 params->part_done_pass[id] = 0;
1188 params->part_pass_head[id] = queue_First(&diskP->vol_list, rx_queue);
1191 /* compute a new thread schedule before releasing all the workers */
1192 ShutdownCreateSchedule(params);
1194 /* wake up all the workers */
1195 assert(pthread_cond_broadcast(¶ms->cv) == 0);
1198 Log("VShutdown: pass %d completed using %d threads on %d partitions\n",
1199 pass, params->n_threads, params->n_parts);
1202 VOL_CV_WAIT(¶ms->cv);
1205 pass = params->pass;
1219 /* shut down all volumes on a given disk partition
1221 * note that this function will not allow mp-fast
1222 * shutdown of a partition */
1224 VShutdownByPartition_r(struct DiskPartition64 * dp)
1230 /* wait for other exclusive ops to finish */
1231 VVByPListWait_r(dp);
1233 /* begin exclusive access */
1234 VVByPListBeginExclusive_r(dp);
1236 /* pick the low-hanging fruit first,
1237 * then do the complicated ones last
1238 * (has the advantage of keeping
1239 * in-use volumes up until the bitter end) */
1240 for (pass = 0, total=0; pass < 4; pass++) {
1241 pass_stats[pass] = ShutdownVByPForPass_r(dp, pass);
1242 total += pass_stats[pass];
1245 /* end exclusive access */
1246 VVByPListEndExclusive_r(dp);
1248 Log("VShutdownByPartition: shut down %d volumes on %s (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1249 total, VPartitionPath(dp), pass_stats[0], pass_stats[1], pass_stats[2], pass_stats[3]);
1254 /* internal shutdown functionality
1256 * for multi-pass shutdown:
1257 * 0 to only "shutdown" {pre,un}attached and error state volumes
1258 * 1 to also shutdown attached volumes w/ volume header loaded
1259 * 2 to also shutdown attached volumes w/o volume header loaded
1260 * 3 to also shutdown exclusive state volumes
1262 * caller MUST hold exclusive access on the hash chain
1263 * because we drop vol_glock_mutex internally
1265 * this function is reentrant for passes 1--3
1266 * (e.g. multiple threads can cooperate to
1267 * shutdown a partition mp-fast)
1269 * pass 0 is not scaleable because the volume state data is
1270 * synchronized by vol_glock mutex, and the locking overhead
1271 * is too high to drop the lock long enough to do linked list
1275 ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass)
1277 struct rx_queue * q = queue_First(&dp->vol_list, rx_queue);
1280 while (ShutdownVolumeWalk_r(dp, pass, &q))
1286 /* conditionally shutdown one volume on partition dp
1287 * returns 1 if a volume was shutdown in this pass,
1290 ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
1291 struct rx_queue ** idx)
1293 struct rx_queue *qp, *nqp;
1298 for (queue_ScanFrom(&dp->vol_list, qp, qp, nqp, rx_queue)) {
1299 vp = (Volume *) (((char *)qp) - offsetof(Volume, vol_list));
1303 if ((V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1304 (V_attachState(vp) != VOL_STATE_ERROR) &&
1305 (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1309 if ((V_attachState(vp) == VOL_STATE_ATTACHED) &&
1310 (vp->header == NULL)) {
1314 if (VIsExclusiveState(V_attachState(vp))) {
1319 DeleteVolumeFromVByPList_r(vp);
1320 VShutdownVolume_r(vp);
1330 * shutdown a specific volume
1332 /* caller MUST NOT hold a heavyweight ref on vp */
1334 VShutdownVolume_r(Volume * vp)
1338 VCreateReservation_r(vp);
1340 if (LogLevel >= 5) {
1341 Log("VShutdownVolume_r: vid=%u, device=%d, state=%hu\n",
1342 vp->hashid, vp->partition->device, V_attachState(vp));
1345 /* wait for other blocking ops to finish */
1346 VWaitExclusiveState_r(vp);
1348 assert(VIsValidState(V_attachState(vp)));
1350 switch(V_attachState(vp)) {
1351 case VOL_STATE_SALVAGING:
1352 /* make sure salvager knows we don't want
1353 * the volume back */
1354 VCancelSalvage_r(vp, SALVSYNC_SHUTDOWN);
1355 case VOL_STATE_PREATTACHED:
1356 case VOL_STATE_ERROR:
1357 VChangeState_r(vp, VOL_STATE_UNATTACHED);
1358 case VOL_STATE_UNATTACHED:
1360 case VOL_STATE_GOING_OFFLINE:
1361 case VOL_STATE_SHUTTING_DOWN:
1362 case VOL_STATE_ATTACHED:
1366 Log("VShutdown: Attempting to take volume %u offline.\n",
1369 /* take the volume offline (drops reference count) */
1370 VOffline_r(vp, "File server was shut down");
1375 VCancelReservation_r(vp);
1379 #endif /* AFS_DEMAND_ATTACH_FS */
1382 /***************************************************/
1383 /* Header I/O routines */
1384 /***************************************************/
1386 /* open a descriptor for the inode (h),
1387 * read in an on-disk structure into buffer (to) of size (size),
1388 * verify versionstamp in structure has magic (magic) and
1389 * optionally verify version (version) if (version) is nonzero
1392 ReadHeader(Error * ec, IHandle_t * h, char *to, int size, bit32 magic,
1395 struct versionStamp *vsn;
1410 if (FDH_SEEK(fdP, 0, SEEK_SET) < 0) {
1412 FDH_REALLYCLOSE(fdP);
1415 vsn = (struct versionStamp *)to;
1416 if (FDH_READ(fdP, to, size) != size || vsn->magic != magic) {
1418 FDH_REALLYCLOSE(fdP);
1423 /* Check is conditional, in case caller wants to inspect version himself */
1424 if (version && vsn->version != version) {
1430 WriteVolumeHeader_r(Error * ec, Volume * vp)
1432 IHandle_t *h = V_diskDataHandle(vp);
1442 if (FDH_SEEK(fdP, 0, SEEK_SET) < 0) {
1444 FDH_REALLYCLOSE(fdP);
1447 if (FDH_WRITE(fdP, (char *)&V_disk(vp), sizeof(V_disk(vp)))
1448 != sizeof(V_disk(vp))) {
1450 FDH_REALLYCLOSE(fdP);
1456 /* VolumeHeaderToDisk
1457 * Allows for storing 64 bit inode numbers in on-disk volume header
1460 /* convert in-memory representation of a volume header to the
1461 * on-disk representation of a volume header */
1463 VolumeHeaderToDisk(VolumeDiskHeader_t * dh, VolumeHeader_t * h)
1466 memset((char *)dh, 0, sizeof(VolumeDiskHeader_t));
1467 dh->stamp = h->stamp;
1469 dh->parent = h->parent;
1471 #ifdef AFS_64BIT_IOPS_ENV
1472 dh->volumeInfo_lo = (afs_int32) h->volumeInfo & 0xffffffff;
1473 dh->volumeInfo_hi = (afs_int32) (h->volumeInfo >> 32) & 0xffffffff;
1474 dh->smallVnodeIndex_lo = (afs_int32) h->smallVnodeIndex & 0xffffffff;
1475 dh->smallVnodeIndex_hi =
1476 (afs_int32) (h->smallVnodeIndex >> 32) & 0xffffffff;
1477 dh->largeVnodeIndex_lo = (afs_int32) h->largeVnodeIndex & 0xffffffff;
1478 dh->largeVnodeIndex_hi =
1479 (afs_int32) (h->largeVnodeIndex >> 32) & 0xffffffff;
1480 dh->linkTable_lo = (afs_int32) h->linkTable & 0xffffffff;
1481 dh->linkTable_hi = (afs_int32) (h->linkTable >> 32) & 0xffffffff;
1483 dh->volumeInfo_lo = h->volumeInfo;
1484 dh->smallVnodeIndex_lo = h->smallVnodeIndex;
1485 dh->largeVnodeIndex_lo = h->largeVnodeIndex;
1486 dh->linkTable_lo = h->linkTable;
1490 /* DiskToVolumeHeader
1491 * Converts an on-disk representation of a volume header to
1492 * the in-memory representation of a volume header.
1494 * Makes the assumption that AFS has *always*
1495 * zero'd the volume header file so that high parts of inode
1496 * numbers are 0 in older (SGI EFS) volume header files.
1499 DiskToVolumeHeader(VolumeHeader_t * h, VolumeDiskHeader_t * dh)
1501 memset((char *)h, 0, sizeof(VolumeHeader_t));
1502 h->stamp = dh->stamp;
1504 h->parent = dh->parent;
1506 #ifdef AFS_64BIT_IOPS_ENV
1508 (Inode) dh->volumeInfo_lo | ((Inode) dh->volumeInfo_hi << 32);
1510 h->smallVnodeIndex =
1511 (Inode) dh->smallVnodeIndex_lo | ((Inode) dh->
1512 smallVnodeIndex_hi << 32);
1514 h->largeVnodeIndex =
1515 (Inode) dh->largeVnodeIndex_lo | ((Inode) dh->
1516 largeVnodeIndex_hi << 32);
1518 (Inode) dh->linkTable_lo | ((Inode) dh->linkTable_hi << 32);
1520 h->volumeInfo = dh->volumeInfo_lo;
1521 h->smallVnodeIndex = dh->smallVnodeIndex_lo;
1522 h->largeVnodeIndex = dh->largeVnodeIndex_lo;
1523 h->linkTable = dh->linkTable_lo;
1528 /***************************************************/
1529 /* Volume Attachment routines */
1530 /***************************************************/
1532 #ifdef AFS_DEMAND_ATTACH_FS
1534 * pre-attach a volume given its path.
1536 * @param[out] ec outbound error code
1537 * @param[in] partition partition path string
1538 * @param[in] name volume id string
1540 * @return volume object pointer
1542 * @note A pre-attached volume will only have its partition
1543 * and hashid fields initialized. At first call to
1544 * VGetVolume, the volume will be fully attached.
1548 VPreAttachVolumeByName(Error * ec, char *partition, char *name)
1552 vp = VPreAttachVolumeByName_r(ec, partition, name);
1558 * pre-attach a volume given its path.
1560 * @param[out] ec outbound error code
1561 * @param[in] partition path to vice partition
1562 * @param[in] name volume id string
1564 * @return volume object pointer
1566 * @pre VOL_LOCK held
1568 * @internal volume package internal use only.
1571 VPreAttachVolumeByName_r(Error * ec, char *partition, char *name)
1573 return VPreAttachVolumeById_r(ec,
1575 VolumeNumber(name));
1579 * pre-attach a volume given its path and numeric volume id.
1581 * @param[out] ec error code return
1582 * @param[in] partition path to vice partition
1583 * @param[in] volumeId numeric volume id
1585 * @return volume object pointer
1587 * @pre VOL_LOCK held
1589 * @internal volume package internal use only.
1592 VPreAttachVolumeById_r(Error * ec,
1597 struct DiskPartition64 *partp;
1601 assert(programType == fileServer);
1603 if (!(partp = VGetPartition_r(partition, 0))) {
1605 Log("VPreAttachVolumeById_r: Error getting partition (%s)\n", partition);
1609 vp = VLookupVolume_r(ec, volumeId, NULL);
1614 return VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
1618 * preattach a volume.
1620 * @param[out] ec outbound error code
1621 * @param[in] partp pointer to partition object
1622 * @param[in] vp pointer to volume object
1623 * @param[in] vid volume id
1625 * @return volume object pointer
1627 * @pre VOL_LOCK is held.
1629 * @warning Returned volume object pointer does not have to
1630 * equal the pointer passed in as argument vp. There
1631 * are potential race conditions which can result in
1632 * the pointers having different values. It is up to
1633 * the caller to make sure that references are handled
1634 * properly in this case.
1636 * @note If there is already a volume object registered with
1637 * the same volume id, its pointer MUST be passed as
1638 * argument vp. Failure to do so will result in a silent
1639 * failure to preattach.
1641 * @internal volume package internal use only.
1644 VPreAttachVolumeByVp_r(Error * ec,
1645 struct DiskPartition64 * partp,
1653 /* check to see if pre-attach already happened */
1655 (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1656 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
1657 !VIsErrorState(V_attachState(vp))) {
1659 * pre-attach is a no-op in all but the following cases:
1661 * - volume is unattached
1662 * - volume is in an error state
1663 * - volume is pre-attached
1665 Log("VPreattachVolumeByVp_r: volume %u not in quiescent state\n", vid);
1668 /* we're re-attaching a volume; clear out some old state */
1669 memset(&vp->salvage, 0, sizeof(struct VolumeOnlineSalvage));
1671 if (V_partition(vp) != partp) {
1672 /* XXX potential race */
1673 DeleteVolumeFromVByPList_r(vp);
1676 /* if we need to allocate a new Volume struct,
1677 * go ahead and drop the vol glock, otherwise
1678 * do the basic setup synchronised, as it's
1679 * probably not worth dropping the lock */
1682 /* allocate the volume structure */
1683 vp = nvp = (Volume *) malloc(sizeof(Volume));
1685 memset(vp, 0, sizeof(Volume));
1686 queue_Init(&vp->vnode_list);
1687 assert(pthread_cond_init(&V_attachCV(vp), NULL) == 0);
1690 /* link the volume with its associated vice partition */
1691 vp->device = partp->device;
1692 vp->partition = partp;
1695 vp->specialStatus = 0;
1697 /* if we dropped the lock, reacquire the lock,
1698 * check for pre-attach races, and then add
1699 * the volume to the hash table */
1702 nvp = VLookupVolume_r(ec, vid, NULL);
1707 } else if (nvp) { /* race detected */
1712 /* hack to make up for VChangeState_r() decrementing
1713 * the old state counter */
1714 VStats.state_levels[0]++;
1718 /* put pre-attached volume onto the hash table
1719 * and bring it up to the pre-attached state */
1720 AddVolumeToHashTable(vp, vp->hashid);
1721 AddVolumeToVByPList_r(vp);
1722 VLRU_Init_Node_r(vp);
1723 VChangeState_r(vp, VOL_STATE_PREATTACHED);
1726 Log("VPreAttachVolumeByVp_r: volume %u pre-attached\n", vp->hashid);
1734 #endif /* AFS_DEMAND_ATTACH_FS */
1736 /* Attach an existing volume, given its pathname, and return a
1737 pointer to the volume header information. The volume also
1738 normally goes online at this time. An offline volume
1739 must be reattached to make it go online */
1741 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
1745 retVal = VAttachVolumeByName_r(ec, partition, name, mode);
1751 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
1753 register Volume *vp = NULL;
1755 struct afs_stat status;
1756 struct VolumeDiskHeader diskHeader;
1757 struct VolumeHeader iheader;
1758 struct DiskPartition64 *partp;
1762 #ifdef AFS_DEMAND_ATTACH_FS
1763 VolumeStats stats_save;
1765 #endif /* AFS_DEMAND_ATTACH_FS */
1769 volumeId = VolumeNumber(name);
1771 if (!(partp = VGetPartition_r(partition, 0))) {
1773 Log("VAttachVolume: Error getting partition (%s)\n", partition);
1777 if (programType == volumeUtility) {
1779 VLockPartition_r(partition);
1780 } else if (programType == fileServer) {
1781 #ifdef AFS_DEMAND_ATTACH_FS
1782 /* lookup the volume in the hash table */
1783 vp = VLookupVolume_r(ec, volumeId, NULL);
1789 /* save any counters that are supposed to
1790 * be monotonically increasing over the
1791 * lifetime of the fileserver */
1792 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
1794 memset(&stats_save, 0, sizeof(VolumeStats));
1797 /* if there's something in the hash table, and it's not
1798 * in the pre-attach state, then we may need to detach
1799 * it before proceeding */
1800 if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1801 VCreateReservation_r(vp);
1802 VWaitExclusiveState_r(vp);
1804 /* at this point state must be one of:
1813 if (vp->specialStatus == VBUSY)
1816 /* if it's already attached, see if we can return it */
1817 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
1818 VGetVolumeByVp_r(ec, vp);
1819 if (V_inUse(vp) == fileServer) {
1820 VCancelReservation_r(vp);
1824 /* otherwise, we need to detach, and attempt to re-attach */
1825 VDetachVolume_r(ec, vp);
1827 Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
1830 /* if it isn't fully attached, delete from the hash tables,
1831 and let the refcounter handle the rest */
1832 DeleteVolumeFromHashTable(vp);
1833 DeleteVolumeFromVByPList_r(vp);
1836 VCancelReservation_r(vp);
1840 /* pre-attach volume if it hasn't been done yet */
1842 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
1843 (V_attachState(vp) == VOL_STATE_ERROR)) {
1845 vp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
1853 /* handle pre-attach races
1855 * multiple threads can race to pre-attach a volume,
1856 * but we can't let them race beyond that
1858 * our solution is to let the first thread to bring
1859 * the volume into an exclusive state win; the other
1860 * threads just wait until it finishes bringing the
1861 * volume online, and then they do a vgetvolumebyvp
1863 if (svp && (svp != vp)) {
1864 /* wait for other exclusive ops to finish */
1865 VCreateReservation_r(vp);
1866 VWaitExclusiveState_r(vp);
1868 /* get a heavyweight ref, kill the lightweight ref, and return */
1869 VGetVolumeByVp_r(ec, vp);
1870 VCancelReservation_r(vp);
1874 /* at this point, we are chosen as the thread to do
1875 * demand attachment for this volume. all other threads
1876 * doing a getvolume on vp->hashid will block until we finish */
1878 /* make sure any old header cache entries are invalidated
1879 * before proceeding */
1880 FreeVolumeHeader(vp);
1882 VChangeState_r(vp, VOL_STATE_ATTACHING);
1884 /* restore any saved counters */
1885 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
1886 #else /* AFS_DEMAND_ATTACH_FS */
1887 vp = VGetVolume_r(ec, volumeId);
1889 if (V_inUse(vp) == fileServer)
1891 if (vp->specialStatus == VBUSY)
1893 VDetachVolume_r(ec, vp);
1895 Log("VAttachVolume: Error detaching volume (%s)\n", name);
1899 #endif /* AFS_DEMAND_ATTACH_FS */
1903 strcpy(path, VPartitionPath(partp));
1909 if ((fd = afs_open(path, O_RDONLY)) == -1 || afs_fstat(fd, &status) == -1) {
1910 Log("VAttachVolume: Failed to open %s (errno %d)\n", path, errno);
1917 n = read(fd, &diskHeader, sizeof(diskHeader));
1919 if (n != sizeof(diskHeader)
1920 || diskHeader.stamp.magic != VOLUMEHEADERMAGIC) {
1921 Log("VAttachVolume: Error reading volume header %s\n", path);
1926 if (diskHeader.stamp.version != VOLUMEHEADERVERSION) {
1927 Log("VAttachVolume: Volume %s, version number is incorrect; volume needs salvaged\n", path);
1933 DiskToVolumeHeader(&iheader, &diskHeader);
1934 #ifdef FSSYNC_BUILD_CLIENT
1935 if (programType == volumeUtility && mode != V_SECRETLY && mode != V_PEEK) {
1937 if (FSYNC_VolOp(iheader.id, partition, FSYNC_VOL_NEEDVOLUME, mode, NULL)
1939 Log("VAttachVolume: attach of volume %u apparently denied by file server\n", iheader.id);
1940 *ec = VNOVOL; /* XXXX */
1948 vp = (Volume *) calloc(1, sizeof(Volume));
1950 vp->device = partp->device;
1951 vp->partition = partp;
1952 queue_Init(&vp->vnode_list);
1953 #ifdef AFS_DEMAND_ATTACH_FS
1954 assert(pthread_cond_init(&V_attachCV(vp), NULL) == 0);
1955 #endif /* AFS_DEMAND_ATTACH_FS */
1958 /* attach2 is entered without any locks, and returns
1959 * with vol_glock_mutex held */
1960 vp = attach2(ec, volumeId, path, &iheader, partp, vp, isbusy, mode);
1962 if (programType == volumeUtility && vp) {
1963 if ((mode == V_VOLUPD) || (VolumeWriteable(vp) && (mode == V_CLONE))) {
1964 /* mark volume header as in use so that volser crashes lead to a
1965 * salvage attempt */
1966 VUpdateVolume_r(ec, vp, 0);
1968 #ifdef AFS_DEMAND_ATTACH_FS
1969 /* for dafs, we should tell the fileserver, except for V_PEEK
1970 * where we know it is not necessary */
1971 if (mode == V_PEEK) {
1972 vp->needsPutBack = 0;
1974 vp->needsPutBack = 1;
1976 #else /* !AFS_DEMAND_ATTACH_FS */
1977 /* duplicate computation in fssync.c about whether the server
1978 * takes the volume offline or not. If the volume isn't
1979 * offline, we must not return it when we detach the volume,
1980 * or the server will abort */
1981 if (mode == V_READONLY || mode == V_PEEK
1982 || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
1983 vp->needsPutBack = 0;
1985 vp->needsPutBack = 1;
1986 #endif /* !AFS_DEMAND_ATTACH_FS */
1988 /* OK, there's a problem here, but one that I don't know how to
1989 * fix right now, and that I don't think should arise often.
1990 * Basically, we should only put back this volume to the server if
1991 * it was given to us by the server, but since we don't have a vp,
1992 * we can't run the VolumeWriteable function to find out as we do
1993 * above when computing vp->needsPutBack. So we send it back, but
1994 * there's a path in VAttachVolume on the server which may abort
1995 * if this volume doesn't have a header. Should be pretty rare
1996 * for all of that to happen, but if it does, probably the right
1997 * fix is for the server to allow the return of readonly volumes
1998 * that it doesn't think are really checked out. */
1999 #ifdef FSSYNC_BUILD_CLIENT
2000 if (programType == volumeUtility && vp == NULL &&
2001 mode != V_SECRETLY && mode != V_PEEK) {
2002 FSYNC_VolOp(iheader.id, partition, FSYNC_VOL_ON, 0, NULL);
2005 if (programType == fileServer && vp) {
2006 #ifdef AFS_DEMAND_ATTACH_FS
2008 * we can get here in cases where we don't "own"
2009 * the volume (e.g. volume owned by a utility).
2010 * short circuit around potential disk header races.
2012 if (V_attachState(vp) != VOL_STATE_ATTACHED) {
2016 V_needsCallback(vp) = 0;
2018 if (VInit >= 2 && V_BreakVolumeCallbacks) {
2019 Log("VAttachVolume: Volume %u was changed externally; breaking callbacks\n", V_id(vp));
2020 (*V_BreakVolumeCallbacks) (V_id(vp));
2023 VUpdateVolume_r(ec, vp, 0);
2025 Log("VAttachVolume: Error updating volume\n");
2030 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2031 #ifndef AFS_DEMAND_ATTACH_FS
2032 /* This is a hack: by temporarily setting the incore
2033 * dontSalvage flag ON, the volume will be put back on the
2034 * Update list (with dontSalvage OFF again). It will then
2035 * come back in N minutes with DONT_SALVAGE eventually
2036 * set. This is the way that volumes that have never had
2037 * it set get it set; or that volumes that have been
2038 * offline without DONT SALVAGE having been set also
2039 * eventually get it set */
2040 V_dontSalvage(vp) = DONT_SALVAGE;
2041 #endif /* !AFS_DEMAND_ATTACH_FS */
2042 VAddToVolumeUpdateList_r(ec, vp);
2044 Log("VAttachVolume: Error adding volume to update list\n");
2051 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2056 if (programType == volumeUtility) {
2057 VUnlockPartition_r(partition);
2060 #ifdef AFS_DEMAND_ATTACH_FS
2061 /* attach failed; make sure we're in error state */
2062 if (vp && !VIsErrorState(V_attachState(vp))) {
2063 VChangeState_r(vp, VOL_STATE_ERROR);
2065 #endif /* AFS_DEMAND_ATTACH_FS */
2072 #ifdef AFS_DEMAND_ATTACH_FS
2073 /* VAttachVolumeByVp_r
2075 * finish attaching a volume that is
2076 * in a less than fully attached state
2078 /* caller MUST hold a ref count on vp */
2080 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
2082 char name[VMAXPATHLEN];
2083 int fd, n, reserve = 0;
2084 struct afs_stat status;
2085 struct VolumeDiskHeader diskHeader;
2086 struct VolumeHeader iheader;
2087 struct DiskPartition64 *partp;
2092 VolumeStats stats_save;
2095 /* volume utility should never call AttachByVp */
2096 assert(programType == fileServer);
2098 volumeId = vp->hashid;
2099 partp = vp->partition;
2100 VolumeExternalName_r(volumeId, name, sizeof(name));
2103 /* if another thread is performing a blocking op, wait */
2104 VWaitExclusiveState_r(vp);
2106 memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2108 /* if it's already attached, see if we can return it */
2109 if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2110 VGetVolumeByVp_r(ec, vp);
2111 if (V_inUse(vp) == fileServer) {
2114 if (vp->specialStatus == VBUSY)
2116 VDetachVolume_r(ec, vp);
2118 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2124 /* pre-attach volume if it hasn't been done yet */
2126 (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2127 (V_attachState(vp) == VOL_STATE_ERROR)) {
2128 nvp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2134 VCreateReservation_r(nvp);
2140 VChangeState_r(vp, VOL_STATE_ATTACHING);
2142 /* restore monotonically increasing stats */
2143 memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2148 /* compute path to disk header,
2150 * and verify magic and version stamps */
2151 strcpy(path, VPartitionPath(partp));
2157 if ((fd = afs_open(path, O_RDONLY)) == -1 || afs_fstat(fd, &status) == -1) {
2158 Log("VAttachVolume: Failed to open %s (errno %d)\n", path, errno);
2165 n = read(fd, &diskHeader, sizeof(diskHeader));
2167 if (n != sizeof(diskHeader)
2168 || diskHeader.stamp.magic != VOLUMEHEADERMAGIC) {
2169 Log("VAttachVolume: Error reading volume header %s\n", path);
2174 if (diskHeader.stamp.version != VOLUMEHEADERVERSION) {
2175 Log("VAttachVolume: Volume %s, version number is incorrect; volume needs salvaged\n", path);
2181 /* convert on-disk header format to in-memory header format */
2182 DiskToVolumeHeader(&iheader, &diskHeader);
2186 * NOTE: attach2 is entered without any locks, and returns
2187 * with vol_glock_mutex held */
2188 vp = attach2(ec, volumeId, path, &iheader, partp, vp, isbusy, mode);
2191 * the event that an error was encountered, or
2192 * the volume was not brought to an attached state
2193 * for any reason, skip to the end. We cannot
2194 * safely call VUpdateVolume unless we "own" it.
2198 (V_attachState(vp) != VOL_STATE_ATTACHED)) {
2202 V_needsCallback(vp) = 0;
2203 VUpdateVolume_r(ec, vp, 0);
2205 Log("VAttachVolume: Error updating volume %u\n", vp->hashid);
2209 if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2210 #ifndef AFS_DEMAND_ATTACH_FS
2211 /* This is a hack: by temporarily setting the incore
2212 * dontSalvage flag ON, the volume will be put back on the
2213 * Update list (with dontSalvage OFF again). It will then
2214 * come back in N minutes with DONT_SALVAGE eventually
2215 * set. This is the way that volumes that have never had
2216 * it set get it set; or that volumes that have been
2217 * offline without DONT SALVAGE having been set also
2218 * eventually get it set */
2219 V_dontSalvage(vp) = DONT_SALVAGE;
2220 #endif /* !AFS_DEMAND_ATTACH_FS */
2221 VAddToVolumeUpdateList_r(ec, vp);
2223 Log("VAttachVolume: Error adding volume %u to update list\n", vp->hashid);
2230 Log("VOnline: volume %u (%s) attached and online\n", V_id(vp),
2234 VCancelReservation_r(nvp);
2237 if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2238 if (vp && !VIsErrorState(V_attachState(vp))) {
2239 VChangeState_r(vp, VOL_STATE_ERROR);
2246 #endif /* AFS_DEMAND_ATTACH_FS */
2249 * called without any locks held
2250 * returns with vol_glock_mutex held
2253 attach2(Error * ec, VolId volumeId, char *path, register struct VolumeHeader * header,
2254 struct DiskPartition64 * partp, register Volume * vp, int isbusy, int mode)
2256 vp->specialStatus = (byte) (isbusy ? VBUSY : 0);
2257 IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header->parent,
2258 header->largeVnodeIndex);
2259 IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header->parent,
2260 header->smallVnodeIndex);
2261 IH_INIT(vp->diskDataHandle, partp->device, header->parent,
2262 header->volumeInfo);
2263 IH_INIT(vp->linkHandle, partp->device, header->parent, header->linkTable);
2264 vp->shuttingDown = 0;
2265 vp->goingOffline = 0;
2267 #ifdef AFS_DEMAND_ATTACH_FS
2268 vp->stats.last_attach = FT_ApproxTime();
2269 vp->stats.attaches++;
2273 IncUInt64(&VStats.attaches);
2274 vp->cacheCheck = ++VolumeCacheCheck;
2275 /* just in case this ever rolls over */
2276 if (!vp->cacheCheck)
2277 vp->cacheCheck = ++VolumeCacheCheck;
2278 GetVolumeHeader(vp);
2281 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2282 /* demand attach changes the V_PEEK mechanism
2284 * we can now suck the current disk data structure over
2285 * the fssync interface without going to disk
2287 * (technically, we don't need to restrict this feature
2288 * to demand attach fileservers. However, I'm trying
2289 * to limit the number of common code changes)
2291 if (programType != fileServer && mode == V_PEEK) {
2293 res.payload.len = sizeof(VolumeDiskData);
2294 res.payload.buf = &vp->header->diskstuff;
2296 if (FSYNC_VolOp(volumeId,
2298 FSYNC_VOL_QUERY_HDR,
2301 goto disk_header_loaded;
2304 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2305 (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2306 sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2308 #ifdef AFS_DEMAND_ATTACH_FS
2311 IncUInt64(&VStats.hdr_loads);
2312 IncUInt64(&vp->stats.hdr_loads);
2314 #endif /* AFS_DEMAND_ATTACH_FS */
2317 Log("VAttachVolume: Error reading diskDataHandle vol header %s; error=%u\n", path, *ec);
2320 #ifdef AFS_DEMAND_ATTACH_FS
2324 /* check for pending volume operations */
2325 if (vp->pending_vol_op) {
2326 /* see if the pending volume op requires exclusive access */
2327 switch (vp->pending_vol_op->vol_op_state) {
2328 case FSSYNC_VolOpPending:
2329 /* this should never happen */
2330 assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpPending);
2333 case FSSYNC_VolOpRunningUnknown:
2334 vp->pending_vol_op->vol_op_state =
2335 (VVolOpLeaveOnline_r(vp, vp->pending_vol_op) ?
2336 FSSYNC_VolOpRunningOnline : FSSYNC_VolOpRunningOffline);
2339 case FSSYNC_VolOpRunningOffline:
2340 /* mark the volume down */
2342 VChangeState_r(vp, VOL_STATE_UNATTACHED);
2343 if (V_offlineMessage(vp)[0] == '\0')
2344 strlcpy(V_offlineMessage(vp),
2345 "A volume utility is running.",
2346 sizeof(V_offlineMessage(vp)));
2347 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
2349 /* check to see if we should set the specialStatus flag */
2350 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
2351 vp->specialStatus = VBUSY;
2356 V_attachFlags(vp) |= VOL_HDR_LOADED;
2357 vp->stats.last_hdr_load = vp->stats.last_attach;
2359 #endif /* AFS_DEMAND_ATTACH_FS */
2362 struct IndexFileHeader iHead;
2364 #if OPENAFS_VOL_STATS
2366 * We just read in the diskstuff part of the header. If the detailed
2367 * volume stats area has not yet been initialized, we should bzero the
2368 * area and mark it as initialized.
2370 if (!(V_stat_initialized(vp))) {
2371 memset((char *)(V_stat_area(vp)), 0, VOL_STATS_BYTES);
2372 V_stat_initialized(vp) = 1;
2374 #endif /* OPENAFS_VOL_STATS */
2376 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
2377 (char *)&iHead, sizeof(iHead),
2378 SMALLINDEXMAGIC, SMALLINDEXVERSION);
2381 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
2386 struct IndexFileHeader iHead;
2388 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
2389 (char *)&iHead, sizeof(iHead),
2390 LARGEINDEXMAGIC, LARGEINDEXVERSION);
2393 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
2397 #ifdef AFS_NAMEI_ENV
2399 struct versionStamp stamp;
2401 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
2402 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
2405 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
2408 #endif /* AFS_NAMEI_ENV */
2410 #if defined(AFS_DEMAND_ATTACH_FS)
2411 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
2413 if (programType == fileServer) {
2414 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2417 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
2423 /* volume operation in progress */
2427 #else /* AFS_DEMAND_ATTACH_FS */
2429 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
2434 #endif /* AFS_DEMAND_ATTACH_FS */
2436 if (V_needsSalvaged(vp)) {
2437 if (vp->specialStatus)
2438 vp->specialStatus = 0;
2440 #if defined(AFS_DEMAND_ATTACH_FS)
2441 if (programType == fileServer) {
2442 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
2445 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
2449 #else /* AFS_DEMAND_ATTACH_FS */
2452 #endif /* AFS_DEMAND_ATTACH_FS */
2457 if (programType == fileServer) {
2458 #ifndef FAST_RESTART
2459 if (V_inUse(vp) && VolumeWriteable(vp)) {
2460 if (!V_needsSalvaged(vp)) {
2461 V_needsSalvaged(vp) = 1;
2462 VUpdateVolume_r(ec, vp, 0);
2464 #if defined(AFS_DEMAND_ATTACH_FS)
2465 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
2467 #else /* AFS_DEMAND_ATTACH_FS */
2468 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
2471 #endif /* AFS_DEMAND_ATTACH_FS */
2474 #endif /* FAST_RESTART */
2476 if (V_destroyMe(vp) == DESTROY_ME) {
2477 #if defined(AFS_DEMAND_ATTACH_FS)
2478 /* schedule a salvage so the volume goes away on disk */
2479 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2480 VChangeState_r(vp, VOL_STATE_ERROR);
2482 #endif /* AFS_DEMAND_ATTACH_FS */
2484 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
2490 vp->nextVnodeUnique = V_uniquifier(vp);
2491 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
2492 #ifndef BITMAP_LATER
2493 if (programType == fileServer && VolumeWriteable(vp)) {
2495 for (i = 0; i < nVNODECLASSES; i++) {
2496 VGetBitmap_r(ec, vp, i);
2498 #ifdef AFS_DEMAND_ATTACH_FS
2499 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2501 #else /* AFS_DEMAND_ATTACH_FS */
2503 #endif /* AFS_DEMAND_ATTACH_FS */
2504 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
2510 #endif /* BITMAP_LATER */
2512 if (programType == fileServer) {
2513 if (vp->specialStatus)
2514 vp->specialStatus = 0;
2515 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
2516 V_inUse(vp) = fileServer;
2517 V_offlineMessage(vp)[0] = '\0';
2520 if ((mode != V_PEEK) && (mode != V_SECRETLY))
2521 V_inUse(vp) = programType;
2522 V_checkoutMode(vp) = mode;
2525 AddVolumeToHashTable(vp, V_id(vp));
2526 #ifdef AFS_DEMAND_ATTACH_FS
2527 if ((programType != fileServer) ||
2528 (V_inUse(vp) == fileServer)) {
2529 AddVolumeToVByPList_r(vp);
2531 VChangeState_r(vp, VOL_STATE_ATTACHED);
2533 VChangeState_r(vp, VOL_STATE_UNATTACHED);
2539 /* Attach an existing volume.
2540 The volume also normally goes online at this time.
2541 An offline volume must be reattached to make it go online.
2545 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
2549 retVal = VAttachVolume_r(ec, volumeId, mode);
2555 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
2558 VGetVolumePath(ec, volumeId, &part, &name);
2560 register Volume *vp;
2562 vp = VGetVolume_r(&error, volumeId);
2564 assert(V_inUse(vp) == 0);
2565 VDetachVolume_r(ec, vp);
2569 return VAttachVolumeByName_r(ec, part, name, mode);
2572 /* Increment a reference count to a volume, sans context swaps. Requires
2573 * possibly reading the volume header in from the disk, since there's
2574 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
2576 * N.B. This call can fail if we can't read in the header!! In this case
2577 * we still guarantee we won't context swap, but the ref count won't be
2578 * incremented (otherwise we'd violate the invariant).
2580 /* NOTE: with the demand attach fileserver extensions, the global lock
2581 * is dropped within VHold */
2582 #ifdef AFS_DEMAND_ATTACH_FS
2584 VHold_r(register Volume * vp)
2588 VCreateReservation_r(vp);
2589 VWaitExclusiveState_r(vp);
2591 LoadVolumeHeader(&error, vp);
2593 VCancelReservation_r(vp);
2597 VCancelReservation_r(vp);
2600 #else /* AFS_DEMAND_ATTACH_FS */
2602 VHold_r(register Volume * vp)
2606 LoadVolumeHeader(&error, vp);
2612 #endif /* AFS_DEMAND_ATTACH_FS */
2616 VHold(register Volume * vp)
2620 retVal = VHold_r(vp);
2627 /***************************************************/
2628 /* get and put volume routines */
2629 /***************************************************/
2632 * put back a heavyweight reference to a volume object.
2634 * @param[in] vp volume object pointer
2636 * @pre VOL_LOCK held
2638 * @post heavyweight volume reference put back.
2639 * depending on state, volume may have been taken offline,
2640 * detached, salvaged, freed, etc.
2642 * @internal volume package internal use only
2645 VPutVolume_r(register Volume * vp)
2647 assert(--vp->nUsers >= 0);
2648 if (vp->nUsers == 0) {
2650 ReleaseVolumeHeader(vp->header);
2651 #ifdef AFS_DEMAND_ATTACH_FS
2652 if (!VCheckDetach(vp)) {
2656 #else /* AFS_DEMAND_ATTACH_FS */
2658 #endif /* AFS_DEMAND_ATTACH_FS */
2663 VPutVolume(register Volume * vp)
2671 /* Get a pointer to an attached volume. The pointer is returned regardless
2672 of whether or not the volume is in service or on/off line. An error
2673 code, however, is returned with an indication of the volume's status */
2675 VGetVolume(Error * ec, Error * client_ec, VolId volumeId)
2679 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
2685 VGetVolume_r(Error * ec, VolId volumeId)
2687 return GetVolume(ec, NULL, volumeId, NULL, 0);
2690 /* try to get a volume we've previously looked up */
2691 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
2693 VGetVolumeByVp_r(Error * ec, Volume * vp)
2695 return GetVolume(ec, NULL, vp->hashid, vp, 0);
2698 /* private interface for getting a volume handle
2699 * volumeId must be provided.
2700 * hint is an optional parameter to speed up hash lookups
2701 * flags is not used at this time
2703 /* for demand attach fs, caller MUST NOT hold a ref count on hint */
2705 GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint, int flags)
2708 /* pull this profiling/debugging code out of regular builds */
2710 #define VGET_CTR_INC(x) x++
2711 unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
2712 0, V7 = 0, V8 = 0, V9 = 0;
2713 unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
2715 #define VGET_CTR_INC(x)
2717 #ifdef AFS_DEMAND_ATTACH_FS
2718 Volume *avp, * rvp = hint;
2722 * if VInit is zero, the volume package dynamic
2723 * data structures have not been initialized yet,
2724 * and we must immediately return an error
2730 *client_ec = VOFFLINE;
2735 #ifdef AFS_DEMAND_ATTACH_FS
2737 VCreateReservation_r(rvp);
2739 #endif /* AFS_DEMAND_ATTACH_FS */
2747 vp = VLookupVolume_r(ec, volumeId, vp);
2753 #ifdef AFS_DEMAND_ATTACH_FS
2754 if (rvp && (rvp != vp)) {
2755 /* break reservation on old vp */
2756 VCancelReservation_r(rvp);
2759 #endif /* AFS_DEMAND_ATTACH_FS */
2765 /* Until we have reached an initialization level of 2
2766 * we don't know whether this volume exists or not.
2767 * We can't sleep and retry later because before a volume
2768 * is attached, the caller tries to get it first. Just
2769 * return VOFFLINE and the caller can choose whether to
2770 * retry the command or not. */
2780 IncUInt64(&VStats.hdr_gets);
2782 #ifdef AFS_DEMAND_ATTACH_FS
2783 /* block if someone else is performing an exclusive op on this volume */
2786 VCreateReservation_r(rvp);
2788 VWaitExclusiveState_r(vp);
2790 /* short circuit with VNOVOL in the following circumstances:
2793 * - VOL_STATE_SHUTTING_DOWN
2795 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
2796 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN) ||
2797 (V_attachState(vp) == VOL_STATE_GOING_OFFLINE)) {
2804 * short circuit with VOFFLINE in the following circumstances:
2806 * - VOL_STATE_UNATTACHED
2808 if (V_attachState(vp) == VOL_STATE_UNATTACHED) {
2809 if (vp->specialStatus) {
2810 *ec = vp->specialStatus;
2818 /* allowable states:
2824 if (vp->salvage.requested) {
2825 VUpdateSalvagePriority_r(vp);
2828 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
2829 avp = VAttachVolumeByVp_r(ec, vp, 0);
2832 /* VAttachVolumeByVp_r can return a pointer
2833 * != the vp passed to it under certain
2834 * conditions; make sure we don't leak
2835 * reservations if that happens */
2837 VCancelReservation_r(rvp);
2839 VCreateReservation_r(rvp);
2849 if (!vp->pending_vol_op) {
2864 if ((V_attachState(vp) == VOL_STATE_SALVAGING) ||
2865 (*ec == VSALVAGING)) {
2867 /* see CheckVnode() in afsfileprocs.c for an explanation
2868 * of this error code logic */
2869 afs_uint32 now = FT_ApproxTime();
2870 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
2873 *client_ec = VRESTARTING;
2882 LoadVolumeHeader(ec, vp);
2885 /* Only log the error if it was a totally unexpected error. Simply
2886 * a missing inode is likely to be caused by the volume being deleted */
2887 if (errno != ENXIO || LogLevel)
2888 Log("Volume %u: couldn't reread volume header\n",
2890 #ifdef AFS_DEMAND_ATTACH_FS
2891 if (programType == fileServer) {
2892 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2897 #else /* AFS_DEMAND_ATTACH_FS */
2900 #endif /* AFS_DEMAND_ATTACH_FS */
2904 #ifdef AFS_DEMAND_ATTACH_FS
2906 * this test MUST happen after the volume header is loaded
2909 /* only valid before/during demand attachment */
2910 assert(!vp->pending_vol_op || vp->pending_vol_op != FSSYNC_VolOpRunningUnknown);
2912 /* deny getvolume due to running mutually exclusive vol op */
2913 if (vp->pending_vol_op && vp->pending_vol_op->vol_op_state==FSSYNC_VolOpRunningOffline) {
2915 * volume cannot remain online during this volume operation.
2918 if (vp->specialStatus) {
2920 * special status codes outrank normal VOFFLINE code
2922 *ec = vp->specialStatus;
2924 *client_ec = vp->specialStatus;
2928 /* see CheckVnode() in afsfileprocs.c for an explanation
2929 * of this error code logic */
2930 afs_uint32 now = FT_ApproxTime();
2931 if ((vp->stats.last_vol_op + (10 * 60)) >= now) {
2934 *client_ec = VRESTARTING;
2939 VChangeState_r(vp, VOL_STATE_UNATTACHED);
2940 FreeVolumeHeader(vp);
2944 #endif /* AFS_DEMAND_ATTACH_FS */
2947 if (vp->shuttingDown) {
2954 if (programType == fileServer) {
2956 if (vp->goingOffline) {
2958 #ifdef AFS_DEMAND_ATTACH_FS
2959 /* wait for the volume to go offline */
2960 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
2961 VWaitStateChange_r(vp);
2963 #elif defined(AFS_PTHREAD_ENV)
2964 VOL_CV_WAIT(&vol_put_volume_cond);
2965 #else /* AFS_PTHREAD_ENV */
2966 LWP_WaitProcess(VPutVolume);
2967 #endif /* AFS_PTHREAD_ENV */
2970 if (vp->specialStatus) {
2972 *ec = vp->specialStatus;
2973 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
2976 } else if (V_inUse(vp) == 0) {
2987 #ifdef AFS_DEMAND_ATTACH_FS
2988 /* if no error, bump nUsers */
2991 VLRU_UpdateAccess_r(vp);
2994 VCancelReservation_r(rvp);
2997 if (client_ec && !*client_ec) {
3000 #else /* AFS_DEMAND_ATTACH_FS */
3001 /* if no error, bump nUsers */
3008 #endif /* AFS_DEMAND_ATTACH_FS */
3016 /***************************************************/
3017 /* Volume offline/detach routines */
3018 /***************************************************/
3020 /* caller MUST hold a heavyweight ref on vp */
3021 #ifdef AFS_DEMAND_ATTACH_FS
3023 VTakeOffline_r(register Volume * vp)
3027 assert(vp->nUsers > 0);
3028 assert(programType == fileServer);
3030 VCreateReservation_r(vp);
3031 VWaitExclusiveState_r(vp);
3033 vp->goingOffline = 1;
3034 V_needsSalvaged(vp) = 1;
3036 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
3037 VCancelReservation_r(vp);
3039 #else /* AFS_DEMAND_ATTACH_FS */
3041 VTakeOffline_r(register Volume * vp)
3043 assert(vp->nUsers > 0);
3044 assert(programType == fileServer);
3046 vp->goingOffline = 1;
3047 V_needsSalvaged(vp) = 1;
3049 #endif /* AFS_DEMAND_ATTACH_FS */
3052 VTakeOffline(register Volume * vp)
3060 * force a volume offline.
3062 * @param[in] vp volume object pointer
3063 * @param[in] flags flags (see note below)
3065 * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
3066 * used when VUpdateVolume_r needs to call VForceOffline_r
3067 * (which in turn would normally call VUpdateVolume_r)
3069 * @see VUpdateVolume_r
3071 * @pre VOL_LOCK must be held.
3072 * for DAFS, caller must hold ref.
3074 * @note for DAFS, it _is safe_ to call this function from an
3077 * @post needsSalvaged flag is set.
3078 * for DAFS, salvage is requested.
3079 * no further references to the volume through the volume
3080 * package will be honored.
3081 * all file descriptor and vnode caches are invalidated.
3083 * @warning this is a heavy-handed interface. it results in
3084 * a volume going offline regardless of the current
3085 * reference count state.
3087 * @internal volume package internal use only
3090 VForceOffline_r(Volume * vp, int flags)
3094 #ifdef AFS_DEMAND_ATTACH_FS
3095 VChangeState_r(vp, VOL_STATE_ERROR);
3100 strcpy(V_offlineMessage(vp),
3101 "Forced offline due to internal error: volume needs to be salvaged");
3102 Log("Volume %u forced offline: it needs salvaging!\n", V_id(vp));
3105 vp->goingOffline = 0;
3106 V_needsSalvaged(vp) = 1;
3107 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
3108 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
3111 #ifdef AFS_DEMAND_ATTACH_FS
3112 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3113 #endif /* AFS_DEMAND_ATTACH_FS */
3115 #ifdef AFS_PTHREAD_ENV
3116 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3117 #else /* AFS_PTHREAD_ENV */
3118 LWP_NoYieldSignal(VPutVolume);
3119 #endif /* AFS_PTHREAD_ENV */
3121 VReleaseVolumeHandles_r(vp);
3125 * force a volume offline.
3127 * @param[in] vp volume object pointer
3129 * @see VForceOffline_r
3132 VForceOffline(Volume * vp)
3135 VForceOffline_r(vp, 0);
3139 /* The opposite of VAttachVolume. The volume header is written to disk, with
3140 the inUse bit turned off. A copy of the header is maintained in memory,
3141 however (which is why this is VOffline, not VDetach).
3144 VOffline_r(Volume * vp, char *message)
3147 VolumeId vid = V_id(vp);
3149 assert(programType != volumeUtility);
3154 if (V_offlineMessage(vp)[0] == '\0')
3155 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
3156 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
3158 vp->goingOffline = 1;
3159 #ifdef AFS_DEMAND_ATTACH_FS
3160 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
3161 VCreateReservation_r(vp);
3164 /* wait for the volume to go offline */
3165 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
3166 VWaitStateChange_r(vp);
3168 VCancelReservation_r(vp);
3169 #else /* AFS_DEMAND_ATTACH_FS */
3171 vp = VGetVolume_r(&error, vid); /* Wait for it to go offline */
3172 if (vp) /* In case it was reattached... */
3174 #endif /* AFS_DEMAND_ATTACH_FS */
3177 #ifdef AFS_DEMAND_ATTACH_FS
3179 * Take a volume offline in order to perform a volume operation.
3181 * @param[inout] ec address in which to store error code
3182 * @param[in] vp volume object pointer
3183 * @param[in] message volume offline status message
3186 * - VOL_LOCK is held
3187 * - caller MUST hold a heavyweight ref on vp
3190 * - volume is taken offline
3191 * - if possible, volume operation is promoted to running state
3192 * - on failure, *ec is set to nonzero
3194 * @note Although this function does not return any value, it may
3195 * still fail to promote our pending volume operation to
3196 * a running state. Any caller MUST check the value of *ec,
3197 * and MUST NOT blindly assume success.
3199 * @warning if the caller does not hold a lightweight ref on vp,
3200 * then it MUST NOT reference vp after this function
3201 * returns to the caller.
3203 * @internal volume package internal use only
3206 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
3208 assert(vp->pending_vol_op);
3214 if (V_offlineMessage(vp)[0] == '\0')
3215 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
3216 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
3218 vp->goingOffline = 1;
3219 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
3220 VCreateReservation_r(vp);
3223 /* Wait for the volume to go offline */
3224 while (!VIsOfflineState(V_attachState(vp))) {
3225 /* do not give corrupted volumes to the volserver */
3226 if (vp->salvage.requested && vp->pending_vol_op->com.programType != salvageServer) {
3230 VWaitStateChange_r(vp);
3234 VCancelReservation_r(vp);
3236 #endif /* AFS_DEMAND_ATTACH_FS */
3239 VOffline(Volume * vp, char *message)
3242 VOffline_r(vp, message);
3246 /* This gets used for the most part by utility routines that don't want
3247 * to keep all the volume headers around. Generally, the file server won't
3248 * call this routine, because then the offline message in the volume header
3249 * (or other information) won't be available to clients. For NAMEI, also
3250 * close the file handles. However, the fileserver does call this during
3251 * an attach following a volume operation.
3254 VDetachVolume_r(Error * ec, Volume * vp)
3257 struct DiskPartition64 *tpartp;
3258 int notifyServer = 0;
3259 int useDone = FSYNC_VOL_ON;
3261 *ec = 0; /* always "succeeds" */
3262 if (programType == volumeUtility) {
3263 notifyServer = vp->needsPutBack;
3264 if (V_destroyMe(vp) == DESTROY_ME)
3265 useDone = FSYNC_VOL_DONE;
3266 #ifdef AFS_DEMAND_ATTACH_FS
3267 else if (!V_blessed(vp) || !V_inService(vp))
3268 useDone = FSYNC_VOL_LEAVE_OFF;
3271 tpartp = vp->partition;
3273 DeleteVolumeFromHashTable(vp);
3274 vp->shuttingDown = 1;
3275 #ifdef AFS_DEMAND_ATTACH_FS
3276 DeleteVolumeFromVByPList_r(vp);
3278 VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
3280 if (programType != fileServer)
3282 #endif /* AFS_DEMAND_ATTACH_FS */
3284 /* Will be detached sometime in the future--this is OK since volume is offline */
3286 /* XXX the following code should really be moved to VCheckDetach() since the volume
3287 * is not technically detached until the refcounts reach zero
3289 #ifdef FSSYNC_BUILD_CLIENT
3290 if (programType == volumeUtility && notifyServer) {
3292 * Note: The server is not notified in the case of a bogus volume
3293 * explicitly to make it possible to create a volume, do a partial
3294 * restore, then abort the operation without ever putting the volume
3295 * online. This is essential in the case of a volume move operation
3296 * between two partitions on the same server. In that case, there
3297 * would be two instances of the same volume, one of them bogus,
3298 * which the file server would attempt to put on line
3300 FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
3301 /* XXX this code path is only hit by volume utilities, thus
3302 * V_BreakVolumeCallbacks will always be NULL. if we really
3303 * want to break callbacks in this path we need to use FSYNC_VolOp() */
3305 /* Dettaching it so break all callbacks on it */
3306 if (V_BreakVolumeCallbacks) {
3307 Log("volume %u detached; breaking all call backs\n", volume);
3308 (*V_BreakVolumeCallbacks) (volume);
3312 #endif /* FSSYNC_BUILD_CLIENT */
3316 VDetachVolume(Error * ec, Volume * vp)
3319 VDetachVolume_r(ec, vp);
3324 /***************************************************/
3325 /* Volume fd/inode handle closing routines */
3326 /***************************************************/
3328 /* For VDetachVolume, we close all cached file descriptors, but keep
3329 * the Inode handles in case we need to read from a busy volume.
3331 /* for demand attach, caller MUST hold ref count on vp */
3333 VCloseVolumeHandles_r(Volume * vp)
3335 #ifdef AFS_DEMAND_ATTACH_FS
3336 VolState state_save;
3338 state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
3343 * XXX need to investigate whether we can perform
3344 * DFlushVolume outside of vol_glock_mutex...
3346 * VCloseVnodeFiles_r drops the glock internally */
3347 DFlushVolume(V_id(vp));
3348 VCloseVnodeFiles_r(vp);
3350 #ifdef AFS_DEMAND_ATTACH_FS
3354 /* Too time consuming and unnecessary for the volserver */
3355 if (programType != volumeUtility) {
3356 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
3357 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
3358 IH_CONDSYNC(vp->diskDataHandle);
3360 IH_CONDSYNC(vp->linkHandle);
3361 #endif /* AFS_NT40_ENV */
3364 IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
3365 IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
3366 IH_REALLYCLOSE(vp->diskDataHandle);
3367 IH_REALLYCLOSE(vp->linkHandle);
3369 #ifdef AFS_DEMAND_ATTACH_FS
3371 VChangeState_r(vp, state_save);
3375 /* For both VForceOffline and VOffline, we close all relevant handles.
3376 * For VOffline, if we re-attach the volume, the files may possible be
3377 * different than before.
3379 /* for demand attach, caller MUST hold a ref count on vp */
3381 VReleaseVolumeHandles_r(Volume * vp)
3383 #ifdef AFS_DEMAND_ATTACH_FS
3384 VolState state_save;
3386 state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
3389 /* XXX need to investigate whether we can perform
3390 * DFlushVolume outside of vol_glock_mutex... */
3391 DFlushVolume(V_id(vp));
3393 VReleaseVnodeFiles_r(vp); /* releases the glock internally */
3395 #ifdef AFS_DEMAND_ATTACH_FS
3399 /* Too time consuming and unnecessary for the volserver */
3400 if (programType != volumeUtility) {
3401 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
3402 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
3403 IH_CONDSYNC(vp->diskDataHandle);
3405 IH_CONDSYNC(vp->linkHandle);
3406 #endif /* AFS_NT40_ENV */
3409 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
3410 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
3411 IH_RELEASE(vp->diskDataHandle);
3412 IH_RELEASE(vp->linkHandle);
3414 #ifdef AFS_DEMAND_ATTACH_FS
3416 VChangeState_r(vp, state_save);
3421 /***************************************************/
3422 /* Volume write and fsync routines */
3423 /***************************************************/
3426 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
3428 #ifdef AFS_DEMAND_ATTACH_FS
3429 VolState state_save;
3431 if (flags & VOL_UPDATE_WAIT) {
3432 VCreateReservation_r(vp);
3433 VWaitExclusiveState_r(vp);
3438 if (programType == fileServer)
3440 (V_inUse(vp) ? V_nextVnodeUnique(vp) +
3441 200 : V_nextVnodeUnique(vp));
3443 #ifdef AFS_DEMAND_ATTACH_FS
3444 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
3448 WriteVolumeHeader_r(ec, vp);
3450 #ifdef AFS_DEMAND_ATTACH_FS
3452 VChangeState_r(vp, state_save);
3453 if (flags & VOL_UPDATE_WAIT) {
3454 VCancelReservation_r(vp);
3459 Log("VUpdateVolume: error updating volume header, volume %u (%s)\n",
3460 V_id(vp), V_name(vp));
3461 /* try to update on-disk header,
3462 * while preventing infinite recursion */
3463 if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
3464 VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
3470 VUpdateVolume(Error * ec, Volume * vp)
3473 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
3478 VSyncVolume_r(Error * ec, Volume * vp, int flags)
3482 #ifdef AFS_DEMAND_ATTACH_FS
3483 VolState state_save;
3486 if (flags & VOL_SYNC_WAIT) {
3487 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
3489 VUpdateVolume_r(ec, vp, 0);
3492 #ifdef AFS_DEMAND_ATTACH_FS
3493 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
3496 fdP = IH_OPEN(V_diskDataHandle(vp));
3497 assert(fdP != NULL);
3498 code = FDH_SYNC(fdP);
3501 #ifdef AFS_DEMAND_ATTACH_FS
3503 VChangeState_r(vp, state_save);
3509 VSyncVolume(Error * ec, Volume * vp)
3512 VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
3517 /***************************************************/
3518 /* Volume dealloaction routines */
3519 /***************************************************/
3521 #ifdef AFS_DEMAND_ATTACH_FS
3523 FreeVolume(Volume * vp)
3525 /* free the heap space, iff it's safe.
3526 * otherwise, pull it out of the hash table, so it
3527 * will get deallocated when all refs to it go away */
3528 if (!VCheckFree(vp)) {
3529 DeleteVolumeFromHashTable(vp);
3530 DeleteVolumeFromVByPList_r(vp);
3532 /* make sure we invalidate the header cache entry */
3533 FreeVolumeHeader(vp);
3536 #endif /* AFS_DEMAND_ATTACH_FS */
3539 ReallyFreeVolume(Volume * vp)
3544 #ifdef AFS_DEMAND_ATTACH_FS
3546 VChangeState_r(vp, VOL_STATE_FREED);
3547 if (vp->pending_vol_op)
3548 free(vp->pending_vol_op);
3549 #endif /* AFS_DEMAND_ATTACH_FS */
3550 for (i = 0; i < nVNODECLASSES; i++)
3551 if (vp->vnodeIndex[i].bitmap)
3552 free(vp->vnodeIndex[i].bitmap);
3553 FreeVolumeHeader(vp);
3554 #ifndef AFS_DEMAND_ATTACH_FS
3555 DeleteVolumeFromHashTable(vp);
3556 #endif /* AFS_DEMAND_ATTACH_FS */
3560 /* check to see if we should shutdown this volume
3561 * returns 1 if volume was freed, 0 otherwise */
3562 #ifdef AFS_DEMAND_ATTACH_FS
3564 VCheckDetach(register Volume * vp)
3569 if (vp->nUsers || vp->nWaiters)
3572 if (vp->shuttingDown) {
3574 if ((programType != fileServer) &&
3575 (V_inUse(vp) == programType) &&
3576 ((V_checkoutMode(vp) == V_VOLUPD) ||
3577 ((V_checkoutMode(vp) == V_CLONE) &&
3578 (VolumeWriteable(vp))))) {
3580 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
3582 Log("VCheckDetach: volume header update for volume %u "
3583 "failed with errno %d\n", vp->hashid, errno);
3586 VReleaseVolumeHandles_r(vp);
3588 ReallyFreeVolume(vp);
3589 if (programType == fileServer) {
3590 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3595 #else /* AFS_DEMAND_ATTACH_FS */
3597 VCheckDetach(register Volume * vp)
3605 if (vp->shuttingDown) {
3607 if ((programType != fileServer) &&
3608 (V_inUse(vp) == programType) &&
3609 ((V_checkoutMode(vp) == V_VOLUPD) ||
3610 ((V_checkoutMode(vp) == V_CLONE) &&
3611 (VolumeWriteable(vp))))) {
3613 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
3615 Log("VCheckDetach: volume header update for volume %u failed with errno %d\n",
3619 VReleaseVolumeHandles_r(vp);
3620 ReallyFreeVolume(vp);
3621 if (programType == fileServer) {
3622 #if defined(AFS_PTHREAD_ENV)
3623 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3624 #else /* AFS_PTHREAD_ENV */
3625 LWP_NoYieldSignal(VPutVolume);
3626 #endif /* AFS_PTHREAD_ENV */
3631 #endif /* AFS_DEMAND_ATTACH_FS */
3633 /* check to see if we should offline this volume
3634 * return 1 if volume went offline, 0 otherwise */
3635 #ifdef AFS_DEMAND_ATTACH_FS
3637 VCheckOffline(register Volume * vp)
3641 if (vp->goingOffline && !vp->nUsers) {
3643 assert(programType == fileServer);
3644 assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
3645 (V_attachState(vp) != VOL_STATE_FREED) &&
3646 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
3647 (V_attachState(vp) != VOL_STATE_UNATTACHED));
3651 * VOL_STATE_GOING_OFFLINE
3652 * VOL_STATE_SHUTTING_DOWN
3653 * VIsErrorState(V_attachState(vp))
3654 * VIsExclusiveState(V_attachState(vp))
3657 VCreateReservation_r(vp);
3658 VChangeState_r(vp, VOL_STATE_OFFLINING);
3661 /* must clear the goingOffline flag before we drop the glock */
3662 vp->goingOffline = 0;
3667 /* perform async operations */
3668 VUpdateVolume_r(&error, vp, 0);
3669 VCloseVolumeHandles_r(vp);
3672 Log("VOffline: Volume %u (%s) is now offline", V_id(vp),
3674 if (V_offlineMessage(vp)[0])
3675 Log(" (%s)", V_offlineMessage(vp));
3679 /* invalidate the volume header cache entry */
3680 FreeVolumeHeader(vp);
3682 /* if nothing changed state to error or salvaging,
3683 * drop state to unattached */
3684 if (!VIsErrorState(V_attachState(vp))) {
3685 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3687 VCancelReservation_r(vp);
3688 /* no usage of vp is safe beyond this point */
3692 #else /* AFS_DEMAND_ATTACH_FS */
3694 VCheckOffline(register Volume * vp)
3696 Volume * rvp = NULL;
3699 if (vp->goingOffline && !vp->nUsers) {
3701 assert(programType == fileServer);
3704 vp->goingOffline = 0;
3706 VUpdateVolume_r(&error, vp, 0);
3707 VCloseVolumeHandles_r(vp);
3709 Log("VOffline: Volume %u (%s) is now offline", V_id(vp),
3711 if (V_offlineMessage(vp)[0])
3712 Log(" (%s)", V_offlineMessage(vp));
3715 FreeVolumeHeader(vp);
3716 #ifdef AFS_PTHREAD_ENV
3717 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3718 #else /* AFS_PTHREAD_ENV */
3719 LWP_NoYieldSignal(VPutVolume);
3720 #endif /* AFS_PTHREAD_ENV */
3724 #endif /* AFS_DEMAND_ATTACH_FS */
3726 /***************************************************/
3727 /* demand attach fs ref counting routines */
3728 /***************************************************/
3730 #ifdef AFS_DEMAND_ATTACH_FS
3731 /* the following two functions handle reference counting for
3732 * asynchronous operations on volume structs.
3734 * their purpose is to prevent a VDetachVolume or VShutdown
3735 * from free()ing the Volume struct during an async i/o op */
3737 /* register with the async volume op ref counter */
3738 /* VCreateReservation_r moved into inline code header because it
3739 * is now needed in vnode.c -- tkeiser 11/20/2007
3743 * decrement volume-package internal refcount.
3745 * @param vp volume object pointer
3747 * @internal volume package internal use only
3750 * @arg VOL_LOCK is held
3751 * @arg lightweight refcount held
3753 * @post volume waiters refcount is decremented; volume may
3754 * have been deallocated/shutdown/offlined/salvaged/
3755 * whatever during the process
3757 * @warning once you have tossed your last reference (you can acquire
3758 * lightweight refs recursively) it is NOT SAFE to reference
3759 * a volume object pointer ever again
3761 * @see VCreateReservation_r
3763 * @note DEMAND_ATTACH_FS only
3766 VCancelReservation_r(Volume * vp)
3768 assert(--vp->nWaiters >= 0);
3769 if (vp->nWaiters == 0) {
3771 if (!VCheckDetach(vp)) {
3778 /* check to see if we should free this volume now
3779 * return 1 if volume was freed, 0 otherwise */
3781 VCheckFree(Volume * vp)
3784 if ((vp->nUsers == 0) &&
3785 (vp->nWaiters == 0) &&
3786 !(V_attachFlags(vp) & (VOL_IN_HASH |
3790 ReallyFreeVolume(vp);
3795 #endif /* AFS_DEMAND_ATTACH_FS */
3798 /***************************************************/
3799 /* online volume operations routines */
3800 /***************************************************/
3802 #ifdef AFS_DEMAND_ATTACH_FS
3804 * register a volume operation on a given volume.
3806 * @param[in] vp volume object
3807 * @param[in] vopinfo volume operation info object
3809 * @pre VOL_LOCK is held
3811 * @post volume operation info object attached to volume object.
3812 * volume operation statistics updated.
3814 * @note by "attached" we mean a copy of the passed in object is made
3816 * @internal volume package internal use only
3819 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3821 FSSYNC_VolOp_info * info;
3823 /* attach a vol op info node to the volume struct */
3824 info = (FSSYNC_VolOp_info *) malloc(sizeof(FSSYNC_VolOp_info));
3825 assert(info != NULL);
3826 memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
3827 vp->pending_vol_op = info;
3830 vp->stats.last_vol_op = FT_ApproxTime();
3831 vp->stats.vol_ops++;
3832 IncUInt64(&VStats.vol_ops);
3838 * deregister the volume operation attached to this volume.
3840 * @param[in] vp volume object pointer
3842 * @pre VOL_LOCK is held
3844 * @post the volume operation info object is detached from the volume object
3846 * @internal volume package internal use only
3849 VDeregisterVolOp_r(Volume * vp)
3851 if (vp->pending_vol_op) {
3852 free(vp->pending_vol_op);
3853 vp->pending_vol_op = NULL;
3857 #endif /* AFS_DEMAND_ATTACH_FS */
3860 * determine whether it is safe to leave a volume online during
3861 * the volume operation described by the vopinfo object.
3863 * @param[in] vp volume object
3864 * @param[in] vopinfo volume operation info object
3866 * @return whether it is safe to leave volume online
3867 * @retval 0 it is NOT SAFE to leave the volume online
3868 * @retval 1 it is safe to leave the volume online during the operation
3871 * @arg VOL_LOCK is held
3872 * @arg disk header attached to vp (heavyweight ref on vp will guarantee
3873 * this condition is met)
3875 * @internal volume package internal use only
3878 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3880 return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
3881 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
3882 (vopinfo->com.reason == V_READONLY ||
3883 (!VolumeWriteable(vp) &&
3884 (vopinfo->com.reason == V_CLONE ||
3885 vopinfo->com.reason == V_DUMP)))));
3889 * determine whether VBUSY should be set during this volume operation.
3891 * @param[in] vp volume object
3892 * @param[in] vopinfo volume operation info object
3894 * @return whether VBUSY should be set
3895 * @retval 0 VBUSY does NOT need to be set
3896 * @retval 1 VBUSY SHOULD be set
3898 * @pre VOL_LOCK is held
3900 * @internal volume package internal use only
3903 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3905 return ((vopinfo->com.command == FSYNC_VOL_OFF &&
3906 vopinfo->com.reason == FSYNC_SALVAGE) ||
3907 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
3908 (vopinfo->com.reason == V_CLONE ||
3909 vopinfo->com.reason == V_DUMP)));
3913 /***************************************************/
3914 /* online salvager routines */
3915 /***************************************************/
3916 #if defined(AFS_DEMAND_ATTACH_FS)
3917 #define SALVAGE_PRIO_UPDATE_INTERVAL 3 /**< number of seconds between prio updates */
3918 #define SALVAGE_COUNT_MAX 16 /**< number of online salvages we
3919 * allow before moving the volume
3920 * into a permanent error state
3922 * once this threshold is reached,
3923 * the operator will have to manually
3924 * issue a 'bos salvage' to bring
3925 * the volume back online
3929 * check whether a salvage needs to be performed on this volume.
3931 * @param[in] vp pointer to volume object
3933 * @return status code
3934 * @retval 0 no salvage scheduled
3935 * @retval 1 a salvage has been scheduled with the salvageserver
3937 * @pre VOL_LOCK is held
3939 * @post if salvage request flag is set and nUsers and nWaiters are zero,
3940 * then a salvage will be requested
3942 * @note this is one of the event handlers called by VCancelReservation_r
3944 * @see VCancelReservation_r
3946 * @internal volume package internal use only.
3949 VCheckSalvage(register Volume * vp)
3952 #ifdef SALVSYNC_BUILD_CLIENT
3953 if (vp->nUsers || vp->nWaiters)
3955 if (vp->salvage.requested) {
3956 VScheduleSalvage_r(vp);
3959 #endif /* SALVSYNC_BUILD_CLIENT */
3964 * request volume salvage.
3966 * @param[out] ec computed client error code
3967 * @param[in] vp volume object pointer
3968 * @param[in] reason reason code (passed to salvageserver via SALVSYNC)
3969 * @param[in] flags see flags note below
3972 * VOL_SALVAGE_INVALIDATE_HEADER causes volume header cache entry
3973 * to be invalidated.
3975 * @pre VOL_LOCK is held.
3977 * @post volume state is changed.
3978 * for fileserver, salvage will be requested once refcount reaches zero.
3980 * @return operation status code
3981 * @retval 0 volume salvage will occur
3982 * @retval 1 volume salvage could not be scheduled
3984 * @note DAFS fileserver only
3986 * @note this call does not synchronously schedule a volume salvage. rather,
3987 * it sets volume state so that when volume refcounts reach zero, a
3988 * volume salvage will occur. by "refcounts", we mean both nUsers and
3989 * nWaiters must be zero.
3991 * @internal volume package internal use only.
3994 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
3998 * for DAFS volume utilities, transition to error state
3999 * (at some point in the future, we should consider
4000 * making volser talk to salsrv)
4002 if (programType != fileServer) {
4003 VChangeState_r(vp, VOL_STATE_ERROR);
4008 if (!vp->salvage.requested) {
4009 vp->salvage.requested = 1;
4010 vp->salvage.reason = reason;
4011 vp->stats.last_salvage = FT_ApproxTime();
4012 if (flags & VOL_SALVAGE_INVALIDATE_HEADER) {
4013 /* Instead of ReleaseVolumeHeader, we do FreeVolumeHeader()
4014 so that the the next VAttachVolumeByVp_r() invocation
4015 of attach2() will pull in a cached header
4016 entry and fail, then load a fresh one from disk and attach
4019 FreeVolumeHeader(vp);
4021 if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
4022 VChangeState_r(vp, VOL_STATE_SALVAGING);
4025 Log("VRequestSalvage: volume %u online salvaged too many times; forced offline.\n", vp->hashid);
4026 VChangeState_r(vp, VOL_STATE_ERROR);
4035 * update salvageserver scheduling priority for a volume.
4037 * @param[in] vp pointer to volume object
4039 * @return operation status
4041 * @retval 1 request denied, or SALVSYNC communications failure
4043 * @pre VOL_LOCK is held.
4045 * @post in-core salvage priority counter is incremented. if at least
4046 * SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
4047 * last SALVSYNC_RAISEPRIO request, we contact the salvageserver
4048 * to update its priority queue. if no salvage is scheduled,
4049 * this function is a no-op.
4051 * @note DAFS fileserver only
4053 * @note this should be called whenever a VGetVolume fails due to a
4054 * pending salvage request
4056 * @todo should set exclusive state and drop glock around salvsync call
4058 * @internal volume package internal use only.
4061 VUpdateSalvagePriority_r(Volume * vp)
4066 #ifdef SALVSYNC_BUILD_CLIENT
4068 now = FT_ApproxTime();
4070 /* update the salvageserver priority queue occasionally so that
4071 * frequently requested volumes get moved to the head of the queue
4073 if ((vp->salvage.scheduled) &&
4074 (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
4075 code = SALVSYNC_SalvageVolume(vp->hashid,
4076 VPartitionPath(vp->partition),
4081 vp->stats.last_salvage_req = now;
4082 if (code != SYNC_OK) {
4086 #endif /* SALVSYNC_BUILD_CLIENT */
4092 * schedule a salvage with the salvage server.
4094 * @param[in] vp pointer to volume object
4096 * @return operation status
4097 * @retval 0 salvage scheduled successfully
4098 * @retval 1 salvage not scheduled, or SALVSYNC com error
4101 * @arg VOL_LOCK is held.
4102 * @arg nUsers and nWaiters should be zero.
4104 * @post salvageserver is sent a salvage request
4106 * @note DAFS fileserver only
4108 * @internal volume package internal use only.
4111 VScheduleSalvage_r(Volume * vp)
4114 #ifdef SALVSYNC_BUILD_CLIENT
4115 VolState state_save;
4116 VThreadOptions_t * thread_opts;
4119 if (vp->nWaiters || vp->nUsers) {
4123 /* prevent endless salvage,attach,salvage,attach,... loops */
4124 if (vp->stats.salvages >= SALVAGE_COUNT_MAX)
4128 * don't perform salvsync ops on certain threads
4130 thread_opts = pthread_getspecific(VThread_key);
4131 if (thread_opts == NULL) {
4132 thread_opts = &VThread_defaults;
4134 if (thread_opts->disallow_salvsync) {
4139 * XXX the scheduling process should really be done asynchronously
4140 * to avoid fssync deadlocks
4142 if (!vp->salvage.scheduled) {
4143 /* if we haven't previously scheduled a salvage, do so now
4145 * set the volume to an exclusive state and drop the lock
4146 * around the SALVSYNC call
4148 * note that we do NOT acquire a reservation here -- doing so
4149 * could result in unbounded recursion
4151 strlcpy(partName, VPartitionPath(vp->partition), sizeof(partName));
4152 state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
4155 /* can't use V_id() since there's no guarantee
4156 * we have the disk data header at this point */
4157 code = SALVSYNC_SalvageVolume(vp->hashid,
4164 VChangeState_r(vp, state_save);
4166 if (code == SYNC_OK) {
4167 vp->salvage.scheduled = 1;
4168 vp->stats.salvages++;
4169 vp->stats.last_salvage_req = FT_ApproxTime();
4170 IncUInt64(&VStats.salvages);
4174 case SYNC_BAD_COMMAND:
4175 case SYNC_COM_ERROR:
4178 Log("VScheduleSalvage_r: SALVSYNC request denied\n");
4181 Log("VScheduleSalvage_r: SALVSYNC unknown protocol error\n");
4186 #endif /* SALVSYNC_BUILD_CLIENT */
4191 * ask salvageserver to cancel a scheduled salvage operation.
4193 * @param[in] vp pointer to volume object
4194 * @param[in] reason SALVSYNC protocol reason code
4196 * @return operation status
4198 * @retval 1 request failed
4200 * @pre VOL_LOCK is held.
4202 * @post salvageserver is sent a request to cancel the volume salvage.
4203 * volume is transitioned to a hard error state.
4205 * @internal volume package internal use only.
4208 VCancelSalvage_r(Volume * vp, int reason)
4212 #ifdef SALVSYNC_BUILD_CLIENT
4213 if (vp->salvage.scheduled) {
4214 VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
4217 /* can't use V_id() since there's no guarantee
4218 * we have the disk data header at this point */
4219 code = SALVSYNC_SalvageVolume(vp->hashid,
4220 VPartitionPath(vp->partition),
4227 VChangeState_r(vp, VOL_STATE_ERROR);
4229 if (code == SYNC_OK) {
4230 vp->salvage.scheduled = 0;
4231 vp->salvage.requested = 0;
4236 #endif /* SALVSYNC_BUILD_CLIENT */
4241 #ifdef SALVSYNC_BUILD_CLIENT
4243 * connect to the salvageserver SYNC service.
4245 * @return operation status
4249 * @post connection to salvageserver SYNC service established
4251 * @see VConnectSALV_r
4252 * @see VDisconnectSALV
4253 * @see VReconnectSALV
4260 retVal = VConnectSALV_r();
4266 * connect to the salvageserver SYNC service.
4268 * @return operation status
4272 * @pre VOL_LOCK is held.
4274 * @post connection to salvageserver SYNC service established
4277 * @see VDisconnectSALV_r
4278 * @see VReconnectSALV_r
4279 * @see SALVSYNC_clientInit
4281 * @internal volume package internal use only.
4284 VConnectSALV_r(void)
4286 return SALVSYNC_clientInit();
4290 * disconnect from the salvageserver SYNC service.
4292 * @return operation status
4295 * @pre client should have a live connection to the salvageserver
4297 * @post connection to salvageserver SYNC service destroyed
4299 * @see VDisconnectSALV_r
4301 * @see VReconnectSALV
4304 VDisconnectSALV(void)
4308 VDisconnectSALV_r();
4314 * disconnect from the salvageserver SYNC service.
4316 * @return operation status
4320 * @arg VOL_LOCK is held.
4321 * @arg client should have a live connection to the salvageserver.
4323 * @post connection to salvageserver SYNC service destroyed
4325 * @see VDisconnectSALV
4326 * @see VConnectSALV_r
4327 * @see VReconnectSALV_r
4328 * @see SALVSYNC_clientFinis
4330 * @internal volume package internal use only.
4333 VDisconnectSALV_r(void)
4335 return SALVSYNC_clientFinis();
4339 * disconnect and then re-connect to the salvageserver SYNC service.
4341 * @return operation status
4345 * @pre client should have a live connection to the salvageserver
4347 * @post old connection is dropped, and a new one is established
4350 * @see VDisconnectSALV
4351 * @see VReconnectSALV_r
4354 VReconnectSALV(void)
4358 retVal = VReconnectSALV_r();
4364 * disconnect and then re-connect to the salvageserver SYNC service.
4366 * @return operation status
4371 * @arg VOL_LOCK is held.
4372 * @arg client should have a live connection to the salvageserver.
4374 * @post old connection is dropped, and a new one is established
4376 * @see VConnectSALV_r
4377 * @see VDisconnectSALV
4378 * @see VReconnectSALV
4379 * @see SALVSYNC_clientReconnect
4381 * @internal volume package internal use only.
4384 VReconnectSALV_r(void)
4386 return SALVSYNC_clientReconnect();
4388 #endif /* SALVSYNC_BUILD_CLIENT */
4389 #endif /* AFS_DEMAND_ATTACH_FS */
4392 /***************************************************/
4393 /* FSSYNC routines */
4394 /***************************************************/
4396 /* This must be called by any volume utility which needs to run while the
4397 file server is also running. This is separated from VInitVolumePackage so
4398 that a utility can fork--and each of the children can independently
4399 initialize communication with the file server */
4400 #ifdef FSSYNC_BUILD_CLIENT
4402 * connect to the fileserver SYNC service.
4404 * @return operation status
4409 * @arg VInit must equal 2.
4410 * @arg Program Type must not be fileserver or salvager.
4412 * @post connection to fileserver SYNC service established
4415 * @see VDisconnectFS
4416 * @see VChildProcReconnectFS
4423 retVal = VConnectFS_r();
4429 * connect to the fileserver SYNC service.
4431 * @return operation status
4436 * @arg VInit must equal 2.
4437 * @arg Program Type must not be fileserver or salvager.
4438 * @arg VOL_LOCK is held.
4440 * @post connection to fileserver SYNC service established
4443 * @see VDisconnectFS_r
4444 * @see VChildProcReconnectFS_r
4446 * @internal volume package internal use only.
4452 assert((VInit == 2) &&
4453 (programType != fileServer) &&
4454 (programType != salvager));
4455 rc = FSYNC_clientInit();
4462 * disconnect from the fileserver SYNC service.
4465 * @arg client should have a live connection to the fileserver.
4466 * @arg VOL_LOCK is held.
4467 * @arg Program Type must not be fileserver or salvager.
4469 * @post connection to fileserver SYNC service destroyed
4471 * @see VDisconnectFS
4473 * @see VChildProcReconnectFS_r
4475 * @internal volume package internal use only.
4478 VDisconnectFS_r(void)
4480 assert((programType != fileServer) &&
4481 (programType != salvager));
4482 FSYNC_clientFinis();
4487 * disconnect from the fileserver SYNC service.
4490 * @arg client should have a live connection to the fileserver.
4491 * @arg Program Type must not be fileserver or salvager.
4493 * @post connection to fileserver SYNC service destroyed
4495 * @see VDisconnectFS_r
4497 * @see VChildProcReconnectFS
4508 * connect to the fileserver SYNC service from a child process following a fork.
4510 * @return operation status
4515 * @arg VOL_LOCK is held.
4516 * @arg current FSYNC handle is shared with a parent process
4518 * @post current FSYNC handle is discarded and a new connection to the
4519 * fileserver SYNC service is established
4521 * @see VChildProcReconnectFS
4523 * @see VDisconnectFS_r
4525 * @internal volume package internal use only.
4528 VChildProcReconnectFS_r(void)
4530 return FSYNC_clientChildProcReconnect();
4534 * connect to the fileserver SYNC service from a child process following a fork.
4536 * @return operation status
4540 * @pre current FSYNC handle is shared with a parent process
4542 * @post current FSYNC handle is discarded and a new connection to the
4543 * fileserver SYNC service is established
4545 * @see VChildProcReconnectFS_r
4547 * @see VDisconnectFS
4550 VChildProcReconnectFS(void)
4554 ret = VChildProcReconnectFS_r();
4558 #endif /* FSSYNC_BUILD_CLIENT */
4561 /***************************************************/
4562 /* volume bitmap routines */
4563 /***************************************************/
4566 * For demand attach fs, flags parameter controls
4567 * locking behavior. If (flags & VOL_ALLOC_BITMAP_WAIT)
4568 * is set, then this function will create a reservation
4569 * and block on any other exclusive operations. Otherwise,
4570 * this function assumes the caller already has exclusive
4571 * access to vp, and we just change the volume state.
4574 VAllocBitmapEntry_r(Error * ec, Volume * vp,
4575 struct vnodeIndex *index, int flags)
4578 register byte *bp, *ep;
4579 #ifdef AFS_DEMAND_ATTACH_FS
4580 VolState state_save;
4581 #endif /* AFS_DEMAND_ATTACH_FS */
4585 /* This test is probably redundant */
4586 if (!VolumeWriteable(vp)) {
4587 *ec = (bit32) VREADONLY;
4591 #ifdef AFS_DEMAND_ATTACH_FS
4592 if (flags & VOL_ALLOC_BITMAP_WAIT) {
4593 VCreateReservation_r(vp);
4594 VWaitExclusiveState_r(vp);
4596 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
4597 #endif /* AFS_DEMAND_ATTACH_FS */
4600 if ((programType == fileServer) && !index->bitmap) {
4602 #ifndef AFS_DEMAND_ATTACH_FS
4603 /* demand attach fs uses the volume state to avoid races.
4604 * specialStatus field is not used at all */
4606 if (vp->specialStatus == VBUSY) {
4607 if (vp->goingOffline) { /* vos dump waiting for the volume to
4608 * go offline. We probably come here
4609 * from AddNewReadableResidency */
4612 while (vp->specialStatus == VBUSY) {
4613 #ifdef AFS_PTHREAD_ENV
4617 #else /* !AFS_PTHREAD_ENV */
4619 #endif /* !AFS_PTHREAD_ENV */
4623 #endif /* !AFS_DEMAND_ATTACH_FS */
4625 if (!index->bitmap) {
4626 #ifndef AFS_DEMAND_ATTACH_FS
4627 vp->specialStatus = VBUSY; /* Stop anyone else from using it. */
4628 #endif /* AFS_DEMAND_ATTACH_FS */
4629 for (i = 0; i < nVNODECLASSES; i++) {
4630 VGetBitmap_r(ec, vp, i);
4632 #ifdef AFS_DEMAND_ATTACH_FS
4633 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
4634 #else /* AFS_DEMAND_ATTACH_FS */
4635 DeleteVolumeFromHashTable(vp);
4636 vp->shuttingDown = 1; /* Let who has it free it. */
4637 vp->specialStatus = 0;
4638 #endif /* AFS_DEMAND_ATTACH_FS */
4643 #ifndef AFS_DEMAND_ATTACH_FS
4645 vp->specialStatus = 0; /* Allow others to have access. */
4646 #endif /* AFS_DEMAND_ATTACH_FS */
4649 #endif /* BITMAP_LATER */
4651 #ifdef AFS_DEMAND_ATTACH_FS
4653 #endif /* AFS_DEMAND_ATTACH_FS */
4654 bp = index->bitmap + index->bitmapOffset;
4655 ep = index->bitmap + index->bitmapSize;
4657 if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
4659 index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
4662 o = ffs(~*bp) - 1; /* ffs is documented in BSTRING(3) */
4664 ret = (VnodeId) ((bp - index->bitmap) * 8 + o);
4665 #ifdef AFS_DEMAND_ATTACH_FS
4667 #endif /* AFS_DEMAND_ATTACH_FS */
4670 bp += sizeof(bit32) /* i.e. 4 */ ;
4672 /* No bit map entry--must grow bitmap */
4674 realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
4677 bp += index->bitmapSize;
4678 memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
4679 index->bitmapOffset = index->bitmapSize;
4680 index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
4682 ret = index->bitmapOffset * 8;
4683 #ifdef AFS_DEMAND_ATTACH_FS
4685 #endif /* AFS_DEMAND_ATTACH_FS */
4688 #ifdef AFS_DEMAND_ATTACH_FS
4689 VChangeState_r(vp, state_save);
4690 if (flags & VOL_ALLOC_BITMAP_WAIT) {
4691 VCancelReservation_r(vp);
4693 #endif /* AFS_DEMAND_ATTACH_FS */
4698 VAllocBitmapEntry(Error * ec, Volume * vp, register struct vnodeIndex * index)
4702 retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
4708 VFreeBitMapEntry_r(Error * ec, register struct vnodeIndex *index,
4711 unsigned int offset;
4717 #endif /* BITMAP_LATER */
4718 offset = bitNumber >> 3;
4719 if (offset >= index->bitmapSize) {
4723 if (offset < index->bitmapOffset)
4724 index->bitmapOffset = offset & ~3; /* Truncate to nearest bit32 */
4725 *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
4729 VFreeBitMapEntry(Error * ec, register struct vnodeIndex *index,
4733 VFreeBitMapEntry_r(ec, index, bitNumber);
4737 /* this function will drop the glock internally.
4738 * for old pthread fileservers, this is safe thanks to vbusy.
4740 * for demand attach fs, caller must have already called
4741 * VCreateReservation_r and VWaitExclusiveState_r */
4743 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
4745 StreamHandle_t *file;
4748 struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
4749 struct vnodeIndex *vip = &vp->vnodeIndex[class];
4750 struct VnodeDiskObject *vnode;
4751 unsigned int unique = 0;
4755 #endif /* BITMAP_LATER */
4756 #ifdef AFS_DEMAND_ATTACH_FS
4757 VolState state_save;
4758 #endif /* AFS_DEMAND_ATTACH_FS */
4762 #ifdef AFS_DEMAND_ATTACH_FS
4763 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
4764 #endif /* AFS_DEMAND_ATTACH_FS */
4767 fdP = IH_OPEN(vip->handle);
4768 assert(fdP != NULL);
4769 file = FDH_FDOPEN(fdP, "r");
4770 assert(file != NULL);
4771 vnode = (VnodeDiskObject *) malloc(vcp->diskSize);
4772 assert(vnode != NULL);
4773 size = OS_SIZE(fdP->fd_fd);
4775 nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
4777 vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4; /* The 10 is a little extra so
4778 * a few files can be created in this volume,
4779 * the whole thing is rounded up to nearest 4
4780 * bytes, because the bit map allocator likes
4783 BitMap = (byte *) calloc(1, vip->bitmapSize);
4784 assert(BitMap != NULL);
4785 #else /* BITMAP_LATER */
4786 vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
4787 assert(vip->bitmap != NULL);
4788 vip->bitmapOffset = 0;
4789 #endif /* BITMAP_LATER */
4790 if (STREAM_SEEK(file, vcp->diskSize, 0) != -1) {
4792 for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
4793 if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
4795 if (vnode->type != vNull) {
4796 if (vnode->vnodeMagic != vcp->magic) {
4797 Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
4802 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
4803 #else /* BITMAP_LATER */
4804 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
4805 #endif /* BITMAP_LATER */
4806 if (unique <= vnode->uniquifier)
4807 unique = vnode->uniquifier + 1;
4809 #ifndef AFS_PTHREAD_ENV
4810 if ((bitNumber & 0x00ff) == 0x0ff) { /* every 256 iterations */
4813 #endif /* !AFS_PTHREAD_ENV */
4816 if (vp->nextVnodeUnique < unique) {
4817 Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
4820 /* Paranoia, partly justified--I think fclose after fdopen
4821 * doesn't seem to close fd. In any event, the documentation
4822 * doesn't specify, so it's safer to close it twice.
4830 /* There may have been a racing condition with some other thread, both
4831 * creating the bitmaps for this volume. If the other thread was faster
4832 * the pointer to bitmap should already be filled and we can free ours.
4834 if (vip->bitmap == NULL) {
4835 vip->bitmap = BitMap;
4836 vip->bitmapOffset = 0;
4838 free((byte *) BitMap);
4839 #endif /* BITMAP_LATER */
4840 #ifdef AFS_DEMAND_ATTACH_FS
4841 VChangeState_r(vp, state_save);
4842 #endif /* AFS_DEMAND_ATTACH_FS */
4846 /***************************************************/
4847 /* Volume Path and Volume Number utility routines */
4848 /***************************************************/
4851 * find the first occurrence of a volume header file and return the path.
4853 * @param[out] ec outbound error code
4854 * @param[in] volumeId volume id to find
4855 * @param[out] partitionp pointer to disk partition path string
4856 * @param[out] namep pointer to volume header file name string
4858 * @post path to first occurrence of volume header is returned in partitionp
4859 * and namep, or ec is set accordingly.
4861 * @warning this function is NOT re-entrant -- partitionp and namep point to
4862 * static data segments
4864 * @note if a volume utility inadvertently leaves behind a stale volume header
4865 * on a vice partition, it is possible for callers to get the wrong one,
4866 * depending on the order of the disk partition linked list.
4870 VGetVolumePath(Error * ec, VolId volumeId, char **partitionp, char **namep)
4872 static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
4873 char path[VMAXPATHLEN];
4875 struct DiskPartition64 *dp;
4879 (void)afs_snprintf(&name[1], (sizeof name) - 1, VFORMAT, afs_cast_uint32(volumeId));
4880 for (dp = DiskPartitionList; dp; dp = dp->next) {
4881 struct afs_stat status;
4882 strcpy(path, VPartitionPath(dp));
4884 if (afs_stat(path, &status) == 0) {
4885 strcpy(partition, dp->name);
4892 *partitionp = *namep = NULL;
4894 *partitionp = partition;
4900 * extract a volume number from a volume header filename string.
4902 * @param[in] name volume header filename string
4904 * @return volume number
4906 * @note the string must be of the form VFORMAT. the only permissible
4907 * deviation is a leading '/' character.
4912 VolumeNumber(char *name)
4916 return atoi(name + 1);
4920 * compute the volume header filename.
4922 * @param[in] volumeId
4924 * @return volume header filename
4926 * @post volume header filename string is constructed
4928 * @warning this function is NOT re-entrant -- the returned string is
4929 * stored in a static char array. see VolumeExternalName_r
4930 * for a re-entrant equivalent.
4932 * @see VolumeExternalName_r
4934 * @deprecated due to the above re-entrancy warning, this interface should
4935 * be considered deprecated. Please use VolumeExternalName_r
4939 VolumeExternalName(VolumeId volumeId)
4941 static char name[VMAXPATHLEN];
4942 (void)afs_snprintf(name, sizeof name, VFORMAT, afs_cast_uint32(volumeId));
4947 * compute the volume header filename.
4949 * @param[in] volumeId
4950 * @param[inout] name array in which to store filename
4951 * @param[in] len length of name array
4953 * @return result code from afs_snprintf
4955 * @see VolumeExternalName
4958 * @note re-entrant equivalent of VolumeExternalName
4960 * @internal volume package internal use only.
4962 #ifdef AFS_DEMAND_ATTACH_FS
4964 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
4966 return afs_snprintf(name, len, VFORMAT, afs_cast_uint32(volumeId));
4971 /***************************************************/
4972 /* Volume Usage Statistics routines */
4973 /***************************************************/
4975 #if OPENAFS_VOL_STATS
4976 #define OneDay (86400) /* 24 hours' worth of seconds */
4978 #define OneDay (24*60*60) /* 24 hours */
4979 #endif /* OPENAFS_VOL_STATS */
4981 #define Midnight(date) ((date-TimeZoneCorrection)/OneDay*OneDay+TimeZoneCorrection)
4983 /*------------------------------------------------------------------------
4984 * [export] VAdjustVolumeStatistics
4987 * If we've passed midnight, we need to update all the day use
4988 * statistics as well as zeroing the detailed volume statistics
4989 * (if we are implementing them).
4992 * vp : Pointer to the volume structure describing the lucky
4993 * volume being considered for update.
4999 * Nothing interesting.
5003 *------------------------------------------------------------------------*/
5006 VAdjustVolumeStatistics_r(register Volume * vp)
5008 unsigned int now = FT_ApproxTime();
5010 if (now - V_dayUseDate(vp) > OneDay) {
5011 register int ndays, i;
5013 ndays = (now - V_dayUseDate(vp)) / OneDay;
5014 for (i = 6; i > ndays - 1; i--)
5015 V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
5016 for (i = 0; i < ndays - 1 && i < 7; i++)
5017 V_weekUse(vp)[i] = 0;
5019 V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
5021 V_dayUseDate(vp) = Midnight(now);
5023 #if OPENAFS_VOL_STATS
5025 * All we need to do is bzero the entire VOL_STATS_BYTES of
5026 * the detailed volume statistics area.
5028 memset((char *)(V_stat_area(vp)), 0, VOL_STATS_BYTES);
5029 #endif /* OPENAFS_VOL_STATS */
5032 /*It's been more than a day of collection */
5034 * Always return happily.
5037 } /*VAdjustVolumeStatistics */
5040 VAdjustVolumeStatistics(register Volume * vp)
5044 retVal = VAdjustVolumeStatistics_r(vp);
5050 VBumpVolumeUsage_r(register Volume * vp)
5052 unsigned int now = FT_ApproxTime();
5053 if (now - V_dayUseDate(vp) > OneDay)
5054 VAdjustVolumeStatistics_r(vp);
5056 * Save the volume header image to disk after every 128 bumps to dayUse.
5058 if ((V_dayUse(vp)++ & 127) == 0) {
5060 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
5065 VBumpVolumeUsage(register Volume * vp)
5068 VBumpVolumeUsage_r(vp);
5073 VSetDiskUsage_r(void)
5075 #ifndef AFS_DEMAND_ATTACH_FS
5076 static int FifteenMinuteCounter = 0;
5080 /* NOTE: Don't attempt to access the partitions list until the
5081 * initialization level indicates that all volumes are attached,
5082 * which implies that all partitions are initialized. */
5083 #ifdef AFS_PTHREAD_ENV
5085 #else /* AFS_PTHREAD_ENV */
5087 #endif /* AFS_PTHREAD_ENV */
5090 VResetDiskUsage_r();
5092 #ifndef AFS_DEMAND_ATTACH_FS
5093 if (++FifteenMinuteCounter == 3) {
5094 FifteenMinuteCounter = 0;
5097 #endif /* !AFS_DEMAND_ATTACH_FS */
5109 /***************************************************/
5110 /* Volume Update List routines */
5111 /***************************************************/
5113 /* The number of minutes that a volume hasn't been updated before the
5114 * "Dont salvage" flag in the volume header will be turned on */
5115 #define SALVAGE_INTERVAL (10*60)
5120 * volume update list functionality has been moved into the VLRU
5121 * the DONT_SALVAGE flag is now set during VLRU demotion
5124 #ifndef AFS_DEMAND_ATTACH_FS
5125 static VolumeId *UpdateList = NULL; /* Pointer to array of Volume ID's */
5126 static int nUpdatedVolumes = 0; /* Updated with entry in UpdateList, salvage after crash flag on */
5127 static int updateSize = 0; /* number of entries possible */
5128 #define UPDATE_LIST_SIZE 128 /* initial size increment (must be a power of 2!) */
5129 #endif /* !AFS_DEMAND_ATTACH_FS */
5132 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
5135 vp->updateTime = FT_ApproxTime();
5136 if (V_dontSalvage(vp) == 0)
5138 V_dontSalvage(vp) = 0;
5139 VSyncVolume_r(ec, vp, 0);
5140 #ifdef AFS_DEMAND_ATTACH_FS
5141 V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
5142 #else /* !AFS_DEMAND_ATTACH_FS */
5145 if (UpdateList == NULL) {
5146 updateSize = UPDATE_LIST_SIZE;
5147 UpdateList = (VolumeId *) malloc(sizeof(VolumeId) * updateSize);
5149 if (nUpdatedVolumes == updateSize) {
5151 if (updateSize > 524288) {
5152 Log("warning: there is likely a bug in the volume update scanner\n");
5156 (VolumeId *) realloc(UpdateList,
5157 sizeof(VolumeId) * updateSize);
5160 assert(UpdateList != NULL);
5161 UpdateList[nUpdatedVolumes++] = V_id(vp);
5162 #endif /* !AFS_DEMAND_ATTACH_FS */
5165 #ifndef AFS_DEMAND_ATTACH_FS
5167 VScanUpdateList(void)
5169 register int i, gap;
5170 register Volume *vp;
5172 afs_uint32 now = FT_ApproxTime();
5173 /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
5174 for (i = gap = 0; i < nUpdatedVolumes; i++) {
5176 UpdateList[i - gap] = UpdateList[i];
5178 /* XXX this routine needlessly messes up the Volume LRU by
5179 * breaking the LRU temporal-locality assumptions.....
5180 * we should use a special volume header allocator here */
5181 vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
5184 } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
5185 V_dontSalvage(vp) = DONT_SALVAGE;
5186 VUpdateVolume_r(&error, vp, 0); /* No need to fsync--not critical */
5194 #ifndef AFS_PTHREAD_ENV
5196 #endif /* !AFS_PTHREAD_ENV */
5198 nUpdatedVolumes -= gap;
5200 #endif /* !AFS_DEMAND_ATTACH_FS */
5203 /***************************************************/
5204 /* Volume LRU routines */
5205 /***************************************************/
5210 * with demand attach fs, we attempt to soft detach(1)
5211 * volumes which have not been accessed in a long time
5212 * in order to speed up fileserver shutdown
5214 * (1) by soft detach we mean a process very similar
5215 * to VOffline, except the final state of the
5216 * Volume will be VOL_STATE_PREATTACHED, instead
5217 * of the usual VOL_STATE_UNATTACHED
5219 #ifdef AFS_DEMAND_ATTACH_FS
5221 /* implementation is reminiscent of a generational GC
5223 * queue 0 is newly attached volumes. this queue is
5224 * sorted by attach timestamp
5226 * queue 1 is volumes that have been around a bit
5227 * longer than queue 0. this queue is sorted by
5230 * queue 2 is volumes tha have been around the longest.
5231 * this queue is unsorted
5233 * queue 3 is volumes that have been marked as
5234 * candidates for soft detachment. this queue is
5237 #define VLRU_GENERATIONS 3 /**< number of generations in VLRU */
5238 #define VLRU_QUEUES 5 /**< total number of VLRU queues */
5241 * definition of a VLRU queue.
5244 volatile struct rx_queue q;
5251 * main VLRU data structure.
5254 struct VLRU_q q[VLRU_QUEUES]; /**< VLRU queues */
5257 /** time interval (in seconds) between promotion passes for
5258 * each young generation queue. */
5259 afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
5261 /** time interval (in seconds) between soft detach candidate
5262 * scans for each generation queue.
5264 * scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
5265 * we perform a soft detach pass. */
5266 afs_uint32 scan_interval[VLRU_GENERATIONS+1];
5268 /* scheduler state */
5269 int next_idx; /**< next queue to receive attention */
5270 afs_uint32 last_promotion[VLRU_GENERATIONS-1]; /**< timestamp of last promotion scan */
5271 afs_uint32 last_scan[VLRU_GENERATIONS+1]; /**< timestamp of last detach scan */
5273 int scanner_state; /**< state of scanner thread */
5274 pthread_cond_t cv; /**< state transition CV */
5277 /** global VLRU state */
5278 static struct VLRU volume_LRU;
5281 * defined states for VLRU scanner thread.
5284 VLRU_SCANNER_STATE_OFFLINE = 0, /**< vlru scanner thread is offline */
5285 VLRU_SCANNER_STATE_ONLINE = 1, /**< vlru scanner thread is online */
5286 VLRU_SCANNER_STATE_SHUTTING_DOWN = 2, /**< vlru scanner thread is shutting down */
5287 VLRU_SCANNER_STATE_PAUSING = 3, /**< vlru scanner thread is getting ready to pause */
5288 VLRU_SCANNER_STATE_PAUSED = 4 /**< vlru scanner thread is paused */
5289 } vlru_thread_state_t;
5291 /* vlru disk data header stuff */
5292 #define VLRU_DISK_MAGIC 0x7a8b9cad /**< vlru disk entry magic number */
5293 #define VLRU_DISK_VERSION 1 /**< vlru disk entry version number */
5295 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
5296 #define VLRU_DUMP_EXPIRATION_TIME (60*60*24*7) /* expire vlru data after 1 week */
5299 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
5300 * soft detachment. */
5301 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
5303 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
5304 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
5306 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
5307 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
5309 /** VLRU control flag. non-zero value implies VLRU subsystem is activated. */
5310 static afs_uint32 VLRU_enabled = 1;
5312 /* queue synchronization routines */
5313 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
5314 static void VLRU_EndExclusive_r(struct VLRU_q * q);
5315 static void VLRU_Wait_r(struct VLRU_q * q);
5318 * set VLRU subsystem tunable parameters.
5320 * @param[in] option tunable option to modify
5321 * @param[in] val new value for tunable parameter
5323 * @pre @c VInitVolumePackage has not yet been called.
5325 * @post tunable parameter is modified
5329 * @note valid option parameters are:
5330 * @arg @c VLRU_SET_THRESH
5331 * set the period of inactivity after which
5332 * volumes are eligible for soft detachment
5333 * @arg @c VLRU_SET_INTERVAL
5334 * set the time interval between calls
5335 * to the volume LRU "garbage collector"
5336 * @arg @c VLRU_SET_MAX
5337 * set the max number of volumes to deallocate
5341 VLRU_SetOptions(int option, afs_uint32 val)
5343 if (option == VLRU_SET_THRESH) {
5344 VLRU_offline_thresh = val;
5345 } else if (option == VLRU_SET_INTERVAL) {
5346 VLRU_offline_interval = val;
5347 } else if (option == VLRU_SET_MAX) {
5348 VLRU_offline_max = val;
5349 } else if (option == VLRU_SET_ENABLED) {
5352 VLRU_ComputeConstants();
5356 * compute VLRU internal timing parameters.
5358 * @post VLRU scanner thread internal timing parameters are computed
5360 * @note computes internal timing parameters based upon user-modifiable
5361 * tunable parameters.
5365 * @internal volume package internal use only.
5368 VLRU_ComputeConstants(void)
5370 afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
5372 /* compute the candidate scan interval */
5373 volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
5375 /* compute the promotion intervals */
5376 volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
5377 volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
5380 /* compute the gen 0 scan interval */
5381 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
5383 /* compute the gen 0 scan interval */
5384 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
5389 * initialize VLRU subsystem.
5391 * @pre this function has not yet been called
5393 * @post VLRU subsystem is initialized and VLRU scanner thread is starting
5397 * @internal volume package internal use only.
5403 pthread_attr_t attrs;
5406 if (!VLRU_enabled) {
5407 Log("VLRU: disabled\n");
5411 /* initialize each of the VLRU queues */
5412 for (i = 0; i < VLRU_QUEUES; i++) {
5413 queue_Init(&volume_LRU.q[i]);
5414 volume_LRU.q[i].len = 0;
5415 volume_LRU.q[i].busy = 0;
5416 assert(pthread_cond_init(&volume_LRU.q[i].cv, NULL) == 0);
5419 /* setup the timing constants */
5420 VLRU_ComputeConstants();
5422 /* XXX put inside LogLevel check? */
5423 Log("VLRU: starting scanner with the following configuration parameters:\n");
5424 Log("VLRU: offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
5425 Log("VLRU: running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
5426 Log("VLRU: taking up to %d volumes offline per pass\n", VLRU_offline_max);
5427 Log("VLRU: scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
5428 Log("VLRU: scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
5429 Log("VLRU: scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
5431 /* start up the VLRU scanner */
5432 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
5433 if (programType == fileServer) {
5434 assert(pthread_cond_init(&volume_LRU.cv, NULL) == 0);
5435 assert(pthread_attr_init(&attrs) == 0);
5436 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
5437 assert(pthread_create(&tid, &attrs, &VLRU_ScannerThread, NULL) == 0);
5442 * initialize the VLRU-related fields of a newly allocated volume object.
5444 * @param[in] vp pointer to volume object
5447 * @arg @c VOL_LOCK is held.
5448 * @arg volume object is not on a VLRU queue.
5450 * @post VLRU fields are initialized to indicate that volume object is not
5451 * currently registered with the VLRU subsystem
5455 * @internal volume package interal use only.
5458 VLRU_Init_Node_r(volatile Volume * vp)
5463 assert(queue_IsNotOnQueue(&vp->vlru));
5464 vp->vlru.idx = VLRU_QUEUE_INVALID;
5468 * add a volume object to a VLRU queue.
5470 * @param[in] vp pointer to volume object
5473 * @arg @c VOL_LOCK is held.
5474 * @arg caller MUST hold a lightweight ref on @p vp.
5475 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
5477 * @post the volume object is added to the appropriate VLRU queue
5479 * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
5480 * then the volume is added to that queue. Otherwise, the value
5481 * @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
5482 * volume is added to the NEW generation queue.
5484 * @note @c VOL_LOCK may be dropped internally
5486 * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
5487 * during the add operation, and is restored to the previous
5488 * state prior to return.
5492 * @internal volume package internal use only.
5495 VLRU_Add_r(volatile Volume * vp)
5498 VolState state_save;
5503 if (queue_IsOnQueue(&vp->vlru))
5506 state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
5509 if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
5510 idx = VLRU_QUEUE_NEW;
5513 VLRU_Wait_r(&volume_LRU.q[idx]);
5515 /* repeat check since VLRU_Wait_r may have dropped
5517 if (queue_IsNotOnQueue(&vp->vlru)) {
5519 queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
5520 volume_LRU.q[idx].len++;
5521 V_attachFlags(vp) |= VOL_ON_VLRU;
5522 vp->stats.last_promote = FT_ApproxTime();
5525 VChangeState_r(vp, state_save);
5529 * delete a volume object from a VLRU queue.
5531 * @param[in] vp pointer to volume object
5534 * @arg @c VOL_LOCK is held.
5535 * @arg caller MUST hold a lightweight ref on @p vp.
5536 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
5538 * @post volume object is removed from the VLRU queue
5540 * @note @c VOL_LOCK may be dropped internally
5544 * @todo We should probably set volume state to something exlcusive
5545 * (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
5547 * @internal volume package internal use only.
5550 VLRU_Delete_r(volatile Volume * vp)
5557 if (queue_IsNotOnQueue(&vp->vlru))
5563 if (idx == VLRU_QUEUE_INVALID)
5565 VLRU_Wait_r(&volume_LRU.q[idx]);
5566 } while (idx != vp->vlru.idx);
5568 /* now remove from the VLRU and update
5569 * the appropriate counter */
5570 queue_Remove(&vp->vlru);
5571 volume_LRU.q[idx].len--;
5572 vp->vlru.idx = VLRU_QUEUE_INVALID;
5573 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
5577 * tell the VLRU subsystem that a volume was just accessed.
5579 * @param[in] vp pointer to volume object
5582 * @arg @c VOL_LOCK is held
5583 * @arg caller MUST hold a lightweight ref on @p vp
5584 * @arg caller MUST NOT hold exclusive ownership of any VLRU queue
5586 * @post volume VLRU access statistics are updated. If the volume was on
5587 * the VLRU soft detach candidate queue, it is moved to the NEW
5590 * @note @c VOL_LOCK may be dropped internally
5594 * @internal volume package internal use only.
5597 VLRU_UpdateAccess_r(volatile Volume * vp)
5599 afs_uint32 live_interval;
5600 Volume * rvp = NULL;
5605 if (queue_IsNotOnQueue(&vp->vlru))
5608 assert(V_attachFlags(vp) & VOL_ON_VLRU);
5610 /* update the access timestamp */
5611 vp->stats.last_get = FT_ApproxTime();
5614 * if the volume is on the soft detach candidate
5615 * list, we need to safely move it back to a
5616 * regular generation. this has to be done
5617 * carefully so we don't race against the scanner
5621 /* if this volume is on the soft detach candidate queue,
5622 * then grab exclusive access to the necessary queues */
5623 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
5625 VCreateReservation_r(rvp);
5627 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
5628 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
5629 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5630 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5633 /* make sure multiple threads don't race to update */
5634 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
5635 VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
5639 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5640 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
5641 VCancelReservation_r(rvp);
5646 * switch a volume between two VLRU queues.
5648 * @param[in] vp pointer to volume object
5649 * @param[in] new_idx index of VLRU queue onto which the volume will be moved
5650 * @param[in] append controls whether the volume will be appended or
5651 * prepended to the queue. A nonzero value means it will
5652 * be appended; zero means it will be prepended.
5654 * @pre The new (and old, if applicable) queue(s) must either be owned
5655 * exclusively by the calling thread for asynchronous manipulation,
5656 * or the queue(s) must be quiescent and VOL_LOCK must be held.
5657 * Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
5658 * for further details of the queue asynchronous processing mechanism.
5660 * @post If the volume object was already on a VLRU queue, it is
5661 * removed from the queue. Depending on the value of the append
5662 * parameter, the volume object is either appended or prepended
5663 * to the VLRU queue referenced by the new_idx parameter.
5667 * @see VLRU_BeginExclusive_r
5668 * @see VLRU_EndExclusive_r
5671 * @internal volume package internal use only.
5674 VLRU_SwitchQueues(volatile Volume * vp, int new_idx, int append)
5676 if (queue_IsNotOnQueue(&vp->vlru))
5679 queue_Remove(&vp->vlru);
5680 volume_LRU.q[vp->vlru.idx].len--;
5682 /* put the volume back on the correct generational queue */
5684 queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
5686 queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
5689 volume_LRU.q[new_idx].len++;
5690 vp->vlru.idx = new_idx;
5694 * VLRU background thread.
5696 * The VLRU Scanner Thread is responsible for periodically scanning through
5697 * each VLRU queue looking for volumes which should be moved to another
5698 * queue, or soft detached.
5700 * @param[in] args unused thread arguments parameter
5702 * @return unused thread return value
5703 * @retval NULL always
5705 * @internal volume package internal use only.
5708 VLRU_ScannerThread(void * args)
5710 afs_uint32 now, min_delay, delay;
5711 afs_uint32 next_scan[VLRU_GENERATIONS];
5712 afs_uint32 next_promotion[VLRU_GENERATIONS];
5713 int i, min_idx, min_op, overdue, state;
5715 /* set t=0 for promotion cycle to be
5716 * fileserver startup */
5717 now = FT_ApproxTime();
5718 for (i=0; i < VLRU_GENERATIONS-1; i++) {
5719 volume_LRU.last_promotion[i] = now;
5722 /* don't start the scanner until VLRU_offline_thresh
5723 * plus a small delay for VInitVolumePackage to finish
5726 sleep(VLRU_offline_thresh + 60);
5728 /* set t=0 for scan cycle to be now */
5729 now = FT_ApproxTime();
5730 for (i=0; i < VLRU_GENERATIONS+1; i++) {
5731 volume_LRU.last_scan[i] = now;
5735 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
5736 volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
5739 while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
5740 /* check to see if we've been asked to pause */
5741 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
5742 volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
5743 assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
5745 VOL_CV_WAIT(&volume_LRU.cv);
5746 } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
5749 /* scheduling can happen outside the glock */
5752 /* figure out what is next on the schedule */
5754 /* figure out a potential schedule for the new generation first */
5756 min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
5759 if (min_delay > volume_LRU.scan_interval[0]) {
5760 /* unsigned overflow -- we're overdue to run this scan */
5765 /* if we're not overdue for gen 0, figure out schedule for candidate gen */
5767 i = VLRU_QUEUE_CANDIDATE;
5768 delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
5769 if (delay < min_delay) {
5773 if (delay > volume_LRU.scan_interval[i]) {
5774 /* unsigned overflow -- we're overdue to run this scan */
5781 /* if we're still not overdue for something, figure out schedules for promotions */
5782 for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
5783 delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
5784 if (delay < min_delay) {
5789 if (delay > volume_LRU.promotion_interval[i]) {
5790 /* unsigned overflow -- we're overdue to run this promotion */
5799 /* sleep as needed */
5804 /* do whatever is next */
5807 VLRU_Promote_r(min_idx);
5808 VLRU_Demote_r(min_idx+1);
5810 VLRU_Scan_r(min_idx);
5812 now = FT_ApproxTime();
5815 Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
5817 /* signal that scanner is down */
5818 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
5819 assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
5825 * promote volumes from one VLRU generation to the next.
5827 * This routine scans a VLRU generation looking for volumes which are
5828 * eligible to be promoted to the next generation. All volumes which
5829 * meet the eligibility requirement are promoted.
5831 * Promotion eligibility is based upon meeting both of the following
5834 * @arg The volume has been accessed since the last promotion:
5835 * @c (vp->stats.last_get >= vp->stats.last_promote)
5836 * @arg The last promotion occurred at least
5837 * @c volume_LRU.promotion_interval[idx] seconds ago
5839 * As a performance optimization, promotions are "globbed". In other
5840 * words, we promote arbitrarily large contiguous sublists of elements
5843 * @param[in] idx VLRU queue index to scan
5847 * @internal VLRU internal use only.
5850 VLRU_Promote_r(int idx)
5852 int len, chaining, promote;
5853 afs_uint32 now, thresh;
5854 struct rx_queue *qp, *nqp;
5855 Volume * vp, *start, *end;
5857 /* get exclusive access to two chains, and drop the glock */
5858 VLRU_Wait_r(&volume_LRU.q[idx]);
5859 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
5860 VLRU_Wait_r(&volume_LRU.q[idx+1]);
5861 VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
5864 thresh = volume_LRU.promotion_interval[idx];
5865 now = FT_ApproxTime();
5868 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
5869 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
5870 promote = (((vp->stats.last_promote + thresh) <= now) &&
5871 (vp->stats.last_get >= vp->stats.last_promote));
5879 /* promote and prepend chain */
5880 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
5894 /* promote and prepend */
5895 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
5899 volume_LRU.q[idx].len -= len;
5900 volume_LRU.q[idx+1].len += len;
5903 /* release exclusive access to the two chains */
5905 volume_LRU.last_promotion[idx] = now;
5906 VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
5907 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
5910 /* run the demotions */
5912 VLRU_Demote_r(int idx)
5915 int len, chaining, demote;
5916 afs_uint32 now, thresh;
5917 struct rx_queue *qp, *nqp;
5918 Volume * vp, *start, *end;
5919 Volume ** salv_flag_vec = NULL;
5920 int salv_vec_offset = 0;
5922 assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
5924 /* get exclusive access to two chains, and drop the glock */
5925 VLRU_Wait_r(&volume_LRU.q[idx-1]);
5926 VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
5927 VLRU_Wait_r(&volume_LRU.q[idx]);
5928 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
5931 /* no big deal if this allocation fails */
5932 if (volume_LRU.q[idx].len) {
5933 salv_flag_vec = (Volume **) malloc(volume_LRU.q[idx].len * sizeof(Volume *));
5936 now = FT_ApproxTime();
5937 thresh = volume_LRU.promotion_interval[idx-1];
5940 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
5941 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
5942 demote = (((vp->stats.last_promote + thresh) <= now) &&
5943 (vp->stats.last_get < (now - thresh)));
5945 /* we now do volume update list DONT_SALVAGE flag setting during
5946 * demotion passes */
5947 if (salv_flag_vec &&
5948 !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
5950 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
5951 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
5952 salv_flag_vec[salv_vec_offset++] = vp;
5953 VCreateReservation_r(vp);
5962 /* demote and append chain */
5963 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
5977 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
5981 volume_LRU.q[idx].len -= len;
5982 volume_LRU.q[idx-1].len += len;
5985 /* release exclusive access to the two chains */
5987 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
5988 VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
5990 /* now go back and set the DONT_SALVAGE flags as appropriate */
5991 if (salv_flag_vec) {
5993 for (i = 0; i < salv_vec_offset; i++) {
5994 vp = salv_flag_vec[i];
5995 if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
5996 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
5997 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
6000 V_attachFlags(vp) |= VOL_HDR_DONTSALV;
6001 V_dontSalvage(vp) = DONT_SALVAGE;
6002 VUpdateVolume_r(&ec, vp, 0);
6006 VCancelReservation_r(vp);
6008 free(salv_flag_vec);
6012 /* run a pass of the VLRU GC scanner */
6014 VLRU_Scan_r(int idx)
6016 afs_uint32 now, thresh;
6017 struct rx_queue *qp, *nqp;
6018 volatile Volume * vp;
6021 assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
6023 /* gain exclusive access to the idx VLRU */
6024 VLRU_Wait_r(&volume_LRU.q[idx]);
6025 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
6027 if (idx != VLRU_QUEUE_CANDIDATE) {
6028 /* gain exclusive access to the candidate VLRU */
6029 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6030 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6033 now = FT_ApproxTime();
6034 thresh = now - VLRU_offline_thresh;
6036 /* perform candidate selection and soft detaching */
6037 if (idx == VLRU_QUEUE_CANDIDATE) {
6038 /* soft detach some volumes from the candidate pool */
6042 for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
6043 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6044 if (i >= VLRU_offline_max) {
6047 /* check timestamp to see if it's a candidate for soft detaching */
6048 if (vp->stats.last_get <= thresh) {
6050 if (VCheckSoftDetach(vp, thresh))
6056 /* scan for volumes to become soft detach candidates */
6057 for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
6058 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6060 /* check timestamp to see if it's a candidate for soft detaching */
6061 if (vp->stats.last_get <= thresh) {
6062 VCheckSoftDetachCandidate(vp, thresh);
6065 if (!(i&0x7f)) { /* lock coarsening optimization */
6073 /* relinquish exclusive access to the VLRU chains */
6077 volume_LRU.last_scan[idx] = now;
6078 if (idx != VLRU_QUEUE_CANDIDATE) {
6079 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6081 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
6084 /* check whether volume is safe to soft detach
6085 * caller MUST NOT hold a ref count on vp */
6087 VCheckSoftDetach(volatile Volume * vp, afs_uint32 thresh)
6091 if (vp->nUsers || vp->nWaiters)
6094 if (vp->stats.last_get <= thresh) {
6095 ret = VSoftDetachVolume_r(vp, thresh);
6101 /* check whether volume should be made a
6102 * soft detach candidate */
6104 VCheckSoftDetachCandidate(volatile Volume * vp, afs_uint32 thresh)
6107 if (vp->nUsers || vp->nWaiters)
6112 assert(idx == VLRU_QUEUE_NEW);
6114 if (vp->stats.last_get <= thresh) {
6115 /* move to candidate pool */
6116 queue_Remove(&vp->vlru);
6117 volume_LRU.q[VLRU_QUEUE_NEW].len--;
6118 queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
6119 vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
6120 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
6128 /* begin exclusive access on VLRU */
6130 VLRU_BeginExclusive_r(struct VLRU_q * q)
6132 assert(q->busy == 0);
6136 /* end exclusive access on VLRU */
6138 VLRU_EndExclusive_r(struct VLRU_q * q)
6142 assert(pthread_cond_broadcast(&q->cv) == 0);
6145 /* wait for another thread to end exclusive access on VLRU */
6147 VLRU_Wait_r(struct VLRU_q * q)
6150 VOL_CV_WAIT(&q->cv);
6155 * volume soft detach
6157 * caller MUST NOT hold a ref count on vp */
6159 VSoftDetachVolume_r(volatile Volume * vp, afs_uint32 thresh)
6164 assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
6166 ts_save = vp->stats.last_get;
6167 if (ts_save > thresh)
6170 if (vp->nUsers || vp->nWaiters)
6173 if (VIsExclusiveState(V_attachState(vp))) {
6177 switch (V_attachState(vp)) {
6178 case VOL_STATE_UNATTACHED:
6179 case VOL_STATE_PREATTACHED:
6180 case VOL_STATE_ERROR:
6181 case VOL_STATE_GOING_OFFLINE:
6182 case VOL_STATE_SHUTTING_DOWN:
6183 case VOL_STATE_SALVAGING:
6184 volume_LRU.q[vp->vlru.idx].len--;
6186 /* create and cancel a reservation to
6187 * give the volume an opportunity to
6189 VCreateReservation_r(vp);
6190 queue_Remove(&vp->vlru);
6191 vp->vlru.idx = VLRU_QUEUE_INVALID;
6192 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
6193 VCancelReservation_r(vp);
6197 /* hold the volume and take it offline.
6198 * no need for reservations, as VHold_r
6199 * takes care of that internally. */
6200 if (VHold_r(vp) == 0) {
6201 /* vhold drops the glock, so now we should
6202 * check to make sure we aren't racing against
6203 * other threads. if we are racing, offlining vp
6204 * would be wasteful, and block the scanner for a while
6208 (vp->shuttingDown) ||
6209 (vp->goingOffline) ||
6210 (vp->stats.last_get != ts_save)) {
6211 /* looks like we're racing someone else. bail */
6215 /* pull it off the VLRU */
6216 assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
6217 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
6218 queue_Remove(&vp->vlru);
6219 vp->vlru.idx = VLRU_QUEUE_INVALID;
6220 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
6222 /* take if offline */
6223 VOffline_r(vp, "volume has been soft detached");
6225 /* invalidate the volume header cache */
6226 FreeVolumeHeader(vp);
6229 IncUInt64(&VStats.soft_detaches);
6230 vp->stats.soft_detaches++;
6232 /* put in pre-attached state so demand
6233 * attacher can work on it */
6234 VChangeState_r(vp, VOL_STATE_PREATTACHED);
6240 #endif /* AFS_DEMAND_ATTACH_FS */
6243 /***************************************************/
6244 /* Volume Header Cache routines */
6245 /***************************************************/
6248 * volume header cache.
6250 struct volume_hdr_LRU_t volume_hdr_LRU;
6253 * initialize the volume header cache.
6255 * @param[in] howMany number of header cache entries to preallocate
6257 * @pre VOL_LOCK held. Function has never been called before.
6259 * @post howMany cache entries are allocated, initialized, and added
6260 * to the LRU list. Header cache statistics are initialized.
6262 * @note only applicable to fileServer program type. Should only be
6263 * called once during volume package initialization.
6265 * @internal volume package internal use only.
6268 VInitVolumeHeaderCache(afs_uint32 howMany)
6270 register struct volHeader *hp;
6271 if (programType != fileServer)
6273 queue_Init(&volume_hdr_LRU);
6274 volume_hdr_LRU.stats.free = 0;
6275 volume_hdr_LRU.stats.used = howMany;
6276 volume_hdr_LRU.stats.attached = 0;
6277 hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
6281 /* We are using ReleaseVolumeHeader to initialize the values on the header list
6282 * to ensure they have the right values
6284 ReleaseVolumeHeader(hp++);
6288 * get a volume header and attach it to the volume object.
6290 * @param[in] vp pointer to volume object
6292 * @return cache entry status
6293 * @retval 0 volume header was newly attached; cache data is invalid
6294 * @retval 1 volume header was previously attached; cache data is valid
6296 * @pre VOL_LOCK held. For DAFS, lightweight ref must be held on volume object.
6298 * @post volume header attached to volume object. if necessary, header cache
6299 * entry on LRU is synchronized to disk. Header is removed from LRU list.
6301 * @note VOL_LOCK may be dropped
6303 * @warning this interface does not load header data from disk. it merely
6304 * attaches a header object to the volume object, and may sync the old
6305 * header cache data out to disk in the process.
6307 * @internal volume package internal use only.
6310 GetVolumeHeader(register Volume * vp)
6313 register struct volHeader *hd;
6315 static int everLogged = 0;
6317 #ifdef AFS_DEMAND_ATTACH_FS
6318 VolState vp_save, back_save;
6320 /* XXX debug 9/19/05 we've apparently got
6321 * a ref counting bug somewhere that's
6322 * breaking the nUsers == 0 => header on LRU
6324 if (vp->header && queue_IsNotOnQueue(vp->header)) {
6325 Log("nUsers == 0, but header not on LRU\n");
6330 old = (vp->header != NULL); /* old == volume already has a header */
6332 if (programType != fileServer) {
6333 /* for volume utilities, we allocate volHeaders as needed */
6335 hd = (struct volHeader *)calloc(1, sizeof(*vp->header));
6339 #ifdef AFS_DEMAND_ATTACH_FS
6340 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
6344 /* for the fileserver, we keep a volume header cache */
6346 /* the header we previously dropped in the lru is
6347 * still available. pull it off the lru and return */
6350 assert(hd->back == vp);
6352 /* we need to grab a new element off the LRU */
6353 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
6354 /* grab an element and pull off of LRU */
6355 hd = queue_First(&volume_hdr_LRU, volHeader);
6358 /* LRU is empty, so allocate a new volHeader
6359 * this is probably indicative of a leak, so let the user know */
6360 hd = (struct volHeader *)calloc(1, sizeof(struct volHeader));
6363 Log("****Allocated more volume headers, probably leak****\n");
6366 volume_hdr_LRU.stats.free++;
6369 /* this header used to belong to someone else.
6370 * we'll need to check if the header needs to
6371 * be sync'd out to disk */
6373 #ifdef AFS_DEMAND_ATTACH_FS
6374 /* if hd->back were in an exclusive state, then
6375 * its volHeader would not be on the LRU... */
6376 assert(!VIsExclusiveState(V_attachState(hd->back)));
6379 if (hd->diskstuff.inUse) {
6380 /* volume was in use, so we'll need to sync
6381 * its header to disk */
6383 #ifdef AFS_DEMAND_ATTACH_FS
6384 back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
6385 vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
6386 VCreateReservation_r(hd->back);
6390 WriteVolumeHeader_r(&error, hd->back);
6391 /* Ignore errors; catch them later */
6393 #ifdef AFS_DEMAND_ATTACH_FS
6398 hd->back->header = NULL;
6399 #ifdef AFS_DEMAND_ATTACH_FS
6400 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
6402 if (hd->diskstuff.inUse) {
6403 VChangeState_r(hd->back, back_save);
6404 VCancelReservation_r(hd->back);
6405 VChangeState_r(vp, vp_save);
6409 volume_hdr_LRU.stats.attached++;
6413 #ifdef AFS_DEMAND_ATTACH_FS
6414 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
6417 volume_hdr_LRU.stats.free--;
6418 volume_hdr_LRU.stats.used++;
6420 IncUInt64(&VStats.hdr_gets);
6421 #ifdef AFS_DEMAND_ATTACH_FS
6422 IncUInt64(&vp->stats.hdr_gets);
6423 vp->stats.last_hdr_get = FT_ApproxTime();
6430 * make sure volume header is attached and contains valid cache data.
6432 * @param[out] ec outbound error code
6433 * @param[in] vp pointer to volume object
6435 * @pre VOL_LOCK held. For DAFS, lightweight ref held on vp.
6437 * @post header cache entry attached, and loaded with valid data, or
6438 * *ec is nonzero, and the header is released back into the LRU.
6440 * @internal volume package internal use only.
6443 LoadVolumeHeader(Error * ec, Volume * vp)
6445 #ifdef AFS_DEMAND_ATTACH_FS
6446 VolState state_save;
6450 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
6451 IncUInt64(&VStats.hdr_loads);
6452 state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
6455 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
6456 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
6458 IncUInt64(&vp->stats.hdr_loads);
6459 now = FT_ApproxTime();
6463 V_attachFlags(vp) |= VOL_HDR_LOADED;
6464 vp->stats.last_hdr_load = now;
6466 VChangeState_r(vp, state_save);
6468 #else /* AFS_DEMAND_ATTACH_FS */
6470 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
6471 IncUInt64(&VStats.hdr_loads);
6473 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
6474 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
6477 #endif /* AFS_DEMAND_ATTACH_FS */
6479 /* maintain (nUsers==0) => header in LRU invariant */
6480 FreeVolumeHeader(vp);
6485 * release a header cache entry back into the LRU list.
6487 * @param[in] hd pointer to volume header cache object
6489 * @pre VOL_LOCK held.
6491 * @post header cache object appended onto end of LRU list.
6493 * @note only applicable to fileServer program type.
6495 * @note used to place a header cache entry back into the
6496 * LRU pool without invalidating it as a cache entry.
6498 * @internal volume package internal use only.
6501 ReleaseVolumeHeader(register struct volHeader *hd)
6503 if (programType != fileServer)
6505 if (!hd || queue_IsOnQueue(hd)) /* no header, or header already released */
6507 queue_Append(&volume_hdr_LRU, hd);
6508 #ifdef AFS_DEMAND_ATTACH_FS
6510 V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
6513 volume_hdr_LRU.stats.free++;
6514 volume_hdr_LRU.stats.used--;
6518 * free/invalidate a volume header cache entry.
6520 * @param[in] vp pointer to volume object
6522 * @pre VOL_LOCK is held.
6524 * @post For fileserver, header cache entry is returned to LRU, and it is
6525 * invalidated as a cache entry. For volume utilities, the header
6526 * cache entry is freed.
6528 * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
6529 * whenever it is necessary to invalidate the header cache entry.
6531 * @see ReleaseVolumeHeader
6533 * @internal volume package internal use only.
6536 FreeVolumeHeader(register Volume * vp)
6538 register struct volHeader *hd = vp->header;
6541 if (programType == fileServer) {
6542 ReleaseVolumeHeader(hd);
6547 #ifdef AFS_DEMAND_ATTACH_FS
6548 V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
6550 volume_hdr_LRU.stats.attached--;
6555 /***************************************************/
6556 /* Volume Hash Table routines */
6557 /***************************************************/
6560 * set size of volume object hash table.
6562 * @param[in] logsize log(2) of desired hash table size
6564 * @return operation status
6566 * @retval -1 failure
6568 * @pre MUST be called prior to VInitVolumePackage
6570 * @post Volume Hash Table will have 2^logsize buckets
6573 VSetVolHashSize(int logsize)
6575 /* 64 to 16384 hash buckets seems like a reasonable range */
6576 if ((logsize < 6 ) || (logsize > 14)) {
6581 VolumeHashTable.Size = 1 << logsize;
6582 VolumeHashTable.Mask = VolumeHashTable.Size - 1;
6584 /* we can't yet support runtime modification of this
6585 * parameter. we'll need a configuration rwlock to
6586 * make runtime modification feasible.... */
6593 * initialize dynamic data structures for volume hash table.
6595 * @post hash table is allocated, and fields are initialized.
6597 * @internal volume package internal use only.
6600 VInitVolumeHash(void)
6604 VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
6605 sizeof(VolumeHashChainHead));
6606 assert(VolumeHashTable.Table != NULL);
6608 for (i=0; i < VolumeHashTable.Size; i++) {
6609 queue_Init(&VolumeHashTable.Table[i]);
6610 #ifdef AFS_DEMAND_ATTACH_FS
6611 assert(pthread_cond_init(&VolumeHashTable.Table[i].chain_busy_cv, NULL) == 0);
6612 #endif /* AFS_DEMAND_ATTACH_FS */
6617 * add a volume object to the hash table.
6619 * @param[in] vp pointer to volume object
6620 * @param[in] hashid hash of volume id
6622 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
6625 * @post volume is added to hash chain.
6627 * @internal volume package internal use only.
6629 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
6630 * asynchronous hash chain reordering to finish.
6633 AddVolumeToHashTable(register Volume * vp, int hashid)
6635 VolumeHashChainHead * head;
6637 if (queue_IsOnQueue(vp))
6640 head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
6642 #ifdef AFS_DEMAND_ATTACH_FS
6643 /* wait for the hash chain to become available */
6646 V_attachFlags(vp) |= VOL_IN_HASH;
6647 vp->chainCacheCheck = ++head->cacheCheck;
6648 #endif /* AFS_DEMAND_ATTACH_FS */
6651 vp->hashid = hashid;
6652 queue_Append(head, vp);
6653 vp->vnodeHashOffset = VolumeHashOffset_r();
6657 * delete a volume object from the hash table.
6659 * @param[in] vp pointer to volume object
6661 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
6664 * @post volume is removed from hash chain.
6666 * @internal volume package internal use only.
6668 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
6669 * asynchronous hash chain reordering to finish.
6672 DeleteVolumeFromHashTable(register Volume * vp)
6674 VolumeHashChainHead * head;
6676 if (!queue_IsOnQueue(vp))
6679 head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
6681 #ifdef AFS_DEMAND_ATTACH_FS
6682 /* wait for the hash chain to become available */
6685 V_attachFlags(vp) &= ~(VOL_IN_HASH);
6687 #endif /* AFS_DEMAND_ATTACH_FS */
6691 /* do NOT reset hashid to zero, as the online
6692 * salvager package may need to know the volume id
6693 * after the volume is removed from the hash */
6697 * lookup a volume object in the hash table given a volume id.
6699 * @param[out] ec error code return
6700 * @param[in] volumeId volume id
6701 * @param[in] hint volume object which we believe could be the correct
6704 * @return volume object pointer
6705 * @retval NULL no such volume id is registered with the hash table.
6707 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
6710 * @post volume object with the given id is returned. volume object and
6711 * hash chain access statistics are updated. hash chain may have
6714 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
6715 * asynchronous hash chain reordering operation to finish, or
6716 * in order for us to perform an asynchronous chain reordering.
6718 * @note Hash chain reorderings occur when the access count for the
6719 * volume object being looked up exceeds the sum of the previous
6720 * node's (the node ahead of it in the hash chain linked list)
6721 * access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
6723 * @note For DAFS, the hint parameter allows us to short-circuit if the
6724 * cacheCheck fields match between the hash chain head and the
6725 * hint volume object.
6728 VLookupVolume_r(Error * ec, VolId volumeId, Volume * hint)
6730 register int looks = 0;
6732 #ifdef AFS_DEMAND_ATTACH_FS
6735 VolumeHashChainHead * head;
6738 head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
6740 #ifdef AFS_DEMAND_ATTACH_FS
6741 /* wait for the hash chain to become available */
6744 /* check to see if we can short circuit without walking the hash chain */
6745 if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
6746 IncUInt64(&hint->stats.hash_short_circuits);
6749 #endif /* AFS_DEMAND_ATTACH_FS */
6751 /* someday we need to either do per-chain locks, RWlocks,
6752 * or both for volhash access.
6753 * (and move to a data structure with better cache locality) */
6755 /* search the chain for this volume id */
6756 for(queue_Scan(head, vp, np, Volume)) {
6758 if ((vp->hashid == volumeId)) {
6763 if (queue_IsEnd(head, vp)) {
6767 #ifdef AFS_DEMAND_ATTACH_FS
6768 /* update hash chain statistics */
6771 FillInt64(lks, 0, looks);
6772 AddUInt64(head->looks, lks, &head->looks);
6773 AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
6774 IncUInt64(&head->gets);
6779 IncUInt64(&vp->stats.hash_lookups);
6781 /* for demand attach fileserver, we permit occasional hash chain reordering
6782 * so that frequently looked up volumes move towards the head of the chain */
6783 pp = queue_Prev(vp, Volume);
6784 if (!queue_IsEnd(head, pp)) {
6785 FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
6786 AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
6787 if (GEInt64(vp->stats.hash_lookups, thresh)) {
6788 VReorderHash_r(head, pp, vp);
6792 /* update the short-circuit cache check */
6793 vp->chainCacheCheck = head->cacheCheck;
6795 #endif /* AFS_DEMAND_ATTACH_FS */
6800 #ifdef AFS_DEMAND_ATTACH_FS
6801 /* perform volume hash chain reordering.
6803 * advance a subchain beginning at vp ahead of
6804 * the adjacent subchain ending at pp */
6806 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
6808 Volume *tp, *np, *lp;
6809 afs_uint64 move_thresh;
6811 /* this should never be called if the chain is already busy, so
6812 * no need to wait for other exclusive chain ops to finish */
6814 /* this is a rather heavy set of operations,
6815 * so let's set the chain busy flag and drop
6817 VHashBeginExclusive_r(head);
6820 /* scan forward in the chain from vp looking for the last element
6821 * in the chain we want to advance */
6822 FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
6823 AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
6824 for(queue_ScanFrom(head, vp, tp, np, Volume)) {
6825 if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
6829 lp = queue_Prev(tp, Volume);
6831 /* scan backwards from pp to determine where to splice and
6832 * insert the subchain we're advancing */
6833 for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
6834 if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
6838 tp = queue_Next(tp, Volume);
6840 /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
6841 queue_MoveChainBefore(tp,vp,lp);
6844 IncUInt64(&VStats.hash_reorders);
6846 IncUInt64(&head->reorders);
6848 /* wake up any threads waiting for the hash chain */
6849 VHashEndExclusive_r(head);
6853 /* demand-attach fs volume hash
6854 * asynchronous exclusive operations */
6857 * begin an asynchronous exclusive operation on a volume hash chain.
6859 * @param[in] head pointer to volume hash chain head object
6861 * @pre VOL_LOCK held. hash chain is quiescent.
6863 * @post hash chain marked busy.
6865 * @note this interface is used in conjunction with VHashEndExclusive_r and
6866 * VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
6867 * volume hash chain. Its main use case is hash chain reordering, which
6868 * has the potential to be a highly latent operation.
6870 * @see VHashEndExclusive_r
6875 * @internal volume package internal use only.
6878 VHashBeginExclusive_r(VolumeHashChainHead * head)
6880 assert(head->busy == 0);
6885 * relinquish exclusive ownership of a volume hash chain.
6887 * @param[in] head pointer to volume hash chain head object
6889 * @pre VOL_LOCK held. thread owns the hash chain exclusively.
6891 * @post hash chain is marked quiescent. threads awaiting use of
6892 * chain are awakened.
6894 * @see VHashBeginExclusive_r
6899 * @internal volume package internal use only.
6902 VHashEndExclusive_r(VolumeHashChainHead * head)
6906 assert(pthread_cond_broadcast(&head->chain_busy_cv) == 0);
6910 * wait for all asynchronous operations on a hash chain to complete.
6912 * @param[in] head pointer to volume hash chain head object
6914 * @pre VOL_LOCK held.
6916 * @post hash chain object is quiescent.
6918 * @see VHashBeginExclusive_r
6919 * @see VHashEndExclusive_r
6923 * @note This interface should be called before any attempt to
6924 * traverse the hash chain. It is permissible for a thread
6925 * to gain exclusive access to the chain, and then perform
6926 * latent operations on the chain asynchronously wrt the
6929 * @warning if waiting is necessary, VOL_LOCK is dropped
6931 * @internal volume package internal use only.
6934 VHashWait_r(VolumeHashChainHead * head)
6936 while (head->busy) {
6937 VOL_CV_WAIT(&head->chain_busy_cv);
6940 #endif /* AFS_DEMAND_ATTACH_FS */
6943 /***************************************************/
6944 /* Volume by Partition List routines */
6945 /***************************************************/
6948 * demand attach fileserver adds a
6949 * linked list of volumes to each
6950 * partition object, thus allowing
6951 * for quick enumeration of all
6952 * volumes on a partition
6955 #ifdef AFS_DEMAND_ATTACH_FS
6957 * add a volume to its disk partition VByPList.
6959 * @param[in] vp pointer to volume object
6961 * @pre either the disk partition VByPList is owned exclusively
6962 * by the calling thread, or the list is quiescent and
6965 * @post volume is added to disk partition VByPList
6969 * @warning it is the caller's responsibility to ensure list
6972 * @see VVByPListWait_r
6973 * @see VVByPListBeginExclusive_r
6974 * @see VVByPListEndExclusive_r
6976 * @internal volume package internal use only.
6979 AddVolumeToVByPList_r(Volume * vp)
6981 if (queue_IsNotOnQueue(&vp->vol_list)) {
6982 queue_Append(&vp->partition->vol_list, &vp->vol_list);
6983 V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
6984 vp->partition->vol_list.len++;
6989 * delete a volume from its disk partition VByPList.
6991 * @param[in] vp pointer to volume object
6993 * @pre either the disk partition VByPList is owned exclusively
6994 * by the calling thread, or the list is quiescent and
6997 * @post volume is removed from the disk partition VByPList
7001 * @warning it is the caller's responsibility to ensure list
7004 * @see VVByPListWait_r
7005 * @see VVByPListBeginExclusive_r
7006 * @see VVByPListEndExclusive_r
7008 * @internal volume package internal use only.
7011 DeleteVolumeFromVByPList_r(Volume * vp)
7013 if (queue_IsOnQueue(&vp->vol_list)) {
7014 queue_Remove(&vp->vol_list);
7015 V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
7016 vp->partition->vol_list.len--;
7021 * begin an asynchronous exclusive operation on a VByPList.
7023 * @param[in] dp pointer to disk partition object
7025 * @pre VOL_LOCK held. VByPList is quiescent.
7027 * @post VByPList marked busy.
7029 * @note this interface is used in conjunction with VVByPListEndExclusive_r and
7030 * VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
7033 * @see VVByPListEndExclusive_r
7034 * @see VVByPListWait_r
7038 * @internal volume package internal use only.
7040 /* take exclusive control over the list */
7042 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
7044 assert(dp->vol_list.busy == 0);
7045 dp->vol_list.busy = 1;
7049 * relinquish exclusive ownership of a VByPList.
7051 * @param[in] dp pointer to disk partition object
7053 * @pre VOL_LOCK held. thread owns the VByPList exclusively.
7055 * @post VByPList is marked quiescent. threads awaiting use of
7056 * the list are awakened.
7058 * @see VVByPListBeginExclusive_r
7059 * @see VVByPListWait_r
7063 * @internal volume package internal use only.
7066 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
7068 assert(dp->vol_list.busy);
7069 dp->vol_list.busy = 0;
7070 assert(pthread_cond_broadcast(&dp->vol_list.cv) == 0);
7074 * wait for all asynchronous operations on a VByPList to complete.
7076 * @param[in] dp pointer to disk partition object
7078 * @pre VOL_LOCK is held.
7080 * @post disk partition's VByP list is quiescent
7084 * @note This interface should be called before any attempt to
7085 * traverse the VByPList. It is permissible for a thread
7086 * to gain exclusive access to the list, and then perform
7087 * latent operations on the list asynchronously wrt the
7090 * @warning if waiting is necessary, VOL_LOCK is dropped
7092 * @see VVByPListEndExclusive_r
7093 * @see VVByPListBeginExclusive_r
7095 * @internal volume package internal use only.
7098 VVByPListWait_r(struct DiskPartition64 * dp)
7100 while (dp->vol_list.busy) {
7101 VOL_CV_WAIT(&dp->vol_list.cv);
7104 #endif /* AFS_DEMAND_ATTACH_FS */
7106 /***************************************************/
7107 /* Volume Cache Statistics routines */
7108 /***************************************************/
7111 VPrintCacheStats_r(void)
7113 afs_uint32 get_hi, get_lo, load_hi, load_lo;
7114 register struct VnodeClassInfo *vcp;
7115 vcp = &VnodeClassInfo[vLarge];
7116 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);
7117 vcp = &VnodeClassInfo[vSmall];
7118 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);
7119 SplitInt64(VStats.hdr_gets, get_hi, get_lo);
7120 SplitInt64(VStats.hdr_loads, load_hi, load_lo);
7121 Log("Volume header cache, %d entries, %d gets, %d replacements\n",
7122 VStats.hdr_cache_size, get_lo, load_lo);
7126 VPrintCacheStats(void)
7129 VPrintCacheStats_r();
7133 #ifdef AFS_DEMAND_ATTACH_FS
7135 UInt64ToDouble(afs_uint64 * x)
7137 static double c32 = 4.0 * 1.073741824 * 1000000000.0;
7139 SplitInt64(*x, h, l);
7140 return (((double)h) * c32) + ((double) l);
7144 DoubleToPrintable(double x, char * buf, int len)
7146 static double billion = 1000000000.0;
7149 y[0] = (afs_uint32) (x / (billion * billion));
7150 y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
7151 y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
7154 snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
7156 snprintf(buf, len, "%d%09d", y[1], y[2]);
7158 snprintf(buf, len, "%d", y[2]);
7164 struct VLRUExtStatsEntry {
7168 struct VLRUExtStats {
7174 } queue_info[VLRU_QUEUE_INVALID];
7175 struct VLRUExtStatsEntry * vec;
7179 * add a 256-entry fudge factor onto the vector in case state changes
7180 * out from under us.
7182 #define VLRU_EXT_STATS_VEC_LEN_FUDGE 256
7185 * collect extended statistics for the VLRU subsystem.
7187 * @param[out] stats pointer to stats structure to be populated
7188 * @param[in] nvols number of volumes currently known to exist
7190 * @pre VOL_LOCK held
7192 * @post stats->vec allocated and populated
7194 * @return operation status
7199 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
7201 afs_uint32 cur, idx, len;
7202 struct rx_queue * qp, * nqp;
7204 struct VLRUExtStatsEntry * vec;
7206 len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
7207 vec = stats->vec = calloc(len,
7208 sizeof(struct VLRUExtStatsEntry));
7214 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
7215 VLRU_Wait_r(&volume_LRU.q[idx]);
7216 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7219 stats->queue_info[idx].start = cur;
7221 for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7223 /* out of space in vec */
7226 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7227 vec[cur].volid = vp->hashid;
7231 stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
7234 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7242 #define ENUMTOSTRING(en) #en
7243 #define ENUMCASE(en) \
7245 return ENUMTOSTRING(en); \
7249 vlru_idx_to_string(int idx)
7252 ENUMCASE(VLRU_QUEUE_NEW);
7253 ENUMCASE(VLRU_QUEUE_MID);
7254 ENUMCASE(VLRU_QUEUE_OLD);
7255 ENUMCASE(VLRU_QUEUE_CANDIDATE);
7256 ENUMCASE(VLRU_QUEUE_HELD);
7257 ENUMCASE(VLRU_QUEUE_INVALID);
7259 return "**UNKNOWN**";
7264 VPrintExtendedCacheStats_r(int flags)
7267 afs_uint32 vol_sum = 0;
7274 struct stats looks, gets, reorders, len;
7275 struct stats ch_looks, ch_gets, ch_reorders;
7277 VolumeHashChainHead *head;
7279 struct VLRUExtStats vlru_stats;
7281 /* zero out stats */
7282 memset(&looks, 0, sizeof(struct stats));
7283 memset(&gets, 0, sizeof(struct stats));
7284 memset(&reorders, 0, sizeof(struct stats));
7285 memset(&len, 0, sizeof(struct stats));
7286 memset(&ch_looks, 0, sizeof(struct stats));
7287 memset(&ch_gets, 0, sizeof(struct stats));
7288 memset(&ch_reorders, 0, sizeof(struct stats));
7290 for (i = 0; i < VolumeHashTable.Size; i++) {
7291 head = &VolumeHashTable.Table[i];
7294 VHashBeginExclusive_r(head);
7297 ch_looks.sum = UInt64ToDouble(&head->looks);
7298 ch_gets.sum = UInt64ToDouble(&head->gets);
7299 ch_reorders.sum = UInt64ToDouble(&head->reorders);
7301 /* update global statistics */
7303 looks.sum += ch_looks.sum;
7304 gets.sum += ch_gets.sum;
7305 reorders.sum += ch_reorders.sum;
7306 len.sum += (double)head->len;
7307 vol_sum += head->len;
7310 len.min = (double) head->len;
7311 len.max = (double) head->len;
7312 looks.min = ch_looks.sum;
7313 looks.max = ch_looks.sum;
7314 gets.min = ch_gets.sum;
7315 gets.max = ch_gets.sum;
7316 reorders.min = ch_reorders.sum;
7317 reorders.max = ch_reorders.sum;
7319 if (((double)head->len) < len.min)
7320 len.min = (double) head->len;
7321 if (((double)head->len) > len.max)
7322 len.max = (double) head->len;
7323 if (ch_looks.sum < looks.min)
7324 looks.min = ch_looks.sum;
7325 else if (ch_looks.sum > looks.max)
7326 looks.max = ch_looks.sum;
7327 if (ch_gets.sum < gets.min)
7328 gets.min = ch_gets.sum;
7329 else if (ch_gets.sum > gets.max)
7330 gets.max = ch_gets.sum;
7331 if (ch_reorders.sum < reorders.min)
7332 reorders.min = ch_reorders.sum;
7333 else if (ch_reorders.sum > reorders.max)
7334 reorders.max = ch_reorders.sum;
7338 if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
7339 /* compute detailed per-chain stats */
7340 struct stats hdr_loads, hdr_gets;
7341 double v_looks, v_loads, v_gets;
7343 /* initialize stats with data from first element in chain */
7344 vp = queue_First(head, Volume);
7345 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
7346 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
7347 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
7348 ch_gets.min = ch_gets.max = v_looks;
7349 hdr_loads.min = hdr_loads.max = v_loads;
7350 hdr_gets.min = hdr_gets.max = v_gets;
7351 hdr_loads.sum = hdr_gets.sum = 0;
7353 vp = queue_Next(vp, Volume);
7355 /* pull in stats from remaining elements in chain */
7356 for (queue_ScanFrom(head, vp, vp, np, Volume)) {
7357 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
7358 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
7359 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
7361 hdr_loads.sum += v_loads;
7362 hdr_gets.sum += v_gets;
7364 if (v_looks < ch_gets.min)
7365 ch_gets.min = v_looks;
7366 else if (v_looks > ch_gets.max)
7367 ch_gets.max = v_looks;
7369 if (v_loads < hdr_loads.min)
7370 hdr_loads.min = v_loads;
7371 else if (v_loads > hdr_loads.max)
7372 hdr_loads.max = v_loads;
7374 if (v_gets < hdr_gets.min)
7375 hdr_gets.min = v_gets;
7376 else if (v_gets > hdr_gets.max)
7377 hdr_gets.max = v_gets;
7380 /* compute per-chain averages */
7381 ch_gets.avg = ch_gets.sum / ((double)head->len);
7382 hdr_loads.avg = hdr_loads.sum / ((double)head->len);
7383 hdr_gets.avg = hdr_gets.sum / ((double)head->len);
7385 /* dump per-chain stats */
7386 Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
7388 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
7389 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
7390 Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
7391 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
7392 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
7393 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
7394 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
7395 Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
7396 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
7397 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
7398 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
7399 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
7400 Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
7401 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
7402 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
7403 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
7404 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
7405 } else if (flags & VOL_STATS_PER_CHAIN) {
7406 /* dump simple per-chain stats */
7407 Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
7409 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
7410 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
7411 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
7415 VHashEndExclusive_r(head);
7420 /* compute global averages */
7421 len.avg = len.sum / ((double)VolumeHashTable.Size);
7422 looks.avg = looks.sum / ((double)VolumeHashTable.Size);
7423 gets.avg = gets.sum / ((double)VolumeHashTable.Size);
7424 reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
7426 /* dump global stats */
7427 Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
7428 Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
7429 DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
7430 DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
7431 DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
7432 DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
7433 Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
7434 DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
7435 DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
7436 DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
7437 DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
7438 Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
7439 DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
7440 DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
7441 DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
7442 DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
7443 Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
7444 DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
7445 DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
7446 DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
7447 DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
7449 /* print extended disk related statistics */
7451 struct DiskPartition64 * diskP;
7452 afs_uint32 vol_count[VOLMAXPARTS+1];
7453 byte part_exists[VOLMAXPARTS+1];
7457 memset(vol_count, 0, sizeof(vol_count));
7458 memset(part_exists, 0, sizeof(part_exists));
7462 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
7464 vol_count[id] = diskP->vol_list.len;
7465 part_exists[id] = 1;
7469 for (i = 0; i <= VOLMAXPARTS; i++) {
7470 if (part_exists[i]) {
7471 /* XXX while this is currently safe, it is a violation
7472 * of the VGetPartitionById_r interface contract. */
7473 diskP = VGetPartitionById_r(i, 0);
7475 Log("Partition %s has %d online volumes\n",
7476 VPartitionPath(diskP), diskP->vol_list.len);
7483 /* print extended VLRU statistics */
7484 if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
7485 afs_uint32 idx, cur, lpos;
7489 Log("VLRU State Dump:\n\n");
7491 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
7492 Log("\t%s:\n", vlru_idx_to_string(idx));
7495 for (cur = vlru_stats.queue_info[idx].start;
7496 cur < vlru_stats.queue_info[idx].len;
7498 line[lpos++] = vlru_stats.vec[cur].volid;
7500 Log("\t\t%u, %u, %u, %u, %u,\n",
7501 line[0], line[1], line[2], line[3], line[4]);
7510 Log("\t\t%u, %u, %u, %u, %u\n",
7511 line[0], line[1], line[2], line[3], line[4]);
7516 free(vlru_stats.vec);
7523 VPrintExtendedCacheStats(int flags)
7526 VPrintExtendedCacheStats_r(flags);
7529 #endif /* AFS_DEMAND_ATTACH_FS */