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