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