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