vol: Allow VAllocVnode of specific vnodes
[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             (V_attachState(vp) == VOL_STATE_GOING_OFFLINE)) {
4049             *ec = VNOVOL;
4050             vp = NULL;
4051             break;
4052         }
4053
4054         /*
4055          * short circuit with VOFFLINE for VOL_STATE_UNATTACHED and
4056          *                    VNOVOL   for VOL_STATE_DELETED
4057          */
4058        if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
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                     break;
4112                 default:
4113                     *ec = VNOVOL;
4114                     endloop = 1;
4115                 }
4116                 if (endloop) {
4117                     vp = NULL;
4118                     break;
4119                 }
4120             }
4121         }
4122
4123         if (VIsSalvaging(vp) || (*ec == VSALVAGING)) {
4124             if (client_ec) {
4125                 /* see CheckVnode() in afsfileprocs.c for an explanation
4126                  * of this error code logic */
4127                 afs_uint32 now = FT_ApproxTime();
4128                 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
4129                     *client_ec = VBUSY;
4130                 } else {
4131                     *client_ec = VRESTARTING;
4132                 }
4133             }
4134             *ec = VSALVAGING;
4135             vp = NULL;
4136             break;
4137         }
4138
4139         if (VIsErrorState(V_attachState(vp))) {
4140             /* make sure we don't take a vp in VOL_STATE_ERROR state and use
4141              * it, or transition it out of that state */
4142             if (!*ec) {
4143                 *ec = VNOVOL;
4144             }
4145             vp = NULL;
4146             break;
4147         }
4148
4149         /*
4150          * this test MUST happen after VAttachVolymeByVp, so vol_op_state is
4151          * not VolOpRunningUnknown (attach2 would have converted it to Online
4152          * or Offline)
4153          */
4154
4155          /* only valid before/during demand attachment */
4156          osi_Assert(!vp->pending_vol_op || vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
4157
4158          /* deny getvolume due to running mutually exclusive vol op */
4159          if (vp->pending_vol_op && vp->pending_vol_op->vol_op_state==FSSYNC_VolOpRunningOffline) {
4160            /*
4161             * volume cannot remain online during this volume operation.
4162             * notify client.
4163             */
4164            if (vp->specialStatus) {
4165                /*
4166                 * special status codes outrank normal VOFFLINE code
4167                 */
4168                *ec = vp->specialStatus;
4169                if (client_ec) {
4170                    *client_ec = vp->specialStatus;
4171                }
4172            } else {
4173                if (client_ec) {
4174                    /* see CheckVnode() in afsfileprocs.c for an explanation
4175                     * of this error code logic */
4176                    afs_uint32 now = FT_ApproxTime();
4177                    if ((vp->stats.last_vol_op + (10 * 60)) >= now) {
4178                        *client_ec = VBUSY;
4179                    } else {
4180                        *client_ec = VRESTARTING;
4181                    }
4182                }
4183                *ec = VOFFLINE;
4184            }
4185            VChangeState_r(vp, VOL_STATE_UNATTACHED);
4186            FreeVolumeHeader(vp);
4187            vp = NULL;
4188            break;
4189         }
4190 #endif /* AFS_DEMAND_ATTACH_FS */
4191
4192         LoadVolumeHeader(ec, vp);
4193         if (*ec) {
4194             VGET_CTR_INC(V6);
4195             /* Only log the error if it was a totally unexpected error.  Simply
4196              * a missing inode is likely to be caused by the volume being deleted */
4197             if (errno != ENXIO || LogLevel)
4198                 Log("Volume %u: couldn't reread volume header\n",
4199                     vp->hashid);
4200 #ifdef AFS_DEMAND_ATTACH_FS
4201             if (VCanScheduleSalvage()) {
4202                 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0 /*flags*/);
4203             } else {
4204                 FreeVolume(vp);
4205                 vp = NULL;
4206             }
4207 #else /* AFS_DEMAND_ATTACH_FS */
4208             FreeVolume(vp);
4209             vp = NULL;
4210 #endif /* AFS_DEMAND_ATTACH_FS */
4211             break;
4212         }
4213
4214         VGET_CTR_INC(V7);
4215         if (vp->shuttingDown) {
4216             VGET_CTR_INC(V8);
4217             *ec = VNOVOL;
4218             vp = NULL;
4219             break;
4220         }
4221
4222         if (programType == fileServer) {
4223             VGET_CTR_INC(V9);
4224             if (vp->goingOffline) {
4225                 if (timeout && VTimedOut(timeout)) {
4226                     /* we've timed out; don't wait for the vol */
4227                 } else {
4228                     VGET_CTR_INC(V10);
4229 #ifdef AFS_DEMAND_ATTACH_FS
4230                     /* wait for the volume to go offline */
4231                     if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
4232                         VTimedWaitStateChange_r(vp, timeout, NULL);
4233                     }
4234 #elif defined(AFS_PTHREAD_ENV)
4235                     VOL_CV_TIMEDWAIT(&vol_put_volume_cond, timeout, NULL);
4236 #else /* AFS_PTHREAD_ENV */
4237                     /* LWP has no timed wait, so the caller better not be
4238                      * expecting one */
4239                     osi_Assert(!timeout);
4240                     LWP_WaitProcess(VPutVolume);
4241 #endif /* AFS_PTHREAD_ENV */
4242                     continue;
4243                 }
4244             }
4245             if (vp->specialStatus) {
4246                 VGET_CTR_INC(V11);
4247                 *ec = vp->specialStatus;
4248             } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
4249                 VGET_CTR_INC(V12);
4250                 *ec = VNOVOL;
4251             } else if (V_inUse(vp) == 0 || vp->goingOffline) {
4252                 VGET_CTR_INC(V13);
4253                 *ec = VOFFLINE;
4254             } else {
4255                 VGET_CTR_INC(V14);
4256             }
4257         }
4258         break;
4259     }
4260     VGET_CTR_INC(V15);
4261
4262 #ifdef AFS_DEMAND_ATTACH_FS
4263     /* if no error, bump nUsers */
4264     if (vp) {
4265         vp->nUsers++;
4266         VLRU_UpdateAccess_r(vp);
4267     }
4268     if (rvp) {
4269         VCancelReservation_r(rvp);
4270         rvp = NULL;
4271     }
4272     if (client_ec && !*client_ec) {
4273         *client_ec = *ec;
4274     }
4275 #else /* AFS_DEMAND_ATTACH_FS */
4276     /* if no error, bump nUsers */
4277     if (vp) {
4278         vp->nUsers++;
4279     }
4280     if (client_ec) {
4281         *client_ec = *ec;
4282     }
4283 #endif /* AFS_DEMAND_ATTACH_FS */
4284
4285  not_inited:
4286     osi_Assert(vp || *ec);
4287     return vp;
4288 }
4289
4290
4291 /***************************************************/
4292 /* Volume offline/detach routines                  */
4293 /***************************************************/
4294
4295 /* caller MUST hold a heavyweight ref on vp */
4296 #ifdef AFS_DEMAND_ATTACH_FS
4297 void
4298 VTakeOffline_r(Volume * vp)
4299 {
4300     Error error;
4301
4302     osi_Assert(vp->nUsers > 0);
4303     osi_Assert(programType == fileServer);
4304
4305     VCreateReservation_r(vp);
4306     VWaitExclusiveState_r(vp);
4307
4308     vp->goingOffline = 1;
4309     V_needsSalvaged(vp) = 1;
4310
4311     VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
4312     VCancelReservation_r(vp);
4313 }
4314 #else /* AFS_DEMAND_ATTACH_FS */
4315 void
4316 VTakeOffline_r(Volume * vp)
4317 {
4318     osi_Assert(vp->nUsers > 0);
4319     osi_Assert(programType == fileServer);
4320
4321     vp->goingOffline = 1;
4322     V_needsSalvaged(vp) = 1;
4323 }
4324 #endif /* AFS_DEMAND_ATTACH_FS */
4325
4326 void
4327 VTakeOffline(Volume * vp)
4328 {
4329     VOL_LOCK;
4330     VTakeOffline_r(vp);
4331     VOL_UNLOCK;
4332 }
4333
4334 /**
4335  * force a volume offline.
4336  *
4337  * @param[in] vp     volume object pointer
4338  * @param[in] flags  flags (see note below)
4339  *
4340  * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
4341  *       used when VUpdateVolume_r needs to call VForceOffline_r
4342  *       (which in turn would normally call VUpdateVolume_r)
4343  *
4344  * @see VUpdateVolume_r
4345  *
4346  * @pre VOL_LOCK must be held.
4347  *      for DAFS, caller must hold ref.
4348  *
4349  * @note for DAFS, it _is safe_ to call this function from an
4350  *       exclusive state
4351  *
4352  * @post needsSalvaged flag is set.
4353  *       for DAFS, salvage is requested.
4354  *       no further references to the volume through the volume
4355  *       package will be honored.
4356  *       all file descriptor and vnode caches are invalidated.
4357  *
4358  * @warning this is a heavy-handed interface.  it results in
4359  *          a volume going offline regardless of the current
4360  *          reference count state.
4361  *
4362  * @internal  volume package internal use only
4363  */
4364 void
4365 VForceOffline_r(Volume * vp, int flags)
4366 {
4367     Error error;
4368     if (!V_inUse(vp)) {
4369 #ifdef AFS_DEMAND_ATTACH_FS
4370         VChangeState_r(vp, VOL_STATE_ERROR);
4371 #endif
4372         return;
4373     }
4374
4375     strcpy(V_offlineMessage(vp),
4376            "Forced offline due to internal error: volume needs to be salvaged");
4377     Log("Volume %u forced offline:  it needs salvaging!\n", V_id(vp));
4378
4379     V_inUse(vp) = 0;
4380     vp->goingOffline = 0;
4381     V_needsSalvaged(vp) = 1;
4382     if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
4383         VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
4384     }
4385
4386 #ifdef AFS_DEMAND_ATTACH_FS
4387     VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0 /*flags*/);
4388 #endif /* AFS_DEMAND_ATTACH_FS */
4389
4390 #ifdef AFS_PTHREAD_ENV
4391     CV_BROADCAST(&vol_put_volume_cond);
4392 #else /* AFS_PTHREAD_ENV */
4393     LWP_NoYieldSignal(VPutVolume);
4394 #endif /* AFS_PTHREAD_ENV */
4395
4396     VReleaseVolumeHandles_r(vp);
4397 }
4398
4399 /**
4400  * force a volume offline.
4401  *
4402  * @param[in] vp  volume object pointer
4403  *
4404  * @see VForceOffline_r
4405  */
4406 void
4407 VForceOffline(Volume * vp)
4408 {
4409     VOL_LOCK;
4410     VForceOffline_r(vp, 0);
4411     VOL_UNLOCK;
4412 }
4413
4414 /**
4415  * Iterate over the RX calls associated with a volume, and interrupt them.
4416  *
4417  * @param[in] vp The volume whose RX calls we want to scan
4418  *
4419  * @pre VOL_LOCK held
4420  */
4421 static void
4422 VScanCalls_r(struct Volume *vp)
4423 {
4424     struct VCallByVol *cbv, *ncbv;
4425     afs_int32 err;
4426 #ifdef AFS_DEMAND_ATTACH_FS
4427     VolState state_save;
4428 #endif
4429
4430     if (queue_IsEmpty(&vp->rx_call_list))
4431         return; /* no calls to interrupt */
4432     if (!vol_opts.interrupt_rxcall)
4433         return; /* we have no function with which to interrupt calls */
4434     err = VIsGoingOffline_r(vp);
4435     if (!err)
4436         return; /* we're not going offline anymore */
4437
4438 #ifdef AFS_DEMAND_ATTACH_FS
4439     VWaitExclusiveState_r(vp);
4440     state_save = VChangeState_r(vp, VOL_STATE_SCANNING_RXCALLS);
4441     VOL_UNLOCK;
4442 #endif /* AFS_DEMAND_ATTACH_FS */
4443
4444     for(queue_Scan(&vp->rx_call_list, cbv, ncbv, VCallByVol)) {
4445         if (LogLevel > 0) {
4446             struct rx_peer *peer;
4447             char hoststr[16];
4448             peer = rx_PeerOf(rx_ConnectionOf(cbv->call));
4449
4450             Log("Offlining volume %lu while client %s:%u is trying to read "
4451                 "from it; kicking client off with error %ld\n",
4452                 (long unsigned) vp->hashid,
4453                 afs_inet_ntoa_r(rx_HostOf(peer), hoststr),
4454                 (unsigned) ntohs(rx_PortOf(peer)),
4455                 (long) err);
4456         }
4457         (*vol_opts.interrupt_rxcall) (cbv->call, err);
4458     }
4459
4460 #ifdef AFS_DEMAND_ATTACH_FS
4461     VOL_LOCK;
4462     VChangeState_r(vp, state_save);
4463 #endif /* AFS_DEMAND_ATTACH_FS */
4464 }
4465
4466 #ifdef AFS_DEMAND_ATTACH_FS
4467 /**
4468  * Wait for a vp to go offline.
4469  *
4470  * @param[out] ec 1 if a salvage on the volume has been requested and
4471  *                salvok == 0, 0 otherwise
4472  * @param[in] vp  The volume to wait for
4473  * @param[in] salvok  If 0, we return immediately with *ec = 1 if the volume
4474  *                    has been requested to salvage. Otherwise we keep waiting
4475  *                    until the volume has gone offline.
4476  *
4477  * @pre VOL_LOCK held
4478  * @pre caller holds a lightweight ref on vp
4479  *
4480  * @note DAFS only
4481  */
4482 static void
4483 VWaitForOfflineByVp_r(Error *ec, struct Volume *vp, int salvok)
4484 {
4485     struct timespec timeout_ts;
4486     const struct timespec *ts;
4487     int timedout = 0;
4488
4489     ts = VOfflineTimeout(&timeout_ts);
4490
4491     *ec = 0;
4492
4493     while (!VIsOfflineState(V_attachState(vp)) && !timedout) {
4494         if (!salvok && vp->salvage.requested) {
4495             *ec = 1;
4496             return;
4497         }
4498         VTimedWaitStateChange_r(vp, ts, &timedout);
4499     }
4500     if (!timedout) {
4501         /* we didn't time out, so the volume must be offline, so we're done */
4502         return;
4503     }
4504
4505     /* If we got here, we timed out waiting for the volume to go offline.
4506      * Kick off the accessing RX calls and wait again */
4507
4508     VScanCalls_r(vp);
4509
4510     while (!VIsOfflineState(V_attachState(vp))) {
4511         if (!salvok && vp->salvage.requested) {
4512             *ec = 1;
4513             return;
4514         }
4515
4516         VWaitStateChange_r(vp);
4517     }
4518 }
4519
4520 #else /* AFS_DEMAND_ATTACH_FS */
4521
4522 /**
4523  * Wait for a volume to go offline.
4524  *
4525  * @pre VOL_LOCK held
4526  *
4527  * @note non-DAFS only (for DAFS, use @see WaitForOfflineByVp_r)
4528  */
4529 static void
4530 VWaitForOffline_r(Error *ec, VolumeId volid)
4531 {
4532     struct Volume *vp;
4533     const struct timespec *ts;
4534 #ifdef AFS_PTHREAD_ENV
4535     struct timespec timeout_ts;
4536 #endif
4537
4538     ts = VOfflineTimeout(&timeout_ts);
4539
4540     vp = GetVolume(ec, NULL, volid, NULL, ts);
4541     if (!vp) {
4542         /* error occurred so bad that we can't even get a vp; we have no
4543          * information on the vol so we don't know whether to wait, so just
4544          * return */
4545         return;
4546     }
4547     if (!VIsGoingOffline_r(vp)) {
4548         /* volume is no longer going offline, so we're done */
4549         VPutVolume_r(vp);
4550         return;
4551     }
4552
4553     /* If we got here, we timed out waiting for the volume to go offline.
4554      * Kick off the accessing RX calls and wait again */
4555
4556     VScanCalls_r(vp);
4557     VPutVolume_r(vp);
4558     vp = NULL;
4559
4560     vp = VGetVolume_r(ec, volid);
4561     if (vp) {
4562         /* In case it was reattached... */
4563         VPutVolume_r(vp);
4564     }
4565 }
4566 #endif /* !AFS_DEMAND_ATTACH_FS */
4567
4568 /* The opposite of VAttachVolume.  The volume header is written to disk, with
4569    the inUse bit turned off.  A copy of the header is maintained in memory,
4570    however (which is why this is VOffline, not VDetach).
4571  */
4572 void
4573 VOffline_r(Volume * vp, char *message)
4574 {
4575     Error error;
4576 #ifndef AFS_DEMAND_ATTACH_FS
4577     VolumeId vid = V_id(vp);
4578 #endif
4579
4580     osi_Assert(programType != volumeUtility && programType != volumeServer);
4581     if (!V_inUse(vp)) {
4582         VPutVolume_r(vp);
4583         return;
4584     }
4585     if (V_offlineMessage(vp)[0] == '\0')
4586         strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4587     V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4588
4589     vp->goingOffline = 1;
4590 #ifdef AFS_DEMAND_ATTACH_FS
4591     VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4592     VCreateReservation_r(vp);
4593     VPutVolume_r(vp);
4594     VWaitForOfflineByVp_r(&error, vp, 1);
4595     VCancelReservation_r(vp);
4596 #else /* AFS_DEMAND_ATTACH_FS */
4597     VPutVolume_r(vp);
4598     VWaitForOffline_r(&error, vid);
4599 #endif /* AFS_DEMAND_ATTACH_FS */
4600 }
4601
4602 #ifdef AFS_DEMAND_ATTACH_FS
4603 /**
4604  * Take a volume offline in order to perform a volume operation.
4605  *
4606  * @param[inout] ec       address in which to store error code
4607  * @param[in]    vp       volume object pointer
4608  * @param[in]    message  volume offline status message
4609  *
4610  * @pre
4611  *    - VOL_LOCK is held
4612  *    - caller MUST hold a heavyweight ref on vp
4613  *
4614  * @post
4615  *    - volume is taken offline
4616  *    - if possible, volume operation is promoted to running state
4617  *    - on failure, *ec is set to nonzero
4618  *
4619  * @note Although this function does not return any value, it may
4620  *       still fail to promote our pending volume operation to
4621  *       a running state.  Any caller MUST check the value of *ec,
4622  *       and MUST NOT blindly assume success.
4623  *
4624  * @warning if the caller does not hold a lightweight ref on vp,
4625  *          then it MUST NOT reference vp after this function
4626  *          returns to the caller.
4627  *
4628  * @internal volume package internal use only
4629  */
4630 void
4631 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
4632 {
4633     int salvok = 1;
4634     osi_Assert(vp->pending_vol_op);
4635     if (!V_inUse(vp)) {
4636         VPutVolume_r(vp);
4637         *ec = 1;
4638         return;
4639     }
4640     if (V_offlineMessage(vp)[0] == '\0')
4641         strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
4642     V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
4643
4644     vp->goingOffline = 1;
4645     VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
4646     VCreateReservation_r(vp);
4647     VPutVolume_r(vp);
4648
4649     if (vp->pending_vol_op->com.programType != salvageServer) {
4650         /* do not give corrupted volumes to the volserver */
4651         salvok = 0;
4652     }
4653
4654     *ec = 0;
4655     VWaitForOfflineByVp_r(ec, vp, salvok);
4656
4657     VCancelReservation_r(vp);
4658 }
4659 #endif /* AFS_DEMAND_ATTACH_FS */
4660
4661 void
4662 VOffline(Volume * vp, char *message)
4663 {
4664     VOL_LOCK;
4665     VOffline_r(vp, message);
4666     VOL_UNLOCK;
4667 }
4668
4669 /* This gets used for the most part by utility routines that don't want
4670  * to keep all the volume headers around.  Generally, the file server won't
4671  * call this routine, because then the offline message in the volume header
4672  * (or other information) won't be available to clients. For NAMEI, also
4673  * close the file handles.  However, the fileserver does call this during
4674  * an attach following a volume operation.
4675  */
4676 void
4677 VDetachVolume_r(Error * ec, Volume * vp)
4678 {
4679 #ifdef FSSYNC_BUILD_CLIENT
4680     VolumeId volume;
4681     struct DiskPartition64 *tpartp;
4682     int notifyServer = 0;
4683     int  useDone = FSYNC_VOL_ON;
4684
4685     if (VCanUseFSSYNC()) {
4686         notifyServer = vp->needsPutBack;
4687         if (V_destroyMe(vp) == DESTROY_ME)
4688             useDone = FSYNC_VOL_LEAVE_OFF;
4689 # ifdef AFS_DEMAND_ATTACH_FS
4690         else if (!V_blessed(vp) || !V_inService(vp))
4691             useDone = FSYNC_VOL_LEAVE_OFF;
4692 # endif
4693     }
4694 # ifdef AFS_DEMAND_ATTACH_FS
4695     if (V_needsSalvaged(vp)) {
4696         notifyServer = 0;
4697         VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, 0);
4698     }
4699 # endif
4700     tpartp = vp->partition;
4701     volume = V_id(vp);
4702 #endif /* FSSYNC_BUILD_CLIENT */
4703
4704     *ec = 0;                    /* always "succeeds" */
4705     DeleteVolumeFromHashTable(vp);
4706     vp->shuttingDown = 1;
4707 #ifdef AFS_DEMAND_ATTACH_FS
4708     DeleteVolumeFromVByPList_r(vp);
4709     VLRU_Delete_r(vp);
4710     VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
4711 #else
4712     if (programType != fileServer)
4713         V_inUse(vp) = 0;
4714 #endif /* AFS_DEMAND_ATTACH_FS */
4715     VPutVolume_r(vp);
4716     /* Will be detached sometime in the future--this is OK since volume is offline */
4717
4718     /* XXX the following code should really be moved to VCheckDetach() since the volume
4719      * is not technically detached until the refcounts reach zero
4720      */
4721 #ifdef FSSYNC_BUILD_CLIENT
4722     if (VCanUseFSSYNC() && notifyServer) {
4723         if (notifyServer == VOL_PUTBACK_DELETE) {
4724             /* Only send FSYNC_VOL_DONE if the volume was actually deleted.
4725              * volserver code will set needsPutBack to VOL_PUTBACK_DELETE
4726              * to signify a deleted volume. */
4727             useDone = FSYNC_VOL_DONE;
4728         }
4729         /*
4730          * Note:  The server is not notified in the case of a bogus volume
4731          * explicitly to make it possible to create a volume, do a partial
4732          * restore, then abort the operation without ever putting the volume
4733          * online.  This is essential in the case of a volume move operation
4734          * between two partitions on the same server.  In that case, there
4735          * would be two instances of the same volume, one of them bogus,
4736          * which the file server would attempt to put on line
4737          */
4738         FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
4739         /* XXX this code path is only hit by volume utilities, thus
4740          * V_BreakVolumeCallbacks will always be NULL.  if we really
4741          * want to break callbacks in this path we need to use FSYNC_VolOp() */
4742 #ifdef notdef
4743         /* Dettaching it so break all callbacks on it */
4744         if (V_BreakVolumeCallbacks) {
4745             Log("volume %u detached; breaking all call backs\n", volume);
4746             (*V_BreakVolumeCallbacks) (volume);
4747         }
4748 #endif
4749     }
4750 #endif /* FSSYNC_BUILD_CLIENT */
4751 }
4752
4753 void
4754 VDetachVolume(Error * ec, Volume * vp)
4755 {
4756     VOL_LOCK;
4757     VDetachVolume_r(ec, vp);
4758     VOL_UNLOCK;
4759 }
4760
4761
4762 /***************************************************/
4763 /* Volume fd/inode handle closing routines         */
4764 /***************************************************/
4765
4766 /* For VDetachVolume, we close all cached file descriptors, but keep
4767  * the Inode handles in case we need to read from a busy volume.
4768  */
4769 /* for demand attach, caller MUST hold ref count on vp */
4770 static void
4771 VCloseVolumeHandles_r(Volume * vp)
4772 {
4773 #ifdef AFS_DEMAND_ATTACH_FS
4774     VolState state_save;
4775
4776     state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
4777
4778     VOL_UNLOCK;
4779 #endif
4780
4781     DFlushVolume(vp->hashid);
4782
4783 #ifdef AFS_DEMAND_ATTACH_FS
4784     VOL_LOCK;
4785 #endif
4786
4787     /* DAFS: VCloseVnodeFiles_r drops the glock internally */
4788     VCloseVnodeFiles_r(vp);
4789
4790 #ifdef AFS_DEMAND_ATTACH_FS
4791     VOL_UNLOCK;
4792 #endif
4793
4794     /* Too time consuming and unnecessary for the volserver */
4795     if (programType == fileServer) {
4796         IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4797         IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4798         IH_CONDSYNC(vp->diskDataHandle);
4799 #ifdef AFS_NT40_ENV
4800         IH_CONDSYNC(vp->linkHandle);
4801 #endif /* AFS_NT40_ENV */
4802     }
4803
4804     IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
4805     IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
4806     IH_REALLYCLOSE(vp->diskDataHandle);
4807     IH_REALLYCLOSE(vp->linkHandle);
4808
4809 #ifdef AFS_DEMAND_ATTACH_FS
4810     if ((V_attachFlags(vp) & VOL_LOCKED)) {
4811         VUnlockVolume(vp);
4812     }
4813
4814     VOL_LOCK;
4815     VChangeState_r(vp, state_save);
4816 #endif
4817 }
4818
4819 /* For both VForceOffline and VOffline, we close all relevant handles.
4820  * For VOffline, if we re-attach the volume, the files may possible be
4821  * different than before.
4822  */
4823 /* for demand attach, caller MUST hold a ref count on vp */
4824 static void
4825 VReleaseVolumeHandles_r(Volume * vp)
4826 {
4827 #ifdef AFS_DEMAND_ATTACH_FS
4828     VolState state_save;
4829
4830     state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
4831
4832     VOL_UNLOCK;
4833 #endif
4834
4835     DFlushVolume(vp->hashid);
4836
4837 #ifdef AFS_DEMAND_ATTACH_FS
4838     VOL_LOCK;
4839 #endif
4840
4841     VReleaseVnodeFiles_r(vp); /* DAFS: releases the glock internally */
4842
4843 #ifdef AFS_DEMAND_ATTACH_FS
4844     VOL_UNLOCK;
4845 #endif
4846
4847     /* Too time consuming and unnecessary for the volserver */
4848     if (programType == fileServer) {
4849         IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
4850         IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
4851         IH_CONDSYNC(vp->diskDataHandle);
4852 #ifdef AFS_NT40_ENV
4853         IH_CONDSYNC(vp->linkHandle);
4854 #endif /* AFS_NT40_ENV */
4855     }
4856
4857     IH_RELEASE(vp->vnodeIndex[vLarge].handle);
4858     IH_RELEASE(vp->vnodeIndex[vSmall].handle);
4859     IH_RELEASE(vp->diskDataHandle);
4860     IH_RELEASE(vp->linkHandle);
4861
4862 #ifdef AFS_DEMAND_ATTACH_FS
4863     if ((V_attachFlags(vp) & VOL_LOCKED)) {
4864         VUnlockVolume(vp);
4865     }
4866
4867     VOL_LOCK;
4868     VChangeState_r(vp, state_save);
4869 #endif
4870 }
4871
4872
4873 /***************************************************/
4874 /* Volume write and fsync routines                 */
4875 /***************************************************/
4876
4877 void
4878 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
4879 {
4880 #ifdef AFS_DEMAND_ATTACH_FS
4881     VolState state_save;
4882
4883     if (flags & VOL_UPDATE_WAIT) {
4884         VCreateReservation_r(vp);
4885         VWaitExclusiveState_r(vp);
4886     }
4887 #endif
4888
4889     *ec = 0;
4890     if (programType == fileServer)
4891         V_uniquifier(vp) =
4892             (V_inUse(vp) ? V_nextVnodeUnique(vp) +
4893              200 : V_nextVnodeUnique(vp));
4894
4895 #ifdef AFS_DEMAND_ATTACH_FS
4896     state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4897     VOL_UNLOCK;
4898 #endif
4899
4900     WriteVolumeHeader_r(ec, vp);
4901
4902 #ifdef AFS_DEMAND_ATTACH_FS
4903     VOL_LOCK;
4904     VChangeState_r(vp, state_save);
4905     if (flags & VOL_UPDATE_WAIT) {
4906         VCancelReservation_r(vp);
4907     }
4908 #endif
4909
4910     if (*ec) {
4911         Log("VUpdateVolume: error updating volume header, volume %u (%s)\n",
4912             V_id(vp), V_name(vp));
4913         /* try to update on-disk header,
4914          * while preventing infinite recursion */
4915         if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
4916             VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
4917         }
4918     }
4919 }
4920
4921 void
4922 VUpdateVolume(Error * ec, Volume * vp)
4923 {
4924     VOL_LOCK;
4925     VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4926     VOL_UNLOCK;
4927 }
4928
4929 void
4930 VSyncVolume_r(Error * ec, Volume * vp, int flags)
4931 {
4932     FdHandle_t *fdP;
4933     int code;
4934 #ifdef AFS_DEMAND_ATTACH_FS
4935     VolState state_save;
4936 #endif
4937
4938     if (flags & VOL_SYNC_WAIT) {
4939         VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
4940     } else {
4941         VUpdateVolume_r(ec, vp, 0);
4942     }
4943     if (!*ec) {
4944 #ifdef AFS_DEMAND_ATTACH_FS
4945         state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
4946         VOL_UNLOCK;
4947 #endif
4948         fdP = IH_OPEN(V_diskDataHandle(vp));
4949         osi_Assert(fdP != NULL);
4950         code = FDH_SYNC(fdP);
4951         osi_Assert(code == 0);
4952         FDH_CLOSE(fdP);
4953 #ifdef AFS_DEMAND_ATTACH_FS
4954         VOL_LOCK;
4955         VChangeState_r(vp, state_save);
4956 #endif
4957     }
4958 }
4959
4960 void
4961 VSyncVolume(Error * ec, Volume * vp)
4962 {
4963     VOL_LOCK;
4964     VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
4965     VOL_UNLOCK;
4966 }
4967
4968
4969 /***************************************************/
4970 /* Volume dealloaction routines                    */
4971 /***************************************************/
4972
4973 #ifdef AFS_DEMAND_ATTACH_FS
4974 static void
4975 FreeVolume(Volume * vp)
4976 {
4977     /* free the heap space, iff it's safe.
4978      * otherwise, pull it out of the hash table, so it
4979      * will get deallocated when all refs to it go away */
4980     if (!VCheckFree(vp)) {
4981         DeleteVolumeFromHashTable(vp);
4982         DeleteVolumeFromVByPList_r(vp);
4983
4984         /* make sure we invalidate the header cache entry */
4985         FreeVolumeHeader(vp);
4986     }
4987 }
4988 #endif /* AFS_DEMAND_ATTACH_FS */
4989
4990 static void
4991 ReallyFreeVolume(Volume * vp)
4992 {
4993     int i;
4994     if (!vp)
4995         return;
4996 #ifdef AFS_DEMAND_ATTACH_FS
4997     /* debug */
4998     VChangeState_r(vp, VOL_STATE_FREED);
4999     if (vp->pending_vol_op)
5000         free(vp->pending_vol_op);
5001 #endif /* AFS_DEMAND_ATTACH_FS */
5002     for (i = 0; i < nVNODECLASSES; i++)
5003         if (vp->vnodeIndex[i].bitmap)
5004             free(vp->vnodeIndex[i].bitmap);
5005     FreeVolumeHeader(vp);
5006 #ifndef AFS_DEMAND_ATTACH_FS
5007     DeleteVolumeFromHashTable(vp);
5008 #endif /* AFS_DEMAND_ATTACH_FS */
5009     free(vp);
5010 }
5011
5012 /* check to see if we should shutdown this volume
5013  * returns 1 if volume was freed, 0 otherwise */
5014 #ifdef AFS_DEMAND_ATTACH_FS
5015 static int
5016 VCheckDetach(Volume * vp)
5017 {
5018     int ret = 0;
5019     Error ec = 0;
5020
5021     if (vp->nUsers || vp->nWaiters)
5022         return ret;
5023
5024     if (vp->shuttingDown) {
5025         ret = 1;
5026         if ((programType != fileServer) &&
5027             (V_inUse(vp) == programType) &&
5028             ((V_checkoutMode(vp) == V_VOLUPD) ||
5029              (V_checkoutMode(vp) == V_SECRETLY) ||
5030              ((V_checkoutMode(vp) == V_CLONE) &&
5031               (VolumeWriteable(vp))))) {
5032             V_inUse(vp) = 0;
5033             VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5034             if (ec) {
5035                 Log("VCheckDetach: volume header update for volume %u "
5036                     "failed with errno %d\n", vp->hashid, errno);
5037             }
5038         }
5039         VReleaseVolumeHandles_r(vp);
5040         VCheckSalvage(vp);
5041         ReallyFreeVolume(vp);
5042         if (programType == fileServer) {
5043             CV_BROADCAST(&vol_put_volume_cond);
5044         }
5045     }
5046     return ret;
5047 }
5048 #else /* AFS_DEMAND_ATTACH_FS */
5049 static int
5050 VCheckDetach(Volume * vp)
5051 {
5052     int ret = 0;
5053     Error ec = 0;
5054
5055     if (vp->nUsers)
5056         return ret;
5057
5058     if (vp->shuttingDown) {
5059         ret = 1;
5060         if ((programType != fileServer) &&
5061             (V_inUse(vp) == programType) &&
5062             ((V_checkoutMode(vp) == V_VOLUPD) ||
5063              (V_checkoutMode(vp) == V_SECRETLY) ||
5064              ((V_checkoutMode(vp) == V_CLONE) &&
5065               (VolumeWriteable(vp))))) {
5066             V_inUse(vp) = 0;
5067             VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
5068             if (ec) {
5069                 Log("VCheckDetach: volume header update for volume %u failed with errno %d\n",
5070                     vp->hashid, errno);
5071             }
5072         }
5073         VReleaseVolumeHandles_r(vp);
5074         ReallyFreeVolume(vp);
5075         if (programType == fileServer) {
5076 #if defined(AFS_PTHREAD_ENV)
5077             CV_BROADCAST(&vol_put_volume_cond);
5078 #else /* AFS_PTHREAD_ENV */
5079             LWP_NoYieldSignal(VPutVolume);
5080 #endif /* AFS_PTHREAD_ENV */
5081         }
5082     }
5083     return ret;
5084 }
5085 #endif /* AFS_DEMAND_ATTACH_FS */
5086
5087 /* check to see if we should offline this volume
5088  * return 1 if volume went offline, 0 otherwise */
5089 #ifdef AFS_DEMAND_ATTACH_FS
5090 static int
5091 VCheckOffline(Volume * vp)
5092 {
5093     int ret = 0;
5094
5095     if (vp->goingOffline && !vp->nUsers) {
5096         Error error;
5097         osi_Assert(programType == fileServer);
5098         osi_Assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
5099                (V_attachState(vp) != VOL_STATE_FREED) &&
5100                (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
5101                (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
5102                (V_attachState(vp) != VOL_STATE_DELETED));
5103
5104         /* valid states:
5105          *
5106          * VOL_STATE_GOING_OFFLINE
5107          * VOL_STATE_SHUTTING_DOWN
5108          * VIsErrorState(V_attachState(vp))
5109          * VIsExclusiveState(V_attachState(vp))
5110          */
5111
5112         VCreateReservation_r(vp);
5113         VChangeState_r(vp, VOL_STATE_OFFLINING);
5114
5115         ret = 1;
5116         /* must clear the goingOffline flag before we drop the glock */
5117         vp->goingOffline = 0;
5118         V_inUse(vp) = 0;
5119
5120         VLRU_Delete_r(vp);
5121
5122         /* perform async operations */
5123         VUpdateVolume_r(&error, vp, 0);
5124         VCloseVolumeHandles_r(vp);
5125
5126         if (LogLevel) {
5127             if (V_offlineMessage(vp)[0]) {
5128                 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5129                     afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5130                     V_offlineMessage(vp));
5131             } else {
5132                 Log("VOffline: Volume %lu (%s) is now offline\n",
5133                     afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5134             }
5135         }
5136
5137         /* invalidate the volume header cache entry */
5138         FreeVolumeHeader(vp);
5139
5140         /* if nothing changed state to error or salvaging,
5141          * drop state to unattached */
5142         if (!VIsErrorState(V_attachState(vp))) {
5143             VChangeState_r(vp, VOL_STATE_UNATTACHED);
5144         }
5145         VCancelReservation_r(vp);
5146         /* no usage of vp is safe beyond this point */
5147     }
5148     return ret;
5149 }
5150 #else /* AFS_DEMAND_ATTACH_FS */
5151 static int
5152 VCheckOffline(Volume * vp)
5153 {
5154     int ret = 0;
5155
5156     if (vp->goingOffline && !vp->nUsers) {
5157         Error error;
5158         osi_Assert(programType == fileServer);
5159
5160         ret = 1;
5161         vp->goingOffline = 0;
5162         V_inUse(vp) = 0;
5163         VUpdateVolume_r(&error, vp, 0);
5164         VCloseVolumeHandles_r(vp);
5165         if (LogLevel) {
5166             if (V_offlineMessage(vp)[0]) {
5167                 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
5168                     afs_printable_uint32_lu(V_id(vp)), V_name(vp),
5169                     V_offlineMessage(vp));
5170             } else {
5171                 Log("VOffline: Volume %lu (%s) is now offline\n",
5172                     afs_printable_uint32_lu(V_id(vp)), V_name(vp));
5173             }
5174         }
5175         FreeVolumeHeader(vp);
5176 #ifdef AFS_PTHREAD_ENV
5177         CV_BROADCAST(&vol_put_volume_cond);
5178 #else /* AFS_PTHREAD_ENV */
5179         LWP_NoYieldSignal(VPutVolume);
5180 #endif /* AFS_PTHREAD_ENV */
5181     }
5182     return ret;
5183 }
5184 #endif /* AFS_DEMAND_ATTACH_FS */
5185
5186 /***************************************************/
5187 /* demand attach fs ref counting routines          */
5188 /***************************************************/
5189
5190 #ifdef AFS_DEMAND_ATTACH_FS
5191 /* the following two functions handle reference counting for
5192  * asynchronous operations on volume structs.
5193  *
5194  * their purpose is to prevent a VDetachVolume or VShutdown
5195  * from free()ing the Volume struct during an async i/o op */
5196
5197 /* register with the async volume op ref counter */
5198 /* VCreateReservation_r moved into inline code header because it
5199  * is now needed in vnode.c -- tkeiser 11/20/2007
5200  */
5201
5202 /**
5203  * decrement volume-package internal refcount.
5204  *
5205  * @param vp  volume object pointer
5206  *
5207  * @internal volume package internal use only
5208  *
5209  * @pre
5210  *    @arg VOL_LOCK is held
5211  *    @arg lightweight refcount held
5212  *
5213  * @post volume waiters refcount is decremented; volume may
5214  *       have been deallocated/shutdown/offlined/salvaged/
5215  *       whatever during the process
5216  *
5217  * @warning once you have tossed your last reference (you can acquire
5218  *          lightweight refs recursively) it is NOT SAFE to reference
5219  *          a volume object pointer ever again
5220  *
5221  * @see VCreateReservation_r
5222  *
5223  * @note DEMAND_ATTACH_FS only
5224  */
5225 void
5226 VCancelReservation_r(Volume * vp)
5227 {
5228     osi_Assert(--vp->nWaiters >= 0);
5229     if (vp->nWaiters == 0) {
5230         VCheckOffline(vp);
5231         if (!VCheckDetach(vp)) {
5232             VCheckSalvage(vp);
5233             VCheckFree(vp);
5234         }
5235     }
5236 }
5237
5238 /* check to see if we should free this volume now
5239  * return 1 if volume was freed, 0 otherwise */
5240 static int
5241 VCheckFree(Volume * vp)
5242 {
5243     int ret = 0;
5244     if ((vp->nUsers == 0) &&
5245         (vp->nWaiters == 0) &&
5246         !(V_attachFlags(vp) & (VOL_IN_HASH |
5247                                VOL_ON_VBYP_LIST |
5248                                VOL_IS_BUSY |
5249                                VOL_ON_VLRU))) {
5250         ReallyFreeVolume(vp);
5251         ret = 1;
5252     }
5253     return ret;
5254 }
5255 #endif /* AFS_DEMAND_ATTACH_FS */
5256
5257
5258 /***************************************************/
5259 /* online volume operations routines               */
5260 /***************************************************/
5261
5262 #ifdef AFS_DEMAND_ATTACH_FS
5263 /**
5264  * register a volume operation on a given volume.
5265  *
5266  * @param[in] vp       volume object
5267  * @param[in] vopinfo  volume operation info object
5268  *
5269  * @pre VOL_LOCK is held
5270  *
5271  * @post volume operation info object attached to volume object.
5272  *       volume operation statistics updated.
5273  *
5274  * @note by "attached" we mean a copy of the passed in object is made
5275  *
5276  * @internal volume package internal use only
5277  */
5278 int
5279 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5280 {
5281     FSSYNC_VolOp_info * info;
5282
5283     /* attach a vol op info node to the volume struct */
5284     info = (FSSYNC_VolOp_info *) malloc(sizeof(FSSYNC_VolOp_info));
5285     osi_Assert(info != NULL);
5286     memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
5287     vp->pending_vol_op = info;
5288
5289     /* update stats */
5290     vp->stats.last_vol_op = FT_ApproxTime();
5291     vp->stats.vol_ops++;
5292     IncUInt64(&VStats.vol_ops);
5293
5294     return 0;
5295 }
5296
5297 /**
5298  * deregister the volume operation attached to this volume.
5299  *
5300  * @param[in] vp  volume object pointer
5301  *
5302  * @pre VOL_LOCK is held
5303  *
5304  * @post the volume operation info object is detached from the volume object
5305  *
5306  * @internal volume package internal use only
5307  */
5308 int
5309 VDeregisterVolOp_r(Volume * vp)
5310 {
5311     if (vp->pending_vol_op) {
5312         free(vp->pending_vol_op);
5313         vp->pending_vol_op = NULL;
5314     }
5315     return 0;
5316 }
5317 #endif /* AFS_DEMAND_ATTACH_FS */
5318
5319 /**
5320  * determine whether it is safe to leave a volume online during
5321  * the volume operation described by the vopinfo object.
5322  *
5323  * @param[in] vp        volume object
5324  * @param[in] vopinfo   volume operation info object
5325  *
5326  * @return whether it is safe to leave volume online
5327  *    @retval 0  it is NOT SAFE to leave the volume online
5328  *    @retval 1  it is safe to leave the volume online during the operation
5329  *
5330  * @pre
5331  *    @arg VOL_LOCK is held
5332  *    @arg disk header attached to vp (heavyweight ref on vp will guarantee
5333  *         this condition is met)
5334  *
5335  * @internal volume package internal use only
5336  */
5337 int
5338 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5339 {
5340     return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
5341             (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5342             (vopinfo->com.reason == V_READONLY ||
5343              (!VolumeWriteable(vp) &&
5344               (vopinfo->com.reason == V_CLONE ||
5345                vopinfo->com.reason == V_DUMP)))));
5346 }
5347
5348 /**
5349  * same as VVolOpLeaveOnline_r, but does not require a volume with an attached
5350  * header.
5351  *
5352  * @param[in] vp        volume object
5353  * @param[in] vopinfo   volume operation info object
5354  *
5355  * @return whether it is safe to leave volume online
5356  *    @retval 0  it is NOT SAFE to leave the volume online
5357  *    @retval 1  it is safe to leave the volume online during the operation
5358  *    @retval -1 unsure; volume header is required in order to know whether or
5359  *               not is is safe to leave the volume online
5360  *
5361  * @pre VOL_LOCK is held
5362  *
5363  * @internal volume package internal use only
5364  */
5365 int
5366 VVolOpLeaveOnlineNoHeader_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5367 {
5368     /* follow the logic in VVolOpLeaveOnline_r; this is the same, except
5369      * assume that we don't know VolumeWriteable; return -1 if the answer
5370      * depends on VolumeWriteable */
5371
5372     if (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline) {
5373         return 1;
5374     }
5375     if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5376         vopinfo->com.reason == V_READONLY) {
5377
5378         return 1;
5379     }
5380     if (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5381         (vopinfo->com.reason == V_CLONE ||
5382          vopinfo->com.reason == V_DUMP)) {
5383
5384         /* must know VolumeWriteable */
5385         return -1;
5386     }
5387     return 0;
5388 }
5389
5390 /**
5391  * determine whether VBUSY should be set during this volume operation.
5392  *
5393  * @param[in] vp        volume object
5394  * @param[in] vopinfo   volume operation info object
5395  *
5396  * @return whether VBUSY should be set
5397  *   @retval 0  VBUSY does NOT need to be set
5398  *   @retval 1  VBUSY SHOULD be set
5399  *
5400  * @pre VOL_LOCK is held
5401  *
5402  * @internal volume package internal use only
5403  */
5404 int
5405 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
5406 {
5407     return ((vopinfo->com.command == FSYNC_VOL_OFF &&
5408             vopinfo->com.reason == FSYNC_SALVAGE) ||
5409             (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
5410             (vopinfo->com.reason == V_CLONE ||
5411              vopinfo->com.reason == V_DUMP)));
5412 }
5413
5414
5415 /***************************************************/
5416 /* online salvager routines                        */
5417 /***************************************************/
5418 #if defined(AFS_DEMAND_ATTACH_FS)
5419
5420 /**
5421  * offline a volume to let it be salvaged.
5422  *
5423  * @param[in] vp  Volume to offline
5424  *
5425  * @return whether we offlined the volume successfully
5426  *  @retval 0 volume was not offlined
5427  *  @retval 1 volume is now offline
5428  *
5429  * @note This is similar to VCheckOffline, but slightly different. We do not
5430  *       deal with vp->goingOffline, and we try to avoid touching the volume
5431  *       header except just to set needsSalvaged
5432  *
5433  * @pre VOL_LOCK held
5434  * @pre vp->nUsers == 0
5435  * @pre V_attachState(vp) == VOL_STATE_SALVAGE_REQ
5436  */
5437 static int
5438 VOfflineForSalvage_r(struct Volume *vp)
5439 {
5440     Error error;
5441
5442     VCreateReservation_r(vp);
5443     VWaitExclusiveState_r(vp);
5444
5445     if (vp->nUsers || V_attachState(vp) == VOL_STATE_SALVAGING) {
5446         /* Someone's using the volume, or someone got to scheduling the salvage
5447          * before us. I don't think either of these should be possible, as we
5448          * should gain no new heavyweight references while we're trying to
5449          * salvage, but just to be sure... */
5450         VCancelReservation_r(vp);
5451         return 0;
5452     }
5453
5454     VChangeState_r(vp, VOL_STATE_OFFLINING);
5455
5456     VLRU_Delete_r(vp);
5457     if (vp->header) {
5458         V_needsSalvaged(vp) = 1;
5459         /* ignore error; updating needsSalvaged is just best effort */
5460         VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
5461     }
5462     VCloseVolumeHandles_r(vp);
5463
5464     FreeVolumeHeader(vp);
5465
5466     /* volume has been effectively offlined; we can mark it in the SALVAGING
5467      * state now, which lets FSSYNC give it away */
5468     VChangeState_r(vp, VOL_STATE_SALVAGING);
5469
5470     VCancelReservation_r(vp);
5471
5472     return 1;
5473 }
5474
5475 /**
5476  * check whether a salvage needs to be performed on this volume.
5477  *
5478  * @param[in] vp   pointer to volume object
5479  *
5480  * @return status code
5481  *    @retval 0 no salvage scheduled
5482  *    @retval 1 a salvage has been scheduled with the salvageserver
5483  *
5484  * @pre VOL_LOCK is held
5485  *
5486  * @post if salvage request flag is set and nUsers and nWaiters are zero,
5487  *       then a salvage will be requested
5488  *
5489  * @note this is one of the event handlers called by VCancelReservation_r
5490  *
5491  * @note the caller must check if the volume needs to be freed after calling
5492  *       this; the volume may not have any references or be on any lists after
5493  *       we return, and we do not free it
5494  *
5495  * @see VCancelReservation_r
5496  *
5497  * @internal volume package internal use only.
5498  */
5499 static int
5500 VCheckSalvage(Volume * vp)
5501 {
5502     int ret = 0;
5503 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5504     if (vp->nUsers)
5505         return ret;
5506     if (!vp->salvage.requested) {
5507         return ret;
5508     }
5509
5510     /* prevent recursion; some of the code below creates and removes
5511      * lightweight refs, which can call VCheckSalvage */
5512     if (vp->salvage.scheduling) {
5513         return ret;
5514     }
5515     vp->salvage.scheduling = 1;
5516
5517     if (V_attachState(vp) == VOL_STATE_SALVAGE_REQ) {
5518         if (!VOfflineForSalvage_r(vp)) {
5519             vp->salvage.scheduling = 0;
5520             return ret;
5521         }
5522     }
5523
5524     if (vp->salvage.requested) {
5525         VScheduleSalvage_r(vp);
5526         ret = 1;
5527     }
5528     vp->salvage.scheduling = 0;
5529 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5530     return ret;
5531 }
5532
5533 /**
5534  * request volume salvage.
5535  *
5536  * @param[out] ec      computed client error code
5537  * @param[in]  vp      volume object pointer
5538  * @param[in]  reason  reason code (passed to salvageserver via SALVSYNC)
5539  * @param[in]  flags   see flags note below
5540  *
5541  * @note flags:
5542  *       VOL_SALVAGE_NO_OFFLINE do not need to wait to offline the volume; it has
5543  *                              not been fully attached
5544  *
5545  * @pre VOL_LOCK is held.
5546  *
5547  * @post volume state is changed.
5548  *       for fileserver, salvage will be requested once refcount reaches zero.
5549  *
5550  * @return operation status code
5551  *   @retval 0  volume salvage will occur
5552  *   @retval 1  volume salvage could not be scheduled
5553  *
5554  * @note DAFS only
5555  *
5556  * @note in the fileserver, this call does not synchronously schedule a volume
5557  *       salvage. rather, it sets volume state so that when volume refcounts
5558  *       reach zero, a volume salvage will occur. by "refcounts", we mean both
5559  *       nUsers and nWaiters must be zero.
5560  *
5561  * @internal volume package internal use only.
5562  */
5563 int
5564 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
5565 {
5566     int code = 0;
5567     /*
5568      * for DAFS volume utilities that are not supposed to schedule salvages,
5569      * just transition to error state instead
5570      */
5571     if (!VCanScheduleSalvage()) {
5572         VChangeState_r(vp, VOL_STATE_ERROR);
5573         *ec = VSALVAGE;
5574         return 1;
5575     }
5576
5577     if (programType != fileServer && !VCanUseFSSYNC()) {
5578         VChangeState_r(vp, VOL_STATE_ERROR);
5579         *ec = VSALVAGE;
5580         return 1;
5581     }
5582
5583     if (!vp->salvage.requested) {
5584         vp->salvage.requested = 1;
5585         vp->salvage.reason = reason;
5586         vp->stats.last_salvage = FT_ApproxTime();
5587
5588         /* Note that it is not possible for us to reach this point if a
5589          * salvage is already running on this volume (even if the fileserver
5590          * was restarted during the salvage). If a salvage were running, the
5591          * salvager would have write-locked the volume header file, so when
5592          * we tried to lock the volume header, the lock would have failed,
5593          * and we would have failed during attachment prior to calling
5594          * VRequestSalvage. So we know that we can schedule salvages without
5595          * fear of a salvage already running for this volume. */
5596
5597         if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
5598
5599             /* if we don't need to offline the volume, we can go directly
5600              * to SALVAGING. SALVAGING says the volume is offline and is
5601              * either salvaging or ready to be handed to the salvager.
5602              * SALVAGE_REQ says that we want to salvage the volume, but we
5603              * are waiting for it to go offline first. */
5604             if (flags & VOL_SALVAGE_NO_OFFLINE) {
5605                 VChangeState_r(vp, VOL_STATE_SALVAGING);
5606             } else {
5607                 VChangeState_r(vp, VOL_STATE_SALVAGE_REQ);
5608                 if (vp->nUsers == 0) {
5609                     /* normally VOfflineForSalvage_r would be called from
5610                      * PutVolume et al when nUsers reaches 0, but if
5611                      * it's already 0, just do it ourselves, since PutVolume
5612                      * isn't going to get called */
5613                     VOfflineForSalvage_r(vp);
5614                 }
5615             }
5616             /* If we are non-fileserver, we're telling the fileserver to
5617              * salvage the vol, so we don't need to give it back separately. */
5618             vp->needsPutBack = 0;
5619
5620             *ec = VSALVAGING;
5621         } else {
5622             Log("VRequestSalvage: volume %u online salvaged too many times; forced offline.\n", vp->hashid);
5623
5624             /* make sure neither VScheduleSalvage_r nor
5625              * VUpdateSalvagePriority_r try to schedule another salvage */
5626             vp->salvage.requested = vp->salvage.scheduled = 0;
5627
5628             VChangeState_r(vp, VOL_STATE_ERROR);
5629             *ec = VSALVAGE;
5630             code = 1;
5631         }
5632     }
5633     return code;
5634 }
5635
5636 /**
5637  * update salvageserver scheduling priority for a volume.
5638  *
5639  * @param[in] vp  pointer to volume object
5640  *
5641  * @return operation status
5642  *   @retval 0  success
5643  *   @retval 1  request denied, or SALVSYNC communications failure
5644  *
5645  * @pre VOL_LOCK is held.
5646  *
5647  * @post in-core salvage priority counter is incremented.  if at least
5648  *       SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
5649  *       last SALVSYNC_RAISEPRIO request, we contact the salvageserver
5650  *       to update its priority queue.  if no salvage is scheduled,
5651  *       this function is a no-op.
5652  *
5653  * @note DAFS fileserver only
5654  *
5655  * @note this should be called whenever a VGetVolume fails due to a
5656  *       pending salvage request
5657  *
5658  * @todo should set exclusive state and drop glock around salvsync call
5659  *
5660  * @internal volume package internal use only.
5661  */
5662 int
5663 VUpdateSalvagePriority_r(Volume * vp)
5664 {
5665     int ret=0;
5666
5667 #ifdef SALVSYNC_BUILD_CLIENT
5668     afs_uint32 now;
5669     int code;
5670
5671     vp->salvage.prio++;
5672     now = FT_ApproxTime();
5673
5674     /* update the salvageserver priority queue occasionally so that
5675      * frequently requested volumes get moved to the head of the queue
5676      */
5677     if ((vp->salvage.scheduled) &&
5678         (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
5679         code = SALVSYNC_SalvageVolume(vp->hashid,
5680                                       VPartitionPath(vp->partition),
5681                                       SALVSYNC_RAISEPRIO,
5682                                       vp->salvage.reason,
5683                                       vp->salvage.prio,
5684                                       NULL);
5685         vp->stats.last_salvage_req = now;
5686         if (code != SYNC_OK) {
5687             ret = 1;
5688         }
5689     }
5690 #endif /* SALVSYNC_BUILD_CLIENT */
5691     return ret;
5692 }
5693
5694
5695 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
5696
5697 /* A couple of little helper functions. These return true if we tried to
5698  * use this mechanism to schedule a salvage, false if we haven't tried.
5699  * If we did try a salvage then the results are contained in code.
5700  */
5701
5702 static_inline int
5703 try_SALVSYNC(Volume *vp, char *partName, int *code) {
5704 #ifdef SALVSYNC_BUILD_CLIENT
5705     if (VCanUseSALVSYNC()) {
5706         Log("Scheduling salvage for volume %lu on part %s over SALVSYNC\n",
5707             afs_printable_uint32_lu(vp->hashid), partName);
5708
5709         /* can't use V_id() since there's no guarantee
5710          * we have the disk data header at this point */
5711         *code = SALVSYNC_SalvageVolume(vp->hashid,
5712                                        partName,
5713                                        SALVSYNC_SALVAGE,
5714                                        vp->salvage.reason,
5715                                        vp->salvage.prio,
5716                                        NULL);
5717         return 1;
5718     }
5719 #endif
5720     return 0;
5721 }
5722
5723 static_inline int
5724 try_FSSYNC(Volume *vp, char *partName, int *code) {
5725 #ifdef FSSYNC_BUILD_CLIENT
5726     if (VCanUseFSSYNC()) {
5727         Log("Scheduling salvage for volume %lu on part %s over FSSYNC\n",
5728             afs_printable_uint32_lu(vp->hashid), partName);
5729
5730         /*
5731          * If we aren't the fileserver, tell the fileserver the volume
5732          * needs to be salvaged. We could directly tell the
5733          * salvageserver, but the fileserver keeps track of some stats
5734          * related to salvages, and handles some other salvage-related
5735          * complications for us.
5736          */
5737         *code = FSYNC_VolOp(vp->hashid, partName,
5738                             FSYNC_VOL_FORCE_ERROR, FSYNC_SALVAGE, NULL);
5739         return 1;
5740     }
5741 #endif /* FSSYNC_BUILD_CLIENT */
5742     return 0;
5743 }
5744
5745 /**
5746  * schedule a salvage with the salvage server or fileserver.
5747  *
5748  * @param[in] vp  pointer to volume object
5749  *
5750  * @return operation status
5751  *    @retval 0 salvage scheduled successfully
5752  *    @retval 1 salvage not scheduled, or SALVSYNC/FSSYNC com error
5753  *
5754  * @pre
5755  *    @arg VOL_LOCK is held.
5756  *    @arg nUsers and nWaiters should be zero.
5757  *
5758  * @post salvageserver or fileserver is sent a salvage request
5759  *
5760  * @note If we are the fileserver, the request will be sent to the salvage
5761  * server over SALVSYNC. If we are not the fileserver, the request will be
5762  * sent to the fileserver over FSSYNC (FSYNC_VOL_FORCE_ERROR/FSYNC_SALVAGE).
5763  *
5764  * @note the caller must check if the volume needs to be freed after calling
5765  *       this; the volume may not have any references or be on any lists after
5766  *       we return, and we do not free it
5767  *
5768  * @note DAFS only
5769  *
5770  * @internal volume package internal use only.
5771  */
5772 static int
5773 VScheduleSalvage_r(Volume * vp)
5774 {
5775     int ret=0;
5776     int code = 0;
5777     VolState state_save;
5778     VThreadOptions_t * thread_opts;
5779     char partName[16];
5780
5781     osi_Assert(VCanUseSALVSYNC() || VCanUseFSSYNC());
5782
5783     if (vp->nWaiters || vp->nUsers) {
5784         return 1;
5785     }
5786
5787     /* prevent endless salvage,attach,salvage,attach,... loops */
5788     if (vp->stats.salvages >= SALVAGE_COUNT_MAX)
5789         return 1;
5790
5791     /*
5792      * don't perform salvsync ops on certain threads
5793      */
5794     thread_opts = pthread_getspecific(VThread_key);
5795     if (thread_opts == NULL) {
5796         thread_opts = &VThread_defaults;
5797     }
5798     if (thread_opts->disallow_salvsync || vol_disallow_salvsync) {
5799         return 1;
5800     }
5801
5802     if (vp->salvage.scheduled) {
5803         return ret;
5804     }
5805
5806     VCreateReservation_r(vp);
5807     VWaitExclusiveState_r(vp);
5808
5809     /*
5810      * XXX the scheduling process should really be done asynchronously
5811      *     to avoid fssync deadlocks
5812      */
5813     if (!vp->salvage.scheduled) {
5814         /* if we haven't previously scheduled a salvage, do so now
5815          *
5816          * set the volume to an exclusive state and drop the lock
5817          * around the SALVSYNC call
5818          */
5819         strlcpy(partName, vp->partition->name, sizeof(partName));
5820         state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
5821         VOL_UNLOCK;
5822
5823         osi_Assert(try_SALVSYNC(vp, partName, &code) ||
5824                try_FSSYNC(vp, partName, &code));
5825
5826         VOL_LOCK;
5827         VChangeState_r(vp, state_save);
5828
5829         if (code == SYNC_OK) {
5830             vp->salvage.scheduled = 1;
5831             vp->stats.last_salvage_req = FT_ApproxTime();
5832             if (VCanUseSALVSYNC()) {
5833                 /* don't record these stats for non-fileservers; let the
5834                  * fileserver take care of these */
5835                 vp->stats.salvages++;
5836                 IncUInt64(&VStats.salvages);
5837             }
5838         } else {
5839             ret = 1;
5840             switch(code) {
5841             case SYNC_BAD_COMMAND:
5842             case SYNC_COM_ERROR:
5843                 break;
5844             case SYNC_DENIED:
5845                 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5846                     "denied\n", afs_printable_uint32_lu(vp->hashid));
5847                 break;
5848             case SYNC_FAILED:
5849                 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5850                     "failed\n", afs_printable_uint32_lu(vp->hashid));
5851                 break;
5852             default:
5853                 Log("VScheduleSalvage_r: Salvage request for volume %lu "
5854                     "received unknown protocol error %d\n",
5855                     afs_printable_uint32_lu(vp->hashid), code);
5856                 break;
5857             }
5858
5859             if (VCanUseFSSYNC()) {
5860                 VChangeState_r(vp, VOL_STATE_ERROR);
5861             }
5862         }
5863     }
5864
5865     /* NB: this is cancelling the reservation we obtained above, but we do
5866      * not call VCancelReservation_r, since that may trigger the vp dtor,
5867      * possibly free'ing the vp. We need to keep the vp around after
5868      * this, as the caller may reference vp without any refs. Instead, it
5869      * is the duty of the caller to inspect 'vp' after we return to see if
5870      * needs to be freed. */
5871     osi_Assert(--vp->nWaiters >= 0);
5872     return ret;
5873 }
5874 #endif /* SALVSYNC_BUILD_CLIENT || FSSYNC_BUILD_CLIENT */
5875
5876 #ifdef SALVSYNC_BUILD_CLIENT
5877
5878 /**
5879  * connect to the salvageserver SYNC service.
5880  *
5881  * @return operation status
5882  *    @retval 0 failure
5883  *    @retval 1 success
5884  *
5885  * @post connection to salvageserver SYNC service established
5886  *
5887  * @see VConnectSALV_r
5888  * @see VDisconnectSALV
5889  * @see VReconnectSALV
5890  */
5891 int
5892 VConnectSALV(void)
5893 {
5894     int retVal;
5895     VOL_LOCK;
5896     retVal = VConnectSALV_r();
5897     VOL_UNLOCK;
5898     return retVal;
5899 }
5900
5901 /**
5902  * connect to the salvageserver SYNC service.
5903  *
5904  * @return operation status
5905  *    @retval 0 failure
5906  *    @retval 1 success
5907  *
5908  * @pre VOL_LOCK is held.
5909  *
5910  * @post connection to salvageserver SYNC service established
5911  *
5912  * @see VConnectSALV
5913  * @see VDisconnectSALV_r
5914  * @see VReconnectSALV_r
5915  * @see SALVSYNC_clientInit
5916  *
5917  * @internal volume package internal use only.
5918  */
5919 int
5920 VConnectSALV_r(void)
5921 {
5922     return SALVSYNC_clientInit();
5923 }
5924
5925 /**
5926  * disconnect from the salvageserver SYNC service.
5927  *
5928  * @return operation status
5929  *    @retval 0 success
5930  *
5931  * @pre client should have a live connection to the salvageserver
5932  *
5933  * @post connection to salvageserver SYNC service destroyed
5934  *
5935  * @see VDisconnectSALV_r
5936  * @see VConnectSALV
5937  * @see VReconnectSALV
5938  */
5939 int
5940 VDisconnectSALV(void)
5941 {
5942     VOL_LOCK;
5943     VDisconnectSALV_r();
5944     VOL_UNLOCK;
5945     return 0;
5946 }
5947
5948 /**
5949  * disconnect from the salvageserver SYNC service.
5950  *
5951  * @return operation status
5952  *    @retval 0 success
5953  *
5954  * @pre
5955  *    @arg VOL_LOCK is held.
5956  *    @arg client should have a live connection to the salvageserver.
5957  *
5958  * @post connection to salvageserver SYNC service destroyed
5959  *
5960  * @see VDisconnectSALV
5961  * @see VConnectSALV_r
5962  * @see VReconnectSALV_r
5963  * @see SALVSYNC_clientFinis
5964  *
5965  * @internal volume package internal use only.
5966  */
5967 int
5968 VDisconnectSALV_r(void)
5969 {
5970     return SALVSYNC_clientFinis();
5971 }
5972
5973 /**
5974  * disconnect and then re-connect to the salvageserver SYNC service.
5975  *
5976  * @return operation status
5977  *    @retval 0 failure
5978  *    @retval 1 success
5979  *
5980  * @pre client should have a live connection to the salvageserver
5981  *
5982  * @post old connection is dropped, and a new one is established
5983  *
5984  * @see VConnectSALV
5985  * @see VDisconnectSALV
5986  * @see VReconnectSALV_r
5987  */
5988 int
5989 VReconnectSALV(void)
5990 {
5991     int retVal;
5992     VOL_LOCK;
5993     retVal = VReconnectSALV_r();
5994     VOL_UNLOCK;
5995     return retVal;
5996 }
5997
5998 /**
5999  * disconnect and then re-connect to the salvageserver SYNC service.
6000  *
6001  * @return operation status
6002  *    @retval 0 failure
6003  *    @retval 1 success
6004  *
6005  * @pre
6006  *    @arg VOL_LOCK is held.
6007  *    @arg client should have a live connection to the salvageserver.
6008  *
6009  * @post old connection is dropped, and a new one is established
6010  *
6011  * @see VConnectSALV_r
6012  * @see VDisconnectSALV
6013  * @see VReconnectSALV
6014  * @see SALVSYNC_clientReconnect
6015  *
6016  * @internal volume package internal use only.
6017  */
6018 int
6019 VReconnectSALV_r(void)
6020 {
6021     return SALVSYNC_clientReconnect();
6022 }
6023 #endif /* SALVSYNC_BUILD_CLIENT */
6024 #endif /* AFS_DEMAND_ATTACH_FS */
6025
6026
6027 /***************************************************/
6028 /* FSSYNC routines                                 */
6029 /***************************************************/
6030
6031 /* This must be called by any volume utility which needs to run while the
6032    file server is also running.  This is separated from VInitVolumePackage2 so
6033    that a utility can fork--and each of the children can independently
6034    initialize communication with the file server */
6035 #ifdef FSSYNC_BUILD_CLIENT
6036 /**
6037  * connect to the fileserver SYNC service.
6038  *
6039  * @return operation status
6040  *    @retval 0 failure
6041  *    @retval 1 success
6042  *
6043  * @pre
6044  *    @arg VInit must equal 2.
6045  *    @arg Program Type must not be fileserver or salvager.
6046  *
6047  * @post connection to fileserver SYNC service established
6048  *
6049  * @see VConnectFS_r
6050  * @see VDisconnectFS
6051  * @see VChildProcReconnectFS
6052  */
6053 int
6054 VConnectFS(void)
6055 {
6056     int retVal;
6057     VOL_LOCK;
6058     retVal = VConnectFS_r();
6059     VOL_UNLOCK;
6060     return retVal;
6061 }
6062
6063 /**
6064  * connect to the fileserver SYNC service.
6065  *
6066  * @return operation status
6067  *    @retval 0 failure
6068  *    @retval 1 success
6069  *
6070  * @pre
6071  *    @arg VInit must equal 2.
6072  *    @arg Program Type must not be fileserver or salvager.
6073  *    @arg VOL_LOCK is held.
6074  *
6075  * @post connection to fileserver SYNC service established
6076  *
6077  * @see VConnectFS
6078  * @see VDisconnectFS_r
6079  * @see VChildProcReconnectFS_r
6080  *
6081  * @internal volume package internal use only.
6082  */
6083 int
6084 VConnectFS_r(void)
6085 {
6086     int rc;
6087     osi_Assert((VInit == 2) &&
6088            (programType != fileServer) &&
6089            (programType != salvager));
6090     rc = FSYNC_clientInit();
6091     if (rc) {
6092         VSetVInit_r(3);
6093     }
6094     return rc;
6095 }
6096
6097 /**
6098  * disconnect from the fileserver SYNC service.
6099  *
6100  * @pre
6101  *    @arg client should have a live connection to the fileserver.
6102  *    @arg VOL_LOCK is held.
6103  *    @arg Program Type must not be fileserver or salvager.
6104  *
6105  * @post connection to fileserver SYNC service destroyed
6106  *
6107  * @see VDisconnectFS
6108  * @see VConnectFS_r
6109  * @see VChildProcReconnectFS_r
6110  *
6111  * @internal volume package internal use only.
6112  */
6113 void
6114 VDisconnectFS_r(void)
6115 {
6116     osi_Assert((programType != fileServer) &&
6117            (programType != salvager));
6118     FSYNC_clientFinis();
6119     VSetVInit_r(2);
6120 }
6121
6122 /**
6123  * disconnect from the fileserver SYNC service.
6124  *
6125  * @pre
6126  *    @arg client should have a live connection to the fileserver.
6127  *    @arg Program Type must not be fileserver or salvager.
6128  *
6129  * @post connection to fileserver SYNC service destroyed
6130  *
6131  * @see VDisconnectFS_r
6132  * @see VConnectFS
6133  * @see VChildProcReconnectFS
6134  */
6135 void
6136 VDisconnectFS(void)
6137 {
6138     VOL_LOCK;
6139     VDisconnectFS_r();
6140     VOL_UNLOCK;
6141 }
6142
6143 /**
6144  * connect to the fileserver SYNC service from a child process following a fork.
6145  *
6146  * @return operation status
6147  *    @retval 0 failure
6148  *    @retval 1 success
6149  *
6150  * @pre
6151  *    @arg VOL_LOCK is held.
6152  *    @arg current FSYNC handle is shared with a parent process
6153  *
6154  * @post current FSYNC handle is discarded and a new connection to the
6155  *       fileserver SYNC service is established
6156  *
6157  * @see VChildProcReconnectFS
6158  * @see VConnectFS_r
6159  * @see VDisconnectFS_r
6160  *
6161  * @internal volume package internal use only.
6162  */
6163 int
6164 VChildProcReconnectFS_r(void)
6165 {
6166     return FSYNC_clientChildProcReconnect();
6167 }
6168
6169 /**
6170  * connect to the fileserver SYNC service from a child process following a fork.
6171  *
6172  * @return operation status
6173  *    @retval 0 failure
6174  *    @retval 1 success
6175  *
6176  * @pre current FSYNC handle is shared with a parent process
6177  *
6178  * @post current FSYNC handle is discarded and a new connection to the
6179  *       fileserver SYNC service is established
6180  *
6181  * @see VChildProcReconnectFS_r
6182  * @see VConnectFS
6183  * @see VDisconnectFS
6184  */
6185 int
6186 VChildProcReconnectFS(void)
6187 {
6188     int ret;
6189     VOL_LOCK;
6190     ret = VChildProcReconnectFS_r();
6191     VOL_UNLOCK;
6192     return ret;
6193 }
6194 #endif /* FSSYNC_BUILD_CLIENT */
6195
6196
6197 /***************************************************/
6198 /* volume bitmap routines                          */
6199 /***************************************************/
6200
6201 /*
6202  * Grow the bitmap by the defined increment
6203  */
6204 void
6205 VGrowBitmap(struct vnodeIndex *index)
6206 {
6207     byte *bp;
6208
6209     bp = realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
6210     osi_Assert(bp != NULL);
6211     index->bitmap = bp;
6212     bp += index->bitmapSize;
6213     memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
6214     index->bitmapOffset = index->bitmapSize;
6215     index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
6216
6217     return;
6218 }
6219
6220 /**
6221  * allocate a vnode bitmap number for the vnode
6222  *
6223  * @param[out] ec  error code
6224  * @param[in] vp   volume object pointer
6225  * @param[in] index vnode index number for the vnode
6226  * @param[in] flags flag values described in note
6227  *
6228  * @note for DAFS, flags parameter controls locking behavior.
6229  * If (flags & VOL_ALLOC_BITMAP_WAIT) is set, then this function
6230  * will create a reservation and block on any other exclusive
6231  * operations.  Otherwise, this function assumes the caller
6232  * already has exclusive access to vp, and we just change the
6233  * volume state.
6234  *
6235  * @pre VOL_LOCK held
6236  *
6237  * @return bit number allocated
6238  */
6239 /*
6240
6241  */
6242 int
6243 VAllocBitmapEntry_r(Error * ec, Volume * vp,
6244                     struct vnodeIndex *index, int flags)
6245 {
6246     int ret = 0;
6247     byte *bp, *ep;
6248 #ifdef AFS_DEMAND_ATTACH_FS
6249     VolState state_save;
6250 #endif /* AFS_DEMAND_ATTACH_FS */
6251
6252     *ec = 0;
6253
6254     /* This test is probably redundant */
6255     if (!VolumeWriteable(vp)) {
6256         *ec = (bit32) VREADONLY;
6257         return ret;
6258     }
6259
6260 #ifdef AFS_DEMAND_ATTACH_FS
6261     if (flags & VOL_ALLOC_BITMAP_WAIT) {
6262         VCreateReservation_r(vp);
6263         VWaitExclusiveState_r(vp);
6264     }
6265     state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6266 #endif /* AFS_DEMAND_ATTACH_FS */
6267
6268 #ifdef BITMAP_LATER
6269     if ((programType == fileServer) && !index->bitmap) {
6270         int i;
6271 #ifndef AFS_DEMAND_ATTACH_FS
6272         /* demand attach fs uses the volume state to avoid races.
6273          * specialStatus field is not used at all */
6274         int wasVBUSY = 0;
6275         if (vp->specialStatus == VBUSY) {
6276             if (vp->goingOffline) {     /* vos dump waiting for the volume to
6277                                          * go offline. We probably come here
6278                                          * from AddNewReadableResidency */
6279                 wasVBUSY = 1;
6280             } else {
6281                 while (vp->specialStatus == VBUSY) {
6282 #ifdef AFS_PTHREAD_ENV
6283                     VOL_UNLOCK;
6284                     sleep(2);
6285                     VOL_LOCK;
6286 #else /* !AFS_PTHREAD_ENV */
6287                     IOMGR_Sleep(2);
6288 #endif /* !AFS_PTHREAD_ENV */
6289                 }
6290             }
6291         }
6292 #endif /* !AFS_DEMAND_ATTACH_FS */
6293
6294         if (!index->bitmap) {
6295 #ifndef AFS_DEMAND_ATTACH_FS
6296             vp->specialStatus = VBUSY;  /* Stop anyone else from using it. */
6297 #endif /* AFS_DEMAND_ATTACH_FS */
6298             for (i = 0; i < nVNODECLASSES; i++) {
6299                 VGetBitmap_r(ec, vp, i);
6300                 if (*ec) {
6301 #ifdef AFS_DEMAND_ATTACH_FS
6302                     VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, 0 /*flags*/);
6303 #else /* AFS_DEMAND_ATTACH_FS */
6304                     DeleteVolumeFromHashTable(vp);
6305                     vp->shuttingDown = 1;       /* Let who has it free it. */
6306                     vp->specialStatus = 0;
6307 #endif /* AFS_DEMAND_ATTACH_FS */
6308                     goto done;
6309                 }
6310             }
6311 #ifndef AFS_DEMAND_ATTACH_FS
6312             if (!wasVBUSY)
6313                 vp->specialStatus = 0;  /* Allow others to have access. */
6314 #endif /* AFS_DEMAND_ATTACH_FS */
6315         }
6316     }
6317 #endif /* BITMAP_LATER */
6318
6319 #ifdef AFS_DEMAND_ATTACH_FS
6320     VOL_UNLOCK;
6321 #endif /* AFS_DEMAND_ATTACH_FS */
6322     bp = index->bitmap + index->bitmapOffset;
6323     ep = index->bitmap + index->bitmapSize;
6324     while (bp < ep) {
6325         if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
6326             int o;
6327             index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
6328             while (*bp == 0xff)
6329                 bp++;
6330             o = ffs(~*bp) - 1;  /* ffs is documented in BSTRING(3) */
6331             *bp |= (1 << o);
6332             ret = ((bp - index->bitmap) * 8 + o);
6333 #ifdef AFS_DEMAND_ATTACH_FS
6334             VOL_LOCK;
6335 #endif /* AFS_DEMAND_ATTACH_FS */
6336             goto done;
6337         }
6338         bp += sizeof(bit32) /* i.e. 4 */ ;
6339     }
6340     /* No bit map entry--must grow bitmap */
6341     VGrowBitmap(index);
6342     bp = index->bitmap;
6343     *bp = 1;
6344     ret = index->bitmapOffset * 8;
6345 #ifdef AFS_DEMAND_ATTACH_FS
6346     VOL_LOCK;
6347 #endif /* AFS_DEMAND_ATTACH_FS */
6348
6349  done:
6350 #ifdef AFS_DEMAND_ATTACH_FS
6351     VChangeState_r(vp, state_save);
6352     if (flags & VOL_ALLOC_BITMAP_WAIT) {
6353         VCancelReservation_r(vp);
6354     }
6355 #endif /* AFS_DEMAND_ATTACH_FS */
6356     return ret;
6357 }
6358
6359 int
6360 VAllocBitmapEntry(Error * ec, Volume * vp, struct vnodeIndex * index)
6361 {
6362     int retVal;
6363     VOL_LOCK;
6364     retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
6365     VOL_UNLOCK;
6366     return retVal;
6367 }
6368
6369 void
6370 VFreeBitMapEntry_r(Error * ec, Volume *vp, struct vnodeIndex *index,
6371                    unsigned bitNumber, int flags)
6372 {
6373     unsigned int offset;
6374
6375     *ec = 0;
6376
6377 #ifdef AFS_DEMAND_ATTACH_FS
6378     if (flags & VOL_FREE_BITMAP_WAIT) {
6379         /* VAllocBitmapEntry_r allocs bitmap entries under an exclusive volume
6380          * state, so ensure we're not in an exclusive volume state when we update
6381          * the bitmap */
6382         VCreateReservation_r(vp);
6383         VWaitExclusiveState_r(vp);
6384     }
6385 #endif
6386
6387 #ifdef BITMAP_LATER
6388     if (!index->bitmap)
6389         goto done;
6390 #endif /* BITMAP_LATER */
6391
6392     offset = bitNumber >> 3;
6393     if (offset >= index->bitmapSize) {
6394         *ec = VNOVNODE;
6395         goto done;
6396     }
6397     if (offset < index->bitmapOffset)
6398         index->bitmapOffset = offset & ~3;      /* Truncate to nearest bit32 */
6399     *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
6400
6401  done:
6402 #ifdef AFS_DEMAND_ATTACH_FS
6403     VCancelReservation_r(vp);
6404 #endif
6405     return; /* make the compiler happy for non-DAFS */
6406 }
6407
6408 void
6409 VFreeBitMapEntry(Error * ec, Volume *vp, struct vnodeIndex *index,
6410                  unsigned bitNumber)
6411 {
6412     VOL_LOCK;
6413     VFreeBitMapEntry_r(ec, vp, index, bitNumber, VOL_FREE_BITMAP_WAIT);
6414     VOL_UNLOCK;
6415 }
6416
6417 /* this function will drop the glock internally.
6418  * for old pthread fileservers, this is safe thanks to vbusy.
6419  *
6420  * for demand attach fs, caller must have already called
6421  * VCreateReservation_r and VWaitExclusiveState_r */
6422 static void
6423 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
6424 {
6425     StreamHandle_t *file;
6426     afs_sfsize_t nVnodes, size;
6427     struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
6428     struct vnodeIndex *vip = &vp->vnodeIndex[class];
6429     struct VnodeDiskObject *vnode;
6430     unsigned int unique = 0;
6431     FdHandle_t *fdP;
6432 #ifdef BITMAP_LATER
6433     byte *BitMap = 0;
6434 #endif /* BITMAP_LATER */
6435 #ifdef AFS_DEMAND_ATTACH_FS
6436     VolState state_save;
6437 #endif /* AFS_DEMAND_ATTACH_FS */
6438
6439     *ec = 0;
6440
6441 #ifdef AFS_DEMAND_ATTACH_FS
6442     state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
6443 #endif /* AFS_DEMAND_ATTACH_FS */
6444     VOL_UNLOCK;
6445
6446     fdP = IH_OPEN(vip->handle);
6447     osi_Assert(fdP != NULL);
6448     file = FDH_FDOPEN(fdP, "r");
6449     osi_Assert(file != NULL);
6450     vnode = (VnodeDiskObject *) malloc(vcp->diskSize);
6451     osi_Assert(vnode != NULL);
6452     size = OS_SIZE(fdP->fd_fd);
6453     osi_Assert(size != -1);
6454     nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
6455         >> vcp->logSize;
6456     vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4;     /* The 10 is a little extra so
6457                                                          * a few files can be created in this volume,
6458                                                          * the whole thing is rounded up to nearest 4
6459                                                          * bytes, because the bit map allocator likes
6460                                                          * it that way */
6461 #ifdef BITMAP_LATER
6462     BitMap = (byte *) calloc(1, vip->bitmapSize);
6463     osi_Assert(BitMap != NULL);
6464 #else /* BITMAP_LATER */
6465     vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
6466     osi_Assert(vip->bitmap != NULL);
6467     vip->bitmapOffset = 0;
6468 #endif /* BITMAP_LATER */
6469     if (STREAM_ASEEK(file, vcp->diskSize) != -1) {
6470         int bitNumber = 0;
6471         for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
6472             if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
6473                 break;
6474             if (vnode->type != vNull) {
6475                 if (vnode->vnodeMagic != vcp->magic) {
6476                     Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
6477                     *ec = VSALVAGE;
6478                     break;
6479                 }
6480 #ifdef BITMAP_LATER
6481                 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6482 #else /* BITMAP_LATER */
6483                 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
6484 #endif /* BITMAP_LATER */
6485                 if (unique <= vnode->uniquifier)
6486                     unique = vnode->uniquifier + 1;
6487             }
6488 #ifndef AFS_PTHREAD_ENV
6489             if ((bitNumber & 0x00ff) == 0x0ff) {        /* every 256 iterations */
6490                 IOMGR_Poll();
6491             }
6492 #endif /* !AFS_PTHREAD_ENV */
6493         }
6494     }
6495     if (vp->nextVnodeUnique < unique) {
6496         Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
6497         *ec = VSALVAGE;
6498     }
6499     /* Paranoia, partly justified--I think fclose after fdopen
6500      * doesn't seem to close fd.  In any event, the documentation
6501      * doesn't specify, so it's safer to close it twice.
6502      */
6503     STREAM_CLOSE(file);
6504     FDH_CLOSE(fdP);
6505     free(vnode);
6506
6507     VOL_LOCK;
6508 #ifdef BITMAP_LATER
6509     /* There may have been a racing condition with some other thread, both
6510      * creating the bitmaps for this volume. If the other thread was faster
6511      * the pointer to bitmap should already be filled and we can free ours.
6512      */
6513     if (vip->bitmap == NULL) {
6514         vip->bitmap = BitMap;
6515         vip->bitmapOffset = 0;
6516     } else
6517         free((byte *) BitMap);
6518 #endif /* BITMAP_LATER */
6519 #ifdef AFS_DEMAND_ATTACH_FS
6520     VChangeState_r(vp, state_save);
6521 #endif /* AFS_DEMAND_ATTACH_FS */
6522 }
6523
6524
6525 /***************************************************/
6526 /* Volume Path and Volume Number utility routines  */
6527 /***************************************************/
6528
6529 /**
6530  * find the first occurrence of a volume header file and return the path.
6531  *
6532  * @param[out] ec          outbound error code
6533  * @param[in]  volumeId    volume id to find
6534  * @param[out] partitionp  pointer to disk partition path string
6535  * @param[out] namep       pointer to volume header file name string
6536  *
6537  * @post path to first occurrence of volume header is returned in partitionp
6538  *       and namep, or ec is set accordingly.
6539  *
6540  * @warning this function is NOT re-entrant -- partitionp and namep point to
6541  *          static data segments
6542  *
6543  * @note if a volume utility inadvertently leaves behind a stale volume header
6544  *       on a vice partition, it is possible for callers to get the wrong one,
6545  *       depending on the order of the disk partition linked list.
6546  *
6547  */
6548 void
6549 VGetVolumePath(Error * ec, VolId volumeId, char **partitionp, char **namep)
6550 {
6551     static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
6552     char path[VMAXPATHLEN];
6553     int found = 0;
6554     struct DiskPartition64 *dp;
6555
6556     *ec = 0;
6557     name[0] = OS_DIRSEPC;
6558     snprintf(&name[1], (sizeof name) - 1, VFORMAT,
6559              afs_printable_uint32_lu(volumeId));
6560     for (dp = DiskPartitionList; dp; dp = dp->next) {
6561         struct afs_stat_st status;
6562         strcpy(path, VPartitionPath(dp));
6563         strcat(path, name);
6564         if (afs_stat(path, &status) == 0) {
6565             strcpy(partition, dp->name);
6566             found = 1;
6567             break;
6568         }
6569     }
6570     if (!found) {
6571         *ec = VNOVOL;
6572         *partitionp = *namep = NULL;
6573     } else {
6574         *partitionp = partition;
6575         *namep = name;
6576     }
6577 }
6578
6579 /**
6580  * extract a volume number from a volume header filename string.
6581  *
6582  * @param[in] name  volume header filename string
6583  *
6584  * @return volume number
6585  *
6586  * @note the string must be of the form VFORMAT.  the only permissible
6587  *       deviation is a leading OS_DIRSEPC character.
6588  *
6589  * @see VFORMAT
6590  */
6591 int
6592 VolumeNumber(char *name)
6593 {
6594     if (*name == OS_DIRSEPC)
6595         name++;
6596     return strtoul(name + 1, NULL, 10);
6597 }
6598
6599 /**
6600  * compute the volume header filename.
6601  *
6602  * @param[in] volumeId
6603  *
6604  * @return volume header filename
6605  *
6606  * @post volume header filename string is constructed
6607  *
6608  * @warning this function is NOT re-entrant -- the returned string is
6609  *          stored in a static char array.  see VolumeExternalName_r
6610  *          for a re-entrant equivalent.
6611  *
6612  * @see VolumeExternalName_r
6613  *
6614  * @deprecated due to the above re-entrancy warning, this interface should
6615  *             be considered deprecated.  Please use VolumeExternalName_r
6616  *             in its stead.
6617  */
6618 char *
6619 VolumeExternalName(VolumeId volumeId)
6620 {
6621     static char name[VMAXPATHLEN];
6622     snprintf(name, sizeof name, VFORMAT, afs_printable_uint32_lu(volumeId));
6623     return name;
6624 }
6625
6626 /**
6627  * compute the volume header filename.
6628  *
6629  * @param[in]     volumeId
6630  * @param[inout]  name       array in which to store filename
6631  * @param[in]     len        length of name array
6632  *
6633  * @return result code from afs_snprintf
6634  *
6635  * @see VolumeExternalName
6636  * @see afs_snprintf
6637  *
6638  * @note re-entrant equivalent of VolumeExternalName
6639  */
6640 int
6641 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
6642 {
6643     return snprintf(name, len, VFORMAT, afs_printable_uint32_lu(volumeId));
6644 }
6645
6646
6647 /***************************************************/
6648 /* Volume Usage Statistics routines                */
6649 /***************************************************/
6650
6651 #define OneDay  (86400)         /* 24 hours' worth of seconds */
6652
6653 static time_t
6654 Midnight(time_t t) {
6655     struct tm local, *l;
6656     time_t midnight;
6657
6658 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
6659     l = localtime_r(&t, &local);
6660 #else
6661     l = localtime(&t);
6662 #endif
6663
6664     if (l != NULL) {
6665         /* the following is strictly speaking problematic on the
6666            switching day to daylight saving time, after the switch,
6667            as tm_isdst does not match.  Similarly, on the looong day when
6668            switching back the OneDay check will not do what naively expected!
6669            The effects are minor, though, and more a matter of interpreting
6670            the numbers. */
6671 #ifndef AFS_PTHREAD_ENV
6672         local = *l;
6673 #endif
6674         local.tm_hour = local.tm_min=local.tm_sec = 0;
6675         midnight = mktime(&local);
6676         if (midnight != (time_t) -1) return(midnight);
6677     }
6678     return( (t/OneDay)*OneDay );
6679
6680 }
6681
6682 /*------------------------------------------------------------------------
6683  * [export] VAdjustVolumeStatistics
6684  *
6685  * Description:
6686  *      If we've passed midnight, we need to update all the day use
6687  *      statistics as well as zeroing the detailed volume statistics
6688  *      (if we are implementing them).
6689  *
6690  * Arguments:
6691  *      vp : Pointer to the volume structure describing the lucky
6692  *              volume being considered for update.
6693  *
6694  * Returns:
6695  *      0 (always!)
6696  *
6697  * Environment:
6698  *      Nothing interesting.
6699  *
6700  * Side Effects:
6701  *      As described.
6702  *------------------------------------------------------------------------*/
6703
6704 int
6705 VAdjustVolumeStatistics_r(Volume * vp)
6706 {
6707     unsigned int now = FT_ApproxTime();
6708
6709     if (now - V_dayUseDate(vp) > OneDay) {
6710         int ndays, i;
6711
6712         ndays = (now - V_dayUseDate(vp)) / OneDay;
6713         for (i = 6; i > ndays - 1; i--)
6714             V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
6715         for (i = 0; i < ndays - 1 && i < 7; i++)
6716             V_weekUse(vp)[i] = 0;
6717         if (ndays <= 7)
6718             V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
6719         V_dayUse(vp) = 0;
6720         V_dayUseDate(vp) = Midnight(now);
6721
6722         /*
6723          * All we need to do is bzero the entire VOL_STATS_BYTES of
6724          * the detailed volume statistics area.
6725          */
6726         memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
6727         }
6728
6729     /*It's been more than a day of collection */
6730     /*
6731      * Always return happily.
6732      */
6733     return (0);
6734 }                               /*VAdjustVolumeStatistics */
6735
6736 int
6737 VAdjustVolumeStatistics(Volume * vp)
6738 {
6739     int retVal;
6740     VOL_LOCK;
6741     retVal = VAdjustVolumeStatistics_r(vp);
6742     VOL_UNLOCK;
6743     return retVal;
6744 }
6745
6746 void
6747 VBumpVolumeUsage_r(Volume * vp)
6748 {
6749     unsigned int now = FT_ApproxTime();
6750     V_accessDate(vp) = now;
6751     if (now - V_dayUseDate(vp) > OneDay)
6752         VAdjustVolumeStatistics_r(vp);
6753     /*
6754      * Save the volume header image to disk after a threshold of bumps to dayUse,
6755      * at most every usage_rate_limit seconds.
6756      */
6757     V_dayUse(vp)++;
6758     vp->usage_bumps_outstanding++;
6759     if (vp->usage_bumps_outstanding >= vol_opts.usage_threshold
6760         && vp->usage_bumps_next_write <= now) {
6761         Error error;
6762         vp->usage_bumps_outstanding = 0;
6763         vp->usage_bumps_next_write = now + vol_opts.usage_rate_limit;
6764         VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
6765     }
6766 }
6767
6768 void
6769 VBumpVolumeUsage(Volume * vp)
6770 {
6771     VOL_LOCK;
6772     VBumpVolumeUsage_r(vp);
6773     VOL_UNLOCK;
6774 }
6775
6776 void
6777 VSetDiskUsage_r(void)
6778 {
6779 #ifndef AFS_DEMAND_ATTACH_FS
6780     static int FifteenMinuteCounter = 0;
6781 #endif
6782
6783     while (VInit < 2) {
6784         /* NOTE: Don't attempt to access the partitions list until the
6785          * initialization level indicates that all volumes are attached,
6786          * which implies that all partitions are initialized. */
6787 #ifdef AFS_PTHREAD_ENV
6788         VOL_CV_WAIT(&vol_vinit_cond);
6789 #else /* AFS_PTHREAD_ENV */
6790         IOMGR_Sleep(10);
6791 #endif /* AFS_PTHREAD_ENV */
6792     }
6793
6794     VResetDiskUsage_r();
6795
6796 #ifndef AFS_DEMAND_ATTACH_FS
6797     if (++FifteenMinuteCounter == 3) {
6798         FifteenMinuteCounter = 0;
6799         VScanUpdateList();
6800     }
6801 #endif /* !AFS_DEMAND_ATTACH_FS */
6802 }
6803
6804 void
6805 VSetDiskUsage(void)
6806 {
6807     VOL_LOCK;
6808     VSetDiskUsage_r();
6809     VOL_UNLOCK;
6810 }
6811
6812
6813 /***************************************************/
6814 /* Volume Update List routines                     */
6815 /***************************************************/
6816
6817 /* The number of minutes that a volume hasn't been updated before the
6818  * "Dont salvage" flag in the volume header will be turned on */
6819 #define SALVAGE_INTERVAL        (10*60)
6820
6821 /*
6822  * demand attach fs
6823  *
6824  * volume update list functionality has been moved into the VLRU
6825  * the DONT_SALVAGE flag is now set during VLRU demotion
6826  */
6827
6828 #ifndef AFS_DEMAND_ATTACH_FS
6829 static VolumeId *UpdateList = NULL;     /* Pointer to array of Volume ID's */
6830 static int nUpdatedVolumes = 0;         /* Updated with entry in UpdateList, salvage after crash flag on */
6831 static int updateSize = 0;              /* number of entries possible */
6832 #define UPDATE_LIST_SIZE 128            /* initial size increment (must be a power of 2!) */
6833 #endif /* !AFS_DEMAND_ATTACH_FS */
6834
6835 void
6836 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
6837 {
6838     *ec = 0;
6839     vp->updateTime = FT_ApproxTime();
6840     if (V_dontSalvage(vp) == 0)
6841         return;
6842     V_dontSalvage(vp) = 0;
6843     VSyncVolume_r(ec, vp, 0);
6844 #ifdef AFS_DEMAND_ATTACH_FS
6845     V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
6846 #else /* !AFS_DEMAND_ATTACH_FS */
6847     if (*ec)
6848         return;
6849     if (UpdateList == NULL) {
6850         updateSize = UPDATE_LIST_SIZE;
6851         UpdateList = (VolumeId *) malloc(sizeof(VolumeId) * updateSize);
6852     } else {
6853         if (nUpdatedVolumes == updateSize) {
6854             updateSize <<= 1;
6855             if (updateSize > 524288) {
6856                 Log("warning: there is likely a bug in the volume update scanner\n");
6857                 return;
6858             }
6859             UpdateList =
6860                 (VolumeId *) realloc(UpdateList,
6861                                      sizeof(VolumeId) * updateSize);
6862         }
6863     }
6864     osi_Assert(UpdateList != NULL);
6865     UpdateList[nUpdatedVolumes++] = V_id(vp);
6866 #endif /* !AFS_DEMAND_ATTACH_FS */
6867 }
6868
6869 #ifndef AFS_DEMAND_ATTACH_FS
6870 static void
6871 VScanUpdateList(void)
6872 {
6873     int i, gap;
6874     Volume *vp;
6875     Error error;
6876     afs_uint32 now = FT_ApproxTime();
6877     /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
6878     for (i = gap = 0; i < nUpdatedVolumes; i++) {
6879         if (gap)
6880             UpdateList[i - gap] = UpdateList[i];
6881
6882         /* XXX this routine needlessly messes up the Volume LRU by
6883          * breaking the LRU temporal-locality assumptions.....
6884          * we should use a special volume header allocator here */
6885         vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
6886         if (error) {
6887             gap++;
6888         } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
6889             V_dontSalvage(vp) = DONT_SALVAGE;
6890             VUpdateVolume_r(&error, vp, 0);     /* No need to fsync--not critical */
6891             gap++;
6892         }
6893
6894         if (vp) {
6895             VPutVolume_r(vp);
6896         }
6897
6898 #ifndef AFS_PTHREAD_ENV
6899         IOMGR_Poll();
6900 #endif /* !AFS_PTHREAD_ENV */
6901     }
6902     nUpdatedVolumes -= gap;
6903 }
6904 #endif /* !AFS_DEMAND_ATTACH_FS */
6905
6906
6907 /***************************************************/
6908 /* Volume LRU routines                             */
6909 /***************************************************/
6910
6911 /* demand attach fs
6912  * volume LRU
6913  *
6914  * with demand attach fs, we attempt to soft detach(1)
6915  * volumes which have not been accessed in a long time
6916  * in order to speed up fileserver shutdown
6917  *
6918  * (1) by soft detach we mean a process very similar
6919  *     to VOffline, except the final state of the
6920  *     Volume will be VOL_STATE_PREATTACHED, instead
6921  *     of the usual VOL_STATE_UNATTACHED
6922  */
6923 #ifdef AFS_DEMAND_ATTACH_FS
6924
6925 /* implementation is reminiscent of a generational GC
6926  *
6927  * queue 0 is newly attached volumes. this queue is
6928  * sorted by attach timestamp
6929  *
6930  * queue 1 is volumes that have been around a bit
6931  * longer than queue 0. this queue is sorted by
6932  * attach timestamp
6933  *
6934  * queue 2 is volumes tha have been around the longest.
6935  * this queue is unsorted
6936  *
6937  * queue 3 is volumes that have been marked as
6938  * candidates for soft detachment. this queue is
6939  * unsorted
6940  */
6941 #define VLRU_GENERATIONS  3   /**< number of generations in VLRU */
6942 #define VLRU_QUEUES       5   /**< total number of VLRU queues */
6943
6944 /**
6945  * definition of a VLRU queue.
6946  */
6947 struct VLRU_q {
6948     volatile struct rx_queue q;
6949     volatile int len;
6950     volatile int busy;
6951     pthread_cond_t cv;
6952 };
6953
6954 /**
6955  * main VLRU data structure.
6956  */
6957 struct VLRU {
6958     struct VLRU_q q[VLRU_QUEUES];   /**< VLRU queues */
6959
6960     /* VLRU config */
6961     /** time interval (in seconds) between promotion passes for
6962      *  each young generation queue. */
6963     afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
6964
6965     /** time interval (in seconds) between soft detach candidate
6966      *  scans for each generation queue.
6967      *
6968      *  scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
6969      *  we perform a soft detach pass. */
6970     afs_uint32 scan_interval[VLRU_GENERATIONS+1];
6971
6972     /* scheduler state */
6973     int next_idx;                                       /**< next queue to receive attention */
6974     afs_uint32 last_promotion[VLRU_GENERATIONS-1];      /**< timestamp of last promotion scan */
6975     afs_uint32 last_scan[VLRU_GENERATIONS+1];           /**< timestamp of last detach scan */
6976
6977     int scanner_state;                                  /**< state of scanner thread */
6978     pthread_cond_t cv;                                  /**< state transition CV */
6979 };
6980
6981 /** global VLRU state */
6982 static struct VLRU volume_LRU;
6983
6984 /**
6985  * defined states for VLRU scanner thread.
6986  */
6987 typedef enum {
6988     VLRU_SCANNER_STATE_OFFLINE        = 0,    /**< vlru scanner thread is offline */
6989     VLRU_SCANNER_STATE_ONLINE         = 1,    /**< vlru scanner thread is online */
6990     VLRU_SCANNER_STATE_SHUTTING_DOWN  = 2,    /**< vlru scanner thread is shutting down */
6991     VLRU_SCANNER_STATE_PAUSING        = 3,    /**< vlru scanner thread is getting ready to pause */
6992     VLRU_SCANNER_STATE_PAUSED         = 4     /**< vlru scanner thread is paused */
6993 } vlru_thread_state_t;
6994
6995 /* vlru disk data header stuff */
6996 #define VLRU_DISK_MAGIC      0x7a8b9cad        /**< vlru disk entry magic number */
6997 #define VLRU_DISK_VERSION    1                 /**< vlru disk entry version number */
6998
6999 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
7000 #define VLRU_DUMP_EXPIRATION_TIME   (60*60*24*7)  /* expire vlru data after 1 week */
7001
7002
7003 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
7004  *  soft detachment. */
7005 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
7006
7007 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
7008 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
7009
7010 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
7011 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
7012
7013 /** VLRU control flag.  non-zero value implies VLRU subsystem is activated. */
7014 static afs_uint32 VLRU_enabled = 1;
7015
7016 /* queue synchronization routines */
7017 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
7018 static void VLRU_EndExclusive_r(struct VLRU_q * q);
7019 static void VLRU_Wait_r(struct VLRU_q * q);
7020
7021 /**
7022  * set VLRU subsystem tunable parameters.
7023  *
7024  * @param[in] option  tunable option to modify
7025  * @param[in] val     new value for tunable parameter
7026  *
7027  * @pre @c VInitVolumePackage2 has not yet been called.
7028  *
7029  * @post tunable parameter is modified
7030  *
7031  * @note DAFS only
7032  *
7033  * @note valid option parameters are:
7034  *    @arg @c VLRU_SET_THRESH
7035  *         set the period of inactivity after which
7036  *         volumes are eligible for soft detachment
7037  *    @arg @c VLRU_SET_INTERVAL
7038  *         set the time interval between calls
7039  *         to the volume LRU "garbage collector"
7040  *    @arg @c VLRU_SET_MAX
7041  *         set the max number of volumes to deallocate
7042  *         in one GC pass
7043  */
7044 void
7045 VLRU_SetOptions(int option, afs_uint32 val)
7046 {
7047     if (option == VLRU_SET_THRESH) {
7048         VLRU_offline_thresh = val;
7049     } else if (option == VLRU_SET_INTERVAL) {
7050         VLRU_offline_interval = val;
7051     } else if (option == VLRU_SET_MAX) {
7052         VLRU_offline_max = val;
7053     } else if (option == VLRU_SET_ENABLED) {
7054         VLRU_enabled = val;
7055     }
7056     VLRU_ComputeConstants();
7057 }
7058
7059 /**
7060  * compute VLRU internal timing parameters.
7061  *
7062  * @post VLRU scanner thread internal timing parameters are computed
7063  *
7064  * @note computes internal timing parameters based upon user-modifiable
7065  *       tunable parameters.
7066  *
7067  * @note DAFS only
7068  *
7069  * @internal volume package internal use only.
7070  */
7071 static void
7072 VLRU_ComputeConstants(void)
7073 {
7074     afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
7075
7076     /* compute the candidate scan interval */
7077     volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
7078
7079     /* compute the promotion intervals */
7080     volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
7081     volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
7082
7083     if (factor > 16) {
7084         /* compute the gen 0 scan interval */
7085         volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
7086     } else {
7087         /* compute the gen 0 scan interval */
7088         volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
7089     }
7090 }
7091
7092 /**
7093  * initialize VLRU subsystem.
7094  *
7095  * @pre this function has not yet been called
7096  *
7097  * @post VLRU subsystem is initialized and VLRU scanner thread is starting
7098  *
7099  * @note DAFS only
7100  *
7101  * @internal volume package internal use only.
7102  */
7103 static void
7104 VInitVLRU(void)
7105 {
7106     pthread_t tid;
7107     pthread_attr_t attrs;
7108     int i;
7109
7110     if (!VLRU_enabled) {
7111         Log("VLRU: disabled\n");
7112         return;
7113     }
7114
7115     /* initialize each of the VLRU queues */
7116     for (i = 0; i < VLRU_QUEUES; i++) {
7117         queue_Init(&volume_LRU.q[i]);
7118         volume_LRU.q[i].len = 0;
7119         volume_LRU.q[i].busy = 0;
7120         CV_INIT(&volume_LRU.q[i].cv, "vol lru", CV_DEFAULT, 0);
7121     }
7122
7123     /* setup the timing constants */
7124     VLRU_ComputeConstants();
7125
7126     /* XXX put inside LogLevel check? */
7127     Log("VLRU: starting scanner with the following configuration parameters:\n");
7128     Log("VLRU:  offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
7129     Log("VLRU:  running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
7130     Log("VLRU:  taking up to %d volumes offline per pass\n", VLRU_offline_max);
7131     Log("VLRU:  scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
7132     Log("VLRU:  scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
7133     Log("VLRU:  scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
7134
7135     /* start up the VLRU scanner */
7136     volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7137     if (programType == fileServer) {
7138         CV_INIT(&volume_LRU.cv, "vol lru", CV_DEFAULT, 0);
7139         osi_Assert(pthread_attr_init(&attrs) == 0);
7140         osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
7141         osi_Assert(pthread_create(&tid, &attrs, &VLRU_ScannerThread, NULL) == 0);
7142     }
7143 }
7144
7145 /**
7146  * initialize the VLRU-related fields of a newly allocated volume object.
7147  *
7148  * @param[in] vp  pointer to volume object
7149  *
7150  * @pre
7151  *    @arg @c VOL_LOCK is held.
7152  *    @arg volume object is not on a VLRU queue.
7153  *
7154  * @post VLRU fields are initialized to indicate that volume object is not
7155  *       currently registered with the VLRU subsystem
7156  *
7157  * @note DAFS only
7158  *
7159  * @internal volume package interal use only.
7160  */
7161 static void
7162 VLRU_Init_Node_r(Volume * vp)
7163 {
7164     if (!VLRU_enabled)
7165         return;
7166
7167     osi_Assert(queue_IsNotOnQueue(&vp->vlru));
7168     vp->vlru.idx = VLRU_QUEUE_INVALID;
7169 }
7170
7171 /**
7172  * add a volume object to a VLRU queue.
7173  *
7174  * @param[in] vp  pointer to volume object
7175  *
7176  * @pre
7177  *    @arg @c VOL_LOCK is held.
7178  *    @arg caller MUST hold a lightweight ref on @p vp.
7179  *    @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7180  *
7181  * @post the volume object is added to the appropriate VLRU queue
7182  *
7183  * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
7184  *       then the volume is added to that queue.  Otherwise, the value
7185  *       @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
7186  *       volume is added to the NEW generation queue.
7187  *
7188  * @note @c VOL_LOCK may be dropped internally
7189  *
7190  * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
7191  *       during the add operation, and is restored to the previous
7192  *       state prior to return.
7193  *
7194  * @note DAFS only
7195  *
7196  * @internal volume package internal use only.
7197  */
7198 static void
7199 VLRU_Add_r(Volume * vp)
7200 {
7201     int idx;
7202     VolState state_save;
7203
7204     if (!VLRU_enabled)
7205         return;
7206
7207     if (queue_IsOnQueue(&vp->vlru))
7208         return;
7209
7210     state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
7211
7212     idx = vp->vlru.idx;
7213     if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
7214         idx = VLRU_QUEUE_NEW;
7215     }
7216
7217     VLRU_Wait_r(&volume_LRU.q[idx]);
7218
7219     /* repeat check since VLRU_Wait_r may have dropped
7220      * the glock */
7221     if (queue_IsNotOnQueue(&vp->vlru)) {
7222         vp->vlru.idx = idx;
7223         queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
7224         volume_LRU.q[idx].len++;
7225         V_attachFlags(vp) |= VOL_ON_VLRU;
7226         vp->stats.last_promote = FT_ApproxTime();
7227     }
7228
7229     VChangeState_r(vp, state_save);
7230 }
7231
7232 /**
7233  * delete a volume object from a VLRU queue.
7234  *
7235  * @param[in] vp  pointer to volume object
7236  *
7237  * @pre
7238  *    @arg @c VOL_LOCK is held.
7239  *    @arg caller MUST hold a lightweight ref on @p vp.
7240  *    @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
7241  *
7242  * @post volume object is removed from the VLRU queue
7243  *
7244  * @note @c VOL_LOCK may be dropped internally
7245  *
7246  * @note DAFS only
7247  *
7248  * @todo We should probably set volume state to something exlcusive
7249  *       (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
7250  *
7251  * @internal volume package internal use only.
7252  */
7253 static void
7254 VLRU_Delete_r(Volume * vp)
7255 {
7256     int idx;
7257
7258     if (!VLRU_enabled)
7259         return;
7260
7261     if (queue_IsNotOnQueue(&vp->vlru))
7262         return;
7263
7264     /* handle races */
7265     do {
7266       idx = vp->vlru.idx;
7267       if (idx == VLRU_QUEUE_INVALID)
7268           return;
7269       VLRU_Wait_r(&volume_LRU.q[idx]);
7270     } while (idx != vp->vlru.idx);
7271
7272     /* now remove from the VLRU and update
7273      * the appropriate counter */
7274     queue_Remove(&vp->vlru);
7275     volume_LRU.q[idx].len--;
7276     vp->vlru.idx = VLRU_QUEUE_INVALID;
7277     V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7278 }
7279
7280 /**
7281  * tell the VLRU subsystem that a volume was just accessed.
7282  *
7283  * @param[in] vp  pointer to volume object
7284  *
7285  * @pre
7286  *    @arg @c VOL_LOCK is held
7287  *    @arg caller MUST hold a lightweight ref on @p vp
7288  *    @arg caller MUST NOT hold exclusive ownership of any VLRU queue
7289  *
7290  * @post volume VLRU access statistics are updated.  If the volume was on
7291  *       the VLRU soft detach candidate queue, it is moved to the NEW
7292  *       generation queue.
7293  *
7294  * @note @c VOL_LOCK may be dropped internally
7295  *
7296  * @note DAFS only
7297  *
7298  * @internal volume package internal use only.
7299  */
7300 static void
7301 VLRU_UpdateAccess_r(Volume * vp)
7302 {
7303     Volume * rvp = NULL;
7304
7305     if (!VLRU_enabled)
7306         return;
7307
7308     if (queue_IsNotOnQueue(&vp->vlru))
7309         return;
7310
7311     osi_Assert(V_attachFlags(vp) & VOL_ON_VLRU);
7312
7313     /* update the access timestamp */
7314     vp->stats.last_get = FT_ApproxTime();
7315
7316     /*
7317      * if the volume is on the soft detach candidate
7318      * list, we need to safely move it back to a
7319      * regular generation.  this has to be done
7320      * carefully so we don't race against the scanner
7321      * thread.
7322      */
7323
7324     /* if this volume is on the soft detach candidate queue,
7325      * then grab exclusive access to the necessary queues */
7326     if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7327         rvp = vp;
7328         VCreateReservation_r(rvp);
7329
7330         VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7331         VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7332         VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7333         VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7334     }
7335
7336     /* make sure multiple threads don't race to update */
7337     if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
7338         VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
7339     }
7340
7341     if (rvp) {
7342       VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7343       VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
7344       VCancelReservation_r(rvp);
7345     }
7346 }
7347
7348 /**
7349  * switch a volume between two VLRU queues.
7350  *
7351  * @param[in] vp       pointer to volume object
7352  * @param[in] new_idx  index of VLRU queue onto which the volume will be moved
7353  * @param[in] append   controls whether the volume will be appended or
7354  *                     prepended to the queue.  A nonzero value means it will
7355  *                     be appended; zero means it will be prepended.
7356  *
7357  * @pre The new (and old, if applicable) queue(s) must either be owned
7358  *      exclusively by the calling thread for asynchronous manipulation,
7359  *      or the queue(s) must be quiescent and VOL_LOCK must be held.
7360  *      Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
7361  *      for further details of the queue asynchronous processing mechanism.
7362  *
7363  * @post If the volume object was already on a VLRU queue, it is
7364  *       removed from the queue.  Depending on the value of the append
7365  *       parameter, the volume object is either appended or prepended
7366  *       to the VLRU queue referenced by the new_idx parameter.
7367  *
7368  * @note DAFS only
7369  *
7370  * @see VLRU_BeginExclusive_r
7371  * @see VLRU_EndExclusive_r
7372  * @see VLRU_Wait_r
7373  *
7374  * @internal volume package internal use only.
7375  */
7376 static void
7377 VLRU_SwitchQueues(Volume * vp, int new_idx, int append)
7378 {
7379     if (queue_IsNotOnQueue(&vp->vlru))
7380         return;
7381
7382     queue_Remove(&vp->vlru);
7383     volume_LRU.q[vp->vlru.idx].len--;
7384
7385     /* put the volume back on the correct generational queue */
7386     if (append) {
7387         queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
7388     } else {
7389         queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
7390     }
7391
7392     volume_LRU.q[new_idx].len++;
7393     vp->vlru.idx = new_idx;
7394 }
7395
7396 /**
7397  * VLRU background thread.
7398  *
7399  * The VLRU Scanner Thread is responsible for periodically scanning through
7400  * each VLRU queue looking for volumes which should be moved to another
7401  * queue, or soft detached.
7402  *
7403  * @param[in] args  unused thread arguments parameter
7404  *
7405  * @return unused thread return value
7406  *    @retval NULL always
7407  *
7408  * @internal volume package internal use only.
7409  */
7410 static void *
7411 VLRU_ScannerThread(void * args)
7412 {
7413     afs_uint32 now, min_delay, delay;
7414     int i, min_idx, min_op, overdue, state;
7415
7416     /* set t=0 for promotion cycle to be
7417      * fileserver startup */
7418     now = FT_ApproxTime();
7419     for (i=0; i < VLRU_GENERATIONS-1; i++) {
7420         volume_LRU.last_promotion[i] = now;
7421     }
7422
7423     /* don't start the scanner until VLRU_offline_thresh
7424      * plus a small delay for VInitVolumePackage2 to finish
7425      * has gone by */
7426
7427     sleep(VLRU_offline_thresh + 60);
7428
7429     /* set t=0 for scan cycle to be now */
7430     now = FT_ApproxTime();
7431     for (i=0; i < VLRU_GENERATIONS+1; i++) {
7432         volume_LRU.last_scan[i] = now;
7433     }
7434
7435     VOL_LOCK;
7436     if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
7437         volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
7438     }
7439
7440     while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
7441         /* check to see if we've been asked to pause */
7442         if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
7443             volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
7444             CV_BROADCAST(&volume_LRU.cv);
7445             do {
7446                 VOL_CV_WAIT(&volume_LRU.cv);
7447             } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
7448         }
7449
7450         /* scheduling can happen outside the glock */
7451         VOL_UNLOCK;
7452
7453         /* figure out what is next on the schedule */
7454
7455         /* figure out a potential schedule for the new generation first */
7456         overdue = 0;
7457         min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
7458         min_idx = 0;
7459         min_op = 0;
7460         if (min_delay > volume_LRU.scan_interval[0]) {
7461             /* unsigned overflow -- we're overdue to run this scan */
7462             min_delay = 0;
7463             overdue = 1;
7464         }
7465
7466         /* if we're not overdue for gen 0, figure out schedule for candidate gen */
7467         if (!overdue) {
7468             i = VLRU_QUEUE_CANDIDATE;
7469             delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
7470             if (delay < min_delay) {
7471                 min_delay = delay;
7472                 min_idx = i;
7473             }
7474             if (delay > volume_LRU.scan_interval[i]) {
7475                 /* unsigned overflow -- we're overdue to run this scan */
7476                 min_delay = 0;
7477                 min_idx = i;
7478                 overdue = 1;
7479             }
7480         }
7481
7482         /* if we're still not overdue for something, figure out schedules for promotions */
7483         for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
7484             delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
7485             if (delay < min_delay) {
7486                 min_delay = delay;
7487                 min_idx = i;
7488                 min_op = 1;
7489             }
7490             if (delay > volume_LRU.promotion_interval[i]) {
7491                 /* unsigned overflow -- we're overdue to run this promotion */
7492                 min_delay = 0;
7493                 min_idx = i;
7494                 min_op = 1;
7495                 overdue = 1;
7496                 break;
7497             }
7498         }
7499
7500         /* sleep as needed */
7501         if (min_delay) {
7502             sleep(min_delay);
7503         }
7504
7505         /* do whatever is next */
7506         VOL_LOCK;
7507         if (min_op) {
7508             VLRU_Promote_r(min_idx);
7509             VLRU_Demote_r(min_idx+1);
7510         } else {
7511             VLRU_Scan_r(min_idx);
7512         }
7513         now = FT_ApproxTime();
7514     }
7515
7516     Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
7517
7518     /* signal that scanner is down */
7519     volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
7520     CV_BROADCAST(&volume_LRU.cv);
7521     VOL_UNLOCK;
7522     return NULL;
7523 }
7524
7525 /**
7526  * promote volumes from one VLRU generation to the next.
7527  *
7528  * This routine scans a VLRU generation looking for volumes which are
7529  * eligible to be promoted to the next generation.  All volumes which
7530  * meet the eligibility requirement are promoted.
7531  *
7532  * Promotion eligibility is based upon meeting both of the following
7533  * requirements:
7534  *
7535  *    @arg The volume has been accessed since the last promotion:
7536  *         @c (vp->stats.last_get >= vp->stats.last_promote)
7537  *    @arg The last promotion occurred at least
7538  *         @c volume_LRU.promotion_interval[idx] seconds ago
7539  *
7540  * As a performance optimization, promotions are "globbed".  In other
7541  * words, we promote arbitrarily large contiguous sublists of elements
7542  * as one operation.
7543  *
7544  * @param[in] idx  VLRU queue index to scan
7545  *
7546  * @note DAFS only
7547  *
7548  * @internal VLRU internal use only.
7549  */
7550 static void
7551 VLRU_Promote_r(int idx)
7552 {
7553     int len, chaining, promote;
7554     afs_uint32 now, thresh;
7555     struct rx_queue *qp, *nqp;
7556     Volume * vp, *start = NULL, *end = NULL;
7557
7558     /* get exclusive access to two chains, and drop the glock */
7559     VLRU_Wait_r(&volume_LRU.q[idx]);
7560     VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7561     VLRU_Wait_r(&volume_LRU.q[idx+1]);
7562     VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
7563     VOL_UNLOCK;
7564
7565     thresh = volume_LRU.promotion_interval[idx];
7566     now = FT_ApproxTime();
7567
7568     len = chaining = 0;
7569     for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7570         vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7571         promote = (((vp->stats.last_promote + thresh) <= now) &&
7572                    (vp->stats.last_get >= vp->stats.last_promote));
7573
7574         if (chaining) {
7575             if (promote) {
7576                 vp->vlru.idx++;
7577                 len++;
7578                 start = vp;
7579             } else {
7580                 /* promote and prepend chain */
7581                 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7582                 chaining = 0;
7583             }
7584         } else {
7585             if (promote) {
7586                 vp->vlru.idx++;
7587                 len++;
7588                 chaining = 1;
7589                 start = end = vp;
7590             }
7591         }
7592     }
7593
7594     if (chaining) {
7595         /* promote and prepend */
7596         queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
7597     }
7598
7599     if (len) {
7600         volume_LRU.q[idx].len -= len;
7601         volume_LRU.q[idx+1].len += len;
7602     }
7603
7604     /* release exclusive access to the two chains */
7605     VOL_LOCK;
7606     volume_LRU.last_promotion[idx] = now;
7607     VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
7608     VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7609 }
7610
7611 /* run the demotions */
7612 static void
7613 VLRU_Demote_r(int idx)
7614 {
7615     Error ec;
7616     int len, chaining, demote;
7617     afs_uint32 now, thresh;
7618     struct rx_queue *qp, *nqp;
7619     Volume * vp, *start = NULL, *end = NULL;
7620     Volume ** salv_flag_vec = NULL;
7621     int salv_vec_offset = 0;
7622
7623     osi_Assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
7624
7625     /* get exclusive access to two chains, and drop the glock */
7626     VLRU_Wait_r(&volume_LRU.q[idx-1]);
7627     VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
7628     VLRU_Wait_r(&volume_LRU.q[idx]);
7629     VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7630     VOL_UNLOCK;
7631
7632     /* no big deal if this allocation fails */
7633     if (volume_LRU.q[idx].len) {
7634         salv_flag_vec = (Volume **) malloc(volume_LRU.q[idx].len * sizeof(Volume *));
7635     }
7636
7637     now = FT_ApproxTime();
7638     thresh = volume_LRU.promotion_interval[idx-1];
7639
7640     len = chaining = 0;
7641     for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7642         vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7643         demote = (((vp->stats.last_promote + thresh) <= now) &&
7644                   (vp->stats.last_get < (now - thresh)));
7645
7646         /* we now do volume update list DONT_SALVAGE flag setting during
7647          * demotion passes */
7648         if (salv_flag_vec &&
7649             !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7650             demote &&
7651             (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7652             (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7653             salv_flag_vec[salv_vec_offset++] = vp;
7654             VCreateReservation_r(vp);
7655         }
7656
7657         if (chaining) {
7658             if (demote) {
7659                 vp->vlru.idx--;
7660                 len++;
7661                 start = vp;
7662             } else {
7663                 /* demote and append chain */
7664                 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7665                 chaining = 0;
7666             }
7667         } else {
7668             if (demote) {
7669                 vp->vlru.idx--;
7670                 len++;
7671                 chaining = 1;
7672                 start = end = vp;
7673             }
7674         }
7675     }
7676
7677     if (chaining) {
7678         queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
7679     }
7680
7681     if (len) {
7682         volume_LRU.q[idx].len -= len;
7683         volume_LRU.q[idx-1].len += len;
7684     }
7685
7686     /* release exclusive access to the two chains */
7687     VOL_LOCK;
7688     VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7689     VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
7690
7691     /* now go back and set the DONT_SALVAGE flags as appropriate */
7692     if (salv_flag_vec) {
7693         int i;
7694         for (i = 0; i < salv_vec_offset; i++) {
7695             vp = salv_flag_vec[i];
7696             if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
7697                 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
7698                 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
7699                 ec = VHold_r(vp);
7700                 if (!ec) {
7701                     V_attachFlags(vp) |= VOL_HDR_DONTSALV;
7702                     V_dontSalvage(vp) = DONT_SALVAGE;
7703                     VUpdateVolume_r(&ec, vp, 0);
7704                     VPutVolume_r(vp);
7705                 }
7706             }
7707             VCancelReservation_r(vp);
7708         }
7709         free(salv_flag_vec);
7710     }
7711 }
7712
7713 /* run a pass of the VLRU GC scanner */
7714 static void
7715 VLRU_Scan_r(int idx)
7716 {
7717     afs_uint32 now, thresh;
7718     struct rx_queue *qp, *nqp;
7719     Volume * vp;
7720     int i, locked = 1;
7721
7722     osi_Assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
7723
7724     /* gain exclusive access to the idx VLRU */
7725     VLRU_Wait_r(&volume_LRU.q[idx]);
7726     VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7727
7728     if (idx != VLRU_QUEUE_CANDIDATE) {
7729         /* gain exclusive access to the candidate VLRU */
7730         VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7731         VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7732     }
7733
7734     now = FT_ApproxTime();
7735     thresh = now - VLRU_offline_thresh;
7736
7737     /* perform candidate selection and soft detaching */
7738     if (idx == VLRU_QUEUE_CANDIDATE) {
7739         /* soft detach some volumes from the candidate pool */
7740         VOL_UNLOCK;
7741         locked = 0;
7742
7743         for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7744             vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7745             if (i >= VLRU_offline_max) {
7746                 break;
7747             }
7748             /* check timestamp to see if it's a candidate for soft detaching */
7749             if (vp->stats.last_get <= thresh) {
7750                 VOL_LOCK;
7751                 if (VCheckSoftDetach(vp, thresh))
7752                     i++;
7753                 VOL_UNLOCK;
7754             }
7755         }
7756     } else {
7757         /* scan for volumes to become soft detach candidates */
7758         for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
7759             vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7760
7761             /* check timestamp to see if it's a candidate for soft detaching */
7762             if (vp->stats.last_get <= thresh) {
7763                 VCheckSoftDetachCandidate(vp, thresh);
7764             }
7765
7766             if (!(i&0x7f)) {   /* lock coarsening optimization */
7767                 VOL_UNLOCK;
7768                 pthread_yield();
7769                 VOL_LOCK;
7770             }
7771         }
7772     }
7773
7774     /* relinquish exclusive access to the VLRU chains */
7775     if (!locked) {
7776         VOL_LOCK;
7777     }
7778     volume_LRU.last_scan[idx] = now;
7779     if (idx != VLRU_QUEUE_CANDIDATE) {
7780         VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
7781     }
7782     VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7783 }
7784
7785 /* check whether volume is safe to soft detach
7786  * caller MUST NOT hold a ref count on vp */
7787 static int
7788 VCheckSoftDetach(Volume * vp, afs_uint32 thresh)
7789 {
7790     int ret=0;
7791
7792     if (vp->nUsers || vp->nWaiters)
7793         return 0;
7794
7795     if (vp->stats.last_get <= thresh) {
7796         ret = VSoftDetachVolume_r(vp, thresh);
7797     }
7798
7799     return ret;
7800 }
7801
7802 /* check whether volume should be made a
7803  * soft detach candidate */
7804 static int
7805 VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh)
7806 {
7807     int idx, ret = 0;
7808     if (vp->nUsers || vp->nWaiters)
7809         return 0;
7810
7811     idx = vp->vlru.idx;
7812
7813     osi_Assert(idx == VLRU_QUEUE_NEW);
7814
7815     if (vp->stats.last_get <= thresh) {
7816         /* move to candidate pool */
7817         queue_Remove(&vp->vlru);
7818         volume_LRU.q[VLRU_QUEUE_NEW].len--;
7819         queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
7820         vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
7821         volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
7822         ret = 1;
7823     }
7824
7825     return ret;
7826 }
7827
7828
7829 /* begin exclusive access on VLRU */
7830 static void
7831 VLRU_BeginExclusive_r(struct VLRU_q * q)
7832 {
7833     osi_Assert(q->busy == 0);
7834     q->busy = 1;
7835 }
7836
7837 /* end exclusive access on VLRU */
7838 static void
7839 VLRU_EndExclusive_r(struct VLRU_q * q)
7840 {
7841     osi_Assert(q->busy);
7842     q->busy = 0;
7843     CV_BROADCAST(&q->cv);
7844 }
7845
7846 /* wait for another thread to end exclusive access on VLRU */
7847 static void
7848 VLRU_Wait_r(struct VLRU_q * q)
7849 {
7850     while(q->busy) {
7851         VOL_CV_WAIT(&q->cv);
7852     }
7853 }
7854
7855 /* demand attach fs
7856  * volume soft detach
7857  *
7858  * caller MUST NOT hold a ref count on vp */
7859 static int
7860 VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh)
7861 {
7862     afs_uint32 ts_save;
7863     int ret = 0;
7864
7865     osi_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7866
7867     ts_save = vp->stats.last_get;
7868     if (ts_save > thresh)
7869         return 0;
7870
7871     if (vp->nUsers || vp->nWaiters)
7872         return 0;
7873
7874     if (VIsExclusiveState(V_attachState(vp))) {
7875         return 0;
7876     }
7877
7878     switch (V_attachState(vp)) {
7879     case VOL_STATE_UNATTACHED:
7880     case VOL_STATE_PREATTACHED:
7881     case VOL_STATE_ERROR:
7882     case VOL_STATE_GOING_OFFLINE:
7883     case VOL_STATE_SHUTTING_DOWN:
7884     case VOL_STATE_SALVAGING:
7885     case VOL_STATE_DELETED:
7886         volume_LRU.q[vp->vlru.idx].len--;
7887
7888         /* create and cancel a reservation to
7889          * give the volume an opportunity to
7890          * be deallocated */
7891         VCreateReservation_r(vp);
7892         queue_Remove(&vp->vlru);
7893         vp->vlru.idx = VLRU_QUEUE_INVALID;
7894         V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7895         VCancelReservation_r(vp);
7896         return 0;
7897     default:
7898         break;
7899     }
7900
7901     /* hold the volume and take it offline.
7902      * no need for reservations, as VHold_r
7903      * takes care of that internally. */
7904     if (VHold_r(vp) == 0) {
7905         /* vhold drops the glock, so now we should
7906          * check to make sure we aren't racing against
7907          * other threads.  if we are racing, offlining vp
7908          * would be wasteful, and block the scanner for a while
7909          */
7910         if (vp->nWaiters ||
7911             (vp->nUsers > 1) ||
7912             (vp->shuttingDown) ||
7913             (vp->goingOffline) ||
7914             (vp->stats.last_get != ts_save)) {
7915             /* looks like we're racing someone else. bail */
7916             VPutVolume_r(vp);
7917             vp = NULL;
7918         } else {
7919             /* pull it off the VLRU */
7920             osi_Assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
7921             volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
7922             queue_Remove(&vp->vlru);
7923             vp->vlru.idx = VLRU_QUEUE_INVALID;
7924             V_attachFlags(vp) &= ~(VOL_ON_VLRU);
7925
7926             /* take if offline */
7927             VOffline_r(vp, "volume has been soft detached");
7928
7929             /* invalidate the volume header cache */
7930             FreeVolumeHeader(vp);
7931
7932             /* update stats */
7933             IncUInt64(&VStats.soft_detaches);
7934             vp->stats.soft_detaches++;
7935
7936             /* put in pre-attached state so demand
7937              * attacher can work on it */
7938             VChangeState_r(vp, VOL_STATE_PREATTACHED);
7939             ret = 1;
7940         }
7941     }
7942     return ret;
7943 }
7944 #endif /* AFS_DEMAND_ATTACH_FS */
7945
7946
7947 /***************************************************/
7948 /* Volume Header Cache routines                    */
7949 /***************************************************/
7950
7951 /**
7952  * volume header cache.
7953  */
7954 struct volume_hdr_LRU_t volume_hdr_LRU;
7955
7956 /**
7957  * initialize the volume header cache.
7958  *
7959  * @param[in] howMany  number of header cache entries to preallocate
7960  *
7961  * @pre VOL_LOCK held.  Function has never been called before.
7962  *
7963  * @post howMany cache entries are allocated, initialized, and added
7964  *       to the LRU list.  Header cache statistics are initialized.
7965  *
7966  * @note only applicable to fileServer program type.  Should only be
7967  *       called once during volume package initialization.
7968  *
7969  * @internal volume package internal use only.
7970  */
7971 static void
7972 VInitVolumeHeaderCache(afs_uint32 howMany)
7973 {
7974     struct volHeader *hp;
7975     if (programType != fileServer)
7976         return;
7977     queue_Init(&volume_hdr_LRU);
7978     volume_hdr_LRU.stats.free = 0;
7979     volume_hdr_LRU.stats.used = howMany;
7980     volume_hdr_LRU.stats.attached = 0;
7981     hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
7982     osi_Assert(hp != NULL);
7983
7984     while (howMany--)
7985         /* We are using ReleaseVolumeHeader to initialize the values on the header list
7986          * to ensure they have the right values
7987          */
7988         ReleaseVolumeHeader(hp++);
7989 }
7990
7991 /* get a volume header off of the volume header LRU.
7992  *
7993  * @return volume header
7994  *  @retval NULL no usable volume header is available on the LRU
7995  *
7996  * @pre VOL_LOCK held
7997  *
7998  * @post for DAFS, if the returned header is associated with a volume, that
7999  *       volume is NOT in an exclusive state
8000  *
8001  * @internal volume package internal use only.
8002  */
8003 #ifdef AFS_DEMAND_ATTACH_FS
8004 static struct volHeader*
8005 GetVolHeaderFromLRU(void)
8006 {
8007     struct volHeader *hd = NULL, *qh, *nqh;
8008     /* Usually, a volume in an exclusive state will not have its header on
8009      * the LRU. However, it is possible for this to occur when a salvage
8010      * request is received over FSSYNC, and possibly in other corner cases.
8011      * So just skip over headers whose volumes are in an exclusive state. We
8012      * could VWaitExclusiveState_r instead, but not waiting is faster and
8013      * easier to do */
8014     for (queue_Scan(&volume_hdr_LRU, qh, nqh, volHeader)) {
8015         if (!qh->back || !VIsExclusiveState(V_attachState(qh->back))) {
8016             queue_Remove(qh);
8017             hd = qh;
8018             break;
8019         }
8020     }
8021     return hd;
8022 }
8023 #else /* AFS_DEMAND_ATTACH_FS */
8024 static struct volHeader*
8025 GetVolHeaderFromLRU(void)
8026 {
8027     struct volHeader *hd = NULL;
8028     if (queue_IsNotEmpty(&volume_hdr_LRU)) {
8029         hd = queue_First(&volume_hdr_LRU, volHeader);
8030         queue_Remove(hd);
8031     }
8032     return hd;
8033 }
8034 #endif /* !AFS_DEMAND_ATTACH_FS */
8035
8036 /**
8037  * get a volume header and attach it to the volume object.
8038  *
8039  * @param[in] vp  pointer to volume object
8040  *
8041  * @return cache entry status
8042  *    @retval 0  volume header was newly attached; cache data is invalid
8043  *    @retval 1  volume header was previously attached; cache data is valid
8044  *
8045  * @pre VOL_LOCK held.  For DAFS, lightweight ref must be held on volume object.
8046  *
8047  * @post volume header attached to volume object.  if necessary, header cache
8048  *       entry on LRU is synchronized to disk.  Header is removed from LRU list.
8049  *
8050  * @note VOL_LOCK may be dropped
8051  *
8052  * @warning this interface does not load header data from disk.  it merely
8053  *          attaches a header object to the volume object, and may sync the old
8054  *          header cache data out to disk in the process.
8055  *
8056  * @internal volume package internal use only.
8057  */
8058 static int
8059 GetVolumeHeader(Volume * vp)
8060 {
8061     Error error;
8062     struct volHeader *hd;
8063     int old;
8064     static int everLogged = 0;
8065
8066 #ifdef AFS_DEMAND_ATTACH_FS
8067     VolState vp_save = 0, back_save = 0;
8068
8069     /* XXX debug 9/19/05 we've apparently got
8070      * a ref counting bug somewhere that's
8071      * breaking the nUsers == 0 => header on LRU
8072      * assumption */
8073     if (vp->header && queue_IsNotOnQueue(vp->header)) {
8074         Log("nUsers == 0, but header not on LRU\n");
8075         return 1;
8076     }
8077 #endif
8078
8079     old = (vp->header != NULL); /* old == volume already has a header */
8080
8081     if (programType != fileServer) {
8082         /* for volume utilities, we allocate volHeaders as needed */
8083         if (!vp->header) {
8084             hd = (struct volHeader *)calloc(1, sizeof(*vp->header));
8085             osi_Assert(hd != NULL);
8086             vp->header = hd;
8087             hd->back = vp;
8088 #ifdef AFS_DEMAND_ATTACH_FS
8089             V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8090 #endif
8091         }
8092     } else {
8093         /* for the fileserver, we keep a volume header cache */
8094         if (old) {
8095             /* the header we previously dropped in the lru is
8096              * still available. pull it off the lru and return */
8097             hd = vp->header;
8098             queue_Remove(hd);
8099             osi_Assert(hd->back == vp);
8100 #ifdef AFS_DEMAND_ATTACH_FS
8101             V_attachFlags(vp) &= ~(VOL_HDR_IN_LRU);
8102 #endif
8103         } else {
8104             hd = GetVolHeaderFromLRU();
8105             if (!hd) {
8106                 /* LRU is empty, so allocate a new volHeader
8107                  * this is probably indicative of a leak, so let the user know */
8108                 hd = (struct volHeader *)calloc(1, sizeof(struct volHeader));
8109                 osi_Assert(hd != NULL);
8110                 if (!everLogged) {
8111                     Log("****Allocated more volume headers, probably leak****\n");
8112                     everLogged = 1;
8113                 }
8114                 volume_hdr_LRU.stats.free++;
8115             }
8116             if (hd->back) {
8117                 /* this header used to belong to someone else.
8118                  * we'll need to check if the header needs to
8119                  * be sync'd out to disk */
8120
8121 #ifdef AFS_DEMAND_ATTACH_FS
8122                 /* GetVolHeaderFromLRU had better not give us back a header
8123                  * with a volume in exclusive state... */
8124                 osi_Assert(!VIsExclusiveState(V_attachState(hd->back)));
8125 #endif
8126
8127                 if (hd->diskstuff.inUse) {
8128                     /* volume was in use, so we'll need to sync
8129                      * its header to disk */
8130
8131 #ifdef AFS_DEMAND_ATTACH_FS
8132                     back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
8133                     vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
8134                     VCreateReservation_r(hd->back);
8135                     VOL_UNLOCK;
8136 #endif
8137
8138                     WriteVolumeHeader_r(&error, hd->back);
8139                     /* Ignore errors; catch them later */
8140
8141 #ifdef AFS_DEMAND_ATTACH_FS
8142                     VOL_LOCK;
8143 #endif
8144                 }
8145
8146                 hd->back->header = NULL;
8147 #ifdef AFS_DEMAND_ATTACH_FS
8148                 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
8149
8150                 if (hd->diskstuff.inUse) {
8151                     VChangeState_r(hd->back, back_save);
8152                     VCancelReservation_r(hd->back);
8153                     VChangeState_r(vp, vp_save);
8154                 }
8155 #endif
8156             } else {
8157                 volume_hdr_LRU.stats.attached++;
8158             }
8159             hd->back = vp;
8160             vp->header = hd;
8161 #ifdef AFS_DEMAND_ATTACH_FS
8162             V_attachFlags(vp) |= VOL_HDR_ATTACHED;
8163 #endif
8164         }
8165         volume_hdr_LRU.stats.free--;
8166         volume_hdr_LRU.stats.used++;
8167     }
8168     IncUInt64(&VStats.hdr_gets);
8169 #ifdef AFS_DEMAND_ATTACH_FS
8170     IncUInt64(&vp->stats.hdr_gets);
8171     vp->stats.last_hdr_get = FT_ApproxTime();
8172 #endif
8173     return old;
8174 }
8175
8176
8177 /**
8178  * make sure volume header is attached and contains valid cache data.
8179  *
8180  * @param[out] ec  outbound error code
8181  * @param[in]  vp  pointer to volume object
8182  *
8183  * @pre VOL_LOCK held.  For DAFS, lightweight ref held on vp.
8184  *
8185  * @post header cache entry attached, and loaded with valid data, or
8186  *       *ec is nonzero, and the header is released back into the LRU.
8187  *
8188  * @internal volume package internal use only.
8189  */
8190 static void
8191 LoadVolumeHeader(Error * ec, Volume * vp)
8192 {
8193 #ifdef AFS_DEMAND_ATTACH_FS
8194     VolState state_save;
8195     afs_uint32 now;
8196     *ec = 0;
8197
8198     if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8199         IncUInt64(&VStats.hdr_loads);
8200         state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
8201         VOL_UNLOCK;
8202
8203         ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8204                    sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8205                    VOLUMEINFOVERSION);
8206         IncUInt64(&vp->stats.hdr_loads);
8207         now = FT_ApproxTime();
8208
8209         VOL_LOCK;
8210         if (!*ec) {
8211             V_attachFlags(vp) |= VOL_HDR_LOADED;
8212             vp->stats.last_hdr_load = now;
8213         }
8214         VChangeState_r(vp, state_save);
8215     }
8216 #else /* AFS_DEMAND_ATTACH_FS */
8217     *ec = 0;
8218     if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
8219         IncUInt64(&VStats.hdr_loads);
8220
8221         ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
8222                    sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
8223                    VOLUMEINFOVERSION);
8224     }
8225 #endif /* AFS_DEMAND_ATTACH_FS */
8226     if (*ec) {
8227         /* maintain (nUsers==0) => header in LRU invariant */
8228         FreeVolumeHeader(vp);
8229     }
8230 }
8231
8232 /**
8233  * release a header cache entry back into the LRU list.
8234  *
8235  * @param[in] hd  pointer to volume header cache object
8236  *
8237  * @pre VOL_LOCK held.
8238  *
8239  * @post header cache object appended onto end of LRU list.
8240  *
8241  * @note only applicable to fileServer program type.
8242  *
8243  * @note used to place a header cache entry back into the
8244  *       LRU pool without invalidating it as a cache entry.
8245  *
8246  * @internal volume package internal use only.
8247  */
8248 static void
8249 ReleaseVolumeHeader(struct volHeader *hd)
8250 {
8251     if (programType != fileServer)
8252         return;
8253     if (!hd || queue_IsOnQueue(hd))     /* no header, or header already released */
8254         return;
8255     queue_Append(&volume_hdr_LRU, hd);
8256 #ifdef AFS_DEMAND_ATTACH_FS
8257     if (hd->back) {
8258         V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
8259     }
8260 #endif
8261     volume_hdr_LRU.stats.free++;
8262     volume_hdr_LRU.stats.used--;
8263 }
8264
8265 /**
8266  * free/invalidate a volume header cache entry.
8267  *
8268  * @param[in] vp  pointer to volume object
8269  *
8270  * @pre VOL_LOCK is held.
8271  *
8272  * @post For fileserver, header cache entry is returned to LRU, and it is
8273  *       invalidated as a cache entry.  For volume utilities, the header
8274  *       cache entry is freed.
8275  *
8276  * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
8277  *       whenever it is necessary to invalidate the header cache entry.
8278  *
8279  * @see ReleaseVolumeHeader
8280  *
8281  * @internal volume package internal use only.
8282  */
8283 static void
8284 FreeVolumeHeader(Volume * vp)
8285 {
8286     struct volHeader *hd = vp->header;
8287     if (!hd)
8288         return;
8289     if (programType == fileServer) {
8290         ReleaseVolumeHeader(hd);
8291         hd->back = NULL;
8292     } else {
8293         free(hd);
8294     }
8295 #ifdef AFS_DEMAND_ATTACH_FS
8296     V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
8297 #endif
8298     volume_hdr_LRU.stats.attached--;
8299     vp->header = NULL;
8300 }
8301
8302
8303 /***************************************************/
8304 /* Volume Hash Table routines                      */
8305 /***************************************************/
8306
8307 /**
8308  * set size of volume object hash table.
8309  *
8310  * @param[in] logsize   log(2) of desired hash table size
8311  *
8312  * @return operation status
8313  *    @retval 0 success
8314  *    @retval -1 failure
8315  *
8316  * @pre MUST be called prior to VInitVolumePackage2
8317  *
8318  * @post Volume Hash Table will have 2^logsize buckets
8319  */
8320 int
8321 VSetVolHashSize(int logsize)
8322 {
8323     /* 64 to 268435456 hash buckets seems like a reasonable range */
8324     if ((logsize < 6 ) || (logsize > 28)) {
8325         return -1;
8326     }
8327
8328     if (!VInit) {
8329         VolumeHashTable.Size = 1 << logsize;
8330         VolumeHashTable.Mask = VolumeHashTable.Size - 1;
8331     } else {
8332         /* we can't yet support runtime modification of this
8333          * parameter. we'll need a configuration rwlock to
8334          * make runtime modification feasible.... */
8335         return -1;
8336     }
8337     return 0;
8338 }
8339
8340 /**
8341  * initialize dynamic data structures for volume hash table.
8342  *
8343  * @post hash table is allocated, and fields are initialized.
8344  *
8345  * @internal volume package internal use only.
8346  */
8347 static void
8348 VInitVolumeHash(void)
8349 {
8350     int i;
8351
8352     VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size,
8353                                                            sizeof(VolumeHashChainHead));
8354     osi_Assert(VolumeHashTable.Table != NULL);
8355
8356     for (i=0; i < VolumeHashTable.Size; i++) {
8357         queue_Init(&VolumeHashTable.Table[i]);
8358 #ifdef AFS_DEMAND_ATTACH_FS
8359         CV_INIT(&VolumeHashTable.Table[i].chain_busy_cv, "vhash busy", CV_DEFAULT, 0);
8360 #endif /* AFS_DEMAND_ATTACH_FS */
8361     }
8362 }
8363
8364 /**
8365  * add a volume object to the hash table.
8366  *
8367  * @param[in] vp      pointer to volume object
8368  * @param[in] hashid  hash of volume id
8369  *
8370  * @pre VOL_LOCK is held.  For DAFS, caller must hold a lightweight
8371  *      reference on vp.
8372  *
8373  * @post volume is added to hash chain.
8374  *
8375  * @internal volume package internal use only.
8376  *
8377  * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8378  *       asynchronous hash chain reordering to finish.
8379  */
8380 static void
8381 AddVolumeToHashTable(Volume * vp, int hashid)
8382 {
8383     VolumeHashChainHead * head;
8384
8385     if (queue_IsOnQueue(vp))
8386         return;
8387
8388     head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
8389
8390 #ifdef AFS_DEMAND_ATTACH_FS
8391     /* wait for the hash chain to become available */
8392     VHashWait_r(head);
8393
8394     V_attachFlags(vp) |= VOL_IN_HASH;
8395     vp->chainCacheCheck = ++head->cacheCheck;
8396 #endif /* AFS_DEMAND_ATTACH_FS */
8397
8398     head->len++;
8399     vp->hashid = hashid;
8400     queue_Append(head, vp);
8401     vp->vnodeHashOffset = VolumeHashOffset_r();
8402 }
8403
8404 /**
8405  * delete a volume object from the hash table.
8406  *
8407  * @param[in] vp  pointer to volume object
8408  *
8409  * @pre VOL_LOCK is held.  For DAFS, caller must hold a lightweight
8410  *      reference on vp.
8411  *
8412  * @post volume is removed from hash chain.
8413  *
8414  * @internal volume package internal use only.
8415  *
8416  * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8417  *       asynchronous hash chain reordering to finish.
8418  */
8419 static void
8420 DeleteVolumeFromHashTable(Volume * vp)
8421 {
8422     VolumeHashChainHead * head;
8423
8424     if (!queue_IsOnQueue(vp))
8425         return;
8426
8427     head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
8428
8429 #ifdef AFS_DEMAND_ATTACH_FS
8430     /* wait for the hash chain to become available */
8431     VHashWait_r(head);
8432
8433     V_attachFlags(vp) &= ~(VOL_IN_HASH);
8434     head->cacheCheck++;
8435 #endif /* AFS_DEMAND_ATTACH_FS */
8436
8437     head->len--;
8438     queue_Remove(vp);
8439     /* do NOT reset hashid to zero, as the online
8440      * salvager package may need to know the volume id
8441      * after the volume is removed from the hash */
8442 }
8443
8444 /**
8445  * lookup a volume object in the hash table given a volume id.
8446  *
8447  * @param[out] ec        error code return
8448  * @param[in]  volumeId  volume id
8449  * @param[in]  hint      volume object which we believe could be the correct
8450                          mapping
8451  *
8452  * @return volume object pointer
8453  *    @retval NULL  no such volume id is registered with the hash table.
8454  *
8455  * @pre VOL_LOCK is held.  For DAFS, caller must hold a lightweight
8456         ref on hint.
8457  *
8458  * @post volume object with the given id is returned.  volume object and
8459  *       hash chain access statistics are updated.  hash chain may have
8460  *       been reordered.
8461  *
8462  * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
8463  *       asynchronous hash chain reordering operation to finish, or
8464  *       in order for us to perform an asynchronous chain reordering.
8465  *
8466  * @note Hash chain reorderings occur when the access count for the
8467  *       volume object being looked up exceeds the sum of the previous
8468  *       node's (the node ahead of it in the hash chain linked list)
8469  *       access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
8470  *
8471  * @note For DAFS, the hint parameter allows us to short-circuit if the
8472  *       cacheCheck fields match between the hash chain head and the
8473  *       hint volume object.
8474  */
8475 Volume *
8476 VLookupVolume_r(Error * ec, VolId volumeId, Volume * hint)
8477 {
8478     int looks = 0;
8479     Volume * vp, *np;
8480 #ifdef AFS_DEMAND_ATTACH_FS
8481     Volume *pp;
8482 #endif
8483     VolumeHashChainHead * head;
8484     *ec = 0;
8485
8486     head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
8487
8488 #ifdef AFS_DEMAND_ATTACH_FS
8489     /* wait for the hash chain to become available */
8490     VHashWait_r(head);
8491
8492     /* check to see if we can short circuit without walking the hash chain */
8493     if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
8494         IncUInt64(&hint->stats.hash_short_circuits);
8495         return hint;
8496     }
8497 #endif /* AFS_DEMAND_ATTACH_FS */
8498
8499     /* someday we need to either do per-chain locks, RWlocks,
8500      * or both for volhash access.
8501      * (and move to a data structure with better cache locality) */
8502
8503     /* search the chain for this volume id */
8504     for(queue_Scan(head, vp, np, Volume)) {
8505         looks++;
8506         if (vp->hashid == volumeId) {
8507             break;
8508         }
8509     }
8510
8511     if (queue_IsEnd(head, vp)) {
8512         vp = NULL;
8513     }
8514
8515 #ifdef AFS_DEMAND_ATTACH_FS
8516     /* update hash chain statistics */
8517     {
8518         afs_uint64 lks;
8519         FillInt64(lks, 0, looks);
8520         AddUInt64(head->looks, lks, &head->looks);
8521         AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
8522         IncUInt64(&head->gets);
8523     }
8524
8525     if (vp) {
8526         afs_uint64 thresh;
8527         IncUInt64(&vp->stats.hash_lookups);
8528
8529         /* for demand attach fileserver, we permit occasional hash chain reordering
8530          * so that frequently looked up volumes move towards the head of the chain */
8531         pp = queue_Prev(vp, Volume);
8532         if (!queue_IsEnd(head, pp)) {
8533             FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
8534             AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
8535             if (GEInt64(vp->stats.hash_lookups, thresh)) {
8536                 VReorderHash_r(head, pp, vp);
8537             }
8538         }
8539
8540         /* update the short-circuit cache check */
8541         vp->chainCacheCheck = head->cacheCheck;
8542     }
8543 #endif /* AFS_DEMAND_ATTACH_FS */
8544
8545     return vp;
8546 }
8547
8548 #ifdef AFS_DEMAND_ATTACH_FS
8549 /* perform volume hash chain reordering.
8550  *
8551  * advance a subchain beginning at vp ahead of
8552  * the adjacent subchain ending at pp */
8553 static void
8554 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
8555 {
8556     Volume *tp, *np, *lp;
8557     afs_uint64 move_thresh;
8558
8559     /* this should never be called if the chain is already busy, so
8560      * no need to wait for other exclusive chain ops to finish */
8561
8562     /* this is a rather heavy set of operations,
8563      * so let's set the chain busy flag and drop
8564      * the vol_glock */
8565     VHashBeginExclusive_r(head);
8566     VOL_UNLOCK;
8567
8568     /* scan forward in the chain from vp looking for the last element
8569      * in the chain we want to advance */
8570     FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
8571     AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
8572     for(queue_ScanFrom(head, vp, tp, np, Volume)) {
8573         if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
8574             break;
8575         }
8576     }
8577     lp = queue_Prev(tp, Volume);
8578
8579     /* scan backwards from pp to determine where to splice and
8580      * insert the subchain we're advancing */
8581     for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
8582         if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
8583             break;
8584         }
8585     }
8586     tp = queue_Next(tp, Volume);
8587
8588     /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
8589     queue_MoveChainBefore(tp,vp,lp);
8590
8591     VOL_LOCK;
8592     IncUInt64(&VStats.hash_reorders);
8593     head->cacheCheck++;
8594     IncUInt64(&head->reorders);
8595
8596     /* wake up any threads waiting for the hash chain */
8597     VHashEndExclusive_r(head);
8598 }
8599
8600
8601 /* demand-attach fs volume hash
8602  * asynchronous exclusive operations */
8603
8604 /**
8605  * begin an asynchronous exclusive operation on a volume hash chain.
8606  *
8607  * @param[in] head   pointer to volume hash chain head object
8608  *
8609  * @pre VOL_LOCK held.  hash chain is quiescent.
8610  *
8611  * @post hash chain marked busy.
8612  *
8613  * @note this interface is used in conjunction with VHashEndExclusive_r and
8614  *       VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8615  *       volume hash chain.  Its main use case is hash chain reordering, which
8616  *       has the potential to be a highly latent operation.
8617  *
8618  * @see VHashEndExclusive_r
8619  * @see VHashWait_r
8620  *
8621  * @note DAFS only
8622  *
8623  * @internal volume package internal use only.
8624  */
8625 static void
8626 VHashBeginExclusive_r(VolumeHashChainHead * head)
8627 {
8628     osi_Assert(head->busy == 0);
8629     head->busy = 1;
8630 }
8631
8632 /**
8633  * relinquish exclusive ownership of a volume hash chain.
8634  *
8635  * @param[in] head   pointer to volume hash chain head object
8636  *
8637  * @pre VOL_LOCK held.  thread owns the hash chain exclusively.
8638  *
8639  * @post hash chain is marked quiescent.  threads awaiting use of
8640  *       chain are awakened.
8641  *
8642  * @see VHashBeginExclusive_r
8643  * @see VHashWait_r
8644  *
8645  * @note DAFS only
8646  *
8647  * @internal volume package internal use only.
8648  */
8649 static void
8650 VHashEndExclusive_r(VolumeHashChainHead * head)
8651 {
8652     osi_Assert(head->busy);
8653     head->busy = 0;
8654     CV_BROADCAST(&head->chain_busy_cv);
8655 }
8656
8657 /**
8658  * wait for all asynchronous operations on a hash chain to complete.
8659  *
8660  * @param[in] head   pointer to volume hash chain head object
8661  *
8662  * @pre VOL_LOCK held.
8663  *
8664  * @post hash chain object is quiescent.
8665  *
8666  * @see VHashBeginExclusive_r
8667  * @see VHashEndExclusive_r
8668  *
8669  * @note DAFS only
8670  *
8671  * @note This interface should be called before any attempt to
8672  *       traverse the hash chain.  It is permissible for a thread
8673  *       to gain exclusive access to the chain, and then perform
8674  *       latent operations on the chain asynchronously wrt the
8675  *       VOL_LOCK.
8676  *
8677  * @warning if waiting is necessary, VOL_LOCK is dropped
8678  *
8679  * @internal volume package internal use only.
8680  */
8681 static void
8682 VHashWait_r(VolumeHashChainHead * head)
8683 {
8684     while (head->busy) {
8685         VOL_CV_WAIT(&head->chain_busy_cv);
8686     }
8687 }
8688 #endif /* AFS_DEMAND_ATTACH_FS */
8689
8690
8691 /***************************************************/
8692 /* Volume by Partition List routines               */
8693 /***************************************************/
8694
8695 /*
8696  * demand attach fileserver adds a
8697  * linked list of volumes to each
8698  * partition object, thus allowing
8699  * for quick enumeration of all
8700  * volumes on a partition
8701  */
8702
8703 #ifdef AFS_DEMAND_ATTACH_FS
8704 /**
8705  * add a volume to its disk partition VByPList.
8706  *
8707  * @param[in] vp  pointer to volume object
8708  *
8709  * @pre either the disk partition VByPList is owned exclusively
8710  *      by the calling thread, or the list is quiescent and
8711  *      VOL_LOCK is held.
8712  *
8713  * @post volume is added to disk partition VByPList
8714  *
8715  * @note DAFS only
8716  *
8717  * @warning it is the caller's responsibility to ensure list
8718  *          quiescence.
8719  *
8720  * @see VVByPListWait_r
8721  * @see VVByPListBeginExclusive_r
8722  * @see VVByPListEndExclusive_r
8723  *
8724  * @internal volume package internal use only.
8725  */
8726 static void
8727 AddVolumeToVByPList_r(Volume * vp)
8728 {
8729     if (queue_IsNotOnQueue(&vp->vol_list)) {
8730         queue_Append(&vp->partition->vol_list, &vp->vol_list);
8731         V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
8732         vp->partition->vol_list.len++;
8733     }
8734 }
8735
8736 /**
8737  * delete a volume from its disk partition VByPList.
8738  *
8739  * @param[in] vp  pointer to volume object
8740  *
8741  * @pre either the disk partition VByPList is owned exclusively
8742  *      by the calling thread, or the list is quiescent and
8743  *      VOL_LOCK is held.
8744  *
8745  * @post volume is removed from the disk partition VByPList
8746  *
8747  * @note DAFS only
8748  *
8749  * @warning it is the caller's responsibility to ensure list
8750  *          quiescence.
8751  *
8752  * @see VVByPListWait_r
8753  * @see VVByPListBeginExclusive_r
8754  * @see VVByPListEndExclusive_r
8755  *
8756  * @internal volume package internal use only.
8757  */
8758 static void
8759 DeleteVolumeFromVByPList_r(Volume * vp)
8760 {
8761     if (queue_IsOnQueue(&vp->vol_list)) {
8762         queue_Remove(&vp->vol_list);
8763         V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
8764         vp->partition->vol_list.len--;
8765     }
8766 }
8767
8768 /**
8769  * begin an asynchronous exclusive operation on a VByPList.
8770  *
8771  * @param[in] dp   pointer to disk partition object
8772  *
8773  * @pre VOL_LOCK held.  VByPList is quiescent.
8774  *
8775  * @post VByPList marked busy.
8776  *
8777  * @note this interface is used in conjunction with VVByPListEndExclusive_r and
8778  *       VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
8779  *       VByPList.
8780  *
8781  * @see VVByPListEndExclusive_r
8782  * @see VVByPListWait_r
8783  *
8784  * @note DAFS only
8785  *
8786  * @internal volume package internal use only.
8787  */
8788 /* take exclusive control over the list */
8789 static void
8790 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
8791 {
8792     osi_Assert(dp->vol_list.busy == 0);
8793     dp->vol_list.busy = 1;
8794 }
8795
8796 /**
8797  * relinquish exclusive ownership of a VByPList.
8798  *
8799  * @param[in] dp   pointer to disk partition object
8800  *
8801  * @pre VOL_LOCK held.  thread owns the VByPList exclusively.
8802  *
8803  * @post VByPList is marked quiescent.  threads awaiting use of
8804  *       the list are awakened.
8805  *
8806  * @see VVByPListBeginExclusive_r
8807  * @see VVByPListWait_r
8808  *
8809  * @note DAFS only
8810  *
8811  * @internal volume package internal use only.
8812  */
8813 static void
8814 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
8815 {
8816     osi_Assert(dp->vol_list.busy);
8817     dp->vol_list.busy = 0;
8818     CV_BROADCAST(&dp->vol_list.cv);
8819 }
8820
8821 /**
8822  * wait for all asynchronous operations on a VByPList to complete.
8823  *
8824  * @param[in] dp  pointer to disk partition object
8825  *
8826  * @pre VOL_LOCK is held.
8827  *
8828  * @post disk partition's VByP list is quiescent
8829  *
8830  * @note DAFS only
8831  *
8832  * @note This interface should be called before any attempt to
8833  *       traverse the VByPList.  It is permissible for a thread
8834  *       to gain exclusive access to the list, and then perform
8835  *       latent operations on the list asynchronously wrt the
8836  *       VOL_LOCK.
8837  *
8838  * @warning if waiting is necessary, VOL_LOCK is dropped
8839  *
8840  * @see VVByPListEndExclusive_r
8841  * @see VVByPListBeginExclusive_r
8842  *
8843  * @internal volume package internal use only.
8844  */
8845 static void
8846 VVByPListWait_r(struct DiskPartition64 * dp)
8847 {
8848     while (dp->vol_list.busy) {
8849         VOL_CV_WAIT(&dp->vol_list.cv);
8850     }
8851 }
8852 #endif /* AFS_DEMAND_ATTACH_FS */
8853
8854 /***************************************************/
8855 /* Volume Cache Statistics routines                */
8856 /***************************************************/
8857
8858 void
8859 VPrintCacheStats_r(void)
8860 {
8861     struct VnodeClassInfo *vcp;
8862     vcp = &VnodeClassInfo[vLarge];
8863     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);
8864     vcp = &VnodeClassInfo[vSmall];
8865     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);
8866     Log("Volume header cache, %d entries, %"AFS_INT64_FMT" gets, "
8867         "%"AFS_INT64_FMT" replacements\n",
8868         VStats.hdr_cache_size, VStats.hdr_gets, VStats.hdr_loads);
8869 }
8870
8871 void
8872 VPrintCacheStats(void)
8873 {
8874     VOL_LOCK;
8875     VPrintCacheStats_r();
8876     VOL_UNLOCK;
8877 }
8878
8879 #ifdef AFS_DEMAND_ATTACH_FS
8880 static double
8881 UInt64ToDouble(afs_uint64 * x)
8882 {
8883     static double c32 = 4.0 * 1.073741824 * 1000000000.0;
8884     afs_uint32 h, l;
8885     SplitInt64(*x, h, l);
8886     return (((double)h) * c32) + ((double) l);
8887 }
8888
8889 static char *
8890 DoubleToPrintable(double x, char * buf, int len)
8891 {
8892     static double billion = 1000000000.0;
8893     afs_uint32 y[3];
8894
8895     y[0] = (afs_uint32) (x / (billion * billion));
8896     y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
8897     y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
8898
8899     if (y[0]) {
8900         snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
8901     } else if (y[1]) {
8902         snprintf(buf, len, "%d%09d", y[1], y[2]);
8903     } else {
8904         snprintf(buf, len, "%d", y[2]);
8905     }
8906     buf[len-1] = '\0';
8907     return buf;
8908 }
8909
8910 struct VLRUExtStatsEntry {
8911     VolumeId volid;
8912 };
8913
8914 struct VLRUExtStats {
8915     afs_uint32 len;
8916     afs_uint32 used;
8917     struct {
8918         afs_uint32 start;
8919         afs_uint32 len;
8920     } queue_info[VLRU_QUEUE_INVALID];
8921     struct VLRUExtStatsEntry * vec;
8922 };
8923
8924 /**
8925  * add a 256-entry fudge factor onto the vector in case state changes
8926  * out from under us.
8927  */
8928 #define VLRU_EXT_STATS_VEC_LEN_FUDGE   256
8929
8930 /**
8931  * collect extended statistics for the VLRU subsystem.
8932  *
8933  * @param[out] stats  pointer to stats structure to be populated
8934  * @param[in] nvols   number of volumes currently known to exist
8935  *
8936  * @pre VOL_LOCK held
8937  *
8938  * @post stats->vec allocated and populated
8939  *
8940  * @return operation status
8941  *    @retval 0 success
8942  *    @retval 1 failure
8943  */
8944 static int
8945 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
8946 {
8947     afs_uint32 cur, idx, len;
8948     struct rx_queue * qp, * nqp;
8949     Volume * vp;
8950     struct VLRUExtStatsEntry * vec;
8951
8952     len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
8953     vec = stats->vec = calloc(len,
8954                               sizeof(struct VLRUExtStatsEntry));
8955     if (vec == NULL) {
8956         return 1;
8957     }
8958
8959     cur = 0;
8960     for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
8961         VLRU_Wait_r(&volume_LRU.q[idx]);
8962         VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
8963         VOL_UNLOCK;
8964
8965         stats->queue_info[idx].start = cur;
8966
8967         for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
8968             if (cur == len) {
8969                 /* out of space in vec */
8970                 break;
8971             }
8972             vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
8973             vec[cur].volid = vp->hashid;
8974             cur++;
8975         }
8976
8977         stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
8978
8979         VOL_LOCK;
8980         VLRU_EndExclusive_r(&volume_LRU.q[idx]);
8981     }
8982
8983     stats->len = len;
8984     stats->used = cur;
8985     return 0;
8986 }
8987
8988 #define ENUMTOSTRING(en)  #en
8989 #define ENUMCASE(en) \
8990     case en: return ENUMTOSTRING(en)
8991
8992 static char *
8993 vlru_idx_to_string(int idx)
8994 {
8995     switch (idx) {
8996         ENUMCASE(VLRU_QUEUE_NEW);
8997         ENUMCASE(VLRU_QUEUE_MID);
8998         ENUMCASE(VLRU_QUEUE_OLD);
8999         ENUMCASE(VLRU_QUEUE_CANDIDATE);
9000         ENUMCASE(VLRU_QUEUE_HELD);
9001         ENUMCASE(VLRU_QUEUE_INVALID);
9002     default:
9003         return "**UNKNOWN**";
9004     }
9005 }
9006
9007 void
9008 VPrintExtendedCacheStats_r(int flags)
9009 {
9010     int i;
9011     afs_uint32 vol_sum = 0;
9012     struct stats {
9013         double min;
9014         double max;
9015         double sum;
9016         double avg;
9017     };
9018     struct stats looks, gets, reorders, len;
9019     struct stats ch_looks, ch_gets, ch_reorders;
9020     char pr_buf[4][32];
9021     VolumeHashChainHead *head;
9022     Volume *vp, *np;
9023     struct VLRUExtStats vlru_stats;
9024
9025     /* zero out stats */
9026     memset(&looks, 0, sizeof(struct stats));
9027     memset(&gets, 0, sizeof(struct stats));
9028     memset(&reorders, 0, sizeof(struct stats));
9029     memset(&len, 0, sizeof(struct stats));
9030     memset(&ch_looks, 0, sizeof(struct stats));
9031     memset(&ch_gets, 0, sizeof(struct stats));
9032     memset(&ch_reorders, 0, sizeof(struct stats));
9033
9034     for (i = 0; i < VolumeHashTable.Size; i++) {
9035         head = &VolumeHashTable.Table[i];
9036
9037         VHashWait_r(head);
9038         VHashBeginExclusive_r(head);
9039         VOL_UNLOCK;
9040
9041         ch_looks.sum    = UInt64ToDouble(&head->looks);
9042         ch_gets.sum     = UInt64ToDouble(&head->gets);
9043         ch_reorders.sum = UInt64ToDouble(&head->reorders);
9044
9045         /* update global statistics */
9046         {
9047             looks.sum    += ch_looks.sum;
9048             gets.sum     += ch_gets.sum;
9049             reorders.sum += ch_reorders.sum;
9050             len.sum      += (double)head->len;
9051             vol_sum      += head->len;
9052
9053             if (i == 0) {
9054                 len.min      = (double) head->len;
9055                 len.max      = (double) head->len;
9056                 looks.min    = ch_looks.sum;
9057                 looks.max    = ch_looks.sum;
9058                 gets.min     = ch_gets.sum;
9059                 gets.max     = ch_gets.sum;
9060                 reorders.min = ch_reorders.sum;
9061                 reorders.max = ch_reorders.sum;
9062             } else {
9063                 if (((double)head->len) < len.min)
9064                     len.min = (double) head->len;
9065                 if (((double)head->len) > len.max)
9066                     len.max = (double) head->len;
9067                 if (ch_looks.sum < looks.min)
9068                     looks.min = ch_looks.sum;
9069                 else if (ch_looks.sum > looks.max)
9070                     looks.max = ch_looks.sum;
9071                 if (ch_gets.sum < gets.min)
9072                     gets.min = ch_gets.sum;
9073                 else if (ch_gets.sum > gets.max)
9074                     gets.max = ch_gets.sum;
9075                 if (ch_reorders.sum < reorders.min)
9076                     reorders.min = ch_reorders.sum;
9077                 else if (ch_reorders.sum > reorders.max)
9078                     reorders.max = ch_reorders.sum;
9079             }
9080         }
9081
9082         if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
9083             /* compute detailed per-chain stats */
9084             struct stats hdr_loads, hdr_gets;
9085             double v_looks, v_loads, v_gets;
9086
9087             /* initialize stats with data from first element in chain */
9088             vp = queue_First(head, Volume);
9089             v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
9090             v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
9091             v_gets  = UInt64ToDouble(&vp->stats.hdr_gets);
9092             ch_gets.min = ch_gets.max = v_looks;
9093             hdr_loads.min = hdr_loads.max = v_loads;
9094             hdr_gets.min = hdr_gets.max = v_gets;
9095             hdr_loads.sum = hdr_gets.sum = 0;
9096
9097             vp = queue_Next(vp, Volume);
9098
9099             /* pull in stats from remaining elements in chain */
9100             for (queue_ScanFrom(head, vp, vp, np, Volume)) {
9101                 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
9102                 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
9103                 v_gets  = UInt64ToDouble(&vp->stats.hdr_gets);
9104
9105                 hdr_loads.sum += v_loads;
9106                 hdr_gets.sum += v_gets;
9107
9108                 if (v_looks < ch_gets.min)
9109                     ch_gets.min = v_looks;
9110                 else if (v_looks > ch_gets.max)
9111                     ch_gets.max = v_looks;
9112
9113                 if (v_loads < hdr_loads.min)
9114                     hdr_loads.min = v_loads;
9115                 else if (v_loads > hdr_loads.max)
9116                     hdr_loads.max = v_loads;
9117
9118                 if (v_gets < hdr_gets.min)
9119                     hdr_gets.min = v_gets;
9120                 else if (v_gets > hdr_gets.max)
9121                     hdr_gets.max = v_gets;
9122             }
9123
9124             /* compute per-chain averages */
9125             ch_gets.avg = ch_gets.sum / ((double)head->len);
9126             hdr_loads.avg = hdr_loads.sum / ((double)head->len);
9127             hdr_gets.avg = hdr_gets.sum / ((double)head->len);
9128
9129             /* dump per-chain stats */
9130             Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
9131                 i, head->len,
9132                 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9133                 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
9134             Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
9135                 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9136                 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9137                 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9138                 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9139             Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
9140                 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
9141                 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
9142                 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9143                 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9144             Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
9145                 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
9146                 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
9147                 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
9148                 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
9149         } else if (flags & VOL_STATS_PER_CHAIN) {
9150             /* dump simple per-chain stats */
9151             Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
9152                 i, head->len,
9153                 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
9154                 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
9155                 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
9156         }
9157
9158         VOL_LOCK;
9159         VHashEndExclusive_r(head);
9160     }
9161
9162     VOL_UNLOCK;
9163
9164     /* compute global averages */
9165     len.avg      = len.sum      / ((double)VolumeHashTable.Size);
9166     looks.avg    = looks.sum    / ((double)VolumeHashTable.Size);
9167     gets.avg     = gets.sum     / ((double)VolumeHashTable.Size);
9168     reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
9169
9170     /* dump global stats */
9171     Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
9172     Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
9173         DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
9174         DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
9175         DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
9176         DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
9177     Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
9178         DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
9179         DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
9180         DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
9181         DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
9182     Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
9183         DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
9184         DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
9185         DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
9186         DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
9187     Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
9188         DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
9189         DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
9190         DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
9191         DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
9192
9193     /* print extended disk related statistics */
9194     {
9195         struct DiskPartition64 * diskP;
9196         afs_uint32 vol_count[VOLMAXPARTS+1];
9197         byte part_exists[VOLMAXPARTS+1];
9198         Device id;
9199         int i;
9200
9201         memset(vol_count, 0, sizeof(vol_count));
9202         memset(part_exists, 0, sizeof(part_exists));
9203
9204         VOL_LOCK;
9205
9206         for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
9207             id = diskP->index;
9208             vol_count[id] = diskP->vol_list.len;
9209             part_exists[id] = 1;
9210         }
9211
9212         VOL_UNLOCK;
9213         for (i = 0; i <= VOLMAXPARTS; i++) {
9214             if (part_exists[i]) {
9215                 /* XXX while this is currently safe, it is a violation
9216                  *     of the VGetPartitionById_r interface contract. */
9217                 diskP = VGetPartitionById_r(i, 0);
9218                 if (diskP) {
9219                     Log("Partition %s has %d online volumes\n",
9220                         VPartitionPath(diskP), diskP->vol_list.len);
9221                 }
9222             }
9223         }
9224         VOL_LOCK;
9225     }
9226
9227     /* print extended VLRU statistics */
9228     if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
9229         afs_uint32 idx, cur, lpos;
9230         VolumeId line[5];
9231
9232         VOL_UNLOCK;
9233
9234         Log("VLRU State Dump:\n\n");
9235
9236         for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
9237             Log("\t%s:\n", vlru_idx_to_string(idx));
9238
9239             lpos = 0;
9240             for (cur = vlru_stats.queue_info[idx].start;
9241                  cur < vlru_stats.queue_info[idx].len;
9242                  cur++) {
9243                 line[lpos++] = vlru_stats.vec[cur].volid;
9244                 if (lpos==5) {
9245                     Log("\t\t%u, %u, %u, %u, %u,\n",
9246                         line[0], line[1], line[2], line[3], line[4]);
9247                     lpos = 0;
9248                 }
9249             }
9250
9251             if (lpos) {
9252                 while (lpos < 5) {
9253                     line[lpos++] = 0;
9254                 }
9255                 Log("\t\t%u, %u, %u, %u, %u\n",
9256                     line[0], line[1], line[2], line[3], line[4]);
9257             }
9258             Log("\n");
9259         }
9260
9261         free(vlru_stats.vec);
9262
9263         VOL_LOCK;
9264     }
9265 }
9266
9267 void
9268 VPrintExtendedCacheStats(int flags)
9269 {
9270     VOL_LOCK;
9271     VPrintExtendedCacheStats_r(flags);
9272     VOL_UNLOCK;
9273 }
9274 #endif /* AFS_DEMAND_ATTACH_FS */
9275
9276 afs_int32
9277 VCanScheduleSalvage(void)
9278 {
9279     return vol_opts.canScheduleSalvage;
9280 }
9281
9282 afs_int32
9283 VCanUseFSSYNC(void)
9284 {
9285     return vol_opts.canUseFSSYNC;
9286 }
9287
9288 afs_int32
9289 VCanUseSALVSYNC(void)
9290 {
9291     return vol_opts.canUseSALVSYNC;
9292 }
9293
9294 afs_int32
9295 VCanUnsafeAttach(void)
9296 {
9297     return vol_opts.unsafe_attach;
9298 }