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