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