DAFS: Fix SYNC_FAILED VScheduleSalvage_r log
[openafs.git] / src / vol / volume.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  *
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  *
9  * Portions Copyright (c) 2005-2008 Sine Nomine Associates
10  */
11
12 /* 1/1/89: NB:  this stuff is all going to be replaced.  Don't take it too seriously */
13 /*
14
15         System:         VICE-TWO
16         Module:         volume.c
17         Institution:    The Information Technology Center, Carnegie-Mellon University
18
19  */
20
21 #include <afsconfig.h>
22 #include <afs/param.h>
23
24 #include <roken.h>
25 #include <afs/opr.h>
26
27 #include <ctype.h>
28 #include <stddef.h>
29
30 #ifdef HAVE_SYS_FILE_H
31 #include <sys/file.h>
32 #endif
33
34 #include <rx/xdr.h>
35 #include <afs/afsint.h>
36
37 #ifndef AFS_NT40_ENV
38 #if !defined(AFS_SGI_ENV)
39 #ifdef  AFS_OSF_ENV
40 #include <ufs/fs.h>
41 #else /* AFS_OSF_ENV */
42 #ifdef AFS_VFSINCL_ENV
43 #define VFS
44 #ifdef  AFS_SUN5_ENV
45 #include <sys/fs/ufs_fs.h>
46 #else
47 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
48 #include <ufs/ufs/dinode.h>
49 #include <ufs/ffs/fs.h>
50 #else
51 #include <ufs/fs.h>
52 #endif
53 #endif
54 #else /* AFS_VFSINCL_ENV */
55 #if !defined(AFS_AIX_ENV) && !defined(AFS_LINUX20_ENV) && !defined(AFS_XBSD_ENV) && !defined(AFS_DARWIN_ENV)
56 #include <sys/fs.h>
57 #endif
58 #endif /* AFS_VFSINCL_ENV */
59 #endif /* AFS_OSF_ENV */
60 #endif /* AFS_SGI_ENV */
61 #endif /* !AFS_NT40_ENV */
62
63 #ifdef  AFS_AIX_ENV
64 #include <sys/vfs.h>
65 #else
66 #ifdef  AFS_HPUX_ENV
67 #include <mntent.h>
68 #else
69 #if     defined(AFS_SUN_ENV) || defined(AFS_SUN5_ENV)
70 #ifdef  AFS_SUN5_ENV
71 #include <sys/mnttab.h>
72 #include <sys/mntent.h>
73 #else
74 #include <mntent.h>
75 #endif
76 #else
77 #ifndef AFS_NT40_ENV
78 #if defined(AFS_SGI_ENV)
79 #include <mntent.h>
80 #else
81 #ifndef AFS_LINUX20_ENV
82 #include <fstab.h>              /* Need to find in libc 5, present in libc 6 */
83 #endif
84 #endif
85 #endif /* AFS_SGI_ENV */
86 #endif
87 #endif /* AFS_HPUX_ENV */
88 #endif
89
90 #include "nfs.h"
91 #include <afs/errors.h>
92 #include "lock.h"
93 #include "lwp.h"
94 #include <afs/afssyscalls.h>
95 #include "ihandle.h"
96 #include <afs/afsutil.h>
97 #include "daemon_com.h"
98 #include "fssync.h"
99 #include "salvsync.h"
100 #include "vnode.h"
101 #include "volume.h"
102 #include "partition.h"
103 #include "volume_inline.h"
104 #include "common.h"
105 #include "vutils.h"
106 #include <afs/dir.h>
107
108 #ifdef AFS_PTHREAD_ENV
109 pthread_mutex_t vol_glock_mutex;
110 pthread_mutex_t vol_trans_mutex;
111 pthread_cond_t vol_put_volume_cond;
112 pthread_cond_t vol_sleep_cond;
113 pthread_cond_t vol_init_attach_cond;
114 pthread_cond_t vol_vinit_cond;
115 int vol_attach_threads = 1;
116 #endif /* AFS_PTHREAD_ENV */
117
118 /* start-time configurable I/O parameters */
119 ih_init_params vol_io_params;
120
121 #ifdef AFS_DEMAND_ATTACH_FS
122 pthread_mutex_t vol_salvsync_mutex;
123
124 /*
125  * Set this to 1 to disallow SALVSYNC communication in all threads; used
126  * during shutdown, since the salvageserver may have gone away.
127  */
128 static volatile sig_atomic_t vol_disallow_salvsync = 0;
129 #endif /* AFS_DEMAND_ATTACH_FS */
130
131 /**
132  * has VShutdown_r been called / is VShutdown_r running?
133  */
134 static int vol_shutting_down = 0;
135
136 #ifdef  AFS_OSF_ENV
137 extern void *calloc(), *realloc();
138 #endif
139
140 /* Forward declarations */
141 static Volume *attach2(Error * ec, VolId volumeId, char *path,
142                        struct DiskPartition64 *partp, Volume * vp,
143                        int isbusy, int mode, int *acheckedOut);
144 static void ReallyFreeVolume(Volume * vp);
145 #ifdef AFS_DEMAND_ATTACH_FS
146 static void FreeVolume(Volume * vp);
147 #else /* !AFS_DEMAND_ATTACH_FS */
148 #define FreeVolume(vp) ReallyFreeVolume(vp)
149 static void VScanUpdateList(void);
150 #endif /* !AFS_DEMAND_ATTACH_FS */
151 static void VInitVolumeHeaderCache(afs_uint32 howMany);
152 static int GetVolumeHeader(Volume * vp);
153 static void ReleaseVolumeHeader(struct volHeader *hd);
154 static void FreeVolumeHeader(Volume * vp);
155 static void AddVolumeToHashTable(Volume * vp, int hashid);
156 static void DeleteVolumeFromHashTable(Volume * vp);
157 #if 0
158 static int VHold(Volume * vp);
159 #endif
160 static int VHold_r(Volume * vp);
161 static void VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class);
162 static void VReleaseVolumeHandles_r(Volume * vp);
163 static void VCloseVolumeHandles_r(Volume * vp);
164 static void LoadVolumeHeader(Error * ec, Volume * vp);
165 static int VCheckOffline(Volume * vp);
166 static int VCheckDetach(Volume * vp);
167 static Volume * GetVolume(Error * ec, Error * client_ec, VolId volumeId,
168                           Volume * hint, const struct timespec *ts);
169
170 int LogLevel;                   /* Vice loglevel--not defined as extern so that it will be
171                                  * defined when not linked with vice, XXXX */
172 ProgramType programType;        /* The type of program using the package */
173 static VolumePackageOptions vol_opts;
174
175 /* extended volume package statistics */
176 VolPkgStats VStats;
177
178 #ifdef VOL_LOCK_DEBUG
179 pthread_t vol_glock_holder = 0;
180 #endif
181
182
183 #define VOLUME_BITMAP_GROWSIZE  16      /* bytes, => 128vnodes */
184                                         /* Must be a multiple of 4 (1 word) !! */
185
186 /* this parameter needs to be tunable at runtime.
187  * 128 was really inadequate for largish servers -- at 16384 volumes this
188  * puts average chain length at 128, thus an average 65 deref's to find a volptr.
189  * talk about bad spatial locality...
190  *
191  * an AVL or splay tree might work a lot better, but we'll just increase
192  * the default hash table size for now
193  */
194 #define DEFAULT_VOLUME_HASH_SIZE 256   /* Must be a power of 2!! */
195 #define DEFAULT_VOLUME_HASH_MASK (DEFAULT_VOLUME_HASH_SIZE-1)
196 #define VOLUME_HASH(volumeId) (volumeId&(VolumeHashTable.Mask))
197
198 /*
199  * turn volume hash chains into partially ordered lists.
200  * when the threshold is exceeded between two adjacent elements,
201  * perform a chain rebalancing operation.
202  *
203  * keep the threshold high in order to keep cache line invalidates
204  * low "enough" on SMPs
205  */
206 #define VOLUME_HASH_REORDER_THRESHOLD 200
207
208 /*
209  * when possible, don't just reorder single elements, but reorder
210  * entire chains of elements at once.  a chain of elements that
211  * exceed the element previous to the pivot by at least CHAIN_THRESH
212  * accesses are moved in front of the chain whose elements have at
213  * least CHAIN_THRESH less accesses than the pivot element
214  */
215 #define VOLUME_HASH_REORDER_CHAIN_THRESH (VOLUME_HASH_REORDER_THRESHOLD / 2)
216
217 #include "rx/rx_queue.h"
218
219
220 VolumeHashTable_t VolumeHashTable = {
221     DEFAULT_VOLUME_HASH_SIZE,
222     DEFAULT_VOLUME_HASH_MASK,
223     NULL
224 };
225
226
227 static void VInitVolumeHash(void);
228
229
230 #ifndef AFS_HAVE_FFS
231 /* This macro is used where an ffs() call does not exist. Was in util/ffs.c */
232 ffs(x)
233 {
234     afs_int32 ffs_i;
235     afs_int32 ffs_tmp = x;
236     if (ffs_tmp == 0)
237         return (-1);
238     else
239         for (ffs_i = 1;; ffs_i++) {
240             if (ffs_tmp & 1)
241                 return (ffs_i);
242             else
243                 ffs_tmp >>= 1;
244         }
245 }
246 #endif /* !AFS_HAVE_FFS */
247
248 #ifdef AFS_PTHREAD_ENV
249 /**
250  * disk partition queue element
251  */
252 typedef struct diskpartition_queue_t {
253     struct rx_queue queue;             /**< queue header */
254     struct DiskPartition64 *diskP;     /**< disk partition table entry */
255 } diskpartition_queue_t;
256
257 #ifndef AFS_DEMAND_ATTACH_FS
258
259 typedef struct vinitvolumepackage_thread_t {
260     struct rx_queue queue;
261     pthread_cond_t thread_done_cv;
262     int n_threads_complete;
263 } vinitvolumepackage_thread_t;
264 static void * VInitVolumePackageThread(void * args);
265
266 #else  /* !AFS_DEMAND_ATTTACH_FS */
267 #define VINIT_BATCH_MAX_SIZE 512
268
269 /**
270  * disk partition work queue
271  */
272 struct partition_queue {
273     struct rx_queue head;              /**< diskpartition_queue_t queue */
274     pthread_mutex_t mutex;
275     pthread_cond_t cv;
276 };
277
278 /**
279  * volumes parameters for preattach
280  */
281 struct volume_init_batch {
282     struct rx_queue queue;               /**< queue header */
283     int thread;                          /**< posting worker thread */
284     int last;                            /**< indicates thread is done */
285     int size;                            /**< number of volume ids in batch */
286     Volume *batch[VINIT_BATCH_MAX_SIZE]; /**< volumes ids to preattach */
287 };
288
289 /**
290  * volume parameters work queue
291  */
292 struct volume_init_queue {
293     struct rx_queue head;                /**< volume_init_batch queue */
294     pthread_mutex_t mutex;
295     pthread_cond_t cv;
296 };
297
298 /**
299  * volume init worker thread parameters
300  */
301 struct vinitvolumepackage_thread_param {
302     int nthreads;                        /**< total number of worker threads */
303     int thread;                          /**< thread number for this worker thread */
304     struct partition_queue *pq;          /**< queue partitions to scan */
305     struct volume_init_queue *vq;        /**< queue of volume to preattach */
306 };
307
308 static void *VInitVolumePackageThread(void *args);
309 static struct DiskPartition64 *VInitNextPartition(struct partition_queue *pq);
310 static VolId VInitNextVolumeId(DIR *dirp);
311 static int VInitPreAttachVolumes(int nthreads, struct volume_init_queue *vq);
312
313 #endif /* !AFS_DEMAND_ATTACH_FS */
314 #endif /* AFS_PTHREAD_ENV */
315
316 #ifndef AFS_DEMAND_ATTACH_FS
317 static int VAttachVolumesByPartition(struct DiskPartition64 *diskP,
318                                      int * nAttached, int * nUnattached);
319 #endif /* AFS_DEMAND_ATTACH_FS */
320
321
322 #ifdef AFS_DEMAND_ATTACH_FS
323 /* demand attach fileserver extensions */
324
325 /* XXX
326  * in the future we will support serialization of VLRU state into the fs_state
327  * disk dumps
328  *
329  * these structures are the beginning of that effort
330  */
331 struct VLRU_DiskHeader {
332     struct versionStamp stamp;            /* magic and structure version number */
333     afs_uint32 mtime;                     /* time of dump to disk */
334     afs_uint32 num_records;               /* number of VLRU_DiskEntry records */
335 };
336
337 struct VLRU_DiskEntry {
338     afs_uint32 vid;                       /* volume ID */
339     afs_uint32 idx;                       /* generation */
340     afs_uint32 last_get;                  /* timestamp of last get */
341 };
342
343 struct VLRU_StartupQueue {
344     struct VLRU_DiskEntry * entry;
345     int num_entries;
346     int next_idx;
347 };
348
349 typedef struct vshutdown_thread_t {
350     struct rx_queue q;
351     pthread_mutex_t lock;
352     pthread_cond_t cv;
353     pthread_cond_t master_cv;
354     int n_threads;
355     int n_threads_complete;
356     int vol_remaining;
357     int schedule_version;
358     int pass;
359     byte n_parts;
360     byte n_parts_done_pass;
361     byte part_thread_target[VOLMAXPARTS+1];
362     byte part_done_pass[VOLMAXPARTS+1];
363     struct rx_queue * part_pass_head[VOLMAXPARTS+1];
364     int stats[4][VOLMAXPARTS+1];
365 } vshutdown_thread_t;
366 static void * VShutdownThread(void * args);
367
368
369 static Volume * VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode);
370 static int VCheckFree(Volume * vp);
371
372 /* VByP List */
373 static void AddVolumeToVByPList_r(Volume * vp);
374 static void DeleteVolumeFromVByPList_r(Volume * vp);
375 static void VVByPListBeginExclusive_r(struct DiskPartition64 * dp);
376 static void VVByPListEndExclusive_r(struct DiskPartition64 * dp);
377 static void VVByPListWait_r(struct DiskPartition64 * dp);
378
379 /* online salvager */
380 static int VCheckSalvage(Volume * vp);
381 #if defined(SALVSYNC_BUILD_CLIENT) || defined(FSSYNC_BUILD_CLIENT)
382 static int VScheduleSalvage_r(Volume * vp);
383 #endif
384
385 /* Volume hash table */
386 static void VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp);
387 static void VHashBeginExclusive_r(VolumeHashChainHead * head);
388 static void VHashEndExclusive_r(VolumeHashChainHead * head);
389 static void VHashWait_r(VolumeHashChainHead * head);
390
391 /* shutdown */
392 static int ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass);
393 static int ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
394                                 struct rx_queue ** idx);
395 static void ShutdownController(vshutdown_thread_t * params);
396 static void ShutdownCreateSchedule(vshutdown_thread_t * params);
397
398 /* VLRU */
399 static void VLRU_ComputeConstants(void);
400 static void VInitVLRU(void);
401 static void VLRU_Init_Node_r(Volume * vp);
402 static void VLRU_Add_r(Volume * vp);
403 static void VLRU_Delete_r(Volume * vp);
404 static void VLRU_UpdateAccess_r(Volume * vp);
405 static void * VLRU_ScannerThread(void * args);
406 static void VLRU_Scan_r(int idx);
407 static void VLRU_Promote_r(int idx);
408 static void VLRU_Demote_r(int idx);
409 static void VLRU_SwitchQueues(Volume * vp, int new_idx, int append);
410
411 /* soft detach */
412 static int VCheckSoftDetach(Volume * vp, afs_uint32 thresh);
413 static int VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh);
414 static int VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh);
415
416
417 pthread_key_t VThread_key;
418 VThreadOptions_t VThread_defaults = {
419     0                           /**< allow salvsync */
420 };
421 #endif /* AFS_DEMAND_ATTACH_FS */
422
423
424 struct Lock vol_listLock;       /* Lock obtained when listing volumes:
425                                  * prevents a volume from being missed
426                                  * if the volume is attached during a
427                                  * list volumes */
428
429
430 /* Common message used when the volume goes off line */
431 char *VSalvageMessage =
432     "Files in this volume are currently unavailable; call operations";
433
434 int VInit;                      /* 0 - uninitialized,
435                                  * 1 - initialized but not all volumes have been attached,
436                                  * 2 - initialized and all volumes have been attached,
437                                  * 3 - initialized, all volumes have been attached, and
438                                  * VConnectFS() has completed. */
439
440 static int vinit_attach_abort = 0;
441
442 bit32 VolumeCacheCheck;         /* Incremented everytime a volume goes on line--
443                                  * used to stamp volume headers and in-core
444                                  * vnodes.  When the volume goes on-line the
445                                  * vnode will be invalidated
446                                  * access only with VOL_LOCK held */
447
448
449
450
451 /***************************************************/
452 /* Startup routines                                */
453 /***************************************************/
454
455 #if defined(FAST_RESTART) && defined(AFS_DEMAND_ATTACH_FS)
456 # error FAST_RESTART and DAFS are incompatible. For the DAFS equivalent \
457         of FAST_RESTART, use the -unsafe-nosalvage fileserver argument
458 #endif
459
460 /**
461  * assign default values to a VolumePackageOptions struct.
462  *
463  * Always call this on a VolumePackageOptions struct first, then set any
464  * specific options you want, then call VInitVolumePackage2.
465  *
466  * @param[in]  pt   caller's program type
467  * @param[out] opts volume package options
468  */
469 void
470 VOptDefaults(ProgramType pt, VolumePackageOptions *opts)
471 {
472     opts->nLargeVnodes = opts->nSmallVnodes = 5;
473     opts->volcache = 0;
474
475     opts->canScheduleSalvage = 0;
476     opts->canUseFSSYNC = 0;
477     opts->canUseSALVSYNC = 0;
478
479     opts->interrupt_rxcall = NULL;
480     opts->offline_timeout = -1;
481     opts->offline_shutdown_timeout = -1;
482     opts->usage_threshold = 128;
483     opts->usage_rate_limit = 5;
484
485 #ifdef FAST_RESTART
486     opts->unsafe_attach = 1;
487 #else /* !FAST_RESTART */
488     opts->unsafe_attach = 0;
489 #endif /* !FAST_RESTART */
490
491     switch (pt) {
492     case fileServer:
493         opts->canScheduleSalvage = 1;
494         opts->canUseSALVSYNC = 1;
495         break;
496
497     case salvageServer:
498         opts->canUseFSSYNC = 1;
499         break;
500
501     case volumeServer:
502         opts->nLargeVnodes = 0;
503         opts->nSmallVnodes = 0;
504
505         opts->canScheduleSalvage = 1;
506         opts->canUseFSSYNC = 1;
507         break;
508
509     default:
510         /* noop */
511         break;
512     }
513 }
514
515 /**
516  * Set VInit to a certain value, and signal waiters.
517  *
518  * @param[in] value  the value to set VInit to
519  *
520  * @pre VOL_LOCK held
521  */
522 static void
523 VSetVInit_r(int value)
524 {
525     VInit = value;
526     CV_BROADCAST(&vol_vinit_cond);
527 }
528
529 static_inline void
530 VLogOfflineTimeout(const char *type, afs_int32 timeout)
531 {
532     if (timeout < 0) {
533         return;
534     }
535     if (timeout == 0) {
536         Log("VInitVolumePackage: Interrupting clients accessing %s "
537             "immediately\n", type);
538     } else {
539         Log("VInitVolumePackage: Interrupting clients accessing %s "
540             "after %ld second%s\n", type, (long)timeout, timeout==1?"":"s");
541     }
542 }
543
544 int
545 VInitVolumePackage2(ProgramType pt, VolumePackageOptions * opts)
546 {
547     int errors = 0;             /* Number of errors while finding vice partitions. */
548
549     programType = pt;
550     vol_opts = *opts;
551
552 #ifndef AFS_PTHREAD_ENV
553     if (opts->offline_timeout != -1 || opts->offline_shutdown_timeout != -1) {
554         Log("VInitVolumePackage: offline_timeout and/or "
555             "offline_shutdown_timeout was specified, but the volume package "
556             "does not support these for LWP builds\n");
557         return -1;
558     }
559 #endif
560     VLogOfflineTimeout("volumes going offline", opts->offline_timeout);
561     VLogOfflineTimeout("volumes going offline during shutdown",
562                        opts->offline_shutdown_timeout);
563
564     memset(&VStats, 0, sizeof(VStats));
565     VStats.hdr_cache_size = 200;
566
567     VInitPartitionPackage();
568     VInitVolumeHash();
569 #ifdef AFS_DEMAND_ATTACH_FS
570     if (programType == fileServer) {
571         VInitVLRU();
572     } else {
573         VLRU_SetOptions(VLRU_SET_ENABLED, 0);
574     }
575     osi_Assert(pthread_key_create(&VThread_key, NULL) == 0);
576 #endif
577
578     MUTEX_INIT(&vol_glock_mutex, "vol glock", MUTEX_DEFAULT, 0);
579     MUTEX_INIT(&vol_trans_mutex, "vol trans", MUTEX_DEFAULT, 0);
580     CV_INIT(&vol_put_volume_cond, "vol put", CV_DEFAULT, 0);
581     CV_INIT(&vol_sleep_cond, "vol sleep", CV_DEFAULT, 0);
582     CV_INIT(&vol_init_attach_cond, "vol init attach", CV_DEFAULT, 0);
583     CV_INIT(&vol_vinit_cond, "vol init", CV_DEFAULT, 0);
584 #ifndef AFS_PTHREAD_ENV
585     IOMGR_Initialize();
586 #endif /* AFS_PTHREAD_ENV */
587     Lock_Init(&vol_listLock);
588
589     srandom(time(0));           /* For VGetVolumeInfo */
590
591 #ifdef AFS_DEMAND_ATTACH_FS
592     MUTEX_INIT(&vol_salvsync_mutex, "salvsync", MUTEX_DEFAULT, 0);
593 #endif /* AFS_DEMAND_ATTACH_FS */
594
595     /* Ok, we have done enough initialization that fileserver can
596      * start accepting calls, even though the volumes may not be
597      * available just yet.
598      */
599     VInit = 1;
600
601 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_SERVER)
602     if (programType == salvageServer) {
603         SALVSYNC_salvInit();
604     }
605 #endif /* AFS_DEMAND_ATTACH_FS */
606 #ifdef FSSYNC_BUILD_SERVER
607     if (programType == fileServer) {
608         FSYNC_fsInit();
609     }
610 #endif
611 #if defined(AFS_DEMAND_ATTACH_FS) && defined(SALVSYNC_BUILD_CLIENT)
612     if (VCanUseSALVSYNC()) {
613         /* establish a connection to the salvager at this point */
614         osi_Assert(VConnectSALV() != 0);
615     }
616 #endif /* AFS_DEMAND_ATTACH_FS */
617
618     if (opts->volcache > VStats.hdr_cache_size)
619         VStats.hdr_cache_size = opts->volcache;
620     VInitVolumeHeaderCache(VStats.hdr_cache_size);
621
622     VInitVnodes(vLarge, opts->nLargeVnodes);
623     VInitVnodes(vSmall, opts->nSmallVnodes);
624
625
626     errors = VAttachPartitions();
627     if (errors)
628         return -1;
629
630     if (programType != fileServer) {
631         errors = VInitAttachVolumes(programType);
632         if (errors) {
633             return -1;
634         }
635     }
636
637 #ifdef FSSYNC_BUILD_CLIENT
638     if (VCanUseFSSYNC()) {
639         if (!VConnectFS()) {
640 #ifdef AFS_DEMAND_ATTACH_FS
641             if (programType == salvageServer) {
642                 Log("Unable to connect to file server; aborted\n");
643                 exit(1);
644             }
645 #endif /* AFS_DEMAND_ATTACH_FS */
646             Log("Unable to connect to file server; will retry at need\n");
647         }
648     }
649 #endif /* FSSYNC_BUILD_CLIENT */
650     return 0;
651 }
652
653
654 #if !defined(AFS_PTHREAD_ENV)
655 /**
656  * Attach volumes in vice partitions
657  *
658  * @param[in]  pt         calling program type
659  *
660  * @return 0
661  * @note This is the original, non-threaded version of attach parititions.
662  *
663  * @post VInit state is 2
664  */
665 int
666 VInitAttachVolumes(ProgramType pt)
667 {
668     osi_Assert(VInit==1);
669     if (pt == fileServer) {
670         struct DiskPartition64 *diskP;
671         /* Attach all the volumes in this partition */
672         for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
673             int nAttached = 0, nUnattached = 0;
674             osi_Assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
675         }
676     }
677     VOL_LOCK;
678     VSetVInit_r(2);                     /* Initialized, and all volumes have been attached */
679     LWP_NoYieldSignal(VInitAttachVolumes);
680     VOL_UNLOCK;
681     return 0;
682 }
683 #endif /* !AFS_PTHREAD_ENV */
684
685 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_DEMAND_ATTACH_FS)
686 /**
687  * Attach volumes in vice partitions
688  *
689  * @param[in]  pt         calling program type
690  *
691  * @return 0
692  * @note Threaded version of attach parititions.
693  *
694  * @post VInit state is 2
695  */
696 int
697 VInitAttachVolumes(ProgramType pt)
698 {
699     osi_Assert(VInit==1);
700     if (pt == fileServer) {
701         struct DiskPartition64 *diskP;
702         struct vinitvolumepackage_thread_t params;
703         struct diskpartition_queue_t * dpq;
704         int i, threads, parts;
705         pthread_t tid;
706         pthread_attr_t attrs;
707
708         CV_INIT(&params.thread_done_cv, "thread done", CV_DEFAULT, 0);
709         queue_Init(&params);
710         params.n_threads_complete = 0;
711
712         /* create partition work queue */
713         for (parts=0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
714             dpq = (diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
715             osi_Assert(dpq != NULL);
716             dpq->diskP = diskP;
717             queue_Append(&params,dpq);
718         }
719
720         threads = MIN(parts, vol_attach_threads);
721
722         if (threads > 1) {
723             /* spawn off a bunch of initialization threads */
724             osi_Assert(pthread_attr_init(&attrs) == 0);
725             osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
726
727             Log("VInitVolumePackage: beginning parallel fileserver startup\n");
728             Log("VInitVolumePackage: using %d threads to attach volumes on %d partitions\n",
729                 threads, parts);
730
731             VOL_LOCK;
732             for (i=0; i < threads; i++) {
733                 AFS_SIGSET_DECL;
734                 AFS_SIGSET_CLEAR();
735                 osi_Assert(pthread_create
736                        (&tid, &attrs, &VInitVolumePackageThread,
737                         &params) == 0);
738                 AFS_SIGSET_RESTORE();
739             }
740
741             while(params.n_threads_complete < threads) {
742                 VOL_CV_WAIT(&params.thread_done_cv);
743             }
744             VOL_UNLOCK;
745
746             osi_Assert(pthread_attr_destroy(&attrs) == 0);
747         } else {
748             /* if we're only going to run one init thread, don't bother creating
749              * another LWP */
750             Log("VInitVolumePackage: beginning single-threaded fileserver startup\n");
751             Log("VInitVolumePackage: using 1 thread to attach volumes on %d partition(s)\n",
752                 parts);
753
754             VInitVolumePackageThread(&params);
755         }
756
757         CV_DESTROY(&params.thread_done_cv);
758     }
759     VOL_LOCK;
760     VSetVInit_r(2);                     /* Initialized, and all volumes have been attached */
761     CV_BROADCAST(&vol_init_attach_cond);
762     VOL_UNLOCK;
763     return 0;
764 }
765
766 static void *
767 VInitVolumePackageThread(void * args) {
768
769     struct DiskPartition64 *diskP;
770     struct vinitvolumepackage_thread_t * params;
771     struct diskpartition_queue_t * dpq;
772
773     params = (vinitvolumepackage_thread_t *) args;
774
775
776     VOL_LOCK;
777     /* Attach all the volumes in this partition */
778     while (queue_IsNotEmpty(params)) {
779         int nAttached = 0, nUnattached = 0;
780
781         if (vinit_attach_abort) {
782             Log("Aborting initialization\n");
783             goto done;
784         }
785
786         dpq = queue_First(params,diskpartition_queue_t);
787         queue_Remove(dpq);
788         VOL_UNLOCK;
789         diskP = dpq->diskP;
790         free(dpq);
791
792         osi_Assert(VAttachVolumesByPartition(diskP, &nAttached, &nUnattached) == 0);
793
794         VOL_LOCK;
795     }
796
797 done:
798     params->n_threads_complete++;
799     CV_SIGNAL(&params->thread_done_cv);
800     VOL_UNLOCK;
801     return NULL;
802 }
803 #endif /* AFS_PTHREAD_ENV && !AFS_DEMAND_ATTACH_FS */
804
805 #if defined(AFS_DEMAND_ATTACH_FS)
806 /**
807  * Attach volumes in vice partitions
808  *
809  * @param[in]  pt         calling program type
810  *
811  * @return 0
812  * @note Threaded version of attach partitions.
813  *
814  * @post VInit state is 2
815  */
816 int
817 VInitAttachVolumes(ProgramType pt)
818 {
819     osi_Assert(VInit==1);
820     if (pt == fileServer) {
821
822         struct DiskPartition64 *diskP;
823         struct partition_queue pq;
824         struct volume_init_queue vq;
825
826         int i, threads, parts;
827         pthread_t tid;
828         pthread_attr_t attrs;
829
830         /* create partition work queue */
831         queue_Init(&pq);
832         CV_INIT(&(pq.cv), "partq", CV_DEFAULT, 0);
833         MUTEX_INIT(&(pq.mutex), "partq", MUTEX_DEFAULT, 0);
834         for (parts = 0, diskP = DiskPartitionList; diskP; diskP = diskP->next, parts++) {
835             struct diskpartition_queue_t *dp;
836             dp = (struct diskpartition_queue_t*)malloc(sizeof(struct diskpartition_queue_t));
837             osi_Assert(dp != NULL);
838             dp->diskP = diskP;
839             queue_Append(&pq, dp);
840         }
841
842         /* number of worker threads; at least one, not to exceed the number of partitions */
843         threads = MIN(parts, vol_attach_threads);
844
845         /* create volume work queue */
846         queue_Init(&vq);
847         CV_INIT(&(vq.cv), "volq", CV_DEFAULT, 0);
848         MUTEX_INIT(&(vq.mutex), "volq", MUTEX_DEFAULT, 0);
849
850         osi_Assert(pthread_attr_init(&attrs) == 0);
851         osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
852
853         Log("VInitVolumePackage: beginning parallel fileserver startup\n");
854         Log("VInitVolumePackage: using %d threads to pre-attach volumes on %d partitions\n",
855                 threads, parts);
856
857         /* create threads to scan disk partitions. */
858         for (i=0; i < threads; i++) {
859             struct vinitvolumepackage_thread_param *params;
860             AFS_SIGSET_DECL;
861
862             params = (struct vinitvolumepackage_thread_param *)malloc(sizeof(struct vinitvolumepackage_thread_param));
863             osi_Assert(params);
864             params->pq = &pq;
865             params->vq = &vq;
866             params->nthreads = threads;
867             params->thread = i+1;
868
869             AFS_SIGSET_CLEAR();
870             osi_Assert(pthread_create (&tid, &attrs, &VInitVolumePackageThread, (void*)params) == 0);
871             AFS_SIGSET_RESTORE();
872         }
873
874         VInitPreAttachVolumes(threads, &vq);
875
876         osi_Assert(pthread_attr_destroy(&attrs) == 0);
877         CV_DESTROY(&pq.cv);
878         MUTEX_DESTROY(&pq.mutex);
879         CV_DESTROY(&vq.cv);
880         MUTEX_DESTROY(&vq.mutex);
881     }
882
883     VOL_LOCK;
884     VSetVInit_r(2);                     /* Initialized, and all volumes have been attached */
885     CV_BROADCAST(&vol_init_attach_cond);
886     VOL_UNLOCK;
887
888     return 0;
889 }
890
891 /**
892  * Volume package initialization worker thread. Scan partitions for volume
893  * header files. Gather batches of volume ids and dispatch them to
894  * the main thread to be preattached.  The volume preattachement is done
895  * in the main thread to avoid global volume lock contention.
896  */
897 static void *
898 VInitVolumePackageThread(void *args)
899 {
900     struct vinitvolumepackage_thread_param *params;
901     struct DiskPartition64 *partition;
902     struct partition_queue *pq;
903     struct volume_init_queue *vq;
904     struct volume_init_batch *vb;
905
906     osi_Assert(args);
907     params = (struct vinitvolumepackage_thread_param *)args;
908     pq = params->pq;
909     vq = params->vq;
910     osi_Assert(pq);
911     osi_Assert(vq);
912
913     vb = (struct volume_init_batch*)malloc(sizeof(struct volume_init_batch));
914     osi_Assert(vb);
915     vb->thread = params->thread;
916     vb->last = 0;
917     vb->size = 0;
918
919     Log("Scanning partitions on thread %d of %d\n", params->thread, params->nthreads);
920     while((partition = VInitNextPartition(pq))) {
921         DIR *dirp;
922         VolId vid;
923
924         Log("Partition %s: pre-attaching volumes\n", partition->name);
925         dirp = opendir(VPartitionPath(partition));
926         if (!dirp) {
927             Log("opendir on Partition %s failed, errno=%d!\n", partition->name, errno);
928             continue;
929         }
930         while ((vid = VInitNextVolumeId(dirp))) {
931             Volume *vp = (Volume*)malloc(sizeof(Volume));
932             osi_Assert(vp);
933             memset(vp, 0, sizeof(Volume));
934             vp->device = partition->device;
935             vp->partition = partition;
936             vp->hashid = vid;
937             queue_Init(&vp->vnode_list);
938             queue_Init(&vp->rx_call_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     vol_shutting_down = 1;
1220
1221     if (vol_attach_threads > 1) {
1222         /* prepare for parallel shutdown */
1223         params.n_threads = vol_attach_threads;
1224         MUTEX_INIT(&params.lock, "params", MUTEX_DEFAULT, 0);
1225         CV_INIT(&params.cv, "params", CV_DEFAULT, 0);
1226         CV_INIT(&params.master_cv, "params master", CV_DEFAULT, 0);
1227         osi_Assert(pthread_attr_init(&attrs) == 0);
1228         osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
1229         queue_Init(&params);
1230
1231         /* setup the basic partition information structures for
1232          * parallel shutdown */
1233         for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1234             /* XXX debug */
1235             struct rx_queue * qp, * nqp;
1236             Volume * vp;
1237             int count = 0;
1238
1239             VVByPListWait_r(diskP);
1240             VVByPListBeginExclusive_r(diskP);
1241
1242             /* XXX debug */
1243             for (queue_Scan(&diskP->vol_list, qp, nqp, rx_queue)) {
1244                 vp = (Volume *)((char *)qp - offsetof(Volume, vol_list));
1245                 if (vp->header)
1246                     count++;
1247             }
1248             Log("VShutdown: partition %s has %d volumes with attached headers\n",
1249                 VPartitionPath(diskP), count);
1250
1251
1252             /* build up the pass 0 shutdown work queue */
1253             dpq = (struct diskpartition_queue_t *) malloc(sizeof(struct diskpartition_queue_t));
1254             osi_Assert(dpq != NULL);
1255             dpq->diskP = diskP;
1256             queue_Prepend(&params, dpq);
1257
1258             params.part_pass_head[diskP->index] = queue_First(&diskP->vol_list, rx_queue);
1259         }
1260
1261         Log("VShutdown:  beginning parallel fileserver shutdown\n");
1262         Log("VShutdown:  using %d threads to offline volumes on %d partition%s\n",
1263             vol_attach_threads, params.n_parts, params.n_parts > 1 ? "s" : "" );
1264
1265         /* do pass 0 shutdown */
1266         MUTEX_ENTER(&params.lock);
1267         for (i=0; i < params.n_threads; i++) {
1268             osi_Assert(pthread_create
1269                    (&tid, &attrs, &VShutdownThread,
1270                     &params) == 0);
1271         }
1272
1273         /* wait for all the pass 0 shutdowns to complete */
1274         while (params.n_threads_complete < params.n_threads) {
1275             CV_WAIT(&params.master_cv, &params.lock);
1276         }
1277         params.n_threads_complete = 0;
1278         params.pass = 1;
1279         CV_BROADCAST(&params.cv);
1280         MUTEX_EXIT(&params.lock);
1281
1282         Log("VShutdown:  pass 0 completed using the 1 thread per partition algorithm\n");
1283         Log("VShutdown:  starting passes 1 through 3 using finely-granular mp-fast algorithm\n");
1284
1285         /* run the parallel shutdown scheduler. it will drop the glock internally */
1286         ShutdownController(&params);
1287
1288         /* wait for all the workers to finish pass 3 and terminate */
1289         while (params.pass < 4) {
1290             VOL_CV_WAIT(&params.cv);
1291         }
1292
1293         osi_Assert(pthread_attr_destroy(&attrs) == 0);
1294         CV_DESTROY(&params.cv);
1295         CV_DESTROY(&params.master_cv);
1296         MUTEX_DESTROY(&params.lock);
1297
1298         /* drop the VByPList exclusive reservations */
1299         for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1300             VVByPListEndExclusive_r(diskP);
1301             Log("VShutdown:  %s stats : (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1302                 VPartitionPath(diskP),
1303                 params.stats[0][diskP->index],
1304                 params.stats[1][diskP->index],
1305                 params.stats[2][diskP->index],
1306                 params.stats[3][diskP->index]);
1307         }
1308
1309         Log("VShutdown:  shutdown finished using %d threads\n", params.n_threads);
1310     } else {
1311         /* if we're only going to run one shutdown thread, don't bother creating
1312          * another LWP */
1313         Log("VShutdown:  beginning single-threaded fileserver shutdown\n");
1314
1315         for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1316             VShutdownByPartition_r(diskP);
1317         }
1318     }
1319
1320     Log("VShutdown:  complete.\n");
1321 }
1322
1323 #else /* AFS_DEMAND_ATTACH_FS */
1324
1325 void
1326 VShutdown_r(void)
1327 {
1328     int i;
1329     Volume *vp, *np;
1330     afs_int32 code;
1331
1332     if (VInit < 2) {
1333         Log("VShutdown:  aborting attach volumes\n");
1334         vinit_attach_abort = 1;
1335 #ifdef AFS_PTHREAD_ENV
1336         VOL_CV_WAIT(&vol_init_attach_cond);
1337 #else
1338         LWP_WaitProcess(VInitAttachVolumes);
1339 #endif /* AFS_PTHREAD_ENV */
1340     }
1341
1342     Log("VShutdown:  shutting down on-line volumes...\n");
1343     vol_shutting_down = 1;
1344     for (i = 0; i < VolumeHashTable.Size; i++) {
1345         /* try to hold first volume in the hash table */
1346         for (queue_Scan(&VolumeHashTable.Table[i],vp,np,Volume)) {
1347             code = VHold_r(vp);
1348             if (code == 0) {
1349                 if (LogLevel >= 5)
1350                     Log("VShutdown:  Attempting to take volume %u offline.\n",
1351                         vp->hashid);
1352
1353                 /* next, take the volume offline (drops reference count) */
1354                 VOffline_r(vp, "File server was shut down");
1355             }
1356         }
1357     }
1358     Log("VShutdown:  complete.\n");
1359 }
1360 #endif /* AFS_DEMAND_ATTACH_FS */
1361
1362
1363 void
1364 VShutdown(void)
1365 {
1366     osi_Assert(VInit>0);
1367     VOL_LOCK;
1368     VShutdown_r();
1369     VOL_UNLOCK;
1370 }
1371
1372 /**
1373  * stop new activity (e.g. SALVSYNC) from occurring
1374  *
1375  * Use this to make the volume package less busy; for example, during
1376  * shutdown. This doesn't actually shutdown/detach anything in the
1377  * volume package, but prevents certain processes from ocurring. For
1378  * example, preventing new SALVSYNC communication in DAFS. In theory, we
1379  * could also use this to prevent new volume attachment, or prevent
1380  * other programs from checking out volumes, etc.
1381  */
1382 void
1383 VSetTranquil(void)
1384 {
1385 #ifdef AFS_DEMAND_ATTACH_FS
1386     /* make sure we don't try to contact the salvageserver, since it may
1387      * not be around anymore */
1388     vol_disallow_salvsync = 1;
1389 #endif
1390 }
1391
1392 #ifdef AFS_DEMAND_ATTACH_FS
1393 /*
1394  * demand attach fs
1395  * shutdown control thread
1396  */
1397 static void
1398 ShutdownController(vshutdown_thread_t * params)
1399 {
1400     /* XXX debug */
1401     struct DiskPartition64 * diskP;
1402     Device id;
1403     vshutdown_thread_t shadow;
1404
1405     ShutdownCreateSchedule(params);
1406
1407     while ((params->pass < 4) &&
1408            (params->n_threads_complete < params->n_threads)) {
1409         /* recompute schedule once per second */
1410
1411         memcpy(&shadow, params, sizeof(vshutdown_thread_t));
1412
1413         VOL_UNLOCK;
1414         /* XXX debug */
1415         Log("ShutdownController:  schedule version=%d, vol_remaining=%d, pass=%d\n",
1416             shadow.schedule_version, shadow.vol_remaining, shadow.pass);
1417         Log("ShutdownController:  n_threads_complete=%d, n_parts_done_pass=%d\n",
1418             shadow.n_threads_complete, shadow.n_parts_done_pass);
1419         for (diskP = DiskPartitionList; diskP; diskP=diskP->next) {
1420             id = diskP->index;
1421             Log("ShutdownController:  part[%d] : (len=%d, thread_target=%d, done_pass=%d, pass_head=%p)\n",
1422                 id,
1423                 diskP->vol_list.len,
1424                 shadow.part_thread_target[id],
1425                 shadow.part_done_pass[id],
1426                 shadow.part_pass_head[id]);
1427         }
1428
1429         sleep(1);
1430         VOL_LOCK;
1431
1432         ShutdownCreateSchedule(params);
1433     }
1434 }
1435
1436 /* create the shutdown thread work schedule.
1437  * this scheduler tries to implement fairness
1438  * by allocating at least 1 thread to each
1439  * partition with volumes to be shutdown,
1440  * and then it attempts to allocate remaining
1441  * threads based upon the amount of work left
1442  */
1443 static void
1444 ShutdownCreateSchedule(vshutdown_thread_t * params)
1445 {
1446     struct DiskPartition64 * diskP;
1447     int sum, thr_workload, thr_left;
1448     int part_residue[VOLMAXPARTS+1];
1449     Device id;
1450
1451     /* compute the total number of outstanding volumes */
1452     sum = 0;
1453     for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1454         sum += diskP->vol_list.len;
1455     }
1456
1457     params->schedule_version++;
1458     params->vol_remaining = sum;
1459
1460     if (!sum)
1461         return;
1462
1463     /* compute average per-thread workload */
1464     thr_workload = sum / params->n_threads;
1465     if (sum % params->n_threads)
1466         thr_workload++;
1467
1468     thr_left = params->n_threads;
1469     memset(&part_residue, 0, sizeof(part_residue));
1470
1471     /* for fairness, give every partition with volumes remaining
1472      * at least one thread */
1473     for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1474         id = diskP->index;
1475         if (diskP->vol_list.len) {
1476             params->part_thread_target[id] = 1;
1477             thr_left--;
1478         } else {
1479             params->part_thread_target[id] = 0;
1480         }
1481     }
1482
1483     if (thr_left && thr_workload) {
1484         /* compute length-weighted workloads */
1485         int delta;
1486
1487         for (diskP = DiskPartitionList; diskP && thr_left; diskP = diskP->next) {
1488             id = diskP->index;
1489             delta = (diskP->vol_list.len / thr_workload) -
1490                 params->part_thread_target[id];
1491             if (delta < 0) {
1492                 continue;
1493             }
1494             if (delta < thr_left) {
1495                 params->part_thread_target[id] += delta;
1496                 thr_left -= delta;
1497             } else {
1498                 params->part_thread_target[id] += thr_left;
1499                 thr_left = 0;
1500                 break;
1501             }
1502         }
1503     }
1504
1505     if (thr_left) {
1506         /* try to assign any leftover threads to partitions that
1507          * had volume lengths closer to needing thread_target+1 */
1508         int max_residue, max_id = 0;
1509
1510         /* compute the residues */
1511         for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1512             id = diskP->index;
1513             part_residue[id] = diskP->vol_list.len -
1514                 (params->part_thread_target[id] * thr_workload);
1515         }
1516
1517         /* now try to allocate remaining threads to partitions with the
1518          * highest residues */
1519         while (thr_left) {
1520             max_residue = 0;
1521             for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1522                 id = diskP->index;
1523                 if (part_residue[id] > max_residue) {
1524                     max_residue = part_residue[id];
1525                     max_id = id;
1526                 }
1527             }
1528
1529             if (!max_residue) {
1530                 break;
1531             }
1532
1533             params->part_thread_target[max_id]++;
1534             thr_left--;
1535             part_residue[max_id] = 0;
1536         }
1537     }
1538
1539     if (thr_left) {
1540         /* punt and give any remaining threads equally to each partition */
1541         int alloc;
1542         if (thr_left >= params->n_parts) {
1543             alloc = thr_left / params->n_parts;
1544             for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1545                 id = diskP->index;
1546                 params->part_thread_target[id] += alloc;
1547                 thr_left -= alloc;
1548             }
1549         }
1550
1551         /* finish off the last of the threads */
1552         for (diskP = DiskPartitionList; thr_left && diskP; diskP = diskP->next) {
1553             id = diskP->index;
1554             params->part_thread_target[id]++;
1555             thr_left--;
1556         }
1557     }
1558 }
1559
1560 /* worker thread for parallel shutdown */
1561 static void *
1562 VShutdownThread(void * args)
1563 {
1564     vshutdown_thread_t * params;
1565     int found, pass, schedule_version_save, count;
1566     struct DiskPartition64 *diskP;
1567     struct diskpartition_queue_t * dpq;
1568     Device id;
1569
1570     params = (vshutdown_thread_t *) args;
1571
1572     /* acquire the shutdown pass 0 lock */
1573     MUTEX_ENTER(&params->lock);
1574
1575     /* if there's still pass 0 work to be done,
1576      * get a work entry, and do a pass 0 shutdown */
1577     if (queue_IsNotEmpty(params)) {
1578         dpq = queue_First(params, diskpartition_queue_t);
1579         queue_Remove(dpq);
1580         MUTEX_EXIT(&params->lock);
1581         diskP = dpq->diskP;
1582         free(dpq);
1583         id = diskP->index;
1584
1585         count = 0;
1586         while (ShutdownVolumeWalk_r(diskP, 0, &params->part_pass_head[id]))
1587             count++;
1588         params->stats[0][diskP->index] = count;
1589         MUTEX_ENTER(&params->lock);
1590     }
1591
1592     params->n_threads_complete++;
1593     if (params->n_threads_complete == params->n_threads) {
1594         /* notify control thread that all workers have completed pass 0 */
1595         CV_SIGNAL(&params->master_cv);
1596     }
1597     while (params->pass == 0) {
1598         CV_WAIT(&params->cv, &params->lock);
1599     }
1600
1601     /* switch locks */
1602     MUTEX_EXIT(&params->lock);
1603     VOL_LOCK;
1604
1605     pass = params->pass;
1606     osi_Assert(pass > 0);
1607
1608     /* now escalate through the more complicated shutdowns */
1609     while (pass <= 3) {
1610         schedule_version_save = params->schedule_version;
1611         found = 0;
1612         /* find a disk partition to work on */
1613         for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1614             id = diskP->index;
1615             if (params->part_thread_target[id] && !params->part_done_pass[id]) {
1616                 params->part_thread_target[id]--;
1617                 found = 1;
1618                 break;
1619             }
1620         }
1621
1622         if (!found) {
1623             /* hmm. for some reason the controller thread couldn't find anything for
1624              * us to do. let's see if there's anything we can do */
1625             for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1626                 id = diskP->index;
1627                 if (diskP->vol_list.len && !params->part_done_pass[id]) {
1628                     found = 1;
1629                     break;
1630                 } else if (!params->part_done_pass[id]) {
1631                     params->part_done_pass[id] = 1;
1632                     params->n_parts_done_pass++;
1633                     if (pass == 3) {
1634                         Log("VShutdown:  done shutting down volumes on partition %s.\n",
1635                             VPartitionPath(diskP));
1636                     }
1637                 }
1638             }
1639         }
1640
1641         /* do work on this partition until either the controller
1642          * creates a new schedule, or we run out of things to do
1643          * on this partition */
1644         if (found) {
1645             count = 0;
1646             while (!params->part_done_pass[id] &&
1647                    (schedule_version_save == params->schedule_version)) {
1648                 /* ShutdownVolumeWalk_r will drop the glock internally */
1649                 if (!ShutdownVolumeWalk_r(diskP, pass, &params->part_pass_head[id])) {
1650                     if (!params->part_done_pass[id]) {
1651                         params->part_done_pass[id] = 1;
1652                         params->n_parts_done_pass++;
1653                         if (pass == 3) {
1654                             Log("VShutdown:  done shutting down volumes on partition %s.\n",
1655                                 VPartitionPath(diskP));
1656                         }
1657                     }
1658                     break;
1659                 }
1660                 count++;
1661             }
1662
1663             params->stats[pass][id] += count;
1664         } else {
1665             /* ok, everyone is done this pass, proceed */
1666
1667             /* barrier lock */
1668             params->n_threads_complete++;
1669             while (params->pass == pass) {
1670                 if (params->n_threads_complete == params->n_threads) {
1671                     /* we are the last thread to complete, so we will
1672                      * reinitialize worker pool state for the next pass */
1673                     params->n_threads_complete = 0;
1674                     params->n_parts_done_pass = 0;
1675                     params->pass++;
1676                     for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
1677                         id = diskP->index;
1678                         params->part_done_pass[id] = 0;
1679                         params->part_pass_head[id] = queue_First(&diskP->vol_list, rx_queue);
1680                     }
1681
1682                     /* compute a new thread schedule before releasing all the workers */
1683                     ShutdownCreateSchedule(params);
1684
1685                     /* wake up all the workers */
1686                     CV_BROADCAST(&params->cv);
1687
1688                     VOL_UNLOCK;
1689                     Log("VShutdown:  pass %d completed using %d threads on %d partitions\n",
1690                         pass, params->n_threads, params->n_parts);
1691                     VOL_LOCK;
1692                 } else {
1693                     VOL_CV_WAIT(&params->cv);
1694                 }
1695             }
1696             pass = params->pass;
1697         }
1698
1699         /* for fairness */
1700         VOL_UNLOCK;
1701         pthread_yield();
1702         VOL_LOCK;
1703     }
1704
1705     VOL_UNLOCK;
1706
1707     return NULL;
1708 }
1709
1710 /* shut down all volumes on a given disk partition
1711  *
1712  * note that this function will not allow mp-fast
1713  * shutdown of a partition */
1714 int
1715 VShutdownByPartition_r(struct DiskPartition64 * dp)
1716 {
1717     int pass;
1718     int pass_stats[4];
1719     int total;
1720
1721     /* wait for other exclusive ops to finish */
1722     VVByPListWait_r(dp);
1723
1724     /* begin exclusive access */
1725     VVByPListBeginExclusive_r(dp);
1726
1727     /* pick the low-hanging fruit first,
1728      * then do the complicated ones last
1729      * (has the advantage of keeping
1730      *  in-use volumes up until the bitter end) */
1731     for (pass = 0, total=0; pass < 4; pass++) {
1732         pass_stats[pass] = ShutdownVByPForPass_r(dp, pass);
1733         total += pass_stats[pass];
1734     }
1735
1736     /* end exclusive access */
1737     VVByPListEndExclusive_r(dp);
1738
1739     Log("VShutdownByPartition:  shut down %d volumes on %s (pass[0]=%d, pass[1]=%d, pass[2]=%d, pass[3]=%d)\n",
1740         total, VPartitionPath(dp), pass_stats[0], pass_stats[1], pass_stats[2], pass_stats[3]);
1741
1742     return 0;
1743 }
1744
1745 /* internal shutdown functionality
1746  *
1747  * for multi-pass shutdown:
1748  * 0 to only "shutdown" {pre,un}attached and error state volumes
1749  * 1 to also shutdown attached volumes w/ volume header loaded
1750  * 2 to also shutdown attached volumes w/o volume header loaded
1751  * 3 to also shutdown exclusive state volumes
1752  *
1753  * caller MUST hold exclusive access on the hash chain
1754  * because we drop vol_glock_mutex internally
1755  *
1756  * this function is reentrant for passes 1--3
1757  * (e.g. multiple threads can cooperate to
1758  *  shutdown a partition mp-fast)
1759  *
1760  * pass 0 is not scaleable because the volume state data is
1761  * synchronized by vol_glock mutex, and the locking overhead
1762  * is too high to drop the lock long enough to do linked list
1763  * traversal
1764  */
1765 static int
1766 ShutdownVByPForPass_r(struct DiskPartition64 * dp, int pass)
1767 {
1768     struct rx_queue * q = queue_First(&dp->vol_list, rx_queue);
1769     int i = 0;
1770
1771     while (ShutdownVolumeWalk_r(dp, pass, &q))
1772         i++;
1773
1774     return i;
1775 }
1776
1777 /* conditionally shutdown one volume on partition dp
1778  * returns 1 if a volume was shutdown in this pass,
1779  * 0 otherwise */
1780 static int
1781 ShutdownVolumeWalk_r(struct DiskPartition64 * dp, int pass,
1782                      struct rx_queue ** idx)
1783 {
1784     struct rx_queue *qp, *nqp;
1785     Volume * vp;
1786
1787     qp = *idx;
1788
1789     for (queue_ScanFrom(&dp->vol_list, qp, qp, nqp, rx_queue)) {
1790         vp = (Volume *) (((char *)qp) - offsetof(Volume, vol_list));
1791
1792         switch (pass) {
1793         case 0:
1794             if ((V_attachState(vp) != VOL_STATE_UNATTACHED) &&
1795                 (V_attachState(vp) != VOL_STATE_ERROR) &&
1796                 (V_attachState(vp) != VOL_STATE_DELETED) &&
1797                 (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
1798                 break;
1799             }
1800         case 1:
1801             if ((V_attachState(vp) == VOL_STATE_ATTACHED) &&
1802                 (vp->header == NULL)) {
1803                 break;
1804             }
1805         case 2:
1806             if (VIsExclusiveState(V_attachState(vp))) {
1807                 break;
1808             }
1809         case 3:
1810             *idx = nqp;
1811             DeleteVolumeFromVByPList_r(vp);
1812             VShutdownVolume_r(vp);
1813             vp = NULL;
1814             return 1;
1815         }
1816     }
1817
1818     return 0;
1819 }
1820
1821 /*
1822  * shutdown a specific volume
1823  */
1824 /* caller MUST NOT hold a heavyweight ref on vp */
1825 int
1826 VShutdownVolume_r(Volume * vp)
1827 {
1828     int code;
1829
1830     VCreateReservation_r(vp);
1831
1832     if (LogLevel >= 5) {
1833         Log("VShutdownVolume_r:  vid=%u, device=%d, state=%hu\n",
1834             vp->hashid, vp->partition->device, V_attachState(vp));
1835     }
1836
1837     /* wait for other blocking ops to finish */
1838     VWaitExclusiveState_r(vp);
1839
1840     osi_Assert(VIsValidState(V_attachState(vp)));
1841
1842     switch(V_attachState(vp)) {
1843     case VOL_STATE_SALVAGING:
1844         /* Leave salvaging volumes alone. Any in-progress salvages will
1845          * continue working after viced shuts down. This is intentional.
1846          */
1847
1848     case VOL_STATE_PREATTACHED:
1849     case VOL_STATE_ERROR:
1850         VChangeState_r(vp, VOL_STATE_UNATTACHED);
1851     case VOL_STATE_UNATTACHED:
1852     case VOL_STATE_DELETED:
1853         break;
1854     case VOL_STATE_GOING_OFFLINE:
1855     case VOL_STATE_SHUTTING_DOWN:
1856     case VOL_STATE_ATTACHED:
1857         code = VHold_r(vp);
1858         if (!code) {
1859             if (LogLevel >= 5)
1860                 Log("VShutdown:  Attempting to take volume %u offline.\n",
1861                     vp->hashid);
1862
1863             /* take the volume offline (drops reference count) */
1864             VOffline_r(vp, "File server was shut down");
1865         }
1866         break;
1867     default:
1868         break;
1869     }
1870
1871     VCancelReservation_r(vp);
1872     vp = NULL;
1873     return 0;
1874 }
1875 #endif /* AFS_DEMAND_ATTACH_FS */
1876
1877
1878 /***************************************************/
1879 /* Header I/O routines                             */
1880 /***************************************************/
1881
1882 static const char *
1883 HeaderName(bit32 magic)
1884 {
1885     switch (magic) {
1886     case VOLUMEINFOMAGIC:
1887         return "volume info";
1888     case SMALLINDEXMAGIC:
1889         return "small index";
1890     case LARGEINDEXMAGIC:
1891         return "large index";
1892     case LINKTABLEMAGIC:
1893         return "link table";
1894     }
1895     return "unknown";
1896 }
1897
1898 /* open a descriptor for the inode (h),
1899  * read in an on-disk structure into buffer (to) of size (size),
1900  * verify versionstamp in structure has magic (magic) and
1901  * optionally verify version (version) if (version) is nonzero
1902  */
1903 static void
1904 ReadHeader(Error * ec, IHandle_t * h, char *to, int size, bit32 magic,
1905            bit32 version)
1906 {
1907     struct versionStamp *vsn;
1908     FdHandle_t *fdP;
1909     afs_sfsize_t nbytes;
1910     afs_ino_str_t stmp;
1911
1912     *ec = 0;
1913     if (h == NULL) {
1914         Log("ReadHeader: Null inode handle argument for %s header file.\n",
1915             HeaderName(magic));
1916         *ec = VSALVAGE;
1917         return;
1918     }
1919
1920     fdP = IH_OPEN(h);
1921     if (fdP == NULL) {
1922         Log("ReadHeader: Failed to open %s header file "
1923             "(volume=%u, inode=%s); errno=%d\n", HeaderName(magic), h->ih_vid,
1924             PrintInode(stmp, h->ih_ino), errno);
1925         *ec = VSALVAGE;
1926         return;
1927     }
1928
1929     vsn = (struct versionStamp *)to;
1930     nbytes = FDH_PREAD(fdP, to, size, 0);
1931     if (nbytes < 0) {
1932         Log("ReadHeader: Failed to read %s header file "
1933             "(volume=%u, inode=%s); errno=%d\n", HeaderName(magic), h->ih_vid,
1934             PrintInode(stmp, h->ih_ino), errno);
1935         *ec = VSALVAGE;
1936         FDH_REALLYCLOSE(fdP);
1937         return;
1938     }
1939     if (nbytes != size) {
1940         Log("ReadHeader: Incorrect number of bytes read from %s header file "
1941             "(volume=%u, inode=%s); expected=%d, read=%d\n",
1942             HeaderName(magic), h->ih_vid, PrintInode(stmp, h->ih_ino), size,
1943             (int)nbytes);
1944         *ec = VSALVAGE;
1945         FDH_REALLYCLOSE(fdP);
1946         return;
1947     }
1948     if (vsn->magic != magic) {
1949         Log("ReadHeader: Incorrect magic for %s header file "
1950             "(volume=%u, inode=%s); expected=0x%x, read=0x%x\n",
1951             HeaderName(magic), h->ih_vid, PrintInode(stmp, h->ih_ino), magic,
1952             vsn->magic);
1953         *ec = VSALVAGE;
1954         FDH_REALLYCLOSE(fdP);
1955         return;
1956     }
1957
1958     FDH_CLOSE(fdP);
1959
1960     /* Check is conditional, in case caller wants to inspect version himself */
1961     if (version && vsn->version != version) {
1962         Log("ReadHeader: Incorrect version for %s header file "
1963             "(volume=%u, inode=%s); expected=%x, read=%x\n",
1964             HeaderName(magic), h->ih_vid, PrintInode(stmp, h->ih_ino),
1965             version, vsn->version);
1966         *ec = VSALVAGE;
1967     }
1968 }
1969
1970 void
1971 WriteVolumeHeader_r(Error * ec, Volume * vp)
1972 {
1973     IHandle_t *h = V_diskDataHandle(vp);
1974     FdHandle_t *fdP;
1975
1976     *ec = 0;
1977
1978     fdP = IH_OPEN(h);
1979     if (fdP == NULL) {
1980         *ec = VSALVAGE;
1981         return;
1982     }
1983     if (FDH_PWRITE(fdP, (char *)&V_disk(vp), sizeof(V_disk(vp)), 0)
1984         != sizeof(V_disk(vp))) {
1985         *ec = VSALVAGE;
1986         FDH_REALLYCLOSE(fdP);
1987         return;
1988     }
1989     FDH_CLOSE(fdP);
1990 }
1991
1992 /* VolumeHeaderToDisk
1993  * Allows for storing 64 bit inode numbers in on-disk volume header
1994  * file.
1995  */
1996 /* convert in-memory representation of a volume header to the
1997  * on-disk representation of a volume header */
1998 void
1999 VolumeHeaderToDisk(VolumeDiskHeader_t * dh, VolumeHeader_t * h)
2000 {
2001
2002     memset(dh, 0, sizeof(VolumeDiskHeader_t));
2003     dh->stamp = h->stamp;
2004     dh->id = h->id;
2005     dh->parent = h->parent;
2006
2007 #ifdef AFS_64BIT_IOPS_ENV
2008     dh->volumeInfo_lo = (afs_int32) h->volumeInfo & 0xffffffff;
2009     dh->volumeInfo_hi = (afs_int32) (h->volumeInfo >> 32) & 0xffffffff;
2010     dh->smallVnodeIndex_lo = (afs_int32) h->smallVnodeIndex & 0xffffffff;
2011     dh->smallVnodeIndex_hi =
2012         (afs_int32) (h->smallVnodeIndex >> 32) & 0xffffffff;
2013     dh->largeVnodeIndex_lo = (afs_int32) h->largeVnodeIndex & 0xffffffff;
2014     dh->largeVnodeIndex_hi =
2015         (afs_int32) (h->largeVnodeIndex >> 32) & 0xffffffff;
2016     dh->linkTable_lo = (afs_int32) h->linkTable & 0xffffffff;
2017     dh->linkTable_hi = (afs_int32) (h->linkTable >> 32) & 0xffffffff;
2018 #else
2019     dh->volumeInfo_lo = h->volumeInfo;
2020     dh->smallVnodeIndex_lo = h->smallVnodeIndex;
2021     dh->largeVnodeIndex_lo = h->largeVnodeIndex;
2022     dh->linkTable_lo = h->linkTable;
2023 #endif
2024 }
2025
2026 /* DiskToVolumeHeader
2027  * Converts an on-disk representation of a volume header to
2028  * the in-memory representation of a volume header.
2029  *
2030  * Makes the assumption that AFS has *always*
2031  * zero'd the volume header file so that high parts of inode
2032  * numbers are 0 in older (SGI EFS) volume header files.
2033  */
2034 void
2035 DiskToVolumeHeader(VolumeHeader_t * h, VolumeDiskHeader_t * dh)
2036 {
2037     memset(h, 0, sizeof(VolumeHeader_t));
2038     h->stamp = dh->stamp;
2039     h->id = dh->id;
2040     h->parent = dh->parent;
2041
2042 #ifdef AFS_64BIT_IOPS_ENV
2043     h->volumeInfo =
2044         (Inode) dh->volumeInfo_lo | ((Inode) dh->volumeInfo_hi << 32);
2045
2046     h->smallVnodeIndex =
2047         (Inode) dh->smallVnodeIndex_lo | ((Inode) dh->
2048                                           smallVnodeIndex_hi << 32);
2049
2050     h->largeVnodeIndex =
2051         (Inode) dh->largeVnodeIndex_lo | ((Inode) dh->
2052                                           largeVnodeIndex_hi << 32);
2053     h->linkTable =
2054         (Inode) dh->linkTable_lo | ((Inode) dh->linkTable_hi << 32);
2055 #else
2056     h->volumeInfo = dh->volumeInfo_lo;
2057     h->smallVnodeIndex = dh->smallVnodeIndex_lo;
2058     h->largeVnodeIndex = dh->largeVnodeIndex_lo;
2059     h->linkTable = dh->linkTable_lo;
2060 #endif
2061 }
2062
2063
2064 /***************************************************/
2065 /* Volume Attachment routines                      */
2066 /***************************************************/
2067
2068 #ifdef AFS_DEMAND_ATTACH_FS
2069 /**
2070  * pre-attach a volume given its path.
2071  *
2072  * @param[out] ec         outbound error code
2073  * @param[in]  partition  partition path string
2074  * @param[in]  name       volume id string
2075  *
2076  * @return volume object pointer
2077  *
2078  * @note A pre-attached volume will only have its partition
2079  *       and hashid fields initialized.  At first call to
2080  *       VGetVolume, the volume will be fully attached.
2081  *
2082  */
2083 Volume *
2084 VPreAttachVolumeByName(Error * ec, char *partition, char *name)
2085 {
2086     Volume * vp;
2087     VOL_LOCK;
2088     vp = VPreAttachVolumeByName_r(ec, partition, name);
2089     VOL_UNLOCK;
2090     return vp;
2091 }
2092
2093 /**
2094  * pre-attach a volume given its path.
2095  *
2096  * @param[out] ec         outbound error code
2097  * @param[in]  partition  path to vice partition
2098  * @param[in]  name       volume id string
2099  *
2100  * @return volume object pointer
2101  *
2102  * @pre VOL_LOCK held
2103  *
2104  * @internal volume package internal use only.
2105  */
2106 Volume *
2107 VPreAttachVolumeByName_r(Error * ec, char *partition, char *name)
2108 {
2109     return VPreAttachVolumeById_r(ec,
2110                                   partition,
2111                                   VolumeNumber(name));
2112 }
2113
2114 /**
2115  * pre-attach a volume given its path and numeric volume id.
2116  *
2117  * @param[out] ec          error code return
2118  * @param[in]  partition   path to vice partition
2119  * @param[in]  volumeId    numeric volume id
2120  *
2121  * @return volume object pointer
2122  *
2123  * @pre VOL_LOCK held
2124  *
2125  * @internal volume package internal use only.
2126  */
2127 Volume *
2128 VPreAttachVolumeById_r(Error * ec,
2129                        char * partition,
2130                        VolId volumeId)
2131 {
2132     Volume *vp;
2133     struct DiskPartition64 *partp;
2134
2135     *ec = 0;
2136
2137     osi_Assert(programType == fileServer);
2138
2139     if (!(partp = VGetPartition_r(partition, 0))) {
2140         *ec = VNOVOL;
2141         Log("VPreAttachVolumeById_r:  Error getting partition (%s)\n", partition);
2142         return NULL;
2143     }
2144
2145     vp = VLookupVolume_r(ec, volumeId, NULL);
2146     if (*ec) {
2147         return NULL;
2148     }
2149
2150     return VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2151 }
2152
2153 /**
2154  * preattach a volume.
2155  *
2156  * @param[out] ec     outbound error code
2157  * @param[in]  partp  pointer to partition object
2158  * @param[in]  vp     pointer to volume object
2159  * @param[in]  vid    volume id
2160  *
2161  * @return volume object pointer
2162  *
2163  * @pre VOL_LOCK is held.
2164  *
2165  * @warning Returned volume object pointer does not have to
2166  *          equal the pointer passed in as argument vp.  There
2167  *          are potential race conditions which can result in
2168  *          the pointers having different values.  It is up to
2169  *          the caller to make sure that references are handled
2170  *          properly in this case.
2171  *
2172  * @note If there is already a volume object registered with
2173  *       the same volume id, its pointer MUST be passed as
2174  *       argument vp.  Failure to do so will result in a silent
2175  *       failure to preattach.
2176  *
2177  * @internal volume package internal use only.
2178  */
2179 Volume *
2180 VPreAttachVolumeByVp_r(Error * ec,
2181                        struct DiskPartition64 * partp,
2182                        Volume * vp,
2183                        VolId vid)
2184 {
2185     Volume *nvp = NULL;
2186
2187     *ec = 0;
2188
2189     /* check to see if pre-attach already happened */
2190     if (vp &&
2191         (V_attachState(vp) != VOL_STATE_UNATTACHED) &&
2192         (V_attachState(vp) != VOL_STATE_DELETED) &&
2193         (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
2194         !VIsErrorState(V_attachState(vp))) {
2195         /*
2196          * pre-attach is a no-op in all but the following cases:
2197          *
2198          *   - volume is unattached
2199          *   - volume is in an error state
2200          *   - volume is pre-attached
2201          */
2202         Log("VPreattachVolumeByVp_r: volume %u not in quiescent state (state %u flags 0x%x)\n",
2203             vid, V_attachState(vp), V_attachFlags(vp));
2204         goto done;
2205     } else if (vp) {
2206         /* we're re-attaching a volume; clear out some old state */
2207         memset(&vp->salvage, 0, sizeof(struct VolumeOnlineSalvage));
2208
2209         if (V_partition(vp) != partp) {
2210             /* XXX potential race */
2211             DeleteVolumeFromVByPList_r(vp);
2212         }
2213     } else {
2214         /* if we need to allocate a new Volume struct,
2215          * go ahead and drop the vol glock, otherwise
2216          * do the basic setup synchronised, as it's
2217          * probably not worth dropping the lock */
2218         VOL_UNLOCK;
2219
2220         /* allocate the volume structure */
2221         vp = nvp = (Volume *) malloc(sizeof(Volume));
2222         osi_Assert(vp != NULL);
2223         memset(vp, 0, sizeof(Volume));
2224         queue_Init(&vp->vnode_list);
2225         queue_Init(&vp->rx_call_list);
2226         CV_INIT(&V_attachCV(vp), "vp attach", CV_DEFAULT, 0);
2227     }
2228
2229     /* link the volume with its associated vice partition */
2230     vp->device = partp->device;
2231     vp->partition = partp;
2232
2233     vp->hashid = vid;
2234     vp->specialStatus = 0;
2235
2236     /* if we dropped the lock, reacquire the lock,
2237      * check for pre-attach races, and then add
2238      * the volume to the hash table */
2239     if (nvp) {
2240         VOL_LOCK;
2241         nvp = VLookupVolume_r(ec, vid, NULL);
2242         if (*ec) {
2243             free(vp);
2244             vp = NULL;
2245             goto done;
2246         } else if (nvp) { /* race detected */
2247             free(vp);
2248             vp = nvp;
2249             goto done;
2250         } else {
2251           /* hack to make up for VChangeState_r() decrementing
2252            * the old state counter */
2253           VStats.state_levels[0]++;
2254         }
2255     }
2256
2257     /* put pre-attached volume onto the hash table
2258      * and bring it up to the pre-attached state */
2259     AddVolumeToHashTable(vp, vp->hashid);
2260     AddVolumeToVByPList_r(vp);
2261     VLRU_Init_Node_r(vp);
2262     VChangeState_r(vp, VOL_STATE_PREATTACHED);
2263
2264     if (LogLevel >= 5)
2265         Log("VPreAttachVolumeByVp_r:  volume %u pre-attached\n", vp->hashid);
2266
2267   done:
2268     if (*ec)
2269         return NULL;
2270     else
2271         return vp;
2272 }
2273 #endif /* AFS_DEMAND_ATTACH_FS */
2274
2275 /* Attach an existing volume, given its pathname, and return a
2276    pointer to the volume header information.  The volume also
2277    normally goes online at this time.  An offline volume
2278    must be reattached to make it go online */
2279 Volume *
2280 VAttachVolumeByName(Error * ec, char *partition, char *name, int mode)
2281 {
2282     Volume *retVal;
2283     VOL_LOCK;
2284     retVal = VAttachVolumeByName_r(ec, partition, name, mode);
2285     VOL_UNLOCK;
2286     return retVal;
2287 }
2288
2289 Volume *
2290 VAttachVolumeByName_r(Error * ec, char *partition, char *name, int mode)
2291 {
2292     Volume *vp = NULL;
2293     struct DiskPartition64 *partp;
2294     char path[64];
2295     int isbusy = 0;
2296     VolId volumeId;
2297     int checkedOut;
2298 #ifdef AFS_DEMAND_ATTACH_FS
2299     VolumeStats stats_save;
2300     Volume *svp = NULL;
2301 #endif /* AFS_DEMAND_ATTACH_FS */
2302
2303     *ec = 0;
2304
2305     volumeId = VolumeNumber(name);
2306
2307     if (!(partp = VGetPartition_r(partition, 0))) {
2308         *ec = VNOVOL;
2309         Log("VAttachVolume: Error getting partition (%s)\n", partition);
2310         goto done;
2311     }
2312
2313     if (VRequiresPartLock()) {
2314         osi_Assert(VInit == 3);
2315         VLockPartition_r(partition);
2316     } else if (programType == fileServer) {
2317 #ifdef AFS_DEMAND_ATTACH_FS
2318         /* lookup the volume in the hash table */
2319         vp = VLookupVolume_r(ec, volumeId, NULL);
2320         if (*ec) {
2321             return NULL;
2322         }
2323
2324         if (vp) {
2325             /* save any counters that are supposed to
2326              * be monotonically increasing over the
2327              * lifetime of the fileserver */
2328             memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2329         } else {
2330             memset(&stats_save, 0, sizeof(VolumeStats));
2331         }
2332
2333         /* if there's something in the hash table, and it's not
2334          * in the pre-attach state, then we may need to detach
2335          * it before proceeding */
2336         if (vp && (V_attachState(vp) != VOL_STATE_PREATTACHED)) {
2337             VCreateReservation_r(vp);
2338             VWaitExclusiveState_r(vp);
2339
2340             /* at this point state must be one of:
2341              *   - UNATTACHED
2342              *   - ATTACHED
2343              *   - SHUTTING_DOWN
2344              *   - GOING_OFFLINE
2345              *   - SALVAGING
2346              *   - ERROR
2347              *   - DELETED
2348              */
2349
2350             if (vp->specialStatus == VBUSY)
2351                 isbusy = 1;
2352
2353             /* if it's already attached, see if we can return it */
2354             if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2355                 VGetVolumeByVp_r(ec, vp);
2356                 if (V_inUse(vp) == fileServer) {
2357                     VCancelReservation_r(vp);
2358                     return vp;
2359                 }
2360
2361                 /* otherwise, we need to detach, and attempt to re-attach */
2362                 VDetachVolume_r(ec, vp);
2363                 if (*ec) {
2364                     Log("VAttachVolume: Error detaching old volume instance (%s)\n", name);
2365                 }
2366             } else {
2367                 /* if it isn't fully attached, delete from the hash tables,
2368                    and let the refcounter handle the rest */
2369                 DeleteVolumeFromHashTable(vp);
2370                 DeleteVolumeFromVByPList_r(vp);
2371             }
2372
2373             VCancelReservation_r(vp);
2374             vp = NULL;
2375         }
2376
2377         /* pre-attach volume if it hasn't been done yet */
2378         if (!vp ||
2379             (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2380             (V_attachState(vp) == VOL_STATE_DELETED) ||
2381             (V_attachState(vp) == VOL_STATE_ERROR)) {
2382             svp = vp;
2383             vp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2384             if (*ec) {
2385                 return NULL;
2386             }
2387         }
2388
2389         osi_Assert(vp != NULL);
2390
2391         /* handle pre-attach races
2392          *
2393          * multiple threads can race to pre-attach a volume,
2394          * but we can't let them race beyond that
2395          *
2396          * our solution is to let the first thread to bring
2397          * the volume into an exclusive state win; the other
2398          * threads just wait until it finishes bringing the
2399          * volume online, and then they do a vgetvolumebyvp
2400          */
2401         if (svp && (svp != vp)) {
2402             /* wait for other exclusive ops to finish */
2403             VCreateReservation_r(vp);
2404             VWaitExclusiveState_r(vp);
2405
2406             /* get a heavyweight ref, kill the lightweight ref, and return */
2407             VGetVolumeByVp_r(ec, vp);
2408             VCancelReservation_r(vp);
2409             return vp;
2410         }
2411
2412         /* at this point, we are chosen as the thread to do
2413          * demand attachment for this volume. all other threads
2414          * doing a getvolume on vp->hashid will block until we finish */
2415
2416         /* make sure any old header cache entries are invalidated
2417          * before proceeding */
2418         FreeVolumeHeader(vp);
2419
2420         VChangeState_r(vp, VOL_STATE_ATTACHING);
2421
2422         /* restore any saved counters */
2423         memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2424 #else /* AFS_DEMAND_ATTACH_FS */
2425         vp = VGetVolume_r(ec, volumeId);
2426         if (vp) {
2427             if (V_inUse(vp) == fileServer)
2428                 return vp;
2429             if (vp->specialStatus == VBUSY)
2430                 isbusy = 1;
2431             VDetachVolume_r(ec, vp);
2432             if (*ec) {
2433                 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2434             }
2435             vp = NULL;
2436         }
2437 #endif /* AFS_DEMAND_ATTACH_FS */
2438     }
2439
2440     *ec = 0;
2441     strcpy(path, VPartitionPath(partp));
2442
2443     VOL_UNLOCK;
2444
2445     strcat(path, OS_DIRSEP);
2446     strcat(path, name);
2447
2448     if (!vp) {
2449       vp = (Volume *) calloc(1, sizeof(Volume));
2450       osi_Assert(vp != NULL);
2451       vp->hashid = volumeId;
2452       vp->device = partp->device;
2453       vp->partition = partp;
2454       queue_Init(&vp->vnode_list);
2455       queue_Init(&vp->rx_call_list);
2456 #ifdef AFS_DEMAND_ATTACH_FS
2457       CV_INIT(&V_attachCV(vp), "vp attach", CV_DEFAULT, 0);
2458 #endif /* AFS_DEMAND_ATTACH_FS */
2459     }
2460
2461     /* attach2 is entered without any locks, and returns
2462      * with vol_glock_mutex held */
2463     vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2464
2465     if (VCanUseFSSYNC() && vp) {
2466 #ifdef AFS_DEMAND_ATTACH_FS
2467         if ((mode == V_VOLUPD) || (VolumeWriteable(vp) && (mode == V_CLONE))) {
2468             /* mark volume header as in use so that volser crashes lead to a
2469              * salvage attempt */
2470             VUpdateVolume_r(ec, vp, 0);
2471         }
2472         /* for dafs, we should tell the fileserver, except for V_PEEK
2473          * where we know it is not necessary */
2474         if (mode == V_PEEK) {
2475             vp->needsPutBack = 0;
2476         } else {
2477             vp->needsPutBack = VOL_PUTBACK;
2478         }
2479 #else /* !AFS_DEMAND_ATTACH_FS */
2480         /* duplicate computation in fssync.c about whether the server
2481          * takes the volume offline or not.  If the volume isn't
2482          * offline, we must not return it when we detach the volume,
2483          * or the server will abort */
2484         if (mode == V_READONLY || mode == V_PEEK
2485             || (!VolumeWriteable(vp) && (mode == V_CLONE || mode == V_DUMP)))
2486             vp->needsPutBack = 0;
2487         else
2488             vp->needsPutBack = VOL_PUTBACK;
2489 #endif /* !AFS_DEMAND_ATTACH_FS */
2490     }
2491 #ifdef FSSYNC_BUILD_CLIENT
2492     /* Only give back the vol to the fileserver if we checked it out; attach2
2493      * will set checkedOut only if we successfully checked it out from the
2494      * fileserver. */
2495     if (VCanUseFSSYNC() && vp == NULL && checkedOut) {
2496
2497 #ifdef AFS_DEMAND_ATTACH_FS
2498         /* If we couldn't attach but we scheduled a salvage, we already
2499          * notified the fileserver; don't online it now */
2500         if (*ec != VSALVAGING)
2501 #endif /* AFS_DEMAND_ATTACH_FS */
2502         FSYNC_VolOp(volumeId, partition, FSYNC_VOL_ON, 0, NULL);
2503     } else
2504 #endif
2505     if (programType == fileServer && vp) {
2506 #ifdef AFS_DEMAND_ATTACH_FS
2507         /*
2508          * we can get here in cases where we don't "own"
2509          * the volume (e.g. volume owned by a utility).
2510          * short circuit around potential disk header races.
2511          */
2512         if (V_attachState(vp) != VOL_STATE_ATTACHED) {
2513             goto done;
2514         }
2515 #endif
2516         VUpdateVolume_r(ec, vp, 0);
2517         if (*ec) {
2518             Log("VAttachVolume: Error updating volume\n");
2519             if (vp)
2520                 VPutVolume_r(vp);
2521             goto done;
2522         }
2523         if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2524 #ifndef AFS_DEMAND_ATTACH_FS
2525             /* This is a hack: by temporarily setting the incore
2526              * dontSalvage flag ON, the volume will be put back on the
2527              * Update list (with dontSalvage OFF again).  It will then
2528              * come back in N minutes with DONT_SALVAGE eventually
2529              * set.  This is the way that volumes that have never had
2530              * it set get it set; or that volumes that have been
2531              * offline without DONT SALVAGE having been set also
2532              * eventually get it set */
2533             V_dontSalvage(vp) = DONT_SALVAGE;
2534 #endif /* !AFS_DEMAND_ATTACH_FS */
2535             VAddToVolumeUpdateList_r(ec, vp);
2536             if (*ec) {
2537                 Log("VAttachVolume: Error adding volume to update list\n");
2538                 if (vp)
2539                     VPutVolume_r(vp);
2540                 goto done;
2541             }
2542         }
2543         if (LogLevel)
2544             Log("VOnline:  volume %u (%s) attached and online\n", V_id(vp),
2545                 V_name(vp));
2546     }
2547
2548   done:
2549     if (VRequiresPartLock()) {
2550         VUnlockPartition_r(partition);
2551     }
2552     if (*ec) {
2553 #ifdef AFS_DEMAND_ATTACH_FS
2554         /* attach failed; make sure we're in error state */
2555         if (vp && !VIsErrorState(V_attachState(vp))) {
2556             VChangeState_r(vp, VOL_STATE_ERROR);
2557         }
2558 #endif /* AFS_DEMAND_ATTACH_FS */
2559         return NULL;
2560     } else {
2561         return vp;
2562     }
2563 }
2564
2565 #ifdef AFS_DEMAND_ATTACH_FS
2566 /* VAttachVolumeByVp_r
2567  *
2568  * finish attaching a volume that is
2569  * in a less than fully attached state
2570  */
2571 /* caller MUST hold a ref count on vp */
2572 static Volume *
2573 VAttachVolumeByVp_r(Error * ec, Volume * vp, int mode)
2574 {
2575     char name[VMAXPATHLEN];
2576     int reserve = 0;
2577     struct DiskPartition64 *partp;
2578     char path[64];
2579     int isbusy = 0;
2580     VolId volumeId;
2581     Volume * nvp = NULL;
2582     VolumeStats stats_save;
2583     int checkedOut;
2584     *ec = 0;
2585
2586     /* volume utility should never call AttachByVp */
2587     osi_Assert(programType == fileServer);
2588
2589     volumeId = vp->hashid;
2590     partp = vp->partition;
2591     VolumeExternalName_r(volumeId, name, sizeof(name));
2592
2593
2594     /* if another thread is performing a blocking op, wait */
2595     VWaitExclusiveState_r(vp);
2596
2597     memcpy(&stats_save, &vp->stats, sizeof(VolumeStats));
2598
2599     /* if it's already attached, see if we can return it */
2600     if (V_attachState(vp) == VOL_STATE_ATTACHED) {
2601         VGetVolumeByVp_r(ec, vp);
2602         if (V_inUse(vp) == fileServer) {
2603             return vp;
2604         } else {
2605             if (vp->specialStatus == VBUSY)
2606                 isbusy = 1;
2607             VDetachVolume_r(ec, vp);
2608             if (*ec) {
2609                 Log("VAttachVolume: Error detaching volume (%s)\n", name);
2610             }
2611             vp = NULL;
2612         }
2613     }
2614
2615     /* pre-attach volume if it hasn't been done yet */
2616     if (!vp ||
2617         (V_attachState(vp) == VOL_STATE_UNATTACHED) ||
2618         (V_attachState(vp) == VOL_STATE_DELETED) ||
2619         (V_attachState(vp) == VOL_STATE_ERROR)) {
2620         nvp = VPreAttachVolumeByVp_r(ec, partp, vp, volumeId);
2621         if (*ec) {
2622             return NULL;
2623         }
2624         if (nvp != vp) {
2625             reserve = 1;
2626             VCreateReservation_r(nvp);
2627             vp = nvp;
2628         }
2629     }
2630
2631     osi_Assert(vp != NULL);
2632     VChangeState_r(vp, VOL_STATE_ATTACHING);
2633
2634     /* restore monotonically increasing stats */
2635     memcpy(&vp->stats, &stats_save, sizeof(VolumeStats));
2636
2637     *ec = 0;
2638
2639     /* compute path to disk header */
2640     strcpy(path, VPartitionPath(partp));
2641
2642     VOL_UNLOCK;
2643
2644     strcat(path, OS_DIRSEP);
2645     strcat(path, name);
2646
2647     /* do volume attach
2648      *
2649      * NOTE: attach2 is entered without any locks, and returns
2650      * with vol_glock_mutex held */
2651     vp = attach2(ec, volumeId, path, partp, vp, isbusy, mode, &checkedOut);
2652
2653     /*
2654      * the event that an error was encountered, or
2655      * the volume was not brought to an attached state
2656      * for any reason, skip to the end.  We cannot
2657      * safely call VUpdateVolume unless we "own" it.
2658      */
2659     if (*ec ||
2660         (vp == NULL) ||
2661         (V_attachState(vp) != VOL_STATE_ATTACHED)) {
2662         goto done;
2663     }
2664
2665     VUpdateVolume_r(ec, vp, 0);
2666     if (*ec) {
2667         Log("VAttachVolume: Error updating volume %u\n", vp->hashid);
2668         VPutVolume_r(vp);
2669         goto done;
2670     }
2671     if (VolumeWriteable(vp) && V_dontSalvage(vp) == 0) {
2672 #ifndef AFS_DEMAND_ATTACH_FS
2673         /* This is a hack: by temporarily setting the incore
2674          * dontSalvage flag ON, the volume will be put back on the
2675          * Update list (with dontSalvage OFF again).  It will then
2676          * come back in N minutes with DONT_SALVAGE eventually
2677          * set.  This is the way that volumes that have never had
2678          * it set get it set; or that volumes that have been
2679          * offline without DONT SALVAGE having been set also
2680          * eventually get it set */
2681         V_dontSalvage(vp) = DONT_SALVAGE;
2682 #endif /* !AFS_DEMAND_ATTACH_FS */
2683         VAddToVolumeUpdateList_r(ec, vp);
2684         if (*ec) {
2685             Log("VAttachVolume: Error adding volume %u to update list\n", vp->hashid);
2686             if (vp)
2687                 VPutVolume_r(vp);
2688             goto done;
2689         }
2690     }
2691     if (LogLevel)
2692         Log("VOnline:  volume %u (%s) attached and online\n", V_id(vp),
2693             V_name(vp));
2694   done:
2695     if (reserve) {
2696         VCancelReservation_r(nvp);
2697         reserve = 0;
2698     }
2699     if (*ec && (*ec != VOFFLINE) && (*ec != VSALVAGE)) {
2700         if (vp && !VIsErrorState(V_attachState(vp))) {
2701             VChangeState_r(vp, VOL_STATE_ERROR);
2702         }
2703         return NULL;
2704     } else {
2705         return vp;
2706     }
2707 }
2708
2709 /**
2710  * lock a volume on disk (non-blocking).
2711  *
2712  * @param[in] vp  The volume to lock
2713  * @param[in] locktype READ_LOCK or WRITE_LOCK
2714  *
2715  * @return operation status
2716  *  @retval 0 success, lock was obtained
2717  *  @retval EBUSY a conflicting lock was held by another process
2718  *  @retval EIO   error acquiring lock
2719  *
2720  * @pre If we're in the fileserver, vp is in an exclusive state
2721  *
2722  * @pre vp is not already locked
2723  */
2724 static int
2725 VLockVolumeNB(Volume *vp, int locktype)
2726 {
2727     int code;
2728
2729     osi_Assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2730     osi_Assert(!(V_attachFlags(vp) & VOL_LOCKED));
2731
2732     code = VLockVolumeByIdNB(vp->hashid, vp->partition, locktype);
2733     if (code == 0) {
2734         V_attachFlags(vp) |= VOL_LOCKED;
2735     }
2736
2737     return code;
2738 }
2739
2740 /**
2741  * unlock a volume on disk that was locked with VLockVolumeNB.
2742  *
2743  * @param[in] vp  volume to unlock
2744  *
2745  * @pre If we're in the fileserver, vp is in an exclusive state
2746  *
2747  * @pre vp has already been locked
2748  */
2749 static void
2750 VUnlockVolume(Volume *vp)
2751 {
2752     osi_Assert(programType != fileServer || VIsExclusiveState(V_attachState(vp)));
2753     osi_Assert((V_attachFlags(vp) & VOL_LOCKED));
2754
2755     VUnlockVolumeById(vp->hashid, vp->partition);
2756
2757     V_attachFlags(vp) &= ~VOL_LOCKED;
2758 }
2759 #endif /* AFS_DEMAND_ATTACH_FS */
2760
2761 /**
2762  * read in a vol header, possibly lock the vol header, and possibly check out
2763  * the vol header from the fileserver, as part of volume attachment.
2764  *
2765  * @param[out] ec     error code
2766  * @param[in] vp      volume pointer object
2767  * @param[in] partp   disk partition object of the attaching partition
2768  * @param[in] mode    attachment mode such as V_VOLUPD, V_DUMP, etc (see
2769  *                    volume.h)
2770  * @param[in] peek    1 to just try to read in the volume header and make sure
2771  *                    we don't try to lock the vol, or check it out from
2772  *                    FSSYNC or anything like that; 0 otherwise, for 'normal'
2773  *                    operation
2774  * @param[out] acheckedOut   If we successfully checked-out the volume from
2775  *                           the fileserver (if we needed to), this is set
2776  *                           to 1, otherwise it is untouched.
2777  *
2778  * @note As part of DAFS volume attachment, the volume header may be either
2779  *       read- or write-locked to ensure mutual exclusion of certain volume
2780  *       operations. In some cases in order to determine whether we need to
2781  *       read- or write-lock the header, we need to read in the header to see
2782  *       if the volume is RW or not. So, if we read in the header under a
2783  *       read-lock and determine that we actually need a write-lock on the
2784  *       volume header, this function will drop the read lock, acquire a write
2785  *       lock, and read the header in again.
2786  */
2787 static void
2788 attach_volume_header(Error *ec, Volume *vp, struct DiskPartition64 *partp,
2789                      int mode, int peek, int *acheckedOut)
2790 {
2791     struct VolumeDiskHeader diskHeader;
2792     struct VolumeHeader header;
2793     int code;
2794     int first_try = 1;
2795     int lock_tries = 0, checkout_tries = 0;
2796     int retry;
2797     VolumeId volid = vp->hashid;
2798 #ifdef FSSYNC_BUILD_CLIENT
2799     int checkout, done_checkout = 0;
2800 #endif /* FSSYNC_BUILD_CLIENT */
2801 #ifdef AFS_DEMAND_ATTACH_FS
2802     int locktype = 0, use_locktype = -1;
2803 #endif /* AFS_DEMAND_ATTACH_FS */
2804
2805  retry:
2806     retry = 0;
2807     *ec = 0;
2808
2809     if (lock_tries > VOL_MAX_CHECKOUT_RETRIES) {
2810         Log("VAttachVolume: retried too many times trying to lock header for "
2811             "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2812             VPartitionPath(partp));
2813         *ec = VNOVOL;
2814         goto done;
2815     }
2816     if (checkout_tries > VOL_MAX_CHECKOUT_RETRIES) {
2817         Log("VAttachVolume: retried too many times trying to checkout "
2818             "vol %lu part %s; giving up\n", afs_printable_uint32_lu(volid),
2819             VPartitionPath(partp));
2820         *ec = VNOVOL;
2821         goto done;
2822     }
2823
2824     if (VReadVolumeDiskHeader(volid, partp, NULL)) {
2825         /* short-circuit the 'volume does not exist' case */
2826         *ec = VNOVOL;
2827         goto done;
2828     }
2829
2830 #ifdef FSSYNC_BUILD_CLIENT
2831     checkout = !done_checkout;
2832     done_checkout = 1;
2833     if (!peek && checkout && VMustCheckoutVolume(mode)) {
2834         SYNC_response res;
2835         memset(&res, 0, sizeof(res));
2836
2837         if (FSYNC_VolOp(volid, partp->name, FSYNC_VOL_NEEDVOLUME, mode, &res)
2838             != SYNC_OK) {
2839
2840             if (res.hdr.reason == FSYNC_SALVAGE) {
2841                 Log("VAttachVolume: file server says volume %lu is salvaging\n",
2842                      afs_printable_uint32_lu(volid));
2843                 *ec = VSALVAGING;
2844             } else {
2845                 Log("VAttachVolume: attach of volume %lu apparently denied by file server\n",
2846                      afs_printable_uint32_lu(volid));
2847                 *ec = VNOVOL;   /* XXXX */
2848             }
2849             goto done;
2850         }
2851         *acheckedOut = 1;
2852     }
2853 #endif
2854
2855 #ifdef AFS_DEMAND_ATTACH_FS
2856     if (use_locktype < 0) {
2857         /* don't know whether vol is RO or RW; assume it's RO and we can retry
2858          * if it turns out to be RW */
2859         locktype = VVolLockType(mode, 0);
2860
2861     } else {
2862         /* a previous try says we should use use_locktype to lock the volume,
2863          * so use that */
2864         locktype = use_locktype;
2865     }
2866
2867     if (!peek && locktype) {
2868         code = VLockVolumeNB(vp, locktype);
2869         if (code) {
2870             if (code == EBUSY) {
2871                 Log("VAttachVolume: another program has vol %lu locked\n",
2872                     afs_printable_uint32_lu(volid));
2873             } else {
2874                 Log("VAttachVolume: error %d trying to lock vol %lu\n",
2875                     code, afs_printable_uint32_lu(volid));
2876             }
2877
2878             *ec = VNOVOL;
2879             goto done;
2880         }
2881     }
2882 #endif /* AFS_DEMAND_ATTACH_FS */
2883
2884     code = VReadVolumeDiskHeader(volid, partp, &diskHeader);
2885     if (code) {
2886         if (code == EIO) {
2887             *ec = VSALVAGE;
2888         } else {
2889             *ec = VNOVOL;
2890         }
2891         goto done;
2892     }
2893
2894     DiskToVolumeHeader(&header, &diskHeader);
2895
2896     IH_INIT(vp->vnodeIndex[vLarge].handle, partp->device, header.parent,
2897             header.largeVnodeIndex);
2898     IH_INIT(vp->vnodeIndex[vSmall].handle, partp->device, header.parent,
2899             header.smallVnodeIndex);
2900     IH_INIT(vp->diskDataHandle, partp->device, header.parent,
2901             header.volumeInfo);
2902     IH_INIT(vp->linkHandle, partp->device, header.parent, header.linkTable);
2903
2904     if (first_try) {
2905         /* only need to do this once */
2906         VOL_LOCK;
2907         GetVolumeHeader(vp);
2908         VOL_UNLOCK;
2909     }
2910
2911 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2912     /* demand attach changes the V_PEEK mechanism
2913      *
2914      * we can now suck the current disk data structure over
2915      * the fssync interface without going to disk
2916      *
2917      * (technically, we don't need to restrict this feature
2918      *  to demand attach fileservers.  However, I'm trying
2919      *  to limit the number of common code changes)
2920      */
2921     if (VCanUseFSSYNC() && (mode == V_PEEK || peek)) {
2922         SYNC_response res;
2923         res.payload.len = sizeof(VolumeDiskData);
2924         res.payload.buf = &vp->header->diskstuff;
2925
2926         if (FSYNC_VolOp(vp->hashid,
2927                         partp->name,
2928                         FSYNC_VOL_QUERY_HDR,
2929                         FSYNC_WHATEVER,
2930                         &res) == SYNC_OK) {
2931             goto disk_header_loaded;
2932         }
2933     }
2934 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2935     (void)ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
2936                      sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
2937
2938 #ifdef AFS_DEMAND_ATTACH_FS
2939     /* update stats */
2940     VOL_LOCK;
2941     IncUInt64(&VStats.hdr_loads);
2942     IncUInt64(&vp->stats.hdr_loads);
2943     VOL_UNLOCK;
2944 #endif /* AFS_DEMAND_ATTACH_FS */
2945
2946     if (*ec) {
2947         Log("VAttachVolume: Error reading diskDataHandle header for vol %lu; "
2948             "error=%u\n", afs_printable_uint32_lu(volid), *ec);
2949         goto done;
2950     }
2951
2952 #ifdef AFS_DEMAND_ATTACH_FS
2953 # ifdef FSSYNC_BUILD_CLIENT
2954  disk_header_loaded:
2955 # endif /* FSSYNC_BUILD_CLIENT */
2956
2957     /* if the lock type we actually used to lock the volume is different than
2958      * the lock type we should have used, retry with the lock type we should
2959      * use */
2960     use_locktype = VVolLockType(mode, VolumeWriteable(vp));
2961     if (locktype != use_locktype) {
2962         retry = 1;
2963         lock_tries++;
2964     }
2965 #endif /* AFS_DEMAND_ATTACH_FS */
2966
2967     *ec = 0;
2968
2969  done:
2970 #if defined(AFS_DEMAND_ATTACH_FS) && defined(FSSYNC_BUILD_CLIENT)
2971     if (!peek && *ec == 0 && retry == 0 && VMustCheckoutVolume(mode)) {
2972
2973         code = FSYNC_VerifyCheckout(volid, partp->name, FSYNC_VOL_NEEDVOLUME, mode);
2974
2975         if (code == SYNC_DENIED) {
2976             /* must retry checkout; fileserver no longer thinks we have
2977              * the volume */
2978             retry = 1;
2979             checkout_tries++;
2980             done_checkout = 0;
2981
2982         } else if (code != SYNC_OK) {
2983             *ec = VNOVOL;
2984         }
2985     }
2986 #endif /* AFS_DEMAND_ATTACH_FS && FSSYNC_BUILD_CLIENT */
2987
2988     if (*ec || retry) {
2989         /* either we are going to be called again for a second pass, or we
2990          * encountered an error; clean up in either case */
2991
2992 #ifdef AFS_DEMAND_ATTACH_FS
2993         if ((V_attachFlags(vp) & VOL_LOCKED)) {
2994             VUnlockVolume(vp);
2995         }
2996 #endif /* AFS_DEMAND_ATTACH_FS */
2997         if (vp->linkHandle) {
2998             IH_RELEASE(vp->vnodeIndex[vLarge].handle);
2999             IH_RELEASE(vp->vnodeIndex[vSmall].handle);
3000             IH_RELEASE(vp->diskDataHandle);
3001             IH_RELEASE(vp->linkHandle);
3002         }
3003     }
3004
3005     if (*ec) {
3006         return;
3007     }
3008     if (retry) {
3009         first_try = 0;
3010         goto retry;
3011     }
3012 }
3013
3014 #ifdef AFS_DEMAND_ATTACH_FS
3015 static void
3016 attach_check_vop(Error *ec, VolumeId volid, struct DiskPartition64 *partp,
3017                  Volume *vp, int *acheckedOut)
3018 {
3019     *ec = 0;
3020
3021     if (vp->pending_vol_op) {
3022
3023         VOL_LOCK;
3024
3025         if (vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningUnknown) {
3026             int code;
3027             code = VVolOpLeaveOnlineNoHeader_r(vp, vp->pending_vol_op);
3028             if (code == 1) {
3029                 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3030             } else if (code == 0) {
3031                 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3032
3033             } else {
3034                 /* we need the vol header to determine if the volume can be
3035                  * left online for the vop, so... get the header */
3036
3037                 VOL_UNLOCK;
3038
3039                 /* attach header with peek=1 to avoid checking out the volume
3040                  * or locking it; we just want the header info, we're not
3041                  * messing with the volume itself at all */
3042                 attach_volume_header(ec, vp, partp, V_PEEK, 1, acheckedOut);
3043                 if (*ec) {
3044                     return;
3045                 }
3046
3047                 VOL_LOCK;
3048
3049                 if (VVolOpLeaveOnline_r(vp, vp->pending_vol_op)) {
3050                     vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
3051                 } else {
3052                     vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
3053                 }
3054
3055                 /* make sure we grab a new vol header and re-open stuff on
3056                  * actual attachment; we can't keep the data we grabbed, since
3057                  * it was not done under a lock and thus not safe */
3058                 FreeVolumeHeader(vp);
3059                 VReleaseVolumeHandles_r(vp);
3060             }
3061         }
3062         /* see if the pending volume op requires exclusive access */
3063         switch (vp->pending_vol_op->vol_op_state) {
3064         case FSSYNC_VolOpPending:
3065             /* this should never happen */
3066             osi_Assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpPending);
3067             break;
3068
3069         case FSSYNC_VolOpRunningUnknown:
3070             /* this should never happen; we resolved 'unknown' above */
3071             osi_Assert(vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
3072             break;
3073
3074         case FSSYNC_VolOpRunningOffline:
3075             /* mark the volume down */
3076             *ec = VOFFLINE;
3077             VChangeState_r(vp, VOL_STATE_UNATTACHED);
3078
3079             /* do not set V_offlineMessage here; we don't have ownership of
3080              * the volume (and probably do not have the header loaded), so we
3081              * can't alter the disk header */
3082
3083             /* check to see if we should set the specialStatus flag */
3084             if (VVolOpSetVBusy_r(vp, vp->pending_vol_op)) {
3085                 /* don't overwrite specialStatus if it was already set to
3086                  * something else (e.g. VMOVED) */
3087                 if (!vp->specialStatus) {
3088                     vp->specialStatus = VBUSY;
3089                 }
3090             }
3091             break;
3092
3093         default:
3094             break;
3095         }
3096
3097         VOL_UNLOCK;
3098     }
3099 }
3100 #endif /* AFS_DEMAND_ATTACH_FS */
3101
3102 /**
3103  * volume attachment helper function.
3104  *
3105  * @param[out] ec      error code
3106  * @param[in] volumeId volume ID of the attaching volume
3107  * @param[in] path     full path to the volume header .vol file
3108  * @param[in] partp    disk partition object for the attaching partition
3109  * @param[in] vp       volume object; vp->hashid, vp->device, vp->partition,
3110  *                     vp->vnode_list, vp->rx_call_list, and V_attachCV (for
3111  *                     DAFS) should already be initialized
3112  * @param[in] isbusy   1 if vp->specialStatus should be set to VBUSY; that is,
3113  *                     if there is a volume operation running for this volume
3114  *                     that should set the volume to VBUSY during its run. 0
3115  *                     otherwise. (see VVolOpSetVBusy_r)
3116  * @param[in] mode     attachment mode such as V_VOLUPD, V_DUMP, etc (see
3117  *                     volume.h)
3118  * @param[out] acheckedOut   If we successfully checked-out the volume from
3119  *                           the fileserver (if we needed to), this is set
3120  *                           to 1, otherwise it is 0.
3121  *
3122  * @return pointer to the semi-attached volume pointer
3123  *  @retval NULL an error occurred (check value of *ec)
3124  *  @retval vp volume successfully attaching
3125  *
3126  * @pre no locks held
3127  *
3128  * @post VOL_LOCK held
3129  */
3130 static Volume *
3131 attach2(Error * ec, VolId volumeId, char *path, struct DiskPartition64 *partp,
3132         Volume * vp, int isbusy, int mode, int *acheckedOut)
3133 {
3134     /* have we read in the header successfully? */
3135     int read_header = 0;
3136
3137 #ifdef AFS_DEMAND_ATTACH_FS
3138     /* should we FreeVolume(vp) instead of VCheckFree(vp) in the error
3139      * cleanup? */
3140     int forcefree = 0;
3141
3142     /* in the case of an error, to what state should the volume be
3143      * transitioned? */
3144     VolState error_state = VOL_STATE_ERROR;
3145 #endif /* AFS_DEMAND_ATTACH_FS */
3146
3147     *ec = 0;
3148
3149     vp->vnodeIndex[vLarge].handle = NULL;
3150     vp->vnodeIndex[vSmall].handle = NULL;
3151     vp->diskDataHandle = NULL;
3152     vp->linkHandle = NULL;
3153
3154     *acheckedOut = 0;
3155
3156 #ifdef AFS_DEMAND_ATTACH_FS
3157     attach_check_vop(ec, volumeId, partp, vp, acheckedOut);
3158     if (!*ec) {
3159         attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3160     }
3161 #else
3162     attach_volume_header(ec, vp, partp, mode, 0, acheckedOut);
3163 #endif /* !AFS_DEMAND_ATTACH_FS */
3164
3165     if (*ec == VNOVOL) {
3166         /* if the volume doesn't exist, skip straight to 'error' so we don't
3167          * request a salvage */
3168         VOL_LOCK;
3169         goto error_notbroken;
3170     }
3171
3172     if (!*ec) {
3173         read_header = 1;
3174
3175         /* ensure that we don't override specialStatus if it was set to
3176          * something else (e.g. VMOVED) */
3177         if (isbusy && !vp->specialStatus) {
3178             vp->specialStatus = VBUSY;
3179         }
3180         vp->shuttingDown = 0;
3181         vp->goingOffline = 0;
3182         vp->nUsers = 1;
3183 #ifdef AFS_DEMAND_ATTACH_FS
3184         vp->stats.last_attach = FT_ApproxTime();
3185         vp->stats.attaches++;
3186 #endif
3187
3188         VOL_LOCK;
3189         IncUInt64(&VStats.attaches);
3190         vp->cacheCheck = ++VolumeCacheCheck;
3191         /* just in case this ever rolls over */
3192         if (!vp->cacheCheck)
3193             vp->cacheCheck = ++VolumeCacheCheck;
3194         VOL_UNLOCK;
3195
3196 #ifdef AFS_DEMAND_ATTACH_FS
3197         V_attachFlags(vp) |= VOL_HDR_LOADED;
3198         vp->stats.last_hdr_load = vp->stats.last_attach;
3199 #endif /* AFS_DEMAND_ATTACH_FS */
3200     }
3201
3202     if (!*ec) {
3203         struct IndexFileHeader iHead;
3204
3205 #if OPENAFS_VOL_STATS
3206         /*
3207          * We just read in the diskstuff part of the header.  If the detailed
3208          * volume stats area has not yet been initialized, we should bzero the
3209          * area and mark it as initialized.
3210          */
3211         if (!(V_stat_initialized(vp))) {
3212             memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
3213             V_stat_initialized(vp) = 1;
3214         }
3215 #endif /* OPENAFS_VOL_STATS */
3216
3217         (void)ReadHeader(ec, vp->vnodeIndex[vSmall].handle,
3218                          (char *)&iHead, sizeof(iHead),
3219                          SMALLINDEXMAGIC, SMALLINDEXVERSION);
3220
3221         if (*ec) {
3222             Log("VAttachVolume: Error reading smallVnode vol header %s; error=%u\n", path, *ec);
3223         }
3224     }
3225
3226     if (!*ec) {
3227         struct IndexFileHeader iHead;
3228
3229         (void)ReadHeader(ec, vp->vnodeIndex[vLarge].handle,
3230                          (char *)&iHead, sizeof(iHead),
3231                          LARGEINDEXMAGIC, LARGEINDEXVERSION);
3232
3233         if (*ec) {
3234             Log("VAttachVolume: Error reading largeVnode vol header %s; error=%u\n", path, *ec);
3235         }
3236     }
3237
3238 #ifdef AFS_NAMEI_ENV
3239     if (!*ec) {
3240         struct versionStamp stamp;
3241
3242         (void)ReadHeader(ec, V_linkHandle(vp), (char *)&stamp,
3243                          sizeof(stamp), LINKTABLEMAGIC, LINKTABLEVERSION);
3244
3245         if (*ec) {
3246             Log("VAttachVolume: Error reading namei vol header %s; error=%u\n", path, *ec);
3247         }
3248     }
3249 #endif /* AFS_NAMEI_ENV */
3250
3251 #if defined(AFS_DEMAND_ATTACH_FS)
3252     if (*ec && ((*ec != VOFFLINE) || (V_attachState(vp) != VOL_STATE_UNATTACHED))) {
3253         VOL_LOCK;
3254         if (!VCanScheduleSalvage()) {
3255             Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3256         }
3257         VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3258         vp->nUsers = 0;
3259
3260         goto locked_error;
3261     } else if (*ec) {
3262         /* volume operation in progress */
3263         VOL_LOCK;
3264         goto error_notbroken;
3265     }
3266 #else /* AFS_DEMAND_ATTACH_FS */
3267     if (*ec) {
3268         Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
3269         goto unlocked_error;
3270     }
3271 #endif /* AFS_DEMAND_ATTACH_FS */
3272
3273     if (V_needsSalvaged(vp)) {
3274         if (vp->specialStatus)
3275             vp->specialStatus = 0;
3276         VOL_LOCK;
3277 #if defined(AFS_DEMAND_ATTACH_FS)
3278         if (!VCanScheduleSalvage()) {
3279             Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
3280         }
3281         VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3282         vp->nUsers = 0;
3283
3284 #else /* AFS_DEMAND_ATTACH_FS */
3285         *ec = VSALVAGE;
3286 #endif /* AFS_DEMAND_ATTACH_FS */
3287
3288         goto locked_error;
3289     }
3290
3291     VOL_LOCK;
3292     vp->nextVnodeUnique = V_uniquifier(vp);
3293
3294     if (VShouldCheckInUse(mode) && V_inUse(vp) && VolumeWriteable(vp)) {
3295         if (!V_needsSalvaged(vp)) {
3296             V_needsSalvaged(vp) = 1;
3297             VUpdateVolume_r(ec, vp, 0);
3298         }
3299 #if defined(AFS_DEMAND_ATTACH_FS)
3300         if (!VCanScheduleSalvage()) {
3301             Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3302         }
3303         VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_NO_OFFLINE);
3304         vp->nUsers = 0;
3305
3306 #else /* AFS_DEMAND_ATTACH_FS */
3307         Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
3308         *ec = VSALVAGE;
3309 #endif /* AFS_DEMAND_ATTACH_FS */
3310
3311         goto locked_error;
3312     }
3313
3314     if (programType == fileServer && V_destroyMe(vp) == DESTROY_ME) {
3315         /* Only check destroyMe if we are the fileserver, since the
3316          * volserver et al sometimes need to work with volumes with
3317          * destroyMe set. Examples are 'temporary' volumes the
3318          * volserver creates, and when we create a volume (destroyMe
3319          * is set on creation; sometimes a separate volserver
3320          * transaction is created to clear destroyMe).
3321          */
3322
3323 #if defined(AFS_DEMAND_ATTACH_FS)
3324         /* schedule a salvage so the volume goes away on disk */
3325         VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3326         VChangeState_r(vp, VOL_STATE_ERROR);
3327         vp->nUsers = 0;
3328         forcefree = 1;
3329 #endif /* AFS_DEMAND_ATTACH_FS */
3330         Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
3331         *ec = VNOVOL;
3332         goto locked_error;
3333     }
3334
3335     vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
3336 #ifndef BITMAP_LATER
3337     if (programType == fileServer && VolumeWriteable(vp)) {
3338         int i;
3339         for (i = 0; i < nVNODECLASSES; i++) {
3340             VGetBitmap_r(ec, vp, i);
3341             if (*ec) {
3342 #ifdef AFS_DEMAND_ATTACH_FS
3343                 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3344                 vp->nUsers = 0;
3345 #endif /* AFS_DEMAND_ATTACH_FS */
3346                 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
3347                     path);
3348                 goto locked_error;
3349             }
3350         }
3351     }
3352 #endif /* BITMAP_LATER */
3353
3354     if (VInit >= 2 && V_needsCallback(vp)) {
3355         if (V_BreakVolumeCallbacks) {
3356             Log("VAttachVolume: Volume %lu was changed externally; breaking callbacks\n",
3357                 afs_printable_uint32_lu(V_id(vp)));
3358             V_needsCallback(vp) = 0;
3359             VOL_UNLOCK;
3360             (*V_BreakVolumeCallbacks) (V_id(vp));
3361             VOL_LOCK;
3362
3363             VUpdateVolume_r(ec, vp, 0);
3364         }
3365 #ifdef FSSYNC_BUILD_CLIENT
3366         else if (VCanUseFSSYNC()) {
3367             afs_int32 fsync_code;
3368
3369             V_needsCallback(vp) = 0;
3370             VOL_UNLOCK;
3371             fsync_code = FSYNC_VolOp(V_id(vp), NULL, FSYNC_VOL_BREAKCBKS, FSYNC_WHATEVER, NULL);
3372             VOL_LOCK;
3373
3374             if (fsync_code) {
3375                 V_needsCallback(vp) = 1;
3376                 Log("Error trying to tell the fileserver to break callbacks for "
3377                     "changed volume %lu; error code %ld\n",
3378                     afs_printable_uint32_lu(V_id(vp)),
3379                     afs_printable_int32_ld(fsync_code));
3380             } else {
3381                 VUpdateVolume_r(ec, vp, 0);
3382             }
3383         }
3384 #endif /* FSSYNC_BUILD_CLIENT */
3385
3386         if (*ec) {
3387             Log("VAttachVolume: error %d clearing needsCallback on volume "
3388                 "%lu; needs salvage\n", (int)*ec,
3389                 afs_printable_uint32_lu(V_id(vp)));
3390 #ifdef AFS_DEMAND_ATTACH_FS
3391             VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_NO_OFFLINE);
3392             vp->nUsers = 0;
3393 #else /* !AFS_DEMAND_ATTACH_FS */
3394             *ec = VSALVAGE;
3395 #endif /* !AFS_DEMAND_ATTACh_FS */
3396             goto locked_error;
3397         }
3398     }
3399
3400     if (programType == fileServer) {
3401         if (vp->specialStatus)
3402             vp->specialStatus = 0;
3403         if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
3404             V_inUse(vp) = fileServer;
3405             V_offlineMessage(vp)[0] = '\0';
3406         }
3407         if (!V_inUse(vp)) {
3408             *ec = VNOVOL;
3409 #ifdef AFS_DEMAND_ATTACH_FS
3410             /* Put the vol into PREATTACHED state, so if someone tries to
3411              * access it again, we try to attach, see that we're not blessed,
3412              * and give a VNOVOL error again. Putting it into UNATTACHED state
3413              * would result in a VOFFLINE error instead. */
3414             error_state = VOL_STATE_PREATTACHED;
3415 #endif /* AFS_DEMAND_ATTACH_FS */
3416
3417             /* mimic e.g. GetVolume errors */
3418             if (!V_blessed(vp)) {
3419                 Log("Volume %lu offline: not blessed\n", afs_printable_uint32_lu(V_id(vp)));
3420                 FreeVolumeHeader(vp);
3421             } else if (!V_inService(vp)) {
3422                 Log("Volume %lu offline: not in service\n", afs_printable_uint32_lu(V_id(vp)));
3423                 FreeVolumeHeader(vp);
3424             } else {
3425                 Log("Volume %lu offline: needs salvage\n", afs_printable_uint32_lu(V_id(vp)));
3426                 *ec = VSALVAGE;
3427 #ifdef AFS_DEMAND_ATTACH_FS
3428                 error_state = VOL_STATE_ERROR;
3429                 /* see if we can recover */
3430                 VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, 0 /*flags*/);
3431 #endif
3432             }
3433 #ifdef AFS_DEMAND_ATTACH_FS
3434             vp->nUsers = 0;
3435 #endif
3436             goto locked_error;
3437         }
3438     } else {
3439 #ifdef AFS_DEMAND_ATTACH_FS
3440         if ((mode != V_PEEK) && (mode != V_SECRETLY))
3441             V_inUse(vp) = programType;
3442 #endif /* AFS_DEMAND_ATTACH_FS */
3443         V_checkoutMode(vp) = mode;
3444     }
3445
3446     AddVolumeToHashTable(vp, V_id(vp));
3447 #ifdef AFS_DEMAND_ATTACH_FS
3448     if (VCanUnlockAttached() && (V_attachFlags(vp) & VOL_LOCKED)) {
3449         VUnlockVolume(vp);
3450     }
3451     if ((programType != fileServer) ||
3452         (V_inUse(vp) == fileServer)) {
3453         AddVolumeToVByPList_r(vp);
3454         VLRU_Add_r(vp);
3455         VChangeState_r(vp, VOL_STATE_ATTACHED);
3456     } else {
3457         VChangeState_r(vp, VOL_STATE_UNATTACHED);
3458     }
3459 #endif
3460
3461     return vp;
3462
3463 #ifndef AFS_DEMAND_ATTACH_FS
3464 unlocked_error:
3465 #endif
3466
3467     VOL_LOCK;
3468 locked_error:
3469 #ifdef AFS_DEMAND_ATTACH_FS
3470     if (!VIsErrorState(V_attachState(vp))) {
3471         if (VIsErrorState(error_state)) {
3472             Log("attach2: forcing vol %u to error state (state %u flags 0x%x ec %d)\n",
3473                 vp->hashid, V_attachState(vp), V_attachFlags(vp), *ec);
3474         }
3475         VChangeState_r(vp, error_state);
3476     }
3477 #endif /* AFS_DEMAND_ATTACH_FS */
3478
3479     if (read_header) {
3480         VReleaseVolumeHandles_r(vp);
3481     }
3482
3483  error_notbroken:
3484 #ifdef AFS_DEMAND_ATTACH_FS
3485     VCheckSalvage(vp);
3486     if (forcefree) {
3487         FreeVolume(vp);
3488     } else {
3489         VCheckFree(vp);
3490     }
3491 #else /* !AFS_DEMAND_ATTACH_FS */
3492     FreeVolume(vp);
3493 #endif /* !AFS_DEMAND_ATTACH_FS */
3494     return NULL;
3495 }
3496
3497 /* Attach an existing volume.
3498    The volume also normally goes online at this time.
3499    An offline volume must be reattached to make it go online.
3500  */
3501
3502 Volume *
3503 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
3504 {
3505     Volume *retVal;
3506     VOL_LOCK;
3507     retVal = VAttachVolume_r(ec, volumeId, mode);
3508     VOL_UNLOCK;
3509     return retVal;
3510 }
3511
3512 Volume *
3513 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
3514 {
3515     char *part, *name;
3516     VGetVolumePath(ec, volumeId, &part, &name);
3517     if (*ec) {
3518         Volume *vp;
3519         Error error;
3520         vp = VGetVolume_r(&error, volumeId);
3521         if (vp) {
3522             osi_Assert(V_inUse(vp) == 0);
3523             VDetachVolume_r(ec, vp);
3524         }
3525         return NULL;
3526     }
3527     return VAttachVolumeByName_r(ec, part, name, mode);
3528 }
3529
3530 /* Increment a reference count to a volume, sans context swaps.  Requires
3531  * possibly reading the volume header in from the disk, since there's
3532  * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
3533  *
3534  * N.B. This call can fail if we can't read in the header!!  In this case
3535  * we still guarantee we won't context swap, but the ref count won't be
3536  * incremented (otherwise we'd violate the invariant).
3537  */
3538 /* NOTE: with the demand attach fileserver extensions, the global lock
3539  * is dropped within VHold */
3540 #ifdef AFS_DEMAND_ATTACH_FS
3541 static int
3542 VHold_r(Volume * vp)
3543 {
3544     Error error;
3545
3546     VCreateReservation_r(vp);
3547     VWaitExclusiveState_r(vp);
3548
3549     LoadVolumeHeader(&error, vp);
3550     if (error) {
3551         VCancelReservation_r(vp);
3552         return error;
3553     }
3554     vp->nUsers++;
3555     VCancelReservation_r(vp);
3556     return 0;
3557 }
3558 #else /* AFS_DEMAND_ATTACH_FS */
3559 static int
3560 VHold_r(Volume * vp)
3561 {
3562     Error error;
3563
3564     LoadVolumeHeader(&error, vp);
3565     if (error)
3566         return error;
3567     vp->nUsers++;
3568     return 0;
3569 }
3570 #endif /* AFS_DEMAND_ATTACH_FS */
3571
3572 /**** volume timeout-related stuff ****/
3573
3574 #ifdef AFS_PTHREAD_ENV
3575
3576 static struct timespec *shutdown_timeout;
3577 static pthread_once_t shutdown_timeout_once = PTHREAD_ONCE_INIT;
3578
3579 static_inline int
3580 VTimedOut(const struct timespec *ts)
3581 {
3582     struct timeval tv;
3583     int code;
3584
3585     if (ts->tv_sec == 0) {
3586         /* short-circuit; this will have always timed out */
3587         return 1;
3588     }
3589
3590     code = gettimeofday(&tv, NULL);
3591     if (code) {
3592         Log("Error %d from gettimeofday, assuming we have not timed out\n", errno);
3593         /* assume no timeout; failure mode is we just wait longer than normal
3594          * instead of returning errors when we shouldn't */
3595         return 0;
3596     }
3597
3598     if (tv.tv_sec < ts->tv_sec ||
3599         (tv.tv_sec == ts->tv_sec && tv.tv_usec*1000 < ts->tv_nsec)) {
3600
3601         return 0;
3602     }
3603
3604     return 1;
3605 }
3606
3607 /**
3608  * Calculate an absolute timeout.
3609  *
3610  * @param[out] ts  A timeout that is "timeout" seconds from now, if we return
3611  *                 NULL, the memory is not touched
3612  * @param[in]  timeout  How long the timeout should be from now
3613  *
3614  * @return timeout to use
3615  *  @retval NULL      no timeout; wait forever
3616  *  @retval non-NULL  the given value for "ts"
3617  *
3618  * @internal
3619  */
3620 static struct timespec *
3621 VCalcTimeout(struct timespec *ts, afs_int32 timeout)
3622 {
3623     struct timeval now;
3624     int code;
3625
3626     if (timeout < 0) {
3627         return NULL;
3628     }
3629
3630     if (timeout == 0) {
3631         ts->tv_sec = ts->tv_nsec = 0;
3632         return ts;
3633     }
3634
3635     code = gettimeofday(&now, NULL);
3636     if (code) {
3637         Log("Error %d from gettimeofday, falling back to 'forever' timeout\n", errno);
3638         return NULL;
3639     }
3640
3641     ts->tv_sec = now.tv_sec + timeout;
3642     ts->tv_nsec = now.tv_usec * 1000;
3643
3644     return ts;
3645 }
3646
3647 /**
3648  * Initialize the shutdown_timeout global.
3649  */
3650 static void
3651 VShutdownTimeoutInit(void)
3652 {
3653     struct timespec *ts;
3654
3655     ts = malloc(sizeof(*ts));
3656
3657     shutdown_timeout = VCalcTimeout(ts, vol_opts.offline_shutdown_timeout);
3658
3659     if (!shutdown_timeout) {
3660         free(ts);
3661     }
3662 }
3663
3664 /**
3665  * Figure out the timeout that should be used for waiting for offline volumes.
3666  *
3667  * @param[out] ats  Storage space for a local timeout value if needed
3668  *
3669  * @return The timeout value that should be used
3670  *   @retval NULL      No timeout; wait forever for offlining volumes
3671  *   @retval non-NULL  A pointer to the absolute time that should be used as
3672  *                     the deadline for waiting for offlining volumes.
3673  *
3674  * @note If we return non-NULL, the pointer we return may or may not be the
3675  *       same as "ats"
3676  */
3677 static const struct timespec *
3678 VOfflineTimeout(struct timespec *ats)
3679 {
3680     if (vol_shutting_down) {
3681         osi_Assert(pthread_once(&shutdown_timeout_once, VShutdownTimeoutInit) == 0);
3682         return shutdown_timeout;
3683     } else {
3684         return VCalcTimeout(ats, vol_opts.offline_timeout);
3685     }
3686 }
3687
3688 #else /* AFS_PTHREAD_ENV */
3689
3690 /* Waiting a certain amount of time for offlining volumes is not supported
3691  * for LWP due to a lack of primitives. So, we never time out */
3692 # define VTimedOut(x) (0)
3693 # define VOfflineTimeout(x) (NULL)
3694
3695 #endif /* !AFS_PTHREAD_ENV */
3696
3697 #if 0
3698 static int
3699 VHold(Volume * vp)
3700 {
3701     int retVal;
3702     VOL_LOCK;
3703     retVal = VHold_r(vp);
3704     VOL_UNLOCK;
3705     return retVal;
3706 }
3707 #endif
3708
3709 static afs_int32
3710 VIsGoingOffline_r(struct Volume *vp)
3711 {
3712     afs_int32 code = 0;
3713
3714     if (vp->goingOffline) {
3715         if (vp->specialStatus) {
3716             code = vp->specialStatus;
3717         } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3718             code = VNOVOL;
3719         } else {
3720             code = VOFFLINE;
3721         }
3722     }
3723
3724     return code;
3725 }
3726
3727 /**
3728  * Tell the caller if a volume is waiting to go offline.
3729  *
3730  * @param[in] vp  The volume we want to know about
3731  *
3732  * @return volume status
3733  *   @retval 0 volume is not waiting to go offline, go ahead and use it
3734  *   @retval nonzero volume is waiting to offline, and give the returned code
3735  *           as an error to anyone accessing the volume
3736  *
3737  * @pre VOL_LOCK is NOT held
3738  * @pre caller holds a heavyweight reference on vp
3739  */
3740 afs_int32
3741 VIsGoingOffline(struct Volume *vp)
3742 {
3743     afs_int32 code;
3744
3745     VOL_LOCK;
3746     code = VIsGoingOffline_r(vp);
3747     VOL_UNLOCK;
3748
3749     return code;
3750 }
3751
3752 /**
3753  * Register an RX call with a volume.
3754  *
3755  * @param[inout] ec        Error code; if unset when passed in, may be set if
3756  *                         the volume starts going offline
3757  * @param[out]   client_ec @see GetVolume
3758  * @param[in] vp   Volume struct
3759  * @param[in] cbv  VCallByVol struct containing the RX call to register
3760  *
3761  * @pre VOL_LOCK held
3762  * @pre caller holds heavy ref on vp
3763  *
3764  * @internal
3765  */
3766 static void
3767 VRegisterCall_r(Error *ec, Error *client_ec, Volume *vp, struct VCallByVol *cbv)
3768 {
3769     if (vp && cbv) {
3770 #ifdef AFS_DEMAND_ATTACH_FS
3771         if (!*ec) {
3772             /* just in case the volume started going offline after we got the
3773              * reference to it... otherwise, if the volume started going
3774              * offline right at the end of GetVolume(), we might race with the
3775              * RX call scanner, and return success and add our cbv to the
3776              * rx_call_list _after_ the scanner has scanned the list. */
3777             *ec = VIsGoingOffline_r(vp);
3778             if (client_ec) {
3779                 *client_ec = *ec;
3780             }
3781         }
3782
3783         while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {
3784             VWaitStateChange_r(vp);
3785         }
3786 #endif /* AFS_DEMAND_ATTACH_FS */
3787
3788         queue_Prepend(&vp->rx_call_list, cbv);
3789     }
3790 }
3791
3792 /**
3793  * Deregister an RX call with a volume.
3794  *
3795  * @param[in] vp   Volume struct
3796  * @param[in] cbv  VCallByVol struct containing the RX call to deregister
3797  *
3798  * @pre VOL_LOCK held
3799  * @pre caller holds heavy ref on vp
3800  *
3801  * @internal
3802  */
3803 static void
3804 VDeregisterCall_r(Volume *vp, struct VCallByVol *cbv)
3805 {
3806     if (cbv && queue_IsOnQueue(cbv)) {
3807 #ifdef AFS_DEMAND_ATTACH_FS
3808         while (V_attachState(vp) == VOL_STATE_SCANNING_RXCALLS) {