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