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