94417ef59b96e4dedbb00a4126fd2785d0810a6b
[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 #ifdef SALVSYNC_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         VCheckFree(vp);
2569         return NULL;
2570     } else if (*ec) {
2571         /* volume operation in progress */
2572         VOL_LOCK;
2573         VCheckFree(vp);
2574         return NULL;
2575     }
2576 #else /* AFS_DEMAND_ATTACH_FS */
2577     if (*ec) {
2578         Log("VAttachVolume: Error attaching volume %s; volume needs salvage; error=%u\n", path, *ec);
2579         VOL_LOCK;
2580         FreeVolume(vp);
2581         return NULL;
2582     }
2583 #endif /* AFS_DEMAND_ATTACH_FS */
2584
2585     if (V_needsSalvaged(vp)) {
2586         if (vp->specialStatus)
2587             vp->specialStatus = 0;
2588         VOL_LOCK;
2589 #if defined(AFS_DEMAND_ATTACH_FS)
2590         if (!VCanScheduleSalvage()) {
2591             Log("VAttachVolume: volume salvage flag is ON for %s; volume needs salvage\n", path);
2592         }
2593         VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
2594         vp->nUsers = 0;
2595
2596         VCheckFree(vp);
2597 #else /* AFS_DEMAND_ATTACH_FS */
2598         FreeVolume(vp);
2599         *ec = VSALVAGE;
2600 #endif /* AFS_DEMAND_ATTACH_FS */
2601         return NULL;
2602     }
2603
2604     VOL_LOCK;
2605     if (VShouldCheckInUse(mode)) {
2606 #ifndef FAST_RESTART
2607         if (V_inUse(vp) && VolumeWriteable(vp)) {
2608             if (!V_needsSalvaged(vp)) {
2609                 V_needsSalvaged(vp) = 1;
2610                 VUpdateVolume_r(ec, vp, 0);
2611             }
2612 #if defined(AFS_DEMAND_ATTACH_FS)
2613             if (!VCanScheduleSalvage()) {
2614                 Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
2615             }
2616             VRequestSalvage_r(ec, vp, SALVSYNC_NEEDED, VOL_SALVAGE_INVALIDATE_HEADER);
2617             vp->nUsers = 0;
2618
2619             VCheckFree(vp);
2620 #else /* AFS_DEMAND_ATTACH_FS */
2621             Log("VAttachVolume: volume %s needs to be salvaged; not attached.\n", path);
2622             FreeVolume(vp);
2623             *ec = VSALVAGE;
2624 #endif /* AFS_DEMAND_ATTACH_FS */
2625             return NULL;
2626         }
2627 #endif /* FAST_RESTART */
2628
2629         if (programType == fileServer && V_destroyMe(vp) == DESTROY_ME) {
2630             /* Only check destroyMe if we are the fileserver, since the
2631              * volserver et al sometimes need to work with volumes with
2632              * destroyMe set. Examples are 'temporary' volumes the
2633              * volserver creates, and when we create a volume (destroyMe
2634              * is set on creation; sometimes a separate volserver
2635              * transaction is created to clear destroyMe).
2636              */
2637
2638 #if defined(AFS_DEMAND_ATTACH_FS)
2639             /* schedule a salvage so the volume goes away on disk */
2640             VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2641             VChangeState_r(vp, VOL_STATE_ERROR);
2642             vp->nUsers = 0;
2643 #endif /* AFS_DEMAND_ATTACH_FS */
2644             FreeVolume(vp);
2645             Log("VAttachVolume: volume %s is junk; it should be destroyed at next salvage\n", path);
2646             *ec = VNOVOL;
2647             return NULL;
2648         }
2649     }
2650
2651     vp->nextVnodeUnique = V_uniquifier(vp);
2652     vp->vnodeIndex[vSmall].bitmap = vp->vnodeIndex[vLarge].bitmap = NULL;
2653 #ifndef BITMAP_LATER
2654     if (programType == fileServer && VolumeWriteable(vp)) {
2655         int i;
2656         for (i = 0; i < nVNODECLASSES; i++) {
2657             VGetBitmap_r(ec, vp, i);
2658             if (*ec) {
2659 #ifdef AFS_DEMAND_ATTACH_FS
2660                 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
2661                 vp->nUsers = 0;
2662                 VCheckFree(vp);
2663 #else /* AFS_DEMAND_ATTACH_FS */
2664                 FreeVolume(vp);
2665 #endif /* AFS_DEMAND_ATTACH_FS */
2666                 Log("VAttachVolume: error getting bitmap for volume (%s)\n",
2667                     path);
2668                 return NULL;
2669             }
2670         }
2671     }
2672 #endif /* BITMAP_LATER */
2673
2674     if (programType == fileServer) {
2675         if (vp->specialStatus)
2676             vp->specialStatus = 0;
2677         if (V_blessed(vp) && V_inService(vp) && !V_needsSalvaged(vp)) {
2678             V_inUse(vp) = fileServer;
2679             V_offlineMessage(vp)[0] = '\0';
2680         }
2681     } else {
2682         if ((mode != V_PEEK) && (mode != V_SECRETLY))
2683             V_inUse(vp) = programType;
2684         V_checkoutMode(vp) = mode;
2685     }
2686
2687     AddVolumeToHashTable(vp, V_id(vp));
2688 #ifdef AFS_DEMAND_ATTACH_FS
2689     if ((programType != fileServer) ||
2690         (V_inUse(vp) == fileServer)) {
2691         AddVolumeToVByPList_r(vp);
2692         VLRU_Add_r(vp);
2693         VChangeState_r(vp, VOL_STATE_ATTACHED);
2694     } else {
2695         VChangeState_r(vp, VOL_STATE_UNATTACHED);
2696     }
2697 #endif
2698     return vp;
2699 }
2700
2701 /* Attach an existing volume.
2702    The volume also normally goes online at this time.
2703    An offline volume must be reattached to make it go online.
2704  */
2705
2706 Volume *
2707 VAttachVolume(Error * ec, VolumeId volumeId, int mode)
2708 {
2709     Volume *retVal;
2710     VOL_LOCK;
2711     retVal = VAttachVolume_r(ec, volumeId, mode);
2712     VOL_UNLOCK;
2713     return retVal;
2714 }
2715
2716 Volume *
2717 VAttachVolume_r(Error * ec, VolumeId volumeId, int mode)
2718 {
2719     char *part, *name;
2720     VGetVolumePath(ec, volumeId, &part, &name);
2721     if (*ec) {
2722         register Volume *vp;
2723         Error error;
2724         vp = VGetVolume_r(&error, volumeId);
2725         if (vp) {
2726             assert(V_inUse(vp) == 0);
2727             VDetachVolume_r(ec, vp);
2728         }
2729         return NULL;
2730     }
2731     return VAttachVolumeByName_r(ec, part, name, mode);
2732 }
2733
2734 /* Increment a reference count to a volume, sans context swaps.  Requires
2735  * possibly reading the volume header in from the disk, since there's
2736  * an invariant in the volume package that nUsers>0 ==> vp->header is valid.
2737  *
2738  * N.B. This call can fail if we can't read in the header!!  In this case
2739  * we still guarantee we won't context swap, but the ref count won't be
2740  * incremented (otherwise we'd violate the invariant).
2741  */
2742 /* NOTE: with the demand attach fileserver extensions, the global lock
2743  * is dropped within VHold */
2744 #ifdef AFS_DEMAND_ATTACH_FS
2745 static int
2746 VHold_r(register Volume * vp)
2747 {
2748     Error error;
2749
2750     VCreateReservation_r(vp);
2751     VWaitExclusiveState_r(vp);
2752
2753     LoadVolumeHeader(&error, vp);
2754     if (error) {
2755         VCancelReservation_r(vp);
2756         return error;
2757     }
2758     vp->nUsers++;
2759     VCancelReservation_r(vp);
2760     return 0;
2761 }
2762 #else /* AFS_DEMAND_ATTACH_FS */
2763 static int
2764 VHold_r(register Volume * vp)
2765 {
2766     Error error;
2767
2768     LoadVolumeHeader(&error, vp);
2769     if (error)
2770         return error;
2771     vp->nUsers++;
2772     return 0;
2773 }
2774 #endif /* AFS_DEMAND_ATTACH_FS */
2775
2776 #if 0
2777 static int
2778 VHold(register Volume * vp)
2779 {
2780     int retVal;
2781     VOL_LOCK;
2782     retVal = VHold_r(vp);
2783     VOL_UNLOCK;
2784     return retVal;
2785 }
2786 #endif
2787
2788
2789 /***************************************************/
2790 /* get and put volume routines                     */
2791 /***************************************************/
2792
2793 /**
2794  * put back a heavyweight reference to a volume object.
2795  *
2796  * @param[in] vp  volume object pointer
2797  *
2798  * @pre VOL_LOCK held
2799  *
2800  * @post heavyweight volume reference put back.
2801  *       depending on state, volume may have been taken offline,
2802  *       detached, salvaged, freed, etc.
2803  *
2804  * @internal volume package internal use only
2805  */
2806 void
2807 VPutVolume_r(register Volume * vp)
2808 {
2809     assert(--vp->nUsers >= 0);
2810     if (vp->nUsers == 0) {
2811         VCheckOffline(vp);
2812         ReleaseVolumeHeader(vp->header);
2813 #ifdef AFS_DEMAND_ATTACH_FS
2814         if (!VCheckDetach(vp)) {
2815             VCheckSalvage(vp);
2816             VCheckFree(vp);
2817         }
2818 #else /* AFS_DEMAND_ATTACH_FS */
2819         VCheckDetach(vp);
2820 #endif /* AFS_DEMAND_ATTACH_FS */
2821     }
2822 }
2823
2824 void
2825 VPutVolume(register Volume * vp)
2826 {
2827     VOL_LOCK;
2828     VPutVolume_r(vp);
2829     VOL_UNLOCK;
2830 }
2831
2832
2833 /* Get a pointer to an attached volume.  The pointer is returned regardless
2834    of whether or not the volume is in service or on/off line.  An error
2835    code, however, is returned with an indication of the volume's status */
2836 Volume *
2837 VGetVolume(Error * ec, Error * client_ec, VolId volumeId)
2838 {
2839     Volume *retVal;
2840     VOL_LOCK;
2841     retVal = GetVolume(ec, client_ec, volumeId, NULL, 0);
2842     VOL_UNLOCK;
2843     return retVal;
2844 }
2845
2846 Volume *
2847 VGetVolume_r(Error * ec, VolId volumeId)
2848 {
2849     return GetVolume(ec, NULL, volumeId, NULL, 0);
2850 }
2851
2852 /* try to get a volume we've previously looked up */
2853 /* for demand attach fs, caller MUST NOT hold a ref count on vp */
2854 Volume * 
2855 VGetVolumeByVp_r(Error * ec, Volume * vp)
2856 {
2857     return GetVolume(ec, NULL, vp->hashid, vp, 0);
2858 }
2859
2860 /* private interface for getting a volume handle
2861  * volumeId must be provided.
2862  * hint is an optional parameter to speed up hash lookups
2863  * flags is not used at this time
2864  */
2865 /* for demand attach fs, caller MUST NOT hold a ref count on hint */
2866 static Volume *
2867 GetVolume(Error * ec, Error * client_ec, VolId volumeId, Volume * hint, int flags)
2868 {
2869     Volume *vp = hint;
2870     /* pull this profiling/debugging code out of regular builds */
2871 #ifdef notdef
2872 #define VGET_CTR_INC(x) x++
2873     unsigned short V0 = 0, V1 = 0, V2 = 0, V3 = 0, V5 = 0, V6 =
2874         0, V7 = 0, V8 = 0, V9 = 0;
2875     unsigned short V10 = 0, V11 = 0, V12 = 0, V13 = 0, V14 = 0, V15 = 0;
2876 #else
2877 #define VGET_CTR_INC(x)
2878 #endif
2879 #ifdef AFS_DEMAND_ATTACH_FS
2880     Volume *avp, * rvp = hint;
2881 #endif
2882
2883     /* 
2884      * if VInit is zero, the volume package dynamic
2885      * data structures have not been initialized yet,
2886      * and we must immediately return an error
2887      */
2888     if (VInit == 0) {
2889         vp = NULL;
2890         *ec = VOFFLINE;
2891         if (client_ec) {
2892             *client_ec = VOFFLINE;
2893         }
2894         goto not_inited;
2895     }
2896
2897 #ifdef AFS_DEMAND_ATTACH_FS
2898     if (rvp) {
2899         VCreateReservation_r(rvp);
2900     }
2901 #endif /* AFS_DEMAND_ATTACH_FS */
2902
2903     for (;;) {
2904         *ec = 0;
2905         if (client_ec)
2906             *client_ec = 0;
2907         VGET_CTR_INC(V0);
2908
2909         vp = VLookupVolume_r(ec, volumeId, vp);
2910         if (*ec) {
2911             vp = NULL;
2912             break;
2913         }
2914
2915 #ifdef AFS_DEMAND_ATTACH_FS
2916         if (rvp && (rvp != vp)) {
2917             /* break reservation on old vp */
2918             VCancelReservation_r(rvp);
2919             rvp = NULL;
2920         }
2921 #endif /* AFS_DEMAND_ATTACH_FS */
2922
2923         if (!vp) {
2924             VGET_CTR_INC(V1);
2925             if (VInit < 2) {
2926                 VGET_CTR_INC(V2);
2927                 /* Until we have reached an initialization level of 2
2928                  * we don't know whether this volume exists or not.
2929                  * We can't sleep and retry later because before a volume
2930                  * is attached, the caller tries to get it first.  Just
2931                  * return VOFFLINE and the caller can choose whether to
2932                  * retry the command or not. */
2933                 *ec = VOFFLINE;
2934                 break;
2935             }
2936
2937             *ec = VNOVOL;
2938             break;
2939         }
2940
2941         VGET_CTR_INC(V3);
2942         IncUInt64(&VStats.hdr_gets);
2943         
2944 #ifdef AFS_DEMAND_ATTACH_FS
2945         /* block if someone else is performing an exclusive op on this volume */
2946         if (rvp != vp) {
2947             rvp = vp;
2948             VCreateReservation_r(rvp);
2949         }
2950         VWaitExclusiveState_r(vp);
2951
2952         /* short circuit with VNOVOL in the following circumstances:
2953          *
2954          *   - VOL_STATE_ERROR
2955          *   - VOL_STATE_SHUTTING_DOWN
2956          */
2957         if ((V_attachState(vp) == VOL_STATE_ERROR) ||
2958             (V_attachState(vp) == VOL_STATE_SHUTTING_DOWN) ||
2959             (V_attachState(vp) == VOL_STATE_GOING_OFFLINE)) {
2960             *ec = VNOVOL;
2961             vp = NULL;
2962             break;
2963         }
2964
2965         /*
2966          * short circuit with VOFFLINE in the following circumstances:
2967          *
2968          *   - VOL_STATE_UNATTACHED
2969          */
2970        if (V_attachState(vp) == VOL_STATE_UNATTACHED) {
2971            if (vp->specialStatus) {
2972                *ec = vp->specialStatus;
2973            } else {
2974                *ec = VOFFLINE;
2975            }
2976            vp = NULL;
2977            break;
2978        }
2979
2980         /* allowable states:
2981          *   - PREATTACHED
2982          *   - ATTACHED
2983          *   - SALVAGING
2984          */
2985
2986         if (vp->salvage.requested) {
2987             VUpdateSalvagePriority_r(vp);
2988         }
2989
2990         if (V_attachState(vp) == VOL_STATE_PREATTACHED) {
2991             avp = VAttachVolumeByVp_r(ec, vp, 0);
2992             if (avp) {
2993                 if (vp != avp) {
2994                     /* VAttachVolumeByVp_r can return a pointer
2995                      * != the vp passed to it under certain
2996                      * conditions; make sure we don't leak
2997                      * reservations if that happens */
2998                     vp = avp;
2999                     VCancelReservation_r(rvp);
3000                     rvp = avp;
3001                     VCreateReservation_r(rvp);
3002                 }
3003                 VPutVolume_r(avp);
3004             }
3005             if (*ec) {
3006                 int endloop = 0;
3007                 switch (*ec) {
3008                 case VSALVAGING:
3009                     break;
3010                 case VOFFLINE:
3011                     if (!vp->pending_vol_op) {
3012                         endloop = 1;
3013                     }
3014                     break;
3015                 default:
3016                     *ec = VNOVOL;
3017                     endloop = 1;
3018                 }
3019                 if (endloop) {
3020                     vp = NULL;
3021                     break;
3022                 }
3023             }
3024         }
3025
3026         if ((V_attachState(vp) == VOL_STATE_SALVAGING) ||
3027             (*ec == VSALVAGING)) {
3028             if (client_ec) {
3029                 /* see CheckVnode() in afsfileprocs.c for an explanation
3030                  * of this error code logic */
3031                 afs_uint32 now = FT_ApproxTime();
3032                 if ((vp->stats.last_salvage + (10 * 60)) >= now) {
3033                     *client_ec = VBUSY;
3034                 } else {
3035                     *client_ec = VRESTARTING;
3036                 }
3037             }
3038             *ec = VSALVAGING;
3039             vp = NULL;
3040             break;
3041         }
3042 #endif
3043
3044         LoadVolumeHeader(ec, vp);
3045         if (*ec) {
3046             VGET_CTR_INC(V6);
3047             /* Only log the error if it was a totally unexpected error.  Simply
3048              * a missing inode is likely to be caused by the volume being deleted */
3049             if (errno != ENXIO || LogLevel)
3050                 Log("Volume %u: couldn't reread volume header\n",
3051                     vp->hashid);
3052 #ifdef AFS_DEMAND_ATTACH_FS
3053             if (VCanScheduleSalvage()) {
3054                 VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3055             } else {
3056                 FreeVolume(vp);
3057                 vp = NULL;
3058             }
3059 #else /* AFS_DEMAND_ATTACH_FS */
3060             FreeVolume(vp);
3061             vp = NULL;
3062 #endif /* AFS_DEMAND_ATTACH_FS */
3063             break;
3064         }
3065
3066 #ifdef AFS_DEMAND_ATTACH_FS
3067         /*
3068          * this test MUST happen after the volume header is loaded
3069          */
3070         
3071          /* only valid before/during demand attachment */
3072          assert(!vp->pending_vol_op || vp->pending_vol_op->vol_op_state != FSSYNC_VolOpRunningUnknown);
3073         
3074          /* deny getvolume due to running mutually exclusive vol op */
3075          if (vp->pending_vol_op && vp->pending_vol_op->vol_op_state==FSSYNC_VolOpRunningOffline) {
3076            /* 
3077             * volume cannot remain online during this volume operation.
3078             * notify client. 
3079             */
3080            if (vp->specialStatus) {
3081                /*
3082                 * special status codes outrank normal VOFFLINE code
3083                 */
3084                *ec = vp->specialStatus;
3085                if (client_ec) {
3086                    *client_ec = vp->specialStatus;
3087                }
3088            } else {
3089                if (client_ec) {
3090                    /* see CheckVnode() in afsfileprocs.c for an explanation
3091                     * of this error code logic */
3092                    afs_uint32 now = FT_ApproxTime();
3093                    if ((vp->stats.last_vol_op + (10 * 60)) >= now) {
3094                        *client_ec = VBUSY;
3095                    } else {
3096                        *client_ec = VRESTARTING;
3097                    }
3098                }
3099                *ec = VOFFLINE;
3100            }
3101            VChangeState_r(vp, VOL_STATE_UNATTACHED);
3102            FreeVolumeHeader(vp);
3103            vp = NULL;
3104            break;
3105         }
3106 #endif /* AFS_DEMAND_ATTACH_FS */
3107         
3108         VGET_CTR_INC(V7);
3109         if (vp->shuttingDown) {
3110             VGET_CTR_INC(V8);
3111             *ec = VNOVOL;
3112             vp = NULL;
3113             break;
3114         }
3115
3116         if (programType == fileServer) {
3117             VGET_CTR_INC(V9);
3118             if (vp->goingOffline) {
3119                 VGET_CTR_INC(V10);
3120 #ifdef AFS_DEMAND_ATTACH_FS
3121                 /* wait for the volume to go offline */
3122                 if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
3123                     VWaitStateChange_r(vp);
3124                 }
3125 #elif defined(AFS_PTHREAD_ENV)
3126                 VOL_CV_WAIT(&vol_put_volume_cond);
3127 #else /* AFS_PTHREAD_ENV */
3128                 LWP_WaitProcess(VPutVolume);
3129 #endif /* AFS_PTHREAD_ENV */
3130                 continue;
3131             }
3132             if (vp->specialStatus) {
3133                 VGET_CTR_INC(V11);
3134                 *ec = vp->specialStatus;
3135             } else if (V_inService(vp) == 0 || V_blessed(vp) == 0) {
3136                 VGET_CTR_INC(V12);
3137                 *ec = VNOVOL;
3138             } else if (V_inUse(vp) == 0) {
3139                 VGET_CTR_INC(V13);
3140                 *ec = VOFFLINE;
3141             } else {
3142                 VGET_CTR_INC(V14);
3143             }
3144         }
3145         break;
3146     }
3147     VGET_CTR_INC(V15);
3148
3149 #ifdef AFS_DEMAND_ATTACH_FS
3150     /* if no error, bump nUsers */
3151     if (vp) {
3152         vp->nUsers++;
3153         VLRU_UpdateAccess_r(vp);
3154     }
3155     if (rvp) {
3156         VCancelReservation_r(rvp);
3157         rvp = NULL;
3158     }
3159     if (client_ec && !*client_ec) {
3160         *client_ec = *ec;
3161     }
3162 #else /* AFS_DEMAND_ATTACH_FS */
3163     /* if no error, bump nUsers */
3164     if (vp) {
3165         vp->nUsers++;
3166     }
3167     if (client_ec) {
3168         *client_ec = *ec;
3169     }
3170 #endif /* AFS_DEMAND_ATTACH_FS */
3171
3172  not_inited:
3173     assert(vp || *ec);
3174     return vp;
3175 }
3176
3177
3178 /***************************************************/
3179 /* Volume offline/detach routines                  */
3180 /***************************************************/
3181
3182 /* caller MUST hold a heavyweight ref on vp */
3183 #ifdef AFS_DEMAND_ATTACH_FS
3184 void
3185 VTakeOffline_r(register Volume * vp)
3186 {
3187     Error error;
3188
3189     assert(vp->nUsers > 0);
3190     assert(programType == fileServer);
3191
3192     VCreateReservation_r(vp);
3193     VWaitExclusiveState_r(vp);
3194
3195     vp->goingOffline = 1;
3196     V_needsSalvaged(vp) = 1;
3197
3198     VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, 0);
3199     VCancelReservation_r(vp);
3200 }
3201 #else /* AFS_DEMAND_ATTACH_FS */
3202 void
3203 VTakeOffline_r(register Volume * vp)
3204 {
3205     assert(vp->nUsers > 0);
3206     assert(programType == fileServer);
3207
3208     vp->goingOffline = 1;
3209     V_needsSalvaged(vp) = 1;
3210 }
3211 #endif /* AFS_DEMAND_ATTACH_FS */
3212
3213 void
3214 VTakeOffline(register Volume * vp)
3215 {
3216     VOL_LOCK;
3217     VTakeOffline_r(vp);
3218     VOL_UNLOCK;
3219 }
3220
3221 /**
3222  * force a volume offline.
3223  *
3224  * @param[in] vp     volume object pointer
3225  * @param[in] flags  flags (see note below)
3226  *
3227  * @note the flag VOL_FORCEOFF_NOUPDATE is a recursion control flag
3228  *       used when VUpdateVolume_r needs to call VForceOffline_r
3229  *       (which in turn would normally call VUpdateVolume_r)
3230  *
3231  * @see VUpdateVolume_r
3232  *
3233  * @pre VOL_LOCK must be held.
3234  *      for DAFS, caller must hold ref.
3235  *
3236  * @note for DAFS, it _is safe_ to call this function from an
3237  *       exclusive state
3238  *
3239  * @post needsSalvaged flag is set.
3240  *       for DAFS, salvage is requested.
3241  *       no further references to the volume through the volume 
3242  *       package will be honored.
3243  *       all file descriptor and vnode caches are invalidated.
3244  *
3245  * @warning this is a heavy-handed interface.  it results in
3246  *          a volume going offline regardless of the current 
3247  *          reference count state.
3248  *
3249  * @internal  volume package internal use only
3250  */
3251 void
3252 VForceOffline_r(Volume * vp, int flags)
3253 {
3254     Error error;
3255     if (!V_inUse(vp)) {
3256 #ifdef AFS_DEMAND_ATTACH_FS
3257         VChangeState_r(vp, VOL_STATE_ERROR);
3258 #endif
3259         return;
3260     }
3261
3262     strcpy(V_offlineMessage(vp),
3263            "Forced offline due to internal error: volume needs to be salvaged");
3264     Log("Volume %u forced offline:  it needs salvaging!\n", V_id(vp));
3265
3266     V_inUse(vp) = 0;
3267     vp->goingOffline = 0;
3268     V_needsSalvaged(vp) = 1;
3269     if (!(flags & VOL_FORCEOFF_NOUPDATE)) {
3270         VUpdateVolume_r(&error, vp, VOL_UPDATE_NOFORCEOFF);
3271     }
3272
3273 #ifdef AFS_DEMAND_ATTACH_FS
3274     VRequestSalvage_r(&error, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
3275 #endif /* AFS_DEMAND_ATTACH_FS */
3276
3277 #ifdef AFS_PTHREAD_ENV
3278     assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3279 #else /* AFS_PTHREAD_ENV */
3280     LWP_NoYieldSignal(VPutVolume);
3281 #endif /* AFS_PTHREAD_ENV */
3282
3283     VReleaseVolumeHandles_r(vp);
3284 }
3285
3286 /**
3287  * force a volume offline.
3288  *
3289  * @param[in] vp  volume object pointer
3290  *
3291  * @see VForceOffline_r
3292  */
3293 void
3294 VForceOffline(Volume * vp)
3295 {
3296     VOL_LOCK;
3297     VForceOffline_r(vp, 0);
3298     VOL_UNLOCK;
3299 }
3300
3301 /* The opposite of VAttachVolume.  The volume header is written to disk, with
3302    the inUse bit turned off.  A copy of the header is maintained in memory,
3303    however (which is why this is VOffline, not VDetach).
3304  */
3305 void
3306 VOffline_r(Volume * vp, char *message)
3307 {
3308 #ifndef AFS_DEMAND_ATTACH_FS
3309     Error error;
3310     VolumeId vid = V_id(vp);
3311 #endif
3312
3313     assert(programType != volumeUtility && programType != volumeServer);
3314     if (!V_inUse(vp)) {
3315         VPutVolume_r(vp);
3316         return;
3317     }
3318     if (V_offlineMessage(vp)[0] == '\0')
3319         strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
3320     V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
3321
3322     vp->goingOffline = 1;
3323 #ifdef AFS_DEMAND_ATTACH_FS
3324     VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
3325     VCreateReservation_r(vp);
3326     VPutVolume_r(vp);
3327
3328     /* wait for the volume to go offline */
3329     if (V_attachState(vp) == VOL_STATE_GOING_OFFLINE) {
3330         VWaitStateChange_r(vp);
3331     }
3332     VCancelReservation_r(vp);
3333 #else /* AFS_DEMAND_ATTACH_FS */
3334     VPutVolume_r(vp);
3335     vp = VGetVolume_r(&error, vid);     /* Wait for it to go offline */
3336     if (vp)                     /* In case it was reattached... */
3337         VPutVolume_r(vp);
3338 #endif /* AFS_DEMAND_ATTACH_FS */
3339 }
3340
3341 #ifdef AFS_DEMAND_ATTACH_FS
3342 /**
3343  * Take a volume offline in order to perform a volume operation.
3344  *
3345  * @param[inout] ec       address in which to store error code
3346  * @param[in]    vp       volume object pointer
3347  * @param[in]    message  volume offline status message
3348  *
3349  * @pre
3350  *    - VOL_LOCK is held
3351  *    - caller MUST hold a heavyweight ref on vp
3352  *
3353  * @post
3354  *    - volume is taken offline
3355  *    - if possible, volume operation is promoted to running state
3356  *    - on failure, *ec is set to nonzero
3357  *
3358  * @note Although this function does not return any value, it may
3359  *       still fail to promote our pending volume operation to
3360  *       a running state.  Any caller MUST check the value of *ec,
3361  *       and MUST NOT blindly assume success.
3362  *
3363  * @warning if the caller does not hold a lightweight ref on vp,
3364  *          then it MUST NOT reference vp after this function
3365  *          returns to the caller.
3366  *
3367  * @internal volume package internal use only
3368  */
3369 void
3370 VOfflineForVolOp_r(Error *ec, Volume *vp, char *message)
3371 {
3372     assert(vp->pending_vol_op);
3373     if (!V_inUse(vp)) {
3374         VPutVolume_r(vp);
3375         *ec = 1;
3376         return;
3377     }
3378     if (V_offlineMessage(vp)[0] == '\0')
3379         strncpy(V_offlineMessage(vp), message, sizeof(V_offlineMessage(vp)));
3380     V_offlineMessage(vp)[sizeof(V_offlineMessage(vp)) - 1] = '\0';
3381
3382     vp->goingOffline = 1;
3383     VChangeState_r(vp, VOL_STATE_GOING_OFFLINE);
3384     VCreateReservation_r(vp);
3385     VPutVolume_r(vp);
3386
3387     /* Wait for the volume to go offline */
3388     while (!VIsOfflineState(V_attachState(vp))) {
3389         /* do not give corrupted volumes to the volserver */
3390         if (vp->salvage.requested && vp->pending_vol_op->com.programType != salvageServer) {
3391            *ec = 1; 
3392            goto error;
3393         }
3394         VWaitStateChange_r(vp);
3395     }
3396     *ec = 0; 
3397  error:
3398     VCancelReservation_r(vp);
3399 }
3400 #endif /* AFS_DEMAND_ATTACH_FS */
3401
3402 void
3403 VOffline(Volume * vp, char *message)
3404 {
3405     VOL_LOCK;
3406     VOffline_r(vp, message);
3407     VOL_UNLOCK;
3408 }
3409
3410 /* This gets used for the most part by utility routines that don't want
3411  * to keep all the volume headers around.  Generally, the file server won't
3412  * call this routine, because then the offline message in the volume header
3413  * (or other information) won't be available to clients. For NAMEI, also
3414  * close the file handles.  However, the fileserver does call this during
3415  * an attach following a volume operation.
3416  */
3417 void
3418 VDetachVolume_r(Error * ec, Volume * vp)
3419 {
3420     VolumeId volume;
3421     struct DiskPartition64 *tpartp;
3422     int notifyServer = 0;
3423     int  useDone = FSYNC_VOL_ON;
3424
3425     *ec = 0;                    /* always "succeeds" */
3426     if (VCanUseFSSYNC()) {
3427         notifyServer = vp->needsPutBack;
3428         if (V_destroyMe(vp) == DESTROY_ME)
3429             useDone = FSYNC_VOL_DONE;
3430 #ifdef AFS_DEMAND_ATTACH_FS
3431         else if (!V_blessed(vp) || !V_inService(vp))
3432             useDone = FSYNC_VOL_LEAVE_OFF;
3433 #endif
3434     }
3435     tpartp = vp->partition;
3436     volume = V_id(vp);
3437     DeleteVolumeFromHashTable(vp);
3438     vp->shuttingDown = 1;
3439 #ifdef AFS_DEMAND_ATTACH_FS
3440     DeleteVolumeFromVByPList_r(vp);
3441     VLRU_Delete_r(vp);
3442     VChangeState_r(vp, VOL_STATE_SHUTTING_DOWN);
3443 #else
3444     if (programType != fileServer) 
3445         V_inUse(vp) = 0;
3446 #endif /* AFS_DEMAND_ATTACH_FS */
3447     VPutVolume_r(vp);
3448     /* Will be detached sometime in the future--this is OK since volume is offline */
3449
3450     /* XXX the following code should really be moved to VCheckDetach() since the volume
3451      * is not technically detached until the refcounts reach zero
3452      */
3453 #ifdef FSSYNC_BUILD_CLIENT
3454     if (VCanUseFSSYNC() && notifyServer) {
3455         /* 
3456          * Note:  The server is not notified in the case of a bogus volume 
3457          * explicitly to make it possible to create a volume, do a partial 
3458          * restore, then abort the operation without ever putting the volume 
3459          * online.  This is essential in the case of a volume move operation 
3460          * between two partitions on the same server.  In that case, there 
3461          * would be two instances of the same volume, one of them bogus, 
3462          * which the file server would attempt to put on line 
3463          */
3464         FSYNC_VolOp(volume, tpartp->name, useDone, 0, NULL);
3465         /* XXX this code path is only hit by volume utilities, thus
3466          * V_BreakVolumeCallbacks will always be NULL.  if we really
3467          * want to break callbacks in this path we need to use FSYNC_VolOp() */
3468 #ifdef notdef
3469         /* Dettaching it so break all callbacks on it */
3470         if (V_BreakVolumeCallbacks) {
3471             Log("volume %u detached; breaking all call backs\n", volume);
3472             (*V_BreakVolumeCallbacks) (volume);
3473         }
3474 #endif
3475     }
3476 #endif /* FSSYNC_BUILD_CLIENT */
3477 }
3478
3479 void
3480 VDetachVolume(Error * ec, Volume * vp)
3481 {
3482     VOL_LOCK;
3483     VDetachVolume_r(ec, vp);
3484     VOL_UNLOCK;
3485 }
3486
3487
3488 /***************************************************/
3489 /* Volume fd/inode handle closing routines         */
3490 /***************************************************/
3491
3492 /* For VDetachVolume, we close all cached file descriptors, but keep
3493  * the Inode handles in case we need to read from a busy volume.
3494  */
3495 /* for demand attach, caller MUST hold ref count on vp */
3496 static void
3497 VCloseVolumeHandles_r(Volume * vp)
3498 {
3499 #ifdef AFS_DEMAND_ATTACH_FS
3500     VolState state_save;
3501
3502     state_save = VChangeState_r(vp, VOL_STATE_OFFLINING);
3503 #endif
3504
3505     /* demand attach fs
3506      *
3507      * XXX need to investigate whether we can perform
3508      * DFlushVolume outside of vol_glock_mutex... 
3509      *
3510      * VCloseVnodeFiles_r drops the glock internally */
3511     DFlushVolume(V_id(vp));
3512     VCloseVnodeFiles_r(vp);
3513
3514 #ifdef AFS_DEMAND_ATTACH_FS
3515     VOL_UNLOCK;
3516 #endif
3517
3518     /* Too time consuming and unnecessary for the volserver */
3519     if (programType == fileServer) {
3520         IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
3521         IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
3522         IH_CONDSYNC(vp->diskDataHandle);
3523 #ifdef AFS_NT40_ENV
3524         IH_CONDSYNC(vp->linkHandle);
3525 #endif /* AFS_NT40_ENV */
3526     }
3527
3528     IH_REALLYCLOSE(vp->vnodeIndex[vLarge].handle);
3529     IH_REALLYCLOSE(vp->vnodeIndex[vSmall].handle);
3530     IH_REALLYCLOSE(vp->diskDataHandle);
3531     IH_REALLYCLOSE(vp->linkHandle);
3532
3533 #ifdef AFS_DEMAND_ATTACH_FS
3534     VOL_LOCK;
3535     VChangeState_r(vp, state_save);
3536 #endif
3537 }
3538
3539 /* For both VForceOffline and VOffline, we close all relevant handles.
3540  * For VOffline, if we re-attach the volume, the files may possible be
3541  * different than before. 
3542  */
3543 /* for demand attach, caller MUST hold a ref count on vp */
3544 static void
3545 VReleaseVolumeHandles_r(Volume * vp)
3546 {
3547 #ifdef AFS_DEMAND_ATTACH_FS
3548     VolState state_save;
3549
3550     state_save = VChangeState_r(vp, VOL_STATE_DETACHING);
3551 #endif
3552
3553     /* XXX need to investigate whether we can perform
3554      * DFlushVolume outside of vol_glock_mutex... */
3555     DFlushVolume(V_id(vp));
3556
3557     VReleaseVnodeFiles_r(vp); /* releases the glock internally */
3558
3559 #ifdef AFS_DEMAND_ATTACH_FS
3560     VOL_UNLOCK;
3561 #endif
3562
3563     /* Too time consuming and unnecessary for the volserver */
3564     if (programType == fileServer) {
3565         IH_CONDSYNC(vp->vnodeIndex[vLarge].handle);
3566         IH_CONDSYNC(vp->vnodeIndex[vSmall].handle);
3567         IH_CONDSYNC(vp->diskDataHandle);
3568 #ifdef AFS_NT40_ENV
3569         IH_CONDSYNC(vp->linkHandle);
3570 #endif /* AFS_NT40_ENV */
3571     }
3572
3573     IH_RELEASE(vp->vnodeIndex[vLarge].handle);
3574     IH_RELEASE(vp->vnodeIndex[vSmall].handle);
3575     IH_RELEASE(vp->diskDataHandle);
3576     IH_RELEASE(vp->linkHandle);
3577
3578 #ifdef AFS_DEMAND_ATTACH_FS
3579     VOL_LOCK;
3580     VChangeState_r(vp, state_save);
3581 #endif
3582 }
3583
3584
3585 /***************************************************/
3586 /* Volume write and fsync routines                 */
3587 /***************************************************/
3588
3589 void
3590 VUpdateVolume_r(Error * ec, Volume * vp, int flags)
3591 {
3592 #ifdef AFS_DEMAND_ATTACH_FS
3593     VolState state_save;
3594
3595     if (flags & VOL_UPDATE_WAIT) {
3596         VCreateReservation_r(vp);
3597         VWaitExclusiveState_r(vp);
3598     }
3599 #endif
3600
3601     *ec = 0;
3602     if (programType == fileServer)
3603         V_uniquifier(vp) =
3604             (V_inUse(vp) ? V_nextVnodeUnique(vp) +
3605              200 : V_nextVnodeUnique(vp));
3606
3607 #ifdef AFS_DEMAND_ATTACH_FS
3608     state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
3609     VOL_UNLOCK;
3610 #endif
3611
3612     WriteVolumeHeader_r(ec, vp);
3613
3614 #ifdef AFS_DEMAND_ATTACH_FS
3615     VOL_LOCK;
3616     VChangeState_r(vp, state_save);
3617     if (flags & VOL_UPDATE_WAIT) {
3618         VCancelReservation_r(vp);
3619     }
3620 #endif
3621
3622     if (*ec) {
3623         Log("VUpdateVolume: error updating volume header, volume %u (%s)\n",
3624             V_id(vp), V_name(vp));
3625         /* try to update on-disk header, 
3626          * while preventing infinite recursion */
3627         if (!(flags & VOL_UPDATE_NOFORCEOFF)) {
3628             VForceOffline_r(vp, VOL_FORCEOFF_NOUPDATE);
3629         }
3630     }
3631 }
3632
3633 void
3634 VUpdateVolume(Error * ec, Volume * vp)
3635 {
3636     VOL_LOCK;
3637     VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
3638     VOL_UNLOCK;
3639 }
3640
3641 void
3642 VSyncVolume_r(Error * ec, Volume * vp, int flags)
3643 {
3644     FdHandle_t *fdP;
3645     int code;
3646 #ifdef AFS_DEMAND_ATTACH_FS
3647     VolState state_save;
3648 #endif
3649
3650     if (flags & VOL_SYNC_WAIT) {
3651         VUpdateVolume_r(ec, vp, VOL_UPDATE_WAIT);
3652     } else {
3653         VUpdateVolume_r(ec, vp, 0);
3654     }
3655     if (!*ec) {
3656 #ifdef AFS_DEMAND_ATTACH_FS
3657         state_save = VChangeState_r(vp, VOL_STATE_UPDATING);
3658         VOL_UNLOCK;
3659 #endif
3660         fdP = IH_OPEN(V_diskDataHandle(vp));
3661         assert(fdP != NULL);
3662         code = FDH_SYNC(fdP);
3663         assert(code == 0);
3664         FDH_CLOSE(fdP);
3665 #ifdef AFS_DEMAND_ATTACH_FS
3666         VOL_LOCK;
3667         VChangeState_r(vp, state_save);
3668 #endif
3669     }
3670 }
3671
3672 void
3673 VSyncVolume(Error * ec, Volume * vp)
3674 {
3675     VOL_LOCK;
3676     VSyncVolume_r(ec, vp, VOL_SYNC_WAIT);
3677     VOL_UNLOCK;
3678 }
3679
3680
3681 /***************************************************/
3682 /* Volume dealloaction routines                    */
3683 /***************************************************/
3684
3685 #ifdef AFS_DEMAND_ATTACH_FS
3686 static void
3687 FreeVolume(Volume * vp)
3688 {
3689     /* free the heap space, iff it's safe.
3690      * otherwise, pull it out of the hash table, so it
3691      * will get deallocated when all refs to it go away */
3692     if (!VCheckFree(vp)) {
3693         DeleteVolumeFromHashTable(vp);
3694         DeleteVolumeFromVByPList_r(vp);
3695
3696         /* make sure we invalidate the header cache entry */
3697         FreeVolumeHeader(vp);
3698     }
3699 }
3700 #endif /* AFS_DEMAND_ATTACH_FS */
3701
3702 static void
3703 ReallyFreeVolume(Volume * vp)
3704 {
3705     int i;
3706     if (!vp)
3707         return;
3708 #ifdef AFS_DEMAND_ATTACH_FS
3709     /* debug */
3710     VChangeState_r(vp, VOL_STATE_FREED);
3711     if (vp->pending_vol_op)
3712         free(vp->pending_vol_op);
3713 #endif /* AFS_DEMAND_ATTACH_FS */
3714     for (i = 0; i < nVNODECLASSES; i++)
3715         if (vp->vnodeIndex[i].bitmap)
3716             free(vp->vnodeIndex[i].bitmap);
3717     FreeVolumeHeader(vp);
3718 #ifndef AFS_DEMAND_ATTACH_FS
3719     DeleteVolumeFromHashTable(vp);
3720 #endif /* AFS_DEMAND_ATTACH_FS */
3721     free(vp);
3722 }
3723
3724 /* check to see if we should shutdown this volume
3725  * returns 1 if volume was freed, 0 otherwise */
3726 #ifdef AFS_DEMAND_ATTACH_FS
3727 static int
3728 VCheckDetach(register Volume * vp)
3729 {
3730     int ret = 0;
3731     Error ec = 0;
3732
3733     if (vp->nUsers || vp->nWaiters)
3734         return ret;
3735
3736     if (vp->shuttingDown) {
3737         ret = 1;
3738         if ((programType != fileServer) &&
3739             (V_inUse(vp) == programType) &&
3740             ((V_checkoutMode(vp) == V_VOLUPD) ||
3741              (V_checkoutMode(vp) == V_SECRETLY) ||
3742              ((V_checkoutMode(vp) == V_CLONE) &&
3743               (VolumeWriteable(vp))))) {
3744             V_inUse(vp) = 0;
3745             VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
3746             if (ec) {
3747                 Log("VCheckDetach: volume header update for volume %u "
3748                     "failed with errno %d\n", vp->hashid, errno);
3749             }
3750         }
3751         VReleaseVolumeHandles_r(vp);
3752         VCheckSalvage(vp);
3753         ReallyFreeVolume(vp);
3754         if (programType == fileServer) {
3755             assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3756         }
3757     }
3758     return ret;
3759 }
3760 #else /* AFS_DEMAND_ATTACH_FS */
3761 static int
3762 VCheckDetach(register Volume * vp)
3763 {
3764     int ret = 0;
3765     Error ec = 0;
3766
3767     if (vp->nUsers)
3768         return ret;
3769
3770     if (vp->shuttingDown) {
3771         ret = 1;
3772         if ((programType != fileServer) &&
3773             (V_inUse(vp) == programType) &&
3774             ((V_checkoutMode(vp) == V_VOLUPD) ||
3775              (V_checkoutMode(vp) == V_SECRETLY) ||
3776              ((V_checkoutMode(vp) == V_CLONE) &&
3777               (VolumeWriteable(vp))))) {
3778             V_inUse(vp) = 0;
3779             VUpdateVolume_r(&ec, vp, VOL_UPDATE_NOFORCEOFF);
3780             if (ec) {
3781                 Log("VCheckDetach: volume header update for volume %u failed with errno %d\n",
3782                     vp->hashid, errno);
3783             }
3784         }
3785         VReleaseVolumeHandles_r(vp);
3786         ReallyFreeVolume(vp);
3787         if (programType == fileServer) {
3788 #if defined(AFS_PTHREAD_ENV)
3789             assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3790 #else /* AFS_PTHREAD_ENV */
3791             LWP_NoYieldSignal(VPutVolume);
3792 #endif /* AFS_PTHREAD_ENV */
3793         }
3794     }
3795     return ret;
3796 }
3797 #endif /* AFS_DEMAND_ATTACH_FS */
3798
3799 /* check to see if we should offline this volume
3800  * return 1 if volume went offline, 0 otherwise */
3801 #ifdef AFS_DEMAND_ATTACH_FS
3802 static int
3803 VCheckOffline(register Volume * vp)
3804 {
3805     int ret = 0;
3806
3807     if (vp->goingOffline && !vp->nUsers) {
3808         Error error;
3809         assert(programType == fileServer);
3810         assert((V_attachState(vp) != VOL_STATE_ATTACHED) &&
3811                (V_attachState(vp) != VOL_STATE_FREED) &&
3812                (V_attachState(vp) != VOL_STATE_PREATTACHED) &&
3813                (V_attachState(vp) != VOL_STATE_UNATTACHED));
3814
3815         /* valid states:
3816          *
3817          * VOL_STATE_GOING_OFFLINE
3818          * VOL_STATE_SHUTTING_DOWN
3819          * VIsErrorState(V_attachState(vp))
3820          * VIsExclusiveState(V_attachState(vp))
3821          */
3822
3823         VCreateReservation_r(vp);
3824         VChangeState_r(vp, VOL_STATE_OFFLINING);
3825
3826         ret = 1;
3827         /* must clear the goingOffline flag before we drop the glock */
3828         vp->goingOffline = 0;
3829         V_inUse(vp) = 0;
3830
3831         VLRU_Delete_r(vp);
3832
3833         /* perform async operations */
3834         VUpdateVolume_r(&error, vp, 0);
3835         VCloseVolumeHandles_r(vp);
3836
3837         if (LogLevel) {
3838             if (V_offlineMessage(vp)[0]) {
3839                 Log("VOffline: Volume %lu (%s) is now offline (%s)\n",
3840                     afs_printable_uint32_lu(V_id(vp)), V_name(vp),
3841                     V_offlineMessage(vp));
3842             } else {
3843                 Log("VOffline: Volume %lu (%s) is now offline\n",
3844                     afs_printable_uint32_lu(V_id(vp)), V_name(vp));
3845             }
3846         }
3847
3848         /* invalidate the volume header cache entry */
3849         FreeVolumeHeader(vp);
3850
3851         /* if nothing changed state to error or salvaging,
3852          * drop state to unattached */
3853         if (!VIsErrorState(V_attachState(vp))) {
3854             VChangeState_r(vp, VOL_STATE_UNATTACHED);
3855         }
3856         VCancelReservation_r(vp);
3857         /* no usage of vp is safe beyond this point */
3858     }
3859     return ret;
3860 }
3861 #else /* AFS_DEMAND_ATTACH_FS */
3862 static int
3863 VCheckOffline(register Volume * vp)
3864 {
3865     int ret = 0;
3866
3867     if (vp->goingOffline && !vp->nUsers) {
3868         Error error;
3869         assert(programType == fileServer);
3870
3871         ret = 1;
3872         vp->goingOffline = 0;
3873         V_inUse(vp) = 0;
3874         VUpdateVolume_r(&error, vp, 0);
3875         VCloseVolumeHandles_r(vp);
3876         if (LogLevel) {
3877             Log("VOffline: Volume %u (%s) is now offline", V_id(vp),
3878                 V_name(vp));
3879             if (V_offlineMessage(vp)[0])
3880                 Log(" (%s)", V_offlineMessage(vp));
3881             Log("\n");
3882         }
3883         FreeVolumeHeader(vp);
3884 #ifdef AFS_PTHREAD_ENV
3885         assert(pthread_cond_broadcast(&vol_put_volume_cond) == 0);
3886 #else /* AFS_PTHREAD_ENV */
3887         LWP_NoYieldSignal(VPutVolume);
3888 #endif /* AFS_PTHREAD_ENV */
3889     }
3890     return ret;
3891 }
3892 #endif /* AFS_DEMAND_ATTACH_FS */
3893
3894 /***************************************************/
3895 /* demand attach fs ref counting routines          */
3896 /***************************************************/
3897
3898 #ifdef AFS_DEMAND_ATTACH_FS
3899 /* the following two functions handle reference counting for
3900  * asynchronous operations on volume structs.
3901  *
3902  * their purpose is to prevent a VDetachVolume or VShutdown
3903  * from free()ing the Volume struct during an async i/o op */
3904
3905 /* register with the async volume op ref counter */
3906 /* VCreateReservation_r moved into inline code header because it 
3907  * is now needed in vnode.c -- tkeiser 11/20/2007 
3908  */
3909
3910 /**
3911  * decrement volume-package internal refcount.
3912  *
3913  * @param vp  volume object pointer
3914  *
3915  * @internal volume package internal use only
3916  *
3917  * @pre 
3918  *    @arg VOL_LOCK is held
3919  *    @arg lightweight refcount held
3920  *
3921  * @post volume waiters refcount is decremented; volume may
3922  *       have been deallocated/shutdown/offlined/salvaged/
3923  *       whatever during the process
3924  *
3925  * @warning once you have tossed your last reference (you can acquire
3926  *          lightweight refs recursively) it is NOT SAFE to reference
3927  *          a volume object pointer ever again
3928  *
3929  * @see VCreateReservation_r
3930  *
3931  * @note DEMAND_ATTACH_FS only
3932  */
3933 void
3934 VCancelReservation_r(Volume * vp)
3935 {
3936     assert(--vp->nWaiters >= 0);
3937     if (vp->nWaiters == 0) {
3938         VCheckOffline(vp);
3939         if (!VCheckDetach(vp)) {
3940             VCheckSalvage(vp);
3941             VCheckFree(vp);
3942         }
3943     }
3944 }
3945
3946 /* check to see if we should free this volume now
3947  * return 1 if volume was freed, 0 otherwise */
3948 static int
3949 VCheckFree(Volume * vp)
3950 {
3951     int ret = 0;
3952     if ((vp->nUsers == 0) &&
3953         (vp->nWaiters == 0) &&
3954         !(V_attachFlags(vp) & (VOL_IN_HASH | 
3955                                VOL_ON_VBYP_LIST | 
3956                                VOL_IS_BUSY |
3957                                VOL_ON_VLRU))) {
3958         ReallyFreeVolume(vp);
3959         ret = 1;
3960     }
3961     return ret;
3962 }
3963 #endif /* AFS_DEMAND_ATTACH_FS */
3964
3965
3966 /***************************************************/
3967 /* online volume operations routines               */
3968 /***************************************************/
3969
3970 #ifdef AFS_DEMAND_ATTACH_FS
3971 /**
3972  * register a volume operation on a given volume.
3973  *
3974  * @param[in] vp       volume object
3975  * @param[in] vopinfo  volume operation info object
3976  *
3977  * @pre VOL_LOCK is held
3978  *
3979  * @post volume operation info object attached to volume object.
3980  *       volume operation statistics updated.
3981  *
3982  * @note by "attached" we mean a copy of the passed in object is made
3983  *
3984  * @internal volume package internal use only
3985  */
3986 int
3987 VRegisterVolOp_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
3988 {
3989     FSSYNC_VolOp_info * info;
3990
3991     /* attach a vol op info node to the volume struct */
3992     info = (FSSYNC_VolOp_info *) malloc(sizeof(FSSYNC_VolOp_info));
3993     assert(info != NULL);
3994     memcpy(info, vopinfo, sizeof(FSSYNC_VolOp_info));
3995     vp->pending_vol_op = info;
3996
3997     /* update stats */
3998     vp->stats.last_vol_op = FT_ApproxTime();
3999     vp->stats.vol_ops++;
4000     IncUInt64(&VStats.vol_ops);
4001
4002     return 0;
4003 }
4004
4005 /**
4006  * deregister the volume operation attached to this volume.
4007  *
4008  * @param[in] vp  volume object pointer
4009  *
4010  * @pre VOL_LOCK is held
4011  *
4012  * @post the volume operation info object is detached from the volume object
4013  *
4014  * @internal volume package internal use only
4015  */
4016 int
4017 VDeregisterVolOp_r(Volume * vp)
4018 {
4019     if (vp->pending_vol_op) {
4020         free(vp->pending_vol_op);
4021         vp->pending_vol_op = NULL;
4022     }
4023     return 0;
4024 }
4025 #endif /* AFS_DEMAND_ATTACH_FS */
4026
4027 /**
4028  * determine whether it is safe to leave a volume online during
4029  * the volume operation described by the vopinfo object.
4030  *
4031  * @param[in] vp        volume object
4032  * @param[in] vopinfo   volume operation info object
4033  *
4034  * @return whether it is safe to leave volume online
4035  *    @retval 0  it is NOT SAFE to leave the volume online
4036  *    @retval 1  it is safe to leave the volume online during the operation
4037  *
4038  * @pre
4039  *    @arg VOL_LOCK is held
4040  *    @arg disk header attached to vp (heavyweight ref on vp will guarantee
4041  *         this condition is met)
4042  *
4043  * @internal volume package internal use only
4044  */
4045 int
4046 VVolOpLeaveOnline_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4047 {
4048     return (vopinfo->vol_op_state == FSSYNC_VolOpRunningOnline ||
4049             (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4050             (vopinfo->com.reason == V_READONLY ||
4051              (!VolumeWriteable(vp) &&
4052               (vopinfo->com.reason == V_CLONE ||
4053                vopinfo->com.reason == V_DUMP)))));
4054 }
4055
4056 /**
4057  * determine whether VBUSY should be set during this volume operation.
4058  *
4059  * @param[in] vp        volume object
4060  * @param[in] vopinfo   volume operation info object
4061  *
4062  * @return whether VBUSY should be set
4063  *   @retval 0  VBUSY does NOT need to be set
4064  *   @retval 1  VBUSY SHOULD be set
4065  *
4066  * @pre VOL_LOCK is held
4067  *
4068  * @internal volume package internal use only
4069  */
4070 int
4071 VVolOpSetVBusy_r(Volume * vp, FSSYNC_VolOp_info * vopinfo)
4072 {
4073     return ((vopinfo->com.command == FSYNC_VOL_OFF &&
4074             vopinfo->com.reason == FSYNC_SALVAGE) ||
4075             (vopinfo->com.command == FSYNC_VOL_NEEDVOLUME &&
4076             (vopinfo->com.reason == V_CLONE ||
4077              vopinfo->com.reason == V_DUMP)));
4078 }
4079
4080
4081 /***************************************************/
4082 /* online salvager routines                        */
4083 /***************************************************/
4084 #if defined(AFS_DEMAND_ATTACH_FS)
4085 /**
4086  * check whether a salvage needs to be performed on this volume.
4087  *
4088  * @param[in] vp   pointer to volume object
4089  *
4090  * @return status code
4091  *    @retval 0 no salvage scheduled
4092  *    @retval 1 a salvage has been scheduled with the salvageserver
4093  *
4094  * @pre VOL_LOCK is held
4095  *
4096  * @post if salvage request flag is set and nUsers and nWaiters are zero,
4097  *       then a salvage will be requested
4098  *
4099  * @note this is one of the event handlers called by VCancelReservation_r
4100  *
4101  * @see VCancelReservation_r
4102  *
4103  * @internal volume package internal use only.
4104  */
4105 static int
4106 VCheckSalvage(register Volume * vp)
4107 {
4108     int ret = 0;
4109 #ifdef SALVSYNC_BUILD_CLIENT
4110     if (vp->nUsers || vp->nWaiters)
4111         return ret;
4112     if (vp->salvage.requested) {
4113         VScheduleSalvage_r(vp);
4114         ret = 1;
4115     }
4116 #endif /* SALVSYNC_BUILD_CLIENT */
4117     return ret;
4118 }
4119
4120 /**
4121  * request volume salvage.
4122  *
4123  * @param[out] ec      computed client error code
4124  * @param[in]  vp      volume object pointer
4125  * @param[in]  reason  reason code (passed to salvageserver via SALVSYNC)
4126  * @param[in]  flags   see flags note below
4127  *
4128  * @note flags:
4129  *       VOL_SALVAGE_INVALIDATE_HEADER causes volume header cache entry 
4130  *                                     to be invalidated.
4131  *
4132  * @pre VOL_LOCK is held.
4133  *
4134  * @post volume state is changed.
4135  *       for fileserver, salvage will be requested once refcount reaches zero.
4136  *
4137  * @return operation status code
4138  *   @retval 0  volume salvage will occur
4139  *   @retval 1  volume salvage could not be scheduled
4140  *
4141  * @note DAFS fileserver only
4142  *
4143  * @note this call does not synchronously schedule a volume salvage.  rather,
4144  *       it sets volume state so that when volume refcounts reach zero, a
4145  *       volume salvage will occur.  by "refcounts", we mean both nUsers and 
4146  *       nWaiters must be zero.
4147  *
4148  * @internal volume package internal use only.
4149  */
4150 int
4151 VRequestSalvage_r(Error * ec, Volume * vp, int reason, int flags)
4152 {
4153     int code = 0;
4154     /*
4155      * for DAFS volume utilities, transition to error state
4156      * (at some point in the future, we should consider
4157      *  making volser talk to salsrv)
4158      */
4159     if (!VCanScheduleSalvage()) {
4160         VChangeState_r(vp, VOL_STATE_ERROR);
4161         *ec = VSALVAGE;
4162         return 1;
4163     }
4164
4165     if (programType != fileServer) {
4166 #ifdef FSSYNC_BUILD_CLIENT
4167         if (VCanUseFSSYNC()) {
4168             /*
4169              * If we aren't the fileserver, tell the fileserver the volume
4170              * needs to be salvaged. We could directly tell the
4171              * salvageserver, but the fileserver keeps track of some stats
4172              * related to salvages, and handles some other salvage-related
4173              * complications for us.
4174              */
4175
4176             /*
4177              * You might wonder why we don't check for
4178              * VIsSalvager(V_inUse(vp)) here, since we do check for that
4179              * in the fileServer case (below). The reason is that the
4180              * below check is done since the fileServer can't tell if a
4181              * salvage is still running or not when V_inUse refers to a
4182              * salvaging program. However, if we are a non-fileserver,
4183              * to get here we must have checked out the volume from the
4184              * fileserver and locked the partition, meaning there must
4185              * be no salvager running; so we just always try to salvage
4186              */
4187
4188             code = FSYNC_VolOp(vp->hashid, vp->partition->name,
4189                                FSYNC_VOL_FORCE_ERROR, FSYNC_SALVAGE, NULL);
4190             if (code == SYNC_OK) {
4191                 *ec = VSALVAGING;
4192                 return 0;
4193             }
4194             Log("VRequestSalvage: force error salvage state of volume %u"
4195                 " denied by fileserver\n", vp->hashid);
4196
4197             /* fall through to error condition below */
4198         }
4199 #endif /* FSSYNC_BUILD_CLIENT */
4200         VChangeState_r(vp, VOL_STATE_ERROR);
4201         *ec = VSALVAGE;
4202         return 1;
4203     }
4204
4205     if (!vp->salvage.requested) {
4206         vp->salvage.requested = 1;
4207         vp->salvage.reason = reason;
4208         vp->stats.last_salvage = FT_ApproxTime();
4209
4210         if (vp->header && VIsSalvager(V_inUse(vp))) {
4211             /* Right now we can't tell for sure if this indicates a
4212              * salvage is running, or if a running salvage crashed, so
4213              * we always ERROR the volume in case a salvage is running.
4214              * Once we get rid of the partition lock and instead lock
4215              * individual volume header files for salvages, we will
4216              * probably be able to tell if a salvage is running, and we
4217              * can do away with this behavior. */
4218             Log("VRequestSalvage: volume %u appears to be salvaging, but we\n", vp->hashid);
4219             Log("  didn't request a salvage. Forcing it offline waiting for the\n");
4220             Log("  salvage to finish; if you are sure no salvage is running,\n");
4221             Log("  run a salvage manually.\n");
4222
4223             /* make sure neither VScheduleSalvage_r nor
4224              * VUpdateSalvagePriority_r try to schedule another salvage */
4225             vp->salvage.requested = vp->salvage.scheduled = 0;
4226
4227             /* these stats aren't correct, but doing this makes them
4228              * slightly closer to being correct */
4229             vp->stats.salvages++;
4230             vp->stats.last_salvage_req = FT_ApproxTime();
4231             IncUInt64(&VStats.salvages);
4232
4233             VChangeState_r(vp, VOL_STATE_ERROR);
4234             *ec = VSALVAGE;
4235             code = 1;
4236
4237         } else if (vp->stats.salvages < SALVAGE_COUNT_MAX) {
4238             VChangeState_r(vp, VOL_STATE_SALVAGING);
4239             *ec = VSALVAGING;
4240         } else {
4241             Log("VRequestSalvage: volume %u online salvaged too many times; forced offline.\n", vp->hashid);
4242
4243             /* make sure neither VScheduleSalvage_r nor
4244              * VUpdateSalvagePriority_r try to schedule another salvage */
4245             vp->salvage.requested = vp->salvage.scheduled = 0;
4246
4247             VChangeState_r(vp, VOL_STATE_ERROR);
4248             *ec = VSALVAGE;
4249             code = 1;
4250         }
4251         if (flags & VOL_SALVAGE_INVALIDATE_HEADER) {
4252             /* Instead of ReleaseVolumeHeader, we do FreeVolumeHeader() 
4253                so that the the next VAttachVolumeByVp_r() invocation 
4254                of attach2() will pull in a cached header 
4255                entry and fail, then load a fresh one from disk and attach 
4256                it to the volume.             
4257             */
4258             FreeVolumeHeader(vp);
4259         }
4260     }
4261     return code;
4262 }
4263
4264 /**
4265  * update salvageserver scheduling priority for a volume.
4266  *
4267  * @param[in] vp  pointer to volume object
4268  *
4269  * @return operation status
4270  *   @retval 0  success
4271  *   @retval 1  request denied, or SALVSYNC communications failure
4272  *
4273  * @pre VOL_LOCK is held.
4274  *
4275  * @post in-core salvage priority counter is incremented.  if at least
4276  *       SALVAGE_PRIO_UPDATE_INTERVAL seconds have elapsed since the
4277  *       last SALVSYNC_RAISEPRIO request, we contact the salvageserver
4278  *       to update its priority queue.  if no salvage is scheduled,
4279  *       this function is a no-op.
4280  *
4281  * @note DAFS fileserver only
4282  *
4283  * @note this should be called whenever a VGetVolume fails due to a 
4284  *       pending salvage request
4285  *
4286  * @todo should set exclusive state and drop glock around salvsync call
4287  *
4288  * @internal volume package internal use only.
4289  */
4290 int
4291 VUpdateSalvagePriority_r(Volume * vp)
4292 {
4293     int ret=0;
4294
4295 #ifdef SALVSYNC_BUILD_CLIENT
4296     afs_uint32 now;
4297     int code;
4298
4299     vp->salvage.prio++;
4300     now = FT_ApproxTime();
4301
4302     /* update the salvageserver priority queue occasionally so that
4303      * frequently requested volumes get moved to the head of the queue 
4304      */
4305     if ((vp->salvage.scheduled) &&
4306         (vp->stats.last_salvage_req < (now-SALVAGE_PRIO_UPDATE_INTERVAL))) {
4307         code = SALVSYNC_SalvageVolume(vp->hashid,
4308                                       VPartitionPath(vp->partition),
4309                                       SALVSYNC_RAISEPRIO,
4310                                       vp->salvage.reason,
4311                                       vp->salvage.prio,
4312                                       NULL);
4313         vp->stats.last_salvage_req = now;
4314         if (code != SYNC_OK) {
4315             ret = 1;
4316         }
4317     }
4318 #endif /* SALVSYNC_BUILD_CLIENT */
4319     return ret;
4320 }
4321
4322
4323 #ifdef SALVSYNC_BUILD_CLIENT
4324 /**
4325  * schedule a salvage with the salvage server.
4326  *
4327  * @param[in] vp  pointer to volume object
4328  *
4329  * @return operation status
4330  *    @retval 0 salvage scheduled successfully
4331  *    @retval 1 salvage not scheduled, or SALVSYNC com error
4332  *
4333  * @pre 
4334  *    @arg VOL_LOCK is held.
4335  *    @arg nUsers and nWaiters should be zero.
4336  *
4337  * @post salvageserver is sent a salvage request
4338  *
4339  * @note DAFS fileserver only
4340  *
4341  * @internal volume package internal use only.
4342  */
4343 static int
4344 VScheduleSalvage_r(Volume * vp)
4345 {
4346     int ret=0;
4347     int code;
4348     VolState state_save;
4349     VThreadOptions_t * thread_opts;
4350     char partName[16];
4351
4352     if (vp->nWaiters || vp->nUsers) {
4353         return 1;
4354     }
4355
4356     /* prevent endless salvage,attach,salvage,attach,... loops */
4357     if (vp->stats.salvages >= SALVAGE_COUNT_MAX)
4358         return 1;
4359
4360     /*
4361      * don't perform salvsync ops on certain threads
4362      */
4363     thread_opts = pthread_getspecific(VThread_key);
4364     if (thread_opts == NULL) {
4365         thread_opts = &VThread_defaults;
4366     }
4367     if (thread_opts->disallow_salvsync || vol_disallow_salvsync) {
4368         return 1;
4369     }
4370
4371     /*
4372      * XXX the scheduling process should really be done asynchronously
4373      *     to avoid fssync deadlocks
4374      */
4375     if (!vp->salvage.scheduled) {
4376         /* if we haven't previously scheduled a salvage, do so now 
4377          *
4378          * set the volume to an exclusive state and drop the lock
4379          * around the SALVSYNC call
4380          *
4381          * note that we do NOT acquire a reservation here -- doing so
4382          * could result in unbounded recursion
4383          */
4384         strlcpy(partName, VPartitionPath(vp->partition), sizeof(partName));
4385         state_save = VChangeState_r(vp, VOL_STATE_SALVSYNC_REQ);
4386         VOL_UNLOCK;
4387
4388         /* can't use V_id() since there's no guarantee
4389          * we have the disk data header at this point */
4390         code = SALVSYNC_SalvageVolume(vp->hashid,
4391                                       partName,
4392                                       SALVSYNC_SALVAGE,
4393                                       vp->salvage.reason,
4394                                       vp->salvage.prio,
4395                                       NULL);
4396         VOL_LOCK;
4397         VChangeState_r(vp, state_save);
4398
4399         if (code == SYNC_OK) {
4400             vp->salvage.scheduled = 1;
4401             vp->stats.salvages++;
4402             vp->stats.last_salvage_req = FT_ApproxTime();
4403             IncUInt64(&VStats.salvages);
4404         } else {
4405             ret = 1;
4406             switch(code) {
4407             case SYNC_BAD_COMMAND:
4408             case SYNC_COM_ERROR:
4409                 break;
4410             case SYNC_DENIED:
4411                 Log("VScheduleSalvage_r:  SALVSYNC request denied\n");
4412                 break;
4413             default:
4414                 Log("VScheduleSalvage_r:  SALVSYNC unknown protocol error\n");
4415                 break;
4416             }
4417         }
4418     }
4419     return ret;
4420 }
4421
4422 /**
4423  * connect to the salvageserver SYNC service.
4424  *
4425  * @return operation status
4426  *    @retval 0 failure
4427  *    @retval 1 success
4428  *
4429  * @post connection to salvageserver SYNC service established
4430  *
4431  * @see VConnectSALV_r
4432  * @see VDisconnectSALV
4433  * @see VReconnectSALV
4434  */
4435 int
4436 VConnectSALV(void)
4437 {
4438     int retVal;
4439     VOL_LOCK;
4440     retVal = VConnectSALV_r();
4441     VOL_UNLOCK;
4442     return retVal;
4443 }
4444
4445 /**
4446  * connect to the salvageserver SYNC service.
4447  *
4448  * @return operation status
4449  *    @retval 0 failure
4450  *    @retval 1 success
4451  *
4452  * @pre VOL_LOCK is held.
4453  *
4454  * @post connection to salvageserver SYNC service established
4455  *
4456  * @see VConnectSALV
4457  * @see VDisconnectSALV_r
4458  * @see VReconnectSALV_r
4459  * @see SALVSYNC_clientInit
4460  *
4461  * @internal volume package internal use only.
4462  */
4463 int
4464 VConnectSALV_r(void)
4465 {
4466     return SALVSYNC_clientInit();
4467 }
4468
4469 /**
4470  * disconnect from the salvageserver SYNC service.
4471  *
4472  * @return operation status
4473  *    @retval 0 success
4474  *
4475  * @pre client should have a live connection to the salvageserver
4476  *
4477  * @post connection to salvageserver SYNC service destroyed
4478  *
4479  * @see VDisconnectSALV_r
4480  * @see VConnectSALV
4481  * @see VReconnectSALV
4482  */
4483 int
4484 VDisconnectSALV(void)
4485 {
4486     VOL_LOCK;
4487     VDisconnectSALV_r();
4488     VOL_UNLOCK;
4489     return 0;
4490 }
4491
4492 /**
4493  * disconnect from the salvageserver SYNC service.
4494  *
4495  * @return operation status
4496  *    @retval 0 success
4497  *
4498  * @pre 
4499  *    @arg VOL_LOCK is held.
4500  *    @arg client should have a live connection to the salvageserver.
4501  *
4502  * @post connection to salvageserver SYNC service destroyed
4503  *
4504  * @see VDisconnectSALV
4505  * @see VConnectSALV_r
4506  * @see VReconnectSALV_r
4507  * @see SALVSYNC_clientFinis
4508  *
4509  * @internal volume package internal use only.
4510  */
4511 int
4512 VDisconnectSALV_r(void)
4513
4514     return SALVSYNC_clientFinis();
4515 }
4516
4517 /**
4518  * disconnect and then re-connect to the salvageserver SYNC service.
4519  *
4520  * @return operation status
4521  *    @retval 0 failure
4522  *    @retval 1 success
4523  *
4524  * @pre client should have a live connection to the salvageserver
4525  *
4526  * @post old connection is dropped, and a new one is established
4527  *
4528  * @see VConnectSALV
4529  * @see VDisconnectSALV
4530  * @see VReconnectSALV_r
4531  */
4532 int
4533 VReconnectSALV(void)
4534 {
4535     int retVal;
4536     VOL_LOCK;
4537     retVal = VReconnectSALV_r();
4538     VOL_UNLOCK;
4539     return retVal;
4540 }
4541
4542 /**
4543  * disconnect and then re-connect to the salvageserver SYNC service.
4544  *
4545  * @return operation status
4546  *    @retval 0 failure
4547  *    @retval 1 success
4548  *
4549  * @pre 
4550  *    @arg VOL_LOCK is held.
4551  *    @arg client should have a live connection to the salvageserver.
4552  *
4553  * @post old connection is dropped, and a new one is established
4554  *
4555  * @see VConnectSALV_r
4556  * @see VDisconnectSALV
4557  * @see VReconnectSALV
4558  * @see SALVSYNC_clientReconnect
4559  *
4560  * @internal volume package internal use only.
4561  */
4562 int
4563 VReconnectSALV_r(void)
4564 {
4565     return SALVSYNC_clientReconnect();
4566 }
4567 #endif /* SALVSYNC_BUILD_CLIENT */
4568 #endif /* AFS_DEMAND_ATTACH_FS */
4569
4570
4571 /***************************************************/
4572 /* FSSYNC routines                                 */
4573 /***************************************************/
4574
4575 /* This must be called by any volume utility which needs to run while the
4576    file server is also running.  This is separated from VInitVolumePackage2 so
4577    that a utility can fork--and each of the children can independently
4578    initialize communication with the file server */
4579 #ifdef FSSYNC_BUILD_CLIENT
4580 /**
4581  * connect to the fileserver SYNC service.
4582  *
4583  * @return operation status
4584  *    @retval 0 failure
4585  *    @retval 1 success
4586  *
4587  * @pre 
4588  *    @arg VInit must equal 2.
4589  *    @arg Program Type must not be fileserver or salvager.
4590  *
4591  * @post connection to fileserver SYNC service established
4592  *
4593  * @see VConnectFS_r
4594  * @see VDisconnectFS
4595  * @see VChildProcReconnectFS
4596  */
4597 int
4598 VConnectFS(void)
4599 {
4600     int retVal;
4601     VOL_LOCK;
4602     retVal = VConnectFS_r();
4603     VOL_UNLOCK;
4604     return retVal;
4605 }
4606
4607 /**
4608  * connect to the fileserver SYNC service.
4609  *
4610  * @return operation status
4611  *    @retval 0 failure
4612  *    @retval 1 success
4613  *
4614  * @pre 
4615  *    @arg VInit must equal 2.
4616  *    @arg Program Type must not be fileserver or salvager.
4617  *    @arg VOL_LOCK is held.
4618  *
4619  * @post connection to fileserver SYNC service established
4620  *
4621  * @see VConnectFS
4622  * @see VDisconnectFS_r
4623  * @see VChildProcReconnectFS_r
4624  *
4625  * @internal volume package internal use only.
4626  */
4627 int
4628 VConnectFS_r(void)
4629 {
4630     int rc;
4631     assert((VInit == 2) && 
4632            (programType != fileServer) &&
4633            (programType != salvager));
4634     rc = FSYNC_clientInit();
4635     if (rc)
4636         VInit = 3;
4637     return rc;
4638 }
4639
4640 /**
4641  * disconnect from the fileserver SYNC service.
4642  *
4643  * @pre 
4644  *    @arg client should have a live connection to the fileserver.
4645  *    @arg VOL_LOCK is held.
4646  *    @arg Program Type must not be fileserver or salvager.
4647  *
4648  * @post connection to fileserver SYNC service destroyed
4649  *
4650  * @see VDisconnectFS
4651  * @see VConnectFS_r
4652  * @see VChildProcReconnectFS_r
4653  *
4654  * @internal volume package internal use only.
4655  */
4656 void
4657 VDisconnectFS_r(void)
4658 {
4659     assert((programType != fileServer) &&
4660            (programType != salvager));
4661     FSYNC_clientFinis();
4662     VInit = 2;
4663 }
4664
4665 /**
4666  * disconnect from the fileserver SYNC service.
4667  *
4668  * @pre
4669  *    @arg client should have a live connection to the fileserver.
4670  *    @arg Program Type must not be fileserver or salvager.
4671  *
4672  * @post connection to fileserver SYNC service destroyed
4673  *
4674  * @see VDisconnectFS_r
4675  * @see VConnectFS
4676  * @see VChildProcReconnectFS
4677  */
4678 void
4679 VDisconnectFS(void)
4680 {
4681     VOL_LOCK;
4682     VDisconnectFS_r();
4683     VOL_UNLOCK;
4684 }
4685
4686 /**
4687  * connect to the fileserver SYNC service from a child process following a fork.
4688  *
4689  * @return operation status
4690  *    @retval 0 failure
4691  *    @retval 1 success
4692  *
4693  * @pre
4694  *    @arg VOL_LOCK is held.
4695  *    @arg current FSYNC handle is shared with a parent process
4696  *
4697  * @post current FSYNC handle is discarded and a new connection to the
4698  *       fileserver SYNC service is established
4699  *
4700  * @see VChildProcReconnectFS
4701  * @see VConnectFS_r
4702  * @see VDisconnectFS_r
4703  *
4704  * @internal volume package internal use only.
4705  */
4706 int
4707 VChildProcReconnectFS_r(void)
4708 {
4709     return FSYNC_clientChildProcReconnect();
4710 }
4711
4712 /**
4713  * connect to the fileserver SYNC service from a child process following a fork.
4714  *
4715  * @return operation status
4716  *    @retval 0 failure
4717  *    @retval 1 success
4718  *
4719  * @pre current FSYNC handle is shared with a parent process
4720  *
4721  * @post current FSYNC handle is discarded and a new connection to the
4722  *       fileserver SYNC service is established
4723  *
4724  * @see VChildProcReconnectFS_r
4725  * @see VConnectFS
4726  * @see VDisconnectFS
4727  */
4728 int
4729 VChildProcReconnectFS(void)
4730 {
4731     int ret;
4732     VOL_LOCK;
4733     ret = VChildProcReconnectFS_r();
4734     VOL_UNLOCK;
4735     return ret;
4736 }
4737 #endif /* FSSYNC_BUILD_CLIENT */
4738
4739
4740 /***************************************************/
4741 /* volume bitmap routines                          */
4742 /***************************************************/
4743
4744 /*
4745  * For demand attach fs, flags parameter controls
4746  * locking behavior.  If (flags & VOL_ALLOC_BITMAP_WAIT)
4747  * is set, then this function will create a reservation
4748  * and block on any other exclusive operations.  Otherwise,
4749  * this function assumes the caller already has exclusive
4750  * access to vp, and we just change the volume state.
4751  */
4752 VnodeId
4753 VAllocBitmapEntry_r(Error * ec, Volume * vp, 
4754                     struct vnodeIndex *index, int flags)
4755 {
4756     VnodeId ret;
4757     register byte *bp, *ep;
4758 #ifdef AFS_DEMAND_ATTACH_FS
4759     VolState state_save;
4760 #endif /* AFS_DEMAND_ATTACH_FS */
4761
4762     *ec = 0;
4763
4764     /* This test is probably redundant */
4765     if (!VolumeWriteable(vp)) {
4766         *ec = (bit32) VREADONLY;
4767         return 0;
4768     }
4769
4770 #ifdef AFS_DEMAND_ATTACH_FS
4771     if (flags & VOL_ALLOC_BITMAP_WAIT) {
4772         VCreateReservation_r(vp);
4773         VWaitExclusiveState_r(vp);
4774     }
4775     state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
4776 #endif /* AFS_DEMAND_ATTACH_FS */
4777
4778 #ifdef BITMAP_LATER
4779     if ((programType == fileServer) && !index->bitmap) {
4780         int i;
4781 #ifndef AFS_DEMAND_ATTACH_FS
4782         /* demand attach fs uses the volume state to avoid races.
4783          * specialStatus field is not used at all */
4784         int wasVBUSY = 0;
4785         if (vp->specialStatus == VBUSY) {
4786             if (vp->goingOffline) {     /* vos dump waiting for the volume to
4787                                          * go offline. We probably come here
4788                                          * from AddNewReadableResidency */
4789                 wasVBUSY = 1;
4790             } else {
4791                 while (vp->specialStatus == VBUSY) {
4792 #ifdef AFS_PTHREAD_ENV
4793                     VOL_UNLOCK;
4794                     sleep(2);
4795                     VOL_LOCK;
4796 #else /* !AFS_PTHREAD_ENV */
4797                     IOMGR_Sleep(2);
4798 #endif /* !AFS_PTHREAD_ENV */
4799                 }
4800             }
4801         }
4802 #endif /* !AFS_DEMAND_ATTACH_FS */
4803
4804         if (!index->bitmap) {
4805 #ifndef AFS_DEMAND_ATTACH_FS
4806             vp->specialStatus = VBUSY;  /* Stop anyone else from using it. */
4807 #endif /* AFS_DEMAND_ATTACH_FS */
4808             for (i = 0; i < nVNODECLASSES; i++) {
4809                 VGetBitmap_r(ec, vp, i);
4810                 if (*ec) {
4811 #ifdef AFS_DEMAND_ATTACH_FS
4812                     VRequestSalvage_r(ec, vp, SALVSYNC_ERROR, VOL_SALVAGE_INVALIDATE_HEADER);
4813 #else /* AFS_DEMAND_ATTACH_FS */
4814                     DeleteVolumeFromHashTable(vp);
4815                     vp->shuttingDown = 1;       /* Let who has it free it. */
4816                     vp->specialStatus = 0;
4817 #endif /* AFS_DEMAND_ATTACH_FS */
4818                     ret = NULL;
4819                     goto done;
4820                 }
4821             }
4822 #ifndef AFS_DEMAND_ATTACH_FS
4823             if (!wasVBUSY)
4824                 vp->specialStatus = 0;  /* Allow others to have access. */
4825 #endif /* AFS_DEMAND_ATTACH_FS */
4826         }
4827     }
4828 #endif /* BITMAP_LATER */
4829
4830 #ifdef AFS_DEMAND_ATTACH_FS
4831     VOL_UNLOCK;
4832 #endif /* AFS_DEMAND_ATTACH_FS */
4833     bp = index->bitmap + index->bitmapOffset;
4834     ep = index->bitmap + index->bitmapSize;
4835     while (bp < ep) {
4836         if ((*(bit32 *) bp) != (bit32) 0xffffffff) {
4837             int o;
4838             index->bitmapOffset = (afs_uint32) (bp - index->bitmap);
4839             while (*bp == 0xff)
4840                 bp++;
4841             o = ffs(~*bp) - 1;  /* ffs is documented in BSTRING(3) */
4842             *bp |= (1 << o);
4843             ret = (VnodeId) ((bp - index->bitmap) * 8 + o);
4844 #ifdef AFS_DEMAND_ATTACH_FS
4845             VOL_LOCK;
4846 #endif /* AFS_DEMAND_ATTACH_FS */
4847             goto done;
4848         }
4849         bp += sizeof(bit32) /* i.e. 4 */ ;
4850     }
4851     /* No bit map entry--must grow bitmap */
4852     bp = (byte *)
4853         realloc(index->bitmap, index->bitmapSize + VOLUME_BITMAP_GROWSIZE);
4854     assert(bp != NULL);
4855     index->bitmap = bp;
4856     bp += index->bitmapSize;
4857     memset(bp, 0, VOLUME_BITMAP_GROWSIZE);
4858     index->bitmapOffset = index->bitmapSize;
4859     index->bitmapSize += VOLUME_BITMAP_GROWSIZE;
4860     *bp = 1;
4861     ret = index->bitmapOffset * 8;
4862 #ifdef AFS_DEMAND_ATTACH_FS
4863     VOL_LOCK;
4864 #endif /* AFS_DEMAND_ATTACH_FS */
4865
4866  done:
4867 #ifdef AFS_DEMAND_ATTACH_FS
4868     VChangeState_r(vp, state_save);
4869     if (flags & VOL_ALLOC_BITMAP_WAIT) {
4870         VCancelReservation_r(vp);
4871     }
4872 #endif /* AFS_DEMAND_ATTACH_FS */
4873     return ret;
4874 }
4875
4876 VnodeId
4877 VAllocBitmapEntry(Error * ec, Volume * vp, register struct vnodeIndex * index)
4878 {
4879     VnodeId retVal;
4880     VOL_LOCK;
4881     retVal = VAllocBitmapEntry_r(ec, vp, index, VOL_ALLOC_BITMAP_WAIT);
4882     VOL_UNLOCK;
4883     return retVal;
4884 }
4885
4886 void
4887 VFreeBitMapEntry_r(Error * ec, register struct vnodeIndex *index,
4888                    unsigned bitNumber)
4889 {
4890     unsigned int offset;
4891
4892     *ec = 0;
4893 #ifdef BITMAP_LATER
4894     if (!index->bitmap)
4895         return;
4896 #endif /* BITMAP_LATER */
4897     offset = bitNumber >> 3;
4898     if (offset >= index->bitmapSize) {
4899         *ec = VNOVNODE;
4900         return;
4901     }
4902     if (offset < index->bitmapOffset)
4903         index->bitmapOffset = offset & ~3;      /* Truncate to nearest bit32 */
4904     *(index->bitmap + offset) &= ~(1 << (bitNumber & 0x7));
4905 }
4906
4907 void
4908 VFreeBitMapEntry(Error * ec, register struct vnodeIndex *index,
4909                  unsigned bitNumber)
4910 {
4911     VOL_LOCK;
4912     VFreeBitMapEntry_r(ec, index, bitNumber);
4913     VOL_UNLOCK;
4914 }
4915
4916 /* this function will drop the glock internally.
4917  * for old pthread fileservers, this is safe thanks to vbusy.
4918  *
4919  * for demand attach fs, caller must have already called
4920  * VCreateReservation_r and VWaitExclusiveState_r */
4921 static void
4922 VGetBitmap_r(Error * ec, Volume * vp, VnodeClass class)
4923 {
4924     StreamHandle_t *file;
4925     int nVnodes;
4926     int size;
4927     struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
4928     struct vnodeIndex *vip = &vp->vnodeIndex[class];
4929     struct VnodeDiskObject *vnode;
4930     unsigned int unique = 0;
4931     FdHandle_t *fdP;
4932 #ifdef BITMAP_LATER
4933     byte *BitMap = 0;
4934 #endif /* BITMAP_LATER */
4935 #ifdef AFS_DEMAND_ATTACH_FS
4936     VolState state_save;
4937 #endif /* AFS_DEMAND_ATTACH_FS */
4938
4939     *ec = 0;
4940
4941 #ifdef AFS_DEMAND_ATTACH_FS
4942     state_save = VChangeState_r(vp, VOL_STATE_GET_BITMAP);
4943 #endif /* AFS_DEMAND_ATTACH_FS */
4944     VOL_UNLOCK;
4945
4946     fdP = IH_OPEN(vip->handle);
4947     assert(fdP != NULL);
4948     file = FDH_FDOPEN(fdP, "r");
4949     assert(file != NULL);
4950     vnode = (VnodeDiskObject *) malloc(vcp->diskSize);
4951     assert(vnode != NULL);
4952     size = OS_SIZE(fdP->fd_fd);
4953     assert(size != -1);
4954     nVnodes = (size <= vcp->diskSize ? 0 : size - vcp->diskSize)
4955         >> vcp->logSize;
4956     vip->bitmapSize = ((nVnodes / 8) + 10) / 4 * 4;     /* The 10 is a little extra so
4957                                                          * a few files can be created in this volume,
4958                                                          * the whole thing is rounded up to nearest 4
4959                                                          * bytes, because the bit map allocator likes
4960                                                          * it that way */
4961 #ifdef BITMAP_LATER
4962     BitMap = (byte *) calloc(1, vip->bitmapSize);
4963     assert(BitMap != NULL);
4964 #else /* BITMAP_LATER */
4965     vip->bitmap = (byte *) calloc(1, vip->bitmapSize);
4966     assert(vip->bitmap != NULL);
4967     vip->bitmapOffset = 0;
4968 #endif /* BITMAP_LATER */
4969     if (STREAM_SEEK(file, vcp->diskSize, 0) != -1) {
4970         int bitNumber = 0;
4971         for (bitNumber = 0; bitNumber < nVnodes + 100; bitNumber++) {
4972             if (STREAM_READ(vnode, vcp->diskSize, 1, file) != 1)
4973                 break;
4974             if (vnode->type != vNull) {
4975                 if (vnode->vnodeMagic != vcp->magic) {
4976                     Log("GetBitmap: addled vnode index in volume %s; volume needs salvage\n", V_name(vp));
4977                     *ec = VSALVAGE;
4978                     break;
4979                 }
4980 #ifdef BITMAP_LATER
4981                 *(BitMap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
4982 #else /* BITMAP_LATER */
4983                 *(vip->bitmap + (bitNumber >> 3)) |= (1 << (bitNumber & 0x7));
4984 #endif /* BITMAP_LATER */
4985                 if (unique <= vnode->uniquifier)
4986                     unique = vnode->uniquifier + 1;
4987             }
4988 #ifndef AFS_PTHREAD_ENV
4989             if ((bitNumber & 0x00ff) == 0x0ff) {        /* every 256 iterations */
4990                 IOMGR_Poll();
4991             }
4992 #endif /* !AFS_PTHREAD_ENV */
4993         }
4994     }
4995     if (vp->nextVnodeUnique < unique) {
4996         Log("GetBitmap: bad volume uniquifier for volume %s; volume needs salvage\n", V_name(vp));
4997         *ec = VSALVAGE;
4998     }
4999     /* Paranoia, partly justified--I think fclose after fdopen
5000      * doesn't seem to close fd.  In any event, the documentation
5001      * doesn't specify, so it's safer to close it twice.
5002      */
5003     STREAM_CLOSE(file);
5004     FDH_CLOSE(fdP);
5005     free(vnode);
5006
5007     VOL_LOCK;
5008 #ifdef BITMAP_LATER
5009     /* There may have been a racing condition with some other thread, both
5010      * creating the bitmaps for this volume. If the other thread was faster
5011      * the pointer to bitmap should already be filled and we can free ours.
5012      */
5013     if (vip->bitmap == NULL) {
5014         vip->bitmap = BitMap;
5015         vip->bitmapOffset = 0;
5016     } else
5017         free((byte *) BitMap);
5018 #endif /* BITMAP_LATER */
5019 #ifdef AFS_DEMAND_ATTACH_FS
5020     VChangeState_r(vp, state_save);
5021 #endif /* AFS_DEMAND_ATTACH_FS */
5022 }
5023
5024
5025 /***************************************************/
5026 /* Volume Path and Volume Number utility routines  */
5027 /***************************************************/
5028
5029 /**
5030  * find the first occurrence of a volume header file and return the path.
5031  *
5032  * @param[out] ec          outbound error code
5033  * @param[in]  volumeId    volume id to find
5034  * @param[out] partitionp  pointer to disk partition path string
5035  * @param[out] namep       pointer to volume header file name string
5036  *
5037  * @post path to first occurrence of volume header is returned in partitionp
5038  *       and namep, or ec is set accordingly.
5039  *
5040  * @warning this function is NOT re-entrant -- partitionp and namep point to
5041  *          static data segments
5042  *
5043  * @note if a volume utility inadvertently leaves behind a stale volume header
5044  *       on a vice partition, it is possible for callers to get the wrong one,
5045  *       depending on the order of the disk partition linked list.
5046  *
5047  */
5048 void
5049 VGetVolumePath(Error * ec, VolId volumeId, char **partitionp, char **namep)
5050 {
5051     static char partition[VMAXPATHLEN], name[VMAXPATHLEN];
5052     char path[VMAXPATHLEN];
5053     int found = 0;
5054     struct DiskPartition64 *dp;
5055
5056     *ec = 0;
5057     name[0] = '/';
5058     (void)afs_snprintf(&name[1], (sizeof name) - 1, VFORMAT, afs_printable_uint32_lu(volumeId));
5059     for (dp = DiskPartitionList; dp; dp = dp->next) {
5060         struct afs_stat status;
5061         strcpy(path, VPartitionPath(dp));
5062         strcat(path, name);
5063         if (afs_stat(path, &status) == 0) {
5064             strcpy(partition, dp->name);
5065             found = 1;
5066             break;
5067         }
5068     }
5069     if (!found) {
5070         *ec = VNOVOL;
5071         *partitionp = *namep = NULL;
5072     } else {
5073         *partitionp = partition;
5074         *namep = name;
5075     }
5076 }
5077
5078 /**
5079  * extract a volume number from a volume header filename string.
5080  *
5081  * @param[in] name  volume header filename string
5082  *
5083  * @return volume number
5084  *
5085  * @note the string must be of the form VFORMAT.  the only permissible
5086  *       deviation is a leading '/' character.
5087  *
5088  * @see VFORMAT
5089  */
5090 int
5091 VolumeNumber(char *name)
5092 {
5093     if (*name == '/')
5094         name++;
5095     return atoi(name + 1);
5096 }
5097
5098 /**
5099  * compute the volume header filename.
5100  *
5101  * @param[in] volumeId
5102  *
5103  * @return volume header filename
5104  *
5105  * @post volume header filename string is constructed
5106  *
5107  * @warning this function is NOT re-entrant -- the returned string is
5108  *          stored in a static char array.  see VolumeExternalName_r
5109  *          for a re-entrant equivalent.
5110  *
5111  * @see VolumeExternalName_r
5112  *
5113  * @deprecated due to the above re-entrancy warning, this interface should
5114  *             be considered deprecated.  Please use VolumeExternalName_r
5115  *             in its stead.
5116  */
5117 char *
5118 VolumeExternalName(VolumeId volumeId)
5119 {
5120     static char name[VMAXPATHLEN];
5121     (void)afs_snprintf(name, sizeof name, VFORMAT, afs_printable_uint32_lu(volumeId));
5122     return name;
5123 }
5124
5125 /**
5126  * compute the volume header filename.
5127  *
5128  * @param[in]     volumeId
5129  * @param[inout]  name       array in which to store filename
5130  * @param[in]     len        length of name array
5131  *
5132  * @return result code from afs_snprintf
5133  *
5134  * @see VolumeExternalName
5135  * @see afs_snprintf
5136  *
5137  * @note re-entrant equivalent of VolumeExternalName
5138  */
5139 int
5140 VolumeExternalName_r(VolumeId volumeId, char * name, size_t len)
5141 {
5142     return afs_snprintf(name, len, VFORMAT, afs_printable_uint32_lu(volumeId));
5143 }
5144
5145
5146 /***************************************************/
5147 /* Volume Usage Statistics routines                */
5148 /***************************************************/
5149
5150 #if OPENAFS_VOL_STATS
5151 #define OneDay  (86400)         /* 24 hours' worth of seconds */
5152 #else
5153 #define OneDay  (24*60*60)      /* 24 hours */
5154 #endif /* OPENAFS_VOL_STATS */
5155
5156 static time_t
5157 Midnight(time_t t) {
5158     struct tm local, *l;
5159     time_t midnight;
5160
5161 #if defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
5162     l = localtime_r(&t, &local);
5163 #else
5164     l = localtime(&t);
5165 #endif
5166
5167     if (l != NULL) {
5168         /* the following is strictly speaking problematic on the
5169            switching day to daylight saving time, after the switch,
5170            as tm_isdst does not match.  Similarly, on the looong day when
5171            switching back the OneDay check will not do what naively expected!
5172            The effects are minor, though, and more a matter of interpreting
5173            the numbers. */
5174 #ifndef AFS_PTHREAD_ENV
5175         local = *l;
5176 #endif
5177         local.tm_hour = local.tm_min=local.tm_sec = 0;
5178         midnight = mktime(&local);
5179         if (midnight != (time_t) -1) return(midnight);
5180     }
5181     return( (t/OneDay)*OneDay );
5182
5183 }
5184
5185 /*------------------------------------------------------------------------
5186  * [export] VAdjustVolumeStatistics
5187  *
5188  * Description:
5189  *      If we've passed midnight, we need to update all the day use
5190  *      statistics as well as zeroing the detailed volume statistics
5191  *      (if we are implementing them).
5192  *
5193  * Arguments:
5194  *      vp : Pointer to the volume structure describing the lucky
5195  *              volume being considered for update.
5196  *
5197  * Returns:
5198  *      0 (always!)
5199  *
5200  * Environment:
5201  *      Nothing interesting.
5202  *
5203  * Side Effects:
5204  *      As described.
5205  *------------------------------------------------------------------------*/
5206
5207 int
5208 VAdjustVolumeStatistics_r(register Volume * vp)
5209 {
5210     unsigned int now = FT_ApproxTime();
5211
5212     if (now - V_dayUseDate(vp) > OneDay) {
5213         register int ndays, i;
5214
5215         ndays = (now - V_dayUseDate(vp)) / OneDay;
5216         for (i = 6; i > ndays - 1; i--)
5217             V_weekUse(vp)[i] = V_weekUse(vp)[i - ndays];
5218         for (i = 0; i < ndays - 1 && i < 7; i++)
5219             V_weekUse(vp)[i] = 0;
5220         if (ndays <= 7)
5221             V_weekUse(vp)[ndays - 1] = V_dayUse(vp);
5222         V_dayUse(vp) = 0;
5223         V_dayUseDate(vp) = Midnight(now);
5224
5225 #if OPENAFS_VOL_STATS
5226         /*
5227          * All we need to do is bzero the entire VOL_STATS_BYTES of
5228          * the detailed volume statistics area.
5229          */
5230         memset((V_stat_area(vp)), 0, VOL_STATS_BYTES);
5231 #endif /* OPENAFS_VOL_STATS */
5232     }
5233
5234     /*It's been more than a day of collection */
5235     /*
5236      * Always return happily.
5237      */
5238     return (0);
5239 }                               /*VAdjustVolumeStatistics */
5240
5241 int
5242 VAdjustVolumeStatistics(register Volume * vp)
5243 {
5244     int retVal;
5245     VOL_LOCK;
5246     retVal = VAdjustVolumeStatistics_r(vp);
5247     VOL_UNLOCK;
5248     return retVal;
5249 }
5250
5251 void
5252 VBumpVolumeUsage_r(register Volume * vp)
5253 {
5254     unsigned int now = FT_ApproxTime();
5255     V_accessDate(vp) = now;
5256     if (now - V_dayUseDate(vp) > OneDay)
5257         VAdjustVolumeStatistics_r(vp);
5258     /*
5259      * Save the volume header image to disk after every 128 bumps to dayUse.
5260      */
5261     if ((V_dayUse(vp)++ & 127) == 0) {
5262         Error error;
5263         VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);
5264     }
5265 }
5266
5267 void
5268 VBumpVolumeUsage(register Volume * vp)
5269 {
5270     VOL_LOCK;
5271     VBumpVolumeUsage_r(vp);
5272     VOL_UNLOCK;
5273 }
5274
5275 void
5276 VSetDiskUsage_r(void)
5277 {
5278 #ifndef AFS_DEMAND_ATTACH_FS
5279     static int FifteenMinuteCounter = 0;
5280 #endif
5281
5282     while (VInit < 2) {
5283         /* NOTE: Don't attempt to access the partitions list until the
5284          * initialization level indicates that all volumes are attached,
5285          * which implies that all partitions are initialized. */
5286 #ifdef AFS_PTHREAD_ENV
5287         sleep(10);
5288 #else /* AFS_PTHREAD_ENV */
5289         IOMGR_Sleep(10);
5290 #endif /* AFS_PTHREAD_ENV */
5291     }
5292
5293     VResetDiskUsage_r();
5294
5295 #ifndef AFS_DEMAND_ATTACH_FS
5296     if (++FifteenMinuteCounter == 3) {
5297         FifteenMinuteCounter = 0;
5298         VScanUpdateList();
5299     }
5300 #endif /* !AFS_DEMAND_ATTACH_FS */
5301 }
5302
5303 void
5304 VSetDiskUsage(void)
5305 {
5306     VOL_LOCK;
5307     VSetDiskUsage_r();
5308     VOL_UNLOCK;
5309 }
5310
5311
5312 /***************************************************/
5313 /* Volume Update List routines                     */
5314 /***************************************************/
5315
5316 /* The number of minutes that a volume hasn't been updated before the
5317  * "Dont salvage" flag in the volume header will be turned on */
5318 #define SALVAGE_INTERVAL        (10*60)
5319
5320 /*
5321  * demand attach fs
5322  *
5323  * volume update list functionality has been moved into the VLRU
5324  * the DONT_SALVAGE flag is now set during VLRU demotion
5325  */
5326
5327 #ifndef AFS_DEMAND_ATTACH_FS
5328 static VolumeId *UpdateList = NULL;     /* Pointer to array of Volume ID's */
5329 static int nUpdatedVolumes = 0;         /* Updated with entry in UpdateList, salvage after crash flag on */
5330 static int updateSize = 0;              /* number of entries possible */
5331 #define UPDATE_LIST_SIZE 128            /* initial size increment (must be a power of 2!) */
5332 #endif /* !AFS_DEMAND_ATTACH_FS */
5333
5334 void
5335 VAddToVolumeUpdateList_r(Error * ec, Volume * vp)
5336 {
5337     *ec = 0;
5338     vp->updateTime = FT_ApproxTime();
5339     if (V_dontSalvage(vp) == 0)
5340         return;
5341     V_dontSalvage(vp) = 0;
5342     VSyncVolume_r(ec, vp, 0);
5343 #ifdef AFS_DEMAND_ATTACH_FS
5344     V_attachFlags(vp) &= ~(VOL_HDR_DONTSALV);
5345 #else /* !AFS_DEMAND_ATTACH_FS */
5346     if (*ec)
5347         return;
5348     if (UpdateList == NULL) {
5349         updateSize = UPDATE_LIST_SIZE;
5350         UpdateList = (VolumeId *) malloc(sizeof(VolumeId) * updateSize);
5351     } else {
5352         if (nUpdatedVolumes == updateSize) {
5353             updateSize <<= 1;
5354             if (updateSize > 524288) {
5355                 Log("warning: there is likely a bug in the volume update scanner\n");
5356                 return;
5357             }
5358             UpdateList =
5359                 (VolumeId *) realloc(UpdateList,
5360                                      sizeof(VolumeId) * updateSize);
5361         }
5362     }
5363     assert(UpdateList != NULL);
5364     UpdateList[nUpdatedVolumes++] = V_id(vp);
5365 #endif /* !AFS_DEMAND_ATTACH_FS */
5366 }
5367
5368 #ifndef AFS_DEMAND_ATTACH_FS
5369 static void
5370 VScanUpdateList(void)
5371 {
5372     register int i, gap;
5373     register Volume *vp;
5374     Error error;
5375     afs_uint32 now = FT_ApproxTime();
5376     /* Be careful with this code, since it works with interleaved calls to AddToVolumeUpdateList */
5377     for (i = gap = 0; i < nUpdatedVolumes; i++) {
5378         if (gap)
5379             UpdateList[i - gap] = UpdateList[i];
5380
5381         /* XXX this routine needlessly messes up the Volume LRU by
5382          * breaking the LRU temporal-locality assumptions.....
5383          * we should use a special volume header allocator here */
5384         vp = VGetVolume_r(&error, UpdateList[i - gap] = UpdateList[i]);
5385         if (error) {
5386             gap++;
5387         } else if (vp->nUsers == 1 && now - vp->updateTime > SALVAGE_INTERVAL) {
5388             V_dontSalvage(vp) = DONT_SALVAGE;
5389             VUpdateVolume_r(&error, vp, 0);     /* No need to fsync--not critical */
5390             gap++;
5391         }
5392
5393         if (vp) {
5394             VPutVolume_r(vp);
5395         }
5396
5397 #ifndef AFS_PTHREAD_ENV
5398         IOMGR_Poll();
5399 #endif /* !AFS_PTHREAD_ENV */
5400     }
5401     nUpdatedVolumes -= gap;
5402 }
5403 #endif /* !AFS_DEMAND_ATTACH_FS */
5404
5405
5406 /***************************************************/
5407 /* Volume LRU routines                             */
5408 /***************************************************/
5409
5410 /* demand attach fs
5411  * volume LRU
5412  *
5413  * with demand attach fs, we attempt to soft detach(1)
5414  * volumes which have not been accessed in a long time
5415  * in order to speed up fileserver shutdown
5416  *
5417  * (1) by soft detach we mean a process very similar
5418  *     to VOffline, except the final state of the 
5419  *     Volume will be VOL_STATE_PREATTACHED, instead
5420  *     of the usual VOL_STATE_UNATTACHED
5421  */
5422 #ifdef AFS_DEMAND_ATTACH_FS
5423
5424 /* implementation is reminiscent of a generational GC
5425  *
5426  * queue 0 is newly attached volumes. this queue is
5427  * sorted by attach timestamp
5428  *
5429  * queue 1 is volumes that have been around a bit
5430  * longer than queue 0. this queue is sorted by
5431  * attach timestamp
5432  *
5433  * queue 2 is volumes tha have been around the longest.
5434  * this queue is unsorted
5435  *
5436  * queue 3 is volumes that have been marked as
5437  * candidates for soft detachment. this queue is
5438  * unsorted
5439  */
5440 #define VLRU_GENERATIONS  3   /**< number of generations in VLRU */
5441 #define VLRU_QUEUES       5   /**< total number of VLRU queues */
5442
5443 /**
5444  * definition of a VLRU queue.
5445  */
5446 struct VLRU_q {
5447     volatile struct rx_queue q;
5448     volatile int len;
5449     volatile int busy;
5450     pthread_cond_t cv;
5451 };
5452
5453 /**
5454  * main VLRU data structure.
5455  */
5456 struct VLRU {
5457     struct VLRU_q q[VLRU_QUEUES];   /**< VLRU queues */
5458
5459     /* VLRU config */
5460     /** time interval (in seconds) between promotion passes for
5461      *  each young generation queue. */
5462     afs_uint32 promotion_interval[VLRU_GENERATIONS-1];
5463
5464     /** time interval (in seconds) between soft detach candidate
5465      *  scans for each generation queue.
5466      *
5467      *  scan_interval[VLRU_QUEUE_CANDIDATE] defines how frequently
5468      *  we perform a soft detach pass. */
5469     afs_uint32 scan_interval[VLRU_GENERATIONS+1];
5470
5471     /* scheduler state */
5472     int next_idx;                                       /**< next queue to receive attention */
5473     afs_uint32 last_promotion[VLRU_GENERATIONS-1];      /**< timestamp of last promotion scan */
5474     afs_uint32 last_scan[VLRU_GENERATIONS+1];           /**< timestamp of last detach scan */
5475
5476     int scanner_state;                                  /**< state of scanner thread */
5477     pthread_cond_t cv;                                  /**< state transition CV */
5478 };
5479
5480 /** global VLRU state */
5481 static struct VLRU volume_LRU;
5482
5483 /**
5484  * defined states for VLRU scanner thread.
5485  */
5486 typedef enum {
5487     VLRU_SCANNER_STATE_OFFLINE        = 0,    /**< vlru scanner thread is offline */
5488     VLRU_SCANNER_STATE_ONLINE         = 1,    /**< vlru scanner thread is online */
5489     VLRU_SCANNER_STATE_SHUTTING_DOWN  = 2,    /**< vlru scanner thread is shutting down */
5490     VLRU_SCANNER_STATE_PAUSING        = 3,    /**< vlru scanner thread is getting ready to pause */
5491     VLRU_SCANNER_STATE_PAUSED         = 4     /**< vlru scanner thread is paused */
5492 } vlru_thread_state_t;
5493
5494 /* vlru disk data header stuff */
5495 #define VLRU_DISK_MAGIC      0x7a8b9cad        /**< vlru disk entry magic number */
5496 #define VLRU_DISK_VERSION    1                 /**< vlru disk entry version number */
5497
5498 /** vlru default expiration time (for eventual fs state serialization of vlru data) */
5499 #define VLRU_DUMP_EXPIRATION_TIME   (60*60*24*7)  /* expire vlru data after 1 week */
5500
5501
5502 /** minimum volume inactivity (in seconds) before a volume becomes eligible for
5503  *  soft detachment. */
5504 static afs_uint32 VLRU_offline_thresh = VLRU_DEFAULT_OFFLINE_THRESH;
5505
5506 /** time interval (in seconds) between VLRU scanner thread soft detach passes. */
5507 static afs_uint32 VLRU_offline_interval = VLRU_DEFAULT_OFFLINE_INTERVAL;
5508
5509 /** maximum number of volumes to soft detach in a VLRU soft detach pass. */
5510 static afs_uint32 VLRU_offline_max = VLRU_DEFAULT_OFFLINE_MAX;
5511
5512 /** VLRU control flag.  non-zero value implies VLRU subsystem is activated. */
5513 static afs_uint32 VLRU_enabled = 1;
5514
5515 /* queue synchronization routines */
5516 static void VLRU_BeginExclusive_r(struct VLRU_q * q);
5517 static void VLRU_EndExclusive_r(struct VLRU_q * q);
5518 static void VLRU_Wait_r(struct VLRU_q * q);
5519
5520 /**
5521  * set VLRU subsystem tunable parameters.
5522  *
5523  * @param[in] option  tunable option to modify
5524  * @param[in] val     new value for tunable parameter
5525  *
5526  * @pre @c VInitVolumePackage2 has not yet been called.
5527  *
5528  * @post tunable parameter is modified
5529  *
5530  * @note DAFS only
5531  *
5532  * @note valid option parameters are:
5533  *    @arg @c VLRU_SET_THRESH 
5534  *         set the period of inactivity after which
5535  *         volumes are eligible for soft detachment
5536  *    @arg @c VLRU_SET_INTERVAL 
5537  *         set the time interval between calls
5538  *         to the volume LRU "garbage collector"
5539  *    @arg @c VLRU_SET_MAX 
5540  *         set the max number of volumes to deallocate
5541  *         in one GC pass
5542  */
5543 void
5544 VLRU_SetOptions(int option, afs_uint32 val)
5545 {
5546     if (option == VLRU_SET_THRESH) {
5547         VLRU_offline_thresh = val;
5548     } else if (option == VLRU_SET_INTERVAL) {
5549         VLRU_offline_interval = val;
5550     } else if (option == VLRU_SET_MAX) {
5551         VLRU_offline_max = val;
5552     } else if (option == VLRU_SET_ENABLED) {
5553         VLRU_enabled = val;
5554     }
5555     VLRU_ComputeConstants();
5556 }
5557
5558 /**
5559  * compute VLRU internal timing parameters.
5560  *
5561  * @post VLRU scanner thread internal timing parameters are computed
5562  *
5563  * @note computes internal timing parameters based upon user-modifiable 
5564  *       tunable parameters.
5565  *
5566  * @note DAFS only
5567  *
5568  * @internal volume package internal use only.
5569  */
5570 static void
5571 VLRU_ComputeConstants(void)
5572 {
5573     afs_uint32 factor = VLRU_offline_thresh / VLRU_offline_interval;
5574
5575     /* compute the candidate scan interval */
5576     volume_LRU.scan_interval[VLRU_QUEUE_CANDIDATE] = VLRU_offline_interval;
5577
5578     /* compute the promotion intervals */
5579     volume_LRU.promotion_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh * 2;
5580     volume_LRU.promotion_interval[VLRU_QUEUE_MID] = VLRU_offline_thresh * 4;
5581
5582     if (factor > 16) {
5583         /* compute the gen 0 scan interval */
5584         volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_thresh / 8;
5585     } else {
5586         /* compute the gen 0 scan interval */
5587         volume_LRU.scan_interval[VLRU_QUEUE_NEW] = VLRU_offline_interval * 2;
5588     }
5589 }
5590
5591 /**
5592  * initialize VLRU subsystem.
5593  *
5594  * @pre this function has not yet been called
5595  *
5596  * @post VLRU subsystem is initialized and VLRU scanner thread is starting
5597  *
5598  * @note DAFS only
5599  *
5600  * @internal volume package internal use only.
5601  */
5602 static void
5603 VInitVLRU(void)
5604 {
5605     pthread_t tid;
5606     pthread_attr_t attrs;
5607     int i;
5608
5609     if (!VLRU_enabled) {
5610         Log("VLRU: disabled\n");
5611         return;
5612     }
5613
5614     /* initialize each of the VLRU queues */
5615     for (i = 0; i < VLRU_QUEUES; i++) {
5616         queue_Init(&volume_LRU.q[i]);
5617         volume_LRU.q[i].len = 0;
5618         volume_LRU.q[i].busy = 0;
5619         assert(pthread_cond_init(&volume_LRU.q[i].cv, NULL) == 0);
5620     }
5621
5622     /* setup the timing constants */
5623     VLRU_ComputeConstants();
5624
5625     /* XXX put inside LogLevel check? */
5626     Log("VLRU: starting scanner with the following configuration parameters:\n");
5627     Log("VLRU:  offlining volumes after minimum of %d seconds of inactivity\n", VLRU_offline_thresh);
5628     Log("VLRU:  running VLRU soft detach pass every %d seconds\n", VLRU_offline_interval);
5629     Log("VLRU:  taking up to %d volumes offline per pass\n", VLRU_offline_max);
5630     Log("VLRU:  scanning generation 0 for inactive volumes every %d seconds\n", volume_LRU.scan_interval[0]);
5631     Log("VLRU:  scanning for promotion/demotion between generations 0 and 1 every %d seconds\n", volume_LRU.promotion_interval[0]);
5632     Log("VLRU:  scanning for promotion/demotion between generations 1 and 2 every %d seconds\n", volume_LRU.promotion_interval[1]);
5633
5634     /* start up the VLRU scanner */
5635     volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
5636     if (programType == fileServer) {
5637         assert(pthread_cond_init(&volume_LRU.cv, NULL) == 0);
5638         assert(pthread_attr_init(&attrs) == 0);
5639         assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
5640         assert(pthread_create(&tid, &attrs, &VLRU_ScannerThread, NULL) == 0);
5641     }
5642 }
5643
5644 /**
5645  * initialize the VLRU-related fields of a newly allocated volume object.
5646  *
5647  * @param[in] vp  pointer to volume object
5648  *
5649  * @pre
5650  *    @arg @c VOL_LOCK is held.
5651  *    @arg volume object is not on a VLRU queue.
5652  *
5653  * @post VLRU fields are initialized to indicate that volume object is not
5654  *       currently registered with the VLRU subsystem
5655  *
5656  * @note DAFS only
5657  *
5658  * @internal volume package interal use only.
5659  */
5660 static void
5661 VLRU_Init_Node_r(Volume * vp)
5662 {
5663     if (!VLRU_enabled)
5664         return;
5665
5666     assert(queue_IsNotOnQueue(&vp->vlru));
5667     vp->vlru.idx = VLRU_QUEUE_INVALID;
5668 }
5669
5670 /**
5671  * add a volume object to a VLRU queue.
5672  *
5673  * @param[in] vp  pointer to volume object
5674  *
5675  * @pre
5676  *    @arg @c VOL_LOCK is held.
5677  *    @arg caller MUST hold a lightweight ref on @p vp.
5678  *    @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
5679  *
5680  * @post the volume object is added to the appropriate VLRU queue
5681  *
5682  * @note if @c vp->vlru.idx contains the index of a valid VLRU queue,
5683  *       then the volume is added to that queue.  Otherwise, the value
5684  *       @c VLRU_QUEUE_NEW is stored into @c vp->vlru.idx and the
5685  *       volume is added to the NEW generation queue.
5686  *
5687  * @note @c VOL_LOCK may be dropped internally
5688  *
5689  * @note Volume state is temporarily set to @c VOL_STATE_VLRU_ADD
5690  *       during the add operation, and is restored to the previous
5691  *       state prior to return.
5692  *
5693  * @note DAFS only
5694  *
5695  * @internal volume package internal use only.
5696  */
5697 static void
5698 VLRU_Add_r(Volume * vp)
5699 {
5700     int idx;
5701     VolState state_save;
5702
5703     if (!VLRU_enabled)
5704         return;
5705
5706     if (queue_IsOnQueue(&vp->vlru))
5707         return;
5708
5709     state_save = VChangeState_r(vp, VOL_STATE_VLRU_ADD);
5710
5711     idx = vp->vlru.idx;
5712     if ((idx < 0) || (idx >= VLRU_QUEUE_INVALID)) {
5713         idx = VLRU_QUEUE_NEW;
5714     }
5715
5716     VLRU_Wait_r(&volume_LRU.q[idx]);
5717
5718     /* repeat check since VLRU_Wait_r may have dropped
5719      * the glock */
5720     if (queue_IsNotOnQueue(&vp->vlru)) {
5721         vp->vlru.idx = idx;
5722         queue_Prepend(&volume_LRU.q[idx], &vp->vlru);
5723         volume_LRU.q[idx].len++;
5724         V_attachFlags(vp) |= VOL_ON_VLRU;
5725         vp->stats.last_promote = FT_ApproxTime();
5726     }
5727
5728     VChangeState_r(vp, state_save);
5729 }
5730
5731 /**
5732  * delete a volume object from a VLRU queue.
5733  *
5734  * @param[in] vp  pointer to volume object
5735  *
5736  * @pre
5737  *    @arg @c VOL_LOCK is held.
5738  *    @arg caller MUST hold a lightweight ref on @p vp.
5739  *    @arg caller MUST NOT hold exclusive ownership of the VLRU queue.
5740  *
5741  * @post volume object is removed from the VLRU queue
5742  *
5743  * @note @c VOL_LOCK may be dropped internally
5744  *
5745  * @note DAFS only
5746  *
5747  * @todo We should probably set volume state to something exlcusive 
5748  *       (as @c VLRU_Add_r does) prior to dropping @c VOL_LOCK.
5749  *
5750  * @internal volume package internal use only.
5751  */
5752 static void
5753 VLRU_Delete_r(Volume * vp)
5754 {
5755     int idx;
5756
5757     if (!VLRU_enabled)
5758         return;
5759
5760     if (queue_IsNotOnQueue(&vp->vlru))
5761         return;
5762
5763     /* handle races */
5764     do {
5765       idx = vp->vlru.idx;
5766       if (idx == VLRU_QUEUE_INVALID)
5767           return;
5768       VLRU_Wait_r(&volume_LRU.q[idx]);
5769     } while (idx != vp->vlru.idx);
5770
5771     /* now remove from the VLRU and update 
5772      * the appropriate counter */
5773     queue_Remove(&vp->vlru);
5774     volume_LRU.q[idx].len--;
5775     vp->vlru.idx = VLRU_QUEUE_INVALID;
5776     V_attachFlags(vp) &= ~(VOL_ON_VLRU);
5777 }
5778
5779 /**
5780  * tell the VLRU subsystem that a volume was just accessed.
5781  *
5782  * @param[in] vp  pointer to volume object
5783  *
5784  * @pre
5785  *    @arg @c VOL_LOCK is held
5786  *    @arg caller MUST hold a lightweight ref on @p vp
5787  *    @arg caller MUST NOT hold exclusive ownership of any VLRU queue
5788  *
5789  * @post volume VLRU access statistics are updated.  If the volume was on
5790  *       the VLRU soft detach candidate queue, it is moved to the NEW
5791  *       generation queue.
5792  *
5793  * @note @c VOL_LOCK may be dropped internally
5794  *
5795  * @note DAFS only
5796  *
5797  * @internal volume package internal use only.
5798  */
5799 static void
5800 VLRU_UpdateAccess_r(Volume * vp)
5801 {
5802     Volume * rvp = NULL;
5803
5804     if (!VLRU_enabled)
5805         return;
5806
5807     if (queue_IsNotOnQueue(&vp->vlru))
5808         return;
5809
5810     assert(V_attachFlags(vp) & VOL_ON_VLRU);
5811
5812     /* update the access timestamp */
5813     vp->stats.last_get = FT_ApproxTime();
5814
5815     /*
5816      * if the volume is on the soft detach candidate
5817      * list, we need to safely move it back to a
5818      * regular generation.  this has to be done
5819      * carefully so we don't race against the scanner
5820      * thread.
5821      */
5822
5823     /* if this volume is on the soft detach candidate queue,
5824      * then grab exclusive access to the necessary queues */
5825     if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
5826         rvp = vp;
5827         VCreateReservation_r(rvp);
5828
5829         VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
5830         VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
5831         VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5832         VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5833     }
5834
5835     /* make sure multiple threads don't race to update */
5836     if (vp->vlru.idx == VLRU_QUEUE_CANDIDATE) {
5837         VLRU_SwitchQueues(vp, VLRU_QUEUE_NEW, 1);
5838     }
5839
5840     if (rvp) {
5841       VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
5842       VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_NEW]);
5843       VCancelReservation_r(rvp);
5844     }
5845 }
5846
5847 /**
5848  * switch a volume between two VLRU queues.
5849  *
5850  * @param[in] vp       pointer to volume object
5851  * @param[in] new_idx  index of VLRU queue onto which the volume will be moved
5852  * @param[in] append   controls whether the volume will be appended or 
5853  *                     prepended to the queue.  A nonzero value means it will
5854  *                     be appended; zero means it will be prepended.
5855  *
5856  * @pre The new (and old, if applicable) queue(s) must either be owned 
5857  *      exclusively by the calling thread for asynchronous manipulation,
5858  *      or the queue(s) must be quiescent and VOL_LOCK must be held.
5859  *      Please see VLRU_BeginExclusive_r, VLRU_EndExclusive_r and VLRU_Wait_r
5860  *      for further details of the queue asynchronous processing mechanism.
5861  *
5862  * @post If the volume object was already on a VLRU queue, it is
5863  *       removed from the queue.  Depending on the value of the append
5864  *       parameter, the volume object is either appended or prepended
5865  *       to the VLRU queue referenced by the new_idx parameter.
5866  *
5867  * @note DAFS only
5868  *
5869  * @see VLRU_BeginExclusive_r
5870  * @see VLRU_EndExclusive_r
5871  * @see VLRU_Wait_r
5872  *
5873  * @internal volume package internal use only.
5874  */
5875 static void
5876 VLRU_SwitchQueues(Volume * vp, int new_idx, int append)
5877 {
5878     if (queue_IsNotOnQueue(&vp->vlru))
5879         return;
5880
5881     queue_Remove(&vp->vlru);
5882     volume_LRU.q[vp->vlru.idx].len--;
5883     
5884     /* put the volume back on the correct generational queue */
5885     if (append) {
5886         queue_Append(&volume_LRU.q[new_idx], &vp->vlru);
5887     } else {
5888         queue_Prepend(&volume_LRU.q[new_idx], &vp->vlru);
5889     }
5890
5891     volume_LRU.q[new_idx].len++;
5892     vp->vlru.idx = new_idx;
5893 }
5894
5895 /**
5896  * VLRU background thread.
5897  *
5898  * The VLRU Scanner Thread is responsible for periodically scanning through
5899  * each VLRU queue looking for volumes which should be moved to another
5900  * queue, or soft detached.
5901  *
5902  * @param[in] args  unused thread arguments parameter
5903  *
5904  * @return unused thread return value
5905  *    @retval NULL always
5906  *
5907  * @internal volume package internal use only.
5908  */
5909 static void *
5910 VLRU_ScannerThread(void * args)
5911 {
5912     afs_uint32 now, min_delay, delay;
5913     int i, min_idx, min_op, overdue, state;
5914
5915     /* set t=0 for promotion cycle to be 
5916      * fileserver startup */
5917     now = FT_ApproxTime();
5918     for (i=0; i < VLRU_GENERATIONS-1; i++) {
5919         volume_LRU.last_promotion[i] = now;
5920     }
5921
5922     /* don't start the scanner until VLRU_offline_thresh
5923      * plus a small delay for VInitVolumePackage2 to finish
5924      * has gone by */
5925
5926     sleep(VLRU_offline_thresh + 60);
5927
5928     /* set t=0 for scan cycle to be now */
5929     now = FT_ApproxTime();
5930     for (i=0; i < VLRU_GENERATIONS+1; i++) {
5931         volume_LRU.last_scan[i] = now;
5932     }
5933
5934     VOL_LOCK;
5935     if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_OFFLINE) {
5936         volume_LRU.scanner_state = VLRU_SCANNER_STATE_ONLINE;
5937     }
5938
5939     while ((state = volume_LRU.scanner_state) != VLRU_SCANNER_STATE_SHUTTING_DOWN) {
5940         /* check to see if we've been asked to pause */
5941         if (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSING) {
5942             volume_LRU.scanner_state = VLRU_SCANNER_STATE_PAUSED;
5943             assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
5944             do {
5945                 VOL_CV_WAIT(&volume_LRU.cv);
5946             } while (volume_LRU.scanner_state == VLRU_SCANNER_STATE_PAUSED);
5947         }
5948
5949         /* scheduling can happen outside the glock */
5950         VOL_UNLOCK;
5951
5952         /* figure out what is next on the schedule */
5953
5954         /* figure out a potential schedule for the new generation first */
5955         overdue = 0;
5956         min_delay = volume_LRU.scan_interval[0] + volume_LRU.last_scan[0] - now;
5957         min_idx = 0;
5958         min_op = 0;
5959         if (min_delay > volume_LRU.scan_interval[0]) {
5960             /* unsigned overflow -- we're overdue to run this scan */
5961             min_delay = 0;
5962             overdue = 1;
5963         }
5964
5965         /* if we're not overdue for gen 0, figure out schedule for candidate gen */
5966         if (!overdue) {
5967             i = VLRU_QUEUE_CANDIDATE;
5968             delay = volume_LRU.scan_interval[i] + volume_LRU.last_scan[i] - now;
5969             if (delay < min_delay) {
5970                 min_delay = delay;
5971                 min_idx = i;
5972             }
5973             if (delay > volume_LRU.scan_interval[i]) {
5974                 /* unsigned overflow -- we're overdue to run this scan */
5975                 min_delay = 0;
5976                 min_idx = i;
5977                 overdue = 1;
5978             }
5979         }
5980
5981         /* if we're still not overdue for something, figure out schedules for promotions */
5982         for (i=0; !overdue && i < VLRU_GENERATIONS-1; i++) {
5983             delay = volume_LRU.promotion_interval[i] + volume_LRU.last_promotion[i] - now;
5984             if (delay < min_delay) {
5985                 min_delay = delay;
5986                 min_idx = i;
5987                 min_op = 1;
5988             }
5989             if (delay > volume_LRU.promotion_interval[i]) {
5990                 /* unsigned overflow -- we're overdue to run this promotion */
5991                 min_delay = 0;
5992                 min_idx = i;
5993                 min_op = 1;
5994                 overdue = 1;
5995                 break;
5996             }
5997         }
5998
5999         /* sleep as needed */
6000         if (min_delay) {
6001             sleep(min_delay);
6002         }
6003
6004         /* do whatever is next */
6005         VOL_LOCK;
6006         if (min_op) {
6007             VLRU_Promote_r(min_idx);
6008             VLRU_Demote_r(min_idx+1);
6009         } else {
6010             VLRU_Scan_r(min_idx);
6011         }
6012         now = FT_ApproxTime();
6013     }
6014
6015     Log("VLRU scanner asked to go offline (scanner_state=%d)\n", state);
6016
6017     /* signal that scanner is down */
6018     volume_LRU.scanner_state = VLRU_SCANNER_STATE_OFFLINE;
6019     assert(pthread_cond_broadcast(&volume_LRU.cv) == 0);
6020     VOL_UNLOCK;
6021     return NULL;
6022 }
6023
6024 /**
6025  * promote volumes from one VLRU generation to the next.
6026  *
6027  * This routine scans a VLRU generation looking for volumes which are
6028  * eligible to be promoted to the next generation.  All volumes which
6029  * meet the eligibility requirement are promoted.
6030  *
6031  * Promotion eligibility is based upon meeting both of the following
6032  * requirements:
6033  *
6034  *    @arg The volume has been accessed since the last promotion:
6035  *         @c (vp->stats.last_get >= vp->stats.last_promote)
6036  *    @arg The last promotion occurred at least 
6037  *         @c volume_LRU.promotion_interval[idx] seconds ago
6038  *
6039  * As a performance optimization, promotions are "globbed".  In other
6040  * words, we promote arbitrarily large contiguous sublists of elements
6041  * as one operation.  
6042  *
6043  * @param[in] idx  VLRU queue index to scan
6044  *
6045  * @note DAFS only
6046  *
6047  * @internal VLRU internal use only.
6048  */
6049 static void
6050 VLRU_Promote_r(int idx)
6051 {
6052     int len, chaining, promote;
6053     afs_uint32 now, thresh;
6054     struct rx_queue *qp, *nqp;
6055     Volume * vp, *start = NULL, *end = NULL;
6056
6057     /* get exclusive access to two chains, and drop the glock */
6058     VLRU_Wait_r(&volume_LRU.q[idx]);
6059     VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
6060     VLRU_Wait_r(&volume_LRU.q[idx+1]);
6061     VLRU_BeginExclusive_r(&volume_LRU.q[idx+1]);
6062     VOL_UNLOCK;
6063
6064     thresh = volume_LRU.promotion_interval[idx];
6065     now = FT_ApproxTime();
6066
6067     len = chaining = 0;
6068     for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
6069         vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6070         promote = (((vp->stats.last_promote + thresh) <= now) &&
6071                    (vp->stats.last_get >= vp->stats.last_promote));
6072
6073         if (chaining) {
6074             if (promote) {
6075                 vp->vlru.idx++;
6076                 len++;
6077                 start = vp;
6078             } else {
6079                 /* promote and prepend chain */
6080                 queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
6081                 chaining = 0;
6082             }
6083         } else {
6084             if (promote) {
6085                 vp->vlru.idx++;
6086                 len++;
6087                 chaining = 1;
6088                 start = end = vp;
6089             }
6090         }
6091     }
6092
6093     if (chaining) {
6094         /* promote and prepend */
6095         queue_MoveChainAfter(&volume_LRU.q[idx+1], &start->vlru, &end->vlru);
6096     }
6097
6098     if (len) {
6099         volume_LRU.q[idx].len -= len;
6100         volume_LRU.q[idx+1].len += len;
6101     }
6102
6103     /* release exclusive access to the two chains */
6104     VOL_LOCK;
6105     volume_LRU.last_promotion[idx] = now;
6106     VLRU_EndExclusive_r(&volume_LRU.q[idx+1]);
6107     VLRU_EndExclusive_r(&volume_LRU.q[idx]);
6108 }
6109
6110 /* run the demotions */
6111 static void
6112 VLRU_Demote_r(int idx)
6113 {
6114     Error ec;
6115     int len, chaining, demote;
6116     afs_uint32 now, thresh;
6117     struct rx_queue *qp, *nqp;
6118     Volume * vp, *start = NULL, *end = NULL;
6119     Volume ** salv_flag_vec = NULL;
6120     int salv_vec_offset = 0;
6121
6122     assert(idx == VLRU_QUEUE_MID || idx == VLRU_QUEUE_OLD);
6123
6124     /* get exclusive access to two chains, and drop the glock */
6125     VLRU_Wait_r(&volume_LRU.q[idx-1]);
6126     VLRU_BeginExclusive_r(&volume_LRU.q[idx-1]);
6127     VLRU_Wait_r(&volume_LRU.q[idx]);
6128     VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
6129     VOL_UNLOCK;
6130
6131     /* no big deal if this allocation fails */
6132     if (volume_LRU.q[idx].len) {
6133         salv_flag_vec = (Volume **) malloc(volume_LRU.q[idx].len * sizeof(Volume *));
6134     }
6135
6136     now = FT_ApproxTime();
6137     thresh = volume_LRU.promotion_interval[idx-1];
6138
6139     len = chaining = 0;
6140     for (queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
6141         vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6142         demote = (((vp->stats.last_promote + thresh) <= now) &&
6143                   (vp->stats.last_get < (now - thresh)));
6144
6145         /* we now do volume update list DONT_SALVAGE flag setting during
6146          * demotion passes */
6147         if (salv_flag_vec &&
6148             !(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
6149             demote && 
6150             (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
6151             (V_attachState(vp) == VOL_STATE_ATTACHED)) {
6152             salv_flag_vec[salv_vec_offset++] = vp;
6153             VCreateReservation_r(vp);
6154         }
6155
6156         if (chaining) {
6157             if (demote) {
6158                 vp->vlru.idx--;
6159                 len++;
6160                 start = vp;
6161             } else {
6162                 /* demote and append chain */
6163                 queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
6164                 chaining = 0;
6165             }
6166         } else {
6167             if (demote) {
6168                 vp->vlru.idx--;
6169                 len++;
6170                 chaining = 1;
6171                 start = end = vp;
6172             }
6173         }
6174     }
6175
6176     if (chaining) {
6177         queue_MoveChainBefore(&volume_LRU.q[idx-1], &start->vlru, &end->vlru);
6178     }
6179
6180     if (len) {
6181         volume_LRU.q[idx].len -= len;
6182         volume_LRU.q[idx-1].len += len;
6183     }
6184
6185     /* release exclusive access to the two chains */
6186     VOL_LOCK;
6187     VLRU_EndExclusive_r(&volume_LRU.q[idx]);
6188     VLRU_EndExclusive_r(&volume_LRU.q[idx-1]);
6189
6190     /* now go back and set the DONT_SALVAGE flags as appropriate */
6191     if (salv_flag_vec) {
6192         int i;
6193         for (i = 0; i < salv_vec_offset; i++) {
6194             vp = salv_flag_vec[i];
6195             if (!(V_attachFlags(vp) & VOL_HDR_DONTSALV) &&
6196                 (vp->updateTime < (now - SALVAGE_INTERVAL)) &&
6197                 (V_attachState(vp) == VOL_STATE_ATTACHED)) {
6198                 ec = VHold_r(vp);
6199                 if (!ec) {
6200                     V_attachFlags(vp) |= VOL_HDR_DONTSALV;
6201                     V_dontSalvage(vp) = DONT_SALVAGE;
6202                     VUpdateVolume_r(&ec, vp, 0);
6203                     VPutVolume_r(vp);
6204                 }
6205             }
6206             VCancelReservation_r(vp);
6207         }
6208         free(salv_flag_vec);
6209     }
6210 }
6211
6212 /* run a pass of the VLRU GC scanner */
6213 static void
6214 VLRU_Scan_r(int idx)
6215 {
6216     afs_uint32 now, thresh;
6217     struct rx_queue *qp, *nqp;
6218     Volume * vp;
6219     int i, locked = 1;
6220
6221     assert(idx == VLRU_QUEUE_NEW || idx == VLRU_QUEUE_CANDIDATE);
6222
6223     /* gain exclusive access to the idx VLRU */
6224     VLRU_Wait_r(&volume_LRU.q[idx]);
6225     VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
6226
6227     if (idx != VLRU_QUEUE_CANDIDATE) {
6228         /* gain exclusive access to the candidate VLRU */
6229         VLRU_Wait_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6230         VLRU_BeginExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6231     }
6232
6233     now = FT_ApproxTime();
6234     thresh = now - VLRU_offline_thresh;
6235
6236     /* perform candidate selection and soft detaching */
6237     if (idx == VLRU_QUEUE_CANDIDATE) {
6238         /* soft detach some volumes from the candidate pool */
6239         VOL_UNLOCK;
6240         locked = 0;
6241
6242         for (i=0,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
6243             vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6244             if (i >= VLRU_offline_max) {
6245                 break;
6246             }
6247             /* check timestamp to see if it's a candidate for soft detaching */
6248             if (vp->stats.last_get <= thresh) {
6249                 VOL_LOCK;
6250                 if (VCheckSoftDetach(vp, thresh))
6251                     i++;
6252                 VOL_UNLOCK;
6253             }
6254         }
6255     } else {
6256         /* scan for volumes to become soft detach candidates */
6257         for (i=1,queue_ScanBackwards(&volume_LRU.q[idx], qp, nqp, rx_queue),i++) {
6258             vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
6259
6260             /* check timestamp to see if it's a candidate for soft detaching */
6261             if (vp->stats.last_get <= thresh) {
6262                 VCheckSoftDetachCandidate(vp, thresh);
6263             }
6264
6265             if (!(i&0x7f)) {   /* lock coarsening optimization */
6266                 VOL_UNLOCK;
6267                 pthread_yield();
6268                 VOL_LOCK;
6269             }
6270         }
6271     }
6272
6273     /* relinquish exclusive access to the VLRU chains */
6274     if (!locked) {
6275         VOL_LOCK;
6276     }
6277     volume_LRU.last_scan[idx] = now;
6278     if (idx != VLRU_QUEUE_CANDIDATE) {
6279         VLRU_EndExclusive_r(&volume_LRU.q[VLRU_QUEUE_CANDIDATE]);
6280     }
6281     VLRU_EndExclusive_r(&volume_LRU.q[idx]);
6282 }
6283
6284 /* check whether volume is safe to soft detach
6285  * caller MUST NOT hold a ref count on vp */
6286 static int
6287 VCheckSoftDetach(Volume * vp, afs_uint32 thresh)
6288 {
6289     int ret=0;
6290
6291     if (vp->nUsers || vp->nWaiters)
6292         return 0;
6293
6294     if (vp->stats.last_get <= thresh) {
6295         ret = VSoftDetachVolume_r(vp, thresh);
6296     }
6297
6298     return ret;
6299 }
6300
6301 /* check whether volume should be made a 
6302  * soft detach candidate */
6303 static int
6304 VCheckSoftDetachCandidate(Volume * vp, afs_uint32 thresh)
6305 {
6306     int idx, ret = 0;
6307     if (vp->nUsers || vp->nWaiters)
6308         return 0;
6309
6310     idx = vp->vlru.idx;
6311
6312     assert(idx == VLRU_QUEUE_NEW);
6313
6314     if (vp->stats.last_get <= thresh) {
6315         /* move to candidate pool */
6316         queue_Remove(&vp->vlru);
6317         volume_LRU.q[VLRU_QUEUE_NEW].len--;
6318         queue_Prepend(&volume_LRU.q[VLRU_QUEUE_CANDIDATE], &vp->vlru);
6319         vp->vlru.idx = VLRU_QUEUE_CANDIDATE;
6320         volume_LRU.q[VLRU_QUEUE_CANDIDATE].len++;
6321         ret = 1;
6322     }
6323
6324     return ret;
6325 }
6326
6327
6328 /* begin exclusive access on VLRU */
6329 static void
6330 VLRU_BeginExclusive_r(struct VLRU_q * q)
6331 {
6332     assert(q->busy == 0);
6333     q->busy = 1;
6334 }
6335
6336 /* end exclusive access on VLRU */
6337 static void
6338 VLRU_EndExclusive_r(struct VLRU_q * q)
6339 {
6340     assert(q->busy);
6341     q->busy = 0;
6342     assert(pthread_cond_broadcast(&q->cv) == 0);
6343 }
6344
6345 /* wait for another thread to end exclusive access on VLRU */
6346 static void
6347 VLRU_Wait_r(struct VLRU_q * q)
6348 {
6349     while(q->busy) {
6350         VOL_CV_WAIT(&q->cv);
6351     }
6352 }
6353
6354 /* demand attach fs
6355  * volume soft detach
6356  *
6357  * caller MUST NOT hold a ref count on vp */
6358 static int
6359 VSoftDetachVolume_r(Volume * vp, afs_uint32 thresh)
6360 {
6361     afs_uint32 ts_save;
6362     int ret = 0;
6363
6364     assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
6365
6366     ts_save = vp->stats.last_get;
6367     if (ts_save > thresh)
6368         return 0;
6369
6370     if (vp->nUsers || vp->nWaiters)
6371         return 0;
6372
6373     if (VIsExclusiveState(V_attachState(vp))) {
6374         return 0;
6375     }
6376
6377     switch (V_attachState(vp)) {
6378     case VOL_STATE_UNATTACHED:
6379     case VOL_STATE_PREATTACHED:
6380     case VOL_STATE_ERROR:
6381     case VOL_STATE_GOING_OFFLINE:
6382     case VOL_STATE_SHUTTING_DOWN:
6383     case VOL_STATE_SALVAGING:
6384         volume_LRU.q[vp->vlru.idx].len--;
6385
6386         /* create and cancel a reservation to
6387          * give the volume an opportunity to
6388          * be deallocated */
6389         VCreateReservation_r(vp);
6390         queue_Remove(&vp->vlru);
6391         vp->vlru.idx = VLRU_QUEUE_INVALID;
6392         V_attachFlags(vp) &= ~(VOL_ON_VLRU);
6393         VCancelReservation_r(vp);
6394         return 0;
6395     default:
6396         break;
6397     }
6398
6399     /* hold the volume and take it offline.
6400      * no need for reservations, as VHold_r
6401      * takes care of that internally. */
6402     if (VHold_r(vp) == 0) {
6403         /* vhold drops the glock, so now we should
6404          * check to make sure we aren't racing against
6405          * other threads.  if we are racing, offlining vp
6406          * would be wasteful, and block the scanner for a while 
6407          */
6408         if (vp->nWaiters || 
6409             (vp->nUsers > 1) ||
6410             (vp->shuttingDown) ||
6411             (vp->goingOffline) ||
6412             (vp->stats.last_get != ts_save)) {
6413             /* looks like we're racing someone else. bail */
6414             VPutVolume_r(vp);
6415             vp = NULL;
6416         } else {
6417             /* pull it off the VLRU */
6418             assert(vp->vlru.idx == VLRU_QUEUE_CANDIDATE);
6419             volume_LRU.q[VLRU_QUEUE_CANDIDATE].len--;
6420             queue_Remove(&vp->vlru);
6421             vp->vlru.idx = VLRU_QUEUE_INVALID;
6422             V_attachFlags(vp) &= ~(VOL_ON_VLRU);
6423
6424             /* take if offline */
6425             VOffline_r(vp, "volume has been soft detached");
6426
6427             /* invalidate the volume header cache */
6428             FreeVolumeHeader(vp);
6429
6430             /* update stats */
6431             IncUInt64(&VStats.soft_detaches);
6432             vp->stats.soft_detaches++;
6433
6434             /* put in pre-attached state so demand
6435              * attacher can work on it */
6436             VChangeState_r(vp, VOL_STATE_PREATTACHED);
6437             ret = 1;
6438         }
6439     }
6440     return ret;
6441 }
6442 #endif /* AFS_DEMAND_ATTACH_FS */
6443
6444
6445 /***************************************************/
6446 /* Volume Header Cache routines                    */
6447 /***************************************************/
6448
6449 /** 
6450  * volume header cache.
6451  */
6452 struct volume_hdr_LRU_t volume_hdr_LRU;
6453
6454 /**
6455  * initialize the volume header cache.
6456  *
6457  * @param[in] howMany  number of header cache entries to preallocate
6458  *
6459  * @pre VOL_LOCK held.  Function has never been called before.
6460  *
6461  * @post howMany cache entries are allocated, initialized, and added 
6462  *       to the LRU list.  Header cache statistics are initialized.
6463  *
6464  * @note only applicable to fileServer program type.  Should only be
6465  *       called once during volume package initialization.
6466  *
6467  * @internal volume package internal use only.
6468  */
6469 static void
6470 VInitVolumeHeaderCache(afs_uint32 howMany)
6471 {
6472     register struct volHeader *hp;
6473     if (programType != fileServer)
6474         return;
6475     queue_Init(&volume_hdr_LRU);
6476     volume_hdr_LRU.stats.free = 0;
6477     volume_hdr_LRU.stats.used = howMany;
6478     volume_hdr_LRU.stats.attached = 0;
6479     hp = (struct volHeader *)(calloc(howMany, sizeof(struct volHeader)));
6480     assert(hp != NULL);
6481
6482     while (howMany--)
6483         /* We are using ReleaseVolumeHeader to initialize the values on the header list
6484          * to ensure they have the right values
6485          */
6486         ReleaseVolumeHeader(hp++);
6487 }
6488
6489 /**
6490  * get a volume header and attach it to the volume object.
6491  *
6492  * @param[in] vp  pointer to volume object
6493  *
6494  * @return cache entry status
6495  *    @retval 0  volume header was newly attached; cache data is invalid
6496  *    @retval 1  volume header was previously attached; cache data is valid
6497  *
6498  * @pre VOL_LOCK held.  For DAFS, lightweight ref must be held on volume object.
6499  *
6500  * @post volume header attached to volume object.  if necessary, header cache 
6501  *       entry on LRU is synchronized to disk.  Header is removed from LRU list.
6502  *
6503  * @note VOL_LOCK may be dropped
6504  *
6505  * @warning this interface does not load header data from disk.  it merely
6506  *          attaches a header object to the volume object, and may sync the old
6507  *          header cache data out to disk in the process.
6508  *
6509  * @internal volume package internal use only.
6510  */
6511 static int
6512 GetVolumeHeader(register Volume * vp)
6513 {
6514     Error error;
6515     register struct volHeader *hd;
6516     int old;
6517     static int everLogged = 0;
6518
6519 #ifdef AFS_DEMAND_ATTACH_FS
6520     VolState vp_save = 0, back_save = 0;
6521
6522     /* XXX debug 9/19/05 we've apparently got
6523      * a ref counting bug somewhere that's
6524      * breaking the nUsers == 0 => header on LRU
6525      * assumption */
6526     if (vp->header && queue_IsNotOnQueue(vp->header)) {
6527         Log("nUsers == 0, but header not on LRU\n");
6528         return 1;
6529     }
6530 #endif
6531
6532     old = (vp->header != NULL); /* old == volume already has a header */
6533
6534     if (programType != fileServer) {
6535         /* for volume utilities, we allocate volHeaders as needed */
6536         if (!vp->header) {
6537             hd = (struct volHeader *)calloc(1, sizeof(*vp->header));
6538             assert(hd != NULL);
6539             vp->header = hd;
6540             hd->back = vp;
6541 #ifdef AFS_DEMAND_ATTACH_FS
6542             V_attachFlags(vp) |= VOL_HDR_ATTACHED;
6543 #endif
6544         }
6545     } else {
6546         /* for the fileserver, we keep a volume header cache */
6547         if (old) {
6548             /* the header we previously dropped in the lru is
6549              * still available. pull it off the lru and return */
6550             hd = vp->header;
6551             queue_Remove(hd);
6552             assert(hd->back == vp);
6553         } else {
6554             /* we need to grab a new element off the LRU */
6555             if (queue_IsNotEmpty(&volume_hdr_LRU)) {
6556                 /* grab an element and pull off of LRU */
6557                 hd = queue_First(&volume_hdr_LRU, volHeader);
6558                 queue_Remove(hd);
6559             } else {
6560                 /* LRU is empty, so allocate a new volHeader 
6561                  * this is probably indicative of a leak, so let the user know */
6562                 hd = (struct volHeader *)calloc(1, sizeof(struct volHeader));
6563                 assert(hd != NULL);
6564                 if (!everLogged) {
6565                     Log("****Allocated more volume headers, probably leak****\n");
6566                     everLogged = 1;
6567                 }
6568                 volume_hdr_LRU.stats.free++;
6569             }
6570             if (hd->back) {
6571                 /* this header used to belong to someone else. 
6572                  * we'll need to check if the header needs to
6573                  * be sync'd out to disk */
6574
6575 #ifdef AFS_DEMAND_ATTACH_FS
6576                 /* if hd->back were in an exclusive state, then
6577                  * its volHeader would not be on the LRU... */
6578                 assert(!VIsExclusiveState(V_attachState(hd->back)));
6579 #endif
6580
6581                 if (hd->diskstuff.inUse) {
6582                     /* volume was in use, so we'll need to sync
6583                      * its header to disk */
6584
6585 #ifdef AFS_DEMAND_ATTACH_FS
6586                     back_save = VChangeState_r(hd->back, VOL_STATE_UPDATING);
6587                     vp_save = VChangeState_r(vp, VOL_STATE_HDR_ATTACHING);
6588                     VCreateReservation_r(hd->back);
6589                     VOL_UNLOCK;
6590 #endif
6591
6592                     WriteVolumeHeader_r(&error, hd->back);
6593                     /* Ignore errors; catch them later */
6594
6595 #ifdef AFS_DEMAND_ATTACH_FS
6596                     VOL_LOCK;
6597 #endif
6598                 }
6599
6600                 hd->back->header = NULL;
6601 #ifdef AFS_DEMAND_ATTACH_FS
6602                 V_attachFlags(hd->back) &= ~(VOL_HDR_ATTACHED | VOL_HDR_LOADED | VOL_HDR_IN_LRU);
6603
6604                 if (hd->diskstuff.inUse) {
6605                     VChangeState_r(hd->back, back_save);
6606                     VCancelReservation_r(hd->back);
6607                     VChangeState_r(vp, vp_save);
6608                 }
6609 #endif
6610             } else {
6611                 volume_hdr_LRU.stats.attached++;
6612             }
6613             hd->back = vp;
6614             vp->header = hd;
6615 #ifdef AFS_DEMAND_ATTACH_FS
6616             V_attachFlags(vp) |= VOL_HDR_ATTACHED;
6617 #endif
6618         }
6619         volume_hdr_LRU.stats.free--;
6620         volume_hdr_LRU.stats.used++;
6621     }
6622     IncUInt64(&VStats.hdr_gets);
6623 #ifdef AFS_DEMAND_ATTACH_FS
6624     IncUInt64(&vp->stats.hdr_gets);
6625     vp->stats.last_hdr_get = FT_ApproxTime();
6626 #endif
6627     return old;
6628 }
6629
6630
6631 /**
6632  * make sure volume header is attached and contains valid cache data.
6633  *
6634  * @param[out] ec  outbound error code
6635  * @param[in]  vp  pointer to volume object
6636  *
6637  * @pre VOL_LOCK held.  For DAFS, lightweight ref held on vp.
6638  *
6639  * @post header cache entry attached, and loaded with valid data, or
6640  *       *ec is nonzero, and the header is released back into the LRU.
6641  *
6642  * @internal volume package internal use only.
6643  */
6644 static void
6645 LoadVolumeHeader(Error * ec, Volume * vp)
6646 {
6647 #ifdef AFS_DEMAND_ATTACH_FS
6648     VolState state_save;
6649     afs_uint32 now;
6650     *ec = 0;
6651
6652     if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
6653         IncUInt64(&VStats.hdr_loads);
6654         state_save = VChangeState_r(vp, VOL_STATE_HDR_LOADING);
6655         VOL_UNLOCK;
6656
6657         ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
6658                    sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
6659                    VOLUMEINFOVERSION);
6660         IncUInt64(&vp->stats.hdr_loads);
6661         now = FT_ApproxTime();
6662
6663         VOL_LOCK;
6664         if (!*ec) {
6665             V_attachFlags(vp) |= VOL_HDR_LOADED;
6666             vp->stats.last_hdr_load = now;
6667         }
6668         VChangeState_r(vp, state_save);
6669     }
6670 #else /* AFS_DEMAND_ATTACH_FS */
6671     *ec = 0;
6672     if (vp->nUsers == 0 && !GetVolumeHeader(vp)) {
6673         IncUInt64(&VStats.hdr_loads);
6674
6675         ReadHeader(ec, V_diskDataHandle(vp), (char *)&V_disk(vp),
6676                    sizeof(V_disk(vp)), VOLUMEINFOMAGIC,
6677                    VOLUMEINFOVERSION);
6678     }
6679 #endif /* AFS_DEMAND_ATTACH_FS */
6680     if (*ec) {
6681         /* maintain (nUsers==0) => header in LRU invariant */
6682         FreeVolumeHeader(vp);
6683     }
6684 }
6685
6686 /**
6687  * release a header cache entry back into the LRU list.
6688  *
6689  * @param[in] hd  pointer to volume header cache object
6690  *
6691  * @pre VOL_LOCK held.
6692  *
6693  * @post header cache object appended onto end of LRU list.
6694  *
6695  * @note only applicable to fileServer program type.
6696  *
6697  * @note used to place a header cache entry back into the
6698  *       LRU pool without invalidating it as a cache entry.
6699  *
6700  * @internal volume package internal use only.
6701  */
6702 static void
6703 ReleaseVolumeHeader(register struct volHeader *hd)
6704 {
6705     if (programType != fileServer)
6706         return;
6707     if (!hd || queue_IsOnQueue(hd))     /* no header, or header already released */
6708         return;
6709     queue_Append(&volume_hdr_LRU, hd);
6710 #ifdef AFS_DEMAND_ATTACH_FS
6711     if (hd->back) {
6712         V_attachFlags(hd->back) |= VOL_HDR_IN_LRU;
6713     }
6714 #endif
6715     volume_hdr_LRU.stats.free++;
6716     volume_hdr_LRU.stats.used--;
6717 }
6718
6719 /**
6720  * free/invalidate a volume header cache entry.
6721  *
6722  * @param[in] vp  pointer to volume object
6723  *
6724  * @pre VOL_LOCK is held.
6725  *
6726  * @post For fileserver, header cache entry is returned to LRU, and it is
6727  *       invalidated as a cache entry.  For volume utilities, the header
6728  *       cache entry is freed.
6729  *
6730  * @note For fileserver, this should be utilized instead of ReleaseVolumeHeader
6731  *       whenever it is necessary to invalidate the header cache entry.
6732  *
6733  * @see ReleaseVolumeHeader
6734  *
6735  * @internal volume package internal use only.
6736  */
6737 static void
6738 FreeVolumeHeader(register Volume * vp)
6739 {
6740     register struct volHeader *hd = vp->header;
6741     if (!hd)
6742         return;
6743     if (programType == fileServer) {
6744         ReleaseVolumeHeader(hd);
6745         hd->back = NULL;
6746     } else {
6747         free(hd);
6748     }
6749 #ifdef AFS_DEMAND_ATTACH_FS
6750     V_attachFlags(vp) &= ~(VOL_HDR_ATTACHED | VOL_HDR_IN_LRU | VOL_HDR_LOADED);
6751 #endif
6752     volume_hdr_LRU.stats.attached--;
6753     vp->header = NULL;
6754 }
6755
6756
6757 /***************************************************/
6758 /* Volume Hash Table routines                      */
6759 /***************************************************/
6760
6761 /**
6762  * set size of volume object hash table.
6763  *
6764  * @param[in] logsize   log(2) of desired hash table size
6765  *
6766  * @return operation status
6767  *    @retval 0 success
6768  *    @retval -1 failure
6769  *
6770  * @pre MUST be called prior to VInitVolumePackage2
6771  *
6772  * @post Volume Hash Table will have 2^logsize buckets
6773  */
6774 int 
6775 VSetVolHashSize(int logsize)
6776 {
6777     /* 64 to 16384 hash buckets seems like a reasonable range */
6778     if ((logsize < 6 ) || (logsize > 14)) {
6779         return -1;
6780     }
6781     
6782     if (!VInit) {
6783         VolumeHashTable.Size = 1 << logsize;
6784         VolumeHashTable.Mask = VolumeHashTable.Size - 1;
6785     } else {
6786         /* we can't yet support runtime modification of this
6787          * parameter. we'll need a configuration rwlock to
6788          * make runtime modification feasible.... */
6789         return -1;
6790     }
6791     return 0;
6792 }
6793
6794 /**
6795  * initialize dynamic data structures for volume hash table.
6796  *
6797  * @post hash table is allocated, and fields are initialized.
6798  *
6799  * @internal volume package internal use only.
6800  */
6801 static void
6802 VInitVolumeHash(void)
6803 {
6804     register int i;
6805
6806     VolumeHashTable.Table = (VolumeHashChainHead *) calloc(VolumeHashTable.Size, 
6807                                                            sizeof(VolumeHashChainHead));
6808     assert(VolumeHashTable.Table != NULL);
6809     
6810     for (i=0; i < VolumeHashTable.Size; i++) {
6811         queue_Init(&VolumeHashTable.Table[i]);
6812 #ifdef AFS_DEMAND_ATTACH_FS
6813         assert(pthread_cond_init(&VolumeHashTable.Table[i].chain_busy_cv, NULL) == 0);
6814 #endif /* AFS_DEMAND_ATTACH_FS */
6815     }
6816 }
6817
6818 /**
6819  * add a volume object to the hash table.
6820  *
6821  * @param[in] vp      pointer to volume object
6822  * @param[in] hashid  hash of volume id
6823  *
6824  * @pre VOL_LOCK is held.  For DAFS, caller must hold a lightweight
6825  *      reference on vp.
6826  *
6827  * @post volume is added to hash chain.
6828  *
6829  * @internal volume package internal use only.
6830  *
6831  * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
6832  *       asynchronous hash chain reordering to finish.
6833  */
6834 static void
6835 AddVolumeToHashTable(register Volume * vp, int hashid)
6836 {
6837     VolumeHashChainHead * head;
6838
6839     if (queue_IsOnQueue(vp))
6840         return;
6841
6842     head = &VolumeHashTable.Table[VOLUME_HASH(hashid)];
6843
6844 #ifdef AFS_DEMAND_ATTACH_FS
6845     /* wait for the hash chain to become available */
6846     VHashWait_r(head);
6847
6848     V_attachFlags(vp) |= VOL_IN_HASH;
6849     vp->chainCacheCheck = ++head->cacheCheck;
6850 #endif /* AFS_DEMAND_ATTACH_FS */
6851
6852     head->len++;
6853     vp->hashid = hashid;
6854     queue_Append(head, vp);
6855     vp->vnodeHashOffset = VolumeHashOffset_r();
6856 }
6857
6858 /**
6859  * delete a volume object from the hash table.
6860  *
6861  * @param[in] vp  pointer to volume object
6862  *
6863  * @pre VOL_LOCK is held.  For DAFS, caller must hold a lightweight
6864  *      reference on vp.
6865  *
6866  * @post volume is removed from hash chain.
6867  *
6868  * @internal volume package internal use only.
6869  *
6870  * @note For DAFS, VOL_LOCK may be dropped in order to wait for an
6871  *       asynchronous hash chain reordering to finish.
6872  */
6873 static void
6874 DeleteVolumeFromHashTable(register Volume * vp)
6875 {
6876     VolumeHashChainHead * head;
6877
6878     if (!queue_IsOnQueue(vp))
6879         return;
6880
6881     head = &VolumeHashTable.Table[VOLUME_HASH(vp->hashid)];
6882
6883 #ifdef AFS_DEMAND_ATTACH_FS
6884     /* wait for the hash chain to become available */
6885     VHashWait_r(head);
6886
6887     V_attachFlags(vp) &= ~(VOL_IN_HASH);
6888     head->cacheCheck++;
6889 #endif /* AFS_DEMAND_ATTACH_FS */
6890
6891     head->len--;
6892     queue_Remove(vp);
6893     /* do NOT reset hashid to zero, as the online
6894      * salvager package may need to know the volume id
6895      * after the volume is removed from the hash */
6896 }
6897
6898 /**
6899  * lookup a volume object in the hash table given a volume id.
6900  *
6901  * @param[out] ec        error code return
6902  * @param[in]  volumeId  volume id
6903  * @param[in]  hint      volume object which we believe could be the correct 
6904                          mapping
6905  *
6906  * @return volume object pointer
6907  *    @retval NULL  no such volume id is registered with the hash table.
6908  *
6909  * @pre VOL_LOCK is held.  For DAFS, caller must hold a lightweight 
6910         ref on hint.
6911  *
6912  * @post volume object with the given id is returned.  volume object and 
6913  *       hash chain access statistics are updated.  hash chain may have 
6914  *       been reordered.
6915  *
6916  * @note For DAFS, VOL_LOCK may be dropped in order to wait for an 
6917  *       asynchronous hash chain reordering operation to finish, or 
6918  *       in order for us to perform an asynchronous chain reordering.
6919  *
6920  * @note Hash chain reorderings occur when the access count for the 
6921  *       volume object being looked up exceeds the sum of the previous 
6922  *       node's (the node ahead of it in the hash chain linked list) 
6923  *       access count plus the constant VOLUME_HASH_REORDER_THRESHOLD.
6924  *
6925  * @note For DAFS, the hint parameter allows us to short-circuit if the 
6926  *       cacheCheck fields match between the hash chain head and the 
6927  *       hint volume object.
6928  */
6929 Volume *
6930 VLookupVolume_r(Error * ec, VolId volumeId, Volume * hint)
6931 {
6932     register int looks = 0;
6933     Volume * vp, *np;
6934 #ifdef AFS_DEMAND_ATTACH_FS
6935     Volume *pp;
6936 #endif
6937     VolumeHashChainHead * head;
6938     *ec = 0;
6939
6940     head = &VolumeHashTable.Table[VOLUME_HASH(volumeId)];
6941
6942 #ifdef AFS_DEMAND_ATTACH_FS
6943     /* wait for the hash chain to become available */
6944     VHashWait_r(head);
6945
6946     /* check to see if we can short circuit without walking the hash chain */
6947     if (hint && (hint->chainCacheCheck == head->cacheCheck)) {
6948         IncUInt64(&hint->stats.hash_short_circuits);
6949         return hint;
6950     }
6951 #endif /* AFS_DEMAND_ATTACH_FS */
6952
6953     /* someday we need to either do per-chain locks, RWlocks,
6954      * or both for volhash access. 
6955      * (and move to a data structure with better cache locality) */
6956
6957     /* search the chain for this volume id */
6958     for(queue_Scan(head, vp, np, Volume)) {
6959         looks++;
6960         if ((vp->hashid == volumeId)) {
6961             break;
6962         }
6963     }
6964
6965     if (queue_IsEnd(head, vp)) {
6966         vp = NULL;
6967     }
6968
6969 #ifdef AFS_DEMAND_ATTACH_FS
6970     /* update hash chain statistics */
6971     {
6972         afs_uint64 lks;
6973         FillInt64(lks, 0, looks);
6974         AddUInt64(head->looks, lks, &head->looks);
6975         AddUInt64(VStats.hash_looks, lks, &VStats.hash_looks);
6976         IncUInt64(&head->gets);
6977     }
6978
6979     if (vp) {
6980         afs_uint64 thresh;
6981         IncUInt64(&vp->stats.hash_lookups);
6982
6983         /* for demand attach fileserver, we permit occasional hash chain reordering
6984          * so that frequently looked up volumes move towards the head of the chain */
6985         pp = queue_Prev(vp, Volume);
6986         if (!queue_IsEnd(head, pp)) {
6987             FillInt64(thresh, 0, VOLUME_HASH_REORDER_THRESHOLD);
6988             AddUInt64(thresh, pp->stats.hash_lookups, &thresh);
6989             if (GEInt64(vp->stats.hash_lookups, thresh)) {
6990                 VReorderHash_r(head, pp, vp);
6991             }
6992         }
6993
6994         /* update the short-circuit cache check */
6995         vp->chainCacheCheck = head->cacheCheck;
6996     }
6997 #endif /* AFS_DEMAND_ATTACH_FS */    
6998
6999     return vp;
7000 }
7001
7002 #ifdef AFS_DEMAND_ATTACH_FS
7003 /* perform volume hash chain reordering.
7004  *
7005  * advance a subchain beginning at vp ahead of
7006  * the adjacent subchain ending at pp */
7007 static void
7008 VReorderHash_r(VolumeHashChainHead * head, Volume * pp, Volume * vp)
7009 {
7010     Volume *tp, *np, *lp;
7011     afs_uint64 move_thresh;
7012
7013     /* this should never be called if the chain is already busy, so
7014      * no need to wait for other exclusive chain ops to finish */
7015
7016     /* this is a rather heavy set of operations,
7017      * so let's set the chain busy flag and drop
7018      * the vol_glock */
7019     VHashBeginExclusive_r(head);
7020     VOL_UNLOCK;
7021
7022     /* scan forward in the chain from vp looking for the last element
7023      * in the chain we want to advance */
7024     FillInt64(move_thresh, 0, VOLUME_HASH_REORDER_CHAIN_THRESH);
7025     AddUInt64(move_thresh, pp->stats.hash_lookups, &move_thresh);
7026     for(queue_ScanFrom(head, vp, tp, np, Volume)) {
7027         if (LTInt64(tp->stats.hash_lookups, move_thresh)) {
7028             break;
7029         }
7030     }
7031     lp = queue_Prev(tp, Volume);
7032
7033     /* scan backwards from pp to determine where to splice and
7034      * insert the subchain we're advancing */
7035     for(queue_ScanBackwardsFrom(head, pp, tp, np, Volume)) {
7036         if (GTInt64(tp->stats.hash_lookups, move_thresh)) {
7037             break;
7038         }
7039     }
7040     tp = queue_Next(tp, Volume);
7041
7042     /* rebalance chain(vp,...,lp) ahead of chain(tp,...,pp) */
7043     queue_MoveChainBefore(tp,vp,lp);
7044
7045     VOL_LOCK;
7046     IncUInt64(&VStats.hash_reorders);
7047     head->cacheCheck++;
7048     IncUInt64(&head->reorders);
7049
7050     /* wake up any threads waiting for the hash chain */
7051     VHashEndExclusive_r(head);
7052 }
7053
7054
7055 /* demand-attach fs volume hash
7056  * asynchronous exclusive operations */
7057
7058 /**
7059  * begin an asynchronous exclusive operation on a volume hash chain.
7060  *
7061  * @param[in] head   pointer to volume hash chain head object
7062  *
7063  * @pre VOL_LOCK held.  hash chain is quiescent.
7064  *
7065  * @post hash chain marked busy.
7066  *
7067  * @note this interface is used in conjunction with VHashEndExclusive_r and
7068  *       VHashWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
7069  *       volume hash chain.  Its main use case is hash chain reordering, which
7070  *       has the potential to be a highly latent operation.
7071  *
7072  * @see VHashEndExclusive_r
7073  * @see VHashWait_r
7074  *
7075  * @note DAFS only
7076  *
7077  * @internal volume package internal use only.
7078  */
7079 static void
7080 VHashBeginExclusive_r(VolumeHashChainHead * head)
7081 {
7082     assert(head->busy == 0);
7083     head->busy = 1;
7084 }
7085
7086 /**
7087  * relinquish exclusive ownership of a volume hash chain.
7088  *
7089  * @param[in] head   pointer to volume hash chain head object
7090  *
7091  * @pre VOL_LOCK held.  thread owns the hash chain exclusively.
7092  *
7093  * @post hash chain is marked quiescent.  threads awaiting use of
7094  *       chain are awakened.
7095  *
7096  * @see VHashBeginExclusive_r
7097  * @see VHashWait_r
7098  *
7099  * @note DAFS only
7100  *
7101  * @internal volume package internal use only.
7102  */
7103 static void
7104 VHashEndExclusive_r(VolumeHashChainHead * head)
7105 {
7106     assert(head->busy);
7107     head->busy = 0;
7108     assert(pthread_cond_broadcast(&head->chain_busy_cv) == 0);
7109 }
7110
7111 /**
7112  * wait for all asynchronous operations on a hash chain to complete.
7113  *
7114  * @param[in] head   pointer to volume hash chain head object
7115  *
7116  * @pre VOL_LOCK held.
7117  *
7118  * @post hash chain object is quiescent.
7119  *
7120  * @see VHashBeginExclusive_r
7121  * @see VHashEndExclusive_r
7122  *
7123  * @note DAFS only
7124  *
7125  * @note This interface should be called before any attempt to
7126  *       traverse the hash chain.  It is permissible for a thread
7127  *       to gain exclusive access to the chain, and then perform
7128  *       latent operations on the chain asynchronously wrt the 
7129  *       VOL_LOCK.
7130  *
7131  * @warning if waiting is necessary, VOL_LOCK is dropped
7132  *
7133  * @internal volume package internal use only.
7134  */
7135 static void
7136 VHashWait_r(VolumeHashChainHead * head)
7137 {
7138     while (head->busy) {
7139         VOL_CV_WAIT(&head->chain_busy_cv);
7140     }
7141 }
7142 #endif /* AFS_DEMAND_ATTACH_FS */
7143
7144
7145 /***************************************************/
7146 /* Volume by Partition List routines               */
7147 /***************************************************/
7148
7149 /*
7150  * demand attach fileserver adds a
7151  * linked list of volumes to each
7152  * partition object, thus allowing
7153  * for quick enumeration of all
7154  * volumes on a partition
7155  */
7156
7157 #ifdef AFS_DEMAND_ATTACH_FS
7158 /**
7159  * add a volume to its disk partition VByPList.
7160  *
7161  * @param[in] vp  pointer to volume object
7162  *
7163  * @pre either the disk partition VByPList is owned exclusively
7164  *      by the calling thread, or the list is quiescent and
7165  *      VOL_LOCK is held.
7166  *
7167  * @post volume is added to disk partition VByPList
7168  *
7169  * @note DAFS only
7170  *
7171  * @warning it is the caller's responsibility to ensure list
7172  *          quiescence.
7173  *
7174  * @see VVByPListWait_r
7175  * @see VVByPListBeginExclusive_r
7176  * @see VVByPListEndExclusive_r
7177  *
7178  * @internal volume package internal use only.
7179  */
7180 static void
7181 AddVolumeToVByPList_r(Volume * vp)
7182 {
7183     if (queue_IsNotOnQueue(&vp->vol_list)) {
7184         queue_Append(&vp->partition->vol_list, &vp->vol_list);
7185         V_attachFlags(vp) |= VOL_ON_VBYP_LIST;
7186         vp->partition->vol_list.len++;
7187     }
7188 }
7189
7190 /**
7191  * delete a volume from its disk partition VByPList.
7192  *
7193  * @param[in] vp  pointer to volume object
7194  *
7195  * @pre either the disk partition VByPList is owned exclusively
7196  *      by the calling thread, or the list is quiescent and
7197  *      VOL_LOCK is held.
7198  *
7199  * @post volume is removed from the disk partition VByPList
7200  *
7201  * @note DAFS only
7202  *
7203  * @warning it is the caller's responsibility to ensure list
7204  *          quiescence.
7205  *
7206  * @see VVByPListWait_r
7207  * @see VVByPListBeginExclusive_r
7208  * @see VVByPListEndExclusive_r
7209  *
7210  * @internal volume package internal use only.
7211  */
7212 static void
7213 DeleteVolumeFromVByPList_r(Volume * vp)
7214 {
7215     if (queue_IsOnQueue(&vp->vol_list)) {
7216         queue_Remove(&vp->vol_list);
7217         V_attachFlags(vp) &= ~(VOL_ON_VBYP_LIST);
7218         vp->partition->vol_list.len--;
7219     }
7220 }
7221
7222 /**
7223  * begin an asynchronous exclusive operation on a VByPList.
7224  *
7225  * @param[in] dp   pointer to disk partition object
7226  *
7227  * @pre VOL_LOCK held.  VByPList is quiescent.
7228  *
7229  * @post VByPList marked busy.
7230  *
7231  * @note this interface is used in conjunction with VVByPListEndExclusive_r and
7232  *       VVByPListWait_r to perform asynchronous (wrt VOL_LOCK) operations on a
7233  *       VByPList.
7234  *
7235  * @see VVByPListEndExclusive_r
7236  * @see VVByPListWait_r
7237  *
7238  * @note DAFS only
7239  *
7240  * @internal volume package internal use only.
7241  */
7242 /* take exclusive control over the list */
7243 static void
7244 VVByPListBeginExclusive_r(struct DiskPartition64 * dp)
7245 {
7246     assert(dp->vol_list.busy == 0);
7247     dp->vol_list.busy = 1;
7248 }
7249
7250 /**
7251  * relinquish exclusive ownership of a VByPList.
7252  *
7253  * @param[in] dp   pointer to disk partition object
7254  *
7255  * @pre VOL_LOCK held.  thread owns the VByPList exclusively.
7256  *
7257  * @post VByPList is marked quiescent.  threads awaiting use of
7258  *       the list are awakened.
7259  *
7260  * @see VVByPListBeginExclusive_r
7261  * @see VVByPListWait_r
7262  *
7263  * @note DAFS only
7264  *
7265  * @internal volume package internal use only.
7266  */
7267 static void
7268 VVByPListEndExclusive_r(struct DiskPartition64 * dp)
7269 {
7270     assert(dp->vol_list.busy);
7271     dp->vol_list.busy = 0;
7272     assert(pthread_cond_broadcast(&dp->vol_list.cv) == 0);
7273 }
7274
7275 /**
7276  * wait for all asynchronous operations on a VByPList to complete.
7277  *
7278  * @param[in] dp  pointer to disk partition object
7279  *
7280  * @pre VOL_LOCK is held.
7281  *
7282  * @post disk partition's VByP list is quiescent
7283  *
7284  * @note DAFS only
7285  *
7286  * @note This interface should be called before any attempt to
7287  *       traverse the VByPList.  It is permissible for a thread
7288  *       to gain exclusive access to the list, and then perform
7289  *       latent operations on the list asynchronously wrt the 
7290  *       VOL_LOCK.
7291  *
7292  * @warning if waiting is necessary, VOL_LOCK is dropped
7293  *
7294  * @see VVByPListEndExclusive_r
7295  * @see VVByPListBeginExclusive_r
7296  *
7297  * @internal volume package internal use only.
7298  */
7299 static void
7300 VVByPListWait_r(struct DiskPartition64 * dp)
7301 {
7302     while (dp->vol_list.busy) {
7303         VOL_CV_WAIT(&dp->vol_list.cv);
7304     }
7305 }
7306 #endif /* AFS_DEMAND_ATTACH_FS */
7307
7308 /***************************************************/
7309 /* Volume Cache Statistics routines                */
7310 /***************************************************/
7311
7312 void
7313 VPrintCacheStats_r(void)
7314 {
7315     afs_uint32 get_hi, get_lo, load_hi, load_lo;
7316     register struct VnodeClassInfo *vcp;
7317     vcp = &VnodeClassInfo[vLarge];
7318     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);
7319     vcp = &VnodeClassInfo[vSmall];
7320     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);
7321     SplitInt64(VStats.hdr_gets, get_hi, get_lo);
7322     SplitInt64(VStats.hdr_loads, load_hi, load_lo);
7323     Log("Volume header cache, %d entries, %d gets, %d replacements\n",
7324         VStats.hdr_cache_size, get_lo, load_lo);
7325 }
7326
7327 void
7328 VPrintCacheStats(void)
7329 {
7330     VOL_LOCK;
7331     VPrintCacheStats_r();
7332     VOL_UNLOCK;
7333 }
7334
7335 #ifdef AFS_DEMAND_ATTACH_FS
7336 static double
7337 UInt64ToDouble(afs_uint64 * x)
7338 {
7339     static double c32 = 4.0 * 1.073741824 * 1000000000.0;
7340     afs_uint32 h, l;
7341     SplitInt64(*x, h, l);
7342     return (((double)h) * c32) + ((double) l);
7343 }
7344
7345 static char *
7346 DoubleToPrintable(double x, char * buf, int len)
7347 {
7348     static double billion = 1000000000.0;
7349     afs_uint32 y[3];
7350
7351     y[0] = (afs_uint32) (x / (billion * billion));
7352     y[1] = (afs_uint32) ((x - (((double)y[0]) * billion * billion)) / billion);
7353     y[2] = (afs_uint32) (x - ((((double)y[0]) * billion * billion) + (((double)y[1]) * billion)));
7354
7355     if (y[0]) {
7356         snprintf(buf, len, "%d%09d%09d", y[0], y[1], y[2]);
7357     } else if (y[1]) {
7358         snprintf(buf, len, "%d%09d", y[1], y[2]);
7359     } else {
7360         snprintf(buf, len, "%d", y[2]);
7361     }
7362     buf[len-1] = '\0';
7363     return buf;
7364 }
7365
7366 struct VLRUExtStatsEntry {
7367     VolumeId volid;
7368 };
7369
7370 struct VLRUExtStats {
7371     afs_uint32 len;
7372     afs_uint32 used;
7373     struct {
7374         afs_uint32 start;
7375         afs_uint32 len;
7376     } queue_info[VLRU_QUEUE_INVALID];
7377     struct VLRUExtStatsEntry * vec;
7378 };
7379
7380 /** 
7381  * add a 256-entry fudge factor onto the vector in case state changes
7382  * out from under us.
7383  */
7384 #define VLRU_EXT_STATS_VEC_LEN_FUDGE   256
7385
7386 /**
7387  * collect extended statistics for the VLRU subsystem.
7388  *
7389  * @param[out] stats  pointer to stats structure to be populated
7390  * @param[in] nvols   number of volumes currently known to exist
7391  *
7392  * @pre VOL_LOCK held
7393  *
7394  * @post stats->vec allocated and populated
7395  *
7396  * @return operation status
7397  *    @retval 0 success
7398  *    @retval 1 failure
7399  */
7400 static int
7401 VVLRUExtStats_r(struct VLRUExtStats * stats, afs_uint32 nvols)
7402 {
7403     afs_uint32 cur, idx, len;
7404     struct rx_queue * qp, * nqp;
7405     Volume * vp;
7406     struct VLRUExtStatsEntry * vec;
7407
7408     len = nvols + VLRU_EXT_STATS_VEC_LEN_FUDGE;
7409     vec = stats->vec = calloc(len,
7410                               sizeof(struct VLRUExtStatsEntry));
7411     if (vec == NULL) {
7412         return 1;
7413     }
7414
7415     cur = 0;
7416     for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
7417         VLRU_Wait_r(&volume_LRU.q[idx]);
7418         VLRU_BeginExclusive_r(&volume_LRU.q[idx]);
7419         VOL_UNLOCK;
7420
7421         stats->queue_info[idx].start = cur;
7422
7423         for (queue_Scan(&volume_LRU.q[idx], qp, nqp, rx_queue)) {
7424             if (cur == len) {
7425                 /* out of space in vec */
7426                 break;
7427             }
7428             vp = (Volume *)((char *)qp - offsetof(Volume, vlru));
7429             vec[cur].volid = vp->hashid;
7430             cur++;
7431         }
7432
7433         stats->queue_info[idx].len = cur - stats->queue_info[idx].start;
7434
7435         VOL_LOCK;
7436         VLRU_EndExclusive_r(&volume_LRU.q[idx]);
7437     }
7438
7439     stats->len = len;
7440     stats->used = cur;
7441     return 0;
7442 }
7443
7444 #define ENUMTOSTRING(en)  #en
7445 #define ENUMCASE(en) \
7446     case en: \
7447         return ENUMTOSTRING(en); \
7448         break
7449
7450 static char *
7451 vlru_idx_to_string(int idx)
7452 {
7453     switch (idx) {
7454         ENUMCASE(VLRU_QUEUE_NEW);
7455         ENUMCASE(VLRU_QUEUE_MID);
7456         ENUMCASE(VLRU_QUEUE_OLD);
7457         ENUMCASE(VLRU_QUEUE_CANDIDATE);
7458         ENUMCASE(VLRU_QUEUE_HELD);
7459         ENUMCASE(VLRU_QUEUE_INVALID);
7460     default:
7461         return "**UNKNOWN**";
7462     }
7463 }
7464
7465 void
7466 VPrintExtendedCacheStats_r(int flags)
7467 {
7468     int i;
7469     afs_uint32 vol_sum = 0;
7470     struct stats {
7471         double min;
7472         double max;
7473         double sum;
7474         double avg;
7475     };
7476     struct stats looks, gets, reorders, len;
7477     struct stats ch_looks, ch_gets, ch_reorders;
7478     char pr_buf[4][32];
7479     VolumeHashChainHead *head;
7480     Volume *vp, *np;
7481     struct VLRUExtStats vlru_stats;
7482
7483     /* zero out stats */
7484     memset(&looks, 0, sizeof(struct stats));
7485     memset(&gets, 0, sizeof(struct stats));
7486     memset(&reorders, 0, sizeof(struct stats));
7487     memset(&len, 0, sizeof(struct stats));
7488     memset(&ch_looks, 0, sizeof(struct stats));
7489     memset(&ch_gets, 0, sizeof(struct stats));
7490     memset(&ch_reorders, 0, sizeof(struct stats));
7491
7492     for (i = 0; i < VolumeHashTable.Size; i++) {
7493         head = &VolumeHashTable.Table[i];
7494
7495         VHashWait_r(head);
7496         VHashBeginExclusive_r(head);
7497         VOL_UNLOCK;
7498
7499         ch_looks.sum    = UInt64ToDouble(&head->looks);
7500         ch_gets.sum     = UInt64ToDouble(&head->gets);
7501         ch_reorders.sum = UInt64ToDouble(&head->reorders);
7502
7503         /* update global statistics */
7504         {
7505             looks.sum    += ch_looks.sum;
7506             gets.sum     += ch_gets.sum;
7507             reorders.sum += ch_reorders.sum;
7508             len.sum      += (double)head->len;
7509             vol_sum      += head->len;
7510             
7511             if (i == 0) {
7512                 len.min      = (double) head->len;
7513                 len.max      = (double) head->len;
7514                 looks.min    = ch_looks.sum;
7515                 looks.max    = ch_looks.sum;
7516                 gets.min     = ch_gets.sum;
7517                 gets.max     = ch_gets.sum;
7518                 reorders.min = ch_reorders.sum;
7519                 reorders.max = ch_reorders.sum;
7520             } else {
7521                 if (((double)head->len) < len.min)
7522                     len.min = (double) head->len;
7523                 if (((double)head->len) > len.max)
7524                     len.max = (double) head->len;
7525                 if (ch_looks.sum < looks.min)
7526                     looks.min = ch_looks.sum;
7527                 else if (ch_looks.sum > looks.max)
7528                     looks.max = ch_looks.sum;
7529                 if (ch_gets.sum < gets.min)
7530                     gets.min = ch_gets.sum;
7531                 else if (ch_gets.sum > gets.max)
7532                     gets.max = ch_gets.sum;
7533                 if (ch_reorders.sum < reorders.min)
7534                     reorders.min = ch_reorders.sum;
7535                 else if (ch_reorders.sum > reorders.max)
7536                     reorders.max = ch_reorders.sum;
7537             }
7538         }
7539
7540         if ((flags & VOL_STATS_PER_CHAIN2) && queue_IsNotEmpty(head)) {
7541             /* compute detailed per-chain stats */
7542             struct stats hdr_loads, hdr_gets;
7543             double v_looks, v_loads, v_gets;
7544
7545             /* initialize stats with data from first element in chain */
7546             vp = queue_First(head, Volume);
7547             v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
7548             v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
7549             v_gets  = UInt64ToDouble(&vp->stats.hdr_gets);
7550             ch_gets.min = ch_gets.max = v_looks;
7551             hdr_loads.min = hdr_loads.max = v_loads;
7552             hdr_gets.min = hdr_gets.max = v_gets;
7553             hdr_loads.sum = hdr_gets.sum = 0;
7554
7555             vp = queue_Next(vp, Volume);
7556
7557             /* pull in stats from remaining elements in chain */
7558             for (queue_ScanFrom(head, vp, vp, np, Volume)) {
7559                 v_looks = UInt64ToDouble(&vp->stats.hash_lookups);
7560                 v_loads = UInt64ToDouble(&vp->stats.hdr_loads);
7561                 v_gets  = UInt64ToDouble(&vp->stats.hdr_gets);
7562
7563                 hdr_loads.sum += v_loads;
7564                 hdr_gets.sum += v_gets;
7565
7566                 if (v_looks < ch_gets.min)
7567                     ch_gets.min = v_looks;
7568                 else if (v_looks > ch_gets.max)
7569                     ch_gets.max = v_looks;
7570
7571                 if (v_loads < hdr_loads.min)
7572                     hdr_loads.min = v_loads;
7573                 else if (v_loads > hdr_loads.max)
7574                     hdr_loads.max = v_loads;
7575
7576                 if (v_gets < hdr_gets.min)
7577                     hdr_gets.min = v_gets;
7578                 else if (v_gets > hdr_gets.max)
7579                     hdr_gets.max = v_gets;
7580             }
7581
7582             /* compute per-chain averages */
7583             ch_gets.avg = ch_gets.sum / ((double)head->len);
7584             hdr_loads.avg = hdr_loads.sum / ((double)head->len);
7585             hdr_gets.avg = hdr_gets.sum / ((double)head->len);
7586
7587             /* dump per-chain stats */
7588             Log("Volume hash chain %d : len=%d, looks=%s, reorders=%s\n",
7589                 i, head->len, 
7590                 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
7591                 DoubleToPrintable(ch_reorders.sum, pr_buf[1], sizeof(pr_buf[1])));
7592             Log("\tVolume gets : min=%s, max=%s, avg=%s, total=%s\n",
7593                 DoubleToPrintable(ch_gets.min, pr_buf[0], sizeof(pr_buf[0])),
7594                 DoubleToPrintable(ch_gets.max, pr_buf[1], sizeof(pr_buf[1])),
7595                 DoubleToPrintable(ch_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
7596                 DoubleToPrintable(ch_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
7597             Log("\tHDR gets : min=%s, max=%s, avg=%s, total=%s\n",
7598                 DoubleToPrintable(hdr_gets.min, pr_buf[0], sizeof(pr_buf[0])),
7599                 DoubleToPrintable(hdr_gets.max, pr_buf[1], sizeof(pr_buf[1])),
7600                 DoubleToPrintable(hdr_gets.avg, pr_buf[2], sizeof(pr_buf[2])),
7601                 DoubleToPrintable(hdr_gets.sum, pr_buf[3], sizeof(pr_buf[3])));
7602             Log("\tHDR loads : min=%s, max=%s, avg=%s, total=%s\n",
7603                 DoubleToPrintable(hdr_loads.min, pr_buf[0], sizeof(pr_buf[0])),
7604                 DoubleToPrintable(hdr_loads.max, pr_buf[1], sizeof(pr_buf[1])),
7605                 DoubleToPrintable(hdr_loads.avg, pr_buf[2], sizeof(pr_buf[2])),
7606                 DoubleToPrintable(hdr_loads.sum, pr_buf[3], sizeof(pr_buf[3])));
7607         } else if (flags & VOL_STATS_PER_CHAIN) {
7608             /* dump simple per-chain stats */
7609             Log("Volume hash chain %d : len=%d, looks=%s, gets=%s, reorders=%s\n",
7610                 i, head->len, 
7611                 DoubleToPrintable(ch_looks.sum, pr_buf[0], sizeof(pr_buf[0])),
7612                 DoubleToPrintable(ch_gets.sum, pr_buf[1], sizeof(pr_buf[1])),
7613                 DoubleToPrintable(ch_reorders.sum, pr_buf[2], sizeof(pr_buf[2])));
7614         }
7615
7616         VOL_LOCK;
7617         VHashEndExclusive_r(head);
7618     }
7619
7620     VOL_UNLOCK;
7621
7622     /* compute global averages */
7623     len.avg      = len.sum      / ((double)VolumeHashTable.Size);
7624     looks.avg    = looks.sum    / ((double)VolumeHashTable.Size);
7625     gets.avg     = gets.sum     / ((double)VolumeHashTable.Size);
7626     reorders.avg = reorders.sum / ((double)VolumeHashTable.Size);
7627
7628     /* dump global stats */
7629     Log("Volume hash summary: %d buckets\n", VolumeHashTable.Size);
7630     Log(" chain length : min=%s, max=%s, avg=%s, total=%s\n",
7631         DoubleToPrintable(len.min, pr_buf[0], sizeof(pr_buf[0])),
7632         DoubleToPrintable(len.max, pr_buf[1], sizeof(pr_buf[1])),
7633         DoubleToPrintable(len.avg, pr_buf[2], sizeof(pr_buf[2])),
7634         DoubleToPrintable(len.sum, pr_buf[3], sizeof(pr_buf[3])));
7635     Log(" looks : min=%s, max=%s, avg=%s, total=%s\n",
7636         DoubleToPrintable(looks.min, pr_buf[0], sizeof(pr_buf[0])),
7637         DoubleToPrintable(looks.max, pr_buf[1], sizeof(pr_buf[1])),
7638         DoubleToPrintable(looks.avg, pr_buf[2], sizeof(pr_buf[2])),
7639         DoubleToPrintable(looks.sum, pr_buf[3], sizeof(pr_buf[3])));
7640     Log(" gets : min=%s, max=%s, avg=%s, total=%s\n",
7641         DoubleToPrintable(gets.min, pr_buf[0], sizeof(pr_buf[0])),
7642         DoubleToPrintable(gets.max, pr_buf[1], sizeof(pr_buf[1])),
7643         DoubleToPrintable(gets.avg, pr_buf[2], sizeof(pr_buf[2])),
7644         DoubleToPrintable(gets.sum, pr_buf[3], sizeof(pr_buf[3])));
7645     Log(" reorders : min=%s, max=%s, avg=%s, total=%s\n",
7646         DoubleToPrintable(reorders.min, pr_buf[0], sizeof(pr_buf[0])),
7647         DoubleToPrintable(reorders.max, pr_buf[1], sizeof(pr_buf[1])),
7648         DoubleToPrintable(reorders.avg, pr_buf[2], sizeof(pr_buf[2])),
7649         DoubleToPrintable(reorders.sum, pr_buf[3], sizeof(pr_buf[3])));
7650
7651     /* print extended disk related statistics */
7652     {
7653         struct DiskPartition64 * diskP;
7654         afs_uint32 vol_count[VOLMAXPARTS+1];
7655         byte part_exists[VOLMAXPARTS+1];
7656         Device id;
7657         int i;
7658
7659         memset(vol_count, 0, sizeof(vol_count));
7660         memset(part_exists, 0, sizeof(part_exists));
7661
7662         VOL_LOCK;
7663
7664         for (diskP = DiskPartitionList; diskP; diskP = diskP->next) {
7665             id = diskP->index;
7666             vol_count[id] = diskP->vol_list.len;
7667             part_exists[id] = 1;
7668         }
7669
7670         VOL_UNLOCK;
7671         for (i = 0; i <= VOLMAXPARTS; i++) {
7672             if (part_exists[i]) {
7673                 /* XXX while this is currently safe, it is a violation
7674                  *     of the VGetPartitionById_r interface contract. */
7675                 diskP = VGetPartitionById_r(i, 0);
7676                 if (diskP) {
7677                     Log("Partition %s has %d online volumes\n", 
7678                         VPartitionPath(diskP), diskP->vol_list.len);
7679                 }
7680             }
7681         }
7682         VOL_LOCK;
7683     }
7684
7685     /* print extended VLRU statistics */
7686     if (VVLRUExtStats_r(&vlru_stats, vol_sum) == 0) {
7687         afs_uint32 idx, cur, lpos;
7688         VOL_UNLOCK;
7689         VolumeId line[5];
7690
7691         Log("VLRU State Dump:\n\n");
7692
7693         for (idx = VLRU_QUEUE_NEW; idx < VLRU_QUEUE_INVALID; idx++) {
7694             Log("\t%s:\n", vlru_idx_to_string(idx));
7695
7696             lpos = 0;
7697             for (cur = vlru_stats.queue_info[idx].start;
7698                  cur < vlru_stats.queue_info[idx].len;
7699                  cur++) {
7700                 line[lpos++] = vlru_stats.vec[cur].volid;
7701                 if (lpos==5) {
7702                     Log("\t\t%u, %u, %u, %u, %u,\n",
7703                         line[0], line[1], line[2], line[3], line[4]);
7704                     lpos = 0;
7705                 }
7706             }
7707
7708             if (lpos) {
7709                 while (lpos < 5) {
7710                     line[lpos++] = 0;
7711                 }
7712                 Log("\t\t%u, %u, %u, %u, %u\n",
7713                     line[0], line[1], line[2], line[3], line[4]);
7714             }
7715             Log("\n");
7716         }
7717
7718         free(vlru_stats.vec);
7719
7720         VOL_LOCK;
7721     }
7722 }
7723
7724 void
7725 VPrintExtendedCacheStats(int flags)
7726 {
7727     VOL_LOCK;
7728     VPrintExtendedCacheStats_r(flags);
7729     VOL_UNLOCK;
7730 }
7731 #endif /* AFS_DEMAND_ATTACH_FS */
7732
7733 afs_int32
7734 VCanScheduleSalvage(void)
7735 {
7736     return vol_opts.canScheduleSalvage;
7737 }
7738
7739 afs_int32
7740 VCanUseFSSYNC(void)
7741 {
7742     return vol_opts.canUseFSSYNC;
7743 }
7744
7745 afs_int32
7746 VCanUseSALVSYNC(void)
7747 {
7748     return vol_opts.canUseSALVSYNC;
7749 }