vol: detach offline volumes on dafs
[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                 /* the volume is offline and should be unattached */
3475                 *ec = VOFFLINE;
3476                 error_state = VOL_STATE_UNATTACHED;
3477                 FreeVolumeHeader(vp);
3478             } else {
3479                 Log("Volume %lu offline: needs salvage\n", afs_printable_uint32_lu(V_id(vp)));
3480                 *ec = VSALVAGE;
3481                 error_state = VOL_STATE_ERROR;
3482                 /* see if we can recover */
3483                 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3484             }
3485             vp->nUsers = 0;
3486             goto locked_error;
3487         }
3488 #endif /* AFS_DEMAND_ATTACH_FS */
3489     } else {
3490 #ifdef AFS_DEMAND_ATTACH_FS
3491         if ((mode != V_PEEK) && (mode != V_SECRETLY) && (mode != V_READONLY))
3492             V_inUse(vp) = programType;
3493 #endif /* AFS_DEMAND_ATTACH_FS */
3494         V_checkoutMode(vp) = mode;
3495     }
3496
3497     AddVolumeToHashTable(vp, vp->hashid);
3498 #ifdef AFS_DEMAND_ATTACH_FS
3499     if (VCanUnlockAttached() && (V_attachFlags(vp) & VOL_LOCKED)) {
3500         VUnlockVolume(vp);
3501     }
3502     if ((programType != fileServer) ||
3503         (V_inUse(vp) == fileServer)) {
3504         AddVolumeToVByPList_r(vp);
3505         VLRU_Add_r(vp);
3506         VChangeState_r(vp, VOL_STATE_ATTACHED);
3507     } else {
3508         VChangeState_r(vp, VOL_STATE_UNATTACHED);
3509     }
3510 #endif
3511
3512     return vp;
3513
3514 unlocked_error:
3515     VOL_LOCK;
3516 locked_error:
3517 #ifdef AFS_DEMAND_ATTACH_FS
3518     if (!VIsErrorState(V_attachState(vp))) {
3519         if (programType != fileServer && *ec == VNOVOL) {
3520             /* do not log anything in this case; it is common for
3521              * non-fileserver programs to fail here with VNOVOL, since that
3522              * is what happens when they simply try to use a volume, but that
3523              * volume doesn't exist. */
3524
3525         } else if (VIsErrorState(error_state)) {
3526             Log("attach2: forcing vol %" AFS_VOLID_FMT " to error state (state %u flags 0x%x ec %d)\n",
3527                 afs_printable_VolumeId_lu(vp->hashid), V_attachState(vp),
3528                 V_attachFlags(vp), *ec);
3529         }
3530         VChangeState_r(vp, error_state);
3531     }
3532 #endif /* AFS_DEMAND_ATTACH_FS */
3533
3534     if (read_header) {
3535         VReleaseVolumeHandles_r(vp);
3536     }
3537
3538 #ifdef AFS_DEMAND_ATTACH_FS
3539  error_notbroken:
3540     if (VCheckSalvage(vp) == VCHECK_SALVAGE_FAIL) {
3541         /* The salvage could not be scheduled with the salvage server
3542          * due to a hard error. Reset the error code to prevent retry loops by
3543          * callers. */
3544         if (*ec == VSALVAGING) {
3545             *ec = VSALVAGE;
3546         }
3547     }
3548     if (forcefree) {
3549         FreeVolume(vp);
3550     } else {
3551         VCheckFree(vp);
3552     }
3553 #else /* !AFS_DEMAND_ATTACH_FS */
3554     FreeVolume(vp);
3555 #endif /* !AFS_DEMAND_ATTACH_FS */
3556     return NULL;
3557 }
3558
3559 /* Attach an existing volume.
3560    The volume also normally goes online at this time.
3561    An offline volume must be reattached to make it go online.
3562  */
3563
3564 Volume *
3565 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
3566 {
3567     Volume *retVal;
3568     VOL_LOCK;
3569     retVal = VAttachVolume_r(ec, volumeId, mode);
3570     VOL_UNLOCK;
3571     return retVal;
3572 }
3573
3574 Volume *
3575 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
3576 {
3577     char *part, *name;
3578     VGetVolumePath(ec, volumeId, &part, &name);
3579     if (*ec) {
3580         Volume *vp;
3581         Error error;
3582         vp = VGetVolume_r(&error, volumeId);
3583         if (vp) {
3584             opr_Assert(V_inUse(vp) == 0);
3585             VDetachVolume_r(ec, vp);
3586         }
3587         return NULL;
3588     }
3589     return VAttachVolumeByName_r(ec, part, name, mode);
3590 }
3591
3592 /* Increment a reference count to a volume, sans context swaps.  Requires
3593  * possibly reading the volume header in from the disk, since there's
3594  * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
3595  *
3596  * N.B. This call can fail if we can't read in the header!!  In this case
3597  * we still guarantee we won't context swap, but the ref count won't be
3598  * incremented (otherwise we'd violate the invariant).
3599  */
3600 /* NOTE: with the demand attach fileserver extensions, the global lock
3601  * is dropped within VHold */
3602 #ifdef AFS_DEMAND_ATTACH_FS
3603 static int
3604 VHold_r(Volume * vp)
3605 {
3606     Error error;
3607
3608     VCreateReservation_r(vp);
3609     VWaitExclusiveState_r(vp);
3610
3611     LoadVolumeHeader(&error, vp);
3612     if (error) {
3613         VCancelReservation_r(vp);
3614         return error;
3615     }
3616     vp->nUsers++;
3617     VCancelReservation_r(vp);
3618     return 0;
3619 }
3620 #else /* AFS_DEMAND_ATTACH_FS */
3621 static int
3622 VHold_r(Volume * vp)
3623 {
3624     Error error;
3625
3626     LoadVolumeHeader(&error, vp);
3627     if (error)
3628         return error;
3629     vp->nUsers++;
3630     return 0;
3631 }
3632 #endif /* AFS_DEMAND_ATTACH_FS */
3633
3634 /**** volume timeout-related stuff ****/
3635
3636 #ifdef AFS_PTHREAD_ENV
3637
3638 static struct timespec *shutdown_timeout;
3639 static pthread_once_t shutdown_timeout_once = PTHREAD_ONCE_INIT;
3640
3641 static_inline int
3642 VTimedOut(const struct timespec *ts)
3643 {
3644     struct timeval tv;
3645     int code;
3646
3647     if (ts->tv_sec == 0) {
3648         /* short-circuit; this will have always timed out */
3649         return 1;
3650     }
3651
3652     code = gettimeofday(&tv, NULL);
3653     if (code) {
3654         Log("Error %d from gettimeofday, assuming we have not timed out\n", errno);
3655         /* assume no timeout; failure mode is we just wait longer than normal
3656          * instead of returning errors when we shouldn't */
3657         return 0;
3658     }
3659
3660     if (tv.tv_sec < ts->tv_sec ||
3661         (tv.tv_sec == ts->tv_sec && tv.tv_usec*1000 < ts->tv_nsec)) {
3662
3663         return 0;
3664     }
3665
3666     return 1;
3667 }
3668
3669 /**
3670  * Calculate an absolute timeout.
3671  *
3672  * @param[out] ts  A timeout that is "timeout" seconds from now, if we return
3673  *                 NULL, the memory is not touched
3674  * @param[in]  timeout  How long the timeout should be from now
3675  *
3676  * @return timeout to use
3677  *  @retval NULL      no timeout; wait forever
3678  *  @retval non-NULL  the given value for "ts"
3679  *
3680  * @internal
3681  */
3682 static struct timespec *
3683 VCalcTimeout(struct timespec *ts, afs_int32 timeout)
3684 {
3685     struct timeval now;
3686     int code;
3687
3688     if (timeout < 0) {
3689         return NULL;
3690     }
3691
3692     if (timeout == 0) {
3693         ts->tv_sec = ts->tv_nsec = 0;
3694         return ts;
3695     }
3696
3697     code = gettimeofday(&now, NULL);
3698     if (code) {
3699         Log("Error %d from gettimeofday, falling back to 'forever' timeout\n", errno);
3700         return NULL;
3701     }
3702
3703     ts->tv_sec = now.tv_sec + timeout;
3704     ts->tv_nsec = now.tv_usec * 1000;
3705
3706     return ts;
3707 }
3708
3709 /**
3710  * Initialize the shutdown_timeout global.
3711  */
3712 static void
3713 VShutdownTimeoutInit(void)
3714 {
3715     struct timespec *ts;
3716
3717     ts = malloc(sizeof(*ts));
3718
3719     shutdown_timeout = VCalcTimeout(ts, vol_opts.offline_shutdown_timeout);
3720
3721     if (!shutdown_timeout) {
3722         free(ts);
3723     }
3724 }
3725
3726 /**
3727  * Figure out the timeout that should be used for waiting for offline volumes.
3728  *
3729  * @param[out] ats  Storage space for a local timeout value if needed
3730  *
3731  * @return The timeout value that should be used
3732  *   @retval NULL      No timeout; wait forever for offlining volumes
3733  *   @retval non-NULL  A pointer to the absolute time that should be used as
3734  *                     the deadline for waiting for offlining volumes.
3735  *
3736  * @note If we return non-NULL, the pointer we return may or may not be the
3737  *       same as "ats"
3738  */
3739 static const struct timespec *
3740 VOfflineTimeout(struct timespec *ats)
3741 {
3742     if (vol_shutting_down) {
3743         opr_Verify(pthread_once(&shutdown_timeout_once,
3744                                 VShutdownTimeoutInit) == 0);
3745         return shutdown_timeout;
3746     } else {
3747         return VCalcTimeout(ats, vol_opts.offline_timeout);
3748     }
3749 }
3750
3751 #else /* AFS_PTHREAD_ENV */
3752
3753 /* Waiting a certain amount of time for offlining volumes is not supported
3754  * for LWP due to a lack of primitives. So, we never time out */
3755 # define VTimedOut(x) (0)
3756 # define VOfflineTimeout(x) (NULL)
3757
3758 #endif /* !AFS_PTHREAD_ENV */
3759
3760 #if 0
3761 static int
3762 VHold(Volume * vp)
3763 {
3764     int retVal;
3765     VOL_LOCK;
3766     retVal = VHold_r(vp);
3767     VOL_UNLOCK;
3768     return retVal;
3769 }
3770 #endif
3771
3772 static afs_int32
3773 VIsGoingOffline_r(struct Volume *vp)
3774 {
3775     afs_int32 code = 0;
3776
3777     if (vp->goingOffline) {
3778         if (vp->specialStatus) {
3779             code = vp->specialStatus;
3780         } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3781             code = VNOVOL;
3782         } else {
3783             code = VOFFLINE;
3784         }
3785     }
3786
3787     return code;
3788 }
3789
3790 /**
3791  * Tell the caller if a volume is waiting to go offline.
3792  *
3793  * @param[in] vp  The volume we want to know about
3794  *
3795  * @return volume status
3796  *   @retval 0 volume is not waiting to go offline, go ahead and use it
3797  *   @retval nonzero volume is waiting to offline, and give the returned code
3798  *           as an error to anyone accessing the volume
3799  *
3800  * @pre VOL_LOCK is NOT held
3801  * @pre caller holds a heavyweight reference on vp
3802  */
3803 afs_int32
3804 VIsGoingOffline(struct Volume *vp)
3805 {
3806     afs_int32 code;
3807
3808     VOL_LOCK;
3809     code = VIsGoingOffline_r(vp);
3810     VOL_UNLOCK;
3811
3812     return code;
3813 }
3814
3815 /**
3816  * Register an RX call with a volume.
3817  *
3818  * @param[inout] ec        Error code; if unset when passed in, may be set if
3819  *                         the volume starts going offline
3820  * @param[out]   client_ec @see GetVolume
3821  * @param[in] vp   Volume struct
3822  * @param[in] cbv  VCallByVol struct containing the RX call to register
3823  *
3824  * @pre VOL_LOCK held
3825  * @pre caller holds heavy ref on vp
3826  *
3827  * @internal
3828  */
3829 static void
3830 VRegisterCall_r(Error *ec, Error *client_ec, Volume *vp, struct VCallByVol *cbv)
3831 {
3832     if (vp && cbv) {
3833 #ifdef AFS_DEMAND_ATTACH_FS
3834         if (!*ec) {
3835             /* just in case the volume started going offline after we got the
3836              * reference to it... otherwise, if the volume started going
3837              * offline right at the end of GetVolume(), we might race with the
3838              * RX call scanner, and return success and add our cbv to the
3839              * rx_call_list _after_ the scanner has scanned the list. */
3840             *ec = VIsGoingOffline_r(vp);
3841             if (client_ec) {
3842                 *client_ec = *ec;
3843             }
3844         }
3845
3846         while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3847             VWaitStateChange_r(vp);
3848         }
3849 #endif /* AFS_DEMAND_ATTACH_FS */
3850
3851         queue_Prepend(&vp->rx_call_list, cbv);
3852     }
3853 }
3854
3855 /**
3856  * Deregister an RX call with a volume.
3857  *
3858  * @param[in] vp   Volume struct
3859  * @param[in] cbv  VCallByVol struct containing the RX call to deregister
3860  *
3861  * @pre VOL_LOCK held
3862  * @pre caller holds heavy ref on vp
3863  *
3864  * @internal
3865  */
3866 static void
3867 VDeregisterCall_r(Volume *vp, struct VCallByVol *cbv)
3868 {
3869     if (cbv && queue_IsOnQueue(cbv)) {
3870 #ifdef AFS_DEMAND_ATTACH_FS
3871         while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3872             VWaitStateChange_r(vp);
3873         }
3874 #endif /* AFS_DEMAND_ATTACH_FS */
3875
3876         queue_Remove(cbv);
3877     }
3878 }
3879
3880 /***************************************************/
3881 /* get and put volume routines                     */
3882 /***************************************************/
3883
3884 /**
3885  * put back a heavyweight reference to a volume object.
3886  *
3887  * @param[in] vp  volume object pointer
3888  *
3889  * @pre VOL_LOCK held
3890  *
3891  * @post heavyweight volume reference put back.
3892  *       depending on state, volume may have been taken offline,
3893  *       detached, salvaged, freed, etc.
3894  *
3895  * @internal volume package internal use only
3896  */
3897 void
3898 VPutVolume_r(Volume * vp)
3899 {
3900     opr_Verify(--vp->nUsers >= 0);
3901     if (vp->nUsers == 0) {
3902         VCheckOffline(vp);
3903         ReleaseVolumeHeader(vp->header);
3904 #ifdef AFS_DEMAND_ATTACH_FS
3905         if (!VCheckDetach(vp)) {
3906             VCheckSalvage(vp);
3907             VCheckFree(vp);
3908         }
3909 #else /* AFS_DEMAND_ATTACH_FS */
3910         VCheckDetach(vp);
3911 #endif /* AFS_DEMAND_ATTACH_FS */
3912     }
3913 }
3914
3915 void
3916 VPutVolume(Volume * vp)
3917 {
3918     VOL_LOCK;
3919     VPutVolume_r(vp);
3920     VOL_UNLOCK;
3921 }
3922
3923 /**
3924  * Puts a volume reference obtained with VGetVolumeWithCall.
3925  *
3926  * @param[in] vp  Volume struct
3927  * @param[in] cbv VCallByVol struct given to VGetVolumeWithCall, or NULL if none
3928  *
3929  * @pre VOL_LOCK is NOT held
3930  */
3931 void
3932 VPutVolumeWithCall(Volume *vp, struct VCallByVol *cbv)
3933 {
3934     VOL_LOCK;
3935     VDeregisterCall_r(vp, cbv);
3936     VPutVolume_r(vp);
3937     VOL_UNLOCK;
3938 }
3939
3940 /* Get a pointer to an attached volume.  The pointer is returned regardless
3941    of whether or not the volume is in service or on/off line.  An error
3942    code, however, is returned with an indication of the volume's status */
3943 Volume *
3944 VGetVolume(Error * ec, Error * client_ec, VolumeId volumeId)
3945 {
3946     Volume *retVal;
3947     VOL_LOCK;
3948     retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
3949     VOL_UNLOCK;
3950     return retVal;
3951 }
3952
3953 /**
3954  * Get a volume reference associated with an RX call.
3955  *
3956  * @param[out] ec @see GetVolume
3957  * @param[out] client_ec @see GetVolume
3958  * @param[in] volumeId @see GetVolume
3959  * @param[in] ts  How long to wait for going-offline volumes (absolute time).
3960  *                If NULL, wait forever. If ts->tv_sec == 0, return immediately
3961  *                with an error if the volume is going offline.
3962  * @param[in] cbv Contains an RX call to be associated with this volume
3963  *                reference. This call may be interrupted if the volume is
3964  *                requested to go offline while we hold a ref on it. Give NULL
3965  *                to not associate an RX call with this reference.
3966  *
3967  * @return @see GetVolume
3968  *
3969  * @note for LWP builds, ts must be NULL
3970  *
3971  * @note A reference obtained with this function MUST be put back with
3972  *       VPutVolumeWithCall
3973  */
3974 Volume *
3975 VGetVolumeWithCall(Error * ec, Error * client_ec, VolumeId volumeId,
3976                    const struct timespec *ts, struct VCallByVol *cbv)
3977 {
3978     Volume *retVal;
3979     VOL_LOCK;
3980     retVal = GetVolume(ec, client_ec, volumeId, NULL, ts);
3981     VRegisterCall_r(ec, client_ec, retVal, cbv);
3982     VOL_UNLOCK;
3983     return retVal;
3984 }
3985
3986 Volume *
3987 VGetVolume_r(Error * ec, VolumeId volumeId)
3988 {
3989     return GetVolume(ec, NULL, volumeId, NULL, NULL);
3990 }
3991
3992 /* try to get a volume we've previously looked up */
3993 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
3994 Volume *
3995 VGetVolumeByVp_r(Error * ec, Volume * vp)
3996 {
3997     return GetVolume(ec, NULL, vp->hashid, vp, NULL);
3998 }
3999
4000 /**
4001  * private interface for getting a volume handle
4002  *
4003  * @param[out] ec         error code (0 if no error)
4004  * @param[out] client_ec  wire error code to be given to clients
4005  * @param[in]  volumeId   ID of the volume we want
4006  * @param[in]  hint       optional hint for hash lookups, or NULL
4007  * @param[in]  timeout    absolute deadline for waiting for the volume to go
4008  *                        offline, if it is going offline. NULL to wait forever.
4009  *
4010  * @return a volume handle for the specified volume
4011  *  @retval NULL an error occurred, or the volume is in such a state that
4012  *               we cannot load a header or return any volume struct
4013  *
4014  * @note for DAFS, caller must NOT hold a ref count on 'hint'
4015  *
4016  * @note 'timeout' is only checked if the volume is actually going offline; so
4017  *       if you pass timeout->tv_sec = 0, this will exhibit typical
4018  *       nonblocking behavior.
4019  *
4020  * @note for LWP builds, 'timeout' must be NULL
4021  */
4022 static Volume *
4023 GetVolume(Error * ec, Error * client_ec, VolumeId volumeId, Volume * hint,
4024           const struct timespec *timeout)
4025 {
4026     Volume *vp = hint;
4027     /* pull this profiling/debugging code out of regular builds */
4028 #ifdef notdef
4029 #define VGET_CTR_INC(x) x++
4030     unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
4031         0, V7 = 0, V8 = 0, V9 = 0;
4032     unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
4033 #else
4034 #define VGET_CTR_INC(x)
4035 #endif
4036 #ifdef AFS_DEMAND_ATTACH_FS
4037     Volume *avp, * rvp = hint;
4038 #endif
4039
4040     /*
4041      * if VInit is zero, the volume package dynamic
4042      * data structures have not been initialized yet,
4043      * and we must immediately return an error
4044      */
4045     if (VInit == 0) {
4046         vp = NULL;
4047         *ec = VOFFLINE;
4048         if (client_ec) {
4049             *client_ec = VOFFLINE;
4050         }
4051         goto not_inited;
4052     }
4053
4054 #ifdef AFS_DEMAND_ATTACH_FS
4055     if (rvp) {
4056         VCreateReservation_r(rvp);
4057     }
4058 #endif /* AFS_DEMAND_ATTACH_FS */
4059
4060     for (;;) {
4061         *ec = 0;
4062         if (client_ec)
4063             *client_ec = 0;
4064         VGET_CTR_INC(V0);
4065
4066         vp = VLookupVolume_r(ec, volumeId, vp);
4067         if (*ec) {
4068             vp = NULL;
4069             break;
4070         }
4071
4072 #ifdef AFS_DEMAND_ATTACH_FS
4073         if (rvp && (rvp != vp)) {
4074             /* break reservation on old vp */
4075             VCancelReservation_r(rvp);
4076             rvp = NULL;
4077         }
4078 #endif /* AFS_DEMAND_ATTACH_FS */
4079
4080         if (!vp) {
4081             VGET_CTR_INC(V1);
4082             if (VInit < 2) {
4083                 VGET_CTR_INC(V2);
4084                 /* Until we have reached an initialization level of 2
4085                  * we don't know whether this volume exists or not.
4086                  * We can't sleep and retry later because before a volume
4087                  * is attached, the caller tries to get it first.  Just
4088                  * return VOFFLINE and the caller can choose whether to
4089                  * retry the command or not. */
4090                 *ec = VOFFLINE;
4091                 break;
4092             }
4093
4094             *ec = VNOVOL;
4095             break;
4096         }
4097
4098         VGET_CTR_INC(V3);
4099         IncUInt64(&VStats.hdr_gets);
4100
4101 #ifdef AFS_DEMAND_ATTACH_FS
4102         /* block if someone else is performing an exclusive op on this volume */
4103         if (rvp != vp) {
4104             rvp = vp;
4105             VCreateReservation_r(rvp);
4106         }
4107         VWaitExclusiveState_r(vp);
4108
4109         /* short circuit with VNOVOL in the following circumstances:
4110          *
4111          *   - VOL_STATE_ERROR
4112          *   - VOL_STATE_SHUTTING_DOWN
4113          */
4114         if ((V_attachState(vp) == VOL_STATE_ERROR) ||
4115             (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN)) {
4116             *ec = VNOVOL;
4117             vp = NULL;
4118             break;
4119         }
4120
4121         /*
4122          * short circuit with VOFFLINE for VOL_STATE_UNATTACHED/GOING_OFFLINE and
4123          *                    VNOVOL   for VOL_STATE_DELETED
4124          */
4125        if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
4126            (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) ||
4127            (V_attachState(vp) == VOL_STATE_DELETED)) {
4128            if (vp->specialStatus) {
4129                *ec = vp->specialStatus;
4130            } else if (V_attachState(vp) == VOL_STATE_DELETED) {
4131                *ec = VNOVOL;
4132            } else {
4133                *ec = VOFFLINE;
4134            }
4135            vp = NULL;
4136            break;
4137        }
4138
4139         /* allowable states:
4140          *   - PREATTACHED
4141          *   - ATTACHED
4142          *   - SALVAGING
4143          *   - SALVAGE_REQ
4144          */
4145
4146         if (vp->salvage.requested) {
4147             VUpdateSalvagePriority_r(vp);
4148         }
4149
4150         if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
4151             if (vp->specialStatus) {
4152                 *ec = vp->specialStatus;
4153                 vp = NULL;
4154                 break;
4155             }
4156             avp = VAttachVolumeByVp_r(ec, vp, 0);
4157             if (avp) {
4158                 if (vp != avp) {
4159                     /* VAttachVolumeByVp_r can return a pointer
4160                      * != the vp passed to it under certain
4161                      * conditions; make sure we don't leak
4162                      * reservations if that happens */
4163                     vp = avp;
4164                     VCancelReservation_r(rvp);
4165                     rvp = avp;
4166                     VCreateReservation_r(rvp);
4167                 }
4168                 VPutVolume_r(avp);
4169             }
4170             if (*ec) {
4171                 int endloop = 0;
4172                 switch (*ec) {
4173                 case VSALVAGING:
4174                     break;
4175                 case VOFFLINE:
4176                     endloop = 1;
4177                     if (vp->specialStatus) {
4178                         *ec = vp->specialStatus;
4179                     }
4180                     break;
4181
4182                 default:
4183                     if (vp->specialStatus) {
4184                         *ec = vp->specialStatus;
4185                     } else {
4186                         *ec = VNOVOL;
4187                     }
4188                     endloop = 1;
4189                 }
4190                 if (endloop) {
4191                     vp = NULL;
4192                     break;
4193                 }
4194             }
4195         }
4196
4197         if (VIsSalvaging(vp) || (*ec == VSALVAGING)) {
4198             if (client_ec) {
4199                 /* see CheckVnode() in afsfileprocs.c for an explanation
4200                  * of this error code logic */
4201                 afs_uint32 now = FT_ApproxTime();
4202                 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
4203                     *client_ec = VBUSY;
4204                 } else {
4205                     *client_ec = VRESTARTING;
4206                 }
4207             }
4208             *ec = VSALVAGING;
4209             vp = NULL;
4210             break;
4211         }
4212
4213         if (VIsErrorState(V_attachState(vp))) {
4214             /* make sure we don't take a vp in VOL_STATE_ERROR state and use
4215              * it, or transition it out of that state */
4216             if (!*ec) {
4217                 *ec = VNOVOL;
4218             }
4219             vp = NULL;
4220             break;
4221         }
4222
4223         /*
4224          * this test MUST happen after VAttachVolymeByVp, so we have no
4225          * conflicting vol op. (attach2 would have errored out if we had one;
4226          * specifically attach_check_vop must have detected a conflicting vop)
4227          */
4228          opr_Assert(!vp->pending_vol_op || vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningOnline);
4229
4230 #endif /* AFS_DEMAND_ATTACH_FS */
4231
4232         LoadVolumeHeader(ec, vp);
4233         if (*ec) {
4234             VGET_CTR_INC(V6);
4235             /* Only log the error if it was a totally unexpected error.  Simply
4236              * a missing inode is likely to be caused by the volume being deleted */
4237             if (errno != ENXIO || GetLogLevel() != 0)
4238                 Log("Volume %" AFS_VOLID_FMT ": couldn't reread volume header\n",
4239                     afs_printable_VolumeId_lu(vp->hashid));
4240 #ifdef AFS_DEMAND_ATTACH_FS
4241             if (VCanScheduleSalvage()) {
4242                 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0 /*flags*/);
4243             } else {
4244                 FreeVolume(vp);
4245                 vp = NULL;
4246             }
4247 #else /* AFS_DEMAND_ATTACH_FS */
4248             FreeVolume(vp);
4249             vp = NULL;
4250 #endif /* AFS_DEMAND_ATTACH_FS */
4251             break;
4252         }
4253
4254         VGET_CTR_INC(V7);
4255         if (vp->shuttingDown) {
4256             VGET_CTR_INC(V8);
4257             *ec = VNOVOL;
4258             vp = NULL;
4259             break;
4260         }
4261
4262         if (programType == fileServer) {
4263             VGET_CTR_INC(V9);
4264             if (vp->goingOffline) {
4265                 if (timeout && VTimedOut(timeout)) {
4266                     /* we've timed out; don't wait for the vol */
4267                 } else {
4268                     VGET_CTR_INC(V10);
4269 #ifdef AFS_DEMAND_ATTACH_FS
4270                     /* wait for the volume to go offline */
4271                     if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
4272                         VTimedWaitStateChange_r(vp, timeout, NULL);
4273                     }
4274 #elif defined(AFS_PTHREAD_ENV)
4275                     VOL_CV_TIMEDWAIT(&vol_put_volume_cond, timeout, NULL);
4276 #else /* AFS_PTHREAD_ENV */
4277                     /* LWP has no timed wait, so the caller better not be
4278                      * expecting one */
4279                     opr_Assert(!timeout);
4280                     LWP_WaitProcess(VPutVolume);
4281 #endif /* AFS_PTHREAD_ENV */
4282                     continue;
4283                 }
4284             }
4285             if (vp->specialStatus) {
4286                 VGET_CTR_INC(V11);
4287                 *ec = vp->specialStatus;
4288             } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
4289                 VGET_CTR_INC(V12);
4290                 *ec = VNOVOL;
4291             } else if (V_inUse(vp) == 0 || vp->goingOffline) {
4292                 VGET_CTR_INC(V13);
4293                 *ec = VOFFLINE;
4294             } else {
4295                 VGET_CTR_INC(V14);
4296             }
4297         }
4298         break;
4299     }
4300     VGET_CTR_INC(V15);
4301
4302 #ifdef AFS_DEMAND_ATTACH_FS
4303     /* if no error, bump nUsers */
4304     if (vp) {
4305         vp->nUsers++;
4306         VLRU_UpdateAccess_r(vp);
4307     }
4308     if (rvp) {
4309         VCancelReservation_r(rvp);
4310         rvp = NULL;
4311     }
4312     if (client_ec && !*client_ec) {
4313         *client_ec = *ec;
4314     }
4315 #else /* AFS_DEMAND_ATTACH_FS */
4316     /* if no error, bump nUsers */
4317     if (vp) {
4318         vp->nUsers++;
4319     }
4320     if (client_ec) {
4321         *client_ec = *ec;
4322     }
4323 #endif /* AFS_DEMAND_ATTACH_FS */
4324
4325  not_inited:
4326     opr_Assert(vp || *ec);
4327     return vp;
4328 }
4329
4330
4331 /***************************************************/
4332 /* Volume offline/detach routines                  */
4333 /***************************************************/
4334
4335 /* caller MUST hold a heavyweight ref on vp */
4336 #ifdef AFS_DEMAND_ATTACH_FS
4337 void
4338 VTakeOffline_r(Volume * vp)
4339 {
4340     Error error;
4341
4342     opr_Assert(vp->nUsers > 0);
4343     opr_Assert(programType == fileServer);
4344
4345     VCreateReservation_r(vp);
4346     VWaitExclusiveState_r(vp);
4347
4348     vp->goingOffline = 1;
4349     V_needsSalvaged(vp) = 1;
4350
4351     VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
4352     VCancelReservation_r(vp);
4353 }
4354 #else /* AFS_DEMAND_ATTACH_FS */
4355 void
4356 VTakeOffline_r(Volume * vp)
4357 {
4358     opr_Assert(vp->nUsers > 0);
4359     opr_Assert(programType == fileServer);
4360
4361     vp->goingOffline = 1;
4362     V_needsSalvaged(vp) = 1;
4363 }
4364 #endif /* AFS_DEMAND_ATTACH_FS */
4365
4366 void
4367 VTakeOffline(Volume * vp)
4368 {
4369     VOL_LOCK;
4370     VTakeOffline_r(vp);
4371     VOL_UNLOCK;
4372 }
4373
4374 /**
4375  * force a volume offline.
4376  *
4377  * @param[in] vp     volume object pointer
4378  * @param[in] flags  flags (see note below)
4379  *
4380  * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
4381  *       used when VUpdateVolume_r needs to call VForceOffline_r
4382  *       (which in turn would normally call VUpdateVolume_r)
4383  *
4384  * @see VUpdateVolume_r
4385  *
4386  * @pre VOL_LOCK must be held.
4387  *      for DAFS, caller must hold ref.
4388  *
4389  * @note for DAFS, it _is safe_ to call this function from an
4390  *       exclusive state
4391  *
4392  * @post needsSalvaged flag is set.
4393  *       for DAFS, salvage is requested.
4394  *       no further references to the volume through the volume
4395  *       package will be honored.
4396  *       all file descriptor and vnode caches are invalidated.
4397  *
4398  * @warning this is a heavy-handed interface.  it results in
4399  *          a volume going offline regardless of the current
4400  *          reference count state.
4401  *
4402  * @internal  volume package internal use only
4403  */
4404 void
4405 VForceOffline_r(Volume * vp, int flags)
4406 {
4407     Error error;
4408     if (!V_inUse(vp)) {
4409 #ifdef AFS_DEMAND_ATTACH_FS
4410         VChangeState_r(vp, VOL_STATE_ERROR);
4411 #endif
4412         return;
4413     }
4414
4415     strcpy(V_offlineMessage(vp),
4416            "Forced offline due to internal error: volume needs to be salvaged");
4417     Log("Volume %" AFS_VOLID_FMT " forced offline:  it needs salvaging!\n", afs_printable_VolumeId_lu(V_id(vp)));
4418
4419     V_inUse(vp) = 0;
4420     vp->goingOffline = 0;
4421     V_needsSalvaged(vp) = 1;
4422     if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
4423         VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
4424     }
4425
4426 #ifdef AFS_DEMAND_ATTACH_FS
4427     VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0 /*flags*/);
4428 #endif /* AFS_DEMAND_ATTACH_FS */
4429
4430 #ifdef AFS_PTHREAD_ENV
4431     opr_cv_broadcast(&vol_put_volume_cond);
4432 #else /* AFS_PTHREAD_ENV */
4433     LWP_NoYieldSignal(VPutVolume);
4434 #endif /* AFS_PTHREAD_ENV */
4435
4436     VReleaseVolumeHandles_r(vp);
4437 }
4438
4439 /**
4440  * force a volume offline.
4441  *
4442  * @param[in] vp  volume object pointer
4443  *
4444  * @see VForceOffline_r
4445  */
4446 void
4447 VForceOffline(Volume * vp)
4448 {
4449     VOL_LOCK;
4450     VForceOffline_r(vp, 0);
4451     VOL_UNLOCK;
4452 }
4453
4454 /**
4455  * Iterate over the RX calls associated with a volume, and interrupt them.
4456  *
4457  * @param[in] vp The volume whose RX calls we want to scan
4458  *
4459  * @pre VOL_LOCK held
4460  */
4461 static void
4462 VScanCalls_r(struct Volume *vp)
4463 {
4464     struct VCallByVol *cbv, *ncbv;
4465     afs_int32 err;
4466 #ifdef AFS_DEMAND_ATTACH_FS
4467     VolState state_save;
4468 #endif
4469
4470     if (queue_IsEmpty(&vp->rx_call_list))
4471         return; /* no calls to interrupt */
4472     if (!vol_opts.interrupt_rxcall)
4473         return; /* we have no function with which to interrupt calls */
4474     err = VIsGoingOffline_r(vp);
4475     if (!err)
4476         return; /* we're not going offline anymore */
4477
4478 #ifdef AFS_DEMAND_ATTACH_FS
4479     VWaitExclusiveState_r(vp);
4480     state_save = VChangeState_r(vp, VOL_STATE_SCANNING_RXCALLS);
4481     VOL_UNLOCK;
4482 #endif /* AFS_DEMAND_ATTACH_FS */
4483
4484     for(queue_Scan(&vp->rx_call_list, cbv, ncbv, VCallByVol)) {
4485         if (GetLogLevel() != 0) {
4486             struct rx_peer *peer;
4487             char hoststr[16];
4488             peer = rx_PeerOf(rx_ConnectionOf(cbv->call));
4489
4490             Log("Offlining volume %" AFS_VOLID_FMT " while client %s:%u is trying to read "
4491                 "from it; kicking client off with error %ld\n",
4492                 afs_printable_VolumeId_lu(vp->hashid),
4493                 afs_inet_ntoa_r(rx_HostOf(peer), hoststr),
4494                 (unsigned) ntohs(rx_PortOf(peer)),
4495                 (long) err);
4496         }
4497         (*vol_opts.interrupt_rxcall) (cbv->call, err);
4498     }
4499
4500 #ifdef AFS_DEMAND_ATTACH_FS
4501     VOL_LOCK;
4502     VChangeState_r(vp, state_save);
4503 #endif /* AFS_DEMAND_ATTACH_FS */
4504 }
4505
4506 #ifdef AFS_DEMAND_ATTACH_FS
4507 /**
4508  * Wait for a vp to go offline.
4509  *
4510  * @param[out] ec 1 if a salvage on the volume has been requested and
4511  *                salvok == 0, 0 otherwise
4512  * @param[in] vp  The volume to wait for
4513  * @param[in] salvok  If 0, we return immediately with *ec = 1 if the volume
4514  *                    has been requested to salvage. Otherwise we keep waiting
4515  *                    until the volume has gone offline.
4516  *
4517  * @pre VOL_LOCK held
4518  * @pre caller holds a lightweight ref on vp
4519  *
4520  * @note DAFS only
4521  */
4522 static void
4523 VWaitForOfflineByVp_r(Error *ec, struct Volume *vp, int salvok)
4524 {
4525     struct timespec timeout_ts;
4526     const struct timespec *ts;
4527     int timedout = 0;
4528
4529     ts = VOfflineTimeout(&timeout_ts);
4530
4531     *ec = 0;
4532
4533     while (!VIsOfflineState(V_attachState(vp)) && !timedout) {
4534         if (!salvok && vp->salvage.requested) {
4535             *ec = 1;
4536             return;
4537         }
4538         VTimedWaitStateChange_r(vp, ts, &timedout);
4539     }
4540     if (!timedout) {
4541         /* we didn't time out, so the volume must be offline, so we're done */
4542         return;
4543     }
4544
4545     /* If we got here, we timed out waiting for the volume to go offline.
4546      * Kick off the accessing RX calls and wait again */
4547
4548     VScanCalls_r(vp);
4549
4550     while (!VIsOfflineState(V_attachState(vp))) {
4551         if (!salvok && vp->salvage.requested) {
4552             *ec = 1;
4553             return;
4554         }
4555
4556         VWaitStateChange_r(vp);
4557     }
4558 }
4559
4560 #else /* AFS_DEMAND_ATTACH_FS */
4561
4562 /**
4563  * Wait for a volume to go offline.
4564  *
4565  * @pre VOL_LOCK held
4566  *
4567  * @note non-DAFS only (for DAFS, use @see WaitForOfflineByVp_r)
4568  */
4569 static void
4570 VWaitForOffline_r(Error *ec, VolumeId volid)
4571 {
4572     struct Volume *vp;
4573     const struct timespec *ts;
4574 #ifdef AFS_PTHREAD_ENV
4575     struct timespec timeout_ts;
4576 #endif
4577
4578     ts = VOfflineTimeout(&timeout_ts);
4579
4580     vp = GetVolume(ec, NULL, volid, NULL, ts);
4581     if (!vp) {
4582         /* error occurred so bad that we can't even get a vp; we have no
4583          * information on the vol so we don't know whether to wait, so just
4584          * return */
4585         return;
4586     }
4587     if (!VIsGoingOffline_r(vp)) {
4588         /* volume is no longer going offline, so we're done */
4589         VPutVolume_r(vp);
4590         return;
4591     }
4592
4593     /* If we got here, we timed out waiting for the volume to go offline.
4594      * Kick off the accessing RX calls and wait again */
4595
4596     VScanCalls_r(vp);
4597     VPutVolume_r(vp);
4598     vp = NULL;
4599
4600     vp = VGetVolume_r(ec, volid);
4601     if (vp) {
4602         /* In case it was reattached... */
4603         VPutVolume_r(vp);
4604     }
4605 }
4606 #endif /* !AFS_DEMAND_ATTACH_FS */
4607
4608 /* The opposite of VAttachVolume.  The volume header is written to disk, with
4609    the inUse bit turned off.  A copy of the header is maintained in memory,
4610    however (which is why this is VOffline, not VDetach).
4611  */
4612 void
4613 VOffline_r(Volume * vp, char *message)
4614 {
4615     Error error;
4616 #ifndef AFS_DEMAND_ATTACH_FS
4617     VolumeId vid = V_id(vp);
4618 #endif
4619
4620     opr_Assert(programType != volumeUtility && programType != volumeServer);
4621     if (!V_inUse(vp)) {
4622         VPutVolume_r(vp);
4623         return;
4624     }
4625     if (V_offlineMessage(vp)[0] == '\0')
4626         strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4627     V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4628
4629     vp->goingOffline = 1;
4630 #ifdef AFS_DEMAND_ATTACH_FS
4631     VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4632     VCreateReservation_r(vp);
4633     VPutVolume_r(vp);
4634     VWaitForOfflineByVp_r(&error, vp, 1);
4635     VCancelReservation_r(vp);
4636 #else /* AFS_DEMAND_ATTACH_FS */
4637     VPutVolume_r(vp);
4638     VWaitForOffline_r(&error, vid);
4639 #endif /* AFS_DEMAND_ATTACH_FS */
4640 }
4641
4642 #ifdef AFS_DEMAND_ATTACH_FS
4643 /**
4644  * Take a volume offline in order to perform a volume operation.
4645  *
4646  * @param[inout] ec       address in which to store error code
4647  * @param[in]    vp       volume object pointer
4648  * @param[in]    message  volume offline status message
4649  *
4650  * @pre
4651  *    - VOL_LOCK is held
4652  *    - caller MUST hold a heavyweight ref on vp
4653  *
4654  * @post
4655  *    - volume is taken offline
4656  *    - if possible, volume operation is promoted to running state
4657  *    - on failure, *ec is set to nonzero
4658  *
4659  * @note Although this function does not return any value, it may
4660  *       still fail to promote our pending volume operation to
4661  *       a running state.  Any caller MUST check the value of *ec,
4662  *       and MUST NOT blindly assume success.
4663  *
4664  * @warning if the caller does not hold a lightweight ref on vp,
4665  *          then it MUST NOT reference vp after this function
4666  *          returns to the caller.
4667  *
4668  * @internal volume package internal use only
4669  */
4670 void
4671 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
4672 {
4673     int salvok = 1;
4674     opr_Assert(vp->pending_vol_op);
4675     if (!V_inUse(vp)) {
4676         VPutVolume_r(vp);
4677         *ec = 1;
4678         return;
4679     }
4680     if (V_offlineMessage(vp)[0] == '\0')
4681         strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4682     V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4683
4684     vp->goingOffline = 1;
4685     VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4686     VCreateReservation_r(vp);
4687     VPutVolume_r(vp);
4688
4689     if (vp->pending_vol_op->com.programType != salvageServer) {
4690         /* do not give corrupted volumes to the volserver */
4691         salvok = 0;
4692     }
4693
4694     *ec = 0;
4695     VWaitForOfflineByVp_r(ec, vp, salvok);
4696
4697     VCancelReservation_r(vp);
4698 }
4699 #endif /* AFS_DEMAND_ATTACH_FS */
4700
4701 void
4702 VOffline(Volume * vp, char *message)
4703 {
4704     VOL_LOCK;
4705     VOffline_r(vp, message);
4706     VOL_UNLOCK;
4707 }
4708
4709 /* This gets used for the most part by utility routines that don't want
4710  * to keep all the volume headers around.  Generally, the file server won't
4711  * call this routine, because then the offline message in the volume header
4712  * (or other information) won't be available to clients. For NAMEI, also
4713  * close the file handles.  However, the fileserver does call this during
4714  * an attach following a volume operation.
4715  */
4716 void
4717 VDetachVolume_r(Error * ec, Volume * vp)
4718 {
4719 #ifdef FSSYNC_BUILD_CLIENT
4720     VolumeId volume;
4721     struct DiskPartition64 *tpartp;
4722     int notifyServer = 0;
4723     int  useDone = FSYNC_VOL_ON;
4724
4725     if (VCanUseFSSYNC()) {
4726         notifyServer = vp->needsPutBack;
4727         if (V_destroyMe(vp) == DESTROY_ME)
4728             useDone = FSYNC_VOL_LEAVE_OFF;
4729 # ifdef AFS_DEMAND_ATTACH_FS
4730         else if (!V_blessed(vp) || !V_inService(vp))
4731             useDone = FSYNC_VOL_LEAVE_OFF;
4732 # endif
4733     }
4734 # ifdef AFS_DEMAND_ATTACH_FS
4735     if (V_needsSalvaged(vp)) {
4736         notifyServer = 0;
4737         VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, 0);
4738     }
4739 # endif
4740     tpartp = vp->partition;
4741     volume = V_id(vp);
4742 #endif /* FSSYNC_BUILD_CLIENT */
4743
4744     *ec = 0;                    /* always "succeeds" */
4745     DeleteVolumeFromHashTable(vp);
4746     vp->shuttingDown = 1;
4747 #ifdef AFS_DEMAND_ATTACH_FS
4748     DeleteVolumeFromVByPList_r(vp);
4749     VLRU_Delete_r(vp);
4750     VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
4751 #else
4752     if (programType != fileServer)
4753         V_inUse(vp) = 0;
4754 #endif /* AFS_DEMAND_ATTACH_FS */
4755     VPutVolume_r(vp);
4756     /* Will be detached sometime in the future--this is OK since volume is offline */
4757
4758     /* XXX the following code should really be moved to VCheckDetach() since the volume
4759      * is not technically detached until the refcounts reach zero
4760      */
4761 #ifdef FSSYNC_BUILD_CLIENT
4762     if (VCanUseFSSYNC() && notifyServer) {
4763         if (notifyServer == VOL_PUTBACK_DELETE) {
4764             /* Only send FSYNC_VOL_DONE if the volume was actually deleted.
4765              * volserver code will set needsPutBack to VOL_PUTBACK_DELETE
4766              * to signify a deleted volume. */
4767             useDone = FSYNC_VOL_DONE;
4768         }
4769         /*
4770          * Note:  The server is not notified in the case of a bogus volume
4771          * explicitly to make it possible to create a volume, do a partial
4772          * restore, then abort the operation without ever putting the volume
4773          * online.  This is essential in the case of a volume move operation
4774          * between two partitions on the same server.  In that case, there
4775          * would be two instances of the same volume, one of them bogus,
4776          * which the file server would attempt to put on line
4777          */
4778         FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
4779         /* XXX this code path is only hit by volume utilities, thus
4780          * V_BreakVolumeCallbacks will always be NULL.  if we really
4781          * want to break callbacks in this path we need to use FSYNC_VolOp() */
4782 #ifdef notdef
4783         /* Dettaching it so break all callbacks on it */
4784         if (V_BreakVolumeCallbacks) {
4785             Log("volume %u detached; breaking all call backs\n", volume);
4786             (*V_BreakVolumeCallbacks) (volume);
4787         }
4788 #endif
4789     }
4790 #endif /* FSSYNC_BUILD_CLIENT */
4791 }
4792
4793 void
4794 VDetachVolume(Error * ec, Volume * vp)
4795 {
4796     VOL_LOCK;
4797     VDetachVolume_r(ec, vp);
4798     VOL_UNLOCK;
4799 }
4800
4801
4802 /***************************************************/
4803 /* Volume fd/inode handle closing routines         */
4804 /***************************************************/
4805
4806 /* For VDetachVolume, we close all cached file descriptors, but keep
4807  * the Inode handles in case we need to read from a busy volume.
4808  */
4809 /* for demand attach, caller MUST hold ref count on vp */
4810 static void
4811 VCloseVolumeHandles_r(Volume * vp)
4812 {
4813 #ifdef AFS_DEMAND_ATTACH_FS
4814     VolState state_save;
4815
4816     state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
4817
4818     VOL_UNLOCK;
4819 #endif
4820
4821     DFlushVolume(vp->hashid);
4822
4823 #ifdef AFS_DEMAND_ATTACH_FS
4824     VOL_LOCK;
4825 #endif
4826
4827     /* DAFS: VCloseVnodeFiles_r drops the glock internally */
4828     VCloseVnodeFiles_r(vp);
4829
4830 #ifdef AFS_DEMAND_ATTACH_FS
4831     VOL_UNLOCK;
4832 #endif
4833
4834     /* Too time consuming and unnecessary for the volserver */
4835     if (programType == fileServer) {
4836         IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4837         IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4838         IH_CONDSYNC(vp->diskDataHandle);
4839 #ifdef AFS_NAMEI_ENV
4840         IH_CONDSYNC(vp->linkHandle);
4841 #endif /* AFS_NAMEI_ENV */
4842     }
4843
4844     IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
4845     IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
4846     IH_REALLYCLOSE(vp->diskDataHandle);
4847     IH_REALLYCLOSE(vp->linkHandle);
4848
4849 #ifdef AFS_DEMAND_ATTACH_FS
4850     if ((V_attachFlags(vp) & VOL_LOCKED)) {
4851         VUnlockVolume(vp);
4852     }
4853
4854     VOL_LOCK;
4855     VChangeState_r(vp, state_save);
4856 #endif
4857 }
4858
4859 /* For both VForceOffline and VOffline, we close all relevant handles.
4860  * For VOffline, if we re-attach the volume, the files may possible be
4861  * different than before.
4862  */
4863 /* for demand attach, caller MUST hold a ref count on vp */
4864 static void
4865 VReleaseVolumeHandles_r(Volume * vp)
4866 {
4867 #ifdef AFS_DEMAND_ATTACH_FS
4868     VolState state_save;
4869
4870     state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
4871
4872     VOL_UNLOCK;
4873 #endif
4874
4875     DFlushVolume(vp->hashid);
4876
4877 #ifdef AFS_DEMAND_ATTACH_FS
4878     VOL_LOCK;
4879 #endif
4880
4881     VReleaseVnodeFiles_r(vp); /* DAFS: releases the glock internally */
4882
4883 #ifdef AFS_DEMAND_ATTACH_FS
4884     VOL_UNLOCK;
4885 #endif
4886
4887     /* Too time consuming and unnecessary for the volserver */
4888     if (programType == fileServer) {
4889         IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4890         IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4891         IH_CONDSYNC(vp->diskDataHandle);
4892 #ifdef AFS_NAMEI_ENV
4893         IH_CONDSYNC(vp->linkHandle);
4894 #endif /* AFS_NAMEI_ENV */
4895     }
4896
4897     IH_RELEASE(vp->vnodeIndex[vLarge].handle);
4898     IH_RELEASE(vp->vnodeIndex[vSmall].handle);
4899     IH_RELEASE(vp->diskDataHandle);
4900     IH_RELEASE(vp->linkHandle);
4901
4902 #ifdef AFS_DEMAND_ATTACH_FS
4903     if ((V_attachFlags(vp) & VOL_LOCKED)) {
4904         VUnlockVolume(vp);
4905     }
4906
4907     VOL_LOCK;
4908     VChangeState_r(vp, state_save);
4909 #endif
4910 }
4911
4912
4913 /***************************************************/
4914 /* Volume write and fsync routines                 */
4915 /***************************************************/
4916
4917 void
4918 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
4919 {
4920 #ifdef AFS_DEMAND_ATTACH_FS
4921     VolState state_save;
4922
4923     if (flags & VOL_UPDATE_WAIT) {
4924         VCreateReservation_r(vp);
4925         VWaitExclusiveState_r(vp);
4926     }
4927 #endif
4928
4929     *ec = 0;
4930     if (programType == fileServer) {
4931         if (!V_inUse(vp)) {
4932             V_uniquifier(vp) = V_nextVnodeUnique(vp);
4933         } else {
4934             V_uniquifier(vp) =
4935                 V_nextVnodeUnique(vp) + VOLUME_UPDATE_UNIQUIFIER_BUMP;
4936             if (V_uniquifier(vp) < V_nextVnodeUnique(vp)) {
4937                 /* uniquifier rolled over; reset the counters */
4938                 V_nextVnodeUnique(vp) = 2;      /* 1 is reserved for the root vnode */
4939                 V_uniquifier(vp) =
4940                     V_nextVnodeUnique(vp) + VOLUME_UPDATE_UNIQUIFIER_BUMP;
4941             }
4942         }
4943     }
4944
4945 #ifdef AFS_DEMAND_ATTACH_FS
4946     state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4947     VOL_UNLOCK;
4948 #endif
4949
4950     WriteVolumeHeader_r(ec, vp);
4951
4952 #ifdef AFS_DEMAND_ATTACH_FS
4953     VOL_LOCK;
4954     VChangeState_r(vp, state_save);
4955     if (flags & VOL_UPDATE_WAIT) {
4956         VCancelReservation_r(vp);
4957     }
4958 #endif
4959
4960     if (*ec) {
4961         Log("VUpdateVolume: error updating volume header, volume %" AFS_VOLID_FMT " (%s)\n",
4962             afs_printable_VolumeId_lu(V_id(vp)), V_name(vp));
4963         /* try to update on-disk header,
4964          * while preventing infinite recursion */
4965         if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
4966             VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
4967         }
4968     }
4969 }
4970
4971 void
4972 VUpdateVolume(Error * ec, Volume * vp)
4973 {
4974     VOL_LOCK;
4975     VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4976     VOL_UNLOCK;
4977 }
4978
4979 void
4980 VSyncVolume_r(Error * ec, Volume * vp, int flags)
4981 {
4982     FdHandle_t *fdP;
4983     int code;
4984 #ifdef AFS_DEMAND_ATTACH_FS
4985     VolState state_save;
4986 #endif
4987
4988     if (flags & VOL_SYNC_WAIT) {
4989         VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4990     } else {
4991         VUpdateVolume_r(ec, vp, 0);
4992     }
4993     if (!*ec) {
4994 #ifdef AFS_DEMAND_ATTACH_FS
4995         state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4996         VOL_UNLOCK;
4997 #endif
4998         fdP = IH_OPEN(V_diskDataHandle(vp));
4999         opr_Assert(fdP != NULL);
5000         code = FDH_SYNC(fdP);
5001         opr_Assert(code == 0);
5002         FDH_CLOSE(fdP);
5003 #ifdef AFS_DEMAND_ATTACH_FS
5004         VOL_LOCK;
5005         VChangeState_r(vp, state_save);
5006 #endif
5007     }
5008 }
5009
5010 void
5011 VSyncVolume(Error * ec, Volume * vp)
5012 {
5013     VOL_LOCK;
5014     VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
5015     VOL_UNLOCK;
5016 }
5017
5018
5019 /***************************************************/
5020 /* Volume dealloaction routines                    */
5021 /***************************************************/
5022
5023 #ifdef AFS_DEMAND_ATTACH_FS
5024 static void
5025 FreeVolume(Volume * vp)
5026 {
5027     /* free the heap space, iff it's safe.
5028      * otherwise, pull it out of the hash table, so it
5029      * will get deallocated when all refs to it go away */
5030     if (!VCheckFree(vp)) {
5031         DeleteVolumeFromHashTable(vp);
5032         DeleteVolumeFromVByPList_r(vp);
5033
5034         /* make sure we invalidate the header cache entry */
5035         FreeVolumeHeader(vp);
5036     }
5037 }
5038 #endif /* AFS_DEMAND_ATTACH_FS */
5039
5040 static void
5041 ReallyFreeVolume(Volume * vp)
5042 {
5043     int i;
5044     if (!vp)
5045         return;
5046 #ifdef AFS_DEMAND_ATTACH_FS
5047     /* debug */
5048     VChangeState_r(vp, VOL_STATE_FREED);
5049     if (vp->pending_vol_op)
5050         free(vp->pending_vol_op);
5051 #endif /* AFS_DEMAND_ATTACH_FS */
5052     for (i = 0; i < nVNODECLASSES; i++)
5053         if (vp->vnodeIndex[i].bitmap)
5054             free(vp->vnodeIndex[i].bitmap);
5055     FreeVolumeHeader(vp);
5056 #ifndef AFS_DEMAND_ATTACH_FS
5057     DeleteVolumeFromHashTable(vp);
5058 #endif /* AFS_DEMAND_ATTACH_FS */
5059     free(vp);
5060 }
5061
5062 /* check to see if we should shutdown this volume
5063  * returns 1 if volume was freed, 0 otherwise */
5064 #ifdef AFS_DEMAND_ATTACH_FS
5065 static int
5066 VCheckDetach(Volume * vp)
5067 {
5068     int ret = 0;
5069     Error ec = 0;
5070
5071     if (vp->nUsers || vp->nWaiters)
5072         return ret;
5073
5074     if (vp->shuttingDown) {
5075         ret = 1;
5076         if ((programType != fileServer) &&
5077             (V_inUse(vp) == programType) &&
5078             ((V_checkoutMode(vp) == V_VOLUPD) ||
5079              (V_checkoutMode(vp) == V_SECRETLY) ||
5080              ((V_checkoutMode(vp) == V_CLONE) &&
5081               (VolumeWriteable(vp))))) {
5082             V_inUse(vp) = 0;
5083             VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5084             if (ec) {
5085                 Log("VCheckDetach: volume header update for volume %" AFS_VOLID_FMT " "
5086                     "failed with errno %d\n", afs_printable_VolumeId_lu(vp->hashid), errno);
5087             }
5088         }
5089         VReleaseVolumeHandles_r(vp);
5090         VCheckSalvage(vp);
5091         ReallyFreeVolume(vp);
5092         if (programType == fileServer) {
5093             opr_cv_broadcast(&vol_put_volume_cond);
5094         }
5095     }
5096     return ret;
5097 }
5098 #else /* AFS_DEMAND_ATTACH_FS */
5099 static int
5100 VCheckDetach(Volume * vp)
5101 {
5102     int ret = 0;
5103     Error ec = 0;
5104
5105     if (vp->nUsers)
5106         return ret;
5107
5108     if (vp->shuttingDown) {
5109         ret = 1;
5110         if ((programType != fileServer) &&
5111             (V_inUse(vp) == programType) &&
5112             ((V_checkoutMode(vp) == V_VOLUPD) ||
5113              (V_checkoutMode(vp) == V_SECRETLY) ||
5114              ((V_checkoutMode(vp) == V_CLONE) &&
5115               (VolumeWriteable(vp))))) {
5116             V_inUse(vp) = 0;
5117             VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5118             if (ec) {
5119                 Log("VCheckDetach: volume header update for volume %" AFS_VOLID_FMT " failed with errno %d\n",
5120                     afs_printable_VolumeId_lu(vp->hashid), errno);
5121             }
5122         }
5123         VReleaseVolumeHandles_r(vp);
5124         ReallyFreeVolume(vp);
5125         if (programType == fileServer) {
5126 #if defined(AFS_PTHREAD_ENV)
5127             opr_cv_broadcast(&vol_put_volume_cond);
5128 #else /* AFS_PTHREAD_ENV */
5129             LWP_NoYieldSignal(VPutVolume);
5130 #endif /* AFS_PTHREAD_ENV */
5131         }
5132     }
5133     return ret;
5134 }
5135 #endif /* AFS_DEMAND_ATTACH_FS */
5136
5137 /* check to see if we should offline this volume
5138  * return 1 if volume went offline, 0 otherwise */
5139 #ifdef AFS_DEMAND_ATTACH_FS
5140 static int
5141 VCheckOffline(Volume * vp)
5142 {
5143     int ret = 0;
5144
5145     if (vp->goingOffline && !vp->nUsers) {
5146         Error error;
5147         opr_Assert(programType == fileServer);
5148         opr_Assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
5149                (V_attachState(vp) != VOL_STATE_FREED) &&
5150                (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
5151                (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
5152                (V_attachState(vp) != VOL_STATE_DELETED));
5153
5154         /* valid states:
5155          *
5156          * VOL_STATE_GOING_OFFLINE
5157          * VOL_STATE_SHUTTING_DOWN
5158          * VIsErrorState(V_attachState(vp))
5159          * VIsExclusiveState(V_attachState(vp))
5160          */
5161
5162         VCreateReservation_r(vp);
5163         VChangeState_r(vp, VOL_STATE_OFFLINING);
5164
5165         ret = 1;
5166         /* must clear the goingOffline flag before we drop the glock */
5167         vp->goingOffline = 0;
5168         V_inUse(vp) = 0;
5169
5170         VLRU_Delete_r(vp);
5171
5172         /* perform async operations */
5173         VUpdateVolume_r(&error, vp, 0);
5174         VCloseVolumeHandles_r(vp);
5175
5176         if (GetLogLevel() != 0) {
5177             if (V_offlineMessage(vp)[0]) {
5178                 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5179                     afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5180                     V_offlineMessage(vp));
5181             } else {
5182                 Log("VOffline: Volume %lu (%s) is now offline\n",
5183                     afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5184             }
5185         }
5186
5187         /* invalidate the volume header cache entry */
5188         FreeVolumeHeader(vp);
5189
5190         /* if nothing changed state to error or salvaging,
5191          * drop state to unattached */
5192         if (!VIsErrorState(V_attachState(vp))) {
5193             VChangeState_r(vp, VOL_STATE_UNATTACHED);
5194         }
5195         VCancelReservation_r(vp);
5196         /* no usage of vp is safe beyond this point */
5197     }
5198     return ret;
5199 }
5200 #else /* AFS_DEMAND_ATTACH_FS */
5201 static int
5202 VCheckOffline(Volume * vp)
5203 {
5204     int ret = 0;
5205
5206     if (vp->goingOffline && !vp->nUsers) {
5207         Error error;
5208         opr_Assert(programType == fileServer);
5209
5210         ret = 1;
5211         vp->goingOffline = 0;
5212         V_inUse(vp) = 0;
5213         VUpdateVolume_r(&error, vp, 0);
5214         VCloseVolumeHandles_r(vp);
5215         if (GetLogLevel() != 0) {
5216             if (V_offlineMessage(vp)[0]) {
5217                 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5218                     afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5219                     V_offlineMessage(vp));
5220             } else {
5221                 Log("VOffline: Volume %lu (%s) is now offline\n",
5222                     afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5223             }
5224         }
5225         FreeVolumeHeader(vp);
5226 #ifdef AFS_PTHREAD_ENV
5227         opr_cv_broadcast(&vol_put_volume_cond);
5228 #else /* AFS_PTHREAD_ENV */
5229         LWP_NoYieldSignal(VPutVolume);
5230 #endif /* AFS_PTHREAD_ENV */
5231     }
5232     return ret;
5233 }
5234 #endif /* AFS_DEMAND_ATTACH_FS */
5235
5236 /***************************************************/
5237 /* demand attach fs ref counting routines          */
5238 /***************************************************/
5239
5240 #ifdef AFS_DEMAND_ATTACH_FS
5241 /* the following two functions handle reference counting for
5242  * asynchronous operations on volume structs.
5243  *
5244  * their purpose is to prevent a VDetachVolume or VShutdown
5245  * from free()ing the Volume struct during an async i/o op */
5246
5247 /* register with the async volume op ref counter */
5248 /* VCreateReservation_r moved into inline code header because it
5249  * is now needed in vnode.c -- tkeiser 11/20/2007
5250  */
5251
5252 /**
5253  * decrement volume-package internal refcount.
5254  *
5255  * @param vp  volume object pointer
5256  *
5257  * @internal volume package internal use only
5258  *
5259  * @pre
5260  *    @arg VOL_LOCK is held
5261  *    @arg lightweight refcount held
5262  *
5263  * @post volume waiters refcount is decremented; volume may
5264  *       have been deallocated/shutdown/offlined/salvaged/
5265  *       whatever during the process
5266  *
5267  * @warning once you have tossed your last reference (you can acquire
5268  *          lightweight refs recursively) it is NOT SAFE to reference
5269  *          a volume object pointer ever again
5270  *
5271  * @see VCreateReservation_r
5272  *
5273  * @note DEMAND_ATTACH_FS only
5274  */
5275 void
5276 VCancelReservation_r(Volume * vp)
5277 {
5278     opr_Verify(--vp->nWaiters >= 0);
5279     if (vp->nWaiters == 0) {
5280         VCheckOffline(vp);
5281         if (!VCheckDetach(vp)) {
5282             VCheckSalvage(vp);
5283             VCheckFree(vp);
5284         }
5285     }
5286 }
5287
5288 /* check to see if we should free this volume now
5289  * return 1 if volume was freed, 0 otherwise */
5290 static int
5291 VCheckFree(Volume * vp)
5292 {
5293     int ret = 0;
5294     if ((vp->nUsers == 0) &&
5295         (vp->nWaiters == 0) &&
5296         !(V_attachFlags(vp) & (VOL_IN_HASH |
5297                                VOL_ON_VBYP_LIST |
5298                                VOL_IS_BUSY |
5299                                VOL_ON_VLRU))) {
5300         ReallyFreeVolume(vp);
5301         ret = 1;
5302     }
5303     return ret;
5304 }
5305 #endif /* AFS_DEMAND_ATTACH_FS */
5306
5307
5308 /***************************************************/
5309 /* online volume operations routines               */
5310 /***************************************************/
5311
5312 #ifdef AFS_DEMAND_ATTACH_FS
5313 /**
5314  * register a volume operation on a given volume.
5315  *
5316  * @param[in] vp       volume object
5317  * @param[in] vopinfo  volume operation info object
5318  *
5319  * @pre VOL_LOCK is held
5320  *
5321  * @post volume operation info object attached to volume object.
5322  *       volume operation statistics updated.
5323  *
5324  * @note by "attached" we mean a copy of the passed in object is made
5325  *
5326  * @internal volume package internal use only
5327  */
5328 int
5329 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5330 {
5331     FSSYNC_VolOp_info * info;
5332
5333     /* attach a vol op info node to the volume struct */
5334     info = malloc(sizeof(FSSYNC_VolOp_info));
5335     opr_Assert(info != NULL);
5336     memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
5337     vp->pending_vol_op = info;
5338
5339     /* update stats */
5340     vp->stats.last_vol_op = FT_ApproxTime();
5341     vp->stats.vol_ops++;
5342     IncUInt64(&VStats.vol_ops);
5343
5344     return 0;
5345 }
5346
5347 /**
5348  * deregister the volume operation attached to this volume.
5349  *
5350  * @param[in] vp  volume object pointer
5351  *
5352  * @pre VOL_LOCK is held
5353  *
5354  * @post the volume operation info object is detached from the volume object
5355  *
5356  * @internal volume package internal use only
5357  */
5358 int
5359 VDeregisterVolOp_r(Volume * vp)
5360 {
5361     if (vp->pending_vol_op) {
5362         free(vp->pending_vol_op);
5363         vp->pending_vol_op = NULL;
5364     }
5365     return 0;
5366 }
5367 #endif /* AFS_DEMAND_ATTACH_FS */
5368
5369 /**
5370  * determine whether it is safe to leave a volume online during
5371  * the volume operation described by the vopinfo object.
5372  *
5373  * @param[in] vp        volume object
5374  * @param[in] vopinfo   volume operation info object
5375  *
5376  * @return whether it is safe to leave volume online
5377  *    @retval 0  it is NOT SAFE to leave the volume online
5378  *    @retval 1  it is safe to leave the volume online during the operation
5379  *
5380  * @pre
5381  *    @arg VOL_LOCK is held
5382  *    @arg disk header attached to vp (heavyweight ref on vp will guarantee
5383  *         this condition is met)
5384  *
5385  * @internal volume package internal use only
5386  */
5387 int
5388 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5389 {
5390     return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
5391             (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5392             (vopinfo->com.reason == V_READONLY ||
5393              (!VolumeWriteable(vp) &&
5394               (vopinfo->com.reason == V_CLONE ||
5395                vopinfo->com.reason == V_DUMP)))));
5396 }
5397
5398 /**
5399  * same as VVolOpLeaveOnline_r, but does not require a volume with an attached
5400  * header.
5401  *
5402  * @param[in] vp        volume object
5403  * @param[in] vopinfo   volume operation info object
5404  *
5405  * @return whether it is safe to leave volume online
5406  *    @retval 0  it is NOT SAFE to leave the volume online
5407  *    @retval 1  it is safe to leave the volume online during the operation
5408  *    @retval -1 unsure; volume header is required in order to know whether or
5409  *               not is is safe to leave the volume online
5410  *
5411  * @pre VOL_LOCK is held
5412  *
5413  * @internal volume package internal use only
5414  */
5415 int
5416 VVolOpLeaveOnlineNoHeader_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5417 {
5418     /* follow the logic in VVolOpLeaveOnline_r; this is the same, except
5419      * assume that we don't know VolumeWriteable; return -1 if the answer
5420      * depends on VolumeWriteable */
5421
5422     if (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline) {
5423         return 1;
5424     }
5425     if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5426         vopinfo->com.reason == V_READONLY) {
5427
5428         return 1;
5429     }
5430     if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5431         (vopinfo->com.reason == V_CLONE ||
5432          vopinfo->com.reason == V_DUMP)) {
5433
5434         /* must know VolumeWriteable */
5435         return -1;
5436     }
5437     return 0;
5438 }
5439
5440 /**
5441  * determine whether VBUSY should be set during this volume operation.
5442  *
5443  * @param[in] vp        volume object
5444  * @param[in] vopinfo   volume operation info object
5445  *
5446  * @return whether VBUSY should be set
5447  *   @retval 0  VBUSY does NOT need to be set
5448  *   @retval 1  VBUSY SHOULD be set
5449  *
5450  * @pre VOL_LOCK is held
5451  *
5452  * @internal volume package internal use only
5453  */
5454 int
5455 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5456 {
5457     return ((vopinfo->com.command == FSYNC_VOL_OFF &&
5458             vopinfo->com.reason == FSYNC_SALVAGE) ||
5459             (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5460             (vopinfo->com.reason == V_CLONE ||
5461              vopinfo->com.reason == V_DUMP)));
5462 }
5463
5464
5465 /***************************************************/
5466 /* online salvager routines                        */
5467 /***************************************************/
5468 #if defined(AFS_DEMAND_ATTACH_FS)
5469
5470 /**
5471  * offline a volume to let it be salvaged.
5472  *
5473  * @param[in] vp  Volume to offline
5474  *
5475  * @return whether we offlined the volume successfully
5476  *  @retval 0 volume was not offlined
5477  *  @retval 1 volume is now offline
5478  *
5479  * @note This is similar to VCheckOffline, but slightly different. We do not
5480  *       deal with vp->goingOffline, and we try to avoid touching the volume
5481  *       header except just to set needsSalvaged
5482  *
5483  * @pre VOL_LOCK held
5484  * @pre vp->nUsers == 0
5485  * @pre V_attachState(vp) == VOL_STATE_SALVAGE_REQ
5486  */
5487 static int
5488 VOfflineForSalvage_r(struct Volume *vp)
5489 {
5490     Error error;
5491
5492     VCreateReservation_r(vp);
5493     VWaitExclusiveState_r(vp);
5494
5495     if (vp->nUsers || V_attachState(vp) == VOL_STATE_SALVAGING) {
5496         /* Someone's using the volume, or someone got to scheduling the salvage
5497          * before us. I don't think either of these should be possible, as we
5498          * should gain no new heavyweight references while we're trying to
5499          * salvage, but just to be sure... */
5500         VCancelReservation_r(vp);
5501         return 0;
5502     }
5503
5504     VChangeState_r(vp, VOL_STATE_OFFLINING);
5505
5506     VLRU_Delete_r(vp);
5507     if (vp->header) {
5508         V_needsSalvaged(vp) = 1;
5509         /* ignore error; updating needsSalvaged is just best effort */
5510         VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
5511     }
5512     VCloseVolumeHandles_r(vp);
5513
5514     FreeVolumeHeader(vp);
5515
5516     /* volume has been effectively offlined; we can mark it in the SALVAGING
5517      * state now, which lets FSSYNC give it away */
5518     VChangeState_r(vp, VOL_STATE_SALVAGING);
5519
5520     VCancelReservation_r(vp);
5521
5522     return 1;
5523 }
5524
5525 /**
5526  * check whether a salvage needs to be performed on this volume.
5527  *
5528  * @param[in] vp   pointer to volume object
5529  *
5530  * @return status code
5531  *    @retval VCHECK_SALVAGE_OK (0)         no pending salvage
5532  *    @retval VCHECK_SALVAGE_SCHEDULED (1)  salvage has been scheduled
5533  *    @retval VCHECK_SALVAGE_ASYNC (2)      salvage being scheduled
5534  *    @retval VCHECK_SALVAGE_DENIED (3)     salvage not scheduled; denied
5535  *    @retval VCHECK_SALVAGE_FAIL (4)       salvage not scheduled; failed
5536  *
5537  * @pre VOL_LOCK is held
5538  *
5539  * @post if salvage request flag is set and nUsers and nWaiters are zero,
5540  *       then a salvage will be requested
5541  *
5542  * @note this is one of the event handlers called by VCancelReservation_r
5543  *
5544  * @note the caller must check if the volume needs to be freed after calling
5545  *       this; the volume may not have any references or be on any lists after
5546  *       we return, and we do not free it
5547  *
5548  * @see VCancelReservation_r
5549  *
5550  * @internal volume package internal use only.
5551  */
5552 static int
5553 VCheckSalvage(Volume * vp)
5554 {
5555     int ret = VCHECK_SALVAGE_OK;
5556
5557 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5558     if (!vp->salvage.requested) {
5559         return VCHECK_SALVAGE_OK;
5560     }
5561     if (vp->nUsers) {
5562         return VCHECK_SALVAGE_ASYNC;
5563     }
5564
5565     /* prevent recursion; some of the code below creates and removes
5566      * lightweight refs, which can call VCheckSalvage */
5567     if (vp->salvage.scheduling) {
5568         return VCHECK_SALVAGE_ASYNC;
5569     }
5570     vp->salvage.scheduling = 1;
5571
5572     if (V_attachState(vp) == VOL_STATE_SALVAGE_REQ) {
5573         if (!VOfflineForSalvage_r(vp)) {
5574             vp->salvage.scheduling = 0;
5575             return VCHECK_SALVAGE_FAIL;
5576         }
5577     }
5578
5579     if (vp->salvage.requested) {
5580         ret = VScheduleSalvage_r(vp);
5581     }
5582     vp->salvage.scheduling = 0;
5583 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5584     return ret;
5585 }
5586
5587 /**
5588  * request volume salvage.
5589  *
5590  * @param[out] ec      computed client error code
5591  * @param[in]  vp      volume object pointer
5592  * @param[in]  reason  reason code (passed to salvageserver via SALVSYNC)
5593  * @param[in]  flags   see flags note below
5594  *
5595  * @note flags:
5596  *       VOL_SALVAGE_NO_OFFLINE do not need to wait to offline the volume; it has
5597  *                              not been fully attached
5598  *
5599  * @pre VOL_LOCK is held.
5600  *
5601  * @post volume state is changed.
5602  *       for fileserver, salvage will be requested once refcount reaches zero.
5603  *
5604  * @return operation status code
5605  *   @retval 0  volume salvage will occur
5606  *   @retval 1  volume salvage could not be scheduled
5607  *
5608  * @note DAFS only
5609  *
5610  * @note in the fileserver, this call does not synchronously schedule a volume
5611  *       salvage. rather, it sets volume state so that when volume refcounts
5612  *       reach zero, a volume salvage will occur. by "refcounts", we mean both
5613  *       nUsers and nWaiters must be zero.
5614  *
5615  * @internal volume package internal use only.
5616  */
5617 int
5618 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
5619 {
5620     int code = 0;
5621     /*
5622      * for DAFS volume utilities that are not supposed to schedule salvages,
5623      * just transition to error state instead
5624      */
5625     if (!VCanScheduleSalvage()) {
5626         VChangeState_r(vp, VOL_STATE_ERROR);
5627         *ec = VSALVAGE;
5628         return 1;
5629     }
5630
5631     if (programType != fileServer && !VCanUseFSSYNC()) {
5632         VChangeState_r(vp, VOL_STATE_ERROR);
5633         *ec = VSALVAGE;
5634         return 1;
5635     }
5636
5637     if (!vp->salvage.requested) {
5638         vp->salvage.requested = 1;
5639         vp->salvage.reason = reason;
5640         vp->stats.last_salvage = FT_ApproxTime();
5641
5642         /* Note that it is not possible for us to reach this point if a
5643          * salvage is already running on this volume (even if the fileserver
5644          * was restarted during the salvage). If a salvage were running, the
5645          * salvager would have write-locked the volume header file, so when
5646          * we tried to lock the volume header, the lock would have failed,
5647          * and we would have failed during attachment prior to calling
5648          * VRequestSalvage. So we know that we can schedule salvages without
5649          * fear of a salvage already running for this volume. */
5650
5651         if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
5652
5653             /* if we don't need to offline the volume, we can go directly
5654              * to SALVAGING. SALVAGING says the volume is offline and is
5655              * either salvaging or ready to be handed to the salvager.
5656              * SALVAGE_REQ says that we want to salvage the volume, but we
5657              * are waiting for it to go offline first. */
5658             if (flags & VOL_SALVAGE_NO_OFFLINE) {
5659                 VChangeState_r(vp, VOL_STATE_SALVAGING);
5660             } else {
5661                 VChangeState_r(vp, VOL_STATE_SALVAGE_REQ);
5662                 if (vp->nUsers == 0) {
5663                     /* normally VOfflineForSalvage_r would be called from
5664                      * PutVolume et al when nUsers reaches 0, but if
5665                      * it's already 0, just do it ourselves, since PutVolume
5666                      * isn't going to get called */
5667                     VOfflineForSalvage_r(vp);
5668                 }
5669             }
5670             /* If we are non-fileserver, we're telling the fileserver to
5671              * salvage the vol, so we don't need to give it back separately. */
5672             vp->needsPutBack = 0;
5673
5674             *ec = VSALVAGING;
5675         } else {
5676             Log("VRequestSalvage: volume %" AFS_VOLID_FMT " online salvaged too many times; forced offline.\n", afs_printable_VolumeId_lu(vp->hashid));
5677
5678             /* make sure neither VScheduleSalvage_r nor
5679              * VUpdateSalvagePriority_r try to schedule another salvage */
5680             vp->salvage.requested = vp->salvage.scheduled = 0;
5681
5682             VChangeState_r(vp, VOL_STATE_ERROR);
5683             *ec = VSALVAGE;
5684             code = 1;
5685         }
5686         if ((flags & VOL_SALVAGE_NO_OFFLINE)) {
5687             /* Here, we free the header for the volume, but make sure to only
5688              * do this if VOL_SALVAGE_NO_OFFLINE is specified. The reason for
5689              * this requires a bit of explanation.
5690              *
5691              * Normally, the volume header will be freed when the volume goes
5692              * goes offline. However, if VOL_SALVAGE_NO_OFFLINE has been
5693              * specified, the volume was in the process of being attached when
5694              * we discovered that it needed salvaging. Thus, the volume will
5695              * never go offline, since it never went fully online in the first
5696              * place. Specifically, we do not call VOfflineForSalvage_r above,
5697              * and we never get rid of the volume via VPutVolume_r; the volume
5698              * has not been initialized enough for those to work.
5699              *
5700              * So instead, explicitly free the volume header here. If we do not
5701              * do this, we are wasting a header that some other volume could be
5702              * using, since the header remains attached to the volume. Also if
5703              * we do not free the header here, we end up with a volume where
5704              * nUsers == 0, but the volume has a header that is not on the
5705              * header LRU. Some code expects that all nUsers == 0 volumes have
5706              * their header on the header LRU (or have no header).
5707              *
5708              * Also note that we must not free the volume header here if
5709              * VOL_SALVAGE_NO_OFFLINE is not set. Since, if
5710              * VOL_SALVAGE_NO_OFFLINE is not set, someone else may have a
5711              * reference to this volume, and they assume they can use the
5712              * volume's header. If we free the volume out from under them, they
5713              * can easily segfault.
5714              */
5715             FreeVolumeHeader(vp);
5716         }
5717     }
5718     return code;
5719 }
5720
5721 /**
5722  * update salvageserver scheduling priority for a volume.
5723  *
5724  * @param[in] vp  pointer to volume object
5725  *
5726  * @return operation status
5727  *   @retval 0  success
5728  *   @retval 1  request denied, or SALVSYNC communications failure
5729  *
5730  * @pre VOL_LOCK is held.
5731  *
5732  * @post in-core salvage priority counter is incremented.  if at least
5733  *       SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
5734  *       last SALVSYNC_RAISEPRIO request, we contact the salvageserver
5735  *       to update its priority queue.  if no salvage is scheduled,
5736  *       this function is a no-op.
5737  *
5738  * @note DAFS fileserver only
5739  *
5740  * @note this should be called whenever a VGetVolume fails due to a
5741  *       pending salvage request
5742  *
5743  * @todo should set exclusive state and drop glock around salvsync call
5744  *
5745  * @internal volume package internal use only.
5746  */
5747 int
5748 VUpdateSalvagePriority_r(Volume * vp)
5749 {
5750     int ret=0;
5751
5752 #ifdef SALVSYNC_BUILD_CLIENT
5753     afs_uint32 now;
5754     int code;
5755
5756     vp->salvage.prio++;
5757     now = FT_ApproxTime();
5758
5759     /* update the salvageserver priority queue occasionally so that
5760      * frequently requested volumes get moved to the head of the queue
5761      */
5762     if ((vp->salvage.scheduled) &&
5763         (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
5764         code = SALVSYNC_SalvageVolume(vp->hashid,
5765                                       VPartitionPath(vp->partition),
5766                                       SALVSYNC_RAISEPRIO,
5767                                       vp->salvage.reason,
5768                                       vp->salvage.prio,
5769                                       NULL);
5770         vp->stats.last_salvage_req = now;
5771         if (code != SYNC_OK) {
5772             ret = 1;
5773         }
5774     }
5775 #endif /* SALVSYNC_BUILD_CLIENT */
5776     return ret;
5777 }
5778
5779
5780 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5781
5782 /* A couple of little helper functions. These return true if we tried to
5783  * use this mechanism to schedule a salvage, false if we haven't tried.
5784  * If we did try a salvage then the results are contained in code.
5785  */
5786
5787 static_inline int
5788 try_SALVSYNC(Volume *vp, char *partName, int *code) {
5789 #ifdef SALVSYNC_BUILD_CLIENT
5790     if (VCanUseSALVSYNC()) {
5791         Log("Scheduling salvage for volume %" AFS_VOLID_FMT " on part %s over SALVSYNC\n",
5792             afs_printable_VolumeId_lu(vp->hashid), partName);
5793
5794         /* can't use V_id() since there's no guarantee
5795          * we have the disk data header at this point */
5796         *code = SALVSYNC_SalvageVolume(vp->hashid,
5797                                        partName,
5798                                        SALVSYNC_SALVAGE,
5799                                        vp->salvage.reason,
5800                                        vp->salvage.prio,
5801                                        NULL);
5802         return 1;
5803     }
5804 #endif
5805     return 0;
5806 }
5807
5808 static_inline int
5809 try_FSSYNC(Volume *vp, char *partName, int *code) {
5810 #ifdef FSSYNC_BUILD_CLIENT
5811     if (VCanUseFSSYNC()) {
5812         Log("Scheduling salvage for volume %" AFS_VOLID_FMT " on part %s over FSSYNC\n",
5813             afs_printable_VolumeId_lu(vp->hashid), partName);
5814
5815         /*
5816          * If we aren't the fileserver, tell the fileserver the volume
5817          * needs to be salvaged. We could directly tell the
5818          * salvageserver, but the fileserver keeps track of some stats
5819          * related to salvages, and handles some other salvage-related
5820          * complications for us.
5821          */
5822         *code = FSYNC_VolOp(vp->hashid, partName,
5823                             FSYNC_VOL_FORCE_ERROR, FSYNC_SALVAGE, NULL);
5824         return 1;
5825     }
5826 #endif /* FSSYNC_BUILD_CLIENT */
5827     return 0;
5828 }
5829
5830 /**
5831  * schedule a salvage with the salvage server or fileserver.
5832  *
5833  * @param[in] vp  pointer to volume object
5834  *
5835  * @return operation status
5836  *    @retval VCHECK_SALVAGE_OK (0)         no pending salvage
5837  *    @retval VCHECK_SALVAGE_SCHEDULED (1)  salvage has been scheduled
5838  *    @retval VCHECK_SALVAGE_ASYNC (2)      salvage being scheduled
5839  *    @retval VCHECK_SALVAGE_DENIED (3)     salvage not scheduled; denied
5840  *    @retval VCHECK_SALVAGE_FAIL (4)       salvage not scheduled; failed
5841  *
5842  * @pre
5843  *    @arg VOL_LOCK is held.
5844  *    @arg nUsers and nWaiters should be zero.
5845  *
5846  * @post salvageserver or fileserver is sent a salvage request
5847  *
5848  * @note If we are the fileserver, the request will be sent to the salvage
5849  * server over SALVSYNC. If we are not the fileserver, the request will be
5850  * sent to the fileserver over FSSYNC (FSYNC_VOL_FORCE_ERROR/FSYNC_SALVAGE).
5851  *
5852  * @note the caller must check if the volume needs to be freed after calling
5853  *       this; the volume may not have any references or be on any lists after
5854  *       we return, and we do not free it
5855  *
5856  * @note DAFS only
5857  *
5858  * @internal volume package internal use only.
5859  */
5860 static int
5861 VScheduleSalvage_r(Volume * vp)
5862 {
5863     int ret = VCHECK_SALVAGE_SCHEDULED;
5864     int code = 0;
5865     VolState state_save;
5866     VThreadOptions_t * thread_opts;
5867     char partName[16];
5868
5869     opr_Verify(VCanUseSALVSYNC() || VCanUseFSSYNC());
5870
5871     if (vp->nWaiters || vp->nUsers) {
5872         return VCHECK_SALVAGE_ASYNC;
5873     }
5874
5875     /* prevent endless salvage,attach,salvage,attach,... loops */
5876     if (vp->stats.salvages >= SALVAGE_COUNT_MAX) {
5877         return VCHECK_SALVAGE_FAIL;
5878     }
5879
5880     /*
5881      * don't perform salvsync ops on certain threads
5882      */
5883     thread_opts = pthread_getspecific(VThread_key);
5884     if (thread_opts == NULL) {
5885         thread_opts = &VThread_defaults;
5886     }
5887     if (thread_opts->disallow_salvsync || vol_disallow_salvsync) {
5888         return VCHECK_SALVAGE_ASYNC;
5889     }
5890
5891     if (vp->salvage.scheduled) {
5892         return VCHECK_SALVAGE_SCHEDULED;
5893     }
5894
5895     VCreateReservation_r(vp);
5896     VWaitExclusiveState_r(vp);
5897
5898     /*
5899      * XXX the scheduling process should really be done asynchronously
5900      *     to avoid fssync deadlocks
5901      */
5902     if (vp->salvage.scheduled) {
5903         ret = VCHECK_SALVAGE_SCHEDULED;
5904     } else {
5905         /* if we haven't previously scheduled a salvage, do so now
5906          *
5907          * set the volume to an exclusive state and drop the lock
5908          * around the SALVSYNC call
5909          */
5910         strlcpy(partName, vp->partition->name, sizeof(partName));
5911         state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
5912         VOL_UNLOCK;
5913
5914         opr_Verify(try_SALVSYNC(vp, partName, &code)
5915                    || try_FSSYNC(vp, partName, &code));
5916
5917         VOL_LOCK;
5918         VChangeState_r(vp, state_save);
5919
5920         if (code == SYNC_OK) {
5921             ret = VCHECK_SALVAGE_SCHEDULED;
5922             vp->salvage.scheduled = 1;
5923             vp->stats.last_salvage_req = FT_ApproxTime();
5924             if (VCanUseSALVSYNC()) {
5925                 /* don't record these stats for non-fileservers; let the
5926                  * fileserver take care of these */
5927                 vp->stats.salvages++;
5928                 IncUInt64(&VStats.salvages);
5929             }
5930         } else {
5931             switch(code) {
5932             case SYNC_BAD_COMMAND:
5933             case SYNC_COM_ERROR:
5934                 ret = VCHECK_SALVAGE_FAIL;
5935                 break;
5936             case SYNC_DENIED:
5937                 ret = VCHECK_SALVAGE_DENIED;
5938                 Log("VScheduleSalvage_r: Salvage request for volume %" AFS_VOLID_FMT " "
5939                     "denied\n", afs_printable_VolumeId_lu(vp->hashid));
5940                 break;
5941             case SYNC_FAILED:
5942                 ret = VCHECK_SALVAGE_FAIL;
5943                 Log("VScheduleSalvage_r: Salvage request for volume %" AFS_VOLID_FMT " "
5944                     "failed\n", afs_printable_VolumeId_lu(vp->hashid));
5945                 break;
5946             default:
5947                 ret = VCHECK_SALVAGE_FAIL;
5948                 Log("VScheduleSalvage_r: Salvage request for volume %" AFS_VOLID_FMT " "
5949                     "received unknown protocol error %d\n",
5950                     afs_printable_VolumeId_lu(vp->hashid), code);
5951                 break;
5952             }
5953
5954             if (VCanUseFSSYNC()) {
5955                 VChangeState_r(vp, VOL_STATE_ERROR);
5956             }
5957         }
5958     }
5959
5960     /* NB: this is cancelling the reservation we obtained above, but we do
5961      * not call VCancelReservation_r, since that may trigger the vp dtor,
5962      * possibly free'ing the vp. We need to keep the vp around after
5963      * this, as the caller may reference vp without any refs. Instead, it
5964      * is the duty of the caller to inspect 'vp' after we return to see if
5965      * needs to be freed. */
5966     opr_Verify(--vp->nWaiters >= 0);
5967     return ret;
5968 }
5969 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5970
5971 #ifdef SALVSYNC_BUILD_CLIENT
5972
5973 /**
5974  * connect to the salvageserver SYNC service.
5975  *
5976  * @return operation status
5977  *    @retval 0 failure
5978  *    @retval 1 success
5979  *
5980  * @post connection to salvageserver SYNC service established
5981  *
5982  * @see VConnectSALV_r
5983  * @see VDisconnectSALV
5984  * @see VReconnectSALV
5985  */
5986 int
5987 VConnectSALV(void)
5988 {
5989     int retVal;
5990     VOL_LOCK;
5991     retVal = VConnectSALV_r();
5992     VOL_UNLOCK;
5993     return retVal;
5994 }
5995
5996 /**
5997  * connect to the salvageserver SYNC service.
5998  *
5999  * @return operation status
6000  *    @retval 0 failure
6001  *    @retval 1 success
6002  *
6003  * @pre VOL_LOCK is held.
6004  *
6005  * @post connection to salvageserver SYNC service established
6006  *
6007  * @see VConnectSALV
6008  * @see VDisconnectSALV_r
6009  * @see VReconnectSALV_r
6010  * @see SALVSYNC_clientInit
6011  *
6012  * @internal volume package internal use only.
6013  */
6014 int
6015 VConnectSALV_r(void)
6016 {
6017     return SALVSYNC_clientInit();
6018 }
6019
6020 /**
6021  * disconnect from the salvageserver SYNC service.
6022  *
6023  * @return operation status
6024  *    @retval 0 success
6025  *
6026  * @pre client should have a live connection to the salvageserver
6027  *
6028  * @post connection to salvageserver SYNC service destroyed
6029  *
6030  * @see VDisconnectSALV_r
6031  * @see VConnectSALV
6032  * @see VReconnectSALV
6033  */
6034 int
6035 VDisconnectSALV(void)
6036 {
6037     VOL_LOCK;
6038     VDisconnectSALV_r();
6039     VOL_UNLOCK;
6040     return 0;
6041 }
6042
6043 /**
6044  * disconnect from the salvageserver SYNC service.
6045  *
6046  * @return operation status
6047  *    @retval 0 success
6048  *
6049  * @pre
6050  *    @arg VOL_LOCK is held.
6051  *    @arg client should have a live connection to the salvageserver.
6052  *
6053  * @post connection to salvageserver SYNC service destroyed
6054  *
6055  * @see VDisconnectSALV
6056  * @see VConnectSALV_r
6057  * @see VReconnectSALV_r
6058  * @see SALVSYNC_clientFinis
6059  *
6060  * @internal volume package internal use only.
6061  */
6062 int
6063 VDisconnectSALV_r(void)
6064 {
6065     return SALVSYNC_clientFinis();
6066 }
6067
6068 /**
6069  * disconnect and then re-connect to the salvageserver SYNC service.
6070  *
6071  * @return operation status
6072  *    @retval 0 failure
6073  *    @retval 1 success
6074  *
6075  * @pre client should have a live connection to the salvageserver
6076  *
6077  * @post old connection is dropped, and a new one is established
6078  *
6079  * @see VConnectSALV
6080  * @see VDisconnectSALV
6081  * @see VReconnectSALV_r
6082  */
6083 int
6084 VReconnectSALV(void)
6085 {
6086     int retVal;
6087     VOL_LOCK;
6088     retVal = VReconnectSALV_r();
6089     VOL_UNLOCK;
6090     return retVal;
6091 }
6092
6093 /**
6094  * disconnect and then re-connect to the salvageserver SYNC service.
6095  *
6096  * @return operation status
6097  *    @retval 0 failure
6098  *    @retval 1 success
6099  *
6100  * @pre
6101  *    @arg VOL_LOCK is held.
6102  *    @arg client should have a live connection to the salvageserver.
6103  *
6104  * @post old connection is dropped, and a new one is established
6105  *
6106  * @see VConnectSALV_r
6107  * @see VDisconnectSALV
6108  * @see VReconnectSALV
6109  * @see SALVSYNC_clientReconnect
6110  *
6111  * @internal volume package internal use only.
6112  */
6113 int
6114 VReconnectSALV_r(void)
6115 {
6116     return SALVSYNC_clientReconnect();
6117 }
6118 #endif /* SALVSYNC_BUILD_CLIENT */
6119 #endif /* AFS_DEMAND_ATTACH_FS */
6120
6121
6122 /***************************************************/
6123 /* FSSYNC routines                                 */
6124 /***************************************************/
6125
6126 /* This must be called by any volume utility which needs to run while the
6127    file server is also running.  This is separated from VInitVolumePackage2 so
6128    that a utility can fork--and each of the children can independently
6129    initialize communication with the file server */
6130 #ifdef FSSYNC_BUILD_CLIENT
6131 /**
6132  * connect to the fileserver SYNC service.
6133  *
6134  * @return operation status
6135  *    @retval 0 failure
6136  *    @retval 1 success
6137  *
6138  * @pre
6139  *    @arg VInit must equal 2.
6140  *    @arg Program Type must not be fileserver or salvager.
6141  *
6142  * @post connection to fileserver SYNC service established
6143  *
6144  * @see VConnectFS_r
6145  * @see VDisconnectFS
6146  * @see VChildProcReconnectFS
6147  */
6148 int
6149 VConnectFS(void)
6150 {
6151     int retVal;
6152     VOL_LOCK;
6153     retVal = VConnectFS_r();
6154     VOL_UNLOCK;
6155     return retVal;
6156 }
6157
6158 /**
6159  * connect to the fileserver SYNC service.
6160  *
6161  * @return operation status
6162  *    @retval 0 failure
6163  *    @retval 1 success
6164  *
6165  * @pre
6166  *    @arg VInit must equal 2.
6167  *    @arg Program Type must not be fileserver or salvager.
6168  *    @arg VOL_LOCK is held.
6169  *
6170  * @post connection to fileserver SYNC service established
6171  *
6172  * @see VConnectFS
6173  * @see VDisconnectFS_r
6174  * @see VChildProcReconnectFS_r
6175  *
6176  * @internal volume package internal use only.
6177  */
6178 int
6179 VConnectFS_r(void)
6180 {
6181     int rc;
6182     opr_Assert((VInit == 2) &&
6183            (programType != fileServer) &&
6184            (programType != salvager));
6185     rc = FSYNC_clientInit();
6186     if (rc) {
6187         VSetVInit_r(3);
6188     }
6189     return rc;
6190 }
6191
6192 /**
6193  * disconnect from the fileserver SYNC service.
6194  *
6195  * @pre
6196  *    @arg client should have a live connection to the fileserver.
6197  *    @arg VOL_LOCK is held.
6198  *    @arg Program Type must not be fileserver or salvager.
6199  *
6200  * @post connection to fileserver SYNC service destroyed
6201  *
6202  * @see VDisconnectFS
6203  * @see VConnectFS_r
6204  * @see VChildProcReconnectFS_r
6205  *
6206  * @internal volume package internal use only.
6207  */
6208 void
6209 VDisconnectFS_r(void)
6210 {
6211     opr_Assert((programType != fileServer) &&
6212            (programType != salvager));
6213     FSYNC_clientFinis();
6214     VSetVInit_r(2);
6215 }
6216
6217 /**
6218  * disconnect from the fileserver SYNC service.
6219  *
6220  * @pre
6221  *    @arg client should have a live connection to the fileserver.
6222  *    @arg Program Type must not be fileserver or salvager.
6223  *
6224  * @post connection to fileserver SYNC service destroyed
6225  *
6226  * @see VDisconnectFS_r
6227  * @see VConnectFS
6228  * @see VChildProcReconnectFS
6229  */
6230 void
6231 VDisconnectFS(void)
6232 {
6233     VOL_LOCK;
6234     VDisconnectFS_r();
6235     VOL_UNLOCK;
6236 }
6237
6238 /**
6239  * connect to the fileserver SYNC service from a child process following a fork.
6240  *
6241  * @return operation status
6242  *    @retval 0 failure
6243  *    @retval 1 success
6244  *
6245  * @pre
6246  *    @arg VOL_LOCK is held.
6247  *    @arg current FSYNC handle is shared with a parent process
6248  *
6249  * @post current FSYNC handle is discarded and a new connection to the
6250  *       fileserver SYNC service is established
6251  *
6252  * @see VChildProcReconnectFS
6253  * @see VConnectFS_r
6254  * @see VDisconnectFS_r
6255  *
6256  * @internal volume package internal use only.
6257  */
6258 int
6259 VChildProcReconnectFS_r(void)
6260 {
6261     return FSYNC_clientChildProcReconnect();
6262 }
6263
6264 /**
6265  * connect to the fileserver SYNC service from a child process following a fork.
6266  *
6267  * @return operation status
6268  *    @retval 0 failure
6269  *    @retval 1 success
6270  *
6271  * @pre current FSYNC handle is shared with a parent process
6272  *
6273  * @post current FSYNC handle is discarded and a new connection to the
6274  *       fileserver SYNC service is established
6275  *
6276  * @see VChildProcReconnectFS_r
6277  * @see VConnectFS
6278  * @see VDisconnectFS
6279  */
6280 int
6281 VChildProcReconnectFS(void)
6282 {
6283     int ret;
6284     VOL_LOCK;
6285     ret = VChildProcReconnectFS_r();
6286     VOL_UNLOCK;
6287     return ret;
6288 }
6289 #endif /* FSSYNC_BUILD_CLIENT */
6290
6291
6292 /***************************************************/
6293 /* volume bitmap routines                          */
6294 /***************************************************/
6295
6296 /*
6297  * Grow the bitmap by the defined increment
6298  */
6299 void
6300 VGrowBitmap(struct vnodeIndex *index)
6301 {
6302     byte *bp;
6303
6304     bp = realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
6305     osi_Assert(bp != NULL);
6306     index->bitmap = bp;
6307     bp += index->bitmapSize;
6308     memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
6309     index->bitmapOffset = index->bitmapSize;
6310     index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
6311
6312     return;
6313 }
6314
6315 /**
6316  * allocate a vnode bitmap number for the vnode
6317  *
6318  * @param[out] ec  error code
6319  * @param[in] vp   volume object pointer
6320  * @param[in] index vnode index number for the vnode
6321  * @param[in] flags flag values described in note
6322  *
6323  * @note for DAFS, flags parameter controls locking behavior.
6324  * If (flags & VOL_ALLOC_BITMAP_WAIT) is set, then this function
6325  * will create a reservation and block on any other exclusive
6326  * operations.  Otherwise, this function assumes the caller
6327  * already has exclusive access to vp, and we just change the
6328  * volume state.
6329  *
6330  * @pre VOL_LOCK held
6331  *
6332  * @return bit number allocated
6333  */
6334 /*
6335
6336  */
6337 int
6338 VAllocBitmapEntry_r(Error * ec, Volume * vp,
6339                     struct vnodeIndex *index, int flags)
6340 {
6341     int ret = 0;
6342     byte *bp, *ep;
6343 #ifdef AFS_DEMAND_ATTACH_FS
6344     VolState state_save;
6345 #endif /* AFS_DEMAND_ATTACH_FS */
6346
6347     *ec = 0;
6348
6349     /* This test is probably redundant */
6350     if (!VolumeWriteable(vp)) {
6351         *ec = (bit32) VREADONLY;
6352         return ret;
6353     }
6354
6355 #ifdef AFS_DEMAND_ATTACH_FS
6356     if (flags & VOL_ALLOC_BITMAP_WAIT) {
6357         VCreateReservation_r(vp);
6358         VWaitExclusiveState_r(vp);
6359     }
6360     state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6361 #endif /* AFS_DEMAND_ATTACH_FS */
6362
6363 #ifdef BITMAP_LATER
6364     if ((programType == fileServer) && !index->bitmap) {
6365         int i;
6366 #ifndef AFS_DEMAND_ATTACH_FS
6367         /* demand attach fs uses the volume state to avoid races.
6368          * specialStatus field is not used at all */
6369         int wasVBUSY = 0;
6370         if (vp->specialStatus == VBUSY) {
6371             if (vp->goingOffline) {     /* vos dump waiting for the volume to
6372                                          * go offline. We probably come here
6373                                          * from AddNewReadableResidency */
6374                 wasVBUSY = 1;
6375             } else {
6376                 while (vp->specialStatus == VBUSY) {
6377 #ifdef AFS_PTHREAD_ENV
6378                     VOL_UNLOCK;
6379                     sleep(2);
6380                     VOL_LOCK;
6381 #else /* !AFS_PTHREAD_ENV */
6382                     IOMGR_Sleep(2);
6383 #endif /* !AFS_PTHREAD_ENV */
6384                 }
6385             }
6386         }
6387 #endif /* !AFS_DEMAND_ATTACH_FS */
6388
6389         if (!index->bitmap) {
6390 #ifndef AFS_DEMAND_ATTACH_FS
6391             vp->specialStatus = VBUSY;  /* Stop anyone else from using it. */
6392 #endif /* AFS_DEMAND_ATTACH_FS */
6393             for (i = 0; i < nVNODECLASSES; i++) {
6394                 VGetBitmap_r(ec, vp, i);
6395                 if (*ec) {
6396 #ifdef AFS_DEMAND_ATTACH_FS
6397                     VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0 /*flags*/);
6398 #else /* AFS_DEMAND_ATTACH_FS */
6399                     DeleteVolumeFromHashTable(vp);
6400                     vp->shuttingDown = 1;       /* Let who has it free it. */
6401                     vp->specialStatus = 0;
6402 #endif /* AFS_DEMAND_ATTACH_FS */
6403                     goto done;
6404                 }
6405             }
6406 #ifndef AFS_DEMAND_ATTACH_FS
6407             if (!wasVBUSY)
6408                 vp->specialStatus = 0;  /* Allow others to have access. */
6409 #endif /* AFS_DEMAND_ATTACH_FS */
6410         }
6411     }
6412 #endif /* BITMAP_LATER */
6413
6414 #ifdef AFS_DEMAND_ATTACH_FS
6415     VOL_UNLOCK;
6416 #endif /* AFS_DEMAND_ATTACH_FS */
6417     bp = index->bitmap + index->bitmapOffset;
6418     ep = index->bitmap + index->bitmapSize;
6419     while (bp < ep) {
6420         if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
6421             int o;
6422             index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
6423             while (*bp == 0xff)
6424                 bp++;
6425             o = opr_ffs(~*bp) - 1;
6426             *bp |= (1 << o);
6427             ret = ((bp - index->bitmap) * 8 + o);
6428 #ifdef AFS_DEMAND_ATTACH_FS
6429             VOL_LOCK;
6430 #endif /* AFS_DEMAND_ATTACH_FS */
6431             goto done;
6432         }
6433         bp += sizeof(bit32) /* i.e. 4 */ ;
6434     }
6435     /* No bit map entry--must grow bitmap */
6436     VGrowBitmap(index);
6437     bp = index->bitmap + index->bitmapOffset;
6438     *bp = 1;
6439     ret = index->bitmapOffset * 8;
6440 #ifdef AFS_DEMAND_ATTACH_FS
6441     VOL_LOCK;
6442 #endif /* AFS_DEMAND_ATTACH_FS */
6443
6444  done:
6445 #ifdef AFS_DEMAND_ATTACH_FS
6446     VChangeState_r(vp, state_save);
6447     if (flags & VOL_ALLOC_BITMAP_WAIT) {
6448         VCancelReservation_r(vp);
6449     }
6450 #endif /* AFS_DEMAND_ATTACH_FS */
6451     return ret;
6452 }
6453
6454 int
6455 VAllocBitmapEntry(Error * ec, Volume * vp, struct vnodeIndex * index)
6456 {
6457     int retVal;
6458     VOL_LOCK;
6459     retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
6460     VOL_UNLOCK;
6461     return retVal;
6462 }
6463
6464 void
6465 VFreeBitMapEntry_r(Error * ec, Volume *vp, struct vnodeIndex *index,
6466                    unsigned bitNumber, int flags)
6467 {
6468     unsigned int offset;
6469
6470     *ec = 0;
6471
6472 #ifdef AFS_DEMAND_ATTACH_FS
6473     if (flags & VOL_FREE_BITMAP_WAIT) {
6474         /* VAllocBitmapEntry_r allocs bitmap entries under an exclusive volume
6475          * state, so ensure we're not in an exclusive volume state when we update
6476          * the bitmap */
6477         VCreateReservation_r(vp);
6478         VWaitExclusiveState_r(vp);
6479     }
6480 #endif
6481
6482 #ifdef BITMAP_LATER
6483     if (!index->bitmap)
6484         goto done;
6485 #endif /* BITMAP_LATER */
6486
6487     offset = bitNumber >> 3;
6488     if (offset >= index->bitmapSize) {
6489         *ec = VNOVNODE;
6490         goto done;
6491     }
6492     if (offset < index->bitmapOffset)
6493         index->bitmapOffset = offset & ~3;      /* Truncate to nearest bit32 */
6494     *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
6495
6496  done:
6497 #ifdef AFS_DEMAND_ATTACH_FS
6498     if (flags & VOL_FREE_BITMAP_WAIT) {
6499         VCancelReservation_r(vp);
6500     }
6501 #endif
6502     return; /* make the compiler happy for non-DAFS */
6503 }
6504
6505 void
6506 VFreeBitMapEntry(Error * ec, Volume *vp, struct vnodeIndex *index,
6507                  unsigned bitNumber)
6508 {
6509     VOL_LOCK;
6510     VFreeBitMapEntry_r(ec, vp, index, bitNumber, VOL_FREE_BITMAP_WAIT);
6511     VOL_UNLOCK;
6512 }
6513
6514 /* this function will drop the glock internally.
6515  * for old pthread fileservers, this is safe thanks to vbusy.
6516  *
6517  * for demand attach fs, caller must have already called
6518  * VCreateReservation_r and VWaitExclusiveState_r */
6519 static void
6520 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
6521 {
6522     StreamHandle_t *file;
6523     afs_sfsize_t nVnodes, size;
6524     struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
6525     struct vnodeIndex *vip = &vp->vnodeIndex[class];
6526     struct VnodeDiskObject *vnode;
6527     unsigned int unique = 0;
6528     FdHandle_t *fdP;
6529 #ifdef BITMAP_LATER
6530     byte *BitMap = 0;
6531 #endif /* BITMAP_LATER */
6532 #ifdef AFS_DEMAND_ATTACH_FS
6533     VolState state_save;
6534 #endif /* AFS_DEMAND_ATTACH_FS */
6535
6536     *ec = 0;
6537
6538 #ifdef AFS_DEMAND_ATTACH_FS
6539     state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6540 #endif /* AFS_DEMAND_ATTACH_FS */
6541     VOL_UNLOCK;
6542
6543     fdP = IH_OPEN(vip->handle);
6544     opr_Assert(fdP != NULL);
6545     file = FDH_FDOPEN(fdP, "r");
6546     opr_Assert(file != NULL);
6547     vnode = malloc(vcp->diskSize);
6548     opr_Assert(vnode != NULL);
6549     size = OS_SIZE(fdP->fd_fd);
6550     opr_Assert(size != -1);
6551     nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
6552         >> vcp->logSize;
6553     vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4;     /* The 10 is a little extra so
6554                                                          * a few files can be created in this volume,
6555                                                          * the whole thing is rounded up to nearest 4
6556                                                          * bytes, because the bit map allocator likes
6557                                                          * it that way */
6558 #ifdef BITMAP_LATER
6559     BitMap = (byte *) calloc(1, vip->bitmapSize);
6560     opr_Assert(BitMap != NULL);
6561 #else /* BITMAP_LATER */
6562     vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
6563     opr_Assert(vip->bitmap != NULL);
6564     vip->bitmapOffset = 0;
6565 #endif /* BITMAP_LATER */
6566     if (STREAM_ASEEK(file, vcp->diskSize) != -1) {
6567         int bitNumber = 0;
6568         for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
6569             if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
6570                 break;
6571             if (vnode->type != vNull) {
6572                 if (vnode->vnodeMagic != vcp->magic) {
6573                     Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
6574                     *ec = VSALVAGE;
6575                     break;
6576                 }
6577 #ifdef BITMAP_LATER
6578                 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6579 #else /* BITMAP_LATER */
6580                 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6581 #endif /* BITMAP_LATER */
6582                 if (unique <= vnode->uniquifier)
6583                     unique = vnode->uniquifier + 1;
6584             }
6585 #ifndef AFS_PTHREAD_ENV
6586             if ((bitNumber & 0x00ff) == 0x0ff) {        /* every 256 iterations */
6587                 IOMGR_Poll();
6588             }
6589 #endif /* !AFS_PTHREAD_ENV */
6590         }
6591     }
6592     if (vp->nextVnodeUnique < unique) {
6593         Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
6594         *ec = VSALVAGE;
6595     }
6596     /* Paranoia, partly justified--I think fclose after fdopen
6597      * doesn't seem to close fd.  In any event, the documentation
6598      * doesn't specify, so it's safer to close it twice.
6599      */
6600     STREAM_CLOSE(file);
6601     FDH_CLOSE(fdP);
6602     free(vnode);
6603
6604     VOL_LOCK;
6605 #ifdef BITMAP_LATER
6606     /* There may have been a racing condition with some other thread, both
6607      * creating the bitmaps for this volume. If the other thread was faster
6608      * the pointer to bitmap should already be filled and we can free ours.
6609      */
6610     if (vip->bitmap == NULL) {
6611         vip->bitmap = BitMap;
6612         vip->bitmapOffset = 0;
6613     } else
6614         free(BitMap);
6615 #endif /* BITMAP_LATER */
6616 #ifdef AFS_DEMAND_ATTACH_FS
6617     VChangeState_r(vp, state_save);
6618 #endif /* AFS_DEMAND_ATTACH_FS */
6619 }
6620
6621
6622 /***************************************************/
6623 /* Volume Path and Volume Number utility routines  */
6624 /***************************************************/
6625
6626 /**
6627  * find the first occurrence of a volume header file and return the path.
6628  *
6629  * @param[out] ec          outbound error code
6630  * @param[in]  volumeId    volume id to find
6631  * @param[out] partitionp  pointer to disk partition path string
6632  * @param[out] namep       pointer to volume header file name string
6633  *
6634  * @post path to first occurrence of volume header is returned in partitionp
6635  *       and namep, or ec is set accordingly.
6636  *
6637  * @warning this function is NOT re-entrant -- partitionp and namep point to
6638  *          static data segments
6639  *
6640  * @note if a volume utility inadvertently leaves behind a stale volume header
6641  *       on a vice partition, it is possible for callers to get the wrong one,
6642  *       depending on the order of the disk partition linked list.
6643  *
6644  */
6645 void
6646 VGetVolumePath(Error * ec, VolumeId volumeId, char **partitionp, char **namep)
6647 {
6648     static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
6649     char path[VMAXPATHLEN];
6650     int found = 0;
6651     struct DiskPartition64 *dp;
6652
6653     *ec = 0;
6654     name[0] = OS_DIRSEPC;
6655     snprintf(&name[1], (sizeof name) - 1, VFORMAT,
6656              afs_printable_VolumeId_lu(volumeId));
6657     for (dp = DiskPartitionList; dp; dp = dp->next) {
6658         struct afs_stat_st status;
6659         strcpy(path, VPartitionPath(dp));
6660         strcat(path, name);
6661         if (afs_stat(path, &status) == 0) {
6662             strcpy(partition, dp->name);
6663             found = 1;
6664             break;
6665         }
6666     }
6667     if (!found) {
6668         *ec = VNOVOL;
6669         *partitionp = *namep = NULL;
6670     } else {
6671         *partitionp = partition;
6672         *namep = name;
6673     }
6674 }
6675
6676 /**
6677  * extract a volume number from a volume header filename string.
6678  *
6679  * @param[in] name  volume header filename string
6680  *
6681  * @return volume number
6682  *
6683  * @note the string must be of the form VFORMAT.  the only permissible
6684  *       deviation is a leading OS_DIRSEPC character.
6685  *
6686  * @see VFORMAT
6687  */
6688 int
6689 VolumeNumber(char *name)
6690 {
6691     if (*name == OS_DIRSEPC)
6692         name++;
6693     return strtoul(name + 1, NULL, 10);
6694 }
6695
6696 /**
6697  * compute the volume header filename.
6698  *
6699  * @param[in] volumeId
6700  *
6701  * @return volume header filename
6702  *
6703  * @post volume header filename string is constructed
6704  *
6705  * @warning this function is NOT re-entrant -- the returned string is
6706  *          stored in a static char array.  see VolumeExternalName_r
6707  *          for a re-entrant equivalent.
6708  *
6709  * @see VolumeExternalName_r
6710  *
6711  * @deprecated due to the above re-entrancy warning, this interface should
6712  *             be considered deprecated.  Please use VolumeExternalName_r
6713  *             in its stead.
6714  */
6715 char *
6716 VolumeExternalName(VolumeId volumeId)
6717 {
6718     static char name[VMAXPATHLEN];
6719     snprintf(name, sizeof name, VFORMAT, afs_printable_VolumeId_lu(volumeId));
6720     return name;
6721 }
6722
6723 /**
6724  * compute the volume header filename.
6725  *
6726  * @param[in]     volumeId
6727  * @param[inout]  name       array in which to store filename
6728  * @param[in]     len        length of name array
6729  *
6730  * @return result code from afs_snprintf
6731  *
6732  * @see VolumeExternalName
6733  * @see afs_snprintf
6734  *
6735  * @note re-entrant equivalent of VolumeExternalName
6736  */
6737 int
6738 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
6739 {
6740     return snprintf(name, len, VFORMAT, afs_printable_VolumeId_lu(volumeId));
6741 }
6742
6743
6744 /***************************************************/
6745 /* Volume Usage Statistics routines                */
6746 /***************************************************/
6747
6748 #define OneDay  (86400)         /* 24 hours' worth of seconds */
6749
6750 static time_t
6751 Midnight(time_t t) {
6752     struct tm local, *l;
6753     time_t midnight;
6754
6755 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
6756     l = localtime_r(&t, &local);
6757 #else
6758     l = localtime(&t);
6759 #endif
6760
6761     if (l != NULL) {
6762         /* the following is strictly speaking problematic on the
6763            switching day to daylight saving time, after the switch,
6764            as tm_isdst does not match.  Similarly, on the looong day when
6765            switching back the OneDay check will not do what naively expected!
6766            The effects are minor, though, and more a matter of interpreting
6767            the numbers. */
6768 #ifndef AFS_PTHREAD_ENV
6769         local = *l;
6770 #endif
6771         local.tm_hour = local.tm_min=local.tm_sec = 0;
6772         midnight = mktime(&local);
6773         if (midnight != (time_t) -1) return(midnight);
6774     }
6775     return( (t/OneDay)*OneDay );
6776
6777 }
6778
6779 /*------------------------------------------------------------------------
6780  * [export] VAdjustVolumeStatistics
6781  *
6782  * Description:
6783  *      If we've passed midnight, we need to update all the day use
6784  *      statistics as well as zeroing the detailed volume statistics
6785  *      (if we are implementing them).
6786  *
6787  * Arguments:
6788  *      vp : Pointer to the volume structure describing the lucky
6789  *              volume being considered for update.
6790  *
6791  * Returns:
6792  *      0 (always!)
6793  *
6794  * Environment:
6795  *      Nothing interesting.
6796  *
6797  * Side Effects:
6798  *      As described.
6799  *------------------------------------------------------------------------*/
6800
6801 int
6802 VAdjustVolumeStatistics_r(Volume * vp)
6803 {
6804     unsigned int now = FT_ApproxTime();
6805
6806     if (now - V_dayUseDate(vp) > OneDay) {
6807         int ndays, i;
6808
6809         ndays = (now - V_dayUseDate(vp)) / OneDay;
6810         for (i = 6; i > ndays - 1; i--)
6811             V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
6812         for (i = 0; i < ndays - 1 && i < 7; i++)
6813             V_weekUse(vp)[i] = 0;
6814         if (ndays <= 7)
6815             V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
6816         V_dayUse(vp) = 0;
6817         V_dayUseDate(vp) = Midnight(now);
6818
6819         /*
6820          * All we need to do is bzero the entire VOL_STATS_BYTES of
6821          * the detailed volume statistics area.
6822          */
6823         memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
6824         }
6825
6826     /*It's been more than a day of collection */
6827     /*
6828      * Always return happily.
6829      */
6830     return (0);
6831 }                               /*VAdjustVolumeStatistics */
6832
6833 int
6834 VAdjustVolumeStatistics(Volume * vp)
6835 {
6836     int retVal;
6837     VOL_LOCK;
6838     retVal = VAdjustVolumeStatistics_r(vp);
6839     VOL_UNLOCK;
6840     return retVal;
6841 }
6842
6843 void
6844 VBumpVolumeUsage_r(Volume * vp)
6845 {
6846     unsigned int now = FT_ApproxTime();
6847     V_accessDate(vp) = now;
6848     if (now - V_dayUseDate(vp) > OneDay)
6849         VAdjustVolumeStatistics_r(vp);
6850     /*
6851      * Save the volume header image to disk after a threshold of bumps to dayUse,
6852      * at most every usage_rate_limit seconds.
6853      */
6854     V_dayUse(vp)++;
6855     vp->usage_bumps_outstanding++;
6856     if (vp->usage_bumps_outstanding >= vol_opts.usage_threshold
6857         && vp->usage_bumps_next_write <= now) {
6858         Error error;
6859         vp->usage_bumps_outstanding = 0;
6860         vp->usage_bumps_next_write = now + vol_opts.usage_rate_limit;
6861         VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
6862     }
6863 }
6864
6865 void
6866 VBumpVolumeUsage(Volume * vp)
6867 {
6868     VOL_LOCK;
6869     VBumpVolumeUsage_r(vp);
6870     VOL_UNLOCK;
6871 }
6872
6873 void
6874 VSetDiskUsage_r(void)
6875 {
6876 #ifndef AFS_DEMAND_ATTACH_FS
6877     static int FifteenMinuteCounter = 0;
6878 #endif
6879
6880     while (VInit < 2) {
6881         /* NOTE: Don't attempt to access the partitions list until the
6882          * initialization level indicates that all volumes are attached,
6883          * which implies that all partitions are initialized. */
6884 #ifdef AFS_PTHREAD_ENV
6885         VOL_CV_WAIT(&vol_vinit_cond);
6886 #else /* AFS_PTHREAD_ENV */
6887         IOMGR_Sleep(10);
6888 #endif /* AFS_PTHREAD_ENV */
6889     }
6890
6891     VResetDiskUsage_r();
6892
6893 #ifndef AFS_DEMAND_ATTACH_FS
6894     if (++FifteenMinuteCounter == 3) {
6895         FifteenMinuteCounter = 0;
6896         VScanUpdateList();
6897     }
6898 #endif /* !AFS_DEMAND_ATTACH_FS */
6899 }
6900
6901 void
6902 VSetDiskUsage(void)
6903 {
6904     VOL_LOCK;
6905     VSetDiskUsage_r();
6906     VOL_UNLOCK;
6907 }
6908
6909
6910 /***************************************************/
6911 /* Volume Update List routines                     */
6912 /***************************************************/
6913
6914 /* The number of minutes that a volume hasn't been updated before the
6915  * "Dont salvage" flag in the volume header will be turned on */
6916 #define SALVAGE_INTERVAL        (10*60)
6917
6918 /*
6919  * demand attach fs
6920  *
6921  * volume update list functionality has been moved into the VLRU
6922  * the DONT_SALVAGE flag is now set during VLRU demotion
6923  */
6924
6925 #ifndef AFS_DEMAND_ATTACH_FS
6926 static VolumeId *UpdateList = NULL;     /* Pointer to array of Volume ID's */
6927 static int nUpdatedVolumes = 0;         /* Updated with entry in UpdateList, salvage after crash flag on */
6928 static int updateSize = 0;              /* number of entries possible */
6929 #define UPDATE_LIST_SIZE 128            /* initial size increment (must be a power of 2!) */
6930 #endif /* !AFS_DEMAND_ATTACH_FS */
6931
6932 void
6933 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
6934 {
6935     *ec = 0;
6936     vp->updateTime = FT_ApproxTime();
6937     if (V_dontSalvage(vp) == 0)
6938         return;
6939     V_dontSalvage(vp) = 0;
6940     VSyncVolume_r(ec, vp, 0);
6941 #ifdef AFS_DEMAND_ATTACH_FS
6942     V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
6943 #else /* !AFS_DEMAND_ATTACH_FS */
6944     if (*ec)
6945         return;
6946     if (UpdateList == NULL) {
6947         updateSize = UPDATE_LIST_SIZE;
6948         UpdateList = malloc(sizeof(VolumeId) * updateSize);
6949     } else {
6950         if (nUpdatedVolumes == updateSize) {
6951             updateSize <<= 1;
6952             if (updateSize > 524288) {
6953                 Log("warning: there is likely a bug in the volume update scanner\n");
6954                 return;
6955             }
6956             UpdateList = realloc(UpdateList,
6957                                  sizeof(VolumeId) * updateSize);
6958         }
6959     }
6960     opr_Assert(UpdateList != NULL);
6961     UpdateList[nUpdatedVolumes++] = V_id(vp);
6962 #endif /* !AFS_DEMAND_ATTACH_FS */
6963 }
6964
6965 #ifndef AFS_DEMAND_ATTACH_FS
6966 static void
6967 VScanUpdateList(void)
6968 {
6969     int i, gap;
6970     Volume *vp;
6971     Error error;
6972     afs_uint32 now = FT_ApproxTime();
6973     /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
6974     for (i = gap = 0; i < nUpdatedVolumes; i++) {
6975         if (gap)
6976             UpdateList[i - gap] = UpdateList[i];
6977
6978         /* XXX this routine needlessly messes up the Volume LRU by
6979          * breaking the LRU temporal-locality assumptions.....
6980          * we should use a special volume header allocator here */
6981         vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
6982         if (error) {
6983             gap++;
6984         } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
6985             V_dontSalvage(vp) = DONT_SALVAGE;
6986             VUpdateVolume_r(&error, vp, 0);     /* No need to fsync--not critical */
6987             gap++;
6988         }
6989
6990         if (vp) {
6991             VPutVolume_r(vp);
6992         }
6993
6994 #ifndef AFS_PTHREAD_ENV
6995         IOMGR_Poll();
6996 #endif /* !AFS_PTHREAD_ENV */
6997     }
6998     nUpdatedVolumes -= gap;
6999 }
7000 #endif /* !AFS_DEMAND_ATTACH_FS */
7001
7002
7003 /***************************************************/
7004 /* Volume LRU routines                             */
7005 /***************************************************/
7006
7007 /* demand attach fs
7008  * volume LRU
7009  *
7010  * with demand attach fs, we attempt to soft detach(1)
7011  * volumes which have not been accessed in a long time
7012  * in order to speed up fileserver shutdown
7013  *
7014  * (1) by soft detach we mean a process very similar
7015  *     to VOffline, except the final state of the
7016  *     Volume will be VOL_STATE_PREATTACHED, instead
7017  *     of the usual VOL_STATE_UNATTACHED
7018  */
7019 #ifdef AFS_DEMAND_ATTACH_FS
7020
7021 /* implementation is reminiscent of a generational GC
7022  *
7023  * queue 0 is newly attached volumes. this queue is
7024  * sorted by attach timestamp
7025  *
7026  * queue 1 is volumes that have been around a bit
7027  * longer than queue 0. this queue is sorted by
7028  * attach timestamp
7029  *
7030  * queue 2 is volumes tha have been around the longest.
7031  * this queue is unsorted
7032  *
7033  * queue 3 is volumes that have been marked as
7034  * candidates for soft detachment. this queue is
7035  * unsorted
7036  */
7037 #define VLRU_GENERATIONS  3   /**< number of generations in VLRU */
7038 #define VLRU_QUEUES       5   /**< total number of VLRU queues */
7039
7040 /**
7041  * definition of a VLRU queue.
7042  */
7043 struct VLRU_q {
7044     volatile struct rx_queue q;
7045     volatile int len;
7046     volatile int busy;
7047     pthread_cond_t cv;
7048 };
7049
7050 /**
7051  * main VLRU data structure.
7052  */
7053 struct VLRU {
7054     struct VLRU_q q[VLRU_QUEUES];   /**< VLRU queues */
7055
7056     /* VLRU config */
7057     /** time interval (in seconds) between promotion passes for
7058      *  each young generation queue. */
7059     afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
7060
7061     /** time interval (in seconds) between soft detach candidate
7062      *  scans for each generation queue.
7063      *
7064      *  scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
7065      *  we perform a soft detach pass. */
7066     afs_uint32 scan_interval[VLRU_GENERATIONS+1];
7067
7068     /* scheduler state */
7069     int next_idx;                                       /**< next queue to receive attention */
7070     afs_uint32 last_promotion[VLRU_GENERATIONS-1];      /**< timestamp of last promotion scan */
7071     afs_uint32 last_scan[VLRU_GENERATIONS+1];           /**< timestamp of last detach scan */
7072
7073     int scanner_state;                                  /**< state of scanner thread */
7074     pthread_cond_t cv;                                  /**< state transition CV */
7075 };
7076
7077 /** global VLRU state */
7078 static struct VLRU volume_LRU;
7079
7080 /**
7081  * defined states for VLRU scanner thread.
7082  */
7083 typedef enum {
7084     VLRU_SCANNER_STATE_OFFLINE        = 0,    /**< vlru scanner thread is offline */
7085     VLRU_SCANNER_STATE_ONLINE         = 1,    /**< vlru scanner thread is online */
7086     VLRU_SCANNER_STATE_SHUTTING_DOWN  = 2,    /**< vlru scanner thread is shutting down */
7087     VLRU_SCANNER_STATE_PAUSING        = 3,    /**< vlru scanner thread is getting ready to pause */
7088     VLRU_SCANNER_STATE_PAUSED         = 4     /**< vlru scanner thread is paused */
7089 } vlru_thread_state_t;
7090
7091 /* vlru disk data header stuff */
7092 #define VLRU_DISK_MAGIC      0x7a8b9cad        /**< vlru disk entry magic number */
7093 #define VLRU_DISK_VERSION    1                 /**< vlru disk entry version number */
7094
7095 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
7096 #define VLRU_DUMP_EXPIRATION_TIME   (60*60*24*7)  /* expire vlru data after 1 week */
7097
7098
7099 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
7100  *  soft detachment. */
7101 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
7102
7103 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
7104 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
7105
7106 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
7107 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
7108
7109 /** VLRU control flag.  non-zero value implies VLRU subsystem is activated. */
7110 static afs_uint32 VLRU_enabled = 1;
7111
7112 /* queue synchronization routines */
7113 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
7114 static void VLRU_EndExclusive_r(struct VLRU_q * q);
7115 static void VLRU_Wait_r(struct VLRU_q * q);
7116
7117 /**
7118  * set VLRU subsystem tunable parameters.
7119  *
7120  * @param[in] option  tunable option to modify
7121  * @param[in] val     new value for tunable parameter
7122  *
7123  * @pre @c VInitVolumePackage2 has not yet been called.
7124  *
7125  * @post tunable parameter is modified
7126  *
7127  * @note DAFS only
7128  *
7129  * @note valid option parameters are:
7130  *    @arg @c VLRU_SET_THRESH
7131  *         set the period of inactivity after which
7132  *         volumes are eligible for soft detachment
7133  *    @arg @c VLRU_SET_INTERVAL
7134  *         set the time interval between calls
7135  *         to the volume LRU "garbage collector"
7136  *    @arg @c VLRU_SET_MAX
7137  *         set the max number of volumes to deallocate
7138  *         in one GC pass
7139  */
7140 void
7141 VLRU_SetOptions(int option, afs_uint32 val)
7142 {
7143     if (option == VLRU_SET_THRESH) {
7144         VLRU_offline_thresh = val;
7145     } else if (option == VLRU_SET_INTERVAL) {
7146         VLRU_offline_interval = val;
7147     } else if (option == VLRU_SET_MAX) {
7148         VLRU_offline_max = val;
7149     } else if (option == VLRU_SET_ENABLED) {
7150         VLRU_enabled = val;
7151     }
7152     VLRU_ComputeConstants();
7153 }
7154
7155 /**
7156  * compute VLRU internal timing parameters.
7157  *
7158  * @post VLRU scanner thread internal timing parameters are computed
7159  *
7160  * @note computes internal timing parameters based upon user-modifiable
7161  *       tunable parameters.
7162  *
7163  * @note DAFS only
7164  *
7165  * @internal volume package internal use only.
7166  */
7167 static void
7168 VLRU_ComputeConstants(void)
7169 {
7170     afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
7171
7172     /* compute the candidate scan interval */
7173     volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
7174
7175     /* compute the promotion intervals */
7176     volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
7177     volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
7178
7179     if (factor > 16) {
7180         /* compute the gen 0 scan interval */
7181         volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
7182     } else {
7183         /* compute the gen 0 scan interval */
7184         volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
7185     }
7186 }
7187
7188 /**
7189  * initialize VLRU subsystem.
7190  *
7191  * @pre this function has not yet been called
7192  *
7193  * @post VLRU subsystem is initialized and VLRU scanner thread is starting
7194  *
7195  * @note DAFS only
7196  *
7197  * @internal volume package internal use only.
7198  */
7199 static void
7200 VInitVLRU(void)
7201 {
7202     pthread_t tid;
7203     pthread_attr_t attrs;
7204     int i;
7205
7206     if (!VLRU_enabled) {
7207         Log("VLRU: disabled\n");
7208         return;
7209     }
7210
7211     /* initialize each of the VLRU queues */
7212     for (i = 0; i < VLRU_QUEUES; i++) {
7213         queue_Init(&volume_LRU.q[i]);
7214         volume_LRU.q[i].len = 0;
7215         volume_LRU.q[i].busy = 0;
7216         opr_cv_init(&volume_LRU.q[i].cv);
7217     }
7218
7219     /* setup the timing constants */
7220     VLRU_ComputeConstants();
7221
7222     /* XXX put inside log level check? */
7223     Log("VLRU: starting scanner with the following configuration parameters:\n");
7224     Log("VLRU:  offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
7225     Log("VLRU:  running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
7226     Log("VLRU:  taking up to %d volumes offline per pass\n", VLRU_offline_max);
7227     Log("VLRU:  scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
7228     Log("VLRU:  scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
7229     Log("VLRU:  scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
7230
7231     /* start up the VLRU scanner */
7232     volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7233     if (programType == fileServer) {
7234         opr_cv_init(&volume_LRU.cv);
7235         opr_Verify(pthread_attr_init(&attrs) == 0);
7236         opr_Verify(pthread_attr_setdetachstate(&attrs,
7237                                                PTHREAD_CREATE_DETACHED) == 0);
7238         opr_Verify(pthread_create(&tid, &attrs,
7239                                   &VLRU_ScannerThread, NULL) == 0);
7240     }
7241 }
7242
7243 /**
7244  * initialize the VLRU-related fields of a newly allocated volume object.
7245  *
7246  * @param[in] vp  pointer to volume object
7247  *
7248  * @pre
7249  *    @arg @c VOL_LOCK is held.
7250  *    @arg volume object is not on a VLRU queue.
7251  *
7252  * @post VLRU fields are initialized to indicate that volume object is not
7253  *       currently registered with the VLRU subsystem
7254  *
7255  * @note DAFS only
7256  *
7257  * @internal volume package interal use only.
7258  */
7259 static void
7260 VLRU_Init_Node_r(Volume * vp)
7261 {
7262     if (!VLRU_enabled)
7263         return;
7264
7265     opr_Assert(queue_IsNotOnQueue(&vp->vlru));
7266     vp->vlru.idx = VLRU_QUEUE_INVALID;
7267 }
7268
7269 /**
7270  * add a volume object to a VLRU queue.
7271  *
7272  * @param[in] vp  pointer to volume object
7273  *
7274  * @pre
7275  *    @arg @c VOL_LOCK is held.
7276  *    @arg caller MUST hold a lightweight ref on @p vp.
7277  *    @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7278  *
7279  * @post the volume object is added to the appropriate VLRU queue
7280  *
7281  * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
7282  *       then the volume is added to that queue.  Otherwise, the value
7283  *       @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
7284  *       volume is added to the NEW generation queue.
7285  *
7286  * @note @c VOL_LOCK may be dropped internally
7287  *
7288  * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
7289  *       during the add operation, and is restored to the previous
7290  *       state prior to return.
7291  *
7292  * @note DAFS only
7293  *
7294  * @internal volume package internal use only.
7295  */
7296 static void
7297 VLRU_Add_r(Volume * vp)
7298 {
7299     int idx;
7300     VolState state_save;
7301
7302     if (!VLRU_enabled)
7303         return;
7304
7305     if (queue_IsOnQueue(&vp->vlru))
7306         return;
7307
7308     state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
7309
7310     idx = vp->vlru.idx;
7311     if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
7312         idx = VLRU_QUEUE_NEW;
7313     }
7314
7315     VLRU_Wait_r(&volume_LRU.q[idx]);
7316
7317     /* repeat check since VLRU_Wait_r may have dropped
7318      * the glock */
7319     if (queue_IsNotOnQueue(&vp->vlru)) {
7320         vp->vlru.idx = idx;
7321         queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
7322         volume_LRU.q[idx].len++;
7323         V_attachFlags(vp) |= VOL_ON_VLRU;
7324         vp->stats.last_promote = FT_ApproxTime();
7325     }
7326
7327     VChangeState_r(vp, state_save);
7328 }
7329
7330 /**
7331  * delete a volume object from a VLRU queue.
7332  *
7333  * @param[in] vp  pointer to volume object
7334  *
7335  * @pre
7336  *    @arg @c VOL_LOCK is held.
7337  *    @arg caller MUST hold a lightweight ref on @p vp.
7338  *    @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7339  *
7340  * @post volume object is removed from the VLRU queue
7341  *
7342  * @note @c VOL_LOCK may be dropped internally
7343  *
7344  * @note DAFS only
7345  *
7346  * @todo We should probably set volume state to something exlcusive
7347  *       (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
7348  *
7349  * @internal volume package internal use only.
7350  */
7351 static void
7352 VLRU_Delete_r(Volume * vp)
7353 {
7354     int idx;
7355
7356     if (!VLRU_enabled)
7357         return;
7358
7359     if (queue_IsNotOnQueue(&vp->vlru))
7360         return;
7361
7362     /* handle races */
7363     do {
7364       idx = vp->vlru.idx;
7365       if (idx == VLRU_QUEUE_INVALID)
7366           return;
7367       VLRU_Wait_r(&volume_LRU.q[idx]);
7368     } while (idx != vp->vlru.idx);
7369
7370     /* now remove from the VLRU and update
7371      * the appropriate counter */
7372     queue_Remove(&vp->vlru);
7373     volume_LRU.q[idx].len--;
7374     vp->vlru.idx = VLRU_QUEUE_INVALID;
7375     V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7376 }
7377
7378 /**
7379  * tell the VLRU subsystem that a volume was just accessed.
7380  *
7381  * @param[in] vp  pointer to volume object
7382  *
7383  * @pre
7384  *    @arg @c VOL_LOCK is held
7385  *    @arg caller MUST hold a lightweight ref on @p vp
7386  *    @arg caller MUST NOT hold exclusive ownership of any VLRU queue
7387  *
7388  * @post volume VLRU access statistics are updated.  If the volume was on
7389  *       the VLRU soft detach candidate queue, it is moved to the NEW
7390  *       generation queue.
7391  *
7392  * @note @c VOL_LOCK may be dropped internally
7393  *
7394  * @note DAFS only
7395  *
7396  * @internal volume package internal use only.
7397  */
7398 static void
7399 VLRU_UpdateAccess_r(Volume * vp)
7400 {
7401     Volume * rvp = NULL;
7402
7403     if (!VLRU_enabled)
7404         return;
7405
7406     if (queue_IsNotOnQueue(&vp->vlru))
7407         return;
7408
7409     opr_Assert(V_attachFlags(vp) & VOL_ON_VLRU);
7410
7411     /* update the access timestamp */
7412     vp->stats.last_get = FT_ApproxTime();
7413
7414     /*
7415      * if the volume is on the soft detach candidate
7416      * list, we need to safely move it back to a
7417      * regular generation.  this has to be done
7418      * carefully so we don't race against the scanner
7419      * thread.
7420      */
7421
7422     /* if this volume is on the soft detach candidate queue,
7423      * then grab exclusive access to the necessary queues */
7424     if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7425         rvp = vp;
7426         VCreateReservation_r(rvp);
7427
7428         VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7429         VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7430         VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7431         VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7432     }
7433
7434     /* make sure multiple threads don't race to update */
7435     if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7436         VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
7437     }
7438
7439     if (rvp) {
7440       VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7441       VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7442       VCancelReservation_r(rvp);
7443     }
7444 }
7445
7446 /**
7447  * switch a volume between two VLRU queues.
7448  *
7449  * @param[in] vp       pointer to volume object
7450  * @param[in] new_idx  index of VLRU queue onto which the volume will be moved
7451  * @param[in] append   controls whether the volume will be appended or
7452  *                     prepended to the queue.  A nonzero value means it will
7453  *                     be appended; zero means it will be prepended.
7454  *
7455  * @pre The new (and old, if applicable) queue(s) must either be owned
7456  *      exclusively by the calling thread for asynchronous manipulation,
7457  *      or the queue(s) must be quiescent and VOL_LOCK must be held.
7458  *      Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
7459  *      for further details of the queue asynchronous processing mechanism.
7460  *
7461  * @post If the volume object was already on a VLRU queue, it is
7462  *       removed from the queue.  Depending on the value of the append
7463  *       parameter, the volume object is either appended or prepended
7464  *       to the VLRU queue referenced by the new_idx parameter.
7465  *
7466  * @note DAFS only
7467  *
7468  * @see VLRU_BeginExclusive_r
7469  * @see VLRU_EndExclusive_r
7470  * @see VLRU_Wait_r
7471  *
7472  * @internal volume package internal use only.
7473  */
7474 static void
7475 VLRU_SwitchQueues(Volume * vp, int new_idx, int append)
7476 {
7477     if (queue_IsNotOnQueue(&vp->vlru))
7478         return;
7479
7480     queue_Remove(&vp->vlru);
7481     volume_LRU.q[vp->vlru.idx].len--;
7482
7483     /* put the volume back on the correct generational queue */
7484     if (append) {
7485         queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
7486     } else {
7487         queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
7488     }
7489
7490     volume_LRU.q[new_idx].len++;
7491     vp->vlru.idx = new_idx;
7492 }
7493
7494 /**
7495  * VLRU background thread.
7496  *
7497  * The VLRU Scanner Thread is responsible for periodically scanning through
7498  * each VLRU queue looking for volumes which should be moved to another
7499  * queue, or soft detached.
7500  *
7501  * @param[in] args  unused thread arguments parameter
7502  *
7503  * @return unused thread return value
7504  *    @retval NULL always
7505  *
7506  * @internal volume package internal use only.
7507  */
7508 static void *
7509 VLRU_ScannerThread(void * args)
7510 {
7511     afs_uint32 now, min_delay, delay;
7512     int i, min_idx, min_op, overdue, state;
7513
7514     /* set t=0 for promotion cycle to be
7515      * fileserver startup */
7516     now = FT_ApproxTime();
7517     for (i=0; i < VLRU_GENERATIONS-1; i++) {
7518         volume_LRU.last_promotion[i] = now;
7519     }
7520
7521     /* don't start the scanner until VLRU_offline_thresh
7522      * plus a small delay for VInitVolumePackage2 to finish
7523      * has gone by */
7524
7525     sleep(VLRU_offline_thresh + 60);
7526
7527     /* set t=0 for scan cycle to be now */
7528     now = FT_ApproxTime();
7529     for (i=0; i < VLRU_GENERATIONS+1; i++) {
7530         volume_LRU.last_scan[i] = now;
7531     }
7532
7533     VOL_LOCK;
7534     if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
7535         volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
7536     }
7537
7538     while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
7539         /* check to see if we've been asked to pause */
7540         if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
7541             volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
7542             opr_cv_broadcast(&volume_LRU.cv);
7543             do {
7544                 VOL_CV_WAIT(&volume_LRU.cv);
7545             } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
7546         }
7547
7548         /* scheduling can happen outside the glock */
7549         VOL_UNLOCK;
7550
7551         /* figure out what is next on the schedule */
7552
7553         /* figure out a potential schedule for the new generation first */
7554         overdue = 0;
7555         min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
7556         min_idx = 0;
7557         min_op = 0;
7558         if (min_delay > volume_LRU.scan_interval[0]) {
7559             /* unsigned overflow -- we're overdue to run this scan */
7560             min_delay = 0;
7561             overdue = 1;
7562         }
7563
7564         /* if we're not overdue for gen 0, figure out schedule for candidate gen */
7565         if (!overdue) {
7566             i = VLRU_QUEUE_CANDIDATE;
7567             delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
7568             if (delay < min_delay) {
7569                 min_delay = delay;
7570                 min_idx = i;
7571             }
7572             if (delay > volume_LRU.scan_interval[i]) {
7573                 /* unsigned overflow -- we're overdue to run this scan */
7574                 min_delay = 0;
7575                 min_idx = i;
7576                 overdue = 1;
7577             }
7578         }
7579
7580         /* if we're still not overdue for something, figure out schedules for promotions */
7581         for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
7582             delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
7583             if (delay < min_delay) {
7584                 min_delay = delay;
7585                 min_idx = i;
7586                 min_op = 1;
7587             }
7588             if (delay > volume_LRU.promotion_interval[i]) {
7589                 /* unsigned overflow -- we're overdue to run this promotion */
7590                 min_delay = 0;
7591                 min_idx = i;
7592                 min_op = 1;
7593                 overdue = 1;
7594                 break;
7595             }
7596         }
7597
7598         /* sleep as needed */
7599         if (min_delay) {
7600             sleep(min_delay);
7601         }
7602
7603         /* do whatever is next */
7604         VOL_LOCK;
7605         if (min_op) {
7606             VLRU_Promote_r(min_idx);
7607             VLRU_Demote_r(min_idx+1);
7608         } else {
7609             VLRU_Scan_r(min_idx);
7610         }
7611         now = FT_ApproxTime();
7612     }
7613
7614     Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
7615
7616     /* signal that scanner is down */
7617     volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7618     opr_cv_broadcast(&volume_LRU.cv);
7619     VOL_UNLOCK;
7620     return NULL;
7621 }
7622
7623 /**
7624  * promote volumes from one VLRU generation to the next.
7625  *
7626  * This routine scans a VLRU generation looking for volumes which are
7627  * eligible to be promoted to the next generation.  All volumes which
7628  * meet the eligibility requirement are promoted.
7629  *
7630  * Promotion eligibility is based upon meeting both of the following
7631  * requirements:
7632  *
7633  *    @arg The volume has been accessed since the last promotion:
7634  *         @c (vp->stats.last_get >= vp->stats.last_promote)
7635  *    @arg The last promotion occurred at least
7636  *         @c volume_LRU.promotion_interval[idx] seconds ago
7637  *
7638  * As a performance optimization, promotions are "globbed".  In other
7639  * words, we promote arbitrarily large contiguous sublists of elements
7640  * as one operation.
7641  *
7642  * @param[in] idx  VLRU queue index to scan
7643  *
7644  * @note DAFS only
7645  *
7646  * @internal VLRU internal use only.
7647  */
7648 static void
7649 VLRU_Promote_r(int idx)
7650 {
7651     int len, chaining, promote;
7652     afs_uint32 now, thresh;
7653     struct rx_queue *qp, *nqp;
7654     Volume * vp, *start = NULL, *end = NULL;
7655
7656     /* get exclusive access to two chains, and drop the glock */
7657     VLRU_Wait_r(&volume_LRU.q[idx]);
7658     VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7659     VLRU_Wait_r(&volume_LRU.q[idx+1]);
7660     VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
7661     VOL_UNLOCK;
7662
7663     thresh = volume_LRU.promotion_interval[idx];
7664     now = FT_ApproxTime();
7665
7666     len = chaining = 0;
7667     for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7668         vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7669         promote = (((vp->stats.last_promote + thresh) <= now) &&
7670                    (vp->stats.last_get >= vp->stats.last_promote));
7671
7672         if (chaining) {
7673             if (promote) {
7674                 vp->vlru.idx++;
7675                 len++;
7676                 start = vp;
7677             } else {
7678                 /* promote and prepend chain */
7679                 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7680                 chaining = 0;
7681             }
7682         } else {
7683             if (promote) {
7684                 vp->vlru.idx++;
7685                 len++;
7686                 chaining = 1;
7687                 start = end = vp;
7688             }
7689         }
7690     }
7691
7692     if (chaining) {
7693         /* promote and prepend */
7694         queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7695     }
7696
7697     if (len) {
7698         volume_LRU.q[idx].len -= len;
7699         volume_LRU.q[idx+1].len += len;
7700     }
7701
7702     /* release exclusive access to the two chains */
7703     VOL_LOCK;
7704     volume_LRU.last_promotion[idx] = now;
7705     VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
7706     VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7707 }
7708
7709 /* run the demotions */
7710 static void
7711 VLRU_Demote_r(int idx)
7712 {
7713     Error ec;
7714     int len, chaining, demote;
7715     afs_uint32 now, thresh;
7716     struct rx_queue *qp, *nqp;
7717     Volume * vp, *start = NULL, *end = NULL;
7718     Volume ** salv_flag_vec = NULL;
7719     int salv_vec_offset = 0;
7720
7721     opr_Assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
7722
7723     /* get exclusive access to two chains, and drop the glock */
7724     VLRU_Wait_r(&volume_LRU.q[idx-1]);
7725     VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
7726     VLRU_Wait_r(&volume_LRU.q[idx]);
7727     VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7728     VOL_UNLOCK;
7729
7730     /* no big deal if this allocation fails */
7731     if (volume_LRU.q[idx].len) {
7732         salv_flag_vec = malloc(volume_LRU.q[idx].len * sizeof(Volume *));
7733     }
7734
7735     now = FT_ApproxTime();
7736     thresh = volume_LRU.promotion_interval[idx-1];
7737
7738     len = chaining = 0;
7739     for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7740         vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7741         demote = (((vp->stats.last_promote + thresh) <= now) &&
7742                   (vp->stats.last_get < (now - thresh)));
7743
7744         /* we now do volume update list DONT_SALVAGE flag setting during
7745          * demotion passes */
7746         if (salv_flag_vec &&
7747             !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7748             demote &&
7749             (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7750             (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7751             salv_flag_vec[salv_vec_offset++] = vp;
7752             VCreateReservation_r(vp);
7753         }
7754
7755         if (chaining) {
7756             if (demote) {
7757                 vp->vlru.idx--;
7758                 len++;
7759                 start = vp;
7760             } else {
7761                 /* demote and append chain */
7762                 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7763                 chaining = 0;
7764             }
7765         } else {
7766             if (demote) {
7767                 vp->vlru.idx--;
7768                 len++;
7769                 chaining = 1;
7770                 start = end = vp;
7771             }
7772         }
7773     }
7774
7775     if (chaining) {
7776         queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7777     }
7778
7779     if (len) {
7780         volume_LRU.q[idx].len -= len;
7781         volume_LRU.q[idx-1].len += len;
7782     }
7783
7784     /* release exclusive access to the two chains */
7785     VOL_LOCK;
7786     VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7787     VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
7788
7789     /* now go back and set the DONT_SALVAGE flags as appropriate */
7790     if (salv_flag_vec) {
7791         int i;
7792         for (i = 0; i < salv_vec_offset; i++) {
7793             vp = salv_flag_vec[i];
7794             if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7795                 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7796                 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7797                 ec = VHold_r(vp);
7798                 if (!ec) {
7799                     V_attachFlags(vp) |= VOL_HDR_DONTSALV;
7800                     V_dontSalvage(vp) = DONT_SALVAGE;
7801                     VUpdateVolume_r(&ec, vp, 0);
7802                     VPutVolume_r(vp);
7803                 }
7804             }
7805             VCancelReservation_r(vp);
7806         }
7807         free(salv_flag_vec);
7808     }
7809 }
7810
7811 /* run a pass of the VLRU GC scanner */
7812 static void
7813 VLRU_Scan_r(int idx)
7814 {
7815     afs_uint32 now, thresh;
7816     struct rx_queue *qp, *nqp;
7817     Volume * vp;
7818     int i, locked = 1;
7819
7820     opr_Assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
7821
7822     /* gain exclusive access to the idx VLRU */
7823     VLRU_Wait_r(&volume_LRU.q[idx]);
7824     VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7825
7826     if (idx != VLRU_QUEUE_CANDIDATE) {
7827         /* gain exclusive access to the candidate VLRU */
7828         VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7829         VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7830     }
7831
7832     now = FT_ApproxTime();
7833     thresh = now - VLRU_offline_thresh;
7834
7835     /* perform candidate selection and soft detaching */
7836     if (idx == VLRU_QUEUE_CANDIDATE) {
7837         /* soft detach some volumes from the candidate pool */
7838         VOL_UNLOCK;
7839         locked = 0;
7840
7841         for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7842             vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7843             if (i >= VLRU_offline_max) {
7844                 break;
7845             }
7846             /* check timestamp to see if it's a candidate for soft detaching */
7847             if (vp->stats.last_get <= thresh) {
7848                 VOL_LOCK;
7849                 if (VCheckSoftDetach(vp, thresh))
7850                     i++;
7851                 VOL_UNLOCK;
7852             }
7853         }
7854     } else {
7855         /* scan for volumes to become soft detach candidates */
7856         for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
7857             vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7858
7859             /* check timestamp to see if it's a candidate for soft detaching */
7860             if (vp->stats.last_get <= thresh) {
7861                 VCheckSoftDetachCandidate(vp, thresh);
7862             }
7863
7864             if (!(i&0x7f)) {   /* lock coarsening optimization */
7865                 VOL_UNLOCK;
7866                 pthread_yield();
7867                 VOL_LOCK;
7868             }
7869         }
7870     }
7871
7872     /* relinquish exclusive access to the VLRU chains */
7873     if (!locked) {
7874         VOL_LOCK;
7875     }
7876     volume_LRU.last_scan[idx] = now;
7877     if (idx != VLRU_QUEUE_CANDIDATE) {
7878         VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7879     }
7880     VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7881 }
7882
7883 /* check whether volume is safe to soft detach
7884  * caller MUST NOT hold a ref count on vp */
7885 static int
7886 VCheckSoftDetach(Volume * vp, afs_uint32 thresh)
7887 {
7888     int ret=0;
7889
7890     if (vp->nUsers || vp->nWaiters)
7891         return 0;
7892
7893     if (vp->stats.last_get <= thresh) {
7894         ret = VSoftDetachVolume_r(vp, thresh);
7895     }
7896
7897     return ret;
7898 }
7899
7900 /* check whether volume should be made a
7901  * soft detach candidate */
7902 static int
7903 VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh)
7904 {
7905     int idx, ret = 0;
7906     if (vp->nUsers || vp->nWaiters)
7907         return 0;
7908
7909     idx = vp->vlru.idx;
7910
7911     opr_Assert(idx == VLRU_QUEUE_NEW);
7912
7913     if (vp->stats.last_get <= thresh) {
7914         /* move to candidate pool */
7915         queue_Remove(&vp->vlru);
7916         volume_LRU.q[VLRU_QUEUE_NEW].len--;
7917         queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
7918         vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
7919         volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
7920         ret = 1;
7921     }
7922
7923     return ret;
7924 }
7925
7926
7927 /* begin exclusive access on VLRU */
7928 static void
7929 VLRU_BeginExclusive_r(struct VLRU_q * q)
7930 {
7931     opr_Assert(q->busy == 0);
7932     q->busy = 1;
7933 }
7934
7935 /* end exclusive access on VLRU */
7936 static void
7937 VLRU_EndExclusive_r(struct VLRU_q * q)
7938 {
7939     opr_Assert(q->busy);
7940     q->busy = 0;
7941     opr_cv_broadcast(&q->cv);
7942 }
7943
7944 /* wait for another thread to end exclusive access on VLRU */
7945 static void
7946 VLRU_Wait_r(struct VLRU_q * q)
7947 {
7948     while(q->busy) {
7949         VOL_CV_WAIT(&q->cv);
7950     }
7951 }
7952
7953 /* demand attach fs
7954  * volume soft detach
7955  *
7956  * caller MUST NOT hold a ref count on vp */
7957 static int
7958 VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh)
7959 {
7960     afs_uint32 ts_save;
7961     int ret = 0;
7962
7963     opr_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7964
7965     ts_save = vp->stats.last_get;
7966     if (ts_save > thresh)
7967         return 0;
7968
7969     if (vp->nUsers || vp->nWaiters)
7970         return 0;
7971
7972     if (VIsExclusiveState(V_attachState(vp))) {
7973         return 0;
7974     }
7975
7976     switch (V_attachState(vp)) {
7977     case VOL_STATE_UNATTACHED:
7978     case VOL_STATE_PREATTACHED:
7979     case VOL_STATE_ERROR:
7980     case VOL_STATE_GOING_OFFLINE:
7981     case VOL_STATE_SHUTTING_DOWN:
7982     case VOL_STATE_SALVAGING:
7983     case VOL_STATE_DELETED:
7984         volume_LRU.q[vp->vlru.idx].len--;
7985
7986         /* create and cancel a reservation to
7987          * give the volume an opportunity to
7988          * be deallocated */
7989         VCreateReservation_r(vp);
7990         queue_Remove(&vp->vlru);
7991         vp->vlru.idx = VLRU_QUEUE_INVALID;
7992         V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7993         VCancelReservation_r(vp);
7994         return 0;
7995     default:
7996         break;
7997     }
7998
7999     /* hold the volume and take it offline.
8000      * no need for reservations, as VHold_r
8001      * takes care of that internally. */
8002     if (VHold_r(vp) == 0) {
8003         /* vhold drops the glock, so now we should
8004          * check to make sure we aren't racing against
8005          * other threads.  if we are racing, offlining vp
8006          * would be wasteful, and block the scanner for a while
8007          */
8008         if (vp->nWaiters ||
8009             (vp->nUsers > 1) ||
8010             (vp->shuttingDown) ||
8011             (vp->goingOffline) ||
8012             (vp->stats.last_get != ts_save)) {
8013             /* looks like we're racing someone else. bail */
8014             VPutVolume_r(vp);
8015             vp = NULL;
8016         } else {
8017             /* pull it off the VLRU */
8018             opr_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
8019             volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
8020             queue_Remove(&vp->vlru);
8021             vp->vlru.idx = VLRU_QUEUE_INVALID;
8022             V_attachFlags(vp) &= ~(VOL_ON_VLRU);
8023
8024             /* take if offline */
8025             VOffline_r(vp, "volume has been soft detached");
8026
8027             /* invalidate the volume header cache */
8028             FreeVolumeHeader(vp);
8029
8030             /* update stats */
8031             IncUInt64(&VStats.soft_detaches);
8032             vp->stats.soft_detaches++;
8033
8034             /* put in pre-attached state so demand
8035              * attacher can work on it */
8036             VChangeState_r(vp, VOL_STATE_PREATTACHED);
8037             ret = 1;
8038         }
8039     }
8040     return ret;
8041 }
8042 #endif /* AFS_DEMAND_ATTACH_FS */
8043
8044
8045 /***************************************************/
8046 /* Volume Header Cache routines                    */
8047 /***************************************************/
8048
8049 /**
8050  * volume header cache.
8051  */
8052 struct volume_hdr_LRU_t volume_hdr_LRU;
8053
8054 /**
8055  * initialize the volume header cache.
8056  *
8057  * @param[in] howMany  number of header cache entries to preallocate
8058  *
8059  * @pre VOL_LOCK held.  Function has never been called before.
8060  *
8061  * @post howMany cache entries are allocated, initialized, and added
8062  *       to the LRU list.  Header cache statistics are initialized.
8063  *
8064  * @note only applicable to fileServer program type.  Should only be
8065  *       called once during volume package initialization.
8066  *
8067  * @internal volume package internal use only.
8068  */
8069 static void
8070 VInitVolumeHeaderCache(afs_uint32 howMany)
8071 {
8072     struct volHeader *hp;
8073     if (programType != fileServer)
8074         return;
8075     queue_Init(&volume_hdr_LRU);
8076     volume_hdr_LRU.stats.free = 0;
8077     volume_hdr_LRU.stats.used = howMany;
8078     volume_hdr_LRU.stats.attached = 0;
8079     hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
8080     opr_Assert(hp != NULL);
8081
8082     while (howMany--)
8083         /* We are using ReleaseVolumeHeader to initialize the values on the header list
8084          * to ensure they have the right values
8085          */
8086         ReleaseVolumeHeader(hp++);
8087 }
8088
8089 /* get a volume header off of the volume header LRU.
8090  *
8091  * @return volume header
8092  *  @retval NULL no usable volume header is available on the LRU
8093  *
8094  * @pre VOL_LOCK held
8095  *
8096  * @post for DAFS, if the returned header is associated with a volume, that
8097  *       volume is NOT in an exclusive state
8098  *
8099  * @internal volume package internal use only.
8100  */
8101 #ifdef AFS_DEMAND_ATTACH_FS
8102 static struct volHeader*
8103 GetVolHeaderFromLRU(void)
8104 {
8105     struct volHeader *hd = NULL, *qh, *nqh;
8106     /* Usually, a volume in an exclusive state will not have its header on
8107      * the LRU. However, it is possible for this to occur when a salvage
8108      * request is received over FSSYNC, and possibly in other corner cases.
8109      * So just skip over headers whose volumes are in an exclusive state. We
8110      * could VWaitExclusiveState_r instead, but not waiting is faster and
8111      * easier to do */
8112     for (queue_Scan(&volume_hdr_LRU, qh, nqh, volHeader)) {
8113         if (!qh->back || !VIsExclusiveState(V_attachState(qh->back))) {
8114             queue_Remove(qh);
8115             hd = qh;
8116             break;
8117         }
8118     }
8119     return hd;
8120 }
8121 #else /* AFS_DEMAND_ATTACH_FS */
8122 static struct volHeader*
8123 GetVolHeaderFromLRU(void)
8124 {
8125     struct volHeader *hd = NULL;
8126     if (queue_IsNotEmpty(&volume_hdr_LRU)) {
8127         hd = queue_First(&volume_hdr_LRU, volHeader);
8128         queue_Remove(hd);
8129     }
8130     return hd;
8131 }
8132 #endif /* !AFS_DEMAND_ATTACH_FS */
8133
8134 /**
8135  * get a volume header and attach it to the volume object.
8136  *
8137  * @param[in] vp  pointer to volume object
8138  *
8139  * @return cache entry status
8140  *    @retval 0  volume header was newly attached; cache data is invalid
8141  *    @retval 1  volume header was previously attached; cache data is valid
8142  *
8143  * @pre VOL_LOCK held.  For DAFS, lightweight ref must be held on volume object.
8144  *
8145  * @post volume header attached to volume object.  if necessary, header cache
8146  *       entry on LRU is synchronized to disk.  Header is removed from LRU list.
8147  *
8148  * @note VOL_LOCK may be dropped
8149  *
8150  * @warning this interface does not load header data from disk.  it merely
8151  *          attaches a header object to the volume object, and may sync the old
8152  *          header cache data out to disk in the process.
8153  *
8154  * @internal volume package internal use only.
8155  */
8156 static int
8157 GetVolumeHeader(Volume * vp)
8158 {
8159     Error error;
8160     struct volHeader *hd;
8161     int old;
8162     static int everLogged = 0;
8163
8164 #ifdef AFS_DEMAND_ATTACH_FS
8165     VolState vp_save = 0, back_save = 0;
8166
8167     /* XXX debug 9/19/05 we've apparently got
8168      * a ref counting bug somewhere that's
8169      * breaking the nUsers == 0 => header on LRU
8170      * assumption */
8171     if (vp->header && queue_IsNotOnQueue(vp->header)) {
8172         Log("nUsers == 0, but header not on LRU\n");
8173         return 1;
8174     }
8175 #endif
8176
8177     old = (vp->header != NULL); /* old == volume already has a header */
8178
8179     if (programType != fileServer) {
8180         /* for volume utilities, we allocate volHeaders as needed */
8181         if (!vp->header) {
8182             hd = calloc(1, sizeof(*vp->header));
8183             opr_Assert(hd != NULL);
8184             vp->header = hd;
8185             hd->back = vp;
8186 #ifdef AFS_DEMAND_ATTACH_FS
8187             V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8188 #endif
8189         }
8190     } else {
8191         /* for the fileserver, we keep a volume header cache */
8192         if (old) {
8193             /* the header we previously dropped in the lru is
8194              * still available. pull it off the lru and return */
8195             hd = vp->header;
8196             queue_Remove(hd);
8197             opr_Assert(hd->back == vp);
8198 #ifdef AFS_DEMAND_ATTACH_FS
8199             V_attachFlags(vp) &= ~(VOL_HDR_IN_LRU);
8200 #endif
8201         } else {
8202             hd = GetVolHeaderFromLRU();
8203             if (!hd) {
8204                 /* LRU is empty, so allocate a new volHeader
8205                  * this is probably indicative of a leak, so let the user know */
8206                 hd = calloc(1, sizeof(struct volHeader));
8207                 opr_Assert(hd != NULL);
8208                 if (!everLogged) {
8209                     Log("****Allocated more volume headers, probably leak****\n");
8210                     everLogged = 1;
8211                 }
8212                 volume_hdr_LRU.stats.free++;
8213             }
8214             if (hd->back) {
8215                 /* this header used to belong to someone else.
8216                  * we'll need to check if the header needs to
8217                  * be sync'd out to disk */
8218
8219 #ifdef AFS_DEMAND_ATTACH_FS
8220                 /* GetVolHeaderFromLRU had better not give us back a header
8221                  * with a volume in exclusive state... */
8222                 opr_Assert(!VIsExclusiveState(V_attachState(hd->back)));
8223 #endif
8224
8225                 if (hd->diskstuff.inUse) {
8226                     /* volume was in use, so we'll need to sync
8227                      * its header to disk */
8228
8229 #ifdef AFS_DEMAND_ATTACH_FS
8230                     back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
8231                     vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
8232                     VCreateReservation_r(hd->back);
8233                     VOL_UNLOCK;
8234 #endif
8235
8236                     WriteVolumeHeader_r(&error, hd->back);
8237                     /* Ignore errors; catch them later */
8238
8239 #ifdef AFS_DEMAND_ATTACH_FS
8240                     VOL_LOCK;
8241 #endif
8242                 }
8243
8244                 hd->back->header = NULL;
8245 #ifdef AFS_DEMAND_ATTACH_FS
8246                 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
8247
8248                 if (hd->diskstuff.inUse) {
8249                     VChangeState_r(hd->back, back_save);
8250                     VCancelReservation_r(hd->back);
8251                     VChangeState_r(vp, vp_save);
8252                 }
8253 #endif
8254             } else {
8255                 volume_hdr_LRU.stats.attached++;
8256             }
8257             hd->back = vp;
8258             vp->header = hd;
8259 #ifdef AFS_DEMAND_ATTACH_FS
8260             V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8261 #endif
8262         }
8263         volume_hdr_LRU.stats.free--;
8264         volume_hdr_LRU.stats.used++;
8265     }
8266     IncUInt64(&VStats.hdr_gets);
8267 #ifdef AFS_DEMAND_ATTACH_FS
8268     IncUInt64(&vp->stats.hdr_gets);
8269     vp->stats.last_hdr_get = FT_ApproxTime();
8270 #endif
8271     return old;
8272 }
8273
8274
8275 /**
8276  * make sure volume header is attached and contains valid cache data.
8277  *
8278  * @param[out] ec  outbound error code
8279  * @param[in]  vp  pointer to volume object
8280  *
8281  * @pre VOL_LOCK held.  For DAFS, lightweight ref held on vp.
8282  *
8283  * @post header cache entry attached, and loaded with valid data, or
8284  *       *ec is nonzero, and the header is released back into the LRU.
8285  *
8286  * @internal volume package internal use only.
8287  */
8288 static void
8289 LoadVolumeHeader(Error * ec, Volume * vp)
8290 {
8291 #ifdef AFS_DEMAND_ATTACH_FS
8292     VolState state_save;
8293     afs_uint32 now;
8294     *ec = 0;
8295
8296     if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8297         IncUInt64(&VStats.hdr_loads);
8298         state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
8299         VOL_UNLOCK;
8300
8301         ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8302                    sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8303                    VOLUMEINFOVERSION);
8304         IncUInt64(&vp->stats.hdr_loads);
8305         now = FT_ApproxTime();
8306
8307         VOL_LOCK;
8308         if (!*ec) {
8309             V_attachFlags(vp) |= VOL_HDR_LOADED;
8310             vp->stats.last_hdr_load = now;
8311         }
8312         VChangeState_r(vp, state_save);
8313     }
8314 #else /* AFS_DEMAND_ATTACH_FS */
8315     *ec = 0;
8316     if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8317         IncUInt64(&VStats.hdr_loads);
8318
8319         ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8320                    sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8321                    VOLUMEINFOVERSION);
8322     }
8323 #endif /* AFS_DEMAND_ATTACH_FS */
8324     if (*ec) {
8325         /* maintain (nUsers==0) => header in LRU invariant */
8326         FreeVolumeHeader(vp);
8327     }
8328 }
8329
8330 /**
8331  * release a header cache entry back into the LRU list.
8332  *
8333  * @param[in] hd  pointer to volume header cache object
8334  *
8335  * @pre VOL_LOCK held.
8336  *
8337  * @post header cache object appended onto end of LRU list.
8338  *
8339  * @note only applicable to fileServer program type.
8340  *
8341  * @note used to place a header cache entry back into the
8342  *       LRU pool without invalidating it as a cache entry.
8343  *
8344  * @internal volume package internal use only.
8345  */
8346 static void
8347 ReleaseVolumeHeader(struct volHeader *hd)
8348 {
8349     if (programType != fileServer)
8350         return;
8351     if (!hd || queue_IsOnQueue(hd))     /* no header, or header already released */
8352         return;
8353     queue_Append(&volume_hdr_LRU, hd);
8354 #ifdef AFS_DEMAND_ATTACH_FS
8355     if (hd->back) {
8356         V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
8357     }
8358 #endif
8359     volume_hdr_LRU.stats.free++;
8360     volume_hdr_LRU.stats.used--;
8361 }
8362
8363 /**
8364  * free/invalidate a volume header cache entry.
8365  *
8366  * @param[in] vp  pointer to volume object
8367  *
8368  * @pre VOL_LOCK is held.
8369  *
8370  * @post For fileserver, header cache entry is returned to LRU, and it is
8371  *       invalidated as a cache entry.  For volume utilities, the header
8372  *       cache entry is freed.
8373  *
8374  * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
8375  *       whenever it is necessary to invalidate the header cache entry.
8376  *
8377  * @see ReleaseVolumeHeader
8378  *
8379  * @internal volume package internal use only.
8380  */
8381 static void
8382 FreeVolumeHeader(Volume * vp)
8383 {
8384     struct volHeader *hd = vp->header;
8385     if (!hd)
8386         return;
8387     if (programType == fileServer) {
8388         ReleaseVolumeHeader(hd);
8389         hd->back = NULL;
8390     } else {
8391         free(hd);
8392     }
8393 #ifdef AFS_DEMAND_ATTACH_FS
8394     V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
8395 #endif
8396     volume_hdr_LRU.stats.attached--;
8397     vp->header = NULL;
8398 }
8399
8400
8401 /***************************************************/
8402 /* Volume Hash Table routines                      */
8403 /***************************************************/
8404
8405 /**
8406  * set size of volume object hash table.
8407  *
8408  * @param[in] logsize   log(2) of desired hash table size
8409  *
8410  * @return operation status
8411  *    @retval 0 success
8412  *    @retval -1 failure
8413  *
8414  * @pre MUST be called prior to VInitVolumePackage2
8415  *
8416  * @post Volume Hash Table will have 2^logsize buckets
8417  */
8418 int
8419 VSetVolHashSize(int logsize)
8420 {
8421     /* 64 to 268435456 hash buckets seems like a reasonable range */
8422     if ((logsize < 6 ) || (logsize > 28)) {
8423         return -1;
8424     }
8425
8426     if (!VInit) {
8427         VolumeHashTable.Size = opr_jhash_size(logsize);
8428         VolumeHashTable.Mask = opr_jhash_mask(logsize);
8429     } else {
8430         /* we can't yet support runtime modification of this
8431          * parameter. we'll need a configuration rwlock to
8432          * make runtime modification feasible.... */
8433         return -1;
8434     }
8435     return 0;
8436 }
8437
8438 /**
8439  * initialize dynamic data structures for volume hash table.
8440  *
8441  * @post hash table is allocated, and fields are initialized.
8442  *
8443  * @internal volume package internal use only.
8444  */
8445 static void
8446 VInitVolumeHash(void)
8447 {
8448     int i;
8449
8450     VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
8451                                                            sizeof(VolumeHashChainHead));
8452     opr_Assert(VolumeHashTable.Table != NULL);
8453
8454     for (i=0; i < VolumeHashTable.Size; i++) {
8455         queue_Init(&VolumeHashTable.Table[i]);
8456 #ifdef AFS_DEMAND_ATTACH_FS
8457         opr_cv_init(&VolumeHashTable.Table[i].chain_busy_cv);
8458 #endif /* AFS_DEMAND_ATTACH_FS */
8459     }
8460 }
8461
8462 /**
8463  * add a volume object to the hash table.
8464  *
8465  * @param[in] vp      pointer to volume object
8466  * @param[in] hashid  hash of volume id
8467  *
8468  * @pre VOL_LOCK is held.  For DAFS, caller must hold a lightweight
8469  *      reference on vp.
8470  *
8471  * @post volume is added to hash chain.
8472  *
8473  * @internal volume package internal use only.
8474  *
8475  * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8476  *       asynchronous hash chain reordering to finish.
8477  */
8478 static void
8479 AddVolumeToHashTable(Volume * vp, VolumeId hashid)
8480 {
8481     VolumeHashChainHead * head;
8482
8483     if (queue_IsOnQueue(vp))
8484         return;
8485
8486     head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
8487
8488 #ifdef AFS_DEMAND_ATTACH_FS
8489     /* wait for the hash chain to become available */
8490     VHashWait_r(head);
8491
8492     V_attachFlags(vp) |= VOL_IN_HASH;
8493     vp->chainCacheCheck = ++head->cacheCheck;
8494 #endif /* AFS_DEMAND_ATTACH_FS */
8495
8496     head->len++;
8497     vp->hashid = hashid;
8498     queue_Append(head, vp);
8499 }
8500
8501 /**
8502  * delete a volume object from the hash table.
8503  *
8504  * @param[in] vp  pointer to volume object
8505  *
8506  * @pre VOL_LOCK is held.  For DAFS, caller must hold a lightweight
8507  *      reference on vp.
8508  *
8509  * @post volume is removed from hash chain.
8510  *
8511  * @internal volume package internal use only.
8512  *
8513  * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8514  *       asynchronous hash chain reordering to finish.
8515  */
8516 static void
8517 DeleteVolumeFromHashTable(Volume * vp)
8518 {
8519     VolumeHashChainHead * head;
8520
8521     if (!queue_IsOnQueue(vp))
8522         return;
8523
8524     head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
8525
8526 #ifdef AFS_DEMAND_ATTACH_FS
8527     /* wait for the hash chain to become available */
8528     VHashWait_r(head);
8529
8530     V_attachFlags(vp) &= ~(VOL_IN_HASH);
8531     head->cacheCheck++;
8532 #endif /* AFS_DEMAND_ATTACH_FS */
8533
8534     head->len--;
8535     queue_Remove(vp);
8536     /* do NOT reset hashid to zero, as the online
8537      * salvager package may need to know the volume id
8538      * after the volume is removed from the hash */
8539 }
8540
8541 /**
8542  * lookup a volume object in the hash table given a volume id.
8543  *
8544  * @param[out] ec        error code return
8545  * @param[in]  volumeId  volume id
8546  * @param[in]  hint      volume object which we believe could be the correct
8547                          mapping
8548  *
8549  * @return volume object pointer
8550  *    @retval NULL  no such volume id is registered with the hash table.
8551  *
8552  * @pre VOL_LOCK is held.  For DAFS, caller must hold a lightweight
8553         ref on hint.
8554  *
8555  * @post volume object with the given id is returned.  volume object and
8556  *       hash chain access statistics are updated.  hash chain may have
8557  *       been reordered.
8558  *
8559  * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8560  *       asynchronous hash chain reordering operation to finish, or
8561  *       in order for us to perform an asynchronous chain reordering.
8562  *
8563  * @note Hash chain reorderings occur when the access count for the
8564  *       volume object being looked up exceeds the sum of the previous
8565  *       node's (the node ahead of it in the hash chain linked list)
8566  *       access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
8567  *
8568  * @note For DAFS, the hint parameter allows us to short-circuit if the
8569  *       cacheCheck fields match between the hash chain head and the
8570  *       hint volume object.
8571  */
8572 Volume *
8573 VLookupVolume_r(Error * ec, VolumeId volumeId, Volume * hint)
8574 {
8575     int looks = 0;
8576     Volume * vp, *np;
8577 #ifdef AFS_DEMAND_ATTACH_FS
8578     Volume *pp;
8579 #endif
8580     VolumeHashChainHead * head;
8581     *ec = 0;
8582
8583     head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
8584
8585 #ifdef AFS_DEMAND_ATTACH_FS
8586     /* wait for the hash chain to become available */
8587     VHashWait_r(head);
8588
8589     /* check to see if we can short circuit without walking the hash chain */
8590     if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
8591         IncUInt64(&hint->stats.hash_short_circuits);
8592         return hint;
8593     }
8594 #endif /* AFS_DEMAND_ATTACH_FS */
8595
8596     /* someday we need to either do per-chain locks, RWlocks,
8597      * or both for volhash access.
8598      * (and move to a data structure with better cache locality) */
8599
8600     /* search the chain for this volume id */
8601     for(queue_Scan(head, vp, np, Volume)) {
8602         looks++;
8603         if (vp->hashid == volumeId) {
8604             break;
8605         }
8606     }
8607
8608     if (queue_IsEnd(head, vp)) {
8609         vp = NULL;
8610     }
8611
8612 #ifdef AFS_DEMAND_ATTACH_FS
8613     /* update hash chain statistics */
8614     {
8615         afs_uint64 lks;
8616         FillInt64(lks, 0, looks);
8617         AddUInt64(head->looks, lks, &head->looks);
8618         AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
8619         IncUInt64(&head->gets);
8620     }
8621
8622     if (vp) {
8623         afs_uint64 thresh;
8624         IncUInt64(&vp->stats.hash_lookups);
8625
8626         /* for demand attach fileserver, we permit occasional hash chain reordering
8627          * so that frequently looked up volumes move towards the head of the chain */
8628         pp = queue_Prev(vp, Volume);
8629         if (!queue_IsEnd(head, pp)) {
8630             FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
8631             AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
8632             if (GEInt64(vp->stats.hash_lookups, thresh)) {
8633                 VReorderHash_r(head, pp, vp);
8634             }
8635         }
8636
8637         /* update the short-circuit cache check */
8638         vp->chainCacheCheck = head->cacheCheck;
8639     }
8640 #endif /* AFS_DEMAND_ATTACH_FS */
8641
8642     return vp;
8643 }
8644
8645 #ifdef AFS_DEMAND_ATTACH_FS
8646 /* perform volume hash chain reordering.
8647  *
8648  * advance a subchain beginning at vp ahead of
8649  * the adjacent subchain ending at pp */
8650 static void
8651 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
8652 {
8653     Volume *tp, *np, *lp;
8654     afs_uint64 move_thresh;
8655
8656     /* this should never be called if the chain is already busy, so
8657      * no need to wait for other exclusive chain ops to finish */
8658
8659     /* this is a rather heavy set of operations,
8660      * so let's set the chain busy flag and drop
8661      * the vol_glock */
8662     VHashBeginExclusive_r(head);
8663     VOL_UNLOCK;
8664
8665     /* scan forward in the chain from vp looking for the last element
8666      * in the chain we want to advance */
8667     FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
8668     AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
8669     for(queue_ScanFrom(head, vp, tp, np, Volume)) {
8670         if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
8671             break;
8672         }
8673     }
8674     lp = queue_Prev(tp, Volume);
8675
8676     /* scan backwards from pp to determine where to splice and
8677      * insert the subchain we're advancing */
8678     for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
8679         if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
8680             break;
8681         }
8682     }
8683     tp = queue_Next(tp, Volume);
8684
8685     /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
8686     queue_MoveChainBefore(tp,vp,lp);
8687
8688     VOL_LOCK;
8689     IncUInt64(&VStats.hash_reorders);
8690     head->cacheCheck++;
8691     IncUInt64(&head->reorders);
8692
8693     /* wake up any threads waiting for the hash chain */
8694     VHashEndExclusive_r(head);
8695 }
8696
8697
8698 /* demand-attach fs volume hash
8699  * asynchronous exclusive operations */
8700
8701 /**
8702  * begin an asynchronous exclusive operation on a volume hash chain.
8703  *
8704  * @param[in] head   pointer to volume hash chain head object
8705  *
8706  * @pre VOL_LOCK held.  hash chain is quiescent.
8707  *
8708  * @post hash chain marked busy.
8709  *
8710  * @note this interface is used in conjunction with VHashEndExclusive_r and
8711  *       VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8712  *       volume hash chain.  Its main use case is hash chain reordering, which
8713  *       has the potential to be a highly latent operation.
8714  *
8715  * @see VHashEndExclusive_r
8716  * @see VHashWait_r
8717  *
8718  * @note DAFS only
8719  *
8720  * @internal volume package internal use only.
8721  */
8722 static void
8723 VHashBeginExclusive_r(VolumeHashChainHead * head)
8724 {
8725     opr_Assert(head->busy == 0);
8726     head->busy = 1;
8727 }
8728
8729 /**
8730  * relinquish exclusive ownership of a volume hash chain.
8731  *
8732  * @param[in] head   pointer to volume hash chain head object
8733  *
8734  * @pre VOL_LOCK held.  thread owns the hash chain exclusively.
8735  *
8736  * @post hash chain is marked quiescent.  threads awaiting use of
8737  *       chain are awakened.
8738  *
8739  * @see VHashBeginExclusive_r
8740  * @see VHashWait_r
8741  *
8742  * @note DAFS only
8743  *
8744  * @internal volume package internal use only.
8745  */
8746 static void
8747 VHashEndExclusive_r(VolumeHashChainHead * head)
8748 {
8749     opr_Assert(head->busy);
8750     head->busy = 0;
8751     opr_cv_broadcast(&head->chain_busy_cv);
8752 }
8753
8754 /**
8755  * wait for all asynchronous operations on a hash chain to complete.
8756  *
8757  * @param[in] head   pointer to volume hash chain head object
8758  *
8759  * @pre VOL_LOCK held.
8760  *
8761  * @post hash chain object is quiescent.
8762  *
8763  * @see VHashBeginExclusive_r
8764  * @see VHashEndExclusive_r
8765  *
8766  * @note DAFS only
8767  *
8768  * @note This interface should be called before any attempt to
8769  *       traverse the hash chain.  It is permissible for a thread
8770  *       to gain exclusive access to the chain, and then perform
8771  *       latent operations on the chain asynchronously wrt the
8772  *       VOL_LOCK.
8773  *
8774  * @warning if waiting is necessary, VOL_LOCK is dropped
8775  *
8776  * @internal volume package internal use only.
8777  */
8778 static void
8779 VHashWait_r(VolumeHashChainHead * head)
8780 {
8781     while (head->busy) {
8782         VOL_CV_WAIT(&head->chain_busy_cv);
8783     }
8784 }
8785 #endif /* AFS_DEMAND_ATTACH_FS */
8786
8787
8788 /***************************************************/
8789 /* Volume by Partition List routines               */
8790 /***************************************************/
8791
8792 /*
8793  * demand attach fileserver adds a
8794  * linked list of volumes to each
8795  * partition object, thus allowing
8796  * for quick enumeration of all
8797  * volumes on a partition
8798  */
8799
8800 #ifdef AFS_DEMAND_ATTACH_FS
8801 /**
8802  * add a volume to its disk partition VByPList.
8803  *
8804  * @param[in] vp  pointer to volume object
8805  *
8806  * @pre either the disk partition VByPList is owned exclusively
8807  *      by the calling thread, or the list is quiescent and
8808  *      VOL_LOCK is held.
8809  *
8810  * @post volume is added to disk partition VByPList
8811  *
8812  * @note DAFS only
8813  *
8814  * @warning it is the caller's responsibility to ensure list
8815  *          quiescence.
8816  *
8817  * @see VVByPListWait_r
8818  * @see VVByPListBeginExclusive_r
8819  * @see VVByPListEndExclusive_r
8820  *
8821  * @internal volume package internal use only.
8822  */
8823 static void
8824 AddVolumeToVByPList_r(Volume * vp)
8825 {
8826     if (queue_IsNotOnQueue(&vp->vol_list)) {
8827         queue_Append(&vp->partition->vol_list, &vp->vol_list);
8828         V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
8829         vp->partition->vol_list.len++;
8830     }
8831 }
8832
8833 /**
8834  * delete a volume from its disk partition VByPList.
8835  *
8836  * @param[in] vp  pointer to volume object
8837  *
8838  * @pre either the disk partition VByPList is owned exclusively
8839  *      by the calling thread, or the list is quiescent and
8840  *      VOL_LOCK is held.
8841  *
8842  * @post volume is removed from the disk partition VByPList
8843  *
8844  * @note DAFS only
8845  *
8846  * @warning it is the caller's responsibility to ensure list
8847  *          quiescence.
8848  *
8849  * @see VVByPListWait_r
8850  * @see VVByPListBeginExclusive_r
8851  * @see VVByPListEndExclusive_r
8852  *
8853  * @internal volume package internal use only.
8854  */
8855 static void
8856 DeleteVolumeFromVByPList_r(Volume * vp)
8857 {
8858     if (queue_IsOnQueue(&vp->vol_list)) {
8859         queue_Remove(&vp->vol_list);
8860         V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
8861         vp->partition->vol_list.len--;
8862     }
8863 }
8864
8865 /**
8866  * begin an asynchronous exclusive operation on a VByPList.
8867  *
8868  * @param[in] dp   pointer to disk partition object
8869  *
8870  * @pre VOL_LOCK held.  VByPList is quiescent.
8871  *
8872  * @post VByPList marked busy.
8873  *
8874  * @note this interface is used in conjunction with VVByPListEndExclusive_r and
8875  *       VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8876  *       VByPList.
8877  *
8878  * @see VVByPListEndExclusive_r
8879  * @see VVByPListWait_r
8880  *
8881  * @note DAFS only
8882  *
8883  * @internal volume package internal use only.
8884  */
8885 /* take exclusive control over the list */
8886 static void
8887 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
8888 {
8889     opr_Assert(dp->vol_list.busy == 0);
8890     dp->vol_list.busy = 1;
8891 }
8892
8893 /**
8894  * relinquish exclusive ownership of a VByPList.
8895  *
8896  * @param[in] dp   pointer to disk partition object
8897  *
8898  * @pre VOL_LOCK held.  thread owns the VByPList exclusively.
8899  *
8900  * @post VByPList is marked quiescent.  threads awaiting use of
8901  *       the list are awakened.
8902  *
8903  * @see VVByPListBeginExclusive_r
8904  * @see VVByPListWait_r
8905  *
8906  * @note DAFS only
8907  *
8908  * @internal volume package internal use only.
8909  */
8910 static void
8911 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
8912 {
8913     opr_Assert(dp->vol_list.busy);
8914     dp->vol_list.busy = 0;
8915     opr_cv_broadcast(&dp->vol_list.cv);
8916 }
8917
8918 /**
8919  * wait for all asynchronous operations on a VByPList to complete.
8920  *
8921  * @param[in] dp  pointer to disk partition object
8922  *
8923  * @pre VOL_LOCK is held.
8924  *
8925  * @post disk partition's VByP list is quiescent
8926  *
8927  * @note DAFS only
8928  *
8929  * @note This interface should be called before any attempt to
8930  *       traverse the VByPList.  It is permissible for a thread
8931  *       to gain exclusive access to the list, and then perform
8932  *       latent operations on the list asynchronously wrt the
8933  *       VOL_LOCK.
8934  *
8935  * @warning if waiting is necessary, VOL_LOCK is dropped
8936  *
8937  * @see VVByPListEndExclusive_r
8938  * @see VVByPListBeginExclusive_r
8939  *
8940  * @internal volume package internal use only.
8941  */
8942 static void
8943 VVByPListWait_r(struct DiskPartition64 * dp)
8944 {
8945     while (dp->vol_list.busy) {
8946         VOL_CV_WAIT(&dp->vol_list.cv);
8947     }
8948 }
8949 #endif /* AFS_DEMAND_ATTACH_FS */
8950
8951 /***************************************************/
8952 /* Volume Cache Statistics routines                */
8953 /***************************************************/
8954
8955 void
8956 VPrintCacheStats_r(void)
8957 {
8958     struct VnodeClassInfo *vcp;
8959     vcp = &VnodeClassInfo[vLarge];
8960     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);
8961     vcp = &VnodeClassInfo[vSmall];
8962     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);
8963     Log("Volume header cache, %d entries, %"AFS_INT64_FMT" gets, "
8964         "%"AFS_INT64_FMT" replacements\n",
8965         VStats.hdr_cache_size, VStats.hdr_gets, VStats.hdr_loads);
8966 }
8967
8968 void
8969 VPrintCacheStats(void)
8970 {
8971     VOL_LOCK;
8972     VPrintCacheStats_r();
8973     VOL_UNLOCK;
8974 }
8975
8976 #ifdef AFS_DEMAND_ATTACH_FS
8977 static double
8978 UInt64ToDouble(afs_uint64 * x)
8979 {
8980     static double c32 = 4.0 * 1.073741824 * 1000000000.0;
8981     afs_uint32 h, l;
8982     SplitInt64(*x, h, l);
8983     return (((double)h) * c32) + ((double) l);
8984 }
8985
8986 static char *
8987 DoubleToPrintable(double x, char * buf, int len)
8988 {
8989     static double billion = 1000000000.0;
8990     afs_uint32 y[3];
8991
8992     y[0] = (afs_uint32) (x / (billion * billion));
8993     y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
8994     y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
8995
8996     if (y[0]) {
8997         snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
8998     } else if (y[1]) {
8999         snprintf(buf, len, "%d%09d", y[1], y[2]);
9000     } else {
9001         snprintf(buf, len, "%d", y[2]);
9002     }
9003     buf[len-1] = '\0';
9004     return buf;
9005 }
9006
9007 struct VLRUExtStatsEntry {
9008     VolumeId volid;
9009 };
9010
9011 struct VLRUExtStats {
9012     afs_uint32 len;
9013     afs_uint32 used;
9014     struct {
9015         afs_uint32 start;
9016         afs_uint32 len;
9017     } queue_info[VLRU_QUEUE_INVALID];
9018     struct VLRUExtStatsEntry * vec;
9019 };
9020
9021 /**
9022  * add a 256-entry fudge factor onto the vector in case state changes
9023  * out from under us.
9024  */
9025 #define VLRU_EXT_STATS_VEC_LEN_FUDGE   256
9026
9027 /**
9028  * collect extended statistics for the VLRU subsystem.
9029  *
9030  * @param[out] stats  pointer to stats structure to be populated
9031  * @param[in] nvols   number of volumes currently known to exist
9032  *
9033  * @pre VOL_LOCK held
9034  *
9035  * @post stats->vec allocated and populated
9036  *
9037  * @return operation status
9038  *    @retval 0 success
9039  *    @retval 1 failure
9040  */
9041 static int
9042 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
9043 {
9044     afs_uint32 cur, idx, len;
9045     struct rx_queue * qp, * nqp;
9046     Volume * vp;
9047     struct VLRUExtStatsEntry * vec;
9048
9049     len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
9050     vec = stats->vec = calloc(len,
9051                               sizeof(struct VLRUExtStatsEntry));
9052     if (vec == NULL) {
9053         return 1;
9054     }
9055
9056     cur = 0;
9057     for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
9058         VLRU_Wait_r(&volume_LRU.q[idx]);
9059         VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
9060         VOL_UNLOCK;
9061
9062         stats->queue_info[idx].start = cur;
9063
9064         for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
9065             if (cur == len) {
9066                 /* out of space in vec */
9067                 break;
9068             }
9069             vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
9070             vec[cur].volid = vp->hashid;
9071             cur++;
9072         }
9073
9074         stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
9075
9076         VOL_LOCK;
9077         VLRU_EndExclusive_r(&volume_LRU.q[idx]);
9078     }
9079
9080     stats->len = len;
9081     stats->used = cur;
9082     return 0;
9083 }
9084
9085 #define ENUMTOSTRING(en)  #en
9086 #define ENUMCASE(en) \
9087     case en: return ENUMTOSTRING(en)
9088
9089 static char *
9090 vlru_idx_to_string(int idx)
9091 {
9092     switch (idx) {
9093         ENUMCASE(VLRU_QUEUE_NEW);
9094         ENUMCASE(VLRU_QUEUE_MID);
9095         ENUMCASE(VLRU_QUEUE_OLD);
9096         ENUMCASE(VLRU_QUEUE_CANDIDATE);
9097         ENUMCASE(VLRU_QUEUE_HELD);
9098         ENUMCASE(VLRU_QUEUE_INVALID);
9099     default:
9100         return "**UNKNOWN**";
9101     }
9102 }
9103
9104 void
9105 VPrintExtendedCacheStats_r(int flags)
9106 {
9107     int i;
9108     afs_uint32 vol_sum = 0;
9109     struct stats {
9110         double min;
9111         double max;
9112         double sum;
9113         double avg;
9114     };
9115     struct stats looks, gets, reorders, len;
9116     struct stats ch_looks, ch_gets, ch_reorders;
9117     char pr_buf[4][32];
9118     VolumeHashChainHead *head;
9119     Volume *vp, *np;
9120     struct VLRUExtStats vlru_stats;
9121
9122     /* zero out stats */
9123     memset(&looks, 0, sizeof(struct stats));
9124     memset(&gets, 0, sizeof(struct stats));
9125     memset(&reorders, 0, sizeof(struct stats));
9126     memset(&len, 0, sizeof(struct stats));
9127     memset(&ch_looks, 0, sizeof(struct stats));
9128     memset(&ch_gets, 0, sizeof(struct stats));
9129     memset(&ch_reorders, 0, sizeof(struct stats));
9130
9131     for (i = 0; i < VolumeHashTable.Size; i++) {
9132         head = &VolumeHashTable.Table[i];
9133
9134         VHashWait_r(head);
9135         VHashBeginExclusive_r(head);
9136         VOL_UNLOCK;
9137
9138         ch_looks.sum    = UInt64ToDouble(&head->looks);
9139         ch_gets.sum     = UInt64ToDouble(&head->gets);
9140         ch_reorders.sum = UInt64ToDouble(&head->reorders);
9141
9142         /* update global statistics */
9143         {
9144             looks.sum    += ch_looks.sum;
9145             gets.sum     += ch_gets.sum;
9146             reorders.sum += ch_reorders.sum;
9147             len.sum      += (double)head->len;
9148             vol_sum      += head->len;
9149
9150             if (i == 0) {
9151                 len.min      = (double) head->len;
9152                 len.max      = (double) head->len;
9153                 looks.min    = ch_looks.sum;
9154                 looks.max    = ch_looks.sum;
9155                 gets.min     = ch_gets.sum;
9156                 gets.max     = ch_gets.sum;
9157                 reorders.min = ch_reorders.sum;
9158                 reorders.max = ch_reorders.sum;
9159             } else {
9160                 if (((double)head->len) < len.min)
9161                     len.min = (double) head->len;
9162                 if (((double)head->len) > len.max)
9163                     len.max = (double) head->len;
9164                 if (ch_looks.sum < looks.min)
9165                     looks.min = ch_looks.sum;
9166                 else if (ch_looks.sum > looks.max)
9167                     looks.max = ch_looks.sum;
9168                 if (ch_gets.sum < gets.min)
9169                     gets.min = ch_gets.sum;
9170                 else if (ch_gets.sum > gets.max)
9171                     gets.max = ch_gets.sum;
9172                 if (ch_reorders.sum < reorders.min)
9173                     reorders.min = ch_reorders.sum;
9174                 else if (ch_reorders.sum > reorders.max)
9175                     reorders.max = ch_reorders.sum;
9176             }
9177         }
9178
9179         if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
9180             /* compute detailed per-chain stats */
9181             struct stats hdr_loads, hdr_gets;
9182             double v_looks, v_loads, v_gets;
9183
9184             /* initialize stats with data from first element in chain */
9185             vp = queue_First(head, Volume);
9186             v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
9187             v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
9188             v_gets  = UInt64ToDouble(&vp->stats.hdr_gets);
9189             ch_gets.min = ch_gets.max = v_looks;
9190             hdr_loads.min = hdr_loads.max = v_loads;
9191             hdr_gets.min = hdr_gets.max = v_gets;
9192             hdr_loads.sum = hdr_gets.sum = 0;
9193
9194             vp = queue_Next(vp, Volume);
9195
9196             /* pull in stats from remaining elements in chain */
9197             for (queue_ScanFrom(head, vp, vp, np, Volume)) {
9198                 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
9199                 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
9200                 v_gets  = UInt64ToDouble(&vp->stats.hdr_gets);
9201
9202                 hdr_loads.sum += v_loads;
9203                 hdr_gets.sum += v_gets;
9204
9205                 if (v_looks < ch_gets.min)
9206                     ch_gets.min = v_looks;
9207                 else if (v_looks > ch_gets.max)
9208                     ch_gets.max = v_looks;
9209
9210                 if (v_loads < hdr_loads.min)
9211                     hdr_loads.min = v_loads;
9212                 else if (v_loads > hdr_loads.max)
9213                     hdr_loads.max = v_loads;
9214
9215                 if (v_gets < hdr_gets.min)
9216                     hdr_gets.min = v_gets;
9217                 else if (v_gets > hdr_gets.max)
9218                     hdr_gets.max = v_gets;
9219             }
9220
9221             /* compute per-chain averages */
9222             ch_gets.avg = ch_gets.sum / ((double)head->len);
9223             hdr_loads.avg = hdr_loads.sum / ((double)head->len);
9224             hdr_gets.avg = hdr_gets.sum / ((double)head->len);
9225
9226             /* dump per-chain stats */
9227             Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
9228                 i, head->len,
9229                 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9230                 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
9231             Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
9232                 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9233                 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9234                 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9235                 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9236             Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
9237                 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9238                 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9239                 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9240                 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9241             Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
9242                 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
9243                 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
9244                 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
9245                 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
9246         } else if (flags & VOL_STATS_PER_CHAIN) {
9247             /* dump simple per-chain stats */
9248             Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
9249                 i, head->len,
9250                 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9251                 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
9252                 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
9253         }
9254
9255         VOL_LOCK;
9256         VHashEndExclusive_r(head);
9257     }
9258
9259     VOL_UNLOCK;
9260
9261     /* compute global averages */
9262     len.avg      = len.sum      / ((double)VolumeHashTable.Size);
9263     looks.avg    = looks.sum    / ((double)VolumeHashTable.Size);
9264     gets.avg     = gets.sum     / ((double)VolumeHashTable.Size);
9265     reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
9266
9267     /* dump global stats */
9268     Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
9269     Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
9270         DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
9271         DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
9272         DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
9273         DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
9274     Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
9275         DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
9276         DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
9277         DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
9278         DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
9279     Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
9280         DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
9281         DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
9282         DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9283         DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9284     Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
9285         DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
9286         DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
9287         DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
9288         DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
9289
9290     /* print extended disk related statistics */
9291     {
9292         struct DiskPartition64 * diskP;
9293         afs_uint32 vol_count[VOLMAXPARTS+1];
9294         byte part_exists[VOLMAXPARTS+1];
9295         Device id;
9296         int i;
9297
9298         memset(vol_count, 0, sizeof(vol_count));
9299         memset(part_exists, 0, sizeof(part_exists));
9300
9301         VOL_LOCK;
9302
9303         for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
9304             id = diskP->index;
9305             vol_count[id] = diskP->vol_list.len;
9306             part_exists[id] = 1;
9307         }
9308
9309         VOL_UNLOCK;
9310         for (i = 0; i <= VOLMAXPARTS; i++) {
9311             if (part_exists[i]) {
9312                 /* XXX while this is currently safe, it is a violation
9313                  *     of the VGetPartitionById_r interface contract. */
9314                 diskP = VGetPartitionById_r(i, 0);
9315                 if (diskP) {
9316                     Log("Partition %s has %d online volumes\n",
9317                         VPartitionPath(diskP), diskP->vol_list.len);
9318                 }
9319             }
9320         }
9321         VOL_LOCK;
9322     }
9323
9324     /* print extended VLRU statistics */
9325     if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
9326         afs_uint32 idx, cur, lpos;
9327         VolumeId line[5];
9328
9329         VOL_UNLOCK;
9330
9331         Log("VLRU State Dump:\n\n");
9332
9333         for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
9334             Log("\t%s:\n", vlru_idx_to_string(idx));
9335
9336             lpos = 0;
9337             for (cur = vlru_stats.queue_info[idx].start;
9338                  cur < vlru_stats.queue_info[idx].len;
9339                  cur++) {
9340                 line[lpos++] = vlru_stats.vec[cur].volid;
9341                 if (lpos==5) {
9342                     Log("\t\t%u, %u, %u, %u, %u,\n",
9343                         line[0], line[1], line[2], line[3], line[4]);
9344                     lpos = 0;
9345                 }
9346             }
9347
9348             if (lpos) {
9349                 while (lpos < 5) {
9350                     line[lpos++] = 0;
9351                 }
9352                 Log("\t\t%u, %u, %u, %u, %u\n",
9353                     line[0], line[1], line[2], line[3], line[4]);
9354             }
9355             Log("\n");
9356         }
9357
9358         free(vlru_stats.vec);
9359
9360         VOL_LOCK;
9361     }
9362 }
9363
9364 void
9365 VPrintExtendedCacheStats(int flags)
9366 {
9367     VOL_LOCK;
9368     VPrintExtendedCacheStats_r(flags);
9369     VOL_UNLOCK;
9370 }
9371 #endif /* AFS_DEMAND_ATTACH_FS */
9372
9373 afs_int32
9374 VCanScheduleSalvage(void)
9375 {
9376     return vol_opts.canScheduleSalvage;
9377 }
9378
9379 afs_int32
9380 VCanUseFSSYNC(void)
9381 {
9382     return vol_opts.canUseFSSYNC;
9383 }
9384
9385 afs_int32
9386 VCanUseSALVSYNC(void)
9387 {
9388     return vol_opts.canUseSALVSYNC;
9389 }
9390
9391 afs_int32
9392 VCanUnsafeAttach(void)
9393 {
9394     return vol_opts.unsafe_attach;
9395 }