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