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