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