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