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