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