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