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