b94f80f76cde8ee84ac81c64f6cd2f20a4fbe1d1
[openafs.git] / src / WINNT / afsd / cm_scache.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
10 #include <afsconfig.h>
11 #include <afs/param.h>
12 #include <afs/stds.h>
13
14 #include <roken.h>
15
16 #include <windows.h>
17 #include <winsock2.h>
18 #include <nb30.h>
19 #include <malloc.h>
20 #include <string.h>
21 #include <stdlib.h>
22 #include <osi.h>
23
24 #include "afsd.h"
25 #include "cm_btree.h"
26 #include <afs/unified_afs.h>
27
28 /*extern void afsi_log(char *pattern, ...);*/
29
30 extern osi_hyper_t hzero;
31
32 /* File locks */
33 osi_queue_t *cm_allFileLocks;
34 osi_queue_t *cm_freeFileLocks;
35 unsigned long cm_lockRefreshCycle;
36
37 /* lock for globals */
38 osi_rwlock_t cm_scacheLock;
39
40 /* Dummy scache entry for use with pioctl fids */
41 cm_scache_t cm_fakeSCache;
42
43 osi_queue_t * cm_allFreeWaiters;        /* protected by cm_scacheLock */
44
45 #ifdef AFS_FREELANCE_CLIENT
46 extern osi_mutex_t cm_Freelance_Lock;
47 #endif
48
49 cm_scache_t *
50 cm_RootSCachep(cm_user_t *userp, cm_req_t *reqp)
51 {
52     afs_int32 code;
53
54     lock_ObtainWrite(&cm_data.rootSCachep->rw);
55     code = cm_SyncOp(cm_data.rootSCachep, NULL, userp, reqp, 0,
56                       CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_NEEDCALLBACK);
57     if (!code)
58         cm_SyncOpDone(cm_data.rootSCachep, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
59     lock_ReleaseWrite(&cm_data.rootSCachep->rw);
60
61     return cm_data.rootSCachep;
62 }
63
64
65 /* must be called with cm_scacheLock write-locked! */
66 void cm_AdjustScacheLRU(cm_scache_t *scp)
67 {
68     lock_AssertWrite(&cm_scacheLock);
69     osi_QRemoveHT((osi_queue_t **) &cm_data.scacheLRUFirstp, (osi_queue_t **) &cm_data.scacheLRULastp, &scp->q);
70     if (scp->flags & CM_SCACHEFLAG_DELETED) {
71         /* Since it has been deleted make it the first to be recycled. */
72         osi_QAddT((osi_queue_t **) &cm_data.scacheLRUFirstp, (osi_queue_t **) &cm_data.scacheLRULastp, &scp->q);
73     } else {
74         osi_QAddH((osi_queue_t **) &cm_data.scacheLRUFirstp, (osi_queue_t **) &cm_data.scacheLRULastp, &scp->q);
75     }
76 }
77
78 /* call with cm_scacheLock write-locked and scp rw held */
79 void cm_RemoveSCacheFromHashTable(cm_scache_t *scp)
80 {
81     cm_scache_t **lscpp;
82     cm_scache_t *tscp;
83     int i;
84
85     lock_AssertWrite(&cm_scacheLock);
86     lock_AssertWrite(&scp->rw);
87     if (scp->flags & CM_SCACHEFLAG_INHASH) {
88         /* hash it out first */
89         i = CM_SCACHE_HASH(&scp->fid);
90         for (lscpp = &cm_data.scacheHashTablep[i], tscp = cm_data.scacheHashTablep[i];
91              tscp;
92              lscpp = &tscp->nextp, tscp = tscp->nextp) {
93             if (tscp == scp) {
94                 *lscpp = scp->nextp;
95                 scp->nextp = NULL;
96                 _InterlockedAnd(&scp->flags, ~CM_SCACHEFLAG_INHASH);
97                 break;
98             }
99         }
100     }
101 }
102
103 /* called with cm_scacheLock and scp write-locked */
104 void cm_ResetSCacheDirectory(cm_scache_t *scp, afs_int32 dirlock)
105 {
106 #ifdef USE_BPLUS
107     /* destroy directory Bplus Tree */
108     if (scp->dirBplus) {
109         LARGE_INTEGER start, end;
110
111         if (!dirlock && !lock_TryWrite(&scp->dirlock)) {
112             /*
113              * We are not holding the dirlock and obtaining it
114              * requires that we drop the scp->rw.  As a result
115              * we will leave the dirBplus tree intact but
116              * invalidate the version number so that whatever
117              * operation is currently active can safely complete
118              * but the contents will be ignored on the next
119              * directory operation.
120              */
121             scp->dirDataVersion = CM_SCACHE_VERSION_BAD;
122             return;
123         }
124
125         QueryPerformanceCounter(&start);
126         bplus_free_tree++;
127         freeBtree(scp->dirBplus);
128         scp->dirBplus = NULL;
129         scp->dirDataVersion = CM_SCACHE_VERSION_BAD;
130         QueryPerformanceCounter(&end);
131
132         if (!dirlock)
133             lock_ReleaseWrite(&scp->dirlock);
134
135         bplus_free_time += (end.QuadPart - start.QuadPart);
136     }
137 #endif
138 }
139
140 /* called with cm_scacheLock and scp write-locked; recycles an existing scp. */
141 long cm_RecycleSCache(cm_scache_t *scp, afs_int32 flags)
142 {
143     cm_fid_t fid;
144     afs_uint32 fileType;
145     int callback;
146
147     lock_AssertWrite(&cm_scacheLock);
148     lock_AssertWrite(&scp->rw);
149
150     if (scp->refCount != 0) {
151         return -1;
152     }
153
154
155     if (scp->flags & CM_SCACHEFLAG_SMB_FID) {
156         osi_Log1(afsd_logp,"cm_RecycleSCache CM_SCACHEFLAG_SMB_FID detected scp 0x%p", scp);
157 #ifdef DEBUG
158         osi_panic("cm_RecycleSCache CM_SCACHEFLAG_SMB_FID detected",__FILE__,__LINE__);
159 #endif
160         return -1;
161     }
162
163     if (scp->redirBufCount != 0) {
164         return -1;
165     }
166
167     fid = scp->fid;
168     fileType = scp->fileType;
169     callback = scp->cbExpires ? 1 : 0;
170
171     cm_RemoveSCacheFromHashTable(scp);
172
173     /* invalidate so next merge works fine;
174      * also initialize some flags */
175     scp->fileType = 0;
176     _InterlockedAnd(&scp->flags,
177                     ~(CM_SCACHEFLAG_STATD
178                      | CM_SCACHEFLAG_DELETED
179                      | CM_SCACHEFLAG_RO
180                      | CM_SCACHEFLAG_PURERO
181                      | CM_SCACHEFLAG_OVERQUOTA
182                      | CM_SCACHEFLAG_OUTOFSPACE
183                      | CM_SCACHEFLAG_EACCESS));
184     scp->serverModTime = 0;
185     scp->dataVersion = CM_SCACHE_VERSION_BAD;
186     scp->bufDataVersionLow = CM_SCACHE_VERSION_BAD;
187     scp->bulkStatProgress = hzero;
188     scp->waitCount = 0;
189     scp->waitQueueT = NULL;
190
191     if (scp->cbServerp) {
192         cm_PutServer(scp->cbServerp);
193         scp->cbServerp = NULL;
194     }
195     scp->cbExpires = 0;
196     scp->cbIssued = 0;
197     scp->volumeCreationDate = 0;
198
199     scp->fid.vnode = 0;
200     scp->fid.volume = 0;
201     scp->fid.unique = 0;
202     scp->fid.cell = 0;
203     scp->fid.hash = 0;
204
205     /* remove from dnlc */
206     cm_dnlcPurgedp(scp);
207     cm_dnlcPurgevp(scp);
208
209     /* discard cached status; if non-zero, Close
210      * tried to store this to server but failed */
211     scp->mask = 0;
212
213     /* discard symlink info */
214     scp->mountPointStringp[0] = '\0';
215     memset(&scp->mountRootFid, 0, sizeof(cm_fid_t));
216     memset(&scp->dotdotFid, 0, sizeof(cm_fid_t));
217
218     /* reset locking info */
219     scp->fileLocksH = NULL;
220     scp->fileLocksT = NULL;
221     scp->serverLock = (-1);
222     scp->exclusiveLocks = 0;
223     scp->sharedLocks = 0;
224     scp->lockDataVersion = CM_SCACHE_VERSION_BAD;
225     scp->fsLockCount = 0;
226
227     /* not locked, but there can be no references to this guy
228      * while we hold the global refcount lock.
229      */
230     cm_FreeAllACLEnts(scp);
231
232     cm_ResetSCacheDirectory(scp, 0);
233
234     if (RDR_Initialized && callback) {
235         /*
236         * We drop the cm_scacheLock because it may be required to
237         * satisfy an ioctl request from the redirector.  It should
238         * be safe to hold the scp->rw lock here because at this
239         * point (a) the object has just been recycled so the fid
240         * is nul and there are no requests that could possibly
241         * be issued by the redirector that would depend upon it.
242         */
243         lock_ReleaseWrite(&cm_scacheLock);
244         RDR_InvalidateObject( fid.cell, fid.volume, fid.vnode,
245                               fid.unique, fid.hash,
246                               fileType, AFS_INVALIDATE_EXPIRED);
247         lock_ObtainWrite(&cm_scacheLock);
248     }
249
250     return 0;
251 }
252
253
254 /*
255  * called with cm_scacheLock write-locked; find a vnode to recycle.
256  * Can allocate a new one if desperate, or if below quota (cm_data.maxSCaches).
257  * returns scp->rw write-locked.
258  */
259 cm_scache_t *
260 cm_GetNewSCache(afs_uint32 locked)
261 {
262     cm_scache_t *scp = NULL;
263     cm_scache_t *scp_prev = NULL;
264     cm_scache_t *scp_next = NULL;
265     int attempt = 0;
266
267     if (locked)
268         lock_AssertWrite(&cm_scacheLock);
269     else
270         lock_ObtainWrite(&cm_scacheLock);
271
272     if (cm_data.currentSCaches >= cm_data.maxSCaches) {
273         /* There were no deleted scache objects that we could use.  Try to find
274          * one that simply hasn't been used in a while.
275          */
276         for (attempt = 0 ; attempt < 128; attempt++) {
277             afs_uint32 count = 0;
278
279             for ( scp = cm_data.scacheLRULastp;
280                   scp;
281                   scp = (cm_scache_t *) osi_QPrev(&scp->q))
282             {
283                 /*
284                  * We save the prev and next pointers in the
285                  * LRU because we are going to drop the cm_scacheLock and
286                  * the order of the list could change out from beneath us.
287                  * If both changed, it means that this entry has been moved
288                  * within the LRU and it should no longer be recycled.
289                  */
290                 scp_prev = (cm_scache_t *) osi_QPrev(&scp->q);
291                 scp_next = (cm_scache_t *) osi_QNext(&scp->q);
292                 count++;
293
294                 /* It is possible for the refCount to be zero and for there still
295                  * to be outstanding dirty buffers.  If there are dirty buffers,
296                  * we must not recycle the scp.
297                  *
298                  * If the object is in use by the redirector, then avoid recycling
299                  * it unless we have to.
300                  */
301                 if (scp->refCount == 0 && scp->bufReadsp == NULL && scp->bufWritesp == NULL) {
302                     afs_uint32 buf_dirty = 0;
303                     afs_uint32 buf_rdr = 0;
304
305                     lock_ReleaseWrite(&cm_scacheLock);
306                     buf_dirty = buf_DirtyBuffersExist(&scp->fid);
307                     if (!buf_dirty)
308                         buf_rdr = buf_RDRBuffersExist(&scp->fid);
309
310                     if (!buf_dirty && !buf_rdr) {
311                         cm_fid_t   fid;
312                         afs_uint32 fileType;
313
314                         if (!lock_TryWrite(&scp->rw)) {
315                             lock_ObtainWrite(&cm_scacheLock);
316                             if (scp_prev != (cm_scache_t *) osi_QPrev(&scp->q) &&
317                                 scp_next != (cm_scache_t *) osi_QNext(&scp->q))
318                                 break;
319                             else
320                                 continue;
321                         }
322
323                         lock_ObtainWrite(&cm_scacheLock);
324                         if (scp_prev != (cm_scache_t *) osi_QPrev(&scp->q) &&
325                             scp_next != (cm_scache_t *) osi_QNext(&scp->q))
326                         {
327                             lock_ReleaseWrite(&scp->rw);
328                             break;
329                         }
330
331                         /* Found a likely candidate.  Save type and fid in case we succeed */
332                         fid = scp->fid;
333                         fileType = scp->fileType;
334
335                         if (!cm_RecycleSCache(scp, 0)) {
336                             /* we found an entry, so return it.
337                              * remove from the LRU queue and put it back at the
338                              * head of the LRU queue.
339                              */
340                             cm_AdjustScacheLRU(scp);
341
342                             /* and we're done - SUCCESS */
343                             osi_assertx(!(scp->flags & CM_SCACHEFLAG_INHASH), "CM_SCACHEFLAG_INHASH set");
344                             goto done;
345                         }
346                         lock_ReleaseWrite(&scp->rw);
347                     } else if (!buf_rdr) {
348                         osi_Log1(afsd_logp, "GetNewSCache dirty buffers scp 0x%p", scp);
349                         lock_ObtainWrite(&cm_scacheLock);
350                         if (scp_prev != (cm_scache_t *) osi_QPrev(&scp->q) &&
351                             scp_next != (cm_scache_t *) osi_QNext(&scp->q))
352                             break;
353                     } else {
354                         osi_Log1(afsd_logp,"GetNewSCache redirector is holding extents scp 0x%p", scp);
355                         lock_ObtainWrite(&cm_scacheLock);
356                         if (scp_prev != (cm_scache_t *) osi_QPrev(&scp->q) &&
357                             scp_next != (cm_scache_t *) osi_QNext(&scp->q))
358                             break;
359                     }
360                 }
361             } /* for */
362
363             osi_Log2(afsd_logp, "GetNewSCache all scache entries in use (attempt = %d, count = %u)", attempt, count);
364         }
365         /* FAILURE */
366         scp = NULL;
367         goto done;
368     }
369
370     /* if we get here, we should allocate a new scache entry.  We either are below
371      * quota or we have a leak and need to allocate a new one to avoid panicing.
372      */
373     scp = cm_data.scacheBaseAddress + cm_data.currentSCaches;
374     osi_assertx(scp >= cm_data.scacheBaseAddress && scp < (cm_scache_t *)cm_data.scacheHashTablep,
375                 "invalid cm_scache_t address");
376     memset(scp, 0, sizeof(cm_scache_t));
377     scp->magic = CM_SCACHE_MAGIC;
378     lock_InitializeRWLock(&scp->rw, "cm_scache_t rw", LOCK_HIERARCHY_SCACHE);
379     osi_assertx(lock_TryWrite(&scp->rw), "cm_scache_t rw held after allocation");
380     lock_InitializeRWLock(&scp->bufCreateLock, "cm_scache_t bufCreateLock", LOCK_HIERARCHY_SCACHE_BUFCREATE);
381 #ifdef USE_BPLUS
382     lock_InitializeRWLock(&scp->dirlock, "cm_scache_t dirlock", LOCK_HIERARCHY_SCACHE_DIRLOCK);
383 #endif
384     lock_InitializeMutex(&scp->redirMx, "cm_scache_t redirMx", LOCK_HIERARCHY_SCACHE_REDIRMX);
385     scp->serverLock = -1;
386     scp->dataVersion = CM_SCACHE_VERSION_BAD;
387     scp->bufDataVersionLow = CM_SCACHE_VERSION_BAD;
388     scp->lockDataVersion = CM_SCACHE_VERSION_BAD;
389
390     /* and put it in the LRU queue */
391     osi_QAddH((osi_queue_t **) &cm_data.scacheLRUFirstp, (osi_queue_t **)&cm_data.scacheLRULastp, &scp->q);
392     cm_data.currentSCaches++;
393     cm_dnlcPurgedp(scp); /* make doubly sure that this is not in dnlc */
394     cm_dnlcPurgevp(scp);
395     scp->allNextp = cm_data.allSCachesp;
396     cm_data.allSCachesp = scp;
397
398   done:
399     if (!locked)
400         lock_ReleaseWrite(&cm_scacheLock);
401
402     return scp;
403 }
404
405 void cm_SetFid(cm_fid_t *fidp, afs_uint32 cell, afs_uint32 volume, afs_uint32 vnode, afs_uint32 unique)
406 {
407     fidp->cell = cell;
408     fidp->volume = volume;
409     fidp->vnode = vnode;
410     fidp->unique = unique;
411     CM_FID_GEN_HASH(fidp);
412 }
413
414 /* like strcmp, only for fids */
415 __inline int cm_FidCmp(cm_fid_t *ap, cm_fid_t *bp)
416 {
417     if (ap->hash != bp->hash)
418         return 1;
419     if (ap->vnode != bp->vnode)
420         return 1;
421     if (ap->volume != bp->volume)
422         return 1;
423     if (ap->unique != bp->unique)
424         return 1;
425     if (ap->cell != bp->cell)
426         return 1;
427     return 0;
428 }
429
430 void cm_fakeSCacheInit(int newFile)
431 {
432     if ( newFile ) {
433         memset(&cm_data.fakeSCache, 0, sizeof(cm_scache_t));
434         cm_data.fakeSCache.magic = CM_SCACHE_MAGIC;
435         cm_data.fakeSCache.cbServerp = (struct cm_server *)(-1);
436         cm_data.fakeSCache.cbExpires = (time_t)-1;
437         cm_data.fakeSCache.cbExpires = time(NULL);
438         /* can leave clientModTime at 0 */
439         cm_data.fakeSCache.fileType = CM_SCACHETYPE_FILE;
440         cm_data.fakeSCache.unixModeBits = 0777;
441         cm_data.fakeSCache.length.LowPart = 1000;
442         cm_data.fakeSCache.linkCount = 1;
443         cm_data.fakeSCache.refCount = 1;
444         cm_data.fakeSCache.serverLock = -1;
445         cm_data.fakeSCache.dataVersion = CM_SCACHE_VERSION_BAD;
446     }
447     lock_InitializeRWLock(&cm_data.fakeSCache.rw, "cm_scache_t rw", LOCK_HIERARCHY_SCACHE);
448     lock_InitializeRWLock(&cm_data.fakeSCache.bufCreateLock, "cm_scache_t bufCreateLock", LOCK_HIERARCHY_SCACHE_BUFCREATE);
449     lock_InitializeRWLock(&cm_data.fakeSCache.dirlock, "cm_scache_t dirlock", LOCK_HIERARCHY_SCACHE_DIRLOCK);
450     lock_InitializeMutex(&cm_data.fakeSCache.redirMx, "cm_scache_t redirMx", LOCK_HIERARCHY_SCACHE_REDIRMX);
451 }
452
453 long
454 cm_ValidateSCache(void)
455 {
456     cm_scache_t * scp, *lscp;
457     long i;
458
459     if ( cm_data.scacheLRUFirstp == NULL && cm_data.scacheLRULastp != NULL ||
460          cm_data.scacheLRUFirstp != NULL && cm_data.scacheLRULastp == NULL) {
461         afsi_log("cm_ValidateSCache failure: inconsistent LRU pointers");
462         fprintf(stderr, "cm_ValidateSCache failure: inconsistent LRU pointers\n");
463         return -17;
464     }
465
466     for ( scp = cm_data.scacheLRUFirstp, lscp = NULL, i = 0;
467           scp;
468           lscp = scp, scp = (cm_scache_t *) osi_QNext(&scp->q), i++ ) {
469         if (scp->magic != CM_SCACHE_MAGIC) {
470             afsi_log("cm_ValidateSCache failure: scp->magic != CM_SCACHE_MAGIC");
471             fprintf(stderr, "cm_ValidateSCache failure: scp->magic != CM_SCACHE_MAGIC\n");
472             return -1;
473         }
474         if (scp->nextp && scp->nextp->magic != CM_SCACHE_MAGIC) {
475             afsi_log("cm_ValidateSCache failure: scp->nextp->magic != CM_SCACHE_MAGIC");
476             fprintf(stderr, "cm_ValidateSCache failure: scp->nextp->magic != CM_SCACHE_MAGIC\n");
477             return -2;
478         }
479         if (scp->randomACLp && scp->randomACLp->magic != CM_ACLENT_MAGIC) {
480             afsi_log("cm_ValidateSCache failure: scp->randomACLp->magic != CM_ACLENT_MAGIC");
481             fprintf(stderr, "cm_ValidateSCache failure: scp->randomACLp->magic != CM_ACLENT_MAGIC\n");
482             return -3;
483         }
484         if (i > cm_data.currentSCaches ) {
485             afsi_log("cm_ValidateSCache failure: LRU First queue loops");
486             fprintf(stderr, "cm_ValidateSCache failure: LUR First queue loops\n");
487             return -13;
488         }
489         if (lscp != (cm_scache_t *) osi_QPrev(&scp->q)) {
490             afsi_log("cm_ValidateSCache failure: QPrev(scp) != previous");
491             fprintf(stderr, "cm_ValidateSCache failure: QPrev(scp) != previous\n");
492             return -15;
493         }
494     }
495
496     for ( scp = cm_data.scacheLRULastp, lscp = NULL, i = 0; scp;
497           lscp = scp, scp = (cm_scache_t *) osi_QPrev(&scp->q), i++ ) {
498         if (scp->magic != CM_SCACHE_MAGIC) {
499             afsi_log("cm_ValidateSCache failure: scp->magic != CM_SCACHE_MAGIC");
500             fprintf(stderr, "cm_ValidateSCache failure: scp->magic != CM_SCACHE_MAGIC\n");
501             return -5;
502         }
503         if (scp->nextp && scp->nextp->magic != CM_SCACHE_MAGIC) {
504             afsi_log("cm_ValidateSCache failure: scp->nextp->magic != CM_SCACHE_MAGIC");
505             fprintf(stderr, "cm_ValidateSCache failure: scp->nextp->magic != CM_SCACHE_MAGIC\n");
506             return -6;
507         }
508         if (scp->randomACLp && scp->randomACLp->magic != CM_ACLENT_MAGIC) {
509             afsi_log("cm_ValidateSCache failure: scp->randomACLp->magic != CM_ACLENT_MAGIC");
510             fprintf(stderr, "cm_ValidateSCache failure: scp->randomACLp->magic != CM_ACLENT_MAGIC\n");
511             return -7;
512         }
513         if (i > cm_data.currentSCaches ) {
514             afsi_log("cm_ValidateSCache failure: LRU Last queue loops");
515             fprintf(stderr, "cm_ValidateSCache failure: LUR Last queue loops\n");
516             return -14;
517         }
518         if (lscp != (cm_scache_t *) osi_QNext(&scp->q)) {
519             afsi_log("cm_ValidateSCache failure: QNext(scp) != next");
520             fprintf(stderr, "cm_ValidateSCache failure: QNext(scp) != next\n");
521             return -16;
522         }
523     }
524
525     for ( i=0; i < cm_data.scacheHashTableSize; i++ ) {
526         for ( scp = cm_data.scacheHashTablep[i]; scp; scp = scp->nextp ) {
527             afs_uint32 hash;
528             hash = CM_SCACHE_HASH(&scp->fid);
529             if (scp->magic != CM_SCACHE_MAGIC) {
530                 afsi_log("cm_ValidateSCache failure: scp->magic != CM_SCACHE_MAGIC");
531                 fprintf(stderr, "cm_ValidateSCache failure: scp->magic != CM_SCACHE_MAGIC\n");
532                 return -9;
533             }
534             if (scp->nextp && scp->nextp->magic != CM_SCACHE_MAGIC) {
535                 afsi_log("cm_ValidateSCache failure: scp->nextp->magic != CM_SCACHE_MAGIC");
536                 fprintf(stderr, "cm_ValidateSCache failure: scp->nextp->magic != CM_SCACHE_MAGIC\n");
537                 return -10;
538             }
539             if (scp->randomACLp && scp->randomACLp->magic != CM_ACLENT_MAGIC) {
540                 afsi_log("cm_ValidateSCache failure: scp->randomACLp->magic != CM_ACLENT_MAGIC");
541                 fprintf(stderr, "cm_ValidateSCache failure: scp->randomACLp->magic != CM_ACLENT_MAGIC\n");
542                 return -11;
543             }
544             if (hash != i) {
545                 afsi_log("cm_ValidateSCache failure: scp hash != hash index");
546                 fprintf(stderr, "cm_ValidateSCache failure: scp hash != hash index\n");
547                 return -13;
548             }
549         }
550     }
551
552     return cm_dnlcValidate();
553 }
554
555 void
556 cm_SuspendSCache(void)
557 {
558     cm_scache_t * scp;
559     time_t now;
560
561     cm_GiveUpAllCallbacksAllServersMulti(TRUE);
562
563     /*
564      * After this call all servers are marked down.
565      * Do not clear the callbacks, instead change the
566      * expiration time so that the callbacks will be expired
567      * when the servers are marked back up.  However, we
568      * want the callbacks to be preserved as long as the
569      * servers are down.  That way if the machine resumes
570      * without network, the stat cache item will still be
571      * considered valid.
572      */
573     now = time(NULL);
574
575     lock_ObtainWrite(&cm_scacheLock);
576     for ( scp = cm_data.allSCachesp; scp; scp = scp->allNextp ) {
577         if (scp->cbServerp) {
578             if (scp->flags & CM_SCACHEFLAG_PURERO) {
579                 cm_volume_t *volp = cm_GetVolumeByFID(&scp->fid);
580                 if (volp) {
581                     if (volp->cbExpiresRO == scp->cbExpires)
582                         volp->cbExpiresRO = now+1;
583                     cm_PutVolume(volp);
584                 }
585             }
586             scp->cbExpires = now+1;
587         }
588     }
589     lock_ReleaseWrite(&cm_scacheLock);
590 }
591
592 long
593 cm_ShutdownSCache(void)
594 {
595     cm_scache_t * scp, * nextp;
596
597     cm_GiveUpAllCallbacksAllServersMulti(FALSE);
598
599     lock_ObtainWrite(&cm_scacheLock);
600
601     for ( scp = cm_data.allSCachesp; scp;
602           scp = nextp ) {
603         nextp = scp->allNextp;
604         lock_ReleaseWrite(&cm_scacheLock);
605 #ifdef USE_BPLUS
606         lock_ObtainWrite(&scp->dirlock);
607 #endif
608         lock_ObtainWrite(&scp->rw);
609         lock_ObtainWrite(&cm_scacheLock);
610
611         if (scp->randomACLp) {
612             cm_FreeAllACLEnts(scp);
613         }
614
615         if (scp->cbServerp) {
616             cm_PutServer(scp->cbServerp);
617             scp->cbServerp = NULL;
618         }
619         scp->cbExpires = 0;
620         scp->cbIssued = 0;
621         _InterlockedAnd(&scp->flags, ~CM_SCACHEFLAG_CALLBACK);
622         lock_ReleaseWrite(&scp->rw);
623
624 #ifdef USE_BPLUS
625         if (scp->dirBplus)
626             freeBtree(scp->dirBplus);
627         scp->dirBplus = NULL;
628         scp->dirDataVersion = CM_SCACHE_VERSION_BAD;
629         lock_ReleaseWrite(&scp->dirlock);
630         lock_FinalizeRWLock(&scp->dirlock);
631 #endif
632         lock_FinalizeRWLock(&scp->rw);
633         lock_FinalizeRWLock(&scp->bufCreateLock);
634         lock_FinalizeMutex(&scp->redirMx);
635     }
636     lock_ReleaseWrite(&cm_scacheLock);
637
638     return cm_dnlcShutdown();
639 }
640
641 void cm_InitSCache(int newFile, long maxSCaches)
642 {
643     static osi_once_t once;
644
645     if (osi_Once(&once)) {
646         lock_InitializeRWLock(&cm_scacheLock, "cm_scacheLock", LOCK_HIERARCHY_SCACHE_GLOBAL);
647         if ( newFile ) {
648             memset(cm_data.scacheHashTablep, 0, sizeof(cm_scache_t *) * cm_data.scacheHashTableSize);
649             cm_data.allSCachesp = NULL;
650             cm_data.currentSCaches = 0;
651             cm_data.maxSCaches = maxSCaches;
652             cm_data.scacheLRUFirstp = cm_data.scacheLRULastp = NULL;
653         } else {
654             cm_scache_t * scp;
655
656             for ( scp = cm_data.allSCachesp; scp;
657                   scp = scp->allNextp ) {
658                 lock_InitializeRWLock(&scp->rw, "cm_scache_t rw", LOCK_HIERARCHY_SCACHE);
659                 lock_InitializeRWLock(&scp->bufCreateLock, "cm_scache_t bufCreateLock", LOCK_HIERARCHY_SCACHE_BUFCREATE);
660 #ifdef USE_BPLUS
661                 lock_InitializeRWLock(&scp->dirlock, "cm_scache_t dirlock", LOCK_HIERARCHY_SCACHE_DIRLOCK);
662 #endif
663                 scp->cbServerp = NULL;
664                 scp->cbExpires = 0;
665                 scp->cbIssued = 0;
666                 scp->volumeCreationDate = 0;
667                 scp->fileLocksH = NULL;
668                 scp->fileLocksT = NULL;
669                 scp->serverLock = (-1);
670                 scp->lastRefreshCycle = 0;
671                 scp->exclusiveLocks = 0;
672                 scp->sharedLocks = 0;
673                 scp->openReads = 0;
674                 scp->openWrites = 0;
675                 scp->openShares = 0;
676                 scp->openExcls = 0;
677                 scp->waitCount = 0;
678                 scp->activeRPCs = 0;
679 #ifdef USE_BPLUS
680                 scp->dirBplus = NULL;
681                 scp->dirDataVersion = CM_SCACHE_VERSION_BAD;
682 #endif
683                 scp->waitQueueT = NULL;
684                 _InterlockedAnd(&scp->flags, ~(CM_SCACHEFLAG_CALLBACK | CM_SCACHEFLAG_WAITING | CM_SCACHEFLAG_RDR_IN_USE));
685
686                 scp->redirBufCount = 0;
687                 scp->redirQueueT = NULL;
688                 scp->redirQueueH = NULL;
689                 lock_InitializeMutex(&scp->redirMx, "cm_scache_t redirMx", LOCK_HIERARCHY_SCACHE_REDIRMX);
690             }
691         }
692         cm_allFileLocks = NULL;
693         cm_freeFileLocks = NULL;
694         cm_lockRefreshCycle = 0;
695         cm_fakeSCacheInit(newFile);
696         cm_allFreeWaiters = NULL;
697         cm_dnlcInit(newFile);
698         osi_EndOnce(&once);
699     }
700 }
701
702 /* version that doesn't bother creating the entry if we don't find it */
703 cm_scache_t *cm_FindSCache(cm_fid_t *fidp)
704 {
705     long hash;
706     cm_scache_t *scp;
707
708     hash = CM_SCACHE_HASH(fidp);
709
710     if (fidp->cell == 0) {
711         return NULL;
712     }
713
714     lock_ObtainRead(&cm_scacheLock);
715     for (scp=cm_data.scacheHashTablep[hash]; scp; scp=scp->nextp) {
716         if (cm_FidCmp(fidp, &scp->fid) == 0) {
717             cm_HoldSCacheNoLock(scp);
718             lock_ConvertRToW(&cm_scacheLock);
719             cm_AdjustScacheLRU(scp);
720             lock_ReleaseWrite(&cm_scacheLock);
721             return scp;
722         }
723     }
724     lock_ReleaseRead(&cm_scacheLock);
725     return NULL;
726 }
727
728 #ifdef DEBUG_REFCOUNT
729 long cm_GetSCacheDbg(cm_fid_t *fidp, cm_fid_t *parentFidp, cm_scache_t **outScpp, cm_user_t *userp,
730                   cm_req_t *reqp, char * file, long line)
731 #else
732 long cm_GetSCache(cm_fid_t *fidp, cm_fid_t *parentFidp, cm_scache_t **outScpp, cm_user_t *userp,
733                   cm_req_t *reqp)
734 #endif
735 {
736     long hash;
737     cm_scache_t *scp = NULL;
738     cm_scache_t *newScp = NULL;
739     long code;
740     cm_volume_t *volp = NULL;
741     cm_cell_t *cellp;
742     int special = 0; // yj: boolean variable to test if file is on root.afs
743     int isRoot = 0;
744     extern cm_fid_t cm_rootFid;
745     afs_int32 refCount;
746
747     hash = CM_SCACHE_HASH(fidp);
748
749     if (fidp->cell == 0)
750         return CM_ERROR_INVAL;
751
752 #ifdef AFS_FREELANCE_CLIENT
753     special = (fidp->cell==AFS_FAKE_ROOT_CELL_ID &&
754                fidp->volume==AFS_FAKE_ROOT_VOL_ID &&
755                !(fidp->vnode==0x1 && fidp->unique==0x1));
756     isRoot = (fidp->cell==AFS_FAKE_ROOT_CELL_ID &&
757               fidp->volume==AFS_FAKE_ROOT_VOL_ID &&
758               fidp->vnode==0x1 && fidp->unique==0x1);
759 #endif
760
761     // yj: check if we have the scp, if so, we don't need
762     // to do anything else
763     lock_ObtainRead(&cm_scacheLock);
764     for (scp=cm_data.scacheHashTablep[hash]; scp; scp=scp->nextp) {
765         if (cm_FidCmp(fidp, &scp->fid) == 0) {
766 #ifdef DEBUG_REFCOUNT
767             afsi_log("%s:%d cm_GetSCache (1) scp 0x%p ref %d", file, line, scp, scp->refCount);
768             osi_Log1(afsd_logp,"cm_GetSCache (1) scp 0x%p", scp);
769 #endif
770 #ifdef AFS_FREELANCE_CLIENT
771             if (cm_freelanceEnabled && special &&
772                 cm_data.fakeDirVersion != scp->dataVersion)
773                 break;
774 #endif
775             if (parentFidp && scp->parentVnode == 0) {
776                 scp->parentVnode = parentFidp->vnode;
777                 scp->parentUnique = parentFidp->unique;
778             }
779             cm_HoldSCacheNoLock(scp);
780             *outScpp = scp;
781             lock_ConvertRToW(&cm_scacheLock);
782             cm_AdjustScacheLRU(scp);
783             lock_ReleaseWrite(&cm_scacheLock);
784             return 0;
785         }
786     }
787     lock_ReleaseRead(&cm_scacheLock);
788
789     // yj: when we get here, it means we don't have an scp
790     // so we need to either load it or fake it, depending
791     // on whether the file is "special", see below.
792
793     // yj: if we're trying to get an scp for a file that's
794     // on root.afs of homecell, we want to handle it specially
795     // because we have to fill in the status stuff 'coz we
796     // don't want trybulkstat to fill it in for us
797 #ifdef AFS_FREELANCE_CLIENT
798     if (cm_freelanceEnabled && isRoot) {
799         osi_Log0(afsd_logp,"cm_GetSCache Freelance and isRoot");
800         /* freelance: if we are trying to get the root scp for the first
801          * time, we will just put in a place holder entry.
802          */
803         volp = NULL;
804     }
805
806     if (cm_freelanceEnabled && special) {
807         osi_Log0(afsd_logp,"cm_GetSCache Freelance and special");
808
809         if (cm_getLocalMountPointChange()) {
810             cm_clearLocalMountPointChange();
811             cm_reInitLocalMountPoints();
812         }
813
814         if (scp == NULL) {
815             scp = cm_GetNewSCache(FALSE);    /* returns scp->rw held */
816             if (scp == NULL) {
817                 osi_Log0(afsd_logp,"cm_GetSCache unable to obtain *new* scache entry");
818                 return CM_ERROR_WOULDBLOCK;
819             }
820         } else {
821             lock_ObtainWrite(&scp->rw);
822         }
823         scp->fid = *fidp;
824         cm_SetFid(&scp->dotdotFid,AFS_FAKE_ROOT_CELL_ID,AFS_FAKE_ROOT_VOL_ID,1,1);
825         if (parentFidp) {
826             scp->parentVnode = parentFidp->vnode;
827             scp->parentUnique = parentFidp->unique;
828         }
829         _InterlockedOr(&scp->flags, (CM_SCACHEFLAG_PURERO | CM_SCACHEFLAG_RO));
830         lock_ObtainWrite(&cm_scacheLock);
831         if (!(scp->flags & CM_SCACHEFLAG_INHASH)) {
832             scp->nextp = cm_data.scacheHashTablep[hash];
833             cm_data.scacheHashTablep[hash] = scp;
834             _InterlockedOr(&scp->flags, CM_SCACHEFLAG_INHASH);
835         }
836         refCount = InterlockedIncrement(&scp->refCount);
837         osi_Log2(afsd_logp,"cm_GetSCache (freelance) sets refCount to 1 scp 0x%p refCount %d", scp, refCount);
838         lock_ReleaseWrite(&cm_scacheLock);
839
840         /* must be called after the scp->fid is set */
841         cm_FreelanceFetchMountPointString(scp);
842         cm_FreelanceFetchFileType(scp);
843
844         scp->length.LowPart = (DWORD)strlen(scp->mountPointStringp)+4;
845         scp->length.HighPart = 0;
846         scp->owner=0x0;
847         scp->unixModeBits=0777;
848         scp->clientModTime=FakeFreelanceModTime;
849         scp->serverModTime=FakeFreelanceModTime;
850         scp->parentUnique = 0x1;
851         scp->parentVnode=0x1;
852         scp->group=0;
853         scp->dataVersion=cm_data.fakeDirVersion;
854         scp->bufDataVersionLow=cm_data.fakeDirVersion;
855         scp->lockDataVersion=CM_SCACHE_VERSION_BAD; /* no lock yet */
856         scp->fsLockCount=0;
857         lock_ReleaseWrite(&scp->rw);
858         *outScpp = scp;
859 #ifdef DEBUG_REFCOUNT
860         afsi_log("%s:%d cm_GetSCache (2) scp 0x%p ref %d", file, line, scp, scp->refCount);
861         osi_Log1(afsd_logp,"cm_GetSCache (2) scp 0x%p", scp);
862 #endif
863         return 0;
864     }
865     // end of yj code
866 #endif /* AFS_FREELANCE_CLIENT */
867
868     /* we don't have the fid, recycle something */
869     newScp = cm_GetNewSCache(FALSE);    /* returns scp->rw held */
870     if (newScp == NULL) {
871         osi_Log0(afsd_logp,"cm_GetNewSCache unable to obtain *new* scache entry");
872         return CM_ERROR_WOULDBLOCK;
873     }
874 #ifdef DEBUG_REFCOUNT
875     afsi_log("%s:%d cm_GetNewSCache returns scp 0x%p flags 0x%x", file, line, newScp, newScp->flags);
876 #endif
877     osi_Log2(afsd_logp,"cm_GetNewSCache returns scp 0x%p flags 0x%x", newScp, newScp->flags);
878
879     /* otherwise, we need to find the volume */
880     if (!cm_freelanceEnabled || !isRoot) {
881         cellp = cm_FindCellByID(fidp->cell, 0);
882         if (!cellp) {
883             /* put back newScp so it can be reused */
884             lock_ObtainWrite(&cm_scacheLock);
885             newScp->flags |= CM_SCACHEFLAG_DELETED;
886             cm_AdjustScacheLRU(newScp);
887             lock_ReleaseWrite(&newScp->rw);
888             lock_ReleaseWrite(&cm_scacheLock);
889             return CM_ERROR_NOSUCHCELL;
890         }
891
892         code = cm_FindVolumeByID(cellp, fidp->volume, userp, reqp, CM_GETVOL_FLAG_CREATE, &volp);
893         if (code) {
894             /* put back newScp so it can be reused */
895             lock_ObtainWrite(&cm_scacheLock);
896             newScp->flags |= CM_SCACHEFLAG_DELETED;
897             cm_AdjustScacheLRU(newScp);
898             lock_ReleaseWrite(&newScp->rw);
899             lock_ReleaseWrite(&cm_scacheLock);
900             return code;
901         }
902     }
903
904     /*
905      * otherwise, we have the volume, now reverify that the scp doesn't
906      * exist, and proceed.  make sure that we hold the cm_scacheLock
907      * write-locked until the scp is put into the hash table in order
908      * to avoid a race.
909      */
910     lock_ObtainWrite(&cm_scacheLock);
911     for (scp=cm_data.scacheHashTablep[hash]; scp; scp=scp->nextp) {
912         if (cm_FidCmp(fidp, &scp->fid) == 0) {
913 #ifdef DEBUG_REFCOUNT
914             afsi_log("%s:%d cm_GetSCache (3) scp 0x%p ref %d", file, line, scp, scp->refCount);
915             osi_Log1(afsd_logp,"cm_GetSCache (3) scp 0x%p", scp);
916 #endif
917             if (parentFidp && scp->parentVnode == 0) {
918                 scp->parentVnode = parentFidp->vnode;
919                 scp->parentUnique = parentFidp->unique;
920             }
921             if (volp)
922                 cm_PutVolume(volp);
923             cm_HoldSCacheNoLock(scp);
924             cm_AdjustScacheLRU(scp);
925
926             /* put back newScp so it can be reused */
927             newScp->flags |= CM_SCACHEFLAG_DELETED;
928             cm_AdjustScacheLRU(newScp);
929             lock_ReleaseWrite(&newScp->rw);
930             lock_ReleaseWrite(&cm_scacheLock);
931
932             *outScpp = scp;
933             return 0;
934         }
935     }
936
937     scp = newScp;
938     scp->fid = *fidp;
939     if (!cm_freelanceEnabled || !isRoot) {
940         /* if this scache entry represents a volume root then we need
941          * to copy the dotdotFid from the volume structure where the
942          * "master" copy is stored (defect 11489)
943          */
944         if (volp->vol[ROVOL].ID == fidp->volume) {
945             _InterlockedOr(&scp->flags, (CM_SCACHEFLAG_PURERO | CM_SCACHEFLAG_RO));
946             if (scp->fid.vnode == 1 && scp->fid.unique == 1)
947                 scp->dotdotFid = cm_VolumeStateByType(volp, ROVOL)->dotdotFid;
948         } else if (volp->vol[BACKVOL].ID == fidp->volume) {
949             _InterlockedOr(&scp->flags, CM_SCACHEFLAG_RO);
950             if (scp->fid.vnode == 1 && scp->fid.unique == 1)
951                 scp->dotdotFid = cm_VolumeStateByType(volp, BACKVOL)->dotdotFid;
952         } else {
953             if (scp->fid.vnode == 1 && scp->fid.unique == 1)
954                 scp->dotdotFid = cm_VolumeStateByType(volp, RWVOL)->dotdotFid;
955         }
956     }
957     if (parentFidp) {
958         scp->parentVnode = parentFidp->vnode;
959         scp->parentUnique = parentFidp->unique;
960     }
961     if (volp)
962         cm_PutVolume(volp);
963
964     scp->nextp = cm_data.scacheHashTablep[hash];
965     cm_data.scacheHashTablep[hash] = scp;
966     _InterlockedOr(&scp->flags, CM_SCACHEFLAG_INHASH);
967     refCount = InterlockedIncrement(&scp->refCount);
968     lock_ReleaseWrite(&cm_scacheLock);
969     lock_ReleaseWrite(&scp->rw);
970 #ifdef DEBUG_REFCOUNT
971     afsi_log("%s:%d cm_GetSCache sets refCount to 1 scp 0x%p refCount %d", file, line, scp, refCount);
972 #endif
973     osi_Log2(afsd_logp,"cm_GetSCache sets refCount to 1 scp 0x%p refCount %d", scp, refCount);
974
975     /* XXX - The following fields in the cm_scache are
976      * uninitialized:
977      *   fileType
978      *   parentVnode
979      *   parentUnique
980      */
981
982     /* now we have a held scache entry; just return it */
983     *outScpp = scp;
984 #ifdef DEBUG_REFCOUNT
985     afsi_log("%s:%d cm_GetSCache (4) scp 0x%p ref %d", file, line, scp, scp->refCount);
986     osi_Log1(afsd_logp,"cm_GetSCache (4) scp 0x%p", scp);
987 #endif
988     return 0;
989 }
990
991 /* Returns a held reference to the scache's parent
992  * if it exists */
993 cm_scache_t * cm_FindSCacheParent(cm_scache_t * scp)
994 {
995     long code = 0;
996     int i;
997     cm_fid_t    parent_fid;
998     cm_scache_t * pscp = NULL;
999
1000     if (scp->parentVnode == 0)
1001         return NULL;
1002
1003     lock_ObtainWrite(&cm_scacheLock);
1004     cm_SetFid(&parent_fid, scp->fid.cell, scp->fid.volume, scp->parentVnode, scp->parentUnique);
1005
1006     if (cm_FidCmp(&scp->fid, &parent_fid)) {
1007         i = CM_SCACHE_HASH(&parent_fid);
1008         for (pscp = cm_data.scacheHashTablep[i]; pscp; pscp = pscp->nextp) {
1009             if (!cm_FidCmp(&pscp->fid, &parent_fid)) {
1010                 cm_HoldSCacheNoLock(pscp);
1011                 break;
1012             }
1013         }
1014     }
1015
1016     lock_ReleaseWrite(&cm_scacheLock);
1017
1018     return pscp;
1019 }
1020
1021 void cm_SyncOpAddToWaitQueue(cm_scache_t * scp, afs_int32 flags, cm_buf_t * bufp)
1022 {
1023     cm_scache_waiter_t * w;
1024
1025     lock_ObtainWrite(&cm_scacheLock);
1026     if (cm_allFreeWaiters == NULL) {
1027         w = malloc(sizeof(*w));
1028         memset(w, 0, sizeof(*w));
1029     } else {
1030         w = (cm_scache_waiter_t *) cm_allFreeWaiters;
1031         osi_QRemove(&cm_allFreeWaiters, (osi_queue_t *) w);
1032     }
1033
1034     w->threadId = thrd_Current();
1035     w->scp = scp;
1036     cm_HoldSCacheNoLock(scp);
1037     w->flags = flags;
1038     w->bufp = bufp;
1039
1040     osi_QAddT(&scp->waitQueueH, &scp->waitQueueT, (osi_queue_t *) w);
1041     lock_ReleaseWrite(&cm_scacheLock);
1042
1043     osi_Log2(afsd_logp, "cm_SyncOpAddToWaitQueue : Adding thread to wait queue scp 0x%p w 0x%p", scp, w);
1044 }
1045
1046 int cm_SyncOpCheckContinue(cm_scache_t * scp, afs_int32 flags, cm_buf_t * bufp)
1047 {
1048     cm_scache_waiter_t * w;
1049     int this_is_me;
1050
1051     osi_Log0(afsd_logp, "cm_SyncOpCheckContinue checking for continuation");
1052
1053     lock_ObtainRead(&cm_scacheLock);
1054     for (w = (cm_scache_waiter_t *)scp->waitQueueH;
1055          w;
1056          w = (cm_scache_waiter_t *)osi_QNext((osi_queue_t *) w)) {
1057         if (w->flags == flags && w->bufp == bufp) {
1058             break;
1059         }
1060     }
1061
1062     osi_assertx(w != NULL, "null cm_scache_waiter_t");
1063     this_is_me = (w->threadId == thrd_Current());
1064     lock_ReleaseRead(&cm_scacheLock);
1065
1066     if (!this_is_me) {
1067         osi_Log1(afsd_logp, "cm_SyncOpCheckContinue MISS: Waiter 0x%p", w);
1068         return 0;
1069     }
1070
1071     osi_Log1(afsd_logp, "cm_SyncOpCheckContinue HIT: Waiter 0x%p", w);
1072
1073     lock_ObtainWrite(&cm_scacheLock);
1074     osi_QRemoveHT(&scp->waitQueueH, &scp->waitQueueT, (osi_queue_t *) w);
1075     cm_ReleaseSCacheNoLock(scp);
1076     memset(w, 0, sizeof(*w));
1077     osi_QAdd(&cm_allFreeWaiters, (osi_queue_t *) w);
1078     lock_ReleaseWrite(&cm_scacheLock);
1079
1080     return 1;
1081 }
1082
1083
1084 /* synchronize a fetch, store, read, write, fetch status or store status.
1085  * Called with scache mutex held, and returns with it held, but temporarily
1086  * drops it during the fetch.
1087  *
1088  * At most one flag can be on in flags, if this is an RPC request.
1089  *
1090  * Also, if we're fetching or storing data, we must ensure that we have a buffer.
1091  *
1092  * There are a lot of weird restrictions here; here's an attempt to explain the
1093  * rationale for the concurrency restrictions implemented in this function.
1094  *
1095  * First, although the file server will break callbacks when *another* machine
1096  * modifies a file or status block, the client itself is responsible for
1097  * concurrency control on its own requests.  Callback breaking events are rare,
1098  * and simply invalidate any concurrent new status info.
1099  *
1100  * In the absence of callback breaking messages, we need to know how to
1101  * synchronize incoming responses describing updates to files.  We synchronize
1102  * operations that update the data version by comparing the data versions.
1103  * However, updates that do not update the data, but only the status, can't be
1104  * synchronized with fetches or stores, since there's nothing to compare
1105  * to tell which operation executed first at the server.
1106  *
1107  * Thus, we can allow multiple ops that change file data, or dir data, and
1108  * fetches.  However, status storing ops have to be done serially.
1109  *
1110  * Furthermore, certain data-changing ops are incompatible: we can't read or
1111  * write a buffer while doing a truncate.  We can't read and write the same
1112  * buffer at the same time, or write while fetching or storing, or read while
1113  * fetching a buffer (this may change).  We can't fetch and store at the same
1114  * time, either.
1115  *
1116  * With respect to status, we can't read and write at the same time, read while
1117  * fetching, write while fetching or storing, or fetch and store at the same time.
1118  *
1119  * We can't allow a get callback RPC to run in concurrently with something that
1120  * will return updated status, since we could start a call, have the server
1121  * return status, have another machine make an update to the status (which
1122  * doesn't change serverModTime), have the original machine get a new callback,
1123  * and then have the original machine merge in the early, old info from the
1124  * first call.  At this point, the easiest way to avoid this problem is to have
1125  * getcallback calls conflict with all others for the same vnode.  Other calls
1126  * to cm_MergeStatus that aren't associated with calls to cm_SyncOp on the same
1127  * vnode must be careful not to merge in their status unless they have obtained
1128  * a callback from the start of their call.
1129  *
1130  * Note added 1/23/96
1131  * Concurrent StoreData RPC's can cause trouble if the file is being extended.
1132  * Each such RPC passes a FileLength parameter, which the server uses to do
1133  * pre-truncation if necessary.  So if two RPC's are processed out of order at
1134  * the server, the one with the smaller FileLength will be processed last,
1135  * possibly resulting in a bogus truncation.  The simplest way to avoid this
1136  * is to serialize all StoreData RPC's.  This is the reason we defined
1137  * CM_SCACHESYNC_STOREDATA_EXCL and CM_SCACHEFLAG_DATASTORING.
1138  *
1139  * CM_SCACHESYNC_BULKREAD is used to permit synchronization of multiple bulk
1140  * readers which may be requesting overlapping ranges.
1141  */
1142 long cm_SyncOp(cm_scache_t *scp, cm_buf_t *bufp, cm_user_t *userp, cm_req_t *reqp,
1143                afs_uint32 rights, afs_uint32 flags)
1144 {
1145     osi_queueData_t *qdp;
1146     long code;
1147     cm_buf_t *tbufp;
1148     afs_uint32 outRights;
1149     int bufLocked;
1150     afs_uint32 sleep_scp_flags = 0;
1151     afs_uint32 sleep_buf_cmflags = 0;
1152     afs_uint32 sleep_scp_bufs = 0;
1153     int wakeupCycle;
1154
1155     lock_AssertWrite(&scp->rw);
1156
1157     /* lookup this first */
1158     bufLocked = flags & CM_SCACHESYNC_BUFLOCKED;
1159
1160     if (bufp)
1161         osi_assertx(bufp->refCount > 0, "cm_buf_t refCount 0");
1162
1163
1164     /* Do the access check.  Now we don't really do the access check
1165      * atomically, since the caller doesn't expect the parent dir to be
1166      * returned locked, and that is what we'd have to do to prevent a
1167      * callback breaking message on the parent due to a setacl call from
1168      * being processed while we're running.  So, instead, we check things
1169      * here, and if things look fine with the access, we proceed to finish
1170      * the rest of this check.  Sort of a hack, but probably good enough.
1171      */
1172
1173     while (1) {
1174         if (flags & CM_SCACHESYNC_FETCHSTATUS) {
1175             /* if we're bringing in a new status block, ensure that
1176              * we aren't already doing so, and that no one is
1177              * changing the status concurrently, either.  We need
1178              * to do this, even if the status is of a different
1179              * type, since we don't have the ability to figure out,
1180              * in the AFS 3 protocols, which status-changing
1181              * operation ran first, or even which order a read and
1182              * a write occurred in.
1183              */
1184             if (scp->flags & (CM_SCACHEFLAG_FETCHING | CM_SCACHEFLAG_STORING | CM_SCACHEFLAG_SIZESETTING |
1185                               CM_SCACHEFLAG_SIZESTORING | CM_SCACHEFLAG_GETCALLBACK)) {
1186                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING|STORING|SIZESETTING|SIZESTORING|GETCALLBACK want FETCHSTATUS", scp);
1187                 goto sleep;
1188             }
1189         }
1190         if (flags & (CM_SCACHESYNC_STORESIZE | CM_SCACHESYNC_STORESTATUS
1191                       | CM_SCACHESYNC_SETSIZE | CM_SCACHESYNC_GETCALLBACK)) {
1192             /* if we're going to make an RPC to change the status, make sure
1193              * that no one is bringing in or sending out the status.
1194              */
1195             if (scp->flags & (CM_SCACHEFLAG_FETCHING | CM_SCACHEFLAG_STORING | CM_SCACHEFLAG_SIZESETTING |
1196                               CM_SCACHEFLAG_SIZESTORING | CM_SCACHEFLAG_GETCALLBACK)) {
1197                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING|STORING|SIZESETTING|SIZESTORING|GETCALLBACK want STORESIZE|STORESTATUS|SETSIZE|GETCALLBACK", scp);
1198                 goto sleep;
1199             }
1200             if ((!bufp || bufp && scp->fileType == CM_SCACHETYPE_FILE) &&
1201                 (scp->bufReadsp || scp->bufWritesp)) {
1202                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is bufRead|bufWrite want STORESIZE|STORESTATUS|SETSIZE|GETCALLBACK", scp);
1203                 goto sleep;
1204             }
1205         }
1206         if (flags & CM_SCACHESYNC_FETCHDATA) {
1207             /* if we're bringing in a new chunk of data, make sure that
1208              * nothing is happening to that chunk, and that we aren't
1209              * changing the basic file status info, either.
1210              */
1211             if (scp->flags & (CM_SCACHEFLAG_FETCHING | CM_SCACHEFLAG_STORING | CM_SCACHEFLAG_SIZESETTING |
1212                               CM_SCACHEFLAG_SIZESTORING | CM_SCACHEFLAG_GETCALLBACK)) {
1213                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING|STORING|SIZESETTING|SIZESTORING|GETCALLBACK want FETCHDATA", scp);
1214                 goto sleep;
1215             }
1216             if (bufp && (bufp->cmFlags & (CM_BUF_CMFETCHING | CM_BUF_CMSTORING | CM_BUF_CMWRITING))) {
1217                 osi_Log2(afsd_logp, "CM SyncOp scp 0x%p bufp 0x%p is BUF_CMFETCHING|BUF_CMSTORING|BUF_CMWRITING want FETCHDATA", scp, bufp);
1218                 goto sleep;
1219             }
1220         }
1221         if (flags & CM_SCACHESYNC_STOREDATA) {
1222             /* same as fetch data */
1223             if (scp->flags & (CM_SCACHEFLAG_FETCHING | CM_SCACHEFLAG_STORING
1224                                | CM_SCACHEFLAG_SIZESTORING | CM_SCACHEFLAG_GETCALLBACK)) {
1225                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING|STORING|SIZESTORING|GETCALLBACK want STOREDATA", scp);
1226                 goto sleep;
1227             }
1228             if (bufp && (bufp->cmFlags & (CM_BUF_CMFETCHING | CM_BUF_CMSTORING | CM_BUF_CMWRITING))) {
1229                 osi_Log2(afsd_logp, "CM SyncOp scp 0x%p bufp 0x%p is BUF_CMFETCHING|BUF_CMSTORING|BUF_CMWRITING want STOREDATA", scp, bufp);
1230                 goto sleep;
1231             }
1232         }
1233
1234         if (flags & CM_SCACHESYNC_STOREDATA_EXCL) {
1235             /* Don't allow concurrent StoreData RPC's */
1236             if (scp->flags & CM_SCACHEFLAG_DATASTORING) {
1237                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is DATASTORING want STOREDATA_EXCL", scp);
1238                 goto sleep;
1239             }
1240         }
1241
1242         if (flags & CM_SCACHESYNC_ASYNCSTORE) {
1243             /* Don't allow more than one BKG store request */
1244             if (scp->flags & CM_SCACHEFLAG_ASYNCSTORING) {
1245                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is ASYNCSTORING want ASYNCSTORE", scp);
1246                 goto sleep;
1247             }
1248         }
1249
1250         if (flags & CM_SCACHESYNC_LOCK) {
1251             /* Don't allow concurrent fiddling with lock lists */
1252             if (scp->flags & CM_SCACHEFLAG_LOCKING) {
1253                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is LOCKING want LOCK", scp);
1254                 goto sleep;
1255             }
1256         }
1257
1258         /* now the operations that don't correspond to making RPCs */
1259         if (flags & CM_SCACHESYNC_GETSTATUS) {
1260             /* we can use the status that's here, if we're not
1261              * bringing in new status.
1262              */
1263             if (scp->flags & (CM_SCACHEFLAG_FETCHING)) {
1264                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING want GETSTATUS", scp);
1265                 goto sleep;
1266             }
1267         }
1268         if (flags & CM_SCACHESYNC_SETSTATUS) {
1269             /* we can make a change to the local status, as long as
1270              * the status isn't changing now.
1271              *
1272              * If we're fetching or storing a chunk of data, we can
1273              * change the status locally, since the fetch/store
1274              * operations don't change any of the data that we're
1275              * changing here.
1276              */
1277             if (scp->flags & (CM_SCACHEFLAG_FETCHING | CM_SCACHEFLAG_STORING |
1278                               CM_SCACHEFLAG_SIZESETTING | CM_SCACHEFLAG_SIZESTORING)) {
1279                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING|STORING|SIZESETTING|SIZESTORING want SETSTATUS", scp);
1280                 goto sleep;
1281             }
1282         }
1283         if (flags & CM_SCACHESYNC_READ) {
1284             /* we're going to read the data, make sure that the
1285              * status is available, and that the data is here.  It
1286              * is OK to read while storing the data back.
1287              */
1288             if (scp->flags & CM_SCACHEFLAG_FETCHING) {
1289                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING want READ", scp);
1290                 goto sleep;
1291             }
1292             if (bufp && ((bufp->cmFlags & (CM_BUF_CMFETCHING | CM_BUF_CMFULLYFETCHED)) == CM_BUF_CMFETCHING)) {
1293                 osi_Log2(afsd_logp, "CM SyncOp scp 0x%p bufp 0x%p is BUF_CMFETCHING want READ", scp, bufp);
1294                 goto sleep;
1295             }
1296             if (bufp && (bufp->cmFlags & CM_BUF_CMWRITING)) {
1297                 osi_Log2(afsd_logp, "CM SyncOp scp 0x%p bufp 0x%p is BUF_CMWRITING want READ", scp, bufp);
1298                 goto sleep;
1299             }
1300         }
1301         if (flags & CM_SCACHESYNC_WRITE) {
1302             /* don't write unless the status is stable and the chunk
1303              * is stable.
1304              */
1305             if (scp->flags & (CM_SCACHEFLAG_FETCHING | CM_SCACHEFLAG_STORING | CM_SCACHEFLAG_SIZESETTING |
1306                               CM_SCACHEFLAG_SIZESTORING)) {
1307                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is FETCHING|STORING|SIZESETTING|SIZESTORING want WRITE", scp);
1308                 goto sleep;
1309             }
1310             if (bufp && (bufp->cmFlags & (CM_BUF_CMFETCHING |
1311                                           CM_BUF_CMSTORING |
1312                                           CM_BUF_CMWRITING))) {
1313                 osi_Log3(afsd_logp, "CM SyncOp scp 0x%p bufp 0x%p is %s want WRITE",
1314                          scp, bufp,
1315                          ((bufp->cmFlags & CM_BUF_CMFETCHING) ? "CM_BUF_CMFETCHING":
1316                           ((bufp->cmFlags & CM_BUF_CMSTORING) ? "CM_BUF_CMSTORING" :
1317                            ((bufp->cmFlags & CM_BUF_CMWRITING) ? "CM_BUF_CMWRITING" :
1318                             "UNKNOWN!!!"))));
1319                 goto sleep;
1320             }
1321         }
1322
1323         if ((flags & CM_SCACHESYNC_NEEDCALLBACK)) {
1324             if ((flags & CM_SCACHESYNC_FORCECB) || !cm_HaveCallback(scp)) {
1325                 osi_Log1(afsd_logp, "CM SyncOp getting callback on scp 0x%p",
1326                           scp);
1327                 if (bufLocked)
1328                     lock_ReleaseMutex(&bufp->mx);
1329                 code = cm_GetCallback(scp, userp, reqp, (flags & CM_SCACHESYNC_FORCECB)?1:0);
1330                 if (bufLocked) {
1331                     lock_ReleaseWrite(&scp->rw);
1332                     lock_ObtainMutex(&bufp->mx);
1333                     lock_ObtainWrite(&scp->rw);
1334                 }
1335                 if (code)
1336                     return code;
1337                 flags &= ~CM_SCACHESYNC_FORCECB;        /* only force once */
1338                 continue;
1339             }
1340         }
1341
1342         if (rights) {
1343             /* can't check access rights without a callback */
1344             osi_assertx(flags & CM_SCACHESYNC_NEEDCALLBACK, "!CM_SCACHESYNC_NEEDCALLBACK");
1345
1346             if ((rights & (PRSFS_WRITE|PRSFS_DELETE)) && (scp->flags & CM_SCACHEFLAG_RO))
1347                 return CM_ERROR_READONLY;
1348
1349             if (cm_HaveAccessRights(scp, userp, reqp, rights, &outRights)) {
1350                 if (~outRights & rights)
1351                     return CM_ERROR_NOACCESS;
1352             }
1353             else {
1354                 /* we don't know the required access rights */
1355                 if (bufLocked) lock_ReleaseMutex(&bufp->mx);
1356                 code = cm_GetAccessRights(scp, userp, reqp);
1357                 if (bufLocked) {
1358                     lock_ReleaseWrite(&scp->rw);
1359                     lock_ObtainMutex(&bufp->mx);
1360                     lock_ObtainWrite(&scp->rw);
1361                 }
1362                 if (code)
1363                     return code;
1364                 continue;
1365             }
1366         }
1367
1368         if (flags & CM_SCACHESYNC_BULKREAD) {
1369             /* Don't allow concurrent fiddling with lock lists */
1370             if (scp->flags & CM_SCACHEFLAG_BULKREADING) {
1371                 osi_Log1(afsd_logp, "CM SyncOp scp 0x%p is BULKREADING want BULKREAD", scp);
1372                 goto sleep;
1373             }
1374         }
1375
1376         /* if we get here, we're happy */
1377         break;
1378
1379       sleep:
1380         /* first check if we're not supposed to wait: fail
1381          * in this case, returning with everything still locked.
1382          */
1383         if (flags & CM_SCACHESYNC_NOWAIT)
1384             return CM_ERROR_WOULDBLOCK;
1385
1386         /* These are used for minidump debugging */
1387         sleep_scp_flags = scp->flags;           /* so we know why we slept */
1388         sleep_buf_cmflags = bufp ? bufp->cmFlags : 0;
1389         sleep_scp_bufs = (scp->bufReadsp ? 1 : 0) | (scp->bufWritesp ? 2 : 0);
1390
1391         /* wait here, then try again */
1392         osi_Log1(afsd_logp, "CM SyncOp sleeping scp 0x%p", scp);
1393         if ( scp->flags & CM_SCACHEFLAG_WAITING ) {
1394             scp->waitCount++;
1395             scp->waitRequests++;
1396             osi_Log3(afsd_logp, "CM SyncOp CM_SCACHEFLAG_WAITING already set for 0x%p; %d threads; %d requests",
1397                      scp, scp->waitCount, scp->waitRequests);
1398         } else {
1399             osi_Log1(afsd_logp, "CM SyncOp CM_SCACHEFLAG_WAITING set for 0x%p", scp);
1400             _InterlockedOr(&scp->flags, CM_SCACHEFLAG_WAITING);
1401             scp->waitCount = scp->waitRequests = 1;
1402         }
1403
1404         cm_SyncOpAddToWaitQueue(scp, flags, bufp);
1405         wakeupCycle = 0;
1406         do {
1407             if (bufLocked)
1408                 lock_ReleaseMutex(&bufp->mx);
1409             osi_SleepW((LONG_PTR) &scp->flags, &scp->rw);
1410             if (bufLocked)
1411                 lock_ObtainMutex(&bufp->mx);
1412             lock_ObtainWrite(&scp->rw);
1413         } while (!cm_SyncOpCheckContinue(scp, flags, bufp));
1414
1415         cm_UpdateServerPriority();
1416
1417         scp->waitCount--;
1418         osi_Log3(afsd_logp, "CM SyncOp woke! scp 0x%p; still waiting %d threads of %d requests",
1419                  scp, scp->waitCount, scp->waitRequests);
1420         if (scp->waitCount == 0) {
1421             osi_Log1(afsd_logp, "CM SyncOp CM_SCACHEFLAG_WAITING reset for 0x%p", scp);
1422             _InterlockedAnd(&scp->flags, ~CM_SCACHEFLAG_WAITING);
1423             scp->waitRequests = 0;
1424         }
1425     } /* big while loop */
1426
1427     /* now, update the recorded state for RPC-type calls */
1428     if (flags & CM_SCACHESYNC_FETCHSTATUS)
1429         _InterlockedOr(&scp->flags, CM_SCACHEFLAG_FETCHING);
1430     if (flags & CM_SCACHESYNC_STORESTATUS)
1431         _InterlockedOr(&scp->flags, CM_SCACHEFLAG_STORING);
1432     if (flags & CM_SCACHESYNC_SETSIZE)
1433         _InterlockedOr(&scp->flags, CM_SCACHEFLAG_SIZESETTING);
1434     if (flags & CM_SCACHESYNC_STORESIZE)
1435         _InterlockedOr(&scp->flags, CM_SCACHEFLAG_SIZESTORING);
1436     if (flags & CM_SCACHESYNC_GETCALLBACK)
1437         _InterlockedOr(&scp->flags, CM_SCACHEFLAG_GETCALLBACK);
1438     if (flags & CM_SCACHESYNC_STOREDATA_EXCL)
1439         _InterlockedOr(&scp->flags, CM_SCACHEFLAG_DATASTORING);
1440     if (flags & CM_SCACHESYNC_ASYNCSTORE)
1441         _InterlockedOr(&scp->flags, CM_SCACHEFLAG_ASYNCSTORING);
1442     if (flags & CM_SCACHESYNC_LOCK)
1443         _InterlockedOr(&scp->flags, CM_SCACHEFLAG_LOCKING);
1444     if (flags & CM_SCACHESYNC_BULKREAD)
1445         _InterlockedOr(&scp->flags, CM_SCACHEFLAG_BULKREADING);
1446
1447     /* now update the buffer pointer */
1448     if (bufp && (flags & CM_SCACHESYNC_FETCHDATA)) {
1449         /* ensure that the buffer isn't already in the I/O list */
1450         for (qdp = scp->bufReadsp; qdp; qdp = (osi_queueData_t *) osi_QNext(&qdp->q)) {
1451             tbufp = osi_GetQData(qdp);
1452             osi_assertx(tbufp != bufp, "unexpected cm_buf_t value");
1453         }
1454
1455         /* queue a held reference to the buffer in the "reading" I/O list */
1456         qdp = osi_QDAlloc();
1457         osi_SetQData(qdp, bufp);
1458
1459         buf_Hold(bufp);
1460         _InterlockedOr(&bufp->cmFlags, CM_BUF_CMFETCHING);
1461         osi_QAdd((osi_queue_t **) &scp->bufReadsp, &qdp->q);
1462     }
1463
1464     if (bufp && (flags & CM_SCACHESYNC_STOREDATA)) {
1465         osi_assertx(scp->fileType == CM_SCACHETYPE_FILE,
1466             "attempting to store extents on a non-file object");
1467
1468         /* ensure that the buffer isn't already in the I/O list */
1469         for (qdp = scp->bufWritesp; qdp; qdp = (osi_queueData_t *) osi_QNext(&qdp->q)) {
1470             tbufp = osi_GetQData(qdp);
1471             osi_assertx(tbufp != bufp, "unexpected cm_buf_t value");
1472         }
1473
1474         /* queue a held reference to the buffer in the "writing" I/O list */
1475         qdp = osi_QDAlloc();
1476         osi_SetQData(qdp, bufp);
1477         buf_Hold(bufp);
1478         _InterlockedOr(&bufp->cmFlags, CM_BUF_CMSTORING);
1479         osi_QAdd((osi_queue_t **) &scp->bufWritesp, &qdp->q);
1480     }
1481
1482     if (bufp && (flags & CM_SCACHESYNC_WRITE)) {
1483         /* mark the buffer as being written to. */
1484         _InterlockedOr(&bufp->cmFlags, CM_BUF_CMWRITING);
1485     }
1486
1487     return 0;
1488 }
1489
1490 /* for those syncops that setup for RPCs.
1491  * Called with scache locked.
1492  */
1493 void cm_SyncOpDone(cm_scache_t *scp, cm_buf_t *bufp, afs_uint32 flags)
1494 {
1495     osi_queueData_t *qdp;
1496     cm_buf_t *tbufp;
1497
1498     lock_AssertWrite(&scp->rw);
1499
1500     /* now, update the recorded state for RPC-type calls */
1501     if (flags & CM_SCACHESYNC_FETCHSTATUS)
1502         _InterlockedAnd(&scp->flags, ~CM_SCACHEFLAG_FETCHING);
1503     if (flags & CM_SCACHESYNC_STORESTATUS)
1504         _InterlockedAnd(&scp->flags, ~CM_SCACHEFLAG_STORING);
1505     if (flags & CM_SCACHESYNC_SETSIZE)
1506         _InterlockedAnd(&scp->flags, ~CM_SCACHEFLAG_SIZESETTING);
1507     if (flags & CM_SCACHESYNC_STORESIZE)
1508         _InterlockedAnd(&scp->flags, ~CM_SCACHEFLAG_SIZESTORING);
1509     if (flags & CM_SCACHESYNC_GETCALLBACK)
1510         _InterlockedAnd(&scp->flags, ~CM_SCACHEFLAG_GETCALLBACK);
1511     if (flags & CM_SCACHESYNC_STOREDATA_EXCL)
1512         _InterlockedAnd(&scp->flags, ~CM_SCACHEFLAG_DATASTORING);
1513     if (flags & CM_SCACHESYNC_ASYNCSTORE)
1514         _InterlockedAnd(&scp->flags, ~CM_SCACHEFLAG_ASYNCSTORING);
1515     if (flags & CM_SCACHESYNC_LOCK)
1516         _InterlockedAnd(&scp->flags, ~CM_SCACHEFLAG_LOCKING);
1517     if (flags & CM_SCACHESYNC_BULKREAD)
1518         _InterlockedAnd(&scp->flags, ~CM_SCACHEFLAG_BULKREADING);
1519
1520     /* now update the buffer pointer */
1521     if (bufp && (flags & CM_SCACHESYNC_FETCHDATA)) {
1522         int release = 0;
1523
1524         /* ensure that the buffer is in the I/O list */
1525         for (qdp = scp->bufReadsp; qdp; qdp = (osi_queueData_t *) osi_QNext(&qdp->q)) {
1526             tbufp = osi_GetQData(qdp);
1527             if (tbufp == bufp)
1528                 break;
1529         }
1530         if (qdp) {
1531             osi_QRemove((osi_queue_t **) &scp->bufReadsp, &qdp->q);
1532             osi_QDFree(qdp);
1533             release = 1;
1534         }
1535         _InterlockedAnd(&bufp->cmFlags, ~(CM_BUF_CMFETCHING | CM_BUF_CMFULLYFETCHED));
1536         if (bufp->flags & CM_BUF_WAITING) {
1537             osi_Log2(afsd_logp, "CM SyncOpDone FetchData Waking [scp 0x%p] bufp 0x%p", scp, bufp);
1538             osi_Wakeup((LONG_PTR) &bufp);
1539         }
1540         if (release)
1541             buf_Release(bufp);
1542     }
1543
1544     /* now update the buffer pointer */
1545     if (bufp && (flags & CM_SCACHESYNC_STOREDATA)) {
1546         int release = 0;
1547         /* ensure that the buffer is in the I/O list */
1548         for (qdp = scp->bufWritesp; qdp; qdp = (osi_queueData_t *) osi_QNext(&qdp->q)) {
1549             tbufp = osi_GetQData(qdp);
1550             if (tbufp == bufp)
1551                 break;
1552         }
1553         if (qdp) {
1554             osi_QRemove((osi_queue_t **) &scp->bufWritesp, &qdp->q);
1555             osi_QDFree(qdp);
1556             release = 1;
1557         }
1558         _InterlockedAnd(&bufp->cmFlags, ~CM_BUF_CMSTORING);
1559         if (bufp->flags & CM_BUF_WAITING) {
1560             osi_Log2(afsd_logp, "CM SyncOpDone StoreData Waking [scp 0x%p] bufp 0x%p", scp, bufp);
1561             osi_Wakeup((LONG_PTR) &bufp);
1562         }
1563         if (release)
1564             buf_Release(bufp);
1565     }
1566
1567     if (bufp && (flags & CM_SCACHESYNC_WRITE)) {
1568         osi_assertx(bufp->cmFlags & CM_BUF_CMWRITING, "!CM_BUF_CMWRITING");
1569         _InterlockedAnd(&bufp->cmFlags, ~CM_BUF_CMWRITING);
1570     }
1571
1572     /* and wakeup anyone who is waiting */
1573     if (scp->flags & CM_SCACHEFLAG_WAITING) {
1574         osi_Log3(afsd_logp, "CM SyncOpDone 0x%x Waking scp 0x%p bufp 0x%p", flags, scp, bufp);
1575         osi_Wakeup((LONG_PTR) &scp->flags);
1576     }
1577 }
1578
1579 static afs_uint32
1580 dv_diff(afs_uint64 dv1, afs_uint64 dv2)
1581 {
1582     if ( dv1 - dv2 > 0x7FFFFFFF )
1583         return (afs_uint32)(dv2 - dv1);
1584     else
1585         return (afs_uint32)(dv1 - dv2);
1586 }
1587
1588 /* merge in a response from an RPC.  The scp must be locked, and the callback
1589  * is optional.
1590  *
1591  * Don't overwrite any status info that is dirty, since we could have a store
1592  * operation (such as store data) that merges some info in, and we don't want
1593  * to lose the local updates.  Typically, there aren't many updates we do
1594  * locally, anyway, probably only mtime.
1595  *
1596  * There is probably a bug in here where a chmod (which doesn't change
1597  * serverModTime) that occurs between two fetches, both of whose responses are
1598  * handled after the callback breaking is done, but only one of whose calls
1599  * started before that, can cause old info to be merged from the first call.
1600  */
1601 void cm_MergeStatus(cm_scache_t *dscp,
1602                     cm_scache_t *scp, AFSFetchStatus *statusp,
1603                     AFSVolSync *volsyncp,
1604                     cm_user_t *userp, cm_req_t *reqp, afs_uint32 flags)
1605 {
1606     afs_uint64 dataVersion;
1607     struct cm_volume *volp = NULL;
1608     struct cm_cell *cellp = NULL;
1609     int rdr_invalidate = 0;
1610     afs_uint32 activeRPCs;
1611
1612     lock_AssertWrite(&scp->rw);
1613
1614     activeRPCs = 1 + InterlockedDecrement(&scp->activeRPCs);
1615
1616     // yj: i want to create some fake status for the /afs directory and the
1617     // entries under that directory
1618 #ifdef AFS_FREELANCE_CLIENT
1619     if (cm_freelanceEnabled && scp->fid.cell==AFS_FAKE_ROOT_CELL_ID &&
1620          scp->fid.volume==AFS_FAKE_ROOT_VOL_ID) {
1621         if (scp == cm_data.rootSCachep) {
1622             osi_Log0(afsd_logp,"cm_MergeStatus Freelance cm_data.rootSCachep");
1623             statusp->FileType = CM_SCACHETYPE_DIRECTORY;
1624             statusp->Length = cm_fakeDirSize;
1625             statusp->Length_hi = 0;
1626         } else {
1627             statusp->FileType = scp->fileType;
1628             statusp->Length = scp->length.LowPart;
1629             statusp->Length_hi = scp->length.HighPart;
1630         }
1631         statusp->InterfaceVersion = 0x1;
1632         statusp->LinkCount = scp->linkCount;
1633         statusp->DataVersion = (afs_uint32)(cm_data.fakeDirVersion & 0xFFFFFFFF);
1634         statusp->Author = 0x1;
1635         statusp->Owner = 0x0;
1636         statusp->CallerAccess = 0x9;
1637         statusp->AnonymousAccess = 0x9;
1638         statusp->UnixModeBits = 0777;
1639         statusp->ParentVnode = 0x1;
1640         statusp->ParentUnique = 0x1;
1641         statusp->ResidencyMask = 0;
1642         statusp->ClientModTime = FakeFreelanceModTime;
1643         statusp->ServerModTime = FakeFreelanceModTime;
1644         statusp->Group = 0;
1645         statusp->SyncCounter = 0;
1646         statusp->dataVersionHigh = (afs_uint32)(cm_data.fakeDirVersion >> 32);
1647         statusp->lockCount = 0;
1648         statusp->errorCode = 0;
1649     }
1650 #endif /* AFS_FREELANCE_CLIENT */
1651
1652     if (statusp->errorCode != 0) {
1653         switch (statusp->errorCode) {
1654         case EACCES:
1655         case UAEACCES:
1656         case EPERM:
1657         case UAEPERM:
1658             _InterlockedOr(&scp->flags, CM_SCACHEFLAG_EACCESS);
1659         }
1660         osi_Log2(afsd_logp, "Merge, Failure scp 0x%p code 0x%x", scp, statusp->errorCode);
1661
1662         if (scp->fid.vnode & 0x1)
1663             scp->fileType = CM_SCACHETYPE_DIRECTORY;
1664         else
1665             scp->fileType = 0;  /* unknown */
1666
1667         scp->serverModTime = 0;
1668         scp->clientModTime = 0;
1669         scp->length.LowPart = 0;
1670         scp->length.HighPart = 0;
1671         scp->serverLength.LowPart = 0;
1672         scp->serverLength.HighPart = 0;
1673         scp->linkCount = 0;
1674         scp->owner = 0;
1675         scp->group = 0;
1676         scp->unixModeBits = 0;
1677         scp->anyAccess = 0;
1678         scp->dataVersion = CM_SCACHE_VERSION_BAD;
1679         scp->bufDataVersionLow = CM_SCACHE_VERSION_BAD;
1680         scp->fsLockCount = 0;
1681
1682         if (dscp && dscp != scp) {
1683             scp->parentVnode = dscp->fid.vnode;
1684             scp->parentUnique = dscp->fid.unique;
1685         } else {
1686             scp->parentVnode = 0;
1687             scp->parentUnique = 0;
1688         }
1689
1690         if (RDR_Initialized)
1691             rdr_invalidate = 1;
1692     } else {
1693         _InterlockedAnd(&scp->flags, ~CM_SCACHEFLAG_EACCESS);
1694     }
1695
1696     dataVersion = statusp->dataVersionHigh;
1697     dataVersion <<= 32;
1698     dataVersion |= statusp->DataVersion;
1699
1700     if (!(flags & CM_MERGEFLAG_FORCE) &&
1701         dataVersion < scp->dataVersion &&
1702         scp->dataVersion != CM_SCACHE_VERSION_BAD) {
1703
1704         cellp = cm_FindCellByID(scp->fid.cell, 0);
1705         if (scp->cbServerp) {
1706             cm_FindVolumeByID(cellp, scp->fid.volume, userp,
1707                               reqp, CM_GETVOL_FLAG_CREATE, &volp);
1708             osi_Log2(afsd_logp, "old data from server %x volume %s",
1709                       scp->cbServerp->addr.sin_addr.s_addr,
1710                       volp ? volp->namep : "(unknown)");
1711         }
1712
1713         osi_Log3(afsd_logp, "Bad merge, scp 0x%p, scp dv %d, RPC dv %d",
1714                   scp, scp->dataVersion, dataVersion);
1715         /* we have a number of data fetch/store operations running
1716          * concurrently, and we can tell which one executed last at the
1717          * server by its mtime.
1718          * Choose the one with the largest mtime, and ignore the rest.
1719          *
1720          * These concurrent calls are incompatible with setting the
1721          * mtime, so we won't have a locally changed mtime here.
1722          *
1723          * We could also have ACL info for a different user than usual,
1724          * in which case we have to do that part of the merge, anyway.
1725          * We won't have to worry about the info being old, since we
1726          * won't have concurrent calls
1727          * that change file status running from this machine.
1728          *
1729          * Added 3/17/98:  if we see data version regression on an RO
1730          * file, it's probably due to a server holding an out-of-date
1731          * replica, rather than to concurrent RPC's.  Failures to
1732          * release replicas are now flagged by the volserver, but only
1733          * since AFS 3.4 5.22, so there are plenty of clients getting
1734          * out-of-date replicas out there.
1735          *
1736          * If we discover an out-of-date replica, by this time it's too
1737          * late to go to another server and retry.  Also, we can't
1738          * reject the merge, because then there is no way for
1739          * GetAccess to do its work, and the caller gets into an
1740          * infinite loop.  So we just grin and bear it.
1741          */
1742         if (!(scp->flags & CM_SCACHEFLAG_RO))
1743             goto done;
1744     }
1745
1746     if (cm_readonlyVolumeVersioning)
1747         scp->volumeCreationDate = volsyncp->spare1;       /* volume creation date */
1748
1749     scp->serverModTime = statusp->ServerModTime;
1750
1751     if (!(scp->mask & CM_SCACHEMASK_CLIENTMODTIME)) {
1752         scp->clientModTime = statusp->ClientModTime;
1753     }
1754     if (!(scp->mask & CM_SCACHEMASK_LENGTH)) {
1755         scp->length.LowPart = statusp->Length;
1756         scp->length.HighPart = statusp->Length_hi;
1757     }
1758
1759     scp->serverLength.LowPart = statusp->Length;
1760     scp->serverLength.HighPart = statusp->Length_hi;
1761
1762     scp->linkCount = statusp->LinkCount;
1763     scp->owner = statusp->Owner;
1764     scp->group = statusp->Group;
1765     scp->unixModeBits = statusp->UnixModeBits & 07777;
1766
1767     if (statusp->FileType == File)
1768         scp->fileType = CM_SCACHETYPE_FILE;
1769     else if (statusp->FileType == Directory)
1770         scp->fileType = CM_SCACHETYPE_DIRECTORY;
1771     else if (statusp->FileType == SymbolicLink) {
1772         if ((scp->unixModeBits & 0111) == 0)
1773             scp->fileType = CM_SCACHETYPE_MOUNTPOINT;
1774         else
1775             scp->fileType = CM_SCACHETYPE_SYMLINK;
1776     }
1777     else {
1778         osi_Log2(afsd_logp, "Merge, Invalid File Type (%d), scp 0x%p", statusp->FileType, scp);
1779         scp->fileType = CM_SCACHETYPE_INVALID;  /* invalid */
1780     }
1781     /* and other stuff */
1782     scp->parentVnode = statusp->ParentVnode;
1783     scp->parentUnique = statusp->ParentUnique;
1784
1785     /* -1 is a write lock; any positive values are read locks */
1786     scp->fsLockCount = (afs_int32)statusp->lockCount;
1787
1788     /* and merge in the private acl cache info, if this is more than the public
1789      * info; merge in the public stuff in any case.
1790      */
1791     scp->anyAccess = statusp->AnonymousAccess;
1792
1793     if (userp != NULL) {
1794         cm_AddACLCache(scp, userp, statusp->CallerAccess);
1795     }
1796
1797     if (dataVersion != 0 && scp->dataVersion != CM_SCACHE_VERSION_BAD &&
1798         (!(flags & (CM_MERGEFLAG_DIROP|CM_MERGEFLAG_STOREDATA)) && (dataVersion != scp->dataVersion) ||
1799          (flags & (CM_MERGEFLAG_DIROP|CM_MERGEFLAG_STOREDATA)) &&
1800          (dv_diff(dataVersion, scp->dataVersion) > activeRPCs))) {
1801         /*
1802          * We now know that all of the data buffers that we have associated
1803          * with this scp are invalid.  Subsequent operations will go faster
1804          * if the buffers are removed from the hash tables.
1805          *
1806          * We do not remove directory buffers if the dataVersion delta is 'activeRPCs' because
1807          * those version numbers will be updated as part of the directory operation.
1808          *
1809          * We do not remove storedata buffers because they will still be valid.
1810          */
1811         int i, j;
1812         cm_buf_t **lbpp;
1813         cm_buf_t *tbp;
1814         cm_buf_t *bp, *prevBp, *nextBp;
1815
1816         lock_ObtainWrite(&buf_globalLock);
1817         i = BUF_FILEHASH(&scp->fid);
1818         for (bp = cm_data.buf_fileHashTablepp[i]; bp; bp=nextBp)
1819         {
1820             nextBp = bp->fileHashp;
1821             /*
1822              * if the buffer belongs to this stat cache entry
1823              * and the buffer mutex can be obtained, check the
1824              * reference count and if it is zero, remove the buffer
1825              * from the hash tables.  If there are references,
1826              * the buffer might be updated to the current version
1827              * so leave it in place.
1828              */
1829             if (cm_FidCmp(&scp->fid, &bp->fid) == 0 &&
1830                  lock_TryMutex(&bp->mx)) {
1831                 if (bp->refCount == 0 &&
1832                     !(bp->flags & (CM_BUF_READING | CM_BUF_WRITING | CM_BUF_DIRTY)) &&
1833                     !(bp->qFlags & CM_BUF_QREDIR)) {
1834                     prevBp = bp->fileHashBackp;
1835                     bp->fileHashBackp = bp->fileHashp = NULL;
1836                     if (prevBp)
1837                         prevBp->fileHashp = nextBp;
1838                     else
1839                         cm_data.buf_fileHashTablepp[i] = nextBp;
1840                     if (nextBp)
1841                         nextBp->fileHashBackp = prevBp;
1842
1843                     j = BUF_HASH(&bp->fid, &bp->offset);
1844                     lbpp = &(cm_data.buf_scacheHashTablepp[j]);
1845                     for(tbp = *lbpp; tbp; lbpp = &tbp->hashp, tbp = tbp->hashp) {
1846                         if (tbp == bp)
1847                             break;
1848                     }
1849
1850                     /* we better find it */
1851                     osi_assertx(tbp != NULL, "cm_MergeStatus: buf_scacheHashTablepp table screwup");
1852
1853                     *lbpp = bp->hashp;  /* hash out */
1854                     bp->hashp = NULL;
1855
1856                     _InterlockedAnd(&bp->qFlags, ~CM_BUF_QINHASH);
1857                 }
1858                 lock_ReleaseMutex(&bp->mx);
1859             }
1860         }
1861         lock_ReleaseWrite(&buf_globalLock);
1862     }
1863
1864     /*
1865      * If the dataVersion has changed, the mountPointStringp must be cleared
1866      * in order to force a re-evaluation by cm_HandleLink().  The Windows CM
1867      * does not update a mountpoint or symlink by altering the contents of
1868      * the file data; but the Unix CM does.
1869      */
1870     if (scp->dataVersion != dataVersion && !(flags & CM_MERGEFLAG_FETCHDATA)) {
1871         scp->mountPointStringp[0] = '\0';
1872
1873         osi_Log5(afsd_logp, "cm_MergeStatus data version change scp 0x%p cell %u vol %u vn %u uniq %u",
1874                  scp, scp->fid.cell, scp->fid.volume, scp->fid.vnode, scp->fid.unique);
1875
1876         osi_Log4(afsd_logp, ".... oldDV 0x%x:%x -> newDV 0x%x:%x",
1877                  (afs_uint32)((scp->dataVersion >> 32) & 0xFFFFFFFF),
1878                  (afs_uint32)(scp->dataVersion & 0xFFFFFFFF),
1879                  (afs_uint32)((dataVersion >> 32) & 0xFFFFFFFF),
1880                  (afs_uint32)(dataVersion & 0xFFFFFFFF));
1881     }
1882
1883     /* We maintain a range of buffer dataVersion values which are considered
1884      * valid.  This avoids the need to update the dataVersion on each buffer
1885      * object during an uncontested storeData operation.  As a result this
1886      * merge status no longer has performance characteristics derived from
1887      * the size of the file.
1888      *
1889      * For directory buffers, only current dataVersion values are up to date.
1890      */
1891     if (((flags & (CM_MERGEFLAG_STOREDATA|CM_MERGEFLAG_DIROP)) && (dv_diff(dataVersion, scp->dataVersion) > activeRPCs)) ||
1892          (!(flags & (CM_MERGEFLAG_STOREDATA|CM_MERGEFLAG_DIROP)) && (scp->dataVersion != dataVersion)) ||
1893          scp->bufDataVersionLow == CM_SCACHE_VERSION_BAD ||
1894          scp->fileType == CM_SCACHETYPE_DIRECTORY)
1895         scp->bufDataVersionLow = dataVersion;
1896
1897     if (RDR_Initialized) {
1898         /*
1899          * The redirector maintains its own cached status information which
1900          * must be updated when a DV change occurs that is not the result
1901          * of a redirector initiated data change.
1902          *
1903          * If the current old DV is BAD, send a DV change notification.
1904          *
1905          * If the DV has changed and request was not initiated by the
1906          * redirector, send a DV change notification.
1907          *
1908          * If the request was initiated by the redirector, send a notification
1909          * for store and directory operations that result in a DV change greater
1910          * than the number of active RPCs or any other operation that results
1911          * in an unexpected DV change such as FetchStatus.
1912          */
1913
1914         if (scp->dataVersion == CM_SCACHE_VERSION_BAD && dataVersion != 0) {
1915             rdr_invalidate = 1;
1916         } else if (!(reqp->flags & CM_REQ_SOURCE_REDIR) && scp->dataVersion != dataVersion) {
1917             rdr_invalidate = 1;
1918         } else if (reqp->flags & CM_REQ_SOURCE_REDIR) {
1919             if (!(flags & (CM_MERGEFLAG_DIROP|CM_MERGEFLAG_STOREDATA)) &&
1920                 (dv_diff(dataVersion, scp->dataVersion) > activeRPCs - 1)) {
1921                 rdr_invalidate = 1;
1922             } else if ((flags & (CM_MERGEFLAG_DIROP|CM_MERGEFLAG_STOREDATA)) &&
1923                        dv_diff(dataVersion, scp->dataVersion) > activeRPCs) {
1924                 rdr_invalidate = 1;
1925             }
1926         }
1927     }
1928     scp->dataVersion = dataVersion;
1929
1930     /*
1931      * If someone is waiting for status information, we can wake them up
1932      * now even though the entity that issued the FetchStatus may not
1933      * have completed yet.
1934      */
1935     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_FETCHSTATUS);
1936
1937     /*
1938      * We just successfully merged status on the stat cache object.
1939      * This means that the associated volume must be online.
1940      */
1941     if (!volp) {
1942         if (!cellp)
1943             cellp = cm_FindCellByID(scp->fid.cell, 0);
1944         cm_FindVolumeByID(cellp, scp->fid.volume, userp, reqp, 0, &volp);
1945     }
1946     if (volp) {
1947         cm_vol_state_t *statep = cm_VolumeStateByID(volp, scp->fid.volume);
1948         if (statep->state != vl_online) {
1949             lock_ObtainWrite(&volp->rw);
1950             cm_VolumeStatusNotification(volp, statep->ID, statep->state, vl_online);
1951             statep->state = vl_online;
1952             lock_ReleaseWrite(&volp->rw);
1953         }
1954     }
1955
1956   done:
1957     if (volp)
1958         cm_PutVolume(volp);
1959
1960     /*
1961      * The scache rw lock cannot be held across the invalidation.
1962      * Doing so can result in deadlocks with other threads processing
1963      * requests initiated by the afs redirector.
1964      */
1965     if (rdr_invalidate) {
1966         lock_ReleaseWrite(&scp->rw);
1967         RDR_InvalidateObject(scp->fid.cell, scp->fid.volume, scp->fid.vnode,
1968                              scp->fid.unique, scp->fid.hash,
1969                              scp->fileType, AFS_INVALIDATE_DATA_VERSION);
1970         lock_ObtainWrite(&scp->rw);
1971     }
1972 }
1973
1974 /* note that our stat cache info is incorrect, so force us eventually
1975  * to stat the file again.  There may be dirty data associated with
1976  * this vnode, and we want to preserve that information.
1977  *
1978  * This function works by simply simulating a loss of the callback.
1979  *
1980  * This function must be called with the scache locked.
1981  */
1982 void cm_DiscardSCache(cm_scache_t *scp)
1983 {
1984     lock_AssertWrite(&scp->rw);
1985     if (scp->cbServerp) {
1986         cm_PutServer(scp->cbServerp);
1987         scp->cbServerp = NULL;
1988     }
1989     scp->cbExpires = 0;
1990     scp->cbIssued = 0;
1991     scp->volumeCreationDate = 0;
1992     _InterlockedAnd(&scp->flags, ~(CM_SCACHEFLAG_CALLBACK | CM_SCACHEFLAG_LOCAL | CM_SCACHEFLAG_RDR_IN_USE));
1993     cm_dnlcPurgedp(scp);
1994     cm_dnlcPurgevp(scp);
1995     cm_FreeAllACLEnts(scp);
1996
1997     if (scp->fileType == CM_SCACHETYPE_DFSLINK)
1998         cm_VolStatus_Invalidate_DFS_Mapping(scp);
1999
2000     /* Force mount points and symlinks to be re-evaluated */
2001     scp->mountPointStringp[0] = '\0';
2002 }
2003
2004 void cm_AFSFidFromFid(AFSFid *afsFidp, cm_fid_t *fidp)
2005 {
2006     afsFidp->Volume = fidp->volume;
2007     afsFidp->Vnode = fidp->vnode;
2008     afsFidp->Unique = fidp->unique;
2009 }
2010
2011 #ifdef DEBUG_REFCOUNT
2012 void cm_HoldSCacheNoLockDbg(cm_scache_t *scp, char * file, long line)
2013 #else
2014 void cm_HoldSCacheNoLock(cm_scache_t *scp)
2015 #endif
2016 {
2017     afs_int32 refCount;
2018
2019     osi_assertx(scp != NULL, "null cm_scache_t");
2020     lock_AssertAny(&cm_scacheLock);
2021     refCount = InterlockedIncrement(&scp->refCount);
2022 #ifdef DEBUG_REFCOUNT
2023     osi_Log2(afsd_logp,"cm_HoldSCacheNoLock scp 0x%p ref %d",scp, refCount);
2024     afsi_log("%s:%d cm_HoldSCacheNoLock scp 0x%p, ref %d", file, line, scp, refCount);
2025 #endif
2026 }
2027
2028 #ifdef DEBUG_REFCOUNT
2029 void cm_HoldSCacheDbg(cm_scache_t *scp, char * file, long line)
2030 #else
2031 void cm_HoldSCache(cm_scache_t *scp)
2032 #endif
2033 {
2034     afs_int32 refCount;
2035
2036     osi_assertx(scp != NULL, "null cm_scache_t");
2037     lock_ObtainRead(&cm_scacheLock);
2038     refCount = InterlockedIncrement(&scp->refCount);
2039 #ifdef DEBUG_REFCOUNT
2040     osi_Log2(afsd_logp,"cm_HoldSCache scp 0x%p ref %d",scp, refCount);
2041     afsi_log("%s:%d cm_HoldSCache scp 0x%p ref %d", file, line, scp, refCount);
2042 #endif
2043     lock_ReleaseRead(&cm_scacheLock);
2044 }
2045
2046 #ifdef DEBUG_REFCOUNT
2047 void cm_ReleaseSCacheNoLockDbg(cm_scache_t *scp, char * file, long line)
2048 #else
2049 void cm_ReleaseSCacheNoLock(cm_scache_t *scp)
2050 #endif
2051 {
2052     afs_int32 refCount;
2053
2054     osi_assertx(scp != NULL, "null cm_scache_t");
2055     lock_AssertAny(&cm_scacheLock);
2056
2057     refCount = InterlockedDecrement(&scp->refCount);
2058 #ifdef DEBUG_REFCOUNT
2059     if (refCount < 0)
2060         osi_Log1(afsd_logp,"cm_ReleaseSCacheNoLock about to panic scp 0x%x",scp);
2061 #endif
2062     osi_assertx(refCount >= 0, "cm_scache_t refCount 0");
2063 #ifdef DEBUG_REFCOUNT
2064     osi_Log2(afsd_logp,"cm_ReleaseSCacheNoLock scp 0x%p ref %d",scp, refCount);
2065     afsi_log("%s:%d cm_ReleaseSCacheNoLock scp 0x%p ref %d", file, line, scp, refCount);
2066 #endif
2067
2068     if (refCount == 0 && (scp->flags & CM_SCACHEFLAG_DELETED)) {
2069         int deleted = 0;
2070         long      lockstate;
2071
2072         lockstate = lock_GetRWLockState(&cm_scacheLock);
2073         if (lockstate != OSI_RWLOCK_WRITEHELD)
2074             lock_ReleaseRead(&cm_scacheLock);
2075         else
2076             lock_ReleaseWrite(&cm_scacheLock);
2077
2078         lock_ObtainWrite(&scp->rw);
2079         if (scp->flags & CM_SCACHEFLAG_DELETED)
2080             deleted = 1;
2081
2082         if (refCount == 0 && deleted) {
2083             lock_ObtainWrite(&cm_scacheLock);
2084             cm_RecycleSCache(scp, 0);
2085             if (lockstate != OSI_RWLOCK_WRITEHELD)
2086                 lock_ConvertWToR(&cm_scacheLock);
2087         } else {
2088             if (lockstate != OSI_RWLOCK_WRITEHELD)
2089                 lock_ObtainRead(&cm_scacheLock);
2090             else
2091                 lock_ObtainWrite(&cm_scacheLock);
2092         }
2093         lock_ReleaseWrite(&scp->rw);
2094     }
2095 }
2096
2097 #ifdef DEBUG_REFCOUNT
2098 void cm_ReleaseSCacheDbg(cm_scache_t *scp, char * file, long line)
2099 #else
2100 void cm_ReleaseSCache(cm_scache_t *scp)
2101 #endif
2102 {
2103     afs_int32 refCount;
2104
2105     osi_assertx(scp != NULL, "null cm_scache_t");
2106     lock_ObtainRead(&cm_scacheLock);
2107     refCount = InterlockedDecrement(&scp->refCount);
2108 #ifdef DEBUG_REFCOUNT
2109     if (refCount < 0)
2110         osi_Log1(afsd_logp,"cm_ReleaseSCache about to panic scp 0x%x",scp);
2111 #endif
2112     osi_assertx(refCount >= 0, "cm_scache_t refCount 0");
2113 #ifdef DEBUG_REFCOUNT
2114     osi_Log2(afsd_logp,"cm_ReleaseSCache scp 0x%p ref %d",scp, refCount);
2115     afsi_log("%s:%d cm_ReleaseSCache scp 0x%p ref %d", file, line, scp, refCount);
2116 #endif
2117     lock_ReleaseRead(&cm_scacheLock);
2118
2119     if (scp->flags & CM_SCACHEFLAG_DELETED) {
2120         int deleted = 0;
2121         lock_ObtainWrite(&scp->rw);
2122         if (scp->flags & CM_SCACHEFLAG_DELETED)
2123             deleted = 1;
2124         if (deleted) {
2125             lock_ObtainWrite(&cm_scacheLock);
2126             cm_RecycleSCache(scp, 0);
2127             lock_ReleaseWrite(&cm_scacheLock);
2128         }
2129         lock_ReleaseWrite(&scp->rw);
2130     }
2131 }
2132
2133 /* just look for the scp entry to get filetype */
2134 /* doesn't need to be perfectly accurate, so locking doesn't matter too much */
2135 int cm_FindFileType(cm_fid_t *fidp)
2136 {
2137     long hash;
2138     cm_scache_t *scp;
2139
2140     hash = CM_SCACHE_HASH(fidp);
2141
2142     osi_assertx(fidp->cell != 0, "unassigned cell value");
2143
2144     lock_ObtainWrite(&cm_scacheLock);
2145     for (scp=cm_data.scacheHashTablep[hash]; scp; scp=scp->nextp) {
2146         if (cm_FidCmp(fidp, &scp->fid) == 0) {
2147             lock_ReleaseWrite(&cm_scacheLock);
2148             return scp->fileType;
2149         }
2150     }
2151     lock_ReleaseWrite(&cm_scacheLock);
2152     return 0;
2153 }
2154
2155 /* dump all scp's that have reference count > 0 to a file.
2156  * cookie is used to identify this batch for easy parsing,
2157  * and it a string provided by a caller
2158  */
2159 int cm_DumpSCache(FILE *outputFile, char *cookie, int lock)
2160 {
2161     int zilch;
2162     cm_scache_t *scp;
2163     osi_queue_t *q;
2164     char output[2048];
2165     int i;
2166
2167     if (lock)
2168         lock_ObtainRead(&cm_scacheLock);
2169
2170     sprintf(output, "%s - dumping all scache - cm_data.currentSCaches=%d, cm_data.maxSCaches=%d\r\n", cookie, cm_data.currentSCaches, cm_data.maxSCaches);
2171     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2172
2173     for (scp = cm_data.allSCachesp; scp; scp = scp->allNextp)
2174     {
2175         time_t t;
2176         char *srvStr = NULL;
2177         afs_uint32 srvStrRpc = TRUE;
2178         char *cbt = NULL;
2179         char *cdrot = NULL;
2180
2181         if (scp->cbServerp) {
2182             if (!((scp->cbServerp->flags & CM_SERVERFLAG_UUID) &&
2183                 UuidToString((UUID *)&scp->cbServerp->uuid, &srvStr) == RPC_S_OK)) {
2184                 srvStr = malloc(16); /* enough for 255.255.255.255 */
2185                 if (srvStr != NULL)
2186                     afs_inet_ntoa_r(scp->cbServerp->addr.sin_addr.s_addr, srvStr);
2187                 srvStrRpc = FALSE;
2188             }
2189         }
2190         if (scp->cbExpires) {
2191             t = scp->cbExpires;
2192             cbt = ctime(&t);
2193             if (cbt) {
2194                 cbt = strdup(cbt);
2195                 cbt[strlen(cbt)-1] = '\0';
2196             }
2197         }
2198         if (scp->volumeCreationDate) {
2199             t = scp->volumeCreationDate;
2200             cdrot = ctime(&t);
2201             if (cdrot) {
2202                 cdrot = strdup(cdrot);
2203                 cdrot[strlen(cdrot)-1] = '\0';
2204             }
2205         }
2206         sprintf(output,
2207                 "%s scp=0x%p, fid (cell=%d, volume=%d, vnode=%d, unique=%d) type=%d dv=%I64d len=0x%I64x "
2208                 "mp='%s' Locks (server=0x%x shared=%d excl=%d clnt=%d) fsLockCount=%d linkCount=%d anyAccess=0x%x "
2209                 "flags=0x%x cbServer='%s' cbExpires='%s' volumeCreationDate='%s' refCount=%u\r\n",
2210                 cookie, scp, scp->fid.cell, scp->fid.volume, scp->fid.vnode, scp->fid.unique,
2211                 scp->fileType, scp->dataVersion, scp->length.QuadPart, scp->mountPointStringp,
2212                 scp->serverLock, scp->sharedLocks, scp->exclusiveLocks, scp->clientLocks, scp->fsLockCount,
2213                 scp->linkCount, scp->anyAccess, scp->flags, srvStr ? srvStr : "<none>", cbt ? cbt : "<none>",
2214                 cdrot ? cdrot : "<none>", scp->refCount);
2215         WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2216
2217         if (scp->fileLocksH) {
2218             sprintf(output, "  %s - begin dumping scp locks\r\n", cookie);
2219             WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2220
2221             for (q = scp->fileLocksH; q; q = osi_QNext(q)) {
2222                 cm_file_lock_t * lockp = fileq_to_cm_file_lock_t(q);
2223                 sprintf(output, "  %s lockp=0x%p scp=0x%p, cm_userp=0x%p offset=0x%I64x len=0x%08I64x type=0x%x "
2224                         "key=0x%I64x flags=0x%x update=0x%I64u\r\n",
2225                         cookie, lockp, lockp->scp, lockp->userp, lockp->range.offset, lockp->range.length,
2226                         lockp->lockType, lockp->key, lockp->flags, (afs_uint64)lockp->lastUpdate);
2227                 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2228             }
2229
2230             sprintf(output, "  %s - done dumping scp locks\r\n", cookie);
2231             WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2232         }
2233
2234         if (srvStr) {
2235             if (srvStrRpc)
2236                 RpcStringFree(&srvStr);
2237             else
2238                 free(srvStr);
2239         }
2240         if (cbt)
2241             free(cbt);
2242         if (cdrot)
2243             free(cdrot);
2244     }
2245
2246     sprintf(output, "%s - Done dumping all scache.\r\n", cookie);
2247     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2248     sprintf(output, "%s - dumping cm_data.scacheHashTable - cm_data.scacheHashTableSize=%d\r\n",
2249             cookie, cm_data.scacheHashTableSize);
2250     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2251
2252     for (i = 0; i < cm_data.scacheHashTableSize; i++)
2253     {
2254         for(scp = cm_data.scacheHashTablep[i]; scp; scp=scp->nextp)
2255         {
2256             sprintf(output, "%s scp=0x%p, hash=%d, fid (cell=%d, volume=%d, vnode=%d, unique=%d)\r\n",
2257                     cookie, scp, i, scp->fid.cell, scp->fid.volume, scp->fid.vnode, scp->fid.unique);
2258             WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2259         }
2260     }
2261
2262     sprintf(output, "%s - Done dumping cm_data.scacheHashTable\r\n", cookie);
2263     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2264
2265     sprintf(output, "%s - begin dumping all file locks\r\n", cookie);
2266     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2267
2268     for (q = cm_allFileLocks; q; q = osi_QNext(q)) {
2269         cm_file_lock_t * lockp = (cm_file_lock_t *)q;
2270         sprintf(output, "%s filelockp=0x%p scp=0x%p, cm_userp=0x%p offset=0x%I64x len=0x%08I64x type=0x%x key=0x%I64x flags=0x%x update=0x%I64u\r\n",
2271                  cookie, lockp, lockp->scp, lockp->userp, lockp->range.offset, lockp->range.length,
2272                  lockp->lockType, lockp->key, lockp->flags, (afs_uint64)lockp->lastUpdate);
2273         WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2274     }
2275
2276     sprintf(output, "%s - done dumping all file locks\r\n", cookie);
2277     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
2278
2279     if (lock)
2280         lock_ReleaseRead(&cm_scacheLock);
2281     return (0);
2282 }
2283