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