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