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