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