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);
199 #ifdef AFS_DEMAND_ATTACH_FS
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 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
2335 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
2338 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
2339 /* fall through to take volume offline */
2342 case FSSYNC_VolOpRunningOffline:
2343 /* mark the volume down */
2345 VChangeState_r(vp, VOL_STATE_UNATTACHED);
2346 if (V_offlineMessage(vp)[0] == '\0')
2347 strlcpy(V_offlineMessage(vp),
2348 "A volume utility is running.",
2349 sizeof(V_offlineMessage(vp)));
2350 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
2352 /* check to see if we should set the specialStatus flag */
2353 if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
2354 vp->specialStatus = VBUSY;
2359 V_attachFlags(vp) |= VOL_HDR_LOADED;
2360 vp->stats.last_hdr_load = vp->stats.last_attach;
2362 #endif /* AFS_DEMAND_ATTACH_FS */
2365 struct IndexFileHeader iHead;
2367 #if OPENAFS_VOL_STATS
2369 * We just read in the diskstuff part of the header. If the detailed
2370 * volume stats area has not yet been initialized, we should bzero the
2371 * area and mark it as initialized.
2373 if (!(V_stat_initialized(vp))) {
2374 memset((char *)(V_stat_area(vp)), 0, VOL_STATS_BYTES);
2375 V_stat_initialized(vp) = 1;
2377 #endif /* OPENAFS_VOL_STATS */
2379 (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
2380 (char *)&iHead, sizeof(iHead),
2381 SMALLINDEXMAGIC, SMALLINDEXVERSION);
2384 Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
2389 struct IndexFileHeader iHead;
2391 (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
2392 (char *)&iHead, sizeof(iHead),
2393 LARGEINDEXMAGIC, LARGEINDEXVERSION);
2396 Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
2400 #ifdef AFS_NAMEI_ENV
2402 struct versionStamp stamp;
2404 (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
2405 sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
2408 Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
2411 #endif /* AFS_NAMEI_ENV */
2413 #if defined(AFS_DEMAND_ATTACH_FS)
2414 if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
2416 if (programType == fileServer) {
2417 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2420 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
2426 /* volume operation in progress */
2430 #else /* AFS_DEMAND_ATTACH_FS */
2432 Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
2437 #endif /* AFS_DEMAND_ATTACH_FS */
2439 if (V_needsSalvaged(vp)) {
2440 if (vp->specialStatus)
2441 vp->specialStatus = 0;
2443 #if defined(AFS_DEMAND_ATTACH_FS)
2444 if (programType == fileServer) {
2445 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
2448 Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
2452 #else /* AFS_DEMAND_ATTACH_FS */
2455 #endif /* AFS_DEMAND_ATTACH_FS */
2460 if (programType == fileServer) {
2461 #ifndef FAST_RESTART
2462 if (V_inUse(vp) && VolumeWriteable(vp)) {
2463 if (!V_needsSalvaged(vp)) {
2464 V_needsSalvaged(vp) = 1;
2465 VUpdateVolume_r(ec, vp, 0);
2467 #if defined(AFS_DEMAND_ATTACH_FS)
2468 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
2470 #else /* AFS_DEMAND_ATTACH_FS */
2471 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
2474 #endif /* AFS_DEMAND_ATTACH_FS */
2477 #endif /* FAST_RESTART */
2479 if (V_destroyMe(vp) == DESTROY_ME) {
2480 #if defined(AFS_DEMAND_ATTACH_FS)
2481 /* schedule a salvage so the volume goes away on disk */
2482 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2483 VChangeState_r(vp, VOL_STATE_ERROR);
2485 #endif /* AFS_DEMAND_ATTACH_FS */
2487 Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
2493 vp->nextVnodeUnique = V_uniquifier(vp);
2494 vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
2495 #ifndef BITMAP_LATER
2496 if (programType == fileServer && VolumeWriteable(vp)) {
2498 for (i = 0; i < nVNODECLASSES; i++) {
2499 VGetBitmap_r(ec, vp, i);
2501 #ifdef AFS_DEMAND_ATTACH_FS
2502 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2504 #else /* AFS_DEMAND_ATTACH_FS */
2506 #endif /* AFS_DEMAND_ATTACH_FS */
2507 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
2513 #endif /* BITMAP_LATER */
2515 if (programType == fileServer) {
2516 if (vp->specialStatus)
2517 vp->specialStatus = 0;
2518 if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
2519 V_inUse(vp) = fileServer;
2520 V_offlineMessage(vp)[0] = '\0';
2523 if ((mode != V_PEEK) && (mode != V_SECRETLY))
2524 V_inUse(vp) = programType;
2525 V_checkoutMode(vp) = mode;
2528 AddVolumeToHashTable(vp, V_id(vp));
2529 #ifdef AFS_DEMAND_ATTACH_FS
2530 if ((programType != fileServer) ||
2531 (V_inUse(vp) == fileServer)) {
2532 AddVolumeToVByPList_r(vp);
2534 VChangeState_r(vp, VOL_STATE_ATTACHED);
2536 VChangeState_r(vp, VOL_STATE_UNATTACHED);
2542 /* Attach an existing volume.
2543 The volume also normally goes online at this time.
2544 An offline volume must be reattached to make it go online.
2548 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
2552 retVal = VAttachVolume_r(ec, volumeId, mode);
2558 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
2561 VGetVolumePath(ec, volumeId, &part, &name);
2563 register Volume *vp;
2565 vp = VGetVolume_r(&error, volumeId);
2567 assert(V_inUse(vp) == 0);
2568 VDetachVolume_r(ec, vp);
2572 return VAttachVolumeByName_r(ec, part, name, mode);
2575 /* Increment a reference count to a volume, sans context swaps. Requires
2576 * possibly reading the volume header in from the disk, since there's
2577 * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
2579 * N.B. This call can fail if we can't read in the header!! In this case
2580 * we still guarantee we won't context swap, but the ref count won't be
2581 * incremented (otherwise we'd violate the invariant).
2583 /* NOTE: with the demand attach fileserver extensions, the global lock
2584 * is dropped within VHold */
2585 #ifdef AFS_DEMAND_ATTACH_FS
2587 VHold_r(register Volume * vp)
2591 VCreateReservation_r(vp);
2592 VWaitExclusiveState_r(vp);
2594 LoadVolumeHeader(&error, vp);
2596 VCancelReservation_r(vp);
2600 VCancelReservation_r(vp);
2603 #else /* AFS_DEMAND_ATTACH_FS */
2605 VHold_r(register Volume * vp)
2609 LoadVolumeHeader(&error, vp);
2615 #endif /* AFS_DEMAND_ATTACH_FS */
2619 VHold(register Volume * vp)
2623 retVal = VHold_r(vp);
2630 /***************************************************/
2631 /* get and put volume routines */
2632 /***************************************************/
2635 * put back a heavyweight reference to a volume object.
2637 * @param[in] vp volume object pointer
2639 * @pre VOL_LOCK held
2641 * @post heavyweight volume reference put back.
2642 * depending on state, volume may have been taken offline,
2643 * detached, salvaged, freed, etc.
2645 * @internal volume package internal use only
2648 VPutVolume_r(register Volume * vp)
2650 assert(--vp->nUsers >= 0);
2651 if (vp->nUsers == 0) {
2653 ReleaseVolumeHeader(vp->header);
2654 #ifdef AFS_DEMAND_ATTACH_FS
2655 if (!VCheckDetach(vp)) {
2659 #else /* AFS_DEMAND_ATTACH_FS */
2661 #endif /* AFS_DEMAND_ATTACH_FS */
2666 VPutVolume(register Volume * vp)
2674 /* Get a pointer to an attached volume. The pointer is returned regardless
2675 of whether or not the volume is in service or on/off line. An error
2676 code, however, is returned with an indication of the volume's status */
2678 VGetVolume(Error * ec, Error * client_ec, VolId volumeId)
2682 retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
2688 VGetVolume_r(Error * ec, VolId volumeId)
2690 return GetVolume(ec, NULL, volumeId, NULL, 0);
2693 /* try to get a volume we've previously looked up */
2694 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
2696 VGetVolumeByVp_r(Error * ec, Volume * vp)
2698 return GetVolume(ec, NULL, vp->hashid, vp, 0);
2701 /* private interface for getting a volume handle
2702 * volumeId must be provided.
2703 * hint is an optional parameter to speed up hash lookups
2704 * flags is not used at this time
2706 /* for demand attach fs, caller MUST NOT hold a ref count on hint */
2708 GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint, int flags)
2711 /* pull this profiling/debugging code out of regular builds */
2713 #define VGET_CTR_INC(x) x++
2714 unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
2715 0, V7 = 0, V8 = 0, V9 = 0;
2716 unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
2718 #define VGET_CTR_INC(x)
2720 #ifdef AFS_DEMAND_ATTACH_FS
2721 Volume *avp, * rvp = hint;
2725 * if VInit is zero, the volume package dynamic
2726 * data structures have not been initialized yet,
2727 * and we must immediately return an error
2733 *client_ec = VOFFLINE;
2738 #ifdef AFS_DEMAND_ATTACH_FS
2740 VCreateReservation_r(rvp);
2742 #endif /* AFS_DEMAND_ATTACH_FS */
2750 vp = VLookupVolume_r(ec, volumeId, vp);
2756 #ifdef AFS_DEMAND_ATTACH_FS
2757 if (rvp && (rvp != vp)) {
2758 /* break reservation on old vp */
2759 VCancelReservation_r(rvp);
2762 #endif /* AFS_DEMAND_ATTACH_FS */
2768 /* Until we have reached an initialization level of 2
2769 * we don't know whether this volume exists or not.
2770 * We can't sleep and retry later because before a volume
2771 * is attached, the caller tries to get it first. Just
2772 * return VOFFLINE and the caller can choose whether to
2773 * retry the command or not. */
2783 IncUInt64(&VStats.hdr_gets);
2785 #ifdef AFS_DEMAND_ATTACH_FS
2786 /* block if someone else is performing an exclusive op on this volume */
2789 VCreateReservation_r(rvp);
2791 VWaitExclusiveState_r(vp);
2793 /* short circuit with VNOVOL in the following circumstances:
2796 * - VOL_STATE_SHUTTING_DOWN
2798 if ((V_attachState(vp) == VOL_STATE_ERROR) ||
2799 (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN) ||
2800 (V_attachState(vp) == VOL_STATE_GOING_OFFLINE)) {
2807 * short circuit with VOFFLINE in the following circumstances:
2809 * - VOL_STATE_UNATTACHED
2811 if (V_attachState(vp) == VOL_STATE_UNATTACHED) {
2812 if (vp->specialStatus) {
2813 *ec = vp->specialStatus;
2821 /* allowable states:
2827 if (vp->salvage.requested) {
2828 VUpdateSalvagePriority_r(vp);
2831 if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
2832 avp = VAttachVolumeByVp_r(ec, vp, 0);
2835 /* VAttachVolumeByVp_r can return a pointer
2836 * != the vp passed to it under certain
2837 * conditions; make sure we don't leak
2838 * reservations if that happens */
2840 VCancelReservation_r(rvp);
2842 VCreateReservation_r(rvp);
2852 if (!vp->pending_vol_op) {
2867 if ((V_attachState(vp) == VOL_STATE_SALVAGING) ||
2868 (*ec == VSALVAGING)) {
2870 /* see CheckVnode() in afsfileprocs.c for an explanation
2871 * of this error code logic */
2872 afs_uint32 now = FT_ApproxTime();
2873 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
2876 *client_ec = VRESTARTING;
2885 LoadVolumeHeader(ec, vp);
2888 /* Only log the error if it was a totally unexpected error. Simply
2889 * a missing inode is likely to be caused by the volume being deleted */
2890 if (errno != ENXIO || LogLevel)
2891 Log("Volume %u: couldn't reread volume header\n",
2893 #ifdef AFS_DEMAND_ATTACH_FS
2894 if (programType == fileServer) {
2895 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2900 #else /* AFS_DEMAND_ATTACH_FS */
2903 #endif /* AFS_DEMAND_ATTACH_FS */
2907 #ifdef AFS_DEMAND_ATTACH_FS
2909 * this test MUST happen after the volume header is loaded
2912 /* only valid before/during demand attachment */
2913 assert(!vp->pending_vol_op || vp->pending_vol_op != FSSYNC_VolOpRunningUnknown);
2915 /* deny getvolume due to running mutually exclusive vol op */
2916 if (vp->pending_vol_op && vp->pending_vol_op->vol_op_state==FSSYNC_VolOpRunningOffline) {
2918 * volume cannot remain online during this volume operation.
2921 if (vp->specialStatus) {
2923 * special status codes outrank normal VOFFLINE code
2925 *ec = vp->specialStatus;
2927 *client_ec = vp->specialStatus;
2931 /* see CheckVnode() in afsfileprocs.c for an explanation
2932 * of this error code logic */
2933 afs_uint32 now = FT_ApproxTime();
2934 if ((vp->stats.last_vol_op + (10 * 60)) >= now) {
2937 *client_ec = VRESTARTING;
2942 VChangeState_r(vp, VOL_STATE_UNATTACHED);
2943 FreeVolumeHeader(vp);
2947 #endif /* AFS_DEMAND_ATTACH_FS */
2950 if (vp->shuttingDown) {
2957 if (programType == fileServer) {
2959 if (vp->goingOffline) {
2961 #ifdef AFS_DEMAND_ATTACH_FS
2962 /* wait for the volume to go offline */
2963 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
2964 VWaitStateChange_r(vp);
2966 #elif defined(AFS_PTHREAD_ENV)
2967 VOL_CV_WAIT(&vol_put_volume_cond);
2968 #else /* AFS_PTHREAD_ENV */
2969 LWP_WaitProcess(VPutVolume);
2970 #endif /* AFS_PTHREAD_ENV */
2973 if (vp->specialStatus) {
2975 *ec = vp->specialStatus;
2976 } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
2979 } else if (V_inUse(vp) == 0) {
2990 #ifdef AFS_DEMAND_ATTACH_FS
2991 /* if no error, bump nUsers */
2994 VLRU_UpdateAccess_r(vp);
2997 VCancelReservation_r(rvp);
3000 if (client_ec && !*client_ec) {
3003 #else /* AFS_DEMAND_ATTACH_FS */
3004 /* if no error, bump nUsers */
3011 #endif /* AFS_DEMAND_ATTACH_FS */
3019 /***************************************************/
3020 /* Volume offline/detach routines */
3021 /***************************************************/
3023 /* caller MUST hold a heavyweight ref on vp */
3024 #ifdef AFS_DEMAND_ATTACH_FS
3026 VTakeOffline_r(register Volume * vp)
3030 assert(vp->nUsers > 0);
3031 assert(programType == fileServer);
3033 VCreateReservation_r(vp);
3034 VWaitExclusiveState_r(vp);
3036 vp->goingOffline = 1;
3037 V_needsSalvaged(vp) = 1;
3039 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
3040 VCancelReservation_r(vp);
3042 #else /* AFS_DEMAND_ATTACH_FS */
3044 VTakeOffline_r(register Volume * vp)
3046 assert(vp->nUsers > 0);
3047 assert(programType == fileServer);
3049 vp->goingOffline = 1;
3050 V_needsSalvaged(vp) = 1;
3052 #endif /* AFS_DEMAND_ATTACH_FS */
3055 VTakeOffline(register Volume * vp)
3063 * force a volume offline.
3065 * @param[in] vp volume object pointer
3066 * @param[in] flags flags (see note below)
3068 * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
3069 * used when VUpdateVolume_r needs to call VForceOffline_r
3070 * (which in turn would normally call VUpdateVolume_r)
3072 * @see VUpdateVolume_r
3074 * @pre VOL_LOCK must be held.
3075 * for DAFS, caller must hold ref.
3077 * @note for DAFS, it _is safe_ to call this function from an
3080 * @post needsSalvaged flag is set.
3081 * for DAFS, salvage is requested.
3082 * no further references to the volume through the volume
3083 * package will be honored.
3084 * all file descriptor and vnode caches are invalidated.
3086 * @warning this is a heavy-handed interface. it results in
3087 * a volume going offline regardless of the current
3088 * reference count state.
3090 * @internal volume package internal use only
3093 VForceOffline_r(Volume * vp, int flags)
3097 #ifdef AFS_DEMAND_ATTACH_FS
3098 VChangeState_r(vp, VOL_STATE_ERROR);
3103 strcpy(V_offlineMessage(vp),
3104 "Forced offline due to internal error: volume needs to be salvaged");
3105 Log("Volume %u forced offline: it needs salvaging!\n", V_id(vp));
3108 vp->goingOffline = 0;
3109 V_needsSalvaged(vp) = 1;
3110 if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
3111 VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
3114 #ifdef AFS_DEMAND_ATTACH_FS
3115 VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3116 #endif /* AFS_DEMAND_ATTACH_FS */
3118 #ifdef AFS_PTHREAD_ENV
3119 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3120 #else /* AFS_PTHREAD_ENV */
3121 LWP_NoYieldSignal(VPutVolume);
3122 #endif /* AFS_PTHREAD_ENV */
3124 VReleaseVolumeHandles_r(vp);
3128 * force a volume offline.
3130 * @param[in] vp volume object pointer
3132 * @see VForceOffline_r
3135 VForceOffline(Volume * vp)
3138 VForceOffline_r(vp, 0);
3142 /* The opposite of VAttachVolume. The volume header is written to disk, with
3143 the inUse bit turned off. A copy of the header is maintained in memory,
3144 however (which is why this is VOffline, not VDetach).
3147 VOffline_r(Volume * vp, char *message)
3150 VolumeId vid = V_id(vp);
3152 assert(programType != volumeUtility);
3157 if (V_offlineMessage(vp)[0] == '\0')
3158 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
3159 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
3161 vp->goingOffline = 1;
3162 #ifdef AFS_DEMAND_ATTACH_FS
3163 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
3164 VCreateReservation_r(vp);
3167 /* wait for the volume to go offline */
3168 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
3169 VWaitStateChange_r(vp);
3171 VCancelReservation_r(vp);
3172 #else /* AFS_DEMAND_ATTACH_FS */
3174 vp = VGetVolume_r(&error, vid); /* Wait for it to go offline */
3175 if (vp) /* In case it was reattached... */
3177 #endif /* AFS_DEMAND_ATTACH_FS */
3180 #ifdef AFS_DEMAND_ATTACH_FS
3182 * Take a volume offline in order to perform a volume operation.
3184 * @param[inout] ec address in which to store error code
3185 * @param[in] vp volume object pointer
3186 * @param[in] message volume offline status message
3189 * - VOL_LOCK is held
3190 * - caller MUST hold a heavyweight ref on vp
3193 * - volume is taken offline
3194 * - if possible, volume operation is promoted to running state
3195 * - on failure, *ec is set to nonzero
3197 * @note Although this function does not return any value, it may
3198 * still fail to promote our pending volume operation to
3199 * a running state. Any caller MUST check the value of *ec,
3200 * and MUST NOT blindly assume success.
3202 * @warning if the caller does not hold a lightweight ref on vp,
3203 * then it MUST NOT reference vp after this function
3204 * returns to the caller.
3206 * @internal volume package internal use only
3209 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
3211 assert(vp->pending_vol_op);
3217 if (V_offlineMessage(vp)[0] == '\0')
3218 strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
3219 V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
3221 vp->goingOffline = 1;
3222 VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
3223 VCreateReservation_r(vp);
3226 /* Wait for the volume to go offline */
3227 while (!VIsOfflineState(V_attachState(vp))) {
3228 /* do not give corrupted volumes to the volserver */
3229 if (vp->salvage.requested && vp->pending_vol_op->com.programType != salvageServer) {
3233 VWaitStateChange_r(vp);
3237 VCancelReservation_r(vp);
3239 #endif /* AFS_DEMAND_ATTACH_FS */
3242 VOffline(Volume * vp, char *message)
3245 VOffline_r(vp, message);
3249 /* This gets used for the most part by utility routines that don't want
3250 * to keep all the volume headers around. Generally, the file server won't
3251 * call this routine, because then the offline message in the volume header
3252 * (or other information) won't be available to clients. For NAMEI, also
3253 * close the file handles. However, the fileserver does call this during
3254 * an attach following a volume operation.
3257 VDetachVolume_r(Error * ec, Volume * vp)
3260 struct DiskPartition64 *tpartp;
3261 int notifyServer = 0;
3262 int useDone = FSYNC_VOL_ON;
3264 *ec = 0; /* always "succeeds" */
3265 if (programType == volumeUtility) {
3266 notifyServer = vp->needsPutBack;
3267 if (V_destroyMe(vp) == DESTROY_ME)
3268 useDone = FSYNC_VOL_DONE;
3269 #ifdef AFS_DEMAND_ATTACH_FS
3270 else if (!V_blessed(vp) || !V_inService(vp))
3271 useDone = FSYNC_VOL_LEAVE_OFF;
3274 tpartp = vp->partition;
3276 DeleteVolumeFromHashTable(vp);
3277 vp->shuttingDown = 1;
3278 #ifdef AFS_DEMAND_ATTACH_FS
3279 DeleteVolumeFromVByPList_r(vp);
3281 VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
3283 if (programType != fileServer)
3285 #endif /* AFS_DEMAND_ATTACH_FS */
3287 /* Will be detached sometime in the future--this is OK since volume is offline */
3289 /* XXX the following code should really be moved to VCheckDetach() since the volume
3290 * is not technically detached until the refcounts reach zero
3292 #ifdef FSSYNC_BUILD_CLIENT
3293 if (programType == volumeUtility && notifyServer) {
3295 * Note: The server is not notified in the case of a bogus volume
3296 * explicitly to make it possible to create a volume, do a partial
3297 * restore, then abort the operation without ever putting the volume
3298 * online. This is essential in the case of a volume move operation
3299 * between two partitions on the same server. In that case, there
3300 * would be two instances of the same volume, one of them bogus,
3301 * which the file server would attempt to put on line
3303 FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
3304 /* XXX this code path is only hit by volume utilities, thus
3305 * V_BreakVolumeCallbacks will always be NULL. if we really
3306 * want to break callbacks in this path we need to use FSYNC_VolOp() */
3308 /* Dettaching it so break all callbacks on it */
3309 if (V_BreakVolumeCallbacks) {
3310 Log("volume %u detached; breaking all call backs\n", volume);
3311 (*V_BreakVolumeCallbacks) (volume);
3315 #endif /* FSSYNC_BUILD_CLIENT */
3319 VDetachVolume(Error * ec, Volume * vp)
3322 VDetachVolume_r(ec, vp);
3327 /***************************************************/
3328 /* Volume fd/inode handle closing routines */
3329 /***************************************************/
3331 /* For VDetachVolume, we close all cached file descriptors, but keep
3332 * the Inode handles in case we need to read from a busy volume.
3334 /* for demand attach, caller MUST hold ref count on vp */
3336 VCloseVolumeHandles_r(Volume * vp)
3338 #ifdef AFS_DEMAND_ATTACH_FS
3339 VolState state_save;
3341 state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
3346 * XXX need to investigate whether we can perform
3347 * DFlushVolume outside of vol_glock_mutex...
3349 * VCloseVnodeFiles_r drops the glock internally */
3350 DFlushVolume(V_id(vp));
3351 VCloseVnodeFiles_r(vp);
3353 #ifdef AFS_DEMAND_ATTACH_FS
3357 /* Too time consuming and unnecessary for the volserver */
3358 if (programType != volumeUtility) {
3359 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
3360 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
3361 IH_CONDSYNC(vp->diskDataHandle);
3363 IH_CONDSYNC(vp->linkHandle);
3364 #endif /* AFS_NT40_ENV */
3367 IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
3368 IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
3369 IH_REALLYCLOSE(vp->diskDataHandle);
3370 IH_REALLYCLOSE(vp->linkHandle);
3372 #ifdef AFS_DEMAND_ATTACH_FS
3374 VChangeState_r(vp, state_save);
3378 /* For both VForceOffline and VOffline, we close all relevant handles.
3379 * For VOffline, if we re-attach the volume, the files may possible be
3380 * different than before.
3382 /* for demand attach, caller MUST hold a ref count on vp */
3384 VReleaseVolumeHandles_r(Volume * vp)
3386 #ifdef AFS_DEMAND_ATTACH_FS
3387 VolState state_save;
3389 state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
3392 /* XXX need to investigate whether we can perform
3393 * DFlushVolume outside of vol_glock_mutex... */
3394 DFlushVolume(V_id(vp));
3396 VReleaseVnodeFiles_r(vp); /* releases the glock internally */
3398 #ifdef AFS_DEMAND_ATTACH_FS
3402 /* Too time consuming and unnecessary for the volserver */
3403 if (programType != volumeUtility) {
3404 IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
3405 IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
3406 IH_CONDSYNC(vp->diskDataHandle);
3408 IH_CONDSYNC(vp->linkHandle);
3409 #endif /* AFS_NT40_ENV */
3412 IH_RELEASE(vp->vnodeIndex[vLarge].handle);
3413 IH_RELEASE(vp->vnodeIndex[vSmall].handle);
3414 IH_RELEASE(vp->diskDataHandle);
3415 IH_RELEASE(vp->linkHandle);
3417 #ifdef AFS_DEMAND_ATTACH_FS
3419 VChangeState_r(vp, state_save);
3424 /***************************************************/
3425 /* Volume write and fsync routines */
3426 /***************************************************/
3429 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
3431 #ifdef AFS_DEMAND_ATTACH_FS
3432 VolState state_save;
3434 if (flags & VOL_UPDATE_WAIT) {
3435 VCreateReservation_r(vp);
3436 VWaitExclusiveState_r(vp);
3441 if (programType == fileServer)
3443 (V_inUse(vp) ? V_nextVnodeUnique(vp) +
3444 200 : V_nextVnodeUnique(vp));
3446 #ifdef AFS_DEMAND_ATTACH_FS
3447 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
3451 WriteVolumeHeader_r(ec, vp);
3453 #ifdef AFS_DEMAND_ATTACH_FS
3455 VChangeState_r(vp, state_save);
3456 if (flags & VOL_UPDATE_WAIT) {
3457 VCancelReservation_r(vp);
3462 Log("VUpdateVolume: error updating volume header, volume %u (%s)\n",
3463 V_id(vp), V_name(vp));
3464 /* try to update on-disk header,
3465 * while preventing infinite recursion */
3466 if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
3467 VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
3473 VUpdateVolume(Error * ec, Volume * vp)
3476 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
3481 VSyncVolume_r(Error * ec, Volume * vp, int flags)
3485 #ifdef AFS_DEMAND_ATTACH_FS
3486 VolState state_save;
3489 if (flags & VOL_SYNC_WAIT) {
3490 VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
3492 VUpdateVolume_r(ec, vp, 0);
3495 #ifdef AFS_DEMAND_ATTACH_FS
3496 state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
3499 fdP = IH_OPEN(V_diskDataHandle(vp));
3500 assert(fdP != NULL);
3501 code = FDH_SYNC(fdP);
3504 #ifdef AFS_DEMAND_ATTACH_FS
3506 VChangeState_r(vp, state_save);
3512 VSyncVolume(Error * ec, Volume * vp)
3515 VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
3520 /***************************************************/
3521 /* Volume dealloaction routines */
3522 /***************************************************/
3524 #ifdef AFS_DEMAND_ATTACH_FS
3526 FreeVolume(Volume * vp)
3528 /* free the heap space, iff it's safe.
3529 * otherwise, pull it out of the hash table, so it
3530 * will get deallocated when all refs to it go away */
3531 if (!VCheckFree(vp)) {
3532 DeleteVolumeFromHashTable(vp);
3533 DeleteVolumeFromVByPList_r(vp);
3535 /* make sure we invalidate the header cache entry */
3536 FreeVolumeHeader(vp);
3539 #endif /* AFS_DEMAND_ATTACH_FS */
3542 ReallyFreeVolume(Volume * vp)
3547 #ifdef AFS_DEMAND_ATTACH_FS
3549 VChangeState_r(vp, VOL_STATE_FREED);
3550 if (vp->pending_vol_op)
3551 free(vp->pending_vol_op);
3552 #endif /* AFS_DEMAND_ATTACH_FS */
3553 for (i = 0; i < nVNODECLASSES; i++)
3554 if (vp->vnodeIndex[i].bitmap)
3555 free(vp->vnodeIndex[i].bitmap);
3556 FreeVolumeHeader(vp);
3557 #ifndef AFS_DEMAND_ATTACH_FS
3558 DeleteVolumeFromHashTable(vp);
3559 #endif /* AFS_DEMAND_ATTACH_FS */
3563 /* check to see if we should shutdown this volume
3564 * returns 1 if volume was freed, 0 otherwise */
3565 #ifdef AFS_DEMAND_ATTACH_FS
3567 VCheckDetach(register Volume * vp)
3572 if (vp->nUsers || vp->nWaiters)
3575 if (vp->shuttingDown) {
3577 if ((programType != fileServer) &&
3578 (V_inUse(vp) == programType) &&
3579 ((V_checkoutMode(vp) == V_VOLUPD) ||
3580 (V_checkoutMode(vp) == V_SECRETLY) ||
3581 ((V_checkoutMode(vp) == V_CLONE) &&
3582 (VolumeWriteable(vp))))) {
3584 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
3586 Log("VCheckDetach: volume header update for volume %u "
3587 "failed with errno %d\n", vp->hashid, errno);
3590 VReleaseVolumeHandles_r(vp);
3592 ReallyFreeVolume(vp);
3593 if (programType == fileServer) {
3594 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3599 #else /* AFS_DEMAND_ATTACH_FS */
3601 VCheckDetach(register Volume * vp)
3609 if (vp->shuttingDown) {
3611 if ((programType != fileServer) &&
3612 (V_inUse(vp) == programType) &&
3613 ((V_checkoutMode(vp) == V_VOLUPD) ||
3614 (V_checkoutMode(vp) == V_SECRETLY) ||
3615 ((V_checkoutMode(vp) == V_CLONE) &&
3616 (VolumeWriteable(vp))))) {
3618 VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
3620 Log("VCheckDetach: volume header update for volume %u failed with errno %d\n",
3624 VReleaseVolumeHandles_r(vp);
3625 ReallyFreeVolume(vp);
3626 if (programType == fileServer) {
3627 #if defined(AFS_PTHREAD_ENV)
3628 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3629 #else /* AFS_PTHREAD_ENV */
3630 LWP_NoYieldSignal(VPutVolume);
3631 #endif /* AFS_PTHREAD_ENV */
3636 #endif /* AFS_DEMAND_ATTACH_FS */
3638 /* check to see if we should offline this volume
3639 * return 1 if volume went offline, 0 otherwise */
3640 #ifdef AFS_DEMAND_ATTACH_FS
3642 VCheckOffline(register Volume * vp)
3646 if (vp->goingOffline && !vp->nUsers) {
3648 assert(programType == fileServer);
3649 assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
3650 (V_attachState(vp) != VOL_STATE_FREED) &&
3651 (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
3652 (V_attachState(vp) != VOL_STATE_UNATTACHED));
3656 * VOL_STATE_GOING_OFFLINE
3657 * VOL_STATE_SHUTTING_DOWN
3658 * VIsErrorState(V_attachState(vp))
3659 * VIsExclusiveState(V_attachState(vp))
3662 VCreateReservation_r(vp);
3663 VChangeState_r(vp, VOL_STATE_OFFLINING);
3666 /* must clear the goingOffline flag before we drop the glock */
3667 vp->goingOffline = 0;
3672 /* perform async operations */
3673 VUpdateVolume_r(&error, vp, 0);
3674 VCloseVolumeHandles_r(vp);
3677 Log("VOffline: Volume %u (%s) is now offline", V_id(vp),
3679 if (V_offlineMessage(vp)[0])
3680 Log(" (%s)", V_offlineMessage(vp));
3684 /* invalidate the volume header cache entry */
3685 FreeVolumeHeader(vp);
3687 /* if nothing changed state to error or salvaging,
3688 * drop state to unattached */
3689 if (!VIsErrorState(V_attachState(vp))) {
3690 VChangeState_r(vp, VOL_STATE_UNATTACHED);
3692 VCancelReservation_r(vp);
3693 /* no usage of vp is safe beyond this point */
3697 #else /* AFS_DEMAND_ATTACH_FS */
3699 VCheckOffline(register Volume * vp)
3701 Volume * rvp = NULL;
3704 if (vp->goingOffline && !vp->nUsers) {
3706 assert(programType == fileServer);
3709 vp->goingOffline = 0;
3711 VUpdateVolume_r(&error, vp, 0);
3712 VCloseVolumeHandles_r(vp);
3714 Log("VOffline: Volume %u (%s) is now offline", V_id(vp),
3716 if (V_offlineMessage(vp)[0])
3717 Log(" (%s)", V_offlineMessage(vp));
3720 FreeVolumeHeader(vp);
3721 #ifdef AFS_PTHREAD_ENV
3722 assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3723 #else /* AFS_PTHREAD_ENV */
3724 LWP_NoYieldSignal(VPutVolume);
3725 #endif /* AFS_PTHREAD_ENV */
3729 #endif /* AFS_DEMAND_ATTACH_FS */
3731 /***************************************************/
3732 /* demand attach fs ref counting routines */
3733 /***************************************************/
3735 #ifdef AFS_DEMAND_ATTACH_FS
3736 /* the following two functions handle reference counting for
3737 * asynchronous operations on volume structs.
3739 * their purpose is to prevent a VDetachVolume or VShutdown
3740 * from free()ing the Volume struct during an async i/o op */
3742 /* register with the async volume op ref counter */
3743 /* VCreateReservation_r moved into inline code header because it
3744 * is now needed in vnode.c -- tkeiser 11/20/2007
3748 * decrement volume-package internal refcount.
3750 * @param vp volume object pointer
3752 * @internal volume package internal use only
3755 * @arg VOL_LOCK is held
3756 * @arg lightweight refcount held
3758 * @post volume waiters refcount is decremented; volume may
3759 * have been deallocated/shutdown/offlined/salvaged/
3760 * whatever during the process
3762 * @warning once you have tossed your last reference (you can acquire
3763 * lightweight refs recursively) it is NOT SAFE to reference
3764 * a volume object pointer ever again
3766 * @see VCreateReservation_r
3768 * @note DEMAND_ATTACH_FS only
3771 VCancelReservation_r(Volume * vp)
3773 assert(--vp->nWaiters >= 0);
3774 if (vp->nWaiters == 0) {
3776 if (!VCheckDetach(vp)) {
3783 /* check to see if we should free this volume now
3784 * return 1 if volume was freed, 0 otherwise */
3786 VCheckFree(Volume * vp)
3789 if ((vp->nUsers == 0) &&
3790 (vp->nWaiters == 0) &&
3791 !(V_attachFlags(vp) & (VOL_IN_HASH |
3795 ReallyFreeVolume(vp);
3800 #endif /* AFS_DEMAND_ATTACH_FS */
3803 /***************************************************/
3804 /* online volume operations routines */
3805 /***************************************************/
3807 #ifdef AFS_DEMAND_ATTACH_FS
3809 * register a volume operation on a given volume.
3811 * @param[in] vp volume object
3812 * @param[in] vopinfo volume operation info object
3814 * @pre VOL_LOCK is held
3816 * @post volume operation info object attached to volume object.
3817 * volume operation statistics updated.
3819 * @note by "attached" we mean a copy of the passed in object is made
3821 * @internal volume package internal use only
3824 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3826 FSSYNC_VolOp_info * info;
3828 /* attach a vol op info node to the volume struct */
3829 info = (FSSYNC_VolOp_info *) malloc(sizeof(FSSYNC_VolOp_info));
3830 assert(info != NULL);
3831 memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
3832 vp->pending_vol_op = info;
3835 vp->stats.last_vol_op = FT_ApproxTime();
3836 vp->stats.vol_ops++;
3837 IncUInt64(&VStats.vol_ops);
3843 * deregister the volume operation attached to this volume.
3845 * @param[in] vp volume object pointer
3847 * @pre VOL_LOCK is held
3849 * @post the volume operation info object is detached from the volume object
3851 * @internal volume package internal use only
3854 VDeregisterVolOp_r(Volume * vp)
3856 if (vp->pending_vol_op) {
3857 free(vp->pending_vol_op);
3858 vp->pending_vol_op = NULL;
3862 #endif /* AFS_DEMAND_ATTACH_FS */
3865 * determine whether it is safe to leave a volume online during
3866 * the volume operation described by the vopinfo object.
3868 * @param[in] vp volume object
3869 * @param[in] vopinfo volume operation info object
3871 * @return whether it is safe to leave volume online
3872 * @retval 0 it is NOT SAFE to leave the volume online
3873 * @retval 1 it is safe to leave the volume online during the operation
3876 * @arg VOL_LOCK is held
3877 * @arg disk header attached to vp (heavyweight ref on vp will guarantee
3878 * this condition is met)
3880 * @internal volume package internal use only
3883 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3885 return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
3886 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
3887 (vopinfo->com.reason == V_READONLY ||
3888 (!VolumeWriteable(vp) &&
3889 (vopinfo->com.reason == V_CLONE ||
3890 vopinfo->com.reason == V_DUMP)))));
3894 * determine whether VBUSY should be set during this volume operation.
3896 * @param[in] vp volume object
3897 * @param[in] vopinfo volume operation info object
3899 * @return whether VBUSY should be set
3900 * @retval 0 VBUSY does NOT need to be set
3901 * @retval 1 VBUSY SHOULD be set
3903 * @pre VOL_LOCK is held
3905 * @internal volume package internal use only
3908 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3910 return ((vopinfo->com.command == FSYNC_VOL_OFF &&
3911 vopinfo->com.reason == FSYNC_SALVAGE) ||
3912 (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
3913 (vopinfo->com.reason == V_CLONE ||
3914 vopinfo->com.reason == V_DUMP)));
3918 /***************************************************/
3919 /* online salvager routines */
3920 /***************************************************/
3921 #if defined(AFS_DEMAND_ATTACH_FS)
3922 #define SALVAGE_PRIO_UPDATE_INTERVAL 3 /**< number of seconds between prio updates */
3923 #define SALVAGE_COUNT_MAX 16 /**< number of online salvages we
3924 * allow before moving the volume
3925 * into a permanent error state
3927 * once this threshold is reached,
3928 * the operator will have to manually
3929 * issue a 'bos salvage' to bring
3930 * the volume back online
3934 * check whether a salvage needs to be performed on this volume.
3936 * @param[in] vp pointer to volume object
3938 * @return status code
3939 * @retval 0 no salvage scheduled
3940 * @retval 1 a salvage has been scheduled with the salvageserver
3942 * @pre VOL_LOCK is held
3944 * @post if salvage request flag is set and nUsers and nWaiters are zero,
3945 * then a salvage will be requested
3947 * @note this is one of the event handlers called by VCancelReservation_r
3949 * @see VCancelReservation_r
3951 * @internal volume package internal use only.
3954 VCheckSalvage(register Volume * vp)
3957 #ifdef SALVSYNC_BUILD_CLIENT
3958 if (vp->nUsers || vp->nWaiters)
3960 if (vp->salvage.requested) {
3961 VScheduleSalvage_r(vp);
3964 #endif /* SALVSYNC_BUILD_CLIENT */
3969 * request volume salvage.
3971 * @param[out] ec computed client error code
3972 * @param[in] vp volume object pointer
3973 * @param[in] reason reason code (passed to salvageserver via SALVSYNC)
3974 * @param[in] flags see flags note below
3977 * VOL_SALVAGE_INVALIDATE_HEADER causes volume header cache entry
3978 * to be invalidated.
3980 * @pre VOL_LOCK is held.
3982 * @post volume state is changed.
3983 * for fileserver, salvage will be requested once refcount reaches zero.
3985 * @return operation status code
3986 * @retval 0 volume salvage will occur
3987 * @retval 1 volume salvage could not be scheduled
3989 * @note DAFS fileserver only
3991 * @note this call does not synchronously schedule a volume salvage. rather,
3992 * it sets volume state so that when volume refcounts reach zero, a
3993 * volume salvage will occur. by "refcounts", we mean both nUsers and
3994 * nWaiters must be zero.
3996 * @internal volume package internal use only.
3999 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
4003 * for DAFS volume utilities, transition to error state
4004 * (at some point in the future, we should consider
4005 * making volser talk to salsrv)
4007 if (programType != fileServer) {
4008 VChangeState_r(vp, VOL_STATE_ERROR);
4013 if (!vp->salvage.requested) {
4014 vp->salvage.requested = 1;
4015 vp->salvage.reason = reason;
4016 vp->stats.last_salvage = FT_ApproxTime();
4017 if (flags & VOL_SALVAGE_INVALIDATE_HEADER) {
4018 /* Instead of ReleaseVolumeHeader, we do FreeVolumeHeader()
4019 so that the the next VAttachVolumeByVp_r() invocation
4020 of attach2() will pull in a cached header
4021 entry and fail, then load a fresh one from disk and attach
4024 FreeVolumeHeader(vp);
4026 if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
4027 VChangeState_r(vp, VOL_STATE_SALVAGING);
4030 Log("VRequestSalvage: volume %u online salvaged too many times; forced offline.\n", vp->hashid);
4031 VChangeState_r(vp, VOL_STATE_ERROR);
4040 * update salvageserver scheduling priority for a volume.
4042 * @param[in] vp pointer to volume object
4044 * @return operation status
4046 * @retval 1 request denied, or SALVSYNC communications failure
4048 * @pre VOL_LOCK is held.
4050 * @post in-core salvage priority counter is incremented. if at least
4051 * SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
4052 * last SALVSYNC_RAISEPRIO request, we contact the salvageserver
4053 * to update its priority queue. if no salvage is scheduled,
4054 * this function is a no-op.
4056 * @note DAFS fileserver only
4058 * @note this should be called whenever a VGetVolume fails due to a
4059 * pending salvage request
4061 * @todo should set exclusive state and drop glock around salvsync call
4063 * @internal volume package internal use only.
4066 VUpdateSalvagePriority_r(Volume * vp)
4071 #ifdef SALVSYNC_BUILD_CLIENT
4073 now = FT_ApproxTime();
4075 /* update the salvageserver priority queue occasionally so that
4076 * frequently requested volumes get moved to the head of the queue
4078 if ((vp->salvage.scheduled) &&
4079 (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
4080 code = SALVSYNC_SalvageVolume(vp->hashid,
4081 VPartitionPath(vp->partition),
4086 vp->stats.last_salvage_req = now;
4087 if (code != SYNC_OK) {
4091 #endif /* SALVSYNC_BUILD_CLIENT */
4097 * schedule a salvage with the salvage server.
4099 * @param[in] vp pointer to volume object
4101 * @return operation status
4102 * @retval 0 salvage scheduled successfully
4103 * @retval 1 salvage not scheduled, or SALVSYNC com error
4106 * @arg VOL_LOCK is held.
4107 * @arg nUsers and nWaiters should be zero.
4109 * @post salvageserver is sent a salvage request
4111 * @note DAFS fileserver only
4113 * @internal volume package internal use only.
4116 VScheduleSalvage_r(Volume * vp)
4119 #ifdef SALVSYNC_BUILD_CLIENT
4120 VolState state_save;
4121 VThreadOptions_t * thread_opts;
4124 if (vp->nWaiters || vp->nUsers) {
4128 /* prevent endless salvage,attach,salvage,attach,... loops */
4129 if (vp->stats.salvages >= SALVAGE_COUNT_MAX)
4133 * don't perform salvsync ops on certain threads
4135 thread_opts = pthread_getspecific(VThread_key);
4136 if (thread_opts == NULL) {
4137 thread_opts = &VThread_defaults;
4139 if (thread_opts->disallow_salvsync) {
4144 * XXX the scheduling process should really be done asynchronously
4145 * to avoid fssync deadlocks
4147 if (!vp->salvage.scheduled) {
4148 /* if we haven't previously scheduled a salvage, do so now
4150 * set the volume to an exclusive state and drop the lock
4151 * around the SALVSYNC call
4153 * note that we do NOT acquire a reservation here -- doing so
4154 * could result in unbounded recursion
4156 strlcpy(partName, VPartitionPath(vp->partition), sizeof(partName));
4157 state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
4160 /* can't use V_id() since there's no guarantee
4161 * we have the disk data header at this point */
4162 code = SALVSYNC_SalvageVolume(vp->hashid,
4169 VChangeState_r(vp, state_save);
4171 if (code == SYNC_OK) {
4172 vp->salvage.scheduled = 1;
4173 vp->stats.salvages++;
4174 vp->stats.last_salvage_req = FT_ApproxTime();
4175 IncUInt64(&VStats.salvages);
4179 case SYNC_BAD_COMMAND:
4180 case SYNC_COM_ERROR:
4183 Log("VScheduleSalvage_r: SALVSYNC request denied\n");
4186 Log("VScheduleSalvage_r: SALVSYNC unknown protocol error\n");
4191 #endif /* SALVSYNC_BUILD_CLIENT */
4196 * ask salvageserver to cancel a scheduled salvage operation.
4198 * @param[in] vp pointer to volume object
4199 * @param[in] reason SALVSYNC protocol reason code
4201 * @return operation status
4203 * @retval 1 request failed
4205 * @pre VOL_LOCK is held.
4207 * @post salvageserver is sent a request to cancel the volume salvage.
4208 * volume is transitioned to a hard error state.
4210 * @internal volume package internal use only.
4213 VCancelSalvage_r(Volume * vp, int reason)
4217 #ifdef SALVSYNC_BUILD_CLIENT
4218 if (vp->salvage.scheduled) {
4219 VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
4222 /* can't use V_id() since there's no guarantee
4223 * we have the disk data header at this point */
4224 code = SALVSYNC_SalvageVolume(vp->hashid,
4225 VPartitionPath(vp->partition),
4232 VChangeState_r(vp, VOL_STATE_ERROR);
4234 if (code == SYNC_OK) {
4235 vp->salvage.scheduled = 0;
4236 vp->salvage.requested = 0;
4241 #endif /* SALVSYNC_BUILD_CLIENT */
4246 #ifdef SALVSYNC_BUILD_CLIENT
4248 * connect to the salvageserver SYNC service.
4250 * @return operation status
4254 * @post connection to salvageserver SYNC service established
4256 * @see VConnectSALV_r
4257 * @see VDisconnectSALV
4258 * @see VReconnectSALV
4265 retVal = VConnectSALV_r();
4271 * connect to the salvageserver SYNC service.
4273 * @return operation status
4277 * @pre VOL_LOCK is held.
4279 * @post connection to salvageserver SYNC service established
4282 * @see VDisconnectSALV_r
4283 * @see VReconnectSALV_r
4284 * @see SALVSYNC_clientInit
4286 * @internal volume package internal use only.
4289 VConnectSALV_r(void)
4291 return SALVSYNC_clientInit();
4295 * disconnect from the salvageserver SYNC service.
4297 * @return operation status
4300 * @pre client should have a live connection to the salvageserver
4302 * @post connection to salvageserver SYNC service destroyed
4304 * @see VDisconnectSALV_r
4306 * @see VReconnectSALV
4309 VDisconnectSALV(void)
4313 VDisconnectSALV_r();
4319 * disconnect from the salvageserver SYNC service.
4321 * @return operation status
4325 * @arg VOL_LOCK is held.
4326 * @arg client should have a live connection to the salvageserver.
4328 * @post connection to salvageserver SYNC service destroyed
4330 * @see VDisconnectSALV
4331 * @see VConnectSALV_r
4332 * @see VReconnectSALV_r
4333 * @see SALVSYNC_clientFinis
4335 * @internal volume package internal use only.
4338 VDisconnectSALV_r(void)
4340 return SALVSYNC_clientFinis();
4344 * disconnect and then re-connect to the salvageserver SYNC service.
4346 * @return operation status
4350 * @pre client should have a live connection to the salvageserver
4352 * @post old connection is dropped, and a new one is established
4355 * @see VDisconnectSALV
4356 * @see VReconnectSALV_r
4359 VReconnectSALV(void)
4363 retVal = VReconnectSALV_r();
4369 * disconnect and then re-connect to the salvageserver SYNC service.
4371 * @return operation status
4376 * @arg VOL_LOCK is held.
4377 * @arg client should have a live connection to the salvageserver.
4379 * @post old connection is dropped, and a new one is established
4381 * @see VConnectSALV_r
4382 * @see VDisconnectSALV
4383 * @see VReconnectSALV
4384 * @see SALVSYNC_clientReconnect
4386 * @internal volume package internal use only.
4389 VReconnectSALV_r(void)
4391 return SALVSYNC_clientReconnect();
4393 #endif /* SALVSYNC_BUILD_CLIENT */
4394 #endif /* AFS_DEMAND_ATTACH_FS */
4397 /***************************************************/
4398 /* FSSYNC routines */
4399 /***************************************************/
4401 /* This must be called by any volume utility which needs to run while the
4402 file server is also running. This is separated from VInitVolumePackage so
4403 that a utility can fork--and each of the children can independently
4404 initialize communication with the file server */
4405 #ifdef FSSYNC_BUILD_CLIENT
4407 * connect to the fileserver SYNC service.
4409 * @return operation status
4414 * @arg VInit must equal 2.
4415 * @arg Program Type must not be fileserver or salvager.
4417 * @post connection to fileserver SYNC service established
4420 * @see VDisconnectFS
4421 * @see VChildProcReconnectFS
4428 retVal = VConnectFS_r();
4434 * connect to the fileserver SYNC service.
4436 * @return operation status
4441 * @arg VInit must equal 2.
4442 * @arg Program Type must not be fileserver or salvager.
4443 * @arg VOL_LOCK is held.
4445 * @post connection to fileserver SYNC service established
4448 * @see VDisconnectFS_r
4449 * @see VChildProcReconnectFS_r
4451 * @internal volume package internal use only.
4457 assert((VInit == 2) &&
4458 (programType != fileServer) &&
4459 (programType != salvager));
4460 rc = FSYNC_clientInit();
4467 * disconnect from the fileserver SYNC service.
4470 * @arg client should have a live connection to the fileserver.
4471 * @arg VOL_LOCK is held.
4472 * @arg Program Type must not be fileserver or salvager.
4474 * @post connection to fileserver SYNC service destroyed
4476 * @see VDisconnectFS
4478 * @see VChildProcReconnectFS_r
4480 * @internal volume package internal use only.
4483 VDisconnectFS_r(void)
4485 assert((programType != fileServer) &&
4486 (programType != salvager));
4487 FSYNC_clientFinis();
4492 * disconnect from the fileserver SYNC service.
4495 * @arg client should have a live connection to the fileserver.
4496 * @arg Program Type must not be fileserver or salvager.
4498 * @post connection to fileserver SYNC service destroyed
4500 * @see VDisconnectFS_r
4502 * @see VChildProcReconnectFS
4513 * connect to the fileserver SYNC service from a child process following a fork.
4515 * @return operation status
4520 * @arg VOL_LOCK is held.
4521 * @arg current FSYNC handle is shared with a parent process
4523 * @post current FSYNC handle is discarded and a new connection to the
4524 * fileserver SYNC service is established
4526 * @see VChildProcReconnectFS
4528 * @see VDisconnectFS_r
4530 * @internal volume package internal use only.
4533 VChildProcReconnectFS_r(void)
4535 return FSYNC_clientChildProcReconnect();
4539 * connect to the fileserver SYNC service from a child process following a fork.
4541 * @return operation status
4545 * @pre current FSYNC handle is shared with a parent process
4547 * @post current FSYNC handle is discarded and a new connection to the
4548 * fileserver SYNC service is established
4550 * @see VChildProcReconnectFS_r
4552 * @see VDisconnectFS
4555 VChildProcReconnectFS(void)
4559 ret = VChildProcReconnectFS_r();
4563 #endif /* FSSYNC_BUILD_CLIENT */
4566 /***************************************************/
4567 /* volume bitmap routines */
4568 /***************************************************/
4571 * For demand attach fs, flags parameter controls
4572 * locking behavior. If (flags & VOL_ALLOC_BITMAP_WAIT)
4573 * is set, then this function will create a reservation
4574 * and block on any other exclusive operations. Otherwise,
4575 * this function assumes the caller already has exclusive
4576 * access to vp, and we just change the volume state.
4579 VAllocBitmapEntry_r(Error * ec, Volume * vp,
4580 struct vnodeIndex *index, int flags)
4583 register byte *bp, *ep;
4584 #ifdef AFS_DEMAND_ATTACH_FS
4585 VolState state_save;
4586 #endif /* AFS_DEMAND_ATTACH_FS */
4590 /* This test is probably redundant */
4591 if (!VolumeWriteable(vp)) {
4592 *ec = (bit32) VREADONLY;
4596 #ifdef AFS_DEMAND_ATTACH_FS
4597 if (flags & VOL_ALLOC_BITMAP_WAIT) {
4598 VCreateReservation_r(vp);
4599 VWaitExclusiveState_r(vp);
4601 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
4602 #endif /* AFS_DEMAND_ATTACH_FS */
4605 if ((programType == fileServer) && !index->bitmap) {
4607 #ifndef AFS_DEMAND_ATTACH_FS
4608 /* demand attach fs uses the volume state to avoid races.
4609 * specialStatus field is not used at all */
4611 if (vp->specialStatus == VBUSY) {
4612 if (vp->goingOffline) { /* vos dump waiting for the volume to
4613 * go offline. We probably come here
4614 * from AddNewReadableResidency */
4617 while (vp->specialStatus == VBUSY) {
4618 #ifdef AFS_PTHREAD_ENV
4622 #else /* !AFS_PTHREAD_ENV */
4624 #endif /* !AFS_PTHREAD_ENV */
4628 #endif /* !AFS_DEMAND_ATTACH_FS */
4630 if (!index->bitmap) {
4631 #ifndef AFS_DEMAND_ATTACH_FS
4632 vp->specialStatus = VBUSY; /* Stop anyone else from using it. */
4633 #endif /* AFS_DEMAND_ATTACH_FS */
4634 for (i = 0; i < nVNODECLASSES; i++) {
4635 VGetBitmap_r(ec, vp, i);
4637 #ifdef AFS_DEMAND_ATTACH_FS
4638 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
4639 #else /* AFS_DEMAND_ATTACH_FS */
4640 DeleteVolumeFromHashTable(vp);
4641 vp->shuttingDown = 1; /* Let who has it free it. */
4642 vp->specialStatus = 0;
4643 #endif /* AFS_DEMAND_ATTACH_FS */
4648 #ifndef AFS_DEMAND_ATTACH_FS
4650 vp->specialStatus = 0; /* Allow others to have access. */
4651 #endif /* AFS_DEMAND_ATTACH_FS */
4654 #endif /* BITMAP_LATER */
4656 #ifdef AFS_DEMAND_ATTACH_FS
4658 #endif /* AFS_DEMAND_ATTACH_FS */
4659 bp = index->bitmap + index->bitmapOffset;
4660 ep = index->bitmap + index->bitmapSize;
4662 if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
4664 index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
4667 o = ffs(~*bp) - 1; /* ffs is documented in BSTRING(3) */
4669 ret = (VnodeId) ((bp - index->bitmap) * 8 + o);
4670 #ifdef AFS_DEMAND_ATTACH_FS
4672 #endif /* AFS_DEMAND_ATTACH_FS */
4675 bp += sizeof(bit32) /* i.e. 4 */ ;
4677 /* No bit map entry--must grow bitmap */
4679 realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
4682 bp += index->bitmapSize;
4683 memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
4684 index->bitmapOffset = index->bitmapSize;
4685 index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
4687 ret = index->bitmapOffset * 8;
4688 #ifdef AFS_DEMAND_ATTACH_FS
4690 #endif /* AFS_DEMAND_ATTACH_FS */
4693 #ifdef AFS_DEMAND_ATTACH_FS
4694 VChangeState_r(vp, state_save);
4695 if (flags & VOL_ALLOC_BITMAP_WAIT) {
4696 VCancelReservation_r(vp);
4698 #endif /* AFS_DEMAND_ATTACH_FS */
4703 VAllocBitmapEntry(Error * ec, Volume * vp, register struct vnodeIndex * index)
4707 retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
4713 VFreeBitMapEntry_r(Error * ec, register struct vnodeIndex *index,
4716 unsigned int offset;
4722 #endif /* BITMAP_LATER */
4723 offset = bitNumber >> 3;
4724 if (offset >= index->bitmapSize) {
4728 if (offset < index->bitmapOffset)
4729 index->bitmapOffset = offset & ~3; /* Truncate to nearest bit32 */
4730 *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
4734 VFreeBitMapEntry(Error * ec, register struct vnodeIndex *index,
4738 VFreeBitMapEntry_r(ec, index, bitNumber);
4742 /* this function will drop the glock internally.
4743 * for old pthread fileservers, this is safe thanks to vbusy.
4745 * for demand attach fs, caller must have already called
4746 * VCreateReservation_r and VWaitExclusiveState_r */
4748 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
4750 StreamHandle_t *file;
4753 struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
4754 struct vnodeIndex *vip = &vp->vnodeIndex[class];
4755 struct VnodeDiskObject *vnode;
4756 unsigned int unique = 0;
4760 #endif /* BITMAP_LATER */
4761 #ifdef AFS_DEMAND_ATTACH_FS
4762 VolState state_save;
4763 #endif /* AFS_DEMAND_ATTACH_FS */
4767 #ifdef AFS_DEMAND_ATTACH_FS
4768 state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
4769 #endif /* AFS_DEMAND_ATTACH_FS */
4772 fdP = IH_OPEN(vip->handle);
4773 assert(fdP != NULL);
4774 file = FDH_FDOPEN(fdP, "r");
4775 assert(file != NULL);
4776 vnode = (VnodeDiskObject *) malloc(vcp->diskSize);
4777 assert(vnode != NULL);
4778 size = OS_SIZE(fdP->fd_fd);
4780 nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
4782 vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4; /* The 10 is a little extra so
4783 * a few files can be created in this volume,
4784 * the whole thing is rounded up to nearest 4
4785 * bytes, because the bit map allocator likes
4788 BitMap = (byte *) calloc(1, vip->bitmapSize);
4789 assert(BitMap != NULL);
4790 #else /* BITMAP_LATER */
4791 vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
4792 assert(vip->bitmap != NULL);
4793 vip->bitmapOffset = 0;
4794 #endif /* BITMAP_LATER */
4795 if (STREAM_SEEK(file, vcp->diskSize, 0) != -1) {
4797 for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
4798 if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
4800 if (vnode->type != vNull) {
4801 if (vnode->vnodeMagic != vcp->magic) {
4802 Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
4807 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
4808 #else /* BITMAP_LATER */
4809 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
4810 #endif /* BITMAP_LATER */
4811 if (unique <= vnode->uniquifier)
4812 unique = vnode->uniquifier + 1;
4814 #ifndef AFS_PTHREAD_ENV
4815 if ((bitNumber & 0x00ff) == 0x0ff) { /* every 256 iterations */
4818 #endif /* !AFS_PTHREAD_ENV */
4821 if (vp->nextVnodeUnique < unique) {
4822 Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
4825 /* Paranoia, partly justified--I think fclose after fdopen
4826 * doesn't seem to close fd. In any event, the documentation
4827 * doesn't specify, so it's safer to close it twice.
4835 /* There may have been a racing condition with some other thread, both
4836 * creating the bitmaps for this volume. If the other thread was faster
4837 * the pointer to bitmap should already be filled and we can free ours.
4839 if (vip->bitmap == NULL) {
4840 vip->bitmap = BitMap;
4841 vip->bitmapOffset = 0;
4843 free((byte *) BitMap);
4844 #endif /* BITMAP_LATER */
4845 #ifdef AFS_DEMAND_ATTACH_FS
4846 VChangeState_r(vp, state_save);
4847 #endif /* AFS_DEMAND_ATTACH_FS */
4851 /***************************************************/
4852 /* Volume Path and Volume Number utility routines */
4853 /***************************************************/
4856 * find the first occurrence of a volume header file and return the path.
4858 * @param[out] ec outbound error code
4859 * @param[in] volumeId volume id to find
4860 * @param[out] partitionp pointer to disk partition path string
4861 * @param[out] namep pointer to volume header file name string
4863 * @post path to first occurrence of volume header is returned in partitionp
4864 * and namep, or ec is set accordingly.
4866 * @warning this function is NOT re-entrant -- partitionp and namep point to
4867 * static data segments
4869 * @note if a volume utility inadvertently leaves behind a stale volume header
4870 * on a vice partition, it is possible for callers to get the wrong one,
4871 * depending on the order of the disk partition linked list.
4875 VGetVolumePath(Error * ec, VolId volumeId, char **partitionp, char **namep)
4877 static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
4878 char path[VMAXPATHLEN];
4880 struct DiskPartition64 *dp;
4884 (void)afs_snprintf(&name[1], (sizeof name) - 1, VFORMAT, afs_cast_uint32(volumeId));
4885 for (dp = DiskPartitionList; dp; dp = dp->next) {
4886 struct afs_stat status;
4887 strcpy(path, VPartitionPath(dp));
4889 if (afs_stat(path, &status) == 0) {
4890 strcpy(partition, dp->name);
4897 *partitionp = *namep = NULL;
4899 *partitionp = partition;
4905 * extract a volume number from a volume header filename string.
4907 * @param[in] name volume header filename string
4909 * @return volume number
4911 * @note the string must be of the form VFORMAT. the only permissible
4912 * deviation is a leading '/' character.
4917 VolumeNumber(char *name)
4921 return atoi(name + 1);
4925 * compute the volume header filename.
4927 * @param[in] volumeId
4929 * @return volume header filename
4931 * @post volume header filename string is constructed
4933 * @warning this function is NOT re-entrant -- the returned string is
4934 * stored in a static char array. see VolumeExternalName_r
4935 * for a re-entrant equivalent.
4937 * @see VolumeExternalName_r
4939 * @deprecated due to the above re-entrancy warning, this interface should
4940 * be considered deprecated. Please use VolumeExternalName_r
4944 VolumeExternalName(VolumeId volumeId)
4946 static char name[VMAXPATHLEN];
4947 (void)afs_snprintf(name, sizeof name, VFORMAT, afs_cast_uint32(volumeId));
4952 * compute the volume header filename.
4954 * @param[in] volumeId
4955 * @param[inout] name array in which to store filename
4956 * @param[in] len length of name array
4958 * @return result code from afs_snprintf
4960 * @see VolumeExternalName
4963 * @note re-entrant equivalent of VolumeExternalName
4965 * @internal volume package internal use only.
4967 #ifdef AFS_DEMAND_ATTACH_FS
4969 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
4971 return afs_snprintf(name, len, VFORMAT, afs_cast_uint32(volumeId));
4976 /***************************************************/
4977 /* Volume Usage Statistics routines */
4978 /***************************************************/
4980 #if OPENAFS_VOL_STATS
4981 #define OneDay (86400) /* 24 hours' worth of seconds */
4983 #define OneDay (24*60*60) /* 24 hours */
4984 #endif /* OPENAFS_VOL_STATS */
4986 #define Midnight(date) ((date-TimeZoneCorrection)/OneDay*OneDay+TimeZoneCorrection)
4988 /*------------------------------------------------------------------------
4989 * [export] VAdjustVolumeStatistics
4992 * If we've passed midnight, we need to update all the day use
4993 * statistics as well as zeroing the detailed volume statistics
4994 * (if we are implementing them).
4997 * vp : Pointer to the volume structure describing the lucky
4998 * volume being considered for update.
5004 * Nothing interesting.
5008 *------------------------------------------------------------------------*/
5011 VAdjustVolumeStatistics_r(register Volume * vp)
5013 unsigned int now = FT_ApproxTime();
5015 if (now - V_dayUseDate(vp) > OneDay) {
5016 register int ndays, i;
5018 ndays = (now - V_dayUseDate(vp)) / OneDay;
5019 for (i = 6; i > ndays - 1; i--)
5020 V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
5021 for (i = 0; i < ndays - 1 && i < 7; i++)
5022 V_weekUse(vp)[i] = 0;
5024 V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
5026 V_dayUseDate(vp) = Midnight(now);
5028 #if OPENAFS_VOL_STATS
5030 * All we need to do is bzero the entire VOL_STATS_BYTES of
5031 * the detailed volume statistics area.
5033 memset((char *)(V_stat_area(vp)), 0, VOL_STATS_BYTES);
5034 #endif /* OPENAFS_VOL_STATS */
5037 /*It's been more than a day of collection */
5039 * Always return happily.
5042 } /*VAdjustVolumeStatistics */
5045 VAdjustVolumeStatistics(register Volume * vp)
5049 retVal = VAdjustVolumeStatistics_r(vp);
5055 VBumpVolumeUsage_r(register Volume * vp)
5057 unsigned int now = FT_ApproxTime();
5058 if (now - V_dayUseDate(vp) > OneDay)
5059 VAdjustVolumeStatistics_r(vp);
5061 * Save the volume header image to disk after every 128 bumps to dayUse.
5063 if ((V_dayUse(vp)++ & 127) == 0) {
5065 VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
5070 VBumpVolumeUsage(register Volume * vp)
5073 VBumpVolumeUsage_r(vp);
5078 VSetDiskUsage_r(void)
5080 #ifndef AFS_DEMAND_ATTACH_FS
5081 static int FifteenMinuteCounter = 0;
5085 /* NOTE: Don't attempt to access the partitions list until the
5086 * initialization level indicates that all volumes are attached,
5087 * which implies that all partitions are initialized. */
5088 #ifdef AFS_PTHREAD_ENV
5090 #else /* AFS_PTHREAD_ENV */
5092 #endif /* AFS_PTHREAD_ENV */
5095 VResetDiskUsage_r();
5097 #ifndef AFS_DEMAND_ATTACH_FS
5098 if (++FifteenMinuteCounter == 3) {
5099 FifteenMinuteCounter = 0;
5102 #endif /* !AFS_DEMAND_ATTACH_FS */
5114 /***************************************************/
5115 /* Volume Update List routines */
5116 /***************************************************/
5118 /* The number of minutes that a volume hasn't been updated before the
5119 * "Dont salvage" flag in the volume header will be turned on */
5120 #define SALVAGE_INTERVAL (10*60)
5125 * volume update list functionality has been moved into the VLRU
5126 * the DONT_SALVAGE flag is now set during VLRU demotion
5129 #ifndef AFS_DEMAND_ATTACH_FS
5130 static VolumeId *UpdateList = NULL; /* Pointer to array of Volume ID's */
5131 static int nUpdatedVolumes = 0; /* Updated with entry in UpdateList, salvage after crash flag on */
5132 static int updateSize = 0; /* number of entries possible */
5133 #define UPDATE_LIST_SIZE 128 /* initial size increment (must be a power of 2!) */
5134 #endif /* !AFS_DEMAND_ATTACH_FS */
5137 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
5140 vp->updateTime = FT_ApproxTime();
5141 if (V_dontSalvage(vp) == 0)
5143 V_dontSalvage(vp) = 0;
5144 VSyncVolume_r(ec, vp, 0);
5145 #ifdef AFS_DEMAND_ATTACH_FS
5146 V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
5147 #else /* !AFS_DEMAND_ATTACH_FS */
5150 if (UpdateList == NULL) {
5151 updateSize = UPDATE_LIST_SIZE;
5152 UpdateList = (VolumeId *) malloc(sizeof(VolumeId) * updateSize);
5154 if (nUpdatedVolumes == updateSize) {
5156 if (updateSize > 524288) {
5157 Log("warning: there is likely a bug in the volume update scanner\n");
5161 (VolumeId *) realloc(UpdateList,
5162 sizeof(VolumeId) * updateSize);
5165 assert(UpdateList != NULL);
5166 UpdateList[nUpdatedVolumes++] = V_id(vp);
5167 #endif /* !AFS_DEMAND_ATTACH_FS */
5170 #ifndef AFS_DEMAND_ATTACH_FS
5172 VScanUpdateList(void)
5174 register int i, gap;
5175 register Volume *vp;
5177 afs_uint32 now = FT_ApproxTime();
5178 /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
5179 for (i = gap = 0; i < nUpdatedVolumes; i++) {
5181 UpdateList[i - gap] = UpdateList[i];
5183 /* XXX this routine needlessly messes up the Volume LRU by
5184 * breaking the LRU temporal-locality assumptions.....
5185 * we should use a special volume header allocator here */
5186 vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
5189 } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
5190 V_dontSalvage(vp) = DONT_SALVAGE;
5191 VUpdateVolume_r(&error, vp, 0); /* No need to fsync--not critical */
5199 #ifndef AFS_PTHREAD_ENV
5201 #endif /* !AFS_PTHREAD_ENV */
5203 nUpdatedVolumes -= gap;
5205 #endif /* !AFS_DEMAND_ATTACH_FS */
5208 /***************************************************/
5209 /* Volume LRU routines */
5210 /***************************************************/
5215 * with demand attach fs, we attempt to soft detach(1)
5216 * volumes which have not been accessed in a long time
5217 * in order to speed up fileserver shutdown
5219 * (1) by soft detach we mean a process very similar
5220 * to VOffline, except the final state of the
5221 * Volume will be VOL_STATE_PREATTACHED, instead
5222 * of the usual VOL_STATE_UNATTACHED
5224 #ifdef AFS_DEMAND_ATTACH_FS
5226 /* implementation is reminiscent of a generational GC
5228 * queue 0 is newly attached volumes. this queue is
5229 * sorted by attach timestamp
5231 * queue 1 is volumes that have been around a bit
5232 * longer than queue 0. this queue is sorted by
5235 * queue 2 is volumes tha have been around the longest.
5236 * this queue is unsorted
5238 * queue 3 is volumes that have been marked as
5239 * candidates for soft detachment. this queue is
5242 #define VLRU_GENERATIONS 3 /**< number of generations in VLRU */
5243 #define VLRU_QUEUES 5 /**< total number of VLRU queues */
5246 * definition of a VLRU queue.
5249 volatile struct rx_queue q;
5256 * main VLRU data structure.
5259 struct VLRU_q q[VLRU_QUEUES]; /**< VLRU queues */
5262 /** time interval (in seconds) between promotion passes for
5263 * each young generation queue. */
5264 afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
5266 /** time interval (in seconds) between soft detach candidate
5267 * scans for each generation queue.
5269 * scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
5270 * we perform a soft detach pass. */
5271 afs_uint32 scan_interval[VLRU_GENERATIONS+1];
5273 /* scheduler state */
5274 int next_idx; /**< next queue to receive attention */
5275 afs_uint32 last_promotion[VLRU_GENERATIONS-1]; /**< timestamp of last promotion scan */
5276 afs_uint32 last_scan[VLRU_GENERATIONS+1]; /**< timestamp of last detach scan */
5278 int scanner_state; /**< state of scanner thread */
5279 pthread_cond_t cv; /**< state transition CV */
5282 /** global VLRU state */
5283 static struct VLRU volume_LRU;
5286 * defined states for VLRU scanner thread.
5289 VLRU_SCANNER_STATE_OFFLINE = 0, /**< vlru scanner thread is offline */
5290 VLRU_SCANNER_STATE_ONLINE = 1, /**< vlru scanner thread is online */
5291 VLRU_SCANNER_STATE_SHUTTING_DOWN = 2, /**< vlru scanner thread is shutting down */
5292 VLRU_SCANNER_STATE_PAUSING = 3, /**< vlru scanner thread is getting ready to pause */
5293 VLRU_SCANNER_STATE_PAUSED = 4 /**< vlru scanner thread is paused */
5294 } vlru_thread_state_t;
5296 /* vlru disk data header stuff */
5297 #define VLRU_DISK_MAGIC 0x7a8b9cad /**< vlru disk entry magic number */
5298 #define VLRU_DISK_VERSION 1 /**< vlru disk entry version number */
5300 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
5301 #define VLRU_DUMP_EXPIRATION_TIME (60*60*24*7) /* expire vlru data after 1 week */
5304 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
5305 * soft detachment. */
5306 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
5308 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
5309 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
5311 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
5312 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
5314 /** VLRU control flag. non-zero value implies VLRU subsystem is activated. */
5315 static afs_uint32 VLRU_enabled = 1;
5317 /* queue synchronization routines */
5318 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
5319 static void VLRU_EndExclusive_r(struct VLRU_q * q);
5320 static void VLRU_Wait_r(struct VLRU_q * q);
5323 * set VLRU subsystem tunable parameters.
5325 * @param[in] option tunable option to modify
5326 * @param[in] val new value for tunable parameter
5328 * @pre @c VInitVolumePackage has not yet been called.
5330 * @post tunable parameter is modified
5334 * @note valid option parameters are:
5335 * @arg @c VLRU_SET_THRESH
5336 * set the period of inactivity after which
5337 * volumes are eligible for soft detachment
5338 * @arg @c VLRU_SET_INTERVAL
5339 * set the time interval between calls
5340 * to the volume LRU "garbage collector"
5341 * @arg @c VLRU_SET_MAX
5342 * set the max number of volumes to deallocate
5346 VLRU_SetOptions(int option, afs_uint32 val)
5348 if (option == VLRU_SET_THRESH) {
5349 VLRU_offline_thresh = val;
5350 } else if (option == VLRU_SET_INTERVAL) {
5351 VLRU_offline_interval = val;
5352 } else if (option == VLRU_SET_MAX) {
5353 VLRU_offline_max = val;
5354 } else if (option == VLRU_SET_ENABLED) {
5357 VLRU_ComputeConstants();
5361 * compute VLRU internal timing parameters.
5363 * @post VLRU scanner thread internal timing parameters are computed
5365 * @note computes internal timing parameters based upon user-modifiable
5366 * tunable parameters.
5370 * @internal volume package internal use only.
5373 VLRU_ComputeConstants(void)
5375 afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
5377 /* compute the candidate scan interval */
5378 volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
5380 /* compute the promotion intervals */
5381 volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
5382 volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
5385 /* compute the gen 0 scan interval */
5386 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
5388 /* compute the gen 0 scan interval */
5389 volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
5394 * initialize VLRU subsystem.
5396 * @pre this function has not yet been called
5398 * @post VLRU subsystem is initialized and VLRU scanner thread is starting
5402 * @internal volume package internal use only.
5408 pthread_attr_t attrs;
5411 if (!VLRU_enabled) {
5412 Log("VLRU: disabled\n");
5416 /* initialize each of the VLRU queues */
5417 for (i = 0; i < VLRU_QUEUES; i++) {
5418 queue_Init(&volume_LRU.q[i]);
5419 volume_LRU.q[i].len = 0;
5420 volume_LRU.q[i].busy = 0;
5421 assert(pthread_cond_init(&volume_LRU.q[i].cv, NULL) == 0);
5424 /* setup the timing constants */
5425 VLRU_ComputeConstants();
5427 /* XXX put inside LogLevel check? */
5428 Log("VLRU: starting scanner with the following configuration parameters:\n");
5429 Log("VLRU: offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
5430 Log("VLRU: running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
5431 Log("VLRU: taking up to %d volumes offline per pass\n", VLRU_offline_max);
5432 Log("VLRU: scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
5433 Log("VLRU: scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
5434 Log("VLRU: scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
5436 /* start up the VLRU scanner */
5437 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
5438 if (programType == fileServer) {
5439 assert(pthread_cond_init(&volume_LRU.cv, NULL) == 0);
5440 assert(pthread_attr_init(&attrs) == 0);
5441 assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
5442 assert(pthread_create(&tid, &attrs, &VLRU_ScannerThread, NULL) == 0);
5447 * initialize the VLRU-related fields of a newly allocated volume object.
5449 * @param[in] vp pointer to volume object
5452 * @arg @c VOL_LOCK is held.
5453 * @arg volume object is not on a VLRU queue.
5455 * @post VLRU fields are initialized to indicate that volume object is not
5456 * currently registered with the VLRU subsystem
5460 * @internal volume package interal use only.
5463 VLRU_Init_Node_r(volatile Volume * vp)
5468 assert(queue_IsNotOnQueue(&vp->vlru));
5469 vp->vlru.idx = VLRU_QUEUE_INVALID;
5473 * add a volume object to a VLRU queue.
5475 * @param[in] vp pointer to volume object
5478 * @arg @c VOL_LOCK is held.
5479 * @arg caller MUST hold a lightweight ref on @p vp.
5480 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
5482 * @post the volume object is added to the appropriate VLRU queue
5484 * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
5485 * then the volume is added to that queue. Otherwise, the value
5486 * @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
5487 * volume is added to the NEW generation queue.
5489 * @note @c VOL_LOCK may be dropped internally
5491 * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
5492 * during the add operation, and is restored to the previous
5493 * state prior to return.
5497 * @internal volume package internal use only.
5500 VLRU_Add_r(volatile Volume * vp)
5503 VolState state_save;
5508 if (queue_IsOnQueue(&vp->vlru))
5511 state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
5514 if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
5515 idx = VLRU_QUEUE_NEW;
5518 VLRU_Wait_r(&volume_LRU.q[idx]);
5520 /* repeat check since VLRU_Wait_r may have dropped
5522 if (queue_IsNotOnQueue(&vp->vlru)) {
5524 queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
5525 volume_LRU.q[idx].len++;
5526 V_attachFlags(vp) |= VOL_ON_VLRU;
5527 vp->stats.last_promote = FT_ApproxTime();
5530 VChangeState_r(vp, state_save);
5534 * delete a volume object from a VLRU queue.
5536 * @param[in] vp pointer to volume object
5539 * @arg @c VOL_LOCK is held.
5540 * @arg caller MUST hold a lightweight ref on @p vp.
5541 * @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
5543 * @post volume object is removed from the VLRU queue
5545 * @note @c VOL_LOCK may be dropped internally
5549 * @todo We should probably set volume state to something exlcusive
5550 * (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
5552 * @internal volume package internal use only.
5555 VLRU_Delete_r(volatile Volume * vp)
5562 if (queue_IsNotOnQueue(&vp->vlru))
5568 if (idx == VLRU_QUEUE_INVALID)
5570 VLRU_Wait_r(&volume_LRU.q[idx]);
5571 } while (idx != vp->vlru.idx);
5573 /* now remove from the VLRU and update
5574 * the appropriate counter */
5575 queue_Remove(&vp->vlru);
5576 volume_LRU.q[idx].len--;
5577 vp->vlru.idx = VLRU_QUEUE_INVALID;
5578 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
5582 * tell the VLRU subsystem that a volume was just accessed.
5584 * @param[in] vp pointer to volume object
5587 * @arg @c VOL_LOCK is held
5588 * @arg caller MUST hold a lightweight ref on @p vp
5589 * @arg caller MUST NOT hold exclusive ownership of any VLRU queue
5591 * @post volume VLRU access statistics are updated. If the volume was on
5592 * the VLRU soft detach candidate queue, it is moved to the NEW
5595 * @note @c VOL_LOCK may be dropped internally
5599 * @internal volume package internal use only.
5602 VLRU_UpdateAccess_r(volatile Volume * vp)
5604 afs_uint32 live_interval;
5605 Volume * rvp = NULL;
5610 if (queue_IsNotOnQueue(&vp->vlru))
5613 assert(V_attachFlags(vp) & VOL_ON_VLRU);
5615 /* update the access timestamp */
5616 vp->stats.last_get = FT_ApproxTime();
5619 * if the volume is on the soft detach candidate
5620 * list, we need to safely move it back to a
5621 * regular generation. this has to be done
5622 * carefully so we don't race against the scanner
5626 /* if this volume is on the soft detach candidate queue,
5627 * then grab exclusive access to the necessary queues */
5628 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
5630 VCreateReservation_r(rvp);
5632 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
5633 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
5634 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5635 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5638 /* make sure multiple threads don't race to update */
5639 if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
5640 VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
5644 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5645 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
5646 VCancelReservation_r(rvp);
5651 * switch a volume between two VLRU queues.
5653 * @param[in] vp pointer to volume object
5654 * @param[in] new_idx index of VLRU queue onto which the volume will be moved
5655 * @param[in] append controls whether the volume will be appended or
5656 * prepended to the queue. A nonzero value means it will
5657 * be appended; zero means it will be prepended.
5659 * @pre The new (and old, if applicable) queue(s) must either be owned
5660 * exclusively by the calling thread for asynchronous manipulation,
5661 * or the queue(s) must be quiescent and VOL_LOCK must be held.
5662 * Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
5663 * for further details of the queue asynchronous processing mechanism.
5665 * @post If the volume object was already on a VLRU queue, it is
5666 * removed from the queue. Depending on the value of the append
5667 * parameter, the volume object is either appended or prepended
5668 * to the VLRU queue referenced by the new_idx parameter.
5672 * @see VLRU_BeginExclusive_r
5673 * @see VLRU_EndExclusive_r
5676 * @internal volume package internal use only.
5679 VLRU_SwitchQueues(volatile Volume * vp, int new_idx, int append)
5681 if (queue_IsNotOnQueue(&vp->vlru))
5684 queue_Remove(&vp->vlru);
5685 volume_LRU.q[vp->vlru.idx].len--;
5687 /* put the volume back on the correct generational queue */
5689 queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
5691 queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
5694 volume_LRU.q[new_idx].len++;
5695 vp->vlru.idx = new_idx;
5699 * VLRU background thread.
5701 * The VLRU Scanner Thread is responsible for periodically scanning through
5702 * each VLRU queue looking for volumes which should be moved to another
5703 * queue, or soft detached.
5705 * @param[in] args unused thread arguments parameter
5707 * @return unused thread return value
5708 * @retval NULL always
5710 * @internal volume package internal use only.
5713 VLRU_ScannerThread(void * args)
5715 afs_uint32 now, min_delay, delay;
5716 afs_uint32 next_scan[VLRU_GENERATIONS];
5717 afs_uint32 next_promotion[VLRU_GENERATIONS];
5718 int i, min_idx, min_op, overdue, state;
5720 /* set t=0 for promotion cycle to be
5721 * fileserver startup */
5722 now = FT_ApproxTime();
5723 for (i=0; i < VLRU_GENERATIONS-1; i++) {
5724 volume_LRU.last_promotion[i] = now;
5727 /* don't start the scanner until VLRU_offline_thresh
5728 * plus a small delay for VInitVolumePackage to finish
5731 sleep(VLRU_offline_thresh + 60);
5733 /* set t=0 for scan cycle to be now */
5734 now = FT_ApproxTime();
5735 for (i=0; i < VLRU_GENERATIONS+1; i++) {
5736 volume_LRU.last_scan[i] = now;
5740 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
5741 volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
5744 while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
5745 /* check to see if we've been asked to pause */
5746 if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
5747 volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
5748 assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
5750 VOL_CV_WAIT(&volume_LRU.cv);
5751 } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
5754 /* scheduling can happen outside the glock */
5757 /* figure out what is next on the schedule */
5759 /* figure out a potential schedule for the new generation first */
5761 min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
5764 if (min_delay > volume_LRU.scan_interval[0]) {
5765 /* unsigned overflow -- we're overdue to run this scan */
5770 /* if we're not overdue for gen 0, figure out schedule for candidate gen */
5772 i = VLRU_QUEUE_CANDIDATE;
5773 delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
5774 if (delay < min_delay) {
5778 if (delay > volume_LRU.scan_interval[i]) {
5779 /* unsigned overflow -- we're overdue to run this scan */
5786 /* if we're still not overdue for something, figure out schedules for promotions */
5787 for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
5788 delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
5789 if (delay < min_delay) {
5794 if (delay > volume_LRU.promotion_interval[i]) {
5795 /* unsigned overflow -- we're overdue to run this promotion */
5804 /* sleep as needed */
5809 /* do whatever is next */
5812 VLRU_Promote_r(min_idx);
5813 VLRU_Demote_r(min_idx+1);
5815 VLRU_Scan_r(min_idx);
5817 now = FT_ApproxTime();
5820 Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
5822 /* signal that scanner is down */
5823 volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
5824 assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
5830 * promote volumes from one VLRU generation to the next.
5832 * This routine scans a VLRU generation looking for volumes which are
5833 * eligible to be promoted to the next generation. All volumes which
5834 * meet the eligibility requirement are promoted.
5836 * Promotion eligibility is based upon meeting both of the following
5839 * @arg The volume has been accessed since the last promotion:
5840 * @c (vp->stats.last_get >= vp->stats.last_promote)
5841 * @arg The last promotion occurred at least
5842 * @c volume_LRU.promotion_interval[idx] seconds ago
5844 * As a performance optimization, promotions are "globbed". In other
5845 * words, we promote arbitrarily large contiguous sublists of elements
5848 * @param[in] idx VLRU queue index to scan
5852 * @internal VLRU internal use only.
5855 VLRU_Promote_r(int idx)
5857 int len, chaining, promote;
5858 afs_uint32 now, thresh;
5859 struct rx_queue *qp, *nqp;
5860 Volume * vp, *start, *end;
5862 /* get exclusive access to two chains, and drop the glock */
5863 VLRU_Wait_r(&volume_LRU.q[idx]);
5864 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
5865 VLRU_Wait_r(&volume_LRU.q[idx+1]);
5866 VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
5869 thresh = volume_LRU.promotion_interval[idx];
5870 now = FT_ApproxTime();
5873 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
5874 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
5875 promote = (((vp->stats.last_promote + thresh) <= now) &&
5876 (vp->stats.last_get >= vp->stats.last_promote));
5884 /* promote and prepend chain */
5885 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
5899 /* promote and prepend */
5900 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
5904 volume_LRU.q[idx].len -= len;
5905 volume_LRU.q[idx+1].len += len;
5908 /* release exclusive access to the two chains */
5910 volume_LRU.last_promotion[idx] = now;
5911 VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
5912 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
5915 /* run the demotions */
5917 VLRU_Demote_r(int idx)
5920 int len, chaining, demote;
5921 afs_uint32 now, thresh;
5922 struct rx_queue *qp, *nqp;
5923 Volume * vp, *start, *end;
5924 Volume ** salv_flag_vec = NULL;
5925 int salv_vec_offset = 0;
5927 assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
5929 /* get exclusive access to two chains, and drop the glock */
5930 VLRU_Wait_r(&volume_LRU.q[idx-1]);
5931 VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
5932 VLRU_Wait_r(&volume_LRU.q[idx]);
5933 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
5936 /* no big deal if this allocation fails */
5937 if (volume_LRU.q[idx].len) {
5938 salv_flag_vec = (Volume **) malloc(volume_LRU.q[idx].len * sizeof(Volume *));
5941 now = FT_ApproxTime();
5942 thresh = volume_LRU.promotion_interval[idx-1];
5945 for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
5946 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
5947 demote = (((vp->stats.last_promote + thresh) <= now) &&
5948 (vp->stats.last_get < (now - thresh)));
5950 /* we now do volume update list DONT_SALVAGE flag setting during
5951 * demotion passes */
5952 if (salv_flag_vec &&
5953 !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
5955 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
5956 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
5957 salv_flag_vec[salv_vec_offset++] = vp;
5958 VCreateReservation_r(vp);
5967 /* demote and append chain */
5968 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
5982 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
5986 volume_LRU.q[idx].len -= len;
5987 volume_LRU.q[idx-1].len += len;
5990 /* release exclusive access to the two chains */
5992 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
5993 VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
5995 /* now go back and set the DONT_SALVAGE flags as appropriate */
5996 if (salv_flag_vec) {
5998 for (i = 0; i < salv_vec_offset; i++) {
5999 vp = salv_flag_vec[i];
6000 if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
6001 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
6002 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
6005 V_attachFlags(vp) |= VOL_HDR_DONTSALV;
6006 V_dontSalvage(vp) = DONT_SALVAGE;
6007 VUpdateVolume_r(&ec, vp, 0);
6011 VCancelReservation_r(vp);
6013 free(salv_flag_vec);
6017 /* run a pass of the VLRU GC scanner */
6019 VLRU_Scan_r(int idx)
6021 afs_uint32 now, thresh;
6022 struct rx_queue *qp, *nqp;
6023 volatile Volume * vp;
6026 assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
6028 /* gain exclusive access to the idx VLRU */
6029 VLRU_Wait_r(&volume_LRU.q[idx]);
6030 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
6032 if (idx != VLRU_QUEUE_CANDIDATE) {
6033 /* gain exclusive access to the candidate VLRU */
6034 VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6035 VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6038 now = FT_ApproxTime();
6039 thresh = now - VLRU_offline_thresh;
6041 /* perform candidate selection and soft detaching */
6042 if (idx == VLRU_QUEUE_CANDIDATE) {
6043 /* soft detach some volumes from the candidate pool */
6047 for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
6048 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6049 if (i >= VLRU_offline_max) {
6052 /* check timestamp to see if it's a candidate for soft detaching */
6053 if (vp->stats.last_get <= thresh) {
6055 if (VCheckSoftDetach(vp, thresh))
6061 /* scan for volumes to become soft detach candidates */
6062 for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
6063 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6065 /* check timestamp to see if it's a candidate for soft detaching */
6066 if (vp->stats.last_get <= thresh) {
6067 VCheckSoftDetachCandidate(vp, thresh);
6070 if (!(i&0x7f)) { /* lock coarsening optimization */
6078 /* relinquish exclusive access to the VLRU chains */
6082 volume_LRU.last_scan[idx] = now;
6083 if (idx != VLRU_QUEUE_CANDIDATE) {
6084 VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6086 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
6089 /* check whether volume is safe to soft detach
6090 * caller MUST NOT hold a ref count on vp */
6092 VCheckSoftDetach(volatile Volume * vp, afs_uint32 thresh)
6096 if (vp->nUsers || vp->nWaiters)
6099 if (vp->stats.last_get <= thresh) {
6100 ret = VSoftDetachVolume_r(vp, thresh);
6106 /* check whether volume should be made a
6107 * soft detach candidate */
6109 VCheckSoftDetachCandidate(volatile Volume * vp, afs_uint32 thresh)
6112 if (vp->nUsers || vp->nWaiters)
6117 assert(idx == VLRU_QUEUE_NEW);
6119 if (vp->stats.last_get <= thresh) {
6120 /* move to candidate pool */
6121 queue_Remove(&vp->vlru);
6122 volume_LRU.q[VLRU_QUEUE_NEW].len--;
6123 queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
6124 vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
6125 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
6133 /* begin exclusive access on VLRU */
6135 VLRU_BeginExclusive_r(struct VLRU_q * q)
6137 assert(q->busy == 0);
6141 /* end exclusive access on VLRU */
6143 VLRU_EndExclusive_r(struct VLRU_q * q)
6147 assert(pthread_cond_broadcast(&q->cv) == 0);
6150 /* wait for another thread to end exclusive access on VLRU */
6152 VLRU_Wait_r(struct VLRU_q * q)
6155 VOL_CV_WAIT(&q->cv);
6160 * volume soft detach
6162 * caller MUST NOT hold a ref count on vp */
6164 VSoftDetachVolume_r(volatile Volume * vp, afs_uint32 thresh)
6169 assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
6171 ts_save = vp->stats.last_get;
6172 if (ts_save > thresh)
6175 if (vp->nUsers || vp->nWaiters)
6178 if (VIsExclusiveState(V_attachState(vp))) {
6182 switch (V_attachState(vp)) {
6183 case VOL_STATE_UNATTACHED:
6184 case VOL_STATE_PREATTACHED:
6185 case VOL_STATE_ERROR:
6186 case VOL_STATE_GOING_OFFLINE:
6187 case VOL_STATE_SHUTTING_DOWN:
6188 case VOL_STATE_SALVAGING:
6189 volume_LRU.q[vp->vlru.idx].len--;
6191 /* create and cancel a reservation to
6192 * give the volume an opportunity to
6194 VCreateReservation_r(vp);
6195 queue_Remove(&vp->vlru);
6196 vp->vlru.idx = VLRU_QUEUE_INVALID;
6197 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
6198 VCancelReservation_r(vp);
6202 /* hold the volume and take it offline.
6203 * no need for reservations, as VHold_r
6204 * takes care of that internally. */
6205 if (VHold_r(vp) == 0) {
6206 /* vhold drops the glock, so now we should
6207 * check to make sure we aren't racing against
6208 * other threads. if we are racing, offlining vp
6209 * would be wasteful, and block the scanner for a while
6213 (vp->shuttingDown) ||
6214 (vp->goingOffline) ||
6215 (vp->stats.last_get != ts_save)) {
6216 /* looks like we're racing someone else. bail */
6220 /* pull it off the VLRU */
6221 assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
6222 volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
6223 queue_Remove(&vp->vlru);
6224 vp->vlru.idx = VLRU_QUEUE_INVALID;
6225 V_attachFlags(vp) &= ~(VOL_ON_VLRU);
6227 /* take if offline */
6228 VOffline_r(vp, "volume has been soft detached");
6230 /* invalidate the volume header cache */
6231 FreeVolumeHeader(vp);
6234 IncUInt64(&VStats.soft_detaches);
6235 vp->stats.soft_detaches++;
6237 /* put in pre-attached state so demand
6238 * attacher can work on it */
6239 VChangeState_r(vp, VOL_STATE_PREATTACHED);
6245 #endif /* AFS_DEMAND_ATTACH_FS */
6248 /***************************************************/
6249 /* Volume Header Cache routines */
6250 /***************************************************/
6253 * volume header cache.
6255 struct volume_hdr_LRU_t volume_hdr_LRU;
6258 * initialize the volume header cache.
6260 * @param[in] howMany number of header cache entries to preallocate
6262 * @pre VOL_LOCK held. Function has never been called before.
6264 * @post howMany cache entries are allocated, initialized, and added
6265 * to the LRU list. Header cache statistics are initialized.
6267 * @note only applicable to fileServer program type. Should only be
6268 * called once during volume package initialization.
6270 * @internal volume package internal use only.
6273 VInitVolumeHeaderCache(afs_uint32 howMany)
6275 register struct volHeader *hp;
6276 if (programType != fileServer)
6278 queue_Init(&volume_hdr_LRU);
6279 volume_hdr_LRU.stats.free = 0;
6280 volume_hdr_LRU.stats.used = howMany;
6281 volume_hdr_LRU.stats.attached = 0;
6282 hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
6286 /* We are using ReleaseVolumeHeader to initialize the values on the header list
6287 * to ensure they have the right values
6289 ReleaseVolumeHeader(hp++);
6293 * get a volume header and attach it to the volume object.
6295 * @param[in] vp pointer to volume object
6297 * @return cache entry status
6298 * @retval 0 volume header was newly attached; cache data is invalid
6299 * @retval 1 volume header was previously attached; cache data is valid
6301 * @pre VOL_LOCK held. For DAFS, lightweight ref must be held on volume object.
6303 * @post volume header attached to volume object. if necessary, header cache
6304 * entry on LRU is synchronized to disk. Header is removed from LRU list.
6306 * @note VOL_LOCK may be dropped
6308 * @warning this interface does not load header data from disk. it merely
6309 * attaches a header object to the volume object, and may sync the old
6310 * header cache data out to disk in the process.
6312 * @internal volume package internal use only.
6315 GetVolumeHeader(register Volume * vp)
6318 register struct volHeader *hd;
6320 static int everLogged = 0;
6322 #ifdef AFS_DEMAND_ATTACH_FS
6323 VolState vp_save, back_save;
6325 /* XXX debug 9/19/05 we've apparently got
6326 * a ref counting bug somewhere that's
6327 * breaking the nUsers == 0 => header on LRU
6329 if (vp->header && queue_IsNotOnQueue(vp->header)) {
6330 Log("nUsers == 0, but header not on LRU\n");
6335 old = (vp->header != NULL); /* old == volume already has a header */
6337 if (programType != fileServer) {
6338 /* for volume utilities, we allocate volHeaders as needed */
6340 hd = (struct volHeader *)calloc(1, sizeof(*vp->header));
6344 #ifdef AFS_DEMAND_ATTACH_FS
6345 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
6349 /* for the fileserver, we keep a volume header cache */
6351 /* the header we previously dropped in the lru is
6352 * still available. pull it off the lru and return */
6355 assert(hd->back == vp);
6357 /* we need to grab a new element off the LRU */
6358 if (queue_IsNotEmpty(&volume_hdr_LRU)) {
6359 /* grab an element and pull off of LRU */
6360 hd = queue_First(&volume_hdr_LRU, volHeader);
6363 /* LRU is empty, so allocate a new volHeader
6364 * this is probably indicative of a leak, so let the user know */
6365 hd = (struct volHeader *)calloc(1, sizeof(struct volHeader));
6368 Log("****Allocated more volume headers, probably leak****\n");
6371 volume_hdr_LRU.stats.free++;
6374 /* this header used to belong to someone else.
6375 * we'll need to check if the header needs to
6376 * be sync'd out to disk */
6378 #ifdef AFS_DEMAND_ATTACH_FS
6379 /* if hd->back were in an exclusive state, then
6380 * its volHeader would not be on the LRU... */
6381 assert(!VIsExclusiveState(V_attachState(hd->back)));
6384 if (hd->diskstuff.inUse) {
6385 /* volume was in use, so we'll need to sync
6386 * its header to disk */
6388 #ifdef AFS_DEMAND_ATTACH_FS
6389 back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
6390 vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
6391 VCreateReservation_r(hd->back);
6395 WriteVolumeHeader_r(&error, hd->back);
6396 /* Ignore errors; catch them later */
6398 #ifdef AFS_DEMAND_ATTACH_FS
6403 hd->back->header = NULL;
6404 #ifdef AFS_DEMAND_ATTACH_FS
6405 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
6407 if (hd->diskstuff.inUse) {
6408 VChangeState_r(hd->back, back_save);
6409 VCancelReservation_r(hd->back);
6410 VChangeState_r(vp, vp_save);
6414 volume_hdr_LRU.stats.attached++;
6418 #ifdef AFS_DEMAND_ATTACH_FS
6419 V_attachFlags(vp) |= VOL_HDR_ATTACHED;
6422 volume_hdr_LRU.stats.free--;
6423 volume_hdr_LRU.stats.used++;
6425 IncUInt64(&VStats.hdr_gets);
6426 #ifdef AFS_DEMAND_ATTACH_FS
6427 IncUInt64(&vp->stats.hdr_gets);
6428 vp->stats.last_hdr_get = FT_ApproxTime();
6435 * make sure volume header is attached and contains valid cache data.
6437 * @param[out] ec outbound error code
6438 * @param[in] vp pointer to volume object
6440 * @pre VOL_LOCK held. For DAFS, lightweight ref held on vp.
6442 * @post header cache entry attached, and loaded with valid data, or
6443 * *ec is nonzero, and the header is released back into the LRU.
6445 * @internal volume package internal use only.
6448 LoadVolumeHeader(Error * ec, Volume * vp)
6450 #ifdef AFS_DEMAND_ATTACH_FS
6451 VolState state_save;
6455 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
6456 IncUInt64(&VStats.hdr_loads);
6457 state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
6460 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
6461 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
6463 IncUInt64(&vp->stats.hdr_loads);
6464 now = FT_ApproxTime();
6468 V_attachFlags(vp) |= VOL_HDR_LOADED;
6469 vp->stats.last_hdr_load = now;
6471 VChangeState_r(vp, state_save);
6473 #else /* AFS_DEMAND_ATTACH_FS */
6475 if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
6476 IncUInt64(&VStats.hdr_loads);
6478 ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
6479 sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
6482 #endif /* AFS_DEMAND_ATTACH_FS */
6484 /* maintain (nUsers==0) => header in LRU invariant */
6485 FreeVolumeHeader(vp);
6490 * release a header cache entry back into the LRU list.
6492 * @param[in] hd pointer to volume header cache object
6494 * @pre VOL_LOCK held.
6496 * @post header cache object appended onto end of LRU list.
6498 * @note only applicable to fileServer program type.
6500 * @note used to place a header cache entry back into the
6501 * LRU pool without invalidating it as a cache entry.
6503 * @internal volume package internal use only.
6506 ReleaseVolumeHeader(register struct volHeader *hd)
6508 if (programType != fileServer)
6510 if (!hd || queue_IsOnQueue(hd)) /* no header, or header already released */
6512 queue_Append(&volume_hdr_LRU, hd);
6513 #ifdef AFS_DEMAND_ATTACH_FS
6515 V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
6518 volume_hdr_LRU.stats.free++;
6519 volume_hdr_LRU.stats.used--;
6523 * free/invalidate a volume header cache entry.
6525 * @param[in] vp pointer to volume object
6527 * @pre VOL_LOCK is held.
6529 * @post For fileserver, header cache entry is returned to LRU, and it is
6530 * invalidated as a cache entry. For volume utilities, the header
6531 * cache entry is freed.
6533 * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
6534 * whenever it is necessary to invalidate the header cache entry.
6536 * @see ReleaseVolumeHeader
6538 * @internal volume package internal use only.
6541 FreeVolumeHeader(register Volume * vp)
6543 register struct volHeader *hd = vp->header;
6546 if (programType == fileServer) {
6547 ReleaseVolumeHeader(hd);
6552 #ifdef AFS_DEMAND_ATTACH_FS
6553 V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
6555 volume_hdr_LRU.stats.attached--;
6560 /***************************************************/
6561 /* Volume Hash Table routines */
6562 /***************************************************/
6565 * set size of volume object hash table.
6567 * @param[in] logsize log(2) of desired hash table size
6569 * @return operation status
6571 * @retval -1 failure
6573 * @pre MUST be called prior to VInitVolumePackage
6575 * @post Volume Hash Table will have 2^logsize buckets
6578 VSetVolHashSize(int logsize)
6580 /* 64 to 16384 hash buckets seems like a reasonable range */
6581 if ((logsize < 6 ) || (logsize > 14)) {
6586 VolumeHashTable.Size = 1 << logsize;
6587 VolumeHashTable.Mask = VolumeHashTable.Size - 1;
6589 /* we can't yet support runtime modification of this
6590 * parameter. we'll need a configuration rwlock to
6591 * make runtime modification feasible.... */
6598 * initialize dynamic data structures for volume hash table.
6600 * @post hash table is allocated, and fields are initialized.
6602 * @internal volume package internal use only.
6605 VInitVolumeHash(void)
6609 VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
6610 sizeof(VolumeHashChainHead));
6611 assert(VolumeHashTable.Table != NULL);
6613 for (i=0; i < VolumeHashTable.Size; i++) {
6614 queue_Init(&VolumeHashTable.Table[i]);
6615 #ifdef AFS_DEMAND_ATTACH_FS
6616 assert(pthread_cond_init(&VolumeHashTable.Table[i].chain_busy_cv, NULL) == 0);
6617 #endif /* AFS_DEMAND_ATTACH_FS */
6622 * add a volume object to the hash table.
6624 * @param[in] vp pointer to volume object
6625 * @param[in] hashid hash of volume id
6627 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
6630 * @post volume is added to hash chain.
6632 * @internal volume package internal use only.
6634 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
6635 * asynchronous hash chain reordering to finish.
6638 AddVolumeToHashTable(register Volume * vp, int hashid)
6640 VolumeHashChainHead * head;
6642 if (queue_IsOnQueue(vp))
6645 head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
6647 #ifdef AFS_DEMAND_ATTACH_FS
6648 /* wait for the hash chain to become available */
6651 V_attachFlags(vp) |= VOL_IN_HASH;
6652 vp->chainCacheCheck = ++head->cacheCheck;
6653 #endif /* AFS_DEMAND_ATTACH_FS */
6656 vp->hashid = hashid;
6657 queue_Append(head, vp);
6658 vp->vnodeHashOffset = VolumeHashOffset_r();
6662 * delete a volume object from the hash table.
6664 * @param[in] vp pointer to volume object
6666 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
6669 * @post volume is removed from hash chain.
6671 * @internal volume package internal use only.
6673 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
6674 * asynchronous hash chain reordering to finish.
6677 DeleteVolumeFromHashTable(register Volume * vp)
6679 VolumeHashChainHead * head;
6681 if (!queue_IsOnQueue(vp))
6684 head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
6686 #ifdef AFS_DEMAND_ATTACH_FS
6687 /* wait for the hash chain to become available */
6690 V_attachFlags(vp) &= ~(VOL_IN_HASH);
6692 #endif /* AFS_DEMAND_ATTACH_FS */
6696 /* do NOT reset hashid to zero, as the online
6697 * salvager package may need to know the volume id
6698 * after the volume is removed from the hash */
6702 * lookup a volume object in the hash table given a volume id.
6704 * @param[out] ec error code return
6705 * @param[in] volumeId volume id
6706 * @param[in] hint volume object which we believe could be the correct
6709 * @return volume object pointer
6710 * @retval NULL no such volume id is registered with the hash table.
6712 * @pre VOL_LOCK is held. For DAFS, caller must hold a lightweight
6715 * @post volume object with the given id is returned. volume object and
6716 * hash chain access statistics are updated. hash chain may have
6719 * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
6720 * asynchronous hash chain reordering operation to finish, or
6721 * in order for us to perform an asynchronous chain reordering.
6723 * @note Hash chain reorderings occur when the access count for the
6724 * volume object being looked up exceeds the sum of the previous
6725 * node's (the node ahead of it in the hash chain linked list)
6726 * access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
6728 * @note For DAFS, the hint parameter allows us to short-circuit if the
6729 * cacheCheck fields match between the hash chain head and the
6730 * hint volume object.
6733 VLookupVolume_r(Error * ec, VolId volumeId, Volume * hint)
6735 register int looks = 0;
6737 #ifdef AFS_DEMAND_ATTACH_FS
6740 VolumeHashChainHead * head;
6743 head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
6745 #ifdef AFS_DEMAND_ATTACH_FS
6746 /* wait for the hash chain to become available */
6749 /* check to see if we can short circuit without walking the hash chain */
6750 if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
6751 IncUInt64(&hint->stats.hash_short_circuits);
6754 #endif /* AFS_DEMAND_ATTACH_FS */
6756 /* someday we need to either do per-chain locks, RWlocks,
6757 * or both for volhash access.
6758 * (and move to a data structure with better cache locality) */
6760 /* search the chain for this volume id */
6761 for(queue_Scan(head, vp, np, Volume)) {
6763 if ((vp->hashid == volumeId)) {
6768 if (queue_IsEnd(head, vp)) {
6772 #ifdef AFS_DEMAND_ATTACH_FS
6773 /* update hash chain statistics */
6776 FillInt64(lks, 0, looks);
6777 AddUInt64(head->looks, lks, &head->looks);
6778 AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
6779 IncUInt64(&head->gets);
6784 IncUInt64(&vp->stats.hash_lookups);
6786 /* for demand attach fileserver, we permit occasional hash chain reordering
6787 * so that frequently looked up volumes move towards the head of the chain */
6788 pp = queue_Prev(vp, Volume);
6789 if (!queue_IsEnd(head, pp)) {
6790 FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
6791 AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
6792 if (GEInt64(vp->stats.hash_lookups, thresh)) {
6793 VReorderHash_r(head, pp, vp);
6797 /* update the short-circuit cache check */
6798 vp->chainCacheCheck = head->cacheCheck;
6800 #endif /* AFS_DEMAND_ATTACH_FS */
6805 #ifdef AFS_DEMAND_ATTACH_FS
6806 /* perform volume hash chain reordering.
6808 * advance a subchain beginning at vp ahead of
6809 * the adjacent subchain ending at pp */
6811 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
6813 Volume *tp, *np, *lp;
6814 afs_uint64 move_thresh;
6816 /* this should never be called if the chain is already busy, so
6817 * no need to wait for other exclusive chain ops to finish */
6819 /* this is a rather heavy set of operations,
6820 * so let's set the chain busy flag and drop
6822 VHashBeginExclusive_r(head);
6825 /* scan forward in the chain from vp looking for the last element
6826 * in the chain we want to advance */
6827 FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
6828 AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
6829 for(queue_ScanFrom(head, vp, tp, np, Volume)) {
6830 if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
6834 lp = queue_Prev(tp, Volume);
6836 /* scan backwards from pp to determine where to splice and
6837 * insert the subchain we're advancing */
6838 for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
6839 if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
6843 tp = queue_Next(tp, Volume);
6845 /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
6846 queue_MoveChainBefore(tp,vp,lp);
6849 IncUInt64(&VStats.hash_reorders);
6851 IncUInt64(&head->reorders);
6853 /* wake up any threads waiting for the hash chain */
6854 VHashEndExclusive_r(head);
6858 /* demand-attach fs volume hash
6859 * asynchronous exclusive operations */
6862 * begin an asynchronous exclusive operation on a volume hash chain.
6864 * @param[in] head pointer to volume hash chain head object
6866 * @pre VOL_LOCK held. hash chain is quiescent.
6868 * @post hash chain marked busy.
6870 * @note this interface is used in conjunction with VHashEndExclusive_r and
6871 * VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
6872 * volume hash chain. Its main use case is hash chain reordering, which
6873 * has the potential to be a highly latent operation.
6875 * @see VHashEndExclusive_r
6880 * @internal volume package internal use only.
6883 VHashBeginExclusive_r(VolumeHashChainHead * head)
6885 assert(head->busy == 0);
6890 * relinquish exclusive ownership of a volume hash chain.
6892 * @param[in] head pointer to volume hash chain head object
6894 * @pre VOL_LOCK held. thread owns the hash chain exclusively.
6896 * @post hash chain is marked quiescent. threads awaiting use of
6897 * chain are awakened.
6899 * @see VHashBeginExclusive_r
6904 * @internal volume package internal use only.
6907 VHashEndExclusive_r(VolumeHashChainHead * head)
6911 assert(pthread_cond_broadcast(&head->chain_busy_cv) == 0);
6915 * wait for all asynchronous operations on a hash chain to complete.
6917 * @param[in] head pointer to volume hash chain head object
6919 * @pre VOL_LOCK held.
6921 * @post hash chain object is quiescent.
6923 * @see VHashBeginExclusive_r
6924 * @see VHashEndExclusive_r
6928 * @note This interface should be called before any attempt to
6929 * traverse the hash chain. It is permissible for a thread
6930 * to gain exclusive access to the chain, and then perform
6931 * latent operations on the chain asynchronously wrt the
6934 * @warning if waiting is necessary, VOL_LOCK is dropped
6936 * @internal volume package internal use only.
6939 VHashWait_r(VolumeHashChainHead * head)
6941 while (head->busy) {
6942 VOL_CV_WAIT(&head->chain_busy_cv);
6945 #endif /* AFS_DEMAND_ATTACH_FS */
6948 /***************************************************/
6949 /* Volume by Partition List routines */
6950 /***************************************************/
6953 * demand attach fileserver adds a
6954 * linked list of volumes to each
6955 * partition object, thus allowing
6956 * for quick enumeration of all
6957 * volumes on a partition
6960 #ifdef AFS_DEMAND_ATTACH_FS
6962 * add a volume to its disk partition VByPList.
6964 * @param[in] vp pointer to volume object
6966 * @pre either the disk partition VByPList is owned exclusively
6967 * by the calling thread, or the list is quiescent and
6970 * @post volume is added to disk partition VByPList
6974 * @warning it is the caller's responsibility to ensure list
6977 * @see VVByPListWait_r
6978 * @see VVByPListBeginExclusive_r
6979 * @see VVByPListEndExclusive_r
6981 * @internal volume package internal use only.
6984 AddVolumeToVByPList_r(Volume * vp)
6986 if (queue_IsNotOnQueue(&vp->vol_list)) {
6987 queue_Append(&vp->partition->vol_list, &vp->vol_list);
6988 V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
6989 vp->partition->vol_list.len++;
6994 * delete a volume from its disk partition VByPList.
6996 * @param[in] vp pointer to volume object
6998 * @pre either the disk partition VByPList is owned exclusively
6999 * by the calling thread, or the list is quiescent and
7002 * @post volume is removed from the disk partition VByPList
7006 * @warning it is the caller's responsibility to ensure list
7009 * @see VVByPListWait_r
7010 * @see VVByPListBeginExclusive_r
7011 * @see VVByPListEndExclusive_r
7013 * @internal volume package internal use only.
7016 DeleteVolumeFromVByPList_r(Volume * vp)
7018 if (queue_IsOnQueue(&vp->vol_list)) {
7019 queue_Remove(&vp->vol_list);
7020 V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
7021 vp->partition->vol_list.len--;
7026 * begin an asynchronous exclusive operation on a VByPList.
7028 * @param[in] dp pointer to disk partition object
7030 * @pre VOL_LOCK held. VByPList is quiescent.
7032 * @post VByPList marked busy.
7034 * @note this interface is used in conjunction with VVByPListEndExclusive_r and
7035 * VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
7038 * @see VVByPListEndExclusive_r
7039 * @see VVByPListWait_r
7043 * @internal volume package internal use only.
7045 /* take exclusive control over the list */
7047 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
7049 assert(dp->vol_list.busy == 0);
7050 dp->vol_list.busy = 1;
7054 * relinquish exclusive ownership of a VByPList.
7056 * @param[in] dp pointer to disk partition object
7058 * @pre VOL_LOCK held. thread owns the VByPList exclusively.
7060 * @post VByPList is marked quiescent. threads awaiting use of
7061 * the list are awakened.
7063 * @see VVByPListBeginExclusive_r
7064 * @see VVByPListWait_r
7068 * @internal volume package internal use only.
7071 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
7073 assert(dp->vol_list.busy);
7074 dp->vol_list.busy = 0;
7075 assert(pthread_cond_broadcast(&dp->vol_list.cv) == 0);
7079 * wait for all asynchronous operations on a VByPList to complete.
7081 * @param[in] dp pointer to disk partition object
7083 * @pre VOL_LOCK is held.
7085 * @post disk partition's VByP list is quiescent
7089 * @note This interface should be called before any attempt to
7090 * traverse the VByPList. It is permissible for a thread
7091 * to gain exclusive access to the list, and then perform
7092 * latent operations on the list asynchronously wrt the
7095 * @warning if waiting is necessary, VOL_LOCK is dropped
7097 * @see VVByPListEndExclusive_r
7098 * @see VVByPListBeginExclusive_r
7100 * @internal volume package internal use only.
7103 VVByPListWait_r(struct DiskPartition64 * dp)
7105 while (dp->vol_list.busy) {
7106 VOL_CV_WAIT(&dp->vol_list.cv);
7109 #endif /* AFS_DEMAND_ATTACH_FS */
7111 /***************************************************/
7112 /* Volume Cache Statistics routines */
7113 /***************************************************/
7116 VPrintCacheStats_r(void)
7118 afs_uint32 get_hi, get_lo, load_hi, load_lo;
7119 register struct VnodeClassInfo *vcp;
7120 vcp = &VnodeClassInfo[vLarge];
7121 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);
7122 vcp = &VnodeClassInfo[vSmall];
7123 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);
7124 SplitInt64(VStats.hdr_gets, get_hi, get_lo);
7125 SplitInt64(VStats.hdr_loads, load_hi, load_lo);
7126 Log("Volume header cache, %d entries, %d gets, %d replacements\n",
7127 VStats.hdr_cache_size, get_lo, load_lo);
7131 VPrintCacheStats(void)
7134 VPrintCacheStats_r();
7138 #ifdef AFS_DEMAND_ATTACH_FS
7140 UInt64ToDouble(afs_uint64 * x)
7142 static double c32 = 4.0 * 1.073741824 * 1000000000.0;
7144 SplitInt64(*x, h, l);
7145 return (((double)h) * c32) + ((double) l);
7149 DoubleToPrintable(double x, char * buf, int len)
7151 static double billion = 1000000000.0;
7154 y[0] = (afs_uint32) (x / (billion * billion));
7155 y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
7156 y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
7159 snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
7161 snprintf(buf, len, "%d%09d", y[1], y[2]);
7163 snprintf(buf, len, "%d", y[2]);
7169 struct VLRUExtStatsEntry {
7173 struct VLRUExtStats {
7179 } queue_info[VLRU_QUEUE_INVALID];
7180 struct VLRUExtStatsEntry * vec;
7184 * add a 256-entry fudge factor onto the vector in case state changes
7185 * out from under us.
7187 #define VLRU_EXT_STATS_VEC_LEN_FUDGE 256
7190 * collect extended statistics for the VLRU subsystem.
7192 * @param[out] stats pointer to stats structure to be populated
7193 * @param[in] nvols number of volumes currently known to exist
7195 * @pre VOL_LOCK held
7197 * @post stats->vec allocated and populated
7199 * @return operation status
7204 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
7206 afs_uint32 cur, idx, len;
7207 struct rx_queue * qp, * nqp;
7209 struct VLRUExtStatsEntry * vec;
7211 len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
7212 vec = stats->vec = calloc(len,
7213 sizeof(struct VLRUExtStatsEntry));
7219 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
7220 VLRU_Wait_r(&volume_LRU.q[idx]);
7221 VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7224 stats->queue_info[idx].start = cur;
7226 for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7228 /* out of space in vec */
7231 vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7232 vec[cur].volid = vp->hashid;
7236 stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
7239 VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7247 #define ENUMTOSTRING(en) #en
7248 #define ENUMCASE(en) \
7250 return ENUMTOSTRING(en); \
7254 vlru_idx_to_string(int idx)
7257 ENUMCASE(VLRU_QUEUE_NEW);
7258 ENUMCASE(VLRU_QUEUE_MID);
7259 ENUMCASE(VLRU_QUEUE_OLD);
7260 ENUMCASE(VLRU_QUEUE_CANDIDATE);
7261 ENUMCASE(VLRU_QUEUE_HELD);
7262 ENUMCASE(VLRU_QUEUE_INVALID);
7264 return "**UNKNOWN**";
7269 VPrintExtendedCacheStats_r(int flags)
7272 afs_uint32 vol_sum = 0;
7279 struct stats looks, gets, reorders, len;
7280 struct stats ch_looks, ch_gets, ch_reorders;
7282 VolumeHashChainHead *head;
7284 struct VLRUExtStats vlru_stats;
7286 /* zero out stats */
7287 memset(&looks, 0, sizeof(struct stats));
7288 memset(&gets, 0, sizeof(struct stats));
7289 memset(&reorders, 0, sizeof(struct stats));
7290 memset(&len, 0, sizeof(struct stats));
7291 memset(&ch_looks, 0, sizeof(struct stats));
7292 memset(&ch_gets, 0, sizeof(struct stats));
7293 memset(&ch_reorders, 0, sizeof(struct stats));
7295 for (i = 0; i < VolumeHashTable.Size; i++) {
7296 head = &VolumeHashTable.Table[i];
7299 VHashBeginExclusive_r(head);
7302 ch_looks.sum = UInt64ToDouble(&head->looks);
7303 ch_gets.sum = UInt64ToDouble(&head->gets);
7304 ch_reorders.sum = UInt64ToDouble(&head->reorders);
7306 /* update global statistics */
7308 looks.sum += ch_looks.sum;
7309 gets.sum += ch_gets.sum;
7310 reorders.sum += ch_reorders.sum;
7311 len.sum += (double)head->len;
7312 vol_sum += head->len;
7315 len.min = (double) head->len;
7316 len.max = (double) head->len;
7317 looks.min = ch_looks.sum;
7318 looks.max = ch_looks.sum;
7319 gets.min = ch_gets.sum;
7320 gets.max = ch_gets.sum;
7321 reorders.min = ch_reorders.sum;
7322 reorders.max = ch_reorders.sum;
7324 if (((double)head->len) < len.min)
7325 len.min = (double) head->len;
7326 if (((double)head->len) > len.max)
7327 len.max = (double) head->len;
7328 if (ch_looks.sum < looks.min)
7329 looks.min = ch_looks.sum;
7330 else if (ch_looks.sum > looks.max)
7331 looks.max = ch_looks.sum;
7332 if (ch_gets.sum < gets.min)
7333 gets.min = ch_gets.sum;
7334 else if (ch_gets.sum > gets.max)
7335 gets.max = ch_gets.sum;
7336 if (ch_reorders.sum < reorders.min)
7337 reorders.min = ch_reorders.sum;
7338 else if (ch_reorders.sum > reorders.max)
7339 reorders.max = ch_reorders.sum;
7343 if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
7344 /* compute detailed per-chain stats */
7345 struct stats hdr_loads, hdr_gets;
7346 double v_looks, v_loads, v_gets;
7348 /* initialize stats with data from first element in chain */
7349 vp = queue_First(head, Volume);
7350 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
7351 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
7352 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
7353 ch_gets.min = ch_gets.max = v_looks;
7354 hdr_loads.min = hdr_loads.max = v_loads;
7355 hdr_gets.min = hdr_gets.max = v_gets;
7356 hdr_loads.sum = hdr_gets.sum = 0;
7358 vp = queue_Next(vp, Volume);
7360 /* pull in stats from remaining elements in chain */
7361 for (queue_ScanFrom(head, vp, vp, np, Volume)) {
7362 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
7363 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
7364 v_gets = UInt64ToDouble(&vp->stats.hdr_gets);
7366 hdr_loads.sum += v_loads;
7367 hdr_gets.sum += v_gets;
7369 if (v_looks < ch_gets.min)
7370 ch_gets.min = v_looks;
7371 else if (v_looks > ch_gets.max)
7372 ch_gets.max = v_looks;
7374 if (v_loads < hdr_loads.min)
7375 hdr_loads.min = v_loads;
7376 else if (v_loads > hdr_loads.max)
7377 hdr_loads.max = v_loads;
7379 if (v_gets < hdr_gets.min)
7380 hdr_gets.min = v_gets;
7381 else if (v_gets > hdr_gets.max)
7382 hdr_gets.max = v_gets;
7385 /* compute per-chain averages */
7386 ch_gets.avg = ch_gets.sum / ((double)head->len);
7387 hdr_loads.avg = hdr_loads.sum / ((double)head->len);
7388 hdr_gets.avg = hdr_gets.sum / ((double)head->len);
7390 /* dump per-chain stats */
7391 Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
7393 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
7394 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
7395 Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
7396 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
7397 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
7398 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
7399 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
7400 Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
7401 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
7402 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
7403 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
7404 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
7405 Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
7406 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
7407 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
7408 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
7409 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
7410 } else if (flags & VOL_STATS_PER_CHAIN) {
7411 /* dump simple per-chain stats */
7412 Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
7414 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
7415 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
7416 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
7420 VHashEndExclusive_r(head);
7425 /* compute global averages */
7426 len.avg = len.sum / ((double)VolumeHashTable.Size);
7427 looks.avg = looks.sum / ((double)VolumeHashTable.Size);
7428 gets.avg = gets.sum / ((double)VolumeHashTable.Size);
7429 reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
7431 /* dump global stats */
7432 Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
7433 Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
7434 DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
7435 DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
7436 DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
7437 DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
7438 Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
7439 DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
7440 DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
7441 DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
7442 DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
7443 Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
7444 DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
7445 DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
7446 DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
7447 DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
7448 Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
7449 DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
7450 DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
7451 DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
7452 DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
7454 /* print extended disk related statistics */
7456 struct DiskPartition64 * diskP;
7457 afs_uint32 vol_count[VOLMAXPARTS+1];
7458 byte part_exists[VOLMAXPARTS+1];
7462 memset(vol_count, 0, sizeof(vol_count));
7463 memset(part_exists, 0, sizeof(part_exists));
7467 for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
7469 vol_count[id] = diskP->vol_list.len;
7470 part_exists[id] = 1;
7474 for (i = 0; i <= VOLMAXPARTS; i++) {
7475 if (part_exists[i]) {
7476 /* XXX while this is currently safe, it is a violation
7477 * of the VGetPartitionById_r interface contract. */
7478 diskP = VGetPartitionById_r(i, 0);
7480 Log("Partition %s has %d online volumes\n",
7481 VPartitionPath(diskP), diskP->vol_list.len);
7488 /* print extended VLRU statistics */
7489 if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
7490 afs_uint32 idx, cur, lpos;
7494 Log("VLRU State Dump:\n\n");
7496 for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
7497 Log("\t%s:\n", vlru_idx_to_string(idx));
7500 for (cur = vlru_stats.queue_info[idx].start;
7501 cur < vlru_stats.queue_info[idx].len;
7503 line[lpos++] = vlru_stats.vec[cur].volid;
7505 Log("\t\t%u, %u, %u, %u, %u,\n",
7506 line[0], line[1], line[2], line[3], line[4]);
7515 Log("\t\t%u, %u, %u, %u, %u\n",
7516 line[0], line[1], line[2], line[3], line[4]);
7521 free(vlru_stats.vec);
7528 VPrintExtendedCacheStats(int flags)
7531 VPrintExtendedCacheStats_r(flags);
7534 #endif /* AFS_DEMAND_ATTACH_FS */