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