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