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