windows-afsifs-20050804
[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 #include <rx_pthread.h>
26
27 #include "afsd.h"
28 #include <WINNT/syscfg.h>
29 #include <WINNT/afsreg.h>
30 #include <../afsrdr/kif.h>
31
32 /*extern void afsi_log(char *pattern, ...);*/
33
34 /* read/write lock for all global storage in this module */
35 osi_rwlock_t cm_callbackLock;
36
37 #ifdef AFS_FREELANCE_CLIENT
38 extern osi_mutex_t cm_Freelance_Lock;
39 #endif
40
41 /* count of # of callback breaking messages received by this CM so far.  We use
42  * this count in determining whether there have been any callback breaks that
43  * apply to a call that returned a new callback.  If the counter doesn't
44  * increase during a call, then we know that no callbacks were broken during
45  * that call, and thus that the callback that was just returned is still valid.
46  */
47 long cm_callbackCount;
48
49 /* count of number of RPCs potentially returning a callback executing now.
50  * When this counter hits zero, we can clear out the racing revokes list, since
51  * at that time, we know that none of the just-executed callback revokes will
52  * apply to any future call that returns a callback (since the latter hasn't
53  * even started execution yet).
54  */
55 long cm_activeCallbackGrantingCalls;
56
57 /* list of callbacks that have been broken recently.  If a call returning a
58  * callback is executing and a callback revoke runs immediately after it at the
59  * server, the revoke may end up being processed before the response to the
60  * original callback granting call.  We detect this by keeping a list of
61  * callback revokes that have been received since we *started* the callback
62  * granting call, and discarding any callbacks received for the same file ID,
63  * even if the callback revoke was received before the callback grant.
64  */
65 cm_racingRevokes_t *cm_racingRevokesp;
66
67 /* record a (potentially) racing revoke for this file ID; null means for all
68  * file IDs, and is used by InitCallBackState.
69  *
70  * The cancelFlags describe whether we're just discarding callbacks for the same
71  * file ID, the same volume, or all from the same server.
72  *
73  * Called with no locks held.
74  */
75 void cm_RecordRacingRevoke(cm_fid_t *fidp, long cancelFlags)
76 {
77     cm_racingRevokes_t *rp;
78
79     lock_ObtainWrite(&cm_callbackLock);
80
81     osi_Log3(afsd_logp, "RecordRacingRevoke Volume %d Flags %lX activeCalls %d",
82                 fidp ? fidp->volume : 0, cancelFlags, cm_activeCallbackGrantingCalls);
83
84     if (cm_activeCallbackGrantingCalls > 0) {
85         rp = malloc(sizeof(*rp));
86         memset(rp, 0, sizeof(*rp));
87         osi_QAdd((osi_queue_t **) &cm_racingRevokesp, &rp->q);
88         rp->flags |= (cancelFlags & CM_RACINGFLAG_ALL);
89         if (fidp) rp->fid = *fidp;
90         rp->callbackCount = ++cm_callbackCount;
91     }
92     lock_ReleaseWrite(&cm_callbackLock);
93 }
94
95 /*
96  * When we lose a callback, may have to send change notification replies.
97  * Do not call with a lock on the scp.
98  */
99 void cm_CallbackNotifyChange(cm_scache_t *scp)
100 {
101     DWORD dwDelay = 0;
102     HKEY  hKey;
103     DWORD dummyLen;
104
105     /* why does this have to query the registry each time? */
106         if (RegOpenKeyEx( HKEY_LOCAL_MACHINE, 
107                       AFSREG_CLT_OPENAFS_SUBKEY,
108                       0,
109                       KEY_READ|KEY_QUERY_VALUE,
110                       &hKey) == ERROR_SUCCESS) {
111
112         dummyLen = sizeof(DWORD);
113         RegQueryValueEx(hKey, "CallBack Notify Change Delay", NULL, NULL,
114                         (BYTE *) &dwDelay, &dummyLen);
115         RegCloseKey(hKey);
116     }
117
118     if (dwDelay > 5000)    /* do not allow a delay of more then 5 seconds */
119         dwDelay = 5000;   
120
121     osi_Log3(afsd_logp, "CallbackNotifyChange FileType %d Flags %lX Delay %dms",
122               scp->fileType, scp->flags, dwDelay);
123
124     if (dwDelay)
125         Sleep(dwDelay);
126
127     /* for directories, this sends a change notification on the dir itself */
128         if (scp->fileType == CM_SCACHETYPE_DIRECTORY) {
129 #ifndef AFSIFS
130         if (scp->flags & CM_SCACHEFLAG_ANYWATCH)
131             smb_NotifyChange(0,
132                              FILE_NOTIFY_GENERIC_DIRECTORY_FILTER,
133                              scp, NULL, NULL, TRUE);
134 #else
135         dc_break_callback(FID_HASH_FN(&scp->fid));
136 #endif
137     } else {
138         /* and for files, this sends a change notification on the file's parent dir */
139         cm_fid_t tfid;
140         cm_scache_t *dscp;
141
142         tfid.cell = scp->fid.cell;
143         tfid.volume = scp->fid.volume;
144         tfid.vnode = scp->parentVnode;
145         tfid.unique = scp->parentUnique;
146         dscp = cm_FindSCache(&tfid);
147 #ifndef AFSIFS
148         if ( dscp &&
149              dscp->flags & CM_SCACHEFLAG_ANYWATCH )
150             smb_NotifyChange( 0,
151                               FILE_NOTIFY_GENERIC_FILE_FILTER,
152                               dscp,   NULL, NULL, TRUE);
153 #else
154         if (dscp)
155             dc_break_callback(FID_HASH_FN(&dscp->fid));
156 #endif
157         if (dscp) 
158             cm_ReleaseSCache(dscp);
159     }
160 }
161
162 /* called with no locks held for every file ID that is revoked directly by
163  * a callback revoke call.  Does not have to handle volume callback breaks,
164  * since those have already been split out.
165  *
166  * The callp parameter is currently unused.
167  */
168 void cm_RevokeCallback(struct rx_call *callp, AFSFid *fidp)
169 {
170     cm_fid_t tfid;
171     cm_scache_t *scp;
172     long hash;
173         
174     /* don't bother setting cell, since we won't be checking it (to aid
175      * in working with multi-homed servers: we don't know the cell if we
176      * don't recognize the IP address).
177      */
178     tfid.cell = 0;
179     tfid.volume = fidp->Volume;
180     tfid.vnode = fidp->Vnode;
181     tfid.unique = fidp->Unique;
182     hash = CM_SCACHE_HASH(&tfid);
183
184     osi_Log3(afsd_logp, "RevokeCallback vol %u vn %u uniq %u",
185              fidp->Volume, fidp->Vnode, fidp->Unique);
186         
187     /* do this first, so that if we're executing a callback granting call
188      * at this moment, we kill it before it can be merged in.  Otherwise,
189      * it could complete while we're doing the scan below, and get missed
190      * by both the scan and by this code.
191      */
192     cm_RecordRacingRevoke(&tfid, 0);
193
194     lock_ObtainWrite(&cm_scacheLock);
195     /* do all in the hash bucket, since we don't know how many we'll find with
196      * varying cells.
197      */
198     for (scp = cm_data.hashTablep[hash]; scp; scp=scp->nextp) {
199         if (scp->fid.volume == tfid.volume &&
200              scp->fid.vnode == tfid.vnode &&
201              scp->fid.unique == tfid.unique &&
202              scp->cbExpires > 0 && 
203              scp->cbServerp != NULL)
204         {
205             cm_HoldSCacheNoLock(scp);
206             lock_ReleaseWrite(&cm_scacheLock);
207             osi_Log4(afsd_logp, "RevokeCallback Discarding SCache scp 0x%x vol %u vn %u uniq %u", 
208                      scp, scp->fid.volume, scp->fid.vnode, scp->fid.unique);
209             lock_ObtainMutex(&scp->mx);
210             cm_DiscardSCache(scp);
211             lock_ReleaseMutex(&scp->mx);
212             cm_CallbackNotifyChange(scp);
213             lock_ObtainWrite(&cm_scacheLock);
214             cm_ReleaseSCacheNoLock(scp);
215         }
216     }
217     lock_ReleaseWrite(&cm_scacheLock);
218
219     osi_Log3(afsd_logp, "RevokeCallback Complete vol %u vn %u uniq %u",
220              fidp->Volume, fidp->Vnode, fidp->Unique);
221 }
222
223 /* called to revoke a volume callback, which is typically issued when a volume
224  * is moved from one server to another.
225  *
226  * Called with no locks held.
227  */
228 void cm_RevokeVolumeCallback(struct rx_call *callp, AFSFid *fidp)
229 {
230     long hash;
231     cm_scache_t *scp;
232     cm_fid_t tfid;
233
234     osi_Log1(afsd_logp, "RevokeVolumeCallback vol %d", fidp->Volume);
235
236     /* do this first, so that if we're executing a callback granting call
237      * at this moment, we kill it before it can be merged in.  Otherwise,
238      * it could complete while we're doing the scan below, and get missed
239      * by both the scan and by this code.
240      */
241     tfid.cell = tfid.vnode = tfid.unique = 0;
242     tfid.volume = fidp->Volume;
243     cm_RecordRacingRevoke(&tfid, CM_RACINGFLAG_CANCELVOL);
244
245
246     lock_ObtainWrite(&cm_scacheLock);
247     for (hash = 0; hash < cm_data.hashTableSize; hash++) {
248         for(scp=cm_data.hashTablep[hash]; scp; scp=scp->nextp) {
249             if (scp->fid.volume == fidp->Volume &&
250                  scp->cbExpires > 0 &&
251                  scp->cbServerp != NULL) {
252                 cm_HoldSCacheNoLock(scp);
253                 lock_ReleaseWrite(&cm_scacheLock);
254                 lock_ObtainMutex(&scp->mx);
255                 osi_Log4(afsd_logp, "RevokeVolumeCallback Discarding SCache scp 0x%x vol %u vn %u uniq %u", 
256                           scp, scp->fid.volume, scp->fid.vnode, scp->fid.unique);
257                 cm_DiscardSCache(scp);
258                 lock_ReleaseMutex(&scp->mx);
259                 cm_CallbackNotifyChange(scp);
260                 lock_ObtainWrite(&cm_scacheLock);
261                 cm_ReleaseSCacheNoLock(scp);
262             }
263         }       /* search one hash bucket */
264     }   /* search all hash buckets */
265
266     lock_ReleaseWrite(&cm_scacheLock);
267
268     osi_Log1(afsd_logp, "RevokeVolumeCallback Complete vol %d", fidp->Volume);
269 }
270
271 /*
272  * afs_data_pointer_to_int32() - returns least significant afs_int32 of the
273  * given data pointer, without triggering "cast truncates pointer"
274  * warnings.  We use this where we explicitly don't care whether a
275  * pointer is truncated -- it loses information where a pointer is
276  * larger than an afs_int32.
277  */
278
279 static afs_int32
280 afs_data_pointer_to_int32(const void *p)
281 {
282     union {
283         afs_int32 i32[sizeof(void *) / sizeof(afs_int32)];
284         const void *p;
285     } ip;
286
287     int i32_sub;                /* subscript of least significant afs_int32 in ip.i32[] */
288
289     /* set i32_sub */
290
291     {
292         /* used to determine the byte order of the system */
293
294         union {
295             char c[sizeof(int) / sizeof(char)];
296             int i;
297         } ci;
298
299         ci.i = 1;
300         if (ci.c[0] == 1) {
301             /* little-endian system */
302             i32_sub = 0;
303         } else {
304             /* big-endian system */
305             i32_sub = (sizeof ip.i32 / sizeof ip.i32[0]) - 1;
306         }
307     }
308
309     ip.p = p;
310     return ip.i32[i32_sub];
311 }
312 /*------------------------------------------------------------------------
313  * EXPORTED SRXAFSCB_CallBack
314  *
315  * Description:
316  *      Routine called by the server-side callback RPC interface to
317  *      implement passing in callback information.
318  *      table.
319  *
320  * Arguments:
321  *      rx_call    : Ptr to Rx call on which this request came in.
322  *      fidsArrayp : Ptr to array of fids involved.
323  *      cbsArrayp  : Ptr to matching callback info for the fids.
324  *
325  * Returns:
326  *      0 (always).
327  *
328  * Environment:
329  *      Nothing interesting.
330  *
331  * Side Effects:
332  *      As advertised.
333  *------------------------------------------------------------------------*/
334 /* handle incoming RPC callback breaking message.
335  * Called with no locks held.
336  */
337 int
338 SRXAFSCB_CallBack(struct rx_call *callp, AFSCBFids *fidsArrayp, AFSCBs *cbsArrayp)
339 {
340     int i;
341     AFSFid *tfidp;
342     struct rx_connection *connp;
343     struct rx_peer *peerp;
344     unsigned long host = 0;
345     unsigned short port = 0;
346
347     MUTEX_ENTER(&callp->lock);
348
349     if ((connp = rx_ConnectionOf(callp)) && (peerp = rx_PeerOf(connp))) {
350         host = rx_HostOf(peerp);
351         port = rx_PortOf(peerp);
352     }
353
354     osi_Log2(afsd_logp, "SRXAFSCB_CallBack from host 0x%x port %d",
355               ntohl(host),
356               ntohs(port));
357
358     for (i=0; i < (long) fidsArrayp->AFSCBFids_len; i++) {
359         tfidp = &fidsArrayp->AFSCBFids_val[i];
360                 
361         if (tfidp->Volume == 0)
362             continue;   /* means don't do anything */
363         else if (tfidp->Vnode == 0)
364             cm_RevokeVolumeCallback(callp, tfidp);
365         else
366             cm_RevokeCallback(callp, tfidp);
367     }
368
369     MUTEX_EXIT(&callp->lock);
370     return 0;
371 }
372
373 /*------------------------------------------------------------------------
374  * EXPORTED SRXAFSCB_InitCallBackState
375  *
376  * Description:
377  *      Routine called by the server-side callback RPC interface to
378  *      implement clearing all callbacks from this host.
379  *
380  * Arguments:
381  *      rx_call : Ptr to Rx call on which this request came in.
382  *
383  * Returns:
384  *      0 (always).
385  *
386  * Environment:
387  *      Nothing interesting.
388  *
389  * Side Effects:
390  *      As advertised.
391  *------------------------------------------------------------------------*/
392 /* called with no locks by RPC system when a server indicates that it has never
393  * heard from us, or for other reasons has had to discard callbacks from us
394  * without telling us, e.g. a network partition.
395  */
396 int
397 SRXAFSCB_InitCallBackState(struct rx_call *callp)
398 {
399     struct sockaddr_in taddr;
400     cm_server_t *tsp;
401     cm_scache_t *scp;
402     int hash;
403     int discarded;
404     struct rx_connection *connp;
405     struct rx_peer *peerp;
406     unsigned long host = 0;
407     unsigned short port = 0;
408
409     MUTEX_ENTER(&callp->lock);
410
411     if ((connp = rx_ConnectionOf(callp)) && (peerp = rx_PeerOf(connp))) {
412         host = rx_HostOf(peerp);
413         port = rx_PortOf(peerp);
414     }
415
416     osi_Log2(afsd_logp, "SRXAFSCB_InitCallBackState from host 0x%x port %d",
417               ntohl(host),
418               ntohs(port));
419
420     if ((rx_ConnectionOf(callp)) && (rx_PeerOf(rx_ConnectionOf(callp)))) {
421         taddr.sin_family = AF_INET;
422         taddr.sin_addr.s_addr = rx_HostOf(rx_PeerOf(rx_ConnectionOf(callp)));
423
424         tsp = cm_FindServer(&taddr, CM_SERVER_FILE);
425
426         osi_Log1(afsd_logp, "Init Callback State server %x", tsp);
427         
428         /* record the callback in the racing revokes structure.  This
429          * shouldn't be necessary, since we shouldn't be making callback
430          * granting calls while we're going to get an initstate call,
431          * but there probably are some obscure races, so better safe
432          * than sorry.
433          *
434          * We do this first since we don't hold the cm_scacheLock and vnode
435          * locks over the entire callback scan operation below.  The
436          * big loop below is guaranteed to hit any callback already
437          * processed.  The call to RecordRacingRevoke is guaranteed
438          * to kill any callback that is currently being returned.
439          * Anything that sneaks past both must start
440          * after the call to RecordRacingRevoke.
441          */
442         cm_RecordRacingRevoke(NULL, CM_RACINGFLAG_CANCELALL);
443         
444         /* now search all vnodes looking for guys with this callback, if we
445          * found it, or guys with any callbacks, if we didn't find the server
446          * (that's how multihomed machines will appear and how we'll handle
447          * them, albeit a little inefficiently).  That is, we're discarding all
448          * callbacks from all hosts if we get an initstate call from an unknown
449          * host.  Since these calls are rare, and multihomed servers
450          * are "rare," hopefully this won't be a problem.
451          */
452         lock_ObtainWrite(&cm_scacheLock);
453         for (hash = 0; hash < cm_data.hashTableSize; hash++) {
454             for (scp=cm_data.hashTablep[hash]; scp; scp=scp->nextp) {
455                 cm_HoldSCacheNoLock(scp);
456                 lock_ReleaseWrite(&cm_scacheLock);
457                 lock_ObtainMutex(&scp->mx);
458                 discarded = 0;
459                 if (scp->cbExpires > 0 && scp->cbServerp != NULL) {
460                     /* we have a callback, now decide if we should clear it */
461                     if (scp->cbServerp == tsp || tsp == NULL) {
462                         osi_Log4(afsd_logp, "InitCallbackState Discarding SCache scp 0x%x vol %u vn %u uniq %u", 
463                                   scp, scp->fid.volume, scp->fid.vnode, scp->fid.unique);
464                         cm_DiscardSCache(scp);
465                         discarded = 1;
466                     }
467                 }
468                 lock_ReleaseMutex(&scp->mx);
469                 if (discarded)
470                     cm_CallbackNotifyChange(scp);
471                 lock_ObtainWrite(&cm_scacheLock);
472                 cm_ReleaseSCacheNoLock(scp);
473             }   /* search one hash bucket */
474         }       /* search all hash buckets */
475         
476         lock_ReleaseWrite(&cm_scacheLock);
477         
478         /* we're done with the server structure */
479         if (tsp) 
480             cm_PutServer(tsp);
481     }
482     MUTEX_EXIT(&callp->lock);
483     return 0;
484 }
485
486 /*------------------------------------------------------------------------
487  * EXPORTED SRXAFSCB_Probe
488  *
489  * Description:
490  *      Routine called by the server-side callback RPC interface to
491  *      implement ``probing'' the Cache Manager, just making sure it's
492  *      still there.
493  *
494  * Arguments:
495  *      rx_call : Ptr to Rx call on which this request came in.
496  *
497  * Returns:
498  *      0 (always).
499  *
500  * Environment:
501  *      Nothing interesting.
502  *
503  * Side Effects:
504  *      As advertised.
505  *------------------------------------------------------------------------*/
506 int
507 SRXAFSCB_Probe(struct rx_call *callp)
508 {
509     struct rx_connection *connp;
510     struct rx_peer *peerp;
511     unsigned long host = 0;
512     unsigned short port = 0;
513
514     MUTEX_ENTER(&callp->lock);
515
516     if ((connp = rx_ConnectionOf(callp)) && (peerp = rx_PeerOf(connp))) {
517         host = rx_HostOf(peerp);
518         port = rx_PortOf(peerp);
519     }
520
521     osi_Log2(afsd_logp, "SRXAFSCB_Probe from host 0x%x port %d",
522               ntohl(host),
523               ntohs(port));
524
525     MUTEX_EXIT(&callp->lock);
526     return 0;
527 }
528
529 /*------------------------------------------------------------------------
530  * EXPORTED SRXAFSCB_GetLock
531  *
532  * Description:
533  *      Routine called by the server-side callback RPC interface to
534  *      implement pulling out the contents of a lock in the lock
535  *      table.
536  *
537  * Arguments:
538  *      a_call   : Ptr to Rx call on which this request came in.
539  *      a_index  : Index of desired lock.
540  *      a_result : Ptr to a buffer for the given lock.
541  *
542  * Returns:
543  *      0 if everything went fine,
544  *      1 if we were given a bad index.
545  *
546  * Environment:
547  *      Nothing interesting.
548  *
549  * Side Effects:
550  *      As advertised.
551  *------------------------------------------------------------------------*/
552 /* debug interface */
553
554 extern osi_rwlock_t cm_aclLock;
555 extern osi_rwlock_t buf_globalLock;
556 extern osi_rwlock_t cm_callbackLock;
557 extern osi_rwlock_t cm_cellLock;
558 extern osi_rwlock_t cm_connLock;
559 extern osi_rwlock_t cm_daemonLock;
560 extern osi_rwlock_t cm_dnlcLock;
561 extern osi_rwlock_t cm_scacheLock;
562 extern osi_rwlock_t cm_serverLock;
563 extern osi_rwlock_t cm_userLock;
564 extern osi_rwlock_t cm_utilsLock;
565 extern osi_rwlock_t cm_volumeLock;
566 extern osi_rwlock_t smb_globalLock;
567 extern osi_rwlock_t smb_rctLock;
568
569 extern osi_mutex_t cm_Freelance_Lock;
570 extern osi_mutex_t cm_bufGetMutex;
571 extern osi_mutex_t cm_Afsdsbmt_Lock;
572 extern osi_mutex_t tokenEventLock;
573 extern osi_mutex_t  smb_ListenerLock;
574 extern osi_mutex_t smb_RawBufLock;
575 extern osi_mutex_t smb_Dir_Watch_Lock;
576
577 #define LOCKTYPE_RW     1
578 #define LOCKTYPE_MUTEX  2
579 static struct _ltable {
580     char *name;
581     char *addr;
582     int  type;
583 } ltable[] = {
584     {"cm_scacheLock",    (char*)&cm_scacheLock,         LOCKTYPE_RW},
585     {"buf_globalLock",   (char*)&buf_globalLock,        LOCKTYPE_RW},
586     {"cm_serverLock",    (char*)&cm_serverLock,         LOCKTYPE_RW},
587     {"cm_callbackLock",  (char*)&cm_callbackLock,       LOCKTYPE_RW},
588     {"cm_aclLock",       (char*)&cm_aclLock,            LOCKTYPE_RW},
589     {"cm_cellLock",      (char*)&cm_cellLock,           LOCKTYPE_RW},
590     {"cm_connLock",      (char*)&cm_connLock,           LOCKTYPE_RW},
591     {"cm_userLock",      (char*)&cm_userLock,           LOCKTYPE_RW},
592     {"cm_volumeLock",    (char*)&cm_volumeLock,         LOCKTYPE_RW},
593     {"cm_daemonLock",    (char*)&cm_daemonLock,         LOCKTYPE_RW},
594     {"cm_dnlcLock",      (char*)&cm_dnlcLock,           LOCKTYPE_RW},
595     {"cm_utilsLock",     (char*)&cm_utilsLock,          LOCKTYPE_RW},
596     {"smb_globalLock",   (char*)&smb_globalLock,        LOCKTYPE_RW},
597     {"smb_rctLock",      (char*)&smb_rctLock,           LOCKTYPE_RW},
598     {"cm_Freelance_Lock",(char*)&cm_Freelance_Lock,     LOCKTYPE_MUTEX},
599     {"cm_bufGetMutex",   (char*)&cm_bufGetMutex,        LOCKTYPE_MUTEX},
600     {"cm_Afsdsbmt_Lock", (char*)&cm_Afsdsbmt_Lock,      LOCKTYPE_MUTEX},
601     {"tokenEventLock",   (char*)&tokenEventLock,        LOCKTYPE_MUTEX},
602     {"smb_ListenerLock", (char*)&smb_ListenerLock,      LOCKTYPE_MUTEX},
603     {"smb_RawBufLock",   (char*)&smb_RawBufLock,        LOCKTYPE_MUTEX},
604     {"smb_Dir_Watch_Lock",(char*)&smb_Dir_Watch_Lock,   LOCKTYPE_MUTEX}
605 };
606
607 int
608 SRXAFSCB_GetLock(struct rx_call *callp, long index, AFSDBLock *lockp)
609 {
610     struct _ltable *tl;          /*Ptr to lock table entry */
611     osi_rwlock_t  *rwp;
612     osi_mutex_t   *mtxp;
613     int nentries;               /*Num entries in table */
614     int code;                   /*Return code */
615     struct rx_connection *connp;
616     struct rx_peer *peerp;
617     unsigned long host = 0;
618     unsigned short port = 0;
619
620     MUTEX_ENTER(&callp->lock);
621
622     if ((connp = rx_ConnectionOf(callp)) && (peerp = rx_PeerOf(connp))) {
623         host = rx_HostOf(peerp);
624         port = rx_PortOf(peerp);
625     }
626
627     osi_Log3(afsd_logp, "SRXAFSCB_GetLock(%d) from host 0x%x port %d", 
628              index, ntohl(host), ntohs(port));
629
630     nentries = sizeof(ltable) / sizeof(struct _ltable);
631     if (index < 0 || index >= nentries) {
632         /*
633          * Past EOF
634          */
635         code = 1;
636     } else {
637         /*
638          * Found it - copy out its contents.
639          */
640         tl = &ltable[index];
641         strncpy(lockp->name, tl->name, sizeof(lockp->name));
642         lockp->name[sizeof(lockp->name)-1] = '\0';
643         lockp->lock.waitStates = 0;
644         switch ( tl->type ) {
645         case LOCKTYPE_RW:
646             rwp = (osi_rwlock_t *)tl->addr;
647             lockp->lock.exclLocked = rwp->flags;
648             lockp->lock.readersReading = rwp->readers;
649             lockp->lock.numWaiting = rwp->waiters;
650             break;
651         case LOCKTYPE_MUTEX:
652             mtxp = (osi_mutex_t *)tl->addr;
653             lockp->lock.exclLocked = mtxp->flags;
654             lockp->lock.readersReading = 0;
655             lockp->lock.numWaiting = mtxp->waiters;
656             break;
657         }
658         lockp->lock.pid_last_reader = 0;
659         lockp->lock.pid_writer = 0;
660         lockp->lock.src_indicator = 0;
661         code = 0;
662     }
663
664     MUTEX_EXIT(&callp->lock);
665     return code;
666 }
667
668 /* debug interface */
669 int
670 SRXAFSCB_GetCE(struct rx_call *callp, long index, AFSDBCacheEntry *cep)
671 {
672     int i;
673     cm_scache_t * scp;
674     int code;
675     struct rx_connection *connp;
676     struct rx_peer *peerp;
677     unsigned long host = 0;
678     unsigned short port = 0;
679
680     MUTEX_ENTER(&callp->lock);
681
682     if ((connp = rx_ConnectionOf(callp)) && (peerp = rx_PeerOf(connp))) {
683         host = rx_HostOf(peerp);
684         port = rx_PortOf(peerp);
685     }
686
687     osi_Log2(afsd_logp, "SRXAFSCB_GetCE from host 0x%x port %d",
688              ntohl(host), ntohs(port));
689
690     lock_ObtainRead(&cm_scacheLock);
691     for (i = 0; i < cm_data.hashTableSize; i++) {
692         for (scp = cm_data.hashTablep[i]; scp; scp = scp->nextp) {
693             if (index == 0)
694                 goto searchDone;
695             index--;
696         }                       /*Zip through current hash chain */
697     }                           /*Zip through hash chains */
698
699   searchDone:
700     if (scp == NULL) {
701         /*Past EOF */
702         code = 1;
703         goto fcnDone;
704     }
705
706     /*
707      * Copy out the located entry.
708      */
709     memset(cep, 0, sizeof(AFSDBCacheEntry));
710     cep->addr = afs_data_pointer_to_int32(scp);
711     cep->cell = scp->fid.cell;
712     cep->netFid.Volume = scp->fid.volume;
713     cep->netFid.Vnode = scp->fid.vnode;
714     cep->netFid.Unique = scp->fid.unique;
715     cep->lock.waitStates = 0;
716     cep->lock.exclLocked = scp->mx.flags;
717     cep->lock.readersReading = 0;
718     cep->lock.numWaiting = scp->mx.waiters;
719     cep->lock.pid_last_reader = 0;
720     cep->lock.pid_writer = 0;
721     cep->lock.src_indicator = 0;
722     cep->Length = scp->length.LowPart;
723     cep->DataVersion = scp->dataVersion;
724     cep->callback = afs_data_pointer_to_int32(scp->cbServerp);
725     cep->cbExpires = scp->cbExpires;
726     cep->refCount = scp->refCount;
727     cep->opens = scp->openReads;
728     cep->writers = scp->openWrites;
729     switch (scp->fileType) {
730     case CM_SCACHETYPE_FILE:
731         cep->mvstat = 0;
732         break;
733     case CM_SCACHETYPE_MOUNTPOINT:
734         cep->mvstat = 1;
735         break;
736     case CM_SCACHETYPE_DIRECTORY:
737         if (scp->fid.vnode == 1 && scp->fid.unique == 1)
738             cep->mvstat = 2;
739         else
740             cep->mvstat = 3;
741         break;
742     case CM_SCACHETYPE_SYMLINK:
743         cep->mvstat = 4;
744         break;
745     case CM_SCACHETYPE_DFSLINK:
746         cep->mvstat = 5;
747         break;
748     case CM_SCACHETYPE_INVALID:
749         cep->mvstat = 6;
750         break;
751     }
752     cep->states = 0;
753     if (scp->flags & CM_SCACHEFLAG_STATD)
754         cep->states |= 1;
755     if (scp->flags & CM_SCACHEFLAG_RO || scp->flags & CM_SCACHEFLAG_PURERO)
756         cep->states |= 4;
757     if (scp->fileType == CM_SCACHETYPE_MOUNTPOINT &&
758         scp->mountPointStringp[0])
759         cep->states |= 8;
760     if (scp->flags & CM_SCACHEFLAG_WAITING)
761         cep->states |= 0x40;
762     code = 0;
763
764     /*
765      * Return our results.
766      */
767   fcnDone:
768     lock_ReleaseRead(&cm_scacheLock);
769
770     MUTEX_EXIT(&callp->lock);
771     return (code);
772 }
773
774 /* debug interface */
775 int
776 SRXAFSCB_GetCE64(struct rx_call *callp, long index, AFSDBCacheEntry64 *cep)
777 {
778     int i;
779     cm_scache_t * scp;
780     int code;
781     struct rx_connection *connp;
782     struct rx_peer *peerp;
783     unsigned long host = 0;
784     unsigned short port = 0;
785
786     MUTEX_ENTER(&callp->lock);
787
788     if ((connp = rx_ConnectionOf(callp)) && (peerp = rx_PeerOf(connp))) {
789         host = rx_HostOf(peerp);
790         port = rx_PortOf(peerp);
791     }
792
793     osi_Log2(afsd_logp, "SRXAFSCB_GetCE64 from host 0x%x port %d",
794              ntohl(host), ntohs(port));
795
796     lock_ObtainRead(&cm_scacheLock);
797     for (i = 0; i < cm_data.hashTableSize; i++) {
798         for (scp = cm_data.hashTablep[i]; scp; scp = scp->nextp) {
799             if (index == 0)
800                 goto searchDone;
801             index--;
802         }                       /*Zip through current hash chain */
803     }                           /*Zip through hash chains */
804
805   searchDone:
806     if (scp == NULL) {
807         /*Past EOF */
808         code = 1;
809         goto fcnDone;
810     }
811
812     /*
813      * Copy out the located entry.
814      */
815     memset(cep, 0, sizeof(AFSDBCacheEntry64));
816     cep->addr = afs_data_pointer_to_int32(scp);
817     cep->cell = scp->fid.cell;
818     cep->netFid.Volume = scp->fid.volume;
819     cep->netFid.Vnode = scp->fid.vnode;
820     cep->netFid.Unique = scp->fid.unique;
821     cep->lock.waitStates = 0;
822     cep->lock.exclLocked = scp->mx.flags;
823     cep->lock.readersReading = 0;
824     cep->lock.numWaiting = scp->mx.waiters;
825     cep->lock.pid_last_reader = 0;
826     cep->lock.pid_writer = 0;
827     cep->lock.src_indicator = 0;
828 #if !defined(AFS_64BIT_ENV)
829     cep->Length.high = scp->length.HighPart;
830     cep->Length.low = scp->length.LowPart;
831 #else
832     cep->Length = ((afs_int64)scp->length.HighPart)<<32 | scp->length.LowPart;
833 #endif
834     cep->DataVersion = scp->dataVersion;
835     cep->callback = afs_data_pointer_to_int32(scp->cbServerp);
836     cep->cbExpires = scp->cbExpires;
837     cep->refCount = scp->refCount;
838     cep->opens = scp->openReads;
839     cep->writers = scp->openWrites;
840     switch (scp->fileType) {
841     case CM_SCACHETYPE_FILE:
842         cep->mvstat = 0;
843         break;
844     case CM_SCACHETYPE_MOUNTPOINT:
845         cep->mvstat = 1;
846         break;
847     case CM_SCACHETYPE_DIRECTORY:
848         if (scp->fid.vnode == 1 && scp->fid.unique == 1)
849             cep->mvstat = 2;
850         else
851             cep->mvstat = 3;
852         break;
853     case CM_SCACHETYPE_SYMLINK:
854         cep->mvstat = 4;
855         break;
856     case CM_SCACHETYPE_DFSLINK:
857         cep->mvstat = 5;
858         break;
859     case CM_SCACHETYPE_INVALID:
860         cep->mvstat = 6;
861         break;
862     }
863     cep->states = 0;
864     if (scp->flags & CM_SCACHEFLAG_STATD)
865         cep->states |= 1;
866     if (scp->flags & CM_SCACHEFLAG_RO || scp->flags & CM_SCACHEFLAG_PURERO)
867         cep->states |= 4;
868     if (scp->fileType == CM_SCACHETYPE_MOUNTPOINT &&
869         scp->mountPointStringp[0])
870         cep->states |= 8;
871     if (scp->flags & CM_SCACHEFLAG_WAITING)
872         cep->states |= 0x40;
873     code = 0;
874
875     /*
876      * Return our results.
877      */
878   fcnDone:
879     lock_ReleaseRead(&cm_scacheLock);
880
881     MUTEX_EXIT(&callp->lock);
882     return (code);
883 }
884
885 /* debug interface: not implemented */
886 int
887 SRXAFSCB_XStatsVersion(struct rx_call *callp, long *vp)
888 {
889     struct rx_connection *connp;
890     struct rx_peer *peerp;
891     unsigned long host = 0;
892     unsigned short port = 0;
893
894     MUTEX_ENTER(&callp->lock);
895
896     if ((connp = rx_ConnectionOf(callp)) && (peerp = rx_PeerOf(connp))) {
897         host = rx_HostOf(peerp);
898         port = rx_PortOf(peerp);
899     }
900
901     osi_Log2(afsd_logp, "SRXAFSCB_XStatsVersion from host 0x%x port %d - not implemented",
902              ntohl(host), ntohs(port));
903     *vp = -1;
904
905     MUTEX_EXIT(&callp->lock);
906     return RXGEN_OPCODE;
907 }
908
909 /* debug interface: not implemented */
910 int
911 SRXAFSCB_GetXStats(struct rx_call *callp, long cvn, long coln, long *srvp, long *timep,
912                    AFSCB_CollData *datap)
913 {
914     struct rx_connection *connp;
915     struct rx_peer *peerp;
916     unsigned long host = 0;
917     unsigned short port = 0;
918
919     MUTEX_ENTER(&callp->lock);
920
921     if ((connp = rx_ConnectionOf(callp)) && (peerp = rx_PeerOf(connp))) {
922         host = rx_HostOf(peerp);
923         port = rx_PortOf(peerp);
924     }
925
926     osi_Log2(afsd_logp, "SRXAFSCB_GetXStats from host 0x%x port %d - not implemented",
927              ntohl(host), ntohs(port));
928
929     MUTEX_EXIT(&callp->lock);
930     return RXGEN_OPCODE;
931 }
932
933 int
934 SRXAFSCB_InitCallBackState2(struct rx_call *callp, struct interfaceAddr* addr)
935 {
936     osi_Log0(afsd_logp, "SRXAFSCB_InitCallBackState2 ->");
937
938     return SRXAFSCB_InitCallBackState(callp);
939 }
940
941 /* debug interface */
942 int
943 SRXAFSCB_WhoAreYou(struct rx_call *callp, struct interfaceAddr* addr)
944 {
945     int i;
946     int cm_noIPAddr;         /* number of client network interfaces */
947     int cm_IPAddr[CM_MAXINTERFACE_ADDR];    /* client's IP address in host order */
948     int cm_SubnetMask[CM_MAXINTERFACE_ADDR];/* client's subnet mask in host order*/
949     int cm_NetMtu[CM_MAXINTERFACE_ADDR];    /* client's MTU sizes */
950     int cm_NetFlags[CM_MAXINTERFACE_ADDR];  /* network flags */
951     long code;
952     struct rx_connection *connp;
953     struct rx_peer *peerp;
954     unsigned long host = 0;
955     unsigned short port = 0;
956
957     MUTEX_ENTER(&callp->lock);
958
959     if ((connp = rx_ConnectionOf(callp)) && (peerp = rx_PeerOf(connp))) {
960         host = rx_HostOf(peerp);
961         port = rx_PortOf(peerp);
962     }
963
964     /* get network related info */
965     cm_noIPAddr = CM_MAXINTERFACE_ADDR;
966     code = syscfg_GetIFInfo(&cm_noIPAddr,
967                              cm_IPAddr, cm_SubnetMask,
968                              cm_NetMtu, cm_NetFlags);
969
970     /* return all network interface addresses */
971     osi_Log2(afsd_logp, "SRXAFSCB_WhoAreYou from host 0x%x port %d",
972               ntohl(host),
973               ntohs(port));
974
975     addr->numberOfInterfaces = cm_noIPAddr;
976     addr->uuid = cm_data.Uuid;
977     for ( i=0; i < cm_noIPAddr; i++ ) {
978         addr->addr_in[i] = cm_IPAddr[i];
979         addr->subnetmask[i] = cm_SubnetMask[i];
980         addr->mtu[i] = (rx_mtu == -1 || (rx_mtu != -1 && cm_NetMtu[i] < rx_mtu)) ? 
981             cm_NetMtu[i] : rx_mtu;
982     }
983
984     MUTEX_EXIT(&callp->lock);
985     return 0;
986 }
987
988 int
989 SRXAFSCB_InitCallBackState3(struct rx_call *callp, afsUUID* serverUuid)
990 {
991     char *p = NULL;
992
993     if (UuidToString((UUID *)serverUuid, &p) == RPC_S_OK) {
994         osi_Log1(afsd_logp, "SRXAFSCB_InitCallBackState3 %s ->",p);
995         RpcStringFree(&p);
996     } else
997         osi_Log0(afsd_logp, "SRXAFSCB_InitCallBackState3 - no server Uuid ->");
998
999     return SRXAFSCB_InitCallBackState(callp);
1000 }
1001
1002 /* debug interface */
1003 int
1004 SRXAFSCB_ProbeUuid(struct rx_call *callp, afsUUID* clientUuid)
1005 {
1006     struct rx_connection *connp;
1007     struct rx_peer *peerp;
1008     unsigned long host = 0;
1009     unsigned short port = 0;
1010     char *p,*q;
1011     int code = 0;
1012
1013     MUTEX_ENTER(&callp->lock);
1014
1015     if ((connp = rx_ConnectionOf(callp)) && (peerp = rx_PeerOf(connp))) {
1016         host = rx_HostOf(peerp);
1017         port = rx_PortOf(peerp);
1018     }
1019
1020     if ( !afs_uuid_equal(&cm_data.Uuid, clientUuid) ) {
1021         UuidToString((UUID *)&cm_data.Uuid, &p);
1022         UuidToString((UUID *)clientUuid, &q);
1023         osi_Log4(afsd_logp, "SRXAFSCB_ProbeUuid %s != %s from host 0x%x port %d", 
1024                   osi_LogSaveString(afsd_logp,p), 
1025                   osi_LogSaveString(afsd_logp,q),
1026                   ntohl(host),
1027                   ntohs(port));
1028         RpcStringFree(&p);
1029         RpcStringFree(&q);
1030
1031         code = 1;       /* failure */
1032     } else
1033         osi_Log2(afsd_logp, "SRXAFSCB_ProbeUuid (success) from host 0x%x port %d",
1034                   ntohl(host),
1035                   ntohs(port));
1036
1037     MUTEX_EXIT(&callp->lock);
1038     return code;
1039 }
1040
1041 /* debug interface */
1042 int 
1043 SRXAFSCB_GetCellByNum(struct rx_call *callp, afs_int32 a_cellnum,
1044                       char **a_name, serverList *a_hosts)
1045 {
1046     afs_int32 sn;
1047     cm_cell_t * cellp;
1048     cm_serverRef_t * serverRefp; 
1049     struct rx_connection *connp;
1050     struct rx_peer *peerp;
1051     unsigned long host = 0;
1052     unsigned short port = 0;
1053
1054     MUTEX_ENTER(&callp->lock);
1055
1056     if ((connp = rx_ConnectionOf(callp)) && (peerp = rx_PeerOf(connp))) {
1057         host = rx_HostOf(peerp);
1058         port = rx_PortOf(peerp);
1059     }
1060
1061     osi_Log3(afsd_logp, "SRXAFSCB_GetCellByNum(%d) from host 0x%x port %d",
1062              a_cellnum, ntohl(host), ntohs(port));
1063
1064     a_hosts->serverList_val = 0;
1065     a_hosts->serverList_len = 0;
1066
1067     cellp = cm_FindCellByID(a_cellnum);
1068     if (!cellp) {
1069         *a_name = strdup("");
1070         MUTEX_EXIT(&callp->lock);
1071         return 0;
1072     }
1073
1074     lock_ObtainRead(&cm_serverLock);
1075     *a_name = strdup(cellp->name);
1076
1077     for ( sn = 0, serverRefp = cellp->vlServersp; 
1078           sn < AFSMAXCELLHOSTS && serverRefp;
1079           sn++, serverRefp = serverRefp->next);
1080
1081     a_hosts->serverList_len = sn;
1082     a_hosts->serverList_val = (afs_int32 *)osi_Alloc(sn * sizeof(afs_int32));
1083
1084     for ( sn = 0, serverRefp = cellp->vlServersp; 
1085           sn < AFSMAXCELLHOSTS && serverRefp;
1086           sn++, serverRefp = serverRefp->next)
1087     {
1088         a_hosts->serverList_val[sn] = ntohl(serverRefp->server->addr.sin_addr.s_addr);
1089     }
1090
1091     lock_ReleaseRead(&cm_serverLock);
1092     MUTEX_EXIT(&callp->lock);
1093     return 0;
1094 }
1095
1096 /* debug interface */
1097 int 
1098 SRXAFSCB_TellMeAboutYourself( struct rx_call *callp, 
1099                               struct interfaceAddr *addr,
1100                               Capabilities * capabilities)
1101 {
1102     int i;
1103     afs_int32 *dataBuffP;
1104     afs_int32 dataBytes;
1105     int cm_noIPAddr;         /* number of client network interfaces */
1106     int cm_IPAddr[CM_MAXINTERFACE_ADDR];    /* client's IP address in host order */
1107     int cm_SubnetMask[CM_MAXINTERFACE_ADDR];/* client's subnet mask in host order*/
1108     int cm_NetMtu[CM_MAXINTERFACE_ADDR];    /* client's MTU sizes */
1109     int cm_NetFlags[CM_MAXINTERFACE_ADDR];  /* network flags */
1110     long code;
1111     struct rx_connection *connp;
1112     struct rx_peer *peerp;
1113     unsigned long host = 0;
1114     unsigned short port = 0;
1115
1116     MUTEX_ENTER(&callp->lock);
1117
1118     if ((connp = rx_ConnectionOf(callp)) && (peerp = rx_PeerOf(connp))) {
1119         host = rx_HostOf(peerp);
1120         port = rx_PortOf(peerp);
1121     }
1122
1123     /* get network related info */
1124     cm_noIPAddr = CM_MAXINTERFACE_ADDR;
1125     code = syscfg_GetIFInfo(&cm_noIPAddr,
1126                              cm_IPAddr, cm_SubnetMask,
1127                              cm_NetMtu, cm_NetFlags);
1128
1129     osi_Log2(afsd_logp, "SRXAFSCB_TellMeAboutYourself from host 0x%x port %d",
1130               ntohl(host),
1131               ntohs(port));
1132
1133     /* return all network interface addresses */
1134     addr->numberOfInterfaces = cm_noIPAddr;
1135     addr->uuid = cm_data.Uuid;
1136     for ( i=0; i < cm_noIPAddr; i++ ) {
1137         addr->addr_in[i] = cm_IPAddr[i];
1138         addr->subnetmask[i] = cm_SubnetMask[i];
1139         addr->mtu[i] = (rx_mtu == -1 || (rx_mtu != -1 && cm_NetMtu[i] < rx_mtu)) ? 
1140             cm_NetMtu[i] : rx_mtu;
1141     }
1142
1143     dataBytes = 1 * sizeof(afs_int32);
1144     dataBuffP = (afs_int32 *) osi_Alloc(dataBytes);
1145     dataBuffP[0] = CAPABILITY_ERRORTRANS;
1146     capabilities->Capabilities_len = dataBytes / sizeof(afs_int32);
1147     capabilities->Capabilities_val = dataBuffP;
1148
1149     MUTEX_EXIT(&callp->lock);
1150     return 0;
1151 }
1152
1153 /*------------------------------------------------------------------------
1154  * EXPORTED SRXAFSCB_GetServerPrefs
1155  *
1156  * Description:
1157  *      Routine to list server preferences used by this client.
1158  *
1159  * Arguments:
1160  *      a_call  : Ptr to Rx call on which this request came in.
1161  *      a_index : Input server index
1162  *      a_srvr_addr  : Output server address (0xffffffff on last server)
1163  *      a_srvr_rank  : Output server rank
1164  *
1165  * Returns:
1166  *      0 on success
1167  *
1168  * Environment:
1169  *      Nothing interesting.
1170  *
1171  * Side Effects:
1172  *      As advertised.
1173  *------------------------------------------------------------------------*/
1174
1175 int SRXAFSCB_GetServerPrefs(
1176     struct rx_call *callp,
1177     afs_int32 a_index,
1178     afs_int32 *a_srvr_addr,
1179     afs_int32 *a_srvr_rank)
1180 {
1181     struct rx_connection *connp;
1182     struct rx_peer *peerp;
1183     unsigned long host = 0;
1184     unsigned short port = 0;
1185
1186     MUTEX_ENTER(&callp->lock);
1187
1188     if ((connp = rx_ConnectionOf(callp)) && (peerp = rx_PeerOf(connp))) {
1189         host = rx_HostOf(peerp);
1190         port = rx_PortOf(peerp);
1191     }
1192
1193     osi_Log2(afsd_logp, "SRXAFSCB_GetServerPrefs from host 0x%x port %d - not implemented",
1194               ntohl(host),
1195               ntohs(port));
1196
1197     *a_srvr_addr = 0xffffffff;
1198     *a_srvr_rank = 0xffffffff;
1199
1200     MUTEX_EXIT(&callp->lock);
1201     return 0;
1202 }
1203
1204 /*------------------------------------------------------------------------
1205  * EXPORTED SRXAFSCB_GetCellServDB
1206  *
1207  * Description:
1208  *      Routine to list cells configured for this client
1209  *
1210  * Arguments:
1211  *      a_call  : Ptr to Rx call on which this request came in.
1212  *      a_index : Input cell index
1213  *      a_name  : Output cell name ("" on last cell)
1214  *      a_hosts : Output cell database servers
1215  *
1216  * Returns:
1217  *      0 on success
1218  *
1219  * Environment:
1220  *      Nothing interesting.
1221  *
1222  * Side Effects:
1223  *      As advertised.
1224  *------------------------------------------------------------------------*/
1225
1226 int SRXAFSCB_GetCellServDB(struct rx_call *callp, afs_int32 index, char **a_name, 
1227                            serverList *a_hosts)
1228 {
1229     char *t_name;
1230     struct rx_connection *connp;
1231     struct rx_peer *peerp;
1232     unsigned long host = 0;
1233     unsigned short port = 0;
1234
1235     MUTEX_ENTER(&callp->lock);
1236
1237     if ((connp = rx_ConnectionOf(callp)) && (peerp = rx_PeerOf(connp))) {
1238         host = rx_HostOf(peerp);
1239         port = rx_PortOf(peerp);
1240     }
1241
1242     osi_Log2(afsd_logp, "SRXAFSCB_GetCellServDB from host 0x%x port %d - not implemented",
1243              ntohl(host), ntohs(port));
1244
1245     t_name = (char *)malloc(AFSNAMEMAX);
1246     t_name[0] = '\0';
1247     *a_name = t_name;
1248     a_hosts->serverList_len = 0;
1249
1250     MUTEX_EXIT(&callp->lock);
1251     return 0;
1252 }
1253
1254 /*------------------------------------------------------------------------
1255  * EXPORTED SRXAFSCB_GetLocalCell
1256  *
1257  * Description:
1258  *      Routine to return name of client's local cell
1259  *
1260  * Arguments:
1261  *      a_call  : Ptr to Rx call on which this request came in.
1262  *      a_name  : Output cell name
1263  *
1264  * Returns:
1265  *      0 on success
1266  *
1267  * Environment:
1268  *      Nothing interesting.
1269  *
1270  * Side Effects:
1271  *      As advertised.
1272  *------------------------------------------------------------------------*/
1273
1274 int SRXAFSCB_GetLocalCell(struct rx_call *callp, char **a_name)
1275 {
1276     char *t_name;
1277     struct rx_connection *connp;
1278     struct rx_peer *peerp;
1279     unsigned long host = 0;
1280     unsigned short port = 0;
1281
1282     MUTEX_ENTER(&callp->lock);
1283
1284     if ((connp = rx_ConnectionOf(callp)) && (peerp = rx_PeerOf(connp))) {
1285         host = rx_HostOf(peerp);
1286         port = rx_PortOf(peerp);
1287     }
1288
1289     osi_Log2(afsd_logp, "SRXAFSCB_GetLocalCell from host 0x%x port %d",
1290              ntohl(host), ntohs(port));
1291
1292     if (cm_data.rootCellp) {
1293         t_name = (char *)malloc(strlen(cm_data.rootCellp->name)+1);
1294         strcpy(t_name, cm_data.rootCellp->name);
1295     } else {
1296         t_name = (char *)malloc(1);
1297         t_name[0] = '\0';
1298     }
1299     *a_name = t_name;
1300
1301     MUTEX_EXIT(&callp->lock);
1302     return 0;
1303 }
1304
1305
1306 /*
1307  * afs_MarshallCacheConfig - marshall client cache configuration
1308  *
1309  * PARAMETERS
1310  *
1311  * IN callerVersion - the rpc stat version of the caller.
1312  *
1313  * IN config - client cache configuration.
1314  *
1315  * OUT ptr - buffer where configuration is marshalled.
1316  *
1317  * RETURN CODES
1318  *
1319  * Returns void.
1320  */
1321 static void afs_MarshallCacheConfig(
1322     afs_uint32 callerVersion,
1323     cm_initparams_v1 *config,
1324     afs_uint32 *ptr)
1325 {
1326     /*
1327      * We currently only support version 1.
1328      */
1329     *(ptr++) = config->nChunkFiles;
1330     *(ptr++) = config->nStatCaches;
1331     *(ptr++) = config->nDataCaches;
1332     *(ptr++) = config->nVolumeCaches;
1333     *(ptr++) = config->firstChunkSize;
1334     *(ptr++) = config->otherChunkSize;
1335     *(ptr++) = config->cacheSize;
1336     *(ptr++) = config->setTime;
1337     *(ptr++) = config->memCache;
1338
1339 }
1340  
1341
1342 /*------------------------------------------------------------------------
1343  * EXPORTED SRXAFSCB_GetCacheConfig
1344  *
1345  * Description:
1346  *      Routine to return parameters used to initialize client cache.
1347  *      Client may request any format version. Server may not return
1348  *      format version greater than version requested by client.
1349  *
1350  * Arguments:
1351  *      a_call:        Ptr to Rx call on which this request came in.
1352  *      callerVersion: Data format version desired by the client.
1353  *      serverVersion: Data format version of output data.
1354  *      configCount:   Number bytes allocated for output data.
1355  *      config:        Client cache configuration.
1356  *
1357  * Returns:
1358  *      0 on success
1359  *
1360  * Environment:
1361  *      Nothing interesting.
1362  *
1363  * Side Effects:
1364  *      As advertised.
1365  *------------------------------------------------------------------------*/
1366
1367 int SRXAFSCB_GetCacheConfig(struct rx_call *callp,
1368                             afs_uint32 callerVersion,
1369                             afs_uint32 *serverVersion,
1370                             afs_uint32 *configCount,
1371                             cacheConfig *config)
1372 {
1373     afs_uint32 *t_config;
1374     size_t allocsize;
1375     extern cm_initparams_v1 cm_initParams;
1376     struct rx_connection *connp;
1377     struct rx_peer *peerp;
1378     unsigned long host = 0;
1379     unsigned short port = 0;
1380
1381     MUTEX_ENTER(&callp->lock);
1382
1383     if ((connp = rx_ConnectionOf(callp)) && (peerp = rx_PeerOf(connp))) {
1384         host = rx_HostOf(peerp);
1385         port = rx_PortOf(peerp);
1386     }
1387
1388     osi_Log2(afsd_logp, "SRXAFSCB_GetCacheConfig from host 0x%x port %d - version 1 only",
1389              ntohl(host), ntohs(port));
1390
1391     /*
1392      * Currently only support version 1
1393      */
1394     allocsize = sizeof(cm_initparams_v1);
1395     t_config = (afs_uint32 *)malloc(allocsize);
1396
1397     afs_MarshallCacheConfig(callerVersion, &cm_initParams, t_config);
1398
1399     *serverVersion = AFS_CLIENT_RETRIEVAL_FIRST_EDITION;
1400     *configCount = allocsize;
1401     config->cacheConfig_val = t_config;
1402     config->cacheConfig_len = allocsize/sizeof(afs_uint32);
1403
1404     MUTEX_EXIT(&callp->lock);
1405     return 0;
1406 }
1407
1408 /* called by afsd without any locks to initialize this module */
1409 void cm_InitCallback(void)
1410 {
1411     lock_InitializeRWLock(&cm_callbackLock, "cm_callbackLock");
1412     cm_activeCallbackGrantingCalls = 0;
1413 }
1414
1415 /* called with locked scp; tells us whether we've got a callback.
1416  * Expirations are checked by a background daemon so as to make
1417  * this function as inexpensive as possible
1418  */
1419 int cm_HaveCallback(cm_scache_t *scp)
1420 {
1421 #ifdef AFS_FREELANCE_CLIENT
1422     // yj: we handle callbacks specially for callbacks on the root directory
1423     // Since it's local, we almost always say that we have callback on it
1424     // The only time we send back a 0 is if we're need to initialize or
1425     // reinitialize the fake directory
1426
1427     // There are 2 state variables cm_fakeGettingCallback and cm_fakeDirCallback
1428     // cm_fakeGettingCallback is 1 if we're in the process of initialization and
1429     // hence should return false. it's 0 otherwise
1430     // cm_fakeDirCallback is 0 if we haven't loaded the fake directory, it's 1
1431     // if the fake directory is loaded and this is the first time cm_HaveCallback
1432     // is called since then. We return false in this case to allow cm_GetCallback
1433     // to be called because cm_GetCallback has some initialization work to do.
1434     // If cm_fakeDirCallback is 2, then it means that the fake directory is in
1435     // good shape and we simply return true, provided no change is detected.
1436     int fdc, fgc;
1437
1438     if (cm_freelanceEnabled && 
1439          scp->fid.cell==AFS_FAKE_ROOT_CELL_ID && scp->fid.volume==AFS_FAKE_ROOT_VOL_ID) {
1440         /* if it's something on /afs */
1441         if (!(scp->fid.vnode==0x1 && scp->fid.unique==0x1)) {
1442             /* if it's not root.afs */
1443             return 1;
1444         }
1445
1446         lock_ObtainMutex(&cm_Freelance_Lock);
1447         fdc = cm_fakeDirCallback;
1448         fgc = cm_fakeGettingCallback;
1449         lock_ReleaseMutex(&cm_Freelance_Lock);
1450             
1451         if (fdc==1) {   // first call since init
1452             return 0;
1453         } else if (fdc==2 && !fgc) {    // we're in good shape
1454             if (cm_getLocalMountPointChange()) {        // check for changes
1455                 cm_clearLocalMountPointChange(); // clear the changefile
1456                 lock_ReleaseMutex(&scp->mx);      // this is re-locked in reInitLocalMountPoints
1457                 cm_reInitLocalMountPoints();    // start reinit
1458                 lock_ObtainMutex(&scp->mx);      // now get the lock back 
1459                 return 0;
1460             }
1461             return 1;                   // no change
1462         }
1463         return 0;
1464     }
1465 #endif
1466
1467     if (scp->cbServerp != NULL)
1468         return 1;
1469     else 
1470         return 0;
1471 }
1472
1473 /* need to detect a broken callback that races with our obtaining a callback.
1474  * Need to be able to do this even if we don't know the file ID of the file
1475  * we're breaking the callback on at the time we start the acquisition of the
1476  * callback (as in the case where we are creating a file).
1477  *
1478  * So, we start by writing down the count of the # of callbacks we've received
1479  * so far, and bumping a global counter of the # of callback granting calls
1480  * outstanding (all done under cm_callbackLock).
1481  *
1482  * When we're back from the call, we look at all of the callback revokes with
1483  * counter numbers greater than the one we recorded in our caller's structure,
1484  * and replay those that are higher than when we started the call.
1485  * 
1486  * We free all the structures in the queue when the count of the # of outstanding
1487  * callback-granting calls drops to zero.
1488  *
1489  * We call this function with the scp locked, too, but in its current implementation,
1490  * this knowledge is not used.
1491  */
1492 void cm_StartCallbackGrantingCall(cm_scache_t *scp, cm_callbackRequest_t *cbrp)
1493 {
1494     lock_ObtainWrite(&cm_callbackLock);
1495     cbrp->callbackCount = cm_callbackCount;
1496     cm_activeCallbackGrantingCalls++;
1497     cbrp->startTime = osi_Time();
1498     cbrp->serverp = NULL;
1499     lock_ReleaseWrite(&cm_callbackLock);
1500 }
1501
1502 /* Called at the end of a callback-granting call, to remove the callback
1503  * info from the scache entry, if necessary.
1504  *
1505  * Called with scp locked, so we can discard the callbacks easily with
1506  * this locking hierarchy.
1507  */
1508 void cm_EndCallbackGrantingCall(cm_scache_t *scp, cm_callbackRequest_t *cbrp,
1509                                 AFSCallBack *cbp, long flags)
1510 {
1511     cm_racingRevokes_t *revp;           /* where we are */
1512     cm_racingRevokes_t *nrevp;          /* where we'll be next */
1513     int freeFlag;
1514     cm_server_t * serverp = 0;
1515     int discardScp = 0;
1516
1517     lock_ObtainWrite(&cm_callbackLock);
1518     if (flags & CM_CALLBACK_MAINTAINCOUNT) {
1519         osi_assert(cm_activeCallbackGrantingCalls > 0);
1520     }
1521     else {
1522         osi_assert(cm_activeCallbackGrantingCalls-- > 0);
1523     }
1524     if (cm_activeCallbackGrantingCalls == 0) 
1525         freeFlag = 1;
1526     else 
1527         freeFlag = 0;
1528
1529     /* record the callback; we'll clear it below if we really lose it */
1530     if (cbrp) {
1531         if (scp) {
1532             if (scp->cbServerp != cbrp->serverp) {
1533                 serverp = scp->cbServerp;
1534                 if (!freeFlag)
1535                     cm_GetServer(cbrp->serverp);
1536                 scp->cbServerp = cbrp->serverp;
1537             } else {
1538                 if (freeFlag)
1539                     serverp = cbrp->serverp;
1540             }
1541             scp->cbExpires = cbrp->startTime + cbp->ExpirationTime;
1542         } else {
1543             if (freeFlag)
1544                 serverp = cbrp->serverp;
1545         }
1546         if (freeFlag)
1547             cbrp->serverp = NULL;
1548     }
1549
1550     /* a callback was actually revoked during our granting call, so
1551      * run down the list of revoked fids, looking for ours.
1552      * If activeCallbackGrantingCalls is zero, free the elements, too.
1553      *
1554      * May need to go through entire list just to do the freeing.
1555      */
1556     for (revp = cm_racingRevokesp; revp; revp = nrevp) {
1557         nrevp = (cm_racingRevokes_t *) osi_QNext(&revp->q);
1558         /* if this callback came in later than when we started the
1559          * callback-granting call, and if this fid is the right fid,
1560          * then clear the callback.
1561          */
1562         if (scp && cbrp && cbrp->callbackCount != cm_callbackCount
1563              && revp->callbackCount > cbrp->callbackCount
1564              && (( scp->fid.volume == revp->fid.volume &&
1565                    scp->fid.vnode == revp->fid.vnode &&
1566                    scp->fid.unique == revp->fid.unique)
1567                   ||
1568                   ((revp->flags & CM_RACINGFLAG_CANCELVOL) &&
1569                     scp->fid.volume == revp->fid.volume)
1570                   ||
1571                   (revp->flags & CM_RACINGFLAG_CANCELALL))) {
1572             /* this one matches */
1573             osi_Log4(afsd_logp,
1574                       "Racing revoke scp 0x%x old cbc %d rev cbc %d cur cbc %d",
1575                       scp,
1576                       cbrp->callbackCount, revp->callbackCount,
1577                       cm_callbackCount);
1578             discardScp = 1;
1579         }
1580         if (freeFlag) 
1581             free(revp);
1582     }
1583
1584     /* if we freed the list, zap the pointer to it */
1585     if (freeFlag) 
1586         cm_racingRevokesp = NULL;
1587
1588     lock_ReleaseWrite(&cm_callbackLock);
1589
1590     if ( discardScp ) {
1591         cm_DiscardSCache(scp);
1592         lock_ReleaseMutex(&scp->mx);
1593         cm_CallbackNotifyChange(scp);
1594         lock_ObtainMutex(&scp->mx);
1595     }
1596
1597     if ( serverp ) {
1598         lock_ObtainWrite(&cm_serverLock);
1599         cm_FreeServer(serverp);
1600         lock_ReleaseWrite(&cm_serverLock);
1601     }
1602 }
1603
1604 /* if flags is 1, we want to force the code to make one call, anyway.
1605  * called with locked scp; returns with same.
1606  */
1607 long cm_GetCallback(cm_scache_t *scp, struct cm_user *userp,
1608                     struct cm_req *reqp, long flags)
1609 {
1610     long code;
1611     cm_conn_t *connp;
1612     AFSFetchStatus afsStatus;
1613     AFSVolSync volSync;
1614     AFSCallBack callback;
1615     AFSFid tfid;
1616     cm_callbackRequest_t cbr;
1617     int mustCall;
1618     long sflags;
1619     cm_fid_t sfid;
1620     struct rx_connection * callp;
1621
1622     osi_Log4(afsd_logp, "GetCallback scp 0x%x cell %d vol %d flags %lX", 
1623              scp, scp->fid.cell, scp->fid.volume, flags);
1624
1625 #ifdef AFS_FREELANCE_CLIENT
1626     // The case where a callback is needed on /afs is handled
1627     // specially. We need to fetch the status by calling
1628     // cm_MergeStatus and mark that cm_fakeDirCallback is 2
1629     if (cm_freelanceEnabled) {
1630         if (scp->fid.cell==AFS_FAKE_ROOT_CELL_ID &&
1631              scp->fid.volume==AFS_FAKE_ROOT_VOL_ID &&
1632              scp->fid.unique==0x1 &&
1633              scp->fid.vnode==0x1) {
1634             
1635             // Start by indicating that we're in the process
1636             // of fetching the callback
1637             lock_ObtainMutex(&cm_Freelance_Lock);
1638             osi_Log0(afsd_logp,"cm_getGetCallback fakeGettingCallback=1");
1639             cm_fakeGettingCallback = 1;
1640             lock_ReleaseMutex(&cm_Freelance_Lock);
1641
1642             // Fetch the status info 
1643             cm_MergeStatus(scp, &afsStatus, &volSync, userp, 0);
1644
1645             // Indicate that the callback is not done
1646             lock_ObtainMutex(&cm_Freelance_Lock);
1647             osi_Log0(afsd_logp,"cm_getGetCallback fakeDirCallback=2");
1648             cm_fakeDirCallback = 2;
1649
1650             // Indicate that we're no longer fetching the callback
1651             osi_Log0(afsd_logp,"cm_getGetCallback fakeGettingCallback=0");
1652             cm_fakeGettingCallback = 0;
1653             lock_ReleaseMutex(&cm_Freelance_Lock);
1654
1655             return 0;
1656         }
1657
1658         if (scp->fid.cell==AFS_FAKE_ROOT_CELL_ID && scp->fid.volume==AFS_FAKE_ROOT_VOL_ID) {
1659             osi_Log0(afsd_logp,"cm_getcallback should NEVER EVER get here... ");
1660         }
1661     }
1662 #endif /* AFS_FREELANCE_CLIENT */
1663         
1664     mustCall = (flags & 1);
1665     cm_AFSFidFromFid(&tfid, &scp->fid);
1666     while (1) {
1667         if (!mustCall && cm_HaveCallback(scp)) {
1668             osi_Log3(afsd_logp, "GetCallback Complete scp 0x%x cell %d vol %d", 
1669                       scp, scp->fid.cell, scp->fid.volume);
1670             return 0;
1671         }
1672
1673         /* turn off mustCall, since it has now forced us past the check above */
1674         mustCall = 0;
1675
1676         /* otherwise, we have to make an RPC to get the status */
1677         sflags = CM_SCACHESYNC_FETCHSTATUS | CM_SCACHESYNC_GETCALLBACK;
1678         cm_SyncOp(scp, NULL, NULL, NULL, 0, sflags);
1679         cm_StartCallbackGrantingCall(scp, &cbr);
1680         sfid = scp->fid;
1681         lock_ReleaseMutex(&scp->mx);
1682                 
1683         /* now make the RPC */
1684         osi_Log4(afsd_logp, "CALL FetchStatus scp 0x%x cell %d vol %d uniq %d", 
1685                  (long) scp, scp->fid.cell, scp->fid.volume, scp->fid.unique);
1686         do {
1687             code = cm_Conn(&sfid, userp, reqp, &connp);
1688             if (code) 
1689                 continue;
1690
1691             callp = cm_GetRxConn(connp);
1692             code = RXAFS_FetchStatus(callp, &tfid,
1693                                      &afsStatus, &callback, &volSync);
1694             rx_PutConnection(callp);
1695
1696         } while (cm_Analyze(connp, userp, reqp, &sfid, &volSync, NULL,
1697                             &cbr, code));
1698         code = cm_MapRPCError(code, reqp);
1699         if (code)
1700             osi_Log4(afsd_logp, "CALL FetchStatus FAILURE code 0x%x scp 0x%x cell %d vol %d", 
1701                      code, (long) scp, scp->fid.cell, scp->fid.volume);
1702         else
1703             osi_Log4(afsd_logp, "CALL FetchStatus SUCCESS scp 0x%x cell %d vol %d uniq %d", 
1704                      (long) scp, scp->fid.cell, scp->fid.volume, scp->fid.unique);
1705
1706         lock_ObtainMutex(&scp->mx);
1707         if (code == 0) {
1708             cm_EndCallbackGrantingCall(scp, &cbr, &callback, 0);
1709             cm_MergeStatus(scp, &afsStatus, &volSync, userp, 0);
1710         } else {
1711             cm_EndCallbackGrantingCall(NULL, &cbr, NULL, 0);
1712         }
1713         cm_SyncOpDone(scp, NULL, sflags);
1714
1715         /* now check to see if we got an error */
1716         if (code) {
1717             osi_Log2(afsd_logp, "GetCallback Failed code 0x%x scp 0x%x -->",code, scp);
1718             osi_Log4(afsd_logp, "            cell %d vol %d vn %d uniq %d",
1719                      scp->fid.cell, scp->fid.volume, scp->fid.vnode, scp->fid.unique);
1720             return code;
1721         }
1722     }
1723 }
1724
1725 /* called periodically by cm_daemon to shut down use of expired callbacks */
1726 void cm_CheckCBExpiration(void)
1727 {
1728     int i;
1729     cm_scache_t *scp;
1730     unsigned long now;
1731         
1732     osi_Log0(afsd_logp, "CheckCBExpiration");
1733
1734     now = osi_Time();
1735     lock_ObtainWrite(&cm_scacheLock);
1736     for (i=0; i<cm_data.hashTableSize; i++) {
1737         for (scp = cm_data.hashTablep[i]; scp; scp=scp->nextp) {
1738             cm_HoldSCacheNoLock(scp);
1739             if (scp->cbExpires > 0 && (scp->cbServerp == NULL || now > scp->cbExpires)) {
1740                 lock_ReleaseWrite(&cm_scacheLock);
1741                 osi_Log4(afsd_logp, "Callback Expiration Discarding SCache scp 0x%x vol %u vn %u uniq %u", 
1742                           scp, scp->fid.volume, scp->fid.vnode, scp->fid.unique);
1743                 lock_ObtainMutex(&scp->mx);
1744                 cm_DiscardSCache(scp);
1745                 lock_ReleaseMutex(&scp->mx);
1746                 cm_CallbackNotifyChange(scp);
1747                 lock_ObtainWrite(&cm_scacheLock);
1748             }
1749             cm_ReleaseSCacheNoLock(scp);
1750         }
1751     }
1752     lock_ReleaseWrite(&cm_scacheLock);
1753
1754     osi_Log0(afsd_logp, "CheckCBExpiration Complete");
1755 }
1756