Remove server logging globals
[openafs.git] / src / vol / volume.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  *
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
8  *
9  * Portions Copyright (c) 2005-2008 Sine Nomine Associates
10  */
11
12 /* 1/1/89: NB:  this stuff is all going to be replaced.  Don't take it too seriously */
13 /*
14
15         System:         VICE-TWO
16         Module:         volume.c
17         Institution:    The Information Technology Center, Carnegie-Mellon University
18
19  */
20
21 #include <afsconfig.h>
22 #include <afs/param.h>
23
24 #include <roken.h>
25 #include <afs/opr.h>
26
27 #include <ctype.h>
28 #include <stddef.h>
29
30 #ifdef HAVE_SYS_FILE_H
31 #include <sys/file.h>
32 #endif
33
34 #ifdef AFS_PTHREAD_ENV
35 # include <opr/lock.h>
36 #else
37 # include <opr/lockstub.h>
38 #endif
39 #include <opr/ffs.h>
40 #include <opr/jhash.h>
41
42 #include <afs/afsint.h>
43
44 #include <rx/rx_queue.h>
45
46 #ifndef AFS_NT40_ENV
47 #if !defined(AFS_SGI_ENV)
48 #ifdef  AFS_OSF_ENV
49 #include <ufs/fs.h>
50 #else /* AFS_OSF_ENV */
51 #ifdef AFS_VFSINCL_ENV
52 #define VFS
53 #ifdef  AFS_SUN5_ENV
54 #include <sys/fs/ufs_fs.h>
55 #else
56 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
57 #include <ufs/ufs/dinode.h>
58 #include <ufs/ffs/fs.h>
59 #else
60 #include <ufs/fs.h>
61 #endif
62 #endif
63 #else /* AFS_VFSINCL_ENV */
64 #if !defined(AFS_AIX_ENV) && !defined(AFS_LINUX20_ENV) && !defined(AFS_XBSD_ENV) && !defined(AFS_DARWIN_ENV)
65 #include <sys/fs.h>
66 #endif
67 #endif /* AFS_VFSINCL_ENV */
68 #endif /* AFS_OSF_ENV */
69 #endif /* AFS_SGI_ENV */
70 #endif /* !AFS_NT40_ENV */
71
72 #ifdef  AFS_AIX_ENV
73 #include <sys/vfs.h>
74 #else
75 #ifdef  AFS_HPUX_ENV
76 #include <mntent.h>
77 #else
78 #if     defined(AFS_SUN_ENV) || defined(AFS_SUN5_ENV)
79 #ifdef  AFS_SUN5_ENV
80 #include <sys/mnttab.h>
81 #include <sys/mntent.h>
82 #else
83 #include <mntent.h>
84 #endif
85 #else
86 #ifndef AFS_NT40_ENV
87 #if defined(AFS_SGI_ENV)
88 #include <mntent.h>
89 #else
90 #ifndef AFS_LINUX20_ENV
91 #include <fstab.h>              /* Need to find in libc 5, present in libc 6 */
92 #endif
93 #endif
94 #endif /* AFS_SGI_ENV */
95 #endif
96 #endif /* AFS_HPUX_ENV */
97 #endif
98
99 #include "nfs.h"
100 #include <afs/errors.h>
101 #include "lock.h"
102 #include "lwp.h"
103 #include <afs/afssyscalls.h>
104 #include "ihandle.h"
105 #include <afs/afsutil.h>
106 #include "daemon_com.h"
107 #include "fssync.h"
108 #include "salvsync.h"
109 #include "vnode.h"
110 #include "volume.h"
111 #include "partition.h"
112 #include "volume_inline.h"
113 #include "common.h"
114 #include "vutils.h"
115 #include <afs/dir.h>
116
117 #ifdef AFS_PTHREAD_ENV
118 pthread_mutex_t vol_glock_mutex;
119 pthread_mutex_t vol_trans_mutex;
120 pthread_cond_t vol_put_volume_cond;
121 pthread_cond_t vol_sleep_cond;
122 pthread_cond_t vol_init_attach_cond;
123 pthread_cond_t vol_vinit_cond;
124 int vol_attach_threads = 1;
125 #endif /* AFS_PTHREAD_ENV */
126
127 /* start-time configurable I/O parameters */
128 ih_init_params vol_io_params;
129
130 #ifdef AFS_DEMAND_ATTACH_FS
131 pthread_mutex_t vol_salvsync_mutex;
132
133 /*
134  * Set this to 1 to disallow SALVSYNC communication in all threads; used
135  * during shutdown, since the salvageserver may have gone away.
136  */
137 static volatile sig_atomic_t vol_disallow_salvsync = 0;
138 #endif /* AFS_DEMAND_ATTACH_FS */
139
140 /**
141  * has VShutdown_r been called / is VShutdown_r running?
142  */
143 static int vol_shutting_down = 0;
144
145 #ifdef  AFS_OSF_ENV
146 extern void *calloc(), *realloc();
147 #endif
148
149 /* Forward declarations */
150 static Volume *attach2(Error * ec, VolumeId volumeId, char *path,
151                        struct DiskPartition64 *partp, Volume * vp,
152                        int isbusy, int mode, int *acheckedOut);
153 static void ReallyFreeVolume(Volume * vp);
154 #ifdef AFS_DEMAND_ATTACH_FS
155 static void FreeVolume(Volume * vp);
156 #else /* !AFS_DEMAND_ATTACH_FS */
157 #define FreeVolume(vp) ReallyFreeVolume(vp)
158 static void VScanUpdateList(void);
159 #endif /* !AFS_DEMAND_ATTACH_FS */
160 static void VInitVolumeHeaderCache(afs_uint32 howMany);
161 static int GetVolumeHeader(Volume * vp);
162 static void ReleaseVolumeHeader(struct volHeader *hd);
163 static void FreeVolumeHeader(Volume * vp);
164 static void AddVolumeToHashTable(Volume * vp, VolumeId hashid);
165 static void DeleteVolumeFromHashTable(Volume * vp);
166 #if 0
167 static int VHold(Volume * vp);
168 #endif
169 static int VHold_r(Volume * vp);
170 static void VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class);
171 static void VReleaseVolumeHandles_r(Volume * vp);
172 static void VCloseVolumeHandles_r(Volume * vp);
173 static void LoadVolumeHeader(Error * ec, Volume * vp);
174 static int VCheckOffline(Volume * vp);
175 static int VCheckDetach(Volume * vp);
176 static Volume * GetVolume(Error * ec, Error * client_ec, VolumeId volumeId,
177                           Volume * hint, const struct timespec *ts);
178
179 ProgramType programType;        /* The type of program using the package */
180 static VolumePackageOptions vol_opts;
181
182 /* extended volume package statistics */
183 VolPkgStats VStats;
184
185 #ifdef VOL_LOCK_DEBUG
186 pthread_t vol_glock_holder = 0;
187 #endif
188
189
190 /* this parameter needs to be tunable at runtime.
191  * 128 was really inadequate for largish servers -- at 16384 volumes this
192  * puts average chain length at 128, thus an average 65 deref's to find a volptr.
193  * talk about bad spatial locality...
194  *
195  * an AVL or splay tree might work a lot better, but we'll just increase
196  * the default hash table size for now
197  */
198 #define DEFAULT_VOLUME_HASH_BITS 10
199 #define DEFAULT_VOLUME_HASH_SIZE opr_jhash_size(DEFAULT_VOLUME_HASH_BITS)
200 #define DEFAULT_VOLUME_HASH_MASK opr_jhash_mask(DEFAULT_VOLUME_HASH_BITS)
201 #define VOLUME_HASH(volumeId) \
202     (opr_jhash_int(volumeId, 0) & VolumeHashTable.Mask)
203
204 /*
205  * turn volume hash chains into partially ordered lists.
206  * when the threshold is exceeded between two adjacent elements,
207  * perform a chain rebalancing operation.
208  *
209  * keep the threshold high in order to keep cache line invalidates
210  * low "enough" on SMPs
211  */
212 #define VOLUME_HASH_REORDER_THRESHOLD 200
213
214 /*
215  * when possible, don't just reorder single elements, but reorder
216  * entire chains of elements at once.  a chain of elements that
217  * exceed the element previous to the pivot by at least CHAIN_THRESH
218  * accesses are moved in front of the chain whose elements have at
219  * least CHAIN_THRESH less accesses than the pivot element
220  */
221 #define VOLUME_HASH_REORDER_CHAIN_THRESH (VOLUME_HASH_REORDER_THRESHOLD / 2)
222
223 /*
224  * The per volume uniquifier is bumped by 200 and and written to disk
225  * every 200 file creates.
226  */
227 #define VOLUME_UPDATE_UNIQUIFIER_BUMP 200
228
229 #include "rx/rx_queue.h"
230
231
232 VolumeHashTable_t VolumeHashTable = {
233     DEFAULT_VOLUME_HASH_SIZE,
234     DEFAULT_VOLUME_HASH_MASK,
235     NULL
236 };
237
238
239 static void VInitVolumeHash(void);
240
241
242 #ifdef AFS_PTHREAD_ENV
243 /**
244  * disk partition queue element
245  */
246 typedef struct diskpartition_queue_t {
247     struct rx_queue queue;             /**< queue header */
248     struct DiskPartition64 *diskP;     /**< disk partition table entry */
249 } diskpartition_queue_t;
250
251 #ifndef AFS_DEMAND_ATTACH_FS
252
253 typedef struct vinitvolumepackage_thread_t {
254     struct rx_queue queue;
255     pthread_cond_t thread_done_cv;
256     int n_threads_complete;
257 } vinitvolumepackage_thread_t;
258 static void * VInitVolumePackageThread(void * args);
259
260 #else  /* !AFS_DEMAND_ATTTACH_FS */
261 #define VINIT_BATCH_MAX_SIZE 512
262
263 /**
264  * disk partition work queue
265  */
266 struct partition_queue {
267     struct rx_queue head;              /**< diskpartition_queue_t queue */
268     pthread_mutex_t mutex;
269     pthread_cond_t cv;
270 };
271
272 /**
273  * volumes parameters for preattach
274  */
275 struct volume_init_batch {
276     struct rx_queue queue;               /**< queue header */
277     int thread;                          /**< posting worker thread */
278     int last;                            /**< indicates thread is done */
279     int size;                            /**< number of volume ids in batch */
280     Volume *batch[VINIT_BATCH_MAX_SIZE]; /**< volumes ids to preattach */
281 };
282
283 /**
284  * volume parameters work queue
285  */
286 struct volume_init_queue {
287     struct rx_queue head;                /**< volume_init_batch queue */
288     pthread_mutex_t mutex;
289     pthread_cond_t cv;
290 };
291
292 /**
293  * volume init worker thread parameters
294  */
295 struct vinitvolumepackage_thread_param {
296     int nthreads;                        /**< total number of worker threads */
297     int thread;                          /**< thread number for this worker thread */
298     struct partition_queue *pq;          /**< queue partitions to scan */
299     struct volume_init_queue *vq;        /**< queue of volume to preattach */
300 };
301
302 static void *VInitVolumePackageThread(void *args);
303 static struct DiskPartition64 *VInitNextPartition(struct partition_queue *pq);
304 static VolumeId VInitNextVolumeId(DIR *dirp);
305 static int VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq);
306
307 #endif /* !AFS_DEMAND_ATTACH_FS */
308 #endif /* AFS_PTHREAD_ENV */
309
310 #ifndef AFS_DEMAND_ATTACH_FS
311 static int VAttachVolumesByPartition(struct DiskPartition64 *diskP,
312                                      int * nAttached, int * nUnattached);
313 #endif /* AFS_DEMAND_ATTACH_FS */
314
315
316 #ifdef AFS_DEMAND_ATTACH_FS
317 /* demand attach fileserver extensions */
318
319 /* XXX
320  * in the future we will support serialization of VLRU state into the fs_state
321  * disk dumps
322  *
323  * these structures are the beginning of that effort
324  */
325 struct VLRU_DiskHeader {
326     struct versionStamp stamp;            /* magic and structure version number */
327     afs_uint32 mtime;                     /* time of dump to disk */
328     afs_uint32 num_records;               /* number of VLRU_DiskEntry records */
329 };
330
331 struct VLRU_DiskEntry {
332     VolumeId vid;                       /* volume ID */
333     afs_uint32 idx;                       /* generation */
334     afs_uint32 last_get;                  /* timestamp of last get */
335 };
336
337 struct VLRU_StartupQueue {
338     struct VLRU_DiskEntry * entry;
339     int num_entries;
340     int next_idx;
341 };
342
343 typedef struct vshutdown_thread_t {
344     struct rx_queue q;
345     pthread_mutex_t lock;
346     pthread_cond_t cv;
347     pthread_cond_t master_cv;
348     int n_threads;
349     int n_threads_complete;
350     int vol_remaining;
351     int schedule_version;
352     int pass;
353     byte n_parts;
354     byte n_parts_done_pass;
355     byte part_thread_target[VOLMAXPARTS+1];
356     byte part_done_pass[VOLMAXPARTS+1];
357     struct rx_queue * part_pass_head[VOLMAXPARTS+1];
358     int stats[4][VOLMAXPARTS+1];
359 } vshutdown_thread_t;
360 static void * VShutdownThread(void * args);
361
362
363 static Volume * VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode);
364 static int VCheckFree(Volume * vp);
365
366 /* VByP List */
367 static void AddVolumeToVByPList_r(Volume * vp);
368 static void DeleteVolumeFromVByPList_r(Volume * vp);
369 static void VVByPListBeginExclusive_r(struct DiskPartition64 * dp);
370 static void VVByPListEndExclusive_r(struct DiskPartition64 * dp);
371 static void VVByPListWait_r(struct DiskPartition64 * dp);
372
373 /* online salvager */
374 typedef enum {
375     VCHECK_SALVAGE_OK = 0,         /**< no pending salvage */
376     VCHECK_SALVAGE_SCHEDULED = 1,  /**< salvage has been scheduled */
377     VCHECK_SALVAGE_ASYNC = 2,      /**< salvage being scheduled */
378     VCHECK_SALVAGE_DENIED = 3,     /**< salvage not scheduled; denied */
379     VCHECK_SALVAGE_FAIL = 4        /**< salvage not scheduled; failed */
380 } vsalvage_check;
381 static int VCheckSalvage(Volume * vp);
382 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
383 static int VScheduleSalvage_r(Volume * vp);
384 #endif
385
386 /* Volume hash table */
387 static void VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp);
388 static void VHashBeginExclusive_r(VolumeHashChainHead * head);
389 static void VHashEndExclusive_r(VolumeHashChainHead * head);
390 static void VHashWait_r(VolumeHashChainHead * head);
391
392 /* shutdown */
393 static int ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass);
394 static int ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
395                                 struct rx_queue ** idx);
396 static void ShutdownController(vshutdown_thread_t * params);
397 static void ShutdownCreateSchedule(vshutdown_thread_t * params);
398
399 /* VLRU */
400 static void VLRU_ComputeConstants(void);
401 static void VInitVLRU(void);
402 static void VLRU_Init_Node_r(Volume * vp);
403 static void VLRU_Add_r(Volume * vp);
404 static void VLRU_Delete_r(Volume * vp);
405 static void VLRU_UpdateAccess_r(Volume * vp);
406 static void * VLRU_ScannerThread(void * args);
407 static void VLRU_Scan_r(int idx);
408 static void VLRU_Promote_r(int idx);
409 static void VLRU_Demote_r(int idx);
410 static void VLRU_SwitchQueues(Volume * vp, int new_idx, int append);
411
412 /* soft detach */
413 static int VCheckSoftDetach(Volume * vp, afs_uint32 thresh);
414 static int VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh);
415 static int VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh);
416
417
418 pthread_key_t VThread_key;
419 VThreadOptions_t VThread_defaults = {
420     0                           /**< allow salvsync */
421 };
422 #endif /* AFS_DEMAND_ATTACH_FS */
423
424
425 struct Lock vol_listLock;       /* Lock obtained when listing volumes:
426                                  * prevents a volume from being missed
427                                  * if the volume is attached during a
428                                  * list volumes */
429
430
431 /* Common message used when the volume goes off line */
432 char *VSalvageMessage =
433     "Files in this volume are currently unavailable; call operations";
434
435 int VInit;                      /* 0 - uninitialized,
436                                  * 1 - initialized but not all volumes have been attached,
437                                  * 2 - initialized and all volumes have been attached,
438                                  * 3 - initialized, all volumes have been attached, and
439                                  * VConnectFS() has completed. */
440
441 static int vinit_attach_abort = 0;
442
443 bit32 VolumeCacheCheck;         /* Incremented everytime a volume goes on line--
444                                  * used to stamp volume headers and in-core
445                                  * vnodes.  When the volume goes on-line the
446                                  * vnode will be invalidated
447                                  * access only with VOL_LOCK held */
448
449
450
451
452 /***************************************************/
453 /* Startup routines                                */
454 /***************************************************/
455
456 #if defined(FAST_RESTART) && defined(AFS_DEMAND_ATTACH_FS)
457 # error FAST_RESTART and DAFS are incompatible. For the DAFS equivalent \
458         of FAST_RESTART, use the -unsafe-nosalvage fileserver argument
459 #endif
460
461 /**
462  * assign default values to a VolumePackageOptions struct.
463  *
464  * Always call this on a VolumePackageOptions struct first, then set any
465  * specific options you want, then call VInitVolumePackage2.
466  *
467  * @param[in]  pt   caller's program type
468  * @param[out] opts volume package options
469  */
470 void
471 VOptDefaults(ProgramType pt, VolumePackageOptions *opts)
472 {
473     opts->nLargeVnodes = opts->nSmallVnodes = 5;
474     opts->volcache = 0;
475
476     opts->canScheduleSalvage = 0;
477     opts->canUseFSSYNC = 0;
478     opts->canUseSALVSYNC = 0;
479
480     opts->interrupt_rxcall = NULL;
481     opts->offline_timeout = -1;
482     opts->offline_shutdown_timeout = -1;
483     opts->usage_threshold = 128;
484     opts->usage_rate_limit = 5;
485
486 #ifdef FAST_RESTART
487     opts->unsafe_attach = 1;
488 #else /* !FAST_RESTART */
489     opts->unsafe_attach = 0;
490 #endif /* !FAST_RESTART */
491
492     switch (pt) {
493     case fileServer:
494         opts->canScheduleSalvage = 1;
495         opts->canUseSALVSYNC = 1;
496         break;
497
498     case salvageServer:
499         opts->canUseFSSYNC = 1;
500         break;
501
502     case volumeServer:
503         opts->nLargeVnodes = 0;
504         opts->nSmallVnodes = 0;
505
506         opts->canScheduleSalvage = 1;
507         opts->canUseFSSYNC = 1;
508         break;
509
510     default:
511         /* noop */
512         break;
513     }
514 }
515
516 /**
517  * Set VInit to a certain value, and signal waiters.
518  *
519  * @param[in] value  the value to set VInit to
520  *
521  * @pre VOL_LOCK held
522  */
523 static void
524 VSetVInit_r(int value)
525 {
526     VInit = value;
527     opr_cv_broadcast(&vol_vinit_cond);
528 }
529
530 static_inline void
531 VLogOfflineTimeout(const char *type, afs_int32 timeout)
532 {
533     if (timeout < 0) {
534         return;
535     }
536     if (timeout == 0) {
537         Log("VInitVolumePackage: Interrupting clients accessing %s "
538             "immediately\n", type);
539     } else {
540         Log("VInitVolumePackage: Interrupting clients accessing %s "
541             "after %ld second%s\n", type, (long)timeout, timeout==1?"":"s");
542     }
543 }
544
545 int
546 VInitVolumePackage2(ProgramType pt, VolumePackageOptions * opts)
547 {
548     int errors = 0;             /* Number of errors while finding vice partitions. */
549
550     programType = pt;
551     vol_opts = *opts;
552
553 #ifndef AFS_PTHREAD_ENV
554     if (opts->offline_timeout != -1 || opts->offline_shutdown_timeout != -1) {
555         Log("VInitVolumePackage: offline_timeout and/or "
556             "offline_shutdown_timeout was specified, but the volume package "
557             "does not support these for LWP builds\n");
558         return -1;
559     }
560 #endif
561     VLogOfflineTimeout("volumes going offline", opts->offline_timeout);
562     VLogOfflineTimeout("volumes going offline during shutdown",
563                        opts->offline_shutdown_timeout);
564
565     memset(&VStats, 0, sizeof(VStats));
566     VStats.hdr_cache_size = 200;
567
568     VInitPartitionPackage();
569     VInitVolumeHash();
570 #ifdef AFS_DEMAND_ATTACH_FS
571     if (programType == fileServer) {
572         VInitVLRU();
573     } else {
574         VLRU_SetOptions(VLRU_SET_ENABLED, 0);
575     }
576     opr_Verify(pthread_key_create(&VThread_key, NULL) == 0);
577 #endif
578
579     opr_mutex_init(&vol_glock_mutex);
580     opr_mutex_init(&vol_trans_mutex);
581     opr_cv_init(&vol_put_volume_cond);
582     opr_cv_init(&vol_sleep_cond);
583     opr_cv_init(&vol_init_attach_cond);
584     opr_cv_init(&vol_vinit_cond);
585 #ifndef AFS_PTHREAD_ENV
586     IOMGR_Initialize();
587 #endif /* AFS_PTHREAD_ENV */
588     Lock_Init(&vol_listLock);
589
590     srandom(time(0));           /* For VGetVolumeInfo */
591
592 #ifdef AFS_DEMAND_ATTACH_FS
593     opr_mutex_init(&vol_salvsync_mutex);
594 #endif /* AFS_DEMAND_ATTACH_FS */
595
596     /* Ok, we have done enough initialization that fileserver can
597      * start accepting calls, even though the volumes may not be
598      * available just yet.
599      */
600     VInit = 1;
601
602 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_SERVER)
603     if (programType == salvageServer) {
604         SALVSYNC_salvInit();
605     }
606 #endif /* AFS_DEMAND_ATTACH_FS */
607 #ifdef FSSYNC_BUILD_SERVER
608     if (programType == fileServer) {
609         FSYNC_fsInit();
610     }
611 #endif
612 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_CLIENT)
613     if (VCanUseSALVSYNC()) {
614         /* establish a connection to the salvager at this point */
615         opr_Verify(VConnectSALV() != 0);
616     }
617 #endif /* AFS_DEMAND_ATTACH_FS */
618
619     if (opts->volcache > VStats.hdr_cache_size)
620         VStats.hdr_cache_size = opts->volcache;
621     VInitVolumeHeaderCache(VStats.hdr_cache_size);
622
623     VInitVnodes(vLarge, opts->nLargeVnodes);
624     VInitVnodes(vSmall, opts->nSmallVnodes);
625
626
627     errors = VAttachPartitions();
628     if (errors)
629         return -1;
630
631     if (programType != fileServer) {
632         errors = VInitAttachVolumes(programType);
633         if (errors) {
634             return -1;
635         }
636     }
637
638 #ifdef FSSYNC_BUILD_CLIENT
639     if (VCanUseFSSYNC()) {
640         if (!VConnectFS()) {
641 #ifdef AFS_DEMAND_ATTACH_FS
642             if (programType == salvageServer) {
643                 Log("Unable to connect to file server; aborted\n");
644                 exit(1);
645             }
646 #endif /* AFS_DEMAND_ATTACH_FS */
647             Log("Unable to connect to file server; will retry at need\n");
648         }
649     }
650 #endif /* FSSYNC_BUILD_CLIENT */
651     return 0;
652 }
653
654
655 #if !defined(AFS_PTHREAD_ENV)
656 /**
657  * Attach volumes in vice partitions
658  *
659  * @param[in]  pt         calling program type
660  *
661  * @return 0
662  * @note This is the original, non-threaded version of attach parititions.
663  *
664  * @post VInit state is 2
665  */
666 int
667 VInitAttachVolumes(ProgramType pt)
668 {
669     opr_Assert(VInit==1);
670     if (pt == fileServer) {
671         struct DiskPartition64 *diskP;
672         /* Attach all the volumes in this partition */
673         for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
674             int nAttached = 0, nUnattached = 0;
675             opr_Verify(VAttachVolumesByPartition(diskP,
676                                                  &nAttached, &nUnattached)
677                             == 0);
678         }
679     }
680     VOL_LOCK;
681     VSetVInit_r(2);                     /* Initialized, and all volumes have been attached */
682     LWP_NoYieldSignal(VInitAttachVolumes);
683     VOL_UNLOCK;
684     return 0;
685 }
686 #endif /* !AFS_PTHREAD_ENV */
687
688 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_DEMAND_ATTACH_FS)
689 /**
690  * Attach volumes in vice partitions
691  *
692  * @param[in]  pt         calling program type
693  *
694  * @return 0
695  * @note Threaded version of attach parititions.
696  *
697  * @post VInit state is 2
698  */
699 int
700 VInitAttachVolumes(ProgramType pt)
701 {
702     opr_Assert(VInit==1);
703     if (pt == fileServer) {
704         struct DiskPartition64 *diskP;
705         struct vinitvolumepackage_thread_t params;
706         struct diskpartition_queue_t * dpq;
707         int i, threads, parts;
708         pthread_t tid;
709         pthread_attr_t attrs;
710
711         opr_cv_init(&params.thread_done_cv);
712         queue_Init(&params);
713         params.n_threads_complete = 0;
714
715         /* create partition work queue */
716         for (parts=0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
717             dpq = malloc(sizeof(struct diskpartition_queue_t));
718             opr_Assert(dpq != NULL);
719             dpq->diskP = diskP;
720             queue_Append(&params,dpq);
721         }
722
723         threads = min(parts, vol_attach_threads);
724
725         if (threads > 1) {
726             /* spawn off a bunch of initialization threads */
727             opr_Verify(pthread_attr_init(&attrs) == 0);
728             opr_Verify(pthread_attr_setdetachstate(&attrs,
729                                                    PTHREAD_CREATE_DETACHED)
730                             == 0);
731
732             Log("VInitVolumePackage: beginning parallel fileserver startup\n");
733             Log("VInitVolumePackage: using %d threads to attach volumes on %d partitions\n",
734                 threads, parts);
735
736             VOL_LOCK;
737             for (i=0; i < threads; i++) {
738                 AFS_SIGSET_DECL;
739                 AFS_SIGSET_CLEAR();
740                 opr_Verify(pthread_create(&tid, &attrs,
741                                           &VInitVolumePackageThread,
742                                           &params) == 0);
743                 AFS_SIGSET_RESTORE();
744             }
745
746             while(params.n_threads_complete < threads) {
747                 VOL_CV_WAIT(&params.thread_done_cv);
748             }
749             VOL_UNLOCK;
750
751             opr_Verify(pthread_attr_destroy(&attrs) == 0);
752         } else {
753             /* if we're only going to run one init thread, don't bother creating
754              * another LWP */
755             Log("VInitVolumePackage: beginning single-threaded fileserver startup\n");
756             Log("VInitVolumePackage: using 1 thread to attach volumes on %d partition(s)\n",
757                 parts);
758
759             VInitVolumePackageThread(&params);
760         }
761
762         opr_cv_destroy(&params.thread_done_cv);
763     }
764     VOL_LOCK;
765     VSetVInit_r(2);                     /* Initialized, and all volumes have been attached */
766     opr_cv_broadcast(&vol_init_attach_cond);
767     VOL_UNLOCK;
768     return 0;
769 }
770
771 static void *
772 VInitVolumePackageThread(void * args) {
773
774     struct DiskPartition64 *diskP;
775     struct vinitvolumepackage_thread_t * params;
776     struct diskpartition_queue_t * dpq;
777
778     params = (vinitvolumepackage_thread_t *) args;
779
780
781     VOL_LOCK;
782     /* Attach all the volumes in this partition */
783     while (queue_IsNotEmpty(params)) {
784         int nAttached = 0, nUnattached = 0;
785
786         if (vinit_attach_abort) {
787             Log("Aborting initialization\n");
788             goto done;
789         }
790
791         dpq = queue_First(params,diskpartition_queue_t);
792         queue_Remove(dpq);
793         VOL_UNLOCK;
794         diskP = dpq->diskP;
795         free(dpq);
796
797         opr_Verify(VAttachVolumesByPartition(diskP, &nAttached,
798                                              &nUnattached) == 0);
799
800         VOL_LOCK;
801     }
802
803 done:
804     params->n_threads_complete++;
805     opr_cv_signal(&params->thread_done_cv);
806     VOL_UNLOCK;
807     return NULL;
808 }
809 #endif /* AFS_PTHREAD_ENV && !AFS_DEMAND_ATTACH_FS */
810
811 #if defined(AFS_DEMAND_ATTACH_FS)
812 /**
813  * Attach volumes in vice partitions
814  *
815  * @param[in]  pt         calling program type
816  *
817  * @return 0
818  * @note Threaded version of attach partitions.
819  *
820  * @post VInit state is 2
821  */
822 int
823 VInitAttachVolumes(ProgramType pt)
824 {
825     opr_Assert(VInit==1);
826     if (pt == fileServer) {
827
828         struct DiskPartition64 *diskP;
829         struct partition_queue pq;
830         struct volume_init_queue vq;
831
832         int i, threads, parts;
833         pthread_t tid;
834         pthread_attr_t attrs;
835
836         /* create partition work queue */
837         queue_Init(&pq);
838         opr_cv_init(&pq.cv);
839         opr_mutex_init(&pq.mutex);
840         for (parts = 0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
841             struct diskpartition_queue_t *dp;
842             dp = malloc(sizeof(struct diskpartition_queue_t));
843             opr_Assert(dp != NULL);
844             dp->diskP = diskP;
845             queue_Append(&pq, dp);
846         }
847
848         /* number of worker threads; at least one, not to exceed the number of partitions */
849         threads = min(parts, vol_attach_threads);
850
851         /* create volume work queue */
852         queue_Init(&vq);
853         opr_cv_init(&vq.cv);
854         opr_mutex_init(&vq.mutex);
855
856         opr_Verify(pthread_attr_init(&attrs) == 0);
857         opr_Verify(pthread_attr_setdetachstate(&attrs,
858                                                PTHREAD_CREATE_DETACHED) == 0);
859
860         Log("VInitVolumePackage: beginning parallel fileserver startup\n");
861         Log("VInitVolumePackage: using %d threads to pre-attach volumes on %d partitions\n",
862                 threads, parts);
863
864         /* create threads to scan disk partitions. */
865         for (i=0; i < threads; i++) {
866             struct vinitvolumepackage_thread_param *params;
867             AFS_SIGSET_DECL;
868
869             params = malloc(sizeof(struct vinitvolumepackage_thread_param));
870             opr_Assert(params);
871             params->pq = &pq;
872             params->vq = &vq;
873             params->nthreads = threads;
874             params->thread = i+1;
875
876             AFS_SIGSET_CLEAR();
877             opr_Verify(pthread_create(&tid, &attrs,
878                                       &VInitVolumePackageThread,
879                                       (void*)params) == 0);
880             AFS_SIGSET_RESTORE();
881         }
882
883         VInitPreAttachVolumes(threads, &vq);
884
885         opr_Verify(pthread_attr_destroy(&attrs) == 0);
886         opr_cv_destroy(&pq.cv);
887         opr_mutex_destroy(&pq.mutex);
888         opr_cv_destroy(&vq.cv);
889         opr_mutex_destroy(&vq.mutex);
890     }
891
892     VOL_LOCK;
893     VSetVInit_r(2);                     /* Initialized, and all volumes have been attached */
894     opr_cv_broadcast(&vol_init_attach_cond);
895     VOL_UNLOCK;
896
897     return 0;
898 }
899
900 /**
901  * Volume package initialization worker thread. Scan partitions for volume
902  * header files. Gather batches of volume ids and dispatch them to
903  * the main thread to be preattached.  The volume preattachement is done
904  * in the main thread to avoid global volume lock contention.
905  */
906 static void *
907 VInitVolumePackageThread(void *args)
908 {
909     struct vinitvolumepackage_thread_param *params;
910     struct DiskPartition64 *partition;
911     struct partition_queue *pq;
912     struct volume_init_queue *vq;
913     struct volume_init_batch *vb;
914
915     opr_Assert(args);
916     params = (struct vinitvolumepackage_thread_param *)args;
917     pq = params->pq;
918     vq = params->vq;
919     opr_Assert(pq);
920     opr_Assert(vq);
921
922     vb = malloc(sizeof(struct volume_init_batch));
923     opr_Assert(vb);
924     vb->thread = params->thread;
925     vb->last = 0;
926     vb->size = 0;
927
928     Log("Scanning partitions on thread %d of %d\n", params->thread, params->nthreads);
929     while((partition = VInitNextPartition(pq))) {
930         DIR *dirp;
931         VolumeId vid;
932
933         Log("Partition %s: pre-attaching volumes\n", partition->name);
934         dirp = opendir(VPartitionPath(partition));
935         if (!dirp) {
936             Log("opendir on Partition %s failed, errno=%d!\n", partition->name, errno);
937             continue;
938         }
939         while ((vid = VInitNextVolumeId(dirp))) {
940             Volume *vp = calloc(1, sizeof(Volume));
941             opr_Assert(vp);
942             vp->device = partition->device;
943             vp->partition = partition;
944             vp->hashid = vid;
945             queue_Init(&vp->vnode_list);
946             queue_Init(&vp->rx_call_list);
947             opr_cv_init(&V_attachCV(vp));
948
949             vb->batch[vb->size++] = vp;
950             if (vb->size == VINIT_BATCH_MAX_SIZE) {
951                 opr_mutex_enter(&vq->mutex);
952                 queue_Append(vq, vb);
953                 opr_cv_broadcast(&vq->cv);
954                 opr_mutex_exit(&vq->mutex);
955
956                 vb = malloc(sizeof(struct volume_init_batch));
957                 opr_Assert(vb);
958                 vb->thread = params->thread;
959                 vb->size = 0;
960                 vb->last = 0;
961             }
962         }
963         closedir(dirp);
964     }
965
966     vb->last = 1;
967     opr_mutex_enter(&vq->mutex);
968     queue_Append(vq, vb);
969     opr_cv_broadcast(&vq->cv);
970     opr_mutex_exit(&vq->mutex);
971
972     Log("Partition scan thread %d of %d ended\n", params->thread, params->nthreads);
973     free(params);
974     return NULL;
975 }
976
977 /**
978  * Read next element from the pre-populated partition list.
979  */
980 static struct DiskPartition64*
981 VInitNextPartition(struct partition_queue *pq)
982 {
983     struct DiskPartition64 *partition;
984     struct diskpartition_queue_t *dp; /* queue element */
985
986     if (vinit_attach_abort) {
987         Log("Aborting volume preattach thread.\n");
988         return NULL;
989     }
990
991     /* get next partition to scan */
992     opr_mutex_enter(&pq->mutex);
993     if (queue_IsEmpty(pq)) {
994         opr_mutex_exit(&pq->mutex);
995         return NULL;
996     }
997     dp = queue_First(pq, diskpartition_queue_t);
998     queue_Remove(dp);
999     opr_mutex_exit(&pq->mutex);
1000
1001     opr_Assert(dp);
1002     opr_Assert(dp->diskP);
1003
1004     partition = dp->diskP;
1005     free(dp);
1006     return partition;
1007 }
1008
1009 /**
1010  * Find next volume id on the partition.
1011  */
1012 static VolumeId
1013 VInitNextVolumeId(DIR *dirp)
1014 {
1015     struct dirent *d;
1016     VolumeId vid = 0;
1017     char *ext;
1018
1019     while((d = readdir(dirp))) {
1020         if (vinit_attach_abort) {
1021             Log("Aborting volume preattach thread.\n");
1022             break;
1023         }
1024         ext = strrchr(d->d_name, '.');
1025         if (d->d_name[0] == 'V' && ext && strcmp(ext, VHDREXT) == 0) {
1026             vid = VolumeNumber(d->d_name);
1027             if (vid) {
1028                break;
1029             }
1030             Log("Warning: bogus volume header file: %s\n", d->d_name);
1031         }
1032     }
1033     return vid;
1034 }
1035
1036 /**
1037  * Preattach volumes in batches to avoid lock contention.
1038  */
1039 static int
1040 VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq)
1041 {
1042     struct volume_init_batch *vb;
1043     int i;
1044
1045     while (nthreads) {
1046         /* dequeue next volume */
1047         opr_mutex_enter(&vq->mutex);
1048         if (queue_IsEmpty(vq)) {
1049             opr_cv_wait(&vq->cv, &vq->mutex);
1050         }
1051         vb = queue_First(vq, volume_init_batch);
1052         queue_Remove(vb);
1053         opr_mutex_exit(&vq->mutex);
1054
1055         if (vb->size) {
1056             VOL_LOCK;
1057             for (i = 0; i<vb->size; i++) {
1058                 Volume *vp;
1059                 Volume *dup;
1060                 Error ec = 0;
1061
1062                 vp = vb->batch[i];
1063                 dup = VLookupVolume_r(&ec, vp->hashid, NULL);
1064                 if (ec) {
1065                     Log("Error looking up volume, code=%d\n", ec);
1066                 }
1067                 else if (dup) {
1068                     Log("Warning: Duplicate volume id %" AFS_VOLID_FMT " detected.\n", afs_printable_VolumeId_lu(vp->hashid));
1069                 }
1070                 else {
1071                     /* put pre-attached volume onto the hash table
1072                      * and bring it up to the pre-attached state */
1073                     AddVolumeToHashTable(vp, vp->hashid);
1074                     AddVolumeToVByPList_r(vp);
1075                     VLRU_Init_Node_r(vp);
1076                     VChangeState_r(vp, VOL_STATE_PREATTACHED);
1077                 }
1078             }
1079             VOL_UNLOCK;
1080         }
1081
1082         if (vb->last) {
1083             nthreads--;
1084         }
1085         free(vb);
1086     }
1087     return 0;
1088 }
1089 #endif /* AFS_DEMAND_ATTACH_FS */
1090
1091 #if !defined(AFS_DEMAND_ATTACH_FS)
1092 /*
1093  * attach all volumes on a given disk partition
1094  */
1095 static int
1096 VAttachVolumesByPartition(struct DiskPartition64 *diskP, int * nAttached, int * nUnattached)
1097 {
1098   DIR * dirp;
1099   struct dirent * dp;
1100   int ret = 0;
1101
1102   Log("Partition %s: attaching volumes\n", diskP->name);
1103   dirp = opendir(VPartitionPath(diskP));
1104   if (!dirp) {
1105     Log("opendir on Partition %s failed!\n", diskP->name);
1106     return 1;
1107   }
1108
1109   while ((dp = readdir(dirp))) {
1110     char *p;
1111     p = strrchr(dp->d_name, '.');
1112
1113     if (vinit_attach_abort) {
1114       Log("Partition %s: abort attach volumes\n", diskP->name);
1115       goto done;
1116     }
1117
1118     if (p != NULL && strcmp(p, VHDREXT) == 0) {
1119       Error error;
1120       Volume *vp;
1121       vp = VAttachVolumeByName(&error, diskP->name, dp->d_name,
1122                                V_VOLUPD);
1123       (*(vp ? nAttached : nUnattached))++;
1124       if (error == VOFFLINE)
1125         Log("Volume %d stays offline (/vice/offline/%s exists)\n", VolumeNumber(dp->d_name), dp->d_name);
1126       else if (GetLogLevel() >= 5) {
1127         Log("Partition %s: attached volume %d (%s)\n",
1128             diskP->name, VolumeNumber(dp->d_name),
1129             dp->d_name);
1130       }
1131       if (vp) {
1132         VPutVolume(vp);
1133       }
1134     }
1135   }
1136
1137   Log("Partition %s: attached %d volumes; %d volumes not attached\n", diskP->name, *nAttached, *nUnattached);
1138 done:
1139   closedir(dirp);
1140   return ret;
1141 }
1142 #endif /* !AFS_DEMAND_ATTACH_FS */
1143
1144 /***************************************************/
1145 /* Shutdown routines                               */
1146 /***************************************************/
1147
1148 /*
1149  * demand attach fs
1150  * highly multithreaded volume package shutdown
1151  *
1152  * with the demand attach fileserver extensions,
1153  * VShutdown has been modified to be multithreaded.
1154  * In order to achieve optimal use of many threads,
1155  * the shutdown code involves one control thread and
1156  * n shutdown worker threads.  The control thread
1157  * periodically examines the number of volumes available
1158  * for shutdown on each partition, and produces a worker
1159  * thread allocation schedule.  The idea is to eliminate
1160  * redundant scheduling computation on the workers by
1161  * having a single master scheduler.
1162  *
1163  * The scheduler's objectives are:
1164  * (1) fairness
1165  *   each partition with volumes remaining gets allocated
1166  *   at least 1 thread (assuming sufficient threads)
1167  * (2) performance
1168  *   threads are allocated proportional to the number of
1169  *   volumes remaining to be offlined.  This ensures that
1170  *   the OS I/O scheduler has many requests to elevator
1171  *   seek on partitions that will (presumably) take the
1172  *   longest amount of time (from now) to finish shutdown
1173  * (3) keep threads busy
1174  *   when there are extra threads, they are assigned to
1175  *   partitions using a simple round-robin algorithm
1176  *
1177  * In the future, we may wish to add the ability to adapt
1178  * to the relative performance patterns of each disk
1179  * partition.
1180  *
1181  *
1182  * demand attach fs
1183  * multi-step shutdown process
1184  *
1185  * demand attach shutdown is a four-step process. Each
1186  * shutdown "pass" shuts down increasingly more difficult
1187  * volumes.  The main purpose is to achieve better cache
1188  * utilization during shutdown.
1189  *
1190  * pass 0
1191  *   shutdown volumes in the unattached, pre-attached
1192  *   and error states
1193  * pass 1
1194  *   shutdown attached volumes with cached volume headers
1195  * pass 2
1196  *   shutdown all volumes in non-exclusive states
1197  * pass 3
1198  *   shutdown all remaining volumes
1199  */
1200
1201 #ifdef AFS_DEMAND_ATTACH_FS
1202
1203 void
1204 VShutdown_r(void)
1205 {
1206     int i;
1207     struct DiskPartition64 * diskP;
1208     struct diskpartition_queue_t * dpq;
1209     vshutdown_thread_t params;
1210     pthread_t tid;
1211     pthread_attr_t attrs;
1212
1213     memset(&params, 0, sizeof(vshutdown_thread_t));
1214
1215     if (VInit < 2) {
1216         Log("VShutdown:  aborting attach volumes\n");
1217         vinit_attach_abort = 1;
1218         VOL_CV_WAIT(&vol_init_attach_cond);
1219     }
1220
1221     for (params.n_parts=0, diskP = DiskPartitionList;
1222          diskP; diskP = diskP->next, params.n_parts++);
1223
1224     Log("VShutdown:  shutting down on-line volumes on %d partition%s...\n",
1225         params.n_parts, params.n_parts > 1 ? "s" : "");
1226
1227     vol_shutting_down = 1;
1228
1229     if (vol_attach_threads > 1) {
1230         /* prepare for parallel shutdown */
1231         params.n_threads = vol_attach_threads;
1232         opr_mutex_init(&params.lock);
1233         opr_cv_init(&params.cv);
1234         opr_cv_init(&params.master_cv);
1235         opr_Verify(pthread_attr_init(&attrs) == 0);
1236         opr_Verify(pthread_attr_setdetachstate(&attrs,
1237                                                PTHREAD_CREATE_DETACHED) == 0);
1238         queue_Init(&params);
1239
1240         /* setup the basic partition information structures for
1241          * parallel shutdown */
1242         for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1243             /* XXX debug */
1244             struct rx_queue * qp, * nqp;
1245             Volume * vp;
1246             int count = 0;
1247
1248             VVByPListWait_r(diskP);
1249             VVByPListBeginExclusive_r(diskP);
1250
1251             /* XXX debug */
1252             for (queue_Scan(&diskP->vol_list, qp, nqp, rx_queue)) {
1253                 vp = (Volume *)((char *)qp - offsetof(Volume, vol_list));
1254                 if (vp->header)
1255                     count++;
1256             }
1257             Log("VShutdown: partition %s has %d volumes with attached headers\n",
1258                 VPartitionPath(diskP), count);
1259
1260
1261             /* build up the pass 0 shutdown work queue */
1262             dpq = malloc(sizeof(struct diskpartition_queue_t));
1263             opr_Assert(dpq != NULL);
1264             dpq->diskP = diskP;
1265             queue_Prepend(&params, dpq);
1266
1267             params.part_pass_head[diskP->index] = queue_First(&diskP->vol_list, rx_queue);
1268         }
1269
1270         Log("VShutdown:  beginning parallel fileserver shutdown\n");
1271         Log("VShutdown:  using %d threads to offline volumes on %d partition%s\n",
1272             vol_attach_threads, params.n_parts, params.n_parts > 1 ? "s" : "" );
1273
1274         /* do pass 0 shutdown */
1275         opr_mutex_enter(&params.lock);
1276         for (i=0; i < params.n_threads; i++) {
1277             opr_Verify(pthread_create(&tid, &attrs, &VShutdownThread,
1278                                       &params) == 0);
1279         }
1280
1281         /* wait for all the pass 0 shutdowns to complete */
1282         while (params.n_threads_complete < params.n_threads) {
1283             CV_WAIT(&params.master_cv, &params.lock);
1284         }
1285         params.n_threads_complete = 0;
1286         params.pass = 1;
1287         opr_cv_broadcast(&params.cv);
1288         opr_mutex_exit(&params.lock);
1289
1290         Log("VShutdown:  pass 0 completed using the 1 thread per partition algorithm\n");
1291         Log("VShutdown:  starting passes 1 through 3 using finely-granular mp-fast algorithm\n");
1292
1293         /* run the parallel shutdown scheduler. it will drop the glock internally */
1294         ShutdownController(&params);
1295
1296         /* wait for all the workers to finish pass 3 and terminate */
1297         while (params.pass < 4) {
1298             VOL_CV_WAIT(&params.cv);
1299         }
1300
1301         opr_Verify(pthread_attr_destroy(&attrs) == 0);
1302         opr_cv_destroy(&params.cv);
1303         opr_cv_destroy(&params.master_cv);
1304         opr_mutex_destroy(&params.lock);
1305
1306         /* drop the VByPList exclusive reservations */
1307         for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1308             VVByPListEndExclusive_r(diskP);
1309             Log("VShutdown:  %s stats : (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1310                 VPartitionPath(diskP),
1311                 params.stats[0][diskP->index],
1312                 params.stats[1][diskP->index],
1313                 params.stats[2][diskP->index],
1314                 params.stats[3][diskP->index]);
1315         }
1316
1317         Log("VShutdown:  shutdown finished using %d threads\n", params.n_threads);
1318     } else {
1319         /* if we're only going to run one shutdown thread, don't bother creating
1320          * another LWP */
1321         Log("VShutdown:  beginning single-threaded fileserver shutdown\n");
1322
1323         for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1324             VShutdownByPartition_r(diskP);
1325         }
1326     }
1327
1328     Log("VShutdown:  complete.\n");
1329 }
1330
1331 #else /* AFS_DEMAND_ATTACH_FS */
1332
1333 void
1334 VShutdown_r(void)
1335 {
1336     int i;
1337     Volume *vp, *np;
1338     afs_int32 code;
1339
1340     if (VInit < 2) {
1341         Log("VShutdown:  aborting attach volumes\n");
1342         vinit_attach_abort = 1;
1343 #ifdef AFS_PTHREAD_ENV
1344         VOL_CV_WAIT(&vol_init_attach_cond);
1345 #else
1346         LWP_WaitProcess(VInitAttachVolumes);
1347 #endif /* AFS_PTHREAD_ENV */
1348     }
1349
1350     Log("VShutdown:  shutting down on-line volumes...\n");
1351     vol_shutting_down = 1;
1352     for (i = 0; i < VolumeHashTable.Size; i++) {
1353         /* try to hold first volume in the hash table */
1354         for (queue_Scan(&VolumeHashTable.Table[i],vp,np,Volume)) {
1355             code = VHold_r(vp);
1356             if (code == 0) {
1357                 if (GetLogLevel() >= 5)
1358                     Log("VShutdown:  Attempting to take volume %" AFS_VOLID_FMT " offline.\n",
1359                         afs_printable_VolumeId_lu(vp->hashid));
1360
1361                 /* next, take the volume offline (drops reference count) */
1362                 VOffline_r(vp, "File server was shut down");
1363             }
1364         }
1365     }
1366     Log("VShutdown:  complete.\n");
1367 }
1368 #endif /* AFS_DEMAND_ATTACH_FS */
1369
1370
1371 void
1372 VShutdown(void)
1373 {
1374     opr_Assert(VInit>0);
1375     VOL_LOCK;
1376     VShutdown_r();
1377     VOL_UNLOCK;
1378 }
1379
1380 /**
1381  * stop new activity (e.g. SALVSYNC) from occurring
1382  *
1383  * Use this to make the volume package less busy; for example, during
1384  * shutdown. This doesn't actually shutdown/detach anything in the
1385  * volume package, but prevents certain processes from ocurring. For
1386  * example, preventing new SALVSYNC communication in DAFS. In theory, we
1387  * could also use this to prevent new volume attachment, or prevent
1388  * other programs from checking out volumes, etc.
1389  */
1390 void
1391 VSetTranquil(void)
1392 {
1393 #ifdef AFS_DEMAND_ATTACH_FS
1394     /* make sure we don't try to contact the salvageserver, since it may
1395      * not be around anymore */
1396     vol_disallow_salvsync = 1;
1397 #endif
1398 }
1399
1400 #ifdef AFS_DEMAND_ATTACH_FS
1401 /*
1402  * demand attach fs
1403  * shutdown control thread
1404  */
1405 static void
1406 ShutdownController(vshutdown_thread_t * params)
1407 {
1408     /* XXX debug */
1409     struct DiskPartition64 * diskP;
1410     Device id;
1411     vshutdown_thread_t shadow;
1412
1413     ShutdownCreateSchedule(params);
1414
1415     while ((params->pass < 4) &&
1416            (params->n_threads_complete < params->n_threads)) {
1417         /* recompute schedule once per second */
1418
1419         memcpy(&shadow, params, sizeof(vshutdown_thread_t));
1420
1421         VOL_UNLOCK;
1422         /* XXX debug */
1423         Log("ShutdownController:  schedule version=%d, vol_remaining=%d, pass=%d\n",
1424             shadow.schedule_version, shadow.vol_remaining, shadow.pass);
1425         Log("ShutdownController:  n_threads_complete=%d, n_parts_done_pass=%d\n",
1426             shadow.n_threads_complete, shadow.n_parts_done_pass);
1427         for (diskP = DiskPartitionList; diskP; diskP=diskP->next) {
1428             id = diskP->index;
1429             Log("ShutdownController:  part[%d] : (len=%d, thread_target=%d, done_pass=%d, pass_head=%p)\n",
1430                 id,
1431                 diskP->vol_list.len,
1432                 shadow.part_thread_target[id],
1433                 shadow.part_done_pass[id],
1434                 shadow.part_pass_head[id]);
1435         }
1436
1437         sleep(1);
1438         VOL_LOCK;
1439
1440         ShutdownCreateSchedule(params);
1441     }
1442 }
1443
1444 /* create the shutdown thread work schedule.
1445  * this scheduler tries to implement fairness
1446  * by allocating at least 1 thread to each
1447  * partition with volumes to be shutdown,
1448  * and then it attempts to allocate remaining
1449  * threads based upon the amount of work left
1450  */
1451 static void
1452 ShutdownCreateSchedule(vshutdown_thread_t * params)
1453 {
1454     struct DiskPartition64 * diskP;
1455     int sum, thr_workload, thr_left;
1456     int part_residue[VOLMAXPARTS+1];
1457     Device id;
1458
1459     /* compute the total number of outstanding volumes */
1460     sum = 0;
1461     for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1462         sum += diskP->vol_list.len;
1463     }
1464
1465     params->schedule_version++;
1466     params->vol_remaining = sum;
1467
1468     if (!sum)
1469         return;
1470
1471     /* compute average per-thread workload */
1472     thr_workload = sum / params->n_threads;
1473     if (sum % params->n_threads)
1474         thr_workload++;
1475
1476     thr_left = params->n_threads;
1477     memset(&part_residue, 0, sizeof(part_residue));
1478
1479     /* for fairness, give every partition with volumes remaining
1480      * at least one thread */
1481     for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1482         id = diskP->index;
1483         if (diskP->vol_list.len) {
1484             params->part_thread_target[id] = 1;
1485             thr_left--;
1486         } else {
1487             params->part_thread_target[id] = 0;
1488         }
1489     }
1490
1491     if (thr_left && thr_workload) {
1492         /* compute length-weighted workloads */
1493         int delta;
1494
1495         for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1496             id = diskP->index;
1497             delta = (diskP->vol_list.len / thr_workload) -
1498                 params->part_thread_target[id];
1499             if (delta < 0) {
1500                 continue;
1501             }
1502             if (delta < thr_left) {
1503                 params->part_thread_target[id] += delta;
1504                 thr_left -= delta;
1505             } else {
1506                 params->part_thread_target[id] += thr_left;
1507                 thr_left = 0;
1508                 break;
1509             }
1510         }
1511     }
1512
1513     if (thr_left) {
1514         /* try to assign any leftover threads to partitions that
1515          * had volume lengths closer to needing thread_target+1 */
1516         int max_residue, max_id = 0;
1517
1518         /* compute the residues */
1519         for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1520             id = diskP->index;
1521             part_residue[id] = diskP->vol_list.len -
1522                 (params->part_thread_target[id] * thr_workload);
1523         }
1524
1525         /* now try to allocate remaining threads to partitions with the
1526          * highest residues */
1527         while (thr_left) {
1528             max_residue = 0;
1529             for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1530                 id = diskP->index;
1531                 if (part_residue[id] > max_residue) {
1532                     max_residue = part_residue[id];
1533                     max_id = id;
1534                 }
1535             }
1536
1537             if (!max_residue) {
1538                 break;
1539             }
1540
1541             params->part_thread_target[max_id]++;
1542             thr_left--;
1543             part_residue[max_id] = 0;
1544         }
1545     }
1546
1547     if (thr_left) {
1548         /* punt and give any remaining threads equally to each partition */
1549         int alloc;
1550         if (thr_left >= params->n_parts) {
1551             alloc = thr_left / params->n_parts;
1552             for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1553                 id = diskP->index;
1554                 params->part_thread_target[id] += alloc;
1555                 thr_left -= alloc;
1556             }
1557         }
1558
1559         /* finish off the last of the threads */
1560         for (diskP = DiskPartitionList; thr_left && diskP; diskP = diskP->next) {
1561             id = diskP->index;
1562             params->part_thread_target[id]++;
1563             thr_left--;
1564         }
1565     }
1566 }
1567
1568 /* worker thread for parallel shutdown */
1569 static void *
1570 VShutdownThread(void * args)
1571 {
1572     vshutdown_thread_t * params;
1573     int found, pass, schedule_version_save, count;
1574     struct DiskPartition64 *diskP;
1575     struct diskpartition_queue_t * dpq;
1576     Device id;
1577
1578     params = (vshutdown_thread_t *) args;
1579
1580     /* acquire the shutdown pass 0 lock */
1581     opr_mutex_enter(&params->lock);
1582
1583     /* if there's still pass 0 work to be done,
1584      * get a work entry, and do a pass 0 shutdown */
1585     if (queue_IsNotEmpty(params)) {
1586         dpq = queue_First(params, diskpartition_queue_t);
1587         queue_Remove(dpq);
1588         opr_mutex_exit(&params->lock);
1589         diskP = dpq->diskP;
1590         free(dpq);
1591         id = diskP->index;
1592
1593         count = 0;
1594         while (ShutdownVolumeWalk_r(diskP, 0, &params->part_pass_head[id]))
1595             count++;
1596         params->stats[0][diskP->index] = count;
1597         opr_mutex_enter(&params->lock);
1598     }
1599
1600     params->n_threads_complete++;
1601     if (params->n_threads_complete == params->n_threads) {
1602         /* notify control thread that all workers have completed pass 0 */
1603         opr_cv_signal(&params->master_cv);
1604     }
1605     while (params->pass == 0) {
1606         opr_cv_wait(&params->cv, &params->lock);
1607     }
1608
1609     /* switch locks */
1610     opr_mutex_exit(&params->lock);
1611     VOL_LOCK;
1612
1613     pass = params->pass;
1614     opr_Assert(pass > 0);
1615
1616     /* now escalate through the more complicated shutdowns */
1617     while (pass <= 3) {
1618         schedule_version_save = params->schedule_version;
1619         found = 0;
1620         /* find a disk partition to work on */
1621         for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1622             id = diskP->index;
1623             if (params->part_thread_target[id] && !params->part_done_pass[id]) {
1624                 params->part_thread_target[id]--;
1625                 found = 1;
1626                 break;
1627             }
1628         }
1629
1630         if (!found) {
1631             /* hmm. for some reason the controller thread couldn't find anything for
1632              * us to do. let's see if there's anything we can do */
1633             for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1634                 id = diskP->index;
1635                 if (diskP->vol_list.len && !params->part_done_pass[id]) {
1636                     found = 1;
1637                     break;
1638                 } else if (!params->part_done_pass[id]) {
1639                     params->part_done_pass[id] = 1;
1640                     params->n_parts_done_pass++;
1641                     if (pass == 3) {
1642                         Log("VShutdown:  done shutting down volumes on partition %s.\n",
1643                             VPartitionPath(diskP));
1644                     }
1645                 }
1646             }
1647         }
1648
1649         /* do work on this partition until either the controller
1650          * creates a new schedule, or we run out of things to do
1651          * on this partition */
1652         if (found) {
1653             count = 0;
1654             while (!params->part_done_pass[id] &&
1655                    (schedule_version_save == params->schedule_version)) {
1656                 /* ShutdownVolumeWalk_r will drop the glock internally */
1657                 if (!ShutdownVolumeWalk_r(diskP, pass, &params->part_pass_head[id])) {
1658                     if (!params->part_done_pass[id]) {
1659                         params->part_done_pass[id] = 1;
1660                         params->n_parts_done_pass++;
1661                         if (pass == 3) {
1662                             Log("VShutdown:  done shutting down volumes on partition %s.\n",
1663                                 VPartitionPath(diskP));
1664                         }
1665                     }
1666                     break;
1667                 }
1668                 count++;
1669             }
1670
1671             params->stats[pass][id] += count;
1672         } else {
1673             /* ok, everyone is done this pass, proceed */
1674
1675             /* barrier lock */
1676             params->n_threads_complete++;
1677             while (params->pass == pass) {
1678                 if (params->n_threads_complete == params->n_threads) {
1679                     /* we are the last thread to complete, so we will
1680                      * reinitialize worker pool state for the next pass */
1681                     params->n_threads_complete = 0;
1682                     params->n_parts_done_pass = 0;
1683                     params->pass++;
1684                     for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1685                         id = diskP->index;
1686                         params->part_done_pass[id] = 0;
1687                         params->part_pass_head[id] = queue_First(&diskP->vol_list, rx_queue);
1688                     }
1689
1690                     /* compute a new thread schedule before releasing all the workers */
1691                     ShutdownCreateSchedule(params);
1692
1693                     /* wake up all the workers */
1694                     opr_cv_broadcast(&params->cv);
1695
1696                     VOL_UNLOCK;
1697                     Log("VShutdown:  pass %d completed using %d threads on %d partitions\n",
1698                         pass, params->n_threads, params->n_parts);
1699                     VOL_LOCK;
1700                 } else {
1701                     VOL_CV_WAIT(&params->cv);
1702                 }
1703             }
1704             pass = params->pass;
1705         }
1706
1707         /* for fairness */
1708         VOL_UNLOCK;
1709         pthread_yield();
1710         VOL_LOCK;
1711     }
1712
1713     VOL_UNLOCK;
1714
1715     return NULL;
1716 }
1717
1718 /* shut down all volumes on a given disk partition
1719  *
1720  * note that this function will not allow mp-fast
1721  * shutdown of a partition */
1722 int
1723 VShutdownByPartition_r(struct DiskPartition64 * dp)
1724 {
1725     int pass;
1726     int pass_stats[4];
1727     int total;
1728
1729     /* wait for other exclusive ops to finish */
1730     VVByPListWait_r(dp);
1731
1732     /* begin exclusive access */
1733     VVByPListBeginExclusive_r(dp);
1734
1735     /* pick the low-hanging fruit first,
1736      * then do the complicated ones last
1737      * (has the advantage of keeping
1738      *  in-use volumes up until the bitter end) */
1739     for (pass = 0, total=0; pass < 4; pass++) {
1740         pass_stats[pass] = ShutdownVByPForPass_r(dp, pass);
1741         total += pass_stats[pass];
1742     }
1743
1744     /* end exclusive access */
1745     VVByPListEndExclusive_r(dp);
1746
1747     Log("VShutdownByPartition:  shut down %d volumes on %s (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1748         total, VPartitionPath(dp), pass_stats[0], pass_stats[1], pass_stats[2], pass_stats[3]);
1749
1750     return 0;
1751 }
1752
1753 /* internal shutdown functionality
1754  *
1755  * for multi-pass shutdown:
1756  * 0 to only "shutdown" {pre,un}attached and error state volumes
1757  * 1 to also shutdown attached volumes w/ volume header loaded
1758  * 2 to also shutdown attached volumes w/o volume header loaded
1759  * 3 to also shutdown exclusive state volumes
1760  *
1761  * caller MUST hold exclusive access on the hash chain
1762  * because we drop vol_glock_mutex internally
1763  *
1764  * this function is reentrant for passes 1--3
1765  * (e.g. multiple threads can cooperate to
1766  *  shutdown a partition mp-fast)
1767  *
1768  * pass 0 is not scaleable because the volume state data is
1769  * synchronized by vol_glock mutex, and the locking overhead
1770  * is too high to drop the lock long enough to do linked list
1771  * traversal
1772  */
1773 static int
1774 ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass)
1775 {
1776     struct rx_queue * q = queue_First(&dp->vol_list, rx_queue);
1777     int i = 0;
1778     const char *pass_strs[4] = {"{un/pre}attached vols", "vols w/ vol header loaded", "vols w/o vol header loaded", "vols with exclusive state"};
1779
1780     while (ShutdownVolumeWalk_r(dp, pass, &q)) {
1781         i++;
1782         if (0 == i%100) {
1783             Log("VShutdownByPartition:  ... shut down %d volumes on %s in pass %d (%s)\n", i, VPartitionPath(dp), pass, pass_strs[pass]);
1784         }
1785     }
1786
1787     return i;
1788 }
1789
1790 /* conditionally shutdown one volume on partition dp
1791  * returns 1 if a volume was shutdown in this pass,
1792  * 0 otherwise */
1793 static int
1794 ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
1795                      struct rx_queue ** idx)
1796 {
1797     struct rx_queue *qp, *nqp;
1798     Volume * vp;
1799
1800     qp = *idx;
1801
1802     for (queue_ScanFrom(&dp->vol_list, qp, qp, nqp, rx_queue)) {
1803         vp = (Volume *) (((char *)qp) - offsetof(Volume, vol_list));
1804
1805         switch (pass) {
1806         case 0:
1807             if ((V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1808                 (V_attachState(vp) != VOL_STATE_ERROR) &&
1809                 (V_attachState(vp) != VOL_STATE_DELETED) &&
1810                 (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1811                 break;
1812             }
1813         case 1:
1814             if ((V_attachState(vp) == VOL_STATE_ATTACHED) &&
1815                 (vp->header == NULL)) {
1816                 break;
1817             }
1818         case 2:
1819             if (VIsExclusiveState(V_attachState(vp))) {
1820                 break;
1821             }
1822         case 3:
1823             *idx = nqp;
1824             DeleteVolumeFromVByPList_r(vp);
1825             VShutdownVolume_r(vp);
1826             vp = NULL;
1827             return 1;
1828         }
1829     }
1830
1831     return 0;
1832 }
1833
1834 /*
1835  * shutdown a specific volume
1836  */
1837 /* caller MUST NOT hold a heavyweight ref on vp */
1838 int
1839 VShutdownVolume_r(Volume * vp)
1840 {
1841     int code;
1842
1843     VCreateReservation_r(vp);
1844
1845     if (GetLogLevel() >= 5) {
1846         Log("VShutdownVolume_r:  vid=%" AFS_VOLID_FMT ", device=%d, state=%u\n",
1847             afs_printable_VolumeId_lu(vp->hashid), vp->partition->device,
1848             (unsigned int) V_attachState(vp));
1849     }
1850
1851     /* wait for other blocking ops to finish */
1852     VWaitExclusiveState_r(vp);
1853
1854     opr_Assert(VIsValidState(V_attachState(vp)));
1855
1856     switch(V_attachState(vp)) {
1857     case VOL_STATE_SALVAGING:
1858         /* Leave salvaging volumes alone. Any in-progress salvages will
1859          * continue working after viced shuts down. This is intentional.
1860          */
1861
1862     case VOL_STATE_PREATTACHED:
1863     case VOL_STATE_ERROR:
1864         VChangeState_r(vp, VOL_STATE_UNATTACHED);
1865     case VOL_STATE_UNATTACHED:
1866     case VOL_STATE_DELETED:
1867         break;
1868     case VOL_STATE_GOING_OFFLINE:
1869     case VOL_STATE_SHUTTING_DOWN:
1870     case VOL_STATE_ATTACHED:
1871         code = VHold_r(vp);
1872         if (!code) {
1873             if (GetLogLevel() >= 5)
1874                 Log("VShutdown:  Attempting to take volume %" AFS_VOLID_FMT " offline.\n",
1875                     afs_printable_VolumeId_lu(vp->hashid));
1876
1877             /* take the volume offline (drops reference count) */
1878             VOffline_r(vp, "File server was shut down");
1879         }
1880         break;
1881     default:
1882         break;
1883     }
1884
1885     VCancelReservation_r(vp);
1886     vp = NULL;
1887     return 0;
1888 }
1889 #endif /* AFS_DEMAND_ATTACH_FS */
1890
1891
1892 /***************************************************/
1893 /* Header I/O routines                             */
1894 /***************************************************/
1895
1896 static const char *
1897 HeaderName(bit32 magic)
1898 {
1899     switch (magic) {
1900     case VOLUMEINFOMAGIC:
1901         return "volume info";
1902     case SMALLINDEXMAGIC:
1903         return "small index";
1904     case LARGEINDEXMAGIC:
1905         return "large index";
1906     case LINKTABLEMAGIC:
1907         return "link table";
1908     }
1909     return "unknown";
1910 }
1911
1912 /* open a descriptor for the inode (h),
1913  * read in an on-disk structure into buffer (to) of size (size),
1914  * verify versionstamp in structure has magic (magic) and
1915  * optionally verify version (version) if (version) is nonzero
1916  */
1917 static void
1918 ReadHeader(Error * ec, IHandle_t * h, char *to, int size, bit32 magic,
1919            bit32 version)
1920 {
1921     struct versionStamp *vsn;
1922     FdHandle_t *fdP;
1923     afs_sfsize_t nbytes;
1924     afs_ino_str_t stmp;
1925
1926     *ec = 0;
1927     if (h == NULL) {
1928         Log("ReadHeader: Null inode handle argument for %s header file.\n",
1929             HeaderName(magic));
1930         *ec = VSALVAGE;
1931         return;
1932     }
1933
1934     fdP = IH_OPEN(h);
1935     if (fdP == NULL) {
1936         Log("ReadHeader: Failed to open %s header file "
1937             "(volume=%" AFS_VOLID_FMT ", inode=%s); errno=%d\n", HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid),
1938             PrintInode(stmp, h->ih_ino), errno);
1939         *ec = VSALVAGE;
1940         return;
1941     }
1942
1943     vsn = (struct versionStamp *)to;
1944     nbytes = FDH_PREAD(fdP, to, size, 0);
1945     if (nbytes < 0) {
1946         Log("ReadHeader: Failed to read %s header file "
1947             "(volume=%" AFS_VOLID_FMT ", inode=%s); errno=%d\n", HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid),
1948             PrintInode(stmp, h->ih_ino), errno);
1949         *ec = VSALVAGE;
1950         FDH_REALLYCLOSE(fdP);
1951         return;
1952     }
1953     if (nbytes != size) {
1954         Log("ReadHeader: Incorrect number of bytes read from %s header file "
1955             "(volume=%" AFS_VOLID_FMT ", inode=%s); expected=%d, read=%d\n",
1956             HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid), 
1957             PrintInode(stmp, h->ih_ino), size, (int)nbytes);
1958         *ec = VSALVAGE;
1959         FDH_REALLYCLOSE(fdP);
1960         return;
1961     }
1962     if (vsn->magic != magic) {
1963         Log("ReadHeader: Incorrect magic for %s header file "
1964             "(volume=%" AFS_VOLID_FMT ", inode=%s); expected=0x%x, read=0x%x\n",
1965             HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid),
1966             PrintInode(stmp, h->ih_ino), magic, vsn->magic);
1967         *ec = VSALVAGE;
1968         FDH_REALLYCLOSE(fdP);
1969         return;
1970     }
1971
1972     FDH_CLOSE(fdP);
1973
1974     /* Check is conditional, in case caller wants to inspect version himself */
1975     if (version && vsn->version != version) {
1976         Log("ReadHeader: Incorrect version for %s header file "
1977             "(volume=%" AFS_VOLID_FMT ", inode=%s); expected=%x, read=%x\n",
1978             HeaderName(magic), afs_printable_VolumeId_lu(h->ih_vid), PrintInode(stmp, h->ih_ino),
1979             version, vsn->version);
1980         *ec = VSALVAGE;
1981     }
1982 }
1983
1984 void
1985 WriteVolumeHeader_r(Error * ec, Volume * vp)
1986 {
1987     IHandle_t *h = V_diskDataHandle(vp);
1988     FdHandle_t *fdP;
1989
1990     *ec = 0;
1991
1992     fdP = IH_OPEN(h);
1993     if (fdP == NULL) {
1994         *ec = VSALVAGE;
1995         return;
1996     }
1997     if (FDH_PWRITE(fdP, (char *)&V_disk(vp), sizeof(V_disk(vp)), 0)
1998         != sizeof(V_disk(vp))) {
1999         *ec = VSALVAGE;
2000         FDH_REALLYCLOSE(fdP);
2001         return;
2002     }
2003     FDH_CLOSE(fdP);
2004 }
2005
2006 /* VolumeHeaderToDisk
2007  * Allows for storing 64 bit inode numbers in on-disk volume header
2008  * file.
2009  */
2010 /* convert in-memory representation of a volume header to the
2011  * on-disk representation of a volume header */
2012 void
2013 VolumeHeaderToDisk(VolumeDiskHeader_t * dh, VolumeHeader_t * h)
2014 {
2015
2016     memset(dh, 0, sizeof(VolumeDiskHeader_t));
2017     dh->stamp = h->stamp;
2018     dh->id = h->id;
2019     dh->parent = h->parent;
2020
2021 #ifdef AFS_64BIT_IOPS_ENV
2022     dh->volumeInfo_lo = (afs_int32) h->volumeInfo & 0xffffffff;
2023     dh->volumeInfo_hi = (afs_int32) (h->volumeInfo >> 32) & 0xffffffff;
2024     dh->smallVnodeIndex_lo = (afs_int32) h->smallVnodeIndex & 0xffffffff;
2025     dh->smallVnodeIndex_hi =
2026         (afs_int32) (h->smallVnodeIndex >> 32) & 0xffffffff;
2027     dh->largeVnodeIndex_lo = (afs_int32) h->largeVnodeIndex & 0xffffffff;
2028     dh->largeVnodeIndex_hi =
2029         (afs_int32) (h->largeVnodeIndex >> 32) & 0xffffffff;
2030     dh->linkTable_lo = (afs_int32) h->linkTable & 0xffffffff;
2031     dh->linkTable_hi = (afs_int32) (h->linkTable >> 32) & 0xffffffff;
2032 #else
2033     dh->volumeInfo_lo = h->volumeInfo;
2034     dh->smallVnodeIndex_lo = h->smallVnodeIndex;
2035     dh->largeVnodeIndex_lo = h->largeVnodeIndex;
2036     dh->linkTable_lo = h->linkTable;
2037 #endif
2038 }
2039
2040 /* DiskToVolumeHeader
2041  * Converts an on-disk representation of a volume header to
2042  * the in-memory representation of a volume header.
2043  *
2044  * Makes the assumption that AFS has *always*
2045  * zero'd the volume header file so that high parts of inode
2046  * numbers are 0 in older (SGI EFS) volume header files.
2047  */
2048 void
2049 DiskToVolumeHeader(VolumeHeader_t * h, VolumeDiskHeader_t * dh)
2050 {
2051     memset(h, 0, sizeof(VolumeHeader_t));
2052     h->stamp = dh->stamp;
2053     h->id = dh->id;
2054     h->parent = dh->parent;
2055
2056 #ifdef AFS_64BIT_IOPS_ENV
2057     h->volumeInfo =
2058         (Inode) dh->volumeInfo_lo | ((Inode) dh->volumeInfo_hi << 32);
2059
2060     h->smallVnodeIndex =
2061         (Inode) dh->smallVnodeIndex_lo | ((Inode) dh->
2062                                           smallVnodeIndex_hi << 32);
2063
2064     h->largeVnodeIndex =
2065         (Inode) dh->largeVnodeIndex_lo | ((Inode) dh->
2066                                           largeVnodeIndex_hi << 32);
2067     h->linkTable =
2068         (Inode) dh->linkTable_lo | ((Inode) dh->linkTable_hi << 32);
2069 #else
2070     h->volumeInfo = dh->volumeInfo_lo;
2071     h->smallVnodeIndex = dh->smallVnodeIndex_lo;
2072     h->largeVnodeIndex = dh->largeVnodeIndex_lo;
2073     h->linkTable = dh->linkTable_lo;
2074 #endif
2075 }
2076
2077
2078 /***************************************************/
2079 /* Volume Attachment routines                      */
2080 /***************************************************/
2081
2082 #ifdef AFS_DEMAND_ATTACH_FS
2083 /**
2084  * pre-attach a volume given its path.
2085  *
2086  * @param[out] ec         outbound error code
2087  * @param[in]  partition  partition path string
2088  * @param[in]  name       volume id string
2089  *
2090  * @return volume object pointer
2091  *
2092  * @note A pre-attached volume will only have its partition
2093  *       and hashid fields initialized.  At first call to
2094  *       VGetVolume, the volume will be fully attached.
2095  *
2096  */
2097 Volume *
2098 VPreAttachVolumeByName(Error * ec, char *partition, char *name)
2099 {
2100     Volume * vp;
2101     VOL_LOCK;
2102     vp = VPreAttachVolumeByName_r(ec, partition, name);
2103     VOL_UNLOCK;
2104     return vp;
2105 }
2106
2107 /**
2108  * pre-attach a volume given its path.
2109  *
2110  * @param[out] ec         outbound error code
2111  * @param[in]  partition  path to vice partition
2112  * @param[in]  name       volume id string
2113  *
2114  * @return volume object pointer
2115  *
2116  * @pre VOL_LOCK held
2117  *
2118  * @internal volume package internal use only.
2119  */
2120 Volume *
2121 VPreAttachVolumeByName_r(Error * ec, char *partition, char *name)
2122 {
2123     return VPreAttachVolumeById_r(ec,
2124                                   partition,
2125                                   VolumeNumber(name));
2126 }
2127
2128 /**
2129  * pre-attach a volume given its path and numeric volume id.
2130  *
2131  * @param[out] ec          error code return
2132  * @param[in]  partition   path to vice partition
2133  * @param[in]  volumeId    numeric volume id
2134  *
2135  * @return volume object pointer
2136  *
2137  * @pre VOL_LOCK held
2138  *
2139  * @internal volume package internal use only.
2140  */
2141 Volume *
2142 VPreAttachVolumeById_r(Error * ec,
2143                        char * partition,
2144                        VolumeId volumeId)
2145 {
2146     Volume *vp;
2147     struct DiskPartition64 *partp;
2148
2149     *ec = 0;
2150
2151     opr_Assert(programType == fileServer);
2152
2153     if (!(partp = VGetPartition_r(partition, 0))) {
2154         *ec = VNOVOL;
2155         Log("VPreAttachVolumeById_r:  Error getting partition (%s)\n", partition);
2156         return NULL;
2157     }
2158
2159     /* ensure that any vp we pass to VPreAttachVolumeByVp_r
2160      * is NOT in exclusive state.
2161      */
2162  retry:
2163     vp = VLookupVolume_r(ec, volumeId, NULL);
2164
2165     if (*ec) {
2166         return NULL;
2167     }
2168
2169     if (vp && VIsExclusiveState(V_attachState(vp))) {
2170         VCreateReservation_r(vp);
2171         VWaitExclusiveState_r(vp);
2172         VCancelReservation_r(vp);
2173         vp = NULL;
2174         goto retry;    /* look up volume again */
2175     }
2176
2177     /* vp == NULL or vp not exclusive both OK */
2178
2179     return VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2180 }
2181
2182 /**
2183  * preattach a volume.
2184  *
2185  * @param[out] ec     outbound error code
2186  * @param[in]  partp  pointer to partition object
2187  * @param[in]  vp     pointer to volume object
2188  * @param[in]  vid    volume id
2189  *
2190  * @return volume object pointer
2191  *
2192  * @pre VOL_LOCK is held.
2193  *
2194  * @pre vp (if specified) must not be in exclusive state.
2195  *
2196  * @warning Returned volume object pointer does not have to
2197  *          equal the pointer passed in as argument vp.  There
2198  *          are potential race conditions which can result in
2199  *          the pointers having different values.  It is up to
2200  *          the caller to make sure that references are handled
2201  *          properly in this case.
2202  *
2203  * @note If there is already a volume object registered with
2204  *       the same volume id, its pointer MUST be passed as
2205  *       argument vp.  Failure to do so will result in a silent
2206  *       failure to preattach.
2207  *
2208  * @internal volume package internal use only.
2209  */
2210 Volume *
2211 VPreAttachVolumeByVp_r(Error * ec,
2212                        struct DiskPartition64 * partp,
2213                        Volume * vp,
2214                        VolumeId vid)
2215 {
2216     Volume *nvp = NULL;
2217
2218     *ec = 0;
2219
2220     /* don't proceed unless it's safe */
2221     if (vp) {
2222         opr_Assert(!VIsExclusiveState(V_attachState(vp)));
2223     }
2224
2225     /* check to see if pre-attach already happened */
2226     if (vp &&
2227         (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
2228         (V_attachState(vp) != VOL_STATE_DELETED) &&
2229         (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
2230         !VIsErrorState(V_attachState(vp))) {
2231         /*
2232          * pre-attach is a no-op in all but the following cases:
2233          *
2234          *   - volume is unattached
2235          *   - volume is in an error state
2236          *   - volume is pre-attached
2237          */
2238         Log("VPreattachVolumeByVp_r: volume %" AFS_VOLID_FMT " not in quiescent state (state %u flags 0x%x)\n",
2239             afs_printable_VolumeId_lu(vid), V_attachState(vp),
2240             V_attachFlags(vp));
2241         goto done;
2242     } else if (vp) {
2243         /* we're re-attaching a volume; clear out some old state */
2244         memset(&vp->salvage, 0, sizeof(struct VolumeOnlineSalvage));
2245
2246         if (V_partition(vp) != partp) {
2247             /* XXX potential race */
2248             DeleteVolumeFromVByPList_r(vp);
2249         }
2250     } else {
2251         /* if we need to allocate a new Volume struct,
2252          * go ahead and drop the vol glock, otherwise
2253          * do the basic setup synchronised, as it's
2254          * probably not worth dropping the lock */
2255         VOL_UNLOCK;
2256
2257         /* allocate the volume structure */
2258         vp = nvp = calloc(1, sizeof(Volume));
2259         opr_Assert(vp != NULL);
2260         queue_Init(&vp->vnode_list);
2261         queue_Init(&vp->rx_call_list);
2262         opr_cv_init(&V_attachCV(vp));
2263     }
2264
2265     /* link the volume with its associated vice partition */
2266     vp->device = partp->device;
2267     vp->partition = partp;
2268
2269     vp->hashid = vid;
2270     vp->specialStatus = 0;
2271
2272     /* if we dropped the lock, reacquire the lock,
2273      * check for pre-attach races, and then add
2274      * the volume to the hash table */
2275     if (nvp) {
2276         VOL_LOCK;
2277         nvp = VLookupVolume_r(ec, vid, NULL);
2278         if (*ec) {
2279             free(vp);
2280             vp = NULL;
2281             goto done;
2282         } else if (nvp) { /* race detected */
2283             free(vp);
2284             vp = nvp;
2285             goto done;
2286         } else {
2287           /* hack to make up for VChangeState_r() decrementing
2288            * the old state counter */
2289           VStats.state_levels[0]++;
2290         }
2291     }
2292
2293     /* put pre-attached volume onto the hash table
2294      * and bring it up to the pre-attached state */
2295     AddVolumeToHashTable(vp, vp->hashid);
2296     AddVolumeToVByPList_r(vp);
2297     VLRU_Init_Node_r(vp);
2298     VChangeState_r(vp, VOL_STATE_PREATTACHED);
2299
2300     if (GetLogLevel() >= 5)
2301         Log("VPreAttachVolumeByVp_r:  volume %" AFS_VOLID_FMT " pre-attached\n", afs_printable_VolumeId_lu(vp->hashid));
2302
2303   done:
2304     if (*ec)
2305         return NULL;
2306     else
2307         return vp;
2308 }
2309 #endif /* AFS_DEMAND_ATTACH_FS */
2310
2311 /* Attach an existing volume, given its pathname, and return a
2312    pointer to the volume header information.  The volume also
2313    normally goes online at this time.  An offline volume
2314    must be reattached to make it go online */
2315 Volume *
2316 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
2317 {
2318     Volume *retVal;
2319     VOL_LOCK;
2320     retVal = VAttachVolumeByName_r(ec, partition, name, mode);
2321     VOL_UNLOCK;
2322     return retVal;
2323 }
2324
2325 Volume *
2326 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
2327 {
2328     Volume *vp = NULL;
2329     struct DiskPartition64 *partp;
2330     char path[64];
2331     int isbusy = 0;
2332     VolumeId volumeId;
2333     int checkedOut;
2334 #ifdef AFS_DEMAND_ATTACH_FS
2335     VolumeStats stats_save;
2336     Volume *svp = NULL;
2337 #endif /* AFS_DEMAND_ATTACH_FS */
2338
2339     *ec = 0;
2340
2341     volumeId = VolumeNumber(name);
2342
2343     if (!(partp = VGetPartition_r(partition, 0))) {
2344         *ec = VNOVOL;
2345         Log("VAttachVolume: Error getting partition (%s)\n", partition);
2346         goto done;
2347     }
2348
2349     if (VRequiresPartLock()) {
2350         opr_Assert(VInit == 3);
2351         VLockPartition_r(partition);
2352     } else if (programType == fileServer) {
2353 #ifdef AFS_DEMAND_ATTACH_FS
2354         /* lookup the volume in the hash table */
2355         vp = VLookupVolume_r(ec, volumeId, NULL);
2356         if (*ec) {
2357             return NULL;
2358         }
2359
2360         if (vp) {
2361             /* save any counters that are supposed to
2362              * be monotonically increasing over the
2363              * lifetime of the fileserver */
2364             memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2365         } else {
2366             memset(&stats_save, 0, sizeof(VolumeStats));
2367         }
2368
2369         /* if there's something in the hash table, and it's not
2370          * in the pre-attach state, then we may need to detach
2371          * it before proceeding */
2372         if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
2373             VCreateReservation_r(vp);
2374             VWaitExclusiveState_r(vp);
2375
2376             /* at this point state must be one of:
2377              *   - UNATTACHED
2378              *   - ATTACHED
2379              *   - SHUTTING_DOWN
2380              *   - GOING_OFFLINE
2381              *   - SALVAGING
2382              *   - ERROR
2383              *   - DELETED
2384              */
2385
2386             if (vp->specialStatus == VBUSY)
2387                 isbusy = 1;
2388
2389             /* if it's already attached, see if we can return it */
2390             if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2391                 VGetVolumeByVp_r(ec, vp);
2392                 if (V_inUse(vp) == fileServer) {
2393                     VCancelReservation_r(vp);
2394                     return vp;
2395                 }
2396
2397                 /* otherwise, we need to detach, and attempt to re-attach */
2398                 VDetachVolume_r(ec, vp);
2399                 if (*ec) {
2400                     Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
2401                 }
2402             } else {
2403                 /* if it isn't fully attached, delete from the hash tables,
2404                    and let the refcounter handle the rest */
2405                 DeleteVolumeFromHashTable(vp);
2406                 DeleteVolumeFromVByPList_r(vp);
2407             }
2408
2409             VCancelReservation_r(vp);
2410             vp = NULL;
2411         }
2412
2413         /* pre-attach volume if it hasn't been done yet */
2414         if (!vp ||
2415             (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2416             (V_attachState(vp) == VOL_STATE_DELETED) ||
2417             (V_attachState(vp) == VOL_STATE_ERROR)) {
2418             svp = vp;
2419             vp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2420             if (*ec) {
2421                 return NULL;
2422             }
2423         }
2424
2425         opr_Assert(vp != NULL);
2426
2427         /* handle pre-attach races
2428          *
2429          * multiple threads can race to pre-attach a volume,
2430          * but we can't let them race beyond that
2431          *
2432          * our solution is to let the first thread to bring
2433          * the volume into an exclusive state win; the other
2434          * threads just wait until it finishes bringing the
2435          * volume online, and then they do a vgetvolumebyvp
2436          */
2437         if (svp && (svp != vp)) {
2438             /* wait for other exclusive ops to finish */
2439             VCreateReservation_r(vp);
2440             VWaitExclusiveState_r(vp);
2441
2442             /* get a heavyweight ref, kill the lightweight ref, and return */
2443             VGetVolumeByVp_r(ec, vp);
2444             VCancelReservation_r(vp);
2445             return vp;
2446         }
2447
2448         /* at this point, we are chosen as the thread to do
2449          * demand attachment for this volume. all other threads
2450          * doing a getvolume on vp->hashid will block until we finish */
2451
2452         /* make sure any old header cache entries are invalidated
2453          * before proceeding */
2454         FreeVolumeHeader(vp);
2455
2456         VChangeState_r(vp, VOL_STATE_ATTACHING);
2457
2458         /* restore any saved counters */
2459         memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2460 #else /* AFS_DEMAND_ATTACH_FS */
2461         vp = VGetVolume_r(ec, volumeId);
2462         if (vp) {
2463             if (V_inUse(vp) == fileServer)
2464                 return vp;
2465             if (vp->specialStatus == VBUSY)
2466                 isbusy = 1;
2467             VDetachVolume_r(ec, vp);
2468             if (*ec) {
2469                 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2470             }
2471             vp = NULL;
2472         }
2473 #endif /* AFS_DEMAND_ATTACH_FS */
2474     }
2475
2476     *ec = 0;
2477     strcpy(path, VPartitionPath(partp));
2478
2479     VOL_UNLOCK;
2480
2481     strcat(path, OS_DIRSEP);
2482     strcat(path, name);
2483
2484     if (!vp) {
2485       vp = (Volume *) calloc(1, sizeof(Volume));
2486       opr_Assert(vp != NULL);
2487       vp->hashid = volumeId;
2488       vp->device = partp->device;
2489       vp->partition = partp;
2490       queue_Init(&vp->vnode_list);
2491       queue_Init(&vp->rx_call_list);
2492 #ifdef AFS_DEMAND_ATTACH_FS
2493       opr_cv_init(&V_attachCV(vp));
2494 #endif /* AFS_DEMAND_ATTACH_FS */
2495     }
2496
2497     /* attach2 is entered without any locks, and returns
2498      * with vol_glock_mutex held */
2499     vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2500
2501     if (VCanUseFSSYNC() && vp) {
2502 #ifdef AFS_DEMAND_ATTACH_FS
2503         if ((mode == V_VOLUPD) || (VolumeWriteable(vp) && (mode == V_CLONE))) {
2504             /* mark volume header as in use so that volser crashes lead to a
2505              * salvage attempt */
2506             VUpdateVolume_r(ec, vp, 0);
2507         }
2508         /* for dafs, we should tell the fileserver, except for V_PEEK
2509          * where we know it is not necessary */
2510         if (mode == V_PEEK) {
2511             vp->needsPutBack = 0;
2512         } else {
2513             vp->needsPutBack = VOL_PUTBACK;
2514         }
2515 #else /* !AFS_DEMAND_ATTACH_FS */
2516         /* duplicate computation in fssync.c about whether the server
2517          * takes the volume offline or not.  If the volume isn't
2518          * offline, we must not return it when we detach the volume,
2519          * or the server will abort */
2520         if (mode == V_READONLY || mode == V_PEEK
2521             || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
2522             vp->needsPutBack = 0;
2523         else
2524             vp->needsPutBack = VOL_PUTBACK;
2525 #endif /* !AFS_DEMAND_ATTACH_FS */
2526     }
2527 #ifdef FSSYNC_BUILD_CLIENT
2528     /* Only give back the vol to the fileserver if we checked it out; attach2
2529      * will set checkedOut only if we successfully checked it out from the
2530      * fileserver. */
2531     if (VCanUseFSSYNC() && vp == NULL && checkedOut) {
2532
2533 #ifdef AFS_DEMAND_ATTACH_FS
2534         /* If we couldn't attach but we scheduled a salvage, we already
2535          * notified the fileserver; don't online it now */
2536         if (*ec != VSALVAGING)
2537 #endif /* AFS_DEMAND_ATTACH_FS */
2538         FSYNC_VolOp(volumeId, partition, FSYNC_VOL_ON, 0, NULL);
2539     } else
2540 #endif
2541     if (programType == fileServer && vp) {
2542 #ifdef AFS_DEMAND_ATTACH_FS
2543         /*
2544          * we can get here in cases where we don't "own"
2545          * the volume (e.g. volume owned by a utility).
2546          * short circuit around potential disk header races.
2547          */
2548         if (V_attachState(vp) != VOL_STATE_ATTACHED) {
2549             goto done;
2550         }
2551 #endif
2552         VUpdateVolume_r(ec, vp, 0);
2553         if (*ec) {
2554             Log("VAttachVolume: Error updating volume\n");
2555             if (vp)
2556                 VPutVolume_r(vp);
2557             goto done;
2558         }
2559         if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2560 #ifndef AFS_DEMAND_ATTACH_FS
2561             /* This is a hack: by temporarily setting the incore
2562              * dontSalvage flag ON, the volume will be put back on the
2563              * Update list (with dontSalvage OFF again).  It will then
2564              * come back in N minutes with DONT_SALVAGE eventually
2565              * set.  This is the way that volumes that have never had
2566              * it set get it set; or that volumes that have been
2567              * offline without DONT SALVAGE having been set also
2568              * eventually get it set */
2569             V_dontSalvage(vp) = DONT_SALVAGE;
2570 #endif /* !AFS_DEMAND_ATTACH_FS */
2571             VAddToVolumeUpdateList_r(ec, vp);
2572             if (*ec) {
2573                 Log("VAttachVolume: Error adding volume to update list\n");
2574                 if (vp)
2575                     VPutVolume_r(vp);
2576                 goto done;
2577             }
2578         }
2579         if (GetLogLevel() != 0)
2580           Log("VOnline:  volume %" AFS_VOLID_FMT " (%s) attached and online\n", afs_printable_VolumeId_lu(V_id(vp)),
2581                 V_name(vp));
2582     }
2583
2584   done:
2585     if (VRequiresPartLock()) {
2586         VUnlockPartition_r(partition);
2587     }
2588     if (*ec) {
2589 #ifdef AFS_DEMAND_ATTACH_FS
2590         /* attach failed; make sure we're in error state */
2591         if (vp && !VIsErrorState(V_attachState(vp))) {
2592             VChangeState_r(vp, VOL_STATE_ERROR);
2593         }
2594 #endif /* AFS_DEMAND_ATTACH_FS */
2595         return NULL;
2596     } else {
2597         return vp;
2598     }
2599 }
2600
2601 #ifdef AFS_DEMAND_ATTACH_FS
2602 /* VAttachVolumeByVp_r
2603  *
2604  * finish attaching a volume that is
2605  * in a less than fully attached state
2606  */
2607 /* caller MUST hold a ref count on vp */
2608 static Volume *
2609 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
2610 {
2611     char name[VMAXPATHLEN];
2612     int reserve = 0;
2613     struct DiskPartition64 *partp;
2614     char path[64];
2615     int isbusy = 0;
2616     VolumeId volumeId;
2617     Volume * nvp = NULL;
2618     VolumeStats stats_save;
2619     int checkedOut;
2620     *ec = 0;
2621
2622     /* volume utility should never call AttachByVp */
2623     opr_Assert(programType == fileServer);
2624
2625     volumeId = vp->hashid;
2626     partp = vp->partition;
2627     VolumeExternalName_r(volumeId, name, sizeof(name));
2628
2629
2630     /* if another thread is performing a blocking op, wait */
2631     VWaitExclusiveState_r(vp);
2632
2633     memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2634
2635     /* if it's already attached, see if we can return it */
2636     if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2637         VGetVolumeByVp_r(ec, vp);
2638         if (V_inUse(vp) == fileServer) {
2639             return vp;
2640         } else {
2641             if (vp->specialStatus == VBUSY)
2642                 isbusy = 1;
2643             VDetachVolume_r(ec, vp);
2644             if (*ec) {
2645                 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2646             }
2647             vp = NULL;
2648         }
2649     }
2650
2651     /* pre-attach volume if it hasn't been done yet */
2652     if (!vp ||
2653         (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2654         (V_attachState(vp) == VOL_STATE_DELETED) ||
2655         (V_attachState(vp) == VOL_STATE_ERROR)) {
2656         nvp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2657         if (*ec) {
2658             return NULL;
2659         }
2660         if (nvp != vp) {
2661             reserve = 1;
2662             VCreateReservation_r(nvp);
2663             vp = nvp;
2664         }
2665     }
2666
2667     opr_Assert(vp != NULL);
2668     VChangeState_r(vp, VOL_STATE_ATTACHING);
2669
2670     /* restore monotonically increasing stats */
2671     memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2672
2673     *ec = 0;
2674
2675     /* compute path to disk header */
2676     strcpy(path, VPartitionPath(partp));
2677
2678     VOL_UNLOCK;
2679
2680     strcat(path, OS_DIRSEP);
2681     strcat(path, name);
2682
2683     /* do volume attach
2684      *
2685      * NOTE: attach2 is entered without any locks, and returns
2686      * with vol_glock_mutex held */
2687     vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2688
2689     /*
2690      * the event that an error was encountered, or
2691      * the volume was not brought to an attached state
2692      * for any reason, skip to the end.  We cannot
2693      * safely call VUpdateVolume unless we "own" it.
2694      */
2695     if (*ec ||
2696         (vp == NULL) ||
2697         (V_attachState(vp) != VOL_STATE_ATTACHED)) {
2698         goto done;
2699     }
2700
2701     VUpdateVolume_r(ec, vp, 0);
2702     if (*ec) {
2703         Log("VAttachVolume: Error updating volume %" AFS_VOLID_FMT "\n",
2704             afs_printable_VolumeId_lu(vp->hashid));
2705         VPutVolume_r(vp);
2706         goto done;
2707     }
2708     if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2709 #ifndef AFS_DEMAND_ATTACH_FS
2710         /* This is a hack: by temporarily setting the incore
2711          * dontSalvage flag ON, the volume will be put back on the
2712          * Update list (with dontSalvage OFF again).  It will then
2713          * come back in N minutes with DONT_SALVAGE eventually
2714          * set.  This is the way that volumes that have never had
2715          * it set get it set; or that volumes that have been
2716          * offline without DONT SALVAGE having been set also
2717          * eventually get it set */
2718         V_dontSalvage(vp) = DONT_SALVAGE;
2719 #endif /* !AFS_DEMAND_ATTACH_FS */
2720         VAddToVolumeUpdateList_r(ec, vp);
2721         if (*ec) {
2722             Log("VAttachVolume: Error adding volume %" AFS_VOLID_FMT " to update list\n",
2723                 afs_printable_VolumeId_lu(vp->hashid));
2724             if (vp)
2725                 VPutVolume_r(vp);
2726             goto done;
2727         }
2728     }
2729     if (GetLogLevel() != 0)
2730         Log("VOnline:  volume %" AFS_VOLID_FMT " (%s) attached and online\n",
2731             afs_printable_VolumeId_lu(V_id(vp)), V_name(vp));
2732   done:
2733     if (reserve) {
2734         VCancelReservation_r(nvp);
2735         reserve = 0;
2736     }
2737     if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2738         if (vp && !VIsErrorState(V_attachState(vp))) {
2739             VChangeState_r(vp, VOL_STATE_ERROR);
2740         }
2741         return NULL;
2742     } else {
2743         return vp;
2744     }
2745 }
2746
2747 /**
2748  * lock a volume on disk (non-blocking).
2749  *
2750  * @param[in] vp  The volume to lock
2751  * @param[in] locktype READ_LOCK or WRITE_LOCK
2752  *
2753  * @return operation status
2754  *  @retval 0 success, lock was obtained
2755  *  @retval EBUSY a conflicting lock was held by another process
2756  *  @retval EIO   error acquiring lock
2757  *
2758  * @pre If we're in the fileserver, vp is in an exclusive state
2759  *
2760  * @pre vp is not already locked
2761  */
2762 static int
2763 VLockVolumeNB(Volume *vp, int locktype)
2764 {
2765     int code;
2766
2767     opr_Assert(programType != fileServer
2768                || VIsExclusiveState(V_attachState(vp)));
2769     opr_Assert(!(V_attachFlags(vp) & VOL_LOCKED));
2770
2771     code = VLockVolumeByIdNB(vp->hashid, vp->partition, locktype);
2772     if (code == 0) {
2773         V_attachFlags(vp) |= VOL_LOCKED;
2774     }
2775
2776     return code;
2777 }
2778
2779 /**
2780  * unlock a volume on disk that was locked with VLockVolumeNB.
2781  *
2782  * @param[in] vp  volume to unlock
2783  *
2784  * @pre If we're in the fileserver, vp is in an exclusive state
2785  *
2786  * @pre vp has already been locked
2787  */
2788 static void
2789 VUnlockVolume(Volume *vp)
2790 {
2791     opr_Assert(programType != fileServer
2792                || VIsExclusiveState(V_attachState(vp)));
2793     opr_Assert((V_attachFlags(vp) & VOL_LOCKED));
2794
2795     VUnlockVolumeById(vp->hashid, vp->partition);
2796
2797     V_attachFlags(vp) &= ~VOL_LOCKED;
2798 }
2799 #endif /* AFS_DEMAND_ATTACH_FS */
2800
2801 /**
2802  * read in a vol header, possibly lock the vol header, and possibly check out
2803  * the vol header from the fileserver, as part of volume attachment.
2804  *
2805  * @param[out] ec     error code
2806  * @param[in] vp      volume pointer object
2807  * @param[in] partp   disk partition object of the attaching partition
2808  * @param[in] mode    attachment mode such as V_VOLUPD, V_DUMP, etc (see
2809  *                    volume.h)
2810  * @param[in] peek    1 to just try to read in the volume header and make sure
2811  *                    we don't try to lock the vol, or check it out from
2812  *                    FSSYNC or anything like that; 0 otherwise, for 'normal'
2813  *                    operation
2814  * @param[out] acheckedOut   If we successfully checked-out the volume from
2815  *                           the fileserver (if we needed to), this is set
2816  *                           to 1, otherwise it is untouched.
2817  *
2818  * @note As part of DAFS volume attachment, the volume header may be either
2819  *       read- or write-locked to ensure mutual exclusion of certain volume
2820  *       operations. In some cases in order to determine whether we need to
2821  *       read- or write-lock the header, we need to read in the header to see
2822  *       if the volume is RW or not. So, if we read in the header under a
2823  *       read-lock and determine that we actually need a write-lock on the
2824  *       volume header, this function will drop the read lock, acquire a write
2825  *       lock, and read the header in again.
2826  */
2827 static void
2828 attach_volume_header(Error *ec, Volume *vp, struct DiskPartition64 *partp,
2829                      int mode, int peek, int *acheckedOut)
2830 {
2831     struct VolumeDiskHeader diskHeader;
2832     struct VolumeHeader header;
2833     int code;
2834     int first_try = 1;
2835     int lock_tries = 0, checkout_tries = 0;
2836     int retry;
2837     VolumeId volid = vp->hashid;
2838 #ifdef FSSYNC_BUILD_CLIENT
2839     int checkout, done_checkout = 0;
2840 #endif /* FSSYNC_BUILD_CLIENT */
2841 #ifdef AFS_DEMAND_ATTACH_FS
2842     int locktype = 0, use_locktype = -1;
2843 #endif /* AFS_DEMAND_ATTACH_FS */
2844
2845  retry:
2846     retry = 0;
2847     *ec = 0;
2848
2849     if (lock_tries > VOL_MAX_CHECKOUT_RETRIES) {
2850         Log("VAttachVolume: retried too many times trying to lock header for "
2851             "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2852             VPartitionPath(partp));
2853         *ec = VNOVOL;
2854         goto done;
2855     }
2856     if (checkout_tries > VOL_MAX_CHECKOUT_RETRIES) {
2857         Log("VAttachVolume: retried too many times trying to checkout "
2858             "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2859             VPartitionPath(partp));
2860         *ec = VNOVOL;
2861         goto done;
2862     }
2863
2864     if (VReadVolumeDiskHeader(volid, partp, NULL)) {
2865         /* short-circuit the 'volume does not exist' case */
2866         *ec = VNOVOL;
2867         goto done;
2868     }
2869
2870 #ifdef FSSYNC_BUILD_CLIENT
2871     checkout = !done_checkout;
2872     done_checkout = 1;
2873     if (!peek && checkout && VMustCheckoutVolume(mode)) {
2874         SYNC_response res;
2875         memset(&res, 0, sizeof(res));
2876
2877         if (FSYNC_VolOp(volid, partp->name, FSYNC_VOL_NEEDVOLUME, mode, &res)
2878             != SYNC_OK) {
2879
2880             if (res.hdr.reason == FSYNC_SALVAGE) {
2881                 Log("VAttachVolume: file server says volume %lu is salvaging\n",
2882                      afs_printable_uint32_lu(volid));
2883                 *ec = VSALVAGING;
2884             } else {
2885                 Log("VAttachVolume: attach of volume %lu apparently denied by file server\n",
2886                      afs_printable_uint32_lu(volid));
2887                 *ec = VNOVOL;   /* XXXX */
2888             }
2889             goto done;
2890         }
2891         *acheckedOut = 1;
2892     }
2893 #endif
2894
2895 #ifdef AFS_DEMAND_ATTACH_FS
2896     if (use_locktype < 0) {
2897         /* don't know whether vol is RO or RW; assume it's RO and we can retry
2898          * if it turns out to be RW */
2899         locktype = VVolLockType(mode, 0);
2900
2901     } else {
2902         /* a previous try says we should use use_locktype to lock the volume,
2903          * so use that */
2904         locktype = use_locktype;
2905     }
2906
2907     if (!peek && locktype) {
2908         code = VLockVolumeNB(vp, locktype);
2909         if (code) {
2910             if (code == EBUSY) {
2911                 Log("VAttachVolume: another program has vol %lu locked\n",
2912                     afs_printable_uint32_lu(volid));
2913             } else {
2914                 Log("VAttachVolume: error %d trying to lock vol %lu\n",
2915                     code, afs_printable_uint32_lu(volid));
2916             }
2917
2918             *ec = VNOVOL;
2919             goto done;
2920         }
2921     }
2922 #endif /* AFS_DEMAND_ATTACH_FS */
2923
2924     code = VReadVolumeDiskHeader(volid, partp, &diskHeader);
2925     if (code) {
2926         if (code == EIO) {
2927             *ec = VSALVAGE;
2928         } else {
2929             *ec = VNOVOL;
2930         }
2931         goto done;
2932     }
2933
2934     DiskToVolumeHeader(&header, &diskHeader);
2935
2936     IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header.parent,
2937             header.largeVnodeIndex);
2938     IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header.parent,
2939             header.smallVnodeIndex);
2940     IH_INIT(vp->diskDataHandle, partp->device, header.parent,
2941             header.volumeInfo);
2942     IH_INIT(vp->linkHandle, partp->device, header.parent, header.linkTable);
2943
2944     if (first_try) {
2945         /* only need to do this once */
2946         VOL_LOCK;
2947         GetVolumeHeader(vp);
2948         VOL_UNLOCK;
2949     }
2950
2951 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2952     /* demand attach changes the V_PEEK mechanism
2953      *
2954      * we can now suck the current disk data structure over
2955      * the fssync interface without going to disk
2956      *
2957      * (technically, we don't need to restrict this feature
2958      *  to demand attach fileservers.  However, I'm trying
2959      *  to limit the number of common code changes)
2960      */
2961     if (VCanUseFSSYNC() && (mode == V_PEEK || peek)) {
2962         SYNC_response res;
2963         res.payload.len = sizeof(VolumeDiskData);
2964         res.payload.buf = &(V_disk(vp));
2965
2966         if (FSYNC_VolOp(vp->hashid,
2967                         partp->name,
2968                         FSYNC_VOL_QUERY_HDR,
2969                         FSYNC_WHATEVER,
2970                         &res) == SYNC_OK) {
2971             goto disk_header_loaded;
2972         }
2973     }
2974 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2975     (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2976                      sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2977
2978 #ifdef AFS_DEMAND_ATTACH_FS
2979     /* update stats */
2980     VOL_LOCK;
2981     IncUInt64(&VStats.hdr_loads);
2982     IncUInt64(&vp->stats.hdr_loads);
2983     VOL_UNLOCK;
2984 #endif /* AFS_DEMAND_ATTACH_FS */
2985
2986     if (*ec) {
2987         Log("VAttachVolume: Error reading diskDataHandle header for vol %lu; "
2988             "error=%u\n", afs_printable_uint32_lu(volid), *ec);
2989         goto done;
2990     }
2991
2992 #ifdef AFS_DEMAND_ATTACH_FS
2993 # ifdef FSSYNC_BUILD_CLIENT
2994  disk_header_loaded:
2995 # endif /* FSSYNC_BUILD_CLIENT */
2996
2997     /* if the lock type we actually used to lock the volume is different than
2998      * the lock type we should have used, retry with the lock type we should
2999      * use */
3000     use_locktype = VVolLockType(mode, VolumeWriteable(vp));
3001     if (locktype != use_locktype) {
3002         retry = 1;
3003         lock_tries++;
3004     }
3005 #endif /* AFS_DEMAND_ATTACH_FS */
3006
3007     *ec = 0;
3008
3009  done:
3010 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
3011     if (!peek && *ec == 0 && retry == 0 && VMustCheckoutVolume(mode)) {
3012
3013         code = FSYNC_VerifyCheckout(volid, partp->name, FSYNC_VOL_NEEDVOLUME, mode);
3014
3015         if (code == SYNC_DENIED) {
3016             /* must retry checkout; fileserver no longer thinks we have
3017              * the volume */
3018             retry = 1;
3019             checkout_tries++;
3020             done_checkout = 0;
3021
3022         } else if (code != SYNC_OK) {
3023             *ec = VNOVOL;
3024         }
3025     }
3026 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
3027
3028     if (*ec || retry) {
3029         /* either we are going to be called again for a second pass, or we
3030          * encountered an error; clean up in either case */
3031
3032 #ifdef AFS_DEMAND_ATTACH_FS
3033         if ((V_attachFlags(vp) & VOL_LOCKED)) {
3034             VUnlockVolume(vp);
3035         }
3036 #endif /* AFS_DEMAND_ATTACH_FS */
3037         if (vp->linkHandle) {
3038             IH_RELEASE(vp->vnodeIndex[vLarge].handle);
3039             IH_RELEASE(vp->vnodeIndex[vSmall].handle);
3040             IH_RELEASE(vp->diskDataHandle);
3041             IH_RELEASE(vp->linkHandle);
3042         }
3043     }
3044
3045     if (*ec) {
3046         VOL_LOCK;
3047         FreeVolumeHeader(vp);
3048         VOL_UNLOCK;
3049         return;
3050     }
3051     if (retry) {
3052         first_try = 0;
3053         goto retry;
3054     }
3055 }
3056
3057 #ifdef AFS_DEMAND_ATTACH_FS
3058 static void
3059 attach_check_vop(Error *ec, VolumeId volid, struct DiskPartition64 *partp,
3060                  Volume *vp, int *acheckedOut)
3061 {
3062     *ec = 0;
3063
3064     if (vp->pending_vol_op) {
3065
3066         VOL_LOCK;
3067
3068         if (vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningUnknown) {
3069             int code;
3070             code = VVolOpLeaveOnlineNoHeader_r(vp, vp->pending_vol_op);
3071             if (code == 1) {
3072                 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3073             } else if (code == 0) {
3074                 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3075
3076             } else {
3077                 /* we need the vol header to determine if the volume can be
3078                  * left online for the vop, so... get the header */
3079
3080                 VOL_UNLOCK;
3081
3082                 /* attach header with peek=1 to avoid checking out the volume
3083                  * or locking it; we just want the header info, we're not
3084                  * messing with the volume itself at all */
3085                 attach_volume_header(ec, vp, partp, V_PEEK, 1, acheckedOut);
3086                 if (*ec) {
3087                     return;
3088                 }
3089
3090                 VOL_LOCK;
3091
3092                 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
3093                     vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3094                 } else {
3095                     vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3096                 }
3097
3098                 /* make sure we grab a new vol header and re-open stuff on
3099                  * actual attachment; we can't keep the data we grabbed, since
3100                  * it was not done under a lock and thus not safe */
3101                 FreeVolumeHeader(vp);
3102                 VReleaseVolumeHandles_r(vp);
3103             }
3104         }
3105         /* see if the pending volume op requires exclusive access */
3106         switch (vp->pending_vol_op->vol_op_state) {
3107         case FSSYNC_VolOpPending:
3108             /* this should never happen */
3109             opr_Assert(vp->pending_vol_op->vol_op_state
3110                             != FSSYNC_VolOpPending);
3111             break;
3112
3113         case FSSYNC_VolOpRunningUnknown:
3114             /* this should never happen; we resolved 'unknown' above */
3115             opr_Assert(vp->pending_vol_op->vol_op_state
3116                             != FSSYNC_VolOpRunningUnknown);
3117             break;
3118
3119         case FSSYNC_VolOpRunningOffline:
3120             /* mark the volume down */
3121             *ec = VOFFLINE;
3122             VChangeState_r(vp, VOL_STATE_UNATTACHED);
3123
3124             /* do not set V_offlineMessage here; we don't have ownership of
3125              * the volume (and probably do not have the header loaded), so we
3126              * can't alter the disk header */
3127
3128             /* check to see if we should set the specialStatus flag */
3129             if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
3130                 /* don't overwrite specialStatus if it was already set to
3131                  * something else (e.g. VMOVED) */
3132                 if (!vp->specialStatus) {
3133                     vp->specialStatus = VBUSY;
3134                 }
3135             }
3136             break;
3137
3138         default:
3139             break;
3140         }
3141
3142         VOL_UNLOCK;
3143     }
3144 }
3145 #endif /* AFS_DEMAND_ATTACH_FS */
3146
3147 /**
3148  * volume attachment helper function.
3149  *
3150  * @param[out] ec      error code
3151  * @param[in] volumeId volume ID of the attaching volume
3152  * @param[in] path     full path to the volume header .vol file
3153  * @param[in] partp    disk partition object for the attaching partition
3154  * @param[in] vp       volume object; vp->hashid, vp->device, vp->partition,
3155  *                     vp->vnode_list, vp->rx_call_list, and V_attachCV (for
3156  *                     DAFS) should already be initialized
3157  * @param[in] isbusy   1 if vp->specialStatus should be set to VBUSY; that is,
3158  *                     if there is a volume operation running for this volume
3159  *                     that should set the volume to VBUSY during its run. 0
3160  *                     otherwise. (see VVolOpSetVBusy_r)
3161  * @param[in] mode     attachment mode such as V_VOLUPD, V_DUMP, etc (see
3162  *                     volume.h)
3163  * @param[out] acheckedOut   If we successfully checked-out the volume from
3164  *                           the fileserver (if we needed to), this is set
3165  *                           to 1, otherwise it is 0.
3166  *
3167  * @return pointer to the semi-attached volume pointer
3168  *  @retval NULL an error occurred (check value of *ec)
3169  *  @retval vp volume successfully attaching
3170  *
3171  * @pre no locks held
3172  *
3173  * @post VOL_LOCK held
3174  */
3175 static Volume *
3176 attach2(Error * ec, VolumeId volumeId, char *path, struct DiskPartition64 *partp,
3177         Volume * vp, int isbusy, int mode, int *acheckedOut)
3178 {
3179     /* have we read in the header successfully? */
3180     int read_header = 0;
3181
3182 #ifdef AFS_DEMAND_ATTACH_FS
3183     /* should we FreeVolume(vp) instead of VCheckFree(vp) in the error
3184      * cleanup? */
3185     int forcefree = 0;
3186
3187     /* in the case of an error, to what state should the volume be
3188      * transitioned? */
3189     VolState error_state = VOL_STATE_ERROR;
3190 #endif /* AFS_DEMAND_ATTACH_FS */
3191
3192     *ec = 0;
3193
3194     vp->vnodeIndex[vLarge].handle = NULL;
3195     vp->vnodeIndex[vSmall].handle = NULL;
3196     vp->diskDataHandle = NULL;
3197     vp->linkHandle = NULL;
3198
3199     *acheckedOut = 0;
3200
3201 #ifdef AFS_DEMAND_ATTACH_FS
3202     attach_check_vop(ec, volumeId, partp, vp, acheckedOut);
3203     if (!*ec) {
3204         attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3205     }
3206 #else
3207     attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3208 #endif /* !AFS_DEMAND_ATTACH_FS */
3209
3210     if (*ec == VNOVOL) {
3211         /* if the volume doesn't exist, skip straight to 'error' so we don't
3212          * request a salvage */
3213         goto unlocked_error;
3214     }
3215
3216     if (!*ec) {
3217         read_header = 1;
3218
3219         /* ensure that we don't override specialStatus if it was set to
3220          * something else (e.g. VMOVED) */
3221         if (isbusy && !vp->specialStatus) {
3222             vp->specialStatus = VBUSY;
3223         }
3224         vp->shuttingDown = 0;
3225         vp->goingOffline = 0;
3226         vp->nUsers = 1;
3227 #ifdef AFS_DEMAND_ATTACH_FS
3228         vp->stats.last_attach = FT_ApproxTime();
3229         vp->stats.attaches++;
3230 #endif
3231
3232         VOL_LOCK;
3233         IncUInt64(&VStats.attaches);
3234         vp->cacheCheck = ++VolumeCacheCheck;
3235         /* just in case this ever rolls over */
3236         if (!vp->cacheCheck)
3237             vp->cacheCheck = ++VolumeCacheCheck;
3238         VOL_UNLOCK;
3239
3240 #ifdef AFS_DEMAND_ATTACH_FS
3241         V_attachFlags(vp) |= VOL_HDR_LOADED;
3242         vp->stats.last_hdr_load = vp->stats.last_attach;
3243 #endif /* AFS_DEMAND_ATTACH_FS */
3244     }
3245
3246     if (!*ec) {
3247         struct IndexFileHeader iHead;
3248
3249         /*
3250          * We just read in the diskstuff part of the header.  If the detailed
3251          * volume stats area has not yet been initialized, we should bzero the
3252          * area and mark it as initialized.
3253          */
3254         if (!(V_stat_initialized(vp))) {
3255             memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
3256             V_stat_initialized(vp) = 1;
3257         }
3258
3259         (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
3260                          (char *)&iHead, sizeof(iHead),
3261                          SMALLINDEXMAGIC, SMALLINDEXVERSION);
3262
3263         if (*ec) {
3264             Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
3265         }
3266     }
3267
3268     if (!*ec) {
3269         struct IndexFileHeader iHead;
3270
3271         (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
3272                          (char *)&iHead, sizeof(iHead),
3273                          LARGEINDEXMAGIC, LARGEINDEXVERSION);
3274
3275         if (*ec) {
3276             Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
3277         }
3278     }
3279
3280 #ifdef AFS_NAMEI_ENV
3281     if (!*ec) {
3282         struct versionStamp stamp;
3283
3284         (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
3285                          sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
3286
3287         if (*ec) {
3288             Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
3289         }
3290     }
3291 #endif /* AFS_NAMEI_ENV */
3292
3293 #if defined(AFS_DEMAND_ATTACH_FS)
3294     if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
3295         VOL_LOCK;
3296         if (!VCanScheduleSalvage()) {
3297             Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3298         }
3299         VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3300         vp->nUsers = 0;
3301
3302         goto locked_error;
3303     } else if (*ec) {
3304         /* volume operation in progress */
3305         VOL_LOCK;
3306         /* we have already transitioned the vp away from ATTACHING state, so we
3307          * can go right to the end of attach2, and we do not need to transition
3308          * to ERROR. */
3309         goto error_notbroken;
3310     }
3311 #else /* AFS_DEMAND_ATTACH_FS */
3312     if (*ec) {
3313         Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3314         goto unlocked_error;
3315     }
3316 #endif /* AFS_DEMAND_ATTACH_FS */
3317
3318     if (V_needsSalvaged(vp)) {
3319         if (vp->specialStatus)
3320             vp->specialStatus = 0;
3321         VOL_LOCK;
3322 #if defined(AFS_DEMAND_ATTACH_FS)
3323         if (!VCanScheduleSalvage()) {
3324             Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
3325         }
3326         VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3327         vp->nUsers = 0;
3328
3329 #else /* AFS_DEMAND_ATTACH_FS */
3330         *ec = VSALVAGE;
3331 #endif /* AFS_DEMAND_ATTACH_FS */
3332
3333         goto locked_error;
3334     }
3335
3336     VOL_LOCK;
3337     vp->nextVnodeUnique = V_uniquifier(vp);
3338
3339     if (VShouldCheckInUse(mode) && V_inUse(vp) && VolumeWriteable(vp)) {
3340         if (!V_needsSalvaged(vp)) {
3341             V_needsSalvaged(vp) = 1;
3342             VUpdateVolume_r(ec, vp, 0);
3343         }
3344 #if defined(AFS_DEMAND_ATTACH_FS)
3345         if (!VCanScheduleSalvage()) {
3346             Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3347         }
3348         VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3349         vp->nUsers = 0;
3350
3351 #else /* AFS_DEMAND_ATTACH_FS */
3352         Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3353         *ec = VSALVAGE;
3354 #endif /* AFS_DEMAND_ATTACH_FS */
3355
3356         goto locked_error;
3357     }
3358
3359     if (programType == fileServer && V_destroyMe(vp) == DESTROY_ME) {
3360         /* Only check destroyMe if we are the fileserver, since the
3361          * volserver et al sometimes need to work with volumes with
3362          * destroyMe set. Examples are 'temporary' volumes the
3363          * volserver creates, and when we create a volume (destroyMe
3364          * is set on creation; sometimes a separate volserver
3365          * transaction is created to clear destroyMe).
3366          */
3367
3368 #if defined(AFS_DEMAND_ATTACH_FS)
3369         /* schedule a salvage so the volume goes away on disk */
3370         VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3371         VChangeState_r(vp, VOL_STATE_ERROR);
3372         vp->nUsers = 0;
3373         forcefree = 1;
3374 #endif /* AFS_DEMAND_ATTACH_FS */
3375         Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
3376         *ec = VNOVOL;
3377         goto locked_error;
3378     }
3379
3380     vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
3381 #ifndef BITMAP_LATER
3382     if (programType == fileServer && VolumeWriteable(vp)) {
3383         int i;
3384         for (i = 0; i < nVNODECLASSES; i++) {
3385             VGetBitmap_r(ec, vp, i);
3386             if (*ec) {
3387 #ifdef AFS_DEMAND_ATTACH_FS
3388                 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3389                 vp->nUsers = 0;
3390 #endif /* AFS_DEMAND_ATTACH_FS */
3391                 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
3392                     path);
3393                 goto locked_error;
3394             }
3395         }
3396     }
3397 #endif /* BITMAP_LATER */
3398
3399     if (VInit >= 2 && V_needsCallback(vp)) {
3400         if (V_BreakVolumeCallbacks) {
3401             Log("VAttachVolume: Volume %lu was changed externally; breaking callbacks\n",
3402                 afs_printable_uint32_lu(V_id(vp)));
3403             V_needsCallback(vp) = 0;
3404             VOL_UNLOCK;
3405             (*V_BreakVolumeCallbacks) (V_id(vp));
3406             VOL_LOCK;
3407
3408             VUpdateVolume_r(ec, vp, 0);
3409         }
3410 #ifdef FSSYNC_BUILD_CLIENT
3411         else if (VCanUseFSSYNC()) {
3412             afs_int32 fsync_code;
3413
3414             V_needsCallback(vp) = 0;
3415             VOL_UNLOCK;
3416             fsync_code = FSYNC_VolOp(V_id(vp), NULL, FSYNC_VOL_BREAKCBKS, FSYNC_WHATEVER, NULL);
3417             VOL_LOCK;
3418
3419             if (fsync_code) {
3420                 V_needsCallback(vp) = 1;
3421                 Log("Error trying to tell the fileserver to break callbacks for "
3422                     "changed volume %lu; error code %ld\n",
3423                     afs_printable_uint32_lu(V_id(vp)),
3424                     afs_printable_int32_ld(fsync_code));
3425             } else {
3426                 VUpdateVolume_r(ec, vp, 0);
3427             }
3428         }
3429 #endif /* FSSYNC_BUILD_CLIENT */
3430
3431         if (*ec) {
3432             Log("VAttachVolume: error %d clearing needsCallback on volume "
3433                 "%lu; needs salvage\n", (int)*ec,
3434                 afs_printable_uint32_lu(V_id(vp)));
3435 #ifdef AFS_DEMAND_ATTACH_FS
3436             VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3437             vp->nUsers = 0;
3438 #else /* !AFS_DEMAND_ATTACH_FS */
3439             *ec = VSALVAGE;
3440 #endif /* !AFS_DEMAND_ATTACh_FS */
3441             goto locked_error;
3442         }
3443     }
3444
3445     if (programType == fileServer) {
3446         if (vp->specialStatus)
3447             vp->specialStatus = 0;
3448         if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
3449             V_inUse(vp) = fileServer;
3450             V_offlineMessage(vp)[0] = '\0';
3451         }
3452 #ifdef AFS_DEMAND_ATTACH_FS
3453         /* check if the volume is actually usable. only do this for DAFS; for
3454          * non-DAFS, volumes that are not inService/blessed can still be
3455          * attached, even if clients cannot access them. this is relevant
3456          * because for non-DAFS, we try to attach the volume when e.g.
3457          * volserver gives us back then vol when its done with it, but
3458          * volserver may give us back a volume that is not inService/blessed. */
3459
3460         if (!V_inUse(vp)) {
3461             *ec = VNOVOL;
3462             /* Put the vol into PREATTACHED state, so if someone tries to
3463              * access it again, we try to attach, see that we're not blessed,
3464              * and give a VNOVOL error again. Putting it into UNATTACHED state
3465              * would result in a VOFFLINE error instead. */
3466             error_state = VOL_STATE_PREATTACHED;
3467
3468             /* mimic e.g. GetVolume errors */
3469             if (!V_blessed(vp)) {
3470                 Log("Volume %lu offline: not blessed\n", afs_printable_uint32_lu(V_id(vp)));
3471                 FreeVolumeHeader(vp);
3472             } else if (!V_inService(vp)) {
3473                 Log("Volume %lu offline: not in service\n", afs_printable_uint32_lu(V_id(vp)));
3474                 FreeVolumeHeader(vp);
3475             } else {
3476                 Log("Volume %lu offline: needs salvage\n", afs_printable_uint32_lu(V_id(vp)));
3477                 *ec = VSALVAGE;
3478                 error_state = VOL_STATE_ERROR;
3479                 /* see if we can recover */
3480                 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3481             }
3482             vp->nUsers = 0;
3483             goto locked_error;
3484         }
3485 #endif /* AFS_DEMAND_ATTACH_FS */
3486     } else {
3487 #ifdef AFS_DEMAND_ATTACH_FS
3488         if ((mode != V_PEEK) && (mode != V_SECRETLY) && (mode != V_READONLY))
3489             V_inUse(vp) = programType;
3490 #endif /* AFS_DEMAND_ATTACH_FS */
3491         V_checkoutMode(vp) = mode;
3492     }
3493
3494     AddVolumeToHashTable(vp, vp->hashid);
3495 #ifdef AFS_DEMAND_ATTACH_FS
3496     if (VCanUnlockAttached() && (V_attachFlags(vp) & VOL_LOCKED)) {
3497         VUnlockVolume(vp);
3498     }
3499     if ((programType != fileServer) ||
3500         (V_inUse(vp) == fileServer)) {
3501         AddVolumeToVByPList_r(vp);
3502         VLRU_Add_r(vp);
3503         VChangeState_r(vp, VOL_STATE_ATTACHED);
3504     } else {
3505         VChangeState_r(vp, VOL_STATE_UNATTACHED);
3506     }
3507 #endif
3508
3509     return vp;
3510
3511 unlocked_error:
3512     VOL_LOCK;
3513 locked_error:
3514 #ifdef AFS_DEMAND_ATTACH_FS
3515     if (!VIsErrorState(V_attachState(vp))) {
3516         if (programType != fileServer && *ec == VNOVOL) {
3517             /* do not log anything in this case; it is common for
3518              * non-fileserver programs to fail here with VNOVOL, since that
3519              * is what happens when they simply try to use a volume, but that
3520              * volume doesn't exist. */
3521
3522         } else if (VIsErrorState(error_state)) {
3523             Log("attach2: forcing vol %" AFS_VOLID_FMT " to error state (state %u flags 0x%x ec %d)\n",
3524                 afs_printable_VolumeId_lu(vp->hashid), V_attachState(vp),
3525                 V_attachFlags(vp), *ec);
3526         }
3527         VChangeState_r(vp, error_state);
3528     }
3529 #endif /* AFS_DEMAND_ATTACH_FS */
3530
3531     if (read_header) {
3532         VReleaseVolumeHandles_r(vp);
3533     }
3534
3535 #ifdef AFS_DEMAND_ATTACH_FS
3536  error_notbroken:
3537     if (VCheckSalvage(vp) == VCHECK_SALVAGE_FAIL) {
3538         /* The salvage could not be scheduled with the salvage server
3539          * due to a hard error. Reset the error code to prevent retry loops by
3540          * callers. */
3541         if (*ec == VSALVAGING) {
3542             *ec = VSALVAGE;
3543         }
3544     }
3545     if (forcefree) {
3546         FreeVolume(vp);
3547     } else {
3548         VCheckFree(vp);
3549     }
3550 #else /* !AFS_DEMAND_ATTACH_FS */
3551     FreeVolume(vp);
3552 #endif /* !AFS_DEMAND_ATTACH_FS */
3553     return NULL;
3554 }
3555
3556 /* Attach an existing volume.
3557    The volume also normally goes online at this time.
3558    An offline volume must be reattached to make it go online.
3559  */
3560
3561 Volume *
3562 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
3563 {
3564     Volume *retVal;
3565     VOL_LOCK;
3566     retVal = VAttachVolume_r(ec, volumeId, mode);
3567     VOL_UNLOCK;
3568     return retVal;
3569 }
3570
3571 Volume *
3572 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
3573 {
3574     char *part, *name;
3575     VGetVolumePath(ec, volumeId, &part, &name);
3576     if (*ec) {
3577         Volume *vp;
3578         Error error;
3579         vp = VGetVolume_r(&error, volumeId);
3580         if (vp) {
3581             opr_Assert(V_inUse(vp) == 0);
3582             VDetachVolume_r(ec, vp);
3583         }
3584         return NULL;
3585     }
3586     return VAttachVolumeByName_r(ec, part, name, mode);
3587 }
3588
3589 /* Increment a reference count to a volume, sans context swaps.  Requires
3590  * possibly reading the volume header in from the disk, since there's
3591  * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
3592  *
3593  * N.B. This call can fail if we can't read in the header!!  In this case
3594  * we still guarantee we won't context swap, but the ref count won't be
3595  * incremented (otherwise we'd violate the invariant).
3596  */
3597 /* NOTE: with the demand attach fileserver extensions, the global lock
3598  * is dropped within VHold */
3599 #ifdef AFS_DEMAND_ATTACH_FS
3600 static int
3601 VHold_r(Volume * vp)
3602 {
3603     Error error;
3604
3605     VCreateReservation_r(vp);
3606     VWaitExclusiveState_r(vp);
3607
3608     LoadVolumeHeader(&error, vp);
3609     if (error) {
3610         VCancelReservation_r(vp);
3611         return error;
3612     }
3613     vp->nUsers++;
3614     VCancelReservation_r(vp);
3615     return 0;
3616 }
3617 #else /* AFS_DEMAND_ATTACH_FS */
3618 static int
3619 VHold_r(Volume * vp)
3620 {
3621     Error error;
3622
3623     LoadVolumeHeader(&error, vp);
3624     if (error)
3625         return error;
3626     vp->nUsers++;
3627     return 0;
3628 }
3629 #endif /* AFS_DEMAND_ATTACH_FS */
3630
3631 /**** volume timeout-related stuff ****/
3632
3633 #ifdef AFS_PTHREAD_ENV
3634
3635 static struct timespec *shutdown_timeout;
3636 static pthread_once_t shutdown_timeout_once = PTHREAD_ONCE_INIT;
3637
3638 static_inline int
3639 VTimedOut(const struct timespec *ts)
3640 {
3641     struct timeval tv;
3642     int code;
3643
3644     if (ts->tv_sec == 0) {
3645         /* short-circuit; this will have always timed out */
3646         return 1;
3647     }
3648
3649     code = gettimeofday(&tv, NULL);
3650     if (code) {
3651         Log("Error %d from gettimeofday, assuming we have not timed out\n", errno);
3652         /* assume no timeout; failure mode is we just wait longer than normal
3653          * instead of returning errors when we shouldn't */
3654         return 0;
3655     }
3656
3657     if (tv.tv_sec < ts->tv_sec ||
3658         (tv.tv_sec == ts->tv_sec && tv.tv_usec*1000 < ts->tv_nsec)) {
3659
3660         return 0;
3661     }
3662
3663     return 1;
3664 }
3665
3666 /**
3667  * Calculate an absolute timeout.
3668  *
3669  * @param[out] ts  A timeout that is "timeout" seconds from now, if we return
3670  *                 NULL, the memory is not touched
3671  * @param[in]  timeout  How long the timeout should be from now
3672  *
3673  * @return timeout to use
3674  *  @retval NULL      no timeout; wait forever
3675  *  @retval non-NULL  the given value for "ts"
3676  *
3677  * @internal
3678  */
3679 static struct timespec *
3680 VCalcTimeout(struct timespec *ts, afs_int32 timeout)
3681 {
3682     struct timeval now;
3683     int code;
3684
3685     if (timeout < 0) {
3686         return NULL;
3687     }
3688
3689     if (timeout == 0) {
3690         ts->tv_sec = ts->tv_nsec = 0;
3691         return ts;
3692     }
3693
3694     code = gettimeofday(&now, NULL);
3695     if (code) {
3696         Log("Error %d from gettimeofday, falling back to 'forever' timeout\n", errno);
3697         return NULL;
3698     }
3699
3700     ts->tv_sec = now.tv_sec + timeout;
3701     ts->tv_nsec = now.tv_usec * 1000;
3702
3703     return ts;
3704 }
3705
3706 /**
3707  * Initialize the shutdown_timeout global.
3708  */
3709 static void
3710 VShutdownTimeoutInit(void)
3711 {
3712     struct timespec *ts;
3713
3714     ts = malloc(sizeof(*ts));
3715
3716     shutdown_timeout = VCalcTimeout(ts, vol_opts.offline_shutdown_timeout);
3717
3718     if (!shutdown_timeout) {
3719         free(ts);
3720     }
3721 }
3722
3723 /**
3724  * Figure out the timeout that should be used for waiting for offline volumes.
3725  *
3726  * @param[out] ats  Storage space for a local timeout value if needed
3727  *
3728  * @return The timeout value that should be used
3729  *   @retval NULL      No timeout; wait forever for offlining volumes
3730  *   @retval non-NULL  A pointer to the absolute time that should be used as
3731  *                     the deadline for waiting for offlining volumes.
3732  *
3733  * @note If we return non-NULL, the pointer we return may or may not be the
3734  *       same as "ats"
3735  */
3736 static const struct timespec *
3737 VOfflineTimeout(struct timespec *ats)
3738 {
3739     if (vol_shutting_down) {
3740         opr_Verify(pthread_once(&shutdown_timeout_once,
3741                                 VShutdownTimeoutInit) == 0);
3742         return shutdown_timeout;
3743     } else {
3744         return VCalcTimeout(ats, vol_opts.offline_timeout);
3745     }
3746 }
3747
3748 #else /* AFS_PTHREAD_ENV */
3749
3750 /* Waiting a certain amount of time for offlining volumes is not supported
3751  * for LWP due to a lack of primitives. So, we never time out */
3752 # define VTimedOut(x) (0)
3753 # define VOfflineTimeout(x) (NULL)
3754
3755 #endif /* !AFS_PTHREAD_ENV */
3756
3757 #if 0
3758 static int
3759 VHold(Volume * vp)
3760 {
3761     int retVal;
3762     VOL_LOCK;
3763     retVal = VHold_r(vp);
3764     VOL_UNLOCK;
3765     return retVal;
3766 }
3767 #endif
3768
3769 static afs_int32
3770 VIsGoingOffline_r(struct Volume *vp)
3771 {
3772     afs_int32 code = 0;
3773
3774     if (vp->goingOffline) {
3775         if (vp->specialStatus) {
3776             code = vp->specialStatus;
3777         } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3778             code = VNOVOL;
3779         } else {
3780             code = VOFFLINE;
3781         }
3782     }
3783
3784     return code;
3785 }
3786
3787 /**
3788  * Tell the caller if a volume is waiting to go offline.
3789  *
3790  * @param[in] vp  The volume we want to know about
3791  *
3792  * @return volume status
3793  *   @retval 0 volume is not waiting to go offline, go ahead and use it
3794  *   @retval nonzero volume is waiting to offline, and give the returned code
3795  *           as an error to anyone accessing the volume
3796  *
3797  * @pre VOL_LOCK is NOT held
3798  * @pre caller holds a heavyweight reference on vp
3799  */
3800 afs_int32
3801 VIsGoingOffline(struct Volume *vp)
3802 {
3803     afs_int32 code;
3804
3805     VOL_LOCK;
3806     code = VIsGoingOffline_r(vp);
3807     VOL_UNLOCK;
3808
3809     return code;
3810 }
3811
3812 /**
3813  * Register an RX call with a volume.
3814  *
3815  * @param[inout] ec        Error code; if unset when passed in, may be set if
3816  *                         the volume starts going offline
3817  * @param[out]   client_ec @see GetVolume
3818  * @param[in] vp   Volume struct
3819  * @param[in] cbv  VCallByVol struct containing the RX call to register
3820  *
3821  * @pre VOL_LOCK held
3822  * @pre caller holds heavy ref on vp
3823  *
3824  * @internal
3825  */
3826 static void
3827 VRegisterCall_r(Error *ec, Error *client_ec, Volume *vp, struct VCallByVol *cbv)
3828 {
3829     if (vp && cbv) {
3830 #ifdef AFS_DEMAND_ATTACH_FS
3831         if (!*ec) {
3832             /* just in case the volume started going offline after we got the
3833              * reference to it... otherwise, if the volume started going
3834              * offline right at the end of GetVolume(), we might race with the
3835              * RX call scanner, and return success and add our cbv to the
3836              * rx_call_list _after_ the scanner has scanned the list. */
3837             *ec = VIsGoingOffline_r(vp);
3838             if (client_ec) {
3839                 *client_ec = *ec;
3840             }
3841         }
3842
3843         while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3844             VWaitStateChange_r(vp);
3845         }
3846 #endif /* AFS_DEMAND_ATTACH_FS */
3847
3848         queue_Prepend(&vp->rx_call_list, cbv);
3849     }
3850 }
3851
3852 /**
3853  * Deregister an RX call with a volume.
3854  *
3855  * @param[in] vp   Volume struct
3856  * @param[in] cbv  VCallByVol struct containing the RX call to deregister
3857  *
3858  * @pre VOL_LOCK held
3859  * @pre caller holds heavy ref on vp
3860  *
3861  * @internal
3862  */
3863 static void
3864 VDeregisterCall_r(Volume *vp, struct VCallByVol *cbv)
3865 {
3866     if (cbv && queue_IsOnQueue(cbv)) {
3867 #ifdef AFS_DEMAND_ATTACH_FS
3868         while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3869             VWaitStateChange_r(vp);
3870         }
3871 #endif /* AFS_DEMAND_ATTACH_FS */
3872
3873         queue_Remove(cbv);
3874     }
3875 }
3876
3877 /***************************************************/
3878 /* get and put volume routines                     */
3879 /***************************************************/
3880
3881 /**
3882  * put back a heavyweight reference to a volume object.
3883  *
3884  * @param[in] vp  volume object pointer
3885  *
3886  * @pre VOL_LOCK held
3887  *
3888  * @post heavyweight volume reference put back.
3889  *       depending on state, volume may have been taken offline,
3890  *       detached, salvaged, freed, etc.
3891  *
3892  * @internal volume package internal use only
3893  */
3894 void
3895 VPutVolume_r(Volume * vp)
3896 {
3897     opr_Verify(--vp->nUsers >= 0);
3898     if (vp->nUsers == 0) {
3899         VCheckOffline(vp);
3900         ReleaseVolumeHeader(vp->header);
3901 #ifdef AFS_DEMAND_ATTACH_FS
3902         if (!VCheckDetach(vp)) {
3903             VCheckSalvage(vp);
3904             VCheckFree(vp);
3905         }
3906 #else /* AFS_DEMAND_ATTACH_FS */
3907         VCheckDetach(vp);
3908 #endif /* AFS_DEMAND_ATTACH_FS */
3909     }
3910 }
3911
3912 void
3913 VPutVolume(Volume * vp)
3914 {
3915     VOL_LOCK;
3916     VPutVolume_r(vp);
3917     VOL_UNLOCK;
3918 }
3919
3920 /**
3921  * Puts a volume reference obtained with VGetVolumeWithCall.
3922  *
3923  * @param[in] vp  Volume struct
3924  * @param[in] cbv VCallByVol struct given to VGetVolumeWithCall, or NULL if none
3925  *
3926  * @pre VOL_LOCK is NOT held
3927  */
3928 void
3929 VPutVolumeWithCall(Volume *vp, struct VCallByVol *cbv)
3930 {
3931     VOL_LOCK;
3932     VDeregisterCall_r(vp, cbv);
3933     VPutVolume_r(vp);
3934     VOL_UNLOCK;
3935 }
3936
3937 /* Get a pointer to an attached volume.  The pointer is returned regardless
3938    of whether or not the volume is in service or on/off line.  An error
3939    code, however, is returned with an indication of the volume's status */
3940 Volume *
3941 VGetVolume(Error * ec, Error * client_ec, VolumeId volumeId)
3942 {
3943     Volume *retVal;
3944     VOL_LOCK;
3945     retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
3946     VOL_UNLOCK;
3947     return retVal;
3948 }
3949
3950 /**
3951  * Get a volume reference associated with an RX call.
3952  *
3953  * @param[out] ec @see GetVolume
3954  * @param[out] client_ec @see GetVolume
3955  * @param[in] volumeId @see GetVolume
3956  * @param[in] ts  How long to wait for going-offline volumes (absolute time).
3957  *                If NULL, wait forever. If ts->tv_sec == 0, return immediately
3958  *                with an error if the volume is going offline.
3959  * @param[in] cbv Contains an RX call to be associated with this volume
3960  *                reference. This call may be interrupted if the volume is
3961  *                requested to go offline while we hold a ref on it. Give NULL
3962  *                to not associate an RX call with this reference.
3963  *
3964  * @return @see GetVolume
3965  *
3966  * @note for LWP builds, ts must be NULL
3967  *
3968  * @note A reference obtained with this function MUST be put back with
3969  *       VPutVolumeWithCall
3970  */
3971 Volume *
3972 VGetVolumeWithCall(Error * ec, Error * client_ec, VolumeId volumeId,
3973                    const struct timespec *ts, struct VCallByVol *cbv)
3974 {
3975     Volume *retVal;
3976     VOL_LOCK;
3977     retVal = GetVolume(ec, client_ec, volumeId, NULL, ts);
3978     VRegisterCall_r(ec, client_ec, retVal, cbv);
3979     VOL_UNLOCK;
3980     return retVal;
3981 }
3982
3983 Volume *
3984 VGetVolume_r(Error * ec, VolumeId volumeId)
3985 {
3986     return GetVolume(ec, NULL, volumeId, NULL, NULL);
3987 }
3988
3989 /* try to get a volume we've previously looked up */
3990 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
3991 Volume *
3992 VGetVolumeByVp_r(Error * ec, Volume * vp)
3993 {
3994     return GetVolume(ec, NULL, vp->hashid, vp, NULL);
3995 }
3996
3997 /**
3998  * private interface for getting a volume handle
3999  *
4000  * @param[out] ec         error code (0 if no error)
4001  * @param[out] client_ec  wire error code to be given to clients
4002  * @param[in]  volumeId   ID of the volume we want
4003  * @param[in]  hint       optional hint for hash lookups, or NULL
4004  * @param[in]  timeout    absolute deadline for waiting for the volume to go
4005  *                        offline, if it is going offline. NULL to wait forever.
4006  *
4007  * @return a volume handle for the specified volume
4008  *  @retval NULL an error occurred, or the volume is in such a state that
4009  *               we cannot load a header or return any volume struct
4010  *
4011  * @note for DAFS, caller must NOT hold a ref count on 'hint'
4012  *
4013  * @note 'timeout' is only checked if the volume is actually going offline; so
4014  *       if you pass timeout->tv_sec = 0, this will exhibit typical
4015  *       nonblocking behavior.
4016  *
4017  * @note for LWP builds, 'timeout' must be NULL
4018  */
4019 static Volume *
4020 GetVolume(Error * ec, Error * client_ec, VolumeId volumeId, Volume * hint,
4021           const struct timespec *timeout)
4022 {
4023     Volume *vp = hint;
4024     /* pull this profiling/debugging code out of regular builds */
4025 #ifdef notdef
4026 #define VGET_CTR_INC(x) x++
4027     unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
4028         0, V7 = 0, V8 = 0, V9 = 0;
4029     unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
4030 #else
4031 #define VGET_CTR_INC(x)
4032 #endif
4033 #ifdef AFS_DEMAND_ATTACH_FS
4034     Volume *avp, * rvp = hint;
4035 #endif
4036
4037     /*
4038      * if VInit is zero, the volume package dynamic
4039      * data structures have not been initialized yet,
4040      * and we must immediately return an error
4041      */
4042     if (VInit == 0) {
4043         vp = NULL;
4044         *ec = VOFFLINE;
4045         if (client_ec) {
4046             *client_ec = VOFFLINE;
4047         }
4048         goto not_inited;
4049     }
4050
4051 #ifdef AFS_DEMAND_ATTACH_FS
4052     if (rvp) {
4053         VCreateReservation_r(rvp);
4054     }
4055 #endif /* AFS_DEMAND_ATTACH_FS */
4056
4057     for (;;) {
4058         *ec = 0;
4059         if (client_ec)
4060             *client_ec = 0;
4061         VGET_CTR_INC(V0);
4062
4063         vp = VLookupVolume_r(ec, volumeId, vp);
4064         if (*ec) {
4065             vp = NULL;
4066             break;
4067         }
4068
4069 #ifdef AFS_DEMAND_ATTACH_FS
4070         if (rvp && (rvp != vp)) {
4071             /* break reservation on old vp */
4072             VCancelReservation_r(rvp);
4073             rvp = NULL;
4074         }
4075 #endif /* AFS_DEMAND_ATTACH_FS */
4076
4077         if (!vp) {
4078             VGET_CTR_INC(V1);
4079             if (VInit < 2) {
4080                 VGET_CTR_INC(V2);
4081                 /* Until we have reached an initialization level of 2
4082                  * we don't know whether this volume exists or not.
4083                  * We can't sleep and retry later because before a volume
4084                  * is attached, the caller tries to get it first.  Just
4085                  * return VOFFLINE and the caller can choose whether to
4086                  * retry the command or not. */
4087                 *ec = VOFFLINE;
4088                 break;
4089             }
4090
4091             *ec = VNOVOL;
4092             break;
4093         }
4094
4095         VGET_CTR_INC(V3);
4096         IncUInt64(&VStats.hdr_gets);
4097
4098 #ifdef AFS_DEMAND_ATTACH_FS
4099         /* block if someone else is performing an exclusive op on this volume */
4100         if (rvp != vp) {
4101             rvp = vp;
4102             VCreateReservation_r(rvp);
4103         }
4104         VWaitExclusiveState_r(vp);
4105
4106         /* short circuit with VNOVOL in the following circumstances:
4107          *
4108          *   - VOL_STATE_ERROR
4109          *   - VOL_STATE_SHUTTING_DOWN
4110          */
4111         if ((V_attachState(vp) == VOL_STATE_ERROR) ||
4112             (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN)) {
4113             *ec = VNOVOL;
4114             vp = NULL;
4115             break;
4116         }
4117
4118         /*
4119          * short circuit with VOFFLINE for VOL_STATE_UNATTACHED/GOING_OFFLINE and
4120          *                    VNOVOL   for VOL_STATE_DELETED
4121          */
4122        if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
4123            (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) ||
4124            (V_attachState(vp) == VOL_STATE_DELETED)) {
4125            if (vp->specialStatus) {
4126                *ec = vp->specialStatus;
4127            } else if (V_attachState(vp) == VOL_STATE_DELETED) {
4128                *ec = VNOVOL;
4129            } else {
4130                *ec = VOFFLINE;
4131            }
4132            vp = NULL;
4133            break;
4134        }
4135
4136         /* allowable states:
4137          *   - PREATTACHED
4138          *   - ATTACHED
4139          *   - SALVAGING
4140          *   - SALVAGE_REQ
4141          */
4142
4143         if (vp->salvage.requested) {
4144             VUpdateSalvagePriority_r(vp);
4145         }
4146
4147         if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
4148             if (vp->specialStatus) {
4149                 *ec = vp->specialStatus;
4150                 vp = NULL;
4151                 break;
4152             }
4153             avp = VAttachVolumeByVp_r(ec, vp, 0);
4154             if (avp) {
4155                 if (vp != avp) {
4156                     /* VAttachVolumeByVp_r can return a pointer
4157                      * != the vp passed to it under certain
4158                      * conditions; make sure we don't leak
4159                      * reservations if that happens */
4160                     vp = avp;
4161                     VCancelReservation_r(rvp);
4162                     rvp = avp;
4163                     VCreateReservation_r(rvp);
4164                 }
4165                 VPutVolume_r(avp);
4166             }
4167             if (*ec) {
4168                 int endloop = 0;
4169                 switch (*ec) {
4170                 case VSALVAGING:
4171                     break;
4172                 case VOFFLINE:
4173                     endloop = 1;
4174                     if (vp->specialStatus) {
4175                         *ec = vp->specialStatus;
4176                     }
4177                     break;
4178
4179                 default:
4180                     if (vp->specialStatus) {
4181                         *ec = vp->specialStatus;
4182                     } else {
4183                         *ec = VNOVOL;
4184                     }
4185                     endloop = 1;
4186                 }
4187                 if (endloop) {
4188                     vp = NULL;
4189                     break;
4190                 }
4191             }
4192         }
4193
4194         if (VIsSalvaging(vp) || (*ec == VSALVAGING)) {
4195             if (client_ec) {
4196                 /* see CheckVnode() in afsfileprocs.c for an explanation
4197                  * of this error code logic */
4198                 afs_uint32 now = FT_ApproxTime();
4199                 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
4200                     *client_ec = VBUSY;
4201                 } else {
4202                     *client_ec = VRESTARTING;
4203                 }
4204             }
4205             *ec = VSALVAGING;
4206             vp = NULL;
4207             break;
4208         }
4209
4210         if (VIsErrorState(V_attachState(vp))) {
4211             /* make sure we don't take a vp in VOL_STATE_ERROR state and use
4212              * it, or transition it out of that state */
4213             if (!*ec) {
4214                 *ec = VNOVOL;
4215             }
4216             vp = NULL;
4217             break;
4218         }
4219
4220         /*
4221          * this test MUST happen after VAttachVolymeByVp, so we have no
4222          * conflicting vol op. (attach2 would have errored out if we had one;
4223          * specifically attach_check_vop must have detected a conflicting vop)
4224          */
4225          opr_Assert(!vp->pending_vol_op || vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningOnline);
4226
4227 #endif /* AFS_DEMAND_ATTACH_FS */
4228
4229         LoadVolumeHeader(ec, vp);
4230         if (*ec) {
4231             VGET_CTR_INC(V6);
4232             /* Only log the error if it was a totally unexpected error.  Simply
4233              * a missing inode is likely to be caused by the volume being deleted */
4234             if (errno != ENXIO || GetLogLevel() != 0)
4235                 Log("Volume %" AFS_VOLID_FMT ": couldn't reread volume header\n",
4236                     afs_printable_VolumeId_lu(vp->hashid));
4237 #ifdef AFS_DEMAND_ATTACH_FS
4238             if (VCanScheduleSalvage()) {
4239                 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0 /*flags*/);
4240             } else {
4241                 FreeVolume(vp);
4242                 vp = NULL;
4243             }
4244 #else /* AFS_DEMAND_ATTACH_FS */
4245             FreeVolume(vp);
4246             vp = NULL;
4247 #endif /* AFS_DEMAND_ATTACH_FS */
4248             break;
4249         }
4250
4251         VGET_CTR_INC(V7);
4252         if (vp->shuttingDown) {
4253             VGET_CTR_INC(V8);
4254             *ec = VNOVOL;
4255             vp = NULL;
4256             break;
4257         }
4258
4259         if (programType == fileServer) {
4260             VGET_CTR_INC(V9);
4261             if (vp->goingOffline) {
4262                 if (timeout && VTimedOut(timeout)) {
4263                     /* we've timed out; don't wait for the vol */
4264                 } else {
4265                     VGET_CTR_INC(V10);
4266 #ifdef AFS_DEMAND_ATTACH_FS
4267                     /* wait for the volume to go offline */
4268                     if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
4269                         VTimedWaitStateChange_r(vp, timeout, NULL);
4270                     }
4271 #elif defined(AFS_PTHREAD_ENV)
4272                     VOL_CV_TIMEDWAIT(&vol_put_volume_cond, timeout, NULL);
4273 #else /* AFS_PTHREAD_ENV */
4274                     /* LWP has no timed wait, so the caller better not be
4275                      * expecting one */
4276                     opr_Assert(!timeout);
4277                     LWP_WaitProcess(VPutVolume);
4278 #endif /* AFS_PTHREAD_ENV */
4279                     continue;
4280                 }
4281             }
4282             if (vp->specialStatus) {
4283                 VGET_CTR_INC(V11);
4284                 *ec = vp->specialStatus;
4285             } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
4286                 VGET_CTR_INC(V12);
4287                 *ec = VNOVOL;
4288             } else if (V_inUse(vp) == 0 || vp->goingOffline) {
4289                 VGET_CTR_INC(V13);
4290                 *ec = VOFFLINE;
4291             } else {
4292                 VGET_CTR_INC(V14);
4293             }
4294         }
4295         break;
4296     }
4297     VGET_CTR_INC(V15);
4298
4299 #ifdef AFS_DEMAND_ATTACH_FS
4300     /* if no error, bump nUsers */
4301     if (vp) {
4302         vp->nUsers++;
4303         VLRU_UpdateAccess_r(vp);
4304     }
4305     if (rvp) {
4306         VCancelReservation_r(rvp);
4307         rvp = NULL;
4308     }
4309     if (client_ec && !*client_ec) {
4310         *client_ec = *ec;
4311     }
4312 #else /* AFS_DEMAND_ATTACH_FS */
4313     /* if no error, bump nUsers */
4314     if (vp) {
4315         vp->nUsers++;
4316     }
4317     if (client_ec) {
4318         *client_ec = *ec;
4319     }
4320 #endif /* AFS_DEMAND_ATTACH_FS */
4321
4322  not_inited:
4323     opr_Assert(vp || *ec);
4324     return vp;
4325 }
4326
4327
4328 /***************************************************/
4329 /* Volume offline/detach routines                  */
4330 /***************************************************/
4331
4332 /* caller MUST hold a heavyweight ref on vp */
4333 #ifdef AFS_DEMAND_ATTACH_FS
4334 void
4335 VTakeOffline_r(Volume * vp)
4336 {
4337     Error error;
4338
4339     opr_Assert(vp->nUsers > 0);
4340     opr_Assert(programType == fileServer);
4341
4342     VCreateReservation_r(vp);
4343     VWaitExclusiveState_r(vp);
4344
4345     vp->goingOffline = 1;
4346     V_needsSalvaged(vp) = 1;
4347
4348     VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
4349     VCancelReservation_r(vp);
4350 }
4351 #else /* AFS_DEMAND_ATTACH_FS */
4352 void
4353 VTakeOffline_r(Volume * vp)
4354 {
4355     opr_Assert(vp->nUsers > 0);
4356     opr_Assert(programType == fileServer);
4357
4358     vp->goingOffline = 1;
4359     V_needsSalvaged(vp) = 1;
4360 }
4361 #endif /* AFS_DEMAND_ATTACH_FS */
4362
4363 void
4364 VTakeOffline(Volume * vp)
4365 {
4366     VOL_LOCK;
4367     VTakeOffline_r(vp);
4368     VOL_UNLOCK;
4369 }
4370
4371 /**
4372  * force a volume offline.
4373  *
4374  * @param[in] vp     volume object pointer
4375  * @param[in] flags  flags (see note below)
4376  *
4377  * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
4378  *       used when VUpdateVolume_r needs to call VForceOffline_r
4379  *       (which in turn would normally call VUpdateVolume_r)
4380  *
4381  * @see VUpdateVolume_r
4382  *
4383  * @pre VOL_LOCK must be held.
4384  *      for DAFS, caller must hold ref.
4385  *
4386  * @note for DAFS, it _is safe_ to call this function from an
4387  *       exclusive state
4388  *
4389  * @post needsSalvaged flag is set.
4390  *       for DAFS, salvage is requested.
4391  *       no further references to the volume through the volume
4392  *       package will be honored.
4393  *       all file descriptor and vnode caches are invalidated.
4394  *
4395  * @warning this is a heavy-handed interface.  it results in
4396  *          a volume going offline regardless of the current
4397  *          reference count state.
4398  *
4399  * @internal  volume package internal use only
4400  */
4401 void
4402 VForceOffline_r(Volume * vp, int flags)
4403 {
4404     Error error;
4405     if (!V_inUse(vp)) {
4406 #ifdef AFS_DEMAND_ATTACH_FS
4407         VChangeState_r(vp, VOL_STATE_ERROR);
4408 #endif
4409         return;
4410     }
4411
4412     strcpy(V_offlineMessage(vp),
4413            "Forced offline due to internal error: volume needs to be salvaged");
4414     Log("Volume %" AFS_VOLID_FMT " forced offline:  it needs salvaging!\n", afs_printable_VolumeId_lu(V_id(vp)));
4415
4416     V_inUse(vp) = 0;
4417     vp->goingOffline = 0;
4418     V_needsSalvaged(vp) = 1;
4419     if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
4420         VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
4421     }
4422
4423 #ifdef AFS_DEMAND_ATTACH_FS
4424     VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0 /*flags*/);
4425 #endif /* AFS_DEMAND_ATTACH_FS */
4426
4427 #ifdef AFS_PTHREAD_ENV
4428     opr_cv_broadcast(&vol_put_volume_cond);
4429 #else /* AFS_PTHREAD_ENV */
4430     LWP_NoYieldSignal(VPutVolume);
4431 #endif /* AFS_PTHREAD_ENV */
4432
4433     VReleaseVolumeHandles_r(vp);
4434 }
4435
4436 /**
4437  * force a volume offline.
4438  *
4439  * @param[in] vp  volume object pointer
4440  *
4441  * @see VForceOffline_r
4442  */
4443 void
4444 VForceOffline(Volume * vp)
4445 {
4446     VOL_LOCK;
4447     VForceOffline_r(vp, 0);
4448     VOL_UNLOCK;
4449 }
4450
4451 /**
4452  * Iterate over the RX calls associated with a volume, and interrupt them.
4453  *
4454  * @param[in] vp The volume whose RX calls we want to scan
4455  *
4456  * @pre VOL_LOCK held
4457  */
4458 static void
4459 VScanCalls_r(struct Volume *vp)
4460 {
4461     struct VCallByVol *cbv, *ncbv;
4462     afs_int32 err;
4463 #ifdef AFS_DEMAND_ATTACH_FS
4464     VolState state_save;
4465 #endif
4466
4467     if (queue_IsEmpty(&vp->rx_call_list))
4468         return; /* no calls to interrupt */
4469     if (!vol_opts.interrupt_rxcall)
4470         return; /* we have no function with which to interrupt calls */
4471     err = VIsGoingOffline_r(vp);
4472     if (!err)
4473         return; /* we're not going offline anymore */
4474
4475 #ifdef AFS_DEMAND_ATTACH_FS
4476     VWaitExclusiveState_r(vp);
4477     state_save = VChangeState_r(vp, VOL_STATE_SCANNING_RXCALLS);
4478     VOL_UNLOCK;
4479 #endif /* AFS_DEMAND_ATTACH_FS */
4480
4481     for(queue_Scan(&vp->rx_call_list, cbv, ncbv, VCallByVol)) {
4482         if (GetLogLevel() != 0) {
4483             struct rx_peer *peer;
4484             char hoststr[16];
4485             peer = rx_PeerOf(rx_ConnectionOf(cbv->call));
4486
4487             Log("Offlining volume %" AFS_VOLID_FMT " while client %s:%u is trying to read "
4488                 "from it; kicking client off with error %ld\n",
4489                 afs_printable_VolumeId_lu(vp->hashid),
4490                 afs_inet_ntoa_r(rx_HostOf(peer), hoststr),
4491                 (unsigned) ntohs(rx_PortOf(peer)),
4492                 (long) err);
4493         }
4494         (*vol_opts.interrupt_rxcall) (cbv->call, err);
4495     }
4496
4497 #ifdef AFS_DEMAND_ATTACH_FS
4498     VOL_LOCK;
4499     VChangeState_r(vp, state_save);
4500 #endif /* AFS_DEMAND_ATTACH_FS */
4501 }
4502
4503 #ifdef AFS_DEMAND_ATTACH_FS
4504 /**
4505  * Wait for a vp to go offline.
4506  *
4507  * @param[out] ec 1 if a salvage on the volume has been requested and
4508  *                salvok == 0, 0 otherwise
4509  * @param[in] vp  The volume to wait for
4510  * @param[in] salvok  If 0, we return immediately with *ec = 1 if the volume
4511  *                    has been requested to salvage. Otherwise we keep waiting
4512  *                    until the volume has gone offline.
4513  *
4514  * @pre VOL_LOCK held
4515  * @pre caller holds a lightweight ref on vp
4516  *
4517  * @note DAFS only
4518  */
4519 static void
4520 VWaitForOfflineByVp_r(Error *ec, struct Volume *vp, int salvok)
4521 {
4522     struct timespec timeout_ts;
4523     const struct timespec *ts;
4524     int timedout = 0;
4525
4526     ts = VOfflineTimeout(&timeout_ts);
4527
4528     *ec = 0;
4529
4530     while (!VIsOfflineState(V_attachState(vp)) && !timedout) {
4531         if (!salvok && vp->salvage.requested) {
4532             *ec = 1;
4533             return;
4534         }
4535         VTimedWaitStateChange_r(vp, ts, &timedout);
4536     }
4537     if (!timedout) {
4538         /* we didn't time out, so the volume must be offline, so we're done */
4539         return;
4540     }
4541
4542     /* If we got here, we timed out waiting for the volume to go offline.
4543      * Kick off the accessing RX calls and wait again */
4544
4545     VScanCalls_r(vp);
4546
4547     while (!VIsOfflineState(V_attachState(vp))) {
4548         if (!salvok && vp->salvage.requested) {
4549             *ec = 1;
4550             return;
4551         }
4552
4553         VWaitStateChange_r(vp);
4554     }
4555 }
4556
4557 #else /* AFS_DEMAND_ATTACH_FS */
4558
4559 /**
4560  * Wait for a volume to go offline.
4561  *
4562  * @pre VOL_LOCK held
4563  *
4564  * @note non-DAFS only (for DAFS, use @see WaitForOfflineByVp_r)
4565  */
4566 static void
4567 VWaitForOffline_r(Error *ec, VolumeId volid)
4568 {
4569     struct Volume *vp;
4570     const struct timespec *ts;
4571 #ifdef AFS_PTHREAD_ENV
4572     struct timespec timeout_ts;
4573 #endif
4574
4575     ts = VOfflineTimeout(&timeout_ts);
4576
4577     vp = GetVolume(ec, NULL, volid, NULL, ts);
4578     if (!vp) {
4579         /* error occurred so bad that we can't even get a vp; we have no
4580          * information on the vol so we don't know whether to wait, so just
4581          * return */
4582         return;
4583     }
4584     if (!VIsGoingOffline_r(vp)) {
4585         /* volume is no longer going offline, so we're done */
4586         VPutVolume_r(vp);
4587         return;
4588     }
4589
4590     /* If we got here, we timed out waiting for the volume to go offline.
4591      * Kick off the accessing RX calls and wait again */
4592
4593     VScanCalls_r(vp);
4594     VPutVolume_r(vp);
4595     vp = NULL;
4596
4597     vp = VGetVolume_r(ec, volid);
4598     if (vp) {
4599         /* In case it was reattached... */
4600         VPutVolume_r(vp);
4601     }
4602 }
4603 #endif /* !AFS_DEMAND_ATTACH_FS */
4604
4605 /* The opposite of VAttachVolume.  The volume header is written to disk, with
4606    the inUse bit turned off.  A copy of the header is maintained in memory,
4607    however (which is why this is VOffline, not VDetach).
4608  */
4609 void
4610 VOffline_r(Volume * vp, char *message)
4611 {
4612     Error error;
4613 #ifndef AFS_DEMAND_ATTACH_FS
4614     VolumeId vid = V_id(vp);
4615 #endif
4616
4617     opr_Assert(programType != volumeUtility && programType != volumeServer);
4618     if (!V_inUse(vp)) {
4619         VPutVolume_r(vp);
4620         return;
4621     }
4622     if (V_offlineMessage(vp)[0] == '\0')
4623         strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4624     V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4625
4626     vp->goingOffline = 1;
4627 #ifdef AFS_DEMAND_ATTACH_FS
4628     VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4629     VCreateReservation_r(vp);
4630     VPutVolume_r(vp);
4631     VWaitForOfflineByVp_r(&error, vp, 1);
4632     VCancelReservation_r(vp);
4633 #else /* AFS_DEMAND_ATTACH_FS */
4634     VPutVolume_r(vp);
4635     VWaitForOffline_r(&error, vid);
4636 #endif /* AFS_DEMAND_ATTACH_FS */
4637 }
4638
4639 #ifdef AFS_DEMAND_ATTACH_FS
4640 /**
4641  * Take a volume offline in order to perform a volume operation.
4642  *
4643  * @param[inout] ec       address in which to store error code
4644  * @param[in]    vp       volume object pointer
4645  * @param[in]    message  volume offline status message
4646  *
4647  * @pre
4648  *    - VOL_LOCK is held
4649  *    - caller MUST hold a heavyweight ref on vp
4650  *
4651  * @post
4652  *    - volume is taken offline
4653  *    - if possible, volume operation is promoted to running state
4654  *    - on failure, *ec is set to nonzero
4655  *
4656  * @note Although this function does not return any value, it may
4657  *       still fail to promote our pending volume operation to
4658  *       a running state.  Any caller MUST check the value of *ec,
4659  *       and MUST NOT blindly assume success.
4660  *
4661  * @warning if the caller does not hold a lightweight ref on vp,
4662  *          then it MUST NOT reference vp after this function
4663  *          returns to the caller.
4664  *
4665  * @internal volume package internal use only
4666  */
4667 void
4668 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
4669 {
4670     int salvok = 1;
4671     opr_Assert(vp->pending_vol_op);
4672     if (!V_inUse(vp)) {
4673         VPutVolume_r(vp);
4674         *ec = 1;
4675         return;
4676     }
4677     if (V_offlineMessage(vp)[0] == '\0')
4678         strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4679     V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4680
4681     vp->goingOffline = 1;
4682     VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4683     VCreateReservation_r(vp);
4684     VPutVolume_r(vp);
4685
4686     if (vp->pending_vol_op->com.programType != salvageServer) {
4687         /* do not give corrupted volumes to the volserver */
4688         salvok = 0;
4689     }
4690
4691     *ec = 0;
4692     VWaitForOfflineByVp_r(ec, vp, salvok);
4693
4694     VCancelReservation_r(vp);
4695 }
4696 #endif /* AFS_DEMAND_ATTACH_FS */
4697
4698 void
4699 VOffline(Volume * vp, char *message)
4700 {
4701     VOL_LOCK;
4702     VOffline_r(vp, message);
4703     VOL_UNLOCK;
4704 }
4705
4706 /* This gets used for the most part by utility routines that don't want
4707  * to keep all the volume headers around.  Generally, the file server won't
4708  * call this routine, because then the offline message in the volume header
4709  * (or other information) won't be available to clients. For NAMEI, also
4710  * close the file handles.  However, the fileserver does call this during
4711  * an attach following a volume operation.
4712  */
4713 void
4714 VDetachVolume_r(Error * ec, Volume * vp)
4715 {
4716 #ifdef FSSYNC_BUILD_CLIENT
4717     VolumeId volume;
4718     struct DiskPartition64 *tpartp;
4719     int notifyServer = 0;
4720     int  useDone = FSYNC_VOL_ON;
4721
4722     if (VCanUseFSSYNC()) {
4723         notifyServer = vp->needsPutBack;
4724         if (V_destroyMe(vp) == DESTROY_ME)
4725             useDone = FSYNC_VOL_LEAVE_OFF;
4726 # ifdef AFS_DEMAND_ATTACH_FS
4727         else if (!V_blessed(vp) || !V_inService(vp))
4728             useDone = FSYNC_VOL_LEAVE_OFF;
4729 # endif
4730     }
4731 # ifdef AFS_DEMAND_ATTACH_FS
4732     if (V_needsSalvaged(vp)) {
4733         notifyServer = 0;
4734         VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, 0);
4735     }
4736 # endif
4737     tpartp = vp->partition;
4738     volume = V_id(vp);
4739 #endif /* FSSYNC_BUILD_CLIENT */
4740
4741     *ec = 0;                    /* always "succeeds" */
4742     DeleteVolumeFromHashTable(vp);
4743     vp->shuttingDown = 1;
4744 #ifdef AFS_DEMAND_ATTACH_FS
4745     DeleteVolumeFromVByPList_r(vp);
4746     VLRU_Delete_r(vp);
4747     VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
4748 #else
4749     if (programType != fileServer)
4750         V_inUse(vp) = 0;
4751 #endif /* AFS_DEMAND_ATTACH_FS */
4752     VPutVolume_r(vp);
4753     /* Will be detached sometime in the future--this is OK since volume is offline */
4754
4755     /* XXX the following code should really be moved to VCheckDetach() since the volume
4756      * is not technically detached until the refcounts reach zero
4757      */
4758 #ifdef FSSYNC_BUILD_CLIENT
4759     if (VCanUseFSSYNC() && notifyServer) {
4760         if (notifyServer == VOL_PUTBACK_DELETE) {
4761             /* Only send FSYNC_VOL_DONE if the volume was actually deleted.
4762              * volserver code will set needsPutBack to VOL_PUTBACK_DELETE
4763              * to signify a deleted volume. */
4764             useDone = FSYNC_VOL_DONE;
4765         }
4766         /*
4767          * Note:  The server is not notified in the case of a bogus volume
4768          * explicitly to make it possible to create a volume, do a partial
4769          * restore, then abort the operation without ever putting the volume
4770          * online.  This is essential in the case of a volume move operation
4771          * between two partitions on the same server.  In that case, there
4772          * would be two instances of the same volume, one of them bogus,
4773          * which the file server would attempt to put on line
4774          */
4775         FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
4776         /* XXX this code path is only hit by volume utilities, thus
4777          * V_BreakVolumeCallbacks will always be NULL.  if we really
4778          * want to break callbacks in this path we need to use FSYNC_VolOp() */
4779 #ifdef notdef
4780         /* Dettaching it so break all callbacks on it */
4781         if (V_BreakVolumeCallbacks) {
4782             Log("volume %u detached; breaking all call backs\n", volume);
4783             (*V_BreakVolumeCallbacks) (volume);
4784         }
4785 #endif
4786     }
4787 #endif /* FSSYNC_BUILD_CLIENT */
4788 }
4789
4790 void
4791 VDetachVolume(Error * ec, Volume * vp)
4792 {
4793     VOL_LOCK;
4794     VDetachVolume_r(ec, vp);
4795     VOL_UNLOCK;
4796 }
4797
4798
4799 /***************************************************/
4800 /* Volume fd/inode handle closing routines         */
4801 /***************************************************/
4802
4803 /* For VDetachVolume, we close all cached file descriptors, but keep
4804  * the Inode handles in case we need to read from a busy volume.
4805  */
4806 /* for demand attach, caller MUST hold ref count on vp */
4807 static void
4808 VCloseVolumeHandles_r(Volume * vp)
4809 {
4810 #ifdef AFS_DEMAND_ATTACH_FS
4811     VolState state_save;
4812
4813     state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
4814
4815     VOL_UNLOCK;
4816 #endif
4817
4818     DFlushVolume(vp->hashid);
4819
4820 #ifdef AFS_DEMAND_ATTACH_FS
4821     VOL_LOCK;
4822 #endif
4823
4824     /* DAFS: VCloseVnodeFiles_r drops the glock internally */
4825     VCloseVnodeFiles_r(vp);
4826
4827 #ifdef AFS_DEMAND_ATTACH_FS
4828     VOL_UNLOCK;
4829 #endif
4830
4831     /* Too time consuming and unnecessary for the volserver */
4832     if (programType == fileServer) {
4833         IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4834         IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4835         IH_CONDSYNC(vp->diskDataHandle);
4836 #ifdef AFS_NAMEI_ENV
4837         IH_CONDSYNC(vp->linkHandle);
4838 #endif /* AFS_NAMEI_ENV */
4839     }
4840
4841     IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
4842     IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
4843     IH_REALLYCLOSE(vp->diskDataHandle);
4844     IH_REALLYCLOSE(vp->linkHandle);
4845
4846 #ifdef AFS_DEMAND_ATTACH_FS
4847     if ((V_attachFlags(vp) & VOL_LOCKED)) {
4848         VUnlockVolume(vp);
4849     }
4850
4851     VOL_LOCK;
4852     VChangeState_r(vp, state_save);
4853 #endif
4854 }
4855
4856 /* For both VForceOffline and VOffline, we close all relevant handles.
4857  * For VOffline, if we re-attach the volume, the files may possible be
4858  * different than before.
4859  */
4860 /* for demand attach, caller MUST hold a ref count on vp */
4861 static void
4862 VReleaseVolumeHandles_r(Volume * vp)
4863 {
4864 #ifdef AFS_DEMAND_ATTACH_FS
4865     VolState state_save;
4866
4867     state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
4868
4869     VOL_UNLOCK;
4870 #endif
4871
4872     DFlushVolume(vp->hashid);
4873
4874 #ifdef AFS_DEMAND_ATTACH_FS
4875     VOL_LOCK;
4876 #endif
4877
4878     VReleaseVnodeFiles_r(vp); /* DAFS: releases the glock internally */
4879
4880 #ifdef AFS_DEMAND_ATTACH_FS
4881     VOL_UNLOCK;
4882 #endif
4883
4884     /* Too time consuming and unnecessary for the volserver */
4885     if (programType == fileServer) {
4886         IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4887         IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4888         IH_CONDSYNC(vp->diskDataHandle);
4889 #ifdef AFS_NAMEI_ENV
4890         IH_CONDSYNC(vp->linkHandle);
4891 #endif /* AFS_NAMEI_ENV */
4892     }
4893
4894     IH_RELEASE(vp->vnodeIndex[vLarge].handle);
4895     IH_RELEASE(vp->vnodeIndex[vSmall].handle);
4896     IH_RELEASE(vp->diskDataHandle);
4897     IH_RELEASE(vp->linkHandle);
4898
4899 #ifdef AFS_DEMAND_ATTACH_FS
4900     if ((V_attachFlags(vp) & VOL_LOCKED)) {
4901         VUnlockVolume(vp);
4902     }
4903
4904     VOL_LOCK;
4905     VChangeState_r(vp, state_save);
4906 #endif
4907 }
4908
4909
4910 /***************************************************/
4911 /* Volume write and fsync routines                 */
4912 /***************************************************/
4913
4914 void
4915 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
4916 {
4917 #ifdef AFS_DEMAND_ATTACH_FS
4918     VolState state_save;
4919
4920     if (flags & VOL_UPDATE_WAIT) {
4921         VCreateReservation_r(vp);
4922         VWaitExclusiveState_r(vp);
4923     }
4924 #endif
4925
4926     *ec = 0;
4927     if (programType == fileServer) {
4928         if (!V_inUse(vp)) {
4929             V_uniquifier(vp) = V_nextVnodeUnique(vp);
4930         } else {
4931             V_uniquifier(vp) =
4932                 V_nextVnodeUnique(vp) + VOLUME_UPDATE_UNIQUIFIER_BUMP;
4933             if (V_uniquifier(vp) < V_nextVnodeUnique(vp)) {
4934                 /* uniquifier rolled over; reset the counters */
4935                 V_nextVnodeUnique(vp) = 2;      /* 1 is reserved for the root vnode */
4936                 V_uniquifier(vp) =
4937                     V_nextVnodeUnique(vp) + VOLUME_UPDATE_UNIQUIFIER_BUMP;
4938             }
4939         }
4940     }
4941
4942 #ifdef AFS_DEMAND_ATTACH_FS
4943     state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4944     VOL_UNLOCK;
4945 #endif
4946
4947     WriteVolumeHeader_r(ec, vp);
4948
4949 #ifdef AFS_DEMAND_ATTACH_FS
4950     VOL_LOCK;
4951     VChangeState_r(vp, state_save);
4952     if (flags & VOL_UPDATE_WAIT) {
4953         VCancelReservation_r(vp);
4954     }
4955 #endif
4956
4957     if (*ec) {
4958         Log("VUpdateVolume: error updating volume header, volume %" AFS_VOLID_FMT " (%s)\n",
4959             afs_printable_VolumeId_lu(V_id(vp)), V_name(vp));
4960         /* try to update on-disk header,
4961          * while preventing infinite recursion */
4962         if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
4963             VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
4964         }
4965     }
4966 }
4967
4968 void
4969 VUpdateVolume(Error * ec, Volume * vp)
4970 {
4971     VOL_LOCK;
4972     VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4973     VOL_UNLOCK;
4974 }
4975
4976 void
4977 VSyncVolume_r(Error * ec, Volume * vp, int flags)
4978 {
4979     FdHandle_t *fdP;
4980     int code;
4981 #ifdef AFS_DEMAND_ATTACH_FS
4982     VolState state_save;
4983 #endif
4984
4985     if (flags & VOL_SYNC_WAIT) {
4986         VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4987     } else {
4988         VUpdateVolume_r(ec, vp, 0);
4989     }
4990     if (!*ec) {
4991 #ifdef AFS_DEMAND_ATTACH_FS
4992         state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4993         VOL_UNLOCK;
4994 #endif
4995         fdP = IH_OPEN(V_diskDataHandle(vp));
4996         opr_Assert(fdP != NULL);
4997         code = FDH_SYNC(fdP);
4998         opr_Assert(code == 0);
4999         FDH_CLOSE(fdP);
5000 #ifdef AFS_DEMAND_ATTACH_FS
5001         VOL_LOCK;
5002         VChangeState_r(vp, state_save);
5003 #endif
5004     }
5005 }
5006
5007 void
5008 VSyncVolume(Error * ec, Volume * vp)
5009 {
5010     VOL_LOCK;
5011     VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
5012     VOL_UNLOCK;
5013 }
5014
5015
5016 /***************************************************/
5017 /* Volume dealloaction routines                    */
5018 /***************************************************/
5019
5020 #ifdef AFS_DEMAND_ATTACH_FS
5021 static void
5022 FreeVolume(Volume * vp)
5023 {
5024     /* free the heap space, iff it's safe.
5025      * otherwise, pull it out of the hash table, so it
5026      * will get deallocated when all refs to it go away */
5027     if (!VCheckFree(vp)) {
5028         DeleteVolumeFromHashTable(vp);
5029         DeleteVolumeFromVByPList_r(vp);
5030
5031         /* make sure we invalidate the header cache entry */
5032         FreeVolumeHeader(vp);
5033     }
5034 }
5035 #endif /* AFS_DEMAND_ATTACH_FS */
5036
5037 static void
5038 ReallyFreeVolume(Volume * vp)
5039 {
5040     int i;
5041     if (!vp)
5042         return;
5043 #ifdef AFS_DEMAND_ATTACH_FS
5044     /* debug */
5045     VChangeState_r(vp, VOL_STATE_FREED);
5046     if (vp->pending_vol_op)
5047         free(vp->pending_vol_op);
5048 #endif /* AFS_DEMAND_ATTACH_FS */
5049     for (i = 0; i < nVNODECLASSES; i++)
5050         if (vp->vnodeIndex[i].bitmap)
5051             free(vp->vnodeIndex[i].bitmap);
5052     FreeVolumeHeader(vp);
5053 #ifndef AFS_DEMAND_ATTACH_FS
5054     DeleteVolumeFromHashTable(vp);
5055 #endif /* AFS_DEMAND_ATTACH_FS */
5056     free(vp);
5057 }
5058
5059 /* check to see if we should shutdown this volume
5060  * returns 1 if volume was freed, 0 otherwise */
5061 #ifdef AFS_DEMAND_ATTACH_FS
5062 static int
5063 VCheckDetach(Volume * vp)
5064 {
5065     int ret = 0;
5066     Error ec = 0;
5067
5068     if (vp->nUsers || vp->nWaiters)
5069         return ret;
5070
5071     if (vp->shuttingDown) {
5072         ret = 1;
5073         if ((programType != fileServer) &&
5074             (V_inUse(vp) == programType) &&
5075             ((V_checkoutMode(vp) == V_VOLUPD) ||
5076              (V_checkoutMode(vp) == V_SECRETLY) ||
5077              ((V_checkoutMode(vp) == V_CLONE) &&
5078               (VolumeWriteable(vp))))) {
5079             V_inUse(vp) = 0;
5080             VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5081             if (ec) {
5082                 Log("VCheckDetach: volume header update for volume %" AFS_VOLID_FMT " "
5083                     "failed with errno %d\n", afs_printable_VolumeId_lu(vp->hashid), errno);
5084             }
5085         }
5086         VReleaseVolumeHandles_r(vp);
5087         VCheckSalvage(vp);
5088         ReallyFreeVolume(vp);
5089         if (programType == fileServer) {
5090             opr_cv_broadcast(&vol_put_volume_cond);
5091         }
5092     }
5093     return ret;
5094 }
5095 #else /* AFS_DEMAND_ATTACH_FS */
5096 static int
5097 VCheckDetach(Volume * vp)
5098 {
5099     int ret = 0;
5100     Error ec = 0;
5101
5102     if (vp->nUsers)
5103         return ret;
5104
5105     if (vp->shuttingDown) {
5106         ret = 1;
5107         if ((programType != fileServer) &&
5108             (V_inUse(vp) == programType) &&
5109             ((V_checkoutMode(vp) == V_VOLUPD) ||
5110              (V_checkoutMode(vp) == V_SECRETLY) ||
5111              ((V_checkoutMode(vp) == V_CLONE) &&
5112               (VolumeWriteable(vp))))) {
5113             V_inUse(vp) = 0;
5114             VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5115             if (ec) {
5116                 Log("VCheckDetach: volume header update for volume %" AFS_VOLID_FMT " failed with errno %d\n",
5117                     afs_printable_VolumeId_lu(vp->hashid), errno);
5118             }
5119         }
5120         VReleaseVolumeHandles_r(vp);
5121         ReallyFreeVolume(vp);
5122         if (programType == fileServer) {
5123 #if defined(AFS_PTHREAD_ENV)
5124             opr_cv_broadcast(&vol_put_volume_cond);
5125 #else /* AFS_PTHREAD_ENV */
5126             LWP_NoYieldSignal(VPutVolume);
5127 #endif /* AFS_PTHREAD_ENV */
5128         }
5129     }
5130     return ret;
5131 }
5132 #endif /* AFS_DEMAND_ATTACH_FS */
5133
5134 /* check to see if we should offline this volume
5135  * return 1 if volume went offline, 0 otherwise */
5136 #ifdef AFS_DEMAND_ATTACH_FS
5137 static int
5138 VCheckOffline(Volume * vp)
5139 {
5140     int ret = 0;
5141
5142     if (vp->goingOffline && !vp->nUsers) {
5143         Error error;
5144         opr_Assert(programType == fileServer);
5145         opr_Assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
5146                (V_attachState(vp) != VOL_STATE_FREED) &&
5147                (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
5148                (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
5149                (V_attachState(vp) != VOL_STATE_DELETED));
5150
5151         /* valid states:
5152          *
5153          * VOL_STATE_GOING_OFFLINE
5154          * VOL_STATE_SHUTTING_DOWN
5155          * VIsErrorState(V_attachState(vp))
5156          * VIsExclusiveState(V_attachState(vp))
5157          */
5158
5159         VCreateReservation_r(vp);
5160         VChangeState_r(vp, VOL_STATE_OFFLINING);
5161
5162         ret = 1;
5163         /* must clear the goingOffline flag before we drop the glock */
5164         vp->goingOffline = 0;
5165         V_inUse(vp) = 0;
5166
5167         VLRU_Delete_r(vp);
5168
5169         /* perform async operations */
5170         VUpdateVolume_r(&error, vp, 0);
5171         VCloseVolumeHandles_r(vp);
5172
5173         if (GetLogLevel() != 0) {
5174             if (V_offlineMessage(vp)[0]) {
5175                 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5176                     afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5177                     V_offlineMessage(vp));
5178             } else {
5179                 Log("VOffline: Volume %lu (%s) is now offline\n",
5180                     afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5181             }
5182         }
5183
5184         /* invalidate the volume header cache entry */
5185         FreeVolumeHeader(vp);
5186
5187         /* if nothing changed state to error or salvaging,
5188          * drop state to unattached */
5189         if (!VIsErrorState(V_attachState(vp))) {
5190             VChangeState_r(vp, VOL_STATE_UNATTACHED);
5191         }
5192         VCancelReservation_r(vp);
5193         /* no usage of vp is safe beyond this point */
5194     }
5195     return ret;
5196 }
5197 #else /* AFS_DEMAND_ATTACH_FS */
5198 static int
5199 VCheckOffline(Volume * vp)
5200 {
5201     int ret = 0;
5202
5203     if (vp->goingOffline && !vp->nUsers) {
5204         Error error;
5205         opr_Assert(programType == fileServer);
5206
5207         ret = 1;
5208         vp->goingOffline = 0;
5209         V_inUse(vp) = 0;
5210         VUpdateVolume_r(&error, vp, 0);
5211         VCloseVolumeHandles_r(vp);
5212         if (GetLogLevel() != 0) {
5213             if (V_offlineMessage(vp)[0]) {
5214                 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5215                     afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5216                     V_offlineMessage(vp));
5217             } else {
5218                 Log("VOffline: Volume %lu (%s) is now offline\n",
5219                     afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5220             }
5221         }
5222         FreeVolumeHeader(vp);
5223 #ifdef AFS_PTHREAD_ENV
5224         opr_cv_broadcast(&vol_put_volume_cond);
5225 #else /* AFS_PTHREAD_ENV */
5226         LWP_NoYieldSignal(VPutVolume);
5227 #endif /* AFS_PTHREAD_ENV */
5228     }
5229     return ret;
5230 }
5231 #endif /* AFS_DEMAND_ATTACH_FS */
5232
5233 /***************************************************/
5234 /* demand attach fs ref counting routines          */
5235 /***************************************************/
5236
5237 #ifdef AFS_DEMAND_ATTACH_FS
5238 /* the following two functions handle reference counting for
5239  * asynchronous operations on volume structs.
5240  *
5241  * their purpose is to prevent a VDetachVolume or VShutdown
5242  * from free()ing the Volume struct during an async i/o op */
5243
5244 /* register with the async volume op ref counter */
5245 /* VCreateReservation_r moved into inline code header because it
5246  * is now needed in vnode.c -- tkeiser 11/20/2007
5247  */
5248
5249 /**
5250  * decrement volume-package internal refcount.
5251  *
5252  * @param vp  volume object pointer
5253  *
5254  * @internal volume package internal use only
5255  *
5256  * @pre
5257  *    @arg VOL_LOCK is held
5258  *    @arg lightweight refcount held
5259  *
5260  * @post volume waiters refcount is decremented; volume may
5261  *       have been deallocated/shutdown/offlined/salvaged/
5262  *       whatever during the process
5263  *
5264  * @warning once you have tossed your last reference (you can acquire
5265  *          lightweight refs recursively) it is NOT SAFE to reference
5266  *          a volume object pointer ever again
5267  *
5268  * @see VCreateReservation_r
5269  *
5270  * @note DEMAND_ATTACH_FS only
5271  */
5272 void
5273 VCancelReservation_r(Volume * vp)
5274 {
5275     opr_Verify(--vp->nWaiters >= 0);
5276     if (vp->nWaiters == 0) {
5277         VCheckOffline(vp);
5278         if (!VCheckDetach(vp)) {
5279             VCheckSalvage(vp);
5280             VCheckFree(vp);
5281         }
5282     }
5283 }
5284
5285 /* check to see if we should free this volume now
5286  * return 1 if volume was freed, 0 otherwise */
5287 static int
5288 VCheckFree(Volume * vp)
5289 {
5290     int ret = 0;
5291     if ((vp->nUsers == 0) &&
5292         (vp->nWaiters == 0) &&
5293         !(V_attachFlags(vp) & (VOL_IN_HASH |
5294                                VOL_ON_VBYP_LIST |
5295                                VOL_IS_BUSY |
5296                                VOL_ON_VLRU))) {
5297         ReallyFreeVolume(vp);
5298         ret = 1;
5299     }
5300     return ret;
5301 }
5302 #endif /* AFS_DEMAND_ATTACH_FS */
5303
5304
5305 /***************************************************/
5306 /* online volume operations routines               */
5307 /***************************************************/
5308
5309 #ifdef AFS_DEMAND_ATTACH_FS
5310 /**
5311  * register a volume operation on a given volume.
5312  *
5313  * @param[in] vp       volume object
5314  * @param[in] vopinfo  volume operation info object
5315  *
5316  * @pre VOL_LOCK is held
5317  *
5318  * @post volume operation info object attached to volume object.
5319  *       volume operation statistics updated.
5320  *
5321  * @note by "attached" we mean a copy of the passed in object is made
5322  *
5323  * @internal volume package internal use only
5324  */
5325 int
5326 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5327 {
5328     FSSYNC_VolOp_info * info;
5329
5330     /* attach a vol op info node to the volume struct */
5331     info = malloc(sizeof(FSSYNC_VolOp_info));
5332     opr_Assert(info != NULL);
5333     memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
5334     vp->pending_vol_op = info;
5335
5336     /* update stats */
5337     vp->stats.last_vol_op = FT_ApproxTime();
5338     vp->stats.vol_ops++;
5339     IncUInt64(&VStats.vol_ops);
5340
5341     return 0;
5342 }
5343
5344 /**
5345  * deregister the volume operation attached to this volume.
5346  *
5347  * @param[in] vp  volume object pointer
5348  *
5349  * @pre VOL_LOCK is held
5350  *
5351  * @post the volume operation info object is detached from the volume object
5352  *
5353  * @internal volume package internal use only
5354  */
5355 int
5356 VDeregisterVolOp_r(Volume * vp)
5357 {
5358     if (vp->pending_vol_op) {
5359         free(vp->pending_vol_op);
5360         vp->pending_vol_op = NULL;
5361     }
5362     return 0;
5363 }
5364 #endif /* AFS_DEMAND_ATTACH_FS */
5365
5366 /**
5367  * determine whether it is safe to leave a volume online during
5368  * the volume operation described by the vopinfo object.
5369  *
5370  * @param[in] vp        volume object
5371  * @param[in] vopinfo   volume operation info object
5372  *
5373  * @return whether it is safe to leave volume online
5374  *    @retval 0  it is NOT SAFE to leave the volume online
5375  *    @retval 1  it is safe to leave the volume online during the operation
5376  *
5377  * @pre
5378  *    @arg VOL_LOCK is held
5379  *    @arg disk header attached to vp (heavyweight ref on vp will guarantee
5380  *         this condition is met)
5381  *
5382  * @internal volume package internal use only
5383  */
5384 int
5385 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5386 {
5387     return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
5388             (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5389             (vopinfo->com.reason == V_READONLY ||
5390              (!VolumeWriteable(vp) &&
5391               (vopinfo->com.reason == V_CLONE ||
5392                vopinfo->com.reason == V_DUMP)))));
5393 }
5394
5395 /**
5396  * same as VVolOpLeaveOnline_r, but does not require a volume with an attached
5397  * header.
5398  *
5399  * @param[in] vp        volume object
5400  * @param[in] vopinfo   volume operation info object
5401  *
5402  * @return whether it is safe to leave volume online
5403  *    @retval 0  it is NOT SAFE to leave the volume online
5404  *    @retval 1  it is safe to leave the volume online during the operation
5405  *    @retval -1 unsure; volume header is required in order to know whether or
5406  *               not is is safe to leave the volume online
5407  *
5408  * @pre VOL_LOCK is held
5409  *
5410  * @internal volume package internal use only
5411  */
5412 int
5413 VVolOpLeaveOnlineNoHeader_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5414 {
5415     /* follow the logic in VVolOpLeaveOnline_r; this is the same, except
5416      * assume that we don't know VolumeWriteable; return -1 if the answer
5417      * depends on VolumeWriteable */
5418
5419     if (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline) {
5420         return 1;
5421     }
5422     if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5423         vopinfo->com.reason == V_READONLY) {
5424
5425         return 1;
5426     }
5427     if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5428         (vopinfo->com.reason == V_CLONE ||
5429          vopinfo->com.reason == V_DUMP)) {
5430
5431         /* must know VolumeWriteable */
5432         return -1;
5433     }
5434     return 0;
5435 }
5436
5437 /**
5438  * determine whether VBUSY should be set during this volume operation.
5439  *
5440  * @param[in] vp        volume object
5441  * @param[in] vopinfo   volume operation info object
5442  *
5443  * @return whether VBUSY should be set
5444  *   @retval 0  VBUSY does NOT need to be set
5445  *   @retval 1  VBUSY SHOULD be set
5446  *
5447  * @pre VOL_LOCK is held
5448  *
5449  * @internal volume package internal use only
5450  */
5451 int
5452 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5453 {
5454     return ((vopinfo->com.command == FSYNC_VOL_OFF &&
5455             vopinfo->com.reason == FSYNC_SALVAGE) ||
5456             (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5457             (vopinfo->com.reason == V_CLONE ||
5458              vopinfo->com.reason == V_DUMP)));
5459 }
5460
5461
5462 /***************************************************/
5463 /* online salvager routines                        */
5464 /***************************************************/
5465 #if defined(AFS_DEMAND_ATTACH_FS)
5466
5467 /**
5468  * offline a volume to let it be salvaged.
5469  *
5470  * @param[in] vp  Volume to offline
5471  *
5472  * @return whether we offlined the volume successfully
5473  *  @retval 0 volume was not offlined
5474  *  @retval 1 volume is now offline
5475  *
5476  * @note This is similar to VCheckOffline, but slightly different. We do not
5477  *       deal with vp->goingOffline, and we try to avoid touching the volume
5478  *       header except just to set needsSalvaged
5479  *
5480  * @pre VOL_LOCK held
5481  * @pre vp->nUsers == 0
5482  * @pre V_attachState(vp) == VOL_STATE_SALVAGE_REQ
5483  */
5484 static int
5485 VOfflineForSalvage_r(struct Volume *vp)
5486 {
5487     Error error;
5488
5489     VCreateReservation_r(vp);
5490     VWaitExclusiveState_r(vp);
5491
5492     if (vp->nUsers || V_attachState(vp) == VOL_STATE_SALVAGING) {
5493         /* Someone's using the volume, or someone got to scheduling the salvage
5494          * before us. I don't think either of these should be possible, as we
5495          * should gain no new heavyweight references while we're trying to
5496          * salvage, but just to be sure... */
5497         VCancelReservation_r(vp);
5498         return 0;
5499     }
5500
5501     VChangeState_r(vp, VOL_STATE_OFFLINING);
5502
5503     VLRU_Delete_r(vp);
5504     if (vp->header) {
5505         V_needsSalvaged(vp) = 1;
5506         /* ignore error; updating needsSalvaged is just best effort */
5507         VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
5508     }
5509     VCloseVolumeHandles_r(vp);
5510
5511     FreeVolumeHeader(vp);
5512
5513     /* volume has been effectively offlined; we can mark it in the SALVAGING
5514      * state now, which lets FSSYNC give it away */
5515     VChangeState_r(vp, VOL_STATE_SALVAGING);
5516
5517     VCancelReservation_r(vp);
5518
5519     return 1;
5520 }
5521
5522 /**
5523  * check whether a salvage needs to be performed on this volume.
5524  *
5525  * @param[in] vp   pointer to volume object
5526  *
5527  * @return status code
5528  *    @retval VCHECK_SALVAGE_OK (0)         no pending salvage
5529  *    @retval VCHECK_SALVAGE_SCHEDULED (1)  salvage has been scheduled
5530  *    @retval VCHECK_SALVAGE_ASYNC (2)      salvage being scheduled
5531  *    @retval VCHECK_SALVAGE_DENIED (3)     salvage not scheduled; denied
5532  *    @retval VCHECK_SALVAGE_FAIL (4)       salvage not scheduled; failed
5533  *
5534  * @pre VOL_LOCK is held
5535  *
5536  * @post if salvage request flag is set and nUsers and nWaiters are zero,
5537  *       then a salvage will be requested
5538  *
5539  * @note this is one of the event handlers called by VCancelReservation_r
5540  *
5541  * @note the caller must check if the volume needs to be freed after calling
5542  *       this; the volume may not have any references or be on any lists after
5543  *       we return, and we do not free it
5544  *
5545  * @see VCancelReservation_r
5546  *
5547  * @internal volume package internal use only.
5548  */
5549 static int
5550 VCheckSalvage(Volume * vp)
5551 {
5552     int ret = VCHECK_SALVAGE_OK;
5553
5554 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5555     if (!vp->salvage.requested) {
5556         return VCHECK_SALVAGE_OK;
5557     }
5558     if (vp->nUsers) {
5559         return VCHECK_SALVAGE_ASYNC;
5560     }
5561
5562     /* prevent recursion; some of the code below creates and removes
5563      * lightweight refs, which can call VCheckSalvage */
5564     if (vp->salvage.scheduling) {
5565         return VCHECK_SALVAGE_ASYNC;
5566     }
5567     vp->salvage.scheduling = 1;
5568
5569     if (V_attachState(vp) == VOL_STATE_SALVAGE_REQ) {
5570         if (!VOfflineForSalvage_r(vp)) {
5571             vp->salvage.scheduling = 0;
5572             return VCHECK_SALVAGE_FAIL;
5573         }
5574     }
5575
5576     if (vp->salvage.requested) {
5577         ret = VScheduleSalvage_r(vp);
5578     }
5579     vp->salvage.scheduling = 0;
5580 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5581     return ret;
5582 }
5583
5584 /**
5585  * request volume salvage.
5586  *
5587  * @param[out] ec      computed client error code
5588  * @param[in]  vp      volume object pointer
5589  * @param[in]  reason  reason code (passed to salvageserver via SALVSYNC)
5590  * @param[in]  flags   see flags note below
5591  *
5592  * @note flags:
5593  *       VOL_SALVAGE_NO_OFFLINE do not need to wait to offline the volume; it has
5594  *                              not been fully attached
5595  *
5596  * @pre VOL_LOCK is held.
5597  *
5598  * @post volume state is changed.
5599  *       for fileserver, salvage will be requested once refcount reaches zero.
5600  *
5601  * @return operation status code
5602  *   @retval 0  volume salvage will occur
5603  *   @retval 1  volume salvage could not be scheduled
5604  *
5605  * @note DAFS only
5606  *
5607  * @note in the fileserver, this call does not synchronously schedule a volume
5608  *       salvage. rather, it sets volume state so that when volume refcounts
5609  *       reach zero, a volume salvage will occur. by "refcounts", we mean both
5610  *       nUsers and nWaiters must be zero.
5611  *
5612  * @internal volume package internal use only.
5613  */
5614 int
5615 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
5616 {
5617     int code = 0;
5618     /*
5619      * for DAFS volume utilities that are not supposed to schedule salvages,
5620      * just transition to error state instead
5621      */
5622     if (!VCanScheduleSalvage()) {
5623         VChangeState_r(vp, VOL_STATE_ERROR);
5624         *ec = VSALVAGE;
5625         return 1;
5626     }
5627
5628     if (programType != fileServer && !VCanUseFSSYNC()) {
5629         VChangeState_r(vp, VOL_STATE_ERROR);
5630         *ec = VSALVAGE;
5631         return 1;
5632     }
5633
5634     if (!vp->salvage.requested) {
5635         vp->salvage.requested = 1;
5636         vp->salvage.reason = reason;
5637         vp->stats.last_salvage = FT_ApproxTime();
5638
5639         /* Note that it is not possible for us to reach this point if a
5640          * salvage is already running on this volume (even if the fileserver
5641          * was restarted during the salvage). If a salvage were running, the
5642          * salvager would have write-locked the volume header file, so when
5643          * we tried to lock the volume header, the lock would have failed,
5644          * and we would have failed during attachment prior to calling
5645          * VRequestSalvage. So we know that we can schedule salvages without
5646          * fear of a salvage already running for this volume. */
5647
5648         if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
5649
5650             /* if we don't need to offline the volume, we can go directly
5651              * to SALVAGING. SALVAGING says the volume is offline and is
5652              * either salvaging or ready to be handed to the salvager.
5653              * SALVAGE_REQ says that we want to salvage the volume, but we
5654              * are waiting for it to go offline first. */
5655             if (flags & VOL_SALVAGE_NO_OFFLINE) {
5656                 VChangeState_r(vp, VOL_STATE_SALVAGING);
5657             } else {
5658                 VChangeState_r(vp, VOL_STATE_SALVAGE_REQ);
5659                 if (vp->nUsers == 0) {
5660                     /* normally VOfflineForSalvage_r would be called from
5661                      * PutVolume et al when nUsers reaches 0, but if
5662                      * it's already 0, just do it ourselves, since PutVolume
5663                      * isn't going to get called */
5664                     VOfflineForSalvage_r(vp);
5665                 }
5666             }
5667             /* If we are non-fileserver, we're telling the fileserver to
5668              * salvage the vol, so we don't need to give it back separately. */
5669             vp->needsPutBack = 0;
5670
5671             *ec = VSALVAGING;
5672         } else {
5673             Log("VRequestSalvage: volume %" AFS_VOLID_FMT " online salvaged too many times; forced offline.\n", afs_printable_VolumeId_lu(vp->hashid));
5674
5675             /* make sure neither VScheduleSalvage_r nor
5676              * VUpdateSalvagePriority_r try to schedule another salvage */
5677             vp->salvage.requested = vp->salvage.scheduled = 0;
5678
5679             VChangeState_r(vp, VOL_STATE_ERROR);
5680             *ec = VSALVAGE;
5681             code = 1;
5682         }
5683         if ((flags & VOL_SALVAGE_NO_OFFLINE)) {
5684             /* Here, we free the header for the volume, but make sure to only
5685              * do this if VOL_SALVAGE_NO_OFFLINE is specified. The reason for
5686              * this requires a bit of explanation.
5687              *
5688              * Normally, the volume header will be freed when the volume goes
5689              * goes offline. However, if VOL_SALVAGE_NO_OFFLINE has been
5690              * specified, the volume was in the process of being attached when
5691              * we discovered that it needed salvaging. Thus, the volume will
5692              * never go offline, since it never went fully online in the first
5693              * place. Specifically, we do not call VOfflineForSalvage_r above,
5694              * and we never get rid of the volume via VPutVolume_r; the volume
5695              * has not been initialized enough for those to work.
5696              *
5697              * So instead, explicitly free the volume header here. If we do not
5698              * do this, we are wasting a header that some other volume could be
5699              * using, since the header remains attached to the volume. Also if
5700              * we do not free the header here, we end up with a volume where
5701              * nUsers == 0, but the volume has a header that is not on the
5702              * header LRU. Some code expects that all nUsers == 0 volumes have
5703              * their header on the header LRU (or have no header).
5704              *
5705              * Also note that we must not free the volume header here if
5706              * VOL_SALVAGE_NO_OFFLINE is not set. Since, if
5707              * VOL_SALVAGE_NO_OFFLINE is not set, someone else may have a
5708              * reference to this volume, and they assume they can use the
5709              * volume's header. If we free the volume out from under them, they
5710              * can easily segfault.
5711              */
5712             FreeVolumeHeader(vp);
5713         }
5714     }
5715     return code;
5716 }
5717
5718 /**
5719  * update salvageserver scheduling priority for a volume.
5720  *
5721  * @param[in] vp  pointer to volume object
5722  *
5723  * @return operation status
5724  *   @retval 0  success
5725  *   @retval 1  request denied, or SALVSYNC communications failure
5726  *
5727  * @pre VOL_LOCK is held.
5728  *
5729  * @post in-core salvage priority counter is incremented.  if at least
5730  *       SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
5731  *       last SALVSYNC_RAISEPRIO request, we contact the salvageserver
5732  *       to update its priority queue.  if no salvage is scheduled,
5733  *       this function is a no-op.
5734  *
5735  * @note DAFS fileserver only
5736  *
5737  * @note this should be called whenever a VGetVolume fails due to a
5738  *       pending salvage request
5739  *
5740  * @todo should set exclusive state and drop glock around salvsync call
5741  *
5742  * @internal volume package internal use only.
5743  */
5744 int
5745 VUpdateSalvagePriority_r(Volume * vp)
5746 {
5747     int ret=0;
5748
5749 #ifdef SALVSYNC_BUILD_CLIENT
5750     afs_uint32 now;
5751     int code;
5752
5753     vp->salvage.prio++;
5754     now = FT_ApproxTime();
5755
5756     /* update the salvageserver priority queue occasionally so that
5757      * frequently requested volumes get moved to the head of the queue
5758      */
5759     if ((vp->salvage.scheduled) &&
5760         (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
5761         code = SALVSYNC_SalvageVolume(vp->hashid,
5762                                       VPartitionPath(vp->partition),
5763                                       SALVSYNC_RAISEPRIO,
5764                                       vp->salvage.reason,
5765                                       vp->salvage.prio,
5766                                       NULL);
5767         vp->stats.last_salvage_req = now;
5768         if (code != SYNC_OK) {
5769             ret = 1;
5770         }
5771     }
5772 #endif /* SALVSYNC_BUILD_CLIENT */
5773     return ret;
5774 }
5775
5776
5777 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5778
5779 /* A couple of little helper functions. These return true if we tried to
5780  * use this mechanism to schedule a salvage, false if we haven't tried.
5781  * If we did try a salvage then the results are contained in code.
5782  */
5783
5784 static_inline int
5785 try_SALVSYNC(Volume *vp, char *partName, int *code) {
5786 #ifdef SALVSYNC_BUILD_CLIENT
5787     if (VCanUseSALVSYNC()) {
5788         Log("Scheduling salvage for volume %" AFS_VOLID_FMT " on part %s over SALVSYNC\n",
5789             afs_printable_VolumeId_lu(vp->hashid), partName);
5790
5791         /* can't use V_id() since there's no guarantee
5792          * we have the disk data header at this point */
5793         *code = SALVSYNC_SalvageVolume(vp->hashid,
5794                                        partName,
5795                                        SALVSYNC_SALVAGE,
5796                                        vp->salvage.reason,
5797                                        vp->salvage.prio,
5798                                        NULL);
5799         return 1;
5800     }
5801 #endif
5802     return 0;
5803 }
5804
5805 static_inline int
5806 try_FSSYNC(Volume *vp, char *partName, int *code) {
5807 #ifdef FSSYNC_BUILD_CLIENT
5808     if (VCanUseFSSYNC()) {
5809         Log("Scheduling salvage for volume %" AFS_VOLID_FMT " on part %s over FSSYNC\n",
5810             afs_printable_VolumeId_lu(vp->hashid), partName);
5811
5812         /*
5813          * If we aren't the fileserver, tell the fileserver the volume
5814          * needs to be salvaged. We could directly tell the
5815          * salvageserver, but the fileserver keeps track of some stats
5816          * related to salvages, and handles some other salvage-related
5817          * complications for us.
5818          */
5819         *code = FSYNC_VolOp(vp->hashid, partName,
5820                             FSYNC_VOL_FORCE_ERROR, FSYNC_SALVAGE, NULL);
5821         return 1;
5822     }
5823 #endif /* FSSYNC_BUILD_CLIENT */
5824     return 0;
5825 }
5826
5827 /**
5828  * schedule a salvage with the salvage server or fileserver.
5829  *
5830  * @param[in] vp  pointer to volume object
5831  *
5832  * @return operation status
5833  *    @retval VCHECK_SALVAGE_OK (0)         no pending salvage
5834  *    @retval VCHECK_SALVAGE_SCHEDULED (1)  salvage has been scheduled
5835  *    @retval VCHECK_SALVAGE_ASYNC (2)      salvage being scheduled
5836  *    @retval VCHECK_SALVAGE_DENIED (3)     salvage not scheduled; denied
5837  *    @retval VCHECK_SALVAGE_FAIL (4)       salvage not scheduled; failed
5838  *
5839  * @pre
5840  *    @arg VOL_LOCK is held.
5841  *    @arg nUsers and nWaiters should be zero.
5842  *
5843  * @post salvageserver or fileserver is sent a salvage request
5844  *
5845  * @note If we are the fileserver, the request will be sent to the salvage
5846  * server over SALVSYNC. If we are not the fileserver, the request will be
5847  * sent to the fileserver over FSSYNC (FSYNC_VOL_FORCE_ERROR/FSYNC_SALVAGE).
5848  *
5849  * @note the caller must check if the volume needs to be freed after calling
5850  *       this; the volume may not have any references or be on any lists after
5851  *       we return, and we do not free it
5852  *
5853  * @note DAFS only
5854  *
5855  * @internal volume package internal use only.
5856  */
5857 static int
5858 VScheduleSalvage_r(Volume * vp)
5859 {
5860     int ret = VCHECK_SALVAGE_SCHEDULED;
5861     int code = 0;
5862     VolState state_save;
5863     VThreadOptions_t * thread_opts;
5864     char partName[16];
5865
5866     opr_Verify(VCanUseSALVSYNC() || VCanUseFSSYNC());
5867
5868     if (vp->nWaiters || vp->nUsers) {
5869         return VCHECK_SALVAGE_ASYNC;
5870     }
5871
5872     /* prevent endless salvage,attach,salvage,attach,... loops */
5873     if (vp->stats.salvages >= SALVAGE_COUNT_MAX) {
5874         return VCHECK_SALVAGE_FAIL;
5875     }
5876
5877     /*
5878      * don't perform salvsync ops on certain threads
5879      */
5880     thread_opts = pthread_getspecific(VThread_key);
5881     if (thread_opts == NULL) {
5882         thread_opts = &VThread_defaults;
5883     }
5884     if (thread_opts->disallow_salvsync || vol_disallow_salvsync) {
5885         return VCHECK_SALVAGE_ASYNC;
5886     }
5887
5888     if (vp->salvage.scheduled) {
5889         return VCHECK_SALVAGE_SCHEDULED;
5890     }
5891
5892     VCreateReservation_r(vp);
5893     VWaitExclusiveState_r(vp);
5894
5895     /*
5896      * XXX the scheduling process should really be done asynchronously
5897      *     to avoid fssync deadlocks
5898      */
5899     if (vp->salvage.scheduled) {
5900         ret = VCHECK_SALVAGE_SCHEDULED;
5901     } else {
5902         /* if we haven't previously scheduled a salvage, do so now
5903          *
5904          * set the volume to an exclusive state and drop the lock
5905          * around the SALVSYNC call
5906          */
5907         strlcpy(partName, vp->partition->name, sizeof(partName));
5908         state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
5909         VOL_UNLOCK;
5910
5911         opr_Verify(try_SALVSYNC(vp, partName, &code)
5912                    || try_FSSYNC(vp, partName, &code));
5913
5914         VOL_LOCK;
5915         VChangeState_r(vp, state_save);
5916
5917         if (code == SYNC_OK) {
5918             ret = VCHECK_SALVAGE_SCHEDULED;
5919             vp->salvage.scheduled = 1;
5920             vp->stats.last_salvage_req = FT_ApproxTime();
5921             if (VCanUseSALVSYNC()) {
5922                 /* don't record these stats for non-fileservers; let the
5923                  * fileserver take care of these */
5924                 vp->stats.salvages++;
5925                 IncUInt64(&VStats.salvages);
5926             }
5927         } else {
5928             switch(code) {
5929             case SYNC_BAD_COMMAND:
5930             case SYNC_COM_ERROR:
5931                 ret = VCHECK_SALVAGE_FAIL;
5932                 break;
5933             case SYNC_DENIED:
5934                 ret = VCHECK_SALVAGE_DENIED;
5935                 Log("VScheduleSalvage_r: Salvage request for volume %" AFS_VOLID_FMT " "
5936                     "denied\n", afs_printable_VolumeId_lu(vp->hashid));
5937                 break;
5938             case SYNC_FAILED:
5939                 ret = VCHECK_SALVAGE_FAIL;
5940                 Log("VScheduleSalvage_r: Salvage request for volume %" AFS_VOLID_FMT " "
5941                     "failed\n", afs_printable_VolumeId_lu(vp->hashid));
5942                 break;
5943             default:
5944                 ret = VCHECK_SALVAGE_FAIL;
5945                 Log("VScheduleSalvage_r: Salvage request for volume %" AFS_VOLID_FMT " "
5946                     "received unknown protocol error %d\n",
5947                     afs_printable_VolumeId_lu(vp->hashid), code);
5948                 break;
5949             }
5950
5951             if (VCanUseFSSYNC()) {
5952                 VChangeState_r(vp, VOL_STATE_ERROR);
5953             }
5954         }
5955     }
5956
5957     /* NB: this is cancelling the reservation we obtained above, but we do
5958      * not call VCancelReservation_r, since that may trigger the vp dtor,
5959      * possibly free'ing the vp. We need to keep the vp around after
5960      * this, as the caller may reference vp without any refs. Instead, it
5961      * is the duty of the caller to inspect 'vp' after we return to see if
5962      * needs to be freed. */
5963     opr_Verify(--vp->nWaiters >= 0);
5964     return ret;
5965 }
5966 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5967
5968 #ifdef SALVSYNC_BUILD_CLIENT
5969
5970 /**
5971  * connect to the salvageserver SYNC service.
5972  *
5973  * @return operation status
5974  *    @retval 0 failure
5975  *    @retval 1 success
5976  *
5977  * @post connection to salvageserver SYNC service established
5978  *
5979  * @see VConnectSALV_r
5980  * @see VDisconnectSALV
5981  * @see VReconnectSALV
5982  */
5983 int
5984 VConnectSALV(void)
5985 {
5986     int retVal;
5987     VOL_LOCK;
5988     retVal = VConnectSALV_r();
5989     VOL_UNLOCK;
5990     return retVal;
5991 }
5992
5993 /**
5994  * connect to the salvageserver SYNC service.
5995  *
5996  * @return operation status
5997  *    @retval 0 failure
5998  *    @retval 1 success
5999  *
6000  * @pre VOL_LOCK is held.
6001  *
6002  * @post connection to salvageserver SYNC service established
6003  *
6004  * @see VConnectSALV
6005  * @see VDisconnectSALV_r
6006  * @see VReconnectSALV_r
6007  * @see SALVSYNC_clientInit
6008  *
6009  * @internal volume package internal use only.
6010  */
6011 int
6012 VConnectSALV_r(void)
6013 {
6014     return SALVSYNC_clientInit();
6015 }
6016
6017 /**
6018  * disconnect from the salvageserver SYNC service.
6019  *
6020  * @return operation status
6021  *    @retval 0 success
6022  *
6023  * @pre client should have a live connection to the salvageserver
6024  *
6025  * @post connection to salvageserver SYNC service destroyed
6026  *
6027  * @see VDisconnectSALV_r
6028  * @see VConnectSALV
6029  * @see VReconnectSALV
6030  */
6031 int
6032 VDisconnectSALV(void)
6033 {
6034     VOL_LOCK;
6035     VDisconnectSALV_r();
6036     VOL_UNLOCK;
6037     return 0;
6038 }
6039
6040 /**
6041  * disconnect from the salvageserver SYNC service.
6042  *
6043  * @return operation status
6044  *    @retval 0 success
6045  *
6046  * @pre
6047  *    @arg VOL_LOCK is held.
6048  *    @arg client should have a live connection to the salvageserver.
6049  *
6050  * @post connection to salvageserver SYNC service destroyed
6051  *
6052  * @see VDisconnectSALV
6053  * @see VConnectSALV_r
6054  * @see VReconnectSALV_r
6055  * @see SALVSYNC_clientFinis
6056  *
6057  * @internal volume package internal use only.
6058  */
6059 int
6060 VDisconnectSALV_r(void)
6061 {
6062     return SALVSYNC_clientFinis();
6063 }
6064
6065 /**
6066  * disconnect and then re-connect to the salvageserver SYNC service.
6067  *
6068  * @return operation status
6069  *    @retval 0 failure
6070  *    @retval 1 success
6071  *
6072  * @pre client should have a live connection to the salvageserver
6073  *
6074  * @post old connection is dropped, and a new one is established
6075  *
6076  * @see VConnectSALV
6077  * @see VDisconnectSALV
6078  * @see VReconnectSALV_r
6079  */
6080 int
6081 VReconnectSALV(void)
6082 {
6083     int retVal;
6084     VOL_LOCK;
6085     retVal = VReconnectSALV_r();
6086     VOL_UNLOCK;
6087     return retVal;
6088 }
6089
6090 /**
6091  * disconnect and then re-connect to the salvageserver SYNC service.
6092  *
6093  * @return operation status
6094  *    @retval 0 failure
6095  *    @retval 1 success
6096  *
6097  * @pre
6098  *    @arg VOL_LOCK is held.
6099  *    @arg client should have a live connection to the salvageserver.
6100  *
6101  * @post old connection is dropped, and a new one is established
6102  *
6103  * @see VConnectSALV_r
6104  * @see VDisconnectSALV
6105  * @see VReconnectSALV
6106  * @see SALVSYNC_clientReconnect
6107  *
6108  * @internal volume package internal use only.
6109  */
6110 int
6111 VReconnectSALV_r(void)
6112 {
6113     return SALVSYNC_clientReconnect();
6114 }
6115 #endif /* SALVSYNC_BUILD_CLIENT */
6116 #endif /* AFS_DEMAND_ATTACH_FS */
6117
6118
6119 /***************************************************/
6120 /* FSSYNC routines                                 */
6121 /***************************************************/
6122
6123 /* This must be called by any volume utility which needs to run while the
6124    file server is also running.  This is separated from VInitVolumePackage2 so
6125    that a utility can fork--and each of the children can independently
6126    initialize communication with the file server */
6127 #ifdef FSSYNC_BUILD_CLIENT
6128 /**
6129  * connect to the fileserver SYNC service.
6130  *
6131  * @return operation status
6132  *    @retval 0 failure
6133  *    @retval 1 success
6134  *
6135  * @pre
6136  *    @arg VInit must equal 2.
6137  *    @arg Program Type must not be fileserver or salvager.
6138  *
6139  * @post connection to fileserver SYNC service established
6140  *
6141  * @see VConnectFS_r
6142  * @see VDisconnectFS
6143  * @see VChildProcReconnectFS
6144  */
6145 int
6146 VConnectFS(void)
6147 {
6148     int retVal;
6149     VOL_LOCK;
6150     retVal = VConnectFS_r();
6151     VOL_UNLOCK;
6152     return retVal;
6153 }
6154
6155 /**
6156  * connect to the fileserver SYNC service.
6157  *
6158  * @return operation status
6159  *    @retval 0 failure
6160  *    @retval 1 success
6161  *
6162  * @pre
6163  *    @arg VInit must equal 2.
6164  *    @arg Program Type must not be fileserver or salvager.
6165  *    @arg VOL_LOCK is held.
6166  *
6167  * @post connection to fileserver SYNC service established
6168  *
6169  * @see VConnectFS
6170  * @see VDisconnectFS_r
6171  * @see VChildProcReconnectFS_r
6172  *
6173  * @internal volume package internal use only.
6174  */
6175 int
6176 VConnectFS_r(void)
6177 {
6178     int rc;
6179     opr_Assert((VInit == 2) &&
6180            (programType != fileServer) &&
6181            (programType != salvager));
6182     rc = FSYNC_clientInit();
6183     if (rc) {
6184         VSetVInit_r(3);
6185     }
6186     return rc;
6187 }
6188
6189 /**
6190  * disconnect from the fileserver SYNC service.
6191  *
6192  * @pre
6193  *    @arg client should have a live connection to the fileserver.
6194  *    @arg VOL_LOCK is held.
6195  *    @arg Program Type must not be fileserver or salvager.
6196  *
6197  * @post connection to fileserver SYNC service destroyed
6198  *
6199  * @see VDisconnectFS
6200  * @see VConnectFS_r
6201  * @see VChildProcReconnectFS_r
6202  *
6203  * @internal volume package internal use only.
6204  */
6205 void
6206 VDisconnectFS_r(void)
6207 {
6208     opr_Assert((programType != fileServer) &&
6209            (programType != salvager));
6210     FSYNC_clientFinis();
6211     VSetVInit_r(2);
6212 }
6213
6214 /**
6215  * disconnect from the fileserver SYNC service.
6216  *
6217  * @pre
6218  *    @arg client should have a live connection to the fileserver.
6219  *    @arg Program Type must not be fileserver or salvager.
6220  *
6221  * @post connection to fileserver SYNC service destroyed
6222  *
6223  * @see VDisconnectFS_r
6224  * @see VConnectFS
6225  * @see VChildProcReconnectFS
6226  */
6227 void
6228 VDisconnectFS(void)
6229 {
6230     VOL_LOCK;
6231     VDisconnectFS_r();
6232     VOL_UNLOCK;
6233 }
6234
6235 /**
6236  * connect to the fileserver SYNC service from a child process following a fork.
6237  *
6238  * @return operation status
6239  *    @retval 0 failure
6240  *    @retval 1 success
6241  *
6242  * @pre
6243  *    @arg VOL_LOCK is held.
6244  *    @arg current FSYNC handle is shared with a parent process
6245  *
6246  * @post current FSYNC handle is discarded and a new connection to the
6247  *       fileserver SYNC service is established
6248  *
6249  * @see VChildProcReconnectFS
6250  * @see VConnectFS_r
6251  * @see VDisconnectFS_r
6252  *
6253  * @internal volume package internal use only.
6254  */
6255 int
6256 VChildProcReconnectFS_r(void)
6257 {
6258     return FSYNC_clientChildProcReconnect();
6259 }
6260
6261 /**
6262  * connect to the fileserver SYNC service from a child process following a fork.
6263  *
6264  * @return operation status
6265  *    @retval 0 failure
6266  *    @retval 1 success
6267  *
6268  * @pre current FSYNC handle is shared with a parent process
6269  *
6270  * @post current FSYNC handle is discarded and a new connection to the
6271  *       fileserver SYNC service is established
6272  *
6273  * @see VChildProcReconnectFS_r
6274  * @see VConnectFS
6275  * @see VDisconnectFS
6276  */
6277 int
6278 VChildProcReconnectFS(void)
6279 {
6280     int ret;
6281     VOL_LOCK;
6282     ret = VChildProcReconnectFS_r();
6283     VOL_UNLOCK;
6284     return ret;
6285 }
6286 #endif /* FSSYNC_BUILD_CLIENT */
6287
6288
6289 /***************************************************/
6290 /* volume bitmap routines                          */
6291 /***************************************************/
6292
6293 /*
6294  * Grow the bitmap by the defined increment
6295  */
6296 void
6297 VGrowBitmap(struct vnodeIndex *index)
6298 {
6299     byte *bp;
6300
6301     bp = realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
6302     osi_Assert(bp != NULL);
6303     index->bitmap = bp;
6304     bp += index->bitmapSize;
6305     memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
6306     index->bitmapOffset = index->bitmapSize;
6307     index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
6308
6309     return;
6310 }
6311
6312 /**
6313  * allocate a vnode bitmap number for the vnode
6314  *
6315  * @param[out] ec  error code
6316  * @param[in] vp   volume object pointer
6317  * @param[in] index vnode index number for the vnode
6318  * @param[in] flags flag values described in note
6319  *
6320  * @note for DAFS, flags parameter controls locking behavior.
6321  * If (flags & VOL_ALLOC_BITMAP_WAIT) is set, then this function
6322  * will create a reservation and block on any other exclusive
6323  * operations.  Otherwise, this function assumes the caller
6324  * already has exclusive access to vp, and we just change the
6325  * volume state.
6326  *
6327  * @pre VOL_LOCK held
6328  *
6329  * @return bit number allocated
6330  */
6331 /*
6332
6333  */
6334 int
6335 VAllocBitmapEntry_r(Error * ec, Volume * vp,
6336                     struct vnodeIndex *index, int flags)
6337 {
6338     int ret = 0;
6339     byte *bp, *ep;
6340 #ifdef AFS_DEMAND_ATTACH_FS
6341     VolState state_save;
6342 #endif /* AFS_DEMAND_ATTACH_FS */
6343
6344     *ec = 0;
6345
6346     /* This test is probably redundant */
6347     if (!VolumeWriteable(vp)) {
6348         *ec = (bit32) VREADONLY;
6349         return ret;
6350     }
6351
6352 #ifdef AFS_DEMAND_ATTACH_FS
6353     if (flags & VOL_ALLOC_BITMAP_WAIT) {
6354         VCreateReservation_r(vp);
6355         VWaitExclusiveState_r(vp);
6356     }
6357     state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6358 #endif /* AFS_DEMAND_ATTACH_FS */
6359
6360 #ifdef BITMAP_LATER
6361     if ((programType == fileServer) && !index->bitmap) {
6362         int i;
6363 #ifndef AFS_DEMAND_ATTACH_FS
6364         /* demand attach fs uses the volume state to avoid races.
6365          * specialStatus field is not used at all */
6366         int wasVBUSY = 0;
6367         if (vp->specialStatus == VBUSY) {
6368             if (vp->goingOffline) {     /* vos dump waiting for the volume to
6369                                          * go offline. We probably come here
6370                                          * from AddNewReadableResidency */
6371                 wasVBUSY = 1;
6372             } else {
6373                 while (vp->specialStatus == VBUSY) {
6374 #ifdef AFS_PTHREAD_ENV
6375                     VOL_UNLOCK;
6376                     sleep(2);
6377                     VOL_LOCK;
6378 #else /* !AFS_PTHREAD_ENV */
6379                     IOMGR_Sleep(2);
6380 #endif /* !AFS_PTHREAD_ENV */
6381                 }
6382             }
6383         }
6384 #endif /* !AFS_DEMAND_ATTACH_FS */
6385
6386         if (!index->bitmap) {
6387 #ifndef AFS_DEMAND_ATTACH_FS
6388             vp->specialStatus = VBUSY;  /* Stop anyone else from using it. */
6389 #endif /* AFS_DEMAND_ATTACH_FS */
6390             for (i = 0; i < nVNODECLASSES; i++) {
6391                 VGetBitmap_r(ec, vp, i);
6392                 if (*ec) {
6393 #ifdef AFS_DEMAND_ATTACH_FS
6394                     VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0 /*flags*/);
6395 #else /* AFS_DEMAND_ATTACH_FS */
6396                     DeleteVolumeFromHashTable(vp);
6397                     vp->shuttingDown = 1;       /* Let who has it free it. */
6398                     vp->specialStatus = 0;
6399 #endif /* AFS_DEMAND_ATTACH_FS */
6400                     goto done;
6401                 }
6402             }
6403 #ifndef AFS_DEMAND_ATTACH_FS
6404             if (!wasVBUSY)
6405                 vp->specialStatus = 0;  /* Allow others to have access. */
6406 #endif /* AFS_DEMAND_ATTACH_FS */
6407         }
6408     }
6409 #endif /* BITMAP_LATER */
6410
6411 #ifdef AFS_DEMAND_ATTACH_FS
6412     VOL_UNLOCK;
6413 #endif /* AFS_DEMAND_ATTACH_FS */
6414     bp = index->bitmap + index->bitmapOffset;
6415     ep = index->bitmap + index->bitmapSize;
6416     while (bp < ep) {
6417         if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
6418             int o;
6419             index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
6420             while (*bp == 0xff)
6421                 bp++;
6422             o = opr_ffs(~*bp) - 1;
6423             *bp |= (1 << o);
6424             ret = ((bp - index->bitmap) * 8 + o);
6425 #ifdef AFS_DEMAND_ATTACH_FS
6426             VOL_LOCK;
6427 #endif /* AFS_DEMAND_ATTACH_FS */
6428             goto done;
6429         }
6430         bp += sizeof(bit32) /* i.e. 4 */ ;
6431     }
6432     /* No bit map entry--must grow bitmap */
6433     VGrowBitmap(index);
6434     bp = index->bitmap + index->bitmapOffset;
6435     *bp = 1;
6436     ret = index->bitmapOffset * 8;
6437 #ifdef AFS_DEMAND_ATTACH_FS
6438     VOL_LOCK;
6439 #endif /* AFS_DEMAND_ATTACH_FS */
6440
6441  done:
6442 #ifdef AFS_DEMAND_ATTACH_FS
6443     VChangeState_r(vp, state_save);
6444     if (flags & VOL_ALLOC_BITMAP_WAIT) {
6445         VCancelReservation_r(vp);
6446     }
6447 #endif /* AFS_DEMAND_ATTACH_FS */
6448     return ret;
6449 }
6450
6451 int
6452 VAllocBitmapEntry(Error * ec, Volume * vp, struct vnodeIndex * index)
6453 {
6454     int retVal;
6455     VOL_LOCK;
6456     retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
6457     VOL_UNLOCK;
6458     return retVal;
6459 }
6460
6461 void
6462 VFreeBitMapEntry_r(Error * ec, Volume *vp, struct vnodeIndex *index,
6463                    unsigned bitNumber, int flags)
6464 {
6465     unsigned int offset;
6466
6467     *ec = 0;
6468
6469 #ifdef AFS_DEMAND_ATTACH_FS
6470     if (flags & VOL_FREE_BITMAP_WAIT) {
6471         /* VAllocBitmapEntry_r allocs bitmap entries under an exclusive volume
6472          * state, so ensure we're not in an exclusive volume state when we update
6473          * the bitmap */
6474         VCreateReservation_r(vp);
6475         VWaitExclusiveState_r(vp);
6476     }
6477 #endif
6478
6479 #ifdef BITMAP_LATER
6480     if (!index->bitmap)
6481         goto done;
6482 #endif /* BITMAP_LATER */
6483
6484     offset = bitNumber >> 3;
6485     if (offset >= index->bitmapSize) {
6486         *ec = VNOVNODE;
6487         goto done;
6488     }
6489     if (offset < index->bitmapOffset)
6490         index->bitmapOffset = offset & ~3;      /* Truncate to nearest bit32 */
6491     *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
6492
6493  done:
6494 #ifdef AFS_DEMAND_ATTACH_FS
6495     if (flags & VOL_FREE_BITMAP_WAIT) {
6496         VCancelReservation_r(vp);
6497     }
6498 #endif
6499     return; /* make the compiler happy for non-DAFS */
6500 }
6501
6502 void
6503 VFreeBitMapEntry(Error * ec, Volume *vp, struct vnodeIndex *index,
6504                  unsigned bitNumber)
6505 {
6506     VOL_LOCK;
6507     VFreeBitMapEntry_r(ec, vp, index, bitNumber, VOL_FREE_BITMAP_WAIT);
6508     VOL_UNLOCK;
6509 }
6510
6511 /* this function will drop the glock internally.
6512  * for old pthread fileservers, this is safe thanks to vbusy.
6513  *
6514  * for demand attach fs, caller must have already called
6515  * VCreateReservation_r and VWaitExclusiveState_r */
6516 static void
6517 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
6518 {
6519     StreamHandle_t *file;
6520     afs_sfsize_t nVnodes, size;
6521     struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
6522     struct vnodeIndex *vip = &vp->vnodeIndex[class];
6523     struct VnodeDiskObject *vnode;
6524     unsigned int unique = 0;
6525     FdHandle_t *fdP;
6526 #ifdef BITMAP_LATER
6527     byte *BitMap = 0;
6528 #endif /* BITMAP_LATER */
6529 #ifdef AFS_DEMAND_ATTACH_FS
6530     VolState state_save;
6531 #endif /* AFS_DEMAND_ATTACH_FS */
6532
6533     *ec = 0;
6534
6535 #ifdef AFS_DEMAND_ATTACH_FS
6536     state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6537 #endif /* AFS_DEMAND_ATTACH_FS */
6538     VOL_UNLOCK;
6539
6540     fdP = IH_OPEN(vip->handle);
6541     opr_Assert(fdP != NULL);
6542     file = FDH_FDOPEN(fdP, "r");
6543     opr_Assert(file != NULL);
6544     vnode = malloc(vcp->diskSize);
6545     opr_Assert(vnode != NULL);
6546     size = OS_SIZE(fdP->fd_fd);
6547     opr_Assert(size != -1);
6548     nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
6549         >> vcp->logSize;
6550     vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4;     /* The 10 is a little extra so
6551                                                          * a few files can be created in this volume,
6552                                                          * the whole thing is rounded up to nearest 4
6553                                                          * bytes, because the bit map allocator likes
6554                                                          * it that way */
6555 #ifdef BITMAP_LATER
6556     BitMap = (byte *) calloc(1, vip->bitmapSize);
6557     opr_Assert(BitMap != NULL);
6558 #else /* BITMAP_LATER */
6559     vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
6560     opr_Assert(vip->bitmap != NULL);
6561     vip->bitmapOffset = 0;
6562 #endif /* BITMAP_LATER */
6563     if (STREAM_ASEEK(file, vcp->diskSize) != -1) {
6564         int bitNumber = 0;
6565         for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
6566             if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
6567                 break;
6568             if (vnode->type != vNull) {
6569                 if (vnode->vnodeMagic != vcp->magic) {
6570                     Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
6571                     *ec = VSALVAGE;
6572                     break;
6573                 }
6574 #ifdef BITMAP_LATER
6575                 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6576 #else /* BITMAP_LATER */
6577                 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6578 #endif /* BITMAP_LATER */
6579                 if (unique <= vnode->uniquifier)
6580                     unique = vnode->uniquifier + 1;
6581             }
6582 #ifndef AFS_PTHREAD_ENV
6583             if ((bitNumber & 0x00ff) == 0x0ff) {        /* every 256 iterations */
6584                 IOMGR_Poll();
6585             }
6586 #endif /* !AFS_PTHREAD_ENV */
6587         }
6588     }
6589     if (vp->nextVnodeUnique < unique) {
6590         Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
6591         *ec = VSALVAGE;
6592     }
6593     /* Paranoia, partly justified--I think fclose after fdopen
6594      * doesn't seem to close fd.  In any event, the documentation
6595      * doesn't specify, so it's safer to close it twice.
6596      */
6597     STREAM_CLOSE(file);
6598     FDH_CLOSE(fdP);
6599     free(vnode);
6600
6601     VOL_LOCK;
6602 #ifdef BITMAP_LATER
6603     /* There may have been a racing condition with some other thread, both
6604      * creating the bitmaps for this volume. If the other thread was faster
6605      * the pointer to bitmap should already be filled and we can free ours.
6606      */
6607     if (vip->bitmap == NULL) {
6608         vip->bitmap = BitMap;
6609         vip->bitmapOffset = 0;
6610     } else
6611         free(BitMap);
6612 #endif /* BITMAP_LATER */
6613 #ifdef AFS_DEMAND_ATTACH_FS
6614     VChangeState_r(vp, state_save);
6615 #endif /* AFS_DEMAND_ATTACH_FS */
6616 }
6617
6618
6619 /***************************************************/
6620 /* Volume Path and Volume Number utility routines  */
6621 /***************************************************/
6622
6623 /**
6624  * find the first occurrence of a volume header file and return the path.
6625  *
6626  * @param[out] ec          outbound error code
6627  * @param[in]  volumeId    volume id to find
6628  * @param[out] partitionp  pointer to disk partition path string
6629  * @param[out] namep       pointer to volume header file name string
6630  *
6631  * @post path to first occurrence of volume header is returned in partitionp
6632  *       and namep, or ec is set accordingly.
6633  *
6634  * @warning this function is NOT re-entrant -- partitionp and namep point to
6635  *          static data segments
6636  *
6637  * @note if a volume utility inadvertently leaves behind a stale volume header
6638  *       on a vice partition, it is possible for callers to get the wrong one,
6639  *       depending on the order of the disk partition linked list.
6640  *
6641  */
6642 void
6643 VGetVolumePath(Error * ec, VolumeId volumeId, char **partitionp, char **namep)
6644 {
6645     static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
6646     char path[VMAXPATHLEN];
6647     int found = 0;
6648     struct DiskPartition64 *dp;
6649
6650     *ec = 0;
6651     name[0] = OS_DIRSEPC;
6652     snprintf(&name[1], (sizeof name) - 1, VFORMAT,
6653              afs_printable_VolumeId_lu(volumeId));
6654     for (dp = DiskPartitionList; dp; dp = dp->next) {
6655         struct afs_stat_st status;
6656         strcpy(path, VPartitionPath(dp));
6657         strcat(path, name);
6658         if (afs_stat(path, &status) == 0) {
6659             strcpy(partition, dp->name);
6660             found = 1;
6661             break;
6662         }
6663     }
6664     if (!found) {
6665         *ec = VNOVOL;
6666         *partitionp = *namep = NULL;
6667     } else {
6668         *partitionp = partition;
6669         *namep = name;
6670     }
6671 }
6672
6673 /**
6674  * extract a volume number from a volume header filename string.
6675  *
6676  * @param[in] name  volume header filename string
6677  *
6678  * @return volume number
6679  *
6680  * @note the string must be of the form VFORMAT.  the only permissible
6681  *       deviation is a leading OS_DIRSEPC character.
6682  *
6683  * @see VFORMAT
6684  */
6685 int
6686 VolumeNumber(char *name)
6687 {
6688     if (*name == OS_DIRSEPC)
6689         name++;
6690     return strtoul(name + 1, NULL, 10);
6691 }
6692
6693 /**
6694  * compute the volume header filename.
6695  *
6696  * @param[in] volumeId
6697  *
6698  * @return volume header filename
6699  *
6700  * @post volume header filename string is constructed
6701  *
6702  * @warning this function is NOT re-entrant -- the returned string is
6703  *          stored in a static char array.  see VolumeExternalName_r
6704  *          for a re-entrant equivalent.
6705  *
6706  * @see VolumeExternalName_r
6707  *
6708  * @deprecated due to the above re-entrancy warning, this interface should
6709  *             be considered deprecated.  Please use VolumeExternalName_r
6710  *             in its stead.
6711  */
6712 char *
6713 VolumeExternalName(VolumeId volumeId)
6714 {
6715     static char name[VMAXPATHLEN];
6716     snprintf(name, sizeof name, VFORMAT, afs_printable_VolumeId_lu(volumeId));
6717     return name;
6718 }
6719
6720 /**
6721  * compute the volume header filename.
6722  *
6723  * @param[in]     volumeId
6724  * @param[inout]  name       array in which to store filename
6725  * @param[in]     len        length of name array
6726  *
6727  * @return result code from afs_snprintf
6728  *
6729  * @see VolumeExternalName
6730  * @see afs_snprintf
6731  *
6732  * @note re-entrant equivalent of VolumeExternalName
6733  */
6734 int
6735 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
6736 {
6737     return snprintf(name, len, VFORMAT, afs_printable_VolumeId_lu(volumeId));
6738 }
6739
6740
6741 /***************************************************/
6742 /* Volume Usage Statistics routines                */
6743 /***************************************************/
6744
6745 #define OneDay  (86400)         /* 24 hours' worth of seconds */
6746
6747 static time_t
6748 Midnight(time_t t) {
6749     struct tm local, *l;
6750     time_t midnight;
6751
6752 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
6753     l = localtime_r(&t, &local);
6754 #else
6755     l = localtime(&t);
6756 #endif
6757
6758     if (l != NULL) {
6759         /* the following is strictly speaking problematic on the
6760            switching day to daylight saving time, after the switch,
6761            as tm_isdst does not match.  Similarly, on the looong day when
6762            switching back the OneDay check will not do what naively expected!
6763            The effects are minor, though, and more a matter of interpreting
6764            the numbers. */
6765 #ifndef AFS_PTHREAD_ENV
6766         local = *l;
6767 #endif
6768         local.tm_hour = local.tm_min=local.tm_sec = 0;
6769         midnight = mktime(&local);
6770         if (midnight != (time_t) -1) return(midnight);
6771     }
6772     return( (t/OneDay)*OneDay );
6773
6774 }
6775
6776 /*------------------------------------------------------------------------
6777  * [export] VAdjustVolumeStatistics
6778  *
6779  * Description:
6780  *      If we've passed midnight, we need to update all the day use
6781  *      statistics as well as zeroing the detailed volume statistics
6782  *      (if we are implementing them).
6783  *
6784  * Arguments:
6785  *      vp : Pointer to the volume structure describing the lucky
6786  *              volume being considered for update.
6787  *
6788  * Returns:
6789  *      0 (always!)
6790  *
6791  * Environment:
6792  *      Nothing interesting.
6793  *
6794  * Side Effects:
6795  *      As described.
6796  *------------------------------------------------------------------------*/
6797
6798 int
6799 VAdjustVolumeStatistics_r(Volume * vp)
6800 {
6801     unsigned int now = FT_ApproxTime();
6802
6803     if (now - V_dayUseDate(vp) > OneDay) {
6804         int ndays, i;
6805
6806         ndays = (now - V_dayUseDate(vp)) / OneDay;
6807         for (i = 6; i > ndays - 1; i--)
6808             V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
6809         for (i = 0; i < ndays - 1 && i < 7; i++)
6810             V_weekUse(vp)[i] = 0;
6811         if (ndays <= 7)
6812             V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
6813         V_dayUse(vp) = 0;
6814         V_dayUseDate(vp) = Midnight(now);
6815
6816         /*
6817          * All we need to do is bzero the entire VOL_STATS_BYTES of
6818          * the detailed volume statistics area.
6819          */
6820         memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
6821         }
6822
6823     /*It's been more than a day of collection */
6824     /*
6825      * Always return happily.
6826      */
6827     return (0);
6828 }                               /*VAdjustVolumeStatistics */
6829
6830 int
6831 VAdjustVolumeStatistics(Volume * vp)
6832 {
6833     int retVal;
6834     VOL_LOCK;
6835     retVal = VAdjustVolumeStatistics_r(vp);
6836     VOL_UNLOCK;
6837     return retVal;
6838 }
6839
6840 void
6841 VBumpVolumeUsage_r(Volume * vp)
6842 {
6843     unsigned int now = FT_ApproxTime();
6844     V_accessDate(vp) = now;
6845     if (now - V_dayUseDate(vp) > OneDay)
6846         VAdjustVolumeStatistics_r(vp);
6847     /*
6848      * Save the volume header image to disk after a threshold of bumps to dayUse,
6849      * at most every usage_rate_limit seconds.
6850      */
6851     V_dayUse(vp)++;
6852     vp->usage_bumps_outstanding++;
6853     if (vp->usage_bumps_outstanding >= vol_opts.usage_threshold
6854         && vp->usage_bumps_next_write <= now) {
6855         Error error;
6856         vp->usage_bumps_outstanding = 0;
6857         vp->usage_bumps_next_write = now + vol_opts.usage_rate_limit;
6858         VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
6859     }
6860 }
6861
6862 void
6863 VBumpVolumeUsage(Volume * vp)
6864 {
6865     VOL_LOCK;
6866     VBumpVolumeUsage_r(vp);
6867     VOL_UNLOCK;
6868 }
6869
6870 void
6871 VSetDiskUsage_r(void)
6872 {
6873 #ifndef AFS_DEMAND_ATTACH_FS
6874     static int FifteenMinuteCounter = 0;
6875 #endif
6876
6877     while (VInit < 2) {
6878         /* NOTE: Don't attempt to access the partitions list until the
6879          * initialization level indicates that all volumes are attached,
6880          * which implies that all partitions are initialized. */
6881 #ifdef AFS_PTHREAD_ENV
6882         VOL_CV_WAIT(&vol_vinit_cond);
6883 #else /* AFS_PTHREAD_ENV */
6884         IOMGR_Sleep(10);
6885 #endif /* AFS_PTHREAD_ENV */
6886     }
6887
6888     VResetDiskUsage_r();
6889
6890 #ifndef AFS_DEMAND_ATTACH_FS
6891     if (++FifteenMinuteCounter == 3) {
6892         FifteenMinuteCounter = 0;
6893         VScanUpdateList();
6894     }
6895 #endif /* !AFS_DEMAND_ATTACH_FS */
6896 }
6897
6898 void
6899 VSetDiskUsage(void)
6900 {
6901     VOL_LOCK;
6902     VSetDiskUsage_r();
6903     VOL_UNLOCK;
6904 }
6905
6906
6907 /***************************************************/
6908 /* Volume Update List routines                     */
6909 /***************************************************/
6910
6911 /* The number of minutes that a volume hasn't been updated before the
6912  * "Dont salvage" flag in the volume header will be turned on */
6913 #define SALVAGE_INTERVAL        (10*60)
6914
6915 /*
6916  * demand attach fs
6917  *
6918  * volume update list functionality has been moved into the VLRU
6919  * the DONT_SALVAGE flag is now set during VLRU demotion
6920  */
6921
6922 #ifndef AFS_DEMAND_ATTACH_FS
6923 static VolumeId *UpdateList = NULL;     /* Pointer to array of Volume ID's */
6924 static int nUpdatedVolumes = 0;         /* Updated with entry in UpdateList, salvage after crash flag on */
6925 static int updateSize = 0;              /* number of entries possible */
6926 #define UPDATE_LIST_SIZE 128            /* initial size increment (must be a power of 2!) */
6927 #endif /* !AFS_DEMAND_ATTACH_FS */
6928
6929 void
6930 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
6931 {
6932     *ec = 0;
6933     vp->updateTime = FT_ApproxTime();
6934     if (V_dontSalvage(vp) == 0)
6935         return;
6936     V_dontSalvage(vp) = 0;
6937     VSyncVolume_r(ec, vp, 0);
6938 #ifdef AFS_DEMAND_ATTACH_FS
6939     V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
6940 #else /* !AFS_DEMAND_ATTACH_FS */
6941     if (*ec)
6942         return;
6943     if (UpdateList == NULL) {
6944         updateSize = UPDATE_LIST_SIZE;
6945         UpdateList = malloc(sizeof(VolumeId) * updateSize);
6946     } else {
6947         if (nUpdatedVolumes == updateSize) {
6948             updateSize <<= 1;
6949             if (updateSize > 524288) {
6950                 Log("warning: there is likely a bug in the volume update scanner\n");
6951                 return;
6952             }
6953             UpdateList = realloc(UpdateList,
6954                                  sizeof(VolumeId) * updateSize);
6955         }
6956     }
6957     opr_Assert(UpdateList != NULL);
6958     UpdateList[nUpdatedVolumes++] = V_id(vp);
6959 #endif /* !AFS_DEMAND_ATTACH_FS */
6960 }
6961
6962 #ifndef AFS_DEMAND_ATTACH_FS
6963 static void
6964 VScanUpdateList(void)
6965 {
6966     int i, gap;
6967     Volume *vp;
6968     Error error;
6969     afs_uint32 now = FT_ApproxTime();
6970     /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
6971     for (i = gap = 0; i < nUpdatedVolumes; i++) {
6972         if (gap)
6973             UpdateList[i - gap] = UpdateList[i];
6974
6975         /* XXX this routine needlessly messes up the Volume LRU by
6976          * breaking the LRU temporal-locality assumptions.....
6977          * we should use a special volume header allocator here */
6978         vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
6979         if (error) {
6980             gap++;
6981         } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
6982             V_dontSalvage(vp) = DONT_SALVAGE;
6983             VUpdateVolume_r(&error, vp, 0);     /* No need to fsync--not critical */
6984             gap++;
6985         }
6986
6987         if (vp) {
6988             VPutVolume_r(vp);
6989         }
6990
6991 #ifndef AFS_PTHREAD_ENV
6992         IOMGR_Poll();
6993 #endif /* !AFS_PTHREAD_ENV */
6994     }
6995     nUpdatedVolumes -= gap;
6996 }
6997 #endif /* !AFS_DEMAND_ATTACH_FS */
6998
6999
7000 /***************************************************/
7001 /* Volume LRU routines                             */
7002 /***************************************************/
7003
7004 /* demand attach fs
7005  * volume LRU
7006  *
7007  * with demand attach fs, we attempt to soft detach(1)
7008  * volumes which have not been accessed in a long time
7009  * in order to speed up fileserver shutdown
7010  *
7011  * (1) by soft detach we mean a process very similar
7012  *     to VOffline, except the final state of the
7013  *     Volume will be VOL_STATE_PREATTACHED, instead
7014  *     of the usual VOL_STATE_UNATTACHED
7015  */
7016 #ifdef AFS_DEMAND_ATTACH_FS
7017
7018 /* implementation is reminiscent of a generational GC
7019  *
7020  * queue 0 is newly attached volumes. this queue is
7021  * sorted by attach timestamp
7022  *
7023  * queue 1 is volumes that have been around a bit
7024  * longer than queue 0. this queue is sorted by
7025  * attach timestamp
7026  *
7027  * queue 2 is volumes tha have been around the longest.
7028  * this queue is unsorted
7029  *
7030  * queue 3 is volumes that have been marked as
7031  * candidates for soft detachment. this queue is
7032  * unsorted
7033  */
7034 #define VLRU_GENERATIONS  3   /**< number of generations in VLRU */
7035 #define VLRU_QUEUES       5   /**< total number of VLRU queues */
7036
7037 /**
7038  * definition of a VLRU queue.
7039  */
7040 struct VLRU_q {
7041     volatile struct rx_queue q;
7042     volatile int len;
7043     volatile int busy;
7044     pthread_cond_t cv;
7045 };
7046
7047 /**
7048  * main VLRU data structure.
7049  */
7050 struct VLRU {
7051     struct VLRU_q q[VLRU_QUEUES];   /**< VLRU queues */
7052
7053     /* VLRU config */
7054     /** time interval (in seconds) between promotion passes for
7055      *  each young generation queue. */
7056     afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
7057
7058     /** time interval (in seconds) between soft detach candidate
7059      *  scans for each generation queue.
7060      *
7061      *  scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
7062      *  we perform a soft detach pass. */
7063     afs_uint32 scan_interval[VLRU_GENERATIONS+1];
7064
7065     /* scheduler state */
7066     int next_idx;                                       /**< next queue to receive attention */
7067     afs_uint32 last_promotion[VLRU_GENERATIONS-1];      /**< timestamp of last promotion scan */
7068     afs_uint32 last_scan[VLRU_GENERATIONS+1];           /**< timestamp of last detach scan */
7069
7070     int scanner_state;                                  /**< state of scanner thread */
7071     pthread_cond_t cv;                                  /**< state transition CV */
7072 };
7073
7074 /** global VLRU state */
7075 static struct VLRU volume_LRU;
7076
7077 /**
7078  * defined states for VLRU scanner thread.
7079  */
7080 typedef enum {
7081     VLRU_SCANNER_STATE_OFFLINE        = 0,    /**< vlru scanner thread is offline */
7082     VLRU_SCANNER_STATE_ONLINE         = 1,    /**< vlru scanner thread is online */
7083     VLRU_SCANNER_STATE_SHUTTING_DOWN  = 2,    /**< vlru scanner thread is shutting down */
7084     VLRU_SCANNER_STATE_PAUSING        = 3,    /**< vlru scanner thread is getting ready to pause */
7085     VLRU_SCANNER_STATE_PAUSED         = 4     /**< vlru scanner thread is paused */
7086 } vlru_thread_state_t;
7087
7088 /* vlru disk data header stuff */
7089 #define VLRU_DISK_MAGIC      0x7a8b9cad        /**< vlru disk entry magic number */
7090 #define VLRU_DISK_VERSION    1                 /**< vlru disk entry version number */
7091
7092 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
7093 #define VLRU_DUMP_EXPIRATION_TIME   (60*60*24*7)  /* expire vlru data after 1 week */
7094
7095
7096 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
7097  *  soft detachment. */
7098 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
7099
7100 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
7101 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
7102
7103 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
7104 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
7105
7106 /** VLRU control flag.  non-zero value implies VLRU subsystem is activated. */
7107 static afs_uint32 VLRU_enabled = 1;
7108
7109 /* queue synchronization routines */
7110 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
7111 static void VLRU_EndExclusive_r(struct VLRU_q * q);
7112 static void VLRU_Wait_r(struct VLRU_q * q);
7113
7114 /**
7115  * set VLRU subsystem tunable parameters.
7116  *
7117  * @param[in] option  tunable option to modify
7118  * @param[in] val     new value for tunable parameter
7119  *
7120  * @pre @c VInitVolumePackage2 has not yet been called.
7121  *
7122  * @post tunable parameter is modified
7123  *
7124  * @note DAFS only
7125  *
7126  * @note valid option parameters are:
7127  *    @arg @c VLRU_SET_THRESH
7128  *         set the period of inactivity after which
7129  *         volumes are eligible for soft detachment
7130  *    @arg @c VLRU_SET_INTERVAL
7131  *         set the time interval between calls
7132  *         to the volume LRU "garbage collector"
7133  *    @arg @c VLRU_SET_MAX
7134  *         set the max number of volumes to deallocate
7135  *         in one GC pass
7136  */
7137 void
7138 VLRU_SetOptions(int option, afs_uint32 val)
7139 {
7140     if (option == VLRU_SET_THRESH) {
7141         VLRU_offline_thresh = val;
7142     } else if (option == VLRU_SET_INTERVAL) {
7143         VLRU_offline_interval = val;
7144     } else if (option == VLRU_SET_MAX) {
7145         VLRU_offline_max = val;
7146     } else if (option == VLRU_SET_ENABLED) {
7147         VLRU_enabled = val;
7148     }
7149     VLRU_ComputeConstants();
7150 }
7151
7152 /**
7153  * compute VLRU internal timing parameters.
7154  *
7155  * @post VLRU scanner thread internal timing parameters are computed
7156  *
7157  * @note computes internal timing parameters based upon user-modifiable
7158  *       tunable parameters.
7159  *
7160  * @note DAFS only
7161  *
7162  * @internal volume package internal use only.
7163  */
7164 static void
7165 VLRU_ComputeConstants(void)
7166 {
7167     afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
7168
7169     /* compute the candidate scan interval */
7170     volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
7171
7172     /* compute the promotion intervals */
7173     volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
7174     volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
7175
7176     if (factor > 16) {
7177         /* compute the gen 0 scan interval */
7178         volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
7179     } else {
7180         /* compute the gen 0 scan interval */
7181         volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
7182     }
7183 }
7184
7185 /**
7186  * initialize VLRU subsystem.
7187  *
7188  * @pre this function has not yet been called
7189  *
7190  * @post VLRU subsystem is initialized and VLRU scanner thread is starting
7191  *
7192  * @note DAFS only
7193  *
7194  * @internal volume package internal use only.
7195  */
7196 static void
7197 VInitVLRU(void)
7198 {
7199     pthread_t tid;
7200     pthread_attr_t attrs;
7201     int i;
7202
7203     if (!VLRU_enabled) {
7204         Log("VLRU: disabled\n");
7205         return;
7206     }
7207
7208     /* initialize each of the VLRU queues */
7209     for (i = 0; i < VLRU_QUEUES; i++) {
7210         queue_Init(&volume_LRU.q[i]);
7211         volume_LRU.q[i].len = 0;
7212         volume_LRU.q[i].busy = 0;
7213         opr_cv_init(&volume_LRU.q[i].cv);
7214     }
7215
7216     /* setup the timing constants */
7217     VLRU_ComputeConstants();
7218
7219     /* XXX put inside log level check? */
7220     Log("VLRU: starting scanner with the following configuration parameters:\n");
7221     Log("VLRU:  offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
7222     Log("VLRU:  running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
7223     Log("VLRU:  taking up to %d volumes offline per pass\n", VLRU_offline_max);
7224     Log("VLRU:  scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
7225     Log("VLRU:  scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
7226     Log("VLRU:  scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
7227
7228     /* start up the VLRU scanner */
7229     volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7230     if (programType == fileServer) {
7231         opr_cv_init(&volume_LRU.cv);
7232         opr_Verify(pthread_attr_init(&attrs) == 0);
7233         opr_Verify(pthread_attr_setdetachstate(&attrs,
7234                                                PTHREAD_CREATE_DETACHED) == 0);
7235         opr_Verify(pthread_create(&tid, &attrs,
7236                                   &VLRU_ScannerThread, NULL) == 0);
7237     }
7238 }
7239
7240 /**
7241  * initialize the VLRU-related fields of a newly allocated volume object.
7242  *
7243  * @param[in] vp  pointer to volume object
7244  *
7245  * @pre
7246  *    @arg @c VOL_LOCK is held.
7247  *    @arg volume object is not on a VLRU queue.
7248  *
7249  * @post VLRU fields are initialized to indicate that volume object is not
7250  *       currently registered with the VLRU subsystem
7251  *
7252  * @note DAFS only
7253  *
7254  * @internal volume package interal use only.
7255  */
7256 static void
7257 VLRU_Init_Node_r(Volume * vp)
7258 {
7259     if (!VLRU_enabled)
7260         return;
7261
7262     opr_Assert(queue_IsNotOnQueue(&vp->vlru));
7263     vp->vlru.idx = VLRU_QUEUE_INVALID;
7264 }
7265
7266 /**
7267  * add a volume object to a VLRU queue.
7268  *
7269  * @param[in] vp  pointer to volume object
7270  *
7271  * @pre
7272  *    @arg @c VOL_LOCK is held.
7273  *    @arg caller MUST hold a lightweight ref on @p vp.
7274  *    @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7275  *
7276  * @post the volume object is added to the appropriate VLRU queue
7277  *
7278  * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
7279  *       then the volume is added to that queue.  Otherwise, the value
7280  *       @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
7281  *       volume is added to the NEW generation queue.
7282  *
7283  * @note @c VOL_LOCK may be dropped internally
7284  *
7285  * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
7286  *       during the add operation, and is restored to the previous
7287  *       state prior to return.
7288  *
7289  * @note DAFS only
7290  *
7291  * @internal volume package internal use only.
7292  */
7293 static void
7294 VLRU_Add_r(Volume * vp)
7295 {
7296     int idx;
7297     VolState state_save;
7298
7299     if (!VLRU_enabled)
7300         return;
7301
7302     if (queue_IsOnQueue(&vp->vlru))
7303         return;
7304
7305     state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
7306
7307     idx = vp->vlru.idx;
7308     if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
7309         idx = VLRU_QUEUE_NEW;
7310     }
7311
7312     VLRU_Wait_r(&volume_LRU.q[idx]);
7313
7314     /* repeat check since VLRU_Wait_r may have dropped
7315      * the glock */
7316     if (queue_IsNotOnQueue(&vp->vlru)) {
7317         vp->vlru.idx = idx;
7318         queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
7319         volume_LRU.q[idx].len++;
7320         V_attachFlags(vp) |= VOL_ON_VLRU;
7321         vp->stats.last_promote = FT_ApproxTime();
7322     }
7323
7324     VChangeState_r(vp, state_save);
7325 }
7326
7327 /**
7328  * delete a volume object from a VLRU queue.
7329  *
7330  * @param[in] vp  pointer to volume object
7331  *
7332  * @pre
7333  *    @arg @c VOL_LOCK is held.
7334  *    @arg caller MUST hold a lightweight ref on @p vp.
7335  *    @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7336  *
7337  * @post volume object is removed from the VLRU queue
7338  *
7339  * @note @c VOL_LOCK may be dropped internally
7340  *
7341  * @note DAFS only
7342  *
7343  * @todo We should probably set volume state to something exlcusive
7344  *       (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
7345  *
7346  * @internal volume package internal use only.
7347  */
7348 static void
7349 VLRU_Delete_r(Volume * vp)
7350 {
7351     int idx;
7352
7353     if (!VLRU_enabled)
7354         return;
7355
7356     if (queue_IsNotOnQueue(&vp->vlru))
7357         return;
7358
7359     /* handle races */
7360     do {
7361       idx = vp->vlru.idx;
7362       if (idx == VLRU_QUEUE_INVALID)
7363           return;
7364       VLRU_Wait_r(&volume_LRU.q[idx]);
7365     } while (idx != vp->vlru.idx);
7366
7367     /* now remove from the VLRU and update
7368      * the appropriate counter */
7369     queue_Remove(&vp->vlru);
7370     volume_LRU.q[idx].len--;
7371     vp->vlru.idx = VLRU_QUEUE_INVALID;
7372     V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7373 }
7374
7375 /**
7376  * tell the VLRU subsystem that a volume was just accessed.
7377  *
7378  * @param[in] vp  pointer to volume object
7379  *
7380  * @pre
7381  *    @arg @c VOL_LOCK is held
7382  *    @arg caller MUST hold a lightweight ref on @p vp
7383  *    @arg caller MUST NOT hold exclusive ownership of any VLRU queue
7384  *
7385  * @post volume VLRU access statistics are updated.  If the volume was on
7386  *       the VLRU soft detach candidate queue, it is moved to the NEW
7387  *       generation queue.
7388  *
7389  * @note @c VOL_LOCK may be dropped internally
7390  *
7391  * @note DAFS only
7392  *
7393  * @internal volume package internal use only.
7394  */
7395 static void
7396 VLRU_UpdateAccess_r(Volume * vp)
7397 {
7398     Volume * rvp = NULL;
7399
7400     if (!VLRU_enabled)
7401         return;
7402
7403     if (queue_IsNotOnQueue(&vp->vlru))
7404         return;
7405
7406     opr_Assert(V_attachFlags(vp) & VOL_ON_VLRU);
7407
7408     /* update the access timestamp */
7409     vp->stats.last_get = FT_ApproxTime();
7410
7411     /*
7412      * if the volume is on the soft detach candidate
7413      * list, we need to safely move it back to a
7414      * regular generation.  this has to be done
7415      * carefully so we don't race against the scanner
7416      * thread.
7417      */
7418
7419     /* if this volume is on the soft detach candidate queue,
7420      * then grab exclusive access to the necessary queues */
7421     if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7422         rvp = vp;
7423         VCreateReservation_r(rvp);
7424
7425         VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7426         VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7427         VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7428         VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7429     }
7430
7431     /* make sure multiple threads don't race to update */
7432     if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7433         VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
7434     }
7435
7436     if (rvp) {
7437       VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7438       VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7439       VCancelReservation_r(rvp);
7440     }
7441 }
7442
7443 /**
7444  * switch a volume between two VLRU queues.
7445  *
7446  * @param[in] vp       pointer to volume object
7447  * @param[in] new_idx  index of VLRU queue onto which the volume will be moved
7448  * @param[in] append   controls whether the volume will be appended or
7449  *                     prepended to the queue.  A nonzero value means it will
7450  *                     be appended; zero means it will be prepended.
7451  *
7452  * @pre The new (and old, if applicable) queue(s) must either be owned
7453  *      exclusively by the calling thread for asynchronous manipulation,
7454  *      or the queue(s) must be quiescent and VOL_LOCK must be held.
7455  *      Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
7456  *      for further details of the queue asynchronous processing mechanism.
7457  *
7458  * @post If the volume object was already on a VLRU queue, it is
7459  *       removed from the queue.  Depending on the value of the append
7460  *       parameter, the volume object is either appended or prepended
7461  *       to the VLRU queue referenced by the new_idx parameter.
7462  *
7463  * @note DAFS only
7464  *
7465  * @see VLRU_BeginExclusive_r
7466  * @see VLRU_EndExclusive_r
7467  * @see VLRU_Wait_r
7468  *
7469  * @internal volume package internal use only.
7470  */
7471 static void
7472 VLRU_SwitchQueues(Volume * vp, int new_idx, int append)
7473 {
7474     if (queue_IsNotOnQueue(&vp->vlru))
7475         return;
7476
7477     queue_Remove(&vp->vlru);
7478     volume_LRU.q[vp->vlru.idx].len--;
7479
7480     /* put the volume back on the correct generational queue */
7481     if (append) {
7482         queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
7483     } else {
7484         queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
7485     }
7486
7487     volume_LRU.q[new_idx].len++;
7488     vp->vlru.idx = new_idx;
7489 }
7490
7491 /**
7492  * VLRU background thread.
7493  *
7494  * The VLRU Scanner Thread is responsible for periodically scanning through
7495  * each VLRU queue looking for volumes which should be moved to another
7496  * queue, or soft detached.
7497  *
7498  * @param[in] args  unused thread arguments parameter
7499  *
7500  * @return unused thread return value
7501  *    @retval NULL always
7502  *
7503  * @internal volume package internal use only.
7504  */
7505 static void *
7506 VLRU_ScannerThread(void * args)
7507 {
7508     afs_uint32 now, min_delay, delay;
7509     int i, min_idx, min_op, overdue, state;
7510
7511     /* set t=0 for promotion cycle to be
7512      * fileserver startup */
7513     now = FT_ApproxTime();
7514     for (i=0; i < VLRU_GENERATIONS-1; i++) {
7515         volume_LRU.last_promotion[i] = now;
7516     }
7517
7518     /* don't start the scanner until VLRU_offline_thresh
7519      * plus a small delay for VInitVolumePackage2 to finish
7520      * has gone by */
7521
7522     sleep(VLRU_offline_thresh + 60);
7523
7524     /* set t=0 for scan cycle to be now */
7525     now = FT_ApproxTime();
7526     for (i=0; i < VLRU_GENERATIONS+1; i++) {
7527         volume_LRU.last_scan[i] = now;
7528     }
7529
7530     VOL_LOCK;
7531     if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
7532         volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
7533     }
7534
7535     while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
7536         /* check to see if we've been asked to pause */
7537         if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
7538             volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
7539             opr_cv_broadcast(&volume_LRU.cv);
7540             do {
7541                 VOL_CV_WAIT(&volume_LRU.cv);
7542             } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
7543         }
7544
7545         /* scheduling can happen outside the glock */
7546         VOL_UNLOCK;
7547
7548         /* figure out what is next on the schedule */
7549
7550         /* figure out a potential schedule for the new generation first */
7551         overdue = 0;
7552         min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
7553         min_idx = 0;
7554         min_op = 0;
7555         if (min_delay > volume_LRU.scan_interval[0]) {
7556             /* unsigned overflow -- we're overdue to run this scan */
7557             min_delay = 0;
7558             overdue = 1;
7559         }
7560
7561         /* if we're not overdue for gen 0, figure out schedule for candidate gen */
7562         if (!overdue) {
7563             i = VLRU_QUEUE_CANDIDATE;
7564             delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
7565             if (delay < min_delay) {
7566                 min_delay = delay;
7567                 min_idx = i;
7568             }
7569             if (delay > volume_LRU.scan_interval[i]) {
7570                 /* unsigned overflow -- we're overdue to run this scan */
7571                 min_delay = 0;
7572                 min_idx = i;
7573                 overdue = 1;
7574             }
7575         }
7576
7577         /* if we're still not overdue for something, figure out schedules for promotions */
7578         for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
7579             delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
7580             if (delay < min_delay) {
7581                 min_delay = delay;
7582                 min_idx = i;
7583                 min_op = 1;
7584             }
7585             if (delay > volume_LRU.promotion_interval[i]) {
7586                 /* unsigned overflow -- we're overdue to run this promotion */
7587                 min_delay = 0;
7588                 min_idx = i;
7589                 min_op = 1;
7590                 overdue = 1;
7591                 break;
7592             }
7593         }
7594
7595         /* sleep as needed */
7596         if (min_delay) {
7597             sleep(min_delay);
7598         }
7599
7600         /* do whatever is next */
7601         VOL_LOCK;
7602         if (min_op) {
7603             VLRU_Promote_r(min_idx);
7604             VLRU_Demote_r(min_idx+1);
7605         } else {
7606             VLRU_Scan_r(min_idx);
7607         }
7608         now = FT_ApproxTime();
7609     }
7610
7611     Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
7612
7613     /* signal that scanner is down */
7614     volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7615     opr_cv_broadcast(&volume_LRU.cv);
7616     VOL_UNLOCK;
7617     return NULL;
7618 }
7619
7620 /**
7621  * promote volumes from one VLRU generation to the next.
7622  *
7623  * This routine scans a VLRU generation looking for volumes which are
7624  * eligible to be promoted to the next generation.  All volumes which
7625  * meet the eligibility requirement are promoted.
7626  *
7627  * Promotion eligibility is based upon meeting both of the following
7628  * requirements:
7629  *
7630  *    @arg The volume has been accessed since the last promotion:
7631  *         @c (vp->stats.last_get >= vp->stats.last_promote)
7632  *    @arg The last promotion occurred at least
7633  *         @c volume_LRU.promotion_interval[idx] seconds ago
7634  *
7635  * As a performance optimization, promotions are "globbed".  In other
7636  * words, we promote arbitrarily large contiguous sublists of elements
7637  * as one operation.
7638  *
7639  * @param[in] idx  VLRU queue index to scan
7640  *
7641  * @note DAFS only
7642  *
7643  * @internal VLRU internal use only.
7644  */
7645 static void
7646 VLRU_Promote_r(int idx)
7647 {
7648     int len, chaining, promote;
7649     afs_uint32 now, thresh;
7650     struct rx_queue *qp, *nqp;
7651     Volume * vp, *start = NULL, *end = NULL;
7652
7653     /* get exclusive access to two chains, and drop the glock */
7654     VLRU_Wait_r(&volume_LRU.q[idx]);
7655     VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7656     VLRU_Wait_r(&volume_LRU.q[idx+1]);
7657     VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
7658     VOL_UNLOCK;
7659
7660     thresh = volume_LRU.promotion_interval[idx];
7661     now = FT_ApproxTime();
7662
7663     len = chaining = 0;
7664     for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7665         vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7666         promote = (((vp->stats.last_promote + thresh) <= now) &&
7667                    (vp->stats.last_get >= vp->stats.last_promote));
7668
7669         if (chaining) {
7670             if (promote) {
7671                 vp->vlru.idx++;
7672                 len++;
7673                 start = vp;
7674             } else {
7675                 /* promote and prepend chain */
7676                 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7677                 chaining = 0;
7678             }
7679         } else {
7680             if (promote) {
7681                 vp->vlru.idx++;
7682                 len++;
7683                 chaining = 1;
7684                 start = end = vp;
7685             }
7686         }
7687     }
7688
7689     if (chaining) {
7690         /* promote and prepend */
7691         queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7692     }
7693
7694     if (len) {
7695         volume_LRU.q[idx].len -= len;
7696         volume_LRU.q[idx+1].len += len;
7697     }
7698
7699     /* release exclusive access to the two chains */
7700     VOL_LOCK;
7701     volume_LRU.last_promotion[idx] = now;
7702     VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
7703     VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7704 }
7705
7706 /* run the demotions */
7707 static void
7708 VLRU_Demote_r(int idx)
7709 {
7710     Error ec;
7711     int len, chaining, demote;
7712     afs_uint32 now, thresh;
7713     struct rx_queue *qp, *nqp;
7714     Volume * vp, *start = NULL, *end = NULL;
7715     Volume ** salv_flag_vec = NULL;
7716     int salv_vec_offset = 0;
7717
7718     opr_Assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
7719
7720     /* get exclusive access to two chains, and drop the glock */
7721     VLRU_Wait_r(&volume_LRU.q[idx-1]);
7722     VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
7723     VLRU_Wait_r(&volume_LRU.q[idx]);
7724     VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7725     VOL_UNLOCK;
7726
7727     /* no big deal if this allocation fails */
7728     if (volume_LRU.q[idx].len) {
7729         salv_flag_vec = malloc(volume_LRU.q[idx].len * sizeof(Volume *));
7730     }
7731
7732     now = FT_ApproxTime();
7733     thresh = volume_LRU.promotion_interval[idx-1];
7734
7735     len = chaining = 0;
7736     for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7737         vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7738         demote = (((vp->stats.last_promote + thresh) <= now) &&
7739                   (vp->stats.last_get < (now - thresh)));
7740
7741         /* we now do volume update list DONT_SALVAGE flag setting during
7742          * demotion passes */
7743         if (salv_flag_vec &&
7744             !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7745             demote &&
7746             (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7747             (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7748             salv_flag_vec[salv_vec_offset++] = vp;
7749             VCreateReservation_r(vp);
7750         }
7751
7752         if (chaining) {
7753             if (demote) {
7754                 vp->vlru.idx--;
7755                 len++;
7756                 start = vp;
7757             } else {
7758                 /* demote and append chain */
7759                 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7760                 chaining = 0;
7761             }
7762         } else {
7763             if (demote) {
7764                 vp->vlru.idx--;
7765                 len++;
7766                 chaining = 1;
7767                 start = end = vp;
7768             }
7769         }
7770     }
7771
7772     if (chaining) {
7773         queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7774     }
7775
7776     if (len) {
7777         volume_LRU.q[idx].len -= len;
7778         volume_LRU.q[idx-1].len += len;
7779     }
7780
7781     /* release exclusive access to the two chains */
7782     VOL_LOCK;
7783     VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7784     VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
7785
7786     /* now go back and set the DONT_SALVAGE flags as appropriate */
7787     if (salv_flag_vec) {
7788         int i;
7789         for (i = 0; i < salv_vec_offset; i++) {
7790             vp = salv_flag_vec[i];
7791             if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7792                 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7793                 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7794                 ec = VHold_r(vp);
7795                 if (!ec) {
7796                     V_attachFlags(vp) |= VOL_HDR_DONTSALV;
7797                     V_dontSalvage(vp) = DONT_SALVAGE;
7798                     VUpdateVolume_r(&ec, vp, 0);
7799                     VPutVolume_r(vp);
7800                 }
7801             }
7802             VCancelReservation_r(vp);
7803         }
7804         free(salv_flag_vec);
7805     }
7806 }
7807
7808 /* run a pass of the VLRU GC scanner */
7809 static void
7810 VLRU_Scan_r(int idx)
7811 {
7812     afs_uint32 now, thresh;
7813     struct rx_queue *qp, *nqp;
7814     Volume * vp;
7815     int i, locked = 1;
7816
7817     opr_Assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
7818
7819     /* gain exclusive access to the idx VLRU */
7820     VLRU_Wait_r(&volume_LRU.q[idx]);
7821     VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7822
7823     if (idx != VLRU_QUEUE_CANDIDATE) {
7824         /* gain exclusive access to the candidate VLRU */
7825         VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7826         VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7827     }
7828
7829     now = FT_ApproxTime();
7830     thresh = now - VLRU_offline_thresh;
7831
7832     /* perform candidate selection and soft detaching */
7833     if (idx == VLRU_QUEUE_CANDIDATE) {
7834         /* soft detach some volumes from the candidate pool */
7835         VOL_UNLOCK;
7836         locked = 0;
7837
7838         for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7839             vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7840             if (i >= VLRU_offline_max) {
7841                 break;
7842             }
7843             /* check timestamp to see if it's a candidate for soft detaching */
7844             if (vp->stats.last_get <= thresh) {
7845                 VOL_LOCK;
7846                 if (VCheckSoftDetach(vp, thresh))
7847                     i++;
7848                 VOL_UNLOCK;
7849             }
7850         }
7851     } else {
7852         /* scan for volumes to become soft detach candidates */
7853         for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
7854             vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7855
7856             /* check timestamp to see if it's a candidate for soft detaching */
7857             if (vp->stats.last_get <= thresh) {
7858                 VCheckSoftDetachCandidate(vp, thresh);
7859             }
7860
7861             if (!(i&0x7f)) {   /* lock coarsening optimization */
7862                 VOL_UNLOCK;
7863                 pthread_yield();
7864                 VOL_LOCK;
7865             }
7866         }
7867     }
7868
7869     /* relinquish exclusive access to the VLRU chains */
7870     if (!locked) {
7871         VOL_LOCK;
7872     }
7873     volume_LRU.last_scan[idx] = now;
7874     if (idx != VLRU_QUEUE_CANDIDATE) {
7875         VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7876     }
7877     VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7878 }
7879
7880 /* check whether volume is safe to soft detach
7881  * caller MUST NOT hold a ref count on vp */
7882 static int
7883 VCheckSoftDetach(Volume * vp, afs_uint32 thresh)
7884 {
7885     int ret=0;
7886
7887     if (vp->nUsers || vp->nWaiters)
7888         return 0;
7889
7890     if (vp->stats.last_get <= thresh) {
7891         ret = VSoftDetachVolume_r(vp, thresh);
7892     }
7893
7894     return ret;
7895 }
7896
7897 /* check whether volume should be made a
7898  * soft detach candidate */
7899 static int
7900 VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh)
7901 {
7902     int idx, ret = 0;
7903     if (vp->nUsers || vp->nWaiters)
7904         return 0;
7905
7906     idx = vp->vlru.idx;
7907
7908     opr_Assert(idx == VLRU_QUEUE_NEW);
7909
7910     if (vp->stats.last_get <= thresh) {
7911         /* move to candidate pool */
7912         queue_Remove(&vp->vlru);
7913         volume_LRU.q[VLRU_QUEUE_NEW].len--;
7914         queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
7915         vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
7916         volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
7917         ret = 1;
7918     }
7919
7920     return ret;
7921 }
7922
7923
7924 /* begin exclusive access on VLRU */
7925 static void
7926 VLRU_BeginExclusive_r(struct VLRU_q * q)
7927 {
7928     opr_Assert(q->busy == 0);
7929     q->busy = 1;
7930 }
7931
7932 /* end exclusive access on VLRU */
7933 static void
7934 VLRU_EndExclusive_r(struct VLRU_q * q)
7935 {
7936     opr_Assert(q->busy);
7937     q->busy = 0;
7938     opr_cv_broadcast(&q->cv);
7939 }
7940
7941 /* wait for another thread to end exclusive access on VLRU */
7942 static void
7943 VLRU_Wait_r(struct VLRU_q * q)
7944 {
7945     while(q->busy) {
7946         VOL_CV_WAIT(&q->cv);
7947     }
7948 }
7949
7950 /* demand attach fs
7951  * volume soft detach
7952  *
7953  * caller MUST NOT hold a ref count on vp */
7954 static int
7955 VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh)
7956 {
7957     afs_uint32 ts_save;
7958     int ret = 0;
7959
7960     opr_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7961
7962     ts_save = vp->stats.last_get;
7963     if (ts_save > thresh)
7964         return 0;
7965
7966     if (vp->nUsers || vp->nWaiters)
7967         return 0;
7968
7969     if (VIsExclusiveState(V_attachState(vp))) {
7970         return 0;
7971     }
7972
7973     switch (V_attachState(vp)) {
7974     case VOL_STATE_UNATTACHED:
7975     case VOL_STATE_PREATTACHED:
7976     case VOL_STATE_ERROR:
7977     case VOL_STATE_GOING_OFFLINE:
7978     case VOL_STATE_SHUTTING_DOWN:
7979     case VOL_STATE_SALVAGING:
7980     case VOL_STATE_DELETED:
7981         volume_LRU.q[vp->vlru.idx].len--;
7982
7983         /* create and cancel a reservation to
7984          * give the volume an opportunity to
7985          * be deallocated */
7986         VCreateReservation_r(vp);
7987         queue_Remove(&vp->vlru);
7988         vp->vlru.idx = VLRU_QUEUE_INVALID;
7989         V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7990         VCancelReservation_r(vp);
7991         return 0;
7992     default:
7993         break;
7994     }
7995
7996     /* hold the volume and take it offline.
7997      * no need for reservations, as VHold_r
7998      * takes care of that internally. */
7999     if (VHold_r(vp) == 0) {
8000         /* vhold drops the glock, so now we should
8001          * check to make sure we aren't racing against
8002          * other threads.  if we are racing, offlining vp
8003          * would be wasteful, and block the scanner for a while
8004          */
8005         if (vp->nWaiters ||
8006             (vp->nUsers > 1) ||
8007             (vp->shuttingDown) ||
8008             (vp->goingOffline) ||
8009             (vp->stats.last_get != ts_save)) {
8010             /* looks like we're racing someone else. bail */
8011             VPutVolume_r(vp);
8012             vp = NULL;
8013         } else {
8014             /* pull it off the VLRU */
8015             opr_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
8016             volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
8017             queue_Remove(&vp->vlru);
8018             vp->vlru.idx = VLRU_QUEUE_INVALID;
8019             V_attachFlags(vp) &= ~(VOL_ON_VLRU);
8020
8021             /* take if offline */
8022             VOffline_r(vp, "volume has been soft detached");
8023
8024             /* invalidate the volume header cache */
8025             FreeVolumeHeader(vp);
8026
8027             /* update stats */
8028             IncUInt64(&VStats.soft_detaches);
8029             vp->stats.soft_detaches++;
8030
8031             /* put in pre-attached state so demand
8032              * attacher can work on it */
8033             VChangeState_r(vp, VOL_STATE_PREATTACHED);
8034             ret = 1;
8035         }
8036     }
8037     return ret;
8038 }
8039 #endif /* AFS_DEMAND_ATTACH_FS */
8040
8041
8042 /***************************************************/
8043 /* Volume Header Cache routines                    */
8044 /***************************************************/
8045
8046 /**
8047  * volume header cache.
8048  */
8049 struct volume_hdr_LRU_t volume_hdr_LRU;
8050
8051 /**
8052  * initialize the volume header cache.
8053  *
8054  * @param[in] howMany  number of header cache entries to preallocate
8055  *
8056  * @pre VOL_LOCK held.  Function has never been called before.
8057  *
8058  * @post howMany cache entries are allocated, initialized, and added
8059  *       to the LRU list.  Header cache statistics are initialized.
8060  *
8061  * @note only applicable to fileServer program type.  Should only be
8062  *       called once during volume package initialization.
8063  *
8064  * @internal volume package internal use only.
8065  */
8066 static void
8067 VInitVolumeHeaderCache(afs_uint32 howMany)
8068 {
8069     struct volHeader *hp;
8070     if (programType != fileServer)
8071         return;
8072     queue_Init(&volume_hdr_LRU);
8073     volume_hdr_LRU.stats.free = 0;
8074     volume_hdr_LRU.stats.used = howMany;
8075     volume_hdr_LRU.stats.attached = 0;
8076     hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
8077     opr_Assert(hp != NULL);
8078
8079     while (howMany--)
8080         /* We are using ReleaseVolumeHeader to initialize the values on the header list
8081          * to ensure they have the right values
8082          */
8083         ReleaseVolumeHeader(hp++);
8084 }
8085
8086 /* get a volume header off of the volume header LRU.
8087  *
8088  * @return volume header
8089  *  @retval NULL no usable volume header is available on the LRU
8090  *
8091  * @pre VOL_LOCK held
8092  *
8093  * @post for DAFS, if the returned header is associated with a volume, that
8094  *       volume is NOT in an exclusive state
8095  *
8096  * @internal volume package internal use only.
8097  */
8098 #ifdef AFS_DEMAND_ATTACH_FS
8099 static struct volHeader*
8100 GetVolHeaderFromLRU(void)
8101 {
8102     struct volHeader *hd = NULL, *qh, *nqh;
8103     /* Usually, a volume in an exclusive state will not have its header on
8104      * the LRU. However, it is possible for this to occur when a salvage
8105      * request is received over FSSYNC, and possibly in other corner cases.
8106      * So just skip over headers whose volumes are in an exclusive state. We
8107      * could VWaitExclusiveState_r instead, but not waiting is faster and
8108      * easier to do */
8109     for (queue_Scan(&volume_hdr_LRU, qh, nqh, volHeader)) {
8110         if (!qh->back || !VIsExclusiveState(V_attachState(qh->back))) {
8111             queue_Remove(qh);
8112             hd = qh;
8113             break;
8114         }
8115     }
8116     return hd;
8117 }
8118 #else /* AFS_DEMAND_ATTACH_FS */
8119 static struct volHeader*
8120 GetVolHeaderFromLRU(void)
8121 {
8122     struct volHeader *hd = NULL;
8123     if (queue_IsNotEmpty(&volume_hdr_LRU)) {
8124         hd = queue_First(&volume_hdr_LRU, volHeader);
8125         queue_Remove(hd);
8126     }
8127     return hd;
8128 }
8129 #endif /* !AFS_DEMAND_ATTACH_FS */
8130
8131 /**
8132  * get a volume header and attach it to the volume object.
8133  *
8134  * @param[in] vp  pointer to volume object
8135  *
8136  * @return cache entry status
8137  *    @retval 0  volume header was newly attached; cache data is invalid
8138  *    @retval 1  volume header was previously attached; cache data is valid
8139  *
8140  * @pre VOL_LOCK held.  For DAFS, lightweight ref must be held on volume object.
8141  *
8142  * @post volume header attached to volume object.  if necessary, header cache
8143  *       entry on LRU is synchronized to disk.  Header is removed from LRU list.
8144  *
8145  * @note VOL_LOCK may be dropped
8146  *
8147  * @warning this interface does not load header data from disk.  it merely
8148  *          attaches a header object to the volume object, and may sync the old
8149  *          header cache data out to disk in the process.
8150  *
8151  * @internal volume package internal use only.
8152  */
8153 static int
8154 GetVolumeHeader(Volume * vp)
8155 {
8156     Error error;
8157     struct volHeader *hd;
8158     int old;
8159     static int everLogged = 0;
8160
8161 #ifdef AFS_DEMAND_ATTACH_FS
8162     VolState vp_save = 0, back_save = 0;
8163
8164     /* XXX debug 9/19/05 we've apparently got
8165      * a ref counting bug somewhere that's
8166      * breaking the nUsers == 0 => header on LRU
8167      * assumption */
8168     if (vp->header && queue_IsNotOnQueue(vp->header)) {
8169         Log("nUsers == 0, but header not on LRU\n");
8170         return 1;
8171     }
8172 #endif
8173
8174     old = (vp->header != NULL); /* old == volume already has a header */
8175
8176     if (programType != fileServer) {
8177         /* for volume utilities, we allocate volHeaders as needed */
8178         if (!vp->header) {
8179             hd = calloc(1, sizeof(*vp->header));
8180             opr_Assert(hd != NULL);
8181             vp->header = hd;
8182             hd->back = vp;
8183 #ifdef AFS_DEMAND_ATTACH_FS
8184             V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8185 #endif
8186         }
8187     } else {
8188         /* for the fileserver, we keep a volume header cache */
8189         if (old) {
8190             /* the header we previously dropped in the lru is
8191              * still available. pull it off the lru and return */
8192             hd = vp->header;
8193             queue_Remove(hd);
8194             opr_Assert(hd->back == vp);
8195 #ifdef AFS_DEMAND_ATTACH_FS
8196             V_attachFlags(vp) &= ~(VOL_HDR_IN_LRU);
8197 #endif
8198         } else {
8199             hd = GetVolHeaderFromLRU();
8200             if (!hd) {
8201                 /* LRU is empty, so allocate a new volHeader
8202                  * this is probably indicative of a leak, so let the user know */
8203                 hd = calloc(1, sizeof(struct volHeader));
8204                 opr_Assert(hd != NULL);
8205                 if (!everLogged) {
8206                     Log("****Allocated more volume headers, probably leak****\n");
8207                     everLogged = 1;
8208                 }
8209                 volume_hdr_LRU.stats.free++;
8210             }
8211             if (hd->back) {
8212                 /* this header used to belong to someone else.
8213                  * we'll need to check if the header needs to
8214                  * be sync'd out to disk */
8215
8216 #ifdef AFS_DEMAND_ATTACH_FS
8217                 /* GetVolHeaderFromLRU had better not give us back a header
8218                  * with a volume in exclusive state... */
8219                 opr_Assert(!VIsExclusiveState(V_attachState(hd->back)));
8220 #endif
8221
8222                 if (hd->diskstuff.inUse) {
8223                     /* volume was in use, so we'll need to sync
8224                      * its header to disk */
8225
8226 #ifdef AFS_DEMAND_ATTACH_FS
8227                     back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
8228                     vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
8229                     VCreateReservation_r(hd->back);
8230                     VOL_UNLOCK;
8231 #endif
8232
8233                     WriteVolumeHeader_r(&error, hd->back);
8234                     /* Ignore errors; catch them later */
8235
8236 #ifdef AFS_DEMAND_ATTACH_FS
8237                     VOL_LOCK;
8238 #endif
8239                 }
8240
8241                 hd->back->header = NULL;
8242 #ifdef AFS_DEMAND_ATTACH_FS
8243                 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
8244
8245                 if (hd->diskstuff.inUse) {
8246                     VChangeState_r(hd->back, back_save);
8247                     VCancelReservation_r(hd->back);
8248                     VChangeState_r(vp, vp_save);
8249                 }
8250 #endif
8251             } else {
8252                 volume_hdr_LRU.stats.attached++;
8253             }
8254             hd->back = vp;
8255             vp->header = hd;
8256 #ifdef AFS_DEMAND_ATTACH_FS
8257             V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8258 #endif
8259         }
8260         volume_hdr_LRU.stats.free--;
8261         volume_hdr_LRU.stats.used++;
8262     }
8263     IncUInt64(&VStats.hdr_gets);
8264 #ifdef AFS_DEMAND_ATTACH_FS
8265     IncUInt64(&vp->stats.hdr_gets);
8266     vp->stats.last_hdr_get = FT_ApproxTime();
8267 #endif
8268     return old;
8269 }
8270
8271
8272 /**
8273  * make sure volume header is attached and contains valid cache data.
8274  *
8275  * @param[out] ec  outbound error code
8276  * @param[in]  vp  pointer to volume object
8277  *
8278  * @pre VOL_LOCK held.  For DAFS, lightweight ref held on vp.
8279  *
8280  * @post header cache entry attached, and loaded with valid data, or
8281  *       *ec is nonzero, and the header is released back into the LRU.
8282  *
8283  * @internal volume package internal use only.
8284  */
8285 static void
8286 LoadVolumeHeader(Error * ec, Volume * vp)
8287 {
8288 #ifdef AFS_DEMAND_ATTACH_FS
8289     VolState state_save;
8290     afs_uint32 now;
8291     *ec = 0;
8292
8293     if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8294         IncUInt64(&VStats.hdr_loads);
8295         state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
8296         VOL_UNLOCK;
8297
8298         ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8299                    sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8300                    VOLUMEINFOVERSION);
8301         IncUInt64(&vp->stats.hdr_loads);
8302         now = FT_ApproxTime();
8303
8304         VOL_LOCK;
8305         if (!*ec) {
8306             V_attachFlags(vp) |= VOL_HDR_LOADED;
8307             vp->stats.last_hdr_load = now;
8308         }
8309         VChangeState_r(vp, state_save);
8310     }
8311 #else /* AFS_DEMAND_ATTACH_FS */
8312     *ec = 0;
8313     if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8314         IncUInt64(&VStats.hdr_loads);
8315
8316         ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8317                    sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8318                    VOLUMEINFOVERSION);
8319     }
8320 #endif /* AFS_DEMAND_ATTACH_FS */
8321     if (*ec) {
8322         /* maintain (nUsers==0) => header in LRU invariant */
8323         FreeVolumeHeader(vp);
8324     }
8325 }
8326
8327 /**
8328  * release a header cache entry back into the LRU list.
8329  *
8330  * @param[in] hd  pointer to volume header cache object
8331  *
8332  * @pre VOL_LOCK held.
8333  *
8334  * @post header cache object appended onto end of LRU list.
8335  *
8336  * @note only applicable to fileServer program type.
8337  *
8338  * @note used to place a header cache entry back into the
8339  *       LRU pool without invalidating it as a cache entry.
8340  *
8341  * @internal volume package internal use only.
8342  */
8343 static void
8344 ReleaseVolumeHeader(struct volHeader *hd)
8345 {
8346     if (programType != fileServer)
8347         return;
8348     if (!hd || queue_IsOnQueue(hd))     /* no header, or header already released */
8349         return;
8350     queue_Append(&volume_hdr_LRU, hd);
8351 #ifdef AFS_DEMAND_ATTACH_FS
8352     if (hd->back) {
8353         V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
8354     }
8355 #endif
8356     volume_hdr_LRU.stats.free++;
8357     volume_hdr_LRU.stats.used--;
8358 }
8359
8360 /**
8361  * free/invalidate a volume header cache entry.
8362  *
8363  * @param[in] vp  pointer to volume object
8364  *
8365  * @pre VOL_LOCK is held.
8366  *
8367  * @post For fileserver, header cache entry is returned to LRU, and it is
8368  *       invalidated as a cache entry.  For volume utilities, the header
8369  *       cache entry is freed.
8370  *
8371  * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
8372  *       whenever it is necessary to invalidate the header cache entry.
8373  *
8374  * @see ReleaseVolumeHeader
8375  *
8376  * @internal volume package internal use only.
8377  */
8378 static void
8379 FreeVolumeHeader(Volume * vp)
8380 {
8381     struct volHeader *hd = vp->header;
8382     if (!hd)
8383         return;
8384     if (programType == fileServer) {
8385         ReleaseVolumeHeader(hd);
8386         hd->back = NULL;
8387     } else {
8388         free(hd);
8389     }
8390 #ifdef AFS_DEMAND_ATTACH_FS
8391     V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
8392 #endif
8393     volume_hdr_LRU.stats.attached--;
8394     vp->header = NULL;
8395 }
8396
8397
8398 /***************************************************/
8399 /* Volume Hash Table routines                      */
8400 /***************************************************/
8401
8402 /**
8403  * set size of volume object hash table.
8404  *
8405  * @param[in] logsize   log(2) of desired hash table size
8406  *
8407  * @return operation status
8408  *    @retval 0 success
8409  *    @retval -1 failure
8410  *
8411  * @pre MUST be called prior to VInitVolumePackage2
8412  *
8413  * @post Volume Hash Table will have 2^logsize buckets
8414  */
8415 int
8416 VSetVolHashSize(int logsize)
8417 {
8418     /* 64 to 268435456 hash buckets seems like a reasonable range */
8419     if ((logsize < 6 ) || (logsize > 28)) {
8420         return -1;
8421     }
8422
8423     if (!VInit) {
8424         VolumeHashTable.Size = opr_jhash_size(logsize);
8425         VolumeHashTable.Mask = opr_jhash_mask(logsize);
8426     } else {
8427         /* we can't yet support runtime modification of this
8428          * parameter. we'll need a configuration rwlock to
8429          * make runtime modification feasible.... */
8430         return -1;
8431     }
8432     return 0;
8433 }
8434
8435 /**
8436  * initialize dynamic data structures for volume hash table.
8437  *
8438  * @post hash table is allocated, and fields are initialized.
8439  *
8440  * @internal volume package internal use only.
8441  */
8442 static void
8443 VInitVolumeHash(void)
8444 {
8445     int i;
8446
8447     VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
8448                                                            sizeof(VolumeHashChainHead));
8449     opr_Assert(VolumeHashTable.Table != NULL);
8450
8451     for (i=0; i < VolumeHashTable.Size; i++) {
8452         queue_Init(&VolumeHashTable.Table[i]);
8453 #ifdef AFS_DEMAND_ATTACH_FS
8454         opr_cv_init(&VolumeHashTable.Table[i].chain_busy_cv);
8455 #endif /* AFS_DEMAND_ATTACH_FS */
8456     }
8457 }
8458
8459 /**
8460  * add a volume object to the hash table.
8461  *
8462  * @param[in] vp      pointer to volume object
8463  * @param[in] hashid  hash of volume id
8464  *
8465  * @pre VOL_LOCK is held.  For DAFS, caller must hold a lightweight
8466  *      reference on vp.
8467  *
8468  * @post volume is added to hash chain.
8469  *
8470  * @internal volume package internal use only.
8471  *
8472  * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8473  *       asynchronous hash chain reordering to finish.
8474  */
8475 static void
8476 AddVolumeToHashTable(Volume * vp, VolumeId hashid)
8477 {
8478     VolumeHashChainHead * head;
8479
8480     if (queue_IsOnQueue(vp))
8481         return;
8482
8483     head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
8484
8485 #ifdef AFS_DEMAND_ATTACH_FS
8486     /* wait for the hash chain to become available */
8487     VHashWait_r(head);
8488
8489     V_attachFlags(vp) |= VOL_IN_HASH;
8490     vp->chainCacheCheck = ++head->cacheCheck;
8491 #endif /* AFS_DEMAND_ATTACH_FS */
8492
8493     head->len++;
8494     vp->hashid = hashid;
8495     queue_Append(head, vp);
8496 }
8497
8498 /**
8499  * delete a volume object from the hash table.
8500  *
8501  * @param[in] vp  pointer to volume object
8502  *
8503  * @pre VOL_LOCK is held.  For DAFS, caller must hold a lightweight
8504  *      reference on vp.
8505  *
8506  * @post volume is removed from hash chain.
8507  *
8508  * @internal volume package internal use only.
8509  *
8510  * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8511  *       asynchronous hash chain reordering to finish.
8512  */
8513 static void
8514 DeleteVolumeFromHashTable(Volume * vp)
8515 {
8516     VolumeHashChainHead * head;
8517
8518     if (!queue_IsOnQueue(vp))
8519         return;
8520
8521     head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
8522
8523 #ifdef AFS_DEMAND_ATTACH_FS
8524     /* wait for the hash chain to become available */
8525     VHashWait_r(head);
8526
8527     V_attachFlags(vp) &= ~(VOL_IN_HASH);
8528     head->cacheCheck++;
8529 #endif /* AFS_DEMAND_ATTACH_FS */
8530
8531     head->len--;
8532     queue_Remove(vp);
8533     /* do NOT reset hashid to zero, as the online
8534      * salvager package may need to know the volume id
8535      * after the volume is removed from the hash */
8536 }
8537
8538 /**
8539  * lookup a volume object in the hash table given a volume id.
8540  *
8541  * @param[out] ec        error code return
8542  * @param[in]  volumeId  volume id
8543  * @param[in]  hint      volume object which we believe could be the correct
8544                          mapping
8545  *
8546  * @return volume object pointer
8547  *    @retval NULL  no such volume id is registered with the hash table.
8548  *
8549  * @pre VOL_LOCK is held.  For DAFS, caller must hold a lightweight
8550         ref on hint.
8551  *
8552  * @post volume object with the given id is returned.  volume object and
8553  *       hash chain access statistics are updated.  hash chain may have
8554  *       been reordered.
8555  *
8556  * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8557  *       asynchronous hash chain reordering operation to finish, or
8558  *       in order for us to perform an asynchronous chain reordering.
8559  *
8560  * @note Hash chain reorderings occur when the access count for the
8561  *       volume object being looked up exceeds the sum of the previous
8562  *       node's (the node ahead of it in the hash chain linked list)
8563  *       access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
8564  *
8565  * @note For DAFS, the hint parameter allows us to short-circuit if the
8566  *       cacheCheck fields match between the hash chain head and the
8567  *       hint volume object.
8568  */
8569 Volume *
8570 VLookupVolume_r(Error * ec, VolumeId volumeId, Volume * hint)
8571 {
8572     int looks = 0;
8573     Volume * vp, *np;
8574 #ifdef AFS_DEMAND_ATTACH_FS
8575     Volume *pp;
8576 #endif
8577     VolumeHashChainHead * head;
8578     *ec = 0;
8579
8580     head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
8581
8582 #ifdef AFS_DEMAND_ATTACH_FS
8583     /* wait for the hash chain to become available */
8584     VHashWait_r(head);
8585
8586     /* check to see if we can short circuit without walking the hash chain */
8587     if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
8588         IncUInt64(&hint->stats.hash_short_circuits);
8589         return hint;
8590     }
8591 #endif /* AFS_DEMAND_ATTACH_FS */
8592
8593     /* someday we need to either do per-chain locks, RWlocks,
8594      * or both for volhash access.
8595      * (and move to a data structure with better cache locality) */
8596
8597     /* search the chain for this volume id */
8598     for(queue_Scan(head, vp, np, Volume)) {
8599         looks++;
8600         if (vp->hashid == volumeId) {
8601             break;
8602         }
8603     }
8604
8605     if (queue_IsEnd(head, vp)) {
8606         vp = NULL;
8607     }
8608
8609 #ifdef AFS_DEMAND_ATTACH_FS
8610     /* update hash chain statistics */
8611     {
8612         afs_uint64 lks;
8613         FillInt64(lks, 0, looks);
8614         AddUInt64(head->looks, lks, &head->looks);
8615         AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
8616         IncUInt64(&head->gets);
8617     }
8618
8619     if (vp) {
8620         afs_uint64 thresh;
8621         IncUInt64(&vp->stats.hash_lookups);
8622
8623         /* for demand attach fileserver, we permit occasional hash chain reordering
8624          * so that frequently looked up volumes move towards the head of the chain */
8625         pp = queue_Prev(vp, Volume);
8626         if (!queue_IsEnd(head, pp)) {
8627             FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
8628             AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
8629             if (GEInt64(vp->stats.hash_lookups, thresh)) {
8630                 VReorderHash_r(head, pp, vp);
8631             }
8632         }
8633
8634         /* update the short-circuit cache check */
8635         vp->chainCacheCheck = head->cacheCheck;
8636     }
8637 #endif /* AFS_DEMAND_ATTACH_FS */
8638
8639     return vp;
8640 }
8641
8642 #ifdef AFS_DEMAND_ATTACH_FS
8643 /* perform volume hash chain reordering.
8644  *
8645  * advance a subchain beginning at vp ahead of
8646  * the adjacent subchain ending at pp */
8647 static void
8648 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
8649 {
8650     Volume *tp, *np, *lp;
8651     afs_uint64 move_thresh;
8652
8653     /* this should never be called if the chain is already busy, so
8654      * no need to wait for other exclusive chain ops to finish */
8655
8656     /* this is a rather heavy set of operations,
8657      * so let's set the chain busy flag and drop
8658      * the vol_glock */
8659     VHashBeginExclusive_r(head);
8660     VOL_UNLOCK;
8661
8662     /* scan forward in the chain from vp looking for the last element
8663      * in the chain we want to advance */
8664     FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
8665     AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
8666     for(queue_ScanFrom(head, vp, tp, np, Volume)) {
8667         if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
8668             break;
8669         }
8670     }
8671     lp = queue_Prev(tp, Volume);
8672
8673     /* scan backwards from pp to determine where to splice and
8674      * insert the subchain we're advancing */
8675     for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
8676         if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
8677             break;
8678         }
8679     }
8680     tp = queue_Next(tp, Volume);
8681
8682     /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
8683     queue_MoveChainBefore(tp,vp,lp);
8684
8685     VOL_LOCK;
8686     IncUInt64(&VStats.hash_reorders);
8687     head->cacheCheck++;
8688     IncUInt64(&head->reorders);
8689
8690     /* wake up any threads waiting for the hash chain */
8691     VHashEndExclusive_r(head);
8692 }
8693
8694
8695 /* demand-attach fs volume hash
8696  * asynchronous exclusive operations */
8697
8698 /**
8699  * begin an asynchronous exclusive operation on a volume hash chain.
8700  *
8701  * @param[in] head   pointer to volume hash chain head object
8702  *
8703  * @pre VOL_LOCK held.  hash chain is quiescent.
8704  *
8705  * @post hash chain marked busy.
8706  *
8707  * @note this interface is used in conjunction with VHashEndExclusive_r and
8708  *       VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8709  *       volume hash chain.  Its main use case is hash chain reordering, which
8710  *       has the potential to be a highly latent operation.
8711  *
8712  * @see VHashEndExclusive_r
8713  * @see VHashWait_r
8714  *
8715  * @note DAFS only
8716  *
8717  * @internal volume package internal use only.
8718  */
8719 static void
8720 VHashBeginExclusive_r(VolumeHashChainHead * head)
8721 {
8722     opr_Assert(head->busy == 0);
8723     head->busy = 1;
8724 }
8725
8726 /**
8727  * relinquish exclusive ownership of a volume hash chain.
8728  *
8729  * @param[in] head   pointer to volume hash chain head object
8730  *
8731  * @pre VOL_LOCK held.  thread owns the hash chain exclusively.
8732  *
8733  * @post hash chain is marked quiescent.  threads awaiting use of
8734  *       chain are awakened.
8735  *
8736  * @see VHashBeginExclusive_r
8737  * @see VHashWait_r
8738  *
8739  * @note DAFS only
8740  *
8741  * @internal volume package internal use only.
8742  */
8743 static void
8744 VHashEndExclusive_r(VolumeHashChainHead * head)
8745 {
8746     opr_Assert(head->busy);
8747     head->busy = 0;
8748     opr_cv_broadcast(&head->chain_busy_cv);
8749 }
8750
8751 /**
8752  * wait for all asynchronous operations on a hash chain to complete.
8753  *
8754  * @param[in] head   pointer to volume hash chain head object
8755  *
8756  * @pre VOL_LOCK held.
8757  *
8758  * @post hash chain object is quiescent.
8759  *
8760  * @see VHashBeginExclusive_r
8761  * @see VHashEndExclusive_r
8762  *
8763  * @note DAFS only
8764  *
8765  * @note This interface should be called before any attempt to
8766  *       traverse the hash chain.  It is permissible for a thread
8767  *       to gain exclusive access to the chain, and then perform
8768  *       latent operations on the chain asynchronously wrt the
8769  *       VOL_LOCK.
8770  *
8771  * @warning if waiting is necessary, VOL_LOCK is dropped
8772  *
8773  * @internal volume package internal use only.
8774  */
8775 static void
8776 VHashWait_r(VolumeHashChainHead * head)
8777 {
8778     while (head->busy) {
8779         VOL_CV_WAIT(&head->chain_busy_cv);
8780     }
8781 }
8782 #endif /* AFS_DEMAND_ATTACH_FS */
8783
8784
8785 /***************************************************/
8786 /* Volume by Partition List routines               */
8787 /***************************************************/
8788
8789 /*
8790  * demand attach fileserver adds a
8791  * linked list of volumes to each
8792  * partition object, thus allowing
8793  * for quick enumeration of all
8794  * volumes on a partition
8795  */
8796
8797 #ifdef AFS_DEMAND_ATTACH_FS
8798 /**
8799  * add a volume to its disk partition VByPList.
8800  *
8801  * @param[in] vp  pointer to volume object
8802  *
8803  * @pre either the disk partition VByPList is owned exclusively
8804  *      by the calling thread, or the list is quiescent and
8805  *      VOL_LOCK is held.
8806  *
8807  * @post volume is added to disk partition VByPList
8808  *
8809  * @note DAFS only
8810  *
8811  * @warning it is the caller's responsibility to ensure list
8812  *          quiescence.
8813  *
8814  * @see VVByPListWait_r
8815  * @see VVByPListBeginExclusive_r
8816  * @see VVByPListEndExclusive_r
8817  *
8818  * @internal volume package internal use only.
8819  */
8820 static void
8821 AddVolumeToVByPList_r(Volume * vp)
8822 {
8823     if (queue_IsNotOnQueue(&vp->vol_list)) {
8824         queue_Append(&vp->partition->vol_list, &vp->vol_list);
8825         V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
8826         vp->partition->vol_list.len++;
8827     }
8828 }
8829
8830 /**
8831  * delete a volume from its disk partition VByPList.
8832  *
8833  * @param[in] vp  pointer to volume object
8834  *
8835  * @pre either the disk partition VByPList is owned exclusively
8836  *      by the calling thread, or the list is quiescent and
8837  *      VOL_LOCK is held.
8838  *
8839  * @post volume is removed from the disk partition VByPList
8840  *
8841  * @note DAFS only
8842  *
8843  * @warning it is the caller's responsibility to ensure list
8844  *          quiescence.
8845  *
8846  * @see VVByPListWait_r
8847  * @see VVByPListBeginExclusive_r
8848  * @see VVByPListEndExclusive_r
8849  *
8850  * @internal volume package internal use only.
8851  */
8852 static void
8853 DeleteVolumeFromVByPList_r(Volume * vp)
8854 {
8855     if (queue_IsOnQueue(&vp->vol_list)) {
8856         queue_Remove(&vp->vol_list);
8857         V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
8858         vp->partition->vol_list.len--;
8859     }
8860 }
8861
8862 /**
8863  * begin an asynchronous exclusive operation on a VByPList.
8864  *
8865  * @param[in] dp   pointer to disk partition object
8866  *
8867  * @pre VOL_LOCK held.  VByPList is quiescent.
8868  *
8869  * @post VByPList marked busy.
8870  *
8871  * @note this interface is used in conjunction with VVByPListEndExclusive_r and
8872  *       VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8873  *       VByPList.
8874  *
8875  * @see VVByPListEndExclusive_r
8876  * @see VVByPListWait_r
8877  *
8878  * @note DAFS only
8879  *
8880  * @internal volume package internal use only.
8881  */
8882 /* take exclusive control over the list */
8883 static void
8884 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
8885 {
8886     opr_Assert(dp->vol_list.busy == 0);
8887     dp->vol_list.busy = 1;
8888 }
8889
8890 /**
8891  * relinquish exclusive ownership of a VByPList.
8892  *
8893  * @param[in] dp   pointer to disk partition object
8894  *
8895  * @pre VOL_LOCK held.  thread owns the VByPList exclusively.
8896  *
8897  * @post VByPList is marked quiescent.  threads awaiting use of
8898  *       the list are awakened.
8899  *
8900  * @see VVByPListBeginExclusive_r
8901  * @see VVByPListWait_r
8902  *
8903  * @note DAFS only
8904  *
8905  * @internal volume package internal use only.
8906  */
8907 static void
8908 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
8909 {
8910     opr_Assert(dp->vol_list.busy);
8911     dp->vol_list.busy = 0;
8912     opr_cv_broadcast(&dp->vol_list.cv);
8913 }
8914
8915 /**
8916  * wait for all asynchronous operations on a VByPList to complete.
8917  *
8918  * @param[in] dp  pointer to disk partition object
8919  *
8920  * @pre VOL_LOCK is held.
8921  *
8922  * @post disk partition's VByP list is quiescent
8923  *
8924  * @note DAFS only
8925  *
8926  * @note This interface should be called before any attempt to
8927  *       traverse the VByPList.  It is permissible for a thread
8928  *       to gain exclusive access to the list, and then perform
8929  *       latent operations on the list asynchronously wrt the
8930  *       VOL_LOCK.
8931  *
8932  * @warning if waiting is necessary, VOL_LOCK is dropped
8933  *
8934  * @see VVByPListEndExclusive_r
8935  * @see VVByPListBeginExclusive_r
8936  *
8937  * @internal volume package internal use only.
8938  */
8939 static void
8940 VVByPListWait_r(struct DiskPartition64 * dp)
8941 {
8942     while (dp->vol_list.busy) {
8943         VOL_CV_WAIT(&dp->vol_list.cv);
8944     }
8945 }
8946 #endif /* AFS_DEMAND_ATTACH_FS */
8947
8948 /***************************************************/
8949 /* Volume Cache Statistics routines                */
8950 /***************************************************/
8951
8952 void
8953 VPrintCacheStats_r(void)
8954 {
8955     struct VnodeClassInfo *vcp;
8956     vcp = &VnodeClassInfo[vLarge];
8957     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);
8958     vcp = &VnodeClassInfo[vSmall];
8959     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);
8960     Log("Volume header cache, %d entries, %"AFS_INT64_FMT" gets, "
8961         "%"AFS_INT64_FMT" replacements\n",
8962         VStats.hdr_cache_size, VStats.hdr_gets, VStats.hdr_loads);
8963 }
8964
8965 void
8966 VPrintCacheStats(void)
8967 {
8968     VOL_LOCK;
8969     VPrintCacheStats_r();
8970     VOL_UNLOCK;
8971 }
8972
8973 #ifdef AFS_DEMAND_ATTACH_FS
8974 static double
8975 UInt64ToDouble(afs_uint64 * x)
8976 {
8977     static double c32 = 4.0 * 1.073741824 * 1000000000.0;
8978     afs_uint32 h, l;
8979     SplitInt64(*x, h, l);
8980     return (((double)h) * c32) + ((double) l);
8981 }
8982
8983 static char *
8984 DoubleToPrintable(double x, char * buf, int len)
8985 {
8986     static double billion = 1000000000.0;
8987     afs_uint32 y[3];
8988
8989     y[0] = (afs_uint32) (x / (billion * billion));
8990     y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
8991     y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
8992
8993     if (y[0]) {
8994         snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
8995     } else if (y[1]) {
8996         snprintf(buf, len, "%d%09d", y[1], y[2]);
8997     } else {
8998         snprintf(buf, len, "%d", y[2]);
8999     }
9000     buf[len-1] = '\0';
9001     return buf;
9002 }
9003
9004 struct VLRUExtStatsEntry {
9005     VolumeId volid;
9006 };
9007
9008 struct VLRUExtStats {
9009     afs_uint32 len;
9010     afs_uint32 used;
9011     struct {
9012         afs_uint32 start;
9013         afs_uint32 len;
9014     } queue_info[VLRU_QUEUE_INVALID];
9015     struct VLRUExtStatsEntry * vec;
9016 };
9017
9018 /**
9019  * add a 256-entry fudge factor onto the vector in case state changes
9020  * out from under us.
9021  */
9022 #define VLRU_EXT_STATS_VEC_LEN_FUDGE   256
9023
9024 /**
9025  * collect extended statistics for the VLRU subsystem.
9026  *
9027  * @param[out] stats  pointer to stats structure to be populated
9028  * @param[in] nvols   number of volumes currently known to exist
9029  *
9030  * @pre VOL_LOCK held
9031  *
9032  * @post stats->vec allocated and populated
9033  *
9034  * @return operation status
9035  *    @retval 0 success
9036  *    @retval 1 failure
9037  */
9038 static int
9039 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
9040 {
9041     afs_uint32 cur, idx, len;
9042     struct rx_queue * qp, * nqp;
9043     Volume * vp;
9044     struct VLRUExtStatsEntry * vec;
9045
9046     len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
9047     vec = stats->vec = calloc(len,
9048                               sizeof(struct VLRUExtStatsEntry));
9049     if (vec == NULL) {
9050         return 1;
9051     }
9052
9053     cur = 0;
9054     for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
9055         VLRU_Wait_r(&volume_LRU.q[idx]);
9056         VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
9057         VOL_UNLOCK;
9058
9059         stats->queue_info[idx].start = cur;
9060
9061         for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
9062             if (cur == len) {
9063                 /* out of space in vec */
9064                 break;
9065             }
9066             vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
9067             vec[cur].volid = vp->hashid;
9068             cur++;
9069         }
9070
9071         stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
9072
9073         VOL_LOCK;
9074         VLRU_EndExclusive_r(&volume_LRU.q[idx]);
9075     }
9076
9077     stats->len = len;
9078     stats->used = cur;
9079     return 0;
9080 }
9081
9082 #define ENUMTOSTRING(en)  #en
9083 #define ENUMCASE(en) \
9084     case en: return ENUMTOSTRING(en)
9085
9086 static char *
9087 vlru_idx_to_string(int idx)
9088 {
9089     switch (idx) {
9090         ENUMCASE(VLRU_QUEUE_NEW);
9091         ENUMCASE(VLRU_QUEUE_MID);
9092         ENUMCASE(VLRU_QUEUE_OLD);
9093         ENUMCASE(VLRU_QUEUE_CANDIDATE);
9094         ENUMCASE(VLRU_QUEUE_HELD);
9095         ENUMCASE(VLRU_QUEUE_INVALID);
9096     default:
9097         return "**UNKNOWN**";
9098     }
9099 }
9100
9101 void
9102 VPrintExtendedCacheStats_r(int flags)
9103 {
9104     int i;
9105     afs_uint32 vol_sum = 0;
9106     struct stats {
9107         double min;
9108         double max;
9109         double sum;
9110         double avg;
9111     };
9112     struct stats looks, gets, reorders, len;
9113     struct stats ch_looks, ch_gets, ch_reorders;
9114     char pr_buf[4][32];
9115     VolumeHashChainHead *head;
9116     Volume *vp, *np;
9117     struct VLRUExtStats vlru_stats;
9118
9119     /* zero out stats */
9120     memset(&looks, 0, sizeof(struct stats));
9121     memset(&gets, 0, sizeof(struct stats));
9122     memset(&reorders, 0, sizeof(struct stats));
9123     memset(&len, 0, sizeof(struct stats));
9124     memset(&ch_looks, 0, sizeof(struct stats));
9125     memset(&ch_gets, 0, sizeof(struct stats));
9126     memset(&ch_reorders, 0, sizeof(struct stats));
9127
9128     for (i = 0; i < VolumeHashTable.Size; i++) {
9129         head = &VolumeHashTable.Table[i];
9130
9131         VHashWait_r(head);
9132         VHashBeginExclusive_r(head);
9133         VOL_UNLOCK;
9134
9135         ch_looks.sum    = UInt64ToDouble(&head->looks);
9136         ch_gets.sum     = UInt64ToDouble(&head->gets);
9137         ch_reorders.sum = UInt64ToDouble(&head->reorders);
9138
9139         /* update global statistics */
9140         {
9141             looks.sum    += ch_looks.sum;
9142             gets.sum     += ch_gets.sum;
9143             reorders.sum += ch_reorders.sum;
9144             len.sum      += (double)head->len;
9145             vol_sum      += head->len;
9146
9147             if (i == 0) {
9148                 len.min      = (double) head->len;
9149                 len.max      = (double) head->len;
9150                 looks.min    = ch_looks.sum;
9151                 looks.max    = ch_looks.sum;
9152                 gets.min     = ch_gets.sum;
9153                 gets.max     = ch_gets.sum;
9154                 reorders.min = ch_reorders.sum;
9155                 reorders.max = ch_reorders.sum;
9156             } else {
9157                 if (((double)head->len) < len.min)
9158                     len.min = (double) head->len;
9159                 if (((double)head->len) > len.max)
9160                     len.max = (double) head->len;
9161                 if (ch_looks.sum < looks.min)
9162                     looks.min = ch_looks.sum;
9163                 else if (ch_looks.sum > looks.max)
9164                     looks.max = ch_looks.sum;
9165                 if (ch_gets.sum < gets.min)
9166                     gets.min = ch_gets.sum;
9167                 else if (ch_gets.sum > gets.max)
9168                     gets.max = ch_gets.sum;
9169                 if (ch_reorders.sum < reorders.min)
9170                     reorders.min = ch_reorders.sum;
9171                 else if (ch_reorders.sum > reorders.max)
9172                     reorders.max = ch_reorders.sum;
9173             }
9174         }
9175
9176         if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
9177             /* compute detailed per-chain stats */
9178             struct stats hdr_loads, hdr_gets;
9179             double v_looks, v_loads, v_gets;
9180
9181             /* initialize stats with data from first element in chain */
9182             vp = queue_First(head, Volume);
9183             v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
9184             v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
9185             v_gets  = UInt64ToDouble(&vp->stats.hdr_gets);
9186             ch_gets.min = ch_gets.max = v_looks;
9187             hdr_loads.min = hdr_loads.max = v_loads;
9188             hdr_gets.min = hdr_gets.max = v_gets;
9189             hdr_loads.sum = hdr_gets.sum = 0;
9190
9191             vp = queue_Next(vp, Volume);
9192
9193             /* pull in stats from remaining elements in chain */
9194             for (queue_ScanFrom(head, vp, vp, np, Volume)) {
9195                 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
9196                 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
9197                 v_gets  = UInt64ToDouble(&vp->stats.hdr_gets);
9198
9199                 hdr_loads.sum += v_loads;
9200                 hdr_gets.sum += v_gets;
9201
9202                 if (v_looks < ch_gets.min)
9203                     ch_gets.min = v_looks;
9204                 else if (v_looks > ch_gets.max)
9205                     ch_gets.max = v_looks;
9206
9207                 if (v_loads < hdr_loads.min)
9208                     hdr_loads.min = v_loads;
9209                 else if (v_loads > hdr_loads.max)
9210                     hdr_loads.max = v_loads;
9211
9212                 if (v_gets < hdr_gets.min)
9213                     hdr_gets.min = v_gets;
9214                 else if (v_gets > hdr_gets.max)
9215                     hdr_gets.max = v_gets;
9216             }
9217
9218             /* compute per-chain averages */
9219             ch_gets.avg = ch_gets.sum / ((double)head->len);
9220             hdr_loads.avg = hdr_loads.sum / ((double)head->len);
9221             hdr_gets.avg = hdr_gets.sum / ((double)head->len);
9222
9223             /* dump per-chain stats */
9224             Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
9225                 i, head->len,
9226                 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9227                 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
9228             Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
9229                 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9230                 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9231                 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9232                 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9233             Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
9234                 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9235                 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9236                 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9237                 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9238             Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
9239                 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
9240                 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
9241                 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
9242                 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
9243         } else if (flags & VOL_STATS_PER_CHAIN) {
9244             /* dump simple per-chain stats */
9245             Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
9246                 i, head->len,
9247                 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9248                 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
9249                 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
9250         }
9251
9252         VOL_LOCK;
9253         VHashEndExclusive_r(head);
9254     }
9255
9256     VOL_UNLOCK;
9257
9258     /* compute global averages */
9259     len.avg      = len.sum      / ((double)VolumeHashTable.Size);
9260     looks.avg    = looks.sum    / ((double)VolumeHashTable.Size);
9261     gets.avg     = gets.sum     / ((double)VolumeHashTable.Size);
9262     reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
9263
9264     /* dump global stats */
9265     Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
9266     Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
9267         DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
9268         DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
9269         DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
9270         DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
9271     Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
9272         DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
9273         DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
9274         DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
9275         DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
9276     Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
9277         DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
9278         DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
9279         DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9280         DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9281     Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
9282         DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
9283         DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
9284         DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
9285         DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
9286
9287     /* print extended disk related statistics */
9288     {
9289         struct DiskPartition64 * diskP;
9290         afs_uint32 vol_count[VOLMAXPARTS+1];
9291         byte part_exists[VOLMAXPARTS+1];
9292         Device id;
9293         int i;
9294
9295         memset(vol_count, 0, sizeof(vol_count));
9296         memset(part_exists, 0, sizeof(part_exists));
9297
9298         VOL_LOCK;
9299
9300         for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
9301             id = diskP->index;
9302             vol_count[id] = diskP->vol_list.len;
9303             part_exists[id] = 1;
9304         }
9305
9306         VOL_UNLOCK;
9307         for (i = 0; i <= VOLMAXPARTS; i++) {
9308             if (part_exists[i]) {
9309                 /* XXX while this is currently safe, it is a violation
9310                  *     of the VGetPartitionById_r interface contract. */
9311                 diskP = VGetPartitionById_r(i, 0);
9312                 if (diskP) {
9313                     Log("Partition %s has %d online volumes\n",
9314                         VPartitionPath(diskP), diskP->vol_list.len);
9315                 }
9316             }
9317         }
9318         VOL_LOCK;
9319     }
9320
9321     /* print extended VLRU statistics */
9322     if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
9323         afs_uint32 idx, cur, lpos;
9324         VolumeId line[5];
9325
9326         VOL_UNLOCK;
9327
9328         Log("VLRU State Dump:\n\n");
9329
9330         for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
9331             Log("\t%s:\n", vlru_idx_to_string(idx));
9332
9333             lpos = 0;
9334             for (cur = vlru_stats.queue_info[idx].start;
9335                  cur < vlru_stats.queue_info[idx].len;
9336                  cur++) {
9337                 line[lpos++] = vlru_stats.vec[cur].volid;
9338                 if (lpos==5) {
9339                     Log("\t\t%u, %u, %u, %u, %u,\n",
9340                         line[0], line[1], line[2], line[3], line[4]);
9341                     lpos = 0;
9342                 }
9343             }
9344
9345             if (lpos) {
9346                 while (lpos < 5) {
9347                     line[lpos++] = 0;
9348                 }
9349                 Log("\t\t%u, %u, %u, %u, %u\n",
9350                     line[0], line[1], line[2], line[3], line[4]);
9351             }
9352             Log("\n");
9353         }
9354
9355         free(vlru_stats.vec);
9356
9357         VOL_LOCK;
9358     }
9359 }
9360
9361 void
9362 VPrintExtendedCacheStats(int flags)
9363 {
9364     VOL_LOCK;
9365     VPrintExtendedCacheStats_r(flags);
9366     VOL_UNLOCK;
9367 }
9368 #endif /* AFS_DEMAND_ATTACH_FS */
9369
9370 afs_int32
9371 VCanScheduleSalvage(void)
9372 {
9373     return vol_opts.canScheduleSalvage;
9374 }
9375
9376 afs_int32
9377 VCanUseFSSYNC(void)
9378 {
9379     return vol_opts.canUseFSSYNC;
9380 }
9381
9382 afs_int32
9383 VCanUseSALVSYNC(void)
9384 {
9385     return vol_opts.canUseSALVSYNC;
9386 }
9387
9388 afs_int32
9389 VCanUnsafeAttach(void)
9390 {
9391     return vol_opts.unsafe_attach;
9392 }