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