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