misc-windows-20040731
[openafs.git] / src / WINNT / afsd / cm_callback.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 <afs/param.h>
11 #include <afs/afs_args.h>
12 #include <afs/stds.h>
13
14 #ifndef DJGPP
15 #include <windows.h>
16 #include <winsock2.h>
17 #else
18 #include <sys/socket.h>
19 #endif /* !DJGPP */
20 #include <malloc.h>
21 #include <string.h>
22 #include <stdlib.h>
23
24 #include <osi.h>
25
26 #include "afsd.h"
27
28 /*extern void afsi_log(char *pattern, ...);*/
29
30 /* read/write lock for all global storage in this module */
31 osi_rwlock_t cm_callbackLock;
32
33 #ifdef AFS_FREELANCE_CLIENT
34 extern osi_mutex_t cm_Freelance_Lock;
35 #endif
36
37 /* count of # of callback breaking messages received by this CM so far.  We use
38  * this count in determining whether there have been any callback breaks that
39  * apply to a call that returned a new callback.  If the counter doesn't
40  * increase during a call, then we know that no callbacks were broken during
41  * that call, and thus that the callback that was just returned is still valid.
42  */
43 long cm_callbackCount;
44
45 /* count of number of RPCs potentially returning a callback executing now.
46  * When this counter hits zero, we can clear out the racing revokes list, since
47  * at that time, we know that none of the just-executed callback revokes will
48  * apply to any future call that returns a callback (since the latter hasn't
49  * even started execution yet).
50  */
51 long cm_activeCallbackGrantingCalls;
52
53 /* list of callbacks that have been broken recently.  If a call returning a
54  * callback is executing and a callback revoke runs immediately after it at the
55  * server, the revoke may end up being processed before the response to the
56  * original callback granting call.  We detect this by keeping a list of
57  * callback revokes that have been received since we *started* the callback
58  * granting call, and discarding any callbacks received for the same file ID,
59  * even if the callback revoke was received before the callback grant.
60  */
61 cm_racingRevokes_t *cm_racingRevokesp;
62
63 /* record a (potentially) racing revoke for this file ID; null means for all
64  * file IDs, and is used by InitCallBackState.
65  *
66  * The cancelFlags describe whether we're just discarding callbacks for the same
67  * file ID, the same volume, or all from the same server.
68  *
69  * Called with no locks held.
70  */
71 void cm_RecordRacingRevoke(cm_fid_t *fidp, long cancelFlags)
72 {
73         cm_racingRevokes_t *rp;
74
75         lock_ObtainWrite(&cm_callbackLock);
76
77     osi_Log3(afsd_logp, "RecordRacingRevoke Volume %d Flags %lX activeCalls %d",
78              fidp->volume, cancelFlags, cm_activeCallbackGrantingCalls);
79
80         if (cm_activeCallbackGrantingCalls > 0) {
81                 rp = malloc(sizeof(*rp));
82                 memset(rp, 0, sizeof(*rp));
83                 osi_QAdd((osi_queue_t **) &cm_racingRevokesp, &rp->q);
84                 rp->flags |= (cancelFlags & CM_RACINGFLAG_ALL);
85                 if (fidp) rp->fid = *fidp;
86                 rp->callbackCount = ++cm_callbackCount;
87         }
88         lock_ReleaseWrite(&cm_callbackLock);
89 }
90
91 /*
92  * When we lose a callback, may have to send change notification replies.
93  */
94 void cm_CallbackNotifyChange(cm_scache_t *scp)
95 {
96     osi_Log2(afsd_logp, "CallbackNotifyChange FileType %d Flags %lX",
97               scp->fileType, scp->flags);
98
99         if (scp->fileType == CM_SCACHETYPE_DIRECTORY) {
100                 if (scp->flags & CM_SCACHEFLAG_ANYWATCH)
101                         smb_NotifyChange(0,
102                          FILE_NOTIFY_GENERIC_DIRECTORY_FILTER,
103                          scp, NULL, NULL, TRUE);
104         } else {
105                 cm_fid_t tfid;
106                 cm_scache_t *dscp;
107
108                 tfid.cell = scp->fid.cell;
109                 tfid.volume = scp->fid.volume;
110                 tfid.vnode = scp->parentVnode;
111                 tfid.unique = scp->parentUnique;
112                 dscp = cm_FindSCache(&tfid);
113                 if (dscp &&
114                         dscp->flags & CM_SCACHEFLAG_ANYWATCH)
115                         smb_NotifyChange(0,
116                          FILE_NOTIFY_GENERIC_FILE_FILTER,
117                          dscp, NULL, NULL, TRUE);
118                 if (dscp) cm_ReleaseSCache(dscp);
119         }
120 }
121
122 /* called with no locks held for every file ID that is revoked directly by
123  * a callback revoke call.  Does not have to handle volume callback breaks,
124  * since those have already been split out.
125  *
126  * The callp parameter is currently unused.
127  */
128 void cm_RevokeCallback(struct rx_call *callp, AFSFid *fidp)
129 {
130         cm_fid_t tfid;
131         cm_scache_t *scp;
132         long hash;
133         
134         /* don't bother setting cell, since we won't be checking it (to aid
135          * in working with multi-homed servers: we don't know the cell if we
136          * don't recognize the IP address).
137          */
138         tfid.cell = 0;
139         tfid.volume = fidp->Volume;
140         tfid.vnode = fidp->Vnode;
141         tfid.unique = fidp->Unique;
142         hash = CM_SCACHE_HASH(&tfid);
143
144     osi_Log3(afsd_logp, "RevokeCallback vol %d vn %d un %d",
145                  fidp->Volume, fidp->Vnode, fidp->Unique);
146         
147         /* do this first, so that if we're executing a callback granting call
148          * at this moment, we kill it before it can be merged in.  Otherwise,
149          * it could complete while we're doing the scan below, and get missed
150          * by both the scan and by this code.
151          */
152         cm_RecordRacingRevoke(&tfid, 0);
153
154         lock_ObtainWrite(&cm_scacheLock);
155         /* do all in the hash bucket, since we don't know how many we'll find with
156          * varying cells.
157          */
158         for(scp = cm_hashTablep[hash]; scp; scp=scp->nextp) {
159                 if (scp->fid.volume == tfid.volume &&
160                         scp->fid.vnode == tfid.vnode &&
161                         scp->fid.unique == tfid.unique) {
162                         scp->refCount++;
163                         lock_ReleaseWrite(&cm_scacheLock);
164             osi_Log1(afsd_logp, "Discarding SCache scp %x", scp);
165                         lock_ObtainMutex(&scp->mx);
166                         cm_DiscardSCache(scp);
167                         lock_ReleaseMutex(&scp->mx);
168                         cm_CallbackNotifyChange(scp);
169                         lock_ObtainWrite(&cm_scacheLock);
170                         scp->refCount--;
171                 }
172         }
173         lock_ReleaseWrite(&cm_scacheLock);
174 }
175
176 /* called to revoke a volume callback, which is typically issued when a volume
177  * is moved from one server to another.
178  *
179  * Called with no locks held.
180  */
181 void cm_RevokeVolumeCallback(struct rx_call *callp, AFSFid *fidp)
182 {
183         long hash;
184         cm_scache_t *scp;
185         cm_fid_t tfid;
186
187     osi_Log1(afsd_logp, "RevokeVolumeCallback %d", fidp->Volume);
188
189         /* do this first, so that if we're executing a callback granting call
190          * at this moment, we kill it before it can be merged in.  Otherwise,
191          * it could complete while we're doing the scan below, and get missed
192          * by both the scan and by this code.
193          */
194         tfid.cell = tfid.vnode = tfid.unique = 0;
195         tfid.volume = fidp->Volume;
196         cm_RecordRacingRevoke(&tfid, CM_RACINGFLAG_CANCELVOL);
197
198
199         lock_ObtainWrite(&cm_scacheLock);
200         for(hash = 0; hash < cm_hashTableSize; hash++) {
201                 for(scp=cm_hashTablep[hash]; scp; scp=scp->nextp) {
202                         if (scp->fid.volume == fidp->Volume) {
203                                 scp->refCount++;
204                                 lock_ReleaseWrite(&cm_scacheLock);
205                                 lock_ObtainMutex(&scp->mx);
206                 osi_Log1(afsd_logp, "Discarding SCache scp %x", scp);
207                                 cm_DiscardSCache(scp);
208                                 lock_ReleaseMutex(&scp->mx);
209                                 cm_CallbackNotifyChange(scp);
210                                 lock_ObtainWrite(&cm_scacheLock);
211                                 scp->refCount--;
212                         }
213                 }       /* search one hash bucket */
214         }       /* search all hash buckets */
215         
216         lock_ReleaseWrite(&cm_scacheLock);
217 }
218
219 /* handle incoming RPC callback breaking message.
220  * Called with no locks held.
221  */
222 SRXAFSCB_CallBack(struct rx_call *callp, AFSCBFids *fidsArrayp, AFSCBs *cbsArrayp)
223 {
224         int i;
225         AFSFid *tfidp;
226         
227     osi_Log0(afsd_logp, "SRXAFSCB_CallBack");
228
229         for(i=0; i < (long) fidsArrayp->AFSCBFids_len; i++) {
230                 tfidp = &fidsArrayp->AFSCBFids_val[i];
231                 
232         if (tfidp->Volume == 0)
233             continue;   /* means don't do anything */
234                 else if (tfidp->Vnode == 0)
235                         cm_RevokeVolumeCallback(callp, tfidp);
236         else
237             cm_RevokeCallback(callp, tfidp);
238         }
239
240         return 0;
241 }
242
243 /* called with no locks by RPC system when a server indicates that it has never
244  * heard from us, or for other reasons has had to discard callbacks from us
245  * without telling us, e.g. a network partition.
246  */
247 SRXAFSCB_InitCallBackState(struct rx_call *callp)
248 {
249     struct sockaddr_in taddr;
250     cm_server_t *tsp;
251     cm_scache_t *scp;
252     int hash;
253     int discarded;
254
255     osi_Log0(afsd_logp, "SRXAFSCB_InitCallBackState");
256
257     if ((rx_ConnectionOf(callp)) && (rx_PeerOf(rx_ConnectionOf(callp)))) {
258         taddr.sin_family = AF_INET;
259         taddr.sin_addr.s_addr = rx_HostOf(rx_PeerOf(rx_ConnectionOf(callp)));
260
261         tsp = cm_FindServer(&taddr, CM_SERVER_FILE);
262
263         osi_Log1(afsd_logp, "Init Callback State server %x", tsp);
264         
265         /* record the callback in the racing revokes structure.  This
266          * shouldn't be necessary, since we shouldn't be making callback
267          * granting calls while we're going to get an initstate call,
268          * but there probably are some obscure races, so better safe
269          * than sorry.
270          *
271          * We do this first since we don't hold the cm_scacheLock and vnode
272          * locks over the entire callback scan operation below.  The
273          * big loop below is guaranteed to hit any callback already
274          * processed.  The call to RecordRacingRevoke is guaranteed
275          * to kill any callback that is currently being returned.
276          * Anything that sneaks past both must start
277          * after the call to RecordRacingRevoke.
278          */
279         cm_RecordRacingRevoke(NULL, CM_RACINGFLAG_CANCELALL);
280         
281         /* now search all vnodes looking for guys with this callback, if we
282          * found it, or guys with any callbacks, if we didn't find the server
283          * (that's how multihomed machines will appear and how we'll handle
284          * them, albeit a little inefficiently).  That is, we're discarding all
285          * callbacks from all hosts if we get an initstate call from an unknown
286          * host.  Since these calls are rare, and multihomed servers
287          * are "rare," hopefully this won't be a problem.
288          */
289         lock_ObtainWrite(&cm_scacheLock);
290         for(hash = 0; hash < cm_hashTableSize; hash++) {
291                 for(scp=cm_hashTablep[hash]; scp; scp=scp->nextp) {
292                         scp->refCount++;
293                         lock_ReleaseWrite(&cm_scacheLock);
294                         lock_ObtainMutex(&scp->mx);
295                         discarded = 0;
296                         if (scp->cbServerp != NULL) {
297                                 /* we have a callback, now decide if we should clear it */
298                                 if (scp->cbServerp == tsp || tsp == NULL) {
299                         osi_Log1(afsd_logp, "Discarding SCache scp %x", scp);
300                                         cm_DiscardSCache(scp);
301                                         discarded = 1;
302                                 }
303                         }
304                         lock_ReleaseMutex(&scp->mx);
305                         if (discarded)
306                                 cm_CallbackNotifyChange(scp);
307                         lock_ObtainWrite(&cm_scacheLock);
308                         scp->refCount--;
309                 }       /* search one hash bucket */
310         }       /* search all hash buckets */
311         
312         lock_ReleaseWrite(&cm_scacheLock);
313         
314         /* we're done with the server structure */
315         if (tsp) cm_PutServer(tsp);
316     }
317
318     return 0;
319 }
320
321 /* just returns if we're up */
322 SRXAFSCB_Probe(struct rx_call *callp)
323 {
324     osi_Log0(afsd_logp, "SRXAFSCB_Probe - not implemented");
325         return 0;
326 }
327
328 /* debug interface: not implemented */
329 SRXAFSCB_GetCE64(struct rx_call *callp, long index, AFSDBCacheEntry *cep)
330 {
331     /* XXXX */
332     osi_Log0(afsd_logp, "SRXAFSCB_GetCE64 - not implemented");
333     return RXGEN_OPCODE;
334 }
335
336 /* debug interface: not implemented */
337 SRXAFSCB_GetLock(struct rx_call *callp, long index, AFSDBLock *lockp)
338 {
339         /* XXXX */
340     osi_Log0(afsd_logp, "SRXAFSCB_GetLock - not implemented");
341         return RXGEN_OPCODE;
342 }
343
344 /* debug interface: not implemented */
345 SRXAFSCB_GetCE(struct rx_call *callp, long index, AFSDBCacheEntry *cep)
346 {
347         /* XXXX */
348     osi_Log0(afsd_logp, "SRXAFSCB_GetCE - not implemented");
349         return RXGEN_OPCODE;
350 }
351
352 /* debug interface: not implemented */
353 SRXAFSCB_XStatsVersion(struct rx_call *callp, long *vp)
354 {
355         /* XXXX */
356     osi_Log0(afsd_logp, "SRXAFSCB_XStatsVersion - not implemented");
357         *vp = -1;
358         return RXGEN_OPCODE;
359 }
360
361 /* debug interface: not implemented */
362 SRXAFSCB_GetXStats(struct rx_call *callp, long cvn, long coln, long *srvp, long *timep,
363         AFSCB_CollData *datap)
364 {
365         /* XXXX */
366     osi_Log0(afsd_logp, "SRXAFSCB_GetXStats - not implemented");
367         return RXGEN_OPCODE;
368 }
369
370 /* debug interface: not implemented */
371 SRXAFSCB_InitCallBackState2(struct rx_call *callp, struct interfaceAddr* addr)
372 {
373         /* XXXX */
374     osi_Log0(afsd_logp, "SRXAFSCB_InitCallBackState2 - not implemented");
375         return RXGEN_OPCODE;
376 }
377
378 /* debug interface: not implemented */
379 SRXAFSCB_WhoAreYou(struct rx_call *callp, struct interfaceAddr* addr)
380 {
381         /* XXXX */
382     osi_Log0(afsd_logp, "SRXAFSCB_WhoAreYou - not implemented");
383         return RXGEN_OPCODE;
384 }
385
386 /* debug interface: not implemented */
387 SRXAFSCB_InitCallBackState3(struct rx_call *callp, afsUUID* serverUuid)
388 {
389         /* XXXX */
390     osi_Log0(afsd_logp, "SRXAFSCB_InitCallBackState3 - not implemented");
391         return RXGEN_OPCODE;
392 }
393
394 /* debug interface: not implemented */
395 SRXAFSCB_ProbeUuid(struct rx_call *callp, afsUUID* clientUuid)
396 {
397         /* XXXX */
398     osi_Log0(afsd_logp, "SRXAFSCB_ProbeUuid - not implemented");
399         return RXGEN_OPCODE;
400 }
401
402 /*------------------------------------------------------------------------
403  * EXPORTED SRXAFSCB_GetServerPrefs
404  *
405  * Description:
406  *      Routine to list server preferences used by this client.
407  *
408  * Arguments:
409  *      a_call  : Ptr to Rx call on which this request came in.
410  *      a_index : Input server index
411  *      a_srvr_addr  : Output server address (0xffffffff on last server)
412  *      a_srvr_rank  : Output server rank
413  *
414  * Returns:
415  *      0 on success
416  *
417  * Environment:
418  *      Nothing interesting.
419  *
420  * Side Effects:
421  *      As advertised.
422  *------------------------------------------------------------------------*/
423
424 int SRXAFSCB_GetServerPrefs(
425     struct rx_call *a_call,
426     afs_int32 a_index,
427     afs_int32 *a_srvr_addr,
428     afs_int32 *a_srvr_rank)
429 {
430     osi_Log0(afsd_logp, "SRXAFSCB_GetServerPrefs - not implemented");
431
432     *a_srvr_addr = 0xffffffff;
433     *a_srvr_rank = 0xffffffff;
434     return 0;
435 }
436
437 /*------------------------------------------------------------------------
438  * EXPORTED SRXAFSCB_GetCellServDB
439  *
440  * Description:
441  *      Routine to list cells configured for this client
442  *
443  * Arguments:
444  *      a_call  : Ptr to Rx call on which this request came in.
445  *      a_index : Input cell index
446  *      a_name  : Output cell name ("" on last cell)
447  *      a_hosts : Output cell database servers
448  *
449  * Returns:
450  *      0 on success
451  *
452  * Environment:
453  *      Nothing interesting.
454  *
455  * Side Effects:
456  *      As advertised.
457  *------------------------------------------------------------------------*/
458
459 int SRXAFSCB_GetCellServDB(
460     struct rx_call *a_call,
461     afs_int32 a_index,
462     char **a_name,
463     serverList *a_hosts)
464 {
465     char *t_name;
466
467     osi_Log0(afsd_logp, "SRXAFSCB_GetCellServDB - not implemented");
468
469     t_name = (char *)malloc(AFSNAMEMAX);
470     t_name[0] = '\0';
471     *a_name = t_name;
472     a_hosts->serverList_len = 0;
473     return 0;
474 }
475
476 /*------------------------------------------------------------------------
477  * EXPORTED SRXAFSCB_GetLocalCell
478  *
479  * Description:
480  *      Routine to return name of client's local cell
481  *
482  * Arguments:
483  *      a_call  : Ptr to Rx call on which this request came in.
484  *      a_name  : Output cell name
485  *
486  * Returns:
487  *      0 on success
488  *
489  * Environment:
490  *      Nothing interesting.
491  *
492  * Side Effects:
493  *      As advertised.
494  *------------------------------------------------------------------------*/
495
496 int SRXAFSCB_GetLocalCell(
497     struct rx_call *a_call,
498     char **a_name)
499 {
500     char *t_name;
501
502     osi_Log0(afsd_logp, "SRXAFSCB_GetLocalCell");
503
504     if (cm_rootCellp) {
505         t_name = (char *)malloc(strlen(cm_rootCellp->namep)+1);
506         strcpy(t_name, cm_rootCellp->namep);
507     } else {
508         t_name = (char *)malloc(1);
509         t_name[0] = '\0';
510     }
511     *a_name = t_name;
512     return 0;
513 }
514
515
516 /*
517  * afs_MarshallCacheConfig - marshall client cache configuration
518  *
519  * PARAMETERS
520  *
521  * IN callerVersion - the rpc stat version of the caller.
522  *
523  * IN config - client cache configuration.
524  *
525  * OUT ptr - buffer where configuration is marshalled.
526  *
527  * RETURN CODES
528  *
529  * Returns void.
530  */
531 static void afs_MarshallCacheConfig(
532     afs_uint32 callerVersion,
533     cm_initparams_v1 *config,
534     afs_uint32 *ptr)
535 {
536     /*
537      * We currently only support version 1.
538      */
539     *(ptr++) = config->nChunkFiles;
540     *(ptr++) = config->nStatCaches;
541     *(ptr++) = config->nDataCaches;
542     *(ptr++) = config->nVolumeCaches;
543     *(ptr++) = config->firstChunkSize;
544     *(ptr++) = config->otherChunkSize;
545     *(ptr++) = config->cacheSize;
546     *(ptr++) = config->setTime;
547     *(ptr++) = config->memCache;
548
549 }
550  
551
552 /*------------------------------------------------------------------------
553  * EXPORTED SRXAFSCB_GetCacheConfig
554  *
555  * Description:
556  *      Routine to return parameters used to initialize client cache.
557  *      Client may request any format version. Server may not return
558  *      format version greater than version requested by client.
559  *
560  * Arguments:
561  *      a_call:        Ptr to Rx call on which this request came in.
562  *      callerVersion: Data format version desired by the client.
563  *      serverVersion: Data format version of output data.
564  *      configCount:   Number bytes allocated for output data.
565  *      config:        Client cache configuration.
566  *
567  * Returns:
568  *      0 on success
569  *
570  * Environment:
571  *      Nothing interesting.
572  *
573  * Side Effects:
574  *      As advertised.
575  *------------------------------------------------------------------------*/
576
577 int SRXAFSCB_GetCacheConfig(a_call, callerVersion, serverVersion,
578                             configCount, config)
579 struct rx_call *a_call;
580 afs_uint32 callerVersion;
581 afs_uint32 *serverVersion;
582 afs_uint32 *configCount;
583 cacheConfig *config;
584 {
585     afs_uint32 *t_config;
586     size_t allocsize;
587     extern cm_initparams_v1 cm_initParams;
588
589     osi_Log0(afsd_logp, "SRXAFSCB_GetCacheConfig - version 1 only");
590
591     /*
592      * Currently only support version 1
593      */
594     allocsize = sizeof(cm_initparams_v1);
595     t_config = (afs_uint32 *)malloc(allocsize);
596
597     afs_MarshallCacheConfig(callerVersion, &cm_initParams, t_config);
598
599     *serverVersion = AFS_CLIENT_RETRIEVAL_FIRST_EDITION;
600     *configCount = allocsize;
601     config->cacheConfig_val = t_config;
602     config->cacheConfig_len = allocsize/sizeof(afs_uint32);
603
604     return 0;
605 }
606
607 /* called by afsd without any locks to initialize this module */
608 void cm_InitCallback(void)
609 {
610         lock_InitializeRWLock(&cm_callbackLock, "cm_callbackLock");
611         cm_activeCallbackGrantingCalls = 0;
612 }
613
614 /* called with locked scp; tells us whether we've got a callback.
615  * Expirations are checked by a background daemon so as to make
616  * this function as inexpensive as possible
617  */
618 int cm_HaveCallback(cm_scache_t *scp)
619 {
620 #ifdef AFS_FREELANCE_CLIENT
621     // yj: we handle callbacks specially for callbacks on the root directory
622     // Since it's local, we almost always say that we have callback on it
623     // The only time we send back a 0 is if we're need to initialize or
624     // reinitialize the fake directory
625
626     // There are 2 state variables cm_fakeGettingCallback and cm_fakeDirCallback
627     // cm_fakeGettingCallback is 1 if we're in the process of initialization and
628     // hence should return false. it's 0 otherwise
629     // cm_fakeDirCallback is 0 if we haven't loaded the fake directory, it's 1
630     // if the fake directory is loaded and this is the first time cm_HaveCallback
631     // is called since then. We return false in this case to allow cm_GetCallback
632     // to be called because cm_GetCallback has some initialization work to do.
633     // If cm_fakeDirCallback is 2, then it means that the fake directory is in
634     // good shape and we simply return true, provided no change is detected.
635   int fdc, fgc;
636
637     if (cm_freelanceEnabled && 
638         scp->fid.cell==AFS_FAKE_ROOT_CELL_ID &&
639         scp->fid.volume==AFS_FAKE_ROOT_VOL_ID) {        // if it's something on /afs
640         if (!(scp->fid.vnode==0x1 && scp->fid.unique==0x1))     // if it's not root.afs
641             return 1;
642         else {
643             lock_ObtainMutex(&cm_Freelance_Lock);
644             fdc = cm_fakeDirCallback;
645             fgc = cm_fakeGettingCallback;
646             lock_ReleaseMutex(&cm_Freelance_Lock);
647             
648             if (fdc==1) {       // first call since init
649                 return 0;
650             } else if (fdc==2 && !fgc) {        // we're in good shape
651                 if (cm_getLocalMountPointChange()) {    // check for changes
652                     cm_clearLocalMountPointChange(); // clear the changefile
653                     cm_reInitLocalMountPoints();        // start reinit
654                     return 0;
655                 }
656                 return 1;                       // no change
657             }
658             return 0;
659         }
660     }
661 #endif
662
663     if (scp->cbServerp != NULL)
664         return 1;
665     else return 0;
666 }
667
668 /* need to detect a broken callback that races with our obtaining a callback.
669  * Need to be able to do this even if we don't know the file ID of the file
670  * we're breaking the callback on at the time we start the acquisition of the
671  * callback (as in the case where we are creating a file).
672  *
673  * So, we start by writing down the count of the # of callbacks we've received
674  * so far, and bumping a global counter of the # of callback granting calls
675  * outstanding (all done under cm_callbackLock).
676  *
677  * When we're back from the call, we look at all of the callback revokes with
678  * counter numbers greater than the one we recorded in our caller's structure,
679  * and replay those that are higher than when we started the call.
680  * 
681  * We free all the structures in the queue when the count of the # of outstanding
682  * callback-granting calls drops to zero.
683  *
684  * We call this function with the scp locked, too, but in its current implementation,
685  * this knowledge is not used.
686  */
687 void cm_StartCallbackGrantingCall(cm_scache_t *scp, cm_callbackRequest_t *cbrp)
688 {
689         lock_ObtainWrite(&cm_callbackLock);
690         cbrp->callbackCount = cm_callbackCount;
691         cm_activeCallbackGrantingCalls++;
692         cbrp->startTime = osi_Time();
693         cbrp->serverp = NULL;
694         lock_ReleaseWrite(&cm_callbackLock);
695 }
696
697 /* Called at the end of a callback-granting call, to remove the callback
698  * info from the scache entry, if necessary.
699  *
700  * Called with scp locked, so we can discard the callbacks easily with
701  * this locking hierarchy.
702  */
703 void cm_EndCallbackGrantingCall(cm_scache_t *scp, cm_callbackRequest_t *cbrp,
704         AFSCallBack *cbp, long flags)
705 {
706         cm_racingRevokes_t *revp;               /* where we are */
707         cm_racingRevokes_t *nrevp;              /* where we'll be next */
708         int freeFlag;
709
710         lock_ObtainWrite(&cm_callbackLock);
711         if (flags & CM_CALLBACK_MAINTAINCOUNT) {
712                 osi_assert(cm_activeCallbackGrantingCalls > 0);
713         }
714         else {
715                 osi_assert(cm_activeCallbackGrantingCalls-- > 0);
716         }
717         if (cm_activeCallbackGrantingCalls == 0) freeFlag = 1;
718         else freeFlag = 0;
719
720         /* record the callback; we'll clear it below if we really lose it */
721         if (scp) {
722                 scp->cbServerp = cbrp->serverp;
723                 scp->cbExpires = cbrp->startTime + cbp->ExpirationTime;
724         }
725
726         /* a callback was actually revoked during our granting call, so
727          * run down the list of revoked fids, looking for ours.
728          * If activeCallbackGrantingCalls is zero, free the elements, too.
729          *
730          * May need to go through entire list just to do the freeing.
731          */
732         for(revp = cm_racingRevokesp; revp; revp = nrevp) {
733                 nrevp = (cm_racingRevokes_t *) osi_QNext(&revp->q);
734                 /* if this callback came in later than when we started the
735                  * callback-granting call, and if this fid is the right fid,
736                  * then clear the callback.
737                  */
738                 if (scp && cbrp->callbackCount != cm_callbackCount
739                         && revp->callbackCount > cbrp->callbackCount
740              && (( scp->fid.volume == revp->fid.volume &&
741                                  scp->fid.vnode == revp->fid.vnode &&
742                                  scp->fid.unique == revp->fid.unique)
743                             ||
744                                 ((revp->flags & CM_RACINGFLAG_CANCELVOL) &&
745                                  scp->fid.volume == revp->fid.volume)
746                             ||
747                                 (revp->flags & CM_RACINGFLAG_CANCELALL))) {
748                         /* this one matches */
749                         osi_Log4(afsd_logp,
750                         "Racing revoke scp %x old cbc %d rev cbc %d cur cbc %d",
751                                  scp,
752                                  cbrp->callbackCount, revp->callbackCount,
753                                  cm_callbackCount);
754                         cm_DiscardSCache(scp);
755                         /*
756                          * Since we don't have a callback to preserve, it's
757                          * OK to drop the lock and re-obtain it.
758                          */
759                         lock_ReleaseMutex(&scp->mx);
760                         cm_CallbackNotifyChange(scp);
761                         lock_ObtainMutex(&scp->mx);
762                 }
763                 if (freeFlag) free(revp);
764         }
765
766         /* if we freed the list, zap the pointer to it */
767         if (freeFlag) cm_racingRevokesp = NULL;
768
769         lock_ReleaseWrite(&cm_callbackLock);
770 }
771
772 /* if flags is 1, we want to force the code to make one call, anyway.
773  * called with locked scp; returns with same.
774  */
775 long cm_GetCallback(cm_scache_t *scp, struct cm_user *userp,
776         struct cm_req *reqp, long flags)
777 {
778         long code;
779     cm_conn_t *connp;
780     AFSFetchStatus afsStatus;
781     AFSVolSync volSync;
782     AFSCallBack callback;
783     AFSFid tfid;
784     cm_callbackRequest_t cbr;
785     int mustCall;
786     long sflags;
787     cm_fid_t sfid;
788
789     osi_Log2(afsd_logp, "GetCallback scp %x flags %lX", scp, flags);
790
791 #ifdef AFS_FREELANCE_CLIENT
792         // yj
793         // The case where a callback is needed on /afs is handled
794         // specially. We need to fetch the status by calling
795         // cm_MergeStatus and mark that cm_fakeDirCallback is 2
796         if (cm_freelanceEnabled &&
797         scp->fid.cell==AFS_FAKE_ROOT_CELL_ID &&
798                 scp->fid.volume==AFS_FAKE_ROOT_VOL_ID &&
799                 scp->fid.unique==0x1 &&
800                 scp->fid.vnode==0x1) {
801                 // Start by indicating that we're in the process
802                 // of fetching the callback
803
804         lock_ObtainMutex(&cm_Freelance_Lock);
805                 cm_fakeGettingCallback = 1;
806                 lock_ReleaseMutex(&cm_Freelance_Lock);
807
808                 // Fetch the status info 
809                 cm_MergeStatus(scp, &afsStatus, &volSync, userp, 0);
810
811                 // Indicate that the callback is not done
812                 lock_ObtainMutex(&cm_Freelance_Lock);
813                 cm_fakeDirCallback = 2;
814                 // Indicate that we're no longer fetching the callback
815                 cm_fakeGettingCallback = 0;
816                 lock_ReleaseMutex(&cm_Freelance_Lock);
817
818                 return 0;
819         }
820
821         if (scp->fid.cell==AFS_FAKE_ROOT_CELL_ID && scp->fid.volume==AFS_FAKE_ROOT_VOL_ID) {
822                 osi_Log0(afsd_logp,"cm_getcallback should NEVER EVER get here... ");
823         }
824         // yj: end of getcallback modifications  ---------------
825                 
826 #endif /* AFS_FREELANCE_CLIENT */
827         
828         mustCall = (flags & 1);
829         cm_AFSFidFromFid(&tfid, &scp->fid);
830         while (1) {
831                 if (!mustCall && cm_HaveCallback(scp)) return 0;
832
833         /* turn off mustCall, since it has now forced us past the check above */
834         mustCall = 0;
835
836         /* otherwise, we have to make an RPC to get the status */
837                 sflags = CM_SCACHESYNC_FETCHSTATUS | CM_SCACHESYNC_GETCALLBACK;
838         cm_SyncOp(scp, NULL, NULL, NULL, 0, sflags);
839         cm_StartCallbackGrantingCall(scp, &cbr);
840         sfid = scp->fid;
841                 lock_ReleaseMutex(&scp->mx);
842                 
843                 /* now make the RPC */
844                 osi_Log1(afsd_logp, "CALL FetchStatus vp %x", (long) scp);
845         do {
846                         code = cm_Conn(&sfid, userp, reqp, &connp);
847             if (code) continue;
848                 
849             code = RXAFS_FetchStatus(connp->callp, &tfid,
850                                      &afsStatus, &callback, &volSync);
851
852                 } while (cm_Analyze(connp, userp, reqp, &sfid, &volSync, NULL,
853                             &cbr, code));
854         code = cm_MapRPCError(code, reqp);
855                 osi_Log0(afsd_logp, "CALL FetchStatus DONE");
856
857                 lock_ObtainMutex(&scp->mx);
858         cm_SyncOpDone(scp, NULL, sflags);
859                 if (code == 0) {
860             cm_EndCallbackGrantingCall(scp, &cbr, &callback, 0);
861             cm_MergeStatus(scp, &afsStatus, &volSync, userp, 0);
862                 }   
863         else
864             cm_EndCallbackGrantingCall(NULL, NULL, NULL, 0);
865
866         /* now check to see if we got an error */
867         if (code) return code;
868     }
869 }
870
871 /* called periodically by cm_daemon to shut down use of expired callbacks */
872 void cm_CheckCBExpiration(void)
873 {
874         int i;
875         cm_scache_t *scp;
876         long now;
877         
878     osi_Log0(afsd_logp, "CheckCBExpiration");
879
880         now = osi_Time();
881         lock_ObtainWrite(&cm_scacheLock);
882         for(i=0; i<cm_hashTableSize; i++) {
883                 for(scp = cm_hashTablep[i]; scp; scp=scp->nextp) {
884                         scp->refCount++;
885                         lock_ReleaseWrite(&cm_scacheLock);
886                         lock_ObtainMutex(&scp->mx);
887                         if (scp->cbServerp && now > scp->cbExpires) {
888                 osi_Log1(afsd_logp, "Discarding SCache scp %x", scp);
889                                 cm_DiscardSCache(scp);
890                         }
891                         lock_ReleaseMutex(&scp->mx);
892                         lock_ObtainWrite(&cm_scacheLock);
893                         osi_assert(scp->refCount-- > 0);
894                 }
895         }
896         lock_ReleaseWrite(&cm_scacheLock);
897 }
898
899 /* debug interface: not implemented */
900 int SRXAFSCB_GetCellByNum(struct rx_call *a_call, afs_int32 a_cellnum,
901                           char **a_name, serverList *a_hosts)
902 {
903     /* XXXX */
904     osi_Log0(afsd_logp, "SRXAFSCB_GetCellByNum - not implemented");
905     return RXGEN_OPCODE;
906 }
907
908 /* debug interface: not implemented */
909 int SRXAFSCB_TellMeAboutYourself(struct rx_call *a_call, afs_int32 a_cellnum,
910                           char **a_name, serverList *a_hosts)
911 {
912     /* XXXX */
913     osi_Log0(afsd_logp, "SRXAFSCB_TellMeAboutYourself - not implemented");
914     return RXGEN_OPCODE;
915 }